Skip to content

Latest commit

 

History

History
1037 lines (837 loc) · 52.3 KB

design.md

File metadata and controls

1037 lines (837 loc) · 52.3 KB

TICO System Design

TICO converts PyTorch programs represented as torch.export.ExportedProgram into Circle FlatBuffers. The implementation uses PyTorch's exported ATen graph as its working IR, applies a fixed legalization/optimization pipeline, conditionally legalizes quantized graphs, and serializes each remaining operator through a registered Circle visitor.

This document describes the behavior implemented on the current main branch. It is the reference for conversion architecture and exported-graph invariants. The Development Guide owns operational commands, and Circle artifact tools owns serialized-artifact APIs, rewrites, and runtime contracts.

Contents

1. Scope and non-goals

Scope

TICO currently provides:

  • nn.Module to Circle conversion through torch.export.export()
  • in-memory ExportedProgram to Circle conversion
  • saved .pt2 to Circle conversion
  • graph decomposition, legalization, canonicalization, and selected optimizations
  • conditional handling of graphs that already contain quantization operations
  • Circle serialization through ATen-target-specific visitors
  • a Python CircleModel wrapper for saving, loading, and local execution
  • post-serialization Circle inspection, verification, extraction, optimization, and cleanup tools
  • a separate model quantization subsystem with public prepare() and convert() APIs
  • config-driven quantization recipes for model-family workflows

Non-goals of the core converter

The core conversion API does not:

  • train a model or support training graphs
  • quantize an arbitrary floating-point model by itself
  • provide an unrestricted PyTorch interpreter
  • guarantee support for every ATen operator or arbitrary Python control flow
  • compile or schedule the result for a particular NPU backend
  • prove numerical parity or backend compatibility merely by producing valid Circle bytes
  • currently generate multiple Circle subgraphs from one ExportedProgram

2. End-to-end architecture

PyTorch nn.Module
    │
    │ tico.convert(...)
    ▼
torch.export.export
    │
    ├──────────────────────────────┐
    │                              │
Saved .pt2                    In-memory ExportedProgram
    │ torch.export.load             │
    └──────────────┬───────────────┘
                   ▼
         _prepare_exported_program
                   │
                   ├─ fake-quant decomposition
                   ├─ PyTorch decomposition with preserved operators
                   ├─ fixed-point legalization/optimization passes
                   ├─ relaxed-invariant cleanup
                   ├─ conditional quantization passes
                   ├─ supported-target and training-op checks
                   ▼
     Circle serializer + configured O1
                   │
                   ▼
       Circle bytes / atomic .circle file
                   │
                   ├─ CircleModel.save/load/__call__
                   └─ tico.circle inspect/verify/extract/optimize

The working graph remains an ExportedProgram; TICO does not introduce a separate custom middle IR between PyTorch export and Circle serialization.

3. Public API layer

The top-level tico package exports:

from tico import (
    CompileConfigV1,
    convert,
    convert_from_exported_program,
    convert_from_exported_program_to_file,
    convert_from_pt2,
    convert_from_pt2_to_file,
    convert_to_file,
    get_default_config,
)

convert

convert(
    mod: torch.nn.Module,
    args: tuple,
    kwargs: dict | None = None,
    dynamic_shapes: dict | tuple | None = None,
    strict: bool = True,
    config: CompileConfigBase = get_default_config(),
) -> CircleModel

Behavior:

  1. Warns fatally when the module reports training=True.
  2. Calls torch.export.export() under torch.no_grad().
  3. Runs the common ExportedProgram conversion path.
  4. Returns a CircleModel containing the serialized bytes.

convert_from_exported_program

Accepts an existing ExportedProgram, skips torch.export.export(), and runs the same legalization, validation, and serializer pipeline.

convert_from_pt2

Loads an exported program with torch.export.load() and runs the same conversion path. The pt2-to-circle executable is a file-oriented wrapper around this behavior and supports a versioned YAML compile configuration.

Explicit file conversion

convert_to_file(mod, args, output_path, ...), convert_from_exported_program_to_file(program, output_path, config=None), and convert_from_pt2_to_file(pt2_path, output_path, config=None) return None and write an atomic output file. They share the PyTorch legalization pipeline with the bytes APIs. A metadata-only schema round trip produces a normalized Circle document with borrowed read-only constants; the same configured O1 pipeline runs on that document before file serialization. The pt2-to-circle executable uses this path. See Large Circle export for memory ownership and layout policies.

4. Package responsibilities

Package Current responsibility
tico/config/ Versioned core compile configuration.
tico/utils/convert.py Public conversion orchestration and the authoritative pass order.
tico/passes/ Rewrites over PyTorch ExportedProgram / FX graphs.
tico/serialize/ Circle graph construction, tensor/buffer encoding, dtype/shape mapping, and operator visitors.
tico/serialize/operators/ Registered ATen-overload-to-Circle operator lowering.
tico/interpreter/ Runtime selection and input binding for CircleModel execution (default: the reference runtime; optional circle-interpreter/onert adapters).
tico/circle/ Post-serialization Circle document APIs, verification, extraction, Circle-to-Circle passes, and the reference runtime (tico/circle/runtime/).
tico/quantization/ Model quantization APIs, algorithms, WrapQ infrastructure, graph quantization passes, recipes, evaluation, export, and analysis.
test/modules/ Small PyTorch programs used by generated conversion/parity tests.
test/unit_test/ Focused core conversion and artifact-tool tests.
test/quantization/ Quantization-specific tests.

