Skip to content

Commit aa95618

Browse files
cyyeverpytorchmergebot
authored andcommitted
[2/N] Apply py39 ruff fixes (pytorch#141938)
Fixes #ISSUE_NUMBER Pull Request resolved: pytorch#141938 Approved by: https://github.com/ezyang
1 parent 653efe1 commit aa95618

16 files changed

+53
-62
lines changed

tools/pyi/gen_pyi.py

Lines changed: 0 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1063,13 +1063,6 @@ def replace_special_case(hint: str) -> str:
10631063
# NB: Keep this in sync with enum in aten/src/ATen/core/Reduction.h
10641064
hint = hint.replace("at::Reduction::Mean", "1")
10651065
hint = hint.replace(": Tensor = None", ": Optional[Tensor] = None")
1066-
# Match both:
1067-
# ": Union[Tensor, Tuple[Tensor, ...], List[Tensor]] = None"
1068-
# ": Union[Tuple[Tensor, ...], List[Tensor]] = None"
1069-
hint = hint.replace(
1070-
"Tuple[Tensor, ...], List[Tensor]] = None",
1071-
"Tuple[Tensor, ...], List[Tensor], None] = None",
1072-
)
10731066
return hint
10741067

10751068
docstrs = gather_docstrs()

torchgen/_autoheuristic/ah_tree.py

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
from typing import Any, Dict, List, Optional, Tuple
1+
from typing import Any, Optional
22

33
import numpy as np
44
from sklearn.tree import _tree # type: ignore[import-untyped]
@@ -34,10 +34,10 @@ class DecisionTree:
3434
does not seem to be easy with sklearn.
3535
"""
3636

37-
def __init__(self, sklearn_tree: Any, feature_names: List[str]) -> None:
37+
def __init__(self, sklearn_tree: Any, feature_names: list[str]) -> None:
3838
self.feature_names = feature_names
3939
self.root = self._convert_sklearn_tree(sklearn_tree.tree_)
40-
self.classes_: List[str] = sklearn_tree.classes_
40+
self.classes_: list[str] = sklearn_tree.classes_
4141

4242
def _convert_sklearn_tree(
4343
self, sklearn_tree: Any, node_id: int = 0
@@ -193,9 +193,9 @@ def _apply_single(self, x: Any) -> int:
193193

194194
def codegen(
195195
self,
196-
dummy_col_2_col_val: Dict[str, Tuple[str, Any]],
197-
lines: List[str],
198-
unsafe_leaves: List[int],
196+
dummy_col_2_col_val: dict[str, tuple[str, Any]],
197+
lines: list[str],
198+
unsafe_leaves: list[int],
199199
) -> None:
200200
# generates python code for the decision tree
201201
def codegen_node(node: DecisionTreeNode, depth: int) -> None:
@@ -223,7 +223,7 @@ def codegen_node(node: DecisionTreeNode, depth: int) -> None:
223223
codegen_node(node.right, depth + 1)
224224

225225
def handle_leaf(
226-
node: DecisionTreeNode, indent: str, unsafe_leaves: List[int]
226+
node: DecisionTreeNode, indent: str, unsafe_leaves: list[int]
227227
) -> str:
228228
"""
229229
This generates the code for a leaf node in the decision tree. If the leaf is unsafe, the learned heuristic

torchgen/_autoheuristic/benchmark_runner.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22
import random
33
import time
44
from abc import abstractmethod
5-
from typing import Any, Tuple
5+
from typing import Any
66

77
from tqdm import tqdm # type: ignore[import-untyped]
88

@@ -71,7 +71,7 @@ def run(self) -> None:
7171
def run_benchmark(self, *args: Any) -> None: ...
7272

7373
@abstractmethod
74-
def create_input(self) -> Tuple[Any, ...]: ...
74+
def create_input(self) -> tuple[Any, ...]: ...
7575

7676
def main(self, num_samples: int, num_reps: int) -> None:
7777
for _ in tqdm(range(num_samples)):

torchgen/_autoheuristic/benchmark_utils.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,10 @@
11
import random
2-
from typing import Any, Tuple
2+
from typing import Any
33

44
import torch
55

66

7-
def transpose_tensors(p_transpose_both: float = 0.05) -> Tuple[bool, bool]:
7+
def transpose_tensors(p_transpose_both: float = 0.05) -> tuple[bool, bool]:
88
transpose_both = random.choices(
99
[True, False], [p_transpose_both, 1 - p_transpose_both]
1010
)[0]
@@ -31,7 +31,7 @@ def get_mm_tensors(
3131
transpose_right: bool,
3232
dtype_left: Any,
3333
dtype_right: Any,
34-
) -> Tuple[Any, Any]:
34+
) -> tuple[Any, Any]:
3535
if transpose_left:
3636
a = torch.randn(k, m, dtype=dtype_left).t()
3737
else:

