Sub topic 2
Pretrained transformers as reusable language understanding
This chapter covers the part of a transformer that zero-shot classification reuses: the knowledge it learns during pretraining. It assumes you know basic Python, have a rough idea of supervised text classification, and can install packages such as torch and transformers. You don't need to know the attention math. We treat the transformer as a component and look at what it learns, how that knowledge is packaged, and how it gets reused for tasks it never saw.
What pretraining produces
A transformer is a neural network that turns a sequence of tokens into a sequence of vectors. A token is a piece of text, usually a word or part of a word. Training one from scratch on a classification task needs a lot of labeled data. Pretraining avoids this by teaching the model language first, using text that has no labels.
Pretraining uses self-supervised objectives. The labels come from the text itself:
- Masked language modeling. Some tokens are hidden, and the model predicts them from the words on both sides. BERT and RoBERTa use this.
- Next-token prediction. The model predicts each token from the tokens before it. GPT-style models use this.
- Denoising. The input is corrupted by masking, deleting or shuffling spans, and the model reconstructs the original. BART uses this.
To do well at these objectives, a model must pick up syntax, word meaning, some world knowledge and patterns of reasoning. The result is a set of weights, a few hundred million numbers for a model like BART-large, that you can download and reuse. Nobody labeled anything for this stage, so it can run on billions of words.
Three architecture families
Transformers come in three shapes. Which one a model has affects how you use it for classification.
| Family | Reads context | Typical pretraining | Examples | Typical classification use |
|---|---|---|---|---|
| Encoder | Both directions at once | Masked language modeling | BERT, RoBERTa, DeBERTa | Add a classification head, or extract embeddings |
| Decoder | Left to right only | Next-token prediction | GPT models, Llama | Prompt it, or add a head on the last token |
| Encoder-decoder | Encoder reads the input, decoder generates | Denoising | BART, T5 | Classification head, or text-to-text generation |
The model used throughout this tutorial, facebook/bart-large-mnli, is an encoder-decoder. Its classification head reads a summary of the decoder's output after the full input passes through the encoder. Encoders are the simplest to reason about, and the next section uses one.
Contextual representations
Older word embeddings such as word2vec gave each word one fixed vector. A transformer instead gives each token a vector that depends on the whole input. These are called contextual representations. The word "bank" gets different vectors in "river bank" and "bank account".
The following script shows this with BERT. It extracts the vector for "bank" from three sentences and compares them with cosine similarity, a measure of how closely two vectors point in the same direction.
import torch
from transformers import AutoTokenizer, AutoModel
name = "bert-base-uncased"
tokenizer = AutoTokenizer.from_pretrained(name)
model = AutoModel.from_pretrained(name)
model.eval()
def word_vector(sentence, word):
inputs = tokenizer(sentence, return_tensors="pt")
tokens = tokenizer.convert_ids_to_tokens(inputs["input_ids"][0])
index = tokens.index(word)
with torch.no_grad():
hidden = model(**inputs).last_hidden_state[0]
return hidden[index]
river = word_vector("We sat on the bank of the river.", "bank")
money_a = word_vector("She deposited the check at the bank.", "bank")
money_b = word_vector("He opened an account at the bank.", "bank")
cos = torch.nn.functional.cosine_similarity
print("river vs money :", round(cos(river, money_a, dim=0).item(), 3))
print("money vs money :", round(cos(money_a, money_b, dim=0).item(), 3))The two financial uses should score noticeably higher with each other than either does with the river sense. The exact numbers depend on the model version, so don't hard-code them in tests.
Two details in this code matter in practice:
AutoModelloads the base network without a task head. Its output,last_hidden_state, has shape(batch, tokens, hidden_size).- The tokenizer adds special tokens such as
[CLS]and[SEP], and splits rare words into pieces. The lookuptokens.index(word)works here because "bank" is a single token. For a word that splits into several pieces you would need to pool over them.
Reusing the model: heads and fine-tuning
The pretrained network is a general-purpose body. To use it for a specific task you attach a small head, usually a linear layer, that maps the body's vectors to task outputs. For classification, the head produces one score (a logit) per class. You then have two choices:
- Feature extraction. Freeze the body and train only the head. This is cheap but usually less accurate.
- Fine-tuning. Train the head and the body together on labeled examples for your task. The body's weights shift slightly to suit the task. This is the standard approach and gives the best supervised accuracy.
Either way you need labeled data for the task, which is the cost the previous chapter described. Zero-shot classification avoids that cost. It fine-tunes once on a different, general task, here natural language inference (NLI). It then reuses that single model for many label sets without further training.
The right-hand path is why the approach works. The NLI model learned a skill, judging whether one statement follows from another, that does not depend on any particular set of categories. The next chapters show how to phrase classification as that skill.
Inspecting a pretrained checkpoint
A checkpoint is a saved set of weights plus a configuration file. The configuration records what kind of head the model has and what its outputs mean. You can read it without downloading the weights:
from transformers import AutoConfig
config = AutoConfig.from_pretrained("facebook/bart-large-mnli")
print("architecture:", config.architectures)
print("hidden size :", config.d_model)
print("encoder layers:", config.encoder_layers)
print("decoder layers:", config.decoder_layers)
print("output labels:", config.id2label)The output shows a BartForSequenceClassification model, and id2label maps three output positions to contradiction, neutral and entailment. These three labels are the NLI task. The head has only three outputs, so the model has no output slot for "billing" or "sales". Zero-shot classification works around this by asking the NLI question once per candidate label.
What transfers, and what does not
Pretrained models carry reusable knowledge, but the transfer has limits. Knowing them early prevents confusion in later chapters.
What transfers well
- Grammar, word senses and common paraphrases.
- Broad world knowledge from the pretraining text, such as the fact that a double charge belongs with payments.
- The ability to compare two pieces of text, which is what the NLI fine-tuning step builds on.
What transfers poorly
- Domain vocabulary. Medical, legal or internal product jargon may be rare in the pretraining text. The tokenizer splits such terms into many fragments, and the model's grasp of them is weaker.
- Recency. The model knows nothing after its training data was collected.
- Language coverage. An English-only checkpoint handles other languages badly. Multilingual checkpoints exist, but they usually trade some English accuracy for breadth.
- Social bias. The model absorbs the associations in its training text, including stereotypes. A zero-shot classifier inherits them.
Practical constraints
- Input length. Each model has a maximum sequence length, 512 tokens for BERT and 1024 for BART. Longer text is cut off or must be split. A label-relevant sentence at the end of a long document can be lost.
- Size and speed.
bart-large-mnlihas roughly 400 million parameters. Loading it takes a few gigabytes of memory, and it runs much faster on a GPU. Smaller distilled models cost less but are less accurate. - Head initialization. If you load a body with
AutoModelForSequenceClassificationand the checkpoint has no trained head, the library prints a warning that some weights are newly initialized. The head's outputs are then random until you train it. A checkpoint that was already fine-tuned on NLI doesn't produce this warning for its head.
Why this matters for the rest of the tutorial
Three ideas from this chapter carry forward:
- Pretraining gives a reusable body, and a head decides what the model outputs.
- Zero-shot classification gets its flexibility from a task, NLI, whose output space (entailment, neutral, contradiction) is independent of your categories.
- Quality is bounded by what the pretrained model knows. Domain jargon, long inputs and bias in the pretraining text all affect the final classifier.
The next chapters cover the NLI task in detail and show how a classification problem becomes an entailment question.
Exercise
A teammate says: "We can't use a pretrained transformer for our new ticket-routing task, because it was never trained on our categories." Using the ideas from this chapter, explain what is wrong with this claim. Name two different ways to reuse the pretrained model, and say which one needs no labeled data for your categories.
Show answer
Pretraining teaches general language knowledge, not specific categories, so the model never needs to have seen your categories. You can reuse it by (1) adding a head and fine-tuning on labeled ticket data, which needs labeled examples of your categories, or (2) using a checkpoint fine-tuned on NLI and posing each category as an entailment question, which is zero-shot classification and needs no labeled data for your categories. The second works because the NLI task's outputs (entailment, neutral, contradiction) don't depend on any particular label set.
Exercise
In the BERT script, tokens.index("bank") is used to find the token position. Why could this fail for the word "unbanked", and what would you need to do to get one vector for that word?
Show answer
A subword tokenizer may split "unbanked" into several pieces (for example "un", "##bank", "##ed"), so the string "unbanked" is not a single entry in the token list and .index would raise a ValueError. To get one vector for the word you would find the positions of all its pieces, for example by using the tokenizer's offset mapping or word IDs, and pool their hidden vectors, typically by averaging.
Exercise
You load facebook/bart-large-mnli and read config.id2label. It has three entries. Why can't the model directly output "billing" or "sales" as a class?
Show answer
The head was trained for NLI, so it has exactly three output positions: contradiction, neutral and entailment. It has no positions for your categories. Zero-shot classification therefore runs the model once per candidate label, with the label placed in a hypothesis, and reads the entailment score for each run.