MCPcopy Create free account
hub / github.com/coperception/star / NativeScalerWithGradNormCount

Class NativeScalerWithGradNormCount

star/utils/misc.py:251–277  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

249
250
251class NativeScalerWithGradNormCount:
252 state_dict_key = "amp_scaler"
253
254 def __init__(self):
255 self._scaler = torch.cuda.amp.GradScaler()
256
257 def __call__(self, loss, optimizer, clip_grad=None, parameters=None, create_graph=False, update_grad=True):
258 self._scaler.scale(loss).backward(create_graph=create_graph)
259 if update_grad:
260 if clip_grad is not None:
261 assert parameters is not None
262 self._scaler.unscale_(optimizer) # unscale the gradients of optimizer's assigned params in-place
263 norm = torch.nn.utils.clip_grad_norm_(parameters, clip_grad)
264 else:
265 self._scaler.unscale_(optimizer)
266 norm = get_grad_norm_(parameters)
267 self._scaler.step(optimizer)
268 self._scaler.update()
269 else:
270 norm = None
271 return norm
272
273 def state_dict(self):
274 return self._scaler.state_dict()
275
276 def load_state_dict(self, state_dict):
277 self._scaler.load_state_dict(state_dict)
278
279
280def get_grad_norm_(parameters, norm_type: float = 2.0) -> torch.Tensor:

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected