Skip to content

Commit

Permalink
Improved MLF to contain workspace info
Browse files Browse the repository at this point in the history
Added functionality to calculate workspace, io and constant
memory required by each primfunc and main function. Moreover,
the workspace information required by each primfunc and main
is reported in metadata.json in the Model Library Format(MLF).
- added functionality to record tir and relay primfuncs
- added tests for model_library_format changes

Change-Id: Ib4a8b787345aa35f8a1645e8a648fad84de37bce
  • Loading branch information
manupak committed Apr 27, 2021
1 parent f681359 commit f786fe4
Show file tree
Hide file tree
Showing 11 changed files with 507 additions and 28 deletions.
94 changes: 90 additions & 4 deletions python/tvm/micro/model_library_format.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,8 @@
from ..relay.backend import graph_executor_factory
from ..relay import param_dict

MAIN_FUNC_NAME_STR = "main_func"


class UnsupportedInModelLibraryFormatError(Exception):
"""Raised when export_model_library_format does not support the given Module tree."""
Expand Down Expand Up @@ -73,8 +75,16 @@ def _populate_codegen_dir(mod, codegen_dir: str):
dso_mod.save(file_name)


def _build_memory_map(graph_json):
"""Build a simpler memory map from graph JSON.
def _build_memory_map(graph_json, function_metadata):
ret = {
"sids": _build_sid_map(graph_json),
"functions": _build_function_memory_map(function_metadata),
}
return ret


def _build_sid_map(graph_json):
"""Build a simpler storage id info map from graph JSON.
Parameters
----------
Expand Down Expand Up @@ -117,6 +127,82 @@ def _build_memory_map(graph_json):
return memory_map


def _build_function_memory_map(function_metadata):
"""Build a simple map that shows how much workspace is required to execute
each primitive function. The main_func describes how much memory is required
to execute the main control code.
Parameters
----------
function_metadata : Map<String, FunctionInfo>
This contains all the compiled metadata on a function basis
Returns
-------
dict :
This will have two entries:
1.) A list with one entry per function describing local memory it is using.
2.) A global memory requirement if all functions are executed sequentially
"""
device_max_workspace = dict()
num_targets = len(function_metadata[MAIN_FUNC_NAME_STR].workspace_sizes.items())
func_entries = []
target_local_entries = dict()
for i in range(num_targets):
for func_name, finfo in function_metadata.items():
if func_name == MAIN_FUNC_NAME_STR:
continue
target = finfo.workspace_sizes.items()[i][0]
device_max_workspace[target] = 0
target_local_entries[func_name] = list()

for func_name, finfo in function_metadata.items():
if func_name == MAIN_FUNC_NAME_STR:
continue
assert len(finfo.constant_sizes.items()) == num_targets
assert len(finfo.io_sizes.items()) == num_targets
target = finfo.workspace_sizes.items()[i][0]
workspace_size = finfo.workspace_sizes.items()[i][1]
target_entry = {
"device": int(target.kind.device_type),
"workspace_size_bytes": int(workspace_size),
}
target_local_entries[func_name].append(target_entry)
if workspace_size > device_max_workspace[target]:
device_max_workspace[target] = workspace_size

for func_name, target_entries_ in target_local_entries.items():
func_entry = {
"function_name": str(func_name),
"workspace": target_entries_,
}
func_entries.append(func_entry)

target_main_entries = list()
for i in range(num_targets):
target = function_metadata[MAIN_FUNC_NAME_STR].workspace_sizes.items()[i][0]
main_func_local_workspace = function_metadata[MAIN_FUNC_NAME_STR].workspace_sizes.items()[
i
][1]
main_func_constants = function_metadata[MAIN_FUNC_NAME_STR].constant_sizes.items()[i][1]
main_func_io = function_metadata[MAIN_FUNC_NAME_STR].io_sizes.items()[i][1]
target_main_entries.append(
{
"device": int(target.kind.device_type),
"workspace_size_bytes": int(device_max_workspace[target])
+ int(main_func_local_workspace),
"constants_size_bytes": int(main_func_constants),
"io_size_bytes": int(main_func_io),
}
)

ret = {
"operator_functions": func_entries,
"main_function": target_main_entries,
}
return ret


def export_model_library_format(mod: graph_executor_factory.GraphExecutorFactoryModule, file_name):
"""Export the build artifact in Model Library Format.
Expand All @@ -133,10 +219,10 @@ def export_model_library_format(mod: graph_executor_factory.GraphExecutorFactory
"""
tempdir = utils.tempdir()
metadata = {
"version": 1,
"version": 2,
"model_name": mod.libmod_name,
"export_datetime": datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%SZ"),
"memory": _build_memory_map(mod.graph_json),
"memory": _build_memory_map(mod.graph_json, mod.function_metadata),
"target": {int(k): str(v) for k, v in mod.target.items()},
"runtimes": ["graph"],
}
Expand Down
1 change: 1 addition & 0 deletions python/tvm/relay/backend/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,3 +16,4 @@
# under the License.
"""Backend codegen modules for relay."""
from . import compile_engine
from . import utils
21 changes: 21 additions & 0 deletions python/tvm/relay/backend/_ffi_api.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
# 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.
"""FFI APIs for tvm.relay.backend"""
import tvm._ffi


