ModhiSathvik commited on
Commit
f331b5e
·
verified ·
1 Parent(s): cef7a92

Add generators/generate_code_exercise.py

Browse files
Files changed (1) hide show
  1. generators/generate_code_exercise.py +266 -0
generators/generate_code_exercise.py ADDED
@@ -0,0 +1,266 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """CODE_EXERCISE format generator (multi-subject).
2
+
3
+ Phi-1 paper's "CodeExercises" format: ONE self-contained function per sample,
4
+ with type hints, docstring, and complete body. No prose, no tests, no examples.
5
+ This is the format Phi-1 §3 credits with +22 HumanEval points.
6
+
7
+ Output shape:
8
+ ```{subject}
9
+ [imports]
10
+ def descriptive_name(arg: T, ...) -> R:
11
+ '''
12
+ One-line summary.
13
+
14
+ Parameters:
15
+ arg (T): description
16
+ Returns:
17
+ R: description
18
+ '''
19
+ # 8-30 lines of working code
20
+ ...
21
+ ```
22
+
23
+ Seed selection:
24
+ Looks for seeds/{subject}_code_exercise.json first.
25
+ Falls back to seeds/{subject}.json.
26
+
27
+ Usage (from /workspace/pluto_run/):
28
+ python generators/generate_code_exercise.py --subject python --limit 50
29
+ python generators/generate_code_exercise.py --subject python --concurrent 128
30
+ """
31
+
32
+ import argparse
33
+ import asyncio
34
+ import hashlib
35
+ import json
36
+ import os
37
+ import random
38
+ import time
39
+ from openai import AsyncOpenAI
40
+ from tqdm import tqdm
41
+
42
+
43
+ client = AsyncOpenAI(base_url="http://localhost:8000/v1", api_key="dummy")
44
+ MODEL = "qwen-coder"
45
+ SEED = 42
46
+ FORMAT = "code_exercise"
47
+
48
+
49
+ def build_system_prompt(subject):
50
+ subject_name = subject.capitalize() if subject != "cpp" else "C++"
51
+ return (
52
+ f"Output exactly one self-contained {subject_name} function in a single "
53
+ f"```{subject}``` code block. The function must have:\n"
54
+ f" - A descriptive snake_case name (e.g. find_closest_pair, "
55
+ f"compute_running_average, normalize_string_keys)\n"
56
+ f" - Type hints on every parameter and the return value\n"
57
+ f" - A docstring with a one-line summary, then Parameters: and Returns: sections\n"
58
+ f" - Required imports inside the block, at the top\n"
59
+ f" - A complete working body of 8-30 lines (no `pass`, no `...`, "
60
+ f"no placeholder comments)\n\n"
61
+ f"After the closing ``` of the code block, STOP. Do not write tests, "
62
+ f"usage examples, prose explanation, a second function, or anything else. "
63
+ f"The function should solve a small concrete sub-problem related to the topic."
64
+ )
65
+
66
+
67
+ PERSONAS = [
68
+ "a senior backend engineer",
69
+ "a library author writing reference implementations",
70
+ "an experienced developer building utility code",
71
+ "a code reviewer writing canonical examples",
72
+ "a competitive programmer with clean idiomatic style",
73
+ "a staff engineer writing internal helpers",
74
+ "a tooling engineer building developer utilities",
75
+ "a careful engineer who handles edge cases properly",
76
+ ]
77
+
78
+ AUDIENCES = [
79
+ "an intermediate developer",
80
+ "a junior developer learning function design",
81
+ "an engineer reviewing for code quality",
82
+ "a developer studying clean function patterns",
83
+ ]
84
+
85
+
86
+ def topic_hash(topic):
87
+ return hashlib.sha256(topic.encode("utf-8")).hexdigest()[:16]
88
+
89
+
90
+ def load_done_topics(output_file):
91
+ done = set()
92
+ if os.path.exists(output_file):
93
+ with open(output_file) as f:
94
+ for line in f:
95
+ try:
96
+ rec = json.loads(line)
97
+ if "topic" in rec:
98
+ done.add(topic_hash(rec["topic"]))
99
+ except Exception:
100
+ pass
101
+ return done
102
+
103
+
104
+ def resolve_seeds_path(subject):
105
+ """Prefer subject-specific filtered seeds, fall back to general seeds."""
106
+ filtered = f"seeds/{subject}_code_exercise.json"
107
+ general = f"seeds/{subject}.json"
108
+ if os.path.exists(filtered):
109
+ print(f"Using filtered seeds: {filtered}")
110
+ return filtered
111
+ if os.path.exists(general):
112
+ print(f"Using general seeds: {general}")
113
+ return general
114
+ raise SystemExit(
115
+ f"No seeds for subject '{subject}'. "
116
+ f"Create {filtered} or {general}."
117
+ )
118
+
119
+
120
+ async def generate_one(topic, persona, audience, system_prompt, subject, sem):
121
+ async with sem:
122
+ prompt = (
123
+ f"Persona: {persona}\n"
124
+ f"Audience: {audience}\n\n"
125
+ f"Topic: {topic}\n\n"
126
+ f"Write a self-contained {subject} function for this topic."
127
+ )
128
+ try:
129
+ response = await client.chat.completions.create(
130
+ model=MODEL,
131
+ messages=[
132
+ {"role": "system", "content": system_prompt},
133
+ {"role": "user", "content": prompt},
134
+ ],
135
+ temperature=0.7,
136
+ top_p=0.95,
137
+ max_tokens=800,
138
+ )
139
+ content = response.choices[0].message.content
140
+ if not content or len(content) < 50:
141
+ return {"_status": "too_short", "topic": topic}
142
+ return {
143
+ "_status": "ok",
144
+ "format": FORMAT,
145
+ "subject": subject,
146
+ "topic": topic,
147
+ "topic_hash": topic_hash(topic),
148
+ "persona": persona,
149
+ "audience": audience,
150
+ "messages": [
151
+ {"role": "system", "content": system_prompt},
152
+ {"role": "user", "content": prompt},
153
+ {"role": "assistant", "content": content},
154
+ ],
155
+ "tokens": response.usage.completion_tokens,
156
+ "char_count": len(content),
157
+ }
158
+ except Exception as e:
159
+ return {"_status": "error", "_error": f"{type(e).__name__}: {e}", "topic": topic}
160
+
161
+
162
+ async def main(subject, limit, concurrent):
163
+ seeds_file = resolve_seeds_path(subject)
164
+ output_file = f"data/{subject}/{FORMAT}.jsonl"
165
+
166
+ os.makedirs(os.path.dirname(output_file), exist_ok=True)
167
+
168
+ system_prompt = build_system_prompt(subject)
169
+
170
+ topics = json.load(open(seeds_file))
171
+ rng = random.Random(SEED)
172
+ rng.shuffle(topics)
173
+
174
+ if limit:
175
+ topics = topics[:limit]
176
+ print(f"SMOKE TEST: limiting to {limit} samples")
177
+
178
+ done = load_done_topics(output_file)
179
+ if done:
180
+ before = len(topics)
181
+ topics = [t for t in topics if topic_hash(t) not in done]
182
+ print(f"Resume: {len(done)} already on disk, {len(topics)} remaining")
183
+
184
+ if not topics:
185
+ print("Nothing to do.")
186
+ return
187
+
188
+ print(f"Subject: {subject}")
189
+ print(f"Format: {FORMAT}")
190
+ print(f"Generating: {len(topics)} samples (concurrency={concurrent})")
191
+ print(f"Output: {output_file}")
192
+ print("=" * 70)
193
+
194
+ sem = asyncio.Semaphore(concurrent)
195
+ tasks = [
196
+ generate_one(t, rng.choice(PERSONAS), rng.choice(AUDIENCES),
197
+ system_prompt, subject, sem)
198
+ for t in topics
199
+ ]
200
+
201
+ written = 0
202
+ failed = 0
203
+ too_short = 0
204
+ total_tokens = 0
205
+ last_error = ""
206
+ t_start = time.time()
207
+
208
+ pbar = tqdm(
209
+ total=len(topics),
210
+ desc=f"{subject}/{FORMAT}",
211
+ unit="sample",
212
+ dynamic_ncols=True,
213
+ smoothing=0.1,
214
+ bar_format="{l_bar}{bar}| {n_fmt}/{total_fmt} [{elapsed}<{remaining}, {rate_fmt}{postfix}]",
215
+ )
216
+
217
+ with open(output_file, "a") as f:
218
+ for coro in asyncio.as_completed(tasks):
219
+ result = await coro
220
+ status = result.get("_status", "error") if result else "error"
221
+
222
+ if status == "ok":
223
+ result.pop("_status", None)
224
+ f.write(json.dumps(result, ensure_ascii=False) + "\n")
225
+ f.flush()
226
+ written += 1
227
+ total_tokens += result.get("tokens", 0)
228
+ elif status == "too_short":
229
+ too_short += 1
230
+ else:
231
+ failed += 1
232
+ last_error = result.get("_error", "")[:50] if result else ""
233
+
234
+ elapsed = time.time() - t_start
235
+ tok_per_sec = total_tokens / max(elapsed, 0.001)
236
+ avg_tokens = total_tokens / max(written, 1)
237
+
238
+ pbar.update(1)
239
+ pbar.set_postfix_str(
240
+ f"ok={written} fail={failed} short={too_short} "
241
+ f"tok/s={tok_per_sec:,.0f} avg_tok={avg_tokens:.0f}"
242
+ + (f" err={last_error}" if last_error else "")
243
+ )
244
+
245
+ pbar.close()
246
+
247
+ elapsed = time.time() - t_start
248
+ print("=" * 70)
249
+ print(f"DONE in {elapsed/60:.1f} min")
250
+ print(f" Written: {written}")
251
+ print(f" Failed: {failed}")
252
+ print(f" Too-short: {too_short}")
253
+ if written:
254
+ print(f" Throughput: {written/elapsed:.2f} samples/s, "
255
+ f"{total_tokens/elapsed:,.0f} tok/s")
256
+ print(f"\nOutput: {output_file} "
257
+ f"({sum(1 for _ in open(output_file))} total samples on disk)")
258
+
259
+
260
+ if __name__ == "__main__":
261
+ p = argparse.ArgumentParser()
262
+ p.add_argument("--subject", required=True)
263
+ p.add_argument("--limit", type=int, default=None)
264
+ p.add_argument("--concurrent", type=int, default=128)
265
+ args = p.parse_args()
266
+ asyncio.run(main(args.subject, args.limit, args.concurrent))