onnx.reference¶
DefaultNone¶
ReferenceEvaluator¶
- class onnx.reference.ReferenceEvaluator(proto: Any, opsets: dict[str, int] | None = None, functions: list[ReferenceEvaluator | FunctionProto] | None = None, verbose: int = 0, new_ops: list[type[OpRun]] | None = None, optimized: bool = True)[source]¶
计算 ONNX proto (ModelProto、FunctionProto、GraphProto、NodeProto) 的输出。
这是 ONNX 规范的纯 Python 实现。官方规范与此处实现之间可能存在不匹配之处。如果存在不匹配,以官方规范为准。
- 参数::
proto –
onnx.ModelProto
,onnx.GraphProto
,onnx.FunctionProto
,onnx.NodeProto
, 文件名或字节串verbose – 执行期间在标准输出上显示中间结果
opsets – 如果 proto 是 GraphProto 的实例,opsets 必须由以下字典定义
functions – 已知的 onnx 函数
new_ops – 此运行时可用于测试新算子的实现,new_ops 是继承自
OpRun
的类列表,每个类必须定义静态属性 domain,同一个算子可以有多个实现,列表中第一个被使用。optimized – 某些算子有两种实现:一种是与算子数学定义相对应的朴素实现,另一种是更高效的实现。算子 Conv 就是这种情况。朴素版本比使用 Conv = im2col + Gemm 分解的优化版本慢十倍。如果为 True,则将所有优化的内核添加到 new_ops 中,并在列表 new_ops 尚未包含相应实现时使用这些优化内核,而非内部实现。
此类将每个节点映射到其关联的实现。当遇到函数的子图时,它使用此类来执行子图或该函数。下一个示例展示了如何使用存储在 model.onnx 文件中的 onnx 模型来运行 ReferenceEvaluator。
import numpy as np from onnx.reference import ReferenceEvaluator X = np.array(...) sess = ReferenceEvaluator("model.onnx") results = sess.run(None, {"X": X}) print(results[0]) # display the first result
参数 verbose 可用于显示中间结果。
import numpy as np from onnx.reference import ReferenceEvaluator X = np.array(...) sess = ReferenceEvaluator("model.onnx", verbose=1) results = sess.run(None, {"X": X}) print(results[0]) # display the first result
此类可以使用文件夹 ops 中提供的任何实现。添加实现需要进行两处更改。第一处是实现本身。任何现有节点都可以用作模板。第二处是在 _op_list.py 文件中添加一行,导入该文件并让引用评估器知道它的存在。
此类也可用于测试自定义算子的实现。假设这个新算子是 domain 为 custom 的 InvAlpha。该实现必须放在一个继承自
OpRun
的类中。它还必须定义属性 op_domain。下面是一个计算 \(\\frac{1}{X + \\alpha}\) 的示例。from onnx.reference.op_run import OpRun class InvAlpha(OpRun): op_domain = "custom" def _run(self, x, alpha=None): # type: ignore # None must be the default value, it is automatically # replaced by class OpRun with either the default value # specified in the NodeProto or an attribute value defined # in a `FunctionProto`. return (1 / (x + alpha),)
alpha 是一个属性。它可以由 onnx 节点定义,也可以由使用此节点的函数定义。可以安全地假设属性与输入同时已知。Class ReferenceEvaluator 必须知道此新实现,这可以通过指定参数 new_ops 来完成。
sess = ReferenceEvaluator(onnx_model, new_ops=[InvAlpha]) got = sess.run(None, {"X": x})[0]
一个特定的节点可以简单地被评估。
import numpy as np from onnx.reference.ops._op_list import Celu x = np.array([[0, 1], [-1, 2]], dtype=np.float32) y = Celu.eval(x, alpha=0.5) print(y)
[[ 0. 1. ] [-0.43233237 2. ]]
这也可以表达为
import numpy as np from onnx.reference.ops import load_op Celu = load_op("", "Celu") # domain is "" x = np.array([[0, 1], [-1, 2]], dtype=np.float32) y = Celu.eval(x, alpha=0.5) print(y)
[[ 0. 1. ] [-0.43233237 2. ]]
可以覆盖现有算子。类名必须相同。对于默认域,不必指定域。但是,默认情况下,OpRun 类将加载此算子的最新版本。可以通过添加
OpSchema
类型的静态属性 op_schema 来明确指定。from onnx.reference.op_run.op_conv import Conv as _Conv class Conv(_Conv): op_schema = instance_of_OpSchema() def _run(self, ...): ... An operator may be different in a later opset. In that case, a new implementation needs to be registered. `Pad_11`, `Pad_18`. `Pad_11` is the implementation chose for opset in [11, 17]. `Pad_18` is selected for any greater opset. Both classes must be imported into file `_op_list.py` to register their existence to the runtime. An operator may have a reference implementation such as `CastLike` and still be defined as a function. By default, the reference implementation is used. This behavior can be changed by adding a class to the list of overwritten operators. It must inherit from :class:`OpRunExpand`. :: from onnx.reference.op_run import OpRunExpand class CastLike(OpRunExpand): op_domain = "" ref = ReferenceEvaluator(model, new_ops=[CastLike]) # ... This mechanism is used in unit test to check the function implementation a schema may define.
- property input_names¶
返回输入名称。
- property opsets¶
返回 opset。
- property output_names¶
返回输出名称。
- run(output_names, feed_inputs: dict[str, Any], attributes: dict[str, Any] | None = None, intermediate: bool = False) dict[str, Any] | list[Any] [source]¶
执行 onnx 模型。
- 参数::
output_names – 按名称请求的输出,None 表示所有输出
feed_inputs – 字典 { 输入名称: 输入值 }
attributes – 如果实例运行 FunctionProto,则为属性值
intermediate – 如果为 True,函数将所有结果(最终结果和中间结果)都在同一个字典中返回;如果为 False,则只在列表中返回最终结果
- 返回::
如果 intermediate 为 False,则返回请求输出的列表;否则,在字典中返回命名结果
OpFunction¶
- class onnx.reference.op_run.OpFunction(onnx_node: NodeProto, run_params: dict[str, Any] | None = None, impl: Any | None = None, attributes: dict[str, Any] | None = None)[source]¶
运行自定义函数。
- classmethod create(n_inputs: int | None = None, n_outputs: int | None = None, verbose: int = 0, **kwargs: Any) Any ¶
根据给定信息实例化此类。
- 参数::
n_inputs – 输入数量(默认由算子 schema 定义)
n_outputs – 输出数量(默认由算子 schema 定义)
verbose – 详细程度
**kwargs – 节点属性
- 返回::
NodeProto
- classmethod eval(*args: list[Any], n_outputs: int | None = None, verbose: int = 0, **kwargs: Any) Any ¶
评估此算子。
- 参数::
*args – 输入
n_outputs – 输出数量(默认由算子 schema 定义)
verbose – 详细程度
**kwargs – 节点属性
- 返回::
NodeProto
- static implicit_inputs(graph: GraphProto) list[str] ¶
返回所有未注册为输入且未由图内节点生成的变量。这些输入是调用此图的图中存在的上下文的一部分。
- classmethod make_node(n_inputs: int | None = None, n_outputs: int | None = None, **kwargs: Any) NodeProto ¶
根据给定信息为此类创建 ONNX 节点。
- 参数::
n_inputs – 输入数量(默认由算子 schema 定义)
n_outputs – 输出数量(默认由算子 schema 定义)
verbose – 详细程度
**kwargs – 节点属性
- 返回::
NodeProto
方法
eval
创建由方法make_node
返回的 onnx 节点。import numpy as np from onnx.reference.ops._op_list import Celu onnx_node = Celu.make_node(alpha=0.5) print(onnx_node)
input: "x0" output: "y0" op_type: "Celu" attribute { name: "alpha" f: 0.5 type: FLOAT }
- run(*args, linked_attributes=None, context=None)¶
调用方法
_run
,捕获异常,显示更长的错误消息。- 参数::
*args – 输入
linked_attributes – 如果此属性链接到其所属函数的属性,则使用此参数
context – 如果此节点是子图的一部分,则 context 是一个字典,其中包含此节点可能使用的值
- 返回::
结果的元组
OpRun¶
- class onnx.reference.op_run.OpRun(onnx_node: NodeProto, run_params: dict[str, Any], schema: Any | None = None)[source]¶
此子文件夹中所有算子的祖先类。
- 参数::
onnx_node – onnx 节点
run_params – 附加参数,例如 verbose, opsets (如果算子有子图,可以有多个), log 用于日志记录函数
schema – 算子 schema
- classmethod create(n_inputs: int | None = None, n_outputs: int | None = None, verbose: int = 0, **kwargs: Any) Any [source]¶
根据给定信息实例化此类。
- 参数::
n_inputs – 输入数量(默认由算子 schema 定义)
n_outputs – 输出数量(默认由算子 schema 定义)
verbose – 详细程度
**kwargs – 节点属性
- 返回::
NodeProto
- classmethod eval(*args: list[Any], n_outputs: int | None = None, verbose: int = 0, **kwargs: Any) Any [source]¶
评估此算子。
- 参数::
*args – 输入
n_outputs – 输出数量(默认由算子 schema 定义)
verbose – 详细程度
**kwargs – 节点属性
- 返回::
NodeProto
- static implicit_inputs(graph: GraphProto) list[str] [source]¶
返回所有未注册为输入且未由图内节点生成的变量。这些输入是调用此图的图中存在的上下文的一部分。
- classmethod make_node(n_inputs: int | None = None, n_outputs: int | None = None, **kwargs: Any) NodeProto [source]¶
根据给定信息为此类创建 ONNX 节点。
- 参数::
n_inputs – 输入数量(默认由算子 schema 定义)
n_outputs – 输出数量(默认由算子 schema 定义)
verbose – 详细程度
**kwargs – 节点属性
- 返回::
NodeProto
方法
eval
创建由方法make_node
返回的 onnx 节点。import numpy as np from onnx.reference.ops._op_list import Celu onnx_node = Celu.make_node(alpha=0.5) print(onnx_node)
input: "x0" output: "y0" op_type: "Celu" attribute { name: "alpha" f: 0.5 type: FLOAT }