Skip to content

Base Optimizer

Use BaseOptimizer to implement an optimizer with shared validation and update helpers. Check this reference for weight decay, bias correction, and gradient operations.

BaseOptimizer

Bases: ABC, Optimizer

Shared update, validation, and state helpers for optimizers.

Source code in pytorch_optimizer/base/optimizer.py
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
class BaseOptimizer(ABC, Optimizer):
    """Shared update, validation, and state helpers for optimizers."""

    state: State
    _supports_compiled_foreach: bool = False
    _step_foreach: Callable

    def __init__(self, params: ParamsT, defaults: Defaults) -> None:
        super().__init__(params, defaults)

    def _compile_foreach(self, compile_kwargs: dict | None = None) -> None:
        self._step_foreach = compile_foreach_step(self._step_foreach, compile_kwargs)

    def load_state_dict(self, state_dict: dict) -> None:
        """Restore state while preserving non-floating tensor types and container metadata."""
        super().load_state_dict(state_dict)
        for group, saved_group in zip(self.param_groups, state_dict['param_groups']):
            for p, key in zip(group['params'], saved_group['params']):
                if key in state_dict['state']:
                    self.state[p] = self._restore_state_types(self.state[p], state_dict['state'][key])

    def _restore_state_types(self, value, saved_value):
        if isinstance(saved_value, torch.Tensor):
            if not saved_value.is_floating_point() and not saved_value.is_complex():
                return saved_value.to(device=value.device)
            return value
        if isinstance(saved_value, str):
            return saved_value
        if isinstance(saved_value, dict):
            return {key: self._restore_state_types(value[key], saved) for key, saved in saved_value.items()}
        if isinstance(saved_value, (tuple, list, deque)):
            restored = [self._restore_state_types(item, saved) for item, saved in zip(value, saved_value)]
            return deque(restored, maxlen=saved_value.maxlen) if isinstance(saved_value, deque) else type(saved_value)(
                restored
            )
        return value

    @staticmethod
    def load_optimizer(optimizer: OptimizerInstanceOrClass, **kwargs) -> Optimizer:
        """Return an optimizer instance or instantiate an optimizer class.

        Args:
            optimizer: Optimizer instance or class.
            **kwargs (dict): Constructor options. Must include `params` when passing a class.

        Returns:
            Optimizer: Existing or newly constructed optimizer.

        Raises:
            ValueError: An optimizer class is supplied without `params`.

        """
        if isinstance(optimizer, Optimizer):
            return optimizer

        if 'params' in kwargs:
            params = kwargs.pop('params')
            return optimizer(params, **kwargs)

        raise ValueError('need to pass `params` when you pass the `torch.optim.Optimizer` instance.')

    @staticmethod
    def get_device_from_param_groups(param_groups: list[ParamGroup]) -> torch.device:
        """Return the first parameter's device, defaulting to CPU when all parameter groups are empty."""
        return next((p.device for group in param_groups for p in group['params']), torch.device('cpu'))

    @staticmethod
    @torch.no_grad()
    def set_hessian(param_groups: list[ParamGroup], state: State, hessian: list[torch.Tensor]) -> None:
        """Store externally computed Hessian estimates in the optimizer state.

        Args:
            param_groups: Optimizer parameter groups.
            state: Optimizer state dictionary to update.
            hessian: One tensor per parameter, in parameter group order, with matching shapes.

        Raises:
            ValueError: A Hessian tensor and its parameter have different shapes.

        Examples:
            ```python
            BaseOptimizer.set_hessian(optimizer.param_groups, optimizer.state, hessian)
            ```

        """
        i: int = 0
        for group in param_groups or []:
            for p in group['params']:
                if p.size() != hessian[i].size():
                    raise ValueError(
                        f'the shape of parameter and hessian does not match. {p.size()} vs {hessian[i].size()}'
                    )

                state[p]['hessian'] = hessian[i]
                i += 1

    @staticmethod
    def zero_hessian(param_groups: list[ParamGroup], state: State, pre_zero: bool = True) -> None:
        """Initialize Hessian buffers and optionally clear existing estimates.

        Args:
            param_groups: Parameter groups from the optimizer.
            state: Optimizer state dictionary.
            pre_zero: Clear existing Hessian estimates before accumulating new ones.

        """
        for group in param_groups or []:
            for p in group['params']:
                if p.requires_grad and p.grad is not None and not p.grad.is_sparse:
                    if 'hessian' not in state[p]:
                        state[p]['hessian'] = torch.zeros_like(p)
                    elif pre_zero:
                        state[p]['hessian'].zero_()

    @staticmethod
    @torch.no_grad()
    def compute_hutchinson_hessian(
        param_groups: list[ParamGroup],
        state: State,
        num_samples: int = 1,
        alpha: float = 1.0,
        distribution: HutchinsonG = 'gaussian',
    ) -> None:
        """Accumulate Hutchinson estimates of the Hessian diagonal in the optimizer state.

        Args:
            param_groups: Parameter groups from the optimizer.
            state: Optimizer state dictionary.
            num_samples: Number of noise vectors for the Hessian diagonal estimate.
            alpha: Scale of the estimate to add to existing Hessian buffers.
            distribution: Noise distribution: `'gaussian'` or `'rademacher'`.

        """
        if distribution not in ('gaussian', 'rademacher'):
            raise NotImplementedError(f'hessian with distribution {distribution} is not implemented.')

        params: list[torch.Tensor] = [
            p
            for group in param_groups or []
            for p in group['params']
            if p.requires_grad and p.grad is not None and not p.grad.is_sparse
        ]
        if len(params) == 0:
            return

        grads = [p.grad for p in params]

        for i in range(num_samples):
            if distribution == 'rademacher':
                zs = [torch.randint_like(p, 0, 2) * 2.0 - 1.0 for p in params]
            else:
                zs = [torch.randn_like(p) for p in params]

            h_zs = torch.autograd.grad(grads, params, grad_outputs=zs, retain_graph=i < num_samples - 1)
            for h_z, z, p in zip(h_zs, zs, params):
                state[p]['hessian'].addcmul_(h_z, z, value=alpha / num_samples)

    @staticmethod
    def apply_weight_decay(
        p: torch.Tensor,
        grad: torch.Tensor | None,
        lr: float | torch.Tensor,
        weight_decay: float,
        weight_decouple: bool,
        fixed_decay: bool,
        ratio: float | None = None,
    ) -> None:
        """Apply coupled or decoupled weight decay in place.

        Args:
            p: Parameter tensor to apply weight decay to.
            grad: Gradient to modify for coupled decay. May be `None` for decoupled decay.
            lr: Learning rate to scale the update.
            weight_decay: Weight decay coefficient (L2 penalty).
            weight_decouple: If True, applies decoupled weight decay as in AdamW.
            fixed_decay: If True, fixes weight decay to not depend on learning rate.
            ratio: Optional scaling factor for decoupled weight decay.

        """
        if weight_decay == 0.0:
            return

        if weight_decouple:
            p.mul_(1.0 - weight_decay * (1.0 if fixed_decay else lr) * (ratio if ratio is not None else 1.0))
        elif weight_decay > 0.0 and grad is not None:
            grad.add_(p, alpha=weight_decay)

    @staticmethod
    def apply_ams_bound(
        ams_bound: bool,
        exp_avg_sq: torch.Tensor,
        max_exp_avg_sq: torch.Tensor | None,
        eps: float,
        exp_avg_sq_eps: float = 1e-15,
    ) -> torch.Tensor:
        """Compute an adaptive denominator, with optional running maximum second moments.

        Args:
            ams_bound: Whether to apply the AMSBound variant.
            exp_avg_sq: Exponential moving average of squared gradients.
            max_exp_avg_sq: Running elementwise maximum of `exp_avg_sq`, updated in place for AMSBound.
            eps: Small epsilon value for numerical stability.
            exp_avg_sq_eps: Epsilon used specifically for numerical stability in exp_avg_sq computations.

        """
        if ams_bound:
            if torch.is_complex(max_exp_avg_sq):
                max_exp_avg_sq = torch.view_as_real(max_exp_avg_sq)

            torch.maximum(max_exp_avg_sq, exp_avg_sq, out=max_exp_avg_sq)
            de_nom = max_exp_avg_sq.add(exp_avg_sq_eps)
        else:
            de_nom = exp_avg_sq.add(exp_avg_sq_eps)

        return de_nom.sqrt_().add_(eps)

    @staticmethod
    def apply_ams_bound_foreach(
        ams_bound: bool,
        exp_avg_sqs: list[torch.Tensor],
        max_exp_avg_sqs: list[torch.Tensor],
        eps: float,
        exp_avg_sq_eps: float = 1e-15,
    ) -> Sequence[torch.Tensor]:
        """Compute batched adaptive denominators with optional running maximum second moments.

        Args:
            ams_bound: Whether to apply the AMSBound variant.
            exp_avg_sqs: Exponential moving averages of squared gradients.
            max_exp_avg_sqs: Running elementwise maxima, updated in place for AMSBound.
            eps: Small epsilon value for numerical stability.
            exp_avg_sq_eps: Epsilon added to second moments before taking square roots.

        """
        if ams_bound:
            torch._foreach_maximum_(max_exp_avg_sqs, exp_avg_sqs)
            de_noms = torch._foreach_add(max_exp_avg_sqs, exp_avg_sq_eps)
        else:
            de_noms = torch._foreach_add(exp_avg_sqs, exp_avg_sq_eps)

        torch._foreach_sqrt_(de_noms)
        torch._foreach_add_(de_noms, eps)

        return de_noms

    @staticmethod
    def debias(beta: float, step: int) -> float:
        """Return the moment bias correction factor `1 - beta ** step`.

        Args:
            beta: Exponential decay rate for moment estimates.
            step: Current optimization step number.

        """
        return 1.0 - math.pow(beta, step)  # fmt: skip

    @staticmethod
    def debias_beta(beta: float, step: int) -> float:
        """Return the decay rate for a bias corrected moving average.

        Computes `beta * (1 - beta ** (step - 1)) / (1 - beta ** step)`.

        Args:
            beta: Exponential decay rate.
            step: Optimization step, starting at 1.

        Returns:
            float: Bias corrected decay rate.

        """
        beta_n: float = beta ** step
        return (beta_n - beta) / (beta_n - 1.0)  # fmt: skip

    @staticmethod
    def apply_adam_debias(adam_debias: bool, step_size: float, bias_correction1: float) -> float:
        """Apply AdamD variant.

        Args:
            adam_debias: If True, only corrects the denominator to avoid inflating step sizes early in training.
            step_size: The step size for the update.
            bias_correction1: The bias correction factor for the first moment.

        """
        return step_size if adam_debias else step_size / bias_correction1

    @staticmethod
    def get_rectify_step_size(
        is_rectify: bool,
        step: int,
        lr: float,
        beta2: float,
        n_sma_threshold: int,
        degenerated_to_sgd: bool,
    ) -> tuple[float, float]:
        """Compute the RAdam step size and effective moving average length.

        Args:
            is_rectify: Whether to apply the rectify variant.
            step: Current step number.
            lr: Base learning rate.
            beta2: Decay rate of the second moment.
            n_sma_threshold: Simple Moving Average (SMA) threshold for rectification.
            degenerated_to_sgd: Whether to degenerate to SGD if below threshold.

        """
        step_size: float = lr
        n_sma: float = 0.0

        if is_rectify:
            n_sma_max: float = 2.0 / (1.0 - beta2) - 1.0
            beta2_t: float = beta2 ** step  # fmt: skip
            n_sma: float = n_sma_max - 2 * step * beta2_t / (1.0 - beta2_t)

            if n_sma >= n_sma_threshold:
                rt = math.sqrt(
                    (1.0 - beta2_t) * (n_sma - 4) / (n_sma_max - 4) * (n_sma - 2) / n_sma * n_sma_max / (n_sma_max - 2)
                )
            elif degenerated_to_sgd:
                rt = 1.0
            else:
                rt = -1.0

            step_size = step_size * rt

        return step_size, n_sma

    @staticmethod
    def get_adanorm_gradient(
        grad: torch.Tensor, adanorm: bool, exp_grad_norm: torch.Tensor | None = None, r: float | None = 0.95
    ) -> torch.Tensor:
        """Rescale gradients whose norm falls below its running average.

        Args:
            grad: Gradient.
            adanorm: Whether to use the AdaNorm variant.
            exp_grad_norm: Exponential moving average of gradient norm.
            r: Decay rate for the gradient norm average.

        """
        if not adanorm or exp_grad_norm is None:
            return grad

        if r is None:
            r = 0.95

        grad_norm = torch.linalg.norm(grad)

        exp_grad_norm.mul_(r).add_(grad_norm, alpha=1.0 - r)

        if grad_norm > 0 and exp_grad_norm > grad_norm:
            return grad.mul(exp_grad_norm.reshape(())).div_(grad_norm)

        return grad

    @staticmethod
    def get_rms(x: Sequence[torch.Tensor] | torch.Tensor) -> Sequence[torch.Tensor] | torch.Tensor:
        """Compute the root mean square of a tensor or each tensor in a list."""
        if isinstance(x, torch.Tensor):
            return x.norm(2).div_(math.sqrt(x.numel()))

        factors: list[float] = [math.sqrt(p.numel()) for p in x]
        norms = torch._foreach_norm(x, ord=2)
        torch._foreach_div_(norms, factors)

        return norms

    @staticmethod
    def approximate_sq_grad(
        exp_avg_sq_row: list[torch.Tensor] | torch.Tensor,
        exp_avg_sq_col: list[torch.Tensor] | torch.Tensor,
        output: list[torch.Tensor] | torch.Tensor,
    ) -> None:
        """Write a factored inverse root second moment approximation to `output`.

        Args:
            exp_avg_sq_row: Row second moments, as a tensor or list of tensors.
            exp_avg_sq_col: Corresponding column second moments.
            output: Tensor or list of tensors to update in place.

        """
        if isinstance(exp_avg_sq_row, torch.Tensor):
            r_factor: torch.Tensor = (
                (exp_avg_sq_row / exp_avg_sq_row.mean(dim=-1, keepdim=True)).rsqrt_().unsqueeze(-1)
            )
            c_factor: torch.Tensor = exp_avg_sq_col.unsqueeze(-2).rsqrt()
            torch.mul(r_factor, c_factor, out=output)
            return

        row_means = [r.mean(dim=-1, keepdim=True) for r in exp_avg_sq_row]

        r_factors = torch._foreach_div(exp_avg_sq_row, row_means)
        foreach_rsqrt_(r_factors)
        r_factors = [r_factor.unsqueeze(-1) for r_factor in r_factors]

        c_factors = [c_factor.unsqueeze(-2) for c_factor in foreach_rsqrt(exp_avg_sq_col)]

        for r_factor, c_factor, update in zip(r_factors, c_factors, output):
            torch.mul(r_factor, c_factor, out=update)

    @staticmethod
    def apply_cautious(update: torch.Tensor, grad: torch.Tensor) -> None:
        """Mask updates that disagree with the gradient sign and rescale them in place.

        Args:
            update: Update tensor, masked in place.
            grad: Gradient tensor.

        """
        mask = (update * grad > 0).to(grad.dtype)
        mask.mul_(mask.numel() / (mask.sum() + 1))
        update.mul_(mask)

    @staticmethod
    @torch.no_grad()
    def apply_orthogonal_gradients(params: Iterable[torch.Tensor], eps: float = 1e-16) -> None:
        """Project gradients orthogonally to parameters and restore their norms.

        Args:
            params: Parameters whose dense real gradients are modified in place.
            eps: Small value to prevent division by zero.

        """
        for p in params:
            if p.grad is None or p.grad.is_sparse or torch.is_complex(p):
                continue

            dtype = torch.float64 if p.dtype == torch.float64 else torch.float32
            w = p.reshape(-1).to(dtype=dtype)
            g = p.grad.reshape(-1).to(dtype=dtype)

            proj = torch.dot(w, g).div_(torch.dot(w, w).add_(eps))
            g_ortho = g.sub(w * proj)

            g_norm = g.norm(2)
            g_ortho_norm = g_ortho.norm(2)
            rounding_eps = 4.0 * torch.finfo(dtype).eps
            # A parallel gradient has no orthogonal direction to normalize.
            g_ortho.masked_fill_(g_ortho_norm <= rounding_eps * g_norm, 0.0)
            g_ortho.mul_(g_norm / g_ortho_norm.add_(eps))

            p.grad.copy_(g_ortho.view_as(p.grad))

    @staticmethod
    def can_use_foreach(
        group: ParamGroup,
        foreach: bool | None,
        *,
        dtypes: tuple[torch.dtype, ...] | None = None,
        default_on_cuda: bool = False,
    ) -> bool:
        """Check whether a parameter group supports batched tensor updates.

        Args:
            group: Parameter group to inspect.
            foreach: Set to `False` to disable batched updates. `True` and `None` check tensor compatibility.
            dtypes: Allowed parameter dtypes. `None` allows all real dtypes.
            default_on_cuda: Enable automatic batching only for groups with CUDA gradients. Explicit `True` allows CPU.

        Returns:
            bool: `True` if at least one parameter has a gradient and all such parameters
                are real with dense gradients.

        """
        if foreach is False:
            return False

        has_param: bool = False
        for p in group['params']:
            g = p.grad
            if g is None:
                continue

            has_param = True
            if g.is_sparse or torch.is_complex(p):
                return False

            if dtypes is not None and p.dtype not in dtypes:
                return False

        if foreach is None and default_on_cuda:
            return any(p.is_cuda for p in group['params'] if p.grad is not None)

        return has_param

    @staticmethod
    def collect_trainable_params(
        group: ParamGroup,
        state: State,
        state_keys: list[str] | None = None,
    ) -> tuple[list[torch.Tensor], list[torch.Tensor], dict[str, list[torch.Tensor]]]:
        """Collect parameters with gradients and their requested state tensors.

        Args:
            group: Optimizer parameter group.
            state: Optimizer state dictionary.
            state_keys: State entries to collect. `None` collects no state tensors.

        Returns:
            tuple: Parameters, gradients, and a dictionary of lists of available state tensors.

        """
        if state_keys is None:
            state_keys = []

        params: list[torch.Tensor] = []
        grads: list[torch.Tensor] = []
        state_dict: dict[str, list[torch.Tensor]] = {key: [] for key in state_keys}

        for p in group['params']:
            if p.grad is None:
                continue

            params.append(p)
            grads.append(p.grad)

            if state_keys:
                p_state = state[p]
                for key in state_keys:
                    if key in p_state:
                        state_dict[key].append(p_state[key])

        return params, grads, state_dict

    @staticmethod
    def apply_weight_decay_foreach(
        params: list[torch.Tensor],
        grads: list[torch.Tensor],
        lr: list[float] | list[torch.Tensor] | tuple[torch.Tensor, ...] | float | torch.Tensor,
        weight_decay: float,
        weight_decouple: bool,
        fixed_decay: bool,
    ) -> None:
        """Apply weight decay to a list of parameters.

        Args:
            params: List of parameter tensors.
            grads: List of gradient tensors.
            lr: Learning rate.
            weight_decay: Weight decay coefficient.
            weight_decouple: If True, applies decoupled weight decay as in AdamW.
            fixed_decay: If True, fixes weight decay to not depend on learning rate.

        """
        if weight_decay == 0.0:
            return

        if not weight_decouple:
            torch._foreach_add_(grads, params, alpha=weight_decay)
            return

        if fixed_decay:
            factor = 1.0 - weight_decay
        elif isinstance(lr, Sequence):
            factor = torch._foreach_mul(lr, -weight_decay)
            torch._foreach_add_(factor, 1.0)
        else:
            factor = 1.0 - weight_decay * lr

        torch._foreach_mul_(params, factor)

    @staticmethod
    def get_stable_adamw_rms(grad: torch.Tensor, exp_avg_sq: torch.Tensor, eps: float = 1e-16) -> torch.Tensor:
        """Get StableAdamW RMS as a scalar tensor on the gradient's device.

        Args:
            grad: Gradient.
            exp_avg_sq: Exponential moving average of squared gradient.
            eps: Small value to prevent division by zero.

        Returns:
            torch.Tensor: RMS scale, computed in float32 for float16 and bfloat16 gradients.

        """
        if grad.dtype in (torch.float16, torch.bfloat16):
            grad, exp_avg_sq = grad.float(), exp_avg_sq.float()

        return grad.pow(2).div_(exp_avg_sq.clip(min=eps)).mean().sqrt_().clip_(min=1.0)

    @staticmethod
    def validate_range(x: float, name: str, low: float, high: float, range_type: str = '[)') -> None:
        """Raise `ValueError` if a value falls outside the requested interval."""
        if range_type == '[)' and not low <= x < high:
            raise ValueError(f'{name} must be in the range [{low}, {high})')
        if range_type == '[]' and not low <= x <= high:
            raise ValueError(f'{name} must be in the range [{low}, {high}]')
        if range_type == '(]' and not low < x <= high:
            raise ValueError(f'{name} must be in the range ({low}, {high}]')
        if range_type == '()' and not low < x < high:
            raise ValueError(f'{name} must be in the range ({low}, {high})')

    @staticmethod
    def validate_non_negative(x: float | None, name: str) -> None:
        """Raise `ValueError` for a negative value. Accept `None`."""
        if x is not None and x < 0.0:
            raise ValueError(f'{name} must be non-negative')

    @staticmethod
    def validate_non_positive(x: float | None, name: str) -> None:
        """Raise `ValueError` for a positive value. Accept `None`."""
        if x is not None and x > 0.0:
            raise ValueError(f'{name} must be non-positive')

    @staticmethod
    def validate_positive(x: float | int, name: str) -> None:
        """Raise `ValueError` if a value is zero or negative."""
        if x <= 0:
            raise ValueError(f'{name} must be positive')

    @staticmethod
    def validate_boundary(constant: float, boundary: float, bound_type: str = 'upper') -> None:
        """Raise `ValueError` if a value exceeds an upper bound or falls below a lower bound."""
        if bound_type == 'upper' and constant > boundary:
            raise ValueError(f'constant {constant} must be in a range of (-inf, {boundary}]')
        if bound_type == 'lower' and constant < boundary:
            raise ValueError(f'constant {constant} must be in a range of [{boundary}, inf)')

    @staticmethod
    def validate_step(step: int, step_type: str) -> None:
        """Raise `NegativeStepError` if the step number is less than 1."""
        if step < 1:
            raise NegativeStepError(step, step_type=step_type)

    @staticmethod
    def validate_options(x: str, name: str, options: list[str]) -> None:
        """Raise `ValueError` if an option is outside the allowed choices."""
        if x not in options:
            opts: str = ' or '.join([f"'{option}'" for option in options]).strip()
            raise ValueError(f'{name} {x} must be one of ({opts})')

    @staticmethod
    def validate_learning_rate(learning_rate: float | torch.Tensor | None) -> None:
        """Raise `NegativeLRError` for a negative learning rate. Accept `None`."""
        if learning_rate is not None and learning_rate < 0.0:
            raise NegativeLRError(learning_rate)

    @staticmethod
    def validate_mod(x: int, y: int) -> None:
        """Raise `ValueError` if `x` is not divisible by `y`."""
        if x % y != 0:
            raise ValueError(f'{x} must be divisible by {y}')

    def validate_betas(
        self,
        betas: Betas | tuple[None, float],
        beta_range_type: str = '[)',
        beta3_range_type: str = '[]',
    ) -> None:
        """Validate the first two beta values and an optional third value against their intervals."""
        if betas[0] is not None:
            self.validate_range(betas[0], 'beta1', 0.0, 1.0, range_type=beta_range_type)

        self.validate_range(betas[1], 'beta2', 0.0, 1.0, range_type=beta_range_type)

        if len(betas) < 3:
            return

        if betas[2] is not None:
            self.validate_range(betas[2], 'beta3', 0.0, 1.0, range_type=beta3_range_type)

    def validate_nus(self, nus: float | tuple[float, float]) -> None:
        """Validate one or two quasi-hyperbolic discount factors in `[0, 1]`."""
        if isinstance(nus, tuple):
            nu1, nu2 = nus
            self.validate_range(nu1, 'nu1', 0.0, 1.0, range_type='[]')
            self.validate_range(nu2, 'nu2', 0.0, 1.0, range_type='[]')
        else:
            self.validate_range(nus, 'nu', 0.0, 1.0, range_type='[]')

    @abstractmethod
    def init_group(self, group: ParamGroup, **kwargs) -> None:  # pragma: no cover
        """Initialize optimizer state for a parameter group."""
        return

    @staticmethod
    def view_as_real(param, *state_and_grads) -> tuple:
        """Return real views of complex parameters, gradients, and state tensors."""
        if torch.is_complex(param):
            param = torch.view_as_real(param)
            state_and_grads = tuple(
                torch.view_as_real(s) if (s is not None and torch.is_complex(s)) else s if s is not None else None
                for s in state_and_grads
            )

        return param, *state_and_grads

    @staticmethod
    def maximize_gradient(grad: torch.Tensor, maximize: bool = False) -> None:
        """Negate the gradient in place when maximizing the objective."""
        if maximize:
            grad.neg_()

    def step(self, closure: Closure = None) -> Loss:  # pragma: no cover
        raise NotImplementedError

