The Transformer, Number by Number  ·  Part 8

What a Row Is Not Allowed to See

Run 1 receives <start>. Run 2 receives <start> J’aime. How does adding J’aime affect the self-attention calculation?

We continue with I love LLMs and the translation J’aime les grands modèles. Each displayed word counts as one token in this teaching example. The token choices illustrate the inference loop; they are not predictions calculated from our hand-picked parameters.

Part 7 calculated the first decoder block on run 1. We now repeat its self-attention calculation with the two-token input on run 2. The causal mask controls which positions each Query may read. Later, we use a padding mask to exclude the extra positions added to shorter sentences.

We use the attention calculation from Part 1 and the distinction between a decoder run and a decoder block from Part 7, Section 7.6.

Numerical conventions inherited from Part 7
  • One attention head; each vector has shape 1 × 4, so \(d_{\text{model}}=d_k=4\).
  • Embedding scaling and positional encoding. The original Transformer multiplies each token embedding by \(\sqrt{d_{\text{model}}}\) before adding positional encoding. We omit both operations and use the supplied embeddings directly. This input scaling is separate from dividing attention scores by \(\sqrt{d_k}\), which we still do.
  • The Query, Key and Value projections have zero biases.
  • Rounding for this hand calculation. As in Part 7, use the displayed rounded results in the next step, including the rounded exponentials and attention weights. Round to two decimals; a value exactly halfway rounds away from zero, so 0.385 becomes 0.39, as in Part 7, Section 7.4.3. This differs from Part 6, which keeps full precision within each calculation. Keeping full precision here can therefore give slightly different final entries.

8.1Two positions, four scores, one forbidden connection

Run 1 receives <start>; run 2 receives <start> J’aime. Each position represents the target prefix ending there. Figure 1 pairs that prefix with the next token in our example translation.

Which target prefix does each position represent?

PositionAllowed target prefixNext token to predict
1 · <start><start>J’aime
2 · J’aime<start> J’aimeles
Figure 1. Each position has its own target-prefix boundary. During inference, only the last position’s final hidden state is used to select the next token on that run.

J’aime is allowed input for position 2, but lies beyond position 1’s prefix. Letting position 1 read it would give that position the token its state is meant to help predict. “Later” is relative to the row’s position, even when both tokens are already in the decoder input. The causal mask enforces this boundary on target-side information; cross-attention can still use the source sentence.

We number positions from 1: row \(i\) computes the output at position \(i\); column \(j\) refers to the position it may read.

In run 2, the decoder input is <start> J’aime. We use the <start> embedding from Part 7, \((1,0,0,0)\), and choose \((1,1,0,1)\) for J’aime. Stacking these embeddings as two rows gives the input to the first decoder block:

\[ \mathbf X_{\text{dec}}=\begin{pmatrix}1&0&0&0\\1&1&0&1\end{pmatrix}. \]

The first row represents <start>; the second represents J’aime. The input has shape 2 × 4. To calculate self-attention, we turn these embeddings into Query, Key and Value vectors. Apply the three projection matrices supplied in Part 7, Section 7.3:

\[ \begin{aligned} \mathbf Q_{\text{dec-self}}&=\mathbf X_{\text{dec}}\mathbf W^Q_{\text{dec-self}}=\begin{pmatrix}-1&0&-1&1\\-1&-1&-3&1\end{pmatrix},\\ \mathbf K_{\text{dec-self}}&=\mathbf X_{\text{dec}}\mathbf W^K_{\text{dec-self}}=\begin{pmatrix}1&0&0&-1\\-1&0&-1&-1\end{pmatrix},\\ \mathbf V_{\text{dec-self}}&=\mathbf X_{\text{dec}}\mathbf W^V_{\text{dec-self}}=\begin{pmatrix}1&0&-1&1\\1&0&0&2\end{pmatrix}. \end{aligned} \]

