MCPcopy Create free account
hub / github.com/OpenGVLab/EfficientQAT / NativeScalerWithGradNormCount

Class NativeScalerWithGradNormCount

utils.py:25–51  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

23 return total_norm
24
25class NativeScalerWithGradNormCount:
26 state_dict_key = "amp_scaler"
27
28 def __init__(self):
29 self._scaler = torch.cuda.amp.GradScaler()
30
31 def __call__(self, loss, optimizer, clip_grad=None, parameters=None, create_graph=False, update_grad=True,retain_graph=False):
32 self._scaler.scale(loss).backward(create_graph=create_graph, retain_graph=retain_graph)
33 if update_grad:
34 if clip_grad is not None:
35 assert parameters is not None
36 self._scaler.unscale_(optimizer) # unscale the gradients of optimizer's assigned params in-place
37 norm = torch.nn.utils.clip_grad_norm_(parameters, clip_grad)
38 else:
39 self._scaler.unscale_(optimizer)
40 norm = ampscaler_get_grad_norm(parameters)
41 self._scaler.step(optimizer)
42 self._scaler.update()
43 else:
44 norm = None
45 return norm
46
47 def state_dict(self):
48 return self._scaler.state_dict()
49
50 def load_state_dict(self, state_dict):
51 self._scaler.load_state_dict(state_dict)
52
53
54def create_logger(output_dir, dist_rank=0, name=''):

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected