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

Add generators/generate_textbook.py

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