onnx_verify.h#
Schema-free structural validation for onnx_proto messages.
The functions declared here validate that a protobuf is internally consistent on its own terms: required fields are set, names are unique, the graph is in single static assignment (SSA) form and topologically sorted, tensor payload sizes match the declared shape/dtype, and so on. None of these checks needs an operator-schema registry: nothing here depends on the semantics of a specific op_type.
For schema-aware validation (operator input/output arity, attribute constraints, type/shape inference), use onnx_lib::checker::check_model() instead (declared in onnx_lib/checker.h).
Validation functions below throw std::invalid_argument (via EXT_THROW_INVALID / EXT_ENFORCE_INVALID) with a descriptive message on the first violation found.
-
namespace onnx_light
Alias that makes onnx-light headers compatible with code that references
ONNX_LIGHT_NAMESPACE(the macro used in the standard onnx package).Set to
ONNX_LIGHT_NAMESPACEso both names resolve to the same namespace.Symbol-visibility attribute for the public onnx-light C++ API.
Maps the upstream compatibility macro to onnx-light’s explicit proto ABI annotation. This keeps declarations from vendored ONNX headers visible when
lib_onnx_protouses hidden visibility by default.Namespace alias so that ONNX C++ code (and consumers such as onnxruntime) that refers to the literal
onnxnamespace — rather than theONNX_NAMESPACEmacro — resolves to the onnx-light namespace. The standard onnx package lives innamespace onnx; onnx-light usesonnx_light(via ONNX_LIGHT_NAMESPACE), so this alias keeps onnx-light a true drop-in. It is only introduced when the onnx-light namespace differs fromonnx.Functions
-
inline constexpr bool IsAffineStorageType(TensorProto::DataType data_type)#
Returns true when
data_typeis one of the supported affine storage types.
- ONNX_LIGHT_PROTO_API void ValidatePersistentType (const StructTypeCatalogue &catalogue, const TypeProto &type)
Validates a persistent type, rejecting strings, maps, optionals, sparse and opaque values.
- ONNX_LIGHT_PROTO_API void ValidatePersistentStructType (const StructTypeCatalogue &catalogue, const StructTypeProto &type)
Validates a persistent encoded layout, including referenced types and constant fields.
- ONNX_LIGHT_PROTO_API bool CompatiblePersistentTypes (const StructTypeCatalogue &catalogue, const TypeProto &left, const TypeProto &right)
Returns whether validated tensor/struct/sequence declarations are compatible. Compares ranks when both are known and dimensions when both are concrete. Allows symbolic dimensions and unknown ranks in ordinary runtime values. Compares declarations directly, without serialization, hashing or payload copies. Throws std::invalid_argument for malformed types or unresolved references.
- ONNX_LIGHT_PROTO_API bool CompatiblePersistentStructTypes (const StructTypeCatalogue &catalogue, const StructTypeProto &left, const StructTypeProto &right)
Returns declaration compatibility of structured types or catalogue references.
- ONNX_LIGHT_PROTO_API void VerifyPersistentInputUses (const GraphProto &graph)
Validates only the value-use counts of the persistent input names bound by
graph.Each bound root input must have at least one value-use. Node input positions, graph outputs and captures in GRAPH/GRAPHS attributes count as uses; locally defined names that shadow the root input do not. Bindings, graph-input declarations and
graph.value_infometadata are not uses. Function bodies are not expanded and aliases are not inferred.Does not validate declarations, duplicate bindings, root-only placement or types, and does not require a struct-type catalogue. Returns immediately when
graphhas no persistent bindings.- Throws:
std::invalid_argument – Thrown when a bound name has no uses; the error names the input.
- ONNX_LIGHT_PROTO_API void VerifyPersistentBindings (const StructTypeCatalogue *struct_types, const GraphProto &graph, bool is_main_graph=true)
Validates root-graph persistent declarations without reading or copying state payloads.
Resolves exact whole-input/output names, rejects duplicate inputs or outputs, and rejects conflicting tensor dtypes, known ranks, concrete dimensions and struct layouts. String tensors are forbidden, including nested fields and structured constants. A null catalogue resolves inline types only. Nested graphs must not declare bindings.
Calls VerifyPersistentInputUses() after all declaration/type/duplicate checks, preserving their error precedence. Graphs without persistent bindings are unaffected.
- ONNX_LIGHT_PROTO_API void VerifyValueInfo (const ValueInfoProto &value_info, bool is_main_graph=true)
Validates a ValueInfoProto.
- ONNX_LIGHT_PROTO_API void VerifyTensor (const TensorProto &tensor)
Validates a TensorProto: data_type is set, at most one payload field is populated, and the populated field matches the declared data_type.
- ONNX_LIGHT_PROTO_API void VerifySparseTensor (const SparseTensorProto &sparse_tensor)
Validates a SparseTensorProto:
valuesandindicesare individually valid tensors andindicesuses the required INT64 data type.- Parameters:
sparse_tensor – Sparse tensor to validate.
- Throws:
std::invalid_argument – Thrown when validation fails.
- ONNX_LIGHT_PROTO_API void VerifyAttribute (const AttributeProto &attribute, bool in_function_body, const std::unordered_set< std::string > &scope)
Validates an AttributeProto: exactly one value field is populated and it matches the declared
type; nested graphs/tensors are recursively validated.- Parameters:
attribute – Attribute to validate.
in_function_body – True when the attribute belongs to a node inside a FunctionProto body, in which case
ref_attr_nameis permitted.scope – Names visible to the attribute’s nested subgraph (if any), i.e. every name defined so far in the enclosing graph. Used to validate that control-flow body subgraphs (Attribute.g / Attribute.graphs) can legally reference outer-scope values.
- Throws:
std::invalid_argument – Thrown when validation fails.
- ONNX_LIGHT_PROTO_API void VerifyAttribute (const StructTypeCatalogue *struct_types, const AttributeProto &attribute, bool in_function_body, const std::unordered_set< std::string > &scope)
Catalogue-aware overload of VerifyAttribute(): additionally resolves the
type_refidentities used byTYPE_PROTO/TYPE_PROTOSattributes and by nested subgraphs againststruct_types.- Parameters:
struct_types – Catalogue resolving
type_refidentities; when null the attribute is checked on its own terms and unresolved references are tolerated.attribute – Attribute to validate.
in_function_body – True when the attribute belongs to a node inside a FunctionProto body.
scope – Names visible to the attribute’s nested subgraph (if any).
- Throws:
std::invalid_argument – Thrown when validation fails.
- ONNX_LIGHT_PROTO_API void VerifyNode (const NodeProto &node, bool in_function_body, const std::unordered_set< std::string > &scope)
Validates a NodeProto:
op_typeis set, the node has at least one input or output, attribute names are unique, and each attribute is valid.- Parameters:
node – Node to validate.
in_function_body – True when
nodebelongs to a FunctionProto body.scope – Names visible to the node, forwarded to VerifyAttribute() for nested subgraph validation.
- Throws:
std::invalid_argument – Thrown when validation fails.
- ONNX_LIGHT_PROTO_API void VerifyNode (const StructTypeCatalogue *struct_types, const NodeProto &node, bool in_function_body, const std::unordered_set< std::string > &scope)
Catalogue-aware overload of VerifyNode(): forwards
struct_typesto VerifyAttribute() so typed attributes and nested subgraphs resolve theirtype_refidentities.- Parameters:
struct_types – Catalogue resolving
type_refidentities; may be null.node – Node to validate.
in_function_body – True when
nodebelongs to a FunctionProto body.scope – Names visible to the node.
- Throws:
std::invalid_argument – Thrown when validation fails.
- ONNX_LIGHT_PROTO_API void VerifyGraph (const GraphProto &graph, bool is_main_graph=true, bool in_function_body=false, const std::unordered_set< std::string > *outer_scope=nullptr)
Validates a GraphProto: inputs/outputs/initializers have unique names (across dense, sparse and encoded initializers), the graph is in SSA form, nodes are topologically sorted (every input is produced by a prior node, initializer, graph input, or outer scope), every declared output is actually produced, and every encoded initializer describes a valid flat byte layout.
- Parameters:
graph – Graph to validate.
is_main_graph – When false, relaxes the ValueInfoProto
typerequirement on graph inputs/outputs (subgraphs may omit it).in_function_body – True when
graphis nested inside a FunctionProto body.outer_scope – Names visible from an enclosing graph (used when validating a control-flow body subgraph); may be null for the main graph.
- Throws:
std::invalid_argument – Thrown when validation fails.
- ONNX_LIGHT_PROTO_API void VerifyGraph (const StructTypeCatalogue *struct_types, const GraphProto &graph, bool is_main_graph=true, bool in_function_body=false, const std::unordered_set< std::string > *outer_scope=nullptr)
Catalogue-aware overload of VerifyGraph().
- Parameters:
struct_types – Catalogue resolving the
type_refidentities used by encoded initializers and structured types. When null the graph is checked on its own terms and a reference the graph cannot resolve suspends the layout checks instead of failing; VerifyModel() supplies the model catalogue.graph – Graph to validate.
is_main_graph – When false, relaxes the ValueInfoProto
typerequirement on graph inputs/outputs (subgraphs may omit it).in_function_body – True when
graphis nested inside a FunctionProto body.outer_scope – Names visible from an enclosing graph; may be null.
- Throws:
std::invalid_argument – Thrown when validation fails.
- ONNX_LIGHT_PROTO_API void VerifyFunction (const FunctionProto &function)
Validates a FunctionProto:
nameis set, inputs are uniquely named, nodes are topologically sorted with respect to the function’s inputs, and every declared output is produced. Opset imports have positive versions and unique normalized domains; every body operator, including nested graphs, has an imported domain. Attribute references are declared byattributeorattribute_protoand use consistent types throughout the body.- Parameters:
function – Function to validate.
- Throws:
std::invalid_argument – Thrown when validation fails.
- ONNX_LIGHT_PROTO_API void VerifyFunction (const StructTypeCatalogue *struct_types, const FunctionProto &function)
Catalogue-aware overload of VerifyFunction(): validates the function’s
value_infotypes and every node attribute againststruct_types.- Parameters:
struct_types – Catalogue resolving
type_refidentities; may be null.function – Function to validate.
- Throws:
std::invalid_argument – Thrown when validation fails.
- ONNX_LIGHT_PROTO_API void VerifyModel (const ModelProto &model)
Validates an in-memory ModelProto without requiring an operator-schema registry:
graphis present, at least one opset is imported with unique domains,struct_typesdeclares unique nonzero identities without unresolved references or cycles, the main graph is structurally valid, and model-local functions are individually valid and uniquely identified by (domain, name, overload).This performs IR-level structural checks only; it does not check operator input/output arity or attribute constraints, and it does not run shape inference. Use
onnx_lib::checker::check_model()for that.- Parameters:
model – Model to validate.
- Throws:
std::invalid_argument – Thrown when a structural inconsistency is found.
- ONNX_LIGHT_PROTO_API void VerifyPipeline (const PipelineProto &pipeline)
Validates an LLM PipelineProto and every contained ModelProto.
The prefill model is required. Optional embedding and decode models are validated when present. Generation limits and sampling parameters must be in range, and metadata keys must be unique.
- Parameters:
pipeline – Pipeline to validate.
- Throws:
std::invalid_argument – Thrown when a structural inconsistency is found.
Variables
-
struct EncodedValueLayout#
- #include <onnx_verify.h>
Describes the validated payload geometry of one
EncodedValueProto.Public Members
-
const StructTypeProto *root = nullptr#
Resolved structured root, or null for the affine branch.
-
const AffineLayoutProto *affine = nullptr#
Affine descriptor, or null for the structured branch.
-
TensorProto::DataType storage_type = TensorProto::UNDEFINED#
Resolved affine code type, including an inferred code width, or UNDEFINED otherwise.
-
uint64_t element_bits = 0#
Size of one record in bits: the element size, or the storage width for the affine branch.
-
uint64_t payload_bytes = 0#
Byte extent of the payload, inline or declared by the external metadata.
-
uint64_t record_count = 0#
Number of records derived from the payload extent, or logical elements for affine.
-
bool external = false#
True when the payload lives outside the message.
-
bool unresolved_reference = false#
True when a
type_refwas left unresolved because no catalogue was available.
-
bool content_verified = false#
True when the payload bytes themselves were inspected, which only an inline
raw_datapayload allows. For an external payload only the metadata is validated:payload_bytesis the declared extent, the backing file is neither opened nor measured, and content rules that need the bytes (the affine 4-bit nibble padding in particular) are not checked. Load the payload and re-validate before treating an external value as fully checked.
-
const StructTypeProto *root = nullptr#
-
class StructTypeCatalogue#
- #include <onnx_verify.h>
Resolves
type_idreferences declared byModelProto.struct_types.The catalogue borrows the model it was built from: it must not outlive that model, and the model must not be mutated while it is in use. A catalogue holds a handful of declarations, so lookups scan them linearly instead of paying for a hash map.
Public Functions
-
StructTypeCatalogue() = default#
Builds an empty catalogue resolving no identity.
-
void Build(const ModelProto &model)#
Indexes and validates every declaration of
model.Each entry must carry a nonzero
type_idunique in the model and a concrete kind; references must resolve and must not form a cycle.- Parameters:
model – Model owning the declarations, borrowed by the catalogue.
- Throws:
std::invalid_argument – Thrown when a declaration is malformed.
-
void Build(const utils::RepeatedProtoField<StructTypeProto> &declarations)#
Indexes and validates borrowed declarations without copying their constants or codecs.
-
inline const StructTypeProto *Find(uint64_t type_id) const#
Returns the declaration for
type_id, or null when the model declares no such identity.
-
inline size_t size() const#
Returns the number of indexed declarations.
-
inline bool empty() const#
Returns true when the catalogue indexes no declaration.
-
inline const StructTypeProto &Resolve(const StructTypeProto &type) const#
Returns the declaration
typedenotes, ortypeitself when it is not a reference.- Throws:
std::invalid_argument – Thrown when the reference does not resolve.
-
bool FixedBitSize(const StructTypeProto &type, uint64_t &bits, std::string *reason = nullptr) const#
Computes the fixed size of
typein bits with checkeduint64_tarithmetic.Constants contribute zero bits, arrays and bit packings are tight and fields follow declaration order.
Returns: True when the type has a fixed inline layout, false otherwise.
- Parameters:
type – Type whose layout is measured.
bits – Receives the size in bits on success.
reason – Optional destination for a human-readable failure cause.
-
inline bool IsByteEncodable(const StructTypeProto &type, uint64_t &bytes, std::string *reason = nullptr) const#
Returns true when
typecan be the root of a byte-encoded payload, that is when its size is fixed, strictly positive and a whole number of bytes.- Parameters:
type – Type to test.
bytes – Receives the size of one record in bytes on success.
reason – Optional destination for a human-readable failure cause.
-
void ValidateType(const TypeProto &type) const#
Validates a
TypeProto, including any nestedstruct_type.Dynamic tensor dimensions, sequences, maps and optional values stay valid types here; only byte encoding requires a fixed layout.
- Parameters:
type – Type to validate.
- Throws:
std::invalid_argument – Thrown when validation fails.
-
EncodedValueLayout ValidateEncodedValue(const EncodedValueProto &value, bool require_resolved_reference = true) const#
Validates one
EncodedValueProtoand returns its payload geometry.Checks the layout choice, raw/external exclusivity, external metadata, byte-encodability of the structured root and payload divisibility, or the frozen affine contract (storage type, parameter types, axis and block size, logical type and shape, code byte length and nibble padding).
Returns: The validated layout.
-
void ValidatePagedCache(const PagedCacheProto &value, bool require_resolved_reference = true, const TypeProto *declared_type = nullptr) const#
Validates contiguous page ranges, concrete logical shapes and inline payload extents.
Private Members
-
const utils::RepeatedProtoField<StructTypeProto> *declarations_ = nullptr#
-
StructTypeCatalogue() = default#
-
inline constexpr bool IsAffineStorageType(TensorProto::DataType data_type)#
Persistent declarations#
VerifyPersistentBindings validates root-graph declarations using an optional
StructTypeCatalogue. VerifyGraph and VerifyModel call it automatically.
Bindings select whole inputs and outputs by exact graph names; dots and
backslashes are literal. Unknown names and duplicate input or output selections
are rejected. PersistentValueState uses this same declaration validator.
String tensors cannot be persistent, including tensor fields and constants
inside whole structures or encoded layouts. ValidatePersistentType and
ValidatePersistentStructType reuse the catalogue’s recursive validation walk,
including reference resolution, cycle detection, depth limits and memoization.
CompatiblePersistentTypes and CompatiblePersistentStructTypes expose
the same direct declaration compatibility checks to native runtime callers.
Compatibility alone does not make a value persistable: ordinary execution
also uses these checks, while persistent bindings additionally reject strings.
Unknown ranks and symbolic dimensions remain valid; conflicting known ranks,
concrete dimensions, dtypes and structured layout identities are rejected.
StructTypeCatalogue::Build also accepts borrowed declarations directly, whose
lifetime and immutability requirements match the model overload.