ONNX Runtime 的 profile 可以怎样找性能瓶颈?
查看完整题解
参考回答
直接回答
通过 SessionOptions.enable_profiling 打开性能分析,执行有代表性的请求后调用 end_profiling()。运行时输出 trace,可按节点、事件类别和时长查看。
讲清原理
先看是否在会话初始化、特定算子或数据搬运环节花了时间。根据实际 trace,再决定改模型、改线程或改输入输出放置。性能分析本身也有开销,通常按需开。
例子与易错点
示例读取 CPU 会话生成的 JSON,找到节点内核记录。生产排查应使用真实批量与硬件,并区分偶发的长请求。
from pathlib import Path
from tempfile import TemporaryDirectory
import json
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])
graph = helper.make_graph([helper.make_node("Relu", ["x"], ["y"])], "profile", [x], [y])
model = helper.make_model(graph, opset_imports=[helper.make_opsetid("", 18)],
ir_version=10)
with TemporaryDirectory() as directory:
options = ort.SessionOptions()
options.enable_profiling = True
options.profile_file_prefix = str(Path(directory) / "trace")
session = ort.InferenceSession(model.SerializeToString(), options,
providers=["CPUExecutionProvider"])
session.run(["y"], {"x": np.array([-1, 2], dtype=np.float32)})
events = json.loads(Path(session.end_profiling()).read_text())
nodes = [event for event in events if event["cat"] == "Node"
and event["name"].endswith("_kernel_time")]
assert any(event["args"].get("op_name") == "Relu"
and event["args"].get("provider") == "CPUExecutionProvider"
and event["dur"] >= 0 for event in nodes)
print("CPU Relu kernel recorded")
这道题,你掌握得怎么样?
掌握程度由你主动标记,阅读和收藏不会自动改变状态。