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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""REFINEMENT format generator (multi-subject).
|
| 2 |
+
|
| 3 |
+
Shape: bad code -> issues called out -> good code -> why each change.
|
| 4 |
+
|
| 5 |
+
Structure:
|
| 6 |
+
## Problem one-line topic context
|
| 7 |
+
## Initial flawed but working code
|
| 8 |
+
## Issues 3-5 specific problems with bullets
|
| 9 |
+
## Refined improved code addressing every issue
|
| 10 |
+
## Why ties each change back to an issue
|
| 11 |
+
|
| 12 |
+
Seed selection:
|
| 13 |
+
Looks for seeds/{subject}_refinement.json first (filtered for
|
| 14 |
+
refinement-friendly topics). Falls back to seeds/{subject}.json.
|
| 15 |
+
|
| 16 |
+
Usage (from /workspace/pluto_run/):
|
| 17 |
+
python generators/generate_refinement.py --subject python --limit 50
|
| 18 |
+
python generators/generate_refinement.py --subject python
|
| 19 |
+
python generators/generate_refinement.py --subject python --concurrent 192
|
| 20 |
+
"""
|
| 21 |
+
|
| 22 |
+
import argparse
|
| 23 |
+
import asyncio
|
| 24 |
+
import hashlib
|
| 25 |
+
import json
|
| 26 |
+
import os
|
| 27 |
+
import random
|
| 28 |
+
import time
|
| 29 |
+
from openai import AsyncOpenAI
|
| 30 |
+
from tqdm import tqdm
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
client = AsyncOpenAI(base_url="http://localhost:8000/v1", api_key="dummy")
|
| 34 |
+
MODEL = "qwen-coder"
|
| 35 |
+
SEED = 42
|
| 36 |
+
FORMAT = "refinement"
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
def build_system_prompt(subject):
|
| 40 |
+
subject_name = subject.capitalize() if subject != "cpp" else "C++"
|
| 41 |
+
return (
|
| 42 |
+
f"You are a senior {subject_name} code reviewer creating a refactor "
|
| 43 |
+
f"example for a training corpus. Show before-and-after code with the "
|
| 44 |
+
f"specific issues called out. Use exactly this structure with these "
|
| 45 |
+
f"section headers:\n\n"
|
| 46 |
+
f"## Problem\n[one or two sentences stating what the code is supposed to do]\n\n"
|
| 47 |
+
f"## Initial\n```{subject}\n[working but flawed code, 10-25 lines]\n```\n\n"
|
| 48 |
+
f"## Issues\n[3-5 bullet points, each pointing at a real, substantive problem: "
|
| 49 |
+
f"poor naming, missing error handling, O(n^2) when O(n) is possible, "
|
| 50 |
+
f"non-idiomatic, fragile to edge cases, mutable default args, etc.]\n\n"
|
| 51 |
+
f"## Refined\n```{subject}\n[improved code that fixes every issue]\n```\n\n"
|
| 52 |
+
f"## Why\n[one paragraph tying each change back to its issue]\n\n"
|
| 53 |
+
f"Length: 600-1200 words. The flaws must be real (not contrived) and the "
|
| 54 |
+
f"refined version must measurably improve correctness, performance, "
|
| 55 |
+
f"readability, or robustness. Stop after the Why section."
|
| 56 |
+
)
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
PERSONAS = [
|
| 60 |
+
"a senior backend engineer who emphasizes correctness",
|
| 61 |
+
"a refactoring specialist with deep code-review experience",
|
| 62 |
+
"a tech lead writing internal style-guide examples",
|
| 63 |
+
"a library maintainer reviewing a contributor's PR",
|
| 64 |
+
"a staff engineer mentoring through critique",
|
| 65 |
+
"a code reviewer with a track record of catching subtle bugs",
|
| 66 |
+
"a performance engineer who sees the hot path first",
|
| 67 |
+
"a principal engineer documenting common anti-patterns",
|
| 68 |
+
]
|
| 69 |
+
|
| 70 |
+
AUDIENCES = [
|
| 71 |
+
"an intermediate developer learning to review code",
|
| 72 |
+
"a junior developer wanting to write idiomatic code",
|
| 73 |
+
"an experienced engineer studying anti-patterns",
|
| 74 |
+
"a senior engineer using these as teaching material",
|
| 75 |
+
"a self-taught developer leveling up code quality",
|
| 76 |
+
]
|
| 77 |
+
|
| 78 |
+
|
| 79 |
+
def topic_hash(topic):
|
| 80 |
+
return hashlib.sha256(topic.encode("utf-8")).hexdigest()[:16]
|
| 81 |
+
|
| 82 |
+
|
| 83 |
+
def load_done_topics(output_file):
|
| 84 |
+
done = set()
|
| 85 |
+
if os.path.exists(output_file):
|
| 86 |
+
with open(output_file) as f:
|
| 87 |
+
for line in f:
|
| 88 |
+
try:
|
| 89 |
+
rec = json.loads(line)
|
| 90 |
+
if "topic" in rec:
|
| 91 |
+
done.add(topic_hash(rec["topic"]))
|
| 92 |
+
except Exception:
|
| 93 |
+
pass
|
| 94 |
+
return done
|
| 95 |
+
|
| 96 |
+
|
| 97 |
+
def resolve_seeds_path(subject):
|
| 98 |
+
"""Prefer subject-specific filtered seeds, fall back to general seeds."""
|
| 99 |
+
filtered = f"seeds/{subject}_refinement.json"
|
| 100 |
+
general = f"seeds/{subject}.json"
|
| 101 |
+
if os.path.exists(filtered):
|
| 102 |
+
print(f"Using filtered seeds: {filtered}")
|
| 103 |
+
return filtered
|
| 104 |
+
if os.path.exists(general):
|
| 105 |
+
print(f"Using general seeds: {general}")
|
| 106 |
+
return general
|
| 107 |
+
raise SystemExit(
|
| 108 |
+
f"No seeds for subject '{subject}'. "
|
| 109 |
+
f"Create {filtered} or {general}."
|
| 110 |
+
)
|
| 111 |
+
|
| 112 |
+
|
| 113 |
+
async def generate_one(topic, persona, audience, system_prompt, subject, sem):
|
| 114 |
+
async with sem:
|
| 115 |
+
prompt = (
|
| 116 |
+
f"Persona: {persona}\n"
|
| 117 |
+
f"Audience: {audience}\n\n"
|
| 118 |
+
f"Write a refactor example for this {subject} topic: {topic}"
|
| 119 |
+
)
|
| 120 |
+
try:
|
| 121 |
+
response = await client.chat.completions.create(
|
| 122 |
+
model=MODEL,
|
| 123 |
+
messages=[
|
| 124 |
+
{"role": "system", "content": system_prompt},
|
| 125 |
+
{"role": "user", "content": prompt},
|
| 126 |
+
],
|
| 127 |
+
temperature=0.8,
|
| 128 |
+
top_p=0.95,
|
| 129 |
+
max_tokens=2200,
|
| 130 |
+
)
|
| 131 |
+
content = response.choices[0].message.content
|
| 132 |
+
if not content or len(content) < 100:
|
| 133 |
+
return {"_status": "too_short", "topic": topic}
|
| 134 |
+
return {
|
| 135 |
+
"_status": "ok",
|
| 136 |
+
"format": FORMAT,
|
| 137 |
+
"subject": subject,
|
| 138 |
+
"topic": topic,
|
| 139 |
+
"topic_hash": topic_hash(topic),
|
| 140 |
+
"persona": persona,
|
| 141 |
+
"audience": audience,
|
| 142 |
+
"messages": [
|
| 143 |
+
{"role": "system", "content": system_prompt},
|
| 144 |
+
{"role": "user", "content": prompt},
|
| 145 |
+
{"role": "assistant", "content": content},
|
| 146 |
+
],
|
| 147 |
+
"tokens": response.usage.completion_tokens,
|
| 148 |
+
"char_count": len(content),
|
| 149 |
+
}
|
| 150 |
+
except Exception as e:
|
| 151 |
+
return {"_status": "error", "_error": f"{type(e).__name__}: {e}", "topic": topic}
|
| 152 |
+
|
| 153 |
+
|
| 154 |
+
async def main(subject, limit, concurrent):
|
| 155 |
+
seeds_file = resolve_seeds_path(subject)
|
| 156 |
+
output_file = f"data/{subject}/{FORMAT}.jsonl"
|
| 157 |
+
|
| 158 |
+
os.makedirs(os.path.dirname(output_file), exist_ok=True)
|
| 159 |
+
|
| 160 |
+
system_prompt = build_system_prompt(subject)
|
| 161 |
+
|
| 162 |
+
topics = json.load(open(seeds_file))
|
| 163 |
+
rng = random.Random(SEED)
|
| 164 |
+
rng.shuffle(topics)
|
| 165 |
+
|
| 166 |
+
if limit:
|
| 167 |
+
topics = topics[:limit]
|
| 168 |
+
print(f"SMOKE TEST: limiting to {limit} samples")
|
| 169 |
+
|
| 170 |
+
done = load_done_topics(output_file)
|
| 171 |
+
if done:
|
| 172 |
+
before = len(topics)
|
| 173 |
+
topics = [t for t in topics if topic_hash(t) not in done]
|
| 174 |
+
print(f"Resume: {len(done)} already on disk, {len(topics)} remaining")
|
| 175 |
+
|
| 176 |
+
if not topics:
|
| 177 |
+
print("Nothing to do.")
|
| 178 |
+
return
|
| 179 |
+
|
| 180 |
+
print(f"Subject: {subject}")
|
| 181 |
+
print(f"Format: {FORMAT}")
|
| 182 |
+
print(f"Generating: {len(topics)} samples (concurrency={concurrent})")
|
| 183 |
+
print(f"Output: {output_file}")
|
| 184 |
+
print("=" * 70)
|
| 185 |
+
|
| 186 |
+
sem = asyncio.Semaphore(concurrent)
|
| 187 |
+
tasks = [
|
| 188 |
+
generate_one(t, rng.choice(PERSONAS), rng.choice(AUDIENCES),
|
| 189 |
+
system_prompt, subject, sem)
|
| 190 |
+
for t in topics
|
| 191 |
+
]
|
| 192 |
+
|
| 193 |
+
written = 0
|
| 194 |
+
failed = 0
|
| 195 |
+
too_short = 0
|
| 196 |
+
total_tokens = 0
|
| 197 |
+
last_error = ""
|
| 198 |
+
t_start = time.time()
|
| 199 |
+
|
| 200 |
+
pbar = tqdm(
|
| 201 |
+
total=len(topics),
|
| 202 |
+
desc=f"{subject}/{FORMAT}",
|
| 203 |
+
unit="sample",
|
| 204 |
+
dynamic_ncols=True,
|
| 205 |
+
smoothing=0.1,
|
| 206 |
+
bar_format="{l_bar}{bar}| {n_fmt}/{total_fmt} [{elapsed}<{remaining}, {rate_fmt}{postfix}]",
|
| 207 |
+
)
|
| 208 |
+
|
| 209 |
+
with open(output_file, "a") as f:
|
| 210 |
+
for coro in asyncio.as_completed(tasks):
|
| 211 |
+
result = await coro
|
| 212 |
+
status = result.get("_status", "error") if result else "error"
|
| 213 |
+
|
| 214 |
+
if status == "ok":
|
| 215 |
+
result.pop("_status", None)
|
| 216 |
+
f.write(json.dumps(result, ensure_ascii=False) + "\n")
|
| 217 |
+
f.flush()
|
| 218 |
+
written += 1
|
| 219 |
+
total_tokens += result.get("tokens", 0)
|
| 220 |
+
elif status == "too_short":
|
| 221 |
+
too_short += 1
|
| 222 |
+
else:
|
| 223 |
+
failed += 1
|
| 224 |
+
last_error = result.get("_error", "")[:50] if result else ""
|
| 225 |
+
|
| 226 |
+
elapsed = time.time() - t_start
|
| 227 |
+
tok_per_sec = total_tokens / max(elapsed, 0.001)
|
| 228 |
+
avg_tokens = total_tokens / max(written, 1)
|
| 229 |
+
|
| 230 |
+
pbar.update(1)
|
| 231 |
+
pbar.set_postfix_str(
|
| 232 |
+
f"ok={written} fail={failed} short={too_short} "
|
| 233 |
+
f"tok/s={tok_per_sec:,.0f} avg_tok={avg_tokens:.0f}"
|
| 234 |
+
+ (f" err={last_error}" if last_error else "")
|
| 235 |
+
)
|
| 236 |
+
|
| 237 |
+
pbar.close()
|
| 238 |
+
|
| 239 |
+
elapsed = time.time() - t_start
|
| 240 |
+
print("=" * 70)
|
| 241 |
+
print(f"DONE in {elapsed/60:.1f} min")
|
| 242 |
+
print(f" Written: {written}")
|
| 243 |
+
print(f" Failed: {failed}")
|
| 244 |
+
print(f" Too-short: {too_short}")
|
| 245 |
+
if written:
|
| 246 |
+
print(f" Throughput: {written/elapsed:.2f} samples/s, "
|
| 247 |
+
f"{total_tokens/elapsed:,.0f} tok/s")
|
| 248 |
+
print(f"\nOutput: {output_file} "
|
| 249 |
+
f"({sum(1 for _ in open(output_file))} total samples on disk)")
|
| 250 |
+
|
| 251 |
+
|
| 252 |
+
if __name__ == "__main__":
|
| 253 |
+
p = argparse.ArgumentParser()
|
| 254 |
+
p.add_argument("--subject", required=True)
|
| 255 |
+
p.add_argument("--limit", type=int, default=None)
|
| 256 |
+
p.add_argument("--concurrent", type=int, default=128)
|
| 257 |
+
args = p.parse_args()
|
| 258 |
+
asyncio.run(main(args.subject, args.limit, args.concurrent))
|