apply_adam_debias(adam_debias, step_size, bias_correction1) staticmethod

Apply AdamD variant.

Parameters:

Name Type Description Default
adam_debias bool

If True, only corrects the denominator to avoid inflating step sizes early in training.

required
step_size float

The step size for the update.

required
bias_correction1 float

The bias correction factor for the first moment.

required
Source code in pytorch_optimizer/base/optimizer.py
297
298
299
300
301
302
303
304
305
306
307
@staticmethod
def apply_adam_debias(adam_debias: bool, step_size: float, bias_correction1: float) -> float:
    """Apply AdamD variant.

    Args:
        adam_debias: If True, only corrects the denominator to avoid inflating step sizes early in training.
        step_size: The step size for the update.
        bias_correction1: The bias correction factor for the first moment.

    """
    return step_size if adam_debias else step_size / bias_correction1

apply_ams_bound(ams_bound, exp_avg_sq, max_exp_avg_sq, eps, exp_avg_sq_eps=1e-15) staticmethod

Compute an adaptive denominator, with optional running maximum second moments.

Parameters:

Name Type Description Default
ams_bound bool

Whether to apply the AMSBound variant.

required
exp_avg_sq Tensor

Exponential moving average of squared gradients.

required
max_exp_avg_sq Tensor | None

