Skip to content

Commit c8bb54c

Browse files
committed
lint: Second pass with ruff --fix --unsafe-fixes
1 parent ae6817d commit c8bb54c

165 files changed

Lines changed: 901 additions & 1163 deletions

File tree

Some content is hidden

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

benchmarks/user/advisor/advisor_logging.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -9,18 +9,18 @@ def check(cond, msg):
99

1010

1111
def err(msg):
12-
print('\033[1;37;31m%s\033[0m' % msg) # print in RED
12+
print(f'\033[1;37;31m{msg}\033[0m') # print in RED
1313

1414

1515
def log(msg):
16-
print('\033[1;37;32m%s\033[0m' % msg) # print in GREEN
16+
print(f'\033[1;37;32m{msg}\033[0m') # print in GREEN
1717

1818

1919
@contextmanager
2020
def progress(msg):
21-
print('\033[1;37;32m%s ... \033[0m' % msg, end='', flush=True) # print in GREEN
21+
print(f'\033[1;37;32m{msg} ... \033[0m', end='', flush=True) # print in GREEN
2222
yield
23-
print('\033[1;37;32m%s\033[0m' % 'Done!')
23+
print('\033[1;37;32m{}\033[0m'.format('Done!'))
2424

2525

2626
def log_process(process, logger):

benchmarks/user/advisor/roofline.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -205,7 +205,7 @@ def roofline(name, project, scale, precision, mode, th):
205205
log(f'\nFigure saved in {figpath}{name}.pdf.')
206206

207207
# Save the JSON file
208-
with open('%s.json' % name, 'w') as f:
208+
with open(f'{name}.json', 'w') as f:
209209
f.write(json.dumps(roofline_data))
210210

211211
log(f'\nJSON file saved as {name}.json.')

benchmarks/user/advisor/run_advisor.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -132,7 +132,7 @@ def run_with_advisor(path, output, name, exec_args):
132132
# Before collecting the `survey` and `tripcounts` a "pure" python run
133133
# to warmup the jit cache is preceded
134134

135-
log('Starting Intel Advisor\'s `roofline` analysis for `%s`' % name)
135+
log(f'Starting Intel Advisor\'s `roofline` analysis for `{name}`')
136136
dt = datetime.datetime.now()
137137

138138
# Set up a file logger that will track the output of the advisor profiling
@@ -142,7 +142,7 @@ def run_with_advisor(path, output, name, exec_args):
142142
advixe_formatter = logging.Formatter('%(asctime)s: %(message)s')
143143
logger_datetime = '%d.%d.%d.%d.%d.%d' % (dt.year, dt.month,
144144
dt.day, dt.hour, dt.minute, dt.second)
145-
advixe_handler = logging.FileHandler('%s/%s_%s.log' % (output, name, logger_datetime))
145+
advixe_handler = logging.FileHandler(f'{output}/{name}_{logger_datetime}.log')
146146
advixe_handler.setFormatter(advixe_formatter)
147147
advixe_logger.addHandler(advixe_handler)
148148

benchmarks/user/benchmark.py

Lines changed: 15 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -74,7 +74,7 @@ def run_op(solver, operator, **options):
7474
try:
7575
op = getattr(solver, operator)
7676
except AttributeError:
77-
raise AttributeError("Operator %s not implemented for %s" % (operator, solver))
77+
raise AttributeError(f"Operator {operator} not implemented for {solver}")
7878

7979
# This is a bit ugly but not sure how to make clean input creation for different op
8080
if operator == "forward":
@@ -95,7 +95,7 @@ def run_op(solver, operator, **options):
9595
args = args[:-1]
9696
return op(*args, **options)
9797
else:
98-
raise ValueError("Unrecognized operator %s" % operator)
98+
raise ValueError(f"Unrecognized operator {operator}")
9999

100100

101101
@click.group()
@@ -157,15 +157,14 @@ def from_opt(ctx, param, value):
157157
# E.g., `('advanced', {'par-tile': True})`
158158
value = eval(value)
159159
if not isinstance(value, tuple) and len(value) >= 1:
160-
raise click.BadParameter("Invalid choice `%s` (`opt` must be "
161-
"either str or tuple)" % str(value))
160+
raise click.BadParameter(f"Invalid choice `{str(value)}` (`opt` must be "
161+
"either str or tuple)")
162162
opt = value[0]
163163
except NameError:
164164
# E.g. `'advanced'`
165165
opt = value
166166
if opt not in configuration._accepted['opt']:
167-
raise click.BadParameter("Invalid choice `%s` (choose from %s)"
168-
% (opt, str(configuration._accepted['opt'])))
167+
raise click.BadParameter("Invalid choice `{}` (choose from {})".format(opt, str(configuration._accepted['opt'])))
169168
return value
170169

