functional_adadelta.py 3.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110
  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 Adadelta 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 _FunctionalAdadelta:
  20. def __init__(
  21. self,
  22. params: list[Tensor],
  23. lr: float = 1.0,
  24. rho: float = 0.9,
  25. eps: float = 1e-6,
  26. weight_decay: float = 0.0,
  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. "rho": rho,
  35. "eps": eps,
  36. "weight_decay": weight_decay,
  37. }
  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[Tensor | None]):
  47. params = self.param_group["params"]
  48. params_with_grad = []
  49. grads = []
  50. square_avgs = []
  51. acc_deltas = []
  52. state_steps = []
  53. lr = self.defaults["lr"]
  54. rho = self.defaults["rho"]
  55. eps = self.defaults["eps"]
  56. weight_decay = self.defaults["weight_decay"]
  57. if len(params) != len(gradients):
  58. raise ValueError(
  59. "the gradients passed in does not equal to the size of the parameters!"
  60. + f"Params length: {len(params)}. "
  61. + f"Gradients length: {len(gradients)}"
  62. )
  63. has_complex = False
  64. for param, gradient in zip(params, gradients):
  65. if gradient is not None:
  66. has_complex |= torch.is_complex(param)
  67. params_with_grad.append(param)
  68. grads.append(gradient)
  69. # Lazy state initialization
  70. if param not in self.state:
  71. self.state[param] = {}
  72. state = self.state[param]
  73. state["step"] = torch.tensor(0.0)
  74. state["square_avg"] = torch.zeros_like(
  75. param, memory_format=torch.preserve_format
  76. )
  77. state["acc_delta"] = torch.zeros_like(
  78. param, memory_format=torch.preserve_format
  79. )
  80. state = self.state[param]
  81. square_avgs.append(state["square_avg"])
  82. acc_deltas.append(state["acc_delta"])
  83. state_steps.append(state["step"])
  84. with torch.no_grad():
  85. F.adadelta(
  86. params_with_grad,
  87. grads,
  88. square_avgs,
  89. acc_deltas,
  90. state_steps,
  91. lr=lr,
  92. rho=rho,
  93. eps=eps,
  94. weight_decay=weight_decay,
  95. foreach=self.foreach,
  96. maximize=self.maximize,
  97. has_complex=has_complex,
  98. )