The first row of each of \(\mathbf Q_{\text{dec-self}}\), \(\mathbf K_{\text{dec-self}}\) and \(\mathbf V_{\text{dec-self}}\) matches Part 7’s calculation for <start>. To check the J’aime Query, multiply \((1,1,0,1)\) by \(\mathbf W^Q_{\text{dec-self}}\). The three 1s select rows 1, 2 and 4 of that projection matrix:

\[ \underbrace{(-1,0,-1,1)}_{\text{row 1}}+ \underbrace{(0,0,-1,-1)}_{\text{row 2}}+ \underbrace{(0,-1,-1,1)}_{\text{row 4}} =(-1,-1,-3,1). \]

The sum is the second row of \(\mathbf Q_{\text{dec-self}}\), corresponding to J’aime.

Each Query is compared with each Key. Divide the dot products by \(\sqrt{d_k}=2\):

\[ \mathbf S_{\text{dec-self}}=\frac{\mathbf Q_{\text{dec-self}}\mathbf K_{\text{dec-self}}^\top}{2} =\frac12\begin{pmatrix}-2&1\\-2&3\end{pmatrix} =\begin{pmatrix}-1&0.5\\-1&1.5\end{pmatrix}. \]

We call this scaled score matrix \(\mathbf S_{\text{dec-self}}\). Rows identify query positions; columns identify key positions. Both axes follow the order <start>, J’aime.

Run 2 produces four attention scores: each of the two Queries is compared with both Keys. Figure 2 highlights the score in row 1, column 2, where the <start> Query is compared with the J’aime Key. The causal mask will block this connection. Next, we compare attention with and without that mask.

TWO ROWS IN, FOUR SCORES OUTrun 2: query rows and key columns both follow the target prefixQ· Query rows−10−11<start>−1−1−31J’aime2 × 4×Kᵀ· transposed Keys1−1000−1−1−1<start>J’aime4 × 2=scores· divided by 2−10.5<start>−11.5J’aime<start>J’aime2 × 2the mask will block:<start> reading J’aimeThe multiplication computes all four scores, including the highlighted score of 0.5.These scores are used in the masked and unmasked comparisons below.

Scroll horizontally to see the full diagram. With this area focused, use the left and right arrow keys.

Figure 2. Two Query vectors and two Key vectors produce four scaled scores. The highlighted score compares the <start> Query with the J’aime Key; the causal mask will block this connection.

Check the highlighted score directly: row 1 of \(\mathbf Q_{\text{dec-self}}\) is the <start> Query, and row 2 of \(\mathbf K_{\text{dec-self}}\) is the J’aime Key. Their scaled dot product gives the score in row 1, column 2:

\[ (S_{\text{dec-self}})_{1,2} =\frac{(-1)(-1)+(0)(0)+(-1)(-1)+(1)(-1)}{2}=0.5. \]

8.1.1First, calculate without a mask

For these hand calculations, we round displayed results to two decimals and use them in the next step.

Without the mask, softmax processes the entire top score row, \((-1,0.5)\):

\[ (e^{-1},e^{0.5})\approx(0.37,1.65),\qquad \frac{(0.37,1.65)}{2.02}\approx(0.18,0.82). \]

The <start> position would give attention weight 0.82 to J’aime. Compare the resulting weighted sum with run 1 in Figure 3.

WHAT GOES INTO THE <start> ROWrun 1 above; unmasked run 2 below: different attention weightsRUN 1 · one Value10−11<start>× 1.0010−11self-attention outputfor <start>ValuesRUN 2 · two Values10−11<start>1002J’aime× 0.18× 0.820.180.00−0.180.180.820.000.001.64+Add matching components=1.000.00−0.181.82Sum: self-attention outputfor <start>In block 1, the Values are projected from the input embeddings.Without the mask, the later position changes the earlier position’s output.

Scroll horizontally to see the full diagram. With this area focused, use the left and right arrow keys.

Figure 3. The self-attention output for <start> on run 1 and on run 2 without a mask. In the unmasked calculation, the output adds 0.18 times the <start> Value and 0.82 times the J’aime Value.
\[ 0.18(1,0,-1,1)+0.82(1,0,0,2)=(1.00,0.00,-0.18,1.82). \]

