Lesson 04 · Mask and interaction

What Attention Must Not See, and How Groups Talk

The LLM restricts attention: a token must not see the future it is trained to predict. The point cloud has the opposite problem: attention is already restricted to a patch, and the patches have to be made to talk. Both then split attention into heads.

map · flow · code: code/llm/c04_causal_mha.py, code/pc/c04_patch_interaction.py · book: chapter 3, sections 3.5 and 3.6

The five lessons; lesson 04 highlighted Both pipelines; the mask and heads row is marked

Where we are. Still inside the block: what the attention of lesson 3 is allowed to see, and how it is split into heads. Book Figure 3.23 shows the same position in the chapter's chain.

Book Figure 3.23: stages 1 and 2 done, now causal attention, then multi-head attention

Book Figure 3.23. Stage 3 (causal attention) exists only on the LLM side; its point-cloud counterpart is the opposite problem, patch interaction. Stage 4 (multi-head) is identical on both sides.

1The chain of this lesson

Definition · causal mask A causal mask forbids unit i from attending to any unit j > i: the weights above the diagonal of the attention matrix are forced to zero and the rest are renormalised so each row still sums to 1.

Why we need it: lesson 1's sliding window made "the next token" the target. If attention could read token t+1 while predicting it, the task is trivial and nothing useful is learned. Segmentation has no such target: every point is labelled at once, nothing is "future", so the point cloud does not mask. The serialization order is a storage order, not a time order.

LLM Book Figure 3.19: the attention weights above the diagonal are masked out so a token cannot see future tokens Book Figure 3.20: softmax, then zero out above the diagonal, then renormalise the rows
lower-triangular mask:
 tensor([[1., 0., 0., 0., 0., 0.],
        [1., 1., 0., 0., 0., 0.],
        [1., 1., 1., 0., 0., 0.],
        [1., 1., 1., 1., 0., 0.],
        [1., 1., 1., 1., 1., 0.],
        [1., 1., 1., 1., 1., 1.]])
masked and renormalised weights:
 tensor([[1.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000],
        [0.4833, 0.5167, 0.0000, 0.0000, 0.0000, 0.0000],
        [0.3190, 0.3408, 0.3402, 0.0000, 0.0000, 0.0000],
        [0.2445, 0.2545, 0.2542, 0.2468, 0.0000, 0.0000],
        [0.1994, 0.2060, 0.2058, 0.1935, 0.1953, 0.0000],
        [0.1624, 0.1709, 0.1706, 0.1654, 0.1625, 0.1682]],
       grad_fn=<DivBackward0>)
⚙ torch.tril(torch.ones(6, 6)), multiply, divide by row sums · c04_causal_mha.py § mask
Point cloud The 3 by 3 weights of the three-point example without a mask, and what a causal mask would do: the first point would see only itself
segmentation labels every point at once: nothing is 'future', so there is no causal mask.
with a causal mask the first point of a patch could see 1 point; without it, every point sees all 64
⚙ no mask line anywhere in PatchAttention · c04_patch_interaction.py § no_mask

↓ masking after softmax needs a second normalisation — there is a cheaper place to mask

Definition · the −∞ trick Set the masked scores to −∞ before the softmax. exp(−∞) = 0, so the masked weights are exactly 0 and the softmax normalises the remaining ones in the same pass.

Why we need it: one normalisation instead of two, and the mask becomes a constant matrix that can be registered once as a buffer and sliced for any sequence length. This is what the book's CausalAttention and MultiHeadAttention classes do.

LLM Book Figure 3.21: mask with minus infinity above the diagonal, then apply softmax
scores with -inf above the diagonal:
 tensor([[0.3111,   -inf,   -inf,   -inf,   -inf,   -inf],
        [0.1655, 0.2602,   -inf,   -inf,   -inf,   -inf],
        [0.1667, 0.2602, 0.2577,   -inf,   -inf,   -inf],
        [0.0510, 0.1080, 0.1064, 0.0643,   -inf,   -inf],
        [0.1415, 0.1875, 0.1863, 0.0987, 0.1121,   -inf],
        [0.0476, 0.1192, 0.1171, 0.0731, 0.0477, 0.0966]],
       grad_fn=<MaskedFillBackward0>)
softmax does the renormalisation for free:
 tensor([[1.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000],
        [0.4833, 0.5167, 0.0000, 0.0000, 0.0000, 0.0000],
        [0.3190, 0.3408, 0.3402, 0.0000, 0.0000, 0.0000],
        [0.2445, 0.2545, 0.2542, 0.2468, 0.0000, 0.0000],
        [0.1994, 0.2060, 0.2058, 0.1935, 0.1953, 0.0000],
        [0.1624, 0.1709, 0.1706, 0.1654, 0.1625, 0.1682]],
       grad_fn=<SoftmaxBackward0>)