171170
def config_blockshape(ctx, param, value):
@@ -181,18 +180,18 @@ def config_blockshape(ctx, param, value):
181180
# 1. integers, not strings
182181
# 2. sanity check the (hierarchical) blocking shape
183182
normalized_value = []
184-
for i, block_shape in enumerate(value):
183+
for _i, block_shape in enumerate(value):
185184
# If hierarchical blocking is activated, say with N levels, here in
186185
# `bs` we expect to see 3*N entries
187186
bs = [int(x) for x in block_shape.split()]
188187
levels = [bs[x:x+3] for x in range(0, len(bs), 3)]
189188
if any(len(level) != 3 for level in levels):
190189
raise ValueError("Expected 3 entries per block shape level, but got "
191-
"one level with less than 3 entries (`%s`)" % levels)
190+
f"one level with less than 3 entries (`{levels}`)")
192191
normalized_value.append(levels)
193192
if not all_equal(len(i) for i in normalized_value):
194193
raise ValueError("Found different block shapes with incompatible "
195-
"number of levels (`%s`)" % normalized_value)
194+
f"number of levels (`{normalized_value}`)")
196195
configuration['opt-options']['blocklevels'] = len(normalized_value[0])
197196
else:
198197
normalized_value = []
@@ -205,8 +204,7 @@ def config_autotuning(ctx, param, value):
205204
elif value != 'off':
206205
# Sneak-peek at the `block-shape` -- if provided, keep auto-tuning off
207206
if ctx.params['block_shape']:
208-
warning("Skipping autotuning (using explicit block-shape `%s`)"
209-
% str(ctx.params['block_shape']))
207+
warning("Skipping autotuning (using explicit block-shape `{}`)".format(str(ctx.params['block_shape'])))
210208
level = False
211209
else:
212210
# Make sure to always run in preemptive mode
@@ -305,11 +303,11 @@ def run(problem, **kwargs):
305303

306304
dumpfile = kwargs.pop('dump_norms')
307305
if dumpfile:
308-
norms = ["'%s': %f" % (i.name, norm(i)) for i in retval[:-1]
306+
norms = [f"'{i.name}': {norm(i):f}" for i in retval[:-1]
309307
if isinstance(i, DiscreteFunction)]
310308
if rank == 0:
311309
with open(dumpfile, 'w') as f:
312-
f.write("{%s}" % ', '.join(norms))
310+
f.write("{{{}}}".format(', '.join(norms)))
313311

314312
return retval
315313

@@ -343,13 +341,13 @@ def run_jit_backdoor(problem, **kwargs):
343341
op = solver.op_fwd()
344342

345343
# Get the filename in the JIT cache
346-
cfile = "%s.c" % str(op._compiler.get_jit_dir().joinpath(op._soname))
344+
cfile = f"{str(op._compiler.get_jit_dir().joinpath(op._soname))}.c"
347345

348346
if not os.path.exists(cfile):
349347
# First time we run this problem, let's generate and jit-compile code
350348
op.cfunction
351-
info("You may now edit the generated code in `%s`. "
352-
"Then save the file, and re-run this benchmark." % cfile)
349+
info(f"You may now edit the generated code in `{cfile}`. "
350+
"Then save the file, and re-run this benchmark.")
353351
return
354352

355353
info("Running wave propagation Operator...")
@@ -364,7 +362,7 @@ def _run_jit_backdoor():
364362
if dumpnorms:
365363
for i in retval[:-1]:
366364
if isinstance(i, DiscreteFunction):
367-
info("'%s': %f" % (i.name, norm(i)))
365+
info(f"'{i.name}': {norm(i):f}")
368366

369367
return retval
370368

conftest.py

Lines changed: 13 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@
1717
FindNodes, FindSymbols, Iteration, ParallelBlock, retrieve_iteration_tree
1818
)
1919
from devito.tools import as_tuple
20+
import contextlib
2021

