"""Latency benchmark on the M1 Max: Laya-multilingual (as shipped via ``mac_laya.inference``, FP32 on MPS) vs MacJev exports (MLX bf16 with bf16 activations, MLX bf16 with fp32 activations = the runtime engine default ``mlx-bf16-f32act``, MLX affine8, llama.cpp F16 / Q8_0). Every MacJev output is checked for NaN/inf (``nonfinite_outputs`` per cell). Same inputs for every system: a deterministic synthetic Mac-agent state sized so that prefix + first question is ~64 / 256 / 1K / 4K / 8K / 16K / 25.6K tokens in the Qwen3.5 tokenizer (actual counts, including Laya's own token counts, are recorded), and 1 / 5 / 10 short questions per state. The 16K and 25.6K (= ``macjev.render.CONTEXT_LIMIT``) points were added 2026-09-24 for the 25,000-token requirement and have not been measured yet; each target is fitted within its own budget (8192 / 16384 / 25600), so every question of the state fits and nothing is truncated. Laya answers each question with a separate ``decide`` call (it re-reads the state each time); MacJev scores all questions of a state in one ``score_state`` call: one question = one fused pass over state+question; several = state prefix once, then all questions as one batch (MLX right-padded batch / llama.cpp multi-sequence decode). ``*-sequential`` variants run the questions one after another on copies of the prefix state (the pre-batching path), for reference. All systems are loaded first and timed round-robin inside each cell (shared, loaded machine). Prefix caching across repeated runs is disabled (``keep_prefix=False``), so every measured run recomputes the state. Times are wall-clock end-to-end (tokenisation, rendering, forward, readout; model load excluded), p50 / p95 over warm runs. ``engine-default`` = ``macjev.runtime.engine.DecisionEngine`` on a release view of the export (symlinks, see ``release_view``) with its default backend (llama.cpp GGUF F16, decided 2026-09-24), called exactly as the Mac runtime would (``decide`` / ``decide_many``, temperatures + softmax included), with the engine's prefix reuse disabled like every other system. Latency does not depend on training, so the untrained Qwen3.5-0.8B-Base exports are used. Results: ``runs/macjev/latency//latency.json`` + ``latency.md``. """ from __future__ import annotations import gc import json import os import platform import statistics import subprocess import time from pathlib import Path import numpy as np from ..render import CONTEXT_LIMIT, SHORT_MAX_LEN TARGETS = (64, 256, 1024, 4096, 8192, 16384, CONTEXT_LIMIT) TARGET_BUDGETS = (SHORT_MAX_LEN, 16384, CONTEXT_LIMIT) # a target is fitted within the smallest budget >= it def target_budget(target: int) -> int: return next((b for b in TARGET_BUDGETS if target <= b), CONTEXT_LIMIT) QCOUNTS = (1, 5, 10) WORDS = ("open file save window click button menu finder safari terminal copy paste move folder " "document spreadsheet download upload settings network wifi volume brightness mail calendar " "reminder note message photo camera screenshot zoom scroll select drag drop rename delete " "archive compress restore backup sync cloud account login logout password token cache").split() QUESTIONS = [ {"t": "choice", "ins": "Next action?", "crit": {"click": None, "type": None, "wait": None}}, {"t": "noul", "ins": "Is the task done?", "crit": {"false": "not done", "true": "done"}}, {"t": "choice", "ins": "Which app is active?", "crit": {"finder": None, "safari": None, "mail": None, "other": None}}, {"t": "score", "ins": "Risk of the last action?", "crit": ["low", "medium", "high"]}, {"t": "noul", "ins": "Did an error occur?", "crit": {"false": "no error", "true": "error"}}, {"t": "choice", "ins": "Ask the user?", "crit": {"proceed": None, "ask": None, "stop": None}}, {"t": "noul", "ins": "Is a dialog open?", "crit": {"false": "no dialog", "true": "dialog open"}}, {"t": "score", "ins": "Progress so far?", "crit": ["none", "some", "most", "all"]}, {"t": "choice", "ins": "Target element?", "crit": {"button": None, "field": None, "link": None}}, {"t": "noul", "ins": "Was data changed?", "crit": {"false": "unchanged", "true": "changed"}}, ] def make_state(n_events: int, seed: int = 7) -> dict: rng = np.random.default_rng(seed) events = [] for i in range(n_events): words = rng.choice(WORDS, size=6) events.append({"step": i, "event": " ".join(words), "ok": bool(i % 5)}) return {"goal": "tidy the downloads folder and email the summary", "app": "finder", "events": events} def fit_state(renderer, target: int, question: dict, others: list[dict] | None = None, budget: int | None = None) -> tuple[dict, int]: """State whose rendered length (prefix + ``question``) is closest to ``target`` tokens while every question in ``others`` still fits the budget (``target_budget(target)`` by default: 8192 for targets up to 8K, then 16384, then the 25,600 context limit; at a budget-sized target the longest question must fit, so the first question lands slightly below it).""" from ..render import InputBudgetError budget = budget or target_budget(target) def length(n): # over-budget states count as infinitely long (never truncated) try: st = make_state(n) for q in others or (): renderer.render(st, q, max_len=budget) return len(renderer.render(st, question, max_len=budget).ids) except InputBudgetError: return float("inf") lo, hi = 0, 1 while length(hi) < target: lo, hi = hi, hi * 2 while lo < hi: mid = (lo + hi) // 2 if length(mid) < target: lo = mid + 1 else: hi = mid best = min((lo, max(0, lo - 1)), key=lambda n: abs(length(n) - target)) if length(best) == float("inf"): raise ValueError(f"no state fits target {target}") return make_state(best), length(best) def pct(xs, q): return float(np.percentile(np.asarray(xs, float), q)) if xs else None def system_snapshot() -> dict: snap = {"platform": platform.platform(), "machine": platform.machine(), "load_avg": os.getloadavg()} try: snap["chip"] = subprocess.check_output(["sysctl", "-n", "machdep.cpu.brand_string"], text=True).strip() out = subprocess.check_output(["ps", "-Ao", "pcpu,comm"], text=True).splitlines()[1:] busy = [l.strip() for l in out if l.strip() and float(l.split()[0]) > 20] snap["busy_processes_gt20pct_cpu"] = busy[:15] except Exception as e: # pragma: no cover snap["error"] = str(e) return snap def softmax(z): z = np.asarray(z, float) p = np.exp(z - z.max()) return p / p.sum() def release_view(export_dir: str | Path, dest: str | Path) -> Path: """A MacJev release directory made of symlinks into an export (no weight copies), with the engine's default backend order (release_config.json written by write_release_config).""" from ..runtime.engine import write_release_config export_dir, dest = Path(export_dir).resolve(), Path(dest) links = {"text-only": export_dir / "text-only", "gguf/model-f16.gguf": export_dir / "gguf" / "model-f16.gguf", "mlx/bf16": export_dir / "mlx" / "bf16"} for rel, src in links.items(): p = dest / rel p.parent.mkdir(parents=True, exist_ok=True) if p.is_symlink() and p.resolve() != src.resolve(): p.unlink() if not p.exists(): p.symlink_to(src) write_release_config(dest, model_name="MacJev-0.8B untrained base (latency view)", temperatures=None, backends={"llama.cpp": "gguf/model-f16.gguf", "mlx": "mlx/bf16", "torch": "text-only"}, acceptance_status="latency_measurement_only") return dest def time_runs(fn, warmup: int, runs: int, budget_s: float | None = None) -> dict: for _ in range(warmup): fn() xs = [] t_start = time.perf_counter() for _ in range(runs): t0 = time.perf_counter() fn() xs.append((time.perf_counter() - t0) * 1000) if budget_s and time.perf_counter() - t_start > budget_s and len(xs) >= 3: break return {"n": len(xs), "p50_ms": pct(xs, 50), "p95_ms": pct(xs, 95), "min_ms": min(xs), "max_ms": max(xs), "raw_ms": xs} def run(out: str | Path, export_dir: str | Path, systems: list[str] | None = None, targets=TARGETS, qcounts=QCOUNTS, runs_short: int = 15, runs_long: int = 8, warmup: int = 2, resume: bool = False, mlx_cache_gib: float | None = 4.0, mlx_memory_gib: float | None = 16.0) -> dict: from transformers import AutoTokenizer from ..render import Renderer out, export_dir = Path(out), Path(export_dir) out.mkdir(parents=True, exist_ok=True) tok = AutoTokenizer.from_pretrained(str(export_dir / "text-only")) r = Renderer(tok, "verdict") # CONTEXT_LIMIT; each target uses target_budget() inputs = {} for t in targets: state, n = fit_state(r, t, QUESTIONS[0], QUESTIONS[:max(qcounts)]) inputs[t] = {"state": state, "tokens_q1": n, "tokens_per_question": [len(r.render(state, q).ids) for q in QUESTIONS], "prefix_tokens": len(r.prefix_ids(state))} systems = systems or ["laya-multilingual-mps-fp32", "mlx-bf16-f32act", "mlx-bf16", "mlx-affine8", "llamacpp-f16", "llamacpp-q8_0", "mlx-bf16-sequential", "llamacpp-q8_0-sequential"] report = {"created_unix": time.time(), "export_dir": str(export_dir), "system_before": system_snapshot(), "targets": list(targets), "qcounts": list(qcounts), "inputs": {str(t): {k: v for k, v in d.items() if k != "state"} for t, d in inputs.items()}, "questions": QUESTIONS, "results": {}, "notes": []} (out / "inputs.json").write_text(json.dumps({"states": {str(t): d["state"] for t, d in inputs.items()}, "questions": QUESTIONS}, ensure_ascii=False)) done_cells = set() if resume and (out / "latency.json").exists(): # keep finished cells of an interrupted run old = json.loads((out / "latency.json").read_text()) if old.get("inputs") != report["inputs"] or set(old.get("results", {})) != set(systems): raise ValueError("--resume: inputs or systems differ from the existing latency.json") report["results"], report["load_avg_by_cell"] = old["results"], old.get("load_avg_by_cell", {}) report["system_before"], report["created_unix"] = old["system_before"], old["created_unix"] report["notes"] = old.get("notes", []) + [f"resumed at {time.time():.0f}; finished cells kept"] done_cells = {k for k in old["load_avg_by_cell"] if all(old["results"][s].get(k, {}).get("status") in ("ok", "unsupported", "error") for s in systems)} uses_mlx = any(s.startswith("mlx") or s == "engine-default" for s in systems) if uses_mlx: # MLX keeps freed buffers (default limit = the memory limit); with several MLX systems it # grew to ~27 GiB and starved the in-process Laya MPS pool (OOM in review). Bounded cache, and # (2026-09-24, 25.6K inputs) a hard MLX memory limit so one long cell cannot take the 64 GB Mac. # engine-default is included: its fallback backend is MLX. import mlx.core as mx from ..runtime.engine import set_mlx_cache_limit got = set_mlx_cache_limit(mlx_cache_gib if mlx_cache_gib is not None else 4.0) report["notes"].append(f"mlx cache limit {got / (1 << 30):.2f} GiB") if mlx_memory_gib is not None: mx.set_memory_limit(int(mlx_memory_gib * (1 << 30))) report["notes"].append(f"mlx memory limit {mlx_memory_gib} GiB") def save(): (out / "latency.json").write_text(json.dumps(report, indent=2)) # Load every system first, then time them interleaved (round robin inside each cell), so # drifting background load on this shared machine hits all systems alike. makers, closers = {}, [] for sysname in systems: res = report["results"].setdefault(sysname, {}) t_load = time.perf_counter() if sysname == "engine-default": from ..runtime.engine import DecisionEngine as MacJevEngine eng = MacJevEngine(release_view(export_dir, out / "_release_view")) if hasattr(eng.backend, "keep_prefix"): eng.backend.keep_prefix = False # every run recomputes the state (as for the others) res["_model"] = f"DecisionEngine[{eng.backend_name}] {getattr(eng.backend, 'name', '')}" res["_backend"], res["_backend_note"] = eng.backend_name, eng.backend_note if hasattr(eng.backend, "close"): closers.append(eng.backend.close) def make_fn(state, qs, eng=eng): def fn(): rs = eng.decide_many(state, qs) fn.mode = rs[0]["timing"].get("mode") fn.nonfinite += sum(int(not np.all(np.isfinite(r["logits"]))) for r in rs) return rs fn.nonfinite = 0 return fn elif sysname.startswith("laya"): from mac_laya.inference import DecisionEngine as LayaEngine from mac_laya.model import build_sequence eng = LayaEngine() res["_model"] = eng.label res["_laya_tokens"] = {} for t in targets: try: res["_laya_tokens"][str(t)] = [len(build_sequence(eng.tokenizer, inputs[t]["state"], q)[0]) for q in QUESTIONS[:max(qcounts)]] except Exception as e: res["_laya_tokens"][str(t)] = f"unsupported: {type(e).__name__}: {e}" def make_fn(state, qs, eng=eng): def fn(): return [eng.decide(state, q) for q in qs] return fn else: from .scorers import LlamaCppScorer, MLXScorer err = out / "macjev-score.stderr.log" cl = mlx_cache_gib if mlx_cache_gib is not None else 4.0 sc = {"mlx-bf16": lambda: MLXScorer(export_dir / "mlx" / "bf16", keep_prefix=False, cache_limit_gib=cl), "mlx-bf16-f32act": lambda: MLXScorer(export_dir / "mlx" / "bf16", keep_prefix=False, compute_dtype="float32", cache_limit_gib=cl), # engine default "mlx-affine8": lambda: MLXScorer(export_dir / "mlx" / "affine8-g64", keep_prefix=False, cache_limit_gib=cl), "mlx-bf16-sequential": lambda: MLXScorer(export_dir / "mlx" / "bf16", keep_prefix=False, batch_questions=False, fuse_single=False, cache_limit_gib=cl), "llamacpp-f16": lambda: LlamaCppScorer(export_dir / "gguf" / "model-f16.gguf", export_dir / "text-only", keep_prefix=False, stderr_path=err), "llamacpp-q8_0": lambda: LlamaCppScorer(export_dir / "gguf" / "model-q8_0.gguf", export_dir / "text-only", keep_prefix=False, stderr_path=err), "llamacpp-q8_0-sequential": lambda: LlamaCppScorer(export_dir / "gguf" / "model-q8_0.gguf", export_dir / "text-only", keep_prefix=False, stderr_path=err, mode="sequential"), }[sysname]() res["_model"] = sc.name if hasattr(sc, "close"): closers.append(sc.close) def make_fn(state, qs, sc=sc): def fn(): z, timing = sc.score_state(state, qs) fn.mode = timing.get("mode") fn.nonfinite += sum(int(not np.all(np.isfinite(x))) for x in z) # GDN NaN watch (M1) return [softmax(x) for x in z] fn.nonfinite = 0 return fn res["_load_s"] = time.perf_counter() - t_load makers[sysname] = make_fn for t in targets: for nq in qcounts: key = f"{t}x{nq}" if key in done_cells: continue qs = QUESTIONS[:nq] state = inputs[t]["state"] fns, xs = {}, {} for sysname in systems: entry = {"target_tokens": t, "questions": nq, "tokens_q1": inputs[t]["tokens_q1"]} lt = report["results"][sysname].get("_laya_tokens", {}).get(str(t)) if isinstance(lt, str): entry.update({"status": "unsupported", "reason": lt}) elif lt is not None: entry["laya_tokens"] = lt[:nq] report["results"][sysname][key] = entry if entry.get("status") != "unsupported": fns[sysname] = makers[sysname](state, qs) xs[sysname] = [] n_runs = runs_short if t <= 1024 else runs_long for sysname, fn in list(fns.items()): try: for _ in range(warmup): fn() except Exception as e: report["results"][sysname][key].update({"status": "error", "reason": f"{type(e).__name__}: {e}"}) fns.pop(sysname) t_cell = time.perf_counter() for i in range(n_runs): order = list(fns)[i % max(1, len(fns)):] + list(fns)[:i % max(1, len(fns))] for sysname in order: t0 = time.perf_counter() try: fns[sysname]() except Exception as e: # one failing system must not end the run report["results"][sysname][key].update({"status": "error", "reason": f"{type(e).__name__}: {e}"}) fns.pop(sysname) continue xs[sysname].append((time.perf_counter() - t0) * 1000) if time.perf_counter() - t_cell > 240 and i >= 2: break for sysname in fns: v = xs[sysname] report["results"][sysname][key].update({ "status": "ok", "n": len(v), "p50_ms": pct(v, 50), "p95_ms": pct(v, 95), "min_ms": min(v), "max_ms": max(v), "raw_ms": v, "mode": getattr(fns[sysname], "mode", None), "nonfinite_outputs": getattr(fns[sysname], "nonfinite", None)}) print(f"[latency] {sysname} {key}: p50={pct(v, 50):.0f} p95={pct(v, 95):.0f}", flush=True) report["load_avg_by_cell"] = {**report.get("load_avg_by_cell", {}), key: os.getloadavg()} if uses_mlx: import mlx.core as mx mx.clear_cache() # return the cell's freed buffers before the next (longer) cell save() for c in closers: c() gc.collect() report["system_after"] = system_snapshot() save() (out / "latency.md").write_text(markdown(report)) return report def markdown(report: dict) -> str: systems = [s for s in report["results"]] lines = ["# MacJev latency (M1 Max, warm runs, end-to-end ms)", "", "Untrained Qwen3.5-0.8B-Base exports (latency does not depend on training). " "Laya = mac_laya.inference DecisionEngine (FP32, MPS), one decide() per question. " "MacJev = one score_state() per state: 1 question = one fused pass; several = state prefix once + " "all questions in one batch (`*-sequential` = questions one by one on prefix copies, reference only). " "Prefix cache disabled between runs. All systems loaded together and timed round-robin per cell.", "", f"Load average before: {report['system_before'].get('load_avg')}, after: " f"{report.get('system_after', {}).get('load_avg')} (shared machine; other jobs were running).", "", "| tokens x questions | " + " | ".join(f"{s} p50 / p95" for s in systems) + " |", "|---|" + "---|" * len(systems)] for t in report["targets"]: for nq in report["qcounts"]: key = f"{t}x{nq}" cells = [] for s in systems: e = report["results"][s].get(key, {}) if e.get("status") == "ok": cells.append(f"{e['p50_ms']:.0f} / {e['p95_ms']:.0f}") else: cells.append(e.get("status", "-")) lines.append(f"| {key} (actual {report['inputs'][str(t)]['tokens_q1']}) | " + " | ".join(cells) + " |") nonfinite = sum(e.get("nonfinite_outputs") or 0 for r in report["results"].values() for e in r.values() if isinstance(e, dict)) lines += ["", f"Non-finite (NaN/inf) MacJev outputs over all timed runs: {nonfinite}.", "`engine-default` = macjev.runtime.engine.DecisionEngine with the backend it picked (see the " "`_backend` field of latency.json; default llama.cpp GGUF F16 since 2026-09-24, " "fallback MLX = `mlx-bf16-f32act`)."] lines += ["", "Laya faster (p50) than every MacJev variant (excluding *-sequential) in:"] laya = next((s for s in systems if s.startswith("laya")), None) if laya: for t in report["targets"]: for nq in report["qcounts"]: key = f"{t}x{nq}" le = report["results"][laya].get(key, {}) ours = [report["results"][s].get(key, {}) for s in systems if s != laya and not s.endswith("-sequential")] ours_ok = [e["p50_ms"] for e in ours if e.get("status") == "ok"] if le.get("status") == "ok" and ours_ok and le["p50_ms"] < min(ours_ok): lines.append(f"- {key}: Laya {le['p50_ms']:.0f} ms vs best MacJev {min(ours_ok):.0f} ms") return "\n".join(lines) + "\n" def main(argv=None): import argparse ap = argparse.ArgumentParser(description=__doc__) ap.add_argument("--export-dir", required=True) ap.add_argument("--out", required=True) ap.add_argument("--systems", default="") ap.add_argument("--targets", default=",".join(map(str, TARGETS))) ap.add_argument("--qcounts", default=",".join(map(str, QCOUNTS))) ap.add_argument("--runs-short", type=int, default=15) ap.add_argument("--runs-long", type=int, default=8) ap.add_argument("--resume", action="store_true", help="keep finished cells of /latency.json") ap.add_argument("--mlx-cache-gib", type=float, default=4.0) ap.add_argument("--mlx-memory-gib", type=float, default=16.0, help="hard MLX memory limit (mx.set_memory_limit); 0 = MLX default") a = ap.parse_args(argv) rep = run(a.out, a.export_dir, [s for s in a.systems.split(",") if s] or None, tuple(int(x) for x in a.targets.split(",")), tuple(int(x) for x in a.qcounts.split(",")), a.runs_short, a.runs_long, resume=a.resume, mlx_cache_gib=a.mlx_cache_gib, mlx_memory_gib=a.mlx_memory_gib or None) print(markdown(rep)) if __name__ == "__main__": main()