⚙ attn_scores.masked_fill(torch.triu(ones, diagonal=1).bool(), -torch.inf) · c04_causal_mha.py § inf
code (CausalAttention, Listing 3.3)
class CausalAttention(nn.Module):

    def __init__(self, d_in, d_out, context_length, dropout, qkv_bias=False):
        super().__init__()
        self.d_out = d_out
        self.W_query = nn.Linear(d_in,d_out, bias=qkv_bias)
        self.W_key = nn.Linear(d_in,d_out, bias=qkv_bias)
        self.W_value = nn.Linear(d_in,d_out, bias=qkv_bias)

        self.dropout = nn.Dropout(dropout) # now we add the dropout rate here

        # The registered_buffer call is also new adddition
        self.register_buffer(
            'mask',
            torch.triu(torch.ones(context_length, context_length),
            diagonal=1)
        )

    def forward(self,x):
        b, num_tokens,d_in = x.shape
        # 1. Projection
        keys = self.W_key(x)
        queries = self.W_query(x)
        values = self.W_value(x)
        #2. Attention scores
        attn_scores = queries @ keys.transpose(1,2)
        # 3. Causal mask (in-place, trailing underscore)
        attn_scores.masked_fill_(self.mask.bool()[:num_tokens, :num_tokens],-torch.inf)
        # 4. Attention weights
        attn_weights = torch.softmax(
            attn_scores/keys.shape[-1]**0.5, dim=-1
        )
        # 5. dropout
        attn_weights = self.dropout(attn_weights)
        # 6. context vector
        context_vec = attn_weights @ values

        return context_vec
Point cloud

Nothing to mask, so nothing to fill. The two mask lines of Listing 3.5 are the only lines removed to get PTv3's attention (see the heads card below).

↓ a model that can see its whole past can also overfit to it — regularise the weights

Definition · dropout on attention (and its point-cloud cousins) Dropout zeroes a random fraction of the attention weights during training and scales the rest by 1/(1−p), so the model cannot rely on any one connection. PTv3 regularises differently: Shuffle Order randomly permutes which serialization pattern each block uses in every stage, and drop path (0.3) skips whole residual branches at random.

Why we need it: with weights that sum to 1 a model can learn to put all of it on one convenient token or one convenient curve. Randomising what is available forces redundancy. For the point cloud the randomness is in the grouping, which is the more useful place, because the grouping is the approximation (lesson 1).

LLM Book Figure 3.22: the causal mask, then a dropout mask zeroes additional attention weights at random
tensor([[2., 2., 0., 2., 2., 0.],
        [0., 0., 0., 2., 0., 2.],
        [2., 2., 2., 2., 0., 2.],
        [0., 2., 2., 0., 0., 2.],
        [0., 2., 0., 2., 0., 2.],
        [0., 2., 2., 2., 2., 0.]])
⚙ torch.nn.Dropout(0.5)(torch.ones(6, 6)) (seed 123) · c04_causal_mha.py § dropout
Point cloud
  stage 0: block order = ['z', 'z-trans', 'hilbert', 'hilbert-trans']
  stage 1: block order = ['hilbert-trans', 'z', 'hilbert', 'z-trans']
  stage 2: block order = ['hilbert-trans', 'z', 'z-trans', 'hilbert']
  stage 3: block order = ['hilbert', 'hilbert-trans', 'z-trans', 'z']
Shuffle Order: a fresh permutation of the four patterns per stage, so no block is tied to one curve
⚙ rng.permutation(['z', 'z-trans', 'hilbert', 'hilbert-trans']) per stage · c04_patch_interaction.py § shuffle

↓ the LLM's attention already reaches the whole past; a patch reaches 64 points — how does a point ever see the rest of the car?

Definition · patch interaction (Shift Order) With fixed patches a point meets the same 63 companions in every layer and the receptive field never grows. Shift Order: block i uses serialization pattern i mod 4 (Z, trans-Z, Hilbert, trans-Hilbert). The points do not move; the patch boundaries do, because each pattern sorts them differently. Since the four permutations were computed once in lesson 1, this costs nothing.

Why we need it: a backbone must give each point information from far away: the roof of the car tells a wheel it is a wheel. Depth alone does not help if every layer sees the same 64 points. The alternatives, shifting patch windows (Swin) or dilating them (OctFormer), need attention masks and cost about 35 ms more per forward in the paper's ablation.

LLM

No counterpart is needed: within a window every token already attends to every earlier token, so one layer connects everything. Depth adds nonlinearity, not reach.

