functional_adagrad.py 3.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103
  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 Adagrad Optimizer
  7. # where we use these optimizer in a functional way.
  8. # Instead of using the `param.grad` when updating parameters,
  9. # we explicitly let the user pass gradients to the `step` function
  10. # this is so that we could separate the gradients and parameters
  11. # and allow multithreaded trainer to update the parameters
  12. # 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 _FunctionalAdagrad:
  17. def __init__(
  18. self,
  19. params: List[Tensor],
  20. lr: float = 1e-2,
  21. lr_decay: float = 0.0,
  22. weight_decay: float = 0.0,
  23. initial_accumulator_value: float = 0.0,
  24. warmup_lr_multiplier: float = 1.0,
  25. warmup_num_iters: float = 0.0,
  26. eps: float = 1e-10,
  27. coalesce_grad: bool = True,
  28. foreach: bool = False,
  29. maximize: bool = False,
  30. _allow_empty_param_list: bool = False,
  31. ):
  32. self.defaults = {
  33. "lr": lr,
  34. "lr_decay": lr_decay,
  35. "eps": eps,
  36. "weight_decay": weight_decay,
  37. "initial_accumulator_value": initial_accumulator_value,
  38. "warmup_lr_multiplier": warmup_lr_multiplier,
  39. "warmup_num_iters": warmup_num_iters,
  40. }
  41. self.coalesce_grad = coalesce_grad
  42. self.foreach = foreach
  43. self.maximize = maximize
  44. self.state = torch.jit.annotate(Dict[torch.Tensor, Dict[str, torch.Tensor]], {})
  45. if len(params) == 0 and not _allow_empty_param_list:
  46. raise ValueError("optimizer got an empty parameter list")
  47. # NOTE: we only have one param_group and don't allow user to add additional
  48. # param group as it's not a common use case.
  49. self.param_group = {"params": params}
  50. # TODO: no union or any types in TorchScript, make step a scalar tensor instead
  51. # This is also needed by if we want to share_memory on the step across processes
  52. for p in self.param_group["params"]:
  53. self.state[p] = {
  54. "sum": torch.full_like(p.data, initial_accumulator_value),
  55. "step": torch.tensor(0.0),
  56. }
  57. def step(self, gradients: List[Optional[Tensor]]):
  58. params = self.param_group["params"]
  59. params_with_grad = []
  60. grads = []
  61. state_sums = []
  62. state_steps: List[Tensor] = []
  63. if len(params) != len(gradients):
  64. raise ValueError(
  65. "the gradients passed in does not equal to the size of the parameters!"
  66. + f"Params length: {len(params)}. "
  67. + f"Gradients length: {len(gradients)}"
  68. )
  69. has_sparse_grad = False
  70. for param, gradient in zip(self.param_group["params"], gradients):
  71. if gradient is not None:
  72. if gradient.is_sparse:
  73. has_sparse_grad = True
  74. params_with_grad.append(param)
  75. grads.append(gradient)
  76. state = self.state[param]
  77. state_sums.append(state["sum"])
  78. state_steps.append(state["step"])
  79. with torch.no_grad():
  80. F.adagrad(
  81. params,
  82. grads,
  83. state_sums,
  84. state_steps,
  85. lr=self.defaults["lr"],
  86. weight_decay=self.defaults["weight_decay"],
  87. lr_decay=self.defaults["lr_decay"],
  88. eps=self.defaults["eps"],
  89. has_sparse_grad=has_sparse_grad,
  90. foreach=self.foreach,
  91. maximize=self.maximize,
  92. )