Skip to content
class

ReduceKernel

extendsAutogradNode<Derived, 1>kernel::IKernel
ReduceKernel

CRTP base for single-input multi-axis reduction ops (sum, mean, prod, max, min, …).

Concrete reductions inherit as class SumBackward : public ReduceKernel<SumBackward> and supply (a) a static constexpr OpSchema schema_v1, (b) one of the kernel hooks recognised by HasReduceDispatch / HasReduceGpuKernel (or a plain cpu_kernel static), and (c) a grad_formula(grad_out) -> Storage that converts the upstream gradient into the input gradient. The base owns axis normalisation, output-shape computation, GPU/CPU dispatch, and the extra reduction-state plumbing that the backward formula needs.

Unlike UnaryKernel, the forward output has a different shape than the input, so the backward pass must broadcast the gradient from the reduced shape back to the full input extent. That broadcast is encoded once in apply_for_graph (graph-mode) and is the responsibility of grad_formula in storage-mode.

Math

y=reducei∈axes(x),∂L∂xi=scaleop ⁣(broadcast ⁣(∂L∂y)). y = \mathrm{reduce}_{i \in \text{axes}}(x), \qquad \frac{\partial \mathcal{L}}{\partial x_i} = \mathrm{scale}_{\text{op}}\!\left( \mathrm{broadcast}\!\left( \frac{\partial \mathcal{L}}{\partial y} \right) \right).

scale_op is identity for sum, 1/N1/N for mean, y/xiy / x_i for prod, an argmax/argmin indicator for max/min.

Template Parameters

Derived : class CRTP self-type. Must expose schema_v1, a kernel hook satisfying one of the reduction concepts (or cpu_kernel), and grad_formula. May override scale_graph_grad for graph-mode scaling (mean, prod, …).

See Also

UnaryKernel, BinaryKernel, NaryKernel — sibling CRTP bases for shape-preserving ops. SumBackward, MeanBackward, ProdBackward, MaxBackward, MinBackward — canonical consumers.

Attributes

kSavesInputbool
true by default — most reductions need the input activation during backward. SumBackward overrides this to false.
kSavesOutputbool
false by default. MaxBackward / MinBackward override to true so they can route gradient through the saved output's argmax indicator.
kHasGradientbool
true. All canonical reductions participate in autograd.
reduce_axes_std::vector<int>
Normalised (non-negative, sorted, deduplicated) axis list saved by forward for use in apply_for_graph and in the derived grad_formula.
keepdims_bool
Whether reduced axes were retained as size-1 dims in the output. Controls whether the backward pass must re-insert those size-1 axes before broadcasting.
full_input_shape_Shape
Shape of the input tensor before reduction — the broadcast target during backward.

Notes

Dispatch order. forward chooses the kernel path with if constexpr:

  1. HasReduceDispatch — call Derived::dispatch(backend, storage, shape, axes, keepdims, dtype).
  2. GPU + HasReduceGpuKernel — call Derived::gpu_kernel.
  3. CPU — call Derived::cpu_kernel.

Contiguity. A strided CPU input needs no copy first: its storage() is packed. GPU inputs are passed through as MLX handles strides natively.

Static methods

2
static

compute_storage

int compute_storage(const int & a_ptr, const int & axes, bool keepdims, const int & out_shape, Dtype eff_dt)

The reduced storage of a_ptr over axes at eff_dt: the backend's dispatch, or the Derived CPU / GPU kernel. A phantom of out_shape under phantom mode, where no kernel runs.

static

forward

→std::shared_ptr<TensorImpl>
int forward(const int & a, const int & axes_user, bool keepdims)

Forward entry point: run the reduction and wire the backward node.

Normalises axes_user (negative indices → positive, dedup), computes the output shape (respecting keepdims), enforces CPU contiguity, dispatches to the most specific kernel hook the Derived class exposes, and — when GradMode is enabled and the input requires grad — constructs the backward node with the extra reduction state (reduce_axes_, keepdims_, full_input_shape_) populated.

Parameters

aconst std::shared_ptr<TensorImpl>&
Input tensor. Must be non-null.
axes_userconst std::vector<int>&
Raw axis list as supplied by the caller. May contain negative indices and duplicates; they are normalised before dispatch. An empty list reduces over every axis.
keepdimsbool
If true, every reduced axis appears as a size-1 dim in the output; otherwise it is removed.

Returns

std::shared_ptr<TensorImpl>

Output tensor with the reduced shape and the AMP-effective dtype (driven by schema_v1.amp_policy).

Raises

LucidError
If a is null.
NotImplemented
If the input lives on GPU and Derived exposes neither HasReduceDispatch nor HasReduceGpuKernel.

Methods

5
fn

apply

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

Storage-mode backward: delegate the full broadcast-and-scale to Derived::grad_formula.

Unlike UnaryKernel::apply, this method performs no reduce_grad_to_shape step — the reduction kernel's grad_formula is responsible for broadcasting the upstream gradient back to full_input_shape_ using the saved reduce_axes_ and keepdims_ fields, and for any reduction-specific scaling.

Parameters

grad_outStorage
Gradient of the loss with respect to this op's output, shaped like the forward output.

Returns

std::vector<Storage>

Single-element vector containing the input gradient, shaped like full_input_shape_.

fn

apply_for_graph

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

Graph-mode backward: rebuild the broadcast in tracked ops.

Re-inserts size-1 axes for any dims that were dropped because keepdims=False, runs broadcast_to_op to expand the gradient back to full_input_shape_, then defers to scale_graph_grad for the reduction-specific factor. The entire chain participates in the autograd graph so higher-order gradients work correctly.

Parameters

grad_outconst TensorImplPtr&
Upstream gradient as a live TensorImpl (i.e. a graph node), not just a Storage.

Returns

std::vector<TensorImplPtr>

Single-element vector containing the input gradient tensor.

fnconst

name

→std::string_view
int name()

Schema-derived op name, exposed to the IKernel virtual interface for error messages and profiler scopes.

Returns

std::string_view

Derived::schema_v1.name (e.g. "sum", "mean").

fnconst

node_name

→std::string
int node_name()

Schema-derived node name used by the autograd graph display and create_graph error reports.

Returns

std::string

Owning copy of Derived::schema_v1.name.

fn

scale_graph_grad

→TensorImplPtr
int scale_graph_grad(const int & g)

Graph-mode gradient scaling hook.

Default implementation passes the gradient through unchanged, matching the sum rule (every reduced element contributed with unit weight). Derived classes whose rule has a non-trivial scale — MeanBackward divides by NN, ProdBackward multiplies by the product of the others, the argmax variants apply an indicator mask — override this method to inject their factor before the gradient is returned.

Parameters

gconst TensorImplPtr&
Broadcast-back gradient already shaped like the original input. Always non-null.

Returns

TensorImplPtr

The scaled gradient — either g itself or a fresh tensor produced by a graph-tracked op.