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
Input tensor to reduce. A list of equally shaped tensors is
stacked along a new leading axis first, so the pattern names it.
patternstrEinops 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 callableReduction 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
TensorThe reduced tensor.
Raises
lucid._C.engine.InvalidArgumentThe pattern is malformed, the reduction is unknown, an axis
appears only on the right, or a keyword names no axis.
lucid._C.engine.ShapeMismatchThe input's shape does not fit the pattern or the keyword lengths.
lucid._C.engine.NotImplementedErrorreduction="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
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.])