MLX
Safetensors

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.
File size: 10,760 Bytes
b406f95
 
 
 
 
 
 
 
e9113c0
 
b406f95
 
 
 
 
 
e9113c0
 
 
 
 
 
b406f95
e9113c0
 
 
b406f95
 
 
 
e9113c0
 
 
 
 
b406f95
 
 
 
e9113c0
 
 
 
b406f95
 
 
e9113c0
 
 
 
 
 
 
b406f95
 
e9113c0
 
b406f95
e9113c0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b406f95
e9113c0
 
 
 
 
b406f95
e9113c0
b406f95
e9113c0
 
 
 
b406f95
e9113c0
b406f95
 
e9113c0
 
 
 
 
 
 
 
 
b406f95
 
 
e9113c0
 
 
 
 
 
 
 
 
 
 
b406f95
e9113c0
 
 
b406f95
e9113c0
b406f95
e9113c0
b406f95
e9113c0
 
b406f95
e9113c0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b406f95
e9113c0
 
 
 
 
 
b406f95
e9113c0
 
 
b406f95
e9113c0
 
 
 
b406f95
e9113c0
b406f95
e9113c0
 
b406f95
e9113c0
b406f95
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e9113c0
b406f95
 
 
 
 
 
 
 
 
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
"""An openpilot frame graph expressed in MLX operations.

Load Model() beside its graph and safetensors files. Pass MLX arrays by
graph input name and feed each next_state_* back as state_* on the next call.
"""

import hashlib
import json
from itertools import accumulate, zip_longest
from math import prod
from pathlib import Path

import mlx.core as mx
import mlx.nn as nn


_DTYPE = {
    name: getattr(mx, name) for name in
    ("bool_", "uint8", "int8", "int16", "int32", "int64", "float16", "float32")
}
_DTYPE["bool"] = _DTYPE["bool_"]

_SIMPLE = {
    "Add": mx.add, "Div": mx.divide, "MatMul": mx.matmul, "Mul": mx.multiply,
    "Not": mx.logical_not, "Pow": mx.power, "Relu": nn.relu, "Sigmoid": mx.sigmoid, "Sqrt": mx.sqrt,
    "Sub": mx.subtract, "Tanh": mx.tanh, "Where": mx.where,
    "org.tinygrad::Contiguous": mx.contiguous,
}


def _axes(input_value, attrs, key="axes"):
    return tuple(input_value.tolist()) if input_value is not None else attrs.get(key)


