This is an automated email from the ASF dual-hosted git repository.
masahi pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/tvm.git
The following commit(s) were added to refs/heads/main by this push:
new 68800fa810 [Contrib] Use f-strings for string formatting, NFC (#14893)
68800fa810 is described below
commit 68800fa8103becccfcfacf588b2b6a7ba90c4ff6
Author: Krzysztof Parzyszek <[email protected]>
AuthorDate: Sat May 20 22:40:46 2023 -0500
[Contrib] Use f-strings for string formatting, NFC (#14893)
* [Contrib] Use f-strings for string formatting, NFC
Replace uses of % and .format() with f-strings.
Reformat modified files.
* Fix linter
---
python/tvm/contrib/clang.py | 6 +-
python/tvm/contrib/cudnn.py | 6 +-
python/tvm/contrib/cutlass/build.py | 27 +++-----
python/tvm/contrib/cutlass/conv2d_operation.py | 10 +--
python/tvm/contrib/cutlass/gemm_operation.py | 21 ++----
python/tvm/contrib/cutlass/gen_conv2d.py | 2 +-
python/tvm/contrib/cutlass/gen_gemm.py | 9 +--
python/tvm/contrib/cutlass/gen_tensor_op.py | 49 ++++----------
python/tvm/contrib/cutlass/library.py | 23 ++-----
python/tvm/contrib/graph_executor.py | 2 +-
.../contrib/hexagon/profiling/process_lwp_data.py | 2 +-
python/tvm/contrib/nvcc.py | 6 +-
python/tvm/contrib/peak.py | 4 +-
python/tvm/contrib/pickle_memoize.py | 4 +-
python/tvm/contrib/pipeline_executor.py | 20 +++---
python/tvm/contrib/pipeline_executor_build.py | 22 +++---
python/tvm/contrib/rocm.py | 4 +-
python/tvm/contrib/sparse.py | 8 +--
python/tvm/contrib/tar.py | 2 +-
python/tvm/contrib/target/coreml.py | 23 ++-----
python/tvm/contrib/target/onnx.py | 79 ++++++++--------------
python/tvm/contrib/target/vitis_ai.py | 2 +-
python/tvm/contrib/tf_op/module.py | 2 +-
python/tvm/contrib/utils.py | 2 +-
python/tvm/contrib/xcode.py | 6 +-
25 files changed, 125 insertions(+), 216 deletions(-)
diff --git a/python/tvm/contrib/clang.py b/python/tvm/contrib/clang.py
index 9894447304..16c465dc22 100644
--- a/python/tvm/contrib/clang.py
+++ b/python/tvm/contrib/clang.py
@@ -45,8 +45,8 @@ def find_clang(required=True):
cc_list = []
major = tvm.target.codegen.llvm_version_major(allow_none=True)
if major is not None:
- cc_list += ["clang-%d.0" % major]
- cc_list += ["clang-%d" % major]
+ cc_list += [f"clang-{major}.0"]
+ cc_list += [f"clang-{major}"]
cc_list += ["clang"]
cc_list += ["clang.exe"]
valid_list = [utils.which(x) for x in cc_list]
@@ -91,7 +91,7 @@ def create_llvm(inputs, output=None, options=None, cc=None):
if utils.is_source_path(code):
input_files.append(code)
else:
- temp_path = temp.relpath("input%d.cc" % i)
+ temp_path = temp.relpath(f"input{i}.cc")
with open(temp_path, "w") as output_file:
output_file.write(code)
input_files.append(temp_path)
diff --git a/python/tvm/contrib/cudnn.py b/python/tvm/contrib/cudnn.py
index d3128a63dd..ff3de647fb 100644
--- a/python/tvm/contrib/cudnn.py
+++ b/python/tvm/contrib/cudnn.py
@@ -232,7 +232,7 @@ def conv_output_shape(
w_shape = w_shape[2:]
else:
- raise ValueError("Unknown CuDNN tensor format:
'{}'".format(tensor_format))
+ raise ValueError(f"Unknown CuDNN tensor format: '{tensor_format}'")
x_lanes = tvm.runtime.DataType(data_dtype).lanes
assert x_chan * x_lanes == w_chan_input * groups, (
@@ -253,7 +253,7 @@ def conv_output_shape(
elif tensor_format == 1:
output = [n_output, *output_dims, c_output]
else:
- raise ValueError("Unknown CuDNN tensor format:
'{}'".format(tensor_format))
+ raise ValueError(f"Unknown CuDNN tensor format: '{tensor_format}'")
return output
@@ -305,7 +305,7 @@ def conv_dgrad_shape(
dy_shape = dy_shape[1:-1]
w_shape = w_shape[1:-1]
else:
- raise ValueError("Unsupported CuDNN tensor format:
'{}'".format(tensor_format))
+ raise ValueError(f"Unsupported CuDNN tensor format: '{tensor_format}'")
input_dims = []
for dy_shape_i, w_shape_i, pad_i, stride_i, dilation_i, out_pad in zip(
diff --git a/python/tvm/contrib/cutlass/build.py
b/python/tvm/contrib/cutlass/build.py
index 3e5cda53d9..0fddee54e0 100644
--- a/python/tvm/contrib/cutlass/build.py
+++ b/python/tvm/contrib/cutlass/build.py
@@ -39,11 +39,9 @@ def has_cutlass():
def _get_cutlass_path():
tvm_root = os.path.join(os.path.dirname(os.path.realpath(__file__)),
"../../../../")
cutlass_path = os.path.join(tvm_root, "3rdparty/cutlass")
- assert os.path.exists(
- cutlass_path
- ), """The CUTLASS root directory not found in {}.
- Currently, using CUTLASS requires building TVM from source.""".format(
- cutlass_path
+ assert os.path.exists(cutlass_path), (
+ f"The CUTLASS root directory not found in {cutlass_path}. Currently,
using CUTLASS "
+ f"requires building TVM from source."
)
return cutlass_path
@@ -58,22 +56,22 @@ def _get_cutlass_compile_options(sm, threads,
use_fast_math=False):
kwargs["options"] = [
"-c",
"-DCUTLASS_ENABLE_TENSOR_CORE_MMA=1",
- "-gencode=arch=compute_%d,code=[sm_%d,compute_%d]" % (sm, sm, sm),
+ f"-gencode=arch=compute_{sm},code=[sm_{sm},compute_{sm}]",
"-DNDEBUG",
"-Xcompiler=-fPIC",
"-Xcompiler=-Wconversion",
"-Xcompiler=-fno-strict-aliasing",
"-O3",
"-std=c++17",
- "-I" + cutlass_include,
- "-I" + cutlass_util_include,
+ f"-I{cutlass_include}",
+ f"-I{cutlass_util_include}",
]
if use_fast_math:
kwargs["options"].append("-DCUTLASS_USE_TANH_FOR_SIGMOID")
cuda_ver = get_cuda_version()
if cuda_ver >= (11, 2):
ncpu = multiprocessing.cpu_count() if threads < 0 else threads
- kwargs["options"].append("-t %d" % ncpu)
+ kwargs["options"].append(f"-t {ncpu}")
return kwargs
@@ -89,8 +87,8 @@ class OpAnnotator(tvm.relay.ExprVisitor):
if isinstance(op, relay.Function) and "Composite" in op.attrs:
self.signature["op_type"] = op.attrs["Composite"]
for i, arg in enumerate(op.params):
- self.signature["arg%d_shape" % i] = arg.checked_type.shape
- self.signature["arg%d_dtype" % i] = arg.checked_type.dtype
+ self.signature[f"arg{i}_shape"] = arg.checked_type.shape
+ self.signature[f"arg{i}_dtype"] = arg.checked_type.dtype
self.signature["ret_shape"] = op.ret_type.shape
self.signature["ret_dtype"] = op.ret_type.dtype
self.visit(op.body)
@@ -292,10 +290,7 @@ def handle_conv2d(
else:
logger.info("Picked the first kernel found %s", name)
- return {
- "cutlass_op_def": cutlass_op_def,
- "cutlass_op_name": name,
- }
+ return {"cutlass_op_def": cutlass_op_def, "cutlass_op_name": name}
def num_cutlass_partitions(mod):
@@ -510,7 +505,7 @@ def tune_cutlass_function(
)
)
else:
- raise ValueError("%s unsupported composite" % op_type)
+ raise ValueError(f"{op_type} unsupported composite")
new_attrs = tvm.ir.make_node("DictAttrs", **new_attrs)
return relay.Function(
diff --git a/python/tvm/contrib/cutlass/conv2d_operation.py
b/python/tvm/contrib/cutlass/conv2d_operation.py
index 1444009799..94ed183ae1 100644
--- a/python/tvm/contrib/cutlass/conv2d_operation.py
+++ b/python/tvm/contrib/cutlass/conv2d_operation.py
@@ -103,7 +103,7 @@ class Conv2dOperation:
return extended_name
def layout_name(self):
- return "%s" % (ShortLayoutTypeNames[self.A.layout])
+ return f"{ShortLayoutTypeNames[self.A.layout]}"
def procedural_name(self):
"""
@@ -130,7 +130,7 @@ class Conv2dOperation:
)
if self.split_k_slices > 1:
- configuration_name += "_splitk%d" % self.split_k_slices
+ configuration_name += f"_splitk{self.split_k_slices}"
return substitute_template(
configuration_name,
@@ -139,7 +139,7 @@ class Conv2dOperation:
"extended_name": self.extended_name(),
"threadblock": threadblock,
"layout": self.layout_name(),
- "alignment": "%d" % self.A.alignment,
+ "alignment": f"{self.A.alignment}",
},
)
@@ -288,7 +288,7 @@ using ReductionStrideIndex = typename
ReductionDevice::StrideIndex;
"opcode_class": OpcodeClassTag[
operation.tile_description.math_instruction.opcode_class
],
- "arch": "cutlass::arch::Sm%d" % operation.arch,
+ "arch": f"cutlass::arch::Sm{operation.arch}",
"threadblock_shape_m":
str(operation.tile_description.threadblock_shape[0]),
"threadblock_shape_n":
str(operation.tile_description.threadblock_shape[1]),
"threadblock_shape_k":
str(operation.tile_description.threadblock_shape[2]),
@@ -535,6 +535,6 @@ def instantiate_conv2d_template(attrs, func_args):
template = substitute_template(template, aux_map)
for i, arg in enumerate(func_args):
- attrs["arg{}".format(i)] = arg
+ attrs[f"arg{i}"] = arg
return substitute_template(template, attrs)
diff --git a/python/tvm/contrib/cutlass/gemm_operation.py
b/python/tvm/contrib/cutlass/gemm_operation.py
index f37e3772a9..5ec211b684 100644
--- a/python/tvm/contrib/cutlass/gemm_operation.py
+++ b/python/tvm/contrib/cutlass/gemm_operation.py
@@ -66,12 +66,7 @@ class GemmOperation:
):
intermediate_type =
DataTypeNames[self.tile_description.math_instruction.element_a]
- return "%s%s%s%s" % (
- self.short_math_name(),
- inst_shape,
- intermediate_type,
- "gemm",
- )
+ return f"{self.short_math_name()}{inst_shape}{intermediate_type}gemm"
def extended_name(self):
"""Append data types if they differ from compute type."""
@@ -100,7 +95,7 @@ class GemmOperation:
return extended_name
def layout_name(self):
- return "%s%s" % (ShortLayoutTypeNames[self.A.layout],
ShortLayoutTypeNames[self.B.layout])
+ return
f"{ShortLayoutTypeNames[self.A.layout]}{ShortLayoutTypeNames[self.B.layout]}"
def procedural_name(self):
"""The full procedural name indicates architecture, extended name,
tile size,
@@ -116,7 +111,7 @@ class GemmOperation:
"extended_name": self.extended_name(),
"threadblock": threadblock,
"layout": self.layout_name(),
- "alignment": "%d" % self.A.alignment,
+ "alignment": f"{self.A.alignment}",
},
)
@@ -145,11 +140,7 @@ class GemmOperation:
return substitute_template(
"int lda = ${lda_val};\n\tint ldb = ${ldb_val};\n\tint ldc =
${ldc_val};\n",
- {
- "lda_val": lda,
- "ldb_val": ldb,
- "ldc_val": ldc,
- },
+ {"lda_val": lda, "ldb_val": ldb, "ldc_val": ldc},
)
@@ -217,7 +208,7 @@ class EmitGemmInstance:
"opcode_class": OpcodeClassTag[
operation.tile_description.math_instruction.opcode_class
],
- "arch": "cutlass::arch::Sm%d" % operation.arch,
+ "arch": f"cutlass::arch::Sm{operation.arch}",
"threadblock_shape_m":
str(operation.tile_description.threadblock_shape[0]),
"threadblock_shape_n":
str(operation.tile_description.threadblock_shape[1]),
"threadblock_shape_k":
str(operation.tile_description.threadblock_shape[2]),
@@ -343,6 +334,6 @@ def instantiate_gemm_template(attrs, func_args):
template = substitute_template(template, aux_map)
for i, arg in enumerate(func_args):
- attrs["arg{}".format(i)] = arg
+ attrs[f"arg{i}"] = arg
return substitute_template(template, attrs)
diff --git a/python/tvm/contrib/cutlass/gen_conv2d.py
b/python/tvm/contrib/cutlass/gen_conv2d.py
index bb26a47a55..3887fc2e2e 100644
--- a/python/tvm/contrib/cutlass/gen_conv2d.py
+++ b/python/tvm/contrib/cutlass/gen_conv2d.py
@@ -179,7 +179,7 @@ class CutlassConv2DProfiler:
def __init__(self, sm, cutlass_path, binary_path):
self.gemm_profiler = CutlassGemmProfiler(sm, cutlass_path, binary_path)
self.sm = sm
- assert sm in GENERATOR_FUNC_TABLE, "sm%d not supported yet." % sm
+ assert sm in GENERATOR_FUNC_TABLE, f"sm{sm} not supported yet."
self.engine = ProfilerEngine(sm, cutlass_path, binary_path)
self.cache = {}
diff --git a/python/tvm/contrib/cutlass/gen_gemm.py
b/python/tvm/contrib/cutlass/gen_gemm.py
index ddeddbd39c..78e19f510d 100644
--- a/python/tvm/contrib/cutlass/gen_gemm.py
+++ b/python/tvm/contrib/cutlass/gen_gemm.py
@@ -30,12 +30,7 @@ from .library import (
def create_gemm_operator_with_epilogue(
- op_type,
- tile_description,
- data_type,
- alignment,
- swizzling_functor,
- batched=False,
+ op_type, tile_description, data_type, alignment, swizzling_functor,
batched=False
):
"""
Instantiate a cutlass kernel from the given configuration,
@@ -154,7 +149,7 @@ class CutlassGemmProfiler:
"""Profile all candidate kernels and select the best one."""
def __init__(self, sm, cutlass_path, binary_path):
- assert sm in GENERATOR_FUNC_TABLE and sm in DEFAULT_KERNELS, "sm%d not
supported yet." % sm
+ assert sm in GENERATOR_FUNC_TABLE and sm in DEFAULT_KERNELS, f"sm{sm}
not supported yet."
self.engine = ProfilerEngine(sm, cutlass_path, binary_path)
self.sm = sm
self.cache = {}
diff --git a/python/tvm/contrib/cutlass/gen_tensor_op.py
b/python/tvm/contrib/cutlass/gen_tensor_op.py
index 1eeb0f4b26..855d8dc2d1 100644
--- a/python/tvm/contrib/cutlass/gen_tensor_op.py
+++ b/python/tvm/contrib/cutlass/gen_tensor_op.py
@@ -72,13 +72,7 @@ def generate_tensor_op_common(
return ops
-def generate_sm50_simt(
- out_dtype,
- arg0_dtype,
- arg1_dtype,
- op_creator,
- accumulator_dtype="float32",
-):
+def generate_sm50_simt(out_dtype, arg0_dtype, arg1_dtype, op_creator,
accumulator_dtype="float32"):
"""Gemerate GEMM or Conv2D SIMT kernels"""
# pylint: disable=unused-argument
min_cc = 50
@@ -93,11 +87,9 @@ def generate_sm50_simt(
DataType.f32,
OpcodeClass.Simt,
MathOperation.multiply_add,
- ),
- ]
- alignment_constraints = [
- 1,
+ )
]
+ alignment_constraints = [1]
tile_descriptions = [
([128, 128, 8], 2, [4, 2, 1], min_cc, max_cc),
([128, 64, 8], 2, [2, 2, 1], min_cc, max_cc),
@@ -169,7 +161,7 @@ def generate_sm75_tensor_op_1688(
DataType.s32,
OpcodeClass.TensorOp,
MathOperation.multiply_add_saturate,
- ),
+ )
]
alignment_constraints = [16, 8, 4, 2, 1]
tile_descriptions = [
@@ -183,13 +175,7 @@ def generate_sm75_tensor_op_1688(
([64, 64, 64], 2, [2, 2, 1], min_cc, max_cc),
]
elif arg0_dtype == "float32" and arg1_dtype == "float32" and out_dtype ==
"float32":
- return generate_sm50_simt(
- out_dtype,
- arg0_dtype,
- arg1_dtype,
- op_creator,
- accumlator_dtype,
- )
+ return generate_sm50_simt(out_dtype, arg0_dtype, arg1_dtype,
op_creator, accumlator_dtype)
else:
raise NotImplementedError()
@@ -271,7 +257,7 @@ def generate_sm80_tensor_op_16816(
DataType.f32,
OpcodeClass.TensorOp,
MathOperation.multiply_add_fast_f32 if use_3xtf32 else
MathOperation.multiply_add,
- ),
+ )
]
alignment_constraints = [4, 2, 1]
@@ -305,7 +291,7 @@ def generate_sm80_tensor_op_16816(
DataType.s32,
OpcodeClass.TensorOp,
MathOperation.multiply_add_saturate,
- ),
+ )
]
alignment_constraints = [16, 8, 4]
tile_descriptions = get_default_tile_descriptions(2)
@@ -354,10 +340,7 @@ def generate_sm80_tensor_op_16816(
return sm75_kernels + sm80_kernels
-GENERATOR_FUNC_TABLE = {
- 75: generate_sm75_tensor_op_1688,
- 80: generate_sm80_tensor_op_16816,
-}
+GENERATOR_FUNC_TABLE = {75: generate_sm75_tensor_op_1688, 80:
generate_sm80_tensor_op_16816}
# (Epilogue functor name, no_beta_scaling)
@@ -386,12 +369,10 @@ class ProfilerEngine:
self.cuda_arch = cuda_arch
self.binary_prefix = binary_prefix
self.cutlass = cutlass_path
- self.cflags = "-I{cutlass}/include -I{cutlass}/tools/util/include -O3
-std=c++17".format(
- cutlass=cutlass_path
- )
+ self.cflags = f"-I{cutlass_path}/include
-I{cutlass_path}/tools/util/include -O3 -std=c++17"
self.cflags += " -DCUTLASS_ENABLE_TENSOR_CORE_MMA=1"
- self.cflags += "
-gencode=arch=compute_{arch},code=[sm_{arch},compute_{arch}]".format(
- arch=cuda_arch
+ self.cflags += (
+ f"
-gencode=arch=compute_{cuda_arch},code=[sm_{cuda_arch},compute_{cuda_arch}]"
)
self.cflags += " -Xcompiler=-Wconversion
-Xcompiler=-fno-strict-aliasing"
self.cmd = "nvcc {cflags} {src} -o {output}"
@@ -503,13 +484,13 @@ def instantiate_template(func_name, annotations,
func_args):
def get_dim(shape_annot, var_name, axis_idx, batched_offset=0):
if isinstance(shape_annot, IntImm):
return str(int(shape_annot))
- return "{}->shape[{}]".format(var_name, batched_offset + axis_idx)
+ return f"{var_name}->shape[{batched_offset + axis_idx}]"
def get_batch_stride(stride_annot, arg0_idx, arg1_idx, arg0_axis_idx,
arg1_axis_idx):
if isinstance(stride_annot, IntImm):
return str(int(stride_annot))
- dim1 = func_args[arg0_idx] + "->shape[{}]".format(arg0_axis_idx)
- dim2 = func_args[arg1_idx] + "->shape[{}]".format(arg1_axis_idx)
+ dim1 = func_args[arg0_idx] + f"->shape[{arg0_axis_idx}]"
+ dim2 = func_args[arg1_idx] + f"->shape[{arg1_axis_idx}]"
return dim1 + " * " + dim2
if "dense" in func_name or "matmul" in func_name:
@@ -599,4 +580,4 @@ def instantiate_template(func_name, annotations, func_args):
code = instantiate_conv2d_template(attrs, func_args)
return CodegenResult(code, headers)
- raise ValueError("Do not have a template for {}".format(func_name))
+ raise ValueError(f"Do not have a template for {func_name}")
diff --git a/python/tvm/contrib/cutlass/library.py
b/python/tvm/contrib/cutlass/library.py
index 8632ab1564..dff166fb58 100644
--- a/python/tvm/contrib/cutlass/library.py
+++ b/python/tvm/contrib/cutlass/library.py
@@ -33,11 +33,7 @@ class DataType(enum.Enum):
s32 = enum_auto()
-ShortDataTypeNames = {
- DataType.f16: "h",
- DataType.f32: "s",
- DataType.s32: "i",
-}
+ShortDataTypeNames = {DataType.f16: "h", DataType.f32: "s", DataType.s32: "i"}
DataTypeNames = {
@@ -143,7 +139,7 @@ def substitute_template(template, values):
while changed:
changed = False
for key, value in values.items():
- regex = "\\$\\{%s\\}" % key
+ regex = f"\\$\\{{{key}\\}}"
newtext = re.sub(regex, value, text)
if newtext != text:
changed = True
@@ -155,9 +151,7 @@ class GemmKind(enum.Enum):
Gemm = enum_auto()
-GemmKindNames = {
- GemmKind.Gemm: "gemm",
-}
+GemmKindNames = {GemmKind.Gemm: "gemm"}
class EpilogueFunctor(enum.Enum):
@@ -217,11 +211,7 @@ ConvKindTag = {
}
-ConvKindNames = {
- ConvKind.Fprop: "fprop",
- ConvKind.Dgrad: "dgrad",
- ConvKind.Wgrad: "wgrad",
-}
+ConvKindNames = {ConvKind.Fprop: "fprop", ConvKind.Dgrad: "dgrad",
ConvKind.Wgrad: "wgrad"}
class StrideSupport(enum.Enum):
@@ -235,10 +225,7 @@ StrideSupportTag = {
}
-StrideSupportNames = {
- StrideSupport.Strided: "",
- StrideSupport.Unity: "unity_stride",
-}
+StrideSupportNames = {StrideSupport.Strided: "", StrideSupport.Unity:
"unity_stride"}
class IteratorAlgorithm(enum.Enum):
diff --git a/python/tvm/contrib/graph_executor.py
b/python/tvm/contrib/graph_executor.py
index 161ca5ffd0..ab94f203c2 100644
--- a/python/tvm/contrib/graph_executor.py
+++ b/python/tvm/contrib/graph_executor.py
@@ -195,7 +195,7 @@ class GraphModule(object):
if key is not None:
v = self._get_input(key)
if v is None:
- raise RuntimeError("Could not find '%s' in graph's inputs" %
key)
+ raise RuntimeError(f"Could not find '{key}' in graph's inputs")
v.copyfrom(value)
if params:
diff --git a/python/tvm/contrib/hexagon/profiling/process_lwp_data.py
b/python/tvm/contrib/hexagon/profiling/process_lwp_data.py
index 7fccfbd096..94946100dd 100644
--- a/python/tvm/contrib/hexagon/profiling/process_lwp_data.py
+++ b/python/tvm/contrib/hexagon/profiling/process_lwp_data.py
@@ -283,7 +283,7 @@ def process_data(data, func_info, so_ld_addr):
f"\nDone processing function [{prev_func_name}] but
ordered_visited_list not empty.\n"
f"\t Possible reasons -- \n"
f"\t\t1) Mismatch between model .so and json file.\n"
- f"\t\t2) LWP buffer may have overflowed resulting into missing
entries!" % prev_func_name
+ f"\t\t2) LWP buffer may have overflowed resulting into missing
entries!"
)
overall_cycles = adjust_per_loop_counts(overall_cycles, data)
diff --git a/python/tvm/contrib/nvcc.py b/python/tvm/contrib/nvcc.py
index 5a104be996..8acd620252 100644
--- a/python/tvm/contrib/nvcc.py
+++ b/python/tvm/contrib/nvcc.py
@@ -70,14 +70,14 @@ def compile_cuda(code, target_format="ptx", arch=None,
options=None, path_target
if target_format not in ["cubin", "ptx", "fatbin"]:
raise ValueError("target_format must be in cubin, ptx, fatbin")
temp_code = temp.relpath("my_kernel.cu")
- temp_target = temp.relpath("my_kernel.%s" % target_format)
+ temp_target = temp.relpath(f"my_kernel.{target_format}")
with open(temp_code, "w") as out_file:
out_file.write(code)
file_target = path_target if path_target else temp_target
cmd = ["nvcc"]
- cmd += ["--%s" % target_format, "-O3"]
+ cmd += [f"--{target_format}", "-O3"]
if isinstance(arch, list):
cmd += arch
elif isinstance(arch, str):
@@ -242,7 +242,7 @@ def find_libdevice_path(arch):
selected_path = fn
if selected_path is None:
- raise RuntimeError("Cannot find libdevice for arch
{}".format(arch))
+ raise RuntimeError(f"Cannot find libdevice for arch {arch}")
path = os.path.join(lib_path, selected_path)
return path
diff --git a/python/tvm/contrib/peak.py b/python/tvm/contrib/peak.py
index 48d0d31a45..78dae846d6 100644
--- a/python/tvm/contrib/peak.py
+++ b/python/tvm/contrib/peak.py
@@ -179,7 +179,7 @@ def measure_bandwidth_all_types(
)
max_speed = max(max_speed, speed)
type_name = base_type + str(bits)
- result.append(["%sx%d" % (type_name, lanes), max_speed])
+ result.append([f"{type_name}x{lanes}", max_speed])
if verbose:
logging.info("\t%-10s %.2f GBPS", result[-1][0],
result[-1][1])
return result
@@ -343,7 +343,7 @@ def measure_compute_all_types(
)
max_speed = max(max_speed, speed)
type_name = base_type + str(bits)
- result.append(["%sx%d" % (type_name, lanes), max_speed])
+ result.append([f"{type_name}x{lanes}", max_speed])
unit = "GFLOPS" if base_type == "float" else "GIOPS"
diff --git a/python/tvm/contrib/pickle_memoize.py
b/python/tvm/contrib/pickle_memoize.py
index d875046038..6d2ffbac06 100644
--- a/python/tvm/contrib/pickle_memoize.py
+++ b/python/tvm/contrib/pickle_memoize.py
@@ -42,7 +42,7 @@ class Cache(object):
cache_by_key = {}
def __init__(self, key, save_at_exit):
- cache_dir = ".pkl_memoize_py{0}".format(sys.version_info[0])
+ cache_dir = f".pkl_memoize_py{sys.version_info[0]}"
try:
os.mkdir(cache_dir)
except FileExistsError:
@@ -62,7 +62,7 @@ class Cache(object):
def save(self):
if self.dirty:
- print("Save memoize result to %s" % self.path)
+ print(f"Save memoize result to {self.path}")
with open(self.path, "wb") as out_file:
pickle.dump(self.cache, out_file, pickle.HIGHEST_PROTOCOL)
diff --git a/python/tvm/contrib/pipeline_executor.py
b/python/tvm/contrib/pipeline_executor.py
index b614630737..d6be16653c 100644
--- a/python/tvm/contrib/pipeline_executor.py
+++ b/python/tvm/contrib/pipeline_executor.py
@@ -198,7 +198,7 @@ class PipelineModule(object):
config = json.loads(config)
if "load_config" not in config or "pipeline_config" not in config:
raise RuntimeError(
- '"load_config" or "pipeline_config" is missing in %s' %
config_file_name
+ f'"load_config" or "pipeline_config" is missing in
{config_file_name}'
)
# The config file used to load library, prameters, and JSON files.
@@ -297,8 +297,8 @@ class PipelineExecutorFactoryModule(object):
if not os.path.exists(directory_path):
raise RuntimeError("The directory {directory_path} does not
exist.")
# Create an load configuration.
- load_config_file_name = "{}/load_config".format(directory_path)
- pipeline_config_file_name = "{}/pipeline_config".format(directory_path)
+ load_config_file_name = f"{directory_path}/load_config"
+ pipeline_config_file_name = f"{directory_path}/pipeline_config"
config = {}
config["load_config"] = load_config_file_name
config["pipeline_config"] = pipeline_config_file_name
@@ -308,12 +308,12 @@ class PipelineExecutorFactoryModule(object):
for lib_index in self.pipeline_mods:
mconfig = {}
mconfig["mod_idx"] = lib_index
- mconfig["lib_name"] = "{}/lib{}.so".format(directory_path,
lib_index)
- mconfig["json_name"] = "{}/json{}".format(directory_path,
lib_index)
- mconfig["params_name"] = "{}/params{}".format(directory_path,
lib_index)
- mconfig["dev"] = "{},{}".format(
- self.pipeline_mods[lib_index]["dev"].device_type,
- self.pipeline_mods[lib_index]["dev"].device_id,
+ mconfig["lib_name"] = f"{directory_path}/lib{lib_index}.so"
+ mconfig["json_name"] = f"{directory_path}/json{lib_index}"
+ mconfig["params_name"] = f"{directory_path}/params{lib_index}"
+ mconfig["dev"] = (
+ f"{self.pipeline_mods[lib_index]['dev'].device_type},"
+ f"{self.pipeline_mods[lib_index]['dev'].device_id}"
)
# Get the graph, lib, and parameters from
GraphExecutorFactoryModule.
lib = self.pipeline_mods[lib_index]["lib"]
@@ -338,7 +338,7 @@ class PipelineExecutorFactoryModule(object):
with open(pipeline_config_file_name, "w") as file_handle:
json.dump(self.mods_config, file_handle)
- config_file_name = "{}/config".format(directory_path)
+ config_file_name = f"{directory_path}/config"
with open(config_file_name, "w") as file_handle:
json.dump(config, file_handle)
diff --git a/python/tvm/contrib/pipeline_executor_build.py
b/python/tvm/contrib/pipeline_executor_build.py
index ac2a681ef5..8ea70f670a 100644
--- a/python/tvm/contrib/pipeline_executor_build.py
+++ b/python/tvm/contrib/pipeline_executor_build.py
@@ -83,7 +83,7 @@ def build(pipe_configs):
mod_name=mod_config["mod_name"],
)
- pipe_config["dev"] = "{},{}".format(dev.device_type, dev.device_id)
+ pipe_config["dev"] = f"{dev.device_type},{dev.device_id}"
# Use "mod_idx" as the key to create a "module_connection" map which
is not only
# for the module index but also for the module connection used to
build the pipeline.
module_string_config[mod_idx] = pipe_config
@@ -123,8 +123,8 @@ def export_library(factory, directory_path):
if not directory_path or not os.path.exists(directory_path):
raise RuntimeError("The directory {directory_path} does not exist.")
# Create an load configuration.
- load_config_file_name = "{}/load_config".format(directory_path)
- pipeline_config_file_name = "{}/pipeline_config".format(directory_path)
+ load_config_file_name = f"{directory_path}/load_config"
+ pipeline_config_file_name = f"{directory_path}/pipeline_config"
config = {}
config["load_config"] = load_config_file_name
config["pipeline_config"] = pipeline_config_file_name
@@ -134,11 +134,11 @@ def export_library(factory, directory_path):
for lib_index in factory.pipeline_mods:
mconfig = {}
mconfig["mod_idx"] = lib_index
- mconfig["lib_name"] = "{}/lib{}.so".format(directory_path, lib_index)
- mconfig["json_name"] = "{}/json{}".format(directory_path, lib_index)
- mconfig["params_name"] = "{}/params{}".format(directory_path,
lib_index)
+ mconfig["lib_name"] = f"{directory_path}/lib{lib_index}.so"
+ mconfig["json_name"] = f"{directory_path}/json{lib_index}"
+ mconfig["params_name"] = f"{directory_path}/params{lib_index}"
lib_config = factory.pipeline_mods[lib_index]
- mconfig["dev"] = "{},{}".format(lib_config["dev"].device_type,
lib_config["dev"].device_id)
+ mconfig["dev"] = f"{lib_config['dev'].device_type},"
f"{lib_config['dev'].device_id}"
fcompile = lib_config["fcompile"]
if not fcompile:
fcompile = False
@@ -160,7 +160,7 @@ def export_library(factory, directory_path):
with open(pipeline_config_file_name, "w") as file_handle:
json.dump(factory.mods_config, file_handle)
- config_file_name = "{}/config".format(directory_path)
+ config_file_name = f"{directory_path}/config"
with open(config_file_name, "w") as file_handle:
json.dump(config, file_handle)
@@ -229,10 +229,10 @@ class PipelineConfig(object):
def __repr__(self):
# Geting the binding information in the form of text.
- str_format = " |{}: ".format(self.name)
+ str_format = f" |{self.name}: "
for binding in self.bindings:
mname, dname = binding.get_name()
- str_format += "{0}:{1} ".format(mname, dname)
+ str_format += f"{mname}:{dname} "
return str_format
@@ -478,7 +478,7 @@ class PipelineConfig(object):
def set_idx_name(self, idx):
# Set the index value and generate the module name.
self.idx = idx
- self.name = "mod{}".format(str(idx))
+ self.name = f"mod{str(idx)}"
def is_root_mod(self):
"""Check whether this node is the root node in DAG, this function
is used
diff --git a/python/tvm/contrib/rocm.py b/python/tvm/contrib/rocm.py
index 372281dbab..b33e20cbc1 100644
--- a/python/tvm/contrib/rocm.py
+++ b/python/tvm/contrib/rocm.py
@@ -48,8 +48,8 @@ def find_lld(required=True):
lld_list = []
major = tvm.target.codegen.llvm_version_major(allow_none=True)
if major is not None:
- lld_list += ["ld.lld-%d.0" % major]
- lld_list += ["ld.lld-%d" % major]
+ lld_list += [f"ld.lld-{major}.0"]
+ lld_list += [f"ld.lld-{major}"]
lld_list += ["ld.lld"]
valid_list = [utils.which(x) for x in lld_list]
valid_list = [x for x in valid_list if x]
diff --git a/python/tvm/contrib/sparse.py b/python/tvm/contrib/sparse.py
index d515f58f9d..d561c5cbb1 100644
--- a/python/tvm/contrib/sparse.py
+++ b/python/tvm/contrib/sparse.py
@@ -65,8 +65,8 @@ class CSRNDArray(object):
self.shape = source_array.shape
else:
raise RuntimeError(
- "Construct CSRNDArray with either a tuple (data, indices,
indptr) "
- "or a numpy.array, can't handle type %s." % (type(arg1),)
+ f"Construct CSRNDArray with either a tuple (data, indices,
indptr) "
+ f"or a numpy.array, can't handle type {type(arg1)}."
)
self.stype = "csr"
self.dtype = self.data.dtype
@@ -106,7 +106,7 @@ def array(source_array, device=None, shape=None,
stype="csr"):
if stype == "csr":
ret = CSRNDArray(source_array, shape=shape, device=device)
else:
- raise NotImplementedError("stype=%s is not supported yet." % (stype,))
+ raise NotImplementedError(f"stype={stype} is not supported yet.")
return ret
@@ -200,5 +200,5 @@ def placeholder(shape, nonzeros=None, dtype=None,
name="placeholder", stype=None
if stype == "csr":
ret = CSRPlaceholderOp(shape=shape, nonzeros=nonzeros, dtype=dtype,
name=name)
else:
- raise NotImplementedError("stype=%s is not supported yet." % (stype,))
+ raise NotImplementedError(f"stype={stype} is not supported yet.")
return ret
diff --git a/python/tvm/contrib/tar.py b/python/tvm/contrib/tar.py
index 717b3fb9b1..67175b8b27 100644
--- a/python/tvm/contrib/tar.py
+++ b/python/tvm/contrib/tar.py
@@ -43,7 +43,7 @@ def tar(output, files):
for fname in files:
base = os.path.basename(fname)
if base in fset:
- raise ValueError("duplicate file name %s" % base)
+ raise ValueError(f"duplicate file name {base}")
fset.add(base)
shutil.copy(fname, temp.relpath(base))
cmd += [output]
diff --git a/python/tvm/contrib/target/coreml.py
b/python/tvm/contrib/target/coreml.py
index b5a03e3804..8ff9e2210c 100644
--- a/python/tvm/contrib/target/coreml.py
+++ b/python/tvm/contrib/target/coreml.py
@@ -145,23 +145,8 @@ class CodegenCoreML(ExprVisitor):
# Update inputs and outputs after we visit all the nodes.
# Set dummy values for now.
# TODO: support multiple outputs
- inputs = [
- (
- "",
- coremltools.models.datatypes.Array(
- 1,
- ),
- )
- for _ in self.function.params
- ]
- outputs = [
- (
- "",
- coremltools.models.datatypes.Array(
- 1,
- ),
- )
- ]
+ inputs = [("", coremltools.models.datatypes.Array(1)) for _ in
self.function.params]
+ outputs = [("", coremltools.models.datatypes.Array(1))]
self.builder = NeuralNetworkBuilder(inputs, outputs,
disable_rank5_shape_mapping=True)
def visit_constant(self, const):
@@ -192,7 +177,7 @@ class CodegenCoreML(ExprVisitor):
op_name = call.op.name
layer_name = op_name + "_" + str(self.buf_idx_)
- assert op_name in _convert_map, "{} is not supported".format(op_name)
+ assert op_name in _convert_map, f"{op_name} is not supported"
_convert_map[op_name](self.builder, layer_name, inputs, outputs,
call.args, call.attrs)
self.buf_idx_ = self.buf_idx_ + 1
@@ -239,7 +224,7 @@ def coreml_compiler(func):
name = str(func.attrs.global_symbol)
builder = CodegenCoreML(name, func)
builder.visit(func.body)
- mlmodelc_path = "{}/{}.mlmodelc".format(model_dir, name)
+ mlmodelc_path = f"{model_dir}/{name}.mlmodelc"
if os.path.exists(mlmodelc_path):
shutil.rmtree(mlmodelc_path)
builder.compile(model_dir)
diff --git a/python/tvm/contrib/target/onnx.py
b/python/tvm/contrib/target/onnx.py
index 272598f7c3..239bf1e4b1 100644
--- a/python/tvm/contrib/target/onnx.py
+++ b/python/tvm/contrib/target/onnx.py
@@ -91,15 +91,13 @@ def call_node_infer_type(node):
elif isinstance(out_type, TupleType):
types = list(out_type.fields)
else:
- raise RuntimeError(
- "Unsupported output type %s in operator %s" % (type(out_type),
node.op.nae)
- )
+ raise RuntimeError(f"Unsupported output type {type(out_type)} in
operator {node.op.name}")
return types
def add_input(data, name, prefix, model_container):
- input_name = "{}_{}".format(prefix, name)
+ input_name = f"{prefix}_{name}"
dtype = onnx.mapping.NP_TYPE_TO_TENSOR_TYPE[data.dtype]
tensor_value_info = onnx.helper.make_tensor_value_info(input_name, dtype,
shape=data.shape)
model_container.add_inputs([tensor_value_info])
@@ -212,7 +210,7 @@ class MatMul(OpConverter):
@classmethod
def convert(cls, node_entry, model_container, node_dict):
- inter_output_name = "inter{}".format(node_entry["name"])
+ inter_output_name = f"inter{node_entry['name']}"
transpose_node = onnx.helper.make_node(
Transpose.__name__, [node_entry["input_names"][1]],
[inter_output_name], perm=(1, 0)
)
@@ -228,9 +226,7 @@ class Flatten(OpConverter):
@classmethod
def convert_attributes(cls, attrs):
- return {
- "axis": 1,
- }
+ return {"axis": 1}
class BatchNormalization(OpConverter):
@@ -238,10 +234,7 @@ class BatchNormalization(OpConverter):
@classmethod
def convert_attributes(cls, attrs):
- return {
- "epsilon": float(attrs.get_str("epsilon")),
- "axis": float(attrs.get_int("axis")),
- }
+ return {"epsilon": float(attrs.get_str("epsilon")), "axis":
float(attrs.get_int("axis"))}
@classmethod
def convert(cls, node_entry, model_container, node_dict):
@@ -253,7 +246,7 @@ class BatchNormalization(OpConverter):
inter_output_names = [node_entry["output_names"][0]]
# axis==3 means channel is specified along the 3rd axis
if attrs["axis"] == 3:
- transpose_out_name = "transpose_{}".format(node_entry["name"])
+ transpose_out_name = f"transpose_{node_entry['name']}"
node_transposed = onnx.helper.make_node(
Transpose.__name__,
[node_entry["input_names"][0]],
@@ -261,7 +254,7 @@ class BatchNormalization(OpConverter):
perm=[0, 3, 1, 2],
)
model_container.add_nodes([node_transposed])
- inter_output_names = ["batch_norm_{}".format(node_entry["name"])]
+ inter_output_names = [f"batch_norm_{node_entry['name']}"]
input_names = [transpose_out_name] + node_entry["input_names"][1:]
batch_norm_node = onnx.helper.make_node(
@@ -284,9 +277,7 @@ class Dropout(OpConverter):
@classmethod
def convert_attributes(cls, attrs):
- return {
- "ratio": float(attrs.get_str("rate")),
- }
+ return {"ratio": float(attrs.get_str("rate"))}
class AveragePool(MaxPool):
@@ -298,9 +289,7 @@ class Concat(OpConverter):
@classmethod
def convert_attributes(cls, attrs):
- return {
- "axis": attrs.get_int("axis"),
- }
+ return {"axis": attrs.get_int("axis")}
class BiasAdd(OpConverter):
@@ -317,7 +306,7 @@ class BiasAdd(OpConverter):
axis = axis + data_ndim
new_axes = data_ndim - axis - 1
if new_axes:
- inter_output_name = "inter{}".format(node_entry["name"])
+ inter_output_name = f"inter{node_entry['name']}"
unsqueeze_node = onnx.helper.make_node(
"Unsqueeze",
[node_entry["input_names"][1]],
@@ -379,10 +368,7 @@ class Pad(OpConverter):
after.append(axis_pads[1])
pads = before + after
pads = numpy.asarray(pads, dtype=pads[0].dtype)
- return {
- "pads": pads,
- "mode": attrs.get_str("pad_mode"),
- }
+ return {"pads": pads, "mode": attrs.get_str("pad_mode")}
@classmethod
def convert(cls, node_entry, model_container, node_dict):
@@ -412,9 +398,7 @@ class Softmax(OpConverter):
@classmethod
def convert_attributes(cls, attrs):
- return {
- "axis": attrs.axis,
- }
+ return {"axis": attrs.axis}
class Squeeze(OpConverter):
@@ -422,9 +406,7 @@ class Squeeze(OpConverter):
@classmethod
def convert_attributes(cls, attrs):
- return {
- "axes": attrs.axis,
- }
+ return {"axes": attrs.axis}
@classmethod
def convert(cls, node_entry, model_container, node_dict):
@@ -513,10 +495,7 @@ class Split(OpConverter):
if isinstance(indices_or_sections, tvm.ir.PrimExpr):
indices_or_sections = indices_or_sections.value
- return {
- "indices_or_section": indices_or_sections,
- "axis": attrs.get_int("axis"),
- }
+ return {"indices_or_section": indices_or_sections, "axis":
attrs.get_int("axis")}
@classmethod
def convert(cls, node_entry, model_container, node_dict):
@@ -679,8 +658,8 @@ class LRN(OpConverter):
Onnx only supports axis=1 (channels)."""
if attrs.get_int("axis") != 1:
raise RuntimeError(
- "Unsupported axis %s in operator relay lrn operator. "
- "Only axis = 1 is supported by Onnx." % (attrs.get_int("axis"))
+ f"Unsupported axis {attrs.get_int('axis')} in operator relay
lrn operator. "
+ f"Only axis = 1 is supported by Onnx."
)
return {"alpha": attrs.alpha, "beta": attrs.beta, "bias": attrs.bias,
"size": attrs.size}
@@ -707,7 +686,7 @@ class Resize(OpConverter):
elif "cubic" in method: # cubic / bicubic
mode = b"cubic"
else:
- raise RuntimeError("Unsupported method %s in operator Resize" %
method)
+ raise RuntimeError(f"Unsupported method {method} in operator
Resize")
coord_trans = attrs.get_str("coordinate_transformation_mode")
if coord_trans == "half_pixel":
@@ -718,7 +697,7 @@ class Resize(OpConverter):
coord_trans = b"asymmetric"
else:
raise RuntimeError(
- "Unsupported coordinate transform mode %s in operator Resize"
% coord_trans
+ f"Unsupported coordinate transform mode {coord_trans} in
operator Resize"
)
rounding_method = attrs.get_str("rounding_method")
@@ -729,9 +708,7 @@ class Resize(OpConverter):
elif rounding_method == "ceil":
rounding_method = b"ceil"
else:
- raise RuntimeError(
- "Unsupported rounding method %s in operator Resize" %
rounding_method
- )
+ raise RuntimeError(f"Unsupported rounding method {rounding_method}
in operator Resize")
size = attrs.get_int_tuple("size")
@@ -959,7 +936,7 @@ class RelayToONNXConverter(ExprVisitor):
def visit_call(self, call):
node_index = self._node_count
op = call.op
- name = "{}_{}".format(op, node_index)
+ name = f"{op}_{node_index}"
node_entry = self._get_node_entry(call, name)
node_entry["op"] = op
@@ -986,7 +963,7 @@ class RelayToONNXConverter(ExprVisitor):
"""Convert Relay operator node to ONNX operator and add it to
container nodes list"""
if node_entry["op"].name not in relay_to_onnx_op_mapping:
raise NotImplementedError(
- "Currently the operator '{0}' is " "not
supported.".format(node_entry["op"].name)
+ f"Currently the operator '{node_entry['op'].name}' is " "not
supported."
)
converter = relay_to_onnx_op_mapping[node_entry["op"].name]()
@@ -995,9 +972,9 @@ class RelayToONNXConverter(ExprVisitor):
def _add_params(self, node_entry, idx):
"""Add param value to initializer and name to inputs"""
param_name = node_entry["name"]
- assert (
- param_name in self._params
- ), "The parameter {0} is not present" "in params dict
provided.".format(param_name)
+ assert param_name in self._params, (
+ f"The parameter {param_name} is not present" "in params dict
provided."
+ )
value = self._params[param_name]
numpy_array = value.numpy()
tensor = numpy_helper.from_array(numpy_array, param_name)
@@ -1071,10 +1048,8 @@ def to_onnx(relay_ir, params, name, opset_version=11,
path=None):
if opset_version > defs.onnx_opset_version():
raise Exception(
- "The ONNX package installed of version {} does not support the
opset "
- "version {}. Upgrade the ONNX package to latest version.".format(
- get_onnx_version(), opset_version
- )
+ f"The ONNX package installed of version {get_onnx_version()} does
not support the "
+ f"opset version {opset_version}. Upgrade the ONNX package to
latest version."
)
func = relay_ir["main"] if isinstance(relay_ir, tvm.ir.IRModule) else
relay_ir
@@ -1132,4 +1107,4 @@ def save_to_file(hex_str, path=None, fmt="onnx"):
offset = stop + model_size
model_onnx = onnx.load_model_from_string(model_serialized)
- onnx.save(model_onnx, "{}{}{}.{}".format(path, os.path.sep, name, fmt))
+ onnx.save(model_onnx, f"{path}{os.path.sep}{name}.{fmt}")
diff --git a/python/tvm/contrib/target/vitis_ai.py
b/python/tvm/contrib/target/vitis_ai.py
index 837e6604bb..1ab52ed724 100644
--- a/python/tvm/contrib/target/vitis_ai.py
+++ b/python/tvm/contrib/target/vitis_ai.py
@@ -113,7 +113,7 @@ class CodegenVitisAI:
elif isinstance(expr, TupleGetItem):
output_relay_ids.append(hash(expr.tuple_value))
else:
- raise ValueError("Vitis-AI codegen does not support {} as
output".format(type(expr)))
+ raise ValueError(f"Vitis-AI codegen does not support {type(expr)}
as output")
return output_relay_ids
diff --git a/python/tvm/contrib/tf_op/module.py
b/python/tvm/contrib/tf_op/module.py
index 2572d5b33d..bcff274163 100644
--- a/python/tvm/contrib/tf_op/module.py
+++ b/python/tvm/contrib/tf_op/module.py
@@ -102,7 +102,7 @@ class TensorFunc:
if not isinstance(dim_value, int):
return False
if dim_value < 0:
- raise Exception("Negative dimension is illegal: %d" %
dim_value)
+ raise Exception(f"Negative dimension is illegal: {dim_value}")
return True
def _pack_shape_tensor(self, shape):
diff --git a/python/tvm/contrib/utils.py b/python/tvm/contrib/utils.py
index 89688b5bf8..4c5cb848fe 100644
--- a/python/tvm/contrib/utils.py
+++ b/python/tvm/contrib/utils.py
@@ -131,7 +131,7 @@ class TempDirectory(object):
def __truediv__(self, other):
if not isinstance(other, (str, pathlib.Path)):
raise TypeError(
- "TempDirectory / operator: must supply str or pathlib.Path;
got %r" % (other,)
+ f"TempDirectory / operator: must supply str or pathlib.Path;
got {repr(other)}"
)
return self.path / other
diff --git a/python/tvm/contrib/xcode.py b/python/tvm/contrib/xcode.py
index 236341e1a4..2b68600197 100644
--- a/python/tvm/contrib/xcode.py
+++ b/python/tvm/contrib/xcode.py
@@ -50,7 +50,7 @@ def __get_min_os_version(sdk):
return None
if sdk in ("iphoneos", "iphonesimulator"):
return "13.0"
- raise RuntimeError("Unsupported sdk: %s" % sdk)
+ raise RuntimeError(f"Unsupported sdk: {sdk}")
def __get_min_os_version_cmd(sdk, min_os_version):
@@ -146,7 +146,7 @@ def compile_metal(code, path_target=None, sdk="macosx",
min_os_version=None):
elif sdk in ("iphoneos", "iphonesimulator"):
language_version = "-std=ios-metal2.3"
else:
- raise RuntimeError("Unsupported sdk: %s" % sdk)
+ raise RuntimeError(f"Unsupported sdk: {sdk}")
cmd1 = ["xcrun", "-sdk", sdk, "metal", language_version, min_target, "-O3"]
cmd1 += ["-c", temp_code, "-o", temp_ir]
cmd2 = ["xcrun", "-sdk", sdk, "metallib"]
@@ -179,6 +179,6 @@ def compile_coreml(model, model_name="main", out_dir="."):
res = xcrun(["coremlcompiler", "compile", mlmodel_path, out_dir])
if not os.path.isdir(mlmodelc_path):
- raise RuntimeError("Compile failed: %s" % res)
+ raise RuntimeError(f"Compile failed: {res}")
return mlmodelc_path