functional_rmsprop.py 4.5 KB

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