functional_rprop.py 3.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102
  1. # mypy: allow-untyped-defs
  2. from typing import Dict, List, Optional, Tuple
  3. import torch
  4. import torch.optim._functional as F
  5. from torch import Tensor
  6. __all__: List[str] = []
  7. # Define a TorchScript compatible Functional Rprop Optimizer
  8. # where we use these optimizer in a functional way.
  9. # Instead of using the `param.grad` when updating parameters,
  10. # we explicitly allow the distributed optimizer pass gradients to
  11. # the `step` function. In this way, we could separate the gradients
  12. # and parameters and allow multithreaded trainer to update the
  13. # parameters without data traces on accumulating to the same .grad.
  14. # NOTE: This should be only used by distributed optimizer internals
  15. # and not meant to expose to the user.
  16. @torch.jit.script
  17. class _FunctionalRprop:
  18. def __init__(
  19. self,
  20. params: List[Tensor],
  21. lr: float = 1e-2,
  22. etas: Tuple[float, float] = (0.5, 1.2),
  23. step_sizes: Tuple[float, float] = (1e-6, 50),
  24. foreach: bool = False,
  25. maximize: bool = False,
  26. _allow_empty_param_list: bool = False,
  27. ):
  28. self.defaults = {
  29. "lr": lr,
  30. }
  31. self.etas = etas
  32. self.step_sizes = step_sizes
  33. self.foreach = foreach
  34. self.maximize = maximize
  35. if len(params) == 0 and not _allow_empty_param_list:
  36. raise ValueError("optimizer got an empty parameter list")
  37. # NOTE: we only have one param_group and don't allow user to add additional
  38. # param group as it's not a common use case.
  39. self.param_group = {"params": params}
  40. self.state = torch.jit.annotate(Dict[torch.Tensor, Dict[str, torch.Tensor]], {})
  41. def step(self, gradients: List[Optional[Tensor]]):
  42. params = self.param_group["params"]
  43. params_with_grad = []
  44. grads = []
  45. prevs = []
  46. step_sizes = []
  47. state_steps = []
  48. lr = self.defaults["lr"]
  49. etaminus, etaplus = self.etas
  50. step_size_min, step_size_max = self.step_sizes
  51. if len(params) != len(gradients):
  52. raise ValueError(
  53. "the gradients passed in does not equal to the size of the parameters!"
  54. + f"Params length: {len(params)}. "
  55. + f"Gradients length: {len(gradients)}"
  56. )
  57. has_complex = False
  58. for param, gradient in zip(params, gradients):
  59. if gradient is not None:
  60. has_complex |= torch.is_complex(param)
  61. params_with_grad.append(param)
  62. grads.append(gradient)
  63. # Lazy state initialization
  64. if param not in self.state:
  65. self.state[param] = {}
  66. state = self.state[param]
  67. state["step"] = torch.tensor(0.0)
  68. state["prev"] = torch.zeros_like(
  69. param, memory_format=torch.preserve_format
  70. )
  71. state["step_size"] = torch.full_like(gradient, lr)
  72. state = self.state[param]
  73. prevs.append(state["prev"])
  74. step_sizes.append(state["step_size"])
  75. state_steps.append(state["step"])
  76. with torch.no_grad():
  77. F.rprop(
  78. params_with_grad,
  79. grads,
  80. prevs,
  81. step_sizes,
  82. state_steps,
  83. step_size_min=step_size_min,
  84. step_size_max=step_size_max,
  85. etaminus=etaminus,
  86. etaplus=etaplus,
  87. foreach=self.foreach,
  88. maximize=self.maximize,
  89. has_complex=has_complex,
  90. )