def _run(op, args, attrs, outputs):
    if op in _SIMPLE:
        return _SIMPLE[op](*args)
    x = args[0]
    match op:
        case "BatchNormalization":
            shape = (1, -1) + (1,) * (x.ndim - 2)
            scale, bias, mean, variance = (a.reshape(shape) for a in args[1:])
            return (x - mean) * mx.rsqrt(variance + attrs.get("epsilon", 1e-5)) * scale + bias
        case "Cast":
            return x.astype(_DTYPE[attrs["to"]])
        case "Clip":
            low = args[1] if len(args) > 1 else attrs.get("min")
            high = args[2] if len(args) > 2 else attrs.get("max")
            if low is not None:
                x = mx.maximum(x, low)
            if high is not None:
                x = mx.minimum(x, high)
            return x
        case "Concat":
            return mx.concatenate(args, axis=attrs["axis"])
        case "ConstantOfShape":
            return mx.full(tuple(x.tolist()), attrs["value"], dtype=_DTYPE[attrs["dtype"]])
        case "Conv":
            strides = tuple(attrs.get("strides", (1, 1)))
            dilation = tuple(attrs.get("dilations", (1, 1)))
            auto = attrs.get("auto_pad", "NOTSET")
            pads = tuple(attrs.get("pads", (0, 0, 0, 0)))
            if auto in ("SAME_UPPER", "SAME_LOWER"):
                needed = [max(0, (size - 1) // stride * stride + (kernel - 1) * rate + 1 - size)
                          for size, kernel, stride, rate in zip(x.shape[2:], args[1].shape[1:3], strides, dilation)]
                begin = [(p + (auto == "SAME_LOWER")) // 2 for p in needed]
                pads = (*begin, *(total - low for total, low in zip(needed, begin)))
            elif auto == "VALID":
                pads = (0, 0, 0, 0)
            elif auto != "NOTSET":
                raise ValueError(f"Unsupported auto_pad {auto!r}")
            x = x.transpose(0, 2, 3, 1)
            if pads[:2] != pads[2:]:
                x = mx.pad(x, ((0, 0), (pads[0], pads[2]), (pads[1], pads[3]), (0, 0)))
                pads = (0, 0, 0, 0)
            y = mx.conv2d(x, args[1], stride=strides, padding=pads[:2], dilation=dilation,
                          groups=attrs.get("group", 1))
            return (y + args[2] if len(args) > 2 and args[2] is not None else y).transpose(0, 3, 1, 2)
        case "Elu":
            return nn.elu(x, alpha=attrs.get("alpha", 1.0))
        case "Expand":
            dims = zip_longest(reversed(x.shape), reversed(args[1].tolist()), fillvalue=1)
            return mx.broadcast_to(x, tuple(want if have == 1 else have for have, want in dims)[::-1])
        case "Flatten":
            axis = attrs.get("axis", 1)
            return x.reshape((prod(x.shape[:axis]), prod(x.shape[axis:])))
        case "Gather":
            return mx.take(x, args[1], axis=attrs.get("axis", 0))
        case "GatherND":
            if attrs.get("batch_dims", 0):
                raise ValueError("Expected GatherND without batch dimensions")
            index = args[1]
            return x[tuple(index[..., i] for i in range(index.shape[-1]))]
        case "Gelu":
            gelu = nn.gelu_approx if attrs.get("approximate") == "tanh" else nn.gelu
            return gelu(x)
        case "Gemm":
            lhs = x.T if attrs.get("transA", 0) else x
            rhs = args[1].T if attrs.get("transB", 0) else args[1]
            alpha, beta = attrs.get("alpha", 1.0), attrs.get("beta", 1.0)
            if len(args) > 2 and args[2] is not None:
                return mx.addmm(args[2], lhs, rhs, alpha=alpha, beta=beta)
            value = lhs @ rhs
            return value if alpha == 1.0 else alpha * value
        case "GlobalAveragePool":
            return mx.mean(x, axis=tuple(range(2, x.ndim)), keepdims=True)
        case "Identity":
            return x
        case "LayerNormalization":
            axis = attrs.get("axis", -1) % x.ndim
            if axis != x.ndim - 1 or outputs != 1:
                raise ValueError("Expected last-axis LayerNormalization with one output")
            bias = args[2] if len(args) > 2 else None
            return mx.fast.layer_norm(x, args[1], bias, attrs.get("epsilon", 1e-5))
        case "ReduceL2" | "ReduceMax" | "ReduceMean" | "ReduceSum":
            selected = _axes(args[1] if len(args) > 1 else None, attrs)
            if not selected and attrs.get("noop_with_empty_axes", 0):
                return x
            dims = tuple(selected) if selected else None
            keep = bool(attrs.get("keepdims", 1))
            if op == "ReduceL2":
                return mx.sqrt(mx.sum(mx.square(x), axis=dims, keepdims=keep))
            reducer = {"ReduceMax": mx.max, "ReduceMean": mx.mean, "ReduceSum": mx.sum}[op]
            return reducer(x, axis=dims, keepdims=keep)
        case "Reshape":
            shape = args[1].tolist() if len(args) > 1 else attrs["shape"]
            if not attrs.get("allowzero", 0):
                shape = [length or x.shape[i] for i, length in enumerate(shape)]
            return x.reshape(shape)
        case "Shape":
            return mx.array(x.shape[slice(attrs.get("start"), attrs.get("end"))], dtype=mx.int64)
        case "Slice":
            if len(args) > 1:
                starts, stops = (item.tolist() for item in args[1:3])
                selected = args[3].tolist() if len(args) > 3 and args[3] is not None else range(len(starts))
                steps = args[4].tolist() if len(args) > 4 and args[4] is not None else [1] * len(starts)
            else:
                starts, stops = attrs["starts"], attrs["ends"]
                selected = attrs.get("axes", range(len(starts)))
                steps = attrs.get("steps", [1] * len(starts))
            parts = [slice(None)] * x.ndim
            for axis, start, stop, step in zip(selected, starts, stops, steps, strict=True):
                width = x.shape[axis]
                start = max(-width - 1, min(width, start))
                stop = None if step < 0 and stop < -width else max(-width - 1, min(width, stop))
                parts[axis] = slice(start, stop, step)
            return x[tuple(parts)]
        case "Softmax":
            opset = attrs.get("opset", 13)
            axis = attrs.get("axis", -1 if opset >= 13 else 1)
            if opset < 13:
                return mx.softmax(x.reshape((prod(x.shape[:axis]), prod(x.shape[axis:]))),
                                  axis=-1, precise=True).reshape(x.shape)
            return mx.softmax(x, axis=axis, precise=True)
        case "Split":
            axis = attrs.get("axis", 0)
            lengths = args[1].tolist() if len(args) > 1 and args[1] is not None else attrs.get("split")
            return mx.split(x, list(accumulate(lengths))[:-1] if lengths else outputs, axis=axis)
        case "Squeeze":
            selected = _axes(args[1] if len(args) > 1 else None, attrs)
            return mx.squeeze(x, axis=tuple(selected) if selected is not None else None)
        case "Tile":
            return mx.tile(x, args[1].tolist())
        case "Transpose":
            return x.transpose(tuple(attrs.get("perm", reversed(range(x.ndim)))))
        case "Unsqueeze":
            selected = _axes(args[1] if len(args) > 1 else None, attrs)
            return mx.expand_dims(x, axis=tuple(selected))
        case _:
            raise ValueError(f"Unsupported ONNX 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] if name else None for name in names], attrs, len(outputs))
            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 result