Skip to content
Permalink
Branch: master
Find file Copy path
Find file Copy path
14068 lines (12090 sloc) 614 KB
import sys
import io
import os
import math
import random
import re
import copy
import shutil
import torch
import torch.cuda
import torch.backends.cuda
import tempfile
import unittest
import warnings
import pickle
import gzip
import types
import textwrap
import zipfile
from torch._utils_internal import get_file_path_2
from torch.utils.dlpack import from_dlpack, to_dlpack
from torch._utils import _rebuild_tensor
from torch._six import inf, nan, string_classes, istuple
from itertools import product, combinations, combinations_with_replacement, permutations
from functools import reduce
from random import randrange
from torch import multiprocessing as mp
from common_methods_invocations import tri_tests_args, run_additional_tri_tests, \
_compare_trilu_indices
from common_utils import TestCase, iter_indices, TEST_NUMPY, TEST_SCIPY, TEST_MKL, \
TEST_LIBROSA, run_tests, download_file, skipIfNoLapack, suppress_warnings, \
IS_WINDOWS, PY3, NO_MULTIPROCESSING_SPAWN, do_test_dtypes, do_test_empty_full, \
IS_SANDCASTLE, load_tests, brute_pdist, brute_cdist, slowTest, \
skipCUDANonDefaultStreamIf, skipCUDAMemoryLeakCheckIf
from multiprocessing.reduction import ForkingPickler
from common_device_type import instantiate_device_type_tests, \
skipCPUIfNoLapack, skipCUDAIfNoMagma, skipCUDAIfRocm, onlyCUDA, onlyCPU, \
dtypes, dtypesIfCUDA, deviceCountAtLeast, skipCUDAIf, precisionOverride
import torch.backends.quantized
# load_tests from common_utils is used to automatically filter tests for
# sharding on sandcastle. This line silences flake warnings
load_tests = load_tests
if TEST_NUMPY:
import numpy as np
if TEST_SCIPY:
from scipy import signal
if TEST_LIBROSA:
import librosa
SIZE = 100
can_retrieve_source = True
with warnings.catch_warnings(record=True) as warns:
with tempfile.NamedTemporaryFile() as checkpoint:
x = torch.save(torch.nn.Module(), checkpoint)
for warn in warns:
if "Couldn't retrieve source code" in warn.message.args[0]:
can_retrieve_source = False
break
class FilelikeMock(object):
def __init__(self, data, has_fileno=True, has_readinto=False):
if has_readinto:
self.readinto = self.readinto_opt
if has_fileno:
# Python 2's StringIO.StringIO has no fileno attribute.
# This is used to test that.
self.fileno = self.fileno_opt
self.calls = set()
self.bytesio = io.BytesIO(data)
def trace(fn, name):
def result(*args, **kwargs):
self.calls.add(name)
return fn(*args, **kwargs)
return result
for attr in ['read', 'readline', 'seek', 'tell', 'write', 'flush']:
traced_fn = trace(getattr(self.bytesio, attr), attr)
setattr(self, attr, traced_fn)
def fileno_opt(self):
raise io.UnsupportedOperation('Not a real file')
def readinto_opt(self, view):
self.calls.add('readinto')
return self.bytesio.readinto(view)
def was_called(self, name):
return name in self.calls
class BytesIOContext(io.BytesIO):
def __enter__(self):
return self
def __exit__(self, *args):
pass
# This is intentionally prefixed by an underscore. Otherwise pytest will try to
# run its methods as test cases.
class _TestTorchMixin(object):
def _make_tensors(self, shape, val_range=(-100, 100), use_floating=True, use_integral=True):
float_types = [torch.double,
torch.float]
int_types = [torch.int64,
torch.int32,
torch.int16]
def make_contiguous(shape, dtype):
if dtype in float_types:
val = torch.randn(shape, dtype=dtype)
val = val * ((val_range[1] - val_range[0]) / (math.pi * 2.0))
val = val + ((val_range[1] - val_range[0]) / 2.0)
val = torch.clamp(val, min=val_range[0], max=val_range[1])
return val
result = torch.zeros(shape, dtype=dtype)
result.apply_(lambda x: random.randint(val_range[0], val_range[1]))
return result
def make_non_contiguous(shape, dtype):
contig = make_contiguous(shape, dtype)
non_contig = torch.empty(shape + (2, 2), dtype=dtype)[..., 0]
non_contig = non_contig.select(-1, -1)
non_contig.copy_(contig)
self.assertFalse(non_contig.is_contiguous())
return non_contig
def make_contiguous_slice(size, dtype):
contig = make_contiguous((1, size), dtype)
non_contig = contig[:1, 1:size - 1]
self.assertTrue(non_contig.is_contiguous())
return contig
types = []
if use_floating:
types += float_types
if use_integral:
types += int_types
tensors = {"cont": [], "noncont": [], "slice": []}
for dtype in types:
tensors["cont"].append(make_contiguous(shape, dtype))
tensors["noncont"].append(make_non_contiguous(shape, dtype))
tensors["slice"].append(make_contiguous_slice(sum(list(shape)), dtype))
return tensors
def test_dir(self):
dir(torch)
def test_type_conversion_via_dtype_name(self):
x = torch.tensor([1])
self.assertEqual(x.byte().dtype, torch.uint8)
self.assertEqual(x.bool().dtype, torch.bool)
self.assertEqual(x.char().dtype, torch.int8)
self.assertEqual(x.double().dtype, torch.float64)
self.assertEqual(x.float().dtype, torch.float32)
self.assertEqual(x.half().dtype, torch.float16)
self.assertEqual(x.int().dtype, torch.int32)
self.assertEqual(x.bfloat16().dtype, torch.bfloat16)
def test_doc_template(self):
from torch._torch_docs import __file__ as doc_file
from torch._torch_docs import multi_dim_common, single_dim_common, factory_common_args, factory_like_common_args
with open(doc_file, "r") as f:
doc_strs = f.read()
for doc_str in re.findall(r'add_docstr\((.*?),.*?("""|\'\'\')(.*?)("""|\'\'\')\)', doc_strs, re.MULTILINE | re.DOTALL):
for common_args in [multi_dim_common, single_dim_common, factory_common_args, factory_like_common_args]:
for k, v in common_args.items():
self.assertNotIn(v, doc_str[2], 'The argument description "{}" in {} can be '
'replaced by {{{}}}'.format(v, doc_str[0], k))
def test_doc(self):
checked_types = (types.MethodType, types.FunctionType,
types.BuiltinFunctionType, types.BuiltinMethodType)
def test_namespace(ns, *skips):
if isinstance(ns, object):
ns_name = ns.__class__.__name__
else:
ns_name = ns.__name__
skip_regexes = []
for r in skips:
if isinstance(r, string_classes):
skip_regexes.append(re.compile('^{}$'.format(re.escape(r))))
else:
skip_regexes.append(r)
for name in dir(ns):
if name.startswith('_'):
continue
var = getattr(ns, name)
if not isinstance(var, checked_types):
continue
doc = var.__doc__
has_doc = doc is not None and len(doc.strip()) > 0
full_name = ns_name + '.' + name
if any(r.match(name) for r in skip_regexes):
self.assertFalse(has_doc,
'New docs have been added for {}, please remove '
'it from the skipped list in TestTorch.test_doc'.format(full_name))
else:
self.assertTrue(has_doc, '{} is missing documentation'.format(full_name))
# FIXME: All of the following should be marked as expected failures
# so that it is easier to tell when missing has been added.
# FIXME: fix all the skipped ones below!
test_namespace(torch.randn(1),
'as_strided_',
re.compile('^clamp_(min|max)_?$'),
'coalesce',
'is_coalesced',
'is_distributed',
'is_complex',
'is_nonzero',
'is_same_size',
'isclose',
'log_softmax',
'map2_',
'new',
'reinforce',
'relu',
'relu_',
'prelu',
'resize',
'resize_as',
'smm',
'softmax',
'split_with_sizes',
'sspaddmm',
'to_dense',
'sparse_resize_',
'sparse_resize_and_clear_',
)
test_namespace(torch.nn)
test_namespace(torch.nn.functional, 'assert_int_or_pair', 'feature_alpha_dropout')
# TODO: add torch.* tests when we have proper namespacing on ATen functions
# test_namespace(torch)
def test_allclose(self):
x = torch.tensor([1.0, 2.0, 3.0])
y = torch.tensor([1.01, 2.01, 3.01])
self.assertTrue(torch.allclose(x, y, rtol=0, atol=0.02))
self.assertTrue(torch.allclose(x, y, rtol=0.01, atol=0.0))
self.assertFalse(torch.allclose(x, y))
self.assertTrue(torch.allclose(torch.tensor([0.0]), torch.tensor([1e-8])))
x = torch.tensor([2.0, 3.0, nan])
y = torch.tensor([2.01, 3.01, nan])
self.assertFalse(torch.allclose(x, y, rtol=1e-2))
self.assertTrue(torch.allclose(x, y, rtol=1e-2, equal_nan=True))
self.assertFalse(torch.allclose(x, y, rtol=1e-3, equal_nan=True))
inf_t = torch.tensor([inf])
self.assertTrue(torch.allclose(inf_t, inf_t))
self.assertTrue(torch.allclose(-inf_t, -inf_t))
self.assertFalse(torch.allclose(inf_t, -inf_t))
self.assertFalse(torch.allclose(inf_t, torch.tensor([1e20])))
self.assertFalse(torch.allclose(-inf_t, torch.tensor([-1e20])))
def test_linear_algebra_scalar_raises(self):
m = torch.randn(5, 5)
v = torch.randn(5)
s = torch.tensor(7)
self.assertRaises(RuntimeError, lambda: torch.mv(m, s))
self.assertRaises(RuntimeError, lambda: torch.addmv(v, m, s))
self.assertRaises(RuntimeError, lambda: torch.ger(v, s))
self.assertRaises(RuntimeError, lambda: torch.ger(s, v))
self.assertRaises(RuntimeError, lambda: torch.addr(m, v, s))
self.assertRaises(RuntimeError, lambda: torch.addr(m, s, v))
def _test_math(self, torchfn, mathfn, input=None, test_expand=False):
if input is None:
input = []
input.append(list(range(-5, 5)))
input.append([0 for x in range(-5, 5)])
input.append([x + 1e-6 for x in range(-5, 5)])
# Some vectorized implementations don't support large ranges
input.append([x + 1e10 for x in range(-5, 5)])
input.append([x - 1e10 for x in range(-5, 5)])
input.append(torch.randn(10).tolist())
input.append((torch.randn(10) + 1e6).tolist())
input.append([math.pi * (x / 2) for x in range(-5, 5)])
def compare_reference(input, dtype):
input = torch.tensor(input, dtype=dtype)
res1 = torchfn(input.clone())
res2 = input.clone().apply_(mathfn)
torch.testing.assert_allclose(res1, res2)
# compare against the reference math function
compare_reference(input, torch.double)
compare_reference(input, torch.float)
def check_non_contiguous(shape, dtype):
contig = torch.randn(shape, dtype=dtype)
non_contig = torch.empty(shape + (2,), dtype=dtype)[..., 0]
non_contig.copy_(contig)
self.assertFalse(non_contig.is_contiguous())
self.assertEqual(torchfn(contig), torchfn(non_contig), 'non-contiguous')
# compare application against contiguous vs. non-contiguous
check_non_contiguous((5, 7), torch.double)
check_non_contiguous((1024,), torch.double)
check_non_contiguous((5, 7), torch.float)
check_non_contiguous((1024,), torch.float)
def check_non_contiguous_index(dtype):
contig = torch.randn((2, 2, 1, 2), dtype=dtype)
non_contig = contig[:, 1, ...]
contig = non_contig.clone()
self.assertFalse(non_contig.is_contiguous())
self.assertEqual(torchfn(contig), torchfn(non_contig), 'non-contiguous index')
check_non_contiguous_index(torch.float)
check_non_contiguous_index(torch.double)
def check_non_contiguous_expand(shape, dtype):
contig = torch.randn(shape, dtype=dtype)
non_contig = contig.clone().expand(3, -1, -1)
self.assertFalse(non_contig.is_contiguous())
contig = torchfn(contig)
non_contig = torchfn(non_contig)
for i in range(3):
self.assertEqual(contig, non_contig[i], 'non-contiguous expand[' + str(i) + ']')
# Expand is not defined for in-place operations
if test_expand:
# The size 1 case is special as it leads to 0 stride and needs to persists
check_non_contiguous_expand((1, 3), torch.double)
check_non_contiguous_expand((1, 7), torch.double)
check_non_contiguous_expand((5, 7), torch.float)
# If size(dim) == 1, stride(dim) is not defined.
# The code needs to be able to handle this
def check_contiguous_size1(dtype):
contig = torch.randn((5, 100), dtype=dtype)
contig = contig[:1, :50]
contig2 = torch.empty(contig.size(), dtype=dtype)
contig2.copy_(contig)
self.assertTrue(contig.is_contiguous())
self.assertTrue(contig2.is_contiguous())
self.assertEqual(torchfn(contig), torchfn(contig2), 'contiguous size1')
check_contiguous_size1(torch.double)
check_contiguous_size1(torch.float)
def check_contiguous_size1_largedim(dtype):
contig = torch.randn((5, 2, 3, 1, 4, 5, 3, 2, 1, 2, 3, 4), dtype=dtype)
contig = contig[:1, :, :, :, :, :, :, :, :, :, :, :]
contig2 = torch.empty(contig.size(), dtype=dtype)
contig2.copy_(contig)
self.assertTrue(contig.is_contiguous())
self.assertTrue(contig2.is_contiguous())
self.assertEqual(torchfn(contig), torchfn(contig2), 'contiguous size1')
check_contiguous_size1_largedim(torch.double)
check_contiguous_size1_largedim(torch.float)
def check_large(dtype):
input = torch.randn(1024, 512, dtype=dtype)
actual = torchfn(input)
expected = torch.stack([torchfn(slice) for slice in input])
self.assertEqual(actual, expected, 'large')
# compare large tensor vs. repeated small applications to expose
# possible parallelism bugs.
check_large(torch.double)
check_large(torch.float)
def __test_math_by_name(self, function_name, mathfn, selffn):
mathfn = getattr(math, mathfn)
if selffn:
def torchfn(x):
return getattr(x, function_name)()
else:
torchfn = getattr(torch, function_name)
self._test_math(torchfn, mathfn, test_expand=(not selffn))
def _test_math_by_name(self, function_name, test_self=True):
if test_self:
self.__test_math_by_name(function_name + "_", function_name, True)
self.__test_math_by_name(function_name, function_name, False)
def test_sin(self):
self._test_math_by_name('sin')
def test_sinh(self):
def sinh(x):
try:
return math.sinh(x)
except OverflowError:
return inf if x > 0 else -inf
self._test_math(torch.sinh, sinh)
def test_lgamma(self):
def lgamma(x):
if x <= 0 and x == int(x):
return inf
return math.lgamma(x)
self._test_math(torch.lgamma, lgamma)
@unittest.skipIf(not TEST_SCIPY, "Scipy not found")
def test_mvlgamma(self):
from scipy.special import multigammaln
for d in range(1, 5):
input = torch.empty(10).uniform_(d, 10)
res_torch = torch.mvlgamma(input, d)
res_scipy = multigammaln(input.numpy(), d)
self.assertEqual(res_torch.numpy(), res_scipy)
def test_mvlgamma_argcheck(self):
def run_test(d):
input = torch.linspace((d - 2) / 2, 10, 10)
torch.mvlgamma(input, d)
with self.assertRaisesRegex(RuntimeError, "Condition for computing multivariate log-gamma not met"):
run_test(3)
def _digamma_input(self, test_poles=True):
input = []
input.append((torch.randn(10).abs() + 1e-4).tolist())
input.append((torch.randn(10).abs() + 1e6).tolist())
zeros = torch.linspace(-9.5, -0.5, 10)
input.append(zeros.tolist())
input.append((zeros - 0.49).tolist())
input.append((zeros + 0.49).tolist())
input.append((zeros + (torch.rand(10) * 0.99) - 0.5).tolist())
if test_poles:
input.append([-0.999999994, -1.999999994, -2.0000000111,
-100.99999994, -1931.99999994, 0.000000111,
-0.000000111, 0, -2, -329])
return input
@unittest.skipIf(not TEST_SCIPY, "Scipy not found")
def test_digamma(self):
from scipy.special import digamma
# scipy 1.1.0 changed when it returns +/-inf vs. NaN
def torch_digamma_without_inf(inp):
res = torch.digamma(inp)
res[(res == -inf) | (res == inf)] = nan
return res
def scipy_digamma_without_inf(inp):
res = digamma(inp)
if np.isscalar(res):
return res if np.isfinite(res) else nan
res[np.isinf(res)] = nan
return res
self._test_math(torch_digamma_without_inf, scipy_digamma_without_inf, self._digamma_input())
@unittest.skipIf(not TEST_SCIPY, "Scipy not found")
def test_polygamma(self):
from scipy.special import polygamma
for n in [0, 1]:
self._test_math(lambda x: torch.polygamma(n, x),
lambda x: polygamma(n, x).item(),
self._digamma_input(test_poles=False))
with self.assertRaisesRegex(RuntimeError, r'polygamma\(n, x\) does not support negative n\.'):
torch.polygamma(-1, torch.tensor([1.0, 2.0]))
def test_asin(self):
self._test_math(torch.asin, lambda x: math.asin(x) if abs(x) <= 1 else nan)
def test_cos(self):
self._test_math_by_name('cos')
def test_cosh(self):
def cosh(x):
try:
return math.cosh(x)
except OverflowError:
# Return inf on overflow.
# See http://en.cppreference.com/w/cpp/numeric/math/cosh
return inf
self._test_math(torch.cosh, cosh)
def test_acos(self):
self._test_math(torch.acos, lambda x: math.acos(x) if abs(x) <= 1 else nan)
def test_tan(self):
self._test_math_by_name('tan')
def test_tanh(self):
self._test_math_by_name('tanh')
def test_atan(self):
self._test_math_by_name('atan')
def test_log(self):
def log(x):
if x == 0:
return -inf
elif x < 0:
return nan
return math.log(x)
self._test_math(torch.log, log)
def test_log10(self):
def log10(x):
if x == 0:
return -inf
elif x < 0:
return nan
return math.log10(x)
self._test_math(torch.log10, log10)
def test_log1p(self):
def log1p(x):
if x == -1:
return -inf
elif x < -1:
return nan
return math.log1p(x)
self._test_math(torch.log1p, log1p)
def test_log2(self):
def log2(x):
if x == 0:
return -inf
elif x < 0:
return nan
try:
return math.log2(x)
except AttributeError:
return math.log(x, 2)
self._test_math(torch.log2, log2)
def test_sqrt(self):
self._test_math(torch.sqrt, lambda x: math.sqrt(x) if x >= 0 else nan)
def test_erf(self):
self._test_math_by_name('erf')
def test_erfc(self):
self._test_math_by_name('erfc')
def test_exp(self):
def exp(x):
try:
return math.exp(x)
except OverflowError:
return inf
self._test_math(torch.exp, exp)
def test_expm1(self):
def expm1(x):
try:
return math.expm1(x)
except OverflowError:
return inf
self._test_math(torch.expm1, expm1)
def test_floor(self):
self._test_math_by_name('floor')
def test_ceil(self):
self._test_math_by_name('ceil')
def test_rsqrt(self):
def rsqrt(x):
if x == 0:
return inf
elif x < 0:
return nan
return 1.0 / math.sqrt(x)
self._test_math(torch.rsqrt, rsqrt)
def test_frac(self):
self._test_math(torch.frac, lambda x: math.fmod(x, 1))
def test_trunc(self):
self._test_math(torch.trunc, lambda x: x - math.fmod(x, 1))
def test_round(self):
self._test_math(torch.round, round)
def test_has_storage(self):
self.assertIsNotNone(torch.Tensor().storage())
self.assertIsNotNone(torch.Tensor(0).storage())
self.assertIsNotNone(torch.Tensor([]).storage())
self.assertIsNotNone(torch.Tensor().clone().storage())
self.assertIsNotNone(torch.Tensor([0, 0, 0]).nonzero().storage())
self.assertIsNotNone(torch.Tensor().new().storage())
def _testSelection(self, torchfn, mathfn):
# contiguous
m1 = torch.randn(100, 100)
res1 = torchfn(m1)
res2 = m1[0, 0]
for i, j in iter_indices(m1):
res2 = mathfn(res2, m1[i, j])
self.assertEqual(res1, res2)
# non-contiguous
m1 = torch.randn(10, 10, 10)
m2 = m1[:, 4]
res1 = torchfn(m2)
res2 = m2[0, 0]
for i, j in iter_indices(m2):
res2 = mathfn(res2, m2[i][j])
self.assertEqual(res1, res2)
# with indices
m1 = torch.randn(100, 100)
res1val, res1ind = torchfn(m1, 1, False)
res2val = m1[:, 0:1].clone().squeeze()
res2ind = res1ind.clone().fill_(0)
for i, j in iter_indices(m1):
if mathfn(res2val[i], m1[i, j]) != res2val[i]:
res2val[i] = m1[i, j]
res2ind[i] = j
maxerr = 0
for i in range(res1val.size(0)):
maxerr = max(maxerr, abs(res1val[i] - res2val[i]))
self.assertEqual(res1ind[i], res2ind[i])
self.assertLessEqual(abs(maxerr), 1e-5)
# NaNs
for index in (0, 4, 99):
m1 = torch.randn(100)
m1[index] = nan
res1val, res1ind = torch.max(m1, 0)
self.assertTrue(math.isnan(res1val))
self.assertEqual(res1ind, index)
res1val = torchfn(m1)
self.assertTrue(math.isnan(res1val))
# Bool
m1 = torch.tensor([True, False, True], dtype=torch.bool)
res1 = torchfn(m1)
res2 = m1[0]
for i in iter_indices(m1):
res2 = mathfn(res2, m1[i])
self.assertEqual(res1, res2)
def test_max(self):
self._testSelection(torch.max, max)
def test_min(self):
self._testSelection(torch.min, min)
def test_dim_reduction_uint8_overflow(self):
example = [[-1, 2, 1], [5, 3, 6]]
x = torch.tensor(example, dtype=torch.uint8)
self.assertEqual(x.sum(dtype=torch.uint8).item(), 16)
self.assertEqual(x.sum(0, dtype=torch.uint8), torch.FloatTensor([4, 5, 7]))
self.assertEqual(x.sum(1, dtype=torch.uint8), torch.FloatTensor([2, 14]))
y = torch.tensor(example, dtype=torch.uint8)
torch.sum(x, 0, out=y)
self.assertEqual(x.sum(0, dtype=torch.uint8), y)
@unittest.skipIf(not TEST_SCIPY, "Scipy not found")
def test_logsumexp(self):
from scipy.special import logsumexp
a = torch.randn(5, 4)
a[0, 0] = inf
a[1, :] = -inf
actual = a.logsumexp(1)
expected = logsumexp(a.numpy(), 1)
self.assertEqual(expected.shape, actual.shape)
self.assertTrue(np.allclose(expected, actual.numpy()))
# check that out is actually inplace
b = torch.zeros(5, 2)
c = b[:, 0]
torch.logsumexp(a, 1, out=c)
self.assertTrue(np.allclose(expected, b[:, 0].numpy()))
@unittest.skipIf(not TEST_NUMPY, "Numpy not found")
def test_cpu_parallel(self):
# To use parallel branches we'll need to compare on tensors
# that are relatively large. Even if this is run on a single
# core machine these tests will still give you signal on
# the correctness
def _run_test(size):
for dim in range(len(size) + 1):
nv = np.round(np.random.rand(*size)) # 0s and 1s
tv = torch.from_numpy(nv)
# Parallelisim is only used if numel is
# larger than grainsize defined in Parallel.h
self.assertTrue(tv.numel() > 32768)
if dim == len(size):
nvs = nv.sum()
tvs = tv.sum()
else:
nvs = nv.sum(dim)
tvs = tv.sum(dim)
diff = np.abs(nvs - tvs.numpy()).sum()
self.assertEqual(diff, 0)
_run_test([2, 3, 3, 3, 3, 2, 2, 3, 2, 3, 2, 3, 3])
_run_test([4, 4, 4, 4, 4, 4, 4, 4, 4, 4])
_run_test([1, 32 * 8 * 32 * 8])
_run_test([1, 32770])
def _testCSelection(self, torchfn, mathfn):
# Two tensors
size = (100, 100)
a = torch.rand(*size)
b = torch.rand(*size)
c = torchfn(a, b)
expected_c = torch.zeros(*size)
expected_c.map2_(a, b, lambda _, a, b: mathfn(a, b))
self.assertEqual(expected_c, c, 0)
def test_max_elementwise(self):
self._testCSelection(torch.max, max)
def test_min_elementwise(self):
self._testCSelection(torch.min, min)
def test_all_any(self):
def test(size):
x = torch.ones(*size).byte()
self.assertTrue(x.all())
self.assertTrue(x.any())
x[3] = 0
self.assertFalse(x.all())
self.assertTrue(x.any())
x.zero_()
self.assertFalse(x.all())
self.assertFalse(x.any())
x.fill_(2)
self.assertTrue(x.all())
self.assertTrue(x.any())
x = torch.ones(*size).bool()
self.assertTrue(x.all())
self.assertTrue(x.any())
x[3] = False
self.assertFalse(x.all())
self.assertTrue(x.any())
test((10,))
test((5, 5))
def test_where_bool_tensor(self):
for d in torch.testing.get_all_device_types():
a = torch.tensor([True, False], device=d)
res = torch.where(a > 0)
self.assertEqual(1, len(res))
def test_all_any_with_dim(self):
def test(x):
r1 = x.prod(dim=0, keepdim=False).byte()
r2 = x.all(dim=0, keepdim=False)
self.assertEqual(r1.shape, r2.shape)
self.assertTrue((r1 == r2).all())
r3 = x.sum(dim=1, keepdim=True).clamp(0, 1).byte()
r4 = x.any(dim=1, keepdim=True)
self.assertEqual(r3.shape, r4.shape)
self.assertTrue((r3 == r4).all())
test(torch.ByteTensor([[0, 0, 0],
[0, 0, 1],
[0, 1, 1],
[1, 1, 1]]))
def test_mv(self):
def _test_mv(m1, v1):
res1 = torch.mv(m1, v1)
res2 = res1.clone().zero_()
for i, j in iter_indices(m1):
res2[i] += m1[i][j] * v1[j]
self.assertEqual(res1, res2)
_test_mv(torch.randn(100, 100, dtype=torch.float32), torch.randn(100, dtype=torch.float32))
_test_mv(torch.randn(100, 100, dtype=torch.float64), torch.randn(100, dtype=torch.float64))
_test_mv(torch.randint(0, 100, (100, 100), dtype=torch.int32), torch.randint(0, 100, (100, ), dtype=torch.int32))
_test_mv(torch.randint(0, 100, (100, 100), dtype=torch.int64), torch.randint(0, 100, (100, ), dtype=torch.int64))
_test_mv(torch.randn(100, 100, dtype=torch.float32).bfloat16(), torch.randn(100, dtype=torch.float32).bfloat16())
def test_numpy_args(self):
x1 = torch.randn(10)
x2 = torch.randn(10)
res1 = torch.add(input=x1, other=x2)
res2 = torch.add(x1=x1, x2=x2)
self.assertEqual(res1, res2)
x1 = torch.randn(10, 10, 10)
res1 = x1.sum(dim=(0, 2), keepdim=True)
res2 = x1.sum(axis=(0, 2), keepdims=True)
self.assertEqual(res1, res2)
def _assert_matches_numpy(self, t, n):
self.assertEqual(n.shape, t.shape)
if t.dtype == torch.float:
self.assertTrue(np.allclose(n, t.numpy(), rtol=1e-03, atol=1e-05,
equal_nan=True))
else:
self.assertTrue(np.allclose(n, t.numpy(), equal_nan=True))
def _test_dim_ops(self, pytorch_op, numpy_op,
use_floating=True, use_integral=True):
def do_one(tensors_dict, dim):
for category, tensors in tensors_dict.items():
if category == "slice":
dim = 0
for tensor in tensors:
# we have no control over NumPy warnings...
with warnings.catch_warnings():
warnings.simplefilter("ignore")
expected = numpy_op(tensor.numpy(), dim)
actual = pytorch_op(tensor, dim)
self._assert_matches_numpy(actual, expected)
if torch.cuda.is_available():
self._assert_matches_numpy(pytorch_op(tensor.cuda(),
dim).cpu(),
expected)
do_one(self._make_tensors((5, 400000), use_floating=use_floating,
use_integral=use_integral), 1)
do_one(self._make_tensors((3, 5, 7), use_floating=use_floating,
use_integral=use_integral), 0)
do_one(self._make_tensors((3, 5, 7), use_floating=use_floating,
use_integral=use_integral), 1)
do_one(self._make_tensors((3, 5, 7), use_floating=use_floating,
use_integral=use_integral), 2)
do_one(self._make_tensors((100000, ), use_floating=use_floating,
use_integral=use_integral), -1)
do_one(self._make_tensors((50, 50, 50), use_floating=use_floating,
use_integral=use_integral), 0)
do_one(self._make_tensors((50, 50, 50), use_floating=use_floating,
use_integral=use_integral), 1)
do_one(self._make_tensors((50, 50, 50), use_floating=use_floating,
use_integral=use_integral), 2)
do_one(self._make_tensors((50, 50, 50), use_floating=use_floating,
use_integral=use_integral), (1, 2))
do_one(self._make_tensors((50, 50, 50), use_floating=use_floating,
use_integral=use_integral), (1, -1))
do_one(self._make_tensors((50, 50, 50), use_floating=use_floating,
use_integral=use_integral), (0, 2))
do_one(self._make_tensors((50, 50, 50), use_floating=use_floating,
use_integral=use_integral), (0, 2, 1))
@slowTest
@unittest.skipIf(not TEST_NUMPY, 'Numpy not found')
def test_sum_dim(self):
self._test_dim_ops(
lambda t, d: t.sum(d),
lambda n, d: n.sum(d))
@unittest.skipIf(not TEST_NUMPY, 'Numpy not found')
def test_mean_dim(self):
self._test_dim_ops(
lambda t, d: t.mean(d),
lambda n, d: n.mean(d),
use_integral=False)
@unittest.skipIf(not TEST_NUMPY, 'Numpy not found')
def test_std_dim(self):
for unbiased in [False, True]:
self._test_dim_ops(
lambda t, d: t.std(d, unbiased=unbiased),
lambda n, d: n.std(d, ddof=1 if unbiased else 0),
use_integral=False)
@unittest.skipIf(not TEST_NUMPY, 'Numpy not found')
def test_var_dim(self):
for unbiased in [False, True]:
self._test_dim_ops(
lambda t, d: t.var(d, unbiased=unbiased),
lambda n, d: n.var(d, ddof=1 if unbiased else 0),
use_integral=False)
@unittest.skipIf(not TEST_NUMPY, 'Numpy not found')
@unittest.skipIf(not TEST_SCIPY, 'Scipy not found')
def test_logsumexp_dim(self):
from scipy.special import logsumexp
self._test_dim_ops(
lambda t, d: t.logsumexp(d),
lambda n, d: logsumexp(n, d),
use_integral=False)
def _test_reduce_integer_upcast(self, fn, has_out=True):
shape = (3, 4, 5)
reduced_shape = fn(torch.ones(shape)).shape
def _test_out(dtype, other_dtype):
out = torch.ones(reduced_shape, dtype=dtype)
result = fn(x, out=out)
self.assertIs(out.dtype, result.dtype)
self.assertEqual(fn(x.type(dtype)), result)
result = fn(x, out=out, dtype=dtype)
self.assertIs(out.dtype, result.dtype)
self.assertEqual(fn(x.type(dtype)), result)
# 'out' is favored over dtype, check error
self.assertRaises(RuntimeError, lambda: fn(x, out=out, dtype=other_dtype))
for dtype in [dtype for dtype in torch.testing.get_all_math_dtypes('cpu') if dtype != torch.float16]:
x = torch.ones(shape, dtype=dtype)
expected_dtype = dtype if dtype.is_floating_point else torch.int64
self.assertIs(expected_dtype, fn(x).dtype)
self.assertEqual(fn(x.type(expected_dtype)), fn(x))
if dtype.is_floating_point:
other_dtype = torch.float32 if dtype == torch.float64 else torch.float64
else:
other_dtype = torch.int32 if dtype != torch.int32 else torch.int16
self.assertIs(other_dtype, fn(x, dtype=other_dtype).dtype)
self.assertEqual(fn(x.type(other_dtype)), fn(x, dtype=other_dtype))
# test mixed int/float
mixed_dtype = torch.int32 if dtype.is_floating_point else torch.float32
self.assertIs(mixed_dtype, fn(x, dtype=mixed_dtype).dtype)
self.assertEqual(fn(x.type(mixed_dtype)), fn(x, dtype=mixed_dtype))
if has_out:
_test_out(dtype, other_dtype)
_test_out(dtype, mixed_dtype)
def test_sum_integer_upcast(self):
self._test_reduce_integer_upcast(lambda x, **kwargs: torch.sum(x, **kwargs), False)
self._test_reduce_integer_upcast(lambda x, **kwargs: torch.sum(x, 0, **kwargs))
def test_prod_integer_upcast(self):
self._test_reduce_integer_upcast(lambda x, **kwargs: torch.prod(x, **kwargs), False)
self._test_reduce_integer_upcast(lambda x, **kwargs: torch.prod(x, 0, **kwargs))
def test_cumsum_integer_upcast(self):
self._test_reduce_integer_upcast(lambda x, **kwargs: torch.cumsum(x, 0, **kwargs))
def test_cumprod_integer_upcast(self):
self._test_reduce_integer_upcast(lambda x, **kwargs: torch.cumprod(x, 0, **kwargs))
def test_cross_validation(self):
self.assertRaisesRegex(
RuntimeError, "inconsistent tensors dimensions",
lambda: torch.cross(torch.rand(100, 3), torch.rand(100, 3, 10)))
self.assertRaisesRegex(
RuntimeError, "inconsistent tensors sizes",
lambda: torch.cross(torch.rand(5, 3), torch.rand(3, 5)))
self.assertRaisesRegex(
RuntimeError, "no dimension of size 3 in input",
lambda: torch.cross(torch.rand(5, 4), torch.rand(5, 4)))
self.assertRaisesRegex(
RuntimeError, "dimension 0 does not have size 3",
lambda: torch.cross(torch.rand(5, 4, 3), torch.rand(5, 4, 3), dim=0))
self.assertRaisesRegex(
RuntimeError, "dimension -1 does not have size 3",
lambda: torch.cross(torch.rand(5, 3, 4), torch.rand(5, 3, 4), dim=-1))
self.assertRaisesRegex(
IndexError, "Dimension out of range",
lambda: torch.cross(torch.rand(5, 3, 4), torch.rand(5, 3, 4), dim=-5))
def test_zeros(self):
res1 = torch.zeros(100, 100)
res2 = torch.Tensor()
torch.zeros(100, 100, out=res2)
self.assertEqual(res1, res2)
boolTensor = torch.zeros(2, 2, dtype=torch.bool)
expected = torch.tensor([[False, False], [False, False]], dtype=torch.bool)
self.assertEqual(boolTensor, expected)
halfTensor = torch.zeros(1, 1, dtype=torch.half)
expected = torch.tensor([[0.]], dtype=torch.float16)
self.assertEqual(halfTensor, expected)
bfloat16Tensor = torch.zeros(1, 1, dtype=torch.bfloat16)
expected = torch.tensor([[0.]], dtype=torch.bfloat16)
self.assertEqual(bfloat16Tensor, expected)
def test_zeros_out(self):
shape = (3, 4)
out = torch.zeros(shape)
torch.zeros(shape, out=out)
# change the dtype, layout, device
self.assertRaises(RuntimeError, lambda: torch.zeros(shape, dtype=torch.int64, out=out))
self.assertRaises(RuntimeError, lambda: torch.zeros(shape, layout=torch.sparse_coo, out=out))
if torch.cuda.is_available():
self.assertRaises(RuntimeError, lambda: torch.zeros(shape, device='cuda', out=out))
# leave them the same
self.assertEqual(torch.zeros(shape), torch.zeros(shape, dtype=out.dtype, out=out))
self.assertEqual(torch.zeros(shape), torch.zeros(shape, layout=torch.strided, out=out))
self.assertEqual(torch.zeros(shape), torch.zeros(shape, device='cpu', out=out))
def test_ones(self):
res1 = torch.ones(100, 100)
res2 = torch.Tensor()
torch.ones(100, 100, out=res2)
self.assertEqual(res1, res2)
# test boolean tensor
res1 = torch.ones(1, 2, dtype=torch.bool)
expected = torch.tensor([[True, True]], dtype=torch.bool)
self.assertEqual(res1, expected)
def test_ones_like(self):
expected = torch.ones(100, 100)
res1 = torch.ones_like(expected)
self.assertEqual(res1, expected)
# test boolean tensor
expected = torch.tensor([True, True], dtype=torch.bool)
res1 = torch.ones_like(expected)
self.assertEqual(res1, expected)
def test_dtypes(self):
all_dtypes = torch.testing.get_all_dtypes()
do_test_dtypes(self, all_dtypes, torch.strided, torch.device('cpu'))
if torch.cuda.is_available():
all_dtypes.remove(torch.bfloat16) # Remove once _th_zero_ is enabled on cuda for bfloat16
do_test_dtypes(self, all_dtypes, torch.strided, torch.device('cuda:0'))
def test_copy_dtypes(self):
all_dtypes = torch.testing.get_all_dtypes()
for dtype in all_dtypes:
copied_dtype = copy.deepcopy(dtype)
self.assertIs(dtype, copied_dtype)
def test_copy_transpose(self):
x = torch.arange(100 * 100, dtype=torch.float).reshape(100, 100).t()
y = torch.empty(100, 100, dtype=torch.float)
y.copy_(x)
self.assertEqual(y[:, 0], range(100))
self.assertEqual(y[:, 40], range(4000, 4100))
y = torch.empty(100, 100, dtype=torch.double)
y.copy_(x)
self.assertEqual(y[:, 0], range(100))
self.assertEqual(y[:, 40], range(4000, 4100))
def test_device(self):
cpu = torch.device('cpu')
self.assertEqual('cpu', str(cpu))
self.assertEqual('cpu', cpu.type)
self.assertEqual(None, cpu.index)
cpu0 = torch.device('cpu:0')
self.assertEqual('cpu:0', str(cpu0))
self.assertEqual('cpu', cpu0.type)
self.assertEqual(0, cpu0.index)
cpu0 = torch.device('cpu', 0)
self.assertEqual('cpu:0', str(cpu0))
self.assertEqual('cpu', cpu0.type)
self.assertEqual(0, cpu0.index)
cuda = torch.device('cuda')
self.assertEqual('cuda', str(cuda))
self.assertEqual('cuda', cuda.type)
self.assertEqual(None, cuda.index)
cuda1 = torch.device('cuda:1')
self.assertEqual('cuda:1', str(cuda1))
self.assertEqual('cuda', cuda1.type)
self.assertEqual(1, cuda1.index)
cuda1 = torch.device('cuda', 1)
self.assertEqual('cuda:1', str(cuda1))
self.assertEqual('cuda', cuda1.type)
self.assertEqual(1, cuda1.index)
self.assertRaises(RuntimeError, lambda: torch.device('cpu:-1'))
self.assertRaises(RuntimeError, lambda: torch.device('cpu:1'))
self.assertRaises(RuntimeError, lambda: torch.device('cpu', -1))
self.assertRaises(RuntimeError, lambda: torch.device('cpu', 1))
self.assertRaises(RuntimeError, lambda: torch.device('cuda:-1'))
self.assertRaises(RuntimeError, lambda: torch.device('cuda', -1))
self.assertRaises(RuntimeError, lambda: torch.device(-1))
self.assertRaises(RuntimeError, lambda: torch.device('other'))
self.assertRaises(RuntimeError, lambda: torch.device('other:0'))
device_set = {'cpu', 'cpu:0', 'cuda', 'cuda:0', 'cuda:1', 'cuda:10', 'cuda:100'}
device_hash_set = set()
for device in list(device_set):
device_hash_set.add(hash(torch.device(device)))
self.assertEqual(len(device_set), len(device_hash_set))
def test_tensor_device(self):
def assertEqual(device_str, fn):
self.assertEqual(torch.device(device_str), fn().device)
self.assertEqual(device_str, str(fn().device))
assertEqual('cpu', lambda: torch.tensor(5))
assertEqual('cpu', lambda: torch.ones((2, 3), dtype=torch.float32, device='cpu'))
# NOTE: 'cpu' is the canonical representation of 'cpu:0', but 'cuda:X' is the canonical
# representation of cuda devices.
assertEqual('cpu', lambda: torch.ones((2, 3), dtype=torch.float32, device='cpu:0'))
assertEqual('cpu', lambda: torch.tensor(torch.ones((2, 3), dtype=torch.float32), device='cpu:0'))
if TEST_NUMPY:
assertEqual('cpu', lambda: torch.tensor(np.random.randn(2, 3), device='cpu'))
if torch.cuda.is_available():
assertEqual('cuda:0', lambda: torch.tensor(5).cuda(0))
assertEqual('cuda:0', lambda: torch.tensor(5).cuda('cuda:0'))
self.assertRaises(RuntimeError, lambda: torch.tensor(5).cuda('cpu'))
self.assertRaises(RuntimeError, lambda: torch.tensor(5).cuda('cpu:0'))
assertEqual('cuda:0', lambda: torch.tensor(5, dtype=torch.int64, device=0))
assertEqual('cuda:0', lambda: torch.tensor(5, dtype=torch.int64, device='cuda:0'))
assertEqual('cuda:' + str(torch.cuda.current_device()),
lambda: torch.tensor(5, dtype=torch.int64, device='cuda'))
assertEqual('cuda:0', lambda: torch.tensor(torch.ones((2, 3), dtype=torch.float32), device='cuda:0'))
if TEST_NUMPY:
assertEqual('cuda:0', lambda: torch.tensor(np.random.randn(2, 3), device='cuda:0'))
if torch.cuda.device_count() > 1:
assertEqual('cuda:1', lambda: torch.tensor(5).cuda(1))
assertEqual('cuda:1', lambda: torch.tensor(5).cuda('cuda:1'))
assertEqual('cuda:1', lambda: torch.tensor(5, dtype=torch.int64, device=1))
assertEqual('cuda:1', lambda: torch.tensor(5, dtype=torch.int64, device='cuda:1'))
assertEqual('cuda:1', lambda: torch.tensor(torch.ones((2, 3), dtype=torch.float32), device='cuda:1'))
if TEST_NUMPY:
assertEqual('cuda:1', lambda: torch.tensor(np.random.randn(2, 3), device='cuda:1'))
def test_to(self):
def test_copy_behavior(t, non_blocking=False):
self.assertIs(t, t.to(t, non_blocking=non_blocking))
self.assertIs(t, t.to(t.dtype, non_blocking=non_blocking))
self.assertIs(t, t.to(torch.empty_like(t), non_blocking=non_blocking))
self.assertIsNot(t, t.to(t, non_blocking=non_blocking, copy=True))
self.assertIsNot(t, t.to(t.dtype, non_blocking=non_blocking, copy=True))
self.assertIsNot(t, t.to(torch.empty_like(t), non_blocking=non_blocking, copy=True))
devices = [t.device]
if t.device.type == 'cuda':
if t.device.index == -1:
devices.append('cuda:{}'.format(torch.cuda.current_device()))
elif t.device.index == torch.cuda.current_device():
devices.append('cuda')
for device in devices:
self.assertIs(t, t.to(device, non_blocking=non_blocking))
self.assertIs(t, t.to(device, t.dtype, non_blocking=non_blocking))
self.assertIsNot(t, t.to(device, non_blocking=non_blocking, copy=True))
self.assertIsNot(t, t.to(device, t.dtype, non_blocking=non_blocking, copy=True))
a = torch.tensor(5)
test_copy_behavior(a)
self.assertEqual(a.device, a.to('cpu').device)
self.assertEqual(a.device, a.to('cpu', dtype=torch.float32).device)
self.assertIs(torch.float32, a.to('cpu', dtype=torch.float32).dtype)
self.assertEqual(a.device, a.to(torch.float32).device)
self.assertIs(torch.float32, a.to(dtype=torch.float32).dtype)
self.assertEqual(a.data_ptr(), a.to('cpu').data_ptr())
self.assertEqual(a.data_ptr(), a.to(dtype=a.dtype, device=a.device, copy=False).data_ptr())
self.assertEqual(a.data_ptr(), a.to('cpu', copy=False).data_ptr())
self.assertNotEqual(a.data_ptr(), a.to('cpu', copy=True).data_ptr())
if torch.cuda.is_available():
for non_blocking in [True, False]:
for cuda in ['cuda', 'cuda:0' if torch.cuda.device_count() == 1 else 'cuda:1']:
b = torch.tensor(5., device=cuda)
test_copy_behavior(b, non_blocking)
self.assertEqual(b.device, b.to(cuda, non_blocking=non_blocking).device)
self.assertEqual(a.device, b.to('cpu', non_blocking=non_blocking).device)
self.assertEqual(b.device, a.to(cuda, non_blocking=non_blocking).device)
self.assertIs(torch.int32, b.to('cpu', dtype=torch.int32, non_blocking=non_blocking).dtype)
self.assertEqual(a.device, b.to('cpu', dtype=torch.int32, non_blocking=non_blocking).device)
self.assertIs(torch.int32, b.to(dtype=torch.int32).dtype)
self.assertEqual(b.device, b.to(dtype=torch.int32).device)
def test_to_with_tensor(self):
a = torch.tensor(5)
self.assertEqual(a.device, a.to(a).device)
if torch.cuda.is_available():
for non_blocking in [True, False]:
for cuda in ['cuda', 'cuda:0' if torch.cuda.device_count() == 1 else 'cuda:1']:
b = torch.tensor(5., device=cuda)
self.assertEqual(b.device, b.to(b, non_blocking=non_blocking).device)
self.assertEqual(a.device, b.to(a, non_blocking=non_blocking).device)
self.assertEqual(b.device, a.to(b, non_blocking=non_blocking).device)
def test_empty_full(self):
do_test_empty_full(self, torch.testing.get_all_math_dtypes('cpu'), torch.strided, torch.device('cpu'))
if torch.cuda.device_count() > 0:
do_test_empty_full(self, torch.testing.get_all_math_dtypes('cpu'), torch.strided, None)
do_test_empty_full(self, torch.testing.get_all_math_dtypes('cpu'), torch.strided, torch.device('cuda:0'))
def test_dtype_out_match(self):
d = torch.autograd.Variable(torch.DoubleTensor(2, 3))
self.assertRaises(RuntimeError, lambda: torch.zeros((2, 3), out=d, dtype=torch.float32))
def test_constructor_dtypes(self):
default_type = torch.Tensor().type()
self.assertIs(torch.Tensor().dtype, torch.get_default_dtype())
self.assertIs(torch.uint8, torch.ByteTensor.dtype)
self.assertIs(torch.float32, torch.FloatTensor.dtype)
self.assertIs(torch.float64, torch.DoubleTensor.dtype)
torch.set_default_tensor_type('torch.FloatTensor')
self.assertIs(torch.float32, torch.get_default_dtype())
self.assertIs(torch.FloatStorage, torch.Storage)
torch.set_default_dtype(torch.float64)
self.assertIs(torch.float64, torch.get_default_dtype())
self.assertIs(torch.DoubleStorage, torch.Storage)
torch.set_default_tensor_type(torch.FloatTensor)
self.assertIs(torch.float32, torch.get_default_dtype())
self.assertIs(torch.FloatStorage, torch.Storage)
if torch.cuda.is_available():
torch.set_default_tensor_type(torch.cuda.FloatTensor)
self.assertIs(torch.float32, torch.get_default_dtype())
self.assertIs(torch.float32, torch.cuda.FloatTensor.dtype)
self.assertIs(torch.cuda.FloatStorage, torch.Storage)
torch.set_default_dtype(torch.float64)
self.assertIs(torch.float64, torch.get_default_dtype())
self.assertIs(torch.cuda.DoubleStorage, torch.Storage)
# don't support integral or sparse default types.
self.assertRaises(TypeError, lambda: torch.set_default_tensor_type('torch.IntTensor'))
self.assertRaises(TypeError, lambda: torch.set_default_dtype(torch.int64))
# don't allow passing dtype to set_default_tensor_type
self.assertRaises(TypeError, lambda: torch.set_default_tensor_type(torch.float32))
torch.set_default_tensor_type(default_type)
def test_constructor_device_legacy(self):
self.assertRaises(RuntimeError, lambda: torch.FloatTensor(device='cuda'))
self.assertRaises(RuntimeError, lambda: torch.FloatTensor(torch.Size([2, 3, 4]), device='cuda'))
self.assertRaises(RuntimeError, lambda: torch.FloatTensor((2.0, 3.0), device='cuda'))
self.assertRaises(RuntimeError, lambda: torch.Tensor(device='cuda'))
self.assertRaises(RuntimeError, lambda: torch.Tensor(torch.Size([2, 3, 4]), device='cuda'))
self.assertRaises(RuntimeError, lambda: torch.Tensor((2.0, 3.0), device='cuda'))
x = torch.randn((3,), device='cpu')
self.assertRaises(RuntimeError, lambda: x.new(device='cuda'))
self.assertRaises(RuntimeError, lambda: x.new(torch.Size([2, 3, 4]), device='cuda'))
self.assertRaises(RuntimeError, lambda: x.new((2.0, 3.0), device='cuda'))
if torch.cuda.is_available():
self.assertRaises(RuntimeError, lambda: torch.cuda.FloatTensor(device='cpu'))
self.assertRaises(RuntimeError, lambda: torch.cuda.FloatTensor(torch.Size([2, 3, 4]), device='cpu'))
self.assertRaises(RuntimeError, lambda: torch.cuda.FloatTensor((2.0, 3.0), device='cpu'))
default_type = torch.Tensor().type()
torch.set_default_tensor_type(torch.cuda.FloatTensor)
self.assertRaises(RuntimeError, lambda: torch.Tensor(device='cpu'))
self.assertRaises(RuntimeError, lambda: torch.Tensor(torch.Size([2, 3, 4]), device='cpu'))
self.assertRaises(RuntimeError, lambda: torch.Tensor((2.0, 3.0), device='cpu'))
torch.set_default_tensor_type(torch.cuda.FloatTensor)
torch.set_default_tensor_type(default_type)
x = torch.randn((3,), device='cuda')
self.assertRaises(RuntimeError, lambda: x.new(device='cpu'))
self.assertRaises(RuntimeError, lambda: x.new(torch.Size([2, 3, 4]), device='cpu'))
self.assertRaises(RuntimeError, lambda: x.new((2.0, 3.0), device='cpu'))
def test_type(self):
x = torch.randn(3, 3).double()
self.assertEqual(x.type('torch.FloatTensor').dtype, torch.float32)
self.assertEqual(x.type(torch.FloatTensor).dtype, torch.float32)
self.assertEqual(x.int().type(torch.Tensor).dtype, torch.get_default_dtype())
self.assertEqual(x.type(torch.int32).dtype, torch.int32)
def test_tensor_factory(self):
expected = torch.Tensor([1, 1])
# test data
res1 = torch.tensor([1, 1])
self.assertEqual(res1, expected)
res1 = torch.tensor([1, 1], dtype=torch.int)
self.assertEqual(res1, expected)
self.assertIs(torch.int, res1.dtype)
# test copy
res2 = torch.tensor(expected)
self.assertEqual(res2, expected)
res2[1] = 2
self.assertEqual(expected, torch.ones_like(expected))
res2 = torch.tensor(expected, dtype=torch.int)
self.assertEqual(res1, expected)
self.assertIs(torch.int, res1.dtype)
# test copy with numpy
if TEST_NUMPY:
for dtype in [np.float64, np.int64, np.int8, np.uint8]:
a = np.array([5.]).astype(dtype)
res1 = torch.tensor(a)
self.assertEqual(5., res1[0].item())
a[0] = 7.
self.assertEqual(5., res1[0].item())
# test boolean tensor
a = torch.tensor([True, True, False, True, True], dtype=torch.bool)
b = torch.tensor([-1, -1.1, 0, 1, 1.1], dtype=torch.bool)
self.assertEqual(a, b)
def test_tensor_factory_copy_var(self):
def check_copy(copy, is_leaf, requires_grad, data_ptr=None):
if data_ptr is None:
data_ptr = copy.data_ptr
self.assertEqual(copy.data, source.data)
self.assertTrue(copy.is_leaf == is_leaf)
self.assertTrue(copy.requires_grad == requires_grad)
self.assertTrue(copy.data_ptr == data_ptr)
source = torch.randn(5, 5, dtype=torch.double, requires_grad=True)
# test torch.tensor()
check_copy(torch.tensor(source), True, False)
check_copy(torch.tensor(source, requires_grad=False), True, False)
check_copy(torch.tensor(source, requires_grad=True), True, True)
# test tensor.new_tensor()
copy = torch.randn(1)
check_copy(copy.new_tensor(source), True, False)
check_copy(copy.new_tensor(source, requires_grad=False), True, False)
check_copy(copy.new_tensor(source, requires_grad=True), True, True)
# test torch.as_tensor()
check_copy(torch.as_tensor(source), source.is_leaf, source.requires_grad, source.data_ptr) # not copy
check_copy(torch.as_tensor(source, dtype=torch.float), False, True) # copy and keep the graph
def test_tensor_factory_type_inference(self):
def test_inference(default_dtype):
saved_dtype = torch.get_default_dtype()
torch.set_default_dtype(default_dtype)
self.assertIs(default_dtype, torch.tensor(()).dtype)
self.assertIs(default_dtype, torch.tensor(5.).dtype)
self.assertIs(torch.int64, torch.tensor(5).dtype)
self.assertIs(torch.bool, torch.tensor(True).dtype)
self.assertIs(torch.int32, torch.tensor(5, dtype=torch.int32).dtype)
self.assertIs(default_dtype, torch.tensor(((7, 5), (9, 5.))).dtype)
self.assertIs(default_dtype, torch.tensor(((5., 5), (3, 5))).dtype)
self.assertIs(torch.int64, torch.tensor(((5, 3), (3, 5))).dtype)
if TEST_NUMPY:
self.assertIs(torch.float64, torch.tensor(np.array(())).dtype)
self.assertIs(torch.float64, torch.tensor(np.array(5.)).dtype)
if np.array(5).dtype == np.int64: # np long, which can be 4 bytes (e.g. on windows)
self.assertIs(torch.int64, torch.tensor(np.array(5)).dtype)
else:
self.assertIs(torch.int32, torch.tensor(np.array(5)).dtype)
self.assertIs(torch.uint8, torch.tensor(np.array(3, dtype=np.uint8)).dtype)
self.assertIs(default_dtype, torch.tensor(((7, np.array(5)), (np.array(9), 5.))).dtype)
self.assertIs(torch.float64, torch.tensor(((7, 5), (9, np.array(5.)))).dtype)
self.assertIs(torch.int64, torch.tensor(((5, np.array(3)), (np.array(3), 5))).dtype)
torch.set_default_dtype(saved_dtype)
test_inference(torch.float64)
test_inference(torch.float32)
def test_qengine(self):
qengines = torch.backends.quantized.supported_engines
original_qe = torch.backends.quantized.engine
for qe in qengines:
torch.backends.quantized.engine = qe
assert torch.backends.quantized.engine == qe, 'qengine not set successfully'
torch.backends.quantized.engine = original_qe
def test_new_tensor(self):
expected = torch.autograd.Variable(torch.ByteTensor([1, 1]))
# test data
res1 = expected.new_tensor([1, 1])
self.assertEqual(res1, expected)
res1 = expected.new_tensor([1, 1], dtype=torch.int)
self.assertEqual(res1, expected)
self.assertIs(torch.int, res1.dtype)
# test copy
res2 = expected.new_tensor(expected)
self.assertEqual(res2, expected)
res2[1] = 2
self.assertEqual(expected, torch.ones_like(expected))
res2 = expected.new_tensor(expected, dtype=torch.int)
self.assertEqual(res2, expected)
self.assertIs(torch.int, res2.dtype)
# test copy with numpy
if TEST_NUMPY:
a = np.array([5.])
res1 = torch.tensor(a)
res1 = res1.new_tensor(a)
self.assertEqual(5., res1[0].item())
a[0] = 7.
self.assertEqual(5., res1[0].item())
if torch.cuda.device_count() >= 2:
expected = expected.cuda(1)
res1 = expected.new_tensor([1, 1])
self.assertEqual(res1.get_device(), expected.get_device())
res1 = expected.new_tensor([1, 1], dtype=torch.int)
self.assertIs(torch.int, res1.dtype)
self.assertEqual(res1.get_device(), expected.get_device())
res2 = expected.new_tensor(expected)
self.assertEqual(res2.get_device(), expected.get_device())
res2 = expected.new_tensor(expected, dtype=torch.int)
self.assertIs(torch.int, res1.dtype)
self.assertEqual(res2.get_device(), expected.get_device())
res2 = expected.new_tensor(expected, dtype=torch.int, device=0)
self.assertIs(torch.int, res1.dtype)
self.assertEqual(res2.get_device(), 0)
res1 = expected.new_tensor(1)
self.assertEqual(res1.get_device(), expected.get_device())
res1 = expected.new_tensor(1, dtype=torch.int)
self.assertIs(torch.int, res1.dtype)
self.assertEqual(res1.get_device(), expected.get_device())
def test_as_tensor(self):
# from python data
x = [[0, 1], [2, 3]]
self.assertEqual(torch.tensor(x), torch.as_tensor(x))
self.assertEqual(torch.tensor(x, dtype=torch.float32), torch.as_tensor(x, dtype=torch.float32))
# python data with heterogeneous types
z = [0, 'torch']
with self.assertRaisesRegex(TypeError, "invalid data type"):
torch.tensor(z)
torch.as_tensor(z)
# python data with self-referential lists
z = [0]
z += [z]
with self.assertRaisesRegex(TypeError, "self-referential lists are incompatible"):
torch.tensor(z)
torch.as_tensor(z)
z = [[1, 2], z]
with self.assertRaisesRegex(TypeError, "self-referential lists are incompatible"):
torch.tensor(z)
torch.as_tensor(z)
# from tensor (doesn't copy unless type is different)
y = torch.tensor(x)
self.assertIs(y, torch.as_tensor(y))
self.assertIsNot(y, torch.as_tensor(y, dtype=torch.float32))
if torch.cuda.is_available():
self.assertIsNot(y, torch.as_tensor(y, device='cuda'))
y_cuda = y.to('cuda')
self.assertIs(y_cuda, torch.as_tensor(y_cuda))
self.assertIs(y_cuda, torch.as_tensor(y_cuda, device='cuda'))
if TEST_NUMPY:
# doesn't copy
for dtype in [np.float64, np.int64, np.int8, np.uint8]:
n = np.random.rand(5, 6).astype(dtype)
n_astensor = torch.as_tensor(n)
self.assertEqual(torch.tensor(n), n_astensor)
n_astensor[0][0] = 25.7
self.assertEqual(torch.tensor(n), n_astensor)
# changing dtype causes copy
n = np.random.rand(5, 6).astype(np.float32)
n_astensor = torch.as_tensor(n, dtype=torch.float64)
self.assertEqual(torch.tensor(n, dtype=torch.float64), n_astensor)
n_astensor[0][1] = 250.8
self.assertNotEqual(torch.tensor(n, dtype=torch.float64), n_astensor)
# changing device causes copy
if torch.cuda.is_available():
n = np.random.randn(5, 6)
n_astensor = torch.as_tensor(n, device='cuda')
self.assertEqual(torch.tensor(n, device='cuda'), n_astensor)
n_astensor[0][2] = 250.9
self.assertNotEqual(torch.tensor(n, device='cuda'), n_astensor)
def test_renorm(self):
m1 = torch.randn(10, 5)
res1 = torch.Tensor()
def renorm(matrix, value, dim, max_norm):
m1 = matrix.transpose(dim, 0).contiguous()
# collapse non-dim dimensions.
m2 = m1.clone().resize_(m1.size(0), int(math.floor(m1.nelement() / m1.size(0))))
norms = m2.norm(value, 1, True)
# clip
new_norms = norms.clone()
new_norms[torch.gt(norms, max_norm)] = max_norm
new_norms.div_(norms.add_(1e-7))
# renormalize
m1.mul_(new_norms.expand_as(m1))
return m1.transpose(dim, 0)
# note that the axis fed to torch.renorm is different (2~=1)
maxnorm = m1.norm(2, 1).mean()
m2 = renorm(m1, 2, 1, maxnorm)
m1.renorm_(2, 1, maxnorm)
self.assertEqual(m1, m2, 1e-5)
self.assertEqual(m1.norm(2, 0), m2.norm(2, 0), 1e-5)
m1 = torch.randn(3, 4, 5)
m2 = m1.transpose(1, 2).contiguous().clone().resize_(15, 4)
maxnorm = m2.norm(2, 0).mean()
m2 = renorm(m2, 2, 1, maxnorm)
m1.renorm_(2, 1, maxnorm)
m3 = m1.transpose(1, 2).contiguous().clone().resize_(15, 4)
self.assertEqual(m3, m2)
self.assertEqual(m3.norm(2, 0), m2.norm(2, 0))
def _spawn_method(self, method, arg):
try:
mp.set_start_method('spawn')
except RuntimeError:
pass
with mp.Pool(1) as pool:
self.assertTrue(pool.map(method, [arg]))
@staticmethod
def _test_multinomial_invalid_probs(probs):
try:
# n_sample = 1 is a special case, test n_sample=2 which is more general
torch.multinomial(probs.to('cpu'), 2)
return False # Should not be reached
except RuntimeError as e:
return 'invalid multinomial distribution' in str(e)
@unittest.skipIf(NO_MULTIPROCESSING_SPAWN, "Disabled for environments that \
don't support multiprocessing with spawn start method")
@unittest.skipIf(IS_WINDOWS, 'FIXME: CUDA OOM error on Windows')
@unittest.skipIf(not PY3,
"spawn start method is not supported in Python 2, \
but we need it for for testing failure case for CPU RNG on Windows")
def test_multinomial_invalid_probs(self):
test_method = _TestTorchMixin._test_multinomial_invalid_probs
self._spawn_method(test_method, torch.Tensor([1, -1, 1]))
self._spawn_method(test_method, torch.Tensor([1, inf, 1]))
self._spawn_method(test_method, torch.Tensor([1, -inf, 1]))
self._spawn_method(test_method, torch.Tensor([1, 1, nan]))
self._spawn_method(test_method, torch.Tensor([0, 1, 0]))
@suppress_warnings
def test_range(self):
res1 = torch.range(0, 1)
res2 = torch.Tensor()
torch.range(0, 1, out=res2)
self.assertEqual(res1, res2, 0)
# Check range for non-contiguous tensors.
x = torch.zeros(2, 3)
torch.range(0, 3, out=x.narrow(1, 1, 2))
res2 = torch.Tensor(((0, 0, 1), (0, 2, 3)))
self.assertEqual(x, res2, 1e-16)
# Check negative
res1 = torch.Tensor((1, 0))
res2 = torch.Tensor()
torch.range(1, 0, -1, out=res2)
self.assertEqual(res1, res2, 0)
# Equal bounds
res1 = torch.ones(1)
res2 = torch.Tensor()
torch.range(1, 1, -1, out=res2)
self.assertEqual(res1, res2, 0)
torch.range(1, 1, 1, out=res2)
self.assertEqual(res1, res2, 0)
# FloatTensor
res1 = torch.range(0.6, 0.9, 0.1, out=torch.FloatTensor())
self.assertEqual(res1.size(0), 4)
res1 = torch.range(1, 10, 0.3, out=torch.FloatTensor())
self.assertEqual(res1.size(0), 31)
# DoubleTensor
res1 = torch.range(0.6, 0.9, 0.1, out=torch.DoubleTensor())
self.assertEqual(res1.size(0), 4)
res1 = torch.range(1, 10, 0.3, out=torch.DoubleTensor())
self.assertEqual(res1.size(0), 31)
def test_range_warning(self):
with warnings.catch_warnings(record=True) as w:
torch.range(0, 10)
self.assertEqual(len(w), 1)
def test_arange(self):
res1 = torch.arange(0, 1)
res2 = torch.Tensor()
torch.arange(0, 1, out=res2)
self.assertEqual(res1, res2, 0)
# Check arange with only one argument
res1 = torch.arange(10)
res2 = torch.arange(0, 10)
self.assertEqual(res1, res2, 0)
# Check arange for non-contiguous tensors.
x = torch.zeros(2, 3)
torch.arange(0, 4, out=x.narrow(1, 1, 2))
res2 = torch.Tensor(((0, 0, 1), (0, 2, 3)))
self.assertEqual(x, res2, 1e-16)
# Check negative
res1 = torch.Tensor((1, 0))
res2 = torch.Tensor()
torch.arange(1, -1, -1, out=res2)
self.assertEqual(res1, res2, 0)
# Equal bounds
res1 = torch.ones(1)
res2 = torch.Tensor()
torch.arange(1, 0, -1, out=res2)
self.assertEqual(res1, res2, 0)
torch.arange(1, 2, 1, out=res2)
self.assertEqual(res1, res2, 0)
# FloatTensor
res1 = torch.arange(0.6, 0.89, 0.1, out=torch.FloatTensor())
self.assertEqual(res1, [0.6, 0.7, 0.8])
res1 = torch.arange(1, 10, 0.3, out=torch.FloatTensor())
self.assertEqual(res1.size(0), 30)
self.assertEqual(res1[0], 1)
self.assertEqual(res1[29], 9.7)
# DoubleTensor
res1 = torch.arange(0.6, 0.89, 0.1, out=torch.DoubleTensor())
self.assertEqual(res1, [0.6, 0.7, 0.8])
res1 = torch.arange(1, 10, 0.3, out=torch.DoubleTensor())
self.assertEqual(res1.size(0), 30)
self.assertEqual(res1[0], 1)
self.assertEqual(res1[29], 9.7)
# Check that it's exclusive
r = torch.arange(0, 5)
self.assertEqual(r.min(), 0)
self.assertEqual(r.max(), 4)
self.assertEqual(r.numel(), 5)
r = torch.arange(0, 5, 2)
self.assertEqual(r.min(), 0)
self.assertEqual(r.max(), 4)
self.assertEqual(r.numel(), 3)
r1 = torch.arange(0, 5 + 1e-6)
r2 = torch.arange(0, 5)
r3 = torch.arange(0, 5 - 1e-6)
self.assertEqual(r1[:-1], r2, 0)
self.assertEqual(r2, r3, 0)
r1 = torch.arange(10, -1 + 1e-6, -1)
r2 = torch.arange(10, -1, -1)
r3 = torch.arange(10, -1 - 1e-6, -1)
self.assertEqual(r1, r2, 0)
self.assertEqual(r2, r3[:-1], 0)
x = torch.empty(1).expand(10)
self.assertRaises(RuntimeError, lambda: torch.arange(10, out=x))
msg = "unsupported range"
self.assertRaisesRegex(RuntimeError, msg, lambda: torch.arange(0, float('inf')))
self.assertRaisesRegex(RuntimeError, msg, lambda: torch.arange(float('inf')))
for device in torch.testing.get_all_device_types():
self.assertRaisesRegex(RuntimeError, msg, lambda: torch.arange(-5, float('nan'), device=device))
# check with step size
self.assertRaisesRegex(RuntimeError, msg, lambda: torch.arange(0, float('-inf'), -1, device=device))
self.assertRaisesRegex(RuntimeError, msg, lambda: torch.arange(0, float('inf'), device=device))
self.assertRaisesRegex(RuntimeError, msg, lambda: torch.arange(float('-inf'), 10, device=device))
self.assertRaisesRegex(RuntimeError, msg, lambda: torch.arange(float('nan'), 10, device=device))
self.assertRaisesRegex(RuntimeError, msg, lambda: torch.arange(float('inf'), device=device))
self.assertRaisesRegex(RuntimeError, msg, lambda: torch.arange(float('nan'), device=device))
self.assertRaisesRegex(
RuntimeError, "overflow",
lambda: torch.arange(1.175494351e-38, 3.402823466e+38, device=device))
# check that it holds a consistent output shape on precision-cornered step sizes
d = torch.arange(-4.0, 4.0, 0.01, dtype=torch.float32, device=device)
self.assertEqual(d.shape[0], 800)
def test_arange_inference(self):
saved_dtype = torch.get_default_dtype()
torch.set_default_dtype(torch.float32)
# end only
self.assertIs(torch.float32, torch.arange(1.).dtype)
self.assertIs(torch.float32, torch.arange(torch.tensor(1.)).dtype)
self.assertIs(torch.float32, torch.arange(torch.tensor(1., dtype=torch.float64)).dtype)
self.assertIs(torch.int64, torch.arange(1).dtype)
self.assertIs(torch.int64, torch.arange(torch.tensor(1)).dtype)
self.assertIs(torch.int64, torch.arange(torch.tensor(1, dtype=torch.int16)).dtype)
# start, end, [step]
self.assertIs(torch.float32, torch.arange(1., 3).dtype)
self.assertIs(torch.float32, torch.arange(torch.tensor(1., dtype=torch.float64), 3).dtype)
self.assertIs(torch.float32, torch.arange(1, 3.).dtype)
self.assertIs(torch.float32, torch.arange(torch.tensor(1, dtype=torch.int16), torch.tensor(3.)).dtype)
self.assertIs(torch.float32, torch.arange(1, 3, 1.).dtype)
self.assertIs(torch.float32,
torch.arange(torch.tensor(1),
torch.tensor(3, dtype=torch.int16),
torch.tensor(1., dtype=torch.float64)).dtype)
self.assertIs(torch.int64, torch.arange(1, 3).dtype)
self.assertIs(torch.int64, torch.arange(torch.tensor(1), 3).dtype)
self.assertIs(torch.int64, torch.arange(torch.tensor(1), torch.tensor(3, dtype=torch.int16)).dtype)
self.assertIs(torch.int64, torch.arange(1, 3, 1).dtype)
self.assertIs(torch.int64,
torch.arange(torch.tensor(1),
torch.tensor(3),
torch.tensor(1, dtype=torch.int16)).dtype)
torch.set_default_dtype(saved_dtype)
def test_randint_inference(self):
size = (2, 1)
for args in [(3,), (1, 3)]: # (low,) and (low, high)
self.assertIs(torch.int64, torch.randint(*args, size=size).dtype)
self.assertIs(torch.int64, torch.randint(*args, size=size, layout=torch.strided).dtype)
self.assertIs(torch.int64, torch.randint(*args, size=size, generator=torch.default_generator).dtype)
self.assertIs(torch.float32, torch.randint(*args, size=size, dtype=torch.float32).dtype)
out = torch.empty(size, dtype=torch.float32)
self.assertIs(torch.float32, torch.randint(*args, size=size, out=out).dtype)
self.assertIs(torch.float32, torch.randint(*args, size=size, out=out, dtype=torch.float32).dtype)
out = torch.empty(size, dtype=torch.int64)
self.assertIs(torch.int64, torch.randint(*args, size=size, out=out).dtype)
self.assertIs(torch.int64, torch.randint(*args, size=size, out=out, dtype=torch.int64).dtype)
def test_broadcast_empty(self):
# empty + empty
self.assertRaises(RuntimeError, lambda: torch.randn(5, 0) + torch.randn(0, 5))
self.assertEqual(torch.randn(5, 0), torch.randn(0) + torch.randn(5, 0))
self.assertEqual(torch.randn(5, 0, 0), torch.randn(0) + torch.randn(5, 0, 1))
# scalar + empty
self.assertEqual(torch.randn(5, 0, 6), torch.randn(()) + torch.randn(5, 0, 6))
# non-empty, empty
self.assertEqual(torch.randn(0), torch.randn(0) + torch.randn(1))
self.assertEqual(torch.randn(0, 7, 0, 6, 5, 0, 7),
torch.randn(0, 7, 0, 6, 5, 0, 1) + torch.randn(1, 1, 5, 1, 7))
self.assertRaises(RuntimeError, lambda: torch.randn(7, 0) + torch.randn(2, 1))
def test_scalars_as_floats(self):
"zero-dim variables that don't require grad should bind to scalar arguments"
x = torch.tensor(2.)
y = torch.tensor(3.)
# 3 + (3 * 3) * 2
self.assertEqual(y.addcmul(y, y, value=x), 21)
x = torch.tensor(2., requires_grad=True)
self.assertRaises(Exception, lambda: y.addcmul(y, y, value=x))
def test_copy_broadcast(self):
torch.zeros(5, 6).copy_(torch.zeros(6))
self.assertRaises(RuntimeError, lambda: torch.zeros(5, 6).copy_(torch.zeros(30)))
def test_copy_many_to_one(self):
# Testing in-place copy where it attempt to write from many memory
# storage to a single storage would cause RuntimeError to be thrown
self.assertRaises(RuntimeError, lambda: torch.zeros(1, 6).expand(5, 6).copy_(torch.zeros(5, 6)))
def test_not_equal(self):
ones = torch.ones(10, dtype=torch.int)
self.assertRaisesRegex(AssertionError, "0 not greater than or equal to",
lambda: self.assertNotEqual(ones, ones))
def assertIsOrdered(self, order, x, mxx, ixx, task):
SIZE = 4
if order == 'descending':
def check_order(a, b):
# `a != a` because we put NaNs
# at the end of ascending sorted lists,
# and the beginning of descending ones.
return a != a or a >= b
elif order == 'ascending':
def check_order(a, b):
# see above
return b != b or a <= b
else:
error('unknown order "{}", must be "ascending" or "descending"'.format(order))
are_ordered = True
for j, k in product(range(SIZE), range(1, SIZE)):
self.assertTrue(check_order(mxx[j][k - 1], mxx[j][k]),
'torch.sort ({}) values unordered for {}'.format(order, task))
seen = set()
indicesCorrect = True
size = x.size(x.dim() - 1)
for k in range(size):
seen.clear()
for j in range(size):
self.assertEqual(x[k][ixx[k][j]], mxx[k][j],
'torch.sort ({}) indices wrong for {}'.format(order, task))
seen.add(ixx[k][j])
self.assertEqual(len(seen), size)
def test_sort(self):
SIZE = 4
x = torch.rand(SIZE, SIZE)
res1val, res1ind = torch.sort(x)
# Test use of result tensor
res2val = torch.Tensor()
res2ind = torch.LongTensor()
torch.sort(x, out=(res2val, res2ind))
self.assertEqual(res1val, res2val, 0)
self.assertEqual(res1ind, res2ind, 0)
self.assertEqual(torch.argsort(x), res1ind)
self.assertEqual(x.argsort(), res1ind)
# Test sorting of random numbers
self.assertIsOrdered('ascending', x, res2val, res2ind, 'random')
# Test simple sort
self.assertEqual(
torch.sort(torch.Tensor((50, 40, 30, 20, 10)))[0],
torch.Tensor((10, 20, 30, 40, 50)),
0
)
# Test that we still have proper sorting with duplicate keys
x = torch.floor(torch.rand(SIZE, SIZE) * 10)
torch.sort(x, out=(res2val, res2ind))
self.assertIsOrdered('ascending', x, res2val, res2ind, 'random with duplicate keys')
# DESCENDING SORT
x = torch.rand(SIZE, SIZE)
res1val, res1ind = torch.sort(x, x.dim() - 1, True)
# Test use of result tensor
res2val = torch.Tensor()
res2ind = torch.LongTensor()
torch.sort(x, x.dim() - 1, True, out=(res2val, res2ind))
self.assertEqual(res1val, res2val, 0)
self.assertEqual(res1ind, res2ind, 0)
self.assertEqual(torch.argsort(x, x.dim() - 1, True), res1ind)
self.assertEqual(x.argsort(x.dim() - 1, True), res1ind)
# Test sorting of random numbers
self.assertIsOrdered('descending', x, res2val, res2ind, 'random')
# Test simple sort task
self.assertEqual(
torch.sort(torch.Tensor((10, 20, 30, 40, 50)), 0, True)[0],
torch.Tensor((50, 40, 30, 20, 10)),
0
)
# Test that we still have proper sorting with duplicate keys
self.assertIsOrdered('descending', x, res2val, res2ind, 'random with duplicate keys')
# Test sorting with NaNs
x = torch.rand(SIZE, SIZE)
x[1][2] = float('NaN')
x[3][0] = float('NaN')
torch.sort(x, out=(res2val, res2ind))
self.assertIsOrdered('ascending', x, res2val, res2ind,
'random with NaNs')
torch.sort(x, out=(res2val, res2ind), descending=True)
self.assertIsOrdered('descending', x, res2val, res2ind,
'random with NaNs')
def test_topk(self):
def topKViaSort(t, k, dim, dir):
sorted, indices = t.sort(dim, dir)
return sorted.narrow(dim, 0, k), indices.narrow(dim, 0, k)
def compareTensors(t, res1, ind1, res2, ind2, dim):
# Values should be exactly equivalent
self.assertEqual(res1, res2, 0)
# Indices might differ based on the implementation, since there is
# no guarantee of the relative order of selection
if not ind1.eq(ind2).all():
# To verify that the indices represent equivalent elements,
# gather from the input using the topk indices and compare against
# the sort indices
vals = t.gather(dim, ind2)
self.assertEqual(res1, vals, 0)
def compare(t, k, dim, dir):
topKVal, topKInd = t.topk(k, dim, dir, True)
sortKVal, sortKInd = topKViaSort(t, k, dim, dir)
compareTensors(t, sortKVal, sortKInd, topKVal, topKInd, dim)
t = torch.rand(random.randint(1, SIZE),
random.randint(1, SIZE),
random.randint(1, SIZE))
for _kTries in range(3):
for _dimTries in range(3):
for transpose in (True, False):
for dir in (True, False):
testTensor = t
if transpose:
dim1 = random.randrange(t.ndimension())
dim2 = dim1
while dim1 == dim2:
dim2 = random.randrange(t.ndimension())
testTensor = t.transpose(dim1, dim2)
dim = random.randrange(testTensor.ndimension())
k = random.randint(1, testTensor.size(dim))
compare(testTensor, k, dim, dir)
def test_topk_arguments(self):
q = torch.randn(10, 2, 10)
# Make sure True isn't mistakenly taken as the 2nd dimension (interpreted as 1)
self.assertRaises(TypeError, lambda: q.topk(4, True))
def test_median(self):
for size in (155, 156):
x = torch.rand(size, size)
x0 = x.clone()
nelem = x.nelement()
res1val = torch.median(x)
res2val, _ = torch.sort(x.view(nelem))
ind = int(math.floor((nelem + 1) / 2) - 1)
self.assertEqual(res2val[ind], res1val, 0)
res1val, res1ind = torch.median(x, dim=1, keepdim=False)
res2val, res2ind = torch.sort(x)
ind = int(math.floor((size + 1) / 2) - 1)
self.assertEqual(res2val.select(1, ind), res1val, 0)
self.assertEqual(res2val.select(1, ind), res1val, 0)
# Test use of result tensor
res2val = torch.Tensor()
res2ind = torch.LongTensor()
torch.median(x, dim=-1, keepdim=False, out=(res2val, res2ind))
self.assertEqual(res2val, res1val, 0)
self.assertEqual(res2ind, res1ind, 0)
# Test non-default dim
res1val, res1ind = torch.median(x, 0, keepdim=False)
res2val, res2ind = torch.sort(x, 0)
self.assertEqual(res1val, res2val[ind], 0)
self.assertEqual(res1ind, res2ind[ind], 0)
# input unchanged
self.assertEqual(x, x0, 0)
def test_mode(self):
x = torch.arange(1., SIZE * SIZE + 1).clone().resize_(SIZE, SIZE)
x[:2] = 1
x[:, :2] = 1
x0 = x.clone()
# Pre-calculated results.
res1val = torch.Tensor(SIZE).fill_(1)
# The indices are the position of the last appearance of the mode element.
res1ind = torch.LongTensor(SIZE).fill_(1)
res1ind[0] = SIZE - 1
res1ind[1] = SIZE - 1
res2val, res2ind = torch.mode(x, keepdim=False)
self.assertEqual(res1val, res2val, 0)
self.assertEqual(res1ind, res2ind, 0)
# Test use of result tensor
res2val = torch.Tensor()
res2ind = torch.LongTensor()
torch.mode(x, keepdim=False, out=(res2val, res2ind))
self.assertEqual(res1val, res2val, 0)
self.assertEqual(res1ind, res2ind, 0)
# Test non-default dim
res2val, res2ind = torch.mode(x, 0, False)
self.assertEqual(res1val, res2val, 0)
self.assertEqual(res1ind, res2ind, 0)
# input unchanged
self.assertEqual(x, x0, 0)
def test_trilu_indices(self):
for test_args in tri_tests_args:
_compare_trilu_indices(self, *test_args)
run_additional_tri_tests(self, 'cpu')
# test default options
x = torch.ones(
3, 3, dtype=torch.long, device='cpu', layout=torch.strided)
self.assertEqual(
x.tril(0).nonzero().transpose(0, 1), torch.tril_indices(3, 3))
self.assertEqual(
x.triu(0).nonzero().transpose(0, 1), torch.triu_indices(3, 3))
# test stride 0 cases
x = torch.ones(
3, 1, 3, 3, dtype=torch.long, device='cpu', layout=torch.strided)
output = x.triu(2).expand(3, 3, 3, 3)
b = x.clone().expand(3, 3, 3, 3)
self.assertEqual(b.triu(2), output)
self.assertRaises(RuntimeError, lambda: b.triu_(2))
def test_narrow(self):
x = torch.Tensor([[0, 1, 2], [3, 4, 5], [6, 7, 8]])
self.assertEqual(x.narrow(0, 0, 1), torch.Tensor([[0, 1, 2]]))
self.assertEqual(x.narrow(0, 0, 2), torch.Tensor([[0, 1, 2], [3, 4, 5]]))
self.assertEqual(x.narrow(0, 1, 1), torch.Tensor([[3, 4, 5]]))
self.assertEqual(x.narrow(0, -1, 1), torch.Tensor([[6, 7, 8]]))
self.assertEqual(x.narrow(0, -2, 2), torch.Tensor([[3, 4, 5], [6, 7, 8]]))
self.assertEqual(x.narrow(0, -3, 3), torch.Tensor([[0, 1, 2], [3, 4, 5], [6, 7, 8]]))
self.assertEqual(x.narrow(-1, -1, 1), torch.Tensor([[2], [5], [8]]))
self.assertEqual(x.narrow(-2, -1, 1), torch.Tensor([[6, 7, 8]]))
def test_stack(self):
for dtype in (torch.half, torch.double, torch.int):
x = torch.randint(low=-100, high=100, size=(2, 3, 4)).to(dtype)
y = torch.randint(low=-100, high=100, size=(2, 3, 4)).to(dtype)
z = torch.randint(low=-100, high=100, size=(2, 3, 4)).to(dtype)
for dim in range(4):
res = torch.stack((x, y, z), dim)
res_neg = torch.stack((x, y, z), dim - 4)
expected_size = x.size()[:dim] + (3,) + x.size()[dim:]
self.assertEqual(res, res_neg)
self.assertEqual(res.size(), expected_size)
self.assertEqual(res.select(dim, 0), x, 0)
self.assertEqual(res.select(dim, 1), y, 0)
self.assertEqual(res.select(dim, 2), z, 0)
def test_stack_out(self):
for dtype in (torch.half, torch.double, torch.int):
x = torch.randint(low=-100, high=100, size=(2, 3, 4)).to(dtype)
y = torch.randint(low=-100, high=100, size=(2, 3, 4)).to(dtype)
z = torch.randint(low=-100, high=100, size=(2, 3, 4)).to(dtype)
for dim in range(4):
expected_size = x.size()[:dim] + (3,) + x.size()[dim:]
res_out = x.new(expected_size)
res_neg_out = x.new(expected_size)
res_out_dp = res_out.data_ptr()
res_out_neg_dp = res_neg_out.data_ptr()
torch.stack((x, y, z), dim, out=res_out)
torch.stack((x, y, z), dim - 4, out=res_neg_out)
self.assertEqual(res_out, res_neg_out)
self.assertEqual(res_out.size(), expected_size)
self.assertEqual(res_out_dp, res_out.data_ptr())
self.assertEqual(res_out_neg_dp, res_neg_out.data_ptr())
self.assertEqual(res_out.select(dim, 0), x, 0)
self.assertEqual(res_out.select(dim, 1), y, 0)
self.assertEqual(res_out.select(dim, 2), z, 0)
def test_unbind(self):
x = torch.rand(2, 3, 4, 5)
for dim in range(4):
res = torch.unbind(x, dim)
res2 = x.unbind(dim)
self.assertEqual(x.size(dim), len(res))
self.assertEqual(x.size(dim), len(res2))
for i in range(dim):
self.assertEqual(x.select(dim, i), res[i])
self.assertEqual(x.select(dim, i), res2[i])
def test_logspace(self):
_from = random.random()
to = _from + random.random()
res1 = torch.logspace(_from, to, 137)
res2 = torch.Tensor()
torch.logspace(_from, to, 137, out=res2)
self.assertEqual(res1, res2, 0)
self.assertRaises(RuntimeError, lambda: torch.logspace(0, 1, -1))
self.assertEqual(torch.logspace(0, 1, 1), torch.ones(1), 0)
# Check non-default base=2
self.assertEqual(torch.logspace(1, 1, 1, 2), torch.ones(1) * 2)
self.assertEqual(torch.logspace(0, 2, 3, 2), torch.Tensor((1, 2, 4)))
# Check logspace_ for generating with start > end.
self.assertEqual(torch.logspace(1, 0, 2), torch.Tensor((10, 1)), 0)
# Check logspace_ for non-contiguous tensors.
x = torch.zeros(2, 3)
y = torch.logspace(0, 3, 4, out=x.narrow(1, 1, 2))
self.assertEqual(x, torch.Tensor(((0, 1, 10), (0, 100, 1000))), 0)
def test_rand(self):
torch.manual_seed(123456)
res1 = torch.rand(SIZE, SIZE)
res2 = torch.Tensor()
torch.manual_seed(123456)
torch.rand(SIZE, SIZE, out=res2)
self.assertEqual(res1, res2)
def test_randint(self):
torch.manual_seed(123456)
res1 = torch.randint(0, 6, (SIZE, SIZE))
res2 = torch.Tensor()
torch.manual_seed(123456)
torch.randint(0, 6, (SIZE, SIZE), out=res2)
torch.manual_seed(123456)
res3 = torch.randint(6, (SIZE, SIZE))
res4 = torch.Tensor()
torch.manual_seed(123456)
torch.randint(6, (SIZE, SIZE), out=res4)
self.assertEqual(res1, res2)
self.assertEqual(res1, res3)
self.assertEqual(res1, res4)
self.assertEqual(res2, res3)
self.assertEqual(res2, res4)
self.assertEqual(res3, res4)
res1 = res1.view(-1)
high = (res1 < 6).type(torch.LongTensor)
low = (res1 >= 0).type(torch.LongTensor)
tensorSize = res1.size()[0]
assert(tensorSize == high.sum())
assert(tensorSize == low.sum())
def test_randn(self):
torch.manual_seed(123456)
res1 = torch.randn(SIZE, SIZE)
res2 = torch.Tensor()
torch.manual_seed(123456)
torch.randn(SIZE, SIZE, out=res2)
self.assertEqual(res1, res2)
def test_slice(self):
empty = torch.empty(0, 4)
x = torch.arange(0., 16).view(4, 4)
self.assertEqual(x[:], x)
self.assertEqual(x[:4], x)
# start and stop are clamped to the size of dim
self.assertEqual(x[:5], x)
# if start >= stop then the result is empty
self.assertEqual(x[2:1], empty)
self.assertEqual(x[2:2], empty)
# out of bounds is also empty
self.assertEqual(x[10:12], empty)
# additional correctness checks
self.assertEqual(x[:1].data.tolist(), [[0, 1, 2, 3]])
self.assertEqual(x[:-3].data.tolist(), [[0, 1, 2, 3]])
self.assertEqual(x[:, -2:3].data.tolist(), [[2], [6], [10], [14]])
self.assertEqual(x[0:-1:2].data.tolist(), [[0, 1, 2, 3], [8, 9, 10, 11]])
@skipIfNoLapack
def test_ormqr(self):
mat1 = torch.randn(7, 7)
mat2 = torch.randn(7, 7)
q, r = torch.qr(mat1)
m, tau = torch.geqrf(mat1)
out_holder = torch.empty_like(mat1)
res1 = torch.mm(q, mat2)
res2 = torch.ormqr(m, tau, mat2, left=True, transpose=False)
torch.ormqr(m, tau, mat2, out=out_holder)
self.assertEqual(res1, res2)
self.assertEqual(res2, out_holder)
res1 = torch.mm(mat2, q)
res2 = torch.ormqr(m, tau, mat2, left=False, transpose=False)
torch.ormqr(m, tau, mat2, left=False, transpose=False, out=out_holder)
self.assertEqual(res1, res2)
self.assertEqual(res2, out_holder)
res1 = torch.mm(q.t(), mat2)
res2 = torch.ormqr(m, tau, mat2, left=True, transpose=True)
torch.ormqr(m, tau, mat2, left=True, transpose=True, out=out_holder)
self.assertEqual(res1, res2)
self.assertEqual(res2, out_holder)
res1 = torch.mm(mat2, q.t())
res2 = torch.ormqr(m, tau, mat2, left=False, transpose=True)
torch.ormqr(m, tau, mat2, left=False, transpose=True, out=out_holder)
self.assertEqual(res1, res2)
self.assertEqual(res2, out_holder)
@staticmethod
def _test_fft_ifft_rfft_irfft(self, device='cpu', dtype=torch.double):
def _test_complex(sizes, signal_ndim, prepro_fn=lambda x: x):
x = prepro_fn(torch.randn(*sizes, dtype=dtype, device=device))
for normalized in (True, False):
res = x.fft(signal_ndim, normalized=normalized)
rec = res.ifft(signal_ndim, normalized=normalized)
self.assertEqual(x, rec, 1e-8, 'fft and ifft')
res = x.ifft(signal_ndim, normalized=normalized)
rec = res.fft(signal_ndim, normalized=normalized)
self.assertEqual(x, rec, 1e-8, 'ifft and fft')
def _test_real(sizes, signal_ndim, prepro_fn=lambda x: x):
x = prepro_fn(torch.randn(*sizes, dtype=dtype, device=device))
signal_numel = 1
signal_sizes = x.size()[-signal_ndim:]
for normalized, onesided in product((True, False), repeat=2):
res = x.rfft(signal_ndim, normalized=normalized, onesided=onesided)
if not onesided: # check Hermitian symmetry
def test_one_sample(res, test_num=10):
idxs_per_dim = [torch.LongTensor(test_num).random_(s).tolist() for s in signal_sizes]
for idx in zip(*idxs_per_dim):
reflected_idx = tuple((s - i) % s for i, s in zip(idx, res.size()))
idx_val = res.__getitem__(idx)
reflected_val = res.__getitem__(reflected_idx)
self.assertEqual(idx_val[0], reflected_val[0], 'rfft hermitian symmetry on real part')
self.assertEqual(idx_val[1], -reflected_val[1], 'rfft hermitian symmetry on imaginary part')
if len(sizes) == signal_ndim:
test_one_sample(res)
else:
output_non_batch_shape = res.size()[-(signal_ndim + 1):]
flatten_batch_res = res.view(-1, *output_non_batch_shape)
nb = flatten_batch_res.size(0)
test_idxs = torch.LongTensor(min(nb, 4)).random_(nb)
for test_idx in test_idxs.tolist():
test_one_sample(flatten_batch_res[test_idx])
# compare with C2C
xc = torch.stack([x, torch.zeros_like(x)], -1)
xc_res = xc.fft(signal_ndim, normalized=normalized)
self.assertEqual(res, xc_res)
test_input_signal_sizes = [signal_sizes]
rec = res.irfft(signal_ndim, normalized=normalized,
onesided=onesided, signal_sizes=signal_sizes)
self.assertEqual(x, rec, 1e-8, 'rfft and irfft')
if not onesided: # check that we can use C2C ifft
rec = res.ifft(signal_ndim, normalized=normalized)
self.assertEqual(x, rec.select(-1, 0), 1e-8, 'twosided rfft and ifft real')
self.assertEqual(rec.select(-1, 1).data.abs().mean(), 0, 1e-8, 'twosided rfft and ifft imaginary')
# contiguous case
_test_real((100,), 1)
_test_real((10, 1, 10, 100), 1)
_test_real((100, 100), 2)
_test_real((2, 2, 5, 80, 60), 2)
_test_real((50, 40, 70), 3)
_test_real((30, 1, 50, 25, 20), 3)
_test_complex((100, 2), 1)
_test_complex((100, 100, 2), 1)
_test_complex((100, 100, 2), 2)
_test_complex((1, 20, 80, 60, 2), 2)
_test_complex((50, 40, 70, 2), 3)
_test_complex((6, 5, 50, 25, 20, 2), 3)
# non-contiguous case
_test_real((165,), 1, lambda x: x.narrow(0, 25, 100)) # input is not aligned to complex type
_test_real((100, 100, 3), 1, lambda x: x[:, :, 0])
_test_real((100, 100), 2, lambda x: x.t())
_test_real((20, 100, 10, 10), 2, lambda x: x.view(20, 100, 100)[:, :60])
_test_real((65, 80, 115), 3, lambda x: x[10:60, 13:53, 10:80])
_test_real((30, 20, 50, 25), 3, lambda x: x.transpose(1, 2).transpose(2, 3))
_test_complex((2, 100), 1, lambda x: x.t())
_test_complex((100, 2), 1, lambda x: x.expand(100, 100, 2))
_test_complex((300, 200, 3), 2, lambda x: x[:100, :100, 1:]) # input is not aligned to complex type
_test_complex((20, 90, 110, 2), 2, lambda x: x[:, 5:85].narrow(2, 5, 100))
_test_complex((40, 60, 3, 80, 2), 3, lambda x: x.transpose(2, 0).select(0, 2)[5:55, :, 10:])
_test_complex((30, 55, 50, 22, 2), 3, lambda x: x[:, 3:53, 15:40, 1:21])
# non-contiguous with strides not representable as aligned with complex type
_test_complex((50,), 1, lambda x: x.as_strided([5, 5, 2], [3, 2, 1]))
_test_complex((50,), 1, lambda x: x.as_strided([5, 5, 2], [4, 2, 2]))
_test_complex((50,), 1, lambda x: x.as_strided([5, 5, 2], [4, 3, 1]))
_test_complex((50,), 2, lambda x: x.as_strided([5, 5, 2], [3, 3, 1]))
_test_complex((50,), 2, lambda x: x.as_strided([5, 5, 2], [4, 2, 2]))
_test_complex((50,), 2, lambda x: x.as_strided([5, 5, 2], [4, 3, 1]))
@unittest.skipIf(not TEST_MKL, "PyTorch is built without MKL support")
def test_fft_ifft_rfft_irfft(self):
self._test_fft_ifft_rfft_irfft(self)
@unittest.skip("Not implemented yet")
def test_conv2(self):
x = torch.rand(math.floor(torch.uniform(50, 100)), math.floor(torch.uniform(50, 100)))
k = torch.rand(math.floor(torch.uniform(10, 20)), math.floor(torch.uniform(10, 20)))
imvc = torch.conv2(x, k)
imvc2 = torch.conv2(x, k, 'V')
imfc = torch.conv2(x, k, 'F')
ki = k.clone()
ks = k.storage()
kis = ki.storage()
for i in range(ks.size() - 1, 0, -1):
kis[ks.size() - i + 1] = ks[i]
# for i=ks.size(), 1, -1 do kis[ks.size()-i+1]=ks[i] end
imvx = torch.xcorr2(x, ki)
imvx2 = torch.xcorr2(x, ki, 'V')
imfx = torch.xcorr2(x, ki, 'F')
self.assertEqual(imvc, imvc2, 0, 'torch.conv2')
self.assertEqual(imvc, imvx, 0, 'torch.conv2')
self.assertEqual(imvc, imvx2, 0, 'torch.conv2')
self.assertEqual(imfc, imfx, 0, 'torch.conv2')
self.assertLessEqual(math.abs(x.dot(x) - torch.xcorr2(x, x)[0][0]), 1e-10, 'torch.conv2')
xx = torch.Tensor(2, x.size(1), x.size(2))
xx[1].copy_(x)
xx[2].copy_(x)
kk = torch.Tensor(2, k.size(1), k.size(2))
kk[1].copy_(k)
kk[2].copy_(k)
immvc = torch.conv2(xx, kk)
immvc2 = torch.conv2(xx, kk, 'V')
immfc = torch.conv2(xx, kk, 'F')
self.assertEqual(immvc[0], immvc[1], 0, 'torch.conv2')
self.assertEqual(immvc[0], imvc, 0, 'torch.conv2')
self.assertEqual(immvc2[0], imvc2, 0, 'torch.conv2')
self.assertEqual(immfc[0], immfc[1], 0, 'torch.conv2')
self.assertEqual(immfc[0], imfc, 0, 'torch.conv2')
@unittest.skip("Not implemented yet")
def test_conv3(self):
x = torch.rand(math.floor(torch.uniform(20, 40)),
math.floor(torch.uniform(20, 40)),
math.floor(torch.uniform(20, 40)))
k = torch.rand(math.floor(torch.uniform(5, 10)),
math.floor(torch.uniform(5, 10)),
math.floor(torch.uniform(5, 10)))
imvc = torch.conv3(x, k)
imvc2 = torch.conv3(x, k, 'V')
imfc = torch.conv3(x, k, 'F')
ki = k.clone()
ks = k.storage()
kis = ki.storage()
for i in range(ks.size() - 1, 0, -1):
kis[ks.size() - i + 1] = ks[i]
imvx = torch.xcorr3(x, ki)
imvx2 = torch.xcorr3(x, ki, 'V')
imfx = torch.xcorr3(x, ki, 'F')
self.assertEqual(imvc, imvc2, 0, 'torch.conv3')
self.assertEqual(imvc, imvx, 0, 'torch.conv3')
self.assertEqual(imvc, imvx2, 0, 'torch.conv3')
self.assertEqual(imfc, imfx, 0, 'torch.conv3')
self.assertLessEqual(math.abs(x.dot(x) - torch.xcorr3(x, x)[0][0][0]), 4e-10, 'torch.conv3')
xx = torch.Tensor(2, x.size(1), x.size(2), x.size(3))
xx[1].copy_(x)
xx[2].copy_(x)
kk = torch.Tensor(2, k.size(1), k.size(2), k.size(3))
kk[1].copy_(k)
kk[2].copy_(k)
immvc = torch.conv3(xx, kk)
immvc2 = torch.conv3(xx, kk, 'V')
immfc = torch.conv3(xx, kk, 'F')
self.assertEqual(immvc[0], immvc[1], 0, 'torch.conv3')
self.assertEqual(immvc[0], imvc, 0, 'torch.conv3')
self.assertEqual(immvc2[0], imvc2, 0, 'torch.conv3')
self.assertEqual(immfc[0], immfc[1], 0, 'torch.conv3')
self.assertEqual(immfc[0], imfc, 0, 'torch.conv3')
@unittest.skip("Not implemented yet")
def _test_conv_corr_eq(self, fn, fn_2_to_3):
ix = math.floor(random.randint(20, 40))
iy = math.floor(random.randint(20, 40))
iz = math.floor(random.randint(20, 40))
kx = math.floor(random.randint(5, 10))
ky = math.floor(random.randint(5, 10))
kz = math.floor(random.randint(5, 10))
x = torch.rand(ix, iy, iz)
k = torch.rand(kx, ky, kz)
o3 = fn(x, k)
o32 = torch.zeros(o3.size())
fn_2_to_3(x, k, o3, o32)
self.assertEqual(o3, o32)
@unittest.skip("Not implemented yet")
def test_xcorr3_xcorr2_eq(self):
def reference(x, k, o3, o32):
for i in range(o3.size(1)):
for j in range(k.size(1)):
o32[i].add(torch.xcorr2(x[i + j - 1], k[j]))
self._test_conv_corr_eq(torch.xcorr3, reference)
@unittest.skip("Not implemented yet")
def test_xcorr3_xcorr2_eq_full(self):
def reference(x, k, o3, o32):
for i in range(x.size(1)):
for j in range(k.size(1)):
o32[i].add(torch.xcorr2(x[i], k[k.size(1) - j + 1], 'F'))
self._test_conv_corr_eq(lambda x, k: torch.xcorr3(x, k, 'F'), reference)
@unittest.skip("Not implemented yet")
def test_conv3_conv2_eq_valid(self):
def reference(x, k, o3, o32):
for i in range(o3.size(1)):
for j in range(k.size(1)):
o32[i].add(torch.conv2(x[i + j - 1], k[k.size(1) - j + 1]))
self._test_conv_corr_eq(torch.conv3, reference)
@unittest.skip("Not implemented yet")
def test_fconv3_fconv2_eq(self):
def reference(x, k, o3, o32):
for i in range(o3.size(1)):
for j in range(k.size(1)):
o32[i + j - 1].add(torch.conv2(x[i], k[j], 'F'))
self._test_conv_corr_eq(lambda x, k: torch.conv3(x, k, 'F'), reference)
def test_isfinite(self):
x = torch.Tensor([1, inf, 2, -inf, nan, -10])
self.assertEqual(torch.isfinite(x), torch.BoolTensor([True, False, True, False, False, True]))
def test_isfinite_int(self):
x = torch.tensor([1, 2, 3])
self.assertEqual(torch.isfinite(x), torch.BoolTensor([True, True, True]))
def test_isfinite_type(self):
with self.assertRaises(TypeError):
torch.isfinite(1) # Parameter must be a tensor
def test_isinf_type(self):
with self.assertRaises(TypeError):
torch.isinf(1) # Parameter must be a tensor
def test_isnan(self):
x = torch.Tensor([1, nan, 2])
self.assertEqual(torch.isnan(x), torch.ByteTensor([0, 1, 0]))
def test_RNGState(self):
state = torch.get_rng_state()
stateCloned = state.clone()
before = torch.rand(1000)
self.assertEqual(state.ne(stateCloned).long().sum(), 0, 0)
torch.set_rng_state(state)
after = torch.rand(1000)
self.assertEqual(before, after, 0)
def test_RNGStateAliasing(self):
# Fork the random number stream at this point
gen = torch.Generator()
gen.set_state(torch.get_rng_state())
self.assertEqual(gen.get_state(), torch.get_rng_state())
target_value = torch.rand(1000)
# Dramatically alter the internal state of the main generator
_ = torch.rand(100000)
forked_value = torch.rand(1000, generator=gen)
self.assertEqual(target_value, forked_value, 0, "RNG has not forked correctly.")
def test_RNG_after_pickle(self):
torch.random.manual_seed(100)
before = torch.rand(10)
torch.random.manual_seed(100)
buf = io.BytesIO()
tensor = torch.Tensor([1, 2, 3])
ForkingPickler(buf, pickle.HIGHEST_PROTOCOL).dump(tensor)
after = torch.rand(10)
self.assertEqual(before, after, 0)
def test_boxMullerState(self):
torch.manual_seed(123)
odd_number = 101
seeded = torch.randn(odd_number)
state = torch.get_rng_state()
midstream = torch.randn(odd_number)
torch.set_rng_state(state)
repeat_midstream = torch.randn(odd_number)
torch.manual_seed(123)
reseeded = torch.randn(odd_number)
self.assertEqual(midstream, repeat_midstream, 0,
'get_rng_state/set_rng_state not generating same sequence of normally distributed numbers')
self.assertEqual(seeded, reseeded, 0,
'repeated calls to manual_seed not generating same sequence of normally distributed numbers')
def test_manual_seed(self):
rng_state = torch.get_rng_state()
torch.manual_seed(2)
x = torch.randn(100)
self.assertEqual(torch.initial_seed(), 2)
torch.manual_seed(2)
y = torch.randn(100)
self.assertEqual(x, y)
torch.set_rng_state(rng_state)
def test_numel(self):
b = torch.ByteTensor(3, 100, 100)
self.assertEqual(b.nelement(), 3 * 100 * 100)
self.assertEqual(b.numel(), 3 * 100 * 100)
@unittest.skipIf(not TEST_NUMPY, "Numpy not found")
def test_empty_storage_view(self):
# we should be able to "modify" slices of a 0-element
# array without an error being raised due to
# trying to resize its storage
t = torch.from_numpy(np.empty((0, 4)))
t[:, 1::2] *= 1
@unittest.skipIf(not TEST_NUMPY, "Numpy not found")
def test_newaxis_numpy_comparison(self):
def run_test(tensor, *idx):
npt = tensor.numpy()
self.assertEqual(tensor[idx], npt[idx])
# 1D Tensor Tests
x = torch.arange(0, 10)
cases = [
[None],
[None, None],
[Ellipsis, None],
[None, Ellipsis],
[2, None],
[None, 2],
[Ellipsis, None, 2],
[Ellipsis, 2, None],
[2, Ellipsis, None],
[2, None, Ellipsis],
[None, 2, Ellipsis],
[None, Ellipsis, 2],
]
for case in cases:
run_test(x, *case)
# 2D Tensor Tests
x = torch.arange(0, 12).view(3, 4)
cases = [
[None],
[None, None],
[None, None, None],
[Ellipsis, None],
[Ellipsis, None, None],
[None, Ellipsis],
[None, Ellipsis, None],
[None, None, Ellipsis],
[2, None],
[2, None, Ellipsis],
[2, Ellipsis, None],
[None, 2, Ellipsis],
[Ellipsis, 2, None],
[Ellipsis, None, 2],
[None, Ellipsis, 2],
[1, 2, None],
[1, 2, Ellipsis, None],
[1, Ellipsis, 2, None],
[Ellipsis, 1, None, 2],
[Ellipsis, 1, 2, None],
[1, None, 2, Ellipsis],
[None, 1, Ellipsis, 2],
[None, 1, 2, Ellipsis],
]
for case in cases:
run_test(x, *case)
def _consecutive(self, size, start=1):
sequence = torch.ones(int(torch.Tensor(size).prod(0))).cumsum(0)
sequence.add_(start - 1)
return sequence.resize_(*size)
def test_newindex(self):
reference = self._consecutive((3, 3, 3))
# This relies on __index__() being correct - but we have separate tests for that
def checkPartialAssign(index):
reference = torch.zeros(3, 3, 3)
reference[index] = self._consecutive((3, 3, 3))[index]
self.assertEqual(reference[index], self._consecutive((3, 3, 3))[index], 0)
reference[index] = 0
self.assertEqual(reference, torch.zeros(3, 3, 3), 0)
checkPartialAssign(0)
checkPartialAssign(1)
checkPartialAssign(2)
checkPartialAssign((0, 1))
checkPartialAssign((1, 2))
checkPartialAssign((0, 2))
checkPartialAssign(torch.LongTensor((0, 2)))
with self.assertRaises(IndexError):
reference[1, 1, 1, 1] = 1
with self.assertRaises(IndexError):
reference[1, 1, 1, (1, 1)] = 1
with self.assertRaises(IndexError):
reference[3, 3, 3, 3, 3, 3, 3, 3] = 1
with self.assertRaises(IndexError):
reference[0.0] = 1
with self.assertRaises(TypeError):
reference[0.0:2.0] = 1
with self.assertRaises(IndexError):
reference[0.0, 0.0:2.0] = 1
with self.assertRaises(IndexError):
reference[0.0, :, 0.0:2.0] = 1
with self.assertRaises(IndexError):
reference[0.0, ..., 0.0:2.0] = 1
with self.assertRaises(IndexError):
reference[0.0, :, 0.0] = 1
def test_index_add(self):
num_copy, num_dest = 3, 3
dest = torch.randn(num_dest, 4, 5)
src = torch.randn(num_copy, 4, 5)
idx = torch.randperm(num_dest).narrow(0, 0, num_copy)
dest2 = dest.clone()
dest.index_add_(0, idx, src)
for i in range(idx.size(0)):
dest2[idx[i]] += src[i]
self.assertEqual(dest, dest2)
dest = torch.randn(num_dest)
src = torch.randn(num_copy)
idx = torch.randperm(num_dest).narrow(0, 0, num_copy)
dest2 = dest.clone()
dest.index_add_(0, idx, src)
for i in range(idx.size(0)):
dest2[idx[i]] = dest2[idx[i]] + src[i]
self.assertEqual(dest, dest2)
def test_t(self):
# Test 0D tensors
x = torch.randn(())
self.assertEqual(x, x.t())
x = x.to_sparse()
self.assertEqual(x, x.t())
# Test 1D tensors
x = torch.arange(4)
self.assertEqual(x, x.t())
x = x.to_sparse()
self.assertEqual(x, x.t())
# Test 2D tensors
x = torch.rand((2, 2))
self.assertEqual(x.t(), x.transpose(0, 1))
x = x.to_sparse()
self.assertEqual(x.t(), x.transpose(0, 1))
# Test 3D tensor
x = torch.rand((2, 2, 2))
with self.assertRaisesRegex(RuntimeError, 'expects a tensor with <= 2 dimensions, but self is 3D'):
x.t()
x = x.to_sparse()
with self.assertRaisesRegex(RuntimeError, 'expects a tensor with <= 2 sparse and 0 dense dimensions'):
x.t()
def test_take(self):
def check(src, idx):
expected = src.contiguous().view(-1).index_select(
0, idx.contiguous().view(-1)).view_as(idx)
actual = src.take(idx)
self.assertEqual(actual.size(), idx.size())
self.assertEqual(expected, actual)
src = torch.randn(2, 3, 5)
idx = torch.LongTensor([[0, 2], [3, 4]])
check(src, idx)
check(src.transpose(1, 2), idx)
check(src.bool(), idx)
def test_put_(self):
def check(dst, idx, value):
expected = dst.clone().view(-1).index_copy_(
0, idx.contiguous().view(-1), value.contiguous().view(-1))
expected = expected.view_as(dst)
dst.put_(idx, value)
self.assertEqual(expected, dst)
dst = torch.randn(2, 3, 5)
idx = torch.LongTensor([[0, 2], [3, 4]])
values = torch.randn(2, 2)
check(dst, idx, values)
check(dst.transpose(1, 2), idx, values)
values = torch.tensor([[False, False], [False, False]])
check(dst.bool(), idx, values)
def test_put_accumulate(self):
dst = torch.ones(2, 2)
idx = torch.LongTensor([[0, 1], [0, 1]])
src = torch.Tensor([1, 2, 3, 4])
dst.put_(idx, src, accumulate=True)
self.assertEqual(dst.tolist(), [[5, 7], [1, 1]])
# Fill idx with valid indices.
@staticmethod
def _fill_indices(self, idx, dim, dim_size, elems_per_row, m, n, o):
for i in range(1 if dim == 0 else m):
for j in range(1 if dim == 1 else n):
for k in range(1 if dim == 2 else o):
ii = [i, j, k]
ii[dim] = slice(0, idx.size(dim) + 1)
idx[tuple(ii)] = torch.randperm(dim_size)[0:elems_per_row]
def test_flatten(self):
# Test that flatten returns 1-dim tensor when given a 0-dim tensor
zero_dim_tensor = torch.tensor(123)
flat0 = zero_dim_tensor.flatten()
one_dim_tensor = torch.tensor([123])
flat1 = zero_dim_tensor.flatten()
self.assertEqual(zero_dim_tensor.shape, torch.Size([]))
self.assertEqual(flat0.shape, torch.Size([1]))
self.assertEqual(one_dim_tensor.shape, torch.Size([1]))
self.assertEqual(flat1.shape, torch.Size([1]))
self.assertEqual(flat0, one_dim_tensor)
self.assertEqual(flat0, flat1)
self.assertEqual(flat0.shape, flat1.shape)
# Test both float tensor and quantized tensor
tensors = [torch.randn(5, 5, 5, 5),
torch._empty_affine_quantized([5, 5, 5, 5],
scale=2,
zero_point=3,
dtype=torch.quint8)]
for src in tensors:
flat = src.flatten(0, -1)
self.assertEqual(flat.shape, torch.Size([625]))
self.assertEqual(src.view(-1), flat.view(-1))
flat = src.flatten(0, 2)
self.assertEqual(flat.shape, torch.Size([125, 5]))
self.assertEqual(src.view(-1), flat.view(-1))
flat = src.flatten(0, 1)
self.assertEqual(flat.shape, torch.Size([25, 5, 5]))
self.assertEqual(src.view(-1), flat.view(-1))
flat = src.flatten(1, 2)
self.assertEqual(flat.shape, torch.Size([5, 25, 5]))
self.assertEqual(src.view(-1), flat.view(-1))
flat = src.flatten(2, 3)
self.assertEqual(flat.shape, torch.Size([5, 5, 25]))
self.assertEqual(src.view(-1), flat.view(-1))
flat = src.flatten(-2, -1)
self.assertEqual(flat.shape, torch.Size([5, 5, 25]))
self.assertEqual(src.view(-1), flat.view(-1))
flat = src.flatten(2, 2)
self.assertEqual(flat, src)
# out of bounds index
with self.assertRaisesRegex(IndexError, 'Dimension out of range'):
src.flatten(5, 10)
# invalid start and end
with self.assertRaisesRegex(RuntimeError, 'start_dim cannot come after end_dim'):
src.flatten(2, 0)
@staticmethod
def _test_gather(self, cast, test_bounds=True):
m, n, o = random.randint(10, 20), random.randint(10, 20), random.randint(10, 20)
elems_per_row = random.randint(1, 10)
dim = random.randrange(3)
src = torch.randn(m, n, o)
idx_size = [m, n, o]
idx_size[dim] = elems_per_row
idx = torch.LongTensor().resize_(*idx_size)
_TestTorchMixin._fill_indices(self, idx, dim, src.size(dim), elems_per_row, m, n, o)
src = cast(src)
idx = cast(idx)
actual = torch.gather(src, dim, idx)
expected = cast(torch.Tensor().resize_(*idx_size))
for i in range(idx_size[0]):
for j in range(idx_size[1]):
for k in range(idx_size[2]):
ii = [i, j, k]
ii[dim] = idx[i, j, k]
expected[i, j, k] = src[tuple(ii)]
self.assertEqual(actual, expected, 0)
if test_bounds:
idx[0][0][0] = 23
self.assertRaises(RuntimeError, lambda: torch.gather(src, dim, idx))
src = cast(torch.randn(3, 4, 5))
expected, idx = src.max(2, True)
expected = cast(expected)
idx = cast(idx)
actual = torch.gather(src, 2, idx)
self.assertEqual(actual, expected, 0)
# Bool test case
t = torch.tensor([[False, True], [True, True]])
self.assertEqual(torch.gather(t, 1, torch.tensor([[0, 0], [1, 0]])), torch.tensor([[False, False], [True, True]]))
def test_gather(self):
self._test_gather(self, lambda t: t)
@staticmethod
def _test_scatter_base(self, cast, method, is_scalar=False, test_bounds=True):
m, n, o = random.randint(10, 20), random.randint(10, 20), random.randint(10, 20)
elems_per_row = random.randint(1, 10)
dim = random.randrange(3)
idx_size = [m, n, o]
idx_size[dim] = elems_per_row
idx = cast(torch.LongTensor().resize_(*idx_size))
_TestTorchMixin._fill_indices(self, idx, dim, ([m, n, o])[dim], elems_per_row, m, n, o)
if is_scalar:
src = random.random()
else:
src = cast(torch.Tensor(*idx_size).normal_())
base = cast(torch.randn(m, n, o))
actual = getattr(base.clone(), method)(dim, idx, src)
expected = base.clone()
for i in range(idx_size[0]):
for j in range(idx_size[1]):
for k in range(idx_size[2]):
ii = [i, j, k]
ii[dim] = idx[i, j, k]
if method == 'scatter_' and not is_scalar:
expected[tuple(ii)] = src[i, j, k]
elif method == 'scatter_add_':
expected[tuple(ii)] += src[i, j, k]
else:
expected[tuple(ii)] = src
self.assertEqual(actual, expected, 0)
if test_bounds:
idx[0][0][0] = 34
with self.assertRaises(RuntimeError):
getattr(base.clone(), method)(dim, idx, src)
# test for empty index, should be a no-op
idx = cast(torch.LongTensor())
actual = getattr(base.clone(), method)(dim, idx, src)
self.assertEqual(actual, base, 0)
def test_scatter(self):
self._test_scatter_base(self, lambda t: t, 'scatter_')
def test_scatterAdd(self):
self._test_scatter_base(self, lambda t: t, 'scatter_add_')
def test_scatterFill(self):
self._test_scatter_base(self, lambda t: t, 'scatter_', True)
def test_masked_scatter(self):
with warnings.catch_warnings(record=True) as w:
for maskType in [torch.uint8, torch.bool]:
for dt in torch.testing.get_all_dtypes():
num_copy, num_dest = 3, 10
dest = torch.tensor([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], dtype=dt)
dest2 = dest.clone()
src = torch.tensor([0, 0, 0, 0, 0, 0, 0, 0, 0, 0], dtype=dt)
mask = torch.tensor((0, 0, 0, 0, 1, 0, 1, 0, 1, 0), dtype=maskType)
if dt == torch.bool:
# torch.bool is a special case and is being tested
# in a separate test
continue
if dt == torch.half:
self.assertRaises(RuntimeError, lambda: dest.masked_scatter_(mask, src))
continue
dest.masked_scatter_(mask, src)
j = 0
for i in range(num_dest):
if mask[i]:
dest2[i] = src[j]
j += 1
self.assertEqual(dest, dest2, 0)
# make source bigger than number of 1s in mask
src = torch.tensor([1, 1, 1, 1, 1, 1, 1, 1, 1, 1], dtype=dt)
dest.masked_scatter_(mask, src)
# make src smaller. this should fail
src = torch.randn(num_copy - 1)
with self.assertRaises(RuntimeError):
dest.masked_scatter_(mask, src)
self.assertEqual(len(w), 25)
warn = 'masked_scatter_ received a mask with dtype torch.uint8,'
for wi in w:
self.assertEqual(str(wi.message)[0:55], str(warn))
def test_masked_fill(self):
with warnings.catch_warnings(record=True) as w:
for dt in torch.testing.get_all_dtypes():
for dtype in [torch.uint8, torch.bool]:
num_dest = 10
dst = torch.tensor([0, 0, 0, 0, 0, 0, 0, 0, 0, 0], dtype=dt)
mask = torch.rand(num_dest).mul(2).floor().to(dtype)
val = random.random()
dst2 = dst.clone()
if dt == torch.half:
self.assertRaises(RuntimeError, lambda: dst.masked_fill_(mask, val))
continue
dst.masked_fill_(mask, val)
for i in range(num_dest):
if mask[i]:
dst2[i] = val
self.assertEqual(dst, dst2, 0)
# test non-contiguous case
dst = torch.randn(num_dest, num_dest, num_dest).permute((2, 0, 1))
dst2 = dst.clone()
dst.masked_fill_((dst > 0).to(dtype), val)
dst2.masked_fill_((dst2 > 0).to(dtype), val)
self.assertEqual(dst, dst2, 0)
self.assertEqual(len(w), 28)
warn = 'masked_fill_ received a mask with dtype torch.uint8,'
for wi in w:
self.assertEqual(str(wi.message)[0:52], str(warn))
def test_abs(self):
def _test_abs(tensors_dict):
for _category, tensors in tensors_dict.items():
for data in tensors:
_test_abs_single(data)
def _test_abs_single(data):
switch = torch.rand(data.size()).mul(2).floor().mul(2).add(-1).type(data.dtype)
res = torch.mul(data, switch)
self.assertTensorsSlowEqual(res.abs(), data, 1e-16)
shapes = [(3, 4), (3, 5, 7), (2, 2, 5, 8, 2, 3), (1000,), (10, 10, 10)]
for shape in shapes:
# Test all except char/byte
_test_abs(self._make_tensors(shape, val_range=(0, 1000)))
# Test char
_test_abs_single(torch.CharTensor(*shape).random_(0, 100))
# Test byte
byte_tensor = torch.ByteTensor(*shape).random_(0, 100)
self.assertTensorsSlowEqual(byte_tensor, byte_tensor.abs(), 1e-16)
# Checking that the right abs function is called for LongTensor
bignumber = 2 ** 31 + 1
res = torch.LongTensor((-bignumber,))
self.assertGreater(res.abs()[0], 0)
# One of
rec = torch.randn(2, 2, 3, 7, 6, 2).type(torch.float64).clamp(0, 1)
val1 = rec.select(-1, -1).data[0][0][0].sum()
val2 = rec.select(-1, -1).data.abs()[0][0][0].sum()
self.assertEqual(val1, val2, 1e-8, 'absolute value')
# Both abs(0.0) and abs(-0.0) should result in 0.0
for dtype in (torch.float, torch.double):
for abs_zeros in (torch.tensor([0.0, -0.0], dtype=dtype).abs().tolist(),
# test a large tensor so that the vectorized version is tested
torch.abs(-torch.zeros(10000, dtype=dtype)).tolist()):
for num in abs_zeros:
self.assertGreater(math.copysign(1.0, num), 0.0)
def test_unbiased(self):
tensor = torch.randn(100)
self.assertEqual(tensor.var(0), tensor.var(0, unbiased=True))
self.assertEqual(tensor.var(), tensor.var(unbiased=True))
self.assertEqual(tensor.var(unbiased=False), tensor.var(0, unbiased=False))
tensor = torch.FloatTensor([1.0, 2.0])
self.assertEqual(tensor.var(unbiased=True), 0.5)
self.assertEqual(tensor.var(unbiased=False), 0.25)
tensor = torch.FloatTensor([1.0, 2.0, 3.0])
self.assertEqual(tensor.var(unbiased=True), 1.0)
self.assertEqual(tensor.var(unbiased=False), 2.0 / 3.0)
tensor = torch.randn(100)
self.assertEqual(tensor.std(0), tensor.std(0, unbiased=True))
self.assertEqual(tensor.std(), tensor.std(unbiased=True))
self.assertEqual(tensor.std(unbiased=False), tensor.std(0, unbiased=False))
def test_structseq_repr(self):
a = torch.arange(250).reshape(5, 5, 10)
expected = """
torch.return_types.max(
values=tensor([[ 40, 41, 42, 43, 44, 45, 46, 47, 48, 49],
[ 90, 91, 92, 93, 94, 95, 96, 97, 98, 99],
[140, 141, 142, 143, 144, 145, 146, 147, 148, 149],
[190, 191, 192, 193, 194, 195, 196, 197, 198, 199],
[240, 241, 242, 243, 244, 245, 246, 247, 248, 249]]),
indices=tensor([[4, 4, 4, 4, 4, 4, 4, 4, 4, 4],
[4, 4, 4, 4, 4, 4, 4, 4, 4, 4],
[4, 4, 4, 4, 4, 4, 4, 4, 4, 4],
[4, 4, 4, 4, 4, 4, 4, 4, 4, 4],
[4, 4, 4, 4, 4, 4, 4, 4, 4, 4]]))"""
self.assertEqual(repr(a.max(1)), textwrap.dedent(expected).strip())
def test_var_stability(self):
tensor = torch.FloatTensor([2281.5, 2281.25])
self.assertEqual(tensor.var(dim=0), 0.03125)
self.assertEqual(tensor.var(), 0.03125)
def test_view_empty(self):
x = torch.randn(0, 6)
self.assertEqual((1, 0, 6, 1, 1), x.view(1, 0, 6, 1, 1).shape)
def test_reshape(self):
x = torch.randn(3, 3)
self.assertEqual(x.data_ptr(), x.reshape(-1).data_ptr())
self.assertEqual(x.data_ptr(), x.reshape(1, 9, 1).data_ptr())
self.assertEqual(torch.reshape(x, (9,)), x.reshape(9))
self.assertRaises(RuntimeError, lambda: x.reshape(-1, -1))
y = torch.randn(4, 4, 4)[:, 0, :]
self.assertNotEqual(y.data_ptr(), y.reshape(-1).data_ptr())
self.assertEqual(y.contiguous().view(-1), y.reshape(-1))
self.assertEqual(y.reshape(2, 2, 4).data_ptr(), y.data_ptr())
s = torch.randn(())
self.assertEqual(s.data_ptr(), s.reshape(()).data_ptr())
self.assertEqual(s.reshape(-1).shape, (1,))
self.assertRaises(RuntimeError, lambda: s.reshape(2))
empty = torch.tensor([])
self.assertEqual(empty, empty.reshape(-1))
self.assertEqual(empty, empty.reshape([0]))
# TODO: fix these once we have multi-dimensional empty tensors
self.assertEqual(empty.reshape([0, 1]).shape, (0, 1))
self.assertEqual(empty.reshape([1, -1]).shape, (1, 0))
self.assertRaises(RuntimeError, lambda: empty.reshape(1))
x = torch.randn(3, 3)
self.assertEqual(x.data_ptr(), x.reshape_as(torch.rand(9)).data_ptr())
self.assertEqual(x.data_ptr(), x.reshape_as(torch.rand(1, 9, 1)).data_ptr())
self.assertRaises(RuntimeError, lambda: x.reshape_as(torch.rand(10)))
def test_empty_reshape(self):
x = torch.randn(0, 6)
self.assertEqual((1, 0, 6, 1, 1), x.reshape(1, 0, 6, 1, 1).shape)
# should be viewable -- i.e. data_ptr is the same.
self.assertEqual(x.data_ptr(), x.reshape(1, 0, 6, 1, 1).data_ptr())
# match NumPy semantics -- don't infer the size of dimension with a degree of freedom
self.assertRaises(RuntimeError, lambda: x.reshape(0, -1))
def check_single_matmul(self, x, y, shape):
a = np.array(x, copy=False)
b = np.array(y, copy=False)
expected = np.matmul(a, b)
ans = torch.matmul(x, y)
self.assertTrue(ans.is_contiguous())
self.assertTrue(np.array_equal(ans, expected))
out = torch.zeros(*shape, dtype=torch.int64)
ans = torch.matmul(x, y, out=out)
self.assertIs(ans, out)
self.assertTrue(ans.is_contiguous())
self.assertTrue(np.array_equal(ans, expected))
@unittest.skipIf(not TEST_NUMPY, "Numpy not found")
def test_matmul_small_brute_force_1d_Nd(self):
# Issue #20452: range(0, 10) does not work.
n = 1
for m in range(1, 8):
for p in range(1, 8):
for o in range(1, 5):
# 1d, 3d, inner dimensions C
x = torch.arange(m)
y = torch.arange(o * m * p).reshape(o, m, p)
self.check_single_matmul(x, y, (o, n, p))
# 1d, 3d, inner dimensions Fortran
x = torch.arange(m)
y = torch.arange(o * p * m).reshape(o, p, m).transpose(-1, -2)
self.check_single_matmul(x, y, (o, n, p))
# 1d, 3d, inner dimensions non-contiguous
x = torch.arange(2 * m)[::2]
y = torch.arange(o * m * 2 * p).reshape(o, m, 2 * p)[:, :, ::2]
self.check_single_matmul(x, y, (o, n, p))
for r in range(1, 5):
# 1d, 4d, inner dimensions C
x = torch.arange(m)
y = torch.arange(r * o * m * p).reshape(r, o, m, p)
self.check_single_matmul(x, y, (r, o, n, p))
# 1d, 4d, inner dimensions Fortran
x = torch.arange(m)
y = torch.arange(r * o * p * m).reshape(r, o, p, m).transpose(-1, -2)
self.check_single_matmul(x, y, (r, o, n, p))
# 1d, 4d, inner dimensions non-contiguous
x = torch.arange(2 * m)[::2]
y = torch.arange(r * o * m * 2 * p).reshape(r, o, m, 2 * p)[:, :, :, ::2]
self.check_single_matmul(x, y, (r, o, n, p))
@unittest.skipIf(not TEST_NUMPY, "Numpy not found")
def test_matmul_small_brute_force_2d_Nd(self):
# Issue #20452: range(0, 10) does not work.
for n in range(1, 5):
for m in range(1, 5):
for p in range(1, 5):
for o in range(1, 3):
# 2d, 3d, inner dimensions C
x = torch.arange(n * m).reshape(n, m)
y = torch.arange(o * m * p).reshape(o, m, p)
self.check_single_matmul(x, y, (o, n, p))
# 2d, 3d, inner dimensions Fortran
x = torch.arange(m * n).reshape(m, n).transpose(-1, -2)
y = torch.arange(o * p * m).reshape(o, p, m).transpose(-1, -2)
self.check_single_matmul(x, y, (o, n, p))
# 2d, 3d, inner dimensions non-contiguous
x = torch.arange(n * 2 * m).reshape(n, 2 * m)[:, ::2]
y = torch.arange(o * m * 2 * p).reshape(o, m, 2 * p)[:, :, ::2]
self.check_single_matmul(x, y, (o, n, p))
for r in range(1, 2):
# 2d, 4d, inner dimensions C
x = torch.arange(n * m).reshape(n, m)
y = torch.arange(r * o * m * p).reshape(r, o, m, p)
self.check_single_matmul(x, y, (r, o, n, p))
# 2d, 4d, inner dimensions Fortran
x = torch.arange(m * n).reshape(m, n).transpose(-1, -2)
y = torch.arange(r * o * p * m).reshape(r, o, p, m).transpose(-1, -2)
self.check_single_matmul(x, y, (r, o, n, p))
# 2d, 4d, inner dimensions non-contiguous
x = torch.arange(n * 2 * m).reshape(n, 2 * m)[:, ::2]
y = torch.arange(r * o * m * 2 * p).reshape(r, o, m, 2 * p)[:, :, :, ::2]
self.check_single_matmul(x, y, (r, o, n, p))
def test_expand(self):
tensor = torch.rand(1, 8, 1)
tensor2 = torch.rand(5)
template = torch.rand(4, 8, 5)
target = template.size()
self.assertEqual(tensor.expand_as(template).size(), target)
self.assertEqual(tensor.expand(4, 8, 5).size(), target)
self.assertEqual(tensor.expand(target).size(), target)
self.assertEqual(tensor2.expand_as(template).size(), target)
self.assertEqual(tensor2.expand(4, 8, 5).size(), target)
self.assertEqual(tensor2.expand(target).size(), target)
# test double expand
self.assertEqual(tensor2.expand(1, 5).expand(2, 2, 5), tensor2.repeat(2, 2, 1))
# test non-contiguous
noncontig = torch.randn(5, 2, 1, 3)[:, 0]
self.assertFalse(noncontig.is_contiguous())
self.assertEqual(noncontig.expand(2, 5, 4, 3), noncontig.contiguous().repeat(2, 1, 4, 1))
# make sure it's compatible with unsqueeze
expanded = tensor2.expand(1, 1, 5)
unsqueezed = tensor2.unsqueeze(0).unsqueeze(1)
self.assertEqual(expanded, unsqueezed)
self.assertEqual(expanded.stride(), unsqueezed.stride())
# test -1 as target size
self.assertEqual(tensor.expand(4, -1, 5), tensor.expand(4, 8, 5))
self.assertRaises(RuntimeError, lambda: tensor2.expand(-1, -1))
# test expanding empty to empty
self.assertEqual(torch.zeros(0).expand((0,)), torch.zeros(0))
def test_repeat(self):
initial_shape = (8, 4)
tensor = torch.rand(*initial_shape)
size = (3, 1, 1)
torchSize = torch.Size(size)
target = [3, 8, 4]
self.assertEqual(tensor.repeat(*size).size(), target, 'Error in repeat')
self.assertEqual(tensor.repeat(torchSize).size(), target,
'Error in repeat using LongStorage')
result = tensor.repeat(*size)
self.assertEqual(result.size(), target, 'Error in repeat using result')
result = tensor.repeat(torchSize)
self.assertEqual(result.size(), target, 'Error in repeat using result and LongStorage')
self.assertEqual(result.mean(0).view(8, 4), tensor, 'Error in repeat (not equal)')
zeroDimTarget = torch.Size([24, 0])
self.assertEqual(tensor.repeat((3, 0)).size(), zeroDimTarget, "Error when calling with 0 repeats")
def test_repeat_interleave(self):
x = torch.tensor([0, 1, 2, 3])
expected = torch.tensor([1, 2, 2, 3, 3, 3])
self.assertEqual(torch.repeat_interleave(x), expected)
with self.assertRaises(RuntimeError):
torch.repeat_interleave(torch.arange(4).reshape(2, 2))
with self.assertRaises(RuntimeError):
torch.repeat_interleave(torch.arange(4.0))
with self.assertRaises(RuntimeError):
torch.repeat_interleave(torch.tensor([1, 2, -1, 3, 4]))
y = torch.tensor([[1, 2], [3, 4]])
y1_v1 = torch.repeat_interleave(y, 2)
y1_v2 = torch.repeat_interleave(y, torch.tensor(2))
y1_v3 = torch.repeat_interleave(y, torch.tensor([2]))
y1_expect = torch.tensor([1, 1, 2, 2, 3, 3, 4, 4])
self.assertEqual(y1_v1, y1_expect)
self.assertEqual(y1_v2, y1_expect)
self.assertEqual(y1_v3, y1_expect)
y2 = torch.repeat_interleave(y, 3, dim=1)
y2_expect = torch.tensor([[1, 1, 1, 2, 2, 2],
[3, 3, 3, 4, 4, 4]])
self.assertEqual(y2, y2_expect)
y3 = torch.repeat_interleave(y, torch.tensor([1, 2]), dim=0)
y3_expect = torch.tensor([[1, 2],
[3, 4],
[3, 4]])
self.assertEqual(y3, y3_expect)
with self.assertRaises(RuntimeError):
torch.repeat_interleave(y, torch.tensor([1, 2, 3]), dim=0)
with self.assertRaises(RuntimeError):
torch.repeat_interleave(y, torch.arange(9).reshape(3, 3), dim=0)
# test zero sized dimension
x = torch.zeros((5, 0))
y = torch.repeat_interleave(x, repeats=3, dim=1)
self.assertEqual(y, x.new_zeros(5, 0))
x = torch.tensor([], dtype=torch.int64)
y = torch.repeat_interleave(x, x)
self.assertEqual(y, x)
@unittest.skipIf(not TEST_NUMPY, "Numpy not found")
def test_repeat_tile(self):
initial_shape = (8, 4)
repeats = ((3, 1, 1),
(3,