Skip to content

Commit 4cc1745

Browse files
justinchubypytorchmergebot
authored andcommitted
[BE] f-stringify torch/ and scripts (pytorch#105538)
This PR is a follow up on the pyupgrade series to convert more strings to use f-strings using `flynt`. - https://docs.python.org/3/reference/lexical_analysis.html#f-strings - https://pypi.org/project/flynt/ Command used: ``` flynt torch/ -ll 120 flynt scripts/ -ll 120 flynt tools/ -ll 120 ``` and excluded `collect_env.py` Pull Request resolved: pytorch#105538 Approved by: https://github.com/ezyang, https://github.com/malfet
1 parent 4c73016 commit 4cc1745

File tree

139 files changed

+350
-670
lines changed

Some content is hidden

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

139 files changed

+350
-670
lines changed

benchmarks/profiler_benchmark/profiler_bench.py

+1-2
Original file line numberDiff line numberDiff line change
@@ -46,8 +46,7 @@ def parallel_task(x):
4646
print("No CUDA available")
4747
sys.exit()
4848

49-
print("Payload: {}, {} iterations; timer min. runtime = {}\n".format(
50-
args.workload, args.internal_iter, args.timer_min_run_time))
49+
print(f"Payload: {args.workload}, {args.internal_iter} iterations; timer min. runtime = {args.timer_min_run_time}\n")
5150
INTERNAL_ITER = args.internal_iter
5251

5352
for profiling_enabled in [False, True]:

functorch/examples/dp_cifar10/cifar10_transforms.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -115,7 +115,7 @@ def compute_loss_and_output(weights, image, target):
115115
# is not to be differentiated. `f'` returns the gradient w.r.t. the loss,
116116
# the loss, and the auxiliary value.
117117
grads_loss_output = grad_and_value(compute_loss_and_output, has_aux=True)
118-
weights = {k: v for k, v in model.named_parameters()}
118+
weights = dict(model.named_parameters())
119119

120120
# detaching weights since we don't need to track gradients outside of transforms
121121
# and this is more performant

scripts/get_python_cmake_flags.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -19,8 +19,8 @@
1919
import sys
2020

2121
flags = [
22-
'-DPYTHON_EXECUTABLE:FILEPATH={}'.format(sys.executable),
23-
'-DPYTHON_INCLUDE_DIR={}'.format(sysconfig.get_path('include')),
22+
f'-DPYTHON_EXECUTABLE:FILEPATH={sys.executable}',
23+
f"-DPYTHON_INCLUDE_DIR={sysconfig.get_path('include')}",
2424
]
2525

2626
print(' '.join(flags), end='')

scripts/model_zoo/update-caffe2-models.py

+5-5
Original file line numberDiff line numberDiff line change
@@ -30,7 +30,7 @@ def _download(self, model):
3030
# (Sep 17, 2017)
3131
downloadFromURLToFile(url, dest)
3232
except Exception as e:
33-
print("Abort: {reason}".format(reason=e))
33+
print(f"Abort: {e}")
3434
print("Cleaning up...")
3535
deleteDirectory(model_dir)
3636
exit(1)
@@ -53,20 +53,20 @@ def _prepare_model_data(self, model):
5353
if os.path.exists(model_dir):
5454
return
5555
os.makedirs(model_dir)
56-
url = 'https://s3.amazonaws.com/download.onnx/models/{}.tar.gz'.format(model)
56+
url = f'https://s3.amazonaws.com/download.onnx/models/{model}.tar.gz'
5757

5858
# On Windows, NamedTemporaryFile cannot be opened for a
5959
# second time
6060
download_file = tempfile.NamedTemporaryFile(delete=False)
6161
try:
6262
download_file.close()
63-
print('Start downloading model {} from {}'.format(model, url))
63+
print(f'Start downloading model {model} from {url}')
6464
urlretrieve(url, download_file.name)
6565
print('Done')
6666
with tarfile.open(download_file.name) as t:
6767
t.extractall(models_dir)
6868
except Exception as e:
69-
print('Failed to prepare data for model {}: {}'.format(model, e))
69+
print(f'Failed to prepare data for model {model}: {e}')
7070
raise
7171
finally:
7272
os.remove(download_file.name)
@@ -133,7 +133,7 @@ def upload_models():
133133
's3',
134134
'cp',
135135
model + '.tar.gz',
136-
"s3://download.onnx/models/{}.tar.gz".format(model),
136+
f"s3://download.onnx/models/{model}.tar.gz",
137137
'--acl', 'public-read'
138138
], cwd=onnx_models_dir)
139139

scripts/model_zoo/update-models-from-caffe2.py

