Replaced Token Detection › The RTD Objective

Michael BrenndoerferUpdated July 12, 202512 min read
Language AI HandbookAll chapters
Part 22 of 67Pre-training Objectives
Chapter 160Replaced Token Detection › The RTD Objective
Reading section 3 of 17 · The RTD Objective · 12 minSection 3 of 17 · 12 min

Book contents

Section 3 of 17 · 12 min read

Replaced Token Detection › The RTD ObjectiveOne section · Sections in this chapter3 / 17 ↓
Reading tools Definitions & inline links

Choose your expertise level to adjust how many terms are explained. Beginners see more tooltips, experts see fewer to maintain reading flow. Hover over underlined terms for instant definitions.

Article links

Make inline references clickable

To understand how RTD trains both networks effectively, we need to think about what each network must learn and how to measure its progress. The generator must learn to produce plausible replacements for masked tokens, while the discriminator must learn to detect which tokens have been swapped. These are different tasks requiring different loss functions, yet they must work together in a single training loop.

Let's build up the complete objective by examining each component, understanding why it takes its particular form, and seeing how the pieces combine into an efficient training signal.

Generator Loss: Learning to Replace

The generator faces a familiar task: predict the original token at each masked position. This is identical to masked language modeling. We mask some positions in the input, show the generator the corrupted sequence, and ask it to predict what was hidden.

Why use MLM for the generator? The goal is to produce plausible replacements that will challenge the discriminator. A generator that simply outputs random tokens would be trivial to detect. By training on MLM, the generator learns the statistical patterns of language, producing replacements that fit grammatically and semantically into their contexts. The discriminator then must use syntax and semantics to distinguish these plausible fakes from originals.

Formally, given a set of masked positions M\mathcal{M}, we minimize the negative log-likelihood of the original tokens:

LGen=−∑i∈Mlog⁡PG(xi∣x~)\mathcal{L}_{\text{Gen}} = -\sum_{i \in \mathcal{M}} \log P_G(x_i | \tilde{x})

where:

  • LGen\mathcal{L}_{\text{Gen}} is the generator loss, identical to standard MLM loss
  • M\mathcal{M} is the set of masked position indices (typically 15% of positions)
  • xix_i is the original token at position ii that we want to predict
  • x~\tilde{x} is the corrupted input sequence with [MASK] tokens at positions in M\mathcal{M}
  • PG(xi∣x~)P_G(x_i | \tilde{x}) is the probability the generator assigns to the correct token xix_i, conditioned on seeing the masked sequence

To understand this formula intuitively, consider what happens as training progresses. Initially, the generator assigns roughly uniform probability across all vocabulary tokens, making PG(xi∣x~)≈1/VP_G(x_i | \tilde{x}) \approx 1/V where VV is vocabulary size. The log of this small probability is a large negative number, producing high loss. As the generator learns, it concentrates probability on likely tokens, increasing PG(xi∣x~)P_G(x_i | \tilde{x}) toward 1. The log approaches zero, and loss decreases.

Out[5]:
Visualization
Line plot showing negative log loss decreasing from high values near zero probability to near zero at probability 1.0.
Generator loss as a function of predicted probability. When the generator assigns low probability to the correct token, loss is high. As probability increases toward 1.0, loss approaches zero. The steep curve near zero creates strong gradients for learning when predictions are poor.

The summation iterates only over masked positions because those are the only positions where we have a prediction task. Unmasked positions pass through unchanged, contributing nothing to generator learning. This sparsity is the inefficiency that the discriminator's loss will address.

Discriminator Loss: Learning to Detect

Now we arrive at the key innovation. The discriminator receives a sequence where masked positions have been filled with generator samples, and must classify every token as original or replaced. This binary classification task applies to all positions. This provides the dense training signal that makes RTD efficient.

Think about what the discriminator must learn. For original tokens, it needs to recognize that they fit naturally into their context. For replaced tokens, even plausible ones, it must detect subtle mismatches. Perhaps the replacement "waiter" in "The waiter barked loudly" is grammatically acceptable but semantically wrong. The discriminator learns these nuances by processing the entire sequence and making a decision at each position.

We create the corrupted sequence x^\hat{x} by sampling from the generator's output distribution at masked positions. The discriminator then outputs a probability for each position, and we compute binary cross-entropy against the ground truth labels:

LDisc=−∑i=1n[yilog⁡D(x^)i+(1−yi)log⁡(1−D(x^)i)]\mathcal{L}_{\text{Disc}} = -\sum_{i=1}^{n} \left[ y_i \log D(\hat{x})_i + (1 - y_i) \log (1 - D(\hat{x})_i) \right]

where:

  • LDisc\mathcal{L}_{\text{Disc}} is the discriminator loss, a sum over all positions
  • nn is the total sequence length (not just masked positions)
  • yiy_i is the binary label at position ii (1 if original, 0 if replaced)
  • x^\hat{x} is the corrupted sequence with generator samples inserted at previously masked positions
  • D(x^)iD(\hat{x})_i is the discriminator's predicted probability that position ii contains an original token

