torch.fft.fftshift(input, dim=None) → Tensor
Reorders n-dimensional FFT data, as provided by fftn(), to have negative frequency terms first. This performs a periodic shift of n-dimensional data such that the origin (0, ..., 0) is moved to the center of the tensor. Specifically, to input.shape[dim] // 2 in each selected dimension.  Note By convention, the FFT returns positive frequency terms first, followed by the negative frequencies in reverse order, so that f[-i] for all 0<i≤n/20 < i \leq n/2  in Python gives the negative frequency terms. fftshift() rearranges all frequencies into ascending order from negative to positive with the zero-frequency term in the center.   Note For even lengths, the Nyquist frequency at f[n/2] can be thought of as either negative or positive. fftshift() always puts the Nyquist term at the 0-index. This is the same convention used by fftfreq().   Parameters

input (Tensor) – the tensor in FFT order
dim (int, Tuple[int], optional) – The dimensions to rearrange. Only dimensions specified here will be rearranged, any other dimensions will be left in their original order. Default: All dimensions of input.    Example >>> f = torch.fft.fftfreq(4)
>>> f
tensor([ 0.0000,  0.2500, -0.5000, -0.2500])
 >>> torch.fft.fftshift(f)
tensor([-0.5000, -0.2500,  0.0000,  0.2500])
 Also notice that the Nyquist frequency term at f[2] was moved to the beginning of the tensor. This also works for multi-dimensional transforms: >>> x = torch.fft.fftfreq(5, d=1/5) + 0.1 * torch.fft.fftfreq(5, d=1/5).unsqueeze(1)
>>> x
tensor([[ 0.0000,  1.0000,  2.0000, -2.0000, -1.0000],
        [ 0.1000,  1.1000,  2.1000, -1.9000, -0.9000],
        [ 0.2000,  1.2000,  2.2000, -1.8000, -0.8000],
        [-0.2000,  0.8000,  1.8000, -2.2000, -1.2000],
        [-0.1000,  0.9000,  1.9000, -2.1000, -1.1000]])
 >>> torch.fft.fftshift(x)
tensor([[-2.2000, -1.2000, -0.2000,  0.8000,  1.8000],
        [-2.1000, -1.1000, -0.1000,  0.9000,  1.9000],
        [-2.0000, -1.0000,  0.0000,  1.0000,  2.0000],
        [-1.9000, -0.9000,  0.1000,  1.1000,  2.1000],
        [-1.8000, -0.8000,  0.2000,  1.2000,  2.2000]])
 fftshift() can also be useful for spatial data. If our data is defined on a centered grid ([-(N//2), (N-1)//2]) then we can use the standard FFT defined on an uncentered grid ([0, N)) by first applying an ifftshift(). >>> x_centered = torch.arange(-5, 5)
>>> x_uncentered = torch.fft.ifftshift(x_centered)
>>> fft_uncentered = torch.fft.fft(x_uncentered)
 Similarly, we can convert the frequency domain components to centered convention by applying fftshift(). >>> fft_centered = torch.fft.fftshift(fft_uncentered)
 The inverse transform, from centered Fourier space back to centered spatial data, can be performed by applying the inverse shifts in reverse order: >>> x_centered_2 = torch.fft.fftshift(torch.fft.ifft(torch.fft.ifftshift(fft_centered)))
>>> torch.allclose(x_centered.to(torch.complex64), x_centered_2)
True


torch.fft.hfft(input, n=None, dim=-1, norm=None) → Tensor
Computes the one dimensional discrete Fourier transform of a Hermitian symmetric input signal.  Note hfft()/ihfft() are analogous to rfft()/irfft(). The real FFT expects a real signal in the time-domain and gives a Hermitian symmetry in the frequency-domain. The Hermitian FFT is the opposite; Hermitian symmetric in the time-domain and real-valued in the frequency-domain. For this reason, special care needs to be taken with the length argument n, in the same way as with irfft().   Note Because the signal is Hermitian in the time-domain, the result will be real in the frequency domain. Note that some input frequencies must be real-valued to satisfy the Hermitian property. In these cases the imaginary component will be ignored. For example, any imaginary component in input[0] would result in one or more complex frequency terms which cannot be represented in a real output and so will always be ignored.   Note The correct interpretation of the Hermitian input depends on the length of the original data, as given by n. This is because each input shape could correspond to either an odd or even length signal. By default, the signal is assumed to be even length and odd signals will not round-trip properly. So, it is recommended to always pass the signal length n.   Parameters

input (Tensor) – the input tensor representing a half-Hermitian signal
n (int, optional) – Output signal length. This determines the length of the real output. If given, the input will either be zero-padded or trimmed to this length before computing the Hermitian FFT. Defaults to even output: n=2*(input.size(dim) - 1).
dim (int, optional) – The dimension along which to take the one dimensional Hermitian FFT.
norm (str, optional) –
Normalization mode. For the forward transform (hfft()), these correspond to:
"forward" - normalize by 1/n

"backward" - no normalization
"ortho" - normalize by 1/sqrt(n) (making the Hermitian FFT orthonormal)  Calling the backward transform (ihfft()) with the same normalization mode will apply an overall normalization of 1/n between the two transforms. This is required to make ihfft() the exact inverse. Default is "backward" (no normalization).     Example Taking a real-valued frequency signal and bringing it into the time domain gives Hermitian symmetric output: >>> t = torch.arange(5)
>>> t
tensor([0, 1, 2, 3, 4])
>>> T = torch.fft.ifft(t)
>>> T
tensor([ 2.0000+-0.0000j, -0.5000-0.6882j, -0.5000-0.1625j, -0.5000+0.1625j,
        -0.5000+0.6882j])
 Note that T[1] == T[-1].conj() and T[2] == T[-2].conj() is redundant. We can thus compute the forward transform without considering negative frequencies: >>> torch.fft.hfft(T[:3], n=5)
tensor([0., 1., 2., 3., 4.])
 Like with irfft(), the output length must be given in order to recover an even length output: >>> torch.fft.hfft(T[:3])
tensor([0.5000, 1.1236, 2.5000, 3.8764])


torch.fft.ifft(input, n=None, dim=-1, norm=None) → Tensor
Computes the one dimensional inverse discrete Fourier transform of input.  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 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).     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])


torch.fft.ifft2(input, s=None, dim=(-2, -1), norm=None) → Tensor
Computes the 2 dimensional inverse discrete Fourier transform of input. Equivalent to ifftn() but IFFTs only the last two dimensions by default.  Parameters

