外部数据¶
加载带有外部数据的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 中(如果已设置),否则存储在 message 中。
external_data 字段¶
external_data 字段存储描述数据位置的字符串键值对
识别的键有:
"location"(必填) - 相对于存储ONNX protobuf模型的文件系统目录的文件路径。不允许使用上级目录路径组件(如…),在解析时应将其去除。"offset"(可选)- 存储数据开始的字节位置。整数以字符串形式存储。偏移值应为页面大小(通常为4kb)的倍数,以支持mmap。在Windows上,偏移值应为VirtualAlloc 分配粒度(通常为64kb)的倍数,以支持内存映射。"length"(可选)- 包含数据的字节数。整数以字符串形式存储。"checksum"(可选)- 在‘location’键下指定的文件的SHA1摘要。
加载ONNX文件后,所有external_data字段可能会更新一个额外的键("basepath"),该键存储加载ONNX模型文件的目录路径。
外部数据文件¶
存储在外部数据文件中的数据将与当前ONNX实现中raw_data字段使用的二进制字节字符串格式相同。