Datasets:
Download code/mt_qa.py from drawais/circuitqa: direct link, hf CLI and curl.
- Browser
- Download file 10.1 kB
-
https://huggingface.co/datasets/drawais/circuitqa/resolve/main/code/mt_qa.py
- Command line
-
hf download hf://datasets/drawais/circuitqa/code/mt_qa.py
-
curl -L -o mt_qa.py https://huggingface.co/datasets/drawais/circuitqa/resolve/main/code/mt_qa.py
10.1 kB
| #!/usr/bin/env python3 | |
| """Multi-tool set, step 3: write one compositional question + reference answer per | |
| plan from the grounded results of ALL its backend calls. | |
| python3 mt_qa.py --split test --provider claude-cli --model claude-opus-5-5 --out splits/mt/test.jsonl | |
| python3 mt_qa.py --split train --provider glm --model glm-5.3 --out splits/mt/train.jsonl | |
| Use of a provider's outputs, in particular to train or fine-tune models, is subject to that | |
| provider's terms; check them, and obtain any authorization they require, before such use. | |
| Only plans whose every call succeeded are used. The writer sees exactly the | |
| context the decoder will see (same per-backend head/tail cap). Validation: | |
| every number in the answer occurs in that context; the answer uses a value | |
| unique to each backend block; the question names the module, states the graph | |
| type / non-default optimisation target, and never names a backend function. | |
| Records follow the corpus schema; stage1_target is a JSON LIST of calls. | |
| """ | |
| import argparse, hashlib, json, os, re, subprocess, sys, tempfile, time, urllib.request | |
| from concurrent.futures import ThreadPoolExecutor, as_completed | |
| TOTAL_CAP = 2700 # all blocks together; fits the training window (ctx_cap) and is | |
| # far below circuitqa_infer TOOL_CAP (8000), so train/infer/writer see the same text | |
| CTX_CAP = 3300 # per-record stage2_context cap for training (question + blocks) | |
| OK = {"success", "estimated"} | |
| FUNCS = ["synthesis_tool", "simulation_tool", "graph_extractor", "static_analyzer", | |
| "optimization_advisor", "cross_stage_mapper"] | |
| LABEL = {"synthesis_tool": "synthesis", "simulation_tool": "simulation", "graph_extractor": "graph extraction", | |
| "static_analyzer": "static analysis", "optimization_advisor": "optimization analysis", | |
| "cross_stage_mapper": "RTL-to-netlist mapping"} | |
| SYS = ("You write evaluation questions for a hardware-design assistant. You are given the outputs of " | |
| "several EDA analysis backends run on one Verilog module. Write ONE realistic question that a " | |
| "hardware engineer could ask about this module and that can only be answered by combining " | |
| "information from ALL of the given backend outputs (for example: relate or compare figures from " | |
| "different analyses, check one result against another, weigh a design decision using several " | |
| "results, or ask for a short multi-part summary). Then write the reference answer.\n" | |
| "Rules for the question: mention the module name exactly; sound natural; do not name tools or " | |
| "software functions (no 'synthesis_tool', 'static_analyzer', no 'backend', no 'tool output'); " | |
| "if a graph analysis is involved, state its graph type (CDFG, AIG or DFG); if an optimization " | |
| "analysis targets delay or power, say so.\n" | |
| "Rules for the answer: 1 to 3 sentences; name the module exactly; every number you write must be copied exactly from the " | |
| "outputs; use at least one specific value from EACH output; no numbers that are not in the outputs " | |
| "(no computed sums, ratios or percentages unless that exact number is in the outputs).\n" | |
| 'Return only JSON: {"question": "...", "answer": "..."}') | |
| GLM_URL = "https://api.z.ai/api/paas/v4/chat/completions" | |
| CWD = tempfile.mkdtemp(prefix="mtqa-") | |
| NUM = re.compile(r"(?<![A-Za-z_\d.])-?\d+(?:\.\d+)?(?![A-Za-z_\d])") | |
| def cap(s, n): | |
| if len(s) <= n: return s | |
| head = n // 3; tail = n - head | |
| return s[:head] + "\n...[" + str(len(s) - n) + " chars elided]...\n" + s[-tail:] | |
| def norm(x): | |
| try: | |
| f = float(x) | |
| except ValueError: | |
| return x | |
| return str(int(f)) if f == int(f) else repr(round(f, 6)) | |
| def nums(s): return {norm(m) for m in NUM.findall(s)} | |
| def blocks(plan, res): | |
| per = TOTAL_CAP // len(plan["calls"]) - 40 | |
| out = [] | |
| for c in plan["calls"]: | |
| r = res[c["key"]]["result"] | |
| out.append((c, f"[{c['tool']} {json.dumps(c['parameters'])}]\n" + cap(json.dumps(r, indent=2), per))) | |
| return out | |
| def ask_glm(model, user, timeout=180): | |
| payload = {"model": model, "temperature": 0.7, "max_tokens": 600, "thinking": {"type": "disabled"}, | |
| "messages": [{"role": "system", "content": SYS}, {"role": "user", "content": user}]} | |
| req = urllib.request.Request(GLM_URL, data=json.dumps(payload).encode(), | |
| headers={"Content-Type": "application/json", "Authorization": f"Bearer {os.environ['GLM_API_KEY']}"}) | |
| with urllib.request.urlopen(req, timeout=timeout) as f: | |
| return json.load(f)["choices"][0]["message"]["content"] | |
| def ask_cli(model, user, timeout=300): | |
| r = subprocess.run(["claude", "-p", "--system-prompt", SYS, "--restricted", "--output-format", "json", "--model", model], | |
| input=user, capture_output=True, text=True, timeout=timeout, cwd=CWD) | |
| if r.returncode != 0: raise RuntimeError((r.stderr or r.stdout)[:200]) | |
| d = json.loads(r.stdout) | |
| if d.get("is_error"): raise RuntimeError(str(d.get("result"))[:200]) | |
| return d.get("result") or "" | |
| def parse(t): | |
| if "```" in t: t = t.split("```")[1].removeprefix("json") | |
| i, j = t.find("{"), t.rfind("}") | |
| d = json.loads(t[i:j + 1]) | |
| return (d.get("question") or "").strip(), (d.get("answer") or "").strip() | |
| def check(plan, bl, q, a): | |
| mod = plan["module_name"] | |
| if mod not in q: return "module" | |
| if mod not in a: return "module_in_answer" # the slot metric requires the module name | |
| if not (20 <= len(q) <= 500) or not (20 <= len(a) <= 900): return "length" | |
| ql = q.lower() | |
| if any(f in ql for f in FUNCS) or "backend" in ql or "tool output" in ql: return "toolname" | |
| for c, _ in bl: | |
| p = c["parameters"] | |
| if c["tool"] == "graph_extractor" and p["graph_type"].lower() not in ql: return "graph_type" | |
| if c["tool"] == "optimization_advisor" and p["target_metric"] != "area": | |
| words = {"delay": ("delay", "timing", "speed", "critical path", "latency"), "power": ("power", "energy")} | |
| if not any(w in ql for w in words[p["target_metric"]]): return "target" | |
| ctx = "\n".join(b for _, b in bl) + "\n" + q | |
| an = nums(a) | |
| if an - nums(ctx): return "foreign_number" | |
| sets = [nums(b) for _, b in bl] | |
| for i, s in enumerate(sets): | |
| uniq = s - set().union(*[t for j, t in enumerate(sets) if j != i]) - nums(q) | |
| if uniq and not (an & uniq): return "missing_block" | |
| return None | |
| def main(): | |
| ap = argparse.ArgumentParser() | |
| ap.add_argument("--split", required=True); ap.add_argument("--out", required=True) | |
| ap.add_argument("--provider", choices=["glm", "claude-cli"], required=True); ap.add_argument("--model", required=True) | |
| ap.add_argument("--plans"); ap.add_argument("--results", default="splits/mt/results_full.jsonl") | |
| ap.add_argument("--designs", default="splits/mt/designs_full.jsonl") | |
| ap.add_argument("--concurrency", type=int, default=8); ap.add_argument("--limit", type=int) | |
| a = ap.parse_args() | |
| res = {} | |
| for l in open(a.results): | |
| r = json.loads(l); res[r["key"]] = r | |
| code = {} | |
| for l in open(a.designs): | |
| d = json.loads(l); code[d["design_id"]] = d["verilog_code"] | |
| plans = [json.loads(l) for l in open(a.plans or f"splits/mt/{a.split}.plan.jsonl")] | |
| plans = [p for p in plans if all(c["key"] in res and res[c["key"]]["result"].get("status") in OK for c in p["calls"])] | |
| done = set() | |
| if os.path.exists(a.out): | |
| for l in open(a.out): done.add(json.loads(l)["plan_id"]) | |
| todo = [p for p in plans if p["plan_id"] not in done][: a.limit] | |
| print(f"{len(plans)} usable plans, {len(done)} done, {len(todo)} to write with {a.provider}:{a.model}", flush=True) | |
| ask = (lambda u: ask_glm(a.model, u)) if a.provider == "glm" else (lambda u: ask_cli(a.model, u)) | |
| from collections import Counter | |
| why = Counter() | |
| def work(p): | |
| bl = blocks(p, res) | |
| user = (f"Module: {p['module_name']}\n\n" + "\n\n".join(b for _, b in bl)) | |
| last = "error" | |
| for _ in range(3): | |
| try: | |
| q, ans = parse(ask(user)) | |
| except Exception as e: | |
| last = "error"; time.sleep(2); continue | |
| last = check(p, bl, q, ans) | |
| if last is None and len(f"Question: {q}\n\n") + sum(len(b) for _, b in bl) + 2 * (len(bl) - 1) > CTX_CAP: | |
| last = "ctx_too_long" | |
| if last is None: | |
| tr = "\n\n".join(b for _, b in bl) | |
| calls = [{"tool": c["tool"], "parameters": c["parameters"]} for c in p["calls"]] | |
| return None, { | |
| "question": q, "answer": ans, "source_file": p["source_file"], "module_name": p["module_name"], | |
| "verilog_code": code[p["design_id"]][:3000], "tool_name": "+".join(c["tool"] for c in calls), | |
| "tool_parameters": [c["parameters"] for c in calls], "tool_result": tr, | |
| "category": "multi_tool", "subcategory": "+".join(c["tool"] for c in calls), | |
| "difficulty": "compositional", | |
| "question_hash": hashlib.sha256((p["plan_id"] + q).encode()).hexdigest()[:12], | |
| "stage1_target": json.dumps(calls), "stage2_context": f"Question: {q}\n\n{tr}", | |
| "plan_id": p["plan_id"], "design_id": p["design_id"], "split": a.split, | |
| "writer_model": a.model, "n_calls": len(calls), "ctx_cap": CTX_CAP} | |
| return last, None | |
| t0 = time.time(); n = 0 | |
| with ThreadPoolExecutor(a.concurrency) as ex, open(a.out, "a") as f: | |
| futs = [ex.submit(work, p) for p in todo] | |
| for fu in as_completed(futs): | |
| err, rec = fu.result(); n += 1 | |
| if rec: f.write(json.dumps(rec) + "\n"); f.flush(); why["ok"] += 1 | |
| else: why[err] += 1 | |
| if n % 50 == 0: print(f" {n}/{len(todo)} {dict(why)} {time.time()-t0:.0f}s", flush=True) | |
| print(json.dumps(dict(why)), flush=True) | |
| if __name__ == "__main__": | |
| main() | |