File size: 7,757 Bytes
676defa
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
#!/usr/bin/env python3
"""CircuitQA inference: base Qwen + LoRA adapter, fp/bf16, no quantization.

Three conditions:
  A         question + Verilog                      (identical to the baselines)
  B         + the record's own tool_result          (identical to the baselines)
  C-oracle  gold category and gold tool name in the system prompt, plus the
            tool output (oracle routing; the router is not used)
"""
import argparse, json, os, time, torch
from transformers import AutoModelForCausalLM, AutoTokenizer
from peft import PeftModel

BASE = "Qwen/Qwen2.5-Coder-7B-Instruct"
TOOL_CAP = 8000   # chars; structural_analysis JSON reaches 52k otherwise

SYS_A = "You are an expert Verilog design analyzer."
SYS_B = ("You are an expert Verilog design analyzer. Use the provided tool analysis "
         "results to answer accurately. Always use the EXACT values from the tool "
         "output - do not estimate or approximate.")

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()[:rec.get("prompt_code_chars", 3000)]

def build(rec, cond, vcap):
    v = design_source(rec)[:vcap]
    q = rec.get("question", "")
    tr = rec.get("tool_result", "")
    if not isinstance(tr, str):
        tr = json.dumps(tr, indent=2)
    if len(tr) > TOOL_CAP:
        # The summary block (node_count, edge_count, avg_degree, gate counts)
        # is emitted at the END of the tool JSON -- for graph_extractor it sits
        # past char 62000 of 62800. A head-only cap removes exactly the fields
        # the gold answers quote, so keep both ends.
        head = TOOL_CAP // 3
        tail = TOOL_CAP - head
        tr = (tr[:head] + "\n...[" + str(len(tr) - TOOL_CAP) +
              " chars elided]...\n" + tr[-tail:])
    if cond == "A":
        return SYS_A, f"Verilog Code:\n```verilog\n{v}\n```\n\nQuestion: {q}"
    if cond == "B":
        return SYS_B, (f"Verilog Code:\n```verilog\n{v}\n```\n\n"
                       f"Tool Analysis:\n{tr}\n\nQuestion: {q}")
    # C-oracle: reproduces training/comprehensive_inference_test.py verbatim
    cat = (rec.get("category") or "").replace("_", " ")
    tool = rec.get("tool_name", "")
    sys_p = (f"You are an expert Verilog design analyzer specializing in {cat}. "
             f"Use the provided tool analysis results to answer accurately. "
             f"Always use the EXACT values from the tool output - do not estimate "
             f"or approximate.")
    return sys_p, (f"Verilog Code:\n```verilog\n{v}\n```\n\n"
                   f"Tool Analysis ({tool}):\n{tr}\n\nQuestion: {q}")

def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--ref", required=True)
    ap.add_argument("--adapter", default="adapter")
    ap.add_argument("--condition", required=True, choices=["A", "B", "C-oracle"])
    ap.add_argument("--out", required=True)
    ap.add_argument("--limit", type=int)
    ap.add_argument("--batch", type=int, default=8)
    ap.add_argument("--threads", type=int, default=48)
    ap.add_argument("--max-new", type=int, default=256)
    ap.add_argument("--verilog-cap", type=int, default=2000)
    ap.add_argument("--max-len", type=int, default=6144,
                    help="prompt window; structural_analysis tool_result alone "
                         "reaches ~15k tokens")
    ap.add_argument("--gpu-gib", type=float, default=0,
                    help="cap GPU use at N GiB and offload the rest to CPU; "
                         "0 = pure CPU. A hard cap means THIS process OOMs "
                         "before it can starve anything else on the card.")
    ap.add_argument("--base-only", action="store_true",
                    help="skip the LoRA adapter: the untuned base-model row")
    a = ap.parse_args()

    torch.set_num_threads(a.threads)
    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:
                r = json.loads(l)
                if (r.get("prediction") or "").strip(): done.add(r["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 not recs: return

    dtype = torch.bfloat16   # training dtype; not quantization
    print(f"loading {BASE} dtype={dtype} threads={a.threads}", flush=True)
    tok = AutoTokenizer.from_pretrained(a.adapter if not a.base_only else BASE)
    if tok.pad_token is None: tok.pad_token = tok.eos_token
    tok.padding_side = "left"
    tok.truncation_side = "left"   # keep the question, drop the oldest context
    if a.gpu_gib > 0 and torch.cuda.is_available():
        total = torch.cuda.get_device_properties(0).total_memory / (1024**3)
        frac = min(0.95, a.gpu_gib / total)
        torch.cuda.set_per_process_memory_fraction(frac, 0)
        print(f"GPU cap {a.gpu_gib:.1f} GiB of {total:.1f} GiB "
              f"(fraction {frac:.3f}); surplus layers go to CPU", flush=True)
        # Weights must leave room for activations and the KV cache inside the
        # same cap, or the first forward pass OOMs against our own limit.
        wbudget = max(2.0, a.gpu_gib - 6.0)
        print(f"  weights<={wbudget:.0f}GiB on GPU, rest on CPU, "
              f"{a.gpu_gib-wbudget:.0f}GiB reserved for activations", flush=True)
        model = AutoModelForCausalLM.from_pretrained(
            BASE, dtype=dtype, device_map="auto",
            max_memory={0: f"{wbudget:.0f}GiB", "cpu": "80GiB"})
    else:
        model = AutoModelForCausalLM.from_pretrained(BASE, dtype=dtype, device_map="cpu")
    if not a.base_only:
        model = PeftModel.from_pretrained(model, a.adapter)
        print("LoRA adapter attached", flush=True)
    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 = []
        for r in chunk:
            s, u = build(r, a.condition, a.verilog_cap)
            prompts.append(tok.apply_chat_template(
                [{"role": "system", "content": s}, {"role": "user", "content": u}],
                tokenize=False, add_generation_prompt=True))
        enc = tok(prompts, return_tensors="pt", padding=True,
                  truncation=True, max_length=a.max_len)
        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"],
                                 "prediction": txt,
                                 "category": r.get("category")}) + "\n")
        fh.flush()
        d = i + len(chunk)
        el = time.time() - t0
        print(f"  {d}/{len(recs)}  {el:.0f}s  {el/max(1,d):.1f}s/sample "
              f"eta {(len(recs)-d)*el/max(1,d)/60:.0f}min", flush=True)
    fh.close()

if __name__ == "__main__":
    main()