Pretrained Encoders

Dive into Deep Learning · §19.2

Pretrained Encoders
masked tokens · ModernBERT · three heads · seeds · encoder or prompt

A Fine-Tuned Encoder Labels MNLI Better Than a Prompt, and Far Faster

The problem

MNLI: does a premise entail, contradict, or leave open a hypothesis? The same 2,000 validation pairs for both models, one RTX 4090.

model labeled examples accuracy seconds per 1,000 pairs
ModernBERT-base, fine-tuned (mean of 3 seeds) 16,000 0.84 0.4
Qwen3-1.7B, 8 solved examples (mean of 3 sets) 8 0.63 48

Not a fair comparison: the encoder learned from 16,000 labels, the decoder from 8. How many labels does the encoder need before it passes the prompt?

By the End of This Deck You Can

Goals

  • say what a masked-token encoder computes, and why BERT masks only 80% of the tokens it scores;
  • compute what alternating attention saves at a given input length;
  • fine-tune a sentence, a pair and a token head;
  • tell seed noise from a run that was too short, and ask for a hypothesis-only baseline;
  • choose between a fine-tuned encoder and a prompted decoder from labels and cost.

Running example: ModernBERT-base (149 million parameters) against Qwen3-1.7B on MNLI (pairs), SST-2 (sentiment) and CoNLL-2003 (names).

With Thousands of Labels and a Stream of Items, a Fine-Tuned Encoder Takes Over

Where this fits

movement section
vectors Word Embeddings
Pretrained Encoders
Text Embeddings
finding Sparse, Dense and Approximate Retrieval
using what is found Retrieval-Augmented Generation
Failures and Fixes in RAG
  • Uses: a bidirectional encoder trained on masked bytes; few-shot prompts read by label log-probabilities.
  • Skips: pretraining an encoder; tuning only part of the weights.

One Pair In, Sixteen Vectors Out, Each from the Whole Input

A released encoder

[CLS] A Ġman Ġplays Ġa Ġguitar Ġon Ġstage . [SEP] Someone Ġis Ġmaking Ġmusic . [SEP]

  • [CLS] opens, [SEP] closes each text, no segment ids; Ġ: a leading space.
  • Output (1, 16, 768): both texts read together, a cross-encoder.
cosine between two vectors, four sentences embedding layer last layer
“bank”, same sense (two by the water; two of money) 1.00 0.81, 0.85
“bank”, other senses (three pairs) 1.00 0.65 to 0.72
“bank” and “the” in one sentence: the floor 0.01 0.32

A table of word vectors gives “bank” one point. The encoder gives it one per sentence, and every same-sense pair lies above every cross-sense pair.

A Masked-Token Encoder Fills a Gap from Both Sides

No causal mask: every token attends to every token. Pretraining hides tokens and predicts them, \max \sum_{t \in \mathcal{M}} \log p(x_t \mid \mathbf{x}_{\setminus \mathcal{M}}), with \mathcal{M} the hidden positions.

text five most probable fills
The capital of France is [MASK]. Paris 0.92, Lyon 0.04, Nancy 0.02, Nice 0.01, Orleans 0.00
He drank a cup of [MASK] before work. coffee 0.61, tea 0.21, water 0.08, milk 0.04, wine 0.01
The encoder reads the words on [MASK] sides of the gap. both 0.94, the 0.03, opposite 0.01, two 0.01, all 0.01

“both” needs the word after the gap. The head predicts words, not labels: every task gets a new head.

BERT Scores 15% of Tokens, and Only 80% of Those Show [MASK]

of the selected 15% becomes why
80% [MASK] the gap-filling the head is built for
10% a random token a visible token may be wrong
10% itself a visible token may be scored

Counted on a million token ids: 15% selected; of those 80% [MASK], 10% random, 10% kept; special tokens never. So 12% of all tokens show [MASK].

[MASK] never occurs in fine-tuning text, and any position may be asked about its own token. Yet in BERT’s ablation fine-tuning was “surprisingly robust” to the mix.

BERT’s Successors Trained Longer or Changed the Objective

  • Next-sentence prediction: BERT’s second objective, on the [CLS] vector: did text B follow text A? The successors dropped it.
  • RoBERTa: new masks each time a text is read; longer training on far more text. BERT was undertrained, not misdesigned.
  • ELECTRA: a small generator replaces tokens; the encoder says for every token whether it was replaced, a training signal at every position, not 15%.
  • T5: masked spans written by a decoder; every task is text to text, a step toward decoders that do everything by writing text.

ModernBERT Keeps BERT’s Objective and Rebuilds the Block

field ModernBERT-base
layers, width, heads 22, 768, 12
parameters 149 million
objective masked tokens; no next-sentence prediction
longest input 8,192 tokens (BERT: 512)
attention every third layer global (all tokens), the others local (window of 128, 64 each side)
pooling in its head mean
  • Two lines matter later: mean pooling (the head must follow it) and alternating attention (the cost of long inputs).
  • Gated feed-forward layer, rotary positions, no biases in the blocks: details of the block.

