Datasets:
Download code/qrm_eval.py from drawais/circuitqa: direct link, hf CLI and curl.
- Browser
- Download file 5.36 kB
-
https://huggingface.co/datasets/drawais/circuitqa/resolve/main/code/qrm_eval.py
- Command line
-
hf download hf://datasets/drawais/circuitqa/code/qrm_eval.py
-
curl -L -o qrm_eval.py https://huggingface.co/datasets/drawais/circuitqa/resolve/main/code/qrm_eval.py
5.36 kB
| #!/usr/bin/env python3 | |
| """Stage-1 routing evaluation: base Qwen + stage-1 LoRA adapter, bf16. | |
| Prompt is byte-identical to the stage1 branch of train_qwen_verilog.py. | |
| Writes {question_hash, gold_tool, pred_tool, raw} per record.""" | |
| import argparse, json, os, re, time, torch | |
| from transformers import AutoModelForCausalLM, AutoTokenizer | |
| from peft import PeftModel | |
| def design_source(rec): | |
| """Released records reference the design (`source`) instead of carrying it: read the file | |
| fetched by scripts/fetch_sources.py from $CIRCUITQA_SOURCES (default ./sources).""" | |
| if rec.get("verilog_code"): | |
| return rec["verilog_code"] | |
| path = os.path.join(os.environ.get("CIRCUITQA_SOURCES", "sources"), rec["source"]["sha256"] + ".v") | |
| if not os.path.exists(path): | |
| raise SystemExit(f"design source {path} not found: run scripts/fetch_sources.py first") | |
| return open(path, encoding="utf-8").read()[:3000] | |
| BASE = "Qwen/Qwen2.5-Coder-7B-Instruct" | |
| SYS = """You are an expert Verilog design analyzer. Given a question about Verilog code, determine which EDA tool to use and what parameters to pass. | |
| Available tools: | |
| - synthesis_tool: For PPA metrics (area, delay, power, gate count) | |
| - simulation_tool: For functional behavior, toggle rates, timing | |
| - graph_extractor: For structural analysis (CDFG, AIG, DFG extraction) | |
| - static_analyzer: For code quality, complexity, style analysis | |
| - optimization_advisor: For synthesis optimization recommendations | |
| - cross_stage_mapper: For RTL-to-netlist alignment analysis | |
| Output format: JSON with tool_name, parameters, and reasoning.""" | |
| TOOLS = ["synthesis_tool","simulation_tool","graph_extractor","static_analyzer", | |
| "optimization_advisor","cross_stage_mapper"] | |
| def parse(txt): | |
| try: | |
| j = json.loads(txt[txt.index("{"):txt.rindex("}")+1]) | |
| t = j.get("tool") or j.get("tool_name") | |
| if t in TOOLS: return t | |
| except Exception: pass | |
| for t in TOOLS: | |
| if t in txt: return t | |
| return "UNPARSED" | |
| ap = argparse.ArgumentParser() | |
| ap.add_argument("--ref", required=True); ap.add_argument("--adapter", required=True) | |
| ap.add_argument("--out", required=True); ap.add_argument("--batch", type=int, default=8) | |
| ap.add_argument("--max-new", type=int, default=64); ap.add_argument("--gpu-gib", type=float, default=19) | |
| ap.add_argument("--limit", type=int) | |
| a = ap.parse_args() | |
| recs = [json.loads(l) for l in open(a.ref) if l.strip()] | |
| if a.limit: recs = recs[:a.limit] | |
| done = set() | |
| if os.path.exists(a.out): | |
| for l in open(a.out): | |
| try: done.add(json.loads(l)["question_hash"]) | |
| except Exception: pass | |
| recs = [r for r in recs if r["question_hash"] not in done] | |
| print(f"{len(done)} already done, {len(recs)} to run", flush=True) | |
| if recs: | |
| tok = AutoTokenizer.from_pretrained(a.adapter) | |
| if tok.pad_token is None: tok.pad_token = tok.eos_token | |
| tok.padding_side = "left"; tok.truncation_side = "left" | |
| total = torch.cuda.get_device_properties(0).total_memory / (1024**3) | |
| torch.cuda.set_per_process_memory_fraction(min(0.95, a.gpu_gib/total), 0) | |
| wb = max(2.0, a.gpu_gib - 6.0) | |
| model = AutoModelForCausalLM.from_pretrained(BASE, dtype=torch.bfloat16, device_map="auto", | |
| max_memory={0: f"{wb:.0f}GiB", "cpu": "80GiB"}) | |
| model = PeftModel.from_pretrained(model, a.adapter); model.eval() | |
| fh = open(a.out, "a"); t0 = time.time() | |
| for i in range(0, len(recs), a.batch): | |
| chunk = recs[i:i+a.batch] | |
| prompts = [tok.apply_chat_template( | |
| [{"role":"system","content":SYS}, | |
| {"role":"user","content":f"Verilog Code:\n```verilog\n{design_source(r)[:2000]}\n```\n\nQuestion: {r['question']}"}], | |
| tokenize=False, add_generation_prompt=True) for r in chunk] | |
| enc = tok(prompts, return_tensors="pt", padding=True, truncation=True, max_length=2048) | |
| enc = {k: v.to(model.device) for k, v in enc.items()} | |
| with torch.no_grad(): | |
| out = model.generate(**enc, max_new_tokens=a.max_new, do_sample=False, | |
| temperature=None, top_p=None, pad_token_id=tok.pad_token_id) | |
| for r, o, n in zip(chunk, out.cpu(), enc["input_ids"].cpu()): | |
| txt = tok.decode(o[len(n):], skip_special_tokens=True).strip() | |
| fh.write(json.dumps({"question_hash": r["question_hash"], "category": r.get("category"), | |
| "gold_tool": r.get("tool_name"), "pred_tool": parse(txt), | |
| "raw": txt[:300]}) + "\n") | |
| fh.flush() | |
| d = i+len(chunk); el = time.time()-t0 | |
| if d % 80 == 0 or d == len(recs): | |
| print(f" {d}/{len(recs)} {el:.0f}s eta {(len(recs)-d)*el/max(1,d)/60:.0f}min", flush=True) | |
| fh.close() | |
| # summary | |
| rows = [json.loads(l) for l in open(a.out)] | |
| import collections | |
| by = collections.defaultdict(lambda: [0,0]); ok = 0 | |
| for r in rows: | |
| by[r["gold_tool"]][1] += 1 | |
| if r["pred_tool"] == r["gold_tool"]: by[r["gold_tool"]][0] += 1; ok += 1 | |
| print(f"ROUTING overall {ok}/{len(rows)} = {100*ok/len(rows):.1f}%") | |
| for t in TOOLS: | |
| k, n = by[t]; print(f" {t:22s} {k:5d}/{n:5d} = {100*k/max(1,n):5.1f}%") | |
| conf = collections.Counter((r["gold_tool"], r["pred_tool"]) for r in rows if r["pred_tool"] != r["gold_tool"]) | |
| for (g, p), c in conf.most_common(8): print(f" confuse {g} -> {p}: {c}") | |