Skip to content

← Matmul and einsum step 6 of 6

Easy Primitives

One matrix, many batches

Jump to the task

Use batch broadcasting when one matrix should be applied to several inputs. PyTorch offers matrix-multiplication functions with different shape requirements:

Function Inputs Batch behavior
torch.mm Two matrices, each rank 2 No batch axes
torch.bmm Two rank-3 tensors Equal batch sizes required
torch.matmul or @ Tensors of rank 1 or higher Compatible batch axes broadcast

All require compatible matrix dimensions. matmul also has special rules for vectors; it does not accept scalar tensors.

One shared matrix

Here two inputs share the same weight matrix:

import torch

x = torch.tensor([[[1.0, 2.0]], [[3.0, 4.0]]])  # (2, 1, 2)
w = torch.tensor([[[10.0], [1.0]]])              # (1, 2, 1)
print((x @ w).tolist())  # [[[12.0]], [[34.0]]]

The last two dimensions describe each matrix multiplication. The leading sizes, 2 and 1, are compatible for broadcasting, so the same matrix from w is used for both batch items.

torch.bmm(x, w) raises an error for these inputs because its batch sizes must match. When both batch sizes are one, it works; that special case can hide the starter's mistake.

Make the intended relationship clear

bmm is useful when you require two batches to pair item by item without broadcasting. matmul is useful when batch broadcasting is intended. Neither verifies what the axes mean in your application, so matching sizes alone do not prove the calculation is correct.

You could also explicitly expand w to the batch size before calling bmm. For this task, x @ w expresses the shared-matrix operation directly.

Your task

def apply_shared(x: torch.Tensor, w: torch.Tensor) -> torch.Tensor

x has shape (batch, n, d) and w has shape (1, d, m), with matching floating dtypes and devices. Return shape (batch, n, m), applying the single matrix in w to every batch item. Preserve the batch dimension even when its size is one.