"""Compare MLX outputs with the bundled ONNX Runtime reference cases.""" import argparse import hashlib import json from pathlib import Path import mlx.core as mx import numpy as np from model import Model REL_FLOOR = 1e-8 MIN_PCC = 0.999 MAX_NRMSE = 0.02 MAX_ABS_ESCAPE = 1e-4 ROOT = Path(__file__).resolve().parent def sha256(path): with path.open("rb") as file: return hashlib.file_digest(file, "sha256").hexdigest() def verify(path, digest, size=None): if (size is not None and path.stat().st_size != size) or sha256(path) != digest: raise ValueError(f"Checksum or size mismatch for {path}") def verify_onnx(path, reference): parts = reference.get("components") if parts is None: verify(path, reference["sha256"], reference["bytes"]) return if not path.is_dir(): raise ValueError("For a split graph, --reference-onnx takes the directory with both FP32 files") descriptor = (json.dumps(parts, indent=2, ensure_ascii=False, allow_nan=False) + "\n").encode() if (sum(part["bytes"] for part in parts) != reference["bytes"] or hashlib.sha256(descriptor).hexdigest() != reference["sha256"]): raise ValueError("The split reference ONNX records differ") for part in parts: verify(path / part["file"], part["sha256"], part["bytes"]) def reference_cases(directory, onnx_path): manifest_path = directory / "manifest.json" if not manifest_path.is_file(): manifest_path = ROOT / "references" / "manifest.json" manifest = json.loads(manifest_path.read_text()) program = json.loads((ROOT / "program.json").read_text()) graph_path = ROOT / "graph.json" verify(graph_path, manifest["graph_summary_sha256"]) graph = json.loads(graph_path.read_text()) reference = graph["reference_onnx"] if not (reference["sha256"] == manifest["reference_onnx_sha256"] == program["reference_onnx_sha256"]): raise ValueError("The reference ONNX records differ") if onnx_path is not None: verify_onnx(onnx_path, reference) verify(ROOT / "model.safetensors", program["weights_sha256"], program["weights_bytes"]) frames = manifest["frames_per_case"] cases = sorted(manifest["cases"], key=lambda case: case["seed"]) seeds = [case["seed"] for case in cases] if frames != 12 or seeds != [0, 1, 2, 3]: raise ValueError("Expected four 12-frame reference cases") paths = [] for case in cases: path = directory / f"seed-{case['seed']}.npz" if path.name != case["file"]: raise ValueError(f"Unexpected archive name {case['file']}") verify(path, case["sha256"], case["bytes"]) paths.append(path) return manifest["model"], frames, paths def measure(reference, actual, *, signed=False): r = reference.astype(np.float64).ravel() a = actual.astype(np.float64).ravel() if not (np.isfinite(r).all() and np.isfinite(a).all()): return {"max_abs": None, "max_rel": None, "pcc": None, "nrmse": None, "sign_match": None, "passed": False} error = np.abs(a - r) max_abs = float(error.max()) max_rel = float(np.max(error / np.maximum(np.abs(r), REL_FLOOR))) nrmse = float(np.sqrt(np.mean(error ** 2)) / max(np.sqrt(np.mean(r ** 2)), REL_FLOOR)) same_sign = bool(np.array_equal(np.sign(a), np.sign(r))) if signed else None if max_abs == 0: pcc = 1.0 elif r.min() == r.max() or a.min() == a.max(): pcc = 0.0 else: r -= np.mean(r) a -= np.mean(a) pcc = float(np.clip(np.dot(r, a) / (np.linalg.norm(r) * np.linalg.norm(a)), -1, 1)) passed = (max_abs <= MAX_ABS_ESCAPE or (pcc >= MIN_PCC and nrmse <= MAX_NRMSE and same_sign is not False)) return {"max_abs": max_abs, "max_rel": max_rel, "pcc": pcc, "nrmse": nrmse, "sign_match": same_sign, "passed": passed} def bits_equal(a, b): if a.shape != b.shape or a.dtype != b.dtype: return False bits = f"u{a.dtype.itemsize}" return np.array_equal(a.view(bits), b.view(bits)) def check_movement(inputs, outputs, hidden): image = outputs["next_state_img_q"] desire = outputs["next_state_desire_q"] features = outputs["next_state_feat_q"] return { "image shift and append": (bits_equal(image[:, :-1], np.asarray(inputs["state_img_q"])[:, 1:]) and bits_equal(image[:, -1], np.asarray(inputs["new_img"]))), "desire shift and append": (bits_equal(desire[:-1], np.asarray(inputs["state_desire_q"])[1:]) and bits_equal(desire[-1, 0], np.asarray(inputs["desire"]))), "feature shift and append": (bits_equal(features[:-1], np.asarray(inputs["state_feat_q"])[1:]) and bits_equal(features[-1], outputs["outputs"][..., hidden])), } def historical_checks(rules, inputs, outputs, reference, frame): checks = {} for state, rule in rules.items(): name = f"next_{state}" after = outputs[name] source = (np.asarray(inputs[rule["source"]]) if rule["after"] == "input" else outputs[rule["source"]]) if rule["head"] is not None: start, stop = rule["head"] source = source[..., start:stop] checks[f"{state} append"] = bits_equal(after[:, -1] if rule["queue"] else after, source) if rule["queue"]: checks[f"{state} shift"] = bits_equal(after[:, :-1], np.asarray(inputs[state])[:, 1:]) if rule["after"] == "input": checks[f"{state} vs reference"] = bits_equal(after, reference[name][frame]) return checks def compare_case(model, path, seed, frames, observations, exact): with np.load(path, allow_pickle=False) as archive: data = {name: archive[name] for name in archive.files} fixed, frame_inputs = {}, {} for name, (shape, _) in model.inputs.items(): if data[name].shape == shape: fixed[name] = mx.array(data[name]) elif data[name].shape == (frames, *shape) and not name.startswith("state_"): frame_inputs[name] = data[name] else: raise ValueError(f"Unexpected input shape for {name}") for spec in model.graph["outputs"]: value = data[spec["name"]] if value.shape != (frames, *spec["shape"]) or value.dtype != np.dtype(spec["dtype"]): raise ValueError(f"Unexpected reference shape or dtype for {spec['name']}") queue_names = [name for name in model.inputs if name.startswith("state_")] heads = model.graph["output_slices"] history = {head.get("tensor", "outputs"): [] for head in heads} rules = model.graph.get("state_rules") if queue_names and rules is None: hidden = next(slice(head["start"], head["stop"]) for head in heads if head["name"] == "hidden_state") for frame in range(frames): inputs = fixed | {name: mx.array(value[frame]) for name, value in frame_inputs.items()} outputs = model(**inputs) mx.eval(*outputs.values()) actual = {name: np.asarray(value) for name, value in outputs.items()} for name, values in history.items(): values.append(actual[name]) if rules is not None: checks = historical_checks(rules, inputs, actual, data, frame) elif queue_names: checks = check_movement(inputs, actual, hidden) checks.update({f"{name} vs reference": bits_equal(actual[name], data[name][frame]) for name in ("next_state_img_q", "next_state_desire_q")}) else: checks = {} for name, passed in checks.items(): exact.setdefault(name, []).append({"seed": seed, "frame": frame, "passed": passed}) for name in queue_names: fixed[name] = outputs[f"next_{name}"] if rules is not None: final_states = [f"next_{name}" for name, rule in rules.items() if rule["after"] != "input"] scope = "final state per case" else: final_states = ["next_state_feat_q"] if queue_names else [] scope = "final queue per case" for name in final_states: readings = measure(data[name][-1], actual[name]) observations.setdefault((name, scope), []).append({"seed": seed, **readings}) predictions = {tensor: np.stack(values) for tensor, values in history.items()} for head in heads: tensor, name = head.get("tensor", "outputs"), head["name"] section = slice(head["start"], head["stop"]) r, a = data[tensor][..., section], predictions[tensor][..., section] if section.stop - section.start == 1: readings = measure(r, a, signed=True) observations.setdefault((name, "series per case"), []).append({"seed": seed, **readings}) else: rows = observations.setdefault((name, "per frame"), []) for frame in range(frames): readings = measure(r[frame], a[frame]) rows.append({"seed": seed, "frame": frame, **readings}) def summarize(name, scope, rows): summary = {"name": name, "scope": scope, "checks": len(rows), "failures": [row for row in rows if not row["passed"]]} for result_key, metric, choose in (("max_abs", "max_abs", max), ("max_rel", "max_rel", max), ("min_pcc", "pcc", min), ("max_nrmse", "nrmse", max)): summary[result_key] = choose((row[metric] for row in rows if row[metric] is not None), default=None) return summary def show(results): print(f"MLX {results['mlx']} CPU, max rel = |actual - ref| / max(|ref|, {REL_FLOOR:g})") print("| Head or final state | Scope | Checks | Max abs | Max rel | Min PCC | Max nRMSE | Result |") print("| --- | --- | ---: | ---: | ---: | ---: | ---: | --- |") for row in results["metrics"]: metrics = [f"{row[key]:.9g}" if row[key] is not None else "n/a" for key in ("max_abs", "max_rel", "min_pcc", "max_nrmse")] status = "FAIL" if row["failures"] else "PASS" print("| " + " | ".join([row["name"], row["scope"], str(row["checks"]), *metrics, status]) + " |") for failure in row["failures"]: print(json.dumps(failure)) if results["exact"]: print("\n| State data movement | Bitwise exact |") print("| --- | ---: |") for name, row in results["exact"].items(): print(f"| {name} | {row['checks'] - len(row['failures'])}/{row['checks']} |") for failure in row["failures"]: print(json.dumps(failure)) def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--references", type=Path, default=ROOT / "references", help="read the reference archives from this directory") parser.add_argument("--reference-onnx", type=Path, help="verify a local FP32 ONNX file or directory for a split graph") parser.add_argument("--json", type=Path, help="write the parity metrics as JSON") args = parser.parse_args() name, frames, paths = reference_cases(args.references, args.reference_onnx) mx.set_default_device(mx.cpu) model = Model() observations, exact = {}, {} for seed, path in enumerate(paths): print(f"{name} seed {seed} ({frames} frames)", flush=True) compare_case(model, path, seed, frames, observations, exact) results = { "model": name, "mlx": mx.__version__, "numpy": np.__version__, "frames": frames * len(paths), "relative_floor": REL_FLOOR, "metrics": [summarize(head, scope, rows) for (head, scope), rows in observations.items()], "exact": {name: {"checks": len(rows), "failures": [row for row in rows if not row["passed"]]} for name, rows in exact.items()}, } results["passed"] = not any(row["failures"] for row in [*results["metrics"], *results["exact"].values()]) show(results) if args.json is not None: args.json.write_text(json.dumps(results, indent=2, allow_nan=False) + "\n") return 0 if results["passed"] else 1 if __name__ == "__main__": raise SystemExit(main())