fairseq_adam.py 5.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148
  1. # Copyright (c) Facebook, Inc. and its affiliates.
  2. #
  3. # This source code is licensed under the MIT license found in the
  4. # LICENSE file in the root directory of this source tree.
  5. import math
  6. import torch
  7. import torch.optim
  8. class FairseqAdam(torch.optim.Optimizer):
  9. r"""Implements Adam algorithm.
  10. This implementation is modified from torch.optim.Adam based on:
  11. `Fixed Weight Decay Regularization in Adam`
  12. (see https://arxiv.org/abs/1711.05101)
  13. It has been proposed in `Adam: A Method for Stochastic Optimization`_.
  14. Args:
  15. params (iterable): iterable of parameters to optimize or dicts defining
  16. parameter groups
  17. lr (float, optional): learning rate (default: 1e-3)
  18. betas (Tuple[float, float], optional): coefficients used for computing
  19. running averages of gradient and its square (default: (0.9, 0.999))
  20. eps (float, optional): term added to the denominator to improve
  21. numerical stability (default: 1e-8)
  22. weight_decay (float, optional): weight decay (L2 penalty) (default: 0)
  23. amsgrad (boolean, optional): whether to use the AMSGrad variant of this
  24. algorithm from the paper `On the Convergence of Adam and Beyond`_
  25. .. _Adam\: A Method for Stochastic Optimization:
  26. https://arxiv.org/abs/1412.6980
  27. .. _On the Convergence of Adam and Beyond:
  28. https://openreview.net/forum?id=ryQu7f-RZ
  29. """
  30. def __init__(
  31. self,
  32. params,
  33. lr=1e-3,
  34. adam_betas=(0.9, 0.999),
  35. adam_eps=1e-8,
  36. weight_decay=0,
  37. amsgrad=False,
  38. ):
  39. defaults = dict(
  40. lr=lr, betas=adam_betas, eps=adam_eps, weight_decay=weight_decay, amsgrad=amsgrad
  41. )
  42. super(FairseqAdam, self).__init__(params, defaults)
  43. self.optimizer_lr = lr
  44. @property
  45. def supports_memory_efficient_fp16(self):
  46. return True
  47. @property
  48. def supports_flat_params(self):
  49. return True
  50. def step(self, closure=None):
  51. """Performs a single optimization step.
  52. Args:
  53. closure (callable, optional): A closure that reevaluates the model
  54. and returns the loss.
  55. """
  56. loss = None
  57. if closure is not None:
  58. loss = closure()
  59. for group in self.param_groups:
  60. for p in group["params"]:
  61. if p.grad is None:
  62. continue
  63. grad = p.grad.data
  64. if grad.dtype in {torch.float16, torch.bfloat16}:
  65. grad = grad.float()
  66. if grad.is_sparse:
  67. raise RuntimeError(
  68. "Adam does not support sparse gradients, please consider SparseAdam instead"
  69. )
  70. amsgrad = group.get("amsgrad", False)
  71. p_data_fp32 = p.data
  72. if p.data.dtype in {torch.float16, torch.bfloat16}:
  73. p_data_fp32 = p_data_fp32.float()
  74. state = self.state[p]
  75. # State initialization
  76. if len(state) == 0:
  77. state["step"] = 0
  78. # Exponential moving average of gradient values
  79. state["exp_avg"] = torch.zeros_like(p_data_fp32)
  80. # Exponential moving average of squared gradient values
  81. state["exp_avg_sq"] = torch.zeros_like(p_data_fp32)
  82. if amsgrad:
  83. # Maintains max of all exp. moving avg. of sq. grad. values
  84. state["max_exp_avg_sq"] = torch.zeros_like(p_data_fp32)
  85. else:
  86. state["exp_avg"] = state["exp_avg"].to(p_data_fp32)
  87. state["exp_avg_sq"] = state["exp_avg_sq"].to(p_data_fp32)
  88. if amsgrad:
  89. state["max_exp_avg_sq"] = state["max_exp_avg_sq"].to(
  90. p_data_fp32
  91. )
  92. exp_avg, exp_avg_sq = state["exp_avg"], state["exp_avg_sq"]
  93. if amsgrad:
  94. max_exp_avg_sq = state["max_exp_avg_sq"]
  95. beta1, beta2 = group["betas"]
  96. state["step"] += 1
  97. # Decay the first and second moment running average coefficient
  98. exp_avg.mul_(beta1).add_(grad, alpha=1 - beta1)
  99. exp_avg_sq.mul_(beta2).addcmul_(grad, grad, value=1 - beta2)
  100. if amsgrad:
  101. # Maintains the maximum of all 2nd moment running avg. till now
  102. torch.max(max_exp_avg_sq, exp_avg_sq, out=max_exp_avg_sq)
  103. # Use the max. for normalizing running avg. of gradient
  104. denom = max_exp_avg_sq.sqrt().add_(group["eps"])
  105. else:
  106. denom = exp_avg_sq.sqrt().add_(group["eps"])
  107. bias_correction1 = 1 - beta1 ** state["step"]
  108. bias_correction2 = 1 - beta2 ** state["step"]
  109. step_size = group["lr"] * math.sqrt(bias_correction2) / bias_correction1
  110. if group["weight_decay"] != 0:
  111. p_data_fp32.add_(
  112. p_data_fp32, alpha=-group["weight_decay"] * group["lr"]
  113. )
  114. p_data_fp32.addcdiv_(exp_avg, denom, value=-step_size)
  115. if p.data.dtype in {torch.float16, torch.bfloat16}:
  116. p.data.copy_(p_data_fp32)
  117. return loss
  118. def set_lr(self, lr):
  119. """Set the learning rate."""
  120. for param_group in self.param_groups:
  121. param_group["lr"] = lr