Week 07 · Transformers for language

Compare causal and bidirectional masks on the same sequence.

← Week 6 · Subject contents · Week 8 →

Compare causal and bidirectional masks on the same sequence.

Work through the problem

Self-attention lets each position form a weighted average of value vectors. With equal logits the weights are uniform over allowed positions. A bidirectional encoder can use tokens on either side. A causal decoder can only read positions up to and including its own index.

For values [2,4,12], uniform bidirectional attention returns 6 everywhere. The causal means are [2,3,6]. Replacing the last value changes all bidirectional outputs but only the last causal output. A padding mask is separate from the direction mask.

Allowed attention positions. Panels from left to right: Causal, Bidirectional.

Allowed attention positions.

Run the Python lab

import numpy as np
values = np.array([2.,4.,12.])
causal = np.tri(3)
full = np.ones((3,3))
for name,mask in [("Causal",causal),("Bidirectional",full)]:
    weights = mask/mask.sum(1,keepdims=True)
    print(name,weights@values,[email protected]([2,4,90]))
assert np.allclose((causal/causal.sum(1,keepdims=True))@values,[2,3,6])

Output from the lab

Causal [2. 3. 6.] [ 2.  3. 32.]
Bidirectional [6. 6. 6.] [32. 32. 32.]

Practice

  1. Which mask supports next-token generation without future leakage?

Check your reasoning

  1. The causal mask, combined with a shift so the target token itself is not part of the input prefix.

← Week 6 · Subject contents · Week 8 →

Further reading · Jurafsky and Martin · Speech and Language Processing