Hello,
I am using the flower as an FL framework and I am trying to put DP support by using Opacus.
Here is the problem I meet:
- I am using a very common MNIST model and inherited to get a new class:
# https://github.com/pytorch/examples/blob/main/mnist/main.py
class Net(nn.Module):
def __init__(self) -> None:
super(Net, self).__init__()
self.conv1 = nn.Conv2d(1, 32, 3, 1)
self.conv2 = nn.Conv2d(32, 64, 3, 1)
self.dropout1 = nn.Dropout(0.25)
self.dropout2 = nn.Dropout(0.5)
self.fc1 = nn.Linear(9216, 128)
self.fc2 = nn.Linear(128, 10)
def forward(self, x) -> torch.Tensor:
x = self.conv1(x)
x = F.relu(x)
x = self.conv2(x)
x = F.relu(x)
x = F.max_pool2d(x, 2)
x = self.dropout1(x)
x = torch.flatten(x, 1)
x = self.fc1(x)
x = F.relu(x)
x = self.dropout2(x)
x = self.fc2(x)
output = F.log_softmax(x, dim=1)
return output
class MNISTNet(Net):
"""inheritance from Net (MNIST Model) """
def get_weights(self): #-> List[np.ndarray]:
"""Get model weights as a list of NumPy ndarrays."""
return [val.cpu().numpy() for _, val in self.state_dict().items()]
def set_weights(self, weights: List[np.ndarray]) -> None:
"""Set model weights from a list of NumPy ndarrays.
Parameters
----------
weights: fl.common.Weights
Weights received by the server and set to local model
Returns
-------
"""
state_dict = OrderedDict(
{
k: torch.Tensor(v)
for k, v in zip(self.state_dict().keys(), weights)
}
)
self.load_state_dict(state_dict, strict=True)
Then I simply put the DP protection before training:
model, optimz, train_loader = privacy_engine.make_private(
module = model,
optimizer = optimz,
data_loader = train_loader,
noise_multiplier = 1.0,
max_grad_norm = 1.0,
)
self.model.set_weights(parameters)
<... training ...>
Then an error report is as below:
File "/home/xeniro/prj/flower_framework/client_zone/dp_pytorch_client.py", line 194, in fit
self.model.set_weights(parameters)
File "/home/xeniro/miniconda3/envs/xflwr/lib/python3.10/site-packages/opacus/grad_sample/grad_sample_module.py", line 140, in __getattr__
raise e
File "/home/xeniro/miniconda3/envs/xflwr/lib/python3.10/site-packages/opacus/grad_sample/grad_sample_module.py", line 135, in __getattr__
return super().__getattr__(item)
File "/home/xeniro/miniconda3/envs/xflwr/lib/python3.10/site-packages/torch/nn/modules/module.py", line 1185, in __getattr__
raise AttributeError("'{}' object has no attribute '{}'".format(
AttributeError: 'GradSampleModule' object has no attribute 'set_weights'
Please let me know if there are some available solution.