Run this model with HF Jobs
Run Xylolabs/openpilot-Chestnut-MLX on Hugging Face's managed compute, monitor its progress, and retrieve the results when it's done.
Paste one of these prompts into your coding agent:
Fine-tune on my dataset
Use HF Jobs to fine-tune https://huggingface.co/Xylolabs/openpilot-Chestnut-MLX. Ask me which dataset to train on, then push the fine-tuned model to a new model repo. Run `hf jobs --help` first to learn the CLI.
Run batch inference
Use HF Jobs to run batch inference with https://huggingface.co/Xylolabs/openpilot-Chestnut-MLX on the inputs in a mounted HF Bucket. Ask me which Bucket to use, then write the outputs back to it and keep each input ID. Run `hf jobs --help` first to learn the CLI.
Instructions to use Xylolabs/openpilot-Chestnut-MLX with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- MLX
How to use Xylolabs/openpilot-Chestnut-MLX with MLX:
# Download the model from the Hub pip install huggingface_hub[hf_xet] hf download Xylolabs/openpilot-Chestnut-MLX --local-dir openpilot-Chestnut-MLX
- Notebooks
- Google Colab
- Kaggle
- Local Apps Settings
- LM Studio
- Atomic Chat
Stage parity.py
Browse files123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217"""Compare MLX outputs with the bundled ONNX Runtime reference cases."""
import argparseimport hashlibimport jsonfrom pathlib import Path
import mlx.core as mximport numpy as np
from model import Model
REL_FLOOR = 1e-8MIN_PCC = 0.999MAX_NRMSE = 0.02MAX_ABS_ESCAPE = 1e-4ROOT = 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 reference_cases(directory, onnx_path): manifest = json.loads((ROOT / "references" / "manifest.json").read_text()) program = json.loads((ROOT / "program.json").read_text()) graph_path = ROOT / "graph.json" verify(graph_path, manifest["graph_summary_sha256"]) reference = json.loads(graph_path.read_text())["reference_onnx"] if reference["sha256"] != manifest["reference_onnx_sha256"]: raise ValueError("The reference ONNX records differ") if onnx_path is not None: verify(onnx_path, reference["sha256"], reference["bytes"]) verify(ROOT / "model.safetensors", program["weights_sha256"], program["weights_bytes"])
frames = manifest["frames_per_case"] cases = sorted(manifest["cases"], key=lambda case: case["seed"]) if frames != 12 or [case["seed"] for case in cases] != list(range(4)): 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 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} in {path}") 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']} in {path}")
queue_names = [name for name in model.inputs if name.startswith("state_")] heads = {item["name"]: slice(item["start"], item["stop"]) for item in model.graph["output_slices"]} vectors = [] 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()} vectors.append(actual["outputs"])
if queue_names: checks = check_movement(inputs, actual, heads["hidden_state"]) checks.update({f"{name} vs reference": bits_equal(actual[name], data[name][frame]) for name in ("next_state_img_q", "next_state_desire_q")}) 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 queue_names: name = "next_state_feat_q" readings = measure(data[name][-1], actual[name]) observations.setdefault((name, "final queue per case"), []).append({"seed": seed, **readings})
prediction = np.stack(vectors) for name, section in heads.items(): r, a = data["outputs"][..., section], prediction[..., 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 reference ONNX file") 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())parity.pyAdded+217