functional_rprop.py 3.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106
  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 Rprop 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 _FunctionalRprop:
  20. def __init__(
  21. self,
  22. params: list[Tensor],
  23. lr: float = 1e-2,
  24. etas: tuple[float, float] = (0.5, 1.2),
  25. step_sizes: tuple[float, float] = (1e-6, 50),
  26. foreach: bool = False,
  27. maximize: bool = False,
  28. _allow_empty_param_list: bool = False,
  29. ):
  30. _scripted_functional_optimizer_deprecation_warning(stacklevel=2)
  31. self.defaults = {
  32. "lr": lr,
  33. }
  34. self.etas = etas
  35. self.step_sizes = step_sizes
  36. self.foreach = foreach
  37. self.maximize = maximize
  38. if len(params) == 0 and not _allow_empty_param_list:
  39. raise ValueError("optimizer got an empty parameter list")
  40. # NOTE: we only have one param_group and don't allow user to add additional
  41. # param group as it's not a common use case.
  42. self.param_group = {"params": params}
  43. self.state = torch.jit.annotate(dict[torch.Tensor, dict[str, torch.Tensor]], {})
  44. def step(self, gradients: list[Tensor | None]):
  45. params = self.param_group["params"]
  46. params_with_grad = []
  47. grads = []
  48. prevs = []
  49. step_sizes = []
  50. state_steps = []
  51. lr = self.defaults["lr"]
  52. etaminus, etaplus = self.etas
  53. step_size_min, step_size_max = self.step_sizes
  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["prev"] = torch.zeros_like(
  72. param, memory_format=torch.preserve_format
  73. )
  74. state["step_size"] = torch.full_like(gradient, lr)
  75. state = self.state[param]
  76. prevs.append(state["prev"])
  77. step_sizes.append(state["step_size"])
  78. state_steps.append(state["step"])
  79. with torch.no_grad():
  80. F.rprop(
  81. params_with_grad,
  82. grads,
  83. prevs,
  84. step_sizes,
  85. state_steps,
  86. step_size_min=step_size_min,
  87. step_size_max=step_size_max,
  88. etaminus=etaminus,
  89. etaplus=etaplus,
  90. foreach=self.foreach,
  91. maximize=self.maximize,
  92. has_complex=has_complex,
  93. )