functional_rprop.py 3.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107
  1. # mypy: allow-untyped-defs
  2. from typing import Optional
  3. import torch
  4. import torch.optim._functional as F
  5. from torch import Tensor
  6. from torch.distributed.optim._deprecation_warning import (
  7. _scripted_functional_optimizer_deprecation_warning,
  8. )
  9. __all__: list[str] = []
  10. # Define a TorchScript compatible Functional Rprop Optimizer
  11. # where we use these optimizer in a functional way.
  12. # Instead of using the `param.grad` when updating parameters,
  13. # we explicitly allow the distributed optimizer pass gradients to
  14. # the `step` function. In this way, we could separate the gradients
  15. # and parameters and allow multithreaded trainer to update the
  16. # parameters without data traces on accumulating to the same .grad.
  17. # NOTE: This should be only used by distributed optimizer internals
  18. # and not meant to expose to the user.
  19. @torch.jit.script
  20. class _FunctionalRprop:
  21. def __init__(
  22. self,
  23. params: list[Tensor],
  24. lr: float = 1e-2,
  25. etas: tuple[float, float] = (0.5, 1.2),
  26. step_sizes: tuple[float, float] = (1e-6, 50),
  27. foreach: bool = False,
  28. maximize: bool = False,
  29. _allow_empty_param_list: bool = False,
  30. ):
  31. _scripted_functional_optimizer_deprecation_warning(stacklevel=2)
  32. self.defaults = {
  33. "lr": lr,
  34. }
  35. self.etas = etas
  36. self.step_sizes = step_sizes
  37. self.foreach = foreach
  38. self.maximize = maximize
  39. if len(params) == 0 and not _allow_empty_param_list:
  40. raise ValueError("optimizer got an empty parameter list")
  41. # NOTE: we only have one param_group and don't allow user to add additional
  42. # param group as it's not a common use case.
  43. self.param_group = {"params": params}
  44. self.state = torch.jit.annotate(dict[torch.Tensor, dict[str, torch.Tensor]], {})
  45. def step(self, gradients: list[Optional[Tensor]]):
  46. params = self.param_group["params"]
  47. params_with_grad = []
  48. grads = []
  49. prevs = []
  50. step_sizes = []
  51. state_steps = []
  52. lr = self.defaults["lr"]
  53. etaminus, etaplus = self.etas
  54. step_size_min, step_size_max = self.step_sizes
  55. if len(params) != len(gradients):
  56. raise ValueError(
  57. "the gradients passed in does not equal to the size of the parameters!"
  58. + f"Params length: {len(params)}. "
  59. + f"Gradients length: {len(gradients)}"
  60. )
  61. has_complex = False
  62. for param, gradient in zip(params, gradients):
  63. if gradient is not None:
  64. has_complex |= torch.is_complex(param)
  65. params_with_grad.append(param)
  66. grads.append(gradient)
  67. # Lazy state initialization
  68. if param not in self.state:
  69. self.state[param] = {}
  70. state = self.state[param]
  71. state["step"] = torch.tensor(0.0)
  72. state["prev"] = torch.zeros_like(
  73. param, memory_format=torch.preserve_format
  74. )
  75. state["step_size"] = torch.full_like(gradient, lr)
  76. state = self.state[param]
  77. prevs.append(state["prev"])
  78. step_sizes.append(state["step_size"])
  79. state_steps.append(state["step"])
  80. with torch.no_grad():
  81. F.rprop(
  82. params_with_grad,
  83. grads,
  84. prevs,
  85. step_sizes,
  86. state_steps,
  87. step_size_min=step_size_min,
  88. step_size_max=step_size_max,
  89. etaminus=etaminus,
  90. etaplus=etaplus,
  91. foreach=self.foreach,
  92. maximize=self.maximize,
  93. has_complex=has_complex,
  94. )