Replaced Token Detection › The RTD Objective
Language AI HandbookAll chapters 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 , we minimize the negative log-likelihood of the original tokens:
where:
- is the generator loss, identical to standard MLM loss
- is the set of masked position indices (typically 15% of positions)
- is the original token at position that we want to predict
- is the corrupted input sequence with
[MASK]tokens at positions in - is the probability the generator assigns to the correct token , 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 where 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 toward 1. The log approaches zero, and loss decreases.

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 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:
where:
- is the discriminator loss, a sum over all positions
- is the total sequence length (not just masked positions)
- is the binary label at position (1 if original, 0 if replaced)
- is the corrupted sequence with generator samples inserted at previously masked positions
- is the discriminator's predicted probability that position contains an original token
This binary cross-entropy formula rewards correct predictions at both extremes. Let's trace through what each term contributes:
-
For original tokens (): The second term vanishes since . The loss becomes . 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.
-
For replaced tokens (): The first term vanishes. The loss becomes . When the discriminator correctly predicts low probability (near 0), is near 1, and the log is near zero. When it incorrectly predicts high probability, the loss is large.


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:
where:
- is the total loss used to update both networks
- is the generator's MLM loss (computed only at masked positions)
- is the discriminator's binary classification loss (computed at all positions)
- 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 , 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.

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 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 . 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.