+24-24
Original file line numberDiff line numberDiff line change
@@ -51,20 +51,20 @@ def upload_onnx_model(model_name, zoo_dir, backup=False, only_local=False):
5151
model_dir = os.path.join(zoo_dir, model_name)
5252
suffix = '-backup' if backup else ''
5353
if backup:
54-
print('Backing up the previous version of ONNX model {}...'.format(model_name))
55-
rel_file_name = '{}{}.tar.gz'.format(model_name, suffix)
54+
print(f'Backing up the previous version of ONNX model {model_name}...')
55+
rel_file_name = f'{model_name}{suffix}.tar.gz'
5656
abs_file_name = os.path.join(zoo_dir, rel_file_name)
57-
print('Compressing {} model to {}'.format(model_name, abs_file_name))
57+
print(f'Compressing {model_name} model to {abs_file_name}')
5858
with tarfile.open(abs_file_name, 'w:gz') as f:
5959
f.add(model_dir, arcname=model_name)
6060
file_size = os.stat(abs_file_name).st_size
61-
print('Uploading {} ({} MB) to s3 cloud...'.format(abs_file_name, float(file_size) / 1024 / 1024))
61+
print(f'Uploading {abs_file_name} ({float(file_size) / 1024 / 1024} MB) to s3 cloud...')
6262
client = boto3.client('s3', 'us-east-1')
6363
transfer = boto3.s3.transfer.S3Transfer(client)
64-
transfer.upload_file(abs_file_name, 'download.onnx', 'models/latest/{}'.format(rel_file_name),
64+
transfer.upload_file(abs_file_name, 'download.onnx', f'models/latest/{rel_file_name}',
6565
extra_args={'ACL': 'public-read'})
6666

67-
print('Successfully uploaded {} to s3!'.format(rel_file_name))
67+
print(f'Successfully uploaded {rel_file_name} to s3!')
6868

6969

7070
def download_onnx_model(model_name, zoo_dir, use_cache=True, only_local=False):
@@ -75,7 +75,7 @@ def download_onnx_model(model_name, zoo_dir, use_cache=True, only_local=False):
7575
return
7676
else:
7777
shutil.rmtree(model_dir)
78-
url = 'https://s3.amazonaws.com/download.onnx/models/latest/{}.tar.gz'.format(model_name)
78+
url = f'https://s3.amazonaws.com/download.onnx/models/latest/{model_name}.tar.gz'
7979

8080
download_file = tempfile.NamedTemporaryFile(delete=False)
8181
try:
@@ -84,10 +84,10 @@ def download_onnx_model(model_name, zoo_dir, use_cache=True, only_local=False):
8484
model_name, url, download_file.name))
8585
urlretrieve(url, download_file.name)
8686
with tarfile.open(download_file.name) as t:
87-
print('Extracting ONNX model {} to {} ...\n'.format(model_name, zoo_dir))
87+
print(f'Extracting ONNX model {model_name} to {zoo_dir} ...\n')
8888
t.extractall(zoo_dir)
8989
except Exception as e:
90-
print('Failed to download/backup data for ONNX model {}: {}'.format(model_name, e))
90+
print(f'Failed to download/backup data for ONNX model {model_name}: {e}')
9191
if not os.path.exists(model_dir):
9292
os.makedirs(model_dir)
9393
finally:
@@ -119,7 +119,7 @@ def download_caffe2_model(model_name, zoo_dir, use_cache=True):
119119
# (Sep 17, 2017)
120120
downloadFromURLToFile(url, dest)
121121
except Exception as e:
122-
print("Abort: {reason}".format(reason=e))
122+
print(f"Abort: {e}")
123123
print("Cleaning up...")
124124
deleteDirectory(model_dir)
125125
raise
@@ -131,14 +131,14 @@ def caffe2_to_onnx(caffe2_model_name, caffe2_model_dir):
131131

132132
with open(os.path.join(caffe2_model_dir, 'init_net.pb'), 'rb') as f:
133133
caffe2_init_proto.ParseFromString(f.read())
134-
caffe2_init_proto.name = '{}_init'.format(caffe2_model_name)
134+
caffe2_init_proto.name = f'{caffe2_model_name}_init'
135135
with open(os.path.join(caffe2_model_dir, 'predict_net.pb'), 'rb') as f:
136136
caffe2_predict_proto.ParseFromString(f.read())
137137
caffe2_predict_proto.name = caffe2_model_name
138138
with open(os.path.join(caffe2_model_dir, 'value_info.json'), 'rb') as f:
139139
value_info = json.loads(f.read())
140140

