CPU (Apple Accelerate-backed) concrete IBackend.
Every public method satisfies the IBackend contract; the
private section holds low-level type-dispatch helpers (unary_op,
binary_op, reduce_axes) plus per-op compute routines that
delegate to the Accelerate helpers in Blas.h,
Lapack.h, Norm.h, Pool.h, Reduce.h,
Vdsp.h, and Vforce.h.
See Also
IBackend — abstract base.
GpuBackend — MLX/Metal counterpart.
Dispatcher — owns the singleton instance.
Notes
Marked final — there is exactly one CPU backend at runtime,
installed by CpuBackendRegistrar at static-init time.
Static methods
52Whether every one of the n values is finite. LAPACK's drivers reject a NaN as an illegal argument, so the linalg kernels ask first.
class_target
int class_target(const char * op, const CpuStorage & target, int i, int ignore_index, int channels)The class of target i, or -1 where the target is ignore_index. A class outside [0, channels) is refused with IndexError, as the reference refuses it. The losses read the probability and the class weight at whatever offset the target named, so an out-of-range label read memory outside both. The comparison with ignore_index is made at full width: cut to int first, a target of 2^32 - 100 was taken for the default -100 and skipped. Metal answers NaN for such a target instead (policy B, GpuBackend's gpu_axis_index).
LUCID_CONV_COLUMN_BUDGET lowers the budget so tests can drive the slab path on small inputs; it is not a tuning knob.
An interleaved complex op over two same-shape buffers. binary_op has no complex branch: its kernels are typed on one real scalar.
ctnd_gemm
void ctnd_gemm(bool ta, bool tb, int M, int Nn, int Kk, float alpha, const float * A, int lda, const float * Bm, int ldb, float beta, float * C, int ldc)Precision-dispatching GEMM so the transposed-conv bodies can be one generic lambda rather than a copy-pasted F32 / F64 pair.
ctnd_im2col
void ctnd_im2col(const float * src, float * cols, int C, const int * O, const int * K, const int * S, const int * stride, const int * pad, const int * dil, int N)im2col / col2im / GEMM shims for the transposed convolution.
The transposed conv is the data gradient of a forward convolution, so
the roles are crossed relative to the forward path: the output
extent O plays the forward conv's input length and the input
extent S plays its output length. That is why O is passed
where the primitives name their argument L / H / D.
The dilation argument used to be hardcoded to 1 here, which
is what confined the whole op to dilation == 1; the underlying
primitives have always accepted it.
Truth of element i in its own dtype. any / all handled F32 / F64 / I32 / Bool and sent every other dtype to a byte loop that read one byte per element: an int64 1 is the bytes 01 00 00 …, so all([[1, 2], [3, 4]]) saw the zero second byte and answered False, and any looked only at the first n bytes — the first n/8 int64s. Floating zero includes -0.0, so the half types mask off the sign bit.
isinf / isnan / isfinite share one body. The dtype picks the bit layout and the question is a template argument (see NonFinite.h). Only float32 and float64 used to be tested. Every other dtype got the integer answer, so a float16 or bfloat16 infinity read as finite. An integer or bool tensor really does hold no NaN and no infinity, so that answer is kept for those dtypes only.
Project one lane out of an interleaved complex buffer.
lane is 0 for the real half and 1 for the imaginary one. The
lane width follows the storage's own dtype rather than being
assumed float32: reading a complex128 buffer as pairs of floats
would report the top half of a double's mantissa as a number.
Registers this backend with the Dispatcher for Device::CPU.
Invoked exactly once at process start by BackendInit.cpp.
See Also
Dispatcher::register_backend — receiving end.
geev has no answer for a non-finite matrix: its balancing step turns the NaN into an illegal argument for the Hessenberg solver (and the Fortran runtime prints that to file descriptor 2). The reference raises for it too, so this raises before LAPACK is reached, with the message the Metal stream uses.
The overwrite scatter's loop, for W-byte elements and index type I. It never does arithmetic on a value, so it moves bytes: one loop per element width serves every dtype of that width. The memcpy of a constant W compiles to a single load and store.
k ascends for every (outer, inner) line, so a position named twice
keeps the value written last, as the reference's CPU kernel does.
j innermost keeps the src reads and the base writes sequential.
Unpack one matrix's worth of LAPACK ?geev output into complex.
?geev reports a real matrix's spectrum in two real arrays,
wr and wi, and its eigenvectors in a single real VR
where a conjugate pair occupies two adjacent columns. Reading only
wr and copying VR verbatim is what this backend used to do,
and for a matrix with any complex eigenvalue that is not a lossy
answer but a wrong one: the pair a \u00b1 bi came back as a, a — two
equal reals where there were two conjugate numbers — with nothing
to say the imaginary halves had been dropped.
A real matrix having complex eigenvalues is the ordinary case, not a corner one. Any rotation has them; so does every companion matrix of a polynomial with complex roots. It went unnoticed because a symmetric or triangular test matrix has a real spectrum, and those are what test suites reach for.
The packing, from ?geev's documentation: if wi[j] is zero,
eigenvector j is column j of VR. Otherwise j and j+1 are a
conjugate pair with wi[j] > 0, and
v[j] = VR[:, j] + i * VR[:, j + 1] v[j+1] = VR[:, j] - i * VR[:, j + 1]
vr arrives row-major (the LAPACK wrapper transposes on the way
out), so eigenvector j is still column j, read with stride n.
Virtual methods
1Methods
257── astype ────────────────────────────────────────────────────────────────
Generic Cartesian-product cast over the supported scalar dtypes. Earlier
versions of this file hand-spelled every supported (src, dst) pair, which
left holes (notably Bool -> I64) that surfaced during the 3.0.2 +
followup smoke runs — bool reductions need to promote through I64 first
and that promotion was silently NotImplementedError. The dispatch below
covers every pair among {F16, F32, F64, I8, I16, I32, I64, Bool}. C64
and BF16 are handled outside the table, through float32, because their
host representation isn't a simple static_cast-able scalar (F16 uses the IEEE half decoder from
item() indirectly via the F32 path — handled with a small helper).
Generic binary dispatch: allocates output, calls fn32/fn64/fni32/fni64 based on dt.
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 ──────────────────────────────────────────────────────────────
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)EmbeddingBag: gather + reduce per bag
Fills ptr with the scalar value 1 for dtype dt. Used by ones().
── flip ──────────────────────────────────────────────────────────────────
Wraps an incoming CpuStorage into the variant directly.
The CPU backend already operates on CpuStorage natively, so
this is a move with no copy. The shape argument is ignored.
Parameters
cpuCpuStorageReturns
Storagecpu re-wrapped as a Storage variant.
{LD, pivots, info} — sytrf completes when D is singular, so its info is returned, not raised (LinalgFactor.h).
{LU, pivots, info} — getrf completes on a singular matrix, so its info is returned, not raised (LinalgFactor.h).
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)Substitution through BLAS trsm, not the LAPACK driver trtrs. trtrs checks the diagonal first and refuses a singular triangle (info > 0) without solving; the reference answers it with the IEEE result of substitution instead — a nonzero over a zero pivot is ±inf, 0 / 0 is NaN — and so does this. The Metal stream delegates here, so this is the one triangular-solve policy for both devices.
lstm_forward_train
int lstm_forward_train(const int & input, const int & h0, const int & c0, const int & weights, const LstmOpts & opts, Dtype dt)Float32 and float64 run natively; the 16-bit formats widen to float32 at the door and round back on the way out. The saved gate and cell trajectories stay float32 — only lstm_backward reads them.
── masked_select ─────────────────────────────────────────────────────────
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): scatter-add (N, CkHkW, L) → (N, C, outH, outW)
reduce_axes
int reduce_axes(const int & a, const int & in_shape, const ReduceOpts & opts, Dtype dt, ReduceOp op)Reduces a over the axes in opts by iterating axes from largest to smallest (descending sort ensures that axis indices remain valid after each step). Each single-axis pass calls the appropriate cpu::sum_axis / max_axis / min_axis primitive. Mean divides by the reduce dimension after summing.
relu_backward
int relu_backward(const int & g, const int & x, const int & shape, Dtype dt)3.4+ Phase A.1: fused ReLU backward. Single-pass loop replacing positive_mask + multiply, eliminating one intermediate buffer. See GpuBackend::relu_backward for the GPU rationale.
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)User-facing scatter-add: copies base then adds src at positions given by indices.
scatter_reduce_loop
int scatter_reduce_loop(const int & base, const int & indices, const int & src, const int & base_shape, const int & idx_shape, int dim, Dtype dt, const char * name, cpu::ScatterReduce reduce)Generic scatter-reduce loop shared by scatter_amax / scatter_amin / scatter_prod. Every dtype at its own width but half, which widens to float32 here; see ScatterReduce.h.
The index is read at its own width and checked against the axis. This
loop read every index as int32 lanes (an int64 index of 2^32 + 1 was 1)
and wrote wherever the value pointed, so an out-of-range index wrote
past the buffer. It also placed the index's elements by the base's
strides, so an index narrower than the base off dim read past the
index and src and took the process down with SIGBUS.
axis_scatter_walk places them now, as it does for scatter_add and
scatter_set.
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)Overwrite scatter: a copy of base with out[..., idx[..., k, ...], ...] = src[..., k, ...] along dim.
Every dtype, by element width. It shared the reduce loop above, which
instantiates f32 and f64 only, so index_copy of a bool, integer,
half or complex tensor refused (CHA-27) — and x[key] = v had been
routed around it through an additive delta that could not express an
overwrite at all (CHA-158). The index may be shorter than base on
every axis but dim, as for scatter_add; a repeated index keeps
the value written last.
Generic unary dispatch: allocates output, calls fn32/fn64/fni32 based on dt. I64 falls back to a scalar loop via static_cast<double>.
unfold_dim
int unfold_dim(const int & a, const int & in_shape, int dim, int size, int step, Dtype dt)Sliding-window view: out shape is (*in_shape[:dim], L, *in_shape[dim+1:], size)