Running elementwise maximum of exp_avg_sq, updated in place for AMSBound.

required
eps float

Small epsilon value for numerical stability.

required
exp_avg_sq_eps float

Epsilon used specifically for numerical stability in exp_avg_sq computations.

1e-15
Source code in pytorch_optimizer/base/optimizer.py
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
@staticmethod
def apply_ams_bound(
    ams_bound: bool,
    exp_avg_sq: torch.Tensor,
    max_exp_avg_sq: torch.Tensor | None,
    eps: float,
    exp_avg_sq_eps: float = 1e-15,
) -> torch.Tensor:
    """Compute an adaptive denominator, with optional running maximum second moments.

    Args:
        ams_bound: Whether to apply the AMSBound variant.
        exp_avg_sq: Exponential moving average of squared gradients.
        max_exp_avg_sq: Running elementwise maximum of `exp_avg_sq`, updated in place for AMSBound.
        eps: Small epsilon value for numerical stability.
        exp_avg_sq_eps: Epsilon used specifically for numerical stability in exp_avg_sq computations.

    """
    if ams_bound:
        if torch.is_complex(max_exp_avg_sq):
            max_exp_avg_sq = torch.view_as_real(max_exp_avg_sq)

        torch.maximum(max_exp_avg_sq, exp_avg_sq, out=max_exp_avg_sq)
        de_nom = max_exp_avg_sq.add(exp_avg_sq_eps)
    else:
        de_nom = exp_avg_sq.add(exp_avg_sq_eps)

    return de_nom.sqrt_().add_(eps)