The run-1 output was \((1,0,-1,1)\). The unmasked run-2 output now includes the J’aime Value, which lies outside position 1’s allowed target prefix.

8.2Where the mask enters the calculation

The mask must give the forbidden connection, <start> reading J’aime, zero attention weight. Part 9, Section 9.2.1 applies this same restriction during training.

The other three pairs remain available. We enforce the restriction by modifying run 2’s scaled scores, \(\mathbf S_{\text{dec-self}}\), before softmax.

A mask records which pairs are allowed. Figure 4 marks those pairs before we assign the mask its numerical values.

Which query–key pairs are allowed?

Query ↓ / Key →<start>J’aime
<start>AllowedForbidden
J’aimeAllowedAllowed

Dashed cells: later key positions. These pairs must receive zero attention weight.

Figure 4. The mask records allowed and forbidden connections. A forbidden connection does not remove either position from the input.

Why mask before softmax? For the first row, the unmasked scores \((-1,0.5)\) produce weights of approximately \((0.18,0.82)\). Simply zeroing the forbidden weight afterward would leave only 0.18 for the allowed position:

\[ \underbrace{(0.18,0)}_{\text{zeroed after softmax}},\qquad 0.18+0\neq1. \]

Zeroing the weight and then dividing by the remaining total, 0.18, would also give 1.00. Adding the mask before softmax does both steps at once. The next section shows that calculation.

Key takeawayAdd the mask to the scaled scores, then apply softmax. Forbidden positions receive zero weight; the allowed weights in each row sum to 1.

8.3Add the mask, then apply softmax

The <start> row has scores \((-1,0.5)\). We keep \(-1\) and replace the forbidden score \(0.5\) with \(-\infty\). Its exponential is then zero, so softmax gives J’aime zero weight.

8.3.1From four scores to four attention weights

We can make this change by adding \(-\infty\) at entry \((1,2)\) and adding 0 at the other three entries:

\[ \underbrace{\begin{pmatrix}-1&0.5\\-1&1.5\end{pmatrix}}_{\mathbf S_{\text{dec-self}}} +\underbrace{\begin{pmatrix}0&-\infty\\0&0\end{pmatrix}}_{\mathbf M_{\text{causal}}} =\begin{pmatrix}-1&-\infty\\-1&1.5\end{pmatrix}. \]

Only entry \((1,2)\) changes: \(0.5+(-\infty)=-\infty\). The other three entries add 0 and keep their original scores. The matrix \(\mathbf M_{\text{causal}}\) is an additive attention mask: 0 preserves an allowed score; \(-\infty\) excludes a forbidden pair.

Implementation note: negative mask values

Code may use a large negative number such as \(-10^{9}\) instead of \(-\infty\). The finite value must suit the numeric type and score range; it is an approximation to excluding a position.

Apply softmax separately to each row. In each row, the two weights correspond to <start> and J’aime, in that order. For <start>:

\[ (e^{-1},e^{-\infty})\approx(0.37,0),\qquad \frac{(0.37,0)}{0.37}=(1.00,0.00). \]

Compare the <start> row in all three cases. The two weight columns refer to <start> and J’aime:

CaseScores entering softmax<start> weightJ’aime weight
Run 1\((-1)\)1.00—
Run 2, no mask\((-1,0.5)\)0.180.82
Run 2, causal mask\((-1,-\infty)\)1.000.00

The masked entry contributes \(e^{-\infty}=0\) to the denominator and receives zero weight. Position 1 therefore combines only the Values within its allowed prefix.

For J’aime, both positions are allowed:

\[ (e^{-1},e^{1.5})\approx(0.37,4.48),\qquad \frac{(0.37,4.48)}{4.85}\approx(0.08,0.92). \]

Collect the attention weights in \(\mathbf A_{\text{dec-self}}\). These are weights over key positions, not next-token probabilities:

\[ \mathbf A_{\text{dec-self}}\approx\begin{pmatrix}1.00&0.00\\0.08&0.92\end{pmatrix}. \]

Read the result row by row:

The mask controls which Value vectors can contribute; it does not remove a token or its row.

