Outer & Middle Ear Filters

Frequency-dependent transfer functions for outer and middle ear.

HeadphoneFilter

class torch_amt.HeadphoneFilter(fs, order=512, phase_type='minimum', learnable=False, compensate_delay=True, dtype=torch.float32)[source]

Bases: Module

Combined headphone and outer ear filter.

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.

Algorithm Overview

The filter design follows a frequency sampling approach:

  1. Frequency response data: Load empirical frequency-amplitude pairs from Pralong & Carlile (1996) Figure 1(e)

  2. Nyquist clipping (if fs 20 kHz): Remove data points above fs/2

  3. FIR design: Use frequency sampling (firwin2 equivalent):

    \[H(\omega) = \text{fir2}(\text{order}, f_{\text{norm}}, A)\]

    where \(f_{\text{norm}} = f / (f_s/2)\) and \(A\) are amplitudes

  4. Phase transformation (optional):

    • Zero-phase: \(A_{\text{used}} = \sqrt{A}\) (compensates for filtfilt squaring)

    • Minimum-phase: Apply Hilbert transform to log-magnitude spectrum

  5. Filtering:

    • Zero-phase: Forward-backward filtering (non-causal, no delay)

    • Minimum-phase: Convolution (causal, introduces delay)

param fs:

Sampling rate in Hz.

type fs:

float

param order:

FIR filter order (number of taps - 1). Higher orders provide better frequency resolution but increase computational cost. Default: 512.

type order:

int

param phase_type:

Phase characteristic of the filter:

  • 'minimum': Minimum phase filter (causal, frequency-dependent group delay)

  • 'zero': Zero phase filter (non-causal, linear phase via filtfilt)

Default: 'minimum'.

type phase_type:

str

param learnable:

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.

type learnable:

bool

param compensate_delay:

If True, compensates for group delay by removing order//2 samples. Only applies to zero-phase filters. Default: True.

type compensate_delay:

bool

param dtype:

Data type for filter coefficients and computations. Default: torch.float32.

type dtype:

dtype

fir_coeffs

FIR filter coefficients of shape [order+1].

Type:

torch.Tensor

frequency_data

Frequency response data of shape [N, 2] where column 0 contains frequencies (Hz) and column 1 contains linear gains.

Type:

torch.Tensor or nn.Parameter

group_delay

Group delay in samples (order // 2).

Type:

int

Shape
-----
- Input
  • \(B\) = batch size

  • \(F\) = frequency channels (optional)

  • \(T\) = time samples

Type:

\((B, T)\) or \((B, F, T)\) where

- Output
Type:

Same shape as input

Notes

Filter Design:

  • 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.

See also

MiddleEarFilter

Middle ear transmission filter

OuterMiddleEarFilter

Combined outer and middle ear (ANSI S3.4-2007)

References

Examples

Basic usage with default parameters:

>>> import torch
>>> from torch_amt.common.ears import HeadphoneFilter
>>>
>>> # Create filter for 16 kHz audio
>>> hpf = HeadphoneFilter(fs=16000, order=512)
>>> print(hpf)
HeadphoneFilter(fs=16000, order=512, phase_type=minimum, learnable=False)
>>>
>>> # Filter a batch of signals
>>> signal = torch.randn(2, 16000)  # 2 channels, 1 second
>>> filtered = hpf(signal)
>>> print(f"Input: {signal.shape} -> Output: {filtered.shape}")
Input: torch.Size([2, 16000]) -> Output: torch.Size([2, 16000])

Multi-channel audio (e.g., from gammatone filterbank):

>>> # Shape: (batch=4, channels=31, time=1600)
>>> multichannel = torch.randn(4, 31, 1600)
>>> filtered_multi = hpf(multichannel)
>>> print(filtered_multi.shape)
torch.Size([4, 31, 1600])

Zero-phase filtering for offline processing:

>>> 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() for p in hpf_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
__init__(fs, order=512, phase_type='minimum', learnable=False, compensate_delay=True, dtype=torch.float32)[source]

Initialize internal Module state, shared by both nn.Module and ScriptModule.

Parameters:
forward(x)[source]

Apply headphone filter to input signal.

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.

Parameters:

x (Tensor) –

Input signal of shape:

  • (B, T): Batch of time-domain signals

  • (B, F, T): Batch of multi-channel signals (e.g., from filterbank)

where B = batch size, F = frequency channels, T = time samples.

Returns:

Filtered signal with same shape as input.

Return type:

Tensor

Notes

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).

get_frequency_response(nfft=8192)[source]

Compute frequency response of the filter.

Parameters:

nfft (int) – Number of FFT points for frequency resolution. Default: 8192.

Return type:

Tuple[Tensor, Tensor]

