doc_content stringlengths 1 386k | doc_id stringlengths 5 188 |
|---|---|
load_state_dict(state_dict, strict=True)
Copies 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. Parameters
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
Returns
missing_keys is a list of str containing the missing keys
unexpected_keys is a list of str containing the unexpected keys Return type
NamedTuple with missing_keys and unexpected_keys fields | torch.generated.torch.nn.unflatten#torch.nn.Unflatten.load_state_dict |
modules()
Returns an iterator over all modules in the network. 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) | torch.generated.torch.nn.unflatten#torch.nn.Unflatten.modules |
named_buffers(prefix='', recurse=True)
Returns an iterator over module buffers, yielding both the name of the buffer as well as the buffer itself. Parameters
prefix (str) – prefix to prepend to all buffer names.
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
(string, torch.Tensor) – Tuple containing the name and buffer Example: >>> for name, buf in self.named_buffers():
>>> if name in ['running_var']:
>>> print(buf.size()) | torch.generated.torch.nn.unflatten#torch.nn.Unflatten.named_buffers |
named_children()
Returns an iterator over immediate children modules, yielding both the name of the module as well as the module itself. Yields
(string, Module) – Tuple containing a name and child module Example: >>> for name, module in model.named_children():
>>> if name in ['conv4', 'conv5']:
>>> print(module) | torch.generated.torch.nn.unflatten#torch.nn.Unflatten.named_children |
named_modules(memo=None, prefix='')
Returns an iterator over all modules in the network, yielding both the name of the module as well as the module itself. Yields
(string, 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)) | torch.generated.torch.nn.unflatten#torch.nn.Unflatten.named_modules |
named_parameters(prefix='', recurse=True)
Returns an iterator over module parameters, yielding both the name of the parameter as well as the parameter itself. Parameters
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. Yields
(string, Parameter) – Tuple containing the name and parameter Example: >>> for name, param in self.named_parameters():
>>> if name in ['bias']:
>>> print(param.size()) | torch.generated.torch.nn.unflatten#torch.nn.Unflatten.named_parameters |
parameters(recurse=True)
Returns an iterator over module parameters. This is typically passed to an optimizer. Parameters
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: >>> for param in model.parameters():
>>> print(type(param), param.size())
<class 'torch.Tensor'> (20L,)
<class 'torch.Tensor'> (20L, 1L, 5L, 5L) | torch.generated.torch.nn.unflatten#torch.nn.Unflatten.parameters |
register_backward_hook(hook)
Registers a backward hook on the module. This function is deprecated in favor of nn.Module.register_full_backward_hook() and the behavior of this function will change in future versions. Returns
a handle that can be used to remove the added hook by calling handle.remove() Return type
torch.utils.hooks.RemovableHandle | torch.generated.torch.nn.unflatten#torch.nn.Unflatten.register_backward_hook |
register_buffer(name, tensor, persistent=True)
Adds a buffer to the module. This is typically used to register a buffer that should not to 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. Parameters
name (string) – name of the buffer. The buffer can be accessed from this module using the given name
tensor (Tensor) – buffer to be registered.
persistent (bool) – whether the buffer is part of this module’s state_dict. Example: >>> self.register_buffer('running_mean', torch.zeros(num_features)) | torch.generated.torch.nn.unflatten#torch.nn.Unflatten.register_buffer |
register_forward_hook(hook)
Registers a forward hook on the module. The hook will be called every time after forward() has computed an output. It should have the following signature: hook(module, input, output) -> None or modified output
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. Returns
a handle that can be used to remove the added hook by calling handle.remove() Return type
torch.utils.hooks.RemovableHandle | torch.generated.torch.nn.unflatten#torch.nn.Unflatten.register_forward_hook |
register_forward_pre_hook(hook)
Registers a forward pre-hook on the module. The hook will be called every time before forward() is invoked. It should have the following signature: hook(module, input) -> None or modified input
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). Returns
a handle that can be used to remove the added hook by calling handle.remove() Return type
torch.utils.hooks.RemovableHandle | torch.generated.torch.nn.unflatten#torch.nn.Unflatten.register_forward_pre_hook |
register_full_backward_hook(hook)
Registers a backward hook on the module. The hook will be called every time the gradients with respect to module inputs are computed. 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. Warning Modifying inputs or outputs inplace is not allowed when using backward hooks and will raise an error. Returns
a handle that can be used to remove the added hook by calling handle.remove() Return type
torch.utils.hooks.RemovableHandle | torch.generated.torch.nn.unflatten#torch.nn.Unflatten.register_full_backward_hook |
register_parameter(name, param)
Adds a parameter to the module. The parameter can be accessed as an attribute using given name. Parameters
name (string) – name of the parameter. The parameter can be accessed from this module using the given name
param (Parameter) – parameter to be added to the module. | torch.generated.torch.nn.unflatten#torch.nn.Unflatten.register_parameter |
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). Parameters
requires_grad (bool) – whether autograd should record operations on parameters in this module. Default: True. Returns
self Return type
Module | torch.generated.torch.nn.unflatten#torch.nn.Unflatten.requires_grad_ |
state_dict(destination=None, prefix='', keep_vars=False)
Returns a dictionary containing a whole state of the module. Both parameters and persistent buffers (e.g. running averages) are included. Keys are corresponding parameter and buffer names. Returns
a dictionary containing a whole state of the module Return type
dict Example: >>> module.state_dict().keys()
['bias', 'weight'] | torch.generated.torch.nn.unflatten#torch.nn.Unflatten.state_dict |
to(*args, **kwargs)
Moves and/or casts 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 dtype`s. In addition, this method will
only cast the floating point or complex parameters and buffers to :attr:`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. Parameters
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
self Return type
Module Examples: >>> 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)
>>> 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) | torch.generated.torch.nn.unflatten#torch.nn.Unflatten.to |
train(mode=True)
Sets the module in training mode. This has any effect only on certain modules. See documentations of particular modules for details of their behaviors in training/evaluation mode, if they are affected, e.g. Dropout, BatchNorm, etc. Parameters
mode (bool) – whether to set training mode (True) or evaluation mode (False). Default: True. Returns
self Return type
Module | torch.generated.torch.nn.unflatten#torch.nn.Unflatten.train |
type(dst_type)
Casts all parameters and buffers to dst_type. Parameters
dst_type (type or string) – the desired type Returns
self Return type
Module | torch.generated.torch.nn.unflatten#torch.nn.Unflatten.type |
xpu(device=None)
Moves 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. Parameters
device (int, optional) – if specified, all parameters will be copied to that device Returns
self Return type
Module | torch.generated.torch.nn.unflatten#torch.nn.Unflatten.xpu |
zero_grad(set_to_none=False)
Sets gradients of all model parameters to zero. See similar function under torch.optim.Optimizer for more context. Parameters
set_to_none (bool) – instead of setting to zero, set the grads to None. See torch.optim.Optimizer.zero_grad() for details. | torch.generated.torch.nn.unflatten#torch.nn.Unflatten.zero_grad |
class torch.nn.Unfold(kernel_size, dilation=1, padding=0, stride=1) [source]
Extracts sliding local blocks from a batched input tensor. Consider a batched input tensor of shape (N,C,∗)(N, C, *) , where NN is the batch dimension, CC is the channel dimension, and ∗* represent arbitrary spatial dimensions. This operation flattens each sliding kernel_size-sized block within the spatial dimensions of input into a column (i.e., last dimension) of a 3-D output tensor of shape (N,C×∏(kernel_size),L)(N, C \times \prod(\text{kernel\_size}), L) , where C×∏(kernel_size)C \times \prod(\text{kernel\_size}) is the total number of values within each block (a block has ∏(kernel_size)\prod(\text{kernel\_size}) spatial locations each containing a CC -channeled vector), and LL is the total number of such blocks: L=∏d⌊spatial_size[d]+2×padding[d]−dilation[d]×(kernel_size[d]−1)−1stride[d]+1⌋,L = \prod_d \left\lfloor\frac{\text{spatial\_size}[d] + 2 \times \text{padding}[d] % - \text{dilation}[d] \times (\text{kernel\_size}[d] - 1) - 1}{\text{stride}[d]} + 1\right\rfloor,
where spatial_size\text{spatial\_size} is formed by the spatial dimensions of input (∗* above), and dd is over all spatial dimensions. Therefore, indexing output at the last dimension (column dimension) gives all values within a certain block. The padding, stride and dilation arguments specify how the sliding blocks are retrieved.
stride controls the stride for the sliding blocks.
padding controls the amount of implicit zero-paddings on both sides for padding number of points for each dimension before reshaping.
dilation controls the spacing between the kernel points; also known as the à trous algorithm. It is harder to describe, but this link has a nice visualization of what dilation does. Parameters
kernel_size (int or tuple) – the size of the sliding blocks
stride (int or tuple, optional) – the stride of the sliding blocks in the input spatial dimensions. Default: 1
padding (int or tuple, optional) – implicit zero padding to be added on both sides of input. Default: 0
dilation (int or tuple, optional) – a parameter that controls the stride of elements within the neighborhood. Default: 1 If kernel_size, dilation, padding or stride is an int or a tuple of length 1, their values will be replicated across all spatial dimensions. For the case of two input spatial dimensions this operation is sometimes called im2col. Note Fold calculates each combined value in the resulting large tensor by summing all values from all containing blocks. Unfold extracts the values in the local blocks by copying from the large tensor. So, if the blocks overlap, they are not inverses of each other. In general, folding and unfolding operations are related as follows. Consider Fold and Unfold instances created with the same parameters: >>> fold_params = dict(kernel_size=..., dilation=..., padding=..., stride=...)
>>> fold = nn.Fold(output_size=..., **fold_params)
>>> unfold = nn.Unfold(**fold_params)
Then for any (supported) input tensor the following equality holds: fold(unfold(input)) == divisor * input
where divisor is a tensor that depends only on the shape and dtype of the input: >>> input_ones = torch.ones(input.shape, dtype=input.dtype)
>>> divisor = fold(unfold(input_ones))
When the divisor tensor contains no zero elements, then fold and unfold operations are inverses of each other (up to constant divisor). Warning Currently, only 4-D input tensors (batched image-like tensors) are supported. Shape:
Input: (N,C,∗)(N, C, *)
Output: (N,C×∏(kernel_size),L)(N, C \times \prod(\text{kernel\_size}), L) as described above Examples: >>> unfold = nn.Unfold(kernel_size=(2, 3))
>>> input = torch.randn(2, 5, 3, 4)
>>> output = unfold(input)
>>> # each patch contains 30 values (2x3=6 vectors, each of 5 channels)
>>> # 4 blocks (2x3 kernels) in total in the 3x4 input
>>> output.size()
torch.Size([2, 30, 4])
>>> # Convolution is equivalent with Unfold + Matrix Multiplication + Fold (or view to output shape)
>>> inp = torch.randn(1, 3, 10, 12)
>>> w = torch.randn(2, 3, 4, 5)
>>> inp_unf = torch.nn.functional.unfold(inp, (4, 5))
>>> out_unf = inp_unf.transpose(1, 2).matmul(w.view(w.size(0), -1).t()).transpose(1, 2)
>>> out = torch.nn.functional.fold(out_unf, (7, 8), (1, 1))
>>> # or equivalently (and avoiding a copy),
>>> # out = out_unf.view(1, 2, 7, 8)
>>> (torch.nn.functional.conv2d(inp, w) - out).abs().max()
tensor(1.9073e-06) | torch.generated.torch.nn.unfold#torch.nn.Unfold |
class torch.nn.Upsample(size=None, scale_factor=None, mode='nearest', align_corners=None) [source]
Upsamples a given multi-channel 1D (temporal), 2D (spatial) or 3D (volumetric) data. The input data is assumed to be of the form minibatch x channels x [optional depth] x [optional height] x width. Hence, for spatial inputs, we expect a 4D Tensor and for volumetric inputs, we expect a 5D Tensor. The algorithms available for upsampling are nearest neighbor and linear, bilinear, bicubic and trilinear for 3D, 4D and 5D input Tensor, respectively. One can either give a scale_factor or the target output size to calculate the output size. (You cannot give both, as it is ambiguous) Parameters
size (int or Tuple[int] or Tuple[int, int] or Tuple[int, int, int], optional) – output spatial sizes
scale_factor (float or Tuple[float] or Tuple[float, float] or Tuple[float, float, float], optional) – multiplier for spatial size. Has to match input size if it is a tuple.
mode (str, optional) – the upsampling algorithm: one of 'nearest', 'linear', 'bilinear', 'bicubic' and 'trilinear'. Default: 'nearest'
align_corners (bool, optional) – if True, the corner pixels of the input and output tensors are aligned, and thus preserving the values at those pixels. This only has effect when mode is 'linear', 'bilinear', or 'trilinear'. Default: False
Shape:
Input: (N,C,Win)(N, C, W_{in}) , (N,C,Hin,Win)(N, C, H_{in}, W_{in}) or (N,C,Din,Hin,Win)(N, C, D_{in}, H_{in}, W_{in})
Output: (N,C,Wout)(N, C, W_{out}) , (N,C,Hout,Wout)(N, C, H_{out}, W_{out}) or (N,C,Dout,Hout,Wout)(N, C, D_{out}, H_{out}, W_{out}) , where Dout=⌊Din×scale_factor⌋D_{out} = \left\lfloor D_{in} \times \text{scale\_factor} \right\rfloor
Hout=⌊Hin×scale_factor⌋H_{out} = \left\lfloor H_{in} \times \text{scale\_factor} \right\rfloor
Wout=⌊Win×scale_factor⌋W_{out} = \left\lfloor W_{in} \times \text{scale\_factor} \right\rfloor
Warning With align_corners = True, the linearly interpolating modes (linear, bilinear, bicubic, and trilinear) don’t proportionally align the output and input pixels, and thus the output values can depend on the input size. This was the default behavior for these modes up to version 0.3.1. Since then, the default behavior is align_corners = False. See below for concrete examples on how this affects the outputs. Note If you want downsampling/general resizing, you should use interpolate(). Examples: >>> input = torch.arange(1, 5, dtype=torch.float32).view(1, 1, 2, 2)
>>> input
tensor([[[[ 1., 2.],
[ 3., 4.]]]])
>>> m = nn.Upsample(scale_factor=2, mode='nearest')
>>> m(input)
tensor([[[[ 1., 1., 2., 2.],
[ 1., 1., 2., 2.],
[ 3., 3., 4., 4.],
[ 3., 3., 4., 4.]]]])
>>> m = nn.Upsample(scale_factor=2, mode='bilinear') # align_corners=False
>>> m(input)
tensor([[[[ 1.0000, 1.2500, 1.7500, 2.0000],
[ 1.5000, 1.7500, 2.2500, 2.5000],
[ 2.5000, 2.7500, 3.2500, 3.5000],
[ 3.0000, 3.2500, 3.7500, 4.0000]]]])
>>> m = nn.Upsample(scale_factor=2, mode='bilinear', align_corners=True)
>>> m(input)
tensor([[[[ 1.0000, 1.3333, 1.6667, 2.0000],
[ 1.6667, 2.0000, 2.3333, 2.6667],
[ 2.3333, 2.6667, 3.0000, 3.3333],
[ 3.0000, 3.3333, 3.6667, 4.0000]]]])
>>> # Try scaling the same data in a larger tensor
>>>
>>> input_3x3 = torch.zeros(3, 3).view(1, 1, 3, 3)
>>> input_3x3[:, :, :2, :2].copy_(input)
tensor([[[[ 1., 2.],
[ 3., 4.]]]])
>>> input_3x3
tensor([[[[ 1., 2., 0.],
[ 3., 4., 0.],
[ 0., 0., 0.]]]])
>>> m = nn.Upsample(scale_factor=2, mode='bilinear') # align_corners=False
>>> # Notice that values in top left corner are the same with the small input (except at boundary)
>>> m(input_3x3)
tensor([[[[ 1.0000, 1.2500, 1.7500, 1.5000, 0.5000, 0.0000],
[ 1.5000, 1.7500, 2.2500, 1.8750, 0.6250, 0.0000],
[ 2.5000, 2.7500, 3.2500, 2.6250, 0.8750, 0.0000],
[ 2.2500, 2.4375, 2.8125, 2.2500, 0.7500, 0.0000],
[ 0.7500, 0.8125, 0.9375, 0.7500, 0.2500, 0.0000],
[ 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000]]]])
>>> m = nn.Upsample(scale_factor=2, mode='bilinear', align_corners=True)
>>> # Notice that values in top left corner are now changed
>>> m(input_3x3)
tensor([[[[ 1.0000, 1.4000, 1.8000, 1.6000, 0.8000, 0.0000],
[ 1.8000, 2.2000, 2.6000, 2.2400, 1.1200, 0.0000],
[ 2.6000, 3.0000, 3.4000, 2.8800, 1.4400, 0.0000],
[ 2.4000, 2.7200, 3.0400, 2.5600, 1.2800, 0.0000],
[ 1.2000, 1.3600, 1.5200, 1.2800, 0.6400, 0.0000],
[ 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000]]]]) | torch.generated.torch.nn.upsample#torch.nn.Upsample |
class torch.nn.UpsamplingBilinear2d(size=None, scale_factor=None) [source]
Applies a 2D bilinear upsampling to an input signal composed of several input channels. To specify the scale, it takes either the size or the scale_factor as it’s constructor argument. When size is given, it is the output size of the image (h, w). Parameters
size (int or Tuple[int, int], optional) – output spatial sizes
scale_factor (float or Tuple[float, float], optional) – multiplier for spatial size. Warning This class is deprecated in favor of interpolate(). It is equivalent to nn.functional.interpolate(..., mode='bilinear', align_corners=True). Shape:
Input: (N,C,Hin,Win)(N, C, H_{in}, W_{in})
Output: (N,C,Hout,Wout)(N, C, H_{out}, W_{out}) where Hout=⌊Hin×scale_factor⌋H_{out} = \left\lfloor H_{in} \times \text{scale\_factor} \right\rfloor
Wout=⌊Win×scale_factor⌋W_{out} = \left\lfloor W_{in} \times \text{scale\_factor} \right\rfloor
Examples: >>> input = torch.arange(1, 5, dtype=torch.float32).view(1, 1, 2, 2)
>>> input
tensor([[[[ 1., 2.],
[ 3., 4.]]]])
>>> m = nn.UpsamplingBilinear2d(scale_factor=2)
>>> m(input)
tensor([[[[ 1.0000, 1.3333, 1.6667, 2.0000],
[ 1.6667, 2.0000, 2.3333, 2.6667],
[ 2.3333, 2.6667, 3.0000, 3.3333],
[ 3.0000, 3.3333, 3.6667, 4.0000]]]]) | torch.generated.torch.nn.upsamplingbilinear2d#torch.nn.UpsamplingBilinear2d |
class torch.nn.UpsamplingNearest2d(size=None, scale_factor=None) [source]
Applies a 2D nearest neighbor upsampling to an input signal composed of several input channels. To specify the scale, it takes either the size or the scale_factor as it’s constructor argument. When size is given, it is the output size of the image (h, w). Parameters
size (int or Tuple[int, int], optional) – output spatial sizes
scale_factor (float or Tuple[float, float], optional) – multiplier for spatial size. Warning This class is deprecated in favor of interpolate(). Shape:
Input: (N,C,Hin,Win)(N, C, H_{in}, W_{in})
Output: (N,C,Hout,Wout)(N, C, H_{out}, W_{out}) where Hout=⌊Hin×scale_factor⌋H_{out} = \left\lfloor H_{in} \times \text{scale\_factor} \right\rfloor
Wout=⌊Win×scale_factor⌋W_{out} = \left\lfloor W_{in} \times \text{scale\_factor} \right\rfloor
Examples: >>> input = torch.arange(1, 5, dtype=torch.float32).view(1, 1, 2, 2)
>>> input
tensor([[[[ 1., 2.],
[ 3., 4.]]]])
>>> m = nn.UpsamplingNearest2d(scale_factor=2)
>>> m(input)
tensor([[[[ 1., 1., 2., 2.],
[ 1., 1., 2., 2.],
[ 3., 3., 4., 4.],
[ 3., 3., 4., 4.]]]]) | torch.generated.torch.nn.upsamplingnearest2d#torch.nn.UpsamplingNearest2d |
torch.nn.utils.clip_grad_norm_(parameters, max_norm, norm_type=2.0) [source]
Clips gradient norm of an iterable of parameters. The norm is computed over all gradients together, as if they were concatenated into a single vector. Gradients are modified in-place. Parameters
parameters (Iterable[Tensor] or Tensor) – an iterable of Tensors or a single Tensor that will have gradients normalized
max_norm (float or int) – max norm of the gradients
norm_type (float or int) – type of the used p-norm. Can be 'inf' for infinity norm. Returns
Total norm of the parameters (viewed as a single vector). | torch.generated.torch.nn.utils.clip_grad_norm_#torch.nn.utils.clip_grad_norm_ |
torch.nn.utils.clip_grad_value_(parameters, clip_value) [source]
Clips gradient of an iterable of parameters at specified value. Gradients are modified in-place. Parameters
parameters (Iterable[Tensor] or Tensor) – an iterable of Tensors or a single Tensor that will have gradients normalized
clip_value (float or int) – maximum allowed value of the gradients. The gradients are clipped in the range [-clip_value,clip_value]\left[\text{-clip\_value}, \text{clip\_value}\right] | torch.generated.torch.nn.utils.clip_grad_value_#torch.nn.utils.clip_grad_value_ |
torch.nn.utils.parameters_to_vector(parameters) [source]
Convert parameters to one vector Parameters
parameters (Iterable[Tensor]) – an iterator of Tensors that are the parameters of a model. Returns
The parameters represented by a single vector | torch.generated.torch.nn.utils.parameters_to_vector#torch.nn.utils.parameters_to_vector |
class torch.nn.utils.prune.BasePruningMethod [source]
Abstract base class for creation of new pruning techniques. Provides a skeleton for customization requiring the overriding of methods such as compute_mask() and apply().
classmethod apply(module, name, *args, importance_scores=None, **kwargs) [source]
Adds the forward pre-hook that enables pruning on the fly and the reparametrization of a tensor in terms of the original tensor and the pruning mask. Parameters
module (nn.Module) – module containing the tensor to prune
name (str) – parameter name within module on which pruning will act.
args – arguments passed on to a subclass of BasePruningMethod
importance_scores (torch.Tensor) – tensor of importance scores (of same shape as module parameter) used to compute mask for pruning. The values in this tensor indicate the importance of the corresponding elements in the parameter being pruned. If unspecified or None, the parameter will be used in its place.
kwargs – keyword arguments passed on to a subclass of a BasePruningMethod
apply_mask(module) [source]
Simply handles the multiplication between the parameter being pruned and the generated mask. Fetches the mask and the original tensor from the module and returns the pruned version of the tensor. Parameters
module (nn.Module) – module containing the tensor to prune Returns
pruned version of the input tensor Return type
pruned_tensor (torch.Tensor)
abstract compute_mask(t, default_mask) [source]
Computes and returns a mask for the input tensor t. Starting from a base default_mask (which should be a mask of ones if the tensor has not been pruned yet), generate a random mask to apply on top of the default_mask according to the specific pruning method recipe. Parameters
t (torch.Tensor) – tensor representing the importance scores of the
to prune. (parameter) –
default_mask (torch.Tensor) – Base mask from previous pruning
that need to be respected after the new mask is (iterations,) –
Same dims as t. (applied.) – Returns
mask to apply to t, of same dims as t Return type
mask (torch.Tensor)
prune(t, default_mask=None, importance_scores=None) [source]
Computes and returns a pruned version of input tensor t according to the pruning rule specified in compute_mask(). Parameters
t (torch.Tensor) – tensor to prune (of same dimensions as default_mask).
importance_scores (torch.Tensor) – tensor of importance scores (of same shape as t) used to compute mask for pruning t. The values in this tensor indicate the importance of the corresponding elements in the t that is being pruned. If unspecified or None, the tensor t will be used in its place.
default_mask (torch.Tensor, optional) – mask from previous pruning iteration, if any. To be considered when determining what portion of the tensor that pruning should act on. If None, default to a mask of ones. Returns
pruned version of tensor t.
remove(module) [source]
Removes the pruning reparameterization from a module. The pruned parameter named name remains permanently pruned, and the parameter named name+'_orig' is removed from the parameter list. Similarly, the buffer named name+'_mask' is removed from the buffers. Note Pruning itself is NOT undone or reversed! | torch.generated.torch.nn.utils.prune.basepruningmethod#torch.nn.utils.prune.BasePruningMethod |
classmethod apply(module, name, *args, importance_scores=None, **kwargs) [source]
Adds the forward pre-hook that enables pruning on the fly and the reparametrization of a tensor in terms of the original tensor and the pruning mask. Parameters
module (nn.Module) – module containing the tensor to prune
name (str) – parameter name within module on which pruning will act.
args – arguments passed on to a subclass of BasePruningMethod
importance_scores (torch.Tensor) – tensor of importance scores (of same shape as module parameter) used to compute mask for pruning. The values in this tensor indicate the importance of the corresponding elements in the parameter being pruned. If unspecified or None, the parameter will be used in its place.
kwargs – keyword arguments passed on to a subclass of a BasePruningMethod | torch.generated.torch.nn.utils.prune.basepruningmethod#torch.nn.utils.prune.BasePruningMethod.apply |
apply_mask(module) [source]
Simply handles the multiplication between the parameter being pruned and the generated mask. Fetches the mask and the original tensor from the module and returns the pruned version of the tensor. Parameters
module (nn.Module) – module containing the tensor to prune Returns
pruned version of the input tensor Return type
pruned_tensor (torch.Tensor) | torch.generated.torch.nn.utils.prune.basepruningmethod#torch.nn.utils.prune.BasePruningMethod.apply_mask |
abstract compute_mask(t, default_mask) [source]
Computes and returns a mask for the input tensor t. Starting from a base default_mask (which should be a mask of ones if the tensor has not been pruned yet), generate a random mask to apply on top of the default_mask according to the specific pruning method recipe. Parameters
t (torch.Tensor) – tensor representing the importance scores of the
to prune. (parameter) –
default_mask (torch.Tensor) – Base mask from previous pruning
that need to be respected after the new mask is (iterations,) –
Same dims as t. (applied.) – Returns
mask to apply to t, of same dims as t Return type
mask (torch.Tensor) | torch.generated.torch.nn.utils.prune.basepruningmethod#torch.nn.utils.prune.BasePruningMethod.compute_mask |
prune(t, default_mask=None, importance_scores=None) [source]
Computes and returns a pruned version of input tensor t according to the pruning rule specified in compute_mask(). Parameters
t (torch.Tensor) – tensor to prune (of same dimensions as default_mask).
importance_scores (torch.Tensor) – tensor of importance scores (of same shape as t) used to compute mask for pruning t. The values in this tensor indicate the importance of the corresponding elements in the t that is being pruned. If unspecified or None, the tensor t will be used in its place.
default_mask (torch.Tensor, optional) – mask from previous pruning iteration, if any. To be considered when determining what portion of the tensor that pruning should act on. If None, default to a mask of ones. Returns
pruned version of tensor t. | torch.generated.torch.nn.utils.prune.basepruningmethod#torch.nn.utils.prune.BasePruningMethod.prune |
remove(module) [source]
Removes the pruning reparameterization from a module. The pruned parameter named name remains permanently pruned, and the parameter named name+'_orig' is removed from the parameter list. Similarly, the buffer named name+'_mask' is removed from the buffers. Note Pruning itself is NOT undone or reversed! | torch.generated.torch.nn.utils.prune.basepruningmethod#torch.nn.utils.prune.BasePruningMethod.remove |
class torch.nn.utils.prune.CustomFromMask(mask) [source]
classmethod apply(module, name, mask) [source]
Adds the forward pre-hook that enables pruning on the fly and the reparametrization of a tensor in terms of the original tensor and the pruning mask. Parameters
module (nn.Module) – module containing the tensor to prune
name (str) – parameter name within module on which pruning will act.
apply_mask(module)
Simply handles the multiplication between the parameter being pruned and the generated mask. Fetches the mask and the original tensor from the module and returns the pruned version of the tensor. Parameters
module (nn.Module) – module containing the tensor to prune Returns
pruned version of the input tensor Return type
pruned_tensor (torch.Tensor)
prune(t, default_mask=None, importance_scores=None)
Computes and returns a pruned version of input tensor t according to the pruning rule specified in compute_mask(). Parameters
t (torch.Tensor) – tensor to prune (of same dimensions as default_mask).
importance_scores (torch.Tensor) – tensor of importance scores (of same shape as t) used to compute mask for pruning t. The values in this tensor indicate the importance of the corresponding elements in the t that is being pruned. If unspecified or None, the tensor t will be used in its place.
default_mask (torch.Tensor, optional) – mask from previous pruning iteration, if any. To be considered when determining what portion of the tensor that pruning should act on. If None, default to a mask of ones. Returns
pruned version of tensor t.
remove(module)
Removes the pruning reparameterization from a module. The pruned parameter named name remains permanently pruned, and the parameter named name+'_orig' is removed from the parameter list. Similarly, the buffer named name+'_mask' is removed from the buffers. Note Pruning itself is NOT undone or reversed! | torch.generated.torch.nn.utils.prune.customfrommask#torch.nn.utils.prune.CustomFromMask |
classmethod apply(module, name, mask) [source]
Adds the forward pre-hook that enables pruning on the fly and the reparametrization of a tensor in terms of the original tensor and the pruning mask. Parameters
module (nn.Module) – module containing the tensor to prune
name (str) – parameter name within module on which pruning will act. | torch.generated.torch.nn.utils.prune.customfrommask#torch.nn.utils.prune.CustomFromMask.apply |
apply_mask(module)
Simply handles the multiplication between the parameter being pruned and the generated mask. Fetches the mask and the original tensor from the module and returns the pruned version of the tensor. Parameters
module (nn.Module) – module containing the tensor to prune Returns
pruned version of the input tensor Return type
pruned_tensor (torch.Tensor) | torch.generated.torch.nn.utils.prune.customfrommask#torch.nn.utils.prune.CustomFromMask.apply_mask |
prune(t, default_mask=None, importance_scores=None)
Computes and returns a pruned version of input tensor t according to the pruning rule specified in compute_mask(). Parameters
t (torch.Tensor) – tensor to prune (of same dimensions as default_mask).
importance_scores (torch.Tensor) – tensor of importance scores (of same shape as t) used to compute mask for pruning t. The values in this tensor indicate the importance of the corresponding elements in the t that is being pruned. If unspecified or None, the tensor t will be used in its place.
default_mask (torch.Tensor, optional) – mask from previous pruning iteration, if any. To be considered when determining what portion of the tensor that pruning should act on. If None, default to a mask of ones. Returns
pruned version of tensor t. | torch.generated.torch.nn.utils.prune.customfrommask#torch.nn.utils.prune.CustomFromMask.prune |
remove(module)
Removes the pruning reparameterization from a module. The pruned parameter named name remains permanently pruned, and the parameter named name+'_orig' is removed from the parameter list. Similarly, the buffer named name+'_mask' is removed from the buffers. Note Pruning itself is NOT undone or reversed! | torch.generated.torch.nn.utils.prune.customfrommask#torch.nn.utils.prune.CustomFromMask.remove |
torch.nn.utils.prune.custom_from_mask(module, name, mask) [source]
Prunes tensor corresponding to parameter called name in module by applying the pre-computed mask in mask. Modifies module in place (and also return the modified module) by: 1) adding a named buffer called name+'_mask' corresponding to the binary mask applied to the parameter name by the pruning method. 2) replacing the parameter name by its pruned version, while the original (unpruned) parameter is stored in a new parameter named name+'_orig'. Parameters
module (nn.Module) – module containing the tensor to prune
name (str) – parameter name within module on which pruning will act.
mask (Tensor) – binary mask to be applied to the parameter. Returns
modified (i.e. pruned) version of the input module Return type
module (nn.Module) Examples >>> m = prune.custom_from_mask(
nn.Linear(5, 3), name='bias', mask=torch.Tensor([0, 1, 0])
)
>>> print(m.bias_mask)
tensor([0., 1., 0.]) | torch.generated.torch.nn.utils.prune.custom_from_mask#torch.nn.utils.prune.custom_from_mask |
torch.nn.utils.prune.global_unstructured(parameters, pruning_method, importance_scores=None, **kwargs) [source]
Globally prunes tensors corresponding to all parameters in parameters by applying the specified pruning_method. Modifies modules in place by: 1) adding a named buffer called name+'_mask' corresponding to the binary mask applied to the parameter name by the pruning method. 2) replacing the parameter name by its pruned version, while the original (unpruned) parameter is stored in a new parameter named name+'_orig'. Parameters
parameters (Iterable of (module, name) tuples) – parameters of the model to prune in a global fashion, i.e. by aggregating all weights prior to deciding which ones to prune. module must be of type nn.Module, and name must be a string.
pruning_method (function) – a valid pruning function from this module, or a custom one implemented by the user that satisfies the implementation guidelines and has PRUNING_TYPE='unstructured'.
importance_scores (dict) – a dictionary mapping (module, name) tuples to the corresponding parameter’s importance scores tensor. The tensor should be the same shape as the parameter, and is used for computing mask for pruning. If unspecified or None, the parameter will be used in place of its importance scores.
kwargs – other keyword arguments such as: amount (int or float): quantity of parameters to prune across the specified parameters. If float, should be between 0.0 and 1.0 and represent the fraction of parameters to prune. If int, it represents the absolute number of parameters to prune. Raises
TypeError – if PRUNING_TYPE != 'unstructured' Note Since global structured pruning doesn’t make much sense unless the norm is normalized by the size of the parameter, we now limit the scope of global pruning to unstructured methods. Examples >>> net = nn.Sequential(OrderedDict([
('first', nn.Linear(10, 4)),
('second', nn.Linear(4, 1)),
]))
>>> parameters_to_prune = (
(net.first, 'weight'),
(net.second, 'weight'),
)
>>> prune.global_unstructured(
parameters_to_prune,
pruning_method=prune.L1Unstructured,
amount=10,
)
>>> print(sum(torch.nn.utils.parameters_to_vector(net.buffers()) == 0))
tensor(10, dtype=torch.uint8) | torch.generated.torch.nn.utils.prune.global_unstructured#torch.nn.utils.prune.global_unstructured |
class torch.nn.utils.prune.Identity [source]
Utility pruning method that does not prune any units but generates the pruning parametrization with a mask of ones.
classmethod apply(module, name) [source]
Adds the forward pre-hook that enables pruning on the fly and the reparametrization of a tensor in terms of the original tensor and the pruning mask. Parameters
module (nn.Module) – module containing the tensor to prune
name (str) – parameter name within module on which pruning will act.
apply_mask(module)
Simply handles the multiplication between the parameter being pruned and the generated mask. Fetches the mask and the original tensor from the module and returns the pruned version of the tensor. Parameters
module (nn.Module) – module containing the tensor to prune Returns
pruned version of the input tensor Return type
pruned_tensor (torch.Tensor)
prune(t, default_mask=None, importance_scores=None)
Computes and returns a pruned version of input tensor t according to the pruning rule specified in compute_mask(). Parameters
t (torch.Tensor) – tensor to prune (of same dimensions as default_mask).
importance_scores (torch.Tensor) – tensor of importance scores (of same shape as t) used to compute mask for pruning t. The values in this tensor indicate the importance of the corresponding elements in the t that is being pruned. If unspecified or None, the tensor t will be used in its place.
default_mask (torch.Tensor, optional) – mask from previous pruning iteration, if any. To be considered when determining what portion of the tensor that pruning should act on. If None, default to a mask of ones. Returns
pruned version of tensor t.
remove(module)
Removes the pruning reparameterization from a module. The pruned parameter named name remains permanently pruned, and the parameter named name+'_orig' is removed from the parameter list. Similarly, the buffer named name+'_mask' is removed from the buffers. Note Pruning itself is NOT undone or reversed! | torch.generated.torch.nn.utils.prune.identity#torch.nn.utils.prune.Identity |
classmethod apply(module, name) [source]
Adds the forward pre-hook that enables pruning on the fly and the reparametrization of a tensor in terms of the original tensor and the pruning mask. Parameters
module (nn.Module) – module containing the tensor to prune
name (str) – parameter name within module on which pruning will act. | torch.generated.torch.nn.utils.prune.identity#torch.nn.utils.prune.Identity.apply |
apply_mask(module)
Simply handles the multiplication between the parameter being pruned and the generated mask. Fetches the mask and the original tensor from the module and returns the pruned version of the tensor. Parameters
module (nn.Module) – module containing the tensor to prune Returns
pruned version of the input tensor Return type
pruned_tensor (torch.Tensor) | torch.generated.torch.nn.utils.prune.identity#torch.nn.utils.prune.Identity.apply_mask |
prune(t, default_mask=None, importance_scores=None)
Computes and returns a pruned version of input tensor t according to the pruning rule specified in compute_mask(). Parameters
t (torch.Tensor) – tensor to prune (of same dimensions as default_mask).
importance_scores (torch.Tensor) – tensor of importance scores (of same shape as t) used to compute mask for pruning t. The values in this tensor indicate the importance of the corresponding elements in the t that is being pruned. If unspecified or None, the tensor t will be used in its place.
default_mask (torch.Tensor, optional) – mask from previous pruning iteration, if any. To be considered when determining what portion of the tensor that pruning should act on. If None, default to a mask of ones. Returns
pruned version of tensor t. | torch.generated.torch.nn.utils.prune.identity#torch.nn.utils.prune.Identity.prune |
remove(module)
Removes the pruning reparameterization from a module. The pruned parameter named name remains permanently pruned, and the parameter named name+'_orig' is removed from the parameter list. Similarly, the buffer named name+'_mask' is removed from the buffers. Note Pruning itself is NOT undone or reversed! | torch.generated.torch.nn.utils.prune.identity#torch.nn.utils.prune.Identity.remove |
torch.nn.utils.prune.is_pruned(module) [source]
Check whether module is pruned by looking for forward_pre_hooks in its modules that inherit from the BasePruningMethod. Parameters
module (nn.Module) – object that is either pruned or unpruned Returns
binary answer to whether module is pruned. Examples >>> m = nn.Linear(5, 7)
>>> print(prune.is_pruned(m))
False
>>> prune.random_unstructured(m, name='weight', amount=0.2)
>>> print(prune.is_pruned(m))
True | torch.generated.torch.nn.utils.prune.is_pruned#torch.nn.utils.prune.is_pruned |
class torch.nn.utils.prune.L1Unstructured(amount) [source]
Prune (currently unpruned) units in a tensor by zeroing out the ones with the lowest L1-norm. Parameters
amount (int or float) – quantity of parameters to prune. If float, should be between 0.0 and 1.0 and represent the fraction of parameters to prune. If int, it represents the absolute number of parameters to prune.
classmethod apply(module, name, amount, importance_scores=None) [source]
Adds the forward pre-hook that enables pruning on the fly and the reparametrization of a tensor in terms of the original tensor and the pruning mask. Parameters
module (nn.Module) – module containing the tensor to prune
name (str) – parameter name within module on which pruning will act.
amount (int or float) – quantity of parameters to prune. If float, should be between 0.0 and 1.0 and represent the fraction of parameters to prune. If int, it represents the absolute number of parameters to prune.
importance_scores (torch.Tensor) – tensor of importance scores (of same shape as module parameter) used to compute mask for pruning. The values in this tensor indicate the importance of the corresponding elements in the parameter being pruned. If unspecified or None, the module parameter will be used in its place.
apply_mask(module)
Simply handles the multiplication between the parameter being pruned and the generated mask. Fetches the mask and the original tensor from the module and returns the pruned version of the tensor. Parameters
module (nn.Module) – module containing the tensor to prune Returns
pruned version of the input tensor Return type
pruned_tensor (torch.Tensor)
prune(t, default_mask=None, importance_scores=None)
Computes and returns a pruned version of input tensor t according to the pruning rule specified in compute_mask(). Parameters
t (torch.Tensor) – tensor to prune (of same dimensions as default_mask).
importance_scores (torch.Tensor) – tensor of importance scores (of same shape as t) used to compute mask for pruning t. The values in this tensor indicate the importance of the corresponding elements in the t that is being pruned. If unspecified or None, the tensor t will be used in its place.
default_mask (torch.Tensor, optional) – mask from previous pruning iteration, if any. To be considered when determining what portion of the tensor that pruning should act on. If None, default to a mask of ones. Returns
pruned version of tensor t.
remove(module)
Removes the pruning reparameterization from a module. The pruned parameter named name remains permanently pruned, and the parameter named name+'_orig' is removed from the parameter list. Similarly, the buffer named name+'_mask' is removed from the buffers. Note Pruning itself is NOT undone or reversed! | torch.generated.torch.nn.utils.prune.l1unstructured#torch.nn.utils.prune.L1Unstructured |
classmethod apply(module, name, amount, importance_scores=None) [source]
Adds the forward pre-hook that enables pruning on the fly and the reparametrization of a tensor in terms of the original tensor and the pruning mask. Parameters
module (nn.Module) – module containing the tensor to prune
name (str) – parameter name within module on which pruning will act.
amount (int or float) – quantity of parameters to prune. If float, should be between 0.0 and 1.0 and represent the fraction of parameters to prune. If int, it represents the absolute number of parameters to prune.
importance_scores (torch.Tensor) – tensor of importance scores (of same shape as module parameter) used to compute mask for pruning. The values in this tensor indicate the importance of the corresponding elements in the parameter being pruned. If unspecified or None, the module parameter will be used in its place. | torch.generated.torch.nn.utils.prune.l1unstructured#torch.nn.utils.prune.L1Unstructured.apply |
apply_mask(module)
Simply handles the multiplication between the parameter being pruned and the generated mask. Fetches the mask and the original tensor from the module and returns the pruned version of the tensor. Parameters
module (nn.Module) – module containing the tensor to prune Returns
pruned version of the input tensor Return type
pruned_tensor (torch.Tensor) | torch.generated.torch.nn.utils.prune.l1unstructured#torch.nn.utils.prune.L1Unstructured.apply_mask |
prune(t, default_mask=None, importance_scores=None)
Computes and returns a pruned version of input tensor t according to the pruning rule specified in compute_mask(). Parameters
t (torch.Tensor) – tensor to prune (of same dimensions as default_mask).
importance_scores (torch.Tensor) – tensor of importance scores (of same shape as t) used to compute mask for pruning t. The values in this tensor indicate the importance of the corresponding elements in the t that is being pruned. If unspecified or None, the tensor t will be used in its place.
default_mask (torch.Tensor, optional) – mask from previous pruning iteration, if any. To be considered when determining what portion of the tensor that pruning should act on. If None, default to a mask of ones. Returns
pruned version of tensor t. | torch.generated.torch.nn.utils.prune.l1unstructured#torch.nn.utils.prune.L1Unstructured.prune |
remove(module)
Removes the pruning reparameterization from a module. The pruned parameter named name remains permanently pruned, and the parameter named name+'_orig' is removed from the parameter list. Similarly, the buffer named name+'_mask' is removed from the buffers. Note Pruning itself is NOT undone or reversed! | torch.generated.torch.nn.utils.prune.l1unstructured#torch.nn.utils.prune.L1Unstructured.remove |
torch.nn.utils.prune.l1_unstructured(module, name, amount, importance_scores=None) [source]
Prunes tensor corresponding to parameter called name in module by removing the specified amount of (currently unpruned) units with the lowest L1-norm. Modifies module in place (and also return the modified module) by: 1) adding a named buffer called name+'_mask' corresponding to the binary mask applied to the parameter name by the pruning method. 2) replacing the parameter name by its pruned version, while the original (unpruned) parameter is stored in a new parameter named name+'_orig'. Parameters
module (nn.Module) – module containing the tensor to prune
name (str) – parameter name within module on which pruning will act.
amount (int or float) – quantity of parameters to prune. If float, should be between 0.0 and 1.0 and represent the fraction of parameters to prune. If int, it represents the absolute number of parameters to prune.
importance_scores (torch.Tensor) – tensor of importance scores (of same shape as module parameter) used to compute mask for pruning. The values in this tensor indicate the importance of the corresponding elements in the parameter being pruned. If unspecified or None, the module parameter will be used in its place. Returns
modified (i.e. pruned) version of the input module Return type
module (nn.Module) Examples >>> m = prune.l1_unstructured(nn.Linear(2, 3), 'weight', amount=0.2)
>>> m.state_dict().keys()
odict_keys(['bias', 'weight_orig', 'weight_mask']) | torch.generated.torch.nn.utils.prune.l1_unstructured#torch.nn.utils.prune.l1_unstructured |
class torch.nn.utils.prune.LnStructured(amount, n, dim=-1) [source]
Prune entire (currently unpruned) channels in a tensor based on their Ln-norm. Parameters
amount (int or float) – quantity of channels to prune. If float, should be between 0.0 and 1.0 and represent the fraction of parameters to prune. If int, it represents the absolute number of parameters to prune.
n (int, float, inf, -inf, 'fro', 'nuc') – See documentation of valid entries for argument p in torch.norm().
dim (int, optional) – index of the dim along which we define channels to prune. Default: -1.
classmethod apply(module, name, amount, n, dim, importance_scores=None) [source]
Adds the forward pre-hook that enables pruning on the fly and the reparametrization of a tensor in terms of the original tensor and the pruning mask. Parameters
module (nn.Module) – module containing the tensor to prune
name (str) – parameter name within module on which pruning will act.
amount (int or float) – quantity of parameters to prune. If float, should be between 0.0 and 1.0 and represent the fraction of parameters to prune. If int, it represents the absolute number of parameters to prune.
n (int, float, inf, -inf, 'fro', 'nuc') – See documentation of valid entries for argument p in torch.norm().
dim (int) – index of the dim along which we define channels to prune.
importance_scores (torch.Tensor) – tensor of importance scores (of same shape as module parameter) used to compute mask for pruning. The values in this tensor indicate the importance of the corresponding elements in the parameter being pruned. If unspecified or None, the module parameter will be used in its place.
apply_mask(module)
Simply handles the multiplication between the parameter being pruned and the generated mask. Fetches the mask and the original tensor from the module and returns the pruned version of the tensor. Parameters
module (nn.Module) – module containing the tensor to prune Returns
pruned version of the input tensor Return type
pruned_tensor (torch.Tensor)
compute_mask(t, default_mask) [source]
Computes and returns a mask for the input tensor t. Starting from a base default_mask (which should be a mask of ones if the tensor has not been pruned yet), generate a mask to apply on top of the default_mask by zeroing out the channels along the specified dim with the lowest Ln-norm. Parameters
t (torch.Tensor) – tensor representing the parameter to prune
default_mask (torch.Tensor) – Base mask from previous pruning iterations, that need to be respected after the new mask is applied. Same dims as t. Returns
mask to apply to t, of same dims as t Return type
mask (torch.Tensor) Raises
IndexError – if self.dim >= len(t.shape)
prune(t, default_mask=None, importance_scores=None)
Computes and returns a pruned version of input tensor t according to the pruning rule specified in compute_mask(). Parameters
t (torch.Tensor) – tensor to prune (of same dimensions as default_mask).
importance_scores (torch.Tensor) – tensor of importance scores (of same shape as t) used to compute mask for pruning t. The values in this tensor indicate the importance of the corresponding elements in the t that is being pruned. If unspecified or None, the tensor t will be used in its place.
default_mask (torch.Tensor, optional) – mask from previous pruning iteration, if any. To be considered when determining what portion of the tensor that pruning should act on. If None, default to a mask of ones. Returns
pruned version of tensor t.
remove(module)
Removes the pruning reparameterization from a module. The pruned parameter named name remains permanently pruned, and the parameter named name+'_orig' is removed from the parameter list. Similarly, the buffer named name+'_mask' is removed from the buffers. Note Pruning itself is NOT undone or reversed! | torch.generated.torch.nn.utils.prune.lnstructured#torch.nn.utils.prune.LnStructured |
classmethod apply(module, name, amount, n, dim, importance_scores=None) [source]
Adds the forward pre-hook that enables pruning on the fly and the reparametrization of a tensor in terms of the original tensor and the pruning mask. Parameters
module (nn.Module) – module containing the tensor to prune
name (str) – parameter name within module on which pruning will act.
amount (int or float) – quantity of parameters to prune. If float, should be between 0.0 and 1.0 and represent the fraction of parameters to prune. If int, it represents the absolute number of parameters to prune.
n (int, float, inf, -inf, 'fro', 'nuc') – See documentation of valid entries for argument p in torch.norm().
dim (int) – index of the dim along which we define channels to prune.
importance_scores (torch.Tensor) – tensor of importance scores (of same shape as module parameter) used to compute mask for pruning. The values in this tensor indicate the importance of the corresponding elements in the parameter being pruned. If unspecified or None, the module parameter will be used in its place. | torch.generated.torch.nn.utils.prune.lnstructured#torch.nn.utils.prune.LnStructured.apply |
apply_mask(module)
Simply handles the multiplication between the parameter being pruned and the generated mask. Fetches the mask and the original tensor from the module and returns the pruned version of the tensor. Parameters
module (nn.Module) – module containing the tensor to prune Returns
pruned version of the input tensor Return type
pruned_tensor (torch.Tensor) | torch.generated.torch.nn.utils.prune.lnstructured#torch.nn.utils.prune.LnStructured.apply_mask |
compute_mask(t, default_mask) [source]
Computes and returns a mask for the input tensor t. Starting from a base default_mask (which should be a mask of ones if the tensor has not been pruned yet), generate a mask to apply on top of the default_mask by zeroing out the channels along the specified dim with the lowest Ln-norm. Parameters
t (torch.Tensor) – tensor representing the parameter to prune
default_mask (torch.Tensor) – Base mask from previous pruning iterations, that need to be respected after the new mask is applied. Same dims as t. Returns
mask to apply to t, of same dims as t Return type
mask (torch.Tensor) Raises
IndexError – if self.dim >= len(t.shape) | torch.generated.torch.nn.utils.prune.lnstructured#torch.nn.utils.prune.LnStructured.compute_mask |
prune(t, default_mask=None, importance_scores=None)
Computes and returns a pruned version of input tensor t according to the pruning rule specified in compute_mask(). Parameters
t (torch.Tensor) – tensor to prune (of same dimensions as default_mask).
importance_scores (torch.Tensor) – tensor of importance scores (of same shape as t) used to compute mask for pruning t. The values in this tensor indicate the importance of the corresponding elements in the t that is being pruned. If unspecified or None, the tensor t will be used in its place.
default_mask (torch.Tensor, optional) – mask from previous pruning iteration, if any. To be considered when determining what portion of the tensor that pruning should act on. If None, default to a mask of ones. Returns
pruned version of tensor t. | torch.generated.torch.nn.utils.prune.lnstructured#torch.nn.utils.prune.LnStructured.prune |
remove(module)
Removes the pruning reparameterization from a module. The pruned parameter named name remains permanently pruned, and the parameter named name+'_orig' is removed from the parameter list. Similarly, the buffer named name+'_mask' is removed from the buffers. Note Pruning itself is NOT undone or reversed! | torch.generated.torch.nn.utils.prune.lnstructured#torch.nn.utils.prune.LnStructured.remove |
torch.nn.utils.prune.ln_structured(module, name, amount, n, dim, importance_scores=None) [source]
Prunes tensor corresponding to parameter called name in module by removing the specified amount of (currently unpruned) channels along the specified dim with the lowest L``n``-norm. Modifies module in place (and also return the modified module) by: 1) adding a named buffer called name+'_mask' corresponding to the binary mask applied to the parameter name by the pruning method. 2) replacing the parameter name by its pruned version, while the original (unpruned) parameter is stored in a new parameter named name+'_orig'. Parameters
module (nn.Module) – module containing the tensor to prune
name (str) – parameter name within module on which pruning will act.
amount (int or float) – quantity of parameters to prune. If float, should be between 0.0 and 1.0 and represent the fraction of parameters to prune. If int, it represents the absolute number of parameters to prune.
n (int, float, inf, -inf, 'fro', 'nuc') – See documentation of valid entries for argument p in torch.norm().
dim (int) – index of the dim along which we define channels to prune.
importance_scores (torch.Tensor) – tensor of importance scores (of same shape as module parameter) used to compute mask for pruning. The values in this tensor indicate the importance of the corresponding elements in the parameter being pruned. If unspecified or None, the module parameter will be used in its place. Returns
modified (i.e. pruned) version of the input module Return type
module (nn.Module) Examples >>> m = prune.ln_structured(
nn.Conv2d(5, 3, 2), 'weight', amount=0.3, dim=1, n=float('-inf')
) | torch.generated.torch.nn.utils.prune.ln_structured#torch.nn.utils.prune.ln_structured |
class torch.nn.utils.prune.PruningContainer(*args) [source]
Container holding a sequence of pruning methods for iterative pruning. Keeps track of the order in which pruning methods are applied and handles combining successive pruning calls. Accepts as argument an instance of a BasePruningMethod or an iterable of them.
add_pruning_method(method) [source]
Adds a child pruning method to the container. Parameters
method (subclass of BasePruningMethod) – child pruning method to be added to the container.
classmethod apply(module, name, *args, importance_scores=None, **kwargs)
Adds the forward pre-hook that enables pruning on the fly and the reparametrization of a tensor in terms of the original tensor and the pruning mask. Parameters
module (nn.Module) – module containing the tensor to prune
name (str) – parameter name within module on which pruning will act.
args – arguments passed on to a subclass of BasePruningMethod
importance_scores (torch.Tensor) – tensor of importance scores (of same shape as module parameter) used to compute mask for pruning. The values in this tensor indicate the importance of the corresponding elements in the parameter being pruned. If unspecified or None, the parameter will be used in its place.
kwargs – keyword arguments passed on to a subclass of a BasePruningMethod
apply_mask(module)
Simply handles the multiplication between the parameter being pruned and the generated mask. Fetches the mask and the original tensor from the module and returns the pruned version of the tensor. Parameters
module (nn.Module) – module containing the tensor to prune Returns
pruned version of the input tensor Return type
pruned_tensor (torch.Tensor)
compute_mask(t, default_mask) [source]
Applies the latest method by computing the new partial masks and returning its combination with the default_mask. The new partial mask should be computed on the entries or channels that were not zeroed out by the default_mask. Which portions of the tensor t the new mask will be calculated from depends on the PRUNING_TYPE (handled by the type handler): for ‘unstructured’, the mask will be computed from the raveled list of nonmasked entries; for ‘structured’, the mask will be computed from the nonmasked channels in the tensor; for ‘global’, the mask will be computed across all entries. Parameters
t (torch.Tensor) – tensor representing the parameter to prune (of same dimensions as default_mask).
default_mask (torch.Tensor) – mask from previous pruning iteration. Returns
new mask that combines the effects of the default_mask and the new mask from the current pruning method (of same dimensions as default_mask and t). Return type
mask (torch.Tensor)
prune(t, default_mask=None, importance_scores=None)
Computes and returns a pruned version of input tensor t according to the pruning rule specified in compute_mask(). Parameters
t (torch.Tensor) – tensor to prune (of same dimensions as default_mask).
importance_scores (torch.Tensor) – tensor of importance scores (of same shape as t) used to compute mask for pruning t. The values in this tensor indicate the importance of the corresponding elements in the t that is being pruned. If unspecified or None, the tensor t will be used in its place.
default_mask (torch.Tensor, optional) – mask from previous pruning iteration, if any. To be considered when determining what portion of the tensor that pruning should act on. If None, default to a mask of ones. Returns
pruned version of tensor t.
remove(module)
Removes the pruning reparameterization from a module. The pruned parameter named name remains permanently pruned, and the parameter named name+'_orig' is removed from the parameter list. Similarly, the buffer named name+'_mask' is removed from the buffers. Note Pruning itself is NOT undone or reversed! | torch.generated.torch.nn.utils.prune.pruningcontainer#torch.nn.utils.prune.PruningContainer |
add_pruning_method(method) [source]
Adds a child pruning method to the container. Parameters
method (subclass of BasePruningMethod) – child pruning method to be added to the container. | torch.generated.torch.nn.utils.prune.pruningcontainer#torch.nn.utils.prune.PruningContainer.add_pruning_method |
classmethod apply(module, name, *args, importance_scores=None, **kwargs)
Adds the forward pre-hook that enables pruning on the fly and the reparametrization of a tensor in terms of the original tensor and the pruning mask. Parameters
module (nn.Module) – module containing the tensor to prune
name (str) – parameter name within module on which pruning will act.
args – arguments passed on to a subclass of BasePruningMethod
importance_scores (torch.Tensor) – tensor of importance scores (of same shape as module parameter) used to compute mask for pruning. The values in this tensor indicate the importance of the corresponding elements in the parameter being pruned. If unspecified or None, the parameter will be used in its place.
kwargs – keyword arguments passed on to a subclass of a BasePruningMethod | torch.generated.torch.nn.utils.prune.pruningcontainer#torch.nn.utils.prune.PruningContainer.apply |
apply_mask(module)
Simply handles the multiplication between the parameter being pruned and the generated mask. Fetches the mask and the original tensor from the module and returns the pruned version of the tensor. Parameters
module (nn.Module) – module containing the tensor to prune Returns
pruned version of the input tensor Return type
pruned_tensor (torch.Tensor) | torch.generated.torch.nn.utils.prune.pruningcontainer#torch.nn.utils.prune.PruningContainer.apply_mask |
compute_mask(t, default_mask) [source]
Applies the latest method by computing the new partial masks and returning its combination with the default_mask. The new partial mask should be computed on the entries or channels that were not zeroed out by the default_mask. Which portions of the tensor t the new mask will be calculated from depends on the PRUNING_TYPE (handled by the type handler): for ‘unstructured’, the mask will be computed from the raveled list of nonmasked entries; for ‘structured’, the mask will be computed from the nonmasked channels in the tensor; for ‘global’, the mask will be computed across all entries. Parameters
t (torch.Tensor) – tensor representing the parameter to prune (of same dimensions as default_mask).
default_mask (torch.Tensor) – mask from previous pruning iteration. Returns
new mask that combines the effects of the default_mask and the new mask from the current pruning method (of same dimensions as default_mask and t). Return type
mask (torch.Tensor) | torch.generated.torch.nn.utils.prune.pruningcontainer#torch.nn.utils.prune.PruningContainer.compute_mask |
prune(t, default_mask=None, importance_scores=None)
Computes and returns a pruned version of input tensor t according to the pruning rule specified in compute_mask(). Parameters
t (torch.Tensor) – tensor to prune (of same dimensions as default_mask).
importance_scores (torch.Tensor) – tensor of importance scores (of same shape as t) used to compute mask for pruning t. The values in this tensor indicate the importance of the corresponding elements in the t that is being pruned. If unspecified or None, the tensor t will be used in its place.
default_mask (torch.Tensor, optional) – mask from previous pruning iteration, if any. To be considered when determining what portion of the tensor that pruning should act on. If None, default to a mask of ones. Returns
pruned version of tensor t. | torch.generated.torch.nn.utils.prune.pruningcontainer#torch.nn.utils.prune.PruningContainer.prune |
remove(module)
Removes the pruning reparameterization from a module. The pruned parameter named name remains permanently pruned, and the parameter named name+'_orig' is removed from the parameter list. Similarly, the buffer named name+'_mask' is removed from the buffers. Note Pruning itself is NOT undone or reversed! | torch.generated.torch.nn.utils.prune.pruningcontainer#torch.nn.utils.prune.PruningContainer.remove |
class torch.nn.utils.prune.RandomStructured(amount, dim=-1) [source]
Prune entire (currently unpruned) channels in a tensor at random. Parameters
amount (int or float) – quantity of parameters to prune. If float, should be between 0.0 and 1.0 and represent the fraction of parameters to prune. If int, it represents the absolute number of parameters to prune.
dim (int, optional) – index of the dim along which we define channels to prune. Default: -1.
classmethod apply(module, name, amount, dim=-1) [source]
Adds the forward pre-hook that enables pruning on the fly and the reparametrization of a tensor in terms of the original tensor and the pruning mask. Parameters
module (nn.Module) – module containing the tensor to prune
name (str) – parameter name within module on which pruning will act.
amount (int or float) – quantity of parameters to prune. If float, should be between 0.0 and 1.0 and represent the fraction of parameters to prune. If int, it represents the absolute number of parameters to prune.
dim (int, optional) – index of the dim along which we define channels to prune. Default: -1.
apply_mask(module)
Simply handles the multiplication between the parameter being pruned and the generated mask. Fetches the mask and the original tensor from the module and returns the pruned version of the tensor. Parameters
module (nn.Module) – module containing the tensor to prune Returns
pruned version of the input tensor Return type
pruned_tensor (torch.Tensor)
compute_mask(t, default_mask) [source]
Computes and returns a mask for the input tensor t. Starting from a base default_mask (which should be a mask of ones if the tensor has not been pruned yet), generate a random mask to apply on top of the default_mask by randomly zeroing out channels along the specified dim of the tensor. Parameters
t (torch.Tensor) – tensor representing the parameter to prune
default_mask (torch.Tensor) – Base mask from previous pruning iterations, that need to be respected after the new mask is applied. Same dims as t. Returns
mask to apply to t, of same dims as t Return type
mask (torch.Tensor) Raises
IndexError – if self.dim >= len(t.shape)
prune(t, default_mask=None, importance_scores=None)
Computes and returns a pruned version of input tensor t according to the pruning rule specified in compute_mask(). Parameters
t (torch.Tensor) – tensor to prune (of same dimensions as default_mask).
importance_scores (torch.Tensor) – tensor of importance scores (of same shape as t) used to compute mask for pruning t. The values in this tensor indicate the importance of the corresponding elements in the t that is being pruned. If unspecified or None, the tensor t will be used in its place.
default_mask (torch.Tensor, optional) – mask from previous pruning iteration, if any. To be considered when determining what portion of the tensor that pruning should act on. If None, default to a mask of ones. Returns
pruned version of tensor t.
remove(module)
Removes the pruning reparameterization from a module. The pruned parameter named name remains permanently pruned, and the parameter named name+'_orig' is removed from the parameter list. Similarly, the buffer named name+'_mask' is removed from the buffers. Note Pruning itself is NOT undone or reversed! | torch.generated.torch.nn.utils.prune.randomstructured#torch.nn.utils.prune.RandomStructured |
classmethod apply(module, name, amount, dim=-1) [source]
Adds the forward pre-hook that enables pruning on the fly and the reparametrization of a tensor in terms of the original tensor and the pruning mask. Parameters
module (nn.Module) – module containing the tensor to prune
name (str) – parameter name within module on which pruning will act.
amount (int or float) – quantity of parameters to prune. If float, should be between 0.0 and 1.0 and represent the fraction of parameters to prune. If int, it represents the absolute number of parameters to prune.
dim (int, optional) – index of the dim along which we define channels to prune. Default: -1. | torch.generated.torch.nn.utils.prune.randomstructured#torch.nn.utils.prune.RandomStructured.apply |
apply_mask(module)
Simply handles the multiplication between the parameter being pruned and the generated mask. Fetches the mask and the original tensor from the module and returns the pruned version of the tensor. Parameters
module (nn.Module) – module containing the tensor to prune Returns
pruned version of the input tensor Return type
pruned_tensor (torch.Tensor) | torch.generated.torch.nn.utils.prune.randomstructured#torch.nn.utils.prune.RandomStructured.apply_mask |
compute_mask(t, default_mask) [source]
Computes and returns a mask for the input tensor t. Starting from a base default_mask (which should be a mask of ones if the tensor has not been pruned yet), generate a random mask to apply on top of the default_mask by randomly zeroing out channels along the specified dim of the tensor. Parameters
t (torch.Tensor) – tensor representing the parameter to prune
default_mask (torch.Tensor) – Base mask from previous pruning iterations, that need to be respected after the new mask is applied. Same dims as t. Returns
mask to apply to t, of same dims as t Return type
mask (torch.Tensor) Raises
IndexError – if self.dim >= len(t.shape) | torch.generated.torch.nn.utils.prune.randomstructured#torch.nn.utils.prune.RandomStructured.compute_mask |
prune(t, default_mask=None, importance_scores=None)
Computes and returns a pruned version of input tensor t according to the pruning rule specified in compute_mask(). Parameters
t (torch.Tensor) – tensor to prune (of same dimensions as default_mask).
importance_scores (torch.Tensor) – tensor of importance scores (of same shape as t) used to compute mask for pruning t. The values in this tensor indicate the importance of the corresponding elements in the t that is being pruned. If unspecified or None, the tensor t will be used in its place.
default_mask (torch.Tensor, optional) – mask from previous pruning iteration, if any. To be considered when determining what portion of the tensor that pruning should act on. If None, default to a mask of ones. Returns
pruned version of tensor t. | torch.generated.torch.nn.utils.prune.randomstructured#torch.nn.utils.prune.RandomStructured.prune |
remove(module)
Removes the pruning reparameterization from a module. The pruned parameter named name remains permanently pruned, and the parameter named name+'_orig' is removed from the parameter list. Similarly, the buffer named name+'_mask' is removed from the buffers. Note Pruning itself is NOT undone or reversed! | torch.generated.torch.nn.utils.prune.randomstructured#torch.nn.utils.prune.RandomStructured.remove |
class torch.nn.utils.prune.RandomUnstructured(amount) [source]
Prune (currently unpruned) units in a tensor at random. Parameters
name (str) – parameter name within module on which pruning will act.
amount (int or float) – quantity of parameters to prune. If float, should be between 0.0 and 1.0 and represent the fraction of parameters to prune. If int, it represents the absolute number of parameters to prune.
classmethod apply(module, name, amount) [source]
Adds the forward pre-hook that enables pruning on the fly and the reparametrization of a tensor in terms of the original tensor and the pruning mask. Parameters
module (nn.Module) – module containing the tensor to prune
name (str) – parameter name within module on which pruning will act.
amount (int or float) – quantity of parameters to prune. If float, should be between 0.0 and 1.0 and represent the fraction of parameters to prune. If int, it represents the absolute number of parameters to prune.
apply_mask(module)
Simply handles the multiplication between the parameter being pruned and the generated mask. Fetches the mask and the original tensor from the module and returns the pruned version of the tensor. Parameters
module (nn.Module) – module containing the tensor to prune Returns
pruned version of the input tensor Return type
pruned_tensor (torch.Tensor)
prune(t, default_mask=None, importance_scores=None)
Computes and returns a pruned version of input tensor t according to the pruning rule specified in compute_mask(). Parameters
t (torch.Tensor) – tensor to prune (of same dimensions as default_mask).
importance_scores (torch.Tensor) – tensor of importance scores (of same shape as t) used to compute mask for pruning t. The values in this tensor indicate the importance of the corresponding elements in the t that is being pruned. If unspecified or None, the tensor t will be used in its place.
default_mask (torch.Tensor, optional) – mask from previous pruning iteration, if any. To be considered when determining what portion of the tensor that pruning should act on. If None, default to a mask of ones. Returns
pruned version of tensor t.
remove(module)
Removes the pruning reparameterization from a module. The pruned parameter named name remains permanently pruned, and the parameter named name+'_orig' is removed from the parameter list. Similarly, the buffer named name+'_mask' is removed from the buffers. Note Pruning itself is NOT undone or reversed! | torch.generated.torch.nn.utils.prune.randomunstructured#torch.nn.utils.prune.RandomUnstructured |
classmethod apply(module, name, amount) [source]
Adds the forward pre-hook that enables pruning on the fly and the reparametrization of a tensor in terms of the original tensor and the pruning mask. Parameters
module (nn.Module) – module containing the tensor to prune
name (str) – parameter name within module on which pruning will act.
amount (int or float) – quantity of parameters to prune. If float, should be between 0.0 and 1.0 and represent the fraction of parameters to prune. If int, it represents the absolute number of parameters to prune. | torch.generated.torch.nn.utils.prune.randomunstructured#torch.nn.utils.prune.RandomUnstructured.apply |
apply_mask(module)
Simply handles the multiplication between the parameter being pruned and the generated mask. Fetches the mask and the original tensor from the module and returns the pruned version of the tensor. Parameters
module (nn.Module) – module containing the tensor to prune Returns
pruned version of the input tensor Return type
pruned_tensor (torch.Tensor) | torch.generated.torch.nn.utils.prune.randomunstructured#torch.nn.utils.prune.RandomUnstructured.apply_mask |
prune(t, default_mask=None, importance_scores=None)
Computes and returns a pruned version of input tensor t according to the pruning rule specified in compute_mask(). Parameters
t (torch.Tensor) – tensor to prune (of same dimensions as default_mask).
importance_scores (torch.Tensor) – tensor of importance scores (of same shape as t) used to compute mask for pruning t. The values in this tensor indicate the importance of the corresponding elements in the t that is being pruned. If unspecified or None, the tensor t will be used in its place.
default_mask (torch.Tensor, optional) – mask from previous pruning iteration, if any. To be considered when determining what portion of the tensor that pruning should act on. If None, default to a mask of ones. Returns
pruned version of tensor t. | torch.generated.torch.nn.utils.prune.randomunstructured#torch.nn.utils.prune.RandomUnstructured.prune |
remove(module)
Removes the pruning reparameterization from a module. The pruned parameter named name remains permanently pruned, and the parameter named name+'_orig' is removed from the parameter list. Similarly, the buffer named name+'_mask' is removed from the buffers. Note Pruning itself is NOT undone or reversed! | torch.generated.torch.nn.utils.prune.randomunstructured#torch.nn.utils.prune.RandomUnstructured.remove |
torch.nn.utils.prune.random_structured(module, name, amount, dim) [source]
Prunes tensor corresponding to parameter called name in module by removing the specified amount of (currently unpruned) channels along the specified dim selected at random. Modifies module in place (and also return the modified module) by: 1) adding a named buffer called name+'_mask' corresponding to the binary mask applied to the parameter name by the pruning method. 2) replacing the parameter name by its pruned version, while the original (unpruned) parameter is stored in a new parameter named name+'_orig'. Parameters
module (nn.Module) – module containing the tensor to prune
name (str) – parameter name within module on which pruning will act.
amount (int or float) – quantity of parameters to prune. If float, should be between 0.0 and 1.0 and represent the fraction of parameters to prune. If int, it represents the absolute number of parameters to prune.
dim (int) – index of the dim along which we define channels to prune. Returns
modified (i.e. pruned) version of the input module Return type
module (nn.Module) Examples >>> m = prune.random_structured(
nn.Linear(5, 3), 'weight', amount=3, dim=1
)
>>> columns_pruned = int(sum(torch.sum(m.weight, dim=0) == 0))
>>> print(columns_pruned)
3 | torch.generated.torch.nn.utils.prune.random_structured#torch.nn.utils.prune.random_structured |
torch.nn.utils.prune.random_unstructured(module, name, amount) [source]
Prunes tensor corresponding to parameter called name in module by removing the specified amount of (currently unpruned) units selected at random. Modifies module in place (and also return the modified module) by: 1) adding a named buffer called name+'_mask' corresponding to the binary mask applied to the parameter name by the pruning method. 2) replacing the parameter name by its pruned version, while the original (unpruned) parameter is stored in a new parameter named name+'_orig'. Parameters
module (nn.Module) – module containing the tensor to prune
name (str) – parameter name within module on which pruning will act.
amount (int or float) – quantity of parameters to prune. If float, should be between 0.0 and 1.0 and represent the fraction of parameters to prune. If int, it represents the absolute number of parameters to prune. Returns
modified (i.e. pruned) version of the input module Return type
module (nn.Module) Examples >>> m = prune.random_unstructured(nn.Linear(2, 3), 'weight', amount=1)
>>> torch.sum(m.weight_mask == 0)
tensor(1) | torch.generated.torch.nn.utils.prune.random_unstructured#torch.nn.utils.prune.random_unstructured |
torch.nn.utils.prune.remove(module, name) [source]
Removes the pruning reparameterization from a module and the pruning method from the forward hook. The pruned parameter named name remains permanently pruned, and the parameter named name+'_orig' is removed from the parameter list. Similarly, the buffer named name+'_mask' is removed from the buffers. Note Pruning itself is NOT undone or reversed! Parameters
module (nn.Module) – module containing the tensor to prune
name (str) – parameter name within module on which pruning will act. Examples >>> m = random_unstructured(nn.Linear(5, 7), name='weight', amount=0.2)
>>> m = remove(m, name='weight') | torch.generated.torch.nn.utils.prune.remove#torch.nn.utils.prune.remove |
torch.nn.utils.remove_spectral_norm(module, name='weight') [source]
Removes the spectral normalization reparameterization from a module. Parameters
module (Module) – containing module
name (str, optional) – name of weight parameter Example >>> m = spectral_norm(nn.Linear(40, 10))
>>> remove_spectral_norm(m) | torch.generated.torch.nn.utils.remove_spectral_norm#torch.nn.utils.remove_spectral_norm |
torch.nn.utils.remove_weight_norm(module, name='weight') [source]
Removes the weight normalization reparameterization from a module. Parameters
module (Module) – containing module
name (str, optional) – name of weight parameter Example >>> m = weight_norm(nn.Linear(20, 40))
>>> remove_weight_norm(m) | torch.generated.torch.nn.utils.remove_weight_norm#torch.nn.utils.remove_weight_norm |
class torch.nn.utils.rnn.PackedSequence [source]
Holds the data and list of batch_sizes of a packed sequence. All RNN modules accept packed sequences as inputs. Note Instances of this class should never be created manually. They are meant to be instantiated by functions like pack_padded_sequence(). Batch sizes represent the number elements at each sequence step in the batch, not the varying sequence lengths passed to pack_padded_sequence(). For instance, given data abc and x the PackedSequence would contain data axbc with batch_sizes=[2,1,1]. Variables
~PackedSequence.data (Tensor) – Tensor containing packed sequence
~PackedSequence.batch_sizes (Tensor) – Tensor of integers holding information about the batch size at each sequence step
~PackedSequence.sorted_indices (Tensor, optional) – Tensor of integers holding how this PackedSequence is constructed from sequences.
~PackedSequence.unsorted_indices (Tensor, optional) – Tensor of integers holding how this to recover the original sequences with correct order. Note data can be on arbitrary device and of arbitrary dtype. sorted_indices and unsorted_indices must be torch.int64 tensors on the same device as data. However, batch_sizes should always be a CPU torch.int64 tensor. This invariant is maintained throughout PackedSequence class, and all functions that construct a :class:PackedSequence in PyTorch (i.e., they only pass in tensors conforming to this constraint).
property batch_sizes
Alias for field number 1
count()
Return number of occurrences of value.
property data
Alias for field number 0
index()
Return first index of value. Raises ValueError if the value is not present.
property is_cuda
Returns true if self.data stored on a gpu
is_pinned() [source]
Returns true if self.data stored on in pinned memory
property sorted_indices
Alias for field number 2
to(*args, **kwargs) [source]
Performs dtype and/or device conversion on self.data. It has similar signature as torch.Tensor.to(), except optional arguments like non_blocking and copy should be passed as kwargs, not args, or they will not apply to the index tensors. Note If the self.data Tensor already has the correct torch.dtype and torch.device, then self is returned. Otherwise, returns a copy with the desired configuration.
property unsorted_indices
Alias for field number 3 | torch.generated.torch.nn.utils.rnn.packedsequence#torch.nn.utils.rnn.PackedSequence |
property batch_sizes
Alias for field number 1 | torch.generated.torch.nn.utils.rnn.packedsequence#torch.nn.utils.rnn.PackedSequence.batch_sizes |
count()
Return number of occurrences of value. | torch.generated.torch.nn.utils.rnn.packedsequence#torch.nn.utils.rnn.PackedSequence.count |
property data
Alias for field number 0 | torch.generated.torch.nn.utils.rnn.packedsequence#torch.nn.utils.rnn.PackedSequence.data |
index()
Return first index of value. Raises ValueError if the value is not present. | torch.generated.torch.nn.utils.rnn.packedsequence#torch.nn.utils.rnn.PackedSequence.index |
property is_cuda
Returns true if self.data stored on a gpu | torch.generated.torch.nn.utils.rnn.packedsequence#torch.nn.utils.rnn.PackedSequence.is_cuda |
is_pinned() [source]
Returns true if self.data stored on in pinned memory | torch.generated.torch.nn.utils.rnn.packedsequence#torch.nn.utils.rnn.PackedSequence.is_pinned |
property sorted_indices
Alias for field number 2 | torch.generated.torch.nn.utils.rnn.packedsequence#torch.nn.utils.rnn.PackedSequence.sorted_indices |
to(*args, **kwargs) [source]
Performs dtype and/or device conversion on self.data. It has similar signature as torch.Tensor.to(), except optional arguments like non_blocking and copy should be passed as kwargs, not args, or they will not apply to the index tensors. Note If the self.data Tensor already has the correct torch.dtype and torch.device, then self is returned. Otherwise, returns a copy with the desired configuration. | torch.generated.torch.nn.utils.rnn.packedsequence#torch.nn.utils.rnn.PackedSequence.to |
property unsorted_indices
Alias for field number 3 | torch.generated.torch.nn.utils.rnn.packedsequence#torch.nn.utils.rnn.PackedSequence.unsorted_indices |
torch.nn.utils.rnn.pack_padded_sequence(input, lengths, batch_first=False, enforce_sorted=True) [source]
Packs a Tensor containing padded sequences of variable length. input can be of size T x B x * where T is the length of the longest sequence (equal to lengths[0]), B is the batch size, and * is any number of dimensions (including 0). If batch_first is True, B x T x * input is expected. For unsorted sequences, use enforce_sorted = False. If enforce_sorted is True, the sequences should be sorted by length in a decreasing order, i.e. input[:,0] should be the longest sequence, and input[:,B-1] the shortest one. enforce_sorted = True is only necessary for ONNX export. Note This function accepts any input that has at least two dimensions. You can apply it to pack the labels, and use the output of the RNN with them to compute the loss directly. A Tensor can be retrieved from a PackedSequence object by accessing its .data attribute. Parameters
input (Tensor) – padded batch of variable length sequences.
lengths (Tensor or list(int)) – list of sequence lengths of each batch element (must be on the CPU if provided as a tensor).
batch_first (bool, optional) – if True, the input is expected in B x T x * format.
enforce_sorted (bool, optional) – if True, the input is expected to contain sequences sorted by length in a decreasing order. If False, the input will get sorted unconditionally. Default: True. Returns
a PackedSequence object | torch.generated.torch.nn.utils.rnn.pack_padded_sequence#torch.nn.utils.rnn.pack_padded_sequence |
torch.nn.utils.rnn.pack_sequence(sequences, enforce_sorted=True) [source]
Packs a list of variable length Tensors sequences should be a list of Tensors of size L x *, where L is the length of a sequence and * is any number of trailing dimensions, including zero. For unsorted sequences, use enforce_sorted = False. If enforce_sorted is True, the sequences should be sorted in the order of decreasing length. enforce_sorted = True is only necessary for ONNX export. Example >>> from torch.nn.utils.rnn import pack_sequence
>>> a = torch.tensor([1,2,3])
>>> b = torch.tensor([4,5])
>>> c = torch.tensor([6])
>>> pack_sequence([a, b, c])
PackedSequence(data=tensor([ 1, 4, 6, 2, 5, 3]), batch_sizes=tensor([ 3, 2, 1]))
Parameters
sequences (list[Tensor]) – A list of sequences of decreasing length.
enforce_sorted (bool, optional) – if True, checks that the input contains sequences sorted by length in a decreasing order. If False, this condition is not checked. Default: True. Returns
a PackedSequence object | torch.generated.torch.nn.utils.rnn.pack_sequence#torch.nn.utils.rnn.pack_sequence |
torch.nn.utils.rnn.pad_packed_sequence(sequence, batch_first=False, padding_value=0.0, total_length=None) [source]
Pads a packed batch of variable length sequences. It is an inverse operation to pack_padded_sequence(). The returned Tensor’s data will be of size T x B x *, where T is the length of the longest sequence and B is the batch size. If batch_first is True, the data will be transposed into B x T x * format. Example >>> from torch.nn.utils.rnn import pack_padded_sequence, pad_packed_sequence
>>> seq = torch.tensor([[1,2,0], [3,0,0], [4,5,6]])
>>> lens = [2, 1, 3]
>>> packed = pack_padded_sequence(seq, lens, batch_first=True, enforce_sorted=False)
>>> packed
PackedSequence(data=tensor([4, 1, 3, 5, 2, 6]), batch_sizes=tensor([3, 2, 1]),
sorted_indices=tensor([2, 0, 1]), unsorted_indices=tensor([1, 2, 0]))
>>> seq_unpacked, lens_unpacked = pad_packed_sequence(packed, batch_first=True)
>>> seq_unpacked
tensor([[1, 2, 0],
[3, 0, 0],
[4, 5, 6]])
>>> lens_unpacked
tensor([2, 1, 3])
Note total_length is useful to implement the pack sequence -> recurrent network -> unpack sequence pattern in a Module wrapped in DataParallel. See this FAQ section for details. Parameters
sequence (PackedSequence) – batch to pad
batch_first (bool, optional) – if True, the output will be in B x T x * format.
padding_value (float, optional) – values for padded elements.
total_length (int, optional) – if not None, the output will be padded to have length total_length. This method will throw ValueError if total_length is less than the max sequence length in sequence. Returns
Tuple of Tensor containing the padded sequence, and a Tensor containing the list of lengths of each sequence in the batch. Batch elements will be re-ordered as they were ordered originally when the batch was passed to pack_padded_sequence or pack_sequence. | torch.generated.torch.nn.utils.rnn.pad_packed_sequence#torch.nn.utils.rnn.pad_packed_sequence |
torch.nn.utils.rnn.pad_sequence(sequences, batch_first=False, padding_value=0.0) [source]
Pad a list of variable length Tensors with padding_value pad_sequence stacks a list of Tensors along a new dimension, and pads them to equal length. For example, if the input is list of sequences with size L x * and if batch_first is False, and T x B x * otherwise. B is batch size. It is equal to the number of elements in sequences. T is length of the longest sequence. L is length of the sequence. * is any number of trailing dimensions, including none. Example >>> from torch.nn.utils.rnn import pad_sequence
>>> a = torch.ones(25, 300)
>>> b = torch.ones(22, 300)
>>> c = torch.ones(15, 300)
>>> pad_sequence([a, b, c]).size()
torch.Size([25, 3, 300])
Note This function returns a Tensor of size T x B x * or B x T x * where T is the length of the longest sequence. This function assumes trailing dimensions and type of all the Tensors in sequences are same. Parameters
sequences (list[Tensor]) – list of variable length sequences.
batch_first (bool, optional) – output will be in B x T x * if True, or in T x B x * otherwise
padding_value (float, optional) – value for padded elements. Default: 0. Returns
Tensor of size T x B x * if batch_first is False. Tensor of size B x T x * otherwise | torch.generated.torch.nn.utils.rnn.pad_sequence#torch.nn.utils.rnn.pad_sequence |
torch.nn.utils.spectral_norm(module, name='weight', n_power_iterations=1, eps=1e-12, dim=None) [source]
Applies spectral normalization to a parameter in the given module. WSN=Wσ(W),σ(W)=maxh:h≠0∥Wh∥2∥h∥2\mathbf{W}_{SN} = \dfrac{\mathbf{W}}{\sigma(\mathbf{W})}, \sigma(\mathbf{W}) = \max_{\mathbf{h}: \mathbf{h} \ne 0} \dfrac{\|\mathbf{W} \mathbf{h}\|_2}{\|\mathbf{h}\|_2}
Spectral normalization stabilizes the training of discriminators (critics) in Generative Adversarial Networks (GANs) by rescaling the weight tensor with spectral norm σ\sigma of the weight matrix calculated using power iteration method. If the dimension of the weight tensor is greater than 2, it is reshaped to 2D in power iteration method to get spectral norm. This is implemented via a hook that calculates spectral norm and rescales weight before every forward() call. See Spectral Normalization for Generative Adversarial Networks . Parameters
module (nn.Module) – containing module
name (str, optional) – name of weight parameter
n_power_iterations (int, optional) – number of power iterations to calculate spectral norm
eps (float, optional) – epsilon for numerical stability in calculating norms
dim (int, optional) – dimension corresponding to number of outputs, the default is 0, except for modules that are instances of ConvTranspose{1,2,3}d, when it is 1
Returns
The original module with the spectral norm hook Example: >>> m = spectral_norm(nn.Linear(20, 40))
>>> m
Linear(in_features=20, out_features=40, bias=True)
>>> m.weight_u.size()
torch.Size([40]) | torch.generated.torch.nn.utils.spectral_norm#torch.nn.utils.spectral_norm |
torch.nn.utils.vector_to_parameters(vec, parameters) [source]
Convert one vector to the parameters Parameters
vec (Tensor) – a single vector represents the parameters of a model.
parameters (Iterable[Tensor]) – an iterator of Tensors that are the parameters of a model. | torch.generated.torch.nn.utils.vector_to_parameters#torch.nn.utils.vector_to_parameters |
torch.nn.utils.weight_norm(module, name='weight', dim=0) [source]
Applies weight normalization to a parameter in the given module. w=gv∥v∥\mathbf{w} = g \dfrac{\mathbf{v}}{\|\mathbf{v}\|}
Weight normalization is a reparameterization that decouples the magnitude of a weight tensor from its direction. This replaces the parameter specified by name (e.g. 'weight') with two parameters: one specifying the magnitude (e.g. 'weight_g') and one specifying the direction (e.g. 'weight_v'). Weight normalization is implemented via a hook that recomputes the weight tensor from the magnitude and direction before every forward() call. By default, with dim=0, the norm is computed independently per output channel/plane. To compute a norm over the entire weight tensor, use dim=None. See https://arxiv.org/abs/1602.07868 Parameters
module (Module) – containing module
name (str, optional) – name of weight parameter
dim (int, optional) – dimension over which to compute the norm Returns
The original module with the weight norm hook Example: >>> m = weight_norm(nn.Linear(20, 40), name='weight')
>>> m
Linear(in_features=20, out_features=40, bias=True)
>>> m.weight_g.size()
torch.Size([40, 1])
>>> m.weight_v.size()
torch.Size([40, 20]) | torch.generated.torch.nn.utils.weight_norm#torch.nn.utils.weight_norm |
class torch.nn.ZeroPad2d(padding) [source]
Pads the input tensor boundaries with zero. For N-dimensional padding, use torch.nn.functional.pad(). Parameters
padding (int, tuple) – the size of the padding. If is int, uses the same padding in all boundaries. If a 4-tuple, uses (padding_left\text{padding\_left} , padding_right\text{padding\_right} , padding_top\text{padding\_top} , padding_bottom\text{padding\_bottom} ) Shape:
Input: (N,C,Hin,Win)(N, C, H_{in}, W_{in})
Output: (N,C,Hout,Wout)(N, C, H_{out}, W_{out}) where Hout=Hin+padding_top+padding_bottomH_{out} = H_{in} + \text{padding\_top} + \text{padding\_bottom} Wout=Win+padding_left+padding_rightW_{out} = W_{in} + \text{padding\_left} + \text{padding\_right} Examples: >>> m = nn.ZeroPad2d(2)
>>> input = torch.randn(1, 1, 3, 3)
>>> input
tensor([[[[-0.1678, -0.4418, 1.9466],
[ 0.9604, -0.4219, -0.5241],
[-0.9162, -0.5436, -0.6446]]]])
>>> m(input)
tensor([[[[ 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000],
[ 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000],
[ 0.0000, 0.0000, -0.1678, -0.4418, 1.9466, 0.0000, 0.0000],
[ 0.0000, 0.0000, 0.9604, -0.4219, -0.5241, 0.0000, 0.0000],
[ 0.0000, 0.0000, -0.9162, -0.5436, -0.6446, 0.0000, 0.0000],
[ 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000],
[ 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000]]]])
>>> # using different paddings for different sides
>>> m = nn.ZeroPad2d((1, 1, 2, 0))
>>> m(input)
tensor([[[[ 0.0000, 0.0000, 0.0000, 0.0000, 0.0000],
[ 0.0000, 0.0000, 0.0000, 0.0000, 0.0000],
[ 0.0000, -0.1678, -0.4418, 1.9466, 0.0000],
[ 0.0000, 0.9604, -0.4219, -0.5241, 0.0000],
[ 0.0000, -0.9162, -0.5436, -0.6446, 0.0000]]]]) | torch.generated.torch.nn.zeropad2d#torch.nn.ZeroPad2d |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.