This binary cross-entropy formula rewards correct predictions at both extremes. Let's trace through what each term contributes:

  1. For original tokens (yi=1y_i = 1): The second term vanishes since (1−yi)=0(1 - y_i) = 0. The loss becomes −log⁡D(x^)i-\log D(\hat{x})_i. When the discriminator correctly predicts high probability (near 1.0), the log is near zero, contributing little loss. When it incorrectly predicts low probability, the log is a large negative number, producing high loss.

  2. For replaced tokens (yi=0y_i = 0): The first term vanishes. The loss becomes −log⁡(1−D(x^)i)-\log(1 - D(\hat{x})_i). When the discriminator correctly predicts low probability (near 0), (1−D(x^)i)(1 - D(\hat{x})_i) is near 1, and the log is near zero. When it incorrectly predicts high probability, the loss is large.

Out[6]:
Visualization
Line plot showing loss curve for original tokens decreasing as probability increases.
Discriminator loss for original tokens. Loss decreases as the predicted 'is original' probability increases toward 1.0.
Line plot showing loss curve for replaced tokens decreasing as probability decreases.
Discriminator loss for replaced tokens. Loss decreases as the predicted probability decreases toward 0.0.

The key point is that this loss applies to every position in the sequence. Most positions contain original tokens, so the discriminator primarily learns what "normal" tokens look like in context. A small fraction contain replacements, teaching the discriminator what "wrong" looks like. Both types of positions contribute to learning, giving 6-7x more training signal than MLM's masked-only approach.

Combining the Losses

With both component losses defined, we need a strategy for combining them into a single objective that trains both networks. The simplest approach is a weighted sum:

LRTD=LGen+λ⋅LDisc\mathcal{L}_{\text{RTD}} = \mathcal{L}_{\text{Gen}} + \lambda \cdot \mathcal{L}_{\text{Disc}}

where:

  • LRTD\mathcal{L}_{\text{RTD}} is the total loss used to update both networks
  • LGen\mathcal{L}_{\text{Gen}} is the generator's MLM loss (computed only at masked positions)
  • LDisc\mathcal{L}_{\text{Disc}} is the discriminator's binary classification loss (computed at all positions)
  • λ\lambda is a weighting factor that balances the two losses

Why weight the losses differently? The answer lies in what we ultimately care about. After pretraining, we discard the generator and use only the discriminator for downstream tasks. The generator exists solely to create challenging training examples. From this perspective, generator learning is a means to an end: we want it good enough to produce useful replacements, but not so good that it dominates the training budget.

The ELECTRA paper uses λ=50\lambda = 50, heavily weighting the discriminator loss. This asymmetry reflects the different roles of the two networks. With this weighting, most of the gradient signal flows to the discriminator, which receives the bulk of the learning capacity. The generator still improves through its share of the gradient, producing increasingly plausible replacements that keep the discriminator challenged.

Out[7]:
Visualization
Stacked bar chart showing generator and discriminator contributions to total loss at different lambda values.
Effect of the discriminator weight on loss contribution. With typical loss values and lambda = 50, the discriminator loss dominates the total, directing most gradient signal to the discriminator. Lower lambda values would shift more learning toward the generator.

This design creates a beneficial training dynamic. As the generator improves, its replacements become harder to detect. The discriminator must develop more sophisticated representations to keep up. But because the generator is smaller and receives less gradient signal, it cannot outpace the discriminator. The asymmetry maintains a productive difficulty level throughout training.

In practice, the λ=50\lambda = 50 weighting means that even a modest reduction in discriminator loss has an outsized effect on the total objective. Consider what this looks like numerically: if the generator loss is around 2.5 and the discriminator loss is around 0.5, then the total loss is 2.5+50×0.5=27.52.5 + 50 \times 0.5 = 27.5. The discriminator component accounts for over 90% of the total. This massive weighting ensures that the combined optimizer's gradient is dominated by what's good for the discriminator, not the generator. The generator improves as a side effect of the shared backward pass through the combined loss, but its improvement is secondary.

An important subtlety in the training procedure is how gradients flow between the two networks. The sampling step that converts generator logits into replacement tokens is discrete and non-differentiable. You cannot backpropagate a gradient through the torch.multinomial operation. This means the discriminator's loss does not flow back into the generator through the replacement tokens. The generator learns only from its own MLM loss, not from whether the discriminator succeeded or failed. This is a key difference from GANs, where generator gradients flow through the discriminator's assessment. In RTD, the two networks are gradient-isolated except through the shared embedding weights.

Out[8]:
Visualization
Bar chart showing sparse loss for MLM where only masked positions contribute signal.
MLM computes loss only at masked positions (15% of tokens). Gray positions provide no training signal.
Bar chart showing dense loss for RTD where all positions contribute signal.
RTD computes discriminator loss at every position. This gives 6-7x more training signal per forward pass.