Skip to content

Commit 69284f6

Browse files
authored
ruff-rules-for-pyupgrade (#436)
1 parent 4ad9add commit 69284f6

Some content is hidden

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

57 files changed

+448
-498
lines changed

compiler_opt/benchmark/benchmark_chromium.py

Lines changed: 3 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -52,8 +52,6 @@
5252
from compiler_opt.benchmark import gtest_executable_utils
5353
from compiler_opt.benchmark import benchmarking_utils
5454

55-
from typing import List, Dict, Union
56-
5755
FLAGS = flags.FLAGS
5856

5957
test_prefix = './compiler_opt/benchmark/chromium_test_descriptions/'
@@ -110,7 +108,7 @@
110108

111109
def build_chromium_tests(regalloc_advisor: str, chromium_build_path: str,
112110
chromium_source_path: str, depot_tools_path: str,
113-
llvm_build_path: str, tests_to_build: List[str]):
111+
llvm_build_path: str, tests_to_build: list[str]):
114112
"""Builds the chromium test suite
115113
116114
This function will build the specified chromium tests using the specified
@@ -170,9 +168,9 @@ def build_chromium_tests(regalloc_advisor: str, chromium_build_path: str,
170168
ninja_compile_process.wait()
171169

172170

173-
def run_tests(tests_to_run: List[Dict[str, Union[str, List[str]]]],
171+
def run_tests(tests_to_run: list[dict[str, str | list[str]]],
174172
chromium_absolute_build_path: str, num_threads: int,
175-
perf_counters: List[str]):
173+
perf_counters: list[str]):
176174
"""A utility to run a set of chromium tests
177175
178176
This function takes in a list of test descriptions containing the

compiler_opt/benchmark/benchmark_report.py

Lines changed: 7 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -18,31 +18,28 @@
1818
import statistics
1919

2020
from typing import Any
21-
from typing import Dict
22-
from typing import Iterable
23-
from typing import List
24-
from typing import Tuple
21+
from collections.abc import Iterable
2522

2623
from absl import logging
2724

2825
# For each benchmark, and for each counter, capture the recorded values.
29-
PerBenchmarkResults = Dict[str, Dict[str, List[float]]]
26+
PerBenchmarkResults = dict[str, dict[str, list[float]]]
3027

3128
# Benchmark data, as captured by the benchmark json output: a dictionary from
3229
# benchmark names to a list of run results. Each run result is a dictionary of
3330
# key-value pairs, e.g. counter name - value.
34-
BenchmarkRunResults = Dict[str, List[Dict[str, Any]]]
31+
BenchmarkRunResults = dict[str, list[dict[str, Any]]]
3532

3633
# A comparison per benchmark, per counter, capturing the geomean and the stdev
3734
# of the base and experiment values.
38-
ABComparison = Dict[str, Dict[str, Tuple[float, float, float]]]
35+
ABComparison = dict[str, dict[str, tuple[float, float, float]]]
3936

4037

41-
def _geomean(data: List[float]):
38+
def _geomean(data: list[float]):
4239
return math.exp(sum(math.log(x) for x in data) / len(data))
4340

4441

45-
def _stdev(data: List[float]):
42+
def _stdev(data: list[float]):
4643
assert data
4744
return 0.0 if len(data) == 1 else statistics.stdev(data)
4845

@@ -70,7 +67,7 @@ def counters(self):
7067
def raw_measurements(self):
7168
return self._raw_measurements
7269

73-
def counter_means(self, benchmark: str, counter: str) -> Tuple[float, float]:
70+
def counter_means(self, benchmark: str, counter: str) -> tuple[float, float]:
7471
if counter not in self.counters():
7572
raise ValueError('unknown counter')
7673
if benchmark not in self.names():

compiler_opt/benchmark/benchmark_report_converter.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -32,7 +32,7 @@
3232
import csv
3333
import json
3434

35-
from typing import Sequence
35+
from collections.abc import Sequence
3636

3737
from absl import app
3838
from absl import flags

compiler_opt/benchmark/benchmarking_utils.py

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -20,11 +20,9 @@
2020
import tensorflow
2121
import json
2222

23-
from typing import Optional, List
24-
2523

2624
def build_llvm(model_path: str, use_existing_build: bool, llvm_build_path: str,
27-
llvm_source_path: Optional[str]):
25+
llvm_source_path: str | None):
2826
"""Builds LLVM/clang with the specified model and the correct settings
2927
3028
This function invokes CMake with all the correct build flags specified
@@ -72,7 +70,7 @@ def build_llvm(model_path: str, use_existing_build: bool, llvm_build_path: str,
7270
cmake_compile_process.wait()
7371

7472

75-
def run_microbenchmark(executable: str, perf_counters: List[str]):
73+
def run_microbenchmark(executable: str, perf_counters: list[str]):
7674
"""Runs all the tests in a specific google benchmark binary
7775
7876
This function takes in an executable and performance counters according to the

compiler_opt/benchmark/gtest_executable_utils.py

Lines changed: 6 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -18,11 +18,10 @@
1818
import re
1919

