# `Einops`
[🔗](https://github.com/woncoh1/einops-nx/blob/v0.1.0/lib/einops.ex#L1)

Pattern-based tensor transformations for Nx.

`rearrange/3`, `reduce/4`, and `repeat/3` take an `Nx.Tensor` and a pattern
such as `"batch height width -> batch (height width)"`, and return a tensor.
`parse_shape/2` extracts dimension sizes as a map with string keys.

## Patterns and lengths

Labels start with an ASCII letter and may contain letters, digits, and
underscores. Each label occurs at most once on each side of a transformation.
Parentheses combine or split dimensions, with the rightmost factor varying
fastest. A split may leave at most one factor unspecified.

The optional `axes` argument supplies positive integer lengths as a keyword
list or a string-keyed map. Supplied lengths must agree with the input shape;
unused or duplicate entries are errors. Use named lengths such as `patch: 2`
for factors greater than one, rather than a numeric pattern like `"(h 2)"`.

The literal `1` represents an anonymous singleton dimension. An ungrouped
input `...` matches zero or more dimensions and may appear at most once per
side. It may be grouped in the output, as in `"batch ... -> batch (...)"`.
`rearrange/3` and `repeat/3` must retain an input ellipsis even when it matches
zero dimensions; `reduce/4` may omit it. An empty pattern side denotes a scalar.

Patterns address ordinary axes, not vectorized axes or Nx dimension names.
Results have unnamed ordinary axes; vectorized axes are preserved.
Labels are local strings and never converted into atoms.

## Numerical definitions and errors

The four functions are `Nx.Defn` transforms and can be called inside `defn`.
Patterns, reduction choices, and supplied lengths must be known while tracing;
they cannot depend on tensor values. Tensor values are never inspected on the
host. Differentiation follows the corresponding Nx operations, while
`parse_shape/2` returns static metadata to consume in a transform.

Invalid patterns, incompatible shapes, and invalid length arguments raise
`Einops.Error` with the original call's context. Errors from the underlying
Nx operations retain their original exception types.

# `axis_lengths`

```elixir
@type axis_lengths() ::
  keyword(pos_integer()) | %{optional(String.t()) =&gt; pos_integer()}
```

Static lengths for named axes, supplied as keywords or string-keyed maps.

# `reduction`

```elixir
@type reduction() :: :sum | :mean | :min | :max | :prod | :any | :all
```

The supported Nx reduction operations.

# `parse_shape`

```elixir
@spec parse_shape(Nx.Tensor.t(), String.t()) :: %{
  optional(String.t()) =&gt; pos_integer()
}
```

Returns a string-keyed map of ordinary dimension sizes.

Use `_` to skip one dimension or `...` to skip zero or more dimensions.
`_` may be repeated; labels and `...` may not. The pattern has no `->`, and
groups and singleton literals are not accepted. An empty pattern matches a
scalar, and a pattern without labels returns an empty map.

Only shape metadata is read, so `Nx.template/2` tensors are accepted and
vectorized dimensions are excluded. Inside `defn`, consume the returned
host-side metadata in a transform; it is not a tensor result.

    iex> Einops.parse_shape(Nx.iota({2, 3, 4}), "batch _ channels")
    %{"batch" => 2, "channels" => 4}
    iex> Einops.parse_shape(Nx.template({2, 3, 4}, :f32), "batch ...")
    %{"batch" => 2}

# `rearrange`

```elixir
@spec rearrange(Nx.Tensor.t(), String.t(), axis_lengths()) :: Nx.Tensor.t()
```

Returns a tensor with dimensions reordered, split, or merged.

The input and output must contain the same named axes, and any input ellipsis
must be retained. Anonymous singleton dimensions, written as `1`, may be
inserted or removed. Use `axes` to supply all but one length in each split
input group. Tensor values and dtype are preserved.

    iex> x = Nx.iota({2, 3, 4})
    iex> Nx.shape(Einops.rearrange(x, "b h c -> b (h c)"))
    {2, 12}
    iex> Nx.shape(Einops.rearrange(x, "b h (heads d) -> b heads h d", heads: 2))
    {2, 2, 3, 2}

# `reduce`

```elixir
@spec reduce(Nx.Tensor.t(), String.t(), reduction(), axis_lengths()) :: Nx.Tensor.t()
```

Aggregates input axes absent from the output using an Nx reduction.

Accepts `:sum`, `:mean`, `:min`, `:max`, `:prod`, `:any`, or `:all`.
Dtype promotion and numerical behavior follow the corresponding Nx operation.
The result is a tensor, including a scalar tensor when the output side is
empty. Remaining axes may be reordered or merged, and singleton dimensions
may be inserted; new named axes are not allowed.

With no eliminated elementary axes, only rearrangement is performed, so
boolean conversion and dtype promotion do not occur in that case.

    iex> x = Nx.iota({2, 3}, type: :f32)
    iex> Einops.reduce(x, "b h -> b", :mean) |> Nx.to_flat_list()
    [1.0, 4.0]

# `repeat`

```elixir
@spec repeat(Nx.Tensor.t(), String.t(), axis_lengths()) :: Nx.Tensor.t()
```

Returns a tensor with additional axes filled by repeated input values.

Every new named axis needs an explicit length in `axes`, including axes of
length one. Existing named axes and any input ellipsis must be retained.
Output groups control whether copies of each element or of the whole sequence
appear consecutively. The input dtype is preserved.

    iex> x = Nx.tensor([1, 2, 3])
    iex> Einops.repeat(x, "n -> (n copies)", copies: 2) |> Nx.to_flat_list()
    [1, 1, 2, 2, 3, 3]
    iex> Einops.repeat(x, "n -> (copies n)", copies: 2) |> Nx.to_flat_list()
    [1, 2, 3, 1, 2, 3]

---

*Consult [api-reference.md](api-reference.md) for complete listing*
