Skip to content

Commit 8229241

Browse files
committed
Upgrade to Python 3.9
1 parent 17dc80e commit 8229241

File tree

187 files changed

+1751
-1709
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

187 files changed

+1751
-1709
lines changed

test/common_extended_utils.py

+12-12
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
import os
22
from collections import defaultdict
33
from numbers import Number
4-
from typing import Any, List
4+
from typing import Any
55

66
import torch
77
from torch.utils._python_dispatch import TorchDispatchMode
@@ -30,7 +30,7 @@ def prod(x):
3030
return res
3131

3232

33-
def matmul_flop(inputs: List[Any], outputs: List[Any]) -> Number:
33+
def matmul_flop(inputs: list[Any], outputs: list[Any]) -> Number:
3434
"""
3535
Count flops for matmul.
3636
"""
@@ -43,7 +43,7 @@ def matmul_flop(inputs: List[Any], outputs: List[Any]) -> Number:
4343
return flop
4444

4545

46-
def addmm_flop(inputs: List[Any], outputs: List[Any]) -> Number:
46+
def addmm_flop(inputs: list[Any], outputs: list[Any]) -> Number:
4747
"""
4848
Count flops for fully connected layers.
4949
"""
@@ -60,7 +60,7 @@ def addmm_flop(inputs: List[Any], outputs: List[Any]) -> Number:
6060
return flops
6161

6262

63-
def bmm_flop(inputs: List[Any], outputs: List[Any]) -> Number:
63+
def bmm_flop(inputs: list[Any], outputs: list[Any]) -> Number:
6464
"""
6565
Count flops for the bmm operation.
6666
"""
@@ -75,9 +75,9 @@ def bmm_flop(inputs: List[Any], outputs: List[Any]) -> Number:
7575

7676