A key boundary is the IR being transformed:

  • tico/passes/ operates before serialization on PyTorch exported graphs.
  • tico/circle/passes/ operates after serialization on Circle object-model documents.

5. Conversion pipeline

The authoritative pass sequence is _prepare_exported_program() in tico/utils/convert.py, shared by bytes-returning and file-output conversion.

5.1 Input assumptions

The input is an ExportedProgram whose graph can be decomposed to supported core ATen patterns. Placeholder order and graph_signature.input_specs must remain aligned. Tensor-producing nodes are expected to carry usable meta["val"] shape and dtype information before serialization.

5.2 Fake-quant decomposition

Before the normal PyTorch decomposition stage, TICO runs:

DecomposeFakeQuantize
DecomposeFakeQuantizeTensorQParams

This exposes quantization behavior in forms that later decomposition, qparam propagation, and Circle serialization understand.

The tensor-qparams cachemask variant requires a compile-time constant fake_quant_enabled flag. The decomposition applies the flag's integer semantics: zero bypasses quantization, retaining floating tensor values and an all-true boolean mask; nonzero emits Q/DQ. Disabled sites do not require constant scale/zero-point values and do not assign a quantization domain to their inputs or outputs. Tuple projections are resolved by index, preserving output order and count. Runtime enable flags and live masks from enabled sites are rejected explicitly; export never drops a requested mask output. This contract is shared by all model families.

5.3 PyTorch decomposition

TICO then calls ExportedProgram.run_decompositions() through a version-adapted helper. Selected operators are deliberately preserved rather than decomposed because TICO has specific legalization or serializer handling for them. The preserved set includes convolution variants, selected activations and normalizations, linear, nearest-neighbor upsampling, and RMS normalization.

When TICO_GRAPH_DUMP is set, the first graph snapshot is written after this stage.

5.4 Main legalization and optimization bundle

The main PassManager currently runs the following ordered bundle. Because the default strategy is RESTART, a successful rewrite restarts scanning from the first pass.

FillMetaVal
ExtractDtypeKwargsPass
RemoveNop
LowerCopy
ConvertGatherToGatherNd
LowerMultiIndexToGatherNd
ConvertSymSizeToCircleShape
ConvertLayoutOpToReshape
RestoreLinear
ConvertToReLU6
DecomposeAddmm
DecomposeSliceScatter
DecomposeGroupNorm
DecomposeBatchNorm
DecomposeGroupedConv2d
CastATenWhereArgType
ConvertRepeatToExpandCopy
RemoveRedundantPermutePasses
RemoveRedundantAssertionNodes
RemoveRedundantExpand
RemoveRedundantSlice
FuseRedundantReshapeToMean
RemoveRedundantViewPasses
RemoveRedundantToCopy
RemoveEmptyCatInputs
MergeConsecutiveCat
CastMixedTypeArgs(preserve_ep_invariant=True)
ConstPropPass
SegmentIndexSelectConst
LegalizeCausalMaskValue(config-gated)
ConvertExpandToSliceCat(config-gated)
ConvertMatmulToLinear(config-gated variants)
LowerToResizeNearestNeighbor
LegalizePreDefinedLayoutOperators
LowerPow2ToMul
ConvertConv1dToConv2d
ConvertConv3dToConv2d
LowerToSlicePasses
FuseLeadingUnsqueezeReshape
CastClampMixedTypeArgs
EliminateRankRoundTripRegion(enabled=True)

This list intentionally mixes legalization and optimization today; the implementation contains a TODO to separate those concerns more explicitly. Adding a pass class does not automatically schedule it. It must be inserted into this explicit pipeline.

LowerCopy preserves aten.copy's destination dtype by casting the source when needed before either reusing it for equal shapes or expanding it to the destination shape. The cast does not change other users of the source tensor.

ConvertToReLU6 preserves the exported result dtype when replacing HardTanh, Clamp, or two nested Clamps with the equivalent [0, 6] activation. Scalar Clamp promotion is made explicit with a cast before ReLU6, including boolean-to-integer promotion and promotion introduced only by an inner Clamp. The rewrite uses the original result metadata rather than the current default dtype and preserves other users of the original input and any shared inner Clamp.

RemoveRedundantReshapePattern1 removes a leading singleton around a rank-three permute and multiplication only when every unchanged tensor multiplier has rank at most three. A rank-four multiplier can restore that axis through broadcasting, so the original final reshape must remain to preserve the graph's output rank.

LowerPow2ToMul squares in the original power's exported result dtype. If scalar promotion changes the base dtype, it casts before multiplying: integer x.pow(2.0) and boolean x.pow(2) retain their floating and integer result types respectively. Integer x.pow(2) retains its original dtype and overflow semantics. This rule uses the exported dtype rather than the process default at pass execution time.

LowerSelectCopyToSlice retains relative negative slice bounds and uses an open end for index=-1. This preserves one-element selection without specializing a symbolic input axis length.

RestoreLinear matches only a rank-two weight transposed by t or permute. It restores addmm only when both alpha and beta are one; other coefficients remain available to DecomposeAddmm, which preserves their scaling.

DecomposeAddmm creates zero-coefficient constants in the corresponding input or matrix-product dtype, independently of the process default floating dtype. A zero beta still discards the bias rather than multiplying it, so a NaN bias is ignored.

