AI Logic

Regularization

R-Drop

Updated:

Training and inference with R-Drop. On the left, during training, the same input x is passed twice through two sub-models that share weights and differ only in the dropped units, producing output distributions P1 and P2. The loss is the sum of each one's loss against the label y (βˆ’log P1 and βˆ’log P2) and the bidirectional KL divergence between the two distributions multiplied by Ξ±/2. On the right, during inference, the input passes once through the full model without Dropout

Background and Overview

R-Drop is a regularization method that passes the same input through a model with Dropout twice and adds the KL divergence between the two resulting output distributions to the loss, so that the two distributions move closer together. Liang, Wu, and colleagues (Soochow University and Microsoft Research Asia) presented it at NeurIPS in 2021. The name is short for Regularized Dropout.

Dropout computes each training step with a "sub-model" in which some units are dropped, while inference uses the full model with nothing dropped. As a result, the model used in training does not match the model used in inference. Moreover, because the dropped units are random, different sub-models can produce quite different outputs for the same input. Earlier methods that penalize the L2 difference between hidden-layer values (ELD and Fraternal Dropout) had been proposed, but they were not widely adopted.

R-Drop reduces this gap by training the model to produce the same output distribution no matter which units are dropped. It leaves the model architecture unchanged and only adds one term to the loss, so it applies almost as-is to any model that uses Dropout. The paper verifies its effect on 5 kinds of tasks and 18 datasets: machine translation with the Transformer, fine-tuning of BERT and RoBERTa, summarization with BART, language modeling, and image classification with ViT.

Theory (Building the Loss)

The explanation follows Equations (2)–(4) and Algorithm 1 of the original paper. Let (xi,yi)(x_i, y_i) be a training pair and Pw(y∣x)P^w(y \mid x) the output distribution of the model with Dropout (ww denotes the weights).

  1. Duplicate the input xix_i as [xi;xi][x_i; x_i] and concatenate along the mini-batch dimension. This lets the two forward passes run as a single computation.
  2. Run the forward pass with Dropout enabled. The first and second halves drop different units, so two sub-models sharing the same weights yield two distributions, P1w(yi∣xi)P_1^w(y_i \mid x_i) and P2w(yi∣xi)P_2^w(y_i \mid x_i).
  3. For each distribution, compute the negative log-likelihood of the label yiy_i (cross-entropy) and sum them. LNLLi=βˆ’log⁑P1w(yi∣xi)βˆ’log⁑P2w(yi∣xi)\mathcal{L}_{\mathrm{NLL}}^i = -\log P_1^w(y_i \mid x_i) - \log P_2^w(y_i \mid x_i)
  4. Compute the average of the two KL divergences between the distributions, one in each direction (the bidirectional KL divergence). LKLi=12(DKL ⁣(P1w(yi∣xi) βˆ₯ P2w(yi∣xi))+DKL ⁣(P2w(yi∣xi) βˆ₯ P1w(yi∣xi)))\mathcal{L}_{\mathrm{KL}}^i = \frac{1}{2}\left( D_{\mathrm{KL}}\!\left(P_1^w(y_i \mid x_i) \,\|\, P_2^w(y_i \mid x_i)\right) + D_{\mathrm{KL}}\!\left(P_2^w(y_i \mid x_i) \,\|\, P_1^w(y_i \mid x_i)\right) \right)
  5. Update the weights with the loss formed by adding the KL term weighted by Ξ±\alpha. Li=LNLLi+Ξ±β‹…LKLi\mathcal{L}^i = \mathcal{L}_{\mathrm{NLL}}^i + \alpha \cdot \mathcal{L}_{\mathrm{KL}}^i
  6. At inference, as with ordinary Dropout, compute once with the full model and no Dropout.

The KL divergence DKL(P βˆ₯ Q)=βˆ‘yP(y)log⁑P(y)Q(y)D_{\mathrm{KL}}(P \,\|\, Q) = \sum_y P(y) \log \frac{P(y)}{Q(y)} depends on direction. Averaging both directions treats the two sub-models symmetrically: rather than pulling one toward the other, it makes them meet in the middle. The gradient of the KL term flows into both sub-models.

For regression tasks, where the output is not a distribution, the mean squared error between the two predictions replaces the KL divergence. The paper uses this form for the regression task in GLUE (STS-B).

Why It Works

The paper frames R-Drop training as the following constrained optimization (Equations (5) and (6)), where ΞΎ\xi is the random variable describing which units Dropout drops.

min⁑wβ€…β€Š1nβˆ‘i=1nEξ ⁣[βˆ’log⁑PΞΎw(yi∣xi)]s.t.1nβˆ‘i=1nEΞΎ(1),ΞΎ(2) ⁣[DKL ⁣(PΞΎ(1)w(yi∣xi) βˆ₯ PΞΎ(2)w(yi∣xi))]≀ϡ\min_w \; \frac{1}{n}\sum_{i=1}^{n} \mathbb{E}_{\xi}\!\left[-\log P_{\xi}^w(y_i \mid x_i)\right] \quad \text{s.t.} \quad \frac{1}{n}\sum_{i=1}^{n} \mathbb{E}_{\xi^{(1)}, \xi^{(2)}}\!\left[D_{\mathrm{KL}}\!\left(P_{\xi^{(1)}}^w(y_i \mid x_i) \,\|\, P_{\xi^{(2)}}^w(y_i \mid x_i)\right)\right] \le \epsilon

