text
stringlengths
1
2.05k
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 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), (E
xecutor("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( """ 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(t
arget)] 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: as
sert 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( """ 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, "siz
e_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( """ 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, chan
nels=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, "workspa
ce_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)) 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) 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 = t
vm.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() e
xecutor = 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.e
xport_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")) 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:]))
import collections
import io
import json
import sys
import unittest from unittest
import mock
import pytest
import tvm
import tvm.testing @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()) 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()) 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()) 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()) 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()) fixture.client_to_server.write(b"foobar\n") assert fixture.server.serve_one_request() == False assert fixture.server_to_client.read() == b"" 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()) 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", } 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", } 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", } 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", } 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 'i
nt'>", }, "id": None, "jsonrpc": "2.0", } 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()
"""Tests for common micro transports."""
import logging
import sys
import unittest
import pytest
import tvm.testing @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): 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): 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): 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(trans
port, transport_logger, get_latest_log): 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): 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): 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): 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()
import tvm
import tvm.testing
import sys
import pytest from tvm
import te
import numpy as np def test_const_saveload_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(): 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(): s1 = tvm.runtime.String("xy\x01z") s2 = tvm.ir.load_json(tvm.ir.save_json(s1)) tvm.ir.assert_structural_equal(s1, s2) 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 assert cfg.config["tir.UnrollLoop"].explicit_unroll == True with pytest.raises(AttributeError): cfg = tvm.transform.PassContext(config={"tir.UnrollLoop": {"invalid": 1}}) with pytest.raises(AttributeError): cfg = tvm.transform.PassContext(config={"inavlid-opt": True}) with pytest.raises(AttributeError): cfg = tvm.transform.PassContext(config={"tir.UnrollLoop": 1}) def test_dict(): x = tvm.tir.const(1) 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()
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 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)
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)) flops = tvm.utils.roofline.x86.estimate_peak_fma_vector_flops(target, dev, remote, "float32") 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)) flops = tvm.utils.roofline.cuda.estimate_peak_flops_tensorcore(target, dev, remote) 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)) bandwidth = tvm.utils.roofline.x86.estimate_peak_bandwidth_dram(target, dev, remote) 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)) bandwidth = tvm.utils.roofline.cuda.estimate_peak_b
andwidth_global_mem(target, dev, remote) 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"): assert call["Percent of Theoretical Optimal"].ratio >= 5.0 elif target == "cuda": assert 90 >= call["Percent of Theoretical Optimal"].ratio >= 0.01 if __name__ == "__main__": tvm.testing.main()
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))]) 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 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 assert stuple == list(shape) assert stuple == tuple(shape) assert stuple == _container.ShapeTuple(shape) if __name__ == "__main__": test_string() test_adt_constructor() test_tuple_object() test_shape_tuple()
"""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()
# 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()
import tvm
import tvm.testing from tvm
import te, runtime
import numpy as np
import json from tvm
import rpc from tvm