API reference for core module¶
Modules:
-
chain
– -
functional
– -
modular
– -
module
– -
reformulation
– -
transform
–
Classes:
-
Chain
–Chain modules, mostly used internally
-
Module
–Abstract base class for an optimizer modules.
-
Optimizer
–Chains multiple modules into an optimizer.
-
TensorTransform
–TensorTransform
is aTransform
that doesn't useObjective
, instead it operates -
Transform
–Transform
is aModule
with only optional children.
Functions:
-
maybe_chain
–Returns a single module directly if only one is provided, otherwise wraps them in a
Chain
. -
step
–doesn't apply hooks!
Attributes:
-
Chainable
–Represent a PEP 604 union type
Chainable
module-attribute
¶
Represent a PEP 604 union type
E.g. for int | str
Chain ¶
Bases: torchzero.core.module.Module
Chain modules, mostly used internally
Source code in torchzero/core/chain.py
Module ¶
Bases: abc.ABC
Abstract base class for an optimizer modules.
Modules represent distinct steps or transformations within the optimization process (e.g., momentum, line search, gradient accumulation).
A module does not store parameters, but it maintains per-parameter state and per-parameter settings where tensors are used as keys (same as torch.optim.Optimizer state.)
Parameters:
-
defaults
(dict[str, Any] | None
, default:None
) –a dict containing default values of optimization options (used when a parameter group doesn't specify them).
Methods:
-
apply
–Updates
objective
using the internal state of this module. -
get_H
–returns a
LinearOperator
corresponding to hessian or hessian approximation. -
get_generator
–If
seed=None
, returnsNone
. -
get_state
–Returns values of per-parameter state for a given key.
-
increment_counter
–first value is
start
-
inner_step
–Passes
objective
to child and returns it. -
inner_step_tensors
–Steps with child module. Can be used to apply transforms to any internal buffers.
-
reset
–Resets the internal state of the module (e.g. momentum) and all children. By default clears state and global state.
-
reset_for_online
–Resets buffers that depend on previous evaluation, such as previous gradient and loss,
-
set_param_groups
–Set custom parameter groups with per-parameter settings that this module will use.
-
state_dict
–state dict
-
step
–Perform a step with this module. Calls
update
, thenapply
. -
update
–Updates internal state of this module. This should not modify
objective.update
.
Source code in torchzero/core/module.py
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 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 |
|
apply ¶
Updates objective
using the internal state of this module.
If update
method is defined, apply
shouldn't modify the internal state of this module if possible.
Specifying update
and apply
methods is optional and allows certain meta-modules to be used,
such as tz.m.Online
or trust regions. Alternatively, define all logic within the apply
method.
update
is guaranteed to be called at least once before apply
.
Parameters:
-
objective
(Objective
) –Objective
object
Source code in torchzero/core/module.py
get_H ¶
returns a LinearOperator
corresponding to hessian or hessian approximation.
The hessian approximation is assumed to be for all parameters concatenated to a vector.
Source code in torchzero/core/module.py
get_generator ¶
If seed=None
, returns None
.
Otherwise, if generator on this device and with this seed hasn't been created, creates it and stores in global state.
Returns torch.Generator
.
Source code in torchzero/core/module.py
get_state ¶
get_state(params: Sequence[Tensor], key: str | list[str] | tuple[str, ...], key2: str | None = None, *keys: str, must_exist: bool = False, init: Any | Sequence[Any] = zeros_like, cls: type[~ListLike] = list) -> Union[~ListLike, list[~ListLike]]
Returns values of per-parameter state for a given key. If key doesn't exist, create it with inits.
This functions like operator.itemgetter
, returning a single value if called with a single key,
or tuple of called with multiple keys.
If you want to force it to return a tuple even with a single key, pass a list/tuple of 1 or more keys.
exp_avg = self.state_vals("exp_avg")
# returns cls (by default TensorList)
exp_avg, exp_avg_sq = self.state_vals("exp_avg", "exp_avg_sq")
# returns list of cls
exp_avg = self.state_vals(["exp_avg"])
# always returns a list of cls, even if got a single key
Parameters:
-
*keys
(str
) –the keys to look for in each parameters state. if a single key is specified, this returns a single value or cls, otherwise this returns a list of values or cls per each key.
-
params
(Iterable[Tensor]
) –parameters to return the states for.
-
must_exist
(bool
, default:False
) –If a key doesn't exist in state, if True, raises a KeyError, if False, creates the value using
init
argument (default = False). -
init
(Any | Sequence[Any]
, default:zeros_like
) –how to initialize a key if it doesn't exist.
can be - Callable like torch.zeros_like - string - "param" or "grad" to use cloned params or cloned grads. - anything else other than list/tuples will be used as-is, tensors will be cloned. - list/tuple of values per each parameter, only if got a single key. - list/tuple of values per each key, only if got multiple keys.
if multiple
keys
are specified, inits is per-key!Defaults to torch.zeros_like.
-
cls
(type[ListLike]
, default:list
) –MutableSequence class to return, this only has effect when state_keys is a list/tuple. Defaults to list.
Returns:
-
Union[~ListLike, list[~ListLike]]
–- if state_keys has a single key and keys has a single key, return a single value.
-
Union[~ListLike, list[~ListLike]]
–- if state_keys has a single key and keys has multiple keys, return a list of values.
-
Union[~ListLike, list[~ListLike]]
–- if state_keys has multiple keys and keys has a single key, return cls.
-
Union[~ListLike, list[~ListLike]]
–- if state_keys has multiple keys and keys has multiple keys, return list of cls.
Source code in torchzero/core/module.py
increment_counter ¶
inner_step ¶
Passes objective
to child and returns it.
Source code in torchzero/core/module.py
inner_step_tensors ¶
inner_step_tensors(key: str, tensors: list[Tensor], clone: bool, params: Iterable[Tensor] | None = None, grads: Sequence[Tensor] | None = None, loss: Tensor | None = None, closure: Callable | None = None, objective: Objective | None = None, must_exist: bool = True) -> list[Tensor]
Steps with child module. Can be used to apply transforms to any internal buffers.
If objective
is specified, other attributes shouldn't to be specified.
Parameters:
-
key
(str
) –Child module key.
-
tensors
(Sequence[Tensor]
) –tensors to pass to child module.
-
clone
(bool
) –If
key
exists, whether to clonetensors
to avoid modifying buffers in-place. Ifkey
doesn't exist,tensors
are always returned without cloning -
params
(Iterable[Tensor] | None
, default:None
) –pass None if
tensors
have different shape. Defaults to None. -
grads
(Sequence[Tensor] | None
, default:None
) –grads. Defaults to None.
-
loss
(Tensor | None
, default:None
) –loss. Defaults to None.
-
closure
(Callable | None
, default:None
) –closure. Defaults to None.
-
must_exist
(bool
, default:True
) –if True, if
key
doesn't exist, raisesKeyError
. Defaults to True.
Source code in torchzero/core/module.py
reset ¶
Resets the internal state of the module (e.g. momentum) and all children. By default clears state and global state.
Source code in torchzero/core/module.py
reset_for_online ¶
Resets buffers that depend on previous evaluation, such as previous gradient and loss, which may become inaccurate due to mini-batching.
Online
module calls reset_for_online
,
then it calls update
with previous parameters,
then it calls update
with current parameters,
and then apply
.
Source code in torchzero/core/module.py
set_param_groups ¶
Set custom parameter groups with per-parameter settings that this module will use.
Source code in torchzero/core/module.py
state_dict ¶
state dict
Source code in torchzero/core/module.py
step ¶
update ¶
Updates internal state of this module. This should not modify objective.update
.
Specifying update
and apply
methods is optional and allows certain meta-modules to be used,
such as tz.m.Online
or trust regions. Alternatively, define all logic within the apply
method.
update
is guaranteed to be called at least once before apply
.
Parameters:
-
objective
(Objective
) –Objective
object
Source code in torchzero/core/module.py
Optimizer ¶
Bases: torch.optim.optimizer.Optimizer
Chains multiple modules into an optimizer.
Parameters:
-
params
(Iterable | Module
) –An iterable of parameters to optimize (typically
model.parameters()
), an iterable of parameter group dicts, or atorch.nn.Module
instance. -
*modules
(Module
) –A sequence of
Module
instances that define the optimization algorithm steps.
Source code in torchzero/core/modular.py
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 |
|
TensorTransform ¶
Bases: torchzero.core.transform.Transform
TensorTransform
is a Transform
that doesn't use Objective
, instead it operates
on lists of tensors directly.
This has a concat_params
setting which is used in quite a few modules, for example it is optional
in all full-matrix method like Quasi-Newton or full-matrix Adagrad.
To use, subclass this and override one of single_tensor_update
or multi_tensor_update
,
and one of single_tensor_apply
or multi_tensor_apply
.
For copying:
multi tensor:
def multi_tensor_initialize(self, tensors, params, grads, loss, states, settings):
...
def multi_tensor_update(self, tensors, params, grads, loss, states, settings):
...
def multi_tensor_apply(self, tensors, params, grads, loss, states, settings):
...
single tensor:
def single_tensor_initialize(self, tensor, param, grad, loss, state, setting):
...
def single_tensor_update(self, tensor, param, grad, loss, state, setting):
...
def single_tensor_apply(self, tensor, param, grad, loss, state, setting):
...
Methods:
-
multi_tensor_apply
–Updates
tensors
and returns it. This shouldn't modifystate
if possible. -
multi_tensor_initialize
–initialize
states
before firstupdate
. -
multi_tensor_update
–Updates
states
. This should not modifytensor
. -
single_tensor_apply
–Updates
tensor
and returns it. This shouldn't modifystate
if possible. -
single_tensor_initialize
–initialize
state
before firstupdate
. -
single_tensor_update
–Updates
state
. This should not modifytensor
.
Source code in torchzero/core/transform.py
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 |
|
multi_tensor_apply ¶
multi_tensor_apply(tensors: list[Tensor], params: list[Tensor], grads: list[Tensor] | None, loss: Tensor | None, states: list[dict[str, Any]], settings: Sequence[Mapping[str, Any]]) -> Sequence[Tensor]
Updates tensors
and returns it. This shouldn't modify state
if possible.
By default calls single_tensor_apply
on all tensors.
Source code in torchzero/core/transform.py
multi_tensor_initialize ¶
multi_tensor_initialize(tensors: list[Tensor], params: list[Tensor], grads: list[Tensor] | None, loss: Tensor | None, states: list[dict[str, Any]], settings: Sequence[Mapping[str, Any]]) -> None
initialize states
before first update
.
By default calls single_tensor_initialize
on all tensors.
Source code in torchzero/core/transform.py
multi_tensor_update ¶
multi_tensor_update(tensors: list[Tensor], params: list[Tensor], grads: list[Tensor] | None, loss: Tensor | None, states: list[dict[str, Any]], settings: Sequence[Mapping[str, Any]]) -> None
Updates states
. This should not modify tensor
.
By default calls single_tensor_update
on all tensors.
Source code in torchzero/core/transform.py
single_tensor_apply ¶
single_tensor_apply(tensor: Tensor, param: Tensor, grad: Tensor | None, loss: Tensor | None, state: dict[str, Any], setting: Mapping[str, Any]) -> Tensor
Updates tensor
and returns it. This shouldn't modify state
if possible.
Source code in torchzero/core/transform.py
single_tensor_initialize ¶
single_tensor_initialize(tensor: Tensor, param: Tensor, grad: Tensor | None, loss: Tensor | None, state: dict[str, Any], setting: Mapping[str, Any]) -> None
initialize state
before first update
.
Source code in torchzero/core/transform.py
single_tensor_update ¶
single_tensor_update(tensor: Tensor, param: Tensor, grad: Tensor | None, loss: Tensor | None, state: dict[str, Any], setting: Mapping[str, Any]) -> None
Updates state
. This should not modify tensor
.
Source code in torchzero/core/transform.py
Transform ¶
Bases: torchzero.core.module.Module
Transform
is a Module
with only optional children.
Transform
if more flexible in that as long as there are no children, it can use a custom list of states
and settings instead of self.state
and self.setting
.
To use, subclass this and override update_states
and apply_states
.
Methods:
-
apply_states
–Updates
objective
usingstates
. -
update_states
–Updates
states
. This should not modifyobjective.update
.
Source code in torchzero/core/transform.py
apply_states ¶
update_states ¶
update_states(objective: Objective, states: list[dict[str, Any]], settings: Sequence[Mapping[str, Any]]) -> None
Updates states
. This should not modify objective.update
.
maybe_chain ¶
Returns a single module directly if only one is provided, otherwise wraps them in a Chain
.
Source code in torchzero/core/chain.py
step ¶
doesn't apply hooks!