adagrad.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345
  1. import torch
  2. from torch import Tensor
  3. from .optimizer import Optimizer
  4. from typing import List, Optional
  5. class Adagrad(Optimizer):
  6. r"""Implements Adagrad algorithm.
  7. .. math::
  8. \begin{aligned}
  9. &\rule{110mm}{0.4pt} \\
  10. &\textbf{input} : \gamma \text{ (lr)}, \: \theta_0 \text{ (params)}, \: f(\theta)
  11. \text{ (objective)}, \: \lambda \text{ (weight decay)}, \\
  12. &\hspace{12mm} \tau \text{ (initial accumulator value)}, \: \eta\text{ (lr decay)}\\
  13. &\textbf{initialize} : state\_sum_0 \leftarrow 0 \\[-1.ex]
  14. &\rule{110mm}{0.4pt} \\
  15. &\textbf{for} \: t=1 \: \textbf{to} \: \ldots \: \textbf{do} \\
  16. &\hspace{5mm}g_t \leftarrow \nabla_{\theta} f_t (\theta_{t-1}) \\
  17. &\hspace{5mm} \tilde{\gamma} \leftarrow \gamma / (1 +(t-1) \eta) \\
  18. &\hspace{5mm} \textbf{if} \: \lambda \neq 0 \\
  19. &\hspace{10mm} g_t \leftarrow g_t + \lambda \theta_{t-1} \\
  20. &\hspace{5mm}state\_sum_t \leftarrow state\_sum_{t-1} + g^2_t \\
  21. &\hspace{5mm}\theta_t \leftarrow
  22. \theta_{t-1}- \tilde{\gamma} \frac{g_t}{\sqrt{state\_sum_t}+\epsilon} \\
  23. &\rule{110mm}{0.4pt} \\[-1.ex]
  24. &\bf{return} \: \theta_t \\[-1.ex]
  25. &\rule{110mm}{0.4pt} \\[-1.ex]
  26. \end{aligned}
  27. For further details regarding the algorithm we refer to `Adaptive Subgradient Methods for Online Learning
  28. and Stochastic Optimization`_.
  29. Args:
  30. params (iterable): iterable of parameters to optimize or dicts defining
  31. parameter groups
  32. lr (float, optional): learning rate (default: 1e-2)
  33. lr_decay (float, optional): learning rate decay (default: 0)
  34. weight_decay (float, optional): weight decay (L2 penalty) (default: 0)
  35. eps (float, optional): term added to the denominator to improve
  36. numerical stability (default: 1e-10)
  37. foreach (bool, optional): whether foreach implementation of optimizer is used (default: None)
  38. maximize (bool, optional): maximize the params based on the objective, instead of
  39. minimizing (default: False)
  40. .. _Adaptive Subgradient Methods for Online Learning and Stochastic
  41. Optimization: http://jmlr.org/papers/v12/duchi11a.html
  42. """
  43. def __init__(
  44. self,
  45. params,
  46. lr=1e-2,
  47. lr_decay=0,
  48. weight_decay=0,
  49. initial_accumulator_value=0,
  50. eps=1e-10,
  51. foreach: Optional[bool] = None,
  52. *,
  53. maximize: bool = False
  54. ):
  55. if not 0.0 <= lr:
  56. raise ValueError("Invalid learning rate: {}".format(lr))
  57. if not 0.0 <= lr_decay:
  58. raise ValueError("Invalid lr_decay value: {}".format(lr_decay))
  59. if not 0.0 <= weight_decay:
  60. raise ValueError("Invalid weight_decay value: {}".format(weight_decay))
  61. if not 0.0 <= initial_accumulator_value:
  62. raise ValueError(
  63. "Invalid initial_accumulator_value value: {}".format(
  64. initial_accumulator_value
  65. )
  66. )
  67. if not 0.0 <= eps:
  68. raise ValueError("Invalid epsilon value: {}".format(eps))
  69. defaults = dict(
  70. lr=lr,
  71. lr_decay=lr_decay,
  72. eps=eps,
  73. weight_decay=weight_decay,
  74. initial_accumulator_value=initial_accumulator_value,
  75. foreach=foreach,
  76. maximize=maximize,
  77. )
  78. super(Adagrad, self).__init__(params, defaults)
  79. for group in self.param_groups:
  80. for p in group["params"]:
  81. state = self.state[p]
  82. state["step"] = torch.tensor(0.0)
  83. init_value = (
  84. complex(initial_accumulator_value, initial_accumulator_value)
  85. if torch.is_complex(p)
  86. else initial_accumulator_value
  87. )
  88. state["sum"] = torch.full_like(
  89. p, init_value, memory_format=torch.preserve_format
  90. )
  91. def __setstate__(self, state):
  92. super().__setstate__(state)
  93. for group in self.param_groups:
  94. group.setdefault("foreach", None)
  95. group.setdefault("maximize", False)
  96. state_values = list(self.state.values())
  97. step_is_tensor = (len(state_values) != 0) and torch.is_tensor(
  98. state_values[0]["step"]
  99. )
  100. if not step_is_tensor:
  101. for s in state_values:
  102. s["step"] = torch.tensor(float(s["step"]))
  103. def share_memory(self):
  104. for group in self.param_groups:
  105. for p in group["params"]:
  106. state = self.state[p]
  107. state["sum"].share_memory_()
  108. @torch.no_grad()
  109. def step(self, closure=None):
  110. """Performs a single optimization step.
  111. Args:
  112. closure (callable, optional): A closure that reevaluates the model
  113. and returns the loss.
  114. """
  115. loss = None
  116. if closure is not None:
  117. with torch.enable_grad():
  118. loss = closure()
  119. for group in self.param_groups:
  120. params_with_grad = []
  121. grads = []
  122. state_sums = []
  123. state_steps = []
  124. has_sparse_grad = False
  125. for p in group["params"]:
  126. if p.grad is not None:
  127. if p.grad.is_sparse:
  128. has_sparse_grad = True
  129. params_with_grad.append(p)
  130. grads.append(p.grad)
  131. state = self.state[p]
  132. state_sums.append(state["sum"])
  133. state_steps.append(state["step"])
  134. adagrad(
  135. params_with_grad,
  136. grads,
  137. state_sums,
  138. state_steps,
  139. lr=group["lr"],
  140. weight_decay=group["weight_decay"],
  141. lr_decay=group["lr_decay"],
  142. eps=group["eps"],
  143. has_sparse_grad=has_sparse_grad,
  144. foreach=group["foreach"],
  145. maximize=group["maximize"],
  146. )
  147. return loss
  148. def adagrad(
  149. params: List[Tensor],
  150. grads: List[Tensor],
  151. state_sums: List[Tensor],
  152. state_steps: List[Tensor],
  153. # kwonly args with defaults are not supported by functions compiled with torchscript issue #70627
  154. # setting these as kwargs for now as functional API is compiled by torch/distributed/optim
  155. has_sparse_grad: bool = None,
  156. foreach: bool = None,
  157. *,
  158. lr: float,
  159. weight_decay: float,
  160. lr_decay: float,
  161. eps: float,
  162. maximize: bool,
  163. ):
  164. r"""Functional API that performs Adagrad algorithm computation.
  165. See :class:`~torch.optim.Adagrad` for details.
  166. """
  167. if not all([isinstance(t, torch.Tensor) for t in state_steps]):
  168. raise RuntimeError(
  169. "API has changed, `state_steps` argument must contain a list of singleton tensors"
  170. )
  171. if foreach is None:
  172. # Placeholder for more complex foreach logic to be added when value is not set
  173. foreach = False
  174. if foreach and torch.jit.is_scripting():
  175. raise RuntimeError("torch.jit.script not supported with foreach optimizers")
  176. if foreach and not torch.jit.is_scripting():
  177. func = _multi_tensor_adagrad
  178. else:
  179. func = _single_tensor_adagrad
  180. func(
  181. params,
  182. grads,
  183. state_sums,
  184. state_steps,
  185. lr=lr,
  186. weight_decay=weight_decay,
  187. lr_decay=lr_decay,
  188. eps=eps,
  189. has_sparse_grad=has_sparse_grad,
  190. maximize=maximize,
  191. )
  192. def _make_sparse(grad, grad_indices, values):
  193. size = grad.size()
  194. if grad_indices.numel() == 0 or values.numel() == 0:
  195. return torch.empty_like(grad)
  196. return torch.sparse_coo_tensor(grad_indices, values, size)
  197. def _single_tensor_adagrad(
  198. params: List[Tensor],
  199. grads: List[Tensor],
  200. state_sums: List[Tensor],
  201. state_steps: List[Tensor],
  202. *,
  203. lr: float,
  204. weight_decay: float,
  205. lr_decay: float,
  206. eps: float,
  207. has_sparse_grad: bool,
  208. maximize: bool,
  209. ):
  210. for (param, grad, state_sum, step_t) in zip(params, grads, state_sums, state_steps):
  211. # update step
  212. step_t += 1
  213. step = step_t.item()
  214. grad = grad if not maximize else -grad
  215. if weight_decay != 0:
  216. if grad.is_sparse:
  217. raise RuntimeError(
  218. "weight_decay option is not compatible with sparse gradients"
  219. )
  220. grad = grad.add(param, alpha=weight_decay)
  221. clr = lr / (1 + (step - 1) * lr_decay)
  222. if grad.is_sparse:
  223. grad = grad.coalesce() # the update is non-linear so indices must be unique
  224. grad_indices = grad._indices()
  225. grad_values = grad._values()
  226. size = grad.size()
  227. state_sum.add_(_make_sparse(grad, grad_indices, grad_values.pow(2)))
  228. std = state_sum.sparse_mask(grad)
  229. std_values = std._values().sqrt_().add_(eps)
  230. param.add_(
  231. _make_sparse(grad, grad_indices, grad_values / std_values), alpha=-clr
  232. )
  233. else:
  234. is_complex = torch.is_complex(param)
  235. if is_complex:
  236. grad = torch.view_as_real(grad)
  237. state_sum = torch.view_as_real(state_sum)
  238. param = torch.view_as_real(param)
  239. state_sum.addcmul_(grad, grad, value=1)
  240. std = state_sum.sqrt().add_(eps)
  241. param.addcdiv_(grad, std, value=-clr)
  242. if is_complex:
  243. param = torch.view_as_complex(param)
  244. state_sum = torch.view_as_complex(state_sum)
  245. def _multi_tensor_adagrad(
  246. params: List[Tensor],
  247. grads: List[Tensor],
  248. state_sums: List[Tensor],
  249. state_steps: List[Tensor],
  250. *,
  251. lr: float,
  252. weight_decay: float,
  253. lr_decay: float,
  254. eps: float,
  255. has_sparse_grad: bool,
  256. maximize: bool,
  257. ):
  258. # Foreach functions will throw errors if given empty lists
  259. if len(params) == 0:
  260. return
  261. if maximize:
  262. grads = torch._foreach_neg(grads)
  263. if has_sparse_grad is None:
  264. has_sparse_grad = any([grad.is_sparse for grad in grads])
  265. if has_sparse_grad:
  266. return _single_tensor_adagrad(
  267. params,
  268. grads,
  269. state_sums,
  270. state_steps,
  271. lr=lr,
  272. weight_decay=weight_decay,
  273. lr_decay=lr_decay,
  274. eps=eps,
  275. has_sparse_grad=has_sparse_grad,
  276. maximize=False,
  277. )
  278. # Update steps
  279. torch._foreach_add_(state_steps, 1)
  280. if weight_decay != 0:
  281. torch._foreach_add_(grads, params, alpha=weight_decay)
  282. minus_clr = [-lr / (1 + (step - 1) * lr_decay) for step in state_steps]
  283. grads = [torch.view_as_real(x) if torch.is_complex(x) else x for x in grads]
  284. state_sums = [
  285. torch.view_as_real(x) if torch.is_complex(x) else x for x in state_sums
  286. ]
  287. torch._foreach_addcmul_(state_sums, grads, grads, value=1)
  288. std = torch._foreach_add(torch._foreach_sqrt(state_sums), eps)
  289. toAdd = torch._foreach_div(torch._foreach_mul(grads, minus_clr), std)
  290. toAdd = [
  291. torch.view_as_complex(x) if torch.is_complex(params[i]) else x
  292. for i, x in enumerate(toAdd)
  293. ]
  294. torch._foreach_add_(params, toAdd)
  295. state_sums = [
  296. torch.view_as_complex(x) if torch.is_complex(params[i]) else x
  297. for i, x in enumerate(state_sums)
  298. ]