DecomposeSliceScatter normalizes unit-step slice bounds against the input axis length before constructing the retained prefix and suffix. Negative and clipped bounds follow ATen slicing semantics; reversed bounds describe an empty replacement. Steps greater than one remain unsupported.

DecomposeGroupNorm supports the normalized output (tuple index 0 or -3) of native LayerNorm and GroupNorm. It rejects live mean/rstd outputs and direct tuple uses before rewriting any normalization; unused statistics do not block conversion.

5.5 Relaxed-invariant cleanup

After the main bundle, TICO runs:

FillMetaVal
CastMixedTypeArgs(preserve_ep_invariant=False)

The code explicitly permits the strict ExportedProgram invariant to be relaxed at this point; graph constants may exist without being lifted back into placeholders. Serializer and subsequent passes must therefore handle the resulting representation.

The second graph snapshot is emitted after this phase when graph dumping is enabled.

5.6 Conditional quantization bundle

TICO detects whether the graph contains quantization operations. Only then it runs two separate pass managers, each using the default RESTART strategy. The first manager completes the pre-fold Q/DQ rewrites in this order:

PreserveEmbeddingQuantization       (preserve_embedding_quantization=True)
MoveAffineQuantizeBeforeLayout      (move_affine_quantize_before_layout=True)
LegalizeMxAffineDomains             (legalize_mx_affine_domains=True)

Q/DQ provenance is still available throughout this phase. Once this manager finishes, conversion crosses into the folded representation using a second manager:

FoldQuantOps
RemoveWeightDequantOp
PropagateQParamForward
PropagateQParamBackward
LegalizeQuantizedClamp
QParamSafeConstPropPass
QuantizeBias
RemoveUnusedPlaceholder
InsertQuantizeOnDtypeMismatch

A modification by a downstream pass restarts only this second manager at FoldQuantOps; it cannot re-enter embedding protection, layout movement or MX/affine pre-fold legalization after their Q/DQ provenance has been removed. This retains normal downstream fixed-point processing, including quantized Clamp legalization, and determines activation domains before bias quantization. The phase boundary also applies when the MX/affine option is disabled; the existing enabled pre-fold policies keep their order and downstream passes retain their restart behavior.

LegalizeQuantizedClamp converts constant Clamp bounds to the activation's per-tensor integer domain, aligns the Clamp input to that same scale and zero point, and removes bounds that cover the complete quantized dtype range. Backend-specific Clamp lowering and Linear fusion remain outside the core converter.

It then reports missing qparams non-strictly, with a specific exception for split_with_sizes because qparams are attached to its getitem result nodes.

MX quantization stores a validated, non-negative block axis in tensor qparams. Propagation remaps that axis through permutations and permits reshapes only when the existing 32-element blocks remain intact, including aligned attention head splits and merges. Unsupported regrouping raises an explicit error. Folding visits affine and MX Q/DQ pairs in graph order and preserves a QUANTIZE boundary when the MX axis or element format changes, including changes after layout operations. The Circle transpose-region optimization conservatively preserves MX regions; see the Circle pass contracts.

An affine Quantize may feed several Dequantize nodes and direct integer consumers. FoldQuantOps assigns the destination domain to the Quantize independently of its consumer count, then folds each matching Dequantize separately. A genuine grid change remains one shared Circle QUANTIZE; direct integer consumers retain their codes and qparams even when matching Dequantize consumers fold into the source domain. Nonmatching Dequantize parameters are not folded or used to retarget the shared domain; serialization rejects a Dequantize whose arguments disagree with its input qparams.

move_affine_quantize_before_layout is enabled by default (True) as the current NPU deployment export policy for MXINT8 -> static reshape/permute chain -> existing per-tensor INT16 Q/DQ. It moves the existing matching affine Q/DQ pair before the complete layout chain, so that chain exports with the original INT16 scale and zero point. It adds no observer, calibration, or quantization stage and retains the original MX quantizer and its rounding/grouping. The pass runs before folding can propagate an MX domain into a reshape that would require regrouping MX blocks.

The layout chain must have a single use at every step, counting graph outputs; the MX producer and final dequantized result may have multiple users. Unsupported layouts, dynamic shapes or qparams, per-channel/group quantization, non-MXINT8 sources, intervening computation or quantizers, shared integer Q outputs, mismatched Q/DQ settings, effectful operations crossed by the move, explicit DQ out_dtype arguments, and protected embedding boundaries are left unchanged. The initial implementation requires float32 FX values, positive static dimensions, and the existing signed INT16 ranges [-32768, 32767] or [-32767, 32767]; it keeps the selected range unchanged. The source MX pair must use matching int8, shared_exp_method="max", and round="nearest" arguments.

The target backend must support the MXINT8-to-INT16 conversion at the new position and the selected INT16 layouts. This option makes no general claim about MX layout support on Circle or NPUs. Circle structural verification and CPU graph equivalence are separate from NPU compilation and execution validation. This limited rewrite does not solve general mixed-domain legalization. Set the option to False to disable the policy and retain the previous export behavior:

config = tico.CompileConfigV1(move_affine_quantize_before_layout=False)
circle_model = tico.convert(quantized_model.eval(), example_args, config=config)

This phase legalizes and completes a graph that has already been prepared as quantized. It is not a replacement for model calibration or the public quantization workflow.