7777
def conv_flop_count(
78-
x_shape: List[int],
79-
w_shape: List[int],
80-
out_shape: List[int],
78+
x_shape: list[int],
79+
w_shape: list[int],
80+
out_shape: list[int],
8181
transposed: bool = False,
8282
) -> Number:
8383
"""
@@ -99,7 +99,7 @@ def conv_flop_count(
9999
return flop
100100

101101

102-
def conv_flop(inputs: List[Any], outputs: List[Any]):
102+
def conv_flop(inputs: list[Any], outputs: list[Any]):
103103
"""
104104
Count flops for convolution.
105105
"""
@@ -110,7 +110,7 @@ def conv_flop(inputs: List[Any], outputs: List[Any]):
110110
return conv_flop_count(x_shape, w_shape, out_shape, transposed=transposed)
111111

112112

113-
def quant_conv_flop(inputs: List[Any], outputs: List[Any]):
113+
def quant_conv_flop(inputs: list[Any], outputs: list[Any]):
114114
"""
115115
Count flops for quantized convolution.
116116
"""
@@ -124,8 +124,8 @@ def transpose_shape(shape):
124124
return [shape[1], shape[0]] + list(shape[2:])
125125

126126

127-
def conv_backward_flop(inputs: List[Any], outputs: List[Any]):
128-
grad_out_shape, x_shape, w_shape = [get_shape(i) for i in inputs[:3]]
127+
def conv_backward_flop(inputs: list[Any], outputs: list[Any]):
128+
grad_out_shape, x_shape, w_shape = (get_shape(i) for i in inputs[:3])
129129
output_mask = inputs[-1]
130130
fwd_transposed = inputs[7]
131131
flop_count = 0
@@ -140,7 +140,7 @@ def conv_backward_flop(inputs: List[Any], outputs: List[Any]):
140140
return flop_count
141141

142142

143-
def scaled_dot_product_flash_attention_flop(inputs: List[Any], outputs: List[Any]):
143+
def scaled_dot_product_flash_attention_flop(inputs: list[Any], outputs: list[Any]):
144144
# FIXME: this needs to count the flops of this kernel
145145
# https://github.com/pytorch/pytorch/blob/207b06d099def9d9476176a1842e88636c1f714f/aten/src/ATen/native/cpu/FlashAttentionKernel.cpp#L52-L267
146146
return 0

test/common_utils.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -285,7 +285,7 @@ def __init__(
285285
**other_parameters,
286286
):
287287
if all(isinstance(input, PIL.Image.Image) for input in [actual, expected]):
288-
actual, expected = [to_image(input) for input in [actual, expected]]
288+
actual, expected = (to_image(input) for input in [actual, expected])
289289

290290
super().__init__(actual, expected, **other_parameters)
291291
self.mae = mae
@@ -418,7 +418,7 @@ def sample_position(values, max_value):
418418

419419
dtype = dtype or torch.float32
420420

421-
h, w = [torch.randint(1, s, (num_boxes,)) for s in canvas_size]
421+
h, w = (torch.randint(1, s, (num_boxes,)) for s in canvas_size)
422422
y = sample_position(h, canvas_size[0])
423423
x = sample_position(w, canvas_size[1])
424424
r = -360 * torch.rand((num_boxes,)) + 180

test/datasets_utils.py

+11-10
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,8 @@
1515
import unittest.mock
1616
import zipfile
1717
from collections import defaultdict
18-
from typing import Any, Callable, Dict, Iterator, List, Optional, Sequence, Tuple, Union
18+
from typing import Any, Callable, Optional, Union
19+
from collections.abc import Iterator, Sequence
1920

2021
import numpy as np
2122

@@ -280,7 +281,7 @@ def test_baz(self):
280281
"download_and_extract_archive",
281282
}
282283

283-
def dataset_args(self, tmpdir: str, config: Dict[str, Any]) -> Sequence[Any]:
284+
def dataset_args(self, tmpdir: str, config: dict[str, Any]) -> Sequence[Any]:
284285
"""Define positional arguments passed to the dataset.
285286
286287
.. note::
@@ -299,7 +300,7 @@ def dataset_args(self, tmpdir: str, config: Dict[str, Any]) -> Sequence[Any]:
299300
"""
300301
return (tmpdir,)
301302

302-
def inject_fake_data(self, tmpdir: str, config: Dict[str, Any]) -> Union[int, Dict[str, Any]]:
303+
def inject_fake_data(self, tmpdir: str, config: dict[str, Any]) -> Union[int, dict[str, Any]]:
303304
"""Inject fake data for dataset into a temporary directory.
304305
305306
During the creation of the dataset the download and extract logic is disabled. Thus, the fake data injected
@@ -323,11 +324,11 @@ def inject_fake_data(self, tmpdir: str, config: Dict[str, Any]) -> Union[int, Di
323324
@contextlib.contextmanager
324325
def create_dataset(
325326
self,
326-
config: Optional[Dict[str, Any]] = None,
327+
config: Optional[dict[str, Any]] = None,
327328
inject_fake_data: bool = True,
328329
patch_checks: Optional[bool] = None,
329330
**kwargs: Any,
330-
) -> Iterator[Tuple[torchvision.datasets.VisionDataset, Dict[str, Any]]]:
331+
) -> Iterator[tuple[torchvision.datasets.VisionDataset, dict[str, Any]]]:
331332
r"""Create the dataset in a temporary directory.
332333
333334
The configuration passed to the dataset is populated to contain at least all parameters with default values.
@@ -616,11 +617,11 @@ class ImageDatasetTestCase(DatasetTestCase):
616617
@contextlib.contextmanager
617618
def create_dataset(
618619
self,
619-
config: Optional[Dict[str, Any]] = None,
620+
config: Optional[dict[str, Any]] = None,
620621
inject_fake_data: bool = True,
621622
patch_checks: Optional[bool] = None,
622623
**kwargs: Any,
623-
) -> Iterator[Tuple[torchvision.datasets.VisionDataset, Dict[str, Any]]]:
624+
) -> Iterator[tuple[torchvision.datasets.VisionDataset, dict[str, Any]]]:
624625
with super().create_dataset(
625626
config=config,
626627
inject_fake_data=inject_fake_data,
@@ -799,7 +800,7 @@ def create_image_folder(
799800
num_examples: int,
800801
size: Optional[Union[Sequence[int], int, Callable[[int], Union[Sequence[int], int]]]] = None,
801802
**kwargs: Any,
802-
) -> List[pathlib.Path]:
803+
) -> list[pathlib.Path]:
803804
"""Create a folder of random images.
804805
805806
Args:
@@ -821,7 +822,7 @@ def create_image_folder(
821822
"""
822823
if size is None:
823824

824-
def size(idx: int) -> Tuple[int, int, int]:
825+
def size(idx: int) -> tuple[int, int, int]:
825826
num_channels = 3
826827
height, width = torch.randint(3, 11, size=(2,), dtype=torch.int).tolist()
827828
return (num_channels, height, width)
@@ -913,7 +914,7 @@ def create_video_folder(
913914
size: Optional[Union[Sequence[int], int, Callable[[int], Union[Sequence[int], int]]]] = None,
914915
fps=25,
915916
**kwargs,
916-
) -> List[pathlib.Path]:
917+
) -> list[pathlib.Path]:
917918
"""Create a folder of random videos.
918919
919920
Args:

test/test_backbone_utils.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
import random
22
from copy import deepcopy
33
from itertools import chain
4-
from typing import Mapping, Sequence
4+
from collections.abc import Mapping, Sequence
55

66
import pytest
77
import torch

test/test_datasets.py

+5-5
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@
1414
import unittest
1515
import xml.etree.ElementTree as ET
1616
import zipfile
17-
from typing import Callable, Tuple, Union
17+
from typing import Callable, Union
1818

1919
import datasets_utils
2020
import numpy as np
@@ -3108,13 +3108,13 @@ class FallingThingsStereoTestCase(datasets_utils.ImageDatasetTestCase):
31083108
FEATURE_TYPES = (PIL.Image.Image, PIL.Image.Image, (np.ndarray, type(None)))
31093109

31103110
@staticmethod
3111-
def _make_dummy_depth_map(root: str, name: str, size: Tuple[int, int]):
3111+
def _make_dummy_depth_map(root: str, name: str, size: tuple[int, int]):
31123112
file = pathlib.Path(root) / name
31133113
image = np.ones((size[0], size[1]), dtype=np.uint8)
31143114
PIL.Image.fromarray(image).save(file)
31153115

31163116
@staticmethod
3117-
def _make_scene_folder(root: str, scene_name: str, size: Tuple[int, int]) -> None:
3117+
def _make_scene_folder(root: str, scene_name: str, size: tuple[int, int]) -> None:
31183118
root = pathlib.Path(root) / scene_name
31193119
os.makedirs(root, exist_ok=True)
31203120
# jpg images
@@ -3185,7 +3185,7 @@ class SceneFlowStereoTestCase(datasets_utils.ImageDatasetTestCase):
31853185

31863186
@staticmethod
31873187
def _create_pfm_folder(
3188-
root: str, name: str, file_name_fn: Callable[..., str], num_examples: int, size: Tuple[int, int]
3188+
root: str, name: str, file_name_fn: Callable[..., str], num_examples: int, size: tuple[int, int]
31893189
) -> None:
31903190
root = pathlib.Path(root) / name
31913191
os.makedirs(root, exist_ok=True)
@@ -3268,7 +3268,7 @@ class InStereo2k(datasets_utils.ImageDatasetTestCase):
32683268
ADDITIONAL_CONFIGS = combinations_grid(split=("train", "test"))
32693269

32703270
@staticmethod
3271-
def _make_scene_folder(root: str, name: str, size: Tuple[int, int]):
3271+
def _make_scene_folder(root: str, name: str, size: tuple[int, int]):
32723272
root = pathlib.Path(root) / name
32733273
os.makedirs(root, exist_ok=True)
32743274

test/test_extended_models.py

+7-7
Original file line numberDiff line numberDiff line change
@@ -116,7 +116,7 @@ def get_models_from_module(module):
116116
)
117117
def test_list_models(module):
118118
a = set(get_models_from_module(module))
119-
b = set(x.replace("quantized_", "") for x in models.list_models(module))
119+
b = {x.replace("quantized_", "") for x in models.list_models(module)}
120120

