# Switching the Mac runtime to the MacJev engine `src/mac_laya/inference.py` is owned by another session and was **not** edited. The diff below is ready to apply once `models/macjev-release/` exists. It keeps the old Laya path unchanged when the release directory is absent, so applying it before the release lands is a no-op. What the new path gives the caller (same keys as the Laya engine: `answer`, `probabilities`, `top_probability`, `entropy_concentration`, `input_tokens`, `latency_ms`, `model`, `acceptance_status`; plus `temperature`, `logits`, `backend`, `backend_note`, `timing`): - `decide(state, question)`; new `decide_many(state, questions)` reads the state once (MLX prompt-cache copy per question; llama.cpp `seq_cp`). On the Laya path `decide_many` is a loop. - Budgets (2026-09-24, 25,000-token requirement): up to **25,600 tokens total** (`macjev.render.CONTEXT_LIMIT`, written into `release_config.json` `budgets.max_len` by `write_release_config`; releases written earlier carry 8,192 and keep it), 1,024 for question + options + readout (release may raise it to 2,048). Over-budget input raises `macjev.render.InputBudgetError`; nothing is truncated. llama.cpp runs with `n_ctx` 32,768 (`macjev.export.scorers.LLAMA_N_CTX`); the torch fallback uses query-chunked attention on MPS/CPU (`macjev.eval.long_attention`, exact for short inputs). The Mac gate itself sends a ~20K-token history view with explicit truncation markers (`macjev.mac.gate.HISTORY_TOKEN_BUDGET` = 20000, fallbacks 12000/6000/3000/1500/600; see `src/macjev/mac/RUNTIME_PATCH.diff`, owned by the mac package). The diff below only gained two comment lines about this (text only; nothing applied). - Temperatures from the release (`macjev.eval.calibration` table; family taken from `runtime_category`, default `mac_gate`). - **Default backend = llama.cpp GGUF F16** (decided 2026-09-24; `DEFAULT_BACKEND_ORDER` = llama.cpp, mlx, torch). Evidence (untrained base): - G5 vs the torch FP32 reference (240 rows): llama.cpp F16 top-1 99.6% verdict / 100% letter, MLX bf16 weights + fp32 activations 99.2% / 99.2% (2 rows above the 99% line); both pass (|dNLL| <= 0.002, no NaN). MLX with bf16 activations fails (98.75% / 97.5%) and is not reproducible run to run (2.5% top-1 flips between two identical runs). Report: `runs/macjev/latency/g5_parity_fp32ref_untrained_base_2026-09-24/`. - Export-readiness rerun (2026-09-24, fresh 240-row fixture from the current raw files, same thresholds): llama.cpp F16 still passes (99.58%, dNLL +0.0009); MLX bf16 + fp32 activations **fails** (97.08%, 7 flips, all at FP32-reference margins < 0.03; deterministic across two runs; torch bf16 itself agrees only 96.67% with FP32 on this sample). `macjev.export.release` therefore ships MLX as a packaged format but not as a runtime backend for that export. Report: `runs/macjev/latency/g5_parity_export_readiness_2026-09-24/`. - Latency does not separate the two: idle machine (2026-09-23 review run) llama.cpp 3-12% faster from 1K tokens, MLX faster at 64x1/64x5/256x5; on the loaded shared Mac of 2026-09-24 the winner flipped between two runs. See `runs/macjev/latency/summary.md`. - Tie-break: parity margin, the idle-machine result, and process isolation (llama.cpp's Metal memory lives in the `macjev-score` process and cannot starve the in-process torch MPS pool). - Needs `tools/macjev-score/build.sh`. If the binary or GGUF is missing, or the process does not start, the engine falls back to MLX (fp32 activations), then torch, and says so in every result's `backend_note`. - MLX runs with an explicit freed-buffer cache limit (`mlx_cache_limit_gib` in `release_config.json`, default 2 GiB, process-wide, never raises a tighter host limit): MLX's default cache limit is the whole memory limit; it grew to ~27 GiB in the latency review and starved torch MPS in the same process (OOM). - Multiple questions: `decide_many` scores all questions of a state in one batched forward after one state pass (MLX right-padded batch; llama.cpp multi-sequence decode). A single `decide` on a new state is one fused pass. Latency (idle-machine rerun incl. the fp32-activation default): `runs/macjev/latency/m1max_untrained_base_2026-09-23_review_idle/` (the earlier `m1max_untrained_base_2026-09-23/` was measured under load average 21-77 and overstates MacJev's single-question times by ~30% at 4K). - Backend: `release_config.json` `"backend"` (written by `write_release_config`: llama.cpp when the release ships a GGUF), `MACJEV_BACKEND=llama.cpp|mlx|torch` overrides. Fallbacks are reported in `backend_note`; a failed integrity check never falls back (it raises). ## Release directory expected at `models/macjev-release/` ``` models/macjev-release/ release_config.json # written by macjev.runtime.engine.write_release_config text-only/ # HF Qwen3_5ForCausalLM (tokenizer + torch fallback) gguf/model-f16.gguf # default backend, llama.cpp (needs tools/macjev-score/build.sh) mlx/bf16/ # first fallback (bf16 weights, run with fp32 activations) ``` Scripted (2026-09-24): `python -m macjev.export.release --export --temperatures /temperatures.json --parity /parity/report.json --out models/macjev-release --model-name "MacJev-0.8B "` copies text-only + every exported GGUF/MLX format (hash-checked against the export manifests), writes `readout_config.json` (slot token ids, temperatures), `release_config.json` (runtime backends = only G5-passing 16-bit formats) and `release_manifest.json` (sha256 of every file); `--verify --out ` re-hashes it. Manual equivalent: create it from an export (`python -m macjev.export.cli ... --out `), copy the chosen formats, then: ```python from macjev.runtime.engine import write_release_config write_release_config("models/macjev-release", model_name="MacJev-0.8B ", backends={"llama.cpp": "gguf/model-f16.gguf", "mlx": "mlx/bf16", "torch": "text-only"}, temperatures=json.load(open("/temperatures.json")), acceptance_status="candidate_system_acceptance_pending") ``` ## Diff for `src/mac_laya/inference.py` Generated with `diff -u` against the file as of 2026-09-23 17:50; regenerated 2026-09-24 (only change: a comment on the default backend) and checked with `patch -p1 --dry-run` against the file as of 2026-09-24 01:40; 2026-09-24 (25.6K context): two comment lines about the budgets added, `patch --dry-run` clean. Apply from the project root: `git apply src/macjev/runtime/RUNTIME_SWITCH.diff` (same content as the block below) or `patch -p1 < src/macjev/runtime/RUNTIME_SWITCH.diff`. ```diff --- a/src/mac_laya/inference.py +++ b/src/mac_laya/inference.py @@ -1,5 +1,6 @@ """Local decision engine for either the immutable official base or a verified release.""" import json +import os from pathlib import Path import time @@ -8,8 +9,31 @@ from .artifacts import ROOT,sha256 from .model import load_base,build_sequence,collate,upstream +MACJEV_RELEASE=ROOT/"models/macjev-release" + +def _macjev_available(release=None): + """Use the MacJev engine when its release exists (or an explicit MacJev release is passed).""" + if os.environ.get("MAC_LAYA_FORCE_LAYA")=="1":return None + path=Path(release) if release else MACJEV_RELEASE + return path if (path/"release_config.json").exists() else None + + class DecisionEngine: + def __new__(cls,release=None,*args,**kwargs): + macjev_release=_macjev_available(release) + if macjev_release is not None: + import sys + src=str(ROOT/"src") + if src not in sys.path:sys.path.insert(0,src) + from macjev.runtime.engine import DecisionEngine as MacJevEngine + # backend: release_config.json "backend" (default llama.cpp GGUF F16, then MLX fp32-act, then torch; + # any fallback is reported in each result's backend_note); MACJEV_BACKEND=llama.cpp|mlx|torch overrides + # budgets from release_config.json: up to 25,600 input tokens (macjev.render.CONTEXT_LIMIT, 2026-09-24); + # the Mac gate view sends ~20K tokens of history with explicit truncation markers (macjev/mac/RUNTIME_PATCH.diff) + return MacJevEngine(macjev_release,backend=os.environ.get("MACJEV_BACKEND") or None) + return super().__new__(cls) + def __init__(self,release=None): if not torch.backends.mps.is_available():raise RuntimeError("MPS unavailable; no silent fallback") torch.set_num_threads(8);torch.mps.set_per_process_memory_fraction(.55) @@ -37,3 +59,5 @@ "entropy_concentration":upstream.confidence_from_probs(__import__("numpy").array(p),len(p)), "input_tokens":len(ids),"latency_ms":(time.monotonic()-started)*1000,"model":self.label, "acceptance_status":self.acceptance_status} + def decide_many(self,state,questions): + return [self.decide(state,q) for q in questions] ``` Notes: - `__new__` returns a `macjev.runtime.engine.DecisionEngine` instance (not a subclass of the Laya class), so Python skips the Laya `__init__`; callers that only use `decide` / `decide_many` and the result dict are unaffected. Callers that read Laya-only attributes (`engine.model`, `engine.tokenizer`, `engine.temperatures` as a `{qtype: T}` dict) must be checked; grep before applying: `grep -rn "DecisionEngine" src/mac_laya`. - Passing an explicit Laya release directory (one with `release_manifest.json` and no `release_config.json`) keeps the Laya path; `MAC_LAYA_FORCE_LAYA=1` forces it globally. - Rollback: `rm -r models/macjev-release` (or set `MAC_LAYA_FORCE_LAYA=1`); no code change needed. - Over-budget input: `mac_laya.assistant.decide_step` retries smaller observations on `except mac_laya.model.InputBudgetError`. That class is NOT related to `macjev.render.InputBudgetError` (both only subclass `ValueError`), so an earlier version of this note was wrong: the MacJev error would have escaped the handler and aborted the step instead of retrying (found in review, 2026-09-23). Fixed in `macjev.runtime.engine.budget_error`: when `mac_laya.model` is loaded (always the case behind this diff, because `mac_laya.inference` imports it), `decide`/`decide_many` raise a `RuntimeInputBudgetError` that subclasses BOTH classes. Test: `tests/macjev/export/test_review_regressions.py::test_engine_budget_error_caught_by_mac_laya_handler`. - llama.cpp backend: `decide_many` with many options (e.g. 10 questions x 30 options = 300 slot logits in one decode) used to abort the `macjev-score` process (libllama `GGML_ASSERT` on `n_outputs_max` = 256); question groups are now split by slot count (fixed in review).