rprop.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472
  1. # mypy: allow-untyped-defs
  2. r"""Implementation for the Resilient backpropagation."""
  3. from typing import cast
  4. import torch
  5. from torch import Tensor
  6. from .optimizer import (
  7. _capturable_doc,
  8. _default_to_fused_or_foreach,
  9. _differentiable_doc,
  10. _disable_dynamo_if_unsupported,
  11. _foreach_doc,
  12. _get_capturable_supported_devices,
  13. _get_scalar_dtype,
  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__ = ["Rprop", "rprop"]
  23. class Rprop(Optimizer): # noqa: D101
  24. def __init__(
  25. self,
  26. params: ParamsT,
  27. lr: float | Tensor = 1e-2,
  28. etas: tuple[float, float] = (0.5, 1.2),
  29. step_sizes: tuple[float, float] = (1e-6, 50),
  30. *,
  31. capturable: bool = False,
  32. foreach: bool | None = None,
  33. maximize: bool = False,
  34. differentiable: bool = False,
  35. ) -> None: # noqa: D107
  36. if isinstance(lr, Tensor) and lr.numel() != 1:
  37. raise ValueError("Tensor lr must be 1-element")
  38. if not 0.0 <= lr:
  39. raise ValueError(f"Invalid learning rate: {lr}")
  40. if not 0.0 < etas[0] < 1.0 < etas[1]:
  41. raise ValueError(f"Invalid eta values: {etas[0]}, {etas[1]}")
  42. defaults = {
  43. "lr": lr,
  44. "etas": etas,
  45. "step_sizes": step_sizes,
  46. "foreach": foreach,
  47. "maximize": maximize,
  48. "differentiable": differentiable,
  49. "capturable": capturable,
  50. }
  51. super().__init__(params, defaults)
  52. def __setstate__(self, state): # noqa: D105
  53. super().__setstate__(state)
  54. for group in self.param_groups:
  55. group.setdefault("foreach", None)
  56. group.setdefault("maximize", False)
  57. group.setdefault("differentiable", False)
  58. group.setdefault("capturable", False)
  59. for p in group["params"]:
  60. p_state = self.state.get(p, [])
  61. if len(p_state) != 0 and not torch.is_tensor(p_state["step"]):
  62. step_val = float(p_state["step"])
  63. p_state["step"] = (
  64. torch.tensor(
  65. step_val, dtype=_get_scalar_dtype(), device=p.device
  66. )
  67. if group["capturable"]
  68. else torch.tensor(step_val, dtype=_get_scalar_dtype())
  69. )
  70. def _init_group(self, group, params, grads, prevs, step_sizes, state_steps):
  71. has_complex = False
  72. for p in group["params"]:
  73. if p.grad is None:
  74. continue
  75. has_complex |= torch.is_complex(p)
  76. params.append(p)
  77. grad = p.grad
  78. if grad.is_sparse:
  79. raise RuntimeError("Rprop does not support sparse gradients")
  80. grads.append(grad)
  81. state = self.state[p]
  82. # State initialization
  83. if len(state) == 0:
  84. state["step"] = (
  85. torch.zeros((), dtype=_get_scalar_dtype(), device=p.device)
  86. if group["capturable"]
  87. else torch.zeros((), dtype=_get_scalar_dtype())
  88. )
  89. state["prev"] = torch.zeros_like(p, memory_format=torch.preserve_format)
  90. if p.dtype.is_complex:
  91. # Complex Number should be as if they are two independent real numbers.
  92. # Hence the step_size shouldn't be zero for imaginary part.
  93. state["step_size"] = torch.full_like(
  94. grad, complex(group["lr"], group["lr"])
  95. )
  96. else:
  97. state["step_size"] = torch.full_like(grad, _to_scalar(group["lr"]))
  98. prevs.append(state["prev"])
  99. step_sizes.append(state["step_size"])
  100. state_steps.append(state["step"])
  101. return has_complex
  102. @_use_grad_for_differentiable
  103. def step(self, closure=None):
  104. """Perform a single optimization step.
  105. Args:
  106. closure (Callable, optional): A closure that reevaluates the model
  107. and returns the loss.
  108. """
  109. self._accelerator_graph_capture_health_check()
  110. loss = None
  111. if closure is not None:
  112. with torch.enable_grad():
  113. loss = closure()
  114. for group in self.param_groups:
  115. params: list[Tensor] = []
  116. grads: list[Tensor] = []
  117. prevs: list[Tensor] = []
  118. step_sizes: list[Tensor] = []
  119. state_steps: list[Tensor] = []
  120. etaminus, etaplus = group["etas"]
  121. step_size_min, step_size_max = group["step_sizes"]
  122. foreach = group["foreach"]
  123. maximize = group["maximize"]
  124. has_complex = self._init_group(
  125. group, params, grads, prevs, step_sizes, state_steps
  126. )
  127. rprop(
  128. params,
  129. grads,
  130. prevs,
  131. step_sizes,
  132. state_steps,
  133. step_size_min=step_size_min,
  134. step_size_max=step_size_max,
  135. etaminus=etaminus,
  136. etaplus=etaplus,
  137. foreach=foreach,
  138. maximize=maximize,
  139. differentiable=group["differentiable"],
  140. capturable=group["capturable"],
  141. has_complex=has_complex,
  142. )
  143. return loss
  144. Rprop.__doc__ = (
  145. r"""Implements the resilient backpropagation algorithm.
  146. .. math::
  147. \begin{aligned}
  148. &\rule{110mm}{0.4pt} \\
  149. &\textbf{input} : \theta_0 \in \mathbf{R}^d \text{ (params)},f(\theta)
  150. \text{ (objective)}, \\
  151. &\hspace{13mm} \eta_{+/-} \text{ (etaplus, etaminus)}, \Gamma_{max/min}
  152. \text{ (step sizes)} \\
  153. &\textbf{initialize} : g^0_{prev} \leftarrow 0,
  154. \: \eta_0 \leftarrow \text{lr (learning rate)} \\
  155. &\rule{110mm}{0.4pt} \\
  156. &\textbf{for} \: t=1 \: \textbf{to} \: \ldots \: \textbf{do} \\
  157. &\hspace{5mm}g_t \leftarrow \nabla_{\theta} f_t (\theta_{t-1}) \\
  158. &\hspace{5mm} \textbf{for} \text{ } i = 0, 1, \ldots, d-1 \: \mathbf{do} \\
  159. &\hspace{10mm} \textbf{if} \: g^i_{prev} g^i_t > 0 \\
  160. &\hspace{15mm} \eta^i_t \leftarrow \mathrm{min}(\eta^i_{t-1} \eta_{+},
  161. \Gamma_{max}) \\
  162. &\hspace{10mm} \textbf{else if} \: g^i_{prev} g^i_t < 0 \\
  163. &\hspace{15mm} \eta^i_t \leftarrow \mathrm{max}(\eta^i_{t-1} \eta_{-},
  164. \Gamma_{min}) \\
  165. &\hspace{15mm} g^i_t \leftarrow 0 \\
  166. &\hspace{10mm} \textbf{else} \: \\
  167. &\hspace{15mm} \eta^i_t \leftarrow \eta^i_{t-1} \\
  168. &\hspace{5mm}\theta_t \leftarrow \theta_{t-1}- \eta_t \mathrm{sign}(g_t) \\
  169. &\hspace{5mm}g_{prev} \leftarrow g_t \\
  170. &\rule{110mm}{0.4pt} \\[-1.ex]
  171. &\bf{return} \: \theta_t \\[-1.ex]
  172. &\rule{110mm}{0.4pt} \\[-1.ex]
  173. \end{aligned}
  174. For further details regarding the algorithm we refer to the paper
  175. `A Direct Adaptive Method for Faster Backpropagation Learning: The RPROP Algorithm
  176. <http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.21.1417>`_.""" # codespell:ignore
  177. + rf"""
  178. Args:
  179. {_params_doc}
  180. lr (float, optional): learning rate (default: 1e-2)
  181. etas (Tuple[float, float], optional): pair of (etaminus, etaplus), that
  182. are multiplicative increase and decrease factors
  183. (default: (0.5, 1.2))
  184. step_sizes (Tuple[float, float], optional): a pair of minimal and
  185. maximal allowed step sizes (default: (1e-6, 50))
  186. {_capturable_doc}
  187. {_foreach_doc}
  188. {_maximize_doc}
  189. {_differentiable_doc}
  190. """
  191. )
  192. def _single_tensor_rprop(
  193. params: list[Tensor],
  194. grads: list[Tensor],
  195. prevs: list[Tensor],
  196. step_sizes: list[Tensor],
  197. state_steps: list[Tensor],
  198. *,
  199. step_size_min: float,
  200. step_size_max: float,
  201. etaminus: float,
  202. etaplus: float,
  203. maximize: bool,
  204. capturable: bool,
  205. differentiable: bool,
  206. has_complex: bool,
  207. ) -> None:
  208. for i, param in enumerate(params):
  209. grad = grads[i]
  210. grad = grad if not maximize else -grad
  211. prev = prevs[i]
  212. step_size = step_sizes[i]
  213. step = state_steps[i]
  214. # If compiling, the compiler will handle cudagraph checks, see note [torch.compile x capturable]
  215. if not torch.compiler.is_compiling() and capturable:
  216. capturable_supported_devices = _get_capturable_supported_devices()
  217. if not (
  218. param.device.type == step.device.type
  219. and param.device.type in capturable_supported_devices
  220. ):
  221. raise AssertionError(
  222. f"If capturable=True, params and state_steps must be on supported devices: {capturable_supported_devices}."
  223. )
  224. step += 1
  225. if torch.is_complex(param):
  226. grad = torch.view_as_real(grad)
  227. prev = torch.view_as_real(prev)
  228. param = torch.view_as_real(param)
  229. step_size = torch.view_as_real(step_size)
  230. if differentiable:
  231. sign = grad.mul(prev.clone()).sign()
  232. else:
  233. sign = grad.mul(prev).sign()
  234. if capturable:
  235. sign.copy_(torch.where(sign.gt(0), etaplus, sign))
  236. sign.copy_(torch.where(sign.lt(0), etaminus, sign))
  237. sign.copy_(torch.where(sign.eq(0), 1, sign))
  238. else:
  239. sign[sign.gt(0)] = etaplus
  240. sign[sign.lt(0)] = etaminus
  241. sign[sign.eq(0)] = 1
  242. # update stepsizes with step size updates
  243. step_size.mul_(sign).clamp_(step_size_min, step_size_max)
  244. # for dir<0, dfdx=0
  245. # for dir>=0 dfdx=dfdx
  246. grad = grad.clone(memory_format=torch.preserve_format)
  247. if capturable:
  248. grad.copy_(torch.where(sign.eq(etaminus), 0, grad))
  249. else:
  250. grad[sign.eq(etaminus)] = 0
  251. # update parameters
  252. param.addcmul_(grad.sign(), step_size, value=-1)
  253. prev.copy_(grad)
  254. def _multi_tensor_rprop(
  255. params: list[Tensor],
  256. grads: list[Tensor],
  257. prevs: list[Tensor],
  258. step_sizes: list[Tensor],
  259. state_steps: list[Tensor],
  260. *,
  261. step_size_min: float,
  262. step_size_max: float,
  263. etaminus: float,
  264. etaplus: float,
  265. maximize: bool,
  266. capturable: bool,
  267. differentiable: bool,
  268. has_complex: bool,
  269. ) -> None:
  270. if len(params) == 0:
  271. return
  272. if differentiable:
  273. raise AssertionError("_foreach ops don't support autograd")
  274. # If compiling, the compiler will handle cudagraph checks, see note [torch.compile x capturable]
  275. if not torch.compiler.is_compiling() and capturable:
  276. capturable_supported_devices = _get_capturable_supported_devices()
  277. if not all(
  278. p.device.type == step.device.type
  279. and p.device.type in capturable_supported_devices
  280. for p, step in zip(params, state_steps, strict=True)
  281. ):
  282. raise AssertionError(
  283. f"If capturable=True, params and state_steps must be on supported devices: {capturable_supported_devices}."
  284. )
  285. grouped_tensors = Optimizer._group_tensors_by_device_and_dtype(
  286. [params, grads, prevs, step_sizes, state_steps] # type: ignore[list-item]
  287. )
  288. for (
  289. grouped_params_,
  290. grouped_grads_,
  291. grouped_prevs_,
  292. grouped_step_sizes_,
  293. grouped_state_steps_,
  294. ), _ in grouped_tensors.values():
  295. grouped_params = cast(list[Tensor], grouped_params_)
  296. grouped_grads = cast(list[Tensor], grouped_grads_)
  297. grouped_prevs = cast(list[Tensor], grouped_prevs_)
  298. grouped_step_sizes = cast(list[Tensor], grouped_step_sizes_)
  299. grouped_state_steps = cast(list[Tensor], grouped_state_steps_)
  300. # Update steps
  301. # If steps are on CPU, foreach will fall back to the slow path, which is a for-loop calling t.add(1) over
  302. # and over. 1 will then be wrapped into a Tensor over and over again, which is slower than if we just
  303. # wrapped it once now. The alpha is required to assure we go to the right overload.
  304. if not torch.compiler.is_compiling() and grouped_state_steps[0].is_cpu:
  305. torch._foreach_add_(
  306. grouped_state_steps, torch.tensor(1.0, device="cpu"), alpha=1.0
  307. )
  308. else:
  309. torch._foreach_add_(grouped_state_steps, 1)
  310. # Handle complex params
  311. if has_complex:
  312. _view_as_real(
  313. grouped_params, grouped_grads, grouped_prevs, grouped_step_sizes
  314. )
  315. signs = torch._foreach_mul(grouped_grads, grouped_prevs)
  316. if maximize:
  317. torch._foreach_neg_(signs)
  318. # At the end of the step, grouped_prevs will contain the current grads, so we reuse
  319. # grouped_prevs memory instead of creating a new buffer, but, for clarity, we reassign
  320. # to keep referring to the buffer as grouped_grads.
  321. torch._foreach_copy_(grouped_prevs, grouped_grads)
  322. if maximize:
  323. torch._foreach_neg_(grouped_prevs)
  324. grouped_grads = grouped_prevs
  325. torch._foreach_sign_(signs)
  326. if capturable:
  327. for sign in signs:
  328. sign.copy_(torch.where(sign.gt(0), etaplus, sign))
  329. sign.copy_(torch.where(sign.lt(0), etaminus, sign))
  330. sign.copy_(torch.where(sign.eq(0), 1, sign))
  331. else:
  332. for sign in signs:
  333. sign[sign.gt(0)] = etaplus
  334. sign[sign.lt(0)] = etaminus
  335. sign[sign.eq(0)] = 1
  336. # update stepsizes with step size updates
  337. torch._foreach_mul_(grouped_step_sizes, signs)
  338. for step_size in grouped_step_sizes:
  339. step_size.clamp_(step_size_min, step_size_max)
  340. # for dir<0, dfdx=0
  341. # for dir>=0 dfdx=dfdx
  342. grouped_grads = list(grouped_grads)
  343. for i in range(len(grouped_grads)):
  344. grouped_grads[i].copy_(
  345. torch.where(signs[i].eq(etaminus), 0, grouped_grads[i])
  346. )
  347. # explicitly del signs as it's not used after here to save memory
  348. del signs
  349. # update parameters
  350. grad_signs = [grad.sign() for grad in grouped_grads]
  351. torch._foreach_addcmul_(
  352. grouped_params, grad_signs, grouped_step_sizes, value=-1
  353. )
  354. # Logically, you may expect grouped_prevs to get updated to grouped_grads, but that's
  355. # basically already happened since we've been using grouped_prevs' memory to store
  356. # updated grouped_grads!
  357. @_disable_dynamo_if_unsupported(single_tensor_fn=_single_tensor_rprop)
  358. def rprop(
  359. params: list[Tensor],
  360. grads: list[Tensor],
  361. prevs: list[Tensor],
  362. step_sizes: list[Tensor],
  363. state_steps: list[Tensor],
  364. # kwonly args with defaults are not supported by functions compiled with torchscript issue #70627
  365. # setting this as kwarg for now as functional API is compiled by torch/distributed/optim
  366. foreach: bool | None = None,
  367. capturable: bool = False,
  368. maximize: bool = False,
  369. differentiable: bool = False,
  370. has_complex: bool = False,
  371. *,
  372. step_size_min: float,
  373. step_size_max: float,
  374. etaminus: float,
  375. etaplus: float,
  376. ) -> None:
  377. r"""Functional API that performs rprop algorithm computation.
  378. See :class:`~torch.optim.Rprop` for details.
  379. """
  380. # this check is slow during compilation, so we skip it
  381. # if it's strictly needed we can add this check back in dynamo
  382. if not torch.compiler.is_compiling() and not all(
  383. isinstance(t, torch.Tensor) for t in state_steps
  384. ):
  385. raise RuntimeError(
  386. "API has changed, `state_steps` argument must contain a list of singleton tensors"
  387. )
  388. if foreach is None:
  389. _, foreach = _default_to_fused_or_foreach(
  390. params, differentiable, use_fused=False
  391. )
  392. if foreach and torch.jit.is_scripting():
  393. raise RuntimeError("torch.jit.script not supported with foreach optimizers")
  394. if foreach and not torch.jit.is_scripting():
  395. func = _multi_tensor_rprop
  396. else:
  397. func = _single_tensor_rprop
  398. func(
  399. params,
  400. grads,
  401. prevs,
  402. step_sizes,
  403. state_steps,
  404. step_size_min=step_size_min,
  405. step_size_max=step_size_max,
  406. etaminus=etaminus,
  407. etaplus=etaplus,
  408. capturable=capturable,
  409. maximize=maximize,
  410. differentiable=differentiable,
  411. has_complex=has_complex,
  412. )