functional_adadelta.py 3.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111
  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 Adadelta 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 _FunctionalAdadelta:
  21. def __init__(
  22. self,
  23. params: list[Tensor],
  24. lr: float = 1.0,
  25. rho: float = 0.9,
  26. eps: float = 1e-6,
  27. weight_decay: float = 0.0,
  28. foreach: bool = False,
  29. maximize: bool = False,
  30. _allow_empty_param_list: bool = False,
  31. ):
  32. _scripted_functional_optimizer_deprecation_warning(stacklevel=2)
  33. self.defaults = {
  34. "lr": lr,
  35. "rho": rho,
  36. "eps": eps,
  37. "weight_decay": weight_decay,
  38. }
  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. acc_deltas = []
  53. state_steps = []
  54. lr = self.defaults["lr"]
  55. rho = self.defaults["rho"]
  56. eps = self.defaults["eps"]
  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. has_complex = False
  65. for param, gradient in zip(params, gradients):
  66. if gradient is not None:
  67. has_complex |= torch.is_complex(param)
  68. params_with_grad.append(param)
  69. grads.append(gradient)
  70. # Lazy state initialization
  71. if param not in self.state:
  72. self.state[param] = {}
  73. state = self.state[param]
  74. state["step"] = torch.tensor(0.0)
  75. state["square_avg"] = torch.zeros_like(
  76. param, memory_format=torch.preserve_format
  77. )
  78. state["acc_delta"] = torch.zeros_like(
  79. param, memory_format=torch.preserve_format
  80. )
  81. state = self.state[param]
  82. square_avgs.append(state["square_avg"])
  83. acc_deltas.append(state["acc_delta"])
  84. state_steps.append(state["step"])
  85. with torch.no_grad():
  86. F.adadelta(
  87. params_with_grad,
  88. grads,
  89. square_avgs,
  90. acc_deltas,
  91. state_steps,
  92. lr=lr,
  93. rho=rho,
  94. eps=eps,
  95. weight_decay=weight_decay,
  96. foreach=self.foreach,
  97. maximize=self.maximize,
  98. has_complex=has_complex,
  99. )