apply_ams_bound_foreach(ams_bound, exp_avg_sqs, max_exp_avg_sqs, eps, exp_avg_sq_eps=1e-15) staticmethod

Compute batched adaptive denominators with optional running maximum second moments.

Parameters:

Name Type Description Default
ams_bound bool

Whether to apply the AMSBound variant.

required
exp_avg_sqs list[Tensor]

Exponential moving averages of squared gradients.

required
max_exp_avg_sqs list[Tensor]

Running elementwise maxima, updated in place for AMSBound.

required
eps float

Small epsilon value for numerical stability.

required
exp_avg_sq_eps float

Epsilon added to second moments before taking square roots.

1e-15
Source code in pytorch_optimizer/base/optimizer.py
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
@staticmethod
def apply_ams_bound_foreach(
    ams_bound: bool,
    exp_avg_sqs: list[torch.Tensor],
    max_exp_avg_sqs: list[torch.Tensor],
    eps: float,
    exp_avg_sq_eps: float = 1e-15,
) -> Sequence[torch.Tensor]:
    """Compute batched adaptive denominators with optional running maximum second moments.

    Args:
        ams_bound: Whether to apply the AMSBound variant.
        exp_avg_sqs: Exponential moving averages of squared gradients.
        max_exp_avg_sqs: Running elementwise maxima, updated in place for AMSBound.
        eps: Small epsilon value for numerical stability.
        exp_avg_sq_eps: Epsilon added to second moments before taking square roots.

    """
    if ams_bound:
        torch._foreach_maximum_(max_exp_avg_sqs, exp_avg_sqs)
        de_noms = torch._foreach_add(max_exp_avg_sqs, exp_avg_sq_eps)
    else:
        de_noms = torch._foreach_add(exp_avg_sqs, exp_avg_sq_eps)

    torch._foreach_sqrt_(de_noms)
    torch._foreach_add_(de_noms, eps)

    return de_noms

apply_cautious(update, grad) staticmethod

Mask updates that disagree with the gradient sign and rescale them in place.

Parameters:

Name Type Description Default
update Tensor

Update tensor, masked in place.

required
grad Tensor

Gradient tensor.

required
Source code in pytorch_optimizer/base/optimizer.py
423
424
425
426
427
428
429
430
431
432
433
434
@staticmethod
def apply_cautious(update: torch.Tensor, grad: torch.Tensor) -> None:
    """Mask updates that disagree with the gradient sign and rescale them in place.

    Args:
        update: Update tensor, masked in place.
        grad: Gradient tensor.

    """
    mask = (update * grad > 0).to(grad.dtype)
    mask.mul_(mask.numel() / (mask.sum() + 1))
    update.mul_(mask)

apply_orthogonal_gradients(params, eps=1e-16) staticmethod

Project gradients orthogonally to parameters and restore their norms.

Parameters:

Name Type Description Default
params Iterable[Tensor]

Parameters whose dense real gradients are modified in place.

required
eps float

Small value to prevent division by zero.

