functional_rprop.py 3.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  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 Rprop 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 _FunctionalRprop:
  17. def __init__(
  18. self,
  19. params: List[Tensor],
  20. lr: float = 1e-2,
  21. etas: Tuple[float, float] = (0.5, 1.2),
  22. step_sizes: Tuple[float, float] = (1e-6, 50),
  23. foreach: bool = False,
  24. maximize: bool = False,
  25. _allow_empty_param_list: bool = False,
  26. ):
  27. self.defaults = {
  28. "lr": lr,
  29. }
  30. self.etas = etas
  31. self.step_sizes = step_sizes
  32. self.foreach = foreach
  33. self.maximize = maximize
  34. if len(params) == 0 and not _allow_empty_param_list:
  35. raise ValueError("optimizer got an empty parameter list")
  36. # NOTE: we only have one param_group and don't allow user to add additional
  37. # param group as it's not a common use case.
  38. self.param_group = {"params": params}
  39. self.state = torch.jit.annotate(Dict[torch.Tensor, Dict[str, torch.Tensor]], {})
  40. def step(self, gradients: List[Optional[Tensor]]):
  41. params = self.param_group["params"]
  42. params_with_grad = []
  43. grads = []
  44. prevs = []
  45. step_sizes = []
  46. lr = self.defaults["lr"]
  47. etaminus, etaplus = self.etas
  48. step_size_min, step_size_max = self.step_sizes
  49. if len(params) != len(gradients):
  50. raise ValueError(
  51. "the gradients passed in does not equal to the size of the parameters!"
  52. + f"Params length: {len(params)}. "
  53. + f"Gradients length: {len(gradients)}"
  54. )
  55. for param, gradient in zip(params, gradients):
  56. if gradient is not None:
  57. params_with_grad.append(param)
  58. grads.append(gradient)
  59. # Lazy state initialization
  60. if param not in self.state:
  61. self.state[param] = {}
  62. state = self.state[param]
  63. state["step"] = torch.tensor(0.0)
  64. state["prev"] = torch.zeros_like(
  65. param, memory_format=torch.preserve_format
  66. )
  67. state["step_size"] = torch.full_like(gradient, lr)
  68. state = self.state[param]
  69. prevs.append(state["prev"])
  70. step_sizes.append(state["step_size"])
  71. state["step"] += 1
  72. with torch.no_grad():
  73. F.rprop(
  74. params_with_grad,
  75. grads,
  76. prevs,
  77. step_sizes,
  78. step_size_min=step_size_min,
  79. step_size_max=step_size_max,
  80. etaminus=etaminus,
  81. etaplus=etaplus,
  82. foreach=self.foreach,
  83. maximize=self.maximize,
  84. )