adamax.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485
  1. # mypy: allow-untyped-defs
  2. from typing import cast
  3. import torch
  4. from torch import Tensor
  5. from .optimizer import (
  6. _capturable_doc,
  7. _default_to_fused_or_foreach,
  8. _differentiable_doc,
  9. _disable_dynamo_if_unsupported,
  10. _foreach_doc,
  11. _get_capturable_supported_devices,
  12. _get_scalar_dtype,
  13. _get_value,
  14. _maximize_doc,
  15. _params_doc,
  16. _to_scalar,
  17. _use_grad_for_differentiable,
  18. _view_as_real,
  19. Optimizer,
  20. ParamsT,
  21. )
  22. __all__ = ["Adamax", "adamax"]
  23. class Adamax(Optimizer):
  24. def __init__(
  25. self,
  26. params: ParamsT,
  27. lr: float | Tensor = 2e-3,
  28. betas: tuple[float, float] = (0.9, 0.999),
  29. eps: float = 1e-8,
  30. weight_decay: float = 0,
  31. foreach: bool | None = None,
  32. *,
  33. maximize: bool = False,
  34. differentiable: bool = False,
  35. capturable: bool = False,
  36. ) -> None:
  37. if isinstance(lr, Tensor) and lr.numel() != 1:
  38. raise ValueError("Tensor lr must be 1-element")
  39. if not 0.0 <= lr:
  40. raise ValueError(f"Invalid learning rate: {lr}")
  41. if not 0.0 <= eps:
  42. raise ValueError(f"Invalid epsilon value: {eps}")
  43. if not 0.0 <= betas[0] < 1.0:
  44. raise ValueError(f"Invalid beta parameter at index 0: {betas[0]}")
  45. if not 0.0 <= betas[1] < 1.0:
  46. raise ValueError(f"Invalid beta parameter at index 1: {betas[1]}")
  47. if not 0.0 <= weight_decay:
  48. raise ValueError(f"Invalid weight_decay value: {weight_decay}")
  49. defaults = {
  50. "lr": lr,
  51. "betas": betas,
  52. "eps": eps,
  53. "weight_decay": weight_decay,
  54. "foreach": foreach,
  55. "maximize": maximize,
  56. "differentiable": differentiable,
  57. "capturable": capturable,
  58. }
  59. super().__init__(params, defaults)
  60. def __setstate__(self, state):
  61. super().__setstate__(state)
  62. for group in self.param_groups:
  63. group.setdefault("foreach", None)
  64. group.setdefault("maximize", False)
  65. group.setdefault("differentiable", False)
  66. group.setdefault("capturable", False)
  67. for p in group["params"]:
  68. p_state = self.state.get(p, [])
  69. if len(p_state) != 0 and not torch.is_tensor(p_state["step"]):
  70. step_val = float(p_state["step"])
  71. p_state["step"] = (
  72. torch.tensor(
  73. step_val, dtype=_get_scalar_dtype(), device=p.device
  74. )
  75. if group["capturable"]
  76. else torch.tensor(step_val, dtype=_get_scalar_dtype())
  77. )
  78. def _init_group(
  79. self, group, params_with_grad, grads, exp_avgs, exp_infs, state_steps
  80. ):
  81. has_complex = False
  82. for p in group["params"]:
  83. if p.grad is None:
  84. continue
  85. has_complex |= torch.is_complex(p)
  86. params_with_grad.append(p)
  87. if p.grad.is_sparse:
  88. raise RuntimeError("Adamax does not support sparse gradients")
  89. grads.append(p.grad)
  90. state = self.state[p]
  91. # State initialization
  92. if len(state) == 0:
  93. state["step"] = (
  94. torch.zeros((), dtype=_get_scalar_dtype(), device=p.device)
  95. if group["capturable"]
  96. else torch.tensor(0.0, dtype=_get_scalar_dtype())
  97. )
  98. state["exp_avg"] = torch.zeros_like(
  99. p, memory_format=torch.preserve_format
  100. )
  101. state["exp_inf"] = torch.zeros_like(
  102. p, memory_format=torch.preserve_format
  103. )
  104. exp_avgs.append(state["exp_avg"])
  105. exp_infs.append(state["exp_inf"])
  106. state_steps.append(state["step"])
  107. return has_complex
  108. @_use_grad_for_differentiable
  109. def step(self, closure=None):
  110. """Performs a single optimization step.
  111. Args:
  112. closure (Callable, optional): A closure that reevaluates the model
  113. and returns the loss.
  114. """
  115. self._accelerator_graph_capture_health_check()
  116. loss = None
  117. if closure is not None:
  118. with torch.enable_grad():
  119. loss = closure()
  120. for group in self.param_groups:
  121. params_with_grad: list[Tensor] = []
  122. grads: list[Tensor] = []
  123. exp_avgs: list[Tensor] = []
  124. exp_infs: list[Tensor] = []
  125. state_steps: list[Tensor] = []
  126. beta1, beta2 = group["betas"]
  127. eps = group["eps"]
  128. lr = group["lr"]
  129. weight_decay = group["weight_decay"]
  130. foreach = group["foreach"]
  131. maximize = group["maximize"]
  132. differentiable = group["differentiable"]
  133. capturable = group["capturable"]
  134. has_complex = self._init_group(
  135. group, params_with_grad, grads, exp_avgs, exp_infs, state_steps
  136. )
  137. adamax(
  138. params_with_grad,
  139. grads,
  140. exp_avgs,
  141. exp_infs,
  142. state_steps,
  143. eps=eps,
  144. beta1=beta1,
  145. beta2=beta2,
  146. lr=lr,
  147. weight_decay=weight_decay,
  148. foreach=foreach,
  149. maximize=maximize,
  150. differentiable=differentiable,
  151. capturable=capturable,
  152. has_complex=has_complex,
  153. )
  154. return loss
  155. Adamax.__doc__ = (
  156. r"""Implements Adamax algorithm (a variant of Adam based on infinity norm).
  157. .. math::
  158. \begin{aligned}
  159. &\rule{110mm}{0.4pt} \\
  160. &\textbf{input} : \gamma \text{ (lr)}, \beta_1, \beta_2
  161. \text{ (betas)},\theta_0 \text{ (params)},f(\theta) \text{ (objective)},
  162. \: \lambda \text{ (weight decay)}, \\
  163. &\hspace{13mm} \epsilon \text{ (epsilon)} \\
  164. &\textbf{initialize} : m_0 \leftarrow 0 \text{ ( first moment)},
  165. u_0 \leftarrow 0 \text{ ( infinity norm)} \\[-1.ex]
  166. &\rule{110mm}{0.4pt} \\
  167. &\textbf{for} \: t=1 \: \textbf{to} \: \ldots \: \textbf{do} \\
  168. &\hspace{5mm}g_t \leftarrow \nabla_{\theta} f_t (\theta_{t-1}) \\
  169. &\hspace{5mm}if \: \lambda \neq 0 \\
  170. &\hspace{10mm} g_t \leftarrow g_t + \lambda \theta_{t-1} \\
  171. &\hspace{5mm}m_t \leftarrow \beta_1 m_{t-1} + (1 - \beta_1) g_t \\
  172. &\hspace{5mm}u_t \leftarrow \mathrm{max}(\beta_2 u_{t-1}, |g_{t}|+\epsilon) \\
  173. &\hspace{5mm}\theta_t \leftarrow \theta_{t-1} - \frac{\gamma m_t}{(1-\beta^t_1) u_t} \\
  174. &\rule{110mm}{0.4pt} \\[-1.ex]
  175. &\bf{return} \: \theta_t \\[-1.ex]
  176. &\rule{110mm}{0.4pt} \\[-1.ex]
  177. \end{aligned}
  178. For further details regarding the algorithm we refer to `Adam: A Method for Stochastic Optimization`_.
  179. """
  180. + rf"""
  181. Args:
  182. {_params_doc}
  183. lr (float, Tensor, optional): learning rate (default: 2e-3)
  184. betas (Tuple[float, float], optional): coefficients used for computing
  185. running averages of gradient and its square
  186. eps (float, optional): term added to the denominator to improve
  187. numerical stability (default: 1e-8)
  188. weight_decay (float, optional): weight decay (L2 penalty) (default: 0)
  189. {_foreach_doc}
  190. {_maximize_doc}
  191. {_differentiable_doc}
  192. {_capturable_doc}
  193. .. _Adam\: A Method for Stochastic Optimization:
  194. https://arxiv.org/abs/1412.6980
  195. """
  196. )
  197. def _single_tensor_adamax(
  198. params: list[Tensor],
  199. grads: list[Tensor],
  200. exp_avgs: list[Tensor],
  201. exp_infs: list[Tensor],
  202. state_steps: list[Tensor],
  203. *,
  204. eps: float,
  205. beta1: float,
  206. beta2: float,
  207. lr: float,
  208. weight_decay: float,
  209. maximize: bool,
  210. differentiable: bool,
  211. capturable: bool,
  212. has_complex: bool,
  213. ) -> None:
  214. if not torch.jit.is_scripting():
  215. lr = _to_scalar(lr)
  216. for i, param in enumerate(params):
  217. grad = grads[i]
  218. grad = grad if not maximize else -grad
  219. exp_avg = exp_avgs[i]
  220. exp_inf = exp_infs[i]
  221. step_t = state_steps[i]
  222. # If compiling, the compiler will handle cudagraph checks, see note [torch.compile x capturable]
  223. if not torch.compiler.is_compiling() and capturable:
  224. capturable_supported_devices = _get_capturable_supported_devices()
  225. if not (
  226. param.device.type == step_t.device.type
  227. and param.device.type in capturable_supported_devices
  228. ):
  229. raise AssertionError(
  230. f"If capturable=True, params and state_steps must be on supported devices: {capturable_supported_devices}."
  231. )
  232. # update step
  233. step_t += 1
  234. if weight_decay != 0:
  235. grad = grad.add(param, alpha=weight_decay)
  236. if torch.is_complex(param):
  237. param = torch.view_as_real(param)
  238. grad = torch.view_as_real(grad)
  239. exp_avg = torch.view_as_real(exp_avg)
  240. exp_inf = torch.view_as_real(exp_inf)
  241. # Update biased first moment estimate.
  242. exp_avg.lerp_(grad, 1 - beta1)
  243. # Update the exponentially weighted infinity norm.
  244. if not differentiable:
  245. torch.maximum(
  246. exp_inf.mul_(beta2),
  247. grad.abs().add_(eps),
  248. out=exp_inf,
  249. )
  250. else:
  251. norm_buf = torch.cat(
  252. [exp_inf.mul_(beta2).unsqueeze(0), grad.abs().add_(eps).unsqueeze_(0)],
  253. 0,
  254. )
  255. exp_inf.copy_(torch.amax(norm_buf, 0, keepdim=False))
  256. if capturable:
  257. # why jump through extra hoops and negate bias_correction? check out #121238
  258. # once fixed, we should use bias_correction with addcdiv value=-1 for readability
  259. neg_bias_correction = beta1**step_t - 1
  260. neg_bias_correction.div_(lr)
  261. denom = exp_inf * neg_bias_correction
  262. param.addcdiv_(exp_avg, denom)
  263. else:
  264. bias_correction = 1 - beta1 ** _get_value(step_t)
  265. clr = lr / bias_correction
  266. param.addcdiv_(exp_avg, exp_inf, value=-clr)
  267. def _multi_tensor_adamax(
  268. params: list[Tensor],
  269. grads: list[Tensor],
  270. exp_avgs: list[Tensor],
  271. exp_infs: list[Tensor],
  272. state_steps: list[Tensor],
  273. *,
  274. eps: float,
  275. beta1: float,
  276. beta2: float,
  277. lr: float,
  278. weight_decay: float,
  279. maximize: bool,
  280. differentiable: bool,
  281. capturable: bool,
  282. has_complex: bool,
  283. ) -> None:
  284. if differentiable:
  285. raise AssertionError("_foreach ops don't support autograd")
  286. if len(params) == 0:
  287. return
  288. # If compiling, the compiler will handle cudagraph checks, see note [torch.compile x capturable]
  289. if not torch.compiler.is_compiling() and capturable:
  290. capturable_supported_devices = _get_capturable_supported_devices(
  291. supports_xla=False
  292. )
  293. if not all(
  294. p.device.type == step.device.type
  295. and p.device.type in capturable_supported_devices
  296. for p, step in zip(params, state_steps, strict=True)
  297. ):
  298. raise AssertionError(
  299. f"If capturable=True, params and state_steps must be on supported devices: {capturable_supported_devices}."
  300. )
  301. lr = _to_scalar(lr)
  302. grouped_tensors = Optimizer._group_tensors_by_device_and_dtype(
  303. [params, grads, exp_avgs, exp_infs, state_steps] # type: ignore[list-item]
  304. )
  305. for (
  306. grouped_params_,
  307. grouped_grads_,
  308. grouped_exp_avgs_,
  309. grouped_exp_infs_,
  310. grouped_state_steps_,
  311. ), _ in grouped_tensors.values():
  312. grouped_params = cast(list[Tensor], grouped_params_)
  313. grouped_grads = cast(list[Tensor], grouped_grads_)
  314. grouped_exp_avgs = cast(list[Tensor], grouped_exp_avgs_)
  315. grouped_exp_infs = cast(list[Tensor], grouped_exp_infs_)
  316. grouped_state_steps = cast(list[Tensor], grouped_state_steps_)
  317. if has_complex:
  318. _view_as_real(
  319. grouped_params, grouped_grads, grouped_exp_avgs, grouped_exp_infs
  320. )
  321. if maximize:
  322. grouped_grads = torch._foreach_neg(grouped_grads) # type: ignore[assignment]
  323. # Update steps
  324. # If steps are on CPU, foreach will fall back to the slow path, which is a for-loop calling t.add(1) over
  325. # and over. 1 will then be wrapped into a Tensor over and over again, which is slower than if we just
  326. # wrapped it once now. The alpha is required to assure we go to the right overload.
  327. if not torch.compiler.is_compiling() and grouped_state_steps[0].is_cpu:
  328. torch._foreach_add_(
  329. grouped_state_steps, torch.tensor(1.0, device="cpu"), alpha=1.0
  330. )
  331. else:
  332. torch._foreach_add_(grouped_state_steps, 1)
  333. if weight_decay != 0:
  334. if maximize:
  335. # Reuse the intermediate memory (grouped_grads) already allocated for maximize
  336. torch._foreach_add_(grouped_grads, grouped_params, alpha=weight_decay)
  337. else:
  338. grouped_grads = torch._foreach_add( # type: ignore[assignment]
  339. grouped_grads, grouped_params, alpha=weight_decay
  340. )
  341. # Update biased first moment estimate.
  342. torch._foreach_lerp_(grouped_exp_avgs, grouped_grads, 1 - beta1)
  343. # Update the exponentially weighted infinity norm.
  344. torch._foreach_mul_(grouped_exp_infs, beta2)
  345. # in this case, we need to introduce a copy of the grads
  346. # since one has not been introduced previously
  347. if not maximize and weight_decay == 0:
  348. grouped_grads = torch._foreach_abs(grouped_grads) # type: ignore[assignment]
  349. else:
  350. torch._foreach_abs_(grouped_grads)
  351. torch._foreach_add_(grouped_grads, eps)
  352. torch._foreach_maximum_(grouped_exp_infs, grouped_grads)
  353. bias_corrections: tuple[Tensor, ...] | list[Tensor]
  354. if capturable:
  355. bias_corrections = torch._foreach_pow(beta1, grouped_state_steps)
  356. # foreach_sub doesn't allow a scalar as the first arg
  357. torch._foreach_sub_(bias_corrections, 1)
  358. torch._foreach_div_(bias_corrections, lr)
  359. denom = torch._foreach_mul(grouped_exp_infs, bias_corrections)
  360. torch._foreach_addcdiv_(grouped_params, grouped_exp_avgs, denom)
  361. else:
  362. bias_corrections = [
  363. 1 - beta1 ** _get_value(step) for step in grouped_state_steps
  364. ]
  365. step_size = [(_get_value(lr) / bc) * -1 for bc in bias_corrections]
  366. torch._foreach_addcdiv_(
  367. grouped_params, grouped_exp_avgs, grouped_exp_infs, step_size
  368. )
  369. @_disable_dynamo_if_unsupported(single_tensor_fn=_single_tensor_adamax)
  370. def adamax(
  371. params: list[Tensor],
  372. grads: list[Tensor],
  373. exp_avgs: list[Tensor],
  374. exp_infs: list[Tensor],
  375. state_steps: list[Tensor],
  376. # kwonly args with defaults are not supported by functions compiled with torchscript issue #70627
  377. # setting this as kwarg for now as functional API is compiled by torch/distributed/optim
  378. foreach: bool | None = None,
  379. maximize: bool = False,
  380. differentiable: bool = False,
  381. capturable: bool = False,
  382. has_complex: bool = False,
  383. *,
  384. eps: float,
  385. beta1: float,
  386. beta2: float,
  387. lr: float,
  388. weight_decay: float,
  389. ) -> None:
  390. r"""Functional API that performs adamax algorithm computation.
  391. See :class:`~torch.optim.Adamax` for details.
  392. """
  393. if not torch.compiler.is_compiling() and not all(
  394. isinstance(t, torch.Tensor) for t in state_steps
  395. ):
  396. raise RuntimeError(
  397. "API has changed, `state_steps` argument must contain a list of singleton tensors"
  398. )
  399. if foreach is None:
  400. _, foreach = _default_to_fused_or_foreach(
  401. params, differentiable, use_fused=False
  402. )
  403. if foreach and torch.jit.is_scripting():
  404. raise RuntimeError("torch.jit.script not supported with foreach optimizers")
  405. if foreach and not torch.jit.is_scripting():
  406. func = _multi_tensor_adamax
  407. else:
  408. func = _single_tensor_adamax
  409. func(
  410. params,
  411. grads,
  412. exp_avgs,
  413. exp_infs,
  414. state_steps,
  415. eps=eps,
  416. beta1=beta1,
  417. beta2=beta2,
  418. lr=lr,
  419. weight_decay=weight_decay,
  420. maximize=maximize,
  421. differentiable=differentiable,
  422. has_complex=has_complex,
  423. capturable=capturable,
  424. )