外部数据

加载带有外部数据的 ONNX 模型

  • [默认] 如果外部数据与模型在同一目录下,直接使用 onnx.load() 即可。

import onnx

onnx_model = onnx.load("path/to/the/model.onnx")
  • 如果外部数据在另一个目录下,使用 load_external_data_for_model() 指定目录路径,并在使用 onnx.load() 后加载。

import onnx
from onnx.external_data_helper import load_external_data_for_model

onnx_model = onnx.load("path/to/the/model.onnx", load_external_data=False)
load_external_data_for_model(onnx_model, "data/directory/path/")
# Then the onnx_model has loaded the external data from the specific directory

将 ONNX 模型转换为外部数据

import onnx
from onnx.external_data_helper import convert_model_to_external_data

onnx_model = ... # Your model in memory as ModelProto
convert_model_to_external_data(onnx_model, all_tensors_to_one_file=True, location="filename", size_threshold=1024, convert_attribute=False)
# Must be followed by save_model to save the converted model to a specific path
onnx.save_model(onnx_model, "path/to/save/the/model.onnx")
# Then the onnx_model has converted raw data as external data and saved to specific directory

将 ONNX 模型转换为外部数据并保存

import onnx

onnx_model = ... # Your model in memory as ModelProto
onnx.save_model(onnx_model, "path/to/save/the/model.onnx", save_as_external_data=True, all_tensors_to_one_file=True, location="filename", size_threshold=1024, convert_attribute=False)
# Then the onnx_model has converted raw data as external data and saved to specific directory

用于带有外部数据的模型的 onnx.checker

带有外部数据的模型 (<2GB)

当前检查器支持检查带有外部数据的模型。请向检查器指定已加载的 onnx 模型或模型路径。

大型模型 >2GB

然而,对于大于 2GB 的模型,请使用模型路径作为 onnx.checker 的输入,并且外部数据需要位于同一目录下。

import onnx

onnx.checker.check_model("path/to/the/model.onnx")
# onnx.checker.check_model(loaded_onnx_model) will fail if given >2GB model

TensorProto: data_location 和 external_data 字段

TensorProto 消息类型中有两个与外部数据相关的字段。

data_location 字段

data_location 字段存储此张量数据的所在位置。值必须是以下之一:

  • MESSAGE - 数据存储在 protobuf 消息内部的类型特定字段中。

  • RAW - 数据存储在 raw_data 字段中。

  • EXTERNAL - 数据存储在 external_data 字段描述的外部位置。

  • value 未设置 - 历史遗留值。假设数据存储在 raw_data 中(如果已设置),否则存储在消息中。

external_data 字段

external_data 字段存储描述数据位置的字符串键值对

可识别的键包括:

  • "location" (必需) - 相对于存储 ONNX protobuf 模型的 文件系统目录的文件路径。不允许使用诸如 .. 之类的上级目录路径组件,解析时应将其剥离。

  • "offset" (可选) - 存储数据起始字节的位置。整数存储为字符串。为启用 mmap 支持,偏移量值应为页大小(通常为 4kb)的倍数。在 Windows 上,为启用内存映射,偏移量值应为 VirtualAlloc 分配粒度(通常为 64kb)的倍数。

  • "length" (可选) - 包含数据的字节数。整数存储为字符串。

  • "checksum" (可选) - ‘location’ 键中指定文件的 SHA1 摘要。

加载 ONNX 文件后,所有 external_data 字段可能会使用附加键 ("basepath") 进行更新,该键存储加载 ONNX 模型文件所在的目录路径。

外部数据文件

存储在外部数据文件中的数据将采用与当前 ONNX 实现中 raw_data 字段使用的相同的二进制字节字符串格式。

参考 https://github.com/onnx/onnx/pull/678