141-
print('Converting Caffe2 model {} in {} to ONNX format'.format(caffe2_model_name, caffe2_model_dir))
141+
print(f'Converting Caffe2 model {caffe2_model_name} in {caffe2_model_dir} to ONNX format')
142142
onnx_model = caffe2.python.onnx.frontend.caffe2_net_to_onnx_model(
143143
init_net=caffe2_init_proto,
144144
predict_net=caffe2_predict_proto,
@@ -245,7 +245,7 @@ def onnx_verify(onnx_model, inputs, ref_outputs):
245245
for onnx_model_name in model_mapping:
246246
c2_model_name = model_mapping[onnx_model_name]
247247

248-
print('####### Processing ONNX model {} ({} in Caffe2) #######'.format(onnx_model_name, c2_model_name))
248+
print(f'####### Processing ONNX model {onnx_model_name} ({c2_model_name} in Caffe2) #######')
249249
download_caffe2_model(c2_model_name, caffe2_zoo_dir, use_cache=use_cache)
250250
download_onnx_model(onnx_model_name, onnx_zoo_dir, use_cache=use_cache, only_local=only_local)
251251

@@ -261,19 +261,19 @@ def onnx_verify(onnx_model, inputs, ref_outputs):
261261

262262
onnx_model, c2_init_net, c2_predict_net = caffe2_to_onnx(c2_model_name, os.path.join(caffe2_zoo_dir, c2_model_name))
263263

264-
print('Deleteing old ONNX {} model...'.format(onnx_model_name))
264+
print(f'Deleteing old ONNX {onnx_model_name} model...')
265265
for f in glob.glob(os.path.join(onnx_model_dir, 'model*'.format(onnx_model_name))):
266266
os.remove(f)
267267

268-
print('Serializing generated ONNX {} model ...'.format(onnx_model_name))
268+
print(f'Serializing generated ONNX {onnx_model_name} model ...')
269269
with open(os.path.join(onnx_model_dir, 'model.onnx'), 'wb') as file:
270270
file.write(onnx_model.SerializeToString())
271271

272-
print('Verifying model {} with ONNX model checker...'.format(onnx_model_name))
272+
print(f'Verifying model {onnx_model_name} with ONNX model checker...')
273273
onnx.checker.check_model(onnx_model)
274274

275275
total_existing_data_set = 0
276-
print('Verifying model {} with existing test data...'.format(onnx_model_name))
276+
print(f'Verifying model {onnx_model_name} with existing test data...')
277277
for f in glob.glob(os.path.join(onnx_model_dir, '*.npz')):
278278
test_data = np.load(f, encoding='bytes')
279279
inputs = list(test_data['inputs'])
@@ -285,41 +285,41 @@ def onnx_verify(onnx_model, inputs, ref_outputs):
285285
inputs_num = len(glob.glob(os.path.join(f, 'input_*.pb')))
286286
for i in range(inputs_num):
287287
tensor = onnx.TensorProto()
288-
with open(os.path.join(f, 'input_{}.pb'.format(i)), 'rb') as pf:
288+
with open(os.path.join(f, f'input_{i}.pb'), 'rb') as pf:
289289
tensor.ParseFromString(pf.read())
290290
inputs.append(numpy_helper.to_array(tensor))
291291
ref_outputs = []
292292
ref_outputs_num = len(glob.glob(os.path.join(f, 'output_*.pb')))
293293
for i in range(ref_outputs_num):
294294
tensor = onnx.TensorProto()
295-
with open(os.path.join(f, 'output_{}.pb'.format(i)), 'rb') as pf:
295+
with open(os.path.join(f, f'output_{i}.pb'), 'rb') as pf:
296296
tensor.ParseFromString(pf.read())
297297
ref_outputs.append(numpy_helper.to_array(tensor))
298298
onnx_verify(onnx_model, inputs, ref_outputs)
299299
total_existing_data_set += 1
300300

301301
starting_index = 0
302-
while os.path.exists(os.path.join(onnx_model_dir, 'test_data_set_{}'.format(starting_index))):
302+
while os.path.exists(os.path.join(onnx_model_dir, f'test_data_set_{starting_index}')):
303303
starting_index += 1
304304

305305
if total_existing_data_set == 0 and add_test_data == 0:
306306
add_test_data = 3
307307
total_existing_data_set = 3
308308

309-
print('Generating {} sets of new test data...'.format(add_test_data))
309+
print(f'Generating {add_test_data} sets of new test data...')
310310
for i in range(starting_index, add_test_data + starting_index):
311-
data_dir = os.path.join(onnx_model_dir, 'test_data_set_{}'.format(i))
311+
data_dir = os.path.join(onnx_model_dir, f'test_data_set_{i}')
312312
os.makedirs(data_dir)
313313
inputs = generate_test_input_data(onnx_model, 255)
314314
ref_outputs = generate_test_output_data(c2_init_net, c2_predict_net, inputs)
315315
onnx_verify(onnx_model, inputs, ref_outputs)
316316
for index, input in enumerate(inputs):
317317
tensor = numpy_helper.from_array(input[1])
318-
with open(os.path.join(data_dir, 'input_{}.pb'.format(index)), 'wb') as file:
318+
with open(os.path.join(data_dir, f'input_{index}.pb'), 'wb') as file:
319319
file.write(tensor.SerializeToString())
320320
for index, output in enumerate(ref_outputs):
321321
tensor = numpy_helper.from_array(output)
322-
with open(os.path.join(data_dir, 'output_{}.pb'.format(index)), 'wb') as file:
322+
with open(os.path.join(data_dir, f'output_{index}.pb'), 'wb') as file:
323323
file.write(tensor.SerializeToString())
324324

325325
del onnx_model

scripts/release_notes/common.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -205,7 +205,7 @@ def run_query(query):
205205
if request.status_code == 200:
206206
return request.json()
207207
else:
208-
raise Exception("Query failed to run by returning code of {}. {}".format(request.status_code, request.json()))
208+
raise Exception(f"Query failed to run by returning code of {request.status_code}. {request.json()}")
209209

210210

211211
def github_data(pr_number):

setup.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -224,7 +224,7 @@
224224
python_min_version = (3, 8, 0)
225225
python_min_version_str = '.'.join(map(str, python_min_version))
226226
if sys.version_info < python_min_version:
227-
print("You are using Python {}. Python >={} is required.".format(platform.python_version(),
227+
print("You are using Python {}. Python >={} is required.".format(platform.python_version(), # noqa: UP032
228228
python_min_version_str))
229229
sys.exit(-1)
230230

test/distributed/test_c10d_nccl.py

+2-6
Original file line numberDiff line numberDiff line change
@@ -1906,9 +1906,7 @@ def first_bucket_size(ddp_bucket_mb):
19061906
):
19071907
with first_bucket_size(bucketsize):
19081908
model_msg = (
1909-
"rank = {} formats = {} dtypes = {} bucketsize = {} ".format(
1910-
self.rank, formats, dtypes, bucketsize
1911-
)
1909+
f"rank = {self.rank} formats = {formats} dtypes = {dtypes} bucketsize = {bucketsize} "
19121910
)
19131911
try:
19141912
m = ConvNet(layer_devs, formats, dtypes)
@@ -2387,9 +2385,7 @@ def test_ddp_weight_sharing(self):
23872385
"mismatch at "
23882386
+ name
23892387
+ ".grad for "
2390-
+ "set_to_none = {}, use_bucket_view = {}".format(
2391-
try_set_to_none, use_bucket_view
2392-
),
2388+
+ f"set_to_none = {try_set_to_none}, use_bucket_view = {use_bucket_view}",
23932389
)
23942390

23952391
@requires_nccl()

test/distributed/test_c10d_spawn.py

+1-3
Original file line numberDiff line numberDiff line change
@@ -57,9 +57,7 @@ def _test_multiprocess(self, f, shared_tensors, init_pg, n_output):
5757
self.assertEqual(
5858
expected,
5959
result,
60-
msg=(
61-
"Expect rank {} to receive tensor {} but got {}."
62-
).format(pid, expected, result)
60+
msg=f"Expect rank {pid} to receive tensor {expected} but got {result}."
6361
)
6462

6563
for _ in range(ws):

test/distributions/test_distributions.py

+4-8
Original file line numberDiff line numberDiff line change
@@ -912,8 +912,7 @@ def test_sample_detached(self):
912912
dist = Dist(**param)
913913
sample = dist.sample()
914914
self.assertFalse(sample.requires_grad,
915-
msg='{} example {}/{}, .sample() is not detached'.format(
916-
Dist.__name__, i + 1, len(params)))
915+
msg=f'{Dist.__name__} example {i + 1}/{len(params)}, .sample() is not detached')
917916

