# Dropout in Transformers

> Where dropout sits in a transformer, the rate BERT used (0.1), and how to tune it, explained for your AI interview.

**In short:** Dropout switches off a random share of values during training, so the model can't rely on any one path. In a transformer it sits on the outputs of the attention and feed-forward steps, and on the embeddings. It is off when the model is used, and its rate is a setting you tune on held-out data.

AI and LLM interview question Q061, Transformer architecture. Intermediate, occasional (our estimate). From Venkat R. Murty's free Interview Kit: https://designervenkat.online/interview/ai/dropout-in-transformers

## Say it in 30 seconds

Dropout switches off a random share of values during training, so the model can't lean on one path too much. In a transformer I'd put it on the outputs of the attention and feed-forward steps, and on the embeddings. It is off when the model is used. In my small fine-tunes it helps against overfitting, and the rate is a setting you tune on held-out data.

## Say it in 2 minutes

Dropout is a simple trick against overfitting, which means a model memorises its training examples and then fails on new ones. During each training step, a random share of values in a layer is set to zero, and the next step draws a fresh set. So the network can't depend on any one path. Srivastava and colleagues introduced it in a paper titled Dropout: A Simple Way to Prevent Neural Networks from Overfitting.

In a transformer, the original paper applies dropout to the output of each sub-layer before it is added back and normalised. It also applies dropout to the sum of the embeddings and positional encodings. BERT's paper says it uses a dropout probability of 0.1 on all layers. For a small fine-tune I start there and check it on held-out data. For a huge pretraining run, the right setting is a team choice, and it depends on the model and the data.

At test time dropout does nothing. PyTorch's docs say that during evaluation the module simply computes an identity function, so values pass through unchanged. During training, the kept values are scaled up so the average stays close to the same. When a model's answers change from one call to the next, the first thing I check is whether it was left in training mode.

## What is dropout, in plain words?

Dropout is a switch for random values. While a model learns, a share of the numbers in one of its layers is set to zero, picked at random. The next step picks a different share. Because no single number is always there, the model can't build its answer on one fragile path.

Think of a claims team at an insurer that cross-trains its analysts. If one person is away, the queue still moves, because nobody holds all the knowledge. Dropout does the same to a network.

A made-up but realistic case: a bank fine-tunes a language model to read card-dispute emails, using 3,000 labelled examples. Without dropout, it learns the exact wording of those emails and misses new phrasings. Dropout is one cheap way to stop that.

- **Dropout:** A random share of values is set to zero during training only.
- **Overfitting:** The model memorises its training examples and fails on new ones.
- **Sub-layer:** One of the two steps in a transformer layer: attention, or the feed-forward network.
- **Embedding:** The list of numbers that stands for one token, such as a word piece.
- **Test time:** When the trained model is used on new input, not while it learns.

## Where does dropout sit in a transformer?

A transformer is a stack of layers. Each layer has two sub-layers: a self-attention step, where each word looks at other words, and a feed-forward step, which refines each word on its own. Dropout sits on the output of those steps and on the embeddings.

*Diagram, Where dropout sits in one transformer layer: One layer of a transformer. Dropout sits on the attention output and on the feed-forward output. The residual add and layer norm are left out to keep the picture small.*
1. The words enter as numbers that carry their position.
2. Dropout then switches off some of the attention output.
3. The result is added back to the layer input, then goes into the feed-forward step.
4. Dropout switches off some of the feed-forward output too.
5. What is left moves on to the next layer.

1. **Sub-layer outputs:** The original paper applies dropout to the output of each sub-layer, before it is added back to the step's input and normalised.
2. **Embeddings:** Dropout also hits the sum of the embeddings and the positional encodings, in both the encoder and the decoder.
3. **Attention and residual:** For the parsing experiments, the authors say they tried only a few dropout settings for both attention and residual parts.

The rate is a setting you choose and test. BERT's paper says it uses a dropout probability of 0.1 on all layers, which is a useful starting point for a fine-tune.

## How does dropout behave in training and at test time?

In PyTorch the layer is called nn.Dropout. Each forward call, which is one pass of a batch through the model, draws new switches. PyTorch's docs say the zeroed elements 'are chosen independently for each forward call'.

During training, PyTorch scales the kept outputs up by a factor of one over the keep rate, so the average stays close to the same.

*Diagram, The same layer, in training and in testing: The same layer in training and in testing. Training switches off a random share of values and scales the rest up. Testing passes every value through unchanged.*
1. The layer's numbers come in.
2. The rest move on to be scaled up.
3. The scaled numbers feed the model output.
4. The same numbers come in when the model is used.
5. Nothing is dropped, so the output is the plain result.

Here is a made-up layer of eight numbers, with dropout at p = 0.1, where p is the share switched off. The script prints one training pass, one test pass and the average over 10,000 training passes.

```python
# One layer of a card-dispute model at a mid-size bank: 8 made-up activations, dropout with p = 0.1 (10% switched off in training).
import random

ACTS = [0.9, -0.4, 1.2, 0.3, -0.7, 0.5, 0.8, -0.1]
P = 0.1

def dropout(values, p, training=True):
    if not training:
        return list(values)  # at test time nothing is switched off
    keep = 1 - p
    # Kept values are scaled up, so the average stays close to the same.
    return [v / keep if random.random() >= p else 0.0 for v in values]

random.seed(42)
print("input :", [round(v, 2) for v in ACTS])
print("train :", [round(v, 2) for v in dropout(ACTS, P)])
print("test  :", [round(v, 2) for v in dropout(ACTS, P, training=False)])

runs = 10000
totals = [0.0] * len(ACTS)
for _ in range(runs):
    for i, v in enumerate(dropout(ACTS, P)):
        totals[i] += v
print("average of 10,000 training passes:", [round(t / runs, 2) for t in totals])
```