input (Tensor) – the input tensor
s (Tuple[int], optional) – Signal size in the transformed dimensions. If given, each dimension dim[i] will either be zero-padded or trimmed to the length s[i] before computing the IFFT. If a length -1 is specified, no padding is done in that dimension. Default: s = [input.size(d) for d in dim]

dim (Tuple[int], optional) – Dimensions to be transformed. Default: last two dimensions.
norm (str, optional) –
Normalization mode. For the backward transform (ifft2()), these correspond to:
"forward" - no normalization
"backward" - normalize by 1/n

"ortho" - normalize by 1/sqrt(n) (making the IFFT orthonormal)  Where n = prod(s) is the logical IFFT size. Calling the forward transform (fft2()) with the same normalization mode will apply an overall normalization of 1/n between the two transforms. This is required to make ifft2() the exact inverse. Default is "backward" (normalize by 1/n).     Example >>> x = torch.rand(10, 10, dtype=torch.complex64)
>>> ifft2 = torch.fft.ifft2(t)
 The discrete Fourier transform is separable, so ifft2() here is equivalent to two one-dimensional ifft() calls: >>> two_iffts = torch.fft.ifft(torch.fft.ifft(x, dim=0), dim=1)
>>> torch.allclose(ifft2, two_iffts)


torch.fft.ifftn(input, s=None, dim=None, norm=None) → Tensor
Computes the N dimensional inverse discrete Fourier transform of input.  Parameters

input (Tensor) – the input tensor
s (Tuple[int], optional) – Signal size in the transformed dimensions. If given, each dimension dim[i] will either be zero-padded or trimmed to the length s[i] before computing the IFFT. If a length -1 is specified, no padding is done in that dimension. Default: s = [input.size(d) for d in dim]

dim (Tuple[int], optional) – Dimensions to be transformed. Default: all dimensions, or the last len(s) dimensions if s is given.
norm (str, optional) –
Normalization mode. For the backward transform (ifftn()), these correspond to:
"forward" - no normalization
"backward" - normalize by 1/n

"ortho" - normalize by 1/sqrt(n) (making the IFFT orthonormal)  Where n = prod(s) is the logical IFFT size. Calling the forward transform (fftn()) with the same normalization mode will apply an overall normalization of 1/n between the two transforms. This is required to make ifftn() the exact inverse. Default is "backward" (normalize by 1/n).     Example >>> x = torch.rand(10, 10, dtype=torch.complex64)
>>> ifftn = torch.fft.ifftn(t)
 The discrete Fourier transform is separable, so ifftn() here is equivalent to two one-dimensional ifft() calls: >>> two_iffts = torch.fft.ifft(torch.fft.ifft(x, dim=0), dim=1)
>>> torch.allclose(ifftn, two_iffts)


torch.fft.ifftshift(input, dim=None) → Tensor
Inverse of fftshift().  Parameters

input (Tensor) – the tensor in FFT order
dim (int, Tuple[int], optional) – The dimensions to rearrange. Only dimensions specified here will be rearranged, any other dimensions will be left in their original order. Default: All dimensions of input.    Example >>> f = torch.fft.fftfreq(5)
>>> f
tensor([ 0.0000,  0.2000,  0.4000, -0.4000, -0.2000])
 A round-trip through fftshift() and ifftshift() gives the same result: >>> shifted = torch.fftshift(f)
>>> torch.ifftshift(shifted)
tensor([ 0.0000,  0.2000,  0.4000, -0.4000, -0.2000])


torch.fft.ihfft(input, n=None, dim=-1, norm=None) → Tensor
Computes the inverse of hfft(). input must be a real-valued signal, interpreted in the Fourier domain. The IFFT of a real signal is Hermitian-symmetric, X[i] = conj(X[-i]). ihfft() represents this in the one-sided form where only the positive frequencies below the Nyquist frequency are included. To compute the full output, use ifft().  Parameters

input (Tensor) – the real input tensor
n (int, optional) – Signal length. If given, the input will either be zero-padded or trimmed to this length before computing the Hermitian IFFT.
dim (int, optional) – The dimension along which to take the one dimensional Hermitian IFFT.
norm (str, optional) –
Normalization mode. For the backward transform (ihfft()), these correspond to:
"forward" - no normalization
"backward" - normalize by 1/n

"ortho" - normalize by 1/sqrt(n) (making the IFFT orthonormal)  Calling the forward transform (hfft()) with the same normalization mode will apply an overall normalization of 1/n between the two transforms. This is required to make ihfft() the exact inverse. Default is "backward" (normalize by 1/n).     Example >>> t = torch.arange(5)
>>> t
tensor([0, 1, 2, 3, 4])
>>> torch.fft.ihfft(t)
tensor([ 2.0000+-0.0000j, -0.5000-0.6882j, -0.5000-0.1625j])
 Compare against the full output from ifft(): >>> torch.fft.ifft(t)
tensor([ 2.0000+-0.0000j, -0.5000-0.6882j, -0.5000-0.1625j, -0.5000+0.1625j,
    -0.5000+0.6882j])


torch.fft.irfft(input, n=None, dim=-1, norm=None) → Tensor
Computes the inverse of rfft(). input is interpreted as a one-sided Hermitian signal in the Fourier domain, as produced by rfft(). By the Hermitian property, the output will be real-valued.  Note Some input frequencies must be real-valued to satisfy the Hermitian property. In these cases the imaginary component will be ignored. For example, any imaginary component in the zero-frequency term cannot be represented in a real output and so will always be ignored.   Note The correct interpretation of the Hermitian input depends on the length of the original data, as given by n. This is because each input shape could correspond to either an odd or even length signal. By default, the signal is assumed to be even length and odd signals will not round-trip properly. So, it is recommended to always pass the signal length n.   Parameters

input (Tensor) – the input tensor representing a half-Hermitian signal
n (int, optional) – Output signal length. This determines the length of the output signal. If given, the input will either be zero-padded or trimmed to this length before computing the real IFFT. Defaults to even output: n=2*(input.size(dim) - 1).
dim (int, optional) – The dimension along which to take the one dimensional real IFFT.
norm (str, optional) –
Normalization mode. For the backward transform (irfft()), these correspond to:
"forward" - no normalization
"backward" - normalize by 1/n

