Concrete GPU backend routing every Lucid op through Apple's MLX library.
Inherits IBackend and overrides each per-op virtual to call
the matching mlx::core::* primitive (broadcast, matmul, reduce,
activations, …). Results are MLX lazy arrays — mx::eval() is
invoked when the engine needs the concrete buffer (e.g. for
MetalKernelRunner or download_gpu_to_cpu). Stream
tagging uses Dispatcher's default GPU stream unless an op
requests another (linalg ops dispatch to a CPU MLX stream per the
H3 carve-out, since MLX's eigh / svd / qr run on CPU).
See Also
CpuBackend — Accelerate-backed sibling.
MlxBridge — Storage ↔ mlx::core::array conversion.
GpuBackendRegistrar — static-init registration.
Attributes
device()DeviceDevice::GPU.Notes
- CPU and GPU backends are static singletons registered with the
Dispatcherat process start (seeGpuBackendRegistrar). - All Storage values passed in MUST hold
GpuStorage— the Dispatcher guarantees this by routing Device::GPU tensors here. - MLX uses lazy evaluation; operations build a graph but defer
execution until
eval()or a CPU read forces it. Dtype::F64is unsupported on the GPU (Metal limitation); callers must cast to F32 or keep the tensor on the CPU.- Convolutions internally permute NCHW ↔ NHWC because MLX expects
channels-last; see
gpu_nchw_to_nhwc_permfamily of helpers.
Examples
Construction is automatic via static registration:: // BackendInit.cpp triggers GpuBackendRegistrar at process start.
auto t = lucid::tensor({1,2,3}, lucid::Device::GPU);
// → routed to GpuBackend::from_cpu → mlx::core::copy.Static methods
28class_pick
::mlx::core::array class_pick(const ::mlx::core::array & x, const ::mlx::core::array & safe_t)The class-axis value at each target (take_along_axis on axis 1).
gpu_apply_pool_divisor
::mlx::core::array gpu_apply_pool_divisor(::mlx::core::array y, int B, int C, const int * S, const int * O, const int * K, const int * stride, const PoolOpts & opts, int N, Dtype dt)Divide a summed pool by the per-output-position window span.
The divisor factorises across axes, so it is built as a product of N rank-broadcast vectors rather than a dense (B,C,O...) tensor.
gpu_avg_pool_span
int gpu_avg_pool_span(int o, int S, int K, int stride, int pad, bool count_pad)Per-axis span of the average-pool window at output index o. Mirrors the CPU kernel's avg_pool_span: the window end is clamped to S + pad, so a ceil-mode overhang counts toward neither the sum nor the divisor, and count_include_pad picks between the padded extent and the real-element count.
Right-hand padding the ceil-mode overhang needs so the window view can address the final window without running off the end of the buffer.
gpu_conv_bias_only
::mlx::core::array gpu_conv_bias_only(const ::mlx::core::array & b, const int & out_shape)The forward of an empty convolution: the bias, broadcast over out_shape (channels on axis 1). b always holds one value per output channel — the op passes zeros when the module has no bias.
gpu_conv_empty_grads
int gpu_conv_empty_grads(const ::mlx::core::array & x, const ::mlx::core::array & w, ::mlx::core::array db, Dtype dt){dx, dW, db} of an empty convolution: zeros shaped like the input and the weight, and db as already reduced from the gradient.
gpu_conv_general
::mlx::core::array gpu_conv_general(const ::mlx::core::array & x, const ::mlx::core::array & w, const int & stride, const int & pad_lo, const int & pad_hi, const int & kernel_dilation, const int & input_dilation, int groups, bool flip)mlx::core::conv_general over channel-aligned operands (see gpu_align_conv_channels). Every convolution this backend runs — forward, both gradients, transposed — goes through here or through gpu_mlx_conv_transpose.
gpu_conv_has_empty_operand
bool gpu_conv_has_empty_operand(const ::mlx::core::array & x, const ::mlx::core::array & w, int out_numel)True when the input, the weight or the output (out_numel, the output of the forward or the incoming gradient of the backward) holds no elements.
gpu_lu_inverse
::mlx::core::array gpu_lu_inverse(const ::mlx::core::array & a, const char * op)for a batch of square matrices, from MLX's LU factors.
linalg::lu reports a zero pivot by leaving it in U rather than
by throwing, so the pivots are read back and a singular matrix raises
here — the CPU stream's LinAlgError, info being the 1-based
index of the first zero pivot, as LAPACK numbers it. Only then are
the factors inverted, and tri_inv fails on nothing but an exactly
zero diagonal: U's was just checked, L's is all ones. (A
NaN pivot is not zero; it propagates into a NaN inverse, which is
what LAPACK's own getri returns for it.)
MLX's lu gives A = L[P] U with P a row-index vector, so
, whose column j is column P[j]
of .
gpu_mlx_conv_grouped
::mlx::core::array gpu_mlx_conv_grouped(const ::mlx::core::array & x_nhwc, const ::mlx::core::array & W_nhwc, const int & stride, const int & pad, const int & dil, int groups, int N)Forward convolution, with the same rank-5 group fallback as gpu_mlx_conv_transpose below. x_nhwc is channels-last and W_nhwc is (out, K..., in / groups).
gpu_nan_where
::mlx::core::array gpu_nan_where(const ::mlx::core::array & bad, const ::mlx::core::array & a)a with every flagged matrix (or vector) replaced by NaN.
Builds a permutation for NCHW → NHWC transpose: [0, 2,..,N+1, 1]. N is the number of spatial dimensions (1, 2, or 3).
Builds a permutation for NHWC → NCHW transpose: [0, N+1, 1,..,N].
gpu_nonfinite_matrices
::mlx::core::array gpu_nonfinite_matrices(const ::mlx::core::array & a)Per-matrix flag, shaped (..., 1, 1): true where the matrix holds a NaN or an infinity.
gpu_require_finite
void gpu_require_finite(const ::mlx::core::array & a, const char * op)Raise, the way the CPU stream does, when a holds a NaN or an infinity. Costs one host round trip.
gpu_slice_axis
::mlx::core::array gpu_slice_axis(const ::mlx::core::array & a, int axis, int lo, int hi)Slice one group's block out of axis.
gpu_w_to_mlx_conv_transpose
::mlx::core::array gpu_w_to_mlx_conv_transpose(const ::mlx::core::array & W, int Cin, int Cout, int G, int N)Lucid stores the transposed weight as (Cin, Cout / G, K...); MLX wants (Cout, K..., Cin / G). Both disagree about which channel axis the grouping divides, so the leading axis is split into (G, Cin / G), the group moved next to Cout, and folded back in. Measured against a per-group reference: MLX pairs Cout-major blocks with the matching Cin block, which is the same convention Lucid uses, so no group reordering is needed — only the relayout.
At G == 1 this is exactly the old (1, 2..N+1, 0) permutation.
gpu_zero_where
::mlx::core::array gpu_zero_where(const ::mlx::core::array & bad, const ::mlx::core::array & a)a with every flagged matrix replaced by zeros.
MLX's isinf and isfinite judge a complex number as a whole — isinf is true only for (inf + 0j), so (1 + inf j) and (-inf + 1j) read as finite — where the reference takes a complex number as infinite when either part is. A complex input is split into its parts. (MLX's isnan already looks at both parts.)
How many offsets a buffer holds — the bag count, or one more under include_last_offset, whose final offset only ends the last bag.
Computes the sign of a permutation by counting cycles. Returns +1.0 if the permutation is even, -1.0 if odd. Used by linalg_det to apply the correct sign correction from the LU pivot permutation.
poison_after_nan
::mlx::core::array poison_after_nan(const ::mlx::core::array & input, const ::mlx::core::array & scanned, int axis)Once a NaN appears in the scan it is the running extreme, and every later element inherits it — the same rule max follows. MLX's cumulative scans skip it instead, so the CPU (fixed to propagate) and Metal disagreed from the NaN onwards.
MLX has no flag for it, so it is composed: a running max over the NaN mask says "a NaN has been seen at or before here", and those positions are overwritten.
Construct + register a fresh GpuBackend singleton with the Dispatcher.
Idempotent only insofar as the Dispatcher replaces any prior
registration for Device::GPU. Normally invoked exactly once
by GpuBackendRegistrar at process start.
Virtual methods
1Methods
265── Arithmetic ───────────────────────────────────────────────────────── Elementwise add with broadcast. Delegates to mlx::core::add.
── Reductions / boolean predicates ─────────────────────────────────── Logical-any over all elements; returns a 0-D bool tensor.
apply_loss_reduction
::mlx::core::array apply_loss_reduction(const ::mlx::core::array & values, int reduction)The sum / mean of a loss, accumulated in float32 for a half loss (see widen_half) and returned in its dtype. The mean divides in float32 too: as a float16 scalar the count of 65536 elements was inf, so the mean came back 0 — or NaN once the sum had overflowed.
── astype — the conversion rules live in gpu/Conversion.h ─────────── Convert a to dst_dt. Identical to cast on this backend.
MLX's scatter_{max,min,prod} have no axis-only variant the way scatter_add has scatter_add_axis. So the axis scatter a[..., idx[i,j,...], ...] op= src[i,j,...] along dim uses the multi-axis form with K = ndim: one coordinate array per axis. For every axis but dim the coordinate is arange(idx_shape[a]) reshaped to (1..N..1). For dim it is the index, made safe by gpu_axis_index. Updates then have the index's shape, which meets MLX's "updates.ndim == K + (ndim - K)" invariant.
An out-of-range index drops its update (policy B): the update becomes
the identity of op.
batch_norm_backward
→std::vector<Storage>int batch_norm_backward(const int & x, const int & gamma, const int & saved_mean, const int & saved_rstd, const int & saved_xnorm, const int & grad, int, int channels, int, int ndim, const int & x_shape_param, Dtype dt, double eps)BatchNorm backward (training mode).
Returns
std::vector<Storage>{dx, dgamma, dbeta}. MLX composite over channel axes.
batch_norm_forward
→std::vector<Storage>int batch_norm_forward(const int & x, const int & gamma, const int & beta, int, int channels, int, int ndim, double eps, const int & x_shape_param, Dtype dt)BatchNorm forward (training mode).
Math
Per-channel reduction over batch + spatial dims: , , .
Returns
std::vector<Storage>{y, saved_mean, saved_rstd}.
Notes
Hand-rolled MLX reductions over channel axes.
bce_loss
int bce_loss(const int & input, const int & target, const int & weight, const int &, Dtype dt, double eps, int reduction)Binary cross-entropy from probability inputs (not logits).
Math
then reduced.
bce_with_logits_loss
int bce_with_logits_loss(const int & input, const int & target, const int & weight, const int & pos_weight, const int &, const int &, const int &, Dtype dt, int reduction)Binary cross-entropy from logits, numerically stable.
Math
— the standard log-sum-exp-stable form.
bernoulli_mask
int bernoulli_mask(double keep_prob, const int & shape, Dtype dt, int key_seed)On-device {0,1} Bernoulli keep-mask at rate keep_prob (see IBackend::bernoulli_mask). Builds an MLX PRNG key from key_seed (pulled from the framework Generator, so masks are reproducible from the global seed) and fills the whole mask in one kernel via mlx::core::random::bernoulli — replacing the per-element CPU Philox loop + host->device upload that made Dropout the dominant cost in training-mode forward passes (~19 ms -> <1 ms for a (32,128,768) mask).
class_scaled_grad
::mlx::core::array class_scaled_grad(const ::mlx::core::array & grad, const ::mlx::core::array & valid_count, const int & target_axis_shape, int reduction)The upstream gradient of a class loss, spread over the target axis. For a mean it is divided by the float32 count in float32 (a half grad is widened), and the caller rounds the input gradient it builds from it back to the loss dtype.
class_valid_count
::mlx::core::array class_valid_count(const ::mlx::core::array & keep_mask)The number of targets not ignored — at least 1 — counted in float32 whatever the loss dtype: float16 holds an integer exactly only up to 2048 and overflows at 65520, so a float16 batch of 70000 tokens was averaged over inf.
Deep-copy a tensor into a fresh contiguous MLX array.
── Complex viewing (mlx native) ──────────────────────────────────────
contiguous
int contiguous(const int & src, const int & shape, const int &, int, bool, Dtype dt)Materialise a non-contiguous view into a contiguous tensor.
Identical to clone on this backend — MLX's
contiguous already handles stride packing internally.
conv_nd_backward
→std::vector<Storage>int conv_nd_backward(const int & grad_out, const int & x, const int & W, int B, int Cin, int Cout, int Cin_g, int Cout_g, const int * S, const int * K, const int * O, const ConvNdOpts & opts, Dtype dt)N-D convolution backward producing {dx, dW, db}.
Returns
std::vector<Storage>{dx, dW, db} in that order; db may be a stub when the forward had no bias.
Notes
Like the forward, this routes through the NHWC permutation
helpers. Heavy lifting is two extra MLX convolutions (one for
each weight slot) plus a reduction for db.
conv_nd_forward
int conv_nd_forward(const int & x, const int & W, const int & b, int B, int Cin, int Cout, int Cin_g, int Cout_g, const int * S, const int * K, const int * O, const ConvNdOpts & opts, const int & out_shape, Dtype dt)── Convolutions ────────────────────────────────────────────────────── N-D convolution forward (N ∈ {1, 2, 3}).
Math
where is the stride and the sum runs over the kernel window.
Notes
MLX uses NHWC (channels-last) ordering, so this routine permutes
input + weight NCHW → NHWC, dispatches mlx::core::conv1d /
conv2d / conv3d based on ndim, then permutes the
result back to NCHW. See gpu_nchw_to_nhwc_perm family.
conv_transpose_nd_backward
int conv_transpose_nd_backward(const int & grad_out, const int & x, const int & W, int B, int Cin, int Cout, const int * S, const int * K, const int * O, const IBackend::ConvTransposeNdOpts & opts, Dtype dt)N-D transposed convolution backward producing {dx, dW, db}.
conv_transpose_nd_forward
int conv_transpose_nd_forward(const int & x, const int & W, const int & b, int, int Cin, int Cout, const int *, const int *, const int *, const IBackend::ConvTransposeNdOpts & opts, const int & out_shape, Dtype dt)N-D transposed convolution (fractionally-strided / "deconv") forward.
Notes
Same NHWC permutation strategy as conv_nd_forward. MLX's
conv_transpose{1,2,3}d take dilation and groups
directly, so both are handed straight to it; only the weight has
to be rearranged, since Lucid and MLX disagree about where the
group-divided channel axis lives.
cross_entropy_backward
int cross_entropy_backward(const int & saved_softmax, const int & target, const int * weight, const int & valid_count, const int & grad, const int & input_shape, Dtype dt, int ignore_index, int reduction)Cross-entropy backward given the saved softmax output.
Math
(probability minus one-hot target), then scaled by the loss reduction weight.
ctc_loss_backward
int ctc_loss_backward(const int & log_probs, const int & targets, const int & input_lengths, const int & target_lengths, const int & grad_out, const int & lp_shape, int blank, bool zero_infinity, Dtype dt)The backward recursion runs where the forward's does, on the CPU, for the same reason: alpha and beta are a sequential walk over time.
ctc_loss_forward
int ctc_loss_forward(const int & log_probs, const int & targets, const int & input_lengths, const int & target_lengths, const int & lp_shape, int blank, bool zero_infinity, Dtype dt)── ctc_loss ────────────────────────────────────────────────────────────── ── Loss functions ──────────────────────────────────────────────────── Connectionist Temporal Classification (CTC) loss forward.
Notes
Implements Graves 2006 forward-only loss on the GPU with MLX primitives. Backward lives separately in the autograd layer.
PERF: cumsum / cumprod / cummax / cummin all produce contiguous output from MLX; the defensive contiguous() wraps below were forcing re-materialization and breaking the lazy-graph fusion chain.
MLX's scan carries its running value in the output dtype, so a half
input is scanned in float32 (see widen_half): a float16 cumsum of
20000 x 0.1 ended at 1999 and a cumprod of 1000 x 1.01 at 15528,
where the reference gives 2000 and 16624.
embedding_bag_forward
int embedding_bag_forward(const int & weight, const int & indices, const int & offsets, const int & weight_shape, const int & indices_shape, int mode, int padding_idx, bool include_last_offset, Dtype dt)embedding_bag: use MLX gather + reduce EmbeddingBag forward — gather + per-bag reduction in one op.
Notes
Reduction mode (sum / mean / max) is encoded in the surrounding op-spec; this routine only handles the gather + reduction kernel dispatch.
── Elementwise unary ───────────────────────────────────────────────── Elementwise exp(x). Each unary op below delegates to the matching mlx::core::* primitive through the mlx_unary helper.
── flip ────────────────────────────────────────────────────────────────── MLX has no built-in flip; implement via take with reversed indices per dim.
Exact, in dt (DivMod.h). floordiv_op no longer calls this.
── Construction / cross-device ──────────────────────────────────────── Upload a CPU storage to GPU-private memory.
Delegates to gpu::upload_cpu_to_gpu, which uses
mlx::core::copy to obtain a fresh GPU-private allocation
(the raw CPU pointer cannot be aliased on Metal).
Parameters
cpuCpuStorageshapeconst Shape&Returns
StorageA GpuStorage participating in MemoryTracker accounting.
gather
int gather(const int & a, const int & indices, const int &, const int &, int axis, Dtype, Dtype dt)── Indexing / scatter ──────────────────────────────────────────────── Gather values from a along dim using indices.
Math
.
GELU forward (tanh approximation).
Math
where , .
See Also
gelu_backward, gelu_exact.
Notes
7-op MLX composition (tanh approximation).
GELU exact (Gaussian-CDF) forward.
Math
. Composed via
mlx::core::erf.
huber_loss
int huber_loss(const int & input, const int & target, const int &, Dtype dt, double delta, int reduction)Huber loss (smooth L1).
Math
Piecewise: for , else .
interpolate_nearest_2d_forward
int interpolate_nearest_2d_forward(const int & input, const int & in_shape, int H_out, int W_out, Dtype dt)── interpolate — the graphs live in gpu/Interpolate.h ─────────────
layer_norm_backward
→std::vector<Storage>int layer_norm_backward(const int & x, const int & gamma, const int & saved_mean, const int & saved_rstd, const int & grad, int outer, int normalized_size, const int & x_shape, const int & gamma_shape, const int & beta_shape, Dtype dt)LayerNorm backward. Composes the gradient as a single MLX expression using the saved mean / rstd.
Returns
std::vector<Storage>{dx, dgamma, dbeta}.
layer_norm_forward
→std::vector<Storage>int layer_norm_forward(const int & x, const int & gamma, const int & beta, int outer, int normalized_size, double eps, const int & x_shape, Dtype dt)── Normalisation ───────────────────────────────────────────────────── LayerNorm forward via MLX's fused fast::layer_norm kernel.
Math
reducing along the trailing axis of size normalized_size.
Returns
std::vector<Storage>{y, saved_mean, saved_rstd} — the activation plus saved stats needed by layer_norm_backward.
Notes
Replaces the 7-op MLX chain (mean → subtract → square → mean → add+rsqrt → multiply → multiply+add) with one fused kernel. Mac Studio Llama-scale forward: 2.4 ms → ~0.6 ms.
Cholesky factorisation (or if upper), on MLX's CPU linalg stream.
MLX reports no failure. Its lower factor keeps LAPACK's failed
pivot — the first diagonal entry that is not positive, or is NaN, at
the step potrf stopped — so info is read there. Its upper
factor does not: [[1, 2], [2, 1]] came back [[1, 2], [0, 1]]
(LCD-206). So U of A is L of A^T, transposed: the
same triangle read, one check for both.
linalg_householder_product
int linalg_householder_product(const int & H, const int & tau, const int & h_shape, Dtype dt)householder_product: fall back to CPU LAPACK
Dense matrix inverse via the MLX CPU linalg stream.
Built from MLX's LU factors rather than linalg::inv, which throws
from the CPU stream's worker thread on a singular matrix and so
aborts the process — see gpu_lu_inverse. A singular input raises
the same LinAlgError the CPU stream does.
ldl_factor: the CPU backend's sytrf, uploaded (MLX has no LDLᵀ).
linalg_lstsq
int linalg_lstsq(const int & a, const int & b, const int & a_shape, const int & b_shape, Dtype dt)lstsq: fall back to CPU LAPACK (MLX has no lstsq)
lu_factor: MLX's lu returns separate (P, L, U), not LAPACK's packed factor and pivots, so the CPU backend factorises and the result is uploaded. Delegating — rather than running getrf again here — keeps the CPU backend the one owner of the info policy.
linalg_lu_solve
int linalg_lu_solve(const int & LU, const int & pivots, const int & b, const int & lu_shape, const int & b_shape, Dtype dt)lu_solve: fall back to CPU LAPACK
linalg_norm
int linalg_norm(const int & a, const int &, double ord, const int & axes, bool keepdims, Dtype dt)Matrix / vector norm. Routed to MLX's CPU linalg stream per H3.
Math
Generic ord-norm along axes. For ord=2 and a matrix
axis pair this is the Frobenius / spectral norm depending on
mode; for a vector axis it is the L2 norm.
Notes
MLX implements linalg::norm on the CPU stream, so the result
physically lives in unified memory but the compute happens on
the CPU (H3 carve-out).
Moore-Penrose pseudo-inverse: the CPU backend's gesdd SVD, uploaded. Delegating keeps CpuBackend::pinv_one the one owner of the SVD driver and non-finite policy (NaN vs single/multiple infinities).
linalg_solve
int linalg_solve(const int & a, const int & b, const int & a_shape, const int & b_shape, Dtype dt)Solve the linear system for x. CPU linalg stream.
x = A^{-1} b with the inverse from gpu_lu_inverse:
linalg::solve inverts the triangular factors with the same
throwing routine, so a singular A aborted the process here too.
MLX's own solve is a product with explicit triangular inverses, so
this is the same arithmetic in a different order, not a weaker one.
linalg_solve_triangular
int linalg_solve_triangular(const int & a, const int & b, const int & a_shape, const int & b_shape, bool upper, bool unitriangular, Dtype dt)solve_triangular: the CPU backend's substitution, uploaded. MLX's own linalg::solve_triangular goes through tri_inv, whose LAPACK trtri throws from the CPU stream's worker thread on a zero diagonal — a process abort, not an exception (see the note on MLX CPU-stream linalg) — where the reference returns inf/NaN. Delegating keeps the CPU backend the one owner of the singular-triangle policy.
linear
int linear(const int & x, const int & weight, const int & bias, const int &, const int &, const int & out_shape, Dtype dt)Fused affine: y = x @ W^T + b (the canonical nn.Linear op).
Math
.
Notes
Uses mlx::core::addmm when b is present so the multiply +
add fuse inside the MLX kernel; falls back to a separate matmul
when b is null. Deferred contiguous wrap matches the conv2d
path (cf perf-conv2d-deferred-contig).
x - logsumexp(x), NaN across a row whose maximum is infinite — see LogSoftmax.h.
masked_select_count
int masked_select_count(const int & mask, const int & shape, Dtype dt)── masked_select ─────────────────────────────────────────────────────────
matmul
→Storageint matmul(const int & a, const int & b, const MatmulOpts & opts, Dtype dt)── Linear algebra ──────────────────────────────────────────────────── General matrix multiply with optional broadcasted batch dims.
Parameters
a, bconst Storage&opts.optsconst MatmulOpts&MatmulOpts).dtDtypeReturns
StorageResult of a @ b (possibly batched), wrapped as GpuStorage.
Notes
Calls mlx::core::matmul. Uses Metal's BLAS-equivalent
tiled kernel internally; for very small matrices the dispatch
overhead may dominate.
Elementwise max(a, b) with broadcast.
Elementwise min(a, b) with broadcast.
Applies a binary MLX operation fn to two GpuStorage arrays. Shape is ignored because MLX handles broadcasting internally.
Same rationale as mlx_unary: binary element-wise ops always produce C-contiguous output in MLX, so contiguous() is not needed here.
Binary counterpart of mlx_unary_fused — for two-input element-wise composites (e.g. activation backward passes consuming the input and the incoming gradient). Same caching, same capture-less requirement.
Applies an MLX reduction fn(array, axes, keepdims). If opts.axes is empty all axes are reduced (full reduction).
MLX reductions always produce C-contiguous output; contiguous() omitted.
Applies a unary MLX operation fn to the underlying array and wraps the result in a new GpuStorage.
No mlx::core::contiguous() call here: element-wise MLX ops (exp, sin, abs, relu, …) always write to a freshly allocated C-contiguous Metal buffer regardless of the input strides. Adding contiguous() would insert a redundant lazy graph node that MLX must inspect and discard at eval time, adding ~150 µs of overhead per call on 10M-element float32 arrays.
If an op genuinely needs the output to be contiguous (e.g. a view op), call mlx_unary_contiguous() instead or wrap explicitly.
Variant of mlx_unary that forces C-contiguous output. Use only for ops that may produce strided/non-contiguous results (e.g. view ops).
Fuse a multi-op element-wise UNARY composite into a single Metal kernel via mlx::core::compile (shapeless → traced once on first call, then the fused kernel is reused for every shape and dtype). MLX eager does NOT fuse element-wise chains (that is what compile is for), so a composite such as gelu (~9 primitives) otherwise pays one kernel launch + a DRAM round-trip PER primitive. Fusing collapses it to one pass — e.g. gelu_exact 1.71 ms -> 0.48 ms on (32,128,3072) F32 (faster than the reference framework), bit-exact (maxdiff <= 2.4e-7; F16/BF16 exact).
Use ONLY for genuine multi-op composites; single-primitive ops
(relu/sigmoid/exp) gain nothing. fn MUST be capture-less — derive any
dtype-specific constant from the input's dtype (x.dtype()), never from
a captured Dtype (the compile overload needs a function-pointer-
convertible lambda). The compiled function is a function-local static, so
it is built once per distinct Fn type and reused thereafter.
mse_loss
int mse_loss(const int & input, const int & target, const int &, Dtype dt, int reduction)Mean-squared-error loss.
Math
with the chosen reduction
(mean / sum / none).
nn_fold
int nn_fold(const int & x, const int & x_shape, const int & out_shape, const int & kernel_size, const int & stride, const int & padding, const int & dilation, Dtype dt)fold (col2im) — Metal-native via scatter_add_axis.
Algorithm: precompute on CPU a length-(kHkWL) table of flat output
positions (ohoutW + ow) for every (ki, kj, l_idx) triple plus a
matching validity mask. Upload both as small MLX arrays. Then a
single scatter_add_axis call accumulates the (N, C, kHkW, L)
input slices into the (N, C, outH*outW) output buffer along axis 2.
Invalid (out-of-bounds) source elements are zeroed via the mask, so
they scatter +0 to position 0 and have no effect on the result.
nn.Fold — reverse of nn.Unfold: scatters unfolded patches back into a feature map.
Notes
Built atop MLX's scatter_add because patches may overlap and
must accumulate.
one_hot_forward
int one_hot_forward(const int & indices, const int & indices_shape, int num_classes, Dtype out_dtype)Built by comparing each index with every class, so no index value is ever used as an offset. One outside [0, num_classes), negative ones included, matches no class and leaves its row zero: policy B for Metal (gpu_axis_index). The CPU raises IndexError, as the reference does.
Allocate a ones-initialised tensor on the GPU. Delegates to mlx::core::ones.
random_uniform
int random_uniform(const int & shape, double lo, double hi, Dtype dt, int key_seed)On-device random fills via mlx::core::random (see IBackend). Each builds a PRNG key from key_seed and fills in one kernel.
reduce_class_loss
int reduce_class_loss(const ::mlx::core::array & values, const ::mlx::core::array & valid_count, Dtype dt, int reduction)The class loss reduced; the sum accumulates in float32 for a half loss and divides by the float32 valid_count before it is rounded back.
3.4+ Phase A.1: fused ReLU backward. Single MLX expression replacing the prior 3-op composition (greater + astype + multiply) which MLX did not fuse — the cast from Bool to F32 between greater and multiply broke the kernel-fusion chain. where(greater(x, 0), g, 0) is a single conditional-select kernel that handles the typecast implicitly. ResNet- 18 ReLU bwd per-op (microbench, M4 Max): the +0.79 ms gap vs the reference framework should close.
safe_class_indices
::mlx::core::array safe_class_indices(const ::mlx::core::array & target_idx, const ::mlx::core::array & keep_mask)The target with every ignored entry replaced by class 0, so the gathers below read a real class there; the loss masks it out. A target that is neither ignored nor a class stays as it is, and the gathers answer NaN for it (policy B, gpu_axis_index): the loss there is NaN, the CPU raises IndexError.
scale_loss_grad
::mlx::core::array scale_loss_grad(const ::mlx::core::array & grad, int reduction, int numel, int dt)grad / numel for a mean loss, in float32 for a half grad: the count is not representable in float16 past 65504 and 1/count is subnormal past 16384. Callers form the input gradient in that dtype and round it to dt once (narrow_to), as the reference does.
scatter_add
int scatter_add(const int & base, const int & indices, const int & src, const int & base_shape, const int & idx_shape, int dim, Dtype dt)Scatter-add: base[indices] += src (out-of-place), along dim: out[..., idx[..., j, ...], ...] += src[..., j, ...]
mlx::core::scatter_add_axis is that primitive exactly. MLX's
multi-axis scatter_add (np.add.at flavour: one index array per
axis) is a different operation and tripped its own "Number of index
arrays does not match number of axes" guard. An out-of-range index
drops its update (policy B, gpu_axis_index).
scatter_set
int scatter_set(const int & base, const int & indices, const int & src, const int & base_shape, const int & idx_shape, int dim, Dtype dt)Axis-scatter overwrite — out[..., idx[..., j, ...], ...] = src[..., j, ...] along dim. mlx::core::put_along_axis is the exact set-mode analogue of scatter_add_axis (single kernel); x[key] = v, scatter and index_copy route through it. A position named twice takes one of the values aimed at it, which one unspecified unless deterministic mode is enabled (put_along_axis_last_write_wins, last write wins).
An out-of-range index drops its write (policy B, gpu_axis_index).
It is aimed at a one-wide sink slab past the end of dim that is cut
off again (gpu_sink_index), because no in-range position can take
a write and stay as it was.
MLX scatters no 8-byte element on Metal: int64 and complex64 both report "[ScatterAxis::eval_gpu] Does not support". Writing each as two uint32 halves would be exact for distinct indices, but two writers racing for one position can land one's low half beside the other's high half — a value nobody wrote. So those two go through the CPU, sink slab and all.
MLX's Metal scatter has no int64 kernel (nor complex64 — see scatter_set).
[ScatterAxis::eval_gpu] Does not support int64 — the values,
not the indices, which it takes at either width. There is no exact
way around it on-device: float32 loses everything above 2^24, and
splitting the word into two int32 halves works for a set but not
for an add, where the carry between halves is exactly what is lost.
So int64 scatter runs on the CPU and comes back. It is a real cost
and it is stated here rather than hidden: the alternative was
lucid.scatter and index_copy raising on Metal for a dtype
the CPU handles, which is the device-dependent behaviour this
backend pair exists to avoid. Same shape as the LAPACK pivot
round-trips further up this file.
── Activations ──────────────────────────────────────────────────────── SiLU / Swish forward.
Math
where is the logistic sigmoid.
See Also
silu_backward.
SiLU / Swish backward. Single fused MLX expression.
Math
.
PERF: softmax + log_softmax produce contiguous output; their backwards are pure elementwise composition. Dropping the contiguous() wraps lets downstream loss ops (cross_entropy_loss is the typical consumer) fuse into a single MLX kernel. ── Softmax family ──────────────────────────────────────────────────── Softmax along axis. Delegates to mlx::core::softmax.
Math
along the chosen axis.
softmax_backward
int softmax_backward(const int & z, const int & grad_out, const int & shape_param, int axis, Dtype dt)Softmax backward, given the saved forward output z. Composes z * (grad - sum(z * grad, axis)) via MLX.
Math
.
unfold_dim
int unfold_dim(const int & a, const int & in_shape, int dim, int size, int step, Dtype dt)Sliding-window unfold along dim producing rank+1 windows of size.
Math
Output dim L = (dim_size - size) / step + 1. Indices built
as starts[l] = l * step, offsets[s] = s, then gathered.
Population variance. A half input is accumulated in float32 (see var_widened): MLX's var takes a mean of its own, so a float16 input overflowed the same way reduce_mean did.
Allocate a zero-initialised tensor on the GPU. Delegates to mlx::core::zeros.