Ordinary Dropout minimizes the average loss of the sub-models (the left expression). Inference, however, uses the full model, so a gap remains between the two losses. For linear models, the paper shows that under the constraint on the right, the difference between the full model's loss and the average sub-model loss is bounded by cΟ΅c\sqrt{\epsilon} (Proposition 2.1; cc is a constant related to the Lipschitz constant of the softmax). In other words, the more closely the sub-models' outputs agree, the smaller the gap between training and inference.

As an analogy, picture a team that is always missing a few members, asked to solve the same problem twice and penalized whenever the two answers disagree. A team trained to give the same answer no matter who is absent is more likely to give that same answer on the day everyone shows up (inference).

The paper highlights the following differences from earlier work.

  • Aligning output distributions: ELD and Fraternal Dropout penalized the L2 distance between hidden-layer values. R-Drop aligns in the space of output probability distributions, the same space as the training objective (negative log-likelihood). In the comparison in the paper's appendix, on IWSLT14 Germanβ†’English translation, R-Drop reached a BLEU of 37.25 versus 35.04 for Fraternal Dropout.
  • A form of self-distillation: Minimizing the KL divergence between two outputs has the same form as bringing the teacher's and student's outputs together in knowledge distillation. In R-Drop, two sub-models of the same model act as each other's teacher for every example.

Experiments also confirm that the KL term itself is what helps. On the same translation task, training that only duplicates the input without adding the KL term scored a BLEU of 34.93, barely different from the 34.64 of the baseline. R-Drop with the KL term scored 37.25.

Experimental Results

Results from the original paper. In every case R-Drop is simply added to the original model, with all other settings kept the same.

TaskModelMetricWithoutR-Drop
Translation IWSLT14 German→EnglishTransformerBLEU (higher is better)34.6437.25
Translation, average of 8 IWSLT directionsTransformerBLEU32.4434.68
Translation WMT14 English→GermanTransformer (big)BLEU29.1230.91
Translation WMT14 English→FrenchTransformer (big)BLEU42.6943.95
Average of 8 GLUE tasksBERT-baseAverage of per-task metrics82.8584.06
Average of 8 GLUE tasksRoBERTa-largeAverage of per-task metrics88.9389.73
Summarization CNN/Daily MailBARTROUGE-1 (higher is better)44.1644.51
Language modeling WikiText-103TransformerTest perplexity (lower is better)26.6224.94
Image classification CIFAR-100ViT-B/16Accuracy (%)92.6493.29
Image classification ImageNetViT-B/16Accuracy (%)83.9784.38
  • Large gains in translation: BLEU rose by more than 1 (mostly by more than 2) in all 8 IWSLT directions. The WMT14 scores of 30.91 and 43.95 were the best reported at the time, including methods that use large amounts of extra data.
  • Effective even on strong pretrained models: The GLUE, summarization, and ViT results all apply R-Drop while fine-tuning pretrained models.
  • The KL weight Ξ±\alpha varies by task: The paper uses 5 for translation, chooses from 0.1, 0.5, and 1.0 for GLUE, and uses 0.7 for summarization, 1.0 for language modeling, and 0.6 for ViT.

Practical Considerations

R-Drop increases both the computation per step and the number of steps to converge. Because the input is duplicated, the forward and backward passes cost as much as doubling the mini-batch. In the paper's measurements, one step of training with a doubled batch took about 9 ms, versus about 10 ms for R-Drop. In addition, because R-Drop resists overfitting, it needs more updates to reach its final performance (Figure 2 of the paper). Budget more training time than for ordinary training.

  • Choose Ξ±\alpha on validation data: In the translation experiment (Table 7), BLEU rose from 36.05 at Ξ±=1\alpha = 1 to 37.25 at Ξ±=5\alpha = 5 and fell to 36.95 at Ξ±=10\alpha = 10. The paper notes that the best value depends on the size of the data and the model, that is, on how prone the setting is to overfitting.
  • Useless without Dropout: The two outputs differ only because Dropout drops different units. With a Dropout rate of 0, or in model.eval() mode, both outputs are identical and the KL term is 0.
  • Use the same Dropout rate for both passes: In experiments that varied the Dropout rates of the two sub-models, the combination with equal rates (0.3 and 0.3) gave the best results.
  • Apply it every step: Applying R-Drop only once every kk steps to save computation led to earlier overfitting and lower BLEU as kk grew.
  • More than two passes gains little: Aligning KL across three sub-models gave a BLEU of 37.30, nearly the same as with two (37.25).
  • Experiments focus on Transformers: The paper's experiments mainly use Transformer-based models, and applying R-Drop to convolutional networks is left as future work.

Comparison with Other Methods

The table compares Dropout and methods that resemble R-Drop in aligning or averaging outputs, from the same viewpoints.

