外部資料

載入具有外部資料的 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