Skip to content

Commit cb68039

Browse files
Port NumPy typing testing style to PyTorch (pytorch#52408)
Summary: ref: pytorch#16574 Pull Request resolved: pytorch#52408 Reviewed By: anjali411 Differential Revision: D26654687 Pulled By: malfet fbshipit-source-id: 6feb603d8fb03c2ba2a01468bfde1a9901e889fd
1 parent 17bc70e commit cb68039

File tree

3 files changed

+264
-0
lines changed

3 files changed

+264
-0
lines changed

test/run_test.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -172,6 +172,7 @@
172172
'distributions/test_constraints',
173173
'distributions/test_transforms',
174174
'distributions/test_utils',
175+
'test_typing',
175176
]
176177

177178
WINDOWS_BLOCKLIST = [

test/test_typing.py

Lines changed: 149 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,149 @@
1+
# based on NumPy numpy/typing/tests/test_typing.py
2+
3+
import itertools
4+
import os
5+
import re
6+
import shutil
7+
from typing import IO, Dict, List
8+
9+
import pytest
10+
11+
try:
12+
from mypy import api
13+
except ImportError:
14+
NO_MYPY = True
15+
else:
16+
NO_MYPY = False
17+
18+
19+
DATA_DIR = os.path.join(os.path.dirname(__file__), "typing")
20+
REVEAL_DIR = os.path.join(DATA_DIR, "reveal")
21+
MYPY_INI = os.path.join(DATA_DIR, os.pardir, os.pardir, "mypy.ini")
22+
CACHE_DIR = os.path.join(DATA_DIR, ".mypy_cache")
23+
24+
#: A dictionary with file names as keys and lists of the mypy stdout as values.
25+
#: To-be populated by `run_mypy`.
26+
OUTPUT_MYPY: Dict[str, List[str]] = {}
27+
28+
29+
def _key_func(key: str) -> str:
30+
"""Split at the first occurance of the ``:`` character.
31+
32+
Windows drive-letters (*e.g.* ``C:``) are ignored herein.
33+
"""
34+
drive, tail = os.path.splitdrive(key)
35+
return os.path.join(drive, tail.split(":", 1)[0])
36+
37+
38+
@pytest.mark.skipif(NO_MYPY, reason="Mypy is not installed")
39+
@pytest.fixture(scope="module", autouse=True)
40+
def run_mypy() -> None:
41+
"""Clears the cache and run mypy before running any of the typing tests.
42+
43+
The mypy results are cached in `OUTPUT_MYPY` for further use.
44+
45+
"""
46+
if os.path.isdir(CACHE_DIR):
47+
shutil.rmtree(CACHE_DIR)
48+
49+
for directory in (REVEAL_DIR,):
50+
# Run mypy
51+
stdout, stderr, _ = api.run(
52+
[
53+
"--show-absolute-path",
54+
"--config-file",
55+
MYPY_INI,
56+
"--cache-dir",
57+
CACHE_DIR,
58+
directory,
59+
]
60+
)
61+
assert not stderr, directory
62+
stdout = stdout.replace("*", "")
63+
64+
# Parse the output
65+
iterator = itertools.groupby(stdout.split("\n"), key=_key_func)
66+
OUTPUT_MYPY.update((k, list(v)) for k, v in iterator if k)
67+
68+
69+
def get_test_cases(directory):
70+
for root, _, files in os.walk(directory):
71+
for fname in files:
72+
if os.path.splitext(fname)[-1] == ".py":
73+
fullpath = os.path.join(root, fname)
74+
# Use relative path for nice py.test name
75+
relpath = os.path.relpath(fullpath, start=directory)
76+
77+
yield pytest.param(
78+
fullpath,
79+
# Manually specify a name for the test
80+
id=relpath,
81+
)
82+
83+
84+
#: A dictionary with all supported format keys (as keys)
85+
#: and matching values
86+
FORMAT_DICT: Dict[str, str] = {}
87+
88+
89+
def _parse_reveals(file: IO[str]) -> List[str]:
90+
"""Extract and parse all ``" # E: "`` comments from the passed file-like object.
91+
92+
All format keys will be substituted for their respective value from `FORMAT_DICT`,
93+
*e.g.* ``"{float64}"`` becomes ``"numpy.floating[numpy.typing._64Bit]"``.
94+
"""
95+
string = file.read().replace("*", "")
96+
97+
# Grab all `# E:`-based comments
98+
comments_array = list(map(lambda str: str.partition(" # E: ")[2], string.split("\n")))
99+
comments = "/n".join(comments_array)
100+
101+
# Only search for the `{*}` pattern within comments,
102+
# otherwise there is the risk of accidently grabbing dictionaries and sets
103+
key_set = set(re.findall(r"\{(.*?)\}", comments))
104+
kwargs = {
105+
k: FORMAT_DICT.get(k, f"<UNRECOGNIZED FORMAT KEY {k!r}>") for k in key_set
106+
}
107+
fmt_str = comments.format(**kwargs)
108+
109+
return fmt_str.split("/n")
110+
111+
112+
@pytest.mark.skipif(NO_MYPY, reason="Mypy is not installed")
113+
@pytest.mark.parametrize("path", get_test_cases(REVEAL_DIR))
114+
def test_reveal(path):
115+
__tracebackhide__ = True
116+
117+
with open(path) as fin:
118+
lines = _parse_reveals(fin)
119+
120+
output_mypy = OUTPUT_MYPY
121+
assert path in output_mypy
122+
for error_line in output_mypy[path]:
123+
match = re.match(
124+
r"^.+\.py:(?P<lineno>\d+): note: .+$",
125+
error_line,
126+
)
127+
if match is None:
128+
raise ValueError(f"Unexpected reveal line format: {error_line}")
129+
lineno = int(match.group("lineno")) - 1
130+
assert "Revealed type is" in error_line
131+
132+
marker = lines[lineno]
133+
_test_reveal(path, marker, error_line, 1 + lineno)
134+
135+
136+
_REVEAL_MSG = """Reveal mismatch at line {}
137+
138+
Expected reveal: {!r}
139+
Observed reveal: {!r}
140+
"""
141+
142+
143+
def _test_reveal(path: str, reveal: str, expected_reveal: str, lineno: int) -> None:
144+
if reveal not in expected_reveal:
145+
raise AssertionError(_REVEAL_MSG.format(lineno, expected_reveal, reveal))
146+
147+
148+
if __name__ == '__main__':
149+
pytest.main([__file__])
Lines changed: 114 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,114 @@
1+
import torch
2+
from torch.testing._internal.common_utils import TEST_NUMPY
3+
if TEST_NUMPY:
4+
import numpy as np
5+
6+
# From the docs, there are quite a few ways to create a tensor:
7+
# https://pytorch.org/docs/stable/tensors.html
8+
9+
# torch.tensor()
10+
reveal_type(torch.tensor([[0.1, 1.2], [2.2, 3.1], [4.9, 5.2]])) # E: torch.tensor.Tensor
11+
reveal_type(torch.tensor([0, 1])) # E: torch.tensor.Tensor
12+
reveal_type(torch.tensor([[0.11111, 0.222222, 0.3333333]],
13+
dtype=torch.float64,
14+
device=torch.device('cuda:0'))) # E: torch.tensor.Tensor
15+
reveal_type(torch.tensor(3.14159)) # E: torch.tensor.Tensor
16+
17+
# torch.sparse_coo_tensor
18+
i = torch.tensor([[0, 1, 1],
19+
[2, 0, 2]]) # E: torch.tensor.Tensor
20+
v = torch.tensor([3, 4, 5], dtype=torch.float32) # E: torch.tensor.Tensor
21+
reveal_type(torch.sparse_coo_tensor(i, v, [2, 4])) # E: torch.tensor.Tensor
22+
reveal_type(torch.sparse_coo_tensor(i, v)) # E: torch.tensor.Tensor
23+
reveal_type(torch.sparse_coo_tensor(i, v, [2, 4],
24+
dtype=torch.float64,
25+
device=torch.device('cuda:0'))) # E: torch.tensor.Tensor
26+
reveal_type(torch.sparse_coo_tensor(torch.empty([1, 0]), [], [1])) # E: torch.tensor.Tensor
27+
reveal_type(torch.sparse_coo_tensor(torch.empty([1, 0]),
28+
torch.empty([0, 2]), [1, 2])) # E: torch.tensor.Tensor
29+
30+
# torch.as_tensor
31+
if TEST_NUMPY:
32+
a = np.array([1, 2, 3])
33+
reveal_type(torch.as_tensor(a)) # E: torch.tensor.Tensor
34+
reveal_type(torch.as_tensor(a, device=torch.device('cuda'))) # E: torch.tensor.Tensor
35+
36+
# torch.as_strided
37+
x = torch.randn(3, 3)
38+
reveal_type(torch.as_strided(x, (2, 2), (1, 2))) # E: torch.tensor.Tensor
39+
reveal_type(torch.as_strided(x, (2, 2), (1, 2), 1)) # E: torch.tensor.Tensor
40+
41+
# torch.from_numpy
42+
if TEST_NUMPY:
43+
a = np.array([1, 2, 3])
44+
reveal_type(torch.from_numpy(a)) # E: torch.tensor.Tensor
45+
46+
# torch.zeros/zeros_like
47+
reveal_type(torch.zeros(2, 3)) # E: torch.tensor.Tensor
48+
reveal_type(torch.zeros(5)) # E: torch.tensor.Tensor
49+
reveal_type(torch.zeros_like(torch.empty(2, 3))) # E: torch.tensor.Tensor
50+
51+
# torch.ones/ones_like
52+
reveal_type(torch.ones(2, 3)) # E: torch.tensor.Tensor
53+
reveal_type(torch.ones(5)) # E: torch.tensor.Tensor
54+
reveal_type(torch.ones_like(torch.empty(2, 3))) # E: torch.tensor.Tensor
55+
56+
# torch.arange
57+
reveal_type(torch.arange(5)) # E: torch.tensor.Tensor
58+
reveal_type(torch.arange(1, 4)) # E: torch.tensor.Tensor
59+
reveal_type(torch.arange(1, 2.5, 0.5)) # E: torch.tensor.Tensor
60+
61+
# torch.range
62+
reveal_type(torch.range(1, 4)) # E: torch.tensor.Tensor
63+
reveal_type(torch.range(1, 4, 0.5)) # E: torch.tensor.Tensor
64+
65+
# torch.linspace
66+
reveal_type(torch.linspace(3, 10, steps=5)) # E: torch.tensor.Tensor
67+
reveal_type(torch.linspace(-10, 10, steps=5)) # E: torch.tensor.Tensor
68+
reveal_type(torch.linspace(start=-10, end=10, steps=5)) # E: torch.tensor.Tensor
69+
reveal_type(torch.linspace(start=-10, end=10, steps=1)) # E: torch.tensor.Tensor
70+
71+
# torch.logspace
72+
reveal_type(torch.logspace(start=-10, end=10, steps=5)) # E: torch.tensor.Tensor
73+
reveal_type(torch.logspace(start=0.1, end=1.0, steps=5)) # E: torch.tensor.Tensor
74+
reveal_type(torch.logspace(start=0.1, end=1.0, steps=1)) # E: torch.tensor.Tensor
75+
reveal_type(torch.logspace(start=2, end=2, steps=1, base=2)) # E: torch.tensor.Tensor
76+
77+
# torch.eye
78+
reveal_type(torch.eye(3)) # E: torch.tensor.Tensor
79+
80+
# torch.empty/empty_like/empty_strided
81+
reveal_type(torch.empty(2, 3)) # E: torch.tensor.Tensor
82+
reveal_type(torch.empty_like(torch.empty(2, 3), dtype=torch.int64)) # E: torch.tensor.Tensor
83+
reveal_type(torch.empty_strided((2, 3), (1, 2))) # E: torch.tensor.Tensor
84+
85+
# torch.full/full_like
86+
reveal_type(torch.full((2, 3), 3.141592)) # E: torch.tensor.Tensor
87+
reveal_type(torch.full_like(torch.full((2, 3), 3.141592), 2.71828)) # E: torch.tensor.Tensor
88+
89+
# torch.quantize_per_tensor
90+
reveal_type(torch.quantize_per_tensor(torch.tensor([-1.0, 0.0, 1.0, 2.0]), 0.1, 10, torch.quint8)) # E: torch.tensor.Tensor
91+
92+
# torch.quantize_per_channel
93+
x = torch.tensor([[-1.0, 0.0], [1.0, 2.0]])
94+
quant = torch.quantize_per_channel(x, torch.tensor([0.1, 0.01]), torch.tensor([10, 0]), 0, torch.quint8)
95+
reveal_type(x) # E: torch.tensor.Tensor
96+
97+
# torch.dequantize
98+
reveal_type(torch.dequantize(x)) # E: torch.tensor.Tensor
99+
100+
# torch.complex
101+
real = torch.tensor([1, 2], dtype=torch.float32)
102+
imag = torch.tensor([3, 4], dtype=torch.float32)
103+
reveal_type(torch.complex(real, imag)) # E: torch.tensor.Tensor
104+
105+
# torch.polar
106+
abs = torch.tensor([1, 2], dtype=torch.float64)
107+
pi = torch.acos(torch.zeros(1)).item() * 2
108+
angle = torch.tensor([pi / 2, 5 * pi / 4], dtype=torch.float64)
109+
reveal_type(torch.polar(abs, angle)) # E: torch.tensor.Tensor
110+
111+
# torch.heaviside
112+
inp = torch.tensor([-1.5, 0, 2.0])
113+
values = torch.tensor([0.5])
114+
reveal_type(torch.heaviside(inp, values)) # E: torch.tensor.Tensor

0 commit comments

Comments
 (0)