Alternating Attention Scores 37% of the Pairs at 8,192 Tokens

s(T) = \frac{n_g T^2 + n_l T w}{(n_g + n_l) T^2} = \frac{n_g T + n_l w}{(n_g + n_l) T}

s: pairs of positions scored, as a share of all-global attention. T: tokens of the input. n_g = 8 global and n_l = 14 local layers, window w = 128. Pairs counted from boolean masks:

T per global layer per local layer share, counted share, formula
512 262,144 61,888 0.51 0.52
8,192 67,108,864 1,052,608 0.37 0.37

For long inputs s \to n_g / (n_g + n_l) = 8/22: the global layers set the cost.

Check: When Does the Window Save Nothing?

Check

A local layer lets token i attend to j when |i - j| \le 64. An MNLI pair has about 40 tokens. What does alternating attention save on it?

Answer. Nothing. For T \le 65 every window covers the whole input, and every local layer acts as a global one. The saving comes only on long texts: half the pairs at 512 tokens.

One Encoder Serves Three Tasks; Only the Input and the Head Change

Sentence and pair classification

task input vectors read output
sentence (SST-2) [CLS] sentence [SEP] mean over tokens 2 logits
pair (MNLI) [CLS] premise [SEP] hypothesis [SEP] mean over tokens 3 logits
tagging (CoNLL-2003) [CLS] sentence among its neighbours [SEP] each word’s first token 9 logits per word

Each head: dense, GELU and norm taken from the pretrained masked-token head, then a new linear map. Fine-tuning trains all weights.

Our Pooled Head Reproduces the Library’s Logits

\bar{\mathbf{h}} = \frac{1}{T}\sum_{t=1}^{T} \mathbf{h}_t, \qquad \mathbf{z} = \mathbf{W}_\textrm{c}\, \textrm{LN}\big(\textrm{GELU}(\mathbf{W}_\textrm{d}\bar{\mathbf{h}})\big) + \mathbf{b}_\textrm{c}

\mathbf{h}_t: final vector of token t of T, padding left out. \mathbf{W}_\textrm{d}: 768 \times 768. \mathbf{W}_\textrm{c}, \mathbf{b}_\textrm{c}: one row per class. LN: layer norm.

  • Library weights loaded by renaming, strictly.
  • Eight padded MNLI pairs: largest logit difference 0.0 in fp32 and in bf16, the same operations in the same order.

Read classifier_pooling from the configuration: this checkpoint pools by the mean, not by [CLS].

Fine-Tuning Trains Every Weight, in Small Steps, for at Least 300 of Them

  • AdamW, weight decay 0.01 on matrices, gradients clipped at norm 1.
  • Learning rate: warmup over 10% of the steps, then linear decay; chosen from \{2, 5, 8, 15\} \times 10^{-5} on held-out training pairs (8 \times 10^{-5}).
  • Batch 32; two epochs, or more to reach 300 steps.
  • A seed fixes the new layer’s initialization and the batch order, nothing else.

16 bytes per parameter for weights, gradients and two moments: 2.4 GB for 149 million, plus activations.

Too Few Optimizer Steps Look Like Seed Noise

Seeds and sample size

MNLI accuracy, mean of three seeds, with the range over seeds in parentheses. Majority rate: 0.36.

labeled pairs 250 1,000 4,000 16,000
two epochs: steps 16 64 250 1,000
accuracy 0.38 (0.05) 0.47 (0.16) 0.75 (0.10) 0.84 (0.00)
at least 300 steps 304 320 375 1,000
accuracy 0.44 (0.02) 0.63 (0.02) 0.76 (0.03) 0.84 (0.00)
  • 1,000 pairs: the same data, five times the steps, and the seeds agree.
  • 250 pairs, two epochs: a small range because every seed sits near the majority rate.

Agreement among seeds shows that a result is reproducible, not that it is good.

Without the Premise, the Encoder Still Scores 0.53 on MNLI

Trained on 5,000 hypotheses alone; intervals resample premises.

majority-class rate: 0.363
        accuracy  CI low  CI high
seed 0     0.523   0.502    0.544
seed 1     0.528   0.507    0.550
seed 2     0.542   0.520    0.564
  • Annotators’ phrasing predicts the label: negations for contradictions, added details for neutral pairs.
  • More than half of the pairs right, after reading half of each.

Report an inference score beside a hypothesis-only baseline.

A Small Head on Token Vectors Tags Names at a Span F1 of 0.96

Token tagging

token [CLS] Peter ĠBlack burn [SEP]
label not scored B-PER I-PER not scored not scored
  • IOB2: B- the first word of a name, I- a later word, O no name; four types (PER, LOC, ORG, MISC), 9 tags.
  • A word’s tag goes to its first token. A name counts only if its type and both ends match.
  • Each sentence is read among its neighbours (256 tokens); only it is scored.
  • Precision 0.95, recall 0.96, span F1 about 0.96, equal to seqeval’s.
  • By type: PER and LOC about 0.98, ORG just under 0.95, MISC about 0.9.
  • Missed organizations: roughly half with wrong ends, the rest another type (NFL as MISC).

