Linear algebra
Matrix multiplication and batched matrix multiplication
PyTorch · Function
Computes tensor contractions using Einstein-summation notation. It aligns dimensions by labels, multiplies corresponding elements, and sums labels omitted from the output.
torch.einsum interprets letters in an equation as dimension labels for each operand. It multiplies operand elements whose labels align, broadcasts ellipsis-covered dimensions when used, and sums dimensions omitted from the output; an explicit arrow selects the output labels.
torch.einsum(*equation*, **operands*) → Tensor| Name | Type | Description |
|---|---|---|
equation | str | Equation string describing the subscripts for each operand and, optionally after ->, the output subscripts. |
operands | Tensor | Input tensors participating in the Einstein summation. |
Tensor containing the computed Einstein summation.
ij,jk->ik performs ordinary matrix multiplication.Ellipsis.import torch
A = torch.tensor([[1., 2., 3.], [4., 5., 6.]])
B = torch.tensor([[7., 8.], [9., 10.], [11., 12.]])
C = torch.einsum("ij,jk->ik", A, B)
print(C)Multiplies a 2×3 matrix by a 3×2 matrix, producing a 2×2 result.
Matrix multiplication and batched matrix multiplication
Tensor contractions with explicit reduction dimensions
Broadcasted operations over leading dimensions
The equation assigns labels to operand dimensions. Einsum multiplies elements after aligning equal labels, then reduces labels absent from the output; for example, ij,jk->ik expresses matrix multiplication.
Follow-up: How would batch matrix multiplication be expressed? Use ellipsis for batch dimensions, such as ...ij,...jk->...ik, provided the ellipsis-covered shapes broadcast.
An explicit -> names output labels and controls their order. If omitted, labels occurring once are retained and sorted alphabetically, while repeated labels are reduced.
Follow-up: What does an ellipsis contribute in the output? It represents broadcast dimensions and must be included in the output if those dimensions should remain rather than be summed out.
The equation is a string whose comma-separated label groups correspond to operands, and operands are tensors supplied after it. Labels are letters for dimensions; ellipsis can stand for one or more broadcast dimensions.
Follow-up: What alternative equation form is documented? A sublist format can pass integer label lists and Python's Ellipsis object instead of a string equation.
torch.backends.opt_einsumtorch.backends.opt_einsum.enabledtorch.backends.opt_einsum.strategy