functional_adamax.py 4.3 KB

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