Returns:

  • freqs (torch.Tensor) – Frequency vector in Hz of shape [nfft//2 + 1].

  • response (torch.Tensor) – Complex frequency response of shape [nfft//2 + 1].

get_parameters()[source]

Get current filter parameters.

Returns:

Dictionary containing:

  • 'fs': Sampling rate in Hz

  • 'order': FIR filter order

  • 'phase_type': Phase characteristic (‘minimum’ or ‘zero’)

  • 'learnable': Whether gains are trainable

  • 'num_frequency_points': Number of frequency response points

  • 'frequency_range': [min_freq, max_freq] in Hz

  • 'compensate_delay': Whether delay compensation is applied

Return type:

dict

extra_repr()[source]

Extra representation string for module printing.

Returns:

String containing key module parameters.

Return type:

str

T_destination = ~T_destination
add_module(name, module)

Add a child module to the current module.

The module can be accessed as an attribute using the given name.

Args:
name (str): name of the child module. The child module can be

accessed from this module using the given name

module (Module): child module to be added to the module.

Parameters:
Return type:

None

apply(fn)

Apply fn recursively to every submodule (as returned by .children()) as well as self.

Typical use includes initializing the parameters of a model (see also torch.nn.init).

Args:

fn (Module -> None): function to be applied to each submodule

Returns:

Module: self

Example:

>>> @torch.no_grad()
>>> def init_weights(m):
>>>     print(m)
>>>     if type(m) is nn.Linear:
>>>         m.weight.fill_(1.0)
>>>         print(m.weight)
>>> net = nn.Sequential(nn.Linear(2, 2), nn.Linear(2, 2))
>>> net.apply(init_weights)
Linear(in_features=2, out_features=2, bias=True)
Parameter containing:
tensor([[1., 1.],
        [1., 1.]], requires_grad=True)
Linear(in_features=2, out_features=2, bias=True)
Parameter containing:
tensor([[1., 1.],
        [1., 1.]], requires_grad=True)
Sequential(
  (0): Linear(in_features=2, out_features=2, bias=True)
  (1): Linear(in_features=2, out_features=2, bias=True)
)
Parameters:

fn (Callable[[Module], None])

Return type:

Self

bfloat16()

Casts all floating point parameters and buffers to bfloat16 datatype.

Note

This method modifies the module in-place.

Returns:

Module: self

Return type:

Self

buffers(recurse=True)

Return an iterator over module buffers.

Args:
recurse (bool): if True, then yields buffers of this module

and all submodules. Otherwise, yields only buffers that are direct members of this module.

Yields:

torch.Tensor: module buffer

Example:

>>> # xdoctest: +SKIP("undefined vars")
>>> for buf in model.buffers():
>>>     print(type(buf), buf.size())
<class 'torch.Tensor'> (20L,)
<class 'torch.Tensor'> (20L, 1L, 5L, 5L)
Parameters:

recurse (bool)

Return type:

Iterator[Tensor]

call_super_init: bool = False
children()

Return an iterator over immediate children modules.

Return type:

Iterator[Module]

Yields:

Module: a child module

compile(*args, **kwargs)

Compile this Module’s forward using torch.compile().

This Module’s __call__ method is compiled and all arguments are passed as-is to torch.compile().

See torch.compile() for details on the arguments for this function.

Return type:

None

cpu()

Move all model parameters and buffers to the CPU.

Note

This method modifies the module in-place.

Returns:

Module: self

Return type:

Self

cuda(device=None)

Move all model parameters and buffers to the GPU.

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

copied to that device

Returns:

Module: self

Parameters:

device (int | device | None)

Return type:

Self

double()

Casts all floating point parameters and buffers to double datatype.

Note

This method modifies the module in-place.

Returns:

Module: self

Return type:

Self

dump_patches: bool = False
eval()

Set the module in evaluation mode.

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.

This is equivalent with self.train(False).

See Locally disabling gradient computation for a comparison between .eval() and several similar mechanisms that may be confused with it.

Return type:

Self

Returns:

Module: self

float()

Casts all floating point parameters and buffers to float datatype.

Note

This method modifies the module in-place.

Returns:

Module: self

Return type:

Self

get_buffer(target)

Return the buffer given by target if it exists, otherwise throw an error.

See the docstring for get_submodule for a more detailed explanation of this method’s functionality as well as how to correctly specify target.

Args:
target: The fully-qualified string name of the buffer

to look for. (See get_submodule for how to specify a fully-qualified string.)

Returns:

torch.Tensor: The buffer referenced by target

Raises:
AttributeError: If the target string references an invalid

path or resolves to something that is not a buffer

Parameters:

target (str)

Return type:

Tensor

get_extra_state()

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.

Return type:

Any

Returns:

object: Any extra state to store in the module’s state_dict

get_parameter(target)

Return the parameter given by target if it exists, otherwise throw an error.

See the docstring for get_submodule for a more detailed explanation of this method’s functionality as well as how to correctly specify target.

Args:
target: The fully-qualified string name of the Parameter

to look for. (See get_submodule for how to specify a fully-qualified string.)

Returns:

torch.nn.Parameter: The Parameter referenced by target

Raises:
AttributeError: If the target string references an invalid

path or resolves to something that is not an nn.Parameter

Parameters:

target (str)

Return type:

Parameter

get_submodule(target)

Return the submodule given by target if it exists, otherwise throw an error.

For example, let’s say you have an nn.Module A that looks like this:

A(
    (net_b): Module(
        (net_c): Module(
            (conv): Conv2d(16, 33, kernel_size=(3, 3), stride=(2, 2))
        )
        (linear): Linear(in_features=100, out_features=200, bias=True)
    )
)

(The diagram shows an nn.Module A. 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.

Parameters:

target (str)

Return type:

Module

half()

Casts all floating point parameters and buffers to half datatype.

Note

This method modifies the module in-place.

Returns:

Module: self

Return type:

Self

ipu(device=None)

Move all model parameters and buffers to the IPU.

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

copied to that device

Returns:

Module: self

Parameters:

device (int | device | None)

Return type:

Self

load_state_dict(state_dict, strict=True, assign=False)

Copy parameters and buffers from state_dict into this module and its descendants.

If strict is True, then the keys of state_dict must exactly match the keys returned by this module’s state_dict() function.

Warning

If assign is True the optimizer must be created after the call to load_state_dict unless get_swap_module_params_on_conversion() is True.

Args:
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.

Parameters:
modules()

Return an iterator over all modules in the network.

Return type:

Iterator[Module]

Yields:

Module: a module in the network

Note:

Duplicate modules are returned only once. In the following example, l will be returned only once.

Example:

>>> l = nn.Linear(2, 2)
>>> net = nn.Sequential(l, l)
>>> for idx, m in enumerate(net.modules()):
...     print(idx, '->', m)

0 -> Sequential(
  (0): Linear(in_features=2, out_features=2, bias=True)
  (1): Linear(in_features=2, out_features=2, bias=True)
)
1 -> Linear(in_features=2, out_features=2, bias=True)
mtia(device=None)

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

copied to that device

Returns:

Module: self

Parameters:

device (int | device | None)

Return type:

Self

named_buffers(prefix='', recurse=True, remove_duplicate=True)

Return an iterator over module buffers, yielding both the name of the buffer as well as the buffer itself.

Args:

prefix (str): prefix to prepend to all buffer names. recurse (bool, optional): if True, then yields buffers of this module

and all submodules. Otherwise, yields only buffers that are direct members of this module. Defaults to True.

remove_duplicate (bool, optional): whether to remove the duplicated buffers in the result. Defaults to True.

Yields:

(str, torch.Tensor): Tuple containing the name and buffer

Example:

>>> # xdoctest: +SKIP("undefined vars")
>>> for name, buf in self.named_buffers():
>>>     if name in ['running_var']:
>>>         print(buf.size())
Parameters:
Return type:

Iterator[tuple[str, Tensor]]

named_children()

Return an iterator over immediate children modules, yielding both the name of the module as well as the module itself.

Return type:

Iterator[tuple[str, Module]]

Yields:

(str, Module): Tuple containing a name and child module

Example:

>>> # xdoctest: +SKIP("undefined vars")
>>> for name, module in model.named_children():
>>>     if name in ['conv4', 'conv5']:
>>>         print(module)
named_modules(memo=None, prefix='', remove_duplicate=True)

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.

Example:

>>> l = nn.Linear(2, 2)
>>> net = nn.Sequential(l, l)
>>> for idx, m in enumerate(net.named_modules()):
...     print(idx, '->', m)

0 -> ('', Sequential(
  (0): Linear(in_features=2, out_features=2, bias=True)
  (1): Linear(in_features=2, out_features=2, bias=True)
))
1 -> ('0', Linear(in_features=2, out_features=2, bias=True))
Parameters:
named_parameters(prefix='', recurse=True, remove_duplicate=True)

Return an iterator over module parameters, yielding both the name of the parameter as well as the parameter itself.

Args:

prefix (str): prefix to prepend to all parameter names. recurse (bool): if True, then yields parameters of this module

and all submodules. Otherwise, yields only parameters that are direct members of this module.

remove_duplicate (bool, optional): whether to remove the duplicated

parameters in the result. Defaults to True.

Yields:

(str, Parameter): Tuple containing the name and parameter

Example:

>>> # xdoctest: +SKIP("undefined vars")
>>> for name, param in self.named_parameters():
>>>     if name in ['bias']:
>>>         print(param.size())
Parameters:
Return type:

Iterator[tuple[str, Parameter]]

parameters(recurse=True)

Return an iterator over module parameters.

This is typically passed to an optimizer.

Args:
recurse (bool): if True, then yields parameters of this module

and all submodules. Otherwise, yields only parameters that are direct members of this module.

Yields:

Parameter: module parameter

Example:

>>> # xdoctest: +SKIP("undefined vars")
>>> for param in model.parameters():
>>>     print(type(param), param.size())
<class 'torch.Tensor'> (20L,)
<class 'torch.Tensor'> (20L, 1L, 5L, 5L)
Parameters:

recurse (bool)

Return type:

Iterator[Parameter]

register_backward_hook(hook)

Register a backward hook on the module.

This function is deprecated in favor of register_full_backward_hook() and the behavior of this function will change in future versions.

Returns:
torch.utils.hooks.RemovableHandle:

a handle that can be used to remove the added hook by calling handle.remove()

Parameters:

hook (Callable[[Module, tuple[Tensor, ...] | Tensor, tuple[Tensor, ...] | Tensor], None | tuple[Tensor, ...] | Tensor])

Return type:

RemovableHandle

register_buffer(name, tensor, persistent=True)

Add a buffer to the module.

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

state_dict.

Example:

>>> # xdoctest: +SKIP("undefined vars")
>>> self.register_buffer('running_mean', torch.zeros(num_features))
Parameters:
Return type:

None

register_forward_hook(hook, *, prepend=False, with_kwargs=False, always_call=False)

Register a forward hook on the module.

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) -> None or modified output

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(module, args, kwargs, output) -> None or modified output
Args:

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()

Parameters:
Return type:

RemovableHandle

register_forward_pre_hook(hook, *, prepend=False, with_kwargs=False)

Register a forward pre-hook on the module.

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) -> None or modified input

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(module, args, kwargs) -> None or a tuple of modified input and kwargs
Args:

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()

Parameters:
Return type:

RemovableHandle

register_full_backward_hook(hook, prepend=False)

Register a backward hook on the module.

The hook will be called every time the gradients with respect to a module are computed, and its firing rules are as follows:

  1. Ordinarily, the hook fires when the gradients are computed with respect to the module inputs.

  2. If none of the module inputs require gradients, the hook will fire when the gradients are computed with respect to module outputs.

  3. If none of the module outputs require gradients, then the hooks will not fire.

The hook should have the following signature:

hook(module, grad_input, grad_output) -> tuple(Tensor) or None

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()

Parameters:
Return type:

RemovableHandle

register_full_backward_pre_hook(hook, prepend=False)

Register a backward pre-hook on the module.

The hook will be called every time the gradients for the module are computed. The hook should have the following signature:

hook(module, grad_output) -> tuple[Tensor, ...], Tensor or None

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()

Parameters:
Return type:

RemovableHandle

register_load_state_dict_post_hook(hook)

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()

register_load_state_dict_pre_hook(hook)

Register a pre-hook to be run before module’s load_state_dict() is called.

It should have the following signature::

hook(module, state_dict, prefix, local_metadata, strict, missing_keys, unexpected_keys, error_msgs) -> None # noqa: B950

Arguments:
hook (Callable): Callable hook that will be invoked before

loading the state dict.

register_module(name, module)

Alias for add_module().

Parameters:
Return type:

None

register_parameter(name, param)

Add a parameter to the module.

The parameter can be accessed as an attribute using given name.

Args:
name (str): name of the parameter. The parameter can be accessed

from this module using the given name

param (Parameter or None): parameter to be added to the module. If

None, then operations that run on parameters, such as cuda, are ignored. If None, the parameter is not included in the module’s state_dict.

Parameters:
Return type:

None

register_state_dict_post_hook(hook)

Register a post-hook for the state_dict() method.

It should have the following signature::

hook(module, state_dict, prefix, local_metadata) -> None

The registered hooks can modify the state_dict inplace.

register_state_dict_pre_hook(hook)

Register a pre-hook for the state_dict() method.

It should have the following signature::

hook(module, prefix, keep_vars) -> None

The registered hooks can be used to perform pre-processing before the state_dict call is made.

requires_grad_(requires_grad=True)

Change if autograd should record operations on parameters in this module.

This method sets the parameters’ requires_grad attributes in-place.

This method is helpful for freezing part of the module for finetuning or training parts of a model individually (e.g., GAN training).

See Locally disabling gradient computation for a comparison between .requires_grad_() and several similar mechanisms that may be confused with it.

Args:
requires_grad (bool): whether autograd should record operations on

parameters in this module. Default: True.

Returns:

Module: self

Parameters:

requires_grad (bool)

Return type:

Self

set_extra_state(state)

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.

Args:

state (dict): Extra state from the state_dict

Parameters:

state (Any)

Return type:

None

set_submodule(target, module, strict=False)

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.Module A that looks like this:

A(
    (net_b): Module(
        (net_c): Module(
            (conv): Conv2d(3, 3, 3)
        )
        (linear): Linear(3, 3)
    )
)

(The diagram shows an nn.Module A. 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.

Parameters:
Return type:

None

share_memory()

See torch.Tensor.share_memory_().

Return type:

Self

state_dict(*args, destination=None, prefix='', keep_vars=False)
Overloads:
  • self, destination (T_destination), prefix (str), keep_vars (bool) → T_destination

  • self, prefix (str), keep_vars (bool) → dict[str, Any]

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

Example:

>>> # xdoctest: +SKIP("undefined vars")
>>> module.state_dict().keys()
['bias', 'weight']
to(*args, **kwargs)
Overloads:
  • self, device (DeviceLikeType | None), dtype (dtype | None), non_blocking (bool) → Self

  • self, dtype (dtype), non_blocking (bool) → Self

  • self, tensor (Tensor), non_blocking (bool) → Self

Move and/or cast the parameters and buffers.

This can be called as

to(device=None, dtype=None, non_blocking=False)
to(dtype, non_blocking=False)
to(tensor, non_blocking=False)
to(memory_format=torch.channels_last)

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

memory_format (torch.memory_format): the desired memory

format for 4D parameters and buffers in this module (keyword only argument)

Returns:

Module: self

Examples:

>>> # xdoctest: +IGNORE_WANT("non-deterministic")
>>> linear = nn.Linear(2, 2)
>>> linear.weight
Parameter containing:
tensor([[ 0.1913, -0.3420],
        [-0.5113, -0.2325]])
>>> linear.to(torch.double)
Linear(in_features=2, out_features=2, bias=True)
>>> linear.weight
Parameter containing:
tensor([[ 0.1913, -0.3420],
        [-0.5113, -0.2325]], dtype=torch.float64)
>>> # xdoctest: +REQUIRES(env:TORCH_DOCTEST_CUDA1)
>>> gpu1 = torch.device("cuda:1")
>>> linear.to(gpu1, dtype=torch.half, non_blocking=True)
Linear(in_features=2, out_features=2, bias=True)
>>> linear.weight
Parameter containing:
tensor([[ 0.1914, -0.3420],
        [-0.5112, -0.2324]], dtype=torch.float16, device='cuda:1')
>>> cpu = torch.device("cpu")
>>> linear.to(cpu)
Linear(in_features=2, out_features=2, bias=True)
>>> linear.weight
Parameter containing:
tensor([[ 0.1914, -0.3420],
        [-0.5112, -0.2324]], dtype=torch.float16)

>>> linear = nn.Linear(2, 2, bias=None).to(torch.cdouble)
>>> linear.weight
Parameter containing:
tensor([[ 0.3741+0.j,  0.2382+0.j],
        [ 0.5593+0.j, -0.4443+0.j]], dtype=torch.complex128)
>>> linear(torch.ones(3, 2, dtype=torch.cdouble))
tensor([[0.6122+0.j, 0.1150+0.j],
        [0.6122+0.j, 0.1150+0.j],
        [0.6122+0.j, 0.1150+0.j]], dtype=torch.complex128)
to_empty(*, device, recurse=True)

Move the parameters and buffers to the specified device without copying storage.

Args:
device (torch.device): The desired device of the parameters

and buffers in this module.

recurse (bool): Whether parameters and buffers of submodules should

be recursively moved to the specified device.

Returns:

Module: self

Parameters:
Return type:

Self

train(mode=True)

Set the module in training mode.

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

mode (False). Default: True.

Returns:

Module: self

Parameters:

mode (bool)

Return type:

Self

type(dst_type)

Casts all parameters and buffers to dst_type.

Note

This method modifies the module in-place.

Args:

dst_type (type or string): the desired type

Returns:

Module: self

Parameters:

dst_type (dtype | str)

Return type:

Self

xpu(device=None)

Move all model parameters and buffers to the XPU.

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

copied to that device

Returns:

Module: self

Parameters:

device (int | device | None)

Return type:

Self

zero_grad(set_to_none=True)

Reset gradients of all model parameters.

See similar function under torch.optim.Optimizer for more context.

Args:
set_to_none (bool): instead of setting to zero, set the grads to None.

See torch.optim.Optimizer.zero_grad() for details.

Parameters:

set_to_none (bool)

Return type:

None

training: bool

MiddleEarFilter

class torch_amt.MiddleEarFilter(fs, filter_type='lopezpoveda2001', order=512, phase_type='minimum', normalize_gain=True, learnable=False, compensate_delay=True, dtype=torch.float32)[source]

Bases: Module

Middle ear filter for auditory models.

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.

Algorithm Overview

The filter design process:

  1. Load frequency response data:

    • lopezpoveda2001: Stapes velocity from Goode et al. (1994) measurements

    • jepsen2008: Stapes impedance (inverted to velocity)

  2. Nyquist handling: Clip data above fs/2 or extrapolate with decay

  3. FIR filter design (frequency sampling):

    \[h[n] = \text{fir2}(\text{order}, f_{\text{norm}}, A)\]

    where \(f_{\text{norm}} = f / (f_s/2)\) and \(A\) are amplitudes

  4. Phase transformation (optional):

    • Zero-phase: \(A_{\text{used}} = \sqrt{A}\) (for filtfilt)

    • Minimum-phase: Hilbert transform of log-magnitude

  5. Scaling:

    • lopezpoveda2001: \(h[n] = h[n] / (20 \times 10^{-6})\) (SPL reference)

    • jepsen2008: \(h[n] = h[n] / \max(|H(\omega)|) \times 10^{-8} \times 10^{104/20}\)

  6. Gain normalization (if enabled):

    \[G_{\text{norm}} = -20 \log_{10}(\max(|H(\omega)|))\]

    Applied to ensure 0 dB passband gain

  7. Filtering:

    • Zero-phase: Forward-backward pass (filtfilt)

    • Minimum-phase: Convolution with delay compensation

param fs:

Sampling rate in Hz.

type fs:

float

param filter_type:

Middle ear filter variant:

  • '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.

Default: 'lopezpoveda2001'.

type filter_type:

Literal['lopezpoveda2001', 'jepsen2008']

param order:

FIR filter order (number of taps - 1). Higher orders provide better frequency resolution but increase computational cost and latency. Default: 512.

type order:

int

param phase_type:

Phase characteristic of the filter:

  • 'minimum': Minimum phase filter (causal, frequency-dependent group delay)

  • 'zero': Zero phase filter (non-causal, linear phase via filtfilt)

Default: 'minimum'.

type phase_type:

str

param normalize_gain:

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.

type normalize_gain:

bool

param learnable:

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.

type learnable:

bool

param compensate_delay:

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.

type compensate_delay:

bool

param dtype:

Data type for filter coefficients and computations. Default: torch.float32.

type dtype:

dtype

fir_coeffs

FIR filter coefficients of shape [order+1].

Type:

torch.Tensor

frequency_data

Frequency response data of shape [N, 2] where column 0 contains frequencies (Hz) and column 1 contains linear gains (velocity or inverted impedance).

Type:

torch.Tensor or nn.Parameter

gain_normalization

Gain normalization factor in dB. Scalar value ensuring 0 dB passband gain.

Type:

torch.Tensor or nn.Parameter

group_delay

Group delay in samples (order // 2).

Type:

int

Shape
-----
- Input
  • \(B\) = batch size

  • \(F\) = frequency channels (optional)

  • \(T\) = time samples

Type:

\((B, T)\) or \((B, F, T)\) where

- Output

compensate_delay=True and phase_type='minimum')

Type:

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.

See also

HeadphoneFilter

Headphone and outer ear response

OuterMiddleEarFilter

Combined outer and middle ear (ANSI S3.4-2007)

References

Examples

Basic usage with lopezpoveda2001 filter:

>>> import torch
>>> from torch_amt.common.ears import MiddleEarFilter
>>>
>>> # Create filter for 16 kHz audio
>>> mef = MiddleEarFilter(fs=16000, filter_type='lopezpoveda2001')
>>> print(mef)
MiddleEarFilter(fs=16000, filter_type=lopezpoveda2001, order=512, ...)
>>>
>>> # Filter a stereo signal
>>> signal = torch.randn(2, 16000)
>>> filtered = mef(signal)
>>> print(f"Input: {signal.shape} -> Output: {filtered.shape}")
Input: torch.Size([2, 16000]) -> Output: torch.Size([2, 15744])
>>> # Note: Output shorter by group_delay (512//2 = 256 samples)

Multi-channel audio (e.g., from gammatone filterbank):

>>> # Shape: (batch=4, channels=31, time=1600)
>>> multichannel = torch.randn(4, 31, 1600)
>>> filtered_multi = mef(multichannel)
>>> print(filtered_multi.shape)
torch.Size([4, 31, 1344])

Compare lopezpoveda2001 vs jepsen2008:

>>> 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

Zero-phase filtering for offline analysis:

>>> mef_zero = MiddleEarFilter(fs=16000, phase_type='zero')
>>> # Non-causal, no delay compensation needed
>>> filtered_zero = mef_zero(signal)
>>> print(filtered_zero.shape)
torch.Size([2, 16000])

Learnable filter for adaptive processing:

>>> mef_learn = MiddleEarFilter(fs=16000, learnable=True, normalize_gain=True)
>>> print(f"Learnable parameters: {sum(p.numel() for p in mef_learn.parameters())}")
Learnable parameters: 53
>>> # frequency_data: 26x2=52 params, gain_normalization: 1 param
>>>
>>> # Use in training loop
>>> optimizer = torch.optim.Adam(mef_learn.parameters(), lr=1e-4)
>>> # Filter adapts during backpropagation

Disable gain normalization:

>>> mef_raw = MiddleEarFilter(fs=16000, normalize_gain=False)
>>> # Filter preserves original scaling from data
>>> freqs, H = mef_raw.get_frequency_response()
>>> mag_db = 20 * torch.log10(torch.abs(H) + 1e-10)
>>> print(f"Peak gain: {mag_db.max():.2f} dB")
Peak gain: 65.16 dB
__init__(fs, filter_type='lopezpoveda2001', order=512, phase_type='minimum', normalize_gain=True, learnable=False, compensate_delay=True, dtype=torch.float32)[source]

Initialize internal Module state, shared by both nn.Module and ScriptModule.

Parameters:
forward(x)[source]

Apply middle ear filter to input signal.

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.

Parameters:

x (Tensor) –

Input signal of shape:

  • (B, T): Batch of time-domain signals

  • (B, F, T): Batch of multi-channel signals (e.g., from filterbank)

where B = batch size, F = frequency channels, T = time samples.

Returns:

Filtered signal. Shape depends on phase type and delay compensation:

  • Zero-phase: Same shape as input (no delay)

  • Minimum-phase with compensation: Shorter by group_delay samples

  • Minimum-phase without compensation: Same shape as input

Return type:

Tensor

Notes

Processing order:

  1. Refresh filter if learnable parameters changed

  2. Reshape input for processing

  3. Apply filtering (filtfilt or convolution)

  4. Apply gain normalization (if enabled)

  5. Compensate delay (if minimum-phase and enabled)

  6. Restore original shape

Gain normalization:

If normalize_gain=True, applies linear gain to achieve 0 dB passband peak:

\[y(t) = y(t) imes 10^{G_{ ext{norm}}/20}\]

Device handling:

Filter coefficients are automatically moved to match input device (CPU/CUDA/MPS).

get_frequency_response(nfft=8192)[source]

Compute frequency response of the filter.

Returns the complex frequency response after applying gain normalization (if enabled). Useful for analyzing filter characteristics and debugging.

Parameters:

nfft (int) – Number of FFT points for frequency resolution. Higher values provide finer frequency resolution. Default: 8192.

Return type:

Tuple[Tensor, Tensor]

Returns:

  • freqs (torch.Tensor) – Frequency vector in Hz of shape [nfft//2 + 1].

  • response (torch.Tensor) – Complex frequency response of shape [nfft//2 + 1]. Includes gain normalization if normalize_gain=True.

Notes

To get magnitude in dB:

freqs, H = mef.get_frequency_response()
magnitude_db = 20 * torch.log10(torch.abs(H) + 1e-10)

With normalize_gain=True, the peak magnitude should be exactly 0 dB.

extra_repr()[source]

Extra representation string for module printing.

Returns:

String containing key module parameters.

Return type:

str

T_destination = ~T_destination
add_module(name, module)

Add a child module to the current module.

The module can be accessed as an attribute using the given name.

Args:
name (str): name of the child module. The child module can be

accessed from this module using the given name

module (Module): child module to be added to the module.

Parameters:
Return type:

None

apply(fn)

Apply fn recursively to every submodule (as returned by .children()) as well as self.

Typical use includes initializing the parameters of a model (see also torch.nn.init).

Args:

fn (Module -> None): function to be applied to each submodule

Returns:

Module: self

Example:

>>> @torch.no_grad()
>>> def init_weights(m):
>>>     print(m)
>>>     if type(m) is nn.Linear:
>>>         m.weight.fill_(1.0)
>>>         print(m.weight)
>>> net = nn.Sequential(nn.Linear(2, 2), nn.Linear(2, 2))
>>> net.apply(init_weights)
Linear(in_features=2, out_features=2, bias=True)
Parameter containing:
tensor([[1., 1.],
        [1., 1.]], requires_grad=True)
Linear(in_features=2, out_features=2, bias=True)
Parameter containing:
tensor([[1., 1.],
        [1., 1.]], requires_grad=True)
Sequential(
  (0): Linear(in_features=2, out_features=2, bias=True)
  (1): Linear(in_features=2, out_features=2, bias=True)
)
Parameters:

fn (Callable[[Module], None])

Return type:

Self

bfloat16()

Casts all floating point parameters and buffers to bfloat16 datatype.

Note

This method modifies the module in-place.

Returns:

Module: self

Return type:

Self

buffers(recurse=True)

Return an iterator over module buffers.

Args:
recurse (bool): if True, then yields buffers of this module

and all submodules. Otherwise, yields only buffers that are direct members of this module.

Yields:

torch.Tensor: module buffer

Example:

>>> # xdoctest: +SKIP("undefined vars")
>>> for buf in model.buffers():
>>>     print(type(buf), buf.size())
<class 'torch.Tensor'> (20L,)
<class 'torch.Tensor'> (20L, 1L, 5L, 5L)
Parameters:

recurse (bool)

Return type:

Iterator[Tensor]

call_super_init: bool = False
children()

Return an iterator over immediate children modules.

Return type:

Iterator[Module]

Yields:

Module: a child module

compile(*args, **kwargs)

Compile this Module’s forward using torch.compile().

This Module’s __call__ method is compiled and all arguments are passed as-is to torch.compile().

See torch.compile() for details on the arguments for this function.

Return type:

None

cpu()

Move all model parameters and buffers to the CPU.

Note

This method modifies the module in-place.

Returns:

Module: self

Return type:

Self

cuda(device=None)

Move all model parameters and buffers to the GPU.

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

copied to that device

Returns:

Module: self

Parameters:

device (int | device | None)

Return type:

Self

double()

Casts all floating point parameters and buffers to double datatype.

Note

This method modifies the module in-place.

Returns:

Module: self

Return type:

Self

dump_patches: bool = False
eval()

Set the module in evaluation mode.

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.

This is equivalent with self.train(False).

See Locally disabling gradient computation for a comparison between .eval() and several similar mechanisms that may be confused with it.

Return type:

Self

Returns:

Module: self

float()

Casts all floating point parameters and buffers to float datatype.

Note

This method modifies the module in-place.

Returns:

Module: self

Return type:

Self

get_buffer(target)

Return the buffer given by target if it exists, otherwise throw an error.

See the docstring for get_submodule for a more detailed explanation of this method’s functionality as well as how to correctly specify target.

Args:
target: The fully-qualified string name of the buffer

to look for. (See get_submodule for how to specify a fully-qualified string.)

Returns:

torch.Tensor: The buffer referenced by target

Raises:
AttributeError: If the target string references an invalid

path or resolves to something that is not a buffer

Parameters:

target (str)

Return type:

Tensor

get_extra_state()

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.

Return type:

Any

Returns:

object: Any extra state to store in the module’s state_dict

get_parameter(target)

Return the parameter given by target if it exists, otherwise throw an error.

See the docstring for get_submodule for a more detailed explanation of this method’s functionality as well as how to correctly specify target.

Args:
target: The fully-qualified string name of the Parameter

to look for. (See get_submodule for how to specify a fully-qualified string.)

Returns:

torch.nn.Parameter: The Parameter referenced by target

Raises:
AttributeError: If the target string references an invalid

path or resolves to something that is not an nn.Parameter

Parameters:

target (str)

Return type:

Parameter

get_submodule(target)

Return the submodule given by target if it exists, otherwise throw an error.

For example, let’s say you have an nn.Module A that looks like this:

A(
    (net_b): Module(
        (net_c): Module(
            (conv): Conv2d(16, 33, kernel_size=(3, 3), stride=(2, 2))
        )
        (linear): Linear(in_features=100, out_features=200, bias=True)
    )
)

(The diagram shows an nn.Module A. 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.

Parameters:

target (str)

Return type:

Module

half()

Casts all floating point parameters and buffers to half datatype.

Note

This method modifies the module in-place.

Returns:

Module: self

Return type:

Self

ipu(device=None)

Move all model parameters and buffers to the IPU.

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

copied to that device

Returns:

Module: self

Parameters:

device (int | device | None)

Return type:

Self

load_state_dict(state_dict, strict=True, assign=False)

Copy parameters and buffers from state_dict into this module and its descendants.

If strict is True, then the keys of state_dict must exactly match the keys returned by this module’s state_dict() function.

Warning

If assign is True the optimizer must be created after the call to load_state_dict unless get_swap_module_params_on_conversion() is True.

Args:
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.

Parameters:
modules()

Return an iterator over all modules in the network.

Return type:

Iterator[Module]

Yields:

Module: a module in the network

Note:

Duplicate modules are returned only once. In the following example, l will be returned only once.

Example:

>>> l = nn.Linear(2, 2)
>>> net = nn.Sequential(l, l)
>>> for idx, m in enumerate(net.modules()):
...     print(idx, '->', m)

0 -> Sequential(
  (0): Linear(in_features=2, out_features=2, bias=True)
  (1): Linear(in_features=2, out_features=2, bias=True)
)
1 -> Linear(in_features=2, out_features=2, bias=True)
mtia(device=None)

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

copied to that device

Returns:

Module: self

Parameters:

device (int | device | None)

Return type:

Self

named_buffers(prefix='', recurse=True, remove_duplicate=True)

Return an iterator over module buffers, yielding both the name of the buffer as well as the buffer itself.

Args:

prefix (str): prefix to prepend to all buffer names. recurse (bool, optional): if True, then yields buffers of this module

and all submodules. Otherwise, yields only buffers that are direct members of this module. Defaults to True.

remove_duplicate (bool, optional): whether to remove the duplicated buffers in the result. Defaults to True.

Yields:

(str, torch.Tensor): Tuple containing the name and buffer

Example:

>>> # xdoctest: +SKIP("undefined vars")
>>> for name, buf in self.named_buffers():
>>>     if name in ['running_var']:
>>>         print(buf.size())
Parameters:
Return type:

Iterator[tuple[str, Tensor]]

named_children()

Return an iterator over immediate children modules, yielding both the name of the module as well as the module itself.

Return type:

Iterator[tuple[str, Module]]

Yields:

(str, Module): Tuple containing a name and child module

Example:

>>> # xdoctest: +SKIP("undefined vars")
>>> for name, module in model.named_children():
>>>     if name in ['conv4', 'conv5']:
>>>         print(module)
named_modules(memo=None, prefix='', remove_duplicate=True)

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.

Example:

>>> l = nn.Linear(2, 2)
>>> net = nn.Sequential(l, l)
>>> for idx, m in enumerate(net.named_modules()):
...     print(idx, '->', m)

0 -> ('', Sequential(
  (0): Linear(in_features=2, out_features=2, bias=True)
  (1): Linear(in_features=2, out_features=2, bias=True)
))
1 -> ('0', Linear(in_features=2, out_features=2, bias=True))
Parameters:
named_parameters(prefix='', recurse=True, remove_duplicate=True)

Return an iterator over module parameters, yielding both the name of the parameter as well as the parameter itself.

Args:

prefix (str): prefix to prepend to all parameter names. recurse (bool): if True, then yields parameters of this module

and all submodules. Otherwise, yields only parameters that are direct members of this module.

remove_duplicate (bool, optional): whether to remove the duplicated

parameters in the result. Defaults to True.

Yields:

(str, Parameter): Tuple containing the name and parameter

Example:

>>> # xdoctest: +SKIP("undefined vars")
>>> for name, param in self.named_parameters():
>>>     if name in ['bias']:
>>>         print(param.size())
Parameters:
Return type:

Iterator[tuple[str, Parameter]]

parameters(recurse=True)

Return an iterator over module parameters.

This is typically passed to an optimizer.

Args:
recurse (bool): if True, then yields parameters of this module

and all submodules. Otherwise, yields only parameters that are direct members of this module.

Yields:

Parameter: module parameter

Example:

>>> # xdoctest: +SKIP("undefined vars")
>>> for param in model.parameters():
>>>     print(type(param), param.size())
<class 'torch.Tensor'> (20L,)
<class 'torch.Tensor'> (20L, 1L, 5L, 5L)
Parameters:

recurse (bool)

Return type:

Iterator[Parameter]

register_backward_hook(hook)

Register a backward hook on the module.

This function is deprecated in favor of register_full_backward_hook() and the behavior of this function will change in future versions.

Returns:
torch.utils.hooks.RemovableHandle:

a handle that can be used to remove the added hook by calling handle.remove()

Parameters:

hook (Callable[[Module, tuple[Tensor, ...] | Tensor, tuple[Tensor, ...] | Tensor], None | tuple[Tensor, ...] | Tensor])

Return type:

RemovableHandle

register_buffer(name, tensor, persistent=True)

Add a buffer to the module.

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

state_dict.

Example:

>>> # xdoctest: +SKIP("undefined vars")
>>> self.register_buffer('running_mean', torch.zeros(num_features))
Parameters:
Return type:

None

register_forward_hook(hook, *, prepend=False, with_kwargs=False, always_call=False)

Register a forward hook on the module.

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) -> None or modified output

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(module, args, kwargs, output) -> None or modified output
Args:

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()

Parameters:
Return type:

RemovableHandle

register_forward_pre_hook(hook, *, prepend=False, with_kwargs=False)

Register a forward pre-hook on the module.

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) -> None or modified input

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(module, args, kwargs) -> None or a tuple of modified input and kwargs
Args:

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()

Parameters:
Return type:

RemovableHandle

register_full_backward_hook(hook, prepend=False)

Register a backward hook on the module.

The hook will be called every time the gradients with respect to a module are computed, and its firing rules are as follows:

  1. Ordinarily, the hook fires when the gradients are computed with respect to the module inputs.

  2. If none of the module inputs require gradients, the hook will fire when the gradients are computed with respect to module outputs.

  3. If none of the module outputs require gradients, then the hooks will not fire.

The hook should have the following signature:

hook(module, grad_input, grad_output) -> tuple(Tensor) or None

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()

Parameters:
Return type:

RemovableHandle

register_full_backward_pre_hook(hook, prepend=False)

Register a backward pre-hook on the module.

The hook will be called every time the gradients for the module are computed. The hook should have the following signature:

hook(module, grad_output) -> tuple[Tensor, ...], Tensor or None

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()

Parameters:
Return type:

RemovableHandle

register_load_state_dict_post_hook(hook)

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()

register_load_state_dict_pre_hook(hook)

Register a pre-hook to be run before module’s load_state_dict() is called.

It should have the following signature::

hook(module, state_dict, prefix, local_metadata, strict, missing_keys, unexpected_keys, error_msgs) -> None # noqa: B950

Arguments:
hook (Callable): Callable hook that will be invoked before

loading the state dict.

register_module(name, module)

Alias for add_module().

Parameters:
Return type:

None

register_parameter(name, param)

Add a parameter to the module.

The parameter can be accessed as an attribute using given name.

Args:
name (str): name of the parameter. The parameter can be accessed

from this module using the given name

param (Parameter or None): parameter to be added to the module. If

None, then operations that run on parameters, such as cuda, are ignored. If None, the parameter is not included in the module’s state_dict.

Parameters:
Return type:

None

register_state_dict_post_hook(hook)

Register a post-hook for the state_dict() method.

It should have the following signature::

hook(module, state_dict, prefix, local_metadata) -> None

The registered hooks can modify the state_dict inplace.

register_state_dict_pre_hook(hook)

Register a pre-hook for the state_dict() method.

It should have the following signature::

hook(module, prefix, keep_vars) -> None

The registered hooks can be used to perform pre-processing before the state_dict call is made.

requires_grad_(requires_grad=True)

Change if autograd should record operations on parameters in this module.

This method sets the parameters’ requires_grad attributes in-place.

This method is helpful for freezing part of the module for finetuning or training parts of a model individually (e.g., GAN training).

See Locally disabling gradient computation for a comparison between .requires_grad_() and several similar mechanisms that may be confused with it.

Args:
requires_grad (bool): whether autograd should record operations on

parameters in this module. Default: True.

Returns:

Module: self

Parameters:

requires_grad (bool)

Return type:

Self

set_extra_state(state)

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.

Args:

state (dict): Extra state from the state_dict

Parameters:

state (Any)

Return type:

None

set_submodule(target, module, strict=False)

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.Module A that looks like this:

A(
    (net_b): Module(
        (net_c): Module(
            (conv): Conv2d(3, 3, 3)
        )
        (linear): Linear(3, 3)
    )
)

(The diagram shows an nn.Module A. 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.

Parameters:
Return type:

None

share_memory()

See torch.Tensor.share_memory_().

Return type:

Self

state_dict(*args, destination=None, prefix='', keep_vars=False)
Overloads:
  • self, destination (T_destination), prefix (str), keep_vars (bool) → T_destination

  • self, prefix (str), keep_vars (bool) → dict[str, Any]

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

Example:

>>> # xdoctest: +SKIP("undefined vars")
>>> module.state_dict().keys()
['bias', 'weight']
to(*args, **kwargs)
Overloads:
  • self, device (DeviceLikeType | None), dtype (dtype | None), non_blocking (bool) → Self

  • self, dtype (dtype), non_blocking (bool) → Self

  • self, tensor (Tensor), non_blocking (bool) → Self

Move and/or cast the parameters and buffers.

This can be called as

to(device=None, dtype=None, non_blocking=False)
to(dtype, non_blocking=False)
to(tensor, non_blocking=False)
to(memory_format=torch.channels_last)

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

memory_format (torch.memory_format): the desired memory

format for 4D parameters and buffers in this module (keyword only argument)

Returns:

Module: self

Examples:

>>> # xdoctest: +IGNORE_WANT("non-deterministic")
>>> linear = nn.Linear(2, 2)
>>> linear.weight
Parameter containing:
tensor([[ 0.1913, -0.3420],
        [-0.5113, -0.2325]])
>>> linear.to(torch.double)
Linear(in_features=2, out_features=2, bias=True)
>>> linear.weight
Parameter containing:
tensor([[ 0.1913, -0.3420],
        [-0.5113, -0.2325]], dtype=torch.float64)
>>> # xdoctest: +REQUIRES(env:TORCH_DOCTEST_CUDA1)
>>> gpu1 = torch.device("cuda:1")
>>> linear.to(gpu1, dtype=torch.half, non_blocking=True)
Linear(in_features=2, out_features=2, bias=True)
>>> linear.weight
Parameter containing:
tensor([[ 0.1914, -0.3420],
        [-0.5112, -0.2324]], dtype=torch.float16, device='cuda:1')
>>> cpu = torch.device("cpu")
>>> linear.to(cpu)
Linear(in_features=2, out_features=2, bias=True)
>>> linear.weight
Parameter containing:
tensor([[ 0.1914, -0.3420],
        [-0.5112, -0.2324]], dtype=torch.float16)

>>> linear = nn.Linear(2, 2, bias=None).to(torch.cdouble)
>>> linear.weight
Parameter containing:
tensor([[ 0.3741+0.j,  0.2382+0.j],
        [ 0.5593+0.j, -0.4443+0.j]], dtype=torch.complex128)
>>> linear(torch.ones(3, 2, dtype=torch.cdouble))
tensor([[0.6122+0.j, 0.1150+0.j],
        [0.6122+0.j, 0.1150+0.j],
        [0.6122+0.j, 0.1150+0.j]], dtype=torch.complex128)
to_empty(*, device, recurse=True)

Move the parameters and buffers to the specified device without copying storage.

Args:
device (torch.device): The desired device of the parameters

and buffers in this module.

recurse (bool): Whether parameters and buffers of submodules should

be recursively moved to the specified device.

Returns:

Module: self

Parameters:
Return type:

Self

train(mode=True)

Set the module in training mode.

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

mode (False). Default: True.

Returns:

Module: self

Parameters:

mode (bool)

Return type:

Self

type(dst_type)

Casts all parameters and buffers to dst_type.

Note

This method modifies the module in-place.

Args:

dst_type (type or string): the desired type

Returns:

Module: self

Parameters:

dst_type (dtype | str)

Return type:

Self

xpu(device=None)

Move all model parameters and buffers to the XPU.

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

copied to that device

Returns:

Module: self

Parameters:

device (int | device | None)

Return type:

Self

zero_grad(set_to_none=True)

Reset gradients of all model parameters.

See similar function under torch.optim.Optimizer for more context.

Args:
set_to_none (bool): instead of setting to zero, set the grads to None.

See torch.optim.Optimizer.zero_grad() for details.

Parameters:

set_to_none (bool)

Return type:

None

training: bool

OuterMiddleEarFilter

class torch_amt.OuterMiddleEarFilter(fs, compensation_type='tfOuterMiddle1997', field_type='free', flow=20.0, fhigh=16000.0, order=4096, learnable=False, dtype=torch.float32)[source]

Bases: Module

Outer and middle ear transfer function filter.

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.

Algorithm Overview

The filter design combines two transfer functions:

  1. Outer ear transfer function \(H_{\text{outer}}(f)\):

    • Free field: Direct sound from frontal incidence

    • Diffuse field: Sound from all directions (reverberant)

    • Provides gain boost at 2-4 kHz due to ear canal resonance

  2. Middle ear transfer function \(H_{\text{middle}}(f)\):

    • tfOuterMiddle1997: Moore et al. (1997) / Glasberg & Moore (2002)

    • tfOuterMiddle2007: ANSI S3.4-2007 standard

    • Attenuation at low frequencies (< 500 Hz) and high frequencies (> 8 kHz)

  3. Combined transfer function (dB):

    \[H_{\text{combined}}(f) = H_{\text{outer}}(f) + H_{\text{middle}}(f)\]
  4. Interpolation: PCHIP (Piecewise Cubic Hermite) from tabulated values to dense frequency grid \([f_{\text{low}}, f_{\text{high}}]\)

  5. FIR filter design: Frequency sampling method (firwin2):

    \[h[n] = \text{IFFT}\{10^{H_{\text{combined}}(f)/10}\}\]
  6. Zero-phase filtering: Forward-backward pass (filtfilt):

    \[y(t) = \text{filtfilt}(h, x(t))\]
param fs:

Sampling rate in Hz.

type fs:

float

param compensation_type:

Transfer function version:

  • '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).

Default: 'tfOuterMiddle1997'.

type compensation_type:

Literal['tfOuterMiddle1997', 'tfOuterMiddle2007']

param field_type:

Sound field type:

  • 'free': Free-field presentation (anechoic, frontal incidence). Typical for experiments with loudspeakers.

  • 'diffuse': Diffuse-field presentation (reverberant, omnidirectional). Typical for headphone equalization.

Default: 'free'.

type field_type:

Literal['free', 'diffuse']

param flow:

Lowest frequency for transfer function evaluation in Hz. Default: 20 Hz.

type flow:

float

param fhigh:

Highest frequency for transfer function evaluation in Hz. Default: 16000 Hz.

type fhigh:

float

param order:

FIR filter order (number of taps - 1). Higher orders provide better frequency resolution but increase computational cost and latency. Default: 4096.

type order:

int

param learnable:

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.

type learnable:

bool

param dtype:

Data type for filter coefficients and computations. Default: torch.float32.

type dtype:

dtype

tf_gains

Transfer function gains in dB of shape [num_freqs], where num_freqs = fhigh - flow + 1 (1 Hz spacing). If learnable=True, this is a trainable parameter.

Type:

torch.Tensor or nn.Parameter

fvec

Frequency vector in Hz of shape [num_freqs] from flow to fhigh.

Type:

torch.Tensor

fir_coeffs

FIR filter coefficients of shape [order+1].

Type:

torch.Tensor

Shape
-----
- Input
  • \(B\) = batch size

  • \(T\) = time samples

Type:

\((B, T)\) where

- Output
Type:

\((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.

See also

HeadphoneFilter

Headphone and outer ear response (Pralong & Carlile 1996)

MiddleEarFilter

Middle ear only (Lopez-Poveda & Meddis 2001)

References

Examples

Basic usage with default parameters (1997 version, free field):

>>> import torch
>>> from torch_amt.common.ears import OuterMiddleEarFilter
>>>
>>> # 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() for p in omef_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
__init__(fs, compensation_type='tfOuterMiddle1997', field_type='free', flow=20.0, fhigh=16000.0, order=4096, learnable=False, dtype=torch.float32)[source]

Initialize internal Module state, shared by both nn.Module and ScriptModule.

Parameters:
forward(x)[source]

Apply outer and middle ear filtering.

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.

Parameters:

x (Tensor) –

Input signal of shape:

  • (T,): Single-channel time-domain signal

  • (B, T): Batch of time-domain signals

where B = batch size, T = time samples.

Returns:

Zero-phase filtered signal with same shape as input.

Return type:

Tensor

Notes

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.

get_frequency_response(nfft=8192)[source]

Compute frequency response of the filter.

Parameters:

nfft (int) – FFT length for frequency response. Default: 8192.

Return type:

Tuple[Tensor, Tensor]

Returns:

  • freqs (torch.Tensor) – Frequency vector in Hz. Shape: [nfft//2 + 1].

  • response (torch.Tensor) – Frequency response in dB. Shape: [nfft//2 + 1].

get_transfer_function()[source]

Get the original transfer function (before FIR design).

Return type:

Tuple[Tensor, Tensor]

Returns:

  • freqs (torch.Tensor) – Frequency vector in Hz. Shape: [num_freqs].

  • gains (torch.Tensor) – Transfer function gains in dB. Shape: [num_freqs].

extra_repr()[source]

Extra representation string for module printing.

Returns:

String containing key module parameters.

Return type:

str

T_destination = ~T_destination
add_module(name, module)

Add a child module to the current module.

The module can be accessed as an attribute using the given name.

Args:
name (str): name of the child module. The child module can be

accessed from this module using the given name

module (Module): child module to be added to the module.

Parameters:
Return type:

None

apply(fn)

Apply fn recursively to every submodule (as returned by .children()) as well as self.

Typical use includes initializing the parameters of a model (see also torch.nn.init).

Args:

fn (Module -> None): function to be applied to each submodule

Returns:

Module: self

Example:

>>> @torch.no_grad()
>>> def init_weights(m):
>>>     print(m)
>>>     if type(m) is nn.Linear:
>>>         m.weight.fill_(1.0)
>>>         print(m.weight)
>>> net = nn.Sequential(nn.Linear(2, 2), nn.Linear(2, 2))
>>> net.apply(init_weights)
Linear(in_features=2, out_features=2, bias=True)
Parameter containing:
tensor([[1., 1.],
        [1., 1.]], requires_grad=True)
Linear(in_features=2, out_features=2, bias=True)
Parameter containing:
tensor([[1., 1.],
        [1., 1.]], requires_grad=True)
Sequential(
  (0): Linear(in_features=2, out_features=2, bias=True)
  (1): Linear(in_features=2, out_features=2, bias=True)
)
Parameters:

fn (Callable[[Module], None])

Return type:

Self

bfloat16()

Casts all floating point parameters and buffers to bfloat16 datatype.

Note

This method modifies the module in-place.

Returns:

Module: self

Return type:

Self

buffers(recurse=True)

Return an iterator over module buffers.

Args:
recurse (bool): if True, then yields buffers of this module

and all submodules. Otherwise, yields only buffers that are direct members of this module.

Yields:

torch.Tensor: module buffer

Example:

>>> # xdoctest: +SKIP("undefined vars")
>>> for buf in model.buffers():
>>>     print(type(buf), buf.size())
<class 'torch.Tensor'> (20L,)
<class 'torch.Tensor'> (20L, 1L, 5L, 5L)
Parameters:

recurse (bool)

Return type:

Iterator[Tensor]

call_super_init: bool = False
children()

Return an iterator over immediate children modules.

Return type:

Iterator[Module]

Yields:

Module: a child module

compile(*args, **kwargs)

Compile this Module’s forward using torch.compile().

This Module’s __call__ method is compiled and all arguments are passed as-is to torch.compile().

See torch.compile() for details on the arguments for this function.

Return type:

None

cpu()

Move all model parameters and buffers to the CPU.

Note

This method modifies the module in-place.

Returns:

Module: self

Return type:

Self

cuda(device=None)

Move all model parameters and buffers to the GPU.

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

copied to that device

Returns:

Module: self

Parameters:

device (int | device | None)

Return type:

Self

double()

Casts all floating point parameters and buffers to double datatype.

Note

This method modifies the module in-place.

Returns:

Module: self

Return type:

Self

dump_patches: bool = False
eval()

Set the module in evaluation mode.

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.

This is equivalent with self.train(False).

See Locally disabling gradient computation for a comparison between .eval() and several similar mechanisms that may be confused with it.

Return type:

Self

Returns:

Module: self

float()

Casts all floating point parameters and buffers to float datatype.

Note

This method modifies the module in-place.

Returns:

Module: self

Return type:

Self

get_buffer(target)

Return the buffer given by target if it exists, otherwise throw an error.

See the docstring for get_submodule for a more detailed explanation of this method’s functionality as well as how to correctly specify target.

Args:
target: The fully-qualified string name of the buffer

to look for. (See get_submodule for how to specify a fully-qualified string.)

Returns:

torch.Tensor: The buffer referenced by target

Raises:
AttributeError: If the target string references an invalid

path or resolves to something that is not a buffer

Parameters:

target (str)

Return type:

Tensor

get_extra_state()

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.

Return type:

Any

Returns:

object: Any extra state to store in the module’s state_dict

get_parameter(target)

Return the parameter given by target if it exists, otherwise throw an error.

See the docstring for get_submodule for a more detailed explanation of this method’s functionality as well as how to correctly specify target.

Args:
target: The fully-qualified string name of the Parameter

to look for. (See get_submodule for how to specify a fully-qualified string.)

Returns:

torch.nn.Parameter: The Parameter referenced by target

Raises:
AttributeError: If the target string references an invalid

path or resolves to something that is not an nn.Parameter

Parameters:

target (str)

Return type:

Parameter

get_submodule(target)

Return the submodule given by target if it exists, otherwise throw an error.

For example, let’s say you have an nn.Module A that looks like this:

A(
    (net_b): Module(
        (net_c): Module(
            (conv): Conv2d(16, 33, kernel_size=(3, 3), stride=(2, 2))
        )
        (linear): Linear(in_features=100, out_features=200, bias=True)
    )
)

(The diagram shows an nn.Module A. 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.

Parameters:

target (str)

Return type:

Module

half()

Casts all floating point parameters and buffers to half datatype.

Note

This method modifies the module in-place.

Returns:

Module: self

Return type:

Self

ipu(device=None)

Move all model parameters and buffers to the IPU.

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

copied to that device

Returns:

Module: self

Parameters:

device (int | device | None)

Return type:

Self

load_state_dict(state_dict, strict=True, assign=False)

Copy parameters and buffers from state_dict into this module and its descendants.

If strict is True, then the keys of state_dict must exactly match the keys returned by this module’s state_dict() function.

Warning

If assign is True the optimizer must be created after the call to load_state_dict unless get_swap_module_params_on_conversion() is True.

Args:
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.

Parameters:
modules()

Return an iterator over all modules in the network.

Return type:

Iterator[Module]

Yields:

Module: a module in the network

Note:

Duplicate modules are returned only once. In the following example, l will be returned only once.

Example:

>>> l = nn.Linear(2, 2)
>>> net = nn.Sequential(l, l)
>>> for idx, m in enumerate(net.modules()):
...     print(idx, '->', m)

0 -> Sequential(
  (0): Linear(in_features=2, out_features=2, bias=True)
  (1): Linear(in_features=2, out_features=2, bias=True)
)
1 -> Linear(in_features=2, out_features=2, bias=True)
mtia(device=None)

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

copied to that device

Returns:

Module: self

Parameters:

device (int | device | None)

Return type:

Self

named_buffers(prefix='', recurse=True, remove_duplicate=True)

Return an iterator over module buffers, yielding both the name of the buffer as well as the buffer itself.

Args:

prefix (str): prefix to prepend to all buffer names. recurse (bool, optional): if True, then yields buffers of this module

and all submodules. Otherwise, yields only buffers that are direct members of this module. Defaults to True.

remove_duplicate (bool, optional): whether to remove the duplicated buffers in the result. Defaults to True.

Yields:

(str, torch.Tensor): Tuple containing the name and buffer

Example:

>>> # xdoctest: +SKIP("undefined vars")
>>> for name, buf in self.named_buffers():
>>>     if name in ['running_var']:
>>>         print(buf.size())
Parameters:
Return type:

Iterator[tuple[str, Tensor]]

named_children()

Return an iterator over immediate children modules, yielding both the name of the module as well as the module itself.

Return type:

Iterator[tuple[str, Module]]

Yields:

(str, Module): Tuple containing a name and child module

Example:

>>> # xdoctest: +SKIP("undefined vars")
>>> for name, module in model.named_children():
>>>     if name in ['conv4', 'conv5']:
>>>         print(module)
named_modules(memo=None, prefix='', remove_duplicate=True)

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.

Example:

>>> l = nn.Linear(2, 2)
>>> net = nn.Sequential(l, l)
>>> for idx, m in enumerate(net.named_modules()):
...     print(idx, '->', m)

0 -> ('', Sequential(
  (0): Linear(in_features=2, out_features=2, bias=True)
  (1): Linear(in_features=2, out_features=2, bias=True)
))
1 -> ('0', Linear(in_features=2, out_features=2, bias=True))
Parameters:
named_parameters(prefix='', recurse=True, remove_duplicate=True)

Return an iterator over module parameters, yielding both the name of the parameter as well as the parameter itself.

Args:

prefix (str): prefix to prepend to all parameter names. recurse (bool): if True, then yields parameters of this module

and all submodules. Otherwise, yields only parameters that are direct members of this module.

remove_duplicate (bool, optional): whether to remove the duplicated

parameters in the result. Defaults to True.

Yields:

(str, Parameter): Tuple containing the name and parameter

Example:

>>> # xdoctest: +SKIP("undefined vars")
>>> for name, param in self.named_parameters():
>>>     if name in ['bias']:
>>>         print(param.size())
Parameters:
Return type:

Iterator[tuple[str, Parameter]]

parameters(recurse=True)

Return an iterator over module parameters.

This is typically passed to an optimizer.

Args:
recurse (bool): if True, then yields parameters of this module

and all submodules. Otherwise, yields only parameters that are direct members of this module.

Yields:

Parameter: module parameter

Example:

>>> # xdoctest: +SKIP("undefined vars")
>>> for param in model.parameters():
>>>     print(type(param), param.size())
<class 'torch.Tensor'> (20L,)
<class 'torch.Tensor'> (20L, 1L, 5L, 5L)
Parameters:

recurse (bool)

Return type:

Iterator[Parameter]

register_backward_hook(hook)

Register a backward hook on the module.

This function is deprecated in favor of register_full_backward_hook() and the behavior of this function will change in future versions.

Returns:
torch.utils.hooks.RemovableHandle:

a handle that can be used to remove the added hook by calling handle.remove()

Parameters:

hook (Callable[[Module, tuple[Tensor, ...] | Tensor, tuple[Tensor, ...] | Tensor], None | tuple[Tensor, ...] | Tensor])

Return type:

RemovableHandle

register_buffer(name, tensor, persistent=True)

Add a buffer to the module.

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

state_dict.

Example:

>>> # xdoctest: +SKIP("undefined vars")
>>> self.register_buffer('running_mean', torch.zeros(num_features))
Parameters:
Return type:

None

register_forward_hook(hook, *, prepend=False, with_kwargs=False, always_call=False)

Register a forward hook on the module.

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) -> None or modified output

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(module, args, kwargs, output) -> None or modified output
Args:

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()

Parameters:
Return type:

RemovableHandle

register_forward_pre_hook(hook, *, prepend=False, with_kwargs=False)

Register a forward pre-hook on the module.

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) -> None or modified input

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(module, args, kwargs) -> None or a tuple of modified input and kwargs
Args:

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()

Parameters:
Return type:

RemovableHandle

register_full_backward_hook(hook, prepend=False)

Register a backward hook on the module.

The hook will be called every time the gradients with respect to a module are computed, and its firing rules are as follows:

  1. Ordinarily, the hook fires when the gradients are computed with respect to the module inputs.

  2. If none of the module inputs require gradients, the hook will fire when the gradients are computed with respect to module outputs.

  3. If none of the module outputs require gradients, then the hooks will not fire.

The hook should have the following signature:

hook(module, grad_input, grad_output) -> tuple(Tensor) or None

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()

Parameters:
Return type:

RemovableHandle

register_full_backward_pre_hook(hook, prepend=False)

Register a backward pre-hook on the module.

The hook will be called every time the gradients for the module are computed. The hook should have the following signature:

hook(module, grad_output) -> tuple[Tensor, ...], Tensor or None

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()

Parameters:
Return type:

RemovableHandle

register_load_state_dict_post_hook(hook)

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()

register_load_state_dict_pre_hook(hook)

Register a pre-hook to be run before module’s load_state_dict() is called.

It should have the following signature::

hook(module, state_dict, prefix, local_metadata, strict, missing_keys, unexpected_keys, error_msgs) -> None # noqa: B950

Arguments:
hook (Callable): Callable hook that will be invoked before

loading the state dict.

register_module(name, module)

Alias for add_module().

Parameters:
Return type:

None

register_parameter(name, param)

Add a parameter to the module.

The parameter can be accessed as an attribute using given name.

Args:
name (str): name of the parameter. The parameter can be accessed

from this module using the given name

param (Parameter or None): parameter to be added to the module. If

None, then operations that run on parameters, such as cuda, are ignored. If None, the parameter is not included in the module’s state_dict.

Parameters:
Return type:

None

register_state_dict_post_hook(hook)

Register a post-hook for the state_dict() method.

It should have the following signature::

hook(module, state_dict, prefix, local_metadata) -> None

The registered hooks can modify the state_dict inplace.

register_state_dict_pre_hook(hook)

Register a pre-hook for the state_dict() method.

It should have the following signature::

hook(module, prefix, keep_vars) -> None

The registered hooks can be used to perform pre-processing before the state_dict call is made.

requires_grad_(requires_grad=True)

Change if autograd should record operations on parameters in this module.

This method sets the parameters’ requires_grad attributes in-place.

This method is helpful for freezing part of the module for finetuning or training parts of a model individually (e.g., GAN training).

See Locally disabling gradient computation for a comparison between .requires_grad_() and several similar mechanisms that may be confused with it.

Args:
requires_grad (bool): whether autograd should record operations on

parameters in this module. Default: True.

Returns:

Module: self

Parameters:

requires_grad (bool)

Return type:

Self

set_extra_state(state)

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.

Args:

state (dict): Extra state from the state_dict

Parameters:

state (Any)

Return type:

None

set_submodule(target, module, strict=False)

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.Module A that looks like this:

A(
    (net_b): Module(
        (net_c): Module(
            (conv): Conv2d(3, 3, 3)
        )
        (linear): Linear(3, 3)
    )
)

(The diagram shows an nn.Module A. 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.

Parameters:
Return type:

None

share_memory()

See torch.Tensor.share_memory_().

Return type:

Self

state_dict(*args, destination=None, prefix='', keep_vars=False)
Overloads:
  • self, destination (T_destination), prefix (str), keep_vars (bool) → T_destination

  • self, prefix (str), keep_vars (bool) → dict[str, Any]

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

Example:

>>> # xdoctest: +SKIP("undefined vars")
>>> module.state_dict().keys()
['bias', 'weight']
to(*args, **kwargs)
Overloads:
  • self, device (DeviceLikeType | None), dtype (dtype | None), non_blocking (bool) → Self

  • self, dtype (dtype), non_blocking (bool) → Self

  • self, tensor (Tensor), non_blocking (bool) → Self

Move and/or cast the parameters and buffers.

This can be called as

to(device=None, dtype=None, non_blocking=False)
to(dtype, non_blocking=False)
to(tensor, non_blocking=False)
to(memory_format=torch.channels_last)

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

memory_format (torch.memory_format): the desired memory

format for 4D parameters and buffers in this module (keyword only argument)

Returns:

Module: self

Examples:

>>> # xdoctest: +IGNORE_WANT("non-deterministic")
>>> linear = nn.Linear(2, 2)
>>> linear.weight
Parameter containing:
tensor([[ 0.1913, -0.3420],
        [-0.5113, -0.2325]])
>>> linear.to(torch.double)
Linear(in_features=2, out_features=2, bias=True)
>>> linear.weight
Parameter containing:
tensor([[ 0.1913, -0.3420],
        [-0.5113, -0.2325]], dtype=torch.float64)
>>> # xdoctest: +REQUIRES(env:TORCH_DOCTEST_CUDA1)
>>> gpu1 = torch.device("cuda:1")
>>> linear.to(gpu1, dtype=torch.half, non_blocking=True)
Linear(in_features=2, out_features=2, bias=True)
>>> linear.weight
Parameter containing:
tensor([[ 0.1914, -0.3420],
        [-0.5112, -0.2324]], dtype=torch.float16, device='cuda:1')
>>> cpu = torch.device("cpu")
>>> linear.to(cpu)
Linear(in_features=2, out_features=2, bias=True)
>>> linear.weight
Parameter containing:
tensor([[ 0.1914, -0.3420],
        [-0.5112, -0.2324]], dtype=torch.float16)

>>> linear = nn.Linear(2, 2, bias=None).to(torch.cdouble)
>>> linear.weight
Parameter containing:
tensor([[ 0.3741+0.j,  0.2382+0.j],
        [ 0.5593+0.j, -0.4443+0.j]], dtype=torch.complex128)
>>> linear(torch.ones(3, 2, dtype=torch.cdouble))
tensor([[0.6122+0.j, 0.1150+0.j],
        [0.6122+0.j, 0.1150+0.j],
        [0.6122+0.j, 0.1150+0.j]], dtype=torch.complex128)
to_empty(*, device, recurse=True)

Move the parameters and buffers to the specified device without copying storage.

Args:
device (torch.device): The desired device of the parameters

and buffers in this module.

recurse (bool): Whether parameters and buffers of submodules should

be recursively moved to the specified device.

Returns:

Module: self

Parameters:
Return type:

Self

train(mode=True)

Set the module in training mode.

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

mode (False). Default: True.

Returns:

Module: self

Parameters:

mode (bool)

Return type:

Self

type(dst_type)

Casts all parameters and buffers to dst_type.

Note

This method modifies the module in-place.

Args:

dst_type (type or string): the desired type

Returns:

Module: self

Parameters:

dst_type (dtype | str)

Return type:

Self

xpu(device=None)

Move all model parameters and buffers to the XPU.

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

copied to that device

Returns:

Module: self

Parameters:

device (int | device | None)

Return type:

Self

zero_grad(set_to_none=True)

Reset gradients of all model parameters.

See similar function under torch.optim.Optimizer for more context.

Args:
set_to_none (bool): instead of setting to zero, set the grads to None.

See torch.optim.Optimizer.zero_grad() for details.

Parameters:

set_to_none (bool)

Return type:

None

training: bool