1# mypy: allow-untyped-decorators
2# mypy: allow-untyped-defs
3from typing import cast, List, Optional, Tuple, Union
4
5import torch
6from torch import Tensor
7from torch.optim.optimizer import (
8 _default_to_fused_or_foreach,
9 _device_dtype_check_for_fused,
10 _disable_dynamo_if_unsupported,
11 _get_capturable_supported_devices,
12 _get_scalar_dtype,
13 _get_value,
14 _use_grad_for_differentiable,
15 _view_as_real,
16 Optimizer,
17 ParamsT,
18)
19
20__all__ = ["ADOPT", "adopt"]
21
22
[docs]
23class ADOPT(Optimizer):
24 def __init__(
25 self,
26 params: ParamsT,
27 lr: Union[float, Tensor] = 1e-3,
28 betas: Tuple[float, float] = (0.9, 0.9999),
29 eps: float = 1e-6,
30 weight_decay: float = 0.0,
31 decoupled: bool = False,
32 *,
33 foreach: Optional[bool] = None,
34 maximize: bool = False,
35 capturable: bool = False,
36 differentiable: bool = False,
37 fused: Optional[bool] = None,
38 ):
39 if isinstance(lr, Tensor):
40 if foreach and not capturable:
41 raise ValueError(
42 "lr as a Tensor is not supported for capturable=False and foreach=True"
43 )
44 if lr.numel() != 1:
45 raise ValueError("Tensor lr must be 1-element")
46 if not 0.0 <= lr:
47 raise ValueError(f"Invalid learning rate: {lr}")
48 if not 0.0 <= eps:
49 raise ValueError(f"Invalid epsilon value: {eps}")
50 if not 0.0 <= betas[0] < 1.0:
51 raise ValueError(f"Invalid beta parameter at index 0: {betas[0]}")
52 if not 0.0 <= betas[1] < 1.0:
53 raise ValueError(f"Invalid beta parameter at index 1: {betas[1]}")
54 if not 0.0 <= weight_decay:
55 raise ValueError(f"Invalid weight_decay value: {weight_decay}")
56
57 defaults = dict(
58 lr=lr,
59 betas=betas,
60 eps=eps,
61 weight_decay=weight_decay,
62 decoupled=decoupled,
63 maximize=maximize,
64 foreach=foreach,
65 capturable=capturable,
66 differentiable=differentiable,
67 fused=fused,
68 )
69 super().__init__(params, defaults)
70
71 if fused:
72 # TODO: support fused
73 raise RuntimeError("`fused` is not currently supported")
74
75 if differentiable:
76 raise RuntimeError("`fused` does not support `differentiable`")
77 self._step_supports_amp_scaling = True
78 # TODO(crcrpar): [low prec params & their higher prec copy]
79 # Support AMP with FP16/BF16 model params which would need
80 # higher prec copy of params to do update math in higher prec to
81 # alleviate the loss of information.
82 if foreach:
83 raise RuntimeError("`fused` and `foreach` cannot be `True` together.")
84
85 def __setstate__(self, state):
86 super().__setstate__(state)
87 for group in self.param_groups:
88 group.setdefault("maximize", False)
89 group.setdefault("foreach", None)
90 group.setdefault("capturable", False)
91 group.setdefault("differentiable", False)
92 fused = group.setdefault("fused", None)
93 for p in group["params"]:
94 p_state = self.state.get(p, [])
95 if len(p_state) != 0 and not torch.is_tensor(p_state["step"]):
96 step_val = float(p_state["step"])
97 p_state["step"] = (
98 torch.tensor(
99 step_val,
100 dtype=_get_scalar_dtype(is_fused=fused),
101 device=p.device,
102 )
103 if group["capturable"] or group["fused"]
104 else torch.tensor(step_val, dtype=_get_scalar_dtype())
105 )
106
107 def _init_group(
108 self,
109 group,
110 params_with_grad,
111 grads,
112 exp_avgs,
113 exp_avg_sqs,
114 state_steps,
115 ):
116 has_complex = False
117 for p in group["params"]:
118 if p.grad is not None:
119 has_complex |= torch.is_complex(p)
120 params_with_grad.append(p)
121 if p.grad.is_sparse:
122 raise RuntimeError("ADOPT does not support sparse gradients")
123 grads.append(p.grad)
124
125 state = self.state[p]
126 # Lazy state initialization
127 if len(state) == 0:
128 if group["fused"]:
129 _device_dtype_check_for_fused(p)
130 # note(crcrpar): [special device hosting for step]
131 # Deliberately host `step` on CPU if both capturable and fused are off.
132 # This is because kernel launches are costly on CUDA and XLA.
133 state["step"] = (
134 torch.zeros(
135 (),
136 dtype=_get_scalar_dtype(is_fused=group["fused"]),
137 device=p.device,
138 )
139 if group["capturable"] or group["fused"]
140 else torch.tensor(0.0, dtype=_get_scalar_dtype())
141 )
142 # Exponential moving average of gradient values
143 state["exp_avg"] = torch.zeros_like(
144 p, memory_format=torch.preserve_format
145 )
146 # Exponential moving average of squared gradient values
147 state["exp_avg_sq"] = torch.zeros_like(
148 p, memory_format=torch.preserve_format
149 )
150
151 exp_avgs.append(state["exp_avg"])
152 exp_avg_sqs.append(state["exp_avg_sq"])
153
154 if group["differentiable"] and state["step"].requires_grad:
155 raise RuntimeError(
156 "`requires_grad` is not supported for `step` in differentiable mode"
157 )
158
159 # Foreach without capturable does not support a tensor lr
160 if (
161 group["foreach"]
162 and torch.is_tensor(group["lr"])
163 and not group["capturable"]
164 ):
165 raise RuntimeError(
166 "lr as a Tensor is not supported for capturable=False and foreach=True"
167 )
168
169 state_steps.append(state["step"])
170 return has_complex
171
172 @_use_grad_for_differentiable
[docs]
173 def step(self, closure=None):
174 """Perform a single optimization step.
175
176 Args:
177 closure (Callable, optional): A closure that reevaluates the model
178 and returns the loss.
179 """
180 self._cuda_graph_capture_health_check()
181
182 loss = None
183 if closure is not None:
184 with torch.enable_grad():
185 loss = closure()
186
187 for group in self.param_groups:
188 params_with_grad: List[Tensor] = []
189 grads: List[Tensor] = []
190 exp_avgs: List[Tensor] = []
191 exp_avg_sqs: List[Tensor] = []
192 state_steps: List[Tensor] = []
193 beta1, beta2 = group["betas"]
194
195 has_complex = self._init_group(
196 group,
197 params_with_grad,
198 grads,
199 exp_avgs,
200 exp_avg_sqs,
201 state_steps,
202 )
203
204 adopt(
205 params_with_grad,
206 grads,
207 exp_avgs,
208 exp_avg_sqs,
209 state_steps,
210 has_complex=has_complex,
211 beta1=beta1,
212 beta2=beta2,
213 lr=group["lr"],
214 weight_decay=group["weight_decay"],
215 decoupled=group["decoupled"],
216 eps=group["eps"],
217 maximize=group["maximize"],
218 foreach=group["foreach"],
219 capturable=group["capturable"],
220 differentiable=group["differentiable"],
221 fused=group["fused"],
222 grad_scale=getattr(self, "grad_scale", None),
223 found_inf=getattr(self, "found_inf", None),
224 )
225
226 return loss
227
228
229def _single_tensor_adopt(
230 params: List[Tensor],
231 grads: List[Tensor],
232 exp_avgs: List[Tensor],
233 exp_avg_sqs: List[Tensor],
234 state_steps: List[Tensor],
235 grad_scale: Optional[Tensor],
236 found_inf: Optional[Tensor],
237 *,
238 has_complex: bool,
239 beta1: float,
240 beta2: float,
241 lr: Union[float, Tensor],
242 weight_decay: float,
243 decoupled: bool,
244 eps: float,
245 maximize: bool,
246 capturable: bool,
247 differentiable: bool,
248):
249 assert grad_scale is None and found_inf is None
250
251 if torch.jit.is_scripting():
252 # this assert is due to JIT being dumb and not realizing that the ops below
253 # have overloads to handle both float and Tensor lrs, so we just assert it's
254 # a float since most people using JIT are using floats
255 assert isinstance(lr, float)
256
257 for i, param in enumerate(params):
258 grad = grads[i] if not maximize else -grads[i]
259 exp_avg = exp_avgs[i]
260 exp_avg_sq = exp_avg_sqs[i]
261 step_t = state_steps[i]
262
263 # If compiling, the compiler will handle cudagraph checks, see note [torch.compile x capturable]
264 if not torch._utils.is_compiling() and capturable:
265 capturable_supported_devices = _get_capturable_supported_devices()
266 assert (
267 param.device.type == step_t.device.type
268 and param.device.type in capturable_supported_devices
269 ), f"If capturable=True, params and state_steps must be on supported devices: {capturable_supported_devices}."
270
271 # update step
272 step_t += 1
273
274 if weight_decay != 0:
275 if decoupled:
276 param.add_(param, alpha=-lr * weight_decay) # ty: ignore[invalid-argument-type]
277 else:
278 grad = grad.add(param, alpha=weight_decay)
279
280 if torch.is_complex(param):
281 grad = torch.view_as_real(grad)
282 if exp_avg is not None:
283 exp_avg = torch.view_as_real(exp_avg)
284 if exp_avg_sq is not None:
285 exp_avg_sq = torch.view_as_real(exp_avg_sq)
286 param = torch.view_as_real(param)
287
288 step = step_t if capturable or differentiable else _get_value(step_t)
289 if step == 1:
290 exp_avg_sq.addcmul_(grad, grad.conj())
291 continue
292
293 denom = torch.clamp(exp_avg_sq.sqrt(), eps)
294 if step == 2:
295 exp_avg.addcdiv_(grad, denom)
296 else:
297 exp_avg.mul_(beta1).addcdiv_(grad, denom, value=1 - beta1)
298
299 param.add_(exp_avg, alpha=-lr) # ty: ignore[invalid-argument-type]
300 exp_avg_sq.mul_(beta2).addcmul_(grad, grad.conj(), value=1 - beta2)
301
302
303def _multi_tensor_adopt(
304 params: List[Tensor],
305 grads: List[Tensor],
306 exp_avgs: List[Tensor],
307 exp_avg_sqs: List[Tensor],
308 state_steps: List[Tensor],
309 grad_scale: Optional[Tensor],
310 found_inf: Optional[Tensor],
311 *,
312 has_complex: bool,
313 beta1: float,
314 beta2: float,
315 lr: Union[float, Tensor],
316 weight_decay: float,
317 decoupled: bool,
318 eps: float,
319 maximize: bool,
320 capturable: bool,
321 differentiable: bool,
322):
323 if len(params) == 0:
324 return
325
326 if isinstance(lr, Tensor) and not capturable:
327 raise RuntimeError(
328 "lr as a Tensor is not supported for capturable=False and foreach=True"
329 )
330
331 # If compiling, the compiler will handle cudagraph checks, see note [torch.compile x capturable]
332 if not torch._utils.is_compiling() and capturable:
333 capturable_supported_devices = _get_capturable_supported_devices(
334 supports_xla=False
335 )
336 assert all(
337 p.device.type == step.device.type
338 and p.device.type in capturable_supported_devices
339 for p, step in zip(params, state_steps)
340 ), f"If capturable=True, params and state_steps must be on supported devices: {capturable_supported_devices}."
341
342 assert grad_scale is None and found_inf is None
343
344 assert not differentiable, "_foreach ops don't support autograd"
345
346 grouped_tensors = Optimizer._group_tensors_by_device_and_dtype(
347 [params, grads, exp_avgs, exp_avg_sqs, state_steps] # type: ignore[list-item] # ty: ignore[invalid-argument-type]
348 )
349 for (
350 device_params_,
351 device_grads_,
352 device_exp_avgs_,
353 device_exp_avg_sqs_,
354 device_state_steps_,
355 ), _ in grouped_tensors.values():
356 device_params = cast(List[Tensor], device_params_)
357 device_grads = cast(List[Tensor], device_grads_)
358 device_exp_avgs = cast(List[Tensor], device_exp_avgs_)
359 device_exp_avg_sqs = cast(List[Tensor], device_exp_avg_sqs_)
360 device_state_steps = cast(List[Tensor], device_state_steps_)
361
362 # Handle complex parameters
363 if has_complex:
364 _view_as_real(
365 device_params, device_grads, device_exp_avgs, device_exp_avg_sqs
366 )
367
368 if maximize:
369 device_grads = torch._foreach_neg(device_grads) # type: ignore[assignment]
370
371 # Update steps
372 # If steps are on CPU, foreach will fall back to the slow path, which is a for-loop calling t.add(1) over
373 # and over. 1 will then be wrapped into a Tensor over and over again, which is slower than if we just
374 # wrapped it once now. The alpha is required to assure we go to the right overload.
375 if not torch._utils.is_compiling() and device_state_steps[0].is_cpu:
376 torch._foreach_add_(
377 device_state_steps, torch.tensor(1.0, device="cpu"), alpha=1.0
378 )
379 else:
380 torch._foreach_add_(device_state_steps, 1)
381
382 if weight_decay != 0:
383 if decoupled:
384 torch._foreach_add_( # ty: ignore[no-matching-overload]
385 device_params, device_params, alpha=-lr * weight_decay
386 )
387 else:
388 # Re-use the intermediate memory (device_grads) already allocated for maximize
389 if maximize:
390 torch._foreach_add_(device_grads, device_params, alpha=weight_decay)
391 else:
392 device_grads = torch._foreach_add( # type: ignore[assignment]
393 device_grads, device_params, alpha=weight_decay
394 )
395
396 if device_state_steps[0] == 1:
397 torch._foreach_addcmul_(device_exp_avg_sqs, device_grads, device_grads)
398 continue
399
400 exp_avg_sq_sqrt = torch._foreach_sqrt(device_exp_avg_sqs)
401 exp_avg_sq_sqrt = torch._foreach_maximum(exp_avg_sq_sqrt, eps)
402
403 if device_state_steps[0] == 2:
404 torch._foreach_addcdiv_(device_exp_avgs, device_grads, exp_avg_sq_sqrt)
405 else:
406 torch._foreach_mul_(device_exp_avgs, beta1)
407 torch._foreach_addcdiv_(
408 device_exp_avgs, device_grads, exp_avg_sq_sqrt, value=1 - beta1
409 )
410
411 torch._foreach_add_(device_params, device_exp_avgs, alpha=-lr) # ty: ignore[no-matching-overload]
412 torch._foreach_mul_(device_exp_avg_sqs, beta2)
413 torch._foreach_addcmul_(
414 device_exp_avg_sqs, device_grads, device_grads, value=1 - beta2
415 )
416
417
418@_disable_dynamo_if_unsupported(single_tensor_fn=_single_tensor_adopt)
[docs]
419def adopt(
420 params: List[Tensor],
421 grads: List[Tensor],
422 exp_avgs: List[Tensor],
423 exp_avg_sqs: List[Tensor],
424 state_steps: List[Tensor],
425 # kwonly args with defaults are not supported by functions compiled with torchscript issue #70627
426 # setting this as kwarg for now as functional API is compiled by torch/distributed/optim
427 foreach: Optional[bool] = None,
428 capturable: bool = False,
429 differentiable: bool = False,
430 fused: Optional[bool] = None,
431 grad_scale: Optional[Tensor] = None,
432 found_inf: Optional[Tensor] = None,
433 has_complex: bool = False,
434 *,
435 beta1: float,
436 beta2: float,
437 lr: Union[float, Tensor],
438 weight_decay: float,
439 decoupled: bool,
440 eps: float,
441 maximize: bool,
442):
443 r"""Functional API that performs ADOPT algorithm computation."""
444 # Respect when the user inputs False/True for foreach or fused. We only want to change
445 # the default when neither have been user-specified. Note that we default to foreach
446 # and pass False to use_fused. This is not a mistake--we want to give the fused impl
447 # bake-in time before making it the default, even if it is typically faster.
448 if fused is None and foreach is None:
449 _, foreach = _default_to_fused_or_foreach(
450 params, differentiable, use_fused=False
451 )
452 # Do not flip on foreach for the unsupported case where lr is a Tensor and capturable=False.
453 if foreach and isinstance(lr, Tensor) and not capturable:
454 foreach = False
455 if fused is None:
456 fused = False
457 if foreach is None:
458 foreach = False
459
460 # this check is slow during compilation, so we skip it
461 # if it's strictly needed we can add this check back in dynamo
462 if not torch._utils.is_compiling() and not all(
463 isinstance(t, torch.Tensor) for t in state_steps
464 ):
465 raise RuntimeError(
466 "API has changed, `state_steps` argument must contain a list of singleton tensors"
467 )
468
469 if foreach and torch.jit.is_scripting():
470 raise RuntimeError(
471 "torch.jit.script not supported with foreach optimizers"
472 )
473 if fused and torch.jit.is_scripting():
474 raise RuntimeError("torch.jit.script not supported with fused optimizers")
475
476 if fused and not torch.jit.is_scripting():
477 raise NotImplementedError("Fused ADOPT is not implemented.")
478 elif foreach and not torch.jit.is_scripting():
479 func = _multi_tensor_adopt
480 else:
481 func = _single_tensor_adopt
482
483 func(
484 params,
485 grads,
486 exp_avgs,
487 exp_avg_sqs,
488 state_steps,
489 has_complex=has_complex,
490 beta1=beta1,
491 beta2=beta2,
492 lr=lr,
493 weight_decay=weight_decay,
494 decoupled=decoupled,
495 eps=eps,
496 maximize=maximize,
497 capturable=capturable,
498 differentiable=differentiable,
499 grad_scale=grad_scale,
500 found_inf=found_inf,
501 )