Opacus requires that the nn.Module used in your training loop consists of supported components. A module is considered supported if it meets one of the following criteria:
- No trainable parameters: Modules like
nn.ReLU or nn.Tanh. - Frozen modules: Any module where all parameters have
requires_grad = False. - Explicitly supported modules: Specific implementations like
nn.Conv2d (check the grad_sample/ directory for the list of explicitly supported modules). - Composite modules: Any complex
nn.Module that is composed entirely of the supported modules listed above.
Note that compatibility depends on the underlying implementation. For example, a module might be logically equivalent to a supported one but use different internal operators that are not yet supported.
class SampleConvNet(nn.Module):
def __init__(self):
super().__init__()
self.conv1 = nn.Conv2d(1, 16, 8, 2, padding=3)
self.conv2 = nn.Conv2d(16, 32, 4, 2)
self.fc1 = nn.Linear(32 * 4 * 4, 32)
self.fc2 = nn.Linear(32, 10)
def forward(self, x):
# x of shape [B, 1, 28, 28]
x = F.relu(self.conv1(x)) # -> [B, 16, 14, 14]
x = F.max_pool2d(x, 2, 1) # -> [B, 16, 13, 13]
x = F.relu(self.conv2(x)) # -> [B, 32, 5, 5]
x = F.max_pool2d(x, 2, 1) # -> [B, 32, 4, 4]
x = x.view(-1, 32 * 4 * 4) # -> [B, 512]
x = F.relu(self.fc1(x)) # -> [B, 32]
x = self.fc2(x) # -> [B, 10]
return x