Python wrappers
Public Python APIs implemented by this engine symbol.Autograd node for the generalised matrix multiplication (matmul) with NumPy broadcasting on leading batch dimensions.
Saves both inputs. Forward dispatches to cblas_*gemm (Accelerate)
for plain 2-D inputs, the batched-GEMM kernel for any leading-batch
shape, and MLX's matmul primitive on the GPU stream. Backward
computes the two factor gradients via two further matmuls, then
reduce_grad_to_shapes each back to the original (pre-broadcast)
batch shape.
Math
2-D case (, ):
Batched case ( rank with broadcastable leading dims):
Shape
- Both inputs must be at least 2-D;
plan_nd_matmulrejects rank < 2. - Trailing two dims drive the GEMM:
a.shape[-1] == b.shape[-2] == K. - Leading dims broadcast NumPy-style; output shape is
broadcast(a.shape[:-2], b.shape[:-2]) + (M, N).
References
NumPy numpy.matmul semantics (which Lucid mirrors).
See Also
dot_op : 1-D × 1-D / 2-D × 2-D specialised dispatch without broadcasting.
inner_op : Last-axis contraction (NumPy inner).
outer_op : 1-D × 1-D outer product.
Attributes
schema_v1OpSchema("matmul", v1, AmpPolicy::Promote, deterministic=true).Notes
MatmulBackward is a FuncOp<..., 2> (alias for
AutogradNode<..., 2>) rather than a BinaryOp because matmul
requires a custom forward that cannot fit into the generic
BinaryKernel dispatch path: it calls plan_nd_matmul, handles
batch broadcasting, and wires the autograd graph manually.
Under AutocastGuard(F16) the schema's AmpPolicy::Promote resolves
to the autocast target (F32 on CPU per the Accelerate-no-F16 carve-out;
F16 on GPU where MLX runs matmul natively at half throughput). The
AMP cast is wired through autograd-aware astype_op so the backward
chain stays intact.
Static methods
1Validate inputs, plan the batched matrix multiply, execute the forward kernel, and wire the autograd graph if gradient tracking is active.
Parameters
aTensorImplPtrbTensorImplPtrReturns
TensorImplPtrOutput tensor with shape broadcast(a.shape[:-2], b.shape[:-2]) + (M, N).
Raises
ShapeMismatchDeviceMismatcha and b live on different devices.DtypeMismatcha and b still disagree.Methods
3Eager-mode backward: compute and from the upstream gradient and reduce any batch dims that were broadcast-expanded during forward.
Parameters
grad_outStorageReturns
std::vector<Storage>{dA, dB} reduced to the original input shapes.
Graph-mode backward: build a symbolic backward subgraph and using matmul_op, mT_op, and sum_op.
Parameters
grad_outTensorImplPtrReturns
std::vector<TensorImplPtr>{dA, dB} as graph tensors reduced to the original input shapes.
Human-readable node label used by the autograd profiler.