nadamw.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410
  1. """ NAdamW Optimizer
  2. Based on simplified algorithm in https://github.com/mlcommons/algorithmic-efficiency/tree/main/baselines/nadamw
  3. Added multi-tensor (foreach) path.
  4. References for added functionality:
  5. Cautious Optimizers: https://arxiv.org/abs/2411.16085
  6. Why Gradients Rapidly Increase Near the End of Training: https://arxiv.org/abs/2506.02285
  7. """
  8. import math
  9. from typing import List, Optional, Tuple
  10. import torch
  11. from torch import Tensor
  12. from ._types import ParamsT
  13. # Modified from github.com/pytorch/pytorch/blob/v1.12.1/torch/optim/adamw.py.
  14. class NAdamW(torch.optim.Optimizer):
  15. """ Implements NAdamW algorithm.
  16. See Table 1 in https://arxiv.org/abs/1910.05446 for the implementation of
  17. the NAdam algorithm (there is also a comment in the code which highlights
  18. the only difference of NAdamW and AdamW).
  19. For further details regarding the algorithm we refer to
  20. - Decoupled Weight Decay Regularization: https://arxiv.org/abs/1711.05101
  21. - On the Convergence of Adam and Beyond: https://openreview.net/forum?id=ryQu7f-RZ
  22. Args:
  23. params: iterable of parameters to optimize or dicts defining parameter groups
  24. lr: learning rate
  25. betas: coefficients used for computing running averages of gradient and its square
  26. eps: term added to the denominator to improve numerical stability
  27. weight_decay: weight decay coefficient
  28. caution: enable caution
  29. corrected_weight_decay: apply corrected weight decay (lr**2 / max_lr)
  30. """
  31. def __init__(
  32. self,
  33. params: ParamsT,
  34. lr: float = 1e-3,
  35. betas: Tuple[float, float] = (0.9, 0.999),
  36. eps: float = 1e-8,
  37. weight_decay: float = 1e-2,
  38. caution: bool = False,
  39. corrected_weight_decay: bool = False,
  40. maximize: bool = False,
  41. foreach: Optional[bool] = None,
  42. capturable: bool = False,
  43. ):
  44. if not 0.0 <= lr:
  45. raise ValueError(f'Invalid learning rate: {lr}')
  46. if not 0.0 <= eps:
  47. raise ValueError(f'Invalid epsilon value: {eps}')
  48. if not 0.0 <= betas[0] < 1.0:
  49. raise ValueError(f'Invalid beta parameter at index 0: {betas[0]}')
  50. if not 0.0 <= betas[1] < 1.0:
  51. raise ValueError(f'Invalid beta parameter at index 1: {betas[1]}')
  52. if not 0.0 <= weight_decay:
  53. raise ValueError(f'Invalid weight_decay value: {weight_decay}')
  54. defaults = dict(
  55. lr=lr,
  56. betas=betas,
  57. eps=eps,
  58. weight_decay=weight_decay,
  59. caution=caution,
  60. corrected_weight_decay=corrected_weight_decay,
  61. foreach=foreach,
  62. maximize=maximize,
  63. capturable=capturable,
  64. )
  65. super().__init__(params, defaults)
  66. def __setstate__(self, state):
  67. super().__setstate__(state)
  68. state_values = list(self.state.values())
  69. step_is_tensor = (len(state_values) != 0) and torch.is_tensor(state_values[0]['step'])
  70. if not step_is_tensor:
  71. for s in state_values:
  72. s['step'] = torch.tensor(float(s['step']))
  73. for group in self.param_groups:
  74. group.setdefault('caution', False)
  75. group.setdefault('corrected_weight_decay', False)
  76. @torch.no_grad()
  77. def step(self, closure=None):
  78. """Performs a single optimization step.
  79. Args:
  80. closure (callable, optional): A closure that reevaluates the model
  81. and returns the loss.
  82. """
  83. self._cuda_graph_capture_health_check()
  84. loss = None
  85. if closure is not None:
  86. with torch.enable_grad():
  87. loss = closure()
  88. for group in self.param_groups:
  89. params_with_grad = []
  90. grads = []
  91. exp_avgs = []
  92. exp_avg_sqs = []
  93. state_steps = []
  94. beta1, beta2 = group['betas']
  95. for p in group['params']:
  96. if p.grad is None:
  97. continue
  98. params_with_grad.append(p)
  99. if p.grad.is_sparse:
  100. raise RuntimeError('NAdamW does not support sparse gradients')
  101. grads.append(p.grad)
  102. state = self.state[p]
  103. # State initialization
  104. if len(state) == 0:
  105. state['step'] = torch.tensor(0.)
  106. # Exponential moving average of gradient values
  107. state['exp_avg'] = torch.zeros_like(p, memory_format=torch.preserve_format)
  108. # Exponential moving average of squared gradient values
  109. state['exp_avg_sq'] = torch.zeros_like(p, memory_format=torch.preserve_format)
  110. exp_avgs.append(state['exp_avg'])
  111. exp_avg_sqs.append(state['exp_avg_sq'])
  112. state_steps.append(state['step'])
  113. nadamw(
  114. params_with_grad,
  115. grads,
  116. exp_avgs,
  117. exp_avg_sqs,
  118. state_steps,
  119. beta1=beta1,
  120. beta2=beta2,
  121. lr=group['lr'],
  122. weight_decay=group['weight_decay'],
  123. eps=group['eps'],
  124. caution=group['caution'],
  125. maximize=group['maximize'],
  126. capturable=group['capturable'],
  127. max_lr=self.defaults['lr'] if group['corrected_weight_decay'] else None,
  128. )
  129. return loss
  130. def nadamw(
  131. params: List[Tensor],
  132. grads: List[Tensor],
  133. exp_avgs: List[Tensor],
  134. exp_avg_sqs: List[Tensor],
  135. state_steps: List[Tensor],
  136. foreach: Optional[bool] = None,
  137. capturable: bool = False,
  138. *,
  139. beta1: float,
  140. beta2: float,
  141. lr: float,
  142. weight_decay: float,
  143. eps: float,
  144. caution: bool,
  145. maximize: bool,
  146. max_lr: Optional[float],
  147. ) -> None:
  148. r"""Functional API that performs NAdamW algorithm computation.
  149. See NAdamW class for details.
  150. """
  151. if not all(isinstance(t, torch.Tensor) for t in state_steps):
  152. raise RuntimeError(
  153. 'API has changed, `state_steps` argument must contain a list of' +
  154. ' singleton tensors')
  155. if foreach is None:
  156. try:
  157. # cannot do foreach if this overload doesn't exist when caution enabled
  158. foreach = not caution or 'Scalar' in torch.ops.aten._foreach_maximum_.overloads()
  159. except Exception:
  160. foreach = False
  161. if foreach and not torch.jit.is_scripting():
  162. func = _multi_tensor_nadamw
  163. else:
  164. func = _single_tensor_nadamw
  165. func(
  166. params,
  167. grads,
  168. exp_avgs,
  169. exp_avg_sqs,
  170. state_steps,
  171. beta1=beta1,
  172. beta2=beta2,
  173. lr=lr,
  174. weight_decay=weight_decay,
  175. eps=eps,
  176. caution=caution,
  177. maximize=maximize,
  178. capturable=capturable,
  179. max_lr=max_lr,
  180. )
  181. def _single_tensor_nadamw(
  182. params: List[Tensor],
  183. grads: List[Tensor],
  184. exp_avgs: List[Tensor],
  185. exp_avg_sqs: List[Tensor],
  186. state_steps: List[Tensor],
  187. *,
  188. beta1: float,
  189. beta2: float,
  190. lr: float,
  191. weight_decay: float,
  192. eps: float,
  193. caution: bool,
  194. maximize: bool,
  195. capturable: bool,
  196. max_lr: Optional[float],
  197. ):
  198. for i, param in enumerate(params):
  199. grad = grads[i] if not maximize else -grads[i]
  200. exp_avg = exp_avgs[i]
  201. exp_avg_sq = exp_avg_sqs[i]
  202. step_t = state_steps[i]
  203. # Update step.
  204. step_t += 1
  205. # Perform stepweight decay.
  206. wd_scale = lr if max_lr is None else lr ** 2 / max_lr
  207. param.mul_(1. - wd_scale * weight_decay)
  208. # Decay the first and second moment running average coefficient.
  209. exp_avg.mul_(beta1).add_(grad, alpha=1 - beta1)
  210. exp_avg_sq.mul_(beta2).addcmul_(grad, grad, value=1 - beta2)
  211. if capturable:
  212. step = step_t
  213. # 1 - beta1 ** step can't be captured in a CUDA graph, even if step is a CUDA tensor
  214. # (incurs "RuntimeError: CUDA error: operation not permitted when stream is capturing")
  215. bias_correction1 = 1 - torch.pow(beta1, step)
  216. bias_correction2 = 1 - torch.pow(beta2, step)
  217. step_size = lr / bias_correction1
  218. step_size_neg = step_size.neg()
  219. bias_correction2_sqrt = bias_correction2.sqrt()
  220. # Only difference between NAdamW and AdamW in this implementation.
  221. # The official PyTorch implementation of NAdam uses a different algorithm.
  222. exp_avg = exp_avg.mul(beta1).add_(grad, alpha=1 - beta1)
  223. denom = (exp_avg_sq.sqrt() / (bias_correction2_sqrt * step_size_neg)).add_(eps / step_size_neg)
  224. if caution:
  225. # Apply caution as per 'Cautious Optimizers' - https://arxiv.org/abs/2411.16085
  226. # FIXME not 100% sure if this remains capturable?
  227. mask = (exp_avg * grad > 0).to(grad.dtype)
  228. mask.div_(mask.mean().clamp_(min=1e-3))
  229. exp_avg.mul_(mask)
  230. param.addcdiv_(exp_avg, denom)
  231. else:
  232. step = step_t.item()
  233. bias_correction1 = 1 - beta1 ** step
  234. bias_correction2 = 1 - beta2 ** step
  235. step_size = lr / bias_correction1
  236. bias_correction2_sqrt = math.sqrt(bias_correction2)
  237. # Apply Nesterov. Only difference between NAdamW and AdamW in this implementation.
  238. # The official PyTorch implementation of NAdam uses a different algorithm.
  239. exp_avg = exp_avg.mul(beta1).add_(grad, alpha=1 - beta1)
  240. denom = (exp_avg_sq.sqrt() / bias_correction2_sqrt).add_(eps)
  241. if caution:
  242. # Apply caution as per 'Cautious Optimizers' - https://arxiv.org/abs/2411.16085
  243. mask = (exp_avg * grad > 0).to(grad.dtype)
  244. mask.div_(mask.mean().clamp_(min=1e-3))
  245. exp_avg.mul_(mask)
  246. param.addcdiv_(exp_avg, denom, value=-step_size)
  247. def _multi_tensor_nadamw(
  248. params: List[Tensor],
  249. grads: List[Tensor],
  250. exp_avgs: List[Tensor],
  251. exp_avg_sqs: List[Tensor],
  252. state_steps: List[Tensor],
  253. *,
  254. beta1: float,
  255. beta2: float,
  256. lr: float,
  257. weight_decay: float,
  258. eps: float,
  259. caution: bool,
  260. maximize: bool,
  261. capturable: bool,
  262. max_lr: Optional[float],
  263. ):
  264. if len(params) == 0:
  265. return
  266. if capturable:
  267. assert all(
  268. p.is_cuda and step.is_cuda for p, step in zip(params, state_steps)
  269. ), "If capturable=True, params and state_steps must be CUDA tensors."
  270. if maximize:
  271. grads = torch._foreach_neg(tuple(grads)) # type: ignore[assignment]
  272. grads = [torch.view_as_real(x) if torch.is_complex(x) else x for x in grads]
  273. exp_avgs = [torch.view_as_real(x) if torch.is_complex(x) else x for x in exp_avgs]
  274. exp_avg_sqs = [torch.view_as_real(x) if torch.is_complex(x) else x for x in exp_avg_sqs]
  275. params = [torch.view_as_real(x) if torch.is_complex(x) else x for x in params]
  276. # update steps
  277. torch._foreach_add_(state_steps, 1)
  278. # Perform stepweight decay
  279. wd_scale = lr if max_lr is None else lr ** 2 / max_lr
  280. torch._foreach_mul_(params, 1 - wd_scale * weight_decay)
  281. # Decay the first and second moment running average coefficient
  282. torch._foreach_mul_(exp_avgs, beta1)
  283. torch._foreach_add_(exp_avgs, grads, alpha=1 - beta1)
  284. torch._foreach_mul_(exp_avg_sqs, beta2)
  285. torch._foreach_addcmul_(exp_avg_sqs, grads, grads, 1 - beta2)
  286. if capturable:
  287. # TODO: use foreach_pow if/when foreach_pow is added
  288. bias_correction1 = [torch.pow(beta1, step) for step in state_steps]
  289. bias_correction2 = [torch.pow(beta2, step) for step in state_steps]
  290. # foreach_sub doesn't allow a scalar as the first arg
  291. torch._foreach_sub_(bias_correction1, 1)
  292. torch._foreach_sub_(bias_correction2, 1)
  293. torch._foreach_neg_(bias_correction1)
  294. torch._foreach_neg_(bias_correction2)
  295. # foreach_div doesn't allow a scalar as the first arg
  296. step_size = torch._foreach_div(bias_correction1, lr)
  297. torch._foreach_reciprocal_(step_size)
  298. torch._foreach_neg_(step_size)
  299. bias_correction2_sqrt = torch._foreach_sqrt(bias_correction2)
  300. # Only difference between NAdamW and AdamW in this implementation.
  301. # The official PyTorch implementation of NAdam uses a different algorithm.
  302. exp_avgs = torch._foreach_mul(exp_avgs, beta1)
  303. torch._foreach_add_(exp_avgs, grads, alpha=1 - beta1)
  304. exp_avg_sq_sqrt = torch._foreach_sqrt(exp_avg_sqs)
  305. torch._foreach_div_(
  306. exp_avg_sq_sqrt,
  307. torch._foreach_mul(bias_correction2_sqrt, step_size)
  308. )
  309. eps_over_step_size = torch._foreach_div(step_size, eps)
  310. torch._foreach_reciprocal_(eps_over_step_size)
  311. denom = torch._foreach_add(exp_avg_sq_sqrt, eps_over_step_size)
  312. if caution:
  313. # Apply caution as per 'Cautious Optimizers' - https://arxiv.org/abs/2411.16085
  314. masks = torch._foreach_mul(exp_avgs, grads)
  315. masks = [(m > 0).to(g.dtype) for m, g in zip(masks, grads)] # capturable?
  316. mask_scale = [m.mean() for m in masks]
  317. torch._foreach_maximum_(mask_scale, 1e-3)
  318. #torch._foreach_clamp_min_(mask_scale, 1e-3)
  319. torch._foreach_div_(masks, mask_scale)
  320. torch._foreach_mul_(exp_avgs, masks)
  321. torch._foreach_addcdiv_(params, exp_avgs, denom)
  322. else:
  323. bias_correction1 = [1 - beta1 ** step.item() for step in state_steps]
  324. bias_correction2 = [1 - beta2 ** step.item() for step in state_steps]
  325. step_size = [(lr / bc) * -1 for bc in bias_correction1]
  326. bias_correction2_sqrt = [math.sqrt(bc) for bc in bias_correction2]
  327. # Apply Nesterov. Only difference between NAdamW and AdamW in this implementation.
  328. # The official PyTorch implementation of NAdam uses a different algorithm.
  329. exp_avgs = torch._foreach_mul(exp_avgs, beta1)
  330. torch._foreach_add_(exp_avgs, grads, alpha=1 - beta1)
  331. exp_avg_sq_sqrt = torch._foreach_sqrt(exp_avg_sqs)
  332. torch._foreach_div_(exp_avg_sq_sqrt, bias_correction2_sqrt)
  333. denom = torch._foreach_add(exp_avg_sq_sqrt, eps)
  334. if caution:
  335. # Apply caution as per 'Cautious Optimizers' - https://arxiv.org/abs/2411.16085
  336. masks = torch._foreach_mul(exp_avgs, grads)
  337. masks = [(m > 0).to(g.dtype) for m, g in zip(masks, grads)]
  338. mask_scale = [m.mean() for m in masks]
  339. torch._foreach_maximum_(mask_scale, 1e-3)
  340. #torch._foreach_clamp_min_(mask_scale, 1e-3)
  341. torch._foreach_div_(masks, mask_scale)
  342. torch._foreach_mul_(exp_avgs, masks)
  343. torch._foreach_addcdiv_(params, exp_avgs, denom, step_size)