Skip to content
fn

var_op

→TensorImplPtr
int var_op(const int & a, const int & axes, bool keepdims)

Python wrappers

Public Python APIs implemented by this engine symbol.

Compute the biased variance of a along axes.

Uses the population estimator σ2=1N∑i(xi−xˉ)2\sigma^2 = \frac{1}{N} \sum_i (x_i - \bar{x})^2 — i.e. the denominator is NN, not N−1N - 1. This corresponds to the reference framework's unbiased=False (population) variant; the unbiased / sample variant is not exposed by this entry point. The standard deviation std_op is built directly on top by composing sqrt with this op so the autograd chain is automatic.

During the forward pass the mean is computed once with keepdims=true and broadcast to the full input shape so that VarBackward::apply can compute x−xˉx - \bar{x} without a second broadcast call. Both the input x and the broadcast mean are saved on the backward node.

Math

σ2=1N∑i∈axes(xi−xˉ)2,∂L∂xi=2N(xi−xˉ)⋅broadcast ⁣(∂L∂σ2). \sigma^2 = \frac{1}{N} \sum_{i \in \text{axes}} (x_i - \bar{x})^2, \qquad \frac{\partial \mathcal{L}}{\partial x_i} = \frac{2}{N}(x_i - \bar{x})\cdot \mathrm{broadcast}\!\left(\frac{\partial \mathcal{L}} {\partial \sigma^2}\right).

Shape

If keepdims is false, the reduced axes are removed; if true, they become size-11.

See Also

std_op — square root of the variance.

Parameters

aTensorImplPtr
Input tensor of float dtype. Non-null.
axesstd::vector<int>
Axes to reduce. May be empty (reduce all axes). Negative indices wrap around ndim.
keepdimsbool
If true, retains reduced dims as size-1 entries; otherwise they are collapsed.

Returns

TensorImplPtr

Output tensor with the reduced shape. Autograd is wired when a->requires_grad() is true and GradMode is enabled.

Notes

Internal dispatch: IBackend::variance — Accelerate on CPU, MLX on GPU. The CPU implementation uses Welford-style accumulation for numerical stability on large NN. The empty-axis edge case (reduced == 0) clamps the count to 11 to avoid a division by zero in the backward node; in that pathological case the gradient is not statistically meaningful but is well-defined.