Course contents 22 / 28

22 / 28 · Pretrained Language Models

Evolution of pretrained models: RoBERTa, ELECTRA, GPT-2 and ModernBERT

Separate architecture, objectives, data and execution when comparing RoBERTa, ELECTRA, GPT-2 and ModernBERT; calculate masking coverage, replacement labels and padding cost.

On this page 7

Two encoders can have the same layer count and still learn different representations. One may see different text, predict different targets or spend less computation on padding. Before attributing a result to an architecture, we need to identify which parts of the experiment changed.

Baseline: the recipes of BERT and GPT#

BERT reconstructs selected tokens from corrupted bidirectional context. GPT predicts the next token from a causal prefix. These pair an attention layout with a training objective. Neither model name specifies the entire experiment: tokenization, sequence construction, optimizer, amount of training and downstream adaptation also affect what is learned.

A comparison at equal training steps may use different numbers of tokens, differently sized batches or different computation per token. A comparison at equal parameter count may still require different memory and latency. State the resource held fixed before interpreting an improvement.

Five kinds of change#

Part of a recipeWhat to record
ArchitectureAttention layout, positions, depth, width and output head
ObjectivePrediction target, corruption and loss reduction
DataSource permissions, selection, mixture and repeated exposure
OptimizationBatch, schedule, updates and token budget
ExecutionPadding, numerical format, kernels and hardware

An ablation changes a controlled subset and evaluates with a fixed protocol. If both the corpus and loss change, a better result does not identify which change caused the gain. Even a controlled comparison needs several runs when optimization randomness materially affects the metric.

RoBERTa: the same network, trained differently#

Liu et al. studied BERT’s training recipe while retaining its core bidirectional Transformer design. Their experiments examine dynamic masking, input construction without the next-sentence prediction objective, batch size and more training data. The final recipe changes several factors together. Its result therefore cannot be attributed to removing one loss term alone.

With a static corruption pattern, repeated visits can present exactly the same reconstruction targets. Dynamic masking resamples positions on each visit. Consider our own simplified rule: select two distinct positions uniformly from a six-token sequence, independently across three visits. There are 15 possible masks per visit. For any position, the probability of never being selected is (2/3)3(2/3)^3. By linearity of expectation, the number UU of distinct selected positions satisfies

E[U]=6(1−(23)3)=389.\mathbb E[U]=6\left(1-\left(\frac23\right)^3\right)=\frac{38}{9}.

Keeping one static mask would cover exactly two positions. The dynamic rule covers about 4.222 positions on average, although any individual run can cover between two and six. Exhaustive enumeration of the 3375 triples of masks verifies the expectation. This is a constructed coverage calculation, not a score for RoBERTa, and it does not imply that every newly masked target is equally informative.

The original BERT preprocessing could store several masked copies; it was not limited to one permanently fixed mask per document. The calculation isolates the resampling mechanism without claiming to reproduce either full training pipeline.

ELECTRA: a training signal at every position#

ELECTRA changes the pretraining target. A generator fills selected masked positions, and a discriminator predicts whether each resulting token matches the original token. The generator learns a masked-token likelihood; it is not optimized through the discriminator as an ordinary differentiable GAN generator. After pretraining, the discriminator is retained for downstream adaptation (Clark et al., §2).

Let xx be the original sequence, x~\tilde x the generator-corrupted sequence and SS the selected positions. Define yi=1y_i=1 when x~i=xi\tilde x_i=x_i, and let DiD_i predict that event. Using mean reductions for this example,

LG=−1∣S∣∑i∈Slog⁡G(xi∣xmasked),LD=−1n∑i=1n[yilog⁡Di+(1−yi)log⁡(1−Di)].\begin{aligned} \mathcal L_G&=-\frac1{|S|}\sum_{i\in S}\log G(x_i\mid x^{\mathrm{masked}}),\\ \mathcal L_D&=-\frac1n\sum_{i=1}^n\left[y_i\log D_i+(1-y_i)\log(1-D_i)\right]. \end{aligned}

Both models receive training signals, but these losses have different targets and denominators. A combined objective must specify their relative weight. Padding is excluded. A discriminator with a binary head does not directly provide a normalized distribution over the vocabulary for next-token generation.

