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

Method step

optimizers/Adam.py:127–194  ·  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

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

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected