functional_rmsprop.py 4.2 KB

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