ModhiSathvik commited on
Commit
be08060
·
verified ·
1 Parent(s): 6189eaf

Add generators/generate_instruction_reversal.py

Browse files
generators/generate_instruction_reversal.py ADDED
@@ -0,0 +1,276 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """INSTRUCTION_REVERSAL format generator (multi-subject).
2
+
3
+ Phi-4's instruction reversal trick (paper section 3.3): generate realistic
4
+ code, then derive the natural-language instruction a developer would have
5
+ given to produce that exact code. Trains the model on the inverse mapping:
6
+ "vague human request -> specific code".
7
+
8
+ Output shape:
9
+ ## Code
10
+ ```{subject}
11
+ [40-80 lines of realistic, idiomatic, production-style code]
12
+ ```
13
+
14
+ ## Instruction
15
+ [the natural-language ask a developer would have given to produce this code,
16
+ phrased the way a real developer would: specific, clear, action-oriented]
17
+
18
+ ## Summary
19
+ [one paragraph describing what the code does, at a high level]
20
+
21
+ Seed selection:
22
+ Looks for seeds/{subject}_instruction_reversal.json first.
23
+ Falls back to seeds/{subject}.json.
24
+
25
+ Usage (from /workspace/pluto_run/):
26
+ python generators/generate_instruction_reversal.py --subject python --limit 50
27
+ python generators/generate_instruction_reversal.py --subject python --concurrent 128
28
+ """
29
+
30
+ import argparse
31
+ import asyncio
32
+ import hashlib
33
+ import json
34
+ import os
35
+ import random
36
+ import time
37
+ from openai import AsyncOpenAI
38
+ from tqdm import tqdm
39
+
40
+
41
+ client = AsyncOpenAI(base_url="http://localhost:8000/v1", api_key="dummy")
42
+ MODEL = "qwen-coder"
43
+ SEED = 42
44
+ FORMAT = "instruction_reversal"
45
+
46
+
47
+ def build_system_prompt(subject):
48
+ subject_name = subject.capitalize() if subject != "cpp" else "C++"
49
+ return (
50
+ f"You are creating training data using the instruction reversal technique. "
51
+ f"For the given topic:\n\n"
52
+ f"Step 1: Write a piece of high-quality {subject_name} code (40-80 lines). "
53
+ f"Realistic, idiomatic, production-style - the kind of code a senior "
54
+ f"engineer would write. Not toy code. Include imports, helper functions "
55
+ f"as needed, and use real library APIs.\n\n"
56
+ f"Step 2: Derive the natural-language instruction a developer would have "
57
+ f"given to an AI to produce this exact code. Phrase it the way a real "
58
+ f"developer would phrase it: specific, action-oriented, technical but "
59
+ f"not over-formal. Include the constraints and library choices that "
60
+ f"would lead to this exact implementation.\n\n"
61
+ f"Step 3: Briefly describe what the code does at a high level.\n\n"
62
+ f"Use exactly this structure:\n\n"
63
+ f"## Code\n"
64
+ f"```{subject}\n"
65
+ f"[the 40-80 line code]\n"
66
+ f"```\n\n"
67
+ f"## Instruction\n"
68
+ f"[the natural-language instruction]\n\n"
69
+ f"## Summary\n"
70
+ f"[one paragraph describing what the code does]\n\n"
71
+ f"After the Summary section, STOP. The instruction must be specific "
72
+ f"enough that following it would produce code very similar to what's "
73
+ f"in the Code section."
74
+ )
75
+
76
+
77
+ PERSONAS = [
78
+ "a senior backend engineer writing production code",
79
+ "a library author building reference implementations",
80
+ "an experienced developer working on real-world utilities",
81
+ "a staff engineer building internal tooling",
82
+ "a tech lead writing canonical example code",
83
+ "a careful engineer who handles edge cases properly",
84
+ "a systems programmer focused on correctness",
85
+ "a developer building reusable helper modules",
86
+ ]
87
+
88
+ AUDIENCES = [
89
+ "an AI code assistant being trained on production patterns",
90
+ "a developer reading an example to learn from",
91
+ "an engineer studying canonical implementations",
92
+ "a code generation model learning to map intent to code",
93
+ ]
94
+
95
+
96
+ def topic_hash(topic):
97
+ return hashlib.sha256(topic.encode("utf-8")).hexdigest()[:16]
98
+
99
+
100
+ def load_done_topics(output_file):
101
+ done = set()
102
+ if os.path.exists(output_file):
103
+ with open(output_file) as f:
104
+ for line in f:
105
+ try:
106
+ rec = json.loads(line)
107
+ if "topic" in rec:
108
+ done.add(topic_hash(rec["topic"]))
109
+ except Exception:
110
+ pass
111
+ return done
112
+
113
+
114
+ def resolve_seeds_path(subject):
115
+ """Prefer subject-specific filtered seeds, fall back to general seeds."""
116
+ filtered = f"seeds/{subject}_instruction_reversal.json"
117
+ general = f"seeds/{subject}.json"
118
+ if os.path.exists(filtered):
119
+ print(f"Using filtered seeds: {filtered}")
120
+ return filtered
121
+ if os.path.exists(general):
122
+ print(f"Using general seeds: {general}")
123
+ return general
124
+ raise SystemExit(
125
+ f"No seeds for subject '{subject}'. "
126
+ f"Create {filtered} or {general}."
127
+ )
128
+
129
+
130
+ async def generate_one(topic, persona, audience, system_prompt, subject, sem):
131
+ async with sem:
132
+ prompt = (
133
+ f"Persona: {persona}\n"
134
+ f"Audience: {audience}\n\n"
135
+ f"Topic: {topic}\n\n"
136
+ f"Generate a code-instruction-summary triple for this {subject} topic."
137
+ )
138
+ try:
139
+ response = await client.chat.completions.create(
140
+ model=MODEL,
141
+ messages=[
142
+ {"role": "system", "content": system_prompt},
143
+ {"role": "user", "content": prompt},
144
+ ],
145
+ temperature=0.8,
146
+ top_p=0.95,
147
+ max_tokens=1500,
148
+ )
149
+ content = response.choices[0].message.content
150
+ if not content or len(content) < 200:
151
+ return {"_status": "too_short", "topic": topic}
152
+ return {
153
+ "_status": "ok",
154
+ "format": FORMAT,
155
+ "subject": subject,
156
+ "topic": topic,
157
+ "topic_hash": topic_hash(topic),
158
+ "persona": persona,
159
+ "audience": audience,
160
+ "messages": [
161
+ {"role": "system", "content": system_prompt},
162
+ {"role": "user", "content": prompt},
163
+ {"role": "assistant", "content": content},
164
+ ],
165
+ "tokens": response.usage.completion_tokens,
166
+ "char_count": len(content),
167
+ }
168
+ except Exception as e:
169
+ return {"_status": "error", "_error": f"{type(e).__name__}: {e}", "topic": topic}
170
+
171
+
172
+ async def main(subject, limit, concurrent):
173
+ seeds_file = resolve_seeds_path(subject)
174
+ output_file = f"data/{subject}/{FORMAT}.jsonl"
175
+
176
+ os.makedirs(os.path.dirname(output_file), exist_ok=True)
177
+
178
+ system_prompt = build_system_prompt(subject)
179
+
180
+ topics = json.load(open(seeds_file))
181
+ rng = random.Random(SEED)
182
+ rng.shuffle(topics)
183
+
184
+ if limit:
185
+ topics = topics[:limit]
186
+ print(f"SMOKE TEST: limiting to {limit} samples")
187
+
188
+ done = load_done_topics(output_file)
189
+ if done:
190
+ before = len(topics)
191
+ topics = [t for t in topics if topic_hash(t) not in done]
192
+ print(f"Resume: {len(done)} already on disk, {len(topics)} remaining")
193
+
194
+ if not topics:
195
+ print("Nothing to do.")
196
+ return
197
+
198
+ print(f"Subject: {subject}")
199
+ print(f"Format: {FORMAT}")
200
+ print(f"Generating: {len(topics)} samples (concurrency={concurrent})")
201
+ print(f"Output: {output_file}")
202
+ print("=" * 70)
203
+
204
+ sem = asyncio.Semaphore(concurrent)
205
+ tasks = [
206
+ generate_one(t, rng.choice(PERSONAS), rng.choice(AUDIENCES),
207
+ system_prompt, subject, sem)
208
+ for t in topics
209
+ ]
210
+
211
+ written = 0
212
+ failed = 0
213
+ too_short = 0
214
+ total_tokens = 0
215
+ last_error = ""
216
+ t_start = time.time()
217
+
218
+ pbar = tqdm(
219
+ total=len(topics),
220
+ desc=f"{subject}/{FORMAT}",
221
+ unit="sample",
222
+ dynamic_ncols=True,
223
+ smoothing=0.1,
224
+ bar_format="{l_bar}{bar}| {n_fmt}/{total_fmt} [{elapsed}<{remaining}, {rate_fmt}{postfix}]",
225
+ )
226
+
227
+ with open(output_file, "a") as f:
228
+ for coro in asyncio.as_completed(tasks):
229
+ result = await coro
230
+ status = result.get("_status", "error") if result else "error"
231
+
232
+ if status == "ok":
233
+ result.pop("_status", None)
234
+ f.write(json.dumps(result, ensure_ascii=False) + "\n")
235
+ f.flush()
236
+ written += 1
237
+ total_tokens += result.get("tokens", 0)
238
+ elif status == "too_short":
239
+ too_short += 1
240
+ else:
241
+ failed += 1
242
+ last_error = result.get("_error", "")[:50] if result else ""
243
+
244
+ elapsed = time.time() - t_start
245
+ tok_per_sec = total_tokens / max(elapsed, 0.001)
246
+ avg_tokens = total_tokens / max(written, 1)
247
+
248
+ pbar.update(1)
249
+ pbar.set_postfix_str(
250
+ f"ok={written} fail={failed} short={too_short} "
251
+ f"tok/s={tok_per_sec:,.0f} avg_tok={avg_tokens:.0f}"
252
+ + (f" err={last_error}" if last_error else "")
253
+ )
254
+
255
+ pbar.close()
256
+
257
+ elapsed = time.time() - t_start
258
+ print("=" * 70)
259
+ print(f"DONE in {elapsed/60:.1f} min")
260
+ print(f" Written: {written}")
261
+ print(f" Failed: {failed}")
262
+ print(f" Too-short: {too_short}")
263
+ if written:
264
+ print(f" Throughput: {written/elapsed:.2f} samples/s, "
265
+ f"{total_tokens/elapsed:,.0f} tok/s")
266
+ print(f"\nOutput: {output_file} "
267
+ f"({sum(1 for _ in open(output_file))} total samples on disk)")
268
+
269
+
270
+ if __name__ == "__main__":
271
+ p = argparse.ArgumentParser()
272
+ p.add_argument("--subject", required=True)
273
+ p.add_argument("--limit", type=int, default=None)
274
+ p.add_argument("--concurrent", type=int, default=128)
275
+ args = p.parse_args()
276
+ asyncio.run(main(args.subject, args.limit, args.concurrent))