Skip to content

[quantization] Add two-stage calibration boundary to WrapQ - #1153

Draft
dvsav wants to merge 8 commits into
Samsung:mainfrom
dvsav:t1
Draft

dvsav wants to merge 8 commits into
Samsung:mainfrom
dvsav:t1

Conversation

@dvsav

@dvsav dvsav commented Nov 30, 2026

Copy link
Copy Markdown
Contributor

Based on: #782
Issue: #1152 (T1)

What

Adds the infrastructure for two-stage calibration and context-aware observation to the WrapQ quantization backend:

  1. A prepare_stage2() lifecycle boundary that propagates between the first and second calibration passes, notifying every quantization wrapper and every observer in the model tree.
  2. Keyword-argument plumbing that lets wrappers pass arbitrary collection context (e.g. weights, step counters — keys defined by wrappers, never by the base classes) through _fq() → ObserverBase.collect() → _update_stats().

Both mechanisms default to no-ops: models that never use them are completely unaffected.

Why

Some quantization strategies (e.g. observers that refine their grids from an intermediate candidate, MSE/percentile-style search seeded by a first-pass estimate) need to observe calibration data in two passes: gather preliminary statistics, transform/reconfigure internal state at the boundary, then re-calibrate with the improved configuration. Additionally, such observers need access to values available at the observation site (such as the layer weight) that a plain activation tensor does not carry.

Before this change there was no sanctioned place in the WrapQ lifecycle for that boundary, and collect() accepted only the activation tensor. This PR adds the mechanical protocol so that feature work in later steps (stage-2-capable observers, context-aware wrappers) can build on it without touching base-class contracts again. It intentionally introduces no behavior change — freeze_qparams() remains the only place that derives, installs, and freezes qparams.

Key Design Decisions

  • Notification-only boundary. prepare_stage2() uses the exact same module/observer inventory as freeze_qparams() but derives/installs/freezes nothing, changes no mode, and mutates no statistics. This keeps the freeze pipeline as the single owner of final-grid derivation and makes the call safe to repeat and safe before any calibration. Immutability is asserted by tests (twin models freeze to bit-identical grids with and without the boundary).
  • Opt-in context forwarding via signature probe. collect() forwards **kwargs to _update_stats() only when the concrete implementation declares **kwargs (detected once per class via a cached inspect.signature probe). This let all existing observers (MinMax, EMA, MSE, Percentile, MX, Identity) stay byte-for-byte unchanged, keeps calls crash-free when a wrapper passes context to a non-aware observer (context is silently dropped), and keeps mypy happy because overrides only widen the base one-argument signature. The alternative (changing the abstract signature to **kwargs) was rejected: mypy flagged every existing subclass override as incompatible.
  • Forwarding only in CALIB mode. _fq() passes context to obs.collect() only in the calibration branch; QUANT (fake_quant) and NO_QUANT paths ignore it, preserving the existing mode semantics. Context is also dropped when collection is disabled or the observer is frozen, matching the "disabled collection collects nothing" contract.
  • No implicit triggering. The boundary is only invoked explicitly (prepare_stage2() on the model or PTQQuantizer.prepare_stage2(model) for recipe drivers); nothing in prepare(), calibration, or convert() calls it.
  • Lifecycle-override guard extended. The existing _modules() guard that rejects wrapper overrides of enable_calibration/freeze_qparams now also rejects overrides of prepare_stage2, pointing subclasses to the local _prepare_stage2() hook instead — same pattern as _prepare_calibration/_validate_freeze.