121121
assert len(b) > 0
122122
assert a == b
@@ -135,7 +135,7 @@ def test_list_models(module):
135135
["*resnet*", "*alexnet*"],
136136
["*resnet*", "*alexnet*", "*not-existing-model-for-test?"],
137137
("*resnet*", "*alexnet*"),
138-
set(["*resnet*", "*alexnet*"]),
138+
{"*resnet*", "*alexnet*"},
139139
],
140140
)
141141
@pytest.mark.parametrize(
@@ -151,7 +151,7 @@ def test_list_models(module):
151151
["resnet34", "*not-existing-model-for-test?"],
152152
["resnet34", "*resnet1*"],
153153
("resnet34", "*resnet1*"),
154-
set(["resnet34", "*resnet1*"]),
154+
{"resnet34", "*resnet1*"},
155155
],
156156
)
157157
def test_list_models_filters(include_filters, exclude_filters):
@@ -167,15 +167,15 @@ def test_list_models_filters(include_filters, exclude_filters):
167167
expected = set()
168168
for include_f in include_filters:
169169
include_f = include_f.strip("*?")
170-
expected = expected | set(x for x in classification_models if include_f in x)
170+
expected = expected | {x for x in classification_models if include_f in x}
171171
else:
172172
expected = classification_models
173173