The causal ruleIn decoder self-attention, the causal mask keeps connections to the current position and earlier positions, and blocks connections to later positions. At query position \(i\), it keeps key positions 1 through \(i\) and gives every position after \(i\) zero attention weight.

Apply the rule separately to each row: position 1 can read only itself; position 2 can read both positions.

✗ Common mistake It is tempting to think replacing the forbidden score 0.5 with 0 would do the same job as the mask, but that is wrong. Scores \((-1,0)\) give weights of approximately \((0.27,0.73)\), because \(e^0=1\), so the forbidden position would still receive most of the weight.

As in Part 7, \(\mathbf A\) holds the attention weights and \(\mathbf Z\) holds the attention output. For decoder self-attention:

\[ \mathbf A_{\text{dec-self}}=\operatorname{softmax}\!\left(\mathbf S_{\text{dec-self}}+\mathbf M_{\text{causal}}\right). \] \[ \mathbf Z_{\text{dec-self}}=\mathbf A_{\text{dec-self}}\mathbf V_{\text{dec-self}}. \tag{8-1} \]

8.3.2Combine the allowed Values

The attention weights multiply the Value vectors. First, the output for <start>:

\[ 1.00(1,0,-1,1)+0.00(1,0,0,2)=(1,0,-1,1). \]

Next, the output for J’aime:

\[ 0.08(1,0,-1,1)+0.92(1,0,0,2)=(1.00,0.00,-0.08,1.92). \]
Recap: from Query–Key scores to the weighted Value sums

The full sequence of operations is:

  1. Compare: compute each Query–Key dot product.
  2. Scale: divide by \(\sqrt{d_k}\).
  3. Mask: preserve allowed scores and replace forbidden ones with \(-\infty\).
  4. Normalise: apply softmax across each row, over key positions.
  5. Combine: multiply each Value by its attention weight, then add the weighted vectors.

The two weighted sums form the attention output:

\[ \mathbf Z_{\text{dec-self}}=\mathbf A_{\text{dec-self}}\mathbf V_{\text{dec-self}} =\begin{pmatrix}1&0&-1&1\\1&0&-0.08&1.92\end{pmatrix}. \]

The attention output \(\mathbf Z_{\text{dec-self}}\) then passes through the remaining decoder-block steps described in Part 7.

Key takeawayMask the scores, normalise the allowed weights, then combine the Values. A forbidden position has zero weight and contributes nothing to the attention output.

Try it: Suppose run 3 appends les at position 3. Its embedding \((0,0,0,1)\) gives the self-attention Key \((-1,0,0,1)\). Compare it with the <start> self-attention Query \((-1,0,-1,1)\) at position 1 and divide by 2: the scaled score at \((1,3)\) is 1. What does the causal mask add at \((1,3)\), and what attention weight does that pair receive?

8.4Extend the causal mask to any prefix length

Run 3 receives <start> J’aime les. Compared with run 2, the new les position adds a Query, a Key and a Value. Its Query adds a row to the score matrix, and its Key adds a column, so the score matrix and its mask grow from \(2\times2\) to \(3\times3\):

The same rule applies whenever the prefix grows, regardless of which tokens occupy the positions.

On run 5, the prefix is <start> J’aime les grands modèles. This run selects <end>. The mask depends on the five positions, not on their embedding values.

8.4.1The triangle, run by run

Use Figure 5 to grow the prefix one position at a time. From run 2 onward, the outlined cells mark the new row and column; the previous mask remains in the top-left corner.

Grow the prefix one position at a time

Run 1

Query ↓ / Key →<start>
<start>0

1 position; 0 forbidden pairs. The first position may read itself.

Run 2

Query ↓ / Key →<start>J’aimenew
<start>0−∞
J’aimenew00

2 positions; 1 forbidden pair. New column 2: earlier Queries cannot read position 2. New row 2: its Query may read positions 1 through 2.

Run 3

Query ↓ / Key →<start>J’aimelesnew
<start>0−∞−∞
J’aime00−∞
lesnew000

