AI Logic

Domain Adaptation

DANN (Gradient Reversal)

Updated:

Training flow of DANN. Left: source and target images pass through the feature extractor, which branches into the label predictor and, through the gradient reversal layer, the domain classifier. Right: what the gradient reversal layer does in the forward and backward passes, and a graph of λ increasing from 0 to 1

Background and overview

DANN (Domain-Adversarial Neural Network) is a domain adaptation method that makes a model trained on labeled data (the source) usable on unlabeled data with different characteristics (the target). Ganin and Lempitsky proposed it in 2015, and a paper with additional theory and experiments was published in JMLR in 2016.

For example, synthetic digit images (the source) may have plenty of labels while real photos of digits (the target) have none. A model trained only on the source and applied directly to the target loses much of its accuracy because of differences such as background and color (domain shift).

DANN addresses this by learning features from which it cannot be told which domain the image came from. The idea is that if features cannot be distinguished between source and target, a classifier learned on the source should work on the target as is. Domain adaptation theory (the results of Ben-David et al.), which states that the smaller the difference between the two domains, the smaller the upper bound on target error, supports this idea.

To do this, DANN adds a "domain classifier" that predicts the domain from the features and performs adversarial training: the classifier tries to tell the domains apart, while the feature extractor tries to make them indistinguishable. This resembles the relationship between the generator and discriminator of a GAN, but DANN's distinguishing feature is that it achieves this within ordinary backpropagation simply by inserting a single layer, the gradient reversal layer. For this reason, "gradient reversal," as in the title, is used almost as another name for the method.

Network structure and the gradient reversal layer

As in Figure 1 of the paper, the DANN network consists of three parts.

  1. Feature extractor GfG_f (parameters θf\theta_f): maps the input x\boldsymbol{x} to features f\boldsymbol{f}. Both source and target images pass through it.
  2. Label predictor GyG_y (parameters θy\theta_y): predicts the class from the features. The loss is computed only on labeled source images.
  3. Domain classifier GdG_d (parameters θd\theta_d): predicts from the features whether an image is from the source or the target (di=0d_i = 0 or 11). The loss is computed on all images. A gradient reversal layer sits between it and the feature extractor.

The training objective is written as follows.

E(θf,θy,θd)=∑i: di=0Lyi(θf,θy)  −  λ∑i=1NLdi(θf,θd)E(\theta_f, \theta_y, \theta_d) = \sum_{i:\,d_i = 0} L_y^i(\theta_f, \theta_y) \;-\; \lambda \sum_{i=1}^{N} L_d^i(\theta_f, \theta_d)

Here, LyiL_y^i is the class loss of the ii-th image (e.g., multiclass cross-entropy), LdiL_d^i is the domain loss (binary cross-entropy), and λ\lambda is a coefficient that balances the two losses. DANN seeks a saddle point of this EE.

(θ^f,θ^y)=arg⁡min⁡θf,θyE(θf,θy,θ^d),θ^d=arg⁡max⁡θdE(θ^f,θ^y,θd)(\hat{\theta}_f, \hat{\theta}_y) = \arg\min_{\theta_f, \theta_y} E(\theta_f, \theta_y, \hat{\theta}_d), \qquad \hat{\theta}_d = \arg\max_{\theta_d} E(\hat{\theta}_f, \hat{\theta}_y, \theta_d)

In other words, the domain classifier θd\theta_d moves to decrease the domain loss (increase EE), while the feature extractor θf\theta_f moves to decrease the class loss and increase the domain loss.

The gradient reversal layer RλR_\lambda performs this "decrease one, increase the other" in a single backward pass.

Rλ(x)=x,dRλdx=−λIR_\lambda(\boldsymbol{x}) = \boldsymbol{x}, \qquad \frac{dR_\lambda}{d\boldsymbol{x}} = -\lambda \boldsymbol{I}

In the forward pass it passes the input through unchanged; in the backward pass it multiplies the incoming gradient by −λ-\lambda before passing it to the previous layer (I\boldsymbol{I} is the identity matrix). The domain classifier itself is updated normally to lower the domain loss, but the feature extractor before the gradient reversal layer receives a gradient pointing in the opposite direction. As a result, the feature extractor is updated in the direction that "makes domains harder to tell apart."

The gradient reversal layer has no learnable parameters and takes only a few lines to write. Any existing classification model becomes DANN by attaching a gradient reversal layer and a domain classifier to its feature output. At inference, only the feature extractor and the label predictor are used.

Training setup and results

In the paper, the weight λ\lambda of the domain loss starts at 0 at the beginning of training and gradually approaches 1.