"ortho" - normalize by 1/sqrt(n) (making the real IFFT orthonormal)  Calling the forward transform (rfft()) with the same normalization mode will apply an overall normalization of 1/n between the two transforms. This is required to make irfft() the exact inverse. Default is "backward" (normalize by 1/n).     Example >>> t = torch.arange(5)
>>> t
tensor([0, 1, 2, 3, 4])
>>> T = torch.fft.rfft(t)
>>> T
tensor([10.0000+0.0000j, -2.5000+3.4410j, -2.5000+0.8123j])
 Without specifying the output length to irfft(), the output will not round-trip properly because the input is odd-length: >>> torch.fft.irfft(T)
tensor([0.6250, 1.4045, 3.1250, 4.8455])
 So, it is recommended to always pass the signal length n: >>> torch.fft.irfft(T, t.numel())
tensor([0.0000, 1.0000, 2.0000, 3.0000, 4.0000])


torch.fft.irfft2(input, s=None, dim=(-2, -1), norm=None) → Tensor
Computes the inverse of rfft2(). Equivalent to irfftn() but IFFTs only the last two dimensions by default. input is interpreted as a one-sided Hermitian signal in the Fourier domain, as produced by rfft2(). By the Hermitian property, the output will be real-valued.  Note Some input frequencies must be real-valued to satisfy the Hermitian property. In these cases the imaginary component will be ignored. For example, any imaginary component in the zero-frequency term cannot be represented in a real output and so will always be ignored.   Note The correct interpretation of the Hermitian input depends on the length of the original data, as given by s. This is because each input shape could correspond to either an odd or even length signal. By default, the signal is assumed to be even length and odd signals will not round-trip properly. So, it is recommended to always pass the signal shape s.   Parameters

input (Tensor) – the input tensor
s (Tuple[int], optional) – Signal size in the transformed dimensions. If given, each dimension dim[i] will either be zero-padded or trimmed to the length s[i] before computing the real FFT. If a length -1 is specified, no padding is done in that dimension. Defaults to even output in the last dimension: s[-1] = 2*(input.size(dim[-1]) - 1).
dim (Tuple[int], optional) – Dimensions to be transformed. The last dimension must be the half-Hermitian compressed dimension. Default: last two dimensions.
norm (str, optional) –
Normalization mode. For the backward transform (irfft2()), these correspond to:
"forward" - no normalization
"backward" - normalize by 1/n

"ortho" - normalize by 1/sqrt(n) (making the real IFFT orthonormal)  Where n = prod(s) is the logical IFFT size. Calling the forward transform (rfft2()) with the same normalization mode will apply an overall normalization of 1/n between the two transforms. This is required to make irfft2() the exact inverse. Default is "backward" (normalize by 1/n).     Example >>> t = torch.rand(10, 9)
>>> T = torch.fft.rfft2(t)
 Without specifying the output length to irfft2(), the output will not round-trip properly because the input is odd-length in the last dimension: >>> torch.fft.irfft2(T).size()
torch.Size([10, 10])
 So, it is recommended to always pass the signal shape s. >>> roundtrip = torch.fft.irfft2(T, t.size())
>>> roundtrip.size()
torch.Size([10, 9])
>>> torch.allclose(roundtrip, t)
True


torch.fft.irfftn(input, s=None, dim=None, norm=None) → Tensor
Computes the inverse of rfftn(). input is interpreted as a one-sided Hermitian signal in the Fourier domain, as produced by rfftn(). By the Hermitian property, the output will be real-valued.  Note Some input frequencies must be real-valued to satisfy the Hermitian property. In these cases the imaginary component will be ignored. For example, any imaginary component in the zero-frequency term cannot be represented in a real output and so will always be ignored.   Note The correct interpretation of the Hermitian input depends on the length of the original data, as given by s. This is because each input shape could correspond to either an odd or even length signal. By default, the signal is assumed to be even length and odd signals will not round-trip properly. So, it is recommended to always pass the signal shape s.   Parameters

input (Tensor) – the input tensor
s (Tuple[int], optional) – Signal size in the transformed dimensions. If given, each dimension dim[i] will either be zero-padded or trimmed to the length s[i] before computing the real FFT. If a length -1 is specified, no padding is done in that dimension. Defaults to even output in the last dimension: s[-1] = 2*(input.size(dim[-1]) - 1).
dim (Tuple[int], optional) – Dimensions to be transformed. The last dimension must be the half-Hermitian compressed dimension. Default: all dimensions, or the last len(s) dimensions if s is given.
norm (str, optional) –
Normalization mode. For the backward transform (irfftn()), these correspond to:
"forward" - no normalization
"backward" - normalize by 1/n

"ortho" - normalize by 1/sqrt(n) (making the real IFFT orthonormal)  Where n = prod(s) is the logical IFFT size. Calling the forward transform (rfftn()) with the same normalization mode will apply an overall normalization of 1/n between the two transforms. This is required to make irfftn() the exact inverse. Default is "backward" (normalize by 1/n).     Example >>> t = torch.rand(10, 9)
>>> T = torch.fft.rfftn(t)
 Without specifying the output length to irfft(), the output will not round-trip properly because the input is odd-length in the last dimension: >>> torch.fft.irfftn(T).size()
torch.Size([10, 10])
 So, it is recommended to always pass the signal shape s. >>> roundtrip = torch.fft.irfftn(T, t.size())
>>> roundtrip.size()
torch.Size([10, 9])
>>> torch.allclose(roundtrip, t)
True


torch.fft.rfft(input, n=None, dim=-1, norm=None) → Tensor
Computes the one dimensional Fourier transform of real-valued input. The FFT of a real signal is Hermitian-symmetric, X[i] = conj(X[-i]) so the output contains only the positive frequencies below the Nyquist frequency. To compute the full output, use fft()  Parameters

input (Tensor) – the real input tensor
n (int, optional) – Signal length. If given, the input will either be zero-padded or trimmed to this length before computing the real FFT.
dim (int, optional) – The dimension along which to take the one dimensional real FFT.
norm (str, optional) –
Normalization mode. For the forward transform (rfft()), these correspond to:
"forward" - normalize by 1/n

"backward" - no normalization
"ortho" - normalize by 1/sqrt(n) (making the FFT orthonormal)  Calling the backward transform (irfft()) with the same normalization mode will apply an overall normalization of 1/n between the two transforms. This is required to make irfft() the exact inverse. Default is "backward" (no normalization).     Example >>> t = torch.arange(4)
>>> t
tensor([0, 1, 2, 3])
>>> torch.fft.rfft(t)
tensor([ 6.+0.j, -2.+2.j, -2.+0.j])
 Compare against the full output from fft(): >>> torch.fft.fft(t)
