怎样用 ONNX Runtime 做图优化和导出优化结果?
先说出你的答案
定义边界、关键机制、一个反例;P8题再补容量、失败与验证。
查看完整题解
参考回答
直接回答
用 SessionOptions.graph_optimization_level 指定级别,传给 InferenceSession。需要保存结果时,再配置 optimized_model_filepath。运行时可在加载时优化,也可复用已保存的优化图。
讲清原理
基础优化可做常量折叠和冗余移除;更深入的优化可能依赖执行后端和硬件布局。离线生成的图要在兼容的部署环境里使用。
例子与易错点
示例配置 CPU 优化并保存模型,再分别加载优化前后的图,用同一输入验证输出。上线还要用目标设备测启动时间与吞吐。
from pathlib import Path
from tempfile import TemporaryDirectory
import numpy as np
import onnxruntime as ort
from onnx import TensorProto, helper
x = helper.make_tensor_value_info("x", TensorProto.FLOAT, [2])
y = helper.make_tensor_value_info("y", TensorProto.FLOAT, [2])
nodes = [helper.make_node("Add", ["a", "b"], ["c"]),
helper.make_node("Add", ["x", "c"], ["y"])]
constants = [helper.make_tensor("a", TensorProto.FLOAT, [2], [1.0, 2.0]),
helper.make_tensor("b", TensorProto.FLOAT, [2], [2.0, 3.0])]
graph = helper.make_graph(nodes, "fold", [x], [y], constants)
model = helper.make_model(graph, opset_imports=[helper.make_opsetid("", 18)],
ir_version=10)
cpu = ["CPUExecutionProvider"]
data = {"x": np.array([10.0, 20.0], dtype=np.float32)}
with TemporaryDirectory() as directory:
path = Path(directory) / "optimized.onnx"
original = ort.SessionOptions()
original.graph_optimization_level = ort.GraphOptimizationLevel.ORT_DISABLE_ALL
reference = ort.InferenceSession(model.SerializeToString(), original, providers=cpu)
options = ort.SessionOptions()
options.graph_optimization_level = ort.GraphOptimizationLevel.ORT_ENABLE_BASIC
options.optimized_model_filepath = str(path)
ort.InferenceSession(model.SerializeToString(), options, providers=cpu)
optimized = ort.InferenceSession(str(path), providers=cpu)
np.testing.assert_allclose(optimized.run(["y"], data)[0], reference.run(["y"], data)[0])
import onnx
assert len(onnx.load(path).graph.node) == 1
print("2 nodes to 1; output unchanged")
和评分标准对照,你能独立回答到哪一步?
自评会安排下一次复习,不保存你的口述内容。
这道题,你掌握得怎么样?
掌握程度由你主动标记,阅读和收藏不会自动改变状态。