2020
from joblib import Parallel, delayed
21-
from typing import Tuple, List, Optional, Dict
2221
from absl import logging
2322

2423

25-
def run_test(test_executable: str, test_name: str, perf_counters: List[str]):
24+
def run_test(test_executable: str, test_name: str, perf_counters: list[str]):
2625
"""Runs a specific test
2726
2827
This function executes a specific test in a gtest executable using
@@ -55,7 +54,7 @@ def run_test(test_executable: str, test_name: str, perf_counters: List[str]):
5554
return decoded_stderr
5655

5756

58-
def parse_perf_stat_output(perf_stat_output: str, perf_counters: List[str]):
57+
def parse_perf_stat_output(perf_stat_output: str, perf_counters: list[str]):
5958
"""Parses raw output from perf stat
6059
6160
This function takes in the raw decoded output from perf stat
@@ -77,7 +76,7 @@ def parse_perf_stat_output(perf_stat_output: str, perf_counters: List[str]):
7776
return counters_dict
7877

7978

80-
def run_and_parse(test_description: Tuple[str, str, List[str]]):
79+
def run_and_parse(test_description: tuple[str, str, list[str]]):
8180
"""Runs a test and processes the output of an individual test
8281
8382
This function takes in a description of an individual test, runs the test
@@ -98,9 +97,9 @@ def run_and_parse(test_description: Tuple[str, str, List[str]]):
9897
return None
9998

10099

101-
def run_test_suite(test_suite_description: Dict[str, List[str]],
102-
test_executable: str, perf_counters: List[str],
103-
num_threads: Optional[int]):
100+
def run_test_suite(test_suite_description: dict[str, list[str]],
101+
test_executable: str, perf_counters: list[str],
102+
num_threads: int | None):
104103
"""Runs an entire test suite
105104
106105
This function takes in a test set description in the form of a path to a JSON

compiler_opt/distributed/buffered_scheduler.py

Lines changed: 8 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -18,17 +18,18 @@
1818
import concurrent.futures
1919
import threading
2020

21-
from typing import Any, Callable, Iterable, List, Optional, Tuple, TypeVar
21+
from typing import Any, TypeVar
22+
from collections.abc import Callable, Iterable
2223

2324
from compiler_opt.distributed import worker
2425

2526
T = TypeVar('T')
2627
W = TypeVar('W')
2728

2829

29-
def schedule(work: List[Callable[[T], worker.WorkerFuture]],
30-
workers: List[T],
31-
buffer=2) -> List[concurrent.futures.Future]:
30+
def schedule(work: list[Callable[[T], worker.WorkerFuture]],
31+
workers: list[T],
32+
buffer=2) -> list[concurrent.futures.Future]:
3233
"""
3334
Assigns work to workers once previous work of the worker are
3435
completed.
@@ -86,8 +87,8 @@ def schedule_on_worker_pool(
8687
action: Callable[[W, T], Any],
8788
jobs: Iterable[T],
8889
worker_pool: worker.WorkerPool,
89-
buffer_size: Optional[int] = None
90-
) -> Tuple[List[W], List[concurrent.futures.Future]]:
90+
buffer_size: int | None = None
91+
) -> tuple[list[W], list[concurrent.futures.Future]]:
9192
"""
9293
Schedule the given action on workers from the given worker pool.
9394
Args:
@@ -111,7 +112,7 @@ def work(w: worker.Worker):
111112
return work
112113

113114
work = [work_factory(job) for job in jobs]
114-
workers: List[W] = worker_pool.get_currently_active()
115+
workers: list[W] = worker_pool.get_currently_active()
115116
return workers, schedule(work, workers,
116117
(worker_pool.get_worker_concurrency()
117118
if buffer_size is None else buffer_size))

compiler_opt/distributed/local/local_worker_manager.py

Lines changed: 7 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -40,7 +40,8 @@
4040

4141
from contextlib import AbstractContextManager
4242
from multiprocessing import connection
43-
from typing import Any, Callable, Dict, List, Optional
43+
from typing import Any
44+
from collections.abc import Callable
4445

4546

4647
@dataclasses.dataclass(frozen=True)
@@ -139,7 +140,7 @@ def __init__(self):
139140
# lock for the msgid -> reply future map. The map will be set to None
140141
# when we stop.
141142
self._lock = threading.Lock()
142-
self._map: Dict[int, concurrent.futures.Future] = {}
143+
self._map: dict[int, concurrent.futures.Future] = {}
143144

144145
# thread draining the pipe
145146
self._pump = threading.Thread(target=self._msg_pump)
@@ -164,7 +165,7 @@ def observer():
164165

