text
stringlengths 0
1.73k
| source
stringlengths 35
119
| category
stringclasses 2
values |
---|---|---|
torch.Tensor.bitwise_right_shift
Tensor.bitwise_right_shift(other) -> Tensor
See "torch.bitwise_right_shift()" | https://pytorch.org/docs/stable/generated/torch.Tensor.bitwise_right_shift.html | pytorch docs |
StreamContext
class torch.cuda.StreamContext(stream)
Context-manager that selects a given stream.
All CUDA kernels queued within its context will be enqueued on a
selected stream.
Parameters:
Stream (Stream) -- selected stream. This manager is a no-
op if it's "None".
Note:
Streams are per-device.
| https://pytorch.org/docs/stable/generated/torch.cuda.StreamContext.html | pytorch docs |
torch.Tensor.sgn
Tensor.sgn() -> Tensor
See "torch.sgn()" | https://pytorch.org/docs/stable/generated/torch.Tensor.sgn.html | pytorch docs |
torch.fft.ifft
torch.fft.ifft(input, n=None, dim=- 1, norm=None, *, out=None) -> Tensor
Computes the one dimensional inverse discrete Fourier transform of
"input".
Note:
Supports torch.half and torch.chalf on CUDA with GPU Architecture
SM53 or greater. However it only supports powers of 2 signal
length in every transformed dimension.
Parameters:
* input (Tensor) -- the input tensor
* **n** (*int**, **optional*) -- Signal length. If given, the
input will either be zero-padded or trimmed to this length
before computing the IFFT.
* **dim** (*int**, **optional*) -- The dimension along which to
take the one dimensional IFFT.
* **norm** (*str**, **optional*) --
Normalization mode. For the backward transform ("ifft()"),
these correspond to:
* ""forward"" - no normalization
* ""backward"" - normalize by "1/n"
* ""ortho"" - normalize by "1/sqrt(n)" (making the IFFT
| https://pytorch.org/docs/stable/generated/torch.fft.ifft.html | pytorch docs |
orthonormal)
Calling the forward transform ("fft()") with the same
normalization mode will apply an overall normalization of
"1/n" between the two transforms. This is required to make
"ifft()" the exact inverse.
Default is ""backward"" (normalize by "1/n").
Keyword Arguments:
out (Tensor, optional) -- the output tensor.
-[ Example ]-
t = torch.tensor([ 6.+0.j, -2.+2.j, -2.+0.j, -2.-2.j])
torch.fft.ifft(t)
tensor([0.+0.j, 1.+0.j, 2.+0.j, 3.+0.j])
| https://pytorch.org/docs/stable/generated/torch.fft.ifft.html | pytorch docs |
torch.Tensor.frac_
Tensor.frac_() -> Tensor
In-place version of "frac()" | https://pytorch.org/docs/stable/generated/torch.Tensor.frac_.html | pytorch docs |
InstanceNorm1d
class torch.nn.InstanceNorm1d(num_features, eps=1e-05, momentum=0.1, affine=False, track_running_stats=False, device=None, dtype=None)
Applies Instance Normalization over a 2D (unbatched) or 3D
(batched) input as described in the paper Instance Normalization:
The Missing Ingredient for Fast Stylization.
y = \frac{x - \mathrm{E}[x]}{ \sqrt{\mathrm{Var}[x] + \epsilon}}
* \gamma + \beta
The mean and standard-deviation are calculated per-dimension
separately for each object in a mini-batch. \gamma and \beta are
learnable parameter vectors of size C (where C is the number of
features or channels of the input) if "affine" is "True". The
standard-deviation is calculated via the biased estimator,
equivalent to torch.var(input, unbiased=False).
By default, this layer uses instance statistics computed from input
data in both training and evaluation modes.
If "track_running_stats" is set to "True", during training this | https://pytorch.org/docs/stable/generated/torch.nn.InstanceNorm1d.html | pytorch docs |
layer keeps running estimates of its computed mean and variance,
which are then used for normalization during evaluation. The
running estimates are kept with a default "momentum" of 0.1.
Note:
This "momentum" argument is different from one used in optimizer
classes and the conventional notion of momentum. Mathematically,
the update rule for running statistics here is \hat{x}_\text{new}
= (1 - \text{momentum}) \times \hat{x} + \text{momentum} \times
x_t, where \hat{x} is the estimated statistic and x_t is the new
observed value.
Note:
"InstanceNorm1d" and "LayerNorm" are very similar, but have some
subtle differences. "InstanceNorm1d" is applied on each channel
of channeled data like multidimensional time series, but
"LayerNorm" is usually applied on entire sample and often in NLP
tasks. Additionally, "LayerNorm" applies elementwise affine
transform, while "InstanceNorm1d" usually don't apply affine
transform.
Parameters: | https://pytorch.org/docs/stable/generated/torch.nn.InstanceNorm1d.html | pytorch docs |
transform.
Parameters:
* num_features (int) -- number of features or channels C
of the input
* **eps** (*float*) -- a value added to the denominator for
numerical stability. Default: 1e-5
* **momentum** (*float*) -- the value used for the running_mean
and running_var computation. Default: 0.1
* **affine** (*bool*) -- a boolean value that when set to
"True", this module has learnable affine parameters,
initialized the same way as done for batch normalization.
Default: "False".
* **track_running_stats** (*bool*) -- a boolean value that when
set to "True", this module tracks the running mean and
variance, and when set to "False", this module does not track
such statistics and always uses batch statistics in both
training and eval modes. Default: "False"
Shape:
* Input: (N, C, L) or (C, L)
* Output: (N, C, L) or (C, L) (same shape as input)
Examples: | https://pytorch.org/docs/stable/generated/torch.nn.InstanceNorm1d.html | pytorch docs |
Examples:
>>> # Without Learnable Parameters
>>> m = nn.InstanceNorm1d(100)
>>> # With Learnable Parameters
>>> m = nn.InstanceNorm1d(100, affine=True)
>>> input = torch.randn(20, 100, 40)
>>> output = m(input)
| https://pytorch.org/docs/stable/generated/torch.nn.InstanceNorm1d.html | pytorch docs |
TransformerEncoder
class torch.nn.TransformerEncoder(encoder_layer, num_layers, norm=None, enable_nested_tensor=True, mask_check=True)
TransformerEncoder is a stack of N encoder layers. Users can build
the BERT(https://arxiv.org/abs/1810.04805) model with corresponding
parameters.
Parameters:
* encoder_layer -- an instance of the
TransformerEncoderLayer() class (required).
* **num_layers** -- the number of sub-encoder-layers in the
encoder (required).
* **norm** -- the layer normalization component (optional).
* **enable_nested_tensor** -- if True, input will automatically
convert to nested tensor (and convert back on output). This
will improve the overall performance of TransformerEncoder
when padding rate is high. Default: "True" (enabled).
Examples::
>>> encoder_layer = nn.TransformerEncoderLayer(d_model=512, nhead=8) | https://pytorch.org/docs/stable/generated/torch.nn.TransformerEncoder.html | pytorch docs |
transformer_encoder = nn.TransformerEncoder(encoder_layer, num_layers=6)
>>> src = torch.rand(10, 32, 512)
>>> out = transformer_encoder(src)
forward(src, mask=None, src_key_padding_mask=None, is_causal=None)
Pass the input through the encoder layers in turn.
Parameters:
* **src** (*Tensor*) -- the sequence to the encoder
(required).
* **mask** (*Optional**[**Tensor**]*) -- the mask for the src
sequence (optional).
* **is_causal** (*Optional**[**bool**]*) -- If specified,
applies a causal mask as mask (optional) and ignores
attn_mask for computing scaled dot product attention.
Default: "False".
* **src_key_padding_mask** (*Optional**[**Tensor**]*) -- the
mask for the src keys per batch (optional).
Return type:
*Tensor*
Shape:
see the docs in Transformer class.
| https://pytorch.org/docs/stable/generated/torch.nn.TransformerEncoder.html | pytorch docs |
torch.atan
torch.atan(input, *, out=None) -> Tensor
Returns a new tensor with the arctangent of the elements of
"input".
\text{out}_{i} = \tan^{-1}(\text{input}_{i})
Parameters:
input (Tensor) -- the input tensor.
Keyword Arguments:
out (Tensor, optional) -- the output tensor.
Example:
>>> a = torch.randn(4)
>>> a
tensor([ 0.2341, 0.2539, -0.6256, -0.6448])
>>> torch.atan(a)
tensor([ 0.2299, 0.2487, -0.5591, -0.5727])
| https://pytorch.org/docs/stable/generated/torch.atan.html | pytorch docs |
LayerNorm
class torch.ao.nn.quantized.LayerNorm(normalized_shape, weight, bias, scale, zero_point, eps=1e-05, elementwise_affine=True, device=None, dtype=None)
This is the quantized version of "LayerNorm".
Additional args:
* scale - quantization scale of the output, type: double.
* **zero_point** - quantization zero point of the output, type:
long.
| https://pytorch.org/docs/stable/generated/torch.ao.nn.quantized.LayerNorm.html | pytorch docs |
torch.nn.functional.embedding_bag
torch.nn.functional.embedding_bag(input, weight, offsets=None, max_norm=None, norm_type=2, scale_grad_by_freq=False, mode='mean', sparse=False, per_sample_weights=None, include_last_offset=False, padding_idx=None)
Computes sums, means or maxes of bags of embeddings, without
instantiating the intermediate embeddings.
See "torch.nn.EmbeddingBag" for more details.
Note:
This operation may produce nondeterministic gradients when given
tensors on a CUDA device. See Reproducibility for more
information.
Parameters:
* input (LongTensor) -- Tensor containing bags of indices
into the embedding matrix
* **weight** (*Tensor*) -- The embedding matrix with number of
rows equal to the maximum possible index + 1, and number of
columns equal to the embedding size
* **offsets** (*LongTensor**, **optional*) -- Only used when
| https://pytorch.org/docs/stable/generated/torch.nn.functional.embedding_bag.html | pytorch docs |
"input" is 1D. "offsets" determines the starting index
position of each bag (sequence) in "input".
* **max_norm** (*float**, **optional*) -- If given, each
embedding vector with norm larger than "max_norm" is
renormalized to have norm "max_norm". Note: this will modify
"weight" in-place.
* **norm_type** (*float**, **optional*) -- The "p" in the
"p"-norm to compute for the "max_norm" option. Default "2".
* **scale_grad_by_freq** (*bool**, **optional*) -- if given,
this will scale gradients by the inverse of frequency of the
words in the mini-batch. Default "False". Note: this option is
not supported when "mode="max"".
* **mode** (*str**, **optional*) -- ""sum"", ""mean"" or
""max"". Specifies the way to reduce the bag. Default:
""mean""
* **sparse** (*bool**, **optional*) -- if "True", gradient
w.r.t. "weight" will be a sparse tensor. See Notes under
| https://pytorch.org/docs/stable/generated/torch.nn.functional.embedding_bag.html | pytorch docs |
"torch.nn.Embedding" for more details regarding sparse
gradients. Note: this option is not supported when
"mode="max"".
* **per_sample_weights** (*Tensor**, **optional*) -- a tensor of
float / double weights, or None to indicate all weights should
be taken to be 1. If specified, "per_sample_weights" must have
exactly the same shape as input and is treated as having the
same "offsets", if those are not None.
* **include_last_offset** (*bool**, **optional*) -- if "True",
the size of offsets is equal to the number of bags + 1. The
last element is the size of the input, or the ending index
position of the last bag (sequence).
* **padding_idx** (*int**, **optional*) -- If specified, the
entries at "padding_idx" do not contribute to the gradient;
therefore, the embedding vector at "padding_idx" is not
updated during training, i.e. it remains as a fixed "pad".
| https://pytorch.org/docs/stable/generated/torch.nn.functional.embedding_bag.html | pytorch docs |
Note that the embedding vector at "padding_idx" is excluded
from the reduction.
Return type:
Tensor
Shape:
* "input" (LongTensor) and "offsets" (LongTensor, optional)
* If "input" is 2D of shape *(B, N)*, it will be treated as
"B" bags (sequences) each of fixed length "N", and this will
return "B" values aggregated in a way depending on the
"mode". "offsets" is ignored and required to be "None" in
this case.
* If "input" is 1D of shape *(N)*, it will be treated as a
concatenation of multiple bags (sequences). "offsets" is
required to be a 1D tensor containing the starting index
positions of each bag in "input". Therefore, for "offsets"
of shape *(B)*, "input" will be viewed as having "B" bags.
Empty bags (i.e., having 0-length) will have returned
vectors filled by zeros.
* "weight" (Tensor): the learnable weights of the module of
| https://pytorch.org/docs/stable/generated/torch.nn.functional.embedding_bag.html | pytorch docs |
shape (num_embeddings, embedding_dim)
* "per_sample_weights" (Tensor, optional). Has the same shape as
"input".
* "output": aggregated embedding values of shape *(B,
embedding_dim)*
Examples:
>>> # an Embedding module containing 10 tensors of size 3
>>> embedding_matrix = torch.rand(10, 3)
>>> # a batch of 2 samples of 4 indices each
>>> input = torch.tensor([1, 2, 4, 5, 4, 3, 2, 9])
>>> offsets = torch.tensor([0, 4])
>>> F.embedding_bag(input, embedding_matrix, offsets)
tensor([[ 0.3397, 0.3552, 0.5545],
[ 0.5893, 0.4386, 0.5882]])
>>> # example with padding_idx
>>> embedding_matrix = torch.rand(10, 3)
>>> input = torch.tensor([2, 2, 2, 2, 4, 3, 2, 9])
>>> offsets = torch.tensor([0, 4])
>>> F.embedding_bag(input, embedding_matrix, offsets, padding_idx=2, mode='sum')
tensor([[ 0.0000, 0.0000, 0.0000],
[-0.7082, 3.2145, -2.6251]])
| https://pytorch.org/docs/stable/generated/torch.nn.functional.embedding_bag.html | pytorch docs |
torch.Tensor.cos_
Tensor.cos_() -> Tensor
In-place version of "cos()" | https://pytorch.org/docs/stable/generated/torch.Tensor.cos_.html | pytorch docs |
torch.Tensor.logaddexp2
Tensor.logaddexp2(other) -> Tensor
See "torch.logaddexp2()" | https://pytorch.org/docs/stable/generated/torch.Tensor.logaddexp2.html | pytorch docs |
Identity
class torch.nn.Identity(args, *kwargs)
A placeholder identity operator that is argument-insensitive.
Parameters:
* args (Any) -- any argument (unused)
* **kwargs** (*Any*) -- any keyword argument (unused)
Shape:
* Input: (*), where * means any number of dimensions.
* Output: (*), same shape as the input.
Examples:
>>> m = nn.Identity(54, unused_argument1=0.1, unused_argument2=False)
>>> input = torch.randn(128, 20)
>>> output = m(input)
>>> print(output.size())
torch.Size([128, 20])
| https://pytorch.org/docs/stable/generated/torch.nn.Identity.html | pytorch docs |
torch.Tensor.positive
Tensor.positive() -> Tensor
See "torch.positive()" | https://pytorch.org/docs/stable/generated/torch.Tensor.positive.html | pytorch docs |
torch.Tensor.logit_
Tensor.logit_() -> Tensor
In-place version of "logit()" | https://pytorch.org/docs/stable/generated/torch.Tensor.logit_.html | pytorch docs |
torch.jit.script_if_tracing
torch.jit.script_if_tracing(fn)
Compiles "fn" when it is first called during tracing.
"torch.jit.script" has a non-negligible start up time when it is
first called due to lazy-initializations of many compiler builtins.
Therefore you should not use it in library code. However, you may
want to have parts of your library work in tracing even if they use
control flow. In these cases, you should use
"@torch.jit.script_if_tracing" to substitute for
"torch.jit.script".
Parameters:
fn -- A function to compile.
Returns:
If called during tracing, a "ScriptFunction" created by
torch.jit.script is returned. Otherwise, the original function
fn is returned. | https://pytorch.org/docs/stable/generated/torch.jit.script_if_tracing.html | pytorch docs |
torch._foreach_sigmoid
torch._foreach_sigmoid(self: List[Tensor]) -> List[Tensor]
Apply "torch.sigmoid()" to each Tensor of the input list. | https://pytorch.org/docs/stable/generated/torch._foreach_sigmoid.html | pytorch docs |
torch.Tensor.eq
Tensor.eq(other) -> Tensor
See "torch.eq()" | https://pytorch.org/docs/stable/generated/torch.Tensor.eq.html | pytorch docs |
torch.Tensor.zero_
Tensor.zero_() -> Tensor
Fills "self" tensor with zeros. | https://pytorch.org/docs/stable/generated/torch.Tensor.zero_.html | pytorch docs |
torch.Tensor.split
Tensor.split(split_size, dim=0)
See "torch.split()" | https://pytorch.org/docs/stable/generated/torch.Tensor.split.html | pytorch docs |
Dropout3d
class torch.nn.Dropout3d(p=0.5, inplace=False)
Randomly zero out entire channels (a channel is a 3D feature map,
e.g., the j-th channel of the i-th sample in the batched input is a
3D tensor \text{input}[i, j]). Each channel will be zeroed out
independently on every forward call with probability "p" using
samples from a Bernoulli distribution.
Usually the input comes from "nn.Conv3d" modules.
As described in the paper Efficient Object Localization Using
Convolutional Networks , if adjacent pixels within feature maps are
strongly correlated (as is normally the case in early convolution
layers) then i.i.d. dropout will not regularize the activations and
will otherwise just result in an effective learning rate decrease.
In this case, "nn.Dropout3d()" will help promote independence
between feature maps and should be used instead.
Parameters:
* p (float, optional) -- probability of an element to
be zeroed. | https://pytorch.org/docs/stable/generated/torch.nn.Dropout3d.html | pytorch docs |
be zeroed.
* **inplace** (*bool**, **optional*) -- If set to "True", will
do this operation in-place
Shape:
* Input: (N, C, D, H, W) or (C, D, H, W).
* Output: (N, C, D, H, W) or (C, D, H, W) (same shape as input).
Examples:
>>> m = nn.Dropout3d(p=0.2)
>>> input = torch.randn(20, 16, 4, 32, 32)
>>> output = m(input)
| https://pytorch.org/docs/stable/generated/torch.nn.Dropout3d.html | pytorch docs |
ASGD
class torch.optim.ASGD(params, lr=0.01, lambd=0.0001, alpha=0.75, t0=1000000.0, weight_decay=0, foreach=None, maximize=False, differentiable=False)
Implements Averaged Stochastic Gradient Descent.
It has been proposed in Acceleration of stochastic approximation by
averaging.
Parameters:
* params (iterable) -- iterable of parameters to optimize
or dicts defining parameter groups
* **lr** (*float**, **optional*) -- learning rate (default:
1e-2)
* **lambd** (*float**, **optional*) -- decay term (default:
1e-4)
* **alpha** (*float**, **optional*) -- power for eta update
(default: 0.75)
* **t0** (*float**, **optional*) -- point at which to start
averaging (default: 1e6)
* **weight_decay** (*float**, **optional*) -- weight decay (L2
penalty) (default: 0)
* **foreach** (*bool**, **optional*) -- whether foreach
implementation of optimizer is used. If unspecified by the
| https://pytorch.org/docs/stable/generated/torch.optim.ASGD.html | pytorch docs |
user (so foreach is None), we will try to use foreach over the
for-loop implementation on CUDA, since it is usually
significantly more performant. (default: None)
* **maximize** (*bool**, **optional*) -- maximize the params
based on the objective, instead of minimizing (default: False)
* **differentiable** (*bool**, **optional*) -- whether autograd
should occur through the optimizer step in training.
Otherwise, the step() function runs in a torch.no_grad()
context. Setting to True can impair performance, so leave it
False if you don't intend to run autograd through this
instance (default: False)
add_param_group(param_group)
Add a param group to the "Optimizer" s *param_groups*.
This can be useful when fine tuning a pre-trained network as
frozen layers can be made trainable and added to the "Optimizer"
as training progresses.
Parameters:
| https://pytorch.org/docs/stable/generated/torch.optim.ASGD.html | pytorch docs |
as training progresses.
Parameters:
**param_group** (*dict*) -- Specifies what Tensors should be
optimized along with group specific optimization options.
load_state_dict(state_dict)
Loads the optimizer state.
Parameters:
**state_dict** (*dict*) -- optimizer state. Should be an
object returned from a call to "state_dict()".
register_step_post_hook(hook)
Register an optimizer step post hook which will be called after
optimizer step. It should have the following signature:
hook(optimizer, args, kwargs) -> None
The "optimizer" argument is the optimizer instance being used.
Parameters:
**hook** (*Callable*) -- The user defined hook to be
registered.
Returns:
a handle that can be used to remove the added hook by calling
"handle.remove()"
Return type:
"torch.utils.hooks.RemoveableHandle"
register_step_pre_hook(hook) | https://pytorch.org/docs/stable/generated/torch.optim.ASGD.html | pytorch docs |
register_step_pre_hook(hook)
Register an optimizer step pre hook which will be called before
optimizer step. It should have the following signature:
hook(optimizer, args, kwargs) -> None or modified args and kwargs
The "optimizer" argument is the optimizer instance being used.
If args and kwargs are modified by the pre-hook, then the
transformed values are returned as a tuple containing the
new_args and new_kwargs.
Parameters:
**hook** (*Callable*) -- The user defined hook to be
registered.
Returns:
a handle that can be used to remove the added hook by calling
"handle.remove()"
Return type:
"torch.utils.hooks.RemoveableHandle"
state_dict()
Returns the state of the optimizer as a "dict".
It contains two entries:
* state - a dict holding current optimization state. Its content
differs between optimizer classes.
| https://pytorch.org/docs/stable/generated/torch.optim.ASGD.html | pytorch docs |
differs between optimizer classes.
* param_groups - a list containing all parameter groups where
each
parameter group is a dict
zero_grad(set_to_none=False)
Sets the gradients of all optimized "torch.Tensor" s to zero.
Parameters:
**set_to_none** (*bool*) -- instead of setting to zero, set
the grads to None. This will in general have lower memory
footprint, and can modestly improve performance. However, it
changes certain behaviors. For example: 1. When the user
tries to access a gradient and perform manual ops on it, a
None attribute or a Tensor full of 0s will behave
differently. 2. If the user requests
"zero_grad(set_to_none=True)" followed by a backward pass,
".grad"s are guaranteed to be None for params that did not
receive a gradient. 3. "torch.optim" optimizers have a
different behavior if the gradient is 0 or None (in one case
| https://pytorch.org/docs/stable/generated/torch.optim.ASGD.html | pytorch docs |
it does the step with a gradient of 0 and in the other it
skips the step altogether). | https://pytorch.org/docs/stable/generated/torch.optim.ASGD.html | pytorch docs |
torch.squeeze
torch.squeeze(input, dim=None) -> Tensor
Returns a tensor with all specified dimensions of "input" of size
1 removed.
For example, if input is of shape: (A \times 1 \times B \times C
\times 1 \times D) then the input.squeeze() will be of shape: (A
\times B \times C \times D).
When "dim" is given, a squeeze operation is done only in the given
dimension(s). If input is of shape: (A \times 1 \times B),
"squeeze(input, 0)" leaves the tensor unchanged, but
"squeeze(input, 1)" will squeeze the tensor to the shape (A \times
B).
Note:
The returned tensor shares the storage with the input tensor, so
changing the contents of one will change the contents of the
other.
Warning:
If the tensor has a batch dimension of size 1, then
*squeeze(input)* will also remove the batch dimension, which can
lead to unexpected errors. Consider specifying only the dims you
wish to be squeezed.
Parameters: | https://pytorch.org/docs/stable/generated/torch.squeeze.html | pytorch docs |
wish to be squeezed.
Parameters:
* input (Tensor) -- the input tensor.
* **dim** (*int** or **tuple of ints**, **optional*) --
if given, the input will be squeezed
only in the specified dimensions.
Changed in version 2.0: "dim" now accepts tuples of
dimensions.
Example:
>>> x = torch.zeros(2, 1, 2, 1, 2)
>>> x.size()
torch.Size([2, 1, 2, 1, 2])
>>> y = torch.squeeze(x)
>>> y.size()
torch.Size([2, 2, 2])
>>> y = torch.squeeze(x, 0)
>>> y.size()
torch.Size([2, 1, 2, 1, 2])
>>> y = torch.squeeze(x, 1)
>>> y.size()
torch.Size([2, 2, 1, 2])
>>> y = torch.squeeze(x, (1, 2, 3))
torch.Size([2, 2, 2])
| https://pytorch.org/docs/stable/generated/torch.squeeze.html | pytorch docs |
torch.cuda.empty_cache
torch.cuda.empty_cache()
Releases all unoccupied cached memory currently held by the caching
allocator so that those can be used in other GPU application and
visible in nvidia-smi.
Note:
"empty_cache()" doesn't increase the amount of GPU memory
available for PyTorch. However, it may help reduce fragmentation
of GPU memory in certain cases. See Memory management for more
details about GPU memory management.
| https://pytorch.org/docs/stable/generated/torch.cuda.empty_cache.html | pytorch docs |
torch.is_deterministic_algorithms_warn_only_enabled
torch.is_deterministic_algorithms_warn_only_enabled()
Returns True if the global deterministic flag is set to warn only.
Refer to "torch.use_deterministic_algorithms()" documentation for
more details. | https://pytorch.org/docs/stable/generated/torch.is_deterministic_algorithms_warn_only_enabled.html | pytorch docs |
torch.Tensor.sub_
Tensor.sub_(other, *, alpha=1) -> Tensor
In-place version of "sub()" | https://pytorch.org/docs/stable/generated/torch.Tensor.sub_.html | pytorch docs |
torch.nn.utils.rnn.pack_sequence
torch.nn.utils.rnn.pack_sequence(sequences, enforce_sorted=True)
Packs a list of variable length Tensors
Consecutive call of the next functions: "pad_sequence",
"pack_padded_sequence".
"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]), sorted_indices=None, unsorted_indices=None)
Parameters: | https://pytorch.org/docs/stable/generated/torch.nn.utils.rnn.pack_sequence.html | pytorch docs |
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
Return type:
PackedSequence | https://pytorch.org/docs/stable/generated/torch.nn.utils.rnn.pack_sequence.html | pytorch docs |
Sigmoid
class torch.ao.nn.quantized.Sigmoid(output_scale, output_zero_point)
This is the quantized equivalent of "Sigmoid".
Parameters:
* scale -- quantization scale of the output tensor
* **zero_point** -- quantization zero point of the output tensor
| https://pytorch.org/docs/stable/generated/torch.ao.nn.quantized.Sigmoid.html | pytorch docs |
torch.Tensor.moveaxis
Tensor.moveaxis(source, destination) -> Tensor
See "torch.moveaxis()" | https://pytorch.org/docs/stable/generated/torch.Tensor.moveaxis.html | pytorch docs |
torch.Tensor.gcd_
Tensor.gcd_(other) -> Tensor
In-place version of "gcd()" | https://pytorch.org/docs/stable/generated/torch.Tensor.gcd_.html | pytorch docs |
torch.Tensor.mean
Tensor.mean(dim=None, keepdim=False, *, dtype=None) -> Tensor
See "torch.mean()" | https://pytorch.org/docs/stable/generated/torch.Tensor.mean.html | pytorch docs |
torch.Tensor.resize_as_
Tensor.resize_as_(tensor, memory_format=torch.contiguous_format) -> Tensor
Resizes the "self" tensor to be the same size as the specified
"tensor". This is equivalent to "self.resize_(tensor.size())".
Parameters:
memory_format ("torch.memory_format", optional) -- the
desired memory format of Tensor. Default:
"torch.contiguous_format". Note that memory format of "self" is
going to be unaffected if "self.size()" matches "tensor.size()". | https://pytorch.org/docs/stable/generated/torch.Tensor.resize_as_.html | pytorch docs |
torch.Tensor.round
Tensor.round(decimals=0) -> Tensor
See "torch.round()" | https://pytorch.org/docs/stable/generated/torch.Tensor.round.html | pytorch docs |
torch.empty_strided
torch.empty_strided(size, stride, *, dtype=None, layout=None, device=None, requires_grad=False, pin_memory=False) -> Tensor
Creates a tensor with the specified "size" and "stride" and filled
with undefined data.
Warning:
If the constructed tensor is "overlapped" (with multiple indices
referring to the same element in memory) its behavior is
undefined.
Parameters:
* size (tuple of python:int) -- the shape of the output
tensor
* **stride** (*tuple of python:int*) -- the strides of the
output tensor
Keyword Arguments:
* dtype ("torch.dtype", optional) -- the desired data type
of returned tensor. Default: if "None", uses a global default
(see "torch.set_default_tensor_type()").
* **layout** ("torch.layout", optional) -- the desired layout of
returned Tensor. Default: "torch.strided".
* **device** ("torch.device", optional) -- the desired device of
| https://pytorch.org/docs/stable/generated/torch.empty_strided.html | pytorch docs |
returned tensor. Default: if "None", uses the current device
for the default tensor type (see
"torch.set_default_tensor_type()"). "device" will be the CPU
for CPU tensor types and the current CUDA device for CUDA
tensor types.
* **requires_grad** (*bool**, **optional*) -- If autograd should
record operations on the returned tensor. Default: "False".
* **pin_memory** (*bool**, **optional*) -- If set, returned
tensor would be allocated in the pinned memory. Works only for
CPU tensors. Default: "False".
Example:
>>> a = torch.empty_strided((2, 3), (1, 2))
>>> a
tensor([[8.9683e-44, 4.4842e-44, 5.1239e+07],
[0.0000e+00, 0.0000e+00, 3.0705e-41]])
>>> a.stride()
(1, 2)
>>> a.size()
torch.Size([2, 3])
| https://pytorch.org/docs/stable/generated/torch.empty_strided.html | pytorch docs |
torch.Tensor.absolute
Tensor.absolute() -> Tensor
Alias for "abs()" | https://pytorch.org/docs/stable/generated/torch.Tensor.absolute.html | pytorch docs |
torch.nn.functional.ctc_loss
torch.nn.functional.ctc_loss(log_probs, targets, input_lengths, target_lengths, blank=0, reduction='mean', zero_infinity=False)
The Connectionist Temporal Classification loss.
See "CTCLoss" for details.
Note:
In some circumstances when given tensors on a CUDA device and
using CuDNN, this operator may select a nondeterministic
algorithm to increase performance. If this is undesirable, you
can try to make the operation deterministic (potentially at a
performance cost) by setting "torch.backends.cudnn.deterministic
= True". See Reproducibility for more information.
Note:
This operation may produce nondeterministic gradients when given
tensors on a CUDA device. See Reproducibility for more
information.
Parameters:
* log_probs (Tensor) -- (T, N, C) or (T, C) where C =
number of characters in alphabet including blank, *T = input | https://pytorch.org/docs/stable/generated/torch.nn.functional.ctc_loss.html | pytorch docs |
length, and N = batch size*. The logarithmized probabilities
of the outputs (e.g. obtained with
"torch.nn.functional.log_softmax()").
* **targets** (*Tensor*) -- (N, S) or *(sum(target_lengths))*.
Targets cannot be blank. In the second form, the targets are
assumed to be concatenated.
* **input_lengths** (*Tensor*) -- (N) or (). Lengths of the
inputs (must each be \leq T)
* **target_lengths** (*Tensor*) -- (N) or (). Lengths of the
targets
* **blank** (*int**, **optional*) -- Blank label. Default 0.
* **reduction** (*str**, **optional*) -- Specifies the reduction
to apply to the output: "'none'" | "'mean'" | "'sum'".
"'none'": no reduction will be applied, "'mean'": the output
losses will be divided by the target lengths and then the mean
over the batch is taken, "'sum'": the output will be summed.
Default: "'mean'"
| https://pytorch.org/docs/stable/generated/torch.nn.functional.ctc_loss.html | pytorch docs |
Default: "'mean'"
* **zero_infinity** (*bool**, **optional*) -- Whether to zero
infinite losses and the associated gradients. Default: "False"
Infinite losses mainly occur when the inputs are too short to
be aligned to the targets.
Return type:
Tensor
Example:
>>> log_probs = torch.randn(50, 16, 20).log_softmax(2).detach().requires_grad_()
>>> targets = torch.randint(1, 20, (16, 30), dtype=torch.long)
>>> input_lengths = torch.full((16,), 50, dtype=torch.long)
>>> target_lengths = torch.randint(10, 30, (16,), dtype=torch.long)
>>> loss = F.ctc_loss(log_probs, targets, input_lengths, target_lengths)
>>> loss.backward()
| https://pytorch.org/docs/stable/generated/torch.nn.functional.ctc_loss.html | pytorch docs |
torch.mm
torch.mm(input, mat2, *, out=None) -> Tensor
Performs a matrix multiplication of the matrices "input" and
"mat2".
If "input" is a (n \times m) tensor, "mat2" is a (m \times p)
tensor, "out" will be a (n \times p) tensor.
Note:
This function does not broadcast. For broadcasting matrix
products, see "torch.matmul()".
Supports strided and sparse 2-D tensors as inputs, autograd with
respect to strided inputs.
This operation has support for arguments with sparse layouts. If
"out" is provided it's layout will be used. Otherwise, the result
layout will be deduced from that of "input".
Warning:
Sparse support is a beta feature and some layout(s)/dtype/device
combinations may not be supported, or may not have autograd
support. If you notice missing functionality please open a
feature request.
This operator supports TensorFloat32.
On certain ROCm devices, when using float16 inputs this module will | https://pytorch.org/docs/stable/generated/torch.mm.html | pytorch docs |
use different precision for backward.
Parameters:
* input (Tensor) -- the first matrix to be matrix
multiplied
* **mat2** (*Tensor*) -- the second matrix to be matrix
multiplied
Keyword Arguments:
out (Tensor, optional) -- the output tensor.
Example:
>>> mat1 = torch.randn(2, 3)
>>> mat2 = torch.randn(3, 3)
>>> torch.mm(mat1, mat2)
tensor([[ 0.4851, 0.5037, -0.3633],
[-0.0760, -3.6705, 2.4784]])
| https://pytorch.org/docs/stable/generated/torch.mm.html | pytorch docs |
torch.le
torch.le(input, other, *, out=None) -> Tensor
Computes \text{input} \leq \text{other} element-wise.
The second argument can be a number or a tensor whose shape is
broadcastable with the first argument.
Parameters:
* input (Tensor) -- the tensor to compare
* **other** (*Tensor** or **Scalar*) -- the tensor or value to
compare
Keyword Arguments:
out (Tensor, optional) -- the output tensor.
Returns:
A boolean tensor that is True where "input" is less than or
equal to "other" and False elsewhere
Example:
>>> torch.le(torch.tensor([[1, 2], [3, 4]]), torch.tensor([[1, 1], [4, 4]]))
tensor([[True, False], [True, True]])
| https://pytorch.org/docs/stable/generated/torch.le.html | pytorch docs |
torch.Tensor.imag
Tensor.imag
Returns a new tensor containing imaginary values of the "self"
tensor. The returned tensor and "self" share the same underlying
storage.
Warning:
"imag()" is only supported for tensors with complex dtypes.
Example::
>>> x=torch.randn(4, dtype=torch.cfloat)
>>> x
tensor([(0.3100+0.3553j), (-0.5445-0.7896j), (-1.6492-0.0633j), (-0.0638-0.8119j)])
>>> x.imag
tensor([ 0.3553, -0.7896, -0.0633, -0.8119]) | https://pytorch.org/docs/stable/generated/torch.Tensor.imag.html | pytorch docs |
torch.nn.utils.prune.identity
torch.nn.utils.prune.identity(module, name)
Applies pruning reparametrization to the tensor corresponding to
the parameter called "name" in "module" without actually pruning
any units. Modifies module in place (and also return the modified
module) by:
adding a named buffer called "name+'_mask'" corresponding to the
binary mask applied to the parameter "name" by the pruning
method.
replacing the parameter "name" by its pruned version, while the
original (unpruned) parameter is stored in a new parameter named
"name+'_orig'".
Note:
The mask is a tensor of ones.
Parameters:
* module (nn.Module) -- module containing the tensor to
prune.
* **name** (*str*) -- parameter name within "module" on which
pruning will act.
Returns:
modified (i.e. pruned) version of the input module
Return type:
module (nn.Module)
-[ Examples ]- | https://pytorch.org/docs/stable/generated/torch.nn.utils.prune.identity.html | pytorch docs |
module (nn.Module)
-[ Examples ]-
m = prune.identity(nn.Linear(2, 3), 'bias')
print(m.bias_mask)
tensor([1., 1., 1.])
| https://pytorch.org/docs/stable/generated/torch.nn.utils.prune.identity.html | pytorch docs |
torch.Tensor.not_equal
Tensor.not_equal(other) -> Tensor
See "torch.not_equal()". | https://pytorch.org/docs/stable/generated/torch.Tensor.not_equal.html | pytorch docs |
Mish
class torch.nn.Mish(inplace=False)
Applies the Mish function, element-wise. Mish: A Self Regularized
Non-Monotonic Neural Activation Function.
\text{Mish}(x) = x * \text{Tanh}(\text{Softplus}(x))
Note:
See Mish: A Self Regularized Non-Monotonic Neural Activation
Function
Shape:
* Input: (*), where * means any number of dimensions.
* Output: (*), same shape as the input.
[image]
Examples:
>>> m = nn.Mish()
>>> input = torch.randn(2)
>>> output = m(input)
| https://pytorch.org/docs/stable/generated/torch.nn.Mish.html | pytorch docs |
torch.nn.functional.elu_
torch.nn.functional.elu_(input, alpha=1.) -> Tensor
In-place version of "elu()". | https://pytorch.org/docs/stable/generated/torch.nn.functional.elu_.html | pytorch docs |
torch.cos
torch.cos(input, *, out=None) -> Tensor
Returns a new tensor with the cosine of the elements of "input".
\text{out}_{i} = \cos(\text{input}_{i})
Parameters:
input (Tensor) -- the input tensor.
Keyword Arguments:
out (Tensor, optional) -- the output tensor.
Example:
>>> a = torch.randn(4)
>>> a
tensor([ 1.4309, 1.2706, -0.8562, 0.9796])
>>> torch.cos(a)
tensor([ 0.1395, 0.2957, 0.6553, 0.5574])
| https://pytorch.org/docs/stable/generated/torch.cos.html | pytorch docs |
torch.Tensor.addr_
Tensor.addr_(vec1, vec2, *, beta=1, alpha=1) -> Tensor
In-place version of "addr()" | https://pytorch.org/docs/stable/generated/torch.Tensor.addr_.html | pytorch docs |
torch.logit
torch.logit(input, eps=None, *, out=None) -> Tensor
Alias for "torch.special.logit()". | https://pytorch.org/docs/stable/generated/torch.logit.html | pytorch docs |
torch.Tensor.ne_
Tensor.ne_(other) -> Tensor
In-place version of "ne()". | https://pytorch.org/docs/stable/generated/torch.Tensor.ne_.html | pytorch docs |
torch.Tensor.renorm
Tensor.renorm(p, dim, maxnorm) -> Tensor
See "torch.renorm()" | https://pytorch.org/docs/stable/generated/torch.Tensor.renorm.html | pytorch docs |
torch.nn.functional.l1_loss
torch.nn.functional.l1_loss(input, target, size_average=None, reduce=None, reduction='mean') -> Tensor
Function that takes the mean element-wise absolute value
difference.
See "L1Loss" for details.
Return type:
Tensor | https://pytorch.org/docs/stable/generated/torch.nn.functional.l1_loss.html | pytorch docs |
torch.nn.functional.celu
torch.nn.functional.celu(input, alpha=1., inplace=False) -> Tensor
Applies element-wise, \text{CELU}(x) = \max(0,x) + \min(0, \alpha *
(\exp(x/\alpha) - 1)).
See "CELU" for more details.
Return type:
Tensor | https://pytorch.org/docs/stable/generated/torch.nn.functional.celu.html | pytorch docs |
torch.cuda.jiterator._create_multi_output_jit_fn
torch.cuda.jiterator._create_multi_output_jit_fn(code_string, num_outputs, **kwargs)
Create a jiterator-generated cuda kernel for an elementwise op that
supports returning one or more outputs.
Parameters:
* code_string (str) -- CUDA code string to be compiled by
jiterator. The entry functor must return value by reference.
* **num_outputs** (*int*) -- number of outputs return by the
kernel
* **kwargs** (*Dict**, **optional*) -- Keyword arguments for
generated function
Return type:
Callable
Example:
code_string = "template <typename T> void my_kernel(T x, T y, T alpha, T& out) { out = -x + alpha * y; }"
jitted_fn = create_jit_fn(code_string, alpha=1.0)
a = torch.rand(3, device='cuda')
b = torch.rand(3, device='cuda')
# invoke jitted function like a regular python function
| https://pytorch.org/docs/stable/generated/torch.cuda.jiterator._create_multi_output_jit_fn.html | pytorch docs |
result = jitted_fn(a, b, alpha=3.14)
Warning:
This API is in beta and may change in future releases.
Warning:
This API only supports up to 8 inputs and 8 outputs
| https://pytorch.org/docs/stable/generated/torch.cuda.jiterator._create_multi_output_jit_fn.html | pytorch docs |
torch.Tensor.sin
Tensor.sin() -> Tensor
See "torch.sin()" | https://pytorch.org/docs/stable/generated/torch.Tensor.sin.html | pytorch docs |
LazyConv3d
class torch.nn.LazyConv3d(out_channels, kernel_size, stride=1, padding=0, dilation=1, groups=1, bias=True, padding_mode='zeros', device=None, dtype=None)
A "torch.nn.Conv3d" module with lazy initialization of the
"in_channels" argument of the "Conv3d" that is inferred from the
"input.size(1)". The attributes that will be lazily initialized are
weight and bias.
Check the "torch.nn.modules.lazy.LazyModuleMixin" for further
documentation on lazy modules and their limitations.
Parameters:
* out_channels (int) -- Number of channels produced by the
convolution
* **kernel_size** (*int** or **tuple*) -- Size of the convolving
kernel
* **stride** (*int** or **tuple**, **optional*) -- Stride of the
convolution. Default: 1
* **padding** (*int** or **tuple**, **optional*) -- Zero-padding
added to both sides of the input. Default: 0
* **padding_mode** (*str**, **optional*) -- "'zeros'",
| https://pytorch.org/docs/stable/generated/torch.nn.LazyConv3d.html | pytorch docs |
"'reflect'", "'replicate'" or "'circular'". Default: "'zeros'"
* **dilation** (*int** or **tuple**, **optional*) -- Spacing
between kernel elements. Default: 1
* **groups** (*int**, **optional*) -- Number of blocked
connections from input channels to output channels. Default: 1
* **bias** (*bool**, **optional*) -- If "True", adds a learnable
bias to the output. Default: "True"
See also:
"torch.nn.Conv3d" and "torch.nn.modules.lazy.LazyModuleMixin"
cls_to_become
alias of "Conv3d"
| https://pytorch.org/docs/stable/generated/torch.nn.LazyConv3d.html | pytorch docs |
torch.ger
torch.ger(input, vec2, *, out=None) -> Tensor
Alias of "torch.outer()".
Warning:
This function is deprecated and will be removed in a future
PyTorch release. Use "torch.outer()" instead.
| https://pytorch.org/docs/stable/generated/torch.ger.html | pytorch docs |
torch.Tensor.expm1
Tensor.expm1() -> Tensor
See "torch.expm1()" | https://pytorch.org/docs/stable/generated/torch.Tensor.expm1.html | pytorch docs |
torch.nn.functional.conv_transpose2d
torch.nn.functional.conv_transpose2d(input, weight, bias=None, stride=1, padding=0, output_padding=0, groups=1, dilation=1) -> Tensor
Applies a 2D transposed convolution operator over an input image
composed of several input planes, sometimes also called
"deconvolution".
This operator supports TensorFloat32.
See "ConvTranspose2d" for details and output shape.
Note:
In some circumstances when given tensors on a CUDA device and
using CuDNN, this operator may select a nondeterministic
algorithm to increase performance. If this is undesirable, you
can try to make the operation deterministic (potentially at a
performance cost) by setting "torch.backends.cudnn.deterministic
= True". See Reproducibility for more information.
Parameters:
* input -- input tensor of shape (\text{minibatch} ,
\text{in_channels} , iH , iW) | https://pytorch.org/docs/stable/generated/torch.nn.functional.conv_transpose2d.html | pytorch docs |
\text{in_channels} , iH , iW)
* **weight** -- filters of shape (\text{in\_channels} ,
\frac{\text{out\_channels}}{\text{groups}} , kH , kW)
* **bias** -- optional bias of shape (\text{out\_channels}).
Default: None
* **stride** -- the stride of the convolving kernel. Can be a
single number or a tuple "(sH, sW)". Default: 1
* **padding** -- "dilation * (kernel_size - 1) - padding" zero-
padding will be added to both sides of each dimension in the
input. Can be a single number or a tuple "(padH, padW)".
Default: 0
* **output_padding** -- additional size added to one side of
each dimension in the output shape. Can be a single number or
a tuple "(out_padH, out_padW)". Default: 0
* **groups** -- split input into groups, \text{in\_channels}
should be divisible by the number of groups. Default: 1
* **dilation** -- the spacing between kernel elements. Can be a
| https://pytorch.org/docs/stable/generated/torch.nn.functional.conv_transpose2d.html | pytorch docs |
single number or a tuple "(dH, dW)". Default: 1
Examples:
>>> # With square kernels and equal stride
>>> inputs = torch.randn(1, 4, 5, 5)
>>> weights = torch.randn(4, 8, 3, 3)
>>> F.conv_transpose2d(inputs, weights, padding=1)
| https://pytorch.org/docs/stable/generated/torch.nn.functional.conv_transpose2d.html | pytorch docs |
torch.nn.utils.parametrize.remove_parametrizations
torch.nn.utils.parametrize.remove_parametrizations(module, tensor_name, leave_parametrized=True)
Removes the parametrizations on a tensor in a module.
If "leave_parametrized=True", "module[tensor_name]" will be set
to its current output. In this case, the parametrization shall
not change the "dtype" of the tensor.
If "leave_parametrized=False", "module[tensor_name]" will be set
to the unparametrised tensor in
"module.parametrizations[tensor_name].original". This is only
possible when the parametrization depends on just one tensor.
Parameters:
* module (nn.Module) -- module from which remove the
parametrization
* **tensor_name** (*str*) -- name of the parametrization to be
removed
* **leave_parametrized** (*bool**, **optional*) -- leave the
attribute "tensor_name" parametrized. Default: "True"
Returns: | https://pytorch.org/docs/stable/generated/torch.nn.utils.parametrize.remove_parametrizations.html | pytorch docs |
Returns:
module
Return type:
Module
Raises:
* ValueError -- if "module[tensor_name]" is not parametrized
* **ValueError** -- if "leave_parametrized=False" and the
parametrization depends on several tensors
| https://pytorch.org/docs/stable/generated/torch.nn.utils.parametrize.remove_parametrizations.html | pytorch docs |
torch.Tensor.q_per_channel_axis
Tensor.q_per_channel_axis() -> int
Given a Tensor quantized by linear (affine) per-channel
quantization, returns the index of dimension on which per-channel
quantization is applied. | https://pytorch.org/docs/stable/generated/torch.Tensor.q_per_channel_axis.html | pytorch docs |
torch.Tensor.triu_
Tensor.triu_(diagonal=0) -> Tensor
In-place version of "triu()" | https://pytorch.org/docs/stable/generated/torch.Tensor.triu_.html | pytorch docs |
RandomUnstructured
class torch.nn.utils.prune.RandomUnstructured(amount)
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)
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
| https://pytorch.org/docs/stable/generated/torch.nn.utils.prune.RandomUnstructured.html | pytorch docs |
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").
| https://pytorch.org/docs/stable/generated/torch.nn.utils.prune.RandomUnstructured.html | pytorch docs |
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
| https://pytorch.org/docs/stable/generated/torch.nn.utils.prune.RandomUnstructured.html | pytorch docs |
list. Similarly, the buffer named "name+'_mask'" is removed from
the buffers.
Note:
Pruning itself is NOT undone or reversed!
| https://pytorch.org/docs/stable/generated/torch.nn.utils.prune.RandomUnstructured.html | pytorch docs |
RNNCell
class torch.nn.RNNCell(input_size, hidden_size, bias=True, nonlinearity='tanh', device=None, dtype=None)
An Elman RNN cell with tanh or ReLU non-linearity.
h' = \tanh(W_{ih} x + b_{ih} + W_{hh} h + b_{hh})
If "nonlinearity" is 'relu', then ReLU is used in place of tanh.
Parameters:
* input_size (int) -- The number of expected features in
the input x
* **hidden_size** (*int*) -- The number of features in the
hidden state *h*
* **bias** (*bool*) -- If "False", then the layer does not use
bias weights *b_ih* and *b_hh*. Default: "True"
* **nonlinearity** (*str*) -- The non-linearity to use. Can be
either "'tanh'" or "'relu'". Default: "'tanh'"
Inputs: input, hidden
* input: tensor containing input features
* **hidden**: tensor containing the initial hidden state
Defaults to zero if not provided.
Outputs: h' | https://pytorch.org/docs/stable/generated/torch.nn.RNNCell.html | pytorch docs |
Outputs: h'
* h' of shape (batch, hidden_size): tensor containing the
next hidden state for each element in the batch
Shape:
* input: (N, H_{in}) or (H_{in}) tensor containing input
features where H_{in} = input_size.
* hidden: (N, H_{out}) or (H_{out}) tensor containing the
initial hidden state where H_{out} = *hidden_size*. Defaults
to zero if not provided.
* output: (N, H_{out}) or (H_{out}) tensor containing the next
hidden state.
Variables:
* weight_ih (torch.Tensor) -- the learnable input-hidden
weights, of shape (hidden_size, input_size)
* **weight_hh** (*torch.Tensor*) -- the learnable hidden-hidden
weights, of shape *(hidden_size, hidden_size)*
* **bias_ih** -- the learnable input-hidden bias, of shape
*(hidden_size)*
* **bias_hh** -- the learnable hidden-hidden bias, of shape
*(hidden_size)*
Note: | https://pytorch.org/docs/stable/generated/torch.nn.RNNCell.html | pytorch docs |
(hidden_size)
Note:
All the weights and biases are initialized from
\mathcal{U}(-\sqrt{k}, \sqrt{k}) where k =
\frac{1}{\text{hidden\_size}}
Examples:
>>> rnn = nn.RNNCell(10, 20)
>>> input = torch.randn(6, 3, 10)
>>> hx = torch.randn(3, 20)
>>> output = []
>>> for i in range(6):
... hx = rnn(input[i], hx)
... output.append(hx)
| https://pytorch.org/docs/stable/generated/torch.nn.RNNCell.html | pytorch docs |
torch.Tensor.rsqrt
Tensor.rsqrt() -> Tensor
See "torch.rsqrt()" | https://pytorch.org/docs/stable/generated/torch.Tensor.rsqrt.html | pytorch docs |
torch.diagonal_scatter
torch.diagonal_scatter(input, src, offset=0, dim1=0, dim2=1) -> Tensor
Embeds the values of the "src" tensor into "input" along the
diagonal elements of "input", with respect to "dim1" and "dim2".
This function returns a tensor with fresh storage; it does not
return a view.
The argument "offset" controls which diagonal to consider:
If "offset" = 0, it is the main diagonal.
If "offset" > 0, it is above the main diagonal.
If "offset" < 0, it is below the main diagonal.
Parameters:
* input (Tensor) -- the input tensor. Must be at least
2-dimensional.
* **src** (*Tensor*) -- the tensor to embed into "input".
* **offset** (*int**, **optional*) -- which diagonal to
consider. Default: 0 (main diagonal).
* **dim1** (*int**, **optional*) -- first dimension with respect
to which to take diagonal. Default: 0.
* **dim2** (*int**, **optional*) -- second dimension with
| https://pytorch.org/docs/stable/generated/torch.diagonal_scatter.html | pytorch docs |
respect to which to take diagonal. Default: 1.
Note:
"src" must be of the proper size in order to be embedded into
"input". Specifically, it should have the same shape as
"torch.diagonal(input, offset, dim1, dim2)"
Examples:
>>> a = torch.zeros(3, 3)
>>> a
tensor([[0., 0., 0.],
[0., 0., 0.],
[0., 0., 0.]])
>>> torch.diagonal_scatter(a, torch.ones(3), 0)
tensor([[1., 0., 0.],
[0., 1., 0.],
[0., 0., 1.]])
>>> torch.diagonal_scatter(a, torch.ones(2), 1)
tensor([[0., 1., 0.],
[0., 0., 1.],
[0., 0., 0.]])
| https://pytorch.org/docs/stable/generated/torch.diagonal_scatter.html | pytorch docs |
torch.nn.utils.prune.l1_unstructured
torch.nn.utils.prune.l1_unstructured(module, name, amount, importance_scores=None)
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:
adding a named buffer called "name+'_mask'" corresponding to the
binary mask applied to the parameter "name" by the pruning
method.
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
| https://pytorch.org/docs/stable/generated/torch.nn.utils.prune.l1_unstructured.html | pytorch docs |
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'])
| https://pytorch.org/docs/stable/generated/torch.nn.utils.prune.l1_unstructured.html | pytorch docs |
torch.Tensor.matrix_exp
Tensor.matrix_exp() -> Tensor
See "torch.matrix_exp()" | https://pytorch.org/docs/stable/generated/torch.Tensor.matrix_exp.html | pytorch docs |
torch.lgamma
torch.lgamma(input, *, out=None) -> Tensor
Computes the natural logarithm of the absolute value of the gamma
function on "input".
\text{out}_{i} = \ln \Gamma(|\text{input}_{i}|)
Parameters:
input (Tensor) -- the input tensor.
Keyword Arguments:
out (Tensor, optional) -- the output tensor.
Example:
>>> a = torch.arange(0.5, 2, 0.5)
>>> torch.lgamma(a)
tensor([ 0.5724, 0.0000, -0.1208])
| https://pytorch.org/docs/stable/generated/torch.lgamma.html | pytorch docs |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.