radam.py 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598
  1. # mypy: allow-untyped-defs
  2. from typing import cast, List, Optional, Tuple, Union
  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. _dispatch_sqrt,
  11. _foreach_doc,
  12. _get_capturable_supported_devices,
  13. _get_scalar_dtype,
  14. _get_value,
  15. _maximize_doc,
  16. _use_grad_for_differentiable,
  17. _view_as_real,
  18. Optimizer,
  19. ParamsT,
  20. )
  21. __all__ = ["RAdam", "radam"]
  22. class RAdam(Optimizer):
  23. def __init__(
  24. self,
  25. params: ParamsT,
  26. lr: float = 1e-3,
  27. betas: Tuple[float, float] = (0.9, 0.999),
  28. eps: float = 1e-8,
  29. weight_decay: float = 0,
  30. decoupled_weight_decay: bool = False,
  31. *,
  32. foreach: Optional[bool] = None,
  33. maximize: bool = False,
  34. capturable: bool = False,
  35. differentiable: bool = False,
  36. ):
  37. if not 0.0 <= lr:
  38. raise ValueError(f"Invalid learning rate: {lr}")
  39. if not 0.0 <= eps:
  40. raise ValueError(f"Invalid epsilon value: {eps}")
  41. if not 0.0 <= betas[0] < 1.0:
  42. raise ValueError(f"Invalid beta parameter at index 0: {betas[0]}")
  43. if not 0.0 <= betas[1] < 1.0:
  44. raise ValueError(f"Invalid beta parameter at index 1: {betas[1]}")
  45. if not 0.0 <= weight_decay:
  46. raise ValueError(f"Invalid weight_decay value: {weight_decay}")
  47. defaults = dict(
  48. lr=lr,
  49. betas=betas,
  50. eps=eps,
  51. weight_decay=weight_decay,
  52. maximize=maximize,
  53. foreach=foreach,
  54. capturable=capturable,
  55. decoupled_weight_decay=decoupled_weight_decay,
  56. differentiable=differentiable,
  57. )
  58. super().__init__(params, defaults)
  59. def __setstate__(self, state):
  60. super().__setstate__(state)
  61. for group in self.param_groups:
  62. group.setdefault("foreach", None)
  63. group.setdefault("maximize", False)
  64. group.setdefault("differentiable", False)
  65. group.setdefault("decoupled_weight_decay", 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_avg_sqs, state_steps
  80. ):
  81. has_complex = False
  82. for p in group["params"]:
  83. if p.grad is not None:
  84. has_complex |= torch.is_complex(p)
  85. params_with_grad.append(p)
  86. if p.grad.is_sparse:
  87. raise RuntimeError("RAdam does not support sparse gradients")
  88. grads.append(p.grad)
  89. state = self.state[p]
  90. # Lazy state initialization
  91. if len(state) == 0:
  92. state["step"] = (
  93. torch.zeros((), dtype=_get_scalar_dtype(), device=p.device)
  94. if group["capturable"]
  95. else torch.tensor(0.0, dtype=_get_scalar_dtype())
  96. )
  97. # Exponential moving average of gradient values
  98. state["exp_avg"] = torch.zeros_like(
  99. p, memory_format=torch.preserve_format
  100. )
  101. # Exponential moving average of squared gradient values
  102. state["exp_avg_sq"] = torch.zeros_like(
  103. p, memory_format=torch.preserve_format
  104. )
  105. exp_avgs.append(state["exp_avg"])
  106. exp_avg_sqs.append(state["exp_avg_sq"])
  107. state_steps.append(state["step"])
  108. return has_complex
  109. @_use_grad_for_differentiable
  110. def step(self, closure=None):
  111. """Performs a single optimization step.
  112. Args:
  113. closure (Callable, optional): A closure that reevaluates the model
  114. and returns the loss.
  115. """
  116. self._cuda_graph_capture_health_check()
  117. loss = None
  118. if closure is not None:
  119. with torch.enable_grad():
  120. loss = closure()
  121. for group in self.param_groups:
  122. params_with_grad: List[Tensor] = []
  123. grads: List[Tensor] = []
  124. exp_avgs: List[Tensor] = []
  125. exp_avg_sqs: List[Tensor] = []
  126. state_steps: List[Tensor] = []
  127. beta1, beta2 = cast(Tuple[float, float], group["betas"])
  128. has_complex = self._init_group(
  129. group, params_with_grad, grads, exp_avgs, exp_avg_sqs, state_steps
  130. )
  131. radam(
  132. params_with_grad,
  133. grads,
  134. exp_avgs,
  135. exp_avg_sqs,
  136. state_steps,
  137. beta1=beta1,
  138. beta2=beta2,
  139. lr=group["lr"],
  140. weight_decay=group["weight_decay"],
  141. eps=group["eps"],
  142. maximize=group["maximize"],
  143. foreach=group["foreach"],
  144. capturable=group["capturable"],
  145. differentiable=group["differentiable"],
  146. decoupled_weight_decay=group["decoupled_weight_decay"],
  147. has_complex=has_complex,
  148. )
  149. return loss
  150. RAdam.__doc__ = (
  151. r"""Implements RAdam algorithm.
  152. .. math::
  153. \begin{aligned}
  154. &\rule{110mm}{0.4pt} \\
  155. &\textbf{input} : \gamma \text{ (lr)}, \: \beta_1, \beta_2
  156. \text{ (betas)}, \: \theta_0 \text{ (params)}, \:f(\theta) \text{ (objective)}, \:
  157. \lambda \text{ (weightdecay)}, \:\textit{maximize} \\
  158. &\hspace{13mm} \epsilon \text{ (epsilon)}, \textit{decoupled\_weight\_decay} \\
  159. &\textbf{initialize} : m_0 \leftarrow 0 \text{ ( first moment)},
  160. v_0 \leftarrow 0 \text{ ( second moment)}, \\
  161. &\hspace{18mm} \rho_{\infty} \leftarrow 2/(1-\beta_2) -1 \\[-1.ex]
  162. &\rule{110mm}{0.4pt} \\
  163. &\textbf{for} \: t=1 \: \textbf{to} \: \ldots \: \textbf{do} \\
  164. &\hspace{6mm}\textbf{if} \: \textit{maximize}: \\
  165. &\hspace{12mm}g_t \leftarrow -\nabla_{\theta} f_t (\theta_{t-1}) \\
  166. &\hspace{6mm}\textbf{else} \\
  167. &\hspace{12mm}g_t \leftarrow \nabla_{\theta} f_t (\theta_{t-1}) \\
  168. &\hspace{6mm} \theta_t \leftarrow \theta_{t-1} \\
  169. &\hspace{6mm} \textbf{if} \: \lambda \neq 0 \\
  170. &\hspace{12mm}\textbf{if} \: \textit{decoupled\_weight\_decay} \\
  171. &\hspace{18mm} \theta_t \leftarrow \theta_{t} - \gamma \lambda \theta_{t} \\
  172. &\hspace{12mm}\textbf{else} \\
  173. &\hspace{18mm} g_t \leftarrow g_t + \lambda \theta_{t} \\
  174. &\hspace{6mm}m_t \leftarrow \beta_1 m_{t-1} + (1 - \beta_1) g_t \\
  175. &\hspace{6mm}v_t \leftarrow \beta_2 v_{t-1} + (1-\beta_2) g^2_t \\
  176. &\hspace{6mm}\widehat{m_t} \leftarrow m_t/\big(1-\beta_1^t \big) \\
  177. &\hspace{6mm}\rho_t \leftarrow \rho_{\infty} -
  178. 2 t \beta^t_2 /\big(1-\beta_2^t \big) \\[0.1.ex]
  179. &\hspace{6mm}\textbf{if} \: \rho_t > 5 \\
  180. &\hspace{12mm} l_t \leftarrow \frac{\sqrt{ (1-\beta^t_2) }}{ \sqrt{v_t} +\epsilon } \\
  181. &\hspace{12mm} r_t \leftarrow
  182. \sqrt{\frac{(\rho_t-4)(\rho_t-2)\rho_{\infty}}{(\rho_{\infty}-4)(\rho_{\infty}-2) \rho_t}} \\
  183. &\hspace{12mm}\theta_t \leftarrow \theta_t - \gamma \widehat{m_t} r_t l_t \\
  184. &\hspace{6mm}\textbf{else} \\
  185. &\hspace{12mm}\theta_t \leftarrow \theta_t - \gamma \widehat{m_t} \\
  186. &\rule{110mm}{0.4pt} \\[-1.ex]
  187. &\bf{return} \: \theta_t \\[-1.ex]
  188. &\rule{110mm}{0.4pt} \\[-1.ex]
  189. \end{aligned}
  190. For further details regarding the algorithm we refer to `On the variance of the adaptive learning rate and beyond`_.
  191. This implementation provides an option to use either the original weight_decay implementation as in Adam
  192. (where the weight_decay is applied to the gradient) or the one from AdamW (where weight_decay is applied
  193. to the weight) through the decoupled_weight_decay option. When decoupled_weight_decay is set to False
  194. (default), it uses the original Adam style weight decay, otherwise, it uses the AdamW style which
  195. corresponds more closely to the `author's implementation`_ in the RAdam paper. Further information
  196. about decoupled weight decay can be found in `Decoupled Weight Decay Regularization`_.
  197. """
  198. + rf"""
  199. Args:
  200. params (iterable): iterable of parameters to optimize or dicts defining
  201. parameter groups
  202. lr (float, optional): learning rate (default: 1e-3)
  203. betas (Tuple[float, float], optional): coefficients used for computing
  204. running averages of gradient and its square (default: (0.9, 0.999))
  205. eps (float, optional): term added to the denominator to improve
  206. numerical stability (default: 1e-8)
  207. weight_decay (float, optional): weight decay (L2 penalty) (default: 0)
  208. decoupled_weight_decay (bool, optional): whether to use decoupled weight
  209. decay as in AdamW to obtain RAdamW (default: False)
  210. {_foreach_doc}
  211. {_maximize_doc}
  212. {_differentiable_doc}
  213. {_capturable_doc}
  214. .. _On the variance of the adaptive learning rate and beyond:
  215. https://arxiv.org/abs/1908.03265
  216. .. _author's implementation:
  217. https://github.com/LiyuanLucasLiu/RAdam
  218. .. _Decoupled Weight Decay Regularization:
  219. https://arxiv.org/abs/1711.05101
  220. """
  221. )
  222. def _single_tensor_radam(
  223. params: List[Tensor],
  224. grads: List[Tensor],
  225. exp_avgs: List[Tensor],
  226. exp_avg_sqs: List[Tensor],
  227. state_steps: List[Tensor],
  228. *,
  229. beta1: float,
  230. beta2: float,
  231. lr: float,
  232. weight_decay: float,
  233. eps: float,
  234. decoupled_weight_decay: bool,
  235. differentiable: bool,
  236. maximize: bool,
  237. capturable: bool,
  238. has_complex: bool,
  239. ):
  240. for i, param in enumerate(params):
  241. grad = grads[i] if not maximize else -grads[i]
  242. exp_avg = exp_avgs[i]
  243. exp_avg_sq = exp_avg_sqs[i]
  244. step_t = state_steps[i]
  245. # If compiling, the compiler will handle cudagraph checks, see note [torch.compile x capturable]
  246. if not torch._utils.is_compiling() and capturable:
  247. capturable_supported_devices = _get_capturable_supported_devices()
  248. assert (
  249. param.device.type == step_t.device.type
  250. and param.device.type in capturable_supported_devices
  251. ), f"If capturable=True, params and state_steps must be on supported devices: {capturable_supported_devices}."
  252. if torch.is_complex(param):
  253. param = torch.view_as_real(param)
  254. grad = torch.view_as_real(grad)
  255. exp_avg = torch.view_as_real(exp_avg)
  256. exp_avg_sq = torch.view_as_real(exp_avg_sq)
  257. # update step
  258. step_t += 1
  259. step = step_t if capturable else _get_value(step_t)
  260. if weight_decay != 0:
  261. if decoupled_weight_decay:
  262. param.mul_(1 - lr * weight_decay)
  263. else:
  264. grad = grad.add(param, alpha=weight_decay)
  265. # Decay the first and second moment running average coefficient
  266. exp_avg.lerp_(grad, 1 - beta1)
  267. exp_avg_sq.mul_(beta2).addcmul_(grad, grad, value=1 - beta2)
  268. bias_correction1 = 1 - beta1**step
  269. bias_correction2 = 1 - beta2**step
  270. # correcting bias for the first moving moment
  271. bias_corrected_exp_avg = exp_avg / bias_correction1
  272. # maximum length of the approximated SMA
  273. rho_inf = 2 / (1 - beta2) - 1
  274. # compute the length of the approximated SMA
  275. rho_t = rho_inf - 2 * step * (beta2**step) / bias_correction2
  276. def _compute_rect():
  277. return (
  278. (rho_t - 4)
  279. * (rho_t - 2)
  280. * rho_inf
  281. / ((rho_inf - 4) * (rho_inf - 2) * rho_t)
  282. ) ** 0.5
  283. def _compute_adaptive_lr():
  284. exp_avg_sq_sqrt = exp_avg_sq.sqrt()
  285. if differentiable:
  286. exp_avg_sq_sqrt = exp_avg_sq_sqrt.add(eps)
  287. else:
  288. exp_avg_sq_sqrt = exp_avg_sq_sqrt.add_(eps)
  289. return (bias_correction2**0.5) / exp_avg_sq_sqrt
  290. # Compute the variance rectification term and update parameters accordingly
  291. if capturable:
  292. update = torch.where(
  293. rho_t > 5.0, _compute_rect() * _compute_adaptive_lr(), 1.0
  294. )
  295. param.add_(bias_corrected_exp_avg * lr * update, alpha=-1.0)
  296. else:
  297. if rho_t > 5.0:
  298. param.add_(
  299. bias_corrected_exp_avg
  300. * lr
  301. * _compute_adaptive_lr()
  302. * _compute_rect(),
  303. alpha=-1.0,
  304. )
  305. else:
  306. param.add_(bias_corrected_exp_avg * lr, alpha=-1.0)
  307. def _multi_tensor_radam(
  308. params: List[Tensor],
  309. grads: List[Tensor],
  310. exp_avgs: List[Tensor],
  311. exp_avg_sqs: List[Tensor],
  312. state_steps: List[Tensor],
  313. *,
  314. beta1: float,
  315. beta2: float,
  316. lr: float,
  317. weight_decay: float,
  318. eps: float,
  319. decoupled_weight_decay: bool,
  320. differentiable: bool,
  321. maximize: bool,
  322. capturable: bool,
  323. has_complex: bool,
  324. ):
  325. if len(params) == 0:
  326. return
  327. assert not differentiable, "_foreach ops don't support autograd"
  328. # If compiling, the compiler will handle cudagraph checks, see note [torch.compile x capturable]
  329. if not torch._utils.is_compiling() and capturable:
  330. capturable_supported_devices = _get_capturable_supported_devices(
  331. supports_xla=False
  332. )
  333. assert all(
  334. p.device.type == step.device.type
  335. and p.device.type in capturable_supported_devices
  336. for p, step in zip(params, state_steps)
  337. ), f"If capturable=True, params and state_steps must be on supported devices: {capturable_supported_devices}."
  338. grouped_tensors = Optimizer._group_tensors_by_device_and_dtype(
  339. [params, grads, exp_avgs, exp_avg_sqs, state_steps]
  340. )
  341. for (
  342. grouped_params,
  343. grouped_grads,
  344. grouped_exp_avgs,
  345. grouped_exp_avg_sqs,
  346. grouped_state_steps,
  347. ), _ in grouped_tensors.values():
  348. # Update steps
  349. # If steps are on CPU, foreach will fall back to the slow path, which is a for-loop calling t.add(1) over
  350. # and over. 1 will then be wrapped into a Tensor over and over again, which is slower than if we just
  351. # wrapped it once now. The alpha is required to assure we go to the right overload.
  352. if grouped_state_steps[0].is_cpu:
  353. torch._foreach_add_(
  354. grouped_state_steps, torch.tensor(1.0, device="cpu"), alpha=1.0
  355. )
  356. else:
  357. torch._foreach_add_(grouped_state_steps, 1)
  358. if has_complex:
  359. _view_as_real(
  360. grouped_params, grouped_grads, grouped_exp_avgs, grouped_exp_avg_sqs
  361. )
  362. if maximize:
  363. grouped_grads = torch._foreach_neg(grouped_grads) # type: ignore[assignment]
  364. # maximum length of the approximated SMA
  365. rho_inf = 2 / (1 - beta2) - 1
  366. # compute the length of the approximated SMA
  367. bias_correction1: Union[Tuple[Tensor, ...], List[Tensor]]
  368. bias_correction2: Union[Tuple[Tensor, ...], List[Tensor]]
  369. rho_t_list: Union[Tuple[Tensor, ...], List[Tensor]]
  370. if capturable:
  371. bias_correction1 = torch._foreach_pow(beta2, grouped_state_steps)
  372. torch._foreach_neg_(bias_correction1)
  373. torch._foreach_add_(bias_correction1, 1)
  374. bias_correction2 = torch._foreach_pow(beta2, grouped_state_steps)
  375. torch._foreach_mul_(bias_correction2, grouped_state_steps)
  376. torch._foreach_mul_(bias_correction2, 2)
  377. torch._foreach_div_(bias_correction2, bias_correction1)
  378. torch._foreach_neg_(bias_correction2)
  379. torch._foreach_add_(bias_correction2, rho_inf)
  380. rho_t_list = bias_correction2
  381. else:
  382. rho_t_list = [
  383. rho_inf
  384. - 2
  385. * _get_value(step)
  386. * (beta2 ** _get_value(step))
  387. / (1 - beta2 ** _get_value(step))
  388. for step in grouped_state_steps
  389. ]
  390. if weight_decay != 0:
  391. if decoupled_weight_decay:
  392. torch._foreach_mul_(grouped_params, 1 - lr * weight_decay)
  393. else:
  394. # Re-use the intermediate memory (grouped_grads) already allocated for maximize
  395. if maximize:
  396. torch._foreach_add_(
  397. grouped_grads, grouped_params, alpha=weight_decay
  398. )
  399. else:
  400. grouped_grads = torch._foreach_add( # type: ignore[assignment]
  401. grouped_grads, grouped_params, alpha=weight_decay
  402. )
  403. # Decay the first and second moment running average coefficient
  404. torch._foreach_lerp_(grouped_exp_avgs, grouped_grads, 1 - beta1)
  405. torch._foreach_mul_(grouped_exp_avg_sqs, beta2)
  406. torch._foreach_addcmul_(
  407. grouped_exp_avg_sqs, grouped_grads, grouped_grads, 1 - beta2
  408. )
  409. # Delete the local intermediate since it won't be used anymore to save on peak memory
  410. del grouped_grads
  411. if capturable:
  412. num = torch._foreach_sub(rho_t_list, 4)
  413. sub2 = torch._foreach_sub(rho_t_list, 2)
  414. torch._foreach_mul_(num, sub2)
  415. del sub2
  416. torch._foreach_mul_(num, rho_inf)
  417. rho_inf = (rho_inf - 4) * (rho_inf - 2)
  418. denom = torch._foreach_mul(rho_t_list, rho_inf)
  419. torch._foreach_div_(num, denom)
  420. del denom
  421. torch._foreach_sqrt_(num)
  422. # TODO(mlazos): we should try and get a foreach_where op https://github.com/pytorch/pytorch/issues/117884
  423. rect = [
  424. torch.where(rho_t > 5.0, n, 0.0) for n, rho_t in zip(num, rho_t_list)
  425. ]
  426. del num
  427. del rho_t_list
  428. unrect_step_size = [torch.where(rect > 0, 0.0, 1.0) for rect in rect]
  429. torch._foreach_mul_(unrect_step_size, lr)
  430. bias_correction1 = torch._foreach_pow(beta1, grouped_state_steps)
  431. torch._foreach_neg_(bias_correction1)
  432. torch._foreach_add_(bias_correction1, 1)
  433. torch._foreach_div_(unrect_step_size, bias_correction1)
  434. torch._foreach_neg_(unrect_step_size)
  435. bias_correction2 = torch._foreach_pow(beta2, grouped_state_steps)
  436. torch._foreach_neg_(bias_correction2)
  437. torch._foreach_add_(bias_correction2, 1)
  438. torch._foreach_sqrt_(bias_correction2)
  439. torch._foreach_mul_(bias_correction2, lr)
  440. torch._foreach_mul_(bias_correction2, rect)
  441. del rect
  442. torch._foreach_neg_(bias_correction2)
  443. torch._foreach_div_(bias_correction2, bias_correction1)
  444. del bias_correction1
  445. else:
  446. rect = [
  447. _dispatch_sqrt(
  448. (rho_t - 4) # type: ignore[arg-type]
  449. * (rho_t - 2)
  450. * rho_inf
  451. / ((rho_inf - 4) * (rho_inf - 2) * rho_t)
  452. )
  453. if rho_t > 5
  454. else 0
  455. for rho_t in rho_t_list
  456. ]
  457. unrectified = [0 if rect > 0 else 1.0 for rect in rect]
  458. bias_correction1 = [
  459. 1 - beta1 ** _get_value(step) for step in grouped_state_steps
  460. ]
  461. unrect_step_size = [
  462. (lr * rect / bc) * -1 for rect, bc in zip(unrectified, bias_correction1)
  463. ]
  464. bias_correction2 = [
  465. _dispatch_sqrt(1 - beta2 ** _get_value(step)) * (lr * rect / bc) * -1
  466. for step, rect, bc in zip(grouped_state_steps, rect, bias_correction1)
  467. ]
  468. buffer = torch._foreach_sqrt(grouped_exp_avg_sqs)
  469. torch._foreach_add_(buffer, eps)
  470. torch._foreach_div_(buffer, bias_correction2)
  471. torch._foreach_reciprocal_(buffer)
  472. torch._foreach_add_(buffer, unrect_step_size)
  473. # Here, buffer = sqrt(1 - beta2^t) * rect_step_size / (sqrt(v) + eps) + unrect_step_size
  474. torch._foreach_addcmul_(grouped_params, grouped_exp_avgs, buffer)
  475. @_disable_dynamo_if_unsupported(single_tensor_fn=_single_tensor_radam)
  476. def radam(
  477. params: List[Tensor],
  478. grads: List[Tensor],
  479. exp_avgs: List[Tensor],
  480. exp_avg_sqs: List[Tensor],
  481. state_steps: List[Tensor],
  482. # kwonly args with defaults are not supported by functions compiled with torchscript issue #70627
  483. # setting this as kwarg for now as functional API is compiled by torch/distributed/optim
  484. decoupled_weight_decay: bool = False,
  485. foreach: Optional[bool] = None,
  486. differentiable: bool = False,
  487. capturable: bool = False,
  488. has_complex: bool = False,
  489. maximize: bool = False,
  490. *,
  491. beta1: float,
  492. beta2: float,
  493. lr: float,
  494. weight_decay: float,
  495. eps: float,
  496. ):
  497. r"""Functional API that performs RAdam algorithm computation.
  498. See :class:`~torch.optim.RAdam` for details.
  499. """
  500. if not all(isinstance(t, torch.Tensor) for t in state_steps):
  501. raise RuntimeError(
  502. "API has changed, `state_steps` argument must contain a list of singleton tensors"
  503. )
  504. if foreach is None:
  505. _, foreach = _default_to_fused_or_foreach(
  506. params, differentiable, use_fused=False
  507. )
  508. if foreach and torch.jit.is_scripting():
  509. raise RuntimeError("torch.jit.script not supported with foreach optimizers")
  510. if foreach and not torch.jit.is_scripting():
  511. func = _multi_tensor_radam
  512. else:
  513. func = _single_tensor_radam
  514. func(
  515. params,
  516. grads,
  517. exp_avgs,
  518. exp_avg_sqs,
  519. state_steps,
  520. beta1=beta1,
  521. beta2=beta2,
  522. lr=lr,
  523. weight_decay=weight_decay,
  524. eps=eps,
  525. maximize=maximize,
  526. decoupled_weight_decay=decoupled_weight_decay,
  527. differentiable=differentiable,
  528. capturable=capturable,
  529. has_complex=has_complex,
  530. )