file_path
stringlengths
7
180
content
stringlengths
0
811k
repo
stringclasses
11 values
tests/python/unittest/test_autotvm_ga_tuner.py
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. """Test genetic algorithm tuner""" from tvm.testing.autotvm import DummyRunner, get_sample_task from tvm import autotvm def test_ga_tuner(): """Test GATuner""" # Test population size smaller than space size tuning configuration task, _ = get_sample_task() tuner = autotvm.tuner.GATuner(task, pop_size=32) valid_indexes = list( filter(lambda idx: tuner.space.is_index_valid(idx), range(tuner.space.range_length)) ) assert tuner.visited.issubset(valid_indexes) assert tuner.pop_size == len(tuner.visited) == len(tuner.genes) assert len(tuner.space) == 64 measure_option = autotvm.measure_option(builder=autotvm.LocalBuilder(), runner=DummyRunner()) tuner.tune(n_trial=len(tuner.space), measure_option=measure_option) assert tuner.visited.issubset(valid_indexes) # Test population size bigger than space size tuning configuration task, _ = get_sample_task() tuner = autotvm.tuner.GATuner(task, pop_size=100) valid_indexes = list( filter(lambda idx: tuner.space.is_index_valid(idx), range(tuner.space.range_length)) ) assert tuner.visited.issubset(valid_indexes) assert tuner.pop_size == len(tuner.visited) == len(tuner.genes) assert len(tuner.space) == 64 measure_option = autotvm.measure_option(builder=autotvm.LocalBuilder(), runner=DummyRunner()) tuner.tune(n_trial=len(tuner.space), measure_option=measure_option) assert tuner.visited.issubset(valid_indexes) # Test population size smaller than multi-filtered space size tuning configuration task, _ = get_sample_task() task.config_space.multi_filter( filter=lambda entity: 8 <= (entity["tile_x"].size[1] * entity["tile_y"].size[1]) < 1024 ) tuner = autotvm.tuner.GATuner(task, pop_size=32) valid_indexes = list( filter(lambda idx: tuner.space.is_index_valid(idx), range(tuner.space.range_length)) ) assert tuner.visited.issubset(valid_indexes) assert tuner.pop_size == len(tuner.visited) == len(tuner.genes) assert len(tuner.space) == 43 measure_option = autotvm.measure_option(builder=autotvm.LocalBuilder(), runner=DummyRunner()) tuner.tune(n_trial=len(tuner.space), measure_option=measure_option) assert tuner.visited.issubset(valid_indexes) # Test population size bigger than multi-filtered space size tuning configuration task, _ = get_sample_task() task.config_space.multi_filter( filter=lambda entity: 8 <= (entity["tile_x"].size[1] * entity["tile_y"].size[1]) < 1024 ) tuner = autotvm.tuner.GATuner(task, pop_size=100) valid_indexes = list( filter(lambda idx: tuner.space.is_index_valid(idx), range(tuner.space.range_length)) ) assert tuner.visited.issubset(valid_indexes) assert tuner.pop_size == len(tuner.visited) == len(tuner.genes) assert len(tuner.space) == 43 measure_option = autotvm.measure_option(builder=autotvm.LocalBuilder(), runner=DummyRunner()) tuner.tune(n_trial=len(tuner.space), measure_option=measure_option) assert tuner.visited.issubset(valid_indexes) if __name__ == "__main__": test_ga_tuner()
https://github.com/zk-ml/tachikoma
tests/python/unittest/test_autotvm_graph_tuner_core.py
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. # NOTE: We name this test file to start with test_graph_tuner # to make it execute after zero_rank tensor test cases. This # helps avoid topi arithmetic operator overloading issue: # https://github.com/apache/tvm/issues/3240. # TODO: restore the file name after this issue is resolved. import os import copy import numpy as np import tvm from tvm import te import tvm.relay.testing from tvm import autotvm from tvm import relay from tvm.autotvm.task import ConfigEntity from tvm.autotvm.measure import MeasureResult, MeasureInput from tvm.autotvm.graph_tuner import DPTuner, PBQPTuner def _create_args(dshape, kshape, strides, padding, dilation, layout, out_layout, dtype, out_dtype): data = tvm.te.placeholder(dshape, dtype=dtype) kernel = tvm.te.placeholder(kshape, dtype=dtype) return autotvm.task.serialize_args( [data, kernel, strides, padding, dilation, layout, layout, out_dtype] ) def _create_data(target, dshape, dtype, layout): data = relay.var("data", shape=dshape, dtype=dtype) w0 = relay.var("w0_weight") conv0 = relay.nn.conv2d(data, w0, channels=16, kernel_size=(3, 3), padding=(1, 1)) w1 = relay.var("w1_weight") conv1 = relay.nn.conv2d(conv0, w1, channels=32, kernel_size=(1, 1)) w2 = relay.var("w2_weight") conv2 = relay.nn.conv2d(conv1, w2, channels=32, kernel_size=(3, 3), padding=(1, 1)) out = relay.add(conv1, conv2) net = relay.Function(relay.analysis.free_vars(out), out) mod, params = relay.testing.create_workload(net) tasks = autotvm.task.extract_from_program( mod["main"], target=target, params=params, ops=(relay.op.get("nn.conv2d"),) ) new_args = [ _create_args( (1, 3, 8, 8), (16, 3, 3, 3), (1, 1), (1, 1, 1, 1), (1, 1), layout, layout, dtype, dtype ), _create_args( (1, 16, 8, 8), (32, 16, 1, 1), (1, 1), (0, 0, 0, 0), (1, 1), layout, layout, dtype, dtype, ), _create_args( (1, 32, 8, 8), (32, 32, 3, 3), (1, 1), (1, 1, 1, 1), (1, 1), layout, layout, dtype, dtype, ), ] costs = [0.04, 0.012, 0.03] config_list = [] cfg_dict = { "index": -1, "code_hash": None, "entity": [ ["tile_ic", "sp", [3, 1]], ["tile_oc", "sp", [4, 4]], ["tile_ow", "sp", [4, 2]], ["unroll_kw", "ot", True], ], } config_list.append(ConfigEntity.from_json_dict(cfg_dict)) cfg_dict = { "index": -1, "code_hash": None, "entity": [ ["tile_ic", "sp", [2, 8]], ["tile_oc", "sp", [1, 32]], ["tile_oh", "ot", 1], ["tile_ow", "sp", [4, 2]], ], } config_list.append(ConfigEntity.from_json_dict(cfg_dict)) cfg_dict = { "index": -1, "code_hash": None, "entity": [ ["tile_ic", "sp", [8, 4]], ["tile_oc", "sp", [4, 8]], ["tile_ow", "sp", [2, 4]], ["unroll_kw", "ot", False], ], } config_list.append(ConfigEntity.from_json_dict(cfg_dict)) records = [] for args, cost, config, task in zip(new_args, costs, config_list, tasks): task.args = args ms_input = MeasureInput(target=target, task=task, config=config) ms_output = MeasureResult(costs=(cost,), error_no=0, all_cost=-1, timestamp=-1) records.append((ms_input, ms_output)) ltf_records = [] ltf_arg = [te.placeholder((1, 64, 16, 16, 8), dtype=dtype), "NCHW8c", "NCHW512c"] ltf_task = autotvm.task.create("layout_transform", ltf_arg, target) ms_input = MeasureInput(target=target, task=ltf_task, config=None) ms_output = MeasureResult(costs=(1.91224744e-05,), error_no=0, all_cost=-1, timestamp=-1) ltf_records.append((ms_input, ms_output)) ltf_keys = [] ltf_arg = [te.placeholder((1, 4, 8, 8, 4), dtype=dtype), "NCHW4c", "NCHW8c"] ltf_wkl = autotvm.task.args_to_workload(ltf_arg, "layout_transform") ltf_keys.append(ltf_wkl) ltf_arg = [te.placeholder((1, 1, 8, 8, 32), dtype=dtype), "NCHW32c", "NCHW4c"] ltf_wkl = autotvm.task.args_to_workload(ltf_arg, "layout_transform") ltf_keys.append(ltf_wkl) ltf_arg = [te.placeholder((1, 4, 8, 8, 8), dtype=dtype), "NCHW8c", "NCHW32c"] ltf_wkl = autotvm.task.args_to_workload(ltf_arg, "layout_transform") ltf_keys.append(ltf_wkl) return net, records, ltf_records, ltf_keys, tasks def test_graph_tuner_layout_transform(): log_file = "%s/test_tuner.log" % (os.getcwd()) target = "llvm" dshape = (1, 3, 8, 8) dtype = "float32" layout = "NCHW" conv2d = relay.op.get("nn.conv2d") target_ops = [conv2d] g, records, ltf_records, ltf_keys, _ = _create_data(target, dshape, dtype, layout) executor = DPTuner(g, {"data": dshape}, records, target_ops, target=target, log_file=log_file) executor.benchmark_layout_transform(layout_records=ltf_records, infer_layout=True) out = executor._layout_transform_perf_records num_flops = 0 total_time = 0 for record in ltf_records: ltf_wkl = record[0].task.workload input_shape = ltf_wkl[1][1] flops = np.prod(input_shape) num_flops += flops total_time += record[1].costs[0] avg_time = total_time / num_flops for ltf_workload in out: input_shape = ltf_workload[1][1] flops = 1 for i in input_shape: flops *= i expected_time = flops * avg_time out_time = out[ltf_workload][1].costs[0] assert ( expected_time == out_time ), "Inferred layout transformation time mismatch for %s: " "expecting %f but got %f" % ( str(ltf_workload), expected_time, out_time, ) def test_graph_tuner_layout_transform_runner(): log_file = "%s/test_tuner.log" % (os.getcwd()) target = "llvm" dshape = (1, 3, 8, 8) dtype = "float32" layout = "NCHW" conv2d = relay.op.get("nn.conv2d") target_ops = [conv2d] g, records, ltf_records, ltf_keys, _ = _create_data(target, dshape, dtype, layout) executor = DPTuner(g, {"data": dshape}, records, target_ops, target=target, log_file=log_file) runner = autotvm.LocalRunner(number=100, repeat=1, timeout=10) executor.benchmark_layout_transform( layout_records=ltf_records, infer_layout=True, runner=runner ) out = executor._layout_transform_perf_records num_flops = 0 total_time = 0 for record in ltf_records: ltf_wkl = record[0].task.workload input_shape = ltf_wkl[1][1] flops = np.prod(input_shape) num_flops += flops total_time += record[1].costs[0] avg_time = total_time / num_flops for ltf_workload in out: input_shape = ltf_workload[1][1] flops = 1 for i in input_shape: flops *= i expected_time = flops * avg_time out_time = out[ltf_workload][1].costs[0] assert ( expected_time == out_time ), "Inferred layout transformation time mismatch for %s: " "expecting %f but got %f" % ( str(ltf_workload), expected_time, out_time, ) def test_DPTuner_run(): log_file = "%s/test_tuner.log" % (os.getcwd()) target = "llvm" dtype = "float32" layout = "NCHW" dshape = (1, 3, 8, 8) conv2d = relay.op.get("nn.conv2d") target_ops = [conv2d] g, records, ltf_records, ltf_keys, tasks = _create_data(target, dshape, dtype, layout) mod = tvm.IRModule() mod["main"] = g costs = [0.02, 0.02, 0.045] config_list = [] cfg_dict = { "index": -1, "code_hash": None, "entity": [ ["tile_ic", "sp", [1, 3]], ["tile_oc", "sp", [2, 8]], ["tile_ow", "sp", [4, 2]], ["unroll_kw", "ot", True], ], } config_list.append(ConfigEntity.from_json_dict(cfg_dict)) cfg_dict = { "index": -1, "code_hash": None, "entity": [ ["tile_ic", "sp", [4, 4]], ["tile_oc", "sp", [2, 16]], ["tile_oh", "ot", 1], ["tile_ow", "sp", [4, 2]], ], } config_list.append(ConfigEntity.from_json_dict(cfg_dict)) cfg_dict = { "index": -1, "code_hash": None, "entity": [ ["tile_ic", "sp", [16, 2]], ["tile_oc", "sp", [8, 4]], ["tile_ow", "sp", [2, 4]], ["unroll_kw", "ot", False], ], } config_list.append(ConfigEntity.from_json_dict(cfg_dict)) for cost, config, task in zip(costs, config_list, tasks): ms_input = MeasureInput(target=target, task=task, config=config) ms_output = MeasureResult(costs=(cost,), error_no=0, all_cost=-1, timestamp=-1) records.append((ms_input, ms_output)) executor = DPTuner(mod, {"data": dshape}, records, target_ops, target, log_file=log_file) executor.benchmark_layout_transform(layout_records=ltf_records, infer_layout=True) executor.run() out = [record[0].config for record in executor.get_optimal_records()] expected_out = [records[3][0].config, records[1][0].config, records[2][0].config] assert expected_out == out, "Output mismatch: expecting %s but got %s" % ( str(expected_out), str(out), ) assert os.path.isfile(log_file), "No log file with name %s exists." % log_file def test_PBQPTuner_run(): target = "llvm" dtype = "float32" layout = "NCHW" dshape = (1, 3, 8, 8) conv2d = relay.op.get("nn.conv2d") target_ops = [conv2d] g, records, ltf_records, ltf_keys, tasks = _create_data(target, dshape, dtype, layout) costs = [0.02, 0.02, 0.045] config_list = [] cfg_dict = { "index": -1, "code_hash": None, "entity": [ ["tile_ic", "sp", [1, 3]], ["tile_oc", "sp", [2, 8]], ["tile_ow", "sp", [4, 2]], ["unroll_kw", "ot", True], ], } config_list.append(ConfigEntity.from_json_dict(cfg_dict)) cfg_dict = { "index": -1, "code_hash": None, "entity": [ ["tile_ic", "sp", [4, 4]], ["tile_oc", "sp", [2, 16]], ["tile_oh", "ot", 1], ["tile_ow", "sp", [4, 2]], ], } config_list.append(ConfigEntity.from_json_dict(cfg_dict)) cfg_dict = { "index": -1, "code_hash": None, "entity": [ ["tile_ic", "sp", [16, 2]], ["tile_oc", "sp", [8, 4]], ["tile_ow", "sp", [2, 4]], ["unroll_kw", "ot", False], ], } config_list.append(ConfigEntity.from_json_dict(cfg_dict)) for cost, config, task in zip(costs, config_list, tasks): ms_input = MeasureInput(target=target, task=task, config=config) ms_output = MeasureResult(costs=(cost,), error_no=0, all_cost=-1, timestamp=-1) records.append((ms_input, ms_output)) executor = PBQPTuner(g, {"data": dshape}, records, target_ops, target) executor.benchmark_layout_transform(layout_records=ltf_records, infer_layout=True) executor.run() out = [record[0].config for record in executor.get_optimal_records()] expected_out = [records[3][0].config, records[1][0].config, records[2][0].config] assert expected_out == out, "Output mismatch: expecting %s but got %s" % ( str(expected_out), str(out), ) def test_many_sub_graphs(): target = "llvm" dtype = "float32" dshape = (1, 8, 8, 3) layout = "NCHW" conv2d = relay.op.get("nn.conv2d") target_ops = [conv2d] data = relay.var("data", shape=dshape, dtype=dtype) t0 = relay.transpose(data, (0, 3, 1, 2)) w0 = relay.var("w0_weight") conv0 = relay.nn.conv2d(t0, w0, channels=16, kernel_size=(3, 3), padding=(1, 1)) t1 = relay.transpose(conv0, (0, 2, 3, 1)) w1 = relay.var("w1_weight") t2 = relay.transpose(t1, (0, 3, 1, 2)) conv1 = relay.nn.conv2d(t2, w1, channels=32, kernel_size=(1, 1)) t3 = relay.transpose(conv1, (0, 2, 3, 1)) w2 = relay.var("w2_weight") t4 = relay.transpose(t3, (0, 3, 1, 2)) conv2 = relay.nn.conv2d(t4, w2, channels=32, kernel_size=(3, 3), padding=(1, 1)) t5 = relay.transpose(conv2, (0, 2, 3, 1)) out = relay.add(t3, t5) net = relay.Function(relay.analysis.free_vars(out), out) net, params = relay.testing.create_workload(net) tasks = autotvm.task.extract_from_program( net["main"], target=target, params=params, ops=(conv2d,) ) new_args = [ _create_args( (1, 3, 8, 8), (16, 3, 3, 3), (1, 1), (1, 1, 1, 1), (1, 1), layout, layout, dtype, dtype ), _create_args( (1, 16, 8, 8), (32, 16, 1, 1), (1, 1), (0, 0, 0, 0), (1, 1), layout, layout, dtype, dtype, ), _create_args( (1, 32, 8, 8), (32, 32, 3, 3), (1, 1), (1, 1, 1, 1), (1, 1), layout, layout, dtype, dtype, ), ] costs = [0.04, 0.012, 0.03, 0.02, 0.02, 0.045] config_list = [] cfg_dict = { "index": -1, "code_hash": None, "entity": [ ["tile_ic", "sp", [3, 1]], ["tile_oc", "sp", [4, 4]], ["tile_ow", "sp", [4, 2]], ["unroll_kw", "ot", True], ], } config_list.append(ConfigEntity.from_json_dict(cfg_dict)) cfg_dict = { "index": -1, "code_hash": None, "entity": [ ["tile_ic", "sp", [2, 8]], ["tile_oc", "sp", [1, 32]], ["tile_oh", "ot", 1], ["tile_ow", "sp", [4, 2]], ], } config_list.append(ConfigEntity.from_json_dict(cfg_dict)) cfg_dict = { "index": -1, "code_hash": None, "entity": [ ["tile_ic", "sp", [8, 4]], ["tile_oc", "sp", [4, 8]], ["tile_ow", "sp", [2, 4]], ["unroll_kw", "ot", False], ], } config_list.append(ConfigEntity.from_json_dict(cfg_dict)) cfg_dict = { "index": -1, "code_hash": None, "entity": [ ["tile_ic", "sp", [1, 3]], ["tile_oc", "sp", [2, 8]], ["tile_ow", "sp", [4, 2]], ["unroll_kw", "ot", True], ], } config_list.append(ConfigEntity.from_json_dict(cfg_dict)) cfg_dict = { "index": -1, "code_hash": None, "entity": [ ["tile_ic", "sp", [4, 4]], ["tile_oc", "sp", [2, 16]], ["tile_oh", "ot", 1], ["tile_ow", "sp", [4, 2]], ], } config_list.append(ConfigEntity.from_json_dict(cfg_dict)) cfg_dict = { "index": -1, "code_hash": None, "entity": [ ["tile_ic", "sp", [16, 2]], ["tile_oc", "sp", [8, 4]], ["tile_ow", "sp", [2, 4]], ["unroll_kw", "ot", False], ], } config_list.append(ConfigEntity.from_json_dict(cfg_dict)) records = [] new_args = new_args + new_args tasks = tasks + tasks for args, cost, config, task in zip(new_args, costs, config_list, tasks): task.args = args ms_input = MeasureInput(target=target, task=task, config=config) ms_output = MeasureResult(costs=(cost,), error_no=0, all_cost=-1, timestamp=-1) records.append((ms_input, ms_output)) ltf_records = [] ltf_arg = [te.placeholder((1, 64, 16, 16, 8), dtype=dtype), "NCHW8c", "NCHW512c"] ltf_task = autotvm.task.create("layout_transform", ltf_arg, target) ms_input = MeasureInput(target=target, task=ltf_task, config=None) ms_output = MeasureResult(costs=(1.91224744e-05,), error_no=0, all_cost=-1, timestamp=-1) ltf_records.append((ms_input, ms_output)) executor = DPTuner(net, {"data": dshape}, records, target_ops, target) executor.benchmark_layout_transform(layout_records=ltf_records, infer_layout=True) executor.run() out = [record[0].config for record in executor.get_optimal_records()] expected_out = [records[3][0].config, records[1][0].config, records[2][0].config] assert expected_out == out, "Output mismatch: expecting %s but got %s" % ( str(expected_out), str(out), ) executor = PBQPTuner(net, {"data": dshape}, records, target_ops, target) executor.benchmark_layout_transform(layout_records=ltf_records, infer_layout=True) executor.run() out = [record[0].config for record in executor.get_optimal_records()] expected_out = [records[3][0].config, records[1][0].config, records[2][0].config] assert expected_out == out, "Output mismatch: expecting %s but got %s" % ( str(expected_out), str(out), ) def test_tuple(): target = "llvm" dtype = "float32" dshape = (1, 5, 32, 32) layout = "NCHW" conv2d = relay.op.get("nn.conv2d") target_ops = [conv2d] data = relay.var("data", shape=dshape, dtype=dtype) w0 = relay.var("w0_weight") conv0 = relay.nn.conv2d(data, w0, channels=2, kernel_size=(3, 3), padding=(1, 1)) w1 = relay.var("w1_weight") conv1 = relay.nn.conv2d(data, w1, channels=3, kernel_size=(3, 3), padding=(1, 1)) out = relay.concatenate([conv0, conv1], axis=1) net = relay.Function(relay.analysis.free_vars(out), out) net, params = relay.testing.create_workload(net) tasks = autotvm.task.extract_from_program( net["main"], target=target, params=params, ops=(conv2d,) ) new_args = [ _create_args( (1, 5, 32, 32), (2, 5, 3, 3), (1, 1), (1, 1, 1, 1), (1, 1), layout, layout, dtype, dtype ), _create_args( (1, 5, 32, 32), (3, 5, 3, 3), (1, 1), (1, 1, 1, 1), (1, 1), layout, layout, dtype, dtype ), ] costs = [0.01, 0.012, 0.03, 0.04] config_list = [] cfg_dict = { "index": -1, "code_hash": None, "entity": [ ["tile_ic", "sp", [1, 5]], ["tile_oc", "sp", [1, 2]], ["tile_ow", "sp", [4, 8]], ["unroll_kw", "ot", True], ], } config_list.append(ConfigEntity.from_json_dict(cfg_dict)) cfg_dict = { "index": -1, "code_hash": None, "entity": [ ["tile_ic", "sp", [1, 5]], ["tile_oc", "sp", [1, 3]], ["tile_ow", "sp", [2, 16]], ["unroll_kw", "ot", False], ], } config_list.append(ConfigEntity.from_json_dict(cfg_dict)) cfg_dict = { "index": -1, "code_hash": None, "entity": [ ["tile_ic", "sp", [1, 5]], ["tile_oc", "sp", [2, 1]], ["tile_ow", "sp", [4, 8]], ["unroll_kw", "ot", True], ], } config_list.append(ConfigEntity.from_json_dict(cfg_dict)) cfg_dict = { "index": -1, "code_hash": None, "entity": [ ["tile_ic", "sp", [1, 5]], ["tile_oc", "sp", [3, 1]], ["tile_ow", "sp", [2, 16]], ["unroll_kw", "ot", False], ], } config_list.append(ConfigEntity.from_json_dict(cfg_dict)) records = [] new_args = new_args + new_args tasks = tasks + tasks for args, cost, config, task in zip(new_args, costs, config_list, tasks): task.args = args ms_input = MeasureInput(target=target, task=task, config=config) ms_output = MeasureResult(costs=(cost,), error_no=0, all_cost=-1, timestamp=-1) records.append((ms_input, ms_output)) ltf_records = [] ltf_arg = [te.placeholder((1, 64, 16, 16, 8), dtype=dtype), "NCHW8c", "NCHW512c"] ltf_task = autotvm.task.create("layout_transform", ltf_arg, target) ms_input = MeasureInput(target=target, task=ltf_task, config=None) ms_output = MeasureResult(costs=(1.91224744e-05,), error_no=0, all_cost=-1, timestamp=-1) ltf_records.append((ms_input, ms_output)) executor = DPTuner(net, {"data": dshape}, records, target_ops, target) executor.benchmark_layout_transform(layout_records=ltf_records, infer_layout=True) executor.run() out = [record[0].config for record in executor.get_optimal_records()] expected_out = [records[2][0].config, records[1][0].config] assert expected_out == out, "Output mismatch: expecting %s but got %s" % ( str(expected_out), str(out), ) executor = PBQPTuner(net, {"data": dshape}, records, target_ops, target) executor.benchmark_layout_transform(layout_records=ltf_records, infer_layout=True) executor.run() out = [record[0].config for record in executor.get_optimal_records()] expected_out = [records[2][0].config, records[1][0].config] assert expected_out == out, "Output mismatch: expecting %s but got %s" % ( str(expected_out), str(out), ) def test_triangle_block(): target = "llvm" dtype = "float32" dshape = (1, 3, 8, 8) layout = "NCHW" conv2d = relay.op.get("nn.conv2d") target_ops = [conv2d] data = relay.var("data", shape=dshape, dtype=dtype) w0 = relay.var("w0_weight") conv0 = relay.nn.conv2d(data, w0, channels=16, kernel_size=(3, 3), padding=(1, 1)) w1 = relay.var("w1_weight") conv1 = relay.nn.conv2d(conv0, w1, channels=32, kernel_size=(1, 1)) w2 = relay.var("w2_weight") conv2 = relay.nn.conv2d(data, w2, channels=32, kernel_size=(3, 3), padding=(1, 1)) out = relay.concatenate([conv0, conv1, conv2], axis=1) net = relay.Function(relay.analysis.free_vars(out), out) net, params = relay.testing.create_workload(net) tasks = autotvm.task.extract_from_program( net["main"], target=target, params=params, ops=(conv2d,) ) new_args = [ _create_args( (1, 3, 8, 8), (16, 3, 3, 3), (1, 1), (1, 1, 1, 1), (1, 1), layout, layout, dtype, dtype ), _create_args( (1, 16, 8, 8), (32, 16, 1, 1), (1, 1), (0, 0, 0, 0), (1, 1), layout, layout, dtype, dtype, ), _create_args( (1, 3, 8, 8), (32, 3, 3, 3), (1, 1), (1, 1, 1, 1), (1, 1), layout, layout, dtype, dtype ), ] costs = [0.04, 0.012, 0.03, 0.02, 0.02, 0.045] config_list = [] cfg_dict = { "index": -1, "code_hash": None, "entity": [ ["tile_ic", "sp", [3, 1]], ["tile_oc", "sp", [4, 4]], ["tile_ow", "sp", [4, 2]], ["unroll_kw", "ot", True], ], } config_list.append(ConfigEntity.from_json_dict(cfg_dict)) cfg_dict = { "index": -1, "code_hash": None, "entity": [ ["tile_ic", "sp", [2, 8]], ["tile_oc", "sp", [1, 32]], ["tile_oh", "ot", 1], ["tile_ow", "sp", [4, 2]], ], } config_list.append(ConfigEntity.from_json_dict(cfg_dict)) cfg_dict = { "index": -1, "code_hash": None, "entity": [ ["tile_ic", "sp", [8, 4]], ["tile_oc", "sp", [4, 8]], ["tile_ow", "sp", [2, 4]], ["unroll_kw", "ot", False], ], } config_list.append(ConfigEntity.from_json_dict(cfg_dict)) cfg_dict = { "index": -1, "code_hash": None, "entity": [ ["tile_ic", "sp", [1, 3]], ["tile_oc", "sp", [2, 8]], ["tile_ow", "sp", [4, 2]], ["unroll_kw", "ot", True], ], } config_list.append(ConfigEntity.from_json_dict(cfg_dict)) cfg_dict = { "index": -1, "code_hash": None, "entity": [ ["tile_ic", "sp", [4, 4]], ["tile_oc", "sp", [2, 16]], ["tile_oh", "ot", 1], ["tile_ow", "sp", [4, 2]], ], } config_list.append(ConfigEntity.from_json_dict(cfg_dict)) cfg_dict = { "index": -1, "code_hash": None, "entity": [ ["tile_ic", "sp", [16, 2]], ["tile_oc", "sp", [8, 4]], ["tile_ow", "sp", [2, 4]], ["unroll_kw", "ot", False], ], } config_list.append(ConfigEntity.from_json_dict(cfg_dict)) records = [] new_args = new_args + new_args tasks = tasks + tasks for args, cost, config, task in zip(new_args, costs, config_list, tasks): task.args = args ms_input = MeasureInput(target=target, task=task, config=config) ms_output = MeasureResult(costs=(cost,), error_no=0, all_cost=-1, timestamp=-1) records.append((ms_input, ms_output)) ltf_records = [] ltf_arg = [te.placeholder((1, 64, 16, 16, 8), dtype=dtype), "NCHW8c", "NCHW512c"] ltf_task = autotvm.task.create("layout_transform", ltf_arg, target) ms_input = MeasureInput(target=target, task=ltf_task, config=None) ms_output = MeasureResult(costs=(1.91224744e-05,), error_no=0, all_cost=-1, timestamp=-1) ltf_records.append((ms_input, ms_output)) executor = DPTuner(net, {"data": dshape}, records, target_ops, target) executor.benchmark_layout_transform(layout_records=ltf_records, infer_layout=True) executor.run() out = [record[0].config for record in executor.get_optimal_records()] expected_out = [records[3][0].config, records[1][0].config, records[2][0].config] assert expected_out == out, "Output mismatch: expecting %s but got %s" % ( str(expected_out), str(out), ) executor = PBQPTuner(net, {"data": dshape}, records, target_ops, target) executor.benchmark_layout_transform(layout_records=ltf_records, infer_layout=True) executor.run() out = [record[0].config for record in executor.get_optimal_records()] expected_out = [records[3][0].config, records[1][0].config, records[2][0].config] assert expected_out == out, "Output mismatch: expecting %s but got %s" % ( str(expected_out), str(out), ) if __name__ == "__main__": test_graph_tuner_layout_transform() test_DPTuner_run() test_PBQPTuner_run() test_many_sub_graphs() test_tuple() test_triangle_block()
https://github.com/zk-ml/tachikoma
tests/python/unittest/test_autotvm_graph_tuner_utils.py
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. # NOTE: We name this test file to start with test_graph_tuner # to make it execute after zero_rank tensor test cases. This # helps avoid topi arithmetic operator overloading issue: # https://github.com/apache/tvm/issues/3240 # TODO: restore the file name after this issue is resolved. import pytest import tvm from tvm import te from tvm import autotvm, relay from tvm.relay.testing import synthetic from tvm.autotvm.graph_tuner.utils import ( has_multiple_inputs, get_direct_ancestor, get_in_nodes, get_out_nodes, expr2graph, bind_inputs, ) from tvm.autotvm.graph_tuner._base import OPT_OUT_OP from tvm.autotvm.graph_tuner.utils.traverse_graph import _replace_device_with_tracing from tvm.relay.expr import Call, TupleGetItem, Tuple, Var def verify_has_multiple_inputs(node_list, node_idx, input_names, expected_result): out = has_multiple_inputs(node_list, node_idx, input_names, OPT_OUT_OP) assert out == expected_result, "Output mismatch: expecting checking %s to be %s but got %s." % ( node_list[node_idx]["op"], str(expected_result), str(out), ) def test_has_multiple_inputs(): data = relay.var("data") out1 = data * relay.expr.const(3.0) w0 = relay.var("w0") out2 = relay.nn.conv2d(data, w0) out = relay.add(out1, out2) net = relay.Function(relay.analysis.free_vars(out), out) net = bind_inputs(net, {"data": (1, 16, 224, 224), "w0": (16, 16, 1, 1)}) target_ops = [relay.op.get("nn.conv2d")] node_list = [] node_dict = {} expr2graph(net, target_ops, node_dict, node_list, tvm.target.Target("llvm")) input_names = ["data"] verify_has_multiple_inputs(node_list, 2, input_names, False) verify_has_multiple_inputs(node_list, 4, input_names, False) verify_has_multiple_inputs(node_list, 5, input_names, True) def test_expr2graph(): mod, _ = synthetic.get_workload() node_dict = {} node_list = [] target_ops = [relay.op.get("nn.conv2d")] op_name_list = [] def _count_node(node): if isinstance(node, Call): op_name_list.append(node.op) elif isinstance(node, (Var, TupleGetItem, Tuple)): op_name_list.append(None) relay.analysis.post_order_visit(mod["main"], _count_node) expr2graph(mod["main"], target_ops, node_dict, node_list, tvm.target.Target("llvm")) assert len(node_list) == len(op_name_list) for i, item in enumerate(zip(op_name_list, node_list)): op_name, node = item assert op_name == node["op"], "%dth Node operator mismatch: expecting %s but got %s" % ( i, str(op_name), str(node["op"]), ) def test_get_direct_ancestor(): data = relay.var("data") w0 = relay.var("w0") out1 = relay.nn.conv2d(data, w0) out2 = relay.add(out1, data * relay.expr.const(5.0)) out3 = out2 + relay.expr.const(2.5) w1 = relay.var("w1") out = relay.nn.conv2d(out3, w1) net = relay.Function(relay.analysis.free_vars(out), out) net = bind_inputs(net, {"data": (1, 16, 224, 224), "w0": (16, 16, 1, 1), "w1": (16, 16, 1, 1)}) target_ops = [relay.op.get("nn.conv2d")] node_list = [] node_dict = {} expr2graph(net, target_ops, node_dict, node_list, tvm.target.Target("llvm")) visited_dict = {} input_names = ["data"] out = get_direct_ancestor(node_list, visited_dict, target_ops, 5, input_names) assert out == [0], "Output mismatch: expecting [0] but got %s." % str(out) # non-regression test out = relay.add(relay.log(data), relay.sqrt(data)) net = relay.Function(relay.analysis.free_vars(out), out) net = bind_inputs(net, {"data": (1, 16, 224, 224)}) node_list = [] node_dict = {} expr2graph(net, target_ops, node_dict, node_list, tvm.target.Target("llvm")) out = get_direct_ancestor(node_list, visited_dict, target_ops, 3, input_names) assert out == [0], "Output mismatch: expecting [0] but got %s." % str(out) def test_get_in_nodes(): data = relay.var("data") w0 = relay.var("w0") out1 = relay.nn.conv2d(data, w0) out2 = relay.add(out1, data) out3 = out2 + relay.expr.const(2.5) w1 = relay.var("w1") out = relay.nn.conv2d(out3, w1) net = relay.Function(relay.analysis.free_vars(out), out) net = bind_inputs(net, {"data": (1, 16, 224, 224), "w0": (16, 16, 1, 1), "w1": (16, 16, 1, 1)}) target_ops = [relay.op.get("nn.conv2d")] input_names = ["data"] node_list = [] node_dict = {} expr2graph(net, target_ops, node_dict, node_list, tvm.target.Target("llvm")) out = get_in_nodes(node_list, target_ops, input_names) expected_out = {3: [0], 4: [3, 0], 7: [4]} diff_set = set(out) ^ set(expected_out) if len(diff_set) != 0: raise RuntimeError( "Output mismatch: expecting %s but got %s." % (str(expected_out), str(out)) ) def test_get_out_nodes(): in_nodes_dict = {8: [4], 4: [3, 0], 3: [0]} expected_out = {0: [3, 4], 3: [4], 4: [8], 8: []} out = get_out_nodes(in_nodes_dict) diff_set = set(out) ^ set(expected_out) if len(diff_set) != 0: raise RuntimeError( "Output mismatch: expecting %s but got %s." % (str(expected_out), str(out)) ) def test_target_device_replacement(): assert _replace_device_with_tracing("cuda") == "cuda -device=tracing" assert ( _replace_device_with_tracing("cuda -device=some_device -libs=cudnn") == "cuda -device=tracing -libs=cudnn" ) assert ( _replace_device_with_tracing("llvm -device=arm_cpu -arg=xxx") == "llvm -device=tracing -arg=xxx" ) assert _replace_device_with_tracing("llvm -device=arm_cpu") == "llvm -device=tracing" assert _replace_device_with_tracing("llvm -device=abc, def") == "llvm -device=tracing" if __name__ == "__main__": test_has_multiple_inputs() test_expr2graph() test_get_direct_ancestor() test_get_in_nodes() test_get_out_nodes()
https://github.com/zk-ml/tachikoma
tests/python/unittest/test_autotvm_index_tuner.py
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. """Test index based tuners""" import multiprocessing from tvm.testing.autotvm import DummyRunner, get_sample_task from tvm import autotvm def test_grid_search_tuner(): """Test GridSearchTuner""" task, _ = get_sample_task() measure_option = autotvm.measure_option(builder=autotvm.LocalBuilder(), runner=DummyRunner()) # When no range index, range_length should be the length of config space tuner = autotvm.tuner.GridSearchTuner(task) assert tuner.begin_idx == 0 assert tuner.end_idx == 64 assert tuner.index == 0 assert tuner.range_length == 64 assert tuner.visited_max == 64 # With range index, range_length should be the length of the specified range tuner = autotvm.tuner.GridSearchTuner(task, range_idx=(8, 15)) assert tuner.begin_idx == 8 assert tuner.end_idx == 16 assert tuner.index == 8 assert tuner.range_length == 8 assert tuner.visited_max == 8 # Tuner should only focus on the specified range tuner.tune(n_trial=8, measure_option=measure_option) assert len(tuner.visited) == 8 assert not tuner.has_next() # With multi-filter task, _ = get_sample_task() task.config_space.multi_filter( filter=lambda entity: 32 <= (entity["tile_x"].size[1] * entity["tile_y"].size[1]) < 1024 ) tuner = autotvm.tuner.GridSearchTuner(task) assert tuner.begin_idx == 0 assert tuner.end_idx == 64 assert tuner.index == 5 assert tuner.range_length == 64 assert tuner.visited_max == 34 # With range index, range_length should be the length of the specified range tuner = autotvm.tuner.GridSearchTuner(task, range_idx=(8, 15)) assert tuner.begin_idx == 8 assert tuner.end_idx == 16 assert tuner.index == 12 assert tuner.range_length == 8 assert tuner.visited_max == 4 # Tuner should only focus on the specified range tuner.tune(n_trial=8, measure_option=measure_option) assert len(tuner.visited) == 4 assert not tuner.has_next() def grid_search_spawn(): assert multiprocessing.get_spawn_method(False) == "spawn" test_grid_search_tuner() def test_grid_search_tuner_spawn(): ctx = multiprocessing.get_context("spawn") p = ctx.Process(target=test_grid_search_tuner) p.start() p.join() def test_random_tuner(): """Test RandomTuner""" task, _ = get_sample_task() measure_option = autotvm.measure_option(builder=autotvm.LocalBuilder(), runner=DummyRunner()) tuner = autotvm.tuner.RandomTuner(task, range_idx=(8, 15)) assert tuner.begin_idx == 8 assert tuner.end_idx == 16 assert tuner.range_length == 8 assert tuner.visited_max == 8 # Tuner should only focus on the specified range and should visit all indices tuner.tune(n_trial=8, measure_option=measure_option) assert len(tuner.visited) == 8 assert not tuner.has_next() for idx in tuner.visited: assert 8 <= idx <= 15 # With multi-filter task, _ = get_sample_task() task.config_space.multi_filter( filter=lambda entity: 32 <= (entity["tile_x"].size[1] * entity["tile_y"].size[1]) < 1024 ) tuner = autotvm.tuner.RandomTuner(task, range_idx=(8, 15)) assert tuner.begin_idx == 8 assert tuner.end_idx == 16 assert tuner.range_length == 8 assert tuner.visited_max == 4 # Tuner should only focus on the specified range and should visit all indices tuner.tune(n_trial=8, measure_option=measure_option) assert len(tuner.visited) == 4 assert not tuner.has_next() for idx in tuner.visited: assert 8 <= idx <= 15 if __name__ == "__main__": test_grid_search_tuner() test_grid_search_tuner_spawn() test_random_tuner()
https://github.com/zk-ml/tachikoma
tests/python/unittest/test_autotvm_measure.py
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. """Test builder and runner""" import logging import multiprocessing import concurrent import numpy as np import tvm from tvm import te from tvm.autotvm.measure import executor from tvm.testing.autotvm import DummyRunner, bad_matmul, get_sample_task from tvm import autotvm from tvm.autotvm.measure.measure import MeasureErrorNo, MeasureResult from tvm.autotvm import measure from inspect import Signature def test_task_tuner_without_measurement(): """test task and tuner without measurement""" task, _ = get_sample_task() measure_option = autotvm.measure_option(builder=autotvm.LocalBuilder(), runner=DummyRunner()) logging.info("%s", task.config_space) for tuner_class in [ autotvm.tuner.RandomTuner, autotvm.tuner.GridSearchTuner, autotvm.tuner.GATuner, autotvm.tuner.XGBTuner, ]: tuner = tuner_class(task) tuner.tune(n_trial=10, measure_option=measure_option) assert tuner.best_flops > 1 def task_tuner_spawn(): assert multiprocessing.get_start_method(False) == "spawn" test_task_tuner_without_measurement() def test_task_tuner_without_measurement_spawn(): # Subprocesses inherit the spawn method of their parents ctx = multiprocessing.get_context("spawn") p = ctx.Process(target=task_tuner_spawn) p.start() p.join() def test_task_runner_with_ref_input(): """test runner ref_input without measurement""" refinp = [np.random.rand(128, 128) for i in range(3)] runner = measure.LocalRunner() runner.ref_input = refinp class DummyExecutor(measure.executor.Executor): def __init__(self): self.ran_dummy_executor = False def submit(self, func, *args, **kwargs): self.ran_dummy_executor = True sig = Signature.from_callable(func) assert sig.bind(*args, **kwargs).arguments["ref_input"] == refinp dummy_future = concurrent.futures.Future() dummy_future.set_result(None) return dummy_future runner.executor = DummyExecutor() runner.run([None], [None]) assert runner.executor.ran_dummy_executor if __name__ == "__main__": logging.basicConfig(level=logging.INFO) test_task_tuner_without_measurement() test_task_tuner_without_measurement_spawn() test_task_runner_with_ref_input()
https://github.com/zk-ml/tachikoma
tests/python/unittest/test_autotvm_record.py
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. """test the correctness of dump and load of data log""" from io import StringIO from os import PathLike import time from tvm.contrib import utils from tvm import autotvm from tvm.autotvm.measure import MeasureInput, MeasureResult, MeasureErrorNo from tvm.autotvm.record import encode, decode, ApplyHistoryBest, measure_str_key from tvm.testing.autotvm import get_sample_task def test_load_dump(): task, target = get_sample_task() inp = MeasureInput(target, task, task.config_space.get(0)) result = MeasureResult( (2.0, 2.23, 0.23, 0.123, 0.234, 0.123), MeasureErrorNo.NO_ERROR, 2.3, time.time() ) for protocol in ["json", "pickle"]: row = encode(inp, result, protocol=protocol) inp_2, result_2 = decode(row, protocol=protocol) assert measure_str_key(inp) == measure_str_key(inp_2), "%s vs %s" % ( measure_str_key(inp), measure_str_key(inp_2), ) assert result.costs == result_2.costs assert result.error_no == result_2.error_no assert result.timestamp == result_2.timestamp def test_file_io(): temp = utils.tempdir() file_path = temp.relpath("temp.log") tsk, target = get_sample_task() inputs = [MeasureInput(target, tsk, tsk.config_space.get(i)) for i in range(0, 10)] results = [MeasureResult((i,), 0, 0, 0) for i in range(0, 10)] invalid_inp = MeasureInput(target, tsk, tsk.config_space.get(10)) invalid_res = MeasureResult((10,), 0, 0, 0) # Erase the entity map to test if it will be ignored when loading back. invalid_inp.config._entity_map = {} with open(file_path, "w") as fo: cb = autotvm.callback.log_to_file(fo) cb(None, inputs, results) cb(None, [invalid_inp], [invalid_res]) ref = zip(inputs, results) for x, y in zip(ref, autotvm.record.load_from_file(file_path)): assert x[1] == y[1] # Confirm functionality of multiple file loads hist_best = ApplyHistoryBest([file_path, file_path]) x = hist_best.query(target, tsk.workload) assert str(x) == str(inputs[0][2]) def test_apply_history_best(tmpdir): tsk, target = get_sample_task() best = str(tsk.config_space.get(2)) inputs_batch_1 = [MeasureInput(target, tsk, tsk.config_space.get(i)) for i in range(3)] results_batch_1 = [MeasureResult((i,), 0, 0, 0) for i in range(1, 3)] results_batch_1.append(MeasureResult((0.5,), 0, 2.3, 0)) # Write data out to file filepath_batch_1 = tmpdir / "batch_1.log" with open(filepath_batch_1, "w") as file: autotvm.callback.log_to_file(file)(None, inputs_batch_1, results_batch_1) # Load best results from Path assert isinstance(filepath_batch_1, PathLike) hist_best = ApplyHistoryBest(filepath_batch_1) assert str(hist_best.query(target, tsk.workload)) == best # Load best results from str(Path) hist_best = ApplyHistoryBest(str(filepath_batch_1)) assert str(hist_best.query(target, tsk.workload)) == best # Write data into StringIO buffer stringio_batch_1 = StringIO() assert isinstance(filepath_batch_1, PathLike) callback = autotvm.callback.log_to_file(stringio_batch_1) callback(None, inputs_batch_1, results_batch_1) stringio_batch_1.seek(0) # Load best results from strIO hist_best = ApplyHistoryBest(stringio_batch_1) assert str(hist_best.query(target, tsk.workload)) == best # Load best result from list of tuples (MeasureInput, MeasureResult) hist_best = ApplyHistoryBest(list(zip(inputs_batch_1, results_batch_1))) assert str(hist_best.query(target, tsk.workload)) == best # Same thing, but iterable instead of list (i.e. no subscripting) hist_best = ApplyHistoryBest(zip(inputs_batch_1, results_batch_1)) assert str(hist_best.query(target, tsk.workload)) == best def test_apply_history_best_multiple_batches(tmpdir): tsk, target = get_sample_task() best = str(tsk.config_space.get(2)) inputs_batch_1 = [MeasureInput(target, tsk, tsk.config_space.get(i)) for i in range(2)] results_batch_1 = [MeasureResult((i,), 0, 0, 0) for i in range(1, 3)] filepath_batch_1 = tmpdir / "batch_1.log" with open(filepath_batch_1, "w") as file: autotvm.callback.log_to_file(file)(None, inputs_batch_1, results_batch_1) inputs_batch_2 = [MeasureInput(target, tsk, tsk.config_space.get(i)) for i in range(2, 4)] results_batch_2 = [MeasureResult((0.5,), 0, 0, 0), MeasureResult((3,), 0, 0, 0)] filepath_batch_2 = tmpdir / "batch_2.log" with open(filepath_batch_2, "w") as file: autotvm.callback.log_to_file(file)(None, inputs_batch_2, results_batch_2) # Check two Path filepaths works hist_best = ApplyHistoryBest([filepath_batch_1, filepath_batch_2]) assert str(hist_best.query(target, tsk.workload)) == best # Check that an arbitrary Iterable of Paths works # Calling zip() on a single list gives a non-subscriptable Iterable hist_best = ApplyHistoryBest(zip([filepath_batch_1, filepath_batch_2])) assert str(hist_best.query(target, tsk.workload)) == best # Check that Iterable of Iterable of tuples is correctly merged hist_best = ApplyHistoryBest( zip( [ zip(inputs_batch_1, results_batch_1), zip(inputs_batch_2, results_batch_2), ] ) ) assert str(hist_best.query(target, tsk.workload)) == best if __name__ == "__main__": test_load_dump() test_apply_history_best() test_file_io()
https://github.com/zk-ml/tachikoma
tests/python/unittest/test_autotvm_space.py
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. """Test space definition primitives""" from tvm import te from tvm.autotvm.task.space import ConfigSpace, FallbackConfigEntity def gemm_func(cfg, N, filter_y=None, filter_x=None): A = te.placeholder((N, N), name="A") B = te.placeholder((N, N), name="B") k = te.reduce_axis((0, N), name="k") C = te.compute((N, N), lambda i, j: te.sum(A[i, k] * B[k, j], axis=[k]), name="C") s = te.create_schedule([C.op]) y, x = s[C].op.axis cfg.define_split("tile_y", cfg.axis(y), num_outputs=2, filter=filter_y) cfg.define_split("tile_x", cfg.axis(x), num_outputs=2, filter=filter_x) return s, [A, B, C] def test_split(): cfg = ConfigSpace() gemm_func(cfg, 128) assert cfg.range_length == 64 assert len(cfg.space_map["tile_y"]) == 8 # test policy cfg = ConfigSpace() cfg.define_split("tile_x", cfg.axis(256), policy="factors", num_outputs=3) assert len(cfg.space_map["tile_x"]) == 45 cfg.define_split("tile_y", cfg.axis(256), policy="power2", num_outputs=3) assert len(cfg.space_map["tile_y"]) == 45 cfg.define_split("tile_z", cfg.axis(256), policy="verbose", num_outputs=3) assert len(cfg.space_map["tile_z"]) == 45 cfg.define_split("tile_a", cfg.axis(224), policy="factors", num_outputs=3) assert len(cfg.space_map["tile_a"]) == 63 cfg.define_split("tile_b", cfg.axis(224), policy="power2", num_outputs=3) assert len(cfg.space_map["tile_b"]) == 36 cfg.define_split("tile_c", cfg.axis(224), policy="verbose", num_outputs=3) assert len(cfg.space_map["tile_c"]) == 84 # Count the number of non-negative integer solutions of a + b + c + d = n def count4(n): cnt = 0 for a in range(0, n + 1): for b in range(0, n - a + 1): cnt += n - a - b + 1 return cnt # test overflow n = 25 cfg = ConfigSpace() cfg.define_split("x", cfg.axis(2**n), policy="factors", num_outputs=4) # count4(25) is 3276. assert len(cfg.space_map["x"]) == count4(n) # test fallback cfg = FallbackConfigEntity() cfg.define_split("tile_n", cfg.axis(128), num_outputs=3) cfg.fallback_split("tile_n", [-1, 8, 4]) # verify if define_split override previously manualy defined split params cfg.define_split("tile_n", cfg.axis(128), num_outputs=3) assert cfg["tile_n"].size == [4, 8, 4] cfg = FallbackConfigEntity() cfg.define_split("tile_n", cfg.axis(49), num_outputs=3) cfg.fallback_split("tile_n", [-1, 8, 4]) assert cfg["tile_n"].size == [7, 7, 1] cfg = FallbackConfigEntity() cfg.define_split("tile_n", cfg.axis(49), num_outputs=3) try: cfg.fallback_split("tile_n", [-1, 1, 0]) assert False except RuntimeError: pass def _raises_exception(f): try: f() except Exception: return True return False def test_multi_filter(): # create config without multi_filter cfg = ConfigSpace() gemm_func(cfg, 128) # create config with multi_filter cfg_mf = ConfigSpace() gemm_func(cfg_mf, 128) cfg_mf.multi_filter( filter=lambda entity: 32 <= (entity["tile_x"].size[1] * entity["tile_y"].size[1]) < 1024 ) # test len assert len(cfg) == 64 assert len(cfg_mf) == 34 # test range_length assert cfg.range_length == 64 assert cfg_mf.range_length == 64 # test dims assert cfg.dims == [8, 8] assert cfg_mf.dims == [8, 8] # test is_index_valid assert cfg.is_index_valid(0) is True assert cfg.is_index_valid(15) is True assert cfg_mf.is_index_valid(0) is False assert cfg_mf.is_index_valid(15) is True # test get assert _raises_exception(lambda: cfg.get(0)) is False assert _raises_exception(lambda: cfg.get(15)) is False assert _raises_exception(lambda: cfg_mf.get(0)) is True assert _raises_exception(lambda: cfg_mf.get(15)) is False # test subrange_length assert cfg.subrange_length(0, 64) == 64 assert cfg.subrange_length(0, 32) == 32 assert cfg.subrange_length(16, 32) == 16 assert cfg.subrange_length(16, 16) == 0 assert _raises_exception(lambda: cfg.subrange_length(0, 128)) assert _raises_exception(lambda: cfg.subrange_length(-64, 64)) assert _raises_exception(lambda: cfg.subrange_length(64, 0)) assert cfg_mf.subrange_length(0, 64) == 34 assert cfg_mf.subrange_length(0, 32) == 17 assert cfg_mf.subrange_length(16, 32) == 10 assert cfg_mf.subrange_length(16, 16) == 0 assert _raises_exception(lambda: cfg_mf.subrange_length(0, 128)) assert _raises_exception(lambda: cfg_mf.subrange_length(-64, 64)) assert _raises_exception(lambda: cfg_mf.subrange_length(64, 0)) # test point2knob assert cfg.point2knob(0) == [0, 0] assert cfg.point2knob(4) == [4, 0] assert cfg.point2knob(8) == [0, 1] assert cfg.point2knob(12) == [4, 1] assert cfg_mf.point2knob(0) == [0, 0] assert cfg_mf.point2knob(4) == [4, 0] assert cfg_mf.point2knob(8) == [0, 1] assert cfg_mf.point2knob(12) == [4, 1] # test knob2point assert cfg.knob2point([0, 0]) == 0 assert cfg.knob2point([4, 0]) == 4 assert cfg.knob2point([0, 1]) == 8 assert cfg.knob2point([4, 1]) == 12 assert cfg_mf.knob2point([0, 0]) == 0 assert cfg_mf.knob2point([4, 0]) == 4 assert cfg_mf.knob2point([0, 1]) == 8 assert cfg_mf.knob2point([4, 1]) == 12 # get_rand_index cfg_valid_indexes = list(filter(lambda idx: cfg.is_index_valid(idx), range(cfg.range_length))) assert cfg.get_rand_index() in cfg_valid_indexes assert cfg.get_rand_index(start=15, end=16) == 15 assert 10 <= cfg.get_rand_index(start=10, end=20) < 20 assert cfg.get_rand_index(to_exclude=cfg_valid_indexes[:-1]) == cfg_valid_indexes[-1:][0] cfg_mf_valid_indexes = list( filter(lambda idx: cfg_mf.is_index_valid(idx), range(cfg_mf.range_length)) ) assert cfg_mf.get_rand_index() in cfg_mf_valid_indexes assert cfg_mf.get_rand_index(start=15, end=16) == 15 assert 10 <= cfg_mf.get_rand_index(start=10, end=20) < 20 assert ( cfg_mf.get_rand_index(to_exclude=cfg_mf_valid_indexes[:-1]) == cfg_mf_valid_indexes[-1:][0] ) # get_next_index assert cfg.get_next_index(0) == 1 assert cfg.get_next_index(0, 1) == 1 assert cfg.get_next_index(0, 2) == 2 assert cfg.get_next_index(0, -1) is None assert cfg.get_next_index(0, -2) is None assert cfg.get_next_index(63) is None assert cfg.get_next_index(63, 1) is None assert cfg.get_next_index(63, 2) is None assert cfg.get_next_index(63, -1) == 62 assert cfg.get_next_index(63, -2) == 61 assert cfg.get_next_index(60, 1, end=63) == 61 assert cfg.get_next_index(63, -1, start=60) == 62 assert cfg_mf.get_next_index(0) == 5 assert cfg_mf.get_next_index(0, 1) == 5 assert cfg_mf.get_next_index(0, 2) == 6 assert cfg_mf.get_next_index(0, -1) is None assert cfg_mf.get_next_index(0, -2) is None assert cfg_mf.get_next_index(63) is None assert cfg_mf.get_next_index(63, 1) is None assert cfg_mf.get_next_index(63, 2) is None assert cfg_mf.get_next_index(63, -1) == 58 assert cfg_mf.get_next_index(63, -2) == 57 assert cfg_mf.get_next_index(60, 1, end=63) is None assert cfg_mf.get_next_index(63, -1, start=60) is None # test sample_ints cfg_ints = cfg.sample_ints(5) assert len(cfg_ints) == 5 assert set(cfg_ints).issubset(cfg_valid_indexes) cfg_mf_ints = cfg_mf.sample_ints(5) assert len(cfg_mf_ints) == 5 assert set(cfg_mf_ints).issubset(cfg_mf_valid_indexes) # test random_walk cfg_walk = cfg.random_walk(15) assert cfg_walk != 15 assert cfg_walk in cfg_valid_indexes cfg_mf_walk = cfg_mf.random_walk(15) assert cfg_mf_walk != 15 assert cfg_mf_walk in cfg_mf_valid_indexes def test_filter_and_multi_filter(): # test the order: filter -> multi_filter cfg = ConfigSpace() gemm_func(cfg, 128, filter_y=lambda y: y.size[-1] < 64) # after adding filter assert len(cfg) == 48 assert cfg.range_length == 48 cfg.multi_filter( filter=lambda entity: 32 <= (entity["tile_x"].size[1] * entity["tile_y"].size[1]) < 1024 ) # after adding multi_filter assert len(cfg) == 27 assert cfg.range_length == 48 # test the order: multi_filter -> filter cfg = ConfigSpace() s, (A, B, C) = gemm_func(cfg, 128, filter_y=None) cfg.multi_filter( filter=lambda entity: 32 <= (entity["tile_x"].size[1] * entity["tile_y"].size[1]) < 1024 ) # after adding multi_filter assert len(cfg) == 34 assert cfg.range_length == 64 y, x = s[C].op.axis cfg.define_split("tile_y", cfg.axis(y), num_outputs=2, filter=lambda y: y.size[-1] < 64) # after adding filter assert len(cfg) == 27 assert cfg.range_length == 48 if __name__ == "__main__": test_split() test_multi_filter() test_filter_and_multi_filter()
https://github.com/zk-ml/tachikoma
tests/python/unittest/test_autotvm_xgboost_model.py
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. import time import multiprocessing import numpy as np import tvm from tvm import te from tvm import autotvm from tvm.autotvm import MeasureInput, MeasureResult from tvm.autotvm.tuner.xgboost_cost_model import XGBoostCostModel from tvm.testing.autotvm import get_sample_task, get_sample_records def test_fit(): task, target = get_sample_task() records = get_sample_records(n=500) base_model = XGBoostCostModel(task, feature_type="itervar", loss_type="rank") base_model.fit_log(records, plan_size=32) upper_model = XGBoostCostModel(task, feature_type="itervar", loss_type="rank") upper_model.load_basemodel(base_model) xs = np.arange(10) ys = np.arange(10) upper_model.fit(xs, ys, plan_size=32) # feature lengths are not guaranteed to always be the same upper_model.predict(np.ones(12)) upper_model.predict(np.ones(8)) def fit_spawn(): assert multiprocessing.get_start_method(False) == "spawn" test_fit() def test_fit_spawn(): # Subprocesses inherit the spawn method of their parents ctx = multiprocessing.get_context("spawn") p = ctx.Process(target=test_fit) p.start() p.join() def test_tuner(): task, target = get_sample_task() records = get_sample_records(n=10) tuner = autotvm.tuner.XGBTuner(task) tuner.load_history(records, min_seed_records=10) # Confirm that loading history successfully loaded a # base_model. assert tuner.cost_model.base_model is not None tuner = autotvm.tuner.XGBTuner(task) tuner.load_history(records, min_seed_records=11) # Confirm that loading history did not load base_model # when not enough records according to `min_seed_records` # are provided assert tuner.cost_model.base_model is None def test_update(): task, target = get_sample_task() tuner = autotvm.tuner.XGBTuner(task) n_records = 5 records = get_sample_records(n=n_records) tuner.update([inp for inp, _ in records], [res for _, res in records]) assert len(tuner.xs) == n_records assert len(tuner.ys) == n_records assert len(tuner.visited) == n_records assert all(x in tuner.visited for x in tuner.xs) if __name__ == "__main__": test_fit() test_fit_spawn() test_tuner() test_update()
https://github.com/zk-ml/tachikoma
tests/python/unittest/test_container_structural_equal.py
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. import pytest import tvm import tvm.testing from tvm.ir.base import get_first_structural_mismatch from tvm.runtime import ObjectPath def get_first_mismatch_ensure_symmetry(a, b): mismatch = get_first_structural_mismatch(a, b) mismatch_swapped = get_first_structural_mismatch(b, a) if mismatch is None and mismatch_swapped is None: return None if ( mismatch is None or mismatch_swapped is None or mismatch[0] != mismatch_swapped[1] or mismatch[1] != mismatch_swapped[0] ): raise AssertionError( "get_first_structural_mismatch(a, b) and get_first_structural_mismatch(b, a) returned" " inconsistent results '{}' and '{}' for a='{}', b='{}'".format( mismatch, mismatch_swapped, a, b ) ) a_path, b_path = mismatch b_path_swapped, a_path_swapped = mismatch_swapped assert a_path == a_path_swapped assert b_path == b_path_swapped return mismatch @pytest.mark.parametrize( "a, b, expected_a_path, expected_b_path", [ ( [1, 2, 3], [1, 4, 3], ObjectPath.root().array_index(1).attr("value"), ObjectPath.root().array_index(1).attr("value"), ), ( [1, 2, 3], [10, 2, 30], ObjectPath.root().array_index(0).attr("value"), ObjectPath.root().array_index(0).attr("value"), ), ( [1, 3, 4], [1, 2, 3, 4], ObjectPath.root().array_index(1).attr("value"), ObjectPath.root().array_index(1).attr("value"), ), ( [1, 2, 3], [1, 2, 3, 4], ObjectPath.root().missing_array_element(3), ObjectPath.root().array_index(3), ), ( [], [1], ObjectPath.root().missing_array_element(0), ObjectPath.root().array_index(0), ), ], ) def test_array_structural_mismatch(a, b, expected_a_path, expected_b_path): a = tvm.runtime.convert(a) b = tvm.runtime.convert(b) a_path, b_path = get_first_mismatch_ensure_symmetry(a, b) assert a_path == expected_a_path assert b_path == expected_b_path @pytest.mark.parametrize( "contents", [ [], [1], [1, 2, 3], ], ) def test_array_structural_equal_to_self(contents): a = tvm.runtime.convert(list(contents)) b = tvm.runtime.convert(list(contents)) assert get_first_mismatch_ensure_symmetry(a, b) is None @pytest.mark.parametrize( "a, b, expected_a_path, expected_b_path", [ ( dict(a=3, b=4), dict(a=3, b=5), ObjectPath.root().map_value("b").attr("value"), ObjectPath.root().map_value("b").attr("value"), ), ( dict(a=3, b=4), dict(a=3, b=4, c=5), ObjectPath.root().missing_map_entry(), ObjectPath.root().map_value("c"), ), ], ) def test_string_map_structural_mismatch(a, b, expected_a_path, expected_b_path): a = tvm.runtime.convert(a) b = tvm.runtime.convert(b) a_path, b_path = get_first_mismatch_ensure_symmetry(a, b) assert a_path == expected_a_path assert b_path == expected_b_path @pytest.mark.parametrize( "contents", [ dict(), dict(a=1), dict(a=3, b=4, c=5), ], ) def test_string_structural_equal_to_self(contents): a = tvm.runtime.convert(dict(contents)) b = tvm.runtime.convert(dict(contents)) assert get_first_mismatch_ensure_symmetry(a, b) is None # The behavior of structural equality for maps with non-string keys is fairly specific # to IR variables because it assumes that map keys have been "mapped" using # `SEqualReducer::FreeVarEqualImpl()`. So we leave this case to TIR tests. if __name__ == "__main__": tvm.testing.main()
https://github.com/zk-ml/tachikoma
tests/python/unittest/test_crt.py
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. import numpy as np import os import pathlib import shutil import pytest pytest.importorskip("pty") import pytest import tvm import tvm.relay import tvm.testing from tvm.target import Target from tvm.relay.backend import Runtime from tvm.relay.backend import Executor BUILD = True DEBUG = False TARGET = tvm.target.target.micro("host") def _make_sess_from_op(temp_dir, op_name, sched, arg_bufs): runtime = Runtime("crt", {"system-lib": True}) with tvm.transform.PassContext(opt_level=3, config={"tir.disable_vectorize": True}): mod = tvm.build(sched, arg_bufs, Target(TARGET, TARGET), runtime=runtime, name=op_name) return _make_session(temp_dir, mod) def _make_session(temp_dir, mod): template_project_dir = os.path.join(tvm.micro.get_standalone_crt_dir(), "template", "host") project = tvm.micro.generate_project( template_project_dir, mod, temp_dir / "project", {"verbose": 1} ) project.build() project.flash() return tvm.micro.Session(project.transport()) def _make_add_sess(temp_dir): A = tvm.te.placeholder((2,), dtype="int8") B = tvm.te.placeholder((1,), dtype="int8") C = tvm.te.compute(A.shape, lambda i: A[i] + B[0], name="C") sched = tvm.te.create_schedule(C.op) return _make_sess_from_op(temp_dir, "add", sched, [A, B, C]) def _make_ident_sess(temp_dir): A = tvm.te.placeholder((2,), dtype="int8") B = tvm.te.compute(A.shape, lambda i: A[i], name="B") sched = tvm.te.create_schedule(B.op) return _make_sess_from_op(temp_dir, "ident", sched, [A, B]) @tvm.testing.requires_micro def test_compile_runtime(): """Test compiling the on-device runtime.""" import tvm.micro temp_dir = tvm.contrib.utils.tempdir() with _make_add_sess(temp_dir) as sess: A_data = tvm.nd.array(np.array([2, 3], dtype="int8"), device=sess.device) assert (A_data.numpy() == np.array([2, 3])).all() B_data = tvm.nd.array(np.array([4], dtype="int8"), device=sess.device) assert (B_data.numpy() == np.array([4])).all() C_data = tvm.nd.array(np.array([0, 0], dtype="int8"), device=sess.device) assert (C_data.numpy() == np.array([0, 0])).all() system_lib = sess.get_system_lib() system_lib.get_function("add")(A_data, B_data, C_data) assert (C_data.numpy() == np.array([6, 7])).all() @tvm.testing.requires_micro def test_compile_runtime_llvm(): """Test targeting the on-device runtime with the llvm backend.""" global TARGET old_target = TARGET try: # NOTE: test_compile_runtime uses the "c" backend--re run it using the llvm backend. target_str = str(TARGET) assert target_str.startswith("c ") TARGET = tvm.target.Target("llvm " + str(TARGET)[len("c ") :]) test_compile_runtime() finally: TARGET = old_target @tvm.testing.requires_micro def test_reset(): """Test when the remote end resets during a session.""" import tvm.micro from tvm.micro import transport temp_dir = tvm.contrib.utils.tempdir() with _make_add_sess(temp_dir) as sess: try: sess._rpc.get_function("tvm.testing.reset_server")() assert False, "expected to raise SessionTerminatedError; did not raise" except tvm.micro.SessionTerminatedError: pass @tvm.testing.requires_micro def test_graph_executor(): """Test use of the graph executor with microTVM.""" ws_root = pathlib.Path(os.path.dirname(__file__) + "/micro-workspace") if ws_root.exists(): shutil.rmtree(ws_root) temp_dir = tvm.contrib.utils.tempdir(ws_root.resolve()) relay_mod = tvm.parser.fromtext( """ #[version = "0.0.5"] def @main(%a : Tensor[(1, 2), uint8], %b : Tensor[(1, 2), uint8]) { %0 = %a + %b; %0 }""" ) runtime = Runtime("crt", {"system-lib": True}) with tvm.transform.PassContext(opt_level=3, config={"tir.disable_vectorize": True}): factory = tvm.relay.build(relay_mod, target=TARGET, runtime=runtime) def do_test(graph_mod): A_data = tvm.nd.array(np.array([2, 3], dtype="uint8"), device=sess.device) assert (A_data.numpy() == np.array([2, 3])).all() B_data = tvm.nd.array(np.array([4, 7], dtype="uint8"), device=sess.device) assert (B_data.numpy() == np.array([4, 7])).all() assert graph_mod.get_input_index("a") == 0 assert graph_mod.get_input_index("b") == 1 graph_mod.run(a=A_data, b=B_data) out = graph_mod.get_output(0) assert (out.numpy() == np.array([6, 10])).all() with _make_session(temp_dir, factory) as sess: graph_mod_local = tvm.micro.create_local_graph_executor( factory.get_graph_json(), sess.get_system_lib(), sess.device ) do_test(graph_mod_local) graph_mod = tvm.contrib.graph_executor.create( factory.get_graph_json(), sess.get_system_lib(), sess.device ) do_test(graph_mod) @tvm.testing.requires_micro def test_aot_executor(): """Test use of the AOT executor with microTVM.""" ws_root = pathlib.Path(os.path.dirname(__file__) + "/micro-workspace") if ws_root.exists(): shutil.rmtree(ws_root) temp_dir = tvm.contrib.utils.tempdir(ws_root.resolve()) relay_mod = tvm.parser.fromtext( """ #[version = "0.0.5"] def @main(%a : Tensor[(1, 2), uint8], %b : Tensor[(1, 2), uint8]) { %0 = %a + %b; %0 }""" ) runtime = Runtime("crt", {"system-lib": True}) executor = Executor("aot") with tvm.transform.PassContext(opt_level=3, config={"tir.disable_vectorize": True}): factory = tvm.relay.build(relay_mod, target=TARGET, runtime=runtime, executor=executor) def do_test(): aot_executor = tvm.runtime.executor.aot_executor.AotModule( sess._rpc.get_function("tvm.aot_executor.create")( sess.get_system_lib(), sess.device, "default" ) ) assert aot_executor.get_input_index("a") == 0 assert aot_executor.get_input_index("b") == 1 assert aot_executor.get_num_inputs() == 2 assert aot_executor.get_num_outputs() == 1 A_np = np.array([[2, 3]], dtype="uint8") B_np = np.array([[4, 7]], dtype="uint8") A_data = aot_executor.get_input("a").copyfrom(A_np) B_data = aot_executor.get_input("b").copyfrom(B_np) aot_executor.run() out = aot_executor.get_output(0) assert (out.numpy() == np.array([6, 10])).all() B_np_new = np.array([[5, 8]]) aot_executor.set_input("b", B_np_new) assert (B_data.numpy() == B_np_new).all() with _make_session(temp_dir, factory) as sess: do_test() enable_usmp, expect_exception = tvm.testing.parameters((True, True), (False, False)) @tvm.testing.requires_micro def test_aot_executor_usmp_const_pool(enable_usmp, expect_exception): """Test the AOT executor with microTVM using usmp. Test should fail if const pool is supplied to executor as these are currently not supported """ ws_root = pathlib.Path(os.path.dirname(__file__) + "/micro-workspace-usmp") if ws_root.exists(): shutil.rmtree(ws_root) temp_dir = tvm.contrib.utils.tempdir(ws_root.resolve()) relay_mod = tvm.parser.fromtext( """ #[version = "0.0.5"] def @main(%a : Tensor[(1, 2), uint8], %b : Tensor[(1, 2), uint8], %c : Tensor[(1,2), uint8]) { %0 = %a + %b; %1 = %0 + %c; %1 }""" ) runtime = Runtime("crt", {"system-lib": True}) executor = Executor("aot") main_func = relay_mod["main"] type_dict = {p.name_hint: p.checked_type.dtype for p in main_func.params} B_np = np.array([[4, 7]], dtype="uint8").astype(type_dict["b"]) C_np = np.array([[8, 9]], dtype="uint8").astype(type_dict["c"]) params = {"c": C_np} with tvm.transform.PassContext( opt_level=3, config={"tir.disable_vectorize": True, "tir.usmp.enable": enable_usmp} ): factory = tvm.relay.build( relay_mod, target=TARGET, runtime=runtime, executor=executor, params=params, ) def do_test(): try: aot_executor = tvm.runtime.executor.aot_executor.AotModule( sess._rpc.get_function("tvm.aot_executor.create")( sess.get_system_lib(), sess.device, "default" ) ) except tvm._ffi.base.TVMError as e: if expect_exception: return else: raise e assert aot_executor.get_input_index("a") == 0 assert aot_executor.get_input_index("b") == 1 assert aot_executor.get_num_inputs() == 2 assert aot_executor.get_num_outputs() == 1 A_np = np.array([[2, 3]], dtype="uint8") B_np = np.array([[4, 7]], dtype="uint8") A_data = aot_executor.get_input("a").copyfrom(A_np) B_data = aot_executor.get_input("b").copyfrom(B_np) aot_executor.run() out = aot_executor.get_output(0) assert (out.numpy() == np.array([14, 19])).all() B_np_new = np.array([[5, 8]]) aot_executor.set_input("b", B_np_new) assert (B_data.numpy() == B_np_new).all() with _make_session(temp_dir, factory) as sess: do_test() @tvm.testing.requires_micro def test_std_math_functions(): """Verify that standard math functions can be used.""" import tvm.micro temp_dir = tvm.contrib.utils.tempdir() with _make_add_sess(temp_dir) as sess: A_data = tvm.nd.array(np.array([2, 3], dtype="int8"), device=sess.device) assert (A_data.numpy() == np.array([2, 3])).all() B_data = tvm.nd.array(np.array([4], dtype="int8"), device=sess.device) assert (B_data.numpy() == np.array([4])).all() C_data = tvm.nd.array(np.array([0, 0], dtype="int8"), device=sess.device) assert (C_data.numpy() == np.array([0, 0])).all() system_lib = sess.get_system_lib() system_lib.get_function("add")(A_data, B_data, C_data) temp_dir = tvm.contrib.utils.tempdir() A = tvm.te.placeholder((2,), dtype="float32", name="A") B = tvm.te.compute(A.shape, lambda i: tvm.te.exp(A[i]), name="B") s = tvm.te.create_schedule(B.op) with _make_sess_from_op(temp_dir, "myexpf", s, [A, B]) as sess: A_data = tvm.nd.array(np.array([2.0, 3.0], dtype="float32"), device=sess.device) B_data = tvm.nd.array(np.array([2.0, 3.0], dtype="float32"), device=sess.device) lib = sess.get_system_lib() func = lib["myexpf"] func(A_data, B_data) np.testing.assert_allclose(B_data.numpy(), np.array([7.389056, 20.085537])) @tvm.testing.requires_micro def test_platform_timer(): """Verify the platform timer can be used to time remote functions.""" import tvm.micro temp_dir = tvm.contrib.utils.tempdir() A = tvm.te.placeholder((2,), dtype="float32", name="A") B = tvm.te.compute(A.shape, lambda i: tvm.te.exp(A[i]), name="B") s = tvm.te.create_schedule(B.op) with _make_sess_from_op(temp_dir, "myexpf", s, [A, B]) as sess: A_data = tvm.nd.array(np.array([2.0, 3.0], dtype="float32"), device=sess.device) B_data = tvm.nd.array(np.array([2.0, 3.0], dtype="float32"), device=sess.device) lib = sess.get_system_lib() time_eval_f = lib.time_evaluator( "myexpf", sess.device, number=2000, repeat=3, min_repeat_ms=40 ) result = time_eval_f(A_data, B_data) assert result.mean > 0 assert len(result.results) == 3 @tvm.testing.requires_micro def test_autotune(): """Verify that autotune works with micro.""" import tvm.relay as relay from tvm.micro.testing.utils import check_tune_log runtime = Runtime("crt", {"system-lib": True}) data = relay.var("data", relay.TensorType((1, 3, 64, 64), "float32")) weight = relay.var("weight", relay.TensorType((8, 3, 5, 5), "float32")) y = relay.nn.conv2d( data, weight, padding=(2, 2), kernel_size=(5, 5), kernel_layout="OIHW", out_dtype="float32", ) f = relay.Function([data, weight], y) mod = tvm.IRModule.from_expr(f) mod = relay.transform.InferType()(mod) main_func = mod["main"] shape_dict = {p.name_hint: p.checked_type.concrete_shape for p in main_func.params} type_dict = {p.name_hint: p.checked_type.dtype for p in main_func.params} weight_data = np.ones(shape_dict["weight"]).astype(type_dict["weight"]) input_data = np.ones(shape_dict["data"]).astype(type_dict["data"]) params = {"weight": weight_data} inputs = {"data": input_data} target = tvm.target.target.micro("host") template_project_dir = pathlib.Path(tvm.micro.get_microtvm_template_projects("crt")) pass_context = tvm.transform.PassContext(opt_level=3, config={"tir.disable_vectorize": True}) with pass_context: tasks = tvm.autotvm.task.extract_from_program(mod["main"], {}, target) assert len(tasks) > 0 module_loader = tvm.micro.AutoTvmModuleLoader( template_project_dir=template_project_dir, project_options={}, ) builder = tvm.autotvm.LocalBuilder( n_parallel=1, build_kwargs={"build_option": {"tir.disable_vectorize": True}}, do_fork=True, build_func=tvm.micro.autotvm_build_func, runtime=runtime, ) runner = tvm.autotvm.LocalRunner(number=1, repeat=1, module_loader=module_loader) measure_option = tvm.autotvm.measure_option(builder=builder, runner=runner) tune_log_file = pathlib.Path("crt_autotune.log") if tune_log_file.exists(): tune_log_file.unlink() num_trials = 10 for task in tasks: tuner = tvm.autotvm.tuner.GATuner(task) tuner.tune( n_trial=num_trials, measure_option=measure_option, callbacks=[ tvm.autotvm.callback.log_to_file(str(tune_log_file)), tvm.autotvm.callback.progress_bar(num_trials, si_prefix="M"), ], si_prefix="M", ) assert tuner.best_flops > 0 # TODO(mehrdadh): commented due to autotuning errors # check_tune_log(tune_log_file) # Build without tuning with pass_context: lowered = tvm.relay.build(mod, target=TARGET, runtime=runtime, params=params) temp_dir = tvm.contrib.utils.tempdir() project = tvm.micro.generate_project(template_project_dir, lowered, temp_dir / "project") project.build() with tvm.micro.Session(project.transport()) as session: graph_mod = tvm.micro.create_local_graph_executor( lowered.get_graph_json(), session.get_system_lib(), session.device ) graph_mod.set_input(**lowered.get_params()) graph_mod.run(**inputs) expected_output = graph_mod.get_output(0).numpy() del graph_mod # Build using autotune logs with tvm.autotvm.apply_history_best(str(tune_log_file)): with pass_context: lowered_tuned = tvm.relay.build(mod, target=target, runtime=runtime, params=params) temp_dir = tvm.contrib.utils.tempdir() project = tvm.micro.generate_project(template_project_dir, lowered_tuned, temp_dir / "project") project.build() with tvm.micro.Session(project.transport()) as session: graph_mod = tvm.micro.create_local_graph_executor( lowered_tuned.get_graph_json(), session.get_system_lib(), session.device ) graph_mod.set_input(**lowered_tuned.get_params()) graph_mod.run(**inputs) output = graph_mod.get_output(0).numpy() del graph_mod tvm.testing.assert_allclose(output, expected_output, rtol=1e-4, atol=1e-5) if __name__ == "__main__": tvm.testing.main()
https://github.com/zk-ml/tachikoma
tests/python/unittest/test_custom_datatypes.py
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. """Unit tests for the Bring Your Own Datatype framework. TODO(@gussmith23 @hypercubestart) link to documentation""" import numpy as np import pytest import tvm import tvm.topi.testing import tvm.testing from tvm import relay from tvm.relay.testing.layers import batch_norm_infer from tvm.target.datatype import ( create_lower_func, create_min_lower_func, lower_call_pure_extern, lower_ite, register, register_min_func, register_op, ) from tvm.tir.op import call_pure_extern # note: we can't use relay.testing models because params are randomly initialized, # which lead the output to have the same values # get mobilenet model from Gluon CV # because: https://discuss.tvm.apache.org/t/mobilenet-intermediate-values-are-0/7812 def get_mobilenet(): dshape = (1, 3, 224, 224) from mxnet.gluon.model_zoo.vision import get_model block = get_model("mobilenet0.25", pretrained=True) shape_dict = {"data": dshape} return relay.frontend.from_mxnet(block, shape_dict) # use real image instead of random data for end-to-end model training # or else output would all be around the same value def get_cat_image(dimensions): from PIL import Image from tvm.contrib.download import download_testdata url = "https://gist.githubusercontent.com/zhreshold/bcda4716699ac97ea44f791c24310193/raw/fa7ef0e9c9a5daea686d6473a62aacd1a5885849/cat.png" dst = "cat.png" real_dst = download_testdata(url, dst, module="data") img = Image.open(real_dst).resize(dimensions) # CoreML's standard model image format is BGR img_bgr = np.array(img)[:, :, ::-1] img = np.transpose(img_bgr, (2, 0, 1))[np.newaxis, :] return np.asarray(img, dtype="float32") # we use a random seed to generate input_data # to guarantee stable tests np.random.seed(0) def convert_ndarray(dst_dtype, array): """Converts NDArray(s) into the specified datatype""" x = relay.var("x", shape=array.shape, dtype=str(array.dtype)) cast = relay.Function([x], x.astype(dst_dtype)) with tvm.transform.PassContext(config={"tir.disable_vectorize": True}): return relay.create_executor("graph").evaluate(cast)(array) def change_dtype(src, dst, module, params): """Convert constants and functions in module from src type to dst type. Returns changed module and converted params of type dst_type. """ module = relay.frontend.ChangeDatatype(src, dst)(module) module = relay.transform.InferType()(module) params = {k: convert_ndarray(dst, v) for k, v in params.items()} return module, params def compare(module, input, src_dtype, dst_dtype, rtol, atol, params={}, target="llvm"): module = relay.transform.InferType()(module) module = relay.transform.SimplifyInference()(module) correct = relay.create_executor("graph", mod=module).evaluate()(*input, **params) module, converted_params = change_dtype(src_dtype, dst_dtype, module, params) # converts all inputs to dst_dtype x_converted = [convert_ndarray(dst_dtype, arr) for arr in input] # Vectorization is not implemented with custom datatypes with tvm.transform.PassContext(config={"tir.disable_vectorize": True}): maybe_correct = relay.create_executor("graph", mod=module, target=target).evaluate()( *x_converted, **converted_params ) # currently this only works for comparing single output maybe_correct_converted = convert_ndarray(src_dtype, maybe_correct) np.testing.assert_allclose( maybe_correct_converted.numpy(), correct.numpy(), rtol=rtol, atol=atol ) def setup_myfloat(): """Set up tests for myfloat (a custom datatype that under the hood is float) Currently, this registers some custom datatypes using the Bring Your Own Datatypes framework. """ # To use datatype operations in an external library, you should first load # the library containing the datatype implementation: # CDLL("libposit.so", RTLD_GLOBAL) # In this case, the datatype library we are using is built right into TVM, # so we do not need to explicitly load any library. # You can pick a code for your datatype arbitrarily, as long as it is # greater than 128 and has not already been chosen. register("myfloat", 131) register_op( create_lower_func({(32, 32): "FloatToCustom32"}), "Cast", "llvm", "float", "myfloat" ) register_op( create_lower_func({(32, 32): "Custom32ToFloat"}), "Cast", "llvm", "myfloat", "float" ) register_op(create_lower_func({32: "Custom32Add"}), "Add", "llvm", "myfloat") register_op( create_lower_func( { 32: "Custom32Sub", } ), "Sub", "llvm", "myfloat", ) register_op(create_lower_func({32: "Custom32Mul"}), "Mul", "llvm", "myfloat") register_op( create_lower_func( { 32: "FloatToCustom32", } ), "FloatImm", "llvm", "myfloat", ) register_op( create_lower_func( { 32: "Custom32Div", } ), "Div", "llvm", "myfloat", ) register_op(create_lower_func({32: "Custom32Max"}), "Max", "llvm", "myfloat") register_op( create_lower_func({32: "Custom32Sqrt"}), "Call", "llvm", "myfloat", intrinsic_name="tir.sqrt", ) register_op( create_lower_func({32: "Custom32Exp"}), "Call", "llvm", "myfloat", intrinsic_name="tir.exp" ) register_op( create_lower_func({32: "Custom32Log"}), "Call", "llvm", "myfloat", intrinsic_name="tir.log" ) register_op( create_lower_func({32: "Custom32Sigmoid"}), "Call", "llvm", "myfloat", intrinsic_name="tir.sigmoid", ) register_op( create_lower_func({32: "Custom32Tanh"}), "Call", "llvm", "myfloat", intrinsic_name="tir.tanh", ) register_op(lower_ite, "Call", "llvm", "myfloat", intrinsic_name="tir.if_then_else") register_op( lower_call_pure_extern, "Call", "llvm", "myfloat", intrinsic_name="tir.call_pure_extern" ) register_min_func(create_min_lower_func({32: "MinCustom32"}, "myfloat"), "myfloat") def setup_posites2(): """Set up tests for posites2 Currently, this registers some custom datatypes using the Bring Your Own Datatypes framework. """ # To use datatype operations in an external library, you should first load # the library containing the datatype implementation: # CDLL("libposit.so", RTLD_GLOBAL) # In this case, the datatype library we are using is built right into TVM, # so we do not need to explicitly load any library. # You can pick a code for your datatype arbitrarily, as long as it is # greater than 128 and has not already been chosen. register("posites2", 132) register_op( create_lower_func( { (32, 32): "FloatToPosit32es2", (32, 16): "FloatToPosit16es2", (32, 8): "FloatToPosit8es2", } ), "Cast", "llvm", "float", "posites2", ) register_op( create_lower_func( { (32, 32): "Posit32es2ToFloat", (16, 32): "Posit16es2ToFloat", (8, 32): "Posit8es2ToFloat", } ), "Cast", "llvm", "posites2", "float", ) register_op( create_lower_func({32: "Posit32es2Add", 16: "Posit16es2Add", 8: "Posit8es2Add"}), "Add", "llvm", "posites2", ) register_op( create_lower_func({32: "Posit32es2Sub", 16: "Posit16es2Sub", 8: "Posit8es2Sub"}), "Sub", "llvm", "posites2", ) register_op( create_lower_func( {32: "FloatToPosit32es2", 16: "FloatToPosit16es2", 8: "FloatToPosit8es2"} ), "FloatImm", "llvm", "posites2", ) register_op( create_lower_func({32: "Posit32es2Mul", 16: "Posit16es2Mul", 8: "Posit8es2Mul"}), "Mul", "llvm", "posites2", ) register_op( create_lower_func({32: "Posit32es2Div", 16: "Posit16es2Div", 8: "Posit8es2Div"}), "Div", "llvm", "posites2", ) register_op( create_lower_func({32: "Posit32es2Max", 16: "Posit16es2Max", 8: "Posit8es2Max"}), "Max", "llvm", "posites2", ) register_op( create_lower_func({32: "Posit32es2Sqrt", 16: "Posit16es2Sqrt", 8: "Posit8es2Sqrt"}), "Call", "llvm", "posites2", intrinsic_name="tir.sqrt", ) register_op(lower_ite, "Call", "llvm", "posites2", intrinsic_name="tir.if_then_else") register_op( lower_call_pure_extern, "Call", "llvm", "posites2", intrinsic_name="tir.call_pure_extern" ) register_op( create_lower_func({32: "Posit32es2Exp", 16: "Posit16es2Exp", 8: "Posit8es2Exp"}), "Call", "llvm", "posites2", intrinsic_name="tir.exp", ) register_op( create_lower_func({32: "Posit32es2Log", 16: "Posit16es2Log", 8: "Posit8es2Log"}), "Call", "llvm", "posites2", intrinsic_name="tir.log", ) register_op( create_lower_func( {32: "Posit32es2Sigmoid", 16: "Posit16es2Sigmoid", 8: "Posit8es2Sigmoid"} ), "Call", "llvm", "posites2", intrinsic_name="tir.sigmoid", ) register_op( create_lower_func({32: "Posit32es2Tanh", 16: "Posit16es2Tanh", 8: "Posit8es2Tanh"}), "Call", "llvm", "posites2", intrinsic_name="tir.tanh", ) register_min_func( create_min_lower_func( {32: "MinPosit32es2", 16: "MinPosit16es2", 8: "MinPosit8es2"}, "posites2" ), "posites2", ) def run_ops(src_dtype, dst_dtype, rtol=1e-7, atol=1e-7): """Run the same op, but with two different datatypes""" # used for unary ops, first shape in binary ops shape1 = (5, 10, 5) # second shape for binary ops shape2 = (5,) def check_unary_op(op, src_dtype, dst_dtype, shape): t1 = relay.TensorType(shape, src_dtype) x = relay.var("x", t1) z = op(x) x_data = np.random.rand(*shape).astype(t1.dtype) module = tvm.IRModule.from_expr(relay.Function([x], z)) compare(module, (x_data,), src_dtype, dst_dtype, rtol, atol) # test unary ops for op in [ relay.nn.softmax, tvm.relay.log, tvm.relay.exp, tvm.relay.sqrt, tvm.relay.rsqrt, tvm.relay.sigmoid, tvm.relay.tanh, relay.nn.relu, relay.nn.batch_flatten, ]: check_unary_op(op, src_dtype, dst_dtype, shape1) # test unary ops over 4d data for op in [relay.nn.max_pool2d, relay.nn.avg_pool2d, relay.nn.global_avg_pool2d]: shape_2d = (3, 32, 32, 32) check_unary_op(op, src_dtype, dst_dtype, shape_2d) def check_binary_op(opfunc, src_dtype, dst_dtype): t1 = relay.TensorType(shape1, src_dtype) t2 = relay.TensorType(shape2, src_dtype) x = relay.var("x", t1) y = relay.var("y", t2) z = opfunc(x, y) x_data = np.random.rand(*shape1).astype(t1.dtype) y_data = np.random.rand(*shape2).astype(t2.dtype) module = tvm.IRModule.from_expr(relay.Function([x, y], z)) compare(module, (x_data, y_data), src_dtype, dst_dtype, rtol, atol) for op in [ relay.add, relay.subtract, relay.divide, relay.multiply, ]: check_binary_op(op, src_dtype, dst_dtype) # we would like to test tvm_if_then_else # but Relay.IfNode is not lowered to this intrinsic, # so to keep our tests consistent with relay, we decide to not unit test # Note: tvm_if_then_else is tested as part of the mobile_net model def run_model(get_workload, input, src_dtype, dst_dtype, rtol=1e-4, atol=1e-4): module, params = get_workload() # we don't generate random data here # because then the output data would all be around the same value compare(module, input, src_dtype, dst_dtype, rtol, atol, params) def run_conv2d(src_dtype, dst_dtype, rtol=1e-7, atol=1e-4): def run_test_conv2d( src_dtype, dst_dtype, scale, dshape, kshape, padding=(1, 1), groups=1, dilation=(1, 1), **attrs, ): x = relay.var("x", shape=dshape, dtype=src_dtype) w = relay.var("w", shape=kshape, dtype=src_dtype) y = relay.nn.conv2d(x, w, padding=padding, dilation=dilation, groups=groups, **attrs) module = tvm.IRModule.from_expr(relay.Function([x, w], y)) data = np.random.uniform(-scale, scale, size=dshape).astype(src_dtype) kernel = np.random.uniform(-scale, scale, size=kshape).astype(src_dtype) compare(module, (data, kernel), src_dtype, dst_dtype, rtol, atol) # depthwise conv2d dshape = (1, 32, 18, 18) kshape = (32, 1, 3, 3) run_test_conv2d( src_dtype, dst_dtype, 1, dshape, kshape, padding=(1, 1), channels=32, groups=32, kernel_size=(3, 3), ) # CUDA is disabled for 'direct' schedule: # https://github.com/dmlc/tvm/pull/3070#issuecomment-486597553 # group conv2d dshape = (1, 32, 18, 18) kshape = (32, 4, 3, 3) run_test_conv2d( src_dtype, dst_dtype, 1, dshape, kshape, padding=(1, 1), channels=32, groups=8, kernel_size=(3, 3), ) # also group conv2d dshape = (1, 32, 18, 18) kshape = (64, 1, 3, 3) run_test_conv2d( src_dtype, dst_dtype, 1, dshape, kshape, padding=(1, 1), channels=64, groups=32, kernel_size=(3, 3), ) # normal conv2d dshape = (1, 3, 224, 224) kshape = (10, 3, 3, 3) run_test_conv2d( src_dtype, dst_dtype, 1, dshape, kshape, padding=(1, 1), channels=10, kernel_size=(3, 3) ) # dilated conv2d dshape = (1, 3, 18, 18) kshape = (10, 3, 3, 3) run_test_conv2d( src_dtype, dst_dtype, 1, dshape, kshape, padding=(1, 1), channels=10, kernel_size=(3, 3), dilation=(3, 3), ) def run_batchnorm(src_dtype, dst_dtype, rtol=1e-6, atol=1e-6): shape = (3, 32, 32) t = relay.TensorType(shape, src_dtype) x = relay.var("x", t) bn = batch_norm_infer(data=x, epsilon=2e-5, scale=False, name="bn_x") f = relay.Function(relay.analysis.free_vars(bn), bn) x_data = np.random.rand(*shape).astype(t.dtype) module = tvm.IRModule.from_expr(f) zero_data = np.zeros((32), "float32") compare( module, (x_data, zero_data, zero_data, zero_data, zero_data), src_dtype, dst_dtype, rtol, atol, ) def test_myfloat(): try: setup_myfloat() except tvm._ffi.base.TVMError as e: if "float is already registered" not in str(e): # Ignore this specific error which can happen if this test runs twice within the same process raise e run_ops("float32", "custom[myfloat]32", rtol=1e-6, atol=1e-6) run_conv2d("float32", "custom[myfloat]32", rtol=1e-6, atol=1e-6) run_batchnorm("float32", "custom[myfloat]32", rtol=1e-6, atol=1e-6) # mxnet python package not available # run_model(get_mobilenet, (get_cat_image((224, 224)), ), # 'float32', # 'custom[myfloat]32') def _has_posit(): return tvm.support.libinfo()["USE_BYODT_POSIT"] == "ON" @pytest.mark.skipif(not _has_posit(), reason="compiled with USE_BYODT_POSIT flag OFF") def test_posites2(): setup_posites2() run_ops("float32", "custom[posites2]8", rtol=1, atol=1) run_ops("float32", "custom[posites2]16", rtol=0.01, atol=1) run_ops("float32", "custom[posites2]32", rtol=1e-6, atol=1e-6) run_conv2d("float32", "custom[posites2]8", rtol=1, atol=1) run_conv2d("float32", "custom[posites2]16", rtol=0.01, atol=1) run_conv2d("float32", "custom[posites2]32") run_batchnorm("float32", "custom[posites2]8", rtol=1, atol=1) run_batchnorm("float32", "custom[posites2]16", rtol=0.01, atol=1) run_batchnorm("float32", "custom[posites2]32", rtol=1e-4, atol=1e-4) # Expected posit8 might be faster, but it's not. # run_model(get_mobilenet, (get_cat_image((224, 224)), ), 'float32', 'custom[posit8]8') # run_model(get_mobilenet, (get_cat_image((224, 224)), ), 'float32', 'custom[posit32]32') # run_model(get_inception, (get_cat_image((229, 229)), ), 'float32', 'custom[posit32]32') # run_model(get_resnet, (get_cat_image((224, 224)), ), 'float32', 'custom[posit32]32') # can't run cifar-10 sizes because dimensions # don't match pretrained weights # runs on the order of minutes... # run_model(get_inception, (get_cat_image((229, 229)), ), # 'float32', # 'custom[posites2]32') # run_model(get_resnet, (get_cat_image((224, 224)), ), # 'float32', # 'custom[posites2]32') if __name__ == "__main__": tvm.testing.main()
https://github.com/zk-ml/tachikoma
tests/python/unittest/test_div_to_mul.py
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. import tvm from tvm import relay import pytest import numpy as np @pytest.mark.parametrize("dtype, rtol", [("float16", 1e-3), ("float32", 1e-7), ("float64", 1e-12)]) def test_div_to_mul(dtype, rtol): x = relay.var("x", relay.TensorType((), dtype)) y = relay.Constant(tvm.nd.array(np.array([1.5]).astype(dtype))) z = x / y mod = tvm.IRModule.from_expr(z) transformed = relay.transform.DivToMul()(mod) assert transformed["main"].body.op.name == "multiply" np.testing.assert_allclose(transformed["main"].body.args[1].data.numpy()[0], 1 / 1.5, rtol=rtol)
https://github.com/zk-ml/tachikoma
tests/python/unittest/test_filter_untracked.py
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. import os import shutil import subprocess import sys import tempfile def setup_git_repo(worktree=False): git_repo_dir = tempfile.mkdtemp() to_rm = [git_repo_dir] try: subprocess.check_output(["git", "init", "."], cwd=git_repo_dir) with open(f"{git_repo_dir}/committed", "w") as committed_f: committed_f.write("normal committed file\n") subprocess.check_output(["git", "add", "committed"], cwd=git_repo_dir) with open(f"{git_repo_dir}/committed-ignored", "w") as gitignore_f: gitignore_f.write("this file is gitignored, but committed already") subprocess.check_output(["git", "add", "committed-ignored"], cwd=git_repo_dir) with open(f"{git_repo_dir}/.gitignore", "w") as gitignore_f: gitignore_f.write("ignored\n" "committed-ignored\n") subprocess.check_output(["git", "add", ".gitignore"], cwd=git_repo_dir) # NOTE: explicitly set the author so this test passes in the CI. subprocess.check_output( [ "git", "-c", "user.name=Unit Test", "-c", "user.email=unit.test@testing.tvm.ai", "commit", "-m", "initial commit", ], cwd=git_repo_dir, ) if worktree: worktree_dir = tempfile.mkdtemp() to_rm.append(worktree_dir) subprocess.check_output(["git", "worktree", "add", worktree_dir], cwd=git_repo_dir) git_repo_dir = worktree_dir with open(f"{git_repo_dir}/ignored", "w") as gitignore_f: gitignore_f.write("this file is gitignored") with open(f"{git_repo_dir}/added-to-index", "w") as added_f: added_f.write("only added to git index\n") subprocess.check_output(["git", "add", "added-to-index"], cwd=git_repo_dir) with open(f"{git_repo_dir}/ignored-added-to-index", "w") as ignored_f: ignored_f.write("this file is gitignored but in the index already\n") subprocess.check_output(["git", "add", "-f", "ignored-added-to-index"], cwd=git_repo_dir) with open(f"{git_repo_dir}/untracked", "w") as untracked_f: untracked_f.write("this file is untracked\n") os.mkdir(f"{git_repo_dir}/subdir") with open(f"{git_repo_dir}/subdir/untracked", "w") as untracked_f: untracked_f.write("this file is untracked\n") with open(f"{git_repo_dir}/subdir/untracked2", "w") as untracked_f: untracked_f.write("this file is also untracked\n") return git_repo_dir, to_rm except Exception: for rm_dir in to_rm: shutil.rmtree(rm_dir) raise def run_test(repo_path, passed_files, filtered_files): test_input = ( "\n".join( passed_files + filtered_files + [f"./{f}" for f in passed_files] + [f"./{f}" for f in filtered_files] ) + "\n" ) test_script_dir = f"{repo_path}/test-script-dir" os.mkdir(test_script_dir) filter_script_path = f"{test_script_dir}/filter_untracked.py" test_script_dirname = os.path.dirname(__file__) or os.getcwd() shutil.copy( os.path.realpath(f"{test_script_dirname}/../../lint/filter_untracked.py"), filter_script_path, ) filter_proc = subprocess.Popen( [sys.executable, filter_script_path], cwd=repo_path, stdin=subprocess.PIPE, stdout=subprocess.PIPE, encoding="utf-8", ) filter_output, _ = filter_proc.communicate(test_input) filter_output_lines = [l for l in filter_output.split("\n") if l] for pass_f in passed_files: assert ( pass_f in filter_output_lines ), f"expected in filter output: {pass_f}\filter output: {filter_output}" assert ( f"./{pass_f}" in filter_output_lines ), f"expected in filter output: ./{pass_f}\filter output: {filter_output}" for filter_f in filtered_files: assert ( filter_f not in filter_output_lines ), f"expected not in filter output: {filter_f}\nfilter_output: {filter_output}" assert ( f"./{filter_f}" not in filter_output_lines ), f"expected not in filter output: ./{filter_f}\nfilter_output: {filter_output}" assert len(filter_output_lines) == 2 * len( passed_files ), f"expected {len(filter_output_lines)} == 2 * {len(passed_files)}" def test_filter_untracked(): repo_path, to_rm = setup_git_repo() try: passed_files = [ "committed", "committed-ignored", "added-to-index", "ignored-added-to-index", ] filtered_files = [ "ignored", "untracked", "subdir/untracked", "subdir/untracked2", ] run_test(repo_path, passed_files, filtered_files) finally: for rm_dir in to_rm: shutil.rmtree(rm_dir) def test_worktree(): repo_path, to_rm = setup_git_repo(worktree=True) try: passed_files = [ "committed", "committed-ignored", "added-to-index", "ignored-added-to-index", ] filtered_files = [ "ignored", "untracked", "subdir/untracked", "subdir/untracked2", ".git", ] run_test(repo_path, passed_files, filtered_files) finally: for rm_dir in to_rm: shutil.rmtree(rm_dir) if __name__ == "__main__": test_filter_untracked() test_worktree()
https://github.com/zk-ml/tachikoma
tests/python/unittest/test_format_si_prefix.py
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. from numpy import isclose import random from tvm.autotvm import utils SI_PREFIXES = "yzafpn\xb5m kMGTPEZY" def test_format_si_prefix(): # test float conversion assert utils.format_si_prefix(1024, "k") == 1.024 for i, prefix in enumerate(SI_PREFIXES): integer, decimal = random.randint(0, 1000), random.randint(0, 1000) exp = -24 + 3 * i # 0th prefix (yocto) is 10^-24 number = integer * (10**exp) + decimal * (10 ** (exp - 3)) expected = integer + decimal / 1000 assert isclose(utils.format_si_prefix(number, prefix), expected) assert utils.format_si_prefix(0, "y") == 0 if __name__ == "__main__": test_format_si_prefix()
https://github.com/zk-ml/tachikoma
tests/python/unittest/test_gen_requirements.py
#!/usr/bin/env python3 # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. """Tests for gen_requirements, found in python/.""" import collections import contextlib import os import sys import tvm import tvm.testing import pytest # Insert the parent dir to python/tvm into the import path, so that gen_requirements may be # imported. sys.path.insert(0, os.path.dirname(tvm.__file__)) try: import gen_requirements finally: sys.path.pop(0) @contextlib.contextmanager def patch(obj, **kw): old = {} for prop_name, new in kw.items(): old[prop_name] = getattr(obj, prop_name) setattr(obj, prop_name, new) yield for prop_name, value in old.items(): setattr(obj, prop_name, value) PROBLEM_REQUIREMENTS = [ ("extras-pre-core", ("", ["foo", 123])), # entry before core (456, ("", ["foo", "bar"])), # invalid extras name, deps should not be processed ("core", ("", ["foo"])), # ordinary core entry. ("wrong-description-type", (None, ["foo"])), # wrong description type ("bad-value", None), # value field is not a 2-tuple ("bad-value-2", ("", ["foo"], 34)), # value field is not a 2-tuple ("invalid", ("", ["qux"])), # duplicate invalid entry, all items valid. ("extras-foo", ("", ["bar", "baz"])), # ordinary extras entry. ("invalid", ("", ["baz", None, 123])), # valid extra name, invalid deps. ("unsorted", ("", ["qux", "bar", "foo"])), # deps out of order ("versioned_dep", ("", ["baz==1.2", "foo==^2.0", "buz<3", "bar>4"])), ("duplicate_dep", ("", ["buz", "buz", "foo"])), # duplicate listed dependency ("dev", ("", ["baz", "qux"])), # ordinary dev entry. ("extras-post-dev", ("", ["bar", "buzz"])), # entry after dev ] def test_validate_requirements(): with patch(gen_requirements, REQUIREMENTS_BY_PIECE=None): assert gen_requirements.validate_requirements_by_piece() == [ "must be list or tuple, see None" ] with patch(gen_requirements, REQUIREMENTS_BY_PIECE=PROBLEM_REQUIREMENTS): problems = gen_requirements.validate_requirements_by_piece() assert problems == [ 'piece extras-pre-core: must list after "core" (core must be first)', "piece extras-pre-core: deps should be a list of strings, got ['foo', 123]", "piece 456: must be str", "piece wrong-description-type: description should be a string, got None", ( 'piece bad-value: should be formatted like ("bad-value", ("<requirements.txt ' 'comment>", ["dep1", "dep2", ...])). got: None' ), ( 'piece bad-value-2: should be formatted like ("bad-value-2", ' '("<requirements.txt comment>", ["dep1", "dep2", ...])). got: (\'\', ' "['foo'], 34)" ), "piece invalid: listed twice", "piece invalid: deps should be a list of strings, got ['baz', None, 123]", "piece unsorted: deps must be sorted. Correct order:\n ['bar', 'foo', 'qux']", "piece versioned_dep: deps must be sorted. Correct order:\n ['bar>4', 'baz==1.2', 'buz<3', 'foo==^2.0']", "piece versioned_dep: dependency baz==1.2 should not specify a version. Add it to CONSTRAINTS instead.", "piece versioned_dep: dependency foo==^2.0 should not specify a version. Add it to CONSTRAINTS instead.", "piece versioned_dep: dependency buz<3 should not specify a version. Add it to CONSTRAINTS instead.", "piece versioned_dep: dependency bar>4 should not specify a version. Add it to CONSTRAINTS instead.", "piece duplicate_dep: dependency buz listed twice", 'piece extras-post-dev: must list before "dev" (dev must be last)', 'pieces other than "core" and "dev" must appear in alphabetical order: ' "['bad-value', 'bad-value-2', 'duplicate_dep', 'extras-foo', 'extras-post-dev', " "'extras-pre-core', 'invalid', 'invalid', 'unsorted', 'versioned_dep', " "'wrong-description-type']", ] TEST_REQUIREMENTS_BY_PIECE = ( ("core", ("core tvm requirements", ("bar", "foo", "non-constrained"))), ("extra-one", ("requirements for one feature", ("baz", "qux"))), ("extra-two", ("requirements for two feature", ("buz", "qux", "semver-minor", "semver-patch"))), ("dev", ("requirements for dev", ("buz", "oof", "rab"))), ) def test_validate_constraints(): with patch( gen_requirements, REQUIREMENTS_BY_PIECE=TEST_REQUIREMENTS_BY_PIECE, CONSTRAINTS=( ("unlisted", "~=3"), ("double-specified", "<2"), ( "double-specified", "==3", ), ("bad-constraint", "1.2.0"), ("bad-semver-constraint", "i don't match the regex :P"), ("alpha-semver-constraint", "^foo.bar.23"), ), ): problems = gen_requirements.validate_constraints() assert problems == [ "unlisted: not specified in REQUIREMENTS_BY_PIECE", "double-specified: not specified in REQUIREMENTS_BY_PIECE", "double-specified: specified twice", "double-specified: not specified in REQUIREMENTS_BY_PIECE", "bad-constraint: not specified in REQUIREMENTS_BY_PIECE", 'bad-constraint: constraint "1.2.0" does not look like a valid constraint', "bad-semver-constraint: not specified in REQUIREMENTS_BY_PIECE", 'bad-semver-constraint: constraint "i don\'t match the regex :P" does not look like a valid constraint', "alpha-semver-constraint: not specified in REQUIREMENTS_BY_PIECE", "alpha-semver-constraint: invalid semver constraint ^foo.bar.23", "CONSTRAINTS entries should be in this sorted order: ['alpha-semver-constraint', 'bad-constraint', 'bad-semver-constraint', 'double-specified', 'double-specified', 'unlisted']", ] TEST_CONSTRAINTS = ( ("bar", "==1.0"), ("baz", ">2.3"), ("buz", "^1.3.0"), ("non-constrained", None), # Support a comment. ("oof", "==0.3.4"), ("qux", "~=1.2.4"), ("semver-minor", "^0.2.2-patch2.post3+buildmeta"), # Ensure prerelease and buildmeta preserved. ("semver-patch", "^0.0.2+bm"), # Ensure postrelease preserved. ) def test_join_requirements(): with patch( gen_requirements, REQUIREMENTS_BY_PIECE=TEST_REQUIREMENTS_BY_PIECE, CONSTRAINTS=TEST_CONSTRAINTS, ): requirements = gen_requirements.join_requirements() assert requirements == collections.OrderedDict( [ ("core", ("core tvm requirements", ["bar==1.0", "foo", "non-constrained"])), ("extra-one", ("requirements for one feature", ["baz>2.3", "qux~=1.2.4"])), ( "extra-two", ( "requirements for two feature", [ "buz>=1.3.0,<2.0.0", "qux~=1.2.4", "semver-minor>=0.2.2-patch2.post3+buildmeta,<0.3.0", "semver-patch>=0.0.2+bm,<0.0.3", ], ), ), ("dev", ("requirements for dev", ["buz>=1.3.0,<2.0.0", "oof==0.3.4", "rab"])), ( "all-prod", ( "Combined dependencies for all TVM pieces, excluding dev", [ "bar==1.0", "baz>2.3", "buz>=1.3.0,<2.0.0", "foo", "non-constrained", "qux~=1.2.4", "semver-minor>=0.2.2-patch2.post3+buildmeta,<0.3.0", "semver-patch>=0.0.2+bm,<0.0.3", ], ), ), ] ) def test_semver(): problems = [] assert gen_requirements.parse_semver("C", "^1.2.0", problems) == (["1", "2", "0"], 0, 1) assert problems == [] assert gen_requirements.parse_semver("C", "^0.2.0", problems) == (["0", "2", "0"], 1, 2) assert problems == [] assert gen_requirements.parse_semver("C", "^0.0.0", problems) == (["0", "0", "0"], 0, 0) assert problems == [] assert gen_requirements.parse_semver("C", "^0.a.0", problems) == ([], 0, 0) assert problems == ["C: invalid semver constraint ^0.a.0"] if __name__ == "__main__": tvm.testing.main()
https://github.com/zk-ml/tachikoma
tests/python/unittest/test_index_map.py
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. import numpy as np import pytest import tvm import tvm.testing from tvm.ir import assert_structural_equal from tvm.tir import IndexMap, IntImm, floordiv, floormod from tvm.runtime import const def assert_equal_index_map(map1: IndexMap, map2: IndexMap) -> None: iters_1 = map1.map_indices(map2.initial_indices) iters_2 = map2.final_indices assert len(iters_1) == len(iters_2) analyzer = tvm.arith.Analyzer() for iter1, iter2 in zip(iters_1, iters_2): assert analyzer.can_prove_equal(iter1, iter2) def test_index_mapping(): index_map = IndexMap.from_func(lambda i: [i // 4, i % 4]) assert_structural_equal(index_map.map_indices([0]), [0, 0]) assert_structural_equal(index_map.map_indices([3]), [0, 3]) assert_structural_equal(index_map.map_indices([4]), [1, 0]) assert_structural_equal(index_map.map_indices([42]), [10, 2]) assert_structural_equal( index_map.map_indices([const(42, "int64")]), [const(10, "int64"), const(2, "int64")] ) def test_shape_mapping(): index_map = IndexMap.from_func(lambda i: [i // 4, i % 4]) assert_structural_equal(index_map.map_shape([4]), [1, 4]) assert_structural_equal(index_map.map_shape([16]), [4, 4]) assert_structural_equal(index_map.map_shape([14]), [4, 4]) assert_structural_equal( index_map.map_shape([const(16, "int64")]), [const(4, "int64"), const(4, "int64")] ) assert_structural_equal( index_map.map_shape([const(14, "int64")]), [const(4, "int64"), const(4, "int64")] ) def test_inverse(): index_map = IndexMap.from_func(lambda i: [i // 4, i % 4]) expected_inverse = IndexMap.from_func(lambda i, j: [4 * i + j]) assert index_map.inverse([16]).is_equivalent_to(expected_inverse) def test_nonbijective_inverse_gives_error(): index_map = IndexMap.from_func(lambda i: [i // 4, i % 4]) with pytest.raises(tvm.TVMError): index_map.inverse([14]) dynamic_N = tvm.tir.Var("N", "int32") padding_test_case = tvm.testing.parameter( by_dict={ "no_padding": dict( forward=lambda i: [i // 4, i % 4], inverse=lambda i, j: [4 * i + j], pre_shape=[16], post_shape=[4, 4], padding=lambda i, j: tvm.runtime.convert(False), ), "right_padding": dict( forward=lambda i: [i // 4, i % 4], inverse=lambda i, j: [4 * i + j], pre_shape=[15], post_shape=[4, 4], padding=lambda i, j: tvm.tir.And(i == 3, tvm.runtime.convert(3) == j), ), "left_padding": dict( forward=lambda i: [(i + 1) // 4, (i + 1) % 4], inverse=lambda i, j: [4 * i + j - 1], pre_shape=[15], post_shape=[4, 4], padding=lambda i, j: tvm.tir.And(i == 0, j < 1), ), "left_and_right_padding": dict( forward=lambda i: [(i + 1) // 4, (i + 1) % 4], inverse=lambda i, j: [4 * i + j - 1], pre_shape=[14], post_shape=[4, 4], padding=lambda i, j: tvm.tir.Or( tvm.tir.And(i == 0, j < 1), tvm.tir.And(i == 3, tvm.runtime.convert(3) == j), ), ), "dynamic_size": dict( forward=lambda i: [i // 4, i % 4], inverse=lambda i, j: [4 * i + j], pre_shape=[dynamic_N], post_shape=[(dynamic_N - dynamic_N % (-4)) // 4, 4], padding=lambda i, j: tvm.tir.And( dynamic_N % (-4) != 0, tvm.tir.And(i == dynamic_N // 4, j >= dynamic_N % 4), ), ), "2d_padding": dict( forward=lambda i, j: [(i + 1) // 4, (j + 5) // 8, (i + 1) % 4, (j + 5) % 8], inverse=lambda i_outer, j_outer, i_inner, j_inner: [ 4 * i_outer + i_inner - 1, 8 * j_outer + j_inner - 5, ], pre_shape=[14, 31], post_shape=[ 4, # ceildiv(left_pad + i.extent, 4) = ceildiv(1 + 14, 4) = 4 5, # ceildiv(left_pad + j.extent, 8) = ceildiv(5 + 31, 8) = 5 4, # Range of iter%4 8, # Range of iter%8 ], padding=lambda i_outer, j_outer, i_inner, j_inner: tvm.tir.Or( tvm.tir.Or( tvm.tir.And(i_outer == 0, i_inner < 1), tvm.tir.And(i_outer == 3, tvm.runtime.convert(3) == i_inner), ), tvm.tir.Or( tvm.tir.And(j_outer == 0, j_inner < 5), tvm.tir.And(j_outer == 4, j_inner >= 4), ), ), ), "multiple_right_padding": dict( forward=lambda i: [i // 32, (i // 4) % 8, i % 4], inverse=lambda i, j, k: [32 * i + 4 * j + k], pre_shape=[116], post_shape=[4, 8, 4], padding=lambda i, j, k: tvm.tir.And(i == 3, 4 * j + k >= 20), ), "multiple_right_padding_transpose": dict( forward=lambda i: [(i // 4) % 8, i // 32, i % 4], inverse=lambda j, i, k: [32 * i + 4 * j + k], pre_shape=[116], post_shape=[8, 4, 4], padding=lambda j, i, k: tvm.tir.And(i == 3, 4 * j + k >= 20), ), "multiple_left_padding": dict( forward=lambda i: [(i + 5) // 32, ((i + 5) // 4) % 8, (i + 5) % 4], inverse=lambda i, j, k: [32 * i + 4 * j + k - 5], pre_shape=[123], post_shape=[4, 8, 4], padding=lambda i, j, k: tvm.tir.And(i == 0, j * 4 + k < 5), ), "multiple_left_padding_with_transpose": dict( forward=lambda i: [((i + 5) // 4) % 8, (i + 5) // 32, (i + 5) % 4], inverse=lambda j, i, k: [32 * i + 4 * j + k - 5], pre_shape=[123], post_shape=[8, 4, 4], padding=lambda j, i, k: tvm.tir.And(i == 0, j * 4 + k < 5), ), "outer_loop_extent_one": dict( forward=lambda i: [i // 4, i % 4], inverse=lambda i, j: [i * 4 + j], pre_shape=[3], post_shape=[1, 4], padding=lambda i, j: tvm.runtime.convert(3) == j, ), } ) def test_nonsurjective_inverse(padding_test_case): index_map = IndexMap.from_func(padding_test_case["forward"]) inverse, padding_predicate = index_map.non_surjective_inverse(padding_test_case["pre_shape"]) expected_inverse = IndexMap.from_func(padding_test_case["inverse"]) assert inverse.is_equivalent_to(expected_inverse) post_shape = index_map.map_shape(padding_test_case["pre_shape"]) tvm.ir.assert_structural_equal(post_shape, padding_test_case["post_shape"]) expected_predicate = padding_test_case["padding"](*inverse.initial_indices) # Can't use analyzer.can_prove_equal, because it can't simplify # expressions like `(4*i+j >= 14) - (4*i+j >= 14)`. analyzer = tvm.arith.Analyzer() expected_predicate = analyzer.simplify(expected_predicate) padding_predicate = analyzer.simplify(padding_predicate) tvm.ir.assert_structural_equal(padding_predicate, expected_predicate) def test_index_map_inverse_no_iter(): def input_example(i0, i1, i2, i3): j0 = floordiv(i3, 32) j1 = floordiv(i2, 2) j2 = floormod(i2, 2) j3 = floormod(i3, 32) return j0, j1, j2, j3 def expected_inverse(i0, i1, i2, i3): return IntImm("int32", 0), IntImm("int32", 0), i2 + i1 * 2, i3 + i0 * 32 index_map = IndexMap.from_func(input_example) inverse_map = index_map.inverse([1, 1, 64, 64]) expected_map = IndexMap.from_func(expected_inverse) assert expected_map.is_equivalent_to(inverse_map) def test_map_ndarray(): index_map = IndexMap.from_func(lambda i: [i // 4, i % 4]) inp = np.arange(16).astype("int8") out = index_map.map_ndarray(tvm.nd.array(inp)).numpy() ref = np.zeros(out.shape).astype("int8") for i in range(16): ref[i // 4, i % 4] = inp[i] np.testing.assert_equal(ref, out) index_map = IndexMap.from_func(lambda i0, i1, i2, i3: (i3, i0, i1, i2)) inp = np.random.randn(10, 10, 10, 10).astype("float16") out = index_map.map_ndarray(tvm.nd.array(inp)).numpy() ref = np.transpose(inp, (3, 0, 1, 2)) np.testing.assert_equal(ref, out) index_map = IndexMap.from_func( lambda i0, i1, i2, i3: ( floordiv(i3, 32), i0, floordiv(i2, 8), floordiv(floormod(i3, 32), 16), i1, floormod(i2, 8), floormod(i3, 16), ) ) kH = kW = 3 I = 64 O = 64 inp = np.random.randn(kH, kW, I, O).astype("float32") arr = tvm.nd.array(inp) out = index_map.map_ndarray(arr).numpy() ref = np.zeros(out.shape).astype("float32") for i0 in range(kH): for i1 in range(kW): for i2 in range(I): for i3 in range(O): v = inp[i0, i1, i2, i3] ref[i3 // 32, i0, i2 // 8, (i3 % 32) // 16, i1, i2 % 8, i3 % 16] = v np.testing.assert_equal(ref, out) inverse_map = index_map.inverse(inp.shape) np.testing.assert_equal(inverse_map.map_ndarray(index_map.map_ndarray(arr)).numpy(), inp) if __name__ == "__main__": tvm.testing.main()
https://github.com/zk-ml/tachikoma
tests/python/unittest/test_ir_attrs.py
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. import tvm import pytest import tvm.ir._ffi_api def test_make_attrs(): with pytest.raises(AttributeError): x = tvm.ir.make_node("attrs.TestAttrs", unknown_key=1, name="xx") with pytest.raises(AttributeError): x = tvm.ir.make_node("attrs.TestAttrs", axis=100, name="xx") x = tvm.ir.make_node("attrs.TestAttrs", name="xx", padding=(3, 4)) assert x.name == "xx" assert x.padding[0].value == 3 assert x.padding[1].value == 4 assert x.axis == 10 def test_dict_attrs(): dattr = tvm.ir.make_node("DictAttrs", x=1, y=10, name="xyz", padding=(0, 0)) assert dattr.x.value == 1 datrr = tvm.ir.load_json(tvm.ir.save_json(dattr)) assert dattr.name == "xyz" assert isinstance(dattr, tvm.ir.DictAttrs) assert "name" in dattr assert dattr["x"].value == 1 assert len(dattr) == 4 assert len([x for x in dattr.keys()]) == 4 assert len(dattr.items()) == 4 def test_attrs_equal(): dattr0 = tvm.ir.make_node("DictAttrs", x=1, y=[10, 20]) dattr1 = tvm.ir.make_node("DictAttrs", y=[10, 20], x=1) dattr2 = tvm.ir.make_node("DictAttrs", x=1, y=None) assert tvm.ir.structural_equal(dattr0, dattr1) assert not tvm.ir.structural_equal(dattr0, dattr2) assert not tvm.ir.structural_equal({"x": 1}, tvm.runtime.convert(1)) assert not tvm.ir.structural_equal([1, 2], tvm.runtime.convert(1)) if __name__ == "__main__": test_make_attrs() test_dict_attrs() test_attrs_equal()
https://github.com/zk-ml/tachikoma
tests/python/unittest/test_ir_container.py
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. import pytest import tvm from tvm import te import numpy as np def test_array(): a = tvm.runtime.convert([1, 2, 3]) assert len(a) == 3 assert a[-1].value == 3 a_slice = a[-3:-1] assert (a_slice[0].value, a_slice[1].value) == (1, 2) def test_array_save_load_json(): a = tvm.runtime.convert([1, 2, 3]) json_str = tvm.ir.save_json(a) a_loaded = tvm.ir.load_json(json_str) assert a_loaded[1].value == 2 def test_dir_array(): a = tvm.runtime.convert([1, 2, 3]) assert dir(a) def test_getattr_array(): a = tvm.runtime.convert([1, 2, 3]) assert getattr(a, "type_key") == "Array" assert not hasattr(a, "test_key") def test_map(): a = te.var("a") b = te.var("b") amap = tvm.runtime.convert({a: 2, b: 3}) assert a in amap assert len(amap) == 2 dd = dict(amap.items()) assert a in dd assert b in dd assert a + 1 not in amap assert {x for x in amap} == {a, b} assert set(amap.keys()) == {a, b} assert set(amap.values()) == {2, 3} def test_str_map(): amap = tvm.runtime.convert({"a": 2, "b": 3}) assert "a" in amap assert len(amap) == 2 dd = dict(amap.items()) assert amap["a"].value == 2 assert "a" in dd assert "b" in dd def test_map_save_load_json(): a = te.var("a") b = te.var("b") amap = tvm.runtime.convert({a: 2, b: 3}) json_str = tvm.ir.save_json(amap) amap = tvm.ir.load_json(json_str) assert len(amap) == 2 dd = {kv[0].name: kv[1].value for kv in amap.items()} assert dd == {"a": 2, "b": 3} def test_dir_map(): a = te.var("a") b = te.var("b") amap = tvm.runtime.convert({a: 2, b: 3}) assert dir(amap) def test_getattr_map(): a = te.var("a") b = te.var("b") amap = tvm.runtime.convert({a: 2, b: 3}) assert getattr(amap, "type_key") == "Map" assert not hasattr(amap, "test_key") def test_in_container(): arr = tvm.runtime.convert(["a", "b", "c"]) assert "a" in arr assert tvm.tir.StringImm("a") in arr assert "d" not in arr def test_ndarray_container(): x = tvm.nd.array([1, 2, 3]) arr = tvm.runtime.convert([x, x]) assert arr[0].same_as(x) assert arr[1].same_as(x) assert isinstance(arr[0], tvm.nd.NDArray) if __name__ == "__main__": pytest.main([__file__])
https://github.com/zk-ml/tachikoma
tests/python/unittest/test_ir_type.py
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. """Test type nodes in the IR""" import tvm def check_json_roundtrip(node): json_str = tvm.ir.save_json(node) back = tvm.ir.load_json(json_str) assert tvm.ir.structural_equal(back, node, map_free_vars=True) def test_prim_type(): x = tvm.ir.PrimType("int32") assert isinstance(x, tvm.ir.PrimType) assert x.dtype == "int32" def test_tensor_type_bad_constructor(): try: x = tvm.ir.TensorType("xx", "xx") except tvm.error.TVMError: pass def test_tensor_type(): shape = tvm.runtime.convert([1, 2, 3]) dtype = "float32" tt = tvm.ir.TensorType(shape, dtype) assert tt.dtype == dtype assert tt.shape == shape assert tt.span == None str(tt) check_json_roundtrip(tt) def test_type_param(): tp = tvm.ir.TypeVar("name", tvm.ir.TypeKind.Type) assert tp.kind == tvm.ir.TypeKind.Type # assert tp.span # TODO allow us to set span str(tp) check_json_roundtrip(tp) def test_func_type(): type_params = tvm.runtime.convert([]) type_constraints = tvm.runtime.convert([]) # TODO: fill me in arg_types = tvm.runtime.convert([]) ret_type = tvm.ir.TensorType((1, 2, 3), "float32") tf = tvm.ir.FuncType(arg_types, ret_type, type_params, type_constraints) assert tf.type_params == type_params assert tf.type_constraints == type_constraints assert tf.arg_types == arg_types assert tf.ret_type == ret_type assert tf.span == None # TODO make sure we can set span str(tf) check_json_roundtrip(tf) def test_tuple_type(): tp = tvm.ir.TypeVar("tp", tvm.ir.TypeKind.Type) tf = tvm.ir.FuncType([], tvm.ir.TupleType([]), [], []) tt = tvm.ir.TensorType(tvm.runtime.convert([1, 2, 3]), "float32") fields = tvm.runtime.convert([tp, tf, tt]) tup_ty = tvm.ir.TupleType(fields) assert tup_ty.fields == fields str(tup_ty) check_json_roundtrip(tup_ty) def test_type_relation(): tp = tvm.ir.TypeVar("tp", tvm.ir.TypeKind.Type) tf = tvm.ir.FuncType([], None, [], []) tt = tvm.ir.TensorType(tvm.runtime.convert([1, 2, 3]), "float32") args = tvm.runtime.convert([tp, tf, tt]) num_inputs = 2 func = tvm.ir.EnvFunc.get("tvm.relay.type_relation.Broadcast") attrs = tvm.ir.make_node("attrs.TestAttrs", name="attr", padding=(3, 4)) tr = tvm.ir.TypeRelation(func, args, num_inputs, attrs) assert tr.args == args assert tr.num_inputs == num_inputs str(tr) check_json_roundtrip(tr) if __name__ == "__main__": test_tensor_type_bad_constructor() test_tensor_type() test_type_param() test_func_type() test_tuple_type() test_type_relation()
https://github.com/zk-ml/tachikoma
tests/python/unittest/test_link_params.py
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. import collections import ctypes import json import os import re from contextlib import redirect_stderr from io import StringIO import numpy as np import tvm import tvm.relay import tvm.testing from tvm import meta_schedule as ms from tvm import relay from tvm.contrib import utils from tvm.relay.backend import Executor, Runtime INPUT_SHAPE = (1, 3, 16, 16) KERNEL_SHAPE = (3, 3, 3, 3) # The data types that are linkable. linkable_dtype = tvm.testing.parameter( *( [f"uint{b}" for b in (8, 16, 32, 64)] + [f"int{b}" for b in (8, 16, 32, 64)] + ["float32", "float64"] ) ) def dtype_info(dtype): """Lookup numpy type info for the given string dtype (of linkable_dtype params above).""" if "int" in dtype: return np.iinfo(getattr(np, dtype)) else: return np.finfo(getattr(np, dtype)) # Note: for debugging, set this to an integer (i.e. 1.0). Then all "random" tensors will become # predictable RANDOM_TENSOR_START = None def _make_random_tensor(dtype, shape): """Create a random test tensor with given shape and dtype.""" global RAND_SEED if RANDOM_TENSOR_START is not None: to_return = np.arange( RANDOM_TENSOR_START, RANDOM_TENSOR_START + np.prod(shape), dtype=dtype ).reshape(shape) RAND_SEED += np.prod(shape) return to_return dinfo = dtype_info(dtype) if "int" in dtype: return np.random.randint(dinfo.min, dinfo.max, shape, dtype=dtype) else: to_return = np.random.uniform(0, dinfo.max, shape).astype(dtype) np.reshape(to_return, np.prod(shape))[::2] *= -1 return to_return def _lookup_sid(graph, name): """Lookup the storage id of a named parameter. Arguments --------- graph : dict Parsed JSON graph. name : str Name of the tensor parameter to lookup. Returns ------- int : The storage_id of the parameter. """ num_outputs_seen = 0 for i, n in enumerate(graph["nodes"]): if n["name"] == name: print("sid", name, graph["attrs"]["storage_id"][1], num_outputs_seen) return graph["attrs"]["storage_id"][1][num_outputs_seen] else: if "attrs" in n and "num_outputs" in n["attrs"]: num_outputs_seen += int(n["attrs"]["num_outputs"]) else: num_outputs_seen += 1 raise KeyError(f"no such param: {name}") def _get_ctypes_dtype(dt): """Return a ctypes c_* datatype given a string data type.""" if "int" in dt: return getattr(ctypes, f"c_{dt}") elif dt == "float32": return ctypes.c_float elif dt == "float64": return ctypes.c_double else: assert False, f"unknown dtype: {dt}" def _verify_linked_param(dtype, lib, mod, graph, name): """Directly read memory from the linked library to verify the linked parameter is correct.""" sid = _lookup_sid(graph, name) # NOTE: query_imports=True because when loading a module from disk (i.e. for C backend), # a GraphExecutorFactory module is created instead of the module itself. param_ptr = mod.get_function("_lookup_linked_param", True)(sid) gen_param = lib.params[name] arr_data = (_get_ctypes_dtype(dtype) * np.prod(gen_param.shape)).from_address(param_ptr.value) arr = np.ndarray(shape=gen_param.shape, dtype=gen_param.dtype, buffer=arr_data, order="C") if "int" in gen_param.dtype: np.testing.assert_equal(gen_param.numpy(), arr) else: np.testing.assert_allclose(gen_param.numpy(), arr) return dtype == gen_param.dtype def _make_mod_and_params(dtype): """Create a Relay module and parameters to test the given datatype.""" param_decls = collections.OrderedDict() param_init = {} def _add_decl(name, dtype): param_decls[name] = f"%{name} : Tensor[{KERNEL_SHAPE}, {dtype}]" param_init[name] = _make_random_tensor(dtype, KERNEL_SHAPE) # Add several parameters so that the number of parameters _add_decl(f"{dtype}_a", dtype) _add_decl(f"{dtype}_b", dtype) mod_lines = [ '#[version = "0.0.5"]', f"def @main(%rand_input : Tensor[{INPUT_SHAPE}, {dtype}], { ', '.join(param_decls.values()) } ) {{", # This program ensures that GraphPlanMemory alternates between the same two storage IDs for a # while. In doing this, it ensures that param %{dtype}_b will be placed into the graph at an # index unequal to its storage_id. This ensures that GraphExecutorCodegen encodes the storage_id # and not the parameter index into the graph. ( f' %0 = nn.conv2d(%rand_input, %{dtype}_a, data_layout="NCHW", kernel_layout="OIHW", ' f'kernel_size=[3, 3], out_dtype="{dtype}");' ), ( f' %1 = nn.conv2d(%0, %{dtype}_a, data_layout="NCHW", kernel_layout="OIHW", ' f'kernel_size=[3, 3], out_dtype="{dtype}");' ), ( f' %2 = nn.conv2d(%1, %{dtype}_a, data_layout="NCHW", kernel_layout="OIHW", ' f'kernel_size=[3, 3], out_dtype="{dtype}");' ), ( f' %3 = nn.conv2d(%2, %{dtype}_b, data_layout="NCHW", kernel_layout="OIHW", ' f'kernel_size=[3, 3], out_dtype="{dtype}");' ), " %3", "}", ] mod = tvm.parser.fromtext("\n".join(mod_lines)) return mod, param_init @tvm.testing.requires_llvm def test_llvm_link_params(linkable_dtype): ir_mod, param_init = _make_mod_and_params(linkable_dtype) rand_input = _make_random_tensor(linkable_dtype, INPUT_SHAPE) main_func = ir_mod["main"] target = "llvm" runtime = Runtime("crt", {"system-lib": True}) executor = Executor("graph", {"link-params": True}) with tvm.transform.PassContext(opt_level=3): lib = tvm.relay.build(ir_mod, target, runtime=runtime, executor=executor, params=param_init) # NOTE: Need to export_library() and load_library() to link all the Module(llvm, ...) # against one another. temp_dir = utils.TempDirectory() export_file = temp_dir / "lib.so" lib.lib.export_library(export_file) mod = tvm.runtime.load_module(export_file) assert len(lib.params.keys()) == 0 # NOTE: params became tir.constants assert mod.get_function("TVMSystemLibEntryPoint") != None graph = json.loads(lib.graph_json) for p in lib.params: _verify_linked_param(linkable_dtype, lib, mod, graph, p) or found_one # Wrap in function to explicitly deallocate the runtime. def _run_linked(lib, mod): graph_json, _, _ = lib graph_rt = tvm.contrib.graph_executor.create(graph_json, mod, tvm.cpu(0)) graph_rt.set_input("rand_input", rand_input) # NOTE: params not required. graph_rt.run() return graph_rt.get_output(0) linked_output = _run_linked(lib, mod) runtime = Runtime("cpp", {"system-lib": True}) with tvm.transform.PassContext(opt_level=3): lib = tvm.relay.build(ir_mod, "llvm", runtime=runtime, params=param_init) def _run_unlinked(lib): graph_json, mod, lowered_params = lib graph_rt = tvm.contrib.graph_executor.create(graph_json, mod, tvm.cpu(0)) graph_rt.set_input("rand_input", rand_input, **lowered_params) graph_rt.run() return graph_rt.get_output(0) unlinked_output = _run_unlinked(lib) if "int" in linkable_dtype: np.testing.assert_equal(unlinked_output.numpy(), linked_output.numpy()) else: np.testing.assert_allclose(unlinked_output.numpy(), linked_output.numpy()) def _get_c_datatype(dtype): """Translate LINKABLE_DTYPES element to c datatype.""" if "int" in dtype: return f"{dtype}_t" elif dtype == "float32": return "float" elif dtype == "float64": return "double" else: assert False, f"unknown dtype {dtype}" HEX_NUM_RE = re.compile(r"[+\-]?(?:(?:0x[0-9A-Fa-f.p+-]+)|(?:INFINITY)|(?:NAN))") def test_c_link_params(linkable_dtype): temp_dir = utils.tempdir() mod, param_init = _make_mod_and_params(linkable_dtype) rand_input = _make_random_tensor(linkable_dtype, INPUT_SHAPE) main_func = mod["main"] target = "c" executor = Executor("graph", {"link-params": True}) with tvm.transform.PassContext(opt_level=3, config={"tir.disable_vectorize": True}): lib = tvm.relay.build(mod, target, executor=executor, params=param_init) assert len(lib.params.keys()) == 0 # NOTE: params became tir.constants src = lib.lib.get_source() lib.lib.save(temp_dir.relpath("test.c"), "c") c_dtype = _get_c_datatype(linkable_dtype) src_lines = src.split("\n") param = param_init[f"{linkable_dtype}_a"].reshape(np.prod(KERNEL_SHAPE)) param_def = rf"^static const {c_dtype} __attribute__\(\(section\(\".rodata.tvm\"\), aligned\(16\)\)\) [a-zA-Z_0-9]*constant_\d+\[{np.prod(param.shape)}\] = {{$" for i, line in enumerate(src_lines): if re.match(param_def, line): i += 1 break else: assert False, f'did not find parameter definition "{param_def}":\n{src}' cursor = 0 width = dtype_info(linkable_dtype).bits // 4 + 2 if linkable_dtype.startswith("int"): width += 1 # Account for sign while "};" not in src_lines[i]: for match in HEX_NUM_RE.finditer(src_lines[i]): cursor += 1 i += 1 assert cursor == np.prod(param.shape) # Need a unique name per library to avoid dlopen caching the lib load. lib_path = temp_dir.relpath(f"test-{linkable_dtype}-linked.so") lib["remove_params"]().export_library(lib_path) lib_mod = tvm.runtime.load_module(lib_path) # lib_mod = lib_factory['default']() graph = json.loads(lib.graph_json) for p in lib.params: _verify_linked_param(linkable_dtype, lib, lib_mod, graph, p) # Wrap in function to explicitly deallocate the runtime. def _run_linked(lib_mod): graph_rt = tvm.contrib.graph_executor.GraphModule(lib_mod["default"](tvm.cpu(0))) graph_rt.set_input("rand_input", rand_input) # NOTE: params not required. graph_rt.run() return graph_rt.get_output(0) linked_output = _run_linked(lib_mod) linked_params = lib.params with tvm.transform.PassContext(opt_level=3, config={"tir.disable_vectorize": True}): lib = tvm.relay.build(mod, "c", params=param_init) _, _, params = lib # Need a unique name per library to avoid dlopen caching the lib load. lib_path = temp_dir.relpath(f"test-{linkable_dtype}-unlinked.so") lib.export_library(lib_path) lib_mod = tvm.runtime.load_module(lib_path) def _run_unlinked(lib_mod): graph_rt = tvm.contrib.graph_executor.GraphModule(lib_mod["default"](tvm.cpu(0))) graph_rt.set_input("rand_input", rand_input, **params) graph_rt.run() return graph_rt.get_output(0) unlinked_output = _run_unlinked(lib_mod) if "int" in linkable_dtype: np.testing.assert_equal(unlinked_output.numpy(), linked_output.numpy()) else: np.testing.assert_allclose(unlinked_output.numpy(), linked_output.numpy()) @tvm.testing.requires_micro def test_crt_link_params(linkable_dtype): from tvm import micro mod, param_init = _make_mod_and_params(linkable_dtype) rand_input = _make_random_tensor(linkable_dtype, INPUT_SHAPE) main_func = mod["main"] target = "c" runtime = Runtime("crt", {"system-lib": True}) executor = Executor("graph", {"link-params": True}) with tvm.transform.PassContext(opt_level=3, config={"tir.disable_vectorize": True}): factory = tvm.relay.build( mod, target, runtime=runtime, executor=executor, params=param_init ) assert len(factory.get_params().keys()) == 0 # NOTE: params became tir.constants temp_dir = tvm.contrib.utils.tempdir() template_project_dir = os.path.join(tvm.micro.get_standalone_crt_dir(), "template", "host") project = tvm.micro.generate_project( template_project_dir, factory, temp_dir / "project", {"verbose": 1} ) project.build() project.flash() with tvm.micro.Session(project.transport()) as sess: graph_rt = tvm.micro.session.create_local_graph_executor( factory.get_graph_json(), sess.get_system_lib(), sess.device ) assert len(factory.params.keys()) == 0 # NOTE: params became tir.constants # NOTE: not setting params here. graph_rt.set_input("rand_input", rand_input) graph_rt.run() linked_output = graph_rt.get_output(0).numpy() runtime = Runtime("cpp", {"system-lib": True}) with tvm.transform.PassContext(opt_level=3): lib = tvm.relay.build(mod, "llvm", runtime=runtime, params=param_init) def _run_unlinked(lib): graph_json, mod, lowered_params = lib graph_rt = tvm.contrib.graph_executor.create(graph_json, mod, tvm.cpu(0)) graph_rt.set_input("rand_input", rand_input, **lowered_params) graph_rt.run() return graph_rt.get_output(0).numpy() unlinked_output = _run_unlinked(lib) if "int" in linkable_dtype: np.testing.assert_equal(unlinked_output, linked_output) else: np.testing.assert_allclose(unlinked_output, linked_output) def test_tir_link_params(): def get_dense(data_shape, weight_shape): data = relay.var("data", shape=data_shape, dtype="float32") weight = relay.var("weight", shape=weight_shape, dtype="float32") dense = relay.nn.dense(data, weight) return relay.Function([data, weight], dense) def get_ref_dense(data_np, weight_np): return np.dot(data_np, np.transpose(weight_np)) def schedule_dense(sch): dense = sch.get_block("T_matmul_NT") _y, _x, _k = sch.get_loops(dense) M, N, K = 128, 128, 128 data_shape = (M, K) weight_shape = (N, K) relay_mod = tvm.IRModule.from_expr(get_dense(data_shape, weight_shape)) relay_mod = relay.transform.InferType()(relay_mod) data_np = np.random.randn(*data_shape).astype("float32") weight_np = np.random.randn(*weight_shape).astype("float32") target = "llvm" params = {"weight": weight_np} def schedule_fn(sch): if "nn_dense" in sch.mod.attrs["task_name"]: schedule_dense(sch) return True return False with StringIO() as stderr_buf, redirect_stderr(stderr_buf): with ms.database.ScheduleFnDatabase(schedule_fn), tvm.transform.PassContext( opt_level=3, config={"relay.backend.use_meta_schedule": True}, ): executor = Executor("graph", {"link-params": True}) lib = relay.build(relay_mod, target=target, executor=executor) # Workload look up should succeed. This does not work when the test is invoked from pytest. assert not "Cannot find workload" in stderr_buf.getvalue() dev = tvm.device(target, 0) runtime = tvm.contrib.graph_executor.GraphModule(lib["default"](dev)) runtime.set_input(**params) runtime.set_input("data", data_np) runtime.run() out = runtime.get_output(0).numpy() ref = get_ref_dense(data_np, weight_np) tvm.testing.assert_allclose(out, ref, atol=1e-4, rtol=1e-4) if __name__ == "__main__": tvm.testing.main()
https://github.com/zk-ml/tachikoma
tests/python/unittest/test_lower_build.py
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. import numpy as np import tvm from tvm import te from tvm.ir.module import IRModule from tvm.script import tir as T import tvm.testing def _check_module_with_numpy(mod, shape=(128, 128, 128)): m, n, k = shape a = tvm.nd.array(np.random.rand(m, k).astype("float32")) b = tvm.nd.array(np.random.rand(n, k).astype("float32")) c = tvm.nd.array(np.zeros((m, n), dtype="float32")) c_np = np.dot(a.numpy(), b.numpy().transpose()) mod(a, b, c) tvm.testing.assert_allclose(c.numpy(), c_np, rtol=1e-5) # pylint: disable=no-self-argument, missing-class-docstring, missing-function-docstring @T.prim_func def matmul(a: T.handle, b: T.handle, c: T.handle) -> None: A = T.match_buffer(a, [128, 128]) B = T.match_buffer(b, [128, 128]) C = T.match_buffer(c, [128, 128]) for i, j in T.grid(128, 128): with T.block("init"): vi, vj = T.axis.remap("SS", [i, j]) C[vi, vj] = T.float32(0) for k in range(128): with T.block("update"): vi, vj, vk = T.axis.remap("SSR", [i, j, k]) C[vi, vj] = C[vi, vj] + A[vi, vk] * B[vj, vk] @tvm.script.ir_module class LoweredModule: @T.prim_func def main( A: T.Buffer[(16384,), "float32"], B: T.Buffer[(16384,), "float32"], C: T.Buffer[(16384,), "float32"], ) -> None: # function attr dict T.func_attr({"global_symbol": "main", "from_legacy_te_schedule": True, "tir.noalias": True}) T.preflattened_buffer(A, [128, 128], data=A.data) T.preflattened_buffer(B, [128, 128], data=B.data) T.preflattened_buffer(C, [128, 128], data=C.data) # body for x, y in T.grid(128, 128): C[x * 128 + y] = 0.0 for k in T.serial(0, 128): C[x * 128 + y] = C[x * 128 + y] + A[x * 128 + k] * B[y * 128 + k] @tvm.script.ir_module class LoweredTIRModule: @T.prim_func def main( A: T.Buffer[(16384,), "float32"], B: T.Buffer[(16384,), "float32"], C: T.Buffer[(16384,), "float32"], ) -> None: # function attr dict T.func_attr({"global_symbol": "main", "tir.noalias": True}) T.preflattened_buffer(A, [128, 128], data=A.data) T.preflattened_buffer(B, [128, 128], data=B.data) T.preflattened_buffer(C, [128, 128], data=C.data) # body for x, y in T.grid(128, 128): C[x * 128 + y] = 0.0 for k in T.serial(0, 128): C[x * 128 + y] = C[x * 128 + y] + A[x * 128 + k] * B[y * 128 + k] def test_lower_build_te_schedule(): m, n, k = 128, 128, 128 axis_k = te.reduce_axis((0, k), "k") A = te.placeholder((m, k), name="A") B = te.placeholder((k, n), name="B") C = te.compute((m, n), lambda x, y: te.sum(A[x, axis_k] * B[y, axis_k], axis=axis_k), name="C") s = te.create_schedule(C.op) # check lowering with the CSE pass disabled as otherwise it would do some commoning with tvm.transform.PassContext(opt_level=3, disabled_pass=["tir.CommonSubexprElimTIR"]): ir_mod = tvm.lower(s, [A, B, C]) tvm.ir.assert_structural_equal(ir_mod, LoweredModule) # check building mod = tvm.build(s, [A, B, C], target="llvm") _check_module_with_numpy(mod) def test_lower_build_tir_func(): # check lowering with the CSE pass disabled as otherwise it would do some commoning with tvm.transform.PassContext(opt_level=3, disabled_pass=["tir.CommonSubexprElimTIR"]): ir_mod = tvm.lower(matmul) tvm.ir.assert_structural_equal(ir_mod, LoweredTIRModule) # check building mod = tvm.build(matmul, target="llvm") _check_module_with_numpy(mod) def test_lower_build_tir_module(): func = matmul.with_attr("global_symbol", "main") func = func.with_attr("tir.noalias", True) ir_mod = IRModule({"main": func}) # check lowering with the CSE pass disabled as otherwise it would do some commoning with tvm.transform.PassContext(opt_level=3, disabled_pass=["tir.CommonSubexprElimTIR"]): lowered_mod = tvm.lower(ir_mod) tvm.ir.assert_structural_equal(lowered_mod, LoweredTIRModule) # check building mod = tvm.build(ir_mod, target="llvm") _check_module_with_numpy(mod) def test_lower_build_lowered_module(): # check lowering with the CSE pass disabled as otherwise it would do some commoning with tvm.transform.PassContext(opt_level=3, disabled_pass=["tir.CommonSubexprElimTIR"]): ir_mod = tvm.lower(LoweredTIRModule) tvm.ir.assert_structural_equal(ir_mod, LoweredTIRModule) # check building mod = tvm.build(ir_mod, target="llvm") _check_module_with_numpy(mod) if __name__ == "__main__": test_lower_build_te_schedule() test_lower_build_tir_func() test_lower_build_tir_module() test_lower_build_lowered_module()
https://github.com/zk-ml/tachikoma
tests/python/unittest/test_meta_schedule_arg_info.py
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. # pylint: disable=missing-module-docstring,missing-function-docstring,missing-class-docstring from tvm.meta_schedule.arg_info import ArgInfo, TensorInfo from tvm.script import tir as T # pylint: disable=invalid-name,no-member,line-too-long,too-many-nested-blocks,no-self-argument # fmt: off @T.prim_func def Matmul(a: T.handle, b: T.handle, c: T.handle) -> None: T.func_attr({"global_symbol": "main"}) A = T.match_buffer(a, (128, 256), "float32") B = T.match_buffer(b, (256, 512), "float32") C = T.match_buffer(c, (128, 512), "float32") for i, j, k in T.grid(128, 256, 512): with T.block("matmul"): vi, vj, vk = T.axis.remap("SSR", [i, j, k]) with T.init(): C[vi, vj] = 0.0 C[vi, vj] = C[vi, vj] + A[vi, vk] * B[vk, vj] # fmt: on # pylint: enable=invalid-name,no-member,line-too-long,too-many-nested-blocks,no-self-argument def test_meta_schedule_tensor_info_creation(): info = TensorInfo("float32", [1, 224, 224, 3]) info = str(info) assert info == 'TensorInfo("float32", [1, 224, 224, 3])' def test_meta_schedule_tensor_info_as_json(): info = TensorInfo("float32", [1, 224, 224, 3]) info = info.as_json() assert info == ["TENSOR", "float32", [1, 224, 224, 3]] def test_meta_schedule_tensor_info_from_json(): info = ["TENSOR", "float32", [1, 224, 224, 3]] info = TensorInfo.from_json(info) assert str(info) == 'TensorInfo("float32", [1, 224, 224, 3])' def test_meta_schedule_arg_info_from_prim_func(): a_info, b_info, c_info = ArgInfo.from_prim_func(Matmul) assert str(a_info) == 'TensorInfo("float32", [128, 256])' assert str(b_info) == 'TensorInfo("float32", [256, 512])' assert str(c_info) == 'TensorInfo("float32", [128, 512])' if __name__ == "__main__": test_meta_schedule_tensor_info_creation() test_meta_schedule_tensor_info_as_json() test_meta_schedule_tensor_info_from_json() test_meta_schedule_arg_info_from_prim_func()
https://github.com/zk-ml/tachikoma
tests/python/unittest/test_meta_schedule_builder.py
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. """ Test Meta Schedule Builder """ import os import sys import time from typing import List import pytest import tvm.testing from tvm import script from tvm._ffi import register_func from tvm.meta_schedule.builder import ( BuilderInput, BuilderResult, LocalBuilder, PyBuilder, ) from tvm.runtime import Module from tvm.script import tir as T from tvm.target import Target # pylint: disable=invalid-name,no-member,line-too-long,too-many-nested-blocks,missing-docstring @script.ir_module class MatmulModule: @T.prim_func def matmul(a: T.handle, b: T.handle, c: T.handle) -> None: # pylint: disable=no-self-argument T.func_attr({"global_symbol": "matmul", "tir.noalias": True}) A = T.match_buffer(a, (1024, 1024), "float32") B = T.match_buffer(b, (1024, 1024), "float32") C = T.match_buffer(c, (1024, 1024), "float32") for i, j, k in T.grid(1024, 1024, 1024): with T.block("matmul"): vi, vj, vk = T.axis.remap("SSR", [i, j, k]) with T.init(): C[vi, vj] = 0.0 C[vi, vj] = C[vi, vj] + A[vi, vk] * B[vk, vj] @script.ir_module class MatmulReluModule: @T.prim_func def matmul_relu( # pylint: disable=no-self-argument a: T.handle, b: T.handle, d: T.handle ) -> None: T.func_attr({"global_symbol": "matmul_relu", "tir.noalias": True}) A = T.match_buffer(a, (1024, 1024), "float32") B = T.match_buffer(b, (1024, 1024), "float32") D = T.match_buffer(d, (1024, 1024), "float32") C = T.alloc_buffer((1024, 1024), "float32") for i, j, k in T.grid(1024, 1024, 1024): with T.block("matmul"): vi, vj, vk = T.axis.remap("SSR", [i, j, k]) with T.init(): C[vi, vj] = 0.0 C[vi, vj] = C[vi, vj] + A[vi, vk] * B[vk, vj] for i, j in T.grid(1024, 1024): with T.block("relu"): vi, vj = T.axis.remap("SS", [i, j]) D[vi, vj] = T.max(C[vi, vj], 0.0) @script.ir_module class BatchMatmulModule: @T.prim_func def batch_matmul( # pylint: disable=no-self-argument a: T.handle, b: T.handle, c: T.handle ) -> None: T.func_attr({"global_symbol": "batch_matmul", "tir.noalias": True}) A = T.match_buffer(a, [16, 128, 128]) B = T.match_buffer(b, [16, 128, 128]) C = T.match_buffer(c, [16, 128, 128]) for n, i, j, k in T.grid(16, 128, 128, 128): with T.block("update"): vn, vi, vj, vk = T.axis.remap("SSSR", [n, i, j, k]) with T.init(): C[vn, vi, vj] = 0.0 C[vn, vi, vj] = C[vn, vi, vj] + A[vn, vi, vk] * B[vn, vj, vk] # pylint: enable=invalid-name,no-member,line-too-long,too-many-nested-blocks,missing-docstring def _check_build_results(builder_results: List[BuilderResult]): """Simple check whether the build is successful""" for result in builder_results: artifact_path = result.artifact_path error_msg = result.error_msg assert artifact_path is not None assert error_msg is None os.remove(artifact_path) os.rmdir(os.path.dirname(artifact_path)) def test_meta_schedule_single_build(): """Test meta schedule builder for a single build""" mod = MatmulModule builder = LocalBuilder() builder_inputs = [BuilderInput(mod, Target("llvm"))] builder_results = builder.build(builder_inputs) assert len(builder_results) == len(builder_inputs) _check_build_results(builder_results) def test_meta_schedule_multiple_build(): """Test meta schedule builder for multiple builds""" builder = LocalBuilder() builder_inputs = [ BuilderInput(MatmulModule, Target("llvm")), BuilderInput(MatmulReluModule, Target("llvm")), BuilderInput(BatchMatmulModule, Target("llvm")), ] builder_results = builder.build(builder_inputs) assert len(builder_results) == len(builder_inputs) _check_build_results(builder_results) def test_meta_schedule_error_handle_test_builder(): """Test the error handing during building""" class TestBuilder(PyBuilder): def build( # pylint: disable=no-self-use self, build_inputs: List[BuilderInput], ) -> List[BuilderResult]: return [BuilderResult(None, "error") for w in build_inputs] builder = TestBuilder() builder_inputs = [ BuilderInput(MatmulModule, Target("llvm")), BuilderInput(MatmulReluModule, Target("llvm")), BuilderInput(BatchMatmulModule, Target("llvm")), ] builder_results = builder.build(builder_inputs) assert len(builder_results) == len(builder_inputs) for result in builder_results: artifact_path = result.artifact_path error_msg = result.error_msg assert artifact_path is None assert error_msg == "error" def test_meta_schedule_error_handle_build_func(): """Test the error handing during building""" def initializer(): @register_func("meta_schedule.builder.test_build") def test_build(mod: Module, target: Target, _) -> None: # pylint: disable=unused-variable raise ValueError("Builder intended Test Error (build func).") builder = LocalBuilder(f_build="meta_schedule.builder.test_build", initializer=initializer) builder_inputs = [BuilderInput(MatmulModule, Target("llvm"))] builder_results = builder.build(builder_inputs) assert len(builder_results) == len(builder_inputs) for result in builder_results: artifact_path = result.artifact_path error_msg = result.error_msg assert artifact_path is None assert error_msg.startswith("LocalBuilder: An exception occurred") def test_meta_schedule_error_handle_export_func(): """Test the error handing during building""" def initializer(): @register_func("meta_schedule.builder.test_export") def test_build(mod: Module) -> str: # pylint: disable=unused-variable raise ValueError("Builder intended Test Error (export func).") builder = LocalBuilder(f_export="meta_schedule.builder.test_export", initializer=initializer) builder_inputs = [BuilderInput(MatmulModule, Target("llvm"))] builder_results = builder.build(builder_inputs) assert len(builder_results) == len(builder_inputs) for result in builder_results: artifact_path = result.artifact_path error_msg = result.error_msg assert artifact_path is None assert error_msg.startswith("LocalBuilder: An exception occurred") def test_meta_schedule_error_handle_time_out(): """Test the error handing time out during building""" def initializer(): @register_func("meta_schedule.builder.test_time_out") def timeout_build(mod, target, _): # pylint: disable=unused-argument, unused-variable time.sleep(2) builder = LocalBuilder( timeout_sec=1, f_build="meta_schedule.builder.test_time_out", initializer=initializer, ) builder_inputs = [BuilderInput(MatmulModule, Target("llvm"))] builder_results = builder.build(builder_inputs) assert len(builder_results) == len(builder_inputs) for result in builder_results: artifact_path = result.artifact_path error_msg = result.error_msg assert artifact_path is None assert error_msg.startswith("LocalBuilder: Timeout") def test_meta_schedule_missing_build_func(): with pytest.raises(ValueError): LocalBuilder(f_build="wrong-name") if __name__ == "__main__": tvm.testing.main()
https://github.com/zk-ml/tachikoma
tests/python/unittest/test_meta_schedule_byoc_tensorrt.py
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. """ Test Meta Schedule Builder """ # pylint: disable=missing-docstring import sys from typing import List import pytest import tvm import tvm.testing from tvm import relay from tvm.meta_schedule.arg_info import TensorInfo from tvm.meta_schedule.builder import BuilderInput, LocalBuilder from tvm.meta_schedule.runner import EvaluatorConfig, LocalRunner, RunnerInput from tvm.meta_schedule.testing.custom_builder_runner import ( build_relay, build_relay_with_tensorrt, run_with_graph_executor, ) from tvm.meta_schedule.testing.relay_workload import get_network from tvm.relay import testing from tvm.relay.op.contrib import tensorrt from tvm.target import Target from tvm.tir import FloatImm has_tensorrt_codegen = pytest.mark.skipif( not tvm.get_global_func("relay.ext.tensorrt", True), reason="TensorRT codegen not available", ) has_tensorrt_runtime = pytest.mark.skipif( not tensorrt.is_tensorrt_runtime_enabled(), reason="TensorRT runtime not available", ) # conv2d+relu network def get_conv2d_relu( data_shape, out_channels, kernel_size, strides, padding, dilation, groups, data_layout, kernel_layout, dtype, ): data = relay.var("data", relay.TensorType(data_shape, dtype)) weight = relay.var("weight") net = relay.nn.conv2d( data=data, weight=weight, # conv kernel strides=strides, padding=padding, dilation=dilation, groups=groups, channels=out_channels, kernel_size=kernel_size, data_layout=data_layout, kernel_layout=kernel_layout, ) net = relay.add(net, net) net = relay.nn.relu(net) inputs = relay.analysis.free_vars(net) return relay.Function(inputs, net) def verify_meta_schedule_with_tensorrt( mod, params, data_shape, use_trt: bool = True, ): # Build builder = LocalBuilder( f_build=build_relay_with_tensorrt if use_trt else build_relay, timeout_sec=1000, ) builder_input = BuilderInput(mod, Target("cuda"), params) builder_result = builder.build([builder_input])[0] assert builder_result.error_msg is None, builder_result.error_msg assert builder_result.artifact_path is not None # Run runner_input = RunnerInput( builder_result.artifact_path, device_type="cuda", args_info=[TensorInfo("float32", data_shape)], ) runner = LocalRunner( evaluator_config=EvaluatorConfig( number=5, repeat=2, min_repeat_ms=0, enable_cpu_cache_flush=False, ), f_run_evaluator=run_with_graph_executor, ) # Run the module runner_future = runner.run([runner_input])[0] runner_result = runner_future.result() assert runner_result is not None assert runner_result.error_msg is None, runner_result.error_msg assert runner_result.run_secs is not None for result in runner_result.run_secs: if isinstance(result, FloatImm): result = result.value assert isinstance(result, float) assert result >= 0.0 @has_tensorrt_codegen def test_conv2d_relu(): data_shape = (1, 1280, 14, 14) out_channels = 256 kernel_size, strides, padding, dilation, groups = (1, 1), (1, 1), (0, 0, 0, 0), (1, 1), 1 data_layout, kernel_layout = "NCHW", "OIHW" dtype = "float32" f = get_conv2d_relu( data_shape, out_channels, kernel_size, strides, padding, dilation, groups, data_layout, kernel_layout, dtype, ) mod, params = testing.create_workload(f) verify_meta_schedule_with_tensorrt(mod, params, data_shape) @has_tensorrt_codegen @pytest.mark.parametrize("model_name", ["resnet_50"]) @pytest.mark.parametrize("input_shape", [[1, 3, 224, 224]]) @pytest.mark.parametrize("use_trt", [True, False]) def test_relay_model(model_name: str, input_shape: List[int], use_trt: bool): mod, params, _ = get_network(model_name, input_shape) verify_meta_schedule_with_tensorrt( mod, params, input_shape, use_trt, ) if __name__ == "__main__": tvm.testing.main()
https://github.com/zk-ml/tachikoma
tests/python/unittest/test_meta_schedule_cost_model.py
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. # pylint: disable=missing-docstring import os import re import shutil import tempfile import unittest from functools import partial from typing import List import numpy as np import tvm import tvm.testing from tvm.meta_schedule.cost_model import PyCostModel, RandomModel, XGBModel from tvm.meta_schedule.cost_model.xgb_model import PackSum, _get_custom_call_back from tvm.meta_schedule.feature_extractor import RandomFeatureExtractor from tvm.meta_schedule.runner import RunnerResult from tvm.meta_schedule.search_strategy import MeasureCandidate from tvm.meta_schedule.tune_context import TuneContext from tvm.meta_schedule.utils import derived_object from tvm.script import tir as T from tvm.tir.schedule.schedule import Schedule # pylint: disable=invalid-name,no-member,line-too-long,too-many-nested-blocks,missing-docstring @tvm.script.ir_module class Matmul: @T.prim_func def main(a: T.handle, b: T.handle, c: T.handle) -> None: # pylint: disable=no-self-argument T.func_attr({"global_symbol": "main", "tir.noalias": True}) A = T.match_buffer(a, (1024, 1024), "float32") B = T.match_buffer(b, (1024, 1024), "float32") C = T.match_buffer(c, (1024, 1024), "float32") for i, j, k in T.grid(1024, 1024, 1024): with T.block("matmul"): vi, vj, vk = T.axis.remap("SSR", [i, j, k]) with T.init(): C[vi, vj] = 0.0 C[vi, vj] = C[vi, vj] + A[vi, vk] * B[vk, vj] # pylint: enable=invalid-name,no-member,line-too-long,too-many-nested-blocks,disable=unused-argument def test_meta_schedule_cost_model(): @derived_object class FancyCostModel(PyCostModel): def load(self, path: str) -> None: pass def save(self, path: str) -> None: pass def update( self, context: TuneContext, candidates: List[MeasureCandidate], results: List[RunnerResult], ) -> None: pass def predict(self, context: TuneContext, candidates: List[MeasureCandidate]) -> np.ndarray: return np.random.rand(10) model = FancyCostModel() model.save("fancy_test_location") model.load("fancy_test_location") model.update(TuneContext(), [], []) results = model.predict( TuneContext(), [MeasureCandidate(Schedule(mod=Matmul), []) for _ in range(10)] ) assert results.shape == (10,) def test_meta_schedule_cost_model_as_string(): @derived_object class NotSoFancyCostModel(PyCostModel): def load(self, path: str) -> None: pass def save(self, path: str) -> None: pass def update( self, context: TuneContext, candidates: List[MeasureCandidate], results: List[RunnerResult], ) -> None: pass def predict(self, context: TuneContext, candidates: List[MeasureCandidate]) -> np.ndarray: return np.random.rand(10) cost_model = NotSoFancyCostModel() pattern = re.compile(r"meta_schedule.NotSoFancyCostModel\(0x[a-f|0-9]*\)") assert pattern.match(str(cost_model)) def test_meta_schedule_random_model(): model = RandomModel() model.update(TuneContext(), [], []) res = model.predict(TuneContext(), [MeasureCandidate(Schedule(Matmul), []) for i in range(10)]) assert len(res) == 10 assert min(res) >= 0 and max(res) <= model.max_range def test_meta_schedule_random_model_reseed(): model = RandomModel(seed=100) res = model.predict(TuneContext(), [MeasureCandidate(Schedule(Matmul), []) for i in range(20)]) new_model = RandomModel(seed=100) new_res = new_model.predict( TuneContext(), [MeasureCandidate(Schedule(Matmul), []) for i in range(20)] ) assert (res == new_res).all() def test_meta_schedule_random_model_reload(): model = RandomModel(seed=25973) model.predict( TuneContext(), [MeasureCandidate(Schedule(Matmul), []) for i in range(30)] ) # change state path = os.path.join(tempfile.mkdtemp(), "test_output_meta_schedule_random_model.npy") model.save(path) res1 = model.predict(TuneContext(), [MeasureCandidate(Schedule(Matmul), []) for i in range(70)]) model.load(path) res2 = model.predict(TuneContext(), [MeasureCandidate(Schedule(Matmul), []) for i in range(70)]) shutil.rmtree(os.path.dirname(path)) assert (res1 == res2).all() def _dummy_candidate(): return MeasureCandidate(Schedule(Matmul), []) def _dummy_result(num_samples: int = 4, max_run_sec: int = 10): return RunnerResult(list(np.random.rand(num_samples) * max_run_sec + 1e-6), None) def test_meta_schedule_xgb_model(): extractor = RandomFeatureExtractor() model = XGBModel(extractor=extractor, num_warmup_samples=2) update_sample_count = 10 predict_sample_count = 100 model.update( TuneContext(), [_dummy_candidate() for i in range(update_sample_count)], [_dummy_result() for i in range(update_sample_count)], ) model.predict(TuneContext(), [_dummy_candidate() for i in range(predict_sample_count)]) def test_meta_schedule_xgb_model_reload(): extractor = RandomFeatureExtractor() model = XGBModel(extractor=extractor, num_warmup_samples=10) update_sample_count = 20 predict_sample_count = 30 model.update( TuneContext(), [_dummy_candidate() for i in range(update_sample_count)], [_dummy_result() for i in range(update_sample_count)], ) model.predict(TuneContext(), [_dummy_candidate() for i in range(predict_sample_count)]) with tempfile.NamedTemporaryFile() as path: # Backup random_state = model.extractor.random_state # save feature extractor's random state old_data = model.data old_data_size = model.data_size model.save(path.name) res1 = model.predict( TuneContext(), [_dummy_candidate() for i in range(predict_sample_count)] ) # Load model.extractor.random_state = random_state # load feature extractor's random state model.load(path.name) new_data = model.data new_data_size = model.data_size res2 = model.predict( TuneContext(), [_dummy_candidate() for i in range(predict_sample_count)] ) assert (res1 == res2).all() assert old_data_size == new_data_size assert len(old_data) == len(new_data) for (k1, g1), (k2, g2) in zip( # pylint: disable=invalid-name old_data.items(), new_data.items() ): assert k1 == k2 assert k1 == g1.group_hash assert k2 == g2.group_hash assert (g1.costs == g2.costs).all() assert len(g1.features) == len(g2.features) for f1, f2 in zip(g1.features, g2.features): # pylint: disable=invalid-name assert (f1 == f2).all() def test_meta_schedule_xgb_model_reupdate(): extractor = RandomFeatureExtractor() model = XGBModel(extractor=extractor, num_warmup_samples=2) update_sample_count = 60 predict_sample_count = 100 model.update( TuneContext(), [_dummy_candidate() for i in range(update_sample_count)], [_dummy_result() for i in range(update_sample_count)], ) model.update( TuneContext(), [_dummy_candidate() for i in range(update_sample_count)], [_dummy_result() for i in range(update_sample_count)], ) model.update( TuneContext(), [_dummy_candidate() for i in range(update_sample_count)], [_dummy_result() for i in range(update_sample_count)], ) model.predict(TuneContext(), [_dummy_candidate() for i in range(predict_sample_count)]) def xgb_version_check(): # pylint: disable=import-outside-toplevel import xgboost as xgb from packaging import version # pylint: enable=import-outside-toplevel return version.parse(xgb.__version__) >= version.parse("1.6.0") @unittest.skipIf(xgb_version_check(), "test not supported for xgboost version after 1.6.0") def test_meta_schedule_xgb_model_callback_as_function(): # pylint: disable=import-outside-toplevel from itertools import chain as itertools_chain import xgboost as xgb # pylint: enable=import-outside-toplevel extractor = RandomFeatureExtractor() model = XGBModel(extractor=extractor, num_warmup_samples=10) update_sample_count = 20 predict_sample_count = 30 model.update( TuneContext(), [_dummy_candidate() for i in range(update_sample_count)], [_dummy_result() for i in range(update_sample_count)], ) model.predict(TuneContext(), [_dummy_candidate() for i in range(predict_sample_count)]) with tempfile.NamedTemporaryFile() as path: # Backup and train on new TrainingCallBack api random_state = model.extractor.random_state # save feature extractor's random state model.save(path.name) old_booster = model.booster xs = [ # pylint: disable=invalid-name x.numpy().astype("float32") for x in extractor.extract_from( TuneContext(), [_dummy_candidate() for i in range(predict_sample_count)], ) ] d_test = PackSum(xs=xs, ys=None) pred1 = old_booster.predict(d_test.dmatrix) # Load and train on deprecated TrainingCallBack api model.extractor.random_state = random_state # load feature extractor's random state model.load(path.name) d_train = PackSum( xs=list(itertools_chain.from_iterable([g.features for g in model.data.values()])), ys=np.concatenate( [g.min_cost / g.costs for g in model.data.values()], axis=0, ), ) def obj(ys_pred: np.ndarray, d_train1: "xgb.DMatrix"): # type: ignore # pylint: disable = unused-argument return d_train.obj_square_error(ys_pred) def rmse(ys_pred: np.ndarray, d_train1: "xgb.DMatrix"): # type: ignore # pylint: disable = unused-argument return d_train.rmse(ys_pred) def avg_peak_score(ys_pred: np.ndarray, d_train1: "xgb.DMatrix"): # type: ignore # pylint: disable = unused-argument return d_train.average_peak_score(ys_pred, model.average_peak_n) new_booster = xgb.train( model.config.to_dict(), d_train.dmatrix, num_boost_round=10000, obj=obj, callbacks=[ partial( _get_custom_call_back( early_stopping_rounds=model.early_stopping_rounds, verbose_eval=model.verbose_eval, fevals=[rmse, avg_peak_score], evals=[(d_train.dmatrix, "tr")], cvfolds=None, ) ) ], ) xs = [ # pylint: disable=invalid-name x.numpy().astype("float32") for x in extractor.extract_from( TuneContext(), [_dummy_candidate() for i in range(predict_sample_count)], ) ] d_test = PackSum(xs=xs, ys=None) pred2 = new_booster.predict(d_test.dmatrix) assert np.allclose(pred1, pred2, rtol=1e-3, atol=1e-3) if __name__ == "__main__": tvm.testing.main()
https://github.com/zk-ml/tachikoma
tests/python/unittest/test_meta_schedule_database.py
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. # pylint: disable=missing-module-docstring,missing-function-docstring,missing-class-docstring """Test Meta Schedule Database""" import os.path as osp import tempfile from typing import Callable, Optional, List import tvm import tvm.testing from tvm.target import Target from tvm import meta_schedule as ms from tvm.meta_schedule.database import TuningRecord, Workload from tvm import tir from tvm.ir.module import IRModule from tvm.script import tir as T from tvm.tir import Schedule # pylint: disable=invalid-name,no-member,line-too-long,too-many-nested-blocks,no-self-argument # fmt: off @tvm.script.ir_module class Matmul: @T.prim_func def main(a: T.handle, b: T.handle, c: T.handle) -> None: T.func_attr({"global_symbol": "main"}) A = T.match_buffer(a, (1024, 1024), "float32") B = T.match_buffer(b, (1024, 1024), "float32") C = T.match_buffer(c, (1024, 1024), "float32") for i, j, k in T.grid(1024, 1024, 1024): with T.block("matmul"): vi, vj, vk = T.axis.remap("SSR", [i, j, k]) with T.init(): C[vi, vj] = 0.0 C[vi, vj] = C[vi, vj] + A[vi, vk] * B[vk, vj] @tvm.script.ir_module class MatmulRelu: @T.prim_func def main(a: T.handle, b: T.handle, d: T.handle) -> None: # pylint: disable=no-self-argument T.func_attr({"global_symbol": "main", "tir.noalias": True}) A = T.match_buffer(a, (16, 16), "float32") B = T.match_buffer(b, (16, 16), "float32") D = T.match_buffer(d, (16, 16), "float32") C = T.alloc_buffer((16, 16), "float32") for i, j, k in T.grid(16, 16, 16): with T.block("matmul"): vi, vj, vk = T.axis.remap("SSR", [i, j, k]) with T.init(): C[vi, vj] = 0.0 C[vi, vj] = C[vi, vj] + A[vi, vk] * B[vk, vj] for i, j in T.grid(16, 16): with T.block("relu"): vi, vj = T.axis.remap("SS", [i, j]) D[vi, vj] = T.max(C[vi, vj], 0.0) # fmt: on # pylint: enable=invalid-name,no-member,line-too-long,too-many-nested-blocks,no-self-argument def _schedule_matmul(sch: Schedule): block = sch.get_block("matmul") i, j, k = sch.get_loops(block=block) i_tiles = [1, 1, 2, 512] j_tiles = [1, 512, 1, 2] k_tiles = [256, 4] i_0, i_1, i_2, i_3 = sch.split(loop=i, factors=i_tiles) j_0, j_1, j_2, j_3 = sch.split(loop=j, factors=j_tiles) k_0, k_1 = sch.split(loop=k, factors=k_tiles) sch.reorder(i_0, j_0, i_1, j_1, k_0, i_2, j_2, k_1, i_3, j_3) def _create_schedule(mod: IRModule, sch_fn: Callable[[Schedule], None]) -> Schedule: sch = tir.Schedule(mod=mod, debug_mask="all") sch_fn(sch) return sch def _create_tmp_database(tmpdir: str) -> ms.database.JSONDatabase: path_workload = osp.join(tmpdir, "workloads.json") path_tuning_record = osp.join(tmpdir, "tuning_records.json") return ms.database.JSONDatabase(path_workload, path_tuning_record) def _equal_record(a: ms.database.TuningRecord, b: ms.database.TuningRecord): assert str(a.trace) == str(b.trace) assert str(a.run_secs) == str(b.run_secs) # AWAIT(@zxybazh): change to export after fixing "(bool)0" assert str(a.target) == str(b.target) assert tvm.ir.structural_equal(a.workload.mod, b.workload.mod) for arg0, arg1 in zip(a.args_info, b.args_info): assert str(arg0.as_json()) == str(arg1.as_json()) @ms.utils.derived_object class PyMemoryDatabaseDefault(ms.database.PyDatabase): def __init__(self): super().__init__() self.tuning_records_: List[TuningRecord] = [] self.workloads_: List[Workload] = [] def has_workload(self, mod: IRModule) -> bool: for workload in self.workloads_: if tvm.ir.structural_equal(mod, workload.mod): return True def commit_workload(self, mod: IRModule) -> ms.database.Workload: if self.has_workload(mod): for workload in self.workloads_: if tvm.ir.structural_equal(mod, workload.mod): return workload else: workload = ms.database.Workload(mod) self.workloads_.append(workload) return workload def commit_tuning_record(self, record: TuningRecord) -> None: self.tuning_records_.append(record) def get_all_tuning_records(self) -> List[TuningRecord]: return self.tuning_records_ def get_top_k(self, workload: ms.database.Workload, top_k: int) -> List[TuningRecord]: return sorted( list( filter( lambda x: tvm.ir.structural_equal(workload.mod, x.workload.mod), self.tuning_records_, ) ), key=lambda x: sum(x.run_secs) / len(x.run_secs) if x.run_secs else 1e9, )[:top_k] def __len__(self) -> int: return len(self.tuning_records_) @ms.utils.derived_object class PyMemoryDatabaseOverride(ms.database.PyDatabase): def __init__(self): super().__init__() self.tuning_records_: List[TuningRecord] = [] self.workloads_: List[Workload] = [] def has_workload(self, mod: IRModule) -> bool: for workload in self.workloads_: if tvm.ir.structural_equal(mod, workload.mod): return True def commit_workload(self, mod: IRModule) -> ms.database.Workload: if self.has_workload(mod): for workload in self.workloads_: if tvm.ir.structural_equal(mod, workload.mod): return workload else: workload = ms.database.Workload(mod) self.workloads_.append(workload) return workload def commit_tuning_record(self, record: TuningRecord) -> None: self.tuning_records_.append(record) def get_all_tuning_records(self) -> List[TuningRecord]: return self.tuning_records_ def get_top_k(self, workload: ms.database.Workload, top_k: int) -> List[TuningRecord]: return sorted( list( filter( lambda x: tvm.ir.structural_equal(workload.mod, x.workload.mod), self.tuning_records_, ) ), key=lambda x: sum(x.run_secs) / len(x.run_secs) if x.run_secs else 1e9, )[:top_k] def __len__(self) -> int: return len(self.tuning_records_) def query_tuning_record( self, mod: IRModule, target: Target, workload_name: Optional[str] = None ) -> Optional[TuningRecord]: if self.has_workload(mod): records = self.get_top_k(self.commit_workload(mod), 2) if len(records) == 1: return records[0] elif len(records) == 2: return records[1] # return the 2nd best if there are two records return None def query_schedule( self, mod: IRModule, target: Target, workload_name: Optional[str] = None ) -> Optional[Schedule]: record = self.query_tuning_record(mod, target, workload_name) if record is not None: sch = Schedule(record.workload.mod) record.trace.apply_to_schedule(sch, remove_postproc=False) return sch return None def query_ir_module( self, mod: IRModule, target: Target, workload_name: Optional[str] = None ) -> Optional[IRModule]: record = self.query_tuning_record(mod, target, workload_name) if record is not None: sch = Schedule(record.workload.mod) record.trace.apply_to_schedule(sch, remove_postproc=False) return sch.mod return None def test_meta_schedule_tuning_record_round_trip(): mod: IRModule = Matmul with tempfile.TemporaryDirectory() as tmpdir: database = _create_tmp_database(tmpdir) workload = database.commit_workload(mod) record = ms.database.TuningRecord( _create_schedule(mod, _schedule_matmul).trace, workload, [1.5, 2.5, 1.8], tvm.target.Target("llvm"), ms.arg_info.ArgInfo.from_prim_func(func=mod["main"]), ) database.commit_tuning_record(record) new_record = ms.database.TuningRecord.from_json(record.as_json(), workload) _equal_record(record, new_record) def test_meta_schedule_database_create(): with tempfile.TemporaryDirectory() as tmpdir: database = _create_tmp_database(tmpdir) assert osp.exists(database.path_workload) assert osp.exists(database.path_tuning_record) def test_meta_schedule_database_has_workload(): mod: IRModule = Matmul missing_mod: IRModule = MatmulRelu with tempfile.TemporaryDirectory() as tmpdir: database = _create_tmp_database(tmpdir) workload = database.commit_workload(mod) record = ms.database.TuningRecord( _create_schedule(mod, _schedule_matmul).trace, workload, [1.5, 2.5, 1.8], tvm.target.Target("llvm"), ms.arg_info.ArgInfo.from_prim_func(func=mod["main"]), ) database.commit_tuning_record(record) assert len(database) == 1 assert database.has_workload(mod) assert not database.has_workload(missing_mod) def test_meta_schedule_database_add_entry(): mod: IRModule = Matmul with tempfile.TemporaryDirectory() as tmpdir: database = _create_tmp_database(tmpdir) workload = database.commit_workload(mod) record = ms.database.TuningRecord( _create_schedule(mod, _schedule_matmul).trace, workload, [1.5, 2.5, 1.8], tvm.target.Target("llvm"), ms.arg_info.ArgInfo.from_prim_func(func=mod["main"]), ) database.commit_tuning_record(record) assert len(database) == 1 (ret,) = database.get_top_k(workload, 3) _equal_record(ret, record) def test_meta_schedule_database_missing(): mod: IRModule = Matmul mod_2: IRModule = MatmulRelu with tempfile.TemporaryDirectory() as tmpdir: database = _create_tmp_database(tmpdir) workload = database.commit_workload(mod) workload_2 = database.commit_workload(mod_2) record = ms.database.TuningRecord( _create_schedule(mod, _schedule_matmul).trace, workload, [1.5, 2.5, 1.8], tvm.target.Target("llvm"), ms.arg_info.ArgInfo.from_prim_func(func=mod["main"]), ) database.commit_tuning_record(record) ret = database.get_top_k(workload_2, 3) assert len(ret) == 0 def test_meta_schedule_database_sorting(): mod: IRModule = Matmul with tempfile.TemporaryDirectory() as tmpdir: database = _create_tmp_database(tmpdir) token = database.commit_workload(mod) trace = _create_schedule(mod, _schedule_matmul).trace records = [ ms.database.TuningRecord( trace, token, [7.0, 8.0, 9.0], tvm.target.Target("llvm"), ms.arg_info.ArgInfo.from_prim_func(func=mod["main"]), ), ms.database.TuningRecord( trace, token, [1.0, 2.0, 3.0], tvm.target.Target("llvm"), ms.arg_info.ArgInfo.from_prim_func(func=mod["main"]), ), ms.database.TuningRecord( trace, token, [4.0, 5.0, 6.0], tvm.target.Target("llvm"), ms.arg_info.ArgInfo.from_prim_func(func=mod["main"]), ), ms.database.TuningRecord( trace, token, [1.1, 1.2, 600.0], tvm.target.Target("llvm"), ms.arg_info.ArgInfo.from_prim_func(func=mod["main"]), ), ms.database.TuningRecord( trace, token, [1.0, 100.0, 6.0], tvm.target.Target("llvm"), ms.arg_info.ArgInfo.from_prim_func(func=mod["main"]), ), ms.database.TuningRecord( trace, token, [4.0, 9.0, 8.0], tvm.target.Target("llvm"), ms.arg_info.ArgInfo.from_prim_func(func=mod["main"]), ), ] for record in records: database.commit_tuning_record(record) ret = database.get_top_k(token, 2) assert len(ret) == 2 try: _equal_record(ret[0], records[2]) _equal_record(ret[1], records[1]) except AssertionError: _equal_record(ret[0], records[1]) _equal_record(ret[1], records[2]) def test_meta_schedule_database_reload(): mod: IRModule = Matmul with tempfile.TemporaryDirectory() as tmpdir: database = _create_tmp_database(tmpdir) token = database.commit_workload(mod) trace = _create_schedule(mod, _schedule_matmul).trace records = [ ms.database.TuningRecord( trace, token, [7.0, 8.0, 9.0], tvm.target.Target("llvm"), ms.arg_info.ArgInfo.from_prim_func(func=mod["main"]), ), ms.database.TuningRecord( trace, token, [1.0, 2.0, 3.0], tvm.target.Target("llvm"), ms.arg_info.ArgInfo.from_prim_func(func=mod["main"]), ), ms.database.TuningRecord( trace, token, [4.0, 5.0, 6.0], tvm.target.Target("llvm"), ms.arg_info.ArgInfo.from_prim_func(func=mod["main"]), ), ] for record in records: database.commit_tuning_record(record) new_database = ms.database.JSONDatabase( path_workload=database.path_workload, path_tuning_record=database.path_tuning_record, ) token = new_database.commit_workload(mod) ret = new_database.get_top_k(token, 2) assert len(ret) == 2 try: _equal_record(ret[0], records[2]) _equal_record(ret[1], records[1]) except AssertionError: _equal_record(ret[0], records[1]) _equal_record(ret[1], records[2]) def test_meta_schedule_database_union(): mod: IRModule = Matmul target = tvm.target.Target("llvm") arg_info = ms.arg_info.ArgInfo.from_prim_func(func=mod["main"]) db_1 = ms.database.MemoryDatabase() db_2 = ms.database.MemoryDatabase() trace = _create_schedule(mod, _schedule_matmul).trace def query(db): # pylint: disable=invalid-name return db.query_tuning_record(mod=mod, target=target, workload_name="main").run_secs def commit_record(db, run_sec): # pylint: disable=invalid-name db.commit_tuning_record( ms.database.TuningRecord( trace, workload=db.commit_workload(mod), run_secs=[run_sec], target=target, args_info=arg_info, ) ) commit_record(db_1, 1.0) (run_sec,) = query(db_1) assert run_sec.value == 1.0 commit_record(db_2, 0.5) (run_sec,) = query(db_2) assert run_sec.value == 0.5 (run_secs,) = query(ms.database.UnionDatabase(db_1, db_2)) assert run_secs.value == 0.5 (run_secs,) = query(ms.database.OrderedUnionDatabase(db_1, db_2)) assert run_secs.value == 1.0 def test_meta_schedule_pydatabase_default_query(): mod: IRModule = Matmul target = tvm.target.Target("llvm") arg_info = ms.arg_info.ArgInfo.from_prim_func(func=mod["main"]) db = PyMemoryDatabaseDefault() # pylint: disable=invalid-name sch = _create_schedule(mod, _schedule_matmul) trace = sch.trace def query(db, mod, target, kind): # pylint: disable=invalid-name return db.query(mod=mod, target=target, workload_name="main", kind=kind) def commit_record(trace, db, run_sec): # pylint: disable=invalid-name db.commit_tuning_record( ms.database.TuningRecord( trace, workload=db.commit_workload(mod), run_secs=[run_sec], target=target, args_info=arg_info, ) ) commit_record(trace, db, 1.0) record = query(db, mod, target, "record") assert record is not None and record.run_secs[0].value == 1.0 sch_res = query(db, mod, target, "schedule") assert sch_res is not None and tvm.ir.structural_equal(sch_res.mod, sch.mod) mod_res = query(db, mod, target, "ir_module") assert mod_res is not None and tvm.ir.structural_equal(mod_res, sch.mod) commit_record(Schedule(mod).trace, db, 0.2) # Empty Trace record = query(db, mod, target, "record") assert record is not None and record.run_secs[0].value == 0.2 sch_res = query(db, mod, target, "schedule") assert sch_res is not None and tvm.ir.structural_equal(sch_res.mod, mod) mod_res = query(db, mod, target, "ir_module") assert mod_res is not None and tvm.ir.structural_equal(mod_res, mod) def test_meta_schedule_pydatabase_override_query(): mod: IRModule = Matmul target = tvm.target.Target("llvm") arg_info = ms.arg_info.ArgInfo.from_prim_func(func=mod["main"]) db = PyMemoryDatabaseOverride() # pylint: disable=invalid-name sch = _create_schedule(mod, _schedule_matmul) trace = sch.trace def query(db, mod, target, kind): # pylint: disable=invalid-name return db.query(mod=mod, target=target, workload_name="main", kind=kind) def commit_record(trace, db, run_sec): # pylint: disable=invalid-name db.commit_tuning_record( ms.database.TuningRecord( trace, workload=db.commit_workload(mod), run_secs=[run_sec], target=target, args_info=arg_info, ) ) commit_record(trace, db, 1.14) record = query(db, mod, target, "record") assert record is not None and record.run_secs[0].value == 1.14 sch_res = query(db, mod, target, "schedule") assert sch_res is not None and tvm.ir.structural_equal(sch_res.mod, sch.mod) mod_res = query(db, mod, target, "ir_module") assert mod_res is not None and tvm.ir.structural_equal(mod_res, sch.mod) commit_record(Schedule(mod).trace, db, 0.514) # Empty Trace record = query(db, mod, target, "record") assert record is not None and record.run_secs[0].value == 1.14 # Override to 2nd best sch_res = query(db, mod, target, "schedule") assert sch_res is not None and tvm.ir.structural_equal(sch_res.mod, sch.mod) mod_res = query(db, mod, target, "ir_module") assert mod_res is not None and tvm.ir.structural_equal(mod_res, sch.mod) def test_meta_schedule_pydatabase_current(): db = PyMemoryDatabaseDefault() # pylint: disable=invalid-name with db: # pylint: disable=not-context-manager assert ms.database.Database.current() == db if __name__ == "__main__": tvm.testing.main()
https://github.com/zk-ml/tachikoma
tests/python/unittest/test_meta_schedule_feature_extractor.py
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. # pylint: disable=missing-module-docstring,missing-function-docstring,missing-class-docstring import re from typing import List import numpy as np from tvm.meta_schedule import TuneContext from tvm.meta_schedule.feature_extractor import PyFeatureExtractor from tvm.meta_schedule.search_strategy import MeasureCandidate from tvm.meta_schedule.utils import derived_object from tvm.runtime.ndarray import array def test_meta_schedule_feature_extractor(): @derived_object class FancyFeatureExtractor(PyFeatureExtractor): def extract_from( self, context: TuneContext, # pylint: disable = unused-argument candidates: List[MeasureCandidate], # pylint: disable = unused-argument ) -> List[np.ndarray]: return [array(np.random.rand(4, 5))] extractor = FancyFeatureExtractor() features = extractor.extract_from(TuneContext(), []) assert len(features) == 1 assert features[0].shape == (4, 5) def test_meta_schedule_feature_extractor_as_string(): @derived_object class NotSoFancyFeatureExtractor(PyFeatureExtractor): def extract_from( self, context: TuneContext, # pylint: disable = unused-argument candidates: List[MeasureCandidate], # pylint: disable = unused-argument ) -> List[np.ndarray]: return [] feature_extractor = NotSoFancyFeatureExtractor() pattern = re.compile(r"meta_schedule.NotSoFancyFeatureExtractor\(0x[a-f|0-9]*\)") assert pattern.match(str(feature_extractor)) if __name__ == "__main__": test_meta_schedule_feature_extractor() test_meta_schedule_feature_extractor_as_string()
https://github.com/zk-ml/tachikoma
tests/python/unittest/test_meta_schedule_feature_extractor_per_store_feature.py
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. # pylint: disable=missing-module-docstring,missing-function-docstring,missing-class-docstring import sys from typing import Callable, List import pytest import tvm import tvm.testing from numpy.testing import assert_allclose from tvm import meta_schedule as ms from tvm import te, tir from tvm.script import tir as T N_FEATURES = 164 @T.prim_func def matmul( A: T.Buffer[(512, 512), "float32"], B: T.Buffer[(512, 512), "float32"], C: T.Buffer[(512, 512), "float32"], ) -> None: # function attr dict T.func_attr({"global_symbol": "main", "tir.noalias": True}) # body # with T.block("root") for i0, i1, i2 in T.grid(512, 512, 512): with T.block("C"): i, j, k = T.axis.remap("SSR", [i0, i1, i2]) T.reads(C[i, j], A[i, k], B[k, j]) T.writes(C[i, j]) with T.init(): C[i, j] = T.float32(0) C[i, j] = C[i, j] + A[i, k] * B[k, j] # pylint: disable=invalid-name,no-member,line-too-long,too-many-nested-blocks,no-self-argument # fmt: off # from tvm.script import tir as T @tvm.script.ir_module class LayoutTransform: @T.prim_func def main(placeholder: T.Buffer[(1, 16, 7, 7, 32), "float32"], placeholder_1: T.Buffer[(25088,), "float32"], T_layout_trans: T.Buffer[(1, 1, 7, 7, 512), "float32"]) -> None: # function attr dict T.func_attr({"tir.noalias": True, "global_symbol": "main"}) # body # with T.block("root") for i0_i1_i2_i3_i4_fused in T.parallel(25088, annotations={"pragma_auto_unroll_max_step":64, "pragma_unroll_explicit":1}): with T.block("T_layout_trans_1"): ax0 = T.axis.spatial(1, 0) ax1 = T.axis.spatial(1, 0) ax2 = T.axis.spatial(7, i0_i1_i2_i3_i4_fused // 3584) ax3 = T.axis.spatial(7, i0_i1_i2_i3_i4_fused % 3584 // 512) ax4 = T.axis.spatial(512, i0_i1_i2_i3_i4_fused % 512) T.reads(placeholder[0, (ax4 * 49 + ax2 * 7 + ax3) % 25088 // 1568, (ax2 * 7 + ax3) % 49 // 7, ax3 % 7, (ax4 * 49 + ax2 * 7 + ax3) % 1568 // 49], placeholder_1[(ax4 * 49 + ax2 * 7 + ax3) % 25088]) T.writes(T_layout_trans[ax0, ax1, ax2, ax3, ax4]) T_layout_trans[ax0, ax1, ax2, ax3, ax4] = T.if_then_else(ax0 < 1 and ax1 * 512 + ax4 < 512 and ax2 < 7 and ax3 < 7, T.Select(T.float32(0) < T.if_then_else(0 < 1 and ((ax1 * 512 + ax4) * 49 + ax2 * 7 + ax3) % 25088 % 25088 // 49 < 512 and ((ax1 * 512 + ax4) * 49 + ax2 * 7 + ax3) % 25088 % 49 // 7 < 7 and ((ax1 * 512 + ax4) * 49 + ax2 * 7 + ax3) % 25088 % 7 < 7, placeholder[0, ((ax1 * 512 + ax4) * 49 + ax2 * 7 + ax3) % 25088 % 25088 // 49 // 32, ((ax1 * 512 + ax4) * 49 + ax2 * 7 + ax3) % 25088 % 49 // 7, ((ax1 * 512 + ax4) * 49 + ax2 * 7 + ax3) % 25088 % 7, ((ax1 * 512 + ax4) * 49 + ax2 * 7 + ax3) % 25088 % 25088 // 49 % 32], T.float32(0), dtype="float32"), T.if_then_else(0 < 1 and ((ax1 * 512 + ax4) * 49 + ax2 * 7 + ax3) % 25088 % 25088 // 49 < 512 and ((ax1 * 512 + ax4) * 49 + ax2 * 7 + ax3) % 25088 % 49 // 7 < 7 and ((ax1 * 512 + ax4) * 49 + ax2 * 7 + ax3) % 25088 % 7 < 7, placeholder[0, ((ax1 * 512 + ax4) * 49 + ax2 * 7 + ax3) % 25088 % 25088 // 49 // 32, ((ax1 * 512 + ax4) * 49 + ax2 * 7 + ax3) % 25088 % 49 // 7, ((ax1 * 512 + ax4) * 49 + ax2 * 7 + ax3) % 25088 % 7, ((ax1 * 512 + ax4) * 49 + ax2 * 7 + ax3) % 25088 % 25088 // 49 % 32], T.float32(0), dtype="float32"), T.if_then_else(0 < 1 and ((ax1 * 512 + ax4) * 49 + ax2 * 7 + ax3) % 25088 % 25088 // 49 < 512 and ((ax1 * 512 + ax4) * 49 + ax2 * 7 + ax3) % 25088 % 49 // 7 < 7 and ((ax1 * 512 + ax4) * 49 + ax2 * 7 + ax3) % 25088 % 7 < 7, placeholder[0, ((ax1 * 512 + ax4) * 49 + ax2 * 7 + ax3) % 25088 % 25088 // 49 // 32, ((ax1 * 512 + ax4) * 49 + ax2 * 7 + ax3) % 25088 % 49 // 7, ((ax1 * 512 + ax4) * 49 + ax2 * 7 + ax3) % 25088 % 7, ((ax1 * 512 + ax4) * 49 + ax2 * 7 + ax3) % 25088 % 25088 // 49 % 32], T.float32(0), dtype="float32") * placeholder_1[((ax1 * 512 + ax4) * 49 + ax2 * 7 + ax3) % 25088]), T.float32(0), dtype="float32") # fmt: on # pylint: enable=invalid-name,no-member,line-too-long,too-many-nested-blocks,no-self-argument def _make_context(target) -> ms.TuneContext: return ms.TuneContext( target=target, num_threads=1, ) def _make_candidate(f_sch: Callable[[], tir.Schedule]) -> ms.MeasureCandidate: return ms.MeasureCandidate(sch=f_sch(), args_info=[]) def _feature_names( # pylint: disable=invalid-name buffers_per_store: int = 5, arith_intensity_curve_num_samples: int = 10, ) -> List[str]: result = [ "float_mad", "float_addsub", "float_mul", "float_divmod", "float_cmp", "float_mathfunc", "float_otherfunc", "int_mad", "int_addsub", "int_mul", "int_divmod", "int_cmp", "int_mathfunc", "int_otherfunc", "bool_op", "select_op", "vec_num", "vec_prod", "vec_len", "vec_type.kPosNone", "vec_type.kPosInnerSpatial", "vec_type.kPosMiddleSpatial", "vec_type.kPosOuterSpatial", "vec_type.kPosInnerReduce", "vec_type.kPosMiddleReduce", "vec_type.kPosOuterReduce", "vec_type.kPosMixed", "unroll_num", "unroll_prod", "unroll_len", "unroll_type.kPosNone", "unroll_type.kPosInnerSpatial", "unroll_type.kPosMiddleSpatial", "unroll_type.kPosOuterSpatial", "unroll_type.kPosInnerReduce", "unroll_type.kPosMiddleReduce", "unroll_type.kPosOuterReduce", "unroll_type.kPosMixed", "parallel_num", "parallel_prod", "parallel_len", "parallel_type.kPosNone", "parallel_type.kPosInnerSpatial", "parallel_type.kPosMiddleSpatial", "parallel_type.kPosOuterSpatial", "parallel_type.kPosInnerReduce", "parallel_type.kPosMiddleReduce", "parallel_type.kPosOuterReduce", "parallel_type.kPosMixed", "is_gpu", "blockIdx_x_len", "blockIdx_y_len", "blockIdx_z_len", "threadIdx_x_len", "threadIdx_y_len", "threadIdx_z_len", "vthread_len", ] for i in range(buffers_per_store): result.extend( f"B{i}.{s}" for s in [ "acc_type.kRead", "acc_type.kWrite", "acc_type.kReadWrite", "bytes", "unique_bytes", "lines", "unique_lines", "reuse_type.kLoopMultipleRead", "reuse_type.kSerialMultipleReadWrite", "reuse_type.kNoReuse", "reuse_dis_iter", "reuse_dis_bytes", "reuse_ct", "bytes_d_reuse_ct", "unique_bytes_d_reuse_ct", "lines_d_reuse_ct", "unique_lines_d_reuse_ct", "stride", ] ) result.extend(f"arith_intensity_curve_{i}" for i in range(arith_intensity_curve_num_samples)) result.extend( [ "alloc_size", "alloc_prod", "alloc_outer_prod", "alloc_inner_prod", "outer_prod", "num_loops", "auto_unroll_max_step", ] ) # 57 + 18 * 5 + 10 + 4 + 3 assert len(result) == N_FEATURES return result def _zip_feature(feature, names): assert feature.ndim == 1 assert feature.shape[0] == N_FEATURES assert len(names) == N_FEATURES return list(zip(names, feature)) def _print_feature(feature, st, ed): # pylint: disable=invalid-name named_feature = _zip_feature(feature, _feature_names()) for k, v in named_feature[st:ed]: print("\t", k, v) def test_cpu_matmul(): def _create_schedule(): func = matmul sch = tir.Schedule(func, debug_mask="all") block = sch.get_block("C") i, j, k = sch.get_loops(block) i_o, i_i = sch.split(i, factors=[None, 16]) # outer: 32 j_o, j_i = sch.split(j, factors=[None, 8]) # outer: 64 sch.reorder(i_o, j_o, k, j_i, i_i) sch.vectorize(j_i) sch.parallel(i_o) sch.parallel(j_o) sch.unroll(k) return sch extractor = ms.feature_extractor.PerStoreFeature() (feature,) = extractor.extract_from( _make_context(tvm.target.Target("llvm")), candidates=[_make_candidate(_create_schedule)], ) feature = feature.numpy() assert feature.shape == (1, N_FEATURES) f = feature[0] # Group 1.1: arith assert_allclose( actual=f[0:16], # fmt: off desired=[ # float math ops 0, 27, 27, 0, 0, 0, 0, # int math ops 0, 29, 29, 0, 0, 0, 0, # bool/select ops 0, 0, ], # fmt: on rtol=1e-5, atol=1e-5, ) # Group 1.2: vectorize assert_allclose( actual=f[16:27], desired=[1.0, 3.169924, 3.169924, 0, 0, 0, 0, 0, 0, 0, 1], rtol=1e-5, atol=1e-5, ) # Group 1.3: unroll assert_allclose( actual=f[27:38], desired=[1.0, 9.002815, 9.002815, 0, 0, 0, 0, 0, 0, 0, 1], rtol=1e-5, atol=1e-5, ) # Group 1.4: parallel assert_allclose( actual=f[38:49], desired=[1.58496, 11.0007, 6.022368, 0, 0, 0, 0, 0, 0, 0, 1], rtol=1e-5, atol=1e-5, ) # Group 1.5: is_gpu, blockIdx.x/y/z, threadIdx.x/y/z, vthread assert_allclose( actual=f[49:57], desired=[0.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0], rtol=1e-5, atol=1e-5, ) # Group 2.1: Buffer A assert_allclose( actual=f[57:75], desired=[ 1, 0, 0, 29, 20, 27, 14, 1, 0, 0, 4.087463, 7.0552826, 3.169925, 26, 17, 24, 11.0007038, 9.002815, ], rtol=1e-5, atol=1e-5, ) # Group 2.2: Buffer C assert_allclose( actual=f[75:93], desired=[ 0.0, 0.0, 1.0, 29.0, 20.000001907348633, 27.0, 14.00008773803711, 1.0, 0.0, 0.0, 7.011227130889893, 9.250298500061035, 9.002815246582031, 20.000001907348633, 11.000703811645508, 18.0000057220459, 5.044394016265869, 9.002815246582031, ], rtol=1e-5, atol=1e-5, ) # Group 2.3: Buffer B assert_allclose( actual=f[93:111], desired=[ 1.0, 0.0, 0.0, 29.0, 20.000001907348633, 19.000001907348633, 14.00008773803711, 1.0, 0.0, 0.0, 1.0, 3.700439691543579, 4.087462902069092, 25.0, 16.000022888183594, 15.000043869018555, 10.001408194392809, 0.0, ], rtol=1e-5, atol=1e-5, ) # Group 2.4: Dummy padding assert_allclose( actual=f[111:129], desired=[0.0] * 18, rtol=1e-5, atol=1e-5, ) # Group 2.5: Dummy padding assert_allclose( actual=f[129:147], desired=[0.0] * 18, rtol=1e-5, atol=1e-5, ) # Group 3: Arithmetic intensity # arithmetic intensity = flops/bytes touched = 2*512*512*512/(3 * 4 * 512*512) # add and multiply ^ 3 arrays ^ ^ 4 bytes per f32 # = 85.3 but log2 is used so values should be around 6.4 assert_allclose( actual=f[147:157], desired=[ 3.812599, 4.464822, 4.912349, 5.253426, 5.529086, 5.76043, 5.959752, 6.134849, 6.290977, 6.431846, ], rtol=1e-5, atol=1e-5, ) # Group 4 & 5 assert_allclose( actual=f[157:164], desired=[ 20.000001907348633, 18.0000057220459, 1.0, 27.0, 27.0, 2.5849626064300537, 0.0, ], rtol=1e-5, atol=1e-5, ) def test_cpu_fusion(): # pylint: disable=all @T.prim_func def func(a: T.handle, b: T.handle, c: T.handle) -> None: A = T.match_buffer(a, [64, 32], dtype="float32") B = T.match_buffer(b, [64, 32], dtype="float32") C = T.match_buffer(c, [64, 32], dtype="float32") for i, j in T.grid(64, 32): # type: ignore with T.block(): T.reads([A[i, j], B[i, j]]) # type: ignore T.writes([B[i, j], C[i, j]]) # type: ignore with T.block("B"): T.reads([A[i, j]]) # type: ignore T.writes([B[i, j]]) # type: ignore B[i, j] = A[i, j] # type: ignore with T.block("C"): T.reads([B[i, j]]) # type: ignore T.writes([C[i, j]]) # type: ignore C[i, j] = B[i, j] # type: ignore # pylint: enable=all def _create_schedule(): return tir.Schedule(func, debug_mask="all") extractor = ms.feature_extractor.PerStoreFeature() (feature,) = extractor.extract_from( _make_context(tvm.target.Target("llvm")), candidates=[_make_candidate(_create_schedule)], ) feature = feature.numpy() assert feature.shape == (2, N_FEATURES) ## Features for BufferStore(B) f = feature[0] # Group 1.1: arith assert_allclose( actual=f[0:16], # fmt: off desired=[0.0] * 16, # fmt: on rtol=1e-5, atol=1e-5, ) # Group 1.2: vectorize assert_allclose( actual=f[16:27], desired=[0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], rtol=1e-5, atol=1e-5, ) # Group 1.3: unroll assert_allclose( actual=f[27:38], desired=[0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], rtol=1e-5, atol=1e-5, ) # Group 1.4: parallel assert_allclose( actual=f[38:49], desired=[0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], rtol=1e-5, atol=1e-5, ) # Group 1.5: is_gpu, blockIdx.x/y/z, threadIdx.x/y/z, vthread assert_allclose( actual=f[49:57], desired=[0.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0], rtol=1e-5, atol=1e-5, ) # Group 2.1: Buffer A assert_allclose( actual=f[57:75], desired=[ 1.0, 0.0, 0.0, 13.000176429748535, 13.000176429748535, 7.011227130889893, 7.011227130889893, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 14.00008773803711, 14.00008773803711, 8.005624771118164, 8.005624771118164, 1.0, ], rtol=1e-5, atol=1e-5, ) # Group 2.2: Buffer B assert_allclose( actual=f[75:93], desired=[ 0.0, 1.0, 0.0, 13.000176429748535, 13.000176429748535, 7.011227130889893, 7.011227130889893, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 14.00008773803711, 14.00008773803711, 8.005624771118164, 8.005624771118164, 1.0, ], rtol=1e-5, atol=1e-5, ) # Group 2.3: Dummy padding assert_allclose( actual=f[93:111], desired=[0.0] * 18, rtol=1e-5, atol=1e-5, ) # Group 2.4: Dummy padding assert_allclose( actual=f[111:129], desired=[0.0] * 18, rtol=1e-5, atol=1e-5, ) # Group 2.5: Dummy padding assert_allclose( actual=f[129:147], desired=[0.0] * 18, rtol=1e-5, atol=1e-5, ) # Group 3: Arithmetic intensity assert_allclose( actual=f[147:157], desired=[0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], rtol=1e-5, atol=1e-5, ) # Group 4 & 5 assert_allclose( actual=f[157:164], desired=[ 13.000176, 11.000703811645508, 1.0, 11.000703811645508, 11.000703811645508, 1.5849624872207642, 0.0, ], rtol=1e-5, atol=1e-5, ) ## Features for BufferStore(C) f = feature[1] # Group 1.1: arith assert_allclose( actual=f[0:16], # fmt: off desired=[0.0] * 16, # fmt: on rtol=1e-5, atol=1e-5, ) # Group 1.2: vectorize assert_allclose( actual=f[16:27], desired=[0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], rtol=1e-5, atol=1e-5, ) # Group 1.3: unroll assert_allclose( actual=f[27:38], desired=[0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], rtol=1e-5, atol=1e-5, ) # Group 1.4: parallel assert_allclose( actual=f[38:49], desired=[0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], rtol=1e-5, atol=1e-5, ) # Group 1.5: is_gpu, blockIdx.x/y/z, threadIdx.x/y/z, vthread assert_allclose( actual=f[49:57], desired=[0.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0], rtol=1e-5, atol=1e-5, ) # Group 2.1: Buffer B assert_allclose( actual=f[57:75], desired=[ 1.0, 0.0, 0.0, 13.000176429748535, 13.000176429748535, 7.011227130889893, 7.011227130889893, 0.0, 1.0, 0.0, 1.0, 4.087462902069092, 1.0, 13.000176429748535, 13.000176429748535, 7.011227130889893, 7.011227130889893, 1.0, ], rtol=1e-5, atol=1e-5, ) # Group 2.2: Buffer C assert_allclose( actual=f[75:93], desired=[ 0.0, 1.0, 0.0, 13.000176429748535, 13.000176429748535, 7.011227130889893, 7.011227130889893, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 14.00008773803711, 14.00008773803711, 8.005624771118164, 8.005624771118164, 1.0, ], rtol=1e-5, atol=1e-5, ) # Group 2.3: Dummy padding assert_allclose( actual=f[93:111], desired=[0.0] * 18, rtol=1e-5, atol=1e-5, ) # Group 2.4: Dummy padding assert_allclose( actual=f[111:129], desired=[0.0] * 18, rtol=1e-5, atol=1e-5, ) # Group 2.5: Dummy padding assert_allclose( actual=f[129:147], desired=[0.0] * 18, rtol=1e-5, atol=1e-5, ) # Group 3: Arithmetic intensity assert_allclose( actual=f[147:157], desired=[0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], rtol=1e-5, atol=1e-5, ) # Group 4 & 5 assert_allclose( actual=f[157:164], desired=[ 13.000176429748535, 11.000703811645508, 1.0, 11.000703811645508, 11.000703811645508, 1.5849624872207642, 0.0, ], rtol=1e-5, atol=1e-5, ) def test_gpu(): def _create_schedule(): func = matmul sch = tir.Schedule(func, debug_mask="all") c = sch.get_block("C") c_local = sch.cache_write(c, 0, "local") i, j, k = sch.get_loops(c) # pylint: disable=invalid-name i0, i1, i2, i3, i4 = sch.split(i, factors=[None, 1, 16, 32, 1]) # outer: 1 j0, j1, j2, j3, j4 = sch.split(j, factors=[None, 4, 1, 1, 16]) # outer: 8 k0, k1, k2 = sch.split(k, factors=[None, 1, 2]) # outer: 256 # pylint: enable=invalid-name # fmt: off sch.reorder( i0, j0, # S i1, j1, # S i2, j2, # S k0, # R k1, # R i3, j3, # S k2, # R i4, j4, # S ) # fmt: on # thread binding i0_j0 = sch.fuse(i0, j0) i1_j1 = sch.fuse(i1, j1) i2_j2 = sch.fuse(i2, j2) sch.bind(i0_j0, "blockIdx.x") sch.bind(i1_j1, "vthread.x") sch.bind(i2_j2, "threadIdx.x") # fusion sch.reverse_compute_at(c_local, i2_j2) # cache read 'A' a_shared = sch.cache_read(c, 1, "shared") sch.compute_at(a_shared, k0) _, _, _, _, a_i, a_j = sch.get_loops(a_shared) a_ij = sch.fuse(a_i, a_j) _, a_j = sch.split(a_ij, factors=[None, 16]) # outer: 64 sch.bind(a_j, "threadIdx.x") # cache read 'B' b_shared = sch.cache_read(c, 2, "shared") sch.compute_at(b_shared, k0) _, _, _, _, b_i, b_j = sch.get_loops(b_shared) b_ij = sch.fuse(b_i, b_j) _, b_j = sch.split(b_ij, factors=[None, 16]) # outer: 8 sch.bind(b_j, "threadIdx.x") # auto unroll sch.annotate(i0_j0, "pragma_auto_unroll_max_step", tir.IntImm("int32", 1024)) sch.annotate(i0_j0, "pragma_unroll_explicit", tir.IntImm("int32", 1)) return sch extractor = ms.feature_extractor.PerStoreFeature() (feature,) = extractor.extract_from( _make_context(tvm.target.Target("cuda")), candidates=[_make_candidate(_create_schedule)], ) feature = feature.numpy() assert feature.shape == (4, N_FEATURES) ### Check feature[0]: BufferStore(A_shared) <= A[...] f = feature[0] # Group 1.1: arith assert_allclose( actual=f[0:16], desired=[ 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 24.000000085991324, 24.000000085991324, 24.000000085991324, 0.0, 0.0, 0.0, 0.0, 0.0, ], rtol=1e-5, atol=1e-5, ) # Group 1.2: vectorize assert_allclose( actual=f[16:27], desired=[0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], rtol=1e-5, atol=1e-5, ) # Group 1.3: unroll assert_allclose( actual=f[27:38], desired=[0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], rtol=1e-5, atol=1e-5, ) # Group 1.4: parallel assert_allclose( actual=f[38:49], desired=[0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], rtol=1e-5, atol=1e-5, ) # Group 1.5: is_gpu, blockIdx.x/y/z, threadIdx.x/y/z, vthread assert_allclose( actual=f[49:57], desired=[1.0, 3.169925001442312, 1.0, 1.0, 4.087462841250339, 1.0, 1.0, 2.321928094887362], rtol=1e-5, atol=1e-5, ) # Group 2.1: Buffer A assert_allclose( actual=f[57:75], desired=[ 1.0, 0.0, 0.0, 25.000000042995662, 20.000001375860553, 23.00000017198264, 14.000088052430122, 1.0, 0.0, 0.0, 18.00000550343433, 20.00562591970089, 2.321928094887362, 23.00000017198264, 18.00000550343433, 21.000000687930438, 12.0003521774803, 12.0003521774803, ], rtol=1e-5, atol=1e-5, ) # Group 2.2: Buffer A.shared assert_allclose( actual=f[75:93], desired=[ 0.0, 1.0, 0.0, 25.000000042995662, 12.0003521774803, 23.00000017198264, 9.002815015607053, 1.0, 0.0, 0.0, 6.022367813028454, 11.98049663618346, 8.005624549193879, 17.000011006847668, 4.087462841250339, 15.000044026886828, 1.584962500721156, 4.087462841250339, ], rtol=1e-5, atol=1e-5, ) # Group 2.3: Dummy padding assert_allclose( actual=f[93:111], desired=[ 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, ], rtol=1e-5, atol=1e-5, ) # Group 2.4: Dummy padding assert_allclose( actual=f[111:129], desired=[ 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, ], rtol=1e-5, atol=1e-5, ) # Group 2.5: Dummy padding assert_allclose( actual=f[129:147], desired=[ 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, ], rtol=1e-5, atol=1e-5, ) # Group 3: Arithmetic intensity assert_allclose( actual=f[147:157], desired=[0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], rtol=1e-5, atol=1e-5, ) # Group 4 & 5 assert_allclose( actual=f[157:164], desired=[ 12.0003521774803, 27.000000010748916, 17.000011006847668, 6.022367813028454, 23.00000017198264, 2.584962500721156, 10.001408, ], rtol=1e-5, atol=1e-5, ) ### Check feature[1]: BufferStore(B_shared) <= B[...] f = feature[1] # Group 1.1: arith assert_allclose( actual=f[0:16], desired=[ 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 21.584962959341485, 21.584962959341485, 21.000000687930438, 0.0, 0.0, 0.0, 0.0, 0.0, ], rtol=1e-5, atol=1e-5, ) # Group 1.2: vectorize assert_allclose( actual=f[16:27], desired=[0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], rtol=1e-5, atol=1e-5, ) # Group 1.3: unroll assert_allclose( actual=f[27:38], desired=[0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], rtol=1e-5, atol=1e-5, ) # Group 1.4: parallel assert_allclose( actual=f[38:49], desired=[0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], rtol=1e-5, atol=1e-5, ) # Group 1.5: is_gpu, blockIdx.x/y/z, threadIdx.x/y/z, vthread assert_allclose( actual=f[49:57], desired=[1.0, 3.169925001442312, 1.0, 1.0, 4.087462841250339, 1.0, 1.0, 2.321928094887362], rtol=1e-5, atol=1e-5, ) # Group 2.1: Buffer B assert_allclose( actual=f[57:75], desired=[ 1.0, 0.0, 0.0, 22.00000034396526, 20.000001375860553, 20.000001375860553, 14.000088052430122, 1.0, 0.0, 0.0, 15.000044026886828, 20.17555076886471, 2.321928094887362, 20.000001375860553, 18.00000550343433, 18.00000550343433, 12.0003521774803, 4.087462841250339, ], rtol=1e-5, atol=1e-5, ) # Group 2.2: Buffer B.shared assert_allclose( actual=f[75:93], desired=[ 0.0, 1.0, 0.0, 22.00000034396526, 9.002815015607053, 20.000001375860553, 3.169925001442312, 1.0, 0.0, 0.0, 3.169925001442312, 9.61654884377899, 8.005624549193879, 14.000088052430122, 1.584962500721156, 12.0003521774803, 0.044394119358453436, 4.087462841250339, ], rtol=1e-5, atol=1e-5, ) # Group 2.3: Dummy padding assert_allclose( actual=f[93:111], desired=[ 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, ], rtol=1e-5, atol=1e-5, ) # Group 2.4: Dummy padding assert_allclose( actual=f[111:129], desired=[ 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, ], rtol=1e-5, atol=1e-5, ) # Group 2.5: Dummy padding assert_allclose( actual=f[129:147], desired=[ 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, ], rtol=1e-5, atol=1e-5, ) # Group 3: Arithmetic intensity assert_allclose( actual=f[147:157], desired=[0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], rtol=1e-5, atol=1e-5, ) # Group 4 & 5 assert_allclose( actual=f[157:164], desired=[ 9.002815015607053, 24.000000085991324, 17.000011006847668, 3.169925001442312, 20.000001375860553, 2.584962500721156, 10.001408, ], rtol=1e-5, atol=1e-5, ) ### Check feature[2]: BufferStore(C_local) <= C_local[...] + A_shared[...] * B_shared[...] f = feature[2] # Group 1.1: arith assert_allclose( actual=f[0:16], desired=[ 0.0, 27.000000010748916, 27.000000010748916, 0.0, 0.0, 0.0, 0.0, 0.0, 28.000000005374456, 28.000000005374456, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, ], rtol=1e-5, atol=1e-5, ) # Group 1.2: vectorize assert_allclose( actual=f[16:27], desired=[0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], rtol=1e-5, atol=1e-5, ) # Group 1.3: unroll assert_allclose( actual=f[27:38], desired=[0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], rtol=1e-5, atol=1e-5, ) # Group 1.4: parallel assert_allclose( actual=f[38:49], desired=[0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], rtol=1e-5, atol=1e-5, ) # Group 1.5: is_gpu, blockIdx.x/y/z, threadIdx.x/y/z, vthread assert_allclose( actual=f[49:57], desired=[1.0, 3.169925001442312, 1.0, 1.0, 4.087462841250339, 1.0, 1.0, 2.321928094887362], rtol=1e-5, atol=1e-5, ) # Group 2.1: Buffer B.shared assert_allclose( actual=f[57:75], desired=[ 1.0, 0.0, 0.0, 29.00000000268723, 9.002815015607053, 23.00000017198264, 3.169925001442312, 1.0, 0.0, 0.0, 5.044394119358453, 7.651051691178929, 5.044394119358453, 24.000000085991324, 4.087462841250339, 18.00000550343433, 0.32192809488736235, 1.0, ], rtol=1e-5, atol=1e-5, ) # Group 2.2: Buffer C.local assert_allclose( actual=f[75:93], desired=[ 0.0, 0.0, 1.0, 29.00000000268723, 11.000704269011246, 23.00000017198264, 5.044394119358453, 1.0, 0.0, 0.0, 4.087462841250339, 7.05528243550119, 1.584962500721156, 28.000000005374456, 10.001408194392809, 22.00000034396526, 4.087462841250339, 1.0, ], rtol=1e-5, atol=1e-5, ) # Group 2.3: Buffer A.shared assert_allclose( actual=f[93:111], desired=[ 1.0, 0.0, 0.0, 29.00000000268723, 12.0003521774803, 19.00000275171979, 9.002815015607053, 1.0, 0.0, 0.0, 1.0, 3.700439718141092, 4.087462841250339, 25.000000042995662, 8.005624549193879, 15.000044026886828, 5.044394119358453, 0.0, ], rtol=1e-5, atol=1e-5, ) # Group 2.4: Dummy padding assert_allclose( actual=f[111:129], desired=[ 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, ], rtol=1e-5, atol=1e-5, ) # Group 2.5: Dummy padding assert_allclose( actual=f[129:147], desired=[ 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, ], rtol=1e-5, atol=1e-5, ) # Group 3: Arithmetic intensity # Arithmetic intensity is high here because of repeated use of a shared # buffer. Multiple accesses to the same memory location are counted as a # single byte, skewing these numbers towards higher intensity. assert_allclose( actual=f[147:157], desired=[ 11.98533, 12.977811, 13.562714, 13.977722, 14.299632, 14.562654, 14.785038, 14.977677, 15.147597, 15.299596, ], rtol=1e-5, atol=1e-5, ) # Group 4 & 5 assert_allclose( actual=f[157:164], desired=[ 11.000704269011246, 18.00000550343433, 9.002815015607053, 18.00000550343433, 27.000000010748916, 3.0, 10.001408, ], rtol=1e-5, atol=1e-5, ) ### Check feature[3]: BufferStore(C) <= C_local[...] f = feature[3] # Group 1.1: arith assert_allclose( actual=f[0:16], desired=[0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], rtol=1e-5, atol=1e-5, ) # Group 1.2: vectorize assert_allclose( actual=f[16:27], desired=[0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], rtol=1e-5, atol=1e-5, ) # Group 1.3: unroll assert_allclose( actual=f[27:38], desired=[0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], rtol=1e-5, atol=1e-5, ) # Group 1.4: parallel assert_allclose( actual=f[38:49], desired=[0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], rtol=1e-5, atol=1e-5, ) # Group 1.5: is_gpu, blockIdx.x/y/z, threadIdx.x/y/z, vthread assert_allclose( actual=f[49:57], desired=[1.0, 3.169925001442312, 1.0, 1.0, 4.087462841250339, 1.0, 1.0, 2.321928094887362], rtol=1e-5, atol=1e-5, ) # Group 2.1: Buffer C assert_allclose( actual=f[57:75], desired=[ 0.0, 1.0, 0.0, 20.000001375860553, 20.000001375860553, 14.000088052430122, 14.000088052430122, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 21.000000687930438, 21.000000687930438, 15.000044026886828, 15.000044026886828, 1.0, ], rtol=1e-5, atol=1e-5, ) # Group 2.2: Buffer C.local assert_allclose( actual=f[75:93], desired=[ 1.0, 0.0, 0.0, 20.000001375860553, 11.000704269011246, 14.000088052430122, 5.044394119358453, 1.0, 0.0, 0.0, 9.002815015607053, 12.0003521774803, 4.087462841250339, 16.00002201361136, 7.011227255423254, 10.001408194392809, 1.584962500721156, 1.0, ], rtol=1e-5, atol=1e-5, ) # Group 2.3: Dummy padding assert_allclose( actual=f[93:111], desired=[ 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, ], rtol=1e-5, atol=1e-5, ) # Group 2.4: Dummy padding assert_allclose( actual=f[111:129], desired=[ 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, ], rtol=1e-5, atol=1e-5, ) # Group 2.5: Dummy padding assert_allclose( actual=f[129:147], desired=[ 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, ], rtol=1e-5, atol=1e-5, ) # Group 3: Arithmetic intensity assert_allclose( actual=f[147:157], desired=[0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], rtol=1e-5, atol=1e-5, ) # Group 4 & 5 assert_allclose( actual=f[157:164], desired=[ 20.000001375860553, 18.00000550343433, 1.0, 18.00000550343433, 18.00000550343433, 2.584962500721156, 10.001408, ], rtol=1e-5, atol=1e-5, ) def test_cpu_layout_transform(): extractor = ms.feature_extractor.PerStoreFeature() (feature,) = extractor.extract_from( _make_context(tvm.target.Target("llvm")), candidates=[_make_candidate(lambda: tir.Schedule(LayoutTransform))], ) @T.prim_func def negative_extent(A: T.Buffer[(1,), "float32"]): for j in range(0, -1): A[j] = A[j] + 1.0 def test_negative_extent(): extractor = ms.feature_extractor.PerStoreFeature() (features,) = extractor.extract_from( _make_context(tvm.target.Target("llvm")), candidates=[_make_candidate(lambda: tir.Schedule(negative_extent))], ) named_features = dict(zip(_feature_names(), list(features.numpy()[0, :]))) assert named_features["B0.unique_bytes"] == 0 if __name__ == "__main__": tvm.testing.main()
https://github.com/zk-ml/tachikoma
tests/python/unittest/test_meta_schedule_measure_callback.py
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. # pylint: disable=missing-module-docstring,missing-function-docstring,missing-class-docstring import re import tempfile from typing import List import pytest import tvm from tvm import meta_schedule as ms from tvm.script import tir as T from tvm.tir.schedule import Schedule # pylint: disable=invalid-name,no-member,line-too-long,too-many-nested-blocks,no-self-argument, # fmt: off @tvm.script.ir_module class Matmul: @T.prim_func def main(a: T.handle, b: T.handle, c: T.handle) -> None: T.func_attr({"global_symbol": "main"}) A = T.match_buffer(a, (1024, 1024), "float32") B = T.match_buffer(b, (1024, 1024), "float32") C = T.match_buffer(c, (1024, 1024), "float32") for i, j, k in T.grid(1024, 1024, 1024): with T.block("matmul"): vi, vj, vk = T.axis.remap("SSR", [i, j, k]) with T.init(): C[vi, vj] = 0.0 C[vi, vj] = C[vi, vj] + A[vi, vk] * B[vk, vj] # fmt: on # pylint: enable=invalid-name,no-member,line-too-long,too-many-nested-blocks,no-self-argument def test_meta_schedule_measure_callback(): @ms.derived_object class FancyMeasureCallback(ms.measure_callback.PyMeasureCallback): def apply( self, task_scheduler: ms.task_scheduler.TaskScheduler, task_id: int, measure_candidates: List[ms.MeasureCandidate], builder_results: List[ms.builder.BuilderResult], runner_results: List[ms.runner.RunnerResult], ) -> None: assert len(measure_candidates) == 1 tvm.ir.assert_structural_equal(measure_candidates[0].sch.mod, Matmul) assert ( len(builder_results) == 1 and builder_results[0].error_msg is None and builder_results[0].artifact_path == "test_build" ) assert ( len(runner_results) == 1 and runner_results[0].error_msg is None and len(runner_results[0].run_secs) == 2 ) measure_callback = FancyMeasureCallback() measure_callback.apply( ms.task_scheduler.RoundRobin(), 0, [ms.MeasureCandidate(Schedule(Matmul), None)], [ms.builder.BuilderResult("test_build", None)], [ms.runner.RunnerResult([1.0, 2.1], None)], ) def test_meta_schedule_measure_callback_fail(): @ms.derived_object class FailingMeasureCallback(ms.measure_callback.PyMeasureCallback): def apply( self, task_scheduler: ms.task_scheduler.TaskScheduler, task_id: int, measure_candidates: List[ms.MeasureCandidate], builder_results: List[ms.builder.BuilderResult], runner_results: List[ms.runner.RunnerResult], ) -> None: raise ValueError("test") measure_callback = FailingMeasureCallback() with pytest.raises(ValueError, match="test"): measure_callback.apply( ms.task_scheduler.RoundRobin(), 0, [ms.MeasureCandidate(Schedule(Matmul), None)], [ms.builder.BuilderResult("test_build", None)], [ms.runner.RunnerResult([1.0, 2.1], None)], ) def test_meta_schedule_measure_callback_as_string(): @ms.derived_object class NotSoFancyMeasureCallback(ms.measure_callback.PyMeasureCallback): def apply( self, task_scheduler: ms.task_scheduler.TaskScheduler, task_id: int, measure_candidates: List[ms.MeasureCandidate], builder_results: List[ms.builder.BuilderResult], runner_results: List[ms.runner.RunnerResult], ) -> None: pass measure_callback = NotSoFancyMeasureCallback() pattern = re.compile(r"meta_schedule.NotSoFancyMeasureCallback\(0x[a-f|0-9]*\)") assert pattern.match(str(measure_callback)) def test_meta_schedule_measure_callback_update_cost_model_with_zero(): @ms.derived_object class AllZeroRunnerFuture(ms.runner.PyRunnerFuture): def done(self) -> bool: return True def result(self) -> ms.runner.RunnerResult: return ms.runner.RunnerResult([0.0, 0.0], None) @ms.derived_object class AllZeroRunner(ms.runner.PyRunner): def run(self, runner_inputs: List[ms.runner.RunnerInput]) -> List[ms.runner.RunnerResult]: return [AllZeroRunnerFuture() for _ in runner_inputs] with tempfile.TemporaryDirectory() as work_dir: ms.tune_tir( mod=Matmul, target="llvm -num-cores=1", work_dir=work_dir, max_trials_global=10, runner=AllZeroRunner(), measure_callbacks=[ms.measure_callback.UpdateCostModel()], ) if __name__ == "__main__": test_meta_schedule_measure_callback() test_meta_schedule_measure_callback_fail() test_meta_schedule_measure_callback_as_string() test_meta_schedule_measure_callback_update_cost_model_with_zero()
https://github.com/zk-ml/tachikoma
tests/python/unittest/test_meta_schedule_multi_anchor.py
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. import numpy as np import tvm import tvm.testing from tvm import meta_schedule as ms from tvm import relay def get_dense_dense(data_shape, weight_shape): def multi_dense(): p_data = relay.var("p_data", shape=data_shape, dtype="float32") p_weight1 = relay.var("p_weight1", shape=weight_shape, dtype="float32") p_weight2 = relay.var("p_weight2", shape=weight_shape, dtype="float32") dense1 = relay.nn.dense(p_data, p_weight1) dense2 = relay.nn.dense(dense1, p_weight2) f = relay.Function([p_data, p_weight1, p_weight2], dense2) f = f.with_attr("Primitive", tvm.tir.IntImm("int32", 1)) return f data = relay.var("data", shape=data_shape, dtype="float32") weight1 = relay.var("weight1", shape=weight_shape, dtype="float32") weight2 = relay.var("weight2", shape=weight_shape, dtype="float32") out = relay.Call(multi_dense(), [data, weight1, weight2]) return relay.Function([data, weight1, weight2], out) def get_ref(data_np, weight1_np, weight2_np): dense1 = np.dot(data_np, np.transpose(weight1_np)) return np.dot(dense1, np.transpose(weight2_np)) def schedule_dense_dense(sch): dense1 = sch.get_block("T_matmul_NT") dense2 = sch.get_block("T_matmul_NT_1") _y1, _x1, _k1 = sch.get_loops(dense1) _y2, _x2, _k2 = sch.get_loops(dense2) def test_dense_dense(): M, N, K = 128, 128, 128 data_shape = (M, K) weight_shape = (N, K) relay_mod = tvm.IRModule.from_expr(get_dense_dense(data_shape, weight_shape)) data_np = np.random.randn(*data_shape).astype("float32") weight1_np = np.random.randn(*weight_shape).astype("float32") weight2_np = np.random.randn(*weight_shape).astype("float32") target = "llvm" params = {"weight1": weight1_np, "weight2": weight2_np} def schedule_fn(sch): if "nn_dense_nn_dense" in sch.mod.attrs["task_name"]: schedule_dense_dense(sch) return True return False with ms.database.ScheduleFnDatabase(schedule_fn): with tvm.transform.PassContext( opt_level=3, config={"relay.backend.use_meta_schedule": True}, ): lib = relay.build(relay_mod, target=target, params=params) dev = tvm.device(target, 0) runtime = tvm.contrib.graph_executor.GraphModule(lib["default"](dev)) runtime.set_input("data", data_np) runtime.run() out = runtime.get_output(0).numpy() ref = get_ref(data_np, weight1_np, weight2_np) tvm.testing.assert_allclose(out, ref, atol=1e-4, rtol=1e-4) if __name__ == "__main__": test_dense_dense()
https://github.com/zk-ml/tachikoma
tests/python/unittest/test_meta_schedule_mutator_mutate_compute_location.py
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. # pylint: disable=missing-module-docstring,missing-function-docstring,missing-class-docstring from tvm import meta_schedule as ms from tvm.script import tir as T from tvm.target import Target from tvm.tir import Schedule # pylint: disable=invalid-name, no-member @T.prim_func def add(a: T.handle, b: T.handle) -> None: # function attr dict T.func_attr({"global_symbol": "main"}) A = T.match_buffer(a, [2048, 2048, 2048], dtype="float32") B = T.match_buffer(b, [2048, 2048, 2048], dtype="float32") A_cached = T.alloc_buffer([2048, 2048, 2048], dtype="float32") # body for i, j, k in T.grid(2048, 2048, 2048): with T.block("move"): vi, vj, vk = T.axis.remap("SSS", [i, j, k]) T.reads([A[vi, vj, vk]]) T.writes([A_cached[vi, vj, vk]]) A_cached[vi, vj, vk] = A[vi, vj, vk] for i0, j0, i1, j1, k0, i2, j2, k1 in T.grid(128, 64, 4, 4, 64, 4, 8, 32): with T.block("add"): vi = T.axis.spatial(2048, i0 * 16 + i1 * 4 + i2) vj = T.axis.spatial(2048, j0 * 32 + j1 * 8 + j2) vk = T.axis.spatial(2048, k0 * 32 + k1) T.reads([A_cached[vi, vj, vk]]) T.writes([B[vi, vj, vk]]) B[vi, vj, vk] = A_cached[vi, vj, vk] + T.float32(1) # pylint: enable=invalid-name, no-member def _sch(decision: int) -> Schedule: sch = Schedule(add, debug_mask="all") # pylint: disable=invalid-name b0 = sch.get_block(name="move", func_name="main") l1 = sch.sample_compute_location(block=b0, decision=decision) sch.compute_at(block=b0, loop=l1, preserve_unit_loops=True) # pylint: enable=invalid-name return sch def _make_mutator(target: Target) -> ms.Mutator: ctx = ms.TuneContext( mod=add, target=target, space_generator=ms.space_generator.PostOrderApply( sch_rules=[], postprocs=[], mutator_probs={ms.mutator.MutateComputeLocation(): 1.0}, ), ) return list(ctx.space_generator.mutator_probs.keys())[0] def test_mutate_compute_location_add(): mutator = _make_mutator( target=Target("llvm"), ) sch = _sch(decision=4) results = set() for _ in range(100): trace = mutator.apply(sch.trace) decision = trace.decisions[trace.insts[-2]] assert not decision == 4 results.add(decision) assert len(results) == 9 if __name__ == "__main__": test_mutate_compute_location_add()
https://github.com/zk-ml/tachikoma
tests/python/unittest/test_meta_schedule_mutator_mutate_parallel.py
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. # pylint: disable=missing-module-docstring,missing-function-docstring,missing-class-docstring from typing import List from tvm import meta_schedule as ms from tvm.script import tir as T from tvm.target import Target from tvm.tir import Schedule # pylint: disable=invalid-name, no-member @T.prim_func def matmul(a: T.handle, b: T.handle, c: T.handle) -> None: A = T.match_buffer(a, [512, 512]) B = T.match_buffer(b, [512, 512]) C = T.match_buffer(c, [512, 512]) for i, j, k in T.grid(512, 512, 512): # type: ignore with T.block("C"): vi, vj, vk = T.axis.remap("SSR", [i, j, k]) # type: ignore with T.init(): C[vi, vj] = 0.0 # type: ignore C[vi, vj] = C[vi, vj] + A[vi, vk] * B[vj, vk] # pylint: enable=invalid-name, no-member def _sch(decisions: List[List[int]], ann_val: int) -> Schedule: sch = Schedule(matmul, debug_mask="all") # pylint: disable=invalid-name d0, d1, d2 = decisions b0 = sch.get_block(name="C", func_name="main") root = sch.get_block(name="root", func_name="main") sch.get_consumers(block=b0) b1 = sch.cache_write(block=b0, write_buffer_index=0, storage_scope="global") l2, l3, l4 = sch.get_loops(block=b0) v5, v6, v7, v8 = sch.sample_perfect_tile( loop=l2, n=4, max_innermost_factor=64, decision=d0, ) l9, l10, l11, l12 = sch.split(loop=l2, factors=[v5, v6, v7, v8]) v13, v14, v15, v16 = sch.sample_perfect_tile( loop=l3, n=4, max_innermost_factor=64, decision=d1, ) l17, l18, l19, l20 = sch.split(loop=l3, factors=[v13, v14, v15, v16]) v21, v22 = sch.sample_perfect_tile( loop=l4, n=2, max_innermost_factor=64, decision=d2, ) l23, l24 = sch.split(loop=l4, factors=[v21, v22]) sch.reorder(l9, l17, l10, l18, l23, l11, l19, l24, l12, l20) sch.reverse_compute_at(block=b1, loop=l18, preserve_unit_loops=True) sch.annotate(block_or_loop=root, ann_key="meta_schedule.parallel", ann_val=ann_val) # pylint: enable=invalid-name return sch def _make_mutator(target: Target, max_jobs_per_core: int) -> ms.Mutator: ctx = ms.TuneContext( mod=matmul, target=target, space_generator=ms.space_generator.PostOrderApply( sch_rules=[], postprocs=[], mutator_probs={ms.mutator.MutateParallel(max_jobs_per_core): 1.0}, ), ) return list(ctx.space_generator.mutator_probs.keys())[0] def test_mutate_parallel_matmul(): mutator = _make_mutator( target=Target("llvm --num-cores=16"), max_jobs_per_core=256, ) sch = _sch( decisions=[ [4, 32, 4, 1], [8, 4, 8, 2], [512, 1], ], ann_val=64, ) results = set() for _ in range(100): trace = mutator.apply(sch.trace) ann_val = int(trace.insts[-1].inputs[1]) results.add(ann_val) if len(results) == 3: break assert len(results) == 3 assert results == {4, 32, 4096} if __name__ == """__main__""": test_mutate_parallel_matmul()
https://github.com/zk-ml/tachikoma
tests/python/unittest/test_meta_schedule_mutator_mutate_thread_binding.py
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. # pylint: disable=missing-module-docstring,missing-function-docstring,missing-class-docstring from tvm import meta_schedule as ms from tvm.script import tir as T from tvm.target import Target from tvm.tir import Schedule # pylint: disable=invalid-name, no-member @T.prim_func def element_wise(var_A: T.handle, var_B: T.handle) -> None: A = T.match_buffer(var_A, [512, 512], dtype="float32") B = T.match_buffer(var_B, [512, 512], dtype="float32") for i, j in T.grid(512, 512): with T.block("C"): vi, vj = T.axis.remap("SS", [i, j]) B[vi, vj] = A[vi, vj] + 1.0 # pylint: enable=invalid-name, no-member def _sch() -> Schedule: sch = Schedule(element_wise, debug_mask="all") # pylint: disable=invalid-name b0 = sch.get_block(name="C", func_name="main") l1, l2 = sch.get_loops(block=b0) l3 = sch.fuse(l1, l2) v4 = sch.sample_categorical( candidates=[32, 64, 128, 256, 512, 1024], probs=[ 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, ], decision=3, ) l5, l6 = sch.split(loop=l3, factors=[None, v4]) sch.bind(loop=l5, thread_axis="blockIdx.x") sch.bind(loop=l6, thread_axis="threadIdx.x") # pylint: enable=invalid-name return sch def _make_mutator(target: Target) -> ms.Mutator: ctx = ms.TuneContext( mod=element_wise, target=target, space_generator=ms.space_generator.PostOrderApply( sch_rules=[], postprocs=[], mutator_probs={ms.mutator.MutateThreadBinding(): 1.0}, ), ) return list(ctx.space_generator.mutator_probs.keys())[0] def test_mutate_thread_binding(): mutator = _make_mutator(target=Target("cuda")) sch = _sch() results = set() for _ in range(100): trace = mutator.apply(sch.trace) decision = trace.decisions[trace.insts[-4]] results.add(decision) if len(results) == 5: break assert len(results) == 5 assert results == {0, 1, 2, 4, 5} if __name__ == "__main__": test_mutate_thread_binding()
https://github.com/zk-ml/tachikoma
tests/python/unittest/test_meta_schedule_mutator_mutate_tile_size.py
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. # pylint: disable=missing-module-docstring,missing-function-docstring,missing-class-docstring import operator from functools import reduce from typing import List from tvm import meta_schedule as ms from tvm.script import tir as T from tvm.target import Target from tvm.tir import Schedule # pylint: disable=invalid-name, no-member @T.prim_func def matmul(a: T.handle, b: T.handle, c: T.handle) -> None: A = T.match_buffer(a, [512, 512]) B = T.match_buffer(b, [512, 512]) C = T.match_buffer(c, [512, 512]) for i, j, k in T.grid(512, 512, 512): # type: ignore with T.block("C"): vi, vj, vk = T.axis.remap("SSR", [i, j, k]) # type: ignore with T.init(): C[vi, vj] = 0.0 # type: ignore C[vi, vj] = C[vi, vj] + A[vi, vk] * B[vj, vk] # pylint: enable=invalid-name, no-member def _sch(decisions: List[List[int]]) -> Schedule: sch = Schedule(matmul, debug_mask="all") # pylint: disable=invalid-name (d0,) = decisions b0 = sch.get_block(name="C", func_name="main") sch.get_consumers(block=b0) b1 = sch.cache_write(block=b0, write_buffer_index=0, storage_scope="global") l2, l3, l4 = sch.get_loops(block=b0) v5, v6, v7, v8 = sch.sample_perfect_tile( loop=l2, n=4, max_innermost_factor=64, decision=d0, ) l9, l10, l11, l12 = sch.split(loop=l2, factors=[v5, v6, v7, v8]) l17, l18, l19, l20 = sch.split(loop=l3, factors=[8, 4, 8, 2]) l23, l24 = sch.split(loop=l4, factors=[512, 1]) sch.reorder(l9, l17, l10, l18, l23, l11, l19, l24, l12, l20) sch.reverse_compute_at(block=b1, loop=l18, preserve_unit_loops=True) # pylint: enable=invalid-name return sch def _make_mutator(target: Target) -> ms.Mutator: ctx = ms.TuneContext( mod=matmul, target=target, space_generator=ms.space_generator.PostOrderApply( sch_rules=[], postprocs=[], mutator_probs={ms.mutator.MutateTileSize(): 1.0}, ), ) return list(ctx.space_generator.mutator_probs.keys())[0] def test_mutate_tile_size_matmul(): mutator = _make_mutator( target=Target("llvm --num-cores=16"), ) results = {} sch = _sch(decisions=[[4, 32, 4, 1]]) for _ in range(1000): trace = mutator.apply(sch.trace) assert trace.insts[4].kind.name == "SamplePerfectTile" decision = trace.decisions[trace.insts[4]] decision = [int(x) for x in decision] results[str(decision)] = decision assert reduce(operator.mul, decision, 1) == 512 assert len(results) > 15 if __name__ == "__main__": test_mutate_tile_size_matmul()
https://github.com/zk-ml/tachikoma
tests/python/unittest/test_meta_schedule_mutator_mutate_unroll.py
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. # pylint: disable=missing-module-docstring,missing-function-docstring,missing-class-docstring from typing import List from tvm import meta_schedule as ms from tvm.script import tir as T from tvm.target import Target from tvm.tir import Schedule # pylint: disable=invalid-name, no-member @T.prim_func def matmul(a: T.handle, b: T.handle, c: T.handle) -> None: A = T.match_buffer(a, [512, 512]) B = T.match_buffer(b, [512, 512]) C = T.match_buffer(c, [512, 512]) for i, j, k in T.grid(512, 512, 512): # type: ignore with T.block("C"): vi, vj, vk = T.axis.remap("SSR", [i, j, k]) # type: ignore with T.init(): C[vi, vj] = 0.0 # type: ignore C[vi, vj] = C[vi, vj] + A[vi, vk] * B[vj, vk] # pylint: enable=invalid-name, no-member def _sch(decisions: List[List[int]]) -> Schedule: sch = Schedule(matmul, debug_mask="all") # pylint: disable=invalid-name d0, d1, d2 = decisions b0 = sch.get_block(name="C", func_name="main") root = sch.get_block(name="root", func_name="main") sch.get_consumers(block=b0) b1 = sch.cache_write(block=b0, write_buffer_index=0, storage_scope="global") l2, l3, l4 = sch.get_loops(block=b0) v5, v6, v7, v8 = sch.sample_perfect_tile( loop=l2, n=4, max_innermost_factor=64, decision=d0, ) l9, l10, l11, l12 = sch.split(loop=l2, factors=[v5, v6, v7, v8]) v13, v14, v15, v16 = sch.sample_perfect_tile( loop=l3, n=4, max_innermost_factor=64, decision=d1, ) l17, l18, l19, l20 = sch.split(loop=l3, factors=[v13, v14, v15, v16]) v21, v22 = sch.sample_perfect_tile( loop=l4, n=2, max_innermost_factor=64, decision=d2, ) l23, l24 = sch.split(loop=l4, factors=[v21, v22]) sch.reorder(l9, l17, l10, l18, l23, l11, l19, l24, l12, l20) sch.reverse_compute_at(block=b1, loop=l18, preserve_unit_loops=True) v57 = sch.sample_categorical( candidates=[0, 16, 64, 512], probs=[0.25, 0.25, 0.25, 0.25], decision=0, ) sch.annotate(block_or_loop=root, ann_key="meta_schedule.unroll_explicit", ann_val=v57) # pylint: enable=invalid-name return sch def _make_mutator(target: Target) -> ms.Mutator: ctx = ms.TuneContext( mod=matmul, target=target, space_generator=ms.space_generator.PostOrderApply( sch_rules=[], postprocs=[], mutator_probs={ms.mutator.MutateUnroll(): 1.0}, ), ) return list(ctx.space_generator.mutator_probs.keys())[0] def test_mutate_unroll_matmul(): mutator = _make_mutator(target=Target("llvm --num-cores=16")) sch = _sch( decisions=[ [4, 32, 4, 1], [8, 4, 8, 2], [512, 1], ], ) results = set() for _ in range(100): trace = mutator.apply(sch.trace) decision = trace.decisions[trace.insts[-2]] results.add(decision) if len(results) == 3: break assert len(results) == 3 assert results == {1, 2, 3} if __name__ == """__main__""": test_mutate_unroll_matmul()
https://github.com/zk-ml/tachikoma
tests/python/unittest/test_meta_schedule_post_order_apply.py
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. # pylint: disable=missing-module-docstring,missing-function-docstring,missing-class-docstring import math import sys from typing import List import pytest import tvm import tvm.testing from tvm._ffi import register_func from tvm.error import TVMError from tvm.meta_schedule import TuneContext from tvm.meta_schedule.schedule_rule import PyScheduleRule from tvm.meta_schedule.space_generator import PostOrderApply from tvm.meta_schedule.utils import derived_object from tvm.script import tir as T from tvm.target import Target from tvm.tir.schedule import BlockRV, Schedule # pylint: disable=invalid-name,no-member,line-too-long,too-many-nested-blocks,no-self-argument, # fmt: off @tvm.script.ir_module class Matmul: @T.prim_func def main(a: T.handle, b: T.handle, c: T.handle) -> None: T.func_attr({"global_symbol": "main"}) A = T.match_buffer(a, (1024, 1024), "float32") B = T.match_buffer(b, (1024, 1024), "float32") C = T.match_buffer(c, (1024, 1024), "float32") for i, j, k in T.grid(1024, 1024, 1024): with T.block("matmul"): vi, vj, vk = T.axis.remap("SSR", [i, j, k]) with T.init(): C[vi, vj] = 0.0 C[vi, vj] = C[vi, vj] + A[vi, vk] * B[vk, vj] @tvm.script.ir_module class DuplicateMatmul: @T.prim_func def main(a: T.handle, b: T.handle, c: T.handle) -> None: T.func_attr({"global_symbol": "main"}) A = T.match_buffer(a, (1024, 1024), "float32") B = T.match_buffer(b, (1024, 1024), "float32") C = T.match_buffer(c, (1024, 1024), "float32") for i, j, k in T.grid(1024, 1024, 1024): with T.block("matmul"): vi, vj, vk = T.axis.remap("SSR", [i, j, k]) with T.init(): C[vi, vj] = 0.0 C[vi, vj] = C[vi, vj] + A[vi, vk] * B[vk, vj] for i, j, k in T.grid(1024, 1024, 1024): with T.block("matmul"): vi, vj, vk = T.axis.remap("SSR", [i, j, k]) C[vi, vj] = C[vi, vj] + A[vi, vk] * B[vk, vj] @tvm.script.ir_module class TrinityMatmul: @T.prim_func def main(a: T.handle, d: T.handle) -> None: T.func_attr({"global_symbol": "main"}) A = T.match_buffer(a, (1024, 1024), "float32") B = T.alloc_buffer((1024, 1024), "float32") C = T.alloc_buffer((1024, 1024), "float32") D = T.match_buffer(d, (1024, 1024), "float32") for i, j in T.grid(1024, 1024): with T.block("A"): vi, vj = T.axis.remap("SS", [i, j]) B[vi, vj] = A[vi, vj] * 2.0 for i, j in T.grid(1024, 1024): with T.block("B"): vi, vj = T.axis.remap("SS", [i, j]) C[vi, vj] = B[vi, vj] + 3.0 for i, j in T.grid(1024, 1024): with T.block("C"): vi, vj = T.axis.remap("SS", [i, j]) D[vi, vj] = C[vi, vj] * 5.0 @tvm.script.ir_module class TrinityMatmulProcessedForReference: @T.prim_func def main(a: T.handle, d: T.handle) -> None: # function attr dict T.func_attr({"global_symbol": "main"}) A = T.match_buffer(a, [1024, 1024], dtype="float32") D = T.match_buffer(d, [1024, 1024], dtype="float32") # body # with tir.block("root") B = T.alloc_buffer([1024, 1024], dtype="float32") for i0_0, i1_0, i0_1, i1_1 in T.grid(16, 64, 64, 16): with T.block("A"): vi = T.axis.S(1024, i0_0 * 64 + i0_1) vj = T.axis.S(1024, i1_0 * 16 + i1_1) T.reads([A[vi, vj]]) T.writes([B[vi, vj]]) B[vi, vj] = A[vi, vj] * T.float32(2) for i0_0, i1_0, i0_1, i1_1 in T.grid(16, 64, 64, 16): with T.block("C"): vi = T.axis.S(1024, i0_0 * 64 + i0_1) vj = T.axis.S(1024, i1_0 * 16 + i1_1) T.reads([B[vi, vj]]) T.writes([D[vi, vj]]) D[vi, vj] = (B[vi, vj] + T.float32(3)) * T.float32(5) # fmt: on # pylint: enable=invalid-name,no-member,line-too-long,too-many-nested-blocks,no-self-argument def _is_root(sch: Schedule, block: BlockRV) -> bool: return sch.get_sref(block).parent is None def _check_correct(schedule: Schedule): trace = schedule.trace for inst in trace.decisions: assert math.prod(trace.decisions[inst]) == 1024 @derived_object class WowSoFancyScheduleRule(PyScheduleRule): def _initialize_with_tune_context(self, context: "TuneContext") -> None: pass def apply(self, sch: Schedule, block: BlockRV) -> List[Schedule]: if _is_root(sch, block): return [sch] new_sch = sch.copy() i, j, k = new_sch.get_loops(block=block) i_0, i_1, i_2, i_3 = new_sch.split(loop=i, factors=[2, 4, 64, 2]) j_0, j_1, j_2, j_3 = new_sch.split(loop=j, factors=[4, 64, 2, 2]) k_0, k_1 = new_sch.split(loop=k, factors=[32, 32]) new_sch.reorder(i_0, j_0, i_1, j_1, k_0, i_2, j_2, k_1, i_3, j_3) return [new_sch] @derived_object class DoubleScheduleRule(PyScheduleRule): def _initialize_with_tune_context(self, context: "TuneContext") -> None: pass def apply(self, sch: Schedule, block: BlockRV) -> List[Schedule]: if _is_root(sch, block): return [sch] new_sch = sch.copy() i, j, k = new_sch.get_loops(block=block) i_0, i_1, i_2, i_3 = new_sch.split(loop=i, factors=[4, 64, 2, 2]) j_0, j_1, j_2, j_3 = new_sch.split(loop=j, factors=[2, 4, 64, 2]) k_0, k_1 = new_sch.split(loop=k, factors=[32, 32]) new_sch.reorder(i_0, j_0, i_1, j_1, k_0, i_2, j_2, k_1, i_3, j_3) result = [new_sch] new_sch = sch.copy() i, j, k = new_sch.get_loops(block=block) i_0, i_1, i_2, i_3 = new_sch.split(loop=i, factors=[4, 64, 2, 2]) j_0, j_1, j_2, j_3 = new_sch.split(loop=j, factors=[2, 4, 64, 2]) k_0, k_1 = new_sch.split(loop=k, factors=[32, 32]) new_sch.reorder(i_0, j_0, i_1, j_1, k_0, i_2, j_2, k_1, i_3, j_3) result.append(new_sch) return result @derived_object class TrinityDoubleRule(PyScheduleRule): def _initialize_with_tune_context(self, context: "TuneContext") -> None: pass def apply(self, sch: Schedule, block: BlockRV) -> List[Schedule]: if _is_root(sch, block): return [sch] new_sch = sch.copy() i, j = new_sch.get_loops(block=block) i_0, i_1 = new_sch.split(loop=i, factors=[16, 64]) j_0, j_1 = new_sch.split(loop=j, factors=[64, 16]) new_sch.reorder(i_0, j_0, i_1, j_1) result = [new_sch] new_sch = sch.copy() i, j = new_sch.get_loops(block=block) i_0, i_1 = new_sch.split(loop=i, factors=[2, 512]) j_0, j_1 = new_sch.split(loop=j, factors=[2, 512]) new_sch.reorder(i_0, j_0, i_1, j_1) result.append(new_sch) return result @derived_object class ReorderScheduleRule(PyScheduleRule): def _initialize_with_tune_context(self, context: "TuneContext") -> None: pass def apply(self, sch: Schedule, block: BlockRV) -> List[Schedule]: if _is_root(sch, block): return [sch] new_sch = sch.copy() i_0, j_0, i_1, j_1, k_0, i_2, j_2, k_1, i_3, j_3 = new_sch.get_loops(block=block) new_sch.reorder(i_1, j_1, k_0, i_2, j_2, k_1, i_3, j_3, i_0, j_0) result = [new_sch] new_sch = sch.copy() i_0, j_0, i_1, j_1, k_0, i_2, j_2, k_1, i_3, j_3 = new_sch.get_loops(block=block) new_sch.reorder(i_1, j_3, i_0, j_0, j_1, k_0, i_2, j_2, k_1, i_3) result.append(new_sch) return result def test_meta_schedule_post_order_apply(): mod = Matmul context = TuneContext( mod=mod, target=Target("llvm"), task_name="Test Task", space_generator=PostOrderApply( sch_rules=[WowSoFancyScheduleRule()], postprocs=[], mutator_probs={}, ), ) post_order_apply = context.space_generator schs = post_order_apply.generate_design_space(mod) assert len(schs) == 1 assert not tvm.ir.structural_equal(schs[0].mod, mod) _check_correct(schs[0]) def test_meta_schedule_post_order_apply_double(): mod = Matmul context = TuneContext( mod=mod, target=Target("llvm"), task_name="Double Rules Task", space_generator=PostOrderApply( sch_rules=[DoubleScheduleRule()], postprocs=[], mutator_probs={}, ), ) post_order_apply = context.space_generator schs = post_order_apply.generate_design_space(mod) assert len(schs) == 2 for sch in schs: assert not tvm.ir.structural_equal(sch.mod, mod) _check_correct(sch) def test_meta_schedule_post_order_apply_multiple(): mod = Matmul context = TuneContext( mod=mod, target=Target("llvm"), task_name="Double Rules Task", space_generator=PostOrderApply( sch_rules=[DoubleScheduleRule(), ReorderScheduleRule()], postprocs=[], mutator_probs={}, ), ) post_order_apply = context.space_generator schs = post_order_apply.generate_design_space(mod) assert len(schs) == 4 for sch in schs: assert not tvm.ir.structural_equal(sch.mod, mod) _check_correct(sch) def test_meta_schedule_post_order_apply_duplicate_matmul(): mod = DuplicateMatmul context = TuneContext( mod=mod, target=Target("llvm"), task_name="Duplicate Matmul Task", space_generator=PostOrderApply( sch_rules=[WowSoFancyScheduleRule()], postprocs=[], mutator_probs={}, ), ) post_order_apply = context.space_generator with pytest.raises( TVMError, match=r".*TVMError: Check failed: \(block_names_.count\(block->name_hint\) == 0\)" r" is false: Duplicated block name matmul in function main not supported!", ): post_order_apply.generate_design_space(mod) def test_meta_schedule_post_order_apply_remove_block(): @derived_object class RemoveBlock(PyScheduleRule): def _initialize_with_tune_context(self, context: "TuneContext") -> None: pass def apply(self, sch: Schedule, block: BlockRV) -> List[Schedule]: if _is_root(sch, block): return [sch] sch = sch.copy() if sch.get(block).name_hint == "B": sch.compute_inline(block) return [sch] def correct_trace(a, b, c, d): return "\n".join( [ "# from tvm import tir", "def apply_trace(sch: tir.Schedule) -> None:", ' b0 = sch.get_block(name="A", func_name="main")', ' b1 = sch.get_block(name="B", func_name="main")', ' b2 = sch.get_block(name="C", func_name="main")', " sch.compute_inline(block=b1)", " l3, l4 = sch.get_loops(block=b2)", " l5, l6 = sch.split(loop=l3, factors=" + str(a) + ", preserve_unit_iters=True)", " l7, l8 = sch.split(loop=l4, factors=" + str(b) + ", preserve_unit_iters=True)", " sch.reorder(l5, l7, l6, l8)", " l9, l10 = sch.get_loops(block=b0)", " l11, l12 = sch.split(loop=l9, factors=" + str(c) + ", preserve_unit_iters=True)", " l13, l14 = sch.split(loop=l10, factors=" + str(d) + ", preserve_unit_iters=True)", " sch.reorder(l11, l13, l12, l14)", ] ) mod = TrinityMatmul context = TuneContext( mod=mod, target=Target("llvm"), task_name="Remove Block Task", space_generator=PostOrderApply( sch_rules=[RemoveBlock(), TrinityDoubleRule()], postprocs=[], mutator_probs={}, ), ) post_order_apply = context.space_generator schs = post_order_apply.generate_design_space(mod) assert len(schs) == 4 for sch in schs: with pytest.raises( tvm.tir.schedule.schedule.ScheduleError, match="ScheduleError: An error occurred in the schedule primitive 'get-block'.", ): sch.get_block("B", "main") sch_trace = sch.trace.simplified(True) assert ( str(sch_trace) == correct_trace([16, 64], [64, 16], [2, 512], [2, 512]) or str(sch_trace) == correct_trace([2, 512], [2, 512], [2, 512], [2, 512]) or str(sch_trace) == correct_trace([16, 64], [64, 16], [16, 64], [64, 16]) or str(sch_trace) == correct_trace([2, 512], [2, 512], [16, 64], [64, 16]) ) def test_target_blocks_search_space(): # Test that specific blocks of trinity matmul can be targeted. def filter_fn(block, target_names) -> bool: return block.name_hint in target_names def _get_sch(filter_fn): mod = TrinityMatmul context = TuneContext( mod=mod, target=Target("llvm"), task_name="Custom Search Space Task", space_generator=PostOrderApply( f_block_filter=filter_fn, sch_rules=[TrinityDoubleRule()], postprocs=[], mutator_probs={}, ), ) post_order_apply = context.space_generator schs = post_order_apply.generate_design_space(mod) return schs # Start by checking that by default each block has a space generated. schs = _get_sch(None) assert len(schs) == 8 # Next check that we can target a specific block and only get its' revelant schedules. schs = _get_sch(lambda block: filter_fn(block, ["B"])) assert len(schs) == 2 ## Check that extracting two blocks works. schs = _get_sch(lambda block: filter_fn(block, ["A", "C"])) assert len(schs) == 4 ## Finally check that all blocks can be extracted by name. schs = _get_sch(lambda block: filter_fn(block, ["A", "B", "C"])) assert len(schs) == 8 if __name__ == "__main__": tvm.testing.main()
https://github.com/zk-ml/tachikoma
tests/python/unittest/test_meta_schedule_postproc_disallow_dynamic_loop.py
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. # pylint: disable=missing-module-docstring,missing-function-docstring,missing-class-docstring import tvm from tvm import meta_schedule as ms from tvm import tir from tvm.script import tir as T from tvm.target import Target def _target() -> Target: return Target("cuda", host="llvm") def _create_context(mod, target) -> ms.TuneContext: ctx = ms.TuneContext( mod=mod, target=target, space_generator=ms.space_generator.PostOrderApply( sch_rules=[], postprocs=[ ms.postproc.DisallowDynamicLoop(), ], mutator_probs={}, ), task_name="test", ) return ctx # pylint: disable=invalid-name,no-member,line-too-long,too-many-nested-blocks,no-self-argument # fmt: off @tvm.script.ir_module class Matmul: @T.prim_func def main(a: T.handle, b: T.handle, c: T.handle) -> None: T.func_attr({"global_symbol": "main"}) A = T.match_buffer(a, (1024, 1024), "float32") B = T.match_buffer(b, (1024, 1024), "float32") C = T.match_buffer(c, (1024, 1024), "float32") for i, j, k in T.grid(1024, 1024, 1024): with T.block("matmul"): vi, vj, vk = T.axis.remap("SSR", [i, j, k]) with T.init(): C[vi, vj] = 0.0 C[vi, vj] = C[vi, vj] + A[vi, vk] * B[vk, vj] @tvm.script.ir_module class DynamicLoop: @T.prim_func def main(a: T.handle, b: T.handle, c: T.handle) -> None: T.func_attr({"global_symbol": "main"}) A = T.match_buffer(a, (1024, 1024), "float32") B = T.match_buffer(b, (1024, 1024), "float32") C = T.match_buffer(c, (1024, 1024), "float32") for i, j in T.grid(1024, 1024): for k in T.serial(0, i): with T.block("matmul"): vi, vj, vk = T.axis.remap("SSR", [i, j, k]) with T.init(): C[vi, vj] = 0.0 C[vi, vj] = C[vi, vj] + A[vi, vk] * B[vk, vj] # fmt: on # pylint: enable=invalid-name,no-member,line-too-long,too-many-nested-blocks,no-self-argument def test_postproc_disallow_dynamic_loops(): mod = Matmul ctx = _create_context(mod, target=_target()) sch = tir.Schedule(mod, debug_mask="all") assert ctx.space_generator.postprocs[0].apply(sch) def test_postproc_disallow_dynamic_loops_fail(): mod = DynamicLoop ctx = _create_context(mod, target=_target()) sch = tir.Schedule(mod, debug_mask="all") assert not ctx.space_generator.postprocs[0].apply(sch) if __name__ == "__main__": test_postproc_disallow_dynamic_loops() test_postproc_disallow_dynamic_loops_fail()
https://github.com/zk-ml/tachikoma
tests/python/unittest/test_meta_schedule_postproc_rewrite_cooperative_fetch.py
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. # pylint: disable=missing-module-docstring,missing-function-docstring,missing-class-docstring import tvm import tvm.testing from tvm import meta_schedule as ms from tvm import tir from tvm.meta_schedule.testing import te_workload from tvm.script import tir as T from tvm.target import Target from tvm.te import create_prim_func def _target() -> Target: return Target("cuda", host="llvm") def _create_context(mod, target) -> ms.TuneContext: ctx = ms.TuneContext( mod=mod, target=target, space_generator=ms.space_generator.PostOrderApply( sch_rules=[], postprocs=[ ms.postproc.RewriteCooperativeFetch(), ], mutator_probs={}, ), task_name="test", ) return ctx # fmt: off # pylint: disable=no-member,invalid-name,unused-variable,no-self-argument,line-too-long,chained-comparison,not-callable,too-many-nested-blocks @tvm.script.ir_module class AfterRewrite0: @T.prim_func def main(var_A: T.handle, var_B: T.handle, var_C: T.handle) -> None: # function attr dict T.func_attr({"global_symbol": "main", "tir.noalias": True}) A = T.match_buffer(var_A, [512, 512], dtype="float32") B = T.match_buffer(var_B, [512, 512], dtype="float32") C = T.match_buffer(var_C, [512, 512], dtype="float32") # body # with T.block("root") C_local = T.alloc_buffer([512, 512], dtype="float32", scope="local") A_shared = T.alloc_buffer([512, 512], dtype="float32", scope="shared") B_shared = T.alloc_buffer([512, 512], dtype="float32", scope="shared") for i0_0_i1_0_fused in T.thread_binding(0, 16, thread="blockIdx.x"): for i0_1_i1_1_fused in T.thread_binding(0, 16, thread="vthread.x"): for i0_2_i1_2_fused in T.thread_binding(0, 8, thread="threadIdx.x"): for i2_0 in T.serial(0, 1): for ax0_ax1_fused_0 in T.serial(0, 32768): for ax0_ax1_fused_1 in T.thread_binding(0, 8, thread="threadIdx.x"): with T.block("A_shared"): v0 = T.axis.spatial(512, (ax0_ax1_fused_0 * 8 + ax0_ax1_fused_1) // 512) v1 = T.axis.spatial(512, (ax0_ax1_fused_0 * 8 + ax0_ax1_fused_1) % 512) T.reads([A[v0, v1]]) T.writes([A_shared[v0, v1]]) A_shared[v0, v1] = A[v0, v1] for ax0_ax1_fused_0 in T.serial(0, 1024): for ax0_ax1_fused_1 in T.thread_binding(0, 8, thread="threadIdx.x"): for ax0_ax1_fused_2 in T.vectorized(0, 2): with T.block("B_shared"): v0 = T.axis.spatial(512, (ax0_ax1_fused_0 * 16 + ax0_ax1_fused_1 * 2 + ax0_ax1_fused_2) // 32) v1 = T.axis.spatial(512, i0_0_i1_0_fused * 32 + (ax0_ax1_fused_0 * 16 + ax0_ax1_fused_1 * 2 + ax0_ax1_fused_2) % 32) T.reads([B[v0, v1]]) T.writes([B_shared[v0, v1]]) B_shared[v0, v1] = B[v0, v1] for i2_1, i0_3, i1_3, i2_2, i0_4, i1_4 in T.grid(16, 2, 2, 32, 16, 2): with T.block("C"): i = T.axis.spatial(512, i0_1_i1_1_fused * 32 + i0_3 * 16 + i0_4) j = T.axis.spatial(512, i0_0_i1_0_fused * 32 + i0_2_i1_2_fused * 4 + i1_3 * 2 + i1_4) k = T.axis.reduce(512, i2_0 * 512 + i2_1 * 32 + i2_2) T.reads([A_shared[i, k], B_shared[k, j]]) T.writes([C_local[i, j]]) with T.init(): C_local[i, j] = T.float32(0) C_local[i, j] = C_local[i, j] + A_shared[i, k] * B_shared[k, j] for ax0, ax1 in T.grid(32, 4): with T.block("C_local"): v0 = T.axis.spatial(512, i0_1_i1_1_fused * 32 + ax0) v1 = T.axis.spatial(512, i0_0_i1_0_fused * 32 + i0_2_i1_2_fused * 4 + ax1) T.reads([C_local[v0, v1]]) T.writes([C[v0, v1]]) C[v0, v1] = C_local[v0, v1] @tvm.script.ir_module class WarpExecutionAfterRewrite: @T.prim_func def main( A: T.Buffer[(512, 512), "float32"], B: T.Buffer[(512, 512), "float32"], C: T.Buffer[(512, 512), "float32"], ) -> None: # function attr dict T.func_attr({"global_symbol": "main", "tir.noalias": True}) # body # with T.block("root") C_local = T.alloc_buffer([512, 512], dtype="float32", scope="local") A_shared = T.alloc_buffer([512, 512], dtype="float32", scope="shared") B_shared = T.alloc_buffer([512, 512], dtype="float32", scope="shared") for i0_0_i1_0_fused in T.thread_binding(0, 16, thread="blockIdx.x"): for i0_1_i1_1_fused in T.thread_binding(0, 16, thread="vthread.x"): for i0_2_i1_2_fused in T.thread_binding(0, 8, thread="threadIdx.y"): for i2_0 in T.serial(0, 1): for ax0_ax1_fused_0 in T.serial(0, 1024): for ax0_ax1_fused_1 in T.thread_binding(0, 8, thread="threadIdx.y"): for ax0_ax1_fused_2 in T.thread_binding( 0, 32, thread="threadIdx.x" ): with T.block("A_shared"): v0 = T.axis.spatial( 512, ( ax0_ax1_fused_0 * 256 + ax0_ax1_fused_1 * 32 + ax0_ax1_fused_2 ) // 512, ) v1 = T.axis.spatial( 512, ( ax0_ax1_fused_0 * 256 + ax0_ax1_fused_1 * 32 + ax0_ax1_fused_2 ) % 512, ) T.reads([A[v0, v1]]) T.writes([A_shared[v0, v1]]) A_shared[v0, v1] = A[v0, v1] for ax0_ax1_fused_0 in T.serial(0, 32): for ax0_ax1_fused_1 in T.thread_binding(0, 8, thread="threadIdx.y"): for ax0_ax1_fused_2 in T.thread_binding( 0, 32, thread="threadIdx.x" ): for ax0_ax1_fused_3 in T.vectorized(0, 2): with T.block("B_shared"): v0 = T.axis.spatial( 512, ( ax0_ax1_fused_0 * 512 + ax0_ax1_fused_1 * 64 + ax0_ax1_fused_2 * 2 + ax0_ax1_fused_3 ) // 32, ) v1 = T.axis.spatial( 512, i0_0_i1_0_fused * 32 + ( ax0_ax1_fused_0 * 512 + ax0_ax1_fused_1 * 64 + ax0_ax1_fused_2 * 2 + ax0_ax1_fused_3 ) % 32, ) T.reads([B[v0, v1]]) T.writes([B_shared[v0, v1]]) B_shared[v0, v1] = B[v0, v1] for i2_1, i0_3, i1_3, i2_2, i0_4, i1_4 in T.grid(16, 2, 2, 32, 16, 2): with T.block("C"): i = T.axis.spatial(512, i0_1_i1_1_fused * 32 + i0_3 * 16 + i0_4) j = T.axis.spatial( 512, i0_0_i1_0_fused * 32 + i0_2_i1_2_fused * 4 + i1_3 * 2 + i1_4, ) k = T.axis.reduce(512, i2_0 * 512 + i2_1 * 32 + i2_2) T.reads([A_shared[i, k], B_shared[k, j]]) T.writes([C_local[i, j]]) T.block_attr({"warp_execution": 1}) with T.init(): C_local[i, j] = T.float32(0) C_local[i, j] = C_local[i, j] + A_shared[i, k] * B_shared[k, j] for ax0, ax1 in T.grid(32, 4): with T.block("C_local"): v0 = T.axis.spatial(512, i0_1_i1_1_fused * 32 + ax0) v1 = T.axis.spatial( 512, i0_0_i1_0_fused * 32 + i0_2_i1_2_fused * 4 + ax1 ) T.reads([C_local[v0, v1]]) T.writes([C[v0, v1]]) C[v0, v1] = C_local[v0, v1] # pylint: enable=no-member,invalid-name,unused-variable,no-self-argument,line-too-long,chained-comparison,not-callable,too-many-nested-blocks # fmt: on def test_rewrite_cooperative_fetch(): mod = create_prim_func(te_workload.matmul(n=512, m=512, k=512)) target = _target() ctx = _create_context(mod, target) sch = tir.Schedule(mod, debug_mask="all") # fmt: off # pylint: disable=line-too-long,invalid-name b0 = sch.get_block(name="C", func_name="main") b1 = sch.cache_write(block=b0, write_buffer_index=0, storage_scope="local") l2, l3, l4 = sch.get_loops(block=b0) v5, v6, v7, v8, v9 = sch.sample_perfect_tile(loop=l2, n=5, max_innermost_factor=64, decision=[1, 16, 1, 2, 16]) l10, l11, l12, l13, l14 = sch.split(loop=l2, factors=[v5, v6, v7, v8, v9]) v15, v16, v17, v18, v19 = sch.sample_perfect_tile(loop=l3, n=5, max_innermost_factor=64, decision=[16, 1, 8, 2, 2]) l20, l21, l22, l23, l24 = sch.split(loop=l3, factors=[v15, v16, v17, v18, v19]) v25, v26, v27 = sch.sample_perfect_tile(loop=l4, n=3, max_innermost_factor=64, decision=[1, 16, 32]) l28, l29, l30 = sch.split(loop=l4, factors=[v25, v26, v27]) sch.reorder(l10, l20, l11, l21, l12, l22, l28, l29, l13, l23, l30, l14, l24) l31 = sch.fuse(l10, l20) sch.bind(loop=l31, thread_axis="blockIdx.x") l32 = sch.fuse(l11, l21) sch.bind(loop=l32, thread_axis="vthread.x") l33 = sch.fuse(l12, l22) sch.bind(loop=l33, thread_axis="threadIdx.x") b34 = sch.cache_read(block=b0, read_buffer_index=0, storage_scope="shared") sch.compute_at(block=b34, loop=l28, preserve_unit_loops=True) _, _, _, _, l39, l40 = sch.get_loops(block=b34) l41 = sch.fuse(l39, l40) _, v43 = sch.sample_perfect_tile(loop=l41, n=2, max_innermost_factor=4, decision=[262144, 1]) sch.annotate(block_or_loop=b34, ann_key="meta_schedule.cooperative_fetch", ann_val=v43) b44 = sch.cache_read(block=b0, read_buffer_index=1, storage_scope="shared") sch.compute_at(block=b44, loop=l28, preserve_unit_loops=True) _, _, _, _, l49, l50 = sch.get_loops(block=b44) l51 = sch.fuse(l49, l50) _, v53 = sch.sample_perfect_tile(loop=l51, n=2, max_innermost_factor=4, decision=[8192, 2]) sch.annotate(block_or_loop=b44, ann_key="meta_schedule.cooperative_fetch", ann_val=v53) sch.reverse_compute_at(block=b1, loop=l33, preserve_unit_loops=True) # pylint: enable=line-too-long,invalid-name # fmt: on sch.enter_postproc() assert ctx.space_generator.postprocs[0].apply(sch) tvm.ir.assert_structural_equal(sch.mod, AfterRewrite0) def test_rewrite_warp_execution(): mod = create_prim_func(te_workload.matmul(n=512, m=512, k=512)) target = _target() ctx = _create_context(mod, target) sch = tir.Schedule(mod, debug_mask="all") # fmt: off # pylint: disable=line-too-long,invalid-name b0 = sch.get_block(name="C", func_name="main") b1 = sch.cache_write(block=b0, write_buffer_index=0, storage_scope="local") l2, l3, l4 = sch.get_loops(block=b0) sch.annotate(b0, "warp_execution", 1) v5, v6, v7, v8, v9 = sch.sample_perfect_tile(loop=l2, n=5, max_innermost_factor=64, decision=[1, 16, 1, 2, 16]) l10, l11, l12, l13, l14 = sch.split(loop=l2, factors=[v5, v6, v7, v8, v9]) v15, v16, v17, v18, v19 = sch.sample_perfect_tile(loop=l3, n=5, max_innermost_factor=64, decision=[16, 1, 8, 2, 2]) l20, l21, l22, l23, l24 = sch.split(loop=l3, factors=[v15, v16, v17, v18, v19]) v25, v26, v27 = sch.sample_perfect_tile(loop=l4, n=3, max_innermost_factor=64, decision=[1, 16, 32]) l28, l29, l30 = sch.split(loop=l4, factors=[v25, v26, v27]) sch.reorder(l10, l20, l11, l21, l12, l22, l28, l29, l13, l23, l30, l14, l24) l31 = sch.fuse(l10, l20) sch.bind(loop=l31, thread_axis="blockIdx.x") l32 = sch.fuse(l11, l21) sch.bind(loop=l32, thread_axis="vthread.x") l33 = sch.fuse(l12, l22) sch.bind(loop=l33, thread_axis="threadIdx.y") b34 = sch.cache_read(block=b0, read_buffer_index=0, storage_scope="shared") sch.compute_at(block=b34, loop=l28, preserve_unit_loops=True) _, _, _, _, l39, l40 = sch.get_loops(block=b34) l41 = sch.fuse(l39, l40) _, v43 = sch.sample_perfect_tile(loop=l41, n=2, max_innermost_factor=4, decision=[262144, 1]) sch.annotate(block_or_loop=b34, ann_key="meta_schedule.cooperative_fetch", ann_val=v43) b44 = sch.cache_read(block=b0, read_buffer_index=1, storage_scope="shared") sch.compute_at(block=b44, loop=l28, preserve_unit_loops=True) _, _, _, _, l49, l50 = sch.get_loops(block=b44) l51 = sch.fuse(l49, l50) _, v53 = sch.sample_perfect_tile(loop=l51, n=2, max_innermost_factor=4, decision=[8192, 2]) sch.annotate(block_or_loop=b44, ann_key="meta_schedule.cooperative_fetch", ann_val=v53) sch.reverse_compute_at(block=b1, loop=l33, preserve_unit_loops=True) # pylint: enable=line-too-long,invalid-name # fmt: on sch.enter_postproc() assert ctx.space_generator.postprocs[0].apply(sch) tvm.ir.assert_structural_equal(sch.mod, WarpExecutionAfterRewrite) if __name__ == "__main__": tvm.testing.main()
https://github.com/zk-ml/tachikoma
tests/python/unittest/test_meta_schedule_postproc_rewrite_layout.py
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. # pylint: disable=missing-module-docstring,missing-function-docstring,missing-class-docstring import tvm import tvm.testing from tvm import meta_schedule as ms from tvm.script import tir as T from tvm.target import Target def _target() -> Target: return Target("cuda", host="llvm") def _create_context(mod, target) -> ms.TuneContext: ctx = ms.TuneContext( mod=mod, target=target, space_generator=ms.space_generator.PostOrderApply( sch_rules=[], postprocs=[ ms.postproc.RewriteLayout(), ], mutator_probs={}, ), task_name="test", ) return ctx class BaseBeforeAfter(tvm.testing.CompareBeforeAfter): def transform(self): def inner(mod): target = Target("cuda", host="llvm") ctx = ms.TuneContext( mod=mod, target=target, space_generator=ms.space_generator.PostOrderApply( sch_rules=[], postprocs=[ ms.postproc.RewriteLayout(), ], mutator_probs={}, ), task_name="test", ) sch = tvm.tir.Schedule(mod, debug_mask="all") sch.enter_postproc() assert ctx.space_generator.postprocs[0].apply(sch) return sch.mod return inner class TestTIRMatmul(BaseBeforeAfter): """Main functionality test A new block should be inserted to transform the layout, with the compute block operating on the temporary transformed buffer. """ def before( A: T.Buffer[(16, 16), "float32"], B: T.Buffer[(16, 16), "float32"], C: T.Buffer[(16, 16), "float32"], ) -> None: T.func_attr({"layout_free_buffers": [1]}) for i0, j, k0, i1, k1 in T.grid(4, 16, 4, 4, 4): with T.block("matmul"): vi = T.axis.S(16, i0 * 4 + i1) vj = T.axis.S(16, j) vk = T.axis.R(16, k0 * 4 + k1) with T.init(): C[vi, vj] = T.float32(0) C[vi, vj] = C[vi, vj] + A[vi, vk] * B[vk, vj] def expected( A: T.Buffer[(16, 16), "float32"], B: T.Buffer[(16, 16), "float32"], C: T.Buffer[(16, 16), "float32"], ) -> None: T.func_attr({"layout_free_buffers": [1]}) B_reindex = T.alloc_buffer([16, 4, 4], dtype="float32") for ax0, ax1 in T.grid(16, 16): with T.block("layout_rewrite"): i0, i1 = T.axis.remap("SS", [ax0, ax1]) T.block_attr({"meta_schedule.layout_rewrite_preproc": True}) B_reindex[i1, i0 // 4, i0 % 4] = B[i0, i1] for i0, j, k0, i1, k1 in T.grid(4, 16, 4, 4, 4): with T.block("matmul"): vi = T.axis.spatial(16, i0 * 4 + i1) vj = T.axis.spatial(16, j) vk = T.axis.reduce(16, k0 * 4 + k1) with T.init(): C[vi, vj] = T.float32(0) C[vi, vj] = C[vi, vj] + A[vi, vk] * B_reindex[vj, vk // 4, vk % 4] class TestRewrittenBuffersMustOccurWithinBlock(BaseBeforeAfter): """Buffers must occur within a Block""" def before( A: T.Buffer[(16, 16), "float32"], ) -> None: T.func_attr({"layout_free_buffers": [0]}) for i, j in T.grid(16, 16): T.evaluate(A[i, j]) expected = tvm.TVMError class TestExtentOne(BaseBeforeAfter): """Buffers with dimensions of extent 1 can be transformed Regression test for a previous bug, in which the removal of trivial variables resulted in an error in `IndexMap::Inverse`. """ def before( A: T.Buffer[(16, 1), "float32"], ) -> None: T.func_attr({"layout_free_buffers": [0]}) for i, j in T.grid(16, 1): with T.block("block"): vi, vj = T.axis.remap("SS", [i, j]) T.evaluate(A[vi, vj]) def expected(A: T.Buffer[(16, 1), "float32"]): T.func_attr({"layout_free_buffers": [0]}) A_global = T.alloc_buffer([16], dtype="float32") for ax0, ax1 in T.grid(16, 1): with T.block("A_global"): v0, v1 = T.axis.remap("SS", [ax0, ax1]) T.block_attr({"meta_schedule.layout_rewrite_preproc": True}) A_global[v0] = A[v0, v1] for i, j in T.grid(16, 1): with T.block("block"): vi, vj = T.axis.remap("SS", [i, j]) T.evaluate(A_global[vi]) @T.prim_func def tir_matmul( A: T.Buffer[(16, 16), "float32"], B: T.Buffer[(16, 16), "float32"], C: T.Buffer[(16, 16), "float32"], ) -> None: T.func_attr({"layout_free_buffers": [1]}) for i0, j, k0, i1, k1 in T.grid(4, 16, 4, 4, 4): with T.block("matmul"): vi = T.axis.S(16, i0 * 4 + i1) vj = T.axis.S(16, j) vk = T.axis.R(16, k0 * 4 + k1) with T.init(): C[vi, vj] = T.float32(0) C[vi, vj] = C[vi, vj] + A[vi, vk] * B[vk, vj] @T.prim_func def rewritten_tir_matmul( A: T.Buffer[(16, 16), "float32"], B: T.Buffer[(16, 16), "float32"], C: T.Buffer[(16, 16), "float32"], ) -> None: T.func_attr({"layout_free_buffers": [1]}) B_reindex = T.alloc_buffer([16, 4, 4], dtype="float32") for ax0, ax1 in T.grid(16, 16): with T.block("layout_rewrite"): i0, i1 = T.axis.remap("SS", [ax0, ax1]) T.block_attr({"meta_schedule.layout_rewrite_preproc": True}) B_reindex[i1, i0 // 4, i0 % 4] = B[i0, i1] for i0, j, k0, i1, k1 in T.grid(4, 16, 4, 4, 4): with T.block("matmul"): vi = T.axis.spatial(16, i0 * 4 + i1) vj = T.axis.spatial(16, j) vk = T.axis.reduce(16, k0 * 4 + k1) with T.init(): C[vi, vj] = T.float32(0) C[vi, vj] = C[vi, vj] + A[vi, vk] * B_reindex[vj, vk // 4, vk % 4] def test_layout_rewrite(): target = _target() ctx = _create_context(tir_matmul, target) sch = tvm.tir.Schedule(tir_matmul, debug_mask="all") sch.enter_postproc() assert ctx.space_generator.postprocs[0].apply(sch) tvm.ir.assert_structural_equal(sch.mod["main"], rewritten_tir_matmul) if __name__ == "__main__": tvm.testing.main()
https://github.com/zk-ml/tachikoma
tests/python/unittest/test_meta_schedule_postproc_rewrite_parallel_vectorize_unroll.py
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. # pylint: disable=missing-module-docstring,missing-function-docstring,missing-class-docstring import tvm from tvm.meta_schedule.postproc import RewriteParallelVectorizeUnroll from tvm.script import tir as T from tvm.tir.schedule import Schedule # pylint: disable=invalid-name,no-member,line-too-long,too-many-nested-blocks,no-self-argument,not-callable,misplaced-comparison-constant # fmt: off @tvm.script.ir_module class Move_PUV: @T.prim_func def main(a: T.handle, b: T.handle) -> None: # function attr dict T.func_attr({"global_symbol": "main"}) A = T.match_buffer(a, [1024, 1024, 1024], dtype="float32") B = T.match_buffer(b, [1024, 1024, 1024], dtype="float32") # body with T.block("root"): T.block_attr({"meta_schedule.parallel":128, "meta_schedule.vectorize":32}) for i0, j0, i1, j1, k0, i2, j2, k1 in T.grid(128, 64, 4, 4, 64, 4, 8, 32): with T.block("move"): vi = T.axis.spatial(1024, i0 * 16 + i1 * 4 + i2) vj = T.axis.spatial(1024, j0 * 32 + j1 * 8 + j2) vk = T.axis.spatial(1024, k0 * 32 + k1) T.where((i0 * 4 + i1) * 4 + i2 < 1024 and (j0 * 4 + j1) * 8 + j2 < 1024 and k0 * 32 + k1 < 1024) T.reads([A[vi, vj, vk]]) T.writes([B[vi, vj, vk]]) B[vi, vj, vk] = A[vi, vj, vk] @T.prim_func def Move_PUV0(a: T.handle, b: T.handle) -> None: # function attr dict T.func_attr({"global_symbol": "main"}) A = T.match_buffer(a, [1024, 1024, 1024], dtype="float32") B = T.match_buffer(b, [1024, 1024, 1024], dtype="float32") # body with T.block("root"): for i0_j0_fused in T.parallel(0, 8192): for i1, j1, k0, i2, j2 in T.grid(4, 4, 64, 4, 8): for k1_fused in T.vectorized(0, 32): with T.block("move"): vi = T.axis.spatial(1024, i0_j0_fused // 64 * 16 + i1 * 4 + i2) vj = T.axis.spatial(1024, i0_j0_fused % 64 * 32 + j1 * 8 + j2) vk = T.axis.spatial(1024, k0 * 32 + k1_fused) T.where( i0_j0_fused // 64 * 16 + i1 * 4 + i2 < 1024 and i0_j0_fused % 64 * 32 + j1 * 8 + j2 < 1024 and k0 * 32 + k1_fused < 1024 ) T.reads([A[vi, vj, vk]]) T.writes([B[vi, vj, vk]]) B[vi, vj, vk] = A[vi, vj, vk] @tvm.script.ir_module class Fused_NN_Dense: @T.prim_func def main(placeholder: T.Buffer[(64, 768), "float32"], placeholder_1: T.Buffer[(768, 768), "float32"], T_matmul_NT: T.Buffer[(64, 768), "float32"]) -> None: for i0, i1, i2 in T.grid(64, 768, 768): with T.block("T_matmul_NT"): i, j, k = T.axis.remap("SSR", [i0, i1, i2]) T.reads(placeholder[i, k], placeholder_1[j, k]) T.writes(T_matmul_NT[i, j]) with T.init(): T_matmul_NT[i, j] = T.float32(0) T_matmul_NT[i, j] = T_matmul_NT[i, j] + placeholder[i, k] * placeholder_1[j, k] @T.prim_func def before_matmul_vectorize( placeholder: T.Buffer[(64, 768), "float32"], placeholder_1: T.Buffer[(768, 768), "float32"], T_matmul_NT: T.Buffer[(64, 768), "float32"], ) -> None: with T.block("root"): T.reads() T.writes() T.block_attr({"meta_schedule.vectorize":64}) T_matmul_NT_global = T.alloc_buffer([64, 768], dtype="float32") for i0_0, i1_0, i0_1, i1_1 in T.grid(1, 16, 1, 3): for i2_0, i0_2, i1_2, i2_1, i0_3, i1_3 in T.grid(48, 8, 1, 16, 8, 16): with T.block("T_matmul_NT"): i = T.axis.spatial(64, i0_2 * 8 + i0_3) j = T.axis.spatial(768, i1_0 * 48 + i1_1 * 16 + i1_3) k = T.axis.reduce(768, i2_0 * 16 + i2_1) T.reads(placeholder[i, k], placeholder_1[j, k]) T.writes(T_matmul_NT_global[i, j]) with T.init(): T_matmul_NT_global[i, j] = T.float32(0) T_matmul_NT_global[i, j] = T_matmul_NT_global[i, j] + placeholder[i, k] * placeholder_1[j, k] for ax0, ax1 in T.grid(64, 16): with T.block("T_matmul_NT_global"): v0 = T.axis.spatial(64, ax0) v1 = T.axis.spatial(768, i1_0 * 48 + i1_1 * 16 + ax1) T.reads(T_matmul_NT_global[v0, v1]) T.writes(T_matmul_NT[v0, v1]) T_matmul_NT[v0, v1] = T_matmul_NT_global[v0, v1] @T.prim_func def after_matmul_vectorize( placeholder: T.Buffer[(64, 768), "float32"], placeholder_1: T.Buffer[(768, 768), "float32"], T_matmul_NT: T.Buffer[(64, 768), "float32"], ) -> None: T_matmul_NT_global = T.alloc_buffer([64, 768], dtype="float32") for i0_0, i1_0, i0_1, i1_1 in T.grid(1, 16, 1, 3): for i2_0, i0_2, i1_2, i2_1, i0_3 in T.grid(48, 8, 1, 16, 8): for i1_3_fused in T.vectorized(16): with T.block("T_matmul_NT"): i = T.axis.spatial(64, i0_2 * 8 + i0_3) j = T.axis.spatial(768, i1_0 * 48 + i1_1 * 16 + i1_3_fused) k = T.axis.reduce(768, i2_0 * 16 + i2_1) T.reads(placeholder[i, k], placeholder_1[j, k]) T.writes(T_matmul_NT_global[i, j]) with T.init(): T_matmul_NT_global[i, j] = T.float32(0) T_matmul_NT_global[i, j] = T_matmul_NT_global[i, j] + placeholder[i, k] * placeholder_1[j, k] for ax0 in T.serial(64): for ax1_fused in T.vectorized(16): with T.block("T_matmul_NT_global"): v0 = T.axis.spatial(64, ax0) v1 = T.axis.spatial(768, i1_0 * 48 + i1_1 * 16 + ax1_fused) T.reads(T_matmul_NT_global[v0, v1]) T.writes(T_matmul_NT[v0, v1]) T_matmul_NT[v0, v1] = T_matmul_NT_global[v0, v1] # fmt: on # pylint: enable=invalid-name,no-member,line-too-long,too-many-nested-blocks,no-self-argument,not-callable def test_meta_schedule_postproc_rewrite_parallel_unroll_vectorize(): postproc = RewriteParallelVectorizeUnroll() sch = Schedule(Move_PUV) assert postproc.apply(sch) mod = tvm.tir.transform.Simplify()(sch.mod) tvm.ir.assert_structural_equal(mod["main"], Move_PUV0) def test_vectorize_inner_loop(): sch = Schedule(before_matmul_vectorize) rule = RewriteParallelVectorizeUnroll() assert rule.apply(sch) tvm.ir.assert_structural_equal(sch.mod["main"], after_matmul_vectorize) if __name__ == "__main__": test_meta_schedule_postproc_rewrite_parallel_unroll_vectorize() test_vectorize_inner_loop()
https://github.com/zk-ml/tachikoma
tests/python/unittest/test_meta_schedule_postproc_rewrite_reduction_block.py
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. # pylint: disable=missing-module-docstring,missing-function-docstring,missing-class-docstring import tvm from tvm import meta_schedule as ms from tvm import tir from tvm.script import tir as T from tvm.target import Target def _target() -> Target: return Target("cuda", host="llvm") def _create_context(mod, target) -> ms.TuneContext: ctx = ms.TuneContext( mod=mod, target=target, space_generator=ms.space_generator.PostOrderApply( sch_rules=[], postprocs=[ ms.postproc.RewriteReductionBlock(), ], mutator_probs={}, ), task_name="test", ) return ctx # fmt: off # pylint: disable=no-member,invalid-name,unused-variable,no-self-argument,line-too-long,chained-comparison,not-callable,too-many-nested-blocks @tvm.script.ir_module class Matmul_before_rewrite: @T.prim_func def main(var_A: T.handle, var_B: T.handle, var_C: T.handle) -> None: A = T.match_buffer(var_A, [512, 512], dtype="float32") B = T.match_buffer(var_B, [512, 512], dtype="float32") C = T.match_buffer(var_C, [512, 512], dtype="float32") C_local = T.alloc_buffer([512, 512], dtype="float32", scope="local") A_shared = T.alloc_buffer([512, 512], dtype="float32", scope="shared") B_shared = T.alloc_buffer([512, 512], dtype="float32", scope="shared") for i0_0_i1_0_fused in T.thread_binding(0, 16, thread="blockIdx.x"): for i0_1_i1_1_fused in T.thread_binding(0, 16, thread="vthread.x"): for i0_2_i1_2_fused in T.thread_binding(0, 8, thread="threadIdx.x"): for i2_0 in T.serial(0, 1): for ax0_ax1_fused_0 in T.serial(0, 32768): for ax0_ax1_fused_1 in T.thread_binding(0, 8, thread="threadIdx.x"): with T.block("A_shared"): v0 = T.axis.spatial(512, (ax0_ax1_fused_0 * 8 + ax0_ax1_fused_1) // 512) v1 = T.axis.spatial(512, (ax0_ax1_fused_0 * 8 + ax0_ax1_fused_1) % 512) T.reads([A[v0, v1]]) T.writes([A_shared[v0, v1]]) T.block_attr({"meta_schedule.cooperative_fetch":1}) A_shared[v0, v1] = A[v0, v1] for ax0_ax1_fused_0 in T.serial(0, 1024): for ax0_ax1_fused_1 in T.thread_binding(0, 8, thread="threadIdx.x"): for ax0_ax1_fused_2 in T.vectorized(0, 2): with T.block("B_shared"): v0 = T.axis.spatial(512, (ax0_ax1_fused_0 * 16 + ax0_ax1_fused_1 * 2 + ax0_ax1_fused_2) // 32) v1 = T.axis.spatial(512, i0_0_i1_0_fused * 32 + (ax0_ax1_fused_0 * 16 + ax0_ax1_fused_1 * 2 + ax0_ax1_fused_2) % 32) T.reads([B[v0, v1]]) T.writes([B_shared[v0, v1]]) T.block_attr({"meta_schedule.cooperative_fetch":2}) B_shared[v0, v1] = B[v0, v1] for i2_1, i0_3, i1_3, i2_2, i0_4, i1_4 in T.grid(16, 2, 2, 32, 16, 2): with T.block("C"): i = T.axis.spatial(512, i0_1_i1_1_fused * 32 + i0_3 * 16 + i0_4) j = T.axis.spatial(512, i0_0_i1_0_fused * 32 + i0_2_i1_2_fused * 4 + i1_3 * 2 + i1_4) k = T.axis.reduce(512, i2_1 * 32 + i2_2) T.reads([C_local[i, j], A_shared[i, k], B_shared[k, j]]) T.writes([C_local[i, j]]) with T.init(): C_local[i, j] = T.float32(0) C_local[i, j] = C_local[i, j] + A_shared[i, k] * B_shared[k, j] for ax0, ax1 in T.grid(32, 4): with T.block("C_local"): v0 = T.axis.spatial(512, i0_1_i1_1_fused * 32 + ax0) v1 = T.axis.spatial(512, i0_0_i1_0_fused * 32 + i0_2_i1_2_fused * 4 + ax1) T.reads([C_local[v0, v1]]) T.writes([C[v0, v1]]) C[v0, v1] = C_local[v0, v1] @tvm.script.ir_module class Matmul_after_rewrite: @T.prim_func def main(var_A: T.handle, var_B: T.handle, var_C: T.handle) -> None: A = T.match_buffer(var_A, [512, 512], dtype="float32") B = T.match_buffer(var_B, [512, 512], dtype="float32") C = T.match_buffer(var_C, [512, 512], dtype="float32") C_local = T.alloc_buffer([512, 512], dtype="float32", scope="local") A_shared = T.alloc_buffer([512, 512], dtype="float32", scope="shared") B_shared = T.alloc_buffer([512, 512], dtype="float32", scope="shared") for i0_0_i1_0_fused in T.thread_binding(0, 16, thread="blockIdx.x"): for i0_1_i1_1_fused in T.thread_binding(0, 16, thread="vthread.x"): for i0_2_i1_2_fused in T.thread_binding(0, 8, thread="threadIdx.x"): for i2_0 in T.serial(0, 1): for ax0_ax1_fused_0 in T.serial(0, 32768): for ax0_ax1_fused_1 in T.thread_binding(0, 8, thread="threadIdx.x"): with T.block("A_shared"): v0 = T.axis.spatial(512, (ax0_ax1_fused_0 * 8 + ax0_ax1_fused_1) // 512) v1 = T.axis.spatial(512, (ax0_ax1_fused_0 * 8 + ax0_ax1_fused_1) % 512) T.reads([A[v0, v1]]) T.writes([A_shared[v0, v1]]) T.block_attr({"meta_schedule.cooperative_fetch":1}) A_shared[v0, v1] = A[v0, v1] for ax0_ax1_fused_0 in T.serial(0, 1024): for ax0_ax1_fused_1 in T.thread_binding(0, 8, thread="threadIdx.x"): for ax0_ax1_fused_2 in T.vectorized(0, 2): with T.block("B_shared"): v0 = T.axis.spatial(512, (ax0_ax1_fused_0 * 16 + ax0_ax1_fused_1 * 2 + ax0_ax1_fused_2) // 32) v1 = T.axis.spatial(512, i0_0_i1_0_fused * 32 + (ax0_ax1_fused_0 * 16 + ax0_ax1_fused_1 * 2 + ax0_ax1_fused_2) % 32) T.reads([B[v0, v1]]) T.writes([B_shared[v0, v1]]) T.block_attr({"meta_schedule.cooperative_fetch":2}) B_shared[v0, v1] = B[v0, v1] for i0_3_init, i1_3_init, i0_4_init, i1_4_init in T.grid(2, 2, 16, 2): with T.block("C_init"): i = T.axis.spatial(512, i0_1_i1_1_fused * 32 + i0_3_init * 16 + i0_4_init) j = T.axis.spatial(512, i0_0_i1_0_fused * 32 + i0_2_i1_2_fused * 4 + i1_3_init * 2 + i1_4_init) T.reads([]) T.writes([C_local[i, j]]) C_local[i, j] = T.float32(0) for i2_1, i0_3, i1_3, i2_2, i0_4, i1_4 in T.grid(16, 2, 2, 32, 16, 2): with T.block("C_update"): i = T.axis.spatial(512, i0_1_i1_1_fused * 32 + i0_3 * 16 + i0_4) j = T.axis.spatial(512, i0_0_i1_0_fused * 32 + i0_2_i1_2_fused * 4 + i1_3 * 2 + i1_4) k = T.axis.reduce(512, i2_1 * 32 + i2_2) T.reads([C_local[i, j], A_shared[i, k], B_shared[k, j]]) T.writes([C_local[i, j]]) C_local[i, j] = C_local[i, j] + A_shared[i, k] * B_shared[k, j] for ax0, ax1 in T.grid(32, 4): with T.block("C_local"): v0 = T.axis.spatial(512, i0_1_i1_1_fused * 32 + ax0) v1 = T.axis.spatial(512, i0_0_i1_0_fused * 32 + i0_2_i1_2_fused * 4 + ax1) T.reads([C_local[v0, v1]]) T.writes([C[v0, v1]]) C[v0, v1] = C_local[v0, v1] @tvm.script.ir_module class Softmax_cross_thread_reduction: @T.prim_func def main(A: T.Buffer[(256, 256), "float32"], T_softmax_norm: T.Buffer[(256, 256), "float32"]) -> None: T_softmax_maxelem_shared = T.alloc_buffer([256], dtype="float32", scope="shared") T_softmax_expsum_shared = T.alloc_buffer([256], dtype="float32", scope="shared") for i0 in T.serial(256): for ax0, ax1_0 in T.grid(1, 8): for ax1_1 in T.thread_binding(32, thread="threadIdx.x"): with T.block("T_softmax_maxelem"): i0_1 = T.axis.spatial(256, i0) k = T.axis.reduce(256, ax1_0 * 32 + ax1_1) T.reads(T_softmax_maxelem_shared[i0_1], A[i0_1, k]) T.writes(T_softmax_maxelem_shared[i0_1]) with T.init(): T_softmax_maxelem_shared[i0_1] = T.float32(-3.4028234663852886e+38) T_softmax_maxelem_shared[i0_1] = T.max(T_softmax_maxelem_shared[i0_1], A[i0_1, k]) for ax0, ax1_0 in T.grid(1, 8): for ax1_1 in T.thread_binding(32, thread="threadIdx.x"): with T.block("T_softmax_expsum"): i0_2 = T.axis.spatial(256, i0) k = T.axis.reduce(256, ax1_0 * 32 + ax1_1) T.reads(T_softmax_expsum_shared[i0_2], A[i0_2, k], T_softmax_maxelem_shared[i0_2]) T.writes(T_softmax_expsum_shared[i0_2]) with T.init(): T_softmax_expsum_shared[i0_2] = T.float32(0) T_softmax_expsum_shared[i0_2] = T_softmax_expsum_shared[i0_2] + T.exp(A[i0_2, k] - T_softmax_maxelem_shared[i0_2], dtype="float32") for i1_0 in T.serial(8): for i1_1 in T.thread_binding(32, thread="threadIdx.x"): with T.block("T_softmax_norm"): i0_3 = T.axis.spatial(256, i0) i1 = T.axis.spatial(256, i1_0 * 32 + i1_1) T.reads(A[i0_3, i1], T_softmax_maxelem_shared[i0_3], T_softmax_expsum_shared[i0_3]) T.writes(T_softmax_norm[i0_3, i1]) T.block_attr({"axis":1}) T_softmax_norm[i0_3, i1] = T.exp(A[i0_3, i1] - T_softmax_maxelem_shared[i0_3], dtype="float32") / T_softmax_expsum_shared[i0_3] # pylint: enable=no-member,invalid-name,unused-variable,no-self-argument,line-too-long,chained-comparison,not-callable,too-many-nested-blocks # fmt: on def test_rewrite_tiled_matmul(): mod = Matmul_before_rewrite target = _target() ctx = _create_context(mod, target) sch = tir.Schedule(mod, debug_mask="all") sch.enter_postproc() assert ctx.space_generator.postprocs[0].apply(sch) tvm.ir.assert_structural_equal(sch.mod, Matmul_after_rewrite) def test_rewrite_softmax(): mod = Softmax_cross_thread_reduction target = _target() ctx = _create_context(mod, target) sch = tir.Schedule(mod, debug_mask="all") sch.enter_postproc() assert ctx.space_generator.postprocs[0].apply(sch) # The module should not be rewritten tvm.ir.assert_structural_equal(sch.mod, Softmax_cross_thread_reduction) if __name__ == "__main__": test_rewrite_tiled_matmul() test_rewrite_softmax()
https://github.com/zk-ml/tachikoma
tests/python/unittest/test_meta_schedule_postproc_rewrite_tensorize.py
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. # pylint: disable=missing-module-docstring,missing-function-docstring,missing-class-docstring import tvm from tvm import meta_schedule as ms from tvm.script import tir as T from tvm.tir.tensor_intrin import arm_cpu, cuda, rocm, x86 @tvm.script.ir_module class Conv2dNCHWcVNNIModuleTiled: @T.prim_func def main( placeholder: T.Buffer[(1, 4, 56, 56, 16), "uint8"], placeholder_1: T.Buffer[(16, 4, 1, 1, 4, 16, 4), "int8"], conv2d_NCHWc_int8: T.Buffer[(1, 16, 56, 56, 16), "int32"], ) -> None: T.func_attr({"global_symbol": "main", "tir.noalias": True}) for ( i0_0, i1_0, i2_0, i3_0, i4_0_0, i0_1, i1_1, i2_1, i3_1, i4_0_1, i5_0, i6_0, i7_0, i8_0, i9_0_0, i0_2, i1_2, i2_2, i3_2, i4_0_2, i5_1, i6_1, i7_1, i8_1, i9_0_1, i0_3, i1_3, i2_3, i3_3, i4_0_3, ) in T.grid( 1, 1, 2, 1, 1, 1, 4, 1, 14, 1, 1, 1, 4, 1, 1, 1, 4, 7, 1, 1, 1, 1, 1, 4, 1, 1, 1, 4, 4, 1, ): with T.block("conv2d_NCHWc_int8_o"): n = T.axis.spatial(1, 0) oc_chunk = T.axis.spatial(16, i1_1 * 4 + i1_2) oh = T.axis.spatial(56, i2_0 * 28 + i2_2 * 4 + i2_3) ow = T.axis.spatial(56, i3_1 * 4 + i3_3) oc_block_o = T.axis.spatial(1, 0) kh = T.axis.reduce(1, 0) kw = T.axis.reduce(1, 0) ic_outer, ic_f_inner = T.axis.remap("RR", [i7_0, i8_1]) ic_s_inner_o = T.axis.reduce(1, 0) T.reads( placeholder[n, ic_outer, oh + kh, ow + kw, ic_f_inner * 4 : ic_f_inner * 4 + 4], placeholder_1[oc_chunk, ic_outer, kh, kw, ic_f_inner, 0:16, 0:4], ) T.writes(conv2d_NCHWc_int8[n, oc_chunk, oh, ow, 0:16]) T.block_attr({"meta_schedule.auto_tensorize": "dot_16x4_vnni"}) with T.init(): for i4_1 in T.serial(16): with T.block("conv2d_NCHWc_int8_init"): oc_block_init = T.axis.spatial(16, i4_1) T.reads() T.writes(conv2d_NCHWc_int8[n, oc_chunk, oh, ow, oc_block_init]) conv2d_NCHWc_int8[n, oc_chunk, oh, ow, oc_block_init] = 0 for i4_1, i9_1 in T.grid(16, 4): with T.block("conv2d_NCHWc_int8"): oc_block, ic_s_inner = T.axis.remap("SR", [i4_1, i9_1]) T.reads( conv2d_NCHWc_int8[n, oc_chunk, oh, ow, oc_block], placeholder[n, ic_outer, oh + kh, ow + kw, ic_f_inner * 4 + ic_s_inner], placeholder_1[ oc_chunk, ic_outer, kh, kw, ic_f_inner, oc_block, ic_s_inner ], ) T.writes(conv2d_NCHWc_int8[n, oc_chunk, oh, ow, oc_block]) T.block_attr({"meta_schedule.tiling_structure": "SSRSRS"}) conv2d_NCHWc_int8[n, oc_chunk, oh, ow, oc_block] = conv2d_NCHWc_int8[ n, oc_chunk, oh, ow, oc_block ] + T.cast( placeholder[n, ic_outer, oh + kh, ow + kw, ic_f_inner * 4 + ic_s_inner], "int32", ) * T.cast( placeholder_1[ oc_chunk, ic_outer, kh, kw, ic_f_inner, oc_block, ic_s_inner ], "int32", ) @tvm.script.ir_module class Conv2dNCHWcVNNIModuleTensorized: @T.prim_func def main( placeholder: T.Buffer[(1, 4, 56, 56, 16), "uint8"], placeholder_1: T.Buffer[(16, 4, 1, 1, 4, 16, 4), "int8"], conv2d_NCHWc_int8: T.Buffer[(1, 16, 56, 56, 16), "int32"], ) -> None: # function attr dict T.func_attr({"global_symbol": "main", "tir.noalias": True}) # body # with T.block("root") for i0_0, i1_0, i2_0, i3_0, i4_0_0, i0_1, i1_1, i2_1, i3_1, i4_0_1, i5_0, i6_0 in T.grid( 1, 1, 2, 1, 1, 1, 4, 1, 14, 1, 1, 1 ): for i1_2_init, i2_2_init, i2_3_init, i3_3_init in T.grid(4, 7, 4, 4): with T.block("conv2d_NCHWc_int8_o_init"): n = T.axis.spatial(1, 0) oc_chunk = T.axis.spatial(16, i1_1 * 4 + i1_2_init) oh = T.axis.spatial(56, i2_0 * 28 + i2_2_init * 4 + i2_3_init) ow = T.axis.spatial(56, i3_1 * 4 + i3_3_init) oc_block_o = T.axis.spatial(1, 0) T.reads() T.writes(conv2d_NCHWc_int8[n, oc_chunk, oh, ow, 0:16]) for i4_1 in T.vectorized(16): with T.block("conv2d_NCHWc_int8_init"): oc_block_init = T.axis.spatial(16, i4_1) T.reads() T.writes(conv2d_NCHWc_int8[n, oc_chunk, oh, ow, oc_block_init]) conv2d_NCHWc_int8[n, oc_chunk, oh, ow, oc_block_init] = 0 for ( i7_0, i8_0, i9_0_0, i0_2, i1_2, i2_2, i3_2, i4_0_2, i5_1, i6_1, i7_1, i8_1, i9_0_1, i0_3, i1_3, i2_3, i3_3, i4_0_3, ) in T.grid(4, 1, 1, 1, 4, 7, 1, 1, 1, 1, 1, 4, 1, 1, 1, 4, 4, 1): with T.block("conv2d_NCHWc_int8_o_update"): n = T.axis.spatial(1, 0) oc_chunk = T.axis.spatial(16, i1_1 * 4 + i1_2) oh = T.axis.spatial(56, i2_0 * 28 + i2_2 * 4 + i2_3) ow = T.axis.spatial(56, i3_1 * 4 + i3_3) oc_block_o = T.axis.spatial(1, 0) kh = T.axis.reduce(1, 0) kw = T.axis.reduce(1, 0) ic_outer, ic_f_inner = T.axis.remap("RR", [i7_0, i8_1]) ic_s_inner_o = T.axis.reduce(1, 0) T.reads( conv2d_NCHWc_int8[n, oc_chunk, oh, ow, 0:16], placeholder[ n, ic_outer, oh + kh, ow + kw, ic_f_inner * 4 : ic_f_inner * 4 + 4 ], placeholder_1[oc_chunk, ic_outer, kh, kw, ic_f_inner, 0:16, 0:4], ) T.writes(conv2d_NCHWc_int8[n, oc_chunk, oh, ow, 0:16]) A = T.match_buffer( placeholder[ n, ic_outer, oh + kh, ow + kw, ic_f_inner * 4 : ic_f_inner * 4 + 4 ], [4], dtype="uint8", offset_factor=1, ) B = T.match_buffer( placeholder_1[oc_chunk, ic_outer, kh, kw, ic_f_inner, 0:16, 0:4], [16, 4], dtype="int8", offset_factor=1, ) C = T.match_buffer( conv2d_NCHWc_int8[n, oc_chunk, oh, ow, 0:16], [16], dtype="int32", offset_factor=1, ) A_u8x4 = A.vload([0], "uint8x4") A_i32 = T.reinterpret(A_u8x4, dtype="int32") B_i8x64 = B.vload([0, 0], dtype="int8x64") B_i32x16 = T.reinterpret(B_i8x64, dtype="int32x16") C_i32x16 = C.vload([0], dtype="int32x16") C[T.ramp(0, 1, 16)] = T.call_llvm_pure_intrin( T.llvm_lookup_intrinsic_id("llvm.x86.avx512.vpdpbusd.512"), T.uint32(0), C_i32x16, T.broadcast(A_i32, 16), B_i32x16, dtype="int32x16", ) @tvm.script.ir_module class DenseDP4ATiled: @T.prim_func def main( X: T.Buffer[(128, 128), "int8"], W: T.Buffer[(128, 128), "int8"], compute: T.Buffer[(128, 128), "int32"], ) -> None: T.func_attr({"global_symbol": "main", "tir.noalias": True}) compute_local = T.alloc_buffer([128, 128], dtype="int32", scope="local") X_shared = T.alloc_buffer([128, 128], dtype="int8", scope="shared") W_shared = T.alloc_buffer([128, 128], dtype="int8", scope="shared") for i0_0_i1_0_fused in T.thread_binding(16, thread="blockIdx.x"): for i0_1_i1_1_fused in T.thread_binding(2, thread="vthread.x"): for i0_2_i1_2_fused in T.thread_binding(2, thread="threadIdx.x"): for i2_0_0 in T.serial(2): for ax0_ax1_fused in T.serial(1024): with T.block("X_shared"): v0 = T.axis.spatial( 128, i0_0_i1_0_fused // 2 * 16 + ax0_ax1_fused // 64 ) v1 = T.axis.spatial(128, i2_0_0 * 64 + ax0_ax1_fused % 64) T.reads(X[v0, v1]) T.writes(X_shared[v0, v1]) T.block_attr({"meta_schedule.cooperative_fetch": 4}) X_shared[v0, v1] = X[v0, v1] for ax0_ax1_fused in T.serial(4096): with T.block("W_shared"): v0 = T.axis.spatial( 128, i0_0_i1_0_fused % 2 * 64 + ax0_ax1_fused // 64 ) v1 = T.axis.spatial(128, i2_0_0 * 64 + ax0_ax1_fused % 64) T.reads(W[v0, v1]) T.writes(W_shared[v0, v1]) T.block_attr({"meta_schedule.cooperative_fetch": 1}) W_shared[v0, v1] = W[v0, v1] for i2_0_1, i0_3, i1_3, i2_0_2, i0_4, i1_4 in T.grid(2, 4, 16, 8, 4, 1): with T.block("compute_o"): i = T.axis.spatial(128, i0_0_i1_0_fused // 2 * 16 + i0_3 * 4 + i0_4) j = T.axis.spatial( 128, i0_0_i1_0_fused % 2 * 64 + i0_1_i1_1_fused * 32 + i0_2_i1_2_fused * 16 + i1_3, ) k_o = T.axis.reduce(32, i2_0_0 * 16 + i2_0_1 * 8 + i2_0_2) T.reads( X_shared[i, k_o * 4 : k_o * 4 + 4], W_shared[j, k_o * 4 : k_o * 4 + 4], ) T.writes(compute_local[i, j]) T.block_attr({"meta_schedule.auto_tensorize": "dp4a"}) with T.init(): with T.block("compute_init"): T.reads() T.writes(compute_local[i, j]) compute_local[i, j] = 0 for i2_1 in T.serial(4): with T.block("compute"): k = T.axis.reduce(4, i2_1) T.reads( compute_local[i, j], X_shared[i, k_o * 4 + k], W_shared[j, k_o * 4 + k], ) T.writes(compute_local[i, j]) T.block_attr({"meta_schedule.tiling_structure": "SSSRRSRS"}) compute_local[i, j] = compute_local[i, j] + T.cast( X_shared[i, k_o * 4 + k], "int32" ) * T.cast(W_shared[j, k_o * 4 + k], "int32") for ax0, ax1 in T.grid(16, 16): with T.block("compute_local"): v0 = T.axis.spatial(128, i0_0_i1_0_fused // 2 * 16 + ax0) v1 = T.axis.spatial( 128, i0_0_i1_0_fused % 2 * 64 + i0_1_i1_1_fused * 32 + i0_2_i1_2_fused * 16 + ax1, ) T.reads(compute_local[v0, v1]) T.writes(compute[v0, v1]) compute[v0, v1] = compute_local[v0, v1] @tvm.script.ir_module class DenseDP4ATensorized: @T.prim_func def main( X: T.Buffer[(128, 128), "int8"], W: T.Buffer[(128, 128), "int8"], compute: T.Buffer[(128, 128), "int32"], ) -> None: # function attr dict T.func_attr({"global_symbol": "main", "tir.noalias": True}) # body # with T.block("root") compute_local = T.alloc_buffer([128, 128], dtype="int32", scope="local") X_shared = T.alloc_buffer([128, 128], dtype="int8", scope="shared") W_shared = T.alloc_buffer([128, 128], dtype="int8", scope="shared") for i0_0_i1_0_fused in T.thread_binding(16, thread="blockIdx.x"): for i0_1_i1_1_fused in T.thread_binding(2, thread="vthread.x"): for i0_2_i1_2_fused in T.thread_binding(2, thread="threadIdx.x"): for i0_3_init, i1_3_init, i0_4_init in T.grid(4, 16, 4): with T.block("compute_o_init"): i = T.axis.spatial( 128, i0_0_i1_0_fused // 2 * 16 + i0_3_init * 4 + i0_4_init ) j = T.axis.spatial( 128, i0_0_i1_0_fused % 2 * 64 + i0_1_i1_1_fused * 32 + i0_2_i1_2_fused * 16 + i1_3_init, ) T.reads() T.writes(compute_local[i, j]) T.block_attr({"meta_schedule.auto_tensorize": ""}) with T.block("compute_init"): T.reads() T.writes(compute_local[i, j]) compute_local[i, j] = 0 for i2_0_0 in T.serial(2): for ax0_ax1_fused in T.serial(1024): with T.block("X_shared"): v0 = T.axis.spatial( 128, i0_0_i1_0_fused // 2 * 16 + ax0_ax1_fused // 64 ) v1 = T.axis.spatial(128, i2_0_0 * 64 + ax0_ax1_fused % 64) T.reads(X[v0, v1]) T.writes(X_shared[v0, v1]) T.block_attr({"meta_schedule.cooperative_fetch": 4}) X_shared[v0, v1] = X[v0, v1] for ax0_ax1_fused in T.serial(4096): with T.block("W_shared"): v0 = T.axis.spatial( 128, i0_0_i1_0_fused % 2 * 64 + ax0_ax1_fused // 64 ) v1 = T.axis.spatial(128, i2_0_0 * 64 + ax0_ax1_fused % 64) T.reads(W[v0, v1]) T.writes(W_shared[v0, v1]) T.block_attr({"meta_schedule.cooperative_fetch": 1}) W_shared[v0, v1] = W[v0, v1] for i2_0_1, i0_3, i1_3, i2_0_2, i0_4, i1_4 in T.grid(2, 4, 16, 8, 4, 1): with T.block("compute_o_update"): i = T.axis.spatial(128, i0_0_i1_0_fused // 2 * 16 + i0_3 * 4 + i0_4) j = T.axis.spatial( 128, i0_0_i1_0_fused % 2 * 64 + i0_1_i1_1_fused * 32 + i0_2_i1_2_fused * 16 + i1_3, ) k_o = T.axis.reduce(32, i2_0_0 * 16 + i2_0_1 * 8 + i2_0_2) T.reads( compute_local[i, j], X_shared[i, k_o * 4 : k_o * 4 + 4], W_shared[j, k_o * 4 : k_o * 4 + 4], ) T.writes(compute_local[i, j]) A = T.match_buffer( X_shared[i, k_o * 4 : k_o * 4 + 4], [4], dtype="int8", scope="shared", align=4, offset_factor=1, ) B = T.match_buffer( W_shared[j, k_o * 4 : k_o * 4 + 4], [4], dtype="int8", scope="shared", align=4, offset_factor=1, ) C = T.match_buffer( compute_local[i, j], [1], dtype="int32", scope="local", align=4, offset_factor=1, ) C[0] = C[0] + T.call_pure_extern( "__dp4a", A[T.ramp(0, 1, 4)], B[T.ramp(0, 1, 4)], 0, dtype="int32", ) for ax0, ax1 in T.grid(16, 16): with T.block("compute_local"): v0 = T.axis.spatial(128, i0_0_i1_0_fused // 2 * 16 + ax0) v1 = T.axis.spatial( 128, i0_0_i1_0_fused % 2 * 64 + i0_1_i1_1_fused * 32 + i0_2_i1_2_fused * 16 + ax1, ) T.reads(compute_local[v0, v1]) T.writes(compute[v0, v1]) compute[v0, v1] = compute_local[v0, v1] def _create_context(mod, target, postprocs) -> ms.TuneContext: ctx = ms.TuneContext( mod=mod, target=target, space_generator=ms.space_generator.PostOrderApply( sch_rules=[], postprocs=postprocs, mutator_probs={}, ), task_name="test", ) return ctx def test_rewrite_tensorize_conv2d_nchwc_vnni(): mod = Conv2dNCHWcVNNIModuleTiled target = tvm.target.Target("llvm -mcpu=cascadelake -num-cores 4") ctx = _create_context( mod, target, [ ms.postproc.RewriteReductionBlock(), ms.postproc.RewriteTensorize(True), ], ) sch = tvm.tir.Schedule(mod, debug_mask="all") sch.enter_postproc() for proc in ctx.space_generator.postprocs: proc.apply(sch) tvm.ir.assert_structural_equal(sch.mod, Conv2dNCHWcVNNIModuleTensorized) def test_rewrite_tensorize_dense_dp4a(): mod = DenseDP4ATiled target = tvm.target.Target("nvidia/geforce-rtx-3070") ctx = _create_context( mod, target, [ ms.postproc.RewriteCooperativeFetch(), ms.postproc.RewriteReductionBlock(), ms.postproc.RewriteTensorize(), ], ) sch = tvm.tir.Schedule(mod, debug_mask="all") sch.enter_postproc() for proc in ctx.space_generator.postprocs: proc.apply(sch) tvm.ir.assert_structural_equal(sch.mod, DenseDP4ATensorized) if __name__ == "__main__": test_rewrite_tensorize_conv2d_nchwc_vnni() test_rewrite_tensorize_dense_dp4a()
https://github.com/zk-ml/tachikoma
tests/python/unittest/test_meta_schedule_postproc_rewrite_unbound_block.py
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. # pylint: disable=missing-module-docstring,missing-function-docstring,missing-class-docstring import tvm from tvm import meta_schedule as ms from tvm import tir from tvm.script import tir as T from tvm.target import Target def _target() -> Target: return Target("cuda --max_threads_per_block=1024", host="llvm") def _create_context(mod, target) -> ms.TuneContext: ctx = ms.TuneContext( mod=mod, target=target, space_generator=ms.space_generator.PostOrderApply( sch_rules=[], postprocs=[ms.postproc.RewriteUnboundBlock()], mutator_probs={}, ), task_name="test", ) return ctx # pylint: disable=no-member,invalid-name,unused-variable,no-self-argument,line-too-long,chained-comparison,not-callable,too-many-nested-blocks @tvm.script.ir_module class Before_cooperative_fetch: @T.prim_func def main(var_A: T.handle, var_B: T.handle) -> None: A = T.match_buffer(var_A, [512, 512], dtype="float32") B = T.match_buffer(var_B, [512, 512], dtype="float32") for i, j in T.grid(512, 512): with T.block("C"): vi, vj = T.axis.remap("SS", [i, j]) B[vi, vj] = A[vi, vj] + 1.0 @tvm.script.ir_module class After_cooperative_fetch: @T.prim_func def main(var_A: T.handle, var_B: T.handle) -> None: A = T.match_buffer(var_A, [512, 512], dtype="float32") B = T.match_buffer(var_B, [512, 512], dtype="float32") for i_j_fused_0 in T.thread_binding(256, thread="blockIdx.x"): for i_j_fused_1 in T.thread_binding(1024, thread="threadIdx.x"): with T.block("C"): vi = T.axis.spatial(512, (i_j_fused_0 * 1024 + i_j_fused_1) // 512) vj = T.axis.spatial(512, (i_j_fused_0 * 1024 + i_j_fused_1) % 512) B[vi, vj] = A[vi, vj] + 1.0 @tvm.script.ir_module class Before_norm_bmn: @T.prim_func def main(A: T.Buffer[(1, 256, 256), "float32"], D: T.Buffer[(1,), "float32"]) -> None: C = T.alloc_buffer([1], dtype="float32") for i0, i1, i2 in T.grid(1, 256, 256): with T.block("C"): b, i, j = T.axis.remap("SRR", [i0, i1, i2]) with T.init(): C[b] = T.float32(0) C[b] = C[b] + A[b, i, j] * A[b, i, j] for i0 in T.serial(1): with T.block("D"): b = T.axis.S(1, i0) D[b] = T.sqrt(C[b], dtype="float32") @tvm.script.ir_module class After_norm_bmn: @T.prim_func def main(A: T.Buffer[(1, 256, 256), "float32"], D: T.Buffer[(1,), "float32"]) -> None: C = T.alloc_buffer([1], dtype="float32") for i0_fused_0 in T.thread_binding(1, thread="blockIdx.x"): for i0_fused_1 in T.thread_binding(1, thread="threadIdx.x"): for i1, i2 in T.grid(256, 256): with T.block("C"): b = T.axis.S(1, 0) i, j = T.axis.remap("RR", [i1, i2]) with T.init(): C[b] = T.float32(0) C[b] = C[b] + A[b, i, j] * A[b, i, j] for i0_fused_0 in T.thread_binding(1, thread="blockIdx.x"): for i0_fused_1 in T.thread_binding(1, thread="threadIdx.x"): with T.block("D"): b = T.axis.S(1, 0) D[b] = T.sqrt(C[b], dtype="float32") @tvm.script.ir_module class Bert_fused_reshape_transpose_reshape: @T.prim_func def main( placeholder: T.Buffer[(12, 64, 64), "float32"], T_reshape: T.Buffer[(64, 768), "float32"] ) -> None: for i0_i1_fused_0, i0_i1_fused_1 in T.grid(1536, 32): with T.block("T_reshape_1"): ax0 = T.axis.spatial(64, (i0_i1_fused_0 * 32 + i0_i1_fused_1) // 768) ax1 = T.axis.spatial(768, (i0_i1_fused_0 * 32 + i0_i1_fused_1) % 768) T.reads(placeholder[ax1 % 768 // 64, (ax1 // 768 + ax0) % 64, ax1 % 64]) T.writes(T_reshape[ax0, ax1]) T_reshape[ax0, ax1] = placeholder[ ((ax1 % 64 // 64 + (ax1 // 768 + ax0) % 64) // 64 + ax1 % 768 // 64) % 12, (ax1 % 64 // 64 + (ax1 // 768 + ax0) % 64) % 64, ax1 % 64 % 64, ] @tvm.script.ir_module class Bert_fused_reshape_transpose_reshape_large: @T.prim_func def main( placeholder: T.Buffer[(12, 64, 64), "float32"], T_reshape: T.Buffer[(64, 768), "float32"] ) -> None: for i0_i1_fused_0, i0_i1_fused_1 in T.grid(1536000, 32): with T.block("T_reshape_1"): ax0 = T.axis.spatial(64, (i0_i1_fused_0 * 32 + i0_i1_fused_1) // 768) ax1 = T.axis.spatial(768, (i0_i1_fused_0 * 32 + i0_i1_fused_1) % 768) T.reads(placeholder[ax1 % 768 // 64, (ax1 // 768 + ax0) % 64, ax1 % 64]) T.writes(T_reshape[ax0, ax1]) T_reshape[ax0, ax1] = placeholder[ ((ax1 % 64 // 64 + (ax1 // 768 + ax0) % 64) // 64 + ax1 % 768 // 64) % 12, (ax1 % 64 // 64 + (ax1 // 768 + ax0) % 64) % 64, ax1 % 64 % 64, ] @tvm.script.ir_module class Bert_fused_reshape_transpose_reshape_after_rub: @T.prim_func def main( placeholder: T.Buffer[(12, 64, 64), "float32"], T_reshape: T.Buffer[(64, 768), "float32"] ) -> None: for i0_i1_fused_0_i0_i1_fused_1_fused_0 in T.thread_binding(48, thread="blockIdx.x"): for i0_i1_fused_0_i0_i1_fused_1_fused_1 in T.thread_binding(1024, thread="threadIdx.x"): with T.block("T_reshape_1"): ax0 = T.axis.spatial( 64, ( ( i0_i1_fused_0_i0_i1_fused_1_fused_0 * 1024 + i0_i1_fused_0_i0_i1_fused_1_fused_1 ) // 32 * 32 + ( i0_i1_fused_0_i0_i1_fused_1_fused_0 * 1024 + i0_i1_fused_0_i0_i1_fused_1_fused_1 ) % 32 ) // 768, ) ax1 = T.axis.spatial( 768, ( ( i0_i1_fused_0_i0_i1_fused_1_fused_0 * 1024 + i0_i1_fused_0_i0_i1_fused_1_fused_1 ) // 32 * 32 + ( i0_i1_fused_0_i0_i1_fused_1_fused_0 * 1024 + i0_i1_fused_0_i0_i1_fused_1_fused_1 ) % 32 ) % 768, ) T.reads(placeholder[ax1 % 768 // 64, (ax1 // 768 + ax0) % 64, ax1 % 64]) T.writes(T_reshape[ax0, ax1]) T_reshape[ax0, ax1] = placeholder[ ((ax1 % 64 // 64 + (ax1 // 768 + ax0) % 64) // 64 + ax1 % 768 // 64) % 12, (ax1 % 64 // 64 + (ax1 // 768 + ax0) % 64) % 64, ax1 % 64 % 64, ] @tvm.script.ir_module class Bert_fused_reshape_transpose_reshape_after_rub_large: @T.prim_func def main( placeholder: T.Buffer[(12, 64, 64), "float32"], T_reshape: T.Buffer[(64, 768), "float32"] ) -> None: # body # with T.block("root") for i0_i1_fused_0_i0_i1_fused_1_fused_1 in T.thread_binding(256, thread="blockIdx.x"): for i0_i1_fused_0_i0_i1_fused_1_fused_2 in T.thread_binding(1024, thread="threadIdx.x"): for i0_i1_fused_0_i0_i1_fused_1_fused_0 in T.serial(188): with T.block("T_reshape_1"): ax0 = T.axis.spatial( 64, ( ( i0_i1_fused_0_i0_i1_fused_1_fused_0 * 262144 + i0_i1_fused_0_i0_i1_fused_1_fused_1 * 1024 + i0_i1_fused_0_i0_i1_fused_1_fused_2 ) // 32 * 32 + ( i0_i1_fused_0_i0_i1_fused_1_fused_0 * 262144 + i0_i1_fused_0_i0_i1_fused_1_fused_1 * 1024 + i0_i1_fused_0_i0_i1_fused_1_fused_2 ) % 32 ) // 768, ) ax1 = T.axis.spatial( 768, ( ( i0_i1_fused_0_i0_i1_fused_1_fused_0 * 262144 + i0_i1_fused_0_i0_i1_fused_1_fused_1 * 1024 + i0_i1_fused_0_i0_i1_fused_1_fused_2 ) // 32 * 32 + ( i0_i1_fused_0_i0_i1_fused_1_fused_0 * 262144 + i0_i1_fused_0_i0_i1_fused_1_fused_1 * 1024 + i0_i1_fused_0_i0_i1_fused_1_fused_2 ) % 32 ) % 768, ) T.where( ( i0_i1_fused_0_i0_i1_fused_1_fused_0 * 256 + i0_i1_fused_0_i0_i1_fused_1_fused_1 ) * 1024 + i0_i1_fused_0_i0_i1_fused_1_fused_2 < 49152000 ) T.reads(placeholder[ax1 % 768 // 64, (ax1 // 768 + ax0) % 64, ax1 % 64]) T.writes(T_reshape[ax0, ax1]) T_reshape[ax0, ax1] = placeholder[ ((ax1 % 64 // 64 + (ax1 // 768 + ax0) % 64) // 64 + ax1 % 768 // 64) % 12, (ax1 % 64 // 64 + (ax1 // 768 + ax0) % 64) % 64, ax1 % 64 % 64, ] @T.prim_func def before_unrolled_loop( placeholder: T.Buffer[(1, 56, 56, 64), "float32"], ) -> None: # function attr dict T.func_attr({"global_symbol": "main", "tir.noalias": True}) bgemm = T.alloc_buffer([6, 6, 196, 64], dtype="float32") inverse = T.alloc_buffer([4, 4, 196, 64], dtype="float32") for i2_0, i3_0, i2_1, i3_1 in T.grid(98, 4, 2, 16): for i0 in T.unroll(4): for i1 in T.unroll(4): for i4 in T.unroll(6): for i5 in T.unroll(6): with T.block("inverse"): vh, vw = T.axis.remap("SS", [i0, i1]) p = T.axis.spatial(196, i2_0 * 2 + i2_1) co = T.axis.spatial(64, i3_0 * 16 + i3_1) r_a, r_b = T.axis.remap("RR", [i4, i5]) T.reads(bgemm[r_a, r_b, p, co]) T.writes(inverse[vh, vw, p, co]) with T.init(): inverse[vh, vw, p, co] = T.float32(0) inverse[vh, vw, p, co] = inverse[vh, vw, p, co] + bgemm[r_a, r_b, p, co] @T.prim_func def after_unrolled_loop( placeholder: T.Buffer[(1, 56, 56, 64), "float32"], ) -> None: T.func_attr({"global_symbol": "main", "tir.noalias": True}) # body # with T.block("root") bgemm = T.alloc_buffer([6, 6, 196, 64], dtype="float32") inverse = T.alloc_buffer([4, 4, 196, 64], dtype="float32") for i2_0_i3_0_i2_1_i3_1_fused_0 in T.thread_binding(13, thread="blockIdx.x"): for i2_0_i3_0_i2_1_i3_1_fused_1 in T.thread_binding(1024, thread="threadIdx.x"): for i0 in T.unroll(4): for i1 in T.unroll(4): for i4 in T.unroll(6): for i5 in T.unroll(6): with T.block("inverse"): vh, vw = T.axis.remap("SS", [i0, i1]) p = T.axis.spatial( 196, ( i2_0_i3_0_i2_1_i3_1_fused_0 * 1024 + i2_0_i3_0_i2_1_i3_1_fused_1 ) // 128 * 2 + ( i2_0_i3_0_i2_1_i3_1_fused_0 * 1024 + i2_0_i3_0_i2_1_i3_1_fused_1 ) % 32 // 16, ) co = T.axis.spatial( 64, ( i2_0_i3_0_i2_1_i3_1_fused_0 * 1024 + i2_0_i3_0_i2_1_i3_1_fused_1 ) % 128 // 32 * 16 + ( i2_0_i3_0_i2_1_i3_1_fused_0 * 1024 + i2_0_i3_0_i2_1_i3_1_fused_1 ) % 16, ) r_a, r_b = T.axis.remap("RR", [i4, i5]) T.where( i2_0_i3_0_i2_1_i3_1_fused_0 * 1024 + i2_0_i3_0_i2_1_i3_1_fused_1 < 12544 ) T.reads(bgemm[r_a, r_b, p, co]) T.writes(inverse[vh, vw, p, co]) with T.init(): inverse[vh, vw, p, co] = T.float32(0) inverse[vh, vw, p, co] = ( inverse[vh, vw, p, co] + bgemm[r_a, r_b, p, co] ) # pylint: enable=no-member,invalid-name,unused-variable,no-self-argument,line-too-long,chained-comparison,not-callable,too-many-nested-blocks # fmt: on def test_rewrite_cooperative_fetch(): mod = Before_cooperative_fetch target = _target() ctx = _create_context(mod, target) sch = tir.Schedule(mod, debug_mask="all") sch.enter_postproc() assert ctx.space_generator.postprocs[0].apply(sch) tvm.ir.assert_structural_equal(sch.mod, After_cooperative_fetch) def test_rewrite_norm_bmn(): mod = Before_norm_bmn target = _target() ctx = _create_context(mod, target) sch = tir.Schedule(mod, debug_mask="all") sch.enter_postproc() assert ctx.space_generator.postprocs[0].apply(sch) tvm.ir.assert_structural_equal(sch.mod, After_norm_bmn) def test_rewrite_cuda_loop_split_no_reduction(): mod = Bert_fused_reshape_transpose_reshape target = Target("nvidia/nvidia-v100", host="llvm") ctx = _create_context(mod, target) sch = tir.Schedule(mod, debug_mask="all") sch.enter_postproc() assert ctx.space_generator.postprocs[0].apply(sch) tvm.ir.assert_structural_equal(sch.mod, Bert_fused_reshape_transpose_reshape_after_rub) def test_rewrite_cuda_loop_split_no_reduction_large(): mod = Bert_fused_reshape_transpose_reshape_large target = Target("nvidia/nvidia-v100", host="llvm") ctx = _create_context(mod, target) sch = tir.Schedule(mod, debug_mask="all") sch.enter_postproc() assert ctx.space_generator.postprocs[0].apply(sch) tvm.ir.assert_structural_equal(sch.mod, Bert_fused_reshape_transpose_reshape_after_rub_large) def test_rewrite_cuda_loop_split_for_kind(): mod = before_unrolled_loop target = Target("nvidia/nvidia-v100", host="llvm") ctx = _create_context(mod, target) sch = tir.Schedule(mod, debug_mask="all") sch.enter_postproc() assert ctx.space_generator.postprocs[0].apply(sch) tvm.ir.assert_structural_equal(sch.mod["main"], after_unrolled_loop) if __name__ == "__main__": test_rewrite_cooperative_fetch() test_rewrite_norm_bmn() test_rewrite_cuda_loop_split_no_reduction() test_rewrite_cuda_loop_split_no_reduction_large() test_rewrite_cuda_loop_split_for_kind()
https://github.com/zk-ml/tachikoma
tests/python/unittest/test_meta_schedule_postproc_verify_gpu_code.py
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. # pylint: disable=missing-module-docstring,missing-function-docstring,missing-class-docstring import pytest import tvm import tvm.testing from tvm import meta_schedule as ms from tvm import tir from tvm.script import tir as T from tvm.target import Target def _target() -> Target: return Target("nvidia/geforce-rtx-3080") def _create_context(mod, target) -> ms.TuneContext: return ms.TuneContext( mod=mod, target=target, space_generator=ms.space_generator.PostOrderApply( sch_rules=[], postprocs=[ms.postproc.VerifyGPUCode()], mutator_probs={}, ), task_name="test", ) # pylint: disable=invalid-name,no-member,line-too-long,too-many-nested-blocks,no-self-argument,not-callable,misplaced-comparison-constant # fmt: off @tvm.script.ir_module class Conv2dCuda0: @T.prim_func def main(a: T.handle, b: T.handle) -> None: # function attr dict T.func_attr({"global_symbol": "main", "T.noalias": True}) # var definition threadIdx_x = T.env_thread("threadIdx.x") threadIdx_y = T.env_thread("threadIdx.y") blockIdx_x = T.env_thread("blockIdx.x") blockIdx_y = T.env_thread("blockIdx.y") blockIdx_z = T.env_thread("blockIdx.z") A = T.match_buffer(a, [14*14*256*256], dtype="float32") B = T.match_buffer(b, [14*14*512*256], dtype="float32") # body T.launch_thread(blockIdx_z, 196) B_local = T.decl_buffer([64], "float32", scope="local") Apad_shared = T.decl_buffer([512], "float32", scope="shared") Apad_shared_local = T.decl_buffer([8], "float32", scope="local") T.launch_thread(blockIdx_y, 8) T.launch_thread(blockIdx_x, 4) T.launch_thread(threadIdx_y, 8) T.launch_thread(threadIdx_x, 8) for ff_c_init, nn_c_init in T.grid(8, 8): B_local[ff_c_init * 8 + nn_c_init] = T.float32(0) for rc_outer, ry, rx in T.grid(32, 3, 3): for ax3_inner_outer in T.serial(0, 2): Apad_shared[T.ramp(threadIdx_y * 64 + threadIdx_x * 8 + ax3_inner_outer * 4, 1, 4)] = T.if_then_else( 1 <= blockIdx_z // 14 + ry and blockIdx_z // 14 + ry < 15 and 1 <= rx + blockIdx_z % 14 and rx + blockIdx_z % 14 < 15, A[T.ramp(ry * 917504 + blockIdx_z * 65536 + rx * 65536 + rc_outer * 2048 + threadIdx_y * 256 + blockIdx_x * 64 + threadIdx_x * 8 + ax3_inner_outer * 4 - 983040, 1, 4)], T.broadcast(T.float32(0), 4), dtype="float32x4", ) for rc_inner in T.serial(0, 8): for ax3 in T.serial(0, 8): Apad_shared_local[ax3] = Apad_shared[rc_inner * 64 + threadIdx_x * 8 + ax3] for ff_c, nn_c in T.grid(8, 8): B_local[ff_c * 8 + nn_c] = B_local[ff_c * 8 + nn_c] + Apad_shared_local[nn_c] for ff_inner_inner_inner, nn_inner_inner_inner in T.grid(8, 8): B[blockIdx_z * 131072 + blockIdx_y * 16384 + threadIdx_y * 2048 + ff_inner_inner_inner * 256 + blockIdx_x * 64 + threadIdx_x * 8 + nn_inner_inner_inner] = B_local[ff_inner_inner_inner * 8 + nn_inner_inner_inner] # fmt: on @tvm.script.ir_module class Conv2dCuda1: @T.prim_func def main(a: T.handle, b: T.handle) -> None: # function attr dict T.func_attr({"global_symbol": "main", "T.noalias": True}) # var definition threadIdx_x = T.env_thread("threadIdx.x") threadIdx_y = T.env_thread("threadIdx.y") blockIdx_x = T.env_thread("blockIdx.x") blockIdx_y = T.env_thread("blockIdx.y") blockIdx_z = T.env_thread("blockIdx.z") A = T.match_buffer(a, [14*14*256*256], dtype="float32") B = T.match_buffer(b, [14*14*512*256], dtype="float32") # body T.launch_thread(blockIdx_z, 196) B_local = T.decl_buffer([6400000], "float32", scope="local") Apad_shared = T.decl_buffer([512], "float32", scope="shared") Apad_shared_local = T.decl_buffer([8], "float32", scope="local") T.launch_thread(blockIdx_y, 8) T.launch_thread(blockIdx_x, 4) T.launch_thread(threadIdx_y, 8) T.launch_thread(threadIdx_x, 8) for ff_c_init, nn_c_init in T.grid(8, 8): B_local[ff_c_init * 8 + nn_c_init] = T.float32(0) # Access of the last element of B_local prevents buffer # compacting from reducing the amount of shared memory # used. B_local[6400000-1 + ff_c_init*8] = 0.0 for rc_outer, ry, rx in T.grid(32, 3, 3): for ax3_inner_outer in T.serial(0, 2): Apad_shared[T.ramp(threadIdx_y * 64 + threadIdx_x * 8 + ax3_inner_outer * 4, 1, 4)] = T.if_then_else( 1 <= blockIdx_z // 14 + ry and blockIdx_z // 14 + ry < 15 and 1 <= rx + blockIdx_z % 14 and rx + blockIdx_z % 14 < 15, A[T.ramp(ry * 917504 + blockIdx_z * 65536 + rx * 65536 + rc_outer * 2048 + threadIdx_y * 256 + blockIdx_x * 64 + threadIdx_x * 8 + ax3_inner_outer * 4 - 983040, 1, 4)], T.broadcast(T.float32(0), 4), dtype="float32x4", ) for rc_inner in T.serial(0, 8): for ax3 in T.serial(0, 8): Apad_shared_local[ax3] = Apad_shared[rc_inner * 64 + threadIdx_x * 8 + ax3] for ff_c, nn_c in T.grid(8, 8): B_local[ff_c * 8 + nn_c] = B_local[ff_c * 8 + nn_c] + Apad_shared_local[nn_c] for ff_inner_inner_inner, nn_inner_inner_inner in T.grid(8, 8): B[blockIdx_z * 131072 + blockIdx_y * 16384 + threadIdx_y * 2048 + ff_inner_inner_inner * 256 + blockIdx_x * 64 + threadIdx_x * 8 + nn_inner_inner_inner] = B_local[ff_inner_inner_inner * 8 + nn_inner_inner_inner]# fmt: on @tvm.script.ir_module class Conv2dCuda2: @T.prim_func def main(a: T.handle, b: T.handle) -> None: # function attr dict T.func_attr({"global_symbol": "main", "T.noalias": True}) # var definition threadIdx_x = T.env_thread("threadIdx.x") threadIdx_y = T.env_thread("threadIdx.y") blockIdx_x = T.env_thread("blockIdx.x") blockIdx_y = T.env_thread("blockIdx.y") blockIdx_z = T.env_thread("blockIdx.z") A = T.match_buffer(a, [14*14*256*256], dtype="float32") B = T.match_buffer(b, [14*14*512*256], dtype="float32") # body T.launch_thread(blockIdx_z, 196) B_local = T.decl_buffer([64], "float32", scope="local") Apad_shared = T.decl_buffer([512000], "float32", scope="shared") Apad_shared_local = T.decl_buffer([8], "float32", scope="local") T.launch_thread(blockIdx_y, 8) T.launch_thread(blockIdx_x, 4) T.launch_thread(threadIdx_y, 8) T.launch_thread(threadIdx_x, 8) for ff_c_init, nn_c_init in T.grid(8, 8): B_local[ff_c_init * 8 + nn_c_init] = T.float32(0) for rc_outer, ry, rx in T.grid(32, 3, 3): for ax3_inner_outer in T.serial(0, 2): Apad_shared[T.ramp(threadIdx_y * 64 + threadIdx_x * 8 + ax3_inner_outer * 4, 1, 4)] = T.if_then_else( 1 <= blockIdx_z // 14 + ry and blockIdx_z // 14 + ry < 15 and 1 <= rx + blockIdx_z % 14 and rx + blockIdx_z % 14 < 15, A[T.ramp(ry * 917504 + blockIdx_z * 65536 + rx * 65536 + rc_outer * 2048 + threadIdx_y * 256 + blockIdx_x * 64 + threadIdx_x * 8 + ax3_inner_outer * 4 - 983040, 1, 4)], T.broadcast(T.float32(0), 4), dtype="float32x4", ) # Access of the last element of Apad_shared prevents # buffer compacting from reducing the amount of shared # memory used. Apad_shared[512000-1] = 0.0 for rc_inner in T.serial(0, 8): for ax3 in T.serial(0, 8): Apad_shared_local[ax3] = Apad_shared[rc_inner * 64 + threadIdx_x * 8 + ax3] for ff_c, nn_c in T.grid(8, 8): B_local[ff_c * 8 + nn_c] = B_local[ff_c * 8 + nn_c] + Apad_shared_local[nn_c] for ff_inner_inner_inner, nn_inner_inner_inner in T.grid(8, 8): B[blockIdx_z * 131072 + blockIdx_y * 16384 + threadIdx_y * 2048 + ff_inner_inner_inner * 256 + blockIdx_x * 64 + threadIdx_x * 8 + nn_inner_inner_inner] = B_local[ff_inner_inner_inner * 8 + nn_inner_inner_inner]# fmt: on @tvm.script.ir_module class Conv2dCuda3: @T.prim_func def main(a: T.handle, b: T.handle) -> None: # function attr dict T.func_attr({"global_symbol": "main", "T.noalias": True}) # var definition threadIdx_x = T.env_thread("threadIdx.x") threadIdx_y = T.env_thread("threadIdx.y") blockIdx_x = T.env_thread("blockIdx.x") blockIdx_y = T.env_thread("blockIdx.y") blockIdx_z = T.env_thread("blockIdx.z") A = T.match_buffer(a, [14*14*256*256], dtype="float32") B = T.match_buffer(b, [14*14*512*256], dtype="float32") # body T.launch_thread(blockIdx_z, 196) B_local = T.decl_buffer([64], "float32", scope="local") Apad_shared = T.decl_buffer([512], "float32", scope="shared") Apad_shared_local = T.decl_buffer([8], "float32", scope="local") T.launch_thread(blockIdx_y, 8) T.launch_thread(blockIdx_x, 4) T.launch_thread(threadIdx_y, 8) T.launch_thread(threadIdx_x, 800000) for ff_c_init, nn_c_init in T.grid(8, 8): B_local[ff_c_init * 8 + nn_c_init] = T.float32(0) for rc_outer, ry, rx in T.grid(32, 3, 3): for ax3_inner_outer in T.serial(0, 2): Apad_shared[T.ramp(threadIdx_y * 64 + threadIdx_x * 8 + ax3_inner_outer * 4, 1, 4)] = T.if_then_else( 1 <= blockIdx_z // 14 + ry and blockIdx_z // 14 + ry < 15 and 1 <= rx + blockIdx_z % 14 and rx + blockIdx_z % 14 < 15, A[T.ramp(ry * 917504 + blockIdx_z * 65536 + rx * 65536 + rc_outer * 2048 + threadIdx_y * 256 + blockIdx_x * 64 + threadIdx_x * 8 + ax3_inner_outer * 4 - 983040, 1, 4)], T.broadcast(T.float32(0), 4), dtype="float32x4", ) for rc_inner in T.serial(0, 8): for ax3 in T.serial(0, 8): Apad_shared_local[ax3] = Apad_shared[rc_inner * 64 + threadIdx_x * 8 + ax3] for ff_c, nn_c in T.grid(8, 8): B_local[ff_c * 8 + nn_c] = B_local[ff_c * 8 + nn_c] + Apad_shared_local[nn_c] for ff_inner_inner_inner, nn_inner_inner_inner in T.grid(8, 8): B[blockIdx_z * 131072 + blockIdx_y * 16384 + threadIdx_y * 2048 + ff_inner_inner_inner * 256 + blockIdx_x * 64 + threadIdx_x * 8 + nn_inner_inner_inner] = B_local[ff_inner_inner_inner * 8 + nn_inner_inner_inner]# fmt: on @T.prim_func def GmmCuda0(X: T.Buffer[(1, 128, 128), "float32"], Y: T.Buffer[(1, 128, 128), "float32"], Z: T.Buffer[(1, 128, 128), "float32"]) -> None: Z_local = T.alloc_buffer([1, 128, 128], dtype="float32", scope="local") X_shared = T.alloc_buffer([1, 128, 128], dtype="float32", scope="shared") Y_shared = T.alloc_buffer([1, 128, 128], dtype="float32", scope="shared") for i0_0_i1_0_i2_0_fused in T.thread_binding(16, thread="blockIdx.x"): for i0_1_i1_1_i2_1_fused in T.thread_binding(1, thread="vthread.x"): for i0_2_i1_2_i2_2_fused in T.thread_binding(128, thread="threadIdx.x"): for i1_3_init, i2_4_init in T.grid(4, 2): with T.block("Z_init"): b = T.axis.spatial(1, 0) i = T.axis.spatial(128, i0_0_i1_0_i2_0_fused // 4 * 32 + i0_2_i1_2_i2_2_fused // 16 * 4 + i1_3_init) j = T.axis.spatial(128, i0_0_i1_0_i2_0_fused % 4 * 32 + i0_2_i1_2_i2_2_fused % 16 * 2 + i2_4_init) T.reads() T.writes(Z_local[b, i, j]) Z_local[b, i, j] = T.float32(0) for i3_0 in T.serial(4): for ax0_ax1_ax2_fused_0 in T.serial(4): for ax0_ax1_ax2_fused_1 in T.thread_binding(128, thread="threadIdx.x"): for ax0_ax1_ax2_fused_2 in T.vectorized(2): with T.block("X_shared"): v0 = T.axis.spatial(1, 0) v1 = T.axis.spatial(128, i0_0_i1_0_i2_0_fused // 4 * 32 + (ax0_ax1_ax2_fused_0 * 256 + ax0_ax1_ax2_fused_1 * 2 + ax0_ax1_ax2_fused_2) // 32) v2 = T.axis.spatial(128, i3_0 * 32 + (ax0_ax1_ax2_fused_0 * 256 + ax0_ax1_ax2_fused_1 * 2 + ax0_ax1_ax2_fused_2) % 32) T.reads(X[v0, v1, v2]) T.writes(X_shared[v0, v1, v2]) X_shared[v0, v1, v2] = X[v0, v1, v2] for ax0_ax1_ax2_fused_0 in T.serial(8): for ax0_ax1_ax2_fused_1 in T.thread_binding(128, thread="threadIdx.x"): with T.block("Y_shared"): v0 = T.axis.spatial(1, 0) v1 = T.axis.spatial(128, i3_0 * 32 + (ax0_ax1_ax2_fused_0 * 128 + ax0_ax1_ax2_fused_1) // 32) v2 = T.axis.spatial(128, i0_0_i1_0_i2_0_fused % 4 * 32 + (ax0_ax1_ax2_fused_0 * 128 + ax0_ax1_ax2_fused_1) % 32) T.reads(Y[v0, v1, v2]) T.writes(Y_shared[v0, v1, v2]) Y_shared[v0, v1, v2] = Y[v0, v1, v2] for i3_1, i0_3, i1_3, i2_3, i3_2, i0_4, i1_4, i2_4 in T.grid(1, 1, 4, 1, 32, 1, 1, 2): with T.block("Z_update"): b = T.axis.spatial(1, 0) i = T.axis.spatial(128, i0_0_i1_0_i2_0_fused // 4 * 32 + i0_2_i1_2_i2_2_fused // 16 * 4 + i1_3) j = T.axis.spatial(128, i0_0_i1_0_i2_0_fused % 4 * 32 + i0_2_i1_2_i2_2_fused % 16 * 2 + i2_4) k = T.axis.reduce(128, i3_0 * 32 + i3_2) T.reads(Z_local[b, i, j], X_shared[b, i, k], Y_shared[b, k, j]) T.writes(Z_local[b, i, j]) Z_local[b, i, j] = Z_local[b, i, j] + X_shared[b, i, k] * Y_shared[b, k, j] for ax0, ax1, ax2 in T.grid(1, 4, 2): with T.block("Z_local"): v0 = T.axis.spatial(1, ax0) v1 = T.axis.spatial(128, i0_0_i1_0_i2_0_fused // 4 * 32 + i0_2_i1_2_i2_2_fused // 16 * 4 + ax1) v2 = T.axis.spatial(128, i0_0_i1_0_i2_0_fused % 4 * 32 + i0_2_i1_2_i2_2_fused % 16 * 2 + ax2) T.reads(Z_local[v0, v1, v2]) T.writes(Z[v0, v1, v2]) Z[v0, v1, v2] = Z_local[v0, v1, v2] @T.prim_func def GmmCuda1(X: T.Buffer[(1, 128, 128), "float32"], Y: T.Buffer[(1, 128, 128), "float32"], Z: T.Buffer[(1, 128, 128), "float32"]) -> None: Z_local = T.alloc_buffer([1, 128, 128], dtype="float32", scope="local") X_shared = T.alloc_buffer([1, 128, 128], dtype="float32", scope="shared") Y_shared = T.alloc_buffer([1, 128, 128], dtype="float32", scope="shared") for i0_0_i1_0_i2_0_fused in T.thread_binding(16, thread="blockIdx.x"): for i0_1_i1_1_i2_1_fused in T.thread_binding(1, thread="vthread.x"): for i0_2_i1_2_i2_2_fused in T.thread_binding(128, thread="threadIdx.x"): for i1_3_init, i2_4_init in T.grid(4, 2): with T.block("Z_init"): b = T.axis.spatial(1, 0) i = T.axis.spatial(128, i0_0_i1_0_i2_0_fused // 4 * 32 + i0_2_i1_2_i2_2_fused // 16 * 4 + i1_3_init) j = T.axis.spatial(128, i0_0_i1_0_i2_0_fused % 4 * 32 + i0_2_i1_2_i2_2_fused % 16 * 2 + i2_4_init) T.reads() T.writes(Z_local[b, i, j]) Z_local[b, i, j] = T.float32(0) for i3_0 in T.serial(4): for ax0_ax1_ax2_fused_0 in T.serial(4): for ax0_ax1_ax2_fused_1 in T.thread_binding(128, thread="threadIdx.x"): for ax0_ax1_ax2_fused_2 in T.vectorized(2): with T.block("X_shared"): v0 = T.axis.spatial(1, 0) v1 = T.axis.spatial(128, i0_0_i1_0_i2_0_fused // 4 * 32 + (ax0_ax1_ax2_fused_0 * 256 + ax0_ax1_ax2_fused_1 * 2 + ax0_ax1_ax2_fused_2) // 32) v2 = T.axis.spatial(128, i3_0 * 32 + (ax0_ax1_ax2_fused_0 * 256 + ax0_ax1_ax2_fused_1 * 2 + ax0_ax1_ax2_fused_2) % 32) T.reads(X[v0, v1, v2]) T.writes(X_shared[v0, v1, v2]) X_shared[v0, v1, v2] = X[v0, v1, v2] for ax0_ax1_ax2_fused_0 in T.serial(8): for ax0_ax1_ax2_fused_1 in T.thread_binding(128, thread="threadIdx.x"): with T.block("Y_shared"): v0 = T.axis.spatial(1, 0) v1 = T.axis.spatial(128, i3_0 * 32 + (ax0_ax1_ax2_fused_0 * 128 + ax0_ax1_ax2_fused_1) // 32) v2 = T.axis.spatial(128, i0_0_i1_0_i2_0_fused % 4 * 32 + (ax0_ax1_ax2_fused_0 * 128 + ax0_ax1_ax2_fused_1) % 32) T.reads(Y[v0, v1, v2]) T.writes(Y_shared[v0, v1, v2]) Y_shared[v0, v1, v2] = Y[v0, v1, v2] for i3_1, i0_3, i1_3, i2_3, i3_2, i0_4, i1_4, i2_4 in T.grid(1, 1, 4, 1, 32, 1, 1, 2): with T.block("Z_update"): b = T.axis.spatial(1, 0) i = T.axis.spatial(128, i0_0_i1_0_i2_0_fused // 4 * 32 + i0_2_i1_2_i2_2_fused // 16 * 4 + i1_3) j = T.axis.spatial(128, i0_0_i1_0_i2_0_fused % 4 * 32 + i0_2_i1_2_i2_2_fused % 16 * 2 + i2_4) k = T.axis.reduce(128, i3_0 * 32 + i3_2) T.block_attr({ "meta_schedule.thread_extent_low_inclusive": 0, "meta_schedule.thread_extent_high_inclusive": 32, }) T.reads(Z_local[b, i, j], X_shared[b, i, k], Y_shared[b, k, j]) T.writes(Z_local[b, i, j]) Z_local[b, i, j] = Z_local[b, i, j] + X_shared[b, i, k] * Y_shared[b, k, j] for ax0, ax1, ax2 in T.grid(1, 4, 2): with T.block("Z_local"): v0 = T.axis.spatial(1, ax0) v1 = T.axis.spatial(128, i0_0_i1_0_i2_0_fused // 4 * 32 + i0_2_i1_2_i2_2_fused // 16 * 4 + ax1) v2 = T.axis.spatial(128, i0_0_i1_0_i2_0_fused % 4 * 32 + i0_2_i1_2_i2_2_fused % 16 * 2 + ax2) T.reads(Z_local[v0, v1, v2]) T.writes(Z[v0, v1, v2]) Z[v0, v1, v2] = Z_local[v0, v1, v2] @T.prim_func def GmmCuda2(X: T.Buffer[(1, 128, 128), "float32"], Y: T.Buffer[(1, 128, 128), "float32"], Z: T.Buffer[(1, 128, 128), "float32"]) -> None: Z_local = T.alloc_buffer([1, 128, 128], dtype="float32", scope="local") X_shared = T.alloc_buffer([1, 128, 128], dtype="float32", scope="shared") Y_shared = T.alloc_buffer([1, 128, 128], dtype="float32", scope="shared") for i0_0_i1_0_i2_0_fused in T.thread_binding(16, thread="blockIdx.x"): for i0_1_i1_1_i2_1_fused in T.thread_binding(1, thread="vthread.x"): for i0_2_i1_2_i2_2_fused in T.thread_binding(128, thread="threadIdx.x"): for i1_3_init, i2_4_init in T.grid(4, 2): with T.block("Z_init"): b = T.axis.spatial(1, 0) i = T.axis.spatial(128, i0_0_i1_0_i2_0_fused // 4 * 32 + i0_2_i1_2_i2_2_fused // 16 * 4 + i1_3_init) j = T.axis.spatial(128, i0_0_i1_0_i2_0_fused % 4 * 32 + i0_2_i1_2_i2_2_fused % 16 * 2 + i2_4_init) T.reads() T.writes(Z_local[b, i, j]) Z_local[b, i, j] = T.float32(0) for i3_0 in T.serial(4): for ax0_ax1_ax2_fused_0 in T.serial(4): for ax0_ax1_ax2_fused_1 in T.thread_binding(128, thread="threadIdx.x"): for ax0_ax1_ax2_fused_2 in T.vectorized(2): with T.block("X_shared"): v0 = T.axis.spatial(1, 0) v1 = T.axis.spatial(128, i0_0_i1_0_i2_0_fused // 4 * 32 + (ax0_ax1_ax2_fused_0 * 256 + ax0_ax1_ax2_fused_1 * 2 + ax0_ax1_ax2_fused_2) // 32) v2 = T.axis.spatial(128, i3_0 * 32 + (ax0_ax1_ax2_fused_0 * 256 + ax0_ax1_ax2_fused_1 * 2 + ax0_ax1_ax2_fused_2) % 32) T.reads(X[v0, v1, v2]) T.writes(X_shared[v0, v1, v2]) X_shared[v0, v1, v2] = X[v0, v1, v2] for ax0_ax1_ax2_fused_0 in T.serial(8): for ax0_ax1_ax2_fused_1 in T.thread_binding(128, thread="threadIdx.x"): with T.block("Y_shared"): v0 = T.axis.spatial(1, 0) v1 = T.axis.spatial(128, i3_0 * 32 + (ax0_ax1_ax2_fused_0 * 128 + ax0_ax1_ax2_fused_1) // 32) v2 = T.axis.spatial(128, i0_0_i1_0_i2_0_fused % 4 * 32 + (ax0_ax1_ax2_fused_0 * 128 + ax0_ax1_ax2_fused_1) % 32) T.reads(Y[v0, v1, v2]) T.writes(Y_shared[v0, v1, v2]) Y_shared[v0, v1, v2] = Y[v0, v1, v2] for i3_1, i0_3, i1_3, i2_3, i3_2, i0_4, i1_4, i2_4 in T.grid(1, 1, 4, 1, 32, 1, 1, 2): with T.block("Z_update"): b = T.axis.spatial(1, 0) i = T.axis.spatial(128, i0_0_i1_0_i2_0_fused // 4 * 32 + i0_2_i1_2_i2_2_fused // 16 * 4 + i1_3) j = T.axis.spatial(128, i0_0_i1_0_i2_0_fused % 4 * 32 + i0_2_i1_2_i2_2_fused % 16 * 2 + i2_4) k = T.axis.reduce(128, i3_0 * 32 + i3_2) T.block_attr({ "meta_schedule.thread_extent_low_inclusive": 1024, "meta_schedule.thread_extent_high_inclusive": 1024, }) T.reads(Z_local[b, i, j], X_shared[b, i, k], Y_shared[b, k, j]) T.writes(Z_local[b, i, j]) Z_local[b, i, j] = Z_local[b, i, j] + X_shared[b, i, k] * Y_shared[b, k, j] for ax0, ax1, ax2 in T.grid(1, 4, 2): with T.block("Z_local"): v0 = T.axis.spatial(1, ax0) v1 = T.axis.spatial(128, i0_0_i1_0_i2_0_fused // 4 * 32 + i0_2_i1_2_i2_2_fused // 16 * 4 + ax1) v2 = T.axis.spatial(128, i0_0_i1_0_i2_0_fused % 4 * 32 + i0_2_i1_2_i2_2_fused % 16 * 2 + ax2) T.reads(Z_local[v0, v1, v2]) T.writes(Z[v0, v1, v2]) Z[v0, v1, v2] = Z_local[v0, v1, v2] @T.prim_func def GMMCUDATensorCore( X: T.Buffer[(1024, 1024), "float16"], Y: T.Buffer[(1024, 1024), "float16"], Z: T.Buffer[(1024, 1024), "float32"], ) -> None: # function attr dict T.func_attr({"global_symbol": "main", "tir.noalias": True}) s0 = T.var("int32") s0_1 = T.var("int32") s0_2 = T.var("int32") s1 = T.var("int32") s1_1 = T.var("int32") s1_2 = T.var("int32") # body # with T.block("root") Z_wmma_accumulator = T.alloc_buffer([1024, 1024], dtype="float32", scope="wmma.accumulator") X_shared = T.alloc_buffer([1024, 1024], dtype="float16", scope="shared") Y_shared = T.alloc_buffer([1024, 1024], dtype="float16", scope="shared") X_shared_wmma_matrix_a = T.alloc_buffer([1024, 1024], dtype="float16", scope="wmma.matrix_a") Y_shared_wmma_matrix_b = T.alloc_buffer([1024, 1024], dtype="float16", scope="wmma.matrix_b") for ax0_0_ax1_0_0_ax2_0_0_fused in T.thread_binding(64, thread="blockIdx.x"): for ax0_1_ax1_0_1_ax2_0_1_fused in T.thread_binding(2, thread="blockIdx.y"): for ax0_2_ax1_0_2_ax2_0_2_fused in T.thread_binding(2, thread="threadIdx.y"): for ax1_0_3_init, ax2_0_3_init, ax1_0_4_init, ax2_0_4_init in T.grid(2, 1, 2, 4): with T.block("Z_o_init"): v0 = T.axis.spatial(1, 0) v1_o = T.axis.spatial( 64, ax0_0_ax1_0_0_ax2_0_0_fused % 64 // 16 * 16 + ax0_1_ax1_0_1_ax2_0_1_fused % 2 * 8 + ax0_2_ax1_0_2_ax2_0_2_fused % 2 * 4 + ax1_0_3_init * 2 + ax1_0_4_init, ) v2_o = T.axis.spatial( 64, (ax0_0_ax1_0_0_ax2_0_0_fused % 16 + 0 + 0 + ax2_0_3_init) * 4 + ax2_0_4_init, ) T.reads() T.writes( Z_wmma_accumulator[ v1_o * 16 : v1_o * 16 + 16, v2_o * 16 : v2_o * 16 + 16 ] ) T.block_attr( { "meta_schedule.thread_extent_high_inclusive": 1024, "meta_schedule.thread_extent_low_inclusive": 32, "warp_execution": 1, } ) C = T.match_buffer( Z_wmma_accumulator[ v1_o * 16 : v1_o * 16 + 16, v2_o * 16 : v2_o * 16 + 16 ], [16, 16], dtype="float32", scope="wmma.accumulator", offset_factor=16, ) T.evaluate( T.tvm_fill_fragment( C.data, 16, 16, 16, C.elem_offset // 256 + C.elem_offset % 256 // 16, T.float32(0), dtype="handle", ) ) for ax3_0_0 in T.serial(32): for ax0_ax1_fused_0 in T.serial(16): for ax0_ax1_fused_1 in T.thread_binding(2, thread="threadIdx.y"): for ax0_ax1_fused_2 in T.thread_binding(32, thread="threadIdx.x"): for ax0_ax1_fused_3 in T.vectorized(4): with T.block("X_shared"): v0 = T.axis.spatial( 1024, ax0_0_ax1_0_0_ax2_0_0_fused // 16 * 256 + ax0_1_ax1_0_1_ax2_0_1_fused * 128 + ( ax0_ax1_fused_0 * 256 + ax0_ax1_fused_1 * 128 + ax0_ax1_fused_2 * 4 + ax0_ax1_fused_3 ) // 32, ) v1 = T.axis.spatial( 1024, ax3_0_0 * 32 + ( ax0_ax1_fused_0 * 256 + ax0_ax1_fused_1 * 128 + ax0_ax1_fused_2 * 4 + ax0_ax1_fused_3 ) % 32, ) T.reads(X[v0, v1]) T.writes(X_shared[v0, v1]) T.block_attr({"buffer_dim_align": [[0, 0, 32, 8]]}) X_shared[v0, v1] = X[v0, v1] for ax0_ax1_fused_0 in T.serial(8): for ax0_ax1_fused_1 in T.thread_binding(2, thread="threadIdx.y"): for ax0_ax1_fused_2 in T.thread_binding(32, thread="threadIdx.x"): for ax0_ax1_fused_3 in T.vectorized(4): with T.block("Y_shared"): v0 = T.axis.spatial( 1024, ax3_0_0 * 32 + ( ax0_ax1_fused_0 * 256 + ax0_ax1_fused_1 * 128 + ax0_ax1_fused_2 * 4 + ax0_ax1_fused_3 ) // 64, ) v1 = T.axis.spatial( 1024, ax0_0_ax1_0_0_ax2_0_0_fused % 16 * 64 + ( ax0_ax1_fused_0 * 256 + ax0_ax1_fused_1 * 128 + ax0_ax1_fused_2 * 4 + ax0_ax1_fused_3 ) % 64, ) T.reads(Y[v0, v1]) T.writes(Y_shared[v0, v1]) T.block_attr({"buffer_dim_align": [[0, 0, 32, 8]]}) Y_shared[v0, v1] = Y[v0, v1] for ax3_0_1 in T.serial(2): for ax0_0, ax1_0 in T.grid(4, 1): with T.block("X_shared_wmma.matrix_a_o"): v0_o = T.axis.spatial( 64, ax0_0_ax1_0_0_ax2_0_0_fused // 16 * 16 + ax0_1_ax1_0_1_ax2_0_1_fused * 8 + ax0_2_ax1_0_2_ax2_0_2_fused * 4 + ax0_0, ) v1_o = T.axis.spatial(64, ax3_0_0 * 2 + ax3_0_1) T.reads( X_shared[v0_o * 16 : v0_o * 16 + 16, v1_o * 16 : v1_o * 16 + 16] ) T.writes( X_shared_wmma_matrix_a[ v0_o * 16 : v0_o * 16 + 16, v1_o * 16 : v1_o * 16 + 16 ] ) A = T.match_buffer( X_shared[ v0_o * 16 : v0_o * 16 + 16, v1_o * 16 : v1_o * 16 + 16 ], [16, 16], dtype="float16", strides=[s1, s0], scope="shared", offset_factor=16, ) C_1 = T.match_buffer( X_shared_wmma_matrix_a[ v0_o * 16 : v0_o * 16 + 16, v1_o * 16 : v1_o * 16 + 16 ], [16, 16], dtype="float16", scope="wmma.matrix_a", offset_factor=16, ) T.evaluate( T.tvm_load_matrix_sync( C_1.data, 16, 16, 16, C_1.elem_offset // 256 + C_1.elem_offset % 256 // 16, T.tvm_access_ptr( T.type_annotation(dtype="float16"), A.data, A.elem_offset, s1 * 16, 1, dtype="handle", ), s1, "row_major", dtype="handle", ) ) for ax0_0, ax1_0 in T.grid(1, 4): with T.block("Y_shared_wmma.matrix_b_o"): v0_o = T.axis.spatial(64, ax3_0_0 * 2 + ax3_0_1) v1_o = T.axis.spatial( 64, ax0_0_ax1_0_0_ax2_0_0_fused % 16 * 4 + ax1_0 ) T.reads( Y_shared[v0_o * 16 : v0_o * 16 + 16, v1_o * 16 : v1_o * 16 + 16] ) T.writes( Y_shared_wmma_matrix_b[ v0_o * 16 : v0_o * 16 + 16, v1_o * 16 : v1_o * 16 + 16 ] ) A_1 = T.match_buffer( Y_shared[ v0_o * 16 : v0_o * 16 + 16, v1_o * 16 : v1_o * 16 + 16 ], [16, 16], dtype="float16", strides=[s1_1, s0_1], scope="shared", offset_factor=16, ) C_2 = T.match_buffer( Y_shared_wmma_matrix_b[ v0_o * 16 : v0_o * 16 + 16, v1_o * 16 : v1_o * 16 + 16 ], [16, 16], dtype="float16", scope="wmma.matrix_b", offset_factor=16, ) T.evaluate( T.tvm_load_matrix_sync( C_2.data, 16, 16, 16, C_2.elem_offset // 256 + C_2.elem_offset % 256 // 16, T.tvm_access_ptr( T.type_annotation(dtype="float16"), A_1.data, A_1.elem_offset, s1_1 * 16, 1, dtype="handle", ), s1_1, "row_major", dtype="handle", ) ) for ax0_3, ax1_0_3, ax2_0_3, ax3_0_2, ax0_4, ax1_0_4, ax2_0_4 in T.grid( 1, 2, 1, 1, 1, 2, 4 ): with T.block("Z_o_update"): v0 = T.axis.spatial(1, 0) v1_o = T.axis.spatial( 64, ax0_0_ax1_0_0_ax2_0_0_fused % 64 // 16 * 16 + ax0_1_ax1_0_1_ax2_0_1_fused % 2 * 8 + ax0_2_ax1_0_2_ax2_0_2_fused % 2 * 4 + ax1_0_3 * 2 + ax1_0_4, ) v2_o = T.axis.spatial( 64, (ax0_0_ax1_0_0_ax2_0_0_fused % 16 + 0 + 0 + ax2_0_3) * 4 + ax2_0_4, ) v3_o = T.axis.reduce(64, ax3_0_0 * 2 + ax3_0_1 + ax3_0_2) T.reads( Z_wmma_accumulator[ v1_o * 16 : v1_o * 16 + 16, v2_o * 16 : v2_o * 16 + 16 ], X_shared_wmma_matrix_a[ v1_o * 16 : v1_o * 16 + 16, v3_o * 16 : v3_o * 16 + 16 ], Y_shared_wmma_matrix_b[ v3_o * 16 : v3_o * 16 + 16, v2_o * 16 : v2_o * 16 + 16 ], ) T.writes( Z_wmma_accumulator[ v1_o * 16 : v1_o * 16 + 16, v2_o * 16 : v2_o * 16 + 16 ] ) T.block_attr( { "meta_schedule.thread_extent_high_inclusive": 1024, "meta_schedule.thread_extent_low_inclusive": 32, "warp_execution": 1, } ) A_2 = T.match_buffer( X_shared_wmma_matrix_a[ v1_o * 16 : v1_o * 16 + 16, v3_o * 16 : v3_o * 16 + 16 ], [16, 16], dtype="float16", scope="wmma.matrix_a", offset_factor=16, ) B = T.match_buffer( Y_shared_wmma_matrix_b[ v3_o * 16 : v3_o * 16 + 16, v2_o * 16 : v2_o * 16 + 16 ], [16, 16], dtype="float16", scope="wmma.matrix_b", offset_factor=16, ) C_3 = T.match_buffer( Z_wmma_accumulator[ v1_o * 16 : v1_o * 16 + 16, v2_o * 16 : v2_o * 16 + 16 ], [16, 16], dtype="float32", scope="wmma.accumulator", offset_factor=16, ) T.evaluate( T.tvm_mma_sync( C_3.data, C_3.elem_offset // 256 + C_3.elem_offset % 256 // 16, A_2.data, A_2.elem_offset // 256, B.data, B.elem_offset // 256, C_3.data, C_3.elem_offset // 256 + C_3.elem_offset % 256 // 16, dtype="handle", ) ) for ax0_0, ax1_0 in T.grid(4, 4): with T.block("Z_wmma.accumulator_o"): v0_o = T.axis.spatial( 64, ax0_0_ax1_0_0_ax2_0_0_fused // 16 * 16 + ax0_1_ax1_0_1_ax2_0_1_fused * 8 + ax0_2_ax1_0_2_ax2_0_2_fused * 4 + ax0_0, ) v1_o = T.axis.spatial(64, ax0_0_ax1_0_0_ax2_0_0_fused % 16 * 4 + ax1_0) T.reads( Z_wmma_accumulator[ v0_o * 16 : v0_o * 16 + 16, v1_o * 16 : v1_o * 16 + 16 ] ) T.writes(Z[v0_o * 16 : v0_o * 16 + 16, v1_o * 16 : v1_o * 16 + 16]) A_3 = T.match_buffer( Z_wmma_accumulator[ v0_o * 16 : v0_o * 16 + 16, v1_o * 16 : v1_o * 16 + 16 ], [16, 16], dtype="float32", scope="wmma.accumulator", offset_factor=16, ) C_4 = T.match_buffer( Z[v0_o * 16 : v0_o * 16 + 16, v1_o * 16 : v1_o * 16 + 16], [16, 16], dtype="float32", strides=[s1_2, s0_2], offset_factor=16, ) T.evaluate( T.tvm_store_matrix_sync( A_3.data, 16, 16, 16, A_3.elem_offset // 256 + A_3.elem_offset % 256 // 16, T.tvm_access_ptr( T.type_annotation(dtype="float32"), C_4.data, C_4.elem_offset, s1_2 * 16, 2, dtype="handle", ), s1_2, "row_major", dtype="handle", ) ) # fmt: on # pylint: enable=invalid-name,no-member,line-too-long,too-many-nested-blocks,no-self-argument,not-callable,misplaced-comparison-constant @pytest.mark.parametrize("mod", [Conv2dCuda0, Conv2dCuda1, GmmCuda0, GMMCUDATensorCore]) def test_postproc_check_pass(mod): ctx = _create_context(mod, target=_target()) sch = tir.Schedule(mod, debug_mask="all") assert ctx.space_generator.postprocs[0].apply(sch) @pytest.mark.parametrize( "mod", [ Conv2dCuda2, # Should fail due to too much local memory per block (large Apad_shared allocation) Conv2dCuda3, # Should fail due to too many threads per block (large threadIdx.x extent) GmmCuda1, GmmCuda2, ], ) def test_postproc_check_fail(mod): ctx = _create_context(mod, target=_target()) sch = tir.Schedule(mod, debug_mask="all") assert not ctx.space_generator.postprocs[0].apply(sch) if __name__ == "__main__": tvm.testing.main()
https://github.com/zk-ml/tachikoma
tests/python/unittest/test_meta_schedule_profiler.py
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. """ Test Meta Schedule Profiler """ import time from tvm import meta_schedule as ms def test_meta_schedule_profiler_context_manager(): with ms.Profiler() as profiler: time.sleep(1) with ms.Profiler.timeit("Level0"): time.sleep(1) with ms.Profiler.timeit("Level1"): time.sleep(2) # Note that the results are in seconds result = profiler.get() assert len(result) == 3 assert 3.9 <= result["Total"] <= 4.1 assert 2.9 <= result["Level0"] <= 3.1 assert 1.9 <= result["Level1"] <= 2.1 def test_meta_schedule_no_context(): with ms.Profiler.timeit("Level0"): assert ms.Profiler.current() is None if __name__ == "__main__": test_meta_schedule_profiler_context_manager() test_meta_schedule_no_context()
https://github.com/zk-ml/tachikoma
tests/python/unittest/test_meta_schedule_relay_integration.py
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. """Integration test for MetaSchedule""" import tempfile from typing import List import numpy as np import pytest import tvm import tvm.testing from tvm import IRModule from tvm import meta_schedule as ms from tvm import relay, te, tir from tvm._ffi import register_func from tvm.contrib import graph_executor from tvm.ir.transform import PassContext from tvm.meta_schedule.database import TuningRecord, Workload from tvm.meta_schedule.testing.relay_workload import get_network from tvm.meta_schedule.testing.tlcbench import load_quantized_bert_base from tvm.meta_schedule.tune_context import _normalize_mod from tvm.script import tir as T from tvm.target import Target # pylint: disable=no-member,line-too-long,too-many-nested-blocks,unbalanced-tuple-unpacking,no-self-argument,missing-docstring,invalid-name @tvm.script.ir_module class MockModule: @T.prim_func def main(a: T.handle, b: T.handle) -> None: # type: ignore T.func_attr({"global_symbol": "main", "tir.noalias": True}) A = T.match_buffer(a, (16,), "float32") B = T.match_buffer(b, (16,), "float32") for i in T.serial(0, 16): with T.block("matmul"): vi = T.axis.remap("S", [i]) B[vi] = A[vi] # pylint: enable=no-member,line-too-long,too-many-nested-blocks,unbalanced-tuple-unpacking,no-self-argument def _has_torch(): import importlib.util # pylint: disable=unused-import,import-outside-toplevel spec = importlib.util.find_spec("torch") return spec is not None requires_torch = pytest.mark.skipif(not _has_torch(), reason="torch is not installed") def test_meta_schedule_dynamic_loop_extent(): a = relay.var("a", shape=(1, 8, 8, 512), dtype="float32") b = relay.nn.adaptive_avg_pool2d(a, (7, 7), "NHWC") mod = IRModule({"main": relay.Function([a], b)}) extracted_tasks = ms.relay_integration.extract_tasks(mod, target="llvm", params={}) assert not extracted_tasks @requires_torch def test_meta_schedule_integration_extract_from_resnet(): mod, params, _ = get_network(name="resnet_18", input_shape=[1, 3, 224, 224]) extracted_tasks = ms.relay_integration.extract_tasks(mod, target="llvm", params=params) expected_task_names = [ "fused_" + s for s in [ "nn_max_pool2d", "nn_adaptive_avg_pool2d", "nn_dense_add", "nn_conv2d_add", "nn_conv2d_add_1", "nn_conv2d_add_2", "nn_conv2d_add_add_nn_relu", "nn_conv2d_add_add_nn_relu_1", "nn_conv2d_add_nn_relu", "nn_conv2d_add_nn_relu_1", "nn_conv2d_add_nn_relu_2", "nn_conv2d_add_nn_relu_3", "nn_conv2d_add_nn_relu_4", "nn_conv2d_add_nn_relu_5", "nn_contrib_conv2d_winograd_without_weight_transform_add_add_nn_relu", "nn_contrib_conv2d_winograd_without_weight_transform_add_add_nn_relu_1", "nn_contrib_conv2d_winograd_without_weight_transform_add_nn_relu", "nn_contrib_conv2d_winograd_without_weight_transform_add_nn_relu_1", # The two tasks below are purely spatial and are ruled out by AutoScheduler "layout_transform", "layout_transform_reshape_squeeze", ] ] assert len(extracted_tasks) == len(expected_task_names) for t in extracted_tasks: assert t.task_name in expected_task_names, t.task_name @requires_torch def test_task_extraction_anchor_block(): mod, params, _ = get_network(name="resnet_18", input_shape=[1, 3, 224, 224]) extracted_tasks = ms.relay_integration.extract_tasks( mod, target="llvm", params=params, module_equality="anchor-block" ) # Note that there is no task from residual blocks expected_task_names = [ "fused_" + s for s in [ "nn_max_pool2d", "nn_adaptive_avg_pool2d", "nn_dense_add", "nn_conv2d_add", "nn_conv2d_add_1", "nn_conv2d_add_2", "nn_conv2d_add_nn_relu", "nn_conv2d_add_nn_relu_1", "nn_conv2d_add_nn_relu_2", "nn_conv2d_add_nn_relu_3", "nn_conv2d_add_nn_relu_4", "nn_conv2d_add_nn_relu_5", "nn_contrib_conv2d_winograd_without_weight_transform_add_nn_relu", "nn_contrib_conv2d_winograd_without_weight_transform_add_nn_relu_1", "layout_transform", "layout_transform_reshape_squeeze", ] ] assert len(extracted_tasks) == len(expected_task_names) for t in extracted_tasks: assert t.task_name in expected_task_names, t.task_name @requires_torch def test_meta_schedule_integration_extract_from_bert_base(): pytest.importorskip( "transformers", reason="transformers package is required to import bert_base" ) expected = { "fused_nn_dense_2": ( 12, [[64, 3072], [768, 3072], [64, 768]], ), "fused_nn_dense": ( 48, [[64, 768], [768, 768], [64, 768]], ), "fused_nn_dense_1": ( 12, [[64, 768], [3072, 768], [64, 3072]], ), "fused_subtract_add_rsqrt_multiply_multiply_add": ( 25, [[1, 64, 768], [1, 64, 1], [1, 64, 1], [768], [768], [1, 64, 768]], ), "fused_nn_batch_matmul": ( 24, [[12, 64, 64], [12, 64, 64], [12, 64, 64]], ), "fused_reshape_add_add": ( 24, [[64, 768], [768], [1, 64, 768], [1, 64, 768]], ), "fused_variance": ( 25, [[1, 64, 768], [1, 64, 1], [1, 64, 1]], ), "fused_mean": ( 25, [[1, 64, 768], [1, 64, 1]], ), "fused_reshape_add_reshape_transpose_reshape": ( 12, [[64, 768], [768], [12, 64, 64]], ), "fused_reshape_add_multiply_fast_erf_multiply_add_multiply_reshape": ( 12, [[64, 3072], [3072], [64, 3072]], ), "fused_nn_fast_softmax": ( 12, [[1, 12, 64, 64], [1, 12, 64, 64]], ), "fused_reshape_add_reshape_transpose_reshape_1": ( 24, [[64, 768], [768], [12, 64, 64]], ), "fused_reshape_divide_add": ( 12, [[12, 64, 64], [1, 1, 1, 64], [1, 12, 64, 64]], ), "fused_reshape_transpose_reshape": ( 12, [[12, 64, 64], [64, 768]], ), "fused_nn_dense_add_fast_tanh": ( 1, [[1, 768], [768, 768], [1, 768], [1, 768]], ), "fused_cast_take_add": ( 1, [[1, 64], [30522, 768], [1, 64, 768], [1, 64, 768]], ), "fused_take": ( 1, [[1, 64, 768], [1, 768]], ), "fused_reshape": ( 12, [[1, 12, 64, 64], [12, 64, 64]], ), "fused_reshape_1": ( 24, [[1, 64, 768], [64, 768]], ), } mod, params, _ = get_network(name="bert_base", input_shape=[1, 64]) extracted_tasks = ms.relay_integration.extract_tasks(mod, target="llvm", params=params) assert len(extracted_tasks) == len(expected) for t in extracted_tasks: prim_func = None for _, v in t.dispatched[0].functions.items(): prim_func = v shape = [[int(x) for x in prim_func.buffer_map[b].shape] for b in prim_func.params] assert t.task_name in expected expected_weight, expected_shape = expected[t.task_name] assert expected_weight == t.weight, t.task_name assert expected_shape == shape, t.task_name @requires_torch def test_meta_schedule_integration_extract_from_resnet_with_filter_func(): @register_func("relay.backend.tir_converter.remove_purely_spatial", override=True) def filter_func(args, _) -> bool: from tvm.te import create_prim_func # pylint: disable=import-outside-toplevel has_complex_op = False visited = set() def traverse(t): nonlocal has_complex_op assert t.handle is not None if t.handle.value in visited: return if isinstance(t.op, te.PlaceholderOp): pass elif isinstance(t.op, te.ComputeOp): has_complex_op = has_complex_op or any(isinstance(e, tir.Reduce) for e in t.op.body) for x in t.op.input_tensors: traverse(x) visited.add(t.handle.value) for t in args: traverse(t) if not has_complex_op: return None return create_prim_func(args) mod, params, _ = get_network(name="resnet_18", input_shape=[1, 3, 224, 224]) extracted_tasks = ms.relay_integration.extract_tasks( mod, target="llvm", params=params, pass_config={ "relay.backend.use_meta_schedule": True, "relay.backend.tir_converter": "remove_purely_spatial", }, ) expected_task_names = [ "fused_" + s for s in [ "nn_max_pool2d", "nn_adaptive_avg_pool2d", "nn_dense_add", "nn_conv2d_add", "nn_conv2d_add_1", "nn_conv2d_add_2", "nn_conv2d_add_add_nn_relu", "nn_conv2d_add_add_nn_relu_1", "nn_conv2d_add_nn_relu", "nn_conv2d_add_nn_relu_1", "nn_conv2d_add_nn_relu_2", "nn_conv2d_add_nn_relu_3", "nn_conv2d_add_nn_relu_4", "nn_conv2d_add_nn_relu_5", "nn_contrib_conv2d_winograd_without_weight_transform_add_add_nn_relu", "nn_contrib_conv2d_winograd_without_weight_transform_add_add_nn_relu_1", "nn_contrib_conv2d_winograd_without_weight_transform_add_nn_relu", "nn_contrib_conv2d_winograd_without_weight_transform_add_nn_relu_1", ] ] assert len(extracted_tasks) == len(expected_task_names) for t in extracted_tasks: assert t.task_name in expected_task_names, t.task_name @pytest.mark.skip("Too slow on CI") def extract_task_qbert(): def _test(mod, params, target): extracted_tasks = ms.relay_integration.extract_tasks(mod, target, params) tune_tasks = list( filter( lambda task: "dense" in task.task_name or "batch_matmul" in task.task_name, extracted_tasks, ) ) # three int8 dense, two int8 bmm, and one fp32 dense assert len(tune_tasks) == 6 for task in tune_tasks: relay_func = list(task.mod.functions.values())[0] out_type = relay_func.body.checked_type if out_type.dtype == "float32": continue sch = tvm.tir.Schedule(_normalize_mod(task.dispatched[0])) block = sch.get_block("compute") annotations = sch.get(block).annotations assert "schedule_rule" in annotations assert "vnni" in annotations["schedule_rule"] mod, params, _ = load_quantized_bert_base(batch_size=1, seq_len=128) _test(mod, params, target="llvm -mcpu=cascadelake") @tvm.testing.skip_if_32bit(reason="Apparently the LLVM version on i386 image is too old") def test_extract_task_arm_conv2d_nchwc(): data_shape = (1, 64, 128, 128) weight_shape = (32, 64, 1, 1) bias_shape = (weight_shape[0],) padding = (1, 1) data = relay.var("data", shape=data_shape, dtype="int8") weight = relay.var("weight", shape=weight_shape, dtype="int8") bias = relay.var("bias", shape=bias_shape, dtype="int32") conv2d = relay.nn.conv2d( data=data, weight=weight, kernel_size=weight_shape[2:], channels=weight_shape[0], padding=padding, strides=(1, 1), out_dtype="int32", ) bias_add = relay.nn.bias_add(conv2d, bias) relay_mod = tvm.IRModule.from_expr(bias_add) weight_np = np.random.uniform(1, 10, size=weight_shape).astype("int8") bias_np = np.random.uniform(1, 10, size=bias_shape).astype("int32") params = {"weight": weight_np, "bias": bias_np} target = "llvm -device arm_cpu -mtriple aarch64-linux-gnu -mattr=+neon" extracted_tasks = ms.relay_integration.extract_tasks(relay_mod, target, params) tune_tasks = list( filter( lambda task: "conv2d" in task.task_name, extracted_tasks, ) ) assert len(tune_tasks) == 1 relay_func = list(tune_tasks[0].mod.functions.values())[0] out_type = relay_func.body.checked_type # Check that the output is in NCHWc layout assert list(out_type.shape) == [1, 8, 130, 130, 4] def test_meta_schedule_te2primfunc_argument_order_and_lowering(): # pylint: disable=invalid-name,no-member,line-too-long,too-many-nested-blocks,no-self-argument # fmt: off @tvm.script.ir_module class _fused_layout_transform: @T.prim_func def main( # type: ignore placeholder: T.Buffer[(1, 3, 16, 16), "float32"], # type: ignore T_layout_trans: T.Buffer[(1, 1, 16, 16, 3), "float32"], # type: ignore ) -> None: # type: ignore # function attr dict T.func_attr({"global_symbol": "main", "tir.noalias": True}) # body # with T.block("root") for i0, i1, i2, i3, i4 in T.grid(1, 1, 16, 16, 3): with T.block("T_layout_trans"): ax0, ax1, ax2, ax3, ax4 = T.axis.remap("SSSSS", [i0, i1, i2, i3, i4]) T.reads(placeholder[ax0, ax1 * 3 + ax4, ax2, ax3]) T.writes(T_layout_trans[ax0, ax1, ax2, ax3, ax4]) T_layout_trans[ax0, ax1, ax2, ax3, ax4] = T.if_then_else( ax0 < 1 and ax1 * 3 + ax4 < 3 and ax2 < 16 and ax3 < 16, # type: ignore placeholder[ax0, ax1 * 3 + ax4, ax2, ax3], T.float32(0), dtype="float32", ) @tvm.script.ir_module class _fused_layout_transform_1: @T.prim_func def main(placeholder: T.Buffer[(1, 2, 16, 16, 4), "float32"], T_layout_trans: T.Buffer[(1, 8, 16, 16), "float32"]) -> None: # type: ignore # function attr dict T.func_attr({"global_symbol": "main", "tir.noalias": True}) # body # with T.block("root") for i0, i1, i2, i3 in T.grid(1, 8, 16, 16): with T.block("T_layout_trans"): ax0, ax1, ax2, ax3 = T.axis.remap("SSSS", [i0, i1, i2, i3]) T.reads(placeholder[ax0, ax1 // 4, ax2, ax3, ax1 % 4]) # type: ignore T.writes(T_layout_trans[ax0, ax1, ax2, ax3]) T_layout_trans[ax0, ax1, ax2, ax3] = T.if_then_else(ax0 < 1 and ax1 < 8 and ax2 < 16 and ax3 < 16, placeholder[ax0, ax1 // 4, ax2, ax3, ax1 % 4], T.float32(0), dtype="float32") # type: ignore @tvm.script.ir_module class _fused_nn_contrib_conv2d_NCHWc: @T.prim_func def main(placeholder: T.Buffer[(1, 1, 16, 16, 3), "float32"], placeholder_1: T.Buffer[(2, 1, 5, 5, 3, 4), "float32"], conv2d_NCHWc: T.Buffer[(1, 2, 16, 16, 4), "float32"]) -> None: # type: ignore # function attr dict T.func_attr({"global_symbol": "main", "tir.noalias": True}) # body # with T.block("root") data_pad = T.alloc_buffer([1, 1, 20, 20, 3], dtype="float32") for i0, i1, i2, i3, i4 in T.grid(1, 1, 20, 20, 3): with T.block("data_pad"): i0_1, i1_1, i2_1, i3_1, i4_1 = T.axis.remap("SSSSS", [i0, i1, i2, i3, i4]) T.reads(placeholder[i0_1, i1_1, i2_1 - 2, i3_1 - 2, i4_1]) T.writes(data_pad[i0_1, i1_1, i2_1, i3_1, i4_1]) data_pad[i0_1, i1_1, i2_1, i3_1, i4_1] = T.if_then_else(2 <= i2_1 and i2_1 < 18 and 2 <= i3_1 and i3_1 < 18, placeholder[i0_1, i1_1, i2_1 - 2, i3_1 - 2, i4_1], T.float32(0), dtype="float32") # type: ignore # pylint: disable=R1716 for i0, i1, i2, i3, i4, i5, i6, i7 in T.grid(1, 2, 16, 16, 4, 3, 5, 5): with T.block("conv2d_NCHWc"): n, oc_chunk, oh, ow, oc_block, ic, kh, kw = T.axis.remap("SSSSSRRR", [i0, i1, i2, i3, i4, i5, i6, i7]) T.reads(data_pad[n, ic // 3, oh + kh, ow + kw, ic % 3], placeholder_1[oc_chunk, ic // 3, kh, kw, ic % 3, oc_block]) # type: ignore T.writes(conv2d_NCHWc[n, oc_chunk, oh, ow, oc_block]) with T.init(): conv2d_NCHWc[n, oc_chunk, oh, ow, oc_block] = T.float32(0) conv2d_NCHWc[n, oc_chunk, oh, ow, oc_block] = conv2d_NCHWc[n, oc_chunk, oh, ow, oc_block] + data_pad[n, ic // 3, oh + kh, ow + kw, ic % 3] * placeholder_1[oc_chunk, ic // 3, kh, kw, ic % 3, oc_block] # type: ignore # fmt: on # pylint: enable=invalid-name,no-member,line-too-long,too-many-nested-blocks,no-self-argument def _create_verification_database(): @ms.derived_object class VerificationDatabase(ms.database.PyDatabase): def __init__(self): super().__init__() self.tuning_records_: List[TuningRecord] = [] self.workloads_: List[Workload] = [] def has_workload(self, mod: IRModule) -> bool: for workload in self.workloads_: if tvm.ir.structural_equal(mod, workload.mod): return True # Note: The database has already put in all correct workloads # This is where we can check if the workload is correct raise ValueError( "The workload searched for is not in given database!" + " Incorrect TIR was generated from TE subgraph." ) def commit_workload(self, mod: IRModule) -> ms.database.Workload: # No need to deduplicate workload because they are specified workload = ms.database.Workload(mod) self.workloads_.append(workload) return workload def commit_tuning_record(self, record: TuningRecord) -> None: self.tuning_records_.append(record) def get_all_tuning_records(self) -> List[TuningRecord]: return self.tuning_records_ def get_top_k(self, workload: ms.database.Workload, top_k: int) -> List[TuningRecord]: return sorted( list( filter( lambda x: tvm.ir.structural_equal(workload.mod, x.workload.mod), self.tuning_records_, ) ), key=lambda x: sum(x.run_secs) / len(x.run_secs) if x.run_secs else 1e9, )[:top_k] def __len__(self) -> int: return len(self.tuning_records_) database = VerificationDatabase() def _commit(mod): workload = database.commit_workload(mod) database.commit_tuning_record( ms.database.TuningRecord( tir.schedule.Trace([], {}), workload=workload, run_secs=[0.1], ) ) _commit(_fused_layout_transform) _commit(_fused_layout_transform_1) _commit(_fused_nn_contrib_conv2d_NCHWc) return database data_shape = (1, 3, 16, 16) weight_shape = (8, 3, 5, 5) def _create_relay_mod(): data = relay.var("data", relay.TensorType(data_shape, "float32")) weight = relay.var("weight", relay.TensorType(weight_shape, "float32")) y = relay.nn.conv2d( data, weight, padding=(2, 2), kernel_size=(5, 5), kernel_layout="OIHW", out_dtype="float32", ) f = relay.Function([data, weight], y) mod = tvm.IRModule.from_expr(f) mod = relay.transform.InferType()(mod) return mod mod = _create_relay_mod() dev = tvm.cpu() target = Target("llvm --num-cores=16") params = { "weight": np.random.rand(*weight_shape).astype("float32"), } data = tvm.nd.array( np.random.rand(*data_shape).astype("float32"), dev, ) with target, _create_verification_database(), PassContext( # pylint: disable=not-context-manager opt_level=3, config={ "relay.backend.use_meta_schedule": True, "relay.backend.use_meta_schedule_dispatch": 7, "relay.backend.tir_converter": "default", }, ): rt_mod1 = relay.build(mod, target=target, params=params) # Compile without meta-schedule for correctness check with tvm.transform.PassContext(opt_level=0): rt_mod2 = relay.build(mod, target=target, params=params) def get_output(data, lib): module = graph_executor.GraphModule(lib["default"](dev)) module.set_input("data", data) module.run() return module.get_output(0).numpy() # Check correctness actual_output = get_output(data, rt_mod1) expected_output = get_output(data, rt_mod2) assert np.allclose(actual_output, expected_output, rtol=1e-4, atol=2e-4) def test_rewrite_layout_link_params(): I, O, H, W = 64, 64, 56, 56 kH = kW = 3 strides = (1, 1) padding = (1, 1) data_shape = (1, H, W, I) w_shape = (kH, kW, I, O) bias_shape = (1, 1, 1, O) data = relay.var("data", shape=data_shape, dtype="float32") weight = relay.var("weight1", shape=w_shape, dtype="float32") bias = relay.var("bias", shape=bias_shape, dtype="float32") conv = relay.nn.conv2d( data=data, weight=weight, kernel_size=(kH, kW), channels=O, padding=padding, strides=strides, data_layout="NHWC", kernel_layout="HWIO", out_dtype="float32", ) mod = tvm.IRModule.from_expr(conv + bias) weight_np = np.random.randn(*w_shape).astype("float32") bias_np = np.random.randn(*bias_shape).astype("float32") params = {"weight1": weight_np, "bias": bias_np} data_np = np.random.randn(*data_shape).astype("float32") ref = ( relay.create_executor("graph", mod=mod, device=tvm.cpu(0), target="llvm") .evaluate()(*[data_np, weight_np, bias_np]) .numpy() ) link_params = True target = "llvm --num-cores=4" executor = relay.backend.Executor("graph", {"link-params": link_params}) mod = mod.with_attr("executor", executor) for strategy in ["replay-trace", "evolutionary"]: with tempfile.TemporaryDirectory() as work_dir: database = ms.relay_integration.tune_relay( mod=mod, target=target, params=params, work_dir=work_dir, max_trials_global=4, strategy=strategy, ) lib = ms.relay_integration.compile_relay( database=database, mod=mod, target=target, params=params, ) dev = tvm.device(target, 0) runtime = tvm.contrib.graph_executor.GraphModule(lib["default"](dev)) runtime.set_input("data", data_np) runtime.run() out = runtime.get_output(0).numpy() np.testing.assert_allclose(ref, out, rtol=1e-4, atol=1e-4) def test_module_equality_ignore_ndarray(): target = "llvm --num-cores=4" data_shape = (128, 128) weight_shape1 = (128, 128) weight_shape2 = (128, 128) data = relay.var("data", shape=data_shape, dtype="float32") weight1 = relay.var("weight1", shape=weight_shape1, dtype="float32") weight2 = relay.var("weight2", shape=weight_shape2, dtype="float32") dense1 = relay.nn.dense(data, weight1) dense2 = relay.nn.dense(dense1, weight2) mod = tvm.IRModule.from_expr(dense2) weight1_np = np.random.randn(*weight_shape1).astype("float32") weight2_np = np.random.randn(*weight_shape2).astype("float32") params = {"weight1": weight1_np, "weight2": weight2_np} executor = relay.backend.Executor("graph", {"link-params": True}) mod = mod.with_attr("executor", executor) # Without using ignore-ndarray for module equality, we get duplicated tasks assert len(ms.relay_integration.extract_tasks(mod, target, params)) == 2 module_eqality = "ignore-ndarray" extracted_tasks = ms.relay_integration.extract_tasks( mod, target, params, module_equality=module_eqality ) assert len(extracted_tasks) == 1 with tempfile.TemporaryDirectory() as work_dir: tasks, task_weights = ms.relay_integration.extracted_tasks_to_tune_contexts( extracted_tasks, work_dir, strategy="replay-trace" ) database = ms.tune.tune_tasks( tasks=tasks, task_weights=task_weights, work_dir=work_dir, max_trials_global=4, module_equality=module_eqality, ) lib = ms.relay_integration.compile_relay(database, mod, target, params) dev = tvm.device(target, 0) runtime = tvm.contrib.graph_executor.GraphModule(lib["default"](dev)) data_np = np.random.randn(*data_shape).astype("float32") runtime.set_input("data", data_np) runtime.run() out = runtime.get_output(0).numpy() ref = np.dot(np.dot(data_np, weight1_np.transpose()), weight2_np.transpose()) np.testing.assert_allclose(ref, out, rtol=1e-4, atol=1e-4) def _test_anchor_tuning(target): data_shape = (128, 128) weight_shape1 = (128, 128) weight_shape2 = (128, 128) data = relay.var("data", shape=data_shape, dtype="float32") weight1 = relay.var("weight1", shape=weight_shape1, dtype="float32") weight2 = relay.var("weight2", shape=weight_shape2, dtype="float32") dense1 = relay.nn.dense(data, weight1) dense2 = relay.nn.dense(dense1 + relay.const(1.0, dtype="float32"), weight2) mod = tvm.IRModule.from_expr(dense2 - data + relay.const(1.0, dtype="float32")) weight1_np = np.random.randn(*weight_shape1).astype("float32") weight2_np = np.random.randn(*weight_shape2).astype("float32") data_np = np.random.randn(*data_shape).astype("float32") params = {"weight1": weight1_np, "weight2": weight2_np} module_equality = "anchor-block" extracted_tasks = ms.relay_integration.extract_tasks( mod, target, params, module_equality=module_equality ) assert len(extracted_tasks) == 1 with tempfile.TemporaryDirectory() as work_dir: database = ms.relay_integration.tune_relay( mod=mod, target=target, params=params, work_dir=work_dir, max_trials_global=4, strategy="replay-trace", module_equality=module_equality, ) lib = ms.relay_integration.compile_relay(database, mod, target, params) dev = tvm.device(target, 0) runtime = tvm.contrib.graph_executor.GraphModule(lib["default"](dev)) runtime.set_input("data", data_np) runtime.run() out = runtime.get_output(0).numpy() ref = ( relay.create_executor("graph", mod=mod, device=tvm.cpu(0), target="llvm") .evaluate()(*[data_np, weight1_np, weight2_np]) .numpy() ) np.testing.assert_allclose(ref, out, atol=1e-3) def test_anchor_tuning_cpu(): _test_anchor_tuning("llvm --num-cores=4") def test_anchor_tuning_cpu_link_params(): data_shape = (128, 128) weight_shape1 = (128, 128) weight_shape2 = (128, 128) data = relay.var("data", shape=data_shape, dtype="float32") weight1 = relay.var("weight1", shape=weight_shape1, dtype="float32") weight2 = relay.var("weight2", shape=weight_shape2, dtype="float32") dense1 = relay.nn.dense(data, weight1) dense2 = relay.nn.dense(dense1, weight2) mod = tvm.IRModule.from_expr(dense2 + relay.const(1.0, dtype="float32")) weight1_np = np.random.randn(*weight_shape1).astype("float32") weight2_np = np.random.randn(*weight_shape2).astype("float32") data_np = np.random.randn(*data_shape).astype("float32") params = {"weight1": weight1_np, "weight2": weight2_np} module_equality = "anchor-block" target = "llvm --num-cores=4" executor = relay.backend.Executor("graph", {"link-params": True}) mod = mod.with_attr("executor", executor) with tempfile.TemporaryDirectory() as work_dir: database = ms.relay_integration.tune_relay( mod=mod, target=target, params=params, work_dir=work_dir, max_trials_global=4, strategy="replay-trace", module_equality=module_equality, ) lib = ms.relay_integration.compile_relay(database, mod, target, params) dev = tvm.device(target, 0) runtime = tvm.contrib.graph_executor.GraphModule(lib["default"](dev)) runtime.set_input("data", data_np) runtime.run() out = runtime.get_output(0).numpy() ref = ( relay.create_executor("graph", mod=mod, device=tvm.cpu(0), target="llvm") .evaluate()(*[data_np, weight1_np, weight2_np]) .numpy() ) np.testing.assert_allclose(ref, out, atol=1e-3) if __name__ == "__main__": tvm.testing.main()
https://github.com/zk-ml/tachikoma
tests/python/unittest/test_meta_schedule_relay_tir_compute.py
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. import numpy as np import tvm import tvm.testing import tvm.topi.testing from tvm import autotvm from tvm import meta_schedule as ms from tvm import relay, te from tvm.relay.testing.temp_op_attr import TempOpAttr from tvm.script import tir as T def compute_tir_conv2d_nchw_oihw(data_shape, weight_shape, dtype): assert dtype == "float32" OC, IC, FH, FW = weight_shape padding = (0, 0, 0, 0) strides = (1, 1) dilation = (1, 1) output_shape = ( data_shape[0], weight_shape[0], (data_shape[2] - ((weight_shape[2] - 1) * dilation[0] + 1) + padding[0] + padding[1]) // strides[0] + 1, (data_shape[3] - ((weight_shape[3] - 1) * dilation[1] + 1) + padding[2] + padding[3]) // strides[1] + 1, ) N, K, BH, BW = output_shape # fmt: off @T.prim_func def conv2d(a: T.handle, filt: T.handle, b: T.handle) -> None: T.func_attr({"global_symbol": "main", "tir.noalias": True}) A = T.match_buffer(a, data_shape, dtype=dtype) Filter = T.match_buffer(filt, weight_shape, dtype=dtype) B = T.match_buffer(b, output_shape, dtype=dtype) for n, k, bh, bw in T.grid(N, K, BH, BW): with T.block("init"): vn, vk, vbh, vbw = T.axis.remap("SSSS", [n, k, bh, bw]) B[vn, vk, vbh, vbw] = T.float32(0) for ic, fh, fw in T.grid(IC, FH, FW): with T.block("update"): vn, vk, vbh, vbw, vc, vfh, vfw = T.axis.remap("SSSSRRR", [n, k, bh, bw, ic, fh, fw]) B[vn, vk, vbh, vbw] = B[vn, vk, vbh, vbw] + A[vn, vc, vbh + vfh, vbw + vfw] * Filter[vk, vc, vfh, vfw] # fmt: on return conv2d def schedule_tir_conv2d_nchw_oihw(sch): update_block = sch.get_block("update") vn, vk, vbh, vbw, vc, vfh, vfw = sch.get_loops(update_block) sch.split(vk, factors=(None, 32)) @autotvm.register_topi_compute("test/conv2d_1") def _compute_conv2d_1(cfg, input, filter, strides, padding, dilation, out_dtype): prim_func = compute_tir_conv2d_nchw_oihw(input.shape, filter.shape, input.dtype) output = te.extern_primfunc([input, filter], prim_func, name="tir") return output @autotvm.register_topi_schedule("test/conv2d_1") def _schedule_conv2d_1(cfg, outs): s = te.create_schedule([x.op for x in outs]) return s @tvm.target.override_native_generic_func("test_conv2d_strategy") def _tmp_strategy(attrs, inputs, out_type, target): strategy = relay.op.OpStrategy() if attrs.groups == 1 and attrs.data_layout == "NCHW" and attrs.kernel_layout == "OIHW": strategy.add_implementation( relay.op.strategy.wrap_compute_conv2d(_compute_conv2d_1), relay.op.strategy.wrap_topi_schedule(_schedule_conv2d_1), name="conv2d_2", plevel=15, ) else: raise ValueError("No valid strategy found") return strategy def get_conv2d(data_shape, weight_shape, **kwargs): data = relay.var("data", shape=data_shape, dtype="float32") weight = relay.var("weight", shape=weight_shape, dtype="float32") conv2d = relay.nn.conv2d( data, weight, **kwargs, ) return relay.Function([data, weight], conv2d) def get_ref(data, weight, stride, padding): return tvm.topi.testing.conv2d_nchw_python(data, weight, stride, padding) def test_conv2d(): N, IC, H, W = 1, 64, 56, 56 OC, IC, FH, FW = 128, 64, 3, 3 data_shape = (N, IC, H, W) weight_shape = (OC, IC, FH, FW) padding = (0, 0) strides = (1, 1) relay_mod = tvm.IRModule.from_expr( get_conv2d( data_shape, weight_shape, padding=padding, strides=strides, channels=OC, kernel_size=(FH, FW), data_layout="NCHW", kernel_layout="OIHW", ) ) data_np = np.random.randn(*data_shape).astype("float32") weight_np = np.random.randn(*weight_shape).astype("float32") target = "llvm" params = {"weight": weight_np} def schedule_fn(sch): if "nn_conv2d" in sch.mod.attrs["task_name"]: schedule_tir_conv2d_nchw_oihw(sch) return True return False with TempOpAttr("nn.conv2d", "FTVMStrategy", _tmp_strategy): with ms.database.ScheduleFnDatabase(schedule_fn), tvm.transform.PassContext( opt_level=3, config={ "relay.backend.use_meta_schedule": True, "relay.backend.tir_converter": "allow_extern", }, ): lib = relay.build(relay_mod, target=target, params=params) dev = tvm.device(target, 0) runtime = tvm.contrib.graph_executor.GraphModule(lib["default"](dev)) runtime.set_input("data", data_np) runtime.run() out = runtime.get_output(0).numpy() ref = get_ref(data_np, weight_np, strides, padding) tvm.testing.assert_allclose(out, ref, atol=1e-4, rtol=1e-4) if __name__ == "__main__": test_conv2d()
https://github.com/zk-ml/tachikoma
tests/python/unittest/test_meta_schedule_runner.py
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. """ Test Meta Schedule Runner """ import itertools import sys import time from typing import Any, List import numpy as np import pytest import tvm import tvm.testing from tvm._ffi import register_func from tvm.meta_schedule.arg_info import TensorInfo from tvm.meta_schedule.builder import BuilderInput, LocalBuilder from tvm.meta_schedule.runner import ( EvaluatorConfig, LocalRunner, PyRunner, RPCConfig, RPCRunner, RunnerFuture, RunnerInput, ) from tvm.meta_schedule.runner.local_runner import ( default_alloc_argument as local_default_alloc_argument, ) from tvm.meta_schedule.runner.rpc_runner import ( T_ARG_INFO_JSON_OBJ_LIST, T_ARGUMENT_LIST, ) from tvm.meta_schedule.runner.rpc_runner import ( default_alloc_argument as rpc_default_alloc_argument, ) from tvm.meta_schedule.testing.local_rpc import LocalRPC from tvm.meta_schedule.utils import ( derived_object, get_global_func_with_default_on_worker, ) from tvm.rpc import RPCSession from tvm.runtime import Device, Module from tvm.script import tir as T from tvm.target import Target from tvm.tir import FloatImm MATMUL_N = 16 MATMUL_M = 32 # pylint: disable=invalid-name,no-member,line-too-long,too-many-nested-blocks,missing-docstring,unbalanced-tuple-unpacking @tvm.script.ir_module class MatmulModule: @T.prim_func def main(a: T.handle, b: T.handle, c: T.handle) -> None: # pylint: disable=no-self-argument T.func_attr({"global_symbol": "main", "tir.noalias": True}) A = T.match_buffer(a, (16, 16), "float32") B = T.match_buffer(b, (16, 16), "float32") C = T.match_buffer(c, (16, 16), "float32") for i, j, k in T.grid(16, 16, 16): with T.block("matmul"): vi, vj, vk = T.axis.remap("SSR", [i, j, k]) with T.init(): C[vi, vj] = 0.0 C[vi, vj] = C[vi, vj] + A[vi, vk] * B[vk, vj] @tvm.script.ir_module class MatmulReluModule: @T.prim_func def main(a: T.handle, b: T.handle, d: T.handle) -> None: # pylint: disable=no-self-argument T.func_attr({"global_symbol": "main", "tir.noalias": True}) A = T.match_buffer(a, (16, 16), "float32") B = T.match_buffer(b, (16, 16), "float32") D = T.match_buffer(d, (16, 16), "float32") C = T.alloc_buffer((16, 16), "float32") for i, j, k in T.grid(16, 16, 16): with T.block("matmul"): vi, vj, vk = T.axis.remap("SSR", [i, j, k]) with T.init(): C[vi, vj] = 0.0 C[vi, vj] = C[vi, vj] + A[vi, vk] * B[vk, vj] for i, j in T.grid(16, 16): with T.block("relu"): vi, vj = T.axis.remap("SS", [i, j]) D[vi, vj] = T.max(C[vi, vj], 0.0) @tvm.script.ir_module class BatchMatmulModule: @T.prim_func def main(a: T.handle, b: T.handle, c: T.handle) -> None: # pylint: disable=no-self-argument T.func_attr({"global_symbol": "main", "tir.noalias": True}) A = T.match_buffer(a, [16, 32, 32]) B = T.match_buffer(b, [16, 32, 32]) C = T.match_buffer(c, [16, 32, 32]) for n, i, j, k in T.grid(16, 32, 32, 32): with T.block("update"): vn, vi, vj, vk = T.axis.remap("SSSR", [n, i, j, k]) with T.init(): C[vn, vi, vj] = 0.0 C[vn, vi, vj] = C[vn, vi, vj] + A[vn, vi, vk] * B[vn, vj, vk] @tvm.script.ir_module class AddModule: @T.prim_func def main(a: T.handle, b: T.handle, c: T.handle) -> None: # pylint: disable=no-self-argument T.func_attr({"global_symbol": "main", "tir.noalias": True}) A = T.match_buffer(a, [32], "float32") B = T.match_buffer(b, [32], "float32") C = T.match_buffer(c, [32], "float32") for i in range(32): with T.block("add"): vi = T.axis.S(32, i) C[vi] = A[vi] + B[vi] # pylint: enable=invalid-name,no-member,line-too-long,too-many-nested-blocks,missing-docstring def _clean_build(artifact_path: str) -> None: f_clean_build = get_global_func_with_default_on_worker("meta_schedule.remove_build_dir", None) if f_clean_build is not None: f_clean_build(artifact_path) else: raise RuntimeError("Unable to find remove_build_dir function.") def test_meta_schedule_rpc_single_run(): """Test meta schedule rpc runner for a single run""" # Build the module mod = MatmulModule builder = LocalBuilder() (builder_result,) = builder.build([BuilderInput(mod, Target("llvm"))]) assert builder_result.artifact_path is not None assert builder_result.error_msg is None runner_input = RunnerInput( builder_result.artifact_path, "llvm", [ TensorInfo("float32", (MATMUL_N, MATMUL_N)), TensorInfo("float32", (MATMUL_N, MATMUL_N)), TensorInfo("float32", (MATMUL_N, MATMUL_N)), ], ) with LocalRPC() as rpc: rpc_config = RPCConfig( tracker_host=rpc.tracker_host, tracker_port=rpc.tracker_port, tracker_key=rpc.tracker_key, session_priority=1, session_timeout_sec=100, ) evaluator_config = EvaluatorConfig( number=1, repeat=1, min_repeat_ms=0, enable_cpu_cache_flush=False, ) runner = RPCRunner(rpc_config, evaluator_config) # Run the module (runner_future,) = runner.run([runner_input]) runner_result = runner_future.result() assert runner_result.error_msg is None for result in runner_result.run_secs: if isinstance(result, FloatImm): result = result.value assert isinstance(result, float) assert result >= 0.0 _clean_build(builder_result.artifact_path) def test_meta_schedule_local_single_run(): """Test meta schedule local runner for a single run""" # Build the module mod = MatmulModule builder = LocalBuilder() (builder_result,) = builder.build([BuilderInput(mod, Target("llvm"))]) assert builder_result.artifact_path is not None assert builder_result.error_msg is None runner_input = RunnerInput( builder_result.artifact_path, "llvm", [ TensorInfo("float32", (MATMUL_N, MATMUL_N)), TensorInfo("float32", (MATMUL_N, MATMUL_N)), TensorInfo("float32", (MATMUL_N, MATMUL_N)), ], ) evaluator_config = EvaluatorConfig( number=1, repeat=1, min_repeat_ms=0, enable_cpu_cache_flush=False, ) runner = LocalRunner(timeout_sec=100, evaluator_config=evaluator_config) # Run the module (runner_future,) = runner.run([runner_input]) runner_result = runner_future.result() assert runner_result.error_msg is None for result in runner_result.run_secs: if isinstance(result, FloatImm): result = result.value assert isinstance(result, float) assert result >= 0.0 _clean_build(builder_result.artifact_path) def test_meta_schedule_rpc_multiple_runs(): """Test meta schedule rpc runner for multiple runs""" # Build the module mods = [ MatmulModule, MatmulReluModule, BatchMatmulModule, ] builder = LocalBuilder() builder_inputs = [BuilderInput(mod, Target("llvm")) for mod in mods] builder_results = builder.build(builder_inputs) for builder_result in builder_results: assert builder_result.artifact_path is not None assert builder_result.error_msg is None args_infos = [ [ TensorInfo("float32", (MATMUL_N, MATMUL_N)), TensorInfo("float32", (MATMUL_N, MATMUL_N)), TensorInfo("float32", (MATMUL_N, MATMUL_N)), ], [ TensorInfo("float32", (MATMUL_N, MATMUL_N)), TensorInfo("float32", (MATMUL_N, MATMUL_N)), TensorInfo("float32", (MATMUL_N, MATMUL_N)), ], [ TensorInfo("float32", [16, MATMUL_M, MATMUL_M]), TensorInfo("float32", [16, MATMUL_M, MATMUL_M]), TensorInfo("float32", [16, MATMUL_M, MATMUL_M]), ], ] runner_inputs = [ RunnerInput(builder_results[i].artifact_path, "llvm", args_infos[i]) for i in range(len(mods)) ] with LocalRPC() as rpc: rpc_config = RPCConfig( tracker_host=rpc.tracker_host, tracker_port=rpc.tracker_port, tracker_key=rpc.tracker_key, session_priority=1, session_timeout_sec=100, ) evaluator_config = EvaluatorConfig( number=1, repeat=1, min_repeat_ms=0, enable_cpu_cache_flush=False, ) runner = RPCRunner(rpc_config, evaluator_config) # Run the module runner_futures = runner.run(runner_inputs) runner_results = [runner_future.result() for runner_future in runner_futures] for runner_result in runner_results: assert runner_result.error_msg is None for result in runner_result.run_secs: if isinstance(result, FloatImm): result = result.value assert isinstance(result, float) assert result >= 0.0 for builder_result in builder_results: _clean_build(builder_result.artifact_path) def test_meta_schedule_local_multiple_runs(): """Test meta schedule local runner for multiple runs""" # Build the module mods = [ MatmulModule, MatmulReluModule, BatchMatmulModule, ] builder = LocalBuilder() builder_inputs = [BuilderInput(mod, Target("llvm")) for mod in mods] builder_results = builder.build(builder_inputs) for builder_result in builder_results: assert builder_result.artifact_path is not None assert builder_result.error_msg is None args_infos = [ [ TensorInfo("float32", (MATMUL_N, MATMUL_N)), TensorInfo("float32", (MATMUL_N, MATMUL_N)), TensorInfo("float32", (MATMUL_N, MATMUL_N)), ], [ TensorInfo("float32", (MATMUL_N, MATMUL_N)), TensorInfo("float32", (MATMUL_N, MATMUL_N)), TensorInfo("float32", (MATMUL_N, MATMUL_N)), ], [ TensorInfo("float32", [16, MATMUL_M, MATMUL_M]), TensorInfo("float32", [16, MATMUL_M, MATMUL_M]), TensorInfo("float32", [16, MATMUL_M, MATMUL_M]), ], ] runner_inputs = [ RunnerInput(builder_results[i].artifact_path, "llvm", args_infos[i]) for i in range(len(mods)) ] evaluator_config = EvaluatorConfig( number=1, repeat=1, min_repeat_ms=0, enable_cpu_cache_flush=False, ) runner = LocalRunner(timeout_sec=100, evaluator_config=evaluator_config) # Run the module runner_futures = runner.run(runner_inputs) runner_results = [runner_future.result() for runner_future in runner_futures] for runner_result in runner_results: assert runner_result.error_msg is None for result in runner_result.run_secs: if isinstance(result, FloatImm): result = result.value assert isinstance(result, float) assert result >= 0.0 for builder_result in builder_results: _clean_build(builder_result.artifact_path) def test_meta_schedule_py_runner(): """Test meta schedule PyRunner""" @derived_object class TestRunner(PyRunner): def run(self, runner_inputs: List[RunnerInput]) -> List[RunnerFuture]: raise ValueError("TestRunner") runner = TestRunner() with pytest.raises(ValueError, match="TestRunner"): runner.run([]) def test_meta_schedule_rpc_runner_time_out(): """Test meta schedule RPC Runner time out""" def initializer(): @register_func("meta_schedule.runner.test_time_out") def timeout_session_creator( # pylint: disable=unused-variable rpc_config: RPCConfig, # pylint: disable=unused-argument ) -> RPCSession: time.sleep(2) runner_input = RunnerInput( "test", "llvm", [ TensorInfo("float32", (MATMUL_N, MATMUL_N)), TensorInfo("float32", (MATMUL_N, MATMUL_N)), TensorInfo("float32", (MATMUL_N, MATMUL_N)), ], ) with LocalRPC() as rpc: rpc_config = RPCConfig( tracker_host=rpc.tracker_host, tracker_port=rpc.tracker_port, tracker_key=rpc.tracker_key, session_priority=1, session_timeout_sec=1, ) evaluator_config = EvaluatorConfig( number=1, repeat=1, min_repeat_ms=0, enable_cpu_cache_flush=False, ) runner = RPCRunner( rpc_config, evaluator_config, initializer=initializer, f_create_session="meta_schedule.runner.test_time_out", ) # Run the module (runner_future,) = runner.run([runner_input]) runner_result = runner_future.result() assert runner_result.error_msg is not None and runner_result.error_msg.startswith( "RPCRunner: Timeout, killed after" ) assert runner_result.run_secs is None def test_meta_schedule_local_runner_time_out(): """Test meta schedule Local Runner time out""" mod = MatmulModule builder = LocalBuilder() (builder_result,) = builder.build([BuilderInput(mod, Target("llvm"))]) assert builder_result.artifact_path is not None assert builder_result.error_msg is None runner_input = RunnerInput( builder_result.artifact_path, "llvm", [ TensorInfo("float32", (MATMUL_N, MATMUL_N)), TensorInfo("float32", (MATMUL_N, MATMUL_N)), TensorInfo("float32", (MATMUL_N, MATMUL_N)), ], ) def initializer(): @register_func("meta_schedule.runner.test_time_out") def timeout_session_creator( # pylint: disable=unused-variable device: Device, # pylint: disable=unused-argument args_info: T_ARG_INFO_JSON_OBJ_LIST, # pylint: disable=unused-argument alloc_repeat: int, # pylint: disable=unused-argument ) -> RPCSession: time.sleep(2) evaluator_config = EvaluatorConfig( number=1, repeat=1, min_repeat_ms=0, enable_cpu_cache_flush=False, ) runner = LocalRunner( timeout_sec=1, evaluator_config=evaluator_config, initializer=initializer, f_alloc_argument="meta_schedule.runner.test_time_out", ) # Run the module (runner_future,) = runner.run([runner_input]) runner_result = runner_future.result() assert runner_result.error_msg is not None and runner_result.error_msg.startswith( "LocalRunner: Timeout, killed after" ) assert runner_result.run_secs is None _clean_build(builder_result.artifact_path) def test_meta_schedule_rpc_runner_exception(): """Test meta schedule RPC Runner exception""" def initializer(): @register_func("meta_schedule.runner.test_exception") def exception_session_creator( # pylint: disable=unused-variable rpc_config: RPCConfig, # pylint: disable=unused-argument ) -> RPCSession: raise Exception("Test") runner_input = RunnerInput( "test", "llvm", [ TensorInfo("float32", (MATMUL_N, MATMUL_N)), TensorInfo("float32", (MATMUL_N, MATMUL_N)), TensorInfo("float32", (MATMUL_N, MATMUL_N)), ], ) with LocalRPC() as rpc: rpc_config = RPCConfig( tracker_host=rpc.tracker_host, tracker_port=rpc.tracker_port, tracker_key=rpc.tracker_key, session_priority=1, session_timeout_sec=100, ) evaluator_config = EvaluatorConfig( number=1, repeat=1, min_repeat_ms=0, enable_cpu_cache_flush=False, ) runner = RPCRunner( rpc_config, evaluator_config, initializer=initializer, f_create_session="meta_schedule.runner.test_exception", ) (runner_future,) = runner.run([runner_input]) runner_result = runner_future.result() assert runner_result.error_msg is not None and runner_result.error_msg.startswith( "RPCRunner: An exception occurred\n" ) assert runner_result.run_secs is None def test_meta_schedule_local_runner_exception(): """Test meta schedule Local Runner exception""" mod = MatmulModule builder = LocalBuilder() (builder_result,) = builder.build([BuilderInput(mod, Target("llvm"))]) assert builder_result.artifact_path is not None assert builder_result.error_msg is None runner_input = RunnerInput( builder_result.artifact_path, "llvm", [ TensorInfo("float32", (MATMUL_N, MATMUL_N)), TensorInfo("float32", (MATMUL_N, MATMUL_N)), TensorInfo("float32", (MATMUL_N, MATMUL_N)), ], ) def initializer(): @register_func("meta_schedule.runner.test_exception") def timeout_session_creator( # pylint: disable=unused-variable device: Device, # pylint: disable=unused-argument args_info: T_ARG_INFO_JSON_OBJ_LIST, # pylint: disable=unused-argument alloc_repeat: int, # pylint: disable=unused-argument ) -> RPCSession: raise Exception("Test") evaluator_config = EvaluatorConfig( number=1, repeat=1, min_repeat_ms=0, enable_cpu_cache_flush=False, ) runner = LocalRunner( evaluator_config=evaluator_config, initializer=initializer, f_alloc_argument="meta_schedule.runner.test_exception", ) # Run the module (runner_future,) = runner.run([runner_input]) runner_result = runner_future.result() assert runner_result.error_msg is not None and runner_result.error_msg.startswith( "LocalRunner: An exception occurred\n" ) assert runner_result.run_secs is None _clean_build(builder_result.artifact_path) def test_meta_schedule_runner_matmul_test(): """Test meta schedule runner with add module""" def _check_correct_matmul( args_before: List[np.ndarray], args_after: List[np.ndarray], ) -> None: a_before, b_before, c_before = args_before a_after, b_after, c_after = args_after c_before = np.matmul(a_before, b_before) assert (a_before == a_after).all() assert (b_before == b_after).all() tvm.testing.assert_allclose(c_before, c_after, rtol=1e-5) def test_alloc_argument( session: RPCSession, device: Device, args_info: Any, alloc_repeat: int, ) -> List[Any]: global repeated_args_before # pylint: disable=global-variable-undefined, invalid-name repeated_args_before = [] # type: ignore repeated_args = rpc_default_alloc_argument(session, device, args_info, alloc_repeat) for args in repeated_args: repeated_args_before.append([arg.numpy() for arg in args]) # type: ignore return repeated_args def test_run_evaluator( session: RPCSession, # pylint: disable=unused-argument rt_mod: Module, device: Device, evaluator_config: EvaluatorConfig, repeated_args: List[Any], ) -> List[float]: global repeated_args_before # pylint: disable=global-variable-undefined, invalid-name repeated_args_after = [] evaluator = rt_mod.time_evaluator( func_name=rt_mod.entry_name, dev=device, number=evaluator_config.number, repeat=evaluator_config.repeat, min_repeat_ms=evaluator_config.min_repeat_ms, f_preproc="cache_flush_cpu_non_first_arg" if evaluator_config.enable_cpu_cache_flush else "", ) repeated_costs: List[List[float]] = [] for args in repeated_args: device.sync() profile_result = evaluator(*args) repeated_costs.append(profile_result.results) repeated_args_after.append([arg.numpy() for arg in args]) costs = [float(cost) for cost in itertools.chain.from_iterable(repeated_costs)] for args_before, args_after in zip( repeated_args_before, # type: ignore repeated_args_after, ): _check_correct_matmul(args_before, args_after) del repeated_args_before # type: ignore return costs # Build the module mod = MatmulModule builder = LocalBuilder() (builder_result,) = builder.build([BuilderInput(mod, Target("llvm"))]) assert builder_result.artifact_path is not None assert builder_result.error_msg is None runner_input = RunnerInput( builder_result.artifact_path, "llvm", [ TensorInfo("float32", (MATMUL_N, MATMUL_N)), TensorInfo("float32", (MATMUL_N, MATMUL_N)), TensorInfo("float32", (MATMUL_N, MATMUL_N)), ], ) with LocalRPC() as rpc: rpc_config = RPCConfig( tracker_host=rpc.tracker_host, tracker_port=rpc.tracker_port, tracker_key=rpc.tracker_key, session_priority=1, session_timeout_sec=100, ) evaluator_config = EvaluatorConfig( number=1, repeat=1, min_repeat_ms=0, enable_cpu_cache_flush=False, ) runner = RPCRunner( rpc_config, evaluator_config, f_alloc_argument=test_alloc_argument, f_run_evaluator=test_run_evaluator, ) # Run the module (runner_future,) = runner.run([runner_input]) runner_result = runner_future.result() assert runner_result.error_msg is None for result in runner_result.run_secs: if isinstance(result, FloatImm): result = result.value assert isinstance(result, float) assert result >= 0.0 _clean_build(builder_result.artifact_path) def test_meta_schedule_runner_add_test(): """Test meta schedule runner with add module""" def _check_correct_add(args_before: List[np.ndarray], args_after: List[np.ndarray]) -> None: a_before, b_before, c_before = args_before a_after, b_after, c_after = args_after c_before = a_before + b_before assert (a_before == a_after).all() assert (b_before == b_after).all() assert (c_before == c_after).all() def test_alloc_argument( session: RPCSession, device: Device, args_info: Any, alloc_repeat: int, ) -> List[Any]: global repeated_args_before # pylint: disable=global-variable-undefined, invalid-name repeated_args_before = [] # type: ignore repeated_args = rpc_default_alloc_argument( session, device, args_info, alloc_repeat, ) for args in repeated_args: repeated_args_before.append([arg.numpy() for arg in args]) # type: ignore return repeated_args def test_run_evaluator( session: RPCSession, # pylint: disable=unused-argument rt_mod: Module, device: Device, evaluator_config: EvaluatorConfig, repeated_args: List[Any], ) -> List[float]: global repeated_args_before # pylint: disable=global-variable-undefined, invalid-name repeated_args_after = [] evaluator = rt_mod.time_evaluator( func_name=rt_mod.entry_name, dev=device, number=evaluator_config.number, repeat=evaluator_config.repeat, min_repeat_ms=evaluator_config.min_repeat_ms, f_preproc="cache_flush_cpu_non_first_arg" if evaluator_config.enable_cpu_cache_flush else "", ) repeated_costs: List[List[float]] = [] for args in repeated_args: device.sync() profile_result = evaluator(*args) repeated_costs.append(profile_result.results) repeated_args_after.append([arg.numpy() for arg in args]) costs = [float(cost) for cost in itertools.chain.from_iterable(repeated_costs)] for args_before, args_after in zip( repeated_args_before, # type: ignore repeated_args_after, ): _check_correct_add(args_before, args_after) del repeated_args_before # type: ignore return costs # Build the module mod = AddModule builder = LocalBuilder() (builder_result,) = builder.build([BuilderInput(mod, Target("llvm"))]) assert builder_result.artifact_path is not None assert builder_result.error_msg is None runner_input = RunnerInput( builder_result.artifact_path, "llvm", [ TensorInfo("float32", [MATMUL_M]), TensorInfo("float32", [MATMUL_M]), TensorInfo("float32", [MATMUL_M]), ], ) with LocalRPC() as rpc: rpc_config = RPCConfig( tracker_host=rpc.tracker_host, tracker_port=rpc.tracker_port, tracker_key=rpc.tracker_key, session_priority=1, session_timeout_sec=100, ) evaluator_config = EvaluatorConfig( number=1, repeat=1, min_repeat_ms=0, enable_cpu_cache_flush=False, ) runner = RPCRunner( rpc_config, evaluator_config, f_alloc_argument=test_alloc_argument, f_run_evaluator=test_run_evaluator, ) # Run the module (runner_future,) = runner.run([runner_input]) runner_result = runner_future.result() assert runner_result.error_msg is None for result in runner_result.run_secs: if isinstance(result, FloatImm): result = result.value assert isinstance(result, float) assert result >= 0.0 _clean_build(builder_result.artifact_path) def test_meta_schedule_local_runner_add_test(): """Test meta schedule local runner with add module""" def _check_correct_add(args_before: List[np.array], args_after: List[np.array]) -> None: a_before, b_before, c_before = args_before a_after, b_after, c_after = args_after c_before = a_before + b_before assert (a_before == a_after).all() assert (b_before == b_after).all() assert (c_before == c_after).all() def test_alloc_argument( device: Device, args_info: T_ARG_INFO_JSON_OBJ_LIST, # pylint: disable=unused-argument alloc_repeat: int, ) -> List[T_ARGUMENT_LIST]: global repeated_args_before # pylint: disable=global-variable-undefined, invalid-name repeated_args_before = [] repeated_args = local_default_alloc_argument(device, args_info, alloc_repeat) for args in repeated_args: repeated_args_before.append([arg.asnumpy() for arg in args]) return repeated_args def test_run_evaluator( rt_mod: Module, device: Device, evaluator_config: EvaluatorConfig, repeated_args: List[Any], ) -> List[float]: global repeated_args_before # pylint: disable=global-variable-undefined, invalid-name repeated_args_after = [] evaluator = rt_mod.time_evaluator( func_name=rt_mod.entry_name, dev=device, number=evaluator_config.number, repeat=evaluator_config.repeat, min_repeat_ms=evaluator_config.min_repeat_ms, f_preproc="cache_flush_cpu_non_first_arg" if evaluator_config.enable_cpu_cache_flush else "", ) repeated_costs: List[List[float]] = [] for args in repeated_args: device.sync() profile_result = evaluator(*args) repeated_costs.append(profile_result.results) repeated_args_after.append([arg.asnumpy() for arg in args]) costs = [float(cost) for cost in itertools.chain.from_iterable(repeated_costs)] for args_before, args_after in zip(repeated_args_before, repeated_args_after): _check_correct_add(args_before, args_after) del repeated_args_before return costs # Build the module mod = AddModule builder = LocalBuilder() (builder_result,) = builder.build([BuilderInput(mod, Target("llvm"))]) assert builder_result.artifact_path is not None assert builder_result.error_msg is None runner_input = RunnerInput( builder_result.artifact_path, "llvm", [ TensorInfo("float32", [MATMUL_M]), TensorInfo("float32", [MATMUL_M]), TensorInfo("float32", [MATMUL_M]), ], ) evaluator_config = EvaluatorConfig( number=1, repeat=1, min_repeat_ms=0, enable_cpu_cache_flush=False, ) runner = LocalRunner( timeout_sec=100, evaluator_config=evaluator_config, f_alloc_argument=test_alloc_argument, f_run_evaluator=test_run_evaluator, ) # Run the module (runner_future,) = runner.run([runner_input]) runner_result = runner_future.result() assert runner_result.error_msg is None for result in runner_result.run_secs: if isinstance(result, FloatImm): result = result.value assert isinstance(result, float) assert result >= 0.0 _clean_build(builder_result.artifact_path) if __name__ == "__main__": tvm.testing.main()
https://github.com/zk-ml/tachikoma
tests/python/unittest/test_meta_schedule_schedule_rule_add_rfactor.py
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. # pylint: disable=missing-module-docstring,missing-function-docstring,missing-class-docstring from tvm import meta_schedule as ms from tvm.meta_schedule.testing import te_workload from tvm.meta_schedule.testing.space_generation import ( check_sketches, generate_design_space, ) from tvm.script import tir as T from tvm.target import Target from tvm.te import create_prim_func def test_cpu_matmul(): @T.prim_func def cpu_matmul_0( A: T.Buffer[(4, 512), "float32"], B: T.Buffer[(512, 4), "float32"], C: T.Buffer[(4, 4), "float32"], ) -> None: T.func_attr({"global_symbol": "main", "tir.noalias": True}) for i0, i1, i2 in T.grid(4, 4, 512): with T.block("C"): i, j, k = T.axis.remap("SSR", [i0, i1, i2]) T.reads(A[i, k], B[k, j]) T.writes(C[i, j]) with T.init(): C[i, j] = T.float32(0) C[i, j] = C[i, j] + A[i, k] * B[k, j] @T.prim_func def cpu_matmul_1( A: T.Buffer[(4, 512), "float32"], B: T.Buffer[(512, 4), "float32"], C: T.Buffer[(4, 4), "float32"], ) -> None: T.func_attr({"global_symbol": "main", "tir.noalias": True}) C_rf = T.alloc_buffer([4, 4, 128], dtype="float32") for i0, i1, i2_0, i2_1 in T.grid(4, 4, 4, 128): with T.block("C_rf"): vi2_1, i, j, vi2_0 = T.axis.remap("SSSR", [i2_1, i0, i1, i2_0]) T.reads(A[i, vi2_0 * 128 + vi2_1], B[vi2_0 * 128 + vi2_1, j]) T.writes(C_rf[i, j, vi2_1]) with T.init(): C_rf[i, j, vi2_1] = T.float32(0) C_rf[i, j, vi2_1] = ( C_rf[i, j, vi2_1] + A[i, vi2_0 * 128 + vi2_1] * B[vi2_0 * 128 + vi2_1, j] ) for i0, i1, i2_1 in T.grid(4, 4, 128): with T.block("C"): vi2_1, i, j = T.axis.remap("RSS", [i2_1, i0, i1]) T.reads(C_rf[i, j, vi2_1]) T.writes(C[i, j]) T.block_attr({"meta_schedule.random_compute_producer": 1}) with T.init(): C[i, j] = T.float32(0) C[i, j] = C[i, j] + C_rf[i, j, vi2_1] @T.prim_func def cpu_matmul_2( A: T.Buffer[(4, 512), "float32"], B: T.Buffer[(512, 4), "float32"], C: T.Buffer[(4, 4), "float32"], ) -> None: T.func_attr({"global_symbol": "main", "tir.noalias": True}) C_rf = T.alloc_buffer([4, 4, 4], dtype="float32") for i0, i1, i2_0, i2_1 in T.grid(4, 4, 4, 128): with T.block("C_rf"): vi2_0, i, j, vi2_1 = T.axis.remap("SSSR", [i2_0, i0, i1, i2_1]) T.reads(A[i, vi2_0 * 128 + vi2_1], B[vi2_0 * 128 + vi2_1, j]) T.writes(C_rf[i, j, vi2_0]) with T.init(): C_rf[i, j, vi2_0] = T.float32(0) C_rf[i, j, vi2_0] = ( C_rf[i, j, vi2_0] + A[i, vi2_0 * 128 + vi2_1] * B[vi2_0 * 128 + vi2_1, j] ) for i0, i1, i2_0 in T.grid(4, 4, 4): with T.block("C"): vi2_0, i, j = T.axis.remap("RSS", [i2_0, i0, i1]) T.reads(C_rf[i, j, vi2_0]) T.writes(C[i, j]) T.block_attr({"meta_schedule.random_compute_producer": 1}) with T.init(): C[i, j] = T.float32(0) C[i, j] = C[i, j] + C_rf[i, j, vi2_0] decision_0 = [] # type: ignore decision_1 = [ ("SamplePerfectTile", [4, 128]), ] decision_2 = [ ("SamplePerfectTile", [4, 128]), ] mod = create_prim_func(te_workload.matmul(n=4, m=4, k=512)) actual = generate_design_space( kind="llvm", mod=mod, target=Target("llvm --num-cores=32"), types=ms.schedule_rule.AddRFactor, ) check_sketches( mod, sketches=actual, expected_mods=[cpu_matmul_0, cpu_matmul_1, cpu_matmul_2], expected_decisions=[decision_0, decision_1, decision_2], ) def test_cpu_argmax(): @T.prim_func def argmax( idx: T.Buffer[(128, 128), "int32"], val: T.Buffer[(128, 128), "float32"], argmax_v0: T.Buffer[(128,), "int32"], argmax_v1: T.Buffer[(128,), "float32"], ) -> None: for i0, i1 in T.grid(128, 128): with T.block("argmax"): i = T.axis.spatial(128, i0) k = T.axis.reduce(128, i1) T.reads(idx[i, k], val[i, k]) T.writes(argmax_v0[i], argmax_v1[i]) with T.init(): argmax_v0[i] = -1 argmax_v1[i] = T.min_value("float32") v_argmax_v0: T.int32 = T.Select(argmax_v1[i] >= val[i, k], argmax_v0[i], idx[i, k]) v_argmax_v1: T.float32 = T.Select( argmax_v1[i] >= val[i, k], argmax_v1[i], val[i, k] ) argmax_v0[i] = v_argmax_v0 argmax_v1[i] = v_argmax_v1 @T.prim_func def argmax_0( idx: T.Buffer[(128, 128), "int32"], val: T.Buffer[(128, 128), "float32"], argmax_v0: T.Buffer[128, "int32"], argmax_v1: T.Buffer[128, "float32"], ) -> None: for i0, i1 in T.grid(128, 128): with T.block("argmax"): i, k = T.axis.remap("SR", [i0, i1]) T.reads(idx[i, k], val[i, k]) T.writes(argmax_v0[i], argmax_v1[i]) with T.init(): argmax_v0[i] = -1 argmax_v1[i] = T.float32(-3.4028234663852886e38) v_argmax_v0: T.int32 = T.Select(argmax_v1[i] >= val[i, k], argmax_v0[i], idx[i, k]) v_argmax_v1: T.float32 = T.Select( argmax_v1[i] >= val[i, k], argmax_v1[i], val[i, k] ) argmax_v0[i] = v_argmax_v0 argmax_v1[i] = v_argmax_v1 @T.prim_func def argmax_1( idx: T.Buffer[(128, 128), "int32"], val: T.Buffer[(128, 128), "float32"], argmax_v0: T.Buffer[128, "int32"], argmax_v1: T.Buffer[128, "float32"], ) -> None: argmax_v0_rf = T.alloc_buffer([128, 16], dtype="int32") argmax_v1_rf = T.alloc_buffer([128, 16], dtype="float32") for i0, i1_0, i1_1 in T.grid(128, 8, 16): with T.block("argmax_rf"): vi1_1, i, vi1_0 = T.axis.remap("SSR", [i1_1, i0, i1_0]) T.reads(idx[i, vi1_0 * 16 + vi1_1], val[i, vi1_0 * 16 + vi1_1]) T.writes(argmax_v0_rf[i, vi1_1], argmax_v1_rf[i, vi1_1]) with T.init(): argmax_v0_rf[i, vi1_1] = -1 argmax_v1_rf[i, vi1_1] = T.float32(-3.4028234663852886e38) v_argmax_v0_rf: T.int32 = T.Select( argmax_v1_rf[i, vi1_1] >= val[i, vi1_0 * 16 + vi1_1], argmax_v0_rf[i, vi1_1], idx[i, vi1_0 * 16 + vi1_1], ) v_argmax_v1_rf: T.float32 = T.Select( argmax_v1_rf[i, vi1_1] >= val[i, vi1_0 * 16 + vi1_1], argmax_v1_rf[i, vi1_1], val[i, vi1_0 * 16 + vi1_1], ) argmax_v0_rf[i, vi1_1] = v_argmax_v0_rf argmax_v1_rf[i, vi1_1] = v_argmax_v1_rf for i0, i1_1 in T.grid(128, 16): with T.block("argmax"): vi1_1, i = T.axis.remap("RS", [i1_1, i0]) T.reads(argmax_v0_rf[i, vi1_1], argmax_v1_rf[i, vi1_1]) T.writes(argmax_v0[i], argmax_v1[i]) T.block_attr({"meta_schedule.random_compute_producer": 1}) with T.init(): argmax_v0[i] = -1 argmax_v1[i] = T.float32(-3.4028234663852886e38) v_argmax_v0: T.int32 = T.Select( argmax_v1[i] >= argmax_v1_rf[i, vi1_1], argmax_v0[i], argmax_v0_rf[i, vi1_1] ) v_argmax_v1: T.float32 = T.Select( argmax_v1[i] >= argmax_v1_rf[i, vi1_1], argmax_v1[i], argmax_v1_rf[i, vi1_1] ) argmax_v0[i] = v_argmax_v0 argmax_v1[i] = v_argmax_v1 @T.prim_func def argmax_2( idx: T.Buffer[(128, 128), "int32"], val: T.Buffer[(128, 128), "float32"], argmax_v0: T.Buffer[128, "int32"], argmax_v1: T.Buffer[128, "float32"], ) -> None: # body # with T.block("root") argmax_v0_rf = T.alloc_buffer([128, 8], dtype="int32") argmax_v1_rf = T.alloc_buffer([128, 8], dtype="float32") for i0, i1_0, i1_1 in T.grid(128, 8, 16): with T.block("argmax_rf"): vi1_0, i, vi1_1 = T.axis.remap("SSR", [i1_0, i0, i1_1]) T.reads(idx[i, vi1_0 * 16 + vi1_1], val[i, vi1_0 * 16 + vi1_1]) T.writes(argmax_v0_rf[i, vi1_0], argmax_v1_rf[i, vi1_0]) with T.init(): argmax_v0_rf[i, vi1_0] = -1 argmax_v1_rf[i, vi1_0] = T.float32(-3.4028234663852886e38) v_argmax_v0_rf: T.int32 = T.Select( argmax_v1_rf[i, vi1_0] >= val[i, vi1_0 * 16 + vi1_1], argmax_v0_rf[i, vi1_0], idx[i, vi1_0 * 16 + vi1_1], ) v_argmax_v1_rf: T.float32 = T.Select( argmax_v1_rf[i, vi1_0] >= val[i, vi1_0 * 16 + vi1_1], argmax_v1_rf[i, vi1_0], val[i, vi1_0 * 16 + vi1_1], ) argmax_v0_rf[i, vi1_0] = v_argmax_v0_rf argmax_v1_rf[i, vi1_0] = v_argmax_v1_rf for i0, i1_0 in T.grid(128, 8): with T.block("argmax"): vi1_0, i = T.axis.remap("RS", [i1_0, i0]) T.reads(argmax_v0_rf[i, vi1_0], argmax_v1_rf[i, vi1_0]) T.writes(argmax_v0[i], argmax_v1[i]) T.block_attr({"meta_schedule.random_compute_producer": 1}) with T.init(): argmax_v0[i] = -1 argmax_v1[i] = T.float32(-3.4028234663852886e38) v_argmax_v0: T.int32 = T.Select( argmax_v1[i] >= argmax_v1_rf[i, vi1_0], argmax_v0[i], argmax_v0_rf[i, vi1_0] ) v_argmax_v1: T.float32 = T.Select( argmax_v1[i] >= argmax_v1_rf[i, vi1_0], argmax_v1[i], argmax_v1_rf[i, vi1_0] ) argmax_v0[i] = v_argmax_v0 argmax_v1[i] = v_argmax_v1 decision_0 = [] # type: ignore decision_1 = [ ("SamplePerfectTile", [8, 16]), ] decision_2 = [ ("SamplePerfectTile", [8, 16]), ] mod = argmax actual = generate_design_space( kind="llvm", mod=mod, target=Target("llvm --num-cores=32"), types=ms.schedule_rule.AddRFactor, ) check_sketches( mod, sketches=actual, expected_mods=[argmax_0, argmax_1, argmax_2], expected_decisions=[decision_0, decision_1, decision_2], ) if __name__ == "__main__": test_cpu_matmul() test_cpu_argmax()
https://github.com/zk-ml/tachikoma
tests/python/unittest/test_meta_schedule_schedule_rule_apply_custom_rule.py
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. # pylint: disable=missing-module-docstring,missing-function-docstring,missing-class-docstring from typing import List import tempfile import pytest import tvm from tvm import meta_schedule as ms from tvm.meta_schedule.schedule_rule import ApplyCustomRule from tvm.script import tir as T @tvm.script.ir_module class Matmul: @T.prim_func def main(a: T.handle, b: T.handle, c: T.handle) -> None: T.func_attr({"global_symbol": "main"}) A = T.match_buffer(a, (1024, 1024), "float32") B = T.match_buffer(b, (1024, 1024), "float32") C = T.match_buffer(c, (1024, 1024), "float32") for i, j, k in T.grid(1024, 1024, 1024): with T.block("matmul"): T.block_attr({"schedule_rule": "test_apply_custom_rule"}) vi, vj, vk = T.axis.remap("SSR", [i, j, k]) with T.init(): C[vi, vj] = 0.0 C[vi, vj] = C[vi, vj] + A[vi, vk] * B[vk, vj] @tvm.register_func("meta_schedule.cpu.test_apply_custom_rule") def sch_fn(sch: tvm.tir.Schedule, block: tvm.tir.Block) -> List[tvm.tir.Schedule]: raise ValueError("Intended for meta_schedule.cpu.test_apply_custom_rule") def test_custom_rule(): with pytest.raises(ValueError) as e_info: with tempfile.TemporaryDirectory() as tmpdir: sch_rules = [ApplyCustomRule()] space_gen = ms.space_generator.PostOrderApply(sch_rules=sch_rules) ms.tune_tir( mod=Matmul, target="llvm -num-cores=1", work_dir=tmpdir, max_trials_global=10, space=space_gen, ) assert "ValueError: Intended for meta_schedule.cpu.test_apply_custom_rule" in str(e_info.value) if __name__ == "__main__": test_custom_rule()
https://github.com/zk-ml/tachikoma
tests/python/unittest/test_meta_schedule_schedule_rule_auto_bind.py
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. # pylint: disable=missing-module-docstring,missing-function-docstring,missing-class-docstring from tvm import meta_schedule as ms from tvm.meta_schedule.testing.space_generation import ( check_sketches, generate_design_space, ) from tvm.script import tir as T from tvm.target import Target @T.prim_func def element_wise(var_A: T.handle, var_B: T.handle) -> None: A = T.match_buffer(var_A, [512, 512], dtype="float32") B = T.match_buffer(var_B, [512, 512], dtype="float32") for i, j in T.grid(512, 512): with T.block("C"): vi, vj = T.axis.remap("SS", [i, j]) B[vi, vj] = A[vi, vj] + 1.0 @T.prim_func def reduction_loop_only( A: T.Buffer[2, "float32"], B: T.Buffer[2, "float32"], C: T.Buffer[(), "float32"], ) -> None: for i0 in T.serial(2): with T.block("C"): k0 = T.axis.reduce(2, i0) T.reads(A[k0], B[k0]) T.writes(C[()]) with T.init(): C[()] = T.float32(1.0) C[()] = T.min(C[()], A[k0] / B[k0]) @T.prim_func def zero_dim_add( A: T.Buffer[(), "float32"], B: T.Buffer[(), "float32"], C: T.Buffer[(), "float32"], ) -> None: with T.block("C"): vi = T.axis.spatial(1, 0) C[()] = A[()] + B[()] def test_cuda_element_wise(): @T.prim_func def elementwise_0( A: T.Buffer[(512, 512), "float32"], B: T.Buffer[(512, 512), "float32"], ) -> None: # body # with T.block("root") for i_j_fused_0 in T.thread_binding(256, thread="blockIdx.x"): for i_j_fused_1 in T.thread_binding(1024, thread="threadIdx.x"): with T.block("C"): vi = T.axis.spatial(512, (i_j_fused_0 * 1024 + i_j_fused_1) // 512) vj = T.axis.spatial(512, (i_j_fused_0 * 1024 + i_j_fused_1) % 512) T.reads(A[vi, vj]) T.writes(B[vi, vj]) B[vi, vj] = A[vi, vj] + T.float32(1) decision_0 = [ ("SampleCategorical", 5), ] mod = element_wise actual = generate_design_space( kind="cuda", mod=mod, target=Target("nvidia/geforce-rtx-3080", host="llvm"), types=ms.schedule_rule.AutoBind, ) check_sketches( mod, sketches=actual, expected_mods=[elementwise_0], expected_decisions=[decision_0], ) def test_cuda_reduction_loop_only(): @T.prim_func def reduction_loop_only_0( A: T.Buffer[2, "float32"], B: T.Buffer[2, "float32"], C: T.Buffer[(), "float32"], ) -> None: for u_fused_0 in T.thread_binding(1, thread="blockIdx.x"): for u_fused_1 in T.thread_binding(1, thread="threadIdx.x"): for i0 in T.serial(2): with T.block("C"): k0 = T.axis.reduce(2, i0) T.reads(A[k0], B[k0]) T.writes(C[()]) with T.init(): C[()] = T.float32(1) C[()] = T.min(C[()], A[k0] / B[k0]) mod = reduction_loop_only actual = generate_design_space( kind="cuda", mod=mod, target=Target("nvidia/geforce-rtx-3080", host="llvm"), types=ms.schedule_rule.AutoBind, ) check_sketches( mod, sketches=actual, expected_mods=[reduction_loop_only_0], expected_decisions=[[]], ) def test_cuda_zero_dim_add(): @T.prim_func def zero_dim_add_0( A: T.Buffer[(), "float32"], B: T.Buffer[(), "float32"], C: T.Buffer[(), "float32"], ) -> None: for u_fused_0 in T.thread_binding(1, thread="blockIdx.x"): for u_fused_1 in T.thread_binding(1, thread="threadIdx.x"): with T.block("C"): vi = T.axis.spatial(1, 0) T.reads(A[()], B[()]) T.writes(C[()]) C[()] = A[()] + B[()] mod = zero_dim_add actual = generate_design_space( kind="cuda", mod=mod, target=Target("nvidia/geforce-rtx-3080", host="llvm"), types=ms.schedule_rule.AutoBind, ) check_sketches( mod, sketches=actual, expected_mods=[zero_dim_add_0], expected_decisions=[[]], ) if __name__ == "__main__": test_cuda_element_wise() test_cuda_reduction_loop_only() test_cuda_zero_dim_add()
https://github.com/zk-ml/tachikoma
tests/python/unittest/test_meta_schedule_schedule_rule_auto_inline.py
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. # pylint: disable=missing-module-docstring,missing-function-docstring,missing-class-docstring import pytest import tvm from tvm.tir import Schedule from tvm import meta_schedule as ms from tvm.meta_schedule.testing.space_generation import generate_design_space from tvm.script import tir as T from tvm.target import Target # fmt: off # pylint: disable=no-member,invalid-name,unused-variable,no-self-argument,line-too-long,chained-comparison,not-callable,too-many-nested-blocks @tvm.script.ir_module class Conv2DBiasBnReLU: @T.prim_func def main(var_X: T.handle, var_W: T.handle, var_B: T.handle, var_bn_scale: T.handle, var_bn_offset: T.handle, var_compute: T.handle) -> None: X = T.match_buffer(var_X, [1, 512, 56, 56], dtype="float32") W = T.match_buffer(var_W, [512, 512, 3, 3], dtype="float32") B = T.match_buffer(var_B, [512, 1, 1], dtype="float32") bn_scale = T.match_buffer(var_bn_scale, [512, 1, 1], dtype="float32") bn_offset = T.match_buffer(var_bn_offset, [512, 1, 1], dtype="float32") compute = T.match_buffer(var_compute, [1, 512, 56, 56], dtype="float32") pad_temp = T.alloc_buffer([1, 512, 58, 58], dtype="float32") compute_1 = T.alloc_buffer([1, 512, 56, 56], dtype="float32") bias_add = T.alloc_buffer([1, 512, 56, 56], dtype="float32") bn_mul = T.alloc_buffer([1, 512, 56, 56], dtype="float32") bn_add = T.alloc_buffer([1, 512, 56, 56], dtype="float32") for i0, i1, i2, i3 in T.grid(1, 512, 58, 58): with T.block("pad_temp"): i0_1, i1_1, i2_1, i3_1 = T.axis.remap("SSSS", [i0, i1, i2, i3]) pad_temp[i0_1, i1_1, i2_1, i3_1] = T.if_then_else(i2_1 >= 1 and i2_1 < 57 and i3_1 >= 1 and i3_1 < 57, X[i0_1, i1_1, i2_1 - 1, i3_1 - 1], T.float32(0), dtype="float32") for i0, i1, i2, i3, i4, i5, i6 in T.grid(1, 512, 56, 56, 512, 3, 3): with T.block("compute"): nn, ff, yy, xx, rc, ry, rx = T.axis.remap("SSSSRRR", [i0, i1, i2, i3, i4, i5, i6]) with T.init(): compute_1[nn, ff, yy, xx] = T.float32(0) compute_1[nn, ff, yy, xx] = compute_1[nn, ff, yy, xx] + pad_temp[nn, rc, yy + ry, xx + rx] * W[ff, rc, ry, rx] for i0, i1, i2, i3 in T.grid(1, 512, 56, 56): with T.block("bias_add"): i, j, k, l = T.axis.remap("SSSS", [i0, i1, i2, i3]) bias_add[i, j, k, l] = compute_1[i, j, k, l] + B[j, 0, 0] for i0, i1, i2, i3 in T.grid(1, 512, 56, 56): with T.block("bn_mul"): i, j, k, l = T.axis.remap("SSSS", [i0, i1, i2, i3]) bn_mul[i, j, k, l] = bias_add[i, j, k, l] * bn_scale[j, 0, 0] for i0, i1, i2, i3 in T.grid(1, 512, 56, 56): with T.block("bn_add"): i, j, k, l = T.axis.remap("SSSS", [i0, i1, i2, i3]) bn_add[i, j, k, l] = bn_mul[i, j, k, l] + bn_offset[j, 0, 0] for i0, i1, i2, i3 in T.grid(1, 512, 56, 56): with T.block("compute_1"): i0_2, i1_2, i2_2, i3_2 = T.axis.remap("SSSS", [i0, i1, i2, i3]) compute[i0_2, i1_2, i2_2, i3_2] = T.max(bn_add[i0_2, i1_2, i2_2, i3_2], T.float32(0)) @tvm.script.ir_module class Conv2DBiasBnReLUInlined: @T.prim_func def main(var_X: T.handle, var_W: T.handle, var_B: T.handle, var_bn_scale: T.handle, var_bn_offset: T.handle, var_compute: T.handle) -> None: X = T.match_buffer(var_X, [1, 512, 56, 56], dtype="float32") W = T.match_buffer(var_W, [512, 512, 3, 3], dtype="float32") B = T.match_buffer(var_B, [512, 1, 1], dtype="float32") bn_scale = T.match_buffer(var_bn_scale, [512, 1, 1], dtype="float32") bn_offset = T.match_buffer(var_bn_offset, [512, 1, 1], dtype="float32") compute = T.match_buffer(var_compute, [1, 512, 56, 56], dtype="float32") pad_temp = T.alloc_buffer([1, 512, 58, 58], dtype="float32") compute_1 = T.alloc_buffer([1, 512, 56, 56], dtype="float32") for i0, i1, i2, i3 in T.grid(1, 512, 58, 58): with T.block("pad_temp"): i0_1, i1_1, i2_1, i3_1 = T.axis.remap("SSSS", [i0, i1, i2, i3]) pad_temp[i0_1, i1_1, i2_1, i3_1] = T.if_then_else(i2_1 >= 1 and i2_1 < 57 and i3_1 >= 1 and i3_1 < 57, X[i0_1, i1_1, i2_1 - 1, i3_1 - 1], T.float32(0), dtype="float32") for i0, i1, i2, i3, i4, i5, i6 in T.grid(1, 512, 56, 56, 512, 3, 3): with T.block("compute"): nn, ff, yy, xx, rc, ry, rx = T.axis.remap("SSSSRRR", [i0, i1, i2, i3, i4, i5, i6]) with T.init(): compute_1[nn, ff, yy, xx] = T.float32(0) compute_1[nn, ff, yy, xx] = compute_1[nn, ff, yy, xx] + pad_temp[nn, rc, yy + ry, xx + rx] * W[ff, rc, ry, rx] for i0, i1, i2, i3 in T.grid(1, 512, 56, 56): with T.block("compute_1"): i0_2, i1_2, i2_2, i3_2 = T.axis.remap("SSSS", [i0, i1, i2, i3]) compute[i0_2, i1_2, i2_2, i3_2] = T.max((compute_1[i0_2, i1_2, i2_2, i3_2] + B[i1_2, 0, 0]) * bn_scale[i1_2, 0, 0] + bn_offset[i1_2, 0, 0], T.float32(0)) @tvm.script.ir_module class MultiLevelTiledConv2D: @T.prim_func def main(var_X: T.handle, var_W: T.handle, var_B: T.handle, var_bn_scale: T.handle, var_bn_offset: T.handle, var_compute: T.handle) -> None: X = T.match_buffer(var_X, [1, 512, 56, 56], dtype="float32") W = T.match_buffer(var_W, [512, 512, 3, 3], dtype="float32") B = T.match_buffer(var_B, [512, 1, 1], dtype="float32") bn_scale = T.match_buffer(var_bn_scale, [512, 1, 1], dtype="float32") bn_offset = T.match_buffer(var_bn_offset, [512, 1, 1], dtype="float32") compute = T.match_buffer(var_compute, [1, 512, 56, 56], dtype="float32") pad_temp = T.alloc_buffer([1, 512, 58, 58], dtype="float32") compute_1 = T.alloc_buffer([1, 512, 56, 56], dtype="float32") compute_local = T.alloc_buffer([1, 512, 56, 56], dtype="float32", scope="local") pad_temp_shared = T.alloc_buffer([1, 512, 58, 58], dtype="float32", scope="shared") W_shared = T.alloc_buffer([512, 512, 3, 3], dtype="float32", scope="shared") for i0, i1, i2, i3 in T.grid(1, 512, 58, 58): with T.block("pad_temp"): i0_1, i1_1, i2_1, i3_1 = T.axis.remap("SSSS", [i0, i1, i2, i3]) pad_temp[i0_1, i1_1, i2_1, i3_1] = T.if_then_else(i2_1 >= 1 and i2_1 < 57 and i3_1 >= 1 and i3_1 < 57, X[i0_1, i1_1, i2_1 - 1, i3_1 - 1], T.float32(0), dtype="float32") for i0_0_i1_0_i2_0_i3_0_fused in T.thread_binding(0, 224, thread="blockIdx.x"): for i0_1_i1_1_i2_1_i3_1_fused in T.thread_binding(0, 2, thread="vthread.x"): for i0_2_i1_2_i2_2_i3_2_fused in T.thread_binding(0, 8, thread="threadIdx.x"): for i4_0, i5_0, i6_0 in T.grid(1, 3, 1): for ax0_ax1_ax2_ax3_fused_0 in T.serial(0, 40960, annotations={"meta_schedule.cooperative_fetch":1}): for ax0_ax1_ax2_ax3_fused_1 in T.vectorized(0, 3): with T.block("pad_temp_shared"): v0 = T.axis.spatial(1, 0) v1 = T.axis.spatial(512, (ax0_ax1_ax2_ax3_fused_0 * 3 + ax0_ax1_ax2_ax3_fused_1) // 30 // 8 % 512) v2 = T.axis.spatial(58, i0_0_i1_0_i2_0_i3_0_fused % 14 // 2 * 8 + i5_0 + (ax0_ax1_ax2_ax3_fused_0 * 3 + ax0_ax1_ax2_ax3_fused_1) // 30 % 8) v3 = T.axis.spatial(58, i0_0_i1_0_i2_0_i3_0_fused % 2 * 28 + (ax0_ax1_ax2_ax3_fused_0 * 3 + ax0_ax1_ax2_ax3_fused_1) % 30) pad_temp_shared[v0, v1, v2, v3] = pad_temp[v0, v1, v2, v3] for ax0_ax1_ax2_ax3_fused_0 in T.serial(0, 12288, annotations={"meta_schedule.cooperative_fetch":1}): for ax0_ax1_ax2_ax3_fused_1 in T.vectorized(0, 4): with T.block("W_shared"): v0 = T.axis.spatial(512, i0_0_i1_0_i2_0_i3_0_fused // 14 * 32 + (ax0_ax1_ax2_ax3_fused_0 * 4 + ax0_ax1_ax2_ax3_fused_1) // 1536) v1 = T.axis.spatial(512, (ax0_ax1_ax2_ax3_fused_0 * 4 + ax0_ax1_ax2_ax3_fused_1) // 3 % 512) v2 = T.axis.spatial(3, i5_0) v3 = T.axis.spatial(3, (ax0_ax1_ax2_ax3_fused_0 * 4 + ax0_ax1_ax2_ax3_fused_1) % 3) W_shared[v0, v1, v2, v3] = W[v0, v1, v2, v3] for i4_1, i5_1, i6_1, i0_3, i1_3, i2_3, i3_3, i4_2, i5_2, i6_2, i0_4, i1_4, i2_4, i3_4 in T.grid(32, 1, 1, 1, 1, 1, 1, 16, 1, 3, 1, 8, 2, 28): with T.block("compute"): nn = T.axis.spatial(1, 0) ff = T.axis.spatial(512, i0_0_i1_0_i2_0_i3_0_fused // 14 * 32 + i0_2_i1_2_i2_2_i3_2_fused // 2 * 8 + i1_4) yy = T.axis.spatial(56, i0_0_i1_0_i2_0_i3_0_fused // 2 % 7 * 8 + i0_1_i1_1_i2_1_i3_1_fused * 4 + i0_2_i1_2_i2_2_i3_2_fused % 2 * 2 + i2_4) xx = T.axis.spatial(56, i0_0_i1_0_i2_0_i3_0_fused % 2 * 28 + i3_4) rc = T.axis.reduce(512, i4_1 * 16 + i4_2) ry, rx = T.axis.remap("RR", [i5_0, i6_2]) with T.init(): compute_local[nn, ff, yy, xx] = T.float32(0) compute_local[nn, ff, yy, xx] = compute_local[nn, ff, yy, xx] + pad_temp_shared[nn, rc, yy + ry, xx + rx] * W_shared[ff, rc, ry, rx] for ax0, ax1, ax2, ax3 in T.grid(1, 8, 2, 28): with T.block("compute_local"): v0 = T.axis.spatial(1, ax0) v1 = T.axis.spatial(512, i0_0_i1_0_i2_0_i3_0_fused // 14 * 32 + i0_2_i1_2_i2_2_i3_2_fused // 2 * 8 + ax1) v2 = T.axis.spatial(56, i0_0_i1_0_i2_0_i3_0_fused % 14 // 2 * 8 + i0_1_i1_1_i2_1_i3_1_fused * 4 + i0_2_i1_2_i2_2_i3_2_fused % 2 * 2 + ax2) v3 = T.axis.spatial(56, i0_0_i1_0_i2_0_i3_0_fused % 2 * 28 + ax3) compute_1[v0, v1, v2, v3] = compute_local[v0, v1, v2, v3] for i0, i1, i2, i3 in T.grid(1, 512, 56, 56): with T.block("compute_1"): i0_2, i1_2, i2_2, i3_2 = T.axis.remap("SSSS", [i0, i1, i2, i3]) compute[i0_2, i1_2, i2_2, i3_2] = T.max((compute_1[i0_2, i1_2, i2_2, i3_2] + B[i1_2, 0, 0]) * bn_scale[i1_2, 0, 0] + bn_offset[i1_2, 0, 0], T.float32(0)) @tvm.script.ir_module class MultiLevelTiledConv2DAfterInline: @T.prim_func def main(X: T.Buffer[(1, 512, 56, 56), "float32"], W: T.Buffer[(512, 512, 3, 3), "float32"], B: T.Buffer[(512, 1, 1), "float32"], bn_scale: T.Buffer[(512, 1, 1), "float32"], bn_offset: T.Buffer[(512, 1, 1), "float32"], compute: T.Buffer[(1, 512, 56, 56), "float32"]) -> None: compute_local = T.alloc_buffer([1, 512, 56, 56], dtype="float32", scope="local") for i0_0_i1_0_i2_0_i3_0_fused in T.thread_binding(224, thread="blockIdx.x"): for i0_1_i1_1_i2_1_i3_1_fused in T.thread_binding(2, thread="vthread.x"): for i0_2_i1_2_i2_2_i3_2_fused in T.thread_binding(8, thread="threadIdx.x"): for i4_0, i5_0, i6_0, i4_1, i5_1, i6_1, i0_3, i1_3, i2_3, i3_3, i4_2, i5_2, i6_2, i0_4, i1_4, i2_4, i3_4 in T.grid(1, 3, 1, 32, 1, 1, 1, 1, 1, 1, 16, 1, 3, 1, 8, 2, 28): with T.block("compute"): nn = T.axis.spatial(1, 0) ff = T.axis.spatial(512, i0_0_i1_0_i2_0_i3_0_fused // 14 * 32 + i0_2_i1_2_i2_2_i3_2_fused // 2 * 8 + i1_4) yy = T.axis.spatial(56, i0_0_i1_0_i2_0_i3_0_fused // 2 % 7 * 8 + i0_1_i1_1_i2_1_i3_1_fused * 4 + i0_2_i1_2_i2_2_i3_2_fused % 2 * 2 + i2_4) xx = T.axis.spatial(56, i0_0_i1_0_i2_0_i3_0_fused % 2 * 28 + i3_4) rc = T.axis.reduce(512, i4_1 * 16 + i4_2) ry, rx = T.axis.remap("RR", [i5_0, i6_2]) with T.init(): compute_local[nn, ff, yy, xx] = T.float32(0) compute_local[nn, ff, yy, xx] = compute_local[nn, ff, yy, xx] + T.if_then_else(yy + ry >= 1 and yy + ry < 57 and xx + rx >= 1 and xx + rx < 57, X[nn, rc, yy + ry - 1, xx + rx - 1], T.float32(0), dtype="float32") * W[ff, rc, ry, rx] for ax0, ax1, ax2, ax3 in T.grid(1, 8, 2, 28): with T.block("compute_local"): v0 = T.axis.spatial(1, ax0) v1 = T.axis.spatial(512, i0_0_i1_0_i2_0_i3_0_fused // 14 * 32 + i0_2_i1_2_i2_2_i3_2_fused // 2 * 8 + ax1) v2 = T.axis.spatial(56, i0_0_i1_0_i2_0_i3_0_fused % 14 // 2 * 8 + i0_1_i1_1_i2_1_i3_1_fused * 4 + i0_2_i1_2_i2_2_i3_2_fused % 2 * 2 + ax2) v3 = T.axis.spatial(56, i0_0_i1_0_i2_0_i3_0_fused % 2 * 28 + ax3) compute[v0, v1, v2, v3] = T.max((compute_local[v0, v1, v2, v3] + B[v1, 0, 0]) * bn_scale[v1, 0, 0] + bn_offset[v1, 0, 0], T.float32(0)) @tvm.script.ir_module class SoftmaxBeforeInline: @T.prim_func def main(A: T.Buffer[(256, 256), "float32"], T_softmax_norm: T.Buffer[(256, 256), "float32"]) -> None: T_softmax_maxelem = T.alloc_buffer([256], dtype="float32") T_softmax_exp = T.alloc_buffer([256, 256], dtype="float32") T_softmax_expsum = T.alloc_buffer([256], dtype="float32") for i0, i1 in T.grid(256, 256): with T.block("T_softmax_maxelem"): i0_1, k = T.axis.remap("SR", [i0, i1]) with T.init(): T_softmax_maxelem[i0_1] = T.min_value("float32") T_softmax_maxelem[i0_1] = T.max(T_softmax_maxelem[i0_1], A[i0_1, k]) for i0, i1 in T.grid(256, 256): with T.block("T_softmax_exp"): i0_2, i1_1 = T.axis.remap("SS", [i0, i1]) T_softmax_exp[i0_2, i1_1] = T.exp(A[i0_2, i1_1] - T_softmax_maxelem[i0_2], dtype="float32") for i0_3, i1 in T.grid(256, 256): with T.block("T_softmax_expsum"): i0_4, k = T.axis.remap("SR", [i0_3, i1]) with T.init(): T_softmax_expsum[i0_4] = T.float32(0) T_softmax_expsum[i0_4] = T_softmax_expsum[i0_4] + T_softmax_exp[i0_4, k] for i0_5, i1 in T.grid(256, 256): with T.block("T_softmax_norm"): i0_6, i1_2 = T.axis.remap("SS", [i0_5, i1]) T_softmax_norm[i0_6, i1_2] = T_softmax_exp[i0_6, i1_2] / T_softmax_expsum[i0_6] @tvm.script.ir_module class SoftmaxAfterInline: @T.prim_func def main(A: T.Buffer[(256, 256), "float32"], T_softmax_norm: T.Buffer[(256, 256), "float32"]) -> None: T_softmax_maxelem = T.alloc_buffer([256], dtype="float32") T_softmax_expsum = T.alloc_buffer([256], dtype="float32") for i0, i1 in T.grid(256, 256): with T.block("T_softmax_maxelem"): i0_1, k = T.axis.remap("SR", [i0, i1]) with T.init(): T_softmax_maxelem[i0_1] = T.min_value("float32") T_softmax_maxelem[i0_1] = T.max(T_softmax_maxelem[i0_1], A[i0_1, k]) for i0, i1 in T.grid(256, 256): with T.block("T_softmax_expsum"): i0_2, k = T.axis.remap("SR", [i0, i1]) with T.init(): T_softmax_expsum[i0_2] = T.float32(0) T_softmax_expsum[i0_2] = T_softmax_expsum[i0_2] + T.exp(A[i0_2, k] - T_softmax_maxelem[i0_2], dtype="float32") for i0_3, i1 in T.grid(256, 256): with T.block("T_softmax_norm"): i0_4, i1_1 = T.axis.remap("SS", [i0_3, i1]) T_softmax_norm[i0_4, i1_1] = T.exp(A[i0_4, i1_1] - T_softmax_maxelem[i0_4], dtype="float32") / T_softmax_expsum[i0_4] @tvm.script.ir_module class BeforePureSpatial: @T.prim_func def main( placeholder: T.Buffer[(1, 384), "int64"], placeholder_1: T.Buffer[(30522, 768), "float32"], placeholder_2: T.Buffer[(1, 384, 768), "float32"], T_add: T.Buffer[(1, 384, 768), "float32"], ) -> None: T.func_attr({"global_symbol": "main", "tir.noalias": True}) compile_engine_const = T.alloc_buffer([], dtype="int64") T_less = T.alloc_buffer([1, 384], dtype="bool") compile_engine_const_1 = T.alloc_buffer([], dtype="int64") T_add_1 = T.alloc_buffer([1, 384], dtype="int64") T_where = T.alloc_buffer([1, 384], dtype="int64") T_take = T.alloc_buffer([1, 384, 768], dtype="float32") with T.block("compile_engine_const"): vi = T.axis.spatial(1, 0) T.reads() T.writes(compile_engine_const[()]) compile_engine_const[()] = T.int64(0) for i0, i1 in T.grid(1, 384): with T.block("T_less"): ax0, ax1 = T.axis.remap("SS", [i0, i1]) T.reads(placeholder[ax0, ax1], compile_engine_const[()]) T.writes(T_less[ax0, ax1]) T_less[ax0, ax1] = placeholder[ax0, ax1] < compile_engine_const[()] with T.block("compile_engine_const_1"): vi = T.axis.spatial(1, 0) T.reads() T.writes(compile_engine_const_1[()]) compile_engine_const_1[()] = T.int64(30522) for i0, i1 in T.grid(1, 384): with T.block("T_add"): ax0, ax1 = T.axis.remap("SS", [i0, i1]) T.reads(placeholder[ax0, ax1], compile_engine_const_1[()]) T.writes(T_add_1[ax0, ax1]) T_add_1[ax0, ax1] = placeholder[ax0, ax1] + compile_engine_const_1[()] for i0, i1 in T.grid(1, 384): with T.block("T_where"): ax0, ax1 = T.axis.remap("SS", [i0, i1]) T.reads(T_less[ax0, ax1], T_add_1[ax0, ax1], placeholder[ax0, ax1]) T.writes(T_where[ax0, ax1]) T_where[ax0, ax1] = T.Select( T.cast(T_less[ax0, ax1], "int32") != 0, T_add_1[ax0, ax1], placeholder[ax0, ax1] ) for i0, i1, i2 in T.grid(1, 384, 768): with T.block("T_take"): ax0, ax1, ax2 = T.axis.remap("SSS", [i0, i1, i2]) T.reads( placeholder_1[T.min(T.max(T.int64(0), T_where[ax0, ax1]), T.int64(30521)), ax2], T_where[ax0, ax1], ) T.writes(T_take[ax0, ax1, ax2]) T_take[ax0, ax1, ax2] = placeholder_1[ T.min(T.max(T.int64(0), T_where[ax0, ax1]), T.int64(30521)), ax2 ] for i0, i1, i2 in T.grid(1, 384, 768): with T.block("T_add_1"): ax0, ax1, ax2 = T.axis.remap("SSS", [i0, i1, i2]) T.reads(T_take[ax0, ax1, ax2], placeholder_2[ax0, ax1, ax2]) T.writes(T_add[ax0, ax1, ax2]) T_add[ax0, ax1, ax2] = T_take[ax0, ax1, ax2] + placeholder_2[ax0, ax1, ax2] @tvm.script.ir_module class AfterPureSpatial: @T.prim_func def main(placeholder: T.Buffer[(1, 384), "int64"], placeholder_1: T.Buffer[(30522, 768), "float32"], placeholder_2: T.Buffer[(1, 384, 768), "float32"], T_add: T.Buffer[(1, 384, 768), "float32"]) -> None: # function attr dict T.func_attr({"global_symbol": "main", "tir.noalias": True}) # body # with T.block("root") for i0, i1, i2 in T.grid(1, 384, 768): with T.block("T_add_1"): ax0, ax1, ax2 = T.axis.remap("SSS", [i0, i1, i2]) T.reads(placeholder[ax0, ax1], placeholder_1[T.min(T.max(T.int64(0), placeholder[ax0, ax1]), T.int64(30521)) : T.min(T.max(T.int64(0), placeholder[ax0, ax1] + T.int64(30522)), T.int64(30521)) + T.int64(1), ax2], placeholder_2[ax0, ax1, ax2]) T.writes(T_add[ax0, ax1, ax2]) T_add[ax0, ax1, ax2] = placeholder_1[T.min(T.max(T.int64(0), T.Select(T.cast(placeholder[ax0, ax1] < T.int64(0), "int32") != 0, placeholder[ax0, ax1] + T.int64(30522), placeholder[ax0, ax1])), T.int64(30521)), ax2] + placeholder_2[ax0, ax1, ax2] @tvm.script.ir_module class ConstConsumer: @T.prim_func def main(T_full: T.Buffer[(1, 12, 4096), "int64"]) -> None: # function attr dict T.func_attr({"global_symbol": "main", "tir.noalias": True}) # body # with T.block("root") for i0, i1, i2 in T.grid(1, 12, 4096): with T.block("T_full"): ax0, ax1, ax2 = T.axis.remap("SSS", [i0, i1, i2]) T.reads() T.writes(T_full[ax0, ax1, ax2]) T_full[ax0, ax1, ax2] = T.int64(0) @tvm.script.ir_module class Conv2dInt8: @T.prim_func def main(p0: T.Buffer[(16, 14, 14, 256), "int8"], p1: T.Buffer[(1024, 1, 1, 256), "int8"], p2: T.Buffer[(1, 1, 1, 1024), "int32"], p3: T.Buffer[(1, 1, 1, 1024), "int32"], p4: T.Buffer[1024, "int32"], p5: T.Buffer[1024, "int32"], p6: T.Buffer[1024, "int32"], p7: T.Buffer[1, "int32"], p8: T.Buffer[(16, 14, 14, 1024), "int32"], compute: T.Buffer[(16, 14, 14, 1024), "int32"]) -> None: # function attr dict T.func_attr({"global_symbol": "main", "tir.noalias": True}) # body # with T.block("root") compile_engine_const = T.alloc_buffer([], dtype="int32") pad_temp = T.alloc_buffer([16, 14, 14, 256], dtype="int8") conv2d_nhwc = T.alloc_buffer([16, 14, 14, 1024], dtype="int32") T_subtract = T.alloc_buffer([16, 14, 14, 1024], dtype="int32") T_add = T.alloc_buffer([16, 14, 14, 1024], dtype="int32") compute_1 = T.alloc_buffer([16, 14, 14, 1024], dtype="int32") T_add_1 = T.alloc_buffer([16, 14, 14, 1024], dtype="int32") compute_2 = T.alloc_buffer([16, 14, 14, 1024], dtype="int32") T_subtract_1 = T.alloc_buffer([16, 14, 14, 1024], dtype="int32") compute_3 = T.alloc_buffer([16, 14, 14, 1024], dtype="int32") T_add_2 = T.alloc_buffer([16, 14, 14, 1024], dtype="int32") with T.block("compile_engine_const"): vi = T.axis.spatial(1, 0) T.reads() T.writes(compile_engine_const[()]) compile_engine_const[()] = 59 for i0, i1, i2, i3 in T.grid(16, 14, 14, 256): with T.block("pad_temp"): i0_1, i1_1, i2_1, i3_1 = T.axis.remap("SSSS", [i0, i1, i2, i3]) T.reads(p0[i0_1, i1_1, i2_1, i3_1]) T.writes(pad_temp[i0_1, i1_1, i2_1, i3_1]) pad_temp[i0_1, i1_1, i2_1, i3_1] = p0[i0_1, i1_1, i2_1, i3_1] for i0, i1, i2, i3, i4, i5, i6 in T.grid(16, 14, 14, 1024, 1, 1, 256): with T.block("conv2d_nhwc"): nn, yy, xx, ff, ry, rx, rc = T.axis.remap("SSSSRRR", [i0, i1, i2, i3, i4, i5, i6]) T.reads(pad_temp[nn, yy + ry, xx + rx, rc], p1[ff, ry, rx, rc]) T.writes(conv2d_nhwc[nn, yy, xx, ff]) with T.init(): conv2d_nhwc[nn, yy, xx, ff] = 0 conv2d_nhwc[nn, yy, xx, ff] = conv2d_nhwc[nn, yy, xx, ff] + T.cast(pad_temp[nn, yy + ry, xx + rx, rc], "int32") * T.cast(p1[ff, ry, rx, rc], "int32") for i0, i1, i2, i3 in T.grid(16, 14, 14, 1024): with T.block("T_subtract"): ax0, ax1, ax2, ax3 = T.axis.remap("SSSS", [i0, i1, i2, i3]) T.reads(conv2d_nhwc[ax0, ax1, ax2, ax3], p2[0, 0, 0, ax3]) T.writes(T_subtract[ax0, ax1, ax2, ax3]) T_subtract[ax0, ax1, ax2, ax3] = conv2d_nhwc[ax0, ax1, ax2, ax3] - p2[0, 0, 0, ax3] for i0, i1, i2, i3 in T.grid(16, 14, 14, 1024): with T.block("T_add"): ax0, ax1, ax2, ax3 = T.axis.remap("SSSS", [i0, i1, i2, i3]) T.reads(T_subtract[ax0, ax1, ax2, ax3], p3[0, 0, 0, ax3]) T.writes(T_add[ax0, ax1, ax2, ax3]) T_add[ax0, ax1, ax2, ax3] = T_subtract[ax0, ax1, ax2, ax3] + p3[0, 0, 0, ax3] for i0, i1, i2, i3 in T.grid(16, 14, 14, 1024): with T.block("compute"): i0_2, i1_2, i2_2, i3_2 = T.axis.remap("SSSS", [i0, i1, i2, i3]) T.reads(T_add[i0_2, i1_2, i2_2, i3_2], p4[i3_2], p5[i3_2], p6[i3_2]) T.writes(compute_1[i0_2, i1_2, i2_2, i3_2]) compute_1[i0_2, i1_2, i2_2, i3_2] = T.q_multiply_shift_per_axis(T_add[i0_2, i1_2, i2_2, i3_2], p4[i3_2], p5[i3_2], p6[i3_2], 31, False, True, dtype="int32") for i0_3, i1_3, i2_3, i3_3 in T.grid(16, 14, 14, 1024): with T.block("T_add_1"): ax0, ax1, ax2, ax3 = T.axis.remap("SSSS", [i0_3, i1_3, i2_3, i3_3]) T.reads(compile_engine_const[()], compute_1[ax0, ax1, ax2, ax3]) T.writes(T_add_1[ax0, ax1, ax2, ax3]) T_add_1[ax0, ax1, ax2, ax3] = compile_engine_const[()] + compute_1[ax0, ax1, ax2, ax3] for i0_4, i1_4, i2_4, i3_4 in T.grid(16, 14, 14, 1024): with T.block("compute_1"): i0_5, i1_5, i2_5, i3_5 = T.axis.remap("SSSS", [i0_4, i1_4, i2_4, i3_4]) T.reads(T_add_1[i0_5, i1_5, i2_5, i3_5]) T.writes(compute_2[i0_5, i1_5, i2_5, i3_5]) compute_2[i0_5, i1_5, i2_5, i3_5] = T.max(T.min(T_add_1[i0_5, i1_5, i2_5, i3_5], 255), 0) for i0_6, i1_6, i2_6, i3_6 in T.grid(16, 14, 14, 1024): with T.block("T_subtract_1"): ax0, ax1, ax2, ax3 = T.axis.remap("SSSS", [i0_6, i1_6, i2_6, i3_6]) T.reads(compute_2[ax0, ax1, ax2, ax3], p7[0]) T.writes(T_subtract_1[ax0, ax1, ax2, ax3]) T_subtract_1[ax0, ax1, ax2, ax3] = compute_2[ax0, ax1, ax2, ax3] - p7[0] for i0_7, i1_7, i2_7, i3_7 in T.grid(16, 14, 14, 1024): with T.block("compute_2"): i0_8, i1_8, i2_8, i3_8 = T.axis.remap("SSSS", [i0_7, i1_7, i2_7, i3_7]) T.reads(T_subtract_1[i0_8, i1_8, i2_8, i3_8]) T.writes(compute_3[i0_8, i1_8, i2_8, i3_8]) compute_3[i0_8, i1_8, i2_8, i3_8] = T.q_multiply_shift(T_subtract_1[i0_8, i1_8, i2_8, i3_8], 1408572815, 31, 1, dtype="int32") for i0_9, i1_9, i2_9, i3_9 in T.grid(16, 14, 14, 1024): with T.block("T_add_2"): ax0, ax1, ax2, ax3 = T.axis.remap("SSSS", [i0_9, i1_9, i2_9, i3_9]) T.reads(compute_3[ax0, ax1, ax2, ax3], p8[ax0, ax1, ax2, ax3]) T.writes(T_add_2[ax0, ax1, ax2, ax3]) T_add_2[ax0, ax1, ax2, ax3] = compute_3[ax0, ax1, ax2, ax3] + p8[ax0, ax1, ax2, ax3] for i0_10, i1_10, i2_10, i3_10 in T.grid(16, 14, 14, 1024): with T.block("compute_3"): i0_11, i1_11, i2_11, i3_11 = T.axis.remap("SSSS", [i0_10, i1_10, i2_10, i3_10]) T.reads(T_add_2[i0_11, i1_11, i2_11, i3_11]) T.writes(compute[i0_11, i1_11, i2_11, i3_11]) compute[i0_11, i1_11, i2_11, i3_11] = T.max(T.min(T_add_2[i0_11, i1_11, i2_11, i3_11], 255), 0) # pylint: enable=no-member,invalid-name,unused-variable,no-self-argument,line-too-long,chained-comparison,not-callable,too-many-nested-blocks # fmt: on def test_inline_consumer_chain(): mod = Conv2DBiasBnReLU target = Target("llvm") (space,) = generate_design_space( kind="llvm", mod=mod, target=target, types=ms.schedule_rule.AutoInline, ) tvm.ir.assert_structural_equal(lhs=space.mod, rhs=Conv2DBiasBnReLUInlined) def test_inline_into_cache(): mod = MultiLevelTiledConv2D target = Target("cuda", host="llvm") (space,) = generate_design_space( kind="cuda", mod=mod, target=target, types=ms.schedule_rule.AutoInline, ) tvm.ir.assert_structural_equal(lhs=space.mod, rhs=MultiLevelTiledConv2DAfterInline) def test_inline_into_multiple_consumers(): mod = SoftmaxBeforeInline target = Target("cuda", host="llvm") (space,) = generate_design_space( kind="cuda", mod=mod, target=target, types=ms.schedule_rule.AutoInline, ) tvm.ir.assert_structural_equal(lhs=space.mod, rhs=SoftmaxAfterInline) def test_inline_pure_spatial(): mod = BeforePureSpatial target = Target("llvm") (space,) = generate_design_space( kind="llvm", mod=mod, target=target, types=ms.schedule_rule.AutoInline, ) tvm.ir.assert_structural_equal(lhs=space.mod, rhs=AfterPureSpatial) def test_inline_constant_tensor(): mod = ConstConsumer target = Target("cuda", host="llvm") (space,) = generate_design_space( kind="cuda", mod=mod, target=target, types=ms.schedule_rule.AutoInline, ) tvm.ir.assert_structural_equal(lhs=space.mod, rhs=ConstConsumer) def test_conv2d_int8_inline_constant_scalars(): sch = Schedule(Conv2dInt8) conv2d = sch.get_block("conv2d_nhwc") sch.cache_write(conv2d, 0, "shared") with pytest.raises(tvm.tir.ScheduleError) as e: sch.reverse_compute_inline(sch.get_block("T_add_1")) err_msg = "The block is only allowed to read a single buffer region, but it reads 2 region(s)" assert err_msg in str(e) ms.schedule_rule.InlineConstantScalars().apply(sch, sch.get_block("compile_engine_const")) sch.reverse_compute_inline(sch.get_block("T_add_1")) if __name__ == "__main__": test_inline_consumer_chain() test_inline_into_cache() test_inline_into_multiple_consumers() test_inline_pure_spatial() test_inline_constant_tensor() test_conv2d_int8_inline_constant_scalars()
https://github.com/zk-ml/tachikoma
tests/python/unittest/test_meta_schedule_schedule_rule_cross_thread_reduction.py
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. # pylint: disable=missing-module-docstring,missing-function-docstring,missing-class-docstring import tvm from tvm import meta_schedule as ms from tvm.meta_schedule.testing import te_workload from tvm.meta_schedule.testing.space_generation import ( check_sketches, generate_design_space, ) from tvm.script import tir as T from tvm.target import Target from tvm.te import create_prim_func @tvm.script.ir_module class Softmax_mn_after_inline: @T.prim_func def main( A: T.Buffer[(256, 256), "float32"], T_softmax_norm: T.Buffer[(256, 256), "float32"] ) -> None: T_softmax_maxelem = T.alloc_buffer([256], dtype="float32") T_softmax_expsum = T.alloc_buffer([256], dtype="float32") for i0, i1 in T.grid(256, 256): with T.block("T_softmax_maxelem"): i0_1, k = T.axis.remap("SR", [i0, i1]) with T.init(): T_softmax_maxelem[i0_1] = T.min_value("float32") T_softmax_maxelem[i0_1] = T.max(T_softmax_maxelem[i0_1], A[i0_1, k]) for i0, i1 in T.grid(256, 256): with T.block("T_softmax_expsum"): i0_2, k = T.axis.remap("SR", [i0, i1]) with T.init(): T_softmax_expsum[i0_2] = T.float32(0) T_softmax_expsum[i0_2] = T_softmax_expsum[i0_2] + T.exp( A[i0_2, k] - T_softmax_maxelem[i0_2], dtype="float32" ) for i0_3, i1 in T.grid(256, 256): with T.block("T_softmax_norm"): i0_4, i1_1 = T.axis.remap("SS", [i0_3, i1]) T.block_attr({"axis": 1}) T_softmax_norm[i0_4, i1_1] = ( T.exp(A[i0_4, i1_1] - T_softmax_maxelem[i0_4], dtype="float32") / T_softmax_expsum[i0_4] ) def test_gpu_softmax_mn(): @T.prim_func def softmax_mn_0( A: T.Buffer[(256, 256), "float32"], T_softmax_norm: T.Buffer[(256, 256), "float32"], ) -> None: # function attr dict T.func_attr({"global_symbol": "main", "tir.noalias": True}) # body # with T.block("root") T_softmax_maxelem = T.alloc_buffer([256], dtype="float32") T_softmax_exp = T.alloc_buffer([256, 256], dtype="float32") T_softmax_expsum = T.alloc_buffer([256], dtype="float32") for i0, i1 in T.grid(256, 256): with T.block("T_softmax_maxelem"): i0_1, k = T.axis.remap("SR", [i0, i1]) T.reads(A[i0_1, k]) T.writes(T_softmax_maxelem[i0_1]) with T.init(): T_softmax_maxelem[i0_1] = T.float32(-3.4028234663852886e38) T_softmax_maxelem[i0_1] = T.max(T_softmax_maxelem[i0_1], A[i0_1, k]) for i0, i1 in T.grid(256, 256): with T.block("T_softmax_exp"): i0_2, i1_1 = T.axis.remap("SS", [i0, i1]) T.reads(A[i0_2, i1_1], T_softmax_maxelem[i0_2]) T.writes(T_softmax_exp[i0_2, i1_1]) T_softmax_exp[i0_2, i1_1] = T.exp( A[i0_2, i1_1] - T_softmax_maxelem[i0_2], dtype="float32" ) for i0_3, i1 in T.grid(256, 256): with T.block("T_softmax_expsum"): i0_4, k = T.axis.remap("SR", [i0_3, i1]) T.reads(T_softmax_exp[i0_4, k]) T.writes(T_softmax_expsum[i0_4]) with T.init(): T_softmax_expsum[i0_4] = T.float32(0) T_softmax_expsum[i0_4] = T_softmax_expsum[i0_4] + T_softmax_exp[i0_4, k] for i0_5, i1 in T.grid(256, 256): with T.block("T_softmax_norm"): i0_6, i1_2 = T.axis.remap("SS", [i0_5, i1]) T.reads(T_softmax_exp[i0_6, i1_2], T_softmax_expsum[i0_6]) T.writes(T_softmax_norm[i0_6, i1_2]) T.block_attr({"axis": 1}) T_softmax_norm[i0_6, i1_2] = T_softmax_exp[i0_6, i1_2] / T_softmax_expsum[i0_6] @T.prim_func def softmax_mn_1( A: T.Buffer[(256, 256), "float32"], T_softmax_norm: T.Buffer[(256, 256), "float32"] ) -> None: # function attr dict T.func_attr({"global_symbol": "main", "tir.noalias": True}) # body # with T.block("root") T_softmax_maxelem_shared = T.alloc_buffer([256], dtype="float32", scope="shared") T_softmax_exp = T.alloc_buffer([256, 256], dtype="float32") T_softmax_expsum = T.alloc_buffer([256], dtype="float32") for i0 in T.serial(256): for ax0, ax1_0 in T.grid(1, 1): for ax1_1 in T.thread_binding(512, thread="threadIdx.x"): with T.block("T_softmax_maxelem"): T.where(ax1_0 * 512 + ax1_1 < 256) i0_1 = T.axis.spatial(256, ax0 + i0) k = T.axis.reduce(256, ax1_0 * 512 + ax1_1) T.reads(A[i0_1, k]) T.writes(T_softmax_maxelem_shared[i0_1]) with T.init(): T_softmax_maxelem_shared[i0_1] = T.float32(-3.4028234663852886e38) T_softmax_maxelem_shared[i0_1] = T.max( T_softmax_maxelem_shared[i0_1], A[i0_1, k] ) for i1_0 in T.serial(1): for i1_1 in T.thread_binding(512, thread="threadIdx.x"): with T.block("T_softmax_exp"): T.where(i1_0 * 512 + i1_1 < 256) i0_2 = T.axis.spatial(256, i0) i1 = T.axis.spatial(256, i1_0 * 512 + i1_1) T.reads(A[i0_2, i1], T_softmax_maxelem_shared[i0_2]) T.writes(T_softmax_exp[i0_2, i1]) T_softmax_exp[i0_2, i1] = T.exp( A[i0_2, i1] - T_softmax_maxelem_shared[i0_2], dtype="float32" ) for i0_3, i1 in T.grid(256, 256): with T.block("T_softmax_expsum"): i0_4, k = T.axis.remap("SR", [i0_3, i1]) T.reads(T_softmax_exp[i0_4, k]) T.writes(T_softmax_expsum[i0_4]) with T.init(): T_softmax_expsum[i0_4] = T.float32(0) T_softmax_expsum[i0_4] = T_softmax_expsum[i0_4] + T_softmax_exp[i0_4, k] for i0_5, i1 in T.grid(256, 256): with T.block("T_softmax_norm"): i0_6, i1_2 = T.axis.remap("SS", [i0_5, i1]) T.reads(T_softmax_exp[i0_6, i1_2], T_softmax_expsum[i0_6]) T.writes(T_softmax_norm[i0_6, i1_2]) T.block_attr({"axis": 1}) T_softmax_norm[i0_6, i1_2] = T_softmax_exp[i0_6, i1_2] / T_softmax_expsum[i0_6] @T.prim_func def softmax_mn_2( A: T.Buffer[(256, 256), "float32"], T_softmax_norm: T.Buffer[(256, 256), "float32"] ) -> None: # function attr dict T.func_attr({"global_symbol": "main", "tir.noalias": True}) # body # with T.block("root") T_softmax_maxelem = T.alloc_buffer([256], dtype="float32") T_softmax_exp = T.alloc_buffer([256, 256], dtype="float32") T_softmax_expsum_shared = T.alloc_buffer([256], dtype="float32", scope="shared") for i0, i1 in T.grid(256, 256): with T.block("T_softmax_maxelem"): i0_1, k = T.axis.remap("SR", [i0, i1]) T.reads(A[i0_1, k]) T.writes(T_softmax_maxelem[i0_1]) with T.init(): T_softmax_maxelem[i0_1] = T.float32(-3.4028234663852886e38) T_softmax_maxelem[i0_1] = T.max(T_softmax_maxelem[i0_1], A[i0_1, k]) for i0, i1 in T.grid(256, 256): with T.block("T_softmax_exp"): i0_2, i1_1 = T.axis.remap("SS", [i0, i1]) T.reads(A[i0_2, i1_1], T_softmax_maxelem[i0_2]) T.writes(T_softmax_exp[i0_2, i1_1]) T_softmax_exp[i0_2, i1_1] = T.exp( A[i0_2, i1_1] - T_softmax_maxelem[i0_2], dtype="float32" ) for i0_3 in T.serial(256): for ax0, ax1_0 in T.grid(1, 32): for ax1_1 in T.thread_binding(8, thread="threadIdx.x"): with T.block("T_softmax_expsum"): i0_4 = T.axis.spatial(256, ax0 + i0_3) k = T.axis.reduce(256, ax1_0 * 8 + ax1_1) T.reads(T_softmax_exp[i0_4, k]) T.writes(T_softmax_expsum_shared[i0_4]) with T.init(): T_softmax_expsum_shared[i0_4] = T.float32(0) T_softmax_expsum_shared[i0_4] = ( T_softmax_expsum_shared[i0_4] + T_softmax_exp[i0_4, k] ) for i1_0 in T.serial(32): for i1_1_1 in T.thread_binding(8, thread="threadIdx.x"): with T.block("T_softmax_norm"): i0_5 = T.axis.spatial(256, i0_3) i1 = T.axis.spatial(256, i1_0 * 8 + i1_1_1) T.reads(T_softmax_exp[i0_5, i1], T_softmax_expsum_shared[i0_5]) T.writes(T_softmax_norm[i0_5, i1]) T.block_attr({"axis": 1}) T_softmax_norm[i0_5, i1] = ( T_softmax_exp[i0_5, i1] / T_softmax_expsum_shared[i0_5] ) @T.prim_func def softmax_mn_3( A: T.Buffer[(256, 256), "float32"], T_softmax_norm: T.Buffer[(256, 256), "float32"] ) -> None: # function attr dict T.func_attr({"global_symbol": "main", "tir.noalias": True}) # body # with T.block("root") T_softmax_maxelem_shared = T.alloc_buffer([256], dtype="float32", scope="shared") T_softmax_exp = T.alloc_buffer([256, 256], dtype="float32") T_softmax_expsum_shared = T.alloc_buffer([256], dtype="float32", scope="shared") for i0 in T.serial(256): for ax0, ax1_0 in T.grid(1, 1): for ax1_1 in T.thread_binding(512, thread="threadIdx.x"): with T.block("T_softmax_maxelem"): T.where(ax1_0 * 512 + ax1_1 < 256) i0_1 = T.axis.spatial(256, ax0 + i0) k = T.axis.reduce(256, ax1_0 * 512 + ax1_1) T.reads(A[i0_1, k]) T.writes(T_softmax_maxelem_shared[i0_1]) with T.init(): T_softmax_maxelem_shared[i0_1] = T.float32(-3.4028234663852886e38) T_softmax_maxelem_shared[i0_1] = T.max( T_softmax_maxelem_shared[i0_1], A[i0_1, k] ) for i1_0 in T.serial(1): for i1_1 in T.thread_binding(512, thread="threadIdx.x"): with T.block("T_softmax_exp"): T.where(i1_0 * 512 + i1_1 < 256) i0_2 = T.axis.spatial(256, i0) i1 = T.axis.spatial(256, i1_0 * 512 + i1_1) T.reads(A[i0_2, i1], T_softmax_maxelem_shared[i0_2]) T.writes(T_softmax_exp[i0_2, i1]) T_softmax_exp[i0_2, i1] = T.exp( A[i0_2, i1] - T_softmax_maxelem_shared[i0_2], dtype="float32" ) for i0_3 in T.serial(256): for ax0, ax1_0 in T.grid(1, 32): for ax1_1 in T.thread_binding(8, thread="threadIdx.x"): with T.block("T_softmax_expsum"): i0_4 = T.axis.spatial(256, ax0 + i0_3) k = T.axis.reduce(256, ax1_0 * 8 + ax1_1) T.reads(T_softmax_exp[i0_4, k]) T.writes(T_softmax_expsum_shared[i0_4]) with T.init(): T_softmax_expsum_shared[i0_4] = T.float32(0) T_softmax_expsum_shared[i0_4] = ( T_softmax_expsum_shared[i0_4] + T_softmax_exp[i0_4, k] ) for i1_0 in T.serial(32): for i1_1 in T.thread_binding(8, thread="threadIdx.x"): with T.block("T_softmax_norm"): i0_5 = T.axis.spatial(256, i0_3) i1 = T.axis.spatial(256, i1_0 * 8 + i1_1) T.reads(T_softmax_exp[i0_5, i1], T_softmax_expsum_shared[i0_5]) T.writes(T_softmax_norm[i0_5, i1]) T.block_attr({"axis": 1}) T_softmax_norm[i0_5, i1] = ( T_softmax_exp[i0_5, i1] / T_softmax_expsum_shared[i0_5] ) decision_0 = [] # type: ignore decision_1 = [ ("SampleCategorical", 7), ] decision_2 = [ ("SampleCategorical", 1), ] decision_3 = [ ("SampleCategorical", 1), ("SampleCategorical", 7), ] mod = create_prim_func(te_workload.softmax_mn(n=256, m=256)) actual = generate_design_space( kind="cuda", mod=mod, target=Target("nvidia/geforce-rtx-3090", host="llvm"), types=ms.schedule_rule.CrossThreadReduction, ) check_sketches( mod, sketches=actual, expected_mods=[softmax_mn_0, softmax_mn_1, softmax_mn_2, softmax_mn_3], expected_decisions=[decision_0, decision_1, decision_2, decision_3], ) def test_gpu_softmax_mn_after_inline(): @T.prim_func def softmax_mn_after_inline_0( A: T.Buffer[(256, 256), "float32"], T_softmax_norm: T.Buffer[(256, 256), "float32"] ) -> None: T_softmax_maxelem = T.alloc_buffer([256], dtype="float32") T_softmax_expsum = T.alloc_buffer([256], dtype="float32") for i0, i1 in T.grid(256, 256): with T.block("T_softmax_maxelem"): i0_1, k = T.axis.remap("SR", [i0, i1]) T.reads(A[i0_1, k]) T.writes(T_softmax_maxelem[i0_1]) with T.init(): T_softmax_maxelem[i0_1] = T.float32(-3.4028234663852886e38) T_softmax_maxelem[i0_1] = T.max(T_softmax_maxelem[i0_1], A[i0_1, k]) for i0, i1 in T.grid(256, 256): with T.block("T_softmax_expsum"): i0_2, k = T.axis.remap("SR", [i0, i1]) T.reads(A[i0_2, k], T_softmax_maxelem[i0_2]) T.writes(T_softmax_expsum[i0_2]) with T.init(): T_softmax_expsum[i0_2] = T.float32(0) T_softmax_expsum[i0_2] = T_softmax_expsum[i0_2] + T.exp( A[i0_2, k] - T_softmax_maxelem[i0_2], dtype="float32" ) for i0_3, i1 in T.grid(256, 256): with T.block("T_softmax_norm"): i0_4, i1_1 = T.axis.remap("SS", [i0_3, i1]) T.reads(A[i0_4, i1_1], T_softmax_maxelem[i0_4], T_softmax_expsum[i0_4]) T.writes(T_softmax_norm[i0_4, i1_1]) T.block_attr({"axis": 1}) T_softmax_norm[i0_4, i1_1] = ( T.exp(A[i0_4, i1_1] - T_softmax_maxelem[i0_4], dtype="float32") / T_softmax_expsum[i0_4] ) @T.prim_func def softmax_mn_after_inline_1( A: T.Buffer[(256, 256), "float32"], T_softmax_norm: T.Buffer[(256, 256), "float32"] ) -> None: T_softmax_maxelem = T.alloc_buffer([256], dtype="float32") T_softmax_expsum = T.alloc_buffer([256], dtype="float32") for i0, i1_0 in T.grid(256, 4): for i1_1 in T.thread_binding(64, thread="threadIdx.x"): with T.block("T_softmax_maxelem"): i0_1 = T.axis.spatial(256, i0) k = T.axis.reduce(256, i1_0 * 64 + i1_1) T.reads(A[i0_1, k]) T.writes(T_softmax_maxelem[i0_1]) with T.init(): T_softmax_maxelem[i0_1] = T.float32(-3.4028234663852886e38) T_softmax_maxelem[i0_1] = T.max(T_softmax_maxelem[i0_1], A[i0_1, k]) for i0, i1 in T.grid(256, 256): with T.block("T_softmax_expsum"): i0_2, k = T.axis.remap("SR", [i0, i1]) T.reads(A[i0_2, k], T_softmax_maxelem[i0_2]) T.writes(T_softmax_expsum[i0_2]) with T.init(): T_softmax_expsum[i0_2] = T.float32(0) T_softmax_expsum[i0_2] = T_softmax_expsum[i0_2] + T.exp( A[i0_2, k] - T_softmax_maxelem[i0_2], dtype="float32" ) for i0_3, i1 in T.grid(256, 256): with T.block("T_softmax_norm"): i0_4, i1_1 = T.axis.remap("SS", [i0_3, i1]) T.reads(A[i0_4, i1_1], T_softmax_maxelem[i0_4], T_softmax_expsum[i0_4]) T.writes(T_softmax_norm[i0_4, i1_1]) T.block_attr({"axis": 1}) T_softmax_norm[i0_4, i1_1] = ( T.exp(A[i0_4, i1_1] - T_softmax_maxelem[i0_4], dtype="float32") / T_softmax_expsum[i0_4] ) @T.prim_func def softmax_mn_after_inline_2( A: T.Buffer[(256, 256), "float32"], T_softmax_norm: T.Buffer[(256, 256), "float32"] ) -> None: T_softmax_maxelem = T.alloc_buffer([256], dtype="float32") T_softmax_expsum_shared = T.alloc_buffer([256], dtype="float32", scope="shared") for i0, i1 in T.grid(256, 256): with T.block("T_softmax_maxelem"): i0_1, k = T.axis.remap("SR", [i0, i1]) T.reads(A[i0_1, k]) T.writes(T_softmax_maxelem[i0_1]) with T.init(): T_softmax_maxelem[i0_1] = T.float32(-3.4028234663852886e38) T_softmax_maxelem[i0_1] = T.max(T_softmax_maxelem[i0_1], A[i0_1, k]) for i0_3 in T.serial(256): for ax0, ax1_0 in T.grid(1, 1): for ax1_1 in T.thread_binding(512, thread="threadIdx.x"): with T.block("T_softmax_expsum"): T.where(ax1_0 * 512 + ax1_1 < 256) i0_2 = T.axis.spatial(256, ax0 + i0_3) k = T.axis.reduce(256, ax1_0 * 512 + ax1_1) T.reads(A[i0_2, k], T_softmax_maxelem[i0_2]) T.writes(T_softmax_expsum_shared[i0_2]) with T.init(): T_softmax_expsum_shared[i0_2] = T.float32(0) T_softmax_expsum_shared[i0_2] = T_softmax_expsum_shared[i0_2] + T.exp( A[i0_2, k] - T_softmax_maxelem[i0_2], dtype="float32" ) for i1_0 in T.serial(1): for i1_1 in T.thread_binding(512, thread="threadIdx.x"): with T.block("T_softmax_norm"): T.where(i1_0 * 512 + i1_1 < 256) i0_4 = T.axis.spatial(256, i0_3) i1_1_1 = T.axis.spatial(256, i1_0 * 512 + i1_1) T.reads( A[i0_4, i1_1_1], T_softmax_maxelem[i0_4], T_softmax_expsum_shared[i0_4] ) T.writes(T_softmax_norm[i0_4, i1_1_1]) T.block_attr({"axis": 1}) T_softmax_norm[i0_4, i1_1_1] = ( T.exp(A[i0_4, i1_1_1] - T_softmax_maxelem[i0_4], dtype="float32") / T_softmax_expsum_shared[i0_4] ) @T.prim_func def softmax_mn_after_inline_3( A: T.Buffer[(256, 256), "float32"], T_softmax_norm: T.Buffer[(256, 256), "float32"] ) -> None: T_softmax_maxelem_shared = T.alloc_buffer([256], dtype="float32", scope="shared") T_softmax_expsum_shared = T.alloc_buffer([256], dtype="float32", scope="shared") for i0_3 in T.serial(256): for ax0, ax1_0 in T.grid(1, 1): for ax1_1 in T.thread_binding(512, thread="threadIdx.x"): with T.block("T_softmax_maxelem"): T.where(ax1_0 * 512 + ax1_1 < 256) i0_1 = T.axis.spatial(256, ax0 + i0_3) k = T.axis.reduce(256, ax1_0 * 512 + ax1_1) T.reads(A[i0_1, k]) T.writes(T_softmax_maxelem_shared[i0_1]) with T.init(): T_softmax_maxelem_shared[i0_1] = T.float32(-3.4028234663852886e38) T_softmax_maxelem_shared[i0_1] = T.max( T_softmax_maxelem_shared[i0_1], A[i0_1, k] ) for ax0, ax1_0 in T.grid(1, 1): for ax1_1 in T.thread_binding(512, thread="threadIdx.x"): with T.block("T_softmax_expsum"): T.where(ax1_0 * 512 + ax1_1 < 256) i0_2 = T.axis.spatial(256, ax0 + i0_3) k = T.axis.reduce(256, ax1_0 * 512 + ax1_1) T.reads(A[i0_2, k], T_softmax_maxelem_shared[i0_2]) T.writes(T_softmax_expsum_shared[i0_2]) with T.init(): T_softmax_expsum_shared[i0_2] = T.float32(0) T_softmax_expsum_shared[i0_2] = T_softmax_expsum_shared[i0_2] + T.exp( A[i0_2, k] - T_softmax_maxelem_shared[i0_2], dtype="float32" ) for i1_0 in T.serial(1): for i1_1 in T.thread_binding(512, thread="threadIdx.x"): with T.block("T_softmax_norm"): T.where(i1_0 * 512 + i1_1 < 256) i0_4 = T.axis.spatial(256, i0_3) i1_1_1 = T.axis.spatial(256, i1_0 * 512 + i1_1) T.reads( A[i0_4, i1_1_1], T_softmax_maxelem_shared[i0_4], T_softmax_expsum_shared[i0_4], ) T.writes(T_softmax_norm[i0_4, i1_1_1]) T.block_attr({"axis": 1}) T_softmax_norm[i0_4, i1_1_1] = ( T.exp(A[i0_4, i1_1_1] - T_softmax_maxelem_shared[i0_4], dtype="float32") / T_softmax_expsum_shared[i0_4] ) decision_0 = [] # type: ignore decision_1 = [ ("SampleCategorical", 4), ] decision_2 = [ ("SampleCategorical", 7), ] decision_3 = [ ("SampleCategorical", 7), ("SampleCategorical", 0), ] mod = Softmax_mn_after_inline actual = generate_design_space( kind="cuda", mod=mod, target=Target("nvidia/geforce-rtx-3090", host="llvm"), types=ms.schedule_rule.CrossThreadReduction, ) check_sketches( mod, sketches=actual, expected_mods=[ softmax_mn_after_inline_0, softmax_mn_after_inline_1, softmax_mn_after_inline_2, softmax_mn_after_inline_3, ], expected_decisions=[decision_0, decision_1, decision_2, decision_3], ) def test_gpu_batch_norm_bmn(): @T.prim_func def batch_norm_bmn_0(A: T.Buffer[(1, 512, 512), "float32"], D: T.Buffer[1, "float32"]) -> None: # function attr dict T.func_attr({"global_symbol": "main", "tir.noalias": True}) # body # with T.block("root") C = T.alloc_buffer([1], dtype="float32") for i0, i1, i2 in T.grid(1, 512, 512): with T.block("C"): b, i, j = T.axis.remap("SRR", [i0, i1, i2]) T.reads(A[b, i, j]) T.writes(C[b]) with T.init(): C[b] = T.float32(0) C[b] = C[b] + A[b, i, j] * A[b, i, j] for i0 in T.serial(1): with T.block("D"): b = T.axis.spatial(1, i0) T.reads(C[b]) T.writes(D[b]) D[b] = T.sqrt(C[b], dtype="float32") @T.prim_func def batch_norm_bmn_1(A: T.Buffer[(1, 512, 512), "float32"], D: T.Buffer[1, "float32"]) -> None: # function attr dict T.func_attr({"global_symbol": "main", "tir.noalias": True}) # body # with T.block("root") C_shared = T.alloc_buffer([1], dtype="float32", scope="shared") for i0_0 in T.serial(1): for ax0, ax1_ax2_fused_0 in T.grid(1, 1024): for ax1_ax2_fused_1 in T.thread_binding(256, thread="threadIdx.x"): with T.block("C"): b = T.axis.spatial(1, ax0) i = T.axis.reduce(512, (ax1_ax2_fused_0 * 256 + ax1_ax2_fused_1) // 512) j = T.axis.reduce(512, (ax1_ax2_fused_0 * 256 + ax1_ax2_fused_1) % 512) T.reads(A[b, i, j]) T.writes(C_shared[b]) with T.init(): C_shared[b] = T.float32(0) C_shared[b] = C_shared[b] + A[b, i, j] * A[b, i, j] for i0_1 in T.thread_binding(256, thread="threadIdx.x"): with T.block("D"): T.where(i0_0 * 256 + i0_1 < 1) b = T.axis.spatial(1, i0_0 * 256 + i0_1) T.reads(C_shared[b]) T.writes(D[b]) D[b] = T.sqrt(C_shared[b], dtype="float32") decision_0 = [] # type: ignore decision_1 = [ ("SampleCategorical", 6), ] mod = create_prim_func(te_workload.norm_bmn(B=1, M=512, N=512)) actual = generate_design_space( kind="cuda", mod=mod, target=Target("nvidia/geforce-rtx-3090", host="llvm"), types=ms.schedule_rule.CrossThreadReduction, ) check_sketches( mod, sketches=actual, expected_mods=[batch_norm_bmn_0, batch_norm_bmn_1], expected_decisions=[decision_0, decision_1], ) @T.prim_func def argmax( idx: T.Buffer[(128, 128), "int32"], val: T.Buffer[(128, 128), "float32"], argmax_v0: T.Buffer[(128,), "int32"], argmax_v1: T.Buffer[(128,), "float32"], ) -> None: for i0, i1 in T.grid(128, 128): with T.block("argmax"): i = T.axis.spatial(128, i0) k = T.axis.reduce(128, i1) T.reads(idx[i, k], val[i, k]) T.writes(argmax_v0[i], argmax_v1[i]) with T.init(): argmax_v0[i] = -1 argmax_v1[i] = T.min_value("float32") v_argmax_v0: T.int32 = T.Select(argmax_v1[i] >= val[i, k], argmax_v0[i], idx[i, k]) v_argmax_v1: T.float32 = T.Select(argmax_v1[i] >= val[i, k], argmax_v1[i], val[i, k]) argmax_v0[i] = v_argmax_v0 argmax_v1[i] = v_argmax_v1 @T.prim_func def argmax_32( idx: T.Buffer[(1, 32), "int32"], val: T.Buffer[(1, 32), "float32"], argmax_v0: T.Buffer[(1,), "int32"], argmax_v1: T.Buffer[(1,), "float32"], ) -> None: for i0, i1 in T.grid(1, 32): with T.block("argmax"): i = T.axis.spatial(1, i0) k = T.axis.reduce(32, i1) T.reads(idx[i, k], val[i, k]) T.writes(argmax_v0[i], argmax_v1[i]) with T.init(): argmax_v0[i] = -1 argmax_v1[i] = T.min_value("float32") v_argmax_v0: T.int32 = T.Select(argmax_v1[i] >= val[i, k], argmax_v0[i], idx[i, k]) v_argmax_v1: T.float32 = T.Select(argmax_v1[i] >= val[i, k], argmax_v1[i], val[i, k]) argmax_v0[i] = v_argmax_v0 argmax_v1[i] = v_argmax_v1 def test_gpu_argmax(): @T.prim_func def argmax_0( idx: T.Buffer[(128, 128), "int32"], val: T.Buffer[(128, 128), "float32"], argmax_v0: T.Buffer[128, "int32"], argmax_v1: T.Buffer[128, "float32"], ) -> None: # body # with T.block("root") for i0, i1 in T.grid(128, 128): with T.block("argmax"): i, k = T.axis.remap("SR", [i0, i1]) T.reads(idx[i, k], val[i, k]) T.writes(argmax_v0[i], argmax_v1[i]) with T.init(): argmax_v0[i] = -1 argmax_v1[i] = T.float32(-3.4028234663852886e38) v_argmax_v0: T.int32 = T.Select(argmax_v1[i] >= val[i, k], argmax_v0[i], idx[i, k]) v_argmax_v1: T.float32 = T.Select( argmax_v1[i] >= val[i, k], argmax_v1[i], val[i, k] ) argmax_v0[i] = v_argmax_v0 argmax_v1[i] = v_argmax_v1 @T.prim_func def argmax_1( idx: T.Buffer[(128, 128), "int32"], val: T.Buffer[(128, 128), "float32"], argmax_v0: T.Buffer[128, "int32"], argmax_v1: T.Buffer[128, "float32"], ) -> None: # body # with T.block("root") for i0, i1_0 in T.grid(128, 2): for i1_1 in T.thread_binding(64, thread="threadIdx.x"): with T.block("argmax"): i = T.axis.spatial(128, i0) k = T.axis.reduce(128, i1_0 * 64 + i1_1) T.reads(idx[i, k], val[i, k]) T.writes(argmax_v0[i], argmax_v1[i]) with T.init(): argmax_v0[i] = -1 argmax_v1[i] = T.float32(-3.4028234663852886e38) v_argmax_v0: T.int32 = T.Select( argmax_v1[i] >= val[i, k], argmax_v0[i], idx[i, k] ) v_argmax_v1: T.float32 = T.Select( argmax_v1[i] >= val[i, k], argmax_v1[i], val[i, k] ) argmax_v0[i] = v_argmax_v0 argmax_v1[i] = v_argmax_v1 decision_0 = [] # type: ignore decision_1 = [ ("SampleCategorical", 4), ] mod = argmax actual = generate_design_space( kind="cuda", mod=mod, target=Target("nvidia/geforce-rtx-3090", host="llvm"), types=ms.schedule_rule.CrossThreadReduction, ) check_sketches( mod, sketches=actual, expected_mods=[argmax_0, argmax_1], expected_decisions=[decision_0, decision_1], ) def test_gpu_argmax_32(): @T.prim_func def argmax_0( idx: T.Buffer[(1, 32), "int32"], val: T.Buffer[(1, 32), "float32"], argmax_v0: T.Buffer[(1,), "int32"], argmax_v1: T.Buffer[(1,), "float32"], ) -> None: # body # with T.block("root") for i0, i1 in T.grid(1, 32): with T.block("argmax"): i, k = T.axis.remap("SR", [i0, i1]) T.reads(idx[i, k], val[i, k]) T.writes(argmax_v0[i], argmax_v1[i]) with T.init(): argmax_v0[i] = -1 argmax_v1[i] = T.float32(-3.4028234663852886e38) v_argmax_v0: T.int32 = T.Select(argmax_v1[i] >= val[i, k], argmax_v0[i], idx[i, k]) v_argmax_v1: T.float32 = T.Select( argmax_v1[i] >= val[i, k], argmax_v1[i], val[i, k] ) argmax_v0[i] = v_argmax_v0 argmax_v1[i] = v_argmax_v1 @T.prim_func def argmax_1( idx: T.Buffer[(1, 32), "int32"], val: T.Buffer[(1, 32), "float32"], argmax_v0: T.Buffer[(1,), "int32"], argmax_v1: T.Buffer[(1,), "float32"], ) -> None: # body # with T.block("root") for i0, i1_0 in T.grid(1, 1): for i1_1 in T.thread_binding(64, thread="threadIdx.x"): with T.block("argmax"): i = T.axis.spatial(1, i0) k = T.axis.reduce(32, i1_0 * 64 + i1_1) T.where(i1_0 * 64 + i1_1 < 32) T.reads(idx[i, k], val[i, k]) T.writes(argmax_v0[i], argmax_v1[i]) with T.init(): argmax_v0[i] = -1 argmax_v1[i] = T.float32(-3.4028234663852886e38) v_argmax_v0: T.int32 = T.Select( argmax_v1[i] >= val[i, k], argmax_v0[i], idx[i, k] ) v_argmax_v1: T.float32 = T.Select( argmax_v1[i] >= val[i, k], argmax_v1[i], val[i, k] ) argmax_v0[i] = v_argmax_v0 argmax_v1[i] = v_argmax_v1 decision_0 = [] # type: ignore decision_1 = [ ("SampleCategorical", 4), ] mod = argmax_32 actual = generate_design_space( kind="cuda", mod=mod, target=Target("nvidia/geforce-rtx-3090", host="llvm"), types=ms.schedule_rule.CrossThreadReduction, ) check_sketches( mod, sketches=actual, expected_mods=[argmax_0, argmax_1], expected_decisions=[decision_0, decision_1], ) if __name__ == "__main__": test_gpu_softmax_mn() test_gpu_softmax_mn_after_inline() test_gpu_batch_norm_bmn() test_gpu_argmax() test_gpu_argmax_32()
https://github.com/zk-ml/tachikoma
tests/python/unittest/test_meta_schedule_schedule_rule_mlt.py
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. # pylint: disable=missing-module-docstring,missing-function-docstring,missing-class-docstring from tvm import meta_schedule as ms from tvm import target, te from tvm.meta_schedule.testing import te_workload from tvm.meta_schedule.testing.space_generation import ( check_sketches, generate_design_space, ) from tvm.script import tir as T from tvm.target import Target def test_cpu_matmul(): @T.prim_func def cpu_matmul_0( A: T.Buffer[(512, 512), "float32"], B: T.Buffer[(512, 512), "float32"], C: T.Buffer[(512, 512), "float32"], ) -> None: # function attr dict T.func_attr({"global_symbol": "main", "tir.noalias": True}) # body # with T.block("root") C_global = T.alloc_buffer([512, 512], dtype="float32") for i0_0, i1_0, i0_1, i1_1 in T.grid(1, 8, 8, 1): for i2_0, i0_2, i1_2, i2_1, i0_3, i1_3 in T.grid(16, 2, 8, 32, 32, 8): with T.block("C"): i = T.axis.spatial(512, i0_0 * 512 + i0_1 * 64 + i0_2 * 32 + i0_3) j = T.axis.spatial(512, i1_0 * 64 + i1_1 * 64 + i1_2 * 8 + i1_3) k = T.axis.reduce(512, i2_0 * 32 + i2_1) T.reads(A[i, k], B[k, j]) T.writes(C_global[i, j]) T.block_attr({"meta_schedule.tiling_structure": "SSRSRS"}) with T.init(): C_global[i, j] = T.float32(0) C_global[i, j] = C_global[i, j] + A[i, k] * B[k, j] for ax0, ax1 in T.grid(64, 64): with T.block("C_global"): v0 = T.axis.spatial(512, i0_1 * 64 + ax0) v1 = T.axis.spatial(512, i1_0 * 64 + ax1) T.reads(C_global[v0, v1]) T.writes(C[v0, v1]) C[v0, v1] = C_global[v0, v1] @T.prim_func def cpu_matmul_1( A: T.Buffer[(512, 512), "float32"], B: T.Buffer[(512, 512), "float32"], C: T.Buffer[(512, 512), "float32"], ) -> None: # function attr dict T.func_attr({"global_symbol": "main", "tir.noalias": True}) # body # with T.block("root") C_global = T.alloc_buffer([512, 512], dtype="float32") for i0_0, i1_0 in T.grid(1, 8): for i0_1, i1_1, i2_0, i0_2, i1_2, i2_1, i0_3, i1_3 in T.grid(8, 1, 16, 2, 8, 32, 32, 8): with T.block("C"): i = T.axis.spatial(512, i0_0 * 512 + i0_1 * 64 + i0_2 * 32 + i0_3) j = T.axis.spatial(512, i1_0 * 64 + i1_1 * 64 + i1_2 * 8 + i1_3) k = T.axis.reduce(512, i2_0 * 32 + i2_1) T.reads(A[i, k], B[k, j]) T.writes(C_global[i, j]) T.block_attr({"meta_schedule.tiling_structure": "SSRSRS"}) with T.init(): C_global[i, j] = T.float32(0) C_global[i, j] = C_global[i, j] + A[i, k] * B[k, j] for ax0, ax1 in T.grid(512, 64): with T.block("C_global"): v0 = T.axis.spatial(512, ax0) v1 = T.axis.spatial(512, i1_0 * 64 + ax1) T.reads(C_global[v0, v1]) T.writes(C[v0, v1]) C[v0, v1] = C_global[v0, v1] @T.prim_func def cpu_matmul_2( A: T.Buffer[(512, 512), "float32"], B: T.Buffer[(512, 512), "float32"], C: T.Buffer[(512, 512), "float32"], ) -> None: # function attr dict T.func_attr({"global_symbol": "main", "tir.noalias": True}) # body # with T.block("root") for i0_0, i1_0, i0_1, i1_1, i2_0, i0_2, i1_2, i2_1, i0_3, i1_3 in T.grid( 1, 8, 8, 1, 16, 2, 8, 32, 32, 8 ): with T.block("C"): i = T.axis.spatial(512, i0_0 * 512 + i0_1 * 64 + i0_2 * 32 + i0_3) j = T.axis.spatial(512, i1_0 * 64 + i1_1 * 64 + i1_2 * 8 + i1_3) k = T.axis.reduce(512, i2_0 * 32 + i2_1) T.reads(A[i, k], B[k, j]) T.writes(C[i, j]) T.block_attr({"meta_schedule.tiling_structure": "SSRSRS"}) with T.init(): C[i, j] = T.float32(0) C[i, j] = C[i, j] + A[i, k] * B[k, j] decision_0 = [ ("SamplePerfectTile", [1, 8, 2, 32]), ("SamplePerfectTile", [8, 1, 8, 8]), ("SamplePerfectTile", [16, 32]), ] decision_1 = [ ("SamplePerfectTile", [1, 8, 2, 32]), ("SamplePerfectTile", [8, 1, 8, 8]), ("SamplePerfectTile", [16, 32]), ] decision_2 = [ ("SamplePerfectTile", [1, 8, 2, 32]), ("SamplePerfectTile", [8, 1, 8, 8]), ("SamplePerfectTile", [16, 32]), ] mod = te.create_prim_func(te_workload.matmul(512, 512, 512)) actual = generate_design_space( kind="llvm", mod=mod, target=Target("llvm"), types=ms.schedule_rule.MultiLevelTiling, ) check_sketches( mod, sketches=actual, expected_mods=[cpu_matmul_0, cpu_matmul_1, cpu_matmul_2], expected_decisions=[decision_0, decision_1, decision_2], ) def test_cpu_matmul_relu(): @T.prim_func def cpu_matmul_relu_0( A: T.Buffer[(512, 512), "float32"], B: T.Buffer[(512, 512), "float32"], compute: T.Buffer[(512, 512), "float32"], ) -> None: # function attr dict T.func_attr({"global_symbol": "main", "tir.noalias": True}) # body # with T.block("root") C = T.alloc_buffer([512, 512], dtype="float32") for i0_0, i1_0, i0_1, i1_1, i2_0, i0_2, i1_2, i2_1, i0_3, i1_3 in T.grid( 256, 4, 1, 4, 64, 1, 32, 8, 2, 1 ): with T.block("C"): i = T.axis.spatial(512, i0_0 * 2 + i0_1 * 2 + i0_2 * 2 + i0_3) j = T.axis.spatial(512, i1_0 * 128 + i1_1 * 32 + i1_2 + i1_3) k = T.axis.reduce(512, i2_0 * 8 + i2_1) T.reads(A[i, k], B[k, j]) T.writes(C[i, j]) T.block_attr({"meta_schedule.tiling_structure": "SSRSRS"}) with T.init(): C[i, j] = T.float32(0) C[i, j] = C[i, j] + A[i, k] * B[k, j] for i0, i1 in T.grid(512, 512): with T.block("compute"): i0_4, i1_4 = T.axis.remap("SS", [i0, i1]) T.reads(C[i0_4, i1_4]) T.writes(compute[i0_4, i1_4]) compute[i0_4, i1_4] = T.max(C[i0_4, i1_4], T.float32(0)) @T.prim_func def cpu_matmul_relu_1( A: T.Buffer[(512, 512), "float32"], B: T.Buffer[(512, 512), "float32"], compute: T.Buffer[(512, 512), "float32"], ) -> None: # function attr dict T.func_attr({"global_symbol": "main", "tir.noalias": True}) # body # with T.block("root") C = T.alloc_buffer([512, 512], dtype="float32") for i0_0, i1_0, i0_1, i1_1 in T.grid(256, 4, 1, 4): for i2_0, i0_2, i1_2, i2_1, i0_3, i1_3 in T.grid(64, 1, 32, 8, 2, 1): with T.block("C"): i = T.axis.spatial(512, i0_0 * 2 + i0_1 * 2 + i0_2 * 2 + i0_3) j = T.axis.spatial(512, i1_0 * 128 + i1_1 * 32 + i1_2 + i1_3) k = T.axis.reduce(512, i2_0 * 8 + i2_1) T.reads(A[i, k], B[k, j]) T.writes(C[i, j]) T.block_attr({"meta_schedule.tiling_structure": "SSRSRS"}) with T.init(): C[i, j] = T.float32(0) C[i, j] = C[i, j] + A[i, k] * B[k, j] for ax0, ax1 in T.grid(2, 32): with T.block("compute"): i0 = T.axis.spatial(512, i0_0 * 2 + ax0) i1 = T.axis.spatial(512, i1_0 * 128 + i1_1 * 32 + ax1) T.reads(C[i0, i1]) T.writes(compute[i0, i1]) compute[i0, i1] = T.max(C[i0, i1], T.float32(0)) @T.prim_func def cpu_matmul_relu_2( A: T.Buffer[(512, 512), "float32"], B: T.Buffer[(512, 512), "float32"], compute: T.Buffer[(512, 512), "float32"], ) -> None: # function attr dict T.func_attr({"global_symbol": "main", "tir.noalias": True}) # body # with T.block("root") C = T.alloc_buffer([512, 512], dtype="float32") for i0_0, i1_0 in T.grid(256, 4): for i0_1, i1_1, i2_0, i0_2, i1_2, i2_1, i0_3, i1_3 in T.grid(1, 4, 64, 1, 32, 8, 2, 1): with T.block("C"): i = T.axis.spatial(512, i0_0 * 2 + i0_1 * 2 + i0_2 * 2 + i0_3) j = T.axis.spatial(512, i1_0 * 128 + i1_1 * 32 + i1_2 + i1_3) k = T.axis.reduce(512, i2_0 * 8 + i2_1) T.reads(A[i, k], B[k, j]) T.writes(C[i, j]) T.block_attr({"meta_schedule.tiling_structure": "SSRSRS"}) with T.init(): C[i, j] = T.float32(0) C[i, j] = C[i, j] + A[i, k] * B[k, j] for ax0, ax1 in T.grid(2, 128): with T.block("compute"): i0 = T.axis.spatial(512, i0_0 * 2 + ax0) i1 = T.axis.spatial(512, i1_0 * 128 + ax1) T.reads(C[i0, i1]) T.writes(compute[i0, i1]) compute[i0, i1] = T.max(C[i0, i1], T.float32(0)) decision_0 = [ ("SamplePerfectTile", [256, 1, 1, 2]), ("SamplePerfectTile", [4, 4, 32, 1]), ("SamplePerfectTile", [64, 8]), ] decision_1 = [ ("SamplePerfectTile", [256, 1, 1, 2]), ("SamplePerfectTile", [4, 4, 32, 1]), ("SamplePerfectTile", [64, 8]), ] decision_2 = [ ("SamplePerfectTile", [256, 1, 1, 2]), ("SamplePerfectTile", [4, 4, 32, 1]), ("SamplePerfectTile", [64, 8]), ] mod = te.create_prim_func(te_workload.matmul_relu(512, 512, 512)) actual = generate_design_space( kind="llvm", mod=mod, target=Target("llvm"), types=ms.schedule_rule.MultiLevelTiling, ) check_sketches( mod, sketches=actual, expected_mods=[cpu_matmul_relu_0, cpu_matmul_relu_1, cpu_matmul_relu_2], expected_decisions=[decision_0, decision_1, decision_2], ) def test_cuda_matmul(): @T.prim_func def cuda_matmul_0( A: T.Buffer[(512, 512), "float32"], B: T.Buffer[(512, 512), "float32"], C: T.Buffer[(512, 512), "float32"], ) -> None: # function attr dict T.func_attr({"global_symbol": "main", "tir.noalias": True}) # body # with T.block("root") C_local = T.alloc_buffer([512, 512], dtype="float32", scope="local") A_shared = T.alloc_buffer([512, 512], dtype="float32", scope="shared") B_shared = T.alloc_buffer([512, 512], dtype="float32", scope="shared") for i0_0_i1_0_fused in T.thread_binding(128, thread="blockIdx.x"): for i0_1_i1_1_fused in T.thread_binding(8, thread="vthread.x"): for i0_2_i1_2_fused in T.thread_binding(4, thread="threadIdx.x"): for i2_0 in T.serial(128): for ax0_ax1_fused in T.serial(256): with T.block("A_shared"): v0 = T.axis.spatial( 512, i0_0_i1_0_fused // 16 * 64 + ax0_ax1_fused // 4 ) v1 = T.axis.spatial(512, i2_0 * 4 + ax0_ax1_fused % 4) T.reads(A[v0, v1]) T.writes(A_shared[v0, v1]) T.block_attr({"meta_schedule.cooperative_fetch": 2}) A_shared[v0, v1] = A[v0, v1] for ax0_ax1_fused in T.serial(128): with T.block("B_shared"): v0 = T.axis.spatial(512, i2_0 * 4 + ax0_ax1_fused // 32) v1 = T.axis.spatial( 512, i0_0_i1_0_fused % 16 * 32 + ax0_ax1_fused % 32 ) T.reads(B[v0, v1]) T.writes(B_shared[v0, v1]) T.block_attr({"meta_schedule.cooperative_fetch": 1}) B_shared[v0, v1] = B[v0, v1] for i2_1, i0_3, i1_3, i2_2, i0_4, i1_4 in T.grid(2, 1, 1, 2, 16, 4): with T.block("C"): i = T.axis.spatial( 512, i0_0_i1_0_fused // 16 * 64 + i0_1_i1_1_fused // 2 * 16 + i0_3 * 16 + i0_4, ) j = T.axis.spatial( 512, i0_0_i1_0_fused % 16 * 32 + i0_1_i1_1_fused % 2 * 16 + i0_2_i1_2_fused * 4 + i1_3 * 4 + i1_4, ) k = T.axis.reduce(512, i2_0 * 4 + i2_1 * 2 + i2_2) T.reads(A_shared[i, k], B_shared[k, j]) T.writes(C_local[i, j]) T.block_attr( { "meta_schedule.thread_extent_high_inclusive": 1024, "meta_schedule.thread_extent_low_inclusive": 32, "meta_schedule.tiling_structure": "SSSRRSRS", } ) with T.init(): C_local[i, j] = T.float32(0) C_local[i, j] = C_local[i, j] + A_shared[i, k] * B_shared[k, j] for ax0, ax1 in T.grid(16, 4): with T.block("C_local"): v0 = T.axis.spatial( 512, i0_0_i1_0_fused // 16 * 64 + i0_1_i1_1_fused // 2 * 16 + ax0 ) v1 = T.axis.spatial( 512, i0_0_i1_0_fused % 16 * 32 + i0_1_i1_1_fused % 2 * 16 + i0_2_i1_2_fused * 4 + ax1, ) T.reads(C_local[v0, v1]) T.writes(C[v0, v1]) C[v0, v1] = C_local[v0, v1] decision_0 = [ ("SamplePerfectTile", [8, 4, 1, 1, 16]), ("SamplePerfectTile", [16, 2, 4, 1, 4]), ("SamplePerfectTile", [128, 2, 2]), ("SampleCategorical", 1), ("SampleCategorical", 0), ] mod = te.create_prim_func(te_workload.matmul(512, 512, 512)) actual = generate_design_space( kind="cuda", mod=mod, target=Target("nvidia/geforce-rtx-3080"), types=ms.schedule_rule.MultiLevelTiling, ) check_sketches( mod, sketches=actual, expected_mods=[cuda_matmul_0], expected_decisions=[decision_0], ) def test_cuda_matmul_relu(): @T.prim_func def cuda_matmul_relu_0( A: T.Buffer[(512, 512), "float32"], B: T.Buffer[(512, 512), "float32"], compute: T.Buffer[(512, 512), "float32"], ) -> None: # function attr dict T.func_attr({"global_symbol": "main", "tir.noalias": True}) # body # with T.block("root") C = T.alloc_buffer([512, 512], dtype="float32") C_local = T.alloc_buffer([512, 512], dtype="float32", scope="local") A_shared = T.alloc_buffer([512, 512], dtype="float32", scope="shared") B_shared = T.alloc_buffer([512, 512], dtype="float32", scope="shared") for i0_0_i1_0_fused in T.thread_binding(64, thread="blockIdx.x"): for i0_1_i1_1_fused in T.thread_binding(64, thread="vthread.x"): for i0_2_i1_2_fused in T.thread_binding(8, thread="threadIdx.x"): for i2_0 in T.serial(8): for ax0_ax1_fused in T.serial(4096): with T.block("A_shared"): v0 = T.axis.spatial( 512, i0_0_i1_0_fused // 8 * 64 + ax0_ax1_fused // 64 ) v1 = T.axis.spatial(512, i2_0 * 64 + ax0_ax1_fused % 64) T.reads(A[v0, v1]) T.writes(A_shared[v0, v1]) T.block_attr({"meta_schedule.cooperative_fetch": 2}) A_shared[v0, v1] = A[v0, v1] for ax0_ax1_fused in T.serial(4096): with T.block("B_shared"): v0 = T.axis.spatial(512, i2_0 * 64 + ax0_ax1_fused // 64) v1 = T.axis.spatial( 512, i0_0_i1_0_fused % 8 * 64 + ax0_ax1_fused % 64 ) T.reads(B[v0, v1]) T.writes(B_shared[v0, v1]) T.block_attr({"meta_schedule.cooperative_fetch": 4}) B_shared[v0, v1] = B[v0, v1] for i2_1, i0_3, i1_3, i2_2, i0_4, i1_4 in T.grid(8, 2, 1, 8, 2, 2): with T.block("C"): i = T.axis.spatial( 512, i0_0_i1_0_fused // 8 * 64 + i0_1_i1_1_fused // 8 * 8 + i0_2_i1_2_fused // 4 * 4 + i0_3 * 2 + i0_4, ) j = T.axis.spatial( 512, i0_0_i1_0_fused % 8 * 64 + i0_1_i1_1_fused % 8 * 8 + i0_2_i1_2_fused % 4 * 2 + i1_3 * 2 + i1_4, ) k = T.axis.reduce(512, i2_0 * 64 + i2_1 * 8 + i2_2) T.reads(A_shared[i, k], B_shared[k, j]) T.writes(C_local[i, j]) T.block_attr( { "meta_schedule.thread_extent_high_inclusive": 1024, "meta_schedule.thread_extent_low_inclusive": 32, "meta_schedule.tiling_structure": "SSSRRSRS", } ) with T.init(): C_local[i, j] = T.float32(0) C_local[i, j] = C_local[i, j] + A_shared[i, k] * B_shared[k, j] for ax0, ax1 in T.grid(4, 2): with T.block("C_local"): v0 = T.axis.spatial( 512, i0_0_i1_0_fused // 8 * 64 + i0_1_i1_1_fused // 8 * 8 + i0_2_i1_2_fused // 4 * 4 + ax0, ) v1 = T.axis.spatial( 512, i0_0_i1_0_fused % 8 * 64 + i0_1_i1_1_fused % 8 * 8 + i0_2_i1_2_fused % 4 * 2 + ax1, ) T.reads(C_local[v0, v1]) T.writes(C[v0, v1]) C[v0, v1] = C_local[v0, v1] for i0, i1 in T.grid(512, 512): with T.block("compute"): i0_1, i1_1 = T.axis.remap("SS", [i0, i1]) T.reads(C[i0_1, i1_1]) T.writes(compute[i0_1, i1_1]) compute[i0_1, i1_1] = T.max(C[i0_1, i1_1], T.float32(0)) decision_0 = [ ("SamplePerfectTile", [8, 8, 2, 2, 2]), ("SamplePerfectTile", [8, 8, 4, 1, 2]), ("SamplePerfectTile", [8, 8, 8]), ("SampleCategorical", 1), ("SampleCategorical", 3), ] mod = te.create_prim_func(te_workload.matmul_relu(512, 512, 512)) actual = generate_design_space( kind="cuda", mod=mod, target=Target("nvidia/geforce-rtx-3080"), types=ms.schedule_rule.MultiLevelTiling, ) check_sketches( mod, sketches=actual, expected_mods=[cuda_matmul_relu_0], expected_decisions=[decision_0], ) def test_cuda_sum_with_trivial_block_iter(): @T.prim_func def sum_with_trivial_block_iter( A: T.Buffer[(1, 64, 768), "float32"], B: T.Buffer[(1, 64, 1), "float32"], ) -> None: for i0, i1, i2, i3 in T.grid(1, 64, 1, 768): with T.block("sum"): ax0, ax1, ax2, k2 = T.axis.remap("SSSR", [i0, i1, i2, i3]) T.reads(A[ax0, ax1, k2]) T.writes(B[ax0, ax1, ax2]) with T.init(): B[ax0, ax1, ax2] = T.float32(0) B[ax0, ax1, ax2] = B[ax0, ax1, ax2] + A[ax0, ax1, k2] # Expect nothing to happen - the rule is not supposed to be applied in this case mod = sum_with_trivial_block_iter (sch,) = generate_design_space( kind="cuda", mod=mod, target=Target("nvidia/geforce-rtx-3080"), types=ms.schedule_rule.MultiLevelTiling, ) assert not sch.trace.simplified(remove_postproc=True).insts def test_multi_level_tiling_hexagon(): @T.prim_func def cpu_conv2d_nhwc( inputs: T.Buffer[(1, 56, 56, 64), "float16"], weight: T.Buffer[(3, 3, 64, 64), "float16"], conv2d_nhwc: T.Buffer[(1, 56, 56, 64), "float16"], ) -> None: # function attr dict T.func_attr({"global_symbol": "main", "tir.noalias": True}) # body # with T.block("root") PadInput = T.alloc_buffer([1, 58, 58, 64], dtype="float16") for i0, i1, i2, i3 in T.grid(1, 58, 58, 64): with T.block("PadInput"): i0_1, i1_1, i2_1, i3_1 = T.axis.remap("SSSS", [i0, i1, i2, i3]) T.reads(inputs[i0_1, i1_1 - 1, i2_1 - 1, i3_1]) T.writes(PadInput[i0_1, i1_1, i2_1, i3_1]) PadInput[i0_1, i1_1, i2_1, i3_1] = T.if_then_else( 1 <= i1_1 and i1_1 < 57 and 1 <= i2_1 and i2_1 < 57, inputs[i0_1, i1_1 - 1, i2_1 - 1, i3_1], T.float16(0), dtype="float16", ) for ( i0_0, i1_0, i2_0, i3_0, i4_0, i5_0, i6_0, i0_1_1, i1_1_1, i2_1_1, i3_1_1, i4_1, i5_1, i6_1, i0_2, i1_2, i2_2, i3_2, ) in T.grid(1, 1, 2, 1, 3, 3, 16, 1, 14, 2, 1, 1, 1, 4, 1, 4, 14, 64): with T.block("conv2d_nhwc"): n = T.axis.spatial(1, i0_1_1 + i0_2 + i0_0) h = T.axis.spatial(56, i1_0 * 56 + i1_1_1 * 4 + i1_2) w = T.axis.spatial(56, i2_0 * 28 + i2_1_1 * 14 + i2_2) co = T.axis.spatial(64, i3_0 * 64 + i3_1_1 * 64 + i3_2) rh = T.axis.reduce(3, i4_1 + i4_0) rw = T.axis.reduce(3, i5_0 + i5_1) rc = T.axis.reduce(64, i6_0 * 4 + i6_1) T.reads(PadInput[n, h + rh, w + rw, co // 64 * 64 + rc], weight[rh, rw, rc, co]) T.writes(conv2d_nhwc[n, h, w, co]) T.block_attr({"meta_schedule.tiling_structure": "SRSRS"}) with T.init(): conv2d_nhwc[n, h, w, co] = T.float16(0) conv2d_nhwc[n, h, w, co] = ( conv2d_nhwc[n, h, w, co] + PadInput[n, h + rh, w + rw, co // 64 * 64 + rc] * weight[rh, rw, rc, co] ) target_hexagon = target.hexagon("v69", num_cores=4) I = 64 O = 64 H = 56 W = 56 mod = te.create_prim_func( te_workload.conv2d_nhwc(1, H, W, I, O, 3, 1, 1, 1, in_dtype="float16", out_dtype="float16") ) actual = generate_design_space( kind="cuda", mod=mod, target=Target(target_hexagon, host=target_hexagon), types=None, sch_rules=[ ms.schedule_rule.MultiLevelTilingWideVector( structure="SRSRS", vector_length_in_bits=1024, max_innermost_factor=64, reuse_read=None, reuse_write=None, ) ], ) decision_0 = [ ("SamplePerfectTile", [1, 1, 1]), ("SamplePerfectTile", [1, 14, 4]), ("SamplePerfectTile", [2, 2, 14]), ("SamplePerfectTile", [3, 1]), ("SamplePerfectTile", [3, 1]), ("SamplePerfectTile", [16, 4]), ] check_sketches( mod, sketches=actual, expected_mods=[cpu_conv2d_nhwc], expected_decisions=[decision_0], ) def test_cache_read_specify_consumer(): A, B, C = te_workload.matmul(512, 512, 512) mod = te.create_prim_func([A, B, C + A]) space = generate_design_space( kind="cuda", mod=mod, target=Target("nvidia/geforce-rtx-3080"), types=ms.schedule_rule.MultiLevelTiling, ) residual_block = """ for i0, i1 in T.grid(512, 512): with T.block("T_add"): ax0, ax1 = T.axis.remap("SS", [i0, i1]) T.reads(C[ax0, ax1], A[ax0, ax1]) T.writes(T_add[ax0, ax1]) T_add[ax0, ax1] = C[ax0, ax1] + A[ax0, ax1] """ assert residual_block in space[0].mod.script() if __name__ == "__main__": test_cpu_matmul() test_cpu_matmul_relu() test_cuda_matmul() test_cuda_matmul_relu() test_cuda_sum_with_trivial_block_iter() test_multi_level_tiling_hexagon()
https://github.com/zk-ml/tachikoma
tests/python/unittest/test_meta_schedule_schedule_rule_mlt_intrin.py
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. # pylint: disable=missing-module-docstring,missing-function-docstring,missing-class-docstring from tvm import meta_schedule as ms from tvm import te from tvm.ir import assert_structural_equal from tvm.meta_schedule.testing.space_generation import ( check_sketches, generate_design_space, ) from tvm.script import tir as T from tvm.target import Target from tvm.tir.tensor_intrin.arm_cpu import DP4A_INTRIN from tvm.tir.tensor_intrin.x86 import VNNI_DOT_16x4_INTRIN as VNNI_INTRIN def test_vnni_conv2d_nchwc(): @T.prim_func def conv2d_nchwc( placeholder: T.Buffer[(1, 4, 56, 56, 16), "uint8"], placeholder_1: T.Buffer[(16, 4, 1, 1, 4, 16, 4), "int8"], conv2d_NCHWc_int8: T.Buffer[(1, 16, 56, 56, 16), "int32"], ) -> None: T.func_attr({"global_symbol": "main", "tir.noalias": True}) for i0, i1, i2, i3, i4, i5, i6, i7, i8, i9 in T.grid(1, 16, 56, 56, 16, 1, 1, 4, 4, 4): with T.block("conv2d_NCHWc_int8"): ( n, oc_chunk, oh, ow, oc_block, kh, kw, ic_outer, ic_f_inner, ic_s_inner, ) = T.axis.remap("SSSSSRRRRR", [i0, i1, i2, i3, i4, i5, i6, i7, i8, i9]) T.reads( placeholder[n, ic_outer, oh + kh, ow + kw, ic_f_inner * 4 + ic_s_inner], placeholder_1[oc_chunk, ic_outer, kh, kw, ic_f_inner, oc_block, ic_s_inner], ) T.writes(conv2d_NCHWc_int8[n, oc_chunk, oh, ow, oc_block]) with T.init(): conv2d_NCHWc_int8[n, oc_chunk, oh, ow, oc_block] = 0 conv2d_NCHWc_int8[n, oc_chunk, oh, ow, oc_block] = conv2d_NCHWc_int8[ n, oc_chunk, oh, ow, oc_block ] + T.cast( placeholder[n, ic_outer, oh + kh, ow + kw, ic_f_inner * 4 + ic_s_inner], "int32" ) * T.cast( placeholder_1[oc_chunk, ic_outer, kh, kw, ic_f_inner, oc_block, ic_s_inner], "int32", ) # fmt: off @T.prim_func def vnni_conv2d_nchwc_0(placeholder: T.Buffer[(1, 4, 56, 56, 16), "uint8"], placeholder_1: T.Buffer[(16, 4, 1, 1, 4, 16, 4), "int8"], conv2d_NCHWc_int8: T.Buffer[(1, 16, 56, 56, 16), "int32"]) -> None: T.func_attr({"global_symbol": "main", "tir.noalias": True}) conv2d_NCHWc_int8_global = T.alloc_buffer([1, 16, 56, 56, 16], dtype="int32") for i0_0, i1_0, i2_0, i3_0, i4_0_0, i0_1, i1_1, i2_1, i3_1, i4_0_1 in T.grid(1, 8, 28, 56, 1, 1, 2, 1, 1, 1): for i5_0, i6_0, i7_0, i8_0, i9_0_0, i0_2, i1_2, i2_2, i3_2, i4_0_2, i5_1, i6_1, i7_1, i8_1, i9_0_1, i0_3, i1_3, i2_3, i3_3, i4_0_3 in T.grid(1, 1, 1, 4, 1, 1, 1, 2, 1, 1, 1, 1, 4, 1, 1, 1, 1, 1, 1, 1): with T.block("conv2d_NCHWc_int8_o"): n = T.axis.spatial(1, 0) oc_chunk = T.axis.spatial(16, i1_0 * 2 + i1_1 + i1_2 + i1_3) oh = T.axis.spatial(56, i2_0 * 2 + i2_1 * 2 + i2_2 + i2_3) ow = T.axis.spatial(56, i3_3 + i3_0 + i3_1 + i3_2) oc_block_o = T.axis.spatial(1, 0) kh = T.axis.reduce(1, 0) kw = T.axis.reduce(1, 0) ic_outer = T.axis.reduce(4, i7_0 * 4 + i7_1) ic_f_inner = T.axis.reduce(4, i8_0 + i8_1) ic_s_inner_o = T.axis.reduce(1, 0) T.reads(placeholder[n, ic_outer, oh + kh, ow + kw, ic_f_inner * 4 : ic_f_inner * 4 + 4], placeholder_1[oc_chunk, ic_outer, kh, kw, ic_f_inner, 0 : 16, 0 : 4]) T.writes(conv2d_NCHWc_int8_global[n, oc_chunk, oh, ow, 0 : 16]) T.block_attr({"meta_schedule.auto_tensorize":"dot_16x4_vnni"}) with T.init(): for i4_1 in T.serial(16): with T.block("conv2d_NCHWc_int8_init"): oc_block_i_init = T.axis.spatial(16, i4_1) T.reads() T.writes(conv2d_NCHWc_int8_global[n, oc_chunk, oh, ow, oc_block_i_init]) conv2d_NCHWc_int8_global[n, oc_chunk, oh, ow, oc_block_i_init] = 0 for i4_1, i9_1 in T.grid(16, 4): with T.block("conv2d_NCHWc_int8"): oc_block_i, ic_s_inner_i = T.axis.remap("SR", [i4_1, i9_1]) T.reads(conv2d_NCHWc_int8_global[n, oc_chunk, oh, ow, oc_block_i], placeholder[n, ic_outer, oh + kh, ow + kw, ic_f_inner * 4 + ic_s_inner_i], placeholder_1[oc_chunk, ic_outer, kh, kw, ic_f_inner, oc_block_i, ic_s_inner_i]) T.writes(conv2d_NCHWc_int8_global[n, oc_chunk, oh, ow, oc_block_i]) T.block_attr({"meta_schedule.tiling_structure":"SSRSRS"}) conv2d_NCHWc_int8_global[n, oc_chunk, oh, ow, oc_block_i] = conv2d_NCHWc_int8_global[n, oc_chunk, oh, ow, oc_block_i] + T.cast(placeholder[n, ic_outer, oh + kh, ow + kw, ic_f_inner * 4 + ic_s_inner_i], "int32") * T.cast(placeholder_1[oc_chunk, ic_outer, kh, kw, ic_f_inner, oc_block_i, ic_s_inner_i], "int32") for ax0, ax1, ax2, ax3, ax4 in T.grid(1, 1, 2, 1, 16): with T.block("conv2d_NCHWc_int8_global"): v0 = T.axis.spatial(1, ax0) v1 = T.axis.spatial(16, i1_0 * 2 + i1_1 + ax1) v2 = T.axis.spatial(56, i2_0 * 2 + ax2) v3 = T.axis.spatial(56, i3_0 + ax3) v4 = T.axis.spatial(16, ax4) T.reads(conv2d_NCHWc_int8_global[v0, v1, v2, v3, v4]) T.writes(conv2d_NCHWc_int8[v0, v1, v2, v3, v4]) conv2d_NCHWc_int8[v0, v1, v2, v3, v4] = conv2d_NCHWc_int8_global[v0, v1, v2, v3, v4] @T.prim_func def vnni_conv2d_nchwc_1(placeholder: T.Buffer[(1, 4, 56, 56, 16), "uint8"], placeholder_1: T.Buffer[(16, 4, 1, 1, 4, 16, 4), "int8"], conv2d_NCHWc_int8: T.Buffer[(1, 16, 56, 56, 16), "int32"]) -> None: T.func_attr({"global_symbol": "main", "tir.noalias": True}) conv2d_NCHWc_int8_global = T.alloc_buffer([1, 16, 56, 56, 16], dtype="int32") for i0_0, i1_0, i2_0, i3_0, i4_0_0 in T.grid(1, 8, 28, 56, 1): for i0_1, i1_1, i2_1, i3_1, i4_0_1, i5_0, i6_0, i7_0, i8_0, i9_0_0, i0_2, i1_2, i2_2, i3_2, i4_0_2, i5_1, i6_1, i7_1, i8_1, i9_0_1, i0_3, i1_3, i2_3, i3_3, i4_0_3 in T.grid(1, 2, 1, 1, 1, 1, 1, 1, 4, 1, 1, 1, 2, 1, 1, 1, 1, 4, 1, 1, 1, 1, 1, 1, 1): with T.block("conv2d_NCHWc_int8_o"): n = T.axis.spatial(1, 0) oc_chunk = T.axis.spatial(16, i1_0 * 2 + i1_1 + i1_2 + i1_3) oh = T.axis.spatial(56, i2_0 * 2 + i2_1 * 2 + i2_2 + i2_3) ow = T.axis.spatial(56, i3_3 + i3_0 + i3_1 + i3_2) oc_block_o = T.axis.spatial(1, 0) kh = T.axis.reduce(1, 0) kw = T.axis.reduce(1, 0) ic_outer = T.axis.reduce(4, i7_0 * 4 + i7_1) ic_f_inner = T.axis.reduce(4, i8_0 + i8_1) ic_s_inner_o = T.axis.reduce(1, 0) T.reads(placeholder[n, ic_outer, oh + kh, ow + kw, ic_f_inner * 4 : ic_f_inner * 4 + 4], placeholder_1[oc_chunk, ic_outer, kh, kw, ic_f_inner, 0 : 16, 0 : 4]) T.writes(conv2d_NCHWc_int8_global[n, oc_chunk, oh, ow, 0 : 16]) T.block_attr({"meta_schedule.auto_tensorize":"dot_16x4_vnni"}) with T.init(): for i4_1 in T.serial(16): with T.block("conv2d_NCHWc_int8_init"): oc_block_i_init = T.axis.spatial(16, i4_1) T.reads() T.writes(conv2d_NCHWc_int8_global[n, oc_chunk, oh, ow, oc_block_i_init]) conv2d_NCHWc_int8_global[n, oc_chunk, oh, ow, oc_block_i_init] = 0 for i4_1, i9_1 in T.grid(16, 4): with T.block("conv2d_NCHWc_int8"): oc_block_i, ic_s_inner_i = T.axis.remap("SR", [i4_1, i9_1]) T.reads(conv2d_NCHWc_int8_global[n, oc_chunk, oh, ow, oc_block_i], placeholder[n, ic_outer, oh + kh, ow + kw, ic_f_inner * 4 + ic_s_inner_i], placeholder_1[oc_chunk, ic_outer, kh, kw, ic_f_inner, oc_block_i, ic_s_inner_i]) T.writes(conv2d_NCHWc_int8_global[n, oc_chunk, oh, ow, oc_block_i]) T.block_attr({"meta_schedule.tiling_structure":"SSRSRS"}) conv2d_NCHWc_int8_global[n, oc_chunk, oh, ow, oc_block_i] = conv2d_NCHWc_int8_global[n, oc_chunk, oh, ow, oc_block_i] + T.cast(placeholder[n, ic_outer, oh + kh, ow + kw, ic_f_inner * 4 + ic_s_inner_i], "int32") * T.cast(placeholder_1[oc_chunk, ic_outer, kh, kw, ic_f_inner, oc_block_i, ic_s_inner_i], "int32") for ax0, ax1, ax2, ax3, ax4 in T.grid(1, 2, 2, 1, 16): with T.block("conv2d_NCHWc_int8_global"): v0 = T.axis.spatial(1, ax0) v1 = T.axis.spatial(16, i1_0 * 2 + ax1) v2 = T.axis.spatial(56, i2_0 * 2 + ax2) v3 = T.axis.spatial(56, i3_0 + ax3) v4 = T.axis.spatial(16, ax4) T.reads(conv2d_NCHWc_int8_global[v0, v1, v2, v3, v4]) T.writes(conv2d_NCHWc_int8[v0, v1, v2, v3, v4]) conv2d_NCHWc_int8[v0, v1, v2, v3, v4] = conv2d_NCHWc_int8_global[v0, v1, v2, v3, v4] @T.prim_func def vnni_conv2d_nchwc_2(placeholder: T.Buffer[(1, 4, 56, 56, 16), "uint8"], placeholder_1: T.Buffer[(16, 4, 1, 1, 4, 16, 4), "int8"], conv2d_NCHWc_int8: T.Buffer[(1, 16, 56, 56, 16), "int32"]) -> None: T.func_attr({"global_symbol": "main", "tir.noalias": True}) for i0_0, i1_0, i2_0, i3_0, i4_0_0, i0_1, i1_1, i2_1, i3_1, i4_0_1, i5_0, i6_0, i7_0, i8_0, i9_0_0, i0_2, i1_2, i2_2, i3_2, i4_0_2, i5_1, i6_1, i7_1, i8_1, i9_0_1, i0_3, i1_3, i2_3, i3_3, i4_0_3 in T.grid(1, 8, 28, 56, 1, 1, 2, 1, 1, 1, 1, 1, 1, 4, 1, 1, 1, 2, 1, 1, 1, 1, 4, 1, 1, 1, 1, 1, 1, 1): with T.block("conv2d_NCHWc_int8_o"): n = T.axis.spatial(1, 0) oc_chunk = T.axis.spatial(16, i1_0 * 2 + i1_1 + i1_2 + i1_3) oh = T.axis.spatial(56, i2_0 * 2 + i2_1 * 2 + i2_2 + i2_3) ow = T.axis.spatial(56, i3_3 + i3_0 + i3_1 + i3_2) oc_block_o = T.axis.spatial(1, 0) kh = T.axis.reduce(1, 0) kw = T.axis.reduce(1, 0) ic_outer = T.axis.reduce(4, i7_0 * 4 + i7_1) ic_f_inner = T.axis.reduce(4, i8_0 + i8_1) ic_s_inner_o = T.axis.reduce(1, 0) T.reads(placeholder[n, ic_outer, oh + kh, ow + kw, ic_f_inner * 4 : ic_f_inner * 4 + 4], placeholder_1[oc_chunk, ic_outer, kh, kw, ic_f_inner, 0 : 16, 0 : 4]) T.writes(conv2d_NCHWc_int8[n, oc_chunk, oh, ow, 0 : 16]) T.block_attr({"meta_schedule.auto_tensorize":"dot_16x4_vnni"}) with T.init(): for i4_1 in T.serial(16): with T.block("conv2d_NCHWc_int8_init"): oc_block_i_init = T.axis.spatial(16, i4_1) T.reads() T.writes(conv2d_NCHWc_int8[n, oc_chunk, oh, ow, oc_block_i_init]) conv2d_NCHWc_int8[n, oc_chunk, oh, ow, oc_block_i_init] = 0 for i4_1, i9_1 in T.grid(16, 4): with T.block("conv2d_NCHWc_int8"): oc_block_i, ic_s_inner_i = T.axis.remap("SR", [i4_1, i9_1]) T.reads(conv2d_NCHWc_int8[n, oc_chunk, oh, ow, oc_block_i], placeholder[n, ic_outer, oh + kh, ow + kw, ic_f_inner * 4 + ic_s_inner_i], placeholder_1[oc_chunk, ic_outer, kh, kw, ic_f_inner, oc_block_i, ic_s_inner_i]) T.writes(conv2d_NCHWc_int8[n, oc_chunk, oh, ow, oc_block_i]) T.block_attr({"meta_schedule.tiling_structure":"SSRSRS"}) conv2d_NCHWc_int8[n, oc_chunk, oh, ow, oc_block_i] = conv2d_NCHWc_int8[n, oc_chunk, oh, ow, oc_block_i] + T.cast(placeholder[n, ic_outer, oh + kh, ow + kw, ic_f_inner * 4 + ic_s_inner_i], "int32") * T.cast(placeholder_1[oc_chunk, ic_outer, kh, kw, ic_f_inner, oc_block_i, ic_s_inner_i], "int32") # fmt: on decision_0 = [ ("SamplePerfectTile", [1, 1, 1, 1]), ("SamplePerfectTile", [8, 2, 1, 1]), ("SamplePerfectTile", [28, 1, 2, 1]), ("SamplePerfectTile", [56, 1, 1, 1]), ("SamplePerfectTile", [1, 1, 1, 1]), ("SamplePerfectTile", [1, 1]), ("SamplePerfectTile", [1, 1]), ("SamplePerfectTile", [1, 4]), ("SamplePerfectTile", [4, 1]), ("SamplePerfectTile", [1, 1]), ] decision_1 = [ ("SamplePerfectTile", [1, 1, 1, 1]), ("SamplePerfectTile", [8, 2, 1, 1]), ("SamplePerfectTile", [28, 1, 2, 1]), ("SamplePerfectTile", [56, 1, 1, 1]), ("SamplePerfectTile", [1, 1, 1, 1]), ("SamplePerfectTile", [1, 1]), ("SamplePerfectTile", [1, 1]), ("SamplePerfectTile", [1, 4]), ("SamplePerfectTile", [4, 1]), ("SamplePerfectTile", [1, 1]), ] decision_2 = [ ("SamplePerfectTile", [1, 1, 1, 1]), ("SamplePerfectTile", [8, 2, 1, 1]), ("SamplePerfectTile", [28, 1, 2, 1]), ("SamplePerfectTile", [56, 1, 1, 1]), ("SamplePerfectTile", [1, 1, 1, 1]), ("SamplePerfectTile", [1, 1]), ("SamplePerfectTile", [1, 1]), ("SamplePerfectTile", [1, 4]), ("SamplePerfectTile", [4, 1]), ("SamplePerfectTile", [1, 1]), ] mod = conv2d_nchwc target = Target("llvm -mcpu=cascadelake -num-cores=4") actual = generate_design_space( kind="llvm", mod=mod, target=Target(target), types=None, sch_rules=[ ms.schedule_rule.MultiLevelTilingWithIntrin( VNNI_INTRIN, structure="SSRSRS", tile_binds=None, max_innermost_factor=64, vector_load_lens=None, reuse_read=None, reuse_write=ms.schedule_rule.ReuseType(req="may", levels=[1, 2], scope="global"), ), ], ) check_sketches( mod, sketches=actual, expected_mods=[vnni_conv2d_nchwc_0, vnni_conv2d_nchwc_1, vnni_conv2d_nchwc_2], expected_decisions=[decision_0, decision_1, decision_2], ) def _check_dp4a_dense(m, n, k, in_dtype, out_dtype, expected_mods, expected_decisions): def _dense(m, n, k, in_dtype, out_dtype): X = te.placeholder((m, k), name="X", dtype=in_dtype) W = te.placeholder((n, k), name="W", dtype=in_dtype) ak = te.reduce_axis((0, k), name="k") matmul = te.compute( (m, n), lambda i, j: te.sum( X[i, ak].astype(out_dtype) * W[j, ak].astype(out_dtype), axis=ak, ), name="compute", ) return te.create_prim_func([X, W, matmul]) mod = _dense(m, n, k, in_dtype, out_dtype) actual = generate_design_space( kind="cuda", mod=mod, target=Target("cuda"), types=None, sch_rules=[ ms.schedule_rule.MultiLevelTilingWithIntrin( DP4A_INTRIN, structure="SSSRRSRS", tile_binds=["blockIdx.x", "vthread.x", "threadIdx.x"], max_innermost_factor=64, vector_load_lens=[1, 2, 3, 4], reuse_read=ms.schedule_rule.ReuseType(req="must", levels=[4], scope="shared"), reuse_write=ms.schedule_rule.ReuseType(req="must", levels=[3], scope="local"), ) ], ) if expected_mods is None: assert expected_decisions is None assert len(actual) == 1 assert_structural_equal(mod, actual[0].mod["main"]) else: check_sketches(mod, actual, expected_mods, expected_decisions) def test_dp4a_dense(): @T.prim_func def dp4a_dense_0( X: T.Buffer[(128, 128), "int8"], W: T.Buffer[(128, 128), "int8"], compute: T.Buffer[(128, 128), "int32"], ) -> None: # function attr dict T.func_attr({"global_symbol": "main", "tir.noalias": True}) # body # with T.block("root") compute_local = T.alloc_buffer([128, 128], dtype="int32", scope="local") X_shared = T.alloc_buffer([128, 128], dtype="int8", scope="shared") W_shared = T.alloc_buffer([128, 128], dtype="int8", scope="shared") for i0_0_i1_0_fused in T.thread_binding(1, thread="blockIdx.x"): for i0_1_i1_1_fused in T.thread_binding(512, thread="vthread.x"): for i0_2_i1_2_fused in T.thread_binding(2, thread="threadIdx.x"): for i2_0_0 in T.serial(1): for ax0_ax1_fused in T.serial(16384): with T.block("X_shared"): v0 = T.axis.spatial(128, ax0_ax1_fused // 128) v1 = T.axis.spatial(128, ax0_ax1_fused % 128) T.reads(X[v0, v1]) T.writes(X_shared[v0, v1]) T.block_attr({"meta_schedule.cooperative_fetch": 1}) X_shared[v0, v1] = X[v0, v1] for ax0_ax1_fused in T.serial(16384): with T.block("W_shared"): v0 = T.axis.spatial(128, ax0_ax1_fused // 128) v1 = T.axis.spatial(128, ax0_ax1_fused % 128) T.reads(W[v0, v1]) T.writes(W_shared[v0, v1]) T.block_attr({"meta_schedule.cooperative_fetch": 1}) W_shared[v0, v1] = W[v0, v1] for i2_0_1, i0_3, i1_3, i2_0_2, i0_4, i1_4 in T.grid(1, 2, 4, 32, 2, 1): with T.block("compute_o"): i = T.axis.spatial( 128, i0_1_i1_1_fused // 32 * 8 + i0_2_i1_2_fused * 4 + i0_3 * 2 + i0_4, ) j = T.axis.spatial(128, i1_4 + i0_1_i1_1_fused % 32 * 4 + i1_3) k_o = T.axis.reduce(32, i2_0_0 * 32 + i2_0_1 * 32 + i2_0_2) T.reads( X_shared[i, k_o * 4 : k_o * 4 + 4], W_shared[j, k_o * 4 : k_o * 4 + 4], ) T.writes(compute_local[i, j]) T.block_attr({"meta_schedule.auto_tensorize": "dp4a"}) with T.init(): with T.block("compute_init"): T.reads() T.writes(compute_local[i, j]) compute_local[i, j] = 0 for i2_1 in T.serial(4): with T.block("compute"): k_i = T.axis.reduce(4, i2_1) T.reads( compute_local[i, j], X_shared[i, k_o * 4 + k_i], W_shared[j, k_o * 4 + k_i], ) T.writes(compute_local[i, j]) T.block_attr({"meta_schedule.tiling_structure": "SSSRRSRS"}) compute_local[i, j] = compute_local[i, j] + T.cast( X_shared[i, k_o * 4 + k_i], "int32" ) * T.cast(W_shared[j, k_o * 4 + k_i], "int32") for ax0, ax1 in T.grid(4, 4): with T.block("compute_local"): v0 = T.axis.spatial( 128, i0_1_i1_1_fused // 32 * 8 + i0_2_i1_2_fused * 4 + ax0 ) v1 = T.axis.spatial(128, i0_1_i1_1_fused % 32 * 4 + ax1) T.reads(compute_local[v0, v1]) T.writes(compute[v0, v1]) compute[v0, v1] = compute_local[v0, v1] decision_0 = [ ("SamplePerfectTile", [1, 16, 2, 2, 2]), ("SamplePerfectTile", [1, 32, 1, 4, 1]), ("SamplePerfectTile", [1, 1, 32]), ("SampleCategorical", 0), ("SampleCategorical", 0), ] _check_dp4a_dense( m=128, n=128, k=128, in_dtype="int8", out_dtype="int32", expected_mods=[dp4a_dense_0], expected_decisions=[decision_0], ) def test_dp4a_dense_no_tensorize_1(): _check_dp4a_dense( m=128, n=128, k=128, in_dtype="float32", out_dtype="float32", expected_mods=None, expected_decisions=None, ) def test_dp4a_dense_no_tensorize_2(): _check_dp4a_dense( m=127, n=127, k=127, in_dtype="int8", out_dtype="int32", expected_mods=None, expected_decisions=None, ) if __name__ == "__main__": test_vnni_conv2d_nchwc() test_dp4a_dense() test_dp4a_dense_no_tensorize_1() test_dp4a_dense_no_tensorize_2()
https://github.com/zk-ml/tachikoma
tests/python/unittest/test_meta_schedule_schedule_rule_mlt_tc.py
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. # pylint: disable=missing-module-docstring,missing-function-docstring,missing-class-docstring import tvm import tvm.testing from tvm import meta_schedule as ms from tvm import te from tvm.meta_schedule.testing import te_workload from tvm.meta_schedule.testing.space_generation import ( check_sketches, generate_design_space, get_rules, ) from tvm.script import tir as T from tvm.tir.tensor_intrin.cuda import get_wmma_intrin_group def multi_level_tiling_tensor_core( *, write_reuse_scope="shared", in_dtype="float16", out_dtype="float32", trans_b=False, use_software_pipeline=False, ) -> ms.schedule_rule.ScheduleRule: assert write_reuse_scope in ["shared", "global"] if not isinstance(in_dtype, list): in_dtype = [in_dtype] if not isinstance(out_dtype, list): out_dtype = [out_dtype] if not isinstance(trans_b, list): trans_b = [trans_b] return ms.schedule_rule.MultiLevelTilingTensorCore( intrin_groups=[ get_wmma_intrin_group(write_reuse_scope, _in_dtype, _out_dtype, _trans_b) for _in_dtype in in_dtype for _out_dtype in out_dtype for _trans_b in trans_b ], structure="SSSRRSRS", tile_binds=["blockIdx.y", "blockIdx.x", "threadIdx.y"], max_innermost_factor=4, # 64 // tensor intrin size vector_load_lens=[1, 2, 3, 4, 8, 16], reuse_read=ms.schedule_rule.ReuseType( req="must", levels=[4], scope="shared", ), reuse_write=ms.schedule_rule.ReuseType( req="must" if write_reuse_scope == "shared" else "no", levels=[2], scope=write_reuse_scope, ), use_software_pipeline=use_software_pipeline, ) def test_matmul_relu(): # fmt: off @T.prim_func def matmul_relu_0(A: T.Buffer[(128, 128), "float16"], B: T.Buffer[(128, 128), "float16"], compute: T.Buffer[(128, 128), "float32"]) -> None: T.func_attr({"global_symbol": "main", "tir.noalias": True}) C_reindex_shared = T.alloc_buffer([128, 128], dtype="float32", scope="shared") C_reindex_shared_wmma_accumulator = T.alloc_buffer([128, 128], dtype="float32", scope="wmma.accumulator") A_reindex_shared = T.alloc_buffer([128, 128], dtype="float16", scope="shared") B_reindex_shared = T.alloc_buffer([128, 128], dtype="float16", scope="shared") A_reindex_shared_wmma_matrix_a = T.alloc_buffer([128, 128], dtype="float16", scope="wmma.matrix_a") B_reindex_shared_wmma_matrix_b = T.alloc_buffer([128, 128], dtype="float16", scope="wmma.matrix_b") for ax0_0_0_ax1_0_0_fused in T.thread_binding(8, thread="blockIdx.y"): for ax0_0_1_ax1_0_1_fused in T.thread_binding(2, thread="blockIdx.x"): for ax0_0_2_ax1_0_2_fused in T.thread_binding(2, thread="threadIdx.y"): for ax2_0_0 in T.serial(1): for ax0_ax1_fused in T.serial(4096): with T.block("A_reindex_shared"): v0 = T.axis.spatial(128, ax0_0_0_ax1_0_0_fused // 2 * 32 + ax0_ax1_fused // 128) v1 = T.axis.spatial(128, ax0_ax1_fused % 128) T.reads(A[v0, v1]) T.writes(A_reindex_shared[v0, v1]) T.block_attr({"buffer_dim_align":[[0, 0, 32, 8]], "meta_schedule.cooperative_fetch":8}) A_reindex_shared[v0, v1] = A[v0, v1] for ax0_ax1_fused in T.serial(4096): with T.block("B_reindex_shared"): v0 = T.axis.spatial(128, ax0_ax1_fused // 32) v1 = T.axis.spatial(128, ax0_0_0_ax1_0_0_fused % 2 * 64 + ax0_0_1_ax1_0_1_fused * 32 + ax0_ax1_fused % 32) T.reads(B[v0, v1]) T.writes(B_reindex_shared[v0, v1]) T.block_attr({"buffer_dim_align":[[0, 0, 32, 8]], "meta_schedule.cooperative_fetch":1}) B_reindex_shared[v0, v1] = B[v0, v1] for ax2_0_1 in T.serial(4): for ax0_0, ax1_0 in T.grid(2, 2): with T.block("A_reindex_shared_wmma.matrix_a_o"): v0_o = T.axis.spatial(8, ax0_0_0_ax1_0_0_fused // 2 * 2 + ax0_0) v1_o = T.axis.spatial(8, ax2_0_1 * 2 + ax1_0) T.reads(A_reindex_shared[v0_o * 16 : v0_o * 16 + 16, v1_o * 16 : v1_o * 16 + 16]) T.writes(A_reindex_shared_wmma_matrix_a[v0_o * 16 : v0_o * 16 + 16, v1_o * 16 : v1_o * 16 + 16]) T.block_attr({"meta_schedule.auto_tensorize":"wmma_load_16x16x16_f16_a"}) for ax0_1, ax1_1 in T.grid(16, 16): with T.block("A_reindex_shared_wmma.matrix_a"): v0_i, v1_i = T.axis.remap("SS", [ax0_1, ax1_1]) T.reads(A_reindex_shared[v0_o * 16 + v0_i, v1_o * 16 + v1_i]) T.writes(A_reindex_shared_wmma_matrix_a[v0_o * 16 + v0_i, v1_o * 16 + v1_i]) A_reindex_shared_wmma_matrix_a[v0_o * 16 + v0_i, v1_o * 16 + v1_i] = A_reindex_shared[v0_o * 16 + v0_i, v1_o * 16 + v1_i] for ax0_0, ax1_0 in T.grid(2, 1): with T.block("B_reindex_shared_wmma.matrix_b_o"): v0_o = T.axis.spatial(8, ax2_0_1 * 2 + ax0_0) v1_o = T.axis.spatial(8, ax0_0_0_ax1_0_0_fused % 2 * 4 + ax0_0_1_ax1_0_1_fused * 2 + ax0_0_2_ax1_0_2_fused) T.reads(B_reindex_shared[v0_o * 16 : v0_o * 16 + 16, v1_o * 16 : v1_o * 16 + 16]) T.writes(B_reindex_shared_wmma_matrix_b[v0_o * 16 : v0_o * 16 + 16, v1_o * 16 : v1_o * 16 + 16]) T.block_attr({"meta_schedule.auto_tensorize":"wmma_load_16x16x16_f16_b"}) for ax0_1, ax1_1 in T.grid(16, 16): with T.block("B_reindex_shared_wmma.matrix_b"): v0_i, v1_i = T.axis.remap("SS", [ax0_1, ax1_1]) T.reads(B_reindex_shared[v0_o * 16 + v0_i, v1_o * 16 + v1_i]) T.writes(B_reindex_shared_wmma_matrix_b[v0_o * 16 + v0_i, v1_o * 16 + v1_i]) B_reindex_shared_wmma_matrix_b[v0_o * 16 + v0_i, v1_o * 16 + v1_i] = B_reindex_shared[v0_o * 16 + v0_i, v1_o * 16 + v1_i] for ax0_0_3, ax1_0_3, ax2_0_2, ax0_0_4, ax1_0_4 in T.grid(1, 1, 2, 2, 1): with T.block("C_o"): v0_o = T.axis.spatial(8, ax0_0_0_ax1_0_0_fused // 2 * 2 + ax0_0_3 * 2 + ax0_0_4) v1_o = T.axis.spatial(8, ax1_0_4 + ax0_0_0_ax1_0_0_fused % 2 * 4 + ax0_0_1_ax1_0_1_fused * 2 + ax0_0_2_ax1_0_2_fused + ax1_0_3) v2_o = T.axis.reduce(8, ax2_0_0 * 8 + ax2_0_1 * 2 + ax2_0_2) T.reads(A_reindex_shared_wmma_matrix_a[v0_o * 16 : v0_o * 16 + 16, v2_o * 16 : v2_o * 16 + 16], B_reindex_shared_wmma_matrix_b[v2_o * 16 : v2_o * 16 + 16, v1_o * 16 : v1_o * 16 + 16]) T.writes(C_reindex_shared_wmma_accumulator[v0_o * 16 : v0_o * 16 + 16, v1_o * 16 : v1_o * 16 + 16]) T.block_attr({"meta_schedule.auto_tensorize":"wmma_sync_16x16x16_f16f16f32", "meta_schedule.auto_tensorize_init":"wmma_fill_16x16x16_f32", "warp_execution":1}) with T.init(): for ax0_1, ax1_1 in T.grid(16, 16): with T.block("C_init"): v0_i_init, v1_i_init = T.axis.remap("SS", [ax0_1, ax1_1]) T.reads() T.writes(C_reindex_shared_wmma_accumulator[v0_o * 16 + v0_i_init, v1_o * 16 + v1_i_init]) C_reindex_shared_wmma_accumulator[v0_o * 16 + v0_i_init, v1_o * 16 + v1_i_init] = T.float32(0) for ax0_1, ax1_1, ax2_1 in T.grid(16, 16, 16): with T.block("C"): v0_i, v1_i, v2_i = T.axis.remap("SSR", [ax0_1, ax1_1, ax2_1]) T.reads(C_reindex_shared_wmma_accumulator[v0_o * 16 + v0_i, v1_o * 16 + v1_i], A_reindex_shared_wmma_matrix_a[v0_o * 16 + v0_i, v2_o * 16 + v2_i], B_reindex_shared_wmma_matrix_b[v2_o * 16 + v2_i, v1_o * 16 + v1_i]) T.writes(C_reindex_shared_wmma_accumulator[v0_o * 16 + v0_i, v1_o * 16 + v1_i]) T.block_attr({"meta_schedule.tiling_structure":"SSSRRSRS"}) C_reindex_shared_wmma_accumulator[v0_o * 16 + v0_i, v1_o * 16 + v1_i] = C_reindex_shared_wmma_accumulator[v0_o * 16 + v0_i, v1_o * 16 + v1_i] + T.cast(A_reindex_shared_wmma_matrix_a[v0_o * 16 + v0_i, v2_o * 16 + v2_i], "float32") * T.cast(B_reindex_shared_wmma_matrix_b[v2_o * 16 + v2_i, v1_o * 16 + v1_i], "float32") for ax0_0, ax1_0 in T.grid(2, 1): with T.block("C_reindex_shared_wmma.accumulator_o"): v0_o = T.axis.spatial(8, ax0_0_0_ax1_0_0_fused // 2 * 2 + ax0_0) v1_o = T.axis.spatial(8, ax0_0_0_ax1_0_0_fused % 2 * 4 + ax0_0_1_ax1_0_1_fused * 2 + ax0_0_2_ax1_0_2_fused) T.reads(C_reindex_shared_wmma_accumulator[v0_o * 16 : v0_o * 16 + 16, v1_o * 16 : v1_o * 16 + 16]) T.writes(C_reindex_shared[v0_o * 16 : v0_o * 16 + 16, v1_o * 16 : v1_o * 16 + 16]) T.block_attr({"meta_schedule.auto_tensorize":"wmma_store_16x16x16_f32_shared"}) for ax0_1, ax1_1 in T.grid(16, 16): with T.block("C_reindex_shared_wmma.accumulator"): v0_i, v1_i = T.axis.remap("SS", [ax0_1, ax1_1]) T.reads(C_reindex_shared_wmma_accumulator[v0_o * 16 + v0_i, v1_o * 16 + v1_i]) T.writes(C_reindex_shared[v0_o * 16 + v0_i, v1_o * 16 + v1_i]) C_reindex_shared[v0_o * 16 + v0_i, v1_o * 16 + v1_i] = C_reindex_shared_wmma_accumulator[v0_o * 16 + v0_i, v1_o * 16 + v1_i] for ax0_ax1_fused in T.serial(1024): with T.block("C_reindex_shared"): v0 = T.axis.spatial(128, ax0_0_0_ax1_0_0_fused // 2 * 32 + ax0_ax1_fused // 32) v1 = T.axis.spatial(128, ax0_0_0_ax1_0_0_fused % 2 * 64 + ax0_0_1_ax1_0_1_fused * 32 + ax0_ax1_fused % 32) T.reads(C_reindex_shared[v0, v1]) T.writes(compute[v0, v1]) T.block_attr({"meta_schedule.cooperative_fetch":4}) compute[v0, v1] = T.max(C_reindex_shared[v0, v1], T.float32(0)) # fmt: on decision_0 = [ ("SamplePerfectTile", [4, 1, 1, 1, 2]), ("SamplePerfectTile", [2, 2, 2, 1, 1]), ("SamplePerfectTile", [1, 4, 2]), ("SampleCategorical", 3), ("SampleCategorical", 3), ("SampleCategorical", 0), ] mod = te.create_prim_func( te_workload.matmul_relu( n=128, m=128, k=128, in_dtype="float16", out_dtype="float32", ) ) actual = generate_design_space( kind="cuda", mod=mod, target=tvm.target.Target("cuda"), types=None, sch_rules=[ multi_level_tiling_tensor_core(), ] + get_rules(kind="cuda", types=ms.schedule_rule.AutoInline), ) check_sketches( mod, sketches=actual, expected_mods=[matmul_relu_0], expected_decisions=[decision_0], ) def test_matmul_relu_with_fallback(): # fmt: off @T.prim_func def matmul_relu_fallback_0(A: T.Buffer[(128, 128), "float16"], B: T.Buffer[(128, 128), "float16"], compute: T.Buffer[(128, 128), "float32"]) -> None: # function attr dict T.func_attr({"global_symbol": "main", "tir.noalias": True}) # body # with T.block("root") C_reindex_shared = T.alloc_buffer([128, 128], dtype="float32", scope="shared") C_reindex_shared_wmma_accumulator = T.alloc_buffer([128, 128], dtype="float32", scope="wmma.accumulator") A_reindex_shared = T.alloc_buffer([128, 128], dtype="float16", scope="shared") B_reindex_shared = T.alloc_buffer([128, 128], dtype="float16", scope="shared") A_reindex_shared_wmma_matrix_a = T.alloc_buffer([128, 128], dtype="float16", scope="wmma.matrix_a") B_reindex_shared_wmma_matrix_b = T.alloc_buffer([128, 128], dtype="float16", scope="wmma.matrix_b") for ax0_0_0_ax1_0_0_fused in T.thread_binding(2, thread="blockIdx.y"): for ax0_0_1_ax1_0_1_fused in T.thread_binding(2, thread="blockIdx.x"): for ax0_0_2_ax1_0_2_fused in T.thread_binding(2, thread="threadIdx.y"): for ax2_0_0 in T.serial(2): for ax0_ax1_fused in T.serial(2048): with T.block("A_reindex_shared"): v0 = T.axis.spatial(128, ax0_0_0_ax1_0_0_fused * 64 + ax0_0_1_ax1_0_1_fused * 32 + ax0_ax1_fused // 64) v1 = T.axis.spatial(128, ax2_0_0 * 64 + ax0_ax1_fused % 64) T.reads(A[v0, v1]) T.writes(A_reindex_shared[v0, v1]) T.block_attr({"buffer_dim_align":[[0, 0, 32, 8]], "meta_schedule.cooperative_fetch":4}) A_reindex_shared[v0, v1] = A[v0, v1] for ax0_ax1_fused in T.serial(8192): with T.block("B_reindex_shared"): v0 = T.axis.spatial(128, ax2_0_0 * 64 + ax0_ax1_fused // 128) v1 = T.axis.spatial(128, ax0_ax1_fused % 128) T.reads(B[v0, v1]) T.writes(B_reindex_shared[v0, v1]) T.block_attr({"buffer_dim_align":[[0, 0, 32, 8]], "meta_schedule.cooperative_fetch":2}) B_reindex_shared[v0, v1] = B[v0, v1] for ax2_0_1 in T.serial(1): for ax0_0, ax1_0 in T.grid(2, 4): with T.block("A_reindex_shared_wmma.matrix_a_o"): v0_o = T.axis.spatial(8, ax0_0_0_ax1_0_0_fused * 4 + ax0_0_1_ax1_0_1_fused * 2 + ax0_0) v1_o = T.axis.spatial(8, ax2_0_0 * 4 + ax1_0) T.reads(A_reindex_shared[v0_o * 16 : v0_o * 16 + 16, v1_o * 16 : v1_o * 16 + 16]) T.writes(A_reindex_shared_wmma_matrix_a[v0_o * 16 : v0_o * 16 + 16, v1_o * 16 : v1_o * 16 + 16]) T.block_attr({"meta_schedule.auto_tensorize":"wmma_load_16x16x16_f16_a"}) for ax0_1, ax1_1 in T.grid(16, 16): with T.block("A_reindex_shared_wmma.matrix_a"): v0_i, v1_i = T.axis.remap("SS", [ax0_1, ax1_1]) T.reads(A_reindex_shared[v0_o * 16 + v0_i, v1_o * 16 + v1_i]) T.writes(A_reindex_shared_wmma_matrix_a[v0_o * 16 + v0_i, v1_o * 16 + v1_i]) A_reindex_shared_wmma_matrix_a[v0_o * 16 + v0_i, v1_o * 16 + v1_i] = A_reindex_shared[v0_o * 16 + v0_i, v1_o * 16 + v1_i] for ax0_0, ax1_0 in T.grid(4, 4): with T.block("B_reindex_shared_wmma.matrix_b_o"): v0_o = T.axis.spatial(8, ax2_0_0 * 4 + ax0_0) v1_o = T.axis.spatial(8, ax0_0_2_ax1_0_2_fused * 4 + ax1_0) T.reads(B_reindex_shared[v0_o * 16 : v0_o * 16 + 16, v1_o * 16 : v1_o * 16 + 16]) T.writes(B_reindex_shared_wmma_matrix_b[v0_o * 16 : v0_o * 16 + 16, v1_o * 16 : v1_o * 16 + 16]) T.block_attr({"meta_schedule.auto_tensorize":"wmma_load_16x16x16_f16_b"}) for ax0_1, ax1_1 in T.grid(16, 16): with T.block("B_reindex_shared_wmma.matrix_b"): v0_i, v1_i = T.axis.remap("SS", [ax0_1, ax1_1]) T.reads(B_reindex_shared[v0_o * 16 + v0_i, v1_o * 16 + v1_i]) T.writes(B_reindex_shared_wmma_matrix_b[v0_o * 16 + v0_i, v1_o * 16 + v1_i]) B_reindex_shared_wmma_matrix_b[v0_o * 16 + v0_i, v1_o * 16 + v1_i] = B_reindex_shared[v0_o * 16 + v0_i, v1_o * 16 + v1_i] for ax0_0_3, ax1_0_3, ax2_0_2, ax0_0_4, ax1_0_4 in T.grid(1, 1, 4, 2, 4): with T.block("C_o"): v0_o = T.axis.spatial(8, ax0_0_0_ax1_0_0_fused * 4 + ax0_0_1_ax1_0_1_fused * 2 + ax0_0_3 * 2 + ax0_0_4) v1_o = T.axis.spatial(8, ax0_0_2_ax1_0_2_fused * 4 + ax1_0_3 * 4 + ax1_0_4) v2_o = T.axis.reduce(8, ax2_0_0 * 4 + ax2_0_1 * 4 + ax2_0_2) T.reads(A_reindex_shared_wmma_matrix_a[v0_o * 16 : v0_o * 16 + 16, v2_o * 16 : v2_o * 16 + 16], B_reindex_shared_wmma_matrix_b[v2_o * 16 : v2_o * 16 + 16, v1_o * 16 : v1_o * 16 + 16]) T.writes(C_reindex_shared_wmma_accumulator[v0_o * 16 : v0_o * 16 + 16, v1_o * 16 : v1_o * 16 + 16]) T.block_attr({"meta_schedule.auto_tensorize":"wmma_sync_16x16x16_f16f16f32", "meta_schedule.auto_tensorize_init":"wmma_fill_16x16x16_f32", "warp_execution":1}) with T.init(): for ax0_1, ax1_1 in T.grid(16, 16): with T.block("C_init"): v0_i_init, v1_i_init = T.axis.remap("SS", [ax0_1, ax1_1]) T.reads() T.writes(C_reindex_shared_wmma_accumulator[v0_o * 16 + v0_i_init, v1_o * 16 + v1_i_init]) C_reindex_shared_wmma_accumulator[v0_o * 16 + v0_i_init, v1_o * 16 + v1_i_init] = T.float32(0) for ax0_1, ax1_1, ax2_1 in T.grid(16, 16, 16): with T.block("C"): v0_i, v1_i, v2_i = T.axis.remap("SSR", [ax0_1, ax1_1, ax2_1]) T.reads(C_reindex_shared_wmma_accumulator[v0_o * 16 + v0_i, v1_o * 16 + v1_i], A_reindex_shared_wmma_matrix_a[v0_o * 16 + v0_i, v2_o * 16 + v2_i], B_reindex_shared_wmma_matrix_b[v2_o * 16 + v2_i, v1_o * 16 + v1_i]) T.writes(C_reindex_shared_wmma_accumulator[v0_o * 16 + v0_i, v1_o * 16 + v1_i]) T.block_attr({"meta_schedule.tiling_structure":"SSSRRSRS"}) C_reindex_shared_wmma_accumulator[v0_o * 16 + v0_i, v1_o * 16 + v1_i] = C_reindex_shared_wmma_accumulator[v0_o * 16 + v0_i, v1_o * 16 + v1_i] + T.cast(A_reindex_shared_wmma_matrix_a[v0_o * 16 + v0_i, v2_o * 16 + v2_i], "float32") * T.cast(B_reindex_shared_wmma_matrix_b[v2_o * 16 + v2_i, v1_o * 16 + v1_i], "float32") for ax0_0, ax1_0 in T.grid(2, 4): with T.block("C_reindex_shared_wmma.accumulator_o"): v0_o = T.axis.spatial(8, ax0_0_0_ax1_0_0_fused * 4 + ax0_0_1_ax1_0_1_fused * 2 + ax0_0) v1_o = T.axis.spatial(8, ax0_0_2_ax1_0_2_fused * 4 + ax1_0) T.reads(C_reindex_shared_wmma_accumulator[v0_o * 16 : v0_o * 16 + 16, v1_o * 16 : v1_o * 16 + 16]) T.writes(C_reindex_shared[v0_o * 16 : v0_o * 16 + 16, v1_o * 16 : v1_o * 16 + 16]) T.block_attr({"meta_schedule.auto_tensorize":"wmma_store_16x16x16_f32_shared"}) for ax0_1, ax1_1 in T.grid(16, 16): with T.block("C_reindex_shared_wmma.accumulator"): v0_i, v1_i = T.axis.remap("SS", [ax0_1, ax1_1]) T.reads(C_reindex_shared_wmma_accumulator[v0_o * 16 + v0_i, v1_o * 16 + v1_i]) T.writes(C_reindex_shared[v0_o * 16 + v0_i, v1_o * 16 + v1_i]) C_reindex_shared[v0_o * 16 + v0_i, v1_o * 16 + v1_i] = C_reindex_shared_wmma_accumulator[v0_o * 16 + v0_i, v1_o * 16 + v1_i] for ax0_ax1_fused in T.serial(4096): with T.block("C_reindex_shared"): v0 = T.axis.spatial(128, ax0_0_0_ax1_0_0_fused * 64 + ax0_0_1_ax1_0_1_fused * 32 + ax0_ax1_fused // 128) v1 = T.axis.spatial(128, ax0_ax1_fused % 128) T.reads(C_reindex_shared[v0, v1]) T.writes(compute[v0, v1]) T.block_attr({"meta_schedule.cooperative_fetch":4}) compute[v0, v1] = T.max(C_reindex_shared[v0, v1], T.float32(0)) # fmt: on decision_0 = [ ("SamplePerfectTile", [2, 2, 1, 1, 2]), ("SamplePerfectTile", [1, 1, 2, 1, 4]), ("SamplePerfectTile", [2, 1, 4]), ("SampleCategorical", 3), ("SampleCategorical", 2), ("SampleCategorical", 1), ] mod = te.create_prim_func( te_workload.matmul_relu( n=128, m=128, k=128, in_dtype="float16", out_dtype="float32", ) ) actual = generate_design_space( kind="cuda", mod=mod, target=tvm.target.Target("cuda"), types=None, sch_rules=[ multi_level_tiling_tensor_core(), ] + get_rules( "cuda", ( ms.schedule_rule.MultiLevelTiling, ms.schedule_rule.AutoInline, ), ), ) check_sketches( mod, sketches=actual, expected_mods=[matmul_relu_fallback_0], expected_decisions=[decision_0], ) def test_conv2d(): # fmt: off @T.prim_func def conv2d_0(inputs: T.Buffer[(1, 16, 16, 32), "float16"], weight: T.Buffer[(3, 3, 32, 32), "float16"], conv2d_nhwc: T.Buffer[(1, 16, 16, 32), "float32"]) -> None: T.func_attr({"global_symbol": "main", "tir.noalias": True}) PadInput = T.alloc_buffer([1, 18, 18, 32], dtype="float16") conv2d_nhwc_reindex_shared = T.alloc_buffer([256, 32], dtype="float32", scope="shared") conv2d_nhwc_reindex_shared_wmma_accumulator = T.alloc_buffer([256, 32], dtype="float32", scope="wmma.accumulator") PadInput_reindex_shared = T.alloc_buffer([256, 288], dtype="float16", scope="shared") weight_reindex_shared = T.alloc_buffer([288, 32], dtype="float16", scope="shared") PadInput_reindex_shared_wmma_matrix_a = T.alloc_buffer([256, 288], dtype="float16", scope="wmma.matrix_a") weight_reindex_shared_wmma_matrix_b = T.alloc_buffer([288, 32], dtype="float16", scope="wmma.matrix_b") for i0, i1, i2, i3 in T.grid(1, 18, 18, 32): with T.block("PadInput"): i0_1, i1_1, i2_1, i3_1 = T.axis.remap("SSSS", [i0, i1, i2, i3]) T.reads(inputs[i0_1, i1_1 - 1, i2_1 - 1, i3_1]) T.writes(PadInput[i0_1, i1_1, i2_1, i3_1]) PadInput[i0_1, i1_1, i2_1, i3_1] = T.if_then_else(1 <= i1_1 and i1_1 < 17 and 1 <= i2_1 and i2_1 < 17, inputs[i0_1, i1_1 - 1, i2_1 - 1, i3_1], T.float16(0), dtype="float16") for ax0_0_0_ax1_0_0_fused in T.thread_binding(2, thread="blockIdx.y"): for ax0_0_1_ax1_0_1_fused in T.thread_binding(16, thread="blockIdx.x"): for ax0_0_2_ax1_0_2_fused in T.thread_binding(1, thread="threadIdx.y"): for ax2_0_0 in T.serial(1): for ax0_ax1_fused in T.serial(4608): with T.block("PadInput_reindex_shared"): v0 = T.axis.spatial(256, ax0_0_1_ax1_0_1_fused * 16 + ax0_ax1_fused // 288) v1 = T.axis.spatial(288, ax0_ax1_fused % 288) T.reads(PadInput[v0 // 256, v1 // 96 + v0 // 16, v1 % 96 // 32 + v0 % 16, v1 % 32]) T.writes(PadInput_reindex_shared[v0, v1]) T.block_attr({"buffer_dim_align":[[0, 0, 32, 8]], "meta_schedule.cooperative_fetch":2}) PadInput_reindex_shared[v0, v1] = PadInput[v0 // 256, v1 // 96 + v0 // 16, v1 % 96 // 32 + v0 % 16, v1 % 32] for ax0_ax1_fused in T.serial(4608): with T.block("weight_reindex_shared"): v0 = T.axis.spatial(288, ax0_ax1_fused // 16) v1 = T.axis.spatial(32, ax0_0_0_ax1_0_0_fused * 16 + ax0_ax1_fused % 16) T.reads(weight[v0 // 96, v0 % 96 // 32, v0 % 32, v1]) T.writes(weight_reindex_shared[v0, v1]) T.block_attr({"buffer_dim_align":[[0, 0, 32, 8]], "meta_schedule.cooperative_fetch":8}) weight_reindex_shared[v0, v1] = weight[v0 // 96, v0 % 96 // 32, v0 % 32, v1] for ax2_0_1 in T.serial(18): for ax0_0, ax1_0 in T.grid(1, 1): with T.block("PadInput_reindex_shared_wmma.matrix_a_o"): v0_o, v1_o = T.axis.remap("SS", [ax0_0_1_ax1_0_1_fused, ax2_0_1]) T.reads(PadInput_reindex_shared[v0_o * 16 : v0_o * 16 + 16, v1_o * 16 : v1_o * 16 + 16]) T.writes(PadInput_reindex_shared_wmma_matrix_a[v0_o * 16 : v0_o * 16 + 16, v1_o * 16 : v1_o * 16 + 16]) T.block_attr({"meta_schedule.auto_tensorize":"wmma_load_16x16x16_f16_a"}) for ax0_1, ax1_1 in T.grid(16, 16): with T.block("PadInput_reindex_shared_wmma.matrix_a"): v0_i, v1_i = T.axis.remap("SS", [ax0_1, ax1_1]) T.reads(PadInput_reindex_shared[v0_o * 16 + v0_i, v1_o * 16 + v1_i]) T.writes(PadInput_reindex_shared_wmma_matrix_a[v0_o * 16 + v0_i, v1_o * 16 + v1_i]) PadInput_reindex_shared_wmma_matrix_a[v0_o * 16 + v0_i, v1_o * 16 + v1_i] = PadInput_reindex_shared[v0_o * 16 + v0_i, v1_o * 16 + v1_i] for ax0_0, ax1_0 in T.grid(1, 1): with T.block("weight_reindex_shared_wmma.matrix_b_o"): v0_o, v1_o = T.axis.remap("SS", [ax2_0_1, ax0_0_0_ax1_0_0_fused]) T.reads(weight_reindex_shared[v0_o * 16 : v0_o * 16 + 16, v1_o * 16 : v1_o * 16 + 16]) T.writes(weight_reindex_shared_wmma_matrix_b[v0_o * 16 : v0_o * 16 + 16, v1_o * 16 : v1_o * 16 + 16]) T.block_attr({"meta_schedule.auto_tensorize":"wmma_load_16x16x16_f16_b"}) for ax0_1, ax1_1 in T.grid(16, 16): with T.block("weight_reindex_shared_wmma.matrix_b"): v0_i, v1_i = T.axis.remap("SS", [ax0_1, ax1_1]) T.reads(weight_reindex_shared[v0_o * 16 + v0_i, v1_o * 16 + v1_i]) T.writes(weight_reindex_shared_wmma_matrix_b[v0_o * 16 + v0_i, v1_o * 16 + v1_i]) weight_reindex_shared_wmma_matrix_b[v0_o * 16 + v0_i, v1_o * 16 + v1_i] = weight_reindex_shared[v0_o * 16 + v0_i, v1_o * 16 + v1_i] for ax0_0_3, ax1_0_3, ax2_0_2, ax0_0_4, ax1_0_4 in T.grid(1, 1, 1, 1, 1): with T.block("conv2d_nhwc_o"): v0_o = T.axis.spatial(16, ax0_0_4 + ax0_0_1_ax1_0_1_fused + ax0_0_3) v1_o = T.axis.spatial(2, ax0_0_0_ax1_0_0_fused + ax1_0_3 + ax1_0_4) v2_o = T.axis.reduce(18, ax2_0_0 * 18 + ax2_0_1 + ax2_0_2) T.reads(PadInput_reindex_shared_wmma_matrix_a[v0_o * 16 : v0_o * 16 + 16, v2_o * 16 : v2_o * 16 + 16], weight_reindex_shared_wmma_matrix_b[v2_o * 16 : v2_o * 16 + 16, v1_o * 16 : v1_o * 16 + 16]) T.writes(conv2d_nhwc_reindex_shared_wmma_accumulator[v0_o * 16 : v0_o * 16 + 16, v1_o * 16 : v1_o * 16 + 16]) T.block_attr({"meta_schedule.auto_tensorize":"wmma_sync_16x16x16_f16f16f32", "meta_schedule.auto_tensorize_init":"wmma_fill_16x16x16_f32", "warp_execution":1}) with T.init(): for ax0_1, ax1_1 in T.grid(16, 16): with T.block("conv2d_nhwc_init"): v0_i_init, v1_i_init = T.axis.remap("SS", [ax0_1, ax1_1]) T.reads() T.writes(conv2d_nhwc_reindex_shared_wmma_accumulator[v0_o * 16 + v0_i_init, v1_o * 16 + v1_i_init]) conv2d_nhwc_reindex_shared_wmma_accumulator[v0_o * 16 + v0_i_init, v1_o * 16 + v1_i_init] = T.float32(0) for ax0_1, ax1_1, ax2_1 in T.grid(16, 16, 16): with T.block("conv2d_nhwc"): v0_i, v1_i, v2_i = T.axis.remap("SSR", [ax0_1, ax1_1, ax2_1]) T.reads(conv2d_nhwc_reindex_shared_wmma_accumulator[v0_o * 16 + v0_i, v1_o * 16 + v1_i], PadInput_reindex_shared_wmma_matrix_a[v0_o * 16 + v0_i, v2_o * 16 + v2_i], weight_reindex_shared_wmma_matrix_b[v2_o * 16 + v2_i, v1_o * 16 + v1_i]) T.writes(conv2d_nhwc_reindex_shared_wmma_accumulator[v0_o * 16 + v0_i, v1_o * 16 + v1_i]) T.block_attr({"meta_schedule.tiling_structure":"SSSRRSRS"}) conv2d_nhwc_reindex_shared_wmma_accumulator[v0_o * 16 + v0_i, v1_o * 16 + v1_i] = conv2d_nhwc_reindex_shared_wmma_accumulator[v0_o * 16 + v0_i, v1_o * 16 + v1_i] + T.cast(PadInput_reindex_shared_wmma_matrix_a[v0_o * 16 + v0_i, v2_o * 16 + v2_i], "float32") * T.cast(weight_reindex_shared_wmma_matrix_b[v2_o * 16 + v2_i, v1_o * 16 + v1_i], "float32") for ax0_0, ax1_0 in T.grid(1, 1): with T.block("conv2d_nhwc_reindex_shared_wmma.accumulator_o"): v0_o, v1_o = T.axis.remap("SS", [ax0_0_1_ax1_0_1_fused, ax0_0_0_ax1_0_0_fused]) T.reads(conv2d_nhwc_reindex_shared_wmma_accumulator[v0_o * 16 : v0_o * 16 + 16, v1_o * 16 : v1_o * 16 + 16]) T.writes(conv2d_nhwc_reindex_shared[v0_o * 16 : v0_o * 16 + 16, v1_o * 16 : v1_o * 16 + 16]) T.block_attr({"meta_schedule.auto_tensorize":"wmma_store_16x16x16_f32_shared"}) for ax0_1, ax1_1 in T.grid(16, 16): with T.block("conv2d_nhwc_reindex_shared_wmma.accumulator"): v0_i, v1_i = T.axis.remap("SS", [ax0_1, ax1_1]) T.reads(conv2d_nhwc_reindex_shared_wmma_accumulator[v0_o * 16 + v0_i, v1_o * 16 + v1_i]) T.writes(conv2d_nhwc_reindex_shared[v0_o * 16 + v0_i, v1_o * 16 + v1_i]) conv2d_nhwc_reindex_shared[v0_o * 16 + v0_i, v1_o * 16 + v1_i] = conv2d_nhwc_reindex_shared_wmma_accumulator[v0_o * 16 + v0_i, v1_o * 16 + v1_i] for ax0_ax1_fused in T.serial(256): with T.block("conv2d_nhwc_reindex_shared"): v0 = T.axis.spatial(256, ax0_0_1_ax1_0_1_fused * 16 + ax0_ax1_fused // 16) v1 = T.axis.spatial(32, ax0_0_0_ax1_0_0_fused * 16 + ax0_ax1_fused % 16) T.reads(conv2d_nhwc_reindex_shared[v0, v1]) T.writes(conv2d_nhwc[v0 // 256, v0 // 16, v0 % 16, v1]) T.block_attr({"meta_schedule.cooperative_fetch":3}) conv2d_nhwc[v0 // 256, v0 // 16, v0 % 16, v1] = conv2d_nhwc_reindex_shared[v0, v1] # fmt: on decision_0 = [ ("SamplePerfectTile", [1, 16, 1, 1, 1]), ("SamplePerfectTile", [2, 1, 1, 1, 1]), ("SamplePerfectTile", [1, 18, 1]), ("SampleCategorical", 2), ("SampleCategorical", 1), ("SampleCategorical", 3), ] mod = te.create_prim_func( te_workload.conv2d_nhwc( N=1, H=16, W=16, CI=32, CO=32, kernel_size=3, stride=1, padding=1, in_dtype="float16", out_dtype="float32", ) ) actual = generate_design_space( kind="cuda", mod=mod, target=tvm.target.Target("cuda"), types=None, sch_rules=[ multi_level_tiling_tensor_core(), ], ) check_sketches( mod, sketches=actual, expected_mods=[conv2d_0], expected_decisions=[decision_0], ) # Test adding inapplicable tensor intrinsics doesn't change the search space # This test case uses the same workload, decision and the expected sketch as above actual = generate_design_space( kind="cuda", mod=mod, target=tvm.target.Target("cuda"), types=None, sch_rules=[ multi_level_tiling_tensor_core( in_dtype="float16", out_dtype=["float16", "float32"], ), ], ) check_sketches( mod, sketches=actual, expected_mods=[conv2d_0], expected_decisions=[decision_0], ) def test_matmul_relu_pipeline(): # fmt: off @T.prim_func def matmul_relu_pipeline_0(A: T.Buffer[(128, 128), "float16"], B: T.Buffer[(128, 128), "float16"], compute: T.Buffer[(128, 128), "float32"]) -> None: # function attr dict T.func_attr({"global_symbol": "main", "tir.noalias": True}) # body # with T.block("root") C = T.alloc_buffer([128, 128], dtype="float32") C_reindex_shared = T.alloc_buffer([128, 128], dtype="float32", scope="shared") C_reindex_shared_wmma_accumulator = T.alloc_buffer([128, 128], dtype="float32", scope="wmma.accumulator") A_reindex_shared = T.alloc_buffer([128, 128], dtype="float16", scope="shared") B_reindex_shared = T.alloc_buffer([128, 128], dtype="float16", scope="shared") A_reindex_shared_wmma_matrix_a = T.alloc_buffer([128, 128], dtype="float16", scope="wmma.matrix_a") B_reindex_shared_wmma_matrix_b = T.alloc_buffer([128, 128], dtype="float16", scope="wmma.matrix_b") for ax0_0_0_ax1_0_0_fused in T.thread_binding(1, thread="blockIdx.y"): for ax0_0_1_ax1_0_1_fused in T.thread_binding(16, thread="blockIdx.x"): for ax0_0_2_ax1_0_2_fused in T.thread_binding(1, thread="threadIdx.y"): for ax2_0_0 in T.serial(4, annotations={"software_pipeline_order":[0, 3, 1, 4, 5, 2, 6], "software_pipeline_stage":[0, 0, 0, 0, 0, 1, 1]}): for ax0_ax1_fused in T.serial(1024): with T.block("A_reindex_shared"): v0 = T.axis.spatial(128, ax0_0_1_ax1_0_1_fused // 4 * 32 + ax0_ax1_fused // 32) v1 = T.axis.spatial(128, ax2_0_0 * 32 + ax0_ax1_fused % 32) T.reads(A[v0, v1]) T.writes(A_reindex_shared[v0, v1]) T.block_attr({"buffer_dim_align":[[0, 0, 32, 8]], "double_buffer_scope":0, "meta_schedule.cooperative_fetch":4, "tir.manifest_shared_memory_local_stage":1}) A_reindex_shared[v0, v1] = A[v0, v1] for ax0_ax1_fused in T.serial(1024): with T.block("B_reindex_shared"): v0 = T.axis.spatial(128, ax2_0_0 * 32 + ax0_ax1_fused // 32) v1 = T.axis.spatial(128, ax0_0_1_ax1_0_1_fused % 4 * 32 + ax0_ax1_fused % 32) T.reads(B[v0, v1]) T.writes(B_reindex_shared[v0, v1]) T.block_attr({"buffer_dim_align":[[0, 0, 32, 8]], "double_buffer_scope":0, "meta_schedule.cooperative_fetch":2, "tir.manifest_shared_memory_local_stage":1}) B_reindex_shared[v0, v1] = B[v0, v1] for ax2_0_1 in T.serial(2, annotations={"software_pipeline_order":[0, 1, 2], "software_pipeline_stage":[0, 0, 1]}): for ax0_0, ax1_0 in T.grid(2, 1): with T.block("A_reindex_shared_wmma.matrix_a_o"): v0_o = T.axis.spatial(8, ax0_0_1_ax1_0_1_fused // 4 * 2 + ax0_0) v1_o = T.axis.spatial(8, ax2_0_0 * 2 + ax2_0_1) T.reads(A_reindex_shared[v0_o * 16 : v0_o * 16 + 16, v1_o * 16 : v1_o * 16 + 16]) T.writes(A_reindex_shared_wmma_matrix_a[v0_o * 16 : v0_o * 16 + 16, v1_o * 16 : v1_o * 16 + 16]) T.block_attr({"meta_schedule.auto_tensorize":"wmma_load_16x16x16_f16_a"}) for ax0_1, ax1_1 in T.grid(16, 16): with T.block("A_reindex_shared_wmma.matrix_a"): v0_i, v1_i = T.axis.remap("SS", [ax0_1, ax1_1]) T.reads(A_reindex_shared[v0_o * 16 + v0_i, v1_o * 16 + v1_i]) T.writes(A_reindex_shared_wmma_matrix_a[v0_o * 16 + v0_i, v1_o * 16 + v1_i]) A_reindex_shared_wmma_matrix_a[v0_o * 16 + v0_i, v1_o * 16 + v1_i] = A_reindex_shared[v0_o * 16 + v0_i, v1_o * 16 + v1_i] for ax0_0, ax1_0 in T.grid(1, 2): with T.block("B_reindex_shared_wmma.matrix_b_o"): v0_o = T.axis.spatial(8, ax2_0_0 * 2 + ax2_0_1) v1_o = T.axis.spatial(8, ax0_0_1_ax1_0_1_fused % 4 * 2 + ax1_0) T.reads(B_reindex_shared[v0_o * 16 : v0_o * 16 + 16, v1_o * 16 : v1_o * 16 + 16]) T.writes(B_reindex_shared_wmma_matrix_b[v0_o * 16 : v0_o * 16 + 16, v1_o * 16 : v1_o * 16 + 16]) T.block_attr({"meta_schedule.auto_tensorize":"wmma_load_16x16x16_f16_b"}) for ax0_1, ax1_1 in T.grid(16, 16): with T.block("B_reindex_shared_wmma.matrix_b"): v0_i, v1_i = T.axis.remap("SS", [ax0_1, ax1_1]) T.reads(B_reindex_shared[v0_o * 16 + v0_i, v1_o * 16 + v1_i]) T.writes(B_reindex_shared_wmma_matrix_b[v0_o * 16 + v0_i, v1_o * 16 + v1_i]) B_reindex_shared_wmma_matrix_b[v0_o * 16 + v0_i, v1_o * 16 + v1_i] = B_reindex_shared[v0_o * 16 + v0_i, v1_o * 16 + v1_i] for ax0_0_3, ax1_0_3, ax2_0_2, ax0_0_4, ax1_0_4 in T.grid(1, 1, 1, 2, 2): with T.block("C_o"): v0_o = T.axis.spatial(8, ax0_0_1_ax1_0_1_fused // 4 * 2 + ax0_0_3 * 2 + ax0_0_4) v1_o = T.axis.spatial(8, ax0_0_1_ax1_0_1_fused % 4 * 2 + ax1_0_3 * 2 + ax1_0_4) v2_o = T.axis.reduce(8, ax2_0_0 * 2 + ax2_0_1 + ax2_0_2) T.reads(A_reindex_shared_wmma_matrix_a[v0_o * 16 : v0_o * 16 + 16, v2_o * 16 : v2_o * 16 + 16], B_reindex_shared_wmma_matrix_b[v2_o * 16 : v2_o * 16 + 16, v1_o * 16 : v1_o * 16 + 16]) T.writes(C_reindex_shared_wmma_accumulator[v0_o * 16 : v0_o * 16 + 16, v1_o * 16 : v1_o * 16 + 16]) T.block_attr({"meta_schedule.auto_tensorize":"wmma_sync_16x16x16_f16f16f32", "meta_schedule.auto_tensorize_init":"wmma_fill_16x16x16_f32", "warp_execution":1}) with T.init(): for ax0_1, ax1_1 in T.grid(16, 16): with T.block("C_init"): v0_i_init, v1_i_init = T.axis.remap("SS", [ax0_1, ax1_1]) T.reads() T.writes(C_reindex_shared_wmma_accumulator[v0_o * 16 + v0_i_init, v1_o * 16 + v1_i_init]) C_reindex_shared_wmma_accumulator[v0_o * 16 + v0_i_init, v1_o * 16 + v1_i_init] = T.float32(0) for ax0_1, ax1_1, ax2_1 in T.grid(16, 16, 16): with T.block("C"): v0_i, v1_i, v2_i = T.axis.remap("SSR", [ax0_1, ax1_1, ax2_1]) T.reads(C_reindex_shared_wmma_accumulator[v0_o * 16 + v0_i, v1_o * 16 + v1_i], A_reindex_shared_wmma_matrix_a[v0_o * 16 + v0_i, v2_o * 16 + v2_i], B_reindex_shared_wmma_matrix_b[v2_o * 16 + v2_i, v1_o * 16 + v1_i]) T.writes(C_reindex_shared_wmma_accumulator[v0_o * 16 + v0_i, v1_o * 16 + v1_i]) T.block_attr({"meta_schedule.tiling_structure":"SSSRRSRS"}) C_reindex_shared_wmma_accumulator[v0_o * 16 + v0_i, v1_o * 16 + v1_i] = C_reindex_shared_wmma_accumulator[v0_o * 16 + v0_i, v1_o * 16 + v1_i] + T.cast(A_reindex_shared_wmma_matrix_a[v0_o * 16 + v0_i, v2_o * 16 + v2_i], "float32") * T.cast(B_reindex_shared_wmma_matrix_b[v2_o * 16 + v2_i, v1_o * 16 + v1_i], "float32") for ax0_0, ax1_0 in T.grid(2, 2): with T.block("C_reindex_shared_wmma.accumulator_o"): v0_o = T.axis.spatial(8, ax0_0_1_ax1_0_1_fused // 4 * 2 + ax0_0) v1_o = T.axis.spatial(8, ax0_0_1_ax1_0_1_fused % 4 * 2 + ax1_0) T.reads(C_reindex_shared_wmma_accumulator[v0_o * 16 : v0_o * 16 + 16, v1_o * 16 : v1_o * 16 + 16]) T.writes(C_reindex_shared[v0_o * 16 : v0_o * 16 + 16, v1_o * 16 : v1_o * 16 + 16]) T.block_attr({"meta_schedule.auto_tensorize":"wmma_store_16x16x16_f32_shared"}) for ax0_1, ax1_1 in T.grid(16, 16): with T.block("C_reindex_shared_wmma.accumulator"): v0_i, v1_i = T.axis.remap("SS", [ax0_1, ax1_1]) T.reads(C_reindex_shared_wmma_accumulator[v0_o * 16 + v0_i, v1_o * 16 + v1_i]) T.writes(C_reindex_shared[v0_o * 16 + v0_i, v1_o * 16 + v1_i]) C_reindex_shared[v0_o * 16 + v0_i, v1_o * 16 + v1_i] = C_reindex_shared_wmma_accumulator[v0_o * 16 + v0_i, v1_o * 16 + v1_i] for ax0_ax1_fused in T.grid(1024): with T.block("C_reindex_shared"): v0 = T.axis.spatial(128, ax0_0_1_ax1_0_1_fused // 4 * 32 + ax0_ax1_fused // 32) v1 = T.axis.spatial(128, ax0_0_1_ax1_0_1_fused % 4 * 32 + ax0_ax1_fused % 32) T.reads(C_reindex_shared[v0, v1]) T.writes(C[v0, v1]) T.block_attr({"meta_schedule.cooperative_fetch":3}) C[v0, v1] = C_reindex_shared[v0, v1] for i0, i1 in T.grid(128, 128): with T.block("compute"): i0_1, i1_1 = T.axis.remap("SS", [i0, i1]) T.reads(C[i0_1, i1_1]) T.writes(compute[i0_1, i1_1]) compute[i0_1, i1_1] = T.max(C[i0_1, i1_1], T.float32(0)) # fmt: on decision_0 = [ ("SamplePerfectTile", [1, 4, 1, 1, 2]), ("SamplePerfectTile", [1, 4, 1, 1, 2]), ("SamplePerfectTile", [4, 2, 1]), ("SampleCategorical", 2), ("SampleCategorical", 2), ("SampleCategorical", 1), ] mod = te.create_prim_func( te_workload.matmul_relu( n=128, m=128, k=128, in_dtype="float16", out_dtype="float32", ) ) actual = generate_design_space( kind="cuda", mod=mod, target=tvm.target.Target("cuda"), types=None, sch_rules=[ multi_level_tiling_tensor_core( use_software_pipeline=True, ), ], ) check_sketches( mod, sketches=actual, expected_mods=[matmul_relu_pipeline_0], expected_decisions=[decision_0], ) def test_matmul_relu_global(): # fmt: off @T.prim_func def matmul_relu_global_0(A: T.Buffer[(128, 128), "float16"], B: T.Buffer[(128, 128), "float16"], compute: T.Buffer[(128, 128), "float32"]) -> None: # function attr dict T.func_attr({"global_symbol": "main", "tir.noalias": True}) # body # with T.block("root") C = T.alloc_buffer([128, 128], dtype="float32") C_reindex_wmma_accumulator = T.alloc_buffer([128, 128], dtype="float32", scope="wmma.accumulator") A_reindex_shared = T.alloc_buffer([128, 128], dtype="float16", scope="shared") B_reindex_shared = T.alloc_buffer([128, 128], dtype="float16", scope="shared") A_reindex_shared_wmma_matrix_a = T.alloc_buffer([128, 128], dtype="float16", scope="wmma.matrix_a") B_reindex_shared_wmma_matrix_b = T.alloc_buffer([128, 128], dtype="float16", scope="wmma.matrix_b") for ax0_0_0_ax1_0_0_fused in T.thread_binding(1, thread="blockIdx.y"): for ax0_0_1_ax1_0_1_fused in T.thread_binding(1, thread="blockIdx.x"): for ax0_0_2_ax1_0_2_fused in T.thread_binding(16, thread="threadIdx.y"): for ax2_0_0 in T.serial(2): for ax0_ax1_fused in T.serial(8192): with T.block("A_reindex_shared"): v0 = T.axis.spatial(128, ax0_ax1_fused // 64) v1 = T.axis.spatial(128, ax2_0_0 * 64 + ax0_ax1_fused % 64) T.reads(A[v0, v1]) T.writes(A_reindex_shared[v0, v1]) T.block_attr({"buffer_dim_align":[[0, 0, 32, 8]], "meta_schedule.cooperative_fetch":1}) A_reindex_shared[v0, v1] = A[v0, v1] for ax0_ax1_fused in T.serial(8192): with T.block("B_reindex_shared"): v0 = T.axis.spatial(128, ax2_0_0 * 64 + ax0_ax1_fused // 128) v1 = T.axis.spatial(128, ax0_ax1_fused % 128) T.reads(B[v0, v1]) T.writes(B_reindex_shared[v0, v1]) T.block_attr({"buffer_dim_align":[[0, 0, 32, 8]], "meta_schedule.cooperative_fetch":1}) B_reindex_shared[v0, v1] = B[v0, v1] for ax2_0_1 in T.serial(2): for ax0_0, ax1_0 in T.grid(1, 2): with T.block("A_reindex_shared_wmma.matrix_a_o"): v0_o = T.axis.spatial(8, ax0_0_2_ax1_0_2_fused // 2) v1_o = T.axis.spatial(8, ax2_0_0 * 4 + ax2_0_1 * 2 + ax1_0) T.reads(A_reindex_shared[v0_o * 16 : v0_o * 16 + 16, v1_o * 16 : v1_o * 16 + 16]) T.writes(A_reindex_shared_wmma_matrix_a[v0_o * 16 : v0_o * 16 + 16, v1_o * 16 : v1_o * 16 + 16]) T.block_attr({"meta_schedule.auto_tensorize":"wmma_load_16x16x16_f16_a"}) for ax0_1, ax1_1 in T.grid(16, 16): with T.block("A_reindex_shared_wmma.matrix_a"): v0_i, v1_i = T.axis.remap("SS", [ax0_1, ax1_1]) T.reads(A_reindex_shared[v0_o * 16 + v0_i, v1_o * 16 + v1_i]) T.writes(A_reindex_shared_wmma_matrix_a[v0_o * 16 + v0_i, v1_o * 16 + v1_i]) A_reindex_shared_wmma_matrix_a[v0_o * 16 + v0_i, v1_o * 16 + v1_i] = A_reindex_shared[v0_o * 16 + v0_i, v1_o * 16 + v1_i] for ax0_0, ax1_0 in T.grid(2, 4): with T.block("B_reindex_shared_wmma.matrix_b_o"): v0_o = T.axis.spatial(8, ax2_0_0 * 4 + ax2_0_1 * 2 + ax0_0) v1_o = T.axis.spatial(8, ax0_0_2_ax1_0_2_fused % 2 * 4 + ax1_0) T.reads(B_reindex_shared[v0_o * 16 : v0_o * 16 + 16, v1_o * 16 : v1_o * 16 + 16]) T.writes(B_reindex_shared_wmma_matrix_b[v0_o * 16 : v0_o * 16 + 16, v1_o * 16 : v1_o * 16 + 16]) T.block_attr({"meta_schedule.auto_tensorize":"wmma_load_16x16x16_f16_b"}) for ax0_1, ax1_1 in T.grid(16, 16): with T.block("B_reindex_shared_wmma.matrix_b"): v0_i, v1_i = T.axis.remap("SS", [ax0_1, ax1_1]) T.reads(B_reindex_shared[v0_o * 16 + v0_i, v1_o * 16 + v1_i]) T.writes(B_reindex_shared_wmma_matrix_b[v0_o * 16 + v0_i, v1_o * 16 + v1_i]) B_reindex_shared_wmma_matrix_b[v0_o * 16 + v0_i, v1_o * 16 + v1_i] = B_reindex_shared[v0_o * 16 + v0_i, v1_o * 16 + v1_i] for ax0_0_3, ax1_0_3, ax2_0_2, ax0_0_4, ax1_0_4 in T.grid(1, 4, 2, 1, 1): with T.block("C_o"): v0_o = T.axis.spatial(8, ax0_0_2_ax1_0_2_fused // 2 + ax0_0_3 + ax0_0_4) v1_o = T.axis.spatial(8, ax1_0_4 + ax0_0_2_ax1_0_2_fused % 2 * 4 + ax1_0_3) v2_o = T.axis.reduce(8, ax2_0_0 * 4 + ax2_0_1 * 2 + ax2_0_2) T.reads(A_reindex_shared_wmma_matrix_a[v0_o * 16 : v0_o * 16 + 16, v2_o * 16 : v2_o * 16 + 16], B_reindex_shared_wmma_matrix_b[v2_o * 16 : v2_o * 16 + 16, v1_o * 16 : v1_o * 16 + 16]) T.writes(C_reindex_wmma_accumulator[v0_o * 16 : v0_o * 16 + 16, v1_o * 16 : v1_o * 16 + 16]) T.block_attr({"meta_schedule.auto_tensorize":"wmma_sync_16x16x16_f16f16f32", "meta_schedule.auto_tensorize_init":"wmma_fill_16x16x16_f32", "warp_execution":1}) with T.init(): for ax0_1, ax1_1 in T.grid(16, 16): with T.block("C_init"): v0_i_init, v1_i_init = T.axis.remap("SS", [ax0_1, ax1_1]) T.reads() T.writes(C_reindex_wmma_accumulator[v0_o * 16 + v0_i_init, v1_o * 16 + v1_i_init]) C_reindex_wmma_accumulator[v0_o * 16 + v0_i_init, v1_o * 16 + v1_i_init] = T.float32(0) for ax0_1, ax1_1, ax2_1 in T.grid(16, 16, 16): with T.block("C"): v0_i, v1_i, v2_i = T.axis.remap("SSR", [ax0_1, ax1_1, ax2_1]) T.reads(C_reindex_wmma_accumulator[v0_o * 16 + v0_i, v1_o * 16 + v1_i], A_reindex_shared_wmma_matrix_a[v0_o * 16 + v0_i, v2_o * 16 + v2_i], B_reindex_shared_wmma_matrix_b[v2_o * 16 + v2_i, v1_o * 16 + v1_i]) T.writes(C_reindex_wmma_accumulator[v0_o * 16 + v0_i, v1_o * 16 + v1_i]) T.block_attr({"meta_schedule.tiling_structure":"SSSRRSRS"}) C_reindex_wmma_accumulator[v0_o * 16 + v0_i, v1_o * 16 + v1_i] = C_reindex_wmma_accumulator[v0_o * 16 + v0_i, v1_o * 16 + v1_i] + T.cast(A_reindex_shared_wmma_matrix_a[v0_o * 16 + v0_i, v2_o * 16 + v2_i], "float32") * T.cast(B_reindex_shared_wmma_matrix_b[v2_o * 16 + v2_i, v1_o * 16 + v1_i], "float32") for ax0_0, ax1_0 in T.grid(1, 4): with T.block("C_reindex_wmma.accumulator_o"): v0_o = T.axis.spatial(8, ax0_0_2_ax1_0_2_fused // 2) v1_o = T.axis.spatial(8, ax0_0_2_ax1_0_2_fused % 2 * 4 + ax1_0) T.reads(C_reindex_wmma_accumulator[v0_o * 16 : v0_o * 16 + 16, v1_o * 16 : v1_o * 16 + 16]) T.writes(C[v0_o * 16 : v0_o * 16 + 16, v1_o * 16 : v1_o * 16 + 16]) T.block_attr({"meta_schedule.auto_tensorize":"wmma_store_16x16x16_f32_global"}) for ax0_1, ax1_1 in T.grid(16, 16): with T.block("C_reindex_wmma.accumulator"): v0_i, v1_i = T.axis.remap("SS", [ax0_1, ax1_1]) T.reads(C_reindex_wmma_accumulator[v0_o * 16 + v0_i, v1_o * 16 + v1_i]) T.writes(C[v0_o * 16 + v0_i, v1_o * 16 + v1_i]) C[v0_o * 16 + v0_i, v1_o * 16 + v1_i] = C_reindex_wmma_accumulator[v0_o * 16 + v0_i, v1_o * 16 + v1_i] for i0, i1 in T.grid(128, 128): with T.block("compute"): i0_1, i1_1 = T.axis.remap("SS", [i0, i1]) T.reads(C[i0_1, i1_1]) T.writes(compute[i0_1, i1_1]) compute[i0_1, i1_1] = T.max(C[i0_1, i1_1], T.float32(0)) # fmt: on decision_0 = [ ("SamplePerfectTile", [1, 1, 8, 1, 1]), ("SamplePerfectTile", [1, 1, 2, 4, 1]), ("SamplePerfectTile", [2, 2, 2]), ("SampleCategorical", 0), ("SampleCategorical", 0), ] mod = te.create_prim_func( te_workload.matmul_relu( n=128, m=128, k=128, in_dtype="float16", out_dtype="float32", ) ) actual = generate_design_space( kind="cuda", mod=mod, target=tvm.target.Target("cuda"), types=None, sch_rules=[multi_level_tiling_tensor_core(write_reuse_scope="global")] + get_rules("cuda", ms.schedule_rule.AutoInline), ) check_sketches( mod, sketches=actual, expected_mods=[matmul_relu_global_0], expected_decisions=[decision_0], ) def test_matmul_relu_non_tensorizable(): # expected to do nothing on non-tensorizable workloads mod = te.create_prim_func( te_workload.matmul_relu( # dtype doesn't match tensor intrin n=128, m=128, k=128, ) ) (sch,) = generate_design_space( kind="cuda", mod=mod, target=tvm.target.Target("cuda"), types=None, sch_rules=[multi_level_tiling_tensor_core(write_reuse_scope="global")] + get_rules("cuda", ms.schedule_rule.AutoInline), ) tvm.ir.assert_structural_equal(mod, sch.mod["main"]) def test_padded_matmul_relu(): # fmt: off @T.prim_func def padded_matmul_relu_0(A: T.Buffer[(127, 127), "float16"], B: T.Buffer[(127, 127), "float16"], compute: T.Buffer[(127, 127), "float32"]) -> None: # function attr dict T.func_attr({"global_symbol": "main", "tir.noalias": True}) # body # with T.block("root") C_reindex_shared = T.alloc_buffer([128, 128], dtype="float32", scope="shared") C_reindex_shared_wmma_accumulator = T.alloc_buffer([128, 128], dtype="float32", scope="wmma.accumulator") A_reindex_shared = T.alloc_buffer([128, 128], dtype="float16", scope="shared") B_reindex_shared = T.alloc_buffer([128, 128], dtype="float16", scope="shared") A_reindex_shared_wmma_matrix_a = T.alloc_buffer([128, 128], dtype="float16", scope="wmma.matrix_a") B_reindex_shared_wmma_matrix_b = T.alloc_buffer([128, 128], dtype="float16", scope="wmma.matrix_b") for ax0_0_0_ax1_0_0_fused in T.thread_binding(8, thread="blockIdx.y"): for ax0_0_1_ax1_0_1_fused in T.thread_binding(2, thread="blockIdx.x"): for ax0_0_2_ax1_0_2_fused in T.thread_binding(2, thread="threadIdx.y"): for ax2_0_0 in T.serial(1): for ax0_ax1_fused in T.serial(4096): with T.block("A_reindex_shared"): v0 = T.axis.spatial(128, ax0_0_0_ax1_0_0_fused // 2 * 32 + ax0_ax1_fused // 128) v1 = T.axis.spatial(128, ax0_ax1_fused % 128) T.reads(A[v0, v1]) T.writes(A_reindex_shared[v0, v1]) T.block_attr({"buffer_dim_align":[[0, 0, 32, 8]], "meta_schedule.cooperative_fetch":8}) A_reindex_shared[v0, v1] = T.if_then_else(v0 < 127 and v1 < 127, A[v0, v1], T.float16(0), dtype="float16") for ax0_ax1_fused in T.serial(4096): with T.block("B_reindex_shared"): v0 = T.axis.spatial(128, ax0_ax1_fused // 32) v1 = T.axis.spatial(128, ax0_0_0_ax1_0_0_fused % 2 * 64 + ax0_0_1_ax1_0_1_fused * 32 + ax0_ax1_fused % 32) T.reads(B[v0, v1]) T.writes(B_reindex_shared[v0, v1]) T.block_attr({"buffer_dim_align":[[0, 0, 32, 8]], "meta_schedule.cooperative_fetch":1}) B_reindex_shared[v0, v1] = T.if_then_else(v0 < 127 and v1 < 127, B[v0, v1], T.float16(0), dtype="float16") for ax2_0_1 in T.serial(4): for ax0_0, ax1_0 in T.grid(2, 2): with T.block("A_reindex_shared_wmma.matrix_a_o"): v0_o = T.axis.spatial(8, ax0_0_0_ax1_0_0_fused // 2 * 2 + ax0_0) v1_o = T.axis.spatial(8, ax2_0_1 * 2 + ax1_0) T.reads(A_reindex_shared[v0_o * 16 : v0_o * 16 + 16, v1_o * 16 : v1_o * 16 + 16]) T.writes(A_reindex_shared_wmma_matrix_a[v0_o * 16 : v0_o * 16 + 16, v1_o * 16 : v1_o * 16 + 16]) T.block_attr({"meta_schedule.auto_tensorize":"wmma_load_16x16x16_f16_a"}) for ax0_1, ax1_1 in T.grid(16, 16): with T.block("A_reindex_shared_wmma.matrix_a"): v0_i, v1_i = T.axis.remap("SS", [ax0_1, ax1_1]) T.reads(A_reindex_shared[v0_o * 16 + v0_i, v1_o * 16 + v1_i]) T.writes(A_reindex_shared_wmma_matrix_a[v0_o * 16 + v0_i, v1_o * 16 + v1_i]) A_reindex_shared_wmma_matrix_a[v0_o * 16 + v0_i, v1_o * 16 + v1_i] = A_reindex_shared[v0_o * 16 + v0_i, v1_o * 16 + v1_i] for ax0_0, ax1_0 in T.grid(2, 1): with T.block("B_reindex_shared_wmma.matrix_b_o"): v0_o = T.axis.spatial(8, ax2_0_1 * 2 + ax0_0) v1_o = T.axis.spatial(8, ax0_0_0_ax1_0_0_fused % 2 * 4 + ax0_0_1_ax1_0_1_fused * 2 + ax0_0_2_ax1_0_2_fused) T.reads(B_reindex_shared[v0_o * 16 : v0_o * 16 + 16, v1_o * 16 : v1_o * 16 + 16]) T.writes(B_reindex_shared_wmma_matrix_b[v0_o * 16 : v0_o * 16 + 16, v1_o * 16 : v1_o * 16 + 16]) T.block_attr({"meta_schedule.auto_tensorize":"wmma_load_16x16x16_f16_b"}) for ax0_1, ax1_1 in T.grid(16, 16): with T.block("B_reindex_shared_wmma.matrix_b"): v0_i, v1_i = T.axis.remap("SS", [ax0_1, ax1_1]) T.reads(B_reindex_shared[v0_o * 16 + v0_i, v1_o * 16 + v1_i]) T.writes(B_reindex_shared_wmma_matrix_b[v0_o * 16 + v0_i, v1_o * 16 + v1_i]) B_reindex_shared_wmma_matrix_b[v0_o * 16 + v0_i, v1_o * 16 + v1_i] = B_reindex_shared[v0_o * 16 + v0_i, v1_o * 16 + v1_i] for ax0_0_3, ax1_0_3, ax2_0_2, ax0_0_4, ax1_0_4 in T.grid(1, 1, 2, 2, 1): with T.block("C_o"): v0_o = T.axis.spatial(8, ax0_0_0_ax1_0_0_fused // 2 * 2 + ax0_0_3 * 2 + ax0_0_4) v1_o = T.axis.spatial(8, ax1_0_4 + ax0_0_0_ax1_0_0_fused % 2 * 4 + ax0_0_1_ax1_0_1_fused * 2 + ax0_0_2_ax1_0_2_fused + ax1_0_3) v2_o = T.axis.reduce(8, ax2_0_0 * 8 + ax2_0_1 * 2 + ax2_0_2) T.reads(A_reindex_shared_wmma_matrix_a[v0_o * 16 : v0_o * 16 + 16, v2_o * 16 : v2_o * 16 + 16], B_reindex_shared_wmma_matrix_b[v2_o * 16 : v2_o * 16 + 16, v1_o * 16 : v1_o * 16 + 16]) T.writes(C_reindex_shared_wmma_accumulator[v0_o * 16 : v0_o * 16 + 16, v1_o * 16 : v1_o * 16 + 16]) T.block_attr({"meta_schedule.auto_tensorize":"wmma_sync_16x16x16_f16f16f32", "meta_schedule.auto_tensorize_init":"wmma_fill_16x16x16_f32", "warp_execution":1}) with T.init(): for ax0_1, ax1_1 in T.grid(16, 16): with T.block("C_init"): v0_i_init, v1_i_init = T.axis.remap("SS", [ax0_1, ax1_1]) T.reads() T.writes(C_reindex_shared_wmma_accumulator[v0_o * 16 + v0_i_init, v1_o * 16 + v1_i_init]) C_reindex_shared_wmma_accumulator[v0_o * 16 + v0_i_init, v1_o * 16 + v1_i_init] = T.float32(0) for ax0_1, ax1_1, ax2_1 in T.grid(16, 16, 16): with T.block("C"): v0_i, v1_i, v2_i = T.axis.remap("SSR", [ax0_1, ax1_1, ax2_1]) T.reads(C_reindex_shared_wmma_accumulator[v0_o * 16 + v0_i, v1_o * 16 + v1_i], A_reindex_shared_wmma_matrix_a[v0_o * 16 + v0_i, v2_o * 16 + v2_i], B_reindex_shared_wmma_matrix_b[v2_o * 16 + v2_i, v1_o * 16 + v1_i]) T.writes(C_reindex_shared_wmma_accumulator[v0_o * 16 + v0_i, v1_o * 16 + v1_i]) T.block_attr({"meta_schedule.tiling_structure":"SSSRRSRS"}) C_reindex_shared_wmma_accumulator[v0_o * 16 + v0_i, v1_o * 16 + v1_i] = C_reindex_shared_wmma_accumulator[v0_o * 16 + v0_i, v1_o * 16 + v1_i] + T.cast(A_reindex_shared_wmma_matrix_a[v0_o * 16 + v0_i, v2_o * 16 + v2_i], "float32") * T.cast(B_reindex_shared_wmma_matrix_b[v2_o * 16 + v2_i, v1_o * 16 + v1_i], "float32") for ax0_0, ax1_0 in T.grid(2, 1): with T.block("C_reindex_shared_wmma.accumulator_o"): v0_o = T.axis.spatial(8, ax0_0_0_ax1_0_0_fused // 2 * 2 + ax0_0) v1_o = T.axis.spatial(8, ax0_0_0_ax1_0_0_fused % 2 * 4 + ax0_0_1_ax1_0_1_fused * 2 + ax0_0_2_ax1_0_2_fused) T.reads(C_reindex_shared_wmma_accumulator[v0_o * 16 : v0_o * 16 + 16, v1_o * 16 : v1_o * 16 + 16]) T.writes(C_reindex_shared[v0_o * 16 : v0_o * 16 + 16, v1_o * 16 : v1_o * 16 + 16]) T.block_attr({"meta_schedule.auto_tensorize":"wmma_store_16x16x16_f32_shared"}) for ax0_1, ax1_1 in T.grid(16, 16): with T.block("C_reindex_shared_wmma.accumulator"): v0_i, v1_i = T.axis.remap("SS", [ax0_1, ax1_1]) T.reads(C_reindex_shared_wmma_accumulator[v0_o * 16 + v0_i, v1_o * 16 + v1_i]) T.writes(C_reindex_shared[v0_o * 16 + v0_i, v1_o * 16 + v1_i]) C_reindex_shared[v0_o * 16 + v0_i, v1_o * 16 + v1_i] = C_reindex_shared_wmma_accumulator[v0_o * 16 + v0_i, v1_o * 16 + v1_i] for ax0_ax1_fused in T.serial(1024): with T.block("C_reindex_shared"): T.where(ax0_0_0_ax1_0_0_fused // 2 * 32 + ax0_ax1_fused // 32 < 127 and ax0_0_0_ax1_0_0_fused % 2 * 64 + ax0_0_1_ax1_0_1_fused * 32 + ax0_ax1_fused % 32 < 127) v0 = T.axis.spatial(128, ax0_0_0_ax1_0_0_fused // 2 * 32 + ax0_ax1_fused // 32) v1 = T.axis.spatial(128, ax0_0_0_ax1_0_0_fused % 2 * 64 + ax0_0_1_ax1_0_1_fused * 32 + ax0_ax1_fused % 32) T.reads(C_reindex_shared[v0, v1]) T.writes(compute[v0, v1]) T.block_attr({"meta_schedule.cooperative_fetch":4}) compute[v0, v1] = T.max(C_reindex_shared[v0, v1], T.float32(0)) # fmt: on decision_0 = [ ("SamplePerfectTile", [4, 1, 1, 1, 2]), ("SamplePerfectTile", [2, 2, 2, 1, 1]), ("SamplePerfectTile", [1, 4, 2]), ("SampleCategorical", 3), ("SampleCategorical", 3), ("SampleCategorical", 0), ] mod = te.create_prim_func( te_workload.matmul_relu( n=127, m=127, k=127, in_dtype="float16", out_dtype="float32", ) ) actual = generate_design_space( kind="cuda", mod=mod, target=tvm.target.Target("cuda"), types=None, sch_rules=[multi_level_tiling_tensor_core(write_reuse_scope="shared")] + get_rules("cuda", ms.schedule_rule.AutoInline), ) check_sketches( mod, sketches=actual, expected_mods=[padded_matmul_relu_0], expected_decisions=[decision_0], ) def test_conv_1x1(): # fmt: off @T.prim_func def conv2d_1x1_0(inputs: T.Buffer[(1, 16, 16, 64), "float16"], weight: T.Buffer[(1, 1, 64, 64), "float16"], conv2d_nhwc: T.Buffer[(1, 16, 16, 64), "float32"]) -> None: T.func_attr({"global_symbol": "main", "tir.noalias": True}) conv2d_nhwc_reindex_shared = T.alloc_buffer([256, 64], dtype="float32", scope="shared") conv2d_nhwc_reindex_shared_wmma_accumulator = T.alloc_buffer([256, 64], dtype="float32", scope="wmma.accumulator") PadInput_reindex_shared = T.alloc_buffer([256, 64], dtype="float16", scope="shared") weight_reindex_shared = T.alloc_buffer([1, 1, 64, 64], dtype="float16", scope="shared") PadInput_reindex_shared_wmma_matrix_a = T.alloc_buffer([256, 64], dtype="float16", scope="wmma.matrix_a") weight_reindex_shared_wmma_matrix_b = T.alloc_buffer([1, 1, 64, 64], dtype="float16", scope="wmma.matrix_b") for ax2_0_0_ax3_0_0_fused in T.thread_binding(16, thread="blockIdx.y"): for ax2_0_1_ax3_0_1_fused in T.thread_binding(2, thread="blockIdx.x"): for ax2_0_2_ax3_0_2_fused in T.thread_binding(2, thread="threadIdx.y"): for ax0_0, ax1_0, ax4_0_0 in T.grid(1, 1, 1): for ax0_ax1_fused in T.serial(1024): with T.block("PadInput_reindex_shared"): v0 = T.axis.spatial(256, ax2_0_0_ax3_0_0_fused // 2 * 32 + ax2_0_1_ax3_0_1_fused * 16 + ax0_ax1_fused // 64) v1 = T.axis.spatial(64, ax0_ax1_fused % 64) T.reads(inputs[v0 // 256, v0 // 16, v0 % 16, v1]) T.writes(PadInput_reindex_shared[v0, v1]) T.block_attr({"buffer_dim_align":[[0, 0, 32, 8]], "meta_schedule.cooperative_fetch":1}) PadInput_reindex_shared[v0, v1] = inputs[v0 // 256, v0 // 16, v0 % 16, v1] for ax0_ax1_ax2_ax3_fused in T.serial(2048): with T.block("weight_reindex_shared"): v0 = T.axis.spatial(1, 0) v1 = T.axis.spatial(1, 0) v2 = T.axis.spatial(64, ax0_ax1_ax2_ax3_fused // 32) v3 = T.axis.spatial(64, ax2_0_0_ax3_0_0_fused % 2 * 32 + ax0_ax1_ax2_ax3_fused % 32) T.reads(weight[v0, v1, v2, v3]) T.writes(weight_reindex_shared[v0, v1, v2, v3]) T.block_attr({"buffer_dim_align":[[0, 2, 32, 8]], "meta_schedule.cooperative_fetch":4}) weight_reindex_shared[v0, v1, v2, v3] = weight[v0, v1, v2, v3] for ax0_1, ax1_1, ax4_0_1 in T.grid(1, 1, 1): for ax0_0_1, ax1_0_1 in T.grid(1, 4): with T.block("PadInput_reindex_shared_wmma.matrix_a_o"): v0_o = T.axis.spatial(16, ax2_0_0_ax3_0_0_fused // 2 * 2 + ax2_0_1_ax3_0_1_fused) v1_o = T.axis.spatial(4, ax1_0_1) T.reads(PadInput_reindex_shared[v0_o * 16 : v0_o * 16 + 16, v1_o * 16 : v1_o * 16 + 16]) T.writes(PadInput_reindex_shared_wmma_matrix_a[v0_o * 16 : v0_o * 16 + 16, v1_o * 16 : v1_o * 16 + 16]) T.block_attr({"meta_schedule.auto_tensorize":"wmma_load_16x16x16_f16_a"}) for ax0_1_1, ax1_1_1 in T.grid(16, 16): with T.block("PadInput_reindex_shared_wmma.matrix_a"): v0_i, v1_i = T.axis.remap("SS", [ax0_1_1, ax1_1_1]) T.reads(PadInput_reindex_shared[v0_o * 16 + v0_i, v1_o * 16 + v1_i]) T.writes(PadInput_reindex_shared_wmma_matrix_a[v0_o * 16 + v0_i, v1_o * 16 + v1_i]) PadInput_reindex_shared_wmma_matrix_a[v0_o * 16 + v0_i, v1_o * 16 + v1_i] = PadInput_reindex_shared[v0_o * 16 + v0_i, v1_o * 16 + v1_i] for ax0, ax1, ax2_0, ax3_0 in T.grid(1, 1, 4, 1): with T.block("weight_reindex_shared_wmma.matrix_b_o"): v0 = T.axis.spatial(1, 0) v1 = T.axis.spatial(1, 0) v2_o = T.axis.spatial(4, ax2_0) v3_o = T.axis.spatial(4, ax2_0_0_ax3_0_0_fused % 2 * 2 + ax2_0_2_ax3_0_2_fused) T.reads(weight_reindex_shared[v0, v1, v2_o * 16 : v2_o * 16 + 16, v3_o * 16 : v3_o * 16 + 16]) T.writes(weight_reindex_shared_wmma_matrix_b[v0, v1, v2_o * 16 : v2_o * 16 + 16, v3_o * 16 : v3_o * 16 + 16]) T.block_attr({"meta_schedule.auto_tensorize":"wmma_load_16x16x16_f16_b"}) for ax2_1, ax3_1 in T.grid(16, 16): with T.block("weight_reindex_shared_wmma.matrix_b"): v2_i, v3_i = T.axis.remap("SS", [ax2_1, ax3_1]) T.reads(weight_reindex_shared[v0, v1, v2_o * 16 + v2_i, v3_o * 16 + v3_i]) T.writes(weight_reindex_shared_wmma_matrix_b[v0, v1, v2_o * 16 + v2_i, v3_o * 16 + v3_i]) weight_reindex_shared_wmma_matrix_b[v0, v1, v2_o * 16 + v2_i, v3_o * 16 + v3_i] = weight_reindex_shared[v0, v1, v2_o * 16 + v2_i, v3_o * 16 + v3_i] for ax2_0_3, ax3_0_3, ax0_2, ax1_2, ax4_0_2, ax2_0_4, ax3_0_4 in T.grid(1, 1, 1, 1, 4, 1, 1): with T.block("conv2d_nhwc_o"): v0 = T.axis.reduce(1, 0) v1 = T.axis.reduce(1, 0) v2_o = T.axis.spatial(16, ax2_0_4 + ax2_0_0_ax3_0_0_fused // 2 * 2 + ax2_0_1_ax3_0_1_fused + ax2_0_3) v3_o = T.axis.spatial(4, ax3_0_4 + ax2_0_0_ax3_0_0_fused % 2 * 2 + ax2_0_2_ax3_0_2_fused + ax3_0_3) v4_o = T.axis.reduce(4, ax4_0_0 * 4 + ax4_0_1 * 4 + ax4_0_2) T.reads(PadInput_reindex_shared_wmma_matrix_a[v2_o * 16 : v2_o * 16 + 16, v4_o * 16 : v4_o * 16 + 16], weight_reindex_shared_wmma_matrix_b[v0, v1, v4_o * 16 : v4_o * 16 + 16, v3_o * 16 : v3_o * 16 + 16]) T.writes(conv2d_nhwc_reindex_shared_wmma_accumulator[v2_o * 16 : v2_o * 16 + 16, v3_o * 16 : v3_o * 16 + 16]) T.block_attr({"meta_schedule.auto_tensorize":"wmma_sync_16x16x16_f16f16f32", "meta_schedule.auto_tensorize_init":"wmma_fill_16x16x16_f32", "warp_execution":1}) with T.init(): for ax2_1, ax3_1 in T.grid(16, 16): with T.block("conv2d_nhwc_init"): v2_i_init, v3_i_init = T.axis.remap("SS", [ax2_1, ax3_1]) T.reads() T.writes(conv2d_nhwc_reindex_shared_wmma_accumulator[v2_o * 16 + v2_i_init, v3_o * 16 + v3_i_init]) conv2d_nhwc_reindex_shared_wmma_accumulator[v2_o * 16 + v2_i_init, v3_o * 16 + v3_i_init] = T.float32(0) for ax2_1, ax3_1, ax4_1 in T.grid(16, 16, 16): with T.block("conv2d_nhwc"): v2_i, v3_i, v4_i = T.axis.remap("SSR", [ax2_1, ax3_1, ax4_1]) T.reads(conv2d_nhwc_reindex_shared_wmma_accumulator[v2_o * 16 + v2_i, v3_o * 16 + v3_i], PadInput_reindex_shared_wmma_matrix_a[v2_o * 16 + v2_i, v4_o * 16 + v4_i], weight_reindex_shared_wmma_matrix_b[v0, v1, v4_o * 16 + v4_i, v3_o * 16 + v3_i]) T.writes(conv2d_nhwc_reindex_shared_wmma_accumulator[v2_o * 16 + v2_i, v3_o * 16 + v3_i]) T.block_attr({"meta_schedule.tiling_structure":"SSSRRSRS"}) conv2d_nhwc_reindex_shared_wmma_accumulator[v2_o * 16 + v2_i, v3_o * 16 + v3_i] = conv2d_nhwc_reindex_shared_wmma_accumulator[v2_o * 16 + v2_i, v3_o * 16 + v3_i] + T.cast(PadInput_reindex_shared_wmma_matrix_a[v2_o * 16 + v2_i, v4_o * 16 + v4_i], "float32") * T.cast(weight_reindex_shared_wmma_matrix_b[v0, v1, v4_o * 16 + v4_i, v3_o * 16 + v3_i], "float32") for ax0_0, ax1_0 in T.grid(1, 1): with T.block("conv2d_nhwc_reindex_shared_wmma.accumulator_o"): v0_o = T.axis.spatial(16, ax2_0_0_ax3_0_0_fused // 2 * 2 + ax2_0_1_ax3_0_1_fused) v1_o = T.axis.spatial(4, ax2_0_0_ax3_0_0_fused % 2 * 2 + ax2_0_2_ax3_0_2_fused) T.reads(conv2d_nhwc_reindex_shared_wmma_accumulator[v0_o * 16 : v0_o * 16 + 16, v1_o * 16 : v1_o * 16 + 16]) T.writes(conv2d_nhwc_reindex_shared[v0_o * 16 : v0_o * 16 + 16, v1_o * 16 : v1_o * 16 + 16]) T.block_attr({"meta_schedule.auto_tensorize":"wmma_store_16x16x16_f32_shared"}) for ax0_1, ax1_1 in T.grid(16, 16): with T.block("conv2d_nhwc_reindex_shared_wmma.accumulator"): v0_i, v1_i = T.axis.remap("SS", [ax0_1, ax1_1]) T.reads(conv2d_nhwc_reindex_shared_wmma_accumulator[v0_o * 16 + v0_i, v1_o * 16 + v1_i]) T.writes(conv2d_nhwc_reindex_shared[v0_o * 16 + v0_i, v1_o * 16 + v1_i]) conv2d_nhwc_reindex_shared[v0_o * 16 + v0_i, v1_o * 16 + v1_i] = conv2d_nhwc_reindex_shared_wmma_accumulator[v0_o * 16 + v0_i, v1_o * 16 + v1_i] for ax0_ax1_fused in T.serial(512): with T.block("conv2d_nhwc_reindex_shared"): v0 = T.axis.spatial(256, ax2_0_0_ax3_0_0_fused // 2 * 32 + ax2_0_1_ax3_0_1_fused * 16 + ax0_ax1_fused // 32) v1 = T.axis.spatial(64, ax2_0_0_ax3_0_0_fused % 2 * 32 + ax0_ax1_fused % 32) T.reads(conv2d_nhwc_reindex_shared[v0, v1]) T.writes(conv2d_nhwc[v0 // 256, v0 // 16, v0 % 16, v1]) T.block_attr({"meta_schedule.cooperative_fetch":2}) conv2d_nhwc[v0 // 256, v0 // 16, v0 % 16, v1] = conv2d_nhwc_reindex_shared[v0, v1] # fmt: on decision_0 = [ ("SamplePerfectTile", [1, 1, 1]), ("SamplePerfectTile", [1, 1, 1]), ("SamplePerfectTile", [8, 2, 1, 1, 1]), ("SamplePerfectTile", [2, 1, 2, 1, 1]), ("SamplePerfectTile", [1, 1, 4]), ("SampleCategorical", 1), ("SampleCategorical", 0), ("SampleCategorical", 2), ] mod = te.create_prim_func( te_workload.conv2d_nhwc( 1, 16, 16, 64, 64, 1, 1, 0, in_dtype="float16", out_dtype="float32", ) ) actual = generate_design_space( kind="cuda", mod=mod, target=tvm.target.Target("cuda"), types=None, sch_rules=[multi_level_tiling_tensor_core(write_reuse_scope="shared")] + get_rules("cuda", ms.schedule_rule.AutoInline), ) check_sketches( mod, sketches=actual, expected_mods=[conv2d_1x1_0], expected_decisions=[decision_0], ) if __name__ == "__main__": tvm.testing.main()
https://github.com/zk-ml/tachikoma
tests/python/unittest/test_meta_schedule_schedule_rule_parallel_vectorize_unroll.py
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. # pylint: disable=missing-module-docstring,missing-function-docstring,missing-class-docstring import tvm from tvm import meta_schedule as ms from tvm.meta_schedule.testing.space_generation import ( check_sketches, generate_design_space, ) from tvm.script import tir as T from tvm.target import Target # fmt: off # pylint: disable=no-member,invalid-name,unused-variable,no-self-argument,line-too-long,chained-comparison,not-callable,too-many-nested-blocks @tvm.script.ir_module class Matmul: @T.prim_func def main(a: T.handle, b: T.handle, c: T.handle) -> None: T.func_attr({"global_symbol": "main"}) A = T.match_buffer(a, (1024, 1024), "float32") B = T.match_buffer(b, (1024, 1024), "float32") C = T.match_buffer(c, (1024, 1024), "float32") for i, j, k in T.grid(1024, 1024, 1024): with T.block("matmul"): vi, vj, vk = T.axis.remap("SSR", [i, j, k]) with T.init(): C[vi, vj] = 0.0 C[vi, vj] = C[vi, vj] + A[vi, vk] * B[vk, vj] @tvm.script.ir_module class ParallelizeVectorizeUnroll: @T.prim_func def main(a: T.handle, b: T.handle, c: T.handle) -> None: T.func_attr({"global_symbol": "main"}) A = T.match_buffer(a, (1024, 1024), "float32") B = T.match_buffer(b, (1024, 1024), "float32") C = T.match_buffer(c, (1024, 1024), "float32") with T.block("root"): T.reads([]) T.writes([]) T.block_attr({"meta_schedule.parallel": 128, "meta_schedule.vectorize": 16, "meta_schedule.unroll_explicit": 2}) for i, j, k in T.grid(1024, 1024, 1024): with T.block("matmul"): vi, vj, vk = T.axis.remap("SSR", [i, j, k]) with T.init(): C[vi, vj] = 0.0 C[vi, vj] = C[vi, vj] + A[vi, vk] * B[vk, vj] # from tvm.script import tir as T @tvm.script.ir_module class PureSpatial: @T.prim_func def main(placeholder: T.Buffer[(1, 13, 13, 3, 85), "float32"], placeholder_1: T.Buffer[(1, 26, 26, 3, 85), "float32"], placeholder_2: T.Buffer[(1, 52, 52, 3, 85), "float32"], T_expand_dims: T.Buffer[(1, 80, 10647), "float32"]) -> None: T.func_attr({"global_symbol": "main", "tir.noalias": True}) T_strided_slice_with_axes = T.alloc_buffer([1, 52, 52, 3, 1], dtype="float32") T_sigmoid = T.alloc_buffer([1, 52, 52, 3, 1], dtype="float32") T_strided_slice_with_axes_1 = T.alloc_buffer([1, 52, 52, 3, 80], dtype="float32") T_sigmoid_1 = T.alloc_buffer([1, 52, 52, 3, 80], dtype="float32") T_multiply = T.alloc_buffer([1, 52, 52, 3, 80], dtype="float32") T_reshape = T.alloc_buffer([8112, 80], dtype="float32") T_strided_slice_with_axes_2 = T.alloc_buffer([1, 26, 26, 3, 1], dtype="float32") T_sigmoid_2 = T.alloc_buffer([1, 26, 26, 3, 1], dtype="float32") T_strided_slice_with_axes_3 = T.alloc_buffer([1, 26, 26, 3, 80], dtype="float32") T_sigmoid_3 = T.alloc_buffer([1, 26, 26, 3, 80], dtype="float32") T_multiply_1 = T.alloc_buffer([1, 26, 26, 3, 80], dtype="float32") T_reshape_1 = T.alloc_buffer([2028, 80], dtype="float32") T_strided_slice_with_axes_4 = T.alloc_buffer([1, 13, 13, 3, 1], dtype="float32") T_sigmoid_4 = T.alloc_buffer([1, 13, 13, 3, 1], dtype="float32") T_strided_slice_with_axes_5 = T.alloc_buffer([1, 13, 13, 3, 80], dtype="float32") T_sigmoid_5 = T.alloc_buffer([1, 13, 13, 3, 80], dtype="float32") T_multiply_2 = T.alloc_buffer([1, 13, 13, 3, 80], dtype="float32") T_reshape_2 = T.alloc_buffer([507, 80], dtype="float32") T_concat = T.alloc_buffer([10647, 80], dtype="float32") T_transpose = T.alloc_buffer([80, 10647], dtype="float32") for i0, i1, i2, i3, i4 in T.grid(1, 52, 52, 3, 1): with T.block("T_strided_slice_with_axes"): ax0, ax1, ax2, ax3, ax4 = T.axis.remap("SSSSS", [i0, i1, i2, i3, i4]) T.reads(placeholder_2[ax0, ax1, ax2, ax3, T.cast(ax4, "int64") + T.int64(4)]) T.writes(T_strided_slice_with_axes[ax0, ax1, ax2, ax3, ax4]) T_strided_slice_with_axes[ax0, ax1, ax2, ax3, ax4] = placeholder_2[ax0, ax1, ax2, ax3, T.cast(ax4, "int64") + T.int64(4)] for i0, i1, i2, i3, i4 in T.grid(1, 52, 52, 3, 1): with T.block("T_sigmoid"): ax0, ax1, ax2, ax3, ax4 = T.axis.remap("SSSSS", [i0, i1, i2, i3, i4]) T.reads(T_strided_slice_with_axes[ax0, ax1, ax2, ax3, ax4]) T.writes(T_sigmoid[ax0, ax1, ax2, ax3, ax4]) T_sigmoid[ax0, ax1, ax2, ax3, ax4] = T.sigmoid(T_strided_slice_with_axes[ax0, ax1, ax2, ax3, ax4], dtype="float32") for i0, i1, i2, i3, i4 in T.grid(1, 52, 52, 3, 80): with T.block("T_strided_slice_with_axes_1"): ax0, ax1, ax2, ax3, ax4 = T.axis.remap("SSSSS", [i0, i1, i2, i3, i4]) T.reads(placeholder_2[ax0, ax1, ax2, ax3, T.cast(ax4, "int64") + T.int64(5)]) T.writes(T_strided_slice_with_axes_1[ax0, ax1, ax2, ax3, ax4]) T_strided_slice_with_axes_1[ax0, ax1, ax2, ax3, ax4] = placeholder_2[ax0, ax1, ax2, ax3, T.cast(ax4, "int64") + T.int64(5)] for i0, i1, i2, i3, i4 in T.grid(1, 52, 52, 3, 80): with T.block("T_sigmoid_1"): ax0, ax1, ax2, ax3, ax4 = T.axis.remap("SSSSS", [i0, i1, i2, i3, i4]) T.reads(T_strided_slice_with_axes_1[ax0, ax1, ax2, ax3, ax4]) T.writes(T_sigmoid_1[ax0, ax1, ax2, ax3, ax4]) T_sigmoid_1[ax0, ax1, ax2, ax3, ax4] = T.sigmoid(T_strided_slice_with_axes_1[ax0, ax1, ax2, ax3, ax4], dtype="float32") for i0, i1, i2, i3, i4 in T.grid(1, 52, 52, 3, 80): with T.block("T_multiply"): ax0, ax1, ax2, ax3, ax4 = T.axis.remap("SSSSS", [i0, i1, i2, i3, i4]) T.reads(T_sigmoid[ax0, ax1, ax2, ax3, 0], T_sigmoid_1[ax0, ax1, ax2, ax3, ax4]) T.writes(T_multiply[ax0, ax1, ax2, ax3, ax4]) T_multiply[ax0, ax1, ax2, ax3, ax4] = T_sigmoid[ax0, ax1, ax2, ax3, 0] * T_sigmoid_1[ax0, ax1, ax2, ax3, ax4] for i0, i1 in T.grid(8112, 80): with T.block("T_reshape"): ax0, ax1 = T.axis.remap("SS", [i0, i1]) T.reads(T_multiply[0, (ax1 // 80 + ax0) % 8112 // 156, (ax1 // 80 + ax0) % 156 // 3, (ax1 // 80 + ax0) % 3, ax1 % 80]) T.writes(T_reshape[ax0, ax1]) T_reshape[ax0, ax1] = T_multiply[0, (ax1 // 80 + ax0) % 8112 // 156, (ax1 // 80 + ax0) % 156 // 3, (ax1 // 80 + ax0) % 3, ax1 % 80] for i0, i1, i2, i3, i4 in T.grid(1, 26, 26, 3, 1): with T.block("T_strided_slice_with_axes_2"): ax0, ax1, ax2, ax3, ax4 = T.axis.remap("SSSSS", [i0, i1, i2, i3, i4]) T.reads(placeholder_1[ax0, ax1, ax2, ax3, T.cast(ax4, "int64") + T.int64(4)]) T.writes(T_strided_slice_with_axes_2[ax0, ax1, ax2, ax3, ax4]) T_strided_slice_with_axes_2[ax0, ax1, ax2, ax3, ax4] = placeholder_1[ax0, ax1, ax2, ax3, T.cast(ax4, "int64") + T.int64(4)] for i0, i1, i2, i3, i4 in T.grid(1, 26, 26, 3, 1): with T.block("T_sigmoid_2"): ax0, ax1, ax2, ax3, ax4 = T.axis.remap("SSSSS", [i0, i1, i2, i3, i4]) T.reads(T_strided_slice_with_axes_2[ax0, ax1, ax2, ax3, ax4]) T.writes(T_sigmoid_2[ax0, ax1, ax2, ax3, ax4]) T_sigmoid_2[ax0, ax1, ax2, ax3, ax4] = T.sigmoid(T_strided_slice_with_axes_2[ax0, ax1, ax2, ax3, ax4], dtype="float32") for i0, i1, i2, i3, i4 in T.grid(1, 26, 26, 3, 80): with T.block("T_strided_slice_with_axes_3"): ax0, ax1, ax2, ax3, ax4 = T.axis.remap("SSSSS", [i0, i1, i2, i3, i4]) T.reads(placeholder_1[ax0, ax1, ax2, ax3, T.cast(ax4, "int64") + T.int64(5)]) T.writes(T_strided_slice_with_axes_3[ax0, ax1, ax2, ax3, ax4]) T_strided_slice_with_axes_3[ax0, ax1, ax2, ax3, ax4] = placeholder_1[ax0, ax1, ax2, ax3, T.cast(ax4, "int64") + T.int64(5)] for i0, i1, i2, i3, i4 in T.grid(1, 26, 26, 3, 80): with T.block("T_sigmoid_3"): ax0, ax1, ax2, ax3, ax4 = T.axis.remap("SSSSS", [i0, i1, i2, i3, i4]) T.reads(T_strided_slice_with_axes_3[ax0, ax1, ax2, ax3, ax4]) T.writes(T_sigmoid_3[ax0, ax1, ax2, ax3, ax4]) T_sigmoid_3[ax0, ax1, ax2, ax3, ax4] = T.sigmoid(T_strided_slice_with_axes_3[ax0, ax1, ax2, ax3, ax4], dtype="float32") for i0, i1, i2, i3, i4 in T.grid(1, 26, 26, 3, 80): with T.block("T_multiply_1"): ax0, ax1, ax2, ax3, ax4 = T.axis.remap("SSSSS", [i0, i1, i2, i3, i4]) T.reads(T_sigmoid_2[ax0, ax1, ax2, ax3, 0], T_sigmoid_3[ax0, ax1, ax2, ax3, ax4]) T.writes(T_multiply_1[ax0, ax1, ax2, ax3, ax4]) T_multiply_1[ax0, ax1, ax2, ax3, ax4] = T_sigmoid_2[ax0, ax1, ax2, ax3, 0] * T_sigmoid_3[ax0, ax1, ax2, ax3, ax4] for i0, i1 in T.grid(2028, 80): with T.block("T_reshape_1"): ax0, ax1 = T.axis.remap("SS", [i0, i1]) T.reads(T_multiply_1[0, (ax1 // 80 + ax0) % 2028 // 78, (ax1 // 80 + ax0) % 78 // 3, (ax1 // 80 + ax0) % 3, ax1 % 80]) T.writes(T_reshape_1[ax0, ax1]) T_reshape_1[ax0, ax1] = T_multiply_1[0, (ax1 // 80 + ax0) % 2028 // 78, (ax1 // 80 + ax0) % 78 // 3, (ax1 // 80 + ax0) % 3, ax1 % 80] for i0, i1, i2, i3, i4 in T.grid(1, 13, 13, 3, 1): with T.block("T_strided_slice_with_axes_4"): ax0, ax1, ax2, ax3, ax4 = T.axis.remap("SSSSS", [i0, i1, i2, i3, i4]) T.reads(placeholder[ax0, ax1, ax2, ax3, T.cast(ax4, "int64") + T.int64(4)]) T.writes(T_strided_slice_with_axes_4[ax0, ax1, ax2, ax3, ax4]) T_strided_slice_with_axes_4[ax0, ax1, ax2, ax3, ax4] = placeholder[ax0, ax1, ax2, ax3, T.cast(ax4, "int64") + T.int64(4)] for i0, i1, i2, i3, i4 in T.grid(1, 13, 13, 3, 1): with T.block("T_sigmoid_4"): ax0, ax1, ax2, ax3, ax4 = T.axis.remap("SSSSS", [i0, i1, i2, i3, i4]) T.reads(T_strided_slice_with_axes_4[ax0, ax1, ax2, ax3, ax4]) T.writes(T_sigmoid_4[ax0, ax1, ax2, ax3, ax4]) T_sigmoid_4[ax0, ax1, ax2, ax3, ax4] = T.sigmoid(T_strided_slice_with_axes_4[ax0, ax1, ax2, ax3, ax4], dtype="float32") for i0, i1, i2, i3, i4 in T.grid(1, 13, 13, 3, 80): with T.block("T_strided_slice_with_axes_5"): ax0, ax1, ax2, ax3, ax4 = T.axis.remap("SSSSS", [i0, i1, i2, i3, i4]) T.reads(placeholder[ax0, ax1, ax2, ax3, T.cast(ax4, "int64") + T.int64(5)]) T.writes(T_strided_slice_with_axes_5[ax0, ax1, ax2, ax3, ax4]) T_strided_slice_with_axes_5[ax0, ax1, ax2, ax3, ax4] = placeholder[ax0, ax1, ax2, ax3, T.cast(ax4, "int64") + T.int64(5)] for i0, i1, i2, i3, i4 in T.grid(1, 13, 13, 3, 80): with T.block("T_sigmoid_5"): ax0, ax1, ax2, ax3, ax4 = T.axis.remap("SSSSS", [i0, i1, i2, i3, i4]) T.reads(T_strided_slice_with_axes_5[ax0, ax1, ax2, ax3, ax4]) T.writes(T_sigmoid_5[ax0, ax1, ax2, ax3, ax4]) T_sigmoid_5[ax0, ax1, ax2, ax3, ax4] = T.sigmoid(T_strided_slice_with_axes_5[ax0, ax1, ax2, ax3, ax4], dtype="float32") for i0, i1, i2, i3, i4 in T.grid(1, 13, 13, 3, 80): with T.block("T_multiply_2"): ax0, ax1, ax2, ax3, ax4 = T.axis.remap("SSSSS", [i0, i1, i2, i3, i4]) T.reads(T_sigmoid_4[ax0, ax1, ax2, ax3, 0], T_sigmoid_5[ax0, ax1, ax2, ax3, ax4]) T.writes(T_multiply_2[ax0, ax1, ax2, ax3, ax4]) T_multiply_2[ax0, ax1, ax2, ax3, ax4] = T_sigmoid_4[ax0, ax1, ax2, ax3, 0] * T_sigmoid_5[ax0, ax1, ax2, ax3, ax4] for i0, i1 in T.grid(507, 80): with T.block("T_reshape_2"): ax0, ax1 = T.axis.remap("SS", [i0, i1]) T.reads(T_multiply_2[0, (ax1 // 80 + ax0) % 507 // 39, (ax1 // 80 + ax0) % 39 // 3, (ax1 // 80 + ax0) % 3, ax1 % 80]) T.writes(T_reshape_2[ax0, ax1]) T_reshape_2[ax0, ax1] = T_multiply_2[0, (ax1 // 80 + ax0) % 507 // 39, (ax1 // 80 + ax0) % 39 // 3, (ax1 // 80 + ax0) % 3, ax1 % 80] for i0, i1 in T.grid(10647, 80): with T.block("T_concat"): ax0, ax1 = T.axis.remap("SS", [i0, i1]) T.reads(T_reshape[ax0 - 2535, ax1], T_reshape_1[ax0 - 507, ax1], T_reshape_2[ax0, ax1]) T.writes(T_concat[ax0, ax1]) T_concat[ax0, ax1] = T.if_then_else(2535 <= ax0, T_reshape[ax0 - 2535, ax1], T.if_then_else(507 <= ax0, T_reshape_1[ax0 - 507, ax1], T_reshape_2[ax0, ax1], dtype="float32"), dtype="float32") for i0, i1 in T.grid(80, 10647): with T.block("T_transpose"): ax0, ax1 = T.axis.remap("SS", [i0, i1]) T.reads(T_concat[ax1, ax0]) T.writes(T_transpose[ax0, ax1]) T_transpose[ax0, ax1] = T_concat[ax1, ax0] for i0, i1, i2 in T.grid(1, 80, 10647): with T.block("T_expand_dims"): ax0, ax1, ax2 = T.axis.remap("SSS", [i0, i1, i2]) T.reads(T_transpose[ax1, ax2]) T.writes(T_expand_dims[ax0, ax1, ax2]) T_expand_dims[ax0, ax1, ax2] = T_transpose[ax1, ax2] # pylint: enable=no-member,invalid-name,unused-variable,no-self-argument,line-too-long,chained-comparison,not-callable,too-many-nested-blocks # fmt: on def test_parallel_vectorize_unroll(): @T.prim_func def Matmul_0( A: T.Buffer[(1024, 1024), "float32"], B: T.Buffer[(1024, 1024), "float32"], C: T.Buffer[(1024, 1024), "float32"], ) -> None: # function attr dict T.func_attr({"global_symbol": "main"}) # body with T.block("root"): T.reads() T.writes() T.block_attr( { "meta_schedule.parallel": 512, "meta_schedule.unroll_explicit": 16, "meta_schedule.vectorize": 32, } ) for i, j, k in T.grid(1024, 1024, 1024): with T.block("matmul"): vi, vj, vk = T.axis.remap("SSR", [i, j, k]) T.reads(A[vi, vk], B[vk, vj]) T.writes(C[vi, vj]) with T.init(): C[vi, vj] = T.float32(0) C[vi, vj] = C[vi, vj] + A[vi, vk] * B[vk, vj] decision_0 = [ ("SampleCategorical", 1), ] mod = Matmul actual = generate_design_space( kind="llvm", mod=mod, target=Target("llvm --num-cores=32"), types=None, sch_rules=[ ms.schedule_rule.ParallelizeVectorizeUnroll( max_jobs_per_core=16, max_vectorize_extent=32, unroll_max_steps=[0, 16, 64, 512], unroll_explicit=True, ), ], ) check_sketches( mod, sketches=actual, expected_mods=[Matmul_0], expected_decisions=[decision_0], ) def test_parallel_vectorize_unroll_spatial(): mod = PureSpatial actual = generate_design_space( kind="llvm", mod=mod, target=Target("llvm --num-cores=32"), types=None, sch_rules=[ ms.schedule_rule.ParallelizeVectorizeUnroll( max_jobs_per_core=-1, max_vectorize_extent=-1, unroll_max_steps=[0, 16, 64, 512], unroll_explicit=True, ), ], ) assert len(actual) == 1 trace = actual[0].trace.simplified(remove_postproc=True) assert not trace.insts if __name__ == "__main__": test_parallel_vectorize_unroll() test_parallel_vectorize_unroll_spatial()
https://github.com/zk-ml/tachikoma
tests/python/unittest/test_meta_schedule_schedule_rule_random_compute_location.py
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. # pylint: disable=missing-module-docstring,missing-function-docstring,missing-class-docstring import tvm from tvm import meta_schedule as ms from tvm.meta_schedule.testing.space_generation import ( check_sketches, generate_design_space, ) from tvm.script import tir as T from tvm.target import Target # fmt: off # pylint: disable=no-member,invalid-name,unused-variable,no-self-argument,line-too-long,chained-comparison,not-callable,too-many-nested-blocks @tvm.script.ir_module class Add: @T.prim_func def main(a: T.handle, b: T.handle) -> None: # function attr dict T.func_attr({"global_symbol": "main"}) A = T.match_buffer(a, [2048, 2048, 2048], dtype="float32") B = T.match_buffer(b, [2048, 2048, 2048], dtype="float32") A_cached = T.alloc_buffer([2048, 2048, 2048], dtype="float32") # body for i, j, k in T.grid(2048, 2048, 2048): with T.block("move"): vi, vj, vk = T.axis.remap("SSS", [i, j, k]) T.reads([A[vi, vj, vk]]) T.writes([A_cached[vi, vj, vk]]) A_cached[vi, vj, vk] = A[vi, vj, vk] for i0, j0, i1, j1, k0, i2, j2, k1 in T.grid(128, 64, 4, 4, 64, 4, 8, 32): with T.block("add"): vi = T.axis.spatial(2048, i0 * 16 + i1 * 4 + i2) vj = T.axis.spatial(2048, j0 * 32 + j1 * 8 + j2) vk = T.axis.spatial(2048, k0 * 32 + k1) T.reads([A_cached[vi, vj, vk]]) T.writes([B[vi, vj, vk]]) B[vi, vj, vk] = A_cached[vi, vj, vk] + T.float32(1) # pylint: enable=no-member,invalid-name,unused-variable,no-self-argument,line-too-long,chained-comparison,not-callable,too-many-nested-blocks # fmt: on def test_random_compute_location(): @T.prim_func def add_0( A: T.Buffer[(2048, 2048, 2048), "float32"], B: T.Buffer[(2048, 2048, 2048), "float32"], ) -> None: # function attr dict T.func_attr({"global_symbol": "main"}) # body # with T.block("root") A_cached = T.alloc_buffer([2048, 2048, 2048], dtype="float32") for i0, j0, i1, j1, k0, i2 in T.grid(128, 64, 4, 4, 64, 4): for ax0, ax1, ax2 in T.grid(1, 8, 32): with T.block("move"): vi = T.axis.spatial(2048, i0 * 16 + i1 * 4 + i2 + ax0) vj = T.axis.spatial(2048, j0 * 32 + j1 * 8 + ax1) vk = T.axis.spatial(2048, k0 * 32 + ax2) T.reads(A[vi, vj, vk]) T.writes(A_cached[vi, vj, vk]) A_cached[vi, vj, vk] = A[vi, vj, vk] for j2, k1 in T.grid(8, 32): with T.block("add"): vi = T.axis.spatial(2048, i0 * 16 + i1 * 4 + i2) vj = T.axis.spatial(2048, j0 * 32 + j1 * 8 + j2) vk = T.axis.spatial(2048, k0 * 32 + k1) T.reads(A_cached[vi, vj, vk]) T.writes(B[vi, vj, vk]) B[vi, vj, vk] = A_cached[vi, vj, vk] + T.float32(1) decision_0 = [ ("SampleComputeLocation", 5), ] mod = Add actual = generate_design_space( kind="llvm", mod=mod, target=Target("llvm"), types=None, sch_rules=[ms.schedule_rule.RandomComputeLocation()], ) check_sketches( mod, sketches=actual, expected_mods=[add_0], expected_decisions=[decision_0], ) if __name__ == "__main__": test_random_compute_location()
https://github.com/zk-ml/tachikoma
tests/python/unittest/test_meta_schedule_search_strategy.py
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. """ Test Meta Schedule SearchStrategy """ # pylint: disable=missing-function-docstring from typing import List import pytest import tvm import tvm.testing from tvm import meta_schedule as ms from tvm.meta_schedule.utils import derived_object from tvm.meta_schedule.testing.dummy_object import DummyMutator from tvm.script import tir as T from tvm.tir.schedule import Schedule, Trace MATMUL_M = 32 # pylint: disable=missing-class-docstring,invalid-name,no-member,line-too-long,too-many-nested-blocks,no-self-argument, unbalanced-tuple-unpacking # fmt: off @tvm.script.ir_module class Matmul: @T.prim_func def main(a: T.handle, b: T.handle, c: T.handle) -> None: # type: ignore T.func_attr({"global_symbol": "main"}) A = T.match_buffer(a, (32, 32), "float32") B = T.match_buffer(b, (32, 32), "float32") C = T.match_buffer(c, (32, 32), "float32") for i, j, k in T.grid(32, 32, 32): with T.block("matmul"): vi, vj, vk = T.axis.remap("SSR", [i, j, k]) with T.init(): C[vi, vj] = 0.0 # type: ignore C[vi, vj] = C[vi, vj] + A[vi, vk] * B[vk, vj] # fmt: on # pylint: enable=missing-class-docstring,invalid-name,no-member,line-too-long,too-many-nested-blocks,no-self-argument def _is_trace_equal(sch_1: Schedule, sch_2: Schedule, remove_decisions=True) -> bool: if remove_decisions: trace_1 = Trace(sch_1.trace.insts, {}) trace_2 = Trace(sch_2.trace.insts, {}) else: trace_1 = sch_1.trace trace_2 = sch_2.trace return str(trace_1) == str(trace_2) def _schedule_matmul(sch: Schedule): block = sch.get_block("matmul") i, j, k = sch.get_loops(block=block) i_0, i_1, i_2, i_3 = sch.split(i, sch.sample_perfect_tile(i, n=4)) j_0, j_1, j_2, j_3 = sch.split(j, sch.sample_perfect_tile(j, n=4)) k_0, k_1 = sch.split(k, sch.sample_perfect_tile(k, n=2)) sch.reorder(i_0, j_0, i_1, j_1, k_0, i_2, j_2, k_1, i_3, j_3) @pytest.mark.parametrize( "TestClass", [ ms.search_strategy.ReplayFunc, ms.search_strategy.ReplayTrace, ], ) def test_meta_schedule_replay_func( TestClass: ms.search_strategy.SearchStrategy, ): # pylint: disable = invalid-name num_trials_per_iter = 7 max_trials_per_task = 20 context = ms.TuneContext( mod=Matmul, space_generator=ms.space_generator.ScheduleFn(sch_fn=_schedule_matmul, postprocs=[]), search_strategy=TestClass(), ) strategy = context.search_strategy spaces = context.space_generator.generate_design_space(context.mod) strategy.pre_tuning( max_trials=max_trials_per_task, num_trials_per_iter=num_trials_per_iter, design_spaces=spaces, ) (correct_sch,) = ms.space_generator.ScheduleFn(sch_fn=_schedule_matmul).generate_design_space( Matmul ) num_trials_each_iter: List[int] = [] candidates = strategy.generate_measure_candidates() while candidates is not None: num_trials_each_iter.append(len(candidates)) runner_results: List[ms.runner.RunnerResult] = [] for candidate in candidates: _is_trace_equal( candidate.sch, correct_sch, remove_decisions=(isinstance(strategy, ms.search_strategy.ReplayTrace)), ) runner_results.append( ms.runner.RunnerResult( run_secs=[0.11, 0.41, 0.54], error_msg=None, ) ) strategy.notify_runner_results(candidates, runner_results) candidates = strategy.generate_measure_candidates() strategy.post_tuning() assert num_trials_each_iter == [7, 7, 6] def test_meta_schedule_evolutionary_search(): # pylint: disable = invalid-name def _schedule_matmul_small(sch: Schedule): block = sch.get_block("matmul") _, j, k = sch.get_loops(block=block) _, _ = sch.split(j, sch.sample_perfect_tile(j, n=2)) _, _ = sch.split(k, sch.sample_perfect_tile(k, n=2)) num_trials_per_iter = 10 max_trials_per_task = 2000 (correct_sch,) = ms.space_generator.ScheduleFn(sch_fn=_schedule_matmul).generate_design_space( Matmul ) context = ms.TuneContext( mod=Matmul, space_generator=ms.space_generator.ScheduleFn( sch_fn=_schedule_matmul_small, sch_rules=[], postprocs=[], mutator_probs={ DummyMutator(): 1.0, }, ), search_strategy=ms.search_strategy.EvolutionarySearch( population_size=5, init_measured_ratio=0.1, init_min_unmeasured=50, genetic_num_iters=3, genetic_mutate_prob=0.5, genetic_max_fail_count=10, eps_greedy=0.9, ), target=tvm.target.Target("llvm"), num_threads=1, # because we are using a mutator from the python side ) strategy = context.search_strategy strategy.pre_tuning( max_trials=max_trials_per_task, num_trials_per_iter=num_trials_per_iter, design_spaces=context.space_generator.generate_design_space(context.mod), database=ms.database.MemoryDatabase(), cost_model=ms.cost_model.RandomModel(), ) num_trials_each_iter: List[int] = [] candidates = strategy.generate_measure_candidates() while candidates is not None: num_trials_each_iter.append(len(candidates)) runner_results: List[ms.runner.RunnerResult] = [] for candidate in candidates: _is_trace_equal( candidate.sch, correct_sch, remove_decisions=(isinstance(strategy, ms.search_strategy.ReplayTrace)), ) runner_results.append( ms.runner.RunnerResult( run_secs=[0.11, 0.41, 0.54], error_msg=None, ) ) strategy.notify_runner_results(candidates, runner_results) candidates = strategy.generate_measure_candidates() strategy.post_tuning() assert sum(num_trials_each_iter) == 25 assert num_trials_each_iter.count(0) < 5 def test_meta_schedule_evolutionary_search_early_stop(): # pylint: disable = invalid-name def _schedule_matmul_empty(sch: Schedule): return sch (correct_sch,) = ms.space_generator.ScheduleFn(sch_fn=_schedule_matmul).generate_design_space( Matmul ) num_trials_per_iter = 10 max_trials_per_task = 100 context = ms.TuneContext( mod=Matmul, search_strategy=ms.search_strategy.EvolutionarySearch( population_size=5, init_measured_ratio=0.1, init_min_unmeasured=50, genetic_num_iters=3, genetic_mutate_prob=0.5, genetic_max_fail_count=10, eps_greedy=0.9, ), space_generator=ms.space_generator.ScheduleFn( sch_fn=_schedule_matmul_empty, sch_rules=[], postprocs=[], mutator_probs={ DummyMutator(): 1.0, }, ), target=tvm.target.Target("llvm"), num_threads=1, ) strategy = context.search_strategy strategy.pre_tuning( max_trials=max_trials_per_task, num_trials_per_iter=num_trials_per_iter, design_spaces=context.space_generator.generate_design_space(context.mod), database=ms.database.MemoryDatabase(), cost_model=ms.cost_model.RandomModel(), ) num_trials_each_iter: List[int] = [] candidates = strategy.generate_measure_candidates() while candidates is not None: num_trials_each_iter.append(len(candidates)) runner_results: List[ms.runner.RunnerResult] = [] for candidate in candidates: _is_trace_equal( candidate.sch, correct_sch, remove_decisions=(isinstance(strategy, ms.search_strategy.ReplayTrace)), ) runner_results.append( ms.runner.RunnerResult( run_secs=[0.11, 0.41, 0.54], error_msg=None, ), ) strategy.notify_runner_results(candidates, runner_results) candidates = strategy.generate_measure_candidates() strategy.post_tuning() assert num_trials_each_iter == [1, 0, 0, 0, 0] def test_meta_schedule_evolutionary_search_fail_init_population(): # pylint: disable = invalid-name @derived_object class AlwaysFailPostproc(ms.postproc.PyPostproc): """A postproc that always fails.""" def _initialize_with_tune_context(self, context: ms.TuneContext) -> None: pass def apply(self, sch: Schedule) -> bool: return False def clone(self) -> "AlwaysFailPostproc": return AlwaysFailPostproc() def __str__(self) -> str: return "AlwaysFailPostproc" num_trials_per_iter = 10 max_trials_per_task = 2000 context = ms.TuneContext( mod=Matmul, space_generator=ms.space_generator.ScheduleFn( sch_fn=_schedule_matmul, sch_rules=[], postprocs=[AlwaysFailPostproc()], mutator_probs={ DummyMutator(): 1.0, }, ), search_strategy=ms.search_strategy.EvolutionarySearch( population_size=5, init_measured_ratio=0.1, init_min_unmeasured=50, genetic_num_iters=3, genetic_mutate_prob=0.5, genetic_max_fail_count=10, eps_greedy=0.9, ), target=tvm.target.Target("llvm"), num_threads=1, # because we are using a mutator from the python side ) strategy = context.search_strategy strategy.pre_tuning( max_trials=max_trials_per_task, num_trials_per_iter=num_trials_per_iter, design_spaces=context.space_generator.generate_design_space(context.mod), database=ms.database.MemoryDatabase(), cost_model=ms.cost_model.RandomModel(), ) candidates = strategy.generate_measure_candidates() assert candidates is None if __name__ == "__main__": test_meta_schedule_replay_func(ms.search_strategy.ReplayFunc) test_meta_schedule_replay_func(ms.search_strategy.ReplayTrace) test_meta_schedule_evolutionary_search() test_meta_schedule_evolutionary_search_early_stop() test_meta_schedule_evolutionary_search_fail_init_population()
https://github.com/zk-ml/tachikoma
tests/python/unittest/test_meta_schedule_space_cpu.py
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. """Tests for MetaSchedule search space on CPU""" from tvm import meta_schedule as ms from tvm.meta_schedule.testing.space_generation import ( check_sketches, print_sketches, generate_design_space, ) from tvm.meta_schedule.testing.te_workload import create_te_workload from tvm.script import tir as T from tvm.target import Target def _target(): return Target("aws/cpu/c5.9xlarge") def _design_space(mod): return generate_design_space( kind="llvm", mod=mod, target=_target(), types=ms.ScheduleRule, ) def test_cpu_c1d(): # fmt: off @T.prim_func def c1d_0(inputs: T.Buffer[(1, 256, 64), "float32"], weight: T.Buffer[(3, 64, 128), "float32"], conv1d_nlc: T.Buffer[(1, 128, 128), "float32"]) -> None: # function attr dict T.func_attr({"global_symbol": "main", "tir.noalias": True}) # body with T.block("root"): T.reads() T.writes() T.block_attr({"meta_schedule.parallel":288, "meta_schedule.unroll_explicit":512, "meta_schedule.vectorize":64}) PadInput = T.alloc_buffer([1, 258, 64], dtype="float32") conv1d_nlc_global = T.alloc_buffer([1, 128, 128], dtype="float32") for i0, i1, i2 in T.grid(1, 258, 64): with T.block("PadInput"): i0_1, i1_1, i2_1 = T.axis.remap("SSS", [i0, i1, i2]) T.reads(inputs[i0_1, i1_1 - 1, i2_1]) T.writes(PadInput[i0_1, i1_1, i2_1]) PadInput[i0_1, i1_1, i2_1] = T.if_then_else(1 <= i1_1 and i1_1 < 257, inputs[i0_1, i1_1 - 1, i2_1], T.float32(0), dtype="float32") for i0_0, i1_0, i2_0, i0_1_1, i1_1_1, i2_1_1 in T.grid(1, 1, 2, 1, 1, 8): for i3_0, i4_0, i0_2, i1_2, i2_2, i3_1, i4_1, i0_3, i1_3, i2_3 in T.grid(1, 64, 1, 64, 8, 3, 1, 1, 2, 1): with T.block("conv1d_nlc"): n = T.axis.spatial(1, i0_1_1 + i0_2 + i0_3 + i0_0) l = T.axis.spatial(128, i1_0 * 128 + i1_1_1 * 128 + i1_2 * 2 + i1_3) co = T.axis.spatial(128, i2_3 + i2_0 * 64 + i2_1_1 * 8 + i2_2) rl = T.axis.reduce(3, i3_0 * 3 + i3_1) rc = T.axis.reduce(64, i4_1 + i4_0) T.reads(PadInput[n, l * 2 + rl, co // 128 * 64 + rc], weight[rl, rc, co]) T.writes(conv1d_nlc_global[n, l, co]) T.block_attr({"meta_schedule.tiling_structure":"SSRSRS"}) with T.init(): conv1d_nlc_global[n, l, co] = T.float32(0) conv1d_nlc_global[n, l, co] = conv1d_nlc_global[n, l, co] + PadInput[n, l * 2 + rl, co // 128 * 64 + rc] * weight[rl, rc, co] for ax0, ax1, ax2 in T.grid(1, 128, 8): with T.block("conv1d_nlc_global"): v0, v1 = T.axis.remap("SS", [ax0, ax1]) v2 = T.axis.spatial(128, i2_0 * 64 + i2_1_1 * 8 + ax2) T.reads(conv1d_nlc_global[v0, v1, v2]) T.writes(conv1d_nlc[v0, v1, v2]) conv1d_nlc[v0, v1, v2] = conv1d_nlc_global[v0, v1, v2] @T.prim_func def c1d_1(inputs: T.Buffer[(1, 256, 64), "float32"], weight: T.Buffer[(3, 64, 128), "float32"], conv1d_nlc: T.Buffer[(1, 128, 128), "float32"]) -> None: # function attr dict T.func_attr({"global_symbol": "main", "tir.noalias": True}) # body with T.block("root"): T.reads() T.writes() T.block_attr({"meta_schedule.parallel":288, "meta_schedule.unroll_explicit":512, "meta_schedule.vectorize":64}) PadInput = T.alloc_buffer([1, 258, 64], dtype="float32") conv1d_nlc_global = T.alloc_buffer([1, 128, 128], dtype="float32") for i0_0, i1_0, i2_0 in T.grid(1, 1, 2): for i0_1, i1_1, i2_1 in T.grid(1, 1, 8): for ax0, ax1, ax2 in T.grid(1, 257, 64): with T.block("PadInput"): i0 = T.axis.spatial(1, ax0) i1 = T.axis.spatial(258, ax1) i2 = T.axis.spatial(64, ax2) T.reads(inputs[i0, i1 - 1, i2]) T.writes(PadInput[i0, i1, i2]) PadInput[i0, i1, i2] = T.if_then_else(1 <= i1 and i1 < 257, inputs[i0, i1 - 1, i2], T.float32(0), dtype="float32") for i3_0, i4_0, i0_2, i1_2, i2_2, i3_1, i4_1, i0_3, i1_3, i2_3 in T.grid(1, 64, 1, 64, 8, 3, 1, 1, 2, 1): with T.block("conv1d_nlc"): n = T.axis.spatial(1, i0_1 + i0_2 + i0_3 + i0_0) l = T.axis.spatial(128, i1_0 * 128 + i1_1 * 128 + i1_2 * 2 + i1_3) co = T.axis.spatial(128, i2_3 + i2_0 * 64 + i2_1 * 8 + i2_2) rl = T.axis.reduce(3, i3_0 * 3 + i3_1) rc = T.axis.reduce(64, i4_1 + i4_0) T.reads(PadInput[n, l * 2 + rl, co // 128 * 64 + rc], weight[rl, rc, co]) T.writes(conv1d_nlc_global[n, l, co]) T.block_attr({"meta_schedule.tiling_structure":"SSRSRS"}) with T.init(): conv1d_nlc_global[n, l, co] = T.float32(0) conv1d_nlc_global[n, l, co] = conv1d_nlc_global[n, l, co] + PadInput[n, l * 2 + rl, co // 128 * 64 + rc] * weight[rl, rc, co] for ax0, ax1, ax2 in T.grid(1, 128, 64): with T.block("conv1d_nlc_global"): v0, v1 = T.axis.remap("SS", [ax0, ax1]) v2 = T.axis.spatial(128, i2_0 * 64 + ax2) T.reads(conv1d_nlc_global[v0, v1, v2]) T.writes(conv1d_nlc[v0, v1, v2]) conv1d_nlc[v0, v1, v2] = conv1d_nlc_global[v0, v1, v2] @T.prim_func def c1d_2(inputs: T.Buffer[(1, 256, 64), "float32"], weight: T.Buffer[(3, 64, 128), "float32"], conv1d_nlc: T.Buffer[(1, 128, 128), "float32"]) -> None: # function attr dict T.func_attr({"global_symbol": "main", "tir.noalias": True}) # body with T.block("root"): T.reads() T.writes() T.block_attr({"meta_schedule.parallel":288, "meta_schedule.unroll_explicit":16, "meta_schedule.vectorize":64}) for i0_0, i1_0, i2_0, i0_1, i1_1, i2_1, i3_0, i4_0, i0_2, i1_2, i2_2, i3_1, i4_1, i0_3, i1_3, i2_3 in T.grid(1, 1, 2, 1, 1, 8, 1, 64, 1, 64, 8, 3, 1, 1, 2, 1): with T.block("conv1d_nlc"): n = T.axis.spatial(1, i0_1 + i0_2 + i0_3 + i0_0) l = T.axis.spatial(128, i1_0 * 128 + i1_1 * 128 + i1_2 * 2 + i1_3) co = T.axis.spatial(128, i2_3 + i2_0 * 64 + i2_1 * 8 + i2_2) rl = T.axis.reduce(3, i3_0 * 3 + i3_1) rc = T.axis.reduce(64, i4_1 + i4_0) T.reads(inputs[n, l * 2 + rl - 1, co // 128 * 64 + rc], weight[rl, rc, co]) T.writes(conv1d_nlc[n, l, co]) T.block_attr({"meta_schedule.tiling_structure":"SSRSRS"}) with T.init(): conv1d_nlc[n, l, co] = T.float32(0) conv1d_nlc[n, l, co] = conv1d_nlc[n, l, co] + T.if_then_else(1 <= l * 2 + rl and l * 2 + rl < 257, inputs[n, l * 2 + rl - 1, co // 128 * 64 + rc], T.float32(0), dtype="float32") * weight[rl, rc, co] # fmt: on decision_0 = [ ("SamplePerfectTile", [1, 1, 1, 1]), ("SamplePerfectTile", [1, 1, 64, 2]), ("SamplePerfectTile", [2, 8, 8, 1]), ("SamplePerfectTile", [1, 3]), ("SamplePerfectTile", [64, 1]), ("SampleCategorical", 3), ("SampleComputeLocation", -1), ] decision_1 = [ ("SamplePerfectTile", [1, 1, 1, 1]), ("SamplePerfectTile", [1, 1, 64, 2]), ("SamplePerfectTile", [2, 8, 8, 1]), ("SamplePerfectTile", [1, 3]), ("SamplePerfectTile", [64, 1]), ("SampleCategorical", 3), ("SampleComputeLocation", 5), ] decision_2 = [ ("SamplePerfectTile", [1, 1, 1, 1]), ("SamplePerfectTile", [1, 1, 64, 2]), ("SamplePerfectTile", [2, 8, 8, 1]), ("SamplePerfectTile", [1, 3]), ("SamplePerfectTile", [64, 1]), ("SampleCategorical", 1), ("SampleComputeLocation", -2), ] mod = create_te_workload("C1D", 0) actual = _design_space(mod) check_sketches( mod, sketches=actual, expected_mods=[c1d_0, c1d_1, c1d_2], expected_decisions=[decision_0, decision_1, decision_2], ) def test_cpu_c2d(): # fmt: off @T.prim_func def c2d_0(inputs: T.Buffer[(1, 224, 224, 3), "float32"], weight: T.Buffer[(7, 7, 3, 64), "float32"], conv2d_nhwc: T.Buffer[(1, 112, 112, 64), "float32"]) -> None: # function attr dict T.func_attr({"global_symbol": "main", "tir.noalias": True}) # body with T.block("root"): T.reads() T.writes() T.block_attr({"meta_schedule.parallel":288, "meta_schedule.unroll_explicit":16, "meta_schedule.vectorize":64}) PadInput = T.alloc_buffer([1, 230, 230, 3], dtype="float32") conv2d_nhwc_global = T.alloc_buffer([1, 112, 112, 64], dtype="float32") for i0_0, i1_0, i2_0, i3_0, i0_1, i1_1, i2_1 in T.grid(1, 7, 4, 2, 1, 1, 28): for ax0, ax1, ax2, ax3 in T.grid(1, 37, 7, 3): with T.block("PadInput"): i0 = T.axis.spatial(1, ax0) i1 = T.axis.spatial(230, i1_0 * 32 + ax1) i2 = T.axis.spatial(230, i2_0 * 56 + i2_1 * 2 + ax2) i3 = T.axis.spatial(3, ax3) T.reads(inputs[i0, i1 - 3, i2 - 3, i3]) T.writes(PadInput[i0, i1, i2, i3]) PadInput[i0, i1, i2, i3] = T.if_then_else(3 <= i1 and i1 < 227 and 3 <= i2 and i2 < 227, inputs[i0, i1 - 3, i2 - 3, i3], T.float32(0), dtype="float32") for i3_1 in T.serial(8): for i4_0, i5_0, i6_0, i0_2, i1_2, i2_2, i3_2, i4_1, i5_1, i6_1, i0_3, i1_3, i2_3, i3_3 in T.grid(7, 7, 1, 1, 2, 1, 1, 1, 1, 3, 1, 8, 1, 4): with T.block("conv2d_nhwc"): n = T.axis.spatial(1, i0_3 + i0_0 + i0_1 + i0_2) h = T.axis.spatial(112, i1_0 * 16 + i1_1 * 16 + i1_2 * 8 + i1_3) w = T.axis.spatial(112, i2_3 + i2_0 * 28 + i2_1 + i2_2) co = T.axis.spatial(64, i3_0 * 32 + i3_1 * 4 + i3_2 * 4 + i3_3) rh = T.axis.reduce(7, i4_1 + i4_0) rw = T.axis.reduce(7, i5_0 + i5_1) rc = T.axis.reduce(3, i6_0 * 3 + i6_1) T.reads(PadInput[n, h * 2 + rh, w * 2 + rw, co // 64 * 3 + rc], weight[rh, rw, rc, co]) T.writes(conv2d_nhwc_global[n, h, w, co]) T.block_attr({"meta_schedule.tiling_structure":"SSRSRS"}) with T.init(): conv2d_nhwc_global[n, h, w, co] = T.float32(0) conv2d_nhwc_global[n, h, w, co] = conv2d_nhwc_global[n, h, w, co] + PadInput[n, h * 2 + rh, w * 2 + rw, co // 64 * 3 + rc] * weight[rh, rw, rc, co] for ax0, ax1, ax2, ax3 in T.grid(1, 16, 1, 4): with T.block("conv2d_nhwc_global"): v0 = T.axis.spatial(1, ax0) v1 = T.axis.spatial(112, i1_0 * 16 + ax1) v2 = T.axis.spatial(112, i2_0 * 28 + i2_1 + ax2) v3 = T.axis.spatial(64, i3_0 * 32 + i3_1 * 4 + ax3) T.reads(conv2d_nhwc_global[v0, v1, v2, v3]) T.writes(conv2d_nhwc[v0, v1, v2, v3]) conv2d_nhwc[v0, v1, v2, v3] = conv2d_nhwc_global[v0, v1, v2, v3] @T.prim_func def c2d_1(inputs: T.Buffer[(1, 224, 224, 3), "float32"], weight: T.Buffer[(7, 7, 3, 64), "float32"], conv2d_nhwc: T.Buffer[(1, 112, 112, 64), "float32"]) -> None: # function attr dict T.func_attr({"global_symbol": "main", "tir.noalias": True}) # body with T.block("root"): T.reads() T.writes() T.block_attr({"meta_schedule.parallel":288, "meta_schedule.unroll_explicit":512, "meta_schedule.vectorize":64}) PadInput = T.alloc_buffer([1, 230, 230, 3], dtype="float32") conv2d_nhwc_global = T.alloc_buffer([1, 112, 112, 64], dtype="float32") for i0, i1, i2, i3 in T.grid(1, 230, 230, 3): with T.block("PadInput"): i0_1, i1_1, i2_1, i3_1 = T.axis.remap("SSSS", [i0, i1, i2, i3]) T.reads(inputs[i0_1, i1_1 - 3, i2_1 - 3, i3_1]) T.writes(PadInput[i0_1, i1_1, i2_1, i3_1]) PadInput[i0_1, i1_1, i2_1, i3_1] = T.if_then_else(3 <= i1_1 and i1_1 < 227 and 3 <= i2_1 and i2_1 < 227, inputs[i0_1, i1_1 - 3, i2_1 - 3, i3_1], T.float32(0), dtype="float32") for i0_0, i1_0, i2_0, i3_0 in T.grid(1, 7, 4, 2): for i0_1_1, i1_1_1, i2_1_1, i3_1_1, i4_0, i5_0, i6_0, i0_2, i1_2, i2_2, i3_2, i4_1, i5_1, i6_1, i0_3, i1_3, i2_3, i3_3 in T.grid(1, 1, 28, 8, 7, 7, 1, 1, 2, 1, 1, 1, 1, 3, 1, 8, 1, 4): with T.block("conv2d_nhwc"): n = T.axis.spatial(1, i0_3 + i0_0 + i0_1_1 + i0_2) h = T.axis.spatial(112, i1_0 * 16 + i1_1_1 * 16 + i1_2 * 8 + i1_3) w = T.axis.spatial(112, i2_3 + i2_0 * 28 + i2_1_1 + i2_2) co = T.axis.spatial(64, i3_0 * 32 + i3_1_1 * 4 + i3_2 * 4 + i3_3) rh = T.axis.reduce(7, i4_1 + i4_0) rw = T.axis.reduce(7, i5_0 + i5_1) rc = T.axis.reduce(3, i6_0 * 3 + i6_1) T.reads(PadInput[n, h * 2 + rh, w * 2 + rw, co // 64 * 3 + rc], weight[rh, rw, rc, co]) T.writes(conv2d_nhwc_global[n, h, w, co]) T.block_attr({"meta_schedule.tiling_structure":"SSRSRS"}) with T.init(): conv2d_nhwc_global[n, h, w, co] = T.float32(0) conv2d_nhwc_global[n, h, w, co] = conv2d_nhwc_global[n, h, w, co] + PadInput[n, h * 2 + rh, w * 2 + rw, co // 64 * 3 + rc] * weight[rh, rw, rc, co] for ax0, ax1, ax2, ax3 in T.grid(1, 16, 28, 32): with T.block("conv2d_nhwc_global"): v0 = T.axis.spatial(1, ax0) v1 = T.axis.spatial(112, i1_0 * 16 + ax1) v2 = T.axis.spatial(112, i2_0 * 28 + ax2) v3 = T.axis.spatial(64, i3_0 * 32 + ax3) T.reads(conv2d_nhwc_global[v0, v1, v2, v3]) T.writes(conv2d_nhwc[v0, v1, v2, v3]) conv2d_nhwc[v0, v1, v2, v3] = conv2d_nhwc_global[v0, v1, v2, v3] @T.prim_func def c2d_2(inputs: T.Buffer[(1, 224, 224, 3), "float32"], weight: T.Buffer[(7, 7, 3, 64), "float32"], conv2d_nhwc: T.Buffer[(1, 112, 112, 64), "float32"]) -> None: # function attr dict T.func_attr({"global_symbol": "main", "tir.noalias": True}) # body with T.block("root"): T.reads() T.writes() T.block_attr({"meta_schedule.parallel":288, "meta_schedule.unroll_explicit":0, "meta_schedule.vectorize":64}) PadInput = T.alloc_buffer([1, 230, 230, 3], dtype="float32") for i0_0, i1_0 in T.grid(1, 7): for ax0, ax1, ax2, ax3 in T.grid(1, 37, 229, 3): with T.block("PadInput"): i0 = T.axis.spatial(1, ax0) i1 = T.axis.spatial(230, i1_0 * 32 + ax1) i2 = T.axis.spatial(230, ax2) i3 = T.axis.spatial(3, ax3) T.reads(inputs[i0, i1 - 3, i2 - 3, i3]) T.writes(PadInput[i0, i1, i2, i3]) PadInput[i0, i1, i2, i3] = T.if_then_else(3 <= i1 and i1 < 227 and 3 <= i2 and i2 < 227, inputs[i0, i1 - 3, i2 - 3, i3], T.float32(0), dtype="float32") for i2_0, i3_0, i0_1, i1_1, i2_1, i3_1, i4_0, i5_0, i6_0, i0_2, i1_2, i2_2, i3_2, i4_1, i5_1, i6_1, i0_3, i1_3, i2_3, i3_3 in T.grid(4, 2, 1, 1, 28, 8, 7, 7, 1, 1, 2, 1, 1, 1, 1, 3, 1, 8, 1, 4): with T.block("conv2d_nhwc"): n = T.axis.spatial(1, i0_3 + i0_0 + i0_1 + i0_2) h = T.axis.spatial(112, i1_0 * 16 + i1_1 * 16 + i1_2 * 8 + i1_3) w = T.axis.spatial(112, i2_3 + i2_0 * 28 + i2_1 + i2_2) co = T.axis.spatial(64, i3_0 * 32 + i3_1 * 4 + i3_2 * 4 + i3_3) rh = T.axis.reduce(7, i4_1 + i4_0) rw = T.axis.reduce(7, i5_0 + i5_1) rc = T.axis.reduce(3, i6_0 * 3 + i6_1) T.reads(PadInput[n, h * 2 + rh, w * 2 + rw, co // 64 * 3 + rc], weight[rh, rw, rc, co]) T.writes(conv2d_nhwc[n, h, w, co]) T.block_attr({"meta_schedule.tiling_structure":"SSRSRS"}) with T.init(): conv2d_nhwc[n, h, w, co] = T.float32(0) conv2d_nhwc[n, h, w, co] = conv2d_nhwc[n, h, w, co] + PadInput[n, h * 2 + rh, w * 2 + rw, co // 64 * 3 + rc] * weight[rh, rw, rc, co] # fmt: on decision_0 = [ ("SamplePerfectTile", [1, 1, 1, 1]), ("SamplePerfectTile", [7, 1, 2, 8]), ("SamplePerfectTile", [4, 28, 1, 1]), ("SamplePerfectTile", [2, 8, 1, 4]), ("SamplePerfectTile", [7, 1]), ("SamplePerfectTile", [7, 1]), ("SamplePerfectTile", [1, 3]), ("SampleCategorical", 1), ("SampleComputeLocation", 6), ] decision_1 = [ ("SamplePerfectTile", [1, 1, 1, 1]), ("SamplePerfectTile", [7, 1, 2, 8]), ("SamplePerfectTile", [4, 28, 1, 1]), ("SamplePerfectTile", [2, 8, 1, 4]), ("SamplePerfectTile", [7, 1]), ("SamplePerfectTile", [7, 1]), ("SamplePerfectTile", [1, 3]), ("SampleCategorical", 3), ("SampleComputeLocation", -1), ] decision_2 = [ ("SamplePerfectTile", [1, 1, 1, 1]), ("SamplePerfectTile", [7, 1, 2, 8]), ("SamplePerfectTile", [4, 28, 1, 1]), ("SamplePerfectTile", [2, 8, 1, 4]), ("SamplePerfectTile", [7, 1]), ("SamplePerfectTile", [7, 1]), ("SamplePerfectTile", [1, 3]), ("SampleCategorical", 0), ("SampleComputeLocation", 1), ] mod = create_te_workload("C2D", 0) actual = _design_space(mod) check_sketches( mod, sketches=actual, expected_mods=[c2d_0, c2d_1, c2d_2], expected_decisions=[decision_0, decision_1, decision_2], ) def test_cpu_c3d(): # fmt: off @T.prim_func def c3d_0(inputs: T.Buffer[(1, 16, 224, 224, 3), "float32"], weight: T.Buffer[(7, 7, 7, 3, 64), "float32"], conv3d_ndhwc: T.Buffer[(1, 8, 112, 112, 64), "float32"]) -> None: # function attr dict T.func_attr({"global_symbol": "main", "tir.noalias": True}) # body with T.block("root"): T.reads() T.writes() T.block_attr({"meta_schedule.parallel":288, "meta_schedule.unroll_explicit":512, "meta_schedule.vectorize":64}) PadInput = T.alloc_buffer([1, 22, 230, 230, 3], dtype="float32") conv3d_ndhwc_global = T.alloc_buffer([1, 8, 112, 112, 64], dtype="float32") for i0_0, i1_0, i2_0, i3_0, i4_0 in T.grid(1, 2, 4, 1, 2): for ax0, ax1, ax2, ax3, ax4 in T.grid(1, 13, 61, 229, 3): with T.block("PadInput"): i0 = T.axis.spatial(1, ax0) i1 = T.axis.spatial(22, i1_0 * 8 + ax1) i2 = T.axis.spatial(230, i2_0 * 56 + ax2) i3 = T.axis.spatial(230, ax3) i4 = T.axis.spatial(3, ax4) T.reads(inputs[i0, i1 - 3, i2 - 3, i3 - 3, i4]) T.writes(PadInput[i0, i1, i2, i3, i4]) PadInput[i0, i1, i2, i3, i4] = T.if_then_else(3 <= i1 and i1 < 19 and 3 <= i2 and i2 < 227 and 3 <= i3 and i3 < 227, inputs[i0, i1 - 3, i2 - 3, i3 - 3, i4], T.float32(0), dtype="float32") for i0_1, i1_1, i2_1, i3_1, i4_1 in T.grid(1, 4, 4, 14, 1): for i5_0, i6_0, i7_0, i8_0, i0_2, i1_2, i2_2, i3_2, i4_2, i5_1, i6_1, i7_1, i8_1, i0_3, i1_3, i2_3, i3_3, i4_3 in T.grid(1, 7, 7, 3, 1, 1, 1, 1, 32, 7, 1, 1, 1, 1, 1, 7, 8, 1): with T.block("conv3d_ndhwc"): n = T.axis.spatial(1, i0_1 + i0_2 + i0_3 + i0_0) d = T.axis.spatial(8, i1_3 + i1_0 * 4 + i1_1 + i1_2) h = T.axis.spatial(112, i2_0 * 28 + i2_1 * 7 + i2_2 * 7 + i2_3) w = T.axis.spatial(112, i3_0 * 112 + i3_1 * 8 + i3_2 * 8 + i3_3) co = T.axis.spatial(64, i4_3 + i4_0 * 32 + i4_1 * 32 + i4_2) rd = T.axis.reduce(7, i5_0 * 7 + i5_1) rh = T.axis.reduce(7, i6_1 + i6_0) rw = T.axis.reduce(7, i7_0 + i7_1) rc = T.axis.reduce(3, i8_1 + i8_0) T.reads(PadInput[n, d * 2 + rd, h * 2 + rh, w * 2 + rw, co // 64 * 3 + rc], weight[rd, rh, rw, rc, co]) T.writes(conv3d_ndhwc_global[n, d, h, w, co]) T.block_attr({"meta_schedule.tiling_structure":"SSRSRS"}) with T.init(): conv3d_ndhwc_global[n, d, h, w, co] = T.float32(0) conv3d_ndhwc_global[n, d, h, w, co] = conv3d_ndhwc_global[n, d, h, w, co] + PadInput[n, d * 2 + rd, h * 2 + rh, w * 2 + rw, co // 64 * 3 + rc] * weight[rd, rh, rw, rc, co] for ax0, ax1, ax2, ax3, ax4 in T.grid(1, 1, 7, 8, 32): with T.block("conv3d_ndhwc_global"): v0 = T.axis.spatial(1, ax0) v1 = T.axis.spatial(8, i1_0 * 4 + i1_1 + ax1) v2 = T.axis.spatial(112, i2_0 * 28 + i2_1 * 7 + ax2) v3 = T.axis.spatial(112, i3_1 * 8 + ax3) v4 = T.axis.spatial(64, i4_0 * 32 + ax4) T.reads(conv3d_ndhwc_global[v0, v1, v2, v3, v4]) T.writes(conv3d_ndhwc[v0, v1, v2, v3, v4]) conv3d_ndhwc[v0, v1, v2, v3, v4] = conv3d_ndhwc_global[v0, v1, v2, v3, v4] @T.prim_func def c3d_1(inputs: T.Buffer[(1, 16, 224, 224, 3), "float32"], weight: T.Buffer[(7, 7, 7, 3, 64), "float32"], conv3d_ndhwc: T.Buffer[(1, 8, 112, 112, 64), "float32"]) -> None: # function attr dict T.func_attr({"global_symbol": "main", "tir.noalias": True}) # body with T.block("root"): T.reads() T.writes() T.block_attr({"meta_schedule.parallel":288, "meta_schedule.unroll_explicit":64, "meta_schedule.vectorize":64}) PadInput = T.alloc_buffer([1, 22, 230, 230, 3], dtype="float32") conv3d_ndhwc_global = T.alloc_buffer([1, 8, 112, 112, 64], dtype="float32") for i0_0, i1_0, i2_0, i3_0, i4_0 in T.grid(1, 2, 4, 1, 2): for i0_1, i1_1, i2_1, i3_1 in T.grid(1, 4, 4, 14): for ax0, ax1, ax2, ax3, ax4 in T.grid(1, 7, 19, 21, 3): with T.block("PadInput"): i0 = T.axis.spatial(1, ax0) i1 = T.axis.spatial(22, i1_0 * 8 + i1_1 * 2 + ax1) i2 = T.axis.spatial(230, i2_0 * 56 + i2_1 * 14 + ax2) i3 = T.axis.spatial(230, i3_1 * 16 + ax3) i4 = T.axis.spatial(3, ax4) T.reads(inputs[i0, i1 - 3, i2 - 3, i3 - 3, i4]) T.writes(PadInput[i0, i1, i2, i3, i4]) PadInput[i0, i1, i2, i3, i4] = T.if_then_else(3 <= i1 and i1 < 19 and 3 <= i2 and i2 < 227 and 3 <= i3 and i3 < 227, inputs[i0, i1 - 3, i2 - 3, i3 - 3, i4], T.float32(0), dtype="float32") for i4_1, i5_0, i6_0, i7_0, i8_0, i0_2, i1_2, i2_2, i3_2, i4_2, i5_1, i6_1, i7_1, i8_1, i0_3, i1_3, i2_3, i3_3, i4_3 in T.grid(1, 1, 7, 7, 3, 1, 1, 1, 1, 32, 7, 1, 1, 1, 1, 1, 7, 8, 1): with T.block("conv3d_ndhwc"): n = T.axis.spatial(1, i0_1 + i0_2 + i0_3 + i0_0) d = T.axis.spatial(8, i1_3 + i1_0 * 4 + i1_1 + i1_2) h = T.axis.spatial(112, i2_0 * 28 + i2_1 * 7 + i2_2 * 7 + i2_3) w = T.axis.spatial(112, i3_0 * 112 + i3_1 * 8 + i3_2 * 8 + i3_3) co = T.axis.spatial(64, i4_3 + i4_0 * 32 + i4_1 * 32 + i4_2) rd = T.axis.reduce(7, i5_0 * 7 + i5_1) rh = T.axis.reduce(7, i6_1 + i6_0) rw = T.axis.reduce(7, i7_0 + i7_1) rc = T.axis.reduce(3, i8_1 + i8_0) T.reads(PadInput[n, d * 2 + rd, h * 2 + rh, w * 2 + rw, co // 64 * 3 + rc], weight[rd, rh, rw, rc, co]) T.writes(conv3d_ndhwc_global[n, d, h, w, co]) T.block_attr({"meta_schedule.tiling_structure":"SSRSRS"}) with T.init(): conv3d_ndhwc_global[n, d, h, w, co] = T.float32(0) conv3d_ndhwc_global[n, d, h, w, co] = conv3d_ndhwc_global[n, d, h, w, co] + PadInput[n, d * 2 + rd, h * 2 + rh, w * 2 + rw, co // 64 * 3 + rc] * weight[rd, rh, rw, rc, co] for ax0, ax1, ax2, ax3, ax4 in T.grid(1, 4, 28, 112, 32): with T.block("conv3d_ndhwc_global"): v0 = T.axis.spatial(1, ax0) v1 = T.axis.spatial(8, i1_0 * 4 + ax1) v2 = T.axis.spatial(112, i2_0 * 28 + ax2) v3 = T.axis.spatial(112, ax3) v4 = T.axis.spatial(64, i4_0 * 32 + ax4) T.reads(conv3d_ndhwc_global[v0, v1, v2, v3, v4]) T.writes(conv3d_ndhwc[v0, v1, v2, v3, v4]) conv3d_ndhwc[v0, v1, v2, v3, v4] = conv3d_ndhwc_global[v0, v1, v2, v3, v4] @T.prim_func def c3d_2(inputs: T.Buffer[(1, 16, 224, 224, 3), "float32"], weight: T.Buffer[(7, 7, 7, 3, 64), "float32"], conv3d_ndhwc: T.Buffer[(1, 8, 112, 112, 64), "float32"]) -> None: # function attr dict T.func_attr({"global_symbol": "main", "tir.noalias": True}) # body with T.block("root"): T.reads() T.writes() T.block_attr({"meta_schedule.parallel":288, "meta_schedule.unroll_explicit":16, "meta_schedule.vectorize":64}) PadInput = T.alloc_buffer([1, 22, 230, 230, 3], dtype="float32") for i0_0, i1_0, i2_0, i3_0, i4_0, i0_1, i1_1, i2_1, i3_1 in T.grid(1, 2, 4, 1, 2, 1, 4, 4, 14): for ax0, ax1, ax2, ax3, ax4 in T.grid(1, 7, 19, 21, 3): with T.block("PadInput"): i0 = T.axis.spatial(1, ax0) i1 = T.axis.spatial(22, i1_0 * 8 + i1_1 * 2 + ax1) i2 = T.axis.spatial(230, i2_0 * 56 + i2_1 * 14 + ax2) i3 = T.axis.spatial(230, i3_1 * 16 + ax3) i4 = T.axis.spatial(3, ax4) T.reads(inputs[i0, i1 - 3, i2 - 3, i3 - 3, i4]) T.writes(PadInput[i0, i1, i2, i3, i4]) PadInput[i0, i1, i2, i3, i4] = T.if_then_else(3 <= i1 and i1 < 19 and 3 <= i2 and i2 < 227 and 3 <= i3 and i3 < 227, inputs[i0, i1 - 3, i2 - 3, i3 - 3, i4], T.float32(0), dtype="float32") for i4_1, i5_0, i6_0, i7_0, i8_0, i0_2, i1_2, i2_2, i3_2, i4_2, i5_1, i6_1, i7_1, i8_1, i0_3, i1_3, i2_3, i3_3, i4_3 in T.grid(1, 1, 7, 7, 3, 1, 1, 1, 1, 32, 7, 1, 1, 1, 1, 1, 7, 8, 1): with T.block("conv3d_ndhwc"): n = T.axis.spatial(1, i0_1 + i0_2 + i0_3 + i0_0) d = T.axis.spatial(8, i1_3 + i1_0 * 4 + i1_1 + i1_2) h = T.axis.spatial(112, i2_0 * 28 + i2_1 * 7 + i2_2 * 7 + i2_3) w = T.axis.spatial(112, i3_0 * 112 + i3_1 * 8 + i3_2 * 8 + i3_3) co = T.axis.spatial(64, i4_3 + i4_0 * 32 + i4_1 * 32 + i4_2) rd = T.axis.reduce(7, i5_0 * 7 + i5_1) rh = T.axis.reduce(7, i6_1 + i6_0) rw = T.axis.reduce(7, i7_0 + i7_1) rc = T.axis.reduce(3, i8_1 + i8_0) T.reads(PadInput[n, d * 2 + rd, h * 2 + rh, w * 2 + rw, co // 64 * 3 + rc], weight[rd, rh, rw, rc, co]) T.writes(conv3d_ndhwc[n, d, h, w, co]) T.block_attr({"meta_schedule.tiling_structure":"SSRSRS"}) with T.init(): conv3d_ndhwc[n, d, h, w, co] = T.float32(0) conv3d_ndhwc[n, d, h, w, co] = conv3d_ndhwc[n, d, h, w, co] + PadInput[n, d * 2 + rd, h * 2 + rh, w * 2 + rw, co // 64 * 3 + rc] * weight[rd, rh, rw, rc, co] # fmt: on decision_0 = [ ("SamplePerfectTile", [1, 1, 1, 1]), ("SamplePerfectTile", [2, 4, 1, 1]), ("SamplePerfectTile", [4, 4, 1, 7]), ("SamplePerfectTile", [1, 14, 1, 8]), ("SamplePerfectTile", [2, 1, 32, 1]), ("SamplePerfectTile", [1, 7]), ("SamplePerfectTile", [7, 1]), ("SamplePerfectTile", [7, 1]), ("SamplePerfectTile", [3, 1]), ("SampleCategorical", 3), ("SampleComputeLocation", 4), ] decision_1 = [ ("SamplePerfectTile", [1, 1, 1, 1]), ("SamplePerfectTile", [2, 4, 1, 1]), ("SamplePerfectTile", [4, 4, 1, 7]), ("SamplePerfectTile", [1, 14, 1, 8]), ("SamplePerfectTile", [2, 1, 32, 1]), ("SamplePerfectTile", [1, 7]), ("SamplePerfectTile", [7, 1]), ("SamplePerfectTile", [7, 1]), ("SamplePerfectTile", [3, 1]), ("SampleCategorical", 2), ("SampleComputeLocation", 8), ] decision_2 = [ ("SamplePerfectTile", [1, 1, 1, 1]), ("SamplePerfectTile", [2, 4, 1, 1]), ("SamplePerfectTile", [4, 4, 1, 7]), ("SamplePerfectTile", [1, 14, 1, 8]), ("SamplePerfectTile", [2, 1, 32, 1]), ("SamplePerfectTile", [1, 7]), ("SamplePerfectTile", [7, 1]), ("SamplePerfectTile", [7, 1]), ("SamplePerfectTile", [3, 1]), ("SampleCategorical", 1), ("SampleComputeLocation", 8), ] mod = create_te_workload("C3D", 0) actual = _design_space(mod) check_sketches( mod, sketches=actual, expected_mods=[c3d_0, c3d_1, c3d_2], expected_decisions=[decision_0, decision_1, decision_2], ) def test_cpu_cap(): # fmt: off @T.prim_func def cap_0(inputs: T.Buffer[(1, 16, 16, 4, 4, 32), "float32"], weight: T.Buffer[(3, 3, 4, 4, 32, 32), "float32"], conv2d_capsule_nhwijc: T.Buffer[(1, 8, 8, 4, 4, 32), "float32"]) -> None: # function attr dict T.func_attr({"global_symbol": "main", "tir.noalias": True}) # body with T.block("root"): T.reads() T.writes() T.block_attr({"meta_schedule.parallel":288, "meta_schedule.unroll_explicit":0, "meta_schedule.vectorize":64}) PadInput = T.alloc_buffer([1, 18, 18, 4, 4, 32], dtype="float32") conv2d_capsule_nhwijc_global = T.alloc_buffer([1, 8, 8, 4, 4, 32], dtype="float32") for i0_0, i1_0, i2_0, i3_0, i4_0, i5_0, i0_1, i1_1 in T.grid(1, 2, 1, 1, 1, 1, 1, 4): for ax0, ax1, ax2, ax3, ax4, ax5 in T.grid(1, 3, 17, 4, 4, 32): with T.block("PadInput"): i0 = T.axis.spatial(1, ax0) i1 = T.axis.spatial(18, i1_0 * 8 + i1_1 * 2 + ax1) i2 = T.axis.spatial(18, ax2) i3, i4, i5 = T.axis.remap("SSS", [ax3, ax4, ax5]) T.reads(inputs[i0, i1 - 1, i2 - 1, i3, i4, i5]) T.writes(PadInput[i0, i1, i2, i3, i4, i5]) PadInput[i0, i1, i2, i3, i4, i5] = T.if_then_else(1 <= i1 and i1 < 17 and 1 <= i2 and i2 < 17, inputs[i0, i1 - 1, i2 - 1, i3, i4, i5], T.float32(0), dtype="float32") for i2_1, i3_1, i4_1, i5_1 in T.grid(4, 1, 4, 2): for i6_0, i7_0, i8_0, i9_0, i0_2, i1_2, i2_2, i3_2, i4_2, i5_2, i6_1, i7_1, i8_1, i9_1, i0_3, i1_3, i2_3, i3_3, i4_3, i5_3 in T.grid(1, 3, 4, 1, 1, 1, 2, 1, 1, 1, 3, 1, 1, 32, 1, 1, 1, 4, 1, 16): with T.block("conv2d_capsule_nhwijc"): n = T.axis.spatial(1, i0_2 + i0_3 + i0_0 + i0_1) h = T.axis.spatial(8, i1_0 * 4 + i1_1 + i1_2 + i1_3) w = T.axis.spatial(8, i2_0 * 8 + i2_1 * 2 + i2_2 + i2_3) cap_i = T.axis.spatial(4, i3_0 * 4 + i3_1 * 4 + i3_2 * 4 + i3_3) cap_j = T.axis.spatial(4, i4_0 * 4 + i4_1 + i4_2 + i4_3) co = T.axis.spatial(32, i5_0 * 32 + i5_1 * 16 + i5_2 * 16 + i5_3) rh = T.axis.reduce(3, i6_0 * 3 + i6_1) rw = T.axis.reduce(3, i7_1 + i7_0) cap_k = T.axis.reduce(4, i8_0 + i8_1) rc = T.axis.reduce(32, i9_0 * 32 + i9_1) T.reads(PadInput[n, h * 2 + rh, w * 2 + rw, cap_i, cap_k, rc], weight[rh, rw, cap_k, cap_j, rc, co]) T.writes(conv2d_capsule_nhwijc_global[n, h, w, cap_i, cap_j, co]) T.block_attr({"meta_schedule.tiling_structure":"SSRSRS"}) with T.init(): conv2d_capsule_nhwijc_global[n, h, w, cap_i, cap_j, co] = T.float32(0) conv2d_capsule_nhwijc_global[n, h, w, cap_i, cap_j, co] = conv2d_capsule_nhwijc_global[n, h, w, cap_i, cap_j, co] + PadInput[n, h * 2 + rh, w * 2 + rw, cap_i, cap_k, rc] * weight[rh, rw, cap_k, cap_j, rc, co] for ax0, ax1, ax2, ax3, ax4, ax5 in T.grid(1, 1, 2, 4, 1, 16): with T.block("conv2d_capsule_nhwijc_global"): v0 = T.axis.spatial(1, ax0) v1 = T.axis.spatial(8, i1_0 * 4 + i1_1 + ax1) v2 = T.axis.spatial(8, i2_1 * 2 + ax2) v3 = T.axis.spatial(4, ax3) v4 = T.axis.spatial(4, i4_1 + ax4) v5 = T.axis.spatial(32, i5_1 * 16 + ax5) T.reads(conv2d_capsule_nhwijc_global[v0, v1, v2, v3, v4, v5]) T.writes(conv2d_capsule_nhwijc[v0, v1, v2, v3, v4, v5]) conv2d_capsule_nhwijc[v0, v1, v2, v3, v4, v5] = conv2d_capsule_nhwijc_global[v0, v1, v2, v3, v4, v5] @T.prim_func def cap_1(inputs: T.Buffer[(1, 16, 16, 4, 4, 32), "float32"], weight: T.Buffer[(3, 3, 4, 4, 32, 32), "float32"], conv2d_capsule_nhwijc: T.Buffer[(1, 8, 8, 4, 4, 32), "float32"]) -> None: # function attr dict T.func_attr({"global_symbol": "main", "tir.noalias": True}) # body with T.block("root"): T.reads() T.writes() T.block_attr({"meta_schedule.parallel":288, "meta_schedule.unroll_explicit":0, "meta_schedule.vectorize":64}) PadInput = T.alloc_buffer([1, 18, 18, 4, 4, 32], dtype="float32") conv2d_capsule_nhwijc_global = T.alloc_buffer([1, 8, 8, 4, 4, 32], dtype="float32") for i0_0, i1_0, i2_0, i3_0, i4_0, i5_0 in T.grid(1, 2, 1, 1, 1, 1): for i0_1, i1_1, i2_1, i3_1, i4_1, i5_1 in T.grid(1, 4, 4, 1, 4, 2): for ax0, ax1, ax2, ax3, ax4, ax5 in T.grid(1, 3, 5, 4, 4, 32): with T.block("PadInput"): i0 = T.axis.spatial(1, ax0) i1 = T.axis.spatial(18, i1_0 * 8 + i1_1 * 2 + ax1) i2 = T.axis.spatial(18, i2_1 * 4 + ax2) i3, i4, i5 = T.axis.remap("SSS", [ax3, ax4, ax5]) T.reads(inputs[i0, i1 - 1, i2 - 1, i3, i4, i5]) T.writes(PadInput[i0, i1, i2, i3, i4, i5]) PadInput[i0, i1, i2, i3, i4, i5] = T.if_then_else(1 <= i1 and i1 < 17 and 1 <= i2 and i2 < 17, inputs[i0, i1 - 1, i2 - 1, i3, i4, i5], T.float32(0), dtype="float32") for i6_0, i7_0, i8_0, i9_0, i0_2, i1_2, i2_2, i3_2, i4_2, i5_2, i6_1, i7_1, i8_1, i9_1, i0_3, i1_3, i2_3, i3_3, i4_3, i5_3 in T.grid(1, 3, 4, 1, 1, 1, 2, 1, 1, 1, 3, 1, 1, 32, 1, 1, 1, 4, 1, 16): with T.block("conv2d_capsule_nhwijc"): n = T.axis.spatial(1, i0_2 + i0_3 + i0_0 + i0_1) h = T.axis.spatial(8, i1_0 * 4 + i1_1 + i1_2 + i1_3) w = T.axis.spatial(8, i2_0 * 8 + i2_1 * 2 + i2_2 + i2_3) cap_i = T.axis.spatial(4, i3_0 * 4 + i3_1 * 4 + i3_2 * 4 + i3_3) cap_j = T.axis.spatial(4, i4_0 * 4 + i4_1 + i4_2 + i4_3) co = T.axis.spatial(32, i5_0 * 32 + i5_1 * 16 + i5_2 * 16 + i5_3) rh = T.axis.reduce(3, i6_0 * 3 + i6_1) rw = T.axis.reduce(3, i7_1 + i7_0) cap_k = T.axis.reduce(4, i8_0 + i8_1) rc = T.axis.reduce(32, i9_0 * 32 + i9_1) T.reads(PadInput[n, h * 2 + rh, w * 2 + rw, cap_i, cap_k, rc], weight[rh, rw, cap_k, cap_j, rc, co]) T.writes(conv2d_capsule_nhwijc_global[n, h, w, cap_i, cap_j, co]) T.block_attr({"meta_schedule.tiling_structure":"SSRSRS"}) with T.init(): conv2d_capsule_nhwijc_global[n, h, w, cap_i, cap_j, co] = T.float32(0) conv2d_capsule_nhwijc_global[n, h, w, cap_i, cap_j, co] = conv2d_capsule_nhwijc_global[n, h, w, cap_i, cap_j, co] + PadInput[n, h * 2 + rh, w * 2 + rw, cap_i, cap_k, rc] * weight[rh, rw, cap_k, cap_j, rc, co] for ax0, ax1, ax2, ax3, ax4, ax5 in T.grid(1, 4, 8, 4, 4, 32): with T.block("conv2d_capsule_nhwijc_global"): v0 = T.axis.spatial(1, ax0) v1 = T.axis.spatial(8, i1_0 * 4 + ax1) v2, v3, v4, v5 = T.axis.remap("SSSS", [ax2, ax3, ax4, ax5]) T.reads(conv2d_capsule_nhwijc_global[v0, v1, v2, v3, v4, v5]) T.writes(conv2d_capsule_nhwijc[v0, v1, v2, v3, v4, v5]) conv2d_capsule_nhwijc[v0, v1, v2, v3, v4, v5] = conv2d_capsule_nhwijc_global[v0, v1, v2, v3, v4, v5] @T.prim_func def cap_2(inputs: T.Buffer[(1, 16, 16, 4, 4, 32), "float32"], weight: T.Buffer[(3, 3, 4, 4, 32, 32), "float32"], conv2d_capsule_nhwijc: T.Buffer[(1, 8, 8, 4, 4, 32), "float32"]) -> None: # function attr dict T.func_attr({"global_symbol": "main", "tir.noalias": True}) # body with T.block("root"): T.reads() T.writes() T.block_attr({"meta_schedule.parallel":288, "meta_schedule.unroll_explicit":16, "meta_schedule.vectorize":64}) PadInput = T.alloc_buffer([1, 18, 18, 4, 4, 32], dtype="float32") for i0, i1, i2, i3, i4, i5 in T.grid(1, 18, 18, 4, 4, 32): with T.block("PadInput"): i0_1, i1_1, i2_1, i3_1, i4_1, i5_1 = T.axis.remap("SSSSSS", [i0, i1, i2, i3, i4, i5]) T.reads(inputs[i0_1, i1_1 - 1, i2_1 - 1, i3_1, i4_1, i5_1]) T.writes(PadInput[i0_1, i1_1, i2_1, i3_1, i4_1, i5_1]) PadInput[i0_1, i1_1, i2_1, i3_1, i4_1, i5_1] = T.if_then_else(1 <= i1_1 and i1_1 < 17 and 1 <= i2_1 and i2_1 < 17, inputs[i0_1, i1_1 - 1, i2_1 - 1, i3_1, i4_1, i5_1], T.float32(0), dtype="float32") for i0_0, i1_0, i2_0, i3_0, i4_0, i5_0, i0_1_1, i1_1_1, i2_1_1, i3_1_1, i4_1_1, i5_1_1, i6_0, i7_0, i8_0, i9_0, i0_2, i1_2, i2_2, i3_2, i4_2, i5_2, i6_1, i7_1, i8_1, i9_1, i0_3, i1_3, i2_3, i3_3, i4_3, i5_3 in T.grid(1, 2, 1, 1, 1, 1, 1, 4, 4, 1, 4, 2, 1, 3, 4, 1, 1, 1, 2, 1, 1, 1, 3, 1, 1, 32, 1, 1, 1, 4, 1, 16): with T.block("conv2d_capsule_nhwijc"): n = T.axis.spatial(1, i0_2 + i0_3 + i0_0 + i0_1_1) h = T.axis.spatial(8, i1_0 * 4 + i1_1_1 + i1_2 + i1_3) w = T.axis.spatial(8, i2_0 * 8 + i2_1_1 * 2 + i2_2 + i2_3) cap_i = T.axis.spatial(4, i3_0 * 4 + i3_1_1 * 4 + i3_2 * 4 + i3_3) cap_j = T.axis.spatial(4, i4_0 * 4 + i4_1_1 + i4_2 + i4_3) co = T.axis.spatial(32, i5_0 * 32 + i5_1_1 * 16 + i5_2 * 16 + i5_3) rh = T.axis.reduce(3, i6_0 * 3 + i6_1) rw = T.axis.reduce(3, i7_1 + i7_0) cap_k = T.axis.reduce(4, i8_0 + i8_1) rc = T.axis.reduce(32, i9_0 * 32 + i9_1) T.reads(PadInput[n, h * 2 + rh, w * 2 + rw, cap_i, cap_k, rc], weight[rh, rw, cap_k, cap_j, rc, co]) T.writes(conv2d_capsule_nhwijc[n, h, w, cap_i, cap_j, co]) T.block_attr({"meta_schedule.tiling_structure":"SSRSRS"}) with T.init(): conv2d_capsule_nhwijc[n, h, w, cap_i, cap_j, co] = T.float32(0) conv2d_capsule_nhwijc[n, h, w, cap_i, cap_j, co] = conv2d_capsule_nhwijc[n, h, w, cap_i, cap_j, co] + PadInput[n, h * 2 + rh, w * 2 + rw, cap_i, cap_k, rc] * weight[rh, rw, cap_k, cap_j, rc, co] # fmt: on decision_0 = [ ("SamplePerfectTile", [1, 1, 1, 1]), ("SamplePerfectTile", [2, 4, 1, 1]), ("SamplePerfectTile", [1, 4, 2, 1]), ("SamplePerfectTile", [1, 1, 1, 4]), ("SamplePerfectTile", [1, 4, 1, 1]), ("SamplePerfectTile", [1, 2, 1, 16]), ("SamplePerfectTile", [1, 3]), ("SamplePerfectTile", [3, 1]), ("SamplePerfectTile", [4, 1]), ("SamplePerfectTile", [1, 32]), ("SampleCategorical", 0), ("SampleComputeLocation", 7), ] decision_1 = [ ("SamplePerfectTile", [1, 1, 1, 1]), ("SamplePerfectTile", [2, 4, 1, 1]), ("SamplePerfectTile", [1, 4, 2, 1]), ("SamplePerfectTile", [1, 1, 1, 4]), ("SamplePerfectTile", [1, 4, 1, 1]), ("SamplePerfectTile", [1, 2, 1, 16]), ("SamplePerfectTile", [1, 3]), ("SamplePerfectTile", [3, 1]), ("SamplePerfectTile", [4, 1]), ("SamplePerfectTile", [1, 32]), ("SampleCategorical", 0), ("SampleComputeLocation", 11), ] decision_2 = [ ("SamplePerfectTile", [1, 1, 1, 1]), ("SamplePerfectTile", [2, 4, 1, 1]), ("SamplePerfectTile", [1, 4, 2, 1]), ("SamplePerfectTile", [1, 1, 1, 4]), ("SamplePerfectTile", [1, 4, 1, 1]), ("SamplePerfectTile", [1, 2, 1, 16]), ("SamplePerfectTile", [1, 3]), ("SamplePerfectTile", [3, 1]), ("SamplePerfectTile", [4, 1]), ("SamplePerfectTile", [1, 32]), ("SampleCategorical", 1), ("SampleComputeLocation", -1), ] mod = create_te_workload("CAP", 0) actual = _design_space(mod) check_sketches( mod, sketches=actual, expected_mods=[cap_0, cap_1, cap_2], expected_decisions=[decision_0, decision_1, decision_2], ) def test_cpu_dep(): # fmt: off @T.prim_func def dep_0(placeholder: T.Buffer[(1, 112, 112, 32), "float32"], placeholder_1: T.Buffer[(1, 3, 3, 32), "float32"], depth_conv2d_nhwc: T.Buffer[(1, 112, 112, 32), "float32"]) -> None: # function attr dict T.func_attr({"global_symbol": "main", "tir.noalias": True}) # body with T.block("root"): T.reads() T.writes() T.block_attr({"meta_schedule.parallel":288, "meta_schedule.unroll_explicit":64, "meta_schedule.vectorize":64}) PadInput = T.alloc_buffer([1, 114, 114, 32], dtype="float32") depth_conv2d_nhwc_global = T.alloc_buffer([1, 112, 112, 32], dtype="float32") for i0, i1, i2, i3 in T.grid(1, 114, 114, 32): with T.block("PadInput"): i0_1, i1_1, i2_1, i3_1 = T.axis.remap("SSSS", [i0, i1, i2, i3]) T.reads(placeholder[i0_1, i1_1 - 1, i2_1 - 1, i3_1]) T.writes(PadInput[i0_1, i1_1, i2_1, i3_1]) PadInput[i0_1, i1_1, i2_1, i3_1] = T.if_then_else(1 <= i1_1 and i1_1 < 113 and 1 <= i2_1 and i2_1 < 113, placeholder[i0_1, i1_1 - 1, i2_1 - 1, i3_1], T.float32(0), dtype="float32") for i0_0, i1_0, i2_0, i3_0, i0_1_1, i1_1_1, i2_1_1, i3_1_1 in T.grid(1, 1, 1, 1, 1, 4, 4, 8): for i4_0, i5_0, i0_2, i1_2, i2_2, i3_2, i4_1, i5_1, i0_3, i1_3, i2_3, i3_3 in T.grid(1, 1, 1, 2, 7, 2, 3, 3, 1, 14, 4, 2): with T.block("depth_conv2d_nhwc"): n = T.axis.spatial(1, i0_2 + i0_3 + i0_0 + i0_1_1) h = T.axis.spatial(112, i1_0 * 112 + i1_1_1 * 28 + i1_2 * 14 + i1_3) w = T.axis.spatial(112, i2_0 * 112 + i2_1_1 * 28 + i2_2 * 4 + i2_3) c = T.axis.spatial(32, i3_0 * 32 + i3_1_1 * 4 + i3_2 * 2 + i3_3) rh = T.axis.reduce(3, i4_0 * 3 + i4_1) rw = T.axis.reduce(3, i5_0 * 3 + i5_1) T.reads(PadInput[n, h + rh, w + rw, c], placeholder_1[0, rh, rw, c]) T.writes(depth_conv2d_nhwc_global[n, h, w, c]) T.block_attr({"meta_schedule.tiling_structure":"SSRSRS"}) with T.init(): depth_conv2d_nhwc_global[n, h, w, c] = T.float32(0) depth_conv2d_nhwc_global[n, h, w, c] = depth_conv2d_nhwc_global[n, h, w, c] + PadInput[n, h + rh, w + rw, c] * placeholder_1[0, rh, rw, c] for ax0, ax1, ax2, ax3 in T.grid(1, 28, 28, 4): with T.block("depth_conv2d_nhwc_global"): v0 = T.axis.spatial(1, ax0) v1 = T.axis.spatial(112, i1_1_1 * 28 + ax1) v2 = T.axis.spatial(112, i2_1_1 * 28 + ax2) v3 = T.axis.spatial(32, i3_1_1 * 4 + ax3) T.reads(depth_conv2d_nhwc_global[v0, v1, v2, v3]) T.writes(depth_conv2d_nhwc[v0, v1, v2, v3]) depth_conv2d_nhwc[v0, v1, v2, v3] = depth_conv2d_nhwc_global[v0, v1, v2, v3] @T.prim_func def dep_1(placeholder: T.Buffer[(1, 112, 112, 32), "float32"], placeholder_1: T.Buffer[(1, 3, 3, 32), "float32"], depth_conv2d_nhwc: T.Buffer[(1, 112, 112, 32), "float32"]) -> None: # function attr dict T.func_attr({"global_symbol": "main", "tir.noalias": True}) # body with T.block("root"): T.reads() T.writes() T.block_attr({"meta_schedule.parallel":288, "meta_schedule.unroll_explicit":16, "meta_schedule.vectorize":64}) PadInput = T.alloc_buffer([1, 114, 114, 32], dtype="float32") depth_conv2d_nhwc_global = T.alloc_buffer([1, 112, 112, 32], dtype="float32") for i0, i1, i2, i3 in T.grid(1, 114, 114, 32): with T.block("PadInput"): i0_1, i1_1, i2_1, i3_1 = T.axis.remap("SSSS", [i0, i1, i2, i3]) T.reads(placeholder[i0_1, i1_1 - 1, i2_1 - 1, i3_1]) T.writes(PadInput[i0_1, i1_1, i2_1, i3_1]) PadInput[i0_1, i1_1, i2_1, i3_1] = T.if_then_else(1 <= i1_1 and i1_1 < 113 and 1 <= i2_1 and i2_1 < 113, placeholder[i0_1, i1_1 - 1, i2_1 - 1, i3_1], T.float32(0), dtype="float32") for i0_0, i1_0, i2_0, i3_0 in T.grid(1, 1, 1, 1): for i0_1_1, i1_1_1, i2_1_1, i3_1_1, i4_0, i5_0, i0_2, i1_2, i2_2, i3_2, i4_1, i5_1, i0_3, i1_3, i2_3, i3_3 in T.grid(1, 4, 4, 8, 1, 1, 1, 2, 7, 2, 3, 3, 1, 14, 4, 2): with T.block("depth_conv2d_nhwc"): n = T.axis.spatial(1, i0_2 + i0_3 + i0_0 + i0_1_1) h = T.axis.spatial(112, i1_0 * 112 + i1_1_1 * 28 + i1_2 * 14 + i1_3) w = T.axis.spatial(112, i2_0 * 112 + i2_1_1 * 28 + i2_2 * 4 + i2_3) c = T.axis.spatial(32, i3_0 * 32 + i3_1_1 * 4 + i3_2 * 2 + i3_3) rh = T.axis.reduce(3, i4_0 * 3 + i4_1) rw = T.axis.reduce(3, i5_0 * 3 + i5_1) T.reads(PadInput[n, h + rh, w + rw, c], placeholder_1[0, rh, rw, c]) T.writes(depth_conv2d_nhwc_global[n, h, w, c]) T.block_attr({"meta_schedule.tiling_structure":"SSRSRS"}) with T.init(): depth_conv2d_nhwc_global[n, h, w, c] = T.float32(0) depth_conv2d_nhwc_global[n, h, w, c] = depth_conv2d_nhwc_global[n, h, w, c] + PadInput[n, h + rh, w + rw, c] * placeholder_1[0, rh, rw, c] for ax0, ax1, ax2, ax3 in T.grid(1, 112, 112, 32): with T.block("depth_conv2d_nhwc_global"): v0, v1, v2, v3 = T.axis.remap("SSSS", [ax0, ax1, ax2, ax3]) T.reads(depth_conv2d_nhwc_global[v0, v1, v2, v3]) T.writes(depth_conv2d_nhwc[v0, v1, v2, v3]) depth_conv2d_nhwc[v0, v1, v2, v3] = depth_conv2d_nhwc_global[v0, v1, v2, v3] @T.prim_func def dep_2(placeholder: T.Buffer[(1, 112, 112, 32), "float32"], placeholder_1: T.Buffer[(1, 3, 3, 32), "float32"], depth_conv2d_nhwc: T.Buffer[(1, 112, 112, 32), "float32"]) -> None: # function attr dict T.func_attr({"global_symbol": "main", "tir.noalias": True}) # body with T.block("root"): T.reads() T.writes() T.block_attr({"meta_schedule.parallel":288, "meta_schedule.unroll_explicit":0, "meta_schedule.vectorize":64}) PadInput = T.alloc_buffer([1, 114, 114, 32], dtype="float32") for i0_0, i1_0, i2_0, i3_0, i0_1, i1_1 in T.grid(1, 1, 1, 1, 1, 4): for ax0, ax1, ax2, ax3 in T.grid(1, 30, 114, 32): with T.block("PadInput"): i0 = T.axis.spatial(1, ax0) i1 = T.axis.spatial(114, i1_1 * 28 + ax1) i2, i3 = T.axis.remap("SS", [ax2, ax3]) T.reads(placeholder[i0, i1 - 1, i2 - 1, i3]) T.writes(PadInput[i0, i1, i2, i3]) PadInput[i0, i1, i2, i3] = T.if_then_else(1 <= i1 and i1 < 113 and 1 <= i2 and i2 < 113, placeholder[i0, i1 - 1, i2 - 1, i3], T.float32(0), dtype="float32") for i2_1, i3_1, i4_0, i5_0, i0_2, i1_2, i2_2, i3_2, i4_1, i5_1, i0_3, i1_3, i2_3, i3_3 in T.grid(4, 8, 1, 1, 1, 2, 7, 2, 3, 3, 1, 14, 4, 2): with T.block("depth_conv2d_nhwc"): n = T.axis.spatial(1, i0_2 + i0_3 + i0_0 + i0_1) h = T.axis.spatial(112, i1_0 * 112 + i1_1 * 28 + i1_2 * 14 + i1_3) w = T.axis.spatial(112, i2_0 * 112 + i2_1 * 28 + i2_2 * 4 + i2_3) c = T.axis.spatial(32, i3_0 * 32 + i3_1 * 4 + i3_2 * 2 + i3_3) rh = T.axis.reduce(3, i4_0 * 3 + i4_1) rw = T.axis.reduce(3, i5_0 * 3 + i5_1) T.reads(PadInput[n, h + rh, w + rw, c], placeholder_1[0, rh, rw, c]) T.writes(depth_conv2d_nhwc[n, h, w, c]) T.block_attr({"meta_schedule.tiling_structure":"SSRSRS"}) with T.init(): depth_conv2d_nhwc[n, h, w, c] = T.float32(0) depth_conv2d_nhwc[n, h, w, c] = depth_conv2d_nhwc[n, h, w, c] + PadInput[n, h + rh, w + rw, c] * placeholder_1[0, rh, rw, c] # fmt: on decision_0 = [ ("SamplePerfectTile", [1, 1, 1, 1]), ("SamplePerfectTile", [1, 4, 2, 14]), ("SamplePerfectTile", [1, 4, 7, 4]), ("SamplePerfectTile", [1, 8, 2, 2]), ("SamplePerfectTile", [1, 3]), ("SamplePerfectTile", [1, 3]), ("SampleCategorical", 2), ("SampleComputeLocation", -1), ] decision_1 = [ ("SamplePerfectTile", [1, 1, 1, 1]), ("SamplePerfectTile", [1, 4, 2, 14]), ("SamplePerfectTile", [1, 4, 7, 4]), ("SamplePerfectTile", [1, 8, 2, 2]), ("SamplePerfectTile", [1, 3]), ("SamplePerfectTile", [1, 3]), ("SampleCategorical", 1), ("SampleComputeLocation", -1), ] decision_2 = [ ("SamplePerfectTile", [1, 1, 1, 1]), ("SamplePerfectTile", [1, 4, 2, 14]), ("SamplePerfectTile", [1, 4, 7, 4]), ("SamplePerfectTile", [1, 8, 2, 2]), ("SamplePerfectTile", [1, 3]), ("SamplePerfectTile", [1, 3]), ("SampleCategorical", 0), ("SampleComputeLocation", 5), ] mod = create_te_workload("DEP", 0) actual = _design_space(mod) check_sketches( mod, sketches=actual, expected_mods=[dep_0, dep_1, dep_2], expected_decisions=[decision_0, decision_1, decision_2], ) def test_cpu_dil(): # fmt: off @T.prim_func def dil_0(inputs: T.Buffer[(1, 224, 224, 3), "float32"], weight: T.Buffer[(7, 7, 3, 64), "float32"], conv2d_nhwc: T.Buffer[(1, 109, 109, 64), "float32"]) -> None: # function attr dict T.func_attr({"global_symbol": "main", "tir.noalias": True}) # body with T.block("root"): T.reads() T.writes() T.block_attr({"meta_schedule.parallel":288, "meta_schedule.unroll_explicit":64, "meta_schedule.vectorize":64}) PadInput = T.alloc_buffer([1, 230, 230, 3], dtype="float32") conv2d_nhwc_global = T.alloc_buffer([1, 109, 109, 64], dtype="float32") for i0_0, i1_0, i2_0, i3_0, i0_1, i1_1, i2_1, i3_1 in T.grid(1, 109, 1, 4, 1, 1, 1, 2): for ax0, ax1, ax2, ax3 in T.grid(1, 13, 229, 3): with T.block("PadInput"): i0 = T.axis.spatial(1, ax0) i1 = T.axis.spatial(230, i1_0 * 2 + ax1) i2 = T.axis.spatial(230, ax2) i3 = T.axis.spatial(3, ax3) T.reads(inputs[i0, i1 - 3, i2 - 3, i3]) T.writes(PadInput[i0, i1, i2, i3]) PadInput[i0, i1, i2, i3] = T.if_then_else(3 <= i1 and i1 < 227 and 3 <= i2 and i2 < 227, inputs[i0, i1 - 3, i2 - 3, i3], T.float32(0), dtype="float32") for i4_0, i5_0, i6_0, i0_2, i1_2, i2_2, i3_2, i4_1, i5_1, i6_1, i0_3, i1_3, i2_3, i3_3 in T.grid(7, 1, 1, 1, 1, 109, 8, 1, 7, 3, 1, 1, 1, 1): with T.block("conv2d_nhwc"): n = T.axis.spatial(1, i0_3 + i0_0 + i0_1 + i0_2) h = T.axis.spatial(109, i1_2 + i1_3 + i1_0 + i1_1) w = T.axis.spatial(109, i2_3 + i2_0 * 109 + i2_1 * 109 + i2_2) co = T.axis.spatial(64, i3_0 * 16 + i3_1 * 8 + i3_2 + i3_3) rh = T.axis.reduce(7, i4_1 + i4_0) rw = T.axis.reduce(7, i5_0 * 7 + i5_1) rc = T.axis.reduce(3, i6_0 * 3 + i6_1) T.reads(PadInput[n, h * 2 + rh * 2, w * 2 + rw * 2, co // 64 * 3 + rc], weight[rh, rw, rc, co]) T.writes(conv2d_nhwc_global[n, h, w, co]) T.block_attr({"meta_schedule.tiling_structure":"SSRSRS"}) with T.init(): conv2d_nhwc_global[n, h, w, co] = T.float32(0) conv2d_nhwc_global[n, h, w, co] = conv2d_nhwc_global[n, h, w, co] + PadInput[n, h * 2 + rh * 2, w * 2 + rw * 2, co // 64 * 3 + rc] * weight[rh, rw, rc, co] for ax0, ax1, ax2, ax3 in T.grid(1, 1, 109, 8): with T.block("conv2d_nhwc_global"): v0 = T.axis.spatial(1, ax0) v1 = T.axis.spatial(109, i1_0 + ax1) v2 = T.axis.spatial(109, ax2) v3 = T.axis.spatial(64, i3_0 * 16 + i3_1 * 8 + ax3) T.reads(conv2d_nhwc_global[v0, v1, v2, v3]) T.writes(conv2d_nhwc[v0, v1, v2, v3]) conv2d_nhwc[v0, v1, v2, v3] = conv2d_nhwc_global[v0, v1, v2, v3] @T.prim_func def dil_1(inputs: T.Buffer[(1, 224, 224, 3), "float32"], weight: T.Buffer[(7, 7, 3, 64), "float32"], conv2d_nhwc: T.Buffer[(1, 109, 109, 64), "float32"]) -> None: # function attr dict T.func_attr({"global_symbol": "main", "tir.noalias": True}) # body with T.block("root"): T.reads() T.writes() T.block_attr({"meta_schedule.parallel":288, "meta_schedule.unroll_explicit":0, "meta_schedule.vectorize":64}) PadInput = T.alloc_buffer([1, 230, 230, 3], dtype="float32") conv2d_nhwc_global = T.alloc_buffer([1, 109, 109, 64], dtype="float32") for i0_0, i1_0, i2_0, i3_0 in T.grid(1, 109, 1, 4): for i0_1, i1_1, i2_1, i3_1, i4_0 in T.grid(1, 1, 1, 2, 7): for ax0, ax1, ax2, ax3 in T.grid(1, 1, 229, 3): with T.block("PadInput"): i0 = T.axis.spatial(1, ax0) i1 = T.axis.spatial(230, i1_0 * 2 + i4_0 * 2 + ax1) i2 = T.axis.spatial(230, ax2) i3 = T.axis.spatial(3, ax3) T.reads(inputs[i0, i1 - 3, i2 - 3, i3]) T.writes(PadInput[i0, i1, i2, i3]) PadInput[i0, i1, i2, i3] = T.if_then_else(3 <= i1 and i1 < 227 and 3 <= i2 and i2 < 227, inputs[i0, i1 - 3, i2 - 3, i3], T.float32(0), dtype="float32") for i5_0, i6_0, i0_2, i1_2, i2_2, i3_2, i4_1, i5_1, i6_1, i0_3, i1_3, i2_3, i3_3 in T.grid(1, 1, 1, 1, 109, 8, 1, 7, 3, 1, 1, 1, 1): with T.block("conv2d_nhwc"): n = T.axis.spatial(1, i0_3 + i0_0 + i0_1 + i0_2) h = T.axis.spatial(109, i1_2 + i1_3 + i1_0 + i1_1) w = T.axis.spatial(109, i2_3 + i2_0 * 109 + i2_1 * 109 + i2_2) co = T.axis.spatial(64, i3_0 * 16 + i3_1 * 8 + i3_2 + i3_3) rh = T.axis.reduce(7, i4_1 + i4_0) rw = T.axis.reduce(7, i5_0 * 7 + i5_1) rc = T.axis.reduce(3, i6_0 * 3 + i6_1) T.reads(PadInput[n, h * 2 + rh * 2, w * 2 + rw * 2, co // 64 * 3 + rc], weight[rh, rw, rc, co]) T.writes(conv2d_nhwc_global[n, h, w, co]) T.block_attr({"meta_schedule.tiling_structure":"SSRSRS"}) with T.init(): conv2d_nhwc_global[n, h, w, co] = T.float32(0) conv2d_nhwc_global[n, h, w, co] = conv2d_nhwc_global[n, h, w, co] + PadInput[n, h * 2 + rh * 2, w * 2 + rw * 2, co // 64 * 3 + rc] * weight[rh, rw, rc, co] for ax0, ax1, ax2, ax3 in T.grid(1, 1, 109, 16): with T.block("conv2d_nhwc_global"): v0 = T.axis.spatial(1, ax0) v1 = T.axis.spatial(109, i1_0 + ax1) v2 = T.axis.spatial(109, ax2) v3 = T.axis.spatial(64, i3_0 * 16 + ax3) T.reads(conv2d_nhwc_global[v0, v1, v2, v3]) T.writes(conv2d_nhwc[v0, v1, v2, v3]) conv2d_nhwc[v0, v1, v2, v3] = conv2d_nhwc_global[v0, v1, v2, v3] @T.prim_func def dil_2(inputs: T.Buffer[(1, 224, 224, 3), "float32"], weight: T.Buffer[(7, 7, 3, 64), "float32"], conv2d_nhwc: T.Buffer[(1, 109, 109, 64), "float32"]) -> None: # function attr dict T.func_attr({"global_symbol": "main", "tir.noalias": True}) # body with T.block("root"): T.reads() T.writes() T.block_attr({"meta_schedule.parallel":288, "meta_schedule.unroll_explicit":0, "meta_schedule.vectorize":64}) PadInput = T.alloc_buffer([1, 230, 230, 3], dtype="float32") for i0_0, i1_0 in T.grid(1, 109): for ax0, ax1, ax2, ax3 in T.grid(1, 13, 229, 3): with T.block("PadInput"): i0 = T.axis.spatial(1, ax0) i1 = T.axis.spatial(230, i1_0 * 2 + ax1) i2 = T.axis.spatial(230, ax2) i3 = T.axis.spatial(3, ax3) T.reads(inputs[i0, i1 - 3, i2 - 3, i3]) T.writes(PadInput[i0, i1, i2, i3]) PadInput[i0, i1, i2, i3] = T.if_then_else(3 <= i1 and i1 < 227 and 3 <= i2 and i2 < 227, inputs[i0, i1 - 3, i2 - 3, i3], T.float32(0), dtype="float32") for i2_0, i3_0, i0_1, i1_1, i2_1, i3_1, i4_0, i5_0, i6_0, i0_2, i1_2, i2_2, i3_2, i4_1, i5_1, i6_1, i0_3, i1_3, i2_3, i3_3 in T.grid(1, 4, 1, 1, 1, 2, 7, 1, 1, 1, 1, 109, 8, 1, 7, 3, 1, 1, 1, 1): with T.block("conv2d_nhwc"): n = T.axis.spatial(1, i0_3 + i0_0 + i0_1 + i0_2) h = T.axis.spatial(109, i1_2 + i1_3 + i1_0 + i1_1) w = T.axis.spatial(109, i2_3 + i2_0 * 109 + i2_1 * 109 + i2_2) co = T.axis.spatial(64, i3_0 * 16 + i3_1 * 8 + i3_2 + i3_3) rh = T.axis.reduce(7, i4_1 + i4_0) rw = T.axis.reduce(7, i5_0 * 7 + i5_1) rc = T.axis.reduce(3, i6_0 * 3 + i6_1) T.reads(PadInput[n, h * 2 + rh * 2, w * 2 + rw * 2, co // 64 * 3 + rc], weight[rh, rw, rc, co]) T.writes(conv2d_nhwc[n, h, w, co]) T.block_attr({"meta_schedule.tiling_structure":"SSRSRS"}) with T.init(): conv2d_nhwc[n, h, w, co] = T.float32(0) conv2d_nhwc[n, h, w, co] = conv2d_nhwc[n, h, w, co] + PadInput[n, h * 2 + rh * 2, w * 2 + rw * 2, co // 64 * 3 + rc] * weight[rh, rw, rc, co] # fmt: on decision_0 = [ ("SamplePerfectTile", [1, 1, 1, 1]), ("SamplePerfectTile", [109, 1, 1, 1]), ("SamplePerfectTile", [1, 1, 109, 1]), ("SamplePerfectTile", [4, 2, 8, 1]), ("SamplePerfectTile", [7, 1]), ("SamplePerfectTile", [1, 7]), ("SamplePerfectTile", [1, 3]), ("SampleCategorical", 2), ("SampleComputeLocation", 7), ] decision_1 = [ ("SamplePerfectTile", [1, 1, 1, 1]), ("SamplePerfectTile", [109, 1, 1, 1]), ("SamplePerfectTile", [1, 1, 109, 1]), ("SamplePerfectTile", [4, 2, 8, 1]), ("SamplePerfectTile", [7, 1]), ("SamplePerfectTile", [1, 7]), ("SamplePerfectTile", [1, 3]), ("SampleCategorical", 0), ("SampleComputeLocation", 8), ] decision_2 = [ ("SamplePerfectTile", [1, 1, 1, 1]), ("SamplePerfectTile", [109, 1, 1, 1]), ("SamplePerfectTile", [1, 1, 109, 1]), ("SamplePerfectTile", [4, 2, 8, 1]), ("SamplePerfectTile", [7, 1]), ("SamplePerfectTile", [1, 7]), ("SamplePerfectTile", [1, 3]), ("SampleCategorical", 0), ("SampleComputeLocation", 1), ] mod = create_te_workload("DIL", 0) actual = _design_space(mod) check_sketches( mod, sketches=actual, expected_mods=[dil_0, dil_1, dil_2], expected_decisions=[decision_0, decision_1, decision_2], ) def test_cpu_gmm(): # fmt: off @T.prim_func def gmm_0(X: T.Buffer[(1, 128, 128), "float32"], Y: T.Buffer[(1, 128, 128), "float32"], Z: T.Buffer[(1, 128, 128), "float32"]) -> None: # function attr dict T.func_attr({"global_symbol": "main", "tir.noalias": True}) # body with T.block("root"): T.reads() T.writes() T.block_attr({"meta_schedule.parallel":288, "meta_schedule.unroll_explicit":16, "meta_schedule.vectorize":64}) Z_global = T.alloc_buffer([1, 128, 128], dtype="float32") for i0_0, i1_0, i2_0, i0_1, i1_1, i2_1 in T.grid(1, 4, 2, 1, 1, 8): for i3_0, i0_2, i1_2, i2_2, i3_1, i0_3, i1_3, i2_3 in T.grid(128, 1, 16, 1, 1, 1, 2, 8): with T.block("Z"): b = T.axis.spatial(1, i0_0 + i0_1 + i0_2 + i0_3) i = T.axis.spatial(128, i1_0 * 32 + i1_1 * 32 + i1_2 * 2 + i1_3) j = T.axis.spatial(128, i2_0 * 64 + i2_1 * 8 + i2_2 * 8 + i2_3) k = T.axis.reduce(128, i3_1 + i3_0) T.reads(X[b, i, k], Y[b, k, j]) T.writes(Z_global[b, i, j]) T.block_attr({"meta_schedule.tiling_structure":"SSRSRS"}) with T.init(): Z_global[b, i, j] = T.float32(0) Z_global[b, i, j] = Z_global[b, i, j] + X[b, i, k] * Y[b, k, j] for ax0, ax1, ax2 in T.grid(1, 32, 8): with T.block("Z_global"): v0 = T.axis.spatial(1, ax0) v1 = T.axis.spatial(128, i1_0 * 32 + ax1) v2 = T.axis.spatial(128, i2_0 * 64 + i2_1 * 8 + ax2) T.reads(Z_global[v0, v1, v2]) T.writes(Z[v0, v1, v2]) Z[v0, v1, v2] = Z_global[v0, v1, v2] @T.prim_func def gmm_1(X: T.Buffer[(1, 128, 128), "float32"], Y: T.Buffer[(1, 128, 128), "float32"], Z: T.Buffer[(1, 128, 128), "float32"]) -> None: # function attr dict T.func_attr({"global_symbol": "main", "tir.noalias": True}) # body with T.block("root"): T.reads() T.writes() T.block_attr({"meta_schedule.parallel":288, "meta_schedule.unroll_explicit":16, "meta_schedule.vectorize":64}) Z_global = T.alloc_buffer([1, 128, 128], dtype="float32") for i0_0, i1_0, i2_0 in T.grid(1, 4, 2): for i0_1, i1_1, i2_1, i3_0, i0_2, i1_2, i2_2, i3_1, i0_3, i1_3, i2_3 in T.grid(1, 1, 8, 128, 1, 16, 1, 1, 1, 2, 8): with T.block("Z"): b = T.axis.spatial(1, i0_0 + i0_1 + i0_2 + i0_3) i = T.axis.spatial(128, i1_0 * 32 + i1_1 * 32 + i1_2 * 2 + i1_3) j = T.axis.spatial(128, i2_0 * 64 + i2_1 * 8 + i2_2 * 8 + i2_3) k = T.axis.reduce(128, i3_1 + i3_0) T.reads(X[b, i, k], Y[b, k, j]) T.writes(Z_global[b, i, j]) T.block_attr({"meta_schedule.tiling_structure":"SSRSRS"}) with T.init(): Z_global[b, i, j] = T.float32(0) Z_global[b, i, j] = Z_global[b, i, j] + X[b, i, k] * Y[b, k, j] for ax0, ax1, ax2 in T.grid(1, 32, 64): with T.block("Z_global"): v0 = T.axis.spatial(1, ax0) v1 = T.axis.spatial(128, i1_0 * 32 + ax1) v2 = T.axis.spatial(128, i2_0 * 64 + ax2) T.reads(Z_global[v0, v1, v2]) T.writes(Z[v0, v1, v2]) Z[v0, v1, v2] = Z_global[v0, v1, v2] @T.prim_func def gmm_2(X: T.Buffer[(1, 128, 128), "float32"], Y: T.Buffer[(1, 128, 128), "float32"], Z: T.Buffer[(1, 128, 128), "float32"]) -> None: # function attr dict T.func_attr({"global_symbol": "main", "tir.noalias": True}) # body with T.block("root"): T.reads() T.writes() T.block_attr({"meta_schedule.parallel":288, "meta_schedule.unroll_explicit":16, "meta_schedule.vectorize":64}) for i0_0, i1_0, i2_0, i0_1, i1_1, i2_1, i3_0, i0_2, i1_2, i2_2, i3_1, i0_3, i1_3, i2_3 in T.grid(1, 4, 2, 1, 1, 8, 128, 1, 16, 1, 1, 1, 2, 8): with T.block("Z"): b = T.axis.spatial(1, i0_0 + i0_1 + i0_2 + i0_3) i = T.axis.spatial(128, i1_0 * 32 + i1_1 * 32 + i1_2 * 2 + i1_3) j = T.axis.spatial(128, i2_0 * 64 + i2_1 * 8 + i2_2 * 8 + i2_3) k = T.axis.reduce(128, i3_1 + i3_0) T.reads(X[b, i, k], Y[b, k, j]) T.writes(Z[b, i, j]) T.block_attr({"meta_schedule.tiling_structure":"SSRSRS"}) with T.init(): Z[b, i, j] = T.float32(0) Z[b, i, j] = Z[b, i, j] + X[b, i, k] * Y[b, k, j] # fmt: on decision_0 = [ ("SamplePerfectTile", [1, 1, 1, 1]), ("SamplePerfectTile", [4, 1, 16, 2]), ("SamplePerfectTile", [2, 8, 1, 8]), ("SamplePerfectTile", [128, 1]), ("SampleCategorical", 1), ] decision_1 = [ ("SamplePerfectTile", [1, 1, 1, 1]), ("SamplePerfectTile", [4, 1, 16, 2]), ("SamplePerfectTile", [2, 8, 1, 8]), ("SamplePerfectTile", [128, 1]), ("SampleCategorical", 1), ] decision_2 = [ ("SamplePerfectTile", [1, 1, 1, 1]), ("SamplePerfectTile", [4, 1, 16, 2]), ("SamplePerfectTile", [2, 8, 1, 8]), ("SamplePerfectTile", [128, 1]), ("SampleCategorical", 1), ] mod = create_te_workload("GMM", 0) actual = _design_space(mod) check_sketches( mod, sketches=actual, expected_mods=[gmm_0, gmm_1, gmm_2], expected_decisions=[decision_0, decision_1, decision_2], ) def test_cpu_grp(): # fmt: off @T.prim_func def grp_0(inputs: T.Buffer[(1, 56, 56, 64), "float32"], weight: T.Buffer[(3, 3, 16, 128), "float32"], conv2d_nhwc: T.Buffer[(1, 28, 28, 128), "float32"]) -> None: # function attr dict T.func_attr({"global_symbol": "main", "tir.noalias": True}) # body with T.block("root"): T.reads() T.writes() T.block_attr({"meta_schedule.parallel":288, "meta_schedule.unroll_explicit":16, "meta_schedule.vectorize":64}) PadInput = T.alloc_buffer([1, 58, 58, 64], dtype="float32") conv2d_nhwc_global = T.alloc_buffer([1, 28, 28, 128], dtype="float32") for i0_0, i1_0, i2_0, i3_0 in T.grid(1, 7, 1, 2): for ax0, ax1, ax2, ax3 in T.grid(1, 9, 57, 32): with T.block("PadInput"): i0 = T.axis.spatial(1, ax0) i1 = T.axis.spatial(58, i1_0 * 8 + ax1) i2 = T.axis.spatial(58, ax2) i3 = T.axis.spatial(64, i3_0 * 32 + ax3) T.reads(inputs[i0, i1 - 1, i2 - 1, i3]) T.writes(PadInput[i0, i1, i2, i3]) PadInput[i0, i1, i2, i3] = T.if_then_else(1 <= i1 and i1 < 57 and 1 <= i2 and i2 < 57, inputs[i0, i1 - 1, i2 - 1, i3], T.float32(0), dtype="float32") for i0_1, i1_1, i2_1, i3_1 in T.grid(1, 4, 1, 1): for i4_0, i5_0, i6_0, i0_2, i1_2, i2_2, i3_2, i4_1, i5_1, i6_1, i0_3, i1_3, i2_3, i3_3 in T.grid(1, 3, 8, 1, 1, 4, 4, 3, 1, 2, 1, 1, 7, 16): with T.block("conv2d_nhwc"): n = T.axis.spatial(1, i0_3 + i0_0 + i0_1 + i0_2) h = T.axis.spatial(28, i1_0 * 4 + i1_1 + i1_2 + i1_3) w = T.axis.spatial(28, i2_0 * 28 + i2_1 * 28 + i2_2 * 7 + i2_3) co = T.axis.spatial(128, i3_0 * 64 + i3_1 * 64 + i3_2 * 16 + i3_3) rh = T.axis.reduce(3, i4_0 * 3 + i4_1) rw = T.axis.reduce(3, i5_0 + i5_1) rc = T.axis.reduce(16, i6_0 * 2 + i6_1) T.reads(PadInput[n, h * 2 + rh, w * 2 + rw, co // 32 * 16 + rc], weight[rh, rw, rc, co]) T.writes(conv2d_nhwc_global[n, h, w, co]) T.block_attr({"meta_schedule.tiling_structure":"SSRSRS"}) with T.init(): conv2d_nhwc_global[n, h, w, co] = T.float32(0) conv2d_nhwc_global[n, h, w, co] = conv2d_nhwc_global[n, h, w, co] + PadInput[n, h * 2 + rh, w * 2 + rw, co // 32 * 16 + rc] * weight[rh, rw, rc, co] for ax0, ax1, ax2, ax3 in T.grid(1, 1, 28, 64): with T.block("conv2d_nhwc_global"): v0 = T.axis.spatial(1, ax0) v1 = T.axis.spatial(28, i1_0 * 4 + i1_1 + ax1) v2 = T.axis.spatial(28, ax2) v3 = T.axis.spatial(128, i3_0 * 64 + ax3) T.reads(conv2d_nhwc_global[v0, v1, v2, v3]) T.writes(conv2d_nhwc[v0, v1, v2, v3]) conv2d_nhwc[v0, v1, v2, v3] = conv2d_nhwc_global[v0, v1, v2, v3] @T.prim_func def grp_1(inputs: T.Buffer[(1, 56, 56, 64), "float32"], weight: T.Buffer[(3, 3, 16, 128), "float32"], conv2d_nhwc: T.Buffer[(1, 28, 28, 128), "float32"]) -> None: # function attr dict T.func_attr({"global_symbol": "main", "tir.noalias": True}) # body with T.block("root"): T.reads() T.writes() T.block_attr({"meta_schedule.parallel":288, "meta_schedule.unroll_explicit":512, "meta_schedule.vectorize":64}) PadInput = T.alloc_buffer([1, 58, 58, 64], dtype="float32") conv2d_nhwc_global = T.alloc_buffer([1, 28, 28, 128], dtype="float32") for i0, i1, i2, i3 in T.grid(1, 58, 58, 64): with T.block("PadInput"): i0_1, i1_1, i2_1, i3_1 = T.axis.remap("SSSS", [i0, i1, i2, i3]) T.reads(inputs[i0_1, i1_1 - 1, i2_1 - 1, i3_1]) T.writes(PadInput[i0_1, i1_1, i2_1, i3_1]) PadInput[i0_1, i1_1, i2_1, i3_1] = T.if_then_else(1 <= i1_1 and i1_1 < 57 and 1 <= i2_1 and i2_1 < 57, inputs[i0_1, i1_1 - 1, i2_1 - 1, i3_1], T.float32(0), dtype="float32") for i0_0, i1_0, i2_0, i3_0 in T.grid(1, 7, 1, 2): for i0_1_1, i1_1_1, i2_1_1, i3_1_1, i4_0, i5_0, i6_0, i0_2, i1_2, i2_2, i3_2, i4_1, i5_1, i6_1, i0_3, i1_3, i2_3, i3_3 in T.grid(1, 4, 1, 1, 1, 3, 8, 1, 1, 4, 4, 3, 1, 2, 1, 1, 7, 16): with T.block("conv2d_nhwc"): n = T.axis.spatial(1, i0_3 + i0_0 + i0_1_1 + i0_2) h = T.axis.spatial(28, i1_0 * 4 + i1_1_1 + i1_2 + i1_3) w = T.axis.spatial(28, i2_0 * 28 + i2_1_1 * 28 + i2_2 * 7 + i2_3) co = T.axis.spatial(128, i3_0 * 64 + i3_1_1 * 64 + i3_2 * 16 + i3_3) rh = T.axis.reduce(3, i4_0 * 3 + i4_1) rw = T.axis.reduce(3, i5_0 + i5_1) rc = T.axis.reduce(16, i6_0 * 2 + i6_1) T.reads(PadInput[n, h * 2 + rh, w * 2 + rw, co // 32 * 16 + rc], weight[rh, rw, rc, co]) T.writes(conv2d_nhwc_global[n, h, w, co]) T.block_attr({"meta_schedule.tiling_structure":"SSRSRS"}) with T.init(): conv2d_nhwc_global[n, h, w, co] = T.float32(0) conv2d_nhwc_global[n, h, w, co] = conv2d_nhwc_global[n, h, w, co] + PadInput[n, h * 2 + rh, w * 2 + rw, co // 32 * 16 + rc] * weight[rh, rw, rc, co] for ax0, ax1, ax2, ax3 in T.grid(1, 4, 28, 64): with T.block("conv2d_nhwc_global"): v0 = T.axis.spatial(1, ax0) v1 = T.axis.spatial(28, i1_0 * 4 + ax1) v2 = T.axis.spatial(28, ax2) v3 = T.axis.spatial(128, i3_0 * 64 + ax3) T.reads(conv2d_nhwc_global[v0, v1, v2, v3]) T.writes(conv2d_nhwc[v0, v1, v2, v3]) conv2d_nhwc[v0, v1, v2, v3] = conv2d_nhwc_global[v0, v1, v2, v3] @T.prim_func def grp_2(inputs: T.Buffer[(1, 56, 56, 64), "float32"], weight: T.Buffer[(3, 3, 16, 128), "float32"], conv2d_nhwc: T.Buffer[(1, 28, 28, 128), "float32"]) -> None: # function attr dict T.func_attr({"global_symbol": "main", "tir.noalias": True}) # body with T.block("root"): T.reads() T.writes() T.block_attr({"meta_schedule.parallel":288, "meta_schedule.unroll_explicit":16, "meta_schedule.vectorize":64}) PadInput = T.alloc_buffer([1, 58, 58, 64], dtype="float32") for i0_0, i1_0, i2_0, i3_0, i0_1, i1_1, i2_1, i3_1, i4_0, i5_0 in T.grid(1, 7, 1, 2, 1, 4, 1, 1, 1, 3): for ax0, ax1, ax2, ax3 in T.grid(1, 3, 55, 32): with T.block("PadInput"): i0 = T.axis.spatial(1, ax0) i1 = T.axis.spatial(58, i1_0 * 8 + i1_1 * 2 + ax1) i2 = T.axis.spatial(58, i5_0 + ax2) i3 = T.axis.spatial(64, i3_0 * 32 + ax3) T.reads(inputs[i0, i1 - 1, i2 - 1, i3]) T.writes(PadInput[i0, i1, i2, i3]) PadInput[i0, i1, i2, i3] = T.if_then_else(1 <= i1 and i1 < 57 and 1 <= i2 and i2 < 57, inputs[i0, i1 - 1, i2 - 1, i3], T.float32(0), dtype="float32") for i6_0, i0_2, i1_2, i2_2, i3_2, i4_1, i5_1, i6_1, i0_3, i1_3, i2_3, i3_3 in T.grid(8, 1, 1, 4, 4, 3, 1, 2, 1, 1, 7, 16): with T.block("conv2d_nhwc"): n = T.axis.spatial(1, i0_3 + i0_0 + i0_1 + i0_2) h = T.axis.spatial(28, i1_0 * 4 + i1_1 + i1_2 + i1_3) w = T.axis.spatial(28, i2_0 * 28 + i2_1 * 28 + i2_2 * 7 + i2_3) co = T.axis.spatial(128, i3_0 * 64 + i3_1 * 64 + i3_2 * 16 + i3_3) rh = T.axis.reduce(3, i4_0 * 3 + i4_1) rw = T.axis.reduce(3, i5_0 + i5_1) rc = T.axis.reduce(16, i6_0 * 2 + i6_1) T.reads(PadInput[n, h * 2 + rh, w * 2 + rw, co // 32 * 16 + rc], weight[rh, rw, rc, co]) T.writes(conv2d_nhwc[n, h, w, co]) T.block_attr({"meta_schedule.tiling_structure":"SSRSRS"}) with T.init(): conv2d_nhwc[n, h, w, co] = T.float32(0) conv2d_nhwc[n, h, w, co] = conv2d_nhwc[n, h, w, co] + PadInput[n, h * 2 + rh, w * 2 + rw, co // 32 * 16 + rc] * weight[rh, rw, rc, co] # fmt: on decision_0 = [ ("SamplePerfectTile", [1, 1, 1, 1]), ("SamplePerfectTile", [7, 4, 1, 1]), ("SamplePerfectTile", [1, 1, 4, 7]), ("SamplePerfectTile", [2, 1, 4, 16]), ("SamplePerfectTile", [1, 3]), ("SamplePerfectTile", [3, 1]), ("SamplePerfectTile", [8, 2]), ("SampleCategorical", 1), ("SampleComputeLocation", 3), ] decision_1 = [ ("SamplePerfectTile", [1, 1, 1, 1]), ("SamplePerfectTile", [7, 4, 1, 1]), ("SamplePerfectTile", [1, 1, 4, 7]), ("SamplePerfectTile", [2, 1, 4, 16]), ("SamplePerfectTile", [1, 3]), ("SamplePerfectTile", [3, 1]), ("SamplePerfectTile", [8, 2]), ("SampleCategorical", 3), ("SampleComputeLocation", -1), ] decision_2 = [ ("SamplePerfectTile", [1, 1, 1, 1]), ("SamplePerfectTile", [7, 4, 1, 1]), ("SamplePerfectTile", [1, 1, 4, 7]), ("SamplePerfectTile", [2, 1, 4, 16]), ("SamplePerfectTile", [1, 3]), ("SamplePerfectTile", [3, 1]), ("SamplePerfectTile", [8, 2]), ("SampleCategorical", 1), ("SampleComputeLocation", 9), ] mod = create_te_workload("GRP", 0) actual = _design_space(mod) check_sketches( mod, sketches=actual, expected_mods=[grp_0, grp_1, grp_2], expected_decisions=[decision_0, decision_1, decision_2], ) def test_cpu_t2d(): # fmt: off @T.prim_func def t2d_0(inputs: T.Buffer[(1, 4, 4, 512), "float32"], weight: T.Buffer[(4, 4, 512, 256), "float32"], conv2d_transpose_nhwc: T.Buffer[(1, 8, 8, 256), "float32"]) -> None: # function attr dict T.func_attr({"global_symbol": "main", "tir.noalias": True}) # body with T.block("root"): T.reads() T.writes() T.block_attr({"meta_schedule.parallel":288, "meta_schedule.unroll_explicit":64, "meta_schedule.vectorize":64}) PadInput = T.alloc_buffer([1, 6, 6, 512], dtype="float32") conv2d_transpose_nhwc_global = T.alloc_buffer([1, 8, 8, 256], dtype="float32") for i0, i1, i2, i3 in T.grid(1, 6, 6, 512): with T.block("PadInput"): i0_1, i1_1, i2_1, i3_1 = T.axis.remap("SSSS", [i0, i1, i2, i3]) T.reads(inputs[i0_1, i1_1 - 1, i2_1 - 1, i3_1]) T.writes(PadInput[i0_1, i1_1, i2_1, i3_1]) PadInput[i0_1, i1_1, i2_1, i3_1] = T.if_then_else(1 <= i1_1 and i1_1 < 5 and 1 <= i2_1 and i2_1 < 5, inputs[i0_1, i1_1 - 1, i2_1 - 1, i3_1], T.float32(0), dtype="float32") for i0_0, i1_0, i2_0, i3_0, i0_1_1, i1_1_1, i2_1_1, i3_1_1 in T.grid(1, 1, 2, 8, 1, 4, 1, 4): for i4_0, i5_0, i6_0, i0_2, i1_2, i2_2, i3_2, i4_1, i5_1, i6_1, i0_3, i1_3, i2_3, i3_3 in T.grid(2, 2, 64, 1, 1, 1, 1, 2, 2, 8, 1, 2, 4, 8): with T.block("conv2d_transpose_nhwc"): n = T.axis.spatial(1, i0_3 + i0_0 + i0_1_1 + i0_2) h = T.axis.spatial(8, i1_0 * 8 + i1_1_1 * 2 + i1_2 * 2 + i1_3) w = T.axis.spatial(8, i2_0 * 4 + i2_1_1 * 4 + i2_2 * 4 + i2_3) co = T.axis.spatial(256, i3_0 * 32 + i3_1_1 * 8 + i3_2 * 8 + i3_3) rh = T.axis.reduce(4, i4_0 * 2 + i4_1) rw = T.axis.reduce(4, i5_0 * 2 + i5_1) rc = T.axis.reduce(512, i6_0 * 8 + i6_1) T.reads(PadInput[n, (h + rh) // 2, (w + rw) // 2, rc], weight[3 - rh, 3 - rw, rc, co]) T.writes(conv2d_transpose_nhwc_global[n, h, w, co]) T.block_attr({"meta_schedule.tiling_structure":"SSRSRS"}) with T.init(): conv2d_transpose_nhwc_global[n, h, w, co] = T.float32(0) conv2d_transpose_nhwc_global[n, h, w, co] = conv2d_transpose_nhwc_global[n, h, w, co] + T.if_then_else((h + rh) % 2 == 0 and (w + rw) % 2 == 0, PadInput[n, (h + rh) // 2, (w + rw) // 2, rc], T.float32(0), dtype="float32") * weight[3 - rh, 3 - rw, rc, co] for ax0, ax1, ax2, ax3 in T.grid(1, 2, 4, 8): with T.block("conv2d_transpose_nhwc_global"): v0 = T.axis.spatial(1, ax0) v1 = T.axis.spatial(8, i1_1_1 * 2 + ax1) v2 = T.axis.spatial(8, i2_0 * 4 + ax2) v3 = T.axis.spatial(256, i3_0 * 32 + i3_1_1 * 8 + ax3) T.reads(conv2d_transpose_nhwc_global[v0, v1, v2, v3]) T.writes(conv2d_transpose_nhwc[v0, v1, v2, v3]) conv2d_transpose_nhwc[v0, v1, v2, v3] = conv2d_transpose_nhwc_global[v0, v1, v2, v3] @T.prim_func def t2d_1(inputs: T.Buffer[(1, 4, 4, 512), "float32"], weight: T.Buffer[(4, 4, 512, 256), "float32"], conv2d_transpose_nhwc: T.Buffer[(1, 8, 8, 256), "float32"]) -> None: # function attr dict T.func_attr({"global_symbol": "main", "tir.noalias": True}) # body with T.block("root"): T.reads() T.writes() T.block_attr({"meta_schedule.parallel":288, "meta_schedule.unroll_explicit":64, "meta_schedule.vectorize":64}) PadInput = T.alloc_buffer([1, 6, 6, 512], dtype="float32") conv2d_transpose_nhwc_global = T.alloc_buffer([1, 8, 8, 256], dtype="float32") for i0_0, i1_0, i2_0, i3_0 in T.grid(1, 1, 2, 8): for ax0, ax1, ax2, ax3 in T.grid(1, 6, 4, 512): with T.block("PadInput"): i0, i1 = T.axis.remap("SS", [ax0, ax1]) i2 = T.axis.spatial(6, i2_0 * 2 + ax2) i3 = T.axis.spatial(512, ax3) T.reads(inputs[i0, i1 - 1, i2 - 1, i3]) T.writes(PadInput[i0, i1, i2, i3]) PadInput[i0, i1, i2, i3] = T.if_then_else(1 <= i1 and i1 < 5 and 1 <= i2 and i2 < 5, inputs[i0, i1 - 1, i2 - 1, i3], T.float32(0), dtype="float32") for i0_1, i1_1, i2_1, i3_1, i4_0, i5_0, i6_0, i0_2, i1_2, i2_2, i3_2, i4_1, i5_1, i6_1, i0_3, i1_3, i2_3, i3_3 in T.grid(1, 4, 1, 4, 2, 2, 64, 1, 1, 1, 1, 2, 2, 8, 1, 2, 4, 8): with T.block("conv2d_transpose_nhwc"): n = T.axis.spatial(1, i0_3 + i0_0 + i0_1 + i0_2) h = T.axis.spatial(8, i1_0 * 8 + i1_1 * 2 + i1_2 * 2 + i1_3) w = T.axis.spatial(8, i2_0 * 4 + i2_1 * 4 + i2_2 * 4 + i2_3) co = T.axis.spatial(256, i3_0 * 32 + i3_1 * 8 + i3_2 * 8 + i3_3) rh = T.axis.reduce(4, i4_0 * 2 + i4_1) rw = T.axis.reduce(4, i5_0 * 2 + i5_1) rc = T.axis.reduce(512, i6_0 * 8 + i6_1) T.reads(PadInput[n, (h + rh) // 2, (w + rw) // 2, rc], weight[3 - rh, 3 - rw, rc, co]) T.writes(conv2d_transpose_nhwc_global[n, h, w, co]) T.block_attr({"meta_schedule.tiling_structure":"SSRSRS"}) with T.init(): conv2d_transpose_nhwc_global[n, h, w, co] = T.float32(0) conv2d_transpose_nhwc_global[n, h, w, co] = conv2d_transpose_nhwc_global[n, h, w, co] + T.if_then_else((h + rh) % 2 == 0 and (w + rw) % 2 == 0, PadInput[n, (h + rh) // 2, (w + rw) // 2, rc], T.float32(0), dtype="float32") * weight[3 - rh, 3 - rw, rc, co] for ax0, ax1, ax2, ax3 in T.grid(1, 8, 4, 32): with T.block("conv2d_transpose_nhwc_global"): v0, v1 = T.axis.remap("SS", [ax0, ax1]) v2 = T.axis.spatial(8, i2_0 * 4 + ax2) v3 = T.axis.spatial(256, i3_0 * 32 + ax3) T.reads(conv2d_transpose_nhwc_global[v0, v1, v2, v3]) T.writes(conv2d_transpose_nhwc[v0, v1, v2, v3]) conv2d_transpose_nhwc[v0, v1, v2, v3] = conv2d_transpose_nhwc_global[v0, v1, v2, v3] @T.prim_func def t2d_2(inputs: T.Buffer[(1, 4, 4, 512), "float32"], weight: T.Buffer[(4, 4, 512, 256), "float32"], conv2d_transpose_nhwc: T.Buffer[(1, 8, 8, 256), "float32"]) -> None: # function attr dict T.func_attr({"global_symbol": "main", "tir.noalias": True}) # body with T.block("root"): T.reads() T.writes() T.block_attr({"meta_schedule.parallel":288, "meta_schedule.unroll_explicit":512, "meta_schedule.vectorize":64}) for i0_0, i1_0, i2_0, i3_0, i0_1, i1_1, i2_1, i3_1, i4_0, i5_0, i6_0, i0_2, i1_2, i2_2, i3_2, i4_1, i5_1, i6_1, i0_3, i1_3, i2_3, i3_3 in T.grid(1, 1, 2, 8, 1, 4, 1, 4, 2, 2, 64, 1, 1, 1, 1, 2, 2, 8, 1, 2, 4, 8): with T.block("conv2d_transpose_nhwc"): n = T.axis.spatial(1, i0_3 + i0_0 + i0_1 + i0_2) h = T.axis.spatial(8, i1_0 * 8 + i1_1 * 2 + i1_2 * 2 + i1_3) w = T.axis.spatial(8, i2_0 * 4 + i2_1 * 4 + i2_2 * 4 + i2_3) co = T.axis.spatial(256, i3_0 * 32 + i3_1 * 8 + i3_2 * 8 + i3_3) rh = T.axis.reduce(4, i4_0 * 2 + i4_1) rw = T.axis.reduce(4, i5_0 * 2 + i5_1) rc = T.axis.reduce(512, i6_0 * 8 + i6_1) T.reads(inputs[n, (h + rh) // 2 - 1, (w + rw) // 2 - 1, rc], weight[3 - rh, 3 - rw, rc, co]) T.writes(conv2d_transpose_nhwc[n, h, w, co]) T.block_attr({"meta_schedule.tiling_structure":"SSRSRS"}) with T.init(): conv2d_transpose_nhwc[n, h, w, co] = T.float32(0) conv2d_transpose_nhwc[n, h, w, co] = conv2d_transpose_nhwc[n, h, w, co] + T.if_then_else((h + rh) % 2 == 0 and (w + rw) % 2 == 0, T.if_then_else(1 <= (h + rh) // 2 and (h + rh) // 2 < 5 and 1 <= (w + rw) // 2 and (w + rw) // 2 < 5, inputs[n, (h + rh) // 2 - 1, (w + rw) // 2 - 1, rc], T.float32(0), dtype="float32"), T.float32(0), dtype="float32") * weight[3 - rh, 3 - rw, rc, co] # fmt: on decision_0 = [ ("SamplePerfectTile", [1, 1, 1, 1]), ("SamplePerfectTile", [1, 4, 1, 2]), ("SamplePerfectTile", [2, 1, 1, 4]), ("SamplePerfectTile", [8, 4, 1, 8]), ("SamplePerfectTile", [2, 2]), ("SamplePerfectTile", [2, 2]), ("SamplePerfectTile", [64, 8]), ("SampleCategorical", 2), ("SampleComputeLocation", -1), ] decision_1 = [ ("SamplePerfectTile", [1, 1, 1, 1]), ("SamplePerfectTile", [1, 4, 1, 2]), ("SamplePerfectTile", [2, 1, 1, 4]), ("SamplePerfectTile", [8, 4, 1, 8]), ("SamplePerfectTile", [2, 2]), ("SamplePerfectTile", [2, 2]), ("SamplePerfectTile", [64, 8]), ("SampleCategorical", 2), ("SampleComputeLocation", 3), ] decision_2 = [ ("SamplePerfectTile", [1, 1, 1, 1]), ("SamplePerfectTile", [1, 4, 1, 2]), ("SamplePerfectTile", [2, 1, 1, 4]), ("SamplePerfectTile", [8, 4, 1, 8]), ("SamplePerfectTile", [2, 2]), ("SamplePerfectTile", [2, 2]), ("SamplePerfectTile", [64, 8]), ("SampleCategorical", 3), ("SampleComputeLocation", -2), ] mod = create_te_workload("T2D", 0) actual = _design_space(mod) check_sketches( mod, sketches=actual, expected_mods=[t2d_0, t2d_1, t2d_2], expected_decisions=[decision_0, decision_1, decision_2], debug_mask=0, ) def test_cpu_nrm(): # fmt: off @T.prim_func def nrm_0(A: T.Buffer[(1, 256, 256), "float32"], D: T.Buffer[1, "float32"]) -> None: # function attr dict T.func_attr({"global_symbol": "main", "tir.noalias": True}) # body with T.block("root"): T.reads() T.writes() T.block_attr({"meta_schedule.parallel":288, "meta_schedule.unroll_explicit":0, "meta_schedule.vectorize":64}) C = T.alloc_buffer([1], dtype="float32") C_rf = T.alloc_buffer([1, 32768], dtype="float32") for i0, i1_i2_fused_0, i1_i2_fused_1 in T.grid(1, 32768, 2): with T.block("C_rf"): vi1_i2_fused_0, b, vi1_i2_fused_1 = T.axis.remap("SSR", [i1_i2_fused_0, i0, i1_i2_fused_1]) T.reads(A[b, (vi1_i2_fused_0 * 2 + vi1_i2_fused_1) // 256, (vi1_i2_fused_0 * 2 + vi1_i2_fused_1) % 256]) T.writes(C_rf[b, vi1_i2_fused_0]) with T.init(): C_rf[b, vi1_i2_fused_0] = T.float32(0) C_rf[b, vi1_i2_fused_0] = C_rf[b, vi1_i2_fused_0] + A[b, (vi1_i2_fused_0 * 2 + vi1_i2_fused_1) // 256, (vi1_i2_fused_0 * 2 + vi1_i2_fused_1) % 256] * A[b, (vi1_i2_fused_0 * 2 + vi1_i2_fused_1) // 256, (vi1_i2_fused_0 * 2 + vi1_i2_fused_1) % 256] for i0, i1_i2_fused_0 in T.grid(1, 32768): with T.block("C"): vi1_i2_fused_0, b = T.axis.remap("RS", [i1_i2_fused_0, i0]) T.reads(C_rf[b, vi1_i2_fused_0]) T.writes(C[b]) with T.init(): C[b] = T.float32(0) C[b] = C[b] + C_rf[b, vi1_i2_fused_0] for i0 in T.serial(1): with T.block("D"): b = T.axis.spatial(1, i0) T.reads(C[b]) T.writes(D[b]) D[b] = T.sqrt(C[b], dtype="float32") @T.prim_func def nrm_1(A: T.Buffer[(1, 256, 256), "float32"], D: T.Buffer[1, "float32"]) -> None: # function attr dict T.func_attr({"global_symbol": "main", "tir.noalias": True}) # body with T.block("root"): T.reads() T.writes() T.block_attr({"meta_schedule.parallel":288, "meta_schedule.unroll_explicit":16, "meta_schedule.vectorize":64}) C = T.alloc_buffer([1], dtype="float32") C_rf = T.alloc_buffer([1, 2], dtype="float32") for i0, i1_i2_fused_0, i1_i2_fused_1 in T.grid(1, 32768, 2): with T.block("C_rf"): vi1_i2_fused_1, b, vi1_i2_fused_0 = T.axis.remap("SSR", [i1_i2_fused_1, i0, i1_i2_fused_0]) T.reads(A[b, (vi1_i2_fused_0 * 2 + vi1_i2_fused_1) // 256, (vi1_i2_fused_0 * 2 + vi1_i2_fused_1) % 256]) T.writes(C_rf[b, vi1_i2_fused_1]) with T.init(): C_rf[b, vi1_i2_fused_1] = T.float32(0) C_rf[b, vi1_i2_fused_1] = C_rf[b, vi1_i2_fused_1] + A[b, (vi1_i2_fused_0 * 2 + vi1_i2_fused_1) // 256, (vi1_i2_fused_0 * 2 + vi1_i2_fused_1) % 256] * A[b, (vi1_i2_fused_0 * 2 + vi1_i2_fused_1) // 256, (vi1_i2_fused_0 * 2 + vi1_i2_fused_1) % 256] for i0, i1_i2_fused_1 in T.grid(1, 2): with T.block("C"): vi1_i2_fused_1, b = T.axis.remap("RS", [i1_i2_fused_1, i0]) T.reads(C_rf[b, vi1_i2_fused_1]) T.writes(C[b]) with T.init(): C[b] = T.float32(0) C[b] = C[b] + C_rf[b, vi1_i2_fused_1] for i0 in T.serial(1): with T.block("D"): b = T.axis.spatial(1, i0) T.reads(C[b]) T.writes(D[b]) D[b] = T.sqrt(C[b], dtype="float32") @T.prim_func def nrm_2(A: T.Buffer[(1, 256, 256), "float32"], D: T.Buffer[1, "float32"]) -> None: # function attr dict T.func_attr({"global_symbol": "main", "tir.noalias": True}) # body with T.block("root"): T.reads() T.writes() T.block_attr({"meta_schedule.parallel":288, "meta_schedule.unroll_explicit":0, "meta_schedule.vectorize":64}) C = T.alloc_buffer([1], dtype="float32") for i0, i1, i2 in T.grid(1, 256, 256): with T.block("C"): b, i, j = T.axis.remap("SRR", [i0, i1, i2]) T.reads(A[b, i, j]) T.writes(C[b]) with T.init(): C[b] = T.float32(0) C[b] = C[b] + A[b, i, j] * A[b, i, j] for i0 in T.serial(1): with T.block("D"): b = T.axis.spatial(1, i0) T.reads(C[b]) T.writes(D[b]) D[b] = T.sqrt(C[b], dtype="float32") # fmt: on decision_0 = [ ("SamplePerfectTile", [32768, 2]), ("SampleCategorical", 0), ("SampleComputeLocation", -1), ("SampleComputeLocation", -1), ] decision_1 = [ ("SamplePerfectTile", [32768, 2]), ("SampleCategorical", 1), ("SampleComputeLocation", -1), ("SampleComputeLocation", -1), ] decision_2 = [ ("SampleCategorical", 0), ("SampleComputeLocation", -1), ] mod = create_te_workload("NRM", 0) actual = _design_space(mod) check_sketches( mod, sketches=actual, expected_mods=[nrm_0, nrm_1, nrm_2], expected_decisions=[decision_0, decision_1, decision_2], ) def test_cpu_sfm(): # fmt: off @T.prim_func def sfm_0(A: T.Buffer[(256, 256), "float32"], T_softmax_norm: T.Buffer[(256, 256), "float32"]) -> None: # function attr dict T.func_attr({"global_symbol": "main", "tir.noalias": True}) # body with T.block("root"): T.reads() T.writes() T.block_attr({"meta_schedule.parallel":288, "meta_schedule.unroll_explicit":0, "meta_schedule.vectorize":64}) T_softmax_maxelem = T.alloc_buffer([256], dtype="float32") T_softmax_expsum = T.alloc_buffer([256], dtype="float32") T_softmax_expsum_rf = T.alloc_buffer([256, 16], dtype="float32") T_softmax_maxelem_rf = T.alloc_buffer([256, 4], dtype="float32") for i0, i1_0, i1_1 in T.grid(256, 4, 64): with T.block("T_softmax_maxelem_rf"): vi1_0, i0_1, vi1_1 = T.axis.remap("SSR", [i1_0, i0, i1_1]) T.reads(A[i0_1, vi1_0 * 64 + vi1_1]) T.writes(T_softmax_maxelem_rf[i0_1, vi1_0]) with T.init(): T_softmax_maxelem_rf[i0_1, vi1_0] = T.float32(-3.4028234663852886e+38) T_softmax_maxelem_rf[i0_1, vi1_0] = T.max(T_softmax_maxelem_rf[i0_1, vi1_0], A[i0_1, vi1_0 * 64 + vi1_1]) for i0, i1_0 in T.grid(256, 4): with T.block("T_softmax_maxelem"): vi1_0, i0_2 = T.axis.remap("RS", [i1_0, i0]) T.reads(T_softmax_maxelem_rf[i0_2, vi1_0]) T.writes(T_softmax_maxelem[i0_2]) with T.init(): T_softmax_maxelem[i0_2] = T.float32(-3.4028234663852886e+38) T_softmax_maxelem[i0_2] = T.max(T_softmax_maxelem[i0_2], T_softmax_maxelem_rf[i0_2, vi1_0]) for i0_3, i1_0, i1_1 in T.grid(256, 16, 16): with T.block("T_softmax_expsum_rf"): vi1_0, i0_4, vi1_1 = T.axis.remap("SSR", [i1_0, i0_3, i1_1]) T.reads(A[i0_4, vi1_0 * 16 + vi1_1], T_softmax_maxelem[i0_4]) T.writes(T_softmax_expsum_rf[i0_4, vi1_0]) with T.init(): T_softmax_expsum_rf[i0_4, vi1_0] = T.float32(0) T_softmax_expsum_rf[i0_4, vi1_0] = T_softmax_expsum_rf[i0_4, vi1_0] + T.exp(A[i0_4, vi1_0 * 16 + vi1_1] - T_softmax_maxelem[i0_4], dtype="float32") for i0_5, i1 in T.grid(256, 256): for ax0, ax1 in T.grid(16, 1): with T.block("T_softmax_expsum"): vi1_0 = T.axis.reduce(16, ax0) i0_6 = T.axis.spatial(256, i0_5 + ax1) T.reads(T_softmax_expsum_rf[i0_6, vi1_0]) T.writes(T_softmax_expsum[i0_6]) with T.init(): T_softmax_expsum[i0_6] = T.float32(0) T_softmax_expsum[i0_6] = T_softmax_expsum[i0_6] + T_softmax_expsum_rf[i0_6, vi1_0] with T.block("T_softmax_norm"): i0_7, i1_2 = T.axis.remap("SS", [i0_5, i1]) T.reads(A[i0_7, i1_2], T_softmax_maxelem[i0_7], T_softmax_expsum[i0_7]) T.writes(T_softmax_norm[i0_7, i1_2]) T.block_attr({"axis":1}) T_softmax_norm[i0_7, i1_2] = T.exp(A[i0_7, i1_2] - T_softmax_maxelem[i0_7], dtype="float32") / T_softmax_expsum[i0_7] @T.prim_func def sfm_1(A: T.Buffer[(256, 256), "float32"], T_softmax_norm: T.Buffer[(256, 256), "float32"]) -> None: # function attr dict T.func_attr({"global_symbol": "main", "tir.noalias": True}) # body with T.block("root"): T.reads() T.writes() T.block_attr({"meta_schedule.parallel":288, "meta_schedule.unroll_explicit":16, "meta_schedule.vectorize":64}) T_softmax_maxelem = T.alloc_buffer([256], dtype="float32") T_softmax_exp = T.alloc_buffer([256, 256], dtype="float32") T_softmax_expsum = T.alloc_buffer([256], dtype="float32") T_softmax_expsum_rf = T.alloc_buffer([256, 16], dtype="float32") T_softmax_maxelem_rf = T.alloc_buffer([256, 64], dtype="float32") for i0 in T.serial(256): for ax0, ax1, ax2 in T.grid(64, 1, 4): with T.block("T_softmax_maxelem_rf"): vi1_1 = T.axis.spatial(64, ax0) i0_1 = T.axis.spatial(256, i0 + ax1) vi1_0 = T.axis.reduce(4, ax2) T.reads(A[i0_1, vi1_0 * 64 + vi1_1]) T.writes(T_softmax_maxelem_rf[i0_1, vi1_1]) with T.init(): T_softmax_maxelem_rf[i0_1, vi1_1] = T.float32(-3.4028234663852886e+38) T_softmax_maxelem_rf[i0_1, vi1_1] = T.max(T_softmax_maxelem_rf[i0_1, vi1_1], A[i0_1, vi1_0 * 64 + vi1_1]) for i1 in T.serial(256): for ax0, ax1 in T.grid(64, 1): with T.block("T_softmax_maxelem"): vi1_1 = T.axis.reduce(64, ax0) i0_2 = T.axis.spatial(256, i0 + ax1) T.reads(T_softmax_maxelem_rf[i0_2, vi1_1]) T.writes(T_softmax_maxelem[i0_2]) with T.init(): T_softmax_maxelem[i0_2] = T.float32(-3.4028234663852886e+38) T_softmax_maxelem[i0_2] = T.max(T_softmax_maxelem[i0_2], T_softmax_maxelem_rf[i0_2, vi1_1]) with T.block("T_softmax_exp"): i0_3, i1_1 = T.axis.remap("SS", [i0, i1]) T.reads(A[i0_3, i1_1], T_softmax_maxelem[i0_3]) T.writes(T_softmax_exp[i0_3, i1_1]) T_softmax_exp[i0_3, i1_1] = T.exp(A[i0_3, i1_1] - T_softmax_maxelem[i0_3], dtype="float32") for i0_4, i1_0, i1_1_1 in T.grid(256, 16, 16): with T.block("T_softmax_expsum_rf"): vi1_0, i0_5, vi1_1 = T.axis.remap("SSR", [i1_0, i0_4, i1_1_1]) T.reads(T_softmax_exp[i0_5, vi1_0 * 16 + vi1_1]) T.writes(T_softmax_expsum_rf[i0_5, vi1_0]) with T.init(): T_softmax_expsum_rf[i0_5, vi1_0] = T.float32(0) T_softmax_expsum_rf[i0_5, vi1_0] = T_softmax_expsum_rf[i0_5, vi1_0] + T_softmax_exp[i0_5, vi1_0 * 16 + vi1_1] for i0_6, i1_0 in T.grid(256, 16): with T.block("T_softmax_expsum"): vi1_0, i0_7 = T.axis.remap("RS", [i1_0, i0_6]) T.reads(T_softmax_expsum_rf[i0_7, vi1_0]) T.writes(T_softmax_expsum[i0_7]) with T.init(): T_softmax_expsum[i0_7] = T.float32(0) T_softmax_expsum[i0_7] = T_softmax_expsum[i0_7] + T_softmax_expsum_rf[i0_7, vi1_0] for i0_8, i1 in T.grid(256, 256): with T.block("T_softmax_norm"): i0_9, i1_2 = T.axis.remap("SS", [i0_8, i1]) T.reads(T_softmax_exp[i0_9, i1_2], T_softmax_expsum[i0_9]) T.writes(T_softmax_norm[i0_9, i1_2]) T.block_attr({"axis":1}) T_softmax_norm[i0_9, i1_2] = T_softmax_exp[i0_9, i1_2] / T_softmax_expsum[i0_9] @T.prim_func def sfm_2(A: T.Buffer[(256, 256), "float32"], T_softmax_norm: T.Buffer[(256, 256), "float32"]) -> None: # function attr dict T.func_attr({"global_symbol": "main", "tir.noalias": True}) # body with T.block("root"): T.reads() T.writes() T.block_attr({"meta_schedule.parallel":288, "meta_schedule.unroll_explicit":512, "meta_schedule.vectorize":64}) T_softmax_maxelem = T.alloc_buffer([256], dtype="float32") T_softmax_expsum = T.alloc_buffer([256], dtype="float32") T_softmax_expsum_rf = T.alloc_buffer([256, 16], dtype="float32") for i0, i1 in T.grid(256, 256): with T.block("T_softmax_maxelem"): i0_1, k = T.axis.remap("SR", [i0, i1]) T.reads(A[i0_1, k]) T.writes(T_softmax_maxelem[i0_1]) with T.init(): T_softmax_maxelem[i0_1] = T.float32(-3.4028234663852886e+38) T_softmax_maxelem[i0_1] = T.max(T_softmax_maxelem[i0_1], A[i0_1, k]) for i0, i1_0, i1_1 in T.grid(256, 16, 16): with T.block("T_softmax_expsum_rf"): vi1_0, i0_2, vi1_1 = T.axis.remap("SSR", [i1_0, i0, i1_1]) T.reads(A[i0_2, vi1_0 * 16 + vi1_1], T_softmax_maxelem[i0_2]) T.writes(T_softmax_expsum_rf[i0_2, vi1_0]) with T.init(): T_softmax_expsum_rf[i0_2, vi1_0] = T.float32(0) T_softmax_expsum_rf[i0_2, vi1_0] = T_softmax_expsum_rf[i0_2, vi1_0] + T.exp(A[i0_2, vi1_0 * 16 + vi1_1] - T_softmax_maxelem[i0_2], dtype="float32") for i0_3, i1_0 in T.grid(256, 16): with T.block("T_softmax_expsum"): vi1_0, i0_4 = T.axis.remap("RS", [i1_0, i0_3]) T.reads(T_softmax_expsum_rf[i0_4, vi1_0]) T.writes(T_softmax_expsum[i0_4]) with T.init(): T_softmax_expsum[i0_4] = T.float32(0) T_softmax_expsum[i0_4] = T_softmax_expsum[i0_4] + T_softmax_expsum_rf[i0_4, vi1_0] for i0_5, i1 in T.grid(256, 256): with T.block("T_softmax_norm"): i0_6, i1_2 = T.axis.remap("SS", [i0_5, i1]) T.reads(A[i0_6, i1_2], T_softmax_maxelem[i0_6], T_softmax_expsum[i0_6]) T.writes(T_softmax_norm[i0_6, i1_2]) T.block_attr({"axis":1}) T_softmax_norm[i0_6, i1_2] = T.exp(A[i0_6, i1_2] - T_softmax_maxelem[i0_6], dtype="float32") / T_softmax_expsum[i0_6] @T.prim_func def sfm_3(A: T.Buffer[(256, 256), "float32"], T_softmax_norm: T.Buffer[(256, 256), "float32"]) -> None: # function attr dict T.func_attr({"global_symbol": "main", "tir.noalias": True}) # body with T.block("root"): T.reads() T.writes() T.block_attr({"meta_schedule.parallel":288, "meta_schedule.unroll_explicit":512, "meta_schedule.vectorize":64}) T_softmax_maxelem = T.alloc_buffer([256], dtype="float32") T_softmax_exp = T.alloc_buffer([256, 256], dtype="float32") T_softmax_expsum = T.alloc_buffer([256], dtype="float32") T_softmax_expsum_rf = T.alloc_buffer([256, 16], dtype="float32") T_softmax_maxelem_rf = T.alloc_buffer([256, 256], dtype="float32") for i0, i1 in T.grid(256, 256): for ax0, ax1, ax2 in T.grid(256, 1, 1): with T.block("T_softmax_maxelem_rf"): vi1_0 = T.axis.spatial(256, ax0) i0_1 = T.axis.spatial(256, i0 + ax1) vi1_1 = T.axis.reduce(1, ax2) T.reads(A[i0_1, vi1_1 + vi1_0]) T.writes(T_softmax_maxelem_rf[i0_1, vi1_0]) with T.init(): T_softmax_maxelem_rf[i0_1, vi1_0] = T.float32(-3.4028234663852886e+38) T_softmax_maxelem_rf[i0_1, vi1_0] = T.max(T_softmax_maxelem_rf[i0_1, vi1_0], A[i0_1, vi1_1 + vi1_0]) for ax0, ax1 in T.grid(256, 1): with T.block("T_softmax_maxelem"): vi1_0 = T.axis.reduce(256, ax0) i0_2 = T.axis.spatial(256, i0 + ax1) T.reads(T_softmax_maxelem_rf[i0_2, vi1_0]) T.writes(T_softmax_maxelem[i0_2]) with T.init(): T_softmax_maxelem[i0_2] = T.float32(-3.4028234663852886e+38) T_softmax_maxelem[i0_2] = T.max(T_softmax_maxelem[i0_2], T_softmax_maxelem_rf[i0_2, vi1_0]) for ax0, ax1 in T.grid(1, 256): with T.block("T_softmax_exp"): i0_3 = T.axis.spatial(256, i0 + ax0) i1_1 = T.axis.spatial(256, ax1) T.reads(A[i0_3, i1_1], T_softmax_maxelem[i0_3]) T.writes(T_softmax_exp[i0_3, i1_1]) T_softmax_exp[i0_3, i1_1] = T.exp(A[i0_3, i1_1] - T_softmax_maxelem[i0_3], dtype="float32") for ax0 in T.serial(16): for ax0_1, ax1, ax2 in T.grid(1, 1, 16): with T.block("T_softmax_expsum_rf"): vi1_1 = T.axis.spatial(16, ax0 + ax0_1) i0_4 = T.axis.spatial(256, i0 + ax1) vi1_0 = T.axis.reduce(16, ax2) T.reads(T_softmax_exp[i0_4, vi1_0 * 16 + vi1_1]) T.writes(T_softmax_expsum_rf[i0_4, vi1_1]) with T.init(): T_softmax_expsum_rf[i0_4, vi1_1] = T.float32(0) T_softmax_expsum_rf[i0_4, vi1_1] = T_softmax_expsum_rf[i0_4, vi1_1] + T_softmax_exp[i0_4, vi1_0 * 16 + vi1_1] for ax1 in T.serial(1): with T.block("T_softmax_expsum"): vi1_1 = T.axis.reduce(16, ax0) i0_5 = T.axis.spatial(256, i0 + ax1) T.reads(T_softmax_expsum_rf[i0_5, vi1_1]) T.writes(T_softmax_expsum[i0_5]) with T.init(): T_softmax_expsum[i0_5] = T.float32(0) T_softmax_expsum[i0_5] = T_softmax_expsum[i0_5] + T_softmax_expsum_rf[i0_5, vi1_1] with T.block("T_softmax_norm"): i0_6, i1_2 = T.axis.remap("SS", [i0, i1]) T.reads(T_softmax_exp[i0_6, i1_2], T_softmax_expsum[i0_6]) T.writes(T_softmax_norm[i0_6, i1_2]) T.block_attr({"axis":1}) T_softmax_norm[i0_6, i1_2] = T_softmax_exp[i0_6, i1_2] / T_softmax_expsum[i0_6] @T.prim_func def sfm_4(A: T.Buffer[(256, 256), "float32"], T_softmax_norm: T.Buffer[(256, 256), "float32"]) -> None: # function attr dict T.func_attr({"global_symbol": "main", "tir.noalias": True}) # body with T.block("root"): T.reads() T.writes() T.block_attr({"meta_schedule.parallel":288, "meta_schedule.unroll_explicit":0, "meta_schedule.vectorize":64}) T_softmax_maxelem = T.alloc_buffer([256], dtype="float32") T_softmax_exp = T.alloc_buffer([256, 256], dtype="float32") T_softmax_expsum = T.alloc_buffer([256], dtype="float32") T_softmax_expsum_rf = T.alloc_buffer([256, 16], dtype="float32") T_softmax_maxelem_rf = T.alloc_buffer([256, 1], dtype="float32") for i0 in T.serial(256): for ax0, ax1, ax2 in T.grid(1, 1, 256): with T.block("T_softmax_maxelem_rf"): vi1_1 = T.axis.spatial(1, ax0) i0_1 = T.axis.spatial(256, i0 + ax1) vi1_0 = T.axis.reduce(256, ax2) T.reads(A[i0_1, vi1_1 + vi1_0]) T.writes(T_softmax_maxelem_rf[i0_1, vi1_1]) with T.init(): T_softmax_maxelem_rf[i0_1, vi1_1] = T.float32(-3.4028234663852886e+38) T_softmax_maxelem_rf[i0_1, vi1_1] = T.max(T_softmax_maxelem_rf[i0_1, vi1_1], A[i0_1, vi1_1 + vi1_0]) for i1_1 in T.serial(1): with T.block("T_softmax_maxelem"): vi1_1, i0_2 = T.axis.remap("RS", [i1_1, i0]) T.reads(T_softmax_maxelem_rf[i0_2, vi1_1]) T.writes(T_softmax_maxelem[i0_2]) with T.init(): T_softmax_maxelem[i0_2] = T.float32(-3.4028234663852886e+38) T_softmax_maxelem[i0_2] = T.max(T_softmax_maxelem[i0_2], T_softmax_maxelem_rf[i0_2, vi1_1]) for i0_3, i1 in T.grid(256, 256): with T.block("T_softmax_exp"): i0_4, i1_2 = T.axis.remap("SS", [i0_3, i1]) T.reads(A[i0_4, i1_2], T_softmax_maxelem[i0_4]) T.writes(T_softmax_exp[i0_4, i1_2]) T_softmax_exp[i0_4, i1_2] = T.exp(A[i0_4, i1_2] - T_softmax_maxelem[i0_4], dtype="float32") for i0_5, i1_0, i1_1 in T.grid(256, 16, 16): with T.block("T_softmax_expsum_rf"): vi1_1, i0_6, vi1_0 = T.axis.remap("SSR", [i1_1, i0_5, i1_0]) T.reads(T_softmax_exp[i0_6, vi1_0 * 16 + vi1_1]) T.writes(T_softmax_expsum_rf[i0_6, vi1_1]) with T.init(): T_softmax_expsum_rf[i0_6, vi1_1] = T.float32(0) T_softmax_expsum_rf[i0_6, vi1_1] = T_softmax_expsum_rf[i0_6, vi1_1] + T_softmax_exp[i0_6, vi1_0 * 16 + vi1_1] for i0_7, i1_1 in T.grid(256, 16): with T.block("T_softmax_expsum"): vi1_1, i0_8 = T.axis.remap("RS", [i1_1, i0_7]) T.reads(T_softmax_expsum_rf[i0_8, vi1_1]) T.writes(T_softmax_expsum[i0_8]) with T.init(): T_softmax_expsum[i0_8] = T.float32(0) T_softmax_expsum[i0_8] = T_softmax_expsum[i0_8] + T_softmax_expsum_rf[i0_8, vi1_1] for i0_9, i1_3 in T.grid(256, 256): with T.block("T_softmax_norm"): i0_10, i1_4 = T.axis.remap("SS", [i0_9, i1_3]) T.reads(T_softmax_exp[i0_10, i1_4], T_softmax_expsum[i0_10]) T.writes(T_softmax_norm[i0_10, i1_4]) T.block_attr({"axis":1}) T_softmax_norm[i0_10, i1_4] = T_softmax_exp[i0_10, i1_4] / T_softmax_expsum[i0_10] @T.prim_func def sfm_5(A: T.Buffer[(256, 256), "float32"], T_softmax_norm: T.Buffer[(256, 256), "float32"]) -> None: # function attr dict T.func_attr({"global_symbol": "main", "tir.noalias": True}) # body with T.block("root"): T.reads() T.writes() T.block_attr({"meta_schedule.parallel":288, "meta_schedule.unroll_explicit":512, "meta_schedule.vectorize":64}) T_softmax_maxelem = T.alloc_buffer([256], dtype="float32") T_softmax_exp = T.alloc_buffer([256, 256], dtype="float32") T_softmax_expsum = T.alloc_buffer([256], dtype="float32") T_softmax_expsum_rf = T.alloc_buffer([256, 16], dtype="float32") for i0 in T.serial(256): for ax0, ax1 in T.grid(1, 256): with T.block("T_softmax_maxelem"): i0_1 = T.axis.spatial(256, i0 + ax0) k = T.axis.reduce(256, ax1) T.reads(A[i0_1, k]) T.writes(T_softmax_maxelem[i0_1]) with T.init(): T_softmax_maxelem[i0_1] = T.float32(-3.4028234663852886e+38) T_softmax_maxelem[i0_1] = T.max(T_softmax_maxelem[i0_1], A[i0_1, k]) for ax0, ax1 in T.grid(1, 256): with T.block("T_softmax_exp"): i0_2 = T.axis.spatial(256, i0 + ax0) i1 = T.axis.spatial(256, ax1) T.reads(A[i0_2, i1], T_softmax_maxelem[i0_2]) T.writes(T_softmax_exp[i0_2, i1]) T_softmax_exp[i0_2, i1] = T.exp(A[i0_2, i1] - T_softmax_maxelem[i0_2], dtype="float32") for ax0 in T.serial(16): for ax0_1, ax1, ax2 in T.grid(1, 1, 16): with T.block("T_softmax_expsum_rf"): vi1_1 = T.axis.spatial(16, ax0 + ax0_1) i0_3 = T.axis.spatial(256, i0 + ax1) vi1_0 = T.axis.reduce(16, ax2) T.reads(T_softmax_exp[i0_3, vi1_0 * 16 + vi1_1]) T.writes(T_softmax_expsum_rf[i0_3, vi1_1]) with T.init(): T_softmax_expsum_rf[i0_3, vi1_1] = T.float32(0) T_softmax_expsum_rf[i0_3, vi1_1] = T_softmax_expsum_rf[i0_3, vi1_1] + T_softmax_exp[i0_3, vi1_0 * 16 + vi1_1] for ax1 in T.serial(1): with T.block("T_softmax_expsum"): vi1_1 = T.axis.reduce(16, ax0) i0_4 = T.axis.spatial(256, i0 + ax1) T.reads(T_softmax_expsum_rf[i0_4, vi1_1]) T.writes(T_softmax_expsum[i0_4]) with T.init(): T_softmax_expsum[i0_4] = T.float32(0) T_softmax_expsum[i0_4] = T_softmax_expsum[i0_4] + T_softmax_expsum_rf[i0_4, vi1_1] for i1 in T.serial(256): with T.block("T_softmax_norm"): i0_5, i1_1 = T.axis.remap("SS", [i0, i1]) T.reads(T_softmax_exp[i0_5, i1_1], T_softmax_expsum[i0_5]) T.writes(T_softmax_norm[i0_5, i1_1]) T.block_attr({"axis":1}) T_softmax_norm[i0_5, i1_1] = T_softmax_exp[i0_5, i1_1] / T_softmax_expsum[i0_5] @T.prim_func def sfm_6(A: T.Buffer[(256, 256), "float32"], T_softmax_norm: T.Buffer[(256, 256), "float32"]) -> None: # function attr dict T.func_attr({"global_symbol": "main", "tir.noalias": True}) # body with T.block("root"): T.reads() T.writes() T.block_attr({"meta_schedule.parallel":288, "meta_schedule.unroll_explicit":64, "meta_schedule.vectorize":64}) T_softmax_maxelem = T.alloc_buffer([256], dtype="float32") T_softmax_expsum = T.alloc_buffer([256], dtype="float32") T_softmax_maxelem_rf = T.alloc_buffer([256, 64], dtype="float32") for i0 in T.serial(256): for ax0, ax1, ax2 in T.grid(64, 1, 4): with T.block("T_softmax_maxelem_rf"): vi1_0 = T.axis.spatial(64, ax0) i0_1 = T.axis.spatial(256, i0 + ax1) vi1_1 = T.axis.reduce(4, ax2) T.reads(A[i0_1, vi1_0 * 4 + vi1_1]) T.writes(T_softmax_maxelem_rf[i0_1, vi1_0]) with T.init(): T_softmax_maxelem_rf[i0_1, vi1_0] = T.float32(-3.4028234663852886e+38) T_softmax_maxelem_rf[i0_1, vi1_0] = T.max(T_softmax_maxelem_rf[i0_1, vi1_0], A[i0_1, vi1_0 * 4 + vi1_1]) for i1_0 in T.serial(64): with T.block("T_softmax_maxelem"): vi1_0, i0_2 = T.axis.remap("RS", [i1_0, i0]) T.reads(T_softmax_maxelem_rf[i0_2, vi1_0]) T.writes(T_softmax_maxelem[i0_2]) with T.init(): T_softmax_maxelem[i0_2] = T.float32(-3.4028234663852886e+38) T_softmax_maxelem[i0_2] = T.max(T_softmax_maxelem[i0_2], T_softmax_maxelem_rf[i0_2, vi1_0]) for i0_3, i1 in T.grid(256, 256): with T.block("T_softmax_expsum"): i0_4, k = T.axis.remap("SR", [i0_3, i1]) T.reads(A[i0_4, k], T_softmax_maxelem[i0_4]) T.writes(T_softmax_expsum[i0_4]) with T.init(): T_softmax_expsum[i0_4] = T.float32(0) T_softmax_expsum[i0_4] = T_softmax_expsum[i0_4] + T.exp(A[i0_4, k] - T_softmax_maxelem[i0_4], dtype="float32") for i0_5, i1 in T.grid(256, 256): with T.block("T_softmax_norm"): i0_6, i1_1 = T.axis.remap("SS", [i0_5, i1]) T.reads(A[i0_6, i1_1], T_softmax_maxelem[i0_6], T_softmax_expsum[i0_6]) T.writes(T_softmax_norm[i0_6, i1_1]) T.block_attr({"axis":1}) T_softmax_norm[i0_6, i1_1] = T.exp(A[i0_6, i1_1] - T_softmax_maxelem[i0_6], dtype="float32") / T_softmax_expsum[i0_6] @T.prim_func def sfm_7(A: T.Buffer[(256, 256), "float32"], T_softmax_norm: T.Buffer[(256, 256), "float32"]) -> None: # function attr dict T.func_attr({"global_symbol": "main", "tir.noalias": True}) # body with T.block("root"): T.reads() T.writes() T.block_attr({"meta_schedule.parallel":288, "meta_schedule.unroll_explicit":64, "meta_schedule.vectorize":64}) T_softmax_maxelem = T.alloc_buffer([256], dtype="float32") T_softmax_expsum = T.alloc_buffer([256], dtype="float32") T_softmax_maxelem_rf = T.alloc_buffer([256, 4], dtype="float32") for i0, i1_0, i1_1 in T.grid(256, 64, 4): with T.block("T_softmax_maxelem_rf"): vi1_1, i0_1, vi1_0 = T.axis.remap("SSR", [i1_1, i0, i1_0]) T.reads(A[i0_1, vi1_0 * 4 + vi1_1]) T.writes(T_softmax_maxelem_rf[i0_1, vi1_1]) with T.init(): T_softmax_maxelem_rf[i0_1, vi1_1] = T.float32(-3.4028234663852886e+38) T_softmax_maxelem_rf[i0_1, vi1_1] = T.max(T_softmax_maxelem_rf[i0_1, vi1_1], A[i0_1, vi1_0 * 4 + vi1_1]) for i0, i1_1 in T.grid(256, 4): with T.block("T_softmax_maxelem"): vi1_1, i0_2 = T.axis.remap("RS", [i1_1, i0]) T.reads(T_softmax_maxelem_rf[i0_2, vi1_1]) T.writes(T_softmax_maxelem[i0_2]) with T.init(): T_softmax_maxelem[i0_2] = T.float32(-3.4028234663852886e+38) T_softmax_maxelem[i0_2] = T.max(T_softmax_maxelem[i0_2], T_softmax_maxelem_rf[i0_2, vi1_1]) for i0_3, i1 in T.grid(256, 256): for ax0, ax1 in T.grid(1, 256): with T.block("T_softmax_expsum"): i0_4 = T.axis.spatial(256, i0_3 + ax0) k = T.axis.reduce(256, ax1) T.reads(A[i0_4, k], T_softmax_maxelem[i0_4]) T.writes(T_softmax_expsum[i0_4]) with T.init(): T_softmax_expsum[i0_4] = T.float32(0) T_softmax_expsum[i0_4] = T_softmax_expsum[i0_4] + T.exp(A[i0_4, k] - T_softmax_maxelem[i0_4], dtype="float32") with T.block("T_softmax_norm"): i0_5, i1_2 = T.axis.remap("SS", [i0_3, i1]) T.reads(A[i0_5, i1_2], T_softmax_maxelem[i0_5], T_softmax_expsum[i0_5]) T.writes(T_softmax_norm[i0_5, i1_2]) T.block_attr({"axis":1}) T_softmax_norm[i0_5, i1_2] = T.exp(A[i0_5, i1_2] - T_softmax_maxelem[i0_5], dtype="float32") / T_softmax_expsum[i0_5] @T.prim_func def sfm_8(A: T.Buffer[(256, 256), "float32"], T_softmax_norm: T.Buffer[(256, 256), "float32"]) -> None: # function attr dict T.func_attr({"global_symbol": "main", "tir.noalias": True}) # body with T.block("root"): T.reads() T.writes() T.block_attr({"meta_schedule.parallel":288, "meta_schedule.unroll_explicit":512, "meta_schedule.vectorize":64}) T_softmax_maxelem = T.alloc_buffer([256], dtype="float32") T_softmax_exp = T.alloc_buffer([256, 256], dtype="float32") T_softmax_expsum = T.alloc_buffer([256], dtype="float32") for i0 in T.serial(256): for ax0, ax1 in T.grid(1, 256): with T.block("T_softmax_maxelem"): i0_1 = T.axis.spatial(256, i0 + ax0) k = T.axis.reduce(256, ax1) T.reads(A[i0_1, k]) T.writes(T_softmax_maxelem[i0_1]) with T.init(): T_softmax_maxelem[i0_1] = T.float32(-3.4028234663852886e+38) T_softmax_maxelem[i0_1] = T.max(T_softmax_maxelem[i0_1], A[i0_1, k]) for i1 in T.serial(256): with T.block("T_softmax_exp"): i0_2, i1_1 = T.axis.remap("SS", [i0, i1]) T.reads(A[i0_2, i1_1], T_softmax_maxelem[i0_2]) T.writes(T_softmax_exp[i0_2, i1_1]) T_softmax_exp[i0_2, i1_1] = T.exp(A[i0_2, i1_1] - T_softmax_maxelem[i0_2], dtype="float32") for i0_3, i1 in T.grid(256, 256): with T.block("T_softmax_expsum"): i0_4, k = T.axis.remap("SR", [i0_3, i1]) T.reads(T_softmax_exp[i0_4, k]) T.writes(T_softmax_expsum[i0_4]) with T.init(): T_softmax_expsum[i0_4] = T.float32(0) T_softmax_expsum[i0_4] = T_softmax_expsum[i0_4] + T_softmax_exp[i0_4, k] for i0_5, i1 in T.grid(256, 256): with T.block("T_softmax_norm"): i0_6, i1_2 = T.axis.remap("SS", [i0_5, i1]) T.reads(T_softmax_exp[i0_6, i1_2], T_softmax_expsum[i0_6]) T.writes(T_softmax_norm[i0_6, i1_2]) T.block_attr({"axis":1}) T_softmax_norm[i0_6, i1_2] = T_softmax_exp[i0_6, i1_2] / T_softmax_expsum[i0_6] # fmt: on decision_0 = [ ("SamplePerfectTile", [16, 16]), ("SamplePerfectTile", [4, 64]), ("SampleCategorical", 0), ("SampleComputeLocation", 1), ("SampleComputeLocation", -1), ("SampleComputeLocation", -2), ("SampleComputeLocation", -1), ("SampleComputeLocation", -1), ] decision_1 = [ ("SamplePerfectTile", [16, 16]), ("SamplePerfectTile", [4, 64]), ("SampleCategorical", 1), ("SampleComputeLocation", -1), ("SampleComputeLocation", -1), ("SampleComputeLocation", -1), ("SampleComputeLocation", 1), ("SampleComputeLocation", 0), ] decision_2 = [ ("SamplePerfectTile", [16, 16]), ("SampleCategorical", 3), ("SampleComputeLocation", -1), ("SampleComputeLocation", -1), ("SampleComputeLocation", -2), ("SampleComputeLocation", -1), ] decision_3 = [ ("SamplePerfectTile", [16, 16]), ("SamplePerfectTile", [256, 1]), ("SampleCategorical", 3), ("SampleComputeLocation", 1), ("SampleComputeLocation", 2), ("SampleComputeLocation", 1), ("SampleComputeLocation", 1), ("SampleComputeLocation", 1), ] decision_4 = [ ("SamplePerfectTile", [16, 16]), ("SamplePerfectTile", [256, 1]), ("SampleCategorical", 0), ("SampleComputeLocation", -1), ("SampleComputeLocation", -1), ("SampleComputeLocation", -1), ("SampleComputeLocation", -1), ("SampleComputeLocation", 0), ] decision_5 = [ ("SamplePerfectTile", [16, 16]), ("SampleCategorical", 3), ("SampleComputeLocation", 0), ("SampleComputeLocation", 1), ("SampleComputeLocation", 0), ("SampleComputeLocation", 0), ] decision_6 = [ ("SamplePerfectTile", [64, 4]), ("SampleCategorical", 2), ("SampleComputeLocation", -1), ("SampleComputeLocation", -2), ("SampleComputeLocation", -1), ("SampleComputeLocation", 0), ] decision_7 = [ ("SamplePerfectTile", [64, 4]), ("SampleCategorical", 2), ("SampleComputeLocation", 1), ("SampleComputeLocation", -2), ("SampleComputeLocation", -1), ("SampleComputeLocation", -1), ] decision_8 = [ ("SampleCategorical", 3), ("SampleComputeLocation", -1), ("SampleComputeLocation", -1), ("SampleComputeLocation", 0), ] mod = create_te_workload("SFM", 0) actual = _design_space(mod) check_sketches( mod, sketches=actual, expected_mods=[sfm_0, sfm_1, sfm_2, sfm_3, sfm_4, sfm_5, sfm_6, sfm_7, sfm_8], expected_decisions=[ decision_0, decision_1, decision_2, decision_3, decision_4, decision_5, decision_6, decision_7, decision_8, ], ) def test_cpu_cbr(): # fmt: off @T.prim_func def cbr_0(data: T.Buffer[(1, 224, 224, 3), "float32"], kernel: T.Buffer[(7, 7, 3, 64), "float32"], bias: T.Buffer[64, "float32"], bn_offset: T.Buffer[64, "float32"], bn_scale: T.Buffer[64, "float32"], compute: T.Buffer[(1, 112, 112, 64), "float32"]) -> None: # function attr dict T.func_attr({"global_symbol": "main", "tir.noalias": True}) # body with T.block("root"): T.reads() T.writes() T.block_attr({"meta_schedule.parallel":288, "meta_schedule.unroll_explicit":64, "meta_schedule.vectorize":64}) Conv2dOutput = T.alloc_buffer([1, 112, 112, 64], dtype="float32") for i0_0, i1_0, i2_0, i3_0, i0_1, i1_1, i2_1, i3_1, i4_0, i5_0, i6_0, i0_2, i1_2, i2_2, i3_2, i4_1, i5_1, i6_1, i0_3, i1_3, i2_3, i3_3 in T.grid(1, 2, 7, 1, 1, 2, 2, 32, 7, 7, 1, 1, 1, 4, 1, 1, 1, 3, 1, 28, 2, 2): with T.block("Conv2dOutput"): nn = T.axis.spatial(1, i0_3 + i0_0 + i0_1 + i0_2) yy = T.axis.spatial(112, i1_0 * 56 + i1_1 * 28 + i1_2 * 28 + i1_3) xx = T.axis.spatial(112, i2_0 * 16 + i2_1 * 8 + i2_2 * 2 + i2_3) ff = T.axis.spatial(64, i3_0 * 64 + i3_1 * 2 + i3_2 * 2 + i3_3) ry = T.axis.reduce(7, i4_1 + i4_0) rx = T.axis.reduce(7, i5_0 + i5_1) rc = T.axis.reduce(3, i6_0 * 3 + i6_1) T.reads(data[nn, yy * 2 + ry - 3, xx * 2 + rx - 3, rc], kernel[ry, rx, rc, ff]) T.writes(Conv2dOutput[nn, yy, xx, ff]) T.block_attr({"meta_schedule.tiling_structure":"SSRSRS"}) with T.init(): Conv2dOutput[nn, yy, xx, ff] = T.float32(0) Conv2dOutput[nn, yy, xx, ff] = Conv2dOutput[nn, yy, xx, ff] + T.if_then_else(3 <= yy * 2 + ry and yy * 2 + ry < 227 and 3 <= xx * 2 + rx and xx * 2 + rx < 227, data[nn, yy * 2 + ry - 3, xx * 2 + rx - 3, rc], T.float32(0), dtype="float32") * kernel[ry, rx, rc, ff] for i0, i1, i2, i3 in T.grid(1, 112, 112, 64): with T.block("compute"): i0_4, i1_4, i2_4, i3_4 = T.axis.remap("SSSS", [i0, i1, i2, i3]) T.reads(Conv2dOutput[i0_4, i1_4, i2_4, i3_4], bias[i3_4], bn_scale[i3_4], bn_offset[i3_4]) T.writes(compute[i0_4, i1_4, i2_4, i3_4]) compute[i0_4, i1_4, i2_4, i3_4] = T.max((Conv2dOutput[i0_4, i1_4, i2_4, i3_4] + bias[i3_4]) * bn_scale[i3_4] + bn_offset[i3_4], T.float32(0)) @T.prim_func def cbr_1(data: T.Buffer[(1, 224, 224, 3), "float32"], kernel: T.Buffer[(7, 7, 3, 64), "float32"], bias: T.Buffer[64, "float32"], bn_offset: T.Buffer[64, "float32"], bn_scale: T.Buffer[64, "float32"], compute: T.Buffer[(1, 112, 112, 64), "float32"]) -> None: # function attr dict T.func_attr({"global_symbol": "main", "tir.noalias": True}) # body with T.block("root"): T.reads() T.writes() T.block_attr({"meta_schedule.parallel":288, "meta_schedule.unroll_explicit":512, "meta_schedule.vectorize":64}) PaddedInput = T.alloc_buffer([1, 230, 230, 3], dtype="float32") Conv2dOutput = T.alloc_buffer([1, 112, 112, 64], dtype="float32") for i0_0, i1_0 in T.grid(1, 2): for ax0, ax1, ax2, ax3 in T.grid(1, 117, 229, 3): with T.block("PaddedInput"): i0 = T.axis.spatial(1, ax0) i1 = T.axis.spatial(230, i1_0 * 112 + ax1) i2 = T.axis.spatial(230, ax2) i3 = T.axis.spatial(3, ax3) T.reads(data[i0, i1 - 3, i2 - 3, i3]) T.writes(PaddedInput[i0, i1, i2, i3]) PaddedInput[i0, i1, i2, i3] = T.if_then_else(3 <= i1 and i1 < 227 and 3 <= i2 and i2 < 227, data[i0, i1 - 3, i2 - 3, i3], T.float32(0), dtype="float32") for i2_0, i3_0, i0_1, i1_1, i2_1, i3_1 in T.grid(7, 1, 1, 2, 2, 32): for i4_0, i5_0, i6_0, i0_2, i1_2, i2_2, i3_2, i4_1, i5_1, i6_1, i0_3, i1_3, i2_3, i3_3 in T.grid(7, 7, 1, 1, 1, 4, 1, 1, 1, 3, 1, 28, 2, 2): with T.block("Conv2dOutput"): nn = T.axis.spatial(1, i0_3 + i0_0 + i0_1 + i0_2) yy = T.axis.spatial(112, i1_0 * 56 + i1_1 * 28 + i1_2 * 28 + i1_3) xx = T.axis.spatial(112, i2_0 * 16 + i2_1 * 8 + i2_2 * 2 + i2_3) ff = T.axis.spatial(64, i3_0 * 64 + i3_1 * 2 + i3_2 * 2 + i3_3) ry = T.axis.reduce(7, i4_1 + i4_0) rx = T.axis.reduce(7, i5_0 + i5_1) rc = T.axis.reduce(3, i6_0 * 3 + i6_1) T.reads(PaddedInput[nn, yy * 2 + ry, xx * 2 + rx, rc], kernel[ry, rx, rc, ff]) T.writes(Conv2dOutput[nn, yy, xx, ff]) T.block_attr({"meta_schedule.tiling_structure":"SSRSRS"}) with T.init(): Conv2dOutput[nn, yy, xx, ff] = T.float32(0) Conv2dOutput[nn, yy, xx, ff] = Conv2dOutput[nn, yy, xx, ff] + PaddedInput[nn, yy * 2 + ry, xx * 2 + rx, rc] * kernel[ry, rx, rc, ff] for ax0, ax1, ax2, ax3 in T.grid(1, 28, 8, 2): with T.block("compute"): i0 = T.axis.spatial(1, ax0) i1 = T.axis.spatial(112, i1_0 * 56 + i1_1 * 28 + ax1) i2 = T.axis.spatial(112, i2_0 * 16 + i2_1 * 8 + ax2) i3 = T.axis.spatial(64, i3_1 * 2 + ax3) T.reads(Conv2dOutput[i0, i1, i2, i3], bias[i3], bn_scale[i3], bn_offset[i3]) T.writes(compute[i0, i1, i2, i3]) compute[i0, i1, i2, i3] = T.max((Conv2dOutput[i0, i1, i2, i3] + bias[i3]) * bn_scale[i3] + bn_offset[i3], T.float32(0)) @T.prim_func def cbr_2(data: T.Buffer[(1, 224, 224, 3), "float32"], kernel: T.Buffer[(7, 7, 3, 64), "float32"], bias: T.Buffer[64, "float32"], bn_offset: T.Buffer[64, "float32"], bn_scale: T.Buffer[64, "float32"], compute: T.Buffer[(1, 112, 112, 64), "float32"]) -> None: # function attr dict T.func_attr({"global_symbol": "main", "tir.noalias": True}) # body with T.block("root"): T.reads() T.writes() T.block_attr({"meta_schedule.parallel":288, "meta_schedule.unroll_explicit":64, "meta_schedule.vectorize":64}) PaddedInput = T.alloc_buffer([1, 230, 230, 3], dtype="float32") Conv2dOutput = T.alloc_buffer([1, 112, 112, 64], dtype="float32") for i0_0, i1_0 in T.grid(1, 2): for ax0, ax1, ax2, ax3 in T.grid(1, 117, 229, 3): with T.block("PaddedInput"): i0 = T.axis.spatial(1, ax0) i1 = T.axis.spatial(230, i1_0 * 112 + ax1) i2 = T.axis.spatial(230, ax2) i3 = T.axis.spatial(3, ax3) T.reads(data[i0, i1 - 3, i2 - 3, i3]) T.writes(PaddedInput[i0, i1, i2, i3]) PaddedInput[i0, i1, i2, i3] = T.if_then_else(3 <= i1 and i1 < 227 and 3 <= i2 and i2 < 227, data[i0, i1 - 3, i2 - 3, i3], T.float32(0), dtype="float32") for i2_0, i3_0 in T.grid(7, 1): for i0_1, i1_1, i2_1, i3_1, i4_0, i5_0, i6_0, i0_2, i1_2, i2_2, i3_2, i4_1, i5_1, i6_1, i0_3, i1_3, i2_3, i3_3 in T.grid(1, 2, 2, 32, 7, 7, 1, 1, 1, 4, 1, 1, 1, 3, 1, 28, 2, 2): with T.block("Conv2dOutput"): nn = T.axis.spatial(1, i0_3 + i0_0 + i0_1 + i0_2) yy = T.axis.spatial(112, i1_0 * 56 + i1_1 * 28 + i1_2 * 28 + i1_3) xx = T.axis.spatial(112, i2_0 * 16 + i2_1 * 8 + i2_2 * 2 + i2_3) ff = T.axis.spatial(64, i3_0 * 64 + i3_1 * 2 + i3_2 * 2 + i3_3) ry = T.axis.reduce(7, i4_1 + i4_0) rx = T.axis.reduce(7, i5_0 + i5_1) rc = T.axis.reduce(3, i6_0 * 3 + i6_1) T.reads(PaddedInput[nn, yy * 2 + ry, xx * 2 + rx, rc], kernel[ry, rx, rc, ff]) T.writes(Conv2dOutput[nn, yy, xx, ff]) T.block_attr({"meta_schedule.tiling_structure":"SSRSRS"}) with T.init(): Conv2dOutput[nn, yy, xx, ff] = T.float32(0) Conv2dOutput[nn, yy, xx, ff] = Conv2dOutput[nn, yy, xx, ff] + PaddedInput[nn, yy * 2 + ry, xx * 2 + rx, rc] * kernel[ry, rx, rc, ff] for ax0, ax1, ax2, ax3 in T.grid(1, 56, 16, 64): with T.block("compute"): i0 = T.axis.spatial(1, ax0) i1 = T.axis.spatial(112, i1_0 * 56 + ax1) i2 = T.axis.spatial(112, i2_0 * 16 + ax2) i3 = T.axis.spatial(64, ax3) T.reads(Conv2dOutput[i0, i1, i2, i3], bias[i3], bn_scale[i3], bn_offset[i3]) T.writes(compute[i0, i1, i2, i3]) compute[i0, i1, i2, i3] = T.max((Conv2dOutput[i0, i1, i2, i3] + bias[i3]) * bn_scale[i3] + bn_offset[i3], T.float32(0)) # fmt: on decision_0 = [ ("SamplePerfectTile", [1, 1, 1, 1]), ("SamplePerfectTile", [2, 2, 1, 28]), ("SamplePerfectTile", [7, 2, 4, 2]), ("SamplePerfectTile", [1, 32, 1, 2]), ("SamplePerfectTile", [7, 1]), ("SamplePerfectTile", [7, 1]), ("SamplePerfectTile", [1, 3]), ("SampleCategorical", 2), ("SampleComputeLocation", -2), ] decision_1 = [ ("SamplePerfectTile", [1, 1, 1, 1]), ("SamplePerfectTile", [2, 2, 1, 28]), ("SamplePerfectTile", [7, 2, 4, 2]), ("SamplePerfectTile", [1, 32, 1, 2]), ("SamplePerfectTile", [7, 1]), ("SamplePerfectTile", [7, 1]), ("SamplePerfectTile", [1, 3]), ("SampleCategorical", 3), ("SampleComputeLocation", 1), ] decision_2 = [ ("SamplePerfectTile", [1, 1, 1, 1]), ("SamplePerfectTile", [2, 2, 1, 28]), ("SamplePerfectTile", [7, 2, 4, 2]), ("SamplePerfectTile", [1, 32, 1, 2]), ("SamplePerfectTile", [7, 1]), ("SamplePerfectTile", [7, 1]), ("SamplePerfectTile", [1, 3]), ("SampleCategorical", 2), ("SampleComputeLocation", 1), ] mod = create_te_workload("CBR", 0) actual = _design_space(mod) check_sketches( mod, sketches=actual, expected_mods=[cbr_0, cbr_1, cbr_2], expected_decisions=[decision_0, decision_1, decision_2], ) def test_cpu_tbg(): # fmt: off @T.prim_func def tbg_0(query: T.Buffer[(1, 128, 12, 64), "float32"], value: T.Buffer[(1, 128, 12, 64), "float32"], C: T.Buffer[(1, 12, 128, 128), "float32"]) -> None: # function attr dict T.func_attr({"global_symbol": "main", "tir.noalias": True}) # body with T.block("root"): T.reads() T.writes() T.block_attr({"meta_schedule.parallel":288, "meta_schedule.unroll_explicit":64, "meta_schedule.vectorize":64}) query_T = T.alloc_buffer([1, 12, 128, 64], dtype="float32") value_T = T.alloc_buffer([1, 12, 64, 128], dtype="float32") C_global = T.alloc_buffer([1, 12, 128, 128], dtype="float32") for i0_0, i1_0, i2_0, i3_0, i0_1, i1_1, i2_1 in T.grid(1, 1, 1, 2, 1, 6, 2): for ax0, ax1, ax2, ax3 in T.grid(1, 2, 64, 64): with T.block("value_T"): b = T.axis.spatial(1, ax0) h = T.axis.spatial(12, i1_1 * 2 + ax1) d = T.axis.spatial(64, ax2) l = T.axis.spatial(128, i3_0 * 64 + ax3) T.reads(value[b, l, h, d]) T.writes(value_T[b, h, d, l]) value_T[b, h, d, l] = value[b, l, h, d] for ax0, ax1, ax2, ax3 in T.grid(1, 2, 64, 64): with T.block("query_T"): b = T.axis.spatial(1, ax0) h = T.axis.spatial(12, i1_1 * 2 + ax1) l = T.axis.spatial(128, i2_1 * 64 + ax2) d = T.axis.spatial(64, ax3) T.reads(query[b, l, h, d]) T.writes(query_T[b, h, l, d]) query_T[b, h, l, d] = query[b, l, h, d] for i3_1 in T.serial(8): for i4_0, i0_2, i1_2, i2_2, i3_2, i4_1, i0_3, i1_3, i2_3, i3_3 in T.grid(1, 1, 2, 2, 4, 64, 1, 1, 32, 2): with T.block("C"): b = T.axis.spatial(1, i0_1 + i0_2 + i0_3 + i0_0) h = T.axis.spatial(12, i1_0 * 12 + i1_1 * 2 + i1_2 + i1_3) i = T.axis.spatial(128, i2_0 * 128 + i2_1 * 64 + i2_2 * 32 + i2_3) j = T.axis.spatial(128, i3_0 * 64 + i3_1 * 8 + i3_2 * 2 + i3_3) k = T.axis.reduce(64, i4_0 * 64 + i4_1) T.reads(query_T[b, h, i, k], value_T[b, h, k, j]) T.writes(C_global[b, h, i, j]) T.block_attr({"meta_schedule.tiling_structure":"SSRSRS"}) with T.init(): C_global[b, h, i, j] = T.float32(0) C_global[b, h, i, j] = C_global[b, h, i, j] + query_T[b, h, i, k] * value_T[b, h, k, j] for ax0, ax1, ax2, ax3 in T.grid(1, 2, 64, 8): with T.block("C_global"): v0 = T.axis.spatial(1, ax0) v1 = T.axis.spatial(12, i1_1 * 2 + ax1) v2 = T.axis.spatial(128, i2_1 * 64 + ax2) v3 = T.axis.spatial(128, i3_0 * 64 + i3_1 * 8 + ax3) T.reads(C_global[v0, v1, v2, v3]) T.writes(C[v0, v1, v2, v3]) C[v0, v1, v2, v3] = C_global[v0, v1, v2, v3] @T.prim_func def tbg_1(query: T.Buffer[(1, 128, 12, 64), "float32"], value: T.Buffer[(1, 128, 12, 64), "float32"], C: T.Buffer[(1, 12, 128, 128), "float32"]) -> None: # function attr dict T.func_attr({"global_symbol": "main", "tir.noalias": True}) # body with T.block("root"): T.reads() T.writes() T.block_attr({"meta_schedule.parallel":288, "meta_schedule.unroll_explicit":64, "meta_schedule.vectorize":64}) query_T = T.alloc_buffer([1, 12, 128, 64], dtype="float32") value_T = T.alloc_buffer([1, 12, 64, 128], dtype="float32") C_global = T.alloc_buffer([1, 12, 128, 128], dtype="float32") for i0, i1, i2, i3 in T.grid(1, 12, 128, 64): with T.block("query_T"): b, h, l, d = T.axis.remap("SSSS", [i0, i1, i2, i3]) T.reads(query[b, l, h, d]) T.writes(query_T[b, h, l, d]) query_T[b, h, l, d] = query[b, l, h, d] for i0_0, i1_0, i2_0, i3_0 in T.grid(1, 1, 1, 2): for i0_1, i1_1, i2_1, i3_1, i4_0, i0_2, i1_2, i2_2, i3_2, i4_1 in T.grid(1, 6, 2, 8, 1, 1, 2, 2, 4, 64): for ax0, ax1, ax2, ax3 in T.grid(1, 1, 1, 2): with T.block("value_T"): b = T.axis.spatial(1, ax0) h = T.axis.spatial(12, i1_1 * 2 + i1_2 + ax1) d = T.axis.spatial(64, i4_1 + ax2) l = T.axis.spatial(128, i3_0 * 64 + i3_1 * 8 + i3_2 * 2 + ax3) T.reads(value[b, l, h, d]) T.writes(value_T[b, h, d, l]) value_T[b, h, d, l] = value[b, l, h, d] for i0_3, i1_3, i2_3, i3_3 in T.grid(1, 1, 32, 2): with T.block("C"): b = T.axis.spatial(1, i0_1 + i0_2 + i0_3 + i0_0) h = T.axis.spatial(12, i1_0 * 12 + i1_1 * 2 + i1_2 + i1_3) i = T.axis.spatial(128, i2_0 * 128 + i2_1 * 64 + i2_2 * 32 + i2_3) j = T.axis.spatial(128, i3_0 * 64 + i3_1 * 8 + i3_2 * 2 + i3_3) k = T.axis.reduce(64, i4_0 * 64 + i4_1) T.reads(query_T[b, h, i, k], value_T[b, h, k, j]) T.writes(C_global[b, h, i, j]) T.block_attr({"meta_schedule.tiling_structure":"SSRSRS"}) with T.init(): C_global[b, h, i, j] = T.float32(0) C_global[b, h, i, j] = C_global[b, h, i, j] + query_T[b, h, i, k] * value_T[b, h, k, j] for ax0, ax1, ax2, ax3 in T.grid(1, 12, 128, 64): with T.block("C_global"): v0, v1, v2 = T.axis.remap("SSS", [ax0, ax1, ax2]) v3 = T.axis.spatial(128, i3_0 * 64 + ax3) T.reads(C_global[v0, v1, v2, v3]) T.writes(C[v0, v1, v2, v3]) C[v0, v1, v2, v3] = C_global[v0, v1, v2, v3] @T.prim_func def tbg_2(query: T.Buffer[(1, 128, 12, 64), "float32"], value: T.Buffer[(1, 128, 12, 64), "float32"], C: T.Buffer[(1, 12, 128, 128), "float32"]) -> None: # function attr dict T.func_attr({"global_symbol": "main", "tir.noalias": True}) # body with T.block("root"): T.reads() T.writes() T.block_attr({"meta_schedule.parallel":288, "meta_schedule.unroll_explicit":512, "meta_schedule.vectorize":64}) value_T = T.alloc_buffer([1, 12, 64, 128], dtype="float32") for i0_0, i1_0, i2_0, i3_0, i0_1, i1_1, i2_1, i3_1 in T.grid(1, 1, 1, 2, 1, 6, 2, 8): for ax0, ax1, ax2, ax3 in T.grid(1, 2, 64, 8): with T.block("value_T"): b = T.axis.spatial(1, ax0) h = T.axis.spatial(12, i1_1 * 2 + ax1) d = T.axis.spatial(64, ax2) l = T.axis.spatial(128, i3_0 * 64 + i3_1 * 8 + ax3) T.reads(value[b, l, h, d]) T.writes(value_T[b, h, d, l]) value_T[b, h, d, l] = value[b, l, h, d] for i4_0, i0_2, i1_2, i2_2, i3_2, i4_1, i0_3, i1_3, i2_3, i3_3 in T.grid(1, 1, 2, 2, 4, 64, 1, 1, 32, 2): with T.block("C"): b = T.axis.spatial(1, i0_1 + i0_2 + i0_3 + i0_0) h = T.axis.spatial(12, i1_0 * 12 + i1_1 * 2 + i1_2 + i1_3) i = T.axis.spatial(128, i2_0 * 128 + i2_1 * 64 + i2_2 * 32 + i2_3) j = T.axis.spatial(128, i3_0 * 64 + i3_1 * 8 + i3_2 * 2 + i3_3) k = T.axis.reduce(64, i4_0 * 64 + i4_1) T.reads(query[b, i, h, k], value_T[b, h, k, j]) T.writes(C[b, h, i, j]) T.block_attr({"meta_schedule.tiling_structure":"SSRSRS"}) with T.init(): C[b, h, i, j] = T.float32(0) C[b, h, i, j] = C[b, h, i, j] + query[b, i, h, k] * value_T[b, h, k, j] # fmt: on decision_0 = [ ("SamplePerfectTile", [1, 1, 1, 1]), ("SamplePerfectTile", [1, 6, 2, 1]), ("SamplePerfectTile", [1, 2, 2, 32]), ("SamplePerfectTile", [2, 8, 4, 2]), ("SamplePerfectTile", [1, 64]), ("SampleCategorical", 2), ("SampleComputeLocation", 6), ("SampleComputeLocation", 6), ] decision_1 = [ ("SamplePerfectTile", [1, 1, 1, 1]), ("SamplePerfectTile", [1, 6, 2, 1]), ("SamplePerfectTile", [1, 2, 2, 32]), ("SamplePerfectTile", [2, 8, 4, 2]), ("SamplePerfectTile", [1, 64]), ("SampleCategorical", 2), ("SampleComputeLocation", 13), ("SampleComputeLocation", -1), ] decision_2 = [ ("SamplePerfectTile", [1, 1, 1, 1]), ("SamplePerfectTile", [1, 6, 2, 1]), ("SamplePerfectTile", [1, 2, 2, 32]), ("SamplePerfectTile", [2, 8, 4, 2]), ("SamplePerfectTile", [1, 64]), ("SampleCategorical", 3), ("SampleComputeLocation", 7), ("SampleComputeLocation", -2), ] mod = create_te_workload("TBG", 0) actual = _design_space(mod) check_sketches( mod, sketches=actual, expected_mods=[tbg_0, tbg_1, tbg_2], expected_decisions=[decision_0, decision_1, decision_2], ) if __name__ == "__main__": test_cpu_c1d() test_cpu_c2d() test_cpu_c3d() test_cpu_cap() test_cpu_dep() test_cpu_dil() test_cpu_gmm() test_cpu_grp() test_cpu_t2d() test_cpu_nrm() test_cpu_sfm() test_cpu_cbr() test_cpu_tbg()
https://github.com/zk-ml/tachikoma
tests/python/unittest/test_meta_schedule_space_cpu_winograd.py
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. """Tests for MetaSchedule search space on CPU""" from tvm import meta_schedule as ms from tvm.meta_schedule.testing.space_generation import ( check_sketches, generate_design_space, print_sketches, ) from tvm.meta_schedule.testing.te_workload import create_te_workload from tvm.script import tir as T from tvm.target import Target def _target(): return Target("aws/cpu/c5.9xlarge") def _design_space(mod): return generate_design_space( kind="llvm", mod=mod, target=_target(), types=ms.ScheduleRule, ) def test_cpu_nhwc(): # fmt: off @T.prim_func def cpu_nhwc_0(X: T.Buffer[(1, 14, 14, 128), "float32"], W: T.Buffer[(6, 6, 128, 128), "float32"], conv2d_winograd: T.Buffer[(1, 12, 12, 128), "float32"]) -> None: # function attr dict T.func_attr({"global_symbol": "main", "tir.noalias": True, "layout_free_buffers": [1]}) # body with T.block("root"): T.reads() T.writes() T.block_attr({"meta_schedule.parallel":288, "meta_schedule.unroll_explicit":64, "meta_schedule.vectorize":64}) data_pad = T.alloc_buffer([1, 16, 16, 128], dtype="float32") input_tile = T.alloc_buffer([6, 6, 9, 128], dtype="float32") data_pack = T.alloc_buffer([6, 6, 9, 128], dtype="float32") bgemm = T.alloc_buffer([6, 6, 9, 128], dtype="float32") inverse = T.alloc_buffer([4, 4, 9, 128], dtype="float32") bgemm_global = T.alloc_buffer([6, 6, 9, 128], dtype="float32") for i2_0 in T.serial(9): for ax0, ax1, ax2, ax3 in T.grid(1, 6, 6, 128): with T.block("data_pad"): i0 = T.axis.spatial(1, ax0) i1 = T.axis.spatial(16, i2_0 // 3 * 4 + ax1) i2 = T.axis.spatial(16, i2_0 % 3 * 4 + ax2) i3 = T.axis.spatial(128, ax3) T.reads(X[i0, i1, i2, i3]) T.writes(data_pad[i0, i1, i2, i3]) T.block_attr({"schedule_rule":"None"}) data_pad[i0, i1, i2, i3] = T.if_then_else(0 <= i1 and i1 < 14 and 0 <= i2 and i2 < 14, X[i0, i1, i2, i3], T.float32(0), dtype="float32") for i3_0 in T.serial(2): for ax0, ax1, ax2, ax3 in T.grid(6, 6, 1, 64): with T.block("input_tile"): eps, nu = T.axis.remap("SS", [ax0, ax1]) p = T.axis.spatial(9, i2_0 + ax2) ci = T.axis.spatial(128, i3_0 * 64 + ax3) T.reads(data_pad[p // 9, p % 9 // 3 * 4 + eps, p % 3 * 4 + nu, ci]) T.writes(input_tile[eps, nu, p, ci]) T.block_attr({"schedule_rule":"None"}) input_tile[eps, nu, p, ci] = data_pad[p // 9, p % 9 // 3 * 4 + eps, p % 3 * 4 + nu, ci] for i2_1, i3_1 in T.grid(1, 64): for i0 in T.unroll(6): for i1 in T.unroll(6): for i4 in T.unroll(6): for i5 in T.unroll(6): with T.block("data_pack"): eps, nu = T.axis.remap("SS", [i0, i1]) p = T.axis.spatial(9, i2_0 + i2_1) ci = T.axis.spatial(128, i3_0 * 64 + i3_1) r_a, r_b = T.axis.remap("RR", [i4, i5]) T.reads(input_tile[r_a, r_b, p, ci]) T.writes(data_pack[eps, nu, p, ci]) T.block_attr({"schedule_rule":"conv2d_nhwc_winograd_data_pack"}) with T.init(): data_pack[eps, nu, p, ci] = T.float32(0) data_pack[eps, nu, p, ci] = data_pack[eps, nu, p, ci] + input_tile[r_a, r_b, p, ci] * T.Select(r_a % 6 == 5 and eps % 6 == 5, T.float32(1), T.Select(r_a % 6 == 5 and eps % 6 == 4, T.float32(0), T.Select(r_a % 6 == 5 and eps % 6 == 3, T.float32(0), T.Select(r_a % 6 == 5 and eps % 6 == 2, T.float32(0), T.Select(r_a % 6 == 5 and eps % 6 == 1, T.float32(0), T.Select(r_a % 6 == 5 and eps % 6 == 0, T.float32(0), T.Select(r_a % 6 == 4 and eps % 6 == 5, T.float32(1.5), T.Select(r_a % 6 == 4 and eps % 6 == 4, T.float32(1), T.Select(r_a % 6 == 4 and eps % 6 == 3, T.float32(1), T.Select(r_a % 6 == 4 and eps % 6 == 2, T.float32(1), T.Select(r_a % 6 == 4 and eps % 6 == 1, T.float32(1), T.Select(r_a % 6 == 4 and eps % 6 == 0, T.float32(1), T.Select(r_a % 6 == 3 and eps % 6 == 5, T.float32(-2), T.Select(r_a % 6 == 3 and eps % 6 == 4, T.float32(-0.5), T.Select(r_a % 6 == 3 and eps % 6 == 3, T.float32(2), T.Select(r_a % 6 == 3 and eps % 6 == 2, T.float32(2.5), T.Select(r_a % 6 == 3 and eps % 6 == 1, T.float32(0.5), T.Select(r_a % 6 == 3 and eps % 6 == 0, T.float32(1.5), T.Select(r_a % 6 == 2 and eps % 6 == 5, T.float32(-1.5), T.Select(r_a % 6 == 2 and eps % 6 == 4, T.float32(-1), T.Select(r_a % 6 == 2 and eps % 6 == 3, T.float32(-1), T.Select(r_a % 6 == 2 and eps % 6 == 2, T.float32(0.5), T.Select(r_a % 6 == 2 and eps % 6 == 1, T.float32(-2.5), T.Select(r_a % 6 == 2 and eps % 6 == 0, T.float32(-2), T.Select(r_a % 6 == 1 and eps % 6 == 5, T.float32(1), T.Select(r_a % 6 == 1 and eps % 6 == 4, T.float32(0.5), T.Select(r_a % 6 == 1 and eps % 6 == 3, T.float32(-2), T.Select(r_a % 6 == 1 and eps % 6 == 2, T.float32(-1), T.Select(r_a % 6 == 1 and eps % 6 == 1, T.float32(1), T.Select(r_a % 6 == 1 and eps % 6 == 0, T.float32(-1.5), T.Select(r_a % 6 == 0 and eps % 6 == 5, T.float32(0), T.Select(r_a % 6 == 0 and eps % 6 == 4, T.float32(0), T.Select(r_a % 6 == 0 and eps % 6 == 3, T.float32(0), T.Select(r_a % 6 == 0 and eps % 6 == 2, T.float32(0), T.Select(r_a % 6 == 0 and eps % 6 == 1, T.float32(0), T.Select(r_a % 6 == 0 and eps % 6 == 0, T.float32(1), T.float32(0))))))))))))))))))))))))))))))))))))) * T.Select(r_b % 6 == 5 and nu % 6 == 5, T.float32(1), T.Select(r_b % 6 == 5 and nu % 6 == 4, T.float32(0), T.Select(r_b % 6 == 5 and nu % 6 == 3, T.float32(0), T.Select(r_b % 6 == 5 and nu % 6 == 2, T.float32(0), T.Select(r_b % 6 == 5 and nu % 6 == 1, T.float32(0), T.Select(r_b % 6 == 5 and nu % 6 == 0, T.float32(0), T.Select(r_b % 6 == 4 and nu % 6 == 5, T.float32(1.5), T.Select(r_b % 6 == 4 and nu % 6 == 4, T.float32(1), T.Select(r_b % 6 == 4 and nu % 6 == 3, T.float32(1), T.Select(r_b % 6 == 4 and nu % 6 == 2, T.float32(1), T.Select(r_b % 6 == 4 and nu % 6 == 1, T.float32(1), T.Select(r_b % 6 == 4 and nu % 6 == 0, T.float32(1), T.Select(r_b % 6 == 3 and nu % 6 == 5, T.float32(-2), T.Select(r_b % 6 == 3 and nu % 6 == 4, T.float32(-0.5), T.Select(r_b % 6 == 3 and nu % 6 == 3, T.float32(2), T.Select(r_b % 6 == 3 and nu % 6 == 2, T.float32(2.5), T.Select(r_b % 6 == 3 and nu % 6 == 1, T.float32(0.5), T.Select(r_b % 6 == 3 and nu % 6 == 0, T.float32(1.5), T.Select(r_b % 6 == 2 and nu % 6 == 5, T.float32(-1.5), T.Select(r_b % 6 == 2 and nu % 6 == 4, T.float32(-1), T.Select(r_b % 6 == 2 and nu % 6 == 3, T.float32(-1), T.Select(r_b % 6 == 2 and nu % 6 == 2, T.float32(0.5), T.Select(r_b % 6 == 2 and nu % 6 == 1, T.float32(-2.5), T.Select(r_b % 6 == 2 and nu % 6 == 0, T.float32(-2), T.Select(r_b % 6 == 1 and nu % 6 == 5, T.float32(1), T.Select(r_b % 6 == 1 and nu % 6 == 4, T.float32(0.5), T.Select(r_b % 6 == 1 and nu % 6 == 3, T.float32(-2), T.Select(r_b % 6 == 1 and nu % 6 == 2, T.float32(-1), T.Select(r_b % 6 == 1 and nu % 6 == 1, T.float32(1), T.Select(r_b % 6 == 1 and nu % 6 == 0, T.float32(-1.5), T.Select(r_b % 6 == 0 and nu % 6 == 5, T.float32(0), T.Select(r_b % 6 == 0 and nu % 6 == 4, T.float32(0), T.Select(r_b % 6 == 0 and nu % 6 == 3, T.float32(0), T.Select(r_b % 6 == 0 and nu % 6 == 2, T.float32(0), T.Select(r_b % 6 == 0 and nu % 6 == 1, T.float32(0), T.Select(r_b % 6 == 0 and nu % 6 == 0, T.float32(1), T.float32(0))))))))))))))))))))))))))))))))))))) for i0_0, i1_0, i2_0, i3_0, i0_1, i1_1, i2_1, i3_1 in T.grid(3, 2, 3, 1, 1, 1, 1, 1): for i4_0, i0_2, i1_2, i2_2, i3_2, i4_1, i0_3, i1_3, i2_3, i3_3 in T.grid(32, 1, 1, 1, 2, 4, 2, 3, 3, 64): with T.block("bgemm"): eps = T.axis.spatial(6, i0_0 * 2 + i0_1 * 2 + i0_2 * 2 + i0_3) nu = T.axis.spatial(6, i1_0 * 3 + i1_1 * 3 + i1_2 * 3 + i1_3) p = T.axis.spatial(9, i2_0 * 3 + i2_1 * 3 + i2_2 * 3 + i2_3) co = T.axis.spatial(128, i3_0 * 128 + i3_1 * 128 + i3_2 * 64 + i3_3) ci = T.axis.reduce(128, i4_0 * 4 + i4_1) T.reads(data_pack[eps, nu, p, ci], W[eps, nu, co, ci]) T.writes(bgemm_global[eps, nu, p, co]) T.block_attr({"meta_schedule.tiling_structure":"SSRSRS", "meta_schedule.write_cache_level":[2]}) with T.init(): bgemm_global[eps, nu, p, co] = T.float32(0) bgemm_global[eps, nu, p, co] = bgemm_global[eps, nu, p, co] + data_pack[eps, nu, p, ci] * W[eps, nu, co, ci] for ax0, ax1, ax2, ax3 in T.grid(2, 3, 3, 128): with T.block("bgemm_global"): v0 = T.axis.spatial(6, i0_0 * 2 + ax0) v1 = T.axis.spatial(6, i1_0 * 3 + ax1) v2 = T.axis.spatial(9, i2_0 * 3 + ax2) v3 = T.axis.spatial(128, ax3) T.reads(bgemm_global[v0, v1, v2, v3]) T.writes(bgemm[v0, v1, v2, v3]) bgemm[v0, v1, v2, v3] = bgemm_global[v0, v1, v2, v3] for i2_0, i3_0, i2_1, i3_1 in T.grid(3, 8, 3, 16): for i0 in T.unroll(4): for i1 in T.unroll(4): for i4 in T.unroll(6): for i5 in T.unroll(6): with T.block("inverse"): vh, vw = T.axis.remap("SS", [i0, i1]) p = T.axis.spatial(9, i2_0 * 3 + i2_1) co = T.axis.spatial(128, i3_0 * 16 + i3_1) r_a, r_b = T.axis.remap("RR", [i4, i5]) T.reads(bgemm[r_a, r_b, p, co]) T.writes(inverse[vh, vw, p, co]) T.block_attr({"schedule_rule":"conv2d_nhwc_winograd_inverse"}) with T.init(): inverse[vh, vw, p, co] = T.float32(0) inverse[vh, vw, p, co] = inverse[vh, vw, p, co] + bgemm[r_a, r_b, p, co] * T.Select(r_a % 6 == 5 and vh % 4 == 3, T.float32(1), T.Select(r_a % 6 == 5 and vh % 4 == 2, T.float32(0), T.Select(r_a % 6 == 5 and vh % 4 == 1, T.float32(0), T.Select(r_a % 6 == 5 and vh % 4 == 0, T.float32(0), T.Select(r_a % 6 == 4 and vh % 4 == 3, T.float32(-8), T.Select(r_a % 6 == 4 and vh % 4 == 2, T.float32(4), T.Select(r_a % 6 == 4 and vh % 4 == 1, T.float32(-2), T.Select(r_a % 6 == 4 and vh % 4 == 0, T.float32(1), T.Select(r_a % 6 == 3 and vh % 4 == 3, T.float32(0.125), T.Select(r_a % 6 == 3 and vh % 4 == 2, T.float32(0.25), T.Select(r_a % 6 == 3 and vh % 4 == 1, T.float32(0.5), T.Select(r_a % 6 == 3 and vh % 4 == 0, T.float32(1), T.Select(r_a % 6 == 2 and vh % 4 == 3, T.float32(1), T.Select(r_a % 6 == 2 and vh % 4 == 2, T.float32(1), T.Select(r_a % 6 == 2 and vh % 4 == 1, T.float32(1), T.Select(r_a % 6 == 2 and vh % 4 == 0, T.float32(1), T.Select(r_a % 6 == 1 and vh % 4 == 3, T.float32(-1), T.Select(r_a % 6 == 1 and vh % 4 == 2, T.float32(1), T.Select(r_a % 6 == 1 and vh % 4 == 1, T.float32(-1), T.Select(r_a % 6 == 1 and vh % 4 == 0, T.float32(1), T.Select(r_a % 6 == 0 and vh % 4 == 3, T.float32(0), T.Select(r_a % 6 == 0 and vh % 4 == 2, T.float32(0), T.Select(r_a % 6 == 0 and vh % 4 == 1, T.float32(0), T.Select(r_a % 6 == 0 and vh % 4 == 0, T.float32(1), T.float32(0))))))))))))))))))))))))) * T.Select(r_b % 6 == 5 and vw % 4 == 3, T.float32(1), T.Select(r_b % 6 == 5 and vw % 4 == 2, T.float32(0), T.Select(r_b % 6 == 5 and vw % 4 == 1, T.float32(0), T.Select(r_b % 6 == 5 and vw % 4 == 0, T.float32(0), T.Select(r_b % 6 == 4 and vw % 4 == 3, T.float32(-8), T.Select(r_b % 6 == 4 and vw % 4 == 2, T.float32(4), T.Select(r_b % 6 == 4 and vw % 4 == 1, T.float32(-2), T.Select(r_b % 6 == 4 and vw % 4 == 0, T.float32(1), T.Select(r_b % 6 == 3 and vw % 4 == 3, T.float32(0.125), T.Select(r_b % 6 == 3 and vw % 4 == 2, T.float32(0.25), T.Select(r_b % 6 == 3 and vw % 4 == 1, T.float32(0.5), T.Select(r_b % 6 == 3 and vw % 4 == 0, T.float32(1), T.Select(r_b % 6 == 2 and vw % 4 == 3, T.float32(1), T.Select(r_b % 6 == 2 and vw % 4 == 2, T.float32(1), T.Select(r_b % 6 == 2 and vw % 4 == 1, T.float32(1), T.Select(r_b % 6 == 2 and vw % 4 == 0, T.float32(1), T.Select(r_b % 6 == 1 and vw % 4 == 3, T.float32(-1), T.Select(r_b % 6 == 1 and vw % 4 == 2, T.float32(1), T.Select(r_b % 6 == 1 and vw % 4 == 1, T.float32(-1), T.Select(r_b % 6 == 1 and vw % 4 == 0, T.float32(1), T.Select(r_b % 6 == 0 and vw % 4 == 3, T.float32(0), T.Select(r_b % 6 == 0 and vw % 4 == 2, T.float32(0), T.Select(r_b % 6 == 0 and vw % 4 == 1, T.float32(0), T.Select(r_b % 6 == 0 and vw % 4 == 0, T.float32(1), T.float32(0))))))))))))))))))))))))) for i0, i1, i2, i3 in T.grid(1, 12, 12, 128): with T.block("conv2d_winograd"): n, h, w, co = T.axis.remap("SSSS", [i0, i1, i2, i3]) T.reads(inverse[h % 4, w % 4, n * 9 + h // 4 * 3 + w // 4, co]) T.writes(conv2d_winograd[n, h, w, co]) conv2d_winograd[n, h, w, co] = inverse[h % 4, w % 4, n * 9 + h // 4 * 3 + w // 4, co] # fmt: on decision_0 = [ ("SamplePerfectTile", [3, 3]), ("SamplePerfectTile", [8, 16]), ("SamplePerfectTile", [9, 1]), ("SamplePerfectTile", [2, 64]), ("SampleComputeLocation", 1), ("SampleComputeLocation", 0), ("SamplePerfectTile", [3, 1, 1, 2]), ("SamplePerfectTile", [2, 1, 1, 3]), ("SamplePerfectTile", [3, 1, 1, 3]), ("SamplePerfectTile", [1, 1, 2, 64]), ("SamplePerfectTile", [32, 4]), ("SampleCategorical", 2), ] with _target(): mod = create_te_workload("C2D_WIN_NHWC", 0) actual = _design_space(mod) check_sketches( mod, sketches=actual, expected_mods=[cpu_nhwc_0], expected_decisions=[decision_0], ) if __name__ == "__main__": test_cpu_nhwc()
https://github.com/zk-ml/tachikoma
tests/python/unittest/test_meta_schedule_space_cuda.py
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. """Tests for MetaSchedule search space on CUDA""" from tvm import meta_schedule as ms from tvm.meta_schedule.testing.space_generation import ( check_sketches, generate_design_space, print_sketches, ) from tvm.meta_schedule.testing.te_workload import create_te_workload from tvm.script import tir as T from tvm.target import Target def _target(): return Target("nvidia/geforce-rtx-3070") def _design_space(mod): return generate_design_space( kind="cuda", mod=mod, target=_target(), types=ms.ScheduleRule, ) def test_cuda_c1d(): # fmt: off @T.prim_func def c1d_0(inputs: T.Buffer[(1, 256, 64), "float32"], weight: T.Buffer[(3, 64, 128), "float32"], conv1d_nlc: T.Buffer[(1, 128, 128), "float32"]) -> None: # function attr dict T.func_attr({"global_symbol": "main", "tir.noalias": True}) # body with T.block("root"): T.reads() T.writes() T.block_attr({"meta_schedule.unroll_explicit":16}) conv1d_nlc_local = T.alloc_buffer([1, 128, 128], dtype="float32", scope="local") PadInput_shared = T.alloc_buffer([1, 258, 64], dtype="float32", scope="shared") weight_shared = T.alloc_buffer([3, 64, 128], dtype="float32", scope="shared") for i0_0_i1_0_i2_0_fused in T.thread_binding(4, thread="blockIdx.x"): for i0_1_i1_1_i2_1_fused in T.thread_binding(16, thread="vthread.x"): for i0_2_i1_2_i2_2_fused in T.thread_binding(4, thread="threadIdx.x"): for i3_0, i4_0 in T.grid(1, 16): for ax0_ax1_ax2_fused in T.serial(260): with T.block("PadInput_shared"): v0 = T.axis.spatial(1, 0) v1 = T.axis.spatial(258, i0_0_i1_0_i2_0_fused * 64 + ax0_ax1_ax2_fused // 4) v2 = T.axis.spatial(64, i4_0 * 4 + ax0_ax1_ax2_fused % 4) T.reads(inputs[v0, v1 - 1, v2]) T.writes(PadInput_shared[v0, v1, v2]) T.block_attr({"meta_schedule.cooperative_fetch":4}) PadInput_shared[v0, v1, v2] = T.if_then_else(1 <= v1 and v1 < 257, inputs[v0, v1 - 1, v2], T.float32(0), dtype="float32") for ax0_ax1_ax2_fused in T.serial(1536): with T.block("weight_shared"): v0 = T.axis.spatial(3, ax0_ax1_ax2_fused // 512) v1 = T.axis.spatial(64, i4_0 * 4 + ax0_ax1_ax2_fused % 512 // 128) v2 = T.axis.spatial(128, ax0_ax1_ax2_fused % 128) T.reads(weight[v0, v1, v2]) T.writes(weight_shared[v0, v1, v2]) T.block_attr({"meta_schedule.cooperative_fetch":3}) weight_shared[v0, v1, v2] = weight[v0, v1, v2] for i3_1, i4_1, i0_3, i1_3, i2_3, i3_2, i4_2, i0_4, i1_4, i2_4 in T.grid(1, 2, 1, 1, 2, 3, 2, 1, 4, 8): with T.block("conv1d_nlc"): n = T.axis.spatial(1, i0_4 + i0_3) l = T.axis.spatial(128, i0_0_i1_0_i2_0_fused * 32 + i0_1_i1_1_i2_1_fused // 2 * 4 + i1_3 * 4 + i1_4) co = T.axis.spatial(128, i0_1_i1_1_i2_1_fused % 2 * 64 + i0_2_i1_2_i2_2_fused * 16 + i2_3 * 8 + i2_4) rl = T.axis.reduce(3, i3_0 * 3 + i3_1 * 3 + i3_2) rc = T.axis.reduce(64, i4_0 * 4 + i4_1 * 2 + i4_2) T.reads(PadInput_shared[n, l * 2 + rl, co // 128 * 64 + rc], weight_shared[rl, rc, co]) T.writes(conv1d_nlc_local[n, l, co]) T.block_attr({"meta_schedule.thread_extent_high_inclusive":1024, "meta_schedule.thread_extent_low_inclusive":32, "meta_schedule.tiling_structure":"SSSRRSRS"}) with T.init(): conv1d_nlc_local[n, l, co] = T.float32(0) conv1d_nlc_local[n, l, co] = conv1d_nlc_local[n, l, co] + PadInput_shared[n, l * 2 + rl, co // 128 * 64 + rc] * weight_shared[rl, rc, co] for ax0, ax1, ax2 in T.grid(1, 4, 16): with T.block("conv1d_nlc_local"): v0 = T.axis.spatial(1, ax0) v1 = T.axis.spatial(128, i0_0_i1_0_i2_0_fused * 32 + i0_1_i1_1_i2_1_fused // 2 * 4 + ax1) v2 = T.axis.spatial(128, i0_1_i1_1_i2_1_fused % 2 * 64 + i0_2_i1_2_i2_2_fused * 16 + ax2) T.reads(conv1d_nlc_local[v0, v1, v2]) T.writes(conv1d_nlc[v0, v1, v2]) conv1d_nlc[v0, v1, v2] = conv1d_nlc_local[v0, v1, v2] # fmt: on decision_0 = [ ("SamplePerfectTile", [1, 1, 1, 1, 1]), ("SamplePerfectTile", [4, 8, 1, 1, 4]), ("SamplePerfectTile", [1, 2, 4, 2, 8]), ("SamplePerfectTile", [1, 1, 3]), ("SamplePerfectTile", [16, 2, 2]), ("SampleCategorical", 3), ("SampleCategorical", 2), ("SampleCategorical", 1), ] mod = create_te_workload("C1D", 0) actual = _design_space(mod) check_sketches( mod, sketches=actual, expected_mods=[c1d_0], expected_decisions=[decision_0], ) def test_cuda_c2d(): # fmt: off @T.prim_func def c2d_0(inputs: T.Buffer[(1, 224, 224, 3), "float32"], weight: T.Buffer[(7, 7, 3, 64), "float32"], conv2d_nhwc: T.Buffer[(1, 112, 112, 64), "float32"]) -> None: T.func_attr({"global_symbol": "main", "tir.noalias": True}) with T.block("root"): T.reads() T.writes() T.block_attr({"meta_schedule.unroll_explicit":16}) conv2d_nhwc_local = T.alloc_buffer([1, 112, 112, 64], dtype="float32", scope="local") PadInput_shared = T.alloc_buffer([1, 230, 230, 3], dtype="float32", scope="shared") weight_shared = T.alloc_buffer([7, 7, 3, 64], dtype="float32", scope="shared") for i0_0_i1_0_i2_0_i3_0_fused in T.thread_binding(16, thread="blockIdx.x"): for i0_1_i1_1_i2_1_i3_1_fused in T.thread_binding(56, thread="vthread.x"): for i0_2_i1_2_i2_2_i3_2_fused in T.thread_binding(14, thread="threadIdx.x"): for i4_0, i5_0, i6_0 in T.grid(1, 1, 1): for ax0_ax1_ax2_ax3_fused in T.serial(80379): with T.block("PadInput_shared"): v0 = T.axis.spatial(1, 0) v1 = T.axis.spatial(230, ax0_ax1_ax2_ax3_fused // 351) v2 = T.axis.spatial(230, i0_0_i1_0_i2_0_i3_0_fused // 8 * 112 + ax0_ax1_ax2_ax3_fused % 351 // 3) v3 = T.axis.spatial(3, ax0_ax1_ax2_ax3_fused % 3) T.reads(inputs[v0, v1 - 3, v2 - 3, v3]) T.writes(PadInput_shared[v0, v1, v2, v3]) T.block_attr({"meta_schedule.cooperative_fetch":2}) PadInput_shared[v0, v1, v2, v3] = T.if_then_else(3 <= v1 and v1 < 227 and 3 <= v2 and v2 < 227, inputs[v0, v1 - 3, v2 - 3, v3], T.float32(0), dtype="float32") for ax0_ax1_ax2_ax3_fused in T.serial(1176): with T.block("weight_shared"): v0 = T.axis.spatial(7, ax0_ax1_ax2_ax3_fused // 168) v1 = T.axis.spatial(7, ax0_ax1_ax2_ax3_fused % 168 // 24) v2 = T.axis.spatial(3, ax0_ax1_ax2_ax3_fused % 24 // 8) v3 = T.axis.spatial(64, i0_0_i1_0_i2_0_i3_0_fused % 8 * 8 + ax0_ax1_ax2_ax3_fused % 8) T.reads(weight[v0, v1, v2, v3]) T.writes(weight_shared[v0, v1, v2, v3]) T.block_attr({"meta_schedule.cooperative_fetch":4}) weight_shared[v0, v1, v2, v3] = weight[v0, v1, v2, v3] for i4_1, i5_1, i6_1, i0_3, i1_3, i2_3, i3_3, i4_2, i5_2, i6_2, i0_4, i1_4, i2_4, i3_4 in T.grid(1, 7, 1, 1, 8, 4, 1, 7, 1, 3, 1, 1, 1, 2): with T.block("conv2d_nhwc"): n = T.axis.spatial(1, i0_3 + i0_4) h = T.axis.spatial(112, i1_4 + i0_2_i1_2_i2_2_i3_2_fused * 8 + i1_3) w = T.axis.spatial(112, i0_0_i1_0_i2_0_i3_0_fused // 8 * 56 + i0_1_i1_1_i2_1_i3_1_fused // 4 * 4 + i2_3 + i2_4) co = T.axis.spatial(64, i0_0_i1_0_i2_0_i3_0_fused % 8 * 8 + i0_1_i1_1_i2_1_i3_1_fused % 4 * 2 + i3_3 * 2 + i3_4) rh = T.axis.reduce(7, i4_0 * 7 + i4_1 * 7 + i4_2) rw = T.axis.reduce(7, i5_2 + i5_0 * 7 + i5_1) rc = T.axis.reduce(3, i6_0 * 3 + i6_1 * 3 + i6_2) T.reads(PadInput_shared[n, h * 2 + rh, w * 2 + rw, co // 64 * 3 + rc], weight_shared[rh, rw, rc, co]) T.writes(conv2d_nhwc_local[n, h, w, co]) T.block_attr({"meta_schedule.thread_extent_high_inclusive":1024, "meta_schedule.thread_extent_low_inclusive":32, "meta_schedule.tiling_structure":"SSSRRSRS"}) with T.init(): conv2d_nhwc_local[n, h, w, co] = T.float32(0) conv2d_nhwc_local[n, h, w, co] = conv2d_nhwc_local[n, h, w, co] + PadInput_shared[n, h * 2 + rh, w * 2 + rw, co // 64 * 3 + rc] * weight_shared[rh, rw, rc, co] for ax0, ax1, ax2, ax3 in T.grid(1, 8, 4, 2): with T.block("conv2d_nhwc_local"): v0 = T.axis.spatial(1, ax0) v1 = T.axis.spatial(112, i0_2_i1_2_i2_2_i3_2_fused * 8 + ax1) v2 = T.axis.spatial(112, i0_0_i1_0_i2_0_i3_0_fused // 8 * 56 + i0_1_i1_1_i2_1_i3_1_fused // 4 * 4 + ax2) v3 = T.axis.spatial(64, i0_0_i1_0_i2_0_i3_0_fused % 8 * 8 + i0_1_i1_1_i2_1_i3_1_fused % 4 * 2 + ax3) T.reads(conv2d_nhwc_local[v0, v1, v2, v3]) T.writes(conv2d_nhwc[v0, v1, v2, v3]) conv2d_nhwc[v0, v1, v2, v3] = conv2d_nhwc_local[v0, v1, v2, v3] # fmt: on decision_0 = [ ("SamplePerfectTile", [1, 1, 1, 1, 1]), ("SamplePerfectTile", [1, 1, 14, 8, 1]), ("SamplePerfectTile", [2, 14, 1, 4, 1]), ("SamplePerfectTile", [8, 4, 1, 1, 2]), ("SamplePerfectTile", [1, 1, 7]), ("SamplePerfectTile", [1, 7, 1]), ("SamplePerfectTile", [1, 1, 3]), ("SampleCategorical", 1), ("SampleCategorical", 3), ("SampleCategorical", 1), ] mod = create_te_workload("C2D", 0) actual = _design_space(mod) check_sketches( mod, sketches=actual, expected_mods=[c2d_0], expected_decisions=[decision_0], ) def test_cuda_c3d(): # fmt: off @T.prim_func def c3d_0(inputs: T.Buffer[(1, 16, 224, 224, 3), "float32"], weight: T.Buffer[(7, 7, 7, 3, 64), "float32"], conv3d_ndhwc: T.Buffer[(1, 8, 112, 112, 64), "float32"]) -> None: T.func_attr({"global_symbol": "main", "tir.noalias": True}) with T.block("root"): T.reads() T.writes() T.block_attr({"meta_schedule.unroll_explicit":16}) conv3d_ndhwc_local = T.alloc_buffer([1, 8, 112, 112, 64], dtype="float32", scope="local") PadInput_shared = T.alloc_buffer([1, 22, 230, 230, 3], dtype="float32", scope="shared") weight_shared = T.alloc_buffer([7, 7, 7, 3, 64], dtype="float32", scope="shared") for i0_0_i1_0_i2_0_i3_0_i4_0_fused in T.thread_binding(2, thread="blockIdx.x"): for i0_1_i1_1_i2_1_i3_1_i4_1_fused in T.thread_binding(8, thread="vthread.x"): for i0_2_i1_2_i2_2_i3_2_i4_2_fused in T.thread_binding(392, thread="threadIdx.x"): for i5_0, i6_0, i7_0, i8_0 in T.grid(1, 1, 1, 1): for ax0_ax1_ax2_ax3_ax4_fused in T.serial(1687959): with T.block("PadInput_shared"): v0 = T.axis.spatial(1, 0) v1 = T.axis.spatial(22, ax0_ax1_ax2_ax3_ax4_fused // 80379) v2 = T.axis.spatial(230, ax0_ax1_ax2_ax3_ax4_fused % 80379 // 351) v3 = T.axis.spatial(230, i0_0_i1_0_i2_0_i3_0_i4_0_fused * 112 + ax0_ax1_ax2_ax3_ax4_fused % 351 // 3) v4 = T.axis.spatial(3, ax0_ax1_ax2_ax3_ax4_fused % 3) T.reads(inputs[v0, v1 - 3, v2 - 3, v3 - 3, v4]) T.writes(PadInput_shared[v0, v1, v2, v3, v4]) T.block_attr({"meta_schedule.cooperative_fetch":4}) PadInput_shared[v0, v1, v2, v3, v4] = T.if_then_else(3 <= v1 and v1 < 19 and 3 <= v2 and v2 < 227 and 3 <= v3 and v3 < 227, inputs[v0, v1 - 3, v2 - 3, v3 - 3, v4], T.float32(0), dtype="float32") for ax0_ax1_ax2_ax3_ax4_fused in T.serial(65856): with T.block("weight_shared"): v0 = T.axis.spatial(7, ax0_ax1_ax2_ax3_ax4_fused // 9408) v1 = T.axis.spatial(7, ax0_ax1_ax2_ax3_ax4_fused % 9408 // 1344) v2 = T.axis.spatial(7, ax0_ax1_ax2_ax3_ax4_fused % 1344 // 192) v3 = T.axis.spatial(3, ax0_ax1_ax2_ax3_ax4_fused % 192 // 64) v4 = T.axis.spatial(64, ax0_ax1_ax2_ax3_ax4_fused % 64) T.reads(weight[v0, v1, v2, v3, v4]) T.writes(weight_shared[v0, v1, v2, v3, v4]) T.block_attr({"meta_schedule.cooperative_fetch":3}) weight_shared[v0, v1, v2, v3, v4] = weight[v0, v1, v2, v3, v4] for i5_1, i6_1, i7_1, i8_1, i0_3, i1_3, i2_3, i3_3, i4_3, i5_2, i6_2, i7_2, i8_2, i0_4, i1_4, i2_4, i3_4, i4_4 in T.grid(7, 7, 1, 3, 1, 2, 2, 1, 32, 1, 1, 7, 1, 1, 1, 2, 4, 1): with T.block("conv3d_ndhwc"): n = T.axis.spatial(1, i0_4 + i0_3) d = T.axis.spatial(8, i1_4 + i0_2_i1_2_i2_2_i3_2_i4_2_fused // 98 * 2 + i1_3) h = T.axis.spatial(112, i0_1_i1_1_i2_1_i3_1_i4_1_fused // 2 * 28 + i0_2_i1_2_i2_2_i3_2_i4_2_fused % 98 // 14 * 4 + i2_3 * 2 + i2_4) w = T.axis.spatial(112, i0_0_i1_0_i2_0_i3_0_i4_0_fused * 56 + i0_1_i1_1_i2_1_i3_1_i4_1_fused % 2 * 28 + i0_2_i1_2_i2_2_i3_2_i4_2_fused % 14 // 2 * 4 + i3_3 * 4 + i3_4) co = T.axis.spatial(64, i0_2_i1_2_i2_2_i3_2_i4_2_fused % 2 * 32 + i4_3 + i4_4) rd = T.axis.reduce(7, i5_2 + i5_0 * 7 + i5_1) rh = T.axis.reduce(7, i6_0 * 7 + i6_1 + i6_2) rw = T.axis.reduce(7, i7_0 * 7 + i7_1 * 7 + i7_2) rc = T.axis.reduce(3, i8_0 * 3 + i8_1 + i8_2) T.reads(PadInput_shared[n, d * 2 + rd, h * 2 + rh, w * 2 + rw, co // 64 * 3 + rc], weight_shared[rd, rh, rw, rc, co]) T.writes(conv3d_ndhwc_local[n, d, h, w, co]) T.block_attr({"meta_schedule.thread_extent_high_inclusive":1024, "meta_schedule.thread_extent_low_inclusive":32, "meta_schedule.tiling_structure":"SSSRRSRS"}) with T.init(): conv3d_ndhwc_local[n, d, h, w, co] = T.float32(0) conv3d_ndhwc_local[n, d, h, w, co] = conv3d_ndhwc_local[n, d, h, w, co] + PadInput_shared[n, d * 2 + rd, h * 2 + rh, w * 2 + rw, co // 64 * 3 + rc] * weight_shared[rd, rh, rw, rc, co] for ax0, ax1, ax2, ax3, ax4 in T.grid(1, 2, 4, 4, 32): with T.block("conv3d_ndhwc_local"): v0 = T.axis.spatial(1, ax0) v1 = T.axis.spatial(8, i0_2_i1_2_i2_2_i3_2_i4_2_fused // 98 * 2 + ax1) v2 = T.axis.spatial(112, i0_1_i1_1_i2_1_i3_1_i4_1_fused // 2 * 28 + i0_2_i1_2_i2_2_i3_2_i4_2_fused % 98 // 14 * 4 + ax2) v3 = T.axis.spatial(112, i0_0_i1_0_i2_0_i3_0_i4_0_fused * 56 + i0_1_i1_1_i2_1_i3_1_i4_1_fused % 2 * 28 + i0_2_i1_2_i2_2_i3_2_i4_2_fused % 14 // 2 * 4 + ax3) v4 = T.axis.spatial(64, i0_2_i1_2_i2_2_i3_2_i4_2_fused % 2 * 32 + ax4) T.reads(conv3d_ndhwc_local[v0, v1, v2, v3, v4]) T.writes(conv3d_ndhwc[v0, v1, v2, v3, v4]) conv3d_ndhwc[v0, v1, v2, v3, v4] = conv3d_ndhwc_local[v0, v1, v2, v3, v4] # fmt: on decision_0 = [ ("SamplePerfectTile", [1, 1, 1, 1, 1]), ("SamplePerfectTile", [1, 1, 4, 2, 1]), ("SamplePerfectTile", [1, 4, 7, 2, 2]), ("SamplePerfectTile", [2, 2, 7, 1, 4]), ("SamplePerfectTile", [1, 1, 2, 32, 1]), ("SamplePerfectTile", [1, 7, 1]), ("SamplePerfectTile", [1, 7, 1]), ("SamplePerfectTile", [1, 1, 7]), ("SamplePerfectTile", [1, 3, 1]), ("SampleCategorical", 3), ("SampleCategorical", 2), ("SampleCategorical", 1), ] mod = create_te_workload("C3D", 0) actual = _design_space(mod) check_sketches( mod, sketches=actual, expected_mods=[c3d_0], expected_decisions=[decision_0], ) def test_cuda_cap(): # fmt: off @T.prim_func def cap_0(inputs: T.Buffer[(1, 16, 16, 4, 4, 32), "float32"], weight: T.Buffer[(3, 3, 4, 4, 32, 32), "float32"], conv2d_capsule_nhwijc: T.Buffer[(1, 8, 8, 4, 4, 32), "float32"]) -> None: # function attr dict T.func_attr({"global_symbol": "main", "tir.noalias": True}) # body with T.block("root"): T.reads() T.writes() T.block_attr({"meta_schedule.unroll_explicit":64}) conv2d_capsule_nhwijc_local = T.alloc_buffer([1, 8, 8, 4, 4, 32], dtype="float32", scope="local") PadInput_shared = T.alloc_buffer([1, 18, 18, 4, 4, 32], dtype="float32", scope="shared") weight_shared = T.alloc_buffer([3, 3, 4, 4, 32, 32], dtype="float32", scope="shared") for i0_0_i1_0_i2_0_i3_0_i4_0_i5_0_fused in T.thread_binding(256, thread="blockIdx.x"): for i0_1_i1_1_i2_1_i3_1_i4_1_i5_1_fused in T.thread_binding(1, thread="vthread.x"): for i0_2_i1_2_i2_2_i3_2_i4_2_i5_2_fused in T.thread_binding(4, thread="threadIdx.x"): for i6_0, i7_0, i8_0, i9_0 in T.grid(3, 3, 2, 8): for ax0_ax1_ax2_ax3_ax4_ax5_fused in T.serial(48): with T.block("PadInput_shared"): v0 = T.axis.spatial(1, 0) v1 = T.axis.spatial(18, i0_0_i1_0_i2_0_i3_0_i4_0_i5_0_fused // 64 * 4 + i6_0 + ax0_ax1_ax2_ax3_ax4_ax5_fused % 48 // 16) v2 = T.axis.spatial(18, i0_0_i1_0_i2_0_i3_0_i4_0_i5_0_fused % 64 // 8 * 2 + i7_0 + 0) v3 = T.axis.spatial(4, i0_0_i1_0_i2_0_i3_0_i4_0_i5_0_fused % 8 // 4 * 2 + ax0_ax1_ax2_ax3_ax4_ax5_fused % 16 // 8) v4 = T.axis.spatial(4, i8_0 * 2 + ax0_ax1_ax2_ax3_ax4_ax5_fused % 8 // 4) v5 = T.axis.spatial(32, i9_0 * 4 + ax0_ax1_ax2_ax3_ax4_ax5_fused % 4) T.reads(inputs[v0, v1 - 1, v2 - 1, v3, v4, v5]) T.writes(PadInput_shared[v0, v1, v2, v3, v4, v5]) T.block_attr({"meta_schedule.cooperative_fetch":2}) PadInput_shared[v0, v1, v2, v3, v4, v5] = T.if_then_else(1 <= v1 and v1 < 17 and 1 <= v2 and v2 < 17, inputs[v0, v1 - 1, v2 - 1, v3, v4, v5], T.float32(0), dtype="float32") for ax0_ax1_ax2_ax3_ax4_ax5_fused in T.serial(256): with T.block("weight_shared"): v0, v1 = T.axis.remap("SS", [i6_0, i7_0]) v2 = T.axis.spatial(4, i8_0 * 2 + ax0_ax1_ax2_ax3_ax4_ax5_fused // 128) v3 = T.axis.spatial(4, ax0_ax1_ax2_ax3_ax4_ax5_fused % 128 // 32) v4 = T.axis.spatial(32, i9_0 * 4 + ax0_ax1_ax2_ax3_ax4_ax5_fused % 32 // 8) v5 = T.axis.spatial(32, i0_0_i1_0_i2_0_i3_0_i4_0_i5_0_fused % 4 * 8 + ax0_ax1_ax2_ax3_ax4_ax5_fused % 8) T.reads(weight[v0, v1, v2, v3, v4, v5]) T.writes(weight_shared[v0, v1, v2, v3, v4, v5]) T.block_attr({"meta_schedule.cooperative_fetch":4}) weight_shared[v0, v1, v2, v3, v4, v5] = weight[v0, v1, v2, v3, v4, v5] for i6_1, i7_1, i8_1, i9_1, i0_3, i1_3, i2_3, i3_3, i4_3, i5_3, i6_2, i7_2, i8_2, i9_2, i0_4, i1_4, i2_4, i3_4, i4_4, i5_4 in T.grid(1, 1, 1, 4, 1, 2, 1, 1, 1, 1, 1, 1, 2, 1, 1, 1, 1, 1, 2, 8): with T.block("conv2d_capsule_nhwijc"): n = T.axis.spatial(1, i0_4 + i0_3) h = T.axis.spatial(8, i0_0_i1_0_i2_0_i3_0_i4_0_i5_0_fused // 64 * 2 + i1_3 + i1_4) w = T.axis.spatial(8, i2_3 + i2_4 + i0_0_i1_0_i2_0_i3_0_i4_0_i5_0_fused % 64 // 8) cap_i = T.axis.spatial(4, i3_3 + i3_4 + i0_0_i1_0_i2_0_i3_0_i4_0_i5_0_fused % 8 // 4 * 2 + i0_2_i1_2_i2_2_i3_2_i4_2_i5_2_fused // 2) cap_j = T.axis.spatial(4, i0_2_i1_2_i2_2_i3_2_i4_2_i5_2_fused % 2 * 2 + i4_3 * 2 + i4_4) co = T.axis.spatial(32, i0_0_i1_0_i2_0_i3_0_i4_0_i5_0_fused % 4 * 8 + i5_3 * 8 + i5_4) rh = T.axis.reduce(3, i6_1 + i6_2 + i6_0) rw = T.axis.reduce(3, i7_0 + i7_1 + i7_2) cap_k = T.axis.reduce(4, i8_0 * 2 + i8_1 * 2 + i8_2) rc = T.axis.reduce(32, i9_0 * 4 + i9_1 + i9_2) T.reads(PadInput_shared[n, h * 2 + rh, w * 2 + rw, cap_i, cap_k, rc], weight_shared[rh, rw, cap_k, cap_j, rc, co]) T.writes(conv2d_capsule_nhwijc_local[n, h, w, cap_i, cap_j, co]) T.block_attr({"meta_schedule.thread_extent_high_inclusive":1024, "meta_schedule.thread_extent_low_inclusive":32, "meta_schedule.tiling_structure":"SSSRRSRS"}) with T.init(): conv2d_capsule_nhwijc_local[n, h, w, cap_i, cap_j, co] = T.float32(0) conv2d_capsule_nhwijc_local[n, h, w, cap_i, cap_j, co] = conv2d_capsule_nhwijc_local[n, h, w, cap_i, cap_j, co] + PadInput_shared[n, h * 2 + rh, w * 2 + rw, cap_i, cap_k, rc] * weight_shared[rh, rw, cap_k, cap_j, rc, co] for ax0, ax1, ax2, ax3, ax4, ax5 in T.grid(1, 2, 1, 1, 2, 8): with T.block("conv2d_capsule_nhwijc_local"): v0 = T.axis.spatial(1, ax0) v1 = T.axis.spatial(8, i0_0_i1_0_i2_0_i3_0_i4_0_i5_0_fused // 64 * 2 + ax1) v2 = T.axis.spatial(8, i0_0_i1_0_i2_0_i3_0_i4_0_i5_0_fused % 64 // 8 + ax2) v3 = T.axis.spatial(4, i0_0_i1_0_i2_0_i3_0_i4_0_i5_0_fused % 8 // 4 * 2 + i0_2_i1_2_i2_2_i3_2_i4_2_i5_2_fused // 2 + ax3) v4 = T.axis.spatial(4, i0_2_i1_2_i2_2_i3_2_i4_2_i5_2_fused % 2 * 2 + ax4) v5 = T.axis.spatial(32, i0_0_i1_0_i2_0_i3_0_i4_0_i5_0_fused % 4 * 8 + ax5) T.reads(conv2d_capsule_nhwijc_local[v0, v1, v2, v3, v4, v5]) T.writes(conv2d_capsule_nhwijc[v0, v1, v2, v3, v4, v5]) conv2d_capsule_nhwijc[v0, v1, v2, v3, v4, v5] = conv2d_capsule_nhwijc_local[v0, v1, v2, v3, v4, v5] # fmt: on decision_0 = [ ("SamplePerfectTile", [1, 1, 1, 1, 1]), ("SamplePerfectTile", [4, 1, 1, 2, 1]), ("SamplePerfectTile", [8, 1, 1, 1, 1]), ("SamplePerfectTile", [2, 1, 2, 1, 1]), ("SamplePerfectTile", [1, 1, 2, 1, 2]), ("SamplePerfectTile", [4, 1, 1, 1, 8]), ("SamplePerfectTile", [3, 1, 1]), ("SamplePerfectTile", [3, 1, 1]), ("SamplePerfectTile", [2, 1, 2]), ("SamplePerfectTile", [8, 4, 1]), ("SampleCategorical", 1), ("SampleCategorical", 3), ("SampleCategorical", 2), ] mod = create_te_workload("CAP", 0) actual = _design_space(mod) check_sketches( mod, sketches=actual, expected_mods=[cap_0], expected_decisions=[decision_0], ) def test_cuda_dep(): # fmt: off @T.prim_func def dep_0(placeholder: T.Buffer[(1, 112, 112, 32), "float32"], placeholder_1: T.Buffer[(1, 3, 3, 32), "float32"], depth_conv2d_nhwc: T.Buffer[(1, 112, 112, 32), "float32"]) -> None: # function attr dict T.func_attr({"global_symbol": "main", "tir.noalias": True}) # body with T.block("root"): T.reads() T.writes() T.block_attr({"meta_schedule.unroll_explicit":16}) depth_conv2d_nhwc_local = T.alloc_buffer([1, 112, 112, 32], dtype="float32", scope="local") PadInput_shared = T.alloc_buffer([1, 114, 114, 32], dtype="float32", scope="shared") placeholder_shared = T.alloc_buffer([1, 3, 3, 32], dtype="float32", scope="shared") for i0_0_i1_0_i2_0_i3_0_fused in T.thread_binding(1, thread="blockIdx.x"): for i0_1_i1_1_i2_1_i3_1_fused in T.thread_binding(8, thread="vthread.x"): for i0_2_i1_2_i2_2_i3_2_fused in T.thread_binding(14, thread="threadIdx.x"): for i4_0, i5_0 in T.grid(1, 1): for ax0_ax1_ax2_ax3_fused in T.serial(415872): with T.block("PadInput_shared"): v0 = T.axis.spatial(1, 0) v1 = T.axis.spatial(114, ax0_ax1_ax2_ax3_fused // 3648) v2 = T.axis.spatial(114, ax0_ax1_ax2_ax3_fused % 3648 // 32) v3 = T.axis.spatial(32, ax0_ax1_ax2_ax3_fused % 32) T.reads(placeholder[v0, v1 - 1, v2 - 1, v3]) T.writes(PadInput_shared[v0, v1, v2, v3]) T.block_attr({"meta_schedule.cooperative_fetch":3}) PadInput_shared[v0, v1, v2, v3] = T.if_then_else(1 <= v1 and v1 < 113 and 1 <= v2 and v2 < 113, placeholder[v0, v1 - 1, v2 - 1, v3], T.float32(0), dtype="float32") for ax0_ax1_ax2_ax3_fused in T.serial(288): with T.block("placeholder_shared"): v0 = T.axis.spatial(1, 0) v1 = T.axis.spatial(3, ax0_ax1_ax2_ax3_fused // 96) v2 = T.axis.spatial(3, ax0_ax1_ax2_ax3_fused % 96 // 32) v3 = T.axis.spatial(32, ax0_ax1_ax2_ax3_fused % 32) T.reads(placeholder_1[v0, v1, v2, v3]) T.writes(placeholder_shared[v0, v1, v2, v3]) T.block_attr({"meta_schedule.cooperative_fetch":3}) placeholder_shared[v0, v1, v2, v3] = placeholder_1[v0, v1, v2, v3] for i4_1, i5_1, i0_3, i1_3, i2_3, i3_3, i4_2, i5_2, i0_4, i1_4, i2_4, i3_4 in T.grid(3, 1, 1, 4, 16, 8, 1, 3, 1, 7, 1, 1): with T.block("depth_conv2d_nhwc"): n = T.axis.spatial(1, i0_4 + i0_3) h = T.axis.spatial(112, i0_1_i1_1_i2_1_i3_1_fused // 2 * 28 + i1_3 * 7 + i1_4) w = T.axis.spatial(112, i2_4 + i0_2_i1_2_i2_2_i3_2_fused // 2 * 16 + i2_3) c = T.axis.spatial(32, i0_1_i1_1_i2_1_i3_1_fused % 2 * 16 + i0_2_i1_2_i2_2_i3_2_fused % 2 * 8 + i3_3 + i3_4) rh = T.axis.reduce(3, i4_2 + i4_0 * 3 + i4_1) rw = T.axis.reduce(3, i5_0 * 3 + i5_1 * 3 + i5_2) T.reads(PadInput_shared[n, h + rh, w + rw, c], placeholder_shared[0, rh, rw, c]) T.writes(depth_conv2d_nhwc_local[n, h, w, c]) T.block_attr({"meta_schedule.thread_extent_high_inclusive":1024, "meta_schedule.thread_extent_low_inclusive":32, "meta_schedule.tiling_structure":"SSSRRSRS"}) with T.init(): depth_conv2d_nhwc_local[n, h, w, c] = T.float32(0) depth_conv2d_nhwc_local[n, h, w, c] = depth_conv2d_nhwc_local[n, h, w, c] + PadInput_shared[n, h + rh, w + rw, c] * placeholder_shared[0, rh, rw, c] for ax0, ax1, ax2, ax3 in T.grid(1, 28, 16, 8): with T.block("depth_conv2d_nhwc_local"): v0 = T.axis.spatial(1, ax0) v1 = T.axis.spatial(112, i0_1_i1_1_i2_1_i3_1_fused // 2 * 28 + ax1) v2 = T.axis.spatial(112, i0_2_i1_2_i2_2_i3_2_fused // 2 * 16 + ax2) v3 = T.axis.spatial(32, i0_1_i1_1_i2_1_i3_1_fused % 2 * 16 + i0_2_i1_2_i2_2_i3_2_fused % 2 * 8 + ax3) T.reads(depth_conv2d_nhwc_local[v0, v1, v2, v3]) T.writes(depth_conv2d_nhwc[v0, v1, v2, v3]) depth_conv2d_nhwc[v0, v1, v2, v3] = depth_conv2d_nhwc_local[v0, v1, v2, v3] # fmt: on decision_0 = [ ("SamplePerfectTile", [1, 1, 1, 1, 1]), ("SamplePerfectTile", [1, 4, 1, 4, 7]), ("SamplePerfectTile", [1, 1, 7, 16, 1]), ("SamplePerfectTile", [1, 2, 2, 8, 1]), ("SamplePerfectTile", [1, 3, 1]), ("SamplePerfectTile", [1, 1, 3]), ("SampleCategorical", 2), ("SampleCategorical", 2), ("SampleCategorical", 1), ] mod = create_te_workload("DEP", 0) actual = _design_space(mod) check_sketches( mod, sketches=actual, expected_mods=[dep_0], expected_decisions=[decision_0], ) def test_cuda_dil(): # fmt: off @T.prim_func def dil_0(inputs: T.Buffer[(1, 224, 224, 3), "float32"], weight: T.Buffer[(7, 7, 3, 64), "float32"], conv2d_nhwc: T.Buffer[(1, 109, 109, 64), "float32"]) -> None: # function attr dict T.func_attr({"global_symbol": "main", "tir.noalias": True}) # body with T.block("root"): T.reads() T.writes() T.block_attr({"meta_schedule.unroll_explicit":512}) conv2d_nhwc_local = T.alloc_buffer([1, 109, 109, 64], dtype="float32", scope="local") PadInput_shared = T.alloc_buffer([1, 230, 230, 3], dtype="float32", scope="shared") weight_shared = T.alloc_buffer([7, 7, 3, 64], dtype="float32", scope="shared") for i0_0_i1_0_i2_0_i3_0_fused in T.thread_binding(218, thread="blockIdx.x"): for i0_1_i1_1_i2_1_i3_1_fused in T.thread_binding(109, thread="vthread.x"): for i0_2_i1_2_i2_2_i3_2_fused in T.thread_binding(1, thread="threadIdx.x"): for i4_0, i5_0, i6_0 in T.grid(7, 7, 3): for ax0_ax1_ax2_ax3_fused in T.serial(217): with T.block("PadInput_shared"): v0 = T.axis.spatial(1, 0) v1 = T.axis.spatial(230, i0_0_i1_0_i2_0_i3_0_fused // 2 * 2 + i4_0 * 2 + 0) v2 = T.axis.spatial(230, i5_0 * 2 + ax0_ax1_ax2_ax3_fused % 217) v3 = T.axis.spatial(3, i6_0 + 0) T.reads(inputs[v0, v1 - 3, v2 - 3, v3]) T.writes(PadInput_shared[v0, v1, v2, v3]) T.block_attr({"meta_schedule.cooperative_fetch":2}) PadInput_shared[v0, v1, v2, v3] = T.if_then_else(3 <= v1 and v1 < 227 and 3 <= v2 and v2 < 227, inputs[v0, v1 - 3, v2 - 3, v3], T.float32(0), dtype="float32") for ax0_ax1_ax2_ax3_fused in T.serial(32): with T.block("weight_shared"): v0, v1, v2 = T.axis.remap("SSS", [i4_0, i5_0, i6_0]) v3 = T.axis.spatial(64, i0_0_i1_0_i2_0_i3_0_fused % 2 * 32 + ax0_ax1_ax2_ax3_fused) T.reads(weight[v0, v1, v2, v3]) T.writes(weight_shared[v0, v1, v2, v3]) T.block_attr({"meta_schedule.cooperative_fetch":4}) weight_shared[v0, v1, v2, v3] = weight[v0, v1, v2, v3] for i4_1, i5_1, i6_1, i0_3, i1_3, i2_3, i3_3, i4_2, i5_2, i6_2, i0_4, i1_4, i2_4, i3_4 in T.grid(1, 1, 1, 1, 1, 1, 8, 1, 1, 1, 1, 1, 1, 4): with T.block("conv2d_nhwc"): n = T.axis.spatial(1, i0_3 + i0_4) h = T.axis.spatial(109, i1_4 + i0_0_i1_0_i2_0_i3_0_fused // 2 + i1_3) w = T.axis.spatial(109, i0_1_i1_1_i2_1_i3_1_fused + i2_3 + i2_4) co = T.axis.spatial(64, i0_0_i1_0_i2_0_i3_0_fused % 2 * 32 + i3_3 * 4 + i3_4) rh = T.axis.reduce(7, i4_0 + i4_1 + i4_2) rw = T.axis.reduce(7, i5_2 + i5_0 + i5_1) rc = T.axis.reduce(3, i6_1 + i6_2 + i6_0) T.reads(PadInput_shared[n, h * 2 + rh * 2, w * 2 + rw * 2, co // 64 * 3 + rc], weight_shared[rh, rw, rc, co]) T.writes(conv2d_nhwc_local[n, h, w, co]) T.block_attr({"meta_schedule.thread_extent_high_inclusive":1024, "meta_schedule.thread_extent_low_inclusive":32, "meta_schedule.tiling_structure":"SSSRRSRS"}) with T.init(): conv2d_nhwc_local[n, h, w, co] = T.float32(0) conv2d_nhwc_local[n, h, w, co] = conv2d_nhwc_local[n, h, w, co] + PadInput_shared[n, h * 2 + rh * 2, w * 2 + rw * 2, co // 64 * 3 + rc] * weight_shared[rh, rw, rc, co] for ax0, ax1, ax2, ax3 in T.grid(1, 1, 1, 32): with T.block("conv2d_nhwc_local"): v0 = T.axis.spatial(1, ax0) v1 = T.axis.spatial(109, i0_0_i1_0_i2_0_i3_0_fused // 2 + ax1) v2 = T.axis.spatial(109, i0_1_i1_1_i2_1_i3_1_fused + ax2) v3 = T.axis.spatial(64, i0_0_i1_0_i2_0_i3_0_fused % 2 * 32 + ax3) T.reads(conv2d_nhwc_local[v0, v1, v2, v3]) T.writes(conv2d_nhwc[v0, v1, v2, v3]) conv2d_nhwc[v0, v1, v2, v3] = conv2d_nhwc_local[v0, v1, v2, v3] # fmt: on decision_0 = [ ("SamplePerfectTile", [1, 1, 1, 1, 1]), ("SamplePerfectTile", [109, 1, 1, 1, 1]), ("SamplePerfectTile", [1, 109, 1, 1, 1]), ("SamplePerfectTile", [2, 1, 1, 8, 4]), ("SamplePerfectTile", [7, 1, 1]), ("SamplePerfectTile", [7, 1, 1]), ("SamplePerfectTile", [3, 1, 1]), ("SampleCategorical", 1), ("SampleCategorical", 3), ("SampleCategorical", 3), ] mod = create_te_workload("DIL", 0) actual = _design_space(mod) check_sketches( mod, sketches=actual, expected_mods=[dil_0], expected_decisions=[decision_0], ) def test_cuda_gmm(): # fmt: off @T.prim_func def gmm_0(X: T.Buffer[(1, 128, 128), "float32"], Y: T.Buffer[(1, 128, 128), "float32"], Z: T.Buffer[(1, 128, 128), "float32"]) -> None: # function attr dict T.func_attr({"global_symbol": "main", "tir.noalias": True}) # body with T.block("root"): T.reads() T.writes() T.block_attr({"meta_schedule.unroll_explicit":1024}) Z_local = T.alloc_buffer([1, 128, 128], dtype="float32", scope="local") X_shared = T.alloc_buffer([1, 128, 128], dtype="float32", scope="shared") Y_shared = T.alloc_buffer([1, 128, 128], dtype="float32", scope="shared") for i0_0_i1_0_i2_0_fused in T.thread_binding(1, thread="blockIdx.x"): for i0_1_i1_1_i2_1_fused in T.thread_binding(32, thread="vthread.x"): for i0_2_i1_2_i2_2_fused in T.thread_binding(2, thread="threadIdx.x"): for i3_0 in T.serial(1): for ax0_ax1_ax2_fused in T.serial(16384): with T.block("X_shared"): v0 = T.axis.spatial(1, 0) v1 = T.axis.spatial(128, ax0_ax1_ax2_fused // 128) v2 = T.axis.spatial(128, ax0_ax1_ax2_fused % 128) T.reads(X[v0, v1, v2]) T.writes(X_shared[v0, v1, v2]) T.block_attr({"meta_schedule.cooperative_fetch":2}) X_shared[v0, v1, v2] = X[v0, v1, v2] for ax0_ax1_ax2_fused in T.serial(16384): with T.block("Y_shared"): v0 = T.axis.spatial(1, 0) v1 = T.axis.spatial(128, ax0_ax1_ax2_fused // 128) v2 = T.axis.spatial(128, ax0_ax1_ax2_fused % 128) T.reads(Y[v0, v1, v2]) T.writes(Y_shared[v0, v1, v2]) T.block_attr({"meta_schedule.cooperative_fetch":1}) Y_shared[v0, v1, v2] = Y[v0, v1, v2] for i3_1, i0_3, i1_3, i2_3, i3_2, i0_4, i1_4, i2_4 in T.grid(32, 1, 2, 64, 4, 1, 2, 1): with T.block("Z"): b = T.axis.spatial(1, i0_4 + i0_3) i = T.axis.spatial(128, i0_1_i1_1_i2_1_fused * 4 + i1_3 * 2 + i1_4) j = T.axis.spatial(128, i2_4 + i0_2_i1_2_i2_2_fused * 64 + i2_3) k = T.axis.reduce(128, i3_0 * 128 + i3_1 * 4 + i3_2) T.reads(X_shared[b, i, k], Y_shared[b, k, j]) T.writes(Z_local[b, i, j]) T.block_attr({"meta_schedule.thread_extent_high_inclusive":1024, "meta_schedule.thread_extent_low_inclusive":32, "meta_schedule.tiling_structure":"SSSRRSRS"}) with T.init(): Z_local[b, i, j] = T.float32(0) Z_local[b, i, j] = Z_local[b, i, j] + X_shared[b, i, k] * Y_shared[b, k, j] for ax0, ax1, ax2 in T.grid(1, 4, 64): with T.block("Z_local"): v0 = T.axis.spatial(1, ax0) v1 = T.axis.spatial(128, i0_1_i1_1_i2_1_fused * 4 + ax1) v2 = T.axis.spatial(128, i0_2_i1_2_i2_2_fused * 64 + ax2) T.reads(Z_local[v0, v1, v2]) T.writes(Z[v0, v1, v2]) Z[v0, v1, v2] = Z_local[v0, v1, v2] # fmt: on decision_0 = [ ("SamplePerfectTile", [1, 1, 1, 1, 1]), ("SamplePerfectTile", [1, 32, 1, 2, 2]), ("SamplePerfectTile", [1, 1, 2, 64, 1]), ("SamplePerfectTile", [1, 32, 4]), ("SampleCategorical", 1), ("SampleCategorical", 0), ("SampleCategorical", 4), ] mod = create_te_workload("GMM", 0) actual = _design_space(mod) check_sketches( mod, sketches=actual, expected_mods=[gmm_0], expected_decisions=[decision_0], ) def test_cuda_grp(): # fmt: off @T.prim_func def grp_0(inputs: T.Buffer[(1, 56, 56, 64), "float32"], weight: T.Buffer[(3, 3, 16, 128), "float32"], conv2d_nhwc: T.Buffer[(1, 28, 28, 128), "float32"]) -> None: # function attr dict T.func_attr({"global_symbol": "main", "tir.noalias": True}) # body with T.block("root"): T.reads() T.writes() T.block_attr({"meta_schedule.unroll_explicit":16}) conv2d_nhwc_local = T.alloc_buffer([1, 28, 28, 128], dtype="float32", scope="local") PadInput_shared = T.alloc_buffer([1, 58, 58, 64], dtype="float32", scope="shared") weight_shared = T.alloc_buffer([3, 3, 16, 128], dtype="float32", scope="shared") for i0_0_i1_0_i2_0_i3_0_fused in T.thread_binding(2, thread="blockIdx.x"): for i0_1_i1_1_i2_1_i3_1_fused in T.thread_binding(1, thread="vthread.x"): for i0_2_i1_2_i2_2_i3_2_fused in T.thread_binding(112, thread="threadIdx.x"): for i4_0, i5_0, i6_0 in T.grid(3, 3, 1): for ax0_ax1_ax2_ax3_fused in T.serial(95040): with T.block("PadInput_shared"): v0 = T.axis.spatial(1, 0) v1 = T.axis.spatial(58, i0_0_i1_0_i2_0_i3_0_fused * 28 + i4_0 + ax0_ax1_ax2_ax3_fused % 95040 // 3520) v2 = T.axis.spatial(58, i5_0 + ax0_ax1_ax2_ax3_fused % 3520 // 64) v3 = T.axis.spatial(64, ax0_ax1_ax2_ax3_fused % 64) T.reads(inputs[v0, v1 - 1, v2 - 1, v3]) T.writes(PadInput_shared[v0, v1, v2, v3]) T.block_attr({"meta_schedule.cooperative_fetch":2}) PadInput_shared[v0, v1, v2, v3] = T.if_then_else(1 <= v1 and v1 < 57 and 1 <= v2 and v2 < 57, inputs[v0, v1 - 1, v2 - 1, v3], T.float32(0), dtype="float32") for ax0_ax1_ax2_ax3_fused in T.serial(2048): with T.block("weight_shared"): v0, v1 = T.axis.remap("SS", [i4_0, i5_0]) v2 = T.axis.spatial(16, ax0_ax1_ax2_ax3_fused // 128) v3 = T.axis.spatial(128, ax0_ax1_ax2_ax3_fused % 128) T.reads(weight[v0, v1, v2, v3]) T.writes(weight_shared[v0, v1, v2, v3]) T.block_attr({"meta_schedule.cooperative_fetch":1}) weight_shared[v0, v1, v2, v3] = weight[v0, v1, v2, v3] for i4_1, i5_1, i6_1, i0_3, i1_3, i2_3, i3_3, i4_2, i5_2, i6_2, i0_4, i1_4, i2_4, i3_4 in T.grid(1, 1, 2, 1, 2, 1, 2, 1, 1, 8, 1, 7, 4, 4): with T.block("conv2d_nhwc"): n = T.axis.spatial(1, i0_3 + i0_4) h = T.axis.spatial(28, i0_0_i1_0_i2_0_i3_0_fused * 14 + i1_3 * 7 + i1_4) w = T.axis.spatial(28, i0_2_i1_2_i2_2_i3_2_fused // 16 * 4 + i2_3 * 4 + i2_4) co = T.axis.spatial(128, i0_2_i1_2_i2_2_i3_2_fused % 16 * 8 + i3_3 * 4 + i3_4) rh = T.axis.reduce(3, i4_0 + i4_1 + i4_2) rw = T.axis.reduce(3, i5_2 + i5_0 + i5_1) rc = T.axis.reduce(16, i6_0 * 16 + i6_1 * 8 + i6_2) T.reads(PadInput_shared[n, h * 2 + rh, w * 2 + rw, co // 32 * 16 + rc], weight_shared[rh, rw, rc, co]) T.writes(conv2d_nhwc_local[n, h, w, co]) T.block_attr({"meta_schedule.thread_extent_high_inclusive":1024, "meta_schedule.thread_extent_low_inclusive":32, "meta_schedule.tiling_structure":"SSSRRSRS"}) with T.init(): conv2d_nhwc_local[n, h, w, co] = T.float32(0) conv2d_nhwc_local[n, h, w, co] = conv2d_nhwc_local[n, h, w, co] + PadInput_shared[n, h * 2 + rh, w * 2 + rw, co // 32 * 16 + rc] * weight_shared[rh, rw, rc, co] for ax0, ax1, ax2, ax3 in T.grid(1, 14, 4, 8): with T.block("conv2d_nhwc_local"): v0 = T.axis.spatial(1, ax0) v1 = T.axis.spatial(28, i0_0_i1_0_i2_0_i3_0_fused * 14 + ax1) v2 = T.axis.spatial(28, i0_2_i1_2_i2_2_i3_2_fused // 16 * 4 + ax2) v3 = T.axis.spatial(128, i0_2_i1_2_i2_2_i3_2_fused % 16 * 8 + ax3) T.reads(conv2d_nhwc_local[v0, v1, v2, v3]) T.writes(conv2d_nhwc[v0, v1, v2, v3]) conv2d_nhwc[v0, v1, v2, v3] = conv2d_nhwc_local[v0, v1, v2, v3] # fmt: on decision_0 = [ ("SamplePerfectTile", [1, 1, 1, 1, 1]), ("SamplePerfectTile", [2, 1, 1, 2, 7]), ("SamplePerfectTile", [1, 1, 7, 1, 4]), ("SamplePerfectTile", [1, 1, 16, 2, 4]), ("SamplePerfectTile", [3, 1, 1]), ("SamplePerfectTile", [3, 1, 1]), ("SamplePerfectTile", [1, 2, 8]), ("SampleCategorical", 1), ("SampleCategorical", 0), ("SampleCategorical", 1), ] mod = create_te_workload("GRP", 0) actual = _design_space(mod) check_sketches( mod, sketches=actual, expected_mods=[grp_0], expected_decisions=[decision_0], ) def test_cuda_t2d(): # fmt: off @T.prim_func def t2d_0(inputs: T.Buffer[(1, 4, 4, 512), "float32"], weight: T.Buffer[(4, 4, 512, 256), "float32"], conv2d_transpose_nhwc: T.Buffer[(1, 8, 8, 256), "float32"]) -> None: # function attr dict T.func_attr({"global_symbol": "main", "tir.noalias": True}) # body with T.block("root"): T.reads() T.writes() T.block_attr({"meta_schedule.unroll_explicit":64}) conv2d_transpose_nhwc_local = T.alloc_buffer([1, 8, 8, 256], dtype="float32", scope="local") PadInput_shared = T.alloc_buffer([1, 6, 6, 512], dtype="float32", scope="shared") weight_shared = T.alloc_buffer([4, 4, 512, 256], dtype="float32", scope="shared") for i0_0_i1_0_i2_0_i3_0_fused in T.thread_binding(256, thread="blockIdx.x"): for i0_1_i1_1_i2_1_i3_1_fused in T.thread_binding(2, thread="vthread.x"): for i0_2_i1_2_i2_2_i3_2_fused in T.thread_binding(1, thread="threadIdx.x"): for i4_0, i5_0, i6_0 in T.grid(4, 1, 16): for ax0_ax1_ax2_ax3_fused in T.serial((i4_0 % 2 + 1) // 2 * 96 + 96): with T.block("PadInput_shared"): v0 = T.axis.spatial(1, 0) v1 = T.axis.spatial(6, i0_0_i1_0_i2_0_i3_0_fused // 64 + i4_0 // 2 + ax0_ax1_ax2_ax3_fused % (96 * ((i4_0 % 2 + 1) // 2 + 1)) // 96) v2 = T.axis.spatial(6, i0_0_i1_0_i2_0_i3_0_fused % 64 // 16 + ax0_ax1_ax2_ax3_fused % 96 // 32) v3 = T.axis.spatial(512, i6_0 * 32 + ax0_ax1_ax2_ax3_fused % 32) T.reads(inputs[v0, v1 - 1, v2 - 1, v3]) T.writes(PadInput_shared[v0, v1, v2, v3]) T.block_attr({"meta_schedule.cooperative_fetch":2}) PadInput_shared[v0, v1, v2, v3] = T.if_then_else(1 <= v1 and v1 < 5 and 1 <= v2 and v2 < 5, inputs[v0, v1 - 1, v2 - 1, v3], T.float32(0), dtype="float32") for ax0_ax1_ax2_ax3_fused in T.serial(2048): with T.block("weight_shared"): v0 = T.axis.spatial(4, i4_0 * -1 + 3) v1 = T.axis.spatial(4, ax0_ax1_ax2_ax3_fused // 512) v2 = T.axis.spatial(512, i6_0 * 32 + ax0_ax1_ax2_ax3_fused % 512 // 16) v3 = T.axis.spatial(256, i0_0_i1_0_i2_0_i3_0_fused % 16 * 16 + ax0_ax1_ax2_ax3_fused % 16) T.reads(weight[v0, v1, v2, v3]) T.writes(weight_shared[v0, v1, v2, v3]) T.block_attr({"meta_schedule.cooperative_fetch":4}) weight_shared[v0, v1, v2, v3] = weight[v0, v1, v2, v3] for i4_1, i5_1, i6_1, i0_3, i1_3, i2_3, i3_3, i4_2, i5_2, i6_2, i0_4, i1_4, i2_4, i3_4 in T.grid(1, 1, 4, 1, 2, 1, 8, 1, 4, 8, 1, 1, 2, 1): with T.block("conv2d_transpose_nhwc"): n = T.axis.spatial(1, i0_3 + i0_4) h = T.axis.spatial(8, i1_4 + i0_0_i1_0_i2_0_i3_0_fused // 64 * 2 + i1_3) w = T.axis.spatial(8, i0_0_i1_0_i2_0_i3_0_fused % 64 // 16 * 2 + i2_3 * 2 + i2_4) co = T.axis.spatial(256, i3_4 + i0_0_i1_0_i2_0_i3_0_fused % 16 * 16 + i0_1_i1_1_i2_1_i3_1_fused * 8 + i3_3) rh = T.axis.reduce(4, i4_0 + i4_1 + i4_2) rw = T.axis.reduce(4, i5_0 * 4 + i5_1 * 4 + i5_2) rc = T.axis.reduce(512, i6_0 * 32 + i6_1 * 8 + i6_2) T.reads(PadInput_shared[n, (h + rh) // 2, (w + rw) // 2, rc], weight_shared[3 - rh, 3 - rw, rc, co]) T.writes(conv2d_transpose_nhwc_local[n, h, w, co]) T.block_attr({"meta_schedule.thread_extent_high_inclusive":1024, "meta_schedule.thread_extent_low_inclusive":32, "meta_schedule.tiling_structure":"SSSRRSRS"}) with T.init(): conv2d_transpose_nhwc_local[n, h, w, co] = T.float32(0) conv2d_transpose_nhwc_local[n, h, w, co] = conv2d_transpose_nhwc_local[n, h, w, co] + T.if_then_else((h + rh) % 2 == 0 and (w + rw) % 2 == 0, PadInput_shared[n, (h + rh) // 2, (w + rw) // 2, rc], T.float32(0), dtype="float32") * weight_shared[3 - rh, 3 - rw, rc, co] for ax0, ax1, ax2, ax3 in T.grid(1, 2, 2, 8): with T.block("conv2d_transpose_nhwc_local"): v0 = T.axis.spatial(1, ax0) v1 = T.axis.spatial(8, i0_0_i1_0_i2_0_i3_0_fused // 64 * 2 + ax1) v2 = T.axis.spatial(8, i0_0_i1_0_i2_0_i3_0_fused % 64 // 16 * 2 + ax2) v3 = T.axis.spatial(256, i0_0_i1_0_i2_0_i3_0_fused % 16 * 16 + i0_1_i1_1_i2_1_i3_1_fused * 8 + ax3) T.reads(conv2d_transpose_nhwc_local[v0, v1, v2, v3]) T.writes(conv2d_transpose_nhwc[v0, v1, v2, v3]) conv2d_transpose_nhwc[v0, v1, v2, v3] = conv2d_transpose_nhwc_local[v0, v1, v2, v3] # fmt: on decision_0 = [ ("SamplePerfectTile", [1, 1, 1, 1, 1]), ("SamplePerfectTile", [4, 1, 1, 2, 1]), ("SamplePerfectTile", [4, 1, 1, 1, 2]), ("SamplePerfectTile", [16, 2, 1, 8, 1]), ("SamplePerfectTile", [4, 1, 1]), ("SamplePerfectTile", [1, 1, 4]), ("SamplePerfectTile", [16, 4, 8]), ("SampleCategorical", 1), ("SampleCategorical", 3), ("SampleCategorical", 2), ] mod = create_te_workload("T2D", 0) actual = _design_space(mod) check_sketches( mod, sketches=actual, expected_mods=[t2d_0], expected_decisions=[decision_0], debug_mask=0, ) def test_cuda_nrm(): # fmt: off @T.prim_func def nrm_0(A: T.Buffer[(1, 256, 256), "float32"], D: T.Buffer[1, "float32"]) -> None: # function attr dict T.func_attr({"global_symbol": "main", "tir.noalias": True}) # body with T.block("root"): T.reads() T.writes() T.block_attr({"meta_schedule.unroll_explicit":512}) C = T.alloc_buffer([1], dtype="float32") for i0_fused_0 in T.thread_binding(1, thread="blockIdx.x"): for i0_fused_1 in T.thread_binding(1, thread="threadIdx.x"): for i1, i2 in T.grid(256, 256): with T.block("C"): b = T.axis.spatial(1, 0) i, j = T.axis.remap("RR", [i1, i2]) T.reads(A[b, i, j]) T.writes(C[b]) with T.init(): C[b] = T.float32(0) C[b] = C[b] + A[b, i, j] * A[b, i, j] for i0_fused_0 in T.thread_binding(1, thread="blockIdx.x"): for i0_fused_1 in T.thread_binding(1, thread="threadIdx.x"): with T.block("D"): b = T.axis.spatial(1, 0) T.reads(C[b]) T.writes(D[b]) D[b] = T.sqrt(C[b], dtype="float32") @T.prim_func def nrm_1(A: T.Buffer[(1, 256, 256), "float32"], D: T.Buffer[1, "float32"]) -> None: # function attr dict T.func_attr({"global_symbol": "main", "tir.noalias": True}) # body with T.block("root"): T.reads() T.writes() T.block_attr({"meta_schedule.unroll_explicit":1024}) C_shared = T.alloc_buffer([1], dtype="float32", scope="shared") for i0_0_fused in T.thread_binding(1, thread="blockIdx.x"): for ax0, ax1_ax2_fused_0 in T.grid(1, 512): for ax1_ax2_fused_1 in T.thread_binding(128, thread="threadIdx.x"): with T.block("C"): b = T.axis.spatial(1, ax0) i = T.axis.reduce(256, (ax1_ax2_fused_0 * 128 + ax1_ax2_fused_1) // 256) j = T.axis.reduce(256, (ax1_ax2_fused_0 * 128 + ax1_ax2_fused_1) % 256) T.reads(A[b, i, j]) T.writes(C_shared[b]) with T.init(): C_shared[b] = T.float32(0) C_shared[b] = C_shared[b] + A[b, i, j] * A[b, i, j] for i0_1 in T.thread_binding(128, thread="threadIdx.x"): with T.block("D"): b = T.axis.spatial(1, i0_1) T.where(T.Mul(0, 128) + i0_1 < 1) T.reads(C_shared[b]) T.writes(D[b]) D[b] = T.sqrt(C_shared[b], dtype="float32") # fmt: on decision_0 = [ ("SampleCategorical", 3), ] decision_1 = [ ("SampleCategorical", 5), ("SampleCategorical", 4), ] mod = create_te_workload("NRM", 0) actual = _design_space(mod) check_sketches( mod, sketches=actual, expected_mods=[nrm_0, nrm_1], expected_decisions=[decision_0, decision_1], ) def test_cuda_sfm(): # fmt: off @T.prim_func def sfm_0(A: T.Buffer[(256, 256), "float32"], T_softmax_norm: T.Buffer[(256, 256), "float32"]) -> None: # function attr dict T.func_attr({"global_symbol": "main", "tir.noalias": True}) # body with T.block("root"): T.reads() T.writes() T.block_attr({"meta_schedule.unroll_explicit":0}) T_softmax_maxelem = T.alloc_buffer([256], dtype="float32") T_softmax_expsum = T.alloc_buffer([256], dtype="float32") for i0_fused_0 in T.thread_binding(2, thread="blockIdx.x"): for i0_fused_1 in T.thread_binding(128, thread="threadIdx.x"): for i1 in T.serial(256): with T.block("T_softmax_maxelem"): i0 = T.axis.spatial(256, i0_fused_0 * 128 + i0_fused_1) k = T.axis.reduce(256, i1) T.reads(A[i0, k]) T.writes(T_softmax_maxelem[i0]) with T.init(): T_softmax_maxelem[i0] = T.float32(-3.4028234663852886e+38) T_softmax_maxelem[i0] = T.max(T_softmax_maxelem[i0], A[i0, k]) for i0_fused_0 in T.thread_binding(1, thread="blockIdx.x"): for i0_fused_1 in T.thread_binding(256, thread="threadIdx.x"): for i1 in T.serial(256): with T.block("T_softmax_expsum"): i0 = T.axis.spatial(256, i0_fused_0 * 256 + i0_fused_1) k = T.axis.reduce(256, i1) T.reads(A[i0, k], T_softmax_maxelem[i0]) T.writes(T_softmax_expsum[i0]) with T.init(): T_softmax_expsum[i0] = T.float32(0) T_softmax_expsum[i0] = T_softmax_expsum[i0] + T.exp(A[i0, k] - T_softmax_maxelem[i0], dtype="float32") for i0_i1_fused_0 in T.thread_binding(1024, thread="blockIdx.x"): for i0_i1_fused_1 in T.thread_binding(64, thread="threadIdx.x"): with T.block("T_softmax_norm"): i0 = T.axis.spatial(256, (i0_i1_fused_0 * 64 + i0_i1_fused_1) // 256) i1 = T.axis.spatial(256, (i0_i1_fused_0 * 64 + i0_i1_fused_1) % 256) T.reads(A[i0, i1], T_softmax_maxelem[i0], T_softmax_expsum[i0]) T.writes(T_softmax_norm[i0, i1]) T.block_attr({"axis":1}) T_softmax_norm[i0, i1] = T.exp(A[i0, i1] - T_softmax_maxelem[i0], dtype="float32") / T_softmax_expsum[i0] @T.prim_func def sfm_1(A: T.Buffer[(256, 256), "float32"], T_softmax_norm: T.Buffer[(256, 256), "float32"]) -> None: # function attr dict T.func_attr({"global_symbol": "main", "tir.noalias": True}) # body with T.block("root"): T.reads() T.writes() T.block_attr({"meta_schedule.unroll_explicit":16}) T_softmax_maxelem = T.alloc_buffer([256], dtype="float32") T_softmax_expsum = T.alloc_buffer([256], dtype="float32") for i0_fused in T.thread_binding(256, thread="blockIdx.x"): for i1_0 in T.serial(64): for i1_1 in T.thread_binding(4, thread="threadIdx.x"): with T.block("T_softmax_maxelem"): i0 = T.axis.spatial(256, i0_fused) k = T.axis.reduce(256, i1_0 * 4 + i1_1) T.reads(A[i0, k]) T.writes(T_softmax_maxelem[i0]) with T.init(): T_softmax_maxelem[i0] = T.float32(-3.4028234663852886e+38) T_softmax_maxelem[i0] = T.max(T_softmax_maxelem[i0], A[i0, k]) for i0_fused_0 in T.thread_binding(4, thread="blockIdx.x"): for i0_fused_1 in T.thread_binding(64, thread="threadIdx.x"): for i1 in T.serial(256): with T.block("T_softmax_expsum"): i0 = T.axis.spatial(256, i0_fused_0 * 64 + i0_fused_1) k = T.axis.reduce(256, i1) T.reads(A[i0, k], T_softmax_maxelem[i0]) T.writes(T_softmax_expsum[i0]) with T.init(): T_softmax_expsum[i0] = T.float32(0) T_softmax_expsum[i0] = T_softmax_expsum[i0] + T.exp(A[i0, k] - T_softmax_maxelem[i0], dtype="float32") for i0_i1_fused_0 in T.thread_binding(256, thread="blockIdx.x"): for i0_i1_fused_1 in T.thread_binding(256, thread="threadIdx.x"): with T.block("T_softmax_norm"): i0 = T.axis.spatial(256, (i0_i1_fused_0 * 256 + i0_i1_fused_1) // 256) i1 = T.axis.spatial(256, (i0_i1_fused_0 * 256 + i0_i1_fused_1) % 256) T.reads(A[i0, i1], T_softmax_maxelem[i0], T_softmax_expsum[i0]) T.writes(T_softmax_norm[i0, i1]) T.block_attr({"axis":1}) T_softmax_norm[i0, i1] = T.exp(A[i0, i1] - T_softmax_maxelem[i0], dtype="float32") / T_softmax_expsum[i0] @T.prim_func def sfm_2(A: T.Buffer[(256, 256), "float32"], T_softmax_norm: T.Buffer[(256, 256), "float32"]) -> None: # function attr dict T.func_attr({"global_symbol": "main", "tir.noalias": True}) # body with T.block("root"): T.reads() T.writes() T.block_attr({"meta_schedule.unroll_explicit":512}) T_softmax_maxelem = T.alloc_buffer([256], dtype="float32") T_softmax_expsum_shared = T.alloc_buffer([256], dtype="float32", scope="shared") for i0_fused_0 in T.thread_binding(8, thread="blockIdx.x"): for i0_fused_1 in T.thread_binding(32, thread="threadIdx.x"): for i1 in T.serial(256): with T.block("T_softmax_maxelem"): i0 = T.axis.spatial(256, i0_fused_0 * 32 + i0_fused_1) k = T.axis.reduce(256, i1) T.reads(A[i0, k]) T.writes(T_softmax_maxelem[i0]) with T.init(): T_softmax_maxelem[i0] = T.float32(-3.4028234663852886e+38) T_softmax_maxelem[i0] = T.max(T_softmax_maxelem[i0], A[i0, k]) for i0_fused in T.thread_binding(256, thread="blockIdx.x"): for ax0, ax1_0 in T.grid(1, 1): for ax1_1 in T.thread_binding(512, thread="threadIdx.x"): with T.block("T_softmax_expsum"): i0 = T.axis.spatial(256, i0_fused + ax0) k = T.axis.reduce(256, ax1_0 * 512 + ax1_1) T.where(ax1_0 * 512 + ax1_1 < 256) T.reads(A[i0, k], T_softmax_maxelem[i0]) T.writes(T_softmax_expsum_shared[i0]) with T.init(): T_softmax_expsum_shared[i0] = T.float32(0) T_softmax_expsum_shared[i0] = T_softmax_expsum_shared[i0] + T.exp(A[i0, k] - T_softmax_maxelem[i0], dtype="float32") for i1_0 in T.serial(1): for i1_1 in T.thread_binding(512, thread="threadIdx.x"): with T.block("T_softmax_norm"): i0 = T.axis.spatial(256, i0_fused) i1 = T.axis.spatial(256, i1_0 * 512 + i1_1) T.where(i1_0 * 512 + i1_1 < 256) T.reads(A[i0, i1], T_softmax_maxelem[i0], T_softmax_expsum_shared[i0]) T.writes(T_softmax_norm[i0, i1]) T.block_attr({"axis":1}) T_softmax_norm[i0, i1] = T.exp(A[i0, i1] - T_softmax_maxelem[i0], dtype="float32") / T_softmax_expsum_shared[i0] @T.prim_func def sfm_3(A: T.Buffer[(256, 256), "float32"], T_softmax_norm: T.Buffer[(256, 256), "float32"]) -> None: # function attr dict T.func_attr({"global_symbol": "main", "tir.noalias": True}) # body with T.block("root"): T.reads() T.writes() T.block_attr({"meta_schedule.unroll_explicit":0}) T_softmax_maxelem_shared = T.alloc_buffer([256], dtype="float32", scope="shared") T_softmax_expsum_shared = T.alloc_buffer([256], dtype="float32", scope="shared") for i0_fused in T.thread_binding(256, thread="blockIdx.x"): for ax0, ax1_0 in T.grid(1, 1): for ax1_1 in T.thread_binding(512, thread="threadIdx.x"): with T.block("T_softmax_maxelem"): i0 = T.axis.spatial(256, i0_fused + ax0) k = T.axis.reduce(256, ax1_0 * 512 + ax1_1) T.where(ax1_0 * 512 + ax1_1 < 256) T.reads(A[i0, k]) T.writes(T_softmax_maxelem_shared[i0]) with T.init(): T_softmax_maxelem_shared[i0] = T.float32(-3.4028234663852886e+38) T_softmax_maxelem_shared[i0] = T.max(T_softmax_maxelem_shared[i0], A[i0, k]) for ax0, ax1_0 in T.grid(1, 1): for ax1_1 in T.thread_binding(512, thread="threadIdx.x"): with T.block("T_softmax_expsum"): i0 = T.axis.spatial(256, i0_fused + ax0) k = T.axis.reduce(256, ax1_0 * 512 + ax1_1) T.where(ax1_0 * 512 + ax1_1 < 256) T.reads(A[i0, k], T_softmax_maxelem_shared[i0]) T.writes(T_softmax_expsum_shared[i0]) with T.init(): T_softmax_expsum_shared[i0] = T.float32(0) T_softmax_expsum_shared[i0] = T_softmax_expsum_shared[i0] + T.exp(A[i0, k] - T_softmax_maxelem_shared[i0], dtype="float32") for i1_0 in T.serial(1): for i1_1 in T.thread_binding(512, thread="threadIdx.x"): with T.block("T_softmax_norm"): i0 = T.axis.spatial(256, i0_fused) i1 = T.axis.spatial(256, i1_0 * 512 + i1_1) T.where(i1_0 * 512 + i1_1 < 256) T.reads(A[i0, i1], T_softmax_maxelem_shared[i0], T_softmax_expsum_shared[i0]) T.writes(T_softmax_norm[i0, i1]) T.block_attr({"axis":1}) T_softmax_norm[i0, i1] = T.exp(A[i0, i1] - T_softmax_maxelem_shared[i0], dtype="float32") / T_softmax_expsum_shared[i0] # fmt: on decision_0 = [ ("SampleCategorical", 0), ("SampleCategorical", 1), ("SampleCategorical", 3), ("SampleCategorical", 2), ] decision_1 = [ ("SampleCategorical", 0), ("SampleCategorical", 1), ("SampleCategorical", 3), ("SampleCategorical", 1), ] decision_2 = [ ("SampleCategorical", 7), ("SampleCategorical", 3), ("SampleCategorical", 0), ] decision_3 = [ ("SampleCategorical", 7), ("SampleCategorical", 0), ("SampleCategorical", 0), ] mod = create_te_workload("SFM", 0) actual = _design_space(mod) check_sketches( mod, sketches=actual, expected_mods=[sfm_0, sfm_1, sfm_2, sfm_3], expected_decisions=[decision_0, decision_1, decision_2, decision_3], ) def test_cuda_cbr(): # fmt: off @T.prim_func def cbr_0(data: T.Buffer[(1, 224, 224, 3), "float32"], kernel: T.Buffer[(7, 7, 3, 64), "float32"], bias: T.Buffer[64, "float32"], bn_offset: T.Buffer[64, "float32"], bn_scale: T.Buffer[64, "float32"], compute: T.Buffer[(1, 112, 112, 64), "float32"]) -> None: # function attr dict T.func_attr({"global_symbol": "main", "tir.noalias": True}) # body with T.block("root"): T.reads() T.writes() T.block_attr({"meta_schedule.unroll_explicit":512}) Conv2dOutput_local = T.alloc_buffer([1, 112, 112, 64], dtype="float32", scope="local") PaddedInput_shared = T.alloc_buffer([1, 230, 230, 3], dtype="float32", scope="shared") kernel_shared = T.alloc_buffer([7, 7, 3, 64], dtype="float32", scope="shared") for i0_0_i1_0_i2_0_i3_0_fused in T.thread_binding(14, thread="blockIdx.x"): for i0_1_i1_1_i2_1_i3_1_fused in T.thread_binding(4, thread="vthread.x"): for i0_2_i1_2_i2_2_i3_2_fused in T.thread_binding(128, thread="threadIdx.x"): for i4_0, i5_0, i6_0 in T.grid(7, 1, 3): for ax0_ax1_ax2_ax3_fused in T.serial(8251): with T.block("PaddedInput_shared"): v0 = T.axis.spatial(1, 0) v1 = T.axis.spatial(230, ax0_ax1_ax2_ax3_fused // 37 + i4_0) v2 = T.axis.spatial(230, i0_0_i1_0_i2_0_i3_0_fused // 2 * 32 + ax0_ax1_ax2_ax3_fused % 37) v3 = T.axis.spatial(3, i6_0) T.reads(data[v0, v1 - 3, v2 - 3, v3]) T.writes(PaddedInput_shared[v0, v1, v2, v3]) T.block_attr({"meta_schedule.cooperative_fetch":1}) PaddedInput_shared[v0, v1, v2, v3] = T.if_then_else(3 <= v1 and v1 < 227 and 3 <= v2 and v2 < 227, data[v0, v1 - 3, v2 - 3, v3], T.float32(0), dtype="float32") for ax0_ax1_ax2_ax3_fused in T.serial(224): with T.block("kernel_shared"): v0 = T.axis.spatial(7, i4_0) v1 = T.axis.spatial(7, ax0_ax1_ax2_ax3_fused // 32) v2 = T.axis.spatial(3, i6_0) v3 = T.axis.spatial(64, i0_0_i1_0_i2_0_i3_0_fused % 2 * 32 + ax0_ax1_ax2_ax3_fused % 32) T.reads(kernel[v0, v1, v2, v3]) T.writes(kernel_shared[v0, v1, v2, v3]) T.block_attr({"meta_schedule.cooperative_fetch":1}) kernel_shared[v0, v1, v2, v3] = kernel[v0, v1, v2, v3] for i4_1, i5_1, i6_1, i0_3, i1_3, i2_3, i3_3, i4_2, i5_2, i6_2, i0_4, i1_4, i2_4, i3_4 in T.grid(1, 1, 1, 1, 1, 1, 2, 1, 7, 1, 1, 7, 1, 8): with T.block("Conv2dOutput"): nn = T.axis.spatial(1, i0_3 + i0_4) yy = T.axis.spatial(112, i0_1_i1_1_i2_1_i3_1_fused // 2 * 56 + i0_2_i1_2_i2_2_i3_2_fused // 16 * 7 + i1_3 * 7 + i1_4) xx = T.axis.spatial(112, i2_4 + i0_0_i1_0_i2_0_i3_0_fused // 2 * 16 + i0_2_i1_2_i2_2_i3_2_fused % 16 + i2_3) ff = T.axis.spatial(64, i0_0_i1_0_i2_0_i3_0_fused % 2 * 32 + i0_1_i1_1_i2_1_i3_1_fused % 2 * 16 + i3_3 * 8 + i3_4) ry = T.axis.reduce(7, i4_0 + i4_1 + i4_2) rx = T.axis.reduce(7, i5_0 * 7 + i5_1 * 7 + i5_2) rc = T.axis.reduce(3, i6_1 + i6_2 + i6_0) T.reads(PaddedInput_shared[nn, yy * 2 + ry, xx * 2 + rx, rc], kernel_shared[ry, rx, rc, ff]) T.writes(Conv2dOutput_local[nn, yy, xx, ff]) T.block_attr({"meta_schedule.thread_extent_high_inclusive":1024, "meta_schedule.thread_extent_low_inclusive":32, "meta_schedule.tiling_structure":"SSSRRSRS"}) with T.init(): Conv2dOutput_local[nn, yy, xx, ff] = T.float32(0) Conv2dOutput_local[nn, yy, xx, ff] = Conv2dOutput_local[nn, yy, xx, ff] + PaddedInput_shared[nn, yy * 2 + ry, xx * 2 + rx, rc] * kernel_shared[ry, rx, rc, ff] for ax0, ax1, ax2, ax3 in T.grid(1, 7, 1, 16): with T.block("Conv2dOutput_local"): v0 = T.axis.spatial(1, ax0) v1 = T.axis.spatial(112, i0_1_i1_1_i2_1_i3_1_fused // 2 * 56 + i0_2_i1_2_i2_2_i3_2_fused // 16 * 7 + ax1) v2 = T.axis.spatial(112, i0_0_i1_0_i2_0_i3_0_fused // 2 * 16 + i0_2_i1_2_i2_2_i3_2_fused % 16 + ax2) v3 = T.axis.spatial(64, i0_0_i1_0_i2_0_i3_0_fused % 2 * 32 + i0_1_i1_1_i2_1_i3_1_fused % 2 * 16 + ax3) T.reads(Conv2dOutput_local[v0, v1, v2, v3], bias[v3], bn_scale[v3], bn_offset[v3]) T.writes(compute[v0, v1, v2, v3]) compute[v0, v1, v2, v3] = T.max((Conv2dOutput_local[v0, v1, v2, v3] + bias[v3]) * bn_scale[v3] + bn_offset[v3], T.float32(0)) # fmt: on decision_0 = [ ("SamplePerfectTile", [1, 1, 1, 1, 1]), ("SamplePerfectTile", [1, 2, 8, 1, 7]), ("SamplePerfectTile", [7, 1, 16, 1, 1]), ("SamplePerfectTile", [2, 2, 1, 2, 8]), ("SamplePerfectTile", [7, 1, 1]), ("SamplePerfectTile", [1, 1, 7]), ("SamplePerfectTile", [3, 1, 1]), ("SampleCategorical", 0), ("SampleCategorical", 0), ("SampleCategorical", 3), ] mod = create_te_workload("CBR", 0) actual = _design_space(mod) check_sketches( mod, sketches=actual, expected_mods=[cbr_0], expected_decisions=[decision_0], ) def test_cuda_tbg(): # fmt: off @T.prim_func def tbg_0(query: T.Buffer[(1, 128, 12, 64), "float32"], value: T.Buffer[(1, 128, 12, 64), "float32"], C: T.Buffer[(1, 12, 128, 128), "float32"]) -> None: T.func_attr({"global_symbol": "main", "tir.noalias": True}) with T.block("root"): T.reads() T.writes() T.block_attr({"meta_schedule.unroll_explicit":1024}) C_local = T.alloc_buffer([1, 12, 128, 128], dtype="float32", scope="local") query_T_shared = T.alloc_buffer([1, 12, 128, 64], dtype="float32", scope="shared") value_T_shared = T.alloc_buffer([1, 12, 64, 128], dtype="float32", scope="shared") for i0_0_i1_0_i2_0_i3_0_fused in T.thread_binding(4, thread="blockIdx.x"): for i0_1_i1_1_i2_1_i3_1_fused in T.thread_binding(192, thread="vthread.x"): for i0_2_i1_2_i2_2_i3_2_fused in T.thread_binding(32, thread="threadIdx.x"): for i4_0 in T.serial(8): for ax0_ax1_ax2_ax3_fused in T.serial(12288): with T.block("query_T_shared"): v0 = T.axis.spatial(1, 0) v1 = T.axis.spatial(12, ax0_ax1_ax2_ax3_fused // 1024) v2 = T.axis.spatial(128, ax0_ax1_ax2_ax3_fused % 1024 // 8) v3 = T.axis.spatial(64, i4_0 * 8 + ax0_ax1_ax2_ax3_fused % 8) T.reads(query[v0, v2, v1, v3]) T.writes(query_T_shared[v0, v1, v2, v3]) T.block_attr({"meta_schedule.cooperative_fetch":3}) query_T_shared[v0, v1, v2, v3] = query[v0, v2, v1, v3] for ax0_ax1_ax2_ax3_fused in T.serial(3072): with T.block("value_T_shared"): v0 = T.axis.spatial(1, 0) v1 = T.axis.spatial(12, ax0_ax1_ax2_ax3_fused // 256) v2 = T.axis.spatial(64, i4_0 * 8 + ax0_ax1_ax2_ax3_fused % 256 // 32) v3 = T.axis.spatial(128, i0_0_i1_0_i2_0_i3_0_fused * 32 + ax0_ax1_ax2_ax3_fused % 32) T.reads(value[v0, v3, v1, v2]) T.writes(value_T_shared[v0, v1, v2, v3]) T.block_attr({"meta_schedule.cooperative_fetch":4}) value_T_shared[v0, v1, v2, v3] = value[v0, v3, v1, v2] for i4_1, i0_3, i1_3, i2_3, i3_3, i4_2, i0_4, i1_4, i2_4, i3_4 in T.grid(4, 1, 2, 1, 1, 2, 1, 1, 4, 1): with T.block("C"): b = T.axis.spatial(1, i0_4 + i0_3) h = T.axis.spatial(12, i1_4 + i0_1_i1_1_i2_1_i3_1_fused // 32 * 2 + i1_3) i = T.axis.spatial(128, i0_1_i1_1_i2_1_i3_1_fused % 32 // 8 * 32 + i0_2_i1_2_i2_2_i3_2_fused // 4 * 4 + i2_3 * 4 + i2_4) j = T.axis.spatial(128, i3_4 + i0_0_i1_0_i2_0_i3_0_fused * 32 + i0_1_i1_1_i2_1_i3_1_fused % 8 * 4 + i0_2_i1_2_i2_2_i3_2_fused % 4 + i3_3) k = T.axis.reduce(64, i4_0 * 8 + i4_1 * 2 + i4_2) T.reads(query_T_shared[b, h, i, k], value_T_shared[b, h, k, j]) T.writes(C_local[b, h, i, j]) T.block_attr({"meta_schedule.thread_extent_high_inclusive":1024, "meta_schedule.thread_extent_low_inclusive":32, "meta_schedule.tiling_structure":"SSSRRSRS"}) with T.init(): C_local[b, h, i, j] = T.float32(0) C_local[b, h, i, j] = C_local[b, h, i, j] + query_T_shared[b, h, i, k] * value_T_shared[b, h, k, j] for ax0, ax1, ax2, ax3 in T.grid(1, 2, 4, 1): with T.block("C_local"): v0 = T.axis.spatial(1, ax0) v1 = T.axis.spatial(12, i0_1_i1_1_i2_1_i3_1_fused // 32 * 2 + ax1) v2 = T.axis.spatial(128, i0_1_i1_1_i2_1_i3_1_fused % 32 // 8 * 32 + i0_2_i1_2_i2_2_i3_2_fused // 4 * 4 + ax2) v3 = T.axis.spatial(128, i0_0_i1_0_i2_0_i3_0_fused * 32 + i0_1_i1_1_i2_1_i3_1_fused % 8 * 4 + i0_2_i1_2_i2_2_i3_2_fused % 4 + ax3) T.reads(C_local[v0, v1, v2, v3]) T.writes(C[v0, v1, v2, v3]) C[v0, v1, v2, v3] = C_local[v0, v1, v2, v3] # fmt: on decision_0 = [ ("SamplePerfectTile", [1, 1, 1, 1, 1]), ("SamplePerfectTile", [1, 6, 1, 2, 1]), ("SamplePerfectTile", [1, 4, 8, 1, 4]), ("SamplePerfectTile", [4, 8, 4, 1, 1]), ("SamplePerfectTile", [8, 4, 2]), ("SampleCategorical", 2), ("SampleCategorical", 3), ("SampleCategorical", 4), ] mod = create_te_workload("TBG", 0) actual = _design_space(mod) check_sketches( mod, sketches=actual, expected_mods=[tbg_0], expected_decisions=[decision_0], ) if __name__ == "__main__": test_cuda_c1d() test_cuda_c2d() test_cuda_c3d() test_cuda_cap() test_cuda_dep() test_cuda_dil() test_cuda_gmm() test_cuda_grp() test_cuda_t2d() test_cuda_nrm() test_cuda_sfm() test_cuda_cbr() test_cuda_tbg()
https://github.com/zk-ml/tachikoma
tests/python/unittest/test_meta_schedule_space_cuda_winograd.py
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. """Tests for MetaSchedule search space on CUDA""" from tvm import meta_schedule as ms from tvm.meta_schedule.testing.space_generation import ( check_sketches, generate_design_space, print_sketches, ) from tvm.meta_schedule.testing.te_workload import create_te_workload from tvm.script import tir as T from tvm.target import Target def _target(): return Target("nvidia/geforce-rtx-3070") def _design_space(mod): return generate_design_space( kind="cuda", mod=mod, target=_target(), types=ms.ScheduleRule, ) def test_cuda_nhwc(): # fmt: off @T.prim_func def cuda_nhwc_0(data: T.Buffer[(1, 14, 14, 128), "float32"], weight: T.Buffer[(6, 6, 128, 128), "float32"], conv2d_winograd: T.Buffer[(1, 12, 12, 128), "float32"]) -> None: # function attr dict T.func_attr({"global_symbol": "main", "tir.noalias": True, "layout_free_buffers": [1]}) # body with T.block("root"): T.reads() T.writes() T.block_attr({"meta_schedule.unroll_explicit":16}) input_tile_local = T.alloc_buffer([6, 6, 9, 128], dtype="float32", scope="local") data_pack = T.alloc_buffer([6, 6, 9, 128], dtype="float32") bgemm = T.alloc_buffer([6, 6, 9, 128], dtype="float32") inverse = T.alloc_buffer([4, 4, 9, 128], dtype="float32") data_pack_local = T.alloc_buffer([6, 6, 9, 128], dtype="float32", scope="local") bgemm_local = T.alloc_buffer([6, 6, 9, 128], dtype="float32", scope="local") data_pack_shared = T.alloc_buffer([6, 6, 9, 128], dtype="float32", scope="shared") weight_shared = T.alloc_buffer([6, 6, 128, 128], dtype="float32", scope="shared") for i2_0_i3_0_i2_1_i3_1_fused_0 in T.thread_binding(2, thread="blockIdx.x"): for i2_0_i3_0_i2_1_i3_1_fused_1 in T.thread_binding(1024, thread="threadIdx.x"): for ax0, ax1, ax2, ax3 in T.grid(6, 6, 1, 1): with T.block("input_tile"): T.where(i2_0_i3_0_i2_1_i3_1_fused_0 * 1024 + i2_0_i3_0_i2_1_i3_1_fused_1 < 1152) eps, nu = T.axis.remap("SS", [ax0, ax1]) p = T.axis.spatial(9, (i2_0_i3_0_i2_1_i3_1_fused_0 * 1024 + i2_0_i3_0_i2_1_i3_1_fused_1) // 384 * 3 + (i2_0_i3_0_i2_1_i3_1_fused_0 * 1024 + i2_0_i3_0_i2_1_i3_1_fused_1) % 24 // 8 + ax2) ci = T.axis.spatial(128, (i2_0_i3_0_i2_1_i3_1_fused_0 * 1024 + i2_0_i3_0_i2_1_i3_1_fused_1) % 384 // 24 * 8 + (i2_0_i3_0_i2_1_i3_1_fused_0 * 1024 + i2_0_i3_0_i2_1_i3_1_fused_1) % 8 + ax3) T.reads(data[p // 9, p % 9 // 3 * 4 + eps, p % 3 * 4 + nu, ci]) T.writes(input_tile_local[eps, nu, p, ci]) T.block_attr({"schedule_rule":"None"}) input_tile_local[eps, nu, p, ci] = T.if_then_else(0 <= p % 9 // 3 * 4 + eps and p % 9 // 3 * 4 + eps < 14 and 0 <= p % 3 * 4 + nu and p % 3 * 4 + nu < 14, data[p // 9, p % 9 // 3 * 4 + eps, p % 3 * 4 + nu, ci], T.float32(0), dtype="float32") for i0 in T.unroll(6): for i1 in T.unroll(6): for i4 in T.unroll(6): for i5 in T.unroll(6): with T.block("data_pack"): T.where(i2_0_i3_0_i2_1_i3_1_fused_0 * 1024 + i2_0_i3_0_i2_1_i3_1_fused_1 < 1152) eps, nu = T.axis.remap("SS", [i0, i1]) p = T.axis.spatial(9, (i2_0_i3_0_i2_1_i3_1_fused_0 * 1024 + i2_0_i3_0_i2_1_i3_1_fused_1) // 384 * 3 + (i2_0_i3_0_i2_1_i3_1_fused_0 * 1024 + i2_0_i3_0_i2_1_i3_1_fused_1) % 24 // 8) ci = T.axis.spatial(128, (i2_0_i3_0_i2_1_i3_1_fused_0 * 1024 + i2_0_i3_0_i2_1_i3_1_fused_1) % 384 // 24 * 8 + (i2_0_i3_0_i2_1_i3_1_fused_0 * 1024 + i2_0_i3_0_i2_1_i3_1_fused_1) % 8) r_a, r_b = T.axis.remap("RR", [i4, i5]) T.reads(input_tile_local[r_a, r_b, p, ci]) T.writes(data_pack_local[eps, nu, p, ci]) T.block_attr({"schedule_rule":"conv2d_nhwc_winograd_data_pack"}) with T.init(): data_pack_local[eps, nu, p, ci] = T.float32(0) data_pack_local[eps, nu, p, ci] = data_pack_local[eps, nu, p, ci] + input_tile_local[r_a, r_b, p, ci] * T.Select(r_a % 6 == 5 and eps % 6 == 5, T.float32(1), T.Select(r_a % 6 == 5 and eps % 6 == 4, T.float32(0), T.Select(r_a % 6 == 5 and eps % 6 == 3, T.float32(0), T.Select(r_a % 6 == 5 and eps % 6 == 2, T.float32(0), T.Select(r_a % 6 == 5 and eps % 6 == 1, T.float32(0), T.Select(r_a % 6 == 5 and eps % 6 == 0, T.float32(0), T.Select(r_a % 6 == 4 and eps % 6 == 5, T.float32(1.5), T.Select(r_a % 6 == 4 and eps % 6 == 4, T.float32(1), T.Select(r_a % 6 == 4 and eps % 6 == 3, T.float32(1), T.Select(r_a % 6 == 4 and eps % 6 == 2, T.float32(1), T.Select(r_a % 6 == 4 and eps % 6 == 1, T.float32(1), T.Select(r_a % 6 == 4 and eps % 6 == 0, T.float32(1), T.Select(r_a % 6 == 3 and eps % 6 == 5, T.float32(-2), T.Select(r_a % 6 == 3 and eps % 6 == 4, T.float32(-0.5), T.Select(r_a % 6 == 3 and eps % 6 == 3, T.float32(2), T.Select(r_a % 6 == 3 and eps % 6 == 2, T.float32(2.5), T.Select(r_a % 6 == 3 and eps % 6 == 1, T.float32(0.5), T.Select(r_a % 6 == 3 and eps % 6 == 0, T.float32(1.5), T.Select(r_a % 6 == 2 and eps % 6 == 5, T.float32(-1.5), T.Select(r_a % 6 == 2 and eps % 6 == 4, T.float32(-1), T.Select(r_a % 6 == 2 and eps % 6 == 3, T.float32(-1), T.Select(r_a % 6 == 2 and eps % 6 == 2, T.float32(0.5), T.Select(r_a % 6 == 2 and eps % 6 == 1, T.float32(-2.5), T.Select(r_a % 6 == 2 and eps % 6 == 0, T.float32(-2), T.Select(r_a % 6 == 1 and eps % 6 == 5, T.float32(1), T.Select(r_a % 6 == 1 and eps % 6 == 4, T.float32(0.5), T.Select(r_a % 6 == 1 and eps % 6 == 3, T.float32(-2), T.Select(r_a % 6 == 1 and eps % 6 == 2, T.float32(-1), T.Select(r_a % 6 == 1 and eps % 6 == 1, T.float32(1), T.Select(r_a % 6 == 1 and eps % 6 == 0, T.float32(-1.5), T.Select(r_a % 6 == 0 and eps % 6 == 5, T.float32(0), T.Select(r_a % 6 == 0 and eps % 6 == 4, T.float32(0), T.Select(r_a % 6 == 0 and eps % 6 == 3, T.float32(0), T.Select(r_a % 6 == 0 and eps % 6 == 2, T.float32(0), T.Select(r_a % 6 == 0 and eps % 6 == 1, T.float32(0), T.Select(r_a % 6 == 0 and eps % 6 == 0, T.float32(1), T.float32(0))))))))))))))))))))))))))))))))))))) * T.Select(r_b % 6 == 5 and nu % 6 == 5, T.float32(1), T.Select(r_b % 6 == 5 and nu % 6 == 4, T.float32(0), T.Select(r_b % 6 == 5 and nu % 6 == 3, T.float32(0), T.Select(r_b % 6 == 5 and nu % 6 == 2, T.float32(0), T.Select(r_b % 6 == 5 and nu % 6 == 1, T.float32(0), T.Select(r_b % 6 == 5 and nu % 6 == 0, T.float32(0), T.Select(r_b % 6 == 4 and nu % 6 == 5, T.float32(1.5), T.Select(r_b % 6 == 4 and nu % 6 == 4, T.float32(1), T.Select(r_b % 6 == 4 and nu % 6 == 3, T.float32(1), T.Select(r_b % 6 == 4 and nu % 6 == 2, T.float32(1), T.Select(r_b % 6 == 4 and nu % 6 == 1, T.float32(1), T.Select(r_b % 6 == 4 and nu % 6 == 0, T.float32(1), T.Select(r_b % 6 == 3 and nu % 6 == 5, T.float32(-2), T.Select(r_b % 6 == 3 and nu % 6 == 4, T.float32(-0.5), T.Select(r_b % 6 == 3 and nu % 6 == 3, T.float32(2), T.Select(r_b % 6 == 3 and nu % 6 == 2, T.float32(2.5), T.Select(r_b % 6 == 3 and nu % 6 == 1, T.float32(0.5), T.Select(r_b % 6 == 3 and nu % 6 == 0, T.float32(1.5), T.Select(r_b % 6 == 2 and nu % 6 == 5, T.float32(-1.5), T.Select(r_b % 6 == 2 and nu % 6 == 4, T.float32(-1), T.Select(r_b % 6 == 2 and nu % 6 == 3, T.float32(-1), T.Select(r_b % 6 == 2 and nu % 6 == 2, T.float32(0.5), T.Select(r_b % 6 == 2 and nu % 6 == 1, T.float32(-2.5), T.Select(r_b % 6 == 2 and nu % 6 == 0, T.float32(-2), T.Select(r_b % 6 == 1 and nu % 6 == 5, T.float32(1), T.Select(r_b % 6 == 1 and nu % 6 == 4, T.float32(0.5), T.Select(r_b % 6 == 1 and nu % 6 == 3, T.float32(-2), T.Select(r_b % 6 == 1 and nu % 6 == 2, T.float32(-1), T.Select(r_b % 6 == 1 and nu % 6 == 1, T.float32(1), T.Select(r_b % 6 == 1 and nu % 6 == 0, T.float32(-1.5), T.Select(r_b % 6 == 0 and nu % 6 == 5, T.float32(0), T.Select(r_b % 6 == 0 and nu % 6 == 4, T.float32(0), T.Select(r_b % 6 == 0 and nu % 6 == 3, T.float32(0), T.Select(r_b % 6 == 0 and nu % 6 == 2, T.float32(0), T.Select(r_b % 6 == 0 and nu % 6 == 1, T.float32(0), T.Select(r_b % 6 == 0 and nu % 6 == 0, T.float32(1), T.float32(0))))))))))))))))))))))))))))))))))))) for ax0, ax1, ax2, ax3 in T.grid(6, 6, 1, 1): with T.block("data_pack_local"): T.where(i2_0_i3_0_i2_1_i3_1_fused_0 * 1024 + i2_0_i3_0_i2_1_i3_1_fused_1 < 1152) v0, v1 = T.axis.remap("SS", [ax0, ax1]) v2 = T.axis.spatial(9, (i2_0_i3_0_i2_1_i3_1_fused_0 * 1024 + i2_0_i3_0_i2_1_i3_1_fused_1) // 384 * 3 + (i2_0_i3_0_i2_1_i3_1_fused_0 * 1024 + i2_0_i3_0_i2_1_i3_1_fused_1) % 24 // 8 + ax2) v3 = T.axis.spatial(128, (i2_0_i3_0_i2_1_i3_1_fused_0 * 1024 + i2_0_i3_0_i2_1_i3_1_fused_1) % 384 // 24 * 8 + (i2_0_i3_0_i2_1_i3_1_fused_0 * 1024 + i2_0_i3_0_i2_1_i3_1_fused_1) % 8 + ax3) T.reads(data_pack_local[v0, v1, v2, v3]) T.writes(data_pack[v0, v1, v2, v3]) data_pack[v0, v1, v2, v3] = data_pack_local[v0, v1, v2, v3] for i0_0_i1_0_i2_0_i3_0_fused in T.thread_binding(96, thread="blockIdx.x"): for i0_1_i1_1_i2_1_i3_1_fused in T.thread_binding(4, thread="vthread.x"): for i0_2_i1_2_i2_2_i3_2_fused in T.thread_binding(27, thread="threadIdx.x"): for i4_0 in T.serial(8): for ax0_ax1_ax2_ax3_fused in T.serial(1728): with T.block("data_pack_shared"): v0 = T.axis.spatial(6, i0_0_i1_0_i2_0_i3_0_fused // 32 * 2 + ax0_ax1_ax2_ax3_fused // 864) v1 = T.axis.spatial(6, ax0_ax1_ax2_ax3_fused % 864 // 144) v2 = T.axis.spatial(9, ax0_ax1_ax2_ax3_fused % 144 // 16) v3 = T.axis.spatial(128, i4_0 * 16 + ax0_ax1_ax2_ax3_fused % 16) T.reads(data_pack[v0, v1, v2, v3]) T.writes(data_pack_shared[v0, v1, v2, v3]) T.block_attr({"meta_schedule.cooperative_fetch":1}) data_pack_shared[v0, v1, v2, v3] = data_pack[v0, v1, v2, v3] for ax0_ax1_ax2_ax3_fused in T.serial(768): with T.block("weight_shared"): v0 = T.axis.spatial(6, i0_0_i1_0_i2_0_i3_0_fused // 32 * 2 + ax0_ax1_ax2_ax3_fused // 384) v1 = T.axis.spatial(6, ax0_ax1_ax2_ax3_fused % 384 // 64) v2 = T.axis.spatial(128, i0_0_i1_0_i2_0_i3_0_fused % 32 * 4 + ax0_ax1_ax2_ax3_fused % 64 // 16) v3 = T.axis.spatial(128, i4_0 * 16 + ax0_ax1_ax2_ax3_fused % 16) T.reads(weight[v0, v1, v2, v3]) T.writes(weight_shared[v0, v1, v2, v3]) T.block_attr({"meta_schedule.cooperative_fetch":3}) weight_shared[v0, v1, v2, v3] = weight[v0, v1, v2, v3] for i4_1, i0_3, i1_3, i2_3, i3_3, i4_2, i0_4, i1_4, i2_4, i3_4 in T.grid(1, 2, 1, 1, 2, 16, 1, 1, 1, 1): with T.block("bgemm"): eps = T.axis.spatial(6, i0_0_i1_0_i2_0_i3_0_fused // 32 * 2 + i0_3 + i0_4) nu = T.axis.spatial(6, i1_3 + i1_4 + i0_1_i1_1_i2_1_i3_1_fused // 2 * 3 + i0_2_i1_2_i2_2_i3_2_fused // 9) p = T.axis.spatial(9, i0_2_i1_2_i2_2_i3_2_fused % 9 + i2_3 + i2_4) co = T.axis.spatial(128, i3_4 + i0_0_i1_0_i2_0_i3_0_fused % 32 * 4 + i0_1_i1_1_i2_1_i3_1_fused % 2 * 2 + i3_3) ci = T.axis.reduce(128, i4_0 * 16 + i4_1 * 16 + i4_2) T.reads(data_pack_shared[eps, nu, p, ci], weight_shared[eps, nu, co, ci]) T.writes(bgemm_local[eps, nu, p, co]) T.block_attr({"meta_schedule.thread_extent_high_inclusive":1024, "meta_schedule.thread_extent_low_inclusive":32, "meta_schedule.tiling_structure":"SSSRRSRS", "meta_schedule.write_cache_level":[3]}) with T.init(): bgemm_local[eps, nu, p, co] = T.float32(0) bgemm_local[eps, nu, p, co] = bgemm_local[eps, nu, p, co] + data_pack_shared[eps, nu, p, ci] * weight_shared[eps, nu, co, ci] for ax0, ax1, ax2, ax3 in T.grid(2, 1, 1, 2): with T.block("bgemm_local"): v0 = T.axis.spatial(6, i0_0_i1_0_i2_0_i3_0_fused // 32 * 2 + ax0) v1 = T.axis.spatial(6, i0_1_i1_1_i2_1_i3_1_fused // 2 * 3 + i0_2_i1_2_i2_2_i3_2_fused // 9 + ax1) v2 = T.axis.spatial(9, i0_2_i1_2_i2_2_i3_2_fused % 9 + ax2) v3 = T.axis.spatial(128, i0_0_i1_0_i2_0_i3_0_fused % 32 * 4 + i0_1_i1_1_i2_1_i3_1_fused % 2 * 2 + ax3) T.reads(bgemm_local[v0, v1, v2, v3]) T.writes(bgemm[v0, v1, v2, v3]) bgemm[v0, v1, v2, v3] = bgemm_local[v0, v1, v2, v3] for i2_0_i3_0_i2_1_i3_1_fused_0 in T.thread_binding(18, thread="blockIdx.x"): for i2_0_i3_0_i2_1_i3_1_fused_1 in T.thread_binding(64, thread="threadIdx.x"): for i0 in T.unroll(4): for i1 in T.unroll(4): for i4 in T.unroll(6): for i5 in T.unroll(6): with T.block("inverse"): vh, vw = T.axis.remap("SS", [i0, i1]) p = T.axis.spatial(9, (i2_0_i3_0_i2_1_i3_1_fused_0 * 64 + i2_0_i3_0_i2_1_i3_1_fused_1) // 384 * 3 + (i2_0_i3_0_i2_1_i3_1_fused_0 * 64 + i2_0_i3_0_i2_1_i3_1_fused_1) % 24 // 8) co = T.axis.spatial(128, (i2_0_i3_0_i2_1_i3_1_fused_0 * 64 + i2_0_i3_0_i2_1_i3_1_fused_1) % 384 // 24 * 8 + (i2_0_i3_0_i2_1_i3_1_fused_0 * 64 + i2_0_i3_0_i2_1_i3_1_fused_1) % 8) r_a, r_b = T.axis.remap("RR", [i4, i5]) T.reads(bgemm[r_a, r_b, p, co]) T.writes(inverse[vh, vw, p, co]) T.block_attr({"schedule_rule":"conv2d_nhwc_winograd_inverse"}) with T.init(): inverse[vh, vw, p, co] = T.float32(0) inverse[vh, vw, p, co] = inverse[vh, vw, p, co] + bgemm[r_a, r_b, p, co] * T.Select(r_a % 6 == 5 and vh % 4 == 3, T.float32(1), T.Select(r_a % 6 == 5 and vh % 4 == 2, T.float32(0), T.Select(r_a % 6 == 5 and vh % 4 == 1, T.float32(0), T.Select(r_a % 6 == 5 and vh % 4 == 0, T.float32(0), T.Select(r_a % 6 == 4 and vh % 4 == 3, T.float32(-8), T.Select(r_a % 6 == 4 and vh % 4 == 2, T.float32(4), T.Select(r_a % 6 == 4 and vh % 4 == 1, T.float32(-2), T.Select(r_a % 6 == 4 and vh % 4 == 0, T.float32(1), T.Select(r_a % 6 == 3 and vh % 4 == 3, T.float32(0.125), T.Select(r_a % 6 == 3 and vh % 4 == 2, T.float32(0.25), T.Select(r_a % 6 == 3 and vh % 4 == 1, T.float32(0.5), T.Select(r_a % 6 == 3 and vh % 4 == 0, T.float32(1), T.Select(r_a % 6 == 2 and vh % 4 == 3, T.float32(1), T.Select(r_a % 6 == 2 and vh % 4 == 2, T.float32(1), T.Select(r_a % 6 == 2 and vh % 4 == 1, T.float32(1), T.Select(r_a % 6 == 2 and vh % 4 == 0, T.float32(1), T.Select(r_a % 6 == 1 and vh % 4 == 3, T.float32(-1), T.Select(r_a % 6 == 1 and vh % 4 == 2, T.float32(1), T.Select(r_a % 6 == 1 and vh % 4 == 1, T.float32(-1), T.Select(r_a % 6 == 1 and vh % 4 == 0, T.float32(1), T.Select(r_a % 6 == 0 and vh % 4 == 3, T.float32(0), T.Select(r_a % 6 == 0 and vh % 4 == 2, T.float32(0), T.Select(r_a % 6 == 0 and vh % 4 == 1, T.float32(0), T.Select(r_a % 6 == 0 and vh % 4 == 0, T.float32(1), T.float32(0))))))))))))))))))))))))) * T.Select(r_b % 6 == 5 and vw % 4 == 3, T.float32(1), T.Select(r_b % 6 == 5 and vw % 4 == 2, T.float32(0), T.Select(r_b % 6 == 5 and vw % 4 == 1, T.float32(0), T.Select(r_b % 6 == 5 and vw % 4 == 0, T.float32(0), T.Select(r_b % 6 == 4 and vw % 4 == 3, T.float32(-8), T.Select(r_b % 6 == 4 and vw % 4 == 2, T.float32(4), T.Select(r_b % 6 == 4 and vw % 4 == 1, T.float32(-2), T.Select(r_b % 6 == 4 and vw % 4 == 0, T.float32(1), T.Select(r_b % 6 == 3 and vw % 4 == 3, T.float32(0.125), T.Select(r_b % 6 == 3 and vw % 4 == 2, T.float32(0.25), T.Select(r_b % 6 == 3 and vw % 4 == 1, T.float32(0.5), T.Select(r_b % 6 == 3 and vw % 4 == 0, T.float32(1), T.Select(r_b % 6 == 2 and vw % 4 == 3, T.float32(1), T.Select(r_b % 6 == 2 and vw % 4 == 2, T.float32(1), T.Select(r_b % 6 == 2 and vw % 4 == 1, T.float32(1), T.Select(r_b % 6 == 2 and vw % 4 == 0, T.float32(1), T.Select(r_b % 6 == 1 and vw % 4 == 3, T.float32(-1), T.Select(r_b % 6 == 1 and vw % 4 == 2, T.float32(1), T.Select(r_b % 6 == 1 and vw % 4 == 1, T.float32(-1), T.Select(r_b % 6 == 1 and vw % 4 == 0, T.float32(1), T.Select(r_b % 6 == 0 and vw % 4 == 3, T.float32(0), T.Select(r_b % 6 == 0 and vw % 4 == 2, T.float32(0), T.Select(r_b % 6 == 0 and vw % 4 == 1, T.float32(0), T.Select(r_b % 6 == 0 and vw % 4 == 0, T.float32(1), T.float32(0))))))))))))))))))))))))) for i0_i1_i2_i3_fused_0 in T.thread_binding(144, thread="blockIdx.x"): for i0_i1_i2_i3_fused_1 in T.thread_binding(128, thread="threadIdx.x"): with T.block("conv2d_winograd"): n = T.axis.spatial(1, 0) h = T.axis.spatial(12, (i0_i1_i2_i3_fused_0 * 128 + i0_i1_i2_i3_fused_1) // 1536) w = T.axis.spatial(12, (i0_i1_i2_i3_fused_0 * 128 + i0_i1_i2_i3_fused_1) % 1536 // 128) co = T.axis.spatial(128, (i0_i1_i2_i3_fused_0 * 128 + i0_i1_i2_i3_fused_1) % 128) T.reads(inverse[h % 4, w % 4, n * 9 + h // 4 * 3 + w // 4, co]) T.writes(conv2d_winograd[n, h, w, co]) conv2d_winograd[n, h, w, co] = inverse[h % 4, w % 4, n * 9 + h // 4 * 3 + w // 4, co] # fmt: on decision_0 = [ ("SamplePerfectTile", [3, 3]), ("SamplePerfectTile", [16, 8]), ("SampleCategorical", 1), ("SamplePerfectTile", [3, 3]), ("SamplePerfectTile", [16, 8]), ("SampleCategorical", 5), ("SamplePerfectTile", [3, 1, 1, 2, 1]), ("SamplePerfectTile", [1, 2, 3, 1, 1]), ("SamplePerfectTile", [1, 1, 9, 1, 1]), ("SamplePerfectTile", [32, 2, 1, 2, 1]), ("SamplePerfectTile", [8, 1, 16]), ("SampleCategorical", 0), ("SampleCategorical", 2), ("SampleCategorical", 1), ("SampleCategorical", 2), ] with _target(): mod = create_te_workload("C2D_WIN_NHWC", 0) actual = _design_space(mod) check_sketches( mod, sketches=actual, expected_mods=[cuda_nhwc_0], expected_decisions=[decision_0], ) def test_cuda_nchw(): # fmt: off @T.prim_func def cuda_nchw_0(data: T.Buffer[(1, 64, 56, 56), "float32"], weight: T.Buffer[(6, 6, 64, 64), "float32"], conv2d_winograd: T.Buffer[(1, 64, 56, 56), "float32"]) -> None: # function attr dict T.func_attr({"global_symbol": "main", "tir.noalias": True, "layout_free_buffers": [1]}) # body with T.block("root"): T.reads() T.writes() T.block_attr({"meta_schedule.unroll_explicit":16}) input_tile_local = T.alloc_buffer([64, 196, 6, 6], dtype="float32", scope="local") data_pack = T.alloc_buffer([6, 6, 64, 196], dtype="float32") bgemm = T.alloc_buffer([6, 6, 64, 196], dtype="float32") inverse_local = T.alloc_buffer([64, 196, 4, 4], dtype="float32", scope="local") data_pack_local = T.alloc_buffer([6, 6, 64, 196], dtype="float32", scope="local") bgemm_local = T.alloc_buffer([6, 6, 64, 196], dtype="float32", scope="local") data_pack_shared = T.alloc_buffer([6, 6, 64, 196], dtype="float32", scope="shared") weight_shared = T.alloc_buffer([6, 6, 64, 64], dtype="float32", scope="shared") for i2_i3_fused_0 in T.thread_binding(25, thread="blockIdx.x"): for i2_i3_fused_1 in T.thread_binding(512, thread="threadIdx.x"): for ax0, ax1, ax2, ax3 in T.grid(1, 1, 6, 6): with T.block("input_tile"): T.where(i2_i3_fused_0 * 512 + i2_i3_fused_1 < 12544) ci = T.axis.spatial(64, (i2_i3_fused_0 * 512 + i2_i3_fused_1) // 196 + ax0) p = T.axis.spatial(196, (i2_i3_fused_0 * 120 + i2_i3_fused_1) % 196 + ax1) eps, nu = T.axis.remap("SS", [ax2, ax3]) T.reads(data[p // 196, ci, p % 196 // 14 * 4 + eps - 1, p % 14 * 4 + nu - 1]) T.writes(input_tile_local[ci, p, eps, nu]) T.block_attr({"schedule_rule":"None"}) input_tile_local[ci, p, eps, nu] = T.if_then_else(1 <= p % 196 // 14 * 4 + eps and p % 196 // 14 * 4 + eps < 57 and 1 <= p % 14 * 4 + nu and p % 14 * 4 + nu < 57, data[p // 196, ci, p % 196 // 14 * 4 + eps - 1, p % 14 * 4 + nu - 1], T.float32(0), dtype="float32") for i0 in T.unroll(6): for i1 in T.unroll(6): for i4 in T.unroll(6): for i5 in T.unroll(6): with T.block("data_pack"): T.where(i2_i3_fused_0 * 512 + i2_i3_fused_1 < 12544) eps, nu = T.axis.remap("SS", [i0, i1]) ci = T.axis.spatial(64, (i2_i3_fused_0 * 512 + i2_i3_fused_1) // 196) p = T.axis.spatial(196, (i2_i3_fused_0 * 512 + i2_i3_fused_1) % 196) r_a, r_b = T.axis.remap("RR", [i4, i5]) T.reads(input_tile_local[ci, p, r_a, r_b]) T.writes(data_pack_local[eps, nu, ci, p]) T.block_attr({"schedule_rule":"conv2d_nchw_winograd_data_pack"}) with T.init(): data_pack_local[eps, nu, ci, p] = T.float32(0) data_pack_local[eps, nu, ci, p] = data_pack_local[eps, nu, ci, p] + input_tile_local[ci, p, r_a, r_b] * T.Select(r_a % 6 == 5 and eps % 6 == 5, T.float32(1), T.Select(r_a % 6 == 5 and eps % 6 == 4, T.float32(0), T.Select(r_a % 6 == 5 and eps % 6 == 3, T.float32(0), T.Select(r_a % 6 == 5 and eps % 6 == 2, T.float32(0), T.Select(r_a % 6 == 5 and eps % 6 == 1, T.float32(0), T.Select(r_a % 6 == 5 and eps % 6 == 0, T.float32(0), T.Select(r_a % 6 == 4 and eps % 6 == 5, T.float32(1.5), T.Select(r_a % 6 == 4 and eps % 6 == 4, T.float32(1), T.Select(r_a % 6 == 4 and eps % 6 == 3, T.float32(1), T.Select(r_a % 6 == 4 and eps % 6 == 2, T.float32(1), T.Select(r_a % 6 == 4 and eps % 6 == 1, T.float32(1), T.Select(r_a % 6 == 4 and eps % 6 == 0, T.float32(1), T.Select(r_a % 6 == 3 and eps % 6 == 5, T.float32(-2), T.Select(r_a % 6 == 3 and eps % 6 == 4, T.float32(-0.5), T.Select(r_a % 6 == 3 and eps % 6 == 3, T.float32(2), T.Select(r_a % 6 == 3 and eps % 6 == 2, T.float32(2.5), T.Select(r_a % 6 == 3 and eps % 6 == 1, T.float32(0.5), T.Select(r_a % 6 == 3 and eps % 6 == 0, T.float32(1.5), T.Select(r_a % 6 == 2 and eps % 6 == 5, T.float32(-1.5), T.Select(r_a % 6 == 2 and eps % 6 == 4, T.float32(-1), T.Select(r_a % 6 == 2 and eps % 6 == 3, T.float32(-1), T.Select(r_a % 6 == 2 and eps % 6 == 2, T.float32(0.5), T.Select(r_a % 6 == 2 and eps % 6 == 1, T.float32(-2.5), T.Select(r_a % 6 == 2 and eps % 6 == 0, T.float32(-2), T.Select(r_a % 6 == 1 and eps % 6 == 5, T.float32(1), T.Select(r_a % 6 == 1 and eps % 6 == 4, T.float32(0.5), T.Select(r_a % 6 == 1 and eps % 6 == 3, T.float32(-2), T.Select(r_a % 6 == 1 and eps % 6 == 2, T.float32(-1), T.Select(r_a % 6 == 1 and eps % 6 == 1, T.float32(1), T.Select(r_a % 6 == 1 and eps % 6 == 0, T.float32(-1.5), T.Select(r_a % 6 == 0 and eps % 6 == 5, T.float32(0), T.Select(r_a % 6 == 0 and eps % 6 == 4, T.float32(0), T.Select(r_a % 6 == 0 and eps % 6 == 3, T.float32(0), T.Select(r_a % 6 == 0 and eps % 6 == 2, T.float32(0), T.Select(r_a % 6 == 0 and eps % 6 == 1, T.float32(0), T.Select(r_a % 6 == 0 and eps % 6 == 0, T.float32(1), T.float32(0))))))))))))))))))))))))))))))))))))) * T.Select(r_b % 6 == 5 and nu % 6 == 5, T.float32(1), T.Select(r_b % 6 == 5 and nu % 6 == 4, T.float32(0), T.Select(r_b % 6 == 5 and nu % 6 == 3, T.float32(0), T.Select(r_b % 6 == 5 and nu % 6 == 2, T.float32(0), T.Select(r_b % 6 == 5 and nu % 6 == 1, T.float32(0), T.Select(r_b % 6 == 5 and nu % 6 == 0, T.float32(0), T.Select(r_b % 6 == 4 and nu % 6 == 5, T.float32(1.5), T.Select(r_b % 6 == 4 and nu % 6 == 4, T.float32(1), T.Select(r_b % 6 == 4 and nu % 6 == 3, T.float32(1), T.Select(r_b % 6 == 4 and nu % 6 == 2, T.float32(1), T.Select(r_b % 6 == 4 and nu % 6 == 1, T.float32(1), T.Select(r_b % 6 == 4 and nu % 6 == 0, T.float32(1), T.Select(r_b % 6 == 3 and nu % 6 == 5, T.float32(-2), T.Select(r_b % 6 == 3 and nu % 6 == 4, T.float32(-0.5), T.Select(r_b % 6 == 3 and nu % 6 == 3, T.float32(2), T.Select(r_b % 6 == 3 and nu % 6 == 2, T.float32(2.5), T.Select(r_b % 6 == 3 and nu % 6 == 1, T.float32(0.5), T.Select(r_b % 6 == 3 and nu % 6 == 0, T.float32(1.5), T.Select(r_b % 6 == 2 and nu % 6 == 5, T.float32(-1.5), T.Select(r_b % 6 == 2 and nu % 6 == 4, T.float32(-1), T.Select(r_b % 6 == 2 and nu % 6 == 3, T.float32(-1), T.Select(r_b % 6 == 2 and nu % 6 == 2, T.float32(0.5), T.Select(r_b % 6 == 2 and nu % 6 == 1, T.float32(-2.5), T.Select(r_b % 6 == 2 and nu % 6 == 0, T.float32(-2), T.Select(r_b % 6 == 1 and nu % 6 == 5, T.float32(1), T.Select(r_b % 6 == 1 and nu % 6 == 4, T.float32(0.5), T.Select(r_b % 6 == 1 and nu % 6 == 3, T.float32(-2), T.Select(r_b % 6 == 1 and nu % 6 == 2, T.float32(-1), T.Select(r_b % 6 == 1 and nu % 6 == 1, T.float32(1), T.Select(r_b % 6 == 1 and nu % 6 == 0, T.float32(-1.5), T.Select(r_b % 6 == 0 and nu % 6 == 5, T.float32(0), T.Select(r_b % 6 == 0 and nu % 6 == 4, T.float32(0), T.Select(r_b % 6 == 0 and nu % 6 == 3, T.float32(0), T.Select(r_b % 6 == 0 and nu % 6 == 2, T.float32(0), T.Select(r_b % 6 == 0 and nu % 6 == 1, T.float32(0), T.Select(r_b % 6 == 0 and nu % 6 == 0, T.float32(1), T.float32(0))))))))))))))))))))))))))))))))))))) for ax0, ax1, ax2, ax3 in T.grid(6, 6, 1, 1): with T.block("data_pack_local"): T.where(i2_i3_fused_0 * 512 + i2_i3_fused_1 < 12544) v0, v1 = T.axis.remap("SS", [ax0, ax1]) v2 = T.axis.spatial(64, (i2_i3_fused_0 * 512 + i2_i3_fused_1) // 196 + ax2) v3 = T.axis.spatial(196, (i2_i3_fused_0 * 120 + i2_i3_fused_1) % 196 + ax3) T.reads(data_pack_local[v0, v1, v2, v3]) T.writes(data_pack[v0, v1, v2, v3]) data_pack[v0, v1, v2, v3] = data_pack_local[v0, v1, v2, v3] for i0_0_i1_0_i2_0_i3_0_fused in T.thread_binding(14, thread="blockIdx.x"): for i0_1_i1_1_i2_1_i3_1_fused in T.thread_binding(224, thread="vthread.x"): for i0_2_i1_2_i2_2_i3_2_fused in T.thread_binding(2, thread="threadIdx.x"): for i4_0 in T.serial(2): for ax0_ax1_ax2_ax3_fused in T.serial(32256): with T.block("data_pack_shared"): v0 = T.axis.spatial(6, ax0_ax1_ax2_ax3_fused // 5376) v1 = T.axis.spatial(6, ax0_ax1_ax2_ax3_fused % 5376 // 896) v2 = T.axis.spatial(64, i4_0 * 32 + ax0_ax1_ax2_ax3_fused % 896 // 28) v3 = T.axis.spatial(196, i0_0_i1_0_i2_0_i3_0_fused % 7 * 28 + ax0_ax1_ax2_ax3_fused % 28) T.reads(data_pack[v0, v1, v2, v3]) T.writes(data_pack_shared[v0, v1, v2, v3]) T.block_attr({"meta_schedule.cooperative_fetch":4}) data_pack_shared[v0, v1, v2, v3] = data_pack[v0, v1, v2, v3] for ax0_ax1_ax2_ax3_fused in T.serial(36864): with T.block("weight_shared"): v0 = T.axis.spatial(6, ax0_ax1_ax2_ax3_fused // 6144) v1 = T.axis.spatial(6, ax0_ax1_ax2_ax3_fused % 6144 // 1024) v2 = T.axis.spatial(64, i4_0 * 32 + ax0_ax1_ax2_ax3_fused % 1024 // 32) v3 = T.axis.spatial(64, i0_0_i1_0_i2_0_i3_0_fused // 7 * 32 + ax0_ax1_ax2_ax3_fused % 32) T.reads(weight[v0, v1, v2, v3]) T.writes(weight_shared[v0, v1, v2, v3]) T.block_attr({"meta_schedule.cooperative_fetch":3}) weight_shared[v0, v1, v2, v3] = weight[v0, v1, v2, v3] for i4_1, i0_3, i1_3, i2_3, i3_3, i4_2, i0_4, i1_4, i2_4, i3_4 in T.grid(16, 2, 3, 1, 4, 2, 3, 1, 1, 1): with T.block("bgemm"): eps = T.axis.spatial(6, i0_3 * 3 + i0_4) nu = T.axis.spatial(6, i1_4 + i0_1_i1_1_i2_1_i3_1_fused // 112 * 3 + i1_3) co = T.axis.spatial(64, i0_0_i1_0_i2_0_i3_0_fused // 7 * 32 + i0_1_i1_1_i2_1_i3_1_fused % 112 // 7 * 2 + i0_2_i1_2_i2_2_i3_2_fused + i2_3 + i2_4) p = T.axis.spatial(196, i3_4 + i0_0_i1_0_i2_0_i3_0_fused % 7 * 28 + i0_1_i1_1_i2_1_i3_1_fused % 7 * 4 + i3_3) ci = T.axis.reduce(64, i4_0 * 32 + i4_1 * 2 + i4_2) T.reads(data_pack_shared[eps, nu, ci, p], weight_shared[eps, nu, ci, co]) T.writes(bgemm_local[eps, nu, co, p]) T.block_attr({"meta_schedule.thread_extent_high_inclusive":1024, "meta_schedule.thread_extent_low_inclusive":32, "meta_schedule.tiling_structure":"SSSRRSRS"}) with T.init(): bgemm_local[eps, nu, co, p] = T.float32(0) bgemm_local[eps, nu, co, p] = bgemm_local[eps, nu, co, p] + data_pack_shared[eps, nu, ci, p] * weight_shared[eps, nu, ci, co] for ax0, ax1, ax2, ax3 in T.grid(6, 3, 1, 4): with T.block("bgemm_local"): v0 = T.axis.spatial(6, ax0) v1 = T.axis.spatial(6, i0_1_i1_1_i2_1_i3_1_fused // 112 * 3 + ax1) v2 = T.axis.spatial(64, i0_0_i1_0_i2_0_i3_0_fused // 7 * 32 + i0_1_i1_1_i2_1_i3_1_fused % 112 // 7 * 2 + i0_2_i1_2_i2_2_i3_2_fused + ax2) v3 = T.axis.spatial(196, i0_0_i1_0_i2_0_i3_0_fused % 7 * 28 + i0_1_i1_1_i2_1_i3_1_fused % 7 * 4 + ax3) T.reads(bgemm_local[v0, v1, v2, v3]) T.writes(bgemm[v0, v1, v2, v3]) bgemm[v0, v1, v2, v3] = bgemm_local[v0, v1, v2, v3] for i0_i1_i2_0_i3_0_fused_0 in T.thread_binding(196, thread="blockIdx.x"): for i0_i1_i2_0_i3_0_fused_1 in T.thread_binding(64, thread="threadIdx.x"): for ax0, ax1 in T.grid(1, 1): for ax2 in T.unroll(4): for ax3 in T.unroll(4): for ax4 in T.unroll(6): for ax5 in T.unroll(6): with T.block("inverse"): co = T.axis.spatial(64, (i0_i1_i2_0_i3_0_fused_0 * 64 + i0_i1_i2_0_i3_0_fused_1) // 196 + ax0) p = T.axis.spatial(196, (i0_i1_i2_0_i3_0_fused_0 * 64 + i0_i1_i2_0_i3_0_fused_1) % 196 // 14 * 14 + (i0_i1_i2_0_i3_0_fused_0 * 64 + i0_i1_i2_0_i3_0_fused_1) % 14 + ax1) vh, vw, r_a, r_b = T.axis.remap("SSRR", [ax2, ax3, ax4, ax5]) T.reads(bgemm[r_a, r_b, co, p]) T.writes(inverse_local[co, p, vh, vw]) T.block_attr({"schedule_rule":"conv2d_nchw_winograd_inverse"}) with T.init(): inverse_local[co, p, vh, vw] = T.float32(0) inverse_local[co, p, vh, vw] = inverse_local[co, p, vh, vw] + bgemm[r_a, r_b, co, p] * T.Select(r_a % 6 == 5 and vh % 4 == 3, T.float32(1), T.Select(r_a % 6 == 5 and vh % 4 == 2, T.float32(0), T.Select(r_a % 6 == 5 and vh % 4 == 1, T.float32(0), T.Select(r_a % 6 == 5 and vh % 4 == 0, T.float32(0), T.Select(r_a % 6 == 4 and vh % 4 == 3, T.float32(-8), T.Select(r_a % 6 == 4 and vh % 4 == 2, T.float32(4), T.Select(r_a % 6 == 4 and vh % 4 == 1, T.float32(-2), T.Select(r_a % 6 == 4 and vh % 4 == 0, T.float32(1), T.Select(r_a % 6 == 3 and vh % 4 == 3, T.float32(0.125), T.Select(r_a % 6 == 3 and vh % 4 == 2, T.float32(0.25), T.Select(r_a % 6 == 3 and vh % 4 == 1, T.float32(0.5), T.Select(r_a % 6 == 3 and vh % 4 == 0, T.float32(1), T.Select(r_a % 6 == 2 and vh % 4 == 3, T.float32(1), T.Select(r_a % 6 == 2 and vh % 4 == 2, T.float32(1), T.Select(r_a % 6 == 2 and vh % 4 == 1, T.float32(1), T.Select(r_a % 6 == 2 and vh % 4 == 0, T.float32(1), T.Select(r_a % 6 == 1 and vh % 4 == 3, T.float32(-1), T.Select(r_a % 6 == 1 and vh % 4 == 2, T.float32(1), T.Select(r_a % 6 == 1 and vh % 4 == 1, T.float32(-1), T.Select(r_a % 6 == 1 and vh % 4 == 0, T.float32(1), T.Select(r_a % 6 == 0 and vh % 4 == 3, T.float32(0), T.Select(r_a % 6 == 0 and vh % 4 == 2, T.float32(0), T.Select(r_a % 6 == 0 and vh % 4 == 1, T.float32(0), T.Select(r_a % 6 == 0 and vh % 4 == 0, T.float32(1), T.float32(0))))))))))))))))))))))))) * T.Select(r_b % 6 == 5 and vw % 4 == 3, T.float32(1), T.Select(r_b % 6 == 5 and vw % 4 == 2, T.float32(0), T.Select(r_b % 6 == 5 and vw % 4 == 1, T.float32(0), T.Select(r_b % 6 == 5 and vw % 4 == 0, T.float32(0), T.Select(r_b % 6 == 4 and vw % 4 == 3, T.float32(-8), T.Select(r_b % 6 == 4 and vw % 4 == 2, T.float32(4), T.Select(r_b % 6 == 4 and vw % 4 == 1, T.float32(-2), T.Select(r_b % 6 == 4 and vw % 4 == 0, T.float32(1), T.Select(r_b % 6 == 3 and vw % 4 == 3, T.float32(0.125), T.Select(r_b % 6 == 3 and vw % 4 == 2, T.float32(0.25), T.Select(r_b % 6 == 3 and vw % 4 == 1, T.float32(0.5), T.Select(r_b % 6 == 3 and vw % 4 == 0, T.float32(1), T.Select(r_b % 6 == 2 and vw % 4 == 3, T.float32(1), T.Select(r_b % 6 == 2 and vw % 4 == 2, T.float32(1), T.Select(r_b % 6 == 2 and vw % 4 == 1, T.float32(1), T.Select(r_b % 6 == 2 and vw % 4 == 0, T.float32(1), T.Select(r_b % 6 == 1 and vw % 4 == 3, T.float32(-1), T.Select(r_b % 6 == 1 and vw % 4 == 2, T.float32(1), T.Select(r_b % 6 == 1 and vw % 4 == 1, T.float32(-1), T.Select(r_b % 6 == 1 and vw % 4 == 0, T.float32(1), T.Select(r_b % 6 == 0 and vw % 4 == 3, T.float32(0), T.Select(r_b % 6 == 0 and vw % 4 == 2, T.float32(0), T.Select(r_b % 6 == 0 and vw % 4 == 1, T.float32(0), T.Select(r_b % 6 == 0 and vw % 4 == 0, T.float32(1), T.float32(0))))))))))))))))))))))))) for i2_1, i3_1 in T.grid(4, 4): with T.block("conv2d_winograd"): n = T.axis.spatial(1, 0) co = T.axis.spatial(64, (i0_i1_i2_0_i3_0_fused_0 * 64 + i0_i1_i2_0_i3_0_fused_1) // 196) h = T.axis.spatial(56, (i0_i1_i2_0_i3_0_fused_0 * 64 + i0_i1_i2_0_i3_0_fused_1) % 196 // 14 * 4 + i2_1) w = T.axis.spatial(56, (i0_i1_i2_0_i3_0_fused_0 * 64 + i0_i1_i2_0_i3_0_fused_1) % 14 * 4 + i3_1) T.reads(inverse_local[co, n * 196 + h // 4 * 14 + w // 4, h % 4, w % 4]) T.writes(conv2d_winograd[n, co, h, w]) conv2d_winograd[n, co, h, w] = inverse_local[co, n * 196 + h // 4 * 14 + w // 4, h % 4, w % 4] # fmt: on decision_0 = [ ("SampleCategorical", 4), ("SamplePerfectTile", [1, 1, 1, 2, 3]), ("SamplePerfectTile", [1, 2, 1, 3, 1]), ("SamplePerfectTile", [2, 16, 2, 1, 1]), ("SamplePerfectTile", [7, 7, 1, 4, 1]), ("SamplePerfectTile", [2, 16, 2]), ("SampleCategorical", 3), ("SampleCategorical", 2), ("SampleCategorical", 1), ("SampleCategorical", 1), ] with _target(): mod = create_te_workload("C2D_WIN_NCHW", 0) actual = _design_space(mod) check_sketches( mod, sketches=actual, expected_mods=[cuda_nchw_0], expected_decisions=[decision_0], debug_mask=0, ) if __name__ == "__main__": test_cuda_nhwc() test_cuda_nchw()
https://github.com/zk-ml/tachikoma
tests/python/unittest/test_meta_schedule_space_generator.py
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. """ Test Meta Schedule SpaceGenerator """ # pylint: disable=missing-function-docstring import math import pytest import tvm import tvm.testing from tvm._ffi.base import TVMError from tvm.meta_schedule.space_generator import ( PySpaceGenerator, ScheduleFn, SpaceGeneratorUnion, ) from tvm.meta_schedule.tune_context import TuneContext from tvm.meta_schedule.utils import derived_object from tvm.script import tir as T from tvm.tir.schedule import Schedule # pylint: disable=invalid-name,no-member,line-too-long,too-many-nested-blocks,no-self-argument # fmt: off @tvm.script.ir_module class Matmul: @T.prim_func def main(a: T.handle, b: T.handle, c: T.handle) -> None: T.func_attr({"global_symbol": "main"}) A = T.match_buffer(a, (1024, 1024), "float32") B = T.match_buffer(b, (1024, 1024), "float32") C = T.match_buffer(c, (1024, 1024), "float32") for i, j, k in T.grid(1024, 1024, 1024): with T.block("matmul"): vi, vj, vk = T.axis.remap("SSR", [i, j, k]) with T.init(): C[vi, vj] = 0.0 C[vi, vj] = C[vi, vj] + A[vi, vk] * B[vk, vj] # fmt: on # pylint: enable=invalid-name,no-member,line-too-long,too-many-nested-blocks,no-self-argument def schedule_matmul(sch: Schedule): block = sch.get_block("matmul") i, j, k = sch.get_loops(block=block) # TODO(@zxybazh): Change to `sample_perfect_tile` after upstreaming i_0, i_1, i_2, i_3 = sch.split(loop=i, factors=[2, 4, 64, 2]) j_0, j_1, j_2, j_3 = sch.split(loop=j, factors=[4, 64, 2, 2]) k_0, k_1 = sch.split(loop=k, factors=[32, 32]) sch.reorder(i_0, j_0, i_1, j_1, k_0, i_2, j_2, k_1, i_3, j_3) def _check_correct(schedule: Schedule): trace = schedule.trace for inst in trace.decisions: assert math.prod(trace.decisions[inst]) == 1024 def test_meta_schedule_space_generator_schedule_fn(): mod = Matmul space_generator = ScheduleFn(sch_fn=schedule_matmul) design_spaces = space_generator.generate_design_space(mod) assert len(design_spaces) == 1 (schedule,) = design_spaces _check_correct(schedule) def test_meta_schedule_design_space_generator_union(): mod = Matmul space_generator = ScheduleFn(sch_fn=schedule_matmul) space_generator_union = SpaceGeneratorUnion([space_generator, space_generator]) design_spaces = space_generator_union.generate_design_space(mod) assert len(design_spaces) == 2 for design_space in design_spaces: _check_correct(design_space) def test_meta_schedule_design_space_generator_NIE(): @derived_object class TestPySpaceGenerator(PySpaceGenerator): def __init__(self): super().__init__() self.sch_rules = [] self.postprocs = [] self.mutator_probs = {} with pytest.raises( TVMError, match="PySpaceGenerator's InitializeWithTuneContext method not implemented!" ): generator = TestPySpaceGenerator() generator._initialize_with_tune_context(TuneContext()) if __name__ == "__main__": tvm.testing.main()
https://github.com/zk-ml/tachikoma
tests/python/unittest/test_meta_schedule_task_scheduler.py
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. """ Test Meta Schedule Task Scheduler """ import random import weakref from typing import Set import pytest import tvm import tvm.testing from tvm import meta_schedule as ms from tvm.meta_schedule.testing.dummy_object import DummyBuilder, DummyRunner from tvm.script import tir as T from tvm.tir import Schedule # pylint: disable=invalid-name,no-member,line-too-long,too-many-nested-blocks,missing-docstring @tvm.script.ir_module class MatmulModule: @T.prim_func def main( # type: ignore a: T.handle, b: T.handle, c: T.handle, ) -> None: # pylint: disable=no-self-argument T.func_attr({"global_symbol": "main", "tir.noalias": True}) A = T.match_buffer(a, (1024, 1024), "float32") B = T.match_buffer(b, (1024, 1024), "float32") C = T.match_buffer(c, (1024, 1024), "float32") for i, j, k in T.grid(1024, 1024, 1024): with T.block("matmul"): vi, vj, vk = T.axis.remap("SSR", [i, j, k]) with T.init(): C[vi, vj] = 0.0 # type: ignore C[vi, vj] = C[vi, vj] + A[vi, vk] * B[vk, vj] @tvm.script.ir_module class MatmulReluModule: @T.prim_func def main( # type: ignore a: T.handle, b: T.handle, d: T.handle, ) -> None: # pylint: disable=no-self-argument T.func_attr({"global_symbol": "main", "tir.noalias": True}) A = T.match_buffer(a, (1024, 1024), "float32") B = T.match_buffer(b, (1024, 1024), "float32") D = T.match_buffer(d, (1024, 1024), "float32") C = T.alloc_buffer((1024, 1024), "float32") for i, j, k in T.grid(1024, 1024, 1024): with T.block("matmul"): vi, vj, vk = T.axis.remap("SSR", [i, j, k]) with T.init(): C[vi, vj] = 0.0 # type: ignore C[vi, vj] = C[vi, vj] + A[vi, vk] * B[vk, vj] for i, j in T.grid(1024, 1024): with T.block("relu"): vi, vj = T.axis.remap("SS", [i, j]) D[vi, vj] = T.max(C[vi, vj], 0.0) # type: ignore @tvm.script.ir_module class BatchMatmulModule: @T.prim_func def main( # type: ignore a: T.handle, b: T.handle, c: T.handle, ) -> None: # pylint: disable=no-self-argument T.func_attr({"global_symbol": "main", "tir.noalias": True}) A = T.match_buffer(a, [16, 128, 128]) B = T.match_buffer(b, [16, 128, 128]) C = T.match_buffer(c, [16, 128, 128]) for n, i, j, k in T.grid(16, 128, 128, 128): with T.block("matmul"): vn, vi, vj, vk = T.axis.remap("SSSR", [n, i, j, k]) with T.init(): C[vn, vi, vj] = 0.0 # type: ignore C[vn, vi, vj] = C[vn, vi, vj] + A[vn, vi, vk] * B[vn, vj, vk] # pylint: enable=invalid-name,no-member,line-too-long,too-many-nested-blocks def _schedule_matmul(sch: Schedule): block = sch.get_block("matmul") i, j, k = sch.get_loops(block=block) i_0, i_1, i_2, i_3 = sch.split(loop=i, factors=[2, 4, 64, 2]) j_0, j_1, j_2, j_3 = sch.split(loop=j, factors=[4, 64, 2, 2]) k_0, k_1 = sch.split(loop=k, factors=[32, 32]) sch.reorder(i_0, j_0, i_1, j_1, k_0, i_2, j_2, k_1, i_3, j_3) def _schedule_batch_matmul(sch: Schedule): block = sch.get_block("matmul") i, j, k, t = sch.get_loops(block=block) i_0, i_1, i_2, i_3 = sch.split(loop=i, factors=[2, 2, 2, 2]) j_0, j_1, j_2, j_3 = sch.split(loop=j, factors=[2, 4, 64, 2]) k_0, k_1 = sch.split(loop=k, factors=[32, 32]) t_0, t_1 = sch.split(loop=t, factors=[2, 512]) sch.reorder(i_0, j_0, i_1, j_1, k_0, i_2, j_2, k_1, i_3, j_3, t_0, t_1) @ms.derived_object class MyTaskScheduler(ms.task_scheduler.PyTaskScheduler): done: Set = set() def next_task_id(self) -> int: tasks = self._outer().tasks_ while len(self.done) != len(tasks): x = random.randint(0, len(tasks) - 1) task = tasks[x] if not task.is_terminated: """Calling base func via following route: Python side: PyTaskScheduler does not have `_touch_task` Call TaskScheduler's `touch_task`, which calls ffi C++ side: The ffi calls TaskScheduler's `touch_task` But it is overridden in PyTaskScheduler PyTaskScheduler checks if the function is overridden in python If not, it returns the TaskScheduler's vtable, calling TaskScheduler::TouchTask """ if task.runner_futures is not None: self.join_running_task(x) return x self.done.add(x) return -1 def test_meta_schedule_task_scheduler_single(): num_trials_per_iter = 3 max_trials_per_task = 10 database = ms.database.MemoryDatabase() round_robin = ms.task_scheduler.RoundRobin() round_robin.tune( [ ms.TuneContext( MatmulModule, target=tvm.target.Target("llvm"), space_generator=_schedule_matmul, search_strategy=ms.search_strategy.ReplayTrace(), task_name="Test", rand_state=42, ) ], [1.0], max_trials_global=num_trials_per_iter, max_trials_per_task=max_trials_per_task, num_trials_per_iter=64, builder=DummyBuilder(), runner=DummyRunner(), database=database, measure_callbacks=[ms.measure_callback.AddToDatabase()], cost_model=None, ) assert len(database) == max_trials_per_task def test_meta_schedule_task_scheduler_multiple(): num_trials_per_iter = 6 max_trials_per_task = 101 tasks = [ ms.TuneContext( MatmulModule, target=tvm.target.Target("llvm"), space_generator=_schedule_matmul, search_strategy=ms.search_strategy.ReplayTrace(), task_name="Matmul", rand_state=42, ), ms.TuneContext( MatmulReluModule, target=tvm.target.Target("llvm"), space_generator=_schedule_matmul, search_strategy=ms.search_strategy.ReplayTrace(), task_name="MatmulRelu", rand_state=0xDEADBEEF, ), ms.TuneContext( BatchMatmulModule, target=tvm.target.Target("llvm"), space_generator=_schedule_batch_matmul, search_strategy=ms.search_strategy.ReplayTrace(), task_name="BatchMatmul", rand_state=0x114514, ), ] database = ms.database.MemoryDatabase() round_robin = ms.task_scheduler.RoundRobin() round_robin.tune( tasks, [1.0, 1.0, 1.0], builder=DummyBuilder(), runner=DummyRunner(), database=database, measure_callbacks=[ms.measure_callback.AddToDatabase()], max_trials_global=max_trials_per_task * len(tasks), max_trials_per_task=max_trials_per_task, num_trials_per_iter=num_trials_per_iter, cost_model=None, ) assert len(database) == max_trials_per_task * len(tasks) for task in tasks: assert ( len( database.get_top_k( database.commit_workload(task.mod), 100000, ) ) == max_trials_per_task ) def test_meta_schedule_task_scheduler_NIE(): # pylint: disable=invalid-name @ms.derived_object class NIETaskScheduler(ms.task_scheduler.PyTaskScheduler): pass with pytest.raises(ValueError, match="next_task_id is not defined"): scheduler = NIETaskScheduler() scheduler.next_task_id() def test_meta_schedule_task_scheduler_avoid_cyclic(): # pylint: disable=invalid-name scheduler = MyTaskScheduler() test = weakref.ref(scheduler) # test if it can be destructed successfully del scheduler assert test() is None def test_meta_schedule_task_scheduler_override_next_task_id_only(): # pylint: disable=invalid-name max_trials_per_task = 101 tasks = [ ms.TuneContext( MatmulModule, target=tvm.target.Target("llvm"), space_generator=_schedule_matmul, search_strategy=ms.search_strategy.ReplayTrace(), task_name="Matmul", rand_state=42, ), ms.TuneContext( MatmulReluModule, target=tvm.target.Target("llvm"), space_generator=_schedule_matmul, search_strategy=ms.search_strategy.ReplayTrace(), task_name="MatmulRelu", rand_state=0xDEADBEEF, ), ms.TuneContext( BatchMatmulModule, target=tvm.target.Target("llvm"), space_generator=_schedule_batch_matmul, search_strategy=ms.search_strategy.ReplayTrace(), task_name="BatchMatmul", rand_state=0x114514, ), ] database = ms.database.MemoryDatabase() scheduler = MyTaskScheduler() scheduler.tune( tasks, task_weights=[1.0] * len(tasks), builder=DummyBuilder(), runner=DummyRunner(), database=database, measure_callbacks=[ms.measure_callback.AddToDatabase()], max_trials_global=max_trials_per_task * len(tasks), max_trials_per_task=max_trials_per_task, num_trials_per_iter=6, cost_model=None, ) assert len(database) == max_trials_per_task * len(tasks) for task in tasks: assert ( len( database.get_top_k( database.commit_workload(task.mod), 100000, ) ) == max_trials_per_task ) def test_meta_schedule_task_scheduler_multiple_gradient_based(): max_trials_per_task = 101 tasks = [ ms.TuneContext( MatmulModule, target=tvm.target.Target("llvm"), space_generator=_schedule_matmul, search_strategy=ms.search_strategy.ReplayTrace(), task_name="Matmul", rand_state=42, ), ms.TuneContext( MatmulReluModule, target=tvm.target.Target("llvm"), space_generator=_schedule_matmul, search_strategy=ms.search_strategy.ReplayTrace(), task_name="MatmulRelu", rand_state=0xDEADBEEF, ), ms.TuneContext( BatchMatmulModule, target=tvm.target.Target("llvm"), space_generator=_schedule_batch_matmul, search_strategy=ms.search_strategy.ReplayTrace(), task_name="BatchMatmul", rand_state=0x114514, ), ] database = ms.database.MemoryDatabase() gradient_based = ms.task_scheduler.GradientBased() gradient_based.tune( tasks, task_weights=[1.0, 1.0, 1.0], builder=DummyBuilder(), runner=DummyRunner(), database=database, measure_callbacks=[ms.measure_callback.AddToDatabase()], max_trials_global=max_trials_per_task * len(tasks), max_trials_per_task=max_trials_per_task, num_trials_per_iter=6, cost_model=None, ) assert len(database) == max_trials_per_task * len(tasks) for task in tasks: assert ( len(database.get_top_k(database.commit_workload(task.mod), 10000)) == max_trials_per_task ) if __name__ == "__main__": test_meta_schedule_task_scheduler_single() test_meta_schedule_task_scheduler_multiple() test_meta_schedule_task_scheduler_NIE() test_meta_schedule_task_scheduler_avoid_cyclic() test_meta_schedule_task_scheduler_override_next_task_id_only() test_meta_schedule_task_scheduler_multiple_gradient_based()
https://github.com/zk-ml/tachikoma
tests/python/unittest/test_meta_schedule_trace_apply.py
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. import pytest import tvm import tvm.testing import tvm.meta_schedule as ms from tvm.script import tir as T from tvm.tir import Schedule, floormod, floordiv from tvm.tir.tensor_intrin.cuda import * from tvm.target import Target from tvm.target.codegen import llvm_lookup_intrinsic_id # fmt: off @tvm.script.ir_module class Dense: @T.prim_func def main( p0: T.Buffer[(128, 128), "float32"], p1: T.Buffer[(128, 128), "float32"], T_matmul_NT: T.Buffer[(128, 128), "float32"], ) -> None: # function attr dict T.func_attr({"layout_free_buffers": [1], "tir.noalias": True, "global_symbol": "main"}) # body # with T.block("root") for i0, i1, i2 in T.grid(128, 128, 128): with T.block("T_matmul_NT"): i, j, k = T.axis.remap("SSR", [i0, i1, i2]) T.reads(p0[i, k], p1[j, k]) T.writes(T_matmul_NT[i, j]) T.block_attr({"layout_free_placeholders": []}) with T.init(): T_matmul_NT[i, j] = T.float32(0) T_matmul_NT[i, j] = T_matmul_NT[i, j] + p0[i, k] * p1[j, k] @tvm.script.ir_module class DenseAdd: @T.prim_func def main( p0: T.Buffer[(128, 128), "float32"], p1: T.Buffer[(128, 128), "float32"], T_add: T.Buffer[(128, 128), "float32"], ) -> None: # function attr dict T.func_attr({"global_symbol": "main", "tir.noalias": True, "layout_free_buffers": [1]}) # body # with T.block("root") T_matmul_NT = T.alloc_buffer([128, 128], dtype="float32") compile_engine_const = T.alloc_buffer([], dtype="float32") for i0, i1, i2 in T.grid(128, 128, 128): with T.block("T_matmul_NT"): i, j, k = T.axis.remap("SSR", [i0, i1, i2]) T.reads(p0[i, k], p1[j, k]) T.writes(T_matmul_NT[i, j]) T.block_attr({"layout_free_placeholders": []}) with T.init(): T_matmul_NT[i, j] = T.float32(0) T_matmul_NT[i, j] = T_matmul_NT[i, j] + p0[i, k] * p1[j, k] with T.block("compile_engine_const"): vi = T.axis.spatial(1, 0) T.reads() T.writes(compile_engine_const[()]) compile_engine_const[()] = T.float32(1) for i0, i1 in T.grid(128, 128): with T.block("T_add"): ax0, ax1 = T.axis.remap("SS", [i0, i1]) T.reads(T_matmul_NT[ax0, ax1], compile_engine_const[()]) T.writes(T_add[ax0, ax1]) T_add[ax0, ax1] = T_matmul_NT[ax0, ax1] + compile_engine_const[()] @tvm.script.ir_module class DenseAdd_scheduled_cpu: @T.prim_func def main( p0: T.Buffer[(128, 128), "float32"], p1: T.Buffer[(128, 128), "float32"], T_add: T.Buffer[(128, 128), "float32"], ) -> None: # function attr dict T.func_attr({"global_symbol": "main", "tir.noalias": True, "layout_free_buffers": [1]}) # body # with T.block("root") T_matmul_NT_global = T.alloc_buffer([128, 128], dtype="float32") p1_global = T.alloc_buffer([2, 128, 64], dtype="float32") for ax0, ax1 in T.grid(128, 128): with T.block("p1_global"): v0, v1 = T.axis.remap("SS", [ax0, ax1]) T.reads(p1[v0, v1]) T.writes(p1_global[v0 // 64, v1, v0 % 64]) T.block_attr({"meta_schedule.layout_rewrite_preproc": 1}) p1_global[v0 // 64, v1, v0 % 64] = p1[v0, v1] for i0_0_i1_0_fused_fused in T.parallel(4): for i0_1, i1_1 in T.grid(8, 1): for i0_2_init, i1_2_init, i0_3_init in T.grid(4, 1, 2): for i1_3_fused_init in T.vectorized(64): with T.block("T_matmul_NT_init"): i = T.axis.spatial( 128, i0_0_i1_0_fused_fused // 2 * 64 + i0_1 * 8 + i0_2_init * 2 + i0_3_init, ) j = T.axis.spatial( 128, i0_0_i1_0_fused_fused % 2 * 64 + i1_1 * 64 + i1_2_init * 64 + i1_3_fused_init, ) T.reads() T.writes(T_matmul_NT_global[i, j]) T.block_attr( { "layout_free_placeholders": [], "meta_schedule.tiling_structure": "SSRSRS", } ) T_matmul_NT_global[i, j] = T.float32(0) for i2_0, i0_2, i1_2, i2_1, i0_3 in T.grid(128, 4, 1, 1, 2): for i1_3_fused in T.vectorized(64): with T.block("T_matmul_NT_update"): i = T.axis.spatial( 128, i0_0_i1_0_fused_fused // 2 * 64 + i0_1 * 8 + i0_2 * 2 + i0_3 ) j = T.axis.spatial( 128, i0_0_i1_0_fused_fused % 2 * 64 + i1_1 * 64 + i1_2 * 64 + i1_3_fused, ) k = T.axis.reduce(128, i2_0 + i2_1) T.reads( T_matmul_NT_global[i, j], p0[i, k], p1_global[j // 64, k, j % 64] ) T.writes(T_matmul_NT_global[i, j]) T.block_attr( { "layout_free_placeholders": [], "meta_schedule.tiling_structure": "SSRSRS", } ) T_matmul_NT_global[i, j] = ( T_matmul_NT_global[i, j] + p0[i, k] * p1_global[j // 64, k, j % 64] ) for ax0 in T.serial(64): for ax1_fused in T.vectorized(64): with T.block("T_matmul_NT_global"): v0 = T.axis.spatial(128, i0_0_i1_0_fused_fused // 2 * 64 + ax0) v1 = T.axis.spatial(128, i0_0_i1_0_fused_fused % 2 * 64 + ax1_fused) T.reads(T_matmul_NT_global[v0, v1]) T.writes(T_add[v0, v1]) T_add[v0, v1] = T_matmul_NT_global[v0, v1] + T.float32(1) @tvm.script.ir_module class DenseAdd_cpu_no_write_cache: @T.prim_func def main(p0: T.Buffer[(128, 128), "float32"], p1: T.Buffer[(128, 128), "float32"], T_add: T.Buffer[(128, 128), "float32"]) -> None: # function attr dict T.func_attr({"global_symbol": "main", "tir.noalias": True, "layout_free_buffers": [1]}) # body # with T.block("root") T_matmul_NT = T.alloc_buffer([128, 128], dtype="float32") p1_global = T.alloc_buffer([8, 4, 16, 32], dtype="float32") for ax0, ax1 in T.grid(128, 128): with T.block("p1_global"): v0, v1 = T.axis.remap("SS", [ax0, ax1]) T.reads(p1[v0, v1]) T.writes(p1_global[v1 // 16, v0 // 32, v1 % 16, v0 % 32]) T.block_attr({"meta_schedule.layout_rewrite_preproc":1}) p1_global[v1 // 16, v0 // 32, v1 % 16, v0 % 32] = p1[v0, v1] for i0_0_i1_0_i0_1_i1_1_fused in T.parallel(16, annotations={"pragma_auto_unroll_max_step":16, "pragma_unroll_explicit":1}): for i0_2_init, i1_2_init, i0_3_init in T.grid(4, 4, 2): for i1_3_fused_init in T.vectorized(32): with T.block("T_matmul_NT_init"): i = T.axis.spatial(128, i0_0_i1_0_i0_1_i1_1_fused // 4 * 32 + i0_0_i1_0_i0_1_i1_1_fused % 4 * 8 + i0_2_init * 2 + i0_3_init) j = T.axis.spatial(128, i1_2_init * 32 + i1_3_fused_init) T.reads() T.writes(T_matmul_NT[i, j]) T.block_attr({"layout_free_placeholders":[], "meta_schedule.tiling_structure":"SSRSRS"}) T_matmul_NT[i, j] = T.float32(0) for i2_0, i0_2, i1_2, i2_1, i0_3 in T.grid(8, 4, 4, 16, 2): for i1_3_fused in T.vectorized(32): with T.block("T_matmul_NT_update"): i = T.axis.spatial(128, i0_0_i1_0_i0_1_i1_1_fused // 4 * 32 + i0_0_i1_0_i0_1_i1_1_fused % 4 * 8 + i0_2 * 2 + i0_3) j = T.axis.spatial(128, i1_2 * 32 + i1_3_fused) k = T.axis.reduce(128, i2_0 * 16 + i2_1) T.reads(T_matmul_NT[i, j], p0[i, k], p1_global[k // 16, j // 32, k % 16, j % 32]) T.writes(T_matmul_NT[i, j]) T.block_attr({"layout_free_placeholders":[], "meta_schedule.tiling_structure":"SSRSRS"}) T_matmul_NT[i, j] = T_matmul_NT[i, j] + p0[i, k] * p1_global[k // 16, j // 32, k % 16, j % 32] for i0_i1_fused in T.parallel(16384): with T.block("T_add"): ax0 = T.axis.spatial(128, i0_i1_fused // 128) ax1 = T.axis.spatial(128, i0_i1_fused % 128) T.reads(T_matmul_NT[ax0, ax1]) T.writes(T_add[ax0, ax1]) T_add[ax0, ax1] = T_matmul_NT[ax0, ax1] + T.float32(1) @tvm.script.ir_module class DenseAdd_scheduled_gpu: @T.prim_func def main( p0: T.Buffer[(128, 128), "float32"], p1: T.Buffer[(128, 128), "float32"], T_add: T.Buffer[(128, 128), "float32"], ) -> None: # function attr dict T.func_attr({"global_symbol": "main", "tir.noalias": True, "layout_free_buffers": [1]}) # body # with T.block("root") T_matmul_NT_local = T.alloc_buffer([128, 128], dtype="float32", scope="local") p0_shared = T.alloc_buffer([128, 128], dtype="float32", scope="shared") p1_shared = T.alloc_buffer([128, 128], dtype="float32", scope="shared") for i0_0_i1_0_fused in T.thread_binding( 32, thread="blockIdx.x", annotations={"pragma_auto_unroll_max_step": 64, "pragma_unroll_explicit": 1}, ): for i0_1_i1_1_fused in T.thread_binding(1, thread="vthread.x"): for i0_2_i1_2_fused in T.thread_binding(128, thread="threadIdx.x"): for i0_3_init, i1_3_init, i0_4_init, i1_4_init in T.grid(1, 4, 1, 1): with T.block("T_matmul_NT_init"): i = T.axis.spatial( 128, i0_0_i1_0_fused // 4 * 16 + i0_2_i1_2_fused // 8 + i0_3_init + i0_4_init, ) j = T.axis.spatial( 128, i1_4_init + i0_0_i1_0_fused % 4 * 32 + i0_2_i1_2_fused % 8 * 4 + i1_3_init, ) T.reads() T.writes(T_matmul_NT_local[i, j]) T.block_attr( { "layout_free_placeholders": [], "meta_schedule.thread_extent_high_inclusive": 256, "meta_schedule.thread_extent_low_inclusive": 16, "meta_schedule.tiling_structure": "SSSRRSRS", } ) T_matmul_NT_local[i, j] = T.float32(0) for i2_0 in T.serial(32): for ax0_ax1_fused_0 in T.serial(1): for ax0_ax1_fused_1 in T.thread_binding(128, thread="threadIdx.x"): for ax0_ax1_fused_2 in T.vectorized(2): with T.block("p0_shared"): T.where( (ax0_ax1_fused_0 * 128 + ax0_ax1_fused_1) * 2 + ax0_ax1_fused_2 < 64 ) v0 = T.axis.spatial( 128, i0_0_i1_0_fused // 4 * 16 + ( ax0_ax1_fused_0 * 256 + ax0_ax1_fused_1 * 2 + ax0_ax1_fused_2 ) // 4, ) v1 = T.axis.spatial( 128, i2_0 * 4 + ( ax0_ax1_fused_0 * 256 + ax0_ax1_fused_1 * 2 + ax0_ax1_fused_2 ) % 4, ) T.reads(p0[v0, v1]) T.writes(p0_shared[v0, v1]) p0_shared[v0, v1] = p0[v0, v1] for ax0_ax1_fused_0 in T.serial(1): for ax0_ax1_fused_1 in T.thread_binding(128, thread="threadIdx.x"): for ax0_ax1_fused_2 in T.vectorized(4): with T.block("p1_shared"): T.where( (ax0_ax1_fused_0 * 128 + ax0_ax1_fused_1) * 4 + ax0_ax1_fused_2 < 128 ) v0 = T.axis.spatial( 128, i0_0_i1_0_fused % 4 * 32 + ( ax0_ax1_fused_0 * 512 + ax0_ax1_fused_1 * 4 + ax0_ax1_fused_2 ) // 4, ) v1 = T.axis.spatial( 128, i2_0 * 4 + ( ax0_ax1_fused_0 * 512 + ax0_ax1_fused_1 * 4 + ax0_ax1_fused_2 ) % 4, ) T.reads(p1[v0, v1]) T.writes(p1_shared[v0, v1]) p1_shared[v0, v1] = p1[v0, v1] for i2_1, i0_3, i1_3, i2_2, i0_4, i1_4 in T.grid(1, 1, 4, 4, 1, 1): with T.block("T_matmul_NT_update"): i = T.axis.spatial( 128, i0_0_i1_0_fused // 4 * 16 + i0_2_i1_2_fused // 8 + i0_3 + i0_4, ) j = T.axis.spatial( 128, i1_4 + i0_0_i1_0_fused % 4 * 32 + i0_2_i1_2_fused % 8 * 4 + i1_3, ) k = T.axis.reduce(128, i2_0 * 4 + i2_1 * 4 + i2_2) T.reads(T_matmul_NT_local[i, j], p0_shared[i, k], p1_shared[j, k]) T.writes(T_matmul_NT_local[i, j]) T.block_attr( { "layout_free_placeholders": [], "meta_schedule.thread_extent_high_inclusive": 256, "meta_schedule.thread_extent_low_inclusive": 16, "meta_schedule.tiling_structure": "SSSRRSRS", } ) T_matmul_NT_local[i, j] = ( T_matmul_NT_local[i, j] + p0_shared[i, k] * p1_shared[j, k] ) for ax0, ax1 in T.grid(1, 4): with T.block("T_matmul_NT_local"): v0 = T.axis.spatial( 128, i0_0_i1_0_fused // 4 * 16 + i0_2_i1_2_fused // 8 + ax0 ) v1 = T.axis.spatial( 128, i0_0_i1_0_fused % 4 * 32 + i0_2_i1_2_fused % 8 * 4 + ax1 ) T.reads(T_matmul_NT_local[v0, v1]) T.writes(T_add[v0, v1]) T_add[v0, v1] = T_matmul_NT_local[v0, v1] + T.float32(1) @tvm.script.ir_module class Conv2dInt8: @T.prim_func def main(p0: T.Buffer[(16, 56, 56, 64), "int8"], p1: T.Buffer[(256, 1, 1, 64), "int8"], p2: T.Buffer[(1, 1, 1, 256), "int32"], p3: T.Buffer[(1, 1, 1, 256), "int32"], p4: T.Buffer[(1, 1, 1, 256), "int64"], p5: T.Buffer[(1, 1, 1, 256), "int64"], p6: T.Buffer[(1, 1, 1, 256), "int64"], p7: T.Buffer[(), "int32"], p8: T.Buffer[1, "int32"], compute: T.Buffer[(16, 56, 56, 256), "int32"]) -> None: # function attr dict T.func_attr({"tir.noalias": True, "global_symbol": "main"}) # body # with T.block("root") pad_temp = T.alloc_buffer([16, 56, 56, 64], dtype="int8") conv2d_nhwc = T.alloc_buffer([16, 56, 56, 256], dtype="int32") T_subtract = T.alloc_buffer([16, 56, 56, 256], dtype="int32") T_add = T.alloc_buffer([16, 56, 56, 256], dtype="int32") T_cast = T.alloc_buffer([16, 56, 56, 256], dtype="int64") T_multiply = T.alloc_buffer([16, 56, 56, 256], dtype="int64") T_add_1 = T.alloc_buffer([16, 56, 56, 256], dtype="int64") T_right_shift = T.alloc_buffer([16, 56, 56, 256], dtype="int64") T_cast_1 = T.alloc_buffer([16, 56, 56, 256], dtype="int32") T_add_2 = T.alloc_buffer([16, 56, 56, 256], dtype="int32") compute_1 = T.alloc_buffer([16, 56, 56, 256], dtype="int32") T_cast_2 = T.alloc_buffer([16, 56, 56, 256], dtype="uint8") T_cast_3 = T.alloc_buffer([16, 56, 56, 256], dtype="int32") T_subtract_1 = T.alloc_buffer([16, 56, 56, 256], dtype="int32") for i0, i1, i2, i3 in T.grid(16, 56, 56, 64): with T.block("pad_temp"): i0_1, i1_1, i2_1, i3_1 = T.axis.remap("SSSS", [i0, i1, i2, i3]) T.reads(p0[i0_1, i1_1, i2_1, i3_1]) T.writes(pad_temp[i0_1, i1_1, i2_1, i3_1]) pad_temp[i0_1, i1_1, i2_1, i3_1] = p0[i0_1, i1_1, i2_1, i3_1] for i0, i1, i2, i3, i4, i5, i6 in T.grid(16, 56, 56, 256, 1, 1, 64): with T.block("conv2d_nhwc"): nn, yy, xx, ff, ry, rx, rc = T.axis.remap("SSSSRRR", [i0, i1, i2, i3, i4, i5, i6]) T.reads(pad_temp[nn, yy + ry, xx + rx, rc], p1[ff, ry, rx, rc]) T.writes(conv2d_nhwc[nn, yy, xx, ff]) with T.init(): conv2d_nhwc[nn, yy, xx, ff] = 0 conv2d_nhwc[nn, yy, xx, ff] = conv2d_nhwc[nn, yy, xx, ff] + T.cast(pad_temp[nn, yy + ry, xx + rx, rc], "int32") * T.cast(p1[ff, ry, rx, rc], "int32") for i0, i1, i2, i3 in T.grid(16, 56, 56, 256): with T.block("T_subtract"): ax0, ax1, ax2, ax3 = T.axis.remap("SSSS", [i0, i1, i2, i3]) T.reads(conv2d_nhwc[ax0, ax1, ax2, ax3], p2[0, 0, 0, ax3]) T.writes(T_subtract[ax0, ax1, ax2, ax3]) T_subtract[ax0, ax1, ax2, ax3] = conv2d_nhwc[ax0, ax1, ax2, ax3] - p2[0, 0, 0, ax3] for i0, i1, i2, i3 in T.grid(16, 56, 56, 256): with T.block("T_add"): ax0, ax1, ax2, ax3 = T.axis.remap("SSSS", [i0, i1, i2, i3]) T.reads(T_subtract[ax0, ax1, ax2, ax3], p3[0, 0, 0, ax3]) T.writes(T_add[ax0, ax1, ax2, ax3]) T_add[ax0, ax1, ax2, ax3] = T_subtract[ax0, ax1, ax2, ax3] + p3[0, 0, 0, ax3] for i0, i1, i2, i3 in T.grid(16, 56, 56, 256): with T.block("T_cast"): ax0, ax1, ax2, ax3 = T.axis.remap("SSSS", [i0, i1, i2, i3]) T.reads(T_add[ax0, ax1, ax2, ax3]) T.writes(T_cast[ax0, ax1, ax2, ax3]) T_cast[ax0, ax1, ax2, ax3] = T.cast(T_add[ax0, ax1, ax2, ax3], "int64") for i0, i1, i2, i3 in T.grid(16, 56, 56, 256): with T.block("T_multiply"): ax0, ax1, ax2, ax3 = T.axis.remap("SSSS", [i0, i1, i2, i3]) T.reads(T_cast[ax0, ax1, ax2, ax3], p4[0, 0, 0, ax3]) T.writes(T_multiply[ax0, ax1, ax2, ax3]) T_multiply[ax0, ax1, ax2, ax3] = T_cast[ax0, ax1, ax2, ax3] * p4[0, 0, 0, ax3] for i0, i1, i2, i3 in T.grid(16, 56, 56, 256): with T.block("T_add_1"): ax0, ax1, ax2, ax3 = T.axis.remap("SSSS", [i0, i1, i2, i3]) T.reads(T_multiply[ax0, ax1, ax2, ax3], p5[0, 0, 0, ax3]) T.writes(T_add_1[ax0, ax1, ax2, ax3]) T_add_1[ax0, ax1, ax2, ax3] = T_multiply[ax0, ax1, ax2, ax3] + p5[0, 0, 0, ax3] for i0, i1, i2, i3 in T.grid(16, 56, 56, 256): with T.block("T_right_shift"): ax0, ax1, ax2, ax3 = T.axis.remap("SSSS", [i0, i1, i2, i3]) T.reads(T_add_1[ax0, ax1, ax2, ax3], p6[0, 0, 0, ax3]) T.writes(T_right_shift[ax0, ax1, ax2, ax3]) T_right_shift[ax0, ax1, ax2, ax3] = T.shift_right(T_add_1[ax0, ax1, ax2, ax3], p6[0, 0, 0, ax3], dtype="int64") for i0, i1, i2, i3 in T.grid(16, 56, 56, 256): with T.block("T_cast_1"): ax0, ax1, ax2, ax3 = T.axis.remap("SSSS", [i0, i1, i2, i3]) T.reads(T_right_shift[ax0, ax1, ax2, ax3]) T.writes(T_cast_1[ax0, ax1, ax2, ax3]) T_cast_1[ax0, ax1, ax2, ax3] = T.cast(T_right_shift[ax0, ax1, ax2, ax3], "int32") for i0, i1, i2, i3 in T.grid(16, 56, 56, 256): with T.block("T_add_2"): ax0, ax1, ax2, ax3 = T.axis.remap("SSSS", [i0, i1, i2, i3]) T.reads(p7[()], T_cast_1[ax0, ax1, ax2, ax3]) T.writes(T_add_2[ax0, ax1, ax2, ax3]) T_add_2[ax0, ax1, ax2, ax3] = p7[()] + T_cast_1[ax0, ax1, ax2, ax3] for i0, i1, i2, i3 in T.grid(16, 56, 56, 256): with T.block("compute"): i0_2, i1_2, i2_2, i3_2 = T.axis.remap("SSSS", [i0, i1, i2, i3]) T.reads(T_add_2[i0_2, i1_2, i2_2, i3_2]) T.writes(compute_1[i0_2, i1_2, i2_2, i3_2]) compute_1[i0_2, i1_2, i2_2, i3_2] = T.max(T.min(T_add_2[i0_2, i1_2, i2_2, i3_2], 255), 0) for i0_3, i1_3, i2_3, i3_3 in T.grid(16, 56, 56, 256): with T.block("T_cast_2"): ax0, ax1, ax2, ax3 = T.axis.remap("SSSS", [i0_3, i1_3, i2_3, i3_3]) T.reads(compute_1[ax0, ax1, ax2, ax3]) T.writes(T_cast_2[ax0, ax1, ax2, ax3]) T_cast_2[ax0, ax1, ax2, ax3] = T.cast(compute_1[ax0, ax1, ax2, ax3], "uint8") for i0_4, i1_4, i2_4, i3_4 in T.grid(16, 56, 56, 256): with T.block("T_cast_3"): ax0, ax1, ax2, ax3 = T.axis.remap("SSSS", [i0_4, i1_4, i2_4, i3_4]) T.reads(T_cast_2[ax0, ax1, ax2, ax3]) T.writes(T_cast_3[ax0, ax1, ax2, ax3]) T_cast_3[ax0, ax1, ax2, ax3] = T.cast(T_cast_2[ax0, ax1, ax2, ax3], "int32") for i0_5, i1_5, i2_5, i3_5 in T.grid(16, 56, 56, 256): with T.block("T_subtract_1"): ax0, ax1, ax2, ax3 = T.axis.remap("SSSS", [i0_5, i1_5, i2_5, i3_5]) T.reads(T_cast_3[ax0, ax1, ax2, ax3], p8[0]) T.writes(T_subtract_1[ax0, ax1, ax2, ax3]) T_subtract_1[ax0, ax1, ax2, ax3] = T_cast_3[ax0, ax1, ax2, ax3] - p8[0] for i0_6, i1_6, i2_6, i3_6 in T.grid(16, 56, 56, 256): with T.block("compute_1"): i0_7, i1_7, i2_7, i3_7 = T.axis.remap("SSSS", [i0_6, i1_6, i2_6, i3_6]) T.reads(T_subtract_1[i0_7, i1_7, i2_7, i3_7]) T.writes(compute[i0_7, i1_7, i2_7, i3_7]) compute[i0_7, i1_7, i2_7, i3_7] = T.q_multiply_shift(T_subtract_1[i0_7, i1_7, i2_7, i3_7], 1963325822, 31, 1, dtype="int32") @tvm.script.ir_module class Conv2dInt8_target: @T.prim_func def main(p0: T.Buffer[(16, 56, 56, 64), "int8"], p1: T.Buffer[(256, 1, 1, 64), "int8"], p2: T.Buffer[(1, 1, 1, 256), "int32"], p3: T.Buffer[(1, 1, 1, 256), "int32"], p4: T.Buffer[(1, 1, 1, 256), "int64"], p5: T.Buffer[(1, 1, 1, 256), "int64"], p6: T.Buffer[(1, 1, 1, 256), "int64"], p7: T.Buffer[(), "int32"], p8: T.Buffer[1, "int32"], p9: T.Buffer[(16, 56, 56, 256), "int32"], compute: T.Buffer[(16, 56, 56, 256), "uint8"]) -> None: # function attr dict T.func_attr({"global_symbol": "main", "tir.noalias": True}) # body # with T.block("root") pad_temp = T.alloc_buffer([16, 56, 56, 64], dtype="int8") conv2d_nhwc = T.alloc_buffer([16, 56, 56, 256], dtype="int32") T_subtract = T.alloc_buffer([16, 56, 56, 256], dtype="int32") T_add = T.alloc_buffer([16, 56, 56, 256], dtype="int32") T_cast = T.alloc_buffer([16, 56, 56, 256], dtype="int64") T_multiply = T.alloc_buffer([16, 56, 56, 256], dtype="int64") T_add_1 = T.alloc_buffer([16, 56, 56, 256], dtype="int64") T_right_shift = T.alloc_buffer([16, 56, 56, 256], dtype="int64") T_cast_1 = T.alloc_buffer([16, 56, 56, 256], dtype="int32") T_add_2 = T.alloc_buffer([16, 56, 56, 256], dtype="int32") compute_1 = T.alloc_buffer([16, 56, 56, 256], dtype="int32") T_cast_2 = T.alloc_buffer([16, 56, 56, 256], dtype="uint8") T_cast_3 = T.alloc_buffer([16, 56, 56, 256], dtype="int32") T_subtract_1 = T.alloc_buffer([16, 56, 56, 256], dtype="int32") compute_2 = T.alloc_buffer([16, 56, 56, 256], dtype="int32") T_add_3 = T.alloc_buffer([16, 56, 56, 256], dtype="int32") compute_3 = T.alloc_buffer([16, 56, 56, 256], dtype="int32") T_cast_4 = T.alloc_buffer([16, 56, 56, 256], dtype="uint8") for i0, i1, i2, i3 in T.grid(16, 56, 56, 64): with T.block("pad_temp"): i0_1, i1_1, i2_1, i3_1 = T.axis.remap("SSSS", [i0, i1, i2, i3]) T.reads(p0[i0_1, i1_1, i2_1, i3_1]) T.writes(pad_temp[i0_1, i1_1, i2_1, i3_1]) pad_temp[i0_1, i1_1, i2_1, i3_1] = p0[i0_1, i1_1, i2_1, i3_1] for i0, i1, i2, i3, i4, i5, i6 in T.grid(16, 56, 56, 256, 1, 1, 64): with T.block("conv2d_nhwc"): nn, yy, xx, ff, ry, rx, rc = T.axis.remap("SSSSRRR", [i0, i1, i2, i3, i4, i5, i6]) T.reads(pad_temp[nn, yy + ry, xx + rx, rc], p1[ff, ry, rx, rc]) T.writes(conv2d_nhwc[nn, yy, xx, ff]) with T.init(): conv2d_nhwc[nn, yy, xx, ff] = 0 conv2d_nhwc[nn, yy, xx, ff] = conv2d_nhwc[nn, yy, xx, ff] + T.cast(pad_temp[nn, yy + ry, xx + rx, rc], "int32") * T.cast(p1[ff, ry, rx, rc], "int32") for i0, i1, i2, i3 in T.grid(16, 56, 56, 256): with T.block("T_subtract"): ax0, ax1, ax2, ax3 = T.axis.remap("SSSS", [i0, i1, i2, i3]) T.reads(conv2d_nhwc[ax0, ax1, ax2, ax3], p2[0, 0, 0, ax3]) T.writes(T_subtract[ax0, ax1, ax2, ax3]) T_subtract[ax0, ax1, ax2, ax3] = conv2d_nhwc[ax0, ax1, ax2, ax3] - p2[0, 0, 0, ax3] for i0, i1, i2, i3 in T.grid(16, 56, 56, 256): with T.block("T_add"): ax0, ax1, ax2, ax3 = T.axis.remap("SSSS", [i0, i1, i2, i3]) T.reads(T_subtract[ax0, ax1, ax2, ax3], p3[0, 0, 0, ax3]) T.writes(T_add[ax0, ax1, ax2, ax3]) T_add[ax0, ax1, ax2, ax3] = T_subtract[ax0, ax1, ax2, ax3] + p3[0, 0, 0, ax3] for i0, i1, i2, i3 in T.grid(16, 56, 56, 256): with T.block("T_cast"): ax0, ax1, ax2, ax3 = T.axis.remap("SSSS", [i0, i1, i2, i3]) T.reads(T_add[ax0, ax1, ax2, ax3]) T.writes(T_cast[ax0, ax1, ax2, ax3]) T_cast[ax0, ax1, ax2, ax3] = T.cast(T_add[ax0, ax1, ax2, ax3], "int64") for i0, i1, i2, i3 in T.grid(16, 56, 56, 256): with T.block("T_multiply"): ax0, ax1, ax2, ax3 = T.axis.remap("SSSS", [i0, i1, i2, i3]) T.reads(T_cast[ax0, ax1, ax2, ax3], p4[0, 0, 0, ax3]) T.writes(T_multiply[ax0, ax1, ax2, ax3]) T_multiply[ax0, ax1, ax2, ax3] = T_cast[ax0, ax1, ax2, ax3] * p4[0, 0, 0, ax3] for i0, i1, i2, i3 in T.grid(16, 56, 56, 256): with T.block("T_add_1"): ax0, ax1, ax2, ax3 = T.axis.remap("SSSS", [i0, i1, i2, i3]) T.reads(T_multiply[ax0, ax1, ax2, ax3], p5[0, 0, 0, ax3]) T.writes(T_add_1[ax0, ax1, ax2, ax3]) T_add_1[ax0, ax1, ax2, ax3] = T_multiply[ax0, ax1, ax2, ax3] + p5[0, 0, 0, ax3] for i0, i1, i2, i3 in T.grid(16, 56, 56, 256): with T.block("T_right_shift"): ax0, ax1, ax2, ax3 = T.axis.remap("SSSS", [i0, i1, i2, i3]) T.reads(T_add_1[ax0, ax1, ax2, ax3], p6[0, 0, 0, ax3]) T.writes(T_right_shift[ax0, ax1, ax2, ax3]) T_right_shift[ax0, ax1, ax2, ax3] = T.shift_right(T_add_1[ax0, ax1, ax2, ax3], p6[0, 0, 0, ax3], dtype="int64") for i0, i1, i2, i3 in T.grid(16, 56, 56, 256): with T.block("T_cast_1"): ax0, ax1, ax2, ax3 = T.axis.remap("SSSS", [i0, i1, i2, i3]) T.reads(T_right_shift[ax0, ax1, ax2, ax3]) T.writes(T_cast_1[ax0, ax1, ax2, ax3]) T_cast_1[ax0, ax1, ax2, ax3] = T.cast(T_right_shift[ax0, ax1, ax2, ax3], "int32") for i0, i1, i2, i3 in T.grid(16, 56, 56, 256): with T.block("T_add_2"): ax0, ax1, ax2, ax3 = T.axis.remap("SSSS", [i0, i1, i2, i3]) T.reads(p7[()], T_cast_1[ax0, ax1, ax2, ax3]) T.writes(T_add_2[ax0, ax1, ax2, ax3]) T_add_2[ax0, ax1, ax2, ax3] = p7[()] + T_cast_1[ax0, ax1, ax2, ax3] for i0, i1, i2, i3 in T.grid(16, 56, 56, 256): with T.block("compute"): i0_2, i1_2, i2_2, i3_2 = T.axis.remap("SSSS", [i0, i1, i2, i3]) T.reads(T_add_2[i0_2, i1_2, i2_2, i3_2]) T.writes(compute_1[i0_2, i1_2, i2_2, i3_2]) compute_1[i0_2, i1_2, i2_2, i3_2] = T.max(T.min(T_add_2[i0_2, i1_2, i2_2, i3_2], 255), 0) for i0_3, i1_3, i2_3, i3_3 in T.grid(16, 56, 56, 256): with T.block("T_cast_2"): ax0, ax1, ax2, ax3 = T.axis.remap("SSSS", [i0_3, i1_3, i2_3, i3_3]) T.reads(compute_1[ax0, ax1, ax2, ax3]) T.writes(T_cast_2[ax0, ax1, ax2, ax3]) T_cast_2[ax0, ax1, ax2, ax3] = T.cast(compute_1[ax0, ax1, ax2, ax3], "uint8") for i0_4, i1_4, i2_4, i3_4 in T.grid(16, 56, 56, 256): with T.block("T_cast_3"): ax0, ax1, ax2, ax3 = T.axis.remap("SSSS", [i0_4, i1_4, i2_4, i3_4]) T.reads(T_cast_2[ax0, ax1, ax2, ax3]) T.writes(T_cast_3[ax0, ax1, ax2, ax3]) T_cast_3[ax0, ax1, ax2, ax3] = T.cast(T_cast_2[ax0, ax1, ax2, ax3], "int32") for i0_5, i1_5, i2_5, i3_5 in T.grid(16, 56, 56, 256): with T.block("T_subtract_1"): ax0, ax1, ax2, ax3 = T.axis.remap("SSSS", [i0_5, i1_5, i2_5, i3_5]) T.reads(T_cast_3[ax0, ax1, ax2, ax3], p8[0]) T.writes(T_subtract_1[ax0, ax1, ax2, ax3]) T_subtract_1[ax0, ax1, ax2, ax3] = T_cast_3[ax0, ax1, ax2, ax3] - p8[0] for i0_6, i1_6, i2_6, i3_6 in T.grid(16, 56, 56, 256): with T.block("compute_1"): i0_7, i1_7, i2_7, i3_7 = T.axis.remap("SSSS", [i0_6, i1_6, i2_6, i3_6]) T.reads(T_subtract_1[i0_7, i1_7, i2_7, i3_7]) T.writes(compute_2[i0_7, i1_7, i2_7, i3_7]) compute_2[i0_7, i1_7, i2_7, i3_7] = T.q_multiply_shift(T_subtract_1[i0_7, i1_7, i2_7, i3_7], 1098990753, 31, 1, dtype="int32") for i0_8, i1_8, i2_8, i3_8 in T.grid(16, 56, 56, 256): with T.block("T_add_3"): ax0, ax1, ax2, ax3 = T.axis.remap("SSSS", [i0_8, i1_8, i2_8, i3_8]) T.reads(compute_2[ax0, ax1, ax2, ax3], p9[ax0, ax1, ax2, ax3]) T.writes(T_add_3[ax0, ax1, ax2, ax3]) T_add_3[ax0, ax1, ax2, ax3] = compute_2[ax0, ax1, ax2, ax3] + p9[ax0, ax1, ax2, ax3] for i0_9, i1_9, i2_9, i3_9 in T.grid(16, 56, 56, 256): with T.block("compute_2"): i0_10, i1_10, i2_10, i3_10 = T.axis.remap("SSSS", [i0_9, i1_9, i2_9, i3_9]) T.reads(T_add_3[i0_10, i1_10, i2_10, i3_10]) T.writes(compute_3[i0_10, i1_10, i2_10, i3_10]) compute_3[i0_10, i1_10, i2_10, i3_10] = T.max(T.min(T_add_3[i0_10, i1_10, i2_10, i3_10], 255), 0) for i0_11, i1_11, i2_11, i3_11 in T.grid(16, 56, 56, 256): with T.block("T_cast_4"): ax0, ax1, ax2, ax3 = T.axis.remap("SSSS", [i0_11, i1_11, i2_11, i3_11]) T.reads(compute_3[ax0, ax1, ax2, ax3]) T.writes(T_cast_4[ax0, ax1, ax2, ax3]) T_cast_4[ax0, ax1, ax2, ax3] = T.cast(compute_3[ax0, ax1, ax2, ax3], "uint8") for i0_12, i1_12, i2_12, i3_12 in T.grid(16, 56, 56, 256): with T.block("compute_3"): i0_13, i1_13, i2_13, i3_13 = T.axis.remap("SSSS", [i0_12, i1_12, i2_12, i3_12]) T.reads(T_cast_4[i0_13, i1_13, i2_13, i3_13]) T.writes(compute[i0_13, i1_13, i2_13, i3_13]) compute[i0_13, i1_13, i2_13, i3_13] = T.max(T.min(T_cast_4[i0_13, i1_13, i2_13, i3_13], T.uint8(255)), T.uint8(0)) @tvm.script.ir_module class Conv2dInt8_tensorcore_scheduled: @T.prim_func def main(p0: T.Buffer[(16, 56, 56, 64), "int8"], p1: T.Buffer[(256, 1, 1, 64), "int8"], p2: T.Buffer[(1, 1, 1, 256), "int32"], p3: T.Buffer[(1, 1, 1, 256), "int32"], p4: T.Buffer[(1, 1, 1, 256), "int64"], p5: T.Buffer[(1, 1, 1, 256), "int64"], p6: T.Buffer[(1, 1, 1, 256), "int64"], p7: T.Buffer[(), "int32"], p8: T.Buffer[1, "int32"], p9: T.Buffer[(16, 56, 56, 256), "int32"], compute: T.Buffer[(16, 56, 56, 256), "uint8"]) -> None: # function attr dict T.func_attr({"global_symbol": "main", "tir.noalias": True}) a0 = T.var("int32") a1 = T.var("int32") b0 = T.var("int32") b1 = T.var("int32") c0 = T.var("int32") c1 = T.var("int32") d0 = T.var("int32") d0_1 = T.var("int32") d0_2 = T.var("int32") d0_3 = T.var("int32") d1 = T.var("int32") d1_1 = T.var("int32") d1_2 = T.var("int32") d1_3 = T.var("int32") s0 = T.var("int32") s0_1 = T.var("int32") s0_2 = T.var("int32") s1 = T.var("int32") s1_1 = T.var("int32") s1_2 = T.var("int32") # body # with T.block("root") conv2d_nhwc_reindex_shared = T.alloc_buffer([50176, 256], dtype="int32", scope="shared") conv2d_nhwc_reindex_shared_wmma_accumulator = T.alloc_buffer([50176, 256], dtype="int32", scope="wmma.accumulator") pad_temp_reindex_shared = T.alloc_buffer([50176, 64], dtype="int8", scope="shared") p1_reindex_shared = T.alloc_buffer([1, 1, 256, 64], dtype="int8", scope="shared") pad_temp_reindex_shared_wmma_matrix_a = T.alloc_buffer([50176, 64], dtype="int8", scope="wmma.matrix_a") p1_reindex_shared_wmma_matrix_b = T.alloc_buffer([1, 1, 256, 64], dtype="int8", scope="wmma.matrix_b") for ax2_0_0_ax3_0_0_fused in T.thread_binding(3136, thread="blockIdx.x", annotations={"pragma_auto_unroll_max_step":512, "pragma_unroll_explicit":1}): for ax2_0_1_ax3_0_1_fused in T.thread_binding(1, thread="vthread.x"): for ax2_0_2_ax3_0_2_fused in T.thread_binding(16, thread="threadIdx.x"): for ax0_0, ax1_0 in T.grid(1, 1): for ax2_0_3_init, ax3_0_3_init, ax2_0_4_init, ax3_0_4_init in T.grid(1, 1, 1, 1): with T.block("conv2d_nhwc_o_init"): v2_o = T.axis.spatial(3136, ax2_0_0_ax3_0_0_fused // 8 * 8 + ax2_0_2_ax3_0_2_fused // 2 + ax2_0_3_init + ax2_0_4_init) v3_o = T.axis.spatial(16, ax3_0_4_init + ax2_0_0_ax3_0_0_fused % 8 * 2 + ax2_0_2_ax3_0_2_fused % 2 + ax3_0_3_init) T.reads() T.writes(conv2d_nhwc_reindex_shared_wmma_accumulator[v2_o * 16 : v2_o * 16 + 16, v3_o * 16 : v3_o * 16 + 16]) T.block_attr({"meta_schedule.thread_extent_high_inclusive":1024, "meta_schedule.thread_extent_low_inclusive":32, "warp_execution":1}) C = T.match_buffer(conv2d_nhwc_reindex_shared_wmma_accumulator[v2_o * 16 : v2_o * 16 + 16, v3_o * 16 : v3_o * 16 + 16], [16, 16], dtype="int32", strides=[d1, d0], scope="wmma.accumulator", offset_factor=16) T.evaluate(T.tvm_fill_fragment(C.data, 16, 16, 16, C.elem_offset // d1 // 16 * (d1 // 16) + C.elem_offset % d1 // 16, T.float32(0), dtype="handle")) for ax4_0_0 in T.serial(2): for ax0_ax1_fused_0 in T.serial(16): for ax0_ax1_fused_1 in T.thread_binding(16, thread="threadIdx.x"): for ax0_ax1_fused_2 in T.vectorized(16): with T.block("pad_temp_reindex_shared"): v0 = T.axis.spatial(50176, ax2_0_0_ax3_0_0_fused // 8 * 128 + (ax0_ax1_fused_0 * 256 + ax0_ax1_fused_1 * 16 + ax0_ax1_fused_2) // 32) v1 = T.axis.spatial(64, ax4_0_0 * 32 + (ax0_ax1_fused_0 * 256 + ax0_ax1_fused_1 * 16 + ax0_ax1_fused_2) % 32) T.reads(p0[v0 // 3136, v0 % 3136 // 56, v0 % 56, v1]) T.writes(pad_temp_reindex_shared[v0, v1]) T.block_attr({"buffer_dim_align":[[0, 0, 32, 16]]}) pad_temp_reindex_shared[v0, v1] = p0[v0 // 3136, v0 % 3136 // 56, v0 % 56, v1] for ax0_ax1_ax2_ax3_fused_0 in T.serial(8): for ax0_ax1_ax2_ax3_fused_1 in T.thread_binding(16, thread="threadIdx.x"): for ax0_ax1_ax2_ax3_fused_2 in T.vectorized(8): with T.block("p1_reindex_shared"): v0 = T.axis.spatial(1, 0) v1 = T.axis.spatial(1, 0) v2 = T.axis.spatial(256, ax2_0_0_ax3_0_0_fused % 8 * 32 + (ax0_ax1_ax2_ax3_fused_0 * 128 + ax0_ax1_ax2_ax3_fused_1 * 8 + ax0_ax1_ax2_ax3_fused_2) // 32) v3 = T.axis.spatial(64, ax4_0_0 * 32 + (ax0_ax1_ax2_ax3_fused_0 * 128 + ax0_ax1_ax2_ax3_fused_1 * 8 + ax0_ax1_ax2_ax3_fused_2) % 32) T.reads(p1[v2, v0, v1, v3]) T.writes(p1_reindex_shared[v0, v1, v2, v3]) T.block_attr({"buffer_dim_align":[[0, 2, 32, 16]]}) p1_reindex_shared[v0, v1, v2, v3] = p1[v2, v0, v1, v3] for ax0_1, ax1_1, ax4_0_1 in T.grid(1, 1, 1): for ax0_0_1, ax1_0_1 in T.grid(1, 2): with T.block("pad_temp_reindex_shared_wmma.matrix_a_o"): v0_o = T.axis.spatial(3136, ax2_0_0_ax3_0_0_fused // 8 * 8 + ax2_0_2_ax3_0_2_fused // 2) v1_o = T.axis.spatial(4, ax4_0_0 * 2 + ax1_0_1) T.reads(pad_temp_reindex_shared[v0_o * 16 : v0_o * 16 + 16, v1_o * 16 : v1_o * 16 + 16]) T.writes(pad_temp_reindex_shared_wmma_matrix_a[v0_o * 16 : v0_o * 16 + 16, v1_o * 16 : v1_o * 16 + 16]) A = T.match_buffer(pad_temp_reindex_shared[v0_o * 16 : v0_o * 16 + 16, v1_o * 16 : v1_o * 16 + 16], [16, 16], dtype="int8", strides=[s1, s0], scope="shared", offset_factor=16) C_1 = T.match_buffer(pad_temp_reindex_shared_wmma_matrix_a[v0_o * 16 : v0_o * 16 + 16, v1_o * 16 : v1_o * 16 + 16], [16, 16], dtype="int8", strides=[d1_1, d0_1], scope="wmma.matrix_a", offset_factor=16) T.evaluate(T.tvm_load_matrix_sync(C_1.data, 16, 16, 16, C_1.elem_offset // d1_1 // 16 * (d1_1 // 16) + C_1.elem_offset % d1_1 // 16, T.tvm_access_ptr(T.type_annotation(dtype="int8"), A.data, A.elem_offset, s1 * 16, 1, dtype="handle"), s1, "row_major", dtype="handle")) for ax0, ax1, ax2_0, ax3_0 in T.grid(1, 1, 1, 2): with T.block("p1_reindex_shared_wmma.matrix_b_o"): v0 = T.axis.spatial(1, 0) v1 = T.axis.spatial(1, 0) v2_o = T.axis.spatial(16, ax2_0_0_ax3_0_0_fused % 8 * 2 + ax2_0_2_ax3_0_2_fused % 2) v3_o = T.axis.spatial(4, ax4_0_0 * 2 + ax3_0) T.reads(p1_reindex_shared[v0, v1, v2_o * 16 : v2_o * 16 + 16, v3_o * 16 : v3_o * 16 + 16]) T.writes(p1_reindex_shared_wmma_matrix_b[v0, v1, v2_o * 16 : v2_o * 16 + 16, v3_o * 16 : v3_o * 16 + 16]) A_1 = T.match_buffer(p1_reindex_shared[v0, v1, v2_o * 16 : v2_o * 16 + 16, v3_o * 16 : v3_o * 16 + 16], [16, 16], dtype="int8", strides=[s1_1, s0_1], scope="shared", offset_factor=16) C_2 = T.match_buffer(p1_reindex_shared_wmma_matrix_b[v0, v1, v2_o * 16 : v2_o * 16 + 16, v3_o * 16 : v3_o * 16 + 16], [16, 16], dtype="int8", strides=[d1_2, d0_2], scope="wmma.matrix_b", offset_factor=16) T.evaluate(T.tvm_load_matrix_sync(C_2.data, 16, 16, 16, C_2.elem_offset // d1_2 // 16 * (d1_2 // 16) + C_2.elem_offset % d1_2 // 16, T.tvm_access_ptr(T.type_annotation(dtype="int8"), A_1.data, A_1.elem_offset, s1_1 * 16, 1, dtype="handle"), s1_1, "col_major", dtype="handle")) for ax2_0_3, ax3_0_3, ax0_2, ax1_2, ax4_0_2, ax2_0_4, ax3_0_4 in T.grid(1, 1, 1, 1, 2, 1, 1): with T.block("conv2d_nhwc_o_update"): v0 = T.axis.reduce(1, 0) v1 = T.axis.reduce(1, 0) v2_o = T.axis.spatial(3136, ax2_0_0_ax3_0_0_fused // 8 * 8 + ax2_0_2_ax3_0_2_fused // 2 + ax2_0_3 + ax2_0_4) v3_o = T.axis.spatial(16, ax3_0_4 + ax2_0_0_ax3_0_0_fused % 8 * 2 + ax2_0_2_ax3_0_2_fused % 2 + ax3_0_3) v4_o = T.axis.reduce(4, ax4_0_0 * 2 + ax4_0_1 * 2 + ax4_0_2) T.reads(conv2d_nhwc_reindex_shared_wmma_accumulator[v2_o * 16 : v2_o * 16 + 16, v3_o * 16 : v3_o * 16 + 16], pad_temp_reindex_shared_wmma_matrix_a[v2_o * 16 : v2_o * 16 + 16, v4_o * 16 : v4_o * 16 + 16], p1_reindex_shared_wmma_matrix_b[v0, v1, v3_o * 16 : v3_o * 16 + 16, v4_o * 16 : v4_o * 16 + 16]) T.writes(conv2d_nhwc_reindex_shared_wmma_accumulator[v2_o * 16 : v2_o * 16 + 16, v3_o * 16 : v3_o * 16 + 16]) T.block_attr({"meta_schedule.thread_extent_high_inclusive":1024, "meta_schedule.thread_extent_low_inclusive":32, "warp_execution":1}) A_2 = T.match_buffer(pad_temp_reindex_shared_wmma_matrix_a[v2_o * 16 : v2_o * 16 + 16, v4_o * 16 : v4_o * 16 + 16], [16, 16], dtype="int8", strides=[a1, a0], scope="wmma.matrix_a", offset_factor=16) B = T.match_buffer(p1_reindex_shared_wmma_matrix_b[v0, v1, v3_o * 16 : v3_o * 16 + 16, v4_o * 16 : v4_o * 16 + 16], [16, 16], dtype="int8", strides=[b1, b0], scope="wmma.matrix_b", offset_factor=16) C_3 = T.match_buffer(conv2d_nhwc_reindex_shared_wmma_accumulator[v2_o * 16 : v2_o * 16 + 16, v3_o * 16 : v3_o * 16 + 16], [16, 16], dtype="int32", strides=[c1, c0], scope="wmma.accumulator", offset_factor=16) T.evaluate(T.tvm_mma_sync(C_3.data, C_3.elem_offset // c1 // 16 * (c1 // 16) + C_3.elem_offset % c1 // 16, A_2.data, A_2.elem_offset // a1 // 16 * (a1 // 16) + A_2.elem_offset % a1 // 16, B.data, B.elem_offset // b1 // 16 * (b1 // 16) + B.elem_offset % b1 // 16, C_3.data, C_3.elem_offset // c1 // 16 * (c1 // 16) + C_3.elem_offset % c1 // 16, dtype="handle")) for ax0_0, ax1_0 in T.grid(1, 1): with T.block("conv2d_nhwc_reindex_shared_wmma.accumulator_o"): v0_o = T.axis.spatial(3136, ax2_0_0_ax3_0_0_fused // 8 * 8 + ax2_0_2_ax3_0_2_fused // 2) v1_o = T.axis.spatial(16, ax2_0_0_ax3_0_0_fused % 8 * 2 + ax2_0_2_ax3_0_2_fused % 2) T.reads(conv2d_nhwc_reindex_shared_wmma_accumulator[v0_o * 16 : v0_o * 16 + 16, v1_o * 16 : v1_o * 16 + 16]) T.writes(conv2d_nhwc_reindex_shared[v0_o * 16 : v0_o * 16 + 16, v1_o * 16 : v1_o * 16 + 16]) A_3 = T.match_buffer(conv2d_nhwc_reindex_shared_wmma_accumulator[v0_o * 16 : v0_o * 16 + 16, v1_o * 16 : v1_o * 16 + 16], [16, 16], dtype="int32", strides=[d1_3, d0_3], scope="wmma.accumulator", offset_factor=16) C_4 = T.match_buffer(conv2d_nhwc_reindex_shared[v0_o * 16 : v0_o * 16 + 16, v1_o * 16 : v1_o * 16 + 16], [16, 16], dtype="int32", strides=[s1_2, s0_2], scope="shared", offset_factor=16) T.evaluate(T.tvm_store_matrix_sync(A_3.data, 16, 16, 16, A_3.elem_offset // d1_3 // 16 * (d1_3 // 16) + A_3.elem_offset % d1_3 // 16, T.tvm_access_ptr(T.type_annotation(dtype="int32"), C_4.data, C_4.elem_offset, s1_2 * 16, 2, dtype="handle"), s1_2, "row_major", dtype="handle")) for ax0, ax1_0 in T.grid(128, 2): for ax1_1 in T.thread_binding(16, thread="threadIdx.x"): with T.block("conv2d_nhwc_reindex_shared"): v0 = T.axis.spatial(50176, ax2_0_0_ax3_0_0_fused // 8 * 128 + ax0) v1 = T.axis.spatial(256, ax2_0_0_ax3_0_0_fused % 8 * 32 + ax1_0 * 16 + ax1_1) T.reads(p7[()], conv2d_nhwc_reindex_shared[v0, v1], p2[0, 0, 0, v1], p3[0, 0, 0, v1], p4[0, 0, 0, v1], p5[0, 0, 0, v1], p6[0, 0, 0, v1], p8[0], p9[v0 // 3136, v0 % 3136 // 56, v0 % 56, v1]) T.writes(compute[v0 // 3136, v0 % 3136 // 56, v0 % 56, v1]) compute[v0 // 3136, v0 % 3136 // 56, v0 % 56, v1] = T.max(T.min(T.cast(T.max(T.min(T.q_multiply_shift(T.cast(T.cast(T.max(T.min(p7[()] + T.cast(T.shift_right(T.cast(conv2d_nhwc_reindex_shared[v0, v1] - p2[0, 0, 0, v1] + p3[0, 0, 0, v1], "int64") * p4[0, 0, 0, v1] + p5[0, 0, 0, v1], p6[0, 0, 0, v1], dtype="int64"), "int32"), 255), 0), "uint8"), "int32") - p8[0], 1098990753, 31, 1, dtype="int32") + p9[v0 // 3136, v0 % 3136 // 56, v0 % 56, v1], 255), 0), "uint8"), T.uint8(255)), T.uint8(0)) @tvm.script.ir_module class Conv2dInt8_NCHWc: @T.prim_func def main(p0: T.Buffer[(1, 32, 7, 7, 16), "uint8"], p1: T.Buffer[(128, 32, 1, 1, 4, 16, 4), "int8"], p2: T.Buffer[(1, 128, 1, 1, 16), "int32"], p3: T.Buffer[(1, 128, 1, 1, 16), "float32"], p4: T.Buffer[1, "float32"], p5: T.Buffer[(1, 128, 7, 7, 16), "int32"], compute: T.Buffer[(1, 128, 7, 7, 16), "uint8"]) -> None: # function attr dict T.func_attr({"tir.noalias": True, "global_symbol": "main"}) # body # with T.block("root") compile_engine_const = T.alloc_buffer([], dtype="float32") conv2d_NCHWc_int8 = T.alloc_buffer([1, 128, 7, 7, 16], dtype="int32") T_add = T.alloc_buffer([1, 128, 7, 7, 16], dtype="int32") T_cast = T.alloc_buffer([1, 128, 7, 7, 16], dtype="float32") T_multiply = T.alloc_buffer([1, 128, 7, 7, 16], dtype="float32") compile_engine_const_1 = T.alloc_buffer([], dtype="float32") T_add_1 = T.alloc_buffer([1, 128, 7, 7, 16], dtype="float32") T_floor = T.alloc_buffer([1, 128, 7, 7, 16], dtype="float32") T_cast_1 = T.alloc_buffer([1, 128, 7, 7, 16], dtype="int32") compute_1 = T.alloc_buffer([1, 128, 7, 7, 16], dtype="int32") T_cast_2 = T.alloc_buffer([1, 128, 7, 7, 16], dtype="uint8") T_cast_3 = T.alloc_buffer([1, 128, 7, 7, 16], dtype="float32") T_subtract = T.alloc_buffer([1, 128, 7, 7, 16], dtype="float32") T_multiply_1 = T.alloc_buffer([1, 128, 7, 7, 16], dtype="float32") compile_engine_const_2 = T.alloc_buffer([], dtype="float32") T_add_2 = T.alloc_buffer([1, 128, 7, 7, 16], dtype="float32") T_floor_1 = T.alloc_buffer([1, 128, 7, 7, 16], dtype="float32") T_cast_4 = T.alloc_buffer([1, 128, 7, 7, 16], dtype="int32") T_add_3 = T.alloc_buffer([1, 128, 7, 7, 16], dtype="int32") compute_2 = T.alloc_buffer([1, 128, 7, 7, 16], dtype="int32") T_cast_5 = T.alloc_buffer([1, 128, 7, 7, 16], dtype="uint8") with T.block("compile_engine_const"): vi = T.axis.spatial(1, 0) T.reads() T.writes(compile_engine_const[()]) compile_engine_const[()] = T.float32(0.94537687301635742) for i0, i1, i2, i3, i4, i5, i6, i7, i8, i9 in T.grid(1, 128, 7, 7, 16, 1, 1, 32, 4, 4): with T.block("conv2d_NCHWc_int8"): n, oc_chunk, oh, ow, oc_block, kh, kw, ic_outer, ic_f_inner, ic_s_inner = T.axis.remap("SSSSSRRRRR", [i0, i1, i2, i3, i4, i5, i6, i7, i8, i9]) T.reads(p0[n, ic_outer, oh + kh, ow + kw, ic_f_inner * 4 + ic_s_inner], p1[oc_chunk, ic_outer, kh, kw, ic_f_inner, oc_block, ic_s_inner]) T.writes(conv2d_NCHWc_int8[n, oc_chunk, oh, ow, oc_block]) T.block_attr({"schedule_rule":"meta_schedule.conv2d_NCHWc_int8", "workload":["conv2d_NCHWc_int8.x86", ["TENSOR", [1, 32, 7, 7, 16], "uint8"], ["TENSOR", [128, 32, 1, 1, 4, 16, 4], "int8"], [1, 1], [0, 0, 0, 0], [1, 1], "NCHW16c", "NCHW16c", "int32"]}) with T.init(): conv2d_NCHWc_int8[n, oc_chunk, oh, ow, oc_block] = 0 conv2d_NCHWc_int8[n, oc_chunk, oh, ow, oc_block] = conv2d_NCHWc_int8[n, oc_chunk, oh, ow, oc_block] + T.cast(p0[n, ic_outer, oh + kh, ow + kw, ic_f_inner * 4 + ic_s_inner], "int32") * T.cast(p1[oc_chunk, ic_outer, kh, kw, ic_f_inner, oc_block, ic_s_inner], "int32") for i0, i1, i2, i3, i4 in T.grid(1, 128, 7, 7, 16): with T.block("T_add"): ax0, ax1, ax2, ax3, ax4 = T.axis.remap("SSSSS", [i0, i1, i2, i3, i4]) T.reads(conv2d_NCHWc_int8[ax0, ax1, ax2, ax3, ax4], p2[ax0, ax1, 0, 0, ax4]) T.writes(T_add[ax0, ax1, ax2, ax3, ax4]) T_add[ax0, ax1, ax2, ax3, ax4] = conv2d_NCHWc_int8[ax0, ax1, ax2, ax3, ax4] + p2[ax0, ax1, 0, 0, ax4] for i0, i1, i2, i3, i4 in T.grid(1, 128, 7, 7, 16): with T.block("T_cast"): ax0, ax1, ax2, ax3, ax4 = T.axis.remap("SSSSS", [i0, i1, i2, i3, i4]) T.reads(T_add[ax0, ax1, ax2, ax3, ax4]) T.writes(T_cast[ax0, ax1, ax2, ax3, ax4]) T_cast[ax0, ax1, ax2, ax3, ax4] = T.cast(T_add[ax0, ax1, ax2, ax3, ax4], "float32") for i0, i1, i2, i3, i4 in T.grid(1, 128, 7, 7, 16): with T.block("T_multiply"): ax0, ax1, ax2, ax3, ax4 = T.axis.remap("SSSSS", [i0, i1, i2, i3, i4]) T.reads(T_cast[ax0, ax1, ax2, ax3, ax4], p3[ax0, ax1, 0, 0, ax4]) T.writes(T_multiply[ax0, ax1, ax2, ax3, ax4]) T_multiply[ax0, ax1, ax2, ax3, ax4] = T_cast[ax0, ax1, ax2, ax3, ax4] * p3[ax0, ax1, 0, 0, ax4] with T.block("compile_engine_const_1"): vi = T.axis.spatial(1, 0) T.reads() T.writes(compile_engine_const_1[()]) compile_engine_const_1[()] = T.float32(54.5) for i0, i1, i2, i3, i4 in T.grid(1, 128, 7, 7, 16): with T.block("T_add_1"): ax0, ax1, ax2, ax3, ax4 = T.axis.remap("SSSSS", [i0, i1, i2, i3, i4]) T.reads(T_multiply[ax0, ax1, ax2, ax3, ax4], compile_engine_const_1[()]) T.writes(T_add_1[ax0, ax1, ax2, ax3, ax4]) T_add_1[ax0, ax1, ax2, ax3, ax4] = T_multiply[ax0, ax1, ax2, ax3, ax4] + compile_engine_const_1[()] for i0, i1, i2, i3, i4 in T.grid(1, 128, 7, 7, 16): with T.block("T_floor"): ax0, ax1, ax2, ax3, ax4 = T.axis.remap("SSSSS", [i0, i1, i2, i3, i4]) T.reads(T_add_1[ax0, ax1, ax2, ax3, ax4]) T.writes(T_floor[ax0, ax1, ax2, ax3, ax4]) T_floor[ax0, ax1, ax2, ax3, ax4] = T.floor(T_add_1[ax0, ax1, ax2, ax3, ax4], dtype="float32") for i0, i1, i2, i3, i4 in T.grid(1, 128, 7, 7, 16): with T.block("T_cast_1"): ax0, ax1, ax2, ax3, ax4 = T.axis.remap("SSSSS", [i0, i1, i2, i3, i4]) T.reads(T_floor[ax0, ax1, ax2, ax3, ax4]) T.writes(T_cast_1[ax0, ax1, ax2, ax3, ax4]) T_cast_1[ax0, ax1, ax2, ax3, ax4] = T.cast(T_floor[ax0, ax1, ax2, ax3, ax4], "int32") for i0, i1, i2, i3, i4 in T.grid(1, 128, 7, 7, 16): with T.block("compute"): i0_1, i1_1, i2_1, i3_1, i4_1 = T.axis.remap("SSSSS", [i0, i1, i2, i3, i4]) T.reads(T_cast_1[i0_1, i1_1, i2_1, i3_1, i4_1]) T.writes(compute_1[i0_1, i1_1, i2_1, i3_1, i4_1]) compute_1[i0_1, i1_1, i2_1, i3_1, i4_1] = T.max(T.min(T_cast_1[i0_1, i1_1, i2_1, i3_1, i4_1], 255), 0) for i0, i1, i2, i3, i4 in T.grid(1, 128, 7, 7, 16): with T.block("T_cast_2"): ax0, ax1, ax2, ax3, ax4 = T.axis.remap("SSSSS", [i0, i1, i2, i3, i4]) T.reads(compute_1[ax0, ax1, ax2, ax3, ax4]) T.writes(T_cast_2[ax0, ax1, ax2, ax3, ax4]) T_cast_2[ax0, ax1, ax2, ax3, ax4] = T.cast(compute_1[ax0, ax1, ax2, ax3, ax4], "uint8") for i0, i1, i2, i3, i4 in T.grid(1, 128, 7, 7, 16): with T.block("T_cast_3"): ax0, ax1, ax2, ax3, ax4 = T.axis.remap("SSSSS", [i0, i1, i2, i3, i4]) T.reads(T_cast_2[ax0, ax1, ax2, ax3, ax4]) T.writes(T_cast_3[ax0, ax1, ax2, ax3, ax4]) T_cast_3[ax0, ax1, ax2, ax3, ax4] = T.cast(T_cast_2[ax0, ax1, ax2, ax3, ax4], "float32") for i0, i1, i2, i3, i4 in T.grid(1, 128, 7, 7, 16): with T.block("T_subtract"): ax0, ax1, ax2, ax3, ax4 = T.axis.remap("SSSSS", [i0, i1, i2, i3, i4]) T.reads(T_cast_3[ax0, ax1, ax2, ax3, ax4], p4[0]) T.writes(T_subtract[ax0, ax1, ax2, ax3, ax4]) T_subtract[ax0, ax1, ax2, ax3, ax4] = T_cast_3[ax0, ax1, ax2, ax3, ax4] - p4[0] for i0, i1, i2, i3, i4 in T.grid(1, 128, 7, 7, 16): with T.block("T_multiply_1"): ax0, ax1, ax2, ax3, ax4 = T.axis.remap("SSSSS", [i0, i1, i2, i3, i4]) T.reads(compile_engine_const[()], T_subtract[ax0, ax1, ax2, ax3, ax4]) T.writes(T_multiply_1[ax0, ax1, ax2, ax3, ax4]) T_multiply_1[ax0, ax1, ax2, ax3, ax4] = compile_engine_const[()] * T_subtract[ax0, ax1, ax2, ax3, ax4] with T.block("compile_engine_const_2"): vi = T.axis.spatial(1, 0) T.reads() T.writes(compile_engine_const_2[()]) compile_engine_const_2[()] = T.float32(0.5) for i0, i1, i2, i3, i4 in T.grid(1, 128, 7, 7, 16): with T.block("T_add_2"): ax0, ax1, ax2, ax3, ax4 = T.axis.remap("SSSSS", [i0, i1, i2, i3, i4]) T.reads(T_multiply_1[ax0, ax1, ax2, ax3, ax4], compile_engine_const_2[()]) T.writes(T_add_2[ax0, ax1, ax2, ax3, ax4]) T_add_2[ax0, ax1, ax2, ax3, ax4] = T_multiply_1[ax0, ax1, ax2, ax3, ax4] + compile_engine_const_2[()] for i0, i1, i2, i3, i4 in T.grid(1, 128, 7, 7, 16): with T.block("T_floor_1"): ax0, ax1, ax2, ax3, ax4 = T.axis.remap("SSSSS", [i0, i1, i2, i3, i4]) T.reads(T_add_2[ax0, ax1, ax2, ax3, ax4]) T.writes(T_floor_1[ax0, ax1, ax2, ax3, ax4]) T_floor_1[ax0, ax1, ax2, ax3, ax4] = T.floor(T_add_2[ax0, ax1, ax2, ax3, ax4], dtype="float32") for i0, i1, i2, i3, i4 in T.grid(1, 128, 7, 7, 16): with T.block("T_cast_4"): ax0, ax1, ax2, ax3, ax4 = T.axis.remap("SSSSS", [i0, i1, i2, i3, i4]) T.reads(T_floor_1[ax0, ax1, ax2, ax3, ax4]) T.writes(T_cast_4[ax0, ax1, ax2, ax3, ax4]) T_cast_4[ax0, ax1, ax2, ax3, ax4] = T.cast(T_floor_1[ax0, ax1, ax2, ax3, ax4], "int32") for i0, i1, i2, i3, i4 in T.grid(1, 128, 7, 7, 16): with T.block("T_add_3"): ax0, ax1, ax2, ax3, ax4 = T.axis.remap("SSSSS", [i0, i1, i2, i3, i4]) T.reads(T_cast_4[ax0, ax1, ax2, ax3, ax4], p5[ax0, ax1, ax2, ax3, ax4]) T.writes(T_add_3[ax0, ax1, ax2, ax3, ax4]) T_add_3[ax0, ax1, ax2, ax3, ax4] = T_cast_4[ax0, ax1, ax2, ax3, ax4] + p5[ax0, ax1, ax2, ax3, ax4] for i0, i1, i2, i3, i4 in T.grid(1, 128, 7, 7, 16): with T.block("compute_1"): i0_2, i1_2, i2_2, i3_2, i4_2 = T.axis.remap("SSSSS", [i0, i1, i2, i3, i4]) T.reads(T_add_3[i0_2, i1_2, i2_2, i3_2, i4_2]) T.writes(compute_2[i0_2, i1_2, i2_2, i3_2, i4_2]) compute_2[i0_2, i1_2, i2_2, i3_2, i4_2] = T.max(T.min(T_add_3[i0_2, i1_2, i2_2, i3_2, i4_2], 255), 0) for i0_3, i1_3, i2_3, i3_3, i4_3 in T.grid(1, 128, 7, 7, 16): with T.block("T_cast_5"): ax0, ax1, ax2, ax3, ax4 = T.axis.remap("SSSSS", [i0_3, i1_3, i2_3, i3_3, i4_3]) T.reads(compute_2[ax0, ax1, ax2, ax3, ax4]) T.writes(T_cast_5[ax0, ax1, ax2, ax3, ax4]) T_cast_5[ax0, ax1, ax2, ax3, ax4] = T.cast(compute_2[ax0, ax1, ax2, ax3, ax4], "uint8") for i0_4, i1_4, i2_4, i3_4, i4_4 in T.grid(1, 128, 7, 7, 16): with T.block("compute_2"): i0_5, i1_5, i2_5, i3_5, i4_5 = T.axis.remap("SSSSS", [i0_4, i1_4, i2_4, i3_4, i4_4]) T.reads(T_cast_5[i0_5, i1_5, i2_5, i3_5, i4_5]) T.writes(compute[i0_5, i1_5, i2_5, i3_5, i4_5]) compute[i0_5, i1_5, i2_5, i3_5, i4_5] = T.max(T.min(T_cast_5[i0_5, i1_5, i2_5, i3_5, i4_5], T.uint8(255)), T.uint8(0)) @tvm.script.ir_module class Conv2dInt8_NCHWc_target: @T.prim_func def main(p0: T.Buffer[(1, 32, 7, 7, 16), "uint8"], p1: T.Buffer[(128, 32, 1, 1, 4, 16, 4), "int8"], p2: T.Buffer[(1, 128, 1, 1, 16), "int32"], p3: T.Buffer[(1, 128, 1, 1, 16), "float32"], p4: T.Buffer[1, "float32"], p5: T.Buffer[(1, 128, 7, 7, 16), "uint8"], T_cast: T.Buffer[(1, 128, 7, 7, 16), "int32"]) -> None: # function attr dict T.func_attr({"global_symbol": "main", "tir.noalias": True}) # body # with T.block("root") compile_engine_const = T.alloc_buffer([], dtype="float32") conv2d_NCHWc_int8 = T.alloc_buffer([1, 128, 7, 7, 16], dtype="int32") T_add = T.alloc_buffer([1, 128, 7, 7, 16], dtype="int32") T_cast_1 = T.alloc_buffer([1, 128, 7, 7, 16], dtype="float32") T_multiply = T.alloc_buffer([1, 128, 7, 7, 16], dtype="float32") compile_engine_const_1 = T.alloc_buffer([], dtype="float32") T_add_1 = T.alloc_buffer([1, 128, 7, 7, 16], dtype="float32") T_floor = T.alloc_buffer([1, 128, 7, 7, 16], dtype="float32") T_cast_2 = T.alloc_buffer([1, 128, 7, 7, 16], dtype="int32") compute = T.alloc_buffer([1, 128, 7, 7, 16], dtype="int32") T_cast_3 = T.alloc_buffer([1, 128, 7, 7, 16], dtype="uint8") T_cast_4 = T.alloc_buffer([1, 128, 7, 7, 16], dtype="float32") T_subtract = T.alloc_buffer([1, 128, 7, 7, 16], dtype="float32") T_multiply_1 = T.alloc_buffer([1, 128, 7, 7, 16], dtype="float32") compile_engine_const_2 = T.alloc_buffer([], dtype="float32") T_add_2 = T.alloc_buffer([1, 128, 7, 7, 16], dtype="float32") T_floor_1 = T.alloc_buffer([1, 128, 7, 7, 16], dtype="float32") T_cast_5 = T.alloc_buffer([1, 128, 7, 7, 16], dtype="int32") compile_engine_const_3 = T.alloc_buffer([], dtype="float32") T_cast_6 = T.alloc_buffer([1, 128, 7, 7, 16], dtype="float32") T_multiply_2 = T.alloc_buffer([1, 128, 7, 7, 16], dtype="float32") compile_engine_const_4 = T.alloc_buffer([], dtype="float32") T_add_3 = T.alloc_buffer([1, 128, 7, 7, 16], dtype="float32") T_floor_2 = T.alloc_buffer([1, 128, 7, 7, 16], dtype="float32") T_cast_7 = T.alloc_buffer([1, 128, 7, 7, 16], dtype="int32") T_add_4 = T.alloc_buffer([1, 128, 7, 7, 16], dtype="int32") compute_1 = T.alloc_buffer([1, 128, 7, 7, 16], dtype="int32") T_cast_8 = T.alloc_buffer([1, 128, 7, 7, 16], dtype="uint8") compute_2 = T.alloc_buffer([1, 128, 7, 7, 16], dtype="uint8") with T.block("compile_engine_const"): vi = T.axis.spatial(1, 0) T.reads() T.writes(compile_engine_const[()]) compile_engine_const[()] = T.float32(0.95489668846130371) for i0, i1, i2, i3, i4, i5, i6, i7, i8, i9 in T.grid(1, 128, 7, 7, 16, 1, 1, 32, 4, 4): with T.block("conv2d_NCHWc_int8"): n, oc_chunk, oh, ow, oc_block, kh, kw, ic_outer, ic_f_inner, ic_s_inner = T.axis.remap("SSSSSRRRRR", [i0, i1, i2, i3, i4, i5, i6, i7, i8, i9]) T.reads(p0[n, ic_outer, oh + kh, ow + kw, ic_f_inner * 4 + ic_s_inner], p1[oc_chunk, ic_outer, kh, kw, ic_f_inner, oc_block, ic_s_inner]) T.writes(conv2d_NCHWc_int8[n, oc_chunk, oh, ow, oc_block]) T.block_attr({"schedule_rule":"meta_schedule.conv2d_NCHWc_int8", "workload":["conv2d_NCHWc_int8.x86", ["TENSOR", [1, 32, 7, 7, 16], "uint8"], ["TENSOR", [128, 32, 1, 1, 4, 16, 4], "int8"], [1, 1], [0, 0, 0, 0], [1, 1], "NCHW16c", "NCHW16c", "int32"]}) with T.init(): conv2d_NCHWc_int8[n, oc_chunk, oh, ow, oc_block] = 0 conv2d_NCHWc_int8[n, oc_chunk, oh, ow, oc_block] = conv2d_NCHWc_int8[n, oc_chunk, oh, ow, oc_block] + T.cast(p0[n, ic_outer, oh + kh, ow + kw, ic_f_inner * 4 + ic_s_inner], "int32") * T.cast(p1[oc_chunk, ic_outer, kh, kw, ic_f_inner, oc_block, ic_s_inner], "int32") for i0, i1, i2, i3, i4 in T.grid(1, 128, 7, 7, 16): with T.block("T_add"): ax0, ax1, ax2, ax3, ax4 = T.axis.remap("SSSSS", [i0, i1, i2, i3, i4]) T.reads(conv2d_NCHWc_int8[ax0, ax1, ax2, ax3, ax4], p2[ax0, ax1, 0, 0, ax4]) T.writes(T_add[ax0, ax1, ax2, ax3, ax4]) T_add[ax0, ax1, ax2, ax3, ax4] = conv2d_NCHWc_int8[ax0, ax1, ax2, ax3, ax4] + p2[ax0, ax1, 0, 0, ax4] for i0, i1, i2, i3, i4 in T.grid(1, 128, 7, 7, 16): with T.block("T_cast"): ax0, ax1, ax2, ax3, ax4 = T.axis.remap("SSSSS", [i0, i1, i2, i3, i4]) T.reads(T_add[ax0, ax1, ax2, ax3, ax4]) T.writes(T_cast_1[ax0, ax1, ax2, ax3, ax4]) T_cast_1[ax0, ax1, ax2, ax3, ax4] = T.cast(T_add[ax0, ax1, ax2, ax3, ax4], "float32") for i0, i1, i2, i3, i4 in T.grid(1, 128, 7, 7, 16): with T.block("T_multiply"): ax0, ax1, ax2, ax3, ax4 = T.axis.remap("SSSSS", [i0, i1, i2, i3, i4]) T.reads(T_cast_1[ax0, ax1, ax2, ax3, ax4], p3[ax0, ax1, 0, 0, ax4]) T.writes(T_multiply[ax0, ax1, ax2, ax3, ax4]) T_multiply[ax0, ax1, ax2, ax3, ax4] = T_cast_1[ax0, ax1, ax2, ax3, ax4] * p3[ax0, ax1, 0, 0, ax4] with T.block("compile_engine_const_1"): vi = T.axis.spatial(1, 0) T.reads() T.writes(compile_engine_const_1[()]) compile_engine_const_1[()] = T.float32(65.5) for i0, i1, i2, i3, i4 in T.grid(1, 128, 7, 7, 16): with T.block("T_add_1"): ax0, ax1, ax2, ax3, ax4 = T.axis.remap("SSSSS", [i0, i1, i2, i3, i4]) T.reads(T_multiply[ax0, ax1, ax2, ax3, ax4], compile_engine_const_1[()]) T.writes(T_add_1[ax0, ax1, ax2, ax3, ax4]) T_add_1[ax0, ax1, ax2, ax3, ax4] = T_multiply[ax0, ax1, ax2, ax3, ax4] + compile_engine_const_1[()] for i0, i1, i2, i3, i4 in T.grid(1, 128, 7, 7, 16): with T.block("T_floor"): ax0, ax1, ax2, ax3, ax4 = T.axis.remap("SSSSS", [i0, i1, i2, i3, i4]) T.reads(T_add_1[ax0, ax1, ax2, ax3, ax4]) T.writes(T_floor[ax0, ax1, ax2, ax3, ax4]) T_floor[ax0, ax1, ax2, ax3, ax4] = T.floor(T_add_1[ax0, ax1, ax2, ax3, ax4], dtype="float32") for i0, i1, i2, i3, i4 in T.grid(1, 128, 7, 7, 16): with T.block("T_cast_1"): ax0, ax1, ax2, ax3, ax4 = T.axis.remap("SSSSS", [i0, i1, i2, i3, i4]) T.reads(T_floor[ax0, ax1, ax2, ax3, ax4]) T.writes(T_cast_2[ax0, ax1, ax2, ax3, ax4]) T_cast_2[ax0, ax1, ax2, ax3, ax4] = T.cast(T_floor[ax0, ax1, ax2, ax3, ax4], "int32") for i0, i1, i2, i3, i4 in T.grid(1, 128, 7, 7, 16): with T.block("compute"): i0_1, i1_1, i2_1, i3_1, i4_1 = T.axis.remap("SSSSS", [i0, i1, i2, i3, i4]) T.reads(T_cast_2[i0_1, i1_1, i2_1, i3_1, i4_1]) T.writes(compute[i0_1, i1_1, i2_1, i3_1, i4_1]) compute[i0_1, i1_1, i2_1, i3_1, i4_1] = T.max(T.min(T_cast_2[i0_1, i1_1, i2_1, i3_1, i4_1], 255), 0) for i0, i1, i2, i3, i4 in T.grid(1, 128, 7, 7, 16): with T.block("T_cast_2"): ax0, ax1, ax2, ax3, ax4 = T.axis.remap("SSSSS", [i0, i1, i2, i3, i4]) T.reads(compute[ax0, ax1, ax2, ax3, ax4]) T.writes(T_cast_3[ax0, ax1, ax2, ax3, ax4]) T_cast_3[ax0, ax1, ax2, ax3, ax4] = T.cast(compute[ax0, ax1, ax2, ax3, ax4], "uint8") for i0, i1, i2, i3, i4 in T.grid(1, 128, 7, 7, 16): with T.block("T_cast_3"): ax0, ax1, ax2, ax3, ax4 = T.axis.remap("SSSSS", [i0, i1, i2, i3, i4]) T.reads(T_cast_3[ax0, ax1, ax2, ax3, ax4]) T.writes(T_cast_4[ax0, ax1, ax2, ax3, ax4]) T_cast_4[ax0, ax1, ax2, ax3, ax4] = T.cast(T_cast_3[ax0, ax1, ax2, ax3, ax4], "float32") for i0, i1, i2, i3, i4 in T.grid(1, 128, 7, 7, 16): with T.block("T_subtract"): ax0, ax1, ax2, ax3, ax4 = T.axis.remap("SSSSS", [i0, i1, i2, i3, i4]) T.reads(T_cast_4[ax0, ax1, ax2, ax3, ax4], p4[0]) T.writes(T_subtract[ax0, ax1, ax2, ax3, ax4]) T_subtract[ax0, ax1, ax2, ax3, ax4] = T_cast_4[ax0, ax1, ax2, ax3, ax4] - p4[0] for i0, i1, i2, i3, i4 in T.grid(1, 128, 7, 7, 16): with T.block("T_multiply_1"): ax0, ax1, ax2, ax3, ax4 = T.axis.remap("SSSSS", [i0, i1, i2, i3, i4]) T.reads(compile_engine_const[()], T_subtract[ax0, ax1, ax2, ax3, ax4]) T.writes(T_multiply_1[ax0, ax1, ax2, ax3, ax4]) T_multiply_1[ax0, ax1, ax2, ax3, ax4] = compile_engine_const[()] * T_subtract[ax0, ax1, ax2, ax3, ax4] with T.block("compile_engine_const_2"): vi = T.axis.spatial(1, 0) T.reads() T.writes(compile_engine_const_2[()]) compile_engine_const_2[()] = T.float32(0.5) for i0, i1, i2, i3, i4 in T.grid(1, 128, 7, 7, 16): with T.block("T_add_2"): ax0, ax1, ax2, ax3, ax4 = T.axis.remap("SSSSS", [i0, i1, i2, i3, i4]) T.reads(T_multiply_1[ax0, ax1, ax2, ax3, ax4], compile_engine_const_2[()]) T.writes(T_add_2[ax0, ax1, ax2, ax3, ax4]) T_add_2[ax0, ax1, ax2, ax3, ax4] = T_multiply_1[ax0, ax1, ax2, ax3, ax4] + compile_engine_const_2[()] for i0, i1, i2, i3, i4 in T.grid(1, 128, 7, 7, 16): with T.block("T_floor_1"): ax0, ax1, ax2, ax3, ax4 = T.axis.remap("SSSSS", [i0, i1, i2, i3, i4]) T.reads(T_add_2[ax0, ax1, ax2, ax3, ax4]) T.writes(T_floor_1[ax0, ax1, ax2, ax3, ax4]) T_floor_1[ax0, ax1, ax2, ax3, ax4] = T.floor(T_add_2[ax0, ax1, ax2, ax3, ax4], dtype="float32") for i0, i1, i2, i3, i4 in T.grid(1, 128, 7, 7, 16): with T.block("T_cast_4"): ax0, ax1, ax2, ax3, ax4 = T.axis.remap("SSSSS", [i0, i1, i2, i3, i4]) T.reads(T_floor_1[ax0, ax1, ax2, ax3, ax4]) T.writes(T_cast_5[ax0, ax1, ax2, ax3, ax4]) T_cast_5[ax0, ax1, ax2, ax3, ax4] = T.cast(T_floor_1[ax0, ax1, ax2, ax3, ax4], "int32") with T.block("compile_engine_const_3"): vi = T.axis.spatial(1, 0) T.reads() T.writes(compile_engine_const_3[()]) compile_engine_const_3[()] = T.float32(0.71245479583740234) for i0, i1, i2, i3, i4 in T.grid(1, 128, 7, 7, 16): with T.block("T_cast_5"): ax0, ax1, ax2, ax3, ax4 = T.axis.remap("SSSSS", [i0, i1, i2, i3, i4]) T.reads(p5[ax0, ax1, ax2, ax3, ax4]) T.writes(T_cast_6[ax0, ax1, ax2, ax3, ax4]) T_cast_6[ax0, ax1, ax2, ax3, ax4] = T.cast(p5[ax0, ax1, ax2, ax3, ax4], "float32") for i0, i1, i2, i3, i4 in T.grid(1, 128, 7, 7, 16): with T.block("T_multiply_2"): ax0, ax1, ax2, ax3, ax4 = T.axis.remap("SSSSS", [i0, i1, i2, i3, i4]) T.reads(compile_engine_const_3[()], T_cast_6[ax0, ax1, ax2, ax3, ax4]) T.writes(T_multiply_2[ax0, ax1, ax2, ax3, ax4]) T_multiply_2[ax0, ax1, ax2, ax3, ax4] = compile_engine_const_3[()] * T_cast_6[ax0, ax1, ax2, ax3, ax4] with T.block("compile_engine_const_4"): vi = T.axis.spatial(1, 0) T.reads() T.writes(compile_engine_const_4[()]) compile_engine_const_4[()] = T.float32(0.5) for i0, i1, i2, i3, i4 in T.grid(1, 128, 7, 7, 16): with T.block("T_add_3"): ax0, ax1, ax2, ax3, ax4 = T.axis.remap("SSSSS", [i0, i1, i2, i3, i4]) T.reads(T_multiply_2[ax0, ax1, ax2, ax3, ax4], compile_engine_const_4[()]) T.writes(T_add_3[ax0, ax1, ax2, ax3, ax4]) T_add_3[ax0, ax1, ax2, ax3, ax4] = T_multiply_2[ax0, ax1, ax2, ax3, ax4] + compile_engine_const_4[()] for i0, i1, i2, i3, i4 in T.grid(1, 128, 7, 7, 16): with T.block("T_floor_2"): ax0, ax1, ax2, ax3, ax4 = T.axis.remap("SSSSS", [i0, i1, i2, i3, i4]) T.reads(T_add_3[ax0, ax1, ax2, ax3, ax4]) T.writes(T_floor_2[ax0, ax1, ax2, ax3, ax4]) T_floor_2[ax0, ax1, ax2, ax3, ax4] = T.floor(T_add_3[ax0, ax1, ax2, ax3, ax4], dtype="float32") for i0, i1, i2, i3, i4 in T.grid(1, 128, 7, 7, 16): with T.block("T_cast_6"): ax0, ax1, ax2, ax3, ax4 = T.axis.remap("SSSSS", [i0, i1, i2, i3, i4]) T.reads(T_floor_2[ax0, ax1, ax2, ax3, ax4]) T.writes(T_cast_7[ax0, ax1, ax2, ax3, ax4]) T_cast_7[ax0, ax1, ax2, ax3, ax4] = T.cast(T_floor_2[ax0, ax1, ax2, ax3, ax4], "int32") for i0, i1, i2, i3, i4 in T.grid(1, 128, 7, 7, 16): with T.block("T_add_4"): ax0, ax1, ax2, ax3, ax4 = T.axis.remap("SSSSS", [i0, i1, i2, i3, i4]) T.reads(T_cast_5[ax0, ax1, ax2, ax3, ax4], T_cast_7[ax0, ax1, ax2, ax3, ax4]) T.writes(T_add_4[ax0, ax1, ax2, ax3, ax4]) T_add_4[ax0, ax1, ax2, ax3, ax4] = T_cast_5[ax0, ax1, ax2, ax3, ax4] + T_cast_7[ax0, ax1, ax2, ax3, ax4] for i0, i1, i2, i3, i4 in T.grid(1, 128, 7, 7, 16): with T.block("compute_1"): i0_2, i1_2, i2_2, i3_2, i4_2 = T.axis.remap("SSSSS", [i0, i1, i2, i3, i4]) T.reads(T_add_4[i0_2, i1_2, i2_2, i3_2, i4_2]) T.writes(compute_1[i0_2, i1_2, i2_2, i3_2, i4_2]) compute_1[i0_2, i1_2, i2_2, i3_2, i4_2] = T.max(T.min(T_add_4[i0_2, i1_2, i2_2, i3_2, i4_2], 255), 0) for i0_3, i1_3, i2_3, i3_3, i4_3 in T.grid(1, 128, 7, 7, 16): with T.block("T_cast_7"): ax0, ax1, ax2, ax3, ax4 = T.axis.remap("SSSSS", [i0_3, i1_3, i2_3, i3_3, i4_3]) T.reads(compute_1[ax0, ax1, ax2, ax3, ax4]) T.writes(T_cast_8[ax0, ax1, ax2, ax3, ax4]) T_cast_8[ax0, ax1, ax2, ax3, ax4] = T.cast(compute_1[ax0, ax1, ax2, ax3, ax4], "uint8") for i0_4, i1_4, i2_4, i3_4, i4_4 in T.grid(1, 128, 7, 7, 16): with T.block("compute_2"): i0_5, i1_5, i2_5, i3_5, i4_5 = T.axis.remap("SSSSS", [i0_4, i1_4, i2_4, i3_4, i4_4]) T.reads(T_cast_8[i0_5, i1_5, i2_5, i3_5, i4_5]) T.writes(compute_2[i0_5, i1_5, i2_5, i3_5, i4_5]) compute_2[i0_5, i1_5, i2_5, i3_5, i4_5] = T.max(T.min(T_cast_8[i0_5, i1_5, i2_5, i3_5, i4_5], T.uint8(255)), T.uint8(0)) for i0_6, i1_6, i2_6, i3_6, i4_6 in T.grid(1, 128, 7, 7, 16): with T.block("T_cast_8"): ax0, ax1, ax2, ax3, ax4 = T.axis.remap("SSSSS", [i0_6, i1_6, i2_6, i3_6, i4_6]) T.reads(compute_2[ax0, ax1, ax2, ax3, ax4]) T.writes(T_cast[ax0, ax1, ax2, ax3, ax4]) T_cast[ax0, ax1, ax2, ax3, ax4] = T.cast(compute_2[ax0, ax1, ax2, ax3, ax4], "int32") def get_conv2d_vnni_mod(intrin_id): @tvm.script.ir_module class Conv2dInt8_NCHWc_scheduled: @T.prim_func def main(p0: T.Buffer[(1, 32, 7, 7, 16), "uint8"], p1: T.Buffer[(128, 32, 1, 1, 4, 16, 4), "int8"], p2: T.Buffer[(1, 128, 1, 1, 16), "int32"], p3: T.Buffer[(1, 128, 1, 1, 16), "float32"], p4: T.Buffer[1, "float32"], p5: T.Buffer[(1, 128, 7, 7, 16), "uint8"], T_cast: T.Buffer[(1, 128, 7, 7, 16), "int32"]) -> None: # function attr dict T.func_attr({"global_symbol": "main", "tir.noalias": True}) # body # with T.block("root") conv2d_NCHWc_int8 = T.alloc_buffer([1, 128, 7, 7, 16], dtype="int32") for i0_0_i1_0_i2_0_i3_0_i4_0_0_i0_1_i1_1_fused in T.parallel(128, annotations={"pragma_auto_unroll_max_step":64, "pragma_unroll_explicit":1}): for i2_1, i3_1, i4_0_1 in T.grid(7, 1, 1): for i5_0, i6_0 in T.grid(1, 1): for i1_2_init, i2_2_init, i3_2_init, i1_3_init, i2_3_init, i3_3_init in T.grid(1, 1, 1, 1, 1, 7): with T.block("conv2d_NCHWc_int8_o_init"): n = T.axis.spatial(1, 0) oc_chunk = T.axis.spatial(128, i1_2_init + i1_3_init + i0_0_i1_0_i2_0_i3_0_i4_0_0_i0_1_i1_1_fused // 32 * 32 + i0_0_i1_0_i2_0_i3_0_i4_0_0_i0_1_i1_1_fused % 32) oh = T.axis.spatial(7, i2_1 + i2_2_init + i2_3_init) ow = T.axis.spatial(7, i3_1 * 7 + i3_2_init * 7 + i3_3_init) oc_block_o = T.axis.spatial(1, 0) T.reads() T.writes(conv2d_NCHWc_int8[n, oc_chunk, oh, ow, 0 : 16]) for i4_1 in T.vectorized(16): with T.block("conv2d_NCHWc_int8_init"): oc_block_i_init = T.axis.spatial(16, i4_1) T.reads() T.writes(conv2d_NCHWc_int8[n, oc_chunk, oh, ow, oc_block_i_init]) conv2d_NCHWc_int8[n, oc_chunk, oh, ow, oc_block_i_init] = 0 for i7_0, i8_0, i9_0_0, i0_2, i1_2, i2_2, i3_2, i4_0_2, i5_1, i6_1, i7_1, i8_1, i9_0_1, i0_3, i1_3, i2_3, i3_3, i4_0_3 in T.grid(4, 4, 1, 1, 1, 1, 1, 1, 1, 1, 8, 1, 1, 1, 1, 1, 7, 1): with T.block("conv2d_NCHWc_int8_o_update"): n = T.axis.spatial(1, 0) oc_chunk = T.axis.spatial(128, i1_2 + i1_3 + i0_0_i1_0_i2_0_i3_0_i4_0_0_i0_1_i1_1_fused // 32 * 32 + i0_0_i1_0_i2_0_i3_0_i4_0_0_i0_1_i1_1_fused % 32) oh = T.axis.spatial(7, i2_1 + i2_2 + i2_3) ow = T.axis.spatial(7, i3_1 * 7 + i3_2 * 7 + i3_3) oc_block_o = T.axis.spatial(1, 0) kh = T.axis.reduce(1, 0) kw = T.axis.reduce(1, 0) ic_outer = T.axis.reduce(32, i7_0 * 8 + i7_1) ic_f_inner = T.axis.reduce(4, i8_1 + i8_0) ic_s_inner_o = T.axis.reduce(1, 0) T.reads(conv2d_NCHWc_int8[n, oc_chunk, oh, ow, 0 : 16], p0[n, ic_outer, oh + kh, ow + kw, ic_f_inner * 4 : ic_f_inner * 4 + 4], p1[oc_chunk, ic_outer, kh, kw, ic_f_inner, 0 : 16, 0 : 4]) T.writes(conv2d_NCHWc_int8[n, oc_chunk, oh, ow, 0 : 16]) A = T.match_buffer(p0[n, ic_outer, oh + kh, ow + kw, ic_f_inner * 4 : ic_f_inner * 4 + 4], [4], dtype="uint8", offset_factor=1) B = T.match_buffer(p1[oc_chunk, ic_outer, kh, kw, ic_f_inner, 0 : 16, 0 : 4], [16, 4], dtype="int8", offset_factor=1) C = T.match_buffer(conv2d_NCHWc_int8[n, oc_chunk, oh, ow, 0 : 16], [16], dtype="int32", offset_factor=1) A_u8x4: T.uint8x4 = A[0:4] A_i32: T.int32 = T.reinterpret(A_u8x4, dtype="int32") B_i8x64: T.int8x64 = B[0, 0:64] B_i32x16: T.int32x16 = T.reinterpret(B_i8x64, dtype="int32x16") C_i32x16: T.int32x16 = C[0:16] C[0:16] = T.call_llvm_pure_intrin(intrin_id, T.uint32(0), C_i32x16, T.broadcast(A_i32, 16), B_i32x16, dtype="int32x16") for ax0, ax1, ax2, ax3 in T.grid(1, 1, 1, 7): for ax4_fused in T.vectorized(16): with T.block("T_cast_8"): ax0_1 = T.axis.spatial(1, ax0) ax1_1 = T.axis.spatial(128, i0_0_i1_0_i2_0_i3_0_i4_0_0_i0_1_i1_1_fused // 32 * 32 + i0_0_i1_0_i2_0_i3_0_i4_0_0_i0_1_i1_1_fused % 32 + ax1) ax2_1 = T.axis.spatial(7, i2_1 + ax2) ax3_1, ax4 = T.axis.remap("SS", [ax3, ax4_fused]) T.reads(conv2d_NCHWc_int8[ax0_1, ax1_1, ax2_1, ax3_1, ax4], p2[ax0_1, ax1_1, 0, 0, ax4], p3[ax0_1, ax1_1, 0, 0, ax4], p4[0], p5[ax0_1, ax1_1, ax2_1, ax3_1, ax4]) T.writes(T_cast[ax0_1, ax1_1, ax2_1, ax3_1, ax4]) T_cast[ax0_1, ax1_1, ax2_1, ax3_1, ax4] = T.cast(T.max(T.min(T.cast(T.max(T.min(T.cast(T.floor(T.float32(0.95489668846130371) * (T.cast(T.cast(T.max(T.min(T.cast(T.floor(T.cast(conv2d_NCHWc_int8[ax0_1, ax1_1, ax2_1, ax3_1, ax4] + p2[ax0_1, ax1_1, 0, 0, ax4], "float32") * p3[ax0_1, ax1_1, 0, 0, ax4] + T.float32(65.5), dtype="float32"), "int32"), 255), 0), "uint8"), "float32") - p4[0]) + T.float32(0.5), dtype="float32"), "int32") + T.cast(T.floor(T.float32(0.71245479583740234) * T.cast(p5[ax0_1, ax1_1, ax2_1, ax3_1, ax4], "float32") + T.float32(0.5), dtype="float32"), "int32"), 255), 0), "uint8"), T.uint8(255)), T.uint8(0)), "int32") return Conv2dInt8_NCHWc_scheduled @tvm.script.ir_module class Conv2dWinogradAddRelu: @T.prim_func def main(p0: T.Buffer[(1, 56, 56, 64), "float32"], p1: T.Buffer[(6, 6, 64, 64), "float32"], p2: T.Buffer[(1, 1, 1, 64), "float32"], T_relu: T.Buffer[(1, 56, 56, 64), "float32"]) -> None: # function attr dict T.func_attr({"layout_free_buffers": [1], "tir.noalias": True, "global_symbol": "main"}) # body # with T.block("root") data_pad = T.alloc_buffer([1, 58, 58, 64], dtype="float32") input_tile = T.alloc_buffer([6, 6, 196, 64], dtype="float32") B = T.alloc_buffer([6, 6], dtype="float32") data_pack = T.alloc_buffer([6, 6, 196, 64], dtype="float32") bgemm = T.alloc_buffer([6, 6, 196, 64], dtype="float32") A = T.alloc_buffer([6, 4], dtype="float32") inverse = T.alloc_buffer([4, 4, 196, 64], dtype="float32") conv2d_winograd = T.alloc_buffer([1, 56, 56, 64], dtype="float32") T_add = T.alloc_buffer([1, 56, 56, 64], dtype="float32") for i0, i1, i2, i3 in T.grid(1, 58, 58, 64): with T.block("data_pad"): i0_1, i1_1, i2_1, i3_1 = T.axis.remap("SSSS", [i0, i1, i2, i3]) T.reads(p0[i0_1, i1_1 - 1, i2_1 - 1, i3_1]) T.writes(data_pad[i0_1, i1_1, i2_1, i3_1]) T.block_attr({"schedule_rule":"None"}) data_pad[i0_1, i1_1, i2_1, i3_1] = T.if_then_else(1 <= i1_1 and i1_1 < 57 and 1 <= i2_1 and i2_1 < 57, p0[i0_1, i1_1 - 1, i2_1 - 1, i3_1], T.float32(0), dtype="float32") for i0, i1, i2, i3 in T.grid(6, 6, 196, 64): with T.block("input_tile"): eps, nu, p, ci = T.axis.remap("SSSS", [i0, i1, i2, i3]) T.reads(data_pad[p // 196, p % 196 // 14 * 4 + eps, p % 14 * 4 + nu, ci]) T.writes(input_tile[eps, nu, p, ci]) T.block_attr({"schedule_rule":"None"}) input_tile[eps, nu, p, ci] = data_pad[p // 196, p % 196 // 14 * 4 + eps, p % 14 * 4 + nu, ci] for i0, i1 in T.grid(6, 6): with T.block("B"): i, j = T.axis.remap("SS", [i0, i1]) T.reads() T.writes(B[i, j]) T.block_attr({"const_matrix":True, "schedule_rule":"meta_schedule.compute_inline"}) B[i, j] = T.Select(i % 6 == 5 and j % 6 == 5, T.float32(1), T.Select(i % 6 == 5 and j % 6 == 4, T.float32(0), T.Select(i % 6 == 5 and j % 6 == 3, T.float32(0), T.Select(i % 6 == 5 and j % 6 == 2, T.float32(0), T.Select(i % 6 == 5 and j % 6 == 1, T.float32(0), T.Select(i % 6 == 5 and j % 6 == 0, T.float32(0), T.Select(i % 6 == 4 and j % 6 == 5, T.float32(1.5), T.Select(i % 6 == 4 and j % 6 == 4, T.float32(1), T.Select(i % 6 == 4 and j % 6 == 3, T.float32(1), T.Select(i % 6 == 4 and j % 6 == 2, T.float32(1), T.Select(i % 6 == 4 and j % 6 == 1, T.float32(1), T.Select(i % 6 == 4 and j % 6 == 0, T.float32(1), T.Select(i % 6 == 3 and j % 6 == 5, T.float32(-2), T.Select(i % 6 == 3 and j % 6 == 4, T.float32(-0.5), T.Select(i % 6 == 3 and j % 6 == 3, T.float32(2), T.Select(i % 6 == 3 and j % 6 == 2, T.float32(2.5), T.Select(i % 6 == 3 and j % 6 == 1, T.float32(0.5), T.Select(i % 6 == 3 and j % 6 == 0, T.float32(1.5), T.Select(i % 6 == 2 and j % 6 == 5, T.float32(-1.5), T.Select(i % 6 == 2 and j % 6 == 4, T.float32(-1), T.Select(i % 6 == 2 and j % 6 == 3, T.float32(-1), T.Select(i % 6 == 2 and j % 6 == 2, T.float32(0.5), T.Select(i % 6 == 2 and j % 6 == 1, T.float32(-2.5), T.Select(i % 6 == 2 and j % 6 == 0, T.float32(-2), T.Select(i % 6 == 1 and j % 6 == 5, T.float32(1), T.Select(i % 6 == 1 and j % 6 == 4, T.float32(0.5), T.Select(i % 6 == 1 and j % 6 == 3, T.float32(-2), T.Select(i % 6 == 1 and j % 6 == 2, T.float32(-1), T.Select(i % 6 == 1 and j % 6 == 1, T.float32(1), T.Select(i % 6 == 1 and j % 6 == 0, T.float32(-1.5), T.Select(i % 6 == 0 and j % 6 == 5, T.float32(0), T.Select(i % 6 == 0 and j % 6 == 4, T.float32(0), T.Select(i % 6 == 0 and j % 6 == 3, T.float32(0), T.Select(i % 6 == 0 and j % 6 == 2, T.float32(0), T.Select(i % 6 == 0 and j % 6 == 1, T.float32(0), T.Select(i % 6 == 0 and j % 6 == 0, T.float32(1), T.float32(0))))))))))))))))))))))))))))))))))))) for i0, i1, i2, i3, i4, i5 in T.grid(6, 6, 196, 64, 6, 6): with T.block("data_pack"): eps, nu, p, ci, r_a, r_b = T.axis.remap("SSSSRR", [i0, i1, i2, i3, i4, i5]) T.reads(input_tile[r_a, r_b, p, ci], B[T.min(r_a, r_b) : T.max(r_a, r_b) + 1, T.min(eps, nu) : T.max(eps, nu) + 1]) T.writes(data_pack[eps, nu, p, ci]) T.block_attr({"auto_scheduler_simplify_const_tensor_indices":["eps", "nu", "r_a", "r_b"], "schedule_rule":"meta_schedule.winograd_data_pack.cuda"}) with T.init(): data_pack[eps, nu, p, ci] = T.float32(0) data_pack[eps, nu, p, ci] = data_pack[eps, nu, p, ci] + input_tile[r_a, r_b, p, ci] * B[r_a, eps] * B[r_b, nu] for i0, i1, i2, i3, i4 in T.grid(6, 6, 196, 64, 64): with T.block("bgemm"): eps, nu, p, co, ci = T.axis.remap("SSSSR", [i0, i1, i2, i3, i4]) T.reads(data_pack[eps, nu, p, ci], p1[eps, nu, co, ci]) T.writes(bgemm[eps, nu, p, co]) T.block_attr({"layout_free_placeholders":[]}) with T.init(): bgemm[eps, nu, p, co] = T.float32(0) bgemm[eps, nu, p, co] = bgemm[eps, nu, p, co] + data_pack[eps, nu, p, ci] * p1[eps, nu, co, ci] for i0, i1 in T.grid(6, 4): with T.block("A"): i, j = T.axis.remap("SS", [i0, i1]) T.reads() T.writes(A[i, j]) T.block_attr({"const_matrix":True, "schedule_rule":"meta_schedule.compute_inline"}) A[i, j] = T.Select(i % 6 == 5 and j % 4 == 3, T.float32(1), T.Select(i % 6 == 5 and j % 4 == 2, T.float32(0), T.Select(i % 6 == 5 and j % 4 == 1, T.float32(0), T.Select(i % 6 == 5 and j % 4 == 0, T.float32(0), T.Select(i % 6 == 4 and j % 4 == 3, T.float32(-8), T.Select(i % 6 == 4 and j % 4 == 2, T.float32(4), T.Select(i % 6 == 4 and j % 4 == 1, T.float32(-2), T.Select(i % 6 == 4 and j % 4 == 0, T.float32(1), T.Select(i % 6 == 3 and j % 4 == 3, T.float32(0.125), T.Select(i % 6 == 3 and j % 4 == 2, T.float32(0.25), T.Select(i % 6 == 3 and j % 4 == 1, T.float32(0.5), T.Select(i % 6 == 3 and j % 4 == 0, T.float32(1), T.Select(i % 6 == 2 and j % 4 == 3, T.float32(1), T.Select(i % 6 == 2 and j % 4 == 2, T.float32(1), T.Select(i % 6 == 2 and j % 4 == 1, T.float32(1), T.Select(i % 6 == 2 and j % 4 == 0, T.float32(1), T.Select(i % 6 == 1 and j % 4 == 3, T.float32(-1), T.Select(i % 6 == 1 and j % 4 == 2, T.float32(1), T.Select(i % 6 == 1 and j % 4 == 1, T.float32(-1), T.Select(i % 6 == 1 and j % 4 == 0, T.float32(1), T.Select(i % 6 == 0 and j % 4 == 3, T.float32(0), T.Select(i % 6 == 0 and j % 4 == 2, T.float32(0), T.Select(i % 6 == 0 and j % 4 == 1, T.float32(0), T.Select(i % 6 == 0 and j % 4 == 0, T.float32(1), T.float32(0))))))))))))))))))))))))) for i0, i1, i2, i3, i4, i5 in T.grid(4, 4, 196, 64, 6, 6): with T.block("inverse"): vh, vw, p, co, r_a, r_b = T.axis.remap("SSSSRR", [i0, i1, i2, i3, i4, i5]) T.reads(bgemm[r_a, r_b, p, co], A[T.min(r_a, r_b) : T.max(r_a, r_b) + 1, T.min(vh, vw) : T.max(vh, vw) + 1]) T.writes(inverse[vh, vw, p, co]) T.block_attr({"auto_scheduler_simplify_const_tensor_indices":["vh", "vw", "r_a", "r_b"], "schedule_rule":"meta_schedule.winograd_inverse.cuda"}) with T.init(): inverse[vh, vw, p, co] = T.float32(0) inverse[vh, vw, p, co] = inverse[vh, vw, p, co] + bgemm[r_a, r_b, p, co] * A[r_a, vh] * A[r_b, vw] for i0, i1, i2, i3 in T.grid(1, 56, 56, 64): with T.block("conv2d_winograd"): n, h, w, co = T.axis.remap("SSSS", [i0, i1, i2, i3]) T.reads(inverse[h % 4, w % 4, n * 196 + h // 4 * 14 + w // 4, co]) T.writes(conv2d_winograd[n, h, w, co]) conv2d_winograd[n, h, w, co] = inverse[h % 4, w % 4, n * 196 + h // 4 * 14 + w // 4, co] for i0, i1, i2, i3 in T.grid(1, 56, 56, 64): with T.block("T_add"): ax0, ax1, ax2, ax3 = T.axis.remap("SSSS", [i0, i1, i2, i3]) T.reads(conv2d_winograd[ax0, ax1, ax2, ax3], p2[ax0, 0, 0, ax3]) T.writes(T_add[ax0, ax1, ax2, ax3]) T_add[ax0, ax1, ax2, ax3] = conv2d_winograd[ax0, ax1, ax2, ax3] + p2[ax0, 0, 0, ax3] for i0, i1, i2, i3 in T.grid(1, 56, 56, 64): with T.block("T_relu"): ax0, ax1, ax2, ax3 = T.axis.remap("SSSS", [i0, i1, i2, i3]) T.reads(T_add[ax0, ax1, ax2, ax3]) T.writes(T_relu[ax0, ax1, ax2, ax3]) T_relu[ax0, ax1, ax2, ax3] = T.max(T_add[ax0, ax1, ax2, ax3], T.float32(0)) @tvm.script.ir_module class Conv2dWinogradAddResidualRelu: @T.prim_func def main(p0: T.Buffer[(1, 56, 56, 64), "float32"], p1: T.Buffer[(6, 6, 64, 64), "float32"], p2: T.Buffer[(1, 1, 1, 64), "float32"], p3: T.Buffer[(1, 56, 56, 64), "float32"], T_relu: T.Buffer[(1, 56, 56, 64), "float32"]) -> None: # function attr dict T.func_attr({"global_symbol": "main", "tir.noalias": True, "layout_free_buffers": [1]}) # body # with T.block("root") data_pad = T.alloc_buffer([1, 58, 58, 64], dtype="float32") input_tile = T.alloc_buffer([6, 6, 196, 64], dtype="float32") B = T.alloc_buffer([6, 6], dtype="float32") data_pack = T.alloc_buffer([6, 6, 196, 64], dtype="float32") bgemm = T.alloc_buffer([6, 6, 196, 64], dtype="float32") A = T.alloc_buffer([6, 4], dtype="float32") inverse = T.alloc_buffer([4, 4, 196, 64], dtype="float32") conv2d_winograd = T.alloc_buffer([1, 56, 56, 64], dtype="float32") T_add = T.alloc_buffer([1, 56, 56, 64], dtype="float32") T_add_1 = T.alloc_buffer([1, 56, 56, 64], dtype="float32") for i0, i1, i2, i3 in T.grid(1, 58, 58, 64): with T.block("data_pad"): i0_1, i1_1, i2_1, i3_1 = T.axis.remap("SSSS", [i0, i1, i2, i3]) T.reads(p0[i0_1, i1_1 - 1, i2_1 - 1, i3_1]) T.writes(data_pad[i0_1, i1_1, i2_1, i3_1]) T.block_attr({"schedule_rule":"None"}) data_pad[i0_1, i1_1, i2_1, i3_1] = T.if_then_else(1 <= i1_1 and i1_1 < 57 and 1 <= i2_1 and i2_1 < 57, p0[i0_1, i1_1 - 1, i2_1 - 1, i3_1], T.float32(0), dtype="float32") for i0, i1, i2, i3 in T.grid(6, 6, 196, 64): with T.block("input_tile"): eps, nu, p, ci = T.axis.remap("SSSS", [i0, i1, i2, i3]) T.reads(data_pad[p // 196, p % 196 // 14 * 4 + eps, p % 14 * 4 + nu, ci]) T.writes(input_tile[eps, nu, p, ci]) T.block_attr({"schedule_rule":"None"}) input_tile[eps, nu, p, ci] = data_pad[p // 196, p % 196 // 14 * 4 + eps, p % 14 * 4 + nu, ci] for i0, i1 in T.grid(6, 6): with T.block("B"): i, j = T.axis.remap("SS", [i0, i1]) T.reads() T.writes(B[i, j]) T.block_attr({"const_matrix":True, "schedule_rule":"meta_schedule.compute_inline"}) B[i, j] = T.Select(i % 6 == 5 and j % 6 == 5, T.float32(1), T.Select(i % 6 == 5 and j % 6 == 4, T.float32(0), T.Select(i % 6 == 5 and j % 6 == 3, T.float32(0), T.Select(i % 6 == 5 and j % 6 == 2, T.float32(0), T.Select(i % 6 == 5 and j % 6 == 1, T.float32(0), T.Select(i % 6 == 5 and j % 6 == 0, T.float32(0), T.Select(i % 6 == 4 and j % 6 == 5, T.float32(1.5), T.Select(i % 6 == 4 and j % 6 == 4, T.float32(1), T.Select(i % 6 == 4 and j % 6 == 3, T.float32(1), T.Select(i % 6 == 4 and j % 6 == 2, T.float32(1), T.Select(i % 6 == 4 and j % 6 == 1, T.float32(1), T.Select(i % 6 == 4 and j % 6 == 0, T.float32(1), T.Select(i % 6 == 3 and j % 6 == 5, T.float32(-2), T.Select(i % 6 == 3 and j % 6 == 4, T.float32(-0.5), T.Select(i % 6 == 3 and j % 6 == 3, T.float32(2), T.Select(i % 6 == 3 and j % 6 == 2, T.float32(2.5), T.Select(i % 6 == 3 and j % 6 == 1, T.float32(0.5), T.Select(i % 6 == 3 and j % 6 == 0, T.float32(1.5), T.Select(i % 6 == 2 and j % 6 == 5, T.float32(-1.5), T.Select(i % 6 == 2 and j % 6 == 4, T.float32(-1), T.Select(i % 6 == 2 and j % 6 == 3, T.float32(-1), T.Select(i % 6 == 2 and j % 6 == 2, T.float32(0.5), T.Select(i % 6 == 2 and j % 6 == 1, T.float32(-2.5), T.Select(i % 6 == 2 and j % 6 == 0, T.float32(-2), T.Select(i % 6 == 1 and j % 6 == 5, T.float32(1), T.Select(i % 6 == 1 and j % 6 == 4, T.float32(0.5), T.Select(i % 6 == 1 and j % 6 == 3, T.float32(-2), T.Select(i % 6 == 1 and j % 6 == 2, T.float32(-1), T.Select(i % 6 == 1 and j % 6 == 1, T.float32(1), T.Select(i % 6 == 1 and j % 6 == 0, T.float32(-1.5), T.Select(i % 6 == 0 and j % 6 == 5, T.float32(0), T.Select(i % 6 == 0 and j % 6 == 4, T.float32(0), T.Select(i % 6 == 0 and j % 6 == 3, T.float32(0), T.Select(i % 6 == 0 and j % 6 == 2, T.float32(0), T.Select(i % 6 == 0 and j % 6 == 1, T.float32(0), T.Select(i % 6 == 0 and j % 6 == 0, T.float32(1), T.float32(0))))))))))))))))))))))))))))))))))))) for i0, i1, i2, i3, i4, i5 in T.grid(6, 6, 196, 64, 6, 6): with T.block("data_pack"): eps, nu, p, ci, r_a, r_b = T.axis.remap("SSSSRR", [i0, i1, i2, i3, i4, i5]) T.reads(input_tile[r_a, r_b, p, ci], B[T.min(r_a, r_b) : T.max(r_a, r_b) + 1, T.min(eps, nu) : T.max(eps, nu) + 1]) T.writes(data_pack[eps, nu, p, ci]) T.block_attr({"auto_scheduler_simplify_const_tensor_indices":["eps", "nu", "r_a", "r_b"], "schedule_rule":"meta_schedule.winograd_data_pack.cuda"}) with T.init(): data_pack[eps, nu, p, ci] = T.float32(0) data_pack[eps, nu, p, ci] = data_pack[eps, nu, p, ci] + input_tile[r_a, r_b, p, ci] * B[r_a, eps] * B[r_b, nu] for i0, i1, i2, i3, i4 in T.grid(6, 6, 196, 64, 64): with T.block("bgemm"): eps, nu, p, co, ci = T.axis.remap("SSSSR", [i0, i1, i2, i3, i4]) T.reads(data_pack[eps, nu, p, ci], p1[eps, nu, co, ci]) T.writes(bgemm[eps, nu, p, co]) T.block_attr({"layout_free_placeholders":[]}) with T.init(): bgemm[eps, nu, p, co] = T.float32(0) bgemm[eps, nu, p, co] = bgemm[eps, nu, p, co] + data_pack[eps, nu, p, ci] * p1[eps, nu, co, ci] for i0, i1 in T.grid(6, 4): with T.block("A"): i, j = T.axis.remap("SS", [i0, i1]) T.reads() T.writes(A[i, j]) T.block_attr({"const_matrix":True, "schedule_rule":"meta_schedule.compute_inline"}) A[i, j] = T.Select(i % 6 == 5 and j % 4 == 3, T.float32(1), T.Select(i % 6 == 5 and j % 4 == 2, T.float32(0), T.Select(i % 6 == 5 and j % 4 == 1, T.float32(0), T.Select(i % 6 == 5 and j % 4 == 0, T.float32(0), T.Select(i % 6 == 4 and j % 4 == 3, T.float32(-8), T.Select(i % 6 == 4 and j % 4 == 2, T.float32(4), T.Select(i % 6 == 4 and j % 4 == 1, T.float32(-2), T.Select(i % 6 == 4 and j % 4 == 0, T.float32(1), T.Select(i % 6 == 3 and j % 4 == 3, T.float32(0.125), T.Select(i % 6 == 3 and j % 4 == 2, T.float32(0.25), T.Select(i % 6 == 3 and j % 4 == 1, T.float32(0.5), T.Select(i % 6 == 3 and j % 4 == 0, T.float32(1), T.Select(i % 6 == 2 and j % 4 == 3, T.float32(1), T.Select(i % 6 == 2 and j % 4 == 2, T.float32(1), T.Select(i % 6 == 2 and j % 4 == 1, T.float32(1), T.Select(i % 6 == 2 and j % 4 == 0, T.float32(1), T.Select(i % 6 == 1 and j % 4 == 3, T.float32(-1), T.Select(i % 6 == 1 and j % 4 == 2, T.float32(1), T.Select(i % 6 == 1 and j % 4 == 1, T.float32(-1), T.Select(i % 6 == 1 and j % 4 == 0, T.float32(1), T.Select(i % 6 == 0 and j % 4 == 3, T.float32(0), T.Select(i % 6 == 0 and j % 4 == 2, T.float32(0), T.Select(i % 6 == 0 and j % 4 == 1, T.float32(0), T.Select(i % 6 == 0 and j % 4 == 0, T.float32(1), T.float32(0))))))))))))))))))))))))) for i0, i1, i2, i3, i4, i5 in T.grid(4, 4, 196, 64, 6, 6): with T.block("inverse"): vh, vw, p, co, r_a, r_b = T.axis.remap("SSSSRR", [i0, i1, i2, i3, i4, i5]) T.reads(bgemm[r_a, r_b, p, co], A[T.min(r_a, r_b) : T.max(r_a, r_b) + 1, T.min(vh, vw) : T.max(vh, vw) + 1]) T.writes(inverse[vh, vw, p, co]) T.block_attr({"auto_scheduler_simplify_const_tensor_indices":["vh", "vw", "r_a", "r_b"], "schedule_rule":"meta_schedule.winograd_inverse.cuda"}) with T.init(): inverse[vh, vw, p, co] = T.float32(0) inverse[vh, vw, p, co] = inverse[vh, vw, p, co] + bgemm[r_a, r_b, p, co] * A[r_a, vh] * A[r_b, vw] for i0, i1, i2, i3 in T.grid(1, 56, 56, 64): with T.block("conv2d_winograd"): n, h, w, co = T.axis.remap("SSSS", [i0, i1, i2, i3]) T.reads(inverse[h % 4, w % 4, n * 196 + h // 4 * 14 + w // 4, co]) T.writes(conv2d_winograd[n, h, w, co]) conv2d_winograd[n, h, w, co] = inverse[h % 4, w % 4, n * 196 + h // 4 * 14 + w // 4, co] for i0, i1, i2, i3 in T.grid(1, 56, 56, 64): with T.block("T_add"): ax0, ax1, ax2, ax3 = T.axis.remap("SSSS", [i0, i1, i2, i3]) T.reads(conv2d_winograd[ax0, ax1, ax2, ax3], p2[ax0, 0, 0, ax3]) T.writes(T_add[ax0, ax1, ax2, ax3]) T_add[ax0, ax1, ax2, ax3] = conv2d_winograd[ax0, ax1, ax2, ax3] + p2[ax0, 0, 0, ax3] for i0, i1, i2, i3 in T.grid(1, 56, 56, 64): with T.block("T_add_1"): ax0, ax1, ax2, ax3 = T.axis.remap("SSSS", [i0, i1, i2, i3]) T.reads(T_add[ax0, ax1, ax2, ax3], p3[ax0, ax1, ax2, ax3]) T.writes(T_add_1[ax0, ax1, ax2, ax3]) T_add_1[ax0, ax1, ax2, ax3] = T_add[ax0, ax1, ax2, ax3] + p3[ax0, ax1, ax2, ax3] for i0, i1, i2, i3 in T.grid(1, 56, 56, 64): with T.block("T_relu"): ax0, ax1, ax2, ax3 = T.axis.remap("SSSS", [i0, i1, i2, i3]) T.reads(T_add_1[ax0, ax1, ax2, ax3]) T.writes(T_relu[ax0, ax1, ax2, ax3]) T_relu[ax0, ax1, ax2, ax3] = T.max(T_add_1[ax0, ax1, ax2, ax3], T.float32(0)) @tvm.script.ir_module class Conv2dWinogradAddResidualRelu_scheduled: @T.prim_func def main(p0: T.Buffer[(1, 56, 56, 64), "float32"], p1: T.Buffer[(6, 6, 64, 64), "float32"], p2: T.Buffer[(1, 1, 1, 64), "float32"], p3: T.Buffer[(1, 56, 56, 64), "float32"], T_relu: T.Buffer[(1, 56, 56, 64), "float32"]) -> None: # function attr dict T.func_attr({"global_symbol": "main", "tir.noalias": True, "layout_free_buffers": [1]}) # body # with T.block("root") input_tile_local = T.alloc_buffer([6, 6, 196, 64], dtype="float32", scope="local") data_pack = T.alloc_buffer([6, 6, 196, 64], dtype="float32") bgemm = T.alloc_buffer([6, 6, 196, 64], dtype="float32") inverse = T.alloc_buffer([4, 4, 196, 64], dtype="float32") bgemm_local = T.alloc_buffer([6, 6, 196, 64], dtype="float32", scope="local") data_pack_shared = T.alloc_buffer([6, 6, 196, 64], dtype="float32", scope="shared") p1_shared = T.alloc_buffer([6, 6, 64, 64], dtype="float32", scope="shared") for i2_0_i3_0_i2_1_i3_1_fused_0 in T.thread_binding(98, thread="blockIdx.x", annotations={"pragma_auto_unroll_max_step":1024, "pragma_unroll_explicit":1}): for i2_0_i3_0_i2_1_i3_1_fused_1 in T.thread_binding(128, thread="threadIdx.x"): for ax0, ax1, ax2, ax3 in T.grid(6, 6, 1, 1): with T.block("input_tile"): eps, nu = T.axis.remap("SS", [ax0, ax1]) p = T.axis.spatial(196, (i2_0_i3_0_i2_1_i3_1_fused_0 * 128 + i2_0_i3_0_i2_1_i3_1_fused_1) // 896 * 14 + (i2_0_i3_0_i2_1_i3_1_fused_0 * 128 + i2_0_i3_0_i2_1_i3_1_fused_1) % 112 // 8 + ax2) ci = T.axis.spatial(64, (i2_0_i3_0_i2_1_i3_1_fused_0 * 128 + i2_0_i3_0_i2_1_i3_1_fused_1) % 896 // 112 * 8 + (i2_0_i3_0_i2_1_i3_1_fused_0 * 128 + i2_0_i3_0_i2_1_i3_1_fused_1) % 8 + ax3) T.reads(p0[p // 196, p % 196 // 14 * 4 + eps - 1, p % 14 * 4 + nu - 1, ci]) T.writes(input_tile_local[eps, nu, p, ci]) T.block_attr({"schedule_rule":"None"}) input_tile_local[eps, nu, p, ci] = T.if_then_else(1 <= p % 196 // 14 * 4 + eps and p % 196 // 14 * 4 + eps < 57 and 1 <= p % 14 * 4 + nu and p % 14 * 4 + nu < 57, p0[p // 196, p % 196 // 14 * 4 + eps - 1, p % 14 * 4 + nu - 1, ci], T.float32(0), dtype="float32") for i0 in T.unroll(6): for i1 in T.unroll(6): with T.block("data_pack_init"): eps, nu = T.axis.remap("SS", [i0, i1]) p = T.axis.spatial(196, (i2_0_i3_0_i2_1_i3_1_fused_0 * 128 + i2_0_i3_0_i2_1_i3_1_fused_1) // 896 * 14 + (i2_0_i3_0_i2_1_i3_1_fused_0 * 128 + i2_0_i3_0_i2_1_i3_1_fused_1) % 112 // 8) ci = T.axis.spatial(64, (i2_0_i3_0_i2_1_i3_1_fused_0 * 128 + i2_0_i3_0_i2_1_i3_1_fused_1) % 896 // 112 * 8 + (i2_0_i3_0_i2_1_i3_1_fused_0 * 128 + i2_0_i3_0_i2_1_i3_1_fused_1) % 8) T.reads() T.writes(data_pack[eps, nu, p, ci]) T.block_attr({"auto_scheduler_simplify_const_tensor_indices":["eps", "nu", "r_a", "r_b"], "schedule_rule":"meta_schedule.winograd_data_pack.cuda"}) data_pack[eps, nu, p, ci] = T.float32(0) for i4 in T.unroll(6): for i5 in T.unroll(6): with T.block("data_pack_update"): eps, nu = T.axis.remap("SS", [i0, i1]) p = T.axis.spatial(196, (i2_0_i3_0_i2_1_i3_1_fused_0 * 128 + i2_0_i3_0_i2_1_i3_1_fused_1) // 896 * 14 + (i2_0_i3_0_i2_1_i3_1_fused_0 * 128 + i2_0_i3_0_i2_1_i3_1_fused_1) % 112 // 8) ci = T.axis.spatial(64, (i2_0_i3_0_i2_1_i3_1_fused_0 * 128 + i2_0_i3_0_i2_1_i3_1_fused_1) % 896 // 112 * 8 + (i2_0_i3_0_i2_1_i3_1_fused_0 * 128 + i2_0_i3_0_i2_1_i3_1_fused_1) % 8) r_a, r_b = T.axis.remap("RR", [i4, i5]) T.reads(data_pack[eps, nu, p, ci], input_tile_local[r_a, r_b, p, ci]) T.writes(data_pack[eps, nu, p, ci]) T.block_attr({"auto_scheduler_simplify_const_tensor_indices":["eps", "nu", "r_a", "r_b"], "schedule_rule":"meta_schedule.winograd_data_pack.cuda"}) data_pack[eps, nu, p, ci] = data_pack[eps, nu, p, ci] + input_tile_local[r_a, r_b, p, ci] * T.Select(r_a % 6 == 5 and eps % 6 == 5, T.float32(1), T.Select(r_a % 6 == 5 and eps % 6 == 4, T.float32(0), T.Select(r_a % 6 == 5 and eps % 6 == 3, T.float32(0), T.Select(r_a % 6 == 5 and eps % 6 == 2, T.float32(0), T.Select(r_a % 6 == 5 and eps % 6 == 1, T.float32(0), T.Select(r_a % 6 == 5 and eps % 6 == 0, T.float32(0), T.Select(r_a % 6 == 4 and eps % 6 == 5, T.float32(1.5), T.Select(r_a % 6 == 4 and eps % 6 == 4, T.float32(1), T.Select(r_a % 6 == 4 and eps % 6 == 3, T.float32(1), T.Select(r_a % 6 == 4 and eps % 6 == 2, T.float32(1), T.Select(r_a % 6 == 4 and eps % 6 == 1, T.float32(1), T.Select(r_a % 6 == 4 and eps % 6 == 0, T.float32(1), T.Select(r_a % 6 == 3 and eps % 6 == 5, T.float32(-2), T.Select(r_a % 6 == 3 and eps % 6 == 4, T.float32(-0.5), T.Select(r_a % 6 == 3 and eps % 6 == 3, T.float32(2), T.Select(r_a % 6 == 3 and eps % 6 == 2, T.float32(2.5), T.Select(r_a % 6 == 3 and eps % 6 == 1, T.float32(0.5), T.Select(r_a % 6 == 3 and eps % 6 == 0, T.float32(1.5), T.Select(r_a % 6 == 2 and eps % 6 == 5, T.float32(-1.5), T.Select(r_a % 6 == 2 and eps % 6 == 4, T.float32(-1), T.Select(r_a % 6 == 2 and eps % 6 == 3, T.float32(-1), T.Select(r_a % 6 == 2 and eps % 6 == 2, T.float32(0.5), T.Select(r_a % 6 == 2 and eps % 6 == 1, T.float32(-2.5), T.Select(r_a % 6 == 2 and eps % 6 == 0, T.float32(-2), T.Select(r_a % 6 == 1 and eps % 6 == 5, T.float32(1), T.Select(r_a % 6 == 1 and eps % 6 == 4, T.float32(0.5), T.Select(r_a % 6 == 1 and eps % 6 == 3, T.float32(-2), T.Select(r_a % 6 == 1 and eps % 6 == 2, T.float32(-1), T.Select(r_a % 6 == 1 and eps % 6 == 1, T.float32(1), T.Select(r_a % 6 == 1 and eps % 6 == 0, T.float32(-1.5), T.Select(r_a % 6 == 0 and eps % 6 == 5, T.float32(0), T.Select(r_a % 6 == 0 and eps % 6 == 4, T.float32(0), T.Select(r_a % 6 == 0 and eps % 6 == 3, T.float32(0), T.Select(r_a % 6 == 0 and eps % 6 == 2, T.float32(0), T.Select(r_a % 6 == 0 and eps % 6 == 1, T.float32(0), T.Select(r_a % 6 == 0 and eps % 6 == 0, T.float32(1), T.float32(0))))))))))))))))))))))))))))))))))))) * T.Select(r_b % 6 == 5 and nu % 6 == 5, T.float32(1), T.Select(r_b % 6 == 5 and nu % 6 == 4, T.float32(0), T.Select(r_b % 6 == 5 and nu % 6 == 3, T.float32(0), T.Select(r_b % 6 == 5 and nu % 6 == 2, T.float32(0), T.Select(r_b % 6 == 5 and nu % 6 == 1, T.float32(0), T.Select(r_b % 6 == 5 and nu % 6 == 0, T.float32(0), T.Select(r_b % 6 == 4 and nu % 6 == 5, T.float32(1.5), T.Select(r_b % 6 == 4 and nu % 6 == 4, T.float32(1), T.Select(r_b % 6 == 4 and nu % 6 == 3, T.float32(1), T.Select(r_b % 6 == 4 and nu % 6 == 2, T.float32(1), T.Select(r_b % 6 == 4 and nu % 6 == 1, T.float32(1), T.Select(r_b % 6 == 4 and nu % 6 == 0, T.float32(1), T.Select(r_b % 6 == 3 and nu % 6 == 5, T.float32(-2), T.Select(r_b % 6 == 3 and nu % 6 == 4, T.float32(-0.5), T.Select(r_b % 6 == 3 and nu % 6 == 3, T.float32(2), T.Select(r_b % 6 == 3 and nu % 6 == 2, T.float32(2.5), T.Select(r_b % 6 == 3 and nu % 6 == 1, T.float32(0.5), T.Select(r_b % 6 == 3 and nu % 6 == 0, T.float32(1.5), T.Select(r_b % 6 == 2 and nu % 6 == 5, T.float32(-1.5), T.Select(r_b % 6 == 2 and nu % 6 == 4, T.float32(-1), T.Select(r_b % 6 == 2 and nu % 6 == 3, T.float32(-1), T.Select(r_b % 6 == 2 and nu % 6 == 2, T.float32(0.5), T.Select(r_b % 6 == 2 and nu % 6 == 1, T.float32(-2.5), T.Select(r_b % 6 == 2 and nu % 6 == 0, T.float32(-2), T.Select(r_b % 6 == 1 and nu % 6 == 5, T.float32(1), T.Select(r_b % 6 == 1 and nu % 6 == 4, T.float32(0.5), T.Select(r_b % 6 == 1 and nu % 6 == 3, T.float32(-2), T.Select(r_b % 6 == 1 and nu % 6 == 2, T.float32(-1), T.Select(r_b % 6 == 1 and nu % 6 == 1, T.float32(1), T.Select(r_b % 6 == 1 and nu % 6 == 0, T.float32(-1.5), T.Select(r_b % 6 == 0 and nu % 6 == 5, T.float32(0), T.Select(r_b % 6 == 0 and nu % 6 == 4, T.float32(0), T.Select(r_b % 6 == 0 and nu % 6 == 3, T.float32(0), T.Select(r_b % 6 == 0 and nu % 6 == 2, T.float32(0), T.Select(r_b % 6 == 0 and nu % 6 == 1, T.float32(0), T.Select(r_b % 6 == 0 and nu % 6 == 0, T.float32(1), T.float32(0))))))))))))))))))))))))))))))))))))) for i0_0_i1_0_i2_0_i3_0_fused in T.thread_binding(168, thread="blockIdx.x", annotations={"pragma_auto_unroll_max_step":1024, "pragma_unroll_explicit":1}): for i0_1_i1_1_i2_1_i3_1_fused in T.thread_binding(4, thread="vthread.x"): for i0_2_i1_2_i2_2_i3_2_fused in T.thread_binding(48, thread="threadIdx.x"): for i0_3_init, i1_3_init, i2_3_init, i3_3_init, i0_4_init, i1_4_init, i2_4_init, i3_4_init in T.grid(1, 1, 14, 1, 1, 1, 1, 1): with T.block("bgemm_init"): eps = T.axis.spatial(6, i0_4_init + i0_1_i1_1_i2_1_i3_1_fused // 2 * 3 + i0_2_i1_2_i2_2_i3_2_fused // 16 + i0_3_init) nu = T.axis.spatial(6, i1_4_init + i0_0_i1_0_i2_0_i3_0_fused // 28 + i1_3_init) p = T.axis.spatial(196, i0_0_i1_0_i2_0_i3_0_fused % 28 // 4 * 28 + i0_1_i1_1_i2_1_i3_1_fused % 2 * 14 + i2_3_init + i2_4_init) co = T.axis.spatial(64, i3_4_init + i0_0_i1_0_i2_0_i3_0_fused % 4 * 16 + i0_2_i1_2_i2_2_i3_2_fused % 16 + i3_3_init) T.reads() T.writes(bgemm_local[eps, nu, p, co]) T.block_attr({"layout_free_placeholders":[], "meta_schedule.thread_extent_high_inclusive":1024, "meta_schedule.thread_extent_low_inclusive":32, "meta_schedule.tiling_structure":"SSSRRSRS"}) bgemm_local[eps, nu, p, co] = T.float32(0) for i4_0 in T.serial(2): for ax0_ax1_ax2_ax3_fused_0 in T.serial(28): for ax0_ax1_ax2_ax3_fused_1 in T.thread_binding(48, thread="threadIdx.x"): for ax0_ax1_ax2_ax3_fused_2 in T.vectorized(4): with T.block("data_pack_shared"): v0 = T.axis.spatial(6, (ax0_ax1_ax2_ax3_fused_0 * 192 + ax0_ax1_ax2_ax3_fused_1 * 4 + ax0_ax1_ax2_ax3_fused_2) // 896) v1 = T.axis.spatial(6, i0_0_i1_0_i2_0_i3_0_fused // 28) v2 = T.axis.spatial(196, i0_0_i1_0_i2_0_i3_0_fused % 28 // 4 * 28 + (ax0_ax1_ax2_ax3_fused_0 * 192 + ax0_ax1_ax2_ax3_fused_1 * 4 + ax0_ax1_ax2_ax3_fused_2) % 896 // 32) v3 = T.axis.spatial(64, i4_0 * 32 + (ax0_ax1_ax2_ax3_fused_0 * 192 + ax0_ax1_ax2_ax3_fused_1 * 4 + ax0_ax1_ax2_ax3_fused_2) % 32) T.reads(data_pack[v0, v1, v2, v3]) T.writes(data_pack_shared[v0, v1, v2, v3]) data_pack_shared[v0, v1, v2, v3] = data_pack[v0, v1, v2, v3] for ax0_ax1_ax2_ax3_fused_0 in T.serial(16): for ax0_ax1_ax2_ax3_fused_1 in T.thread_binding(48, thread="threadIdx.x"): for ax0_ax1_ax2_ax3_fused_2 in T.vectorized(4): with T.block("p1_shared"): v0 = T.axis.spatial(6, (ax0_ax1_ax2_ax3_fused_0 * 192 + ax0_ax1_ax2_ax3_fused_1 * 4 + ax0_ax1_ax2_ax3_fused_2) // 512) v1 = T.axis.spatial(6, i0_0_i1_0_i2_0_i3_0_fused // 28) v2 = T.axis.spatial(64, i0_0_i1_0_i2_0_i3_0_fused % 4 * 16 + (ax0_ax1_ax2_ax3_fused_0 * 192 + ax0_ax1_ax2_ax3_fused_1 * 4 + ax0_ax1_ax2_ax3_fused_2) % 512 // 32) v3 = T.axis.spatial(64, i4_0 * 32 + (ax0_ax1_ax2_ax3_fused_0 * 192 + ax0_ax1_ax2_ax3_fused_1 * 4 + ax0_ax1_ax2_ax3_fused_2) % 32) T.reads(p1[v0, v1, v2, v3]) T.writes(p1_shared[v0, v1, v2, v3]) p1_shared[v0, v1, v2, v3] = p1[v0, v1, v2, v3] for i4_1, i0_3, i1_3, i2_3, i3_3, i4_2, i0_4, i1_4, i2_4, i3_4 in T.grid(2, 1, 1, 14, 1, 16, 1, 1, 1, 1): with T.block("bgemm_update"): eps = T.axis.spatial(6, i0_4 + i0_1_i1_1_i2_1_i3_1_fused // 2 * 3 + i0_2_i1_2_i2_2_i3_2_fused // 16 + i0_3) nu = T.axis.spatial(6, i1_4 + i0_0_i1_0_i2_0_i3_0_fused // 28 + i1_3) p = T.axis.spatial(196, i0_0_i1_0_i2_0_i3_0_fused % 28 // 4 * 28 + i0_1_i1_1_i2_1_i3_1_fused % 2 * 14 + i2_3 + i2_4) co = T.axis.spatial(64, i3_4 + i0_0_i1_0_i2_0_i3_0_fused % 4 * 16 + i0_2_i1_2_i2_2_i3_2_fused % 16 + i3_3) ci = T.axis.reduce(64, i4_0 * 32 + i4_1 * 16 + i4_2) T.reads(bgemm_local[eps, nu, p, co], data_pack_shared[eps, nu, p, ci], p1_shared[eps, nu, co, ci]) T.writes(bgemm_local[eps, nu, p, co]) T.block_attr({"layout_free_placeholders":[], "meta_schedule.thread_extent_high_inclusive":1024, "meta_schedule.thread_extent_low_inclusive":32, "meta_schedule.tiling_structure":"SSSRRSRS"}) bgemm_local[eps, nu, p, co] = bgemm_local[eps, nu, p, co] + data_pack_shared[eps, nu, p, ci] * p1_shared[eps, nu, co, ci] for ax0, ax1, ax2, ax3 in T.grid(1, 1, 14, 1): with T.block("bgemm_local"): v0 = T.axis.spatial(6, i0_1_i1_1_i2_1_i3_1_fused // 2 * 3 + i0_2_i1_2_i2_2_i3_2_fused // 16 + ax0) v1 = T.axis.spatial(6, i0_0_i1_0_i2_0_i3_0_fused // 28 + ax1) v2 = T.axis.spatial(196, i0_0_i1_0_i2_0_i3_0_fused % 28 // 4 * 28 + i0_1_i1_1_i2_1_i3_1_fused % 2 * 14 + ax2) v3 = T.axis.spatial(64, i0_0_i1_0_i2_0_i3_0_fused % 4 * 16 + i0_2_i1_2_i2_2_i3_2_fused % 16 + ax3) T.reads(bgemm_local[v0, v1, v2, v3]) T.writes(bgemm[v0, v1, v2, v3]) bgemm[v0, v1, v2, v3] = bgemm_local[v0, v1, v2, v3] for i2_0_i3_0_i2_1_i3_1_fused_0 in T.thread_binding(25, thread="blockIdx.x", annotations={"pragma_auto_unroll_max_step":1024, "pragma_unroll_explicit":1}): for i2_0_i3_0_i2_1_i3_1_fused_1 in T.thread_binding(512, thread="threadIdx.x"): for i0 in T.unroll(4): for i1 in T.unroll(4): with T.block("inverse_init"): T.where(i2_0_i3_0_i2_1_i3_1_fused_0 * 512 + i2_0_i3_0_i2_1_i3_1_fused_1 < 12544) vh, vw = T.axis.remap("SS", [i0, i1]) p = T.axis.spatial(196, (i2_0_i3_0_i2_1_i3_1_fused_0 * 512 + i2_0_i3_0_i2_1_i3_1_fused_1) // 448 * 7 + (i2_0_i3_0_i2_1_i3_1_fused_0 * 512 + i2_0_i3_0_i2_1_i3_1_fused_1) % 224 // 32) co = T.axis.spatial(64, (i2_0_i3_0_i2_1_i3_1_fused_0 * 512 + i2_0_i3_0_i2_1_i3_1_fused_1) % 448 // 224 * 32 + (i2_0_i3_0_i2_1_i3_1_fused_0 * 512 + i2_0_i3_0_i2_1_i3_1_fused_1) % 32) T.reads() T.writes(inverse[vh, vw, p, co]) T.block_attr({"auto_scheduler_simplify_const_tensor_indices":["vh", "vw", "r_a", "r_b"], "schedule_rule":"meta_schedule.winograd_inverse.cuda"}) inverse[vh, vw, p, co] = T.float32(0) for i4 in T.unroll(6): for i5 in T.unroll(6): with T.block("inverse_update"): T.where(i2_0_i3_0_i2_1_i3_1_fused_0 * 512 + i2_0_i3_0_i2_1_i3_1_fused_1 < 12544) vh, vw = T.axis.remap("SS", [i0, i1]) p = T.axis.spatial(196, (i2_0_i3_0_i2_1_i3_1_fused_0 * 512 + i2_0_i3_0_i2_1_i3_1_fused_1) // 448 * 7 + (i2_0_i3_0_i2_1_i3_1_fused_0 * 512 + i2_0_i3_0_i2_1_i3_1_fused_1) % 224 // 32) co = T.axis.spatial(64, (i2_0_i3_0_i2_1_i3_1_fused_0 * 512 + i2_0_i3_0_i2_1_i3_1_fused_1) % 448 // 224 * 32 + (i2_0_i3_0_i2_1_i3_1_fused_0 * 512 + i2_0_i3_0_i2_1_i3_1_fused_1) % 32) r_a, r_b = T.axis.remap("RR", [i4, i5]) T.reads(inverse[vh, vw, p, co], bgemm[r_a, r_b, p, co]) T.writes(inverse[vh, vw, p, co]) T.block_attr({"auto_scheduler_simplify_const_tensor_indices":["vh", "vw", "r_a", "r_b"], "schedule_rule":"meta_schedule.winograd_inverse.cuda"}) inverse[vh, vw, p, co] = inverse[vh, vw, p, co] + bgemm[r_a, r_b, p, co] * T.Select(r_a % 6 == 5 and vh % 4 == 3, T.float32(1), T.Select(r_a % 6 == 5 and vh % 4 == 2, T.float32(0), T.Select(r_a % 6 == 5 and vh % 4 == 1, T.float32(0), T.Select(r_a % 6 == 5 and vh % 4 == 0, T.float32(0), T.Select(r_a % 6 == 4 and vh % 4 == 3, T.float32(-8), T.Select(r_a % 6 == 4 and vh % 4 == 2, T.float32(4), T.Select(r_a % 6 == 4 and vh % 4 == 1, T.float32(-2), T.Select(r_a % 6 == 4 and vh % 4 == 0, T.float32(1), T.Select(r_a % 6 == 3 and vh % 4 == 3, T.float32(0.125), T.Select(r_a % 6 == 3 and vh % 4 == 2, T.float32(0.25), T.Select(r_a % 6 == 3 and vh % 4 == 1, T.float32(0.5), T.Select(r_a % 6 == 3 and vh % 4 == 0, T.float32(1), T.Select(r_a % 6 == 2 and vh % 4 == 3, T.float32(1), T.Select(r_a % 6 == 2 and vh % 4 == 2, T.float32(1), T.Select(r_a % 6 == 2 and vh % 4 == 1, T.float32(1), T.Select(r_a % 6 == 2 and vh % 4 == 0, T.float32(1), T.Select(r_a % 6 == 1 and vh % 4 == 3, T.float32(-1), T.Select(r_a % 6 == 1 and vh % 4 == 2, T.float32(1), T.Select(r_a % 6 == 1 and vh % 4 == 1, T.float32(-1), T.Select(r_a % 6 == 1 and vh % 4 == 0, T.float32(1), T.Select(r_a % 6 == 0 and vh % 4 == 3, T.float32(0), T.Select(r_a % 6 == 0 and vh % 4 == 2, T.float32(0), T.Select(r_a % 6 == 0 and vh % 4 == 1, T.float32(0), T.Select(r_a % 6 == 0 and vh % 4 == 0, T.float32(1), T.float32(0))))))))))))))))))))))))) * T.Select(r_b % 6 == 5 and vw % 4 == 3, T.float32(1), T.Select(r_b % 6 == 5 and vw % 4 == 2, T.float32(0), T.Select(r_b % 6 == 5 and vw % 4 == 1, T.float32(0), T.Select(r_b % 6 == 5 and vw % 4 == 0, T.float32(0), T.Select(r_b % 6 == 4 and vw % 4 == 3, T.float32(-8), T.Select(r_b % 6 == 4 and vw % 4 == 2, T.float32(4), T.Select(r_b % 6 == 4 and vw % 4 == 1, T.float32(-2), T.Select(r_b % 6 == 4 and vw % 4 == 0, T.float32(1), T.Select(r_b % 6 == 3 and vw % 4 == 3, T.float32(0.125), T.Select(r_b % 6 == 3 and vw % 4 == 2, T.float32(0.25), T.Select(r_b % 6 == 3 and vw % 4 == 1, T.float32(0.5), T.Select(r_b % 6 == 3 and vw % 4 == 0, T.float32(1), T.Select(r_b % 6 == 2 and vw % 4 == 3, T.float32(1), T.Select(r_b % 6 == 2 and vw % 4 == 2, T.float32(1), T.Select(r_b % 6 == 2 and vw % 4 == 1, T.float32(1), T.Select(r_b % 6 == 2 and vw % 4 == 0, T.float32(1), T.Select(r_b % 6 == 1 and vw % 4 == 3, T.float32(-1), T.Select(r_b % 6 == 1 and vw % 4 == 2, T.float32(1), T.Select(r_b % 6 == 1 and vw % 4 == 1, T.float32(-1), T.Select(r_b % 6 == 1 and vw % 4 == 0, T.float32(1), T.Select(r_b % 6 == 0 and vw % 4 == 3, T.float32(0), T.Select(r_b % 6 == 0 and vw % 4 == 2, T.float32(0), T.Select(r_b % 6 == 0 and vw % 4 == 1, T.float32(0), T.Select(r_b % 6 == 0 and vw % 4 == 0, T.float32(1), T.float32(0))))))))))))))))))))))))) for i0_i1_i2_i3_fused_0 in T.thread_binding(1568, thread="blockIdx.x", annotations={"pragma_auto_unroll_max_step":1024, "pragma_unroll_explicit":1}): for i0_i1_i2_i3_fused_1 in T.thread_binding(128, thread="threadIdx.x"): with T.block("conv2d_winograd"): n = T.axis.spatial(1, 0) h = T.axis.spatial(56, (i0_i1_i2_i3_fused_0 * 128 + i0_i1_i2_i3_fused_1) // 3584) w = T.axis.spatial(56, (i0_i1_i2_i3_fused_0 * 128 + i0_i1_i2_i3_fused_1) % 3584 // 64) co = T.axis.spatial(64, (i0_i1_i2_i3_fused_0 * 128 + i0_i1_i2_i3_fused_1) % 64) T.reads(inverse[h % 4, w % 4, n * 196 + h // 4 * 14 + w // 4, co], p2[n, 0, 0, co], p3[n, h, w, co]) T.writes(T_relu[n, h, w, co]) T_relu[n, h, w, co] = T.max(inverse[h % 4, w % 4, n * 196 + h // 4 * 14 + w // 4, co] + p2[n, 0, 0, co] + p3[n, h, w, co], T.float32(0)) @tvm.script.ir_module class Conv2dInt8_with_predicate: @T.prim_func def main(p0: T.Buffer[(16, 56, 56, 64), "int8"], p1: T.Buffer[(256, 1, 1, 64), "int8"], p2: T.Buffer[(1, 1, 1, 256), "int32"], p3: T.Buffer[(1, 1, 1, 256), "int32"], p4: T.Buffer[256, "int32"], p5: T.Buffer[256, "int32"], p6: T.Buffer[256, "int32"], p7: T.Buffer[(), "int32"], p8: T.Buffer[1, "int32"], compute: T.Buffer[(16, 56, 56, 256), "int32"]) -> None: # function attr dict T.func_attr({"tir.noalias": True, "global_symbol": "main"}) # body # with T.block("root") pad_temp = T.alloc_buffer([16, 56, 56, 64], dtype="int8") conv2d_nhwc = T.alloc_buffer([16, 56, 56, 256], dtype="int32") T_subtract = T.alloc_buffer([16, 56, 56, 256], dtype="int32") T_add = T.alloc_buffer([16, 56, 56, 256], dtype="int32") compute_1 = T.alloc_buffer([16, 56, 56, 256], dtype="int32") T_add_1 = T.alloc_buffer([16, 56, 56, 256], dtype="int32") compute_2 = T.alloc_buffer([16, 56, 56, 256], dtype="int32") T_subtract_1 = T.alloc_buffer([16, 56, 56, 256], dtype="int32") for i0, i1, i2, i3 in T.grid(16, 56, 56, 64): with T.block("pad_temp"): i0_1, i1_1, i2_1, i3_1 = T.axis.remap("SSSS", [i0, i1, i2, i3]) T.reads(p0[i0_1, i1_1, i2_1, i3_1]) T.writes(pad_temp[i0_1, i1_1, i2_1, i3_1]) pad_temp[i0_1, i1_1, i2_1, i3_1] = p0[i0_1, i1_1, i2_1, i3_1] for i0, i1, i2, i3, i4, i5, i6 in T.grid(16, 56, 56, 256, 1, 1, 64): with T.block("conv2d_nhwc"): nn, yy, xx, ff, ry, rx, rc = T.axis.remap("SSSSRRR", [i0, i1, i2, i3, i4, i5, i6]) T.reads(pad_temp[nn, yy + ry, xx + rx, rc], p1[ff, ry, rx, rc]) T.writes(conv2d_nhwc[nn, yy, xx, ff]) with T.init(): conv2d_nhwc[nn, yy, xx, ff] = 0 conv2d_nhwc[nn, yy, xx, ff] = conv2d_nhwc[nn, yy, xx, ff] + T.cast(pad_temp[nn, yy + ry, xx + rx, rc], "int32") * T.cast(p1[ff, ry, rx, rc], "int32") for i0, i1, i2, i3 in T.grid(16, 56, 56, 256): with T.block("T_subtract"): ax0, ax1, ax2, ax3 = T.axis.remap("SSSS", [i0, i1, i2, i3]) T.reads(conv2d_nhwc[ax0, ax1, ax2, ax3], p2[0, 0, 0, ax3]) T.writes(T_subtract[ax0, ax1, ax2, ax3]) T_subtract[ax0, ax1, ax2, ax3] = conv2d_nhwc[ax0, ax1, ax2, ax3] - p2[0, 0, 0, ax3] for i0, i1, i2, i3 in T.grid(16, 56, 56, 256): with T.block("T_add"): ax0, ax1, ax2, ax3 = T.axis.remap("SSSS", [i0, i1, i2, i3]) T.reads(T_subtract[ax0, ax1, ax2, ax3], p3[0, 0, 0, ax3]) T.writes(T_add[ax0, ax1, ax2, ax3]) T_add[ax0, ax1, ax2, ax3] = T_subtract[ax0, ax1, ax2, ax3] + p3[0, 0, 0, ax3] for i0, i1, i2, i3 in T.grid(16, 56, 56, 256): with T.block("compute"): i0_2, i1_2, i2_2, i3_2 = T.axis.remap("SSSS", [i0, i1, i2, i3]) T.reads(T_add[i0_2, i1_2, i2_2, i3_2], p4[i3_2], p5[i3_2], p6[i3_2]) T.writes(compute_1[i0_2, i1_2, i2_2, i3_2]) compute_1[i0_2, i1_2, i2_2, i3_2] = T.q_multiply_shift_per_axis(T_add[i0_2, i1_2, i2_2, i3_2], p4[i3_2], p5[i3_2], p6[i3_2], 31, False, True, dtype="int32") for i0_3, i1_3, i2_3, i3_3 in T.grid(16, 56, 56, 256): with T.block("T_add_1"): ax0, ax1, ax2, ax3 = T.axis.remap("SSSS", [i0_3, i1_3, i2_3, i3_3]) T.reads(p7[()], compute_1[ax0, ax1, ax2, ax3]) T.writes(T_add_1[ax0, ax1, ax2, ax3]) T_add_1[ax0, ax1, ax2, ax3] = p7[()] + compute_1[ax0, ax1, ax2, ax3] for i0_4, i1_4, i2_4, i3_4 in T.grid(16, 56, 56, 256): with T.block("compute_1"): i0_5, i1_5, i2_5, i3_5 = T.axis.remap("SSSS", [i0_4, i1_4, i2_4, i3_4]) T.reads(T_add_1[i0_5, i1_5, i2_5, i3_5]) T.writes(compute_2[i0_5, i1_5, i2_5, i3_5]) compute_2[i0_5, i1_5, i2_5, i3_5] = T.max(T.min(T_add_1[i0_5, i1_5, i2_5, i3_5], 255), 0) for i0_6, i1_6, i2_6, i3_6 in T.grid(16, 56, 56, 256): with T.block("T_subtract_1"): ax0, ax1, ax2, ax3 = T.axis.remap("SSSS", [i0_6, i1_6, i2_6, i3_6]) T.reads(compute_2[ax0, ax1, ax2, ax3], p8[0]) T.writes(T_subtract_1[ax0, ax1, ax2, ax3]) T_subtract_1[ax0, ax1, ax2, ax3] = compute_2[ax0, ax1, ax2, ax3] - p8[0] for i0_7, i1_7, i2_7, i3_7 in T.grid(16, 56, 56, 256): with T.block("compute_2"): i0_8, i1_8, i2_8, i3_8 = T.axis.remap("SSSS", [i0_7, i1_7, i2_7, i3_7]) T.reads(T_subtract_1[i0_8, i1_8, i2_8, i3_8]) T.writes(compute[i0_8, i1_8, i2_8, i3_8]) compute[i0_8, i1_8, i2_8, i3_8] = T.q_multiply_shift(T_subtract_1[i0_8, i1_8, i2_8, i3_8], 1963325822, 31, 1, dtype="int32") @tvm.script.ir_module class Conv2dInt8_with_predicate_target: @T.prim_func def main(p0: T.Buffer[(16, 56, 56, 64), "int8"], p1: T.Buffer[(256, 1, 1, 64), "int8"], p2: T.Buffer[(1, 1, 1, 256), "int32"], p3: T.Buffer[(1, 1, 1, 256), "int32"], p4: T.Buffer[256, "int32"], p5: T.Buffer[256, "int32"], p6: T.Buffer[256, "int32"], p7: T.Buffer[(), "int32"], p8: T.Buffer[1, "int32"], p9: T.Buffer[(16, 56, 56, 256), "int32"], compute: T.Buffer[(16, 56, 56, 256), "int32"]) -> None: # function attr dict T.func_attr({"global_symbol": "main", "tir.noalias": True}) # body # with T.block("root") pad_temp = T.alloc_buffer([16, 56, 56, 64], dtype="int8") conv2d_nhwc = T.alloc_buffer([16, 56, 56, 256], dtype="int32") T_subtract = T.alloc_buffer([16, 56, 56, 256], dtype="int32") T_add = T.alloc_buffer([16, 56, 56, 256], dtype="int32") compute_1 = T.alloc_buffer([16, 56, 56, 256], dtype="int32") T_add_1 = T.alloc_buffer([16, 56, 56, 256], dtype="int32") compute_2 = T.alloc_buffer([16, 56, 56, 256], dtype="int32") T_subtract_1 = T.alloc_buffer([16, 56, 56, 256], dtype="int32") compute_3 = T.alloc_buffer([16, 56, 56, 256], dtype="int32") compute_4 = T.alloc_buffer([16, 56, 56, 256], dtype="int32") T_add_2 = T.alloc_buffer([16, 56, 56, 256], dtype="int32") for i0, i1, i2, i3 in T.grid(16, 56, 56, 64): with T.block("pad_temp"): i0_1, i1_1, i2_1, i3_1 = T.axis.remap("SSSS", [i0, i1, i2, i3]) T.reads(p0[i0_1, i1_1, i2_1, i3_1]) T.writes(pad_temp[i0_1, i1_1, i2_1, i3_1]) pad_temp[i0_1, i1_1, i2_1, i3_1] = p0[i0_1, i1_1, i2_1, i3_1] for i0, i1, i2, i3, i4, i5, i6 in T.grid(16, 56, 56, 256, 1, 1, 64): with T.block("conv2d_nhwc"): nn, yy, xx, ff, ry, rx, rc = T.axis.remap("SSSSRRR", [i0, i1, i2, i3, i4, i5, i6]) T.reads(pad_temp[nn, yy + ry, xx + rx, rc], p1[ff, ry, rx, rc]) T.writes(conv2d_nhwc[nn, yy, xx, ff]) with T.init(): conv2d_nhwc[nn, yy, xx, ff] = 0 conv2d_nhwc[nn, yy, xx, ff] = conv2d_nhwc[nn, yy, xx, ff] + T.cast(pad_temp[nn, yy + ry, xx + rx, rc], "int32") * T.cast(p1[ff, ry, rx, rc], "int32") for i0, i1, i2, i3 in T.grid(16, 56, 56, 256): with T.block("T_subtract"): ax0, ax1, ax2, ax3 = T.axis.remap("SSSS", [i0, i1, i2, i3]) T.reads(conv2d_nhwc[ax0, ax1, ax2, ax3], p2[0, 0, 0, ax3]) T.writes(T_subtract[ax0, ax1, ax2, ax3]) T_subtract[ax0, ax1, ax2, ax3] = conv2d_nhwc[ax0, ax1, ax2, ax3] - p2[0, 0, 0, ax3] for i0, i1, i2, i3 in T.grid(16, 56, 56, 256): with T.block("T_add"): ax0, ax1, ax2, ax3 = T.axis.remap("SSSS", [i0, i1, i2, i3]) T.reads(T_subtract[ax0, ax1, ax2, ax3], p3[0, 0, 0, ax3]) T.writes(T_add[ax0, ax1, ax2, ax3]) T_add[ax0, ax1, ax2, ax3] = T_subtract[ax0, ax1, ax2, ax3] + p3[0, 0, 0, ax3] for i0, i1, i2, i3 in T.grid(16, 56, 56, 256): with T.block("compute"): i0_2, i1_2, i2_2, i3_2 = T.axis.remap("SSSS", [i0, i1, i2, i3]) T.reads(T_add[i0_2, i1_2, i2_2, i3_2], p4[i3_2], p5[i3_2], p6[i3_2]) T.writes(compute_1[i0_2, i1_2, i2_2, i3_2]) compute_1[i0_2, i1_2, i2_2, i3_2] = T.q_multiply_shift_per_axis(T_add[i0_2, i1_2, i2_2, i3_2], p4[i3_2], p5[i3_2], p6[i3_2], 31, False, True, dtype="int32") for i0_3, i1_3, i2_3, i3_3 in T.grid(16, 56, 56, 256): with T.block("T_add_1"): ax0, ax1, ax2, ax3 = T.axis.remap("SSSS", [i0_3, i1_3, i2_3, i3_3]) T.reads(p7[()], compute_1[ax0, ax1, ax2, ax3]) T.writes(T_add_1[ax0, ax1, ax2, ax3]) T_add_1[ax0, ax1, ax2, ax3] = p7[()] + compute_1[ax0, ax1, ax2, ax3] for i0_4, i1_4, i2_4, i3_4 in T.grid(16, 56, 56, 256): with T.block("compute_1"): i0_5, i1_5, i2_5, i3_5 = T.axis.remap("SSSS", [i0_4, i1_4, i2_4, i3_4]) T.reads(T_add_1[i0_5, i1_5, i2_5, i3_5]) T.writes(compute_2[i0_5, i1_5, i2_5, i3_5]) compute_2[i0_5, i1_5, i2_5, i3_5] = T.max(T.min(T_add_1[i0_5, i1_5, i2_5, i3_5], 255), 0) for i0_6, i1_6, i2_6, i3_6 in T.grid(16, 56, 56, 256): with T.block("T_subtract_1"): ax0, ax1, ax2, ax3 = T.axis.remap("SSSS", [i0_6, i1_6, i2_6, i3_6]) T.reads(compute_2[ax0, ax1, ax2, ax3], p8[0]) T.writes(T_subtract_1[ax0, ax1, ax2, ax3]) T_subtract_1[ax0, ax1, ax2, ax3] = compute_2[ax0, ax1, ax2, ax3] - p8[0] for i0_7, i1_7, i2_7, i3_7 in T.grid(16, 56, 56, 256): with T.block("compute_2"): i0_8, i1_8, i2_8, i3_8 = T.axis.remap("SSSS", [i0_7, i1_7, i2_7, i3_7]) T.reads(T_subtract_1[i0_8, i1_8, i2_8, i3_8]) T.writes(compute_3[i0_8, i1_8, i2_8, i3_8]) compute_3[i0_8, i1_8, i2_8, i3_8] = T.q_multiply_shift(T_subtract_1[i0_8, i1_8, i2_8, i3_8], 1457846997, 31, 0, dtype="int32") for i0_9, i1_9, i2_9, i3_9 in T.grid(16, 56, 56, 256): with T.block("compute_3"): i0_10, i1_10, i2_10, i3_10 = T.axis.remap("SSSS", [i0_9, i1_9, i2_9, i3_9]) T.reads(p9[i0_10, i1_10, i2_10, i3_10]) T.writes(compute_4[i0_10, i1_10, i2_10, i3_10]) compute_4[i0_10, i1_10, i2_10, i3_10] = T.q_multiply_shift(p9[i0_10, i1_10, i2_10, i3_10], 2101000910, 31, 0, dtype="int32") for i0_11, i1_11, i2_11, i3_11 in T.grid(16, 56, 56, 256): with T.block("T_add_2"): ax0, ax1, ax2, ax3 = T.axis.remap("SSSS", [i0_11, i1_11, i2_11, i3_11]) T.reads(compute_3[ax0, ax1, ax2, ax3], compute_4[ax0, ax1, ax2, ax3]) T.writes(T_add_2[ax0, ax1, ax2, ax3]) T_add_2[ax0, ax1, ax2, ax3] = compute_3[ax0, ax1, ax2, ax3] + compute_4[ax0, ax1, ax2, ax3] for i0_12, i1_12, i2_12, i3_12 in T.grid(16, 56, 56, 256): with T.block("compute_4"): i0_13, i1_13, i2_13, i3_13 = T.axis.remap("SSSS", [i0_12, i1_12, i2_12, i3_12]) T.reads(T_add_2[i0_13, i1_13, i2_13, i3_13]) T.writes(compute[i0_13, i1_13, i2_13, i3_13]) compute[i0_13, i1_13, i2_13, i3_13] = T.max(T.min(T_add_2[i0_13, i1_13, i2_13, i3_13], 255), 0) @tvm.script.ir_module class Conv2dInt8_with_predicate_scheduled: @T.prim_func def main(p0: T.Buffer[(16, 56, 56, 64), "int8"], p1: T.Buffer[(256, 1, 1, 64), "int8"], p2: T.Buffer[(1, 1, 1, 256), "int32"], p3: T.Buffer[(1, 1, 1, 256), "int32"], p4: T.Buffer[256, "int32"], p5: T.Buffer[256, "int32"], p6: T.Buffer[256, "int32"], p7: T.Buffer[(), "int32"], p8: T.Buffer[1, "int32"], p9: T.Buffer[(16, 56, 56, 256), "int32"], compute: T.Buffer[(16, 56, 56, 256), "int32"]) -> None: # function attr dict T.func_attr({"global_symbol": "main", "tir.noalias": True}) # body with T.block("root"): T.reads() T.writes() T.block_attr({"meta_schedule.unroll_explicit":1024}) conv2d_nhwc_reindex_shared = T.alloc_buffer([50176, 256], dtype="int32", scope="shared") conv2d_nhwc_reindex_shared_wmma_accumulator = T.alloc_buffer([50176, 256], dtype="int32", scope="wmma.accumulator") pad_temp_reindex_shared = T.alloc_buffer([50176, 64], dtype="int8", scope="shared") p1_reindex_shared = T.alloc_buffer([1, 1, 256, 64], dtype="int8", scope="shared") pad_temp_reindex_shared_wmma_matrix_a = T.alloc_buffer([50176, 64], dtype="int8", scope="wmma.matrix_a") p1_reindex_shared_wmma_matrix_b = T.alloc_buffer([1, 1, 256, 64], dtype="int8", scope="wmma.matrix_b") for ax2_0_0_ax3_0_0_fused in T.thread_binding(32, thread="blockIdx.y"): for ax2_0_1_ax3_0_1_fused in T.thread_binding(196, thread="blockIdx.x"): for ax2_0_2_ax3_0_2_fused in T.thread_binding(4, thread="threadIdx.y"): for ax0_0, ax1_0, ax4_0_0 in T.grid(1, 1, 2): for ax0_ax1_fused in T.serial(1024): with T.block("pad_temp_reindex_shared"): v0 = T.axis.spatial(50176, ax2_0_0_ax3_0_0_fused // 4 * 6272 + ax2_0_1_ax3_0_1_fused * 32 + ax0_ax1_fused // 32) v1 = T.axis.spatial(64, ax4_0_0 * 32 + ax0_ax1_fused % 32) T.reads(p0[v0 // 3136, v0 % 3136 // 56, v0 % 56, v1]) T.writes(pad_temp_reindex_shared[v0, v1]) T.block_attr({"buffer_dim_align":[[0, 0, 32, 16]], "meta_schedule.cooperative_fetch":4}) pad_temp_reindex_shared[v0, v1] = p0[v0 // 3136, v0 % 3136 // 56, v0 % 56, v1] for ax0_ax1_ax2_ax3_fused in T.serial(2048): with T.block("p1_reindex_shared"): v0 = T.axis.spatial(1, 0) v1 = T.axis.spatial(1, 0) v2 = T.axis.spatial(256, ax2_0_0_ax3_0_0_fused % 4 * 64 + ax0_ax1_ax2_ax3_fused // 32) v3 = T.axis.spatial(64, ax4_0_0 * 32 + ax0_ax1_ax2_ax3_fused % 32) T.reads(p1[v2, v0, v1, v3]) T.writes(p1_reindex_shared[v0, v1, v2, v3]) T.block_attr({"buffer_dim_align":[[0, 2, 32, 16]], "meta_schedule.cooperative_fetch":3}) p1_reindex_shared[v0, v1, v2, v3] = p1[v2, v0, v1, v3] for ax0_1, ax1_1, ax4_0_1 in T.grid(1, 1, 2): for ax0_0_1, ax1_0_1 in T.grid(1, 1): with T.block("pad_temp_reindex_shared_wmma.matrix_a_o"): v0_o = T.axis.spatial(3136, ax2_0_0_ax3_0_0_fused // 4 * 392 + ax2_0_1_ax3_0_1_fused * 2 + ax2_0_2_ax3_0_2_fused // 2) v1_o = T.axis.spatial(4, ax4_0_0 * 2 + ax4_0_1) T.reads(pad_temp_reindex_shared[v0_o * 16 : v0_o * 16 + 16, v1_o * 16 : v1_o * 16 + 16]) T.writes(pad_temp_reindex_shared_wmma_matrix_a[v0_o * 16 : v0_o * 16 + 16, v1_o * 16 : v1_o * 16 + 16]) T.block_attr({"meta_schedule.auto_tensorize":"wmma_load_16x16x16_s8_a"}) for ax0_1_1, ax1_1_1 in T.grid(16, 16): with T.block("pad_temp_reindex_shared_wmma.matrix_a"): v0_i, v1_i = T.axis.remap("SS", [ax0_1_1, ax1_1_1]) T.reads(pad_temp_reindex_shared[v0_o * 16 + v0_i, v1_o * 16 + v1_i]) T.writes(pad_temp_reindex_shared_wmma_matrix_a[v0_o * 16 + v0_i, v1_o * 16 + v1_i]) pad_temp_reindex_shared_wmma_matrix_a[v0_o * 16 + v0_i, v1_o * 16 + v1_i] = pad_temp_reindex_shared[v0_o * 16 + v0_i, v1_o * 16 + v1_i] for ax0, ax1, ax2_0, ax3_0 in T.grid(1, 1, 2, 1): with T.block("p1_reindex_shared_wmma.matrix_b_o"): v0 = T.axis.spatial(1, 0) v1 = T.axis.spatial(1, 0) v2_o = T.axis.spatial(16, ax2_0_0_ax3_0_0_fused % 4 * 4 + ax2_0_2_ax3_0_2_fused % 2 * 2 + ax2_0) v3_o = T.axis.spatial(4, ax4_0_0 * 2 + ax4_0_1) T.reads(p1_reindex_shared[v0, v1, v2_o * 16 : v2_o * 16 + 16, v3_o * 16 : v3_o * 16 + 16]) T.writes(p1_reindex_shared_wmma_matrix_b[v0, v1, v2_o * 16 : v2_o * 16 + 16, v3_o * 16 : v3_o * 16 + 16]) T.block_attr({"meta_schedule.auto_tensorize":"wmma_load_16x16x16_s8_b_trans"}) for ax2_1, ax3_1 in T.grid(16, 16): with T.block("p1_reindex_shared_wmma.matrix_b"): v2_i, v3_i = T.axis.remap("SS", [ax2_1, ax3_1]) T.reads(p1_reindex_shared[v0, v1, v2_o * 16 + v2_i, v3_o * 16 + v3_i]) T.writes(p1_reindex_shared_wmma_matrix_b[v0, v1, v2_o * 16 + v2_i, v3_o * 16 + v3_i]) p1_reindex_shared_wmma_matrix_b[v0, v1, v2_o * 16 + v2_i, v3_o * 16 + v3_i] = p1_reindex_shared[v0, v1, v2_o * 16 + v2_i, v3_o * 16 + v3_i] for ax2_0_3, ax3_0_3, ax0_2, ax1_2, ax4_0_2, ax2_0_4, ax3_0_4 in T.grid(1, 1, 1, 1, 1, 1, 2): with T.block("conv2d_nhwc_o"): v0 = T.axis.reduce(1, 0) v1 = T.axis.reduce(1, 0) v2_o = T.axis.spatial(3136, ax2_0_0_ax3_0_0_fused // 4 * 392 + ax2_0_1_ax3_0_1_fused * 2 + ax2_0_2_ax3_0_2_fused // 2 + ax2_0_3 + ax2_0_4) v3_o = T.axis.spatial(16, ax2_0_0_ax3_0_0_fused % 4 * 4 + ax2_0_2_ax3_0_2_fused % 2 * 2 + ax3_0_3 * 2 + ax3_0_4) v4_o = T.axis.reduce(4, ax4_0_0 * 2 + ax4_0_1 + ax4_0_2) T.reads(pad_temp_reindex_shared_wmma_matrix_a[v2_o * 16 : v2_o * 16 + 16, v4_o * 16 : v4_o * 16 + 16], p1_reindex_shared_wmma_matrix_b[v0, v1, v3_o * 16 : v3_o * 16 + 16, v4_o * 16 : v4_o * 16 + 16]) T.writes(conv2d_nhwc_reindex_shared_wmma_accumulator[v2_o * 16 : v2_o * 16 + 16, v3_o * 16 : v3_o * 16 + 16]) T.block_attr({"meta_schedule.auto_tensorize":"wmma_sync_16x16x16_s8s8s32_trans", "meta_schedule.auto_tensorize_init":"wmma_fill_16x16x16_s32", "meta_schedule.thread_extent_high_inclusive":1024, "meta_schedule.thread_extent_low_inclusive":32, "warp_execution":1}) with T.init(): for ax2_1, ax3_1 in T.grid(16, 16): with T.block("conv2d_nhwc_init"): v2_i_init, v3_i_init = T.axis.remap("SS", [ax2_1, ax3_1]) T.reads() T.writes(conv2d_nhwc_reindex_shared_wmma_accumulator[v2_o * 16 + v2_i_init, v3_o * 16 + v3_i_init]) conv2d_nhwc_reindex_shared_wmma_accumulator[v2_o * 16 + v2_i_init, v3_o * 16 + v3_i_init] = 0 for ax2_1, ax3_1, ax4_1 in T.grid(16, 16, 16): with T.block("conv2d_nhwc"): v2_i, v3_i, v4_i = T.axis.remap("SSR", [ax2_1, ax3_1, ax4_1]) T.reads(conv2d_nhwc_reindex_shared_wmma_accumulator[v2_o * 16 + v2_i, v3_o * 16 + v3_i], pad_temp_reindex_shared_wmma_matrix_a[v2_o * 16 + v2_i, v4_o * 16 + v4_i], p1_reindex_shared_wmma_matrix_b[v0, v1, v3_o * 16 + v3_i, v4_o * 16 + v4_i]) T.writes(conv2d_nhwc_reindex_shared_wmma_accumulator[v2_o * 16 + v2_i, v3_o * 16 + v3_i]) T.block_attr({"meta_schedule.tiling_structure":"SSSRRSRS"}) conv2d_nhwc_reindex_shared_wmma_accumulator[v2_o * 16 + v2_i, v3_o * 16 + v3_i] = conv2d_nhwc_reindex_shared_wmma_accumulator[v2_o * 16 + v2_i, v3_o * 16 + v3_i] + T.cast(pad_temp_reindex_shared_wmma_matrix_a[v2_o * 16 + v2_i, v4_o * 16 + v4_i], "int32") * T.cast(p1_reindex_shared_wmma_matrix_b[v0, v1, v3_o * 16 + v3_i, v4_o * 16 + v4_i], "int32") for ax0_0, ax1_0 in T.grid(1, 2): with T.block("conv2d_nhwc_reindex_shared_wmma.accumulator_o"): v0_o = T.axis.spatial(3136, ax2_0_0_ax3_0_0_fused // 4 * 392 + ax2_0_1_ax3_0_1_fused * 2 + ax2_0_2_ax3_0_2_fused // 2) v1_o = T.axis.spatial(16, ax2_0_0_ax3_0_0_fused % 4 * 4 + ax2_0_2_ax3_0_2_fused % 2 * 2 + ax1_0) T.reads(conv2d_nhwc_reindex_shared_wmma_accumulator[v0_o * 16 : v0_o * 16 + 16, v1_o * 16 : v1_o * 16 + 16]) T.writes(conv2d_nhwc_reindex_shared[v0_o * 16 : v0_o * 16 + 16, v1_o * 16 : v1_o * 16 + 16]) T.block_attr({"meta_schedule.auto_tensorize":"wmma_store_16x16x16_s32_shared"}) for ax0_1, ax1_1 in T.grid(16, 16): with T.block("conv2d_nhwc_reindex_shared_wmma.accumulator"): v0_i, v1_i = T.axis.remap("SS", [ax0_1, ax1_1]) T.reads(conv2d_nhwc_reindex_shared_wmma_accumulator[v0_o * 16 + v0_i, v1_o * 16 + v1_i]) T.writes(conv2d_nhwc_reindex_shared[v0_o * 16 + v0_i, v1_o * 16 + v1_i]) conv2d_nhwc_reindex_shared[v0_o * 16 + v0_i, v1_o * 16 + v1_i] = conv2d_nhwc_reindex_shared_wmma_accumulator[v0_o * 16 + v0_i, v1_o * 16 + v1_i] for ax0, ax1_0, ax1_1, ax1_2, ax1_3 in T.grid(32, 1, 4, 32, 2): with T.block("conv2d_nhwc_reindex_shared"): T.where(((ax1_0 * 4 + ax1_1) * 32 + ax1_2) * 2 + ax1_3 < 64) v0 = T.axis.spatial(50176, ax2_0_0_ax3_0_0_fused // 4 * 6272 + ax2_0_1_ax3_0_1_fused * 32 + ax0) v1 = T.axis.spatial(256, ax2_0_0_ax3_0_0_fused % 4 * 64 + (ax1_0 * 256 + ax1_1 * 64 + ax1_2 * 2 + ax1_3)) T.reads(p7[()], conv2d_nhwc_reindex_shared[v0, v1], p2[0, 0, 0, v1], p3[0, 0, 0, v1], p4[v1], p5[v1], p6[v1], p8[0], p9[v0 // 3136, v0 % 3136 // 56, v0 % 56, v1]) T.writes(compute[v0 // 3136, v0 % 3136 // 56, v0 % 56, v1]) compute[v0 // 3136, v0 % 3136 // 56, v0 % 56, v1] = T.max(T.min(T.q_multiply_shift(T.max(T.min(p7[()] + T.q_multiply_shift_per_axis(conv2d_nhwc_reindex_shared[v0, v1] - p2[0, 0, 0, v1] + p3[0, 0, 0, v1], p4[v1], p5[v1], p6[v1], 31, False, True, dtype="int32"), 255), 0) - p8[0], 1457846997, 31, 0, dtype="int32") + T.q_multiply_shift(p9[v0 // 3136, v0 % 3136 // 56, v0 % 56, v1], 2101000910, 31, 0, dtype="int32"), 255), 0) # fmt: on def verify(anchor_mod, anchor_trace_fun, target_mod, target, ref): anchor_sch = Schedule(anchor_mod) anchor_trace_fun(anchor_sch) anchor_trace = anchor_sch.trace sch = Schedule(target_mod) ms.trace_apply.schedule_using_anchor_trace(sch, anchor_trace, Target(target)) tvm.ir.assert_structural_equal(ref, sch.mod) def test_dense_add_cpu(): def apply_anchor_trace(sch: Schedule) -> None: b0 = sch.get_block(name="T_matmul_NT", func_name="main") b1 = sch.get_block(name="root", func_name="main") sch.annotate(block_or_loop=b0, ann_key="meta_schedule.tiling_structure", ann_val="SSRSRS") l2, l3, l4 = sch.get_loops(block=b0) v5, v6, v7, v8 = sch.sample_perfect_tile( loop=l2, n=4, max_innermost_factor=64, decision=[2, 8, 4, 2] ) l9, l10, l11, l12 = sch.split(loop=l2, factors=[v5, v6, v7, v8], preserve_unit_iters=True) v13, v14, v15, v16 = sch.sample_perfect_tile( loop=l3, n=4, max_innermost_factor=64, decision=[2, 1, 1, 64] ) l17, l18, l19, l20 = sch.split( loop=l3, factors=[v13, v14, v15, v16], preserve_unit_iters=True ) v21, v22 = sch.sample_perfect_tile(loop=l4, n=2, max_innermost_factor=64, decision=[128, 1]) l23, l24 = sch.split(loop=l4, factors=[v21, v22], preserve_unit_iters=True) sch.reorder(l9, l17, l10, l18, l23, l11, l19, l24, l12, l20) b25 = sch.cache_write(block=b0, write_buffer_index=0, storage_scope="global") sch.reverse_compute_at(block=b25, loop=l17, preserve_unit_loops=True, index=-1) sch.annotate(block_or_loop=b1, ann_key="meta_schedule.parallel", ann_val=160) sch.annotate(block_or_loop=b1, ann_key="meta_schedule.vectorize", ann_val=64) v26 = sch.sample_categorical( candidates=[0, 16, 64, 512], probs=[0.25, 0.25, 0.25, 0.25], decision=0 ) sch.annotate(block_or_loop=b1, ann_key="meta_schedule.unroll_explicit", ann_val=v26) sch.enter_postproc() b27 = sch.get_block(name="root", func_name="main") sch.unannotate(block_or_loop=b27, ann_key="meta_schedule.parallel") sch.unannotate(block_or_loop=b27, ann_key="meta_schedule.vectorize") sch.unannotate(block_or_loop=b27, ann_key="meta_schedule.unroll_explicit") b28, b29 = sch.get_child_blocks(b27) l30, l31, l32, l33, l34, l35, l36, l37, l38, l39 = sch.get_loops(block=b28) l40 = sch.fuse(l30, l31, preserve_unit_iters=True) sch.parallel(loop=l40) l41 = sch.fuse(l39, preserve_unit_iters=True) sch.vectorize(loop=l41) l42, l43, l44 = sch.get_loops(block=b29) l45 = sch.fuse(l42, preserve_unit_iters=True) sch.parallel(loop=l45) l46 = sch.fuse(l44, preserve_unit_iters=True) sch.vectorize(loop=l46) b47 = sch.get_block(name="T_matmul_NT", func_name="main") l48, l49, l50, l51, l52, l53, l54, l55, l56 = sch.get_loops(block=b47) b57 = sch.decompose_reduction(block=b47, loop=l51) b58 = sch.get_block(name="T_matmul_NT_update", func_name="main") b59 = sch.cache_read(block=b58, read_buffer_index=2, storage_scope="global") sch.transform_layout( block=b58, buffer=("read", 2), index_map=tvm.tir.IndexMap.from_func( lambda i0, i1: ( floordiv(i0, 64), i1, floormod(i0, 64), ), inverse_index_map=lambda i0, i1, i2: ( ((i0 * 64) + i2), i1, ), ), pad_value=None, ) sch.annotate(block_or_loop=b59, ann_key="meta_schedule.layout_rewrite_preproc", ann_val=1) verify(Dense, apply_anchor_trace, DenseAdd, "llvm", DenseAdd_scheduled_cpu) def test_dense_add_cpu_no_write_cache(): def apply_trace(sch): b0 = sch.get_block(name="T_matmul_NT", func_name="main") b1 = sch.get_block(name="root", func_name="main") sch.annotate(block_or_loop=b0, ann_key="meta_schedule.tiling_structure", ann_val="SSRSRS") l2, l3, l4 = sch.get_loops(block=b0) v5, v6, v7, v8 = sch.sample_perfect_tile( loop=l2, n=4, max_innermost_factor=64, decision=[4, 4, 4, 2] ) l9, l10, l11, l12 = sch.split(loop=l2, factors=[v5, v6, v7, v8], preserve_unit_iters=True) v13, v14, v15, v16 = sch.sample_perfect_tile( loop=l3, n=4, max_innermost_factor=64, decision=[1, 1, 4, 32] ) l17, l18, l19, l20 = sch.split( loop=l3, factors=[v13, v14, v15, v16], preserve_unit_iters=True ) v21, v22 = sch.sample_perfect_tile(loop=l4, n=2, max_innermost_factor=64, decision=[8, 16]) l23, l24 = sch.split(loop=l4, factors=[v21, v22], preserve_unit_iters=True) sch.reorder(l9, l17, l10, l18, l23, l11, l19, l24, l12, l20) sch.annotate(block_or_loop=b1, ann_key="meta_schedule.parallel", ann_val=160) sch.annotate(block_or_loop=b1, ann_key="meta_schedule.vectorize", ann_val=64) v25 = sch.sample_categorical( candidates=[0, 16, 64, 512], probs=[0.25, 0.25, 0.25, 0.25], decision=1 ) sch.annotate(block_or_loop=b1, ann_key="meta_schedule.unroll_explicit", ann_val=v25) sch.enter_postproc() b26 = sch.get_block(name="root", func_name="main") sch.unannotate(block_or_loop=b26, ann_key="meta_schedule.parallel") sch.unannotate(block_or_loop=b26, ann_key="meta_schedule.vectorize") sch.unannotate(block_or_loop=b26, ann_key="meta_schedule.unroll_explicit") (b27,) = sch.get_child_blocks(b26) l28, l29, l30, l31, l32, l33, l34, l35, l36, l37 = sch.get_loops(block=b27) l38 = sch.fuse(l28, l29, l30, l31, preserve_unit_iters=True) sch.parallel(loop=l38) l39 = sch.fuse(l37, preserve_unit_iters=True) sch.vectorize(loop=l39) sch.annotate(block_or_loop=l38, ann_key="pragma_auto_unroll_max_step", ann_val=16) sch.annotate(block_or_loop=l38, ann_key="pragma_unroll_explicit", ann_val=1) b40 = sch.get_block(name="T_matmul_NT", func_name="main") l41, l42, l43, l44, l45, l46, l47 = sch.get_loops(block=b40) b48 = sch.decompose_reduction(block=b40, loop=l42) b49 = sch.get_block(name="T_matmul_NT_update", func_name="main") b50 = sch.cache_read(block=b49, read_buffer_index=2, storage_scope="global") sch.transform_layout( block=b49, buffer=("read", 2), index_map=tvm.tir.IndexMap.from_func( lambda i0, i1: ( floordiv(i1, 16), floordiv(i0, 32), floormod(i1, 16), floormod(i0, 32), ), inverse_index_map=lambda i0, i1, i2, i3: ( ((i1 * 32) + i3), ((i0 * 16) + i2), ), ), pad_value=None, ) sch.annotate(block_or_loop=b50, ann_key="meta_schedule.layout_rewrite_preproc", ann_val=1) verify(Dense, apply_trace, DenseAdd, "llvm", DenseAdd_cpu_no_write_cache) def test_dense_add_gpu(): def apply_anchor_trace(sch: Schedule) -> None: b0 = sch.get_block(name="T_matmul_NT", func_name="main") b1 = sch.get_block(name="root", func_name="main") sch.annotate(block_or_loop=b0, ann_key="meta_schedule.tiling_structure", ann_val="SSSRRSRS") l2, l3, l4 = sch.get_loops(block=b0) v5, v6, v7, v8, v9 = sch.sample_perfect_tile( loop=l2, n=5, max_innermost_factor=64, decision=[8, 1, 16, 1, 1] ) l10, l11, l12, l13, l14 = sch.split( loop=l2, factors=[v5, v6, v7, v8, v9], preserve_unit_iters=True ) v15, v16, v17, v18, v19 = sch.sample_perfect_tile( loop=l3, n=5, max_innermost_factor=64, decision=[4, 1, 8, 4, 1] ) l20, l21, l22, l23, l24 = sch.split( loop=l3, factors=[v15, v16, v17, v18, v19], preserve_unit_iters=True ) v25, v26, v27 = sch.sample_perfect_tile( loop=l4, n=3, max_innermost_factor=64, decision=[32, 1, 4] ) l28, l29, l30 = sch.split(loop=l4, factors=[v25, v26, v27], preserve_unit_iters=True) sch.reorder(l10, l20, l11, l21, l12, l22, l28, l29, l13, l23, l30, l14, l24) l31 = sch.fuse(l10, l20, preserve_unit_iters=True) sch.bind(loop=l31, thread_axis="blockIdx.x") l32 = sch.fuse(l11, l21, preserve_unit_iters=True) sch.bind(loop=l32, thread_axis="vthread.x") l33 = sch.fuse(l12, l22, preserve_unit_iters=True) sch.bind(loop=l33, thread_axis="threadIdx.x") sch.annotate( block_or_loop=b0, ann_key="meta_schedule.thread_extent_low_inclusive", ann_val=16 ) sch.annotate( block_or_loop=b0, ann_key="meta_schedule.thread_extent_high_inclusive", ann_val=256 ) b34 = sch.cache_write(block=b0, write_buffer_index=0, storage_scope="local") sch.reverse_compute_at(block=b34, loop=l33, preserve_unit_loops=True, index=-1) b35 = sch.cache_read( block=b0, read_buffer_index=0, storage_scope="shared", consumer_blocks=[b0] ) sch.compute_at(block=b35, loop=l28, preserve_unit_loops=True, index=-1) l36, l37, l38, l39, l40, l41 = sch.get_loops(block=b35) l42 = sch.fuse(l40, l41, preserve_unit_iters=True) v43 = sch.sample_categorical( candidates=[1, 2, 3, 4], probs=[0.25, 0.25, 0.25, 0.25], decision=1 ) sch.annotate(block_or_loop=b35, ann_key="meta_schedule.cooperative_fetch", ann_val=v43) b44 = sch.cache_read( block=b0, read_buffer_index=1, storage_scope="shared", consumer_blocks=[b0] ) sch.compute_at(block=b44, loop=l28, preserve_unit_loops=True, index=-1) l45, l46, l47, l48, l49, l50 = sch.get_loops(block=b44) l51 = sch.fuse(l49, l50, preserve_unit_iters=True) v52 = sch.sample_categorical( candidates=[1, 2, 3, 4], probs=[0.25, 0.25, 0.25, 0.25], decision=3 ) sch.annotate(block_or_loop=b44, ann_key="meta_schedule.cooperative_fetch", ann_val=v52) v53 = sch.sample_categorical( candidates=[0, 16, 64, 512, 1024], probs=[ 0.20000000000000001, 0.20000000000000001, 0.20000000000000001, 0.20000000000000001, 0.20000000000000001, ], decision=2, ) sch.annotate(block_or_loop=b1, ann_key="meta_schedule.unroll_explicit", ann_val=v53) sch.enter_postproc() sch.unannotate(block_or_loop=b35, ann_key="meta_schedule.cooperative_fetch") l54, l55, l56, l57, l58 = sch.get_loops(block=b35) l59, l60, l61 = sch.split(loop=l58, factors=[None, 128, 2], preserve_unit_iters=True) sch.vectorize(loop=l61) sch.bind(loop=l60, thread_axis="threadIdx.x") sch.unannotate(block_or_loop=b44, ann_key="meta_schedule.cooperative_fetch") l62, l63, l64, l65, l66 = sch.get_loops(block=b44) l67, l68, l69 = sch.split(loop=l66, factors=[None, 128, 4], preserve_unit_iters=True) sch.vectorize(loop=l69) sch.bind(loop=l68, thread_axis="threadIdx.x") b70 = sch.get_block(name="root", func_name="main") sch.unannotate(block_or_loop=b70, ann_key="meta_schedule.unroll_explicit") b71, b72, b73, b74 = sch.get_child_blocks(b70) l75, l76, l77, l78, l79, l80, l81 = sch.get_loops(block=b71) sch.annotate(block_or_loop=l75, ann_key="pragma_auto_unroll_max_step", ann_val=64) sch.annotate(block_or_loop=l75, ann_key="pragma_unroll_explicit", ann_val=1) l82, l83, l84, l85, l86, l87, l88 = sch.get_loops(block=b72) sch.annotate(block_or_loop=l82, ann_key="pragma_auto_unroll_max_step", ann_val=64) sch.annotate(block_or_loop=l82, ann_key="pragma_unroll_explicit", ann_val=1) l89, l90, l91, l92, l93, l94, l95, l96, l97, l98 = sch.get_loops(block=b73) sch.annotate(block_or_loop=l89, ann_key="pragma_auto_unroll_max_step", ann_val=64) sch.annotate(block_or_loop=l89, ann_key="pragma_unroll_explicit", ann_val=1) l99, l100, l101, l102, l103 = sch.get_loops(block=b74) sch.annotate(block_or_loop=l99, ann_key="pragma_auto_unroll_max_step", ann_val=64) sch.annotate(block_or_loop=l99, ann_key="pragma_unroll_explicit", ann_val=1) b104 = sch.get_block(name="T_matmul_NT", func_name="main") l105, l106, l107, l108, l109, l110, l111, l112, l113, l114 = sch.get_loops(block=b104) b115 = sch.decompose_reduction(block=b104, loop=l108) verify(Dense, apply_anchor_trace, DenseAdd, "cuda", DenseAdd_scheduled_gpu) def test_conv2d_int8_tensorcore(): def apply_trace(sch): b0 = sch.get_block(name="pad_temp", func_name="main") b1 = sch.get_block(name="conv2d_nhwc", func_name="main") b2 = sch.get_block(name="T_subtract", func_name="main") b3 = sch.get_block(name="T_add", func_name="main") b4 = sch.get_block(name="T_cast", func_name="main") b5 = sch.get_block(name="T_multiply", func_name="main") b6 = sch.get_block(name="T_add_1", func_name="main") b7 = sch.get_block(name="T_right_shift", func_name="main") b8 = sch.get_block(name="T_cast_1", func_name="main") b9 = sch.get_block(name="T_add_2", func_name="main") b10 = sch.get_block(name="compute", func_name="main") b11 = sch.get_block(name="T_cast_2", func_name="main") b12 = sch.get_block(name="T_cast_3", func_name="main") b13 = sch.get_block(name="T_subtract_1", func_name="main") b14 = sch.get_block(name="compute_1", func_name="main") b15 = sch.get_block(name="root", func_name="main") sch.annotate(block_or_loop=b1, ann_key="meta_schedule.tiling_structure", ann_val="SSSRRSRS") b16 = sch.reindex(block=b1, buffer=("write", 0)) b17 = sch.reindex(block=b1, buffer=("read", 0)) b18 = sch.reindex(block=b1, buffer=("read", 1)) sch.transform_layout( block=b1, buffer=("read", 0), index_map=lambda nn, yy, xx, rc: ( (((nn * 3136) + (yy * 56)) + xx), rc, ), pad_value=None, ) sch.transform_layout( block=b1, buffer=("read", 1), index_map=lambda ff, ry, rx, rc: ( ry, rx, ff, rc, ), pad_value=None, ) sch.transform_layout( block=b1, buffer=("write", 0), index_map=lambda nn, yy, xx, ff: ( (((nn * 3136) + (yy * 56)) + xx), ff, ), pad_value=None, ) sch.transform_block_layout( block=b16, index_map=lambda nn, yy, xx, ff: ( (((nn * 3136) + (yy * 56)) + xx), ff, ), ) sch.transform_block_layout( block=b17, index_map=lambda nn, yy, xx, rc: ( (((nn * 3136) + (yy * 56)) + xx), rc, ), ) sch.transform_block_layout( block=b18, index_map=lambda ff, ry, rx, rc: ( ry, rx, ff, rc, ), ) sch.transform_block_layout( block=b1, index_map=lambda nn, yy, xx, ff, ry, rx, rc: ( ry, rx, (((nn * 3136) + (yy * 56)) + xx), ff, rc, ), ) l19, l20, l21, l22, l23 = sch.get_loops(block=b1) l24, l25 = sch.split(loop=l23, factors=[None, 16], preserve_unit_iters=True) l26, l27 = sch.split(loop=l22, factors=[None, 16], preserve_unit_iters=True) l28, l29 = sch.split(loop=l21, factors=[None, 16], preserve_unit_iters=True) l30, l31, l32, l33, l34, l35, l36, l37 = sch.get_loops(block=b1) sch.reorder(l34, l36, l29, l27, l25) b38 = sch.blockize(loop=l29) sch.annotate( block_or_loop=b38, ann_key="meta_schedule.auto_tensorize", ann_val="wmma_sync_16x16x16_s8s8s32_trans", ) sch.annotate( block_or_loop=b38, ann_key="meta_schedule.auto_tensorize_init", ann_val="wmma_fill_16x16x16_s32", ) sch.annotate(block_or_loop=b38, ann_key="warp_execution", ann_val=1) l39, l40, l41, l42, l43 = sch.get_loops(block=b38) v44, v45, v46 = sch.sample_perfect_tile( loop=l39, n=3, max_innermost_factor=4, decision=[1, 1, 1] ) l47, l48, l49 = sch.split(loop=l39, factors=[v44, v45, v46], preserve_unit_iters=True) v50, v51, v52 = sch.sample_perfect_tile( loop=l40, n=3, max_innermost_factor=4, decision=[1, 1, 1] ) l53, l54, l55 = sch.split(loop=l40, factors=[v50, v51, v52], preserve_unit_iters=True) v56, v57, v58, v59, v60 = sch.sample_perfect_tile( loop=l41, n=5, max_innermost_factor=4, decision=[392, 1, 8, 1, 1] ) l61, l62, l63, l64, l65 = sch.split( loop=l41, factors=[v56, v57, v58, v59, v60], preserve_unit_iters=True ) v66, v67, v68, v69, v70 = sch.sample_perfect_tile( loop=l42, n=5, max_innermost_factor=4, decision=[8, 1, 2, 1, 1] ) l71, l72, l73, l74, l75 = sch.split( loop=l42, factors=[v66, v67, v68, v69, v70], preserve_unit_iters=True ) v76, v77, v78 = sch.sample_perfect_tile( loop=l43, n=3, max_innermost_factor=4, decision=[2, 1, 2] ) l79, l80, l81 = sch.split(loop=l43, factors=[v76, v77, v78], preserve_unit_iters=True) sch.reorder( l61, l71, l62, l72, l63, l73, l47, l53, l79, l48, l54, l80, l64, l74, l49, l55, l81, l65, l75, ) l82 = sch.fuse(l61, l71, preserve_unit_iters=True) sch.bind(loop=l82, thread_axis="blockIdx.x") l83 = sch.fuse(l62, l72, preserve_unit_iters=True) sch.bind(loop=l83, thread_axis="vthread.x") l84 = sch.fuse(l63, l73, preserve_unit_iters=True) sch.bind(loop=l84, thread_axis="threadIdx.x") sch.annotate( block_or_loop=b38, ann_key="meta_schedule.thread_extent_low_inclusive", ann_val=32 ) sch.annotate( block_or_loop=b38, ann_key="meta_schedule.thread_extent_high_inclusive", ann_val=1024 ) b85 = sch.cache_write(block=b38, write_buffer_index=0, storage_scope="shared") sch.reverse_compute_at(block=b85, loop=l83, preserve_unit_loops=True, index=-1) b86 = sch.cache_write(block=b38, write_buffer_index=0, storage_scope="wmma.accumulator") sch.reverse_compute_at(block=b86, loop=l84, preserve_unit_loops=True, index=-1) v87 = sch.sample_categorical( candidates=[1, 2, 3, 4, 8, 16], probs=[ 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, ], decision=0, ) sch.annotate(block_or_loop=b85, ann_key="meta_schedule.cooperative_fetch", ann_val=v87) sch.reverse_compute_inline(block=b16) l88, l89, l90, l91, l92 = sch.get_loops(block=b86) l93, l94 = sch.split(loop=l92, factors=[None, 16], preserve_unit_iters=True) l95, l96 = sch.split(loop=l91, factors=[None, 16], preserve_unit_iters=True) l97, l98, l99, l100, l101, l102, l103 = sch.get_loops(block=b86) sch.reorder(l102, l96, l94) b104 = sch.blockize(loop=l96) sch.annotate( block_or_loop=b104, ann_key="meta_schedule.auto_tensorize", ann_val="wmma_store_16x16x16_s32_shared", ) b105 = sch.cache_read( block=b38, read_buffer_index=0, storage_scope="shared", consumer_blocks=[b38] ) sch.compute_at(block=b105, loop=l79, preserve_unit_loops=True, index=-1) l106, l107, l108, l109, l110, l111, l112, l113 = sch.get_loops(block=b105) l114 = sch.fuse(l112, l113, preserve_unit_iters=True) v115 = sch.sample_categorical( candidates=[1, 2, 3, 4, 8, 16], probs=[ 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, ], decision=5, ) sch.annotate(block_or_loop=b105, ann_key="meta_schedule.cooperative_fetch", ann_val=v115) b116 = sch.cache_read( block=b38, read_buffer_index=1, storage_scope="shared", consumer_blocks=[b38] ) sch.compute_at(block=b116, loop=l79, preserve_unit_loops=True, index=-1) l117, l118, l119, l120, l121, l122, l123, l124, l125, l126 = sch.get_loops(block=b116) l127 = sch.fuse(l123, l124, l125, l126, preserve_unit_iters=True) v128 = sch.sample_categorical( candidates=[1, 2, 3, 4, 8, 16], probs=[ 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, ], decision=4, ) sch.annotate(block_or_loop=b116, ann_key="meta_schedule.cooperative_fetch", ann_val=v128) b129 = sch.cache_read(block=b38, read_buffer_index=0, storage_scope="wmma.matrix_a") sch.compute_at(block=b129, loop=l80, preserve_unit_loops=True, index=-1) l130, l131, l132, l133, l134, l135, l136, l137, l138, l139, l140 = sch.get_loops(block=b129) l141, l142 = sch.split(loop=l140, factors=[None, 16], preserve_unit_iters=True) l143, l144 = sch.split(loop=l139, factors=[None, 16], preserve_unit_iters=True) ( l145, l146, l147, l148, l149, l150, l151, l152, l153, l154, l155, l156, l157, ) = sch.get_loops(block=b129) sch.reorder(l156, l144, l142) b158 = sch.blockize(loop=l144) sch.annotate( block_or_loop=b158, ann_key="meta_schedule.auto_tensorize", ann_val="wmma_load_16x16x16_s8_a", ) b159 = sch.cache_read(block=b38, read_buffer_index=1, storage_scope="wmma.matrix_b") sch.compute_at(block=b159, loop=l80, preserve_unit_loops=True, index=-1) ( l160, l161, l162, l163, l164, l165, l166, l167, l168, l169, l170, l171, l172, ) = sch.get_loops(block=b159) l173, l174 = sch.split(loop=l172, factors=[None, 16], preserve_unit_iters=True) l175, l176 = sch.split(loop=l171, factors=[None, 16], preserve_unit_iters=True) ( l177, l178, l179, l180, l181, l182, l183, l184, l185, l186, l187, l188, l189, l190, l191, ) = sch.get_loops(block=b159) sch.reorder(l190, l176, l174) b192 = sch.blockize(loop=l176) sch.annotate( block_or_loop=b192, ann_key="meta_schedule.auto_tensorize", ann_val="wmma_load_16x16x16_s8_b_trans", ) sch.compute_inline(block=b17) sch.compute_inline(block=b18) sch.storage_align(block=b105, buffer_index=0, axis=-2, factor=32, offset=16) sch.storage_align(block=b116, buffer_index=0, axis=-2, factor=32, offset=16) sch.reverse_compute_inline(block=b14) sch.reverse_compute_inline(block=b13) sch.reverse_compute_inline(block=b12) sch.reverse_compute_inline(block=b11) sch.reverse_compute_inline(block=b10) sch.reverse_compute_inline(block=b9) sch.reverse_compute_inline(block=b8) sch.reverse_compute_inline(block=b7) sch.reverse_compute_inline(block=b6) sch.reverse_compute_inline(block=b5) sch.reverse_compute_inline(block=b4) sch.reverse_compute_inline(block=b3) sch.reverse_compute_inline(block=b2) sch.compute_inline(block=b0) v193 = sch.sample_categorical( candidates=[0, 16, 64, 512, 1024], probs=[ 0.20000000000000001, 0.20000000000000001, 0.20000000000000001, 0.20000000000000001, 0.20000000000000001, ], decision=3, ) sch.annotate(block_or_loop=b15, ann_key="meta_schedule.unroll_explicit", ann_val=v193) sch.enter_postproc() sch.unannotate(block_or_loop=b85, ann_key="meta_schedule.cooperative_fetch") l194, l195, l196, l197 = sch.get_loops(block=b85) l198, l199 = sch.split(loop=l197, factors=[None, 16], preserve_unit_iters=True) sch.bind(loop=l199, thread_axis="threadIdx.x") sch.unannotate(block_or_loop=b105, ann_key="meta_schedule.cooperative_fetch") l200, l201, l202, l203, l204, l205, l206 = sch.get_loops(block=b105) l207, l208, l209 = sch.split(loop=l206, factors=[None, 16, 16], preserve_unit_iters=True) sch.vectorize(loop=l209) sch.bind(loop=l208, thread_axis="threadIdx.x") sch.unannotate(block_or_loop=b116, ann_key="meta_schedule.cooperative_fetch") l210, l211, l212, l213, l214, l215, l216 = sch.get_loops(block=b116) l217, l218, l219 = sch.split(loop=l216, factors=[None, 16, 8], preserve_unit_iters=True) sch.vectorize(loop=l219) sch.bind(loop=l218, thread_axis="threadIdx.x") b220 = sch.get_block(name="root", func_name="main") sch.unannotate(block_or_loop=b220, ann_key="meta_schedule.unroll_explicit") b221, b222, b223, b224, b225, b226, b227 = sch.get_child_blocks(b220) l228, l229, l230, l231, l232, l233, l234, l235, l236 = sch.get_loops(block=b221) sch.annotate(block_or_loop=l228, ann_key="pragma_auto_unroll_max_step", ann_val=512) sch.annotate(block_or_loop=l228, ann_key="pragma_unroll_explicit", ann_val=1) l237, l238, l239, l240, l241, l242, l243, l244, l245 = sch.get_loops(block=b222) sch.annotate(block_or_loop=l237, ann_key="pragma_auto_unroll_max_step", ann_val=512) sch.annotate(block_or_loop=l237, ann_key="pragma_unroll_explicit", ann_val=1) l246, l247, l248, l249, l250, l251, l252, l253, l254, l255, l256 = sch.get_loops(block=b223) sch.annotate(block_or_loop=l246, ann_key="pragma_auto_unroll_max_step", ann_val=512) sch.annotate(block_or_loop=l246, ann_key="pragma_unroll_explicit", ann_val=1) ( l257, l258, l259, l260, l261, l262, l263, l264, l265, l266, l267, l268, l269, ) = sch.get_loops(block=b224) sch.annotate(block_or_loop=l257, ann_key="pragma_auto_unroll_max_step", ann_val=512) sch.annotate(block_or_loop=l257, ann_key="pragma_unroll_explicit", ann_val=1) ( l270, l271, l272, l273, l274, l275, l276, l277, l278, l279, l280, l281, l282, l283, l284, l285, ) = sch.get_loops(block=b225) sch.annotate(block_or_loop=l270, ann_key="pragma_auto_unroll_max_step", ann_val=512) sch.annotate(block_or_loop=l270, ann_key="pragma_unroll_explicit", ann_val=1) l286, l287, l288, l289, l290 = sch.get_loops(block=b226) sch.annotate(block_or_loop=l286, ann_key="pragma_auto_unroll_max_step", ann_val=512) sch.annotate(block_or_loop=l286, ann_key="pragma_unroll_explicit", ann_val=1) l291, l292, l293, l294, l295 = sch.get_loops(block=b227) sch.annotate(block_or_loop=l291, ann_key="pragma_auto_unroll_max_step", ann_val=512) sch.annotate(block_or_loop=l291, ann_key="pragma_unroll_explicit", ann_val=1) b296 = sch.get_block(name="conv2d_nhwc_o", func_name="main") ( l297, l298, l299, l300, l301, l302, l303, l304, l305, l306, l307, l308, l309, l310, l311, l312, ) = sch.get_loops(block=b296) b313 = sch.decompose_reduction(block=b296, loop=l302) sch.unannotate(block_or_loop=b313, ann_key="meta_schedule.auto_tensorize") sch.annotate( block_or_loop=b313, ann_key="meta_schedule.auto_tensorize", ann_val="wmma_fill_16x16x16_s32", ) sch.unannotate(block_or_loop=b296, ann_key="meta_schedule.auto_tensorize_init") sch.unannotate(block_or_loop=b313, ann_key="meta_schedule.auto_tensorize_init") b314 = sch.get_block(name="conv2d_nhwc_o_init", func_name="main") sch.unannotate(block_or_loop=b314, ann_key="meta_schedule.auto_tensorize") sch.tensorize(block_or_loop=b314, tensor_intrin="wmma_fill_16x16x16_s32") b315 = sch.get_block(name="pad_temp_reindex_shared_wmma.matrix_a_o", func_name="main") sch.unannotate(block_or_loop=b315, ann_key="meta_schedule.auto_tensorize") sch.tensorize(block_or_loop=b315, tensor_intrin="wmma_load_16x16x16_s8_a") b316 = sch.get_block(name="p1_reindex_shared_wmma.matrix_b_o", func_name="main") sch.unannotate(block_or_loop=b316, ann_key="meta_schedule.auto_tensorize") sch.tensorize(block_or_loop=b316, tensor_intrin="wmma_load_16x16x16_s8_b_trans") b317 = sch.get_block(name="conv2d_nhwc_o_update", func_name="main") sch.unannotate(block_or_loop=b317, ann_key="meta_schedule.auto_tensorize") sch.tensorize(block_or_loop=b317, tensor_intrin="wmma_sync_16x16x16_s8s8s32_trans") b318 = sch.get_block(name="conv2d_nhwc_reindex_shared_wmma.accumulator_o", func_name="main") sch.unannotate(block_or_loop=b318, ann_key="meta_schedule.auto_tensorize") sch.tensorize(block_or_loop=b318, tensor_intrin="wmma_store_16x16x16_s32_shared") verify(Conv2dInt8, apply_trace, Conv2dInt8_target, "cuda", Conv2dInt8_tensorcore_scheduled) def test_conv2d_int8_vnni(): def apply_trace(sch): b0 = sch.get_block(name="compile_engine_const", func_name="main") b1 = sch.get_block(name="conv2d_NCHWc_int8", func_name="main") b2 = sch.get_block(name="T_add", func_name="main") b3 = sch.get_block(name="T_cast", func_name="main") b4 = sch.get_block(name="T_multiply", func_name="main") b5 = sch.get_block(name="compile_engine_const_1", func_name="main") b6 = sch.get_block(name="T_add_1", func_name="main") b7 = sch.get_block(name="T_floor", func_name="main") b8 = sch.get_block(name="T_cast_1", func_name="main") b9 = sch.get_block(name="compute", func_name="main") b10 = sch.get_block(name="T_cast_2", func_name="main") b11 = sch.get_block(name="T_cast_3", func_name="main") b12 = sch.get_block(name="T_subtract", func_name="main") b13 = sch.get_block(name="T_multiply_1", func_name="main") b14 = sch.get_block(name="compile_engine_const_2", func_name="main") b15 = sch.get_block(name="T_add_2", func_name="main") b16 = sch.get_block(name="T_floor_1", func_name="main") b17 = sch.get_block(name="T_cast_4", func_name="main") b18 = sch.get_block(name="T_add_3", func_name="main") b19 = sch.get_block(name="compute_1", func_name="main") b20 = sch.get_block(name="T_cast_5", func_name="main") b21 = sch.get_block(name="root", func_name="main") sch.compute_inline(block=b20) sch.compute_inline(block=b19) sch.compute_inline(block=b18) sch.compute_inline(block=b17) sch.compute_inline(block=b16) sch.compute_inline(block=b15) sch.compute_inline(block=b14) sch.compute_inline(block=b13) sch.compute_inline(block=b12) sch.compute_inline(block=b11) sch.compute_inline(block=b10) sch.compute_inline(block=b9) sch.compute_inline(block=b8) sch.compute_inline(block=b7) sch.compute_inline(block=b6) sch.compute_inline(block=b5) sch.compute_inline(block=b4) sch.compute_inline(block=b3) sch.compute_inline(block=b2) sch.compute_inline(block=b0) sch.annotate(block_or_loop=b1, ann_key="meta_schedule.tiling_structure", ann_val="SSRSRS") l22, l23, l24, l25, l26, l27, l28, l29, l30, l31 = sch.get_loops(block=b1) l32, l33 = sch.split(loop=l31, factors=[None, 4], preserve_unit_iters=True) l34, l35 = sch.split(loop=l26, factors=[None, 16], preserve_unit_iters=True) l36, l37, l38, l39, l40, l41, l42, l43, l44, l45, l46, l47 = sch.get_loops(block=b1) sch.reorder(l42, l43, l44, l45, l46, l35, l33) b48 = sch.blockize(loop=l35) sch.annotate( block_or_loop=b48, ann_key="meta_schedule.auto_tensorize", ann_val="dot_16x4_vnni" ) l49, l50, l51, l52, l53, l54, l55, l56, l57, l58 = sch.get_loops(block=b48) v59, v60, v61, v62 = sch.sample_perfect_tile( loop=l49, n=4, max_innermost_factor=64, decision=[1, 1, 1, 1] ) l63, l64, l65, l66 = sch.split( loop=l49, factors=[v59, v60, v61, v62], preserve_unit_iters=True ) v67, v68, v69, v70 = sch.sample_perfect_tile( loop=l50, n=4, max_innermost_factor=64, decision=[4, 32, 1, 1] ) l71, l72, l73, l74 = sch.split( loop=l50, factors=[v67, v68, v69, v70], preserve_unit_iters=True ) v75, v76, v77, v78 = sch.sample_perfect_tile( loop=l51, n=4, max_innermost_factor=64, decision=[1, 7, 1, 1] ) l79, l80, l81, l82 = sch.split( loop=l51, factors=[v75, v76, v77, v78], preserve_unit_iters=True ) v83, v84, v85, v86 = sch.sample_perfect_tile( loop=l52, n=4, max_innermost_factor=64, decision=[1, 1, 1, 7] ) l87, l88, l89, l90 = sch.split( loop=l52, factors=[v83, v84, v85, v86], preserve_unit_iters=True ) v91, v92, v93, v94 = sch.sample_perfect_tile( loop=l53, n=4, max_innermost_factor=64, decision=[1, 1, 1, 1] ) l95, l96, l97, l98 = sch.split( loop=l53, factors=[v91, v92, v93, v94], preserve_unit_iters=True ) v99, v100 = sch.sample_perfect_tile(loop=l54, n=2, max_innermost_factor=64, decision=[1, 1]) l101, l102 = sch.split(loop=l54, factors=[v99, v100], preserve_unit_iters=True) v103, v104 = sch.sample_perfect_tile( loop=l55, n=2, max_innermost_factor=64, decision=[1, 1] ) l105, l106 = sch.split(loop=l55, factors=[v103, v104], preserve_unit_iters=True) v107, v108 = sch.sample_perfect_tile( loop=l56, n=2, max_innermost_factor=64, decision=[4, 8] ) l109, l110 = sch.split(loop=l56, factors=[v107, v108], preserve_unit_iters=True) v111, v112 = sch.sample_perfect_tile( loop=l57, n=2, max_innermost_factor=64, decision=[4, 1] ) l113, l114 = sch.split(loop=l57, factors=[v111, v112], preserve_unit_iters=True) v115, v116 = sch.sample_perfect_tile( loop=l58, n=2, max_innermost_factor=64, decision=[1, 1] ) l117, l118 = sch.split(loop=l58, factors=[v115, v116], preserve_unit_iters=True) sch.reorder( l63, l71, l79, l87, l95, l64, l72, l80, l88, l96, l101, l105, l109, l113, l117, l65, l73, l81, l89, l97, l102, l106, l110, l114, l118, l66, l74, l82, l90, l98, ) (b119,) = sch.get_consumers(block=b48) sch.reverse_compute_at(block=b119, loop=l96, preserve_unit_loops=True, index=-1) sch.annotate(block_or_loop=b21, ann_key="meta_schedule.parallel", ann_val=96) sch.annotate(block_or_loop=b21, ann_key="meta_schedule.vectorize", ann_val=64) v120 = sch.sample_categorical( candidates=[0, 16, 64, 512], probs=[0.25, 0.25, 0.25, 0.25], decision=2 ) sch.annotate(block_or_loop=b21, ann_key="meta_schedule.unroll_explicit", ann_val=v120) sch.enter_postproc() b121 = sch.get_block(name="root", func_name="main") sch.unannotate(block_or_loop=b121, ann_key="meta_schedule.parallel") sch.unannotate(block_or_loop=b121, ann_key="meta_schedule.vectorize") sch.unannotate(block_or_loop=b121, ann_key="meta_schedule.unroll_explicit") b122, b123 = sch.get_child_blocks(b121) ( l124, l125, l126, l127, l128, l129, l130, l131, l132, l133, l134, l135, l136, l137, l138, l139, l140, l141, l142, l143, l144, l145, l146, l147, l148, l149, l150, l151, l152, l153, ) = sch.get_loops(block=b122) l154 = sch.fuse(l124, l125, l126, l127, l128, l129, l130, preserve_unit_iters=True) sch.parallel(loop=l154) sch.annotate(block_or_loop=l154, ann_key="pragma_auto_unroll_max_step", ann_val=64) sch.annotate(block_or_loop=l154, ann_key="pragma_unroll_explicit", ann_val=1) l155, l156, l157, l158, l159, l160, l161, l162, l163 = sch.get_loops(block=b123) l164 = sch.fuse(l163, preserve_unit_iters=True) sch.vectorize(loop=l164) sch.annotate(block_or_loop=l155, ann_key="pragma_auto_unroll_max_step", ann_val=64) sch.annotate(block_or_loop=l155, ann_key="pragma_unroll_explicit", ann_val=1) b165 = sch.get_block(name="conv2d_NCHWc_int8_o", func_name="main") ( l166, l167, l168, l169, l170, l171, l172, l173, l174, l175, l176, l177, l178, l179, l180, l181, l182, l183, l184, l185, l186, l187, l188, l189, ) = sch.get_loops(block=b165) b190 = sch.decompose_reduction(block=b165, loop=l172) sch.unannotate(block_or_loop=b190, ann_key="meta_schedule.auto_tensorize") sch.annotate(block_or_loop=b190, ann_key="meta_schedule.auto_tensorize", ann_val="") b191 = sch.get_block(name="conv2d_NCHWc_int8_o_init", func_name="main") sch.unannotate(block_or_loop=b191, ann_key="meta_schedule.auto_tensorize") (b192,) = sch.get_child_blocks(b191) (l193,) = sch.get_loops(block=b192) sch.vectorize(loop=l193) b194 = sch.get_block(name="conv2d_NCHWc_int8_o_update", func_name="main") sch.unannotate(block_or_loop=b194, ann_key="meta_schedule.auto_tensorize") sch.tensorize(block_or_loop=b194, tensor_intrin="dot_16x4_vnni") vnni_id = llvm_lookup_intrinsic_id("llvm.x86.avx512.vpdpbusd.512") verify( Conv2dInt8_NCHWc, apply_trace, Conv2dInt8_NCHWc_target, "llvm -mcpu=cascadelake", get_conv2d_vnni_mod(vnni_id), ) def test_winograd_gpu(): def apply_trace(sch): b0 = sch.get_block(name="B", func_name="main") b1 = sch.get_block(name="data_pack", func_name="main") b2 = sch.get_block(name="bgemm", func_name="main") b3 = sch.get_block(name="A", func_name="main") b4 = sch.get_block(name="inverse", func_name="main") b5 = sch.get_block(name="conv2d_winograd", func_name="main") b6 = sch.get_block(name="T_add", func_name="main") b7 = sch.get_block(name="T_relu", func_name="main") b8 = sch.get_block(name="root", func_name="main") sch.compute_inline(block=b0) (b9,) = sch.get_producers(block=b1) (b10,) = sch.get_producers(block=b9) l11, l12, l13, l14, l15, l16 = sch.get_loops(block=b1) v17, v18 = sch.sample_perfect_tile( loop=l13, n=2, max_innermost_factor=64, decision=[14, 14] ) l19, l20 = sch.split(loop=l13, factors=[v17, v18], preserve_unit_iters=True) v21, v22 = sch.sample_perfect_tile(loop=l14, n=2, max_innermost_factor=64, decision=[8, 8]) l23, l24 = sch.split(loop=l14, factors=[v21, v22], preserve_unit_iters=True) sch.unroll(loop=l11) sch.unroll(loop=l12) sch.unroll(loop=l15) sch.unroll(loop=l16) sch.reorder(l19, l23, l20, l24, l11, l12, l15, l16) sch.compute_at(block=b9, loop=l24, preserve_unit_loops=True, index=-1) sch.set_scope(block=b9, buffer_index=0, storage_scope="local") sch.compute_inline(block=b10) l25, l26, l27, l28, l29, l30, l31, l32 = sch.get_loops(block=b1) l33 = sch.fuse(l25, l26, l27, l28, preserve_unit_iters=True) v34 = sch.sample_categorical( candidates=[32, 64, 128, 256, 512, 1024], probs=[ 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, ], decision=2, ) l35, l36 = sch.split(loop=l33, factors=[None, v34], preserve_unit_iters=True) sch.bind(loop=l35, thread_axis="blockIdx.x") sch.bind(loop=l36, thread_axis="threadIdx.x") sch.compute_inline(block=b3) l37, l38, l39, l40, l41, l42 = sch.get_loops(block=b4) v43, v44 = sch.sample_perfect_tile(loop=l39, n=2, max_innermost_factor=64, decision=[28, 7]) l45, l46 = sch.split(loop=l39, factors=[v43, v44], preserve_unit_iters=True) v47, v48 = sch.sample_perfect_tile(loop=l40, n=2, max_innermost_factor=64, decision=[2, 32]) l49, l50 = sch.split(loop=l40, factors=[v47, v48], preserve_unit_iters=True) sch.unroll(loop=l37) sch.unroll(loop=l38) sch.unroll(loop=l41) sch.unroll(loop=l42) sch.reorder(l45, l49, l46, l50, l37, l38, l41, l42) l51, l52, l53, l54, l55, l56, l57, l58 = sch.get_loops(block=b4) l59 = sch.fuse(l51, l52, l53, l54, preserve_unit_iters=True) v60 = sch.sample_categorical( candidates=[32, 64, 128, 256, 512, 1024], probs=[ 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, ], decision=4, ) l61, l62 = sch.split(loop=l59, factors=[None, v60], preserve_unit_iters=True) sch.bind(loop=l61, thread_axis="blockIdx.x") sch.bind(loop=l62, thread_axis="threadIdx.x") sch.annotate(block_or_loop=b2, ann_key="meta_schedule.tiling_structure", ann_val="SSSRRSRS") l63, l64, l65, l66, l67 = sch.get_loops(block=b2) v68, v69, v70, v71, v72 = sch.sample_perfect_tile( loop=l63, n=5, max_innermost_factor=64, decision=[1, 2, 3, 1, 1] ) l73, l74, l75, l76, l77 = sch.split( loop=l63, factors=[v68, v69, v70, v71, v72], preserve_unit_iters=True ) v78, v79, v80, v81, v82 = sch.sample_perfect_tile( loop=l64, n=5, max_innermost_factor=64, decision=[6, 1, 1, 1, 1] ) l83, l84, l85, l86, l87 = sch.split( loop=l64, factors=[v78, v79, v80, v81, v82], preserve_unit_iters=True ) v88, v89, v90, v91, v92 = sch.sample_perfect_tile( loop=l65, n=5, max_innermost_factor=64, decision=[7, 2, 1, 14, 1] ) l93, l94, l95, l96, l97 = sch.split( loop=l65, factors=[v88, v89, v90, v91, v92], preserve_unit_iters=True ) v98, v99, v100, v101, v102 = sch.sample_perfect_tile( loop=l66, n=5, max_innermost_factor=64, decision=[4, 1, 16, 1, 1] ) l103, l104, l105, l106, l107 = sch.split( loop=l66, factors=[v98, v99, v100, v101, v102], preserve_unit_iters=True ) v108, v109, v110 = sch.sample_perfect_tile( loop=l67, n=3, max_innermost_factor=64, decision=[2, 2, 16] ) l111, l112, l113 = sch.split(loop=l67, factors=[v108, v109, v110], preserve_unit_iters=True) sch.reorder( l73, l83, l93, l103, l74, l84, l94, l104, l75, l85, l95, l105, l111, l112, l76, l86, l96, l106, l113, l77, l87, l97, l107, ) l114 = sch.fuse(l73, l83, l93, l103, preserve_unit_iters=True) sch.bind(loop=l114, thread_axis="blockIdx.x") l115 = sch.fuse(l74, l84, l94, l104, preserve_unit_iters=True) sch.bind(loop=l115, thread_axis="vthread.x") l116 = sch.fuse(l75, l85, l95, l105, preserve_unit_iters=True) sch.bind(loop=l116, thread_axis="threadIdx.x") sch.annotate( block_or_loop=b2, ann_key="meta_schedule.thread_extent_low_inclusive", ann_val=32 ) sch.annotate( block_or_loop=b2, ann_key="meta_schedule.thread_extent_high_inclusive", ann_val=1024 ) b117 = sch.cache_write(block=b2, write_buffer_index=0, storage_scope="local") sch.reverse_compute_at(block=b117, loop=l116, preserve_unit_loops=True, index=-1) b118 = sch.cache_read( block=b2, read_buffer_index=0, storage_scope="shared", consumer_blocks=[b2] ) sch.compute_at(block=b118, loop=l111, preserve_unit_loops=True, index=-1) l119, l120, l121, l122, l123, l124, l125, l126 = sch.get_loops(block=b118) l127 = sch.fuse(l123, l124, l125, l126, preserve_unit_iters=True) v128 = sch.sample_categorical( candidates=[1, 2, 3, 4], probs=[0.25, 0.25, 0.25, 0.25], decision=3 ) sch.annotate(block_or_loop=b118, ann_key="meta_schedule.cooperative_fetch", ann_val=v128) b129 = sch.cache_read( block=b2, read_buffer_index=1, storage_scope="shared", consumer_blocks=[b2] ) sch.compute_at(block=b129, loop=l111, preserve_unit_loops=True, index=-1) l130, l131, l132, l133, l134, l135, l136, l137 = sch.get_loops(block=b129) l138 = sch.fuse(l134, l135, l136, l137, preserve_unit_iters=True) v139 = sch.sample_categorical( candidates=[1, 2, 3, 4], probs=[0.25, 0.25, 0.25, 0.25], decision=3 ) sch.annotate(block_or_loop=b129, ann_key="meta_schedule.cooperative_fetch", ann_val=v139) sch.reverse_compute_inline(block=b7) sch.reverse_compute_inline(block=b6) v140 = sch.sample_categorical( candidates=[0, 16, 64, 512, 1024], probs=[ 0.20000000000000001, 0.20000000000000001, 0.20000000000000001, 0.20000000000000001, 0.20000000000000001, ], decision=4, ) sch.annotate(block_or_loop=b8, ann_key="meta_schedule.unroll_explicit", ann_val=v140) l141, l142, l143, l144 = sch.get_loops(block=b5) l145 = sch.fuse(l141, l142, l143, l144, preserve_unit_iters=True) v146 = sch.sample_categorical( candidates=[32, 64, 128, 256, 512, 1024], probs=[ 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, ], decision=2, ) l147, l148 = sch.split(loop=l145, factors=[None, v146], preserve_unit_iters=True) sch.bind(loop=l147, thread_axis="blockIdx.x") sch.bind(loop=l148, thread_axis="threadIdx.x") sch.enter_postproc() sch.unannotate(block_or_loop=b118, ann_key="meta_schedule.cooperative_fetch") l149, l150, l151, l152, l153 = sch.get_loops(block=b118) l154, l155, l156 = sch.split(loop=l153, factors=[None, 48, 4], preserve_unit_iters=True) sch.vectorize(loop=l156) sch.bind(loop=l155, thread_axis="threadIdx.x") sch.unannotate(block_or_loop=b129, ann_key="meta_schedule.cooperative_fetch") l157, l158, l159, l160, l161 = sch.get_loops(block=b129) l162, l163, l164 = sch.split(loop=l161, factors=[None, 48, 4], preserve_unit_iters=True) sch.vectorize(loop=l164) sch.bind(loop=l163, thread_axis="threadIdx.x") b165 = sch.get_block(name="root", func_name="main") sch.unannotate(block_or_loop=b165, ann_key="meta_schedule.unroll_explicit") b166, b167, b168, b169, b170, b171, b172, b173 = sch.get_child_blocks(b165) l174, l175, l176, l177, l178, l179 = sch.get_loops(block=b166) sch.annotate(block_or_loop=l174, ann_key="pragma_auto_unroll_max_step", ann_val=1024) sch.annotate(block_or_loop=l174, ann_key="pragma_unroll_explicit", ann_val=1) l180, l181, l182, l183, l184, l185 = sch.get_loops(block=b167) sch.annotate(block_or_loop=l180, ann_key="pragma_auto_unroll_max_step", ann_val=1024) sch.annotate(block_or_loop=l180, ann_key="pragma_unroll_explicit", ann_val=1) l186, l187, l188, l189, l190, l191, l192 = sch.get_loops(block=b168) sch.annotate(block_or_loop=l186, ann_key="pragma_auto_unroll_max_step", ann_val=1024) sch.annotate(block_or_loop=l186, ann_key="pragma_unroll_explicit", ann_val=1) l193, l194, l195, l196, l197, l198, l199 = sch.get_loops(block=b169) sch.annotate(block_or_loop=l193, ann_key="pragma_auto_unroll_max_step", ann_val=1024) sch.annotate(block_or_loop=l193, ann_key="pragma_unroll_explicit", ann_val=1) ( l200, l201, l202, l203, l204, l205, l206, l207, l208, l209, l210, l211, l212, l213, ) = sch.get_loops(block=b170) sch.annotate(block_or_loop=l200, ann_key="pragma_auto_unroll_max_step", ann_val=1024) sch.annotate(block_or_loop=l200, ann_key="pragma_unroll_explicit", ann_val=1) l214, l215, l216, l217, l218, l219, l220 = sch.get_loops(block=b171) sch.annotate(block_or_loop=l214, ann_key="pragma_auto_unroll_max_step", ann_val=1024) sch.annotate(block_or_loop=l214, ann_key="pragma_unroll_explicit", ann_val=1) l221, l222, l223, l224, l225, l226 = sch.get_loops(block=b172) sch.annotate(block_or_loop=l221, ann_key="pragma_auto_unroll_max_step", ann_val=1024) sch.annotate(block_or_loop=l221, ann_key="pragma_unroll_explicit", ann_val=1) l227, l228 = sch.get_loops(block=b173) sch.annotate(block_or_loop=l227, ann_key="pragma_auto_unroll_max_step", ann_val=1024) sch.annotate(block_or_loop=l227, ann_key="pragma_unroll_explicit", ann_val=1) b229 = sch.get_block(name="data_pack", func_name="main") l230, l231, l232, l233, l234, l235 = sch.get_loops(block=b229) b236 = sch.decompose_reduction(block=b229, loop=l234) b237 = sch.get_block(name="bgemm", func_name="main") ( l238, l239, l240, l241, l242, l243, l244, l245, l246, l247, l248, l249, l250, l251, ) = sch.get_loops(block=b237) b252 = sch.decompose_reduction(block=b237, loop=l241) b253 = sch.get_block(name="inverse", func_name="main") l254, l255, l256, l257, l258, l259 = sch.get_loops(block=b253) b260 = sch.decompose_reduction(block=b253, loop=l258) verify( Conv2dWinogradAddRelu, apply_trace, Conv2dWinogradAddResidualRelu, "cuda", Conv2dWinogradAddResidualRelu_scheduled, ) def test_inline_order(): # In this test, the order of applying AutoInline is tested. # We need to make sure that the last block in Conv2dInt8_with_predicate_target, # "compute_4", is AutoInline-ed after all other blocks have been processed. # # Otherwise, if the order is "T_add_2" -> "compute_4" -> "compute_3", "compute_4" is neither # inlined (because this is the last block) nor reverse-inlined # (because it has multiple producers). This results in the "compute_4" block being # reverse-inlined at the very end of ScheduleUsingAnchorTrace, where its producer block # "conv2d_nhwc_reindex_shared" has the predicate # T.where(((ax1_0 * 4 + ax1_1) * 32 + ax1_2) * 2 + ax1_3 < 64) due to anchor-block scheduling # (see Conv2dInt8_with_predicate_scheduled). ReverseComputeInline cannot be applied in # such cases. def apply_trace(sch: Schedule) -> None: b0 = sch.get_block(name="pad_temp", func_name="main") b1 = sch.get_block(name="conv2d_nhwc", func_name="main") b2 = sch.get_block(name="T_subtract", func_name="main") b3 = sch.get_block(name="T_add", func_name="main") b4 = sch.get_block(name="compute", func_name="main") b5 = sch.get_block(name="T_add_1", func_name="main") b6 = sch.get_block(name="compute_1", func_name="main") b7 = sch.get_block(name="T_subtract_1", func_name="main") b8 = sch.get_block(name="compute_2", func_name="main") b9 = sch.get_block(name="root", func_name="main") sch.annotate(block_or_loop=b1, ann_key="meta_schedule.tiling_structure", ann_val="SSSRRSRS") b10 = sch.reindex(block=b1, buffer=("write", 0)) b11 = sch.reindex(block=b1, buffer=("read", 0)) b12 = sch.reindex(block=b1, buffer=("read", 1)) sch.transform_layout( block=b1, buffer=("read", 0), index_map=lambda nn, yy, xx, rc: ( (((nn * 3136) + (yy * 56)) + xx), rc, ), pad_value=None, ) sch.transform_layout( block=b1, buffer=("read", 1), index_map=lambda ff, ry, rx, rc: ( ry, rx, ff, rc, ), pad_value=None, ) sch.transform_layout( block=b1, buffer=("write", 0), index_map=lambda nn, yy, xx, ff: ( (((nn * 3136) + (yy * 56)) + xx), ff, ), pad_value=None, ) sch.transform_block_layout( block=b10, index_map=lambda nn, yy, xx, ff: ( (((nn * 3136) + (yy * 56)) + xx), ff, ), ) sch.transform_block_layout( block=b11, index_map=lambda nn, yy, xx, rc: ( (((nn * 3136) + (yy * 56)) + xx), rc, ), ) sch.transform_block_layout( block=b12, index_map=lambda ff, ry, rx, rc: ( ry, rx, ff, rc, ), ) sch.transform_block_layout( block=b1, index_map=lambda nn, yy, xx, ff, ry, rx, rc: ( ry, rx, (((nn * 3136) + (yy * 56)) + xx), ff, rc, ), ) l13, l14, l15, l16, l17 = sch.get_loops(block=b1) l18, l19 = sch.split(loop=l17, factors=[None, 16], preserve_unit_iters=True) l20, l21 = sch.split(loop=l16, factors=[None, 16], preserve_unit_iters=True) l22, l23 = sch.split(loop=l15, factors=[None, 16], preserve_unit_iters=True) l24, l25, l26, l27, l28, l29, l30, l31 = sch.get_loops(block=b1) sch.reorder(l28, l30, l23, l21, l19) b32 = sch.blockize(loop=l23) sch.annotate( block_or_loop=b32, ann_key="meta_schedule.auto_tensorize", ann_val="wmma_sync_16x16x16_s8s8s32_trans", ) sch.annotate( block_or_loop=b32, ann_key="meta_schedule.auto_tensorize_init", ann_val="wmma_fill_16x16x16_s32", ) sch.annotate(block_or_loop=b32, ann_key="warp_execution", ann_val=1) l33, l34, l35, l36, l37 = sch.get_loops(block=b32) v38, v39, v40 = sch.sample_perfect_tile( loop=l33, n=3, max_innermost_factor=4, decision=[1, 1, 1] ) l41, l42, l43 = sch.split(loop=l33, factors=[v38, v39, v40], preserve_unit_iters=True) v44, v45, v46 = sch.sample_perfect_tile( loop=l34, n=3, max_innermost_factor=4, decision=[1, 1, 1] ) l47, l48, l49 = sch.split(loop=l34, factors=[v44, v45, v46], preserve_unit_iters=True) v50, v51, v52, v53, v54 = sch.sample_perfect_tile( loop=l35, n=5, max_innermost_factor=4, decision=[8, 196, 2, 1, 1] ) l55, l56, l57, l58, l59 = sch.split( loop=l35, factors=[v50, v51, v52, v53, v54], preserve_unit_iters=True ) v60, v61, v62, v63, v64 = sch.sample_perfect_tile( loop=l36, n=5, max_innermost_factor=4, decision=[4, 1, 2, 1, 2] ) l65, l66, l67, l68, l69 = sch.split( loop=l36, factors=[v60, v61, v62, v63, v64], preserve_unit_iters=True ) v70, v71, v72 = sch.sample_perfect_tile( loop=l37, n=3, max_innermost_factor=4, decision=[2, 2, 1] ) l73, l74, l75 = sch.split(loop=l37, factors=[v70, v71, v72], preserve_unit_iters=True) sch.reorder( l55, l65, l56, l66, l57, l67, l41, l47, l73, l42, l48, l74, l58, l68, l43, l49, l75, l59, l69, ) l76 = sch.fuse(l55, l65, preserve_unit_iters=True) sch.bind(loop=l76, thread_axis="blockIdx.y") l77 = sch.fuse(l56, l66, preserve_unit_iters=True) sch.bind(loop=l77, thread_axis="blockIdx.x") l78 = sch.fuse(l57, l67, preserve_unit_iters=True) sch.bind(loop=l78, thread_axis="threadIdx.y") sch.annotate( block_or_loop=b32, ann_key="meta_schedule.thread_extent_low_inclusive", ann_val=32 ) sch.annotate( block_or_loop=b32, ann_key="meta_schedule.thread_extent_high_inclusive", ann_val=1024 ) b79 = sch.cache_write(block=b32, write_buffer_index=0, storage_scope="shared") sch.reverse_compute_at(block=b79, loop=l77, preserve_unit_loops=True, index=-1) b80 = sch.cache_write(block=b32, write_buffer_index=0, storage_scope="wmma.accumulator") sch.reverse_compute_at(block=b80, loop=l78, preserve_unit_loops=True, index=-1) v81 = sch.sample_categorical( candidates=[1, 2, 3, 4, 8, 16], probs=[ 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, ], decision=1, ) sch.annotate(block_or_loop=b79, ann_key="meta_schedule.cooperative_fetch", ann_val=v81) sch.reverse_compute_inline(block=b10) l82, l83, l84, l85, l86 = sch.get_loops(block=b80) l87, l88 = sch.split(loop=l86, factors=[None, 16], preserve_unit_iters=True) l89, l90 = sch.split(loop=l85, factors=[None, 16], preserve_unit_iters=True) l91, l92, l93, l94, l95, l96, l97 = sch.get_loops(block=b80) sch.reorder(l96, l90, l88) b98 = sch.blockize(loop=l90) sch.annotate( block_or_loop=b98, ann_key="meta_schedule.auto_tensorize", ann_val="wmma_store_16x16x16_s32_shared", ) b99 = sch.cache_read( block=b32, read_buffer_index=0, storage_scope="shared", consumer_blocks=[b32] ) sch.compute_at(block=b99, loop=l73, preserve_unit_loops=True, index=-1) l100, l101, l102, l103, l104, l105, l106, l107 = sch.get_loops(block=b99) l108 = sch.fuse(l106, l107, preserve_unit_iters=True) v109 = sch.sample_categorical( candidates=[1, 2, 3, 4, 8, 16], probs=[ 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, ], decision=3, ) sch.annotate(block_or_loop=b99, ann_key="meta_schedule.cooperative_fetch", ann_val=v109) b110 = sch.cache_read( block=b32, read_buffer_index=1, storage_scope="shared", consumer_blocks=[b32] ) sch.compute_at(block=b110, loop=l73, preserve_unit_loops=True, index=-1) l111, l112, l113, l114, l115, l116, l117, l118, l119, l120 = sch.get_loops(block=b110) l121 = sch.fuse(l117, l118, l119, l120, preserve_unit_iters=True) v122 = sch.sample_categorical( candidates=[1, 2, 3, 4, 8, 16], probs=[ 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, ], decision=2, ) sch.annotate(block_or_loop=b110, ann_key="meta_schedule.cooperative_fetch", ann_val=v122) b123 = sch.cache_read(block=b32, read_buffer_index=0, storage_scope="wmma.matrix_a") sch.compute_at(block=b123, loop=l74, preserve_unit_loops=True, index=-1) l124, l125, l126, l127, l128, l129, l130, l131, l132, l133, l134 = sch.get_loops(block=b123) l135, l136 = sch.split(loop=l134, factors=[None, 16], preserve_unit_iters=True) l137, l138 = sch.split(loop=l133, factors=[None, 16], preserve_unit_iters=True) ( l139, l140, l141, l142, l143, l144, l145, l146, l147, l148, l149, l150, l151, ) = sch.get_loops(block=b123) sch.reorder(l150, l138, l136) b152 = sch.blockize(loop=l138) sch.annotate( block_or_loop=b152, ann_key="meta_schedule.auto_tensorize", ann_val="wmma_load_16x16x16_s8_a", ) b153 = sch.cache_read(block=b32, read_buffer_index=1, storage_scope="wmma.matrix_b") sch.compute_at(block=b153, loop=l74, preserve_unit_loops=True, index=-1) ( l154, l155, l156, l157, l158, l159, l160, l161, l162, l163, l164, l165, l166, ) = sch.get_loops(block=b153) l167, l168 = sch.split(loop=l166, factors=[None, 16], preserve_unit_iters=True) l169, l170 = sch.split(loop=l165, factors=[None, 16], preserve_unit_iters=True) ( l171, l172, l173, l174, l175, l176, l177, l178, l179, l180, l181, l182, l183, l184, l185, ) = sch.get_loops(block=b153) sch.reorder(l184, l170, l168) b186 = sch.blockize(loop=l170) sch.annotate( block_or_loop=b186, ann_key="meta_schedule.auto_tensorize", ann_val="wmma_load_16x16x16_s8_b_trans", ) sch.compute_inline(block=b11) sch.compute_inline(block=b12) sch.storage_align(block=b99, buffer_index=0, axis=-2, factor=32, offset=16) sch.storage_align(block=b110, buffer_index=0, axis=-2, factor=32, offset=16) sch.reverse_compute_inline(block=b8) sch.reverse_compute_inline(block=b7) sch.reverse_compute_inline(block=b6) sch.reverse_compute_inline(block=b5) sch.reverse_compute_inline(block=b4) sch.reverse_compute_inline(block=b3) sch.reverse_compute_inline(block=b2) sch.compute_inline(block=b0) v187 = sch.sample_categorical( candidates=[0, 16, 64, 512, 1024], probs=[ 0.20000000000000001, 0.20000000000000001, 0.20000000000000001, 0.20000000000000001, 0.20000000000000001, ], decision=4, ) sch.annotate(block_or_loop=b9, ann_key="meta_schedule.unroll_explicit", ann_val=v187) sch.enter_postproc() sch.unannotate(block_or_loop=b79, ann_key="meta_schedule.cooperative_fetch") l188, l189, l190, l191 = sch.get_loops(block=b79) l192, l193, l194, l195 = sch.split( loop=l191, factors=[None, 4, 32, 2], preserve_unit_iters=True ) verify( Conv2dInt8_with_predicate, apply_trace, Conv2dInt8_with_predicate_target, "cuda", Conv2dInt8_with_predicate_scheduled, ) if __name__ == "__main__": tvm.testing.main()
https://github.com/zk-ml/tachikoma
tests/python/unittest/test_meta_schedule_tune_context.py
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. """Test the tune context of meta schedule.""" import sys import pytest import tvm import tvm.testing from tvm.script import tir as T from tvm.target import Target from tvm.meta_schedule import TuneContext # pylint: disable=invalid-name,no-member,line-too-long,too-many-nested-blocks,missing-docstring @tvm.script.ir_module class Matmul: @T.prim_func def main(a: T.handle, b: T.handle, c: T.handle) -> None: # pylint: disable=no-self-argument T.func_attr({"global_symbol": "main", "tir.noalias": True}) A = T.match_buffer(a, (1024, 1024), "float32") B = T.match_buffer(b, (1024, 1024), "float32") C = T.match_buffer(c, (1024, 1024), "float32") for i, j, k in T.grid(1024, 1024, 1024): with T.block("matmul"): vi, vj, vk = T.axis.remap("SSR", [i, j, k]) with T.init(): C[vi, vj] = 0.0 C[vi, vj] = C[vi, vj] + A[vi, vk] * B[vk, vj] # pylint: enable=invalid-name,no-member,line-too-long,too-many-nested-blocks,missing-docstring def test_tune_context_create(): mod = Matmul context = TuneContext(mod=mod, target=Target("llvm"), task_name="Test Task") assert context.num_threads > 0 assert context.rand_state != -1 assert context.task_name == "Test Task" assert context.mod == mod or tvm.ir.structural_equal(context.mod, mod) if __name__ == "__main__": tvm.testing.main()
https://github.com/zk-ml/tachikoma
tests/python/unittest/test_meta_schedule_tune_tir.py
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. # pylint: disable=missing-docstring,no-member,invalid-name,unused-variable import logging import tempfile import numpy as np import pytest import tvm import tvm.testing from tvm import meta_schedule as ms from tvm.meta_schedule.testing.custom_builder_runner import run_module_via_rpc from tvm.meta_schedule.testing.local_rpc import LocalRPC from tvm.script import tir as T from tvm.target import Target from tvm.tir.schedule import BlockRV, Schedule logging.basicConfig() logging.getLogger("tvm.meta_schedule").setLevel(logging.DEBUG) @T.prim_func def matmul(a: T.handle, b: T.handle, c: T.handle) -> None: A = T.match_buffer(a, [128, 128]) B = T.match_buffer(b, [128, 128]) C = T.match_buffer(c, [128, 128]) for i, j, k in T.grid(128, 128, 128): with T.block("update"): vi, vj, vk = T.axis.remap("SSR", [i, j, k]) with T.init(): C[vi, vj] = 0.0 C[vi, vj] = C[vi, vj] + A[vi, vk] * B[vj, vk] @T.prim_func def two_step(a: T.handle, c: T.handle) -> None: A = T.match_buffer(a, (1024, 1024), "float32") B = T.alloc_buffer((1024, 1024), "float32") C = T.match_buffer(c, (1024, 1024), "float32") for i, j in T.grid(1024, 1024): with T.block("A"): vi, vj = T.axis.remap("SS", [i, j]) B[vi, vj] = A[vi, vj] * 2.0 for i, j in T.grid(1024, 1024): with T.block("B"): vi, vj = T.axis.remap("SS", [i, j]) C[vi, vj] = B[vi, vj] + 3.0 @tvm.testing.requires_llvm def test_tune_matmul_cpu(): with tempfile.TemporaryDirectory() as work_dir: target = Target("llvm --num-cores=16") database = ms.tir_integration.tune_tir( mod=matmul, target=target, work_dir=work_dir, max_trials_global=32, num_trials_per_iter=16, ) sch = ms.tir_integration.compile_tir(database, matmul, target) if sch is None: print("No valid schedule found!") else: sch.mod.show() sch.trace.show() @tvm.testing.requires_cuda def test_tune_matmul_cuda(): with tempfile.TemporaryDirectory() as work_dir: target = Target("nvidia/geforce-rtx-3070") database = ms.tir_integration.tune_tir( mod=matmul, target=target, work_dir=work_dir, max_trials_global=32, num_trials_per_iter=16, ) sch = ms.tir_integration.compile_tir(database, matmul, target) if sch is None: print("No valid schedule found!") else: sch.mod.show() sch.trace.show() def test_tune_run_module_via_rpc(): target = tvm.target.Target("llvm") rt_mod = tvm.build(matmul, target) # construct the input input_data = {} input_shape = (128, 128) input_dtype = "float32" a_np = np.random.uniform(size=input_shape).astype(input_dtype) b_np = np.random.uniform(size=input_shape).astype(input_dtype) c_np = np.zeros(input_shape).astype(input_dtype) for i in range(128): for j in range(128): for k in range(128): c_np[i, j] = c_np[i, j] + a_np[i, k] * b_np[j, k] input_data["a"] = a_np input_data["b"] = b_np input_data["c"] = np.zeros(input_shape).astype(input_dtype) with LocalRPC() as rpc: rpc_config = ms.runner.RPCConfig( tracker_host=rpc.tracker_host, tracker_port=rpc.tracker_port, tracker_key=rpc.tracker_key, session_priority=1, session_timeout_sec=100, ) def f_timer(rt_mod, dev, input_data): rt_mod(input_data["a"], input_data["b"], input_data["c"]) return input_data["c"] result = run_module_via_rpc( rpc_config=rpc_config, lib=rt_mod, dev_type=target.kind.name, args=input_data, continuation=f_timer, ) tvm.testing.assert_allclose(result.numpy(), c_np, rtol=1e-3) def test_tune_block_cpu(): @ms.derived_object class RemoveBlock(ms.schedule_rule.PyScheduleRule): def _initialize_with_tune_context(self, context: ms.TuneContext) -> None: pass def apply(self, sch: Schedule, block: BlockRV): if sch.get(block).name_hint == "root": return [sch] sch = sch.copy() sch.compute_inline(block) return [sch] def clone(self) -> "RemoveBlock": return RemoveBlock() with tempfile.TemporaryDirectory() as work_dir: target = Target("llvm --num-cores=16") database = ms.tir_integration.tune_tir( mod=two_step, target=target, work_dir=work_dir, max_trials_global=32, num_trials_per_iter=16, space=ms.space_generator.PostOrderApply( f_block_filter=lambda block: block.name_hint == "A", sch_rules=[RemoveBlock()], postprocs=[], mutator_probs={}, ), ) sch = ms.tir_integration.compile_tir(database, two_step, target) assert sch is not None sch.mod.show() sch.trace.show() if __name__ == """__main__""": test_tune_matmul_cpu() test_tune_matmul_cuda() test_tune_run_module_via_rpc() test_tune_block_cpu()
https://github.com/zk-ml/tachikoma
tests/python/unittest/test_meta_schedule_vnni_integration.py
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. # pylint: disable=missing-docstring import logging import tempfile from typing import Optional import numpy as np # type: ignore import tvm import tvm.testing from tvm import meta_schedule as ms from tvm import relay from tvm._ffi import register_func from tvm.tir.schedule import BlockRV, Schedule from tvm.tir.schedule.analysis import has_block from tvm.tir.tensor_intrin.x86 import VNNI_DOT_16x4_INTRIN as VNNI_INTRIN logging.basicConfig( format="%(asctime)s.%(msecs)03d %(levelname)s %(message)s", datefmt="%Y-%m-%d %H:%M:%S", ) logging.getLogger("tvm.meta_schedule").setLevel(logging.DEBUG) def _schedule_dense(m: Optional[int], do_tune: bool): """Manually schedule a dense block, created from TE compute op via CreatePrimFunc, using VNNI instruction. """ def schedule_fn(sch, dense_block: Optional[BlockRV] = None) -> bool: if sch.mod.attrs is not None and "dense" not in sch.mod.attrs["task_name"]: return False if dense_block is None: assert has_block(sch, "compute") dense_block = sch.get_block("compute") assert "dense_vnni" in sch.get(dense_block).annotations["schedule_rule"] post_blocks = sch.get_consumers(dense_block) if len(post_blocks) > 0: # Fuse all intermediate post ops into the last op. # This is equivalent to the traverse_inline function used in TE schedules. while True: next_post_blocks = [] for post_block in post_blocks: next_consumers = sch.get_consumers(post_block) if len(next_consumers) > 0: sch.compute_inline(post_block) next_post_blocks += next_consumers if len(next_post_blocks) == 0: assert len(post_blocks) == 1 outer_block = post_blocks[0] a_y, a_x = sch.get_loops(outer_block)[-2:] break post_blocks = next_post_blocks else: a_y, a_x, _ = sch.get_loops(dense_block)[-3:] outer_block = dense_block if do_tune: y_factors = sch.sample_perfect_tile(a_y, n=2, max_innermost_factor=128) a_yo, a_yi = sch.split(a_y, factors=y_factors) else: a_yo, a_yi = sch.split(a_y, factors=[None, min(m, 64)]) a_xo, a_xi = sch.split(a_x, factors=[None, 16]) sch.reorder(a_yo, a_xo, a_yi, a_xi) fused = sch.fuse(a_yo, a_xo) if outer_block != dense_block: # Handle the case when dense is fused with post ops. sch.vectorize(a_xi) sch.compute_at(dense_block, a_yi) a_xi, a_k = sch.get_loops(dense_block)[-2:] a_ko, a_ki = sch.split(a_k, factors=[None, 4]) sch.reorder(a_ko, a_xi, a_ki) # We need to parallelize before decompose_reduction, otherwise the so-called "Compact dataflow" # condition is violated. sch.parallel(fused) dec = sch.decompose_reduction(dense_block, a_ko) init_loop = sch.get_loops(dec)[-1] sch.vectorize(init_loop) sch.tensorize(a_xi, VNNI_INTRIN) return True return schedule_fn def _relay_dense(m, n, k): data = relay.var("data", shape=(m, k), dtype="uint8") weight = relay.var("weight", shape=(n, k), dtype="int8") bias = relay.var("bias", shape=(n,), dtype="int32") # dense is tuned by the TIR schedule above, bmm is scheduled by TE (topi/x86/batch_matmul.py) dense = relay.nn.dense(data, weight, out_dtype="int32") bias_add = relay.nn.bias_add(dense, bias) + relay.const(1, dtype="int32") out = relay.nn.batch_matmul( relay.cast(relay.expand_dims(bias_add, 0), "uint8"), relay.cast(relay.expand_dims(bias_add, 0), "int8"), out_dtype="int32", ) relay_mod = tvm.IRModule.from_expr(out) data = np.random.uniform(1, 10, size=(m, k)).astype("uint8") params = { "weight": np.random.uniform(1, 10, size=(n, k)).astype("int8"), "bias": np.random.uniform(1, 10, size=(n,)).astype("int32"), } def f_check(lib, dev): ref = ( relay.create_executor( "vm", mod=relay_mod, device=dev, target="llvm", ) .evaluate()(data, params["weight"], params["bias"]) .numpy() ) runtime = tvm.contrib.graph_executor.GraphModule(lib["default"](dev)) runtime.set_input("data", data) runtime.run() out = runtime.get_output(0).numpy() np.testing.assert_equal(out, ref) return relay_mod, params, f_check @tvm.testing.requires_cascadelake def test_vnni_schedule_fn_database(): m, n, k = 1024, 1024, 1024 target = tvm.target.Target("llvm -mcpu=cascadelake -num-cores 4") dev = tvm.cpu(0) relay_mod, params, f_check = _relay_dense(m, n, k) with ms.database.ScheduleFnDatabase( _schedule_dense( m=m, do_tune=False, ) ), tvm.transform.PassContext( opt_level=3, config={"relay.backend.use_meta_schedule": True}, ): # pylint: disable=W0105 """The log should say Warning: Cannot find workload: tvmgen_default_fused_expand_dims Warning: Cannot find workload: tvmgen_default_fused_cast Warning: Cannot find workload: tvmgen_default_fused_cast_1 Warning: Cannot find workload: tvmgen_default_fused_nn_batch_matmul This means batch matmul and others are scheduled by TE, and dense (the one not warned) is found in the meta schedule tuning database during compilation """ # pylint: enable=W0105 lib = relay.build(relay_mod, target=target, params=params) f_check(lib, dev) @tvm.testing.requires_cascadelake def test_vnni_schedule_fn_tune(): # pylint: disable=W0105 """ We can inject and apply a custom TIR scheduling to a TE compute of interest, using the "schedule_rule" annotation. For example, in topi/x86/dense.py we have the following declaration for int8 dense targeting the VNNI instruction. C = te.compute( ... attrs={"schedule_rule": "meta_schedule.x86.dense_vnni"}, ) When the MetaSchedule encounters a TensorIR block with the "schedule_rule" annotation, it looks up the packed func registry for a function that is associated with the given schedule rule key ("meta_schedule.x86.dense_vnni" in this example). The signature of such custom schedule functions must be (tir.schedule.Schedule, tir.schedule.BlockRV) -> [tir.schedule.Schedule]. The BlockRV argument corresponds to the TE compute annotated with "schedule_rule". The relevant code is in `src/meta_schedule/space_generator/apply_custom_rule.cc`. """ def schedule_rule_dense_vnni(sch: Schedule, dense_block: BlockRV): _schedule_dense(m=None, do_tune=True)(sch, dense_block) return [sch] register_func("meta_schedule.x86.dense_vnni", schedule_rule_dense_vnni) m, n, k = 1024, 1024, 1024 target = tvm.target.Target("llvm -keys=x86,cpu -mcpu=cascadelake -num-cores=4") dev = tvm.cpu(0) relay_mod, params, f_check = _relay_dense(m, n, k) extracted_tasks = ms.relay_integration.extract_tasks(relay_mod, target, params) with tempfile.TemporaryDirectory() as work_dir: # postprocs=lambda: [] is important to prevent default post processors from # tampering with the manual schedule. tasks, weights = ms.relay_integration.extracted_tasks_to_tune_contexts( list( filter( lambda task: "dense" in task.task_name, extracted_tasks, ) ), work_dir=work_dir, space=ms.space_generator.PostOrderApply( f_block_filter=None, sch_rules="from-target", postprocs=[], mutator_probs="from-target", ), ) database = ms.relay_integration.tune_tasks( tasks=tasks, task_weights=weights, work_dir=work_dir, max_trials_per_task=32, max_trials_global=20000, ) with database, tvm.transform.PassContext( opt_level=3, config={"relay.backend.use_meta_schedule": True}, ): # pylint: disable=W0105 """The log should say Warning: Cannot find workload: tvmgen_default_fused_expand_dims Warning: Cannot find workload: tvmgen_default_fused_cast Warning: Cannot find workload: tvmgen_default_fused_cast_1 Warning: Cannot find workload: tvmgen_default_fused_nn_batch_matmul This means batch matmul and others are scheduled by TE, and dense (the one not warned) is found in the meta schedule tuning database during compilation """ # pylint: enable=W0105 lib = relay.build(relay_mod, target=target, params=params) f_check(lib, dev) if __name__ == """__main__""": test_vnni_schedule_fn_database() test_vnni_schedule_fn_tune()
https://github.com/zk-ml/tachikoma
tests/python/unittest/test_micro_model_library_format.py
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. import pathlib import sys import datetime import json import os import tarfile import numpy as np import pytest import platform pytest.importorskip("tvm.micro") import tvm import tvm.relay from tvm.relay.backend import Executor, Runtime from tvm.relay.testing import byoc import tvm.runtime.module import tvm.testing from tvm.contrib import utils import tvm.micro as micro from tvm.micro.testing.utils import get_conv2d_relay_module import tvm.micro.model_library_format as model_library_format from tvm.micro.model_library_format import _GENERATED_VERSION @tvm.testing.requires_micro def test_export_operator_model_library_format(): target = tvm.target.target.micro("host") with tvm.transform.PassContext(opt_level=3, config={"tir.disable_vectorize": True}): A = tvm.te.placeholder((2,), dtype="int8") B = tvm.te.placeholder((1,), dtype="int8") C = tvm.te.compute(A.shape, lambda i: A[i] + B[0], name="C") sched = tvm.te.create_schedule(C.op) mod = tvm.build( sched, [A, B, C], tvm.target.Target(target, target), runtime=Runtime("crt", {"system-lib": True}), name="add", ) temp_dir = utils.tempdir() mlf_tar_path = temp_dir.relpath("lib.tar") micro.export_model_library_format(mod, mlf_tar_path) tf = tarfile.open(mlf_tar_path) extract_dir = temp_dir.relpath("extract") os.mkdir(extract_dir) tf.extractall(extract_dir) with open(os.path.join(extract_dir, "metadata.json")) as json_f: metadata = json.load(json_f) assert metadata["version"] == _GENERATED_VERSION assert metadata["model_name"] == "add" export_datetime = datetime.datetime.strptime( metadata["export_datetime"], "%Y-%m-%d %H:%M:%SZ" ) assert (datetime.datetime.now() - export_datetime) < datetime.timedelta(seconds=60 * 5) assert metadata["target"] == [str(target)] assert metadata["memory"]["add"][0]["dtype"] == "int8" assert metadata["memory"]["add"][0]["shape"] == [2] assert metadata["memory"]["add"][0]["size_bytes"] == 2 assert metadata["memory"]["add"][1]["dtype"] == "int8" assert metadata["memory"]["add"][1]["shape"] == [1] assert metadata["memory"]["add"][1]["size_bytes"] == 1 assert metadata["memory"]["add"][2]["dtype"] == "int8" assert metadata["memory"]["add"][2]["shape"] == [2] assert metadata["memory"]["add"][2]["size_bytes"] == 2 assert os.path.exists(os.path.join(extract_dir, "codegen", "host", "src", "lib0.c")) assert os.path.exists(os.path.join(extract_dir, "codegen", "host", "src", "lib1.c")) assert ( len(mod.ir_module_by_target) == 1 ), f"expect 1 ir_model_by_target: {mod.ir_module_by_target!r}" for target, ir_mod in mod.ir_module_by_target.items(): assert int(tvm.runtime.ndarray.device(str(target)).device_type) == 1 with open(os.path.join(extract_dir, "src", "tir-1.txt")) as tir_f: assert tir_f.read() == str(ir_mod) @tvm.testing.requires_micro def test_export_multiple_operator_model_library_format(): target = tvm.target.target.micro("host") with tvm.transform.PassContext(opt_level=3, config={"tir.disable_vectorize": True}): A = tvm.te.placeholder((2,), dtype="int8") B = tvm.te.placeholder((1,), dtype="int8") C = tvm.te.compute(A.shape, lambda i: A[i] + B[0], name="C") sched = tvm.te.create_schedule(C.op) mod = tvm.build( sched, [A, B, C], tvm.target.Target(target, target), runtime=Runtime("crt", {"system-lib": True}), name="add", ) temp_dir = utils.tempdir() mlf_tar_path = temp_dir.relpath("lib.tar") with pytest.raises(RuntimeError) as exc: micro.export_model_library_format([mod, mod], mlf_tar_path) assert str(exc.exception) == ("Multiple operator is not supported.") def validate_graph_json(extract_dir, factory): with open( os.path.join(extract_dir, "executor-config", "graph", f"{factory.libmod_name}.graph") ) as graph_f: graph_json = graph_f.read() assert graph_json == factory.graph_json # Just check it parses and looks roughly right. graph = json.loads(graph_json) assert "nodes" in graph assert len(graph["nodes"]) == 4 assert "attrs" in graph @tvm.testing.requires_micro @pytest.mark.parametrize( "executor,runtime,should_generate_interface,json_constants_size_bytes", [ (Executor("graph"), Runtime("crt", {"system-lib": True}), False, 8), (Executor("aot", {"link-params": True}), Runtime("crt"), False, 0), ( Executor("aot", {"unpacked-api": True, "interface-api": "c"}), Runtime("crt"), True, 0, ), ], ) def test_export_model_library_format_c( executor, runtime, should_generate_interface, json_constants_size_bytes ): target = tvm.target.target.micro("host") with utils.TempDirectory.set_keep_for_debug(True): with tvm.transform.PassContext(opt_level=3, config={"tir.disable_vectorize": True}): relay_mod = tvm.parser.fromtext( """ #[version = "0.0.5"] def @main(%a : Tensor[(1, 2), uint8], %b : Tensor[(1, 2), float32], %c : Tensor[(1, 2), float32]) { %0 = cast(%a, dtype="float32") + %b * %c; %0 }""" ) factory = tvm.relay.build( relay_mod, target, executor=executor, runtime=runtime, mod_name="add", params={"c": np.array([[2.0, 4.0]], dtype="float32")}, ) temp_dir = utils.tempdir() mlf_tar_path = temp_dir.relpath("lib.tar") micro.export_model_library_format(factory, mlf_tar_path) tf = tarfile.open(mlf_tar_path) extract_dir = temp_dir.relpath("extract") os.mkdir(extract_dir) tf.extractall(extract_dir) with open(os.path.join(extract_dir, "metadata.json")) as json_f: metadata = json.load(json_f) module_name = factory.libmod_name assert metadata["version"] == _GENERATED_VERSION assert metadata["modules"][module_name]["model_name"] == "add" export_datetime = datetime.datetime.strptime( metadata["modules"][module_name]["export_datetime"], "%Y-%m-%d %H:%M:%SZ" ) assert (datetime.datetime.now() - export_datetime) < datetime.timedelta(seconds=60 * 5) assert metadata["modules"][module_name]["target"] == [str(target)] if executor.name == "graph": assert metadata["modules"][module_name]["memory"]["sids"] == [ {"storage_id": 0, "size_bytes": 2, "input_binding": "a"}, {"storage_id": 1, "size_bytes": 8, "input_binding": "b"}, {"storage_id": 2, "size_bytes": 8, "input_binding": "p0"}, {"storage_id": 3, "size_bytes": 8}, ] assert metadata["modules"][module_name]["memory"]["functions"]["main"] == [ { "constants_size_bytes": json_constants_size_bytes, "device": 1, "io_size_bytes": 18, "workspace_size_bytes": 0, } ] assert metadata["modules"][module_name]["memory"]["functions"]["operator_functions"][0][ "workspace" ] == [{"device": 1, "workspace_size_bytes": 0}] assert ( "fused_cast_multiply_add" in metadata["modules"][module_name]["memory"]["functions"]["operator_functions"][0][ "function_name" ] ) assert os.path.exists(os.path.join(extract_dir, "codegen", "host", "src", "add_lib0.c")) assert os.path.exists(os.path.join(extract_dir, "codegen", "host", "src", "add_lib1.c")) assert should_generate_interface == os.path.exists( os.path.join(extract_dir, "codegen", "host", "include", "tvmgen_add.h") ) if executor.name == "graph": validate_graph_json(extract_dir, factory) with open(os.path.join(extract_dir, "src", f"{module_name}.relay")) as relay_f: assert relay_f.read() == str(relay_mod) with open(os.path.join(extract_dir, "parameters", "add.params"), "rb") as params_f: params = tvm.relay.load_param_dict(params_f.read()) if json_constants_size_bytes != 0: assert "p0" in params else: assert len(params) == 0 @tvm.testing.requires_micro def test_export_model_library_format_llvm(): with utils.TempDirectory.set_keep_for_debug(True): target = tvm.target.target.micro("host") assert str(target)[:2] == "c " target = tvm.target.Target("llvm " + str(target)[2:]) with tvm.transform.PassContext(opt_level=3): relay_mod = tvm.parser.fromtext( """ #[version = "0.0.5"] def @main(%a : Tensor[(1, 2), uint8], %b : Tensor[(1, 2), float32], %c : Tensor[(1, 2), float32]) { %0 = cast(%a, dtype="float32") + %b * %c; %0 }""" ) factory = tvm.relay.build( relay_mod, target, runtime=Runtime("crt", {"system-lib": True}), mod_name="add", params={"c": np.array([[2.0, 4.0]], dtype="float32")}, ) temp_dir = utils.tempdir() mlf_tar_path = temp_dir.relpath("lib.tar") micro.export_model_library_format(factory, mlf_tar_path) tf = tarfile.open(mlf_tar_path) extract_dir = temp_dir.relpath("extract") os.mkdir(extract_dir) tf.extractall(extract_dir) with open(os.path.join(extract_dir, "metadata.json")) as json_f: metadata = json.load(json_f) module_name = factory.libmod_name assert metadata["version"] == _GENERATED_VERSION assert metadata["modules"][module_name]["model_name"] == "add" export_datetime = datetime.datetime.strptime( metadata["modules"][module_name]["export_datetime"], "%Y-%m-%d %H:%M:%SZ" ) assert (datetime.datetime.now() - export_datetime) < datetime.timedelta(seconds=60 * 5) assert metadata["modules"][module_name]["target"] == [str(target)] assert metadata["modules"][module_name]["memory"]["sids"] == [ {"storage_id": 0, "size_bytes": 2, "input_binding": "a"}, {"storage_id": 1, "size_bytes": 8, "input_binding": "b"}, {"storage_id": 2, "size_bytes": 8, "input_binding": "p0"}, {"storage_id": 3, "size_bytes": 8}, ] assert metadata["modules"][module_name]["memory"]["functions"]["main"] == [ { "constants_size_bytes": 8, "device": 1, "io_size_bytes": 18, "workspace_size_bytes": 0, } ] assert metadata["modules"][module_name]["memory"]["functions"]["operator_functions"][0][ "workspace" ] == [{"device": 1, "workspace_size_bytes": 0}] assert ( "fused_cast_multiply_add" in metadata["modules"][module_name]["memory"]["functions"]["operator_functions"][0][ "function_name" ] ) assert os.path.exists(os.path.join(extract_dir, "codegen", "host", "lib", "add_lib0.o")) validate_graph_json(extract_dir, factory) with open(os.path.join(extract_dir, "src", f"{module_name}.relay")) as relay_f: assert relay_f.read() == str(relay_mod) with open(os.path.join(extract_dir, "parameters", "add.params"), "rb") as params_f: params = tvm.relay.load_param_dict(params_f.read()) assert "p0" in params @tvm.testing.requires_micro @pytest.mark.parametrize( "executor,runtime", [(Executor("graph"), Runtime("crt", {"system-lib": True})), (Executor("aot"), Runtime("crt"))], ) def test_export_model_library_format_workspace(executor, runtime): target = tvm.target.target.micro("host") with tvm.transform.PassContext(opt_level=3, config={"tir.disable_vectorize": True}): relay_mod = tvm.parser.fromtext( """ #[version = "0.0.5"] def @main(%p0: Tensor[(1, 56, 56, 128), int16], %p1: Tensor[(3, 3, 128, 1), int16], %p2: Tensor[(1, 1, 1, 128), int32]){ %0 = nn.conv2d(%p0, %p1, padding=[1, 1, 1, 1], groups=128, channels=128, kernel_size=[3, 3], data_layout="NHWC", kernel_layout="HWOI", out_dtype="int32") /* ty=Tensor[(1, 56, 56, 128), int32] */; %1 = add(%0, %p2) /* ty=Tensor[(1, 56, 56, 128), int32] */; %2 = fixed_point_multiply(%1, multiplier=2080045879, shift=-4) /* ty=Tensor[(1, 56, 56, 128), int32] */; %3 = clip(%2, a_min=0f, a_max=255f) /* ty=Tensor[(1, 56, 56, 128), int32] */; cast(%3, dtype="uint8") /* ty=Tensor[(1, 56, 56, 128), uint8] */ } """ ) factory = tvm.relay.build( relay_mod, target, executor=executor, runtime=runtime, mod_name="qnn_conv2d", ) temp_dir = utils.tempdir() mlf_tar_path = temp_dir.relpath("lib.tar") micro.export_model_library_format(factory, mlf_tar_path) tf = tarfile.open(mlf_tar_path) extract_dir = temp_dir.relpath("extract") os.mkdir(extract_dir) tf.extractall(extract_dir) with open(os.path.join(extract_dir, "metadata.json")) as json_f: metadata = json.load(json_f) module_name = factory.libmod_name assert metadata["version"] == _GENERATED_VERSION assert metadata["modules"][module_name]["model_name"] == "qnn_conv2d" export_datetime = datetime.datetime.strptime( metadata["modules"][module_name]["export_datetime"], "%Y-%m-%d %H:%M:%SZ" ) assert (datetime.datetime.now() - export_datetime) < datetime.timedelta(seconds=60 * 5) assert metadata["modules"][module_name]["target"] == [str(target)] assert metadata["modules"][module_name]["memory"]["functions"]["main"] == [ { "constants_size_bytes": 0, "device": 1, "io_size_bytes": 1207040, "workspace_size_bytes": 2466816, } ] assert metadata["modules"][module_name]["memory"]["functions"]["operator_functions"][0][ "workspace" ] == [{"device": 1, "workspace_size_bytes": 2466816}] assert ( "fused_nn_conv2d_add_fixed_point_multiply_clip_cast" in metadata["modules"][module_name]["memory"]["functions"]["operator_functions"][0][ "function_name" ] ) @tvm.testing.requires_micro def test_export_non_dso_exportable(): module = tvm.support.FrontendTestModule() temp_dir = utils.tempdir() with pytest.raises(micro.UnsupportedInModelLibraryFormatError) as exc: model_library_format._populate_codegen_dir([module], temp_dir.relpath("codegen")) assert str(exc.exception) == ( "Don't know how to export non-c or non-llvm modules; found: ffi_testing" ) @tvm.testing.requires_micro def test_export_byoc_c_module(): """Test BYOC flow when it produces DSO-exportable modules. NOTE the general BYOC flow is not fully supported by Model Library Format right now. """ x = tvm.relay.var("x", shape=(10, 10)) w0 = tvm.relay.var("w0", shape=(10, 10)) w1 = tvm.relay.var("w1", shape=(10, 10)) w2 = tvm.relay.var("w2", shape=(10, 10)) w3 = tvm.relay.var("w3", shape=(10, 10)) w4 = tvm.relay.var("w4", shape=(10, 10)) w5 = tvm.relay.var("w5", shape=(10, 10)) w6 = tvm.relay.var("w6", shape=(10, 10)) w7 = tvm.relay.var("w7", shape=(10, 10)) # C compiler z0 = tvm.relay.add(x, w0) p0 = tvm.relay.subtract(z0, w1) q0 = tvm.relay.multiply(p0, w2) z1 = tvm.relay.add(x, w3) p1 = tvm.relay.subtract(z1, w4) q1 = tvm.relay.multiply(p1, w5) # Other parts on TVM z2 = tvm.relay.add(x, w6) q2 = tvm.relay.subtract(z2, w7) r = tvm.relay.concatenate((q0, q1, q2), axis=0) f = tvm.relay.Function([x, w0, w1, w2, w3, w4, w5, w6, w7], r) mod = tvm.IRModule() ann = byoc.CcompilerAnnotator() mod["main"] = ann.visit(f) mod = tvm.relay.transform.PartitionGraph("mod_name")(mod) mod = tvm.relay.transform.InferType()(mod) with tvm.transform.PassContext(opt_level=3, config={"tir.disable_vectorize": True}): factory = tvm.relay.build(mod, tvm.target.target.micro("host"), runtime=Runtime("crt")) temp_dir = utils.tempdir() mlf_tar_path = temp_dir.relpath("lib.tar") micro.export_model_library_format(factory, mlf_tar_path) with tarfile.open(mlf_tar_path, "r:*") as tf: tar_members = [ti.name for ti in tf.getmembers()] print("tar members", tar_members) assert "./metadata.json" in tar_members with tf.extractfile("./metadata.json") as f: metadata = json.load(f) main_md = metadata["modules"][factory.libmod_name]["memory"]["functions"]["main"] if platform.architecture()[0] == "64bit": assert main_md == [ { "constants_size_bytes": 0, "device": 1, "io_size_bytes": 4800, "workspace_size_bytes": 1200, } ] else: assert main_md == [ { "constants_size_bytes": 0, "device": 1, "io_size_bytes": 4800, "workspace_size_bytes": 1200, } ] @tvm.testing.requires_micro def test_multiple_relay_modules_same_module_name(): mod = get_conv2d_relay_module() executor = Executor("graph") runtime = Runtime("crt") target = tvm.target.target.micro("host") with tvm.transform.PassContext(opt_level=3, config={"tir.disable_vectorize": True}): factory1 = tvm.relay.build(mod, target, runtime=runtime, executor=executor, mod_name="mod") factory2 = tvm.relay.build(mod, target, runtime=runtime, executor=executor, mod_name="mod") temp_dir = utils.tempdir() mlf_tar_path = temp_dir.relpath("lib.tar") with pytest.raises(AssertionError, match="Multiple modules should have unique names"): micro.export_model_library_format([factory1, factory2], mlf_tar_path) @tvm.testing.requires_micro def test_multiple_relay_modules_graph(): mod = get_conv2d_relay_module() executor = Executor("graph") runtime = Runtime("crt") target = tvm.target.target.micro("host") with tvm.transform.PassContext(opt_level=3, config={"tir.disable_vectorize": True}): factory1 = tvm.relay.build(mod, target, runtime=runtime, executor=executor, mod_name="mod1") factory2 = tvm.relay.build(mod, target, runtime=runtime, executor=executor, mod_name="mod2") temp_dir = utils.tempdir() mlf_tar_path = temp_dir.relpath("lib.tar") micro.export_model_library_format([factory1, factory2], mlf_tar_path) with tarfile.open(mlf_tar_path, "r:*") as tf: tar_members = [ti.name for ti in tf.getmembers()] print("tar members", tar_members) assert "./metadata.json" in tar_members assert "./codegen/host/src/mod1_lib0.c" in tar_members assert "./codegen/host/src/mod2_lib0.c" in tar_members with tf.extractfile("./metadata.json") as f: metadata = json.load(f) mod2_main_md = metadata["modules"]["mod2"]["memory"]["functions"]["main"] assert mod2_main_md == [ { "constants_size_bytes": 0, "device": 1, "io_size_bytes": 143960, "workspace_size_bytes": 158088, } ] assert metadata["modules"]["mod1"]["model_name"] == "mod1" assert metadata["modules"]["mod2"]["model_name"] == "mod2" @tvm.testing.requires_micro def test_multiple_relay_modules_c(): mod = get_conv2d_relay_module() executor = Executor("aot", {"unpacked-api": True, "interface-api": "c"}) runtime = Runtime("crt") target = tvm.target.target.micro("host") with tvm.transform.PassContext(opt_level=3, config={"tir.disable_vectorize": True}): factory1 = tvm.relay.build(mod, target, runtime=runtime, executor=executor, mod_name="mod1") factory2 = tvm.relay.build(mod, target, runtime=runtime, executor=executor, mod_name="mod2") temp_dir = utils.tempdir() mlf_tar_path = temp_dir.relpath("lib.tar") micro.export_model_library_format([factory1, factory2], mlf_tar_path) tf = tarfile.open(mlf_tar_path) extract_dir = temp_dir.relpath("extract") os.mkdir(extract_dir) tf.extractall(extract_dir) assert os.path.exists(os.path.join(extract_dir, "codegen", "host", "src", "mod1_lib0.c")) assert os.path.exists(os.path.join(extract_dir, "codegen", "host", "src", "mod1_lib1.c")) assert os.path.exists(os.path.join(extract_dir, "codegen", "host", "src", "mod2_lib0.c")) assert os.path.exists(os.path.join(extract_dir, "codegen", "host", "src", "mod2_lib1.c")) assert os.path.exists(os.path.join(extract_dir, "codegen", "host", "include", "tvmgen_mod1.h")) assert os.path.exists(os.path.join(extract_dir, "codegen", "host", "include", "tvmgen_mod2.h")) # check CRT runtime directory assert os.path.exists(os.path.join(extract_dir, "runtime")) @tvm.testing.requires_micro def test_multiple_relay_modules_aot_graph(): mod = get_conv2d_relay_module() executor1 = Executor("graph") executor2 = Executor("aot", {"unpacked-api": True, "interface-api": "c"}) runtime = Runtime("crt") target = tvm.target.target.micro("host") with tvm.transform.PassContext(opt_level=3, config={"tir.disable_vectorize": True}): factory1 = tvm.relay.build( mod, target, runtime=runtime, executor=executor1, mod_name="mod1" ) factory2 = tvm.relay.build( mod, target, runtime=runtime, executor=executor2, mod_name="mod2" ) temp_dir = utils.tempdir() mlf_tar_path = temp_dir.relpath("lib.tar") micro.export_model_library_format([factory1, factory2], mlf_tar_path) tf = tarfile.open(mlf_tar_path) extract_dir = temp_dir.relpath("extract") os.mkdir(extract_dir) tf.extractall(extract_dir) assert os.path.exists(os.path.join(extract_dir, "codegen", "host", "src", "mod1_lib0.c")) assert os.path.exists(os.path.join(extract_dir, "codegen", "host", "src", "mod1_lib1.c")) assert os.path.exists(os.path.join(extract_dir, "codegen", "host", "src", "mod1_lib2.c")) assert os.path.exists(os.path.join(extract_dir, "codegen", "host", "src", "mod2_lib0.c")) assert os.path.exists(os.path.join(extract_dir, "codegen", "host", "src", "mod2_lib1.c")) assert os.path.exists(os.path.join(extract_dir, "codegen", "host", "include", "tvmgen_mod2.h")) with open(os.path.join(extract_dir, "metadata.json")) as f: metadata = json.load(f) assert metadata["modules"]["mod1"]["executors"] == ["graph"] assert metadata["modules"]["mod2"]["executors"] == ["aot"] assert metadata["version"] == _GENERATED_VERSION if __name__ == "__main__": sys.exit(pytest.main([__file__] + sys.argv[1:]))
https://github.com/zk-ml/tachikoma
tests/python/unittest/test_micro_project_api.py
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. import collections import io import json import sys import unittest from unittest import mock import pytest import tvm import tvm.testing # Implementing as a fixture so that the tvm.micro import doesn't occur # until fixture setup time. This is necessary for pytest's collection # phase to work when USE_MICRO=OFF, while still explicitly listing the # tests as skipped. @tvm.testing.fixture def BaseTestHandler(): from tvm.micro import project_api class BaseTestHandler_Impl(project_api.server.ProjectAPIHandler): DEFAULT_TEST_SERVER_INFO = project_api.server.ServerInfo( platform_name="platform_name", is_template=True, model_library_format_path="./model-library-format-path.sh", project_options=[ project_api.server.ProjectOption( name="foo", optional=["build"], type="bool", help="Option foo" ), project_api.server.ProjectOption( name="bar", required=["generate_project"], type="str", choices=["qux"], help="Option bar", ), ], ) def server_info_query(self, tvm_version): return self.DEFAULT_TEST_SERVER_INFO def generate_project(self, model_library_format_path, crt_path, project_path, options): assert False, "generate_project is not implemented for this test" def build(self, options): assert False, "build is not implemented for this test" def flash(self, options): assert False, "flash is not implemented for this test" def open_transport(self, options): assert False, "open_transport is not implemented for this test" def close_transport(self, options): assert False, "open_transport is not implemented for this test" def read_transport(self, n, timeout_sec): assert False, "read_transport is not implemented for this test" def write_transport(self, data, timeout_sec): assert False, "write_transport is not implemented for this test" return BaseTestHandler_Impl class Transport: def readable(self): return True def writable(self): return True def seekable(self): return False closed = False def __init__(self): self.data = bytearray() self.rpos = 0 self.items = [] def read(self, size=-1): to_read = len(self.data) - self.rpos if size != -1: to_read = min(size, to_read) rpos = self.rpos self.rpos += to_read return self.data[rpos : self.rpos] def write(self, data): self.data.extend(data) class ClientServerFixture: def __init__(self, handler): from tvm.micro import project_api self.handler = handler self.client_to_server = Transport() self.server_to_client = Transport() self.server = project_api.server.ProjectAPIServer( self.client_to_server, self.server_to_client, handler ) self.client = project_api.client.ProjectAPIClient( self.server_to_client, self.client_to_server, testonly_did_write_request=self._process_server_request, ) self.expect_failure = False def _process_server_request(self): assert self.server.serve_one_request() == ( not self.expect_failure ), "Server failed to process request" @tvm.testing.requires_micro def test_server_info_query(BaseTestHandler): fixture = ClientServerFixture(BaseTestHandler()) # Examine reply explicitly because these are the defaults for all derivative test cases. reply = fixture.client.server_info_query(tvm.__version__) assert reply["protocol_version"] == 1 assert reply["platform_name"] == "platform_name" assert reply["is_template"] == True assert reply["model_library_format_path"] == "./model-library-format-path.sh" assert reply["project_options"] == [ { "name": "foo", "choices": None, "default": None, "type": "bool", "required": None, "optional": ["build"], "help": "Option foo", }, { "name": "bar", "choices": ["qux"], "default": None, "type": "str", "required": ["generate_project"], "optional": None, "help": "Option bar", }, ] @tvm.testing.requires_micro def test_server_info_query_wrong_tvm_version(BaseTestHandler): from tvm.micro import project_api def server_info_query(tvm_version): raise project_api.server.UnsupportedTVMVersionError() with mock.patch.object(BaseTestHandler, "server_info_query", side_effect=server_info_query): fixture = ClientServerFixture(BaseTestHandler()) with pytest.raises(project_api.server.UnsupportedTVMVersionError) as exc_info: fixture.client.server_info_query(tvm.__version__) assert "UnsupportedTVMVersionError" in str(exc_info.value) @tvm.testing.requires_micro def test_server_info_query_wrong_protocol_version(BaseTestHandler): from tvm.micro import project_api ServerInfoProtocol = collections.namedtuple( "ServerInfoProtocol", list(project_api.server.ServerInfo._fields) + ["protocol_version"] ) def server_info_query(tvm_version): return ServerInfoProtocol( protocol_version=0, **BaseTestHandler.DEFAULT_TEST_SERVER_INFO._asdict() ) with mock.patch.object(BaseTestHandler, "server_info_query", side_effect=server_info_query): fixture = ClientServerFixture(BaseTestHandler()) with pytest.raises(project_api.client.UnsupportedProtocolVersionError) as exc_info: fixture.client.server_info_query(tvm.__version__) assert "microTVM API Server supports protocol version 0; want 1" in str(exc_info.value) @tvm.testing.requires_micro def test_base_test_handler(BaseTestHandler): """All methods should raise AssertionError on BaseTestHandler.""" fixture = ClientServerFixture(BaseTestHandler()) for method in dir(fixture.handler): if method.startswith("_") or not callable(method) or method == "server_info_query": continue with self.assertThrows(AssertionError) as exc_info: getattr(fixture.client, method)() assert (exc_info.exception) == f"{method} is not implemented for this test" @tvm.testing.requires_micro def test_build(BaseTestHandler): with mock.patch.object(BaseTestHandler, "build", return_value=None) as patch: fixture = ClientServerFixture(BaseTestHandler()) fixture.client.build(options={"bar": "baz"}) fixture.handler.build.assert_called_once_with(options={"bar": "baz"}) @tvm.testing.requires_micro def test_flash(BaseTestHandler): with mock.patch.object(BaseTestHandler, "flash", return_value=None) as patch: fixture = ClientServerFixture(BaseTestHandler()) fixture.client.flash(options={"bar": "baz"}) fixture.handler.flash.assert_called_once_with(options={"bar": "baz"}) @tvm.testing.requires_micro def test_open_transport(BaseTestHandler): from tvm.micro import project_api timeouts = project_api.server.TransportTimeouts( session_start_retry_timeout_sec=1.0, session_start_timeout_sec=2.0, session_established_timeout_sec=3.0, ) with mock.patch.object(BaseTestHandler, "open_transport", return_value=timeouts) as patch: fixture = ClientServerFixture(BaseTestHandler()) assert fixture.client.open_transport(options={"bar": "baz"}) == { "timeouts": dict(timeouts._asdict()) } fixture.handler.open_transport.assert_called_once_with({"bar": "baz"}) @tvm.testing.requires_micro def test_close_transport(BaseTestHandler): with mock.patch.object(BaseTestHandler, "close_transport", return_value=None) as patch: fixture = ClientServerFixture(BaseTestHandler()) fixture.client.close_transport() fixture.handler.close_transport.assert_called_once_with() @tvm.testing.requires_micro def test_read_transport(BaseTestHandler): from tvm.micro import project_api with mock.patch.object(BaseTestHandler, "read_transport", return_value=b"foo\x1b") as patch: fixture = ClientServerFixture(BaseTestHandler()) assert fixture.client.read_transport(128, timeout_sec=5.0) == {"data": b"foo\x1b"} fixture.handler.read_transport.assert_called_with(128, 5.0) fixture.handler.read_transport.side_effect = project_api.server.IoTimeoutError with pytest.raises(project_api.server.IoTimeoutError) as exc_info: fixture.client.read_transport(256, timeout_sec=10.0) fixture.handler.read_transport.assert_called_with(256, 10.0) fixture.handler.read_transport.side_effect = project_api.server.TransportClosedError with pytest.raises(project_api.server.TransportClosedError) as exc_info: fixture.client.read_transport(512, timeout_sec=15.0) fixture.handler.read_transport.assert_called_with(512, 15.0) assert fixture.handler.read_transport.call_count == 3 @tvm.testing.requires_micro def test_write_transport(BaseTestHandler): from tvm.micro import project_api with mock.patch.object(BaseTestHandler, "write_transport", return_value=None) as patch: fixture = ClientServerFixture(BaseTestHandler()) assert fixture.client.write_transport(b"foo", timeout_sec=5.0) is None fixture.handler.write_transport.assert_called_with(b"foo", 5.0) fixture.handler.write_transport.side_effect = project_api.server.IoTimeoutError with pytest.raises(project_api.server.IoTimeoutError) as exc_info: fixture.client.write_transport(b"bar", timeout_sec=10.0) fixture.handler.write_transport.assert_called_with(b"bar", 10.0) fixture.handler.write_transport.side_effect = project_api.server.TransportClosedError with pytest.raises(project_api.server.TransportClosedError) as exc_info: fixture.client.write_transport(b"baz", timeout_sec=15.0) fixture.handler.write_transport.assert_called_with(b"baz", 15.0) assert fixture.handler.write_transport.call_count == 3 class ProjectAPITestError(Exception): """An error raised in test.""" @tvm.testing.requires_micro def test_method_raises_error(BaseTestHandler): from tvm.micro import project_api with mock.patch.object( BaseTestHandler, "close_transport", side_effect=ProjectAPITestError ) as patch: fixture = ClientServerFixture(BaseTestHandler()) with pytest.raises(project_api.server.ServerError) as exc_info: fixture.client.close_transport() fixture.handler.close_transport.assert_called_once_with() assert "ProjectAPITestError" in str(exc_info.value) @tvm.testing.requires_micro def test_method_not_found(BaseTestHandler): from tvm.micro import project_api fixture = ClientServerFixture(BaseTestHandler()) with pytest.raises(project_api.server.JSONRPCError) as exc_info: fixture.client._request_reply("invalid_method", {"bar": None}) assert exc_info.value.code == project_api.server.ErrorCode.METHOD_NOT_FOUND @tvm.testing.requires_micro def test_extra_param(BaseTestHandler): from tvm.micro import project_api fixture = ClientServerFixture(BaseTestHandler()) # test one with has_preprocssing and one without assert hasattr(fixture.server, "_dispatch_build") == False with pytest.raises(project_api.server.JSONRPCError) as exc_info: fixture.client._request_reply("build", {"invalid_param_name": None, "options": {}}) assert exc_info.value.code == project_api.server.ErrorCode.INVALID_PARAMS assert "build: extra parameters: invalid_param_name" in str(exc_info.value) assert hasattr(fixture.server, "_dispatch_open_transport") == True with pytest.raises(project_api.server.JSONRPCError) as exc_info: fixture.client._request_reply("open_transport", {"invalid_param_name": None, "options": {}}) assert exc_info.value.code == project_api.server.ErrorCode.INVALID_PARAMS assert "open_transport: extra parameters: invalid_param_name" in str(exc_info.value) @tvm.testing.requires_micro def test_missing_param(BaseTestHandler): from tvm.micro import project_api fixture = ClientServerFixture(BaseTestHandler()) # test one with has_preprocssing and one without assert hasattr(fixture.server, "_dispatch_build") == False with pytest.raises(project_api.server.JSONRPCError) as exc_info: fixture.client._request_reply("build", {}) assert exc_info.value.code == project_api.server.ErrorCode.INVALID_PARAMS assert "build: parameter options not given" in str(exc_info.value) assert hasattr(fixture.server, "_dispatch_open_transport") == True with pytest.raises(project_api.server.JSONRPCError) as exc_info: fixture.client._request_reply("open_transport", {}) assert exc_info.value.code == project_api.server.ErrorCode.INVALID_PARAMS assert "open_transport: parameter options not given" in str(exc_info.value) @tvm.testing.requires_micro def test_incorrect_param_type(BaseTestHandler): from tvm.micro import project_api fixture = ClientServerFixture(BaseTestHandler()) # The error message given at the JSON-RPC server level doesn't make sense when preprocessing is # used. Only test without preprocessing here. assert hasattr(fixture.server, "_dispatch_build") == False with pytest.raises(project_api.server.JSONRPCError) as exc_info: fixture.client._request_reply("build", {"options": None}) assert exc_info.value.code == project_api.server.ErrorCode.INVALID_PARAMS assert "build: parameter options: want <class 'dict'>, got <class 'NoneType'>" in str( exc_info.value ) @tvm.testing.requires_micro def test_invalid_request(BaseTestHandler): from tvm.micro import project_api fixture = ClientServerFixture(BaseTestHandler()) # Invalid JSON does not get a reply. fixture.client_to_server.write(b"foobar\n") assert fixture.server.serve_one_request() == False assert fixture.server_to_client.read() == b"" # EOF causes a clean return assert fixture.server.serve_one_request() == False assert fixture.server_to_client.read() == b"" def _request_reply(request): fixture.client_to_server.write(request + b"\n") assert fixture.server.serve_one_request() == False return json.loads(fixture.server_to_client.read()) # Parseable JSON with the wrong schema gets a reply. assert _request_reply(b"1") == { "error": { "code": project_api.server.ErrorCode.INVALID_REQUEST, "data": None, "message": "request: want dict; got 1", }, "id": None, "jsonrpc": "2.0", } # Incorrect JSON-RPC spec version. assert _request_reply(b'{"jsonrpc": 1.0}') == { "error": { "code": project_api.server.ErrorCode.INVALID_REQUEST, "data": None, "message": 'request["jsonrpc"]: want "2.0"; got 1.0', }, "id": None, "jsonrpc": "2.0", } # Method not a str assert _request_reply(b'{"jsonrpc": "2.0", "method": 123}') == { "error": { "code": project_api.server.ErrorCode.INVALID_REQUEST, "data": None, "message": 'request["method"]: want str; got 123', }, "id": None, "jsonrpc": "2.0", } # Method name has invalid characters assert _request_reply(b'{"jsonrpc": "2.0", "method": "bar!"}') == { "error": { "code": project_api.server.ErrorCode.INVALID_REQUEST, "data": None, "message": "request[\"method\"]: should match regex ^[a-zA-Z0-9_]+$; got 'bar!'", }, "id": None, "jsonrpc": "2.0", } # params not a dict assert _request_reply(b'{"jsonrpc": "2.0", "method": "bar", "params": 123}') == { "error": { "code": project_api.server.ErrorCode.INVALID_REQUEST, "data": None, "message": "request[\"params\"]: want dict; got <class 'int'>", }, "id": None, "jsonrpc": "2.0", } # id not valid assert _request_reply(b'{"jsonrpc": "2.0", "method": "bar", "params": {}, "id": {}}') == { "error": { "code": project_api.server.ErrorCode.INVALID_REQUEST, "data": None, "message": 'request["id"]: want str, number, null; got {}', }, "id": None, "jsonrpc": "2.0", } @tvm.testing.requires_micro def test_default_project_options(): from tvm.micro import project_api default_options = project_api.server.default_project_options() names = [] for option in default_options: names.append(option.name) if option.name == "verbose": assert "generate_project" in option.optional if option.name in ["project_type", "board"]: assert "generate_project" in option.required if option.name == "warning_as_error": assert "generate_project" in option.optional for name in ["verbose", "project_type", "board", "cmsis_path", "warning_as_error"]: assert name in names @tvm.testing.requires_micro def test_modified_project_options(): from tvm.micro import project_api modified_options = project_api.server.default_project_options( verbose={"optional": ["flash"], "required": ["build"]}, board={"choices": ["board1", "board2"]}, ) for option in modified_options: if option.name == "verbose": assert option.optional == ["flash"] assert option.required == ["build"] if option.name == "board": assert option.choices == ["board1", "board2"] if __name__ == "__main__": tvm.testing.main()
https://github.com/zk-ml/tachikoma
tests/python/unittest/test_micro_transport.py
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. """Tests for common micro transports.""" import logging import sys import unittest import pytest import tvm.testing # Implementing as a fixture so that the tvm.micro import doesn't occur # until fixture setup time. This is necessary for pytest's collection # phase to work when USE_MICRO=OFF, while still explicitly listing the # tests as skipped. @tvm.testing.fixture def transport(): import tvm.micro class MockTransport_Impl(tvm.micro.transport.Transport): def __init__(self): self.exc = None self.to_return = None def _raise_or_return(self): if self.exc is not None: to_raise = self.exc self.exc = None raise to_raise elif self.to_return is not None: to_return = self.to_return self.to_return = None return to_return else: assert False, "should not get here" def open(self): pass def close(self): pass def timeouts(self): raise NotImplementedError() def read(self, n, timeout_sec): return self._raise_or_return() def write(self, data, timeout_sec): return self._raise_or_return() return MockTransport_Impl() @tvm.testing.fixture def transport_logger(transport): logger = logging.getLogger("transport_logger_test") return tvm.micro.transport.TransportLogger("foo", transport, logger=logger) @tvm.testing.fixture def get_latest_log(caplog): def inner(): return caplog.records[-1].getMessage() with caplog.at_level(logging.INFO, "transport_logger_test"): yield inner @tvm.testing.requires_micro def test_open(transport_logger, get_latest_log): transport_logger.open() assert get_latest_log() == "foo: opening transport" @tvm.testing.requires_micro def test_close(transport_logger, get_latest_log): transport_logger.close() assert get_latest_log() == "foo: closing transport" @tvm.testing.requires_micro def test_read_normal(transport, transport_logger, get_latest_log): transport.to_return = b"data" transport_logger.read(23, 3.0) assert get_latest_log() == ( "foo: read { 3.00s} 23 B -> [ 4 B]: 64 61 74 61" " data" ) @tvm.testing.requires_micro def test_read_multiline(transport, transport_logger, get_latest_log): transport.to_return = b"data" * 6 transport_logger.read(23, 3.0) assert get_latest_log() == ( "foo: read { 3.00s} 23 B -> [ 24 B]:\n" "0000 64 61 74 61 64 61 74 61 64 61 74 61 64 61 74 61 datadatadatadata\n" "0010 64 61 74 61 64 61 74 61 datadata" ) @tvm.testing.requires_micro def test_read_no_timeout_prints(transport, transport_logger, get_latest_log): transport.to_return = b"data" transport_logger.read(15, None) assert get_latest_log() == ( "foo: read { None } 15 B -> [ 4 B]: 64 61 74 61" " data" ) @tvm.testing.requires_micro def test_read_io_timeout(transport, transport_logger, get_latest_log): # IoTimeoutError includes the timeout value. transport.exc = tvm.micro.transport.IoTimeoutError() with pytest.raises(tvm.micro.transport.IoTimeoutError): transport_logger.read(23, 0.0) assert get_latest_log() == ("foo: read { 0.00s} 23 B -> [IoTimeoutError 0.00s]") @tvm.testing.requires_micro def test_read_other_exception(transport, transport_logger, get_latest_log): # Other exceptions are logged by name. transport.exc = tvm.micro.transport.TransportClosedError() with pytest.raises(tvm.micro.transport.TransportClosedError): transport_logger.read(8, 0.0) assert get_latest_log() == ("foo: read { 0.00s} 8 B -> [err: TransportClosedError]") @tvm.testing.requires_micro def test_read_keyboard_interrupt(transport, transport_logger, get_latest_log): # KeyboardInterrupt produces no log record. transport.exc = KeyboardInterrupt() with pytest.raises(KeyboardInterrupt): transport_logger.read(8, 0.0) with pytest.raises(IndexError): get_latest_log() @tvm.testing.requires_micro def test_write_normal(transport, transport_logger, get_latest_log): transport.to_return = 3 transport_logger.write(b"data", 3.0) assert get_latest_log() == ( "foo: write { 3.00s} <- [ 4 B]: 64 61 74 61" " data" ) @tvm.testing.requires_micro def test_write_multiline(transport, transport_logger, get_latest_log): # Normal log, multi-line data written. transport.to_return = 20 transport_logger.write(b"data" * 6, 3.0) assert get_latest_log() == ( "foo: write { 3.00s} <- [ 24 B]:\n" "0000 64 61 74 61 64 61 74 61 64 61 74 61 64 61 74 61 datadatadatadata\n" "0010 64 61 74 61 64 61 74 61 datadata" ) @tvm.testing.requires_micro def test_write_no_timeout_prints(transport, transport_logger, get_latest_log): transport.to_return = 3 transport_logger.write(b"data", None) assert get_latest_log() == ( "foo: write { None } <- [ 4 B]: 64 61 74 61" " data" ) @tvm.testing.requires_micro def test_write_io_timeout(transport, transport_logger, get_latest_log): # IoTimeoutError includes the timeout value. transport.exc = tvm.micro.transport.IoTimeoutError() with pytest.raises(tvm.micro.transport.IoTimeoutError): transport_logger.write(b"data", 0.0) assert get_latest_log() == ("foo: write { 0.00s} <- [ 4 B]: [IoTimeoutError 0.00s]") @tvm.testing.requires_micro def test_write_other_exception(transport, transport_logger, get_latest_log): # Other exceptions are logged by name. transport.exc = tvm.micro.transport.TransportClosedError() with pytest.raises(tvm.micro.transport.TransportClosedError): transport_logger.write(b"data", 0.0) assert get_latest_log() == ("foo: write { 0.00s} <- [ 4 B]: [err: TransportClosedError]") @tvm.testing.requires_micro def test_write_keyboard_interrupt(transport, transport_logger, get_latest_log): # KeyboardInterrupt produces no log record. transport.exc = KeyboardInterrupt() with pytest.raises(KeyboardInterrupt): transport_logger.write(b"data", 0.0) with pytest.raises(IndexError): get_latest_log() if __name__ == "__main__": tvm.testing.main()
https://github.com/zk-ml/tachikoma
tests/python/unittest/test_node_reflection.py
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. import tvm import tvm.testing import sys import pytest from tvm import te import numpy as np def test_const_saveload_json(): # save load json x = tvm.tir.const(1, "int32") y = tvm.tir.const(10, "int32") z = x + y z = z + z json_str = tvm.ir.save_json(z) zz = tvm.ir.load_json(json_str) tvm.ir.assert_structural_equal(zz, z, map_free_vars=True) def _test_infinity_value(value, dtype): x = tvm.tir.const(value, dtype) json_str = tvm.ir.save_json(x) tvm.ir.assert_structural_equal(x, tvm.ir.load_json(json_str)) def test_infinity_value(): _test_infinity_value(float("inf"), "float64") _test_infinity_value(float("-inf"), "float64") _test_infinity_value(float("inf"), "float32") _test_infinity_value(float("-inf"), "float32") def _test_minmax_value(value): json_str = tvm.ir.save_json(value) tvm.ir.assert_structural_equal(value, tvm.ir.load_json(json_str)) def test_minmax_value(): _test_minmax_value(tvm.tir.min_value("float32")) _test_minmax_value(tvm.tir.max_value("float32")) def test_make_smap(): # save load json x = tvm.tir.const(1, "int32") y = tvm.tir.const(10, "int32") z = tvm.tir.Add(x, y) smap = tvm.runtime.convert({"z": z, "x": x}) json_str = tvm.ir.save_json(tvm.runtime.convert([smap])) arr = tvm.ir.load_json(json_str) assert len(arr) == 1 assert arr[0]["z"].a == arr[0]["x"] tvm.ir.assert_structural_equal(arr, [smap], map_free_vars=True) def test_make_node(): x = tvm.ir.make_node("IntImm", dtype="int32", value=10, span=None) assert isinstance(x, tvm.tir.IntImm) assert x.value == 10 A = te.placeholder((10,), name="A") AA = tvm.ir.make_node( "Tensor", shape=A.shape, dtype=A.dtype, op=A.op, value_index=A.value_index ) assert AA.op == A.op assert AA.value_index == A.value_index y = tvm.ir.make_node("IntImm", dtype=tvm.runtime.String("int32"), value=10, span=None) def test_make_sum(): A = te.placeholder((2, 10), name="A") k = te.reduce_axis((0, 10), "k") B = te.compute((2,), lambda i: te.sum(A[i, k], axis=k), name="B") json_str = tvm.ir.save_json(B) BB = tvm.ir.load_json(json_str) assert B.op.body[0].combiner is not None assert BB.op.body[0].combiner is not None def test_env_func(): @tvm.register_func("test.env_func") def test(x): return x + 1 f = tvm.get_global_func("test.env_func") x = tvm.ir.EnvFunc.get("test.env_func") assert x.name == "test.env_func" json_str = tvm.ir.save_json([x]) y = tvm.ir.load_json(json_str)[0] assert y.name == x.name assert y(1) == 2 assert y.func(1) == 2 x = tvm.ir.make_node("attrs.TestAttrs", name="xx", padding=(3, 4), func=y) assert x.name == "xx" assert x.padding[0].value == 3 assert x.padding[1].value == 4 assert x.axis == 10 x = tvm.ir.load_json(tvm.ir.save_json(x)) assert isinstance(x.func, tvm.ir.EnvFunc) assert x.func(10) == 11 def test_string(): # non printable str, need to store by b64 s1 = tvm.runtime.String("xy\x01z") s2 = tvm.ir.load_json(tvm.ir.save_json(s1)) tvm.ir.assert_structural_equal(s1, s2) # printable str, need to store by repr_str s1 = tvm.runtime.String("xyz") s2 = tvm.ir.load_json(tvm.ir.save_json(s1)) tvm.ir.assert_structural_equal(s1, s2) def test_pass_config(): cfg = tvm.transform.PassContext( opt_level=1, config={ "tir.UnrollLoop": { "auto_max_step": 10, } }, ) cfg.opt_level == 1 assert cfg.config["tir.UnrollLoop"].auto_max_step == 10 # default option assert cfg.config["tir.UnrollLoop"].explicit_unroll == True # schema checking for specific config key with pytest.raises(AttributeError): cfg = tvm.transform.PassContext(config={"tir.UnrollLoop": {"invalid": 1}}) # schema check for un-registered config with pytest.raises(AttributeError): cfg = tvm.transform.PassContext(config={"inavlid-opt": True}) # schema check for wrong type with pytest.raises(AttributeError): cfg = tvm.transform.PassContext(config={"tir.UnrollLoop": 1}) def test_dict(): x = tvm.tir.const(1) # a class that has Python-defined methods # instances should see the full class dict assert set(dir(x.__class__)) <= set(dir(x)) def test_ndarray(): dev = tvm.cpu(0) tvm_arr = tvm.nd.array(np.random.rand(4), device=dev) tvm_arr2 = tvm.ir.load_json(tvm.ir.save_json(tvm_arr)) tvm.ir.assert_structural_equal(tvm_arr, tvm_arr2) np.testing.assert_array_equal(tvm_arr.numpy(), tvm_arr2.numpy()) def test_ndarray_dict(): dev = tvm.cpu(0) m1 = { "key1": tvm.nd.array(np.random.rand(4), device=dev), "key2": tvm.nd.array(np.random.rand(4), device=dev), } m2 = tvm.ir.load_json(tvm.ir.save_json(m1)) tvm.ir.assert_structural_equal(m1, m2) def test_alloc_const(): dev = tvm.cpu(0) dtype = "float32" shape = (16,) buf = tvm.tir.decl_buffer(shape, dtype) np_data = np.random.rand(*shape).astype(dtype) data = tvm.nd.array(np_data, device=dev) body = tvm.tir.Evaluate(0) alloc_const = tvm.tir.AllocateConst(buf.data, dtype, shape, data, body) alloc_const2 = tvm.ir.load_json(tvm.ir.save_json(alloc_const)) tvm.ir.assert_structural_equal(alloc_const, alloc_const2) np.testing.assert_array_equal(np_data, alloc_const2.data.numpy()) if __name__ == "__main__": tvm.testing.main()
https://github.com/zk-ml/tachikoma
tests/python/unittest/test_object_path.py
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. import pytest import tvm from tvm.runtime import object_path from tvm.runtime.object_path import ObjectPath def test_root_path(): root = ObjectPath.root() assert isinstance(root, object_path.RootPath) assert str(root) == "<root>" assert len(root) == 1 assert root == ObjectPath.root() assert root.parent is None def test_path_attr(): path = ObjectPath.root().attr("foo") assert isinstance(path, object_path.AttributeAccessPath) assert str(path) == "<root>.foo" assert len(path) == 2 assert path.parent == ObjectPath.root() def test_path_attr_unknown(): path = ObjectPath.root().attr(None) assert isinstance(path, object_path.UnknownAttributeAccessPath) assert str(path) == "<root>.<unknown attribute>" assert len(path) == 2 assert path.parent == ObjectPath.root() def test_path_array_index(): path = ObjectPath.root().array_index(2) assert isinstance(path, object_path.ArrayIndexPath) assert str(path) == "<root>[2]" assert len(path) == 2 assert path.parent == ObjectPath.root() def test_path_missing_array_element(): path = ObjectPath.root().missing_array_element(2) assert isinstance(path, object_path.MissingArrayElementPath) assert str(path) == "<root>[<missing element #2>]" assert len(path) == 2 assert path.parent == ObjectPath.root() def test_path_map_value(): path = ObjectPath.root().map_value("foo") assert isinstance(path, object_path.MapValuePath) assert str(path) == '<root>["foo"]' assert len(path) == 2 assert path.parent == ObjectPath.root() def test_path_missing_map_entry(): path = ObjectPath.root().missing_map_entry() assert isinstance(path, object_path.MissingMapEntryPath) assert str(path) == "<root>[<missing entry>]" assert len(path) == 2 assert path.parent == ObjectPath.root() @pytest.mark.parametrize( "a, b, expected", [ (ObjectPath.root(), ObjectPath.root(), True), (ObjectPath.root(), ObjectPath.root().attr("foo"), True), (ObjectPath.root().attr("foo"), ObjectPath.root(), False), (ObjectPath.root().attr("foo"), ObjectPath.root().attr("foo"), True), (ObjectPath.root().attr("bar"), ObjectPath.root().attr("foo"), False), (ObjectPath.root().attr("foo"), ObjectPath.root().attr("foo").array_index(2), True), (ObjectPath.root().attr("foo").array_index(2), ObjectPath.root().attr("foo"), False), (ObjectPath.root().attr("foo"), ObjectPath.root().attr("bar").array_index(2), False), ], ) def test_path_is_prefix_of(a, b, expected): assert a.is_prefix_of(b) == expected paths_for_equality_test = [ ObjectPath.root(), ObjectPath.root().attr("foo"), ObjectPath.root().attr("bar"), ObjectPath.root().array_index(3), ObjectPath.root().array_index(4), ObjectPath.root().missing_array_element(3), ObjectPath.root().missing_array_element(4), ObjectPath.root().map_value("foo"), ObjectPath.root().map_value("bar"), ObjectPath.root().missing_map_entry(), ObjectPath.root().attr("foo").missing_map_entry(), ] def make_test_params_for_eq_test(): return [ pytest.param(idx, path, id="path{}".format(idx)) for idx, path in enumerate(paths_for_equality_test) ] @pytest.mark.parametrize("a_idx, a_path", make_test_params_for_eq_test()) @pytest.mark.parametrize("b_idx, b_path", make_test_params_for_eq_test()) def test_path_equal(a_idx, a_path, b_idx, b_path): expected = a_idx == b_idx result = a_path == b_path assert result == expected def test_path_get_prefix(): p1 = ObjectPath.root() p2 = p1.attr("foo") p3 = p2.array_index(5) assert p3.parent == p2 assert p2.parent == p1 assert p1.parent is None assert p2.get_prefix(1) == p1 assert p3.get_prefix(1) == p1 assert p3.get_prefix(2) == p2 assert p3.get_prefix(3) == p3 with pytest.raises(IndexError) as e: p3.get_prefix(0) assert "Prefix length must be at least 1" in str(e.value) with pytest.raises(IndexError) as e: p3.get_prefix(4) assert "Attempted to get a prefix longer than the path itself" in str(e.value)
https://github.com/zk-ml/tachikoma
tests/python/unittest/test_roofline.py
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. import csv import json import os import platform from io import StringIO import numpy as np import pytest import tvm.testing import tvm.utils from tvm import relay, rpc from tvm.contrib import utils from tvm.contrib.debugger import debug_executor from tvm.relay.testing import mlp from tvm.runtime import profiler_vm from tvm.runtime.profiling import Report from tvm.script import tir as T @tvm.testing.requires_llvm @pytest.mark.parametrize("dtype", ["float32", "int8", "int32"]) def test_estimate_peak_flops_cpu(dtype): server = rpc.Server(key="roofline_flops_cpu") remote = rpc.connect("127.0.0.1", server.port, key="roofline_flops_cpu") target = tvm.target.Target("llvm -mattr=+fma,+avx2") dev = remote.device(str(target)) # This test uses vectorized instructions so we need a target that supports them flops = tvm.utils.roofline.x86.estimate_peak_fma_vector_flops(target, dev, remote, "float32") # Assume we can achieve 1 GFLOP/s per thread, which is 1 FLOP per cycle on a 1GHz cpu. assert ( flops > 10**9 and flops < 10**14 ), f"FLOP/s should be between 10^9 and 10^14, but it is {flops}" @tvm.testing.requires_cuda def test_estimate_peak_flops_gpu(): server = rpc.Server(key="roofline_flops_gpu") remote = rpc.connect("127.0.0.1", server.port, key="roofline_flops_gpu") target = tvm.target.Target("cuda") dev = remote.device(str(target)) # This test uses vectorized instructions so we need a target that supports them flops = tvm.utils.roofline.cuda.estimate_peak_flops_tensorcore(target, dev, remote) # should be able to hit a TFLOP/s with tensor cores assert ( flops > 10**12 and flops < 10**14 ), f"FLOP/s should be between 10^12 and 10^14, but it is {flops}" @tvm.testing.skip_if_32bit(reason="Cannot allocate enough memory on i386") @tvm.testing.requires_llvm def test_estimate_peak_bandwidth_cpu(): server = rpc.Server(key="roofline_bandwidth_cpu") remote = rpc.connect("127.0.0.1", server.port, key="roofline_bandwidth_cpu") target = tvm.target.Target("llvm -mattr=+fma,+avx2") dev = remote.device(str(target)) # This test uses vectorized instructions so we need a target that supports them bandwidth = tvm.utils.roofline.x86.estimate_peak_bandwidth_dram(target, dev, remote) # Assume we can achieve 1 GB/s. DDR2 should transfer somewhere around 6 # GB/s, so this should leave enough wiggle room. assert ( bandwidth > 10**9 and bandwidth < 10**12 ), f"Bandwidth should be between 10^9 and 10^12, but it is {bandwidth}" @tvm.testing.requires_cuda def test_estimate_peak_bandwidth_gpu(): server = rpc.Server(key="roofline_bandwidth_gpu") remote = rpc.connect("127.0.0.1", server.port, key="roofline_bandwidth_gpu") target = tvm.target.Target("cuda") dev = remote.device(str(target)) # This test uses vectorized instructions so we need a target that supports them bandwidth = tvm.utils.roofline.cuda.estimate_peak_bandwidth_global_mem(target, dev, remote) # should be able to hit a 100 GB/s on a GPU. GTX 280 hits 140 GB/s and # it is really old. assert ( bandwidth > 10**11 and bandwidth < 10**13 ), f"Bandwidth should be between 10^9 and 10^12, but it is {bandwidth}" @tvm.testing.skip_if_32bit(reason="Cannot allocate enough memory on i386") @tvm.testing.parametrize_targets("llvm -mattr=+fma,+avx2", "cuda") def test_roofline_analysis(target, dev): a = relay.var("a", relay.TensorType((512, 512), "float32")) b = relay.var("b", relay.TensorType((512, 512), "float32")) c = relay.nn.dense(a, b) mod = tvm.IRModule.from_expr(relay.Function([a, b], c)) params = {} server = rpc.Server(key="roofline") remote = rpc.connect("127.0.0.1", server.port, key="roofline") dev = remote.device(target) report = tvm.utils.roofline_analysis(mod, params, target, dev, remote=remote) print(report) assert "Bound" in report.table() assert "Percent of Theoretical Optimal" in report.table() for call in report.calls: if "Percent of Theoretical Optimal" in call: if target.startswith("llvm"): # Ideally we'd like a little tighter bound here, but it is hard to # know how well this dense will perform without tuning. And we # don't have an operator that uses a specific number of flops. assert call["Percent of Theoretical Optimal"].ratio >= 5.0 elif target == "cuda": # The cuda gpu kernel is really poorly optimized assert 90 >= call["Percent of Theoretical Optimal"].ratio >= 0.01 if __name__ == "__main__": tvm.testing.main()
https://github.com/zk-ml/tachikoma
tests/python/unittest/test_runtime_container.py
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. import numpy as np import random import tvm import tvm.testing import pickle from tvm import te from tvm import nd, relay from tvm.runtime import container as _container def test_adt_constructor(): arr = nd.array([1, 2, 3]) fields = [arr, arr] y = _container.ADT(0, [arr, arr]) assert len(y) == 2 assert isinstance(y, _container.ADT) y[0:1][-1] == arr assert y.tag == 0 assert isinstance(arr, nd.NDArray) def test_tuple_object(): x = relay.var( "x", type_annotation=relay.ty.TupleType( [relay.ty.TensorType((), "int32"), relay.ty.TensorType((), "int32")] ), ) fn = relay.Function([x], relay.expr.TupleGetItem(x, 0)) mod = tvm.IRModule.from_expr(fn) f = relay.create_executor(kind="vm", mod=mod, device=nd.cpu(), target="llvm").evaluate() value_tuple = _container.tuple_object([nd.array(np.array(11)), nd.array(np.array(12))]) # pass an ADT object to evaluate out = f(value_tuple) tvm.testing.assert_allclose(out.numpy(), np.array(11)) def test_string(): s = tvm.runtime.String("xyz") assert isinstance(s, tvm.runtime.String) assert isinstance(s, str) assert s.startswith("xy") assert s + "1" == "xyz1" y = tvm.testing.echo(s) assert isinstance(y, tvm.runtime.String) assert s.__tvm_object__.same_as(y.__tvm_object__) assert s == y x = tvm.ir.load_json(tvm.ir.save_json(y)) assert isinstance(x, tvm.runtime.String) assert x == y # test pickle z = pickle.loads(pickle.dumps(s)) assert isinstance(z, tvm.runtime.String) assert s == z def test_shape_tuple(): shape = [random.randint(-10, 10) for _ in range(5)] stuple = _container.ShapeTuple(shape) len(stuple) == len(shape) for a, b in zip(stuple, shape): assert a == b # ShapleTuple vs. list assert stuple == list(shape) # ShapleTuple vs. tuple assert stuple == tuple(shape) # ShapleTuple vs. ShapeTuple assert stuple == _container.ShapeTuple(shape) if __name__ == "__main__": test_string() test_adt_constructor() test_tuple_object() test_shape_tuple()
https://github.com/zk-ml/tachikoma
tests/python/unittest/test_runtime_error.py
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. """Test runtime error handling""" import tvm from tvm import te import tvm.testing def test_op_translation(): ferror = tvm.testing.test_raise_error_callback("OpNotImplemented: myop") try: ferror() assert False except tvm.error.OpNotImplemented as e: msg = str(e) assert isinstance(e, NotImplementedError) assert msg.find("ffi_testing.cc") != -1 fchk_eq = tvm.testing.test_check_eq_callback("InternalError: myop") try: fchk_eq(0, 1) assert False except tvm.error.InternalError as e: msg = str(e) assert msg.find("ffi_testing.cc") != -1 try: tvm.testing.ErrorTest(0, 1) assert False except ValueError as e: msg = str(e) assert msg.find("ffi_testing.cc") != -1 def test_deep_callback(): def error_callback(): raise ValueError("callback error") wrap1 = tvm.testing.test_wrap_callback(error_callback) def flevel2(): wrap1() wrap2 = tvm.testing.test_wrap_callback(flevel2) def flevel3(): wrap2() wrap3 = tvm.testing.test_wrap_callback(flevel3) try: wrap3() assert False except ValueError as e: msg = str(e) idx2 = msg.find("in flevel2") idx3 = msg.find("in flevel3") assert idx2 != -1 and idx3 != -1 assert idx2 > idx3 if __name__ == "__main__": test_op_translation() test_deep_callback()
https://github.com/zk-ml/tachikoma
tests/python/unittest/test_runtime_extension.py
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. import tvm from tvm import te import numpy as np @tvm.register_extension class MyTensorView(object): _tvm_tcode = tvm._ffi.runtime_ctypes.ArgTypeCode.DLTENSOR_HANDLE def __init__(self, arr): self.arr = arr @property def _tvm_handle(self): return self.arr._tvm_handle def test_dltensor_compatible(): dtype = "int64" n = te.var("n") Ab = tvm.tir.decl_buffer((n,), dtype) i = te.var("i") ib = tvm.tir.ir_builder.create() A = ib.buffer_ptr(Ab) with ib.for_range(0, n - 1, "i") as i: A[i + 1] = A[i] + 1 stmt = ib.get() mod = tvm.IRModule.from_expr(tvm.tir.PrimFunc([Ab], stmt).with_attr("global_symbol", "arange")) f = tvm.build(mod, target="stackvm") a = tvm.nd.array(np.zeros(10, dtype=dtype)) aview = MyTensorView(a) f(aview) np.testing.assert_equal(a.numpy(), np.arange(a.shape[0])) if __name__ == "__main__": test_dltensor_compatible()
https://github.com/zk-ml/tachikoma
tests/python/unittest/test_runtime_graph.py
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. import tvm import tvm.testing from tvm import te, runtime import numpy as np import json from tvm import rpc from tvm import relay from tvm.contrib import utils, graph_executor @tvm.testing.requires_llvm def test_graph_simple(): n = 4 A = te.placeholder((n,), name="A") B = te.compute(A.shape, lambda *i: A(*i) + 1.0, name="B") s = te.create_schedule(B.op) node0 = {"op": "null", "name": "x", "inputs": []} node1 = { "op": "tvm_op", "name": "add", "inputs": [[0, 0, 0]], "attrs": {"func_name": "myadd", "flatten_data": "1", "num_inputs": "1", "num_outputs": "1"}, } nodes = [node0, node1] arg_nodes = [0] node_row_ptr = [0, 1, 2] outputs = [[1, 0, 0]] shape = (4,) attrs = { "shape": ["list_shape", [shape, shape]], "dltype": ["list_str", ["float32", "float32"]], "storage_id": ["list_int", [0, 1]], } graph = { "nodes": nodes, "arg_nodes": arg_nodes, "node_row_ptr": node_row_ptr, "heads": outputs, "attrs": attrs, } graph = json.dumps(graph) def check_verify(): mlib = tvm.build(s, [A, B], "llvm", name="myadd") mod = graph_executor.create(graph, mlib, tvm.cpu(0)) a = np.random.uniform(size=(n,)).astype(A.dtype) mod.run(x=a) out = mod.get_output(0, tvm.nd.empty((n,))) np.testing.assert_equal(out.numpy(), a + 1) def check_remote(server): mlib = tvm.build(s, [A, B], "llvm", name="myadd") remote = rpc.connect(server.host, server.port) temp = utils.tempdir() dev = remote.cpu(0) path_dso = temp.relpath("dev_lib.so") mlib.export_library(path_dso) remote.upload(path_dso) mlib = remote.load_module("dev_lib.so") mod = graph_executor.create(graph, mlib, remote.cpu(0)) a = np.random.uniform(size=(n,)).astype(A.dtype) mod.run(x=tvm.nd.array(a, dev)) out = tvm.nd.empty((n,), device=dev) out = mod.get_output(0, out) np.testing.assert_equal(out.numpy(), a + 1) def check_sharing(): x = relay.var("x", shape=(1, 10)) y = relay.var("y", shape=(1, 10)) z = relay.add(x, y) func = relay.Function([x, y], z) x_in = np.ones((1, 10)).astype("float32") params = {"x": x_in} graph, lib, params = relay.build(func, target="llvm", params=params) mod_shared = graph_executor.create(graph, lib, tvm.cpu(0)) mod_shared.load_params(runtime.save_param_dict(params)) num_mods = 10 mods = [graph_executor.create(graph, lib, tvm.cpu(0)) for _ in range(num_mods)] for mod in mods: mod.share_params(mod_shared, runtime.save_param_dict(params)) a = np.random.uniform(size=(1, 10)).astype("float32") for mod in mods: mod.run(y=a) out = mod.get_output(0, tvm.nd.empty((1, 10))) np.testing.assert_equal(out.numpy(), x_in + a) # Explicitly delete the shared module and verify correctness. del mod_shared for mod in mods: mod.run(y=a) out = mod.get_output(0, tvm.nd.empty((1, 10))) np.testing.assert_equal(out.numpy(), x_in + a) del mod check_verify() check_remote(rpc.Server("127.0.0.1")) check_sharing() def test_load_unexpected_params(): # Test whether graph_executor.load_params works if parameters # are provided that are not an expected input. mod = tvm.IRModule() params = {} x = relay.var("x", shape=(1, 10)) y = relay.var("y", shape=(1, 10)) z = relay.add(x, y) mod["main"] = relay.Function([x, y], z) graph_module = relay.build(mod, target="llvm", params=params) rt_mod = tvm.contrib.graph_executor.create( graph_module.get_graph_json(), graph_module.get_lib(), tvm.cpu(0) ) new_params = graph_module.get_params() new_params.update({"y_unknown": np.ones((1,)).astype("float32")}) rt_mod.load_params(runtime.save_param_dict(new_params)) if __name__ == "__main__": test_graph_simple() test_load_unexpected_params()
https://github.com/zk-ml/tachikoma
tests/python/unittest/test_runtime_graph_cuda_graph.py
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. import json import os import re import sys import time import pytest import tvm import tvm.testing from tvm import te import numpy as np from tvm.contrib import utils, graph_executor from tvm.contrib.cuda_graph import cuda_graph_executor bx = te.thread_axis("blockIdx.x") tx = te.thread_axis("threadIdx.x") @tvm.testing.requires_cudagraph def test_graph_simple(): n = 32 A = te.placeholder((n,), name="A") B = te.compute(A.shape, lambda *i: A(*i) + 1.0, name="B") s = te.create_schedule(B.op) xo, xi = s[B].split(B.op.axis[0], factor=8) s[B].bind(xo, bx) s[B].bind(xi, tx) node0 = {"op": "null", "name": "x", "inputs": []} node1 = { "op": "tvm_op", "name": "add", "inputs": [[0, 0, 0]], "attrs": {"func_name": "myadd", "flatten_data": "1", "num_inputs": "1", "num_outputs": "1"}, } nodes = [node0, node1] arg_nodes = [0] node_row_ptr = [0, 1, 2] outputs = [[1, 0, 0]] shape = (n,) attrs = { "shape": ["list_shape", [shape, shape]], "dltype": ["list_str", ["float32", "float32"]], "storage_id": ["list_int", [0, 1]], } graph = { "nodes": nodes, "arg_nodes": arg_nodes, "node_row_ptr": node_row_ptr, "heads": outputs, "attrs": attrs, } graph = json.dumps(graph) def check_verify(): mlib = tvm.build(s, [A, B], "cuda", name="myadd") dev = tvm.cuda(0) try: mod = cuda_graph_executor.create(graph, mlib, dev) except ValueError: return for i in range(3): a = np.random.uniform(size=(n,)).astype(A.dtype) mod.run(x=a) # The first run captured a CUDA graph out = mod.get_output(0, tvm.nd.empty((n,))) np.testing.assert_equal(out.numpy(), a + 1) # capture / run CUDA graph manually mod.capture_cuda_graph() a = np.random.uniform(size=(n,)).astype(A.dtype) mod.set_input(x=a) mod.run_cuda_graph() out = mod.get_output(0, tvm.nd.empty((n,))) np.testing.assert_equal(out.numpy(), a + 1) check_verify() if __name__ == "__main__": test_graph_simple()
https://github.com/zk-ml/tachikoma
tests/python/unittest/test_runtime_graph_debug.py
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. import json import os import re import sys import time from distutils.log import debug import numpy as np import pytest import tvm import tvm.testing from tvm import rpc, te from tvm._ffi.base import TVMError from tvm.contrib import utils from tvm.contrib.debugger import debug_executor # Constants for creating simple graphs, fixtures to avoid free globals @pytest.fixture def n(): return 4 @pytest.fixture def A(n): return te.placeholder((n,), name="A") @pytest.fixture def B(A): return te.compute(A.shape, lambda *i: A(*i) + 1.0, name="B") @pytest.fixture def s(B): return te.create_schedule(B.op) @pytest.fixture def mlib(s, A, B): return tvm.build(s, [A, B], "llvm", name="myadd") @pytest.fixture def myadd(mlib): def _myadd(*args): to_return = mlib["myadd"](*args) time.sleep(0.25) return to_return return _myadd @pytest.fixture def graph(): node0 = {"op": "null", "name": "x", "inputs": []} node1 = { "op": "tvm_op", "name": "add", "inputs": [[0, 0, 0]], "attrs": {"func_name": "myadd", "flatten_data": "1", "num_inputs": "1", "num_outputs": "1"}, } nodes = [node0, node1] arg_nodes = [0] node_row_ptr = [0, 1, 2] outputs = [[1, 0, 0]] shape = (4,) attrs = { "shape": ["list_shape", [shape, shape]], "dltype": ["list_str", ["float32", "float32"]], "storage_id": ["list_int", [0, 1]], } graph = { "nodes": nodes, "arg_nodes": arg_nodes, "node_row_ptr": node_row_ptr, "heads": outputs, "attrs": attrs, } graph = json.dumps(graph) return graph @tvm.testing.requires_llvm @tvm.testing.requires_rpc @pytest.mark.skipif( tvm.support.libinfo()["USE_PROFILER"] != "ON", reason="TVM was not built with profiler support" ) def test_end_to_end_graph_simple(graph, n, A, B, s, myadd): def check_verify(): mlib_proxy = tvm.support.FrontendTestModule() mlib_proxy["myadd"] = myadd mod = debug_executor.create(graph, mlib_proxy, tvm.cpu(0)) a = np.random.uniform(size=(n,)).astype(A.dtype) mod.set_input(x=a) # verify dumproot created directory = mod._dump_path assert os.path.exists(directory) # verify graph is there GRAPH_DUMP_FILE_NAME = "_tvmdbg_graph_dump.json" assert len(os.listdir(directory)) == 1 # verify the file name is proper graph_dump_path = os.path.join(directory, GRAPH_DUMP_FILE_NAME) assert os.path.exists(graph_dump_path) # verify the graph contains some expected keys with open(graph_dump_path) as graph_f: dumped_graph = json.load(graph_f) assert isinstance(dumped_graph, dict) for k in ("nodes", "arg_nodes", "node_row_ptr", "heads", "attrs"): assert k in dumped_graph, f"key {k} not in dumped graph {graph!r}" mod.run() # Verify the tensors are dumped assert len(os.listdir(directory)) > 1 debug_lines = mod.debug_datum.get_debug_result().split("\n") def split_debug_line(i): to_return = re.split(r" [ ]*", debug_lines[i]) assert to_return[-1] == "" to_return = to_return[:-1] # strip empty trailing part return to_return assert split_debug_line(0) == [ "Node Name", "Ops", "Time(us)", "Time(%)", "Shape", "Inputs", "Outputs", "Measurements(us)", ] myadd_lines = split_debug_line(2) assert myadd_lines[0] == "add" assert myadd_lines[1] == "myadd" runtime_sec = float(myadd_lines[2]) / 1e6 # printed in us # Ensure runtime is at least the sleep time and less than a unit prefix order of magnitude. # Here we just care that the prefix is correct. assert runtime_sec > 0.25 and runtime_sec < 0.25 * 1000 total_lines = split_debug_line(3) assert total_lines[0] == "Total_time" assert total_lines[2] == myadd_lines[2] CHROME_TRACE_FILE_NAME = "_tvmdbg_execution_trace.json" assert os.path.exists(os.path.join(directory, CHROME_TRACE_FILE_NAME)) with open(os.path.join(directory, CHROME_TRACE_FILE_NAME)) as f: trace = json.load(f) assert trace["displayTimeUnit"] == "ns" events = trace["traceEvents"] assert len(events) == 4 assert all(event["ph"] in ("B", "E") for event in events) assert all(event["pid"] == 1 for event in events) assert all(event["tid"] == 1 for event in events) assert all(event["name"] == "x" for event in events[:2]) assert all(event["name"] == "add" for event in events[2:]) assert events[0]["ts"] == 0 assert events[0]["ph"] == "B" # verify the output is correct out = mod.get_output(0, tvm.nd.empty((n,))) np.testing.assert_equal(out.numpy(), a + 1) mod.exit() # verify dump root delete after cleanup assert not os.path.exists(directory) def check_remote(server): mlib = tvm.build(s, [A, B], "llvm", name="myadd") remote = rpc.connect(server.host, server.port) temp = utils.tempdir() dev = remote.cpu(0) path_dso = temp.relpath("dev_lib.so") mlib.export_library(path_dso) remote.upload(path_dso) mlib = remote.load_module("dev_lib.so") try: mod = debug_executor.create(graph, mlib, remote.cpu(0)) except ValueError: print("Skip because debug runtime not enabled") return a = np.random.uniform(size=(n,)).astype(A.dtype) mod.run(x=tvm.nd.array(a, dev)) out = tvm.nd.empty((n,), device=dev) out = mod.get_output(0, out) np.testing.assert_equal(out.numpy(), a + 1) check_verify() check_remote(rpc.Server("127.0.0.1")) @tvm.testing.requires_llvm @pytest.mark.skipif( tvm.support.libinfo()["USE_PROFILER"] != "ON", reason="TVM was not built with profiler support" ) def test_run_single_node(graph, n, A, myadd): mlib_proxy = tvm.support.FrontendTestModule() mlib_proxy["myadd"] = myadd mod: debug_executor.GraphModuleDebug = debug_executor.create(graph, mlib_proxy, tvm.cpu(0)) a = np.random.uniform(size=(n,)).astype(A.dtype) mod.set_input(x=a) assert len(mod.debug_datum.get_graph_nodes()) == 2 assert mod.debug_datum.get_graph_nodes()[0]["op"] == "param" assert mod.debug_datum.get_graph_nodes()[1]["op"] == "myadd" # Running a node with no associated function should return instantly and have 0 runtime assert mod.run_individual_node(0, number=1).mean == 0 # Meanwhile the actual function should take some time, more time if you run it more times repeat_1_result = mod.run_individual_node(1, repeat=1) assert repeat_1_result.mean > 0 # Running multiple times (10) should take longer than 1 time repeat_3_results = mod.run_individual_node(1, repeat=3) assert sum(repeat_3_results.results) > sum(repeat_1_result.results) # Increasing the number of repeats should give you the number of results asked for assert len(mod.run_individual_node(1, repeat=10).results) == 10 # Doing repeat_ms should have the run time greater than the asked amount start = time.time() mod.run_individual_node(1, min_repeat_ms=500) end = time.time() elapsed_time_in_seconds = end - start assert elapsed_time_in_seconds >= 0.5 # Doing `cooldown_interval_ms` should have the execution time increases start = time.time() mod.run_individual_node(1, repeat=2, min_repeat_ms=500, cooldown_interval_ms=1000) end = time.time() elapsed_time_in_seconds_with_def_rep = end - start assert elapsed_time_in_seconds_with_def_rep >= 3 # Doing with `repeats_to_cooldown` not equal 1 should not trigger # cooldown after each repeat start = time.time() mod.run_individual_node( 1, repeat=2, min_repeat_ms=500, cooldown_interval_ms=1000, repeats_to_cooldown=2 ) end = time.time() elapsed_time_in_seconds_with_rep_2 = end - start assert elapsed_time_in_seconds_with_rep_2 >= 2 and ( elapsed_time_in_seconds_with_rep_2 < elapsed_time_in_seconds_with_def_rep ) # Going out of bounds of node index throws a tvm error with pytest.raises(TVMError): mod.run_individual_node(2) if __name__ == "__main__": tvm.testing.main()
https://github.com/zk-ml/tachikoma
tests/python/unittest/test_runtime_heterogeneous.py
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. # pylint: disable=too-many-locals """Unit tests for heterogeneous runtime""" import json import numpy as np import tvm from tvm import te from tvm.contrib import graph_executor, utils from tvm import topi def get_simplex_graph(host_dev_type, device_dev_type): r""" Return the hand-crafted json object where only one copy node is inserted. This node copies data from the target device to cpu. The network is constructed as following: A B \ / elemwise_add (gpu) \ copy C \ / elemwise_sub (cpu) Parameters ---------- host_dev_type : int The device type of the host processor, e.g. cpu. device_dev_type : int The device type of the device processor, e.g. gpu, opencl, etc. Returns ------- json : json A json encoded object. """ # Construct each node in the graph. var_a = {"op": "null", "name": "A", "inputs": []} var_b = {"op": "null", "name": "B", "inputs": []} elemwise_add = { "op": "tvm_op", "name": "elemwise_add", "attrs": { "flatten_data": "1", "func_name": "elemwise_add", "num_inputs": "2", "num_outputs": "1", }, "inputs": [[0, 0, 0], [1, 0, 0]], } copy = { "op": "tvm_op", "name": "__copy_add_to_sub", "attrs": { "flatten_data": "0", "func_name": "__copy", "num_inputs": "1", "num_outputs": "1", }, "inputs": [[2, 0, 0]], } var_c = {"op": "null", "name": "C", "inputs": []} elemwise_sub = { "op": "tvm_op", "name": "elemwise_sub", "attrs": { "flatten_data": "0", "func_name": "elemwise_sub", "num_inputs": "2", "num_outputs": "1", }, "inputs": [[3, 0, 0], [4, 0, 0]], } # Group the nodes. nodes = [var_a, var_b, elemwise_add, copy, var_c, elemwise_sub] arg_nodes = [0, 1, 4] node_row_ptr = [0, 1, 2, 3, 4, 5, 6] heads = [[5, 0, 0]] shape = (4,) attrs = { "storage_id": ["list_int", [3, 4, 0, 1, 5, 2]], "shape": ["list_shape", [shape, shape, shape, shape, shape, shape]], "device_index": [ "list_int", [ device_dev_type, device_dev_type, device_dev_type, host_dev_type, host_dev_type, host_dev_type, ], ], "dtype": ["list_int", [0, 0, 0, 0, 0, 0]], "dltype": ["list_str", ["float32", "float32", "float32", "float32", "float32", "float32"]], } # Construct the graph. graph = { "nodes": nodes, "arg_nodes": arg_nodes, "node_row_ptr": node_row_ptr, "heads": heads, "attrs": attrs, } return json.dumps(graph) def test_simplex_data_transferring(): r""" Test the heterogeneous execution of a simple network where data transferring is from the target device to the host processor at runtime. The host processor is always assumed to be cpu, and the device varies. """ host = "cpu" target_host = "llvm" host_dev = tvm.device(host) if not tvm.runtime.enabled(target_host): print("Skip test because llvm is not enabled.") return def check_device(device, target_device): if not tvm.runtime.enabled(target_device): print("Skip test because {} is not enabled.".format(target_device)) return device_dev = tvm.device(device) graph = get_simplex_graph(host_dev.device_type, device_dev.device_type) shape = (4,) # Create module for add whose target is the device. tensor_a = te.placeholder(shape, name="A") tensor_b = te.placeholder(shape, name="B") elemwise_add = te.compute( shape, lambda *i: tensor_a(*i) + tensor_b(*i), name="elemwise_add" ) target = topi.cpp.TEST_create_target(device) schedule_add = topi.cpp.cuda.schedule_injective(target, [elemwise_add]) lower_add = tvm.lower(schedule_add, [tensor_a, tensor_b, elemwise_add], name="elemwise_add") # Insert copy. Neither compute nor schedule is required for the copy # node. The compute will be performed at runtime which is just data # copy from the input to the output. tensor_copy = te.placeholder(shape, name="__copy") # Create module for sub whose target is the host. tensor_c = te.placeholder(shape, name="C") elemwise_sub = te.compute( shape, lambda *i: tensor_copy(*i) - tensor_c(*i), name="elemwise_sub" ) schedule_sub = te.create_schedule(elemwise_sub.op) lower_sub = tvm.lower( schedule_sub, [tensor_copy, tensor_c, elemwise_sub], name="elemwise_sub" ) target_flist = {target_device: lower_add, target_host: lower_sub} target = tvm.target.Target(target, target_host) mhost = tvm.build(target_flist, target=target) dev = [host_dev, device_dev] mod = graph_executor.create(graph, mhost, dev) params = {} params["A"] = tensor_a = np.random.uniform(size=shape).astype(tensor_a.dtype) params["B"] = tensor_b = np.random.uniform(size=shape).astype(tensor_b.dtype) params["C"] = tensor_c = np.random.uniform(size=shape).astype(tensor_c.dtype) mod.set_input(**params) mod.run() out = mod.get_output(0, tvm.nd.empty(shape)) np.testing.assert_equal(out.numpy(), (tensor_a + tensor_b) - tensor_c) dev_tar = {"cuda": "cuda", "opencl": "opencl"} for device, target in dev_tar.items(): with tvm.target.Target(device): check_device(device, target) def get_duplex_graph(host_dev_type, device_dev_type): r""" Return the hand-crafted json object where two copy nodes are inserted. Data transferring happens back-and-forth between the target device and CPU. The network is constructed as following: A B \ / elemwise_add (gpu) \ copy C \ / elemwise_sub (cpu) \ copy D \ / elemwise_add (gpu) Parameters ---------- host_dev_type : int The device type of the host processor, e.g. cpu. device_dev_type : int The device type of the device processor, e.g. gpu, opencl, etc. Returns ------- json : json A json encoded object. """ # Construct each node in the graph. var_a = {"op": "null", "name": "A", "inputs": []} var_b = {"op": "null", "name": "B", "inputs": []} elemwise_add0 = { "op": "tvm_op", "name": "elemwise_add0", "attrs": { "flatten_data": "1", "func_name": "elemwise_add0", "num_inputs": "2", "num_outputs": "1", }, "inputs": [[0, 0, 0], [1, 0, 0]], } copy_add_sub = { "op": "tvm_op", "name": "__copy_add_to_sub", "attrs": { "flatten_data": "0", "func_name": "__copy", "num_inputs": "1", "num_outputs": "1", }, "inputs": [[2, 0, 0]], } var_c = {"op": "null", "name": "C", "inputs": []} elemwise_sub = { "op": "tvm_op", "name": "elemwise_sub", "attrs": { "flatten_data": "0", "func_name": "elemwise_sub", "num_inputs": "2", "num_outputs": "1", }, "inputs": [[3, 0, 0], [4, 0, 0]], } copy_sub_add = { "op": "tvm_op", "name": "__copy_sub_to_add", "attrs": { "flatten_data": "0", "func_name": "__copy", "num_inputs": "1", "num_outputs": "1", }, "inputs": [[5, 0, 0]], } var_d = {"op": "null", "name": "D", "inputs": []} elemwise_add1 = { "op": "tvm_op", "name": "elemwise_add1", "attrs": { "flatten_data": "0", "func_name": "elemwise_add1", "num_inputs": "2", "num_outputs": "1", }, "inputs": [[6, 0, 0], [7, 0, 0]], } # Group the nodes. nodes = [ var_a, var_b, elemwise_add0, copy_add_sub, var_c, elemwise_sub, copy_sub_add, var_d, elemwise_add1, ] arg_nodes = [0, 1, 4, 7] node_row_ptr = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] heads = [[8, 0, 0]] shape = (4,) attrs = { "storage_id": ["list_int", [4, 5, 0, 1, 6, 2, 0, 7, 3]], "shape": ["list_shape", [shape, shape, shape, shape, shape, shape, shape, shape, shape]], "device_index": [ "list_int", [ device_dev_type, device_dev_type, device_dev_type, host_dev_type, host_dev_type, host_dev_type, device_dev_type, device_dev_type, device_dev_type, ], ], "dtype": ["list_int", [0, 0, 0, 0, 0, 0, 0, 0, 0]], "dltype": [ "list_str", [ "float32", "float32", "float32", "float32", "float32", "float32", "float32", "float32", "float32", ], ], } # Construct the graph. graph = { "nodes": nodes, "arg_nodes": arg_nodes, "node_row_ptr": node_row_ptr, "heads": heads, "attrs": attrs, } return json.dumps(graph) def test_duplex_data_transferring(): r""" Test the heterogeneous execution of a simple network where data transferring occurs back-and-forth between the target device and host processor. The host processor is always assumed to be cpu, and the target device varies. """ host = "cpu" target_host = "llvm" host_dev = tvm.device(host) if not tvm.runtime.enabled(target_host): print("Skip test because llvm is not enabled.") return def check_device(device, target_device): if not tvm.runtime.enabled(target_device): print("Skip test because {} is not enabled.".format(target_device)) return device_dev = tvm.device(device) graph = get_duplex_graph(host_dev.device_type, device_dev.device_type) shape = (4,) # Insert copy nodes for data transferring between add and sub nodes. # Transfers data from gpu to cpu. copy_add_sub = te.placeholder(shape, name="__copy0") # Transfers data from cpu to gpu. copy_sub_add = te.placeholder(shape, name="__copy1") # Create a module containing adds on the device. tensor_a = te.placeholder(shape, name="A") tensor_b = te.placeholder(shape, name="B") tensor_d = te.placeholder(shape, name="D") elemwise_add0 = te.compute( shape, lambda *i: tensor_a(*i) + tensor_b(*i), name="elemwise_add0" ) elemwise_add1 = te.compute( shape, lambda *i: copy_sub_add(*i) + tensor_d(*i), name="elemwise_add1" ) target = topi.cpp.TEST_create_target(device) add_schedule0 = topi.cpp.cuda.schedule_injective(target, [elemwise_add0]) lower_add0 = tvm.lower( add_schedule0, [tensor_a, tensor_b, elemwise_add0], name="elemwise_add0" ) add_schedule1 = topi.cpp.cuda.schedule_injective(target, [elemwise_add1]) lower_add1 = tvm.lower( add_schedule1, [tensor_d, copy_sub_add, elemwise_add1], name="elemwise_add1" ) # Create module for sub whose target is the host. tensor_c = te.placeholder(shape, name="C") elemwise_sub = te.compute( shape, lambda *i: copy_add_sub(*i) - tensor_c(*i), name="elemwise_sub" ) sub_schedule = te.create_schedule(elemwise_sub.op) lower_sub = tvm.lower( sub_schedule, [copy_add_sub, tensor_c, elemwise_sub], name="elemwise_sub" ) lower_add0.update(lower_add1) target_flist = {target_device: lower_add0, target_host: lower_sub} target = tvm.target.Target(target, target_host) mhost = tvm.build(target_flist, target=target) dev = [host_dev, device_dev] params = {} params["A"] = tensor_a = np.random.uniform(size=shape).astype(tensor_a.dtype) params["B"] = tensor_b = np.random.uniform(size=shape).astype(tensor_b.dtype) params["C"] = tensor_c = np.random.uniform(size=shape).astype(tensor_c.dtype) params["D"] = tensor_d = np.random.uniform(size=shape).astype(tensor_d.dtype) def check_verify(): mod = graph_executor.create(graph, mhost, dev) mod.set_input(**params) mod.run() out = mod.get_output(0, tvm.nd.empty(shape)) np.testing.assert_equal(out.numpy(), tensor_a + tensor_b - tensor_c + tensor_d) def check_load_module(): temp = utils.tempdir() path_lib = temp.relpath("deploy.so") mhost.export_library(path_lib) with open(temp.relpath("deploy.json"), "w") as out_file: out_file.write(graph) loaded_lib = tvm.runtime.load_module(path_lib) loaded_graph = open(temp.relpath("deploy.json")).read() mod = graph_executor.create(loaded_graph, loaded_lib, dev) mod.set_input(**params) mod.run() out = mod.get_output(0, tvm.nd.empty(shape)) np.testing.assert_equal(out.numpy(), tensor_a + tensor_b - tensor_c + tensor_d) check_verify() check_load_module() dev_tar = {"cuda": "cuda", "opencl": "opencl"} for device, target in dev_tar.items(): with tvm.target.Target(device): check_device(device, target) if __name__ == "__main__": test_simplex_data_transferring() test_duplex_data_transferring()
https://github.com/zk-ml/tachikoma
tests/python/unittest/test_runtime_measure.py
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. import time import ctypes import tvm from tvm import te from tvm.contrib.utils import tempdir from tvm.runtime.module import BenchmarkResult def test_min_repeat_ms(): tmp = tempdir() filename = tmp.relpath("log") @tvm.register_func def my_debug(filename): """one call lasts for 100 ms and writes one character to a file""" time.sleep(0.1) with open(filename, "a") as fout: fout.write("c") X = te.compute((), lambda: tvm.tir.call_packed("my_debug", filename)) s = te.create_schedule(X.op) func = tvm.build(s, [X]) x = tvm.nd.empty((), dtype="int32") ftimer = func.time_evaluator(func.entry_name, tvm.cpu(), number=1, repeat=1) ftimer(x) with open(filename, "r") as fin: ct = len(fin.readline()) assert ct == 2 ftimer = func.time_evaluator(func.entry_name, tvm.cpu(), number=1, repeat=1, min_repeat_ms=1000) ftimer(x) # make sure we get more than 10 calls with open(filename, "r") as fin: ct = len(fin.readline()) assert ct > 10 + 2 def test_benchmark_result(): r = BenchmarkResult([1, 2, 2, 5]) assert r.mean == 2.5 assert r.median == 2.0 assert r.min == 1 assert r.max == 5 assert r.std == 1.5 if __name__ == "__main__": test_min_repeat_ms() test_benchmark_result()
https://github.com/zk-ml/tachikoma
tests/python/unittest/test_runtime_module_based_interface.py
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. import numpy as np import os from tvm import relay, runtime from tvm.relay import testing import tvm from tvm.contrib import graph_executor from tvm.contrib.debugger import debug_executor from tvm.contrib.cuda_graph import cuda_graph_executor import tvm.testing def input_shape(mod): return [int(x) for x in mod["main"].checked_type.arg_types[0].shape] def verify(data): if not tvm.runtime.enabled("llvm"): print("Skip because llvm is not enabled") return mod, params = relay.testing.synthetic.get_workload() with relay.build_config(opt_level=3): graph, lib, graph_params = relay.build_module.build(mod, "llvm", params=params) dev = tvm.cpu() module = graph_executor.create(graph, lib, dev) module.set_input("data", data) module.set_input(**graph_params) module.run() out = module.get_output(0).numpy() return out @tvm.testing.requires_llvm def test_legacy_compatibility(): mod, params = relay.testing.synthetic.get_workload() with relay.build_config(opt_level=3): graph, lib, graph_params = relay.build_module.build(mod, "llvm", params=params) data = np.random.uniform(-1, 1, size=input_shape(mod)).astype("float32") dev = tvm.cpu() module = graph_executor.create(graph, lib, dev) module.set_input("data", data) module.set_input(**graph_params) module.run() out = module.get_output(0).numpy() tvm.testing.assert_allclose(out, verify(data), atol=1e-5) @tvm.testing.requires_llvm def test_cpu(): mod, params = relay.testing.synthetic.get_workload() with relay.build_config(opt_level=3): complied_graph_lib = relay.build_module.build(mod, "llvm", params=params) data = np.random.uniform(-1, 1, size=input_shape(mod)).astype("float32") # raw api dev = tvm.cpu() gmod = complied_graph_lib["default"](dev) set_input = gmod["set_input"] run = gmod["run"] get_output = gmod["get_output"] set_input("data", tvm.nd.array(data)) run() out = get_output(0).numpy() tvm.testing.assert_allclose(out, verify(data), atol=1e-5) # graph executor wrapper gmod = graph_executor.GraphModule(complied_graph_lib["default"](dev)) gmod.set_input("data", data) gmod.run() out = gmod.get_output(0).numpy() tvm.testing.assert_allclose(out, verify(data), atol=1e-5) @tvm.testing.requires_llvm def test_cpu_get_graph_json(): mod, params = relay.testing.synthetic.get_workload() with relay.build_config(opt_level=3): complied_graph_lib = relay.build_module.build(mod, "llvm", params=params) from tvm.contrib import utils temp = utils.tempdir() file_name = "deploy_lib.so" path_lib = temp.relpath(file_name) complied_graph_lib.export_library(path_lib) loaded_lib = tvm.runtime.load_module(path_lib) json = loaded_lib["get_graph_json"]() assert isinstance(json, str) == True assert json.find("tvmgen_default_fused_nn_softmax_add") > -1 @tvm.testing.requires_llvm def test_cpu_get_graph_params_run(): mod, params = relay.testing.synthetic.get_workload() with tvm.transform.PassContext(opt_level=3): complied_graph_lib = relay.build_module.build(mod, "llvm", params=params) data = np.random.uniform(-1, 1, size=input_shape(mod)).astype("float32") dev = tvm.cpu() from tvm.contrib import utils temp = utils.tempdir() file_name = "deploy_lib.so" path_lib = temp.relpath(file_name) complied_graph_lib.export_library(path_lib) loaded_lib = tvm.runtime.load_module(path_lib) loaded_params = loaded_lib["get_graph_params"]() gmod = graph_executor.GraphModule(loaded_lib["default"](dev)) gmod.set_input(key="data", value=data, **loaded_params) gmod.run() out = gmod.get_output(0).numpy() tvm.testing.assert_allclose(out, verify(data), atol=1e-5) @tvm.testing.requires_llvm def test_cpu_get_graph_params_compare(): # Create sample net from tvm.relay.testing.init import create_workload, Constant inp_shape = (1, 3, 24, 12) dtype = "float32" data = relay.var("data", shape=inp_shape, dtype=dtype) conv_shape = [inp_shape[1], inp_shape[1], 3, 3] conv = relay.nn.conv2d( data, relay.var("conv_weight", shape=conv_shape, dtype=dtype), padding=1, kernel_size=3, ) args = relay.analysis.free_vars(conv) func = relay.Function(args, conv) mod, params = create_workload(func, initializer=Constant()) with tvm.transform.PassContext(opt_level=3): complied_graph_lib = relay.build_module.build(mod, "llvm", params=params) from tvm.contrib import utils temp = utils.tempdir() file_name = "deploy_lib.so" path_lib = temp.relpath(file_name) complied_graph_lib.export_library(path_lib) loaded_lib = tvm.runtime.load_module(path_lib) loaded_params = loaded_lib["get_graph_params"]() tvm.testing.assert_allclose( params["conv_weight"].numpy(), loaded_params["p0"].numpy()[0][0], atol=1e-5 ) @tvm.testing.requires_cuda @tvm.testing.requires_gpu def test_gpu(): mod, params = relay.testing.synthetic.get_workload() with relay.build_config(opt_level=3): complied_graph_lib = relay.build_module.build(mod, "cuda", params=params) data = np.random.uniform(-1, 1, size=input_shape(mod)).astype("float32") dev = tvm.cuda() # raw api gmod = complied_graph_lib["default"](dev) set_input = gmod["set_input"] run = gmod["run"] get_output = gmod["get_output"] set_input("data", tvm.nd.array(data)) run() out = get_output(0).numpy() tvm.testing.assert_allclose(out, verify(data), atol=1e-5) # graph executor wrapper gmod = graph_executor.GraphModule(complied_graph_lib["default"](dev)) gmod.set_input("data", data) gmod.run() out = gmod.get_output(0).numpy() tvm.testing.assert_allclose(out, verify(data), atol=1e-5) @tvm.testing.uses_gpu def test_mod_export(): def verify_cpu_export(obj_format): mod, params = relay.testing.synthetic.get_workload() with relay.build_config(opt_level=3): complied_graph_lib = relay.build_module.build(mod, "llvm", params=params) from tvm.contrib import utils temp = utils.tempdir() if obj_format == ".so": file_name = "deploy_lib.so" else: assert obj_format == ".tar" file_name = "deploy_lib.tar" path_lib = temp.relpath(file_name) complied_graph_lib.export_library(path_lib) # run the setup in a separate function, so the load_lib # can get destructed right away # test the robustness wrt to parent module destruction def setup_gmod(): loaded_lib = tvm.runtime.load_module(path_lib) dev = tvm.cpu(0) return loaded_lib["default"](dev) gmod = setup_gmod() # raw api set_input = gmod["set_input"] run = gmod["run"] get_output = gmod["get_output"] data = np.random.uniform(-1, 1, size=input_shape(mod)).astype("float32") set_input("data", tvm.nd.array(data)) run() out = get_output(0).numpy() tvm.testing.assert_allclose(out, verify(data), atol=1e-5) # graph executor wrapper gmod = graph_executor.GraphModule(setup_gmod()) gmod.set_input("data", data) gmod.run() out = gmod.get_output(0).numpy() tvm.testing.assert_allclose(out, verify(data), atol=1e-5) def verify_gpu_export(obj_format): if not tvm.testing.device_enabled("cuda"): print("Skip because cuda is not enabled") return mod, params = relay.testing.synthetic.get_workload() with relay.build_config(opt_level=3): complied_graph_lib = relay.build_module.build(mod, "cuda", params=params) from tvm.contrib import utils temp = utils.tempdir() if obj_format == ".so": file_name = "deploy_lib.so" else: assert obj_format == ".tar" file_name = "deploy_lib.tar" path_lib = temp.relpath(file_name) complied_graph_lib.export_library(path_lib) data = np.random.uniform(-1, 1, size=input_shape(mod)).astype("float32") # run the setup in a separate function, so the load_lib # can get destructed right away # test the robustness wrt to parent module destruction def setup_gmod(): loaded_lib = tvm.runtime.load_module(path_lib) dev = tvm.cuda() return loaded_lib["default"](dev) gmod = setup_gmod() # raw api set_input = gmod["set_input"] run = gmod["run"] get_output = gmod["get_output"] set_input("data", tvm.nd.array(data)) run() out = get_output(0).numpy() tvm.testing.assert_allclose(out, verify(data), atol=1e-5) # graph executor wrapper gmod = graph_executor.GraphModule(setup_gmod()) gmod.set_input("data", data) gmod.run() out = gmod.get_output(0).numpy() tvm.testing.assert_allclose(out, verify(data), atol=1e-5) @tvm.testing.requires_llvm def verify_rpc_cpu_export(obj_format): mod, params = relay.testing.synthetic.get_workload() with relay.build_config(opt_level=3): complied_graph_lib = relay.build_module.build(mod, "llvm", params=params) from tvm.contrib import utils temp = utils.tempdir() if obj_format == ".so": file_name = "deploy_lib.so" else: assert obj_format == ".tar" file_name = "deploy_lib.tar" path_lib = temp.relpath(file_name) complied_graph_lib.export_library(path_lib) from tvm import rpc remote = rpc.LocalSession() remote.upload(path_lib) loaded_lib = remote.load_module(path_lib) data = np.random.uniform(-1, 1, size=input_shape(mod)).astype("float32") dev = remote.cpu() # raw api gmod = loaded_lib["default"](dev) set_input = gmod["set_input"] run = gmod["run"] get_output = gmod["get_output"] set_input("data", tvm.nd.array(data, device=dev)) run() out = get_output(0).numpy() tvm.testing.assert_allclose(out, verify(data), atol=1e-5) # graph executor wrapper gmod = graph_executor.GraphModule(loaded_lib["default"](dev)) gmod.set_input("data", data) gmod.run() out = gmod.get_output(0).numpy() tvm.testing.assert_allclose(out, verify(data), atol=1e-5) def verify_rpc_gpu_export(obj_format): if not tvm.testing.device_enabled("cuda"): print("Skip because cuda is not enabled") return mod, params = relay.testing.synthetic.get_workload() with relay.build_config(opt_level=3): complied_graph_lib = relay.build_module.build(mod, "cuda", params=params) from tvm.contrib import utils temp = utils.tempdir() if obj_format == ".so": file_name = "deploy_lib.so" else: assert obj_format == ".tar" file_name = "deploy_lib.tar" path_lib = temp.relpath(file_name) complied_graph_lib.export_library(path_lib) from tvm import rpc def check_remote(server): remote = rpc.connect(server.host, server.port) remote.upload(path_lib) loaded_lib = remote.load_module(path_lib) data = np.random.uniform(-1, 1, size=input_shape(mod)).astype("float32") dev = remote.cuda() # raw api gmod = loaded_lib["default"](dev) set_input = gmod["set_input"] run = gmod["run"] get_output = gmod["get_output"] set_input("data", tvm.nd.array(data, device=dev)) run() out = get_output(0).numpy() tvm.testing.assert_allclose(out, verify(data), atol=1e-5) # graph executor wrapper gmod = graph_executor.GraphModule(loaded_lib["default"](dev)) gmod.set_input("data", data) gmod.run() out = gmod.get_output(0).numpy() tvm.testing.assert_allclose(out, verify(data), atol=1e-5) check_remote(rpc.Server("127.0.0.1")) for obj_format in [".so", ".tar"]: verify_cpu_export(obj_format) verify_gpu_export(obj_format) verify_rpc_cpu_export(obj_format) verify_rpc_gpu_export(obj_format) @tvm.testing.requires_llvm @tvm.testing.uses_gpu def test_remove_package_params(): def verify_cpu_remove_package_params(obj_format): mod, params = relay.testing.synthetic.get_workload() with relay.build_config(opt_level=3): complied_graph_lib = relay.build_module.build(mod, "llvm", params=params) from tvm.contrib import utils temp = utils.tempdir() if obj_format == ".so": file_name = "deploy_lib.so" else: assert obj_format == ".tar" file_name = "deploy_lib.tar" path_lib = temp.relpath(file_name) complied_graph_lib_no_params = complied_graph_lib["remove_params"]() complied_graph_lib_no_params.export_library(path_lib) with open(temp.relpath("deploy_param.params"), "wb") as fo: fo.write(runtime.save_param_dict(complied_graph_lib.get_params())) loaded_lib = tvm.runtime.load_module(path_lib) data = np.random.uniform(-1, 1, size=input_shape(mod)).astype("float32") dev = tvm.cpu(0) # raw api gmod = loaded_lib["default"](dev) set_input = gmod["set_input"] run = gmod["run"] get_output = gmod["get_output"] load_params = gmod["load_params"] loaded_params = bytearray(open(temp.relpath("deploy_param.params"), "rb").read()) set_input("data", tvm.nd.array(data)) load_params(loaded_params) run() out = get_output(0).numpy() tvm.testing.assert_allclose(out, verify(data), atol=1e-5) # graph executor wrapper gmod = graph_executor.GraphModule(loaded_lib["default"](dev)) loaded_params = bytearray(open(temp.relpath("deploy_param.params"), "rb").read()) gmod.set_input("data", data) gmod.load_params(loaded_params) gmod.run() out = gmod.get_output(0).numpy() tvm.testing.assert_allclose(out, verify(data), atol=1e-5) def verify_gpu_remove_package_params(obj_format): if not tvm.testing.device_enabled("cuda"): print("Skip because cuda is not enabled") return mod, params = relay.testing.synthetic.get_workload() with relay.build_config(opt_level=3): complied_graph_lib = relay.build_module.build(mod, "cuda", params=params) from tvm.contrib import utils temp = utils.tempdir() if obj_format == ".so": file_name = "deploy_lib.so" else: assert obj_format == ".tar" file_name = "deploy_lib.tar" path_lib = temp.relpath(file_name) complied_graph_lib_no_params = complied_graph_lib["remove_params"]() complied_graph_lib_no_params.export_library(path_lib) with open(temp.relpath("deploy_param.params"), "wb") as fo: fo.write(runtime.save_param_dict(complied_graph_lib.get_params())) loaded_lib = tvm.runtime.load_module(path_lib) data = np.random.uniform(-1, 1, size=input_shape(mod)).astype("float32") dev = tvm.cuda(0) # raw api gmod = loaded_lib["default"](dev) set_input = gmod["set_input"] run = gmod["run"] get_output = gmod["get_output"] load_params = gmod["load_params"] loaded_params = bytearray(open(temp.relpath("deploy_param.params"), "rb").read()) set_input("data", tvm.nd.array(data)) load_params(loaded_params) run() out = get_output(0).numpy() tvm.testing.assert_allclose(out, verify(data), atol=1e-5) # graph executor wrapper gmod = graph_executor.GraphModule(loaded_lib["default"](dev)) loaded_params = bytearray(open(temp.relpath("deploy_param.params"), "rb").read()) gmod.set_input("data", data) gmod.load_params(loaded_params) gmod.run() out = gmod.get_output(0).numpy() tvm.testing.assert_allclose(out, verify(data), atol=1e-5) @tvm.testing.requires_llvm def verify_rpc_cpu_remove_package_params(obj_format): mod, params = relay.testing.synthetic.get_workload() with relay.build_config(opt_level=3): complied_graph_lib = relay.build_module.build(mod, "llvm", params=params) from tvm.contrib import utils temp = utils.tempdir() if obj_format == ".so": file_name = "deploy_lib.so" else: assert obj_format == ".tar" file_name = "deploy_lib.tar" path_lib = temp.relpath(file_name) complied_graph_lib_no_params = complied_graph_lib["remove_params"]() complied_graph_lib_no_params.export_library(path_lib) path_params = temp.relpath("deploy_param.params") with open(path_params, "wb") as fo: fo.write(runtime.save_param_dict(complied_graph_lib.get_params())) from tvm import rpc remote = rpc.LocalSession() remote.upload(path_lib) loaded_lib = remote.load_module(path_lib) data = np.random.uniform(-1, 1, size=input_shape(mod)).astype("float32") dev = remote.cpu() # raw api gmod = loaded_lib["default"](dev) set_input = gmod["set_input"] run = gmod["run"] get_output = gmod["get_output"] load_params = gmod["load_params"] loaded_params = bytearray(open(path_params, "rb").read()) set_input("data", tvm.nd.array(data, device=dev)) load_params(loaded_params) run() out = get_output(0).numpy() tvm.testing.assert_allclose(out, verify(data), atol=1e-5) # graph executor wrapper gmod = graph_executor.GraphModule(loaded_lib["default"](dev)) loaded_params = bytearray(open(path_params, "rb").read()) gmod.set_input("data", data) gmod.load_params(loaded_params) gmod.run() out = gmod.get_output(0).numpy() tvm.testing.assert_allclose(out, verify(data), atol=1e-5) def verify_rpc_gpu_remove_package_params(obj_format): if not tvm.testing.device_enabled("cuda"): print("Skip because cuda is not enabled") return mod, params = relay.testing.synthetic.get_workload() with relay.build_config(opt_level=3): complied_graph_lib = relay.build_module.build(mod, "cuda", params=params) from tvm.contrib import utils temp = utils.tempdir() if obj_format == ".so": file_name = "deploy_lib.so" else: assert obj_format == ".tar" file_name = "deploy_lib.tar" path_lib = temp.relpath(file_name) complied_graph_lib_no_params = complied_graph_lib["remove_params"]() complied_graph_lib_no_params.export_library(path_lib) path_params = temp.relpath("deploy_param.params") with open(path_params, "wb") as fo: fo.write(runtime.save_param_dict(complied_graph_lib.get_params())) from tvm import rpc remote = rpc.LocalSession() remote.upload(path_lib) loaded_lib = remote.load_module(path_lib) data = np.random.uniform(-1, 1, size=input_shape(mod)).astype("float32") dev = remote.cuda() # raw api gmod = loaded_lib["default"](dev) set_input = gmod["set_input"] run = gmod["run"] get_output = gmod["get_output"] load_params = gmod["load_params"] loaded_params = bytearray(open(path_params, "rb").read()) set_input("data", tvm.nd.array(data, device=dev)) load_params(loaded_params) run() out = get_output(0).numpy() tvm.testing.assert_allclose(out, verify(data), atol=1e-5) # graph executor wrapper gmod = graph_executor.GraphModule(loaded_lib["default"](dev)) loaded_params = bytearray(open(path_params, "rb").read()) gmod.set_input("data", data) gmod.load_params(loaded_params) gmod.run() out = gmod.get_output(0).numpy() tvm.testing.assert_allclose(out, verify(data), atol=1e-5) for obj_format in [".so", ".tar"]: verify_cpu_remove_package_params(obj_format) verify_gpu_remove_package_params(obj_format) verify_rpc_cpu_remove_package_params(obj_format) verify_rpc_gpu_remove_package_params(obj_format) @tvm.testing.requires_llvm def test_debug_graph_executor(): mod, params = relay.testing.synthetic.get_workload() with relay.build_config(opt_level=3): complied_graph_lib = relay.build_module.build(mod, "llvm", params=params) data = np.random.uniform(-1, 1, size=input_shape(mod)).astype("float32") # raw api dev = tvm.cpu() try: gmod = complied_graph_lib["debug_create"]("default", dev) except: print("Skip because debug graph_executor not enabled") return set_input = gmod["set_input"] run = gmod["run"] get_output = gmod["get_output"] set_input("data", tvm.nd.array(data)) run() out = get_output(0).numpy() tvm.testing.assert_allclose(out, verify(data), atol=1e-5) # debug graph executor wrapper debug_g_mod = debug_executor.GraphModuleDebug( complied_graph_lib["debug_create"]("default", dev), [dev], complied_graph_lib.get_graph_json(), None, ) debug_g_mod.set_input("data", data) debug_g_mod.run() out = debug_g_mod.get_output(0).numpy() tvm.testing.assert_allclose(out, verify(data), atol=1e-5) @tvm.testing.requires_cudagraph def test_cuda_graph_executor(): mod, params = relay.testing.synthetic.get_workload() with tvm.transform.PassContext(opt_level=3): complied_graph_lib = relay.build_module.build(mod, "cuda", params=params) data = np.random.uniform(-1, 1, size=input_shape(mod)).astype("float32") dev = tvm.cuda() try: gmod = complied_graph_lib["cuda_graph_create"](dev) except: print("Skip because cuda_graph not enabled") return set_input = gmod["set_input"] run = gmod["run"] get_output = gmod["get_output"] set_input("data", tvm.nd.array(data)) run() out = get_output(0).numpy() tvm.testing.assert_allclose(out, verify(data), atol=1e-5) # cuda graph executor wrapper cu_gmod = cuda_graph_executor.GraphModuleCudaGraph(gmod) cu_gmod.set_input("data", data) cu_gmod.run() out = cu_gmod.get_output(0).numpy() tvm.testing.assert_allclose(out, verify(data), atol=1e-5) def test_multiple_imported_modules(): def make_func(symbol): n = tvm.te.size_var("n") Ab = tvm.tir.decl_buffer((n,), dtype="float32") i = tvm.te.var("i") stmt = tvm.tir.For( i, 0, n - 1, tvm.tir.ForKind.SERIAL, tvm.tir.BufferStore(Ab, tvm.tir.BufferLoad(Ab, [i]) + 1, [i + 1]), ) return tvm.tir.PrimFunc([Ab], stmt).with_attr("global_symbol", symbol) def make_module(mod): mod = tvm.IRModule(mod) mod = tvm.driver.build(mod, target="llvm") return mod module_main = make_module({"main": make_func("main")}) module_a = make_module({"func_a": make_func("func_a")}) module_b = make_module({"func_b": make_func("func_b")}) module_main.import_module(module_a) module_main.import_module(module_b) module_main.get_function("func_a", query_imports=True) module_main.get_function("func_b", query_imports=True) def test_num_threads(): reported = tvm.runtime.num_threads() env_threads = os.getenv("TVM_NUM_THREADS") omp_env_threads = os.getenv("OMP_NUM_THREADS") if env_threads is not None: assert reported == env_threads elif omp_env_threads is not None: assert reported == omp_env_threads else: hardware_threads = os.cpu_count() assert reported == hardware_threads or reported == hardware_threads // 2 if __name__ == "__main__": test_legacy_compatibility() test_cpu() test_gpu() test_mod_export() test_remove_package_params() test_debug_graph_executor() test_multiple_imported_modules() test_cpu_get_graph_json() test_cpu_get_graph_params_run() test_cpu_get_graph_params_compare()
https://github.com/zk-ml/tachikoma
tests/python/unittest/test_runtime_module_export.py
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. from tvm import relay from tvm.relay import testing import tvm from tvm import te import tvm.testing from tvm.contrib import utils header_file_dir_path = utils.tempdir() def gen_engine_header(): code = r""" #ifndef _ENGINE_H_ #define _ENGINE_H_ #include <cstdint> #include <string> #include <sstream> #include <vector> class Engine { }; #endif """ header_file = header_file_dir_path.relpath("gcc_engine.h") with open(header_file, "w") as f: f.write(code) def generate_engine_module(): code = r""" #include <tvm/runtime/c_runtime_api.h> #include <dlpack/dlpack.h> #include "gcc_engine.h" extern "C" void gcc_1_(float* gcc_input4, float* gcc_input5, float* gcc_input6, float* gcc_input7, float* out) { Engine engine; } """ import tvm.runtime._ffi_api gen_engine_header() csource_module = tvm.runtime._ffi_api.CSourceModuleCreate(code, "cc", [], None) return csource_module @tvm.testing.uses_gpu def test_mod_export(): def verify_gpu_mod_export(obj_format): for device in ["llvm", "cuda"]: if not tvm.testing.device_enabled(device): print("skip because %s is not enabled..." % device) return synthetic_mod, synthetic_params = relay.testing.synthetic.get_workload() synthetic_llvm_mod, synthetic_llvm_params = relay.testing.synthetic.get_workload() with tvm.transform.PassContext(opt_level=3): _, synthetic_gpu_lib, _ = relay.build_module.build( synthetic_mod, "cuda", params=synthetic_params, mod_name="cudalib" ) _, synthetic_llvm_cpu_lib, _ = relay.build_module.build( synthetic_llvm_mod, "llvm", params=synthetic_llvm_params, mod_name="llvmlib" ) temp = utils.tempdir() if obj_format == ".so": file_name = "deploy_lib.so" else: assert obj_format == ".tar" file_name = "deploy_lib.tar" path_lib = temp.relpath(file_name) synthetic_gpu_lib.import_module(synthetic_llvm_cpu_lib) synthetic_gpu_lib.export_library(path_lib) loaded_lib = tvm.runtime.load_module(path_lib) assert loaded_lib.type_key == "library" assert loaded_lib.imported_modules[0].type_key == "cuda" # dso modules are merged together assert len(loaded_lib.imported_modules) == 1 def verify_multi_dso_mod_export(obj_format): for device in ["llvm"]: if not tvm.testing.device_enabled(device): print("skip because %s is not enabled..." % device) return A = te.placeholder((1024,), name="A") B = te.compute(A.shape, lambda *i: A(*i) + 1.0, name="B") s = te.create_schedule(B.op) mod0 = tvm.build(s, [A, B], "llvm", name="myadd0") mod1 = tvm.build(s, [A, B], "llvm", name="myadd1") temp = utils.tempdir() if obj_format == ".so": file_name = "deploy_lib.so" else: assert obj_format == ".tar" file_name = "deploy_lib.tar" path_lib = temp.relpath(file_name) mod0.import_module(mod1) mod0.export_library(path_lib) loaded_lib = tvm.runtime.load_module(path_lib) assert loaded_lib.type_key == "library" # dso modules are merged assert len(loaded_lib.imported_modules) == 0 def verify_json_import_dso(obj_format): for device in ["llvm"]: if not tvm.testing.device_enabled(device): print("skip because %s is not enabled..." % device) return # Get subgraph Json. subgraph_json = ( "json_rt_0\n" + "input 0 10 10\n" + "input 1 10 10\n" + "input 2 10 10\n" + "input 3 10 10\n" + "add 4 inputs: 0 1 shape: 10 10\n" + "sub 5 inputs: 4 2 shape: 10 10\n" + "mul 6 inputs: 5 3 shape: 10 10\n" + "json_rt_1\n" + "input 0 10 10\n" + "input 1 10 10\n" + "input 2 10 10\n" + "input 3 10 10\n" + "add 4 inputs: 0 1 shape: 10 10\n" + "sub 5 inputs: 4 2 shape: 10 10\n" + "mul 6 inputs: 5 3 shape: 10 10" ) temp = utils.tempdir() subgraph_path = temp.relpath("subgraph.examplejson") with open(subgraph_path, "w") as f: f.write(subgraph_json) # Get Json and module. A = te.placeholder((1024,), name="A") B = te.compute(A.shape, lambda *i: A(*i) + 1.0, name="B") s = te.create_schedule(B.op) f = tvm.build(s, [A, B], "llvm", name="myadd") try: ext_lib = tvm.runtime.load_module(subgraph_path, "examplejson") except: print("skip because Loader of examplejson is not presented") return ext_lib.import_module(f) if obj_format == ".so": file_name = "deploy_lib.so" else: assert obj_format == ".tar" file_name = "deploy_lib.tar" path_lib = temp.relpath(file_name) ext_lib.export_library(path_lib) lib = tvm.runtime.load_module(path_lib) assert lib.type_key == "examplejson" assert lib.imported_modules[0].type_key == "library" def verify_multi_c_mod_export(): from shutil import which if which("gcc") is None: print("Skip test because gcc is not available.") for device in ["llvm"]: if not tvm.testing.device_enabled(device): print("skip because %s is not enabled..." % device) return synthetic_mod, synthetic_params = relay.testing.synthetic.get_workload() with tvm.transform.PassContext(opt_level=3): _, synthetic_cpu_lib, _ = relay.build_module.build( synthetic_mod, "llvm", params=synthetic_params ) A = te.placeholder((1024,), name="A") B = te.compute(A.shape, lambda *i: A(*i) + 1.0, name="B") s = te.create_schedule(B.op) f = tvm.build(s, [A, B], "c", name="myadd") engine_module = generate_engine_module() temp = utils.tempdir() file_name = "deploy_lib.so" path_lib = temp.relpath(file_name) synthetic_cpu_lib.import_module(f) synthetic_cpu_lib.import_module(engine_module) kwargs = {"options": ["-O2", "-std=c++17", "-I" + header_file_dir_path.relpath("")]} synthetic_cpu_lib.export_library(path_lib, fcompile=False, **kwargs) loaded_lib = tvm.runtime.load_module(path_lib) assert loaded_lib.type_key == "library" # dso modules are merged assert len(loaded_lib.imported_modules) == 0 for obj_format in [".so", ".tar"]: verify_gpu_mod_export(obj_format) verify_multi_dso_mod_export(obj_format) verify_json_import_dso(obj_format) verify_multi_c_mod_export() @tvm.testing.requires_llvm def test_import_static_library(): # Generate two LLVM modules. A = te.placeholder((1024,), name="A") B = te.compute(A.shape, lambda *i: A(*i) + 1.0, name="B") s = te.create_schedule(B.op) mod0 = tvm.build(s, [A, B], "llvm", name="myadd0") mod1 = tvm.build(s, [A, B], "llvm", name="myadd1") assert mod0.implements_function("myadd0") assert mod1.implements_function("myadd1") assert mod1.is_dso_exportable # mod1 is currently an 'llvm' module. # Save and reload it as a vanilla 'static_library'. temp = utils.tempdir() mod1_o_path = temp.relpath("mod1.o") mod1.save(mod1_o_path) mod1_o = tvm.runtime.load_static_library(mod1_o_path, ["myadd1"]) assert mod1_o.implements_function("myadd1") assert mod1_o.is_dso_exportable # Import mod1 as a static library into mod0 and compile to its own DSO. mod0.import_module(mod1_o) mod0_dso_path = temp.relpath("mod0.so") mod0.export_library(mod0_dso_path) # The imported mod1 is statically linked into mod0. loaded_lib = tvm.runtime.load_module(mod0_dso_path) assert loaded_lib.type_key == "library" assert len(loaded_lib.imported_modules) == 0 assert loaded_lib.implements_function("myadd0") assert loaded_lib.get_function("myadd0") assert loaded_lib.implements_function("myadd1") assert loaded_lib.get_function("myadd1") assert not loaded_lib.is_dso_exportable if __name__ == "__main__": tvm.testing.main()
https://github.com/zk-ml/tachikoma
tests/python/unittest/test_runtime_module_load.py
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. import tvm from tvm import te from tvm.contrib import cc, utils import ctypes import sys import numpy as np import subprocess import tvm.testing from tvm.relay.backend import Runtime runtime_py = """ import os import sys os.environ["TVM_USE_RUNTIME_LIB"] = "1" os.environ["TVM_FFI"] = "ctypes" import tvm from tvm import te import numpy as np path_dso = sys.argv[1] dtype = sys.argv[2] ff = tvm.runtime.load_module(path_dso) a = tvm.nd.array(np.zeros(10, dtype=dtype)) ff(a) np.testing.assert_equal(a.numpy(), np.arange(a.shape[0])) print("Finish runtime checking...") """ def test_dso_module_load(): if not tvm.testing.device_enabled("llvm"): return dtype = "int64" temp = utils.tempdir() def save_object(names): n = te.size_var("n") Ab = tvm.tir.decl_buffer((n,), dtype) i = te.var("i") # for i in 0 to n-1: stmt = tvm.tir.For( i, 0, n - 1, tvm.tir.ForKind.SERIAL, tvm.tir.BufferStore(Ab, tvm.tir.BufferLoad(Ab, [i]) + 1, [i + 1]), ) mod = tvm.IRModule.from_expr( tvm.tir.PrimFunc([Ab], stmt).with_attr("global_symbol", "main") ) m = tvm.driver.build(mod, target="llvm") for name in names: m.save(name) path_obj = temp.relpath("test.o") path_ll = temp.relpath("test.ll") path_bc = temp.relpath("test.bc") path_dso = temp.relpath("test.so") save_object([path_obj, path_ll, path_bc]) cc.create_shared(path_dso, [path_obj]) f1 = tvm.runtime.load_module(path_dso) f2 = tvm.runtime.load_module(path_ll) a = tvm.nd.array(np.zeros(10, dtype=dtype)) f1(a) np.testing.assert_equal(a.numpy(), np.arange(a.shape[0])) a = tvm.nd.array(np.zeros(10, dtype=dtype)) f2(a) np.testing.assert_equal(a.numpy(), np.arange(a.shape[0])) path_runtime_py = temp.relpath("runtime.py") with open(path_runtime_py, "w") as fo: fo.write(runtime_py) proc = subprocess.run( [sys.executable, path_runtime_py, path_dso, dtype], stdout=subprocess.PIPE, stderr=subprocess.STDOUT, ) assert proc.returncode == 0, f"{proc.args} exited with {proc.returncode}: {proc.stdout}" @tvm.testing.requires_gpu def test_device_module_dump(): # graph n = tvm.runtime.convert(1024) A = te.placeholder((n,), name="A") B = te.compute(A.shape, lambda *i: A(*i) + 1.0, name="B") s = te.create_schedule(B.op) # create iter var and assign them tags. num_thread = 8 bx, tx = s[B].split(B.op.axis[0], factor=num_thread) s[B].bind(bx, te.thread_axis("blockIdx.x")) s[B].bind(tx, te.thread_axis("threadIdx.x")) def check_device(device): dev = tvm.device(device, 0) if not tvm.testing.device_enabled(device): print("Skip because %s is not enabled" % device) return temp = utils.tempdir() name = "myadd_%s" % device if sys.platform == "darwin" or sys.platform.startswith("linux"): runtime = Runtime("cpp", {"system-lib": True}) f = tvm.build(s, [A, B], device, "llvm", runtime=runtime, name=name) elif sys.platform == "win32": f = tvm.build(s, [A, B], device, "llvm", name=name) else: raise ValueError("Unsupported platform") path_dso = temp.relpath("dev_lib.so") # test cross compiler function f.export_library(path_dso, cc.cross_compiler("g++")) f1 = tvm.runtime.load_module(path_dso) a = tvm.nd.array(np.random.uniform(size=1024).astype(A.dtype), dev) b = tvm.nd.array(np.zeros(1024, dtype=A.dtype), dev) f1(a, b) np.testing.assert_equal(b.numpy(), a.numpy() + 1) if sys.platform != "win32": f2 = tvm.runtime.system_lib() f2[name](a, b) np.testing.assert_equal(b.numpy(), a.numpy() + 1) def check_stackvm(device): dev = tvm.device(device, 0) if not tvm.testing.device_enabled(device): print("Skip because %s is not enabled" % device) return temp = utils.tempdir() name = "myadd_%s" % device f = tvm.build(s, [A, B], device, "stackvm", name=name) path_dso = temp.relpath("dev_lib.stackvm") f.export_library(path_dso) f1 = tvm.runtime.load_module(path_dso) a = tvm.nd.array(np.random.uniform(size=1024).astype(A.dtype), dev) b = tvm.nd.array(np.zeros(1024, dtype=A.dtype), dev) f(a, b) np.testing.assert_equal(b.numpy(), a.numpy() + 1) for device in ["cuda", "vulkan", "opencl", "metal"]: check_device(device) check_stackvm(device) def test_combine_module_llvm(): """Test combine multiple module into one shared lib.""" # graph nn = 12 n = tvm.runtime.convert(nn) A = te.placeholder((n,), name="A") B = te.compute(A.shape, lambda *i: A(*i) + 1.0, name="B") s = te.create_schedule(B.op) def check_llvm(): dev = tvm.cpu(0) if not tvm.testing.device_enabled("llvm"): print("Skip because llvm is not enabled") return temp = utils.tempdir() fadd1 = tvm.build(s, [A, B], "llvm", name="myadd1") fadd2 = tvm.build(s, [A, B], "llvm", name="myadd2") path1 = temp.relpath("myadd1.o") path2 = temp.relpath("myadd2.o") path_dso = temp.relpath("mylib.so") fadd1.save(path1) fadd2.save(path2) # create shared library with multiple functions cc.create_shared(path_dso, [path1, path2]) m = tvm.runtime.load_module(path_dso) fadd1 = m["myadd1"] fadd2 = m["myadd2"] a = tvm.nd.array(np.random.uniform(size=nn).astype(A.dtype), dev) b = tvm.nd.array(np.zeros(nn, dtype=A.dtype), dev) fadd1(a, b) np.testing.assert_equal(b.numpy(), a.numpy() + 1) fadd2(a, b) np.testing.assert_equal(b.numpy(), a.numpy() + 1) def check_system_lib(): dev = tvm.cpu(0) if not tvm.testing.device_enabled("llvm"): print("Skip because llvm is not enabled") return temp = utils.tempdir() runtime = Runtime("cpp", {"system-lib": True}) fadd1 = tvm.build(s, [A, B], "llvm", runtime=runtime, name="myadd1") fadd2 = tvm.build(s, [A, B], "llvm", runtime=runtime, name="myadd2") path1 = temp.relpath("myadd1.o") path2 = temp.relpath("myadd2.o") path_dso = temp.relpath("mylib.so") fadd1.save(path1) fadd2.save(path2) cc.create_shared(path_dso, [path1, path2]) # Load dll, will trigger system library registration ctypes.CDLL(path_dso) # Load the system wide library mm = tvm.runtime.system_lib() a = tvm.nd.array(np.random.uniform(size=nn).astype(A.dtype), dev) b = tvm.nd.array(np.zeros(nn, dtype=A.dtype), dev) mm["myadd1"](a, b) np.testing.assert_equal(b.numpy(), a.numpy() + 1) mm["myadd2"](a, b) np.testing.assert_equal(b.numpy(), a.numpy() + 1) if sys.platform != "win32": check_system_lib() check_llvm() if __name__ == "__main__": test_combine_module_llvm() test_device_module_dump() test_dso_module_load()
https://github.com/zk-ml/tachikoma
tests/python/unittest/test_runtime_profiling.py
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. import numpy as np import pytest from io import StringIO import csv import os import json import platform import tvm.testing import tvm.utils from tvm.runtime import profiler_vm from tvm import relay from tvm.relay.testing import mlp from tvm.contrib.debugger import debug_executor from tvm import rpc from tvm.contrib import utils from tvm.runtime.profiling import Report from tvm.script import tir as T def read_csv(report): f = StringIO(report.csv()) headers = [] rows = [] reader = csv.reader(f, delimiter=",") # force parsing in_header = True for row in reader: if in_header: headers = row in_header = False rows = [[] for x in headers] else: for i in range(len(row)): rows[i].append(row[i]) return dict(zip(headers, rows)) @pytest.mark.skipif(not profiler_vm.enabled(), reason="VM Profiler not enabled") @tvm.testing.skip_if_wheel_test @tvm.testing.parametrize_targets def test_vm(target, dev): dtype = "float32" x = relay.var("x", shape=(relay.Any(), relay.Any()), dtype=dtype) y = relay.var("y", shape=(relay.Any(), relay.Any()), dtype=dtype) mod = tvm.IRModule() mod["main"] = relay.Function([x, y], relay.add(x, y)) exe = relay.vm.compile(mod, target) vm = profiler_vm.VirtualMachineProfiler(exe, dev) data = np.random.rand(28, 28).astype("float32") report = vm.profile(data, data, func_name="main") assert "fused_add" in str(report) assert "Total" in str(report) assert "AllocTensorReg" in str(report) assert "AllocStorage" in str(report) assert report.configuration["Executor"] == "VM" csv = read_csv(report) assert "Hash" in csv.keys() # Ops should have a duration greater than zero. assert all( [ float(dur) > 0 for dur, name in zip(csv["Duration (us)"], csv["Name"]) if name[:5] == "fused" ] ) # AllocTensor or AllocStorage may be cached, so their duration could be 0. assert all( [ float(dur) >= 0 for dur, name in zip(csv["Duration (us)"], csv["Name"]) if name[:5] != "fused" ] ) @tvm.testing.parametrize_targets def test_graph_executor(target, dev): mod, params = mlp.get_workload(1) exe = relay.build(mod, target, params=params) gr = debug_executor.create(exe.get_graph_json(), exe.lib, dev) data = np.random.rand(1, 1, 28, 28).astype("float32") report = gr.profile(data=data) assert "fused_nn_softmax" in str(report) assert "Total" in str(report) assert "Hash" in str(report) assert "Graph" in str(report) @tvm.testing.parametrize_targets("cuda", "llvm") @pytest.mark.skipif( tvm.get_global_func("runtime.profiling.PAPIMetricCollector", allow_missing=True) is None, reason="PAPI profiling not enabled", ) def test_papi(target, dev): target = tvm.target.Target(target) if str(target.kind) == "llvm": metric = "PAPI_FP_OPS" elif str(target.kind) == "cuda": metric = "cuda:::event:shared_load:device=0" else: pytest.skip(f"Target {target.kind} not supported by this test") mod, params = mlp.get_workload(1) exe = relay.vm.compile(mod, target, params=params) vm = profiler_vm.VirtualMachineProfiler(exe, dev) data = tvm.nd.array(np.random.rand(1, 1, 28, 28).astype("float32"), device=dev) report = vm.profile( data, func_name="main", collectors=[tvm.runtime.profiling.PAPIMetricCollector({dev: [metric]})], ) assert metric in str(report) csv = read_csv(report) assert metric in csv.keys() assert any([float(x) > 0 for x in csv[metric]]) @tvm.testing.requires_llvm def test_json(): mod, params = mlp.get_workload(1) exe = relay.vm.compile(mod, "llvm", params=params) vm = profiler_vm.VirtualMachineProfiler(exe, tvm.cpu()) data = np.random.rand(1, 1, 28, 28).astype("float32") report = vm.profile(data, func_name="main") parsed = json.loads(report.json()) assert "device_metrics" in parsed assert "calls" in parsed assert "configuration" in parsed assert "Duration (us)" in parsed["calls"][0] assert "microseconds" in parsed["calls"][0]["Duration (us)"] assert len(parsed["calls"]) > 0 for call in parsed["calls"]: assert isinstance(call["Name"]["string"], str) assert isinstance(call["Count"]["count"], int) assert isinstance(call["Duration (us)"]["microseconds"], float) @tvm.testing.requires_llvm def test_rpc_vm(): server = rpc.Server(key="profiling") remote = rpc.connect("127.0.0.1", server.port, key="profiling") mod, params = mlp.get_workload(1) exe = relay.vm.compile(mod, "llvm", params=params) temp = utils.tempdir() path = temp.relpath("lib.tar") exe.mod.export_library(path) remote.upload(path) rexec = remote.load_module("lib.tar") vm = profiler_vm.VirtualMachineProfiler(rexec, remote.cpu()) report = vm.profile(tvm.nd.array(np.ones((1, 1, 28, 28), dtype="float32"), device=remote.cpu())) assert len(report.calls) > 0 def test_rpc_graph(): server = rpc.Server(key="profiling") remote = rpc.connect("127.0.0.1", server.port, key="profiling") mod, params = mlp.get_workload(1) exe = relay.build(mod, "llvm", params=params) temp = utils.tempdir() path = temp.relpath("lib.tar") exe.export_library(path) remote.upload(path) rexec = remote.load_module("lib.tar") gr = debug_executor.create(exe.get_graph_json(), rexec, remote.cpu()) data = np.random.rand(1, 1, 28, 28).astype("float32") report = gr.profile(data=data) assert len(report.calls) > 0 def test_report_serialization(): mod, params = mlp.get_workload(1) exe = relay.vm.compile(mod, "llvm", params=params) vm = profiler_vm.VirtualMachineProfiler(exe, tvm.cpu()) data = np.random.rand(1, 1, 28, 28).astype("float32") report = vm.profile(data, func_name="main") report2 = Report.from_json(report.json()) # Equality on reports compares pointers, so we compare the printed # results instead. # Use .table() instead of str(), because str() includes aggregate # and column summations whose values may be impacted by otherwise # negligible conversion errors. (2 occurrences / 3000 trials) assert report.table(aggregate=False, col_sums=False) == report2.table( aggregate=False, col_sums=False ) @T.prim_func def axpy_cpu(a: T.handle, b: T.handle, c: T.handle) -> None: A = T.match_buffer(a, [10], "float64") B = T.match_buffer(b, [10], "float64") C = T.match_buffer(c, [10], "float64") for i in range(10): C[i] = A[i] + B[i] @T.prim_func def axpy_gpu(a: T.handle, b: T.handle, c: T.handle) -> None: A = T.match_buffer(a, [10], "float64") B = T.match_buffer(b, [10], "float64") C = T.match_buffer(c, [10], "float64") for i in T.thread_binding(0, 10, "threadIdx.x"): C[i] = A[i] + B[i] @tvm.testing.parametrize_targets("cuda", "llvm") @pytest.mark.skipif( tvm.get_global_func("runtime.profiling.PAPIMetricCollector", allow_missing=True) is None, reason="PAPI profiling not enabled", ) def test_profile_function(target, dev): target = tvm.target.Target(target) if str(target.kind) == "llvm": metric = "PAPI_FP_OPS" func = axpy_cpu elif str(target.kind) == "cuda": metric = ( "cuda:::gpu__compute_memory_access_throughput.max.pct_of_peak_sustained_region:device=0" ) func = axpy_gpu else: pytest.skip(f"Target {target.kind} not supported by this test") f = tvm.build(func, target=target) a = tvm.nd.array(np.ones(10), device=dev) b = tvm.nd.array(np.ones(10), device=dev) c = tvm.nd.array(np.zeros(10), device=dev) report = tvm.runtime.profiling.profile_function( f, dev, [tvm.runtime.profiling.PAPIMetricCollector({dev: [metric]})] )(a, b, c) assert metric in report.keys() assert report[metric].value > 0 if __name__ == "__main__": tvm.testing.main()
https://github.com/zk-ml/tachikoma
tests/python/unittest/test_runtime_rpc.py
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. import tvm from tvm import te import tvm.testing import multiprocessing import os import stat import sys import time import pytest import numpy as np from tvm import rpc from tvm.relay.backend import Runtime from tvm.contrib import utils, cc from tvm.rpc.tracker import Tracker from tvm.rpc.proxy import Proxy if __name__ == "__main__": # NOTE: must live here to avoid registering PackedFunc with libtvm.so twice. tvm.testing.main() # tkonolige: The issue as I understand it is this: multiprocessing's spawn # method launches a new process and then imports the relevant modules. This # means that all registered functions must exist at the top level scope. In # this file they are, so all is well when we run this file directly. # However, when run under pytest, the functions aren't registered on the # server. I believe this is because pytest is also using multiprocessing to # run individual functions. Somewhere along the way, the imports are being # lost, so the server ends up not registering the functions. pytestmark = pytest.mark.skipif( # Windows does not support fork so we can enable Windows for testing sys.platform.startswith("win") == False and multiprocessing.get_start_method() != "fork", reason=( "pytest + multiprocessing spawn method causes tvm.register_func to " "not work on the rpc.Server." ), ) # NOTE: When writing tests, wrap remote related checking in a sub-function # to ensure all the remote resources destructs before the server terminates @tvm.testing.requires_rpc def test_bigendian_rpc(): """Test big endian rpc when there is a PowerPC RPC server available""" host = os.environ.get("TVM_POWERPC_TEST_HOST", None) port = os.environ.get("TVM_POWERPC_TEST_PORT", 9090) if host is None: return def verify_rpc(remote, target, shape, dtype): A = te.placeholder(shape, dtype=dtype) B = te.compute(A.shape, lambda i: A[i] + tvm.tir.const(1, A.dtype)) s = te.create_schedule(B.op) f = tvm.build(s, [A, B], target, name="myadd") dev = remote.cpu(0) a = tvm.nd.array(np.random.randint(0, 256, size=shape).astype(A.dtype), device=dev) b = tvm.nd.array(np.zeros(shape).astype(A.dtype), device=dev) temp = utils.tempdir() path_dso = temp.relpath("dev_lib.o") f.save(path_dso) remote.upload(path_dso) f = remote.load_module("dev_lib.o") f(a, b) tvm.testing.assert_allclose(a.numpy() + 1, b.numpy()) print("Test RPC connection to PowerPC...") remote = rpc.connect(host, port) target = "llvm -mtriple=powerpc-linux-gnu" for dtype in ["float32", "float64", "int32", "int8"]: verify_rpc(remote, target, (10,), dtype) @tvm.testing.requires_rpc def test_rpc_simple(): server = rpc.Server(key="x1") client = rpc.connect("127.0.0.1", server.port, key="x1") def check_remote(): f1 = client.get_function("rpc.test.addone") assert f1(10) == 11 f3 = client.get_function("rpc.test.except") with pytest.raises(tvm._ffi.base.TVMError): f3("abc") f2 = client.get_function("rpc.test.strcat") assert f2("abc", 11) == "abc:11" check_remote() @tvm.testing.requires_rpc def test_rpc_simple_wlog(): server = rpc.Server(key="x1") client = rpc.connect("127.0.0.1", server.port, key="x1", enable_logging=True) def check_remote(): f1 = client.get_function("rpc.test.addone") assert f1(10) == 11 f3 = client.get_function("rpc.test.except") with pytest.raises(tvm._ffi.base.TVMError): f3("abc") f2 = client.get_function("rpc.test.strcat") assert f2("abc", 11) == "abc:11" check_remote() @tvm.testing.requires_rpc def test_rpc_runtime_string(): server = rpc.Server(key="x1") client = rpc.connect("127.0.0.1", server.port, key="x1") def check_remote(): func = client.get_function("rpc.test.runtime_str_concat") x = tvm.runtime.container.String("abc") y = tvm.runtime.container.String("def") assert str(func(x, y)) == "abcdef" check_remote() @tvm.testing.requires_rpc def test_rpc_array(): server = rpc.Server() remote = rpc.connect("127.0.0.1", server.port) def check_remote(): x = np.ones((3, 4)) r_cpu = tvm.nd.array(x, remote.cpu(0)) assert str(r_cpu.device).startswith("remote") np.testing.assert_equal(r_cpu.numpy(), x) fremote = remote.get_function("rpc.test.remote_array_func") fremote(r_cpu) check_remote() @tvm.testing.requires_rpc def test_rpc_large_array(): # testcase of large array creation server = rpc.Server() remote = rpc.connect("127.0.0.1", server.port) def check_remote(): dev = remote.cpu(0) a_np = np.ones((5041, 720)).astype("float32") b_np = np.ones((720, 192)).astype("float32") a = tvm.nd.array(a_np, dev) b = tvm.nd.array(b_np, dev) np.testing.assert_equal(a.numpy(), a_np) np.testing.assert_equal(b.numpy(), b_np) check_remote() @tvm.testing.requires_rpc def test_rpc_echo(): def check(remote): fecho = remote.get_function("testing.echo") assert fecho(1, 2, 3) == 1 assert fecho(100, 2, 3) == 100 assert fecho("xyz") == "xyz" assert bytes(fecho(bytearray(b"123"))) == b"123" with pytest.raises(RuntimeError): raise_err = remote.get_function("testing.test_raise_error_callback")("RuntimeError") raise_err() remote.cpu().sync() with pytest.raises(AttributeError): f3 = remote.system_lib()["notexist"] temp = rpc.server._server_env([]) server = rpc.Server() client = rpc.connect("127.0.0.1", server.port) check(rpc.LocalSession()) check(client) def check_minrpc(): if tvm.get_global_func("rpc.CreatePipeClient", allow_missing=True) is None: return # Test minrpc server. temp = utils.tempdir() minrpc_exec = temp.relpath("minrpc") tvm.rpc.with_minrpc(cc.create_executable)(minrpc_exec, []) check(rpc.PopenSession(minrpc_exec)) # minrpc on the remote server = rpc.Server() client = rpc.connect( "127.0.0.1", server.port, session_constructor_args=["rpc.PopenSession", open(minrpc_exec, "rb").read()], ) check(client) check_minrpc() @tvm.testing.requires_rpc def test_rpc_file_exchange(): server = rpc.Server() remote = rpc.connect("127.0.0.1", server.port) def check_remote(): blob = bytearray(np.random.randint(0, 10, size=(10))) remote.upload(blob, "dat.bin") rev = remote.download("dat.bin") assert rev == blob check_remote() @tvm.testing.requires_rpc @tvm.testing.requires_llvm def test_rpc_remote_module(): # graph n = tvm.runtime.convert(102) A = te.placeholder((n,), name="A") B = te.compute(A.shape, lambda *i: A(*i) + 1.0, name="B") s = te.create_schedule(B.op) server0 = rpc.Server(key="x0") server1 = rpc.Server(key="x1") client = rpc.connect( "127.0.0.1", server0.port, key="x0", session_constructor_args=["rpc.Connect", "127.0.0.1", server1.port, "x1", False], ) def check_remote(remote): temp = utils.tempdir() dev = remote.cpu(0) f = tvm.build(s, [A, B], "llvm", name="myadd") path_dso = temp.relpath("dev_lib.so") f.export_library(path_dso) remote.upload(path_dso) f1 = remote.load_module("dev_lib.so") a = tvm.nd.array(np.random.uniform(size=102).astype(A.dtype), dev) b = tvm.nd.array(np.zeros(102, dtype=A.dtype), dev) time_f = f1.time_evaluator(f1.entry_name, remote.cpu(0), number=10) cost = time_f(a, b).mean print("%g secs/op" % cost) np.testing.assert_equal(b.numpy(), a.numpy() + 1) # Download the file from the remote path_tar = temp.relpath("dev_lib.tar") f.export_library(path_tar) remote.upload(path_tar) local_download_path = temp.relpath("dev_lib.download.so") with open(local_download_path, "wb") as fo: fo.write(remote.download_linked_module("dev_lib.tar")) fupdated = tvm.runtime.load_module(local_download_path) a = tvm.nd.array(np.random.uniform(size=102).astype(A.dtype), tvm.cpu(0)) b = tvm.nd.array(np.zeros(102, dtype=A.dtype), tvm.cpu(0)) fupdated(a, b) np.testing.assert_equal(b.numpy(), a.numpy() + 1) def check_minrpc(): if tvm.get_global_func("rpc.CreatePipeClient", allow_missing=True) is None: return # export to minrpc temp = utils.tempdir() runtime = Runtime("cpp", {"system-lib": True}) f = tvm.build(s, [A, B], "llvm", name="myadd", runtime=runtime) path_minrpc = temp.relpath("dev_lib.minrpc") f.export_library(path_minrpc, rpc.with_minrpc(cc.create_executable)) with pytest.raises(RuntimeError): rpc.PopenSession("filenotexist") # statrt the minrpc session. remote = tvm.rpc.PopenSession(path_minrpc) dev = remote.cpu(0) f1 = remote.system_lib() a = tvm.nd.array(np.random.uniform(size=102).astype(A.dtype), dev) b = tvm.nd.array(np.zeros(102, dtype=A.dtype), dev) time_f = f1.time_evaluator("myadd", remote.cpu(0), number=1) cost = time_f(a, b).mean np.testing.assert_equal(b.numpy(), a.numpy() + 1) # change to not executable os.chmod(path_minrpc, stat.S_IRUSR) with pytest.raises(RuntimeError): rpc.PopenSession(path_minrpc) def check_remote_link_cl(remote): """Test function to run remote code such as cl This is not enabled because there is forking issue of TVM runtime when server launches after OpenCL runtime initializes. We leave it as an example on how to do rpc when we want to do linking on remote. """ if not tvm.testing.device_enabled("opencl"): print("Skip because opencl is not enabled") return temp = utils.tempdir() dev = remote.cl(0) s = te.create_schedule(B.op) xo, xi = s[B].split(B.op.axis[0], factor=32) s[B].bind(xo, te.thread_axis("blockIdx.x")) s[B].bind(xi, te.thread_axis("threadIdx.x")) f = tvm.build(s, [A, B], "opencl --host=llvm", name="myadd") # Option 1: save modules separately and rely on remote compiler path_o = temp.relpath("myadd.o") path_cl = temp.relpath("myadd.cl") path_json = temp.relpath("myadd.tvm_meta.json") f.save(path_o) f.imported_modules[0].save(path_cl) remote.upload(path_o) remote.upload(path_cl) # upload meta data remote.upload(path_json) fhost = remote.load_module("myadd.o") fdev = remote.load_module("myadd.cl") fhost.import_module(fdev) a = tvm.nd.array(np.random.uniform(size=102).astype(A.dtype), dev) b = tvm.nd.array(np.zeros(102, dtype=A.dtype), dev) fhost(a, b) np.testing.assert_equal(b.numpy(), a.numpy() + 1) # Option 2: export library as a tar ball then handled by remote compiler path_tar = temp.relpath("myadd.tar") f.export_library(path_tar) remote.upload(path_tar) fhost = remote.load_module("myadd.tar") a = tvm.nd.array(np.random.uniform(size=102).astype(A.dtype), dev) b = tvm.nd.array(np.zeros(102, dtype=A.dtype), dev) fhost(a, b) np.testing.assert_equal(b.numpy(), a.numpy() + 1) check_remote(rpc.LocalSession()) check_remote(client) check_minrpc() @tvm.testing.requires_rpc def test_rpc_return_func(): server = rpc.Server(key="x1") client = rpc.connect("127.0.0.1", server.port, key="x1") def check_remote(): f1 = client.get_function("rpc.test.add_to_lhs") fadd = f1(10) assert fadd(12) == 22 check_remote() @tvm.testing.requires_rpc def test_rpc_session_constructor_args(): # start server server0 = rpc.Server(key="x0") server1 = rpc.Server(key="x1") def check_multi_hop(): # use server0 as proxy to connect to server1 client = rpc.connect( "127.0.0.1", server0.port, key="x0", session_constructor_args=["rpc.Connect", "127.0.0.1", server1.port, "x1", False], ) fecho = client.get_function("testing.echo") assert fecho(1, 2, 3) == 1 assert fecho(100, 2, 3) == 100 assert fecho("xyz") == "xyz" assert bytes(fecho(bytearray(b"123"))) == b"123" nd = tvm.nd.array([1, 2, 3], device=client.cpu(0)) assert nd.numpy()[1] == 2 def check_error_handling(): with pytest.raises(tvm.error.RPCError): client = rpc.connect( "127.0.0.1", server0.port, key="x0", session_constructor_args=["rpc.NonExistingConstructor"], ) check_multi_hop() check_error_handling() @tvm.testing.requires_rpc def test_rpc_return_ndarray(): # start server server = rpc.Server(key="x1") client = rpc.connect("127.0.0.1", server.port, key="x1") m = client.get_function("rpc.test.remote_return_nd") get_arr = m("get_arr") ref_count = m("ref_count") get_elem = m("get_elem") get_arr_elem = m("get_arr_elem") # array test def run_arr_test(): arr = get_arr() assert get_elem(0) == 0.0 assert get_arr_elem(arr, 0) == 0.0 run_arr_test() @tvm.testing.requires_rpc def test_local_func(): client = rpc.LocalSession() def check_remote(): f1 = client.get_function("rpc.test.add_to_lhs") fadd = f1(10) assert fadd(12) == 22 blob = bytearray(np.random.randint(0, 10, size=(10))) client.upload(blob, "dat.bin") rev = client.download("dat.bin") assert rev == blob check_remote() @tvm.testing.requires_rpc def test_rpc_tracker_register(): # test registration tracker = Tracker(port=9000, port_end=10000) device_key = "test_device" server1 = rpc.Server( host="127.0.0.1", port=9000, port_end=10000, key=device_key, tracker_addr=("127.0.0.1", tracker.port), ) server2 = rpc.Server( host="127.0.0.1", port=9000, port_end=10000, key=device_key, tracker_addr=("127.0.0.1", tracker.port), custom_addr="test_addr", # this is a test address, which is unable to connect ) time.sleep(1) client = rpc.connect_tracker("127.0.0.1", tracker.port) def exist_address(summary, key, host, port): server_info = summary["server_info"] for device in server_info: if device["key"] == "server:%s" % key: addr = device["addr"] if (host is None or host == addr[0]) and port == addr[1]: return True return False summary = client.summary() assert summary["queue_info"][device_key]["free"] == 2 assert exist_address(summary, device_key, "127.0.0.1", server1.port) assert exist_address(summary, device_key, "test_addr", server2.port) remote = client.request(device_key) summary = client.summary() assert summary["queue_info"][device_key]["free"] == 1 del remote time.sleep(1) summary = client.summary() assert summary["queue_info"][device_key]["free"] == 2 server1.terminate() time.sleep(1) summary = client.summary() assert summary["queue_info"][device_key]["free"] == 1 assert not exist_address(summary, device_key, "127.0.0.1", server1.port) assert exist_address(summary, device_key, "test_addr", server2.port) server2.terminate() time.sleep(1) summary = client.summary() assert summary["queue_info"][device_key]["free"] == 0 assert not exist_address(summary, device_key, "test_addr", server2.port) tracker.terminate() def _target(host, port, device_key, timeout): client = rpc.connect_tracker(host, port) remote = client.request(device_key, session_timeout=timeout) while True: pass remote.cpu() @tvm.testing.requires_rpc def test_rpc_tracker_request(): # test concurrent request tracker = Tracker(port=9000, port_end=10000) device_key = "test_device" server = rpc.Server( port=9000, port_end=10000, key=device_key, tracker_addr=("127.0.0.1", tracker.port), ) client = rpc.connect_tracker("127.0.0.1", tracker.port) proc1 = multiprocessing.Process(target=_target, args=("127.0.0.1", tracker.port, device_key, 4)) proc2 = multiprocessing.Process( target=_target, args=("127.0.0.1", tracker.port, device_key, 200) ) proc1.start() time.sleep(0.5) proc2.start() time.sleep(0.5) summary = client.summary() assert summary["queue_info"][device_key]["free"] == 0 assert summary["queue_info"][device_key]["pending"] == 1 proc1.terminate() proc1.join() time.sleep(0.5) summary = client.summary() assert summary["queue_info"][device_key]["free"] == 0 assert summary["queue_info"][device_key]["pending"] == 0 proc2.terminate() proc2.join() server.terminate() tracker.terminate() @tvm.testing.requires_rpc def test_rpc_tracker_via_proxy(): """ tracker / \ Host -- Proxy -- RPC server """ device_key = "test_device" tracker_server = Tracker(port=9000, port_end=9100) proxy_server = Proxy( host=tracker_server.host, port=8888, port_end=8988, tracker_addr=(tracker_server.host, tracker_server.port), ) server1 = rpc.Server( host=proxy_server.host, port=proxy_server.port, key=device_key, tracker_addr=(tracker_server.host, tracker_server.port), is_proxy=True, ) server2 = rpc.Server( host=proxy_server.host, port=proxy_server.port, key=device_key, tracker_addr=(tracker_server.host, tracker_server.port), is_proxy=True, ) client = rpc.connect_tracker(tracker_server.host, tracker_server.port) remote1 = client.request(device_key, session_timeout=30) # pylint: disable=unused-variable remote2 = client.request(device_key, session_timeout=30) # pylint: disable=unused-variable server2.terminate() server1.terminate() proxy_server.terminate() tracker_server.terminate()
https://github.com/zk-ml/tachikoma
tests/python/unittest/test_runtime_trace.py
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. import tvm from tvm import te import numpy as np def test_trace_default_action(): n = 2 x = te.placeholder((n, n, n), name="X", dtype="float32") y = te.compute(x.shape, lambda i, j, k: tvm.tir.trace([i, j, k, x[i][j][k]])) s = te.create_schedule(y.op) f = tvm.build(s, [x, y], target="llvm") xnd = tvm.nd.array(np.ones((n, n, n), dtype=x.dtype)) ynd = tvm.nd.array(np.zeros((n, n, n), dtype=y.dtype)) f(xnd, ynd) def test_trace_expr_assign(): @tvm.register_func("tvm.tir.trace_callback2") def trace_buffer(x): return def check_assign(dtype): n = 4 x = te.placeholder((n, n, n), name="X", dtype=dtype) y = te.compute( x.shape, lambda i, j, k: tvm.tir.trace([x[i][j][k]], "tvm.tir.trace_callback2") ) z = te.compute( x.shape, lambda i, j, k: tvm.tir.trace([y[i][j][k]], "tvm.tir.trace_callback2") ) s = te.create_schedule(z.op) f = tvm.build(s, [x, y, z], "llvm") xnd = tvm.nd.array(np.ones((n, n, n), dtype=x.dtype)) ynd = tvm.nd.array(np.zeros((n, n, n), dtype=y.dtype)) znd = tvm.nd.array(np.zeros((n, n, n), dtype=z.dtype)) f(xnd, ynd, znd) assert np.array_equal(xnd.numpy(), np.ones((n, n, n))) assert np.array_equal(ynd.numpy(), np.ones((n, n, n))) assert np.array_equal(znd.numpy(), np.ones((n, n, n))) for t in ["float64", "float32", "int64", "int32"]: check_assign(t) def test_trace_expr_sum_generated(): @tvm.register_func("tvm.tir.trace_callback3") def trace_buffer(x): return def check_expr_sum(dtype): n = 4 a = te.placeholder((n, n, n), name="a", dtype=dtype) b = te.placeholder((n, n, n), name="b", dtype=dtype) c = te.compute( a.shape, lambda i, j, k: tvm.tir.trace([a[i][j][k]], "tvm.tir.trace_callback3") + tvm.tir.trace([b[i][j][k]], "tvm.tir.trace_callback3"), ) s = te.create_schedule(c.op) f = tvm.build(s, [a, b, c]) xnd = tvm.nd.array(np.array(np.ones((n, n, n), dtype=a.dtype))) ynd = tvm.nd.array(np.array(np.ones((n, n, n), dtype=b.dtype))) znd = tvm.nd.array(np.zeros((n, n, n), dtype=c.dtype)) f(xnd, ynd, znd) assert np.array_equal(znd.numpy(), xnd.numpy() + ynd.numpy()) for t in ["float64", "float32", "int64", "int32"]: check_expr_sum(t) def test_trace_expr_sum_args(): @tvm.register_func("tvm.tir.trace_silent") def silent(*args): return def check_expr_sum(dtype): n = 4 a = te.placeholder((n, n, n), name="a", dtype=dtype) b = te.placeholder((n, n, n), name="b", dtype=dtype) e = te.placeholder((n, n, n), name="e", dtype=dtype) d = te.placeholder((n, n, n), name="d", dtype=dtype) c = te.compute( a.shape, lambda i, j, k: tvm.tir.trace([i, j, k, a[i][j][k]], "tvm.tir.trace_silent") + tvm.tir.trace([i, j, k, b[i][j][k]], "tvm.tir.trace_silent") + tvm.tir.trace([i, j, k, d[i][j][k]], "tvm.tir.trace_silent") + tvm.tir.trace([i, j, k, e[i][j][k]], "tvm.tir.trace_silent"), ) s = te.create_schedule(c.op) f = tvm.build(s, [a, b, d, e, c]) a_nd = tvm.nd.array(np.array(np.ones((n, n, n), dtype=a.dtype))) b_nd = tvm.nd.array(np.array(np.ones((n, n, n), dtype=b.dtype))) d_nd = tvm.nd.array(np.array(np.ones((n, n, n), dtype=d.dtype))) e_nd = tvm.nd.array(np.array(np.ones((n, n, n), dtype=e.dtype))) c_nd = tvm.nd.array(np.zeros((n, n, n), dtype=c.dtype)) f(a_nd, b_nd, d_nd, e_nd, c_nd) assert np.array_equal( c_nd.numpy(), a_nd.numpy() + b_nd.numpy() + d_nd.numpy() + e_nd.numpy() ) for t in ["float64", "float32", "int64", "int32"]: check_expr_sum(t) def test_trace_expr_sum_custom(): @tvm.register_func("tvm.tir.trace_callback4") def trace_buffer(x): return def check_expr_sum_custom(dtype): n = 4 a = te.placeholder((n, n), name="a", dtype=dtype) b = te.placeholder((n, n), name="b", dtype=dtype) c = te.compute( a.shape, lambda i, j: tvm.tir.trace([a[i][j]], "tvm.tir.trace_callback4") + tvm.tir.trace([b[i][j]], "tvm.tir.trace_callback4"), ) s = te.create_schedule(c.op) f = tvm.build(s, [a, b, c]) npa = np.array([[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0, 1]], dtype=a.dtype) npb = np.array([[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0, 1]], dtype=a.dtype) xnd = tvm.nd.array(npa) ynd = tvm.nd.array(npb) znd = tvm.nd.array(np.zeros((n, n), dtype=c.dtype)) f(xnd, ynd, znd) assert np.array_equal(znd.numpy(), npa + npb) for t in ["float64", "float32", "int64", "int32"]: check_expr_sum_custom(t) def test_trace_can_change_traced_value_int(): @tvm.register_func("tvm.tir.trace_change_int_first") def trace_buffer(x): return 13 @tvm.register_func("tvm.tir.trace_change_int_second") def trace_buffer(x): return 14 def check_assign(dtype): n = 4 x = te.placeholder((n,), name="X", dtype=dtype) y = te.compute(x.shape, lambda i: tvm.tir.trace([x[i]], "tvm.tir.trace_change_int_first")) z = te.compute(x.shape, lambda i: tvm.tir.trace([y[i]], "tvm.tir.trace_change_int_second")) s = te.create_schedule(z.op) f = tvm.build(s, [x, y, z], "llvm") xnd = tvm.nd.array(np.ones((n,), dtype=x.dtype)) ynd = tvm.nd.array(np.zeros((n,), dtype=y.dtype)) znd = tvm.nd.array(np.zeros((n,), dtype=z.dtype)) f(xnd, ynd, znd) check_array_first = np.array([13, 13, 13, 13]) check_array_second = np.array([14, 14, 14, 14]) assert np.array_equal(ynd.numpy(), check_array_first) assert np.array_equal(znd.numpy(), check_array_second) for t in ["int64", "int32"]: check_assign(t) def test_trace_can_change_traced_value_float(): @tvm.register_func("tvm.tir.trace_change_float_first") def trace_buffer(x): return 13.0 @tvm.register_func("tvm.tir.trace_change_float_second") def trace_buffer(x): return 14.0 def check_assign(dtype): n = 4 x = te.placeholder((n,), name="X", dtype=dtype) y = te.compute(x.shape, lambda i: tvm.tir.trace([x[i]], "tvm.tir.trace_change_float_first")) z = te.compute( x.shape, lambda i: tvm.tir.trace([y[i]], "tvm.tir.trace_change_float_second") ) s = te.create_schedule(z.op) f = tvm.build(s, [x, y, z], "llvm") xnd = tvm.nd.array(np.ones((n,), dtype=x.dtype)) ynd = tvm.nd.array(np.zeros((n,), dtype=y.dtype)) znd = tvm.nd.array(np.zeros((n,), dtype=z.dtype)) f(xnd, ynd, znd) check_array_first = np.array([13.0, 13.0, 13.0, 13.0]) check_array_second = np.array([14.0, 14.0, 14.0, 14.0]) assert np.array_equal(ynd.numpy(), check_array_first) assert np.array_equal(znd.numpy(), check_array_second) for t in ["float64", "float32"]: check_assign(t) if __name__ == "__main__": test_trace_expr_assign() test_trace_expr_sum_generated() test_trace_expr_sum_custom() test_trace_expr_sum_args() test_trace_default_action() test_trace_can_change_traced_value_int() test_trace_can_change_traced_value_float()
https://github.com/zk-ml/tachikoma
tests/python/unittest/test_runtime_vm_profiler.py
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. import numpy as np import tvm import tvm.testing from tvm.runtime import profiler_vm from tvm import relay from tvm.relay.testing import mlp @tvm.testing.parametrize_targets def test_basic(dev, target): mod, params = mlp.get_workload(batch_size=1) if not profiler_vm.enabled(): return exe = relay.vm.compile(mod, target, params=params) code, lib = exe.save() des_exe = tvm.runtime.vm.Executable.load_exec(code, lib) vm = profiler_vm.VirtualMachineProfiler(des_exe, dev) data = np.random.rand(1, 1, 28, 28).astype("float32") res = vm.profile(tvm.nd.array(data), func_name="main") assert "softmax" in str(res) def test_vm_reshape_and_copy(): target = "llvm" dev = tvm.gpu() x_np = np.random.uniform(size=(8, 16)).astype("float32") x = relay.var("x", shape=(8, 16), dtype="float32") y = relay.reshape(x, [-1, 4, 8]) mod = tvm.IRModule() mod["main"] = relay.Function([x], y) with tvm.transform.PassContext(opt_level=3): exec = relay.vm.compile(mod, "llvm") assert "reshape_tensor" in exec.bytecode vm = profiler_vm.VirtualMachineProfiler(exec, dev) vm.profile(tvm.nd.array(x_np)) if __name__ == "__main__": tvm.testing.main()
https://github.com/zk-ml/tachikoma
tests/python/unittest/test_slice_tir.py
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. import tvm import tvm.testing from tvm.script import tir as T import pytest # --------------------------------------------------------------------------------------------------- # ABOUT THIS FILE: # --------------------------------------------------------------------------------------------------- # We (cconvey / OctoML) are working on a sequence of PRs to allow a single TIR primfunc's # AST to be sliced into multiple partitiones, where each partition will be converted into # a new TIR primfunc. (See https://en.wikipedia.org/wiki/Program_slicing). # # The unit tests below provide a roadmap for that sequence of PRs; each PR should allow # one more of these tests to pass. # # NOTE: These unit tests may change as work progresses. They aren't meant to # indicate hard requirements. # NOTE! The `tvm.testing.CompareBeforeAfter` class provides TWO useful mechanisms for # these tests: # # (a) It lets us specify code snippets which are valid Python, but which aren't YET # recognized as valid TVMScript. This allows unit tests for new constructs, # e.g. 'call_tir(...)' to simply be disabled rather than fully commented out. # # (b) It lets us structurally compare the TIR bodies of two primfuncs. # # Note that some of the tests below will require the structural comparison of # two entire IRModules, not just primfuncs. This will require adding functionality # to the `CompareBeforeAfter` class, or implementing that level of comparison within # the individual unit tests. # # Some of the unit tests below which require whole-IRModule comparison. For expedience # we simply comment out the (early draft) bodies of those unit tests, rather than # hacking their structure to get the benefits of (a). # --------------------------------------------------------------------------------------------------- # 'CALL_TIR' (AND RELATED) CAVEATS: # --------------------------------------------------------------------------------------------------- # (c) "call_tir" is a placeholder name. # The TVM "Relax" effort also defines a node named "call_tir", which is likely # become something different from what we're calling "call_tir" here. So # we may rename *this* "call_tir" during implementation. # # (d) For "call_tir" calls, the syntax/semantics for passing buffer regions is still # an active area of development. So that detail of these unit tests is likely # to change. # # (e) The specific string "extract_as_subroutine" used to annotate some IR Blocks, # i.e., `T.annotate("extract_as_subroutine", ...)`, may change as work progresses. # --------------------------------------------------------------------------------------------------- # step 1: Simply passes Python / TVMScript parsing. # --------------------------------------------------------------------------------------------------- # # The only requirement for this test is that the TVMScript parser # doesn't raise an error when encountering `T.call_tir(foo)`, # where "foo" is a syntactically valid TVMScript function name. # # NOTE! The role of this unit test should evolve as follows: # 1) Initially the test should fail, because we haven't yet changed the TVMScript # parser to support 'call_tir'. # # 2) Initial TVMScript support for 'call_tir' will be minimal, essentially ignoring # it. This test should pass once that change is made. # # 3) As support for 'call_tir' becomes more complete, this test should once again # fail, because the specified callee doesn't exist. This test should be updated # to once again expect failure. @pytest.mark.xfail(reason="Awaiting TVMScript support for 'call_tir' token.", strict=True) class TestParseCallTIR(tvm.testing.CompareBeforeAfter): """ Simply confirm that the TIR node `call_tir` doesn't interfere with the successful parsing of the TVMScript. """ def before(): T.call_tir(add_one) T.evalute(0) def expected(): T.evaluate(0) # Provide a trivial 'transform' pass to satisfy the requirements of # tvm.testing.CompareBeforeAfter. transform = tvm.tir.transform.prim_func_pass(lambda func, _mod, _ctx: func, 0) # --------------------------------------------------------------------------------------------------- # step 2: transform annotated block ==> separate primfuncs + call_tir # # NOTE: This early-draft version of the unit test contains pseudocode to compare entire IRModule # objects, analogously to how tvm.testing.CompareBeforeAfter compares two primfuncs. # TVM's testing infrastructure currently has no such functionality, and it will need to be added # (or approximated) to make this unit test useable. # --------------------------------------------------------------------------------------------------- @pytest.mark.xfail( reason="Awaiting TVMScript support for 'call_tir' and T.annotation(\"extract_as_subroutine\").", strict=True, ) class TestAnnotateAndSliceTIR(tvm.testing.CompareBeforeAfter): # def test_annotate_and_slice(): # @tvm.script.ir_module # class irmod_before: # @T.prim_func # def main(A: T.Buffer[(1,), "int8"): # #A = T.match_buffer(a, (1,), "int8") # A[0] = 0 # with T.block("block_foo"): # optional: give this block a name, perhaps for testing? # # NOTE: nice to have: human control over name used for the generated callee # T.annotate("extract_as_subroutine", "add_one") # A[0] += 1 # return 42 # # @tvm.script.ir_module # class irmod_after: # @T.prim_func # def main(): # A = T.buffer[[1], "int8"] # A[0] = 0 # with T.block("block_foo"): # call_tir(add_one, A) # # @T.prim_func # def add_one(X: T.buffer[[1], "int8"]): # X[0] += 1 pass # --------------------------------------------------------------------------------------------------- # step 3: transform call_tir ==> packed call # --------------------------------------------------------------------------------------------------- @pytest.mark.xfail( reason="Awaiting TVMScript support for lowering of 'T.call_tir' to 'T.call_packed'.", strict=True, ) class TestLowerCallTir(tvm.testing.CompareBeforeAfter): # @tvm.script.ir_module # class test_lower_before: # @T.prim_func # def main(): # A = T.buffer[[1], "int8"] # A[0] = 0 # with T.block(): # call_tir(add_one, A) # # @T.prim_func # def add_one(X: T.buffer[[1], "int8"]): # X[0] += 1 # # @tvm.script.ir_module # class test_lower_after: # @T.prim_func # def main(): # A = T.buffer[[1], "int8"] # A[0] = 0 # with T.block(): # # TODO: figure out the right TVMScript thing to do here # call_packed(add_one, A) # not sure about this function / interface # # @T.prim_func # def add_one(X: T.buffer[[1], "int8"]): # X[0] += 1 # # TODO(cconvey): additional test logic needed. # NOTE(lunderberg): Will also need a `transform` defined here. # I think we'll want it to occur in `tvm.tir.transform.MakePackedAPI`. pass # --------------------------------------------------------------------------------------------------- # step 4: end-to-end functionality # --------------------------------------------------------------------------------------------------- @pytest.mark.xfail(reason="Awaiting end-to-end support for Primfunc slicing.", strict=True) class TestPrimfuncSlicingEndToEnd(tvm.testing.CompareBeforeAfter): # @tvm.script.ir_module # class test_annotate_before: # @T.prim_func # def main(): # A = T.buffer[[1], "int8"] # A[0] = 0 # with T.block(): # optional: give this block a name, perhaps for testing? # # NOTE: nice to have: human control over name used for the generated callee # T.annotate("extract_as_subroutine", "add_one") # A[0] += 1 # assert(A[0] == 1) # # TODO(cconvey): additional test logic needed: # Starting with the IRModule shown above, end up with a running test that # module actually increments A[0] on Hexagon and x86-64 Linux. # # NOTE(lunderberg): We can use the function calls currently generated by `SplitHostDevice` as a template # (see https://github.com/apache/tvm/blob/9a673faa74ed7cd715a4e011716bcce3fd2158b6/src/tir/transforms/split_host_device.cc#L336). # Overall, we'll want to output a Call node with the operation builtin::tvm_call_packed(). pass
https://github.com/zk-ml/tachikoma
tests/python/unittest/test_subwarp_reduction_cuda.py
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. import tvm import tvm.testing import numpy as np from tvm.script import tir as T @T.prim_func def reduce(a: T.handle, b: T.handle, d1: T.int32, d2: T.int32, d3: T.int32) -> None: A = T.match_buffer(a, [1, d1, d2, d3]) B = T.match_buffer(b, [1, d1, d2]) for i, j, k, l in T.grid(1, d1, d2, d3): with T.block("reduce"): vi, vj, vk, vl = T.axis.remap("SSSR", [i, j, k, l]) with T.init(): B[vi, vj, vk] = 0.0 B[vi, vj, vk] = B[vi, vj, vk] + A[vi, vj, vk, vl] @T.prim_func def reduce_max(a: T.handle, b: T.handle, d1: T.int32, d2: T.int32, d3: T.int32) -> None: A = T.match_buffer(a, [1, d1, d2, d3]) B = T.match_buffer(b, [1, d1, d2]) for i, j, k, l in T.grid(1, d1, d2, d3): with T.block("reduce"): vi, vj, vk, vl = T.axis.remap("SSSR", [i, j, k, l]) with T.init(): B[vi, vj, vk] = T.float32(-3.4028234663852886e38) B[vi, vj, vk] = T.max(B[vi, vj, vk], A[vi, vj, vk, vl]) @tvm.testing.requires_gpu @tvm.testing.requires_cuda def test_cuda_subwarp_reduction(): def check_sum(d1: int, d2: int, d3: int): _, _, _d1, _d2, _d3 = reduce.params mod = reduce.specialize({_d1: d1, _d2: d2, _d3: d3}) sch = tvm.tir.Schedule(mod) blk = sch.get_block("reduce") i, j, k, l = sch.get_loops(blk) sch.bind(i, "blockIdx.x") sch.bind(j, "threadIdx.z") sch.bind(k, "threadIdx.y") sch.bind(l, "threadIdx.x") f = tvm.build(sch.mod["main"], target="cuda") # prepare input and output array a_np = np.random.rand(1, d1, d2, d3).astype("float32") b_np = a_np.sum(axis=-1).astype("float32") a = tvm.nd.array(a_np, tvm.cuda(0)) b = tvm.nd.array(np.zeros_like(b_np), tvm.cuda(0)) # launch kernel f(a, b) tvm.testing.assert_allclose(b.numpy(), b_np, rtol=1e-6, atol=1e-6) def check_max(d1: int, d2: int, d3: int): _, _, _d1, _d2, _d3 = reduce_max.params mod = reduce_max.specialize({_d1: d1, _d2: d2, _d3: d3}) sch = tvm.tir.Schedule(mod) blk = sch.get_block("reduce") i, j, k, l = sch.get_loops(blk) sch.bind(i, "blockIdx.x") sch.bind(j, "threadIdx.z") sch.bind(k, "threadIdx.y") sch.bind(l, "threadIdx.x") f = tvm.build(sch.mod["main"], target="cuda") # prepare input and output array a_np = -np.random.rand(1, d1, d2, d3).astype("float32") b_np = a_np.max(axis=-1).astype("float32") a = tvm.nd.array(a_np, tvm.cuda(0)) b = tvm.nd.array(np.zeros_like(b_np), tvm.cuda(0)) # launch kernel f(a, b) tvm.testing.assert_allclose(b.numpy(), b_np, rtol=1e-6, atol=1e-6) for d1 in range(1, 5): for d2 in range(1, 5): for d3 in range(2, 33): check_sum(d1, d2, d3) check_max(d1, d2, d3) if __name__ == "__main__": test_cuda_subwarp_reduction()
https://github.com/zk-ml/tachikoma
tests/python/unittest/test_target_codegen_arm.py
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. import tvm from tvm import te import re import os import ctypes def test_popcount(): target = "llvm -mtriple=armv7l-none-linux-gnueabihf -mcpu=cortex-a53 -mattr=+neon" def check_correct_assembly(type, elements, counts): n = tvm.runtime.convert(elements) A = te.placeholder(n, dtype=type, name="A") B = te.compute(A.shape, lambda i: tvm.tir.popcount(A[i]), name="B") s = te.create_schedule(B.op) s[B].vectorize(s[B].op.axis[0]) f = tvm.build(s, [A, B], target) # Verify we see the correct number of vpaddl and vcnt instructions in the assembly assembly = f.get_source("asm") matches = re.findall("vpaddl", assembly) assert len(matches) == counts matches = re.findall("vcnt", assembly) assert len(matches) == 1 check_correct_assembly("uint16", 8, 1) check_correct_assembly("uint16", 4, 1) check_correct_assembly("uint32", 4, 2) check_correct_assembly("uint32", 2, 2) check_correct_assembly("uint64", 2, 3) def test_vmlal_s16(): target = "llvm -mtriple=armv7l-none-linux-gnueabihf -mcpu=cortex-a53 -mattr=+neon" def check_correct_assembly(N): K = te.size_var("K") A = te.placeholder((K, N), dtype="int8", name="A") B = te.placeholder((K, N), dtype="int8", name="B") k = te.reduce_axis((0, K)) C = te.compute( (N,), lambda n: te.sum(A[k, n].astype("int32") * B[k, n].astype("int32"), axis=[k]), name="C", ) s = te.create_schedule(C.op) s[C].vectorize(s[C].op.axis[0]) f = tvm.build(s, [A, B, C], target) # Verify we see the correct number of vmlal.s16 instructions assembly = f.get_source("asm") matches = re.findall("vmlal.s16", assembly) assert len(matches) == N // 4 check_correct_assembly(8) check_correct_assembly(16) check_correct_assembly(32) check_correct_assembly(64) def check_broadcast_correct_assembly(N): K = te.size_var("K") A = te.placeholder((K, N), dtype="int8", name="A") B = te.placeholder((K,), dtype="int8", name="B") k = te.reduce_axis((0, K)) C = te.compute( (N,), lambda n: te.sum(A[k, n].astype("int32") * B[k].astype("int32"), axis=[k]), name="C", ) s = te.create_schedule(C.op) s[C].vectorize(s[C].op.axis[0]) f = tvm.build(s, [A, B, C], target) # Verify we see the correct number of vmlal.s16 instructions assembly = f.get_source("asm") matches = re.findall("vmlal.s16", assembly) assert len(matches) == N // 4 check_broadcast_correct_assembly(8) check_broadcast_correct_assembly(16) check_broadcast_correct_assembly(32) check_broadcast_correct_assembly(64) if __name__ == "__main__": test_popcount() test_vmlal_s16()
https://github.com/zk-ml/tachikoma
tests/python/unittest/test_target_codegen_blob.py
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. import numpy as np from tvm import relay from tvm.relay import testing from tvm.contrib import graph_executor import tvm from tvm import te import ctypes import tvm.testing @tvm.testing.uses_gpu def test_synthetic(): for device in ["llvm", "cuda"]: if not tvm.testing.device_enabled(device): print("skip because %s is not enabled..." % device) return input_shape = (1, 5, 23, 61) def verify(data): mod, params = relay.testing.synthetic.get_workload(input_shape=input_shape) with tvm.transform.PassContext(opt_level=3): lib = relay.build_module.build(mod, "llvm", params=params) dev = tvm.cpu() module = graph_executor.GraphModule(lib["default"](dev)) module.set_input("data", data) module.run() out = module.get_output(0).numpy() return out synthetic_mod, synthetic_params = relay.testing.synthetic.get_workload(input_shape=input_shape) with tvm.transform.PassContext(opt_level=3): synthetic_gpu_lib = relay.build_module.build(synthetic_mod, "cuda", params=synthetic_params) from tvm.contrib import utils temp = utils.tempdir() path_lib = temp.relpath("deploy_lib.so") synthetic_gpu_lib.export_library(path_lib) loaded_lib = tvm.runtime.load_module(path_lib) data = np.random.uniform(-1, 1, size=input_shape).astype("float32") dev = tvm.cuda() module = graph_executor.GraphModule(loaded_lib["default"](dev)) module.set_input("data", data) module.run() out = module.get_output(0).numpy() tvm.testing.assert_allclose(out, verify(data), atol=1e-5) @tvm.testing.uses_gpu def test_cuda_lib(): dev = tvm.cuda(0) for device in ["llvm", "cuda"]: if not tvm.testing.device_enabled(device): print("skip because %s is not enabled..." % device) return nn = 12 n = tvm.runtime.convert(nn) A = te.placeholder((n,), name="A") B = te.compute(A.shape, lambda *i: A(*i) + 1.0, name="B") s = te.create_schedule(B.op) bx, tx = s[B].split(B.op.axis[0], factor=4) s[B].bind(bx, te.thread_axis("blockIdx.x")) s[B].bind(tx, te.thread_axis("threadIdx.x")) from tvm.contrib import utils temp = utils.tempdir() fn_add = tvm.build(s, [A, B], target="cuda --host=llvm", name="add") path_lib = temp.relpath("deploy_lib.so") fn_add.export_library(path_lib) m = tvm.runtime.load_module(path_lib) a = tvm.nd.array(np.random.uniform(size=nn).astype(A.dtype), dev) b = tvm.nd.array(np.zeros(nn, dtype=A.dtype), dev) m["add"](a, b) np.testing.assert_equal(b.numpy(), a.numpy() + 1) if __name__ == "__main__": test_synthetic() test_cuda_lib()
https://github.com/zk-ml/tachikoma
tests/python/unittest/test_target_codegen_bool.py
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. """codegen related to bool types""" import tvm import tvm.testing from tvm import te import numpy as np import tvm.testing arr_size = tvm.testing.parameter(32) @tvm.testing.fixture def compute(arr_size): A = te.placeholder((arr_size,), name="A") B = te.placeholder((arr_size,), name="B") C = te.compute(A.shape, lambda *i: A(*i) > B(*i), name="C") D = te.compute(C.shape, lambda *i: tvm.tir.all(C(*i), A(*i) > 1).astype("float32"), name="D") return [A, B, C, D] @tvm.testing.fixture def schedule(target, compute): target = tvm.target.Target(target) A, B, C, D = compute if target.kind.name == "llvm": s = te.create_schedule(D.op) xo, xi = s[C].split(C.op.axis[0], factor=4) xo1, xo2 = s[C].split(xo, factor=13) s[C].parallel(xo2) else: s = te.create_schedule(D.op) for stage in [C, D]: xo, xi = s[stage].split(stage.op.axis[0], factor=4) s[stage].bind(xo, te.thread_axis("blockIdx.x")) s[stage].bind(xi, te.thread_axis("threadIdx.x")) return s @tvm.testing.uses_gpu def test_cmp_load_store(target, dev, arr_size, compute, schedule): A, B, _, D = compute f = tvm.build(schedule, [A, B, D], target) a_np = np.random.uniform(size=arr_size).astype(A.dtype) b_np = np.random.uniform(size=arr_size).astype(B.dtype) a = tvm.nd.array(a_np, dev) b = tvm.nd.array(b_np, dev) d = tvm.nd.array(np.zeros(arr_size, dtype=D.dtype), dev) f(a, b, d) np.testing.assert_equal( d.numpy(), np.logical_and(a_np > b_np, a_np > 1).astype("float32"), ) if __name__ == "__main__": tvm.testing.main()
https://github.com/zk-ml/tachikoma
tests/python/unittest/test_target_codegen_c_host.py
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. import tvm import tvm.testing from tvm import te import numpy as np from tvm.contrib import utils def test_add(): nn = 1024 n = tvm.runtime.convert(nn) A = te.placeholder((n,), name="A") B = te.placeholder((n,), name="B") C = te.compute(A.shape, lambda *i: A(*i) + B(*i), name="C") s = te.create_schedule(C.op) def check_c(): mhost = tvm.build(s, [A, B, C], "c", name="test_fadd") temp = utils.tempdir() path_dso = temp.relpath("temp.so") mhost.export_library(path_dso) m = tvm.runtime.load_module(path_dso) fadd = m["test_fadd"] dev = tvm.cpu(0) # launch the kernel. n = nn a = tvm.nd.array(np.random.uniform(size=n).astype(A.dtype), dev) b = tvm.nd.array(np.random.uniform(size=n).astype(B.dtype), dev) c = tvm.nd.array(np.zeros(n, dtype=C.dtype), dev) fadd(a, b, c) tvm.testing.assert_allclose(c.numpy(), a.numpy() + b.numpy()) check_c() def test_add_pipeline(): nn = 1024 n = tvm.runtime.convert(nn) A = te.placeholder((n,), name="A") B = te.placeholder((n,), name="B") AA = te.compute((n,), lambda *i: A(*i), name="A") BB = te.compute((n,), lambda *i: B(*i), name="B") T = te.compute(A.shape, lambda *i: AA(*i) + BB(*i), name="T") C = te.compute(A.shape, lambda *i: T(*i), name="C") s = te.create_schedule(C.op) xo, xi = s[C].split(C.op.axis[0], factor=4) xo1, xo2 = s[C].split(xo, factor=13) s[C].parallel(xo2) s[C].pragma(xo1, "parallel_launch_point") s[C].pragma(xo2, "parallel_stride_pattern") s[C].pragma(xo2, "parallel_barrier_when_finish") s[C].vectorize(xi) def check_c(): # Specifically allow offset to test codepath when offset is available Ab = tvm.tir.decl_buffer( A.shape, A.dtype, elem_offset=te.size_var("Aoffset"), offset_factor=8, name="A" ) binds = {A: Ab} # BUILD and invoke the kernel. f1 = tvm.lower(s, [A, B, C], name="test_fadd_pipeline") mhost = tvm.build(f1, target="c") temp = utils.tempdir() path_dso = temp.relpath("temp.so") mhost.export_library(path_dso) m = tvm.runtime.load_module(path_dso) fadd = m["test_fadd_pipeline"] dev = tvm.cpu(0) # launch the kernel. n = nn a = tvm.nd.array(np.random.uniform(size=n).astype(A.dtype), dev) b = tvm.nd.array(np.random.uniform(size=n).astype(B.dtype), dev) c = tvm.nd.array(np.zeros(n, dtype=C.dtype), dev) fadd(a, b, c) tvm.testing.assert_allclose(c.numpy(), a.numpy() + b.numpy()) check_c() def test_reinterpret(): nn = 1024 n = tvm.runtime.convert(nn) A = te.placeholder((n,), name="A", dtype="int32") B = te.compute( A.shape, lambda *i: tvm.tir.call_intrin("float32", "tir.reinterpret", 2 + A(*i)), name="B" ) s = te.create_schedule(B.op) def check_c(): mhost = tvm.build(s, [A, B], "c", name="test_reinterpret") temp = utils.tempdir() path_dso = temp.relpath("temp.so") mhost.export_library(path_dso) m = tvm.runtime.load_module(path_dso) fadd = m["test_reinterpret"] dev = tvm.cpu(0) n = nn a = tvm.nd.array(np.random.randint(-(2**30), 2**30, size=n).astype(A.dtype), dev) b = tvm.nd.array(np.zeros(n, dtype=B.dtype), dev) fadd(a, b) tvm.testing.assert_allclose(b.numpy(), (2 + a.numpy()).view("float32")) check_c() def test_ceil(): nn = 1024 n = tvm.runtime.convert(nn) A = te.placeholder((n,), name="A", dtype="float32") B = te.compute(A.shape, lambda *i: tvm.tir.call_intrin("float32", "tir.ceil", A(*i)), name="B") s = te.create_schedule(B.op) def check_c(): mhost = tvm.build(s, [A, B], "c", name="test_ceil") temp = utils.tempdir() path_dso = temp.relpath("temp.so") mhost.export_library(path_dso) m = tvm.runtime.load_module(path_dso) fceil = m["test_ceil"] dev = tvm.cpu(0) n = nn a = tvm.nd.array(np.random.rand(n).astype(A.dtype), dev) b = tvm.nd.array(np.zeros(n, dtype=B.dtype), dev) fceil(a, b) tvm.testing.assert_allclose(b.numpy(), (np.ceil(a.numpy()).view("float32"))) check_c() def test_floor(): nn = 1024 n = tvm.runtime.convert(nn) A = te.placeholder((n,), name="A", dtype="float32") B = te.compute(A.shape, lambda *i: tvm.tir.call_intrin("float32", "tir.floor", A(*i)), name="B") s = te.create_schedule(B.op) def check_c(): mhost = tvm.build(s, [A, B], "c", name="test_floor") temp = utils.tempdir() path_dso = temp.relpath("temp.so") mhost.export_library(path_dso) m = tvm.runtime.load_module(path_dso) ffloor = m["test_floor"] dev = tvm.cpu(0) n = nn a = tvm.nd.array(np.random.rand(n).astype(A.dtype), dev) b = tvm.nd.array(np.zeros(n, dtype=B.dtype), dev) ffloor(a, b) tvm.testing.assert_allclose(b.numpy(), (np.floor(a.numpy()).view("float32"))) check_c() def test_round(): nn = 1024 n = tvm.runtime.convert(nn) A = te.placeholder((n,), name="A", dtype="float32") B = te.compute(A.shape, lambda *i: tvm.tir.call_intrin("float32", "tir.round", A(*i)), name="B") s = te.create_schedule(B.op) def check_c(): mhost = tvm.build(s, [A, B], "c", name="test_round") temp = utils.tempdir() path_dso = temp.relpath("temp.so") mhost.export_library(path_dso) m = tvm.runtime.load_module(path_dso) fround = m["test_round"] dev = tvm.cpu(0) n = nn a = tvm.nd.array(np.random.rand(n).astype(A.dtype), dev) b = tvm.nd.array(np.zeros(n, dtype=B.dtype), dev) fround(a, b) tvm.testing.assert_allclose(b.numpy(), (np.round(a.numpy()).view("float32"))) check_c() def test_call_packed(): def fake_func(fname="fake.func"): ib = tvm.tir.ir_builder.create() A = ib.pointer("float32", name="A") fake_func1 = tvm.tir.call_packed(fname, A[0]) ib.emit(fake_func1) body = ib.get() return A, body def check_global_packed_func(): fname = "fake.func" A, body = fake_func(fname) func1 = tvm.tir.PrimFunc([A], body).with_attr("global_symbol", "func1") B, body = fake_func() func2 = tvm.tir.PrimFunc([B], body).with_attr("global_symbol", "func2") mod = tvm.IRModule({"fake_func1": func1, "fake_func2": func2}) fcode = tvm.build(mod, None, "c") src = fcode.get_source() # there are two locations calling the packed func assert src.count(fname) == 2 suffix = "_packed" packed_func_name = fname + suffix # func name will be standardized by GetUniqueName and not exists anymore assert src.find(packed_func_name) == -1 packed_func_real_name = "_".join(fname.split(".")) + suffix func_declaration = "static void* %s = NULL;" % packed_func_real_name # src only has 1 valid declaration assert src.count(func_declaration) == 1 check_global_packed_func() if __name__ == "__main__": test_add() test_add_pipeline() test_reinterpret() test_ceil() test_floor() test_round() test_call_packed()
https://github.com/zk-ml/tachikoma
tests/python/unittest/test_target_codegen_cross_llvm.py
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. """Test cross compilation""" import tvm import tvm.testing from tvm import te import os import struct from tvm import rpc from tvm.contrib import utils, cc import numpy as np @tvm.testing.requires_llvm def test_llvm_add_pipeline(): nn = 1024 n = tvm.runtime.convert(nn) A = te.placeholder((n,), name="A") B = te.placeholder((n,), name="B") C = te.compute(A.shape, lambda *i: A(*i) + B(*i), name="C") s = te.create_schedule(C.op) xo, xi = s[C].split(C.op.axis[0], factor=4) s[C].parallel(xo) s[C].vectorize(xi) def verify_elf(path, e_machine): with open(path, "rb") as fi: arr = fi.read(20) assert struct.unpack("ccc", arr[1:4]) == (b"E", b"L", b"F") endian = struct.unpack("b", arr[0x5:0x6])[0] endian = "<" if endian == 1 else ">" assert struct.unpack(endian + "h", arr[0x12:0x14])[0] == e_machine def build_i386(): temp = utils.tempdir() target = "llvm -mtriple=i386-pc-linux-gnu" f = tvm.build(s, [A, B, C], target) path = temp.relpath("myadd.o") f.save(path) verify_elf(path, 0x03) def build_arm(): target = "llvm -mtriple=armv7-none-linux-gnueabihf" if not tvm.runtime.enabled(target): print("Skip because %s is not enabled.." % target) return temp = utils.tempdir() f = tvm.build(s, [A, B, C], target) path = temp.relpath("myadd.o") f.save(path) verify_elf(path, 0x28) asm_path = temp.relpath("myadd.asm") f.save(asm_path) # Do a RPC verification, launch kernel on Arm Board if available. host = os.environ.get("TVM_RPC_ARM_HOST", None) remote = None if host: port = int(os.environ["TVM_RPC_ARM_PORT"]) try: remote = rpc.connect(host, port) except tvm.error.TVMError as e: pass if remote: remote.upload(path) farm = remote.load_module("myadd.o") dev = remote.cpu(0) n = nn a = tvm.nd.array(np.random.uniform(size=n).astype(A.dtype), dev) b = tvm.nd.array(np.random.uniform(size=n).astype(A.dtype), dev) c = tvm.nd.array(np.zeros(n, dtype=C.dtype), dev) farm(a, b, c) tvm.testing.assert_allclose(c.numpy(), a.numpy() + b.numpy()) print("Verification finish on remote..") build_i386() build_arm() if __name__ == "__main__": test_llvm_add_pipeline()
https://github.com/zk-ml/tachikoma
tests/python/unittest/test_target_codegen_cuda.py
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. import re import tvm from tvm import te import numpy as np from tvm import topi from tvm.contrib.nvcc import have_fp16, have_int8, have_bf16 import tvm.testing import pytest tx = te.thread_axis("threadIdx.x") bx = te.thread_axis("blockIdx.x") @tvm.testing.requires_gpu @tvm.testing.requires_cuda def test_cuda_vectorize_add(): num_thread = 8 def check_cuda(dtype, n, lanes): if dtype == "float16" and not have_fp16(tvm.cuda(0).compute_version): print("Skip because gpu does not have fp16 support") return if dtype == "int8" and not have_int8(tvm.cuda(0).compute_version): print("skip because gpu does not support int8") return A = te.placeholder((n,), name="A", dtype="%sx%d" % (dtype, lanes)) B = te.compute((n,), lambda i: A[i] + tvm.tir.const(1, A.dtype), name="B") s = te.create_schedule(B.op) xo, xi = s[B].split(B.op.axis[0], factor=num_thread) s[B].bind(xo, bx) s[B].bind(xi, tx) fun = tvm.build(s, [A, B], "cuda") dev = tvm.cuda(0) a = tvm.nd.empty((n,), A.dtype, dev).copyfrom(np.random.uniform(size=(n, lanes))) c = tvm.nd.empty((n,), B.dtype, dev) fun(a, c) tvm.testing.assert_allclose(c.numpy(), a.numpy() + 1) check_cuda("float32", 64, 2) check_cuda("float32", 64, 3) check_cuda("float32", 64, 4) check_cuda("int8", 64, 2) check_cuda("int8", 64, 3) check_cuda("int8", 64, 4) check_cuda("uint8", 64, 2) check_cuda("uint8", 64, 3) check_cuda("uint8", 64, 4) check_cuda("float16", 64, 2) check_cuda("float16", 64, 4) check_cuda("float16", 64, 6) check_cuda("float16", 64, 8) @tvm.testing.requires_gpu @tvm.testing.requires_cuda def test_cuda_bf16_vectorize_add(): if not have_bf16(tvm.cuda(0).compute_version): print("skip because gpu does not support bf16") return num_thread = 8 def np_float2np_bf16(arr): """Convert a numpy array of float to a numpy array of bf16 in uint16""" orig = arr.view("<u4") bias = np.bitwise_and(np.right_shift(orig, 16), 1) + 0x7FFF return np.right_shift(orig + bias, 16).astype("uint16") def np_bf162np_float(arr): """Convert a numpy array of bf16 (uint16) to a numpy array of float""" u32 = np.left_shift(arr.astype("uint32"), 16) return u32.view("<f4") def check_cuda(n, lanes): A = te.placeholder((n,), name="A", dtype="bfloat16x%d" % lanes) B = te.compute((n,), lambda i: A[i] + tvm.tir.const(1, A.dtype), name="B") s = te.create_schedule(B.op) xo, xi = s[B].split(B.op.axis[0], factor=num_thread) s[B].bind(xo, bx) s[B].bind(xi, tx) with tvm.transform.PassContext( disabled_pass=["tir.BF16Promote", "tir.BF16CastElimination", "tir.BF16TypeLowering"] ): fun = tvm.build(s, [A, B], "cuda") dev = tvm.cuda(0) np_a = np.random.uniform(size=(n, lanes)).astype("float32") np_a = np_bf162np_float(np_float2np_bf16(np_a)) a = tvm.nd.empty((n,), A.dtype, dev).copyfrom(np_float2np_bf16(np_a)) c = tvm.nd.empty((n,), B.dtype, dev) fun(a, c) c = tvm.nd.empty((n, lanes), "uint16", dev).copyfrom(c) tvm.testing.assert_allclose(c.numpy(), np_float2np_bf16(np_a + 1)) check_cuda(64, 2) check_cuda(64, 4) check_cuda(64, 6) check_cuda(64, 8) @tvm.testing.requires_gpu @tvm.testing.requires_cuda def test_cuda_multiply_add(): num_thread = 8 def check_cuda(dtype, n, lanes): if dtype == "int8" and not have_int8(tvm.cuda(0).compute_version): print("skip because gpu does not support int8") return A = te.placeholder((n,), name="A", dtype="%sx%d" % (dtype, lanes)) B = te.placeholder((n,), name="B", dtype="%sx%d" % (dtype, lanes)) C = te.placeholder((n,), name="C", dtype="int32") D = te.compute( (n,), lambda i: tvm.tir.call_pure_extern("int32", "__dp4a", A[i], B[i], C[i]), name="D" ) s = te.create_schedule(D.op) xo, xi = s[D].split(D.op.axis[0], factor=num_thread) s[D].bind(xo, bx) s[D].bind(xi, tx) fun = tvm.build(s, [A, B, C, D], "cuda") np_a = np.random.randint(low=-128, high=127, size=(n, lanes)) np_b = np.random.randint(low=-128, high=127, size=(n, lanes)) np_c = np.random.randint(low=0, high=127, size=(n,)) np_d = [sum(x * y) + z for x, y, z in zip(np_a, np_b, np_c)] dev = tvm.cuda(0) a = tvm.nd.empty((n,), A.dtype, dev).copyfrom(np_a) b = tvm.nd.empty((n,), B.dtype, dev).copyfrom(np_b) c = tvm.nd.empty((n,), C.dtype, dev).copyfrom(np_c) d = tvm.nd.empty((n,), D.dtype, dev) fun(a, b, c, d) tvm.testing.assert_allclose(d.numpy(), np_d) check_cuda("int8", 64, 4) @tvm.testing.requires_gpu @tvm.testing.requires_cuda def test_cuda_vectorize_load(): num_thread = 8 def check_cuda(dtype, n, lanes): dev = tvm.cuda(0) A = te.placeholder((n,), name="A", dtype="%sx%d" % (dtype, lanes)) B = te.compute((n,), lambda i: A[i], name="B") s = te.create_schedule(B.op) block, thread = s[B].split(B.op.axis[0], factor=num_thread) s[B].bind(block, bx) s[B].bind(thread, tx) fun = tvm.build(s, [A, B], "cuda", name="vector_load") np_a = np.random.randint(low=-128, high=127, size=(n, lanes)) a = tvm.nd.empty((n,), A.dtype, dev).copyfrom(np_a) b = tvm.nd.empty((n,), B.dtype, dev) fun(a, b) tvm.testing.assert_allclose(a.numpy(), b.numpy()) check_cuda("int8", 64, 2) check_cuda("int8", 64, 3) check_cuda("int8", 64, 4) check_cuda("int8", 64, 8) check_cuda("int8", 64, 16) @tvm.testing.requires_gpu @tvm.testing.requires_cuda def test_cuda_make_int8(): def check_cuda(n, value, lanes): dtype = "int8" dev = tvm.cuda(0) A = te.compute((n, lanes), lambda i, j: tvm.tir.const(value, dtype=dtype)) s = te.create_schedule(A.op) y, x = s[A].op.axis s[A].vectorize(x) s[A].bind(y, bx) fun = tvm.build(s, [A], "cuda", name="make_int8x4") np_a = np.full((n, lanes), value, dtype=dtype) a = tvm.nd.empty(np_a.shape, dtype, dev) fun(a) np.testing.assert_equal(a.numpy(), np_a) check_cuda(64, np.int8(0xAB), 4) check_cuda(64, 0, 4) check_cuda(64, -3, 4) check_cuda(64, np.int8(0xAB), 3) check_cuda(64, 0, 3) check_cuda(64, -3, 3) check_cuda(64, np.int8(0xAB), 2) check_cuda(64, 0, 2) check_cuda(64, -3, 2) @tvm.testing.requires_gpu @tvm.testing.requires_cuda def test_cuda_make_int4(): def check_cuda(n, value, lanes): dtype = "int4" dev = tvm.cuda(0) A = te.compute((n, lanes), lambda i, j: tvm.tir.const(value, dtype=dtype)) s = te.create_schedule(A.op) y, x = s[A].op.axis s[A].vectorize(x) s[A].bind(y, bx) kernel_name = "make_int4x" + str(lanes) fun = tvm.build(s, [A], "cuda", name=kernel_name) np_a = np.full((n, lanes), value, dtype="int8") a = tvm.nd.empty((n, lanes), dtype, dev) fun(a) np.testing.assert_equal(a.numpy(), np_a) check_cuda(64, 1, 4) check_cuda(64, 7, 4) check_cuda(64, 1, 8) check_cuda(64, 7, 8) check_cuda(64, 1, 16) check_cuda(64, 7, 16) check_cuda(64, 1, 32) check_cuda(64, 7, 32) @tvm.testing.requires_gpu @tvm.testing.requires_cuda def test_cuda_inf_nan(): target = "cuda" def check_inf_nan(dev, n, value, dtype): A = te.placeholder((n,), name="A", dtype=dtype) inf_value = tvm.tir.const(value, dtype=dtype) C = te.compute((n,), lambda i: inf_value, name="C") s = te.create_schedule(C.op) s[C].bind(s[C].op.axis[0], tx) fun = tvm.build(s, [A, C], target) a = tvm.nd.empty((n,), A.dtype, dev) c = tvm.nd.empty((n,), A.dtype, dev) # Only need to test compiling here fun(a, c) dev = tvm.device(target, 0) check_inf_nan(dev, 1, -float("inf"), "float32") check_inf_nan(dev, 1, -float("inf"), "float64") check_inf_nan(dev, 1, float("inf"), "float32") check_inf_nan(dev, 1, float("inf"), "float64") check_inf_nan(dev, 1, float("nan"), "float32") check_inf_nan(dev, 1, float("nan"), "float64") @tvm.testing.requires_gpu @tvm.testing.requires_cuda def test_cuda_shuffle(): idxm = tvm.tir.indexmod a = te.placeholder((64,), "int32") b = te.placeholder((64,), "int32") c = te.compute((64,), lambda x: a[x] + b[x - idxm(x, 4) + (3 - idxm(x, 4))]) sch = te.create_schedule(c.op) x = c.op.axis[0] xo, xi = sch[c].split(x, 4) thrx = te.thread_axis("threadIdx.x") sch[c].bind(xo, thrx) sch[c].vectorize(xi) def MyVectorize(): def vectorizer(op): if op.kind == tvm.tir.ForKind.VECTORIZED: idx = tvm.tir.Ramp(4 * thrx.var, 1, 4) store = op.body value = store.value new_a = tvm.tir.BufferLoad(value.a.buffer, [idx]) bs, ids = [], [] for i in range(4): bs.append(tvm.tir.BufferLoad(value.b.buffer, [4 * thrx.var + i])) ids.append(3 - i) new_b = tvm.tir.Shuffle(bs, ids) return tvm.tir.BufferStore(store.buffer, new_a + new_b, [idx]) return None def _transform(f, *_): return f.with_body( tvm.tir.stmt_functor.ir_transform(f.body, None, vectorizer, ["tir.For"]) ) return tvm.tir.transform.prim_func_pass(_transform, opt_level=0, name="MyVectorize") with tvm.transform.PassContext(config={"tir.add_lower_pass": [(1, MyVectorize())]}): module = tvm.build(sch, [a, b, c], target="cuda") a_ = np.array(list(range(64)), dtype="int32") b_ = np.array((list(range(4))[::-1]) * 16, dtype="int32") c_ = np.zeros((64,), dtype="int32") ref = a_ + np.array((list(range(4))) * 16, dtype="int32") nda, ndb, ndc = [tvm.nd.array(i, tvm.cuda(0)) for i in [a_, b_, c_]] module(nda, ndb, ndc) tvm.testing.assert_allclose(ndc.numpy(), ref) @tvm.testing.parametrize_targets("cuda", "rocm") def test_crossthread_reduction1(target, dev): n = te.var("n") m = te.var("m") A = te.placeholder((n, m), name="A") k = te.reduce_axis((0, m), "m") B = te.compute((n,), lambda i: te.sum(A[i, k], axis=k), name="B") def sched(nthd): s = te.create_schedule(B.op) ko, _ = s[B].split(B.op.reduce_axis[0], nparts=nthd) s[B].bind(ko, te.thread_axis("threadIdx.x")) s[B].bind(B.op.axis[0], te.thread_axis("blockIdx.x")) func = tvm.build(s, [A, B], target) return func def verify(nthd): func = sched(nthd) nn = 3 # checks three typical cases vals = [nthd - 1, nthd, nthd + 1] for kk in [x for x in vals]: size = (nn, kk) a = tvm.nd.array(np.random.uniform(size=size).astype(A.dtype), dev) b = tvm.nd.array(np.zeros(nn, dtype=B.dtype), dev) func(a, b) tvm.testing.assert_allclose(b.numpy(), np.sum(a.numpy(), axis=1), rtol=1e-3) verify(16) verify(32) verify(64) @tvm.testing.parametrize_targets("cuda", "rocm") def test_crossthread_reduction2(target, dev): n = te.var("n") k0 = te.var("k0") k1 = te.var("k1") A = te.placeholder((n, k0, k1), name="A") k0 = te.reduce_axis((0, k0), "k0") k1 = te.reduce_axis((0, k1), "k1") B = te.compute((n,), lambda i: te.sum(A[i, k0, k1], axis=(k0, k1)), name="B") def sched(nthdx, nthdy): s = te.create_schedule(B.op) k0o, _ = s[B].split(B.op.reduce_axis[0], nparts=nthdx) k1o, _ = s[B].split(B.op.reduce_axis[1], nparts=nthdy) s[B].bind(k0o, te.thread_axis("threadIdx.x")) s[B].bind(k1o, te.thread_axis("threadIdx.y")) s[B].bind(B.op.axis[0], te.thread_axis("blockIdx.x")) func = tvm.build(s, [A, B], target) return func def verify(nthdx, nthdy): func = sched(nthdx, nthdy) nn = 3 # checks three typical cases vx = [nthdx - 1, nthdx, nthdx + 1] vy = [nthdy - 1, nthdy, nthdy + 1] for kk0, kk1 in [(x, y) for x in vx for y in vy]: size = (nn, kk0, kk1) a = tvm.nd.array(np.random.uniform(size=size).astype(A.dtype), dev) b = tvm.nd.array(np.zeros(nn, dtype=B.dtype), dev) func(a, b) tvm.testing.assert_allclose(b.numpy(), np.sum(a.numpy(), axis=(1, 2)), rtol=1e-3) verify(16, 16) verify(32, 32) verify(16, 32) verify(32, 16) @tvm.testing.requires_gpu @tvm.testing.requires_cuda def test_cuda_reduction_binding(): k = te.reduce_axis((0, 32), "k") A = te.placeholder((96, 32), name="A") B = te.compute((96,), lambda m: te.sum(A[m, k], axis=k), name="B") s = te.create_schedule(B.op) s[B].reorder(B.op.reduce_axis[0], B.op.axis[0]) mo, _ = s[B].split(B.op.axis[0], 32) s[B].bind(mo, te.thread_axis("blockIdx.x")) fcuda = tvm.build(s, [A, B], "cuda") @tvm.testing.parametrize_targets("cuda", "rocm") def test_rfactor_predicates(target, dev): n = te.reduce_axis((0, 129), "n") A = te.placeholder((129,), name="A") B = te.compute((1,), lambda b: te.sum(A[n], axis=n), name="B") s = te.create_schedule(B.op) _, ni = s[B].split(s[B].op.reduce_axis[0], factor=8) BF = s.rfactor(B, ni, 0) s[B].set_store_predicate(tx.var.equal(0)) s[B].bind(s[B].op.reduce_axis[0], tx) s[B].bind(s[B].op.axis[0], bx) s[BF].compute_at(s[B], s[B].op.axis[0]) _, noi = s[BF].split(s[BF].op.reduce_axis[0], factor=2) BF2 = s.rfactor(BF, noi, 0) s[BF].bind(s[BF].op.axis[0], tx) s[BF2].compute_at(s[BF], s[BF].op.axis[1]) fcuda = tvm.build(s, [A, B], target) @tvm.testing.requires_gpu @tvm.testing.requires_cuda def test_cuda_const_float_to_half(): # This import is required to use nvcc to perform code gen; # otherwise it is found that the code gen is done by nvrtc. from tvm import autotvm shape = (2, 3, 4) a = te.placeholder(shape, dtype="float16", name="a") b = tvm.tir.const(0.5, dtype="float16") c = te.compute(shape, lambda i, j, k: a[i, j, k] > b, name="c") s = te.create_schedule(c.op) axes = [axis for axis in c.op.axis] fused = s[c].fuse(*axes) bx, tx = s[c].split(fused, factor=64) s[c].bind(bx, te.thread_axis("blockIdx.x")) s[c].bind(tx, te.thread_axis("threadIdx.x")) func = tvm.build(s, [a, c], "cuda") dev = tvm.cuda(0) a_np = np.random.uniform(size=shape).astype(a.dtype) c_np = np.zeros(shape=shape, dtype=c.dtype) a = tvm.nd.array(a_np, dev) c = tvm.nd.array(c_np, dev) func(a, c) np.testing.assert_equal(c.numpy(), a_np > b.value) @tvm.testing.requires_gpu @tvm.testing.requires_cuda def test_cuda_reduction(): def check(device, dtype, m=32, n=32): if not tvm.testing.device_enabled(device): print("Skipping", device) return dev = tvm.device(device, 0) a = te.placeholder((m, n), name="a", dtype=dtype) b = te.placeholder((m, n), name="b", dtype=dtype) c = a + b d = a * b e = topi.elemwise_sum([c, d]) g = topi.sum(e) with tvm.target.Target(device): sg = topi.cuda.schedule_reduce(g) func = tvm.build(sg, [a, b, g], device) a_np = np.random.uniform(size=(m, n)).astype(a.dtype) b_np = np.random.uniform(size=(m, n)).astype(b.dtype) g_np = np.sum(np.add(a_np * b_np, a_np + b_np)) a_nd = tvm.nd.array(a_np, dev) b_nd = tvm.nd.array(b_np, dev) g_nd = tvm.nd.array(np.zeros(g_np.shape, dtype=g_np.dtype), dev) func(a_nd, b_nd, g_nd) tvm.testing.assert_allclose(g_nd.numpy(), g_np, rtol=1e-3) check("cuda", "float32") check("rocm", "float32") check("cuda", "float16") @tvm.testing.requires_gpu @tvm.testing.requires_cuda def test_cuda_mix_threaded_and_normal_reduction(): def check(device, dtype, m=32, n=32): if not tvm.testing.device_enabled(device): print("Skipping", device) return dev = tvm.device(device, 0) if dtype == "float16" and not have_fp16(dev.compute_version): print("Skip because gpu does not have fp16 support") return a = tvm.te.placeholder((m, n), name="a", dtype=dtype) b = topi.sum(a) with tvm.target.Target(device): sb = tvm.te.create_schedule(b.op) i, _ = b.op.reduce_axis sb[b].bind(i, tvm.te.thread_axis("threadIdx.x")) func = tvm.build(sb, [a, b], device) a_np = np.random.uniform(size=(m, n)).astype(a.dtype) b_np = np.sum(a_np) a_nd = tvm.nd.array(a_np, dev) b_nd = tvm.nd.array(np.zeros(b_np.shape, dtype=b_np.dtype), dev) func(a_nd, b_nd) tvm.testing.assert_allclose(b_nd.numpy(), b_np, rtol=1e-3) check("cuda", "float32") check("rocm", "float32") check("cuda", "float16") @tvm.testing.requires_gpu @tvm.testing.requires_cuda def test_cuda_floordiv_with_vectorization(): with tvm.target.cuda(): # B[i] = A[floordiv(i, k)] n = 256 k = 37 A = te.placeholder((n,), name="A") B = te.compute((n,), lambda i: A[tvm.tir.floordiv(i, k)], name="B") s = te.create_schedule(B.op) xo, xi = s[B].split(B.op.axis[0], nparts=1) xio, xii = s[B].split(xi, factor=4) s[B].vectorize(xii) s[B].bind(xo, bx) s[B].bind(xio, tx) func = tvm.build(s, [A, B], "cuda") dev = tvm.cuda(0) a_np = np.random.uniform(size=(n,)).astype(A.dtype) b_np = np.array([a_np[i // k] for i in range(0, n)]) a_nd = tvm.nd.array(a_np, dev) b_nd = tvm.nd.array(np.zeros(b_np.shape, dtype=b_np.dtype), dev) func(a_nd, b_nd) tvm.testing.assert_allclose(b_nd.numpy(), b_np, rtol=1e-3) @tvm.testing.requires_gpu @tvm.testing.requires_cuda def test_cuda_floormod_with_vectorization(): with tvm.target.cuda(): # B[i] = A[floormod(i, k)] n = 256 k = 37 A = te.placeholder((n,), name="A") B = te.compute((n,), lambda i: A[tvm.tir.floormod(i, k)], name="B") s = te.create_schedule(B.op) xo, xi = s[B].split(B.op.axis[0], nparts=1) xio, xii = s[B].split(xi, factor=4) s[B].vectorize(xii) s[B].bind(xo, bx) s[B].bind(xio, tx) func = tvm.build(s, [A, B], "cuda") dev = tvm.cuda(0) a_np = np.random.uniform(size=(n,)).astype(A.dtype) b_np = np.array([a_np[i % k] for i in range(0, n)]) a_nd = tvm.nd.array(a_np, dev) b_nd = tvm.nd.array(np.zeros(b_np.shape, dtype=b_np.dtype), dev) func(a_nd, b_nd) tvm.testing.assert_allclose(b_nd.numpy(), b_np, rtol=1e-3) @tvm.testing.requires_gpu @tvm.testing.requires_cuda def test_vectorized_casts(): def check(t0, t1, factor): if (t0 == "float16" or t1 == "float16") and not have_fp16(tvm.cuda(0).compute_version): print("Skip because gpu does not have fp16 support") return # compute n = 128 A = te.placeholder((n,), dtype=t0, name="A") B = te.placeholder((n,), dtype=t1, name="B") C = te.compute((n,), lambda i: A[i] + topi.cast(B[i], A.dtype), name="C") # schedule s = tvm.te.create_schedule(C.op) ob, ib = s[C].split(s[C].op.axis[0], factor=factor) s[C].vectorize(ib) s[C].bind(ob, tx) func = tvm.build(s, [A, B, C], "cuda") # correctness dev = tvm.cuda(0) low, high = (0, 20) if t0.startswith("u") or t1.startswith("u") else (-10, 10) a_np = np.random.randint(low, high, size=n).astype(A.dtype) b_np = np.random.randint(low, high, size=n).astype(B.dtype) c_np = (a_np + b_np).astype(A.dtype) a_nd = tvm.nd.array(a_np, dev) b_nd = tvm.nd.array(b_np, dev) c_nd = tvm.nd.array(np.zeros(c_np.shape, dtype=c_np.dtype), dev) func(a_nd, b_nd, c_nd) tvm.testing.assert_allclose(c_nd.numpy(), c_np, rtol=1e-3) def skip(t0, t1): if t0 == t1: return True # CUDA does support cast between {u}int8 and fp16. skip_set = {"float16", "uint8", "int8"} if t0 in skip_set and t1 in skip_set: return True return False types_4 = [ "float16", "float32", "int8", "uint8", "int16", "uint16", "int32", "uint32", "float64", "int64", "uint64", ] types_8 = ["float16", "float32", "int8", "uint8", "int16", "uint16", "int32", "uint32"] for t0, t1 in [(x, y) for x in types_4 for y in types_4 if not skip(x, y)]: check(t0, t1, 4) for t0, t1 in [(x, y) for x in types_8 for y in types_8 if not skip(x, y)]: check(t0, t1, 8) check("int8", "uint8", 16) check("uint8", "int8", 16) def sched(B): s = te.create_schedule(B.op) io, ii = s[B].split(s[B].op.axis[0], nparts=1) iio, iii = s[B].split(ii, nparts=32) _, iiii = s[B].split(iii, factor=4) s[B].vectorize(iiii) s[B].bind(io, bx) s[B].bind(iio, tx) return s @tvm.testing.requires_gpu @tvm.testing.requires_cuda def test_vectorized_intrin1(): test_funcs = [ (tvm.tir.floor, lambda x: np.floor(x)), (tvm.tir.ceil, lambda x: np.ceil(x)), (tvm.tir.trunc, lambda x: np.trunc(x)), (tvm.tir.abs, lambda x: np.fabs(x)), (tvm.tir.round, lambda x: np.round(x)), (tvm.tir.exp, lambda x: np.exp(x)), (tvm.tir.exp2, lambda x: np.exp2(x)), (tvm.tir.exp10, lambda x: np.power(10, x)), (tvm.tir.log, lambda x: np.log(x)), (tvm.tir.log2, lambda x: np.log2(x)), (tvm.tir.log10, lambda x: np.log10(x)), (tvm.tir.tan, lambda x: np.tan(x)), (tvm.tir.cos, lambda x: np.cos(x)), (tvm.tir.cosh, lambda x: np.cosh(x)), (tvm.tir.sin, lambda x: np.sin(x)), (tvm.tir.sinh, lambda x: np.sinh(x)), (tvm.tir.atan, lambda x: np.arctan(x)), (tvm.tir.tanh, lambda x: np.tanh(x)), (tvm.tir.sqrt, lambda x: np.sqrt(x)), ] def run_test(tvm_intrin, np_func, dtype): if dtype == "float16" and not have_fp16(tvm.cuda(0).compute_version): print("Skip because gpu does not have fp16 support") return # set of intrinsics does not support fp16 yet. skip_set = { tvm.tir.abs, tvm.tir.round, tvm.tir.tan, tvm.tir.atan, tvm.tir.tanh, tvm.tir.cosh, tvm.tir.sinh, } if dtype == "float16" and tvm_intrin in skip_set: print("Skip because '{0}' does not support fp16 yet".format(tvm_intrin.__name__)) return n = 128 A = te.placeholder((n,), dtype=dtype, name="A") B = te.compute((n,), lambda *i: tvm_intrin(A(*i)), name="B") s = sched(B) f = tvm.build(s, [A, B], "cuda") dev = tvm.cuda(0) a = tvm.nd.array(np.random.uniform(0, 1, size=n).astype(A.dtype), dev) b = tvm.nd.array(np.zeros(shape=(n,)).astype(A.dtype), dev) f(a, b) tvm.testing.assert_allclose(b.numpy(), np_func(a.numpy()), atol=1e-3, rtol=1e-3) for func in test_funcs: run_test(*func, "float32") run_test(*func, "float16") @tvm.testing.requires_gpu @tvm.testing.requires_cuda def test_vectorized_intrin2(dtype="float32"): c2 = tvm.tir.const(2, dtype=dtype) test_funcs = [ (tvm.tir.power, lambda x: np.power(x, 2.0)), (tvm.tir.fmod, lambda x: np.fmod(x, 2.0)), ] def run_test(tvm_intrin, np_func): n = 128 A = te.placeholder((n,), dtype=dtype, name="A") B = te.compute((n,), lambda i: tvm_intrin(A[i], c2), name="B") s = sched(B) f = tvm.build(s, [A, B], "cuda") dev = tvm.cuda(0) a = tvm.nd.array(np.random.uniform(0, 1, size=n).astype(A.dtype), dev) b = tvm.nd.array(np.zeros(shape=(n,)).astype(A.dtype), dev) f(a, b) tvm.testing.assert_allclose(b.numpy(), np_func(a.numpy()), atol=1e-3, rtol=1e-3) for func in test_funcs: run_test(*func) @tvm.testing.requires_gpu @tvm.testing.requires_cuda def test_vectorized_popcount(): def ref_popcount(x): cnt = 0 while x: x -= x & -x cnt += 1 return cnt def run_test(dtype): n = 128 A = te.placeholder((n,), dtype=dtype, name="A") B = te.compute((n,), lambda i: tvm.tir.popcount(A[i]), name="B") s = sched(B) f = tvm.build(s, [A, B], "cuda") dev = tvm.cuda(0) a = tvm.nd.array(np.random.randint(0, 100000, size=n).astype(A.dtype), dev) b = tvm.nd.array(np.zeros(shape=(n,)).astype(B.dtype), dev) f(a, b) ref = np.vectorize(ref_popcount)(a.numpy()) tvm.testing.assert_allclose(b.numpy(), ref) run_test("uint32") run_test("uint64") @tvm.testing.requires_gpu @tvm.testing.requires_cuda def test_cuda_vectorize_load_permute_pad(): def check_cuda(dtype, n, l, padding, lanes): if dtype == "float16" and not have_fp16(tvm.cuda(0).compute_version): print("Skip because gpu does not have fp16 support") return dev = tvm.cuda(0) A = tvm.te.placeholder((n, l), name="A", dtype=dtype) B = tvm.te.compute( (n // lanes, l + 2 * padding, lanes), lambda i, j, k: tvm.te.if_then_else( tvm.te.any(j < padding, j >= l + padding), tvm.runtime.convert(0).astype(dtype), A[i * lanes + k, j - padding], ), name="B", ) s = te.create_schedule(B.op) block, thread, vectorize = s[B].op.axis s[B].bind(block, bx) s[B].bind(thread, tx) s[B].vectorize(vectorize) fun = tvm.build(s, [A, B], "cuda", name="vector_load_permute_pad") np_a = np.random.randint(low=-128, high=127, size=(n, l)).astype(A.dtype) a = tvm.nd.empty((n, l), A.dtype, dev).copyfrom(np_a) b = tvm.nd.empty((n // lanes, l + padding * 2, lanes), B.dtype, dev) fun(a, b) np_a_reshape = np_a.reshape(n // lanes, lanes, l).transpose(0, 2, 1) ref = np.pad( np_a_reshape, ((0, 0), (padding, padding), (0, 0)), mode="constant", constant_values=0 ) tvm.testing.assert_allclose(b.numpy(), ref) check_cuda("int8", 64, 16, 3, 2) check_cuda("uint8", 64, 16, 3, 2) check_cuda("int8", 64, 16, 3, 4) check_cuda("uint8", 64, 16, 3, 4) check_cuda("int32", 64, 16, 3, 4) check_cuda("float16", 64, 16, 3, 4) check_cuda("float32", 64, 16, 3, 4) def vcf_check_common(s, args): N = 512 # To check if every vectorize loop transforms to ramp expr successfully stmt = tvm.lower(s, args) # Use this as a stack flag to show whether this stmt is inside a BroadcastNode inside_broadcast = [False] # Possible patterns: # Reduce init: BufferStore[Ramp] = Broadcast(0) # Shared memory copy: BufferStore[Ramp] = BufferLoad[Ramp] # Compute: BufferStore[Ramp] = BufferLoad[Ramp] ... Broadcast[Load] def pre_visit(stmt): if isinstance(stmt, tvm.tir.Broadcast): inside_broadcast[0] = True # Check Broadcast[Imm numbers] or Broadcast[Load] patterns assert isinstance(stmt.value, (tvm.tir.IntImm, tvm.tir.FloatImm, tvm.tir.BufferLoad)) if isinstance(stmt, (tvm.tir.BufferStore, tvm.tir.BufferLoad)): is_ramp_index = isinstance(stmt.indices[-1], tvm.tir.Ramp) is_vectorized_buffer = re.match(r"^.*x\d+$", stmt.buffer.dtype) if isinstance(stmt, tvm.tir.BufferLoad): # Check Broadcast[BufferLoad] or BufferLoad[Ramp] patterns assert inside_broadcast[0] or is_ramp_index or is_vectorized_buffer # Skip the rest of the BufferLoad return stmt else: assert is_ramp_index or is_vectorized_buffer return None def post_visit(stmt): if isinstance(stmt, tvm.tir.Broadcast): inside_broadcast[0] = False return None tvm.tir.stmt_functor.ir_transform(stmt["main"].body, pre_visit, post_visit) tgt = tvm.target.cuda() mod = tvm.build(s, args, tgt) # To check if every vectorize loop transforms to correct instruction # print(mod.imported_modules[0].get_source()) dev = tvm.device("cuda", 0) a = tvm.nd.array(np.random.uniform(size=(512, 512)).astype("float32"), dev) b = tvm.nd.array(np.random.uniform(size=(512, 512)).astype("float32"), dev) c = tvm.nd.array(np.zeros((512, 512), dtype="float32"), dev) mod(a, b, c) tvm.testing.assert_allclose(c.numpy(), np.dot(a.numpy(), b.numpy()), rtol=1e-5) @tvm.testing.requires_gpu @tvm.testing.requires_cuda def test_vectorized_cooperative_fetching_x(): N = 512 A = te.placeholder((N, N), name="A", dtype="float32") B = te.placeholder((N, N), name="B", dtype="float32") k = te.reduce_axis((0, N), name="k") C = te.compute((N, N), lambda i, j: te.sum(A[i, k] * B[k, j], axis=k)) s = te.create_schedule(C.op) i, j = s[C].op.axis k = s[C].op.reduce_axis[0] AA = s.cache_read(A, "shared", [C]) BB = s.cache_read(B, "shared", [C]) i3, i4 = s[C].split(i, factor=4) i2, i3 = s[C].split(i3, factor=2) i1, i2 = s[C].split(i2, factor=8) i0, i1 = s[C].split(i1, factor=1) j3, j4 = s[C].split(j, factor=4) j2, j3 = s[C].split(j3, factor=2) j1, j2 = s[C].split(j2, factor=8) j0, j1 = s[C].split(j1, factor=2) k1, k2 = s[C].split(k, factor=8) k0, k1 = s[C].split(k1, factor=8) s[C].reorder(i0, j0, i1, j1, i2, j2, k0, k1, i3, j3, k2, i4, j4) block_it = s[C].fuse(i0, j0) s[C].bind(block_it, tvm.te.thread_axis("blockIdx.x")) vthread_it = s[C].fuse(i1, j1) s[C].bind(vthread_it, tvm.te.thread_axis("vthread")) thread_it = s[C].fuse(i2, j2) s[C].bind(thread_it, tvm.te.thread_axis("threadIdx.x")) s[C].vectorize(j4) s[AA].compute_at(s[C], k0) iaa, jaa = s[AA].op.axis s[BB].compute_at(s[C], k0) ibb, jbb = s[BB].op.axis aa_fused = s[AA].fuse(iaa, jaa) bb_fused = s[BB].fuse(ibb, jbb) aa1, aa2 = s[AA].split(aa_fused, factor=4) aa0, aa1 = s[AA].split(aa1, factor=64) bb1, bb2 = s[BB].split(bb_fused, factor=4) bb0, bb1 = s[BB].split(bb1, factor=64) s[AA].bind(aa1, tvm.te.thread_axis("threadIdx.x")) s[AA].vectorize(aa2) s[BB].bind(bb1, tvm.te.thread_axis("threadIdx.x")) s[BB].vectorize(bb2) vcf_check_common(s, [A, B, C]) @tvm.testing.requires_gpu @tvm.testing.requires_cuda def test_vectorized_cooperative_fetching_xy(): N = 512 A = te.placeholder((N, N), name="A") B = te.placeholder((N, N), name="B") k = te.reduce_axis((0, N), name="k") C = te.compute((N, N), lambda i, j: te.sum(A[i, k] * B[k, j], axis=k)) s = te.create_schedule(C.op) i, j = s[C].op.axis k = s[C].op.reduce_axis[0] AA = s.cache_read(A, "shared", [C]) BB = s.cache_read(B, "shared", [C]) i3, i4 = s[C].split(i, factor=4) i2, i3 = s[C].split(i3, factor=2) i1, i2 = s[C].split(i2, factor=8) i0, i1 = s[C].split(i1, factor=1) j3, j4 = s[C].split(j, factor=4) j2, j3 = s[C].split(j3, factor=2) j1, j2 = s[C].split(j2, factor=8) j0, j1 = s[C].split(j1, factor=2) k1, k2 = s[C].split(k, factor=8) k0, k1 = s[C].split(k1, factor=8) s[C].reorder(i0, j0, i1, j1, i2, j2, k0, k1, i3, j3, k2, i4, j4) block_it = s[C].fuse(i0, j0) s[C].bind(block_it, tvm.te.thread_axis("blockIdx.x")) vthread_it = s[C].fuse(i1, j1) s[C].bind(vthread_it, tvm.te.thread_axis("vthread")) s[C].bind(i2, tvm.te.thread_axis("threadIdx.y")) s[C].bind(j2, tvm.te.thread_axis("threadIdx.x")) s[C].vectorize(j4) s[AA].compute_at(s[C], k0) iaa, jaa = s[AA].op.axis s[BB].compute_at(s[C], k0) ibb, jbb = s[BB].op.axis aa_fused = s[AA].fuse(iaa, jaa) bb_fused = s[BB].fuse(ibb, jbb) aa2, aa3 = s[AA].split(aa_fused, factor=4) aa1, aa2 = s[AA].split(aa2, factor=8) aa0, aa1 = s[AA].split(aa1, factor=8) bb2, bb3 = s[BB].split(bb_fused, factor=4) bb1, bb2 = s[BB].split(bb2, factor=8) bb0, bb1 = s[BB].split(bb1, factor=8) s[AA].bind(aa1, tvm.te.thread_axis("threadIdx.y")) s[AA].bind(aa2, tvm.te.thread_axis("threadIdx.x")) s[AA].vectorize(aa3) s[BB].bind(bb1, tvm.te.thread_axis("threadIdx.y")) s[BB].bind(bb2, tvm.te.thread_axis("threadIdx.x")) s[BB].vectorize(bb3) vcf_check_common(s, [A, B, C]) @tvm.testing.requires_gpu @tvm.testing.requires_cuda def test_unrolled_vectorization(): dtype = "float32" target = "cuda" # Compute declaration N = 128 A = te.placeholder((N, N), name="A") B = te.placeholder((N, N), name="B") k = te.reduce_axis((0, N), name="k") C = te.compute((N, N), lambda i, j: te.sum(A[i][k] * B[k][j], axis=[k]), name="C") # Schedule s = te.create_schedule([C.op]) CC = s.cache_write(C, "local") i, j = s[C].op.axis bx, tx, ii, ji = s[C].tile(i, j, 1, 2) s[C].bind(bx, te.thread_axis("blockIdx.x")) s[C].bind(tx, te.thread_axis("threadIdx.x")) s[C].vectorize(ji) s[CC].compute_at(s[C], tx) i, j = s[CC].op.axis k = s[CC].op.reduce_axis[0] ko, ki = s[CC].split(k, 2) s[CC].unroll(ki) s[CC].vectorize(j) # Check correctness dev = tvm.device(target) a_tvm = tvm.nd.array(np.ones((N, N)).astype(dtype), device=dev) b_tvm = tvm.nd.array(np.ones((N, N)).astype(dtype), device=dev) c_tvm = tvm.nd.empty((N, N), device=dev) func_tvm = tvm.build(s, [A, B, C], target=target) func_tvm(a_tvm, b_tvm, c_tvm) c_np = c_tvm.numpy() tvm.testing.assert_allclose(c_np, N * np.ones((N, N))) @tvm.testing.requires_gpu @tvm.testing.requires_cuda def test_try_unaligned_vector_load(): def get_compute(N, C_N, offset): A = te.placeholder((N,), name="A", dtype="float16") C = te.compute((C_N,), lambda i: A[i + offset], name="C") return N, C_N, A, C def get_compute_unaligned(): return get_compute(3, 2, 1) def get_compute_aligned(): return get_compute(4, 2, 2) def build(A, C, N, C_N): s = te.create_schedule(C.op) oi, ii = s[C].split(C.op.axis[0], factor=2) s[C].bind(oi, te.thread_axis("threadIdx.x")) s[C].vectorize(ii) # BUG: misalignment tgt = tvm.target.Target(target="cuda", host="llvm") dev = tvm.device(tgt.kind.name, 0) f = tvm.build(s, [A, C], tgt, name="foo") kernel_source = f.imported_modules[0].get_source() a_data = np.arange(0, N).astype(A.dtype) a = tvm.nd.array(a_data, dev) c = tvm.nd.array(np.zeros(C_N, dtype=C.dtype), dev) f(a, c) return a_data, c.numpy(), kernel_source N, C_N, A, C = get_compute_unaligned() a_data, c, kernel_source = build(A, C, N, C_N) # (uint1*)(A + (1)) is invalid assert "A + (1)" not in kernel_source expected = a_data[1 : C_N + 1] assert np.allclose(c, expected), f"expected={expected}\nactual={c}" N, C_N, A, C = get_compute_aligned() a_data, c, kernel_source = build(A, C, N, C_N) # (uint1*)(A + (2)) is a valid vector load assert "A + 2" in kernel_source expected = a_data[2 : C_N + 2] assert np.allclose(c, expected), f"expected={expected}\nactual={c}" if __name__ == "__main__": pytest.main([__file__])
https://github.com/zk-ml/tachikoma
tests/python/unittest/test_target_codegen_device.py
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. import tvm from tvm import te from tvm.contrib import utils import numpy as np import tvm.testing @tvm.testing.requires_gpu def test_large_uint_imm(): value = (1 << 63) + 123 other = tvm.tir.const(3, "uint64") n = 12 num_thread = 2 A = te.compute((n,), lambda *i: tvm.tir.const(value, "uint64") + other, name="A") s = te.create_schedule(A.op) xo, xi = s[A].split(A.op.axis[0], factor=num_thread) s[A].bind(xi, te.thread_axis("threadIdx.x")) s[A].bind(xo, te.thread_axis("blockIdx.x")) def check_target(device): if not tvm.testing.device_enabled(device): return dev = tvm.device(device, 0) f = tvm.build(s, [A], device) # launch the kernel. a = tvm.nd.empty((n,), dtype=A.dtype, device=dev) f(a) assert a.numpy()[0] == value + 3 check_target("cuda") check_target("vulkan -from_device=0") @tvm.testing.requires_gpu def test_add_pipeline(): n = te.size_var("n") A = te.placeholder((n,), name="A") B = te.placeholder((), name="B") C = te.compute(A.shape, lambda *i: A(*i) + B(), name="C") D = te.compute(A.shape, lambda *i: C(*i) + 1, name="D") s = te.create_schedule(D.op) # GPU schedule have to split by gridIdx and threadIdx num_thread = 256 xo, xi = s[C].split(C.op.axis[0], factor=num_thread) s[C].bind(xi, te.thread_axis("threadIdx.x")) s[C].bind(xo, te.thread_axis("blockIdx.x")) xo, xi = s[D].split(D.op.axis[0], factor=num_thread) s[D].bind(xi, te.thread_axis("threadIdx.x")) s[D].bind(xo, te.thread_axis("blockIdx.x")) def check_target(device, host="stackvm"): if not tvm.testing.device_enabled(device) or not tvm.testing.device_enabled(host): return dev = tvm.device(device, 0) mhost = tvm.driver.build(s, [A, B, D], target=tvm.target.Target(device, host)) f = mhost.entry_func # launch the kernel. n = 1027 a = tvm.nd.array(np.random.uniform(size=n).astype(A.dtype), dev) b = tvm.nd.array(np.random.uniform(size=()).astype(B.dtype), dev) d = tvm.nd.array(np.zeros(n, dtype=D.dtype), dev) f(a, b, d) tvm.testing.assert_allclose(d.numpy(), a.numpy() + b.numpy() + 1) check_target("cuda", host="llvm") check_target("nvptx", host="llvm") check_target("vulkan", host="llvm") check_target("rocm", host="llvm") if __name__ == "__main__": test_large_uint_imm() test_add_pipeline()
https://github.com/zk-ml/tachikoma
tests/python/unittest/test_target_codegen_extern.py
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. import tvm from tvm import te import numpy as np import tvm.testing @tvm.testing.uses_gpu def test_add_pipeline(): nn = 64 max_threads = 4 n = tvm.runtime.convert(nn) A = te.placeholder((n,), name="A") def extern_generator(ins, outs): """Manually write the IR for the extern function, add pipeline""" ib = tvm.tir.ir_builder.create() with ib.for_range(0, (n + 1) // 2) as i: ib.emit( outs[0].vstore( i * 2, ins[0].vload(i * 2, "float32x2") + tvm.tir.const(1, "float32x2") ) ) return ib.get() def extern_generator_gpu(ins, outs): """Manually write the IR for the extern function, add pipeline""" ib = tvm.tir.ir_builder.create() bx = te.thread_axis("blockIdx.x") tx = te.thread_axis("threadIdx.x") ib.scope_attr(bx, "thread_extent", (nn + max_threads - 1) // max_threads) ib.scope_attr(tx, "thread_extent", max_threads) idx = bx.var * max_threads + tx.var with ib.if_scope(ib.likely(idx < n)): ib.emit( outs[0].vstore( idx * 2, ins[0].vload(idx * 2, "float32x2") + tvm.tir.const(1, "float32x2") ) ) return ib.get() C_cpu = te.extern(A.shape, [A], extern_generator, name="C") C_gpu = te.extern(A.shape, [A], extern_generator_gpu, name="C") s_cpu = te.create_schedule(C_cpu.op) s_gpu = te.create_schedule(C_gpu.op) print(tvm.lower(s_cpu, [A, C_cpu], simple_mode=True)) print(tvm.lower(s_gpu, [A, C_gpu], simple_mode=True)) def check_target(target): if not tvm.testing.device_enabled(target): return s = s_gpu if target in ["opencl", "cuda"] else s_cpu C = C_gpu if target in ["opencl", "cuda"] else C_cpu # build and invoke the kernel. f = tvm.build(s, [A, C], target) dev = tvm.device(target, 0) # launch the kernel. n = nn a = tvm.nd.array(np.random.uniform(size=n).astype(A.dtype), dev) c = tvm.nd.array(np.zeros(n, dtype=C.dtype), dev) f(a, c) tvm.testing.assert_allclose(c.numpy(), a.numpy() + 1) check_target("llvm") check_target("opencl") check_target("cuda") def test_pack_buffer_simple(): nn = 1024 n = tvm.runtime.convert(nn) A = te.placeholder((n,), name="A") def extern_generator(ins, outs): """Manually write the IR for the extern function, add pipeline.""" return tvm.tir.call_packed("my_extern_array_func1", ins[0], outs[0]) C = te.extern(A.shape, [A], extern_generator, name="C") s = te.create_schedule(C.op) @tvm.register_func def my_extern_array_func1(aa, bb): aa.copyto(bb) def check_target(target): if not tvm.testing.device_enabled(target): return # build and invoke the kernel. f = tvm.build(s, [A, C], target) dev = tvm.cpu(0) # launch the kernel. n = nn a = tvm.nd.array(np.random.uniform(size=n).astype(A.dtype), dev) c = tvm.nd.array(np.zeros(n, dtype=C.dtype), dev) f(a, c) tvm.testing.assert_allclose(c.numpy(), a.numpy()) check_target("stackvm") check_target("llvm") def test_pack_buffer_intermediate(): nn = 1024 n = tvm.runtime.convert(nn) A = te.placeholder((n,), name="A") B = te.compute((n,), lambda i: A[i] + 1, name="B") def extern_generator(ins, outs): """Manually write the IR for the extern function, add pipeline.""" return tvm.tir.call_packed("my_extern_array_func2", ins[0], outs[0]) C = te.extern(B.shape, [B], extern_generator, name="C") s = te.create_schedule(C.op) def check_target(target): if not tvm.testing.device_enabled(target): return # build and invoke the kernel. f = tvm.build(s, [A, C], target) dev = tvm.cpu(0) # launch the kernel. n = nn a = tvm.nd.array(np.random.uniform(size=n).astype(A.dtype), dev) c = tvm.nd.array(np.zeros(n, dtype=C.dtype), dev) @tvm.register_func def my_extern_array_func2(aa, bb): assert aa.shape == a.shape tvm.testing.assert_allclose(aa.numpy(), a.numpy() + 1) aa.copyto(bb) f(a, c) tvm.testing.assert_allclose(c.numpy(), a.numpy() + 1) check_target("llvm") if __name__ == "__main__": test_pack_buffer_simple() test_pack_buffer_intermediate() test_add_pipeline()
https://github.com/zk-ml/tachikoma