functional_adamax.py 4.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122
  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 Adamax 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 _FunctionalAdamax:
  20. def __init__(
  21. self,
  22. params: list[Tensor],
  23. lr: float = 1e-3,
  24. betas: tuple[float, float] = (0.9, 0.999),
  25. eps: float = 1e-8,
  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. if not 0.0 <= lr:
  33. raise ValueError(f"Invalid learning rate: {lr}")
  34. if not 0.0 <= eps:
  35. raise ValueError(f"Invalid epsilon value: {eps}")
  36. if not 0.0 <= betas[0] < 1.0:
  37. raise ValueError(f"Invalid beta parameter at index 0: {betas[0]}")
  38. if not 0.0 <= betas[1] < 1.0:
  39. raise ValueError(f"Invalid beta parameter at index 1: {betas[1]}")
  40. if not 0.0 <= weight_decay:
  41. raise ValueError(f"Invalid weight_decay value: {weight_decay}")
  42. self.defaults = {
  43. "lr": lr,
  44. "eps": eps,
  45. "beta1": betas[0],
  46. "beta2": betas[1],
  47. "weight_decay": weight_decay,
  48. }
  49. self.foreach = foreach
  50. self.maximize = maximize
  51. self.state = torch.jit.annotate(dict[torch.Tensor, dict[str, torch.Tensor]], {})
  52. if len(params) == 0 and not _allow_empty_param_list:
  53. raise ValueError("optimizer got an empty parameter list")
  54. # NOTE: we only have one param_group and don't allow user to add additional
  55. # param group as it's not a common use case.
  56. self.param_group = {"params": params}
  57. def step(self, gradients: list[Tensor | None]):
  58. params = self.param_group["params"]
  59. params_with_grad = []
  60. grads = []
  61. exp_avgs = []
  62. exp_infs = []
  63. state_steps: list[Tensor] = []
  64. if len(params) != len(gradients):
  65. raise ValueError(
  66. "the gradients passed in does not equal to the size of the parameters!"
  67. + f"Params length: {len(params)}. "
  68. + f"Gradients length: {len(gradients)}"
  69. )
  70. has_complex = False
  71. for param, gradient in zip(self.param_group["params"], gradients):
  72. if gradient is not None:
  73. has_complex |= torch.is_complex(param)
  74. params_with_grad.append(param)
  75. grads.append(gradient)
  76. # Lazy state initialization
  77. if param not in self.state:
  78. self.state[param] = {}
  79. state = self.state[param]
  80. state["step"] = torch.tensor(0.0)
  81. # Exponential moving average of gradient values
  82. state["exp_avg"] = torch.zeros_like(
  83. param, memory_format=torch.preserve_format
  84. )
  85. # Exponential moving average of squared gradient values
  86. state["exp_inf"] = torch.zeros_like(
  87. param, memory_format=torch.preserve_format
  88. )
  89. state = self.state[param]
  90. exp_avgs.append(state["exp_avg"])
  91. exp_infs.append(state["exp_inf"])
  92. state_steps.append(state["step"])
  93. with torch.no_grad():
  94. F.adamax(
  95. params_with_grad,
  96. grads,
  97. exp_avgs,
  98. exp_infs,
  99. state_steps,
  100. eps=self.defaults["eps"],
  101. beta1=self.defaults["beta1"],
  102. beta2=self.defaults["beta2"],
  103. lr=self.defaults["lr"],
  104. weight_decay=self.defaults["weight_decay"],
  105. foreach=self.foreach,
  106. maximize=self.maximize,
  107. has_complex=has_complex,
  108. )