Implements a FIR filter approximating the combined frequency response of
headphones and the outer ear based on measurements from Pralong & Carlile (1996).
The filter emphasizes the 2-3 kHz region characteristic of outer ear resonance
and headphone coloration.
This filter is commonly used in auditory models when sounds are presented via
headphones, compensating for the frequency-dependent transmission from the
headphone driver to the eardrum. The measurements are based on Sennheiser HD 250
Linear circumaural headphones.
If True, the frequency response gains become trainable nn.Parameter objects.
The frequency grid remains fixed, but amplitudes can be adjusted during training.
Default: False.
The frequency sampling method (fir2) creates a FIR filter matching
arbitrary frequency response specifications
For zero-phase filtering, filtfilt is used (forward-backward pass)
For minimum-phase, Hilbert transform converts linear-phase to minimum-phase
Delay Compensation:
Zero-phase: No inherent delay (filtfilt is symmetric)
Minimum-phase: Causal with frequency-dependent group delay minimized
Compensation removes order//2 samples to align signals
Learnable Parameters:
When learnable=True, the filter is recomputed each forward pass to
reflect updated frequency response gains. This enables adaptive equalization
or personalized HRTF modeling.
Device Handling:
This module is device-agnostic and works on CPU, CUDA, and MPS.
>>> hpf_zero=HeadphoneFilter(fs=16000,phase_type='zero')>>> # Non-causal, better frequency response but cannot be used in real-time>>> offline_filtered=hpf_zero(signal)
Learnable filter for adaptive processing:
>>> hpf_learn=HeadphoneFilter(fs=16000,learnable=True)>>> print(f"Learnable parameters: {sum(p.numel()forpinhpf_learn.parameters())}")Learnable parameters: 44>>>>>> # Use in training loop>>> optimizer=torch.optim.Adam(hpf_learn.parameters(),lr=1e-3)>>> # Filter adapts during backpropagation
Get frequency response:
>>> freqs,H=hpf.get_frequency_response(nfft=8192)>>> magnitude_db=20*torch.log10(torch.abs(H)+1e-10)>>> print(f"Freq range: [{freqs[0]:.1f}, {freqs[-1]:.1f}] Hz")Freq range: [0.0, 8000.0] Hz>>> print(f"Peak gain: {magnitude_db.max():.2f} dB at {freqs[magnitude_db.argmax()]:.1f} Hz")Peak gain: 9.02 dB at 2721.3 Hz
Filters the input through the combined headphone and outer ear frequency
response. Automatically handles 2D (batch, time) and 3D (batch, channels, time)
inputs. Refreshes filter coefficients if learnable parameters have changed.
Learnable filter update:
If learnable=True and frequency_data has changed since last call,
the filter is redesigned automatically. This enables gradient-based adaptation.
Phase type behavior:
- Minimum-phase: Causal filtering via convolution, introduces group delay
- Zero-phase: Non-causal via filtfilt, no phase distortion
Device handling:
Filter coefficients are automatically moved to match input device (CPU/CUDA/MPS).
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
Implements FIR filters approximating the frequency-dependent transmission
characteristics of the human middle ear, modeling the mechanical transfer
from the tympanic membrane through the ossicular chain to the cochlear oval
window. The filter captures the impedance matching function that efficiently
transmits sound energy from air to the fluid-filled cochlea.
Two empirically-derived filter variants are available based on stapes velocity
measurements, representing the dominant approach in computational auditory models.
'lopezpoveda2001': Based on Goode et al. (1994) stapes velocity
measurements at 0 dB SPL. Default for Osses et al. (2021) model.
Provides bandpass characteristic with peak around 800 Hz - 1 kHz.
'jepsen2008': Based on stapes impedance data (inverted to velocity).
Used in Jepsen et al. (2008) model. Similar frequency response with
slightly different scaling.
If True, normalizes the filter to have 0 dB gain at the passband peak.
This ensures consistent signal levels across different filter types and
sampling rates. Default: True.
If True, both the frequency response gains and the gain normalization
factor become trainable nn.Parameter objects. The frequency grid
remains fixed, but amplitudes can adapt during training. Default: False.
If True, compensates for group delay by removing order//2 samples.
Only effective for minimum-phase filters (zero-phase has no delay from
filtfilt). Default: True.
Same shape as input (note: length reduced by group_delay if
Notes
Filter Characteristics:
lopezpoveda2001: Peak gain around 800 Hz, -40 dB at 100 Hz, -20 dB at 10 kHz
jepsen2008: Similar bandpass shape with slightly different scaling
Both models capture the resonant behavior of the ossicular chain
Scaling Differences:
lopezpoveda2001: Scaled to 0 dB SPL reference (20 µPa)
jepsen2008: Normalized by max FFT magnitude, then scaled by 1e-8 × 10^(104/20)
Gain Normalization:
When normalize_gain=True, the filter is adjusted so the maximum gain
in the passband is exactly 0 dB. This:
- Ensures consistent output levels across sampling rates
- Facilitates comparison between filter variants
- Prevents unexpected level changes in auditory model pipelines
Phase Options:
Minimum-phase: Suitable for real-time processing, causal
Zero-phase: Suitable for offline analysis, preserves temporal symmetry
Learnable Parameters:
When learnable=True, the filter can adapt to:
- Individual middle ear transfer functions (pathologies, age-related changes)
- Calibration for specific experimental setups
- End-to-end optimization in neural auditory models
Device Handling:
This module is device-agnostic and works on CPU, CUDA, and MPS.
>>> mef_lp=MiddleEarFilter(fs=16000,filter_type='lopezpoveda2001')>>> mef_jp=MiddleEarFilter(fs=16000,filter_type='jepsen2008')>>>>>> # Get frequency responses>>> freqs_lp,H_lp=mef_lp.get_frequency_response(nfft=8192)>>> freqs_jp,H_jp=mef_jp.get_frequency_response(nfft=8192)>>>>>> # Both have peak around 800 Hz>>> mag_lp=20*torch.log10(torch.abs(H_lp)+1e-10)>>> mag_jp=20*torch.log10(torch.abs(H_jp)+1e-10)>>> print(f"LP peak: {mag_lp.max():.2f} dB at {freqs_lp[mag_lp.argmax()]:.1f} Hz")LP peak: 0.00 dB at 800.8 Hz>>> print(f"JP peak: {mag_jp.max():.2f} dB at {freqs_jp[mag_jp.argmax()]:.1f} Hz")JP peak: 0.00 dB at 800.8 Hz
Filters the input through the middle ear frequency response. Automatically
handles 2D (batch, time) and 3D (batch, channels, time) inputs. Applies
gain normalization and delay compensation if configured. Refreshes filter
coefficients if learnable parameters have changed.
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
Implements FIR filtering based on the combined frequency-dependent transmission
characteristics of the outer ear (pinna, ear canal) and middle ear (tympanic
membrane, ossicular chain) transfer functions from ANSI S3.4-2007 and Moore et al.
(1997). The filter compensates for the acoustic gain from free-field or diffuse-field
sound pressure to the oval window.
This filter is essential in auditory models to account for the pre-cochlear filtering
that shapes the acoustic input before neural transduction. The outer ear provides
resonance around 2-4 kHz, while the middle ear acts as an impedance matching network
between air and cochlear fluid.
'tfOuterMiddle1997': Original from Moore et al. (1997), revised 2006.
Used in Glasberg & Moore (2002) loudness model. Based on Goode et al. (1994)
middle ear measurements.
'tfOuterMiddle2007': Updated version following ANSI S3.4-2007 standard.
Slight differences at mid frequencies (1-2 kHz).
If True, the transfer function gains become trainable nn.Parameter objects.
The frequency grid remains fixed, but the dB gains can be adjusted during
training for adaptive equalization. Default: False.
\((B, T)\) - Filtered signal with same shape as input
Notes
Transfer Function Differences:
tfOuterMiddle1997: Revised data from 2006 based on Goode et al. (1994)
tfOuterMiddle2007: ANSI S3.4-2007 with updated middle ear values at 1.25 kHz
Main difference: Middle ear gain at 1250 Hz (3.2 dB vs 4.5 dB)
Field Type Impact:
Free field: Higher gain at 2-4 kHz (pinna resonance peak ~12 dB at 2 kHz)
Diffuse field: More uniform gain distribution (peak ~10 dB at 2 kHz)
Filter Characteristics:
Zero-phase filtering via filtfilt (non-causal, no phase distortion)
Dense frequency sampling (1 Hz resolution) for accurate transfer function
PCHIP interpolation preserves monotonicity and smoothness
Learnable Parameters:
When learnable=True, the filter can adapt to:
- Individual anatomical differences (personalized HRTFs)
- Specific headphone frequency responses
- Equalization for particular acoustic environments
Device Handling:
This module is device-agnostic and works on CPU, CUDA, and MPS.
Basic usage with default parameters (1997 version, free field):
>>> importtorch>>> fromtorch_amt.common.earsimportOuterMiddleEarFilter>>>>>> # Create filter for 32 kHz audio>>> omef=OuterMiddleEarFilter(fs=32000,compensation_type='tfOuterMiddle1997',... field_type='free')>>> print(omef)OuterMiddleEarFilter(fs=32000, type='tfOuterMiddle1997', field='free')>>>>>> # Filter a signal (1 second stereo)>>> signal=torch.randn(2,32000)>>> filtered=omef(signal)>>> print(f"Input: {signal.shape} -> Output: {filtered.shape}")Input: torch.Size([2, 32000]) -> Output: torch.Size([2, 32000])
Compare 1997 vs 2007 versions:
>>> omef_1997=OuterMiddleEarFilter(fs=32000,compensation_type='tfOuterMiddle1997')>>> omef_2007=OuterMiddleEarFilter(fs=32000,compensation_type='tfOuterMiddle2007')>>>>>> # Get transfer functions>>> freqs_1997,tf_1997=omef_1997.get_transfer_function()>>> freqs_2007,tf_2007=omef_2007.get_transfer_function()>>>>>> # Main difference at 1.25 kHz>>> idx=(freqs_1997-1250).abs().argmin()>>> print(f"1997 at 1250 Hz: {tf_1997[idx]:.2f} dB")1997 at 1250 Hz: 0.60 dB>>> print(f"2007 at 1250 Hz: {tf_2007[idx]:.2f} dB")2007 at 1250 Hz: 1.90 dB
Free field vs diffuse field:
>>> omef_free=OuterMiddleEarFilter(fs=32000,field_type='free')>>> omef_diff=OuterMiddleEarFilter(fs=32000,field_type='diffuse')>>>>>> # Diffuse field has less pronounced resonance peak>>> x=torch.randn(1,32000)>>> y_free=omef_free(x)>>> y_diff=omef_diff(x)
Learnable filter for adaptive processing:
>>> omef_learn=OuterMiddleEarFilter(fs=32000,learnable=True)>>> print(f"Learnable parameters: {sum(p.numel()forpinomef_learn.parameters())}")Learnable parameters: 15981>>>>>> # Use in training loop with optimizer>>> optimizer=torch.optim.Adam(omef_learn.parameters(),lr=1e-4)>>> # Transfer function adapts during backpropagation
Get frequency response:
>>> freqs,H_db=omef.get_frequency_response(nfft=8192)>>> print(f"Freq range: [{freqs[0]:.1f}, {freqs[-1]:.1f}] Hz")Freq range: [0.0, 16000.0] Hz>>> print(f"Peak gain: {H_db.max():.2f} dB at {freqs[H_db.argmax()]:.1f} Hz")Peak gain: 16.41 dB at 2978.5 Hz
Uses zero-phase filtering (equivalent to MATLAB’s filtfilt) by applying
the FIR filter in forward and backward passes. Handles 1D and 2D inputs
automatically. Refreshes filter if learnable parameters have changed.
Zero-phase filtering:
Applies filtfilt algorithm (forward + reverse + filter + reverse) to achieve
zero phase distortion. The effective frequency response is \(|H(\omega)|^2\).
Learnable filter update:
If learnable=True and training mode, the filter is redesigned each forward
pass to reflect updated transfer function gains.
Device handling:
Filter coefficients are automatically moved to match input device.
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