1e-16
Source code in pytorch_optimizer/base/optimizer.py
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
@staticmethod
@torch.no_grad()
def apply_orthogonal_gradients(params: Iterable[torch.Tensor], eps: float = 1e-16) -> None:
    """Project gradients orthogonally to parameters and restore their norms.

    Args:
        params: Parameters whose dense real gradients are modified in place.
        eps: Small value to prevent division by zero.

    """
    for p in params:
        if p.grad is None or p.grad.is_sparse or torch.is_complex(p):
            continue

        dtype = torch.float64 if p.dtype == torch.float64 else torch.float32
        w = p.reshape(-1).to(dtype=dtype)
        g = p.grad.reshape(-1).to(dtype=dtype)

        proj = torch.dot(w, g).div_(torch.dot(w, w).add_(eps))
        g_ortho = g.sub(w * proj)

        g_norm = g.norm(2)
        g_ortho_norm = g_ortho.norm(2)
        rounding_eps = 4.0 * torch.finfo(dtype).eps
        # A parallel gradient has no orthogonal direction to normalize.
        g_ortho.masked_fill_(g_ortho_norm <= rounding_eps * g_norm, 0.0)
        g_ortho.mul_(g_norm / g_ortho_norm.add_(eps))

        p.grad.copy_(g_ortho.view_as(p.grad))

apply_weight_decay(p, grad, lr, weight_decay, weight_decouple, fixed_decay, ratio=None) staticmethod

Apply coupled or decoupled weight decay in place.

Parameters:

Name Type Description Default
p Tensor

Parameter tensor to apply weight decay to.

required
grad Tensor | None

Gradient to modify for coupled decay. May be None for decoupled decay.

required
lr float | Tensor

Learning rate to scale the update.

required
weight_decay float

Weight decay coefficient (L2 penalty).

required
weight_decouple bool

If True, applies decoupled weight decay as in AdamW.

required
fixed_decay bool

If True, fixes weight decay to not depend on learning rate.

required
ratio float | None

Optional scaling factor for decoupled weight decay.

None
Source code in pytorch_optimizer/base/optimizer.py
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
@staticmethod
def apply_weight_decay(
    p: torch.Tensor,
    grad: torch.Tensor | None,
    lr: float | torch.Tensor,
    weight_decay: float,
    weight_decouple: bool,
    fixed_decay: bool,
    ratio: float | None = None,
) -> None:
    """Apply coupled or decoupled weight decay in place.

    Args:
        p: Parameter tensor to apply weight decay to.
        grad: Gradient to modify for coupled decay. May be `None` for decoupled decay.
        lr: Learning rate to scale the update.
        weight_decay: Weight decay coefficient (L2 penalty).
        weight_decouple: If True, applies decoupled weight decay as in AdamW.
        fixed_decay: If True, fixes weight decay to not depend on learning rate.
        ratio: Optional scaling factor for decoupled weight decay.

    """
    if weight_decay == 0.0:
        return

    if weight_decouple:
        p.mul_(1.0 - weight_decay * (1.0 if fixed_decay else lr) * (ratio if ratio is not None else 1.0))
    elif weight_decay > 0.0 and grad is not None:
        grad.add_(p, alpha=weight_decay)

apply_weight_decay_foreach(params, grads, lr, weight_decay, weight_decouple, fixed_decay) staticmethod

Apply weight decay to a list of parameters.

Parameters:

Name Type Description Default
params list[Tensor]

List of parameter tensors.

required
grads list[Tensor]

List of gradient tensors.

required
lr list[float] | list[Tensor] | tuple[Tensor, ...] | float | Tensor

Learning rate.

required
weight_decay float

Weight decay coefficient.

required
weight_decouple bool

If True, applies decoupled weight decay as in AdamW.

required
fixed_decay bool

If True, fixes weight decay to not depend on learning rate.

required
Source code in pytorch_optimizer/base/optimizer.py
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
@staticmethod
def apply_weight_decay_foreach(
    params: list[torch.Tensor],
    grads: list[torch.Tensor],
    lr: list[float] | list[torch.Tensor] | tuple[torch.Tensor, ...] | float | torch.Tensor,
    weight_decay: float,
    weight_decouple: bool,
    fixed_decay: bool,
) -> None:
    """Apply weight decay to a list of parameters.

    Args:
        params: List of parameter tensors.
        grads: List of gradient tensors.
        lr: Learning rate.
        weight_decay: Weight decay coefficient.
        weight_decouple: If True, applies decoupled weight decay as in AdamW.
        fixed_decay: If True, fixes weight decay to not depend on learning rate.

    """
    if weight_decay == 0.0:
        return

    if not weight_decouple:
        torch._foreach_add_(grads, params, alpha=weight_decay)
        return

    if fixed_decay:
        factor = 1.0 - weight_decay
    elif isinstance(lr, Sequence):
        factor = torch._foreach_mul(lr, -weight_decay)
        torch._foreach_add_(factor, 1.0)
    else:
        factor = 1.0 - weight_decay * lr

    torch._foreach_mul_(params, factor)

approximate_sq_grad(exp_avg_sq_row, exp_avg_sq_col, output) staticmethod

Write a factored inverse root second moment approximation to output.

Parameters:

Name Type Description Default
exp_avg_sq_row list[Tensor] | Tensor

Row second moments, as a tensor or list of tensors.

required
exp_avg_sq_col list[Tensor] | Tensor

Corresponding column second moments.

required
output list[Tensor] | Tensor

Tensor or list of tensors to update in place.

required
Source code in pytorch_optimizer/base/optimizer.py
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
@staticmethod
def approximate_sq_grad(
    exp_avg_sq_row: list[torch.Tensor] | torch.Tensor,
    exp_avg_sq_col: list[torch.Tensor] | torch.Tensor,
    output: list[torch.Tensor] | torch.Tensor,
) -> None:
    """Write a factored inverse root second moment approximation to `output`.

    Args:
        exp_avg_sq_row: Row second moments, as a tensor or list of tensors.
        exp_avg_sq_col: Corresponding column second moments.
        output: Tensor or list of tensors to update in place.

    """
    if isinstance(exp_avg_sq_row, torch.Tensor):
        r_factor: torch.Tensor = (
            (exp_avg_sq_row / exp_avg_sq_row.mean(dim=-1, keepdim=True)).rsqrt_().unsqueeze(-1)
        )
        c_factor: torch.Tensor = exp_avg_sq_col.unsqueeze(-2).rsqrt()
        torch.mul(r_factor, c_factor, out=output)
        return

    row_means = [r.mean(dim=-1, keepdim=True) for r in exp_avg_sq_row]

    r_factors = torch._foreach_div(exp_avg_sq_row, row_means)
    foreach_rsqrt_(r_factors)
    r_factors = [r_factor.unsqueeze(-1) for r_factor in r_factors]

    c_factors = [c_factor.unsqueeze(-2) for c_factor in foreach_rsqrt(exp_avg_sq_col)]

    for r_factor, c_factor, update in zip(r_factors, c_factors, output):
        torch.mul(r_factor, c_factor, out=update)

can_use_foreach(group, foreach, *, dtypes=None, default_on_cuda=False) staticmethod

Check whether a parameter group supports batched tensor updates.

Parameters:

Name Type Description Default
group ParamGroup

Parameter group to inspect.

required
foreach bool | None

Set to False to disable batched updates. True and None check tensor compatibility.

required
dtypes tuple[dtype, ...] | None

Allowed parameter dtypes. None allows all real dtypes.

None
default_on_cuda bool

Enable automatic batching only for groups with CUDA gradients. Explicit True allows CPU.

False

Returns:

Name Type Description
bool bool

True if at least one parameter has a gradient and all such parameters are real with dense gradients.

