ModelProto#

Deferred weights#

load(path, defer_weights=True) reads binary ONNX structure without materializing large raw tensor payloads. Unlike skip_raw_data, it retains a non-serialized immutable source range for every inline raw_data field and ordinary external tensor. External locations remain relative to the original model directory, including when several tensors share one weights file. Non-empty payloads smaller than raw_data_threshold (1024 bytes in Python, 64 bytes by default in C++) are loaded during parsing while keeping their source, so they can still be unloaded; pass raw_data_threshold=0 to defer every payload. The main model file is memory-mapped through its securely pinned descriptor: metadata decoding does not issue a system call per varint byte. Parsing reads small payloads but skips large raw payload ranges without copying or explicitly reading them. Mapping reserves virtual address space, not a resident copy of the weights; the operating system may still fetch neighboring bytes at page granularity.

from onnx_light.onnx import load, save

model = load("model.onnx", defer_weights=True)
model.load_weight("layer.weight")  # Other weights remain unloaded.
assert model.is_weight_loaded("layer.weight")
model.unload_weight("layer.weight")
model.load_weight("layer.weight")  # Reloads from the original byte range.
model.load_weights()
save(model, "materialized.onnx")

The equivalent native API uses a file-backed stream and ParseOptions:

onnx_light::ModelProto model;
onnx_light::ParseOptions options;
options.defer_weights = true;
onnx_light::utils::FileStream input("model.onnx");
model.ParseFromStream(input, options);
model.LoadWeight("layer.weight");
model.UnloadWeight("layer.weight");
model.LoadWeights();
model.SerializeToFile("materialized.onnx");

weight_names() / WeightNames() includes nested graphs, tensor attributes, sparse tensors, functions and rewrite plans. A name must match exactly one tensor: missing and duplicate names raise errors, including repeated empty names. Bulk operations traverse all deferred tensors without name lookup. Load/unload methods return whether they changed the payload state; bulk methods return a count. Zero-sized raw tensors have a distinct loaded state. Unloading an eager tensor without a recoverable source raises an error.

Only fixed-width raw payloads are supported. Typed protobuf payload fields (float_data, int64_data, string_data, etc.), encrypted external weights, ORT/text input, bytes input, explicit external streams, no_copy=True and tiny-external-data eager loading are explicitly rejected in deferred mode. PipelineProto input is unsupported; deferred loading applies to ModelProto. Pipelines constructed from source-backed models are also rejected before file, descriptor or stream export, even after their weights have been loaded. Encoded values (including affine layouts), paged-cache blocks and struct-type declarations are also rejected: their extension-owned tensors are not covered by the weight-name traversal. Models constructed in memory by copying deferred tensors into these unsupported extensions are rejected during weight traversal and before export destination I/O, even when those tensors are loaded. Existing eager parsing and skip_raw_data behavior are unchanged.

GraphBuilder and GraphGraph accept deferred models directly. GraphGraph.GetComputedConstant (Python: get_computed_constant) loads a deferred constant on demand into an index-owned copy when a pattern needs its values. This includes large constants and payloads deferred with threshold zero: value-dependent matches do not silently fail just because their bytes are unloaded. The original model and builder declarations remain unloaded. GetConstantMetadata / get_constant_metadata returns the declaration without reading payloads; custom patterns should use it for shape/type checks and size guards. Scalar shape checks also avoid loading values. Parallel matching shares a synchronized value cache, invalidated when the graph index is rebuilt. Constant folding likewise loads temporary inputs only after its work/size guards. Partitioning and repeated-layer extraction leave large weights deferred and shared; only small constants eligible for internalization require their values.

Large unloaded weights still have unknown inferred numeric bounds. Shape-value inference loads temporary copies of small scalar/vector integer constants within its existing rank/element limit, even with threshold zero, without changing their declarations’ loaded state. Ordinary external references without deferred sources retain their existing behavior: use deferred file loading to enable on-demand access. Mixed raw/typed models and the unsupported structures listed above must use the existing eager load path; deferred parsing raises rather than silently discarding their values.

For capture, replay, undo and saving, no full reload of the source model is necessary:

from onnx_light.onnx_core.optimization import GraphBuilder, GraphGraph

model = load("model.onnx", defer_weights=True)
builder = GraphBuilder(model)
plan = GraphGraph(builder, ["Sub1Mul"]).optimize()
optimized = builder.to_model()  # Unrelated payloads remain deferred.
replayed = GraphBuilder(model).apply_rewritings(plan).to_model()
restored = builder.undo_rewritings(plan).to_model()
model.add_rewriting("optimized", plan)
model.load_weights()  # Materializes graph, function and plan tensors for export.
save(model, "with_plan.onnx")

