-
Notifications
You must be signed in to change notification settings - Fork 3.5k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
[RUNTIME] Support module based interface runtime #5753
Merged
Merged
Changes from all commits
Commits
Show all changes
29 commits
Select commit
Hold shift + click to select a range
3fbf640
Support Module based interface runtime
FrozenGene 3fbd368
remove unnecessary comment
FrozenGene cb101ac
support rpc (except params issue)
FrozenGene 95803d0
solve rpc issue
FrozenGene 166e009
support package params
FrozenGene 52adf79
[Complete all the functionality] Support multi models of package params
FrozenGene 081af5f
refactor graph runtime module list
FrozenGene 4b34dc2
header reorder
FrozenGene 1acf52d
graph runtime debug
FrozenGene b3f2873
function signature
FrozenGene 46ff4e1
rebase to master and solve lint / clang-format error
FrozenGene ba5b0c5
remove export_graph_mod
FrozenGene bae954c
address comments
FrozenGene 1e69f4b
refactor
FrozenGene ef18312
refactor
FrozenGene 6f7ceee
clang-format
FrozenGene 893c531
comment
FrozenGene 6c515ef
fix GetLib() CHECK issue
FrozenGene 926acec
refactor
FrozenGene edb60a3
add missing device api check
FrozenGene 5e08ea9
Solve tvm::Map odr
FrozenGene c8f505c
skip debug graph runtime test if not enable
FrozenGene da6b1d9
Trigger notification
FrozenGene e796d4b
address comments
FrozenGene 03793b3
update doc comments
FrozenGene d7f44a9
add get_json for debug graph runtime
FrozenGene 5c23a07
comment fix
FrozenGene 54bbdc8
Trigger CI
FrozenGene a83333a
update
FrozenGene File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,84 @@ | ||
# 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. | ||
"""Graph runtime factory.""" | ||
import warnings | ||
from tvm._ffi.base import string_types | ||
from tvm._ffi.registry import get_global_func | ||
from tvm.runtime import ndarray | ||
|
||
class GraphRuntimeFactoryModule(object): | ||
"""Graph runtime factory module. | ||
This is a module of graph runtime factory | ||
|
||
Parameters | ||
---------- | ||
graph_json_str : str | ||
The graph to be deployed in json format output by graph compiler. | ||
The graph can contain operator(tvm_op) that points to the name of | ||
PackedFunc in the libmod. | ||
libmod : tvm.Module | ||
The module of the corresponding function | ||
libmod_name: str | ||
The name of module | ||
params : dict of str to NDArray | ||
The parameters of module | ||
""" | ||
|
||
def __init__(self, graph_json_str, libmod, libmod_name, params): | ||
assert isinstance(graph_json_str, string_types) | ||
fcreate = get_global_func("tvm.graph_runtime_factory.create") | ||
args = [] | ||
for k, v in params.items(): | ||
args.append(k) | ||
args.append(ndarray.array(v)) | ||
self.module = fcreate(graph_json_str, libmod, libmod_name, *args) | ||
self.graph_json = graph_json_str | ||
self.lib = libmod | ||
self.libmod_name = libmod_name | ||
self.params = params | ||
self.iter_cnt = 0 | ||
|
||
def export_library(self, file_name, fcompile=None, addons=None, **kwargs): | ||
return self.module.export_library(file_name, fcompile, addons, **kwargs) | ||
|
||
# Sometimes we want to get params explicitly. | ||
# For example, we want to save its params value to | ||
# an independent file. | ||
def get_params(self): | ||
return self.params | ||
|
||
def get_json(self): | ||
return self.graph_json | ||
|
||
def __getitem__(self, item): | ||
return self.module.__getitem__(item) | ||
|
||
def __iter__(self): | ||
warnings.warn( | ||
"legacy graph runtime behaviour of producing json / lib / params will be " | ||
"removed in the next release ", | ||
DeprecationWarning, 2) | ||
return self | ||
|
||
def __next__(self): | ||
if self.iter_cnt > 2: | ||
raise StopIteration | ||
|
||
objs = [self.graph_json, self.lib, self.params] | ||
obj = objs[self.iter_cnt] | ||
self.iter_cnt += 1 | ||
return obj |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,175 @@ | ||
/* | ||
* 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. | ||
*/ | ||
|
||
/*! | ||
* \file graph_runtime_factory.cc | ||
* \brief Graph runtime factory implementations | ||
*/ | ||
|
||
#include "./graph_runtime_factory.h" | ||
|
||
#include <tvm/node/container.h> | ||
#include <tvm/runtime/device_api.h> | ||
#include <tvm/runtime/registry.h> | ||
|
||
#include <iterator> | ||
#include <vector> | ||
|
||
namespace tvm { | ||
namespace runtime { | ||
|
||
GraphRuntimeFactory::GraphRuntimeFactory( | ||
const std::string& graph_json, | ||
const std::unordered_map<std::string, tvm::runtime::NDArray>& params, | ||
const std::string& module_name) { | ||
graph_json_ = graph_json; | ||
params_ = params; | ||
module_name_ = module_name; | ||
} | ||
|
||
PackedFunc GraphRuntimeFactory::GetFunction( | ||
const std::string& name, const tvm::runtime::ObjectPtr<tvm::runtime::Object>& sptr_to_self) { | ||
if (name == module_name_) { | ||
return PackedFunc([sptr_to_self, this](TVMArgs args, TVMRetValue* rv) { | ||
std::vector<TVMContext> contexts; | ||
for (int i = 0; i < args.num_args; ++i) { | ||
contexts.emplace_back(args[i].operator TVMContext()); | ||
} | ||
*rv = this->RuntimeCreate(contexts); | ||
}); | ||
} else if (name == "debug_create") { | ||
return PackedFunc([sptr_to_self, this](TVMArgs args, TVMRetValue* rv) { | ||
CHECK_GE(args.size(), 2); | ||
std::string module_name = args[0].operator String(); | ||
CHECK(module_name == module_name_) << "Currently we only support single model for now."; | ||
std::vector<TVMContext> contexts; | ||
for (int i = 1; i < args.num_args; ++i) { | ||
contexts.emplace_back(args[i].operator TVMContext()); | ||
} | ||
*rv = this->DebugRuntimeCreate(contexts); | ||
}); | ||
} else if (name == "remove_params") { | ||
return PackedFunc([sptr_to_self, this](TVMArgs args, TVMRetValue* rv) { | ||
std::unordered_map<std::string, tvm::runtime::NDArray> empty_params{}; | ||
auto exec = | ||
make_object<GraphRuntimeFactory>(this->graph_json_, empty_params, this->module_name_); | ||
exec->Import(this->imports_[0]); | ||
*rv = Module(exec); | ||
}); | ||
} else { | ||
return PackedFunc(); | ||
} | ||
} | ||
|
||
void GraphRuntimeFactory::SaveToBinary(dmlc::Stream* stream) { | ||
stream->Write(graph_json_); | ||
std::vector<std::string> names; | ||
std::vector<DLTensor*> arrays; | ||
for (const auto& v : params_) { | ||
names.emplace_back(v.first); | ||
arrays.emplace_back(const_cast<DLTensor*>(v.second.operator->())); | ||
} | ||
uint64_t sz = arrays.size(); | ||
CHECK(sz == names.size()); | ||
stream->Write(sz); | ||
stream->Write(names); | ||
for (size_t i = 0; i < sz; ++i) { | ||
tvm::runtime::SaveDLTensor(stream, arrays[i]); | ||
} | ||
stream->Write(module_name_); | ||
} | ||
|
||
Module GraphRuntimeFactory::RuntimeCreate(const std::vector<TVMContext>& ctxs) { | ||
auto exec = make_object<GraphRuntime>(); | ||
exec->Init(this->graph_json_, this->imports_[0], ctxs); | ||
// set params | ||
SetParams(exec.get(), this->params_); | ||
return Module(exec); | ||
} | ||
|
||
Module GraphRuntimeFactory::DebugRuntimeCreate(const std::vector<TVMContext>& ctxs) { | ||
const PackedFunc* pf = tvm::runtime::Registry::Get("tvm.graph_runtime_debug.create"); | ||
CHECK(pf != nullptr) << "Cannot find function tvm.graph_runtime_debug.create in registry. " | ||
"Do you enable debug graph runtime build?"; | ||
// Debug runtime create packed function will call GetAllContexs, so we unpack the ctxs. | ||
std::vector<int> unpacked_ctxs; | ||
for (const auto& ctx : ctxs) { | ||
unpacked_ctxs.emplace_back(ctx.device_type); | ||
unpacked_ctxs.emplace_back(ctx.device_id); | ||
} | ||
size_t args_size = unpacked_ctxs.size() + 2; | ||
std::vector<TVMValue> values(args_size); | ||
std::vector<int> codes(args_size); | ||
runtime::TVMArgsSetter setter(values.data(), codes.data()); | ||
setter(0, this->graph_json_); | ||
setter(1, this->imports_[0]); | ||
for (size_t i = 0; i < unpacked_ctxs.size(); ++i) { | ||
setter(i + 2, unpacked_ctxs[i]); | ||
} | ||
TVMRetValue rv; | ||
pf->CallPacked(TVMArgs(values.data(), codes.data(), args_size), &rv); | ||
Module mod = rv.operator Module(); | ||
// debug graph runtime is one child class of graph runtime. | ||
SetParams(const_cast<GraphRuntime*>(mod.as<GraphRuntime>()), this->params_); | ||
return mod; | ||
} | ||
|
||
Module GraphRuntimeFactoryModuleLoadBinary(void* strm) { | ||
dmlc::Stream* stream = static_cast<dmlc::Stream*>(strm); | ||
std::string graph_json; | ||
std::unordered_map<std::string, tvm::runtime::NDArray> params; | ||
std::string module_name; | ||
CHECK(stream->Read(&graph_json)); | ||
uint64_t sz; | ||
CHECK(stream->Read(&sz)); | ||
std::vector<std::string> names; | ||
CHECK(stream->Read(&names)); | ||
CHECK(sz == names.size()); | ||
for (size_t i = 0; i < sz; ++i) { | ||
tvm::runtime::NDArray temp; | ||
temp.Load(stream); | ||
params[names[i]] = temp; | ||
} | ||
CHECK(stream->Read(&module_name)); | ||
auto exec = make_object<GraphRuntimeFactory>(graph_json, params, module_name); | ||
return Module(exec); | ||
} | ||
|
||
TVM_REGISTER_GLOBAL("tvm.graph_runtime_factory.create").set_body([](TVMArgs args, TVMRetValue* rv) { | ||
CHECK_GE(args.num_args, 3) << "The expected number of arguments for " | ||
"graph_runtime_factory.create needs at least 3, " | ||
FrozenGene marked this conversation as resolved.
Show resolved
Hide resolved
|
||
"but it has " | ||
<< args.num_args; | ||
// The argument order is graph_json, module, module_name, params. | ||
CHECK_EQ((args.size() - 3) % 2, 0); | ||
std::unordered_map<std::string, tvm::runtime::NDArray> params; | ||
for (size_t i = 3; i < static_cast<size_t>(args.size()); i += 2) { | ||
std::string name = args[i].operator String(); | ||
params[name] = args[i + 1].operator tvm::runtime::NDArray(); | ||
} | ||
auto exec = make_object<GraphRuntimeFactory>(args[0], params, args[2]); | ||
exec->Import(args[1]); | ||
*rv = Module(exec); | ||
}); | ||
|
||
TVM_REGISTER_GLOBAL("runtime.module.loadbinary_GraphRuntimeFactory") | ||
.set_body_typed(GraphRuntimeFactoryModuleLoadBinary); | ||
|
||
} // namespace runtime | ||
} // namespace tvm |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
With the
MetadataModule
, we should be able to remove the serialization and deserialization of params for GraphRuntime and the factory. That may affect downstream users. I can take a stab on it later.There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Could you give me a link about this MetadataModule?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
It was introduced in #5770. We should not do it in this pr. This just makes you aware of it.