λp=21+exp⁡(−γ⋅p)−1\lambda_p = \frac{2}{1 + \exp(-\gamma \cdot p)} - 1

Here, pp is the training progress (increasing linearly from 0 to 1) and γ\gamma controls how fast it rises; γ=10\gamma = 10 in all experiments. Early in training, the features are not yet useful and the domain classifier's signal is close to noise, so its influence is suppressed.

The learning rate μp\mu_p is also lowered as training progresses.

μp=μ0(1+α⋅p)β,μ0=0.01, α=10, β=0.75\mu_p = \frac{\mu_0}{(1 + \alpha \cdot p)^\beta}, \qquad \mu_0 = 0.01,\ \alpha = 10,\ \beta = 0.75

Optimization uses SGD with momentum 0.9 and a batch size of 128 (half source images, half target images).

Because training is adversarial, it becomes unstable if λ\lambda is too large or the domain classifier is too strong or too weak. In addition, DANN aligns the distribution of the features as a whole, which does not guarantee that the per-class distributions are aligned. When class proportions differ greatly between source and target, for example, aligning the features can actually shift the class boundaries.

The results of the digit and traffic sign experiments in the 2015 paper (ICML), measured as accuracy on the unlabeled target, are shown below. The values in parentheses indicate how much of the gap between "no adaptation" and "the upper bound trained with target labels" was closed.

Source → TargetNo adaptationDANNTrained on target (upper bound)
MNIST → MNIST-M0.57490.8149 (57.9%)0.9891
Synthetic digits → SVHN0.86650.9048 (66.1%)0.9244
SVHN → MNIST0.59190.7107 (29.3%)0.9951
Synthetic signs → GTSRB0.74000.8866 (56.7%)0.9987

MNIST-M blends MNIST digits with patches of natural images, giving data with varied backgrounds and colors.

Comparison with other domain adaptation methods

Domain adaptation methods in deep learning can be compared by "what they align in the features of the two domains, and how."

MethodWhat is alignedHowFeature extractor
DDCFeature distribution of one layerAdd MMD (the difference between the means of the two distributions) to the lossShared between the two domains
DANFeature distributions of multiple layersAdd multi-kernel MMD to the lossShared
Deep CORALSecond-order statistics of the features (covariance)Add the covariance difference to the lossShared
DANNFeature distributionAdversarial training with a domain classifier and a gradient reversal layerShared
ADDAFeature distributionAdversarial training with the GAN loss. Fixes the extractor trained on the source and trains a separate extractor for the targetSeparate per domain

Methods that "compute a distance directly," such as MMD and CORAL, tend to train stably, but they align only the chosen statistics. Adversarial methods such as DANN and ADDA try to reduce any difference the classifier can detect, which makes them more expressive, but their training stability needs care.

PyTorch example

Show code
python
import math
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from torchvision import datasets, transforms
from torch.utils.data import DataLoader
from tqdm import tqdm

"""
Domain adaptation from MNIST (source, labeled) to USPS (target, unlabeled).
USPS labels are used only for evaluation
"""

# Hyperparameters (λ and learning rate schedules follow the paper)
batch_size = 64       # batch size for each of source and target
epochs = 10           # number of epochs
mu0, alpha, beta = 0.01, 10, 0.75   # learning rate μp = μ0 / (1 + α p)^β
gamma = 10            # λp = 2 / (1 + exp(-γ p)) - 1

device = 'cuda' if torch.cuda.is_available() else 'mps' if torch.backends.mps.is_available() else 'cpu'

transform = transforms.Compose([
  transforms.Resize(28),  # USPS is 16×16, so resize to match MNIST
  transforms.ToTensor(),
  transforms.Normalize((0.5,), (0.5,))
])
source = datasets.MNIST(root='./data', train=True, download=True, transform=transform)
target = datasets.USPS(root='./data', train=True, download=True, transform=transform)
target_test = datasets.USPS(root='./data', train=False, download=True, transform=transform)
source_loader = DataLoader(source, batch_size=batch_size, shuffle=True, drop_last=True)
target_loader = DataLoader(target, batch_size=batch_size, shuffle=True, drop_last=True)
test_loader = DataLoader(target_test, batch_size=256)


# Gradient reversal layer: identity in the forward pass, multiplies the gradient by -λ in the backward pass
class GradReverse(torch.autograd.Function):
  @staticmethod
  def forward(ctx, x, lam):
    ctx.lam = lam
    return x.view_as(x)

  @staticmethod
  def backward(ctx, grad_output):
    return -ctx.lam * grad_output, None