Plans retain shared deferred sources in memory, including tensors in nested graphs and functions. After loading and saving the owning model, its serialized plan can be replayed independently of the original backing files. Undo state is in-memory state of the builder that applied the plan, not serialized history. An in-memory borrowed buffer still requires the existing shared-copy ownership and snapshot contract; deferred file loading does not make mutable or detachable foreign buffers safe to share.

Keep all backing files immutable and available until reloading is no longer needed. File identity, size and modification metadata are checked on reload; missing, replaced, truncated or normally modified sources raise errors. This is not a content hash or a guarantee against adversarial restoration of file metadata. Secure external-file containment, link checks, byte-range validation, alignment and max_tensor_size_bytes also apply to empty payloads. Do not edit a deferred tensor’s shape or type before reloading it.

Unloading releases the proto’s allocation ownership, not merely its logical size. Existing owning buffer views, explicit shared-payload copies and runtime consumers may retain their own storage: unloading a proto does not unload weights already retained by a runtime session. Runtime preparation rejects unloaded deferred initializers; load them before preparing a new context. Ordinary tensor/model copies and CopyFrom retain recoverable sources; serialization does not. Other subproto CopyFrom operations use serialization and reject unloaded deferred tensors. Serialization node callbacks preserve deferred sources in tensor attributes and nested graphs, including when callback changes are restored afterwards.

Export requires all deferred tensors to be loaded. Safe single-file ONNX export inlines their bytes without changing in-memory external metadata or sources. Export to a retained source, including symlink/hardlink aliases or the same open file descriptor, is rejected before writing. Native callers constructing their own output streams must call ValidateWeightSavePath before opening or truncating a destination; use SerializeToFile for automatic preflight. Python file-like export supports standard binary files and io.BytesIO. Standalone deferred tensor file, descriptor and stream exports (including save_tensor) are rejected, even after loading. Path-based helpers reject before opening the destination; descriptor/stream methods reject before writing. This also applies recursively to tensor-containing submessages, including graphs, nodes, attributes, sparse tensors, sequences, maps and optional values. Export the owning model or eagerly reload a serialized, loaded tensor to detach its source before exporting it independently. External-output, text and ORT conversions require first saving a single-file export and reloading it eagerly. Unloaded weights are never silently serialized.

rewritings is an onnx-light extension at field 1001, following struct_types at 1000 within the local 1000-1099 extension range. Its protobuf map entries contain a string key (field 1) and a rewriting_proto value (field 2), without an additional public message. Names must be nonempty and unique; duplicate wire keys are rejected rather than overwritten.

The graph and functions remain canonical. Reading a model never executes a plan. GraphBuilder.apply_rewritings(name) explicitly applies one plan to this canonical source and rejects unknown names, invalid edits and unavailable implementations, without falling back to another variant. The same method accepts a RewritingProto directly instead of a name. For SequenceMap, named-plan compatibility also requires a registered output-packing callback, not just the control-flow handler and body kernels.

model.add_rewriting(name, plan) rejects duplicate names. model.rewritings is a mutable map, not a detached Python dictionary. As with nanobind’s standard map bindings, reading an entry returns a plan copy; modify a plan and assign it back with model.rewritings[name] = plan. This keeps retained Python values safe when an entry or the entire map is cleared. GraphBuilder retains plans across import/export, clears them on canonical mutations (including nested mutations), and never transfers them to a replay result. Finalization that changes node order also invalidates positional plans; finalize the canonical builder before attaching plans. Direct proto field mutations cannot be tracked: callers must call model.clear_rewritings() before editing the canonical graph, functions, opsets or type declarations. ORT serialization and standard-model builder export reject bundled variants rather than silently discarding them. Export modes and external-data packaging remain the following implementation step.

Binary-size budget#

Named-plan maps and explicit shared-payload snapshots add serialization, comparison, copy-on-write storage and export-lease code to lib_onnx_proto. Linux CI run 39752559187 at commit f470c5a8 established the installed-size reference of 1,773,952 bytes. Authenticated encrypted external weights add shard I/O, validation and extended tensor traversal. Linux CI run 40030558220 at commit 9048f1bc4 measures 1,851,608 installed bytes, 1,331,306 .text bytes and 898 defined dynamic symbols. The initial deferred-source implementation measured 1,903,824 installed bytes, 1,388,540 .text bytes and 884 defined dynamic symbols with GCC 14.2.0 on Linux (stripped Release, core-only Python build). Linux CI run 40126419070 at commit e353b5cc4 measured 1,904,888 installed bytes, 1,373,642 .text bytes and 912 defined dynamic symbols with GCC 13.3. CI retains the initial installed-size reference and uses that CI text reference, with a 5% margin (--size-budget-margin-percent 5), giving limits of 1,999,015 installed bytes and 1,442,324 .text bytes. Exceeding either limit still fails CI. The error reports the reference, margin and effective limit, and explains that new proto fields, native code or compiler/build changes can increase binary size. Review those changes before updating a reference. The strict symbol limit is 914: the CI measurement plus the pipeline and recursive-submessage deferred-export validators. The shared-library dependency allowlist is unchanged.

