Skip to content

Commit 267f82b

Browse files
XuehaiPanpytorchmergebot
authored andcommitted
[BE] Format .ci/ / .github/ / benchmarks/ / functorch/ / tools/ / torchgen/ with ruff format (pytorch#132577)
Pull Request resolved: pytorch#132577 Approved by: https://github.com/malfet
1 parent 04adb74 commit 267f82b

Some content is hidden

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

64 files changed

+210
-233
lines changed

.ci/pytorch/create_test_cert.py

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -45,8 +45,7 @@ def create_cert(path, C, ST, L, O, key):
4545
.not_valid_before(datetime.now(timezone.utc))
4646
.not_valid_after(
4747
# Our certificate will be valid for 10 days
48-
datetime.now(timezone.utc)
49-
+ timedelta(days=10)
48+
datetime.now(timezone.utc) + timedelta(days=10)
5049
)
5150
.add_extension(
5251
x509.BasicConstraints(ca=True, path_length=None),
@@ -91,8 +90,7 @@ def sign_certificate_request(path, csr_cert, ca_cert, private_ca_key):
9190
.not_valid_before(datetime.now(timezone.utc))
9291
.not_valid_after(
9392
# Our certificate will be valid for 10 days
94-
datetime.now(timezone.utc)
95-
+ timedelta(days=10)
93+
datetime.now(timezone.utc) + timedelta(days=10)
9694
# Sign our certificate with our private key
9795
)
9896
.sign(private_ca_key, hashes.SHA256())

.github/scripts/generate_binary_build_matrix.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -409,7 +409,7 @@ def generate_wheels_matrix(
409409
"container_image": WHEEL_CONTAINER_IMAGES[arch_version],
410410
"package_type": package_type,
411411
"pytorch_extra_install_requirements": (
412-
PYTORCH_EXTRA_INSTALL_REQUIREMENTS[arch_version] # fmt: skip
412+
PYTORCH_EXTRA_INSTALL_REQUIREMENTS[arch_version]
413413
if os != "linux-aarch64"
414414
else ""
415415
),
@@ -457,7 +457,7 @@ def generate_wheels_matrix(
457457
".", "_"
458458
),
459459
"pytorch_extra_install_requirements": (
460-
PYTORCH_EXTRA_INSTALL_REQUIREMENTS["12.1"] # fmt: skip
460+
PYTORCH_EXTRA_INSTALL_REQUIREMENTS["12.1"]
461461
if os != "linux" and gpu_arch_type != "xpu"
462462
else ""
463463
),

.github/scripts/trymerge.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1506,7 +1506,7 @@ def checks_to_str(checks: List[Tuple[str, Optional[str]]]) -> str:
15061506

15071507

15081508
def checks_to_markdown_bullets(
1509-
checks: List[Tuple[str, Optional[str], Optional[int]]]
1509+
checks: List[Tuple[str, Optional[str], Optional[int]]],
15101510
) -> List[str]:
15111511
return [
15121512
f"- [{c[0]}]({c[1]})" if c[1] is not None else f"- {c[0]}" for c in checks[:5]

benchmarks/distributed/ddp/diff.py

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -51,9 +51,7 @@ def main():
5151
print()
5252
print(f"{'':>10s}", end="") # noqa: E999
5353
for _ in [75, 95]:
54-
print(
55-
f"{'sec/iter':>16s}{'ex/sec':>10s}{'diff':>10s}", end=""
56-
) # noqa: E999
54+
print(f"{'sec/iter':>16s}{'ex/sec':>10s}{'diff':>10s}", end="") # noqa: E999
5755
print()
5856

5957
# Print measurements

benchmarks/distributed/rpc/rl/launcher.py

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -209,9 +209,8 @@ def main():
209209
x_axis_variables
210210
): # run benchmark for every x axis variable
211211
if len(x_axis_variables) > 1:
212-
args[
213-
args["x_axis_name"]
214-
] = x_axis_variable # set x axis variable for this benchmark iteration
212+
# set x axis variable for this benchmark iteration
213+
args[args["x_axis_name"]] = x_axis_variable
215214
processes = []
216215
start_time = time.time()
217216
for rank in range(args["world_size"]):

benchmarks/dynamo/common.py

Lines changed: 17 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -1391,9 +1391,7 @@ def load(cls, model, example_inputs, device):
13911391
strict=False,
13921392
).module()
13931393
with torch.no_grad():
1394-
so_path = torch._inductor.aot_compile(
1395-
gm, example_args, example_kwargs
1396-
) # type: ignore[arg-type]
1394+
so_path = torch._inductor.aot_compile(gm, example_args, example_kwargs) # type: ignore[arg-type]
13971395

13981396
cls.cache[key] = torch._export.aot_load(so_path, device)
13991397

@@ -1559,12 +1557,10 @@ def _generate_onnx_model_directory(
15591557
return model_path
15601558

15611559
@abc.abstractmethod
1562-
def format_pt_inputs(self, pt_inputs: Any) -> Sequence[torch.Tensor]:
1563-
...
1560+
def format_pt_inputs(self, pt_inputs: Any) -> Sequence[torch.Tensor]: ...
15641561

15651562
@abc.abstractmethod
1566-
def format_pt_outputs(self, pt_outputs: Any) -> Sequence[torch.Tensor]:
1567-
...
1563+
def format_pt_outputs(self, pt_outputs: Any) -> Sequence[torch.Tensor]: ...
15681564

15691565
def adapt_pt_inputs_to_onnx(self, pt_inputs) -> Mapping[str, npt.NDArray]:
15701566
pt_inputs = self.format_pt_inputs(pt_inputs)
@@ -3134,9 +3130,9 @@ def warmup(fn, model, example_inputs, mode, niters=10):
31343130
experiment_kwargs["dynamo_peak_mem"] = dynamo_peak_mem
31353131
experiment_kwargs["dynamo_stats"] = dynamo_stats
31363132
if self.args.profile_dynamo_cache_lookup:
3137-
experiment_kwargs[
3138-
"cache_lookup_latency"
3139-
] = dynamo_cache_lookup_latency
3133+
experiment_kwargs["cache_lookup_latency"] = (
3134+
dynamo_cache_lookup_latency
3135+
)
31403136

31413137
if experiment.func is speedup_experiment_onnx:
31423138
experiment = functools.partial(
@@ -3290,9 +3286,9 @@ def warmup(fn, model, example_inputs, mode, niters=5):
32903286
experiment_kwargs["dynamo_peak_mem"] = dynamo_peak_mem
32913287
experiment_kwargs["dynamo_stats"] = dynamo_stats
32923288
if self.args.profile_dynamo_cache_lookup:
3293-
experiment_kwargs[
3294-
"cache_lookup_latency"
3295-
] = dynamo_cache_lookup_latency
3289+
experiment_kwargs["cache_lookup_latency"] = (
3290+
dynamo_cache_lookup_latency
3291+
)
32963292

32973293
if experiment.func is coverage_experiment:
32983294
ok, total = Stats.reset_counters()
@@ -4324,7 +4320,14 @@ def run(runner, args, original_dir=None):
43244320
runner.skip_models.clear()
43254321

43264322
experiment = null_experiment
4327-
global current_name, current_device, current_batch_size, output_filename, disable_output, optimize_ctx, current_onnx_compiler
4323+
global \
4324+
current_name, \
4325+
current_device, \
4326+
current_batch_size, \
4327+
output_filename, \
4328+
disable_output, \
4329+
optimize_ctx, \
4330+
current_onnx_compiler
43284331
optimize_ctx = contextlib.nullcontext()
43294332

43304333
if args.disable_output:

benchmarks/dynamo/join_results.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22
A tool to merge multiple csv files (generated by torchbench.py/etc) into a single csv file.
33
Performs an outer join based on the benchmark name, filling in any missing data with zeros.
44
"""
5+
56
import argparse
67
import functools
78
import operator

benchmarks/dynamo/microbenchmarks/analyze_templates.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44
55
That file can be fed into this script to generate the minimizes total, weighted matmul time as a function of allowed templates.
66
"""
7+
78
import json
89

910
import click

benchmarks/fastrnns/bench.py

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -214,8 +214,7 @@ def bench(rnn_runners, group_name, print_json=False, sep=" ", **params):
214214
k: {"avg": v.avg_fwd, "std": v.std_fwd, "info": v.info_fwd}
215215
for k, v in results.items()
216216
},
217-
group_name
218-
+ "-backward": {
217+
f"{group_name}-backward": {
219218
k: {"avg": v.avg_bwd, "std": v.std_bwd, "info": v.info_bwd}
220219
for k, v in results.items()
221220
},

benchmarks/gpt_fast/mixtral_moe_quantize.py

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -184,7 +184,5 @@ def forward(self, x, expert_indices):
184184
].to(x.dtype)
185185
expert_outs = torch.einsum(
186186
"tao, taio -> tai", (x1 * x3), w2_weights
187-
) * self.scales2[expert_indices].to(
188-
x.dtype
189-
) # [T, A, D, D]
187+
) * self.scales2[expert_indices].to(x.dtype) # [T, A, D, D]
190188
return expert_outs

benchmarks/instruction_counts/applications/ci.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,7 @@
11
"""Collect instruction counts for continuous integration."""
2+
23
# mypy: ignore-errors
4+
35
import argparse
46
import hashlib
57
import json

benchmarks/instruction_counts/core/api.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,7 @@
11
"""Key enums and structs used to handle data flow within the benchmark."""
2+
23
# mypy: ignore-errors
4+
35
import dataclasses
46
import enum
57
import itertools as it

benchmarks/instruction_counts/core/expand.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,9 @@
22
33
This is mostly string manipulation, with just a bit of importlib magic.
44
"""
5+
56
# mypy: ignore-errors
7+
68
import importlib.abc
79
import importlib.util
810
import itertools as it

benchmarks/instruction_counts/core/types.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,7 @@
11
"""Type annotations for various benchmark objects."""
2+
23
# mypy: ignore-errors
4+
35
from typing import Any, Dict, Optional, Tuple, Union
46

57
from core.api import AutoLabels, GroupedBenchmark, TimerArgs

benchmarks/instruction_counts/definitions/setup.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,7 @@
11
"""Define some common setup blocks which benchmarks can reuse."""
2+
23
# mypy: ignore-errors
4+
35
import enum
46

57
from core.api import GroupedSetup

benchmarks/instruction_counts/execution/runner.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,7 @@
11
"""Run benchmarks while handling parallelism, isolation, and fault tolerance."""
2+
23
# mypy: ignore-errors
4+
35
import math
46
import multiprocessing
57
import subprocess

benchmarks/instruction_counts/execution/work.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,7 @@
11
"""Handle the details of subprocess calls and retries for a given benchmark run."""
2+
23
# mypy: ignore-errors
4+
35
import dataclasses
46
import json
57
import os

benchmarks/instruction_counts/main.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,9 @@
55
components) in future iterations. However this allows us to excercise the
66
underlying benchmark generation infrastructure in the mean time.
77
"""
8+
89
# mypy: ignore-errors
10+
911
import argparse
1012
import sys
1113
from typing import List

benchmarks/instruction_counts/worker/main.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@
1515
Because this file only expects to run in a child context, error handling means
1616
plumbing failures up to the caller, not raising in this process.
1717
"""
18+
1819
import argparse
1920
import dataclasses
2021
import io

benchmarks/operator_benchmark/pt/qrnn_test.py

Lines changed: 12 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -48,14 +48,20 @@ def init(self, I, H, NL, B, D, dtype):
4848
)[0]
4949

5050
x = torch.randn(
51-
sequence_len, batch_size, I # sequence length # batch size
52-
) # Number of features in X
51+
sequence_len, # sequence length
52+
batch_size, # batch size
53+
I, # Number of features in X
54+
)
5355
h = torch.randn(
54-
NL * (D + 1), batch_size, H # layer_num * dir_num # batch size
55-
) # hidden size
56+
NL * (D + 1), # layer_num * dir_num
57+
batch_size, # batch size
58+
H, # hidden size
59+
)
5660
c = torch.randn(
57-
NL * (D + 1), batch_size, H # layer_num * dir_num # batch size
58-
) # hidden size
61+
NL * (D + 1), # layer_num * dir_num
62+
batch_size, # batch size
63+
H, # hidden size
64+
)
5965

6066
self.inputs = {"x": x, "h": h, "c": c}
6167
self.set_module_name("QLSTM")

benchmarks/transformer/better_transformer_vs_mha_functional.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -152,8 +152,8 @@ def run(
152152
result_entry["sequence_length"] = sequence_length
153153
result_entry["n_heads"] = num_heads
154154
result_entry["embed_dim"] = embed_dim
155-
result_entry["time_native_mha_slow(\u00B5s)"] = f"{time_native_mha_slow:.3f}"
156-
result_entry["time_native_mha_fast (\u00B5s)"] = f"{time_native_mha_fast:.3f}"
155+
result_entry["time_native_mha_slow(\u00b5s)"] = f"{time_native_mha_slow:.3f}"
156+
result_entry["time_native_mha_fast (\u00b5s)"] = f"{time_native_mha_fast:.3f}"
157157
result_entry["speedup flash_mha v native_mha"] = f"{speedup_fast_internal:.3f}"
158158
result_entry["padding"] = f"{padding:.3f}"
159159
return result_entry

benchmarks/transformer/sdp.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -82,10 +82,10 @@ def get_entries(self) -> List:
8282
@classmethod
8383
def get_entry_names(cls) -> List[str]:
8484
return [
85-
"nn_mha_time (\u00B5s)",
86-
"compiled_nn_mha_time (\u00B5s)",
87-
"composite_mha_time (\u00B5s)",
88-
"compiled_composite_mha_time (\u00B5s)",
85+
"nn_mha_time (\u00b5s)",
86+
"compiled_nn_mha_time (\u00b5s)",
87+
"composite_mha_time (\u00b5s)",
88+
"compiled_composite_mha_time (\u00b5s)",
8989
]
9090

9191

functorch/dim/dim.py

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -32,8 +32,7 @@ def __del__(self):
3232
if self._vmap_level is not None:
3333
_vmap_active_levels[self._vmap_stack].alive = False # noqa: F821
3434
while (
35-
not _vmap_levels[-1].alive
36-
and current_level() == _vmap_levels[-1].level # noqa: F821
35+
not _vmap_levels[-1].alive and current_level() == _vmap_levels[-1].level # noqa: F821
3736
):
3837
_vmap_decrement_nesting() # noqa: F821
3938
_vmap_levels.pop()

functorch/einops/_parsing.py

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,7 @@
2222
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
2323
SOFTWARE.
2424
"""
25+
2526
from __future__ import annotations
2627

2728
import keyword
@@ -283,16 +284,16 @@ def comma_separate(collection: Collection[Union[str, Collection[str]]]) -> str:
283284
str: the comma-separated string
284285
285286
Examples:
286-
>>> comma_separate(('d0',))
287+
>>> comma_separate(("d0",))
287288
'd0'
288289
289-
>>> comma_separate(('d0', 'd1', 'd2', 'd3'))
290+
>>> comma_separate(("d0", "d1", "d2", "d3"))
290291
'd0, d1, d2, d3'
291292
292-
>>> comma_separate([('d1', 'd4')])
293+
>>> comma_separate([("d1", "d4")])
293294
'(d1, d4)'
294295
295-
>>> comma_separate([('d0',), (), ('d1',), ('d2',), ('d3', 'd4')])
296+
>>> comma_separate([("d0",), (), ("d1",), ("d2",), ("d3", "d4")])
296297
'(d0,), (), (d1,), (d2,), (d3, d4)'
297298
"""
298299
return ", ".join(

functorch/einops/rearrange.py

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -95,7 +95,7 @@ def _create_rearrange_callable(
9595
raise ValueError(f"Unexpected dimension: {dimension}")
9696

9797
def composition_to_dims(
98-
composition: Sequence[Union[List[Union[str, AnonymousAxis]], str]]
98+
composition: Sequence[Union[List[Union[str, AnonymousAxis]], str]],
9999
) -> List[Union[str, Tuple[str, ...]]]:
100100
"""Convert a `ParsedExpression.composition` into a `Tensor.__getitem__` index of strings representing first
101101
class dims."""
@@ -171,31 +171,31 @@ def rearrange(
171171
>>> images = torch.randn((32, 30, 40, 3))
172172
173173
>>> # stack along first (batch) axis, output is a single array
174-
>>> rearrange(images, 'b h w c -> b h w c').shape
174+
>>> rearrange(images, "b h w c -> b h w c").shape
175175
torch.Size([32, 30, 40, 3])
176176
177177
>>> # concatenate images along height (vertical axis), 960 = 32 * 30
178-
>>> rearrange(images, 'b h w c -> (b h) w c').shape
178+
>>> rearrange(images, "b h w c -> (b h) w c").shape
179179
torch.Size([960, 40, 3])
180180
181181
>>> # concatenated images along horizontal axis, 1280 = 32 * 40
182-
>>> rearrange(images, 'b h w c -> h (b w) c').shape
182+
>>> rearrange(images, "b h w c -> h (b w) c").shape
183183
torch.Size([30, 1280, 3])
184184
185185
>>> # reordered axes to "b c h w" format for deep learning
186-
>>> rearrange(images, 'b h w c -> b c h w').shape
186+
>>> rearrange(images, "b h w c -> b c h w").shape
187187
torch.Size([32, 3, 30, 40])
188188
189189
>>> # flattened each image into a vector, 3600 = 30 * 40 * 3
190-
>>> rearrange(images, 'b h w c -> b (c h w)').shape
190+
>>> rearrange(images, "b h w c -> b (c h w)").shape
191191
torch.Size([32, 3600])
192192
193193
>>> # split each image into 4 smaller (top-left, top-right, bottom-left, bottom-right), 128 = 32 * 2 * 2
194-
>>> rearrange(images, 'b (h1 h) (w1 w) c -> (b h1 w1) h w c', h1=2, w1=2).shape
194+
>>> rearrange(images, "b (h1 h) (w1 w) c -> (b h1 w1) h w c", h1=2, w1=2).shape
195195
torch.Size([128, 15, 20, 3])
196196
197197
>>> # space-to-depth operation
198-
>>> rearrange(images, 'b (h h1) (w w1) c -> b h w (c h1 w1)', h1=2, w1=2).shape
198+
>>> rearrange(images, "b (h h1) (w w1) c -> b h w (c h1 w1)", h1=2, w1=2).shape
199199
torch.Size([32, 15, 20, 12])
200200
"""
201201
if not isinstance(tensor, torch.Tensor):

0 commit comments

Comments
 (0)