Skip to content

Commit 754fb83

Browse files
XuehaiPanpytorchmergebot
authored andcommitted
[BE][CI] bump ruff to 0.9.0: string quote styles (pytorch#144569)
Reference: https://docs.astral.sh/ruff/formatter/#f-string-formatting - Change the outer quotes to double quotes for nested f-strings ```diff - f'{", ".join(args)}' + f"{', '.join(args)}" ``` - Change the inner quotes to double quotes for triple f-strings ```diff string = """ - {', '.join(args)} + {", ".join(args)} """ ``` - Join implicitly concatenated strings ```diff - string = "short string " "short string " f"{var}" + string = f"short string short string {var}" ``` Pull Request resolved: pytorch#144569 Approved by: https://github.com/Skylion007 ghstack dependencies: pytorch#146509
1 parent 52f6d4a commit 754fb83

Some content is hidden

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

52 files changed

+135
-135
lines changed

.ci/aarch64_linux/aarch64_wheel_ci_build.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -204,7 +204,7 @@ def parse_arguments():
204204
else:
205205
build_vars += f"BUILD_TEST=0 PYTORCH_BUILD_VERSION={version}.dev{build_date} PYTORCH_BUILD_NUMBER=1 "
206206
elif branch.startswith(("v1.", "v2.")):
207-
build_vars += f"BUILD_TEST=0 PYTORCH_BUILD_VERSION={branch[1:branch.find('-')]} PYTORCH_BUILD_NUMBER=1 "
207+
build_vars += f"BUILD_TEST=0 PYTORCH_BUILD_VERSION={branch[1 : branch.find('-')]} PYTORCH_BUILD_NUMBER=1 "
208208

209209
if enable_mkldnn:
210210
build_ArmComputeLibrary()

.ci/aarch64_linux/build_aarch64_wheel.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -761,7 +761,7 @@ def start_build(
761761
version = host.check_output("cat pytorch/version.txt").strip()[:-2]
762762
build_vars += f"BUILD_TEST=0 PYTORCH_BUILD_VERSION={version}.dev{build_date} PYTORCH_BUILD_NUMBER=1"
763763
if branch.startswith(("v1.", "v2.")):
764-
build_vars += f"BUILD_TEST=0 PYTORCH_BUILD_VERSION={branch[1:branch.find('-')]} PYTORCH_BUILD_NUMBER=1"
764+
build_vars += f"BUILD_TEST=0 PYTORCH_BUILD_VERSION={branch[1 : branch.find('-')]} PYTORCH_BUILD_NUMBER=1"
765765
if host.using_docker():
766766
build_vars += " CMAKE_SHARED_LINKER_FLAGS=-Wl,-z,max-page-size=0x10000"
767767
if enable_mkldnn:

.ci/pytorch/smoke_test/max_autotune.py

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -46,7 +46,9 @@ def train(args, model, device, train_loader, optimizer, epoch):
4646
optimizer.step()
4747
if batch_idx % args.log_interval == 0:
4848
print(
49-
f"Train Epoch: {epoch} [{batch_idx * len(data)}/{len(train_loader.dataset)} ({100. * batch_idx / len(train_loader):.0f}%)]\tLoss: {loss.item():.6f}" # noqa: B950
49+
f"Train Epoch: {epoch} "
50+
f"[{batch_idx * len(data)}/{len(train_loader.dataset)} "
51+
f"({100.0 * batch_idx / len(train_loader):.0f}%)]\tLoss: {loss.item():.6f}"
5052
)
5153
if args.dry_run:
5254
break
@@ -71,7 +73,9 @@ def test(model, device, test_loader):
7173
test_loss /= len(test_loader.dataset)
7274

7375
print(
74-
f"\nTest set: Average loss: {test_loss:.4f}, Accuracy: {correct}/{len(test_loader.dataset)} ({100. * correct / len(test_loader.dataset):.0f}%)\n" # noqa: B950
76+
f"\nTest set: Average loss: {test_loss:.4f}, "
77+
f"Accuracy: {correct}/{len(test_loader.dataset)} "
78+
f"({100.0 * correct / len(test_loader.dataset):.0f}%)\n"
7579
)
7680

7781

.github/scripts/github_utils.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -57,10 +57,10 @@ def gh_fetch_url_and_headers(
5757
print(
5858
f"""{url}
5959
Rate limit exceeded:
60-
Used: {err.headers['X-RateLimit-Used']}
61-
Limit: {err.headers['X-RateLimit-Limit']}
62-
Remaining: {err.headers['X-RateLimit-Remaining']}
63-
Resets at: {err.headers['x-RateLimit-Reset']}"""
60+
Used: {err.headers["X-RateLimit-Used"]}
61+
Limit: {err.headers["X-RateLimit-Limit"]}
62+
Remaining: {err.headers["X-RateLimit-Remaining"]}
63+
Resets at: {err.headers["x-RateLimit-Reset"]}"""
6464
)
6565
else:
6666
print(f"Error fetching {url} {err}")

.github/scripts/trymerge.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -485,7 +485,7 @@ def get_check_run_name_prefix(workflow_run: Any) -> str:
485485
if workflow_run is None:
486486
return ""
487487
else:
488-
return f'{workflow_run["workflow"]["name"]} / '
488+
return f"{workflow_run['workflow']['name']} / "
489489

490490

491491
def is_passing_status(status: Optional[str]) -> bool:
@@ -545,7 +545,7 @@ def add_conclusions(edges: Any) -> None:
545545
if not isinstance(checkrun_node, dict):
546546
warn(f"Expected dictionary, but got {type(checkrun_node)}")
547547
continue
548-
checkrun_name = f'{get_check_run_name_prefix(workflow_run)}{checkrun_node["name"]}'
548+
checkrun_name = f"{get_check_run_name_prefix(workflow_run)}{checkrun_node['name']}"
549549
existing_checkrun = workflow_obj.jobs.get(checkrun_name)
550550
if existing_checkrun is None or not is_passing_status(
551551
existing_checkrun.status

.github/scripts/trymerge_explainer.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -79,7 +79,7 @@ def get_merge_message(
7979
(
8080
"<details><summary>Advanced Debugging</summary>",
8181
"Check the merge workflow status ",
82-
f"<a href=\"{os.getenv('GH_RUN_URL')}\">here</a>",
82+
f'<a href="{os.getenv("GH_RUN_URL")}">here</a>',
8383
"</details>",
8484
)
8585
)

aten/src/ATen/native/transformers/cuda/flash_attn/kernels/generate_kernels.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -103,7 +103,7 @@ def main(output_dir: Optional[str]) -> None:
103103
"-o",
104104
"--output_dir",
105105
required=False,
106-
help="Where to generate the kernels " " will default to the current directory ",
106+
help="Where to generate the kernels will default to the current directory",
107107
)
108108
args = parser.parse_args()
109109
main(args.output_dir)

benchmarks/dynamo/check_accuracy.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -102,15 +102,15 @@ def check_accuracy(actual_csv, expected_csv, expected_filename):
102102
msg += textwrap.dedent(
103103
f"""
104104
Error: {len(failed)} models have accuracy status regressed:
105-
{' '.join(failed)}
105+
{" ".join(failed)}
106106
107107
"""
108108
)
109109
if improved:
110110
msg += textwrap.dedent(
111111
f"""
112112
Improvement: {len(improved)} models have accuracy status improved:
113-
{' '.join(improved)}
113+
{" ".join(improved)}
114114
115115
"""
116116
)

benchmarks/dynamo/check_csv.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -26,7 +26,7 @@ def check_csv(filename):
2626
textwrap.dedent(
2727
f"""
2828
Error {len(failed)} models failed
29-
{' '.join(failed)}
29+
{" ".join(failed)}
3030
"""
3131
)
3232
)

benchmarks/dynamo/check_graph_breaks.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -91,15 +91,15 @@ def check_graph_breaks(actual_csv, expected_csv, expected_filename):
9191
msg += textwrap.dedent(
9292
f"""
9393
Error: {len(failed)} models have new dynamo graph breaks:
94-
{' '.join(failed)}
94+
{" ".join(failed)}
9595
9696
"""
9797
)
9898
if improved:
9999
msg += textwrap.dedent(
100100
f"""
101101
Improvement: {len(improved)} models have fixed dynamo graph breaks:
102-
{' '.join(improved)}
102+
{" ".join(improved)}
103103
104104
"""
105105
)

benchmarks/dynamo/check_memory_compression_ratio.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -40,7 +40,7 @@ def main(args):
4040
textwrap.dedent(
4141
f"""
4242
Error: {len(failed)} models below expected memory compression ratio:
43-
{' '.join(failed)}
43+
{" ".join(failed)}
4444
If this drop is expected, you can update `{args.expected}`.
4545
"""
4646
)

benchmarks/dynamo/check_perf_csv.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -26,7 +26,7 @@ def check_perf_csv(filename, threshold, threshold_scale):
2626
textwrap.dedent(
2727
f"""
2828
Error {len(failed)} models performance regressed
29-
{' '.join(failed)}
29+
{" ".join(failed)}
3030
"""
3131
)
3232
)

benchmarks/instruction_counts/core/api.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -368,7 +368,7 @@ def _model_from_py_stmt(
368368

369369
return textwrap.dedent(
370370
f"""\
371-
def model({', '.join(signature_args)}):
371+
def model({", ".join(signature_args)}):
372372
{{stmt_str}}
373373
return {signature_output}
374374
"""
@@ -397,7 +397,7 @@ def _make_model_invocation(
397397
cpp_invocation = textwrap.dedent(
398398
f"""\
399399
std::vector<torch::jit::IValue> ivalue_inputs({{
400-
{', '.join([f'torch::jit::IValue({a})' for a in signature_args])}
400+
{", ".join([f"torch::jit::IValue({a})" for a in signature_args])}
401401
}});
402402
{cpp_prefix}{model_name}.forward(ivalue_inputs);
403403
"""

docs/source/scripts/exportdb/generate_example_rst.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -49,7 +49,7 @@ def generate_example_rst(example_case: ExportCase):
4949
# Generate contents of the .rst file
5050
title = f"{example_case.name}"
5151
doc_contents = f"""{title}
52-
{'^' * (len(title))}
52+
{"^" * (len(title))}
5353
5454
.. note::
5555
@@ -117,7 +117,7 @@ def generate_index_rst(example_cases, tag_to_modules, support_level_to_modules):
117117
module_contents = "\n\n".join(v)
118118
support_contents += f"""
119119
{support_level}
120-
{'-' * (len(support_level))}
120+
{"-" * (len(support_level))}
121121
122122
{module_contents}
123123
"""

functorch/examples/dp_cifar10/cifar10_opacus.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -119,7 +119,7 @@ def test(args, model, test_loader, device):
119119

120120
top1_avg = np.mean(top1_acc)
121121

122-
print(f"\tTest set:Loss: {np.mean(losses):.6f} Acc@1: {top1_avg :.6f} ")
122+
print(f"\tTest set:Loss: {np.mean(losses):.6f} Acc@1: {top1_avg:.6f}")
123123
return np.mean(top1_acc)
124124

125125

functorch/examples/dp_cifar10/cifar10_transforms.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -185,7 +185,7 @@ def test(args, model, test_loader, device):
185185

186186
top1_avg = np.mean(top1_acc)
187187

188-
print(f"\tTest set:Loss: {np.mean(losses):.6f} Acc@1: {top1_avg :.6f} ")
188+
print(f"\tTest set:Loss: {np.mean(losses):.6f} Acc@1: {top1_avg:.6f}")
189189
return np.mean(top1_acc)
190190

191191

scripts/compile_tests/failures_histogram.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -108,7 +108,7 @@ def failures_histogram(eager_dir, dynamo_dir, verbose=False, format_issues=False
108108
def as_issue(count, msg, repro, tests):
109109
tests = "\n".join(tests)
110110
result = f"""
111-
{'-' * 50}
111+
{"-" * 50}
112112
{count} Dynamo test are failing with \"{msg}\".
113113
114114
## Repro

scripts/release_notes/categorize.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -145,7 +145,7 @@ def handle_commit(self, commit, i, total, commits):
145145
146146
Current category: {commit.category}
147147
148-
Select from: {', '.join(common.categories)}
148+
Select from: {", ".join(common.categories)}
149149
150150
"""
151151
)
@@ -165,7 +165,7 @@ def handle_commit(self, commit, i, total, commits):
165165
cat_choice = choices[0]
166166
print(f"\nSelected: {cat_choice}")
167167
print(f"\nCurrent topic: {commit.topic}")
168-
print(f"""Select from: {', '.join(topics)}""")
168+
print(f"""Select from: {", ".join(topics)}""")
169169
topic_choice = None
170170
while topic_choice is None:
171171
value = input("topic> ").strip()

setup.py

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1454,8 +1454,7 @@ def main():
14541454
name=package_name,
14551455
version=version,
14561456
description=(
1457-
"Tensors and Dynamic neural networks in "
1458-
"Python with strong GPU acceleration"
1457+
"Tensors and Dynamic neural networks in Python with strong GPU acceleration"
14591458
),
14601459
long_description=long_description,
14611460
long_description_content_type="text/markdown",

test/run_test.py

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -759,7 +759,7 @@ def run_test(
759759
stepcurrent_key = f"{test_file}_{test_module.shard}_{os.urandom(8).hex()}"
760760

761761
if options.verbose:
762-
unittest_args.append(f'-{"v" * options.verbose}') # in case of pytest
762+
unittest_args.append(f"-{'v' * options.verbose}") # in case of pytest
763763

764764
if test_file in RUN_PARALLEL_BLOCKLIST:
765765
unittest_args = [
@@ -1895,8 +1895,7 @@ def get_selected_tests(options) -> list[str]:
18951895
selected_tests = exclude_tests(
18961896
TESTS_NOT_USING_GRADCHECK,
18971897
selected_tests,
1898-
"Running in slow gradcheck mode, skipping tests "
1899-
"that don't use gradcheck.",
1898+
"Running in slow gradcheck mode, skipping tests that don't use gradcheck.",
19001899
exact_match=True,
19011900
)
19021901

test/test_dispatch.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -151,7 +151,7 @@ def check_invariants(actual_provenance):
151151
active_ops.add(op_ix)
152152
try:
153153
ops[op_ix](refs[op_ix])
154-
check_invariants(f"running ctors {ctor_order[:i + 1]}")
154+
check_invariants(f"running ctors {ctor_order[: i + 1]}")
155155
except RuntimeError as e:
156156
if not expect_raises:
157157
raise
@@ -160,7 +160,7 @@ def check_invariants(actual_provenance):
160160
expected, _, expected_provenance = results.setdefault(
161161
frozenset(active_ops),
162162
Result(
163-
actual, "", f"error after running ctors {ctor_order[:i + 1]}"
163+
actual, "", f"error after running ctors {ctor_order[: i + 1]}"
164164
),
165165
)
166166
self.assertMultiLineEqual(expected, actual, expected_provenance)
@@ -195,7 +195,7 @@ def check_invariants(actual_provenance):
195195
else:
196196
active_ops.remove(op_ix)
197197
check_invariants(
198-
f"running ctors {ctor_order[:last_ctor + 1]}, then running dtors {dtor_order[:i + 1]}"
198+
f"running ctors {ctor_order[: last_ctor + 1]}, then running dtors {dtor_order[: i + 1]}"
199199
)
200200
return results[set_to_report][0]
201201

test/test_jit_fuser_te.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2878,8 +2878,8 @@ def te_compile(self, device, dtype, op):
28782878
fx_args.append(f"{k} = {repr(v)}")
28792879

28802880
code = f"""
2881-
def f({', '.join(param_names)}):
2882-
return op.op({', '.join(fx_args)})"""
2881+
def f({", ".join(param_names)}):
2882+
return op.op({", ".join(fx_args)})"""
28832883
g = {"torch": torch, "inf": math.inf, "op": op}
28842884
exec(code, g)
28852885
f = g["f"]

tools/autograd/gen_inplace_or_view_type.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -575,7 +575,7 @@ def gen_formals(f: NativeFunction) -> str:
575575
# See Note [Plumbing Keys Through The Dispatcher] for details.
576576
["c10::DispatchKeySet ks"]
577577
+ [
578-
f'{cpp.argument_type(a, binds="__placeholder__", symint=True).cpp_type()} {a.name}'
578+
f"{cpp.argument_type(a, binds='__placeholder__', symint=True).cpp_type()} {a.name}"
579579
for a in f.func.schema_order_arguments()
580580
]
581581
)

tools/autograd/gen_python_functions.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -723,7 +723,7 @@ def emit_structseq_call(
723723
tn_key = gen_structseq_typename_key(overload.function)
724724
typename = typenames.get(tn_key)
725725
if typename is None:
726-
typename = f'NamedTuple{"" if not typedefs else len(typedefs)}'
726+
typename = f"NamedTuple{'' if not typedefs else len(typedefs)}"
727727
typenames[tn_key] = typename
728728
typedefs.append(
729729
f"""\
@@ -759,7 +759,7 @@ def generate_return_type_definition_and_registrations(
759759
typename = typenames.get(tn_key)
760760

761761
if typename is None:
762-
typename = f'{name}NamedTuple{"" if not definitions else len(definitions)}'
762+
typename = f"{name}NamedTuple{'' if not definitions else len(definitions)}"
763763
typenames[tn_key] = typename
764764
definitions.append(
765765
f"""\
@@ -807,7 +807,7 @@ def generate_return_type_declarations(
807807

808808
if typename is None:
809809
typename = (
810-
f'{name}NamedTuple{"" if not declarations else len(declarations)}'
810+
f"{name}NamedTuple{'' if not declarations else len(declarations)}"
811811
)
812812
typenames[tn_key] = typename
813813
declarations.append(f"PyTypeObject* get_{name}_structseq();")
@@ -1351,7 +1351,7 @@ def go(f: NativeFunction) -> str:
13511351
or (ps.method and ("requires_grad" in parser_outputs))
13521352
)
13531353
set_requires_grad = (
1354-
f'.set_requires_grad({parser_outputs["requires_grad"].expr})'
1354+
f".set_requires_grad({parser_outputs['requires_grad'].expr})"
13551355
if need_set_requires_grad
13561356
else ""
13571357
)

tools/autograd/gen_trace_type.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -381,17 +381,17 @@ def format_postrecord_trace(f: NativeFunction) -> str:
381381

382382
def tie_return_values(f: NativeFunction) -> str:
383383
if len(f.func.returns) == 1:
384-
return f'auto {f.func.returns[0].name or "result"}'
384+
return f"auto {f.func.returns[0].name or 'result'}"
385385
names = cpp.return_names(f)
386-
return f'auto [{", ".join(names)}]'
386+
return f"auto [{', '.join(names)}]"
387387

388388

389389
def get_return_value(f: NativeFunction) -> str:
390390
names = cpp.return_names(f)
391391
if len(f.func.returns) == 1:
392392
return names[0]
393393
if f.func.kind() == SchemaKind.out:
394-
return f'std::forward_as_tuple({", ".join(names)})'
394+
return f"std::forward_as_tuple({', '.join(names)})"
395395
else:
396396
moved = ", ".join(f"std::move({name})" for name in names)
397397
return f"std::make_tuple({moved})"
@@ -474,7 +474,7 @@ def method_definition(f: NativeFunction) -> str:
474474
# See Note [Plumbing Keys Through The Dispatcher] for details.
475475
["c10::DispatchKeySet ks"]
476476
+ [
477-
f'{cpp.argument_type(a, binds="__placeholder__", symint=True).cpp_type()} {a.name}'
477+
f"{cpp.argument_type(a, binds='__placeholder__', symint=True).cpp_type()} {a.name}"
478478
for a in f.func.schema_order_arguments()
479479
]
480480
)

tools/autograd/gen_variable_factories.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -108,9 +108,9 @@ def process_function(f: NativeFunction) -> str | None:
108108
exprs.append(arg.name)
109109

110110
r += f"""\
111-
inline at::Tensor {sig.name()}({', '.join(formals)}) {{
111+
inline at::Tensor {sig.name()}({", ".join(formals)}) {{
112112
at::AutoDispatchBelowADInplaceOrView guard;
113-
return autograd::make_variable(at::{sig.name()}({', '.join(exprs)}), /*requires_grad=*/{requires_grad});
113+
return autograd::make_variable(at::{sig.name()}({", ".join(exprs)}), /*requires_grad=*/{requires_grad});
114114
}}
115115
"""
116116
return r

0 commit comments

Comments
 (0)