Run this model with HF Jobs
Run Xylolabs/openpilot-driving-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-driving-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-driving-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-driving-MLX with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- MLX
How to use Xylolabs/openpilot-driving-MLX with MLX:
# Download the model from the Hub pip install huggingface_hub[hf_xet] hf download Xylolabs/openpilot-driving-MLX --local-dir openpilot-driving-MLX
- Notebooks
- Google Colab
- Kaggle
- Local Apps Settings
- LM Studio
- Atomic Chat
Stage model.py
Browse files123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157"""An openpilot frame graph expressed in MLX operations.
Load Model() beside its graph and safetensors files. Pass MLX arrays bygraph input name and feed each next_state_* back as state_* on the next call."""
import hashlibimport jsonfrom itertools import zip_longestfrom pathlib import Path
import mlx.core as mximport mlx.nn as nn
_DTYPE = {"float32": mx.float32, "uint8": mx.uint8}_SIMPLE = { "Add": mx.add, "Div": mx.divide, "MatMul": mx.matmul, "Mul": mx.multiply, "Not": mx.logical_not, "Relu": nn.relu, "Sigmoid": mx.sigmoid, "Sub": mx.subtract, "Tanh": mx.tanh, "Where": mx.where, "org.tinygrad::Contiguous": mx.contiguous,}
def _run(op, args, attrs): if op in _SIMPLE: return _SIMPLE[op](*args) x = args[0] match op: case "Cast": return x.astype(_DTYPE[attrs["to"]]) case "Clip": return mx.maximum(x, args[1]) case "Concat": return mx.concatenate(args, axis=attrs["axis"]) case "Conv": y = mx.conv2d( x.transpose(0, 2, 3, 1), args[1], stride=tuple(attrs["strides"]), padding=tuple(attrs["pads"][:2]), dilation=tuple(attrs["dilations"]), groups=attrs["group"], ) return (y + args[2]).transpose(0, 3, 1, 2) case "Expand": target = args[1].tolist() dims = zip_longest(reversed(x.shape), reversed(target), fillvalue=1) shape = tuple(want if have == 1 else have for have, want in dims) return mx.broadcast_to(x, shape[::-1]) case "Gather": return mx.take(x, args[1], axis=attrs["axis"]) case "GatherND": indices = args[1] return x[tuple(indices[..., i] for i in range(indices.shape[-1]))] case "Gelu": gelu = nn.gelu_approx if attrs["approximate"] == "tanh" else nn.gelu return gelu(x) case "Gemm": rhs = args[1].T return mx.addmm(args[2], x, rhs) if len(args) == 3 else x @ rhs case "Identity": return x case "LayerNormalization": return mx.fast.layer_norm(x, args[1], args[2], attrs["epsilon"]) case "ReduceL2" | "ReduceMax" | "ReduceMean": axes = tuple(args[1].tolist()) keepdims = bool(attrs["keepdims"]) if op == "ReduceL2": return mx.sqrt(mx.sum(mx.square(x), axis=axes, keepdims=keepdims)) reduce = mx.max if op == "ReduceMax" else mx.mean return reduce(x, axis=axes, keepdims=keepdims) case "Reshape": shape = args[1].tolist() if not attrs.get("allowzero", 0): shape = [size or x.shape[i] for i, size in enumerate(shape)] return x.reshape(shape) case "Slice": starts, ends, axes = (value.tolist() for value in args[1:4]) steps = args[4].tolist() if len(args) == 5 else [1] * len(axes) slices = [slice(None)] * x.ndim for start, end, axis, step in zip(starts, ends, axes, steps, strict=True): size = x.shape[axis] # The ONNX endpoints can be INT64 sentinels. MLX takes int32 indices. start = min(size, max(-size - 1, start)) end = min(size, max(-size - 1, end)) slices[axis] = slice(start, end, step) return x[tuple(slices)] case "Softmax": return mx.softmax(x, axis=attrs["axis"], precise=True) case "Split": return mx.split(x, attrs["num_outputs"], axis=attrs["axis"]) case "Squeeze": return mx.squeeze(x, axis=tuple(args[1].tolist())) case "Transpose": return x.transpose(attrs["perm"]) case "Unsqueeze": return mx.expand_dims(x, axis=tuple(args[1].tolist())) case _: raise ValueError(f"Unsupported graph operator {op!r}")
def _validate(values, specs): if values.keys() != specs.keys(): raise ValueError(f"Expected {sorted(specs)}, received {sorted(values)}") for name, value in values.items(): shape, dtype = specs[name] if value.shape != shape or value.dtype != dtype: raise ValueError(f"{name} must have shape {shape} and dtype {dtype}")
class Model: """Load a staged model directory and evaluate one frame per call."""
def __init__(self, directory=None): self.directory = Path(directory) if directory is not None else Path(__file__).resolve().parent program = json.loads((self.directory / "program.json").read_text()) graph_bytes = (self.directory / "graph.json").read_bytes() if program["version"] != 1 or hashlib.sha256(graph_bytes).hexdigest() != program["graph_sha256"]: raise ValueError("Program and graph summary do not match") self.graph = json.loads(graph_bytes) self.inputs, self.outputs = ( {item["name"]: (tuple(item["shape"]), _DTYPE[item["dtype"]]) for item in self.graph[key]} for key in ("inputs", "outputs") ) weights = mx.load(str(self.directory / "model.safetensors")) # Widen the exact stored halves once for the FP32 reference graph. self._weights = { name: value.astype(mx.float32) if value.dtype == mx.float16 else value for name, value in weights.items() } mx.eval(*self._weights.values()) self._nodes = program["nodes"]
def initial_state(self): return {name: mx.zeros(shape, dtype) for name, (shape, dtype) in self.inputs.items() if name.startswith("state_")}
def __call__(self, **inputs): _validate(inputs, self.inputs) values = self._weights | inputs for op, names, outputs, attrs in self._nodes: try: result = _run(op, [values[name] for name in names], attrs) except (KeyError, TypeError, ValueError, RuntimeError) as exc: raise RuntimeError(f"{op} producing {', '.join(outputs)}") from exc if len(outputs) == 1: values[outputs[0]] = result else: values.update(zip(outputs, result, strict=True)) result = {name: values[name] for name in self.outputs} _validate(result, self.outputs) return resultmodel.pyAdded+157