Utilization
get_optimizer_parameters(model_or_parameter, weight_decay, wd_ban_list=('bias', 'LayerNorm.bias', 'LayerNorm.weight'))
Get optimizer parameters while filtering specified modules.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
model_or_parameter |
Union[Module, List]
|
Union[nn.Module, List]. model or parameters. |
required |
weight_decay |
float
|
float. weight_decay. |
required |
wd_ban_list |
List[str]
|
List[str]. ban list not to set weight decay. |
('bias', 'LayerNorm.bias', 'LayerNorm.weight')
|
Returns:
Type | Description |
---|---|
PARAMETERS
|
PARAMETERS. new parameter list. |
Source code in pytorch_optimizer/optimizer/utils.py
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 |
|
is_valid_parameters(parameters)
Check where the parameters are valid.
Source code in pytorch_optimizer/optimizer/utils.py
15 16 17 |
|
has_overflow(grad_norm)
Detect inf and NaN in grad_norm.
Source code in pytorch_optimizer/optimizer/utils.py
20 21 22 |
|
to_real(x)
Return real value of tensor.
Source code in pytorch_optimizer/optimizer/utils.py
25 26 27 |
|
normalize_gradient(x, use_channels=False, epsilon=1e-08)
Normalize gradient with stddev.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
x |
Tensor
|
torch.Tensor. gradient. |
required |
use_channels |
bool
|
bool. channel-wise normalization. |
False
|
epsilon |
float
|
float. eps. |
1e-08
|
Source code in pytorch_optimizer/optimizer/utils.py
30 31 32 33 34 35 36 37 38 39 40 41 42 43 |
|
flatten_grad(grads)
Flatten the gradient.
Source code in pytorch_optimizer/optimizer/utils.py
46 47 48 |
|
un_flatten_grad(grads, shapes)
Unflatten the gradient.
Source code in pytorch_optimizer/optimizer/utils.py
51 52 53 54 55 56 57 58 59 |
|
channel_view(x)
Do channel view.
Source code in pytorch_optimizer/optimizer/utils.py
62 63 64 |
|
layer_view(x)
Do layer view.
Source code in pytorch_optimizer/optimizer/utils.py
67 68 69 |
|
cosine_similarity_by_view(x, y, eps, view_func)
Calculate cosine similarity by the view.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
x |
Tensor
|
torch.Tensor. src. |
required |
y |
Tensor
|
torch.Tensor. dst. |
required |
eps |
float
|
float. epsilon. |
required |
view_func |
Callable[[Tensor], Tensor]
|
Callable. view (channel or layer) function. |
required |
Source code in pytorch_optimizer/optimizer/utils.py
72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 |
|
clip_grad_norm(parameters, max_norm=0.0, sync=False)
Clip gradient norms.
During combination with FSDP, will also ensure that grad norms are aggregated across all workers,
since each worker only stores their shard of the gradients.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
parameters |
PARAMETERS
|
PARAMETERS. Parameters whose gradients we wish to clip. |
required |
max_norm |
float
|
float. Maximum norm we wish the gradients to have. If non-positive, then we will not perform clipping. |
0.0
|
sync |
bool
|
bool. Boolean indicating whether we should aggregate across the distributed group. Used only in combination with FSDP. |
False
|
Returns:
Type | Description |
---|---|
Union[Tensor, float]
|
The gradient norm across all parameters, before clipping. |
Source code in pytorch_optimizer/optimizer/utils.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 119 120 121 122 123 124 125 126 127 128 |
|
projection(p, grad, perturb, delta, wd_ratio, eps)
Project to remove the radial component from the update vector.
Source code in pytorch_optimizer/optimizer/utils.py
131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 |
|
unit_norm(x, norm=2.0)
Get norm of unit.
Source code in pytorch_optimizer/optimizer/utils.py
154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 |
|
neuron_norm(x)
Get norm of the tensor.
Source code in pytorch_optimizer/optimizer/utils.py
199 200 201 202 203 204 205 206 |
|
neuron_mean(x)
Get mean of the tensor.
Source code in pytorch_optimizer/optimizer/utils.py
209 210 211 212 213 214 215 216 |
|
disable_running_stats(model)
Disable running stats (momentum) of BatchNorm.
Source code in pytorch_optimizer/optimizer/utils.py
219 220 221 222 223 224 225 226 227 |
|
enable_running_stats(model)
Enable running stats (momentum) of BatchNorm.
Source code in pytorch_optimizer/optimizer/utils.py
230 231 232 233 234 235 236 237 |
|
l2_projection(parameters, max_norm=100.0)
Get l2 normalized parameter.
Source code in pytorch_optimizer/optimizer/utils.py
240 241 242 243 244 245 246 247 |
|
get_global_gradient_norm(param_groups, device)
Get global gradient norm.
Source code in pytorch_optimizer/optimizer/utils.py
250 251 252 253 254 255 256 257 258 259 260 |
|
reduce_max_except_dim(x, dim)
Perform reduce-max along all dimensions except the given dim.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
x |
Tensor
|
torch.Tensor. tensor to reduce-max. |
required |
dim |
int
|
int. dimension to exclude. |
required |
Source code in pytorch_optimizer/optimizer/utils.py
263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 |
|
merge_small_dims(shape_to_merge, max_dim)
Merge small dimensions.
If there are some small dimensions, we collapse them
e.g. [1, 2, 512, 1, 2048, 1, 3, 4] --> [1024, 2048, 12] if max_dim = 1024
[1, 2, 768, 1, 2048] --> [2, 768, 2048].
Parameters:
Name | Type | Description | Default |
---|---|---|---|
shape_to_merge |
List[int]
|
List[int]. Shape to merge small dimensions. |
required |
max_dim |
int
|
int. Maximal dimension of output shape used in merging. |
required |
Source code in pytorch_optimizer/optimizer/shampoo_utils.py
506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 |
|
Newton methods
power_iteration(mat_g, num_iters=100)
Compute the maximum eigenvalue of matrix, for scaling.
Mostly, power_iteration method is faster than torch.einval in case of the symmetric PSD matrix.
Also, I removed the validation, error of singular value every iteration, so that boosting the speed.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
mat_g |
Tensor
|
torch.Tensor. the symmetric PSD matrix. |
required |
num_iters |
int
|
int. Number of iterations. |
100
|
Source code in pytorch_optimizer/optimizer/shampoo_utils.py
395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 |
|
compute_power_schur_newton(mat_g, p, max_iters=100, error_tolerance=0.001, ridge_epsilon=1e-06, max_error_ratio=1.2)
Compute G^{-1/p} using a coupled Newton iteration.
See for example equation 3.2 on page 9 of:
A Schur-Newton Method for the Matrix p-th Root and its Inverse by Chun-Hua Guo and Nicholas J. Higham
SIAM Journal on Matrix Analysis and Applications, 2006, Vol. 28, No. 3 : pp. 788-804
https://pdfs.semanticscholar.org/0abe/7f77433cf5908bfe2b79aa91af881da83858.pdf.
The best value for z is (1 + p) * (c_max^{1/p} - c_min^{1/p}) / (c_max^{1+1/p} - c_min^{1+1/p})
where c_max and c_min are the largest and smallest singular values of mat_g.
The above estimate assumes that c_max > c_min * 2^p can replace above line by the one below,
but it is less accurate, hence needs more iterations to converge.
z = (1 + p) / tf.trace(mat_g)
If we want the method to always converge, use z = 1 / norm(mat_g) or z = 1 / tf.trace(mat_g),
but these can result in many extra iterations.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
mat_g |
Tensor
|
torch.Tensor. A square positive semi-definite matrix. |
required |
p |
int
|
int. a positive integer. |
required |
max_iters |
int
|
int. Stop iterating after this many rounds. |
100
|
error_tolerance |
float
|
float. Threshold for stopping iteration. |
0.001
|
ridge_epsilon |
float
|
float. We add this times I to G, to make is positive definite. For scaling, we multiply it by the largest eigenvalue of G. |
1e-06
|
max_error_ratio |
float
|
float. Sometimes error increases after an iteration before decreasing and converging. 1.2 factor is used to bound the maximal allowed increase. |
1.2
|
Source code in pytorch_optimizer/optimizer/shampoo_utils.py
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 |
|
compute_power_svd(matrix, power)
Compute G^{-1/p} using a SVD.
Calculate SVD on the GPU. Sometimes, SVD on the CPU is faster than GPU, but based on the several experiments,
CUDA seems much faster than on CPU.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
matrix |
Tensor
|
torch.Tensor. a square positive semi-definite matrix. |
required |
power |
float
|
float. rank. |
required |
Source code in pytorch_optimizer/optimizer/shampoo_utils.py
491 492 493 494 495 496 497 498 499 500 501 502 503 |
|
Grafting
Graft
Base class to perform grafting onto Shampoo. This class does no grafting.
Source code in pytorch_optimizer/optimizer/shampoo_utils.py
26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 |
|
add_statistics(grad, unused_beta2)
Add the statistics.
Source code in pytorch_optimizer/optimizer/shampoo_utils.py
32 33 34 |
|
precondition_gradient(grad)
Get preconditioned gradient.
Source code in pytorch_optimizer/optimizer/shampoo_utils.py
36 37 38 |
|
update_momentum(update, unused_beta1)
Update momentum.
Source code in pytorch_optimizer/optimizer/shampoo_utils.py
40 41 42 |
|
LayerWiseGrafting
Bases: IntEnum
Layer-wise grafting.
Grafting is a technique to fix the layer-wise scale of Shampoo optimizer. https://arxiv.org/pdf/2002.11803.pdf studies this in detail. This allows us to plugin the Shampoo optimizer into settings where SGD/AdaGrad is already well tuned. Grafting onto Shampoo means take the Shampoo direction, but use the step magnitude from the grafted optimizer such as Adagrad or SGD.
Source code in pytorch_optimizer/optimizer/shampoo_utils.py
9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
|
SGDGraft
Bases: Graft
Graft using SGD + momentum. momentum maintains an exponentially weighted moving average of gradients.
Source code in pytorch_optimizer/optimizer/shampoo_utils.py
45 46 47 48 49 50 51 52 53 54 55 |
|
update_momentum(update, beta1)
Update momentum.
Source code in pytorch_optimizer/optimizer/shampoo_utils.py
52 53 54 55 |
|
SQRTNGraft
Bases: Graft
Graft using SQRTN.
Source code in pytorch_optimizer/optimizer/shampoo_utils.py
58 59 60 61 62 63 64 65 66 |
|
precondition_gradient(grad)
Get preconditioned gradient.
Source code in pytorch_optimizer/optimizer/shampoo_utils.py
64 65 66 |
|
AdaGradGraft
Bases: SGDGraft
Graft using AdaGrad. Essentially an implementation of AdaGrad with momentum.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
var |
Tensor
|
torch.Tensor. variable. |
required |
diagonal_eps |
float
|
float. diagonal epsilon. |
required |
Source code in pytorch_optimizer/optimizer/shampoo_utils.py
69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 |
|
add_statistics(grad, _)
Add the statistics.
Source code in pytorch_optimizer/optimizer/shampoo_utils.py
81 82 83 |
|
precondition_gradient(grad)
Get preconditioned gradient.
Source code in pytorch_optimizer/optimizer/shampoo_utils.py
85 86 87 |
|
RMSPropGraft
Bases: SGDGraft
Graft using RMSProp. Essentially an implementation of RMSProp with momentum.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
var |
Tensor
|
torch.Tensor. variable. |
required |
diagonal_eps |
float
|
float. diagonal epsilon. |
required |
Source code in pytorch_optimizer/optimizer/shampoo_utils.py
90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 |
|
add_statistics(grad, beta2)
Add the statistics.
Source code in pytorch_optimizer/optimizer/shampoo_utils.py
102 103 104 |
|
precondition_gradient(grad)
Get preconditioned gradient.
Source code in pytorch_optimizer/optimizer/shampoo_utils.py
106 107 108 |
|
build_graft(p, graft_type, diagonal_eps=1e-10)
Build Graft by given graft_type.
Source code in pytorch_optimizer/optimizer/shampoo_utils.py
382 383 384 385 386 387 388 389 390 391 392 |
|
Block Partitioner
BlockPartitioner
Partition a tensor into smaller tensors for preconditioning.
For example, if a variable has shape (4096, 512), we might split the 4096 into 4 blocks,
so we effectively have 4 variables of size (1024, 512) each.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
var |
Tensor
|
torch.Tensor. tensor variable. |
required |
rank |
int
|
int. rank. |
required |
block_size |
int
|
int. block size. |
required |
pre_conditioner_type |
int
|
int type of pre-conditioner. |
required |
Source code in pytorch_optimizer/optimizer/shampoo_utils.py
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 |
|
build_pre_conditioner_shapes(split_sizes, pre_conditioner_type, rank)
staticmethod
Build pre-conditioner shapes.
Source code in pytorch_optimizer/optimizer/shampoo_utils.py
153 154 155 156 157 158 159 160 161 162 163 164 165 166 |
|
merge_partitions(partitions)
Merge partitions back to original shape.
Source code in pytorch_optimizer/optimizer/shampoo_utils.py
184 185 186 187 188 189 190 191 192 193 |
|
partition(x)
Partition tensor into blocks.
Source code in pytorch_optimizer/optimizer/shampoo_utils.py
172 173 174 175 176 177 178 179 180 181 182 |
|
shapes_for_pre_conditioners()
Get shapes of pre-conditioner.
Source code in pytorch_optimizer/optimizer/shampoo_utils.py
168 169 170 |
|
Pre-Conditioner
PreConditionerType
Bases: IntEnum
Type of PreConditioner.
In default (ALL), computes pre-conditioner for each dim. INPUT/OUTPUT is one-sided Shampoo, in this case only on input/output dim. Assumes last dim is always the output dim and everything else input dim.
Source code in pytorch_optimizer/optimizer/shampoo_utils.py
196 197 198 199 200 201 202 203 204 205 206 |
|
PreConditioner
Compute statistics & shape from gradients for preconditioning.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
var |
Tensor
|
torch.Tensor. variable. |
required |
beta2 |
float
|
float. beta2. |
required |
inverse_exponent_override |
int
|
int. override inv exp. |
required |
block_size |
int
|
int. size of block. |
required |
skip_preconditioning_rank_lt |
int
|
int. skip low-rank parameter. |
required |
no_preconditioning_for_layers_with_dim_gt |
int
|
int. skip large size of dim of parameter. |
required |
shape_interpretation |
bool
|
bool. reshaping parameter. |
required |
pre_conditioner_type |
int
|
int. type of pre-conditioner. |
required |
matrix_eps |
float
|
float. epsilon of matrix. |
1e-06
|
use_svd |
bool
|
bool. use SVD instead of Schur-Newton method to calculate M^{-1/p}. |
False
|
Source code in pytorch_optimizer/optimizer/shampoo_utils.py
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 |
|
add_statistics(grad)
Compute statistics from gradients and add to the correct state entries.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
grad |
Tensor
|
torch.Tensor. gradient to compute statistics from. |
required |
Source code in pytorch_optimizer/optimizer/shampoo_utils.py
294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 |
|
compute_pre_conditioners()
Compute L^{-1/exp} for each stats matrix L.
If self.use_svd
is enabled and where all shapes of statistics & pre-conditioners are same, perform batch SVD.
else, SVD one by one.
If self.use_svd
is disabled, use Schur-Newton method, which is usually much faster.
Source code in pytorch_optimizer/optimizer/shampoo_utils.py
312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 |
|
get_should_precondition_dims()
Get pre-condition dimensions by the type of conditioner.
Source code in pytorch_optimizer/optimizer/shampoo_utils.py
279 280 281 282 283 284 285 286 287 |
|
precondition_block(partitioned_grad, should_preconditioned_dims, pre_conditioners_for_grad)
staticmethod
Perform a preconditioning operation on a single gradient block.
Loop invariant: the dimension to be preconditioned is first We keep all axes in the same cyclic order they were originally.
Source code in pytorch_optimizer/optimizer/shampoo_utils.py
332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 |
|
preconditioned_grad(grad)
Precondition the gradient.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
grad |
Tensor
|
torch.Tensor. a gradient tensor to precondition. |
required |
Source code in pytorch_optimizer/optimizer/shampoo_utils.py
357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 |
|