pitchscapes.optimization.WarmAdam
- class pitchscapes.optimization.WarmAdam(params, lr=0.001, init_lr=None, lr_beta=0.0, betas=(0.9, 0.999), eps=1e-08, weight_decay=0, amsgrad=False)[source]
Bases:
OptimizerModified from Adam class
Public Data Attributes:
alias of
Callable[[Self,Tuple[Any, ...],Dict[str,Any]],Tuple[Tuple[Any, ...],Dict[str,Any]] |None]alias of
Callable[[Self,Tuple[Any, ...],Dict[str,Any]],None]stateparam_groupsInherited from
OptimizerOptimizerPreHookalias of
Callable[[Self,Tuple[Any, ...],Dict[str,Any]],Tuple[Tuple[Any, ...],Dict[str,Any]] |None]OptimizerPostHookalias of
Callable[[Self,Tuple[Any, ...],Dict[str,Any]],None]Public Methods:
__init__(params[, lr, init_lr, lr_beta, ...])__setstate__(state)step([closure])Performs a single optimization step.
Inherited from
Optimizer__init__(params, defaults)__getstate__()Helper for pickle.
__setstate__(state)__repr__()Return repr(self).
profile_hook_step(func)register_step_pre_hook(hook)Register an optimizer step pre hook which will be called before optimizer step.
register_step_post_hook(hook)Register an optimizer step post hook which will be called after optimizer step.
register_state_dict_pre_hook(hook[, prepend])Register a state dict pre-hook which will be called before
state_dict()is called.register_state_dict_post_hook(hook[, prepend])Register a state dict post-hook which will be called after
state_dict()is called.state_dict()Return the state of the optimizer as a
dict.register_load_state_dict_pre_hook(hook[, ...])Register a load_state_dict pre-hook which will be called before
load_state_dict()is called. It should have the following signature::.register_load_state_dict_post_hook(hook[, ...])Register a load_state_dict post-hook which will be called after
load_state_dict()is called. It should have the following signature::.load_state_dict(state_dict)Load the optimizer state.
zero_grad([set_to_none])Reset the gradients of all optimized
torch.Tensors.step([closure])Perform a single optimization step to update parameter.
add_param_group(param_group)Add a param group to the
Optimizers param_groups.Private Data Attributes:
Inherited from
Optimizer_optimizer_step_pre_hooks_optimizer_step_post_hooks_optimizer_state_dict_pre_hooks_optimizer_state_dict_post_hooks_optimizer_load_state_dict_pre_hooks_optimizer_load_state_dict_post_hooksPrivate Methods:
Inherited from
Optimizer_cuda_graph_capture_health_check()_optimizer_step_code()Entry point for torch.profile.profiler.
_group_tensors_by_device_and_dtype(...[, ...])Group a list of lists of tensors by device and dtype.
_patch_step_function()_process_value_according_to_param_policy(...)
- OptimizerPostHook
alias of
Callable[[Self,Tuple[Any, …],Dict[str,Any]],None]
- OptimizerPreHook
alias of
Callable[[Self,Tuple[Any, …],Dict[str,Any]],Tuple[Tuple[Any, …],Dict[str,Any]] |None]
- __annotations__ = {'OptimizerPostHook': 'TypeAlias', 'OptimizerPreHook': 'TypeAlias', '_optimizer_load_state_dict_post_hooks': '\'OrderedDict[int, Callable[["Optimizer"], None]]\'', '_optimizer_load_state_dict_pre_hooks': '\'OrderedDict[int, Callable[["Optimizer", StateDict], Optional[StateDict]]]\'', '_optimizer_state_dict_post_hooks': '\'OrderedDict[int, Callable[["Optimizer", StateDict], Optional[StateDict]]]\'', '_optimizer_state_dict_pre_hooks': '\'OrderedDict[int, Callable[["Optimizer"], None]]\'', '_optimizer_step_post_hooks': 'Dict[int, OptimizerPostHook]', '_optimizer_step_pre_hooks': 'Dict[int, OptimizerPreHook]', 'param_groups': 'List[Dict[str, Any]]', 'state': 'DefaultDict[torch.Tensor, Any]'}
- __dict__ = mappingproxy({'__module__': 'pitchscapes.optimization', '__doc__': '\n Modified from Adam class\n ', '__init__': <function WarmAdam.__init__>, '__setstate__': <function WarmAdam.__setstate__>, 'step': <function WarmAdam.step>, '__annotations__': {'OptimizerPreHook': 'TypeAlias', 'OptimizerPostHook': 'TypeAlias', '_optimizer_step_pre_hooks': 'Dict[int, OptimizerPreHook]', '_optimizer_step_post_hooks': 'Dict[int, OptimizerPostHook]', '_optimizer_state_dict_pre_hooks': '\'OrderedDict[int, Callable[["Optimizer"], None]]\'', '_optimizer_state_dict_post_hooks': '\'OrderedDict[int, Callable[["Optimizer", StateDict], Optional[StateDict]]]\'', '_optimizer_load_state_dict_pre_hooks': '\'OrderedDict[int, Callable[["Optimizer", StateDict], Optional[StateDict]]]\'', '_optimizer_load_state_dict_post_hooks': '\'OrderedDict[int, Callable[["Optimizer"], None]]\'', 'state': 'DefaultDict[torch.Tensor, Any]', 'param_groups': 'List[Dict[str, Any]]'}})
- __getstate__()
Helper for pickle.
- Return type:
Dict[str,Any]
- __init__(params, lr=0.001, init_lr=None, lr_beta=0.0, betas=(0.9, 0.999), eps=1e-08, weight_decay=0, amsgrad=False)[source]
- __module__ = 'pitchscapes.optimization'
- __repr__()
Return repr(self).
- Return type:
str
- __weakref__
list of weak references to the object
- _cuda_graph_capture_health_check()
- Return type:
None
- static _group_tensors_by_device_and_dtype(tensorlistlist, with_indices=False)
Group a list of lists of tensors by device and dtype.
Skips this step if we are compiling since this will occur during inductor lowering.
- Return type:
Union[Dict[Tuple[None,None],Tuple[List[List[Optional[Tensor]]],List[int]]],Dict[Tuple[device,dtype],Tuple[List[List[Optional[Tensor]]],List[int]]]]
- _optimizer_load_state_dict_post_hooks: OrderedDict[int, Callable[["Optimizer"], None]]
- _optimizer_load_state_dict_pre_hooks: OrderedDict[int, Callable[["Optimizer", StateDict], Optional[StateDict]]]
- _optimizer_state_dict_post_hooks: OrderedDict[int, Callable[["Optimizer", StateDict], Optional[StateDict]]]
- _optimizer_state_dict_pre_hooks: OrderedDict[int, Callable[["Optimizer"], None]]
- _optimizer_step_code()
Entry point for torch.profile.profiler.
When python tracing is enabled the profiler will hook into this function at the CPython level to inspect the optimizer’s parameters and param groups. It is called it after step() since many optimizers lazily initialize state.
This is a workaround due to lack of a proper step hook on the optimizer, and will be removed if it exists.
- Return type:
None
- _optimizer_step_post_hooks: Dict[int, OptimizerPostHook]
- _optimizer_step_pre_hooks: Dict[int, OptimizerPreHook]
- _patch_step_function()
- Return type:
None
- static _process_value_according_to_param_policy(param, value, param_id, param_groups, key=None)
- Return type:
Tensor
- add_param_group(param_group)
Add a param group to the
Optimizers param_groups.This can be useful when fine tuning a pre-trained network as frozen layers can be made trainable and added to the
Optimizeras training progresses.- Return type:
None
- Args:
- param_group (dict): Specifies what Tensors should be optimized along with group
specific optimization options.
- load_state_dict(state_dict)
Load the optimizer state.
- Return type:
None
- Args:
- state_dict (dict): optimizer state. Should be an object returned
from a call to
state_dict().
Note
The names of the parameters (if they exist under the “param_names” key of each param group in
state_dict()) will not affect the loading process. To use the parameters’ names for custom cases (such as when the parameters in the loaded state dict differ from those initialized in the optimizer), a customregister_load_state_dict_pre_hookshould be implemented to adapt the loaded dict accordingly. Ifparam_namesexist in loaded state dictparam_groupsthey will be saved and override the current names, if present, in the optimizer state. If they do not exist in loaded state dict, the optimizerparam_nameswill remain unchanged.
- static profile_hook_step(func)
- Return type:
Callable[[ParamSpec(_P, bound=None)],TypeVar(R)]
- register_load_state_dict_post_hook(hook, prepend=False)
Register a load_state_dict post-hook which will be called after
load_state_dict()is called. It should have the following signature:hook(optimizer) -> None
The
optimizerargument is the optimizer instance being used.The hook will be called with argument
selfafter callingload_state_dictonself. The registered hook can be used to perform post-processing afterload_state_dicthas loaded thestate_dict.- Return type:
RemovableHandle
- Args:
hook (Callable): The user defined hook to be registered. prepend (bool): If True, the provided post
hookwill be fired beforeall the already registered post-hooks on
load_state_dict. Otherwise, the providedhookwill be fired after all the already registered post-hooks. (default: False)- Returns:
torch.utils.hooks.RemoveableHandle:a handle that can be used to remove the added hook by calling
handle.remove()
- register_load_state_dict_pre_hook(hook, prepend=False)
Register a load_state_dict pre-hook which will be called before
load_state_dict()is called. It should have the following signature:hook(optimizer, state_dict) -> state_dict or None
The
optimizerargument is the optimizer instance being used and thestate_dictargument is a shallow copy of thestate_dictthe user passed in toload_state_dict. The hook may modify the state_dict inplace or optionally return a new one. If a state_dict is returned, it will be used to be loaded into the optimizer.The hook will be called with argument
selfandstate_dictbefore callingload_state_dictonself. The registered hook can be used to perform pre-processing before theload_state_dictcall is made.- Return type:
RemovableHandle
- Args:
hook (Callable): The user defined hook to be registered. prepend (bool): If True, the provided pre
hookwill be fired beforeall the already registered pre-hooks on
load_state_dict. Otherwise, the providedhookwill be fired after all the already registered pre-hooks. (default: False)- Returns:
torch.utils.hooks.RemoveableHandle:a handle that can be used to remove the added hook by calling
handle.remove()
- register_state_dict_post_hook(hook, prepend=False)
Register a state dict post-hook which will be called after
state_dict()is called.It should have the following signature:
hook(optimizer, state_dict) -> state_dict or None
The hook will be called with arguments
selfandstate_dictafter generating astate_dictonself. The hook may modify the state_dict inplace or optionally return a new one. The registered hook can be used to perform post-processing on thestate_dictbefore it is returned.- Return type:
RemovableHandle
- Args:
hook (Callable): The user defined hook to be registered. prepend (bool): If True, the provided post
hookwill be fired beforeall the already registered post-hooks on
state_dict. Otherwise, the providedhookwill be fired after all the already registered post-hooks. (default: False)- Returns:
torch.utils.hooks.RemoveableHandle:a handle that can be used to remove the added hook by calling
handle.remove()
- register_state_dict_pre_hook(hook, prepend=False)
Register a state dict pre-hook which will be called before
state_dict()is called.It should have the following signature:
hook(optimizer) -> None
The
optimizerargument is the optimizer instance being used. The hook will be called with argumentselfbefore callingstate_dictonself. The registered hook can be used to perform pre-processing before thestate_dictcall is made.- Return type:
RemovableHandle
- Args:
hook (Callable): The user defined hook to be registered. prepend (bool): If True, the provided pre
hookwill be fired beforeall the already registered pre-hooks on
state_dict. Otherwise, the providedhookwill be fired after all the already registered pre-hooks. (default: False)- Returns:
torch.utils.hooks.RemoveableHandle:a handle that can be used to remove the added hook by calling
handle.remove()
- register_step_post_hook(hook)
Register an optimizer step post hook which will be called after optimizer step.
It should have the following signature:
hook(optimizer, args, kwargs) -> None
The
optimizerargument is the optimizer instance being used.- Return type:
RemovableHandle
- Args:
hook (Callable): The user defined hook to be registered.
- Returns:
torch.utils.hooks.RemovableHandle:a handle that can be used to remove the added hook by calling
handle.remove()
- register_step_pre_hook(hook)
Register an optimizer step pre hook which will be called before optimizer step.
It should have the following signature:
hook(optimizer, args, kwargs) -> None or modified args and kwargs
The
optimizerargument is the optimizer instance being used. If args and kwargs are modified by the pre-hook, then the transformed values are returned as a tuple containing the new_args and new_kwargs.- Return type:
RemovableHandle
- Args:
hook (Callable): The user defined hook to be registered.
- Returns:
torch.utils.hooks.RemovableHandle:a handle that can be used to remove the added hook by calling
handle.remove()
- state_dict()
Return the state of the optimizer as a
dict.It contains two entries: :rtype:
Dict[str,Any]state: a Dict holding current optimization state. Its contentdiffers between optimizer classes, but some common characteristics hold. For example, state is saved per parameter, and the parameter itself is NOT saved.
stateis a Dictionary mapping parameter ids to a Dict with state corresponding to each parameter.
param_groups: a List containing all parameter groups where eachparameter group is a Dict. Each parameter group contains metadata specific to the optimizer, such as learning rate and weight decay, as well as a List of parameter IDs of the parameters in the group. If a param group was initialized with
named_parameters()the names content will also be saved in the state dict.
NOTE: The parameter IDs may look like indices but they are just IDs associating state with param_group. When loading from a state_dict, the optimizer will zip the param_group
params(int IDs) and the optimizerparam_groups(actualnn.Parameters) in order to match state WITHOUT additional verification.A returned state dict might look something like:
{ 'state': { 0: {'momentum_buffer': tensor(...), ...}, 1: {'momentum_buffer': tensor(...), ...}, 2: {'momentum_buffer': tensor(...), ...}, 3: {'momentum_buffer': tensor(...), ...} }, 'param_groups': [ { 'lr': 0.01, 'weight_decay': 0, ... 'params': [0] 'param_names' ['param0'] (optional) }, { 'lr': 0.001, 'weight_decay': 0.5, ... 'params': [1, 2, 3] 'param_names': ['param1', 'layer.weight', 'layer.bias'] (optional) } ] }
- step(closure=None)[source]
Performs a single optimization step.
- Arguments:
- closure (callable, optional): A closure that reevaluates the model
and returns the loss.
- zero_grad(set_to_none=True)
Reset the gradients of all optimized
torch.Tensors.- Return type:
None
- Args:
- set_to_none (bool): instead of setting to zero, set the grads to None.
This will in general have lower memory footprint, and can modestly improve performance. However, it changes certain behaviors. For example: 1. When the user tries to access a gradient and perform manual ops on it, a None attribute or a Tensor full of 0s will behave differently. 2. If the user requests
zero_grad(set_to_none=True)followed by a backward pass,.grads are guaranteed to be None for params that did not receive a gradient. 3.torch.optimoptimizers have a different behavior if the gradient is 0 or None (in one case it does the step with a gradient of 0 and in the other it skips the step altogether).