Modulation filterbank for temporal envelope analysis.
Applies a bank of bandpass filters to extract amplitude modulation frequencies
from the output of auditory filterbanks. Modulation filters capture temporal
envelope fluctuations that are important for speech perception, auditory masking,
and detection tasks.
The filterbank analyzes modulations from 0 Hz (DC) up to a maximum modulation
frequency, with filters spaced logarithmically at higher modulation rates.
Phase information is preserved for low modulation frequencies (≤10 Hz) to
maintain temporal fine structure, while only envelope is extracted for higher
modulation frequencies.
Configuration preset selecting published model parameters:
‘dau1997’: Original CASP model (Dau et al. 1997)
lp_cutoff=2.5 Hz
att_factor=1.0
use_upper_limit=False (fixed 150 Hz max)
No 150 Hz pre-filtering
‘jepsen2008’: Updated CASP model (Jepsen et al. 2008)
lp_cutoff=2.5 Hz (main lowpass)
att_factor=1/√2 (≈ 0.707)
use_upper_limit=True (dynamic limit = 0.25 × fc)
max_mfc=150 Hz
150 Hz pre-filtering enabled
‘paulick2024’: Revised CASP model (Paulick et al. 2024)
Same configuration as ‘jepsen2008’
Derived from paulick2024 model for reusability
If preset is provided, it overrides lp_cutoff, att_factor,
use_upper_limit, and max_mfc (unless explicitly provided as arguments).
Default: None (use provided parameters).
‘efilt’: Complex frequency-shifted first-order lowpass (default).
MATLAB AMT compatible. Creates resonant filters with asymmetric response.
‘butterworth’: True Butterworth bandpass with symmetric flat passband.
Uses Second-Order Sections (SOS) for numerical stability.
Conceptually more accurate but numerically different from AMT.
Extension not present in original MATLAB AMT.
Modulation center frequencies for each auditory channel.
Length equals num_channels, each element is 1D tensor with
variable length depending on the upper modulation frequency limit.
\((B, M_f, T)\) and \(M_f\) is the number of modulation filters for
frequency channel \(f\) (varies per channel when use_upper_limit=True).
Type:
List[torch.Tensor] of length \(F\), where each element has shape
Notes
Preset Differences:
Preset
lp_cutoff
(Hz)
att_factor
use_upper_limit
150 Hz pre-filter
dau1997
2.5
1.0
False
No
jepsen2008
2.5
1/√2 (0.707)
True (0.25xfc)
Yes
paulick2024
2.5
1/√2 (0.707)
True (0.25xfc)
Yes
Filter Type Comparison:
efilt: MATLAB AMT compatible. Implements frequency-shifted lowpass, creating
resonant bandpass filters. Not a true symmetric bandpass, but matches original
implementations.
butterworth: Extension for improved numerical stability. True symmetric
bandpass with flat passband. Uses SOS format to avoid coefficient overflow.
This option is not available in original MATLAB AMT.
150 Hz Pre-filtering:
For jepsen2008 and paulick2024 presets, a 1st-order Butterworth lowpass
at 150 Hz is applied before the modulation filterbank to remove very high
modulation frequencies. This is motivated by physiological limitations and
improves predictions for certain psychoacoustic tasks (Kohlrausch et al. 2000).
The 150 Hz pre-filter is separate from the main 2.5 Hz lowpass (mfc=0),
which remains constant across all presets.
Computational Complexity:
Time complexity: \(O(B \cdot F \cdot M \cdot T)\) where \(M\) is the
average number of modulation filters per channel
The number of modulation filters varies per frequency channel when
use_upper_limit=True
For typical configurations: 8-15 modulation filters per channel
Processes each auditory frequency channel independently through its
corresponding modulation filterbank. Applies optional 150 Hz pre-filtering,
then filters with lowpass (mfc=0) and bandpass modulation filters,
and finally applies phase processing (real vs envelope extraction).
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
Optimized modulation filterbank using mega-batch processing.
Drop-in replacement for ModulationFilterbank that achieves 3-5x speedup
through vectorized mega-batch processing while maintaining numerical accuracy
(difference < 1e-12). Inherits all functionality from parent class but overrides
the forward pass to use intelligent batching of filter operations.
Key Optimizations:
Mega-batch flattening: Combines all channel-filter pairs into single batch
Filter grouping: Groups identical coefficients for parallel processing
Vectorized operations: Eliminates Python loops in favor of tensor ops
Intelligent reconstruction: Uses pre-built indexing for ragged outputs
tolerance (int) – Number of decimal places for coefficient rounding during filter grouping.
Lower values create more groups (slower but more accurate).
Higher values create fewer groups (faster but less accurate).
Default: 2 (optimal tradeoff: 34x speedup within grouping, max_diff=1.69e-3).
*args – All other parameters inherited from ModulationFilterbank.
See parent class documentation for complete parameter list.
**kwargs – All other parameters inherited from ModulationFilterbank.
See parent class documentation for complete parameter list.
Grouping is performed each forward pass when learnable=True to adapt to
parameter changes. For fixed filters (learnable=False), grouping could be
cached but current implementation recomputes for simplicity.
Gradient Flow for Learnable Filters:
When learnable=True, filter coefficients can be trained via gradient descent.
The mega-batch processing preserves full gradient flow, but filter grouping means
only one filter per group directly receives gradients during forward pass.
To distribute gradients to all filters in each group, call
distribute_gradients() after backward() and before
optimizer.step():
output=fast_mod(x)loss=criterion(output,target)loss.backward()fast_mod.distribute_gradients()# ← Important for learnable filters!optimizer.step()
Computational Complexity:
Time: \(O(B \cdot F \cdot M \cdot T / G)\) where \(G\) is number of
filter groups (typically 5-10x fewer than total filters)
Space: \(O(B \cdot F \cdot M \cdot T)\) same as parent
>>> importtorch>>> fromtorch_amt.common.modulationimportFastModulationFilterbank>>>>>> # Create auditory center frequencies>>> fc=torch.linspace(100,8000,31)>>>>>> # Initialize fast modulation filterbank>>> modfb=FastModulationFilterbank(fs=16000,fc=fc,preset='jepsen2008')>>>>>> # Same API as ModulationFilterbank>>> x=torch.randn(2,31,16000)>>> y=modfb(x)# 3-5x faster!>>>>>> print(f\"Output: List of {len(y)} tensors\")Output: List of 31 tensors>>> print(f\"First channel shape: {y[0].shape}\")First channel shape: torch.Size([2, 13, 16000])
Distribute gradients from representative filters to all group members.
Call this method after backward() to ensure all filter coefficients
receive gradient updates, even if they weren’t directly used in the
forward pass due to filter grouping.
This implements weight sharing where filters in the same group receive
the same gradient update.
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
Modulation filterbank for King et al. (2019) auditory model.
Implements the specific modulation filtering approach used in King2019,
with logarithmically-spaced bandpass filters based on Q-factor and
Butterworth 2nd-order design. This differs from the standard
ModulationFilterbank which uses preset configurations (dau1997, jepsen2008).
The filterbank extracts amplitude modulation content from 2-150 Hz using
bandpass filters with consistent Q-factor across all modulation frequencies.
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
Fast FFT-based modulation filterbank for King et al. (2019) model.
Drop-in replacement for King2019ModulationFilterbank that uses
FFT-based convolution instead of recursive IIR filtering. Achieves ~250x
speedup with ~15% output difference and ~13% gradient difference.
Trade-offs:
Speed: ~250x faster (2.6s → 0.01s for 0.5s @ 48kHz)
mflow (float) – Minimum modulation frequency in Hz. Default: 2.0.
mfhigh (float) – Maximum modulation frequency in Hz. Default: 150.0.
qfactor (float) – Q-factor for all modulation filters. Default: 1.0.
nmod (int) – Number of modulation filters. If None, automatically determined.
Default: None (automatic).
learnable (bool) – If True, filter coefficients become trainable. Default: False.
Note: Learnable mode uses the same FFT convolution, so gradients
will have ~13% error compared to exact IIR backprop.
dtype (dtype) – Data type for computations. Default: torch.float32.
ir_length_ratio (float) – Ratio of signal length to use for impulse response.
Default: 1.0 (use full signal length for maximum accuracy).
Can be reduced (e.g., 0.5) for faster computation with slightly
more error.
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