.. _l-quantized-values-cpp: Quantizes tensors into encoded values ===================================== This guide covers the C++ interface. For the other language, see :doc:`../python/quantized_values`. For revision/subtype import/export support and unsupported checkpoint layouts, see the :ref:`GPTQModel compatibility matrix `. The converters implement **portable onnx-light representations** of the :ref:`quantization catalogue `, plus three explicit :ref:`ORT MatMulNBits input layouts `. The portable profiles do not emit GGUF, Marlin or bitsandbytes buffers. Their profile names identify numerical families, not those libraries' packing ABIs, published bits-per-weight figures, training algorithms or accuracy guarantees. The single ``QuantizationFormat`` catalogue also includes ``kQ40``, ``kQ80``, ``kQ2K``, ``kQ3K``, ``kQ4K``, ``kQ5K``, ``kQ6K``, ``kIq4Nl``, ``kIq1S``, ``kTq10`` and ``kTq20``, with canonical uppercase names returned by ``QuantizationFormatName``. They use :ref:`native GGUF blocks ` rather than portable packing. ``QuantizationFormats()`` lists all formats; ``IsGgufQuantizationFormat`` identifies those requiring native block imports. ``MakeQuantizationPlan`` rejects these formats because floating-point-to-GGML quantization is not implemented. Codecs without a GGUF counterpart retain their existing representations. ``Tensor`` converts to an owned ``RuntimeValue`` of kind ``kEncoded``. ``TensorProto`` converts to ``EncodedValueProto``. Both use the same native implementation and can be dequantized without the original plan. A self-contained message has an inline ``StructTypeProto`` describing all fields and a versioned native consumer identity. It can subsequently be put in a model's catalogue and referenced by ``type_ref``. The implementation lives in ``onnx_core``, not ``lib_onnx_proto``, and does not require registered operator kernels. The Python module requires the runtime bindings, as do other Python reference-runtime utilities. Native GPTQModel VPTQ weights ----------------------------- ``VptqWeights`` in ``onnx_core/runtime/quantization.h`` describes the pinned native VPTQ constructor configuration and loaded state-dictionary tensors. Its ``schema_version`` defaults to 1; other versions are rejected. ``ImportVptqWeights`` produces ``onnx_light.vptq_weights.v1``; ``ExportVptqWeights`` restores the original metadata and tensor bytes. ``ReconstructVptqWeights`` returns FLOAT ``[out_features,in_features]`` with the upstream codebook-dtype rounding boundaries, inverse permutation and normalization. See the :ref:`VPTQ support matrix `. No portable codebook decoder is changed. .. code-block:: cpp VptqWeights checkpoint; checkpoint.in_features = 37; checkpoint.out_features = 7; checkpoint.bits = 2; checkpoint.vector_lens = {-1, 3}; checkpoint.num_centroids = {-1, 4}; checkpoint.group_size = 19; checkpoint.tensors = loaded_module_tensors; auto encoded = ImportVptqWeights(checkpoint); auto restored = ExportVptqWeights(encoded); auto weight = ReconstructVptqWeights(encoded); Native GPTQModel GPTQ weights ----------------------------- ``GptqWeights`` in ``onnx_core/runtime/quantization.h`` describes a pinned native ``gptq``, ``gptq_v2`` or ``gptq_p`` checkpoint, separate from the unchanged portable ``kGptq`` profile. See :ref:`the checkpoint support rules ` for packing, storage dtypes, dimensions and legacy zero-point conversion limits. .. code-block:: cpp GptqWeights checkpoint; checkpoint.format = "gptq_v2"; checkpoint.in_features = 128; checkpoint.out_features = 128; checkpoint.group_size = 128; checkpoint.bits = 4; checkpoint.word_dtype = TensorProto::INT32; checkpoint.tensors = loaded_module_tensors; // qweight, qzeros, scales, g_idx auto encoded = ImportGptqWeights(checkpoint); auto restored = ExportGptqWeights(encoded); // exact tensors and metadata auto codes = UnpackGptqCodes(encoded); // UINT8 [N,K] auto zeros = UnpackGptqZeros(encoded); // INT16 [H,N], true zeros auto weights = ReconstructGptqWeights(encoded); // FLOAT [N,K] ``PackGptqWeights(metadata, codes, zeros, scales, g_idx, max_bytes)`` encodes already-quantized tensors into an explicitly requested layout; ``metadata.tensors`` must be empty. It rejects out-of-range codes and unrepresentable zero points, rather than wrapping, clipping or requantizing. Import/export preserves padding; repacking creates canonical padding. Generic dequantization also recognizes the native encoded schema. Native GPTQModel AWQ weights ---------------------------- ``AwqWeights`` in ``onnx_core/runtime/quantization.h`` describes one loaded module with an explicit ``variant``, input/output dimensions, group size, four-bit codes, and grouping axis 1 of the reconstructed ``[output,input]`` matrix. See the :ref:`AWQ support matrix ` for the pinned packing contracts. The portable ``kAwq`` profile remains unchanged. .. code-block:: cpp AwqWeights checkpoint; checkpoint.variant = "gemm"; // or gemv, gemv_fast, llm-awq checkpoint.in_features = 128; checkpoint.out_features = 128; checkpoint.group_size = 128; checkpoint.tensors = loaded_module_tensors; auto encoded = ImportAwqWeights(checkpoint); auto restored = ExportAwqWeights(encoded); // exact native tensors and metadata auto codes = UnpackAwqCodes(encoded); // UINT8 [output,input] auto weights = ReconstructAwqWeights(encoded); // FLOAT [output,input] The adapters preserve original codes, scale bits, zero parameters and padding; they do not calibrate weights or implement GPU kernels. Generic dequantization also recognizes this schema. Native GPTQModel ParoQuant operators ----------------------------------- ``ParoQuantWeights`` in ``onnx_core/runtime/quantization.h`` retains the exact AWQ-GEMM words together with learned ``pairs``, ``theta``, ``channel_scales`` and optional ``bias``. See :ref:`l-paroquant-checkpoints` for the pinned upstream, tensor shapes, dtype contract and mandatory activation transformation. .. code-block:: cpp ParoQuantWeights checkpoint; checkpoint.in_features = 128; checkpoint.out_features = 128; checkpoint.group_size = 32; checkpoint.krot = 8; checkpoint.tensors = loaded_module_tensors; auto encoded = ImportParoQuantWeights(checkpoint); auto restored = ExportParoQuantWeights(encoded); auto codes = UnpackParoQuantCodes(encoded); // UINT8 [output,input] auto weight = ReconstructParoQuantWeights(encoded); // transformed basis only auto output = ApplyParoQuantLinear(encoded, input); // FLOAT [...,input] -> [...,output] Generic dequantization rejects ParoQuant: discarding rotations/channel scales would change the operator. ``ApplyParoQuantLinear`` scales and rotates FLOAT activations in serialized order before the reference matrix multiplication and optional bias; it does not emulate accelerator rounding. Weight reconstruction first retains the pinned dense consumer's rounding to the saved FP16/BF16 scale dtype, then widens to FLOAT. Native GPTQModel QQQ weights ---------------------------- ``QqqWeights`` in ``onnx_core/runtime/quantization.h`` describes the pinned four-bit tiled ``B`` tensor and separately permuted ``s_channel``/``s_group`` buffers. See :ref:`the exact weight contract ` for dimensions, scale permutations, code interpretation and reference arithmetic. .. code-block:: cpp QqqWeights checkpoint; checkpoint.in_features = 256; checkpoint.out_features = 128; checkpoint.group_size = 128; checkpoint.tensors = loaded_module_tensors; // B, s_channel, s_group auto encoded = ImportQqqWeights(checkpoint); auto restored = ExportQqqWeights(encoded); // exact native tensors and metadata auto codes = UnpackQqqCodes(encoded); // UINT8 native nibbles [output,input] auto weights = ReconstructQqqWeights(encoded); // FLOAT [output,input] ``PackQqqWeights(metadata, codes, s_channel, s_group, max_bytes)`` accepts already-quantized nibble codes and the original **already-permuted** scale tensors; ``metadata.tensors`` must be empty. It does not derive or combine scales. Grouped reconstruction rounds and saturates to INT8 before channel scaling. Export, unpack and reconstruction accept a ``StructTypeCatalogue`` as their third argument; generic dequantization also recognizes this schema. ``max_bytes`` separately bounds payload and logical FLOAT storage (default 1 GiB). These APIs provide weight serialization and reference reconstruction, not calibration, activation quantization or accelerated QQQ inference. Native GPTQModel bitsandbytes weights ------------------------------------ ``BitsAndBytesWeights`` in ``onnx_core/runtime/quantization.h`` accepts the module-local ``weight_*`` buffers, including original packed JSON for NF4/FP4, or ``weight`` and ``weight_scb`` for INT8. The :ref:`pinned native contract ` describes exact shapes, high-nibble-first packing, nested scale state, arithmetic and exclusions. This is separate from the unchanged portable ``kNf4`` profile and MX/NV FP4. .. code-block:: cpp BitsAndBytesWeights checkpoint; checkpoint.tensors = loaded_module_tensors; auto encoded = ImportBitsAndBytesWeights(checkpoint); auto restored = ExportBitsAndBytesWeights(encoded); // exact bytes, including JSON auto codes = UnpackBitsAndBytesCodes(encoded); // UINT8 or INT8 [output,input] auto weights = ReconstructBitsAndBytesWeights(encoded); // FLOAT [output,input] Both payload and logical FLOAT output are separately bounded by ``max_bytes`` (default 1 GiB). Export, unpack and reconstruction accept a ``StructTypeCatalogue`` as their third argument. The fourth reconstruction argument selects FLOAT, FLOAT16 or BFLOAT16 output; saved source dtype remains checkpoint metadata. Generic ``DequantizeTensor`` and ``DequantizeTensorProto`` recognize this schema and return FLOAT. No quantization algorithm or accelerated inference is added. Native GPTQModel EXL3 weights ----------------------------- ``Exl3Weights`` in ``onnx_core/runtime/quantization.h`` accepts the canonical loaded trellis, scales and optional codebook marker for one module. See the :ref:`pinned EXL3 contract ` for exact tensor shapes, rates, arithmetic, provenance and rejected configurations. This API is separate from the unchanged portable ``kExl3`` affine profile. .. code-block:: cpp Exl3Weights checkpoint; checkpoint.tensors = loaded_module_tensors; // trellis, suh, svh, optional mcg/mul1 auto encoded = ImportExl3Weights(checkpoint); auto restored = ExportExl3Weights(encoded); // original checkpoint bytes auto states = UnpackExl3States(encoded); // cyclic INT16 state bit patterns auto weights = ReconstructExl3Weights(encoded); // FLOAT [input,output] Both payload and logical FLOAT workspace are separately bounded by ``max_bytes`` (default 1 GiB). Generic ``DequantizeTensor`` and ``DequantizeTensorProto`` also recognize this schema. Pass ``TensorProto::FLOAT16`` as the fourth argument of ``ReconstructExl3Weights`` to round transform/scale boundaries to FP16. No accelerated inference or floating-point-to-trellis quantizer is implemented. Compressed-tensors checkpoint interoperability ---------------------------------------------- The native ``ImportCompressedTensorsWeights`` and ``ExportCompressedTensorsWeights`` functions implement the pinned :ref:`checkpoint adapter ` metadata, validation, and import/export paths. They accept owned runtime ``Tensor`` objects and never dequantize or requantize checkpoint codes. Python exposes these functions through nanobind; the Python module contains only aliases to that interface. No PyTorch dependency or checkpoint-container loader is added. Unsupported formats, activation configurations and lossy parameter mappings are rejected. Complete MXFP6 E2M3 profile ------------------------- ``QuantizationFormat::kMxfp6E2m3`` (``mxfp6_e2m3``) implements packed E2M3 values with automatic E8M0 scales in complete groups of 32 columns. The portable ``kMxfp6`` and ``kFp6Llm`` E3M2 payloads remain unchanged. See :ref:`the complete E2M3 contract ` for the pinned reference, exact codes/packing, scale rounding, reconstruction and validation. .. code-block:: cpp using namespace onnx_light::core::runtime; auto weights = Tensor::FromFloat("weight", {2, 64}, std::vector(128, 1)); auto plan = MakeQuantizationPlan(QuantizationFormat::kMxfp6E2m3, 128); auto encoded = QuantizeTensor(weights, plan); auto native = ExportMxfp6E2m3Weights(encoded.Encoded()); auto imported = ImportMxfp6E2m3Weights(native); auto restored = DequantizeTensor(imported); ``QuantizeMxfp6E2m3Weights`` selects the same codec directly. ``Mxfp6E2m3Weights`` owns UINT8 packed weights and E8M0 scales. The versioned descriptor is ``onnx_light.mxfp6_e2m3_weights.v1``. Complete MXFP8 profile --------------------- ``QuantizationFormat::kMxfp8`` (``mxfp8``) implements native E4M3FN values with automatically selected E8M0 scales, not the existing ``kFp8E4m3`` codebook contract. It requires a nonempty finite FLOAT matrix ``[N,K]``, with groups of 32 columns along axis 1 and ``K`` divisible by 32. See :ref:`the complete MXFP8 contract ` for the pinned compressed-tensors reference, precise scale selection, rounding, saturation, range extensions and rejection policies. .. code-block:: cpp Tensor weights = Tensor::FromFloat("W", {2, 64}, std::vector(128, 1.f)); auto plan = MakeQuantizationPlan(QuantizationFormat::kMxfp8, 128); RuntimeValue encoded = QuantizeTensor(weights, plan); // The dedicated entry point produces the same self-contained codec. EncodedValueProto direct = QuantizeMxfp8Weights(weights); Mxfp8Weights parameters = ExportMxfp8Weights(direct); EncodedValueProto imported = ImportMxfp8Weights(parameters); Tensor restored = DequantizeTensor(imported); ``Mxfp8Weights`` owns E4M3FN ``weight`` (``[N,K]``) and UINT8 ``weight_scale`` (``[N,K/32]``). The versioned ``onnx_light.mxfp8_weights.v1`` descriptor and payload preserve all bytes through ordinary wire serialization; decoding needs no quantization plan. This supplies a portable block-scale representation, not a general checkpoint importer or accelerated MXFP8 matrix multiplication. Complete MXFP4 weights ---------------------- The complete MXFP4 weight codec is separate from the portable ``QuantizationFormat::kMxfp4`` profile, whose existing parameters and serialized decoder remain unchanged. ``QuantizeMxfp4Weights`` selects each scale from the input, and the versioned ``onnx_light.mxfp4_weights.v1`` value is self-contained. Its numerical rules follow the MXFP4 group-size-32 convention in `compressed-tensors at eb058d630f7344099459b6795b1e3eeffdda4b40 `_. * Input is a finite FLOAT matrix ``[N,K]``. Groups are consecutive columns on axis 1; ``K`` must be a positive multiple of 32. Incomplete groups, empty matrices and nonfinite inputs are rejected, not padded. * For each nonzero group, ``round_to_power_2(max(abs(group)))`` is computed using the pinned helper's E2M1 mantissa threshold, then divided by four (the E2M1 exponent offset of 2) to obtain the scale. An all-zero group uses scale one. The scale exponent is clamped to ``[-127, 125]`` to keep FLOAT reconstruction finite. The stored UINT8 scale is the biased exponent (bias 127); ``0xff`` is invalid. * Values are divided by the selected scale in FLOAT32, saturated to ``[-6,6]``, then rounded to E2M1 with midpoint ties to even. Negative normalized values that round to zero retain the sign bit; input ``-0.0`` and normalized ``-0.0`` encode as positive zero. * E2M1 sign is bit 3 and magnitude is bits 0--2. The first column occupies the low nibble. Payload bytes contain row-major packed values followed by row-major scale bytes. This byte ordering is explicit and swizzle-free, but does not claim compatibility with every vendor checkpoint packing ABI. The codec supplies numerical and portable storage compatibility for this contract. It does not provide an accelerated MXFP4 compute kernel. .. code-block:: cpp Tensor weights = Tensor::FromFloat("W", {2, 64}, std::vector(128, 1.f)); EncodedValueProto encoded = QuantizeMxfp4Weights(weights); Mxfp4Weights parameters = ExportMxfp4Weights(encoded); EncodedValueProto imported = ImportMxfp4Weights(parameters); ``Mxfp4Weights`` owns UINT8 ``weight_packed`` (``[N,K/2]``) and ``weight_scale`` (``[N,K/32]``). Export/import preserves the packed nibbles and E8M0 bytes exactly, and the encoded value survives ordinary wire serialization. Complete NVFP4 weights ---------------------- The complete fixed-weight codec is distinct from the existing portable ``QuantizationFormat::kNvfp4``. It preserves E2M1 packed values, E4M3FN local scales for groups of 16 along matrix axis 1, and a FLOAT32 global scale. See :ref:`the complete numerical contract ` for the pinned compressed-tensors reference, rounding order, packing and rejection policies. Activation-local dynamic scaling is **not** supported. .. code-block:: cpp // Both inputs are FLOAT tensors; K must be a positive multiple of 16. Tensor weights = Tensor::FromFloat("W", {2, 32}, std::vector(64, 1.f)); Tensor local = Tensor::FromFloat("scale", {2, 2}, std::vector(4, 1.f)); EncodedValueProto encoded = QuantizeNvfp4Weights(weights, local, 2.f); Tensor restored = DequantizeTensor(encoded); Nvfp4Weights parameters = ExportNvfp4Weights(encoded); EncodedValueProto imported = ImportNvfp4Weights(parameters); ``Nvfp4Weights`` owns ``weight_packed`` (UINT8 ``[N,K/2]``), ``weight_scale`` (FLOAT8E4M3FN ``[N,K/16]``), and ``weight_global_scale`` (``float``). Export/import preserves these parameters exactly without requantization. The self-describing ``onnx_light.nvfp4_weights.v1`` descriptor and payload also survive ordinary ``EncodedValueProto`` wire serialization. The encoder accepts FLOAT or FLOAT8E4M3FN local scales; FLOAT scales are rounded to FP8 before the FLOAT32 local/global division. Zero groups require positive local scales, just like nonzero groups. The codec rejects incomplete groups, nonfinite inputs, invalid scale shapes and zero/nonfinite effective scales. It performs no calibration and does not change the portable plan API. Reconstruction precision ------------------------ ``QuantizationPlan::reconstruction_dtype`` defaults to ``TensorProto::DOUBLE`` and preserves the existing ``onnx_light.quantization.v1/`` decoder. Set it to ``TensorProto::FLOAT`` to opt into the portable ``onnx_light.quantization.v2/`` contract. Output dtype does not select reconstruction precision: even DOUBLE outputs use FLOAT arithmetic for v2. The three ORT-compatible profiles retain v1 and reject FLOAT. v2 rounds operands and every reconstruction operation separately to binary32, including ordered codebook sums and inverse transforms, before output conversion. It uses float-valued reconstruction workspaces rather than a full binary64 tensor. See :doc:`the precise rounding and validation rules in the Python guide <../python/quantized_values>`; both APIs use the same decoder. Graph operators --------------- ``ai.rt::Quantize`` and ``ai.rt::Dequantize`` (opset 1) expose the native codecs as CPU kernels, with ``LightOpSchema`` declarations and shape inference. They are onnx-light extensions, not ONNX ``QuantizeLinear``/``DequantizeLinear``. The :ref:`graph-kernel gallery example ` demonstrates linear INT8 quantization with a scale and zero point, then nonlinear NF4 codebook quantization with automatic or explicit scales. It also serializes an encoded output for reuse as an initializer. * ``Quantize(X, scales?, zero_points?, offsets?, codebooks?, permutation?, forward?, inverse?, outliers?) -> Y`` takes a floating tensor and returns an ``EncodedValueProto``. Its required ``type`` attribute is a ``TypeProto`` containing the destination ``StructTypeProto``, inline or a model-catalogue reference. The encoded value retains the input's logical shape and dtype. * ``Dequantize(X) -> Y`` takes an encoded value and returns a tensor. Its required integer ``dtype`` attribute selects ``FLOAT``, ``DOUBLE``, ``FLOAT16`` or ``BFLOAT16``. Conversion writes directly to that dtype and rejects nonfinite results and overflow. ``make_quantization_type(plan)`` returns a portable plan's storage descriptor without requiring learned codebook values or populated transform matrices. The type fixes block coverage and the sizes of tables, permutations and transforms; it does not prescribe their numerical contents. For ORT layouts, use the ``struct_type`` of an existing ORT encoded value as the destination descriptor. Its matrix dimensions, scale dtype and zero-point storage must match the new result. When ``scales`` is omitted, ``Quantize`` calibrates **each block** from the actual input, after outlier removal, permutation and the forward transform: affine scales use the largest positive/negative ratio to the available code range, scalar codebooks use their minimum/maximum entries, and cast blocks use scale one. All-zero blocks use scale one. Default affine zero points are zero for signed codes and the midpoint for unsigned codes; offsets default to zero. Values outside a one-sided codebook/range still saturate or select the nearest entry. ORT calibration follows column/K-block order and the existing source-dtype rounding rules. Explicit per-node scales, zero points and offsets accept floating scalar tensors or one-dimensional tensors with one value per block. They override calibration. Codebooks concatenate all blocks' tables in run order. FLOAT, DOUBLE, FLOAT16 and BFLOAT16 parameter tensors are supported independently. Permutation and outlier indices are one-dimensional INT64 tensors. Transform inputs must have rank two and shape ``[n, n]`` matching the declared transform size, with values in row-major order. Flattened or reshaped tensors with the same element count are rejected. The kernel supplies the existing fixed scalar tables, but **does not train learned codebooks or run GPTQ/AWQ optimization**. Learned codebooks must be provided; vector/additive codebooks also require explicit scales. Nonempty permutations, transforms and outlier indices must be supplied. Missing or incompatible parameters fail explicitly. ORT layouts reject transforms, outliers, codebooks and offsets. For example, this creates a graph that calibrates INT4 blocks automatically: See the :doc:`Python recipe ` for this example. The runtime stores encoded edges in ``RuntimeContext.values()`` (Python ``get_value``/``put_value``), not in its ordinary tensor map. Sessions load encoded initializers and resolve model-scoped types; child contexts inherit the catalogue. Shape inference records Quantize's physical structured type. Dequantize propagates a concrete encoded initializer's logical shape; otherwise only its requested dtype is known. These inference rules belong to ``onnx_core.shape_inference.infer_shapes_model``; the ONNX-compatible ``onnx.shape_inference.infer_shapes`` does not register these ``ai.rt`` extension operators. The model checker validates encoded initializer names, layouts and model-scoped type references, including inside nested graphs. .. _l-shared-quantization-parameters-cpp: Model-level shared parameters ----------------------------- A storage type describes the arrangement of codes and parameter fields, not their numerical values. Two nodes using the same ``StructTypeProto.type_ref`` do **not** thereby share scales, zero points, codebooks or transforms. Without a numerical-parameter reference, each Quantize follows the explicit-input or automatic-calibration rules above and produces a self-contained payload. A shared numerical parameter set is a separate model resource. Selecting it fixes the encoding and reconstruction parameters for every input using that set; it must not recalibrate scales independently for those inputs. Values outside the selected range still follow the codec's existing saturation or nearest-code rules. The actual codes and any saved outlier **values** remain local to each encoded value. Declaring and selecting a set ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ``add_quantization_parameters(model, name, storage_type, logical_type, *, scales, ...)`` declares one named set. The optional numerical arguments have the same names, shapes and dtypes as Quantize's optional inputs. ``scales`` is required: shared mode never performs automatic calibration. Omitted optional parameters retain the codec's fixed defaults; learned tables, nonempty permutations, transforms and outlier indices must still be provided when the storage descriptor requires them. The declaration binds the full storage descriptor and a concrete logical tensor shape and dtype. Every consumer must match them. Quantize selects it with the string attribute ``parameter_ref`` and still supplies its full ``type`` attribute. Combining a reference with any nonempty optional parameter input is an error, rather than an override. The helper returns the **compact output storage type**. Use that type for encoded graph outputs, not Quantize's full input descriptor. A compact value contains a reserved byte, local outlier values and packed codes (or ORT ``B`` bytes), and records the set's name in ``EncodedValueProto.parameter_ref``. Its descriptor describes the actual local byte extent; it does not pretend the omitted parameters are present in the payload. For example, two paths can share one scale, including a path through Identity: See the :doc:`Python recipe ` for this example. The second input saturates at the range selected by the shared scale. It is not independently recalibrated to accommodate its larger values. Representation, scope and lifetime ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Declarations reuse the root graph's ``quantization_annotation`` catalogue. An annotation named ``onnx_light.quantization.parameters:`` maps roles to root ``initializer`` names through ``quant_parameter_tensor_names``. ``storage_type`` and ``logical_type`` are rank-one UINT8 initializers containing serialized ``StructTypeProto`` and ``TypeProto`` descriptors; the other roles refer to ordinary numerical TensorProto initializers. Unprefixed annotations keep their existing meaning. Duplicate set names, duplicate or unknown roles, missing initializers and incompatible descriptors or numerical tensors are errors. ``checker.check_model`` uses the runtime catalogue's declaration validation and reports these errors as ``ValidationError``. Numerical parameters stored in external data must be loaded before this validation. Catalogue construction derives the fixed plan, shared bytes and local byte ranges directly from descriptors and supplied parameters. It does not allocate a logical tensor or a full encoded payload. Its storage depends on parameter blocks, tables, transforms and indices, not on the number of local code bytes. This representation uses onnx-light's protobuf model serialization. Native ORT model serialization rejects quantization annotations and encoded initializers; textproto export also rejects unsupported structured/shared values instead of silently dropping their references. These declarations are model-scoped, not lexical graph inputs. Nested graphs and model-local functions inherit the model's parameter catalogue; local input names do not select a different set. Identity preserves the reference and its owner. Model checking resolves function-bound ``parameter_ref`` attributes using call-site values or function defaults, including nested calls and subgraphs. Unresolved attribute references in graph execution scope and omitted required function attributes are rejected. Shared encoded initializers must match their catalogue entry's logical type, compact storage type and payload extent; validation does not reconstruct the full encoded payload. Session initialization uses the same non-materializing validation before retaining the compact initializer and its shared parameter catalogue. The runtime takes an owned, immutable snapshot of the resolved numerical parameters, so retained encoded outputs can outlive the source model, session and context. Changing a model after creating its session does not update that session's parameter snapshot. Python exposes such retained outputs as ``SharedQuantizedValue`` rather than a bare proto. ``shared.encoded`` returns an independent snapshot of the compact encoded message, not a mutable alias of the runtime's value. ``dequantize_tensor(shared)`` and ``materialize_quantized_value(shared)`` use its retained resource; ``quantize_tensor_shared(tensor, model, name)`` provides the same fixed-parameter encoding without constructing a graph. For compact serialization, serialize ``shared.encoded`` and keep the declaring model alongside it. A parsed bare message has no in-memory owner: pass its model to the Python dequantization or materialization helper, or place it in that model's ``extended_initializer`` collection (``encoded_value`` alternative). A reference string alone cannot recover a missing model resource. For independent export, call ``materialize_quantized_value(shared)`` first. It produces a self-contained ``EncodedValueProto`` with inline storage type and numerical parameters and no ``parameter_ref``. Serialize that result when the recipient must decode it without the original model. Materialization does not change the shared source value. Sharing reduces retained and serialized per-value payloads. The reference codec still uses temporary full-layout buffers while encoding or materializing a shared value; this feature does not promise zero-copy quantization or dequantization. C++ --- .. code-block:: cpp #include "onnx_core/runtime/quantization.h" using namespace onnx_light::core::runtime; Tensor input = Tensor::FromFloat("weight", {3}, {-4, 0, 3.5f}); auto plan = MakeQuantizationPlan(QuantizationFormat::kInt4, 3); plan.runs[0].blocks[0].scale = 0.5; RuntimeValue encoded = QuantizeTensor(input, plan); Tensor restored = DequantizeTensor(encoded); ``MakeQuantizationType(plan)`` extracts the storage descriptor. ``QuantizeTensor(input, type, parameters, catalogue)`` applies the same calibration as the graph operator; the overload taking a plan uses its parameters unchanged. ``QuantizeTensorProto`` and ``DequantizeTensorProto`` provide the corresponding message conversions. C++ dequantizers accept a ``StructTypeCatalogue`` for model-scoped references; Python dequantizers accept an optional ``model``. The C++ tensor dequantizer also accepts an allocator. Its ``EncodedValueProto`` overload reads the message by const reference, without first copying it into a ``RuntimeValue``. The Python tensor dequantizer uses this overload too. For shared encoding, build an owned ``QuantizationParameterCatalogue`` from the model and pass it to ``QuantizeTensorShared``. The returned ``RuntimeValue`` retains that catalogue. ``DequantizeTensor(value)`` resolves it automatically; ``MaterializeQuantizedValue(value)`` exports an independent message. A bare compact ``EncodedValueProto`` instead needs the catalogue supplied to ``MaterializeQuantizedValue`` before calling the ordinary C++ proto decoder. The self-contained converters allocate the final ``raw_data`` buffer at its exact size and write into it directly. Proto encoding does not copy a completed encoded message out of a runtime wrapper; proto decoding does not materialize an intermediate output ``Tensor``. Numerical workspace (decoded values, transforms and codebook search) is still allocated: these are reference codecs, not zero-allocation conversions. Outputs own their storage independently of inputs. ``QuantizationFormats()`` is defined in the header as a ``constexpr`` function returning ``std::array`` without dynamic allocation: .. code-block:: cpp constexpr auto formats = QuantizationFormats(); static_assert(formats.front() == QuantizationFormat::kInt8); The Python ``quantization_formats()`` function returns a list of ``QuantizationFormat`` values. C++ provides ``QuantizationFormatName`` and ``ParseQuantizationFormat`` for explicit conversions to and from stable wire names. Numerical contract ------------------ This section describes the portable profiles. The ORT profiles have the :ref:`matrix-specific contract below `. Inputs and logical outputs support FLOAT, DOUBLE, FLOAT16 and BFLOAT16. Input shapes are concrete, including scalars and empty tensors. Inputs must be finite. Source storage is never modified and results own their storage. Nonfinite reconstructions and floating-point cast overflows are rejected. External messages must have their payload loaded before conversion. For a Python ``TensorProto``, call ``tensor.load_external_data(base_dir)``. The loader preserves ``data_location=EXTERNAL`` and its file metadata; quantization accepts it once ``raw_data`` is loaded, without changing that metadata. Blocks cover the flattened tensor exactly, in order. Each can select: * **Affine:** ``scale * (code - zero_point) + offset``. Codes have 1--16 bits and may be signed. Quantization clips to their range and rounds halfway cases to even, independently of the process rounding mode. * **Codebook:** ``scale * sum(codebook[book, index, :])``. Tables have ``books * entries * vector_size`` doubles in row-major order. The encoder chooses each book's closest vector to the remaining residual; equal distances select the first entry. This is a deterministic reference encoder, not AQLM training or a global optimal additive-codebook search. A final partial vector compares only its logical components. * **Cast:** a FLOAT, DOUBLE, FLOAT16 or BFLOAT16 scalar representation, with an optional multiplicative scale. With the explicit-plan APIs, scales default to **one**, not to an automatically estimated calibration. Callers supply their scales, integer zero points, real offsets, trained codebooks, rotations and selected outlier indices. Missing learned tables and required rotations raise an error. No GPTQ Hessian calculation, AWQ calibration, QAT or codebook training is performed. Encoding rejects invalid enum values, including after a caller edits ``plan.format`` in C++. Python rejects assigning strings or integers to that field. Decoding rejects unknown profile names in the encoded layout. The plan applies these steps: 1. Saves selected outliers and substitutes zero before quantization. 2. Gathers ``permutation[i]`` into quantization position ``i``. 3. Applies ``forward`` to consecutive row vectors of ``transform_size`` values. 4. Encodes consecutive blocks. Decoding applies ``inverse``, scatters back through the permutation, then restores the original outliers. The supplied matrices must be finite square inverse pairs (product within absolute tolerance ``1e-6``). This covers dense rotations and diagonal rescaling; the matrices are not assumed orthogonal. An empty permutation or transform is the identity. Per-channel quantization and tiling are explicit: group the intended channel/tile values with a permutation, choose matching block counts, and supply their parameters. Catalogue coverage ------------------ ``quantization_formats()`` returns these profiles. Parameters and block sizes can be overridden: a profile supplies starting values, not a vendor schema. In particular, hierarchical scale products are supplied as effective per-block scales/offsets; this representation does not reproduce compressed scale layouts. The third column contains executable plan configurations using this common setup. Each row is independent. Loops show how to configure every profile in the row; quantize inside the loop to use each resulting plan. The scales and synthetic codebooks are illustrative, not calibrated or trained. Replace them with your own parameters for real weights. See the :doc:`Python recipe ` for this example. .. list-table:: :header-rows: 1 :widths: 20 35 45 * - Profiles - Portable representation and caller inputs - Python plan configuration * - ``int8``, ``eetq``, ``int4`` - Signed affine codes: 8 bits for the first two, 4 for ``int4``. Scales supplied explicitly. - .. code-block:: python for profile in ( QuantizationFormat.INT8, QuantizationFormat.EETQ, QuantizationFormat.INT4, ): plan = make_quantization_plan(profile, n) run = plan.run(0) block = run.block(0) block.scale = 1 / (2 ** (run.layout.bits - 1) - 1) run.set_block(0, block) plan.set_run(0, run) * - ``int8_per_channel`` - Signed INT8 with explicit channel grouping. Here columns are channels, gathered into blocks before encoding; decoding restores row-major order. - .. code-block:: python plan = make_quantization_plan( QuantizationFormat.INT8_PER_CHANNEL, n, block_size=weights.shape[0] ) plan.permutation = numpy.arange(n).reshape(weights.shape).T.ravel().tolist() for i in range(weights.shape[1]): run = plan.run(0) block = run.block(i) maximum = float(numpy.abs(weights[:, i]).max()) block.scale = maximum / 127 if maximum > 0 else 1 run.set_block(i, block) plan.set_run(0, run) * - ``gptq``, ``awq``, ``matmulnbits`` - Unsigned INT4 affine codes, default zero point 8; supplied group parameters. - .. code-block:: python for profile in ( QuantizationFormat.GPTQ, QuantizationFormat.AWQ, QuantizationFormat.MATMULNBITS, ): plan = make_quantization_plan(profile, n, block_size=4) run = plan.run(0) blocks = run.blocks for block, scale in zip(blocks, [0.15, 0.05, 0.05, 0.15]): block.scale = scale block.zero_point = 8 run.blocks = blocks plan.set_run(0, run) * - ``hqq``, ``exl2``, ``exl3`` - Signed 4-bit affine defaults; override bits, counts and parameters for mixed precision, or select a codebook block explicitly. - .. code-block:: python for profile in ( QuantizationFormat.HQQ, QuantizationFormat.EXL2, QuantizationFormat.EXL3, ): plan = make_quantization_plan(profile, n, block_size=8) runs = [] for bits, scale in ((3, 0.25), (5, 0.125)): run = plan.run(0) run.layout.bits = bits block = run.block(0) block.scale = scale run.blocks = [block] runs.append(run) plan.runs = runs * - ``nf4`` - Fixed normal-float scalar codebook and supplied scale. - .. code-block:: python for profile in (QuantizationFormat.NF4,): plan = make_quantization_plan(profile, n) run = plan.run(0) block = run.block(0) block.scale = 1 run.set_block(0, block) plan.set_run(0, run) * - ``binary`` - One-bit indices into ``[-1, 1]``. - .. code-block:: python plan = make_quantization_plan(QuantizationFormat.BINARY, n) run = plan.run(0) block = run.block(0) block.scale = 0.5 run.set_block(0, block) plan.set_run(0, run) * - ``ternary``, ``bitnet``, ``paretoq``, ``tequila`` - Indices into ``[-1, 0, 1]``; five base-3 digits per byte. This represents ternary weights, not the associated training procedures. - .. code-block:: python for profile in ( QuantizationFormat.TERNARY, QuantizationFormat.BITNET, QuantizationFormat.PARETOQ, QuantizationFormat.TEQUILA, ): plan = make_quantization_plan(profile, n) run = plan.run(0) block = run.block(0) block.scale = 0.75 run.set_block(0, block) plan.set_run(0, run) * - ``stq1_0`` - Supplied vector codebook; defaults to 32 four-component entries and 5-bit indices. Code/sign splitting and vendor scatter layouts are not emitted. - .. code-block:: python plan = make_quantization_plan(QuantizationFormat.STQ1_0, n) run = plan.run(0) block = run.block(0) table = numpy.linspace(-1, 1, 128).reshape(1, 32, 4) block.codebook = table.ravel().tolist() run.set_block(0, block) plan.set_run(0, run) * - ``quip_sharp`` - A supplied 256-entry, eight-component codebook, plus an explicit transform pair. This example uses a two-component orthogonal rotation. - .. code-block:: python plan = make_quantization_plan(QuantizationFormat.QUIP_SHARP, n) run = plan.run(0) block = run.block(0) table = numpy.linspace(-1, 1, 2048).reshape(1, 256, 8) block.codebook = table.ravel().tolist() run.set_block(0, block) plan.set_run(0, run) rotation = numpy.array([[1, 1], [1, -1]]) / numpy.sqrt(2) plan.transform_size = 2 plan.forward = rotation.ravel().tolist() plan.inverse = rotation.T.ravel().tolist() * - ``aqlm`` - Supplied additive vector codebooks; defaults to two 256-entry, eight-component books with 8-bit indices. - .. code-block:: python plan = make_quantization_plan(QuantizationFormat.AQLM, n) run = plan.run(0) block = run.block(0) table = numpy.empty((2, 256, 8)) table[0] = numpy.linspace(-1, 1, 256)[:, None] table[1] = numpy.linspace(-0.125, 0.125, 256)[:, None] block.codebook = table.ravel().tolist() run.set_block(0, block) plan.set_run(0, run) * - ``spqr`` - Signed 4-bit affine base plus exact sparse outliers. Indices refer to the original flattened tensor; selection is the caller's responsibility. - .. code-block:: python plan = make_quantization_plan(QuantizationFormat.SPQR, n) plan.outliers = [0, 15] run = plan.run(0) block = run.block(0) block.scale = 0.125 run.set_block(0, block) plan.set_run(0, run) * - ``squeezellm`` - Supplied scalar-codebook base plus exact sparse outliers. Defaults to 16 supplied levels. - .. code-block:: python plan = make_quantization_plan(QuantizationFormat.SQUEEZELLM, n) plan.outliers = [0, 15] run = plan.run(0) block = run.block(0) block.codebook = numpy.linspace(-1, 1, 16).tolist() run.set_block(0, block) plan.set_run(0, run) * - ``log`` - Scalar codebook with zero and signed powers of two from ``2**-3`` through ``2**3``. Supply another table for a different base, range or logarithmic rule. - .. code-block:: python plan = make_quantization_plan(QuantizationFormat.LOG, n) run = plan.run(0) block = run.block(0) block.scale = 0.125 run.set_block(0, block) plan.set_run(0, run) * - ``fp6_llm``, ``mxfp6`` - E3M2 finite levels and supplied scales, using 6-bit codebook indices. - .. code-block:: python for profile in (QuantizationFormat.FP6_LLM, QuantizationFormat.MXFP6): plan = make_quantization_plan(profile, n) run = plan.run(0) block = run.block(0) block.scale = 0.25 run.set_block(0, block) plan.set_run(0, run) * - ``mxfp4``, ``nvfp4`` - E2M1 finite levels and supplied effective scales. The caller rounds scales to E8M0/FP8 and combines scale levels if required by their numerical profile. - .. code-block:: python for profile in (QuantizationFormat.MXFP4, QuantizationFormat.NVFP4): plan = make_quantization_plan(profile, n, block_size=8) run = plan.run(0) blocks = run.blocks for block, scale in zip(blocks, [0.25, 0.5]): block.scale = scale run.blocks = blocks plan.set_run(0, run) * - ``fp8_e4m3`` - Finite E4M3FN levels with 8-bit codebook indices; nonfinite levels excluded. - .. code-block:: python plan = make_quantization_plan(QuantizationFormat.FP8_E4M3, n) run = plan.run(0) block = run.block(0) block.scale = 0.5 run.set_block(0, block) plan.set_run(0, run) * - ``quarot``, ``smoothquant`` - Signed affine blocks (4 and 8 bits respectively), with explicit forward/inverse rotations or rescaling. - .. code-block:: python for profile in (QuantizationFormat.QUAROT, QuantizationFormat.SMOOTHQUANT): plan = make_quantization_plan(profile, n) matrix = ( numpy.array([[1, 1], [1, -1]]) / numpy.sqrt(2) if profile == QuantizationFormat.QUAROT else numpy.diag([2.0, 0.5]) ) plan.transform_size = 2 plan.forward = matrix.ravel().tolist() plan.inverse = numpy.linalg.inv(matrix).ravel().tolist() run = plan.run(0) block = run.block(0) block.scale = 0.25 run.set_block(0, block) plan.set_run(0, run) * - ``tiled_float`` - FLOAT casts by default. Here an explicit permutation groups 2-by-2 tiles and the physical storage is changed to FLOAT16. - .. code-block:: python plan = make_quantization_plan( QuantizationFormat.TILED_FLOAT, n, block_size=4 ) indices = numpy.arange(n).reshape(4, 4) plan.permutation = ( indices.reshape(2, 2, 2, 2).transpose(0, 2, 1, 3).ravel().tolist() ) run = plan.run(0) run.layout.cast_type = onnx.TensorProto.FLOAT16 plan.set_run(0, run) * - ``column_major`` - FLOAT casts with a supplied column-major ordering permutation. Decoding restores the original logical shape and order. - .. code-block:: python plan = make_quantization_plan(QuantizationFormat.COLUMN_MAJOR, n) plan.permutation = numpy.arange(n).reshape(weights.shape).T.ravel().tolist() After any row, use its configured plan as follows (or put these lines inside the profile loop to encode each profile): See the :doc:`Python recipe ` for this example. All floating-point/codebook profiles use closest-level encoding, with first-entry ties. They do not promise the external format's float bit patterns or tie-breaking. Scale tensors and learned codebooks belong to numerical parameter storage, not shared type constants. They are local to a self-contained value or supplied by an explicitly selected model parameter set. Consecutive blocks with the same physical layout share one array element declaration; changing scales or table contents does not duplicate the descriptor. This reference representation prioritizes correctness and explicit semantics over minimal payload size or fast quantization. Wire layout and validation -------------------------- This section describes the self-contained portable wire layout. The ORT profiles use the B/scales/zero_points layout described below instead. Shared values use the compact layout described in :ref:`l-shared-quantization-parameters-cpp`. The structured root name is ``onnx_light.quantization.v1/``. Its fields are, in order: one zero reserved byte, an INT64 permutation, DOUBLE forward and inverse matrices, INT64 outlier indices, DOUBLE outlier values, and a structure of block runs with a constant total block count. Each run is an array of blocks with identical layout parameters, named ``run_``. Adjacent compatible runs are merged. Integers/floats in the payload are little-endian. ``QuantizationPlan.runs`` follows this same organization in memory, with one layout per run instead of duplicating it in every block. The enum is converted to the existing profile name; neither the versioned wire schema nor the per-block payload order changes. Each block has a nine-element INT64 type constant containing count, method, index width, signedness, number of books, entries, vector width, base-3 flag and cast dtype. Method values are affine=0, codebook=1 and cast=2. Instance fields are DOUBLE scale, DOUBLE zero point, DOUBLE offset, the DOUBLE codebook and UINT8 packed codes. Binary indices are LSB-first, with zero high padding bits; base-3 packing stores the first index in the least significant trit and zero unused high trits. For additive codebooks, indices are ordered by logical vector, then book; each table is ordered by book, entry, then vector component. A partial final vector still stores one index per book. Cast codes are the requested floating dtype's ordinary little-endian bytes. The descriptor is checked against this exact versioned schema, including field names/types/dimensions. The generic proto validator checks payload extent and layout first; the converter additionally checks parameters, codebook indices, padding, permutations, inverse matrices and exact logical coverage. Unknown layouts are rejected, never interpreted by shape or profile name alone. Only this native consumer is implemented: the descriptor is not an automatically executable ONNX ``FunctionProto`` decoder, and tensor-only operators cannot consume it without explicit dequantization or a matching custom kernel. .. _l-ort-matmulnbits-inputs-cpp: ONNX Runtime MatMulNBits inputs ------------------------------- ``QuantizationFormat.ORT_MATMULNBITS_INT2``, ``ORT_MATMULNBITS_INT4`` and ``ORT_MATMULNBITS_INT8`` implement the input packing of ``com.microsoft::MatMulNBits`` version 1. They are separate from the original ``MATMULNBITS`` profile, which remains a portable onnx-light affine codec. These formats do **not** implement CPU microkernel or CUDA ``weight_prepacked`` layouts; the execution provider may still prepack the exported inputs internally. ``make_matmul_nbits_plan(format, k, n, block_size=128)`` accepts a positive ``[K,N]`` matrix shape and a power-of-two block size of at least 16 (at most ``UINT32_MAX``). Execution providers may restrict this further; the ORT CPU implementation supports 16, 32, 64, 128 and 256. The plan records ``matrix_shape=[K,N]`` and rejects mismatched sources. Sources are FLOAT, FLOAT16 or BFLOAT16 matrices, not DOUBLE or arbitrary-rank tensors. BFLOAT16 kernel availability depends on the ORT execution provider and version. ORT CPU currently also lacks the 8-bit unpacked-compute path selected by floating zero points. For INT8 execution on that provider, use implicit or packed integer zero points; floating zero points remain supported by this codec and the operator schema. There is one shared run layout and ``N * ceil(K/block_size)`` parameter blocks, ordered by column first, then by group along K. Each layout count is the full block size, including padding. Scales default to one; zero points default to ``2**(bits-1)``. Supply parameters explicitly; this is packing and conversion, not an implementation of ORT's scale-calibration algorithm. Scales and floating zero points are rounded to the source dtype **before** quantization so decoding and ORT use the same values. Codes are unsigned and use nearest-even rounding and clipping to ``[0, 2**bits-1]``. The reconstruction is ``(code-zero_point)*scale``. Negative finite scales are accepted. A zero scale is allowed only for an all-zero source group, and nonzero scales that round to zero are rejected. Offsets, codebooks, permutations, transforms, outliers, ``g_idx`` and fused bias are not part of these representations. The encoded root name is ``onnx_light.quantization.v1/ort_matmulnbits_int{2,4,8}``. Its logical type is the original ``[K,N]`` matrix. Its fields are: .. list-table:: :header-rows: 1 * - Field - Type and shape * - ``parameters`` - INT64 type constant ``[bits, block_size]``; consumes no payload bytes. * - ``B`` - UINT8 ``[N, ceil(K/block_size), block_size*bits/8]``. * - ``scales`` - Source dtype ``[N, ceil(K/block_size)]``. * - ``zero_points`` (optional) - UINT8 ``[N, ceil(ceil(K/block_size)*bits/8)]`` for packed integer zero points, or source dtype ``[N, ceil(K/block_size)]`` for floating zero points. ``raw_data`` concatenates B, scales and optional zero points, with no portable codec header or per-block DOUBLE metadata between them. B codes are packed least-significant bits first within each K block. The last block of each column is padded with zero codes. Packed zero points restart at a byte boundary for every column; unused high bits are zero. Both decoding and export reject nonzero weight-tail codes or unused zero-point bits. If all effective zero points equal the midpoint, the zero-point tensor is omitted. Otherwise all in-range integer zero points use packed UINT8 storage; any fractional or out-of-range value selects floating storage for the whole tensor. ``export_matmul_nbits_inputs(encoded, model=None)`` validates the descriptor and extracts owned TensorProto inputs without dequantizing. Its result exposes ``weights``, ``scales``, optional ``zero_points`` (``None`` when implicit), and the attributes ``k``, ``n``, ``bits`` and ``block_size``. Use the tensors as initializers for a normal ``MatMulNBits`` node, leaving ``weight_prepacked`` unset. Inline layouts and model-catalogue references both work. ``plan.matrix_shape`` is the native Python-visible ``Shape`` holding ``[K, N]``, also exported by ``onnx_light.onnx_core.shape_inference`` and ``onnx_light.onnx_core.quantization``. Its getter returns a mutable view that keeps the plan alive; assignment accepts a ``Shape`` or an integer list/tuple and copies the dimensions. Use ``list(plan.matrix_shape)`` for a plain list. Changing this shape does not rebuild the plan's blocks; incompatible geometry is rejected when encoding. See the :doc:`Python recipe ` for this example. The C++ equivalents are ``MakeMatMulNBitsPlan`` and ``ExportMatMulNBitsInputs``. The contract follows the `ORT operator schema `_ and `weight quantizer input shapes `_.