class onnx_light.onnx.ModelProto(*args, **kwargs)#

ModelProto is a top-level file/container format for bundling a ML model and associating its computation graph with metadata. The semantics of the model are described by the associated GraphProto’s.

ByteSize(self) → int#

Returns the serialized size in bytes, following the protobuf API.

Clear(self) → None#

Clears the object.

ClearField(self, field_name: str) → None#

Clears the field field_name, following the protobuf API.

CopyFrom(self, arg: onnx_light.onnx_py._onnxpyprotoop.ModelProto, /) → None#

Copies one instance into this one.

Equals(self, other: onnx_light.onnx_py._onnxpyprotoop.ModelProto) → bool#

Compares message fields directly without serialization.

HasField(self, field_name: str) → bool#

Checks if a field is set, following the protobuf HasField API.

ParseFromEncryptedFile(self, name: str, key: str, options: object | None = None) → None#

Decrypts an ONNXCRY1/ONNXCRY2/ONNXCRY3 encrypted file (written by SerializeToEncryptedFile) and parses the payload into this model instance.

ParseFromEncryptedString(self, data: bytes, key: str, options: object | None = None) → None#

Decrypts an ONNXCRY1/ONNXCRY2/ONNXCRY3 encrypted bytes object (produced by SerializeToEncryptedString) and parses the payload into this model instance.

ParseFromFile(self, name: str, options: object | None = None, external_data_file: str = '') → None#

Parses a binary file to fill this instance.

ParseFromString(self, data: bytes, options: object | None = None) → None#
ParseFromString(self, data: str, options: object | None = None) → None

Overloaded function.

  1. ParseFromString(self, data: bytes, options: object | None = None) -> None

Parses a sequence of bytes to fill this instance.

  1. ParseFromString(self, data: str, options: object | None = None) -> None

Parses a string to fill this instance.

SerializeSize(self, options: object | None = None) → onnx_light.onnx_py._onnxpyprotoop.SerializeSizeResult#

Returns the size once serialized without serializing.

SerializeToEncryptedFile(self, name: str, key: str, options: object | None = None, encryption: str = 'AES-256-CBC') → None#

Encrypts the model and writes it to a single binary file. Supported values are “AES-256-CBC” (legacy ONNXCRY1), “ChaCha20-Poly1305” (ONNXCRY2), and “AES-256-GCM” (ONNXCRY3). Prefer authenticated ONNXCRY2 or ONNXCRY3.

SerializeToEncryptedString(self, key: str, options: object | None = None, encryption: str = 'AES-256-CBC') → bytes#

Encrypts the model and returns ciphertext bytes in ONNXCRY1 (AES-256-CBC), ONNXCRY2 (ChaCha20-Poly1305), or ONNXCRY3 (AES-256-GCM) format.

SerializeToFile(self, name: str, options: object | None = None, external_data_file: str = '') → None#

Serializes this instance into a file. Standalone messages require single-file ONNX output. If external_data_file is not empty, big weights are stored in this (depending on options.raw_data_threshold). When writing to two files, temporary external-data metadata is cleared so the model’s values and metadata stay unchanged. Borrowed buffers not proven independent of files are first snapshotted in the source, even if a later write fails; their addresses and ownership may change.

SerializeToFileDescriptor(self, fd: int, options: object | None = None) → None#

Serializes this instance into an open file descriptor without closing it.

SerializeToOStream(self, output: object) → None#

Alias for SerializeToOstream (capital S) for protobuf API compatibility. Serializes this instance to a Python file-like object that has a write() method.

SerializeToOstream(self, output: object) → None#

Serializes this instance to a Python file-like object that has a write() method.

SerializeToString(self, options: object | None = None) → bytes#

Serializes this instance into a sequence of bytes.

add_function(self, function: onnx_light.onnx_py._onnxpyprotoop.FunctionProto) → onnx_light.onnx_py._onnxpyprotoop.FunctionProto#

Appends a FunctionProto and returns it.

add_graph(self) → onnx_light.onnx_py._onnxpyprotoop.GraphProto#

Sets an empty value.