Affine backward propagation may retarget an explicit per-tensor Quantize to a Concat's domain, including through reshape/permute nodes, when the quantized dtype matches, the Quantize's sole user is the propagating node, and its input has no established quantization domain. A proven requantization retains its original boundary even when private. Explicit Quantize boundaries marked by PreserveEmbeddingQuantization are excluded from this retargeting, even when their float inputs have no qparams. See embedding boundary invariants. Retargeting updates its scale/zero-point arguments and output qparam metadata atomically and stops at its input boundary. Shared Quantize outputs, unsupported overloads, and non-affine or non-scalar domains remain unchanged. Serialization rejects Quantize arguments and output metadata that disagree.

The third graph snapshot is emitted after this phase when enabled.

5.7 Final checks and serialization

Before serialization, TICO:

  1. Checks every remaining call_function target against registered serializer visitors, allowing operator.getitem as a multiple-output bookkeeping operation.
  2. Rejects training operators such as aten.dropout and aten.native_dropout.
  3. Builds Circle tables through the shared serializer. Bytes APIs call build_circle_bytes() and then optimize the serialized document; file APIs call build_circle_model() and optimize its normalized document before saving.

full_like retains its dtype through legalization. Its serializer creates the fill values directly in that dtype, or in the input dtype when it is omitted or None. This preserves fractional and large integer fill values without casting the input tensor's data.

6. Pass manager and graph invariants

Pass interface

Core PyTorch-IR passes implement:

class PassBase(ABC):
    def call(self, exported_program: ExportedProgram) -> PassResult:
        ...

@dataclass
class PassResult:
    modified: bool

modified is part of the scheduler contract. A pass that changes the graph must report it accurately unless it intentionally guarantees a one-shot transformation and has a well-documented reason not to restart.

Scheduling strategies

  • PassStrategy.RESTART is the default. After a modification, execution resumes from the first pass in the bundle.
  • PassStrategy.UNTIL_NO_CHANGE completes the bundle before starting another iteration.
  • The manager fails after 1,000 changing iterations to detect circular rewrite loops.

Graph signature maintenance

Each pass call runs under the ExportedProgram graph-signature replacement hook. Node replacement must still preserve these invariants:

  • Placeholder node order matches graph_signature.input_specs.
  • User inputs, parameters, buffers, constants, and outputs retain valid bindings.
  • New tensor nodes carry correct shape/dtype metadata.
  • Dead nodes are removed when the rewrite makes them unreachable.
  • Graph linting and recompilation follow structural changes where required.

Serializer-facing invariant

At the end of conversion:

  • Every non-getitem call_function target has a registered NodeVisitor.
  • Tensor-producing nodes have serializable dense values and metadata.
  • User inputs and outputs resolve to registered Circle tensors.
  • Circle shapes and shape signatures are internally consistent.
  • Quantized tensors carry qparam metadata in a representation understood by the serializer.

7. Compile configuration

CompileConfigFactory currently supports version 1.0, implemented by CompileConfigV1.

Field Default Consumed by
legalize_causal_mask_value False LegalizeCausalMaskValue
remove_constant_input False Circle input registration in build_circle_bytes()
convert_lhs_const_mm_to_fc False ConvertMatmulToLinear
convert_rhs_const_mm_to_fc True ConvertMatmulToLinear
convert_single_batch_lhs_const_bmm_to_fc False ConvertMatmulToLinear
convert_expand_to_slice_cat False ConvertExpandToSliceCat
eliminate_rank_round_trip False Currently not consumed; the pass is instantiated with enabled=True.
circle_optimize True Shared Circle O1 document pipeline, after packing on the bytes path and before final packing on the file path.
preserve_embedding_quantization False Conditionally inserts PreserveEmbeddingQuantization before FoldQuantOps to preserve explicit quantization boundaries in supported embedding paths during Circle export.
legalize_mx_affine_domains False Opt-in pre-fold target quantization policy: explicit MXINT8 activation adapters and native output rounding; no export-time calibration.
move_affine_quantize_before_layout True Conditionally inserts MoveAffineQuantizeBeforeLayout after embedding-boundary preservation and before FoldQuantOps, moving existing INT16 affine Q/DQ ahead of supported static MXINT8 layout chains.

CompileConfigBase.from_dict() applies only keys already present on the dataclass. The current implementation ignores unknown fields rather than rejecting them. Configuration review and tests should therefore catch misspellings and obsolete keys.

Conversion behavior that affects semantics or backend compatibility should be exposed through an explicit configuration field only when the pipeline actually consumes that field. Keep the dataclass, YAML examples, implementation wiring, and tests synchronized.

8. Circle serialization

build_circle_bytes() constructs a generated Circle object model and packs it with FlatBuffers. build_circle_model() shares construction but normalizes only metadata through the schema, retaining constant payload views for file output.

8.1 Model construction

The current serializer:

  • creates one CircleSubgraph
  • reserves buffer 0 for tensors without embedded data
  • exports graph tensors and constants
  • registers InputKind.USER_INPUT values as graph inputs
  • optionally excludes ConstantArgument inputs
  • always excludes None constant inputs
  • registers non-None user outputs
  • dispatches each supported non-getitem call-function node to its registered visitor, which emits the required Circle operator or operator sequence
  • validates tensor shapes before packing
  • writes the CIR0 file identifier

8.2 Operator visitors

NodeVisitor subclasses register one or more ATen overload targets with the register_node_visitor decorator. The registry provides both:

  • the target-to-visitor mapping used by the serializer
  • the supported-target set used by pre-serialization validation

