Lesson 9 of 97 min
Encoders and decoders
A decoder's tokens see only the tokens before them so it can write, while an encoder's tokens see the whole text so it reads, and for a label on many texts a small trained encoder beats a chat model asked.
After this lesson you can choose between a BERT-style and a GPT-style model for classification, extraction or generation.
Loading the video…
Refreshers
An idea from an earlier lesson shows up here when the video leans on it.
In real code
What the video left out, as you will meet it in your own code.
Train the label layer
The video named the training and skipped it. Here it is: Amazon Polarity's reviews, 2,000 to learn from and 1,000 to score on, then two passes over the 2,000, sixteen at a time. The label layer starts from random numbers, so your count may differ by a few from the video's 943. Ettin's encoder
import torch
from datasets import load_dataset
from transformers import AutoTokenizer, AutoModelForSequenceClassification
files = {"train": "amazon_polarity/train-00000-of-00004.parquet", "test": "amazon_polarity/test-00000-of-00001.parquet"}
data = load_dataset("fancyzhx/amazon_polarity", data_files=files)
train, test = data["train"].shuffle(seed=0).select(range(2000)), data["test"].shuffle(seed=0).select(range(1000))
dev = "mps" if torch.backends.mps.is_available() else "cuda" if torch.cuda.is_available() else "cpu"
tok = AutoTokenizer.from_pretrained("jhu-clsp/ettin-encoder-150m")
batch = lambda rows: tok([f"{t}. {c}" for t, c in zip(rows["title"], rows["content"])], truncation=True, max_length=256, padding=True, return_tensors="pt").to(dev)
print(dev, sum(train["label"]), sum(test["label"]))mps 1031 497
model = AutoModelForSequenceClassification.from_pretrained("jhu-clsp/ettin-encoder-150m", num_labels=2).to(dev).train()
opt = torch.optim.AdamW(model.parameters(), lr=5e-5)
for epoch in range(2):
for rows in train.shuffle(seed=epoch).iter(batch_size=16):
model(**batch(rows), labels=torch.tensor(rows["label"], device=dev)).loss.backward()
opt.step(); opt.zero_grad()
model.eval()
with torch.no_grad():
right = sum((model(**batch(r)).logits.argmax(-1).cpu() == torch.tensor(r["label"])).sum().item() for r in test.iter(batch_size=32))
print(right, "of", len(test))932 of 1000
Names pulled out of a text
A label for the whole text is one job. A label for every token is another: each token gets person, company, place or nothing. That is where seeing both ways matters most. This encoder is BERT, trained on news with its names marked. dslim/bert-base-NER
from transformers import pipeline
ner = pipeline("token-classification", model="dslim/bert-base-NER", aggregation_strategy="simple")
for found in ner("Jane Smith signed the lease with Acme Corporation in Toronto on March 3."):
print(found["entity_group"], found["word"], round(float(found["score"]), 3))PER Jane Smith 0.999 ORG Acme Corporation 0.981 LOC Toronto 0.999
What 1,000 labels cost by API
A chat model behind an API is paid by the token. Each review was a prompt of about 128 tokens, and the answer is one word. At Claude Haiku 5.5's price on the day this was checked, it is cheap. At a million reviews a day, it adds up, and the small encoder runs on your own computer. Claude's pricing
tokens_in = 128 * 1000 # about 128 tokens a prompt, for each of the 1,000 reviews
tokens_out = 1 * 1000 # one word back for each
price_in, price_out = 0.10, 0.50 # dollars per million tokens
cost = tokens_in / 1e6 * price_in + tokens_out / 1e6 * price_out
print(round(cost, 4), "dollars for 1,000 reviews")
print(round(cost * 1000, 2), "dollars a day, at a million reviews a day")0.0133 dollars for 1,000 reviews 13.3 dollars a day, at a million reviews a day
An encoder and a decoder together
Whisper turns speech into text with both. The encoder reads the whole sound, both ways. The decoder writes the text, looking only back, and each of its layers has a second attention, encoder_attn, that reads the encoder's vectors. Building it from its settings downloads no weights. Whisper
from transformers import AutoConfig, WhisperForConditionalGeneration
config = AutoConfig.from_pretrained("openai/whisper-tiny")
whisper = WhisperForConditionalGeneration(config)
print(config.encoder_layers, config.decoder_layers)
print([name for name, _ in whisper.model.decoder.layers[0].named_children()])4 4 ['self_attn', 'activation_fn', 'self_attn_layer_norm', 'encoder_attn', 'encoder_attn_layer_norm', 'fc1', 'fc2', 'final_layer_norm']
Newer encoders to start from
BERT reads 512 tokens at most. ModernBERT (December 2024) reads 8,192, and Ettin's encoders, built the same way, nearly as many. mmBERT (July 2025) is the same idea, trained on over 1,800 languages, with a much larger table of tokens. For English, start from ModernBERT or Ettin; for other languages, mmBERT. ModernBERT, mmBERT
for name in ["google-bert/bert-base-uncased", "answerdotai/ModernBERT-base", "jhu-clsp/mmBERT-base", "jhu-clsp/ettin-encoder-150m"]:
c = AutoConfig.from_pretrained(name)
print(name, c.max_position_embeddings, c.vocab_size)google-bert/bert-base-uncased 512 30522 answerdotai/ModernBERT-base 8192 50368 jhu-clsp/mmBERT-base 8192 256000 jhu-clsp/ettin-encoder-150m 7999 50368
Run on Python 3.13, PyTorch 2.15.0, Transformers 5.24.0, Datasets 5.2.0, on a Mac's GPU (MPS). Checked on .
Quiz
Two questions on this lesson, and one from earlier. Answer as often as you like.
1 of 3
From earlier: The transformer block
Seven tokens' vectors, 1,024 numbers each, go through the second half of a block: a norm, an MLP that widens to 3,072 and comes back, and its change added. What does this print?
import torch
from torch import nn
x = torch.randn(7, 1024)
norm = nn.RMSNorm(1024)
mlp = nn.Sequential(nn.Linear(1024, 3072), nn.ReLU(), nn.Linear(3072, 1024))
x = x + mlp(norm(x))
print(x.shape)2 of 3
Every day you must mark 50,000 support tickets urgent or not. You already have 3,000 tickets marked. Which do you use?
3 of 3
A decoder reads "The box was closed with a seal.", 8 tokens. In its grid of shares, each row is one token. How many of the grid's 64 cells are open, where a token may look?
The ideas in this lesson
- Decoder
- Each token sees only the tokens before it, so the model can be trained to write the next token: the GPT kind.
- Encoder
- Every token sees every token; trained to fill in hidden words, it reads a text and gives a vector or a label: the BERT kind.
- Encoder or decoder
- A label or names on many texts: a small trained encoder; writing: a decoder; reading then writing: both.
It leans on
Transcript
What the video says, part by part. Press a time to watch from there.
Ask a chat model, or train a small one?
Here's a bet. You have a thousand product reviews. You want each one marked good or bad. You could ask a chat model. Or you could train a much smaller model. Which one gets more of them right?
The job
Here's the job: a thousand real product reviews, half good and half bad. On one side, chat models, asked with no training. On the other, a small model, trained on two thousand reviews with their labels. Hold on to your guess. The answer comes from how each model sees a sentence.
Why only back
Every model in this course so far writes. It learns by guessing each next token in a text, all at once.
In attention, a token takes a share from what it can see. So what if it could see ahead? It would see the very token it has to guess. That's no test at all.
So which tokens can "box" look at?
Only "The", and itself.
Each token sees only the tokens before it. In the grid of shares, the upper half is closed. It's like writing: you don't know your next word until you get there.
A model like this is called a decoder. The GPT kind.
Both ways
A decoder's tokens see only the tokens before them, so it can write.
But what if a model never writes? What if it only reads?
Then nothing needs to be hidden. Every token looks at every token, before and after.
Here, "box" looks most at "seal", which comes after it. The grid is full. It's like reading a finished sentence.
A model like this is called an encoder. The BERT kind.
Fill a gap
But how do you train a model that never writes? There's no next token to guess.
So you hide a word, and it fills in the gap from both sides. "The blank was closed with a seal." What will it guess?
Door. It used "closed with a seal", which comes after the gap. A decoder at that place sees only "The". Its best guesses could start any sentence.
A label from an encoder
So what do you get from an encoder?
A vector for every token, each made from the whole text. Put one small layer on top that turns those vectors into a label: good or bad. Then train it on reviews with their labels.
This encoder has a hundred and fifty million weights. It trained on two thousand reviews in under three minutes, once.
Then it labeled a thousand new ones. Nine hundred and forty-three right, in thirteen seconds.
The training is done once. Every thousand after that takes thirteen seconds.
The same size, the other shape
Does seeing both ways matter here?
Here's a decoder made by the same people as this encoder, on the same text, the same size. It was trained on the same reviews, the same way.
Nine hundred and thirty-five. Close.
Its label is read at its last token. Looking back, that last token sees the whole review. So where does seeing both ways matter most? Where every token needs its own label, like pulling names out of a contract. There, a decoder's tokens can't see the words after them, just like the decoder at the gap.
A chat model, asked
So why not just ask a chat model? A chat model is a decoder, trained to answer people. This one is four times the encoder's size. We asked it about the same thousand reviews, "Is this review positive or negative?", with no training at all.
Eight hundred and one right. And it took eighty-four seconds, more than six times as long as the encoder. And a chat model eleven times the encoder's size?
Nine hundred and twenty-two. Closer, but still fewer. And it took three and a half minutes. So for one simple job on many texts, the small trained model wins.
Which to use
So which one should you use? It depends on the job. An encoder reads a whole text, both ways. A decoder sees only back, and writes.
For a label, or for names pulled out of many texts: a small encoder, trained on a few thousand examples. For writing a reply: a decoder. For reading one thing and writing another, like translation, or speech to text: both, an encoder and a decoder together.
And a chat model is a quick way to start, when you have no labeled examples yet.
In code
Now in real code. Here's the encoder, filling in a gap with a Hugging Face pipeline. A special token stands where the word is hidden. What comes out first?
"Door", with almost four in ten.
For a label, load the same encoder with a label layer and two labels. Train it on the two thousand reviews. Then it labels the thousand in thirteen seconds.
Here's one of those reviews. It praises a camera battery. The encoder says: good. The smaller chat model said: bad.
BERT, from twenty eighteen, is still the most downloaded model of its kind. So for a job you do every day, try a small model first.
Three ideas
A decoder sees only back, so it can write.
An encoder sees both ways, so it reads.
For a label on many texts, a small trained encoder. For writing, a decoder.
The lab
That's the end of this unit. In the lab, you use these three lessons to open up a real transformer. You'll run one of its blocks by hand, and test what each token can see.
Read both ways, write one way
Read with an encoder, and write with a decoder. Now try it on this lesson's page, and take the quiz. Find what "seal" looks at in the encoder.
You use this lesson in Lab 3: Open up a real transformer, which comes next.
Facts last checked on .