Source code in pytorch_optimizer/base/optimizer.py
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
@staticmethod
def can_use_foreach(
    group: ParamGroup,
    foreach: bool | None,
    *,
    dtypes: tuple[torch.dtype, ...] | None = None,
    default_on_cuda: bool = False,
) -> bool:
    """Check whether a parameter group supports batched tensor updates.

    Args:
        group: Parameter group to inspect.
        foreach: Set to `False` to disable batched updates. `True` and `None` check tensor compatibility.
        dtypes: Allowed parameter dtypes. `None` allows all real dtypes.
        default_on_cuda: Enable automatic batching only for groups with CUDA gradients. Explicit `True` allows CPU.

    Returns:
        bool: `True` if at least one parameter has a gradient and all such parameters
            are real with dense gradients.

    """
    if foreach is False:
        return False

    has_param: bool = False
    for p in group['params']:
        g = p.grad
        if g is None:
            continue

        has_param = True
        if g.is_sparse or torch.is_complex(p):
            return False

        if dtypes is not None and p.dtype not in dtypes:
            return False

    if foreach is None and default_on_cuda:
        return any(p.is_cuda for p in group['params'] if p.grad is not None)

    return has_param

collect_trainable_params(group, state, state_keys=None) staticmethod

Collect parameters with gradients and their requested state tensors.

Parameters:

Name Type Description Default
group ParamGroup

Optimizer parameter group.

required
state State

Optimizer state dictionary.

required
state_keys list[str] | None

State entries to collect. None collects no state tensors.

None

Returns:

Name Type Description
tuple tuple[list[Tensor], list[Tensor], dict[str, list[Tensor]]]

Parameters, gradients, and a dictionary of lists of available state tensors.

Source code in pytorch_optimizer/base/optimizer.py
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
@staticmethod
def collect_trainable_params(
    group: ParamGroup,
    state: State,
    state_keys: list[str] | None = None,
) -> tuple[list[torch.Tensor], list[torch.Tensor], dict[str, list[torch.Tensor]]]:
    """Collect parameters with gradients and their requested state tensors.

    Args:
        group: Optimizer parameter group.
        state: Optimizer state dictionary.
        state_keys: State entries to collect. `None` collects no state tensors.

    Returns:
        tuple: Parameters, gradients, and a dictionary of lists of available state tensors.

    """
    if state_keys is None:
        state_keys = []

    params: list[torch.Tensor] = []
    grads: list[torch.Tensor] = []
    state_dict: dict[str, list[torch.Tensor]] = {key: [] for key in state_keys}

    for p in group['params']:
        if p.grad is None:
            continue

        params.append(p)
        grads.append(p.grad)

        if state_keys:
            p_state = state[p]
            for key in state_keys:
                if key in p_state:
                    state_dict[key].append(p_state[key])

    return params, grads, state_dict

compute_hutchinson_hessian(param_groups, state, num_samples=1, alpha=1.0, distribution='gaussian') staticmethod

Accumulate Hutchinson estimates of the Hessian diagonal in the optimizer state.

Parameters:

Name Type Description Default
param_groups list[ParamGroup]

Parameter groups from the optimizer.

required
state State

Optimizer state dictionary.

required
num_samples int

Number of noise vectors for the Hessian diagonal estimate.

1
alpha float

Scale of the estimate to add to existing Hessian buffers.

1.0
distribution HutchinsonG

Noise distribution: 'gaussian' or 'rademacher'.

'gaussian'
Source code in pytorch_optimizer/base/optimizer.py
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
@staticmethod
@torch.no_grad()
def compute_hutchinson_hessian(
    param_groups: list[ParamGroup],
    state: State,
    num_samples: int = 1,
    alpha: float = 1.0,
    distribution: HutchinsonG = 'gaussian',
) -> None:
    """Accumulate Hutchinson estimates of the Hessian diagonal in the optimizer state.

    Args:
        param_groups: Parameter groups from the optimizer.
        state: Optimizer state dictionary.
        num_samples: Number of noise vectors for the Hessian diagonal estimate.
        alpha: Scale of the estimate to add to existing Hessian buffers.
        distribution: Noise distribution: `'gaussian'` or `'rademacher'`.

    """
    if distribution not in ('gaussian', 'rademacher'):
        raise NotImplementedError(f'hessian with distribution {distribution} is not implemented.')

    params: list[torch.Tensor] = [
        p
        for group in param_groups or []
        for p in group['params']
        if p.requires_grad and p.grad is not None and not p.grad.is_sparse
    ]
    if len(params) == 0:
        return

    grads = [p.grad for p in params]

    for i in range(num_samples):
        if distribution == 'rademacher':
            zs = [torch.randint_like(p, 0, 2) * 2.0 - 1.0 for p in params]
        else:
            zs = [torch.randn_like(p) for p in params]

        h_zs = torch.autograd.grad(grads, params, grad_outputs=zs, retain_graph=i < num_samples - 1)
        for h_z, z, p in zip(h_zs, zs, params):
            state[p]['hessian'].addcmul_(h_z, z, value=alpha / num_samples)

debias(beta, step) staticmethod

Return the moment bias correction factor 1 - beta ** step.

Parameters:

Name Type Description Default
beta float

Exponential decay rate for moment estimates.

required
step int

Current optimization step number.

required
Source code in pytorch_optimizer/base/optimizer.py
269
270
271
272
273
274
275
276
277
278
@staticmethod
def debias(beta: float, step: int) -> float:
    """Return the moment bias correction factor `1 - beta ** step`.

    Args:
        beta: Exponential decay rate for moment estimates.
        step: Current optimization step number.

    """
    return 1.0 - math.pow(beta, step)  # fmt: skip

debias_beta(beta, step) staticmethod

Return the decay rate for a bias corrected moving average.

Computes beta * (1 - beta ** (step - 1)) / (1 - beta ** step).

Parameters:

Name Type Description Default
beta float

Exponential decay rate.

required
step int

Optimization step, starting at 1.

required

Returns:

Name Type Description
float float

Bias corrected decay rate.

Source code in pytorch_optimizer/base/optimizer.py
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
@staticmethod
def debias_beta(beta: float, step: int) -> float:
    """Return the decay rate for a bias corrected moving average.

    Computes `beta * (1 - beta ** (step - 1)) / (1 - beta ** step)`.

    Args:
        beta: Exponential decay rate.
        step: Optimization step, starting at 1.

    Returns:
        float: Bias corrected decay rate.

    """
    beta_n: float = beta ** step
    return (beta_n - beta) / (beta_n - 1.0)  # fmt: skip

get_adanorm_gradient(grad, adanorm, exp_grad_norm=None, r=0.95) staticmethod

Rescale gradients whose norm falls below its running average.

Parameters:

Name Type Description Default
grad Tensor

Gradient.

required
adanorm bool

Whether to use the AdaNorm variant.

required
exp_grad_norm Tensor | None

Exponential moving average of gradient norm.

None
r float | None

Decay rate for the gradient norm average.

0.95
Source code in pytorch_optimizer/base/optimizer.py
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
@staticmethod
def get_adanorm_gradient(
    grad: torch.Tensor, adanorm: bool, exp_grad_norm: torch.Tensor | None = None, r: float | None = 0.95
) -> torch.Tensor:
    """Rescale gradients whose norm falls below its running average.

    Args:
        grad: Gradient.
        adanorm: Whether to use the AdaNorm variant.
        exp_grad_norm: Exponential moving average of gradient norm.
        r: Decay rate for the gradient norm average.

    """
    if not adanorm or exp_grad_norm is None:
        return grad

    if r is None:
        r = 0.95

    grad_norm = torch.linalg.norm(grad)

    exp_grad_norm.mul_(r).add_(grad_norm, alpha=1.0 - r)

    if grad_norm > 0 and exp_grad_norm > grad_norm:
        return grad.mul(exp_grad_norm.reshape(())).div_(grad_norm)

    return grad

get_device_from_param_groups(param_groups) staticmethod

Return the first parameter's device, defaulting to CPU when all parameter groups are empty.

Source code in pytorch_optimizer/base/optimizer.py
85
86
87
88
@staticmethod
def get_device_from_param_groups(param_groups: list[ParamGroup]) -> torch.device:
    """Return the first parameter's device, defaulting to CPU when all parameter groups are empty."""
    return next((p.device for group in param_groups for p in group['params']), torch.device('cpu'))

