Datasets:
Download gen_teacher_v2.py from logic65/whittle-teacher32-complete-answers: direct link, hf CLI and curl.
- Browser
- Download file 12.8 kB
-
https://huggingface.co/datasets/logic65/whittle-teacher32-complete-answers/resolve/main/gen_teacher_v2.py
- Command line
-
hf download hf://datasets/logic65/whittle-teacher32-complete-answers/gen_teacher_v2.py
-
curl -L -o gen_teacher_v2.py https://huggingface.co/datasets/logic65/whittle-teacher32-complete-answers/resolve/main/gen_teacher_v2.py
12.8 kB
| #!/usr/bin/env python3 | |
| """Teacher complete-answer KD data, v2 (L4 session). | |
| v1 -> v2: (1) training prompts DISJOINT from gate_local.py (11/12 gate | |
| prompts were in the v1 list - train-on-test, caught 20 Aug); (2) length | |
| diversity so the stop position is conditioned on content, not a length | |
| prior: short/medium/enum/code families; (3) multi-turn conversations with | |
| late-turn enumeration asks (the measured failure site); (4) TOPK=32. | |
| Every row: {key, family, prompt|convo, seed, input_ids, spans, idx, val} | |
| spans = [[start,end)] token ranges of assistant answers (trainer masks | |
| labels to these). Alignment: position p holds teacher top-k for predicting | |
| token p+1 (trainer t_idx[:,:-1]/labels[:,1:] convention). Multi-turn is | |
| built by prefix extension with a hard assert: each turn's render must be an | |
| exact token-prefix extension of the previous; drift -> skip convo, log. | |
| Keeps only answers ending on EOS 248046. | |
| """ | |
| import json, os, sys, urllib.request, hashlib | |
| import numpy as np | |
| URL = sys.argv[1] if len(sys.argv) > 1 else "http://127.0.0.1:8240" | |
| OUT_DIR = "/content/drive/MyDrive/whittle/teacher32" | |
| os.makedirs(OUT_DIR, exist_ok=True) | |
| JSONL = os.path.join(OUT_DIR, "teacher_complete.jsonl") | |
| NPZ = os.path.join(OUT_DIR, "teacher_complete.npz") | |
| SKIPF = os.path.join(OUT_DIR, "teacher_skips.txt") | |
| IM_END = 248046 | |
| TOPK = 32 | |
| SEEDS = (1, 2) | |
| # ENUM: 17 v1 prompts NOT in gate_local P1, plus 8 new. NEVER add gate prompts. | |
| ENUM = [ | |
| "Give me 25 ideas for a blog, numbered, one line each.", | |
| "List 20 kinds of software engineers and what they do.", | |
| "List 25 things to check before deploying to production.", | |
| "Give me 20 categories of scientific research, one per line.", | |
| "List 30 common programming tasks, numbered.", | |
| "Describe everything a modern operating system kernel is responsible for.", | |
| "What are the major periods of world history and what defined them?", | |
| "What are the different kinds of machine learning, with examples of each?", | |
| "List 15 programming languages and what each is best at.", | |
| "List 12 common Linux commands with a one line description.", | |
| "List 20 animals and their habitats.", | |
| "List 15 famous scientists and their discoveries.", | |
| "Name 25 European capital cities, one per line.", | |
| "List 20 healthy meals and their main ingredient.", | |
| "Give me 25 tips for writing clearly, numbered.", | |
| "List 18 world rivers and the continent of each.", | |
| "Enumerate 30 topics you know about, one per line.", | |
| "List 22 board games and how many players each needs.", | |
| "Name 20 musical instruments and their families.", | |
| "List 25 common kitchen tools and what each is for.", | |
| "Give me 20 study tips for exams, numbered.", | |
| "List 15 famous mountains and the range each belongs to.", | |
| "Name 18 chemical elements and one everyday use of each.", | |
| "Give me 24 productivity tips, numbered.", | |
| "List 20 categories of mobile apps with an example of each.", | |
| ] | |
| SHORT = [ | |
| "What is the capital of Japan?", | |
| "How many legs does a spider have?", | |
| "What does HTTP stand for?", | |
| "Is Python compiled or interpreted? Answer in one short paragraph.", | |
| "What year did the Berlin Wall fall?", | |
| "What is the boiling point of water at sea level?", | |
| "Define photosynthesis in two sentences.", | |
| "What is 15% of 240?", | |
| "Name the largest ocean on Earth.", | |
| "What does CPU stand for and what does it do, briefly?", | |
| "Give a one-sentence definition of recursion.", | |
| "What language is spoken in Brazil?", | |
| "Briefly, what is inflation?", | |
| "What is the difference between RAM and storage, in a few sentences?", | |
| ] | |
| SHORT = [p + " Answer in one or two sentences." for p in SHORT] | |
| MEDIUM = [ | |
| "Explain how a refrigerator works.", | |
| "Why is the sky blue?", | |
| "Explain what DNS does when you type a URL into a browser.", | |
| "How does compound interest work? Include a small example.", | |
| "Explain the water cycle.", | |
| "What causes the seasons?", | |
| "How do vaccines work?", | |
| "Explain how git branching works, conceptually.", | |
| ] | |
| CODE = [ | |
| "Write a Python function that checks if a string is a palindrome.", | |
| "Write a bash one-liner to find the 10 largest files under a directory, and explain it.", | |
| "Show a minimal Flask hello-world app.", | |
| "Write a Python snippet that reads a CSV file and prints the mean of each numeric column.", | |
| "Write a JavaScript function that debounces another function.", | |
| ] | |
| CONVOS = [ # fresh topics, disjoint from gate convos; late-turn enum ask in each | |
| ["I want to learn to cook. Where do I start?", | |
| "What equipment do I actually need?", | |
| "Teach me one simple technique to practice first.", | |
| "What should my first three dishes be?", | |
| "How do I plan a week of meals without waste?", | |
| "List 15 pantry staples I should always have, one per line."], | |
| ["I'm planning a two week trip to Portugal. What should I know?", | |
| "Which cities are worth the time?", | |
| "How do I get between them cheaply?", | |
| "What food should I try?", | |
| "Any safety or etiquette tips?", | |
| "Now give me a numbered 14 day itinerary, one line per day."], | |
| ["My laptop has gotten really slow. What could cause that?", | |
| "How do I check what's eating the memory?", | |
| "Should I upgrade the RAM or the disk first?", | |
| "Is reinstalling the OS worth it?", | |
| "How do I back everything up safely before I try?", | |
| "Summarise the whole plan as a numbered checklist of 12 steps."], | |
| ["I want to start a small vegetable garden. What do I need?", | |
| "What vegetables are easiest for a beginner?", | |
| "How often should I water them?", | |
| "What about pests, without harsh chemicals?", | |
| "When do I harvest?", | |
| "List 20 tasks for my first season, in order."], | |
| ["Help me make a monthly budget. Where do I begin?", | |
| "What categories do people usually forget?", | |
| "How much should go to savings?", | |
| "What's the best way to track spending without an app?", | |
| "How do I handle irregular income?", | |
| "Recap everything as a numbered action list of 15 items."], | |
| ["I want to learn guitar as an adult. Is it too late?", | |
| "Acoustic or electric to start?", | |
| "How long should I practice each day?", | |
| "What should I practice in the first month?", | |
| "How do I stop my fingers hurting?", | |
| "Give me a 30 day practice plan, one line per day."], | |
| ["Explain what an API is like I'm new to programming.", | |
| "What's the difference between REST and a database?", | |
| "How does authentication usually work?", | |
| "What is rate limiting for?", | |
| "What happens when an API changes and breaks things?", | |
| "List 18 terms I should know from this conversation, each with a one line definition."], | |
| ["I need to present to executives next week and I'm nervous. Help?", | |
| "How do I structure the talk?", | |
| "How many slides is too many?", | |
| "What if they ask something I can't answer?", | |
| "How do I handle the nerves in the moment?", | |
| "Summarise your advice as 12 numbered rules."], | |
| ] | |
| NPRED = {"enum": 1200, "short": 200, "medium": 900, "code": 900, "convo": 2200} | |
| def post(path, body, timeout=1800): | |
| req = urllib.request.Request(URL + path, data=json.dumps(body).encode(), | |
| headers={"Content-Type": "application/json"}) | |
| return json.load(urllib.request.urlopen(req, timeout=timeout)) | |
| def render(messages): | |
| return post("/apply-template", {"messages": messages, | |
| "chat_template_kwargs": {"enable_thinking": False}})["prompt"] | |
| def tokenize(text): | |
| return post("/tokenize", {"content": text, "add_special": False})["tokens"] | |
| def complete(rendered, n_predict, seed): | |
| r = post("/completion", { | |
| "prompt": rendered, "n_predict": n_predict, "seed": seed, | |
| "temperature": 0.6, "top_p": 0.9, "top_k": 40, | |
| "n_probs": TOPK, "cache_prompt": True}) | |
| cp = r.get("completion_probabilities", []) | |
| return [e["id"] for e in cp], cp, r.get("content", "") | |
| def load_done(): | |
| done = set() | |
| if os.path.exists(SKIPF): | |
| done |= {l.strip() for l in open(SKIPF) if l.strip()} | |
| rows = [json.loads(l) for l in open(JSONL)] if os.path.exists(JSONL) else [] | |
| return done | {r["key"] for r in rows}, rows | |
| def mark_skip(key, why): | |
| print(f"SKIP {key} ({why})", flush=True) | |
| with open(SKIPF, "a") as f: | |
| f.write(key + "\n") | |
| def place_probs(cp, plen, idx, val, n): | |
| """teacher top-k for generated step j -> cache position plen+j-1""" | |
| for j, e in enumerate(cp): | |
| tl = e.get("top_logprobs") or [] | |
| ids = [c["id"] for c in tl][:TOPK] | |
| lps = [c["logprob"] for c in tl][:TOPK] | |
| if e["id"] not in ids: | |
| ids[-1], lps[-1] = e["id"], e["logprob"] | |
| while len(ids) < TOPK: | |
| ids.append(ids[-1]); lps.append(-1e4) | |
| pos = plen + j - 1 | |
| if pos < 0 or pos >= n: | |
| return False | |
| idx[pos], val[pos] = ids, lps | |
| return True | |
| def bank(row, rows, done): | |
| rows.append(row); done.add(row["key"]) | |
| with open(JSONL, "a") as f: | |
| f.write(json.dumps(row) + "\n") | |
| if len(rows) % 5 == 0: | |
| save_npz(rows) | |
| def save_npz(rows): | |
| np.savez(NPZ, topk=np.array([TOPK]), | |
| row_ids=np.arange(len(rows), dtype=np.int64), | |
| lengths=np.array([len(r["input_ids"]) for r in rows], dtype=np.int64), | |
| idx=np.concatenate([np.array(r["idx"], dtype=np.int32) for r in rows]), | |
| val=np.concatenate([np.array(r["val"], dtype=np.float16) for r in rows])) | |
| done, rows = load_done() | |
| print(f"resuming with {len(done)} keys done, {len(rows)} rows banked", flush=True) | |
| SINGLES = ([("enum", p) for p in ENUM] + [("short", p) for p in SHORT] + | |
| [("medium", p) for p in MEDIUM] + [("code", p) for p in CODE]) | |
| EXTRAF = os.path.join(OUT_DIR, "extra_prompts.json") | |
| EXTRA = json.load(open(EXTRAF)) if os.path.exists(EXTRAF) else [] | |
| NPRED["extra"] = 4096 | |
| for seed in SEEDS: | |
| singles = SINGLES + ([("extra", p) for p in EXTRA] if seed == 1 else []) | |
| for fam, prompt in singles: | |
| key = f"{hashlib.md5(prompt.encode()).hexdigest()[:8]}-{seed}" | |
| if key in done: | |
| continue | |
| rendered = render([{"role": "user", "content": prompt}]) | |
| p_ids = tokenize(rendered) | |
| gen_ids, cp, _ = complete(rendered, NPRED[fam], seed) | |
| if not gen_ids or gen_ids[-1] != IM_END: | |
| mark_skip(key, f"no EOS len={len(gen_ids)}"); done.add(key); continue | |
| full = p_ids + gen_ids | |
| n = len(full) | |
| idx = [[0] * TOPK for _ in range(n)] | |
| val = [[-1e4] * TOPK for _ in range(n)] | |
| if not place_probs(cp, len(p_ids), idx, val, n): | |
| mark_skip(key, "pos-out-of-range"); done.add(key); continue | |
| bank({"key": key, "family": fam, "prompt": prompt, "seed": seed, | |
| "input_ids": full, "spans": [[len(p_ids), n]], | |
| "idx": idx, "val": val}, rows, done) | |
| print(f"OK {len(rows):3d} | {fam:6s} s{seed} {prompt[:50]:50s} gen={len(gen_ids)}", flush=True) | |
| for ci, turns in enumerate(CONVOS): | |
| msgs = [] | |
| for ti, u in enumerate(turns): | |
| msgs.append({"role": "user", "content": u}) | |
| key = f"convo{ci}t{ti}-{seed}" | |
| if key in done: | |
| prev = next((r for r in rows if r.get("key") == key), None) | |
| if prev is None: | |
| break # this turn was skipped; later turns lack history | |
| msgs.append({"role": "assistant", "content": prev["content_text"]}) | |
| continue | |
| rendered = render(msgs) | |
| ids = tokenize(rendered) | |
| n_pred = min(NPRED["convo"], 12288 - len(ids) - 64) | |
| if n_pred < 600: | |
| mark_skip(key, f"ctx budget ids={len(ids)}"); done.add(key); break | |
| gen_ids, cp, content = complete(rendered, n_pred, seed) | |
| if not gen_ids or gen_ids[-1] != IM_END: | |
| mark_skip(key, f"turn no EOS len={len(gen_ids)}") | |
| done.add(key) | |
| break | |
| full = ids + gen_ids | |
| n = len(full) | |
| idx = [[0] * TOPK for _ in range(n)] | |
| val = [[-1e4] * TOPK for _ in range(n)] | |
| if not place_probs(cp, len(ids), idx, val, n): | |
| mark_skip(key, "pos-out-of-range"); done.add(key); break | |
| text = content.replace("<|im_end|>", "").rstrip() | |
| bank({"key": key, "family": "convo", "convo": ci, "turn": ti, | |
| "seed": seed, "content_text": text, "input_ids": full, | |
| "spans": [[len(ids), n]], "idx": idx, "val": val}, rows, done) | |
| print(f"OK {len(rows):3d} | convo{ci}t{ti} s{seed} gen={len(gen_ids):4d} ctx={len(ids)}", flush=True) | |
| msgs.append({"role": "assistant", "content": text}) | |
| save_npz(rows) | |
| print(f"DONE: {len(rows)} rows -> {NPZ}", flush=True) | |