A newly added visitor is not useful unless its module is imported by the serializer operator package so its registration side effect occurs.

Multi-axis repeat that cannot become a singleton broadcast is serialized as a chain of CONCATENATION operators. RepeatVisitor owns the cumulative shape of that chain: each intermediate tensor retains all preceding axis expansions and preserves symbolic dimensions in its shape signature.

8.3 Tensor data and shared storage

Parameters, buffers, and lifted constants are copied to CPU, made contiguous, and encoded into Circle buffers. The serializer tracks tensor identity using device, storage pointer, storage offset, shape, stride, dtype, layout, and qparam identity. This allows genuinely shared storage, such as tied embedding and LM-head weights, to reuse one Circle tensor without deduplicating unrelated cloned tensors that merely have equal values.

Empty tensors and tensors without a stable nonzero data pointer are intentionally not shared through this mechanism.

8.4 Quantized tensor encoding

When a node carries TICO qparam metadata, the Circle tensor dtype and quantization record are derived from that metadata. The serializer supports regular integer types as well as project-specific quantized string dtypes used by current workflows, including uint4, mxint8, and mxfp4. Packed uint4 data is encoded before buffer insertion.

9. Shapes, interfaces, and runtime binding

Static and symbolic shapes

A static PyTorch shape becomes a Circle shape with no shapeSignature.

When a dimension is a torch.SymInt:

  • Circle shape stores 1 as a concrete placeholder.
  • Circle shapeSignature stores -1 for that dimension.
  • Static dimensions are repeated in both vectors.

Shape validation requires equal ranks and requires every dynamic -1 signature entry to correspond to placeholder value 1.

Model input binding

ModelInputSpec reads the one-subgraph Circle interface and binds user arguments in serialized input order. It:

  • flattens nested list/tuple positional values
  • skips None
  • flattens nested keyword values into generated names
  • understands Hugging Face DynamicCache when Transformers provides it
  • converts supported scalar values to tensors
  • checks input count, dtype, rank, and static dimensions
  • permits dimensions marked -1 in the shape signature

CircleModel

CircleModel owns raw bytes and provides:

CircleModel.save(path)
CircleModel.load(path)
CircleModel(*args, **kwargs)

The built-in inference path executes the serialized bytes with the reference runtime in tico/circle/runtime/. It supports one subgraph, validates every operator result against the serialized shape/dtype contract, executes dynamic shape signatures from the actual input sizes, and returns one NumPy array for one output and a list for multiple outputs. CircleModel(..., runtime=...) can select the optional circle-interpreter (ONE) or onert adapters explicitly; the default never depends on which external packages are installed.

10. Quantization integration

WrapQ admission precedes graph export. Observer-owned schema-versioned snapshots hold exact grids, policy, provenance and locks. A common coordinator derives and validates all required candidates and wrapper semantic constraints before an atomic commit to QUANT; missing required calibration rejects without partial conversion. Wrappers declare active sites and optional execution capabilities and collect local parameters. Exporters consume snapshots; generated profile constants have separate local grids. State restoration validates frozen semantics rather than recomputing from ranges. See WrapQ lifecycle.

This admission boundary does not change Q/DQ domain lowering or final Circle ABI.

Quantization has two related but distinct layers.

10.1 Public model quantization API

tico.quantization exports:

from tico.quantization import prepare, convert, QuantStub

The lifecycle is:

prepare(model, quant_config, args, kwargs)
    -> calibration or algorithm statistics collection
    -> convert(prepared_model)

prepare() chooses a quantizer through the quantizer registry and stores it on the prepared model. convert() retrieves that quantizer; it does not accept the configuration again. The classic GPTQQuantizer requires in-place conversion because deep copying would break its calibration catcher restoration.

10.2 Conversion-time quantized-graph legalization

After a model has been quantized or instrumented to contain supported quantization operations, the core Circle conversion path detects those operations and performs qparam folding, propagation, bias quantization, safe constant propagation, placeholder cleanup, and dtype-bridge insertion.

These graph passes do not perform calibration and do not select a quantization algorithm.

A Circle CONCATENATION copies integer codes, so the exported operator uses one quantization domain (dtype, scale, zero point) on every input and its output. This rule applies to every concat axis and to every module origin, including width-direction tico.ops.Concat; there is no per-axis exception. For affine uint8/int16 per-tensor domains, legalization makes each required domain change explicit with a QUANTIZE:

  • Identical input and output domains need no conversion. Observer min/max metadata is not part of the domain; scales compare exactly.
  • When every input shares one domain A and the output requests B, the concat runs in A and one QUANTIZE converts the joined result to B. An already folded concat[A] -> QUANTIZE[B] boundary is kept as is.
  • When input domains differ, each input connection whose domain differs from the output domain gets a QUANTIZE into that domain. Producers keep their own qparams and their other uses (graph inputs, graph outputs, other consumers), and a repeated operand reuses one conversion.
  • An input that is itself a requantization keeps that earlier rounding and saturation step; the concat conversion is chained after it, never merged into it.

Fully annotated domains outside this scope (per-channel or non-uint8/int16 affine grids) are rejected explicitly, and incompletely annotated or MX concats keep their existing contracts. Running the legalization again does not add operators.

The NPU compiler previously realized mismatched concat inputs with implicit rescales; the explicit QUANTIZE describes the same source-to-destination domain change in the Circle itself, so structural verification and the reference runtime can check it. The tico.ops.Concat flag allow_distinct_input_qparams is a WrapQ calibration policy: it decides whether QuantConcat observes and fake-quantizes every input in the shared output domain or lets each branch keep its producer's domain. It does not change the export contract above.