Nobody wrote a rule about capital letters or a list of cities.

Neighbouring Sentences and a Chosen Rate Close More than Half the Gap to BERT

Token tagging

trained on 14,041 sentences, three seeds span F1
sentence alone, rate 5 \times 10^{-5} 0.945 to 0.951
sentence alone, rate 8 \times 10^{-5} 0.952
with neighbours, rate 8 \times 10^{-5} 0.958
BERT-base, as reported 0.964
  • Rate chosen on 2,000 held-out training sentences (mean of three seeds).
  • With neighbours about 35 organizations get another type, without about 50.
  • 30 names right in every run with neighbours and in none without; 7 the other way.

Tag a sentence with its article around it, as BERT’s authors did, and choose the rate rather than fix it.

Eight Examples Convey Sentiment and Only Part of Inference

Encoder or prompted decoder

Qwen3-1.7B, accuracy by the number of solved examples in the prompt:

task (majority rate) 0 4 8 (three sets) naive Bayes, 8,000 / 16,000 labels
SST-2 (0.51) 0.71 0.93 0.93 to 0.95 0.78
MNLI (0.36) 0.40 0.65 0.62 to 0.65 0.42
  • MNLI errors over the three sets: entailed called neutral about 850 times, contradiction called neutral about 450, neutral called entailment about 300 and contradiction about 400; entailment and contradiction confused fewer than 200 times.
  • Word counts carry sentiment and little entailment.

Nearly all of the decoder’s MNLI errors are about where “maybe” begins.

Check: How Many Tokens Does the 8-Shot Decoder Read per Pair?

Check

The prompt holds 8 solved MNLI pairs and the query, about 500 tokens. The answer is read by appending each of the three label words yes, maybe, no and scoring it. The encoder reads about 40 tokens per pair.

Answer. Three copies of the prompt: 1,543 tokens measured, about 38 times the encoder’s 40. Most of them are the same solved examples, read again for every item. The label words are single tokens: with the examples cached and one pass per item, only the query is left, 49 tokens with its label word.

Operations Predict 500 Times the Cost; the Clock Shows 100

Cost per example

C = 2\,(N - N_\textrm{emb})\,T: a multiply and an add per non-embedding weight and token.

per MNLI pair encoder 8-shot decoder ratio
tokens 40 1,543 38
GFLOPs per token 0.22 2.8 13
GFLOPs 8.9 4,350 close to 500
seconds per 1,000, measured about 0.4 about 48 about 100
  • The clock gap: the encoder’s batch is padded to 87 tokens, 2.2 times the 40 counted; short pairs in batches of 32 leave the GPU partly idle.
  • With the examples cached, the query and one label word remain: 49 tokens at 13 times the weights per token, 16 times the encoder’s operations.

A hundredth as run here; 16 times the operations is what caching cannot remove. SST-2: about 30 times on the clock.

The Encoder Draws Level with 8 Shots on MNLI at 1,000 Labels and Leads from 4,000

  • Ahead = every seed × every set of examples agrees, and the gap exceeds both spreads.
  • MNLI, gap to 8 shots: -0.20 at 250; zero at 1,000; +0.13 at 4,000; +0.21 at 16,000.
  • SST-2: level only at 8,000.

Where the line runs depends on how much of the task the decoder already knows.

Check: Prompt or Fine-Tune?

Check

Case A: 50 labeled support messages, and new topics every month. Case B: 20,000 labeled pairs for a fixed task, and a million new items a day.

Answer. A: prompt a decoder. With a few hundred labels or fewer the decoder was ahead, and a new topic is a new prompt. B: fine-tune an encoder. From 4,000 MNLI pairs it led the 8-shot prompt, at a hundredth of the time per pair as run here, and about a sixteenth of the operations even with a cached prompt.

Wrap-up

  • A masked-token encoder gives one vector per token from both sides; a fine-tuned head turns them into a label per sentence, pair or word.
  • ModernBERT-base: 0.84 on MNLI (16,000 pairs), 0.93 on SST-2 (8,000), span F1 about 0.96 on CoNLL-2003 (sentences read among their neighbours).
  • Too few steps look like seed noise: seed range 0.16 with 64 steps, 0.02 with 320, at 1,000 MNLI pairs.
  • Hypothesis only: 0.53 on MNLI; majority rate 0.36.
  • Against 8-shot Qwen3-1.7B: level on MNLI at 1,000 labels, ahead from 4,000; level on SST-2 only at 8,000.
  • Cost per MNLI pair: a hundredth of the time as run here; about a sixteenth of the operations even with the examples cached.

Next: one vector per text, for search without labels.