RiptideRiptide
Download Riptide SDKInstall Riptorch
Menu
Riptorch docs · Reference

torch.nn

Modules and layers: containers, convolution, pooling, activations, normalization, recurrent and transformer layers, losses, plus nn.init and nn.utils. Every name stock PyTorch has is here; the reference marks what is the same, what is different and what Riptorch adds. PyTorch’s own page for torch.nn.

import riptorch as torch
from riptorch import nn
210 same as PyTorch3 different4 Riptorch extras

Containers

nn.ModuleclassSame as PyTorch
Module(*args: Any, **kwargs: Any) -> None

torch.nn.Module: parameters, buffers and submodules in their own tables (_parameters, _buffers, _modules), reached as attributes; forward hooks; state_dict with persistent buffers. Written from PyTorch's docs.

34 methods and properties defined on Module
  • add_module(self, name, module)Adds a submodule under name (register_module is the same).
  • apply(self, fn)Calls fn on every submodule (children first) and then on the module itself; returns the module.
  • bfloat16(self)Converts floating parameters and buffers to bfloat16.
  • buffers(self, recurse=True)Every buffer once, submodules included unless recurse=False.
  • children(self)The direct submodules, each once, in registration order.
  • cpu(self)Returns the module unchanged (one unified memory).
  • cuda(self, device=None)Returns the module unchanged (one unified memory; no CUDA device).
  • double(self)Converts floating parameters and buffers to float64.
  • eval(self)train(False): evaluation mode for the module and every submodule.
  • extra_repr(self)Extra text inside the module's repr parentheses; subclasses override it ("" here).
  • float(self)Converts floating parameters and buffers to float32.
  • get_buffer(self, target)The buffer at a dotted path such as "bn.running_mean".
  • get_parameter(self, target)The parameter at a dotted path such as "layer.0.weight".
  • get_submodule(self, target)The submodule at a dotted path ("" is the module itself); AttributeError when a part is missing.
  • half(self)Converts floating parameters and buffers to float16.
  • load_state_dict(self, state_dict, strict=True, assign=False)Copies tensors from state_dict into the parameters and buffers, by dotted name.
  • modules(self)The module and all submodules, depth first, each once.
  • named_buffers(self, prefix='', recurse=True, remove_duplicate=True)(dotted name, buffer) pairs, each buffer once.
  • named_children(self)The direct submodules with their names, each module once, in registration order.
  • named_modules(self, memo=None, prefix='', remove_duplicate=True)The module and all submodules (depth first) with dotted names; shared modules once unless remove_duplicate=False.
  • named_parameters(self, prefix='', recurse=True, remove_duplicate=True)Each parameter once, under its first name, as in PyTorch: a tied weight (head.weight = wte.weight) is one parameter, updated and saved once.
  • parameters(self, recurse=True)Every parameter once (tied tensors once), submodules included unless recurse=False.
  • register_buffer(self, name, tensor, persistent=True)Adds a tensor that is part of the module's state but not a parameter.
  • register_forward_hook(self, hook, *, prepend=False, with_kwargs=False, always_call=False)Calls hook(module, args, output) after forward; a non-None result replaces the output.
  • register_forward_pre_hook(self, hook, *, prepend=False, with_kwargs=False)Calls hook(module, args) before forward; a non-None result replaces the arguments.
  • register_module(self, name, module)Adds a submodule under name (register_module is the same).
  • register_parameter(self, name, param)Adds a parameter under name (None registers an empty slot).
  • requires_grad_(self, requires_grad=True)Sets requires_grad on every parameter; returns the module.
  • share_memory(self)Returns the module unchanged (tensors are already in memory every process of this machine maps).
  • state_dict(self, *args, destination=None, prefix='', keep_vars=False)Parameters and persistent buffers by dotted name. A tied tensor is under each of its names, as in PyTorch (so a PyTorch model loads the checkpoint with strict=True); torch.save writes its values once.
  • to(self, *args, **kwargs)Converts every floating parameter and buffer to a floating dtype; returns the module.
  • train(self, mode=True)Sets training on the module and every submodule; mode must be a bool (ValueError otherwise, as PyTorch).
  • type(self, dst_type)Converts floating parameters and buffers to dst_type (as to(dst_type)).
  • zero_grad(self, set_to_none=True)Clears every parameter's gradient (sets it to None; set_to_none is accepted).
nn.ModuleDictclassSame as PyTorch
ModuleDict(modules=None)

torch.nn.ModuleDict: modules by name, registered as submodules in insertion order.

5 methods and properties defined on ModuleDict
  • items(self)(name, module) pairs, in insertion order.
  • keys(self)The names, in insertion order.
  • pop(self, k)Removes the module named k and returns it.
  • update(self, modules)Adds or replaces modules from a mapping or (name, module) pairs.
  • values(self)The modules, in insertion order.
nn.ModuleListclassSame as PyTorch
ModuleList(mods=None)

Submodules by position ("0", "1",...), in order.

3 methods and properties defined on ModuleList
  • append(self, m)Adds a module at the end; returns the list.
  • extend(self, mods)Appends each module of an iterable; returns the list.
  • insert(self, i, m)Inserts a module at position i, renumbering the ones after it.
nn.ParameterDictclassSame as PyTorch
ParameterDict(parameters=None)

Parameters by key, registered under the keys; plain tensors become parameters.

9 methods and properties defined on ParameterDict
  • clear(self)Removes every parameter.
  • copy(self)A new ParameterDict holding the same parameters.
  • forward(self, *a)Raises RuntimeError: a ParameterDict is not callable (as PyTorch).
  • get(self, k, default=None)The parameter under k, or default.
  • items(self)(key, parameter) pairs, in insertion order.
  • keys(self)The keys, in insertion order.
  • pop(self, k)Removes and returns the parameter under k.
  • update(self, params)Adds or replaces parameters from a dict or (key, value) pairs.
  • values(self)The parameters, in insertion order.
nn.ParameterListclassSame as PyTorch
ParameterList(values=None)

Parameters by position, registered as "0", "1",...; plain floating tensors become parameters.

3 methods and properties defined on ParameterList
  • append(self, v)Adds a parameter at the end; returns the list.
  • extend(self, values)Appends each value of an iterable; returns the list.
  • forward(self, *a)Raises RuntimeError: a ParameterList is not callable (as PyTorch).
nn.SequentialclassSame as PyTorch
Sequential(*mods)

Runs its modules in order, each one's output the next one's input.

Sequential(m1, m2,...) names them "0", "1",...; Sequential(OrderedDict) keeps the given names.

2 methods and properties defined on Sequential
  • append(self, m)Adds a module at the end; returns the Sequential.
  • forward(self, x)Passes x through each module in order.

Parameters and buffers

nn.BufferclassSame as PyTorch
Buffer(data=None, *, persistent=True)

nn.Buffer(data, persistent=True): a tensor that a module registers as a buffer when assigned to an attribute.

nn.ParameterclassSame as PyTorch
Parameter(data=None, requires_grad=True)

nn.Parameter(t): a leaf of t's values and dtype that needs gradients (floating dtypes; an integer parameter records none, as PyTorch allows with requires_grad=False), marked as a parameter.

nn.UninitializedBufferclassSame as PyTorch
UninitializedBuffer(requires_grad=False, device=None, dtype=None, persistent=True)

A buffer not yet initialised: materialize(shape) turns it into a tensor.

1 methods and properties defined on UninitializedBuffer
  • requires_grad
nn.UninitializedParameterclassSame as PyTorch
UninitializedParameter(requires_grad=True, device=None, dtype=None)

A parameter not yet initialised (Lazy modules): materialize(shape) turns it into a Parameter.

1 methods and properties defined on UninitializedParameter
  • requires_grad

Convolution layers

nn.Conv1dclassSame as PyTorch
Conv1d(in_channels, out_channels, kernel_size, stride=1, padding=0, dilation=1, groups=1, bias=True, padding_mode='zeros', device=None, dtype=None, output_padding=0)

nn.Conv1d: a 1-d convolution with weight and bias drawn as PyTorch (U(-k, k), k = 1 / sqrt(fan_in)).

1 methods and properties defined on Conv1d
  • forward(self, x)The 1-d convolution of x.
nn.Conv2dclassSame as PyTorch
Conv2d(in_channels, out_channels, kernel_size, stride=1, padding=0, dilation=1, groups=1, bias=True, padding_mode='zeros', device=None, dtype=None, output_padding=0)

nn.Conv2d: a 2-d convolution (stride, padding incl. "same" / "valid", dilation, groups, padding_mode) with weight and bias drawn as PyTorch (U(-k, k), k = 1 / sqrt(fan_in)).

1 methods and properties defined on Conv2d
  • forward(self, x)The convolution of x (padding_mode applied first).
nn.Conv3dclassSame as PyTorch
Conv3d(in_channels, out_channels, kernel_size, stride=1, padding=0, dilation=1, groups=1, bias=True, padding_mode='zeros', device=None, dtype=None, output_padding=0)

nn.Conv3d: a 3-d convolution with weight and bias drawn as PyTorch.

1 methods and properties defined on Conv3d
  • forward(self, x)The 3-d convolution of x.
nn.ConvTranspose1dclassSame as PyTorch
ConvTranspose1d(in_channels, out_channels, kernel_size, stride=1, padding=0, output_padding=0, groups=1, bias=True, dilation=1, padding_mode='zeros', device=None, dtype=None)

nn.ConvTranspose1d: the transposed 1-d convolution (output_padding as PyTorch).

nn.ConvTranspose2dclassSame as PyTorch
ConvTranspose2d(in_channels, out_channels, kernel_size, stride=1, padding=0, output_padding=0, groups=1, bias=True, dilation=1, padding_mode='zeros', device=None, dtype=None)

nn.ConvTranspose2d: the transposed 2-d convolution.

nn.ConvTranspose3dclassSame as PyTorch
ConvTranspose3d(in_channels, out_channels, kernel_size, stride=1, padding=0, output_padding=0, groups=1, bias=True, dilation=1, padding_mode='zeros', device=None, dtype=None)

nn.ConvTranspose3d: the transposed 3-d convolution.

nn.FoldclassSame as PyTorch
Fold(output_size: Union[int, tuple[int, ...]], kernel_size: Union[int, tuple[int, ...]], dilation: Union[int, tuple[int, ...]] = 1, padding: Union[int, tuple[int, ...]] = 0, stride: Union[int, tuple[int, ...]] = 1) -> None

Same as PyTorch’s torch.nn.Fold.

1 methods and properties defined on Fold
  • forward(self, *inputs)
nn.LazyConv1dclassSame as PyTorch
LazyConv1d(out_channels: int, kernel_size: Union[int, tuple[int]], stride: Union[int, tuple[int]] = 1, padding: Union[int, tuple[int]] = 0, dilation: Union[int, tuple[int]] = 1, groups: int = 1, bias: bool = True, padding_mode: Literal['zeros', 'reflect', 'replicate', 'circular'] = 'zeros', device=None, dtype=None) -> None

Same as PyTorch’s torch.nn.LazyConv1d.

2 methods and properties defined on LazyConv1d
  • forward(self, x, *rest, **kw)
  • has_uninitialized_params(self)
nn.LazyConv2dclassSame as PyTorch
LazyConv2d(out_channels: int, kernel_size: Union[int, tuple[int, int]], stride: Union[int, tuple[int, int]] = 1, padding: Union[int, tuple[int, int]] = 0, dilation: Union[int, tuple[int, int]] = 1, groups: int = 1, bias: bool = True, padding_mode: Literal['zeros', 'reflect', 'replicate', 'circular'] = 'zeros', device=None, dtype=None) -> None

