ModhiSathvik commited on
Commit
5a4eb76
·
verified ·
1 Parent(s): 9145815

Add generators/generate_infilling_long.py

Browse files
Files changed (1) hide show
  1. generators/generate_infilling_long.py +235 -0
generators/generate_infilling_long.py ADDED
@@ -0,0 +1,235 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """INFILLING_LONG format generator.
2
+
3
+ Variant of infilling that produces 60-120 line code samples instead of 30-60.
4
+ Teaches the model to use distant code as context — critical for IDE autocomplete
5
+ where the model needs to predict middle from far-apart prefix/suffix.
6
+
7
+ Output shape: a single ```{subject}``` block with a substantial multi-component
8
+ code sample. Multiple functions, possibly a class + helpers + main usage,
9
+ with cross-references between them.
10
+
11
+ Seed selection:
12
+ Looks for seeds/{subject}_infilling_long.json first.
13
+ Falls back to seeds/{subject}_infilling.json then seeds/{subject}.json.
14
+
15
+ Usage (from /workspace/pluto_run/):
16
+ python generators/generate_infilling_long.py --subject python --limit 50
17
+ python generators/generate_infilling_long.py --subject python --concurrent 96
18
+ """
19
+
20
+ import argparse
21
+ import asyncio
22
+ import hashlib
23
+ import json
24
+ import os
25
+ import random
26
+ import time
27
+ from openai import AsyncOpenAI
28
+ from tqdm import tqdm
29
+
30
+
31
+ client = AsyncOpenAI(base_url="http://localhost:8000/v1", api_key="dummy")
32
+ MODEL = "qwen-coder"
33
+ SEED = 42
34
+ FORMAT = "infilling_long"
35
+
36
+
37
+ def build_system_prompt(subject):
38
+ subject_name = subject.capitalize() if subject != "cpp" else "C++"
39
+ return (
40
+ f"Output a SUBSTANTIAL {subject_name} code sample. The code MUST be "
41
+ f"between 70 and 130 lines. This is a hard requirement. Short answers "
42
+ f"will be rejected.\n\n"
43
+ f"Format: a single ```{subject}``` code block with no prose around it.\n\n"
44
+ f"Required components (all of these):\n"
45
+ f" - 5+ imports at the top\n"
46
+ f" - At least one class with __init__ and 2-3 methods (15-25 lines)\n"
47
+ f" - At least 3 module-level helper functions (10-20 lines each)\n"
48
+ f" - A main() function or `if __name__ == \"__main__\":` block "
49
+ f"that demonstrates usage (10-15 lines)\n"
50
+ f" - Realistic error handling (try/except blocks, validation)\n"
51
+ f" - Type hints on every function\n"
52
+ f" - Docstrings on every function and method\n"
53
+ f" - Cross-references: helpers called from class methods, class used in main\n\n"
54
+ f"Style: production-grade {subject_name}, not toy code. Include realistic "
55
+ f"data validation, edge case handling, and logging where appropriate. "
56
+ f"Use real library APIs.\n\n"
57
+ f"NO `pass`, NO `...`, NO TODO comments, NO placeholder code.\n\n"
58
+ f"After the closing ``` of the code block, STOP. NO prose around it."
59
+ )
60
+
61
+
62
+ PERSONAS = [
63
+ "a senior backend engineer writing production-grade code",
64
+ "a library author building reference implementations",
65
+ "an experienced developer building real-world utilities",
66
+ "a staff engineer writing internal tooling",
67
+ "a tooling engineer building developer infrastructure",
68
+ "a careful engineer who handles edge cases properly",
69
+ "a systems programmer writing performance-aware code",
70
+ "a tech lead writing canonical example modules",
71
+ ]
72
+
73
+ AUDIENCES = [
74
+ "an intermediate developer studying complete patterns",
75
+ "an experienced engineer learning from canonical examples",
76
+ "a senior reviewer studying clean implementations",
77
+ "a developer learning from realistic code samples",
78
+ ]
79
+
80
+
81
+ def topic_hash(topic):
82
+ return hashlib.sha256(topic.encode("utf-8")).hexdigest()[:16]
83
+
84
+
85
+ def load_done_topics(output_file):
86
+ done = set()
87
+ if os.path.exists(output_file):
88
+ with open(output_file) as f:
89
+ for line in f:
90
+ try:
91
+ rec = json.loads(line)
92
+ if "topic" in rec:
93
+ done.add(topic_hash(rec["topic"]))
94
+ except Exception:
95
+ pass
96
+ return done
97
+
98
+
99
+ def resolve_seeds_path(subject):
100
+ candidates = [
101
+ f"seeds/{subject}_infilling_long.json",
102
+ f"seeds/{subject}_infilling.json",
103
+ f"seeds/{subject}.json",
104
+ ]
105
+ for path in candidates:
106
+ if os.path.exists(path):
107
+ print(f"Using seeds: {path}")
108
+ return path
109
+ raise SystemExit(f"No seeds found in any of: {candidates}")
110
+
111
+
112
+ async def generate_one(topic, persona, audience, system_prompt, subject, sem):
113
+ async with sem:
114
+ prompt = (
115
+ f"Persona: {persona}\n"
116
+ f"Audience: {audience}\n\n"
117
+ f"Topic: {topic}\n\n"
118
+ f"Write a substantial {subject} code sample (60-120 lines) "
119
+ f"with multiple cross-referenced components."
120
+ )
121
+ try:
122
+ response = await client.chat.completions.create(
123
+ model=MODEL,
124
+ messages=[
125
+ {"role": "system", "content": system_prompt},
126
+ {"role": "user", "content": prompt},
127
+ ],
128
+ temperature=0.7,
129
+ top_p=0.95,
130
+ max_tokens=2800,
131
+ )
132
+ content = response.choices[0].message.content
133
+ if not content or len(content) < 200:
134
+ return {"_status": "too_short", "topic": topic}
135
+ return {
136
+ "_status": "ok",
137
+ "format": FORMAT,
138
+ "subject": subject,
139
+ "topic": topic,
140
+ "topic_hash": topic_hash(topic),
141
+ "persona": persona,
142
+ "audience": audience,
143
+ "messages": [
144
+ {"role": "system", "content": system_prompt},
145
+ {"role": "user", "content": prompt},
146
+ {"role": "assistant", "content": content},
147
+ ],
148
+ "tokens": response.usage.completion_tokens,
149
+ "char_count": len(content),
150
+ }
151
+ except Exception as e:
152
+ return {"_status": "error", "_error": f"{type(e).__name__}: {e}", "topic": topic}
153
+
154
+
155
+ async def main(subject, limit, concurrent):
156
+ seeds_file = resolve_seeds_path(subject)
157
+ output_file = f"data/{subject}/{FORMAT}.jsonl"
158
+ os.makedirs(os.path.dirname(output_file), exist_ok=True)
159
+ system_prompt = build_system_prompt(subject)
160
+
161
+ topics = json.load(open(seeds_file))
162
+ rng = random.Random(SEED)
163
+ rng.shuffle(topics)
164
+ if limit:
165
+ topics = topics[:limit]
166
+ print(f"SMOKE TEST: limiting to {limit} samples")
167
+
168
+ done = load_done_topics(output_file)
169
+ if done:
170
+ topics = [t for t in topics if topic_hash(t) not in done]
171
+ print(f"Resume: {len(done)} on disk, {len(topics)} remaining")
172
+ if not topics:
173
+ print("Nothing to do.")
174
+ return
175
+
176
+ print(f"Subject: {subject} Format: {FORMAT}")
177
+ print(f"Generating {len(topics)} samples (concurrency={concurrent})")
178
+ print(f"Output: {output_file}")
179
+ print("=" * 70)
180
+
181
+ sem = asyncio.Semaphore(concurrent)
182
+ tasks = [
183
+ generate_one(t, rng.choice(PERSONAS), rng.choice(AUDIENCES),
184
+ system_prompt, subject, sem)
185
+ for t in topics
186
+ ]
187
+
188
+ written = failed = too_short = total_tokens = 0
189
+ last_error = ""
190
+ t_start = time.time()
191
+ pbar = tqdm(total=len(topics), desc=f"{subject}/{FORMAT}", unit="sample",
192
+ dynamic_ncols=True, smoothing=0.1,
193
+ bar_format="{l_bar}{bar}| {n_fmt}/{total_fmt} [{elapsed}<{remaining}, {rate_fmt}{postfix}]")
194
+
195
+ with open(output_file, "a") as f:
196
+ for coro in asyncio.as_completed(tasks):
197
+ result = await coro
198
+ status = result.get("_status", "error") if result else "error"
199
+ if status == "ok":
200
+ result.pop("_status", None)
201
+ f.write(json.dumps(result, ensure_ascii=False) + "\n")
202
+ f.flush()
203
+ written += 1
204
+ total_tokens += result.get("tokens", 0)
205
+ elif status == "too_short":
206
+ too_short += 1
207
+ else:
208
+ failed += 1
209
+ last_error = result.get("_error", "")[:50] if result else ""
210
+ elapsed = time.time() - t_start
211
+ tps = total_tokens / max(elapsed, 0.001)
212
+ avg = total_tokens / max(written, 1)
213
+ pbar.update(1)
214
+ pbar.set_postfix_str(f"ok={written} fail={failed} short={too_short} "
215
+ f"tok/s={tps:,.0f} avg_tok={avg:.0f}"
216
+ + (f" err={last_error}" if last_error else ""))
217
+ pbar.close()
218
+
219
+ elapsed = time.time() - t_start
220
+ print("=" * 70)
221
+ print(f"DONE in {elapsed/60:.1f} min")
222
+ print(f" Written: {written} | Failed: {failed} | Too-short: {too_short}")
223
+ if written:
224
+ print(f" Throughput: {written/elapsed:.2f} samples/s, {total_tokens/elapsed:,.0f} tok/s")
225
+ print(f"\nOutput: {output_file} ({sum(1 for _ in open(output_file))} total)")
226
+
227
+
228
+ if __name__ == "__main__":
229
+ p = argparse.ArgumentParser()
230
+ p.add_argument("--subject", required=True)
231
+ p.add_argument("--limit", type=int, default=None)
232
+ p.add_argument("--concurrent", type=int, default=96)
233
+ args = p.parse_args()
234
+ asyncio.run(main(args.subject, args.limit, args.concurrent))
235
+