3 positions; 3 forbidden pairs. New column 3: earlier Queries cannot read position 3. New row 3: its Query may read positions 1 through 3.

Run 4

Query ↓ / Key →<start>J’aimelesgrandsnew
<start>0−∞−∞−∞
J’aime00−∞−∞
les000−∞
grandsnew0000

4 positions; 6 forbidden pairs. New column 4: earlier Queries cannot read position 4. New row 4: its Query may read positions 1 through 4.

Run 5

Query ↓ / Key →<start>J’aimelesgrandsmodèlesnew
<start>0−∞−∞−∞−∞
J’aime00−∞−∞−∞
les000−∞−∞
grands0000−∞
modèlesnew00000

5 positions; 10 forbidden pairs. New column 5: earlier Queries cannot read position 5. New row 5: its Query may read positions 1 through 5.

Figure 5. The causal mask for prefix lengths one through five. Each new position adds a row and a column while preserving the previous mask in the top-left corner.

In Figure 5, each new row allows the new position to read itself and all earlier positions. The entries on and below the diagonal therefore remain 0. With five positions, the mask is:

\[ \mathbf M_{\text{causal}}=\begin{pmatrix} 0&-\infty&-\infty&-\infty&-\infty\\ 0&0&-\infty&-\infty&-\infty\\ 0&0&0&-\infty&-\infty\\ 0&0&0&0&-\infty\\ 0&0&0&0&0 \end{pmatrix}. \]

Number rows and columns from 1. Row \(i\) identifies the query position; column \(j\) identifies the key position:

\[ (M_{\text{causal}})_{ij}=\begin{cases}0&\text{if }j\leq i,\\-\infty&\text{if }j>i.\end{cases} \]

The diagonal is allowed because a position may read itself. Entries below the diagonal refer to earlier positions. Entries above it refer to later positions and are masked.

Appending a masked position leaves the existing attention weights unchanged when their scores stay the same. For the J’aime row:

\[ \begin{aligned} \text{Run 2:}\quad &\operatorname{softmax}(-1,1.5)\approx(0.08,0.92),\\ \text{Run 3:}\quad &\operatorname{softmax}(-1,1.5,-\infty)\approx(0.08,0.92,0). \end{aligned} \]

The new entry adds \(e^{-\infty}=0\) to the denominator. Part 10, Section 10.8 discusses how unchanged earlier states support KV caching.

8.5Exclude padding positions

We now turn to encoder self-attention to examine a different problem: processing source sentences of different lengths together.

Consider two source sentences: I love LLMs and I love. The first has three tokens; the second has two. Their embedding matrices have three rows and two rows, respectively.

8.5.1Two sequence lengths in one batch

A batch is a group of examples processed together. To give both input matrices the same shape in a padded batch, append <pad> to the shorter sentence. It becomes I love <pad>, with three positions. The extra position is a padding position; it is not part of the sentence.

Figure 6 shows the two matrices before and after padding. It supplies the embeddings, including \((0,0,0,0)\) for <pad>. This zero embedding is a choice for the demonstration.

TWO SEQUENCES, ONE BATCH SHAPEone embedding per token; right padding gives both examples three positionsBEFORE PADDING · different sequence lengthsI love LLMs0011I0101love1001LLMs3 × 4I love0011I0101love2 × 4one row shortPADDED · one <pad> row of zeros, and the batch is 2 × 3 × 4I love LLMs0011I0101love1001LLMs3 × 4I love <pad>0011I0101love0000<pad>3 × 4padding positionnot a sentence tokenEach example has shape 3 × 4; the batch has shape 2 × 3 × 4.Attention operates within each example; the padding Key needs to be excluded.

Scroll horizontally to see the full diagram. With this area focused, use the left and right arrow keys.

Figure 6. Right padding gives two different sequence lengths a common batch shape. The zero padding embedding is supplied for this example; it still needs a padding mask.

The batch has shape 2 × 3 × 4: two examples, three positions per example, four components per vector. Attention still operates separately within each example. The I position in one sentence does not attend to positions in the other sentence.

