adamw.py 16 KB

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