174174
if exclude_filters:
175175
for exclude_f in exclude_filters:
176176
exclude_f = exclude_f.strip("*?")
177177
if exclude_f != "":
178-
a_exclude = set(x for x in classification_models if exclude_f in x)
178+
a_exclude = {x for x in classification_models if exclude_f in x}
179179
expected = expected - a_exclude
180180

181181
assert expected == actual
@@ -289,11 +289,11 @@ def test_schema_meta_validation(model_fn):
289289
bad_names = []
290290
for w in weights_enum:
291291
actual_fields = set(w.meta.keys())
292-
actual_fields |= set(
292+
actual_fields |= {
293293
("_metrics", dataset, metric_key)
294294
for dataset in w.meta.get("_metrics", {}).keys()
295295
for metric_key in w.meta.get("_metrics", {}).get(dataset, {}).keys()
296-
)
296+
}
297297
missing_fields = expected_fields - actual_fields
298298
unsupported_fields = set(w.meta.keys()) - permitted_fields
299299
if missing_fields or unsupported_fields:

test/test_functional_tensor.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@
33
import math
44
import os
55
from functools import partial
6-
from typing import Sequence
6+
from collections.abc import Sequence
77

88
import numpy as np
99
import PIL.Image

test/test_image.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -398,7 +398,7 @@ def test_read_1_bit_png_consistency(shape, mode, tmpdir):
398398
def test_read_interlaced_png():
399399
imgs = list(get_images(INTERLACED_PNG, ".png"))
400400
with Image.open(imgs[0]) as im1, Image.open(imgs[1]) as im2:
401-
assert not (im1.info.get("interlace") is im2.info.get("interlace"))
401+
assert im1.info.get("interlace") is not im2.info.get("interlace")
402402
img1 = read_image(imgs[0])
403403
img2 = read_image(imgs[1])
404404
assert_equal(img1, img2)
@@ -1040,7 +1040,7 @@ def test_decode_avif_heic_against_pil(decode_fun, mode, pil_mode, filename):
10401040
from torchvision.utils import make_grid
10411041

10421042
g = make_grid([img, from_pil])
1043-
F.to_pil_image(g).save((f"/home/nicolashug/out_images/{filename.name}.{pil_mode}.png"))
1043+
F.to_pil_image(g).save(f"/home/nicolashug/out_images/{filename.name}.{pil_mode}.png")
10441044

