| 451 | |
| 452 | |
| 453 | class FP32Optimizer(MegatronOptimizer): |
| 454 | def __init__( |
| 455 | self, optimizer, clip_grad, log_num_zeros_in_grad, params_have_main_grad |
| 456 | ): |
| 457 | |
| 458 | super(FP32Optimizer, self).__init__( |
| 459 | optimizer, clip_grad, log_num_zeros_in_grad, params_have_main_grad |
| 460 | ) |
| 461 | |
| 462 | self._scale = torch.cuda.FloatTensor([1.0]) |
| 463 | |
| 464 | def zero_grad(self, set_to_none=True): |
| 465 | """Copied from torch.optim.optimizer""" |
| 466 | for group in self.optimizer.param_groups: |
| 467 | _zero_grad_group_helper(group["params"], set_to_none) |
| 468 | |
| 469 | def get_loss_scale(self): |
| 470 | """FP32 optimizer does not do any scaling.""" |
| 471 | return self._scale |
| 472 | |
| 473 | @torch.no_grad() |
| 474 | def step(self): |
| 475 | """Clip gradients (if needed) and step the base optimizer. |
| 476 | Always return successful since there is no overflow.""" |
| 477 | |
| 478 | # Copy main_grads to grads. |
| 479 | if self.params_have_main_grad: |
| 480 | for param_group in self.optimizer.param_groups: |
| 481 | for param in param_group["params"]: |
| 482 | param.grad = param.main_grad |
| 483 | |
| 484 | # Clip gradients. |
| 485 | grad_norm = None |
| 486 | if self.clip_grad > 0.0: |
| 487 | grad_norm = self.clip_grad_norm(self.clip_grad) |
| 488 | |
| 489 | # count the zeros in the grads |
| 490 | num_zeros_in_grad = self.count_zeros() if self.log_num_zeros_in_grad else None |
| 491 | |
| 492 | # Update parameters. |
| 493 | self.optimizer.step() |
| 494 | |
| 495 | # No overflow for FP32 optimizer. |
| 496 | return True, grad_norm, num_zeros_in_grad |
| 497 | |
| 498 | def reload_model_params(self): |
| 499 | pass |
| 500 | |
| 501 | def state_dict(self): |
| 502 | return self.optimizer.state_dict() |
| 503 | |
| 504 | def load_state_dict(self, state_dict): |
| 505 | self.optimizer.load_state_dict(state_dict) |
no outgoing calls
no test coverage detected