2122
try:
2223
from mpi4py import MPI # noqa
@@ -40,29 +41,28 @@ def skipif(items, whole_module=False):
4041
accepted.update({'nodevice', 'noomp'})
4142
unknown = sorted(set(items) - accepted)
4243
if unknown:
43-
raise ValueError("Illegal skipif argument(s) `%s`" % unknown)
44+
raise ValueError(f"Illegal skipif argument(s) `{unknown}`")
4445
skipit = False
4546
for i in items:
4647
# Skip if won't run on GPUs
4748
if i == 'device' and isinstance(configuration['platform'], Device):
48-
skipit = "device `%s` unsupported" % configuration['platform'].name
49+
skipit = "device `{}` unsupported".format(configuration['platform'].name)
4950
break
5051
# Skip if won't run on a specific GPU backend
5152
langs = configuration._accepted['language']
52-
if any(i == 'device-%s' % l and configuration['language'] == l for l in langs)\
53+
if any(i == f'device-{l}' and configuration['language'] == l for l in langs)\
5354
and isinstance(configuration['platform'], Device):
54-
skipit = "language `%s` for device unsupported" % configuration['language']
55+
skipit = "language `{}` for device unsupported".format(configuration['language'])
5556
break
56-
if any(i == 'device-%s' % k and isinstance(configuration['compiler'], v)
57+
if any(i == f'device-{k}' and isinstance(configuration['compiler'], v)
5758
for k, v in compiler_registry.items()) and\
5859
isinstance(configuration['platform'], Device):
59-
skipit = "compiler `%s` for device unsupported" % configuration['compiler']
60+
skipit = "compiler `{}` for device unsupported".format(configuration['compiler'])
6061
break
6162
# Skip if must run on GPUs but not currently on a GPU
6263
if i in ('nodevice', 'nodevice-omp', 'nodevice-acc') and\
6364
not isinstance(configuration['platform'], Device):
64-
skipit = ("must run on device, but currently on `%s`" %
65-
configuration['platform'].name)
65+
skipit = ("must run on device, but currently on `{}`".format(configuration['platform'].name))
6666
break
6767
# Skip if it won't run with nvc on CPU backend
6868
if i == 'cpu64-nvc' and \
@@ -137,9 +137,9 @@ def EVAL(exprs, *args):
137137

138138
def get_testname(item):
139139
if item.cls is not None:
140-
return "%s::%s::%s" % (item.fspath, item.cls.__name__, item.name)
140+
return f"{item.fspath}::{item.cls.__name__}::{item.name}"
141141
else:
142-
return "%s::%s" % (item.fspath, item.name)
142+
return f"{item.fspath}::{item.name}"
143143

144144

145145
def set_run_reset(env_vars, call):
@@ -179,7 +179,7 @@ def parallel(item, m):
179179
if len(m) == 2:
180180
nprocs, scheme = m
181181
else:
182-
raise ValueError("Can't run test: unexpected mode `%s`" % m)
182+
raise ValueError(f"Can't run test: unexpected mode `{m}`")
183183

184184
env_vars = {'DEVITO_MPI': scheme}
185185

@@ -247,10 +247,8 @@ def pytest_generate_tests(metafunc):
247247
@pytest.hookimpl(tryfirst=True, hookwrapper=True)
248248
def pytest_runtest_call(item):
249249
inside_pytest_marker = os.environ.get('DEVITO_PYTEST_FLAG', 0)
250-
try:
250+
with contextlib.suppress(ValueError):
251251
inside_pytest_marker = int(inside_pytest_marker)
252-
except ValueError:
253-
pass
254252

255253
if inside_pytest_marker:
256254
outcome = yield
@@ -281,10 +279,8 @@ def pytest_runtest_makereport(item, call):
281279
result = outcome.get_result()
282280

283281
inside_pytest_marker = os.environ.get('DEVITO_PYTEST_FLAG', 0)
284-
try:
282+
with contextlib.suppress(ValueError):
285283
inside_pytest_marker = int(inside_pytest_marker)
286-
except ValueError:
287-
pass
288284
if inside_pytest_marker:
289285
return
290286

devito/arch/archinfo.py

Lines changed: 77 additions & 31 deletions
Original file line numberDiff line numberDiff line change
@@ -15,31 +15,79 @@
1515

1616
from devito.logger import warning
1717
from devito.tools import all_equal, as_tuple, memoized_func
18-
19-
__all__ = ['platform_registry', 'get_cpu_info', 'get_gpu_info', 'get_visible_devices',
20-
'get_nvidia_cc', 'get_cuda_path', 'get_hip_path', 'check_cuda_runtime',
21-
'get_m1_llvm_path', 'get_advisor_path', 'Platform', 'Cpu64', 'Intel64',
22-
'IntelSkylake', 'Amd', 'Arm', 'Power', 'Device', 'NvidiaDevice',
23-
'AmdDevice', 'IntelDevice',
24-
# Brand-agnostic
25-
'ANYCPU', 'ANYGPU',
26-
# Intel CPUs
27-
'INTEL64', 'SNB', 'IVB', 'HSW', 'BDW', 'KNL', 'KNL7210',
28-
'SKX', 'KLX', 'CLX', 'CLK', 'SPR',
29-
# AMD CPUs
30-
'AMD',
31-
# ARM CPUs
32-
'ARM', 'AppleArm', 'M1', 'M2', 'M3',
33-
'Graviton', 'GRAVITON2', 'GRAVITON3', 'GRAVITON4',
34-
'Cortex', 'NvidiaArm', 'GRACE',
35-
# Other legacy CPUs
36-
'POWER8', 'POWER9',
37-
# Generic GPUs
38-
'AMDGPUX', 'NVIDIAX', 'INTELGPUX',
39-
# Nvidia GPUs
40-
'VOLTA', 'AMPERE', 'HOPPER', 'BLACKWELL',
41-
# Intel GPUs
42-
'PVC', 'INTELGPUMAX', 'MAX1100', 'MAX1550']
18+
import contextlib
19+
20+
__all__ = [
21+
# AMD CPUs
22+
'AMD',
23+
# Generic GPUs
24+
'AMDGPUX',
25+
'AMPERE',
26+
# Brand-agnostic
27+
'ANYCPU',
28+
'ANYGPU',
29+
# ARM CPUs
30+
'ARM',
31+
'BDW',
32+
'BLACKWELL',
33+
'CLK',
34+
'CLX',
35+
'GRACE',
36+
'GRAVITON2',
37+
'GRAVITON3',
38+
'GRAVITON4',
39+
'HOPPER',
40+
'HSW',
41+
# Intel CPUs
42+
'INTEL64',
43+
'INTELGPUMAX',
44+
'INTELGPUX',
45+
'IVB',
46+
'KLX',
47+
'KNL',
48+
'KNL7210',
49+
'M1',
50+
'M2',
51+
'M3',
52+
'MAX1100',
53+
'MAX1550',
54+
'NVIDIAX',
55+
# Other legacy CPUs
56+
'POWER8',
57+
'POWER9',
58+
# Intel GPUs
59+
'PVC',
60+
'SKX',
61+
'SNB',
62+
'SPR',
63+
# Nvidia GPUs
64+
'VOLTA',
65+
'Amd',
66+
'AmdDevice',
67+
'AppleArm',
68+
'Arm',
69+
'Cortex',
70+
'Cpu64',
71+
'Device',
72+
'Graviton',
73+
'Intel64',
74+
'IntelDevice',
75+
'IntelSkylake',
76+
'NvidiaArm',
77+
'NvidiaDevice',
78+
'Platform',
79+
'Power',
80+
'check_cuda_runtime',
81+
'get_advisor_path',
82+
'get_cpu_info',
83+
'get_cuda_path',
84+
'get_gpu_info',
85+
'get_hip_path',
86+
'get_m1_llvm_path',
87+
'get_nvidia_cc',
88+
'get_visible_devices',
89+
'platform_registry',
90+
]
4391

4492

4593
@memoized_func
@@ -387,7 +435,7 @@ def cbk(deviceid=0):
387435
return None
388436
return cbk
389437

390-
gpu_info['mem.%s' % i] = make_cbk(i)
438+
gpu_info[f'mem.{i}'] = make_cbk(i)
391439

392440
gpu_info['architecture'] = 'unspecified'
393441
gpu_info['vendor'] = 'INTEL'
@@ -745,7 +793,7 @@ def __str__(self):
745793
return self.name
746794

747795
def __repr__(self):
748-
return "TargetPlatform[%s]" % self.name
796+
return f"TargetPlatform[{self.name}]"
749797

750798
def _detect_isa(self):
751799
return 'unknown'
@@ -1139,10 +1187,8 @@ def march(cls):
11391187
try:
11401188
p1 = Popen(['offload-arch'], stdout=PIPE, stderr=PIPE)
11411189
except OSError:
1142-
try:
1190+
with contextlib.suppress(OSError):
11431191
p1 = Popen(['mygpu', '-d', fallback], stdout=PIPE, stderr=PIPE)
1144-
except OSError:
1145-
pass
11461192
return fallback
11471193

11481194
output, _ = p1.communicate()
@@ -1185,7 +1231,7 @@ def node_max_mem_trans_nbytes(platform):
11851231
elif isinstance(platform, Device):
11861232
return max(Cpu64.max_mem_trans_nbytes, mmtb0)
11871233
else:
1188-
assert False, f"Unknown platform type: {type(platform)}"
1234+
raise AssertionError(f"Unknown platform type: {type(platform)}")
11891235

11901236

11911237
# CPUs

0 commit comments

Comments
 (0)