pytorch-revgrad is a minimalist PyTorch package that provides a gradient reversal layer (GRL) as both a module and a function. This layer is commonly used in domain adaptation techniques, such as Domain-Adversarial Neural Networks (DANN), to encourage feature extractors to learn domain-invariant representations by reversing the gradient signal for a subsequent domain classifier. The current version, `0.2.0`, was released in January 2021, and the library maintains a low release cadence, indicating stability for its core functionality.
pip install pytorch-revgradVerified import paths — ran on the pinned version, not inferred.
This quickstart demonstrates how to integrate `RevGrad` into a simple PyTorch model architecture, typical for domain adaptation. It shows a `FeatureExtractor` and a `DomainClassifier` where `RevGrad` is placed before the classifier's layers to reverse gradients for domain classification.
Ensure the `RevGrad` layer is placed within a sub-network (e.g., a domain classifier) whose parameters are intended to learn from the reversed gradients, and that this sub-network is part of a larger architecture where other parts learn from the normal gradients (e.g., feature extractor).
Be aware of this limitation and potentially exclude `backward` methods of custom autograd functions from coverage reports, or rely on functional correctness tests rather than line-by-line coverage for these specific parts.
Carefully manage graph retention and avoid in-place operations on tensors that require gradients unless explicitly designed for. If `loss.backward()` is called multiple times on the same graph, ensure `retain_graph=True` is used for intermediate calls, or recreate the graph where possible.
Ensure all relevant tensors and the model are moved to the same device (e.g., `model.to(device)`, `input_data.to(device)`) before computation. This applies to `RevGrad` inputs as well.
Review the placement of the `RevGrad` layer. It should typically be positioned after a shared feature extractor and before a domain-specific classifier, allowing the feature extractor to learn from both standard and reversed gradients without immediate instability. Adjust learning rates or add gradient clipping if necessary.
Verify that `requires_grad=True` is set for all tensors whose gradients are needed (e.g., model parameters, or inputs if testing gradient flow). Ensure that operations are not inadvertently enclosed in `torch.no_grad()` if gradients are required for those computations.