Sub topic 4
Pretrained encoders as the backbone
This chapter covers the part of an extractive question answering model that does most of the work: the pretrained transformer encoder. It assumes you can read PyTorch code, know that a pretrained language model is a network trained on large amounts of unlabeled text, and know that a tokenizer turns text into subword token IDs. Later chapters cover how the question and context are packed into one input and how the span head works. Here the focus is what the encoder provides and how to choose one.
What the backbone does
A question answering model has two parts:
- An encoder, which turns each input token into a vector that reflects the whole input.
- A span head, a small linear layer that turns each vector into a start score and an end score.
The encoder holds almost all the parameters. For DistilBERT, the span head has 1,538 parameters (768 × 2 weights plus 2 biases), against roughly 66 million in the encoder. Nearly all of the model's language knowledge lives in the encoder, so a good encoder matters more than a clever head.
Why an encoder, and why pretrained
Bidirectional context
An encoder uses bidirectional self-attention. Every token can attend to every other token in the input, left and right. This matters for question answering. Whether the word "seven" starts the answer depends on the question tokens before it and on the words that follow it. A decoder-only model with causal attention sees only earlier tokens when it builds each vector, so it is a poor fit for scoring every position independently.
What pretraining gives you
Encoders such as BERT are pretrained with masked language modeling. About 15% of the input tokens are hidden, and the model learns to predict them from the surrounding words. To do that well, the model must learn syntax, word meaning, and how entities and phrases relate to each other. Question answering needs all of these. The fine-tuning step then teaches the network a narrow task: use that knowledge to point at the answer.
Training from scratch on SQuAD alone (about 100,000 training questions) would give much weaker results. The pretrained encoder has already seen billions of words. Fine-tuning only has to adapt it.
Looking at the encoder output
The base encoder takes token IDs and returns one vector per token. The size of those vectors is the hidden size, 768 for most "base" models.
import torch
from transformers import AutoTokenizer, AutoModel
name = "distilbert-base-cased"
tokenizer = AutoTokenizer.from_pretrained(name)
encoder = AutoModel.from_pretrained(name)
encoder.eval()
question = "What does the Amazon basin cover?"
context = "Its drainage basin covers about seven million square kilometres."
inputs = tokenizer(question, context, return_tensors="pt")
with torch.no_grad():
output = encoder(**inputs)
print(inputs["input_ids"].shape) # (1, n) where n is the token count
print(output.last_hidden_state.shape) # (1, n, 768)
print(encoder.config.hidden_size, encoder.config.n_layers) # 768 6The shape (1, n, 768) means one sequence, n tokens, and 768 numbers per token. The vector for "seven" is not a fixed word embedding. It depends on the question and the sentence around it. The same word in a different context gets a different vector. This is why the head can be so small: a single linear layer is enough once the encoder has encoded the answer-relevant information into each vector.
Attaching the span head
AutoModelForQuestionAnswering wraps an encoder and adds the head. The next snippet uses a checkpoint already fine-tuned on SQuAD and rebuilds its logits by hand to show that the head is only a linear layer on top of the hidden states.
import torch
from transformers import AutoTokenizer, AutoModelForQuestionAnswering
name = "distilbert-base-cased-distilled-squad"
tokenizer = AutoTokenizer.from_pretrained(name)
qa_model = AutoModelForQuestionAnswering.from_pretrained(name)
qa_model.eval()
question = "What does the Amazon basin cover?"
context = "Its drainage basin covers about seven million square kilometres."
inputs = tokenizer(question, context, return_tensors="pt")
with torch.no_grad():
official = qa_model(**inputs)
# Rebuild the same logits manually: encoder, then the linear head.
hidden = qa_model.base_model(**inputs).last_hidden_state # (1, n, 768)
logits = qa_model.qa_outputs(hidden) # (1, n, 2)
start_logits, end_logits = logits[..., 0], logits[..., 1] # each (1, n)
print(qa_model.qa_outputs) # Linear(in_features=768, out_features=2, bias=True)
print(torch.allclose(start_logits, official.start_logits, atol=1e-5)) # True
print(torch.allclose(end_logits, official.end_logits, atol=1e-5)) # TrueThe two output channels of the head are the start score and the end score. Every token gets both, which is why the output has shape (1, n, 2) before it is split.
The attribute name qa_outputs is the same for BERT, DistilBERT, and RoBERTa, but the encoder attribute differs (bert, distilbert, roberta). base_model works for all of them.
Choosing an encoder
Most encoder models on the Hugging Face Hub can be fine-tuned for extractive QA. The common choices differ in size, speed, and tokenizer.
| Model | Layers | Parameters | Tokenizer | Notes |
|---|---|---|---|---|
| `distilbert-base-cased` | 6 | about 66M | WordPiece, cased | Fast and small. A good default for learning and prototypes. |
| `bert-base-cased` | 12 | about 110M | WordPiece, cased | The classic reference model. Uses segment IDs (`token_type_ids`). |
| `roberta-base` | 12 | about 125M | Byte-level BPE | Trained longer on more data. Usually scores higher than BERT on SQuAD. |
All three accept at most 512 positions. Larger models in each family (the "large" variants with 24 layers) score higher and cost roughly three times as much compute.
Use these criteria:
- Latency and memory. DistilBERT keeps most of BERT's accuracy at about 60% of the parameters and runs faster, because it was trained to imitate a larger teacher (distillation).
- Accuracy. RoBERTa and larger models give higher exact match and F1 when you can afford them.
- Language and casing. Pick a model pretrained on your language. A cased model keeps capitalization, which helps for names and acronyms. An uncased model lowercases text and may lose that signal.
- Input length. If your contexts are routinely much longer than 512 tokens, consider an encoder built for long inputs, or plan for the windowing described in the chapter on long contexts.
Common errors
- Loading a base checkpoint and expecting answers.
AutoModelForQuestionAnswering.from_pretrained("distilbert-base-cased")prints a warning thatqa_outputsweights are newly initialized. The encoder is pretrained, but the head is random, so the outputs are meaningless until you fine-tune. A checkpoint with "squad" in its name already includes a trained head. - Exceeding 512 tokens. The encoder has a fixed table of position embeddings. A longer input raises an indexing error, or, if you truncate with
truncation=True, may cut off the part of the context that holds the answer. Usetruncation="only_second"so the question is never cut, and use a stride for long contexts. - Passing
token_type_idsto a model that does not use them. DistilBERT and RoBERTa do not take segment IDs. Their tokenizers do not return them, so callmodel(**inputs)with what the tokenizer gave you instead of building the dictionary yourself. - Training mode during inference. A model in training mode applies dropout, so the same input gives different logits on each call. Call
model.eval()and wrap inference intorch.no_grad().
What the encoder cannot do
The encoder can only produce vectors for the tokens it is given. The span head can only pick tokens from that input. Extractive QA therefore has a hard ceiling: if the answer is not in the context window, no encoder can find it. The encoder also does not reason across documents it has not seen. Questions that need facts from two passages, or arithmetic over the text, are weak spots that the limitations chapter returns to.
Exercise
You load AutoModelForQuestionAnswering.from_pretrained("roberta-base") and run it on a question and a context. The code runs without error, but the predicted spans look random. Name the cause and the fix.
Show answer
The roberta-base checkpoint contains only the pretrained encoder. The span head (qa_outputs) is newly initialized with random weights, as the loading warning says. The fix is to fine-tune the model on QA data such as SQuAD, or to load a checkpoint that was already fine-tuned for question answering.
Exercise
A hidden-state tensor from the encoder has shape (1, 120, 768). What is the shape of the output of the span head Linear(768, 2) on it, and what do the last two values mean for one token?
Show answer
The output has shape (1, 120, 2). For each of the 120 tokens, the two values are its start logit and its end logit. Splitting the last dimension gives a start tensor and an end tensor, each of shape (1, 120).
Exercise
Your contexts are product manuals of about 3,000 tokens, and your service must answer in under 100 ms on a CPU. Which factors from this chapter push you toward DistilBERT, and which constraint does it not solve?
Show answer
DistilBERT has fewer layers and parameters, so it uses less memory and runs faster than BERT or RoBERTa, which helps the latency target. It does not solve the input length. It still accepts at most 512 positions, so the 3,000-token manuals must be split into overlapping windows, and each window is a separate forward pass that adds latency.