# What Is Causal (Masked) Attention?

> How causal attention hides later words from a model, why GPT-style models need it, and how to test it, explained simply for your AI interview.

**In short:** Causal (masked) attention lets each word look only at itself and the words before it, never at later ones. That hides the future during training and while the model writes, which is how GPT-style models predict the next word.

AI and LLM interview question Q050, Transformer architecture. Intermediate, common (our estimate). From Venkat R. Murty's free Interview Kit: https://designervenkat.online/interview/ai/what-is-causal-masked-attention

## Say it in 30 seconds

Causal attention, also called masked attention, lets each word look only at itself and the words before it. The model scores every pair of words, then sets the scores for later words to minus infinity. After softmax those words get zero weight, so the future stays hidden. That's how a model like GPT learns to predict the next word without peeking ahead, and why it writes one token at a time.

## Say it in 2 minutes

A language model writes one word at a time. When it picks word three, it must rely only on words one and two, because word three is what it is trying to guess. Causal attention, also called masked attention, is the rule that enforces this. Each word may look at itself and the words before it, and nothing after it.

The rule lives in the attention step. The model scores every word against every other word, then a mask sets the scores for later words to minus infinity. After softmax, those words get a weight of zero. The 2017 Transformer paper describes the same idea for its decoder, the half that writes: it stops positions attending to subsequent positions.

This is why GPT-style models can train on a whole sentence at once. Every position predicts its own next word in one pass, and the mask stops any position from peeking at the answer. A support bot drafting a refund reply follows the same rule, so its choice of 'approved' depends only on the words before it.

The trade-off is that each word sees only the left side. Bidirectional models such as BERT read the words on both sides of each word. Causal models suit writing, because they never need words that have not been written yet. I would say that plainly in an interview and name the trade-off.

## What is causal (masked) attention, in plain words?

A language model reads text as tokens, small pieces of words. Attention is how each token decides how much to use every other token when it builds its meaning. Causal attention adds one rule: a token can look only at itself and the tokens before it.

Picture a claims adjuster writing a case note line by line. She can point back to what is already in the file, but she must not quote a page that has not been written yet. Causal attention gives the model that same rule.

Real case: an insurer's assistant drafts a reply to a policyholder, one word at a time. When it writes 'approved', it may use 'Your claim is' before that word, but not the sentence that comes after, because that text does not exist yet.

- **Token:** A small piece of text, often part of a word, that the model reads and writes.
- **Attention:** The step where each token weighs how much to use every other token.
- **Mask:** A rule that blocks some pairs of tokens, here every pair where the other token comes later.
- **Softmax:** A step that turns scores into weights that add up to 1.
- **Causal model:** A model that predicts the next token from the tokens before it, like GPT-2.

## How does the mask stop a model looking ahead?

Attention starts with a score for every pair of tokens, so a four-token reply makes a four by four table. The causal mask covers the upper-right half of that table, the pairs where the other token comes later.

*Diagram, How a causal mask hides the future: Each word's scores go through the mask, then softmax, which turns the visible scores into weights that add up to 1. Masked words get weight 0, so the next word can only draw on words that already exist.*
1. Each pair's score moves on to the mask.
2. Masked scores go on to softmax, where later words count as 0.
3. The visible weights pick the next word.

1. **Score every pair:** Each token gets a score against every token, including itself.
2. **Hide the later ones:** Scores for later tokens are set to minus infinity, so they can't count.
3. **Turn scores into weights:** Softmax makes each row's visible weights add up to 1.

Here is a made-up four-token reply from a bank's drafting assistant, with the mask applied. Read each row: 'today' spreads its weight across all four words, because it comes last. 'Refund' is 1.00, because it can see only itself.

```python
# A made-up score table for four tokens of a bank's drafted reply.
import math

tokens = ["Refund", "is", "approved", "today"]
scores = [
    [1.2, 0.3, 0.1, 0.4],
    [0.5, 1.0, 0.2, 0.3],
    [0.1, 0.6, 1.4, 0.2],
    [0.3, 0.2, 0.9, 1.1],
]

def causal_softmax(row, i):
    # Future positions get -infinity before the softmax, so their weight becomes 0.
    masked = [s if j <= i else float("-inf") for j, s in enumerate(row)]
    exps = [math.exp(s) for s in masked]
    total = sum(exps)
    return [e / total for e in exps]

print("query    " + "".join(f"{t:>10}" for t in tokens))
for i, row in enumerate(scores):
    weights = causal_softmax(row, i)
    print(f"{tokens[i]:<9}" + "".join(f"{w:>10.2f}" for w in weights))
```

Output:

```text
query        Refund        is  approved     today
Refund         1.00      0.00      0.00      0.00
is             0.38      0.62      0.00      0.00
approved       0.16      0.26      0.58      0.00
today          0.17      0.15      0.31      0.37
```

## Why do GPT-style models use it?

