Broken-stick compression for auditory nerve fiber dynamics.
Implements a piecewise power-law compression where signals below a knee point
pass through unchanged (linear), while signals above the knee are compressed
using a power-law function. This creates a “broken stick” transfer function
that simulates the nonlinear input-output characteristics of inner hair cells
and auditory nerve fibers.
where:
- \(n\) is the compression exponent (typically 0.3)
- \(\\text{knee}\) is the threshold in linear units
- The formula ensures continuity at the knee point
This also makes associated parameters and buffers different objects. So
it should be called before constructing the optimizer if the module will
live on GPU while being optimized.
Note
This method modifies the module in-place.
Args:
device (int, optional): if specified, all parameters will be
This has an effect only on certain modules. See the documentation of
particular modules for details of their behaviors in training/evaluation
mode, i.e. whether they are affected, e.g. Dropout, BatchNorm,
etc.
Return any extra state to include in the module’s state_dict.
Implement this and a corresponding set_extra_state() for your module
if you need to store extra state. This function is called when building the
module’s state_dict().
Note that extra state should be picklable to ensure working serialization
of the state_dict. We only provide backwards compatibility guarantees
for serializing Tensors; other objects may break backwards compatibility if
their serialized pickled form changes.
(The diagram shows an nn.ModuleA. A which has a nested
submodule net_b, which itself has two submodules net_c
and linear. net_c then has a submodule conv.)
To check whether or not we have the linear submodule, we
would call get_submodule("net_b.linear"). To check whether
we have the conv submodule, we would call
get_submodule("net_b.net_c.conv").
The runtime of get_submodule is bounded by the degree
of module nesting in target. A query against
named_modules achieves the same result, but it is O(N) in
the number of transitive modules. So, for a simple check to see
if some submodule exists, get_submodule should always be
used.
Args:
target: The fully-qualified string name of the submodule
to look for. (See above example for how to specify a
fully-qualified string.)
Returns:
torch.nn.Module: The submodule referenced by target
Raises:
AttributeError: If at any point along the path resulting from
the target string the (sub)path resolves to a non-existent
attribute name or an object that is not an instance of nn.Module.
This also makes associated parameters and buffers different objects. So
it should be called before constructing the optimizer if the module will
live on IPU while being optimized.
Note
This method modifies the module in-place.
Arguments:
device (int, optional): if specified, all parameters will be
state_dict (dict): a dict containing parameters and
persistent buffers.
strict (bool, optional): whether to strictly enforce that the keys
in state_dict match the keys returned by this module’s
state_dict() function. Default: True
assign (bool, optional): When set to False, the properties of the tensors
in the current module are preserved whereas setting it to True preserves
properties of the Tensors in the state dict. The only
exception is the requires_grad field of Parameter
for which the value from the module is preserved. Default: False
Returns:
NamedTuple with missing_keys and unexpected_keys fields:
missing_keys is a list of str containing any keys that are expected
by this module but missing from the provided state_dict.
unexpected_keys is a list of str containing the keys that are not
expected by this module but present in the provided state_dict.
Note:
If a parameter or buffer is registered as None and its corresponding key
exists in state_dict, load_state_dict() will raise a
RuntimeError.
Move all model parameters and buffers to the MTIA.
This also makes associated parameters and buffers different objects. So
it should be called before constructing the optimizer if the module will
live on MTIA while being optimized.
Note
This method modifies the module in-place.
Arguments:
device (int, optional): if specified, all parameters will be
Return an iterator over all modules in the network, yielding both the name of the module as well as the module itself.
Args:
memo: a memo to store the set of modules already added to the result
prefix: a prefix that will be added to the name of the module
remove_duplicate: whether to remove the duplicated module instances in the result
or not
Yields:
(str, Module): Tuple of name and module
Note:
Duplicate modules are returned only once. In the following
example, l will be returned only once.
This is typically used to register a buffer that should not be
considered a model parameter. For example, BatchNorm’s running_mean
is not a parameter, but is part of the module’s state. Buffers, by
default, are persistent and will be saved alongside parameters. This
behavior can be changed by setting persistent to False. The
only difference between a persistent buffer and a non-persistent buffer
is that the latter will not be a part of this module’s
state_dict.
Buffers can be accessed as attributes using given names.
Args:
name (str): name of the buffer. The buffer can be accessed
from this module using the given name
tensor (Tensor or None): buffer to be registered. If None, then operations
that run on buffers, such as cuda, are ignored. If None,
the buffer is not included in the module’s state_dict.
persistent (bool): whether the buffer is part of this module’s
The hook will be called every time after forward() has computed an output.
If with_kwargs is False or not specified, the input contains only
the positional arguments given to the module. Keyword arguments won’t be
passed to the hooks and only to the forward. The hook can modify the
output. It can modify the input inplace but it will not have effect on
forward since this is called after forward() is called. The hook
should have the following signature:
hook(module,args,output)->Noneormodifiedoutput
If with_kwargs is True, the forward hook will be passed the
kwargs given to the forward function and be expected to return the
output possibly modified. The hook should have the following signature:
hook (Callable): The user defined hook to be registered.
prepend (bool): If True, the provided hook will be fired
before all existing forward hooks on this
torch.nn.Module. Otherwise, the provided
hook will be fired after all existing forward hooks on
this torch.nn.Module. Note that global
forward hooks registered with
register_module_forward_hook() will fire before all hooks
registered by this method.
Default: False
with_kwargs (bool): If True, the hook will be passed the
kwargs given to the forward function.
Default: False
always_call (bool): If True the hook will be run regardless of
whether an exception is raised while calling the Module.
Default: False
Returns:
torch.utils.hooks.RemovableHandle:
a handle that can be used to remove the added hook by calling
handle.remove()
The hook will be called every time before forward() is invoked.
If with_kwargs is false or not specified, the input contains only
the positional arguments given to the module. Keyword arguments won’t be
passed to the hooks and only to the forward. The hook can modify the
input. User can either return a tuple or a single modified value in the
hook. We will wrap the value into a tuple if a single value is returned
(unless that value is already a tuple). The hook should have the
following signature:
hook(module,args)->Noneormodifiedinput
If with_kwargs is true, the forward pre-hook will be passed the
kwargs given to the forward function. And if the hook modifies the
input, both the args and kwargs should be returned. The hook should have
the following signature:
hook (Callable): The user defined hook to be registered.
prepend (bool): If true, the provided hook will be fired before
all existing forward_pre hooks on this
torch.nn.Module. Otherwise, the provided
hook will be fired after all existing forward_pre hooks
on this torch.nn.Module. Note that global
forward_pre hooks registered with
register_module_forward_pre_hook() will fire before all
hooks registered by this method.
Default: False
with_kwargs (bool): If true, the hook will be passed the kwargs
given to the forward function.
Default: False
Returns:
torch.utils.hooks.RemovableHandle:
a handle that can be used to remove the added hook by calling
handle.remove()
The grad_input and grad_output are tuples that contain the gradients
with respect to the inputs and outputs respectively. The hook should
not modify its arguments, but it can optionally return a new gradient with
respect to the input that will be used in place of grad_input in
subsequent computations. grad_input will only correspond to the inputs given
as positional arguments and all kwarg arguments are ignored. Entries
in grad_input and grad_output will be None for all non-Tensor
arguments.
For technical reasons, when this hook is applied to a Module, its forward function will
receive a view of each Tensor passed to the Module. Similarly the caller will receive a view
of each Tensor returned by the Module’s forward function.
Warning
Modifying inputs or outputs inplace is not allowed when using backward hooks and
will raise an error.
Args:
hook (Callable): The user-defined hook to be registered.
prepend (bool): If true, the provided hook will be fired before
all existing backward hooks on this
torch.nn.Module. Otherwise, the provided
hook will be fired after all existing backward hooks on
this torch.nn.Module. Note that global
backward hooks registered with
register_module_full_backward_hook() will fire before
all hooks registered by this method.
Returns:
torch.utils.hooks.RemovableHandle:
a handle that can be used to remove the added hook by calling
handle.remove()
The grad_output is a tuple. The hook should
not modify its arguments, but it can optionally return a new gradient with
respect to the output that will be used in place of grad_output in
subsequent computations. Entries in grad_output will be None for
all non-Tensor arguments.
For technical reasons, when this hook is applied to a Module, its forward function will
receive a view of each Tensor passed to the Module. Similarly the caller will receive a view
of each Tensor returned by the Module’s forward function.
Warning
Modifying inputs inplace is not allowed when using backward hooks and
will raise an error.
Args:
hook (Callable): The user-defined hook to be registered.
prepend (bool): If true, the provided hook will be fired before
all existing backward_pre hooks on this
torch.nn.Module. Otherwise, the provided
hook will be fired after all existing backward_pre hooks
on this torch.nn.Module. Note that global
backward_pre hooks registered with
register_module_full_backward_pre_hook() will fire before
all hooks registered by this method.
Returns:
torch.utils.hooks.RemovableHandle:
a handle that can be used to remove the added hook by calling
handle.remove()
Register a post-hook to be run after module’s load_state_dict() is called.
It should have the following signature::
hook(module, incompatible_keys) -> None
The module argument is the current module that this hook is registered
on, and the incompatible_keys argument is a NamedTuple consisting
of attributes missing_keys and unexpected_keys. missing_keys
is a list of str containing the missing keys and
unexpected_keys is a list of str containing the unexpected keys.
The given incompatible_keys can be modified inplace if needed.
Note that the checks performed when calling load_state_dict() with
strict=True are affected by modifications the hook makes to
missing_keys or unexpected_keys, as expected. Additions to either
set of keys will result in an error being thrown when strict=True, and
clearing out both missing and unexpected keys will avoid an error.
Returns:
torch.utils.hooks.RemovableHandle:
a handle that can be used to remove the added hook by calling
handle.remove()
Set extra state contained in the loaded state_dict.
This function is called from load_state_dict() to handle any extra state
found within the state_dict. Implement this function and a corresponding
get_extra_state() for your module if you need to store extra state within its
state_dict.
Set the submodule given by target if it exists, otherwise throw an error.
Note
If strict is set to False (default), the method will replace an existing submodule
or create a new submodule if the parent module exists. If strict is set to True,
the method will only attempt to replace an existing submodule and throw an error if
the submodule does not exist.
For example, let’s say you have an nn.ModuleA that
looks like this:
(The diagram shows an nn.ModuleA. A has a nested
submodule net_b, which itself has two submodules net_c
and linear. net_c then has a submodule conv.)
To override the Conv2d with a new submodule Linear, you
could call set_submodule("net_b.net_c.conv",nn.Linear(1,1))
where strict could be True or False
To add a new submodule Conv2d to the existing net_b module,
you would call set_submodule("net_b.conv",nn.Conv2d(1,1,1)).
In the above if you set strict=True and call
set_submodule("net_b.conv",nn.Conv2d(1,1,1),strict=True), an AttributeError
will be raised because net_b does not have a submodule named conv.
Args:
target: The fully-qualified string name of the submodule
to look for. (See above example for how to specify a
fully-qualified string.)
module: The module to set the submodule to.
strict: If False, the method will replace an existing submodule
or create a new submodule if the parent module exists. If True,
the method will only attempt to replace an existing submodule and throw an error
if the submodule doesn’t already exist.
Raises:
ValueError: If the target string is empty or if module is not an instance of nn.Module.
AttributeError: If at any point along the path resulting from
the target string the (sub)path resolves to a non-existent
attribute name or an object that is not an instance of nn.Module.
Return a dictionary containing references to the whole state of the module.
Both parameters and persistent buffers (e.g. running averages) are
included. Keys are corresponding parameter and buffer names.
Parameters and buffers set to None are not included.
Note
The returned object is a shallow copy. It contains references
to the module’s parameters and buffers.
Warning
Currently state_dict() also accepts positional arguments for
destination, prefix and keep_vars in order. However,
this is being deprecated and keyword arguments will be enforced in
future releases.
Warning
Please avoid the use of argument destination as it is not
designed for end-users.
Args:
destination (dict, optional): If provided, the state of module will
be updated into the dict and the same object is returned.
Otherwise, an OrderedDict will be created and returned.
Default: None.
prefix (str, optional): a prefix added to parameter and buffer
names to compose the keys in state_dict. Default: ''.
keep_vars (bool, optional): by default the Tensor s
returned in the state dict are detached from autograd. If it’s
set to True, detaching will not be performed.
Default: False.
Returns:
dict:
a dictionary containing a whole state of the module
Its signature is similar to torch.Tensor.to(), but only accepts
floating point or complex dtypes. In addition, this method will
only cast the floating point or complex parameters and buffers to dtype
(if given). The integral parameters and buffers will be moved
device, if that is given, but with dtypes unchanged. When
non_blocking is set, it tries to convert/move asynchronously
with respect to the host if possible, e.g., moving CPU Tensors with
pinned memory to CUDA devices.
See below for examples.
Note
This method modifies the module in-place.
Args:
device (torch.device): the desired device of the parameters
and buffers in this module
dtype (torch.dtype): the desired floating point or complex dtype of
the parameters and buffers in this module
tensor (torch.Tensor): Tensor whose dtype and device are the desired
dtype and device for all parameters and buffers in this module
This has an effect only on certain modules. See the documentation of
particular modules for details of their behaviors in training/evaluation
mode, i.e., whether they are affected, e.g. Dropout, BatchNorm,
etc.
Args:
mode (bool): whether to set training mode (True) or evaluation
This also makes associated parameters and buffers different objects. So
it should be called before constructing optimizer if the module will
live on XPU while being optimized.
Note
This method modifies the module in-place.
Arguments:
device (int, optional): if specified, all parameters will be
Full power-law compression for auditory processing.
Applies a power-law compression/expansion to the entire signal without a
linear region. Unlike BrokenStickCompression, this affects all signal levels
and can cause expansion below the knee when exponent < 1.
PowerCompression: Affects all signal levels, no linear region
BrokenStickCompression: Linear below knee, compressed above knee
WARNING: With typical exponent values (n < 1), this compression can
amplify low-level signals (expansion below knee), which may not be
physiologically accurate for auditory modeling.
Usage in King et al. (2019):
This compression type is specific to the PEMO model. The Dau et al. (1997)
model does not use compression at this stage.
This also makes associated parameters and buffers different objects. So
it should be called before constructing the optimizer if the module will
live on GPU while being optimized.
Note
This method modifies the module in-place.
Args:
device (int, optional): if specified, all parameters will be
This has an effect only on certain modules. See the documentation of
particular modules for details of their behaviors in training/evaluation
mode, i.e. whether they are affected, e.g. Dropout, BatchNorm,
etc.
Return any extra state to include in the module’s state_dict.
Implement this and a corresponding set_extra_state() for your module
if you need to store extra state. This function is called when building the
module’s state_dict().
Note that extra state should be picklable to ensure working serialization
of the state_dict. We only provide backwards compatibility guarantees
for serializing Tensors; other objects may break backwards compatibility if
their serialized pickled form changes.
(The diagram shows an nn.ModuleA. A which has a nested
submodule net_b, which itself has two submodules net_c
and linear. net_c then has a submodule conv.)
To check whether or not we have the linear submodule, we
would call get_submodule("net_b.linear"). To check whether
we have the conv submodule, we would call
get_submodule("net_b.net_c.conv").
The runtime of get_submodule is bounded by the degree
of module nesting in target. A query against
named_modules achieves the same result, but it is O(N) in
the number of transitive modules. So, for a simple check to see
if some submodule exists, get_submodule should always be
used.
Args:
target: The fully-qualified string name of the submodule
to look for. (See above example for how to specify a
fully-qualified string.)
Returns:
torch.nn.Module: The submodule referenced by target
Raises:
AttributeError: If at any point along the path resulting from
the target string the (sub)path resolves to a non-existent
attribute name or an object that is not an instance of nn.Module.
This also makes associated parameters and buffers different objects. So
it should be called before constructing the optimizer if the module will
live on IPU while being optimized.
Note
This method modifies the module in-place.
Arguments:
device (int, optional): if specified, all parameters will be
state_dict (dict): a dict containing parameters and
persistent buffers.
strict (bool, optional): whether to strictly enforce that the keys
in state_dict match the keys returned by this module’s
state_dict() function. Default: True
assign (bool, optional): When set to False, the properties of the tensors
in the current module are preserved whereas setting it to True preserves
properties of the Tensors in the state dict. The only
exception is the requires_grad field of Parameter
for which the value from the module is preserved. Default: False
Returns:
NamedTuple with missing_keys and unexpected_keys fields:
missing_keys is a list of str containing any keys that are expected
by this module but missing from the provided state_dict.
unexpected_keys is a list of str containing the keys that are not
expected by this module but present in the provided state_dict.
Note:
If a parameter or buffer is registered as None and its corresponding key
exists in state_dict, load_state_dict() will raise a
RuntimeError.
Move all model parameters and buffers to the MTIA.
This also makes associated parameters and buffers different objects. So
it should be called before constructing the optimizer if the module will
live on MTIA while being optimized.
Note
This method modifies the module in-place.
Arguments:
device (int, optional): if specified, all parameters will be
Return an iterator over all modules in the network, yielding both the name of the module as well as the module itself.
Args:
memo: a memo to store the set of modules already added to the result
prefix: a prefix that will be added to the name of the module
remove_duplicate: whether to remove the duplicated module instances in the result
or not
Yields:
(str, Module): Tuple of name and module
Note:
Duplicate modules are returned only once. In the following
example, l will be returned only once.
This is typically used to register a buffer that should not be
considered a model parameter. For example, BatchNorm’s running_mean
is not a parameter, but is part of the module’s state. Buffers, by
default, are persistent and will be saved alongside parameters. This
behavior can be changed by setting persistent to False. The
only difference between a persistent buffer and a non-persistent buffer
is that the latter will not be a part of this module’s
state_dict.
Buffers can be accessed as attributes using given names.
Args:
name (str): name of the buffer. The buffer can be accessed
from this module using the given name
tensor (Tensor or None): buffer to be registered. If None, then operations
that run on buffers, such as cuda, are ignored. If None,
the buffer is not included in the module’s state_dict.
persistent (bool): whether the buffer is part of this module’s
The hook will be called every time after forward() has computed an output.
If with_kwargs is False or not specified, the input contains only
the positional arguments given to the module. Keyword arguments won’t be
passed to the hooks and only to the forward. The hook can modify the
output. It can modify the input inplace but it will not have effect on
forward since this is called after forward() is called. The hook
should have the following signature:
hook(module,args,output)->Noneormodifiedoutput
If with_kwargs is True, the forward hook will be passed the
kwargs given to the forward function and be expected to return the
output possibly modified. The hook should have the following signature:
hook (Callable): The user defined hook to be registered.
prepend (bool): If True, the provided hook will be fired
before all existing forward hooks on this
torch.nn.Module. Otherwise, the provided
hook will be fired after all existing forward hooks on
this torch.nn.Module. Note that global
forward hooks registered with
register_module_forward_hook() will fire before all hooks
registered by this method.
Default: False
with_kwargs (bool): If True, the hook will be passed the
kwargs given to the forward function.
Default: False
always_call (bool): If True the hook will be run regardless of
whether an exception is raised while calling the Module.
Default: False
Returns:
torch.utils.hooks.RemovableHandle:
a handle that can be used to remove the added hook by calling
handle.remove()
The hook will be called every time before forward() is invoked.
If with_kwargs is false or not specified, the input contains only
the positional arguments given to the module. Keyword arguments won’t be
passed to the hooks and only to the forward. The hook can modify the
input. User can either return a tuple or a single modified value in the
hook. We will wrap the value into a tuple if a single value is returned
(unless that value is already a tuple). The hook should have the
following signature:
hook(module,args)->Noneormodifiedinput
If with_kwargs is true, the forward pre-hook will be passed the
kwargs given to the forward function. And if the hook modifies the
input, both the args and kwargs should be returned. The hook should have
the following signature:
hook (Callable): The user defined hook to be registered.
prepend (bool): If true, the provided hook will be fired before
all existing forward_pre hooks on this
torch.nn.Module. Otherwise, the provided
hook will be fired after all existing forward_pre hooks
on this torch.nn.Module. Note that global
forward_pre hooks registered with
register_module_forward_pre_hook() will fire before all
hooks registered by this method.
Default: False
with_kwargs (bool): If true, the hook will be passed the kwargs
given to the forward function.
Default: False
Returns:
torch.utils.hooks.RemovableHandle:
a handle that can be used to remove the added hook by calling
handle.remove()
The grad_input and grad_output are tuples that contain the gradients
with respect to the inputs and outputs respectively. The hook should
not modify its arguments, but it can optionally return a new gradient with
respect to the input that will be used in place of grad_input in
subsequent computations. grad_input will only correspond to the inputs given
as positional arguments and all kwarg arguments are ignored. Entries
in grad_input and grad_output will be None for all non-Tensor
arguments.
For technical reasons, when this hook is applied to a Module, its forward function will
receive a view of each Tensor passed to the Module. Similarly the caller will receive a view
of each Tensor returned by the Module’s forward function.
Warning
Modifying inputs or outputs inplace is not allowed when using backward hooks and
will raise an error.
Args:
hook (Callable): The user-defined hook to be registered.
prepend (bool): If true, the provided hook will be fired before
all existing backward hooks on this
torch.nn.Module. Otherwise, the provided
hook will be fired after all existing backward hooks on
this torch.nn.Module. Note that global
backward hooks registered with
register_module_full_backward_hook() will fire before
all hooks registered by this method.
Returns:
torch.utils.hooks.RemovableHandle:
a handle that can be used to remove the added hook by calling
handle.remove()
The grad_output is a tuple. The hook should
not modify its arguments, but it can optionally return a new gradient with
respect to the output that will be used in place of grad_output in
subsequent computations. Entries in grad_output will be None for
all non-Tensor arguments.
For technical reasons, when this hook is applied to a Module, its forward function will
receive a view of each Tensor passed to the Module. Similarly the caller will receive a view
of each Tensor returned by the Module’s forward function.
Warning
Modifying inputs inplace is not allowed when using backward hooks and
will raise an error.
Args:
hook (Callable): The user-defined hook to be registered.
prepend (bool): If true, the provided hook will be fired before
all existing backward_pre hooks on this
torch.nn.Module. Otherwise, the provided
hook will be fired after all existing backward_pre hooks
on this torch.nn.Module. Note that global
backward_pre hooks registered with
register_module_full_backward_pre_hook() will fire before
all hooks registered by this method.
Returns:
torch.utils.hooks.RemovableHandle:
a handle that can be used to remove the added hook by calling
handle.remove()
Register a post-hook to be run after module’s load_state_dict() is called.
It should have the following signature::
hook(module, incompatible_keys) -> None
The module argument is the current module that this hook is registered
on, and the incompatible_keys argument is a NamedTuple consisting
of attributes missing_keys and unexpected_keys. missing_keys
is a list of str containing the missing keys and
unexpected_keys is a list of str containing the unexpected keys.
The given incompatible_keys can be modified inplace if needed.
Note that the checks performed when calling load_state_dict() with
strict=True are affected by modifications the hook makes to
missing_keys or unexpected_keys, as expected. Additions to either
set of keys will result in an error being thrown when strict=True, and
clearing out both missing and unexpected keys will avoid an error.
Returns:
torch.utils.hooks.RemovableHandle:
a handle that can be used to remove the added hook by calling
handle.remove()
Set extra state contained in the loaded state_dict.
This function is called from load_state_dict() to handle any extra state
found within the state_dict. Implement this function and a corresponding
get_extra_state() for your module if you need to store extra state within its
state_dict.
Set the submodule given by target if it exists, otherwise throw an error.
Note
If strict is set to False (default), the method will replace an existing submodule
or create a new submodule if the parent module exists. If strict is set to True,
the method will only attempt to replace an existing submodule and throw an error if
the submodule does not exist.
For example, let’s say you have an nn.ModuleA that
looks like this:
(The diagram shows an nn.ModuleA. A has a nested
submodule net_b, which itself has two submodules net_c
and linear. net_c then has a submodule conv.)
To override the Conv2d with a new submodule Linear, you
could call set_submodule("net_b.net_c.conv",nn.Linear(1,1))
where strict could be True or False
To add a new submodule Conv2d to the existing net_b module,
you would call set_submodule("net_b.conv",nn.Conv2d(1,1,1)).
In the above if you set strict=True and call
set_submodule("net_b.conv",nn.Conv2d(1,1,1),strict=True), an AttributeError
will be raised because net_b does not have a submodule named conv.
Args:
target: The fully-qualified string name of the submodule
to look for. (See above example for how to specify a
fully-qualified string.)
module: The module to set the submodule to.
strict: If False, the method will replace an existing submodule
or create a new submodule if the parent module exists. If True,
the method will only attempt to replace an existing submodule and throw an error
if the submodule doesn’t already exist.
Raises:
ValueError: If the target string is empty or if module is not an instance of nn.Module.
AttributeError: If at any point along the path resulting from
the target string the (sub)path resolves to a non-existent
attribute name or an object that is not an instance of nn.Module.
Return a dictionary containing references to the whole state of the module.
Both parameters and persistent buffers (e.g. running averages) are
included. Keys are corresponding parameter and buffer names.
Parameters and buffers set to None are not included.
Note
The returned object is a shallow copy. It contains references
to the module’s parameters and buffers.
Warning
Currently state_dict() also accepts positional arguments for
destination, prefix and keep_vars in order. However,
this is being deprecated and keyword arguments will be enforced in
future releases.
Warning
Please avoid the use of argument destination as it is not
designed for end-users.
Args:
destination (dict, optional): If provided, the state of module will
be updated into the dict and the same object is returned.
Otherwise, an OrderedDict will be created and returned.
Default: None.
prefix (str, optional): a prefix added to parameter and buffer
names to compose the keys in state_dict. Default: ''.
keep_vars (bool, optional): by default the Tensor s
returned in the state dict are detached from autograd. If it’s
set to True, detaching will not be performed.
Default: False.
Returns:
dict:
a dictionary containing a whole state of the module
Its signature is similar to torch.Tensor.to(), but only accepts
floating point or complex dtypes. In addition, this method will
only cast the floating point or complex parameters and buffers to dtype
(if given). The integral parameters and buffers will be moved
device, if that is given, but with dtypes unchanged. When
non_blocking is set, it tries to convert/move asynchronously
with respect to the host if possible, e.g., moving CPU Tensors with
pinned memory to CUDA devices.
See below for examples.
Note
This method modifies the module in-place.
Args:
device (torch.device): the desired device of the parameters
and buffers in this module
dtype (torch.dtype): the desired floating point or complex dtype of
the parameters and buffers in this module
tensor (torch.Tensor): Tensor whose dtype and device are the desired
dtype and device for all parameters and buffers in this module
This has an effect only on certain modules. See the documentation of
particular modules for details of their behaviors in training/evaluation
mode, i.e., whether they are affected, e.g. Dropout, BatchNorm,
etc.
Args:
mode (bool): whether to set training mode (True) or evaluation
This also makes associated parameters and buffers different objects. So
it should be called before constructing optimizer if the module will
live on XPU while being optimized.
Note
This method modifies the module in-place.
Arguments:
device (int, optional): if specified, all parameters will be
Specific loudness transformation for Glasberg & Moore (2002) loudness model.
Transforms excitation pattern from ERB filterbank to specific loudness using
a three-regime model that accounts for absolute threshold, linear region, and
compressive region. Based on Moore & Glasberg (1997) model with ISO 226
threshold curves.
The three-regime model captures the transition from complete masking (sub-threshold),
through a linear loudness growth region, to the compressive loudness region
The absolute threshold \(E_{Thrq}\) is frequency-dependent and follows ISO 226,
with minimum threshold (~4 dB SPL) around 2-5 kHz
The linear region (Regime 2) extends from threshold to ~10 dB above threshold
The compressive region (Regime 3) with \(\\alpha=0.2\) implements the well-known
power-law loudness growth (approximately doubling loudness per 10 dB)
When learnable=True, the model can adapt the threshold, gain, and compression
characteristics through backpropagation
This implementation is compatible with glasberg2002 model from AMT MATLAB
>>> importtorch>>> fromtorch_amt.common.loudnessimportSpecificLoudness>>>>>> # Create module>>> spec_loud=SpecificLoudness(fs=32000,f_min=50,f_max=15000,erb_step=0.25)>>> print(f"Number of ERB bands: {spec_loud.n_erb_bands}")Number of ERB bands: 150>>>>>> # Simulate excitation pattern (e.g., from ERB filterbank)>>> batch,n_frames,n_erb=2,100,150>>> excitation_db=torch.randn(batch,n_frames,n_erb)*20+60# ~60 dB SPL mean>>>>>> # Transform to specific loudness>>> N=spec_loud(excitation_db)>>> print(f"Specific loudness shape: {N.shape}, range: [{N.min():.3f}, {N.max():.3f}] sone/ERB")Specific loudness shape: torch.Size([2, 100, 150]), range: [0.000, 15.234] sone/ERB
Check absolute threshold in quiet:
>>> threshold=spec_loud.get_threshold()>>> print(f"Threshold at 1 kHz: {threshold[spec_loud.fc_erb.argmin((spec_loud.fc_erb-1000).abs())]:.2f} dB SPL")Threshold at 1 kHz: 4.23 dB SPL>>> print(f"Min threshold: {threshold.min():.2f} dB SPL at {spec_loud.fc_erb[threshold.argmin()]:.0f} Hz")Min threshold: 3.85 dB SPL at 3500 Hz
Learnable parameters for model adaptation:
>>> spec_loud_learn=SpecificLoudness(fs=32000,learnable=True)>>> params=spec_loud_learn.get_parameters()>>> print(f"C={params['C']:.4f}, alpha={params['alpha']:.3f}, E0={params['E0_offset']:.1f} dB")C=0.0470, alpha=0.200, E0=10.0 dB>>>>>> # Can now train these parameters with backpropagation>>> optimizer=torch.optim.Adam(spec_loud_learn.parameters(),lr=1e-3)
This also makes associated parameters and buffers different objects. So
it should be called before constructing the optimizer if the module will
live on GPU while being optimized.
Note
This method modifies the module in-place.
Args:
device (int, optional): if specified, all parameters will be
This has an effect only on certain modules. See the documentation of
particular modules for details of their behaviors in training/evaluation
mode, i.e. whether they are affected, e.g. Dropout, BatchNorm,
etc.
Return any extra state to include in the module’s state_dict.
Implement this and a corresponding set_extra_state() for your module
if you need to store extra state. This function is called when building the
module’s state_dict().
Note that extra state should be picklable to ensure working serialization
of the state_dict. We only provide backwards compatibility guarantees
for serializing Tensors; other objects may break backwards compatibility if
their serialized pickled form changes.
(The diagram shows an nn.ModuleA. A which has a nested
submodule net_b, which itself has two submodules net_c
and linear. net_c then has a submodule conv.)
To check whether or not we have the linear submodule, we
would call get_submodule("net_b.linear"). To check whether
we have the conv submodule, we would call
get_submodule("net_b.net_c.conv").
The runtime of get_submodule is bounded by the degree
of module nesting in target. A query against
named_modules achieves the same result, but it is O(N) in
the number of transitive modules. So, for a simple check to see
if some submodule exists, get_submodule should always be
used.
Args:
target: The fully-qualified string name of the submodule
to look for. (See above example for how to specify a
fully-qualified string.)
Returns:
torch.nn.Module: The submodule referenced by target
Raises:
AttributeError: If at any point along the path resulting from
the target string the (sub)path resolves to a non-existent
attribute name or an object that is not an instance of nn.Module.
This also makes associated parameters and buffers different objects. So
it should be called before constructing the optimizer if the module will
live on IPU while being optimized.
Note
This method modifies the module in-place.
Arguments:
device (int, optional): if specified, all parameters will be
state_dict (dict): a dict containing parameters and
persistent buffers.
strict (bool, optional): whether to strictly enforce that the keys
in state_dict match the keys returned by this module’s
state_dict() function. Default: True
assign (bool, optional): When set to False, the properties of the tensors
in the current module are preserved whereas setting it to True preserves
properties of the Tensors in the state dict. The only
exception is the requires_grad field of Parameter
for which the value from the module is preserved. Default: False
Returns:
NamedTuple with missing_keys and unexpected_keys fields:
missing_keys is a list of str containing any keys that are expected
by this module but missing from the provided state_dict.
unexpected_keys is a list of str containing the keys that are not
expected by this module but present in the provided state_dict.
Note:
If a parameter or buffer is registered as None and its corresponding key
exists in state_dict, load_state_dict() will raise a
RuntimeError.
Move all model parameters and buffers to the MTIA.
This also makes associated parameters and buffers different objects. So
it should be called before constructing the optimizer if the module will
live on MTIA while being optimized.
Note
This method modifies the module in-place.
Arguments:
device (int, optional): if specified, all parameters will be
Return an iterator over all modules in the network, yielding both the name of the module as well as the module itself.
Args:
memo: a memo to store the set of modules already added to the result
prefix: a prefix that will be added to the name of the module
remove_duplicate: whether to remove the duplicated module instances in the result
or not
Yields:
(str, Module): Tuple of name and module
Note:
Duplicate modules are returned only once. In the following
example, l will be returned only once.
This is typically used to register a buffer that should not be
considered a model parameter. For example, BatchNorm’s running_mean
is not a parameter, but is part of the module’s state. Buffers, by
default, are persistent and will be saved alongside parameters. This
behavior can be changed by setting persistent to False. The
only difference between a persistent buffer and a non-persistent buffer
is that the latter will not be a part of this module’s
state_dict.
Buffers can be accessed as attributes using given names.
Args:
name (str): name of the buffer. The buffer can be accessed
from this module using the given name
tensor (Tensor or None): buffer to be registered. If None, then operations
that run on buffers, such as cuda, are ignored. If None,
the buffer is not included in the module’s state_dict.
persistent (bool): whether the buffer is part of this module’s
The hook will be called every time after forward() has computed an output.
If with_kwargs is False or not specified, the input contains only
the positional arguments given to the module. Keyword arguments won’t be
passed to the hooks and only to the forward. The hook can modify the
output. It can modify the input inplace but it will not have effect on
forward since this is called after forward() is called. The hook
should have the following signature:
hook(module,args,output)->Noneormodifiedoutput
If with_kwargs is True, the forward hook will be passed the
kwargs given to the forward function and be expected to return the
output possibly modified. The hook should have the following signature:
hook (Callable): The user defined hook to be registered.
prepend (bool): If True, the provided hook will be fired
before all existing forward hooks on this
torch.nn.Module. Otherwise, the provided
hook will be fired after all existing forward hooks on
this torch.nn.Module. Note that global
forward hooks registered with
register_module_forward_hook() will fire before all hooks
registered by this method.
Default: False
with_kwargs (bool): If True, the hook will be passed the
kwargs given to the forward function.
Default: False
always_call (bool): If True the hook will be run regardless of
whether an exception is raised while calling the Module.
Default: False
Returns:
torch.utils.hooks.RemovableHandle:
a handle that can be used to remove the added hook by calling
handle.remove()
The hook will be called every time before forward() is invoked.
If with_kwargs is false or not specified, the input contains only
the positional arguments given to the module. Keyword arguments won’t be
passed to the hooks and only to the forward. The hook can modify the
input. User can either return a tuple or a single modified value in the
hook. We will wrap the value into a tuple if a single value is returned
(unless that value is already a tuple). The hook should have the
following signature:
hook(module,args)->Noneormodifiedinput
If with_kwargs is true, the forward pre-hook will be passed the
kwargs given to the forward function. And if the hook modifies the
input, both the args and kwargs should be returned. The hook should have
the following signature:
hook (Callable): The user defined hook to be registered.
prepend (bool): If true, the provided hook will be fired before
all existing forward_pre hooks on this
torch.nn.Module. Otherwise, the provided
hook will be fired after all existing forward_pre hooks
on this torch.nn.Module. Note that global
forward_pre hooks registered with
register_module_forward_pre_hook() will fire before all
hooks registered by this method.
Default: False
with_kwargs (bool): If true, the hook will be passed the kwargs
given to the forward function.
Default: False
Returns:
torch.utils.hooks.RemovableHandle:
a handle that can be used to remove the added hook by calling
handle.remove()
The grad_input and grad_output are tuples that contain the gradients
with respect to the inputs and outputs respectively. The hook should
not modify its arguments, but it can optionally return a new gradient with
respect to the input that will be used in place of grad_input in
subsequent computations. grad_input will only correspond to the inputs given
as positional arguments and all kwarg arguments are ignored. Entries
in grad_input and grad_output will be None for all non-Tensor
arguments.
For technical reasons, when this hook is applied to a Module, its forward function will
receive a view of each Tensor passed to the Module. Similarly the caller will receive a view
of each Tensor returned by the Module’s forward function.
Warning
Modifying inputs or outputs inplace is not allowed when using backward hooks and
will raise an error.
Args:
hook (Callable): The user-defined hook to be registered.
prepend (bool): If true, the provided hook will be fired before
all existing backward hooks on this
torch.nn.Module. Otherwise, the provided
hook will be fired after all existing backward hooks on
this torch.nn.Module. Note that global
backward hooks registered with
register_module_full_backward_hook() will fire before
all hooks registered by this method.
Returns:
torch.utils.hooks.RemovableHandle:
a handle that can be used to remove the added hook by calling
handle.remove()
The grad_output is a tuple. The hook should
not modify its arguments, but it can optionally return a new gradient with
respect to the output that will be used in place of grad_output in
subsequent computations. Entries in grad_output will be None for
all non-Tensor arguments.
For technical reasons, when this hook is applied to a Module, its forward function will
receive a view of each Tensor passed to the Module. Similarly the caller will receive a view
of each Tensor returned by the Module’s forward function.
Warning
Modifying inputs inplace is not allowed when using backward hooks and
will raise an error.
Args:
hook (Callable): The user-defined hook to be registered.
prepend (bool): If true, the provided hook will be fired before
all existing backward_pre hooks on this
torch.nn.Module. Otherwise, the provided
hook will be fired after all existing backward_pre hooks
on this torch.nn.Module. Note that global
backward_pre hooks registered with
register_module_full_backward_pre_hook() will fire before
all hooks registered by this method.
Returns:
torch.utils.hooks.RemovableHandle:
a handle that can be used to remove the added hook by calling
handle.remove()
Register a post-hook to be run after module’s load_state_dict() is called.
It should have the following signature::
hook(module, incompatible_keys) -> None
The module argument is the current module that this hook is registered
on, and the incompatible_keys argument is a NamedTuple consisting
of attributes missing_keys and unexpected_keys. missing_keys
is a list of str containing the missing keys and
unexpected_keys is a list of str containing the unexpected keys.
The given incompatible_keys can be modified inplace if needed.
Note that the checks performed when calling load_state_dict() with
strict=True are affected by modifications the hook makes to
missing_keys or unexpected_keys, as expected. Additions to either
set of keys will result in an error being thrown when strict=True, and
clearing out both missing and unexpected keys will avoid an error.
Returns:
torch.utils.hooks.RemovableHandle:
a handle that can be used to remove the added hook by calling
handle.remove()
Set extra state contained in the loaded state_dict.
This function is called from load_state_dict() to handle any extra state
found within the state_dict. Implement this function and a corresponding
get_extra_state() for your module if you need to store extra state within its
state_dict.
Set the submodule given by target if it exists, otherwise throw an error.
Note
If strict is set to False (default), the method will replace an existing submodule
or create a new submodule if the parent module exists. If strict is set to True,
the method will only attempt to replace an existing submodule and throw an error if
the submodule does not exist.
For example, let’s say you have an nn.ModuleA that
looks like this:
(The diagram shows an nn.ModuleA. A has a nested
submodule net_b, which itself has two submodules net_c
and linear. net_c then has a submodule conv.)
To override the Conv2d with a new submodule Linear, you
could call set_submodule("net_b.net_c.conv",nn.Linear(1,1))
where strict could be True or False
To add a new submodule Conv2d to the existing net_b module,
you would call set_submodule("net_b.conv",nn.Conv2d(1,1,1)).
In the above if you set strict=True and call
set_submodule("net_b.conv",nn.Conv2d(1,1,1),strict=True), an AttributeError
will be raised because net_b does not have a submodule named conv.
Args:
target: The fully-qualified string name of the submodule
to look for. (See above example for how to specify a
fully-qualified string.)
module: The module to set the submodule to.
strict: If False, the method will replace an existing submodule
or create a new submodule if the parent module exists. If True,
the method will only attempt to replace an existing submodule and throw an error
if the submodule doesn’t already exist.
Raises:
ValueError: If the target string is empty or if module is not an instance of nn.Module.
AttributeError: If at any point along the path resulting from
the target string the (sub)path resolves to a non-existent
attribute name or an object that is not an instance of nn.Module.
Return a dictionary containing references to the whole state of the module.
Both parameters and persistent buffers (e.g. running averages) are
included. Keys are corresponding parameter and buffer names.
Parameters and buffers set to None are not included.
Note
The returned object is a shallow copy. It contains references
to the module’s parameters and buffers.
Warning
Currently state_dict() also accepts positional arguments for
destination, prefix and keep_vars in order. However,
this is being deprecated and keyword arguments will be enforced in
future releases.
Warning
Please avoid the use of argument destination as it is not
designed for end-users.
Args:
destination (dict, optional): If provided, the state of module will
be updated into the dict and the same object is returned.
Otherwise, an OrderedDict will be created and returned.
Default: None.
prefix (str, optional): a prefix added to parameter and buffer
names to compose the keys in state_dict. Default: ''.
keep_vars (bool, optional): by default the Tensor s
returned in the state dict are detached from autograd. If it’s
set to True, detaching will not be performed.
Default: False.
Returns:
dict:
a dictionary containing a whole state of the module
Its signature is similar to torch.Tensor.to(), but only accepts
floating point or complex dtypes. In addition, this method will
only cast the floating point or complex parameters and buffers to dtype
(if given). The integral parameters and buffers will be moved
device, if that is given, but with dtypes unchanged. When
non_blocking is set, it tries to convert/move asynchronously
with respect to the host if possible, e.g., moving CPU Tensors with
pinned memory to CUDA devices.
See below for examples.
Note
This method modifies the module in-place.
Args:
device (torch.device): the desired device of the parameters
and buffers in this module
dtype (torch.dtype): the desired floating point or complex dtype of
the parameters and buffers in this module
tensor (torch.Tensor): Tensor whose dtype and device are the desired
dtype and device for all parameters and buffers in this module
This has an effect only on certain modules. See the documentation of
particular modules for details of their behaviors in training/evaluation
mode, i.e., whether they are affected, e.g. Dropout, BatchNorm,
etc.
Args:
mode (bool): whether to set training mode (True) or evaluation
This also makes associated parameters and buffers different objects. So
it should be called before constructing optimizer if the module will
live on XPU while being optimized.
Note
This method modifies the module in-place.
Arguments:
device (int, optional): if specified, all parameters will be
Specific loudness transformation for Moore et al. (2016) binaural loudness model.
Implements the ANSI S3.4-2007 specific loudness transformation with three loudness
regimes (sub-threshold, standard, high-level) and frequency-dependent parameters
derived from lookup tables. Uses binaural constant C = 0.0631 (Moore & Glasberg 2007).
This module operates on single time frames with 150 ERB channels
Input shape is (batch, 150), different from Glasberg2002 SpecificLoudness
which processes time series (batch, n_frames, n_erb)
The 150 channels correspond to ERB scale 1.75 to 39 in 0.25 ERB steps
Lookup tables G, Alpha, A are derived from ANSI S3.4-2007 standard
The three-regime model provides smooth transitions:
* Sub-threshold: Gradual onset with threshold-dependent weighting
* Standard: Main loudness growth with frequency-dependent compression
* High-level: Simplified power-law to prevent overflow
Binaural constant C = 0.0631 accounts for binaural summation
(approximately √2 loudness increase for identical binaural signals)
>>> spec_loud_learn=Moore2016SpecificLoudness(learnable=True)>>> # Can train C, G, Alpha, A with backpropagation>>> optimizer=torch.optim.Adam(spec_loud_learn.parameters(),lr=1e-4)
This also makes associated parameters and buffers different objects. So
it should be called before constructing the optimizer if the module will
live on GPU while being optimized.
Note
This method modifies the module in-place.
Args:
device (int, optional): if specified, all parameters will be
This has an effect only on certain modules. See the documentation of
particular modules for details of their behaviors in training/evaluation
mode, i.e. whether they are affected, e.g. Dropout, BatchNorm,
etc.
Return any extra state to include in the module’s state_dict.
Implement this and a corresponding set_extra_state() for your module
if you need to store extra state. This function is called when building the
module’s state_dict().
Note that extra state should be picklable to ensure working serialization
of the state_dict. We only provide backwards compatibility guarantees
for serializing Tensors; other objects may break backwards compatibility if
their serialized pickled form changes.
(The diagram shows an nn.ModuleA. A which has a nested
submodule net_b, which itself has two submodules net_c
and linear. net_c then has a submodule conv.)
To check whether or not we have the linear submodule, we
would call get_submodule("net_b.linear"). To check whether
we have the conv submodule, we would call
get_submodule("net_b.net_c.conv").
The runtime of get_submodule is bounded by the degree
of module nesting in target. A query against
named_modules achieves the same result, but it is O(N) in
the number of transitive modules. So, for a simple check to see
if some submodule exists, get_submodule should always be
used.
Args:
target: The fully-qualified string name of the submodule
to look for. (See above example for how to specify a
fully-qualified string.)
Returns:
torch.nn.Module: The submodule referenced by target
Raises:
AttributeError: If at any point along the path resulting from
the target string the (sub)path resolves to a non-existent
attribute name or an object that is not an instance of nn.Module.
This also makes associated parameters and buffers different objects. So
it should be called before constructing the optimizer if the module will
live on IPU while being optimized.
Note
This method modifies the module in-place.
Arguments:
device (int, optional): if specified, all parameters will be
state_dict (dict): a dict containing parameters and
persistent buffers.
strict (bool, optional): whether to strictly enforce that the keys
in state_dict match the keys returned by this module’s
state_dict() function. Default: True
assign (bool, optional): When set to False, the properties of the tensors
in the current module are preserved whereas setting it to True preserves
properties of the Tensors in the state dict. The only
exception is the requires_grad field of Parameter
for which the value from the module is preserved. Default: False
Returns:
NamedTuple with missing_keys and unexpected_keys fields:
missing_keys is a list of str containing any keys that are expected
by this module but missing from the provided state_dict.
unexpected_keys is a list of str containing the keys that are not
expected by this module but present in the provided state_dict.
Note:
If a parameter or buffer is registered as None and its corresponding key
exists in state_dict, load_state_dict() will raise a
RuntimeError.
Move all model parameters and buffers to the MTIA.
This also makes associated parameters and buffers different objects. So
it should be called before constructing the optimizer if the module will
live on MTIA while being optimized.
Note
This method modifies the module in-place.
Arguments:
device (int, optional): if specified, all parameters will be
Return an iterator over all modules in the network, yielding both the name of the module as well as the module itself.
Args:
memo: a memo to store the set of modules already added to the result
prefix: a prefix that will be added to the name of the module
remove_duplicate: whether to remove the duplicated module instances in the result
or not
Yields:
(str, Module): Tuple of name and module
Note:
Duplicate modules are returned only once. In the following
example, l will be returned only once.
This is typically used to register a buffer that should not be
considered a model parameter. For example, BatchNorm’s running_mean
is not a parameter, but is part of the module’s state. Buffers, by
default, are persistent and will be saved alongside parameters. This
behavior can be changed by setting persistent to False. The
only difference between a persistent buffer and a non-persistent buffer
is that the latter will not be a part of this module’s
state_dict.
Buffers can be accessed as attributes using given names.
Args:
name (str): name of the buffer. The buffer can be accessed
from this module using the given name
tensor (Tensor or None): buffer to be registered. If None, then operations
that run on buffers, such as cuda, are ignored. If None,
the buffer is not included in the module’s state_dict.
persistent (bool): whether the buffer is part of this module’s
The hook will be called every time after forward() has computed an output.
If with_kwargs is False or not specified, the input contains only
the positional arguments given to the module. Keyword arguments won’t be
passed to the hooks and only to the forward. The hook can modify the
output. It can modify the input inplace but it will not have effect on
forward since this is called after forward() is called. The hook
should have the following signature:
hook(module,args,output)->Noneormodifiedoutput
If with_kwargs is True, the forward hook will be passed the
kwargs given to the forward function and be expected to return the
output possibly modified. The hook should have the following signature:
hook (Callable): The user defined hook to be registered.
prepend (bool): If True, the provided hook will be fired
before all existing forward hooks on this
torch.nn.Module. Otherwise, the provided
hook will be fired after all existing forward hooks on
this torch.nn.Module. Note that global
forward hooks registered with
register_module_forward_hook() will fire before all hooks
registered by this method.
Default: False
with_kwargs (bool): If True, the hook will be passed the
kwargs given to the forward function.
Default: False
always_call (bool): If True the hook will be run regardless of
whether an exception is raised while calling the Module.
Default: False
Returns:
torch.utils.hooks.RemovableHandle:
a handle that can be used to remove the added hook by calling
handle.remove()
The hook will be called every time before forward() is invoked.
If with_kwargs is false or not specified, the input contains only
the positional arguments given to the module. Keyword arguments won’t be
passed to the hooks and only to the forward. The hook can modify the
input. User can either return a tuple or a single modified value in the
hook. We will wrap the value into a tuple if a single value is returned
(unless that value is already a tuple). The hook should have the
following signature:
hook(module,args)->Noneormodifiedinput
If with_kwargs is true, the forward pre-hook will be passed the
kwargs given to the forward function. And if the hook modifies the
input, both the args and kwargs should be returned. The hook should have
the following signature:
hook (Callable): The user defined hook to be registered.
prepend (bool): If true, the provided hook will be fired before
all existing forward_pre hooks on this
torch.nn.Module. Otherwise, the provided
hook will be fired after all existing forward_pre hooks
on this torch.nn.Module. Note that global
forward_pre hooks registered with
register_module_forward_pre_hook() will fire before all
hooks registered by this method.
Default: False
with_kwargs (bool): If true, the hook will be passed the kwargs
given to the forward function.
Default: False
Returns:
torch.utils.hooks.RemovableHandle:
a handle that can be used to remove the added hook by calling
handle.remove()
The grad_input and grad_output are tuples that contain the gradients
with respect to the inputs and outputs respectively. The hook should
not modify its arguments, but it can optionally return a new gradient with
respect to the input that will be used in place of grad_input in
subsequent computations. grad_input will only correspond to the inputs given
as positional arguments and all kwarg arguments are ignored. Entries
in grad_input and grad_output will be None for all non-Tensor
arguments.
For technical reasons, when this hook is applied to a Module, its forward function will
receive a view of each Tensor passed to the Module. Similarly the caller will receive a view
of each Tensor returned by the Module’s forward function.
Warning
Modifying inputs or outputs inplace is not allowed when using backward hooks and
will raise an error.
Args:
hook (Callable): The user-defined hook to be registered.
prepend (bool): If true, the provided hook will be fired before
all existing backward hooks on this
torch.nn.Module. Otherwise, the provided
hook will be fired after all existing backward hooks on
this torch.nn.Module. Note that global
backward hooks registered with
register_module_full_backward_hook() will fire before
all hooks registered by this method.
Returns:
torch.utils.hooks.RemovableHandle:
a handle that can be used to remove the added hook by calling
handle.remove()
The grad_output is a tuple. The hook should
not modify its arguments, but it can optionally return a new gradient with
respect to the output that will be used in place of grad_output in
subsequent computations. Entries in grad_output will be None for
all non-Tensor arguments.
For technical reasons, when this hook is applied to a Module, its forward function will
receive a view of each Tensor passed to the Module. Similarly the caller will receive a view
of each Tensor returned by the Module’s forward function.
Warning
Modifying inputs inplace is not allowed when using backward hooks and
will raise an error.
Args:
hook (Callable): The user-defined hook to be registered.
prepend (bool): If true, the provided hook will be fired before
all existing backward_pre hooks on this
torch.nn.Module. Otherwise, the provided
hook will be fired after all existing backward_pre hooks
on this torch.nn.Module. Note that global
backward_pre hooks registered with
register_module_full_backward_pre_hook() will fire before
all hooks registered by this method.
Returns:
torch.utils.hooks.RemovableHandle:
a handle that can be used to remove the added hook by calling
handle.remove()
Register a post-hook to be run after module’s load_state_dict() is called.
It should have the following signature::
hook(module, incompatible_keys) -> None
The module argument is the current module that this hook is registered
on, and the incompatible_keys argument is a NamedTuple consisting
of attributes missing_keys and unexpected_keys. missing_keys
is a list of str containing the missing keys and
unexpected_keys is a list of str containing the unexpected keys.
The given incompatible_keys can be modified inplace if needed.
Note that the checks performed when calling load_state_dict() with
strict=True are affected by modifications the hook makes to
missing_keys or unexpected_keys, as expected. Additions to either
set of keys will result in an error being thrown when strict=True, and
clearing out both missing and unexpected keys will avoid an error.
Returns:
torch.utils.hooks.RemovableHandle:
a handle that can be used to remove the added hook by calling
handle.remove()
Set extra state contained in the loaded state_dict.
This function is called from load_state_dict() to handle any extra state
found within the state_dict. Implement this function and a corresponding
get_extra_state() for your module if you need to store extra state within its
state_dict.
Set the submodule given by target if it exists, otherwise throw an error.
Note
If strict is set to False (default), the method will replace an existing submodule
or create a new submodule if the parent module exists. If strict is set to True,
the method will only attempt to replace an existing submodule and throw an error if
the submodule does not exist.
For example, let’s say you have an nn.ModuleA that
looks like this:
(The diagram shows an nn.ModuleA. A has a nested
submodule net_b, which itself has two submodules net_c
and linear. net_c then has a submodule conv.)
To override the Conv2d with a new submodule Linear, you
could call set_submodule("net_b.net_c.conv",nn.Linear(1,1))
where strict could be True or False
To add a new submodule Conv2d to the existing net_b module,
you would call set_submodule("net_b.conv",nn.Conv2d(1,1,1)).
In the above if you set strict=True and call
set_submodule("net_b.conv",nn.Conv2d(1,1,1),strict=True), an AttributeError
will be raised because net_b does not have a submodule named conv.
Args:
target: The fully-qualified string name of the submodule
to look for. (See above example for how to specify a
fully-qualified string.)
module: The module to set the submodule to.
strict: If False, the method will replace an existing submodule
or create a new submodule if the parent module exists. If True,
the method will only attempt to replace an existing submodule and throw an error
if the submodule doesn’t already exist.
Raises:
ValueError: If the target string is empty or if module is not an instance of nn.Module.
AttributeError: If at any point along the path resulting from
the target string the (sub)path resolves to a non-existent
attribute name or an object that is not an instance of nn.Module.
Return a dictionary containing references to the whole state of the module.
Both parameters and persistent buffers (e.g. running averages) are
included. Keys are corresponding parameter and buffer names.
Parameters and buffers set to None are not included.
Note
The returned object is a shallow copy. It contains references
to the module’s parameters and buffers.
Warning
Currently state_dict() also accepts positional arguments for
destination, prefix and keep_vars in order. However,
this is being deprecated and keyword arguments will be enforced in
future releases.
Warning
Please avoid the use of argument destination as it is not
designed for end-users.
Args:
destination (dict, optional): If provided, the state of module will
be updated into the dict and the same object is returned.
Otherwise, an OrderedDict will be created and returned.
Default: None.
prefix (str, optional): a prefix added to parameter and buffer
names to compose the keys in state_dict. Default: ''.
keep_vars (bool, optional): by default the Tensor s
returned in the state dict are detached from autograd. If it’s
set to True, detaching will not be performed.
Default: False.
Returns:
dict:
a dictionary containing a whole state of the module
Its signature is similar to torch.Tensor.to(), but only accepts
floating point or complex dtypes. In addition, this method will
only cast the floating point or complex parameters and buffers to dtype
(if given). The integral parameters and buffers will be moved
device, if that is given, but with dtypes unchanged. When
non_blocking is set, it tries to convert/move asynchronously
with respect to the host if possible, e.g., moving CPU Tensors with
pinned memory to CUDA devices.
See below for examples.
Note
This method modifies the module in-place.
Args:
device (torch.device): the desired device of the parameters
and buffers in this module
dtype (torch.dtype): the desired floating point or complex dtype of
the parameters and buffers in this module
tensor (torch.Tensor): Tensor whose dtype and device are the desired
dtype and device for all parameters and buffers in this module
This has an effect only on certain modules. See the documentation of
particular modules for details of their behaviors in training/evaluation
mode, i.e., whether they are affected, e.g. Dropout, BatchNorm,
etc.
Args:
mode (bool): whether to set training mode (True) or evaluation
This also makes associated parameters and buffers different objects. So
it should be called before constructing optimizer if the module will
live on XPU while being optimized.
Note
This method modifies the module in-place.
Arguments:
device (int, optional): if specified, all parameters will be
Gaussian smoothing over ERB frequency channels for spatial integration.
Applies a Gaussian kernel to smooth specific loudness across frequency channels,
implementing the spatial integration mechanism of the auditory system. This models
the spread of excitation across the auditory nerve and represents the limited
frequency selectivity of loudness integration.
>>> smoothing_learn=SpatialSmoothing(kernel_width=18.0,sigma=0.08,learnable=True)>>> # Kernel computed dynamically in forward() based on learned sigma>>> optimizer=torch.optim.Adam(smoothing_learn.parameters(),lr=1e-3)
This also makes associated parameters and buffers different objects. So
it should be called before constructing the optimizer if the module will
live on GPU while being optimized.
Note
This method modifies the module in-place.
Args:
device (int, optional): if specified, all parameters will be
This has an effect only on certain modules. See the documentation of
particular modules for details of their behaviors in training/evaluation
mode, i.e. whether they are affected, e.g. Dropout, BatchNorm,
etc.
Return any extra state to include in the module’s state_dict.
Implement this and a corresponding set_extra_state() for your module
if you need to store extra state. This function is called when building the
module’s state_dict().
Note that extra state should be picklable to ensure working serialization
of the state_dict. We only provide backwards compatibility guarantees
for serializing Tensors; other objects may break backwards compatibility if
their serialized pickled form changes.
(The diagram shows an nn.ModuleA. A which has a nested
submodule net_b, which itself has two submodules net_c
and linear. net_c then has a submodule conv.)
To check whether or not we have the linear submodule, we
would call get_submodule("net_b.linear"). To check whether
we have the conv submodule, we would call
get_submodule("net_b.net_c.conv").
The runtime of get_submodule is bounded by the degree
of module nesting in target. A query against
named_modules achieves the same result, but it is O(N) in
the number of transitive modules. So, for a simple check to see
if some submodule exists, get_submodule should always be
used.
Args:
target: The fully-qualified string name of the submodule
to look for. (See above example for how to specify a
fully-qualified string.)
Returns:
torch.nn.Module: The submodule referenced by target
Raises:
AttributeError: If at any point along the path resulting from
the target string the (sub)path resolves to a non-existent
attribute name or an object that is not an instance of nn.Module.
This also makes associated parameters and buffers different objects. So
it should be called before constructing the optimizer if the module will
live on IPU while being optimized.
Note
This method modifies the module in-place.
Arguments:
device (int, optional): if specified, all parameters will be
state_dict (dict): a dict containing parameters and
persistent buffers.
strict (bool, optional): whether to strictly enforce that the keys
in state_dict match the keys returned by this module’s
state_dict() function. Default: True
assign (bool, optional): When set to False, the properties of the tensors
in the current module are preserved whereas setting it to True preserves
properties of the Tensors in the state dict. The only
exception is the requires_grad field of Parameter
for which the value from the module is preserved. Default: False
Returns:
NamedTuple with missing_keys and unexpected_keys fields:
missing_keys is a list of str containing any keys that are expected
by this module but missing from the provided state_dict.
unexpected_keys is a list of str containing the keys that are not
expected by this module but present in the provided state_dict.
Note:
If a parameter or buffer is registered as None and its corresponding key
exists in state_dict, load_state_dict() will raise a
RuntimeError.
Move all model parameters and buffers to the MTIA.
This also makes associated parameters and buffers different objects. So
it should be called before constructing the optimizer if the module will
live on MTIA while being optimized.
Note
This method modifies the module in-place.
Arguments:
device (int, optional): if specified, all parameters will be
Return an iterator over all modules in the network, yielding both the name of the module as well as the module itself.
Args:
memo: a memo to store the set of modules already added to the result
prefix: a prefix that will be added to the name of the module
remove_duplicate: whether to remove the duplicated module instances in the result
or not
Yields:
(str, Module): Tuple of name and module
Note:
Duplicate modules are returned only once. In the following
example, l will be returned only once.
This is typically used to register a buffer that should not be
considered a model parameter. For example, BatchNorm’s running_mean
is not a parameter, but is part of the module’s state. Buffers, by
default, are persistent and will be saved alongside parameters. This
behavior can be changed by setting persistent to False. The
only difference between a persistent buffer and a non-persistent buffer
is that the latter will not be a part of this module’s
state_dict.
Buffers can be accessed as attributes using given names.
Args:
name (str): name of the buffer. The buffer can be accessed
from this module using the given name
tensor (Tensor or None): buffer to be registered. If None, then operations
that run on buffers, such as cuda, are ignored. If None,
the buffer is not included in the module’s state_dict.
persistent (bool): whether the buffer is part of this module’s
The hook will be called every time after forward() has computed an output.
If with_kwargs is False or not specified, the input contains only
the positional arguments given to the module. Keyword arguments won’t be
passed to the hooks and only to the forward. The hook can modify the
output. It can modify the input inplace but it will not have effect on
forward since this is called after forward() is called. The hook
should have the following signature:
hook(module,args,output)->Noneormodifiedoutput
If with_kwargs is True, the forward hook will be passed the
kwargs given to the forward function and be expected to return the
output possibly modified. The hook should have the following signature:
hook (Callable): The user defined hook to be registered.
prepend (bool): If True, the provided hook will be fired
before all existing forward hooks on this
torch.nn.Module. Otherwise, the provided
hook will be fired after all existing forward hooks on
this torch.nn.Module. Note that global
forward hooks registered with
register_module_forward_hook() will fire before all hooks
registered by this method.
Default: False
with_kwargs (bool): If True, the hook will be passed the
kwargs given to the forward function.
Default: False
always_call (bool): If True the hook will be run regardless of
whether an exception is raised while calling the Module.
Default: False
Returns:
torch.utils.hooks.RemovableHandle:
a handle that can be used to remove the added hook by calling
handle.remove()
The hook will be called every time before forward() is invoked.
If with_kwargs is false or not specified, the input contains only
the positional arguments given to the module. Keyword arguments won’t be
passed to the hooks and only to the forward. The hook can modify the
input. User can either return a tuple or a single modified value in the
hook. We will wrap the value into a tuple if a single value is returned
(unless that value is already a tuple). The hook should have the
following signature:
hook(module,args)->Noneormodifiedinput
If with_kwargs is true, the forward pre-hook will be passed the
kwargs given to the forward function. And if the hook modifies the
input, both the args and kwargs should be returned. The hook should have
the following signature:
hook (Callable): The user defined hook to be registered.
prepend (bool): If true, the provided hook will be fired before
all existing forward_pre hooks on this
torch.nn.Module. Otherwise, the provided
hook will be fired after all existing forward_pre hooks
on this torch.nn.Module. Note that global
forward_pre hooks registered with
register_module_forward_pre_hook() will fire before all
hooks registered by this method.
Default: False
with_kwargs (bool): If true, the hook will be passed the kwargs
given to the forward function.
Default: False
Returns:
torch.utils.hooks.RemovableHandle:
a handle that can be used to remove the added hook by calling
handle.remove()
The grad_input and grad_output are tuples that contain the gradients
with respect to the inputs and outputs respectively. The hook should
not modify its arguments, but it can optionally return a new gradient with
respect to the input that will be used in place of grad_input in
subsequent computations. grad_input will only correspond to the inputs given
as positional arguments and all kwarg arguments are ignored. Entries
in grad_input and grad_output will be None for all non-Tensor
arguments.
For technical reasons, when this hook is applied to a Module, its forward function will
receive a view of each Tensor passed to the Module. Similarly the caller will receive a view
of each Tensor returned by the Module’s forward function.
Warning
Modifying inputs or outputs inplace is not allowed when using backward hooks and
will raise an error.
Args:
hook (Callable): The user-defined hook to be registered.
prepend (bool): If true, the provided hook will be fired before
all existing backward hooks on this
torch.nn.Module. Otherwise, the provided
hook will be fired after all existing backward hooks on
this torch.nn.Module. Note that global
backward hooks registered with
register_module_full_backward_hook() will fire before
all hooks registered by this method.
Returns:
torch.utils.hooks.RemovableHandle:
a handle that can be used to remove the added hook by calling
handle.remove()
The grad_output is a tuple. The hook should
not modify its arguments, but it can optionally return a new gradient with
respect to the output that will be used in place of grad_output in
subsequent computations. Entries in grad_output will be None for
all non-Tensor arguments.
For technical reasons, when this hook is applied to a Module, its forward function will
receive a view of each Tensor passed to the Module. Similarly the caller will receive a view
of each Tensor returned by the Module’s forward function.
Warning
Modifying inputs inplace is not allowed when using backward hooks and
will raise an error.
Args:
hook (Callable): The user-defined hook to be registered.
prepend (bool): If true, the provided hook will be fired before
all existing backward_pre hooks on this
torch.nn.Module. Otherwise, the provided
hook will be fired after all existing backward_pre hooks
on this torch.nn.Module. Note that global
backward_pre hooks registered with
register_module_full_backward_pre_hook() will fire before
all hooks registered by this method.
Returns:
torch.utils.hooks.RemovableHandle:
a handle that can be used to remove the added hook by calling
handle.remove()
Register a post-hook to be run after module’s load_state_dict() is called.
It should have the following signature::
hook(module, incompatible_keys) -> None
The module argument is the current module that this hook is registered
on, and the incompatible_keys argument is a NamedTuple consisting
of attributes missing_keys and unexpected_keys. missing_keys
is a list of str containing the missing keys and
unexpected_keys is a list of str containing the unexpected keys.
The given incompatible_keys can be modified inplace if needed.
Note that the checks performed when calling load_state_dict() with
strict=True are affected by modifications the hook makes to
missing_keys or unexpected_keys, as expected. Additions to either
set of keys will result in an error being thrown when strict=True, and
clearing out both missing and unexpected keys will avoid an error.
Returns:
torch.utils.hooks.RemovableHandle:
a handle that can be used to remove the added hook by calling
handle.remove()
Set extra state contained in the loaded state_dict.
This function is called from load_state_dict() to handle any extra state
found within the state_dict. Implement this function and a corresponding
get_extra_state() for your module if you need to store extra state within its
state_dict.
Set the submodule given by target if it exists, otherwise throw an error.
Note
If strict is set to False (default), the method will replace an existing submodule
or create a new submodule if the parent module exists. If strict is set to True,
the method will only attempt to replace an existing submodule and throw an error if
the submodule does not exist.
For example, let’s say you have an nn.ModuleA that
looks like this:
(The diagram shows an nn.ModuleA. A has a nested
submodule net_b, which itself has two submodules net_c
and linear. net_c then has a submodule conv.)
To override the Conv2d with a new submodule Linear, you
could call set_submodule("net_b.net_c.conv",nn.Linear(1,1))
where strict could be True or False
To add a new submodule Conv2d to the existing net_b module,
you would call set_submodule("net_b.conv",nn.Conv2d(1,1,1)).
In the above if you set strict=True and call
set_submodule("net_b.conv",nn.Conv2d(1,1,1),strict=True), an AttributeError
will be raised because net_b does not have a submodule named conv.
Args:
target: The fully-qualified string name of the submodule
to look for. (See above example for how to specify a
fully-qualified string.)
module: The module to set the submodule to.
strict: If False, the method will replace an existing submodule
or create a new submodule if the parent module exists. If True,
the method will only attempt to replace an existing submodule and throw an error
if the submodule doesn’t already exist.
Raises:
ValueError: If the target string is empty or if module is not an instance of nn.Module.
AttributeError: If at any point along the path resulting from
the target string the (sub)path resolves to a non-existent
attribute name or an object that is not an instance of nn.Module.
Return a dictionary containing references to the whole state of the module.
Both parameters and persistent buffers (e.g. running averages) are
included. Keys are corresponding parameter and buffer names.
Parameters and buffers set to None are not included.
Note
The returned object is a shallow copy. It contains references
to the module’s parameters and buffers.
Warning
Currently state_dict() also accepts positional arguments for
destination, prefix and keep_vars in order. However,
this is being deprecated and keyword arguments will be enforced in
future releases.
Warning
Please avoid the use of argument destination as it is not
designed for end-users.
Args:
destination (dict, optional): If provided, the state of module will
be updated into the dict and the same object is returned.
Otherwise, an OrderedDict will be created and returned.
Default: None.
prefix (str, optional): a prefix added to parameter and buffer
names to compose the keys in state_dict. Default: ''.
keep_vars (bool, optional): by default the Tensor s
returned in the state dict are detached from autograd. If it’s
set to True, detaching will not be performed.
Default: False.
Returns:
dict:
a dictionary containing a whole state of the module
Its signature is similar to torch.Tensor.to(), but only accepts
floating point or complex dtypes. In addition, this method will
only cast the floating point or complex parameters and buffers to dtype
(if given). The integral parameters and buffers will be moved
device, if that is given, but with dtypes unchanged. When
non_blocking is set, it tries to convert/move asynchronously
with respect to the host if possible, e.g., moving CPU Tensors with
pinned memory to CUDA devices.
See below for examples.
Note
This method modifies the module in-place.
Args:
device (torch.device): the desired device of the parameters
and buffers in this module
dtype (torch.dtype): the desired floating point or complex dtype of
the parameters and buffers in this module
tensor (torch.Tensor): Tensor whose dtype and device are the desired
dtype and device for all parameters and buffers in this module
This has an effect only on certain modules. See the documentation of
particular modules for details of their behaviors in training/evaluation
mode, i.e., whether they are affected, e.g. Dropout, BatchNorm,
etc.
Args:
mode (bool): whether to set training mode (True) or evaluation
This also makes associated parameters and buffers different objects. So
it should be called before constructing optimizer if the module will
live on XPU while being optimized.
Note
This method modifies the module in-place.
Arguments:
device (int, optional): if specified, all parameters will be
Cross-ear binaural inhibition using hyperbolic secant (sech) function.
Implements the binaural inhibition mechanism where specific loudness in one ear is
suppressed based on the loudness ratio between ears. The inhibition is symmetric
and models the competitive interaction between the two ears in loudness perception.
>>> N_L_inhib=N_left/I_left# Inhibited left loudness>>> N_R_inhib=N_right/I_right# Inhibited right loudness>>> print(f"After inhibition: Left sum={N_L_inhib.sum():.2f}, Right sum={N_R_inhib.sum():.2f}")After inhibition: Left sum=523.45, Right sum=487.32
This also makes associated parameters and buffers different objects. So
it should be called before constructing the optimizer if the module will
live on GPU while being optimized.
Note
This method modifies the module in-place.
Args:
device (int, optional): if specified, all parameters will be
This has an effect only on certain modules. See the documentation of
particular modules for details of their behaviors in training/evaluation
mode, i.e. whether they are affected, e.g. Dropout, BatchNorm,
etc.
Return any extra state to include in the module’s state_dict.
Implement this and a corresponding set_extra_state() for your module
if you need to store extra state. This function is called when building the
module’s state_dict().
Note that extra state should be picklable to ensure working serialization
of the state_dict. We only provide backwards compatibility guarantees
for serializing Tensors; other objects may break backwards compatibility if
their serialized pickled form changes.
(The diagram shows an nn.ModuleA. A which has a nested
submodule net_b, which itself has two submodules net_c
and linear. net_c then has a submodule conv.)
To check whether or not we have the linear submodule, we
would call get_submodule("net_b.linear"). To check whether
we have the conv submodule, we would call
get_submodule("net_b.net_c.conv").
The runtime of get_submodule is bounded by the degree
of module nesting in target. A query against
named_modules achieves the same result, but it is O(N) in
the number of transitive modules. So, for a simple check to see
if some submodule exists, get_submodule should always be
used.
Args:
target: The fully-qualified string name of the submodule
to look for. (See above example for how to specify a
fully-qualified string.)
Returns:
torch.nn.Module: The submodule referenced by target
Raises:
AttributeError: If at any point along the path resulting from
the target string the (sub)path resolves to a non-existent
attribute name or an object that is not an instance of nn.Module.
This also makes associated parameters and buffers different objects. So
it should be called before constructing the optimizer if the module will
live on IPU while being optimized.
Note
This method modifies the module in-place.
Arguments:
device (int, optional): if specified, all parameters will be
state_dict (dict): a dict containing parameters and
persistent buffers.
strict (bool, optional): whether to strictly enforce that the keys
in state_dict match the keys returned by this module’s
state_dict() function. Default: True
assign (bool, optional): When set to False, the properties of the tensors
in the current module are preserved whereas setting it to True preserves
properties of the Tensors in the state dict. The only
exception is the requires_grad field of Parameter
for which the value from the module is preserved. Default: False
Returns:
NamedTuple with missing_keys and unexpected_keys fields:
missing_keys is a list of str containing any keys that are expected
by this module but missing from the provided state_dict.
unexpected_keys is a list of str containing the keys that are not
expected by this module but present in the provided state_dict.
Note:
If a parameter or buffer is registered as None and its corresponding key
exists in state_dict, load_state_dict() will raise a
RuntimeError.
Move all model parameters and buffers to the MTIA.
This also makes associated parameters and buffers different objects. So
it should be called before constructing the optimizer if the module will
live on MTIA while being optimized.
Note
This method modifies the module in-place.
Arguments:
device (int, optional): if specified, all parameters will be
Return an iterator over all modules in the network, yielding both the name of the module as well as the module itself.
Args:
memo: a memo to store the set of modules already added to the result
prefix: a prefix that will be added to the name of the module
remove_duplicate: whether to remove the duplicated module instances in the result
or not
Yields:
(str, Module): Tuple of name and module
Note:
Duplicate modules are returned only once. In the following
example, l will be returned only once.
This is typically used to register a buffer that should not be
considered a model parameter. For example, BatchNorm’s running_mean
is not a parameter, but is part of the module’s state. Buffers, by
default, are persistent and will be saved alongside parameters. This
behavior can be changed by setting persistent to False. The
only difference between a persistent buffer and a non-persistent buffer
is that the latter will not be a part of this module’s
state_dict.
Buffers can be accessed as attributes using given names.
Args:
name (str): name of the buffer. The buffer can be accessed
from this module using the given name
tensor (Tensor or None): buffer to be registered. If None, then operations
that run on buffers, such as cuda, are ignored. If None,
the buffer is not included in the module’s state_dict.
persistent (bool): whether the buffer is part of this module’s
The hook will be called every time after forward() has computed an output.
If with_kwargs is False or not specified, the input contains only
the positional arguments given to the module. Keyword arguments won’t be
passed to the hooks and only to the forward. The hook can modify the
output. It can modify the input inplace but it will not have effect on
forward since this is called after forward() is called. The hook
should have the following signature:
hook(module,args,output)->Noneormodifiedoutput
If with_kwargs is True, the forward hook will be passed the
kwargs given to the forward function and be expected to return the
output possibly modified. The hook should have the following signature:
hook (Callable): The user defined hook to be registered.
prepend (bool): If True, the provided hook will be fired
before all existing forward hooks on this
torch.nn.Module. Otherwise, the provided
hook will be fired after all existing forward hooks on
this torch.nn.Module. Note that global
forward hooks registered with
register_module_forward_hook() will fire before all hooks
registered by this method.
Default: False
with_kwargs (bool): If True, the hook will be passed the
kwargs given to the forward function.
Default: False
always_call (bool): If True the hook will be run regardless of
whether an exception is raised while calling the Module.
Default: False
Returns:
torch.utils.hooks.RemovableHandle:
a handle that can be used to remove the added hook by calling
handle.remove()
The hook will be called every time before forward() is invoked.
If with_kwargs is false or not specified, the input contains only
the positional arguments given to the module. Keyword arguments won’t be
passed to the hooks and only to the forward. The hook can modify the
input. User can either return a tuple or a single modified value in the
hook. We will wrap the value into a tuple if a single value is returned
(unless that value is already a tuple). The hook should have the
following signature:
hook(module,args)->Noneormodifiedinput
If with_kwargs is true, the forward pre-hook will be passed the
kwargs given to the forward function. And if the hook modifies the
input, both the args and kwargs should be returned. The hook should have
the following signature:
hook (Callable): The user defined hook to be registered.
prepend (bool): If true, the provided hook will be fired before
all existing forward_pre hooks on this
torch.nn.Module. Otherwise, the provided
hook will be fired after all existing forward_pre hooks
on this torch.nn.Module. Note that global
forward_pre hooks registered with
register_module_forward_pre_hook() will fire before all
hooks registered by this method.
Default: False
with_kwargs (bool): If true, the hook will be passed the kwargs
given to the forward function.
Default: False
Returns:
torch.utils.hooks.RemovableHandle:
a handle that can be used to remove the added hook by calling
handle.remove()
The grad_input and grad_output are tuples that contain the gradients
with respect to the inputs and outputs respectively. The hook should
not modify its arguments, but it can optionally return a new gradient with
respect to the input that will be used in place of grad_input in
subsequent computations. grad_input will only correspond to the inputs given
as positional arguments and all kwarg arguments are ignored. Entries
in grad_input and grad_output will be None for all non-Tensor
arguments.
For technical reasons, when this hook is applied to a Module, its forward function will
receive a view of each Tensor passed to the Module. Similarly the caller will receive a view
of each Tensor returned by the Module’s forward function.
Warning
Modifying inputs or outputs inplace is not allowed when using backward hooks and
will raise an error.
Args:
hook (Callable): The user-defined hook to be registered.
prepend (bool): If true, the provided hook will be fired before
all existing backward hooks on this
torch.nn.Module. Otherwise, the provided
hook will be fired after all existing backward hooks on
this torch.nn.Module. Note that global
backward hooks registered with
register_module_full_backward_hook() will fire before
all hooks registered by this method.
Returns:
torch.utils.hooks.RemovableHandle:
a handle that can be used to remove the added hook by calling
handle.remove()
The grad_output is a tuple. The hook should
not modify its arguments, but it can optionally return a new gradient with
respect to the output that will be used in place of grad_output in
subsequent computations. Entries in grad_output will be None for
all non-Tensor arguments.
For technical reasons, when this hook is applied to a Module, its forward function will
receive a view of each Tensor passed to the Module. Similarly the caller will receive a view
of each Tensor returned by the Module’s forward function.
Warning
Modifying inputs inplace is not allowed when using backward hooks and
will raise an error.
Args:
hook (Callable): The user-defined hook to be registered.
prepend (bool): If true, the provided hook will be fired before
all existing backward_pre hooks on this
torch.nn.Module. Otherwise, the provided
hook will be fired after all existing backward_pre hooks
on this torch.nn.Module. Note that global
backward_pre hooks registered with
register_module_full_backward_pre_hook() will fire before
all hooks registered by this method.
Returns:
torch.utils.hooks.RemovableHandle:
a handle that can be used to remove the added hook by calling
handle.remove()
Register a post-hook to be run after module’s load_state_dict() is called.
It should have the following signature::
hook(module, incompatible_keys) -> None
The module argument is the current module that this hook is registered
on, and the incompatible_keys argument is a NamedTuple consisting
of attributes missing_keys and unexpected_keys. missing_keys
is a list of str containing the missing keys and
unexpected_keys is a list of str containing the unexpected keys.
The given incompatible_keys can be modified inplace if needed.
Note that the checks performed when calling load_state_dict() with
strict=True are affected by modifications the hook makes to
missing_keys or unexpected_keys, as expected. Additions to either
set of keys will result in an error being thrown when strict=True, and
clearing out both missing and unexpected keys will avoid an error.
Returns:
torch.utils.hooks.RemovableHandle:
a handle that can be used to remove the added hook by calling
handle.remove()
Set extra state contained in the loaded state_dict.
This function is called from load_state_dict() to handle any extra state
found within the state_dict. Implement this function and a corresponding
get_extra_state() for your module if you need to store extra state within its
state_dict.
Set the submodule given by target if it exists, otherwise throw an error.
Note
If strict is set to False (default), the method will replace an existing submodule
or create a new submodule if the parent module exists. If strict is set to True,
the method will only attempt to replace an existing submodule and throw an error if
the submodule does not exist.
For example, let’s say you have an nn.ModuleA that
looks like this:
(The diagram shows an nn.ModuleA. A has a nested
submodule net_b, which itself has two submodules net_c
and linear. net_c then has a submodule conv.)
To override the Conv2d with a new submodule Linear, you
could call set_submodule("net_b.net_c.conv",nn.Linear(1,1))
where strict could be True or False
To add a new submodule Conv2d to the existing net_b module,
you would call set_submodule("net_b.conv",nn.Conv2d(1,1,1)).
In the above if you set strict=True and call
set_submodule("net_b.conv",nn.Conv2d(1,1,1),strict=True), an AttributeError
will be raised because net_b does not have a submodule named conv.
Args:
target: The fully-qualified string name of the submodule
to look for. (See above example for how to specify a
fully-qualified string.)
module: The module to set the submodule to.
strict: If False, the method will replace an existing submodule
or create a new submodule if the parent module exists. If True,
the method will only attempt to replace an existing submodule and throw an error
if the submodule doesn’t already exist.
Raises:
ValueError: If the target string is empty or if module is not an instance of nn.Module.
AttributeError: If at any point along the path resulting from
the target string the (sub)path resolves to a non-existent
attribute name or an object that is not an instance of nn.Module.
Return a dictionary containing references to the whole state of the module.
Both parameters and persistent buffers (e.g. running averages) are
included. Keys are corresponding parameter and buffer names.
Parameters and buffers set to None are not included.
Note
The returned object is a shallow copy. It contains references
to the module’s parameters and buffers.
Warning
Currently state_dict() also accepts positional arguments for
destination, prefix and keep_vars in order. However,
this is being deprecated and keyword arguments will be enforced in
future releases.
Warning
Please avoid the use of argument destination as it is not
designed for end-users.
Args:
destination (dict, optional): If provided, the state of module will
be updated into the dict and the same object is returned.
Otherwise, an OrderedDict will be created and returned.
Default: None.
prefix (str, optional): a prefix added to parameter and buffer
names to compose the keys in state_dict. Default: ''.
keep_vars (bool, optional): by default the Tensor s
returned in the state dict are detached from autograd. If it’s
set to True, detaching will not be performed.
Default: False.
Returns:
dict:
a dictionary containing a whole state of the module
Its signature is similar to torch.Tensor.to(), but only accepts
floating point or complex dtypes. In addition, this method will
only cast the floating point or complex parameters and buffers to dtype
(if given). The integral parameters and buffers will be moved
device, if that is given, but with dtypes unchanged. When
non_blocking is set, it tries to convert/move asynchronously
with respect to the host if possible, e.g., moving CPU Tensors with
pinned memory to CUDA devices.
See below for examples.
Note
This method modifies the module in-place.
Args:
device (torch.device): the desired device of the parameters
and buffers in this module
dtype (torch.dtype): the desired floating point or complex dtype of
the parameters and buffers in this module
tensor (torch.Tensor): Tensor whose dtype and device are the desired
dtype and device for all parameters and buffers in this module
This has an effect only on certain modules. See the documentation of
particular modules for details of their behaviors in training/evaluation
mode, i.e., whether they are affected, e.g. Dropout, BatchNorm,
etc.
Args:
mode (bool): whether to set training mode (True) or evaluation
This also makes associated parameters and buffers different objects. So
it should be called before constructing optimizer if the module will
live on XPU while being optimized.
Note
This method modifies the module in-place.
Arguments:
device (int, optional): if specified, all parameters will be
Complete binaural loudness computation for Moore et al. (2016) model.
Combines spatial smoothing, binaural inhibition, and loudness integration
to compute total binaural loudness from left and right specific loudness patterns.
Implements the complete loudness stage following Moore, Glasberg & Schlittenlacher (2016)
with ANSI S3.4-2007 normalization.
>>> binaural_learn=Moore2016BinauralLoudness(learnable=True)>>> # Can train spatial_smoothing.sigma and inhibition.p>>> optimizer=torch.optim.Adam(binaural_learn.parameters(),lr=1e-3)
This also makes associated parameters and buffers different objects. So
it should be called before constructing the optimizer if the module will
live on GPU while being optimized.
Note
This method modifies the module in-place.
Args:
device (int, optional): if specified, all parameters will be
This has an effect only on certain modules. See the documentation of
particular modules for details of their behaviors in training/evaluation
mode, i.e. whether they are affected, e.g. Dropout, BatchNorm,
etc.
Return any extra state to include in the module’s state_dict.
Implement this and a corresponding set_extra_state() for your module
if you need to store extra state. This function is called when building the
module’s state_dict().
Note that extra state should be picklable to ensure working serialization
of the state_dict. We only provide backwards compatibility guarantees
for serializing Tensors; other objects may break backwards compatibility if
their serialized pickled form changes.
(The diagram shows an nn.ModuleA. A which has a nested
submodule net_b, which itself has two submodules net_c
and linear. net_c then has a submodule conv.)
To check whether or not we have the linear submodule, we
would call get_submodule("net_b.linear"). To check whether
we have the conv submodule, we would call
get_submodule("net_b.net_c.conv").
The runtime of get_submodule is bounded by the degree
of module nesting in target. A query against
named_modules achieves the same result, but it is O(N) in
the number of transitive modules. So, for a simple check to see
if some submodule exists, get_submodule should always be
used.
Args:
target: The fully-qualified string name of the submodule
to look for. (See above example for how to specify a
fully-qualified string.)
Returns:
torch.nn.Module: The submodule referenced by target
Raises:
AttributeError: If at any point along the path resulting from
the target string the (sub)path resolves to a non-existent
attribute name or an object that is not an instance of nn.Module.
This also makes associated parameters and buffers different objects. So
it should be called before constructing the optimizer if the module will
live on IPU while being optimized.
Note
This method modifies the module in-place.
Arguments:
device (int, optional): if specified, all parameters will be
state_dict (dict): a dict containing parameters and
persistent buffers.
strict (bool, optional): whether to strictly enforce that the keys
in state_dict match the keys returned by this module’s
state_dict() function. Default: True
assign (bool, optional): When set to False, the properties of the tensors
in the current module are preserved whereas setting it to True preserves
properties of the Tensors in the state dict. The only
exception is the requires_grad field of Parameter
for which the value from the module is preserved. Default: False
Returns:
NamedTuple with missing_keys and unexpected_keys fields:
missing_keys is a list of str containing any keys that are expected
by this module but missing from the provided state_dict.
unexpected_keys is a list of str containing the keys that are not
expected by this module but present in the provided state_dict.
Note:
If a parameter or buffer is registered as None and its corresponding key
exists in state_dict, load_state_dict() will raise a
RuntimeError.
Move all model parameters and buffers to the MTIA.
This also makes associated parameters and buffers different objects. So
it should be called before constructing the optimizer if the module will
live on MTIA while being optimized.
Note
This method modifies the module in-place.
Arguments:
device (int, optional): if specified, all parameters will be
Return an iterator over all modules in the network, yielding both the name of the module as well as the module itself.
Args:
memo: a memo to store the set of modules already added to the result
prefix: a prefix that will be added to the name of the module
remove_duplicate: whether to remove the duplicated module instances in the result
or not
Yields:
(str, Module): Tuple of name and module
Note:
Duplicate modules are returned only once. In the following
example, l will be returned only once.
This is typically used to register a buffer that should not be
considered a model parameter. For example, BatchNorm’s running_mean
is not a parameter, but is part of the module’s state. Buffers, by
default, are persistent and will be saved alongside parameters. This
behavior can be changed by setting persistent to False. The
only difference between a persistent buffer and a non-persistent buffer
is that the latter will not be a part of this module’s
state_dict.
Buffers can be accessed as attributes using given names.
Args:
name (str): name of the buffer. The buffer can be accessed
from this module using the given name
tensor (Tensor or None): buffer to be registered. If None, then operations
that run on buffers, such as cuda, are ignored. If None,
the buffer is not included in the module’s state_dict.
persistent (bool): whether the buffer is part of this module’s
The hook will be called every time after forward() has computed an output.
If with_kwargs is False or not specified, the input contains only
the positional arguments given to the module. Keyword arguments won’t be
passed to the hooks and only to the forward. The hook can modify the
output. It can modify the input inplace but it will not have effect on
forward since this is called after forward() is called. The hook
should have the following signature:
hook(module,args,output)->Noneormodifiedoutput
If with_kwargs is True, the forward hook will be passed the
kwargs given to the forward function and be expected to return the
output possibly modified. The hook should have the following signature:
hook (Callable): The user defined hook to be registered.
prepend (bool): If True, the provided hook will be fired
before all existing forward hooks on this
torch.nn.Module. Otherwise, the provided
hook will be fired after all existing forward hooks on
this torch.nn.Module. Note that global
forward hooks registered with
register_module_forward_hook() will fire before all hooks
registered by this method.
Default: False
with_kwargs (bool): If True, the hook will be passed the
kwargs given to the forward function.
Default: False
always_call (bool): If True the hook will be run regardless of
whether an exception is raised while calling the Module.
Default: False
Returns:
torch.utils.hooks.RemovableHandle:
a handle that can be used to remove the added hook by calling
handle.remove()
The hook will be called every time before forward() is invoked.
If with_kwargs is false or not specified, the input contains only
the positional arguments given to the module. Keyword arguments won’t be
passed to the hooks and only to the forward. The hook can modify the
input. User can either return a tuple or a single modified value in the
hook. We will wrap the value into a tuple if a single value is returned
(unless that value is already a tuple). The hook should have the
following signature:
hook(module,args)->Noneormodifiedinput
If with_kwargs is true, the forward pre-hook will be passed the
kwargs given to the forward function. And if the hook modifies the
input, both the args and kwargs should be returned. The hook should have
the following signature:
hook (Callable): The user defined hook to be registered.
prepend (bool): If true, the provided hook will be fired before
all existing forward_pre hooks on this
torch.nn.Module. Otherwise, the provided
hook will be fired after all existing forward_pre hooks
on this torch.nn.Module. Note that global
forward_pre hooks registered with
register_module_forward_pre_hook() will fire before all
hooks registered by this method.
Default: False
with_kwargs (bool): If true, the hook will be passed the kwargs
given to the forward function.
Default: False
Returns:
torch.utils.hooks.RemovableHandle:
a handle that can be used to remove the added hook by calling
handle.remove()
The grad_input and grad_output are tuples that contain the gradients
with respect to the inputs and outputs respectively. The hook should
not modify its arguments, but it can optionally return a new gradient with
respect to the input that will be used in place of grad_input in
subsequent computations. grad_input will only correspond to the inputs given
as positional arguments and all kwarg arguments are ignored. Entries
in grad_input and grad_output will be None for all non-Tensor
arguments.
For technical reasons, when this hook is applied to a Module, its forward function will
receive a view of each Tensor passed to the Module. Similarly the caller will receive a view
of each Tensor returned by the Module’s forward function.
Warning
Modifying inputs or outputs inplace is not allowed when using backward hooks and
will raise an error.
Args:
hook (Callable): The user-defined hook to be registered.
prepend (bool): If true, the provided hook will be fired before
all existing backward hooks on this
torch.nn.Module. Otherwise, the provided
hook will be fired after all existing backward hooks on
this torch.nn.Module. Note that global
backward hooks registered with
register_module_full_backward_hook() will fire before
all hooks registered by this method.
Returns:
torch.utils.hooks.RemovableHandle:
a handle that can be used to remove the added hook by calling
handle.remove()
The grad_output is a tuple. The hook should
not modify its arguments, but it can optionally return a new gradient with
respect to the output that will be used in place of grad_output in
subsequent computations. Entries in grad_output will be None for
all non-Tensor arguments.
For technical reasons, when this hook is applied to a Module, its forward function will
receive a view of each Tensor passed to the Module. Similarly the caller will receive a view
of each Tensor returned by the Module’s forward function.
Warning
Modifying inputs inplace is not allowed when using backward hooks and
will raise an error.
Args:
hook (Callable): The user-defined hook to be registered.
prepend (bool): If true, the provided hook will be fired before
all existing backward_pre hooks on this
torch.nn.Module. Otherwise, the provided
hook will be fired after all existing backward_pre hooks
on this torch.nn.Module. Note that global
backward_pre hooks registered with
register_module_full_backward_pre_hook() will fire before
all hooks registered by this method.
Returns:
torch.utils.hooks.RemovableHandle:
a handle that can be used to remove the added hook by calling
handle.remove()
Register a post-hook to be run after module’s load_state_dict() is called.
It should have the following signature::
hook(module, incompatible_keys) -> None
The module argument is the current module that this hook is registered
on, and the incompatible_keys argument is a NamedTuple consisting
of attributes missing_keys and unexpected_keys. missing_keys
is a list of str containing the missing keys and
unexpected_keys is a list of str containing the unexpected keys.
The given incompatible_keys can be modified inplace if needed.
Note that the checks performed when calling load_state_dict() with
strict=True are affected by modifications the hook makes to
missing_keys or unexpected_keys, as expected. Additions to either
set of keys will result in an error being thrown when strict=True, and
clearing out both missing and unexpected keys will avoid an error.
Returns:
torch.utils.hooks.RemovableHandle:
a handle that can be used to remove the added hook by calling
handle.remove()
Set extra state contained in the loaded state_dict.
This function is called from load_state_dict() to handle any extra state
found within the state_dict. Implement this function and a corresponding
get_extra_state() for your module if you need to store extra state within its
state_dict.
Set the submodule given by target if it exists, otherwise throw an error.
Note
If strict is set to False (default), the method will replace an existing submodule
or create a new submodule if the parent module exists. If strict is set to True,
the method will only attempt to replace an existing submodule and throw an error if
the submodule does not exist.
For example, let’s say you have an nn.ModuleA that
looks like this:
(The diagram shows an nn.ModuleA. A has a nested
submodule net_b, which itself has two submodules net_c
and linear. net_c then has a submodule conv.)
To override the Conv2d with a new submodule Linear, you
could call set_submodule("net_b.net_c.conv",nn.Linear(1,1))
where strict could be True or False
To add a new submodule Conv2d to the existing net_b module,
you would call set_submodule("net_b.conv",nn.Conv2d(1,1,1)).
In the above if you set strict=True and call
set_submodule("net_b.conv",nn.Conv2d(1,1,1),strict=True), an AttributeError
will be raised because net_b does not have a submodule named conv.
Args:
target: The fully-qualified string name of the submodule
to look for. (See above example for how to specify a
fully-qualified string.)
module: The module to set the submodule to.
strict: If False, the method will replace an existing submodule
or create a new submodule if the parent module exists. If True,
the method will only attempt to replace an existing submodule and throw an error
if the submodule doesn’t already exist.
Raises:
ValueError: If the target string is empty or if module is not an instance of nn.Module.
AttributeError: If at any point along the path resulting from
the target string the (sub)path resolves to a non-existent
attribute name or an object that is not an instance of nn.Module.
Return a dictionary containing references to the whole state of the module.
Both parameters and persistent buffers (e.g. running averages) are
included. Keys are corresponding parameter and buffer names.
Parameters and buffers set to None are not included.
Note
The returned object is a shallow copy. It contains references
to the module’s parameters and buffers.
Warning
Currently state_dict() also accepts positional arguments for
destination, prefix and keep_vars in order. However,
this is being deprecated and keyword arguments will be enforced in
future releases.
Warning
Please avoid the use of argument destination as it is not
designed for end-users.
Args:
destination (dict, optional): If provided, the state of module will
be updated into the dict and the same object is returned.
Otherwise, an OrderedDict will be created and returned.
Default: None.
prefix (str, optional): a prefix added to parameter and buffer
names to compose the keys in state_dict. Default: ''.
keep_vars (bool, optional): by default the Tensor s
returned in the state dict are detached from autograd. If it’s
set to True, detaching will not be performed.
Default: False.
Returns:
dict:
a dictionary containing a whole state of the module
Its signature is similar to torch.Tensor.to(), but only accepts
floating point or complex dtypes. In addition, this method will
only cast the floating point or complex parameters and buffers to dtype
(if given). The integral parameters and buffers will be moved
device, if that is given, but with dtypes unchanged. When
non_blocking is set, it tries to convert/move asynchronously
with respect to the host if possible, e.g., moving CPU Tensors with
pinned memory to CUDA devices.
See below for examples.
Note
This method modifies the module in-place.
Args:
device (torch.device): the desired device of the parameters
and buffers in this module
dtype (torch.dtype): the desired floating point or complex dtype of
the parameters and buffers in this module
tensor (torch.Tensor): Tensor whose dtype and device are the desired
dtype and device for all parameters and buffers in this module
This has an effect only on certain modules. See the documentation of
particular modules for details of their behaviors in training/evaluation
mode, i.e., whether they are affected, e.g. Dropout, BatchNorm,
etc.
Args:
mode (bool): whether to set training mode (True) or evaluation
This also makes associated parameters and buffers different objects. So
it should be called before constructing optimizer if the module will
live on XPU while being optimized.
Note
This method modifies the module in-place.
Arguments:
device (int, optional): if specified, all parameters will be
\(\\tau_{attack} = 0.05\) s (50 ms, fast response to increases)
\(\\tau_{release} = 0.20\) s (200 ms, slow response to decreases)
\(\\Delta t = 1 / f_{frame}\) is the frame period (inverse of frame rate)
\(\\text{LTL}[n]\) is the Long-Term Loudness (sone)
This asymmetric integration models the auditory system’s fast adaptation to
loudness increases and slow adaptation to decreases, preventing abrupt loudness
drops in time-varying signals.
type fs:
int, optional
param fs:
Sampling rate in Hz. Default: 32000
Used to estimate frame rate if not provided to forward()
type fs:
int, optional
type learnable:
bool, optional
param learnable:
If True, time constants τ_attack and τ_release become learnable parameters.
Default: False
Asymmetric temporal integration (attack vs release):
>>> # Create impulse: sudden increase then decrease>>> impulse=torch.zeros(1,100,150)>>> impulse[:,20:30,:]=10.0# 10-frame pulse>>>>>> integration.reset_state()# Clear state>>> ltl_impulse,stl_impulse=integration(impulse,return_stl=True)>>>>>> # STL shows immediate jump at frame 20>>> print(f"STL at frame 19-21: {stl_impulse[0,19:22].tolist()}")STL at frame 19-21: [0.0, 1500.0, 1500.0]>>>>>> # LTL rises fast (attack) but falls slowly (release)>>> print(f"LTL at frame 19-21: {ltl_impulse[0,19:22]:.2f} (fast rise)")LTL at frame 19-21: [0.0, 350.45, 750.23] (fast rise)>>> print(f"LTL at frame 29-32: {ltl_impulse[0,29:33]:.2f} (slow fall)")LTL at frame 29-32: [1450.12, 1398.34, 1350.67, 1305.23] (slow fall)
Reset state between non-continuous signals:
>>> # First signal>>> N1=torch.randn(1,50,150).abs()*5>>> ltl1=integration(N1)>>> print(f"LTL1 final state: {integration.ltl_state[0]:.2f}")LTL1 final state: 235.67>>>>>> # Reset before processing second signal>>> integration.reset_state()>>> N2=torch.randn(1,50,150).abs()*5>>> ltl2=integration(N2)>>> print(f"LTL2 starts from: {ltl2[0,0]:.2f} (should be small)")LTL2 starts from: 8.45 (should be small)
Learnable time constants for model adaptation:
>>> integration_learn=LoudnessIntegration(fs=32000,learnable=True)>>> optimizer=torch.optim.Adam(integration_learn.parameters(),lr=1e-3)>>> # Can train τ_attack and τ_release with backpropagation
This also makes associated parameters and buffers different objects. So
it should be called before constructing the optimizer if the module will
live on GPU while being optimized.
Note
This method modifies the module in-place.
Args:
device (int, optional): if specified, all parameters will be
This has an effect only on certain modules. See the documentation of
particular modules for details of their behaviors in training/evaluation
mode, i.e. whether they are affected, e.g. Dropout, BatchNorm,
etc.
Return any extra state to include in the module’s state_dict.
Implement this and a corresponding set_extra_state() for your module
if you need to store extra state. This function is called when building the
module’s state_dict().
Note that extra state should be picklable to ensure working serialization
of the state_dict. We only provide backwards compatibility guarantees
for serializing Tensors; other objects may break backwards compatibility if
their serialized pickled form changes.
(The diagram shows an nn.ModuleA. A which has a nested
submodule net_b, which itself has two submodules net_c
and linear. net_c then has a submodule conv.)
To check whether or not we have the linear submodule, we
would call get_submodule("net_b.linear"). To check whether
we have the conv submodule, we would call
get_submodule("net_b.net_c.conv").
The runtime of get_submodule is bounded by the degree
of module nesting in target. A query against
named_modules achieves the same result, but it is O(N) in
the number of transitive modules. So, for a simple check to see
if some submodule exists, get_submodule should always be
used.
Args:
target: The fully-qualified string name of the submodule
to look for. (See above example for how to specify a
fully-qualified string.)
Returns:
torch.nn.Module: The submodule referenced by target
Raises:
AttributeError: If at any point along the path resulting from
the target string the (sub)path resolves to a non-existent
attribute name or an object that is not an instance of nn.Module.
This also makes associated parameters and buffers different objects. So
it should be called before constructing the optimizer if the module will
live on IPU while being optimized.
Note
This method modifies the module in-place.
Arguments:
device (int, optional): if specified, all parameters will be
state_dict (dict): a dict containing parameters and
persistent buffers.
strict (bool, optional): whether to strictly enforce that the keys
in state_dict match the keys returned by this module’s
state_dict() function. Default: True
assign (bool, optional): When set to False, the properties of the tensors
in the current module are preserved whereas setting it to True preserves
properties of the Tensors in the state dict. The only
exception is the requires_grad field of Parameter
for which the value from the module is preserved. Default: False
Returns:
NamedTuple with missing_keys and unexpected_keys fields:
missing_keys is a list of str containing any keys that are expected
by this module but missing from the provided state_dict.
unexpected_keys is a list of str containing the keys that are not
expected by this module but present in the provided state_dict.
Note:
If a parameter or buffer is registered as None and its corresponding key
exists in state_dict, load_state_dict() will raise a
RuntimeError.
Move all model parameters and buffers to the MTIA.
This also makes associated parameters and buffers different objects. So
it should be called before constructing the optimizer if the module will
live on MTIA while being optimized.
Note
This method modifies the module in-place.
Arguments:
device (int, optional): if specified, all parameters will be
Return an iterator over all modules in the network, yielding both the name of the module as well as the module itself.
Args:
memo: a memo to store the set of modules already added to the result
prefix: a prefix that will be added to the name of the module
remove_duplicate: whether to remove the duplicated module instances in the result
or not
Yields:
(str, Module): Tuple of name and module
Note:
Duplicate modules are returned only once. In the following
example, l will be returned only once.
This is typically used to register a buffer that should not be
considered a model parameter. For example, BatchNorm’s running_mean
is not a parameter, but is part of the module’s state. Buffers, by
default, are persistent and will be saved alongside parameters. This
behavior can be changed by setting persistent to False. The
only difference between a persistent buffer and a non-persistent buffer
is that the latter will not be a part of this module’s
state_dict.
Buffers can be accessed as attributes using given names.
Args:
name (str): name of the buffer. The buffer can be accessed
from this module using the given name
tensor (Tensor or None): buffer to be registered. If None, then operations
that run on buffers, such as cuda, are ignored. If None,
the buffer is not included in the module’s state_dict.
persistent (bool): whether the buffer is part of this module’s
The hook will be called every time after forward() has computed an output.
If with_kwargs is False or not specified, the input contains only
the positional arguments given to the module. Keyword arguments won’t be
passed to the hooks and only to the forward. The hook can modify the
output. It can modify the input inplace but it will not have effect on
forward since this is called after forward() is called. The hook
should have the following signature:
hook(module,args,output)->Noneormodifiedoutput
If with_kwargs is True, the forward hook will be passed the
kwargs given to the forward function and be expected to return the
output possibly modified. The hook should have the following signature:
hook (Callable): The user defined hook to be registered.
prepend (bool): If True, the provided hook will be fired
before all existing forward hooks on this
torch.nn.Module. Otherwise, the provided
hook will be fired after all existing forward hooks on
this torch.nn.Module. Note that global
forward hooks registered with
register_module_forward_hook() will fire before all hooks
registered by this method.
Default: False
with_kwargs (bool): If True, the hook will be passed the
kwargs given to the forward function.
Default: False
always_call (bool): If True the hook will be run regardless of
whether an exception is raised while calling the Module.
Default: False
Returns:
torch.utils.hooks.RemovableHandle:
a handle that can be used to remove the added hook by calling
handle.remove()
The hook will be called every time before forward() is invoked.
If with_kwargs is false or not specified, the input contains only
the positional arguments given to the module. Keyword arguments won’t be
passed to the hooks and only to the forward. The hook can modify the
input. User can either return a tuple or a single modified value in the
hook. We will wrap the value into a tuple if a single value is returned
(unless that value is already a tuple). The hook should have the
following signature:
hook(module,args)->Noneormodifiedinput
If with_kwargs is true, the forward pre-hook will be passed the
kwargs given to the forward function. And if the hook modifies the
input, both the args and kwargs should be returned. The hook should have
the following signature:
hook (Callable): The user defined hook to be registered.
prepend (bool): If true, the provided hook will be fired before
all existing forward_pre hooks on this
torch.nn.Module. Otherwise, the provided
hook will be fired after all existing forward_pre hooks
on this torch.nn.Module. Note that global
forward_pre hooks registered with
register_module_forward_pre_hook() will fire before all
hooks registered by this method.
Default: False
with_kwargs (bool): If true, the hook will be passed the kwargs
given to the forward function.
Default: False
Returns:
torch.utils.hooks.RemovableHandle:
a handle that can be used to remove the added hook by calling
handle.remove()
The grad_input and grad_output are tuples that contain the gradients
with respect to the inputs and outputs respectively. The hook should
not modify its arguments, but it can optionally return a new gradient with
respect to the input that will be used in place of grad_input in
subsequent computations. grad_input will only correspond to the inputs given
as positional arguments and all kwarg arguments are ignored. Entries
in grad_input and grad_output will be None for all non-Tensor
arguments.
For technical reasons, when this hook is applied to a Module, its forward function will
receive a view of each Tensor passed to the Module. Similarly the caller will receive a view
of each Tensor returned by the Module’s forward function.
Warning
Modifying inputs or outputs inplace is not allowed when using backward hooks and
will raise an error.
Args:
hook (Callable): The user-defined hook to be registered.
prepend (bool): If true, the provided hook will be fired before
all existing backward hooks on this
torch.nn.Module. Otherwise, the provided
hook will be fired after all existing backward hooks on
this torch.nn.Module. Note that global
backward hooks registered with
register_module_full_backward_hook() will fire before
all hooks registered by this method.
Returns:
torch.utils.hooks.RemovableHandle:
a handle that can be used to remove the added hook by calling
handle.remove()
The grad_output is a tuple. The hook should
not modify its arguments, but it can optionally return a new gradient with
respect to the output that will be used in place of grad_output in
subsequent computations. Entries in grad_output will be None for
all non-Tensor arguments.
For technical reasons, when this hook is applied to a Module, its forward function will
receive a view of each Tensor passed to the Module. Similarly the caller will receive a view
of each Tensor returned by the Module’s forward function.
Warning
Modifying inputs inplace is not allowed when using backward hooks and
will raise an error.
Args:
hook (Callable): The user-defined hook to be registered.
prepend (bool): If true, the provided hook will be fired before
all existing backward_pre hooks on this
torch.nn.Module. Otherwise, the provided
hook will be fired after all existing backward_pre hooks
on this torch.nn.Module. Note that global
backward_pre hooks registered with
register_module_full_backward_pre_hook() will fire before
all hooks registered by this method.
Returns:
torch.utils.hooks.RemovableHandle:
a handle that can be used to remove the added hook by calling
handle.remove()
Register a post-hook to be run after module’s load_state_dict() is called.
It should have the following signature::
hook(module, incompatible_keys) -> None
The module argument is the current module that this hook is registered
on, and the incompatible_keys argument is a NamedTuple consisting
of attributes missing_keys and unexpected_keys. missing_keys
is a list of str containing the missing keys and
unexpected_keys is a list of str containing the unexpected keys.
The given incompatible_keys can be modified inplace if needed.
Note that the checks performed when calling load_state_dict() with
strict=True are affected by modifications the hook makes to
missing_keys or unexpected_keys, as expected. Additions to either
set of keys will result in an error being thrown when strict=True, and
clearing out both missing and unexpected keys will avoid an error.
Returns:
torch.utils.hooks.RemovableHandle:
a handle that can be used to remove the added hook by calling
handle.remove()
Set extra state contained in the loaded state_dict.
This function is called from load_state_dict() to handle any extra state
found within the state_dict. Implement this function and a corresponding
get_extra_state() for your module if you need to store extra state within its
state_dict.
Set the submodule given by target if it exists, otherwise throw an error.
Note
If strict is set to False (default), the method will replace an existing submodule
or create a new submodule if the parent module exists. If strict is set to True,
the method will only attempt to replace an existing submodule and throw an error if
the submodule does not exist.
For example, let’s say you have an nn.ModuleA that
looks like this:
(The diagram shows an nn.ModuleA. A has a nested
submodule net_b, which itself has two submodules net_c
and linear. net_c then has a submodule conv.)
To override the Conv2d with a new submodule Linear, you
could call set_submodule("net_b.net_c.conv",nn.Linear(1,1))
where strict could be True or False
To add a new submodule Conv2d to the existing net_b module,
you would call set_submodule("net_b.conv",nn.Conv2d(1,1,1)).
In the above if you set strict=True and call
set_submodule("net_b.conv",nn.Conv2d(1,1,1),strict=True), an AttributeError
will be raised because net_b does not have a submodule named conv.
Args:
target: The fully-qualified string name of the submodule
to look for. (See above example for how to specify a
fully-qualified string.)
module: The module to set the submodule to.
strict: If False, the method will replace an existing submodule
or create a new submodule if the parent module exists. If True,
the method will only attempt to replace an existing submodule and throw an error
if the submodule doesn’t already exist.
Raises:
ValueError: If the target string is empty or if module is not an instance of nn.Module.
AttributeError: If at any point along the path resulting from
the target string the (sub)path resolves to a non-existent
attribute name or an object that is not an instance of nn.Module.
Return a dictionary containing references to the whole state of the module.
Both parameters and persistent buffers (e.g. running averages) are
included. Keys are corresponding parameter and buffer names.
Parameters and buffers set to None are not included.
Note
The returned object is a shallow copy. It contains references
to the module’s parameters and buffers.
Warning
Currently state_dict() also accepts positional arguments for
destination, prefix and keep_vars in order. However,
this is being deprecated and keyword arguments will be enforced in
future releases.
Warning
Please avoid the use of argument destination as it is not
designed for end-users.
Args:
destination (dict, optional): If provided, the state of module will
be updated into the dict and the same object is returned.
Otherwise, an OrderedDict will be created and returned.
Default: None.
prefix (str, optional): a prefix added to parameter and buffer
names to compose the keys in state_dict. Default: ''.
keep_vars (bool, optional): by default the Tensor s
returned in the state dict are detached from autograd. If it’s
set to True, detaching will not be performed.
Default: False.
Returns:
dict:
a dictionary containing a whole state of the module
Its signature is similar to torch.Tensor.to(), but only accepts
floating point or complex dtypes. In addition, this method will
only cast the floating point or complex parameters and buffers to dtype
(if given). The integral parameters and buffers will be moved
device, if that is given, but with dtypes unchanged. When
non_blocking is set, it tries to convert/move asynchronously
with respect to the host if possible, e.g., moving CPU Tensors with
pinned memory to CUDA devices.
See below for examples.
Note
This method modifies the module in-place.
Args:
device (torch.device): the desired device of the parameters
and buffers in this module
dtype (torch.dtype): the desired floating point or complex dtype of
the parameters and buffers in this module
tensor (torch.Tensor): Tensor whose dtype and device are the desired
dtype and device for all parameters and buffers in this module
This has an effect only on certain modules. See the documentation of
particular modules for details of their behaviors in training/evaluation
mode, i.e., whether they are affected, e.g. Dropout, BatchNorm,
etc.
Args:
mode (bool): whether to set training mode (True) or evaluation
This also makes associated parameters and buffers different objects. So
it should be called before constructing optimizer if the module will
live on XPU while being optimized.
Note
This method modifies the module in-place.
Arguments:
device (int, optional): if specified, all parameters will be
Automatic Gain Control (AGC) for temporal smoothing in Moore et al. (2016) model.
Implements asymmetric first-order IIR filtering with different attack and release
coefficients, following the AGC mechanism in Moore et al. (2016) and ANSI S3.4-2007.
This module provides temporal smoothing that models the auditory system’s integration
time with different responses to signal increases (attack) and decreases (release).
The AGC is applied frame-by-frame to maintain causality
Attack/release selection is element-wise (per channel or per batch element)
State is updated at each frame and carried to the next
Alpha coefficients interpretation:
* α = 0: No filtering (output = input, instantaneous)
* α = 0.5: Medium smoothing (half-weight to previous state)
* α = 1: Infinite hold (output = previous state, no update)
Short-term AGC (α_attack=0.045, α_release=0.033):
* Fast attack: ~22 frames to 63% (1-e^-1), ~100 frames to 99%
* Fast release: ~30 frames to 63%, ~138 frames to 99%
Long-term AGC (α_attack=0.01, α_release=0.00133):
* Slow attack: ~100 frames to 63%, ~460 frames to 99%
* Very slow release: ~752 frames to 63%, ~3460 frames to 99%
>>> # First chunk>>> chunk1=torch.randn(50,150).abs()*5>>> out1=stl_agc(chunk1)>>> final_state=out1[-1,:]# Last frame as state>>>>>> # Second chunk with initial state>>> chunk2=torch.randn(50,150).abs()*5>>> out2=stl_agc(chunk2,state=final_state)>>> print(f"Continuous processing: out2 starts from state={final_state.mean():.2f}")Continuous processing: out2 starts from state=3.45
Learnable coefficients for model adaptation:
>>> agc_learn=Moore2016AGC(attack_alpha=0.045,release_alpha=0.033,learnable=True)>>> optimizer=torch.optim.Adam(agc_learn.parameters(),lr=1e-3)>>> # Can train α_attack and α_release with backpropagation
This also makes associated parameters and buffers different objects. So
it should be called before constructing the optimizer if the module will
live on GPU while being optimized.
Note
This method modifies the module in-place.
Args:
device (int, optional): if specified, all parameters will be
This has an effect only on certain modules. See the documentation of
particular modules for details of their behaviors in training/evaluation
mode, i.e. whether they are affected, e.g. Dropout, BatchNorm,
etc.
Return any extra state to include in the module’s state_dict.
Implement this and a corresponding set_extra_state() for your module
if you need to store extra state. This function is called when building the
module’s state_dict().
Note that extra state should be picklable to ensure working serialization
of the state_dict. We only provide backwards compatibility guarantees
for serializing Tensors; other objects may break backwards compatibility if
their serialized pickled form changes.
(The diagram shows an nn.ModuleA. A which has a nested
submodule net_b, which itself has two submodules net_c
and linear. net_c then has a submodule conv.)
To check whether or not we have the linear submodule, we
would call get_submodule("net_b.linear"). To check whether
we have the conv submodule, we would call
get_submodule("net_b.net_c.conv").
The runtime of get_submodule is bounded by the degree
of module nesting in target. A query against
named_modules achieves the same result, but it is O(N) in
the number of transitive modules. So, for a simple check to see
if some submodule exists, get_submodule should always be
used.
Args:
target: The fully-qualified string name of the submodule
to look for. (See above example for how to specify a
fully-qualified string.)
Returns:
torch.nn.Module: The submodule referenced by target
Raises:
AttributeError: If at any point along the path resulting from
the target string the (sub)path resolves to a non-existent
attribute name or an object that is not an instance of nn.Module.
This also makes associated parameters and buffers different objects. So
it should be called before constructing the optimizer if the module will
live on IPU while being optimized.
Note
This method modifies the module in-place.
Arguments:
device (int, optional): if specified, all parameters will be
state_dict (dict): a dict containing parameters and
persistent buffers.
strict (bool, optional): whether to strictly enforce that the keys
in state_dict match the keys returned by this module’s
state_dict() function. Default: True
assign (bool, optional): When set to False, the properties of the tensors
in the current module are preserved whereas setting it to True preserves
properties of the Tensors in the state dict. The only
exception is the requires_grad field of Parameter
for which the value from the module is preserved. Default: False
Returns:
NamedTuple with missing_keys and unexpected_keys fields:
missing_keys is a list of str containing any keys that are expected
by this module but missing from the provided state_dict.
unexpected_keys is a list of str containing the keys that are not
expected by this module but present in the provided state_dict.
Note:
If a parameter or buffer is registered as None and its corresponding key
exists in state_dict, load_state_dict() will raise a
RuntimeError.
Move all model parameters and buffers to the MTIA.
This also makes associated parameters and buffers different objects. So
it should be called before constructing the optimizer if the module will
live on MTIA while being optimized.
Note
This method modifies the module in-place.
Arguments:
device (int, optional): if specified, all parameters will be
Return an iterator over all modules in the network, yielding both the name of the module as well as the module itself.
Args:
memo: a memo to store the set of modules already added to the result
prefix: a prefix that will be added to the name of the module
remove_duplicate: whether to remove the duplicated module instances in the result
or not
Yields:
(str, Module): Tuple of name and module
Note:
Duplicate modules are returned only once. In the following
example, l will be returned only once.
This is typically used to register a buffer that should not be
considered a model parameter. For example, BatchNorm’s running_mean
is not a parameter, but is part of the module’s state. Buffers, by
default, are persistent and will be saved alongside parameters. This
behavior can be changed by setting persistent to False. The
only difference between a persistent buffer and a non-persistent buffer
is that the latter will not be a part of this module’s
state_dict.
Buffers can be accessed as attributes using given names.
Args:
name (str): name of the buffer. The buffer can be accessed
from this module using the given name
tensor (Tensor or None): buffer to be registered. If None, then operations
that run on buffers, such as cuda, are ignored. If None,
the buffer is not included in the module’s state_dict.
persistent (bool): whether the buffer is part of this module’s
The hook will be called every time after forward() has computed an output.
If with_kwargs is False or not specified, the input contains only
the positional arguments given to the module. Keyword arguments won’t be
passed to the hooks and only to the forward. The hook can modify the
output. It can modify the input inplace but it will not have effect on
forward since this is called after forward() is called. The hook
should have the following signature:
hook(module,args,output)->Noneormodifiedoutput
If with_kwargs is True, the forward hook will be passed the
kwargs given to the forward function and be expected to return the
output possibly modified. The hook should have the following signature:
hook (Callable): The user defined hook to be registered.
prepend (bool): If True, the provided hook will be fired
before all existing forward hooks on this
torch.nn.Module. Otherwise, the provided
hook will be fired after all existing forward hooks on
this torch.nn.Module. Note that global
forward hooks registered with
register_module_forward_hook() will fire before all hooks
registered by this method.
Default: False
with_kwargs (bool): If True, the hook will be passed the
kwargs given to the forward function.
Default: False
always_call (bool): If True the hook will be run regardless of
whether an exception is raised while calling the Module.
Default: False
Returns:
torch.utils.hooks.RemovableHandle:
a handle that can be used to remove the added hook by calling
handle.remove()
The hook will be called every time before forward() is invoked.
If with_kwargs is false or not specified, the input contains only
the positional arguments given to the module. Keyword arguments won’t be
passed to the hooks and only to the forward. The hook can modify the
input. User can either return a tuple or a single modified value in the
hook. We will wrap the value into a tuple if a single value is returned
(unless that value is already a tuple). The hook should have the
following signature:
hook(module,args)->Noneormodifiedinput
If with_kwargs is true, the forward pre-hook will be passed the
kwargs given to the forward function. And if the hook modifies the
input, both the args and kwargs should be returned. The hook should have
the following signature:
hook (Callable): The user defined hook to be registered.
prepend (bool): If true, the provided hook will be fired before
all existing forward_pre hooks on this
torch.nn.Module. Otherwise, the provided
hook will be fired after all existing forward_pre hooks
on this torch.nn.Module. Note that global
forward_pre hooks registered with
register_module_forward_pre_hook() will fire before all
hooks registered by this method.
Default: False
with_kwargs (bool): If true, the hook will be passed the kwargs
given to the forward function.
Default: False
Returns:
torch.utils.hooks.RemovableHandle:
a handle that can be used to remove the added hook by calling
handle.remove()
The grad_input and grad_output are tuples that contain the gradients
with respect to the inputs and outputs respectively. The hook should
not modify its arguments, but it can optionally return a new gradient with
respect to the input that will be used in place of grad_input in
subsequent computations. grad_input will only correspond to the inputs given
as positional arguments and all kwarg arguments are ignored. Entries
in grad_input and grad_output will be None for all non-Tensor
arguments.
For technical reasons, when this hook is applied to a Module, its forward function will
receive a view of each Tensor passed to the Module. Similarly the caller will receive a view
of each Tensor returned by the Module’s forward function.
Warning
Modifying inputs or outputs inplace is not allowed when using backward hooks and
will raise an error.
Args:
hook (Callable): The user-defined hook to be registered.
prepend (bool): If true, the provided hook will be fired before
all existing backward hooks on this
torch.nn.Module. Otherwise, the provided
hook will be fired after all existing backward hooks on
this torch.nn.Module. Note that global
backward hooks registered with
register_module_full_backward_hook() will fire before
all hooks registered by this method.
Returns:
torch.utils.hooks.RemovableHandle:
a handle that can be used to remove the added hook by calling
handle.remove()
The grad_output is a tuple. The hook should
not modify its arguments, but it can optionally return a new gradient with
respect to the output that will be used in place of grad_output in
subsequent computations. Entries in grad_output will be None for
all non-Tensor arguments.
For technical reasons, when this hook is applied to a Module, its forward function will
receive a view of each Tensor passed to the Module. Similarly the caller will receive a view
of each Tensor returned by the Module’s forward function.
Warning
Modifying inputs inplace is not allowed when using backward hooks and
will raise an error.
Args:
hook (Callable): The user-defined hook to be registered.
prepend (bool): If true, the provided hook will be fired before
all existing backward_pre hooks on this
torch.nn.Module. Otherwise, the provided
hook will be fired after all existing backward_pre hooks
on this torch.nn.Module. Note that global
backward_pre hooks registered with
register_module_full_backward_pre_hook() will fire before
all hooks registered by this method.
Returns:
torch.utils.hooks.RemovableHandle:
a handle that can be used to remove the added hook by calling
handle.remove()
Register a post-hook to be run after module’s load_state_dict() is called.
It should have the following signature::
hook(module, incompatible_keys) -> None
The module argument is the current module that this hook is registered
on, and the incompatible_keys argument is a NamedTuple consisting
of attributes missing_keys and unexpected_keys. missing_keys
is a list of str containing the missing keys and
unexpected_keys is a list of str containing the unexpected keys.
The given incompatible_keys can be modified inplace if needed.
Note that the checks performed when calling load_state_dict() with
strict=True are affected by modifications the hook makes to
missing_keys or unexpected_keys, as expected. Additions to either
set of keys will result in an error being thrown when strict=True, and
clearing out both missing and unexpected keys will avoid an error.
Returns:
torch.utils.hooks.RemovableHandle:
a handle that can be used to remove the added hook by calling
handle.remove()
Set extra state contained in the loaded state_dict.
This function is called from load_state_dict() to handle any extra state
found within the state_dict. Implement this function and a corresponding
get_extra_state() for your module if you need to store extra state within its
state_dict.
Set the submodule given by target if it exists, otherwise throw an error.
Note
If strict is set to False (default), the method will replace an existing submodule
or create a new submodule if the parent module exists. If strict is set to True,
the method will only attempt to replace an existing submodule and throw an error if
the submodule does not exist.
For example, let’s say you have an nn.ModuleA that
looks like this:
(The diagram shows an nn.ModuleA. A has a nested
submodule net_b, which itself has two submodules net_c
and linear. net_c then has a submodule conv.)
To override the Conv2d with a new submodule Linear, you
could call set_submodule("net_b.net_c.conv",nn.Linear(1,1))
where strict could be True or False
To add a new submodule Conv2d to the existing net_b module,
you would call set_submodule("net_b.conv",nn.Conv2d(1,1,1)).
In the above if you set strict=True and call
set_submodule("net_b.conv",nn.Conv2d(1,1,1),strict=True), an AttributeError
will be raised because net_b does not have a submodule named conv.
Args:
target: The fully-qualified string name of the submodule
to look for. (See above example for how to specify a
fully-qualified string.)
module: The module to set the submodule to.
strict: If False, the method will replace an existing submodule
or create a new submodule if the parent module exists. If True,
the method will only attempt to replace an existing submodule and throw an error
if the submodule doesn’t already exist.
Raises:
ValueError: If the target string is empty or if module is not an instance of nn.Module.
AttributeError: If at any point along the path resulting from
the target string the (sub)path resolves to a non-existent
attribute name or an object that is not an instance of nn.Module.
Return a dictionary containing references to the whole state of the module.
Both parameters and persistent buffers (e.g. running averages) are
included. Keys are corresponding parameter and buffer names.
Parameters and buffers set to None are not included.
Note
The returned object is a shallow copy. It contains references
to the module’s parameters and buffers.
Warning
Currently state_dict() also accepts positional arguments for
destination, prefix and keep_vars in order. However,
this is being deprecated and keyword arguments will be enforced in
future releases.
Warning
Please avoid the use of argument destination as it is not
designed for end-users.
Args:
destination (dict, optional): If provided, the state of module will
be updated into the dict and the same object is returned.
Otherwise, an OrderedDict will be created and returned.
Default: None.
prefix (str, optional): a prefix added to parameter and buffer
names to compose the keys in state_dict. Default: ''.
keep_vars (bool, optional): by default the Tensor s
returned in the state dict are detached from autograd. If it’s
set to True, detaching will not be performed.
Default: False.
Returns:
dict:
a dictionary containing a whole state of the module
Its signature is similar to torch.Tensor.to(), but only accepts
floating point or complex dtypes. In addition, this method will
only cast the floating point or complex parameters and buffers to dtype
(if given). The integral parameters and buffers will be moved
device, if that is given, but with dtypes unchanged. When
non_blocking is set, it tries to convert/move asynchronously
with respect to the host if possible, e.g., moving CPU Tensors with
pinned memory to CUDA devices.
See below for examples.
Note
This method modifies the module in-place.
Args:
device (torch.device): the desired device of the parameters
and buffers in this module
dtype (torch.dtype): the desired floating point or complex dtype of
the parameters and buffers in this module
tensor (torch.Tensor): Tensor whose dtype and device are the desired
dtype and device for all parameters and buffers in this module
This has an effect only on certain modules. See the documentation of
particular modules for details of their behaviors in training/evaluation
mode, i.e., whether they are affected, e.g. Dropout, BatchNorm,
etc.
Args:
mode (bool): whether to set training mode (True) or evaluation
This also makes associated parameters and buffers different objects. So
it should be called before constructing optimizer if the module will
live on XPU while being optimized.
Note
This method modifies the module in-place.
Arguments:
device (int, optional): if specified, all parameters will be
Complete two-stage temporal integration for Moore et al. (2016) binaural loudness model.
Implements the complete temporal processing pipeline with two AGC stages followed by
frequency integration, transforming instantaneous specific loudness into long-term
loudness. This models the auditory system’s temporal integration at multiple time scales.
>>> temporal_learn=Moore2016TemporalIntegration(learnable=True)>>> # Can train all 4 alpha coefficients with backpropagation>>> optimizer=torch.optim.Adam(temporal_learn.parameters(),lr=1e-4)
This also makes associated parameters and buffers different objects. So
it should be called before constructing the optimizer if the module will
live on GPU while being optimized.
Note
This method modifies the module in-place.
Args:
device (int, optional): if specified, all parameters will be
This has an effect only on certain modules. See the documentation of
particular modules for details of their behaviors in training/evaluation
mode, i.e. whether they are affected, e.g. Dropout, BatchNorm,
etc.
Return any extra state to include in the module’s state_dict.
Implement this and a corresponding set_extra_state() for your module
if you need to store extra state. This function is called when building the
module’s state_dict().
Note that extra state should be picklable to ensure working serialization
of the state_dict. We only provide backwards compatibility guarantees
for serializing Tensors; other objects may break backwards compatibility if
their serialized pickled form changes.
(The diagram shows an nn.ModuleA. A which has a nested
submodule net_b, which itself has two submodules net_c
and linear. net_c then has a submodule conv.)
To check whether or not we have the linear submodule, we
would call get_submodule("net_b.linear"). To check whether
we have the conv submodule, we would call
get_submodule("net_b.net_c.conv").
The runtime of get_submodule is bounded by the degree
of module nesting in target. A query against
named_modules achieves the same result, but it is O(N) in
the number of transitive modules. So, for a simple check to see
if some submodule exists, get_submodule should always be
used.
Args:
target: The fully-qualified string name of the submodule
to look for. (See above example for how to specify a
fully-qualified string.)
Returns:
torch.nn.Module: The submodule referenced by target
Raises:
AttributeError: If at any point along the path resulting from
the target string the (sub)path resolves to a non-existent
attribute name or an object that is not an instance of nn.Module.
This also makes associated parameters and buffers different objects. So
it should be called before constructing the optimizer if the module will
live on IPU while being optimized.
Note
This method modifies the module in-place.
Arguments:
device (int, optional): if specified, all parameters will be
state_dict (dict): a dict containing parameters and
persistent buffers.
strict (bool, optional): whether to strictly enforce that the keys
in state_dict match the keys returned by this module’s
state_dict() function. Default: True
assign (bool, optional): When set to False, the properties of the tensors
in the current module are preserved whereas setting it to True preserves
properties of the Tensors in the state dict. The only
exception is the requires_grad field of Parameter
for which the value from the module is preserved. Default: False
Returns:
NamedTuple with missing_keys and unexpected_keys fields:
missing_keys is a list of str containing any keys that are expected
by this module but missing from the provided state_dict.
unexpected_keys is a list of str containing the keys that are not
expected by this module but present in the provided state_dict.
Note:
If a parameter or buffer is registered as None and its corresponding key
exists in state_dict, load_state_dict() will raise a
RuntimeError.
Move all model parameters and buffers to the MTIA.
This also makes associated parameters and buffers different objects. So
it should be called before constructing the optimizer if the module will
live on MTIA while being optimized.
Note
This method modifies the module in-place.
Arguments:
device (int, optional): if specified, all parameters will be
Return an iterator over all modules in the network, yielding both the name of the module as well as the module itself.
Args:
memo: a memo to store the set of modules already added to the result
prefix: a prefix that will be added to the name of the module
remove_duplicate: whether to remove the duplicated module instances in the result
or not
Yields:
(str, Module): Tuple of name and module
Note:
Duplicate modules are returned only once. In the following
example, l will be returned only once.
This is typically used to register a buffer that should not be
considered a model parameter. For example, BatchNorm’s running_mean
is not a parameter, but is part of the module’s state. Buffers, by
default, are persistent and will be saved alongside parameters. This
behavior can be changed by setting persistent to False. The
only difference between a persistent buffer and a non-persistent buffer
is that the latter will not be a part of this module’s
state_dict.
Buffers can be accessed as attributes using given names.
Args:
name (str): name of the buffer. The buffer can be accessed
from this module using the given name
tensor (Tensor or None): buffer to be registered. If None, then operations
that run on buffers, such as cuda, are ignored. If None,
the buffer is not included in the module’s state_dict.
persistent (bool): whether the buffer is part of this module’s
The hook will be called every time after forward() has computed an output.
If with_kwargs is False or not specified, the input contains only
the positional arguments given to the module. Keyword arguments won’t be
passed to the hooks and only to the forward. The hook can modify the
output. It can modify the input inplace but it will not have effect on
forward since this is called after forward() is called. The hook
should have the following signature:
hook(module,args,output)->Noneormodifiedoutput
If with_kwargs is True, the forward hook will be passed the
kwargs given to the forward function and be expected to return the
output possibly modified. The hook should have the following signature:
hook (Callable): The user defined hook to be registered.
prepend (bool): If True, the provided hook will be fired
before all existing forward hooks on this
torch.nn.Module. Otherwise, the provided
hook will be fired after all existing forward hooks on
this torch.nn.Module. Note that global
forward hooks registered with
register_module_forward_hook() will fire before all hooks
registered by this method.
Default: False
with_kwargs (bool): If True, the hook will be passed the
kwargs given to the forward function.
Default: False
always_call (bool): If True the hook will be run regardless of
whether an exception is raised while calling the Module.
Default: False
Returns:
torch.utils.hooks.RemovableHandle:
a handle that can be used to remove the added hook by calling
handle.remove()
The hook will be called every time before forward() is invoked.
If with_kwargs is false or not specified, the input contains only
the positional arguments given to the module. Keyword arguments won’t be
passed to the hooks and only to the forward. The hook can modify the
input. User can either return a tuple or a single modified value in the
hook. We will wrap the value into a tuple if a single value is returned
(unless that value is already a tuple). The hook should have the
following signature:
hook(module,args)->Noneormodifiedinput
If with_kwargs is true, the forward pre-hook will be passed the
kwargs given to the forward function. And if the hook modifies the
input, both the args and kwargs should be returned. The hook should have
the following signature:
hook (Callable): The user defined hook to be registered.
prepend (bool): If true, the provided hook will be fired before
all existing forward_pre hooks on this
torch.nn.Module. Otherwise, the provided
hook will be fired after all existing forward_pre hooks
on this torch.nn.Module. Note that global
forward_pre hooks registered with
register_module_forward_pre_hook() will fire before all
hooks registered by this method.
Default: False
with_kwargs (bool): If true, the hook will be passed the kwargs
given to the forward function.
Default: False
Returns:
torch.utils.hooks.RemovableHandle:
a handle that can be used to remove the added hook by calling
handle.remove()
The grad_input and grad_output are tuples that contain the gradients
with respect to the inputs and outputs respectively. The hook should
not modify its arguments, but it can optionally return a new gradient with
respect to the input that will be used in place of grad_input in
subsequent computations. grad_input will only correspond to the inputs given
as positional arguments and all kwarg arguments are ignored. Entries
in grad_input and grad_output will be None for all non-Tensor
arguments.
For technical reasons, when this hook is applied to a Module, its forward function will
receive a view of each Tensor passed to the Module. Similarly the caller will receive a view
of each Tensor returned by the Module’s forward function.
Warning
Modifying inputs or outputs inplace is not allowed when using backward hooks and
will raise an error.
Args:
hook (Callable): The user-defined hook to be registered.
prepend (bool): If true, the provided hook will be fired before
all existing backward hooks on this
torch.nn.Module. Otherwise, the provided
hook will be fired after all existing backward hooks on
this torch.nn.Module. Note that global
backward hooks registered with
register_module_full_backward_hook() will fire before
all hooks registered by this method.
Returns:
torch.utils.hooks.RemovableHandle:
a handle that can be used to remove the added hook by calling
handle.remove()
The grad_output is a tuple. The hook should
not modify its arguments, but it can optionally return a new gradient with
respect to the output that will be used in place of grad_output in
subsequent computations. Entries in grad_output will be None for
all non-Tensor arguments.
For technical reasons, when this hook is applied to a Module, its forward function will
receive a view of each Tensor passed to the Module. Similarly the caller will receive a view
of each Tensor returned by the Module’s forward function.
Warning
Modifying inputs inplace is not allowed when using backward hooks and
will raise an error.
Args:
hook (Callable): The user-defined hook to be registered.
prepend (bool): If true, the provided hook will be fired before
all existing backward_pre hooks on this
torch.nn.Module. Otherwise, the provided
hook will be fired after all existing backward_pre hooks
on this torch.nn.Module. Note that global
backward_pre hooks registered with
register_module_full_backward_pre_hook() will fire before
all hooks registered by this method.
Returns:
torch.utils.hooks.RemovableHandle:
a handle that can be used to remove the added hook by calling
handle.remove()
Register a post-hook to be run after module’s load_state_dict() is called.
It should have the following signature::
hook(module, incompatible_keys) -> None
The module argument is the current module that this hook is registered
on, and the incompatible_keys argument is a NamedTuple consisting
of attributes missing_keys and unexpected_keys. missing_keys
is a list of str containing the missing keys and
unexpected_keys is a list of str containing the unexpected keys.
The given incompatible_keys can be modified inplace if needed.
Note that the checks performed when calling load_state_dict() with
strict=True are affected by modifications the hook makes to
missing_keys or unexpected_keys, as expected. Additions to either
set of keys will result in an error being thrown when strict=True, and
clearing out both missing and unexpected keys will avoid an error.
Returns:
torch.utils.hooks.RemovableHandle:
a handle that can be used to remove the added hook by calling
handle.remove()
Set extra state contained in the loaded state_dict.
This function is called from load_state_dict() to handle any extra state
found within the state_dict. Implement this function and a corresponding
get_extra_state() for your module if you need to store extra state within its
state_dict.
Set the submodule given by target if it exists, otherwise throw an error.
Note
If strict is set to False (default), the method will replace an existing submodule
or create a new submodule if the parent module exists. If strict is set to True,
the method will only attempt to replace an existing submodule and throw an error if
the submodule does not exist.
For example, let’s say you have an nn.ModuleA that
looks like this:
(The diagram shows an nn.ModuleA. A has a nested
submodule net_b, which itself has two submodules net_c
and linear. net_c then has a submodule conv.)
To override the Conv2d with a new submodule Linear, you
could call set_submodule("net_b.net_c.conv",nn.Linear(1,1))
where strict could be True or False
To add a new submodule Conv2d to the existing net_b module,
you would call set_submodule("net_b.conv",nn.Conv2d(1,1,1)).
In the above if you set strict=True and call
set_submodule("net_b.conv",nn.Conv2d(1,1,1),strict=True), an AttributeError
will be raised because net_b does not have a submodule named conv.
Args:
target: The fully-qualified string name of the submodule
to look for. (See above example for how to specify a
fully-qualified string.)
module: The module to set the submodule to.
strict: If False, the method will replace an existing submodule
or create a new submodule if the parent module exists. If True,
the method will only attempt to replace an existing submodule and throw an error
if the submodule doesn’t already exist.
Raises:
ValueError: If the target string is empty or if module is not an instance of nn.Module.
AttributeError: If at any point along the path resulting from
the target string the (sub)path resolves to a non-existent
attribute name or an object that is not an instance of nn.Module.
Return a dictionary containing references to the whole state of the module.
Both parameters and persistent buffers (e.g. running averages) are
included. Keys are corresponding parameter and buffer names.
Parameters and buffers set to None are not included.
Note
The returned object is a shallow copy. It contains references
to the module’s parameters and buffers.
Warning
Currently state_dict() also accepts positional arguments for
destination, prefix and keep_vars in order. However,
this is being deprecated and keyword arguments will be enforced in
future releases.
Warning
Please avoid the use of argument destination as it is not
designed for end-users.
Args:
destination (dict, optional): If provided, the state of module will
be updated into the dict and the same object is returned.
Otherwise, an OrderedDict will be created and returned.
Default: None.
prefix (str, optional): a prefix added to parameter and buffer
names to compose the keys in state_dict. Default: ''.
keep_vars (bool, optional): by default the Tensor s
returned in the state dict are detached from autograd. If it’s
set to True, detaching will not be performed.
Default: False.
Returns:
dict:
a dictionary containing a whole state of the module
Its signature is similar to torch.Tensor.to(), but only accepts
floating point or complex dtypes. In addition, this method will
only cast the floating point or complex parameters and buffers to dtype
(if given). The integral parameters and buffers will be moved
device, if that is given, but with dtypes unchanged. When
non_blocking is set, it tries to convert/move asynchronously
with respect to the host if possible, e.g., moving CPU Tensors with
pinned memory to CUDA devices.
See below for examples.
Note
This method modifies the module in-place.
Args:
device (torch.device): the desired device of the parameters
and buffers in this module
dtype (torch.dtype): the desired floating point or complex dtype of
the parameters and buffers in this module
tensor (torch.Tensor): Tensor whose dtype and device are the desired
dtype and device for all parameters and buffers in this module
This has an effect only on certain modules. See the documentation of
particular modules for details of their behaviors in training/evaluation
mode, i.e., whether they are affected, e.g. Dropout, BatchNorm,
etc.
Args:
mode (bool): whether to set training mode (True) or evaluation
This also makes associated parameters and buffers different objects. So
it should be called before constructing optimizer if the module will
live on XPU while being optimized.
Note
This method modifies the module in-place.
Arguments:
device (int, optional): if specified, all parameters will be