Wrapper fake-quantization calls mark tensor quantization domains and calibration points. After decomposition, their Q-DQ pairs are an intermediate representation of those domains; they do not require physical Circle QUANTIZE and DEQUANTIZE operators at every marked point. With the default embedding export policy, or outside embedding paths explicitly preserved by CompileConfigV1(preserve_embedding_quantization=True), for a producer with no existing qparams, FoldQuantOps converts its first quantization point into tensor metadata:

op -> Q(A) -> DQ(A)    =>    op [QPARAM=A]

The serializer uses that annotation to give the corresponding Circle tensor its quantized dtype, scale, and zero-point (or the configured MX domain). Intermediate FX meta["val"] dtypes are not the final runtime ABI: quantization passes may briefly contain float value metadata on an edge whose serialized tensor will be quantized. Passes must not reconstruct floating-point execution solely to make those intermediate edges executable under final runtime dtype semantics.

An existing domain changes the meaning of a subsequent quantization point. If a tensor already belongs to domain A and Q-DQ requests a different domain B, the QUANTIZE represents genuine requantization and remains:

op [QPARAM=A] -> Q(B) -> DQ(B)    =>    op [QPARAM=A] -> Quantize [QPARAM=B]

Scale, zero-point, dtype, and MX element format or axis can distinguish domains. Supported view chains, per-tensor split/getitem outputs, zero padding in a per-tensor affine domain, and same-domain concatenations retain proven source domains so folding can distinguish redundant annotation from requantization. Zero PAD preserves its input domain; a different requested output grid requires an explicit requantization boundary, since native PAD copies interior integer codes. Propagation preserves established producer and consumer domains, and a private quantizer with a proven source domain cannot be retargeted to a later consumer's grid: sequential rounding and saturation remain observable even when storage dtypes match. MX propagation also checks axis remapping and shared-exponent block membership; layouts that regroup blocks are not interchangeable domains.

For NPU-targeted quantized tensors, valid qparams remain required. Semantic index, shape, and control values are excluded. An intentional CPU float island instead uses real FLOAT32 tensors without qparams, with explicit conversion operators at its integer boundaries; it must not use fabricated qparams to satisfy NPU checks.

Explicit embedding preservation is an opt-in export policy: preserve_embedding_quantization=True inserts PreserveEmbeddingQuantization first in the pre-fold manager, before optional layout movement and domain legalization; omission or False retains the existing policy and following pass order. It keeps the supported lookup's float region and explicit Q/DQ boundaries while preserving shared integer weights and the output ABI. GATHER remains a selection operation and does not requantize codes across domains.

The CPU embedding guide owns the export policy, numerical and storage contracts, pass invariants, and selected-row execution pattern. Runtime planning follows the serialized graph independently of the compile option. Structural verification, native reference execution, fake-quant evaluation, and external backend validation remain separate checks; see reference execution modes.

10.3 Opt-in MXINT8 / affine activation policy

CompileConfigV1(legalize_mx_affine_domains=True) inserts LegalizeMxAffineDomains after embedding protection and MoveAffineQuantizeBeforeLayout in the pre-fold manager. That manager completes before FoldQuantOps, propagation and QuantizeBias enter their separate restart scope; downstream changes cannot execute this Q/DQ-dependent policy on a folded graph. See quantization phase ordering. Its initial default is False. The independent layout option still defaults to True: #1130 commutes an existing quantizer equivalently; this policy can introduce additional rounding. This change is based on #1130 head 22caefedf503d990d195f2b9d49d93c4c8f94eac and depends on that PR until it is merged. #1129 implementation is not a source of this policy.

The target activation contract is same-family inputs and native output (MX or affine), with affine weights independently represented. Type compatibility is not grid equality. In particular, arithmetic may have different input/output scales and zero points. Serializer support alone is not evidence of NPU support; the native MX activation/affine weight contract here is the target requirement, not a result of running an NPU compiler.

Operation Opt-in cross-domain behavior Constraints
linear Select MX activation/native output when activation input or requested output is MX; preserve affine weight and float32 bias Existing affine per-tensor/channel/group weight lowering is reused without retargeting its bit width, axis or sharing; integer bias cannot be reinterpreted
add.Tensor, sub.Tensor, mul.Tensor Convert each affine operand after its existing Q/DQ to MX; preserve existing MX input; quantize native output in MX before requested affine output Broadcasting preserved; ADD/SUB alpha remains in the Q/DQ reference; Circle alpha other than 1 is explicitly unsupported rather than silently dropped
bmm Separate operand adapters: left contraction axis 2, right contraction axis 1, native output axis 2 Existing MX quantizers remain; a different required axis adds another Q/DQ; original output axis is retained as an explicit conversion
relu, sigmoid MX input/native output; retain original requested affine output conversion Input and output boundaries are independent; neither activation is a layout quantizer mover
aten.rms_norm, circle_custom.rms_norm MX activation/native output with independently affine gamma Preserve eps/normalized_shape and existing serializer limitations (one normalized dimension, explicit eps and weight); no output grid reused at input
cat Commute the original output quantizer onto each input connection Per-tensor affine commutes pointwise; MX destination requires compatible axis and intact block boundaries; every nonfinal input on the concat MX axis must end at a complete block
split_with_sizes / tensor getitem Preserve input domain; keep conversion on each selected result Validate unused slots as well; repeated/negative indices alias the correct result; no shape/Python indexing inference
slice.Tensor Carry known per-tensor affine or MX domains through lowered indexing/unbind paths Reuse remap_mx_qparam() for MX axis/block proofs; reject cuts or regrouping, preserve unknown inputs as unknown; this does not move Q/DQ across slices
reshape, permute Reuse #1130 boundary movement and existing MX remapping Does not legalize arbitrary regrouping or prohibit all existing MX layouts; explicit move_affine_quantize_before_layout=False retains that option's behavior

