Sub topic 2
Pretrained Transformers as Reusable Language Understanding
Prerequisites: You should know basic Python, understand supervised text classification, and have a general idea of what a pretrained language model is.
A pretrained transformer is a language model that learned patterns from a large text collection before you use it for a specific task. It can recognize relationships between words, sentence structure, and many common meanings. You can reuse this learned knowledge instead of training a new model from the beginning.
What a transformer encoder learns
A transformer processes tokens, which are words or word pieces. Its attention mechanism lets each token consider other tokens in the same input. For example, in “The bank approved the loan,” the word “bank” receives context from “approved” and “loan.” In “The boat reached the river bank,” the surrounding words suggest a different meaning.
A transformer encoder converts the input into numerical vectors called hidden states. A hidden state is a vector that represents a token in its context. The vector for “bank” can differ between the two examples because the surrounding text changes its meaning.
Pretraining usually uses an objective that does not require your task labels. For example, a model may learn to predict a masked word from its surrounding words. This teaches the model useful language patterns. The model does not automatically know your business categories, but its representations can support many later tasks.
Reusing encoder representations
You can use an encoder in several ways:
- Add a task-specific classification layer and fine-tune the model with labeled examples.
- Compare the resulting vectors with other vectors to measure semantic similarity.
- Give the encoder a premise and a hypothesis for a natural language inference task.
- Use a model that has already been fine-tuned for zero-shot classification.
The raw encoder produces representations. A task-specific head or scoring method turns those representations into a decision. This separation is important: AutoModel gives hidden states, while a classification pipeline usually includes a model and the logic needed to interpret its output.
The following example creates one vector for each input sentence by averaging its token vectors. The attention mask prevents padding tokens from affecting the average.
import torch
from transformers import AutoModel, AutoTokenizer
name = "bert-base-uncased"
tokenizer = AutoTokenizer.from_pretrained(name)
model = AutoModel.from_pretrained(name)
texts = [
"The bank approved the loan.",
"The boat reached the river bank.",
]
inputs = tokenizer(
texts,
return_tensors="pt",
padding=True,
truncation=True,
)
with torch.no_grad():
outputs = model(**inputs)
token_vectors = outputs.last_hidden_state
mask = inputs["attention_mask"].unsqueeze(-1)
masked_vectors = token_vectors * mask
sentence_vectors = masked_vectors.sum(dim=1) / mask.sum(dim=1)
print(sentence_vectors.shape)The printed tensor has one row per sentence. Each row is a fixed-length representation. The two rows may be close in some dimensions because both sentences mention a bank, but contextual information helps preserve their different meanings.
Why this supports zero-shot classification
A zero-shot classifier uses a pretrained model that has learned a relationship between text and a natural-language hypothesis. Instead of learning only fixed category IDs, the model can compare a new text with statements such as “This message is about billing.”
This works because the model has reusable language knowledge and has been trained for a task that measures relationships between sentences. The candidate labels still matter. A vague or unfamiliar label may produce poor results even when the input is clear.
| Component | Main role | Example |
|---|---|---|
| Encoder | Builds contextual representations | `bert-base-uncased` |
| Task head | Converts representations into task scores | Classification layer |
| NLI model | Scores whether a hypothesis follows from text | `facebook/bart-large-mnli` |
| Candidate label | Supplies the category wording | `billing` |
Common errors
- Treating token vectors as fixed word definitions. Their values depend on context.
- Assuming every pretrained model supports every downstream task.
- Comparing vectors from different models as if they were in the same vector space.
- Ignoring tokenization. A single visible word may become several tokens.
- Using a general encoder when a model fine-tuned for NLI or embeddings would fit the task better.
Exercise
Why can the same word receive different hidden-state vectors in two sentences?
Show answer
Self-attention uses surrounding tokens as context, so the encoder can represent different meanings of the same word.