Parametric Optimizer#
optimizer
#
| FUNCTION | DESCRIPTION |
|---|---|
initialize_optimizer_fn |
Initialize optimizer class from string name or class/instance. |
Functions#
initialize_optimizer_fn(optimizer_fn: type[torch.optim.Optimizer] | torch.optim.Optimizer | str | None, optimizer_kwargs: dict[str, Any] | None = None) -> type[torch.optim.Optimizer]
#
Initialize optimizer class from string name or class/instance.
This function provides flexible optimizer initialization following the pattern used for kernels and distance functions in the Spectre library. It accepts optimizer specifications as strings, classes, or instances and returns an optimizer class ready for instantiation with model parameters.
| PARAMETER | DESCRIPTION |
|---|---|
optimizer_fn
|
Optimizer specification:
TYPE:
|
optimizer_kwargs
|
Keyword arguments for optimizer instantiation. Only used when
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
type[Optimizer]
|
Optimizer class ready for instantiation with |
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If |
TypeError
|
If |
Examples:
Using string optimizer name:
>>> from spectre.parametric.optimizer_utils import initialize_optimizer_fn
>>> optimizer_cls = initialize_optimizer_fn("AdamW")
>>> optimizer_cls
<class 'torch.optim.adamw.AdamW'>
Using optimizer class (supports third-party):
>>> import torch.optim
>>> optimizer_cls = initialize_optimizer_fn(torch.optim.SGD)
>>> optimizer_cls
<class 'torch.optim.sgd.SGD'>
Using default (None):
With validation - kwargs with instance raises error:
>>> from torch.optim import Adam
>>> model = torch.nn.Linear(10, 2)
>>> opt_instance = Adam(model.parameters(), lr=1e-3)
>>> initialize_optimizer_fn(opt_instance, {"lr": 1e-4})
Traceback (most recent call last):
...
ValueError: optimizer_kwargs cannot be provided with optimizer instance
Notes
This function returns the optimizer class, not an instantiated optimizer.
The actual instantiation with model.parameters() should be done later in
the configure_optimizers() method to ensure correct parameter binding.
Source code in spectre/parametric/optimizer.py
8 9 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 | |