Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Update model_maintainer.py #338

Merged
merged 1 commit into from
Nov 6, 2023
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 15 additions & 1 deletion fedlab/core/model_maintainer.py
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,20 @@ def model_parameters(self) -> torch.Tensor:
"""Return serialized model parameters."""
return SerializationTool.serialize_model(self._model)

@property
def model_grads(self) -> torch.Tensor:
"""Return serialized model gradients(base on model.state_dict(), Shape is the same as model_parameters)."""
params = self._model.state_dict()
for name, p in self._model.named_parameters():
params[name].grad = p.grad
for key in params:
if params[key].grad is None:
params[key].grad = torch.zeros_like(params[key])
gradients = [param.grad.data.view(-1) for param in params.values()]
m_gradients = torch.cat(gradients)
m_gradients = m_gradients.cpu()
return m_gradients

@property
def model_gradients(self) -> torch.Tensor:
"""Return serialized model gradients."""
Expand Down Expand Up @@ -117,4 +131,4 @@ def set_model(self, parameters: torch.Tensor = None, id: int = None):
if id is None:
super().set_model(parameters)
else:
super().set_model(self.parameters[id])
super().set_model(self.parameters[id])
Loading