GPT is a family of models that write text one word at a time. They come from the 2017 Transformer design, which has two halves: the decoder, which writes, and the encoder, which reads a whole text at once.

Training needs the model to predict every position in a sentence. With the mask, one pass over the sentence gives a prediction at each position, and none of them can read the word it is meant to predict. Writing works the same way: one word at a time, from the words so far.

> "We also modify the self-attention sub-layer in the decoder stack to prevent positions from attending to subsequent positions." (The Transformer paper, 2017)
>
> "Causal language modeling predicts the next token in a sequence of tokens, and the model can only attend to tokens on the left." (Hugging Face, on causal language modelling)
>
> "If set to true, the attention masking is a lower triangular matrix when the mask is a square matrix." (PyTorch, the is_causal option)

- **Causal (GPT-style): Reads left to right.** Each word sees only the words before it. Used for writing the next word.
- **Bidirectional: Reads the whole text.** Each word sees words on both sides. Used by models such as BERT.

## What are the trade-offs?

- **Training covers every position:** One pass trains every position at once, instead of one word after another.
- **Each word sees one side only:** A causal model cannot use words after a word. A bidirectional model such as BERT can.
- **The mask must be right:** A wrong mask can let answers leak into training, so test scores can look better than the model really is.

> **Tip:** Asked what can go wrong? Say that a leaky mask makes the model look strong in tests. Then say how you'd catch it: with the peek test below.

### How would you test that a model cannot peek ahead?

Say a claims team's contract summariser looks too good in staging. You suspect the mask is leaking. Here is a simple check you can describe in an interview.

1. **Change a later word:** Take a finished prompt and swap its last word for a different one.
2. **Compare earlier scores:** Scores for earlier positions must stay the same. If they change, the mask leaks.
3. **Check the serving code:** A misconfigured serving stack might skip the mask, so test the real stack too.

## What does the interviewer want to hear?

**A strong answer covers**

- [ ] A plain definition: each word sees only itself and the words before it.
- [ ] The mechanism: scores for later words set to minus infinity before softmax.
- [ ] The why: next-word training, and writing one word at a time.
- [ ] Where it's used: GPT-2 and similar text-writing models.
- [ ] The trade-off: a one-sided view against a bidirectional reader.
- [ ] How you'd test it: change a later word and check earlier scores stay the same.

**Common traps**

- Trap: "The model just skips the future words." Better: It still computes them. The mask sets their weight to zero before softmax.
- Trap: "The mask filters the final text." Better: It acts on the attention scores, before softmax, which is where the weights come from.
- Trap: "Causal attention is only for chatbots." Better: It applies to any model that writes one token at a time, chat or otherwise.

## Can you spot the leak?

**Spot the leak:** Which line hides the later words from each word?

A. masked = [s if j >= i else float("-inf") for j, s in enumerate(row)]
B. masked = row  # the scores go to softmax unchanged
C. masked = [s if j <= i else float("-inf") for j, s in enumerate(row)]
D. masked = [s if j <= i + 1 else float("-inf") for j, s in enumerate(row)]

**Answer:** C. j <= i keeps each word and the words before it, and hides the rest. The other three leak: j >= i keeps the later words, leaving the row unchanged shows them all, and i + 1 lets one future word through. That off-by-one is a real bug to look for in review.

**Quick check:** A bank's drafting assistant writes replies one word at a time. Which mask does it need?

A. A bidirectional mask, so each word reads the whole reply
B. A causal mask, so each word sees only the words before it
C. No mask, since the model should read everything
D. A longer system prompt

**Answer:** B. Writing one word at a time means the later words don't exist yet, so the causal mask hides them. The other choices let a word see text it has not written, or don't touch attention at all.

## Can you answer these from memory?

**Flash cards**

- **What is causal (masked) attention?** Each word sees only itself and the words before it.
- **How is the future hidden?** Scores for later words are set to minus infinity before softmax, so their weight is 0.
- **Why does a writing model need it?** It writes one word at a time, so later words don't exist yet.
- **Which models use it?** GPT-2 and similar text-writing models.
- **Causal vs bidirectional?** Causal sees only the left. Bidirectional reads both sides at once, as BERT does.
- **What breaks if the mask is wrong?** The model can learn from words it should not see, so real use is worse than the tests showed.

## Likely follow-up questions

- Q043 What is self-attention? https://designervenkat.online/interview/ai/what-is-self-attention
- Q044 What are queries, keys and values? https://designervenkat.online/interview/ai/what-are-queries-keys-and-values
- Q049 Encoder-only vs decoder-only vs encoder-decoder? https://designervenkat.online/interview/ai/encoder-only-vs-decoder-only-vs-encoder-decoder
- Q051 What is cross-attention? https://designervenkat.online/interview/ai/what-is-cross-attention
- Q055 What is the KV cache, and why does it speed up generation? https://designervenkat.online/interview/ai/what-is-the-kv-cache

## Learn it in depth

- [Self-Attention](https://designervenkat.online/learn/machine-learning/self-attention)
