Dau et al. (1997) auditory model for amplitude modulation processing.
Implements the complete auditory processing pipeline from Dau, Kollmeier, and
Kohlrausch (1997) for modeling detection and masking with amplitude-modulated
signals. The model simulates peripheral auditory processing from cochlear filtering
through neural adaptation to modulation detection.
This implementation is based on the MATLAB Auditory Modeling Toolbox (AMT)
dau1997 function and provides a differentiable, GPU-accelerated version
suitable for neural network training and optimization.
Lower frequency bound for gammatone filterbank in Hz. Default: 80 Hz.
Lower values extend low-frequency coverage but increase filter count.
Typical range: [50, 200] Hz.
Upper frequency bound for gammatone filterbank in Hz. Default: 8000 Hz.
Higher values extend high-frequency coverage but increase filter count.
Must be less than Nyquist frequency (fs/2). Typical range: [4000, 16000] Hz.
If True, all model stages (filterbank, IHC, adaptation, modulation) become
trainable with gradient-based optimization. Default: False (fixed parameters).
When True, enables end-to-end model training for task-specific optimization.
If True, returns intermediate processing stages along with final output.
Default: False (only final modulation representation).
Useful for visualization, analysis, and multi-stage training.
Second element: dict with keys [‘filterbank’, ‘ihc’, ‘adaptation’]
containing intermediate outputs, each shape \((B, F, T)\) where
\(F\) = num_channels
>>> model_learnable=Dau1997(fs=44100,learnable=True)>>> n_params=sum(p.numel()forpinmodel_learnable.parameters())>>> print(f"Trainable parameters: {n_params}")Trainable parameters: 15234>>>>>> # Example training loop>>> optimizer=torch.optim.Adam(model_learnable.parameters(),lr=1e-3)>>> # ... training code ...
Different frequency ranges:
>>> # Extended low frequency>>> model_low=Dau1997(fs=44100,flow=50,fhigh=8000)>>> print(f"Channels with flow=50Hz: {model_low.num_channels}")Channels with flow=50Hz: 35>>>>>> # Extended high frequency>>> model_high=Dau1997(fs=44100,flow=80,fhigh=16000)>>> print(f"Channels with fhigh=16kHz: {model_high.num_channels}")Channels with fhigh=16kHz: 39
Custom submodule parameters via kwargs:
>>> # Custom filterbank: 6th-order filters instead of default 4th-order>>> model_custom_fb=Dau1997(... fs=44100,... filterbank_kwargs={'n':6}... )>>>>>> # Custom adaptation: different overshoot limit and time constants>>> model_custom_adapt=Dau1997(... fs=44100,... adaptation_kwargs={... 'limit':5.0,# Lower overshoot limit... 'tau':[0.01,0.1,0.2,0.4,0.8]# Custom time constants... }... )>>>>>> # Custom modulation: higher Q and different max frequency>>> model_custom_mod=Dau1997(... fs=44100,... modulation_kwargs={... 'Q':1.0,# Lower Q (broader filters)... 'max_mfc':200.0,# Extend to 200 Hz... 'filter_type':'butterworth'# Use Butterworth instead of efilt... }... )>>>>>> # Combine multiple custom parameters>>> model_fully_custom=Dau1997(... fs=44100,... flow=50,... fhigh=12000,... filterbank_kwargs={'n':5,'erb_scale':1.2},... ihc_kwargs={'method':'breebaart2001'},... adaptation_kwargs={'limit':8.0,'minspl':-10.0},... modulation_kwargs={'Q':1.5,'max_mfc':180.0}... )>>> print(f"Fully custom model channels: {model_fully_custom.num_channels}")Fully custom model channels: 43
Notes
Model Configuration:
The Dau1997 model uses specific configurations for each processing stage:
Gammatone filterbank: 4th-order filters with 1-ERB spacing
The learnable and dtype parameters are always centralized and applied
to all submodules automatically. Custom parameters override defaults while
maintaining the Dau1997 model structure.
Example: To use 6th-order gammatone filters with a different adaptation limit:
\[\begin{split}T_{compute} \\propto B \\cdot F \\cdot T \\cdot (1 + M)\end{split}\]
where \(F\) = num_channels (20-40), \(M\) = avg modulation channels (~10).
For 1 second at 44.1 kHz: ~0.1-0.5 seconds on CPU, ~0.01-0.05 seconds on GPU.
Memory Requirements:
Peak memory scales with output representation size:
\[\begin{split}Memory \\approx B \\cdot F \\cdot M \\cdot T \\cdot 4\\,\\text{bytes}\end{split}\]
For batch=8, 1 second @ 44.1 kHz: ~50-100 MB.
Applications:
The model internal representation can be used for:
Amplitude modulation detection and discrimination
Monaural masking predictions
Temporal modulation transfer function (TMTF) modeling
Distribute gradients to grouped filter coefficients in FastModulationFilterbank.
Call this method after loss.backward() to ensure all filter coefficients
in the modulation filterbank receive gradient updates. This is necessary when
using FastModulationFilterbank with learnable=True, as filters are
grouped for efficiency and gradients need to be shared across group members.
Notes
This method should be called in the training loop:
>>> model=Dau1997(fs=44100,learnable=True)>>> output=model(input_signal)>>> loss=criterion(output,target)>>> loss.backward()>>> model.distribute_gradients()# ← Important for FastModulationFilterbank!>>> optimizer.step()
If the modulation filterbank doesn’t have a distribute_gradients method
(e.g., using standard ModulationFilterbank), this is a no-op.
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
Glasberg & Moore (2002) model for time-varying loudness perception.
Implements the complete loudness computation pipeline from Glasberg & Moore (2002),
providing perceptual loudness measures in sone from audio waveforms. The model
accounts for frequency-dependent hearing sensitivity (ISO 226), masking effects
via asymmetric excitation spreading, and temporal integration with attack/release
dynamics.
This implementation is based on the MATLAB Auditory Modeling Toolbox (AMT)
glasberg2002 function and provides a differentiable, GPU-accelerated version
suitable for neural network training and loudness-based optimization.
\[\begin{split}N(t, f) = \\begin{cases}
0 & E < E_{\\text{thrq}} \\\\
C \\cdot (E - E_{\\text{thrq}}) & E_{\\text{thrq}} < E < E_0 \\\\
C \\cdot E_0^{1-\\alpha} (E - E_{\\text{thrq}})^{\\alpha} & E > E_0
\\end{cases}\end{split}\]
with \(C=0.047\), \(\\alpha=0.2\), \(E_0=10\) dB above threshold.
Stage 5: Loudness Integration
Spatial integration (sum across ERB channels) followed by temporal integration
with asymmetric attack/release filter:
where \(\\alpha = \\exp(-\\Delta t / \\tau)\) with \(\\tau_{\\text{attack}}=50\) ms,
\(\\tau_{\\text{release}}=200\) ms.
param fs:
Sampling rate in Hz. Default: 32000 Hz.
Higher sampling rates improve temporal resolution but increase computational cost.
Typical values: 16000, 32000, 44100, 48000 Hz.
If True, all model stages become trainable with gradient-based optimization.
Default: False (fixed parameters).
When True, enables end-to-end model training for task-specific optimization.
If True, returns intermediate processing stages along with final output.
Default: False (only final long-term loudness).
Useful for visualization, analysis, and multi-stage training.
>>> # Process first signal>>> signal1=torch.randn(1,32000)>>> ltl1=model(signal1)>>>>>> # Reset before processing unrelated second signal>>> model.reset_state()>>> signal2=torch.randn(1,32000)>>> ltl2=model(signal2)
The learnable and dtype parameters are always centralized and applied
to all submodules automatically. Custom parameters override defaults while
maintaining the Glasberg2002 model structure.
Computational Complexity:
Processing time scales approximately as:
\[\begin{split}T_{\\text{compute}} \\propto B \\cdot F \\cdot N_{\\text{ERB}} \\cdot \\log N_{\\text{FFT}}\end{split}\]
where \(F\) = number of time frames (~60 per second), \(N_{\\text{ERB}}=150\).
For 1 second at 32 kHz: ~0.05-0.2 seconds on CPU, ~0.005-0.02 seconds on GPU.
Memory Requirements:
Peak memory scales with intermediate representations:
\[\begin{split}Memory \\approx B \\cdot F \\cdot N_{\\text{ERB}} \\cdot 4\\,\\text{bytes}\end{split}\]
For batch=8, 1 second @ 32 kHz: ~20-40 MB.
Differences from MATLAB AMT:
This implementation uses PyTorch tensors for GPU acceleration
Supports batch processing natively
All stages are differentiable for gradient-based optimization
Output frames depend on hop_length (not fixed downsampling)
Loudness Units:
Sone: Perceptual loudness unit. 1 sone = loudness of 1 kHz tone at 40 dB SPL
Phon: Loudness level unit. Equal to dB SPL at 1 kHz
Tuple of (ltl, stages) where stages is a dict with:
- ‘stl’: Short-term loudness (B, F) in sone
- ‘specific_loudness’: Specific loudness (B, F, N_ERB) in sone/ERB
- ‘excitation’: Excitation pattern (B, F, N_ERB) in dB SPL
- ‘erb_excitation’: ERB-integrated excitation (B, F, N_ERB) in dB SPL
- ‘psd’: Power spectral density (B, F, N_freq)
- ‘freqs’: Frequency vector (N_freq,) in Hz
Reset temporal integration state for processing discontinuous signals.
Clears the internal state of the temporal integration filter (LoudnessIntegration).
Call this method when processing multiple unrelated audio signals sequentially
to prevent temporal blending between signals.
Examples
>>> model=Glasberg2002(fs=32000)>>> signal1=torch.randn(1,32000)>>> ltl1=model(signal1)>>>>>> # Reset before processing new signal>>> model.reset_state()>>> signal2=torch.randn(1,32000)>>> ltl2=model(signal2)# No temporal carryover from signal1
Returns the center frequencies (in Hz) of the ERB-spaced frequency channels
used throughout the model pipeline. Useful for frequency-domain visualization
and analysis.
Returns:
Center frequencies of ERB channels, shape (n_erb_bands,) in Hz.
Typically 150 channels from 50 Hz to 15 kHz with 1/4 ERB spacing.
Get all learnable parameters organized by model component.
Returns a nested dictionary containing the current values of all trainable
parameters in each pipeline stage. Only returns parameters when model is
initialized with learnable=True.
Returns:
Dictionary with component names as keys and parameter dicts as values:
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
Moore et al. (2016) model for binaural loudness perception.
Implements the complete binaural loudness processing pipeline from Moore, Glasberg,
and Schlittenlacher (2016), providing perceptual loudness measures in sone from
stereo audio waveforms. The model extends monaural loudness computation with binaural
inhibition effects, accounting for both diotic summation and dichotic interactions
between ears.
This implementation is a 1:1 port of the MATLAB Auditory Modeling Toolbox (AMT)
moore2016 function and provides a differentiable, GPU-accelerated version
suitable for neural network training and binaural loudness optimization.
Output: short-term loudness (STL), long-term loudness (LTL), max loudness.
param fs:
Sampling rate in Hz. Must be 32000 Hz. Default: 32000.
This requirement is enforced by the outer/middle ear filter design (ANSI S3.4-2007).
If you have audio at different sampling rates, resample to 32 kHz before processing.
If True, all model stages become trainable with gradient-based optimization.
Default: False (fixed parameters).
When True, enables end-to-end model training for task-specific optimization.
If True, returns intermediate processing stages along with final output.
Default: False (only final STL, LTL, mLoud).
Useful for visualization, analysis, and multi-stage training.
Dictionary with model parameters:
- ‘fs’: Sampling rate (32000 Hz)
- ‘learnable’: Whether parameters are trainable
- ‘return_stages’: Whether intermediate stages are returned
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
King et al. (2019) auditory model with nonlinear compression.
Implements a computational model of the auditory periphery designed for
studying masking of frequency modulation (FM) by amplitude modulation (AM).
The model features explicit nonlinear compression (broken-stick or power-law)
and adaptation stages, with a modulation filterbank for extracting temporal
modulation content.
This implementation follows the MATLAB Auditory Modeling Toolbox (AMT)
king2019 configuration and provides a differentiable, GPU-accelerated
version suitable for neural network training and optimization.
where \(L_i(t) = 20\\log_{10}(|y_i(t)|/p_{\\text{ref}}) + \\text{dboffset}\),
\(L_{\\text{knee}}\) is the knee point (default 30 dB), and \(n\)
is the compression exponent (default 0.3).
Power-law compression:
\[c_i(t) = |y_i(t)|^n\]
Stage 3: Inner Hair Cell (IHC) Envelope
Extracts envelope via half-wave rectification and lowpass filtering:
Modulation center frequencies \(f_{\\text{mod},k}\) are logarithmically
spaced from \(f_{\\text{low}}\) (default 2 Hz) to \(f_{\\text{high}}\)
(default 150 Hz) based on Q-factor. Each filter is a 2nd-order Butterworth
bandpass with bandwidth \(\\text{BW} = f_{\\text{mod},k} / Q\).
Output: Tensor of shape \((B, T, F, M)\) where \(M\) is the number
of modulation channels.
param fs:
Sampling rate in Hz. Must match the audio sampling rate.
Common values: 44100, 48000, 32000 Hz.
Base frequency in Hz for centered analysis. If provided, flow and
fhigh are automatically computed as basef±2ERB, creating
a narrow frequency range centered on basef. Default: None (use
flow/fhigh).
Target sampling rate in Hz for downsampling output. If None, no
downsampling is applied. Default: None (keep original fs).
Reduces computational cost for downstream processing.
If True, all model stages become trainable with gradient-based optimization.
Default: False (fixed parameters).
Enables end-to-end model training for task-specific optimization.
If True, returns intermediate processing stages along with final output.
Default: False (only final modulation output).
Useful for visualization, analysis, and multi-stage training.
The compression stage requires correct calibration via dboffset:
100 dB (default): MATLAB AMT convention (0 dBFS = 100 dB SPL)
94 dB: Alternative convention for specific AMT signals
The dboffset must match your signal’s reference level. Incorrect
calibration leads to improper compression behavior and inaccurate
modulation representations.
Example calibration:
# For signals calibrated to 100 dB SPL at 0 dBFSmodel=King2019(fs=48000,dboffset=100.0)# For AMT-specific signals at 94 dB SPLmodel=King2019(fs=48000,dboffset=94.0)
basef Parameter:
When basef is specified, flow and fhigh are automatically
computed to create a narrow frequency range:
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
Osses et al. (2021) auditory model with realistic peripheral filtering.
Implements a computational model of the auditory periphery designed for
fluctuation strength prediction and other psychoacoustic tasks. The model
extends the Dau1997 framework by incorporating headphone and middle ear
transfer functions, providing more accurate peripheral modeling suitable
for headphone-presented stimuli and perceptual predictions.
This implementation follows the MATLAB Auditory Modeling Toolbox (AMT)
osses2021 configuration and provides a differentiable, GPU-accelerated
version suitable for neural network training and optimization.
If True, all model stages become trainable with gradient-based optimization.
Default: False (fixed parameters).
When True, enables end-to-end model training for task-specific optimization.
If True, returns intermediate processing stages along with final output.
Default: False (only final modulation output).
Useful for visualization, analysis, and multi-stage training.
The learnable, dtype, and phase_type parameters are always
centralized and applied to all submodules automatically. Custom parameters
override defaults while maintaining the Osses2021 model structure.
Phase Type Selection:
The phase_type parameter controls peripheral filter characteristics:
‘minimum’ (default): Causal minimum-phase FIR filters
Introduces frequency-dependent group delay
Suitable for real-time or causal processing
Matches physiological phase response
‘zero’: Zero-phase filtering via filtfilt
No phase distortion (symmetric impulse response)
Non-causal (requires future samples)
Better for offline analysis and visualization
Choose based on application: real-time → ‘minimum’, offline → ‘zero’.
Output Format (List of Tensors):
Unlike other models that return a single tensor, Osses2021 returns a
List[torch.Tensor] because each frequency channel has a different
number of modulation channels:
output=model(audio)# List of N tensorsfori,channel_outputinenumerate(output):print(f"Channel {i}: {channel_output.shape}")# Channel 0: torch.Size([B, 13, T])# Channel 1: torch.Size([B, 12, T])# ...
This reflects the jepsen2008 modulation filterbank configuration where
higher frequency channels have fewer modulation channels. To work with
a single tensor, you can concatenate or pad as needed for your application.
Computational Complexity:
Processing time scales as:
\[\begin{split}T_{compute} \\propto T \\cdot (N_{filter} + N_{filt} \\cdot N_{mod})\end{split}\]
where \(T\) = signal length, \(N_{filter}\) = peripheral filter taps,
\(N_{filt}\) = number of frequency channels (~31),
\(N_{mod}\) = modulation channels per frequency (~8-13).
For 1 second @ 44.1 kHz: ~0.1-0.5 seconds on CPU, ~0.01-0.05 seconds on GPU.
Memory Requirements:
Peak memory with intermediate stages:
\[\begin{split}Memory \\approx B \\cdot T \\cdot (N + \\sum_i M_i) \\cdot 4\\,\\text{bytes}\end{split}\]
Distribute gradients to grouped filter coefficients in FastModulationFilterbank.
Call this method after loss.backward() to ensure all filter coefficients
in the modulation filterbank receive gradient updates. This is necessary when
using FastModulationFilterbank with learnable=True, as filters are
grouped for efficiency and gradients need to be shared across group members.
Notes
This method should be called in the training loop:
>>> model=Osses2021(fs=44100,learnable=True)>>> output=model(input_signal)>>> loss=criterion(output,target)>>> loss.backward()>>> model.distribute_gradients()# ← Important for FastModulationFilterbank!>>> optimizer.step()
If the modulation filterbank doesn’t have a distribute_gradients method
(e.g., using standard ModulationFilterbank), this is a no-op.
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
Paulick et al. (2024) CASP model for auditory processing.
Implements the revised Computational Auditory Signal Processing and Perception
(CASP) model, an advanced auditory periphery simulation with physiologically
accurate nonlinear processing and integrated decision-making capabilities for
psychophysical task modeling.
The model extends Jepsen et al. (2008) with improved IHC transduction,
frequency-dependent adaptation, and comprehensive decision-making methods
for detection, discrimination, and masking studies. It provides both the
auditory internal representation and psychophysical decision mechanisms
in a single unified framework.
This implementation follows the MATLAB Auditory Modeling Toolbox (AMT)
implementation and provides a differentiable, GPU-accelerated version
suitable for neural network training and optimization.
Extract Region of Interest (ROI) from internal representation.
Useful for focusing decision metrics on specific:
- Time windows (e.g., signal interval vs. silence)
- Auditory channels (e.g., low-frequency vs. high-frequency)
- Modulation channels (e.g., slow vs. fast modulations)
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