Performs a single optimization step. Args: closure (callable, optional): A closure that reevaluates the model and returns the loss.
(self, closure=None)
| 117 | |
| 118 | @torch.no_grad() |
| 119 | def step(self, closure=None): |
| 120 | """Performs a single optimization step. |
| 121 | Args: |
| 122 | closure (callable, optional): A closure that reevaluates the model |
| 123 | and returns the loss. |
| 124 | """ |
| 125 | loss = None |
| 126 | if closure is not None: |
| 127 | with torch.enable_grad(): |
| 128 | loss = closure() |
| 129 | |
| 130 | for group in self.param_groups: |
| 131 | params_with_grad = [] |
| 132 | grads = [] |
| 133 | exp_avgs = [] |
| 134 | exp_avg_sqs = [] |
| 135 | ema_params_with_grad = [] |
| 136 | state_sums = [] |
| 137 | max_exp_avg_sqs = [] |
| 138 | state_steps = [] |
| 139 | amsgrad = group['amsgrad'] |
| 140 | beta1, beta2 = group['betas'] |
| 141 | ema_decay = group['ema_decay'] |
| 142 | ema_power = group['ema_power'] |
| 143 | |
| 144 | for p in group['params']: |
| 145 | if p.grad is None: |
| 146 | continue |
| 147 | params_with_grad.append(p) |
| 148 | if p.grad.is_sparse: |
| 149 | raise RuntimeError('AdamW does not support sparse gradients') |
| 150 | grads.append(p.grad) |
| 151 | |
| 152 | state = self.state[p] |
| 153 | |
| 154 | # State initialization |
| 155 | if len(state) == 0: |
| 156 | state['step'] = 0 |
| 157 | # Exponential moving average of gradient values |
| 158 | state['exp_avg'] = torch.zeros_like(p, memory_format=torch.preserve_format) |
| 159 | # Exponential moving average of squared gradient values |
| 160 | state['exp_avg_sq'] = torch.zeros_like(p, memory_format=torch.preserve_format) |
| 161 | if amsgrad: |
| 162 | # Maintains max of all exp. moving avg. of sq. grad. values |
| 163 | state['max_exp_avg_sq'] = torch.zeros_like(p, memory_format=torch.preserve_format) |
| 164 | # Exponential moving average of parameter values |
| 165 | state['param_exp_avg'] = p.detach().float().clone() |
| 166 | |
| 167 | exp_avgs.append(state['exp_avg']) |
| 168 | exp_avg_sqs.append(state['exp_avg_sq']) |
| 169 | ema_params_with_grad.append(state['param_exp_avg']) |
| 170 | |
| 171 | if amsgrad: |
| 172 | max_exp_avg_sqs.append(state['max_exp_avg_sq']) |
| 173 | |
| 174 | # update the steps for each param group update |
| 175 | state['step'] += 1 |
| 176 | # record the step after step update |
nothing calls this directly
no outgoing calls
no test coverage detected