Python wrappers
Public Python APIs implemented by this engine symbols.Autograd node for the linear (fully-connected) transformation .
Inherits FuncOp<LinearBackward, 3> which wires three saved-input
slots (x, W, b) and records each operand's shape so that
apply can reconstruct the three gradients during backward.
The forward dispatches to IBackend::linear (BNNS / Accelerate on
CPU, MLX on Metal); the backward delegates to
IBackend::linear_backward which returns {dx, dW, db} in one
fused call.
Attributes
schema_v1OpSchema"linear", version 1, AmpPolicy::Promote). Promote means the op participates in autocast and its operands are cast to the current autocast target dtype — F16 on GPU and F32 on CPU per the Accelerate-no-F16 carve-out.Notes
The bias slot is mandatory at the C++ level. When the Python
Linear(bias=False) form is requested, the binding layer passes
a zero-length tensor (shape (0,)) and the GEMM contribution from
b evaluates to zero. Thread safety: instances are created once
during forward and consumed once during backward — no concurrent
access is expected.
Static methods
1Run the forward pass and, when grad mode is on, register this as the grad_fn of the returned output.
The forward flattens all leading dimensions of x into an
M-row batch (),
dispatches the GEMM through backend::Dispatcher, and
reports 2 * M * N * K FLOPs to the profiler scope. Under an
active AutocastGuard, the three operands are cast to the
effective dtype using astype_op (which preserves autograd)
before the kernel call so the matmul takes the native F16 fast
path on Metal.
Math
Shape
- Input
x: - Weight
W: - Bias
b: - Output :
Parameters
xTensorImplPtrK = in_features. Must be at least 1-D.WTensorImplPtr(N, K). Treated as at the math level: the kernel multiplies x by W^T.bTensorImplPtr(N,). Pass an empty 1-D tensor when the Python module is constructed with bias=False.Returns
TensorImplPtrOutput tensor of shape , matching x's leading dimensions with the last axis replaced by N = out_features.
Raises
ShapeMismatchW.shape[1] != x.last_dim or b.shape[0] != W.shape[0].DeviceMismatchx, W, and b do not all live on the same device.Methods
1Compute the three gradients from the incoming grad_out.
Delegates to IBackend::linear_backward which produces
, , and
in a single backend call using the
shapes recorded in input_shapes_. The closed-form is
Parameters
grad_outStorageReturns
std::vector<Storage>Three-element vector {dx, dW, db} matching the saved-input ordering (x, W, b).