get_rectify_step_size(is_rectify, step, lr, beta2, n_sma_threshold, degenerated_to_sgd) staticmethod

Compute the RAdam step size and effective moving average length.

Parameters:

Name Type Description Default
is_rectify bool

Whether to apply the rectify variant.

required
step int

Current step number.

required
lr float

Base learning rate.

required
beta2 float

Decay rate of the second moment.

required
n_sma_threshold int

Simple Moving Average (SMA) threshold for rectification.

required
degenerated_to_sgd bool

Whether to degenerate to SGD if below threshold.

required
Source code in pytorch_optimizer/base/optimizer.py
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
@staticmethod
def get_rectify_step_size(
    is_rectify: bool,
    step: int,
    lr: float,
    beta2: float,
    n_sma_threshold: int,
    degenerated_to_sgd: bool,
) -> tuple[float, float]:
    """Compute the RAdam step size and effective moving average length.

    Args:
        is_rectify: Whether to apply the rectify variant.
        step: Current step number.
        lr: Base learning rate.
        beta2: Decay rate of the second moment.
        n_sma_threshold: Simple Moving Average (SMA) threshold for rectification.
        degenerated_to_sgd: Whether to degenerate to SGD if below threshold.

    """
    step_size: float = lr
    n_sma: float = 0.0

    if is_rectify:
        n_sma_max: float = 2.0 / (1.0 - beta2) - 1.0
        beta2_t: float = beta2 ** step  # fmt: skip
        n_sma: float = n_sma_max - 2 * step * beta2_t / (1.0 - beta2_t)

        if n_sma >= n_sma_threshold:
            rt = math.sqrt(
                (1.0 - beta2_t) * (n_sma - 4) / (n_sma_max - 4) * (n_sma - 2) / n_sma * n_sma_max / (n_sma_max - 2)
            )
        elif degenerated_to_sgd:
            rt = 1.0
        else:
            rt = -1.0

        step_size = step_size * rt

    return step_size, n_sma

get_rms(x) staticmethod

Compute the root mean square of a tensor or each tensor in a list.

Source code in pytorch_optimizer/base/optimizer.py
378
379
380
381
382
383
384
385
386
387
388
@staticmethod
def get_rms(x: Sequence[torch.Tensor] | torch.Tensor) -> Sequence[torch.Tensor] | torch.Tensor:
    """Compute the root mean square of a tensor or each tensor in a list."""
    if isinstance(x, torch.Tensor):
        return x.norm(2).div_(math.sqrt(x.numel()))

    factors: list[float] = [math.sqrt(p.numel()) for p in x]
    norms = torch._foreach_norm(x, ord=2)
    torch._foreach_div_(norms, factors)

    return norms

get_stable_adamw_rms(grad, exp_avg_sq, eps=1e-16) staticmethod

Get StableAdamW RMS as a scalar tensor on the gradient's device.

Parameters:

Name Type Description Default
grad Tensor

Gradient.

required
exp_avg_sq Tensor

Exponential moving average of squared gradient.

required
eps float

Small value to prevent division by zero.

1e-16

Returns:

Type Description
Tensor

torch.Tensor: RMS scale, computed in float32 for float16 and bfloat16 gradients.

Source code in pytorch_optimizer/base/optimizer.py
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
@staticmethod
def get_stable_adamw_rms(grad: torch.Tensor, exp_avg_sq: torch.Tensor, eps: float = 1e-16) -> torch.Tensor:
    """Get StableAdamW RMS as a scalar tensor on the gradient's device.

    Args:
        grad: Gradient.
        exp_avg_sq: Exponential moving average of squared gradient.
        eps: Small value to prevent division by zero.

    Returns:
        torch.Tensor: RMS scale, computed in float32 for float16 and bfloat16 gradients.

    """
    if grad.dtype in (torch.float16, torch.bfloat16):
        grad, exp_avg_sq = grad.float(), exp_avg_sq.float()

    return grad.pow(2).div_(exp_avg_sq.clip(min=eps)).mean().sqrt_().clip_(min=1.0)

init_group(group, **kwargs) abstractmethod

Initialize optimizer state for a parameter group.

Source code in pytorch_optimizer/base/optimizer.py
692
693
694
695
@abstractmethod
def init_group(self, group: ParamGroup, **kwargs) -> None:  # pragma: no cover
    """Initialize optimizer state for a parameter group."""
    return

load_optimizer(optimizer, **kwargs) staticmethod

Return an optimizer instance or instantiate an optimizer class.

Parameters:

Name Type Description Default
optimizer OptimizerInstanceOrClass

Optimizer instance or class.

required
**kwargs dict

Constructor options. Must include params when passing a class.

{}

Returns:

Name Type Description
Optimizer Optimizer

Existing or newly constructed optimizer.

Raises:

Type Description
ValueError

An optimizer class is supplied without params.

Source code in pytorch_optimizer/base/optimizer.py
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
@staticmethod
def load_optimizer(optimizer: OptimizerInstanceOrClass, **kwargs) -> Optimizer:
    """Return an optimizer instance or instantiate an optimizer class.

    Args:
        optimizer: Optimizer instance or class.
        **kwargs (dict): Constructor options. Must include `params` when passing a class.

    Returns:
        Optimizer: Existing or newly constructed optimizer.

    Raises:
        ValueError: An optimizer class is supplied without `params`.

    """
    if isinstance(optimizer, Optimizer):
        return optimizer

    if 'params' in kwargs:
        params = kwargs.pop('params')
        return optimizer(params, **kwargs)

    raise ValueError('need to pass `params` when you pass the `torch.optim.Optimizer` instance.')

load_state_dict(state_dict)

Restore state while preserving non-floating tensor types and container metadata.

Source code in pytorch_optimizer/base/optimizer.py
37
38
39
40
41
42
43
def load_state_dict(self, state_dict: dict) -> None:
    """Restore state while preserving non-floating tensor types and container metadata."""
    super().load_state_dict(state_dict)
    for group, saved_group in zip(self.param_groups, state_dict['param_groups']):
        for p, key in zip(group['params'], saved_group['params']):
            if key in state_dict['state']:
                self.state[p] = self._restore_state_types(self.state[p], state_dict['state'][key])

maximize_gradient(grad, maximize=False) staticmethod

Negate the gradient in place when maximizing the objective.

Source code in pytorch_optimizer/base/optimizer.py
709
710
711
712
713
@staticmethod
def maximize_gradient(grad: torch.Tensor, maximize: bool = False) -> None:
    """Negate the gradient in place when maximizing the objective."""
    if maximize:
        grad.neg_()

set_hessian(param_groups, state, hessian) staticmethod

Store externally computed Hessian estimates in the optimizer state.

Parameters:

Name Type Description Default
param_groups list[ParamGroup]

Optimizer parameter groups.

required
state State

Optimizer state dictionary to update.

required
hessian list[Tensor]

One tensor per parameter, in parameter group order, with matching shapes.

required

Raises:

Type Description
ValueError

A Hessian tensor and its parameter have different shapes.

Examples:

BaseOptimizer.set_hessian(optimizer.param_groups, optimizer.state, hessian)
Source code in pytorch_optimizer/base/optimizer.py
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
@staticmethod
@torch.no_grad()
def set_hessian(param_groups: list[ParamGroup], state: State, hessian: list[torch.Tensor]) -> None:
    """Store externally computed Hessian estimates in the optimizer state.

    Args:
        param_groups: Optimizer parameter groups.
        state: Optimizer state dictionary to update.
        hessian: One tensor per parameter, in parameter group order, with matching shapes.

    Raises:
        ValueError: A Hessian tensor and its parameter have different shapes.

    Examples:
        ```python
        BaseOptimizer.set_hessian(optimizer.param_groups, optimizer.state, hessian)
        ```

    """
    i: int = 0
    for group in param_groups or []:
        for p in group['params']:
            if p.size() != hessian[i].size():
                raise ValueError(
                    f'the shape of parameter and hessian does not match. {p.size()} vs {hessian[i].size()}'
                )

            state[p]['hessian'] = hessian[i]
            i += 1

