MCPcopy Create free account
hub / github.com/AtlasAnalyticsLab/AdaFisher / step

Method step

optimizers/AdamW.py:130–195  ·  view source on GitHub ↗

Performs a single optimization step. Arguments: closure (callable, optional): A closure that reevaluates the model and returns the loss.

(self, closure=None)

Source from the content-addressed store, hash-verified

128
129 @torch.no_grad()
130 def step(self, closure=None):
131 """Performs a single optimization step.
132
133 Arguments:
134 closure (callable, optional): A closure that reevaluates the model
135 and returns the loss.
136 """
137 loss = None
138 if closure is not None:
139 with torch.enable_grad():
140 loss = closure()
141 self.second_moments = []
142
143 for group in self.param_groups:
144 for p in group['params']:
145 if p.grad is None:
146 continue
147 grad = p.grad
148 if grad.is_sparse:
149 raise RuntimeError(
150 'Adam does not support sparse gradients, please consider SparseAdam instead')
151 amsgrad = group['amsgrad']
152
153 state = self.state[p]
154
155 # State initialization
156 if len(state) == 0:
157 state['step'] = 0
158 # Exponential moving average of gradient values
159 state['exp_avg'] = torch.zeros_like(
160 p, memory_format=torch.preserve_format)
161 # Exponential moving average of squared gradient values
162 state['exp_avg_sq'] = torch.zeros_like(
163 p, memory_format=torch.preserve_format)
164 if amsgrad:
165 # Maintains max of all exp. moving avg. of sq. grad. values
166 state['max_exp_avg_sq'] = torch.zeros_like(
167 p, memory_format=torch.preserve_format)
168
169 exp_avg, exp_avg_sq = state['exp_avg'], state['exp_avg_sq']
170 if amsgrad:
171 max_exp_avg_sq = state['max_exp_avg_sq']
172 beta1, beta2 = group['betas']
173
174 state['step'] += 1
175 bias_correction1 = 1 - beta1 ** state['step']
176 bias_correction2 = 1 - beta2 ** state['step']
177
178 # Decay the first and second moment running average coefficient
179 exp_avg.mul_(beta1).add_(grad, alpha=1 - beta1)
180 exp_avg_sq.mul_(beta2).addcmul_(grad, grad, value=1 - beta2)
181 self.second_moments.append(grad * grad)
182 if amsgrad:
183 # Maintains the maximum of all 2nd moment running avg. till now
184 torch.max(max_exp_avg_sq, exp_avg_sq, out=max_exp_avg_sq)
185 # Use the max. for normalizing running avg. of gradient
186 denom = (max_exp_avg_sq.sqrt() /
187 math.sqrt(bias_correction2)).add_(group['eps'])

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected