File size: 19,437 Bytes
72c7148 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 | """MacJev runtime engine: ``DecisionEngine(release_dir).decide(state, question)``.
Drop-in for ``mac_laya.inference.DecisionEngine`` (same ``decide`` result keys) plus
``decide_many(state, questions)``, which reads the state once and scores every question on a
copy of the prefix state (MLX prompt-cache copy / llama.cpp sequence copy).
Release directory (``models/macjev-release/`` by default)::
release_config.json {"format": "macjev-release-v1", "model_name", "readout": "verdict"|"letter",
"backend": "llama.cpp", "backends": {"llama.cpp": "gguf/model-f16.gguf", "mlx": "mlx/bf16",
"torch": "text-only"}, "tokenizer": "text-only", "mlx_compute_dtype": "float32",
"mlx_cache_limit_gib": 2.0,
"temperatures": <macjev.eval.calibration.fit_temperatures output>,
"runtime_category": "mac_gate", "budgets": {"max_len": 25600, "head_max": 1024},
"files": {relpath: sha256}, "acceptance_status": "..."}
Budgets: total input <= ``macjev.render.CONTEXT_LIMIT`` = 25,600 tokens (2026-09-24; releases written
before that carry 8192 and keep it), question+options+readout <= 1024 tokens (``head_max``, up
to the hard cap 2048). Anything larger raises ``macjev.render.InputBudgetError`` - never
truncated. llama.cpp runs with ``n_ctx`` 32768 (``macjev.export.scorers.LLAMA_N_CTX``); the torch
fallback uses query-chunked attention on MPS/CPU (``macjev.eval.long_attention``) so a 25.6K
input does not materialise the full attention matrix. Temperatures come from the release (``calibration.lookup`` keyed by family x qtype x
option bucket; ``runtime_category`` gives the family because a live Mac question carries no
category), so probabilities are softmax(logits / T).
Only ship a 16-bit GGUF as the llama.cpp backend: Q8_0 failed G5 on the untrained base (95.4%
verdict top-1 vs the FP32 reference, gate 98%); re-judge on the trained weights before shipping it.
Default backend (decided 2026-09-24 from measured parity + latency on the untrained base; see
``runs/macjev/latency/summary.md``): **llama.cpp GGUF F16** (``DEFAULT_BACKEND_ORDER`` =
llama.cpp, mlx, torch). Both candidates pass G5 against the torch FP32 reference (llama.cpp F16
top-1 99.6% verdict / 100% letter; MLX bf16 weights + fp32 activations 99.2% / 99.2%, i.e. only
2 of 240 rows above the 99% line). Latency did not separate them: on the one idle-machine run
llama.cpp was 3-12% faster from 1K tokens (MLX faster at 64 tokens), and on two runs on the
loaded, shared Mac of 2026-09-24 the winner flipped (MLX ahead in all 15 cells of one run, llama.cpp
ahead in most single-question cells of the next). Tie-break: the larger parity margin and the
idle-machine result, plus process isolation (llama.cpp's Metal memory lives in its own process
and cannot starve an in-process torch MPS pool). MLX-f32act is the first fallback (used when
the ``tools/macjev-score`` binary or the GGUF is missing or the process does not start), then
torch. Every fallback is explicit and reported in each result as ``backend_note``; an explicitly
requested backend is still honoured; a failed integrity check raises and never falls back.
MLX computes with fp32 activations on the bf16 weights by default (``mlx_compute_dtype``,
"float32"; null = native bf16): on the G5 fixture this matched PyTorch fp32 top-1 on 99.2% of rows
vs 97.5-98.75% with bf16 activations (which also flipped 2.5% of top-1 decisions between two
identical runs; fp32 activations were bit-identical), at 3-16% extra latency. MLX keeps freed Metal buffers in a
cache whose default limit is the whole memory limit; in the latency review it grew to ~27 GiB and
starved torch MPS in the same process (OOM). The engine therefore sets an explicit cache limit
(``mlx_cache_limit_gib`` in release_config.json, default ``MLX_CACHE_LIMIT_GIB`` = 2 GiB; the
limit is process-wide, the engine never raises an already lower limit).
"""
from __future__ import annotations
import hashlib
import json
import math
import sys
import time
from pathlib import Path
from typing import Any, Sequence
import numpy as np
from ..eval import calibration
from ..paths import ROOT
from ..render import CONTEXT_LIMIT, HARD_HEAD_MAX, InputBudgetError, Renderer, canonical_probs # noqa: F401
from ..schema import option_names
DEFAULT_RELEASE = ROOT / "models" / "macjev-release"
RELEASE_FORMAT = "macjev-release-v1"
DEFAULT_BACKEND_ORDER = ("llama.cpp", "mlx", "torch") # preference when the release does not pin one
MLX_CACHE_LIMIT_GIB = 2.0
class BackendStartError(RuntimeError):
"""A backend's runtime exists but could not be started (engine falls back, reported)."""
def set_mlx_cache_limit(gib: float | None) -> int | None:
"""Bound MLX's freed-buffer cache (process-wide). Returns the limit in bytes, or None if unset.
Never raises an already lower limit set by the host process."""
if gib is None:
return None
import mlx.core as mx
want = int(float(gib) * (1 << 30))
prev = mx.set_cache_limit(want)
if prev is not None and prev < want: # host already set a tighter limit (0 = no cache): keep it
mx.set_cache_limit(prev)
return int(prev)
return want
def _sha256(path: Path) -> str:
h = hashlib.sha256()
with open(path, "rb") as f:
for b in iter(lambda: f.read(1 << 22), b""):
h.update(b)
return h.hexdigest()
_BRIDGED: dict = {}
def budget_error(err: InputBudgetError) -> InputBudgetError:
"""Re-type an over-budget error so that the Mac runtime's existing handler catches it.
``mac_laya.assistant.decide_step`` retries smaller observations on
``except mac_laya.model.InputBudgetError``; that class is unrelated to
``macjev.render.InputBudgetError`` (both are plain ``ValueError`` subclasses), so without this
the MacJev engine's error would escape the handler and abort the step (found in review).
When ``mac_laya.model`` is loaded (always the case behind the RUNTIME_SWITCH diff, because
``mac_laya.inference`` imports it), the error is raised as a subclass of BOTH classes. No
import is triggered here: standalone use keeps the plain macjev class."""
laya = sys.modules.get("mac_laya.model")
other = getattr(laya, "InputBudgetError", None)
if not isinstance(other, type) or isinstance(err, other):
return err
cls = _BRIDGED.get(other)
if cls is None:
cls = type("RuntimeInputBudgetError", (type(err), other), {"__module__": __name__})
_BRIDGED[other] = cls
return cls(*err.args)
def concentration(p: np.ndarray) -> float:
"""Laya's normalised-entropy confidence 1 - H(p)/log k (laya/common.py)."""
k = len(p)
if k < 2:
return 1.0
ent = -(p * np.log(np.clip(p, 1e-12, 1.0))).sum()
return float(np.clip(1.0 - ent / math.log(k), 0.0, 1.0))
class TorchBackend:
"""PyTorch fallback (bf16 on MPS if available, else fp32 CPU). No prefix sharing."""
name = "torch"
def __init__(self, path: Path, readout: str, max_len: int, head_max: int):
import torch
from .. import backbone as bb
self.torch = torch
dev = "mps" if torch.backends.mps.is_available() else "cpu"
self.bb = bb.load(path, device=dev, dtype=torch.bfloat16 if dev == "mps" else torch.float32)
self.bb.model.eval()
if dev != "cuda":
from ..eval.long_attention import enable
enable(self.bb.model) # exact for short inputs; bounded attention memory for long ones
self.device = dev
self.renderer = Renderer(self.bb.tokenizer, readout, max_len=max_len, head_max=head_max)
self.readout = readout
def score_state(self, state, questions, orders=None, head_max=None):
from ..readout import letter_scores, verdict_scores
torch = self.torch
out, q_ms = [], []
t0 = time.perf_counter()
rendered = [self.renderer.render(state, q, order=(orders[i] if orders else None), head_max=head_max)
for i, q in enumerate(questions)]
W = self.bb.lm_head_weight
with torch.no_grad():
for r in rendered:
t1 = time.perf_counter()
ids = torch.tensor([r.ids], device=self.device)
h = self.bb.hidden(ids)
if self.readout == "verdict":
pos = torch.tensor([r.slots], device=self.device)
sc = verdict_scores(h, pos, torch.ones_like(pos, dtype=torch.bool), W,
self.renderer.tokens.yes, self.renderer.tokens.no)[0]
else:
sc = letter_scores(h, torch.tensor([r.slots[0]], device=self.device),
torch.tensor([len(r.order)], device=self.device), W,
self.renderer.tokens.letters)[0]
out.append(canonical_probs(sc.float().cpu().tolist(), r.order))
q_ms.append((time.perf_counter() - t1) * 1000)
return out, {"prefix_ms": 0.0, "question_ms": q_ms, "total_ms": (time.perf_counter() - t0) * 1000,
"prefix_reused": False, "n_prefix": rendered[0].prefix_len,
"n_suffix": [len(r.ids) - r.prefix_len for r in rendered]}
class DecisionEngine:
def __init__(self, release: str | Path | None = None, backend: str | None = None, verify: bool = True):
self.release = Path(release) if release else DEFAULT_RELEASE
cfg_path = self.release / "release_config.json"
if not cfg_path.exists():
raise FileNotFoundError(f"{cfg_path} missing (not a MacJev release)")
self.config = cfg = json.loads(cfg_path.read_text())
if cfg.get("format") != RELEASE_FORMAT:
raise ValueError(f"unsupported release format {cfg.get('format')!r}")
self.readout = cfg.get("readout", "verdict")
b = cfg.get("budgets") or {}
self.max_len = int(b.get("max_len", 8192)) # releases written before 2026-09-24: 8192
self.head_max = int(b.get("head_max", 1024))
if self.head_max > HARD_HEAD_MAX or self.max_len > CONTEXT_LIMIT:
raise ValueError(f"release budgets exceed max_len {CONTEXT_LIMIT} / head_max {HARD_HEAD_MAX}")
self.temperatures = cfg.get("temperatures") or {"global": 1.0, "groups": {}}
self.runtime_category = cfg.get("runtime_category", "mac_gate")
self.label = cfg.get("model_name", "MacJev")
self.acceptance_status = cfg.get("acceptance_status", "candidate_system_acceptance_pending")
self.backend_note = ""
backends = cfg.get("backends") or {}
if backend: # explicit request (MACJEV_BACKEND / caller)
if backend not in backends:
raise FileNotFoundError(f"release lists no {backend!r} backend (backends: {sorted(backends)})")
order = [backend] + [b for b in DEFAULT_BACKEND_ORDER if b != backend and b in backends]
else:
first = cfg.get("backend") or next((b for b in DEFAULT_BACKEND_ORDER if b in backends), None)
if first not in backends:
raise FileNotFoundError(f"release lists no {first!r} backend (backends: {sorted(backends)})")
order = [first] + [b for b in DEFAULT_BACKEND_ORDER if b != first and b in backends]
self.mlx_cache_limit_bytes = None
notes, err = [], None
for want in order:
try:
self.backend = self._open(want, backends[want], verify)
except (ImportError, FileNotFoundError, OSError, BackendStartError) as e: # missing runtime/binary/files
notes.append(f"{want} unavailable ({type(e).__name__}: {e})")
err = e
continue
break
else:
raise FileNotFoundError("no usable backend: " + "; ".join(notes)) from err
if notes:
self.backend_note = "; ".join(notes) + f"; using {want} fallback"
self.backend_name = want
def _open(self, want: str, rel: str, verify: bool):
cfg = self.config
path = self.release / rel
if want == "llama.cpp":
from ..export.scorers import SCORE_BIN
if not SCORE_BIN.exists():
raise FileNotFoundError(f"{SCORE_BIN} missing; run tools/macjev-score/build.sh")
if not path.exists():
raise FileNotFoundError(f"{path} missing")
if verify:
self._verify(rel)
if want == "llama.cpp": # the GGUF backend tokenises with the separate tokenizer dir
self._verify(cfg.get("tokenizer", "text-only"), skip_suffixes=(".safetensors",))
if want == "mlx":
import mlx.core # noqa: F401 (ImportError -> next backend)
self.mlx_cache_limit_bytes = set_mlx_cache_limit(cfg.get("mlx_cache_limit_gib", MLX_CACHE_LIMIT_GIB))
from ..export.scorers import MLXScorer
return MLXScorer(path, readout=self.readout, max_len=self.max_len, head_max=self.head_max,
compute_dtype=cfg.get("mlx_compute_dtype", "float32") or None,
cache_limit_gib=cfg.get("mlx_cache_limit_gib", MLX_CACHE_LIMIT_GIB))
if want == "llama.cpp":
from ..export.scorers import LlamaCppScorer
try:
return LlamaCppScorer(path, self.release / cfg.get("tokenizer", "text-only"), readout=self.readout,
max_len=self.max_len, head_max=self.head_max)
except RuntimeError as e: # binary present but the process did not come up
if "failed to start" not in str(e):
raise
raise BackendStartError(str(e)) from e
if want == "torch":
return TorchBackend(path, self.readout, self.max_len, self.head_max)
raise ValueError(f"unknown backend {want!r}")
def _verify(self, rel: str, skip_suffixes: tuple = ()) -> None:
files = self.config.get("files") or {}
target = self.release / rel
checked = 0
for name, digest in files.items():
p = self.release / name
if p.suffix in skip_suffixes:
continue
if p == target or target in p.parents:
if _sha256(p) != digest:
raise RuntimeError(f"release integrity error: {name}")
checked += 1
if files and checked == 0:
raise RuntimeError(f"release lists no checksums for backend path {rel}")
def temperature(self, question: dict, category: str | None = None) -> float:
row = {"category": category or self.runtime_category, "qtype": question["t"],
"names": option_names(question)}
if "groups" in self.temperatures or "global" in self.temperatures:
return calibration.lookup(self.temperatures, row)
return float(self.temperatures.get(question["t"], 1.0)) # legacy {"choice": T, ...}
def _result(self, question, logits, n_tokens, latency_ms, timing, category):
names = option_names(question)
t = self.temperature(question, category)
z = np.asarray(logits, float) / t
if not np.all(np.isfinite(z)):
raise FloatingPointError("non-finite decision logits")
p = np.exp(z - z.max())
p /= p.sum()
i = int(p.argmax())
return {"answer": names[i], "probabilities": dict(zip(names, p.tolist())), "top_probability": float(p[i]),
"entropy_concentration": concentration(p), "input_tokens": n_tokens, "latency_ms": latency_ms,
"model": self.label, "acceptance_status": self.acceptance_status, "temperature": t,
"logits": [float(x) for x in logits], "backend": self.backend_name,
"backend_note": self.backend_note, "timing": timing}
def decide(self, state: Any, question: dict, category: str | None = None) -> dict:
return self.decide_many(state, [question], category=category)[0]
def decide_many(self, state: Any, questions: Sequence[dict], category: str | None = None) -> list[dict]:
"""Several questions on one state; the state prefix is computed once. Raises InputBudgetError."""
if not questions:
return []
started = time.monotonic()
try:
logits, timing = self.backend.score_state(state, list(questions))
except InputBudgetError as e:
raise budget_error(e) from None
total_ms = (time.monotonic() - started) * 1000
n_prefix = timing["n_prefix"]
out = []
for q, z, n_suf, q_ms in zip(questions, logits, timing["n_suffix"], timing["question_ms"]):
out.append(self._result(q, z, n_prefix + n_suf, total_ms if len(questions) == 1 else q_ms,
{**{k: v for k, v in timing.items() if k not in ("question_ms", "n_suffix")},
"batch_total_ms": total_ms}, category))
return out
def write_release_config(release: str | Path, *, model_name: str, backends: dict, temperatures: dict | None,
readout: str = "verdict", backend: str | None = None, tokenizer: str = "text-only",
runtime_category: str = "mac_gate", head_max: int = 1024, max_len: int = CONTEXT_LIMIT,
acceptance_status: str = "candidate_system_acceptance_pending", extra: dict | None = None,
mlx_compute_dtype: str | None = "float32",
mlx_cache_limit_gib: float | None = MLX_CACHE_LIMIT_GIB) -> dict:
"""Write release_config.json with sha256 of every weight file under the listed backend paths.
``backend=None`` = first of ``DEFAULT_BACKEND_ORDER`` present in ``backends`` (llama.cpp
GGUF F16 when the release ships it)."""
release = Path(release)
if not 0 < int(max_len) <= CONTEXT_LIMIT or head_max > HARD_HEAD_MAX:
raise ValueError(f"budgets must satisfy max_len <= {CONTEXT_LIMIT} and head_max <= {HARD_HEAD_MAX}")
backend = backend or next((b for b in DEFAULT_BACKEND_ORDER if b in backends), None)
if backend not in backends:
raise ValueError(f"default backend {backend!r} not in backends {sorted(backends)}")
files = {}
for rel in set(backends.values()) | {tokenizer}:
p = release / rel
for f in ([p] if p.is_file() else sorted(x for x in p.rglob("*") if x.is_file() and not x.is_symlink())):
if f.suffix in (".safetensors", ".gguf", ".json", ".jinja", ".txt", ".model"):
files[str(f.relative_to(release))] = _sha256(f)
cfg = {"format": RELEASE_FORMAT, "model_name": model_name, "readout": readout, "backend": backend,
"backends": backends, "tokenizer": tokenizer, "temperatures": temperatures or {"global": 1.0, "groups": {}},
"runtime_category": runtime_category, "budgets": {"max_len": int(max_len), "head_max": head_max},
"mlx_compute_dtype": mlx_compute_dtype, "mlx_cache_limit_gib": mlx_cache_limit_gib,
"acceptance_status": acceptance_status, "files": files, **(extra or {})}
(release / "release_config.json").write_text(json.dumps(cfg, indent=2))
return cfg
|