In I love <pad>, column 3 of the score matrix corresponds to <pad>. A padding mask excludes this column from every row’s softmax. We are padding the source sentence, so this is a source padding mask. Encoder self-attention needs no causal restriction.

8.5.2Why even a zero padding vector needs a mask

Follow only the I row. Padding I love to I love <pad> should preserve the attention output at I. Entries below follow the order I, love, then <pad> when present.

1 · Without padding

The scaled scores in the I row are \((2,1)\).

Calculate the two scores: 2 and 1

Using the vectors from Part 1, Section 1.2:

\[ \mathbf q_I=(2,1,0,0),\qquad \mathbf k_I=(2,0,1,0),\qquad \mathbf k_{\text{love}}=(0,2,0,1). \] \[ d_k=4,\qquad \sqrt{d_k}=2. \] \[ \begin{aligned} s_{I,I}&=\frac{\mathbf q_I\mathbf k_I^\top}{\sqrt{d_k}} =\frac{2\cdot2+1\cdot0+0\cdot1+0\cdot0}{2}=2,\\ s_{I,\text{love}}&=\frac{\mathbf q_I\mathbf k_{\text{love}}^\top}{\sqrt{d_k}} =\frac{2\cdot0+1\cdot2+0\cdot0+0\cdot1}{2}=1. \end{aligned} \]
\[ \operatorname{softmax}(2,1) =\frac{(e^2,e^1)}{e^2+e^1} \approx(0.73,0.27). \] \[ \mathbf z_I^{\text{original}} \approx0.73\mathbf v_I+0.27\mathbf v_{\text{love}}. \]

2 · Add a zero padding position

With our zero padding embedding, omitted positional encoding and zero projection biases, the added score is 0 and \(\mathbf v_{\text{pad}}=\mathbf 0\).

Calculate the three scores: 2, 1 and 0

The existing Query and Keys stay unchanged. The padding position adds a zero Key:

\[ \mathbf q_I=(2,1,0,0),\qquad \sqrt{d_k}=2. \] \[ \mathbf k_I=(2,0,1,0),\qquad \mathbf k_{\text{love}}=(0,2,0,1). \] \[ \mathbf k_{\text{pad}}=\mathbf x_{\text{pad}}\mathbf W^K =\mathbf 0\mathbf W^K=(0,0,0,0). \] \[ \begin{aligned} s_{I,I}&=\frac{\mathbf q_I\mathbf k_I^\top}{\sqrt{d_k}} =\frac{2\cdot2+1\cdot0+0\cdot1+0\cdot0}{2}=2,\\ s_{I,\text{love}}&=\frac{\mathbf q_I\mathbf k_{\text{love}}^\top}{\sqrt{d_k}} =\frac{2\cdot0+1\cdot2+0\cdot0+0\cdot1}{2}=1,\\ s_{I,\text{pad}}&=\frac{\mathbf q_I\mathbf k_{\text{pad}}^\top}{\sqrt{d_k}} =\frac{2\cdot0+1\cdot0+0\cdot0+0\cdot0}{2}=0. \end{aligned} \] \[ (s_{I,I},s_{I,\text{love}},s_{I,\text{pad}})=(2,1,0). \]
\[ \operatorname{softmax}(2,1,0) =\frac{(e^2,e^1,1)}{e^2+e^1+1} \approx(0.67,0.24,0.09). \] \[ \begin{aligned} \mathbf z_I^{\text{padded}} &\approx0.67\mathbf v_I+0.24\mathbf v_{\text{love}}+0.09\mathbf 0\\ &=0.67\mathbf v_I+0.24\mathbf v_{\text{love}}. \end{aligned} \]

The zero Value adds nothing, but \(e^0=1\) enlarges the softmax denominator. The weights on I and love shrink.

3 · Mask the padding score

\[ (2,1,0)+(0,0,-\infty)=(2,1,-\infty). \] \[ \operatorname{softmax}(2,1,-\infty) =\frac{(e^2,e^1,0)}{e^2+e^1} \approx(0.73,0.27,0). \] \[ \mathbf z_I^{\text{masked}}=\mathbf z_I^{\text{original}}. \]

