Qwen3.5-9B-Weight-Space-Programming / scripts /evaluate_terminal_bench.py
jstarks's picture
Update WSP v3.0 qwen35_9b adapters/patches, 100-task & Terminal-Bench 2.0 results, and model card
5adb591 verified
Raw History Blame Contribute Delete
41.9 kB
"""20-Task Official Terminal-Bench Evaluation Across All 10 Models (Base vs. WSP). Evaluates all 5 GGUF + WSP v3.0 (9 Subspaces) models, both larger Sparse-MoE / 27B models via llama-server.exe, and all 3 PyTorch BF16 edge WSP models inside real WSL2 Ubuntu-24.04 sandboxes: - GGUF 9S (Q4_K_M, -c 16384): qwen35_2b, qwen35_4b, nemotron3_4b, qwen35_9b, gemma4_12b - Edge BF16 (PyTorch CUDA): qwen35_0_8b, gemma4_e2b, gemma4_e4b - Large GGUF (Q4_K_M): gemma4_26b_a4b (--cpu-moe), qwen38_27b (-ngl 46) Checkpoints results incrementally after each (model, mode) to `terminal_bench_results.json`. """ from __future__ import annotations import argparse import base64 import gc import json import re import subprocess import sys import time import urllib.request from pathlib import Path from typing import Any, Callable, Dict, List, Optional, Tuple PIPELINE_DIR = Path(r"C:\Users\jhjwi\.gemini\antigravity\scratch\wsp-5model-pipeline") QWEN08_DIR = Path(r"C:\Users\jhjwi\.gemini\antigravity\scratch\qwen35-iphone-agent") GEMMA_E2B_DIR = Path(r"C:\Users\jhjwi\.gemini\antigravity\scratch\gemma4-e2b-agent") GEMMA_E4B_DIR = Path(r"C:\Users\jhjwi\.gemini\antigravity\scratch\gemma4-weight-space") GEMMA_26B_DIR = Path(r"C:\Users\jhjwi\.gemini\antigravity\scratch\gemma4-26b-a4b-wsp") QWEN38_DIR = Path(r"C:\Users\jhjwi\.gemini\antigravity\scratch\qwen38-27b-wsp") RESULTS_PATH = PIPELINE_DIR / "terminal_bench_results.json" sys.path.insert(0, str(PIPELINE_DIR)) from dynamic_router_9s import DynamicSubspaceRouter9S # noqa: E402 from evaluate_all_models import ( # noqa: E402 LLAMA_SERVER_EXE, LlamaServerHandle, get_gpu_vram_mb, http_get_json, parse_tool_calls, ) from model_registry import MODEL_SPECS, ModelSpec # noqa: E402 from setup_terminal_bench_20 import ( # noqa: E402 WSL_DISTRO, grade_task_in_wsl, load_or_fetch_tasks, prepare_task_in_wsl, run_wsl_bash, ) import wsp_tasks_9subspaces as tasks # noqa: E402 sys.stdout.reconfigure(encoding="utf-8", line_buffering=True) TERMINAL_TOOLS = [tasks.WORKER_TOOLS[0]] # exec tool only MAX_TURNS = 5 CMD_TIMEOUT_S = 25 MAX_TOKENS_GGUF = 768 MAX_TOKENS_EDGE = 512 SYSTEM_PROMPT = ( "You are an autonomous Linux terminal agent working inside /app. " "Use the `exec` tool to run bash commands to inspect files, make changes, and verify your solution. " "Prefer combining inspection and solution steps into concise, self-contained bash commands. " "Once the task is completely solved and verified, reply with a brief summary without calling a tool." ) ALL_MODEL_ORDER = [ "qwen35_2b", "qwen35_4b", "nemotron3_4b", "qwen35_9b", "gemma4_12b", "qwen35_0_8b", "gemma4_e2b", "gemma4_e4b", "gemma4_26b_a4b", "qwen38_27b", ] def run_agent_cmd_in_wsl(cmd: str, cwd: str, timeout: int = CMD_TIMEOUT_S) -> Tuple[int, str, str]: """Run an agent shell command in WSL2 Ubuntu-24.04 while tracking persistent cwd.""" clean_cmd = (cmd or "").replace("\r\n", "\n") cmd_b64 = base64.b64encode(clean_cmd.encode("utf-8")).decode("ascii") wrapper = "\n".join([ "export PAGER=cat GIT_PAGER=cat TERM=dumb DEBIAN_FRONTEND=noninteractive", f"echo '{cmd_b64}' | base64 -d > /tmp/_tbench_cmd.sh", "_tbench_exit() {", " local rc=$?", " printf '\\n__TBENCH_PWD__:%s\\n' \"$(pwd)\"", " exit $rc", "}", "trap _tbench_exit EXIT", "source /tmp/_tbench_cmd.sh </dev/null", ]) rc, out, err = run_wsl_bash(wrapper, cwd=cwd, timeout=timeout) new_cwd = cwd kept_lines: List[str] = [] for line in out.splitlines(): if line.startswith("__TBENCH_PWD__:"): cand = line.split(":", 1)[1].strip() if cand: new_cwd = cand else: kept_lines.append(line) clean_out = "\n".join(kept_lines).strip() clean_err = (err or "").strip() combined = "\n".join(part for part in (clean_out, clean_err) if part).strip() if len(combined) > 2000: combined = combined[:2000] + "\n...[truncated]" if not combined: combined = "(no output)" formatted = f"[exit_code={rc}] [cwd={new_cwd}]\n{combined}" return rc, formatted, new_cwd def _extract_exec_cmd(tc: Dict[str, Any]) -> str: args = tc.get("arguments") or {} if isinstance(args, str): try: args = json.loads(args) except Exception: return "" if not isinstance(args, dict): return "" for key in ("command", "cmd", "script"): val = args.get(key) if isinstance(val, str) and val.strip(): return val return "" def _summarize_records(mode: str, display_name: str, extra: Dict[str, Any], records: List[Dict[str, Any]]) -> Dict[str, Any]: total = len(records) passed = sum(1 for r in records if r["passed"]) def _diff_stats(diff: str) -> Tuple[int, int]: sub = [r for r in records if r.get("difficulty") == diff] return sum(1 for r in sub if r["passed"]), len(sub) easy_p, easy_t = _diff_stats("easy") med_p, med_t = _diff_stats("medium") hard_p, hard_t = _diff_stats("hard") tps_vals = [r["tps"] for r in records if r["tps"] > 0] return { "mode": mode, "display_name": display_name, **extra, "pass": passed, "total": total, "pct": round(100.0 * passed / max(total, 1), 1), "easy_pass": easy_p, "easy_total": easy_t, "medium_pass": med_p, "medium_total": med_t, "hard_pass": hard_p, "hard_total": hard_t, "avg_turns": round(sum(r["turns_used"] for r in records) / max(total, 1), 2), "avg_cmds": round(sum(r["cmds_executed"] for r in records) / max(total, 1), 2), "avg_comp_tok": round(sum(r["comp_tok"] for r in records) / max(total, 1), 1), "avg_ms": round(sum(r["infer_ms"] for r in records) / max(total, 1), 1), "mean_tps": round(sum(tps_vals) / max(len(tps_vals), 1), 1) if tps_vals else 0.0, "total_eval_s": round(sum(r["infer_ms"] for r in records) / 1000.0, 2), "records": records, } def run_terminal_episode( task_row: Dict[str, Any], infer_fn: Callable[[List[Dict[str, Any]]], Dict[str, Any]], openai_tool_history: bool, max_turns: int = MAX_TURNS, tool_args_as_dict: bool = False, ) -> Dict[str, Any]: """Run one stateful multi-turn Terminal-Bench episode and grade via official pytest.""" workdir, info = prepare_task_in_wsl(task_row) cwd = workdir messages: List[Dict[str, Any]] = [ {"role": "system", "content": SYSTEM_PROMPT}, {"role": "user", "content": info["instruction"]}, ] total_tok = 0 total_ms = 0.0 turns_used = 0 cmds_executed = 0 regimes_trace: List[str] = [] turn1_regime = "static_wsp" turn1_scales: List[float] = [] cmd_history: List[str] = [] for turn in range(1, max_turns + 1): turns_used = turn try: step = infer_fn(messages) except Exception as exc: print(f" [WARN] Turn {turn} inference error on {info['task_id']}: {exc}", flush=True) break total_tok += int(step.get("comp_tok") or 0) total_ms += float(step.get("infer_ms") or 0.0) if step.get("regime"): regimes_trace.append(step["regime"]) if turn == 1: turn1_regime = step.get("regime") or "static_wsp" turn1_scales = list(step.get("scales") or []) tcs = step.get("parsed_tool_calls") or [] exec_calls = [tc for tc in tcs if tc.get("name") == "exec"] if not exec_calls: break if openai_tool_history: raw_tcs = step.get("raw_tool_calls") or [] tc_payload = [ { "id": (raw_tcs[i].get("id") if i < len(raw_tcs) and isinstance(raw_tcs[i], dict) else None) or f"call_t{turn}_{i}", "type": "function", "function": { "name": "exec", "arguments": ( {"command": _extract_exec_cmd(tc)} if tool_args_as_dict else json.dumps({"command": _extract_exec_cmd(tc)}) ), }, } for i, tc in enumerate(exec_calls) ] tc_ids = [x["id"] for x in tc_payload] messages.append({"role": "assistant", "content": "", "tool_calls": tc_payload}) for idx_c, tc in enumerate(exec_calls): cmd_str = _extract_exec_cmd(tc) if not cmd_str.strip(): tool_out = ( f"[exit_code=2] [cwd={cwd}]\n" "Error: tool call arguments were truncated at max_tokens. " "Emit a shorter, self-contained bash command." ) else: cmds_executed += 1 cmd_history.append(cmd_str[:120]) _, tool_out, cwd = run_agent_cmd_in_wsl(cmd_str, cwd=cwd, timeout=CMD_TIMEOUT_S) tool_msg: Dict[str, Any] = { "role": "tool", "tool_call_id": tc_ids[idx_c] if idx_c < len(tc_ids) else f"call_t{turn}_{idx_c}", "content": tool_out, } if tool_args_as_dict: tool_msg["name"] = "exec" messages.append(tool_msg) else: messages.append({"role": "assistant", "content": step.get("raw_text") or ""}) for tc in exec_calls: cmd_str = _extract_exec_cmd(tc) if not cmd_str.strip(): tool_out = ( f"[exit_code=2] [cwd={cwd}]\n" "Error: tool call arguments were truncated at max_tokens. " "Emit a shorter, self-contained bash command." ) else: cmds_executed += 1 cmd_history.append(cmd_str[:120]) _, tool_out, cwd = run_agent_cmd_in_wsl(cmd_str, cwd=cwd, timeout=CMD_TIMEOUT_S) messages.append({"role": "tool", "name": "exec", "content": tool_out}) passed, pytest_summary = grade_task_in_wsl(info["task_id"], workdir) tps = round(total_tok / max(total_ms / 1000.0, 1e-4), 1) if total_tok > 0 else 0.0 return { "id": info["task_id"], "difficulty": info["difficulty"], "category": info["category"], "passed": bool(passed), "turns_used": turns_used, "cmds_executed": cmds_executed, "comp_tok": total_tok, "infer_ms": round(total_ms, 1), "tps": tps, "regime": turn1_regime, "scales": turn1_scales, "regimes_trace": regimes_trace, "cmd_preview": cmd_history, "pytest_summary": pytest_summary[-400:] if pytest_summary else "", } def evaluate_gguf_mode( spec: ModelSpec, router: DynamicSubspaceRouter9S, server: LlamaServerHandle, mode: str, tbench_tasks: List[Dict[str, Any]], ) -> Dict[str, Any]: n_slots = 11 if router.has_tbench_subspaces else 9 force_scales = [0.0] * n_slots if mode == "base" else None router.last_scales = None router.last_regime = None def infer_fn(msgs: List[Dict[str, Any]]) -> Dict[str, Any]: res = router.chat_completion( server.base_url, msgs, tools=TERMINAL_TOOLS, max_tokens=MAX_TOKENS_GGUF, temperature=0.0, force_scales=force_scales, ) server.sample_peak_vram() parsed = parse_tool_calls(res) return { "comp_tok": int((res.get("usage") or {}).get("completion_tokens") or 0), "infer_ms": float(res.get("infer_ms") or 0.0), "regime": res["decision"].regime, "scales": res["scales_used"], "raw_tool_calls": res.get("tool_calls") or [], "parsed_tool_calls": parsed, "raw_text": res.get("content") or "", } records: List[Dict[str, Any]] = [] for idx, row in enumerate(tbench_tasks, 1): rec = run_terminal_episode(row, infer_fn=infer_fn, openai_tool_history=True) records.append(rec) tag = "PASS" if rec["passed"] else "FAIL" print( f" [{idx:2d}/20] {tag} | {rec['id']:43s} | turns={rec['turns_used']} cmds={rec['cmds_executed']} " f"| tok={rec['comp_tok']:4d} | {rec['infer_ms']/1000.0:5.1f}s | {rec['regime']}", flush=True, ) return _summarize_records( mode=mode, display_name=spec.display_name, extra={"backend": "llama_server_q4km", "vram_c16384": dict(server.vram_info)}, records=records, ) def _apply_hf_template_with_fallback( tokenizer, messages: List[Dict[str, Any]], tools: List[Dict[str, Any]], extra_kwargs: Dict[str, Any], ) -> str: """Format multi-turn messages with role='tool', falling back to user messages if template fails.""" try: return tokenizer.apply_chat_template( messages, tools=tools, tokenize=False, add_generation_prompt=True, **extra_kwargs, ) except Exception: converted: List[Dict[str, Any]] = [] for m in messages: if m.get("role") == "tool": converted.append({"role": "user", "content": f"Tool output (`{m.get('name', 'exec')}`):\n{m.get('content', '')}"}) else: converted.append({"role": m.get("role", "user"), "content": m.get("content", "")}) return tokenizer.apply_chat_template( converted, tools=tools, tokenize=False, add_generation_prompt=True, **extra_kwargs, ) def _generate_hf_turn( model, tokenizer, messages: List[Dict[str, Any]], tools: List[Dict[str, Any]], extra_kwargs: Dict[str, Any], stop_strings: List[str], max_new_tokens: int = MAX_TOKENS_EDGE, eos_token_ids: Optional[List[int]] = None, ) -> Tuple[str, int, float]: import torch prompt = _apply_hf_template_with_fallback(tokenizer, messages, tools, extra_kwargs) inputs = tokenizer(prompt, return_tensors="pt").to(model.device) in_len = inputs["input_ids"].shape[1] gen_kwargs: Dict[str, Any] = { "max_new_tokens": max_new_tokens, "do_sample": False, "pad_token_id": tokenizer.eos_token_id, } if eos_token_ids is not None: gen_kwargs["eos_token_id"] = eos_token_ids t0 = time.perf_counter() with torch.no_grad(): out = model.generate(**inputs, **gen_kwargs) infer_ms = (time.perf_counter() - t0) * 1000.0 gen_ids = out[0][in_len:] raw_text = tokenizer.decode(gen_ids, skip_special_tokens=False) clean_text = raw_text for tok in stop_strings: clean_text = clean_text.replace(tok, "") clean_text = clean_text.strip() return clean_text, int(gen_ids.shape[0]), infer_ms class _WslKeepalive: """Keep the WSL2 Ubuntu-24.04 distro awake so systemd-tmpfiles doesn't wipe state mid-episode.""" def __init__(self) -> None: self.proc: Optional[subprocess.Popen] = None def __enter__(self) -> "_WslKeepalive": self.proc = subprocess.Popen( ["wsl", "-d", WSL_DISTRO, "-u", "root", "--", "sleep", "infinity"], stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, ) run_wsl_bash("true", cwd="/root", timeout=30) return self def __exit__(self, exc_type, exc_val, exc_tb) -> None: if self.proc is not None and self.proc.poll() is None: self.proc.terminate() try: self.proc.wait(timeout=5) except subprocess.TimeoutExpired: self.proc.kill() def _is_run_complete(model_entry: Dict[str, Any], mode: str, n_tasks: int, force: bool = False) -> bool: if force: return False run_entry = model_entry.get("runs", {}).get(mode, {}) records = run_entry.get("records", []) if len(records) != n_tasks: return False for rec in records: if "file or directory not found:" in (rec.get("pytest_summary") or ""): return False return True def evaluate_edge_model( slug: str, modes_to_run: List[str], tbench_tasks: List[Dict[str, Any]], model_entry: Dict[str, Any], checkpoint_cb: Callable[[], None], force: bool = False, ) -> None: """Evaluate qwen35_0_8b, gemma4_e2b, or gemma4_e4b in PyTorch BF16 on CUDA.""" import torch need_modes = [m for m in ("base", "wsp") if m in modes_to_run and not _is_run_complete(model_entry, m, len(tbench_tasks), force=force)] if not need_modes: print(f" [Skip] All requested clean modes already recorded for {slug}.", flush=True) return eos_token_ids: Optional[List[int]] = None openai_tool_history = False tool_args_as_dict = False if slug == "qwen35_0_8b": sys.path.insert(0, str(QWEN08_DIR)) from qwen35_loader import apply_mit_exp8_edit, load_qwen35 # noqa: E402 from qwen35_surgeon import apply_stage2_iphone_agent_edit # noqa: E402 display_name = "Qwen/Qwen3.5-0.8B" model, tokenizer = load_qwen35("cuda") extra_kwargs = {"enable_thinking": True} eos_token_ids = [248046, 248044] stop_strings = ["<|im_end|>", "<|endoftext|>"] fallback_parser = None elif slug == "gemma4_e2b": sys.path.insert(0, str(GEMMA_E2B_DIR)) sys.path.insert(0, str(QWEN08_DIR)) from benchmark_gemma4_e2b import parse_gemma4_tool_call # noqa: E402 from gemma4_e2b_loader import load_gemma4_e2b_text # noqa: E402 from gemma4_e2b_surgeon import apply_gemma4_e2b_wsp_edit # noqa: E402 display_name = "google/gemma-4-E2B-it" model, tokenizer = load_gemma4_e2b_text() extra_kwargs = {} stop_strings = ["<turn|>", "<end_of_turn>", "<eos>"] eos_token_ids = [1, 106, 49] openai_tool_history = True tool_args_as_dict = True fallback_parser = parse_gemma4_tool_call elif slug == "gemma4_e4b": sys.path.insert(0, str(GEMMA_E4B_DIR)) from apply_patch import apply_gemma4_weight_space_patch # noqa: E402 from model_loader import load_gemma4_e4b_text, parse_gemma4_tool_call # noqa: E402 display_name = "google/gemma-4-E4B-it" model, tokenizer = load_gemma4_e4b_text() extra_kwargs = {"enable_thinking": True} stop_strings = ["<turn|>", "<end_of_turn>", "<eos>"] eos_token_ids = [1, 106, 49] openai_tool_history = True tool_args_as_dict = True fallback_parser = parse_gemma4_tool_call else: raise ValueError(f"Unsupported edge slug: {slug}") model_entry["display_name"] = display_name vram_mb = round(torch.cuda.memory_allocated() / (1024 ** 2), 1) model_entry["vram_bf16_allocated_mb"] = vram_mb edge_adapter_path = PIPELINE_DIR / "models" / slug / "edge_tbench_adapters.safetensors" edge_router = None if edge_adapter_path.exists(): from edge_wsp_router import EdgeDynamicSubspaceRouter # noqa: E402 edge_router = EdgeDynamicSubspaceRouter(slug, model) wsp_applied = False try: for mode in ("base", "wsp"): if mode not in modes_to_run: continue existing = model_entry.get("runs", {}).get(mode, {}) if _is_run_complete(model_entry, mode, len(tbench_tasks), force=force): print(f" [Skip] {slug} mode={mode} already complete ({existing['pass']}/{existing['total']})", flush=True) continue if edge_router is not None: if mode == "base": edge_router.restore_base() elif mode == "wsp" and not wsp_applied: if slug == "qwen35_0_8b": apply_mit_exp8_edit(model) apply_stage2_iphone_agent_edit(model, tokenizer) elif slug == "gemma4_e2b": apply_gemma4_e2b_wsp_edit(model, tokenizer) else: apply_gemma4_weight_space_patch( model, str(GEMMA_E4B_DIR / "dist" / "gemma4_e4b_weight_space_patch.safetensors"), ) wsp_applied = True def infer_fn(msgs: List[Dict[str, Any]]) -> Dict[str, Any]: if edge_router is not None and mode == "wsp": regime, scales = edge_router.route(msgs, TERMINAL_TOOLS) edge_router.set_scales(scales) else: regime = "static_wsp" if mode == "wsp" else "base" scales = [0.0, 0.0, 0.0, 0.0] if edge_router is not None else [] clean_text, tok_cnt, infer_ms = _generate_hf_turn( model=model, tokenizer=tokenizer, messages=msgs, tools=TERMINAL_TOOLS, extra_kwargs=extra_kwargs, stop_strings=stop_strings, max_new_tokens=MAX_TOKENS_EDGE, eos_token_ids=eos_token_ids, ) parsed = parse_tool_calls({"content": clean_text, "reasoning": ""}) if not parsed and fallback_parser is not None: tc_fb = fallback_parser(clean_text) if tc_fb is not None: parsed = [{"name": tc_fb["name"], "arguments": tc_fb.get("arguments") or {}}] return { "comp_tok": tok_cnt, "infer_ms": infer_ms, "regime": regime, "scales": scales, "raw_tool_calls": [], "parsed_tool_calls": parsed, "raw_text": clean_text, } print(f" Running {slug} mode={mode} (PyTorch BF16, max_new_tokens={MAX_TOKENS_EDGE})...", flush=True) t0 = time.time() records: List[Dict[str, Any]] = [] for idx, row in enumerate(tbench_tasks, 1): rec = run_terminal_episode( row, infer_fn=infer_fn, openai_tool_history=openai_tool_history, tool_args_as_dict=tool_args_as_dict, ) records.append(rec) tag = "PASS" if rec["passed"] else "FAIL" print( f" [{idx:2d}/20] {tag} | {rec['id']:43s} | turns={rec['turns_used']} cmds={rec['cmds_executed']} " f"| tok={rec['comp_tok']:4d} | {rec['infer_ms']/1000.0:5.1f}s", flush=True, ) run_res = _summarize_records( mode=mode, display_name=display_name, extra={"backend": "pytorch_bf16", "vram_bf16_allocated_mb": vram_mb}, records=records, ) model_entry.setdefault("runs", {})[mode] = run_res print( f" [{mode.upper()}] {run_res['pass']}/{run_res['total']} ({run_res['pct']}%) " f"| easy={run_res['easy_pass']}/{run_res['easy_total']} " f"med={run_res['medium_pass']}/{run_res['medium_total']} " f"hard={run_res['hard_pass']}/{run_res['hard_total']} " f"| tok={run_res['avg_comp_tok']} | {run_res['mean_tps']} tok/s | {round(time.time() - t0, 1)}s", flush=True, ) checkpoint_cb() finally: del model, tokenizer gc.collect() torch.cuda.empty_cache() def _post_json(url: str, payload: Any, timeout: float = 180.0) -> Any: """Send a JSON POST request and decode the JSON response.""" req = urllib.request.Request( url, data=json.dumps(payload).encode("utf-8"), headers={"Content-Type": "application/json"}, method="POST", ) with urllib.request.urlopen(req, timeout=timeout) as resp: return json.loads(resp.read().decode("utf-8")) class _CustomLlamaServerHandle: """Managed llama-server subprocess for non-9S models (e.g., 26B MoE, 27B hybrid).""" def __init__( self, slug: str, gguf_path: Path, lora_paths: List[Path], work_dir: Path, port: int, ctx_size: int, extra_args: List[str], ): self.slug = slug self.gguf_path = gguf_path self.lora_paths = lora_paths self.work_dir = work_dir self.port = port self.ctx_size = ctx_size self.extra_args = extra_args self.proc: Optional[subprocess.Popen] = None self.log_fp = None self.base_url = f"http://127.0.0.1:{port}" self.vram_info: Dict[str, Any] = {} def __enter__(self) -> "_CustomLlamaServerHandle": if not self.gguf_path.exists(): raise FileNotFoundError(f"Missing GGUF for {self.slug}: {self.gguf_path}") for lp in self.lora_paths: if not lp.exists(): raise FileNotFoundError(f"Missing LoRA adapter for {self.slug}: {lp}") tot0, used0, free0 = get_gpu_vram_mb() log_path = self.work_dir / f"llama_tbench_{self.slug}_p{self.port}_c{self.ctx_size}.log" self.log_fp = open(log_path, "w", encoding="utf-8", errors="replace") cmd = [ str(LLAMA_SERVER_EXE), "-m", str(self.gguf_path), "--host", "127.0.0.1", "--port", str(self.port), "-np", "1", "-c", str(self.ctx_size), "-ctk", "q8_0", "-ctv", "q8_0", "-b", "512", "-ub", "256", "--jinja", *self.extra_args, ] if self.lora_paths: cmd.append("--lora-init-without-apply") for lp in self.lora_paths: cmd += ["--lora", str(lp)] t0 = time.time() self.proc = subprocess.Popen( cmd, stdin=subprocess.DEVNULL, stdout=self.log_fp, stderr=subprocess.STDOUT, ) deadline = time.time() + 180.0 ready = False last_err = "" while time.time() < deadline: if self.proc.poll() is not None: self.log_fp.flush() tail = log_path.read_text(encoding="utf-8", errors="replace")[-1500:] raise RuntimeError(f"llama-server exited early (code={self.proc.returncode}) for {self.slug}:\n{tail}") try: h = http_get_json(f"{self.base_url}/health", timeout=3.0) if h.get("status") == "ok": ready = True break except Exception as e: last_err = str(e) time.sleep(0.5) if not ready: self.log_fp.flush() tail = log_path.read_text(encoding="utf-8", errors="replace")[-1500:] raise TimeoutError(f"llama-server health timeout for {self.slug}: {last_err}\n{tail}") loaded_loras = http_get_json(f"{self.base_url}/lora-adapters", timeout=10.0) if self.lora_paths else [] if len(loaded_loras) != len(self.lora_paths): raise RuntimeError(f"Expected {len(self.lora_paths)} LoRAs on {self.slug}, got {len(loaded_loras)}") tot1, used1, free1 = get_gpu_vram_mb() self.vram_info = { "ctx_size": self.ctx_size, "gpu_total_mb": tot1, "baseline_used_mb": used0, "baseline_free_mb": free0, "loaded_used_mb": used1, "loaded_free_mb": free1, "delta_load_mb": max(used1 - used0, free0 - free1), "peak_used_mb": used1, "peak_delta_mb": max(used1 - used0, free0 - free1), "startup_s": round(time.time() - t0, 2), "lora_count": len(loaded_loras), } return self def sample_peak_vram(self) -> None: _, used, _ = get_gpu_vram_mb() if used > self.vram_info["peak_used_mb"]: self.vram_info["peak_used_mb"] = used self.vram_info["peak_delta_mb"] = max( used - self.vram_info["baseline_used_mb"], self.vram_info["peak_delta_mb"], ) def __exit__(self, exc_type, exc_val, exc_tb) -> None: if self.proc is not None and self.proc.poll() is None: self.proc.terminate() try: self.proc.wait(timeout=15) except subprocess.TimeoutExpired: self.proc.kill() if self.log_fp is not None: self.log_fp.close() def _parse_gemma4_moe_fallback(text: str) -> List[Dict[str, Any]]: """Parse Gemma 4 native `<|tool_call>call:NAME{...}<tool_call|>` blocks as a fallback.""" after_thought = text.split("<channel|>")[-1] if "<channel|>" in text else text m = re.search(r"<\|tool_call>call:([a-zA-Z0-9_.-]+)\{(.*?)\}(?:<tool_call\|>)?", after_thought, flags=re.DOTALL) if not m: return [] func_name = m.group(1).strip() body = m.group(2).strip() args: Dict[str, Any] = {} for pair in re.finditer( r'([a-zA-Z0-9_-]+)\s*:\s*(?:<\|"\|>(.*?)<\|"\|>|"([^"]*)"|\'([^\']*)\'|([^,}]+))', body, flags=re.DOTALL, ): k = pair.group(1).strip() v = next((pair.group(i) for i in (2, 3, 4, 5) if pair.group(i) is not None), None) if v is not None: args[k] = v.strip() return [{"name": func_name, "arguments": args}] def evaluate_custom_gguf_model( slug: str, modes_to_run: List[str], tbench_tasks: List[Dict[str, Any]], model_entry: Dict[str, Any], port: int, ctx_size: int, checkpoint_cb: Callable[[], None], force: bool = False, ) -> None: """Evaluate gemma4_26b_a4b or qwen38_27b via llama-server.exe with LoRA hot-swap.""" if slug == "gemma4_26b_a4b": display_name = "google/gemma-4-26B-A4B-it" work_dir = GEMMA_26B_DIR gguf_path = work_dir / "gguf" / "gemma-4-26B-A4B-it-UD-Q4_K_M.gguf" lora_paths = [work_dir / "wsp_gemma4_subspace4_mid.gguf"] extra_args = ["--cpu-moe", "-ngl", "99"] backend_tag = "llama_server_q4km_cpumoe" server_ctx = ctx_size model_alias = "gemma4" def route_fn(msgs: List[Dict[str, Any]], mode: str) -> Tuple[str, List[float]]: if mode == "base": return "base", [0.0] return "arm3_mid_s4_2.0", [2.0] elif slug == "qwen38_27b": sys.path.insert(0, str(QWEN38_DIR)) from run_4way_ablation import dynamic_route_scales # noqa: E402 display_name = "Qwen/Qwen3.8-27B" work_dir = QWEN38_DIR gguf_path = work_dir / "gguf" / "Qwen3.8-27B-UD-Q4_K_M.gguf" lora_paths = [ work_dir / "wsp_subspace1_think.gguf", work_dir / "wsp_subspace2_restraint.gguf", work_dir / "wsp_subspace3_bash.gguf", work_dir / "wsp_subspace4_mid.gguf", ] extra_args = ["-ngl", "46"] backend_tag = "llama_server_q4km_partial_offload" server_ctx = min(ctx_size, 8192) model_alias = "qwen" def route_fn(msgs: List[Dict[str, Any]], mode: str) -> Tuple[str, List[float]]: if mode == "base": return "base", [0.0, 0.0, 0.0, 0.0] first_user = next((m.get("content") or "" for m in msgs if m.get("role") == "user"), "") s1, s2, s3 = dynamic_route_scales(first_user, TERMINAL_TOOLS) s4_mid = 0.85 if s1 > 0: s1 = round(s1 * 0.82, 2) return "both_s4_0.85_dynamic", [float(s1), float(s2), float(s3), s4_mid] else: raise ValueError(f"Unsupported custom GGUF slug: {slug}") model_entry["display_name"] = display_name need_modes = [ m for m in modes_to_run if not _is_run_complete(model_entry, m, len(tbench_tasks), force=force) ] if not need_modes: print(f" [Skip] All requested modes already recorded for {slug}.", flush=True) return with _CustomLlamaServerHandle( slug=slug, gguf_path=gguf_path, lora_paths=lora_paths, work_dir=work_dir, port=port, ctx_size=server_ctx, extra_args=extra_args, ) as srv: for mode in need_modes: print(f" Running {slug} mode={mode} (-c {server_ctx}, max_tokens={MAX_TOKENS_GGUF})...", flush=True) t0 = time.time() def infer_fn(msgs: List[Dict[str, Any]], _mode: str = mode) -> Dict[str, Any]: regime, scales = route_fn(msgs, _mode) _post_json( f"{srv.base_url}/lora-adapters", [{"id": i, "scale": float(s)} for i, s in enumerate(scales)], timeout=10.0, ) req_body = { "model": model_alias, "messages": msgs, "tools": TERMINAL_TOOLS, "max_tokens": MAX_TOKENS_GGUF, "temperature": 0.0, "cache_prompt": False, } t_req = time.perf_counter() res = _post_json(f"{srv.base_url}/v1/chat/completions", req_body, timeout=240.0) infer_ms = (time.perf_counter() - t_req) * 1000.0 srv.sample_peak_vram() choice = res["choices"][0] msg = choice["message"] usage = res.get("usage") or {} timings = res.get("timings") or {} content = msg.get("content") or "" reasoning = msg.get("reasoning_content") or "" raw_tcs = msg.get("tool_calls") or [] parsed = parse_tool_calls({"content": content, "reasoning": reasoning, "tool_calls": raw_tcs}) if not parsed and slug == "gemma4_26b_a4b": parsed = _parse_gemma4_moe_fallback(content) or _parse_gemma4_moe_fallback(reasoning + "\n" + content) timings_ms = timings.get("predicted_ms") return { "comp_tok": int(usage.get("completion_tokens") or 0), "infer_ms": float(timings_ms) if timings_ms else infer_ms, "regime": regime, "scales": scales, "raw_tool_calls": raw_tcs, "parsed_tool_calls": parsed, "raw_text": content, } records: List[Dict[str, Any]] = [] for idx, row in enumerate(tbench_tasks, 1): rec = run_terminal_episode(row, infer_fn=infer_fn, openai_tool_history=True) records.append(rec) tag = "PASS" if rec["passed"] else "FAIL" print( f" [{idx:2d}/20] {tag} | {rec['id']:43s} | turns={rec['turns_used']} cmds={rec['cmds_executed']} " f"| tok={rec['comp_tok']:4d} | {rec['infer_ms']/1000.0:5.1f}s | {rec['regime']}", flush=True, ) run_res = _summarize_records( mode=mode, display_name=display_name, extra={"backend": backend_tag, f"vram_c{server_ctx}": dict(srv.vram_info)}, records=records, ) model_entry.setdefault("runs", {})[mode] = run_res print( f" [{mode.upper()}] {run_res['pass']}/{run_res['total']} ({run_res['pct']}%) " f"| easy={run_res['easy_pass']}/{run_res['easy_total']} " f"med={run_res['medium_pass']}/{run_res['medium_total']} " f"hard={run_res['hard_pass']}/{run_res['hard_total']} " f"| tok={run_res['avg_comp_tok']} | {run_res['mean_tps']} tok/s | {round(time.time() - t0, 1)}s", flush=True, ) checkpoint_cb() def save_checkpoint(data: Dict[str, Any]) -> None: tmp = RESULTS_PATH.with_suffix(".tmp") tmp.write_text(json.dumps(data, indent=2), encoding="utf-8") tmp.replace(RESULTS_PATH) def main() -> None: parser = argparse.ArgumentParser(description="Evaluate all 10 models on 20 official Terminal-Bench tasks.") parser.add_argument("--models", default="all", help="Comma-separated slugs from ALL_MODEL_ORDER or 'all'") parser.add_argument("--modes", default="base,wsp", help="Comma-separated modes: base,wsp") parser.add_argument("--port", type=int, default=8126, help="Port for llama-server.exe") parser.add_argument("--ctx-size", type=int, default=16384, help="Context size for llama-server.exe") parser.add_argument("--force", action="store_true", help="Re-evaluate even if clean results are already recorded") args = parser.parse_args() selected = ALL_MODEL_ORDER if args.models == "all" else [s.strip() for s in args.models.split(",") if s.strip()] modes_to_run = [m.strip() for m in args.modes.split(",") if m.strip()] tbench_tasks = load_or_fetch_tasks() print(f"Loaded {len(tbench_tasks)} official Terminal-Bench tasks.", flush=True) results: Dict[str, Any] = { "benchmark": "ia03/terminal-bench (20-task multi-turn WSL2 Ubuntu-24.04)", "max_turns": MAX_TURNS, "cmd_timeout_s": CMD_TIMEOUT_S, "models": {}, } if RESULTS_PATH.exists(): try: loaded = json.loads(RESULTS_PATH.read_text(encoding="utf-8")) if isinstance(loaded, dict) and isinstance(loaded.get("models"), dict): results["models"] = loaded["models"] except Exception: pass gguf_specs = {spec.slug: spec for spec in MODEL_SPECS} with _WslKeepalive(): for slug in selected: model_entry = results["models"].setdefault(slug, {"slug": slug, "runs": {}}) print(f"\n{'=' * 78}\nTERMINAL-BENCH (20 TASKS) -> {slug}\n{'=' * 78}", flush=True) if slug in gguf_specs: spec = gguf_specs[slug] model_entry["display_name"] = spec.display_name need_modes = [ m for m in modes_to_run if not _is_run_complete(model_entry, m, len(tbench_tasks), force=args.force) ] if not need_modes: print(f" [Skip] All requested modes already recorded for {slug}.", flush=True) continue has_tb_extra = ( (spec.adapter_dir / "tbench_subspaces_manifest.json").exists() and (spec.adapter_dir / "wsp_s10_term_action.gguf").exists() and (spec.adapter_dir / "wsp_s11_term_code.gguf").exists() ) extra_loras = ["wsp_s10_term_action.gguf", "wsp_s11_term_code.gguf"] if has_tb_extra else None with LlamaServerHandle(spec, port=args.port, ctx_size=args.ctx_size, load_loras=True, extra_loras=extra_loras) as srv: router = DynamicSubspaceRouter9S(spec.adapter_dir, model_name=spec.slug, use_tbench_subspaces=has_tb_extra) for mode in need_modes: print(f" Running {slug} mode={mode} (-c {args.ctx_size}, max_tokens={MAX_TOKENS_GGUF})...", flush=True) t0 = time.time() run_res = evaluate_gguf_mode(spec, router, srv, mode, tbench_tasks) model_entry["runs"][mode] = run_res print( f" [{mode.upper()}] {run_res['pass']}/{run_res['total']} ({run_res['pct']}%) " f"| easy={run_res['easy_pass']}/{run_res['easy_total']} " f"med={run_res['medium_pass']}/{run_res['medium_total']} " f"hard={run_res['hard_pass']}/{run_res['hard_total']} " f"| tok={run_res['avg_comp_tok']} | {run_res['mean_tps']} tok/s | {round(time.time() - t0, 1)}s", flush=True, ) save_checkpoint(results) elif slug in ("qwen35_0_8b", "gemma4_e2b", "gemma4_e4b"): evaluate_edge_model( slug=slug, modes_to_run=modes_to_run, tbench_tasks=tbench_tasks, model_entry=model_entry, checkpoint_cb=lambda: save_checkpoint(results), force=args.force, ) save_checkpoint(results) elif slug in ("gemma4_26b_a4b", "qwen38_27b"): evaluate_custom_gguf_model( slug=slug, modes_to_run=modes_to_run, tbench_tasks=tbench_tasks, model_entry=model_entry, port=args.port, ctx_size=args.ctx_size, checkpoint_cb=lambda: save_checkpoint(results), force=args.force, ) save_checkpoint(results) else: raise ValueError(f"Unknown model slug: {slug}") save_checkpoint(results) print(f"\nSaved all Terminal-Bench results -> {RESULTS_PATH}", flush=True) if __name__ == "__main__": main()
"""20-Task Official Terminal-Bench Evaluation Across All 10 Models (Base vs. WSP).
Evaluates all 5 GGUF + WSP v3.0 (9 Subspaces) models, both larger Sparse-MoE / 27B
models via llama-server.exe, and all 3 PyTorch BF16 edge WSP models inside real WSL2
Ubuntu-24.04 sandboxes:
- GGUF 9S (Q4_K_M, -c 16384): qwen35_2b, qwen35_4b, nemotron3_4b, qwen35_9b, gemma4_12b
- Edge BF16 (PyTorch CUDA): qwen35_0_8b, gemma4_e2b, gemma4_e4b
- Large GGUF (Q4_K_M): gemma4_26b_a4b (--cpu-moe), qwen38_27b (-ngl 46)
Checkpoints results incrementally after each (model, mode) to `terminal_bench_results.json`.
"""
from __future__ import annotations
import argparse
import base64
import gc
import json
import re
import subprocess
import sys
import time
import urllib.request
from pathlib import Path
from typing import Any, Callable, Dict, List, Optional, Tuple
PIPELINE_DIR = Path(r"C:\Users\jhjwi\.gemini\antigravity\scratch\wsp-5model-pipeline")
QWEN08_DIR = Path(r"C:\Users\jhjwi\.gemini\antigravity\scratch\qwen35-iphone-agent")
GEMMA_E2B_DIR = Path(r"C:\Users\jhjwi\.gemini\antigravity\scratch\gemma4-e2b-agent")
GEMMA_E4B_DIR = Path(r"C:\Users\jhjwi\.gemini\antigravity\scratch\gemma4-weight-space")
GEMMA_26B_DIR = Path(r"C:\Users\jhjwi\.gemini\antigravity\scratch\gemma4-26b-a4b-wsp")
QWEN38_DIR = Path(r"C:\Users\jhjwi\.gemini\antigravity\scratch\qwen38-27b-wsp")
RESULTS_PATH = PIPELINE_DIR / "terminal_bench_results.json"
sys.path.insert(0, str(PIPELINE_DIR))
from dynamic_router_9s import DynamicSubspaceRouter9S # noqa: E402
from evaluate_all_models import ( # noqa: E402
LLAMA_SERVER_EXE,
LlamaServerHandle,
get_gpu_vram_mb,
http_get_json,
parse_tool_calls,
)
from model_registry import MODEL_SPECS, ModelSpec # noqa: E402
from setup_terminal_bench_20 import ( # noqa: E402
WSL_DISTRO,
grade_task_in_wsl,
load_or_fetch_tasks,
prepare_task_in_wsl,
run_wsl_bash,
)
import wsp_tasks_9subspaces as tasks # noqa: E402
sys.stdout.reconfigure(encoding="utf-8", line_buffering=True)
TERMINAL_TOOLS = [tasks.WORKER_TOOLS[0]] # exec tool only
MAX_TURNS = 5
CMD_TIMEOUT_S = 25
MAX_TOKENS_GGUF = 768
MAX_TOKENS_EDGE = 512
SYSTEM_PROMPT = (
"You are an autonomous Linux terminal agent working inside /app. "
"Use the `exec` tool to run bash commands to inspect files, make changes, and verify your solution. "
"Prefer combining inspection and solution steps into concise, self-contained bash commands. "
"Once the task is completely solved and verified, reply with a brief summary without calling a tool."
)
ALL_MODEL_ORDER = [
"qwen35_2b",
"qwen35_4b",
"nemotron3_4b",
"qwen35_9b",
"gemma4_12b",
"qwen35_0_8b",
"gemma4_e2b",
"gemma4_e4b",
"gemma4_26b_a4b",
"qwen38_27b",
]
def run_agent_cmd_in_wsl(cmd: str, cwd: str, timeout: int = CMD_TIMEOUT_S) -> Tuple[int, str, str]:
"""Run an agent shell command in WSL2 Ubuntu-24.04 while tracking persistent cwd."""
clean_cmd = (cmd or "").replace("\r\n", "\n")
cmd_b64 = base64.b64encode(clean_cmd.encode("utf-8")).decode("ascii")
wrapper = "\n".join([
"export PAGER=cat GIT_PAGER=cat TERM=dumb DEBIAN_FRONTEND=noninteractive",
f"echo '{cmd_b64}' | base64 -d > /tmp/_tbench_cmd.sh",
"_tbench_exit() {",
" local rc=$?",
" printf '\\n__TBENCH_PWD__:%s\\n' \"$(pwd)\"",
" exit $rc",
"}",
"trap _tbench_exit EXIT",
"source /tmp/_tbench_cmd.sh </dev/null",
])
rc, out, err = run_wsl_bash(wrapper, cwd=cwd, timeout=timeout)