class DANN(nn.Module):
  def __init__(self):
    super().__init__()
    self.features = nn.Sequential(        # feature extractor G_f
      nn.Conv2d(1, 32, 5), nn.ReLU(), nn.MaxPool2d(2),
      nn.Conv2d(32, 48, 5), nn.ReLU(), nn.MaxPool2d(2),
      nn.Flatten(),                       # [B, 48 * 4 * 4]
    )
    self.label_predictor = nn.Sequential( # label predictor G_y
      nn.Linear(48 * 4 * 4, 100), nn.ReLU(),
      nn.Linear(100, 10),
    )
    self.domain_classifier = nn.Sequential(  # domain classifier G_d
      nn.Linear(48 * 4 * 4, 100), nn.ReLU(),
      nn.Linear(100, 1),                  # source (0) or target (1)
    )

  def forward(self, x, lam=0.0):
    f = self.features(x)
    return self.label_predictor(f), self.domain_classifier(GradReverse.apply(f, lam))


model = DANN().to(device)
optimizer = optim.SGD(model.parameters(), lr=mu0, momentum=0.9)

total_steps = epochs * min(len(source_loader), len(target_loader))
step = 0
for epoch in tqdm(range(epochs)):
  model.train()
  for (xs, ys), (xt, _) in zip(source_loader, target_loader):
    p = step / total_steps                       # training progress (0→1)
    lam = 2 / (1 + math.exp(-gamma * p)) - 1
    for group in optimizer.param_groups:
      group['lr'] = mu0 / (1 + alpha * p) ** beta

    xs, ys, xt = xs.to(device), ys.to(device), xt.to(device)
    x = torch.cat([xs, xt])
    d = torch.cat([torch.zeros(len(xs)), torch.ones(len(xt))]).to(device)

    class_logits, domain_logits = model(x, lam)
    loss_y = F.cross_entropy(class_logits[:len(xs)], ys)           # source only
    loss_d = F.binary_cross_entropy_with_logits(domain_logits.squeeze(1), d)  # all images
    loss = loss_y + loss_d   # λ is applied inside the gradient reversal layer

    optimizer.zero_grad()
    loss.backward()
    optimizer.step()
    step += 1

# Evaluate on the target (USPS) test data
model.eval()
correct = 0
total = 0
with torch.no_grad():
  for images, labels in test_loader:
    images, labels = images.to(device), labels.to(device)
    predicted = model(images)[0].argmax(dim=1)
    total += labels.size(0)
    correct += (predicted == labels).sum().item()

print(f"Target Accuracy: {100 * correct / total:.2f}%")

FAQ

Q. Can't I just add −λL_d to the loss instead of using a gradient reversal layer?
A.

Then the domain classifier would also be updated to increase the domain loss, and it would never learn to discriminate. In DANN, the classifier must decrease the domain loss while only the feature extractor increases it. The gradient reversal layer achieves this in a single backward pass by sending the reversed gradient only to the layers before the classifier.

Q. Are no target labels needed at all?
A.

None are needed for training. DANN is an "unsupervised domain adaptation" method in which the target has no labels at all. However, having a few target labels for evaluation is reassuring for choosing hyperparameters and checking whether adaptation worked.

Q. Can it be used for data other than images?
A.

Yes. The gradient reversal layer and domain classifier can be attached to any network that produces features. Besides image classification, the JMLR paper also applies it to document sentiment analysis (adaptation between product categories) and person re-identification.

References

  1. Ganin, Y., & Lempitsky, V. (2015). Unsupervised Domain Adaptation by Backpropagation. Proceedings of the 32nd International Conference on Machine Learning (ICML), PMLR 37, 1180–1189.
  2. Ganin, Y., Ustinova, E., Ajakan, H., Germain, P., Larochelle, H., Laviolette, F., Marchand, M., & Lempitsky, V. (2016). Domain-Adversarial Training of Neural Networks. Journal of Machine Learning Research, 17(59), 1–35.
  3. Tzeng, E., Hoffman, J., Zhang, N., Saenko, K., & Darrell, T. (2014). Deep Domain Confusion: Maximizing for Domain Invariance. arXiv:1412.3474.
  4. Long, M., Cao, Y., Wang, J., & Jordan, M. I. (2015). Learning Transferable Features with Deep Adaptation Networks. ICML 2015.
  5. Sun, B., & Saenko, K. (2016). Deep CORAL: Correlation Alignment for Deep Domain Adaptation. ECCV 2016 Workshops.
  6. Tzeng, E., Hoffman, J., Saenko, K., & Darrell, T. (2017). Adversarial Discriminative Domain Adaptation. CVPR 2017.