matmul¶
Batched matrix product of tensors with arbitrary leading batch dimensions.
Category: arithmetic ยท Identity: matmul@1
Shape¶
| Port | Direction | Pattern | dtype |
|---|---|---|---|
a |
input | a[B, ..., N, K] |
compute |
b |
input | b[B, ..., K, M] |
compute |
out |
output | out[B, ..., N, M] |
compute |
Arguments¶
This operator takes no scalar arguments.
Description¶
out[i] = a[i] @ b[i] for every batch element i: the operation
torch.bmm performs (torch.matmul agrees at rank 3).
Both tensor inputs must be supplied explicitly, as with mul and
add; there is no implicit current-tensor operand for the second port.
The inner dimension K is a shared symbol, so a known width on either
side fixes the other and a mismatch is reported as E_CONSTRAINT while
the plan resolves. The batch is shared: there is no broadcasting of the
batch axis or of a missing axis.
Batched matrix multiplication supports rank 3 and rank 4 tensors with
matching leading batch dimensions [B, ..., N, K] @ [B, ..., K, M] -> [B, ..., N, M].
Both operands must share the same rank (at least 3) and leading dimensions;
rank 2 tensors are not supported (use linear for 2D feature maps).
There are no parameters and no buffers, train and eval behave identically, and the product runs in the plan compute dtype. Reduced-precision matrix multiplies accumulate in float32 on CUDA tensor cores, so float16 and bfloat16 results are close to, but not bitwise equal to, the same product done in full precision.
Examples¶
Example 1¶
The energy map of self-attention: a sequence times its own transpose.
Input ['B', 6, 4] โ output ['B', 6, 6].
Network: [B, 6, 4] -> [B, 6, 6] dtype=float32
name operation input shapes output shapes
n0 transpose x=input:x:[B, 6, 4] out=[B, 4, 6]
n1 matmul a=input:x:[B, 6, 4], b=node:n0/out:[B, 4, 6] out=[B, 6, 6]
Parameters: 0
Example 2¶
Dot-product attention without projections: scores, softmax, then a weighted sum of x.
Input ['B', 6, 4] โ output ['B', 6, 4].
Network: [B, 6, 4] -> [B, 6, 4] dtype=float32
name operation input shapes output shapes
n0 transpose x=input:x:[B, 6, 4] out=[B, 4, 6]
n1 matmul a=input:x:[B, 6, 4], b=node:n0/out:[B, 4, 6] out=[B, 6, 6]
n2 softmax x=node:n1/out:[B, 6, 6] out=[B, 6, 6]
n3 matmul a=node:n2/out:[B, 6, 6], b=input:x:[B, 6, 4] out=[B, 6, 4]
Parameters: 0
Example 3¶
The shared inner dimension K flows backward: the projection width is inferred as 6.
Input ['B', 4, 6] โ output ['B', 4, 4].
Network: [B, 4, 6] -> [B, 4, 4] dtype=float32
name operation input shapes output shapes
n0 linear x=input:x:[B, 4, 6] out=[B, 4, 6]
n1 transpose x=input:x:[B, 4, 6] out=[B, 6, 4]
n2 matmul a=node:n0/out:[B, 4, 6], b=node:n1/out:[B, 6, 4] out=[B, 4, 4]
Parameters: 42