918917
@skipIfTorchDynamo("Not a TorchDynamo suitable test")
919918
def test_rsample_requires_grad(self):
@@ -926,8 +925,7 @@ def test_rsample_requires_grad(self):
926925
continue
927926
sample = dist.rsample()
928927
self.assertTrue(sample.requires_grad,
929-
msg='{} example {}/{}, .rsample() does not require grad'.format(
930-
Dist.__name__, i + 1, len(params)))
928+
msg=f'{Dist.__name__} example {i + 1}/{len(params)}, .rsample() does not require grad')
931929

932930
def test_enumerate_support_type(self):
933931
for Dist, params in EXAMPLES:
@@ -4377,8 +4375,7 @@ def test_params_constraints(self):
43774375
if is_dependent(constraint):
43784376
continue
43794377

4380-
message = '{} example {}/{} parameter {} = {}'.format(
4381-
Dist.__name__, i + 1, len(params), name, value)
4378+
message = f'{Dist.__name__} example {i + 1}/{len(params)} parameter {name} = {value}'
43824379
self.assertTrue(constraint.check(value).all(), msg=message)
43834380

43844381
def test_support_constraints(self):
@@ -4388,8 +4385,7 @@ def test_support_constraints(self):
43884385
dist = Dist(**param)
43894386
value = dist.sample()
43904387
constraint = dist.support
4391-
message = '{} example {}/{} sample = {}'.format(
4392-
Dist.__name__, i + 1, len(params), value)
4388+
message = f'{Dist.__name__} example {i + 1}/{len(params)} sample = {value}'
43934389
self.assertEqual(constraint.event_dim, len(dist.event_shape), msg=message)
43944390
ok = constraint.check(value)
43954391
self.assertEqual(ok.shape, dist.batch_shape, msg=message)