Same as PyTorch’s torch.nn.LazyConv2d.

2 methods and properties defined on LazyConv2d
  • forward(self, x, *rest, **kw)
  • has_uninitialized_params(self)
nn.LazyConv3dclassSame as PyTorch
LazyConv3d(out_channels: int, kernel_size: Union[int, tuple[int, int, int]], stride: Union[int, tuple[int, int, int]] = 1, padding: Union[int, tuple[int, int, int]] = 0, dilation: Union[int, tuple[int, int, int]] = 1, groups: int = 1, bias: bool = True, padding_mode: Literal['zeros', 'reflect', 'replicate', 'circular'] = 'zeros', device=None, dtype=None) -> None

Same as PyTorch’s torch.nn.LazyConv3d.

2 methods and properties defined on LazyConv3d
  • forward(self, x, *rest, **kw)
  • has_uninitialized_params(self)
nn.LazyConvTranspose1dclassSame as PyTorch
LazyConvTranspose1d(out_channels: int, kernel_size: Union[int, tuple[int]], stride: Union[int, tuple[int]] = 1, padding: Union[int, tuple[int]] = 0, output_padding: Union[int, tuple[int]] = 0, groups: int = 1, bias: bool = True, dilation: Union[int, tuple[int]] = 1, padding_mode: Literal['zeros', 'reflect', 'replicate', 'circular'] = 'zeros', device=None, dtype=None) -> None

Same as PyTorch’s torch.nn.LazyConvTranspose1d.

2 methods and properties defined on LazyConvTranspose1d
  • forward(self, x, *rest, **kw)
  • has_uninitialized_params(self)
nn.LazyConvTranspose2dclassSame as PyTorch
LazyConvTranspose2d(out_channels: int, kernel_size: Union[int, tuple[int, int]], stride: Union[int, tuple[int, int]] = 1, padding: Union[int, tuple[int, int]] = 0, output_padding: Union[int, tuple[int, int]] = 0, groups: int = 1, bias: bool = True, dilation: int = 1, padding_mode: Literal['zeros', 'reflect', 'replicate', 'circular'] = 'zeros', device=None, dtype=None) -> None

Same as PyTorch’s torch.nn.LazyConvTranspose2d.

2 methods and properties defined on LazyConvTranspose2d
  • forward(self, x, *rest, **kw)
  • has_uninitialized_params(self)
nn.LazyConvTranspose3dclassSame as PyTorch
LazyConvTranspose3d(out_channels: int, kernel_size: Union[int, tuple[int, int, int]], stride: Union[int, tuple[int, int, int]] = 1, padding: Union[int, tuple[int, int, int]] = 0, output_padding: Union[int, tuple[int, int, int]] = 0, groups: int = 1, bias: bool = True, dilation: Union[int, tuple[int, int, int]] = 1, padding_mode: Literal['zeros', 'reflect', 'replicate', 'circular'] = 'zeros', device=None, dtype=None) -> None

Same as PyTorch’s torch.nn.LazyConvTranspose3d.

2 methods and properties defined on LazyConvTranspose3d
  • forward(self, x, *rest, **kw)
  • has_uninitialized_params(self)
nn.UnfoldclassSame as PyTorch
Unfold(kernel_size: Union[int, tuple[int, ...]], dilation: Union[int, tuple[int, ...]] = 1, padding: Union[int, tuple[int, ...]] = 0, stride: Union[int, tuple[int, ...]] = 1) -> None

Same as PyTorch’s torch.nn.Unfold.

1 methods and properties defined on Unfold
  • forward(self, *inputs)

Pooling layers

nn.AdaptiveAvgPool1dclassSame as PyTorch
AdaptiveAvgPool1d(output_size)

nn.AdaptiveAvgPool1d: F.adaptive_avg_pool1d to output_size.

1 methods and properties defined on AdaptiveAvgPool1d
  • forward(self, x)F.adaptive_avg_pool1d of x.
nn.AdaptiveAvgPool2dclassSame as PyTorch
AdaptiveAvgPool2d(output_size: Union[int, NoneType, tuple[int | None, ...]]) -> None

nn.AdaptiveAvgPool2d: the module form of torch.nn.functional.adaptive_avg_pool2d; forward(*inputs) calls it with the arguments given at construction (output_size).

