Skip to content
fn

reduce

→Tensor
reduce(tensor: Tensor | list[Tensor], pattern: str, reduction: str | Callable[[Tensor, tuple[int, ...]], Tensor], axes_lengths: int = {})

Reduce tensor along axes implied by an einops pattern.

Generalises standard sum / mean / max / min / prod reductions to arbitrary axes selected by symbolic pattern. Any axis present on the left-hand side of -> but absent on the right-hand side is collapsed by the chosen reduction.

Parameters

tensorTensor or list of Tensor
Input tensor to reduce. A list of equally shaped tensors is stacked along a new leading axis first, so the pattern names it.
patternstr
Einops pattern such as "b h w -> b w". A number on the left is an unnamed axis of that length, so "(h 2) (w 2) -> h w" pools 2x2 windows.
reductionstr or callable
Reduction operation; one of "sum", "mean", "max", "min", "prod", "any", "all". A callable f(tensor, axes) is also accepted: it is given the tensor with the axes to reduce moved last, and the positions axes they then occupy, and returns the reduced tensor.
**axes_lengthsint= {}
Axis lengths, needed to split a dimension into a group and checked against the input wherever the input already fixes the axis.

Returns

Tensor

The reduced tensor.

Raises

lucid._C.engine.InvalidArgument
The pattern is malformed, the reduction is unknown, an axis appears only on the right, or a keyword names no axis.
lucid._C.engine.ShapeMismatch
The input's shape does not fit the pattern or the keyword lengths.
lucid._C.engine.NotImplementedError
reduction="mean" over a tensor that is not floating point.

Notes

Conceptually equivalent to a permutation followed by a reduction along contiguous trailing axes. For reduction="mean" the result is

ybw=1H∑h=1Hxbhw.y_{b w} = \frac{1}{H} \sum_{h=1}^{H} x_{b h w}.

Examples

>>> import lucid
>>> x = lucid.randn(2, 3, 4)
>>> lucid.einops.reduce(x, "b h w -> b w", "mean").shape
(2, 4)
>>> lucid.einops.reduce(lucid.randn(2, 4, 6), "b (h 2) (w 3) -> b h w", "max").shape
(2, 2, 2)
>>> total = lambda t, axes: lucid.sum(t, dim=list(axes))
>>> lucid.einops.reduce(lucid.ones(2, 3), "b w -> b", total)
tensor([3., 3.])