For newly converted elementwise operands the MX axis is their last tensor axis. Existing MX operands keep their axis, grouping and quantizer; BMM's explicit role-dependent reblocking is chained after them. Native output uses the requested MX axis when already provided, otherwise its last axis (BMM always axis 2). MX export remains block32, int8, shared_exp_method="max", round="nearest". Full UINT8/INT16 and narrow INT16 [-32767,32767] output adapters retain exact quantizer arguments. Narrow INT16 adapters carry a clipping marker through folding and serialize as QUANTIZE followed by same-grid MAXIMUM(code=-32767), since the Circle QUANTIZE options do not encode quant_min. The same marker preserves original narrow input boundaries before an MX adapter: full-storage native rounding followed by a same-grid clamp equals the original narrow rounding. Existing embedding float clamps retain their own handling without a second clamp. Arbitrary narrower activation ranges are diagnosed rather than widened. Other MX formats, dynamic qparams and per-channel activation adapters are outside this policy. Already legal affine/float graphs and same-domain MX graphs remain unchanged. Same-family copy operations still require grid/group preservation.

For example, with two independent grids A and B and requested output grid C:

before: DQ_A(Q_A(x)) ---- MUL ---- Q_C ---- DQ_C
        DQ_M(Q_M(y)) -----/

after:  DQ_A(Q_A(x)) -- Q_M -- DQ_M -- MUL -- Q_M -- DQ_M -- Q_C -- DQ_C
        DQ_M(Q_M(y)) ----------------/

The original A, M and C boundaries stay intact. Q_M(MUL(...)) is native output rounding, not an equivalent algebraic optimization. No arithmetic output grid is copied from an input. Source connections are updated by operand position; BMM(x,x) can therefore adapt only its right operand. Conversion sharing is local to one consumer and requires identical source and complete destination arguments. Raw shared operation outputs that cannot safely adopt a native output domain are rejected. Policy admission inspects every relevant output Q/DQ for MX, independently of selecting a single private output boundary. A completed native domain plan is restored first. A CAT whose inputs share a domain also keeps its native copy domain when the existing axis/block-preservation proof succeeds. These established outputs may feed several consumer-specific MX Q/DQ adapters; restarting the pre-fold manager does not reinterpret those adapters as ambiguous native output requests. This applies both to a previously rewritten CAT and to an unchanged same-domain CAT without a completed-plan marker. MX CATs must still pass the full axis and block checks, and a private destination boundary can still commute to the inputs when a native copy cannot preserve blocks.

When native output selection or rewriting is still necessary and an activation input or any output boundary is MX, multiple output Q/DQ boundaries are rejected with node/op and native-output-selection context, regardless of quantizer creation order. In particular, affine-input SIGMOID with MX and affine output boundaries remains unsupported. No branch is selected arbitrarily, no quantizer is retargeted, and no adapter deduplication is required to accept a proven native domain. Affine-only multiple-boundary paths retain their existing behavior. QuantParam objects are copied instead of mutated across branches. The MX fake kernels also return independent fake tensors in accordance with the non-aliasing custom-op schema, preserving shared affine/MX graph outputs.

The plan is represented solely by Q/DQ in the pre-fold graph. The internal run_target_reference(program, *inputs) executes that stage on CPU with real affine Q/DQ and the existing MX fake-quant kernel. It must be used before folding. There is no second reference legalizer. After folding, the same inserted boundaries serialize as Circle QUANTIZE, including native output metadata and explicit cross-domain adapters. O1 output-requantize fusion excludes MX tensors so it cannot absorb a required MX-to-affine output adapter.

This policy never calibrates at export. No affine grid is manufactured from dtype, example/FakeTensor values, an unrelated operand, or output statistics. All affine destinations come from an existing explicit Q/DQ; an affine native input path would require its own independently observed/frozen boundary during preparation. Since all supported activation operations can execute natively in MX, no new observer lifecycle is required here. Missing boundaries, unknown weight family, shared raw outputs, unsupported grouping/options/ranges are diagnosed with node, operation and boundary context. Explicit float islands and embedding protection retain their independent policies. Round trips are never eliminated by this pass.

Validation separates three questions: exact preservation when commuting CAT or #1130 layout boundaries; equality to an independently constructed target Q/DQ reference including new rounding; and error against the original eager model. For example, a wide-input sigmoid test changes by up to 1/256 at its UINT8 output because of native MX output quantization. Eager model accuracy therefore cannot be reported as exported target accuracy. Structural Circle verification and CPU Q/DQ reference tests do not establish bit-exact NPU behavior. The built-in reference runtime still cannot execute MX Circle tensors; no MX backend execution is implied by these tests.

10.4 Recipe architecture

