"""Generate model outputs for every condition and write them to raw/.jsonl. Usage: python run_bench.py # full run (needs Metal GPU, no network) python run_bench.py --dry-run # no MLX: render every prompt, check prefix caching, count tokens python run_bench.py --limit 6 --budget-scale 0.2 # quick partial run """ import argparse import copy import hashlib import json import os import platform import subprocess import sys import time from pathlib import Path from prompts import encode, interleaved, menu, menu_key, render, shared_prefix from tasks import TASKS, WARMUP HERE = Path(__file__).parent RAW = HERE / "raw" MODELS = { "qwen": "mlx-community/Qwen3.6-35B-A3B-4bit", "gemma": "mlx-community/gemma-3-12b-it-4bit", } # Sampling from the model cards. Qwen3.6 card: non-thinking temp 0.7, top_p 0.8, top_k 20, min_p 0, # presence_penalty 1.5; thinking (general) temp 1.0, top_p 0.95, top_k 20, min_p 0, presence 1.5. # Gemma 3: temp 1.0, top_k 64, top_p 0.95 (Gemma team's recommended settings). SAMPLING = { "qwen_nothink": dict(temp=0.7, top_p=0.8, top_k=20, min_p=0.0, presence_penalty=1.5), "qwen_think": dict(temp=1.0, top_p=0.95, top_k=20, min_p=0.0, presence_penalty=1.5), "gemma": dict(temp=1.0, top_p=0.95, top_k=64, min_p=0.0, presence_penalty=0.0), } # deadline_min is cumulative from process start, so unused time rolls forward to later conditions. CONDITIONS = [ dict(name="qwen_nothink_8", family="qwen", menu=8, thinking=False, seeds=[0, 1, 2], max_tokens=512, sampling="qwen_nothink", deadline_min=10), dict(name="qwen_nothink_32", family="qwen", menu=32, thinking=False, seeds=[0], max_tokens=512, sampling="qwen_nothink", deadline_min=14), dict(name="qwen_think_8", family="qwen", menu=8, thinking=True, seeds=[0], max_tokens=1536, sampling="qwen_think", deadline_min=25), dict(name="gemma_8", family="gemma", menu=8, thinking=False, seeds=[0, 1, 2], max_tokens=512, sampling="gemma", deadline_min=36.5), ] def sha256(path): return hashlib.sha256(Path(path).read_bytes()).hexdigest() def sh(cmd): try: return subprocess.run(cmd, capture_output=True, text=True, timeout=10).stdout.strip() except Exception as e: # noqa: BLE001 - environment probing only return f"unavailable ({type(e).__name__})" def model_path(repo): from huggingface_hub import snapshot_download return Path(snapshot_download(repo, local_files_only=True)) def environment(): import importlib.metadata as md env = { "machine": sh(["sysctl", "-n", "hw.model"]), "cpu": sh(["sysctl", "-n", "machdep.cpu.brand_string"]), "memory_gb": None, "os": f"macOS {sh(['sw_vers', '-productVersion'])} build {sh(['sw_vers', '-buildVersion'])}", "kernel": platform.release(), "python": sys.version.split()[0], "packages": {p: md.version(p) for p in ["mlx", "mlx-metal", "mlx-lm", "numpy", "transformers"]}, "file_sha256": {f: sha256(HERE / f) for f in ["tasks.py", "tools.py", "prompts.py", "parsers.py", "scoring.py", "run_bench.py"]}, "models": {}, } mem = sh(["sysctl", "-n", "hw.memsize"]) env["memory_gb"] = round(int(mem) / 2**30) if mem.isdigit() else mem for fam, repo in MODELS.items(): p = model_path(repo) tmpl = p / "chat_template.jinja" if (p / "chat_template.jinja").exists() else p / "chat_template.json" env["models"][fam] = {"repo": repo, "snapshot": p.name, "chat_template_file": tmpl.name, "chat_template_sha256": sha256(tmpl)} return env def load_tokenizer_only(repo): from transformers import AutoTokenizer return AutoTokenizer.from_pretrained(model_path(repo)) def dry_run(limit): """Everything except the model forward pass.""" report = {} for cond in CONDITIONS: tok = load_tokenizer_only(MODELS[cond["family"]]) n_tok, prefix_lens, miss = [], [], 0 for task in interleaved()[:limit]: tools = menu(task, cond["menu"]) toks = encode(tok, render(tok, cond["family"], task["prompt"], tools, cond["thinking"])) pre = shared_prefix(tok, cond["family"], tools, cond["thinking"]) miss += toks[:len(pre)] != pre n_tok.append(len(toks)) prefix_lens.append(len(pre)) report[cond["name"]] = {"prompts": len(n_tok), "prompt_tokens_min": min(n_tok), "prompt_tokens_max": max(n_tok), "prefix_tokens_min": min(prefix_lens), "prefix_tokens_max": max(prefix_lens), "prefix_mismatches": miss} print(json.dumps(report, indent=2)) assert all(r["prefix_mismatches"] == 0 for r in report.values()), "prefix cache would not apply" return report class Runner: def __init__(self, family): import mlx.core as mx from mlx_lm import load self.mx = mx t = time.perf_counter() self.model, self.tok = load(str(model_path(MODELS[family]))) self.load_s = time.perf_counter() - t self.family = family stops = set(self.tok.eos_token_ids) for s in ["<|im_end|>", "", "", "<|endoftext|>"]: i = self.tok.convert_tokens_to_ids(s) if isinstance(i, int) and i != self.tok.unk_token_id: stops.add(i) self.stop_ids = stops self.prefix_caches = {} # (menu key, thinking) -> (prefix tokens, cache, prefill seconds) def prefix_cache(self, tools, thinking): from mlx_lm.models.cache import make_prompt_cache key = (menu_key(tools), thinking) if key not in self.prefix_caches: if len(self.prefix_caches) >= 8: self.prefix_caches.pop(next(iter(self.prefix_caches))) pre = shared_prefix(self.tok, self.family, tools, thinking) cache = make_prompt_cache(self.model) t = time.perf_counter() for i in range(0, len(pre), 2048): self.model(self.mx.array(pre[i:i + 2048])[None], cache=cache) self.mx.eval([c.state for c in cache]) self.prefix_caches[key] = (pre, cache, time.perf_counter() - t) return self.prefix_caches[key] def generate(self, prompt_text, tools, thinking, max_tokens, sampling, seed): from mlx_lm.generate import generate_step from mlx_lm.models.cache import make_prompt_cache from mlx_lm.sample_utils import make_sampler mx = self.mx toks = encode(self.tok, prompt_text) pre, pcache, prefill_s = self.prefix_cache(tools, thinking) cached = toks[:len(pre)] == pre and len(toks) > len(pre) mx.random.seed(seed) t0 = time.perf_counter() cache = copy.deepcopy(pcache) if cached else make_prompt_cache(self.model) rest = toks[len(pre):] if cached else toks sampler = make_sampler(temp=sampling["temp"], top_p=sampling["top_p"], top_k=sampling["top_k"], min_p=sampling["min_p"]) procs = [] if sampling["presence_penalty"]: pen = sampling["presence_penalty"] def presence_on_output(tokens, logits): # generate_step passes [last prompt token] + generated tokens; penalise generated only, # like the OpenAI/vLLM presence_penalty the model card refers to. if tokens.shape[0] > 1: logits[:, tokens[1:]] -= pen return logits procs.append(presence_on_output) out, finish, ttft = [], "length", None for tok_id, _ in generate_step(mx.array(rest), self.model, max_tokens=max_tokens, sampler=sampler, logits_processors=procs, prompt_cache=cache): if ttft is None: ttft = time.perf_counter() - t0 if tok_id in self.stop_ids: finish = "stop" break out.append(tok_id) latency = time.perf_counter() - t0 return { "text": self.tok.decode(out), "gen_tokens": len(out), "finish": finish, "cap_hit": finish == "length", "latency_s": latency, "ttft_s": ttft, "prompt_tokens": len(toks), "prefix_tokens": len(pre) if cached else 0, "prefix_cached": cached, "prefix_prefill_s": prefill_s, } def run(limit, budget_scale, only): import mlx.core as mx RAW.mkdir(exist_ok=True) start = time.perf_counter() env = environment() meta = {"environment": env, "conditions": {}} tasks = interleaved()[:limit] runner = None for cond in CONDITIONS: if only and cond["name"] not in only: continue if runner is None or runner.family != cond["family"]: runner = None mx.clear_cache() runner = Runner(cond["family"]) print(f"[{cond['family']}] loaded in {runner.load_s:.1f}s", flush=True) for w in WARMUP: # 3 untimed warm-up tasks, not part of the suite wtools = menu(w, 8) runner.generate(render(runner.tok, cond["family"], w["prompt"], wtools, cond["thinking"]), wtools, cond["thinking"], 64, SAMPLING[cond["sampling"]], 12345) deadline = start + cond["deadline_min"] * 60 * budget_scale mx.reset_peak_memory() runner.prefix_caches.clear() done, stopped_early = 0, False cstart = time.perf_counter() from mlx_lm.generate import generation_stream, wired_limit with wired_limit(runner.model, [generation_stream]), open(RAW / f"{cond['name']}.jsonl", "w") as f: for ti, task in enumerate(tasks): if time.perf_counter() > deadline: stopped_early = True break tools = menu(task, cond["menu"]) prompt = render(runner.tok, cond["family"], task["prompt"], tools, cond["thinking"]) for seed in cond["seeds"]: # seeds innermost: a budget cut never leaves seeds unpaired r = runner.generate(prompt, tools, cond["thinking"], cond["max_tokens"], SAMPLING[cond["sampling"]], seed * 100003 + ti) f.write(json.dumps({"condition": cond["name"], "task_id": task["id"], "category": task["category"], "seed": seed, "menu": [t["function"]["name"] for t in tools], **r}) + "\n") f.flush() done += 1 print(f" {cond['name']} {done}/{len(tasks)} {task['id']} " f"{r['latency_s']:.2f}s {r['gen_tokens']}tok {r['finish']}", flush=True) meta["conditions"][cond["name"]] = { **{k: cond[k] for k in ["family", "menu", "thinking", "seeds", "max_tokens"]}, "sampling": SAMPLING[cond["sampling"]], "model": MODELS[cond["family"]], "model_load_s": runner.load_s, "tasks_completed": done, "tasks_planned": len(tasks), "stopped_early_by_time_budget": stopped_early, "wall_s": time.perf_counter() - cstart, "peak_memory_gb": mx.get_peak_memory() / 1e9, } (RAW / "meta.json").write_text(json.dumps(meta, indent=2)) meta["total_wall_s"] = time.perf_counter() - start (RAW / "meta.json").write_text(json.dumps(meta, indent=2)) if __name__ == "__main__": ap = argparse.ArgumentParser() ap.add_argument("--dry-run", action="store_true") ap.add_argument("--limit", type=int, default=len(TASKS)) ap.add_argument("--budget-scale", type=float, default=float(os.environ.get("BUDGET_SCALE", 1.0))) ap.add_argument("--only", nargs="*", default=None) a = ap.parse_args() if a.dry_run: dry_run(a.limit) else: run(a.limit, a.budget_scale, a.only)