MCPcopy Create free account
hub / github.com/csuhan/OneLLM / NativeScalerWithGradNormCount

Class NativeScalerWithGradNormCount

util/misc.py:310–340  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

308
309
310class NativeScalerWithGradNormCount:
311 state_dict_key = "amp_scaler"
312
313 def __init__(self, args):
314 self._scaler = ShardedGradScaler(enabled=args.precision in ["fp16"])
315
316 def __call__(self, loss, optimizer, model, clip_grad=None, parameters=None, create_graph=False, update_grad=True):
317 if update_grad:
318 self._scaler.scale(loss).backward(create_graph=create_graph)
319 if clip_grad is not None:
320 assert parameters is not None
321 self._scaler.unscale_(optimizer) # unscale the gradients of optimizer's assigned params in-place
322 # norm = torch.nn.utils.clip_grad_norm_(parameters, clip_grad)
323 norm = model.clip_grad_norm_(clip_grad)
324 else:
325 raise NotImplementedError("please set clip_grad to a very large value if you do not want to clip.")
326 self._scaler.unscale_(optimizer)
327 norm = get_grad_norm_(parameters)
328 self._scaler.step(optimizer)
329 self._scaler.update()
330 else:
331 with model.no_sync():
332 self._scaler.scale(loss).backward(create_graph=create_graph)
333 norm = None
334 return norm
335
336 def state_dict(self):
337 return self._scaler.state_dict()
338
339 def load_state_dict(self, state_dict):
340 self._scaler.load_state_dict(state_dict)
341
342
343def 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