functional_rmsprop.py 4.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130
  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 RMSprop 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 _FunctionalRMSprop:
  21. def __init__(
  22. self,
  23. params: list[Tensor],
  24. lr: float = 1e-2,
  25. alpha: float = 0.99,
  26. eps: float = 1e-8,
  27. weight_decay: float = 0.0,
  28. momentum: float = 0.0,
  29. centered: bool = False,
  30. foreach: bool = False,
  31. maximize: bool = False,
  32. _allow_empty_param_list: bool = False,
  33. ):
  34. _scripted_functional_optimizer_deprecation_warning(stacklevel=2)
  35. self.defaults = {
  36. "lr": lr,
  37. "alpha": alpha,
  38. "eps": eps,
  39. "weight_decay": weight_decay,
  40. "momentum": momentum,
  41. }
  42. self.centered = centered
  43. self.foreach = foreach
  44. self.maximize = maximize
  45. if len(params) == 0 and not _allow_empty_param_list:
  46. raise ValueError("optimizer got an empty parameter list")
  47. # NOTE: we only have one param_group and don't allow user to add additional
  48. # param group as it's not a common use case.
  49. self.param_group = {"params": params}
  50. self.state = torch.jit.annotate(dict[torch.Tensor, dict[str, torch.Tensor]], {})
  51. def step(self, gradients: list[Optional[Tensor]]):
  52. params = self.param_group["params"]
  53. params_with_grad = []
  54. grads = []
  55. square_avgs = []
  56. grad_avgs = []
  57. momentum_buffer_list = []
  58. state_steps = []
  59. lr = self.defaults["lr"]
  60. alpha = self.defaults["alpha"]
  61. eps = self.defaults["eps"]
  62. momentum = self.defaults["momentum"]
  63. weight_decay = self.defaults["weight_decay"]
  64. if len(params) != len(gradients):
  65. raise ValueError(
  66. "the gradients passed in does not equal to the size of the parameters!"
  67. + f"Params length: {len(params)}. "
  68. + f"Gradients length: {len(gradients)}"
  69. )
  70. has_complex = False
  71. for param, gradient in zip(params, gradients):
  72. if gradient is not None:
  73. has_complex |= torch.is_complex(param)
  74. params_with_grad.append(param)
  75. grads.append(gradient)
  76. # Lazy state initialization
  77. if param not in self.state:
  78. self.state[param] = {}
  79. state = self.state[param]
  80. state["step"] = torch.tensor(0.0)
  81. state["square_avg"] = torch.zeros_like(
  82. param, memory_format=torch.preserve_format
  83. )
  84. if momentum > 0:
  85. state["momentum_buffer"] = torch.zeros_like(
  86. param, memory_format=torch.preserve_format
  87. )
  88. if self.centered:
  89. state["grad_avg"] = torch.zeros_like(
  90. param, memory_format=torch.preserve_format
  91. )
  92. state = self.state[param]
  93. square_avgs.append(state["square_avg"])
  94. if momentum > 0:
  95. momentum_buffer_list.append(state["momentum_buffer"])
  96. if self.centered:
  97. grad_avgs.append(state["grad_avg"])
  98. state_steps.append(state["step"])
  99. with torch.no_grad():
  100. F.rmsprop(
  101. params_with_grad,
  102. grads,
  103. square_avgs,
  104. grad_avgs,
  105. momentum_buffer_list,
  106. state_steps,
  107. lr=lr,
  108. alpha=alpha,
  109. eps=eps,
  110. weight_decay=weight_decay,
  111. momentum=momentum,
  112. centered=self.centered,
  113. foreach=self.foreach,
  114. maximize=self.maximize,
  115. has_complex=has_complex,
  116. )