You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@tvm.apache.org by ma...@apache.org on 2023/03/09 23:59:03 UTC
[tvm] branch unity updated: [Unity][BYOC] Add conv2d and residual block patterns for Relax cutlass BYOC (#14252)
This is an automated email from the ASF dual-hosted git repository.
masahi pushed a commit to branch unity
in repository https://gitbox.apache.org/repos/asf/tvm.git
The following commit(s) were added to refs/heads/unity by this push:
new e56dc13c58 [Unity][BYOC] Add conv2d and residual block patterns for Relax cutlass BYOC (#14252)
e56dc13c58 is described below
commit e56dc13c58acd78ebb64215460d3cdc42c7c699d
Author: Lite Ye <ye...@gmail.com>
AuthorDate: Thu Mar 9 18:58:57 2023 -0500
[Unity][BYOC] Add conv2d and residual block patterns for Relax cutlass BYOC (#14252)
* Add conv2d and residual block pattern for cutlass
* Fix lint
---
python/tvm/contrib/cutlass/build.py | 16 +-
python/tvm/contrib/cutlass/conv2d_operation.py | 15 +-
python/tvm/contrib/cutlass/gen_tensor_op.py | 34 ++--
python/tvm/relax/backend/contrib/cutlass.py | 237 ++++++++++++++++---------
python/tvm/relax/backend/patterns.py | 47 ++++-
tests/python/relax/test_codegen_cutlass.py | 136 +++++++++++---
6 files changed, 348 insertions(+), 137 deletions(-)
diff --git a/python/tvm/contrib/cutlass/build.py b/python/tvm/contrib/cutlass/build.py
index 95d9363bc6..416c780fec 100644
--- a/python/tvm/contrib/cutlass/build.py
+++ b/python/tvm/contrib/cutlass/build.py
@@ -633,13 +633,17 @@ class CutlassRelaxFunctionAnnotator(relax.PyExprMutator):
def handle_conv2d(self, f, op_type):
"""Tune and annotate a conv2d op."""
signature = _extract_relax_function_signature(f)
+ arg_idx = _extract_arg_idx(op_type, f)
op_attrs = _get_call_node(f.body, "relax.nn.conv2d").attrs
- d_shape = signature["arg0_shape"]
- w_shape = signature["arg1_shape"]
+ data_arg = f"arg{arg_idx['lhs']}"
+ weight_arg = f"arg{arg_idx['rhs']}"
+
+ d_shape = signature[f"{data_arg}_shape"]
+ w_shape = signature[f"{weight_arg}_shape"]
out_shape = signature["ret_shape"]
- data_dtype = signature["arg0_dtype"]
- weight_dtype = signature["arg1_dtype"]
+ data_dtype = signature[f"{data_arg}_dtype"]
+ weight_dtype = signature[f"{weight_arg}_dtype"]
out_dtype = signature["ret_dtype"]
padding = op_attrs["padding"]
strides = op_attrs["strides"]
@@ -673,6 +677,10 @@ class CutlassRelaxFunctionAnnotator(relax.PyExprMutator):
return f.with_attrs(
{
"op_type": op_type,
+ "data_arg_idx": arg_idx["lhs"],
+ "weight_arg_idx": arg_idx["rhs"],
+ "bias_arg_idx": arg_idx.get("bias"),
+ "residual_arg_idx": arg_idx.get("residual"),
"arg0_dtype": data_dtype,
"arg1_dtype": weight_dtype,
"ret_dtype": out_dtype,
diff --git a/python/tvm/contrib/cutlass/conv2d_operation.py b/python/tvm/contrib/cutlass/conv2d_operation.py
index 1444009799..5996d50d88 100644
--- a/python/tvm/contrib/cutlass/conv2d_operation.py
+++ b/python/tvm/contrib/cutlass/conv2d_operation.py
@@ -354,7 +354,7 @@ using ReductionStrideIndex = typename ReductionDevice::StrideIndex;
return substitute_template(template, values)
-def instantiate_conv2d_template(attrs, func_args):
+def instantiate_conv2d_template(attrs):
"""Return CUTLASS host code for conv2d based on a template and the provided attribute map."""
template = """
${cutlass_op_def}
@@ -382,8 +382,8 @@ def instantiate_conv2d_template(attrs, func_args):
cutlass::conv::Conv2dProblemSize problem_size(N, H, W, C, K, R, S, P, Q, pad_h, pad_w, stride_h, stride_w, dilation_h, dilation_w, cutlass::conv::Mode::kCrossCorrelation, split_k_slices);
const cutlass::conv::SplitKMode split_k_mode = cutlass::conv::SplitKMode::${split_k_mode};
- void* ptr_a = (void*)(${arg0}->data);
- void* ptr_b = (void*)(${arg1}->data);
+ void* ptr_a = (void*)(${data_arg}->data);
+ void* ptr_b = (void*)(${weight_arg}->data);
${bias_decl}
${residual_decl}
void* ptr_out = (void*)(out0->data);
@@ -481,12 +481,12 @@ def instantiate_conv2d_template(attrs, func_args):
aux_map["beta"] = "1"
if has_residual_blcok:
- aux_map["bias_decl"] = "void* ptr_bias = (void*)(${arg2}->data);\n"
- aux_map["residual_decl"] = "void* ptr_residual = (void*)(${arg3}->data);"
+ aux_map["bias_decl"] = "void* ptr_bias = (void*)(${bias_arg}->data);\n"
+ aux_map["residual_decl"] = "void* ptr_residual = (void*)(${residual_arg}->data);"
aux_map["tensor_c"] = "ptr_residual"
aux_map["tensor_c_layout"] = "layout_C"
elif has_bias:
- aux_map["bias_decl"] = "void* ptr_c_bias = (void*)(${arg2}->data);\n"
+ aux_map["bias_decl"] = "void* ptr_c_bias = (void*)(${bias_arg}->data);\n"
aux_map["residual_decl"] = ""
aux_map["tensor_c"] = "ptr_c_bias"
aux_map["tensor_c_layout"] = "cutlass::layout::TensorNHWC::Stride(0)"
@@ -534,7 +534,4 @@ 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
-
return substitute_template(template, attrs)
diff --git a/python/tvm/contrib/cutlass/gen_tensor_op.py b/python/tvm/contrib/cutlass/gen_tensor_op.py
index 62c06cabd1..9833600be0 100644
--- a/python/tvm/contrib/cutlass/gen_tensor_op.py
+++ b/python/tvm/contrib/cutlass/gen_tensor_op.py
@@ -28,9 +28,9 @@ from tvm.runtime import Object
from tvm.tir import IntImm
from . import _ffi_api as ffi
+from .attention_operation import instantiate_attention_template
from .conv2d_operation import instantiate_conv2d_template
from .gemm_operation import instantiate_gemm_template
-from .attention_operation import instantiate_attention_template
from .library import (
DataType,
DataTypeSize,
@@ -463,9 +463,9 @@ class CodegenResult(Object):
def _get_optional_int_annotation(annotations, key, default=None):
value = annotations.get(key, default)
- if value is not None:
- return int(value)
- return value
+ if value is None:
+ return default
+ return int(value)
@tvm._ffi.register_func("contrib.cutlass.instantiate_template")
@@ -614,10 +614,21 @@ def instantiate_template(func_name, annotations, func_args):
return CodegenResult(code, headers)
elif "conv2d" in func_name:
- activation_shape = arg0_shape
- weight_shape = arg1_shape
+ data_arg_idx = _get_optional_int_annotation(annotations, "data_arg_idx", 0)
+ weight_arg_idx = _get_optional_int_annotation(annotations, "weight_arg_idx", 1)
+ bias_arg_idx = _get_optional_int_annotation(annotations, "bias_arg_idx", 2)
+ residual_arg_idx = _get_optional_int_annotation(annotations, "residual_arg_idx", 3)
+
+ attrs["data_arg"] = func_args[data_arg_idx]
+ attrs["weight_arg"] = func_args[weight_arg_idx]
+ if len(func_args) > bias_arg_idx:
+ attrs["bias_arg"] = func_args[bias_arg_idx]
+ if len(func_args) > residual_arg_idx:
+ attrs["residual_arg"] = func_args[residual_arg_idx]
+
+ activation_shape = annotations[f"arg{data_arg_idx}_shape"]
+ weight_shape = annotations[f"arg{weight_arg_idx}_shape"]
output_shape = annotations["ret_shape"]
- activation_var = func_args[0]
if "conv2d_transpose" in func_name:
headers.append("cutlass/conv/kernel/default_conv2d_dgrad.h")
@@ -643,9 +654,10 @@ def instantiate_template(func_name, annotations, func_args):
"cutlass/reduction/thread/reduction_operators.h",
]
- attrs["N"] = get_dim(activation_shape[0], activation_var, 0)
- attrs["H"] = get_dim(activation_shape[1], activation_var, 1)
- attrs["W"] = get_dim(activation_shape[2], activation_var, 2)
+ data_arg = attrs["data_arg"]
+ attrs["N"] = get_dim(activation_shape[0], data_arg, 0)
+ attrs["H"] = get_dim(activation_shape[1], data_arg, 1)
+ attrs["W"] = get_dim(activation_shape[2], data_arg, 2)
attrs["C"] = activation_shape[3]
attrs["P"] = get_dim(output_shape[1], "out0", 1)
attrs["Q"] = get_dim(output_shape[2], "out0", 2)
@@ -666,7 +678,7 @@ def instantiate_template(func_name, annotations, func_args):
attrs["split_k_mode"] = "kSerial"
attrs["split_k_slices"] = 1
- code = instantiate_conv2d_template(attrs, func_args)
+ code = instantiate_conv2d_template(attrs)
return CodegenResult(code, headers)
elif "attention" in func_name:
diff --git a/python/tvm/relax/backend/contrib/cutlass.py b/python/tvm/relax/backend/contrib/cutlass.py
index 17af2e0597..29026b194d 100644
--- a/python/tvm/relax/backend/contrib/cutlass.py
+++ b/python/tvm/relax/backend/contrib/cutlass.py
@@ -26,9 +26,10 @@ from tvm.relax.dpl import CallPattern, DFPattern
from ..pattern_registry import get_patterns_with_prefix, register_patterns
from ..patterns import (
+ make_attention_pattern,
make_fused_bias_activation_pattern,
make_matmul_pattern,
- make_attention_pattern,
+ make_residual_block_pattern,
)
@@ -51,21 +52,59 @@ def _is_supported_dtype(lhs_dtype, rhs_dtype):
)
-def _check_matmul(
- match_result: Mapping[DFPattern, Expr],
- _: Expr,
-) -> bool:
- matmul_call: Call = None
+def _find_call(op_name: str, match_result: Mapping[DFPattern, Expr]) -> Optional[Expr]:
+ result = None
+
for pattern, expr in match_result.items():
if (
isinstance(expr, Call)
and isinstance(pattern, CallPattern)
and isinstance(expr.op, tvm.ir.Op)
- and expr.op.name == "relax.matmul"
+ and expr.op.name == op_name
):
- matmul_call = expr
+ if result is not None:
+ raise ValueError(f"Found multiple matched call node for {op_name}")
+ result = expr
+
+ return result
+
+
+def _check_conv2d(
+ match_result: Mapping[DFPattern, Expr],
+ _: Expr,
+):
+ """Check if the given conv2d workload can be offloaded to CUTLASS."""
+
+ conv2d_call = _find_call("relax.nn.conv2d", match_result)
+ if conv2d_call is None:
+ return False
+
+ data_layout = conv2d_call.attrs.data_layout
+ kernel_layout = conv2d_call.attrs.kernel_layout
+ data, weight, *_ = conv2d_call.args
+ if (
+ data_layout != "NHWC"
+ or kernel_layout != "OHWI"
+ or not _is_supported_dtype(data.struct_info.dtype, weight.struct_info.dtype)
+ ):
+ return False
+
+ # pylint: disable=invalid-name
+ IC = data.struct_info.shape.values[3]
+ OC = weight.struct_info.shape.values[0]
+ # not depthwise conv2d
+ return not IC == OC == conv2d_call.attrs.groups
+
+
+def _check_matmul(
+ match_result: Mapping[DFPattern, Expr],
+ _: Expr,
+) -> bool:
+ """Check if the given matmul workload can be offloaded to CUTLASS."""
+
+ matmul_call: Call = _find_call("relax.matmul", match_result)
if matmul_call is None:
- raise ValueError("Cannot find call to matmul from match_result.")
+ return False
lhs, rhs, *_ = matmul_call.args
@@ -79,88 +118,103 @@ def _check_matmul(
return is_shape_valid_for_cutlass_matmul(lhs_shape, rhs_shape)
-register_patterns(
- [
- (
- "cutlass.conv2d",
- *make_fused_bias_activation_pattern(
- "relax.nn.conv2d",
- with_bias=False,
- activation=None,
- ),
- ),
- (
- "cutlass.conv2d_bias_relu",
- *make_fused_bias_activation_pattern(
- "relax.nn.conv2d",
- with_bias=True,
- activation="relax.nn.relu",
- ),
- ),
- (
- "cutlass.matmul",
- *make_matmul_pattern(
- with_bias=False,
- ),
- _check_matmul,
- ),
- (
- "cutlass.matmul_bias",
- *make_matmul_pattern(
- with_bias=True,
- ),
- _check_matmul,
- ),
- (
- "cutlass.matmul_bias_relu",
- *make_matmul_pattern(
- with_bias=True,
- activation="relax.nn.relu",
- ),
- _check_matmul,
- ),
- (
- "cutlass.matmul_bias_gelu",
- *make_matmul_pattern(
- with_bias=True,
- activation="relax.nn.gelu",
- ),
- _check_matmul,
- ),
- (
- "cutlass.matmul_transposed",
- *make_matmul_pattern(
- with_bias=False,
- transposed_rhs=True,
- ),
- _check_matmul,
- ),
- (
- "cutlass.matmul_transposed_bias",
- *make_matmul_pattern(
- with_bias=True,
- transposed_rhs=True,
- ),
- _check_matmul,
- ),
- (
- "cutlass.matmul_transposed_bias_relu",
+def _get_activation_from_name(pattern_name):
+ if "_relu" in pattern_name:
+ return "relax.nn.relu"
+ elif "_gelu" in pattern_name:
+ return "relax.nn.gelu"
+ elif "_silu" in pattern_name:
+ return "relax.nn.silu"
+ else:
+ return None
+
+
+def matmul_patterns():
+ """
+ Returns a list of all matmul patterns in cutlass BYOC backend.
+ """
+
+ def _matmul_pattern(pattern_name):
+ transposed_rhs = "_transposed" in pattern_name
+ with_bias = "_bias" in pattern_name
+ activation = _get_activation_from_name(pattern_name)
+
+ return (
+ pattern_name,
*make_matmul_pattern(
- with_bias=True,
- activation="relax.nn.relu",
- transposed_rhs=True,
+ transposed_rhs=transposed_rhs,
+ with_bias=with_bias,
+ activation=activation,
),
_check_matmul,
- ),
- (
- "cutlass.matmul_transposed_bias_gelu",
- *make_matmul_pattern(
- with_bias=True,
- activation="relax.nn.gelu",
- transposed_rhs=True,
+ )
+
+ return [
+ _matmul_pattern("cutlass.matmul"),
+ _matmul_pattern("cutlass.matmul_bias"),
+ _matmul_pattern("cutlass.matmul_bias_relu"),
+ _matmul_pattern("cutlass.matmul_bias_gelu"),
+ _matmul_pattern("cutlass.matmul_transposed"),
+ _matmul_pattern("cutlass.matmul_transposed_bias"),
+ _matmul_pattern("cutlass.matmul_transposed_bias_relu"),
+ _matmul_pattern("cutlass.matmul_transposed_bias_gelu"),
+ ]
+
+
+def conv2d_patterns():
+ """
+ Returns a list of all conv2d patterns in cutlass BYOC backend.
+ """
+
+ def _conv2d_pattern(pattern_name):
+ with_bias = "_bias" in pattern_name
+ activation = _get_activation_from_name(pattern_name)
+
+ return (
+ pattern_name,
+ *make_fused_bias_activation_pattern(
+ "relax.nn.conv2d",
+ with_bias=with_bias,
+ activation=activation,
),
- _check_matmul,
- ),
+ _check_conv2d,
+ )
+
+ return [
+ _conv2d_pattern("cutlass.conv2d"),
+ _conv2d_pattern("cutlass.conv2d_bias"),
+ _conv2d_pattern("cutlass.conv2d_bias_relu"),
+ _conv2d_pattern("cutlass.conv2d_bias_silu"),
+ ]
+
+
+def residual_block_patterns():
+ """
+ Returns a list of all residual block patterns in cutlass BYOC backend.
+ """
+ patterns = []
+
+ for activation, name_postfix in [(None, ""), ("relax.nn.relu", "_relu")]:
+ for name, pat, arg_pat, _ in conv2d_patterns()[1:]:
+ for bin_op in ["relax.add", "relax.multiply"]:
+ patterns.append(
+ (
+ name + "_residual_" + bin_op.split(".")[-1] + name_postfix,
+ *make_residual_block_pattern(
+ (pat, arg_pat), binary_op=bin_op, activation=activation
+ ),
+ _check_conv2d,
+ )
+ )
+
+ return patterns
+
+
+def attention_patterns():
+ """
+ Returns a list of all attention patterns in cutlass BYOC backend.
+ """
+ return [
(
"cutlass.attention",
*make_attention_pattern(),
@@ -170,6 +224,15 @@ register_patterns(
*make_attention_pattern(with_bias=True),
),
]
+
+
+register_patterns(
+ [
+ *conv2d_patterns(),
+ *matmul_patterns(),
+ *residual_block_patterns(),
+ *attention_patterns(),
+ ]
)
diff --git a/python/tvm/relax/backend/patterns.py b/python/tvm/relax/backend/patterns.py
index a2ea803d9d..d770cc6faf 100644
--- a/python/tvm/relax/backend/patterns.py
+++ b/python/tvm/relax/backend/patterns.py
@@ -17,7 +17,7 @@
"""Common patterns used in BYOC"""
-from typing import Dict, Mapping, Tuple
+from typing import Dict, Mapping, Tuple, Union
from tvm.relax.dpl.pattern import DFPattern, is_op, wildcard
@@ -74,6 +74,51 @@ def make_fused_bias_activation_pattern(
return _with_bias_activation_pattern(out, args, with_bias, activation)
+def make_residual_block_pattern(
+ node_output: Union[DFPattern, Tuple[DFPattern, Mapping[str, DFPattern]]],
+ binary_op="relax.add",
+ activation=None,
+) -> Tuple[DFPattern, Mapping[str, DFPattern]]:
+ """
+ Create pattern for residual block.
+
+ Parameters
+ ----------
+ node_output: Union[DFPattern, Tuple[DFPattern, Mapping[str, DFPattern]]]
+ The output of previous node.
+
+ binary_op: str
+ The op used to combine previous node output and residual input.
+
+ activation: str
+ The activation function of this residual block. It should be a name of
+ activation Relax op, such as "relax.nn.relu".
+
+ Returns
+ -------
+ pattern: DFPattern
+ The resulting pattern describing a matrix multiplication.
+
+ args: Mapping[str, DFPattern]
+ The mapping from arg name to its pattern. It can be used to extract
+ arg expression from match result.
+ """
+
+ if isinstance(node_output, tuple):
+ node_output, arg_patterns = node_output
+ else:
+ arg_patterns = {}
+
+ residual_input = wildcard()
+ op = is_op(binary_op)
+ output = op(node_output, residual_input) | op(residual_input, node_output)
+
+ if activation is not None:
+ output = is_op(activation)(output)
+
+ return output, {**arg_patterns, "residual": residual_input}
+
+
def make_matmul_pattern(
with_bias: bool = False,
activation: str = None,
diff --git a/tests/python/relax/test_codegen_cutlass.py b/tests/python/relax/test_codegen_cutlass.py
index f2d2da15b5..02802211a9 100644
--- a/tests/python/relax/test_codegen_cutlass.py
+++ b/tests/python/relax/test_codegen_cutlass.py
@@ -27,6 +27,8 @@ from tvm.relax.backend import get_patterns_with_prefix
from tvm.relax.backend.contrib.cutlass import partition_for_cutlass
from tvm.script import relax as R
from tvm.script import tir as T
+from tvm.script.ir_builder import IRBuilder
+from tvm.script.ir_builder import relax as relax_builder
@pytest.fixture(autouse=True)
@@ -43,13 +45,9 @@ class Conv2dBiasReLU:
bias: R.Tensor((1, 1, 1, 32), "float16"),
):
with R.dataflow():
- conv1 = relax.op.nn.relu(
- relax.op.add(
- relax.op.nn.conv2d(
- data, weight, padding=(1, 1), data_layout="NHWC", kernel_layout="OHWI"
- ),
- bias,
- )
+ conv1 = R.nn.relu(
+ R.nn.conv2d(data, weight, padding=(1, 1), data_layout="NHWC", kernel_layout="OHWI")
+ + bias,
)
R.output(conv1)
@@ -98,42 +96,78 @@ def build_and_run(mod, inputs_np, target, legalize=False):
return f(*inputs).numpy()
-def get_result_with_relax_cutlass_offload(mod, *args):
+def get_result_with_relax_cutlass_offload(mod, *args, assert_all_bindings_fused=True):
patterns = [(entry.name, entry.pattern) for entry in get_patterns_with_prefix("cutlass")]
assert len(patterns) != 0, "Cannot find cutlass patterns"
mod = partition_for_cutlass(mod)
+ if assert_all_bindings_fused:
+ assert len(mod["main"].body.blocks[0].bindings) == 1
+
codegen_pass = relax.transform.RunCodegen({"cutlass": {"sm": 80, "find_first_valid": True}})
mod = codegen_pass(mod)
return build_and_run(mod, args, "cuda")
-def test_conv2d_offload():
- low, high = -1, 1
- data = np.random.randint(low, high, size=(16, 32, 32, 16)).astype("float16")
- weight = np.random.randint(low, high, size=(32, 3, 3, 16)).astype("float16")
- bias = np.random.randint(low, high, size=(1, 1, 1, 32)).astype("float16")
-
- out = get_result_with_relax_cutlass_offload(Conv2dBiasReLU, data, weight, bias)
-
- ref = build_and_run(Conv2dBiasReLU, [data, weight, bias], "llvm", legalize=True)
-
- np.testing.assert_equal(out, ref)
-
-
def test_kernel_sharing():
low, high = -1, 1
data_np = np.random.randint(low, high, size=(16, 32, 32, 8)).astype("float16")
weight1_np = np.random.randint(low, high, size=(8, 3, 3, 8)).astype("float16")
weight2_np = np.random.randint(low, high, size=(8, 3, 3, 8)).astype("float16")
- out = get_result_with_relax_cutlass_offload(Conv2dx2, data_np, weight1_np, weight2_np)
+ out = get_result_with_relax_cutlass_offload(
+ Conv2dx2, data_np, weight1_np, weight2_np, assert_all_bindings_fused=False
+ )
ref = build_and_run(Conv2dx2, [data_np, weight1_np, weight2_np], "llvm", legalize=True)
np.testing.assert_equal(out, ref)
+def get_relax_conv2d_module(
+ data_shape,
+ weight_shape,
+ dtype,
+ with_bias=False,
+ activation=None,
+ residual_bin_op=None,
+ residual_activation=None,
+):
+ with IRBuilder() as builder:
+ with relax_builder.function():
+ R.func_name("main")
+ data = R.arg("data", R.Tensor(data_shape, dtype))
+ weight = R.arg("weight", R.Tensor(weight_shape, dtype))
+ if with_bias:
+ bias = R.arg("bias", R.Tensor((1, 1, 1, weight_shape[0]), dtype))
+
+ with R.dataflow() as frame:
+ output = R.emit(
+ R.nn.conv2d(
+ data,
+ weight,
+ out_dtype=dtype,
+ padding=(1, 1),
+ data_layout="NHWC",
+ kernel_layout="OHWI",
+ )
+ )
+ if with_bias:
+ output = R.emit(output + bias)
+ if activation is not None:
+ output = R.emit(activation(output))
+ if residual_bin_op is not None:
+ output = R.emit(residual_bin_op(output, data))
+ if residual_activation is not None:
+ output = R.emit(residual_activation(output))
+ R.output(output)
+
+ R.func_ret_value(frame.output_vars[0])
+
+ func = builder.get()
+ return tvm.IRModule({"main": func})
+
+
def get_relax_matmul_module(
x_shape, y_shape, dtype, transposed_y=False, with_bias=False, activation=None
):
@@ -142,9 +176,6 @@ def get_relax_matmul_module(
else:
n = y_shape[-1]
- from tvm.script.ir_builder import IRBuilder
- from tvm.script.ir_builder import relax as relax_builder
-
with IRBuilder() as builder:
with relax_builder.function():
R.func_name("main")
@@ -195,9 +226,64 @@ _epilogue_table = {
"bias": (True, None),
"relu": (True, R.nn.relu),
"gelu": (True, R.nn.gelu),
+ "silu": (True, R.nn.silu),
}
+_residual_block_table = {
+ "none": (None, None),
+ "add_relu": (R.add, R.nn.relu),
+ "mul_relu": (R.multiply, R.nn.relu),
+ "add": (R.add, None),
+ "mul": (R.multiply, None),
+}
+
+
+@pytest.mark.parametrize(
+ "data_shape, weight_shape, dtype, epilogue, residual_block",
+ [
+ # Regular
+ ((16, 32, 32, 16), (32, 3, 3, 16), "float16", "none", "none"),
+ ((40, 128, 50, 16), (16, 2, 2, 16), "float16", "bias", "none"),
+ ((3, 64, 64, 128), (32, 1, 1, 128), "float16", "relu", "none"),
+ ((12, 32, 32, 16), (45, 5, 5, 16), "float16", "silu", "none"),
+ # residual block
+ ((3, 64, 64, 16), (16, 3, 3, 16), "float16", "relu", "add"),
+ ((16, 32, 32, 16), (16, 3, 3, 16), "float16", "relu", "mul_relu"),
+ ((40, 128, 50, 16), (16, 3, 3, 16), "float16", "bias", "add_relu"),
+ ((128, 32, 32, 16), (16, 3, 3, 16), "float16", "silu", "mul"),
+ ],
+)
+def test_conv2d_offload(data_shape, weight_shape, dtype, epilogue, residual_block):
+ low, high = -1, 1
+ data = np.random.randint(low, high, size=data_shape).astype(dtype)
+ weight = np.random.randint(low, high, size=weight_shape).astype(dtype)
+ bias = np.random.randint(low, high, size=(1, 1, 1, weight_shape[0])).astype(dtype)
+
+ with_bias, activation = _epilogue_table[epilogue]
+ residual_bin_op, residual_activation = _residual_block_table[residual_block]
+
+ if with_bias:
+ args = (data, weight, bias)
+ else:
+ args = (data, weight)
+
+ mod = get_relax_conv2d_module(
+ data_shape,
+ weight_shape,
+ dtype,
+ with_bias=with_bias,
+ activation=activation,
+ residual_bin_op=residual_bin_op,
+ residual_activation=residual_activation,
+ )
+ out = get_result_with_relax_cutlass_offload(mod, *args)
+
+ ref = build_and_run(mod, args, "llvm", legalize=True)
+
+ tvm.testing.assert_allclose(out, ref, rtol=1e-5, atol=1e-5)
+
+
@pytest.mark.parametrize(
"x_shape, y_shape, transpose_y, epilogue",
[