MethodWhat is alignedExtra training costInference cost
Dropoutβ€”None1 pass
R-DropOutput distributions of two sub-models (KL)2Γ— forward and backward1 pass
Fraternal DropoutHidden-layer values of two sub-models (L2)2Γ— forward and backward1 pass
Knowledge distillationOutput distributions of teacher and studentTraining and running the teacher1 pass (student)
MC Dropoutβ€” (uses Dropout at inference too and averages outputs)NoneMultiple passes
Deep ensemblesβ€” (averages outputs of separately trained models)One training run per modelOne pass per model
  • To improve accuracy in a Dropout model without increasing inference cost, R-Drop is an easy choice.
  • If multiple inference passes are acceptable, ensembles are also an option. However, in the paper's appendix, a single model trained with R-Drop (BLEU 37.25) outperformed an ensemble of 6 separately trained Transformers (BLEU 36.92).
  • When training cost cannot grow, combine ordinary Dropout with a cheap regularizer such as Label Smoothing. The paper's translation experiments also use Label Smoothing (0.1) together with R-Drop.

PyTorch example

Show code
python
import torch
import torch.nn as nn
import torch.nn.functional as F


def r_drop_loss(logits1, logits2, target, alpha):
    """Eq. (4): L = NLL(P1) + NLL(P2) + Ξ± Β· 1/2 [KL(P1β€–P2) + KL(P2β€–P1)]"""
    nll = F.cross_entropy(logits1, target) + F.cross_entropy(logits2, target)
    logp1 = F.log_softmax(logits1, dim=-1)
    logp2 = F.log_softmax(logits2, dim=-1)
    # F.kl_div(input, target) computes KL(target β€– input) (pass input as log-probabilities)
    kl_12 = F.kl_div(logp2, logp1, log_target=True, reduction="batchmean")  # KL(P1β€–P2)
    kl_21 = F.kl_div(logp1, logp2, log_target=True, reduction="batchmean")  # KL(P2β€–P1)
    return nll + alpha * 0.5 * (kl_12 + kl_21)


# A model with Dropout (R-Drop is meaningless without Dropout)
model = nn.Sequential(
    nn.Linear(128, 256), nn.ReLU(), nn.Dropout(p=0.3),
    nn.Linear(256, 256), nn.ReLU(), nn.Dropout(p=0.3),
    nn.Linear(256, 10),
)
optimizer = torch.optim.Adam(model.parameters(), lr=1e-3)
alpha = 1.0  # weight of the KL term (choose per task on validation data)

x = torch.randn(32, 128)            # dummy mini-batch
y = torch.randint(0, 10, (32,))

# Training: duplicate the input as [x; x] and run one forward pass. The two halves drop different units
model.train()
logits = model(torch.cat([x, x], dim=0))
logits1, logits2 = logits.chunk(2, dim=0)
loss = r_drop_loss(logits1, logits2, y, alpha)
optimizer.zero_grad()
loss.backward()                     # the KL term's gradient flows into both sub-models
optimizer.step()

# Inference: disable Dropout and compute once
model.eval()
with torch.no_grad():
    predicted = model(x).argmax(dim=-1)

FAQ

Q. How should the KL weight Ξ± be chosen?
A.

Choose it on validation data. The paper uses 5 for translation, one of 0.1, 0.5, and 1.0 for GLUE fine-tuning (1.0 works well for most tasks), 0.7 for summarization, 1.0 for language modeling, and 0.6 for ViT fine-tuning. The paper notes that the best value depends on how prone each task is to overfitting (the size of the data and the model). In the translation experiments, accuracy dropped when Ξ± was either too small or too large.

Q. Are the two forward passes run through separate models?
A.

No. The weights belong to one and the same model; only the units dropped by Dropout differ. In practice, the input is stacked twice along the mini-batch dimension as [x; x], computed in one pass, and the output is split into first and second halves. Dropout draws a random number for each element, so the two halves have different units dropped.

Q. Is there anything to watch out for in the argument order of PyTorch's F.kl_div?
A.

Yes. F.kl_div(input, target) computes KL(target β€– input), and input must be log-probabilities. If target is also passed as log-probabilities, set log_target=True. Since R-Drop sums both directions, mixing up the direction has little effect on the result, but use reduction="batchmean" so the value is per example, matching the cross-entropy.

References

  1. X. Liang, L. Wu, J. Li, Y. Wang, Q. Meng, T. Qin, W. Chen, M. Zhang, and T.-Y. Liu, "R-Drop: Regularized Dropout for Neural Networks," NeurIPS, 2021.
  2. dropreg, "R-Drop" (the paper's implementation, GitHub).
  3. N. Srivastava, G. Hinton, A. Krizhevsky, I. Sutskever, and R. Salakhutdinov, "Dropout: A Simple Way to Prevent Neural Networks from Overfitting," Journal of Machine Learning Research, 15(56), 1929–1958, 2014.
  4. K. Zolna, D. Arpit, D. Suhubdy, and Y. Bengio, "Fraternal Dropout," ICLR, 2018.
  5. PyTorch Documentation, "torch.nn.functional.kl_div."