validate_betas(betas, beta_range_type='[)', beta3_range_type='[]')

Validate the first two beta values and an optional third value against their intervals.

Source code in pytorch_optimizer/base/optimizer.py
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
def validate_betas(
    self,
    betas: Betas | tuple[None, float],
    beta_range_type: str = '[)',
    beta3_range_type: str = '[]',
) -> None:
    """Validate the first two beta values and an optional third value against their intervals."""
    if betas[0] is not None:
        self.validate_range(betas[0], 'beta1', 0.0, 1.0, range_type=beta_range_type)

    self.validate_range(betas[1], 'beta2', 0.0, 1.0, range_type=beta_range_type)

    if len(betas) < 3:
        return

    if betas[2] is not None:
        self.validate_range(betas[2], 'beta3', 0.0, 1.0, range_type=beta3_range_type)

validate_boundary(constant, boundary, bound_type='upper') staticmethod

Raise ValueError if a value exceeds an upper bound or falls below a lower bound.

Source code in pytorch_optimizer/base/optimizer.py
632
633
634
635
636
637
638
@staticmethod
def validate_boundary(constant: float, boundary: float, bound_type: str = 'upper') -> None:
    """Raise `ValueError` if a value exceeds an upper bound or falls below a lower bound."""
    if bound_type == 'upper' and constant > boundary:
        raise ValueError(f'constant {constant} must be in a range of (-inf, {boundary}]')
    if bound_type == 'lower' and constant < boundary:
        raise ValueError(f'constant {constant} must be in a range of [{boundary}, inf)')

validate_learning_rate(learning_rate) staticmethod

Raise NegativeLRError for a negative learning rate. Accept None.

Source code in pytorch_optimizer/base/optimizer.py
653
654
655
656
657
@staticmethod
def validate_learning_rate(learning_rate: float | torch.Tensor | None) -> None:
    """Raise `NegativeLRError` for a negative learning rate. Accept `None`."""
    if learning_rate is not None and learning_rate < 0.0:
        raise NegativeLRError(learning_rate)

validate_mod(x, y) staticmethod

Raise ValueError if x is not divisible by y.

Source code in pytorch_optimizer/base/optimizer.py
659
660
661
662
663
@staticmethod
def validate_mod(x: int, y: int) -> None:
    """Raise `ValueError` if `x` is not divisible by `y`."""
    if x % y != 0:
        raise ValueError(f'{x} must be divisible by {y}')

validate_non_negative(x, name) staticmethod

Raise ValueError for a negative value. Accept None.

Source code in pytorch_optimizer/base/optimizer.py
614
615
616
617
618
@staticmethod
def validate_non_negative(x: float | None, name: str) -> None:
    """Raise `ValueError` for a negative value. Accept `None`."""
    if x is not None and x < 0.0:
        raise ValueError(f'{name} must be non-negative')

validate_non_positive(x, name) staticmethod

Raise ValueError for a positive value. Accept None.

Source code in pytorch_optimizer/base/optimizer.py
620
621
622
623
624
@staticmethod
def validate_non_positive(x: float | None, name: str) -> None:
    """Raise `ValueError` for a positive value. Accept `None`."""
    if x is not None and x > 0.0:
        raise ValueError(f'{name} must be non-positive')

validate_nus(nus)

Validate one or two quasi-hyperbolic discount factors in [0, 1].

Source code in pytorch_optimizer/base/optimizer.py
683
684
685
686
687
688
689
690
def validate_nus(self, nus: float | tuple[float, float]) -> None:
    """Validate one or two quasi-hyperbolic discount factors in `[0, 1]`."""
    if isinstance(nus, tuple):
        nu1, nu2 = nus
        self.validate_range(nu1, 'nu1', 0.0, 1.0, range_type='[]')
        self.validate_range(nu2, 'nu2', 0.0, 1.0, range_type='[]')
    else:
        self.validate_range(nus, 'nu', 0.0, 1.0, range_type='[]')

validate_options(x, name, options) staticmethod

Raise ValueError if an option is outside the allowed choices.

Source code in pytorch_optimizer/base/optimizer.py
646
647
648
649
650
651
@staticmethod
def validate_options(x: str, name: str, options: list[str]) -> None:
    """Raise `ValueError` if an option is outside the allowed choices."""
    if x not in options:
        opts: str = ' or '.join([f"'{option}'" for option in options]).strip()
        raise ValueError(f'{name} {x} must be one of ({opts})')

validate_positive(x, name) staticmethod

Raise ValueError if a value is zero or negative.

Source code in pytorch_optimizer/base/optimizer.py
626
627
628
629
630
@staticmethod
def validate_positive(x: float | int, name: str) -> None:
    """Raise `ValueError` if a value is zero or negative."""
    if x <= 0:
        raise ValueError(f'{name} must be positive')

validate_range(x, name, low, high, range_type='[)') staticmethod

Raise ValueError if a value falls outside the requested interval.

Source code in pytorch_optimizer/base/optimizer.py
602
603
604
605
606
607
608
609
610
611
612
@staticmethod
def validate_range(x: float, name: str, low: float, high: float, range_type: str = '[)') -> None:
    """Raise `ValueError` if a value falls outside the requested interval."""
    if range_type == '[)' and not low <= x < high:
        raise ValueError(f'{name} must be in the range [{low}, {high})')
    if range_type == '[]' and not low <= x <= high:
        raise ValueError(f'{name} must be in the range [{low}, {high}]')
    if range_type == '(]' and not low < x <= high:
        raise ValueError(f'{name} must be in the range ({low}, {high}]')
    if range_type == '()' and not low < x < high:
        raise ValueError(f'{name} must be in the range ({low}, {high})')

validate_step(step, step_type) staticmethod

Raise NegativeStepError if the step number is less than 1.

Source code in pytorch_optimizer/base/optimizer.py
640
641
642
643
644
@staticmethod
def validate_step(step: int, step_type: str) -> None:
    """Raise `NegativeStepError` if the step number is less than 1."""
    if step < 1:
        raise NegativeStepError(step, step_type=step_type)

view_as_real(param, *state_and_grads) staticmethod

Return real views of complex parameters, gradients, and state tensors.

Source code in pytorch_optimizer/base/optimizer.py
697
698
699
700
701
702
703
704
705
706
707
@staticmethod
def view_as_real(param, *state_and_grads) -> tuple:
    """Return real views of complex parameters, gradients, and state tensors."""
    if torch.is_complex(param):
        param = torch.view_as_real(param)
        state_and_grads = tuple(
            torch.view_as_real(s) if (s is not None and torch.is_complex(s)) else s if s is not None else None
            for s in state_and_grads
        )

    return param, *state_and_grads

zero_hessian(param_groups, state, pre_zero=True) staticmethod

Initialize Hessian buffers and optionally clear existing estimates.

Parameters:

Name Type Description Default
param_groups list[ParamGroup]

Parameter groups from the optimizer.

required
state State

Optimizer state dictionary.

required
pre_zero bool

Clear existing Hessian estimates before accumulating new ones.

True
Source code in pytorch_optimizer/base/optimizer.py
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
@staticmethod
def zero_hessian(param_groups: list[ParamGroup], state: State, pre_zero: bool = True) -> None:
    """Initialize Hessian buffers and optionally clear existing estimates.

    Args:
        param_groups: Parameter groups from the optimizer.
        state: Optimizer state dictionary.
        pre_zero: Clear existing Hessian estimates before accumulating new ones.

    """
    for group in param_groups or []:
        for p in group['params']:
            if p.requires_grad and p.grad is not None and not p.grad.is_sparse:
                if 'hessian' not in state[p]:
                    state[p]['hessian'] = torch.zeros_like(p)
                elif pre_zero:
                    state[p]['hessian'].zero_()