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

Add generators/generate_debug_dialogue.py

Browse files
Files changed (1) hide show
  1. generators/generate_debug_dialogue.py +268 -0
generators/generate_debug_dialogue.py ADDED
@@ -0,0 +1,268 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """DEBUG_DIALOGUE format generator (multi-subject).
2
+
3
+ Multi-turn debugging conversations between a developer and an AI assistant.
4
+ Trains the model on interactive reasoning over time:
5
+ - Reading buggy code and error messages
6
+ - Hypothesis formation and revision
7
+ - Asking clarifying questions
8
+ - Iterating toward a fix
9
+
10
+ Output shape (as a 4-turn dialogue):
11
+ **User:** [bug description + buggy ```{subject}``` code]
12
+ **Assistant:** [diagnosis, proposed fix with reasoning]
13
+ **User:** [tries fix, reports result - partial fix or new error]
14
+ **Assistant:** [final fix + root cause explanation]
15
+
16
+ Seed selection:
17
+ Looks for seeds/{subject}_debug_dialogue.json first.
18
+ Falls back to seeds/{subject}.json.
19
+
20
+ Usage (from /workspace/pluto_run/):
21
+ python generators/generate_debug_dialogue.py --subject python --limit 50
22
+ python generators/generate_debug_dialogue.py --subject python --concurrent 96
23
+ """
24
+
25
+ import argparse
26
+ import asyncio
27
+ import hashlib
28
+ import json
29
+ import os
30
+ import random
31
+ import time
32
+ from openai import AsyncOpenAI
33
+ from tqdm import tqdm
34
+
35
+
36
+ client = AsyncOpenAI(base_url="http://localhost:8000/v1", api_key="dummy")
37
+ MODEL = "qwen-coder"
38
+ SEED = 42
39
+ FORMAT = "debug_dialogue"
40
+
41
+
42
+ def build_system_prompt(subject):
43
+ subject_name = subject.capitalize() if subject != "cpp" else "C++"
44
+ return (
45
+ f"You are creating a multi-turn debugging dialogue for a training corpus. "
46
+ f"The dialogue is between a developer with a real bug and an AI assistant. "
47
+ f"Show 4 turns where they work toward the fix. Use exactly this format:\n\n"
48
+ f"**User:** [describes the bug they're seeing — what they expected, what "
49
+ f"actually happened, error messages if any. Include the buggy {subject} "
50
+ f"code in a ```{subject}``` code block]\n\n"
51
+ f"**Assistant:** [diagnoses the problem; either asks one targeted "
52
+ f"clarifying question, or proposes a fix with reasoning about the root "
53
+ f"cause. Include corrected ```{subject}``` code if proposing a fix]\n\n"
54
+ f"**User:** [reports what happened when they tried the fix — partial "
55
+ f"success with a new error, or 'still broken' with a more specific symptom. "
56
+ f"This makes the bug realistic; not all bugs reveal themselves at once]\n\n"
57
+ f"**Assistant:** [final fix with explanation of the actual root cause "
58
+ f"and why the first attempt was incomplete. Include the corrected "
59
+ f"```{subject}``` code]\n\n"
60
+ f"Make the bug subtle and realistic - the kind that takes a real engineer "
61
+ f"two iterations to nail. Avoid trivial typos. Aim for bugs in: edge "
62
+ f"cases, off-by-one errors, mutable state, race conditions, async "
63
+ f"misuse, scope issues, type confusion, library API misuse, etc. "
64
+ f"Length: 500-900 words. After the final assistant turn, STOP."
65
+ )
66
+
67
+
68
+ PERSONAS = [
69
+ "a senior engineer mentoring through debugging conversations",
70
+ "an experienced developer with deep debugging instincts",
71
+ "a code reviewer skilled at root-cause analysis",
72
+ "a tech lead who walks juniors through bug reports",
73
+ "a staff engineer who debugs by understanding intent first",
74
+ "a careful debugger who asks before assuming",
75
+ "a teaching engineer who explains the why behind every fix",
76
+ ]
77
+
78
+ AUDIENCES = [
79
+ "an intermediate developer asking for help",
80
+ "a junior developer stuck on a real bug",
81
+ "a self-taught programmer learning to debug systematically",
82
+ "an engineer new to this codebase or library",
83
+ "a developer learning debugging methodology",
84
+ ]
85
+
86
+
87
+ def topic_hash(topic):
88
+ return hashlib.sha256(topic.encode("utf-8")).hexdigest()[:16]
89
+
90
+
91
+ def load_done_topics(output_file):
92
+ done = set()
93
+ if os.path.exists(output_file):
94
+ with open(output_file) as f:
95
+ for line in f:
96
+ try:
97
+ rec = json.loads(line)
98
+ if "topic" in rec:
99
+ done.add(topic_hash(rec["topic"]))
100
+ except Exception:
101
+ pass
102
+ return done
103
+
104
+
105
+ def resolve_seeds_path(subject):
106
+ """Prefer subject-specific filtered seeds, fall back to general seeds."""
107
+ filtered = f"seeds/{subject}_debug_dialogue.json"
108
+ general = f"seeds/{subject}.json"
109
+ if os.path.exists(filtered):
110
+ print(f"Using filtered seeds: {filtered}")
111
+ return filtered
112
+ if os.path.exists(general):
113
+ print(f"Using general seeds: {general}")
114
+ return general
115
+ raise SystemExit(
116
+ f"No seeds for subject '{subject}'. "
117
+ f"Create {filtered} or {general}."
118
+ )
119
+
120
+
121
+ async def generate_one(topic, persona, audience, system_prompt, subject, sem):
122
+ async with sem:
123
+ prompt = (
124
+ f"Persona: {persona}\n"
125
+ f"Audience: {audience}\n\n"
126
+ f"Topic: {topic}\n\n"
127
+ f"Generate a 4-turn debugging dialogue around a realistic bug "
128
+ f"related to this {subject} topic."
129
+ )
130
+ try:
131
+ response = await client.chat.completions.create(
132
+ model=MODEL,
133
+ messages=[
134
+ {"role": "system", "content": system_prompt},
135
+ {"role": "user", "content": prompt},
136
+ ],
137
+ temperature=0.85,
138
+ top_p=0.95,
139
+ max_tokens=2000,
140
+ )
141
+ content = response.choices[0].message.content
142
+ if not content or len(content) < 200:
143
+ return {"_status": "too_short", "topic": topic}
144
+ return {
145
+ "_status": "ok",
146
+ "format": FORMAT,
147
+ "subject": subject,
148
+ "topic": topic,
149
+ "topic_hash": topic_hash(topic),
150
+ "persona": persona,
151
+ "audience": audience,
152
+ "messages": [
153
+ {"role": "system", "content": system_prompt},
154
+ {"role": "user", "content": prompt},
155
+ {"role": "assistant", "content": content},
156
+ ],
157
+ "tokens": response.usage.completion_tokens,
158
+ "char_count": len(content),
159
+ }
160
+ except Exception as e:
161
+ return {"_status": "error", "_error": f"{type(e).__name__}: {e}", "topic": topic}
162
+
163
+
164
+ async def main(subject, limit, concurrent):
165
+ seeds_file = resolve_seeds_path(subject)
166
+ output_file = f"data/{subject}/{FORMAT}.jsonl"
167
+
168
+ os.makedirs(os.path.dirname(output_file), exist_ok=True)
169
+
170
+ system_prompt = build_system_prompt(subject)
171
+
172
+ topics = json.load(open(seeds_file))
173
+ rng = random.Random(SEED)
174
+ rng.shuffle(topics)
175
+
176
+ if limit:
177
+ topics = topics[:limit]
178
+ print(f"SMOKE TEST: limiting to {limit} samples")
179
+
180
+ done = load_done_topics(output_file)
181
+ if done:
182
+ before = len(topics)
183
+ topics = [t for t in topics if topic_hash(t) not in done]
184
+ print(f"Resume: {len(done)} already on disk, {len(topics)} remaining")
185
+
186
+ if not topics:
187
+ print("Nothing to do.")
188
+ return
189
+
190
+ print(f"Subject: {subject}")
191
+ print(f"Format: {FORMAT}")
192
+ print(f"Generating: {len(topics)} samples (concurrency={concurrent})")
193
+ print(f"Output: {output_file}")
194
+ print("=" * 70)
195
+
196
+ sem = asyncio.Semaphore(concurrent)
197
+ tasks = [
198
+ generate_one(t, rng.choice(PERSONAS), rng.choice(AUDIENCES),
199
+ system_prompt, subject, sem)
200
+ for t in topics
201
+ ]
202
+
203
+ written = 0
204
+ failed = 0
205
+ too_short = 0
206
+ total_tokens = 0
207
+ last_error = ""
208
+ t_start = time.time()
209
+
210
+ pbar = tqdm(
211
+ total=len(topics),
212
+ desc=f"{subject}/{FORMAT}",
213
+ unit="sample",
214
+ dynamic_ncols=True,
215
+ smoothing=0.1,
216
+ bar_format="{l_bar}{bar}| {n_fmt}/{total_fmt} [{elapsed}<{remaining}, {rate_fmt}{postfix}]",
217
+ )
218
+
219
+ with open(output_file, "a") as f:
220
+ for coro in asyncio.as_completed(tasks):
221
+ result = await coro
222
+ status = result.get("_status", "error") if result else "error"
223
+
224
+ if status == "ok":
225
+ result.pop("_status", None)
226
+ f.write(json.dumps(result, ensure_ascii=False) + "\n")
227
+ f.flush()
228
+ written += 1
229
+ total_tokens += result.get("tokens", 0)
230
+ elif status == "too_short":
231
+ too_short += 1
232
+ else:
233
+ failed += 1
234
+ last_error = result.get("_error", "")[:50] if result else ""
235
+
236
+ elapsed = time.time() - t_start
237
+ tok_per_sec = total_tokens / max(elapsed, 0.001)
238
+ avg_tokens = total_tokens / max(written, 1)
239
+
240
+ pbar.update(1)
241
+ pbar.set_postfix_str(
242
+ f"ok={written} fail={failed} short={too_short} "
243
+ f"tok/s={tok_per_sec:,.0f} avg_tok={avg_tokens:.0f}"
244
+ + (f" err={last_error}" if last_error else "")
245
+ )
246
+
247
+ pbar.close()
248
+
249
+ elapsed = time.time() - t_start
250
+ print("=" * 70)
251
+ print(f"DONE in {elapsed/60:.1f} min")
252
+ print(f" Written: {written}")
253
+ print(f" Failed: {failed}")
254
+ print(f" Too-short: {too_short}")
255
+ if written:
256
+ print(f" Throughput: {written/elapsed:.2f} samples/s, "
257
+ f"{total_tokens/elapsed:,.0f} tok/s")
258
+ print(f"\nOutput: {output_file} "
259
+ f"({sum(1 for _ in open(output_file))} total samples on disk)")
260
+
261
+
262
+ if __name__ == "__main__":
263
+ p = argparse.ArgumentParser()
264
+ p.add_argument("--subject", required=True)
265
+ p.add_argument("--limit", type=int, default=None)
266
+ p.add_argument("--concurrent", type=int, default=128)
267
+ args = p.parse_args()
268
+ asyncio.run(main(args.subject, args.limit, args.concurrent))