Skip to content
class

LinearBackward

LinearBackward

Python wrappers

Public Python APIs implemented by this engine symbols.

Autograd node for the linear (fully-connected) transformation y=xW⊤+b\mathbf{y} = \mathbf{x}\mathbf{W}^\top + \mathbf{b}.

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
Registered schema (name "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

1
static

forward

→TensorImplPtr
int forward(const int & x, const int & W, const int & b)

Run 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 (M=∏i<ndim−1x.shape[i]M = \prod_{i<\text{ndim}-1} x.\text{shape}[i]), 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

y=xW⊤+b\mathbf{y} = \mathbf{x}\mathbf{W}^\top + \mathbf{b}

Shape

  • Input x : (∗,K)(\ast, K)
  • Weight W : (N,K)(N, K)
  • Bias b : (N,)(N,)
  • Output : (∗,N)(\ast, N)

Parameters

xTensorImplPtr
Input tensor of shape (∗,K)(\ast, K) — any number of leading batch dimensions followed by K = in_features. Must be at least 1-D.
WTensorImplPtr
Weight matrix of shape (N, K). Treated as W⊤\mathbf{W}^\top at the math level: the kernel multiplies x by W^T.
bTensorImplPtr
Bias of shape (N,). Pass an empty 1-D tensor when the Python module is constructed with bias=False.

Returns

TensorImplPtr

Output tensor of shape (∗,N)(\ast, N), matching x's leading dimensions with the last axis replaced by N = out_features.

Raises

ShapeMismatch
If W.shape[1] != x.last_dim or b.shape[0] != W.shape[0].
DeviceMismatch
If x, W, and b do not all live on the same device.

Methods

2
fn

apply

→std::vector<Storage>
int apply(int grad_out)

Compute the three gradients from the incoming grad_out.

Delegates to IBackend::linear_backward which produces dx=∇ ⁣xℓdx = \nabla_{\!x}\ell, dW=∇ ⁣WℓdW = \nabla_{\!W}\ell, and db=∇ ⁣bℓdb = \nabla_{\!b}\ell in a single backend call using the shapes recorded in input_shapes_. The closed-form is

dW = \text{grad\_out}^\top \cdot \mathbf{x}_\text{flat},\quad db = \sum_{\text{batch}} \text{grad\_out}.$$

Parameters

grad_outStorage
Incoming gradient of shape (∗,N)(\ast, N) matching the forward output.

Returns

std::vector<Storage>

Three-element vector {dx, dW, db} matching the saved-input ordering (x, W, b).

fn

apply_for_graph

→std::vector<TensorImplPtr>
int apply_for_graph(const int & grad_out)

Same three gradients, built from ops instead of one fused backend call, so that each stays differentiable.

What apply returns are Storages, which carry no autograd history — enough for one backward pass and nothing beyond it. Any second derivative through a dense layer goes through here instead: a gradient penalty, a meta-learning inner step, a Hessian-vector product, or the divergence of a continuous flow's vector field.

Parameters

grad_outconst TensorImplPtr&
Incoming gradient of shape (∗,N)(\ast, N), itself possibly carrying a grad_fn.

Returns

std::vector<TensorImplPtr>

Three-element vector {dx, dW, db} in saved-input order.