10451045
is_decode_heic = getattr(decode_fun, "__name__", getattr(decode_fun, "name", None)) == "decode_heic"
10461046
if mode == ImageReadMode.RGB and not is_decode_heic:

test/test_onnx.py

+3-3
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
import io
22
from collections import OrderedDict
3-
from typing import List, Optional, Tuple
3+
from typing import Optional
44

55
import pytest
66
import torch
@@ -404,7 +404,7 @@ def forward(self_module, images, features):
404404
},
405405
)
406406

407-
def get_image(self, rel_path: str, size: Tuple[int, int]) -> torch.Tensor:
407+
def get_image(self, rel_path: str, size: tuple[int, int]) -> torch.Tensor:
408408
import os
409409

410410
from PIL import Image
@@ -416,7 +416,7 @@ def get_image(self, rel_path: str, size: Tuple[int, int]) -> torch.Tensor:
416416

417417
return F.convert_image_dtype(F.pil_to_tensor(image))
418418

419-
def get_test_images(self) -> Tuple[List[torch.Tensor], List[torch.Tensor]]:
419+
def get_test_images(self) -> tuple[list[torch.Tensor], list[torch.Tensor]]:
420420
return (
421421
[self.get_image("encode_jpeg/grace_hopper_517x606.jpg", (100, 320))],
422422
[self.get_image("fakedata/logos/rgb_pytorch.png", (250, 380))],

test/test_ops.py

+3-3
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@
33
from abc import ABC, abstractmethod
44
from functools import lru_cache
55
from itertools import product
6-
from typing import Callable, List, Tuple
6+
from typing import Callable
77

88
import numpy as np
99
import pytest
@@ -100,7 +100,7 @@ def __init__(self, pool: nn.Module):
100100
super().__init__()
101101
self.pool = pool
102102

103-
def forward(self, imgs: Tensor, boxes: List[Tensor]) -> Tensor:
103+
def forward(self, imgs: Tensor, boxes: list[Tensor]) -> Tensor:
104104
return self.pool(imgs, boxes)
105105

106106

@@ -1485,7 +1485,7 @@ def _run_test(target_fn: Callable, actual_box1, actual_box2, dtypes, atol, expec
14851485
torch.testing.assert_close(out, expected_box, rtol=0.0, check_dtype=False, atol=atol)
14861486

14871487
@staticmethod
1488-
def _run_jit_test(target_fn: Callable, actual_box: List):
1488+
def _run_jit_test(target_fn: Callable, actual_box: list):
14891489
box_tensor = torch.tensor(actual_box, dtype=torch.float)
14901490
expected = target_fn(box_tensor, box_tensor)
14911491
scripted_fn = torch.jit.script(target_fn)

test/test_transforms_v2.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -1298,7 +1298,7 @@ def _compute_affine_matrix(self, *, angle, translate, scale, shear, center):
12981298
rot = math.radians(angle)
12991299
cx, cy = center
13001300
tx, ty = translate
1301-
sx, sy = [math.radians(s) for s in ([shear, 0.0] if isinstance(shear, (int, float)) else shear)]
1301+
sx, sy = (math.radians(s) for s in ([shear, 0.0] if isinstance(shear, (int, float)) else shear))
13021302

13031303
c_matrix = np.array([[1, 0, cx], [0, 1, cy], [0, 0, 1]])
13041304
t_matrix = np.array([[1, 0, tx], [0, 1, ty], [0, 0, 1]])
@@ -4497,7 +4497,7 @@ def test_transform(self, make_input):
44974497

44984498
def _reference_normalize_image(self, image, *, mean, std):
44994499
image = image.numpy()
4500-
mean, std = [np.array(stat, dtype=image.dtype).reshape((-1, 1, 1)) for stat in [mean, std]]
4500+
mean, std = (np.array(stat, dtype=image.dtype).reshape((-1, 1, 1)) for stat in [mean, std])
45014501
return tv_tensors.Image((image - mean) / std)
45024502

45034503
@pytest.mark.parametrize(("mean", "std"), MEANS_STDS)

0 commit comments

Comments
 (0)