AI Logic

Semi-Supervised Learning

Virtual Adversarial Training (VAT)

Updated:

Training flow of VAT. The left side shows the overall flow: the cross-entropy on labeled images and the consistency loss LDS on all images are added to update the model. The right side shows the inside: the prediction under the current weights is used as the target, the perturbation that changes the prediction the most is found from a random direction with a single backward pass and added to the image, and the KL divergence between that prediction and the target is taken

Background and Overview

Virtual Adversarial Training (VAT) is a regularization method that adds a small perturbation (noise) near the data in the direction where the model's prediction changes most easily, and trains the model so that its prediction still does not change. It was proposed by Miyato et al. at Kyoto University in 2016, and an extended version with semi-supervised learning experiments was published in 2017.

It builds on adversarial training with adversarial examples. Adversarial training uses the ground-truth label to create a perturbation in "the direction that increases the loss the most" (e.g., FGSM) and trains the model to withstand it. This approach, however, requires ground-truth labels.

Instead of the ground truth, VAT uses the current model's own prediction as a "virtual label". Because it creates the perturbation by searching for "the direction that moves furthest away from the current prediction", it can also be used on unlabeled images. The word "virtual" in the name refers to this virtual label.

As an analogy, other consistency regularization methods check "whether the answer stays the same when the image is lightly shaken in various directions", whereas VAT "finds the one direction in which the answer wobbles most easily and reinforces it there". Unlike data augmentation, there is no need for a person to decide which transformations preserve meaning.

In the paper, "VAT+EntMin", which combines VAT with entropy minimization, achieved the best error rates of the time in semi-supervised learning on SVHN and CIFAR-10. It also lowered error rates as a regularizer in ordinary supervised learning using all labels.

Training Procedure and Loss

The VAT regularization term is defined as follows in Eqs. (5)–(8) of the paper.

LDS(x,θ)=D[ p(y∣x,θ^), p(y∣x+rvadv,θ) ],rvadv=arg⁡max⁡∥r∥2≤ϵD[ p(y∣x,θ^), p(y∣x+r,θ^) ]\mathrm{LDS}(x, \theta) = D\left[\, p(y \mid x, \hat{\theta}),\ p(y \mid x + r_{\mathrm{vadv}}, \theta) \,\right], \qquad r_{\mathrm{vadv}} = \mathop{\arg\max}_{\|r\|_2 \le \epsilon} D\left[\, p(y \mid x, \hat{\theta}),\ p(y \mid x + r, \hat{\theta}) \,\right]

Here p(y∣x,θ)p(y \mid x, \theta) is the class probability output by the model, θ^\hat{\theta} is the current weights (treated as a constant when building the target), DD is the KL divergence, and ϵ\epsilon is the upper bound on the perturbation size. LDS (local distributional smoothness) measures how easily the prediction changes near xx; the smaller it is, the smoother the model.

The training objective is the negative log-likelihood (cross-entropy) ℓ\ell on labeled images plus RvadvR_{\mathrm{vadv}}, the LDS averaged over all labeled and unlabeled images.

ℓ(Dl,θ)+α Rvadv(Dl,Dul,θ)\ell(\mathcal{D}_l, \theta) + \alpha\, R_{\mathrm{vadv}}(\mathcal{D}_l, \mathcal{D}_{ul}, \theta)

The question is how to obtain rvadvr_{\mathrm{vadv}}. Trying to use the direction of the loss gradient as in ordinary adversarial training does not work, because the KL divergence is minimal at r=0r = 0, so its gradient is 0. The paper therefore considers a second-order approximation of the KL divergence (the Hessian) and approximates the direction of its dominant eigenvector with power iteration and finite differences. One training step proceeds in the following order, as in Algorithm 1 of the paper.

  1. Pass the image xx through the model at its current weights to obtain the target prediction p(y∣x,θ^)p(y \mid x, \hat{\theta}).
  2. Draw a random unit vector dd with the same shape as the image from a Gaussian distribution.
  3. Pass x+ξdx + \xi d, scaled by a very small number ξ\xi (10−610^{-6} in the paper), through the model, and differentiate the KL divergence from the target with respect to rr to obtain gg (one backward pass).
  4. Rescale the direction of gg to size ϵ\epsilon to create the perturbation rvadv=ϵ g/∥g∥2r_{\mathrm{vadv}} = \epsilon\, g / \|g\|_2.
  5. Pass x+rvadvx + r_{\mathrm{vadv}} through the model and compute the KL divergence from the target (LDS).
  6. Add the cross-entropy on labeled images and the average LDS, and update the weights.

Steps 3 and 4 correspond to a single iteration (K=1K = 1) of power iteration. Increasing KK improves the approximation, but in the paper's experiments one iteration was sufficient.

The dependence of the perturbation rvadvr_{\mathrm{vadv}} on the weights θ\theta is ignored when differentiating. According to the paper, differentiating through that dependence makes the computation complicated and heavy, and also increases gradient variance and lowers performance. No gradient flows through the target p(y∣x,θ^)p(y \mid x, \hat{\theta}) either; only the prediction on the perturbed image is trained.

