functional_adadelta.py 3.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106
  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 Adadelta 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 _FunctionalAdadelta:
  18. def __init__(
  19. self,
  20. params: List[Tensor],
  21. lr: float = 1.0,
  22. rho: float = 0.9,
  23. eps: float = 1e-6,
  24. weight_decay: float = 0.0,
  25. foreach: bool = False,
  26. maximize: bool = False,
  27. _allow_empty_param_list: bool = False,
  28. ):
  29. self.defaults = {
  30. "lr": lr,
  31. "rho": rho,
  32. "eps": eps,
  33. "weight_decay": weight_decay,
  34. }
  35. self.foreach = foreach
  36. self.maximize = maximize
  37. if len(params) == 0 and not _allow_empty_param_list:
  38. raise ValueError("optimizer got an empty parameter list")
  39. # NOTE: we only have one param_group and don't allow user to add additional
  40. # param group as it's not a common use case.
  41. self.param_group = {"params": params}
  42. self.state = torch.jit.annotate(Dict[torch.Tensor, Dict[str, torch.Tensor]], {})
  43. def step(self, gradients: List[Optional[Tensor]]):
  44. params = self.param_group["params"]
  45. params_with_grad = []
  46. grads = []
  47. square_avgs = []
  48. acc_deltas = []
  49. state_steps = []
  50. lr = self.defaults["lr"]
  51. rho = self.defaults["rho"]
  52. eps = self.defaults["eps"]
  53. weight_decay = self.defaults["weight_decay"]
  54. if len(params) != len(gradients):
  55. raise ValueError(
  56. "the gradients passed in does not equal to the size of the parameters!"
  57. + f"Params length: {len(params)}. "
  58. + f"Gradients length: {len(gradients)}"
  59. )
  60. has_complex = False
  61. for param, gradient in zip(params, gradients):
  62. if gradient is not None:
  63. has_complex |= torch.is_complex(param)
  64. params_with_grad.append(param)
  65. grads.append(gradient)
  66. # Lazy state initialization
  67. if param not in self.state:
  68. self.state[param] = {}
  69. state = self.state[param]
  70. state["step"] = torch.tensor(0.0)
  71. state["square_avg"] = torch.zeros_like(
  72. param, memory_format=torch.preserve_format
  73. )
  74. state["acc_delta"] = torch.zeros_like(
  75. param, memory_format=torch.preserve_format
  76. )
  77. state = self.state[param]
  78. square_avgs.append(state["square_avg"])
  79. acc_deltas.append(state["acc_delta"])
  80. state_steps.append(state["step"])
  81. with torch.no_grad():
  82. F.adadelta(
  83. params_with_grad,
  84. grads,
  85. square_avgs,
  86. acc_deltas,
  87. state_steps,
  88. lr=lr,
  89. rho=rho,
  90. eps=eps,
  91. weight_decay=weight_decay,
  92. foreach=self.foreach,
  93. maximize=self.maximize,
  94. has_complex=has_complex
  95. )