Contents

Foundation Model Engineering

Manuscript updated (UTC) · Chapter source on GitHub · Cite this chapter (RIS)

On this page

4.4 Hybrid & Prefix LM

A translation service receives the whole source sentence before it writes the first word of the translation. While reading the source, a word near the end can clarify a word near the beginning. While writing the translation, each decision has to use only what the service has received or written so far. A prefix language model can enforce both rules in one stack of Transformer layers. [2]

Which positions can read one another?

Suppose the input has three source positions, P1–P3, followed by four translation positions, T1–T4. P1 can read P3. P1 must never read T1, even during training when the whole translation is present in memory. If it could, an answer could leak into a source representation that later layers read.

Let ii be the query position, jj the key position, and LpL_p the prefix length. Positions start at 1. The mask permits a pair when j≤Lpj \le L_p or j≤ij \le i. Every row can read the entire prefix. A target row can also read its own token and earlier target tokens. A row describes the input used to predict the next token. [2]

Rows are query positions. Columns are key positions.
Query P1P2P3T1T2T3T4
P1 1110000
P2 1110000
P3 1110000
T1 1111000
T2 1111100
T3 1111110
T4 1111111

1 = visible · 0 = blocked. The heavier rules separate prefix (P) from target (T).

HTML table calculated for seven positions using the mask rule in Figure 3 of Raffel et al. [2]

Read the row for T1. Its four visible values come from P1, P2, P3 and T1 itself. That row predicts T2. To predict T1, read the output at P3, the last source position in this example. The two rows show why the diagonal belongs in the mask and why the labels shift one place.

How GLM uses the boundary

In the original GLM blank-infilling objective, the prefix contains a damaged passage with a marker at each missing span. The target contains the missing spans in a sampled order. For example, the source can use the words on both sides of a blank, but the only missing words a target position can read are the ones supplied so far. GLM records the location of the blank and the position within its reconstruction separately. Its span markers and training targets add structure beyond the simple translation example. [1]

Parallel sublayers in PaLM

PaLM computes attention and feed-forward branches in parallel inside each block. That choice changes how a layer runs. The attention mask separately determines which token positions can exchange information. [4]

Test for a leak with PyTorch

In PyTorch’s scaled dot-product attention (SDPA), a Boolean True makes a key visible. Passing a floating-point matrix of ones and zeros instead adds those numbers to the attention scores. A zero in that matrix leaves a forbidden key eligible for softmax. [3]

Run python prefix_mask.py in an environment with PyTorch installed. The CPU example uses one unpadded sequence, one head, and one scalar per position. Padding and packed examples need additional masks for valid keys and example boundaries.

Download the PyTorch example (prefix_mask.py)

"""Change one future value and check whether it reaches an earlier SDPA row.

Foundation Model Engineering, section 4.4
English: https://sungeuns.github.io/foundation-model-engineering/chapter-4/hybrid-prefix-lm/#prefix-mask-test
Korean: https://sungeuns.github.io/foundation-model-engineering/ko/chapter-4/hybrid-prefix-lm/#prefix-mask-test
"""

import torch
from torch.nn.functional import scaled_dot_product_attention

prefix_len, length = 3, 7
position = torch.arange(length)
query_pos, key_pos = position[:, None], position[None, :]
allowed = (key_pos < prefix_len) | (key_pos <= query_pos)

# [batch, heads, positions, features]. Zero logits give visible keys equal weight.
q = k = torch.zeros(1, 1, length, 1)
values = torch.arange(1, length + 1, dtype=q.dtype).view_as(q)


def attend(v, mask):
    return scaled_dot_product_attention(q, k, v, attn_mask=mask, dropout_p=0.0).flatten()


# Increase T2 from 5 to 105. Can T1 see the change?
t1, t2 = 3, 4
changed = values.clone()
changed[0, 0, t2, 0] += 100
output = attend(values, allowed)
new_output = attend(changed, allowed)
torch.testing.assert_close(output, torch.tensor([2., 2., 2., 2.5, 3., 3.5, 4.]))
torch.testing.assert_close(new_output[:t2], output[:t2])
assert new_output[t2] > output[t2]
print(f"Boolean mask, T1: {output[t1]:.1f} -> {new_output[t1]:.1f}")

# SDPA adds float masks to the logits. Adding 0 leaves future keys in the softmax.
float_mask = allowed.float()
before = attend(values, float_mask)[t1]
after = attend(changed, float_mask)[t1]
torch.testing.assert_close(
    torch.stack([before, after]), torch.tensor([3.257, 10.465]), atol=0.001, rtol=0
)
print(f"Float 0/1 mask, T1: {before:.3f} -> {after:.3f}")

With every query and key set to zero, visible keys receive equal weight. T1 returns the mean of 1, 2, 3 and 4, which is 2.5. Raising T2 from 5 to 105 leaves T1 at 2.5 with the Boolean mask. Look at the second output line. With the float 0/1 mask, T1 jumps from 3.257 to 10.465 (rounded). The model can read a token that it is supposed to predict.

The same boundary matters when reusing a prompt cache. If a new source token becomes part of the bidirectional prefix, earlier source positions can read it. Recompute the affected prefix representations before treating them as final. Adding a target token preserves the earlier rows’ visibility.

Quizzes

Quiz 1: Why does a strictly causal mask miss information at P1? P1 could use P2 and P3 to interpret the source, but a strictly causal row at P1 exposes only P1.

Quiz 2: Why can the T1 row read T1 without learning its answer in advance? Its label is T2. The T1 row must block T2 and later target positions.

Quiz 3: What does the value at T1 become if all seven keys are visible in the example? With zero attention logits the weights would be uniform across all seven positions. Their mean is 4. With the prefix mask only the first four are visible and the mean is 2.5.

Quiz 4: When would adding a token force you to revisit cached prefix states? Extending the bidirectional source opens a new key to earlier source positions. Appending a target token leaves those earlier rows unchanged.

Quiz 5: How does GLM know which blank to fill when it generates spans out of text order? One position coordinate identifies the original blank and a second tracks progress within the span being generated.

References

  1. Du, Z., et al. (2022). GLM: General Language Model Pretraining with Autoregressive Blank Infilling, §2.1 and Figure 2.
  2. Raffel, C., et al. (2020). Exploring the Limits of Transfer Learning with a Unified Text-to-Text Transformer, §3.2.1 and Figures 3–4.
  3. PyTorch. Scaled dot product attention, PyTorch 2.15.
  4. Chowdhery, A., et al. (2023). PaLM: Scaling Language Modeling with Pathways, §2.