Why It Works

The paper explains the effectiveness of VAT in terms of "smoothing by targeting the weakest direction".

  • Labels spread from labeled images along clusters: In the paper's experiment on 2D synthetic data, predictions within the same cluster were inconsistent early in training, and LDS was large at the boundaries. As VAT focused on smoothing points with large LDS, the predictions of nearby labeled points spread across the whole cluster, and the boundaries moved away from dense regions of the data. The paper describes this as similar to label propagation.
  • More efficient than random perturbations: Using perturbations in random directions (called RPT in the paper; power iteration with 0 iterations) smooths uniformly in all directions. VAT smooths only in the direction where the prediction is most sensitive, so it achieves a strong effect with little computation. The paper explains that VAT corresponds to suppressing the largest eigenvalue of the Hessian, while RPT suppresses the sum of eigenvalues.
  • Lower gradient variance: Random directions change greatly each time, whereas the direction found by power iteration converges toward a nearly fixed direction. Gradient variance early in training was smaller with VAT. However, since VAT still outperformed in a comparison with matched variance, the paper concludes that the main reason for its effectiveness lies in the objective itself, which "targets the dominant direction".

Having few hyperparameters is another advantage. Only two need tuning, the perturbation size ϵ\epsilon and the regularization weight α\alpha, and when ϵ\epsilon is small, the regularization strength is determined roughly by αϵ2\alpha \epsilon^2. The paper therefore fixed α=1\alpha = 1 in all experiments and tuned only ϵ\epsilon.

Experimental Results

The paper compared semi-supervised learning on SVHN (1,000 labels) and CIFAR-10 (4,000 labels) (error rate).

MethodSVHN (no aug.)CIFAR-10 (no aug.)SVHN (with aug.)CIFAR-10 (with aug.)
Π-model5.43%16.55%4.82%12.36%
Temporal Ensembling——4.42%12.16%
VAT5.77%14.18%5.42%11.36%
VAT+EntMin4.28%13.15%3.86%10.55%

