functional_adadelta.py 3.4 KB

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