Utilities¶
Use these helpers to find registered components, manage gradients, and offload optimizer work to the CPU.
get_supported_optimizers(filters=None)
¶
List registered optimizer names in alphabetical order.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
filters
|
str | list[str] | None
|
Wildcard pattern or list of patterns, such as |
None
|
Returns:
| Type | Description |
|---|---|
list[str]
|
list[str]: Matching names in lowercase, without duplicates. |
Source code in pytorch_optimizer/optimizer/__init__.py
715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 | |
get_supported_lr_schedulers(filters=None)
¶
List registered scheduler names in alphabetical order.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
filters
|
str | list[str] | None
|
Wildcard pattern or list of patterns, such as |
None
|
Returns:
| Type | Description |
|---|---|
list[str]
|
list[str]: Matching names in lowercase, without duplicates. |
Source code in pytorch_optimizer/lr_scheduler/__init__.py
116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 | |
get_supported_loss_functions(filters=None)
¶
List registered loss function names in alphabetical order.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
filters
|
str | list[str] | None
|
Wildcard pattern or list of patterns, such as |
None
|
Returns:
| Type | Description |
|---|---|
list[str]
|
list[str]: Matching names in lowercase, without duplicates. |
Source code in pytorch_optimizer/loss/__init__.py
60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 | |
CPUOffloadOptimizer
¶
Offload optimizer states and updates to the CPU for single GPU training.
Transfers gradients to pinned CPU memory and copies updated parameters back to the GPU.
Reference: https://github.com/pytorch/ao/blob/main/torchao/prototype/low_bit_optim/cpu_offload.py
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
params
|
ParamsT
|
Parameters to optimize or dictionaries defining parameter groups. |
required |
optimizer_class
|
type[Optimizer]
|
Base optimizer class. Defaults to |
AdamW
|
offload_gradients
|
bool
|
Free GPU gradients after transfer. Incompatible with gradient accumulation. |
False
|
**kwargs
|
dict
|
Options for the base optimizer, such as |
{}
|
Source code in pytorch_optimizer/optimizer/utils/offload.py
10 11 12 13 14 15 16 17 18 19 20 21 22 23 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 | |
is_valid_parameters(parameters)
¶
Check for a nonempty list or tuple whose first entry is a parameter group dictionary.
Source code in pytorch_optimizer/optimizer/utils/model.py
10 11 12 | |
has_overflow(grad_norm)
¶
Return whether a tensor contains NaN or infinite values.
Source code in pytorch_optimizer/optimizer/utils/precision.py
5 6 7 | |
to_real(x)
¶
Return the real part of a complex tensor, or the original real tensor.
Source code in pytorch_optimizer/optimizer/utils/precision.py
10 11 12 | |
normalize_gradient(x, use_channels=False, epsilon=1e-08)
¶
Divide gradients by their standard deviation in place.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x
|
Tensor
|
Gradient tensor to normalize. |
required |
use_channels
|
bool
|
If True, perform channel wise normalization. |
False
|
epsilon
|
float
|
Small constant added for numerical stability. |
1e-08
|
Source code in pytorch_optimizer/optimizer/utils/gradient.py
12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 | |
clip_grad_norm(parameters, max_norm=0.0, sync=False)
¶
Compute the global L2 gradient norm and optionally clip gradients in place.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
parameters
|
ParamsT | Tensor
|
Tensor or iterable of tensors whose gradients to inspect. |
required |
max_norm
|
float
|
Maximum gradient norm. A nonpositive value disables clipping. |
0.0
|
sync
|
bool
|
Sum squared norms across the distributed process group for sharded gradients. |
False
|
Returns:
| Type | Description |
|---|---|
Tensor
|
torch.Tensor: Global gradient norm before clipping. |
Source code in pytorch_optimizer/optimizer/utils/gradient.py
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 | |
unit_norm(x, norm=2.0)
¶
Compute parameter unit norms for adaptive gradient clipping.
Uses the full norm for scalars and vectors, dimension 1 for 2D and 3D tensors, and all dimensions after the first for tensors with four or more dimensions.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x
|
Tensor
|
Parameter or gradient tensor. |
required |
norm
|
float
|
Order of the vector norm. |
2.0
|
Returns:
| Type | Description |
|---|---|
Tensor
|
torch.Tensor: Unit norms, with reduced dimensions retained for multidimensional inputs. |
Source code in pytorch_optimizer/optimizer/utils/gradient.py
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 | |
disable_running_stats(model)
¶
Pause BatchNorm running statistic updates by setting momentum to zero.
Source code in pytorch_optimizer/optimizer/utils/model.py
15 16 17 18 19 20 21 22 23 | |
enable_running_stats(model)
¶
Restore BatchNorm momentum after pausing running statistic updates.
Source code in pytorch_optimizer/optimizer/utils/model.py
26 27 28 29 30 31 32 33 | |
get_global_gradient_norm(param_groups, device=None, *, weight_adaptive=False)
¶
Return the sum of squared L2 gradient norms across parameter groups.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
param_groups
|
list[ParamGroup] | None
|
Optimizer parameter groups, or None for no parameters. |
required |
device
|
device | None
|
Output device. Defaults to the first parameter's device, or CPU for empty groups. |
None
|
weight_adaptive
|
bool
|
Weight gradients by absolute parameter values for groups with |
False
|
Returns:
| Type | Description |
|---|---|
Tensor
|
torch.Tensor: Squared global norm as a single element float32 tensor. |
Source code in pytorch_optimizer/optimizer/utils/gradient.py
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 | |
reg_noise(network1, network2, num_data, lr, eta=0.008, temperature=0.0001)
¶
Compute the Entropy-MCMC coupling and noise term for two networks.
Usage example and detailed implementation can be found at: https://github.com/lblaoke/EMCMC/blob/master/exp/cifar10_emcmc.py
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
network1
|
Module
|
First neural network. |
required |
network2
|
Module
|
Second neural network. |
required |
num_data
|
int
|
Number of training data points. |
required |
lr
|
float
|
Learning rate. |
required |
eta
|
float
|
Eta parameter controlling auxiliary guiding variable. |
0.008
|
temperature
|
float
|
Temperature parameter for sampling. |
0.0001
|
Source code in pytorch_optimizer/optimizer/utils/model.py
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 | |
copy_stochastic(target, source)
¶
Copy float32 values to bfloat16 with stochastic rounding.
reference: https://github.com/pytorch/pytorch/issues/120376#issuecomment-1974828905
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
target
|
Tensor
|
A tensor in bfloat16 format to copy to. |
required |
source
|
Tensor
|
A tensor in float32 format to copy from. |
required |
Source code in pytorch_optimizer/optimizer/utils/precision.py
15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 | |
batched_power_iteration(matrix, num_iters=10, num_vectors=16)
¶
Estimate the largest eigenvalue of each positive semidefinite matrix in a batch.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
matrix
|
Tensor
|
Batch of symmetric positive semidefinite matrices with shape |
required |
num_iters
|
int
|
Number of power iterations. |
10
|
num_vectors
|
int
|
Number of parallel starting vectors per matrix. |
16
|
Returns:
| Type | Description |
|---|---|
Tensor
|
torch.Tensor: Largest Rayleigh quotient per matrix, with shape |
Source code in pytorch_optimizer/optimizer/utils/matrix.py
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 | |
compute_power_newton_db(matrix, scale, num_iters=10, inverse=True)
¶
Compute batched square roots or inverse square roots with Newton-Denman-Beavers iterations.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
matrix
|
Tensor
|
Batch of symmetric positive definite matrices with shape |
required |
scale
|
Tensor
|
Positive normalization factors with shape |
required |
num_iters
|
int
|
Positive number of Newton-Denman-Beavers iterations. |
10
|
inverse
|
bool
|
Return inverse square roots when |
True
|
Returns:
| Type | Description |
|---|---|
Tensor
|
torch.Tensor: Approximate matrix roots with the same shape and data type as |
Source code in pytorch_optimizer/optimizer/utils/matrix.py
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 | |