Performs a single optimization step. Args: closure (callable, optional): A closure that reevaluates the model and returns the loss.
(self, closure=None)
| 58 | |
| 59 | @torch.no_grad() |
| 60 | def step(self, closure=None): |
| 61 | """Performs a single optimization step. |
| 62 | |
| 63 | Args: |
| 64 | closure (callable, optional): A closure that reevaluates the model |
| 65 | and returns the loss. |
| 66 | """ |
| 67 | loss = None |
| 68 | if closure is not None: |
| 69 | with torch.enable_grad(): |
| 70 | loss = closure() |
| 71 | |
| 72 | for group in self.param_groups: |
| 73 | params_with_grad = [] |
| 74 | grads = [] |
| 75 | exp_avgs = [] |
| 76 | exp_avg_sqs = [] |
| 77 | state_sums = [] |
| 78 | max_exp_avg_sqs = [] |
| 79 | state_steps = [] |
| 80 | amsgrad = group['amsgrad'] |
| 81 | |
| 82 | # put this line here for solving bug |
| 83 | beta1, beta2 = group['betas'] |
| 84 | |
| 85 | for p in group['params']: |
| 86 | if p.grad is None: |
| 87 | continue |
| 88 | params_with_grad.append(p) |
| 89 | if p.grad.is_sparse: |
| 90 | raise RuntimeError('AdamW does not support sparse gradients') |
| 91 | grads.append(p.grad) |
| 92 | |
| 93 | state = self.state[p] |
| 94 | |
| 95 | # State initialization |
| 96 | if len(state) == 0: |
| 97 | state['step'] = 0 |
| 98 | # Exponential moving average of gradient values |
| 99 | state['exp_avg'] = torch.zeros_like(p, memory_format=torch.preserve_format) |
| 100 | # Exponential moving average of squared gradient values |
| 101 | state['exp_avg_sq'] = torch.zeros_like(p, memory_format=torch.preserve_format) |
| 102 | if amsgrad: |
| 103 | # Maintains max of all exp. moving avg. of sq. grad. values |
| 104 | state['max_exp_avg_sq'] = torch.zeros_like(p, memory_format=torch.preserve_format) |
| 105 | |
| 106 | exp_avgs.append(state['exp_avg']) |
| 107 | exp_avg_sqs.append(state['exp_avg_sq']) |
| 108 | |
| 109 | if amsgrad: |
| 110 | max_exp_avg_sqs.append(state['max_exp_avg_sq']) |
| 111 | |
| 112 | |
| 113 | # update the steps for each param group update |
| 114 | state['step'] += 1 |
| 115 | # record the step after step update |
| 116 | state_steps.append(state['step']) |
| 117 |
nothing calls this directly
no outgoing calls
no test coverage detected