The padding entry contributes zero to both the denominator and the weighted sum. Figure 7 compares this same row in all three cases.

One row, three cases

Attention weights in the I rowIlove<pad>
Original: I love0.730.27—
Padding, no mask0.670.240.09
Padding + mask0.730.270.00
Figure 7. The padding mask restores the original weights on I and love. All three rows here describe the same position, I, under different conditions. Displayed weights are rounded.

Apply the same rule to every row: add \(-\infty\) in the <pad> column and 0 elsewhere.

Optional: verify the full matrices

Use the vectors from Part 1, Section 1.2, with zero vectors at the padding position:

PositionQueryKey
I\((2,1,0,0)\)\((2,0,1,0)\)
love\((1,2,0,1)\)\((0,2,0,1)\)
<pad>\((0,0,0,0)\)\((0,0,0,0)\)

Both axes follow I, love, <pad>. Each row now represents a different position.

\[ \mathbf S_{\text{enc-self}}=\frac{\mathbf Q\mathbf K^\top}{2} =\begin{pmatrix}2&1&0\\1&2.5&0\\0&0&0\end{pmatrix},\qquad \mathbf M_{\text{pad}}=\begin{pmatrix}0&0&-\infty\\0&0&-\infty\\0&0&-\infty\end{pmatrix}. \] \[ \mathbf S_{\text{enc-self}}+\mathbf M_{\text{pad}} =\begin{pmatrix}2&1&-\infty\\1&2.5&-\infty\\0&0&-\infty\end{pmatrix}. \] \[ \mathbf A_{\text{enc-self}} =\operatorname{softmax}(\mathbf S_{\text{enc-self}}+\mathbf M_{\text{pad}}) \approx\begin{pmatrix}0.73&0.27&0\\0.18&0.82&0\\0.50&0.50&0\end{pmatrix}. \]

Softmax acts separately on each row. Mask entries of 0 preserve scores; \(-\infty\) makes the corresponding attention weights zero.

Key takeawayA padding score of 0 adds \(e^0=1\) to the softmax denominator, even when its Value is zero. Mask the score with \(-\infty\), so \(e^{-\infty}=0\).

Try it: Repeat the comparison for the love row: \(\operatorname{softmax}(1,2.5)\), \(\operatorname{softmax}(1,2.5,0)\), and \(\operatorname{softmax}(1,2.5,-\infty)\). Which two give the same weights on the real tokens?

8.6Choose the mask for each attention sublayer

Decoder inputs can also need padding. For example, <start> J’aime may become <start> J’aime <pad> when batched with longer decoder inputs. Masking its padding column follows the same rule as in Section 8.5; this is a target padding mask.

Source and target identify which sequence contains the padding. The masking operation is the same.

Attention sublayerSequence being readMask
Encoder self-attentionSourceSource padding
Decoder self-attentionTargetTarget padding + causal
Cross-attentionSourceSource padding
Figure 8. Apply the listed masks in every corresponding attention sublayer.

Cross-attention gets its Queries from the decoder, but reads Keys and Values from source memory \(\mathbf C\), so it needs the source padding mask. The complete source is available during inference; no causal restriction is needed on its positions.

Decoder self-attention combines its two restrictions:

\[ \mathbf M=\mathbf M_{\text{causal}}+\mathbf M_{\text{target-pad}}. \] \[ M_{ij}=\begin{cases} 0 & \text{if both masks allow the pair }(i,j),\\ -\infty & \text{if either mask forbids it}. \end{cases} \]

Add the combined mask to the scaled scores, then apply softmax to each row:

\[ \mathbf A=\operatorname{softmax}(\mathbf S+\mathbf M). \]

NextUse the masks during training

We have seen which connections the masks block and how that changes attention. Part 9 starts with a known translation, pairs each decoder input position with the token it should predict, and explains why causal masking is needed for those predictions. It then shows how the predictions are evaluated and how training updates the model’s parameters.

Part 10 returns to inference, including token selection and KV caching.