torchgen/_autoheuristic/merge_data.py

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,13 @@
11
import sys
2-
from typing import List
32

43

5-
def merge_txt_files(file_list: List[str], output_file: str) -> None:
4+
def merge_txt_files(file_list: list[str], output_file: str) -> None:
65
if not file_list:
76
print("No input files provided.")
87
return
98

10-
metadata: List[str] = []
11-
content: List[str] = []
9+
metadata: list[str] = []
10+
content: list[str] = []
1211

1312
# Read metadata and content from all files
1413
for file_path in file_list:

torchgen/_autoheuristic/mixed_mm/gen_data_mixed_mm.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@
66

77
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
88

9-
from typing import Any, Tuple
9+
from typing import Any
1010

1111
from benchmark_runner import BenchmarkRunner # type: ignore[import-not-found]
1212
from benchmark_utils import ( # type: ignore[import-not-found]
@@ -33,7 +33,7 @@ class BenchmarkRunnerMixedMM(BenchmarkRunner): # type: ignore[misc, no-any-unim
3333
def __init__(self) -> None:
3434
super().__init__("mixed_mm")
3535

36-
def create_input(self) -> Tuple[Any, ...]:
36+
def create_input(self) -> tuple[Any, ...]:
3737
dtype1, dtype2 = self.get_dtypes()
3838
m, k, n = self.get_m_k_n(dtype1)
3939
transpose_left, transpose_right = False, True
@@ -109,7 +109,7 @@ def get_random_num_small(self) -> int:
109109
else:
110110
return get_random_between_pow2(1, 7)
111111

112-
def get_m_k_n(self, dtype: Any) -> Tuple[int, int, int]:
112+
def get_m_k_n(self, dtype: Any) -> tuple[int, int, int]:
113113
numel_max = 2**31
114114

115115
# repeat until tensors fit in memory

torchgen/_autoheuristic/mixed_mm/test_mixed_mm.py

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,7 @@ def test_mixedmm_a100(self) -> None:
2424
# fmt: off
2525
# This file was generated by AutoHeuristic. Do not modify it manually!
2626
# To regenerate this file, take a look at the steps in the README.md file inside torchgen/_autoheuristic/mixed_mm/
27-
from typing import List, Optional, Tuple
27+
from typing import Optional
2828
2929
from torch._inductor.autoheuristic.autoheuristic_utils import (
3030
AHContext,
@@ -39,7 +39,7 @@ def test_mixedmm_a100(self) -> None:
3939
class MixedMMA100(LearnedHeuristicDecision):
4040
4141
def __init__(self) -> None:
42-
self.choices: List[Choice] = []
42+
self.choices: list[Choice] = []
4343
self.fill_choices()
4444
4545
def check_precondition(self, metadata: AHMetadata, context: AHContext,) -> bool:
@@ -84,7 +84,7 @@ def fill_choices(self) -> None:
8484
def get_name(self) -> str:
8585
return 'mixed_mm'
8686
87-
def get_best_choices(self, context: AHContext) -> Optional[List[Tuple[float, int]]]:
87+
def get_best_choices(self, context: AHContext) -> Optional[list[tuple[float, int]]]:
8888
if str(context.get_value('1LEQmLEQ16')) != 'True':
8989
if context.get_value('m') <= 32.5:
9090
if context.get_value('n') <= 6976.0:
@@ -186,7 +186,7 @@ def test_mixedmm_h100(self) -> None:
186186
# fmt: off
187187
# This file was generated by AutoHeuristic. Do not modify it manually!
188188
# To regenerate this file, take a look at the steps in the README.md file inside torchgen/_autoheuristic/mixed_mm/
189-
from typing import List, Optional, Tuple
189+
from typing import Optional
190190
191191
from torch._inductor.autoheuristic.autoheuristic_utils import (
192192
AHContext,
@@ -201,7 +201,7 @@ def test_mixedmm_h100(self) -> None:
201201
class MixedMMH100(LearnedHeuristicDecision):
202202
203203
def __init__(self) -> None:
204-
self.choices: List[Choice] = []
204+
self.choices: list[Choice] = []
205205
self.fill_choices()
206206
207207
def check_precondition(self, metadata: AHMetadata, context: AHContext,) -> bool:
@@ -245,7 +245,7 @@ def fill_choices(self) -> None:
245245
def get_name(self) -> str:
246246
return 'mixed_mm'
247247
248-
def get_best_choices(self, context: AHContext) -> Optional[List[Tuple[float, int]]]:
248+
def get_best_choices(self, context: AHContext) -> Optional[list[tuple[float, int]]]:
249249
if context.get_value('arith_intensity') <= 15.988086223602295:
250250
if context.get_value('n') <= 25280.0:
251251
if context.get_value('n') <= 1344.0:

torchgen/_autoheuristic/mm/gen_data_mm.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@
66

77
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
88

9-
from typing import Any, Tuple
9+
from typing import Any
1010

1111
from benchmark_runner import BenchmarkRunner # type: ignore[import-not-found]
1212
from benchmark_utils import ( # type: ignore[import-not-found]
@@ -28,7 +28,7 @@ class BenchmarkRunnerMM(BenchmarkRunner): # type: ignore[misc, no-any-unimporte
2828
def __init__(self) -> None:
2929
super().__init__("mm")
3030

31-
def create_input(self) -> Tuple[Any, ...]:
31+
def create_input(self) -> tuple[Any, ...]:
3232
dtype = random.choices([torch.float32, torch.float16, torch.bfloat16])[0]
3333
set_precision(dtype)
3434
m, k, n = self.get_m_k_n(dtype)
@@ -100,7 +100,7 @@ def get_random_dim(self) -> int:
100100
print(f"random_type {distr_type} not supported")
101101
sys.exit(1)
102102

103-
def get_m_k_n(self, dtype: Any) -> Tuple[int, int, int]:
103+
def get_m_k_n(self, dtype: Any) -> tuple[int, int, int]:
104104
numel_max = 2**31
105105

106106
# repeat until tensors fit in memory

torchgen/_autoheuristic/pad_mm/gen_data_pad_mm.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@
55

66
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
77

8-
from typing import Any, Tuple
8+
from typing import Any
99

1010
from benchmark_runner import BenchmarkRunner # type: ignore[import-not-found]
1111
from benchmark_utils import ( # type: ignore[import-not-found]
@@ -30,7 +30,7 @@ class BenchmarkRunnerPadMM(BenchmarkRunner): # type: ignore[misc, no-any-unimpo
3030
def __init__(self) -> None:
3131
super().__init__("pad_mm")
3232

33-
def create_input(self) -> Tuple[Any, ...]:
33+
def create_input(self) -> tuple[Any, ...]:
3434
dtype = self.get_dtype()
3535
set_precision(dtype)
3636
m, k, n = self.get_m_k_n(dtype)
@@ -113,7 +113,7 @@ def get_random_dim(
113113
def is_aligned(self, dim: int, align_size: int) -> bool:
114114
return dim % align_size == 0
115115

116-
def get_m_k_n(self, dtype: Any) -> Tuple[int, int, int]:
116+
def get_m_k_n(self, dtype: Any) -> tuple[int, int, int]:
117117
uniform = random.choices([True, False])[0]
118118
align_size = get_alignment_size_dtype(dtype)
119119

torchgen/_autoheuristic/train_decision.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -531,7 +531,7 @@ def gen_predict_fn_def(self):
531531
"""
532532
Generates the definition of the predict function.
533533
"""
534-
return "def get_best_choices(self, context: AHContext) -> Optional[List[Tuple[float, int]]]:"
534+
return "def get_best_choices(self, context: AHContext) -> Optional[list[tuple[float, int]]]:"
535535

536536
def codegen_boilerplate(
537537
self, heuristic_name, opt_name, threshold, shared_memory, device_capa, classes
@@ -545,7 +545,7 @@ def codegen_boilerplate(
545545
# fmt: off
546546
# This file was generated by AutoHeuristic. Do not modify it manually!
547547
# To regenerate this file, take a look at the steps in the README.md file inside torchgen/_autoheuristic/{opt_name}/
548-
from typing import List, Optional, Tuple
548+
from typing import Optional
549549
550550
from torch._inductor.autoheuristic.autoheuristic_utils import (
551551
AHContext,
@@ -560,7 +560,7 @@ def codegen_boilerplate(
560560
class {heuristic_name}(LearnedHeuristicDecision):
561561
562562
def __init__(self) -> None:
563-
self.choices: List[Choice] = []
563+
self.choices: list[Choice] = []
564564
self.fill_choices()
565565
566566
{self.gen_precondition(opt_name, shared_memory, device_capa)}

torchgen/api/lazy.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -80,7 +80,7 @@ def process_ir_type(
8080
(3) making cpp-reference types into cpp-value types (e.g. vector instead of IntArrayRef)
8181
8282
(1) converts at::Tensors to lazy::Values (which wrap lazy::Nodes, with which Lazy IR represents tensors.)
83-
There is special handling for Optional[Tensor] or List[Tensor], etc- hence 'tensor-like'
83+
There is special handling for Optional[Tensor] or list[Tensor], etc- hence 'tensor-like'
8484
8585
This is incomplete- there are assertions in places that it's expected to need to add
8686
more types as the codegen is used with more operators.

torchgen/api/python.py

Lines changed: 10 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -956,14 +956,13 @@ def argument_type_str_pyi(t: Type) -> str:
956956
ret = "Union[_int, _size]" if t.size is not None else "_size"
957957
elif t.is_tensor_like():
958958
# TODO: this doesn't seem right...
959-
# Tensor?[] currently translates to Optional[Union[Tuple[Tensor, ...], List[Tensor]]]
960-
# It should probably translate to Union[Tuple[Optional[Tensor], ...], List[Optional[Tensor]]]
961-
if isinstance(t.elem, OptionalType):
962-
add_optional = True
959+
# Tensor?[] currently translates to Optional[Union[tuple[Tensor, ...], list[Tensor]]]
960+
# It should probably translate to Union[tuple[Optional[Tensor], ...], list[Optional[Tensor]]]
961+
add_optional = True
963962
ret = (
964-
"Union[Tensor, Tuple[Tensor, ...], List[Tensor]]"
963+
"Union[Tensor, tuple[Tensor, ...], list[Tensor]]"
965964
if t.size is not None
966-
else "Union[Tuple[Tensor, ...], List[Tensor]]"
965+
else "Union[tuple[Tensor, ...], list[Tensor]]"
967966
)
968967
elif str(t.elem) == "float":
969968
ret = "Sequence[_float]"
@@ -1001,7 +1000,7 @@ def return_type_str_pyi(t: Type) -> str:
10011000

10021001
if isinstance(t, ListType):
10031002
inner = return_type_str_pyi(t.elem)
1004-
return f"Tuple[{inner}, ...]"
1003+
return f"tuple[{inner}, ...]"
10051004

10061005
return argument_type_str_pyi(t)
10071006

@@ -1014,7 +1013,7 @@ def returns_structseq_pyi(signature: PythonSignature) -> tuple[str, str] | None:
10141013
# These types are structseq objects which act like named NamedTuples, but
10151014
# the constructor acts like the constructor of tuple. Using typing.NamedTuple
10161015
# does not allow us to override __init__.
1017-
seq_type = f"Tuple[{', '.join(python_returns)}]"
1016+
seq_type = f"tuple[{', '.join(python_returns)}]"
10181017
structseq_def_lines = [
10191018
f"class {structseq_name}({seq_type}):",
10201019
]
@@ -1038,12 +1037,12 @@ def returns_structseq_pyi(signature: PythonSignature) -> tuple[str, str] | None:
10381037
structseq_def = "\n".join(structseq_def_lines)
10391038
# Example:
10401039
# structseq_def = (
1041-
# "class max(Tuple[Tensor, Tensor]):\n"
1040+
# "class max(tuple[Tensor, Tensor]):\n"
10421041
# " @property\n"
10431042
# " def values(self) -> Tensor: ...\n"
10441043
# " @property\n"
10451044
# " def indices(self) -> Tensor: ...\n"
1046-
# " def __new__(cls, sequence: Tuple[Tensor, Tensor]): ...\n"
1045+
# " def __new__(cls, sequence: tuple[Tensor, Tensor]): ...\n"
10471046
# " n_fields: _int = 2",
10481047
# " n_sequeunce_fields: _int = 2",
10491048
# " n_unnamed_fields: _int = 0",
@@ -1060,7 +1059,7 @@ def returns_str_pyi(signature: PythonSignature) -> str:
10601059

10611060
python_returns = [return_type_str_pyi(r.type) for r in signature.returns.returns]
10621061
if len(python_returns) > 1:
1063-
return "Tuple[" + ", ".join(python_returns) + "]"
1062+
return "tuple[" + ", ".join(python_returns) + "]"
10641063
if len(python_returns) == 1:
10651064
return python_returns[0]
10661065
return "None"

torchgen/context.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22

33
import contextlib
44
import functools
5-
from typing import Any, Callable, List, Optional, Tuple, TYPE_CHECKING, TypeVar, Union
5+
from typing import Any, Callable, Optional, TYPE_CHECKING, TypeVar, Union
66

77
import torchgen.local as local
88
from torchgen.model import (
@@ -39,7 +39,7 @@
3939
str,
4040
)
4141

42-
F3 = TypeVar("F3", Tuple[NativeFunction, Any], List[NativeFunction])
42+
F3 = TypeVar("F3", tuple[NativeFunction, Any], list[NativeFunction])
4343

4444

4545
@contextlib.contextmanager

torchgen/executorch/model.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
# Represents all kernels used by an Executorch model.
2-
# It maintains a Dict[OperatorName, Dict[ETKernelKey, BackendMetadata]] structure.
2+
# It maintains a dict[OperatorName, dict[ETKernelKey, BackendMetadata]] structure.
33

44
from __future__ import annotations
55

torchgen/gen_schema_utils.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
from typing import Any, Optional, Tuple, Union
1+
from typing import Any, Optional, Union
22

33
from torchgen.model import (
44
Annotation,
@@ -80,8 +80,8 @@ class FunctionSchemaGen:
8080
@staticmethod
8181
def from_example(
8282
op_name: str,
83-
example_inputs: Tuple[Tuple[str, Any], ...],
84-
example_outputs: Tuple[Any, ...],
83+
example_inputs: tuple[tuple[str, Any], ...],
84+
example_outputs: tuple[Any, ...],
8585
) -> FunctionSchema:
8686
args = []
8787
for name, inp in example_inputs:

0 commit comments

Comments
 (0)