ModhiSathvik commited on
Commit
53d7d76
·
verified ·
1 Parent(s): b7a475a

Add generators/generate_worked_example.py

Browse files
Files changed (1) hide show
  1. generators/generate_worked_example.py +230 -0
generators/generate_worked_example.py ADDED
@@ -0,0 +1,230 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """WORKED EXAMPLE format generator (multi-subject).
2
+
3
+ Shape:
4
+ Problem -> Reasoning -> Solution -> Walkthrough -> Tests
5
+
6
+ Usage (from /workspace/pluto_run/):
7
+ python generators/generate_worked_example.py --subject python --limit 50
8
+ python generators/generate_worked_example.py --subject python
9
+ """
10
+
11
+ import argparse
12
+ import asyncio
13
+ import hashlib
14
+ import json
15
+ import os
16
+ import random
17
+ import time
18
+ from openai import AsyncOpenAI
19
+ from tqdm import tqdm
20
+
21
+
22
+ client = AsyncOpenAI(base_url="http://localhost:8000/v1", api_key="dummy")
23
+ MODEL = "qwen-coder"
24
+ SEED = 42
25
+ FORMAT = "worked_example"
26
+
27
+
28
+ def build_system_prompt(subject):
29
+ subject_name = subject.capitalize() if subject != "cpp" else "C++"
30
+ return (
31
+ f"You are a senior {subject_name} developer creating a worked example for a "
32
+ f"training corpus. Walk the reader through solving a concrete problem from "
33
+ f"start to finish. Structure your output as: "
34
+ f"(1) Problem - one or two sentences stating the concrete task. "
35
+ f"(2) Reasoning - a short paragraph explaining the approach. "
36
+ f"(3) Solution - a single ```{subject}``` block with self-contained, "
37
+ f"runnable code (imports included). "
38
+ f"(4) Walkthrough - a paragraph explaining what each section does. "
39
+ f"(5) Tests - 2-3 simple assertions or example calls demonstrating it works. "
40
+ f"Length: 400-700 words. Write the example once and stop after the tests."
41
+ )
42
+
43
+
44
+ PERSONAS = [
45
+ "a senior backend engineer",
46
+ "a CS professor with a knack for clear examples",
47
+ "a tech blogger known for practical, idiomatic code",
48
+ "a code reviewer who emphasizes correctness and edge cases",
49
+ "an experienced developer mentoring a junior",
50
+ "a library maintainer documenting their own work",
51
+ "a staff engineer writing internal docs",
52
+ "a workshop instructor teaching hands-on coding",
53
+ ]
54
+
55
+ AUDIENCES = [
56
+ "an intermediate developer",
57
+ "a junior developer with 6 months of experience",
58
+ "an experienced engineer new to this language",
59
+ "a senior engineer reviewing their understanding",
60
+ "a self-taught programmer building production systems",
61
+ ]
62
+
63
+
64
+ def topic_hash(topic):
65
+ return hashlib.sha256(topic.encode("utf-8")).hexdigest()[:16]
66
+
67
+
68
+ def load_done_topics(output_file):
69
+ done = set()
70
+ if os.path.exists(output_file):
71
+ with open(output_file) as f:
72
+ for line in f:
73
+ try:
74
+ rec = json.loads(line)
75
+ if "topic" in rec:
76
+ done.add(topic_hash(rec["topic"]))
77
+ except Exception:
78
+ pass
79
+ return done
80
+
81
+
82
+ async def generate_one(topic, persona, audience, system_prompt, subject, sem):
83
+ async with sem:
84
+ prompt = (
85
+ f"Persona: {persona}\n"
86
+ f"Audience: {audience}\n\n"
87
+ f"Write a worked example for this {subject} topic: {topic}"
88
+ )
89
+ try:
90
+ response = await client.chat.completions.create(
91
+ model=MODEL,
92
+ messages=[
93
+ {"role": "system", "content": system_prompt},
94
+ {"role": "user", "content": prompt},
95
+ ],
96
+ temperature=0.8,
97
+ top_p=0.95,
98
+ max_tokens=1500,
99
+ )
100
+ content = response.choices[0].message.content
101
+ if not content or len(content) < 100:
102
+ return {"_status": "too_short", "topic": topic}
103
+ return {
104
+ "_status": "ok",
105
+ "format": FORMAT,
106
+ "subject": subject,
107
+ "topic": topic,
108
+ "topic_hash": topic_hash(topic),
109
+ "persona": persona,
110
+ "audience": audience,
111
+ "messages": [
112
+ {"role": "system", "content": system_prompt},
113
+ {"role": "user", "content": prompt},
114
+ {"role": "assistant", "content": content},
115
+ ],
116
+ "tokens": response.usage.completion_tokens,
117
+ "char_count": len(content),
118
+ }
119
+ except Exception as e:
120
+ return {"_status": "error", "_error": f"{type(e).__name__}: {e}", "topic": topic}
121
+
122
+
123
+ async def main(subject, limit, concurrent):
124
+ seeds_file = f"seeds/{subject}.json"
125
+ output_file = f"data/{subject}/{FORMAT}.jsonl"
126
+
127
+ if not os.path.exists(seeds_file):
128
+ raise SystemExit(f"Seeds file not found: {seeds_file}")
129
+
130
+ os.makedirs(os.path.dirname(output_file), exist_ok=True)
131
+
132
+ system_prompt = build_system_prompt(subject)
133
+
134
+ topics = json.load(open(seeds_file))
135
+ rng = random.Random(SEED)
136
+ rng.shuffle(topics)
137
+
138
+ if limit:
139
+ topics = topics[:limit]
140
+ print(f"SMOKE TEST: limiting to {limit} samples")
141
+
142
+ done = load_done_topics(output_file)
143
+ if done:
144
+ before = len(topics)
145
+ topics = [t for t in topics if topic_hash(t) not in done]
146
+ print(f"Resume: {len(done)} already on disk, {len(topics)} remaining")
147
+
148
+ if not topics:
149
+ print("Nothing to do.")
150
+ return
151
+
152
+ print(f"Subject: {subject}")
153
+ print(f"Format: {FORMAT}")
154
+ print(f"Generating: {len(topics)} samples (concurrency={concurrent})")
155
+ print(f"Output: {output_file}")
156
+ print("=" * 70)
157
+
158
+ sem = asyncio.Semaphore(concurrent)
159
+ tasks = [
160
+ generate_one(t, rng.choice(PERSONAS), rng.choice(AUDIENCES),
161
+ system_prompt, subject, sem)
162
+ for t in topics
163
+ ]
164
+
165
+ written = 0
166
+ failed = 0
167
+ too_short = 0
168
+ total_tokens = 0
169
+ last_error = ""
170
+ t_start = time.time()
171
+
172
+ pbar = tqdm(
173
+ total=len(topics),
174
+ desc=f"{subject}/{FORMAT}",
175
+ unit="sample",
176
+ dynamic_ncols=True,
177
+ smoothing=0.1,
178
+ bar_format="{l_bar}{bar}| {n_fmt}/{total_fmt} [{elapsed}<{remaining}, {rate_fmt}{postfix}]",
179
+ )
180
+
181
+ with open(output_file, "a") as f:
182
+ for coro in asyncio.as_completed(tasks):
183
+ result = await coro
184
+ status = result.get("_status", "error") if result else "error"
185
+
186
+ if status == "ok":
187
+ result.pop("_status", None)
188
+ f.write(json.dumps(result, ensure_ascii=False) + "\n")
189
+ f.flush()
190
+ written += 1
191
+ total_tokens += result.get("tokens", 0)
192
+ elif status == "too_short":
193
+ too_short += 1
194
+ else:
195
+ failed += 1
196
+ last_error = result.get("_error", "")[:50] if result else ""
197
+
198
+ elapsed = time.time() - t_start
199
+ tok_per_sec = total_tokens / max(elapsed, 0.001)
200
+ avg_tokens = total_tokens / max(written, 1)
201
+
202
+ pbar.update(1)
203
+ pbar.set_postfix_str(
204
+ f"ok={written} fail={failed} short={too_short} "
205
+ f"tok/s={tok_per_sec:,.0f} avg_tok={avg_tokens:.0f}"
206
+ + (f" err={last_error}" if last_error else "")
207
+ )
208
+
209
+ pbar.close()
210
+
211
+ elapsed = time.time() - t_start
212
+ print("=" * 70)
213
+ print(f"DONE in {elapsed/60:.1f} min")
214
+ print(f" Written: {written}")
215
+ print(f" Failed: {failed}")
216
+ print(f" Too-short: {too_short}")
217
+ if written:
218
+ print(f" Throughput: {written/elapsed:.2f} samples/s, "
219
+ f"{total_tokens/elapsed:,.0f} tok/s")
220
+ print(f"\nOutput: {output_file} "
221
+ f"({sum(1 for _ in open(output_file))} total samples on disk)")
222
+
223
+
224
+ if __name__ == "__main__":
225
+ p = argparse.ArgumentParser()
226
+ p.add_argument("--subject", required=True)
227
+ p.add_argument("--limit", type=int, default=None)
228
+ p.add_argument("--concurrent", type=int, default=64)
229
+ args = p.parse_args()
230
+ asyncio.run(main(args.subject, args.limit, args.concurrent))