functional_rmsprop.py 4.4 KB

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