Point cloud Four blocks using the four patterns in turn; the number of points reachable from one point grows 64, 86, 112, 130, measured on the car
points reachable from one point after L layers (patch 64, Shift Order cycling Z, TZ, H, TH):
  L=1: mean   64.0   min  64   max  64   ( 2.6% of the cloud)
  L=2: mean   85.7   min  65   max 127   ( 3.4% of the cloud)
  L=3: mean  112.2   min  78   max 177   ( 4.5% of the cloud)
  L=4: mean  129.5   min  84   max 228   ( 5.2% of the cloud)
same pattern in every layer (no Shift Order): 64 points, forever
Shift Patch (2 layers, Z only): mean reach 94.8  vs Shift Order 2 layers above; but it needs attention masks
⚙ reach(point, layers) = union of patch-mates under patterns 0..L−1 · c04_patch_interaction.py § reach
code
pids = {name: patch_id_of(inverses[name], PATCH) for name in PATTERNS}
names = list(PATTERNS)
def reach(point, layers):
    seen = set()
    for L in range(layers):
        name = names[L % 4]
        seen |= set(np.flatnonzero(pids[name] == pids[name][point]))
    return len(seen)
rng = np.random.default_rng(0)
sample = rng.choice(len(coords), 200, replace=False)
print("points reachable from one point after L layers (patch 64, Shift Order cycling Z, TZ, H, TH):")
for L in (1, 2, 3, 4):
    r = [reach(p, L) for p in sample]
    print(f"  L={L}: mean {np.mean(r):6.1f}   min {min(r):3d}   max {max(r):3d}   ({np.mean(r)/len(coords)*100:4.1f}% of the cloud)")
print("same pattern in every layer (no Shift Order):", reach(int(sample[0]), 1), "points, forever")

↓ one attention learns one kind of relation — run several in parallel

Definition · multi-head attention Split dout into h heads of dout/h dimensions, run the attention of lesson 3 in each head with its own slice of q, k, v, concatenate the h context vectors, and project once. Implemented as one qkv projection followed by a reshape (b, T, h, d/h) and a transpose, so all heads are one batched matmul.

Why we need it: one softmax row is one pattern of who-looks-at-whom. Language needs several at once (subject, previous word, punctuation); a point needs several too (along the surface, across the gap, by intensity). Heads give the layer h independent weightings at the same cost as one wide head.

LLM Book Figure 3.24: two single-head attention modules stacked, each with its own weight matrices and context vectors Book Figure 3.26: one large query matrix is computed, then split into per-head queries
tensor([[ 0.1184,  0.3120, -0.0847, -0.5774],
        [ 0.0178,  0.3221, -0.0763, -0.4225],
        [-0.0147,  0.3259, -0.0734, -0.3721],
        [-0.0116,  0.3138, -0.0708, -0.3624],
        [-0.0117,  0.2973, -0.0698, -0.3543],
        [-0.0132,  0.2990, -0.0689, -0.3490]], grad_fn=<SelectBackward0>)
context_vecs.shape: (2, 6, 4) = (batch, tokens, d_out) with head_dim = 2
GPT-2 small attention module: 12 heads x head_dim 64; parameters: 2,360,064
⚙ MultiHeadAttention(d_in=3, d_out=4, context_length=6, dropout=0.0, num_heads=2) (Listing 3.5) · c04_causal_mha.py § mha, § gpt2
code (MultiHeadAttention)
class MultiHeadAttention(nn.Module):
    def __init__(self, d_in, d_out, context_length, dropout, num_heads, qkv_bias=False):
        super().__init__()

        assert(d_out%num_heads ==0), "d_out must be divisible by num_heads"

        self.d_out = d_out
        self.num_heads = num_heads
        #Reduce the projection dimension to match the desired output dim
        self.head_dim = d_out//num_heads
        # Projection weight matrix
        self.W_query = nn.Linear(d_in, d_out, bias=qkv_bias)
        self.W_key = nn.Linear(d_in, d_out, bias=qkv_bias)
        self.W_value = nn.Linear(d_in, d_out, bias=qkv_bias)
        # Uses a Linear Layer to combine head outputs
        self.out_proj = nn.Linear(d_out,d_out)

        self.dropout = nn.Dropout(dropout)

        self.register_buffer("mask", torch.triu(torch.ones(context_length,context_length),diagonal=1))

    def forward(self, x):
        b, num_tokens, d_in = x.shape
        # Projection
        keys = self.W_key(x) # tensor shape: [b,num_tokes, d_out]
        queries = self.W_query(x) # tensor shape: [b,num_tokes, d_out]
        values = self.W_value(x) # tensor shape: [b,num_tokes, d_out]

        # Unroll last dim: (b, num_tokens, d_out) -> (b, num_tokens, num_heads, head_dim)
        keys = keys.view(b, num_tokens, self.num_heads,self.head_dim)
        values = values.view(b, num_tokens, self.num_heads,self.head_dim)
        queries = queries.view(b, num_tokens, self.num_heads,self.head_dim)

        #Transpose: (b,num_tokens,num_heads, head_dim) --> (b, num_heads, num_tokens, head_dim)
        keys = keys.transpose(1,2)
        queries = queries.transpose(1,2)
        values = values.transpose(1,2)

        # Compute scaled dot-product attention (aka self-attention) with a causal mask
        attn_scores = queries @ keys.transpose(2,3) # Dot product for each head

        # Original mask truncated to the number of tokens and converted to boolean
        mask_bool = self.mask.bool()[:num_tokens, :num_tokens]

        # use the mask to fill attention scores
        attn_scores.masked_fill_(mask_bool, -torch.inf)

        attn_weights = torch.softmax(attn_scores/keys.shape[-1]**0.5, dim = -1)
        attn_weights = self.dropout(attn_weights)

        # Shape: (b, num_tokens, num_heads, head_dim)
        context_vec = (attn_weights @ values).transpose(1,2)

        # Combine heads, where self.d_out = self.num_heads * self.head_dim
        context_vec = context_vec.contiguous().view(b,num_tokens, self.d_out)
        context_vec = self.out_proj(context_vec) # optional projection

        return context_vec
