Skip to content

Commit 0334414

Browse files
justinchubyashrit-ms
authored andcommitted
Target py310 and modernize codebase with ruff (#23401)
Change `target-version = "py310"` and modernize the code base with ruff.
1 parent 87341ac commit 0334414

File tree

268 files changed

+1206
-1372
lines changed

Some content is hidden

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

268 files changed

+1206
-1372
lines changed

csharp/tools/MauiModelTester/create_test_data.py

+4-5
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,6 @@
22
import shutil
33
import sys
44
from pathlib import Path
5-
from typing import Dict, List, Optional
65

76
import numpy as np
87

@@ -84,7 +83,7 @@ def parse_args():
8483
return args
8584

8685

87-
def create_existing_data_map(pb_files: List[Path]):
86+
def create_existing_data_map(pb_files: list[Path]):
8887
import onnx_test_data_utils as data_utils
8988

9089
data_map = {}
@@ -98,9 +97,9 @@ def create_existing_data_map(pb_files: List[Path]):
9897

9998
def add_model_and_test_data_to_app(
10099
model_path: Path,
101-
symbolic_dims: Optional[Dict[str, int]] = None,
102-
input_map: Optional[Dict[str, np.ndarray]] = None,
103-
output_map: Optional[Dict[str, np.ndarray]] = None,
100+
symbolic_dims: dict[str, int] | None = None,
101+
input_map: dict[str, np.ndarray] | None = None,
102+
output_map: dict[str, np.ndarray] | None = None,
104103
):
105104
import ort_test_dir_utils as utils
106105

onnxruntime/python/backend/backend_rep.py

-2
Original file line numberDiff line numberDiff line change
@@ -6,8 +6,6 @@
66
Implements ONNX's backend API.
77
"""
88

9-
from typing import Any, Tuple # noqa: F401
10-
119
from onnx.backend.base import BackendRep
1210

1311
from onnxruntime import RunOptions

onnxruntime/python/onnxruntime_inference_collection.py

+3-2
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,8 @@
99
import os
1010
import typing
1111
import warnings
12-
from typing import Any, Sequence
12+
from collections.abc import Sequence
13+
from typing import Any
1314

1415
from onnxruntime.capi import _pybind_state as C
1516

@@ -143,7 +144,7 @@ def set_provider_options(name, options):
143144
if not all([isinstance(options_for_provider, dict) for options_for_provider in provider_options]):
144145
raise ValueError("'provider_options' values must be dicts.")
145146

146-
for name, options in zip(providers, provider_options):
147+
for name, options in zip(providers, provider_options, strict=False):
147148
set_provider_options(name, options)
148149

149150
else:

onnxruntime/python/tools/custom_op_wrapper/create_custom_op_wrapper.py

+3-4
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,6 @@
2222
import os
2323
import sys
2424
from dataclasses import dataclass
25-
from typing import List, Optional, Union
2625

2726
import onnx
2827
from onnx import TensorProto, helper
@@ -65,7 +64,7 @@ class IOInfo:
6564
index: int
6665
name: str
6766
elem_type: TensorProto.DataType
68-
shape: Optional[List[Union[int, str]]]
67+
shape: list[int | str] | None
6968

7069

7170
def str_is_int(string: str) -> bool:
@@ -76,7 +75,7 @@ def str_is_int(string: str) -> bool:
7675
return False
7776

7877

79-
def parse_shape(shape_str: str) -> Optional[List[Union[int, str]]]:
78+
def parse_shape(shape_str: str) -> list[int | str] | None:
8079
try:
8180
shape = [int(s) if str_is_int(s) else s for s in shape_str.split(",")]
8281
except ValueError:
@@ -204,7 +203,7 @@ def parse_arguments() -> argparse.Namespace:
204203
return parser.parse_args()
205204

206205

207-
def get_attributes(attr_data_info: List[List[str]]):
206+
def get_attributes(attr_data_info: list[list[str]]):
208207
if not attr_data_info:
209208
return {}
210209

onnxruntime/python/tools/kernel_explorer/kernels/kernel_explorer.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -13,11 +13,11 @@
1313
import sys
1414
from abc import abstractmethod
1515
from argparse import Action, ArgumentParser
16+
from collections.abc import Callable
1617
from contextlib import contextmanager
1718
from dataclasses import dataclass
1819
from fnmatch import fnmatch
1920
from functools import wraps
20-
from typing import Callable
2121

2222
build_dir = os.environ.get("KERNEL_EXPLORER_BUILD_DIR", None)
2323
if build_dir is None:

onnxruntime/python/tools/offline_tuning.py

+5-5
Original file line numberDiff line numberDiff line change
@@ -7,11 +7,11 @@
77
import sys
88
from collections import OrderedDict
99
from pprint import pprint
10-
from typing import Any, Dict, List
10+
from typing import Any
1111

1212
import onnx
1313

14-
TuningResults = Dict[str, Any]
14+
TuningResults = dict[str, Any]
1515

1616
_TUNING_RESULTS_KEY = "tuning_results"
1717

@@ -32,7 +32,7 @@ def extract(model: onnx.ModelProto):
3232
return json.loads(tuning_results_prop.value)
3333

3434

35-
def embed(model: onnx.ModelProto, tuning_results: List[TuningResults], overwrite=False):
35+
def embed(model: onnx.ModelProto, tuning_results: list[TuningResults], overwrite=False):
3636
idx = _find_tuning_results_in_props(model.metadata_props)
3737
assert overwrite or idx <= 0, "the supplied onnx file already have tuning results embedded!"
3838

@@ -47,7 +47,7 @@ def embed(model: onnx.ModelProto, tuning_results: List[TuningResults], overwrite
4747

4848
class Merger:
4949
class EpAndValidators:
50-
def __init__(self, ep: str, validators: Dict[str, str]):
50+
def __init__(self, ep: str, validators: dict[str, str]):
5151
self.ep = ep
5252
self.validators = copy.deepcopy(validators)
5353
self.key = (ep, tuple(sorted(validators.items())))
@@ -61,7 +61,7 @@ def __eq__(self, other):
6161
def __init__(self):
6262
self.ev_to_results = OrderedDict()
6363

64-
def merge(self, tuning_results: List[TuningResults]):
64+
def merge(self, tuning_results: list[TuningResults]):
6565
for trs in tuning_results:
6666
self._merge_one(trs)
6767

onnxruntime/python/tools/quantization/base_quantizer.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@
44
# license information.
55
# --------------------------------------------------------------------------
66
import logging
7-
from typing import Any, Dict
7+
from typing import Any
88

99
import numpy as np
1010
import onnx
@@ -36,7 +36,7 @@
3636

3737

3838
class QuantizationParams:
39-
def __init__(self, **data: Dict[str, Any]):
39+
def __init__(self, **data: dict[str, Any]):
4040
self.data = {}
4141
for k, v in data.items():
4242
if not isinstance(k, str):

onnxruntime/python/tools/quantization/calibrate.py

+24-20
Original file line numberDiff line numberDiff line change
@@ -9,9 +9,9 @@
99
import itertools
1010
import os
1111
import uuid
12+
from collections.abc import Sequence
1213
from enum import Enum
1314
from pathlib import Path
14-
from typing import Dict, Optional, Sequence, Tuple, Union
1515

1616
import numpy as np
1717
import onnx
@@ -39,7 +39,7 @@ def rel_entr(pk: np.ndarray, qk: np.ndarray) -> np.ndarray:
3939
def entropy(
4040
pk: np.ndarray,
4141
qk: np.ndarray,
42-
base: Optional[float] = None,
42+
base: float | None = None,
4343
axis: int = 0,
4444
) -> np.ndarray:
4545
"""
@@ -100,7 +100,7 @@ def to_dict(self):
100100

101101

102102
class TensorsData:
103-
def __init__(self, calibration_method, data: Dict[str, Union[TensorData, Tuple]]):
103+
def __init__(self, calibration_method, data: dict[str, TensorData | tuple]):
104104
self.calibration_method = calibration_method
105105
self.data = {}
106106
for k, v in data.items():
@@ -187,8 +187,8 @@ def set_range(self, start_index: int, end_index: int):
187187
class CalibraterBase:
188188
def __init__(
189189
self,
190-
model_path: Union[str, Path],
191-
op_types_to_calibrate: Optional[Sequence[str]] = None,
190+
model_path: str | Path,
191+
op_types_to_calibrate: Sequence[str] | None = None,
192192
augmented_model_path="augmented_model.onnx",
193193
symmetric=False,
194194
use_external_data_format=False,
@@ -297,8 +297,8 @@ def compute_data(self) -> TensorsData:
297297
class MinMaxCalibrater(CalibraterBase):
298298
def __init__(
299299
self,
300-
model_path: Union[str, Path],
301-
op_types_to_calibrate: Optional[Sequence[str]] = None,
300+
model_path: str | Path,
301+
op_types_to_calibrate: Sequence[str] | None = None,
302302
augmented_model_path="augmented_model.onnx",
303303
symmetric=False,
304304
use_external_data_format=False,
@@ -476,7 +476,8 @@ def compute_data(self) -> TensorsData:
476476

477477
output_names = [self.infer_session.get_outputs()[i].name for i in range(len(self.intermediate_outputs[0]))]
478478
output_dicts_list = [
479-
dict(zip(output_names, intermediate_output)) for intermediate_output in self.intermediate_outputs
479+
dict(zip(output_names, intermediate_output, strict=False))
480+
for intermediate_output in self.intermediate_outputs
480481
]
481482

482483
merged_output_dict = {}
@@ -507,7 +508,9 @@ def compute_data(self) -> TensorsData:
507508
else:
508509
pairs.append(tuple([min_value_array, max_value_array]))
509510

510-
new_calibrate_tensors_range = TensorsData(CalibrationMethod.MinMax, dict(zip(calibrate_tensor_names, pairs)))
511+
new_calibrate_tensors_range = TensorsData(
512+
CalibrationMethod.MinMax, dict(zip(calibrate_tensor_names, pairs, strict=False))
513+
)
511514
if self.calibrate_tensors_range:
512515
self.calibrate_tensors_range = self.merge_range(self.calibrate_tensors_range, new_calibrate_tensors_range)
513516
else:
@@ -519,8 +522,8 @@ def compute_data(self) -> TensorsData:
519522
class HistogramCalibrater(CalibraterBase):
520523
def __init__(
521524
self,
522-
model_path: Union[str, Path],
523-
op_types_to_calibrate: Optional[Sequence[str]] = None,
525+
model_path: str | Path,
526+
op_types_to_calibrate: Sequence[str] | None = None,
524527
augmented_model_path="augmented_model.onnx",
525528
use_external_data_format=False,
526529
method="percentile",
@@ -608,7 +611,8 @@ def collect_data(self, data_reader: CalibrationDataReader):
608611
raise ValueError("No data is collected.")
609612

610613
output_dicts_list = [
611-
dict(zip(output_names, intermediate_output)) for intermediate_output in self.intermediate_outputs
614+
dict(zip(output_names, intermediate_output, strict=False))
615+
for intermediate_output in self.intermediate_outputs
612616
]
613617

614618
merged_dict = {}
@@ -653,8 +657,8 @@ def compute_data(self) -> TensorsData:
653657
class EntropyCalibrater(HistogramCalibrater):
654658
def __init__(
655659
self,
656-
model_path: Union[str, Path],
657-
op_types_to_calibrate: Optional[Sequence[str]] = None,
660+
model_path: str | Path,
661+
op_types_to_calibrate: Sequence[str] | None = None,
658662
augmented_model_path="augmented_model.onnx",
659663
use_external_data_format=False,
660664
method="entropy",
@@ -687,8 +691,8 @@ def __init__(
687691
class PercentileCalibrater(HistogramCalibrater):
688692
def __init__(
689693
self,
690-
model_path: Union[str, Path],
691-
op_types_to_calibrate: Optional[Sequence[str]] = None,
694+
model_path: str | Path,
695+
op_types_to_calibrate: Sequence[str] | None = None,
692696
augmented_model_path="augmented_model.onnx",
693697
use_external_data_format=False,
694698
method="percentile",
@@ -721,8 +725,8 @@ def __init__(
721725
class DistributionCalibrater(HistogramCalibrater):
722726
def __init__(
723727
self,
724-
model_path: Union[str, Path],
725-
op_types_to_calibrate: Optional[Sequence[str]] = None,
728+
model_path: str | Path,
729+
op_types_to_calibrate: Sequence[str] | None = None,
726730
augmented_model_path="augmented_model.onnx",
727731
use_external_data_format=False,
728732
method="distribution",
@@ -1168,8 +1172,8 @@ def get_entropy_threshold(self, histogram, num_quantized_bins):
11681172

11691173

11701174
def create_calibrator(
1171-
model: Union[str, Path],
1172-
op_types_to_calibrate: Optional[Sequence[str]] = None,
1175+
model: str | Path,
1176+
op_types_to_calibrate: Sequence[str] | None = None,
11731177
augmented_model_path="augmented_model.onnx",
11741178
calibrate_method=CalibrationMethod.MinMax,
11751179
use_external_data_format=False,

onnxruntime/python/tools/quantization/matmul_bnb4_quantizer.py

+3-4
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,6 @@
77
import argparse
88
import logging
99
import os
10-
from typing import List, Tuple
1110

1211
import numpy as np
1312
import numpy.typing as npt
@@ -44,7 +43,7 @@ def __init__(self, model: ModelProto, quant_type: int, block_size: int, nodes_to
4443
self.nodes_to_exclude = set(nodes_to_exclude)
4544

4645
@staticmethod
47-
def __get_initializer(name, graph_path: List[GraphProto]) -> Tuple[TensorProto, GraphProto]:
46+
def __get_initializer(name, graph_path: list[GraphProto]) -> tuple[TensorProto, GraphProto]:
4847
for gid in range(len(graph_path) - 1, -1, -1):
4948
graph = graph_path[gid]
5049
for tensor in graph.initializer:
@@ -74,7 +73,7 @@ def bnb4_block_quant(self, fpweight: npt.ArrayLike) -> np.ndarray:
7473

7574
return (packed, absmax)
7675

77-
def _bnb4_matmul_node_weight(self, node: NodeProto, graph_stack: List[GraphProto]) -> NodeProto:
76+
def _bnb4_matmul_node_weight(self, node: NodeProto, graph_stack: list[GraphProto]) -> NodeProto:
7877
"""If the node is MatMul with fp32 const weight, quantize the weight with int4, and return the new node"""
7978

8079
if node.op_type != "MatMul":
@@ -129,7 +128,7 @@ def _bnb4_matmul_node_weight(self, node: NodeProto, graph_stack: List[GraphProto
129128

130129
return matmul_bnb4_node
131130

132-
def _process_subgraph(self, graph_stack: List[GraphProto]):
131+
def _process_subgraph(self, graph_stack: list[GraphProto]):
133132
new_nodes = []
134133
graph = graph_stack[-1]
135134

0 commit comments

Comments
 (0)