adaptive_avg_pool2d: When the input size is a multiple of the output size (the windows don't overlap): a reshape and a mean. Otherwise PyTorch's overlapping windows as two averaging matrices (P_h x P_w^T, gradients flow).

2 methods and properties defined on AdaptiveAvgPool2d
  • extra_repr(self)
  • forward(self, *a, **k)Calls the layer's function on the inputs with the arguments given at construction (and training= following train / eval where the function takes it). A quantized input runs the quantized kernel (same parameters).
nn.AdaptiveAvgPool3dclassSame as PyTorch
AdaptiveAvgPool3d(output_size: Union[int, NoneType, tuple[int | None, ...]]) -> None

Same as PyTorch’s torch.nn.AdaptiveAvgPool3d.

1 methods and properties defined on AdaptiveAvgPool3d
  • forward(self, *inputs)
nn.AdaptiveMaxPool1dclassSame as PyTorch
AdaptiveMaxPool1d(output_size: Union[int, NoneType, tuple[int | None, ...]], return_indices: bool = False) -> None

Same as PyTorch’s torch.nn.AdaptiveMaxPool1d.

1 methods and properties defined on AdaptiveMaxPool1d
  • forward(self, *inputs)
nn.AdaptiveMaxPool2dclassSame as PyTorch
AdaptiveMaxPool2d(output_size: Union[int, NoneType, tuple[int | None, ...]], return_indices: bool = False) -> None

Same as PyTorch’s torch.nn.AdaptiveMaxPool2d.

1 methods and properties defined on AdaptiveMaxPool2d
  • forward(self, *inputs)
nn.AdaptiveMaxPool3dclassSame as PyTorch
AdaptiveMaxPool3d(output_size: Union[int, NoneType, tuple[int | None, ...]], return_indices: bool = False) -> None

Same as PyTorch’s torch.nn.AdaptiveMaxPool3d.

1 methods and properties defined on AdaptiveMaxPool3d
  • forward(self, *inputs)
nn.AvgPool1dclassSame as PyTorch
AvgPool1d(kernel_size, stride=None, padding=0, ceil_mode=False, count_include_pad=True)

nn.AvgPool1d: F.avg_pool1d with the stored window arguments.

1 methods and properties defined on AvgPool1d
  • forward(self, x)F.avg_pool1d of x.
nn.AvgPool2dclassSame as PyTorch
AvgPool2d(kernel_size, stride=None, padding=0, ceil_mode=False, count_include_pad=True, divisor_override=None)

nn.AvgPool2d: F.avg_pool2d with the stored kernel_size, stride, padding, ceil_mode, count_include_pad and divisor_override.

1 methods and properties defined on AvgPool2d
  • forward(self, *a, **k)F.avg_pool2d of x. A quantized input runs the quantized kernel (same parameters).
nn.AvgPool3dclassSame as PyTorch
AvgPool3d(kernel_size: Union[int, tuple[int, int, int]], stride: Union[int, tuple[int, int, int], NoneType] = None, padding: Union[int, tuple[int, int, int]] = 0, ceil_mode: bool = False, count_include_pad: bool = True, divisor_override: int | None = None) -> None

Same as PyTorch’s torch.nn.AvgPool3d.

1 methods and properties defined on AvgPool3d
  • forward(self, *inputs)
nn.FractionalMaxPool2dclassSame as PyTorch
FractionalMaxPool2d(kernel_size, output_size=None, output_ratio=None, return_indices=False, _random_samples=None)

nn.FractionalMaxPool2d / 3d: F.fractional_max_pool2d / 3d as a module (output_size or output_ratio, return_indices, _random_samples kept as a buffer).

2 methods and properties defined on FractionalMaxPool2d
  • extra_repr(self)kernel_size, output_size and output_ratio for the repr.
  • forward(self, input)Pools input with the module's settings.
nn.FractionalMaxPool3dclassSame as PyTorch
FractionalMaxPool3d(kernel_size, output_size=None, output_ratio=None, return_indices=False, _random_samples=None)

nn.FractionalMaxPool2d / 3d: F.fractional_max_pool2d / 3d as a module (output_size or output_ratio, return_indices, _random_samples kept as a buffer).

2 methods and properties defined on FractionalMaxPool3d
  • extra_repr(self)kernel_size, output_size and output_ratio for the repr.
  • forward(self, input)Pools input with the module's settings.
nn.LPPool1dclassSame as PyTorch
LPPool1d(norm_type: float, kernel_size: Union[int, tuple[int, ...]], stride: Union[int, tuple[int, ...], NoneType] = None, ceil_mode: bool = False) -> None

Same as PyTorch’s torch.nn.LPPool1d.

1 methods and properties defined on LPPool1d
  • forward(self, *inputs)
nn.LPPool2dclassSame as PyTorch
LPPool2d(norm_type: float, kernel_size: Union[int, tuple[int, ...]], stride: Union[int, tuple[int, ...], NoneType] = None, ceil_mode: bool = False) -> None

Same as PyTorch’s torch.nn.LPPool2d.

1 methods and properties defined on LPPool2d
  • forward(self, *inputs)
nn.LPPool3dclassSame as PyTorch
LPPool3d(norm_type: float, kernel_size: Union[int, tuple[int, ...]], stride: Union[int, tuple[int, ...], NoneType] = None, ceil_mode: bool = False) -> None

Same as PyTorch’s torch.nn.LPPool3d.

1 methods and properties defined on LPPool3d
  • forward(self, *inputs)
nn.MaxPool1dclassSame as PyTorch
MaxPool1d(kernel_size: Union[int, tuple[int, ...]], stride: Union[int, tuple[int, ...], NoneType] = None, padding: Union[int, tuple[int, ...]] = 0, dilation: Union[int, tuple[int, ...]] = 1, return_indices: bool = False, ceil_mode: bool = False) -> None

Same as PyTorch’s torch.nn.MaxPool1d.

1 methods and properties defined on MaxPool1d
  • forward(self, *a, **k)The module's forward. A quantized input runs the quantized kernel (same parameters).
nn.MaxPool2dclassDifferent from PyTorch
MaxPool2d(kernel_size: Union[int, tuple[int, ...]], stride: Union[int, tuple[int, ...], NoneType] = None, padding: Union[int, tuple[int, ...]] = 0, dilation: Union[int, tuple[int, ...]] = 1, return_indices: bool = False, ceil_mode: bool = False) -> None

nn.MaxPool2d: the module form of torch.nn.functional.max_pool2d; forward(*inputs) calls it with the arguments given at construction (kernel_size, stride, padding, dilation, ceil_mode, return_indices).

max_pool2d: Any window, stride and padding (padding counts as -inf): the max over the kh x kw shifted strided slices. ceil_mode / return_indices / dilation != 1 raise NotImplementedError.

Different from PyTorch: nn.MaxPool2d: the module form of torch.nn.functional.max_pool2d; forward(*inputs) calls it with the arguments given at construction (kernel_size, stride, padding, dilation, ceil_mode, return_indices). max_pool2d: Any window, stride and padding (padding counts as -inf): the max over the kh x kw shift

2 methods and properties defined on MaxPool2d
  • extra_repr(self)
  • forward(self, *a, **k)Calls the layer's function on the inputs with the arguments given at construction (and training= following train / eval where the function takes it). A quantized input runs the quantized kernel (same parameters).
nn.MaxPool3dclassSame as PyTorch
MaxPool3d(kernel_size: Union[int, tuple[int, ...]], stride: Union[int, tuple[int, ...], NoneType] = None, padding: Union[int, tuple[int, ...]] = 0, dilation: Union[int, tuple[int, ...]] = 1, return_indices: bool = False, ceil_mode: bool = False) -> None

Same as PyTorch’s torch.nn.MaxPool3d.

1 methods and properties defined on MaxPool3d
  • forward(self, *a, **k)The module's forward. A quantized input runs the quantized kernel (same parameters).

Padding layers

nn.CircularPad1dclassSame as PyTorch
CircularPad1d(padding, value=0.0)

Same as PyTorch’s torch.nn.CircularPad1d.

1 methods and properties defined on CircularPad1d
  • forward(self, x)
nn.CircularPad2dclassSame as PyTorch
CircularPad2d(padding, value=0.0)

Same as PyTorch’s torch.nn.CircularPad2d.

1 methods and properties defined on CircularPad2d
  • forward(self, x)
nn.CircularPad3dclassSame as PyTorch
CircularPad3d(padding, value=0.0)

Same as PyTorch’s torch.nn.CircularPad3d.

1 methods and properties defined on CircularPad3d
  • forward(self, x)
nn.ConstantPad1dclassSame as PyTorch
ConstantPad1d(padding, value=0.0)

Same as PyTorch’s torch.nn.ConstantPad1d.

1 methods and properties defined on ConstantPad1d
  • forward(self, x)
nn.ConstantPad2dclassSame as PyTorch
ConstantPad2d(padding, value=0.0)

Same as PyTorch’s torch.nn.ConstantPad2d.

1 methods and properties defined on ConstantPad2d
  • forward(self, x)
nn.ConstantPad3dclassSame as PyTorch
ConstantPad3d(padding, value=0.0)

Same as PyTorch’s torch.nn.ConstantPad3d.

1 methods and properties defined on ConstantPad3d
  • forward(self, x)
nn.ReflectionPad1dclassSame as PyTorch
ReflectionPad1d(padding, value=0.0)

Same as PyTorch’s torch.nn.ReflectionPad1d.

1 methods and properties defined on ReflectionPad1d
  • forward(self, x)
nn.ReflectionPad2dclassSame as PyTorch
ReflectionPad2d(padding, value=0.0)

Same as PyTorch’s torch.nn.ReflectionPad2d.

1 methods and properties defined on ReflectionPad2d
  • forward(self, x)
nn.ReflectionPad3dclassSame as PyTorch
ReflectionPad3d(padding, value=0.0)

Same as PyTorch’s torch.nn.ReflectionPad3d.

1 methods and properties defined on ReflectionPad3d
  • forward(self, x)
nn.ReplicationPad1dclassSame as PyTorch
ReplicationPad1d(padding, value=0.0)

Same as PyTorch’s torch.nn.ReplicationPad1d.

1 methods and properties defined on ReplicationPad1d
  • forward(self, x)
nn.ReplicationPad2dclassSame as PyTorch
ReplicationPad2d(padding, value=0.0)

Same as PyTorch’s torch.nn.ReplicationPad2d.

1 methods and properties defined on ReplicationPad2d
  • forward(self, x)
nn.ReplicationPad3dclassSame as PyTorch
ReplicationPad3d(padding, value=0.0)

Same as PyTorch’s torch.nn.ReplicationPad3d.

1 methods and properties defined on ReplicationPad3d
  • forward(self, x)
nn.ZeroPad1dclassSame as PyTorch
ZeroPad1d(padding, _nd=1)

Same as PyTorch’s torch.nn.ZeroPad1d.

nn.ZeroPad2dclassSame as PyTorch
ZeroPad2d(padding, _nd=2)

Same as PyTorch’s torch.nn.ZeroPad2d.

nn.ZeroPad3dclassSame as PyTorch
ZeroPad3d(padding, _nd=3)

Same as PyTorch’s torch.nn.ZeroPad3d.

Non-linear activations

nn.AdaptiveLogSoftmaxWithLossclassSame as PyTorch
AdaptiveLogSoftmaxWithLoss(in_features, n_classes, cutoffs, div_value=4.0, head_bias=False, device=None, dtype=None)

Efficient softmax approximation (Grave et al.): a head over the shortlist and one entry per cluster, and a two-layer projection per tail cluster.

4 methods and properties defined on AdaptiveLogSoftmaxWithLoss
  • forward(self, input_, target_)(output, loss): each row's log-probability of its target class, and the mean negative log likelihood.
  • log_prob(self, input)Log-probabilities of every class, (N, n_classes) (or (n_classes,) for one input).
  • predict(self, input)The most likely class of each row (argmax of log_prob).
  • reset_parameters(self)Re-initialises the head and every tail projection.
nn.CELUclassSame as PyTorch
CELU(alpha: float = 1.0, inplace: bool = False) -> None

nn.CELU: the module form of torch.nn.functional.celu; forward(*inputs) calls it with the arguments given at construction (alpha, inplace).

celu: max(0, x) + min(0, alpha * (exp(x / alpha) - 1)). Dtypes: float32, float64, float16 and bfloat16 (autograd for the floating-point types).

2 methods and properties defined on CELU
  • extra_repr(self)
  • forward(self, *xs)Calls the layer's function on the inputs with the arguments given at construction (and training= following train / eval where the function takes it).
nn.ELUclassSame as PyTorch
ELU(alpha: float = 1.0, inplace: bool = False) -> None

nn.ELU: the module form of torch.nn.functional.elu; forward(*inputs) calls it with the arguments given at construction (alpha, inplace).

elu: x for x > 0, alpha * (exp(x) - 1) otherwise. Dtypes: float32, float64, float16 and bfloat16 (autograd for the floating-point types).

2 methods and properties defined on ELU
  • extra_repr(self)
  • forward(self, *xs)Calls the layer's function on the inputs with the arguments given at construction (and training= following train / eval where the function takes it).
nn.GELUclassSame as PyTorch
GELU(approximate: str = 'none') -> None

nn.GELU: the module form of torch.nn.functional.gelu; forward(*inputs) calls it with the arguments given at construction (approximate).

gelu: approximate="tanh": 0.5 x (1 + tanh(sqrt(2/pi) (x + 0.044715 x^3))).

2 methods and properties defined on GELU
  • extra_repr(self)
  • forward(self, *xs)Calls the layer's function on the inputs with the arguments given at construction (and training= following train / eval where the function takes it).
nn.GLUclassSame as PyTorch
GLU(dim: int = -1) -> None

nn.GLU: the module form of torch.nn.functional.glu; forward(*inputs) calls it with the arguments given at construction (dim).

glu: a * sigmoid(b), with a and b the two halves of input along dim. Dtypes: float32, float64, float16 and bfloat16 (autograd for the floating-point types).

2 methods and properties defined on GLU
  • extra_repr(self)
  • forward(self, *xs)Calls the layer's function on the inputs with the arguments given at construction (and training= following train / eval where the function takes it).
nn.HardshrinkclassSame as PyTorch
Hardshrink(lambd: float = 0.5) -> None

nn.Hardshrink: the module form of torch.nn.functional.hardshrink; forward(*inputs) calls it with the arguments given at construction (lambd).

hardshrink: x where |x| > lambd, else 0. Dtypes: float32, float64, float16 and bfloat16 (autograd for the floating-point types).

2 methods and properties defined on Hardshrink
  • extra_repr(self)
  • forward(self, *xs)Calls the layer's function on the inputs with the arguments given at construction (and training= following train / eval where the function takes it).
nn.HardsigmoidclassSame as PyTorch
Hardsigmoid(inplace: bool = False) -> None

nn.Hardsigmoid: the module form of torch.nn.functional.hardsigmoid; forward(*inputs) calls it with the arguments given at construction (inplace).

hardsigmoid: relu6(x + 3) / 6. Dtypes: float32, float64, float16 and bfloat16 (autograd for the floating-point types).

2 methods and properties defined on Hardsigmoid
  • extra_repr(self)
  • forward(self, *xs)Calls the layer's function on the inputs with the arguments given at construction (and training= following train / eval where the function takes it).
nn.HardswishclassSame as PyTorch
Hardswish(inplace: bool = False) -> None

nn.Hardswish: the module form of torch.nn.functional.hardswish; forward(*inputs) calls it with the arguments given at construction (inplace).

hardswish: x * relu6(x + 3) / 6. Dtypes: float32, float64, float16 and bfloat16 (autograd for the floating-point types).

2 methods and properties defined on Hardswish
  • extra_repr(self)
  • forward(self, *xs)Calls the layer's function on the inputs with the arguments given at construction (and training= following train / eval where the function takes it).
nn.HardtanhclassSame as PyTorch
Hardtanh(min_val: float = -1.0, max_val: float = 1.0, inplace: bool = False, min_value: float | None = None, max_value: float | None = None) -> None

nn.Hardtanh: the module form of torch.nn.functional.hardtanh; forward(*inputs) calls it with the arguments given at construction (min_val, max_val, inplace).

2 methods and properties defined on Hardtanh
  • extra_repr(self)
  • forward(self, *a, **k)Calls the layer's function on the inputs with the arguments given at construction (and training= following train / eval where the function takes it). A quantized input runs the quantized kernel (same parameters).
nn.LeakyReLUclassSame as PyTorch
LeakyReLU(negative_slope: float = 0.01, inplace: bool = False) -> None

nn.LeakyReLU: the module form of torch.nn.functional.leaky_relu; forward(*inputs) calls it with the arguments given at construction (negative_slope, inplace).

leaky_relu: max(x, 0) + negative_slope * min(x, 0). Dtypes: float32, float64, float16 and bfloat16 (autograd for the floating-point types).

2 methods and properties defined on LeakyReLU
  • extra_repr(self)
  • forward(self, *xs)Calls the layer's function on the inputs with the arguments given at construction (and training= following train / eval where the function takes it).
nn.LogSigmoidclassSame as PyTorch
LogSigmoid(*args: Any, **kwargs: Any) -> None

nn.LogSigmoid: the module form of torch.nn.functional.logsigmoid; forward(*inputs) calls it with the arguments given at construction.

logsigmoid: log(sigmoid(x)), computed stably. Dtypes: float32, float64, float16 and bfloat16 (autograd for the floating-point types).

2 methods and properties defined on LogSigmoid
  • extra_repr(self)
  • forward(self, *xs)Calls the layer's function on the inputs with the arguments given at construction (and training= following train / eval where the function takes it).
nn.LogSoftmaxclassSame as PyTorch
LogSoftmax(dim: int | None = None) -> None

nn.LogSoftmax: the module form of torch.nn.functional.log_softmax; forward(*inputs) calls it with the arguments given at construction (dim).

log_softmax: log(softmax(x)) along dim, computed stably (x - logsumexp); dtype= casts the input first. Dtypes: float32, float64, float16 and bfloat16 (autograd for the floating-point types).

2 methods and properties defined on LogSoftmax
  • extra_repr(self)
  • forward(self, *xs)Calls the layer's function on the inputs with the arguments given at construction (and training= following train / eval where the function takes it).
nn.MishclassSame as PyTorch
Mish(inplace: bool = False) -> None

nn.Mish: the module form of torch.nn.functional.mish; forward(*inputs) calls it with the arguments given at construction (inplace).

mish: x * tanh(softplus(x)). Dtypes: float32, float64, float16 and bfloat16 (autograd for the floating-point types).

2 methods and properties defined on Mish
  • extra_repr(self)
  • forward(self, *xs)Calls the layer's function on the inputs with the arguments given at construction (and training= following train / eval where the function takes it).
nn.MultiheadAttentionclassSame as PyTorch
MultiheadAttention(embed_dim, num_heads, dropout=0.0, bias=True, add_bias_kv=False, add_zero_attn=False, kdim=None, vdim=None, batch_first=False, device=None, dtype=None)

nn.MultiheadAttention: multi-head attention with PyTorch's parameters (in_proj_weight or separate q / k / v weights, out_proj, bias_k / bias_v, add_zero_attn).

1 methods and properties defined on MultiheadAttention
  • forward(self, query, key, value, key_padding_mask=None, need_weights=True, attn_mask=None, average_attn_weights=True, is_causal=False)Attention of query over key / value: returns (output, attention weights: averaged over heads unless average_attn_weights=False, None with need_weights=False).
nn.PReLUclassSame as PyTorch
PReLU(num_parameters=1, init=0.25, device=None, dtype=None)

nn.PReLU: a learnable negative slope (num_parameters of them, initialised to init) applied with F.prelu.

1 methods and properties defined on PReLU
  • forward(self, x)F.prelu(x, weight).
nn.ReLUclassSame as PyTorch
ReLU(inplace: bool = False) -> None

nn.ReLU: the module form of torch.nn.functional.relu; forward(*inputs) calls it with the arguments given at construction (inplace).

relu: max(x, 0). Dtypes: float32, float64, float16 and bfloat16 (autograd for the floating-point types).

2 methods and properties defined on ReLU
  • extra_repr(self)
  • forward(self, *a, **k)Calls the layer's function on the inputs with the arguments given at construction (and training= following train / eval where the function takes it). A quantized input runs the quantized kernel (same parameters).
nn.ReLU6classSame as PyTorch
ReLU6(inplace: bool = False) -> None

nn.ReLU6: the module form of torch.nn.functional.relu6; forward(*inputs) calls it with the arguments given at construction (inplace).

relu6: min(max(x, 0), 6). Dtypes: float32, float64, float16 and bfloat16 (autograd for the floating-point types).

2 methods and properties defined on ReLU6
  • extra_repr(self)
  • forward(self, *a, **k)Calls the layer's function on the inputs with the arguments given at construction (and training= following train / eval where the function takes it). A quantized input runs the quantized kernel (same parameters).
nn.RReLUclassSame as PyTorch
RReLU(lower: float = 0.125, upper: float = 0.3333333333333333, inplace: bool = False) -> None

Same as PyTorch’s torch.nn.RReLU.

1 methods and properties defined on RReLU
  • forward(self, *inputs)
nn.SELUclassSame as PyTorch
SELU(inplace: bool = False) -> None

nn.SELU: the module form of torch.nn.functional.selu; forward(*inputs) calls it with the arguments given at construction (inplace).

selu: scale * elu(x, alpha) with the SELU constants. Dtypes: float32, float64, float16 and bfloat16 (autograd for the floating-point types).

2 methods and properties defined on SELU
  • extra_repr(self)
  • forward(self, *xs)Calls the layer's function on the inputs with the arguments given at construction (and training= following train / eval where the function takes it).
nn.SigmoidclassSame as PyTorch
Sigmoid(*args: Any, **kwargs: Any) -> None

nn.Sigmoid: the module form of torch.nn.functional.sigmoid_fn; forward(*inputs) calls it with the arguments given at construction.

sigmoid_fn: sigmoid(Tensor input) -> Tensor

2 methods and properties defined on Sigmoid
  • extra_repr(self)
  • forward(self, *xs)Calls the layer's function on the inputs with the arguments given at construction (and training= following train / eval where the function takes it).
nn.SiLUclassSame as PyTorch
SiLU(inplace: bool = False) -> None

nn.SiLU: the module form of torch.nn.functional.silu; forward(*inputs) calls it with the arguments given at construction (inplace).

2 methods and properties defined on SiLU
  • extra_repr(self)
  • forward(self, *xs)Calls the layer's function on the inputs with the arguments given at construction (and training= following train / eval where the function takes it).
nn.SoftmaxclassSame as PyTorch
Softmax(dim: int | None = None) -> None

nn.Softmax: the module form of torch.nn.functional.softmax; forward(*inputs) calls it with the arguments given at construction (dim).

2 methods and properties defined on Softmax
  • extra_repr(self)
  • forward(self, *xs)Calls the layer's function on the inputs with the arguments given at construction (and training= following train / eval where the function takes it).
nn.Softmax2dclassSame as PyTorch
Softmax2d(*args: Any, **kwargs: Any) -> None

Same as PyTorch’s torch.nn.Softmax2d.

1 methods and properties defined on Softmax2d
  • forward(self, *inputs)
nn.SoftminclassSame as PyTorch
Softmin(dim: int | None = None) -> None

nn.Softmin: the module form of torch.nn.functional.softmin; forward(*inputs) calls it with the arguments given at construction (dim).

softmin: softmax(-x) along dim. Dtypes: float32, float64, float16 and bfloat16 (autograd for the floating-point types).

2 methods and properties defined on Softmin
  • extra_repr(self)
  • forward(self, *xs)Calls the layer's function on the inputs with the arguments given at construction (and training= following train / eval where the function takes it).
nn.SoftplusclassSame as PyTorch
Softplus(beta: float = 1.0, threshold: float = 20.0) -> None

nn.Softplus: the module form of torch.nn.functional.softplus; forward(*inputs) calls it with the arguments given at construction (beta, threshold).

softplus: log(1 + exp(beta * x)) / beta, linear above threshold. Dtypes: float32, float64, float16 and bfloat16 (autograd for the floating-point types).

2 methods and properties defined on Softplus
  • extra_repr(self)
  • forward(self, *xs)Calls the layer's function on the inputs with the arguments given at construction (and training= following train / eval where the function takes it).
nn.SoftshrinkclassSame as PyTorch
Softshrink(lambd: float = 0.5) -> None

nn.Softshrink: the module form of torch.nn.functional.softshrink; forward(*inputs) calls it with the arguments given at construction (lambd).

softshrink: x - lambd above lambd, x + lambd below -lambd, else 0. Dtypes: float32, float64, float16 and bfloat16 (autograd for the floating-point types).

2 methods and properties defined on Softshrink
  • extra_repr(self)
  • forward(self, *xs)Calls the layer's function on the inputs with the arguments given at construction (and training= following train / eval where the function takes it).
nn.SoftsignclassSame as PyTorch
Softsign(*args: Any, **kwargs: Any) -> None

nn.Softsign: the module form of torch.nn.functional.softsign; forward(*inputs) calls it with the arguments given at construction.

softsign: x / (1 + |x|). Dtypes: float32, float64, float16 and bfloat16 (autograd for the floating-point types).

2 methods and properties defined on Softsign
  • extra_repr(self)
  • forward(self, *xs)Calls the layer's function on the inputs with the arguments given at construction (and training= following train / eval where the function takes it).
nn.TanhclassSame as PyTorch
Tanh(*args: Any, **kwargs: Any) -> None

nn.Tanh: the module form of torch.nn.functional.tanh; forward(*inputs) calls it with the arguments given at construction.

2 methods and properties defined on Tanh
  • extra_repr(self)
  • forward(self, *xs)Calls the layer's function on the inputs with the arguments given at construction (and training= following train / eval where the function takes it).
nn.TanhshrinkclassSame as PyTorch
Tanhshrink(*args: Any, **kwargs: Any) -> None

nn.Tanhshrink: the module form of torch.nn.functional.tanhshrink; forward(*inputs) calls it with the arguments given at construction.

tanhshrink: x - tanh(x). Dtypes: float32, float64, float16 and bfloat16 (autograd for the floating-point types).

2 methods and properties defined on Tanhshrink
  • extra_repr(self)
  • forward(self, *xs)Calls the layer's function on the inputs with the arguments given at construction (and training= following train / eval where the function takes it).
nn.TemperatureclassRiptorch extra
Temperature(s0=None)

A learned temperature for one layer: a scalar parameter s and, by riptorch.set_maths(temperature=...), T = 1 + s^2 ("learned", order 2, T >= 1) or 1/T = 1 + s + s^2/2 ("learned_inv", 1/T >= 1/2). Calling it gives the tensor 1/T; pass the module as temperature= to F.cross_entropy or F.scaled_dot_product_attention. s starts at s0 (T = 1 + s0^2): at s = 0 exactly, 1 + s^2 has zero gradient and s would never move.

Riptorch extra: not in stock PyTorch.

2 methods and properties defined on Temperature
  • forward(self)1/T as a tensor: 1 / (1 + s^2) (learned) or 1 + s + s^2/2 (learned_inv).
  • value(self)T now (host arithmetic, for logs).
nn.ThresholdclassSame as PyTorch
Threshold(threshold: float, value: float, inplace: bool = False) -> None

nn.Threshold: the module form of torch.nn.functional.threshold; forward(*inputs) calls it with the arguments given at construction (threshold, value, inplace).

threshold: x where x > threshold, else value. Dtypes: float32, float64, float16 and bfloat16 (autograd for the floating-point types).

2 methods and properties defined on Threshold
  • extra_repr(self)
  • forward(self, *xs)Calls the layer's function on the inputs with the arguments given at construction (and training= following train / eval where the function takes it).

Normalization layers

nn.BatchNorm1dclassSame as PyTorch
BatchNorm1d(num_features, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True, device=None, dtype=None)

nn.BatchNorm1d: batch norm over (N, C) or (N, C, L) input.

nn.BatchNorm2dclassSame as PyTorch
BatchNorm2d(num_features, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True, device=None, dtype=None)

nn.BatchNorm2d: batch norm over (N, C, H, W) input.

nn.BatchNorm3dclassSame as PyTorch
BatchNorm3d(num_features, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True, device=None, dtype=None)

nn.BatchNorm3d: batch norm over (N, C, D, H, W) input.

nn.GroupNormclassSame as PyTorch
GroupNorm(num_groups, num_channels, eps=1e-05, affine=True, device=None, dtype=None)

nn.GroupNorm: F.group_norm with learnable per-channel weight (ones) and bias (zeros) when affine.

1 methods and properties defined on GroupNorm
  • forward(self, x)F.group_norm of x.
nn.InstanceNorm1dclassSame as PyTorch
InstanceNorm1d(num_features, eps=1e-05, momentum=0.1, affine=False, track_running_stats=False, device=None, dtype=None)

nn.InstanceNorm1d: instance norm over (N, C, L) or unbatched (C, L) input.

nn.InstanceNorm2dclassSame as PyTorch
InstanceNorm2d(num_features, eps=1e-05, momentum=0.1, affine=False, track_running_stats=False, device=None, dtype=None)

nn.InstanceNorm2d: instance norm over (N, C, H, W) or unbatched (C, H, W) input.

nn.InstanceNorm3dclassSame as PyTorch
InstanceNorm3d(num_features, eps=1e-05, momentum=0.1, affine=False, track_running_stats=False, device=None, dtype=None)

nn.InstanceNorm3d: instance norm over (N, C, D, H, W) or unbatched input.

nn.LayerNormclassSame as PyTorch
LayerNorm(normalized_shape, eps=1e-05, elementwise_affine=True, bias=True, device=None, dtype=None)

nn.LayerNorm: normalized_shape an int or a shape (the last dims); weight ones / bias zeros of that shape.

2 methods and properties defined on LayerNorm
  • extra_repr(self)normalized_shape, eps and elementwise_affine.
  • forward(self, x)F.layer_norm of x over normalized_shape.
nn.LazyBatchNorm1dclassSame as PyTorch
LazyBatchNorm1d(eps=1e-05, momentum=0.1, affine=True, track_running_stats=True, device=None, dtype=None, *, bias=True) -> None

Same as PyTorch’s torch.nn.LazyBatchNorm1d.

2 methods and properties defined on LazyBatchNorm1d
  • forward(self, x, *rest, **kw)
  • has_uninitialized_params(self)
nn.LazyBatchNorm2dclassSame as PyTorch
LazyBatchNorm2d(eps=1e-05, momentum=0.1, affine=True, track_running_stats=True, device=None, dtype=None, *, bias=True) -> None

Same as PyTorch’s torch.nn.LazyBatchNorm2d.

2 methods and properties defined on LazyBatchNorm2d
  • forward(self, x, *rest, **kw)
  • has_uninitialized_params(self)
nn.LazyBatchNorm3dclassSame as PyTorch
LazyBatchNorm3d(eps=1e-05, momentum=0.1, affine=True, track_running_stats=True, device=None, dtype=None, *, bias=True) -> None

Same as PyTorch’s torch.nn.LazyBatchNorm3d.

2 methods and properties defined on LazyBatchNorm3d
  • forward(self, x, *rest, **kw)
  • has_uninitialized_params(self)
nn.LazyInstanceNorm1dclassSame as PyTorch
LazyInstanceNorm1d(eps=1e-05, momentum=0.1, affine=True, track_running_stats=True, device=None, dtype=None, *, bias=True) -> None

Same as PyTorch’s torch.nn.LazyInstanceNorm1d.

2 methods and properties defined on LazyInstanceNorm1d
  • forward(self, x, *rest, **kw)
  • has_uninitialized_params(self)
nn.LazyInstanceNorm2dclassSame as PyTorch
LazyInstanceNorm2d(eps=1e-05, momentum=0.1, affine=True, track_running_stats=True, device=None, dtype=None, *, bias=True) -> None

Same as PyTorch’s torch.nn.LazyInstanceNorm2d.

2 methods and properties defined on LazyInstanceNorm2d
  • forward(self, x, *rest, **kw)
  • has_uninitialized_params(self)
nn.LazyInstanceNorm3dclassSame as PyTorch
LazyInstanceNorm3d(eps=1e-05, momentum=0.1, affine=True, track_running_stats=True, device=None, dtype=None, *, bias=True) -> None

Same as PyTorch’s torch.nn.LazyInstanceNorm3d.

2 methods and properties defined on LazyInstanceNorm3d
  • forward(self, x, *rest, **kw)
  • has_uninitialized_params(self)
nn.LocalResponseNormclassSame as PyTorch
LocalResponseNorm(size: int, alpha: float = 0.0001, beta: float = 0.75, k: float = 1.0) -> None

Same as PyTorch’s torch.nn.LocalResponseNorm.

1 methods and properties defined on LocalResponseNorm
  • forward(self, *inputs)
nn.RMSNormclassSame as PyTorch
RMSNorm(normalized_shape, eps=None, elementwise_affine=True, device=None, dtype=None)

nn.RMSNorm: F.rms_norm over the last dims with a learnable weight (ones).

1 methods and properties defined on RMSNorm
  • forward(self, x)F.rms_norm of x over normalized_shape.
nn.SyncBatchNormclassSame as PyTorch
SyncBatchNorm(num_features, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True, device=None, dtype=None)

nn.BatchNorm2d: batch norm over (N, C, H, W) input.

Recurrent layers

nn.GRUclassSame as PyTorch
GRU(input_size, hidden_size, num_layers=1, bias=True, batch_first=False, dropout=0.0, bidirectional=False, proj_size=0, device=None, dtype=None, nonlinearity='tanh', mode=None)

nn.GRU: a multi-layer gated recurrent unit.

1 methods and properties defined on GRU
  • forward(self, input, hx=None, **kw)Runs the sequence (seq-first unless batch_first; unbatched 2-d input too); returns (output, h_n) or, for LSTM, (output, (h_n, c_n)).
nn.GRUCellclassSame as PyTorch
GRUCell(input_size, hidden_size, bias=True, nonlinearity='tanh', device=None, dtype=None)

nn.GRUCell: one GRU step.

nn.LSTMclassSame as PyTorch
LSTM(input_size, hidden_size, num_layers=1, bias=True, batch_first=False, dropout=0.0, bidirectional=False, proj_size=0, device=None, dtype=None, nonlinearity='tanh', mode=None)

nn.LSTM: a multi-layer long short-term memory RNN; forward(input, (h0, c0)) returns (output, (h_n, c_n)).

1 methods and properties defined on LSTM
  • forward(self, input, hx=None, **kw)Runs the sequence (seq-first unless batch_first; unbatched 2-d input too); returns (output, h_n) or, for LSTM, (output, (h_n, c_n)).
nn.LSTMCellclassSame as PyTorch
LSTMCell(input_size, hidden_size, bias=True, nonlinearity='tanh', device=None, dtype=None)

nn.LSTMCell: one LSTM step; returns (h, c).

nn.RNNclassSame as PyTorch
RNN(input_size, hidden_size, num_layers=1, bias=True, batch_first=False, dropout=0.0, bidirectional=False, proj_size=0, device=None, dtype=None, nonlinearity='tanh', mode=None)

nn.RNN: a multi-layer Elman RNN with tanh or relu.

1 methods and properties defined on RNN
  • forward(self, input, hx=None, **kw)Runs the sequence (seq-first unless batch_first; unbatched 2-d input too); returns (output, h_n) or, for LSTM, (output, (h_n, c_n)).
nn.RNNBaseclassDifferent from PyTorch
RNNBase(input_size, hidden_size, num_layers=1, bias=True, batch_first=False, dropout=0.0, bidirectional=False, proj_size=0, device=None, dtype=None, nonlinearity='tanh', mode=None)

The base of nn.RNN / LSTM / GRU: stacked (optionally bidirectional) layers with PyTorch's parameter names and U(-k, k) init, k = 1 / sqrt(hidden_size); proj_size and PackedSequence input raise NotImplementedError.

Different from PyTorch: The base of nn.RNN / LSTM / GRU: stacked (optionally bidirectional) layers with PyTorch's parameter names and U(-k, k) init, k = 1 / sqrt(hidden_size); proj_size and PackedSequence input raise NotImplementedError.

3 methods and properties defined on RNNBase
  • extra_repr(self)input_size, hidden_size and the non-default options.
  • flatten_parameters(self)Does nothing (no cuDNN weight buffer).
  • forward(self, input, hx=None, *, maths=None)Runs the sequence (seq-first unless batch_first; unbatched 2-d input too); returns (output, h_n) or, for LSTM, (output, (h_n, c_n)).
nn.RNNCellclassSame as PyTorch
RNNCell(input_size, hidden_size, bias=True, nonlinearity='tanh', device=None, dtype=None)

nn.RNNCell: one Elman RNN step with tanh or relu.

nn.RNNCellBaseclassSame as PyTorch
RNNCellBase(input_size, hidden_size, bias=True, nonlinearity='tanh', device=None, dtype=None)

The base of nn.RNNCell / LSTMCell / GRUCell: one time step with weight_ih, weight_hh and biases.

1 methods and properties defined on RNNCellBase
  • forward(self, input, hx=None)One step: the new h (RNN, GRU) or (h, c) (LSTM); unbatched 1-d input too.

Transformer layers

nn.TransformerclassSame as PyTorch
Transformer(d_model=512, nhead=8, num_encoder_layers=6, num_decoder_layers=6, dim_feedforward=2048, dropout=0.1, activation='relu', custom_encoder=None, custom_decoder=None, layer_norm_eps=1e-05, batch_first=False, norm_first=False, bias=True, device=None, dtype=None)

The encoder-decoder Transformer (Vaswani et al.): an encoder and a decoder stack with final norms; weights of rank > 1 initialised Xavier-uniform.

2 methods and properties defined on Transformer
  • forward(self, src, tgt, src_mask=None, tgt_mask=None, memory_mask=None, src_key_padding_mask=None, tgt_key_padding_mask=None, memory_key_padding_mask=None, src_is_causal=None, tgt_is_causal=None, memory_is_causal=False)Encodes src, then decodes tgt against it; returns the decoder output.
  • generate_square_subsequent_mask(sz, device=None, dtype=None)An (sz, sz) causal mask: -inf above the diagonal, 0 on and below it.
nn.TransformerDecoderclassSame as PyTorch
TransformerDecoder(decoder_layer, num_layers, norm=None)

num_layers copies of a decoder layer, then an optional norm.

1 methods and properties defined on TransformerDecoder
  • forward(self, tgt, memory, tgt_mask=None, memory_mask=None, tgt_key_padding_mask=None, memory_key_padding_mask=None, tgt_is_causal=None, memory_is_causal=False)Runs tgt through every layer against memory (then the norm).
nn.TransformerDecoderLayerclassSame as PyTorch
TransformerDecoderLayer(d_model, nhead, dim_feedforward=2048, dropout=0.1, activation='relu', layer_norm_eps=1e-05, batch_first=False, norm_first=False, bias=True, device=None, dtype=None)

Self-attention, attention over the encoder memory, then a feed-forward block, each with a residual connection and LayerNorm (norm_first puts the norm first).

1 methods and properties defined on TransformerDecoderLayer
  • forward(self, tgt, memory, tgt_mask=None, memory_mask=None, tgt_key_padding_mask=None, memory_key_padding_mask=None, tgt_is_causal=False, memory_is_causal=False)Decodes tgt against memory with the given masks.
nn.TransformerEncoderclassSame as PyTorch
TransformerEncoder(encoder_layer, num_layers, norm=None, enable_nested_tensor=True, mask_check=True)

num_layers copies of an encoder layer, then an optional norm.

1 methods and properties defined on TransformerEncoder
  • forward(self, src, mask=None, src_key_padding_mask=None, is_causal=None)Runs src through every layer (then the norm).
nn.TransformerEncoderLayerclassSame as PyTorch
TransformerEncoderLayer(d_model, nhead, dim_feedforward=2048, dropout=0.1, activation='relu', layer_norm_eps=1e-05, batch_first=False, norm_first=False, bias=True, device=None, dtype=None)

Self-attention then a feed-forward block, each with a residual connection and LayerNorm (norm_first puts the norm before each block). Layout (S, N, E), or (N, S, E) with batch_first.

1 methods and properties defined on TransformerEncoderLayer
  • forward(self, src, src_mask=None, src_key_padding_mask=None, is_causal=False)Encodes src; src_mask / src_key_padding_mask / is_causal go to the self-attention.

Linear layers

nn.BilinearclassSame as PyTorch
Bilinear(in1_features, in2_features, out_features, bias=True, device=None, dtype=None)

y = x1^T W x2 + b; weight (out, in1, in2) and bias uniform in +-1/sqrt(in1), as PyTorch.

1 methods and properties defined on Bilinear
  • forward(self, a, b)F.bilinear(a, b, weight, bias).
nn.IdentityclassSame as PyTorch
Identity(*args: Any, **kwargs: Any) -> None

nn.Identity: returns its input; constructor arguments are accepted and ignored, as in PyTorch.

1 methods and properties defined on Identity
  • forward(self, *a, **k)The module's forward. A quantized input runs the quantized kernel (same parameters).
nn.LazyLinearclassSame as PyTorch
LazyLinear(out_features: int, bias: bool = True, device=None, dtype=None) -> None

Same as PyTorch’s torch.nn.LazyLinear.

2 methods and properties defined on LazyLinear
  • forward(self, x, *rest, **kw)
  • has_uninitialized_params(self)
nn.LinearclassSame as PyTorch
Linear(in_features, out_features, bias=True)

y = x @ W.T + b, W shape (out, in), as in torch.nn.Linear.

1 methods and properties defined on Linear
  • forward(self, x)x @ weight.T + bias (one F.linear); a 1-d x gives a 1-d result.

Dropout layers

nn.AlphaDropoutclassSame as PyTorch
AlphaDropout(p: float = 0.5, inplace: bool = False) -> None

Same as PyTorch’s torch.nn.AlphaDropout.

1 methods and properties defined on AlphaDropout
  • forward(self, *inputs)
nn.DropoutclassSame as PyTorch
Dropout(p: float = 0.5, inplace: bool = False) -> None

nn.Dropout: the module form of torch.nn.functional.dropout; forward(*inputs) calls it with the arguments given at construction (p, inplace), and training= following train / eval.

dropout: nn.Dropout passes training=self.training. The kept fraction and scale match PyTorch; the mask bits don't.

2 methods and properties defined on Dropout
  • extra_repr(self)
  • forward(self, *a, **k)Calls the layer's function on the inputs with the arguments given at construction (and training= following train / eval where the function takes it). A quantized input runs the quantized kernel (same parameters).
nn.Dropout1dclassSame as PyTorch
Dropout1d(p: float = 0.5, inplace: bool = False) -> None

Same as PyTorch’s torch.nn.Dropout1d.

1 methods and properties defined on Dropout1d
  • forward(self, *inputs)
nn.Dropout2dclassSame as PyTorch
Dropout2d(p: float = 0.5, inplace: bool = False) -> None

Same as PyTorch’s torch.nn.Dropout2d.

1 methods and properties defined on Dropout2d
  • forward(self, *inputs)
nn.Dropout3dclassSame as PyTorch
Dropout3d(p: float = 0.5, inplace: bool = False) -> None

Same as PyTorch’s torch.nn.Dropout3d.

1 methods and properties defined on Dropout3d
  • forward(self, *inputs)
nn.FeatureAlphaDropoutclassSame as PyTorch
FeatureAlphaDropout(p: float = 0.5, inplace: bool = False) -> None

Same as PyTorch’s torch.nn.FeatureAlphaDropout.

1 methods and properties defined on FeatureAlphaDropout
  • forward(self, *inputs)

Sparse layers

nn.EmbeddingclassSame as PyTorch
Embedding(num_embeddings, embedding_dim, padding_idx=None, max_norm=None, norm_type=2.0, scale_grad_by_freq=False, sparse=False, _weight=None, _freeze=False, device=None, dtype=None)

nn.Embedding: weight ~ N(0, 1) (the padding row zeroed), forward = F.embedding.

2 methods and properties defined on Embedding
  • extra_repr(self)num_embeddings, embedding_dim (and padding_idx).
  • forward(self, input)The rows of weight at the indices in input (F.embedding with the stored options).
nn.EmbeddingBagclassSame as PyTorch
EmbeddingBag(num_embeddings, embedding_dim, max_norm=None, norm_type=2.0, scale_grad_by_freq=False, mode='mean', sparse=False, _weight=None, include_last_offset=False, padding_idx=None, device=None, dtype=None)

Embedding table whose forward reduces bags of indices (F.embedding_bag); weight ~ N(0, 1).

2 methods and properties defined on EmbeddingBag
  • forward(self, input, offsets=None, per_sample_weights=None)F.embedding_bag over input (2-d bags, or 1-d with offsets).
  • from_pretrained(embeddings, freeze=True, max_norm=None, norm_type=2.0, scale_grad_by_freq=False, mode='mean', sparse=False, include_last_offset=False, padding_idx=None)An EmbeddingBag holding embeddings as its weight (frozen unless freeze=False).

Distance functions

nn.CosineSimilarityclassSame as PyTorch
CosineSimilarity(dim: int = 1, eps: float = 1e-08) -> None

nn.CosineSimilarity: the module form of torch.nn.functional.cosine_similarity; forward(*inputs) calls it with the arguments given at construction (dim, eps).

2 methods and properties defined on CosineSimilarity
  • extra_repr(self)
  • forward(self, *xs)Calls the layer's function on the inputs with the arguments given at construction (and training= following train / eval where the function takes it).
nn.PairwiseDistanceclassSame as PyTorch
PairwiseDistance(p: float = 2.0, eps: float = 1e-06, keepdim: bool = False) -> None

nn.PairwiseDistance: the module form of torch.nn.functional.pairwise_distance; forward(*inputs) calls it with the arguments given at construction (p, eps, keepdim).

pairwise_distance: ||x1 - x2 + eps||_p along the last dim (PyTorch adds eps to the difference).

2 methods and properties defined on PairwiseDistance
  • extra_repr(self)
  • forward(self, *xs)Calls the layer's function on the inputs with the arguments given at construction (and training= following train / eval where the function takes it).

Loss functions

nn.BCELossclassSame as PyTorch
BCELoss(*args, reduction='mean', size_average=None, reduce=None, **kw)

nn.BCELoss: the loss as a module; forward calls the functional form with reduction and the constructor arguments.

1 methods and properties defined on BCELoss
  • forward(self, *xs)The loss of the inputs with the module's reduction and constructor arguments.
nn.BCEWithLogitsLossclassSame as PyTorch
BCEWithLogitsLoss(*args, reduction='mean', size_average=None, reduce=None, **kw)

nn.BCEWithLogitsLoss: the loss as a module; forward calls the functional form with reduction and the constructor arguments.

1 methods and properties defined on BCEWithLogitsLoss
  • forward(self, *xs)The loss of the inputs with the module's reduction and constructor arguments.
nn.CosineEmbeddingLossclassSame as PyTorch
CosineEmbeddingLoss(margin: float = 0.0, size_average=None, reduce=None, reduction: str = 'mean') -> None

Same as PyTorch’s torch.nn.CosineEmbeddingLoss.

1 methods and properties defined on CosineEmbeddingLoss
  • forward(self, *inputs)
nn.CrossEntropyLossclassDifferent from PyTorch
CrossEntropyLoss(weight: torch.Tensor | None = None, size_average=None, ignore_index: int = -100, reduce=None, reduction: str = 'mean', label_smoothing: float = 0.0) -> None

nn.CrossEntropyLoss: the module form of torch.nn.functional.cross_entropy; forward(*inputs) calls it with the arguments given at construction (ignore_index, reduction, label_smoothing).

cross_entropy: input [N, C] with class-index targets [N]; rows whose target is ignore_index count for nothing (the mean is over the other rows, as PyTorch). weight and label_smoothing raise NotImplementedError for now.

Different from PyTorch: nn.CrossEntropyLoss: the module form of torch.nn.functional.cross_entropy; forward(*inputs) calls it with the arguments given at construction (ignore_index, reduction, label_smoothing). cross_entropy: input [N, C] with class-index targets [N]; rows whose target is ignore_index count for nothing (the

2 methods and properties defined on CrossEntropyLoss
  • extra_repr(self)
  • forward(self, input, target)F.cross_entropy(input, target) with the loss's arguments (weight, ignore_index, reduction, label_smoothing); class indices or class probabilities as target.
nn.CTCLossclassSame as PyTorch
CTCLoss(blank: int = 0, reduction: str = 'mean', zero_infinity: bool = False) -> None

Same as PyTorch’s torch.nn.CTCLoss.

1 methods and properties defined on CTCLoss
  • forward(self, *inputs)
nn.GaussianNLLLossclassSame as PyTorch
GaussianNLLLoss(*, full: bool = False, eps: float = 1e-06, reduction: str = 'mean') -> None

Same as PyTorch’s torch.nn.GaussianNLLLoss.

1 methods and properties defined on GaussianNLLLoss
  • forward(self, *inputs)
nn.HingeEmbeddingLossclassSame as PyTorch
HingeEmbeddingLoss(margin: float = 1.0, size_average=None, reduce=None, reduction: str = 'mean') -> None

Same as PyTorch’s torch.nn.HingeEmbeddingLoss.

1 methods and properties defined on HingeEmbeddingLoss
  • forward(self, *inputs)
nn.HuberLossclassSame as PyTorch
HuberLoss(*args, reduction='mean', size_average=None, reduce=None, **kw)

nn.HuberLoss: the loss as a module; forward calls the functional form with reduction and the constructor arguments.

1 methods and properties defined on HuberLoss
  • forward(self, *xs)The loss of the inputs with the module's reduction and constructor arguments.
nn.KLDivLossclassSame as PyTorch
KLDivLoss(*args, reduction='mean', size_average=None, reduce=None, **kw)

nn.KLDivLoss: the loss as a module; forward calls the functional form with reduction and the constructor arguments.

1 methods and properties defined on KLDivLoss
  • forward(self, *xs)The loss of the inputs with the module's reduction and constructor arguments.
nn.L1LossclassSame as PyTorch
L1Loss(*args, reduction='mean', size_average=None, reduce=None, **kw)

nn.L1Loss: the loss as a module; forward calls the functional form with reduction and the constructor arguments.

1 methods and properties defined on L1Loss
  • forward(self, *xs)The loss of the inputs with the module's reduction and constructor arguments.
nn.LinearCrossEntropyLossclassSame as PyTorch
LinearCrossEntropyLoss(in_features, num_classes, *, out_features=(), bias=False, device=None, dtype=None, reduction='mean', weight=None, ignore_index=None, label_smoothing=0.0, options=None)

Cross entropy of a linear layer's logits (in_features -> num_classes * prod(out_features)).

2 methods and properties defined on LinearCrossEntropyLoss
  • extra_repr(self)The module's settings for the repr.
  • forward(self, input, target)Cross-entropy of linear(input) against target, chunked by options when given.
nn.MarginRankingLossclassSame as PyTorch
MarginRankingLoss(*args, reduction='mean', size_average=None, reduce=None, **kw)

nn.MarginRankingLoss: the loss as a module; forward calls the functional form with reduction and the constructor arguments.

1 methods and properties defined on MarginRankingLoss
  • forward(self, *xs)The loss of the inputs with the module's reduction and constructor arguments.
nn.MSELossclassSame as PyTorch
MSELoss(size_average=None, reduce=None, reduction: str = 'mean') -> None

Mean squared error, mean((a - b)^2).

1 methods and properties defined on MSELoss
  • forward(self, a, b)mean((a - b)^2) over every element.
nn.MultiLabelMarginLossclassSame as PyTorch
MultiLabelMarginLoss(size_average=None, reduce=None, reduction: str = 'mean') -> None

Same as PyTorch’s torch.nn.MultiLabelMarginLoss.

1 methods and properties defined on MultiLabelMarginLoss
  • forward(self, *inputs)
nn.MultiLabelSoftMarginLossclassSame as PyTorch
MultiLabelSoftMarginLoss(weight: torch.Tensor | None = None, size_average=None, reduce=None, reduction: str = 'mean') -> None

Same as PyTorch’s torch.nn.MultiLabelSoftMarginLoss.

1 methods and properties defined on MultiLabelSoftMarginLoss
  • forward(self, *inputs)
nn.MultiMarginLossclassSame as PyTorch
MultiMarginLoss(p: int = 1, margin: float = 1.0, weight: torch.Tensor | None = None, size_average=None, reduce=None, reduction: str = 'mean') -> None

Same as PyTorch’s torch.nn.MultiMarginLoss.

1 methods and properties defined on MultiMarginLoss
  • forward(self, *inputs)
nn.NLLLossclassSame as PyTorch
NLLLoss(weight: torch.Tensor | None = None, size_average=None, ignore_index: int = -100, reduce=None, reduction: str = 'mean') -> None

Same as PyTorch’s torch.nn.NLLLoss.

1 methods and properties defined on NLLLoss
  • forward(self, *inputs)
nn.PoissonNLLLossclassSame as PyTorch
PoissonNLLLoss(log_input: bool = True, full: bool = False, size_average=None, eps: float = 1e-08, reduce=None, reduction: str = 'mean') -> None

Same as PyTorch’s torch.nn.PoissonNLLLoss.

1 methods and properties defined on PoissonNLLLoss
  • forward(self, *inputs)
nn.SmoothL1LossclassSame as PyTorch
SmoothL1Loss(*args, reduction='mean', size_average=None, reduce=None, **kw)

nn.SmoothL1Loss: the loss as a module; forward calls the functional form with reduction and the constructor arguments.

1 methods and properties defined on SmoothL1Loss
  • forward(self, *xs)The loss of the inputs with the module's reduction and constructor arguments.
nn.SoftMarginLossclassSame as PyTorch
SoftMarginLoss(*args, reduction='mean', size_average=None, reduce=None, **kw)

nn.SoftMarginLoss: the loss as a module; forward calls the functional form with reduction and the constructor arguments.

1 methods and properties defined on SoftMarginLoss
  • forward(self, *xs)The loss of the inputs with the module's reduction and constructor arguments.
nn.TripletMarginLossclassSame as PyTorch
TripletMarginLoss(margin: float = 1.0, p: float = 2.0, eps: float = 1e-06, swap: bool = False, size_average=None, reduce=None, reduction: str = 'mean') -> None

Same as PyTorch’s torch.nn.TripletMarginLoss.

1 methods and properties defined on TripletMarginLoss
  • forward(self, *inputs)
TripletMarginWithDistanceLoss(*, distance_function: collections.abc.Callable[[torch.Tensor, torch.Tensor], torch.Tensor] | None = None, margin: float = 1.0, swap: bool = False, reduction: str = 'mean') -> None

Same as PyTorch’s torch.nn.TripletMarginWithDistanceLoss.

1 methods and properties defined on TripletMarginWithDistanceLoss
  • forward(self, *inputs)

Vision layers

nn.ChannelShuffleclassSame as PyTorch
ChannelShuffle(groups: int) -> None

Same as PyTorch’s torch.nn.ChannelShuffle.

1 methods and properties defined on ChannelShuffle
  • forward(self, *inputs)
nn.PixelShuffleclassSame as PyTorch
PixelShuffle(upscale_factor: int) -> None

nn.PixelShuffle: the module form of torch.nn.functional.pixel_shuffle; forward(*inputs) calls it with the arguments given at construction (upscale_factor).

pixel_shuffle: Rearranges (C r^2, H, W) to (C, H r, W r). Dtypes: float32, float64, float16 and bfloat16 (autograd for the floating-point types).

2 methods and properties defined on PixelShuffle
  • extra_repr(self)
  • forward(self, *xs)Calls the layer's function on the inputs with the arguments given at construction (and training= following train / eval where the function takes it).
nn.PixelUnshuffleclassSame as PyTorch
PixelUnshuffle(downscale_factor: int) -> None

nn.PixelUnshuffle: the module form of torch.nn.functional.pixel_unshuffle; forward(*inputs) calls it with the arguments given at construction (downscale_factor).

pixel_unshuffle: Rearranges (C, H r, W r) to (C r^2, H, W). Dtypes: float32, float64, float16 and bfloat16 (autograd for the floating-point types).

2 methods and properties defined on PixelUnshuffle
  • extra_repr(self)
  • forward(self, *xs)Calls the layer's function on the inputs with the arguments given at construction (and training= following train / eval where the function takes it).
nn.UpsampleclassSame as PyTorch
Upsample(size=None, scale_factor=None, mode='nearest', align_corners=None, recompute_scale_factor=None)

nn.Upsample: F.interpolate with the stored size or scale_factor, mode and align_corners.

2 methods and properties defined on Upsample
  • extra_repr(self)scale_factor (or size) and mode.
  • forward(self, x)F.interpolate of x with the stored arguments.
nn.UpsamplingBilinear2dclassSame as PyTorch
UpsamplingBilinear2d(size=None, scale_factor=None)

nn.UpsamplingBilinear2d: Upsample with mode "bilinear" and align_corners=True.

nn.UpsamplingNearest2dclassSame as PyTorch
UpsamplingNearest2d(size=None, scale_factor=None)

nn.UpsamplingNearest2d: Upsample with mode "nearest".

Utilities

nn.clip_grad_norm_functionRiptorch extra
clip_grad_norm_(parameters, max_norm, norm_type=2.0, error_if_nonfinite=False, foreach=None)

Scales the gradients so their combined 2-norm is at most max_norm; returns the norm before scaling. In rational maths (riptorch.set_maths("rational")) it compares quadrances instead: scales by min(1, max_norm^2 / Q) and returns Q = |g|^2. Inside riptorch.compile it is part of the compiled step (no Python on replay).

Riptorch extra: not in stock PyTorch.

nn.factory_kwargsfunctionSame as PyTorch
factory_kwargs(kwargs)

The device / dtype / memory_format entries of kwargs (PyTorch's helper for module constructors).

nn.fan_in_valuesfunctionRiptorch extra
fan_in_values(rnd, n, fan_in)

n initial values with variance 1/(3 fan_in) (torch.nn.Linear's and Conv2d's). Classic maths: PyTorch's uniform(-k, k), k = 1/root(fan_in). Rational maths: (2B - m)/m with B the number of ones among m = 3 fan_in random bits (Binomial(m, 1/2)), whose variance is exactly 1/m. rnd: random.Random or the random module.

Riptorch extra: not in stock PyTorch.

nn.FlattenclassSame as PyTorch
Flatten(start_dim=1, end_dim=-1)

Flattens dims start_dim to end_dim (default: the last) into one.

2 methods and properties defined on Flatten
  • extra_repr(self)
  • forward(self, *a, **k)The module's forward. A quantized input runs the quantized kernel (same parameters).
nn.UnflattenclassSame as PyTorch
Unflatten(dim, unflattened_size)

Expands dim into unflattened_size (torch.unflatten as a module).

1 methods and properties defined on Unflatten
  • forward(self, x)torch.unflatten(x, dim, unflattened_size).

Initialisation (nn.init)

nn.init.calculate_gainfunctionSame as PyTorch
calculate_gain(nonlinearity, param=None)

The recommended gain for a nonlinearity: 1 (linear, conv, sigmoid), 5/3 (tanh), sqrt(2) (relu), sqrt(2 / (1 + slope^2)) (leaky_relu, param = slope, default 0.01), 3/4 (selu); ValueError otherwise.

nn.init.constantfunctionSame as PyTorch
constant(tensor, val)

Fills the tensor in place with val (Tensor.fill_ too). Every dtype.

nn.init.constant_functionSame as PyTorch
constant_(tensor, val)

Fills the tensor in place with val (Tensor.fill_ too). Every dtype.

nn.init.diracfunctionSame as PyTorch
dirac(*args: _P.args, **kwargs: _P.kwargs) -> ~_R

The identity convolution: in each group, output channel d takes input channel d at the kernel's centre.

nn.init.dirac_functionSame as PyTorch
dirac_(tensor, groups=1)

The identity convolution: in each group, output channel d takes input channel d at the kernel's centre.

nn.init.eyefunctionSame as PyTorch
eye(tensor)

Fills a 2-d tensor in place with the identity (ones on the diagonal). Dtypes: float32.

nn.init.eye_functionSame as PyTorch
eye_(tensor)

Fills a 2-d tensor in place with the identity (ones on the diagonal). Dtypes: float32.

nn.init.kaiming_normalfunctionSame as PyTorch
kaiming_normal(tensor, a=0, mode='fan_in', nonlinearity='leaky_relu', generator=None)

He normal fill: N(0, std) with std = gain / sqrt(fan), fan from mode, gain from nonlinearity and a. Dtypes: float32.

nn.init.kaiming_normal_functionSame as PyTorch
kaiming_normal_(tensor, a=0, mode='fan_in', nonlinearity='leaky_relu', generator=None)

He normal fill: N(0, std) with std = gain / sqrt(fan), fan from mode, gain from nonlinearity and a. Dtypes: float32.

nn.init.kaiming_uniformfunctionSame as PyTorch
kaiming_uniform(tensor, a=0, mode='fan_in', nonlinearity='leaky_relu', generator=None)

He uniform fill: U(-b, b) with b = gain * sqrt(3 / fan), fan from mode, gain from nonlinearity and a. Dtypes: float32.

nn.init.kaiming_uniform_functionSame as PyTorch
kaiming_uniform_(tensor, a=0, mode='fan_in', nonlinearity='leaky_relu', generator=None)

He uniform fill: U(-b, b) with b = gain * sqrt(3 / fan), fan from mode, gain from nonlinearity and a. Dtypes: float32.

nn.init.normalfunctionSame as PyTorch
normal(tensor, mean=0.0, std=1.0, generator=None)

Fills the tensor in place with normal draws N(mean, std). Dtypes: float32.

nn.init.normal_functionSame as PyTorch
normal_(tensor, mean=0.0, std=1.0, generator=None)

Fills the tensor in place with normal draws N(mean, std). Dtypes: float32.

nn.init.ones_functionSame as PyTorch
ones_(tensor)

Fills the tensor in place with ones. Every dtype.

nn.init.orthogonalfunctionSame as PyTorch
orthogonal(*args: _P.args, **kwargs: _P.kwargs) -> ~_R

A (semi-)orthogonal matrix from the QR factorisation of a normal draw, signs fixed by R's diagonal.

nn.init.orthogonal_functionSame as PyTorch
orthogonal_(tensor, gain=1, generator=None)

A (semi-)orthogonal matrix from the QR factorisation of a normal draw, signs fixed by R's diagonal.

nn.init.sparsefunctionSame as PyTorch
sparse(*args: _P.args, **kwargs: _P.kwargs) -> ~_R

Normal(0, std) entries with ceil(sparsity * rows) zeros in each column, at random rows.

nn.init.sparse_functionSame as PyTorch
sparse_(tensor, sparsity, std=0.01, generator=None)

Normal(0, std) entries with ceil(sparsity * rows) zeros in each column, at random rows.

nn.init.trunc_normalfunctionRiptorch extra
trunc_normal(tensor, mean=0.0, std=1.0, a=-2.0, b=2.0, generator=None)

Fills the tensor in place with N(mean, std) draws truncated to [a, b]. Dtypes: float32.

Riptorch extra: not in stock PyTorch.

nn.init.trunc_normal_functionSame as PyTorch
trunc_normal_(tensor, mean=0.0, std=1.0, a=-2.0, b=2.0, generator=None)

Fills the tensor in place with N(mean, std) draws truncated to [a, b]. Dtypes: float32.

nn.init.uniformfunctionSame as PyTorch
uniform(tensor, a=0.0, b=1.0, generator=None)

Fills the tensor in place with uniform draws in [a, b). Dtypes: float32.

nn.init.uniform_functionSame as PyTorch
uniform_(tensor, a=0.0, b=1.0, generator=None)

Fills the tensor in place with uniform draws in [a, b). Dtypes: float32.

nn.init.xavier_normalfunctionSame as PyTorch
xavier_normal(tensor, gain=1.0, generator=None)

Glorot normal fill: N(0, std) with std = gain * sqrt(2 / (fan_in + fan_out)). Dtypes: float32.

nn.init.xavier_normal_functionSame as PyTorch
xavier_normal_(tensor, gain=1.0, generator=None)

Glorot normal fill: N(0, std) with std = gain * sqrt(2 / (fan_in + fan_out)). Dtypes: float32.

nn.init.xavier_uniformfunctionSame as PyTorch
xavier_uniform(tensor, gain=1.0, generator=None)

Glorot uniform fill: U(-a, a) with a = gain * sqrt(6 / (fan_in + fan_out)). Dtypes: float32.

nn.init.xavier_uniform_functionSame as PyTorch
xavier_uniform_(tensor, gain=1.0, generator=None)

Glorot uniform fill: U(-a, a) with a = gain * sqrt(6 / (fan_in + fan_out)). Dtypes: float32.

nn.init.zeros_functionSame as PyTorch
zeros_(tensor)

Fills the tensor in place with zeros (Tensor.zero_ too). Every dtype.

Utilities (nn.utils)

nn.utils.clip_grad_normfunctionSame as PyTorch
clip_grad_norm(parameters, max_norm, norm_type=2.0, error_if_nonfinite=False, foreach=None)

Scales the gradients so their combined norm (any order; inf = largest entry) is at most max_norm; returns the norm before scaling. Order 2 runs in the Raya core (one call, part of a compiled step).

nn.utils.clip_grad_norm_functionSame as PyTorch
clip_grad_norm_(parameters, max_norm, norm_type=2.0, error_if_nonfinite=False, foreach=None)

Scales the gradients so their combined norm (any order; inf = largest entry) is at most max_norm; returns the norm before scaling. Order 2 runs in the Raya core (one call, part of a compiled step).

nn.utils.clip_grad_value_functionSame as PyTorch
clip_grad_value_(parameters, clip_value, foreach=None)

Clamps every gradient to [-clip_value, clip_value].

nn.utils.clip_grads_with_norm_functionSame as PyTorch
clip_grads_with_norm_(parameters, max_norm, total_norm, foreach=None)

Scales every gradient by min(1, max_norm / (total_norm + 1e-6)), given the total norm.

convert_conv2d_weight_memory_format(module, memory_format)

Returns module unchanged: Riptorch tensors have one layout (memory_format has no effect).

convert_conv3d_weight_memory_format(module, memory_format)

Returns module unchanged: Riptorch tensors have one layout (memory_format has no effect).

nn.utils.fuse_conv_bn_evalfunctionSame as PyTorch
fuse_conv_bn_eval(conv, bn, transpose=False)

A copy of conv with bn (in eval mode) folded into its weight and bias.

nn.utils.fuse_conv_bn_weightsfunctionSame as PyTorch
fuse_conv_bn_weights(conv_w, conv_b, bn_rm, bn_rv, bn_eps, bn_w, bn_b, transpose=False)

Folds batch-norm statistics into convolution weights: (w * gamma / sqrt(var + eps), (b - mean) * gamma / sqrt(var + eps) + beta) as Parameters (transpose=True scales dim 1).

nn.utils.fuse_linear_bn_evalfunctionSame as PyTorch
fuse_linear_bn_eval(linear, bn)

A copy of linear with bn (in eval mode) folded into its weight and bias.

nn.utils.fuse_linear_bn_weightsfunctionSame as PyTorch
fuse_linear_bn_weights(linear_w, linear_b, bn_rm, bn_rv, bn_eps, bn_w, bn_b)

Folds batch-norm statistics into a linear layer's weight and bias, as Parameters.

nn.utils.get_total_normfunctionSame as PyTorch
get_total_norm(tensors, norm_type=2.0, error_if_nonfinite=False, foreach=None)

The norm (norm_type; inf = largest absolute entry) of the norms of tensors, as if all were one vector.

error_if_nonfinite=True raises when it is nan or inf.

nn.utils.parameters_to_vectorfunctionSame as PyTorch
parameters_to_vector(parameters)

The parameters flattened and concatenated into one 1-d tensor.

nn.utils.remove_spectral_normfunctionSame as PyTorch
remove_spectral_norm(module, name='weight')

Undoes spectral_norm: name becomes a plain parameter with the current normalised value.

nn.utils.remove_weight_normfunctionSame as PyTorch
remove_weight_norm(module, name='weight')

Undoes weight_norm: name becomes a plain parameter with the current normalised value.

nn.utils.skip_initfunctionSame as PyTorch
skip_init(module_cls, *args, **kwargs)

module_cls(*args, **kwargs). PyTorch skips the parameter initialisation; Riptorch initialises as usual.

nn.utils.spectral_normfunctionSame as PyTorch
spectral_norm(module, name='weight', n_power_iterations=1, eps=1e-12, dim=None)

The older hook form of spectral normalisation: name_orig parameter, name_u / name_v buffers, name = W / sigma recomputed before each forward (power iteration in training).

nn.utils.vector_to_parametersfunctionSame as PyTorch
vector_to_parameters(vec, parameters)

Copies consecutive slices of vec into the parameters (the inverse of parameters_to_vector).

nn.utils.weight_normfunctionSame as PyTorch
weight_norm(module, name='weight', dim=0)

The older hook form of weight normalisation: replaces name with name_g and name_v parameters and recomputes name = g * v / ||v|| before each forward.

More

nn.ContainerclassSame as PyTorch
Container(*args, **kwargs)

torch.nn.Module: parameters, buffers and submodules in their own tables (_parameters, _buffers, _modules), reached as attributes; forward hooks; state_dict with persistent buffers. Written from PyTorch's docs.

34 methods and properties defined on Container
  • add_module(self, name, module)Adds a submodule under name (register_module is the same).
  • apply(self, fn)Calls fn on every submodule (children first) and then on the module itself; returns the module.
  • bfloat16(self)Converts floating parameters and buffers to bfloat16.
  • buffers(self, recurse=True)Every buffer once, submodules included unless recurse=False.
  • children(self)The direct submodules, each once, in registration order.
  • cpu(self)Returns the module unchanged (one unified memory).
  • cuda(self, device=None)Returns the module unchanged (one unified memory; no CUDA device).
  • double(self)Converts floating parameters and buffers to float64.
  • eval(self)train(False): evaluation mode for the module and every submodule.
  • extra_repr(self)Extra text inside the module's repr parentheses; subclasses override it ("" here).
  • float(self)Converts floating parameters and buffers to float32.
  • get_buffer(self, target)The buffer at a dotted path such as "bn.running_mean".
  • get_parameter(self, target)The parameter at a dotted path such as "layer.0.weight".
  • get_submodule(self, target)The submodule at a dotted path ("" is the module itself); AttributeError when a part is missing.
  • half(self)Converts floating parameters and buffers to float16.
  • load_state_dict(self, state_dict, strict=True, assign=False)Copies tensors from state_dict into the parameters and buffers, by dotted name.
  • modules(self)The module and all submodules, depth first, each once.
  • named_buffers(self, prefix='', recurse=True, remove_duplicate=True)(dotted name, buffer) pairs, each buffer once.
  • named_children(self)The direct submodules with their names, each module once, in registration order.
  • named_modules(self, memo=None, prefix='', remove_duplicate=True)The module and all submodules (depth first) with dotted names; shared modules once unless remove_duplicate=False.
  • named_parameters(self, prefix='', recurse=True, remove_duplicate=True)Each parameter once, under its first name, as in PyTorch: a tied weight (head.weight = wte.weight) is one parameter, updated and saved once.
  • parameters(self, recurse=True)Every parameter once (tied tensors once), submodules included unless recurse=False.
  • register_buffer(self, name, tensor, persistent=True)Adds a tensor that is part of the module's state but not a parameter.
  • register_forward_hook(self, hook, *, prepend=False, with_kwargs=False, always_call=False)Calls hook(module, args, output) after forward; a non-None result replaces the output.
  • register_forward_pre_hook(self, hook, *, prepend=False, with_kwargs=False)Calls hook(module, args) before forward; a non-None result replaces the arguments.
  • register_module(self, name, module)Adds a submodule under name (register_module is the same).
  • register_parameter(self, name, param)Adds a parameter under name (None registers an empty slot).
  • requires_grad_(self, requires_grad=True)Sets requires_grad on every parameter; returns the module.
  • share_memory(self)Returns the module unchanged (tensors are already in memory every process of this machine maps).
  • state_dict(self, *args, destination=None, prefix='', keep_vars=False)Parameters and persistent buffers by dotted name. A tied tensor is under each of its names, as in PyTorch (so a PyTorch model loads the checkpoint with strict=True); torch.save writes its values once.
  • to(self, *args, **kwargs)Converts every floating parameter and buffer to a floating dtype; returns the module.
  • train(self, mode=True)Sets training on the module and every submodule; mode must be a bool (ValueError otherwise, as PyTorch).
  • type(self, dst_type)Converts floating parameters and buffers to dst_type (as to(dst_type)).
  • zero_grad(self, set_to_none=True)Clears every parameter's gradient (sets it to None; set_to_none is accepted).
nn.CrossMapLRN2dclassSame as PyTorch
CrossMapLRN2d(size: int, alpha: float = 0.0001, beta: float = 0.75, k: float = 1) -> None

Same as PyTorch’s torch.nn.CrossMapLRN2d.

1 methods and properties defined on CrossMapLRN2d
  • forward(self, *inputs)
nn.DataParallelclassSame as PyTorch
DataParallel(module, device_ids=None, output_device=None, dim=0)

nn.DataParallel without CUDA: forward calls the module.

1 methods and properties defined on DataParallel
  • forward(self, *a, **k)Calls the wrapped module.
nn.LinearCrossEntropyOptionsclassSame as PyTorch
LinearCrossEntropyOptions(allow_retain_graph: bool = False, batch_chunk_size: Optional[int] = None, chunking_method: Optional[str] = 'auto', acc_policy: str = 'auto', acc_dtype: Any = None) -> None

Configuration of the chunked linear_cross_entropy (batch_chunk_size rows at a time). Riptorch computes the same loss either way; with options it runs the batch in chunks so the logits of one chunk exist at a time.

nn.MaxUnpool1dclassSame as PyTorch
MaxUnpool1d(kernel_size: Union[int, tuple[int]], stride: Union[int, tuple[int], NoneType] = None, padding: Union[int, tuple[int]] = 0) -> None

Same as PyTorch’s torch.nn.MaxUnpool1d.

1 methods and properties defined on MaxUnpool1d
  • forward(self, *inputs)
nn.MaxUnpool2dclassSame as PyTorch
MaxUnpool2d(kernel_size: Union[int, tuple[int, int]], stride: Union[int, tuple[int, int], NoneType] = None, padding: Union[int, tuple[int, int]] = 0) -> None

Same as PyTorch’s torch.nn.MaxUnpool2d.

1 methods and properties defined on MaxUnpool2d
  • forward(self, *inputs)
nn.MaxUnpool3dclassSame as PyTorch
MaxUnpool3d(kernel_size: Union[int, tuple[int, int, int]], stride: Union[int, tuple[int, int, int], NoneType] = None, padding: Union[int, tuple[int, int, int]] = 0) -> None

Same as PyTorch’s torch.nn.MaxUnpool3d.

1 methods and properties defined on MaxUnpool3d
  • forward(self, *inputs)
nn.NLLLoss2dclassSame as PyTorch
NLLLoss2d(*args, **kwargs)

Same as PyTorch’s torch.nn.NLLLoss2d.

1 methods and properties defined on NLLLoss2d
  • forward(self, *inputs)