tensor([ 6.+0.j, -2.+2.j, -2.+0.j, -2.-2.j])
 Notice that the symmetric element T[-1] == T[1].conj() is omitted. At the Nyquist frequency T[-2] == T[2] is it’s own symmetric pair, and therefore must always be real-valued.


torch.fft.rfft2(input, s=None, dim=(-2, -1), norm=None) → Tensor
Computes the 2-dimensional discrete Fourier transform of real input. Equivalent to rfftn() but FFTs only the last two dimensions by default. The FFT of a real signal is Hermitian-symmetric, X[i, j] = conj(X[-i, -j]), so the full fft2() output contains redundant information. rfft2() instead omits the negative frequencies in the last dimension.  Parameters

input (Tensor) – the input tensor
s (Tuple[int], optional) – Signal size in the transformed dimensions. If given, each dimension dim[i] will either be zero-padded or trimmed to the length s[i] before computing the real FFT. If a length -1 is specified, no padding is done in that dimension. Default: s = [input.size(d) for d in dim]

dim (Tuple[int], optional) – Dimensions to be transformed. Default: last two dimensions.
norm (str, optional) –
Normalization mode. For the forward transform (rfft2()), these correspond to:
"forward" - normalize by 1/n

"backward" - no normalization
"ortho" - normalize by 1/sqrt(n) (making the real FFT orthonormal)  Where n = prod(s) is the logical FFT size. Calling the backward transform (irfft2()) with the same normalization mode will apply an overall normalization of 1/n between the two transforms. This is required to make irfft2() the exact inverse. Default is "backward" (no normalization).     Example >>> t = torch.rand(10, 10)
>>> rfft2 = torch.fft.rfft2(t)
>>> rfft2.size()
torch.Size([10, 6])
 Compared against the full output from fft2(), we have all elements up to the Nyquist frequency. >>> fft2 = torch.fft.fft2(t)
>>> torch.allclose(fft2[..., :6], rfft2)
True
 The discrete Fourier transform is separable, so rfft2() here is equivalent to a combination of fft() and rfft(): >>> two_ffts = torch.fft.fft(torch.fft.rfft(x, dim=1), dim=0)
>>> torch.allclose(rfft2, two_ffts)


