Add the Batch Axis Without Mixing Sequences
Batch-major attention preserves separate batch, position, and feature axes while sharing projection parameters. Trace batched matrix multiplication, mask broadcasting, padding, and an independence test that detects cross-sequence mixing.
A batch stores several sequences in one tensor so the same operations can be carried out together. For batch-major input,
The first axis selects a sequence, the second selects a position within that sequence, and the third selects a feature. Keeping these meanings explicit is more useful than memorizing a framework call.
Projections Preserve Batch and Position Axes
Multiplication by a projection matrix contracts only the final feature axis:
The same parameter matrices are used at every position and in every batch item. Sharing parameters does not mix the data. Sequence still produces , , and only from .
Transpose Only the Final Two Axes
For each batch item,
In tensor notation,
The transpose swaps the position and key-feature axes inside each batch item. Moving the batch axis would change which sequences are paired and can create a silent data-leakage bug even when a matrix multiplication still runs.
A Shared Causal Mask Can Broadcast
When every batch item has the same sequence length and causal rule, one mask with shape can be broadcast across :
Broadcasting means that the same mask values are applied to every batch item; it does not combine their scores.
Sequences of different lengths are often padded to a common . A padding mask removes artificial padding positions, while the causal mask removes real future positions. These masks express different rules and may be combined before softmax. Every query row that is used must retain at least one allowed key, or softmax has no valid distribution to normalize.
Two Sequences Stay Independent
Let the batch contain
With identity Q/K/V projections, the first sequence forms scores from entries in only. Doubling changes the second sequence's dot products but cannot change , , or . This independence is a useful test: alter one batch item and assert that every output in the other items remains fixed.
Check independence across a batch
The function computes identity-projection attention separately for each batch item. Change the second sequence and verify that the first output remains fixed.
Ready to run.
Q1. Derive a batched score shape
and both have shape under the batch-major convention. What is the shape of when the transpose swaps only the final two axes?
Select one choice, then check.
Hint
Solution
Name Every Axis Before Reshaping
Many attention bugs are valid tensor operations with the wrong semantic axes. Before a transpose, broadcast, or matrix multiplication, write the axis names beside the shapes. Then test independence by changing one batch item. A passing shape check alone does not prove that batch boundaries were preserved.