tvm._ffi._init_api("relay.backend", __name__)
7 changes: 6 additions & 1 deletion python/tvm/relay/backend/graph_executor_factory.py
Original file line number Diff line number Diff line change
Expand Up @@ -39,9 +39,13 @@ class GraphExecutorFactoryModule:
The name of module
params : dict of str to NDArray
The parameters of module
function_metadata : Map of String to FunctionInfo
This holds a map function names to their information
"""

def __init__(self, ir_mod, target, graph_json_str, libmod, libmod_name, params):
def __init__(
self, ir_mod, target, graph_json_str, libmod, libmod_name, params, function_metadata
):
assert isinstance(graph_json_str, string_types)
fcreate = get_global_func("tvm.graph_executor_factory.create")
args = []
Expand All @@ -56,6 +60,7 @@ def __init__(self, ir_mod, target, graph_json_str, libmod, libmod_name, params):
self.libmod_name = libmod_name
self.params = params
self.iter_cnt = 0
self.function_metadata = function_metadata

def export_library(self, file_name, fcompile=None, addons=None, **kwargs):
return self.module.export_library(file_name, fcompile, addons, **kwargs)
Expand Down
29 changes: 29 additions & 0 deletions python/tvm/relay/backend/utils.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
# 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.
"""The utility functions and classes for relay backend compilation"""
from tvm.runtime import Object
from . import _ffi_api


class FunctionInfo(Object):
"""A data structure to hold metadata of relay primitive functions"""

def __init__(self, dummy):
self.__init_handle_by_constructor__(_ffi_api.FunctionInfo, dummy)

def set_workspace_size(self, target, size):
_ffi_api._FunctionInfo_SetWorkspaceSize(self, target, size)
10 changes: 9 additions & 1 deletion python/tvm/relay/build_module.py
Original file line number Diff line number Diff line change
Expand Up @@ -83,6 +83,7 @@ def __init__(self):
self._optimize = self.mod["optimize"]
self._set_params_func = self.mod["set_params"]
self._get_params_func = self.mod["get_params"]
self._get_function_metadata = self.mod["get_function_metadata"]

def build(self, mod, target=None, target_host=None, params=None):
"""
Expand Down Expand Up @@ -189,6 +190,12 @@ def get_module(self):
"""Return the built module."""
return self._get_module()

def get_function_metadata(self):
"""Return the compiled function metadata.
Currently, the metadata contains workspace size required by
each PrimFunc"""
return self._get_function_metadata()

def get_params(self):
"""Return the updated weights."""
params = self._get_params_func()
Expand Down Expand Up @@ -288,8 +295,9 @@ def build(ir_mod, target=None, target_host=None, params=None, mod_name="default"
with tophub_context:
bld_mod = BuildModule()
graph_json, runtime_mod, params = bld_mod.build(mod=ir_mod, target=target, params=params)
func_metadata = bld_mod.get_function_metadata()
executor_factory = _graph_executor_factory.GraphExecutorFactoryModule(
ir_mod, target, graph_json, runtime_mod, mod_name, params
ir_mod, target, graph_json, runtime_mod, mod_name, params, func_metadata
)
return executor_factory

Expand Down
8 changes: 8 additions & 0 deletions src/relay/backend/build_module.cc
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,10 @@ struct GraphCodegen {
return CallFunc<Array<tvm::runtime::Module>>("get_external_modules", nullptr);
}

Map<String, FunctionInfo> GetFunctionMetadata() {
return CallFunc<Map<String, FunctionInfo>>("get_function_metadata", nullptr);
}

Map<String, IRModule> GetIRModule() {
return CallFunc<Map<String, IRModule>>("get_irmodule", nullptr);
}
Expand Down Expand Up @@ -161,6 +165,10 @@ class RelayBuildModule : public runtime::ModuleNode {
return PackedFunc([sptr_to_self, this](TVMArgs args, TVMRetValue* rv) {
*rv = this->graph_codegen_->GetExternalModules();
});
} else if (name == "get_function_metadata") {
return PackedFunc([sptr_to_self, this](TVMArgs args, TVMRetValue* rv) {
*rv = this->graph_codegen_->GetFunctionMetadata();
});
} else if (name == "optimize") {
return PackedFunc([sptr_to_self, this](TVMArgs args, TVMRetValue* rv) {
ICHECK_EQ(args.num_args, 2);
Expand Down
Loading

0 comments on commit f786fe4

Please sign in to comment.