add_metadata(self, key: str, value: str) → onnx_light.onnx_py._onnxpyprotoop.StringStringEntryProto#

Sets metadata property key to value, updating an existing entry in place.

add_opset(self, domain: str, version: int) → onnx_light.onnx_py._onnxpyprotoop.OperatorSetIdProto#

Appends an opset import (domain, version).

add_rewriting(self, name: str, rewrites: onnx_light.onnx_py._onnxpyprotoop.RewritingProto) → None#

Adds a named plan, rejecting duplicate names.

clear_rewritings(self) → None#
property configuration#

Describes different target configurations for a multi-device use case. A model MAY describe multiple multi-device configurations for execution.

property doc_string#

A human-readable documentation for this graph. Markdown is allowed.

property domain#

company.name. Together with model_version and GraphProto.name, this forms the unique identity of the graph.

Type:

Domain name of the model. We use reverse domain names as name space indicators. For example

property functions#

A list of function protos local to the model. The (domain, name, overload) tuple must be unique across the function protos in this list. In case of any conflicts the behavior (whether the model local functions are given higher priority, or standard operator sets are given higher priority or this is treated as error) is defined by the runtimes. The operator sets imported by FunctionProto should be compatible with the ones imported by ModelProto and other model local FunctionProtos. Example, if same operator set say ‘A’ is imported by a FunctionProto and ModelProto or by 2 FunctionProtos then versions for the operator set may be different but, the operator schema returned for op_type, domain, version combination for both the versions should be same for every node in the function body. One FunctionProto can reference other FunctionProto in the model, however, recursive reference is not allowed.

property graph#

The parameterized graph that is evaluated to execute the model.

has_configuration(self) → bool#

Tells if ‘configuration’ has a value.

has_deferred_weights(self) → bool#

Returns whether this model retains any deferred backing sources.

has_doc_string(self) → bool#

Tells if ‘doc_string’ has a value

has_domain(self) → bool#

Tells if ‘domain’ has a value

has_functions(self) → bool#

Tells if ‘functions’ has a value.

has_graph(self) → bool#

Tells if ‘graph’ has a value.

has_ir_version(self) → bool#

Tells if ‘ir_version’ has a value.

has_metadata_props(self) → bool#

Tells if ‘metadata_props’ has a value.

has_model_version(self) → bool#

Tells if ‘model_version’ has a value.

has_opset_import(self) → bool#

Tells if ‘opset_import’ has a value.

has_producer_name(self) → bool#

Tells if ‘producer_name’ has a value

has_producer_version(self) → bool#

Tells if ‘producer_version’ has a value

has_struct_types(self) → bool#

Tells if ‘struct_types’ has a value.

property ir_version#

The version of the IR this model targets. See Version enum above. This field MUST be present.

is_weight_loaded(self, name: str) → bool#

Returns whether the uniquely named tensor has a materialized payload.

load_weight(self, name: str) → bool#

Loads one deferred tensor; returns false if already loaded.

load_weights(self) → int#

Loads all deferred tensors and returns the number changed.

property metadata_props#

Named metadata values; keys should be distinct.

property model_version#

The version of the graph encoded. See Version enum below.

property opset_import#

The OperatorSets this model relies on. All ModelProtos MUST have at least one entry that specifies which version of the ONNX OperatorSet is being imported. All nodes in the ModelProto’s graph will bind against the operator with the same-domain/same-op_type operator with the HIGHEST version in the referenced operator sets.

property producer_name#

The name of the framework or tool used to generate this model. This field SHOULD be present to indicate which implementation/tool/framework emitted the model.

property producer_version#

The version of the framework or tool used to generate this model. This field SHOULD be present to indicate which implementation/tool/framework emitted the model.

rewriting_hash(self) → int#

Returns the combined positioned-node structural hash without reading weights.

property rewritings#

Named variants applied independently to the canonical model (onnx-light extension). Keys must be nonempty and unique. Model mutations must clear or regenerate these plans.

property struct_types#

Model-scoped catalogue of struct declarations (onnx-light extension, field numbers 1000-1099 are reserved for local extensions). Every entry MUST carry a nonzero, unique type_id; duplicate IDs, unresolved references and reference cycles are invalid, and reordering the catalogue does not change identity.

unload_weight(self, name: str) → bool#

Releases one tensor’s payload ownership, retaining its source for reloading.

unload_weights(self) → int#

Unloads all deferred tensors and returns the number changed.

validate_weight_save_path(self, path: str = '') → None#

Requires loaded weights and rejects paths aliasing their backing sources.

weight_names(self) → list[str]#

Returns tensor names across all scopes; duplicate names remain ambiguous.