Point cloud Shapes through PTv3's patch attention: patches tensor, fused qkv, split into 4 heads, 64 by 64 weights per head, merge, inverse order
patches tensor: (40, 64, 32) = (patches, patch_size, channels)
attention weights: (40, 4, 64, 64) = (patches, heads, K, K); row sums: [1.0, 1.0, 1.0]
output: (40, 64, 32)  -> back to (N, C) with the inverse permutation
PTv3 heads per stage: 4, 8, 16, 32 (head_dim stays 16 as channels grow 64 -> 512)
⚙ PatchAttention(dim=32, num_heads=4)(seq): Listing 3.5 minus the two mask lines, with a fused qkv linear · c04_patch_interaction.py § heads
code (PatchAttention)
class PatchAttention(nn.Module):
    """Multi-head scaled dot-product attention inside each patch. No mask: every point sees its whole patch."""
    def __init__(self, dim, num_heads, qkv_bias=True):
        super().__init__()
        assert dim % num_heads == 0
        self.num_heads = num_heads
        self.head_dim = dim // num_heads
        self.qkv = nn.Linear(dim, 3 * dim, bias=qkv_bias)   # one fused projection, as in PTv3
        self.proj = nn.Linear(dim, dim)

    def forward(self, x, return_weights=False):
        B, K, C = x.shape                                    # (patches, patch_size, channels)
        qkv = self.qkv(x).view(B, K, 3, self.num_heads, self.head_dim)
        q, k, v = qkv.unbind(2)                              # each (B, K, heads, head_dim)
        q, k, v = q.transpose(1, 2), k.transpose(1, 2), v.transpose(1, 2)   # (B, heads, K, head_dim)
        attn = (q @ k.transpose(-2, -1)) / self.head_dim ** 0.5
        attn = attn.softmax(dim=-1)                          # no causal mask
        out = (attn @ v).transpose(1, 2).reshape(B, K, C)
        out = self.proj(out)
        return (out, attn) if return_weights else out

↓ attention with heads is one sub-layer — lesson 5 wraps it into a block and stacks the blocks

2Try it

LLM · what the mask removes, and what two heads see

Hatched cells are −∞ before softmax. The two heads of the same layer weight the same tokens differently.

Point cloud · click a point, add layers

1
Click a point on the car.

Colour = the layer in which a point first becomes reachable from the clicked point. Turn Shift Order off and the set stops growing.

3What this lesson established

Why is −∞ better than multiplying the weights by a 0/1 mask?

Masking after softmax leaves rows that no longer sum to one and needs a second normalisation. With −∞ before softmax, exp gives exactly 0 and the normalisation happens once.

Would a causal mask hurt a point-cloud model?

Yes. Points early in the serialized order would see only themselves; there is no reason a point should ignore its neighbour because that neighbour has a larger curve code.

Why does Shift Order cost nothing while Shift Patch costs about 35 ms?

Shift Order reuses a permutation computed once; grouping is still contiguous slicing. Shift Patch and Shift Dilation change the grouping inside a fixed order, so attention needs masks to express the irregular groups.