Adds noise from a standard normal distribution to the gradients. The standard deviation (`sigma`) is controlled by the three hyper-parameters below. `sigma` goes to zero (no noise) with more iterations. Args: model: Model. iteration: Number of iterations. du
(
model: torch.nn.Module,
iteration: int,
duration: float = 100,
eta: float = 1.0,
scale_factor: float = 0.55,
)
| 2 | |
| 3 | |
| 4 | def add_gradient_noise( |
| 5 | model: torch.nn.Module, |
| 6 | iteration: int, |
| 7 | duration: float = 100, |
| 8 | eta: float = 1.0, |
| 9 | scale_factor: float = 0.55, |
| 10 | ): |
| 11 | """Adds noise from a standard normal distribution to the gradients. |
| 12 | |
| 13 | The standard deviation (`sigma`) is controlled |
| 14 | by the three hyper-parameters below. |
| 15 | `sigma` goes to zero (no noise) with more iterations. |
| 16 | |
| 17 | Args: |
| 18 | model: Model. |
| 19 | iteration: Number of iterations. |
| 20 | duration: {100, 1000}: Number of durations to control |
| 21 | the interval of the `sigma` change. |
| 22 | eta: {0.01, 0.3, 1.0}: The magnitude of `sigma`. |
| 23 | scale_factor: {0.55}: The scale of `sigma`. |
| 24 | """ |
| 25 | interval = (iteration // duration) + 1 |
| 26 | sigma = eta / interval**scale_factor |
| 27 | for param in model.parameters(): |
| 28 | if param.grad is not None: |
| 29 | _shape = param.grad.size() |
| 30 | noise = sigma * torch.randn(_shape).to(param.device) |
| 31 | param.grad += noise |
nothing calls this directly
no test coverage detected
searching dependent graphs…