forked from apache/tvm
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
[microTVM] Autotuning performance tests (apache#11782)
* Common autotuning test * Autotuned model evaluation utilities * Bugfixes and more enablement * Working autotune profiling test * Refactoring based on PR comments Bugfixes to get tests passing Refactor to remove tflite model for consistency Black formatting Linting and bugfixes Add Apache license header Use larger chunk size to read files Explicitly specify LRU cache size for compatibility with Python 3.7 Pass platform to microTVM common tests Better comment for runtime bound Stop directory from being removed after session creation * Use the actual Zephyr timing library Use unsigned integer Additional logging Try negation Try 64 bit timer Use Zephyr's timing library Fix linting Enable timing utilities
- Loading branch information
Showing
14 changed files
with
373 additions
and
88 deletions.
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,20 @@ | ||
# 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. | ||
|
||
"""Allows the tools specified below to be imported directly from tvm.micro.testing""" | ||
from .evaluation import tune_model, create_aot_session, evaluate_model_accuracy | ||
from .utils import get_supported_boards, get_target |
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,150 @@ | ||
# 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. | ||
|
||
""" | ||
Provides high-level functions for instantiating and timing AOT models. Used | ||
by autotuning tests in tests/micro, and may be used for more performance | ||
tests in the future. | ||
""" | ||
|
||
from io import StringIO | ||
from pathlib import Path | ||
from contextlib import ExitStack | ||
import tempfile | ||
|
||
import tvm | ||
|
||
|
||
def tune_model( | ||
platform, board, target, mod, params, num_trials, tuner_cls=tvm.autotvm.tuner.GATuner | ||
): | ||
"""Autotunes a model with microTVM and returns a StringIO with the tuning logs""" | ||
with tvm.transform.PassContext(opt_level=3, config={"tir.disable_vectorize": True}): | ||
tasks = tvm.autotvm.task.extract_from_program(mod["main"], {}, target) | ||
assert len(tasks) > 0 | ||
assert isinstance(params, dict) | ||
|
||
module_loader = tvm.micro.AutoTvmModuleLoader( | ||
template_project_dir=tvm.micro.get_microtvm_template_projects(platform), | ||
project_options={ | ||
f"{platform}_board": board, | ||
"project_type": "host_driven", | ||
}, | ||
) | ||
|
||
builder = tvm.autotvm.LocalBuilder( | ||
n_parallel=1, | ||
build_kwargs={"build_option": {"tir.disable_vectorize": True}}, | ||
do_fork=False, | ||
build_func=tvm.micro.autotvm_build_func, | ||
runtime=tvm.relay.backend.Runtime("crt", {"system-lib": True}), | ||
) | ||
runner = tvm.autotvm.LocalRunner(number=1, repeat=1, timeout=100, module_loader=module_loader) | ||
measure_option = tvm.autotvm.measure_option(builder=builder, runner=runner) | ||
|
||
results = StringIO() | ||
for task in tasks: | ||
tuner = tuner_cls(task) | ||
|
||
tuner.tune( | ||
n_trial=num_trials, | ||
measure_option=measure_option, | ||
callbacks=[ | ||
tvm.autotvm.callback.log_to_file(results), | ||
tvm.autotvm.callback.progress_bar(num_trials, si_prefix="M"), | ||
], | ||
si_prefix="M", | ||
) | ||
assert tuner.best_flops > 1 | ||
|
||
return results | ||
|
||
|
||
def create_aot_session( | ||
platform, | ||
board, | ||
target, | ||
mod, | ||
params, | ||
build_dir=Path(tempfile.mkdtemp()), | ||
tune_logs=None, | ||
use_cmsis_nn=False, | ||
): | ||
"""AOT-compiles and uploads a model to a microcontroller, and returns the RPC session""" | ||
|
||
executor = tvm.relay.backend.Executor("aot") | ||
crt_runtime = tvm.relay.backend.Runtime("crt", {"system-lib": True}) | ||
|
||
with ExitStack() as stack: | ||
config = {"tir.disable_vectorize": True} | ||
if use_cmsis_nn: | ||
config["relay.ext.cmsisnn.options"] = {"mcpu": target.mcpu} | ||
stack.enter_context(tvm.transform.PassContext(opt_level=3, config=config)) | ||
if tune_logs is not None: | ||
stack.enter_context(tvm.autotvm.apply_history_best(tune_logs)) | ||
|
||
lowered = tvm.relay.build( | ||
mod, | ||
target=target, | ||
params=params, | ||
runtime=crt_runtime, | ||
executor=executor, | ||
) | ||
parameter_size = len(tvm.runtime.save_param_dict(lowered.get_params())) | ||
print(f"Model parameter size: {parameter_size}") | ||
|
||
# Once the project has been uploaded, we don't need to keep it | ||
project = tvm.micro.generate_project( | ||
str(tvm.micro.get_microtvm_template_projects(platform)), | ||
lowered, | ||
build_dir / "project", | ||
{ | ||
f"{platform}_board": board, | ||
"project_type": "host_driven", | ||
}, | ||
) | ||
project.build() | ||
project.flash() | ||
|
||
return tvm.micro.Session(project.transport()) | ||
|
||
|
||
# This utility functions was designed ONLY for one input / one output models | ||
# where the outputs are confidences for different classes. | ||
def evaluate_model_accuracy(session, aot_executor, input_data, true_labels, runs_per_sample=1): | ||
"""Evaluates an AOT-compiled model's accuracy and runtime over an RPC session. Works well | ||
when used with create_aot_session.""" | ||
|
||
assert aot_executor.get_num_inputs() == 1 | ||
assert aot_executor.get_num_outputs() == 1 | ||
assert runs_per_sample > 0 | ||
|
||
predicted_labels = [] | ||
aot_runtimes = [] | ||
for sample in input_data: | ||
aot_executor.get_input(0).copyfrom(sample) | ||
result = aot_executor.module.time_evaluator("run", session.device, number=runs_per_sample)() | ||
runtime = result.mean | ||
output = aot_executor.get_output(0).numpy() | ||
predicted_labels.append(output.argmax()) | ||
aot_runtimes.append(runtime) | ||
|
||
num_correct = sum(u == v for u, v in zip(true_labels, predicted_labels)) | ||
average_time = sum(aot_runtimes) / len(aot_runtimes) | ||
accuracy = num_correct / len(predicted_labels) | ||
return average_time, accuracy |
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
Oops, something went wrong.