logic65 commited on
Commit
b2f4386
·
verified ·
1 Parent(s): 9ac50e4

data: gen_teacher_v2.py

Browse files
Files changed (1) hide show
  1. gen_teacher_v2.py +284 -0
gen_teacher_v2.py ADDED
@@ -0,0 +1,284 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Teacher complete-answer KD data, v2 (L4 session).
3
+
4
+ v1 -> v2: (1) training prompts DISJOINT from gate_local.py (11/12 gate
5
+ prompts were in the v1 list - train-on-test, caught 20 Aug); (2) length
6
+ diversity so the stop position is conditioned on content, not a length
7
+ prior: short/medium/enum/code families; (3) multi-turn conversations with
8
+ late-turn enumeration asks (the measured failure site); (4) TOPK=32.
9
+
10
+ Every row: {key, family, prompt|convo, seed, input_ids, spans, idx, val}
11
+ spans = [[start,end)] token ranges of assistant answers (trainer masks
12
+ labels to these). Alignment: position p holds teacher top-k for predicting
13
+ token p+1 (trainer t_idx[:,:-1]/labels[:,1:] convention). Multi-turn is
14
+ built by prefix extension with a hard assert: each turn's render must be an
15
+ exact token-prefix extension of the previous; drift -> skip convo, log.
16
+ Keeps only answers ending on EOS 248046.
17
+ """
18
+ import json, os, sys, urllib.request, hashlib
19
+ import numpy as np
20
+
21
+ URL = sys.argv[1] if len(sys.argv) > 1 else "http://127.0.0.1:8240"
22
+ OUT_DIR = "/content/drive/MyDrive/whittle/teacher32"
23
+ os.makedirs(OUT_DIR, exist_ok=True)
24
+ JSONL = os.path.join(OUT_DIR, "teacher_complete.jsonl")
25
+ NPZ = os.path.join(OUT_DIR, "teacher_complete.npz")
26
+ SKIPF = os.path.join(OUT_DIR, "teacher_skips.txt")
27
+ IM_END = 248046
28
+ TOPK = 32
29
+ SEEDS = (1, 2)
30
+
31
+ # ENUM: 17 v1 prompts NOT in gate_local P1, plus 8 new. NEVER add gate prompts.
32
+ ENUM = [
33
+ "Give me 25 ideas for a blog, numbered, one line each.",
34
+ "List 20 kinds of software engineers and what they do.",
35
+ "List 25 things to check before deploying to production.",
36
+ "Give me 20 categories of scientific research, one per line.",
37
+ "List 30 common programming tasks, numbered.",
38
+ "Describe everything a modern operating system kernel is responsible for.",
39
+ "What are the major periods of world history and what defined them?",
40
+ "What are the different kinds of machine learning, with examples of each?",
41
+ "List 15 programming languages and what each is best at.",
42
+ "List 12 common Linux commands with a one line description.",
43
+ "List 20 animals and their habitats.",
44
+ "List 15 famous scientists and their discoveries.",
45
+ "Name 25 European capital cities, one per line.",
46
+ "List 20 healthy meals and their main ingredient.",
47
+ "Give me 25 tips for writing clearly, numbered.",
48
+ "List 18 world rivers and the continent of each.",
49
+ "Enumerate 30 topics you know about, one per line.",
50
+ "List 22 board games and how many players each needs.",
51
+ "Name 20 musical instruments and their families.",
52
+ "List 25 common kitchen tools and what each is for.",
53
+ "Give me 20 study tips for exams, numbered.",
54
+ "List 15 famous mountains and the range each belongs to.",
55
+ "Name 18 chemical elements and one everyday use of each.",
56
+ "Give me 24 productivity tips, numbered.",
57
+ "List 20 categories of mobile apps with an example of each.",
58
+ ]
59
+ SHORT = [
60
+ "What is the capital of Japan?",
61
+ "How many legs does a spider have?",
62
+ "What does HTTP stand for?",
63
+ "Is Python compiled or interpreted? Answer in one short paragraph.",
64
+ "What year did the Berlin Wall fall?",
65
+ "What is the boiling point of water at sea level?",
66
+ "Define photosynthesis in two sentences.",
67
+ "What is 15% of 240?",
68
+ "Name the largest ocean on Earth.",
69
+ "What does CPU stand for and what does it do, briefly?",
70
+ "Give a one-sentence definition of recursion.",
71
+ "What language is spoken in Brazil?",
72
+ "Briefly, what is inflation?",
73
+ "What is the difference between RAM and storage, in a few sentences?",
74
+ ]
75
+ SHORT = [p + " Answer in one or two sentences." for p in SHORT]
76
+ MEDIUM = [
77
+ "Explain how a refrigerator works.",
78
+ "Why is the sky blue?",
79
+ "Explain what DNS does when you type a URL into a browser.",
80
+ "How does compound interest work? Include a small example.",
81
+ "Explain the water cycle.",
82
+ "What causes the seasons?",
83
+ "How do vaccines work?",
84
+ "Explain how git branching works, conceptually.",
85
+ ]
86
+ CODE = [
87
+ "Write a Python function that checks if a string is a palindrome.",
88
+ "Write a bash one-liner to find the 10 largest files under a directory, and explain it.",
89
+ "Show a minimal Flask hello-world app.",
90
+ "Write a Python snippet that reads a CSV file and prints the mean of each numeric column.",
91
+ "Write a JavaScript function that debounces another function.",
92
+ ]
93
+ CONVOS = [ # fresh topics, disjoint from gate convos; late-turn enum ask in each
94
+ ["I want to learn to cook. Where do I start?",
95
+ "What equipment do I actually need?",
96
+ "Teach me one simple technique to practice first.",
97
+ "What should my first three dishes be?",
98
+ "How do I plan a week of meals without waste?",
99
+ "List 15 pantry staples I should always have, one per line."],
100
+ ["I'm planning a two week trip to Portugal. What should I know?",
101
+ "Which cities are worth the time?",
102
+ "How do I get between them cheaply?",
103
+ "What food should I try?",
104
+ "Any safety or etiquette tips?",
105
+ "Now give me a numbered 14 day itinerary, one line per day."],
106
+ ["My laptop has gotten really slow. What could cause that?",
107
+ "How do I check what's eating the memory?",
108
+ "Should I upgrade the RAM or the disk first?",
109
+ "Is reinstalling the OS worth it?",
110
+ "How do I back everything up safely before I try?",
111
+ "Summarise the whole plan as a numbered checklist of 12 steps."],
112
+ ["I want to start a small vegetable garden. What do I need?",
113
+ "What vegetables are easiest for a beginner?",
114
+ "How often should I water them?",
115
+ "What about pests, without harsh chemicals?",
116
+ "When do I harvest?",
117
+ "List 20 tasks for my first season, in order."],
118
+ ["Help me make a monthly budget. Where do I begin?",
119
+ "What categories do people usually forget?",
120
+ "How much should go to savings?",
121
+ "What's the best way to track spending without an app?",
122
+ "How do I handle irregular income?",
123
+ "Recap everything as a numbered action list of 15 items."],
124
+ ["I want to learn guitar as an adult. Is it too late?",
125
+ "Acoustic or electric to start?",
126
+ "How long should I practice each day?",
127
+ "What should I practice in the first month?",
128
+ "How do I stop my fingers hurting?",
129
+ "Give me a 30 day practice plan, one line per day."],
130
+ ["Explain what an API is like I'm new to programming.",
131
+ "What's the difference between REST and a database?",
132
+ "How does authentication usually work?",
133
+ "What is rate limiting for?",
134
+ "What happens when an API changes and breaks things?",
135
+ "List 18 terms I should know from this conversation, each with a one line definition."],
136
+ ["I need to present to executives next week and I'm nervous. Help?",
137
+ "How do I structure the talk?",
138
+ "How many slides is too many?",
139
+ "What if they ask something I can't answer?",
140
+ "How do I handle the nerves in the moment?",
141
+ "Summarise your advice as 12 numbered rules."],
142
+ ]
143
+ NPRED = {"enum": 1200, "short": 200, "medium": 900, "code": 900, "convo": 2200}
144
+
145
+
146
+ def post(path, body, timeout=1800):
147
+ req = urllib.request.Request(URL + path, data=json.dumps(body).encode(),
148
+ headers={"Content-Type": "application/json"})
149
+ return json.load(urllib.request.urlopen(req, timeout=timeout))
150
+
151
+
152
+ def render(messages):
153
+ return post("/apply-template", {"messages": messages,
154
+ "chat_template_kwargs": {"enable_thinking": False}})["prompt"]
155
+
156
+
157
+ def tokenize(text):
158
+ return post("/tokenize", {"content": text, "add_special": False})["tokens"]
159
+
160
+
161
+ def complete(rendered, n_predict, seed):
162
+ r = post("/completion", {
163
+ "prompt": rendered, "n_predict": n_predict, "seed": seed,
164
+ "temperature": 0.6, "top_p": 0.9, "top_k": 40,
165
+ "n_probs": TOPK, "cache_prompt": True})
166
+ cp = r.get("completion_probabilities", [])
167
+ return [e["id"] for e in cp], cp, r.get("content", "")
168
+
169
+
170
+ def load_done():
171
+ done = set()
172
+ if os.path.exists(SKIPF):
173
+ done |= {l.strip() for l in open(SKIPF) if l.strip()}
174
+ rows = [json.loads(l) for l in open(JSONL)] if os.path.exists(JSONL) else []
175
+ return done | {r["key"] for r in rows}, rows
176
+
177
+
178
+ def mark_skip(key, why):
179
+ print(f"SKIP {key} ({why})", flush=True)
180
+ with open(SKIPF, "a") as f:
181
+ f.write(key + "\n")
182
+
183
+
184
+ def place_probs(cp, plen, idx, val, n):
185
+ """teacher top-k for generated step j -> cache position plen+j-1"""
186
+ for j, e in enumerate(cp):
187
+ tl = e.get("top_logprobs") or []
188
+ ids = [c["id"] for c in tl][:TOPK]
189
+ lps = [c["logprob"] for c in tl][:TOPK]
190
+ if e["id"] not in ids:
191
+ ids[-1], lps[-1] = e["id"], e["logprob"]
192
+ while len(ids) < TOPK:
193
+ ids.append(ids[-1]); lps.append(-1e4)
194
+ pos = plen + j - 1
195
+ if pos < 0 or pos >= n:
196
+ return False
197
+ idx[pos], val[pos] = ids, lps
198
+ return True
199
+
200
+
201
+ def bank(row, rows, done):
202
+ rows.append(row); done.add(row["key"])
203
+ with open(JSONL, "a") as f:
204
+ f.write(json.dumps(row) + "\n")
205
+ if len(rows) % 5 == 0:
206
+ save_npz(rows)
207
+
208
+
209
+ def save_npz(rows):
210
+ np.savez(NPZ, topk=np.array([TOPK]),
211
+ row_ids=np.arange(len(rows), dtype=np.int64),
212
+ lengths=np.array([len(r["input_ids"]) for r in rows], dtype=np.int64),
213
+ idx=np.concatenate([np.array(r["idx"], dtype=np.int32) for r in rows]),
214
+ val=np.concatenate([np.array(r["val"], dtype=np.float16) for r in rows]))
215
+
216
+
217
+ done, rows = load_done()
218
+ print(f"resuming with {len(done)} keys done, {len(rows)} rows banked", flush=True)
219
+
220
+ SINGLES = ([("enum", p) for p in ENUM] + [("short", p) for p in SHORT] +
221
+ [("medium", p) for p in MEDIUM] + [("code", p) for p in CODE])
222
+
223
+ EXTRAF = os.path.join(OUT_DIR, "extra_prompts.json")
224
+ EXTRA = json.load(open(EXTRAF)) if os.path.exists(EXTRAF) else []
225
+ NPRED["extra"] = 4096
226
+
227
+ for seed in SEEDS:
228
+ singles = SINGLES + ([("extra", p) for p in EXTRA] if seed == 1 else [])
229
+ for fam, prompt in singles:
230
+ key = f"{hashlib.md5(prompt.encode()).hexdigest()[:8]}-{seed}"
231
+ if key in done:
232
+ continue
233
+ rendered = render([{"role": "user", "content": prompt}])
234
+ p_ids = tokenize(rendered)
235
+ gen_ids, cp, _ = complete(rendered, NPRED[fam], seed)
236
+ if not gen_ids or gen_ids[-1] != IM_END:
237
+ mark_skip(key, f"no EOS len={len(gen_ids)}"); done.add(key); continue
238
+ full = p_ids + gen_ids
239
+ n = len(full)
240
+ idx = [[0] * TOPK for _ in range(n)]
241
+ val = [[-1e4] * TOPK for _ in range(n)]
242
+ if not place_probs(cp, len(p_ids), idx, val, n):
243
+ mark_skip(key, "pos-out-of-range"); done.add(key); continue
244
+ bank({"key": key, "family": fam, "prompt": prompt, "seed": seed,
245
+ "input_ids": full, "spans": [[len(p_ids), n]],
246
+ "idx": idx, "val": val}, rows, done)
247
+ print(f"OK {len(rows):3d} | {fam:6s} s{seed} {prompt[:50]:50s} gen={len(gen_ids)}", flush=True)
248
+
249
+ for ci, turns in enumerate(CONVOS):
250
+ msgs = []
251
+ for ti, u in enumerate(turns):
252
+ msgs.append({"role": "user", "content": u})
253
+ key = f"convo{ci}t{ti}-{seed}"
254
+ if key in done:
255
+ prev = next((r for r in rows if r.get("key") == key), None)
256
+ if prev is None:
257
+ break # this turn was skipped; later turns lack history
258
+ msgs.append({"role": "assistant", "content": prev["content_text"]})
259
+ continue
260
+ rendered = render(msgs)
261
+ ids = tokenize(rendered)
262
+ n_pred = min(NPRED["convo"], 12288 - len(ids) - 64)
263
+ if n_pred < 600:
264
+ mark_skip(key, f"ctx budget ids={len(ids)}"); done.add(key); break
265
+ gen_ids, cp, content = complete(rendered, n_pred, seed)
266
+ if not gen_ids or gen_ids[-1] != IM_END:
267
+ mark_skip(key, f"turn no EOS len={len(gen_ids)}")
268
+ done.add(key)
269
+ break
270
+ full = ids + gen_ids
271
+ n = len(full)
272
+ idx = [[0] * TOPK for _ in range(n)]
273
+ val = [[-1e4] * TOPK for _ in range(n)]
274
+ if not place_probs(cp, len(ids), idx, val, n):
275
+ mark_skip(key, "pos-out-of-range"); done.add(key); break
276
+ text = content.replace("<|im_end|>", "").rstrip()
277
+ bank({"key": key, "family": "convo", "convo": ci, "turn": ti,
278
+ "seed": seed, "content_text": text, "input_ids": full,
279
+ "spans": [[len(ids), n]], "idx": idx, "val": val}, rows, done)
280
+ print(f"OK {len(rows):3d} | convo{ci}t{ti} s{seed} gen={len(gen_ids):4d} ctx={len(ids)}", flush=True)
281
+ msgs.append({"role": "assistant", "content": text})
282
+
283
+ save_npz(rows)
284
+ print(f"DONE: {len(rows)} rows -> {NPZ}", flush=True)