Implementation:Onnx Onnx Save Model External
| Knowledge Sources | |
|---|---|
| Domains | External_Data, Model_Persistence |
| Last Updated | 2026-02-10 00:00 GMT |
Overview
Concrete tool for saving ONNX models with external tensor data using save_model with external data parameters and the internal write_external_data_tensors function.
Description
When save_model is called with save_as_external_data=True, it automatically calls convert_model_to_external_data to mark tensors for externalization, then write_external_data_tensors to write the tensor data to external files, and finally serializes the lightweight model protobuf. The write_external_data_tensors function iterates over all tensors marked as external, writes their raw data to the specified files, and clears the in-memory raw data from the tensors.
Usage
Use save_model with save_as_external_data=True for the simple case. Use write_external_data_tensors directly when you have already called convert_model_to_external_data and need to control the writing step separately.
Code Reference
Source Location
- Repository: onnx
- File: onnx/__init__.py:295-345 (save_model), onnx/external_data_helper.py:335-356 (write_external_data_tensors)
Signature
# save_model with external data parameters (see Save_Model for full signature)
onnx.save_model(
proto,
f,
save_as_external_data=True,
all_tensors_to_one_file=True,
location="weights.bin",
size_threshold=1024,
)
# Internal function for manual control
def write_external_data_tensors(
model: ModelProto,
filepath: str,
) -> ModelProto:
"""Serializes data for tensors with data_location=EXTERNAL.
Args:
model: Model with externally-marked tensors.
filepath: Base directory for writing external data files.
Returns:
Modified model with raw_data cleared from externalized tensors.
"""
Import
import onnx
from onnx.external_data_helper import write_external_data_tensors
I/O Contract
Inputs
| Name | Type | Required | Description |
|---|---|---|---|
| model | ModelProto | Yes | Model with external data markers |
| filepath | str | Yes | Base directory for writing external data files |
Outputs
| Name | Type | Description |
|---|---|---|
| return | ModelProto | Model with raw_data cleared (data written to disk) |
| files | Files on disk | External data file(s) containing tensor data |
Usage Examples
Automatic External Data Save
import onnx
# One-step save with external data
onnx.save_model(
model,
"output/model.onnx",
save_as_external_data=True,
all_tensors_to_one_file=True,
location="model_weights.bin",
size_threshold=1024,
)
# Creates: output/model.onnx + output/model_weights.bin
Manual Two-step Process
import onnx
from onnx.external_data_helper import (
convert_model_to_external_data,
write_external_data_tensors,
)
# Step 1: Mark tensors for externalization
convert_model_to_external_data(model, location="weights.bin")
# Step 2: Write external data and save model
write_external_data_tensors(model, "output/")
onnx.save_model(model, "output/model.onnx")