Changes

  • tico/quantization/wrapq/observers/base.py — collect(x, **kwargs) with gated forwarding to _update_stats(); cached _update_stats_accepts_context() signature probe; new no-op ObserverBase.prepare_stage2() observer hook; docstring contracts for context keys and drop semantics.
  • tico/quantization/wrapq/wrappers/quant_module_base.py — _fq(x, obs, **kwargs) forwards context to collect() in CALIB mode only; public prepare_stage2() delegating to the lifecycle walker; overridable no-op _prepare_stage2() module hook. (One hunk is a formatter-only reflow of a pre-existing ternary.)
  • tico/quantization/wrapq/lifecycle.py — new prepare_stage2(root) walker (same _modules()/_inventory() walk as freeze_qparams; observers notified first, then modules); override guard extended to reject subclass overrides of prepare_stage2.
  • tico/quantization/wrapq/quantizer.py — PTQQuantizer.prepare_stage2(model) user-facing entry point (explicit, @torch.no_grad(), returns the model) with the documented usage sequence.
  • tico/quantization/wrapq/README.md — paragraph documenting the two-stage calibration boundary and its no-op-by-default contract.
  • tico/quantization/wrapq/observers/mse.py — formatter-only reflow (no semantic change).
  • test/quantization/wrapq/observers/test_collection_context.py — new, 6 tests for the context plumbing.
  • test/quantization/wrapq/test_prepare_stage2.py — new, 9 tests for the boundary propagation, no-op guarantees, and quantizer hook.

Tests

New deterministic CPU tests (no model downloads):

  • test_collection_context.py — kwargs reach a **kwargs-aware observer via collect() (identity preserved); one-argument overrides tolerate and ignore context; MinMaxObserver yields identical statistics with and without context; disabled/frozen observers short-circuit before stats even with context.
  • test_prepare_stage2.py — _fq forwards context only in CALIB mode; the walker reaches every wrapper and observer of a nested tree; safe before any calibration and on repeat; statistics and frozen results are provably unchanged (twin-model bit-identical grids after two boundary calls); quantizer hook propagates on hand-wrapped and prepare()-wrapped nn.Linear models; subclass overrides of prepare_stage2 are rejected.

Commands and output:

$ python3 -m unittest test.quantization.wrapq.observers.test_collection_context \
                      test.quantization.wrapq.test_prepare_stage2 -v
...
test_context_observer_receives_kwargs ... ok
test_context_observer_without_kwargs ... ok
test_disabled_collection_skips_stats_even_with_kwargs ... ok
test_frozen_observer_ignores_context_kwargs ... ok
test_minmax_observer_works_with_and_without_kwargs ... ok
test_plain_override_drops_context_kwargs ... ok
test_fq_forwards_context_in_calib_mode ... ok
test_fq_ignores_context_in_no_quant_mode ... ok
test_fq_ignores_context_in_quant_mode ... ok
test_default_noop_before_any_calibration ... ok
test_override_of_entrypoint_is_rejected ... ok
test_preserves_statistics_and_freeze_result ... ok
test_reaches_every_wrapper_and_observer ... ok
test_quantizer_hook_on_prepared_wrapped_model ... ok
test_quantizer_hook_triggers_propagation ... ok
----------------------------------------------------------------------
Ran 15 tests in 3.157s

OK

Regression suites (all pass):

$ python3 -m unittest discover -s test/quantization/wrapq/observers -t .
Ran 128 tests in 6.080s
OK (skipped=1)                      # skip pre-existing, unrelated

$ python3 -m unittest test.quantization.wrapq.test_lifecycle \
                      test.quantization.wrapq.test_frozen_state_export \
                      test.quantization.wrapq.wrappers.test_quant_module_base
Ran 57 tests in 85.532s
OK

$ python3 -m unittest discover -s test/quantization/config -t .
Ran 104 tests — OK

Lint/format (lintrunner, matching ./ccex format): UFMT, PYLINT, MYPY all clean on every changed/added file.

Example Scripts

None added. The intended consumer usage (for future stage-2 observers) is:

model = quantizer.prepare(model)
for data in calibration_dataset:      # stage 1
    model(data)
quantizer.prepare_stage2(model)       # boundary (no-op today)
for data in calibration_dataset:      # stage 2
    model(data)
model = quantizer.convert(model)      # freeze + export

d.savchenkov added 6 commits November 27, 2026 10:16
Search MSE-optimal affine grids and merge them across batches.

Co-authored-by: Cline

TICO-DCO-1.0-Signed-off-by: d.savchenkov <d.savchenkov@partner.samsung.com>
Plumb collection context and stage-2 hooks through the quantizer lifecycle.

Co-authored-by: Cline

TICO-DCO-1.0-Signed-off-by: d.savchenkov <d.savchenkov@partner.samsung.com>

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant