File size: 16,486 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 | """Release packaging: one export (``macjev.export.cli``) + fitted temperatures -> a release directory.
``python -m macjev.export.release --export <export_dir> --temperatures <temperatures.json>
--parity <export_dir>/parity/report.json --out <release_dir> --model-name "MacJev-0.8B <version>"``
Writes (every weight file is hash-checked against the export manifests before and after copying)::
text-only/ HF Qwen3_5ForCausalLM without vision/MTP (+ tokenizer; torch fallback)
gguf/model-{f16,q8_0,q4_k_m}.gguf
mlx/{bf16,affine8-g64,affine4-g64}/
readout_config.json readout, slot token ids (" yes"/" no"/" ->"/letters), tokenizer sha256,
temperatures, budgets, render template
release_config.json macjev.runtime.engine.write_release_config (runtime backends = only the
16-bit formats that passed G5; readout config folded in)
release_manifest.json sha256 + bytes of every file, per-format quant + G5 verdict, source export
G5 handling (thresholds live in ``macjev.export.parity``; nothing here relaxes them): every requested
format is packaged, with its G5 verdict from the parity report recorded next to it. Only formats
whose gated verdict passed become runtime backends (llama.cpp <- gguf-f16, mlx <- mlx-bf16 run with
fp32 activations, i.e. the ``mlx-bf16-f32act`` verdict). 4-bit formats are report-only (plan G5:
reported, never claimed). The parity report must belong to this export (its ``cache_key.json``
text-only hashes must match); without a report the release is refused unless ``--allow-no-parity``,
which marks it ``g5_not_run``; a failed report appends ``+g5_fail`` to ``acceptance_status``. Temperatures must be a ``macjev-temperatures-v1`` fit unless
``--allow-uncalibrated`` (T = 1, marked uncalibrated).
"""
from __future__ import annotations
import argparse
import json
import os
import shutil
import time
from pathlib import Path
from .convert import GGUF_FORMATS, MLX_FORMATS, text_only_id
from .text_only import sha256_file
MANIFEST_FORMAT = "macjev-release-manifest-v1"
READOUT_FORMAT = "macjev-readout-v1"
# runtime backend -> (exported format, the parity entry that must pass for it)
BACKEND_FORMATS = {"llama.cpp": ("gguf-f16", "gguf-f16"), "mlx": ("mlx-bf16", "mlx-bf16-f32act")}
def format_relpath(fmt: str) -> str:
if fmt in GGUF_FORMATS:
return f"gguf/model-{GGUF_FORMATS[fmt][0]}.gguf"
return f"mlx/{MLX_FORMATS[fmt][0]}"
def _files(p: Path) -> list[Path]:
if p.is_file():
return [p]
return sorted(x for x in p.rglob("*") if x.is_file())
def _place(src: Path, dst: Path, link: str) -> None:
dst.parent.mkdir(parents=True, exist_ok=True)
if link == "hard":
try:
os.link(src.resolve(), dst)
return
except OSError: # cross-device: fall back to a copy
pass
shutil.copy2(src.resolve(), dst)
def expected_hashes(export_dir: Path, fmt: str, export_manifest: dict) -> dict:
"""{filename: sha256} the export recorded for ``fmt`` (weights only)."""
if fmt in GGUF_FORMATS:
rec = (export_manifest.get("gguf") or {}).get(fmt)
if not rec:
raise FileNotFoundError(f"{fmt} not in export_manifest.json (not exported)")
return {Path(rec["path"]).name: rec["sha256"]}
rec = (export_manifest.get("mlx") or {}).get(fmt)
if not rec:
raise FileNotFoundError(f"{fmt} not in export_manifest.json (not exported)")
return dict(rec["sha256"])
def g5_verdicts(parity_report: Path | None, export_dir: Path, readout: str) -> tuple[dict, dict]:
"""(per-format verdicts for ``readout``, summary). Refuses a report of a different export."""
if parity_report is None:
return {}, {"status": "g5_not_run"}
rep = json.loads(Path(parity_report).read_text())
key_path = Path(parity_report).parent / "cache_key.json"
if not key_path.exists():
raise ValueError(f"{key_path} missing: cannot tie the parity report to this export")
key = json.loads(key_path.read_text())
if key.get("text_only") != text_only_id(export_dir / "text-only"):
raise ValueError("parity report was computed on a different text-only checkpoint than this export")
res = (rep.get("results") or {}).get(readout)
if not res:
raise ValueError(f"parity report has no {readout!r} readout results")
out = {}
for fmt, m in res.items():
if isinstance(m, dict) and "verdict" in m:
out[fmt] = {"pass": bool(m["verdict"]["pass"]), "gate": m["verdict"]["gate"],
"n": m["n"], "top1_agreement": m["top1_agreement"], "dnll": m["dnll"],
"nan_rows": m["nan_rows"]}
summary = {"status": "g5_pass" if rep.get("g5_pass") else "g5_fail", "g5_pass": bool(rep.get("g5_pass")),
"g5_failures": rep.get("g5_failures", []), "g5_blockers": rep.get("g5_blockers", []),
"rows": (rep.get("fixture") or {}).get("n"), "reference": rep.get("reference"),
"report_sha256": sha256_file(Path(parity_report))}
return out, summary
def readout_config(tokenizer_dir: Path, readout: str, temperatures: dict, head_max: int) -> dict:
from transformers import AutoTokenizer
from ..render import CONTEXT_LIMIT, LETTERS, TEMPLATE_VERSION, Renderer
tok = AutoTokenizer.from_pretrained(str(tokenizer_dir))
r = Renderer(tok, readout, head_max=head_max)
tj = tokenizer_dir / "tokenizer.json"
return {"format": READOUT_FORMAT, "readout": readout, "template": TEMPLATE_VERSION,
"slot_tokens": {"yes": {"text": " yes", "id": r.tokens.yes}, "no": {"text": " no", "id": r.tokens.no},
"verdict_slot": {"text": " ->", "id": r._arrow[0]},
"letters": {ch: i for ch, i in zip(LETTERS, r.tokens.letters)}},
"score": ("per option: logit[yes] - logit[no] at that option's ' ->' slot (fp32)" if readout == "verdict"
else "logits of the option letters at the single 'Answer:' slot"),
"probabilities": "softmax(scores / T), T = macjev.eval.calibration.lookup(temperatures, row)",
"tokenizer_sha256": sha256_file(tj) if tj.exists() else None,
"budgets": {"max_len": CONTEXT_LIMIT, "head_max": head_max}, "temperatures": temperatures}
def build_release(export_dir: str | Path, out: str | Path, *, model_name: str, temperatures: str | Path | None,
parity_report: str | Path | None, formats: list[str] | None = None, readout: str = "verdict",
link: str = "copy", allow_no_parity: bool = False, allow_uncalibrated: bool = False,
head_max: int = 1024, smoke: bool = False) -> dict:
from ..eval import calibration
from ..runtime.engine import write_release_config
export_dir, out = Path(export_dir), Path(out)
em_path = export_dir / "export_manifest.json"
export_manifest = json.loads(em_path.read_text())
formats = formats or list(export_manifest.get("formats") or [])
if not formats:
raise ValueError("no formats requested and none recorded in export_manifest.json")
if out.exists() and any(out.iterdir()):
raise FileExistsError(f"{out} is not empty; releases are never overwritten in place")
if parity_report is None and not allow_no_parity:
raise ValueError("no parity report (G5); pass --parity <report.json> or --allow-no-parity")
verdicts, g5 = g5_verdicts(Path(parity_report) if parity_report else None, export_dir, readout)
if temperatures:
temps = json.loads(Path(temperatures).read_text())
if temps.get("version") != calibration.VERSION:
raise ValueError(f"temperatures version {temps.get('version')!r} != {calibration.VERSION}")
calibrated = True
elif allow_uncalibrated:
temps, calibrated = {"version": calibration.VERSION, "global": 1.0, "groups": {}}, False
else:
raise ValueError("no temperatures; pass --temperatures <temperatures.json> or --allow-uncalibrated")
# 1. verify the source files against the export manifests ({release-relative path: sha256})
to_only = export_dir / "text-only"
tman = json.loads((to_only / "text_only_manifest.json").read_text())
expect = {f"text-only/{n}": h for n, h in tman["files"].items()}
for fmt in formats:
rel = format_relpath(fmt)
for n, h in expected_hashes(export_dir, fmt, export_manifest).items():
expect[rel if fmt in GGUF_FORMATS else f"{rel}/{n}"] = h
for rel, h in expect.items():
if sha256_file(export_dir / rel) != h:
raise RuntimeError(f"export integrity error: {export_dir / rel} does not match its export manifest")
# 2. place files (the MLX staging dir and anything outside the requested formats stay behind)
out.mkdir(parents=True, exist_ok=True)
for rel in ["text-only"] + [format_relpath(f) for f in formats]:
src = export_dir / rel
for f in _files(src):
_place(f, out / rel / f.relative_to(src) if src.is_dir() else out / rel, link)
for rel, h in expect.items(): # after copy: same bytes
if sha256_file(out / rel) != h:
raise RuntimeError(f"release integrity error after copy: {out / rel}")
# 3. readout config + runtime config
rcfg = readout_config(out / "text-only", readout, temps, head_max)
(out / "readout_config.json").write_text(json.dumps(rcfg, indent=2))
backends, backend_notes = {}, {}
for be, (fmt, gate_key) in BACKEND_FORMATS.items():
if fmt not in formats:
continue
v = verdicts.get(gate_key)
if parity_report is None or (v and v["pass"]):
backends[be] = format_relpath(fmt)
else:
backend_notes[be] = f"{gate_key} G5 " + ("failed" if v else "not in parity report") + "; not a runtime backend"
backends["torch"] = "text-only"
status = "candidate_system_acceptance_pending" if parity_report is not None else "g5_not_run"
if parity_report is not None and not g5.get("g5_pass"):
# review fix 2026-09-24: a release whose G5 report failed (any gated format, or a blocker) says so
# in the status every runtime result carries, not only in release_manifest.json's g5 block
status += "+g5_fail"
if not calibrated:
status += "+uncalibrated"
cfg = write_release_config(out, model_name=model_name, backends=backends, temperatures=temps, readout=readout,
head_max=head_max, acceptance_status=status,
extra={"readout_config": "readout_config.json", "slot_tokens": rcfg["slot_tokens"],
"template": rcfg["template"], "calibrated": calibrated, "g5": g5,
"backend_notes": backend_notes})
# 4. manifest over every file
fmts = {}
for fmt in formats:
rel = format_relpath(fmt)
rec = (export_manifest.get("gguf") or {}).get(fmt) or (export_manifest.get("mlx") or {}).get(fmt) or {}
fmts[fmt] = {"path": rel, "quant": rec.get("quant"),
"bytes": sum(f.stat().st_size for f in _files(out / rel)),
"g5": verdicts.get(fmt, {"status": "not_run" if parity_report is None else "not_in_report"})}
if "mlx-bf16-f32act" in verdicts:
fmts.setdefault("mlx-bf16", {})["g5_fp32_activations"] = verdicts["mlx-bf16-f32act"]
files = {str(f.relative_to(out)): {"sha256": sha256_file(f), "bytes": f.stat().st_size}
for f in _files(out) if f.name != "release_manifest.json"}
manifest = {"format": MANIFEST_FORMAT, "model_name": model_name, "created_unix": time.time(), "readout": readout,
"source": {"export_dir": str(export_dir.resolve()), "weights": export_manifest.get("weights"),
"base": export_manifest.get("base"), "export_manifest_sha256": sha256_file(em_path),
"text_only_source": tman.get("source_fingerprint"),
"llama_cpp_commit": export_manifest.get("llama_cpp_commit"),
"mlx": (export_manifest.get("mlx") or {}).get("mlx"),
"mlx_lm": (export_manifest.get("mlx") or {}).get("mlx_lm")},
"formats": fmts, "runtime_backends": cfg["backends"], "default_backend": cfg["backend"],
"backend_notes": backend_notes, "g5": g5, "calibrated": calibrated, "acceptance_status": status,
"files": files}
(out / "release_manifest.json").write_text(json.dumps(manifest, indent=2))
if smoke: # every exported runtime backend loads (hash-verified) and answers; torch (MPS) is skipped
from ..runtime.engine import DecisionEngine
q = {"t": "noul", "ins": "Is the task done?", "crit": None}
manifest["smoke"] = {}
for be in [b for b in cfg["backends"] if b != "torch"]:
eng = DecisionEngine(out, backend=be, verify=True)
r = eng.decide({"goal": "smoke"}, q)
manifest["smoke"][be] = {"backend": r["backend"], "answer": r["answer"], "backend_note": r["backend_note"]}
if hasattr(eng.backend, "close"):
eng.backend.close()
del eng
(out / "release_manifest.json").write_text(json.dumps(manifest, indent=2))
return manifest
def verify_release(release: str | Path) -> dict:
"""Re-hash every file listed in release_manifest.json; returns {"ok", "bad", "missing", "extra"}."""
release = Path(release)
man = json.loads((release / "release_manifest.json").read_text())
bad = [n for n, r in man["files"].items() if (release / n).exists() and sha256_file(release / n) != r["sha256"]]
missing = [n for n in man["files"] if not (release / n).exists()]
extra = [str(f.relative_to(release)) for f in _files(release)
if f.name != "release_manifest.json" and str(f.relative_to(release)) not in man["files"]]
return {"ok": not (bad or missing or extra), "bad": bad, "missing": missing, "extra": extra}
def main(argv=None) -> int:
ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
ap.add_argument("--export", help="output dir of macjev.export.cli (required unless --verify)")
ap.add_argument("--out", required=True)
ap.add_argument("--model-name", help="required unless --verify")
ap.add_argument("--temperatures", help="temperatures.json from macjev.eval.calibrate")
ap.add_argument("--parity", help="G5 report.json of this export (default <export>/parity/report.json if present)")
ap.add_argument("--formats", help="comma list (default: every format in export_manifest.json)")
ap.add_argument("--readout", default="verdict", choices=["verdict", "letter"])
ap.add_argument("--link", default="copy", choices=["copy", "hard"])
ap.add_argument("--allow-no-parity", action="store_true")
ap.add_argument("--allow-uncalibrated", action="store_true")
ap.add_argument("--no-smoke", action="store_true")
ap.add_argument("--verify", action="store_true", help="only re-hash an existing release (--out)")
a = ap.parse_args(argv)
if a.verify:
r = verify_release(a.out)
print(json.dumps(r, indent=2))
return 0 if r["ok"] else 4
if not a.export or not a.model_name: # review fix 2026-09-24: --verify --out <release> needs neither
ap.error("--export and --model-name are required to build a release")
parity = a.parity or (str(Path(a.export) / "parity" / "report.json")
if (Path(a.export) / "parity" / "report.json").exists() else None)
m = build_release(a.export, a.out, model_name=a.model_name, temperatures=a.temperatures, parity_report=parity,
formats=[f.strip() for f in a.formats.split(",")] if a.formats else None, readout=a.readout,
link=a.link, allow_no_parity=a.allow_no_parity, allow_uncalibrated=a.allow_uncalibrated,
smoke=not a.no_smoke)
print(json.dumps({k: m[k] for k in ("runtime_backends", "default_backend", "backend_notes", "g5",
"acceptance_status")} | {"n_files": len(m["files"])}, indent=2))
return 0
if __name__ == "__main__":
raise SystemExit(main())
|