Worked example. Start with store the amber crate inside. Select amber and crate. Suppose the generator produces amber and box. Only the fourth token actually changed, so the real-token labels are (1,1,1,0,1)(1,1,1,0,1). Selecting a token for corruption does not by itself make its discriminator label zero.

Give the discriminator hypothetical real-token probabilities (0.9,0.8,0.6,0.3,0.7)(0.9,0.8,0.6,0.3,0.7). Its mean loss is approximately 0.310536. If the generator assigns the two original target tokens probabilities 0.4 and 0.25, its mean loss is approximately 1.151293. These are specified probabilities, not outputs of a trained network. Under repeated generator sampling, the expected number of changed selected tokens would be (1−0.4)+(1−0.25)=1.35(1-0.4)+(1-0.25)=1.35; the displayed single corruption changed one.

A larger number of scored positions does not guarantee a better representation. If replacements are trivial to detect, the discriminator may rely on superficial cues. If nearly every replacement matches the original, the negative class becomes rare. The generator and corruption policy determine the task’s difficulty.

GPT-2: the same objective at a larger scale#

The next-token objective remains the one derived in GPT. The GPT-2 report studies larger models and a web-text collection, with changes including byte-level tokenization and pre-normalization. Task transfer is evaluated through textual context without updating weights separately for each evaluated task.

More parameters, more data and a different tokenizer all change the experiment. In particular, perplexities measured with different token units are not directly interchangeable. A historical report’s training collection is also not automatically available for reuse: source permissions and any separately released data require their own review. No part of that collection is used in our examples.

ModernBERT: an encoder rebuilt with a decoder’s parts#

ModernBERT brings changes familiar from later Transformer systems into a bidirectional encoder: rotary positions, pre-normalization, gated feed-forward layers and alternating local/global attention. Its report also describes variable-length unpadding, efficient attention kernels and a changed data/training recipe. These changes do not turn the encoder into an autoregressive decoder; its attention layout and masked-token target remain decisive.

Unpadding illustrates the difference between architecture and execution. Take three independent sequences of lengths 2, 5 and 3. Padding every sequence to length five allocates 15 token slots although only ten contain real tokens. A dense per-sequence attention implementation computes 75 query-key score slots. Processing actual lengths separately requires

22+52+32=382^2+5^2+3^2=38

valid within-sequence pairs. Concatenating the ten tokens without boundary information would instead allow cross-document interactions and change the model’s computation. A variable-length implementation must preserve the three boundaries. The pair counts are exact for our dense example; they are not a latency prediction and do not include local-attention patterns or projections.

A kernel can compute the same allowed attention result with a different memory-access pattern. Local attention changes the allowed pairs themselves. Treating both as “faster attention” hides an important distinction when validating equivalence.

What changed#

RoBERTa motivates controlled training-recipe comparisons; ELECTRA changes what the model predicts; GPT-2 studies scale and prompt-based transfer; ModernBERT combines architectural and execution changes. The name of a successor is a starting point for reading its recipe, not an explanation of every measured improvement.

Limitations#

Our examples isolate counting, loss and masking mechanisms without training any model. They cannot establish downstream ranking, throughput or fairness. Published ablations apply to their data, budgets and evaluation settings. Moving to another language, domain or hardware setup requires new measurements, and permission to use a library does not provide permission for its training corpus or weights.

What you should remember#

Compare objectives, data, budgets and execution separately. A masked position can remain an original token after sampling. State loss reductions. Resampling changes target coverage. Unpadding must preserve sequence boundaries.

Code#

This original small calculation checks the discriminator labels and the two mean losses.

import math

original = ['store', 'the', 'amber', 'crate', 'inside']
corrupted = ['store', 'the', 'amber', 'box', 'inside']
labels = [int(a == b) for a, b in zip(original, corrupted)]
probabilities = [0.9, 0.8, 0.6, 0.3, 0.7]
loss_d = -sum(math.log(p if y else 1-p)
              for p, y in zip(probabilities, labels)) / len(labels)
loss_g = -(math.log(0.4) + math.log(0.25)) / 2
print(labels)
print(f'generator {loss_g:.6f}; discriminator {loss_d:.6f}')
[1, 1, 1, 0, 1]
generator 1.151293; discriminator 0.310536

Next#

Architecture names alone leave the information flow underspecified. Encoder, decoder and encoder–decoder models compares their masks, output structures and training targets directly.

References#