API reference for core module¶
Modules:
-
module
– -
reformulation
– -
transform
–
Classes:
-
Chain
–Chain of modules, mostly used internally
-
Modular
–Chains multiple modules into an optimizer.
-
Module
–Abstract base class for an optimizer modules.
-
TensorwiseTransform
–Base class for a parameter-wise transform.
-
Transform
–Base class for a transform.
-
Var
–Holds parameters, gradient, update, objective function (closure) if supplied, loss, and some other info.
Functions:
-
maybe_chain
–Returns a single module directly if only one is provided, otherwise wraps them in a :code:
Chain
.
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 of modules, mostly used internally
Source code in torchzero/core/module.py
Modular ¶
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/module.py
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 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 |
|
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:
-
Hvp
–Returns
(Hvp, rgrad)
, wherergrad
is gradient at current parameters, -
apply
–Applies this module to
var.get_update()
. -
get_H
–returns a
LinearOperator
corresponding to hessian or hessian approximation. -
get_state
–Returns values of per-parameter state for a given key.
-
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
–performs a step, returns new
var
but may update it in-place. -
update
–Updates the internal state of this module. This should not modify
var.update
.
Source code in torchzero/core/module.py
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 |
|
Hvp ¶
Hvp(v: Sequence[Tensor], at_x0: bool, var: Var, rgrad: Sequence[Tensor] | None, hvp_method: Literal['autograd', 'forward', 'central'], h: float, normalize: bool, retain_grad: bool) -> tuple[Sequence[Tensor], Sequence[Tensor] | None]
Returns (Hvp, rgrad)
, where rgrad
is gradient at current parameters,
possibly with create_graph=True
, or it may be None with hvp_method="central"
.
Gradient is set to vars automatically if at_x0
, you can always access it with vars.get_grad()
Single sample example:
Multiple samples example:
D = None
rgrad = None
for i in range(n_samples):
v = [torch.randn_like(p) for p in params]
Hvp, rgrad = self.hvp(v, at_x0=True, rgrad=rgrad, ..., retain_graph=i < n_samples-1)
if D is None: D = Hvp
else: torch._foreach_add_(D, Hvp)
if n_samples > 1: torch._foreach_div_(D, n_samples)
Parameters:
-
v
(Sequence[Tensor]
) –vector in hessian-vector product
-
at_x0
(bool
) –whether this is being called at original or perturbed parameters.
-
var
(Var
) –Var
-
rgrad
(Sequence[Tensor] | None
) –pass None initially, then pass what this returns.
-
hvp_method
(str
) –hvp method.
-
h
(float
) –finite difference step size
-
normalize
(bool
) –whether to normalize v for finite difference
-
retain_grad
(bool
) –retain grad
Source code in torchzero/core/module.py
apply ¶
Applies this module to var.get_update()
.
This should not 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, simply override the step
method.
Source code in torchzero/core/module.py
get_H ¶
get_H(var: Var) -> LinearOperator | None
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_state ¶
get_state(params: Sequence[Tensor], key: str | list[str] | tuple[str, ...], key2: str | None = None, *keys: str, must_exist: bool = False, init: Union[Literal['param', 'grad'], Any, list[Union[Literal['param', 'grad'], Any]], tuple[Union[Literal['param', 'grad'], Any]], Sequence[Union[Literal['param', 'grad'], Any, list[Union[Literal['param', 'grad'], Any]], tuple[Union[Literal['param', 'grad'], 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
(Union | Sequence[Union]
, 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
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, 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 ¶
update(var: Var) -> Any
Updates the internal state of this module. This should not modify var.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, simply override the step
method.
Source code in torchzero/core/module.py
TensorwiseTransform ¶
Bases: torchzero.core.transform.Transform
, abc.ABC
Base class for a parameter-wise transform.
This is an abstract class, to use it, subclass it and override update_tensor
and apply_tensor
.
Parameters:
-
defaults
(dict[str, Any] | None
) –dict with default values.
-
uses_grad
(bool
, default:False
) –Set this to True if
transform
method uses thegrad
argument. This will ensuregrad
is always computed and can't be None. Otherwise set to False. -
target
(Literal
, default:'update'
) –what to set on var. Defaults to 'update'.
Methods:
-
apply_tensor
–Applies the update rule to
tensor
. -
update_tensor
–Updates this transform. By default does nothing - if logic is in
apply
method.
Source code in torchzero/core/transform.py
apply_tensor ¶
apply_tensor(tensor: Tensor, param: Tensor, grad: Tensor | None, loss: Tensor | float | None, state: dict[str, Any], setting: Mapping[str, Any]) -> Tensor
Applies the update rule to tensor
.
Source code in torchzero/core/transform.py
update_tensor ¶
update_tensor(tensor: Tensor, param: Tensor, grad: Tensor | None, loss: Tensor | float | None, state: dict[str, Any], setting: Mapping[str, Any]) -> None
Updates this transform. By default does nothing - if logic is in apply
method.
Source code in torchzero/core/transform.py
Transform ¶
Bases: torchzero.core.module.Module
, abc.ABC
Base class for a transform.
This is an abstract class, to use it, subclass it and override update_tensors
and apply_tensors
methods.
A transform is a module that can also be applied manually to an arbitrary sequence of tensors. It has two methods:
update_tensors
updates the internal state of this transform, it doesn't modify tensors. It may be called multiple times beforeapply_tensors
.apply_tensors
applies this transform to tensors, without modifying the internal state if possible.
Alternatively, if update-apply structure doesn't make sense for a transform, all logic can be defined within apply_tensors
.
Transform can be applied to tensors corresponding to custom parameters
by calling keyed_transform_update
and keyed_transform_apply
,
parameters will be keys to store per-parameter states, so they should remain the same python objects.
Alternatively you can manually create a list of state dictionaries per each tensor and pass it to
transform_update
and transform_apply
.
A transform can modify the closure instead of directly modifying update by passing target="closure"
.
Parameters:
-
defaults
(dict[str, Any] | None
) –dict with default values.
-
uses_grad
(bool
, default:False
) –Set this to True if
transform
method uses thegrad
argument. This will ensuregrad
is always computed and can't be None. Otherwise set to False. -
target
(Literal
, default:'update'
) –what to set on var. Defaults to 'update'.
Methods:
-
apply_tensors
–apply function, this shouldn't be called directly. Applies the update rule to
tensors
and returns them. -
keyed_transform_apply
–params
will be used as keys and need to always point to same tensor objects.` -
keyed_transform_update
–params
will be used as keys and need to always point to same tensor objects.` -
post_step
–Logic to run post-transform, this way transform has access to Var.
-
pre_step
–Logic to run pre-transform, this way transform has access to Var.
-
transform_apply
–Applies this transform to an arbitrary sequence of tensors.
-
transform_update
–Updates this transform from an arbitrary sequence of tensors.
-
update_tensors
–update function, this shouldn't be called directly. Updates this module.
Source code in torchzero/core/transform.py
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 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 |
|
apply_tensors ¶
apply_tensors(tensors: list[Tensor], params: list[Tensor], grads: list[Tensor] | None, loss: Tensor | float | None, states: list[dict[str, Any]], settings: Sequence[Mapping[str, Any]]) -> Sequence[Tensor]
apply function, this shouldn't be called directly. Applies the update rule to tensors
and returns them.
If possible, this shouldn't modify the internal state of this transform.
Source code in torchzero/core/transform.py
keyed_transform_apply ¶
keyed_transform_apply(tensors: list[Tensor], params: list[Tensor], grads: list[Tensor] | None, loss: Tensor | float | None)
params
will be used as keys and need to always point to same tensor objects.`
Source code in torchzero/core/transform.py
keyed_transform_update ¶
keyed_transform_update(tensors: list[Tensor], params: list[Tensor], grads: list[Tensor] | None, loss: Tensor | float | None)
params
will be used as keys and need to always point to same tensor objects.`
Source code in torchzero/core/transform.py
transform_apply ¶
transform_apply(tensors: list[Tensor], params: list[Tensor], grads: list[Tensor] | None, loss: Tensor | float | None, states: list[dict[str, Any]], settings: Sequence[Mapping[str, Any]] | None) -> list[Tensor]
Applies this transform to an arbitrary sequence of tensors.
This can be used after transform_update
has been used at least once.
Source code in torchzero/core/transform.py
transform_update ¶
transform_update(tensors: list[Tensor], params: list[Tensor], grads: list[Tensor] | None, loss: Tensor | float | None, states: list[dict[str, Any]], settings: Sequence[Mapping[str, Any]] | None) -> None
Updates this transform from an arbitrary sequence of tensors.
Source code in torchzero/core/transform.py
update_tensors ¶
update_tensors(tensors: list[Tensor], params: list[Tensor], grads: list[Tensor] | None, loss: Tensor | float | None, states: list[dict[str, Any]], settings: Sequence[Mapping[str, Any]]) -> None
update function, this shouldn't be called directly. Updates this module.
Source code in torchzero/core/transform.py
Var ¶
Holds parameters, gradient, update, objective function (closure) if supplied, loss, and some other info.
Modules take in a Var
object, modify and it is passed to the next module.
Methods:
-
clone
–Creates a shallow copy of the Vars object, update can optionally be deep-copied (via
torch.clone
). -
get_grad
–Returns the gradient at initial parameters, computing it if it hasn't been computed already and assigning
-
get_loss
–Returns the loss at current parameters, computing it if it hasn't been computed already and assigning
var.loss
. -
get_update
–Returns the update. If update is None, it is initialized by cloning the gradients and assigning to
var.update
. -
update_attrs_from_clone_
–Updates attributes of this
Vars
instance from a cloned instance.
Source code in torchzero/core/module.py
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 |
|
clone ¶
clone(clone_update: bool, parent: Var | None = None)
Creates a shallow copy of the Vars object, update can optionally be deep-copied (via torch.clone
).
Doesn't copy is_last
, nested_is_last
and last_module_lrs
. They will always be False
/None
.
Setting parent
is only if clone's parameters are something different,
while clone's closure referes to the same objective but with a "view" on parameters.
Source code in torchzero/core/module.py
get_grad ¶
Returns the gradient at initial parameters, computing it if it hasn't been computed already and assigning
var.grad
and potentially var.loss
. Do not call this at perturbed parameters.
Source code in torchzero/core/module.py
get_loss ¶
Returns the loss at current parameters, computing it if it hasn't been computed already and assigning var.loss
.
Do not call this at perturbed parameters. Backward always sets grads to None before recomputing.
Source code in torchzero/core/module.py
get_update ¶
Returns the update. If update is None, it is initialized by cloning the gradients and assigning to var.update
.
Computing the gradients may assign var.grad
and var.loss
if they haven't been computed.
Do not call this at perturbed parameters.
Source code in torchzero/core/module.py
update_attrs_from_clone_ ¶
update_attrs_from_clone_(var: Var)
Updates attributes of this Vars
instance from a cloned instance.
Typically called after a child module has processed a cloned Vars
object. This propagates any newly computed loss or gradient values
from the child's context back to the parent Vars
if the parent
didn't have them computed already.
Also, as long as post_step_hooks
and attrs
are modified in-place,
if the child updates them, the update will affect the parent too.
Source code in torchzero/core/module.py
maybe_chain ¶
Returns a single module directly if only one is provided, otherwise wraps them in a :code:Chain
.