Download benchmark/run_benchmark_v1.py from muratkarahan/codev-qwen2.5-coder-7B: direct link, hf CLI and curl.
- Browser
- Download file 14.2 kB
-
https://huggingface.co/muratkarahan/codev-qwen2.5-coder-7B/resolve/main/benchmark/run_benchmark_v1.py
- Command line
-
hf download hf://muratkarahan/codev-qwen2.5-coder-7B/benchmark/run_benchmark_v1.py
-
curl -L -o run_benchmark_v1.py https://huggingface.co/muratkarahan/codev-qwen2.5-coder-7B/resolve/main/benchmark/run_benchmark_v1.py
14.2 kB
| #!/usr/bin/env python3 | |
| """ | |
| VerilogEval v1 Benchmark — Paper-uyumlu inference | |
| - VerilogEval v1 (143 Machine + 156 Human, JSONL format) | |
| - CodeV-Qwen icin: ### Instruction / ### Response prompt formati | |
| - Qwen base/instruct icin: chat template veya raw completion | |
| - Temperature sweep: {0.2, 0.5, 0.8} | |
| - n=20, top_p=0.95, max_tokens=2048 | |
| """ | |
| import json, subprocess, tempfile, argparse, re, torch | |
| from pathlib import Path | |
| from math import comb | |
| from tqdm import tqdm | |
| from datetime import datetime | |
| from transformers import AutoTokenizer, AutoModelForCausalLM | |
| VALID_MODELS = { | |
| "qwen-base": { | |
| "hf_id": "Qwen/Qwen2.5-Coder-7B", | |
| "mode": "completion", # base model -> raw completion | |
| }, | |
| "qwen-instruct": { | |
| "hf_id": "Qwen/Qwen2.5-Coder-7B-Instruct", | |
| "mode": "chat", # instruct model -> chat template | |
| }, | |
| "codev-qwen": { | |
| "hf_id": "muratkarahan/codev-qwen2.5-coder-7B", | |
| "mode": "instruction", # fine-tuned -> ### Instruction / ### Response | |
| }, | |
| } | |
| WORKSPACE = Path(__file__).parent.resolve() | |
| parser = argparse.ArgumentParser() | |
| parser.add_argument("--model", required=True, choices=list(VALID_MODELS.keys())) | |
| parser.add_argument("--benchmark", default="machine", choices=["machine", "human"]) | |
| parser.add_argument("--n_samples", type=int, default=20) | |
| parser.add_argument("--temperature", type=float, default=0.2) | |
| parser.add_argument("--max_tokens", type=int, default=2048) | |
| parser.add_argument("--subset", type=int, default=None) | |
| parser.add_argument("--output_dir", default=str(WORKSPACE / "results_v1")) | |
| parser.add_argument("--iverilog", default="iverilog") | |
| parser.add_argument("--vvp", default="vvp") | |
| args = parser.parse_args() | |
| MODEL_CFG = VALID_MODELS[args.model] | |
| HF_MODEL_ID = MODEL_CFG["hf_id"] | |
| INFERENCE_MODE = MODEL_CFG["mode"] | |
| SYSTEM = ( | |
| "Please act as a professional Verilog designer. " | |
| "Implement the described hardware module. " | |
| "Output only the complete Verilog module code, no explanation, no markdown." | |
| ) | |
| # ============================================================ | |
| # VerilogEval v1 JSONL loader | |
| # ============================================================ | |
| def load_problems_v1(benchmark: str) -> list: | |
| """VerilogEval v1 JSONL formatini yukler (143 Machine / 156 Human)""" | |
| dataset_dir = WORKSPACE / "verilog-eval-v1" / "data" | |
| if benchmark == "machine": | |
| jsonl_file = dataset_dir / "VerilogEval_Machine.jsonl" | |
| else: | |
| jsonl_file = dataset_dir / "VerilogEval_Human.jsonl" | |
| if not jsonl_file.exists(): | |
| raise FileNotFoundError(f"Dataset bulunamadi: {jsonl_file}") | |
| problems = [] | |
| with open(jsonl_file) as f: | |
| for line in f: | |
| if not line.strip(): | |
| continue | |
| item = json.loads(line) | |
| # v1 format: test icinde reference_module zaten gomulu | |
| # ref (canonical_solution) = sadece modul body'si | |
| # prompt = modul header (model body'yi tamamlamali) | |
| problems.append({ | |
| "task_id": item["task_id"], | |
| "prompt": item["prompt"], | |
| "test": item["test"], | |
| "ref": item.get("canonical_solution", ""), | |
| }) | |
| return problems | |
| # ============================================================ | |
| # Prompt building — model tipine gore | |
| # ============================================================ | |
| def build_prompt(tokenizer, user_prompt: str) -> str: | |
| if INFERENCE_MODE == "instruction": | |
| # CodeV-Qwen: egitildigi format | |
| return f"### Instruction:\n{user_prompt}\n\n### Response:\n" | |
| elif INFERENCE_MODE == "chat": | |
| # Qwen-Instruct: chat template | |
| messages = [ | |
| {"role": "system", "content": SYSTEM}, | |
| {"role": "user", "content": user_prompt}, | |
| ] | |
| try: | |
| return tokenizer.apply_chat_template( | |
| messages, tokenize=False, add_generation_prompt=True | |
| ) | |
| except Exception: | |
| return f"### System:\n{SYSTEM}\n\n### User:\n{user_prompt}\n\n### Assistant:\n" | |
| else: | |
| # Qwen-base: raw completion — prompt'u oldugu gibi ver | |
| return user_prompt | |
| # ============================================================ | |
| # Model loading | |
| # ============================================================ | |
| def load_model(): | |
| print(f"Loading model: {HF_MODEL_ID} (FP16, mode={INFERENCE_MODE})...") | |
| tokenizer = AutoTokenizer.from_pretrained(HF_MODEL_ID, trust_remote_code=True) | |
| model = AutoModelForCausalLM.from_pretrained( | |
| HF_MODEL_ID, | |
| torch_dtype=torch.float16, | |
| device_map="auto", | |
| trust_remote_code=True, | |
| ) | |
| model.eval() | |
| if tokenizer.pad_token is None: | |
| tokenizer.pad_token = tokenizer.eos_token | |
| print(f"Model loaded. Device: {model.device}") | |
| return tokenizer, model | |
| # ============================================================ | |
| # Generation | |
| # ============================================================ | |
| def generate_n(tokenizer, model, prompt: str, n: int) -> list: | |
| text = build_prompt(tokenizer, prompt) | |
| inputs = tokenizer(text, return_tensors="pt").to(model.device) | |
| input_len = inputs["input_ids"].shape[1] | |
| with torch.no_grad(): | |
| outputs = model.generate( | |
| **inputs, | |
| max_new_tokens=args.max_tokens, | |
| temperature=args.temperature, | |
| top_p=0.95, | |
| do_sample=True, | |
| num_return_sequences=n, | |
| pad_token_id=tokenizer.pad_token_id, | |
| ) | |
| results = [] | |
| for output in outputs: | |
| generated = output[input_len:] | |
| text_out = tokenizer.decode(generated, skip_special_tokens=True) | |
| results.append(text_out) | |
| return results | |
| # ============================================================ | |
| # Verilog extraction | |
| # ============================================================ | |
| def extract_verilog(raw: str, original_prompt: str) -> str: | |
| """ | |
| V1 format: prompt = modul header, model body uretir. | |
| - completion/base mode: model sadece body uretir -> prompt + output = tam modul | |
| - instruction/chat mode: model tam modul uretebilir -> extraction gerekir | |
| """ | |
| # Markdown code block varsa icinden cikar | |
| if "```verilog" in raw: | |
| s = raw.find("```verilog") + len("```verilog") | |
| e = raw.find("```", s) | |
| code = raw[s:e].strip() if e != -1 else raw[s:].strip() | |
| elif "```" in raw: | |
| s = raw.find("```") + 3 | |
| e = raw.find("```", s) | |
| code = raw[s:e].strip() if e != -1 else raw[s:].strip() | |
| else: | |
| code = raw.strip() | |
| # Model tam modul urettiyse (module ... endmodule iceriyorsa) oldugu gibi kullan | |
| if "module " in code and "endmodule" in code: | |
| return code | |
| # Model sadece body urettiyse, prompt (header) ile birlestir | |
| # endmodule yoksa ekle | |
| body = code | |
| if "endmodule" not in body: | |
| body = body + "\nendmodule" | |
| # Prompt zaten header iceriyor (module top_module(...);) | |
| full_code = original_prompt + body | |
| return full_code | |
| # ============================================================ | |
| # Functional check (iverilog + vvp) | |
| # ============================================================ | |
| def functional_check(code: str, testbench: str, ref_code: str, task_id: str) -> dict: | |
| with tempfile.TemporaryDirectory() as tmp: | |
| code_f = Path(tmp) / f"{task_id}.v" | |
| tb_f = Path(tmp) / f"{task_id}_tb.sv" | |
| out_f = Path(tmp) / f"{task_id}.out" | |
| code_f.write_text(code) | |
| tb_f.write_text(testbench) | |
| # v1: reference_module testbench icinde gomulu, ayri dosya gerekmez | |
| try: | |
| compile_r = subprocess.run( | |
| [args.iverilog, "-g2012", "-o", str(out_f), | |
| str(tb_f), str(code_f)], | |
| capture_output=True, timeout=30 | |
| ) | |
| except subprocess.TimeoutExpired: | |
| return {"syntax": False, "functional": False, "error": "compile timeout"} | |
| if compile_r.returncode != 0: | |
| return {"syntax": False, "functional": False, | |
| "error": compile_r.stderr.decode()[:300]} | |
| try: | |
| sim_r = subprocess.run( | |
| [args.vvp, str(out_f)], capture_output=True, timeout=30 | |
| ) | |
| except subprocess.TimeoutExpired: | |
| return {"syntax": True, "functional": False, "error": "simulation timeout"} | |
| stdout = sim_r.stdout.decode() | |
| passed = bool(re.search(r"Mismatches:\s*0\s+in\s+\d+\s+samples", stdout)) | |
| return {"syntax": True, "functional": passed, "error": None} | |
| # ============================================================ | |
| # pass@k | |
| # ============================================================ | |
| def pass_at_k(n: int, c: int, k: int) -> float: | |
| if n - c < k: | |
| return 1.0 | |
| return 1.0 - comb(n - c, k) / comb(n, k) | |
| # ============================================================ | |
| # Checkpoint | |
| # ============================================================ | |
| def get_checkpoint_path() -> Path: | |
| model_tag = args.model.replace(":", "-") | |
| temp_tag = f"t{args.temperature}".replace(".", "") | |
| return Path(args.output_dir) / f"{model_tag}_{args.benchmark}_{temp_tag}_checkpoint.json" | |
| def load_checkpoint(ckpt_path: Path) -> tuple: | |
| if ckpt_path.exists(): | |
| data = json.load(open(ckpt_path)) | |
| results = data.get("results", []) | |
| responses = data.get("responses", {}) | |
| print(f"[Checkpoint] {len(results)} tamamlanmis problem yuklendi") | |
| return results, responses | |
| return [], {} | |
| def save_checkpoint(ckpt_path: Path, results: list, responses: dict): | |
| ckpt_path.parent.mkdir(parents=True, exist_ok=True) | |
| json.dump({"results": results, "responses": responses}, | |
| open(ckpt_path, "w"), indent=2) | |
| # ============================================================ | |
| # Main | |
| # ============================================================ | |
| def main(): | |
| print(f"\n{'='*60}") | |
| print(f"Model : {args.model} ({HF_MODEL_ID})") | |
| print(f"Inference : {INFERENCE_MODE}") | |
| print(f"Precision : FP16") | |
| print(f"Benchmark : VerilogEval-v1-{args.benchmark.capitalize()}") | |
| print(f"n_samples : {args.n_samples}") | |
| print(f"temperature: {args.temperature}") | |
| print(f"max_tokens : {args.max_tokens}") | |
| print(f"{'='*60}\n") | |
| problems = load_problems_v1(args.benchmark) | |
| print(f"Loaded {len(problems)} problems\n") | |
| if args.subset: | |
| problems = problems[:args.subset] | |
| print(f"[Subset] Ilk {args.subset} problem\n") | |
| Path(args.output_dir).mkdir(parents=True, exist_ok=True) | |
| ckpt_path = get_checkpoint_path() | |
| all_results, all_responses = load_checkpoint(ckpt_path) | |
| completed_ids = {r["task_id"] for r in all_results} | |
| remaining = [p for p in problems if p["task_id"] not in completed_ids] | |
| if remaining: | |
| print(f"[Resume] {len(remaining)} problem kaldi ({len(completed_ids)} tamamlanmis)\n") | |
| tokenizer, model = load_model() | |
| for problem in tqdm(remaining, desc=f"{args.model} FP16"): | |
| task_id = problem["task_id"] | |
| testbench = problem["test"] | |
| ref_code = problem["ref"] | |
| generations = generate_n(tokenizer, model, problem["prompt"], args.n_samples) | |
| syntax_ok = 0 | |
| func_ok = 0 | |
| sample_details = [] | |
| for i, raw in enumerate(generations): | |
| extracted = extract_verilog(raw, problem["prompt"]) | |
| r = functional_check(extracted, testbench, ref_code, task_id) | |
| if r["syntax"]: | |
| syntax_ok += 1 | |
| if r["functional"]: | |
| func_ok += 1 | |
| sample_details.append({ | |
| "sample_id": i, | |
| "raw_response": raw, | |
| "extracted_verilog": extracted, | |
| "syntax": r["syntax"], | |
| "functional": r["functional"], | |
| "error": r["error"], | |
| }) | |
| n, c = args.n_samples, func_ok | |
| all_results.append({ | |
| "task_id": task_id, | |
| "n": n, | |
| "syntax_passes": syntax_ok, | |
| "func_passes": c, | |
| "syntax_rate": syntax_ok / n, | |
| "pass@1": pass_at_k(n, c, 1), | |
| "pass@5": pass_at_k(n, c, 5), | |
| "pass@10": pass_at_k(n, c, 10), | |
| }) | |
| all_responses[task_id] = sample_details | |
| save_checkpoint(ckpt_path, all_results, all_responses) | |
| total = len(all_results) | |
| avg_p1 = sum(r["pass@1"] for r in all_results) / total * 100 | |
| avg_p5 = sum(r["pass@5"] for r in all_results) / total * 100 | |
| avg_p10 = sum(r["pass@10"] for r in all_results) / total * 100 | |
| avg_syn = sum(r["syntax_rate"] for r in all_results) / total * 100 | |
| print(f"\n{'='*60}") | |
| print(f"SONUCLAR — {args.model} / VerilogEval-v1-{args.benchmark.capitalize()}") | |
| print(f"{'='*60}") | |
| print(f" pass@1 : {avg_p1:.1f}%") | |
| print(f" pass@5 : {avg_p5:.1f}%") | |
| print(f" pass@10 : {avg_p10:.1f}%") | |
| print(f" syntax : {avg_syn:.1f}%") | |
| print(f"{'='*60}") | |
| model_tag = args.model | |
| ts = datetime.now().strftime("%Y%m%d_%H%M%S") | |
| out_file = f"{args.output_dir}/{model_tag}_{args.benchmark}_t{args.temperature}_{ts}.json" | |
| json.dump({ | |
| "model": args.model, | |
| "hf_model_id": HF_MODEL_ID, | |
| "inference_mode": INFERENCE_MODE, | |
| "precision": "FP16", | |
| "benchmark": f"VerilogEval-v1-{args.benchmark}", | |
| "benchmark_version": "v1.0.0", | |
| "n_samples": args.n_samples, | |
| "temperature": args.temperature, | |
| "max_tokens": args.max_tokens, | |
| "timestamp": ts, | |
| "aggregate": { | |
| "pass@1": round(avg_p1, 2), | |
| "pass@5": round(avg_p5, 2), | |
| "pass@10": round(avg_p10, 2), | |
| "syntax": round(avg_syn, 2), | |
| }, | |
| "per_problem": all_results, | |
| }, open(out_file, "w"), indent=2) | |
| print(f"\nSonuclar: {out_file}") | |
| resp_file = f"{args.output_dir}/{model_tag}_{args.benchmark}_t{args.temperature}_{ts}_responses.json" | |
| json.dump(all_responses, open(resp_file, "w"), indent=2) | |
| print(f"Cevaplar: {resp_file}") | |
| if ckpt_path.exists(): | |
| ckpt_path.unlink() | |
| print(f"[Checkpoint temizlendi]") | |
| if __name__ == "__main__": | |
| main() | |