The VAT values are for the larger convolutional network (Conv-Large) with the same architecture as the Π-model. "With aug." adds translations (plus horizontal flips for CIFAR-10). VAT+EntMin adds a term that reduces the entropy of predictions (making each image's prediction confident), and it had the lowest error rate in every setting. The effect of VAT remained even with augmentation, and the paper argues that the effects of VAT and data augmentation overlap little, so they can be combined.

Compared with RPT, which uses random perturbations, on the same smaller network (Conv-Small), VAT was far better (RPT versus VAT): 8.41% versus 6.83% on SVHN and 18.56% versus 14.87% on CIFAR-10.

Increasing the number of power iterations KK barely changed the CIFAR-10 error rate: 14.18% with K=1K = 1, 14.19% with K=2K = 2, and 14.25% with K=4K = 4.

VAT is also effective in supervised learning with all labels. On MNIST (fully connected network), VAT reached 0.64% compared with 1.11% without regularization. On CIFAR-10, it reached 5.81% compared with 6.67% with dropout alone.

Practical Considerations

The perturbation size ϵ\epsilon is the most important hyperparameter in VAT, and its appropriate value depends on the value range of the data (preprocessing). In the paper's validation, if it was too small the perturbation was invisible and the effect weak; if it was too large, the model was smoothed even over unnatural images far from the originals, the regularization became too strong, and performance dropped. Choose ϵ\epsilon on validation data.

Also keep the following in mind.

  • Computation is about 3 times that of standard training: For unlabeled images, it needs the target prediction, a forward and backward pass on x+ξdx + \xi d, and a forward and backward pass on x+rvadvx + r_{\mathrm{vadv}}. According to the paper, the full gradient including the cross-entropy term can be obtained with K+2K + 2 backward passes.
  • K=1K = 1 is not always enough: One power iteration was sufficient in the paper's experiments, but the paper itself cautions that "depending on the data and model, one iteration may not be enough".
  • Watch the batch normalization statistics: If perturbed images are passed through the model in training mode, the running averages of batch normalization are also updated with the perturbed images. The code below avoids updating the running averages while perturbed images are being passed through.
  • Entropy minimization is a separate term: The paper's best results come from VAT plus entropy minimization. When comparing with VAT-only results, check which value is being reported.

Comparison with Other Semi-Supervised Methods

Semi-supervised methods based on consistency regularization compare as follows in terms of "under what change the prediction is kept the same".

MethodTarget predictionPrediction being trained (how the input is changed)Distance between predictionsTransformations designed by hand
Π-modelPrediction from the same model with different noiseAugmentation and dropoutSquared errorTypes of augmentation
Mean TeacherPrediction of the model with exponentially averaged weightsAugmentation and dropoutSquared errorTypes of augmentation
VATPrediction on the unperturbed imageSmall perturbation in the direction that changes the prediction mostKL divergenceOnly the perturbation size ϵ\epsilon
UDAPrediction on the unaugmented image (sharpened)Strong data augmentationKL divergenceTypes of strong augmentation
FixMatchPrediction on weak augmentation (one-hot if above a threshold)Strong augmentationCross-entropyTypes of weak and strong augmentation

Guidelines for choosing:

  • Data for which label-preserving augmentations are hard to define: VAT only adds small perturbations to input values, so it is easy to apply to data other than images. There is no need to design augmentation types.
  • Images with good augmentations available: Methods that use strong data augmentation, such as UDA and FixMatch, achieve high accuracy when labels are scarce. The UDA paper states that the essential difference from VAT is only how the noise is generated, shows that UDA outperformed VAT under every label count, and explains that VAT noise tends to contain fine patterns not found in real images, whereas data augmentation can produce diverse, natural images.
  • As a regularizer for supervised learning: VAT can also be used when all labels are available. If the goal is robustness to adversarial noise itself, adversarial training with PGD or TRADES is a better fit.

PyTorch example

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

"""
VAT regularization term LDS (following Eqs. (5)(6)(14)(15) and Algorithm 1 of the paper, with K power iterations)
"""


@contextlib.contextmanager
def freeze_bn_stats(model):
  """Do not update batch norm running averages on perturbed images"""
  saved = {}
  for m in model.modules():
    if isinstance(m, nn.modules.batchnorm._BatchNorm):
      saved[m] = m.momentum
      m.momentum = 0.0
  yield
  for m, mom in saved.items():
    m.momentum = mom


def l2_normalize(d):
  return d / (d.flatten(1).norm(dim=1).view(-1, *([1] * (d.dim() - 1))) + 1e-12)


def vat_loss(model, x, eps=8.0, xi=1e-6, K=1):
  # 1. target: prediction p(y|x, θ^) under the current weights. No gradient
  with torch.no_grad():
    p = model(x).softmax(dim=1)

  with freeze_bn_stats(model):
    # 2. random unit vector d
    d = l2_normalize(torch.randn_like(x))
    # 3. power iteration: replace d with the direction g of the gradient of KL at x + ξd with respect to r
    for _ in range(K):
      d = (xi * d).requires_grad_()
      log_q = model(x + d).log_softmax(dim=1)
      dist = F.kl_div(log_q, p, reduction="batchmean")      # KL(p || q)
      g = torch.autograd.grad(dist, d)[0]
      d = l2_normalize(g.detach())
    # 4. perturbation r_vadv = ε g / ||g|| (already detached, since the dependence on θ is ignored)
    r_vadv = eps * d
    # 5. LDS: pull the prediction on the perturbed image toward the target (gradient flows here)
    log_q = model(x + r_vadv).log_softmax(dim=1)
    return F.kl_div(log_q, p, reduction="batchmean")


# One training step (paper settings: α = 1, ε chosen on validation data, Adam)
def train_step(model, optimizer, x_l, y_l, x_ul, alpha=1.0, eps=8.0):
  model.train()
  loss_s = F.cross_entropy(model(x_l), y_l)               # cross-entropy on labeled images
  loss_u = vat_loss(model, torch.cat([x_l, x_ul]), eps)   # LDS on both labeled and unlabeled images
  loss = loss_s + alpha * loss_u
  optimizer.zero_grad()
  loss.backward()
  optimizer.step()
  return loss.item()

FAQ

Q. How does it differ from ordinary adversarial training?
A.

Ordinary adversarial training creates the perturbation in the direction that most increases the loss with respect to the ground-truth label, so it requires labels. VAT uses the current model's prediction as a virtual label and creates the perturbation in the direction that moves furthest from that prediction, so it can also be used on unlabeled images. In the paper's MNIST experiments, even with all labels, VAT (0.64% error) outperformed adversarial training constrained by the L2 norm (0.71%).

Q. How large should the perturbation size $\epsilon$ be?
A.

It depends on input preprocessing, so choose it on validation data. In the paper's semi-supervised validation (with ZCA-whitened inputs for CIFAR-10), the best results were at ϵ=3.0\epsilon = 3.0 for SVHN and ϵ=8.0\epsilon = 8.0 for CIFAR-10. At that setting, the perturbed CIFAR-10 images were degraded to the point of being barely recognizable. Larger values gradually lowered performance.

Q. Why is the KL divergence used as the distance to the target?
A.

In the paper, VAT's LDS is defined using the KL divergence as a measure of how much the predicted probability distribution changes. The perturbation direction is also found as the direction that maximizes this KL divergence. The key to VAT's computation is using the property that the KL divergence and its gradient are 0 at r=0r = 0 to find the direction from a second-order approximation (the Hessian).

References

  1. Miyato, T., Maeda, S., Koyama, M., & Ishii, S. Virtual Adversarial Training: A Regularization Method for Supervised and Semi-Supervised Learning. IEEE Transactions on Pattern Analysis and Machine Intelligence. arXiv:1704.03976.
  2. Miyato, T., Maeda, S., Koyama, M., Nakae, K., & Ishii, S. (2016). Distributional Smoothing with Virtual Adversarial Training. International Conference on Learning Representations (ICLR 2016).
  3. Goodfellow, I. J., Shlens, J., & Szegedy, C. (2015). Explaining and Harnessing Adversarial Examples. International Conference on Learning Representations (ICLR 2015).