Output:

```text
input : [0.9, -0.4, 1.2, 0.3, -0.7, 0.5, 0.8, -0.1]
train : [1.0, 0.0, 1.33, 0.33, -0.78, 0.56, 0.89, 0.0]
test  : [0.9, -0.4, 1.2, 0.3, -0.7, 0.5, 0.8, -0.1]
average of 10,000 training passes: [0.9, -0.4, 1.2, 0.3, -0.7, 0.5, 0.79, -0.1]
```

At test time, dropout does nothing. PyTorch's docs say that 'during evaluation the module simply computes an identity function'. Calling eval() on a model sets evaluation mode, which has an effect on certain modules, and the docs name Dropout among them.

## Why do some large models turn dropout off?

Dropout trades a little fit for less overfitting. Srivastava and colleagues wrote that 'overfitting is a serious problem in such networks', and the fix they proposed is to drop units at random during training.

> "The key idea is to randomly drop units (along with their connections) from the neural network during training." (Srivastava and colleagues, JMLR)
>
> "dropout is very helpful in avoiding over-fitting" (Vaswani and colleagues, ablation in section 6.2)

- **Small fine-tune: Dropout usually helps.** A few thousand labelled examples leave room to memorise. Start near 0.1 and compare validation scores.
- **Huge pretraining: Setting is team-specific.** The right value depends on the model and the data. Hugging Face's Llama config defaults attention dropout to 0.0, a library default.

A worked case, with made-up numbers. The bank's model scores 98% on the 3,000 emails it trained on and 84% on new ones. With dropout at 0.1 in the attention and feed-forward outputs, the new-email score rose to 88% in this run. A rate of 0.3 learned more slowly and scored lower on new emails, so the team kept 0.1 and checked it again each week.

Hugging Face's Llama code defaults attention dropout to 0.0. That is a library default, not proof of what any trained model uses.

### How would you tune dropout for a small fine-tune?

1. **Hold out a test set:** Set aside about 15% of the labelled emails for validation, and do not train on them.
2. **Try a few rates:** Train with 0.0, 0.1 and 0.2 on the same data, and compare the validation scores.
3. **Freeze and watch:** Keep the rate with the best validation score, then check the live answers each week for drift.

> **Tip:** Never pick the rate from training accuracy. That score tends to rise as the model memorises more.

## What does the interviewer want to hear?

**A strong answer covers**

- [ ] What dropout does: a random share of values is switched off during training.
- [ ] Where a transformer puts it: sub-layer outputs and embeddings.
- [ ] Why it helps: it stops the model leaning on one path, which limits overfitting.
- [ ] That it is off at test time, and why a model left in training mode gives changing answers.
- [ ] That the rate depends on the data: small fine-tunes use it, huge pretraining may not.
- [ ] Tuning on held-out data, never on training accuracy.

**Common traps**

- Trap: "Dropout stays on in production for richer answers." Better: It is off at test time. Leaving it on makes the same input give a different answer on each call.
- Trap: "Dropout always fixes overfitting." Better: It helps when the data is small. At huge scale it may be unneeded, so tune it on held-out data.
- Trap: "Put dropout on every weight matrix." Better: Use it where it helps: sub-layer outputs and embeddings are the usual places, and validation decides the rest.

## Can you spot the problem?

**Spot the bug:** Our claims model gives a different risk score each time the same claim is scored. Which line causes it?

A. model.eval()  # dropout off before serving
B. model.train()  # dropout stays on while serving
C. score = model(claim)  # one forward pass per call
D. torch.no_grad()  # skips gradient tracking

**Answer:** B. In training mode, dropout keeps drawing new random switches, so each call changes the scores. Calling eval() before serving turns it off, and the scores repeat.

**Quick check:** A fine-tuned model scores 98% on its 3,000 training emails and 84% on new ones. What is the sound first move?

A. Turn dropout off to train faster
B. Run more passes over the same data so it learns more
C. Hold out validation data and compare dropout rates on it
D. Remove the validation set so training has more data

**Answer:** C. The gap is overfitting. Choose the rate on held-out data, because the training score tends to rise as the model memorises more.

## Can you answer these from memory?

**Flash cards**

- **What is dropout?** A random share of values is set to zero during training only.
- **Where does a transformer use it?** On sub-layer outputs and the embeddings. The paper tried a few attention dropout settings.
- **Is dropout on at test time?** No. In evaluation the module passes values through unchanged.
- **Why does it help?** It stops the model leaning on one path, which limits overfitting.
- **Why are kept values scaled up?** So the average value stays close to the same during training.
- **Is it always used?** No. It is a setting you tune, and Hugging Face's Llama config defaults attention dropout to 0.0.

## Likely follow-up questions

- Q053 What do residual connections do? https://designervenkat.online/interview/ai/what-do-residual-connections-do
- Q054 What does the feed-forward block do? https://designervenkat.online/interview/ai/what-does-the-feed-forward-block-do
- Q062 How does BERT differ from GPT? https://designervenkat.online/interview/ai/how-does-bert-differ-from-gpt
- Q063 Masked vs causal language modelling? https://designervenkat.online/interview/ai/masked-vs-causal-language-modelling
- Q073 Walk through one decoder block's forward pass. https://designervenkat.online/interview/ai/walk-through-one-decoder-block-forward-pass
- Q414 L1, L2 and dropout regularisation? https://designervenkat.online/interview/ai/l1-l2-and-dropout-regularisation