The recipe layer keeps end-to-end model workflows separate by responsibility:

  • model-family behavior: recipes/adapters/
  • algorithm orchestration stages: recipes/stages/
  • calibration data: recipes/data/
  • evaluation: recipes/evaluation/
  • artifact export: recipes/export/
  • saved Circle bundle execution and host KV-cache composition: recipes/runtime/
  • debugging and parity: recipes/debug/
  • user-selectable workflows: YAML presets under examples/configs/

See the Quantization Recipes Developer Guide for the current package contracts.

11. Circle artifact layer

tico.circle operates on Circle object-model documents and is independent from the exported-graph pass pipeline. Documents may come from serialized bytes or the file converter's metadata-only schema round trip. The same document layer supports inspection, verification, extraction, and Circle-to-Circle transformations.

The built-in O1 pipeline completes ordered optimization rounds until no pass changes the document, then compacts indices once. This artifact-level fixed point is separate from the PyTorch-IR scheduling described in Pass manager and graph invariants. Static verification, numerical parity, and target-backend support are distinct validation claims.

The Circle guide owns the detailed contracts:

Concern Reference
Document API and extraction Python API and CLI
Pass responsibilities and O1 phases Pass taxonomy and scheduling
Analysis caches, local rules, and rollback Optimization sessions and atomic rewrites
Structural validation and indexed resources Verification and graph/index handling
Observable roots and protected inputs Optimization and dead-code elimination
Serialized execution and quantized modes Reference runtime

12. Validation, errors, and diagnostics

Unsupported target validation

Before serialization, all remaining function targets are compared with the visitor registry. TICO logs each unsupported operator and its source stack trace when present, then raises NotYetSupportedError.

Training validation

convert() reports a fatal message for a module still in training mode. The final graph check also rejects known training operators, currently dropout variants.

Shape validation

The serializer validates Circle tensor shapes and shape signatures before packing. The runtime input binder separately validates user input count, dtype, rank, and static dimensions.

Debugging

Pass diagnostics expose graph and constant changes; serialized-artifact inspection then checks the resulting interfaces and structural consistency. The Development Guide maintains the logging, graph-image, and Circle inspection commands.

13. Extension points

Add a new exported-graph pass

  1. Implement PassBase in tico/passes/.
  2. Define precise matching preconditions and return PassResult.modified correctly.
  3. Preserve graph signature and metadata invariants.
  4. Add the pass explicitly to the correct position in tico/utils/convert.py.
  5. Add focused unit tests, including non-matching cases.
  6. Add an end-to-end module test when the serialized graph or numerical behavior is affected.

Add a new Circle operator lowering

  1. Add a NodeVisitor under tico/serialize/operators/.
  2. Register every supported ATen overload.
  3. Ensure the module is imported by the operator package.
  4. Encode inputs, outputs, attributes, and opcode data through existing graph helpers.
  5. Add visitor/serializer unit tests and a PyTorch-to-Circle parity test.

Add a quantizer or quantization workflow

Preserve the public prepare/statistics/convert lifecycle. The quantization guide owns algorithm configuration and registration; the recipe guide owns adapter, stage, and algorithm responsibility boundaries. Use the quantization testing criteria and recipe testing checklist for deterministic unit coverage and the smallest useful workflow smoke test.

Add a Circle-to-Circle pass

Circle passes extend the serialized-artifact layer. Follow Writing a new Circle pass for semantic placement, mutation and invariant requirements, and CLI/preset registration. The Circle testing checklist covers positive and non-matching rewrites, shared resources, rollback, and fixed-point behavior.

14. Current limitations

  • Core serialization emits one subgraph.
  • Built-in CircleModel inference also supports one subgraph.
  • Only registered ATen overloads can reach serialization.
  • Dynamic shape signatures are preserved and executed by the reference runtime; the optional circle-interpreter adapter cannot execute them.
  • The main exported-graph pass schedule is a fixed list in tico/utils/convert.py, not a plugin-discovered pipeline.
  • Legalization and optimization passes are currently combined in one main bundle.
  • CompileConfigV1.eliminate_rank_round_trip is declared but not wired to the pass; the pass is currently always enabled.
  • Unknown YAML configuration keys are ignored by the current dataclass loader.
  • Successful Circle serialization does not imply compatibility with a particular NPU compiler.
  • The reference runtime rejects integer arithmetic on quantized tensors in native mode and offers a fake-quantize mode instead; it does not emulate a specific NPU backend bit-exactly.

15. Implementation source map

Use these files as the source of truth when updating this document:

Topic Source
Public exports and minimum Torch warning tico/__init__.py
Conversion APIs and pass order tico/utils/convert.py
Pass interface and scheduling tico/utils/passes.py
Compile configuration tico/config/base.py, tico/config/v1.py, tico/config/factory.py
Circle construction tico/serialize/circle_serializer.py
Tensor/buffer representation tico/serialize/circle_graph.py
Shape and dtype mapping tico/serialize/circle_mapping.py
Operator registry tico/serialize/operators/node_visitor.py
Input binding and dynamic signatures tico/utils/signature.py
Built-in runtime tico/utils/model.py, tico/interpreter/, tico/circle/runtime/
Quantization public API tico/quantization/public_interface.py
Circle artifact APIs and pass taxonomy tico/circle/README.md, tico/circle/passes/optimization/
Circle optimization presets and scheduling tico/circle/passes/presets.py, tico/circle/passes/manager.py
Circle CLI pass registry tico/circle/cli/main.py
Source tooling and CI infra/, .github/workflows/check-pr.yaml