165166
def _msg_pump(self):
166167
while True:
167-
task_result: Optional[TaskResult] = self._pipe.recv()
168+
task_result: TaskResult | None = self._pipe.recv()
168169
if task_result is None: # Poison pill fed by observer
169170
break
170171
with self._lock:
@@ -229,7 +230,7 @@ def set_nice(self, val: int):
229230
"""
230231
psutil.Process(self._process.pid).nice(val)
231232

232-
def set_affinity(self, val: List[int]):
233+
def set_affinity(self, val: list[int]):
233234
"""Sets the CPU affinity of the process, this modifies which cores the OS
234235
schedules it on.
235236
"""
@@ -247,7 +248,7 @@ def __dir__(self):
247248

248249

249250
def create_local_worker_pool(worker_cls: 'type[worker.Worker]',
250-
count: Optional[int], *args,
251+
count: int | None, *args,
251252
**kwargs) -> worker.FixedWorkerPool:
252253
"""Create a local worker pool for worker_cls."""
253254
if not count:
@@ -271,7 +272,7 @@ def close_local_worker_pool(pool: worker.FixedWorkerPool):
271272
class LocalWorkerPoolManager(AbstractContextManager):
272273
"""A pool of workers hosted on the local machines, each in its own process."""
273274

274-
def __init__(self, worker_class: 'type[worker.Worker]', count: Optional[int],
275+
def __init__(self, worker_class: 'type[worker.Worker]', count: int | None,
275276
*args, **kwargs):
276277
self._pool = create_local_worker_pool(worker_class, count, *args, **kwargs)
277278

compiler_opt/distributed/worker.py

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,8 @@
1414
"""Common abstraction for a worker contract."""
1515

1616
import abc
17-
from typing import Any, List, Iterable, Optional, Protocol, TypeVar
17+
from typing import Any, Protocol, TypeVar
18+
from collections.abc import Iterable
1819

1920
import gin
2021

@@ -35,7 +36,7 @@ class WorkerPool(metaclass=abc.ABCMeta):
3536

3637
# Issue #155 would strongly-type the return type.
3738
@abc.abstractmethod
38-
def get_currently_active(self) -> List[Any]:
39+
def get_currently_active(self) -> list[Any]:
3940
raise NotImplementedError()
4041

4142
@abc.abstractmethod
@@ -47,7 +48,7 @@ class FixedWorkerPool(WorkerPool):
4748
"""A WorkerPool built from a fixed list of workers."""
4849

4950
# Issue #155 would strongly-type `workers`
50-
def __init__(self, workers: List[Any], worker_concurrency: int = 2):
51+
def __init__(self, workers: list[Any], worker_concurrency: int = 2):
5152
self._workers = workers
5253
self._worker_concurrency = worker_concurrency
5354

@@ -80,7 +81,7 @@ def wait_for(futures: Iterable[WorkerFuture]):
8081
pass
8182

8283

83-
def get_exception(worker_future: WorkerFuture) -> Optional[Exception]:
84+
def get_exception(worker_future: WorkerFuture) -> Exception | None:
8485
assert worker_future.done()
8586
try:
8687
_ = worker_future.result()

compiler_opt/es/blackbox_evaluator.py

Lines changed: 8 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,6 @@
1515

1616
import abc
1717
import concurrent.futures
18-
from typing import List, Optional
1918

2019
from absl import logging
2120
import gin
@@ -36,16 +35,16 @@ def __init__(self, train_corpus: corpus.Corpus):
3635

3736
@abc.abstractmethod
3837
def get_results(
39-
self, pool: FixedWorkerPool, perturbations: List[policy_saver.Policy]
40-
) -> List[concurrent.futures.Future]:
38+
self, pool: FixedWorkerPool, perturbations: list[policy_saver.Policy]
39+
) -> list[concurrent.futures.Future]:
4140
raise NotImplementedError()
4241

4342
@abc.abstractmethod
4443
def set_baseline(self, pool: FixedWorkerPool) -> None:
4544
raise NotImplementedError()
4645

4746
def get_rewards(
48-
self, results: List[concurrent.futures.Future]) -> List[Optional[float]]:
47+
self, results: list[concurrent.futures.Future]) -> list[float | None]:
4948
rewards = [None] * len(results)
5049

5150
for i in range(len(results)):
@@ -74,8 +73,8 @@ def __init__(self, train_corpus: corpus.Corpus,
7473
super().__init__(train_corpus)
7574

7675
def get_results(
77-
self, pool: FixedWorkerPool, perturbations: List[policy_saver.Policy]
78-
) -> List[concurrent.futures.Future]:
76+
self, pool: FixedWorkerPool, perturbations: list[policy_saver.Policy]
77+
) -> list[concurrent.futures.Future]:
7978
if not self._samples:
8079
for _ in range(self._total_num_perturbations):
8180
sample = self._train_corpus.sample(self._num_ir_repeats_within_worker)
@@ -118,11 +117,11 @@ def __init__(self, train_corpus: corpus.Corpus,
118117
self._bb_trace_path = bb_trace_path
119118
self._function_index_path = function_index_path
120119

121-
self._baseline: Optional[float] = None
120+
self._baseline: float | None = None
122121

123122
def get_results(
124-
self, pool: FixedWorkerPool, perturbations: List[policy_saver.Policy]
125-
) -> List[concurrent.futures.Future]:
123+
self, pool: FixedWorkerPool, perturbations: list[policy_saver.Policy]
124+
) -> list[concurrent.futures.Future]:
126125
job_args = [{
127126
'modules': self._train_corpus.module_specs,
128127
'function_index_path': self._function_index_path,

0 commit comments

Comments
 (0)