"""Time prefill (TTFT) and decode for the Qwen3.8-27B GGUF in ollama (llama.cpp backend). Expects an `ollama serve` already running on --host (run.sh starts it with flash attention on, f16 KV cache, num_parallel=1). Prompts are the same chat-templated text as config A, sent with raw=true so ollama does not apply its own template. Usage: python bench_ollama.py --config B --gguf --host 127.0.0.1:11545 --deadline python bench_ollama.py --config B --gguf --dry-run Writes raw/.json. """ import argparse import hashlib import http.client import json import os import re import subprocess import time from common import MAX_TOKENS, SCHEDULE, SEED, Budget, load_prompts, output_checks, thermal MODEL_NAME = "bench-qwen38-27b-gguf" NUM_CTX = 20480 OPTIONS = {"temperature": 0, "top_k": 1, "seed": SEED, "num_predict": MAX_TOKENS, "num_ctx": NUM_CTX} def api(host, method, path, body=None, timeout=900): h, p = host.split(":") c = http.client.HTTPConnection(h, int(p), timeout=timeout) c.request(method, path, body=json.dumps(body) if body is not None else None, headers={"Content-Type": "application/json"}) r = c.getresponse() data = r.read().decode() c.close() if r.status >= 300: raise RuntimeError(f"{method} {path} -> {r.status}: {data[:500]}") return json.loads(data.splitlines()[-1]) if data.strip() else {} def gguf_digest(path): real = os.path.realpath(path) name = os.path.basename(real) if re.fullmatch(r"[0-9a-f]{64}", name): # HF cache blobs are named by their sha256 return name h = hashlib.sha256() with open(real, "rb") as f: for chunk in iter(lambda: f.read(1 << 24), b""): h.update(chunk) return h.hexdigest() def create_model(host, gguf): """Register the local GGUF with ollama. Uses /api/create with the blob digest (no copy if run.sh hard-linked the blob into OLLAMA_MODELS); falls back to `ollama create -f`.""" digest = gguf_digest(gguf) body = {"model": MODEL_NAME, "stream": False, "files": {os.path.basename(gguf): f"sha256:{digest}"}, "parameters": {"num_ctx": NUM_CTX, "temperature": 0, "seed": SEED}} try: api(host, "POST", "/api/create", body) return {"method": "api/create", "digest": digest} except Exception as e: err = str(e) with open("Modelfile.bench", "w") as f: f.write(f"FROM {os.path.realpath(gguf)}\nPARAMETER num_ctx {NUM_CTX}\n" f"PARAMETER temperature 0\nPARAMETER seed {SEED}\n") env = dict(os.environ, OLLAMA_HOST=host) subprocess.run(["ollama", "create", MODEL_NAME, "-f", "Modelfile.bench"], check=True, env=env) return {"method": "cli create (api failed: " + err[:200] + ")", "digest": digest} def run_once(host, text): h, p = host.split(":") c = http.client.HTTPConnection(h, int(p), timeout=1800) body = {"model": MODEL_NAME, "prompt": text, "raw": True, "stream": True, "keep_alive": "30m", "options": OPTIONS} t0 = time.perf_counter() c.request("POST", "/api/generate", body=json.dumps(body), headers={"Content-Type": "application/json"}) r = c.getresponse() if r.status != 200: raise RuntimeError(f"generate -> {r.status}: {r.read()[:500]}") t_first, pieces, final = None, [], None while True: line = r.readline() if not line: break if not line.strip(): continue msg = json.loads(line) if "error" in msg: raise RuntimeError(msg["error"]) if msg.get("response"): if t_first is None: t_first = time.perf_counter() pieces.append(msg["response"]) if msg.get("done"): final = msg break t_end = time.perf_counter() c.close() text_out = "".join(pieces) n = final["eval_count"] pe_n, pe_ns = final.get("prompt_eval_count", 0), final.get("prompt_eval_duration", 0) return { "prompt_tokens": pe_n, "ttft_s": (t_first or t_end) - t0, "prefill_tps": pe_n / (pe_ns / 1e9) if pe_ns else None, "prompt_eval_s": pe_ns / 1e9, "decode_tokens": n, "decode_tps": n / (final["eval_duration"] / 1e9) if final.get("eval_duration") else None, "wall_s": t_end - t0, "load_s": final.get("load_duration", 0) / 1e9, "total_s_server": final.get("total_duration", 0) / 1e9, "done_reason": final.get("done_reason"), "text": text_out, "checks": output_checks(text_out), } def vm_stat(): try: return subprocess.run(["vm_stat"], capture_output=True, text=True, timeout=5).stdout except Exception as e: return f"unavailable: {e}" def main(): ap = argparse.ArgumentParser() ap.add_argument("--config", default="B") ap.add_argument("--gguf", required=True) ap.add_argument("--host", default="127.0.0.1:11545") ap.add_argument("--deadline", type=float, default=time.time() + 3600) ap.add_argument("--dry-run", action="store_true") args = ap.parse_args() prompts = load_prompts(args.config) lengths = prompts["lengths"] assert os.path.exists(args.gguf), args.gguf if args.dry_run: print(f"[dry-run] {args.config}: gguf={args.gguf} digest={gguf_digest(args.gguf)[:12]}… " f"options={OPTIONS} schedule={SCHEDULE}") return out = {"config": args.config, "backend": "ollama", "gguf": os.path.realpath(args.gguf), "server_version": api(args.host, "GET", "/api/version").get("version"), "options": OPTIONS, "raw_prompt": True, "server_env": {k: v for k, v in os.environ.items() if k.startswith("OLLAMA_") and k != "OLLAMA_MODELS"}, "eos": "not suppressible in ollama API; actual decode_tokens recorded per run", "thermal_before": thermal(), "vm_stat_before": vm_stat(), "runs": [], "skipped": []} t = time.perf_counter() out["create"] = create_model(args.host, args.gguf) out["create_s"] = time.perf_counter() - t out["show"] = {k: v for k, v in api(args.host, "POST", "/api/show", {"model": MODEL_NAME}).items() if k in ("details", "parameters", "model_info")} w = run_once(args.host, lengths["512"]["variants"][0]["text"]) # warm-up, includes load out["warmup"] = {k: v for k, v in w.items() if k != "text"} out["load_s"] = w["load_s"] out["ps"] = api(args.host, "GET", "/api/ps") out["vm_stat_loaded"] = vm_stat() print(f"[{args.config}] warm-up ttft={w['ttft_s']:.2f}s (load {w['load_s']:.1f}s) " f"decode={w['decode_tps']:.1f} tok/s") budget = Budget(args.deadline) for rep, order in SCHEDULE: for ctx in order: if not budget.allows(ctx): out["skipped"].append({"rep": rep, "ctx": ctx, "reason": "time budget"}) print(f"[{args.config}] skip rep{rep} ctx{ctx} (time budget)") continue th = thermal() r = run_once(args.host, lengths[str(ctx)]["variants"][rep]["text"]) r.update({"rep": rep, "ctx": ctx, "t_unix": time.time(), "cpu_speed_limit": th["cpu_speed_limit"], # nonce at token ~3 means at most a few template tokens can be cached "cache_suspect": r["prompt_tokens"] < ctx - 16}) budget.record(ctx, r["wall_s"]) out["runs"].append(r) print(f"[{args.config}] rep{rep} ctx{ctx}: ttft={r['ttft_s']:.2f}s " f"prefill={r['prefill_tps']:.0f} tok/s decode={r['decode_tps']:.1f} tok/s " f"evaluated={r['prompt_tokens']} gen={r['decode_tokens']}") out["ps_end"] = api(args.host, "GET", "/api/ps") out["thermal_after"] = thermal() try: api(args.host, "POST", "/api/generate", {"model": MODEL_NAME, "keep_alive": 0}) except Exception as e: out["unload_error"] = str(e) os.makedirs("raw", exist_ok=True) with open(f"raw/{args.config}.json", "w") as f: json.dump(out, f, indent=1) if __name__ == "__main__": main()