torch.fft.rfftfreq(n, d=1.0, *, dtype=None, layout=torch.strided, device=None, requires_grad=False) → Tensor
Computes the sample frequencies for rfft() with a signal of size n.  Note rfft() returns Hermitian one-sided output, so only the positive frequency terms are returned. For a real FFT of length n and with inputs spaced in length unit d, the frequencies are: f = torch.arange((n + 1) // 2) / (d * n)
   Note For even lengths, the Nyquist frequency at f[n/2] can be thought of as either negative or positive. Unlike fftfreq(), rfftfreq() always returns it as positive.   Parameters

n (int) – the real FFT length
d (float, optional) – The sampling length scale. The spacing between individual samples of the FFT input. The default assumes unit spacing, dividing that result by the actual spacing gives the result in physical frequency units.   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 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.    Example >>> torch.fft.rfftfreq(5)
tensor([ 0.0000,  0.2000,  0.4000])
 >>> torch.fft.rfftfreq(4)
tensor([ 0.0000,  0.2500, 0.5000])
 Compared to the output from fftfreq(), we see that the Nyquist frequency at f[2] has changed sign: >>> torch.fft.fftfreq(4) tensor([ 0.0000, 0.2500, -0.5000, -0.2500])


torch.fft.rfftn(input, s=None, dim=None, norm=None) → Tensor
Computes the N-dimensional discrete Fourier transform of real input. The FFT of a real signal is Hermitian-symmetric, X[i_1, ..., i_n] = conj(X[-i_1, ..., -i_n]) so the full fftn() output contains redundant information. rfftn() instead omits the negative frequencies in the last dimension.  Parameters

input (Tensor) – the input tensor
s (Tuple[int], optional) – Signal size in the transformed dimensions. If given, each dimension dim[i] will either be zero-padded or trimmed to the length s[i] before computing the real FFT. If a length -1 is specified, no padding is done in that dimension. Default: s = [input.size(d) for d in dim]

dim (Tuple[int], optional) – Dimensions to be transformed. Default: all dimensions, or the last len(s) dimensions if s is given.
norm (str, optional) –
Normalization mode. For the forward transform (rfftn()), these correspond to:
"forward" - normalize by 1/n

"backward" - no normalization
"ortho" - normalize by 1/sqrt(n) (making the real FFT orthonormal)  Where n = prod(s) is the logical FFT size. Calling the backward transform (irfftn()) with the same normalization mode will apply an overall normalization of 1/n between the two transforms. This is required to make irfftn() the exact inverse. Default is "backward" (no normalization).     Example >>> t = torch.rand(10, 10)
>>> rfftn = torch.fft.rfftn(t)
>>> rfftn.size()
torch.Size([10, 6])
 Compared against the full output from fftn(), we have all elements up to the Nyquist frequency. >>> fftn = torch.fft.fftn(t)
>>> torch.allclose(fftn[..., :6], rfftn)
True
 The discrete Fourier transform is separable, so rfftn() here is equivalent to a combination of fft() and rfft(): >>> two_ffts = torch.fft.fft(torch.fft.rfft(x, dim=1), dim=0)
>>> torch.allclose(rfftn, two_ffts)


torch.fix(input, *, out=None) → Tensor
Alias for torch.trunc()


torch.flatten(input, start_dim=0, end_dim=-1) → Tensor
Flattens input by reshaping it into a one-dimensional tensor. If start_dim or end_dim are passed, only dimensions starting with start_dim and ending with end_dim are flattened. The order of elements in input is unchanged. Unlike NumPy’s flatten, which always copies input’s data, this function may return the original object, a view, or copy. If no dimensions are flattened, then the original object input is returned. Otherwise, if input can be viewed as the flattened shape, then that view is returned. Finally, only if the input cannot be viewed as the flattened shape is input’s data copied. See torch.Tensor.view() for details on when a view will be returned.  Note Flattening a zero-dimensional tensor will return a one-dimensional view.   Parameters

input (Tensor) – the input tensor.
start_dim (int) – the first dim to flatten
end_dim (int) – the last dim to flatten    Example: >>> t = torch.tensor([[[1, 2],
...                    [3, 4]],
...                   [[5, 6],
...                    [7, 8]]])
>>> torch.flatten(t)
tensor([1, 2, 3, 4, 5, 6, 7, 8])
>>> torch.flatten(t, start_dim=1)
tensor([[1, 2, 3, 4],
        [5, 6, 7, 8]])


torch.flip(input, dims) → Tensor
Reverse the order of a n-D tensor along given axis in dims.  Note torch.flip makes a copy of input’s data. This is different from NumPy’s np.flip, which returns a view in constant time. Since copying a tensor’s data is more work than viewing that data, torch.flip is expected to be slower than np.flip.   Parameters

input (Tensor) – the input tensor.
dims (a list or tuple) – axis to flip on    Example: >>> x = torch.arange(8).view(2, 2, 2)
>>> x
tensor([[[ 0,  1],
         [ 2,  3]],

        [[ 4,  5],
         [ 6,  7]]])
>>> torch.flip(x, [0, 1])
tensor([[[ 6,  7],
         [ 4,  5]],

        [[ 2,  3],
         [ 0,  1]]])


torch.fliplr(input) → Tensor
Flip tensor in the left/right direction, returning a new tensor. Flip the entries in each row in the left/right direction. Columns are preserved, but appear in a different order than before.  Note Requires the tensor to be at least 2-D.   Note torch.fliplr makes a copy of input’s data. This is different from NumPy’s np.fliplr, which returns a view in constant time. Since copying a tensor’s data is more work than viewing that data, torch.fliplr is expected to be slower than np.fliplr.   Parameters
input (Tensor) – Must be at least 2-dimensional.   Example: >>> x = torch.arange(4).view(2, 2)
>>> x
tensor([[0, 1],
        [2, 3]])
>>> torch.fliplr(x)
tensor([[1, 0],
        [3, 2]])


torch.flipud(input) → Tensor
Flip tensor in the up/down direction, returning a new tensor. Flip the entries in each column in the up/down direction. Rows are preserved, but appear in a different order than before.  Note Requires the tensor to be at least 1-D.   Note torch.flipud makes a copy of input’s data. This is different from NumPy’s np.flipud, which returns a view in constant time. Since copying a tensor’s data is more work than viewing that data, torch.flipud is expected to be slower than np.flipud.   Parameters
input (Tensor) – Must be at least 1-dimensional.   Example: >>> x = torch.arange(4).view(2, 2)
>>> x
tensor([[0, 1],
        [2, 3]])
>>> torch.flipud(x)
tensor([[2, 3],
        [0, 1]])


class torch.FloatStorage(*args, **kwargs) [source]

bfloat16()
Casts this storage to bfloat16 type

bool()
Casts this storage to bool type

byte()
Casts this storage to byte type

char()
Casts this storage to char type

clone()
Returns a copy of this storage

complex_double()
Casts this storage to complex double type

complex_float()
Casts this storage to complex float type

copy_()

cpu()
Returns a CPU copy of this storage if it’s not already on the CPU

cuda(device=None, non_blocking=False, **kwargs)
Returns a copy of this object in CUDA memory. If this object is already in CUDA memory and on the correct device, then no copy is performed and the original object is returned.  Parameters

device (int) – The destination GPU id. Defaults to the current device.
non_blocking (bool) – If True and the source is in pinned memory, the copy will be asynchronous with respect to the host. Otherwise, the argument has no effect.
**kwargs – For compatibility, may contain the key async in place of the non_blocking argument.

data_ptr()

device

double()
Casts this storage to double type

dtype

element_size()

fill_()

float()
Casts this storage to float type

static from_buffer()

static from_file(filename, shared=False, size=0) → Storage
If shared is True, then memory is shared between all processes. All changes are written to the file. If shared is False, then the changes on the storage do not affect the file. size is the number of elements in the storage. If shared is False, then the file must contain at least size * sizeof(Type) bytes (Type is the type of storage). If shared is True the file will be created if needed.  Parameters

filename (str) – file name to map
shared (bool) – whether to share memory
size (int) – number of elements in the storage

get_device()

half()
Casts this storage to half type

int()
Casts this storage to int type

is_cuda: bool = False

is_pinned()

is_shared()

is_sparse: bool = False

long()
Casts this storage to long type

new()

pin_memory()
Copies the storage to pinned memory, if it’s not already pinned.

resize_()

share_memory_()
Moves the storage to shared memory. This is a no-op for storages already in shared memory and for CUDA storages, which do not need to be moved for sharing across processes. Storages in shared memory cannot be resized. Returns: self

short()
Casts this storage to short type

size()

tolist()
Returns a list containing the elements of this storage

type(dtype=None, non_blocking=False, **kwargs)
Returns the type if dtype is not provided, else casts this object to the specified type. If this is already of the correct type, no copy is performed and the original object is returned.  Parameters

dtype (type or string) – The desired type
non_blocking (bool) – If True, and the source is in pinned memory and destination is on the GPU or vice versa, the copy is performed asynchronously with respect to the host. Otherwise, the argument has no effect.
**kwargs – For compatibility, may contain the key async in place of the non_blocking argument. The async arg is deprecated.


bfloat16()
Casts this storage to bfloat16 type


complex_double()
Casts this storage to complex double type


complex_float()
Casts this storage to complex float type


cpu()
Returns a CPU copy of this storage if it’s not already on the CPU


cuda(device=None, non_blocking=False, **kwargs)
Returns a copy of this object in CUDA memory. If this object is already in CUDA memory and on the correct device, then no copy is performed and the original object is returned.  Parameters

device (int) – The destination GPU id. Defaults to the current device.
non_blocking (bool) – If True and the source is in pinned memory, the copy will be asynchronous with respect to the host. Otherwise, the argument has no effect.
**kwargs – For compatibility, may contain the key async in place of the non_blocking argument.


double()
Casts this storage to double type


float()
Casts this storage to float type


static from_file(filename, shared=False, size=0) → Storage
If shared is True, then memory is shared between all processes. All changes are written to the file. If shared is False, then the changes on the storage do not affect the file. size is the number of elements in the storage. If shared is False, then the file must contain at least size * sizeof(Type) bytes (Type is the type of storage). If shared is True the file will be created if needed.  Parameters

filename (str) – file name to map
shared (bool) – whether to share memory
size (int) – number of elements in the storage


pin_memory()
Copies the storage to pinned memory, if it’s not already pinned.


share_memory_()
Moves the storage to shared memory. This is a no-op for storages already in shared memory and for CUDA storages, which do not need to be moved for sharing across processes. Storages in shared memory cannot be resized. Returns: self


short()
Casts this storage to short type


tolist()
Returns a list containing the elements of this storage


type(dtype=None, non_blocking=False, **kwargs)
Returns the type if dtype is not provided, else casts this object to the specified type. If this is already of the correct type, no copy is performed and the original object is returned.  Parameters

dtype (type or string) – The desired type
non_blocking (bool) – If True, and the source is in pinned memory and destination is on the GPU or vice versa, the copy is performed asynchronously with respect to the host. Otherwise, the argument has no effect.
**kwargs – For compatibility, may contain the key async in place of the non_blocking argument. The async arg is deprecated.


torch.float_power(input, exponent, *, out=None) → Tensor
Raises input to the power of exponent, elementwise, in double precision. If neither input is complex returns a torch.float64 tensor, and if one or more inputs is complex returns a torch.complex128 tensor.  Note This function always computes in double precision, unlike torch.pow(), which implements more typical type promotion. This is useful when the computation needs to be performed in a wider or more precise dtype, or the results of the computation may contain fractional values not representable in the input dtypes, like when an integer base is raised to a negative integer exponent.   Parameters

input (Tensor or Number) – the base value(s)
exponent (Tensor or Number) – the exponent value(s)   Keyword Arguments
out (Tensor, optional) – the output tensor.   Example: >>> a = torch.randint(10, (4,))
>>> a
tensor([6, 4, 7, 1])
>>> torch.float_power(a, 2)
tensor([36., 16., 49.,  1.], dtype=torch.float64)

>>> a = torch.arange(1, 5)
>>> a
tensor([ 1,  2,  3,  4])
>>> exp = torch.tensor([2, -3, 4, -5])
>>> exp
tensor([ 2, -3,  4, -5])
>>> torch.float_power(a, exp)
tensor([1.0000e+00, 1.2500e-01, 8.1000e+01, 9.7656e-04], dtype=torch.float64)


torch.floor(input, *, out=None) → Tensor
Returns a new tensor with the floor of the elements of input, the largest integer less than or equal to each element.  outi=⌊inputi⌋\text{out}_{i} = \left\lfloor \text{input}_{i} \right\rfloor
 Parameters
input (Tensor) – the input tensor.  Keyword Arguments
out (Tensor, optional) – the output tensor.   Example: >>> a = torch.randn(4)
>>> a
tensor([-0.8166,  1.5308, -0.2530, -0.2091])
>>> torch.floor(a)
tensor([-1.,  1., -1., -1.])


torch.floor_divide(input, other, *, out=None) → Tensor
 Warning This function’s name is a misnomer. It actually rounds the quotient towards zero instead of taking its floor. This behavior will be deprecated in a future PyTorch release.  Computes input divided by other, elementwise, and rounds each quotient towards zero. Equivalently, it truncates the quotient(s):  outi=trunc(inputiotheri)\text{{out}}_i = \text{trunc} \left( \frac{{\text{{input}}_i}}{{\text{{other}}_i}} \right)
Supports broadcasting to a common shape, type promotion, and integer and float inputs.  Parameters

input (Tensor or Number) – the dividend
other (Tensor or Number) – the divisor   Keyword Arguments
out (Tensor, optional) – the output tensor.   Example: >>> a = torch.tensor([4.0, 3.0])
>>> b = torch.tensor([2.0, 2.0])
>>> torch.floor_divide(a, b)
tensor([2.0, 1.0])
>>> torch.floor_divide(a, 1.4)
tensor([2.0, 2.0])


torch.fmax(input, other, *, out=None) → Tensor
Computes the element-wise maximum of input and other. This is like torch.maximum() except it handles NaNs differently: if exactly one of the two elements being compared is a NaN then the non-NaN element is taken as the maximum. Only if both elements are NaN is NaN propagated. This function is a wrapper around C++’s std::fmax and is similar to NumPy’s fmax function. Supports broadcasting to a common shape, type promotion, and integer and floating-point inputs.  Parameters

input (Tensor) – the input tensor.
other (Tensor) – the second input tensor   Keyword Arguments
out (Tensor, optional) – the output tensor.   Example: >>> a = torch.tensor([9.7, float('nan'), 3.1, float('nan')])
>>> b = torch.tensor([-2.2, 0.5, float('nan'), float('nan')])
>>> torch.fmax(a, b)
tensor([9.7000, 0.5000, 3.1000,    nan])


torch.fmin(input, other, *, out=None) → Tensor
Computes the element-wise minimum of input and other. This is like torch.minimum() except it handles NaNs differently: if exactly one of the two elements being compared is a NaN then the non-NaN element is taken as the minimum. Only if both elements are NaN is NaN propagated. This function is a wrapper around C++’s std::fmin and is similar to NumPy’s fmin function. Supports broadcasting to a common shape, type promotion, and integer and floating-point inputs.  Parameters

input (Tensor) – the input tensor.
other (Tensor) – the second input tensor   Keyword Arguments
out (Tensor, optional) – the output tensor.   Example: >>> a = torch.tensor([2.2, float('nan'), 2.1, float('nan')])
>>> b = torch.tensor([-9.3, 0.1, float('nan'), float('nan')])
>>> torch.fmin(a, b)
tensor([-9.3000, 0.1000, 2.1000,    nan])


torch.fmod(input, other, *, out=None) → Tensor
Computes the element-wise remainder of division. The dividend and divisor may contain both for integer and floating point numbers. The remainder has the same sign as the dividend input. Supports broadcasting to a common shape, type promotion, and integer and float inputs.  Note When the divisor is zero, returns NaN for floating point dtypes on both CPU and GPU; raises RuntimeError for integer division by zero on CPU; Integer division by zero on GPU may return any value.   Parameters

input (Tensor) – the dividend
other (Tensor or Scalar) – the divisor   Keyword Arguments
out (Tensor, optional) – the output tensor.   Example: >>> torch.fmod(torch.tensor([-3., -2, -1, 1, 2, 3]), 2)
tensor([-1., -0., -1.,  1.,  0.,  1.])
>>> torch.fmod(torch.tensor([1, 2, 3, 4, 5]), 1.5)
tensor([1.0000, 0.5000, 0.0000, 1.0000, 0.5000])


torch.frac(input, *, out=None) → Tensor
Computes the fractional portion of each element in input.  outi=inputi−⌊∣inputi∣⌋∗sgn(inputi)\text{out}_{i} = \text{input}_{i} - \left\lfloor |\text{input}_{i}| \right\rfloor * \operatorname{sgn}(\text{input}_{i})
Example: >>> torch.frac(torch.tensor([1, 2.5, -3.2]))
tensor([ 0.0000,  0.5000, -0.2000])


torch.from_numpy(ndarray) → Tensor
Creates a Tensor from a numpy.ndarray. The returned tensor and ndarray share the same memory. Modifications to the tensor will be reflected in the ndarray and vice versa. The returned tensor is not resizable. It currently accepts ndarray with dtypes of numpy.float64, numpy.float32, numpy.float16, numpy.complex64, numpy.complex128, numpy.int64, numpy.int32, numpy.int16, numpy.int8, numpy.uint8, and numpy.bool. Example: >>> a = numpy.array([1, 2, 3])
>>> t = torch.from_numpy(a)
>>> t
tensor([ 1,  2,  3])
>>> t[0] = -1
>>> a
array([-1,  2,  3])


torch.full(size, fill_value, *, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False) → Tensor
Creates a tensor of size size filled with fill_value. The tensor’s dtype is inferred from fill_value.  Parameters

size (int...) – a list, tuple, or torch.Size of integers defining the shape of the output tensor.
fill_value (Scalar) – the value to fill the output tensor with.   Keyword Arguments

out (Tensor, optional) – the output tensor.
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 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.    Example: >>> torch.full((2, 3), 3.141592)
tensor([[ 3.1416,  3.1416,  3.1416],
        [ 3.1416,  3.1416,  3.1416]])


torch.full_like(input, fill_value, *, dtype=None, layout=torch.strided, device=None, requires_grad=False, memory_format=torch.preserve_format) → Tensor
Returns a tensor with the same size as input filled with fill_value. torch.full_like(input, fill_value) is equivalent to torch.full(input.size(), fill_value, dtype=input.dtype, layout=input.layout, device=input.device).  Parameters

input (Tensor) – the size of input will determine size of the output tensor.
fill_value – the number to fill the output tensor with.   Keyword Arguments

dtype (torch.dtype, optional) – the desired data type of returned Tensor. Default: if None, defaults to the dtype of input.
layout (torch.layout, optional) – the desired layout of returned tensor. Default: if None, defaults to the layout of input.
device (torch.device, optional) – the desired device of returned tensor. Default: if None, defaults to the device of input.
requires_grad (bool, optional) – If autograd should record operations on the returned tensor. Default: False.
memory_format (torch.memory_format, optional) – the desired memory format of returned Tensor. Default: torch.preserve_format.


torch.futures  Warning The torch.futures package is experimental and subject to change.  This package provides a Future type that encapsulates an asynchronous execution and a set of utility functions to simplify operations on Future objects. Currently, the Future type is primarily used by the Distributed RPC Framework.
class torch.futures.Future
Wrapper around a torch._C.Future which encapsulates an asynchronous execution of a callable, e.g. rpc_async(). It also exposes a set of APIs to add callback functions and set results.
add_done_callback(self: torch._C.Future, arg0: function) → None

done() [source]

Return True if this Future is done. A Future is done if it has a result or an exception.

set_exception(result) [source]

Set an exception for this Future, which will mark this Future as completed with an error and trigger all attached callbacks. Note that when calling wait()/value() on this Future, the exception set here will be raised inline.  Parameters
result (BaseException) – the exception for this Future.    Example::

>>> import torch
>>>
>>> fut = torch.futures.Future()
>>> fut.set_exception(ValueError("foo"))
>>> fut.wait()
>>>
>>> # Output:
>>> # This will run after the future has finished.
>>> ValueError: foo

set_result(result) [source]

Set the result for this Future, which will mark this Future as completed and trigger all attached callbacks. Note that a Future cannot be marked completed twice.  Parameters
result (object) – the result object of this Future.    Example::

>>> import threading
>>> import time
>>> import torch
>>>
>>> def slow_set_future(fut, value):
>>>     time.sleep(0.5)
>>>     fut.set_result(value)
>>>
>>> fut = torch.futures.Future()
>>> t = threading.Thread(
>>>     target=slow_set_future,
>>>     args=(fut, torch.ones(2) * 3)
>>> )
>>> t.start()
>>>
>>> print(fut.wait())  # tensor([3., 3.])
>>> t.join()

then(callback) [source]

Append the given callback function to this Future, which will be run when the Future is completed. Multiple callbacks can be added to the same Future, and will be invoked in the same order as they were added. The callback must take one argument, which is the reference to this Future. The callback function can use the Future.wait() API to get the value. Note that if this Future is already completed, the given callback will be run immediately inline.  Parameters
callback (Callable) – a Callable that takes this Future as the only argument.  Returns
A new Future object that holds the return value of the callback and will be marked as completed when the given callback finishes.    Example::

>>> import torch
>>>
>>> def callback(fut):
>>>     print(f"RPC return value is {fut.wait()}.")
>>>
>>> fut = torch.futures.Future()
>>> # The inserted callback will print the return value when
>>> # receiving the response from "worker1"
>>> cb_fut = fut.then(callback)
>>> chain_cb_fut = cb_fut.then(
>>>     lambda x : print(f"Chained cb done. {x.wait()}")
>>> )
>>> fut.set_result(5)
>>>
>>> # Outputs are:
>>> # RPC return value is 5.
>>> # Chained cb done. None

value(self: torch._C.Future) → object

wait() [source]

Block until the value of this Future is ready.  Returns
The value held by this Future. If the function (callback or RPC) creating the value has thrown an error, this wait method will also throw an error.

torch.futures.collect_all(futures) [source]

Collects the provided Future objects into a single combined Future that is completed when all of the sub-futures are completed.  Parameters
futures (list) – a list of Future objects.  Returns
Returns a Future object to a list of the passed in Futures.    Example::

>>> import torch
>>>
>>> fut0 = torch.futures.Future()
>>> fut1 = torch.futures.Future()
>>>
>>> fut = torch.futures.collect_all([fut0, fut1])
>>>
>>> fut0.set_result(0)
>>> fut1.set_result(1)
>>>
>>> fut_list = fut.wait()
>>> print(f"fut0 result = {fut_list[0].wait()}")
>>> print(f"fut1 result = {fut_list[1].wait()}")
>>> # outputs:
>>> # fut0 result = 0
>>> # fut1 result = 1

torch.futures.wait_all(futures) [source]

Waits for all provided futures to be complete, and returns the list of completed values.  Parameters
futures (list) – a list of Future object.  Returns
A list of the completed Future results. This method will throw an error if wait on any Future throws.


torch.futures.collect_all(futures) [source]

Collects the provided Future objects into a single combined Future that is completed when all of the sub-futures are completed.  Parameters
futures (list) – a list of Future objects.  Returns
Returns a Future object to a list of the passed in Futures.    Example::

>>> import torch
>>>
>>> fut0 = torch.futures.Future()
>>> fut1 = torch.futures.Future()
>>>
>>> fut = torch.futures.collect_all([fut0, fut1])
>>>
>>> fut0.set_result(0)
>>> fut1.set_result(1)
>>>
>>> fut_list = fut.wait()
>>> print(f"fut0 result = {fut_list[0].wait()}")
>>> print(f"fut1 result = {fut_list[1].wait()}")
>>> # outputs:
>>> # fut0 result = 0
>>> # fut1 result = 1


class torch.futures.Future
Wrapper around a torch._C.Future which encapsulates an asynchronous execution of a callable, e.g. rpc_async(). It also exposes a set of APIs to add callback functions and set results.
add_done_callback(self: torch._C.Future, arg0: function) → None

done() [source]

Return True if this Future is done. A Future is done if it has a result or an exception.

set_exception(result) [source]

Set an exception for this Future, which will mark this Future as completed with an error and trigger all attached callbacks. Note that when calling wait()/value() on this Future, the exception set here will be raised inline.  Parameters
result (BaseException) – the exception for this Future.    Example::

>>> import torch
>>>
>>> fut = torch.futures.Future()
>>> fut.set_exception(ValueError("foo"))
>>> fut.wait()
>>>
>>> # Output:
>>> # This will run after the future has finished.
>>> ValueError: foo

set_result(result) [source]

Set the result for this Future, which will mark this Future as completed and trigger all attached callbacks. Note that a Future cannot be marked completed twice.  Parameters
result (object) – the result object of this Future.    Example::

>>> import threading
>>> import time
>>> import torch
>>>
>>> def slow_set_future(fut, value):
>>>     time.sleep(0.5)
>>>     fut.set_result(value)
>>>
>>> fut = torch.futures.Future()
>>> t = threading.Thread(
>>>     target=slow_set_future,
>>>     args=(fut, torch.ones(2) * 3)
>>> )
>>> t.start()
>>>
>>> print(fut.wait())  # tensor([3., 3.])
>>> t.join()

then(callback) [source]

Append the given callback function to this Future, which will be run when the Future is completed. Multiple callbacks can be added to the same Future, and will be invoked in the same order as they were added. The callback must take one argument, which is the reference to this Future. The callback function can use the Future.wait() API to get the value. Note that if this Future is already completed, the given callback will be run immediately inline.  Parameters
callback (Callable) – a Callable that takes this Future as the only argument.  Returns
A new Future object that holds the return value of the callback and will be marked as completed when the given callback finishes.    Example::

>>> import torch
>>>
>>> def callback(fut):
>>>     print(f"RPC return value is {fut.wait()}.")
>>>
>>> fut = torch.futures.Future()
>>> # The inserted callback will print the return value when
>>> # receiving the response from "worker1"
>>> cb_fut = fut.then(callback)
>>> chain_cb_fut = cb_fut.then(
>>>     lambda x : print(f"Chained cb done. {x.wait()}")
>>> )
>>> fut.set_result(5)
>>>
>>> # Outputs are:
>>> # RPC return value is 5.
>>> # Chained cb done. None

value(self: torch._C.Future) → object

wait() [source]

Block until the value of this Future is ready.  Returns
The value held by this Future. If the function (callback or RPC) creating the value has thrown an error, this wait method will also throw an error.


add_done_callback(self: torch._C.Future, arg0: function) → None


done() [source]

Return True if this Future is done. A Future is done if it has a result or an exception.


set_exception(result) [source]

Set an exception for this Future, which will mark this Future as completed with an error and trigger all attached callbacks. Note that when calling wait()/value() on this Future, the exception set here will be raised inline.  Parameters
result (BaseException) – the exception for this Future.    Example::

>>> import torch
>>>
>>> fut = torch.futures.Future()
>>> fut.set_exception(ValueError("foo"))
>>> fut.wait()
>>>
>>> # Output:
>>> # This will run after the future has finished.
>>> ValueError: foo


set_result(result) [source]

Set the result for this Future, which will mark this Future as completed and trigger all attached callbacks. Note that a Future cannot be marked completed twice.  Parameters
result (object) – the result object of this Future.    Example::

>>> import threading
>>> import time
>>> import torch
>>>
>>> def slow_set_future(fut, value):
>>>     time.sleep(0.5)
>>>     fut.set_result(value)
>>>
>>> fut = torch.futures.Future()
>>> t = threading.Thread(
>>>     target=slow_set_future,
>>>     args=(fut, torch.ones(2) * 3)
>>> )
>>> t.start()
>>>
>>> print(fut.wait())  # tensor([3., 3.])
>>> t.join()


then(callback) [source]

Append the given callback function to this Future, which will be run when the Future is completed. Multiple callbacks can be added to the same Future, and will be invoked in the same order as they were added. The callback must take one argument, which is the reference to this Future. The callback function can use the Future.wait() API to get the value. Note that if this Future is already completed, the given callback will be run immediately inline.  Parameters
callback (Callable) – a Callable that takes this Future as the only argument.  Returns
A new Future object that holds the return value of the callback and will be marked as completed when the given callback finishes.    Example::

>>> import torch
>>>
>>> def callback(fut):
>>>     print(f"RPC return value is {fut.wait()}.")
>>>
>>> fut = torch.futures.Future()
>>> # The inserted callback will print the return value when
>>> # receiving the response from "worker1"
>>> cb_fut = fut.then(callback)
>>> chain_cb_fut = cb_fut.then(
>>>     lambda x : print(f"Chained cb done. {x.wait()}")
>>> )
>>> fut.set_result(5)
>>>
>>> # Outputs are:
>>> # RPC return value is 5.
>>> # Chained cb done. None


wait() [source]

Block until the value of this Future is ready.  Returns
The value held by this Future. If the function (callback or RPC) creating the value has thrown an error, this wait method will also throw an error.


torch.futures.wait_all(futures) [source]

Waits for all provided futures to be complete, and returns the list of completed values.  Parameters
futures (list) – a list of Future object.  Returns
A list of the completed Future results. This method will throw an error if wait on any Future throws.