test/onnx/pytorch_helper.py

+1-3
Original file line numberDiff line numberDiff line change
@@ -68,9 +68,7 @@ def PyTorchModule(helper, model, sample_arguments, caffe2_inputs, prefix_name=No
6868

6969
if len(uninitialized_inputs) != len(caffe2_inputs):
7070
raise ValueError(
71-
"Expected {} inputs but found {}".format(
72-
len(uninitialized_inputs), len(caffe2_inputs)
73-
)
71+
f"Expected {len(uninitialized_inputs)} inputs but found {len(caffe2_inputs)}"
7472
)
7573

7674
def remap_blob_name(name):

test/onnx/test_operators.py

+1-3
Original file line numberDiff line numberDiff line change
@@ -105,9 +105,7 @@ def assertONNX(self, f, args, params=None, **kwargs):
105105
# Assume:
106106
# 1) the old test should be delete before the test.
107107
# 2) only one assertONNX in each test, otherwise will override the data.
108-
assert not os.path.exists(output_dir), "{} should not exist!".format(
109-
output_dir
110-
)
108+
assert not os.path.exists(output_dir), f"{output_dir} should not exist!"
111109
os.makedirs(output_dir)
112110
with open(os.path.join(output_dir, "model.onnx"), "wb") as file:
113111
file.write(model_def.SerializeToString())

test/onnx_caffe2/export_onnx_tests_generator.py

+2-6
Original file line numberDiff line numberDiff line change
@@ -145,14 +145,10 @@ def convert_tests(testcases, sets=1):
145145
failed += 1
146146

147147
print(
148-
"Collect {} test cases from PyTorch repo, failed to export {} cases.".format(
149-
len(testcases), failed
150-
)
148+
f"Collect {len(testcases)} test cases from PyTorch repo, failed to export {failed} cases."
151149
)
152150
print(
153-
"PyTorch converted cases are stored in {}.".format(
154-
onnx_test_common.pytorch_converted_dir
155-
)
151+
f"PyTorch converted cases are stored in {onnx_test_common.pytorch_converted_dir}."
156152
)
157153
print_stats(FunctionalModule_nums, nn_module)
158154

test/optim/test_lrscheduler.py

+1-3
Original file line numberDiff line numberDiff line change
@@ -1989,9 +1989,7 @@ def _test_get_last_lr(self, schedulers, targets, epochs=10):
19891989
self.assertEqual(
19901990
target,
19911991
result,
1992-
msg="LR is wrong in epoch {}: expected {}, got {}".format(
1993-
epoch, t, r
1994-
),
1992+
msg=f"LR is wrong in epoch {epoch}: expected {t}, got {r}",
19951993
atol=1e-5,
19961994
rtol=0,
19971995
)

test/quantization/core/test_docs.py

+1-3
Original file line numberDiff line numberDiff line change
@@ -62,9 +62,7 @@ def get_correct_path(path_from_pytorch):
6262
if "\n" not in unique_identifier:
6363
unique_identifier += "\n"
6464

65-
assert unique_identifier in content, "could not find {} in {}".format(
66-
unique_identifier, path_to_file
67-
)
65+
assert unique_identifier in content, f"could not find {unique_identifier} in {path_to_file}"
6866

6967
# get index of first line of code
7068
line_num_start = content.index(unique_identifier) + 1

0 commit comments

Comments
 (0)