Skip to content

refactor(definitions): declare calibration side modules instead of per-model hook pairs - #6464

Merged
Qubitium merged 1 commit into
mainfrom
refactor/defs-declared-side-modules
Nov 30, 2026
Merged

Qubitium merged 1 commit into
mainfrom
refactor/defs-declared-side-modules

Conversation

@Qubitium

Copy link
Copy Markdown
Collaborator

Summary

Twenty-eight model definitions hand-wrote the same pre_quantize_generate_hook_start/_end pair. The start hook materialized a fixed list of non-decoder modules (embeddings, final norm, rotary, vision/audio towers, projectors) onto the quantize device. The end hook then either offloaded each module to disk relative to its parent or moved it back to CPU. Seven _materialize_* helper copies and four test-only _turtle_lock shims came along with the pairs. BaseQModel now owns that pair, and each definition supplies data:

class SmolVLMQModel(BaseQModel):
    calibration_device_modules = (
        "model.text_model.embed_tokens",
        "model.text_model.norm",
        "model.text_model.rotary_emb",
        "model.vision_model",
        "model.connector",
    )

This is a behavior-preserving refactor. No numerics, checkpoint-format or public-API change. Every GPU A/B checkpoint is bit-identical, VL models included.

git diff --shortstat origin/main: 45 files changed, 605 insertions(+), 1147 deletions(-). Under gptqmodel/ alone: 32 files changed, 276 insertions(+), 1104 deletions(-) (net −828). The remaining +329/−43 is tests (+1 new file) and the docs section.

What Changed

  • BaseQModel (gptqmodel/models/base.py):
    • New class attribute calibration_device_modules: Tuple[str, ...] = ().
    • New method calibration_device_module_paths(). It returns the tuple. Override it only when a path depends on the loaded layout.
    • pre_quantize_generate_hook_start() replaces the pass stub. For each path it calls shell_module_materialize(module, quantize_config.device, module_path=path) and installs the returned module.
    • pre_quantize_generate_hook_end() replaces the pass stub. For each path it calls offload_to_disk(model=<immediate parent>, module) (same offload directory names as before) or setattr(parent, name, move_to(module, CPU)).
  • Converted, now a plain tuple (14): deepseek_ocr2, deepseek_vl, inkling, intern_s2_preview, interns1, internvl, lfm2_vl, llava, minicpmv, ovis, ovis2, qwen2_audio, smolvlm, zdtaichu5.
  • Converted with a layout-dependent calibration_device_module_paths():
    • BaseQwen2VL/BaseQwen3VL: model. or root prefix.
    • MLlama: the resolved language model.
    • OpenVLA: norm vs final_layernorm.
    • Nemotron-Omni and LFM3-Omni: optional towers.
    • Unlimited-OCR: get_base_modules.
  • Converted with a short super() wrapper for real per-model work:
    • Qwen3-VL family: deepstack capture.
    • Gemma3-VL: replay-mask capture.
    • Cohere-Compass, LFM3-VL, LFM3-Omni: outer capture. LFM3-VL and LFM3-Omni call BaseQModel directly to skip LFM3QModel's text-only hooks, as before.
    • DeepSeek-VL2: direct meta and direct parameters.
    • Unlimited-OCR: direct parameters and position_ids.
    • Inkling2-Loop: counter reset.
    • MiniCPM-o: keeps its existing CPU-only tts move.
    • LocateAnything: keeps pre_quantize staging and uses the base release.
  • Qwen2VLTextQModel/Qwen2_5_VLTextQModel now reset calibration_device_module_paths to the base method instead of aliasing the two hooks.
  • ModuleLooper._model_initial_capture_is_generic (gptqmodel/looper/module_looper.py) also returns False when a class declares calibration_device_modules or overrides calibration_device_module_paths. Without this, each converted VLM would silently become eligible for GPTAQ/FOEM first-capture reuse ([Audit][GPTAQ/FOEM] Native and GPTQ processors repeat the same first-layer capture #5831), because its hooks are now the base ones.
  • Docs: a "Declared side modules" section with a flow diagram in docs/input-capture-cleanup-lifecycle.md. That page is already linked from docs/README.md.

Kept as-is (out of scope, deliberately):

  • apertus and hunyuan_vl materialize to normalize_device_like(qcfg.device). That pins an index-less DEVICE.CUDA to cuda:0, while the base and every other definition pass the family through, which means the current CUDA device. Converting them would change placement when the current device is not 0.
  • qwen2_5_omni, qwen3_omni_moe, internvl_chat, minicpmv_4_6, ovis2_5 (and ovis2_6_*) offload some modules relative to a non-parent root. The offload directory name is read back by _resolve_offload_entry during save.
  • ernie4_5_vl_moe has a total release with a partial-meta leaf move and error aggregation, pinned by its 20 tests.
  • lfm3 materializes and never releases.
  • diffusion_gemma and internvl_chat stage through pre_quantize.
  • gemma3n, gemma4, falcon_h1, falcon_mamba and mimo_v2 do no side-module staging.

Follow-ups, not in this PR:

  • Unify apertus/hunyuan_vl on quantize_config.device. This is a placement change.
  • Give the base release ERNIE's total-release semantics. The docs contract asks for them, but the 28 converted definitions never had them (see Notes).

Tests

  • Unit tests have been executed and passed, or the reason they are not applicable is documented.
  • I added a new simple/fast unit test for this change, or documented why that is not applicable.

New tests:

  • tests/test_calibration_device_modules.py::test_declared_side_modules_stage_and_release_the_replaced_hook_modules[<21 model types>-cpu|disk] (42 nodes, CPU).
    • Each node builds the real vendored model on meta from its native-parity fixture: cohere_compass, deepseek_ocr2, deepseek_vl, exaone4_5, gemma3 (composite VL config), glm_ocr, internvl, lfm2_vl, lfm3_vl, llava, ovis2, qwen2_vl, qwen2_5_vl, qwen2_vl_text, qwen2_5_vl_text, qwen2_audio, qwen3_vl, qwen3_vl_moe, qwen3_5_moe, smolvlm, unlimited_ocr.
    • It drives both hooks and asserts the materialized and released paths equal EXPECTED. EXPECTED is the release order recorded from the removed hooks on origin/main.
    • It also asserts:
      • each path is the module's own qualified name, so LazyTurtle resolves the same checkpoint keys as the old path-less calls;
      • the device is quantize_config.device;
      • offload_to_disk receives the immediate parent and the same directory name;
      • the CPU branch calls move_to(..., CPU).
  • tests/test_gptaq_foem_first_capture_5831.py::test_declared_calibration_side_modules_disable_reuse[calibration_device_modules|calibration_device_module_paths] (CPU, real tiny Qwen2 quantize).
    • Red: with the new guard removed, both nodes fail at assert 6 == (2 * 6), meaning the capture was reused.
    • Green: with the guard, both pass.

Updated tests (they patched the definition-module offload_to_disk/move_to, used materialize fakes without module_path, or relied on the removed _turtle_lock shim). Each now patches gptqmodel.models.base, accepts module_path (and asserts it in the cohere/deepseek cases), or gives its stub _turtle_lock/turtle_model=None and an nn.Module tree:

  • test_cohere_compass
  • test_deepseek_vl
  • test_deepseek_vl_v2
  • test_gemma3_vl_support
  • test_mllama_support
  • test_qwen2_audio_support
  • test_qwen2_family_compat
  • test_qwen3_vl_dependency
  • test_smolvlm_support
  • test_zdtaichu5_support

Affected-family run: 110 test files, i.e. every test file that references a hook, a converted definition class or the capture-reuse guard. The 12 tests/models/*::Test*::test_* full-model eval cases are deselected; the GPU A/B below covers end to end.

export PYTHONPATH=$PWD HF_HOME=/root/.cache/huggingface CUDA_DEVICE_ORDER=PCI_BUS_ID CUDA_VISIBLE_DEVICES=0 HF_HUB_OFFLINE=1
python -P -m pytest -o addopts="" -q -rs -p no:cacheprovider -n 16 <12 x --deselect models/test_*::Test*> <110 files> [tests/test_calibration_device_modules.py]
# origin/main 1c51b32a7: 5 failed, 3066 passed, 24 skipped
# branch:                5 failed, 3110 passed, 24 skipped   (+44 = the new nodes)
  • The 5 failures are identical on origin/main and are unrelated:
    • models/test_cohere_compass.py::test_cohere_compass_model_type_selects_definition and models/test_llava.py::test_llava_model_type_selects_image_text_definition: gptqmodel.models.auto has no AutoConfig.
    • test_vlm_prepare_dataset_contract_4633.py::test_conversation_path_rejects_concat_size[Qwen2VLTextQModel|Qwen2_5_VLTextQModel]: the error message is stale.
    • test_unlimited_ocr_support.py::test_unlimited_ocr_prepares_native_image_layout_and_retries: cpu/cuda index tensor mismatch when a GPU is visible.
  • The 24 skips are identical on both and leave these paths unverified:
    • 6 need ≥2 CUDA devices.
    • 5 are HF greedy-id references recorded for sdpa on non-sliding variants only.
    • 4 MiniCPM-o TTS cases need gptqmodel[minicpm-o].
    • 6 need /monster/data/model/LFM3-* checkpoints.
    • 1 Unlimited-OCR release asset needs network.
    • 2 are families not exercised as buildable CausalLM (muse_glimmer, opt350).
bash format/check.sh   # ruff 0.14.2: All checks passed!  (temporary no-op pip shim; venv ruff 0.14.2)

Structural A/B: hook-call log, old vs new, every affected definition

The recorder record_hooks.py covers 58 MODEL_MAP types: every type whose MRO defines either hook or the new attribute or method on either tree. That includes the unconverted ones as controls.

  • It runs both hooks with offload_to_disk False and True, on two shells per type:
    • (a) the real port model built on meta from its native-parity fixture (29 types);
    • (b) an auto-vivifying nn.Module shell where every path exists (all 58).
  • It records, in order: each shell_module_materialize (effective LazyTurtle path and device), each offload_to_disk (module, root, directory name), each move_to, the per-model extras (capture start/stop, direct parameters, pre_quantize) and any raise.
PYTHONPATH=<tree> python -P record_hooks.py hooks_<tree>.json   # once on origin/main, once on the branch
python compare_hooks.py hooks_base.json hooks_new.json
# identical runs: 166, differing runs: 8
# all 8 = qwen2_vl / qwen2_5_vl [real|auto x offload False|True]: start-order-only
#   old start: model.visual, model.language_model.embed_tokens, model.language_model.rotary_emb
#   new start: model.language_model.embed_tokens, model.language_model.rotary_emb, model.visual
#   release sequence, offload roots/dir names, devices: identical
# materialize path != qualified module name: none (old or new)

The capture-reuse guard A/B evaluates ModuleLooper._model_initial_capture_is_generic() for all 210 MODEL_MAP entries on both trees. Result: 140 generic on both, 0 differences.

GPU A/B: bit-identical saved checkpoints

Setup:

  • GPU 0 (RTX 4090), CUDA_DEVICE_ORDER=PCI_BUS_ID, trust_remote_code=False.
  • Each case was quantized on origin/main 1c51b32 and on this branch with an identical config (GPTQConfig(bits=4, group_size=128), FP16), seed and calibration rows. The rows are 8 deterministic synthetic 224×224 images with fixed captions as chat conversations. The text control uses 32 wikitext rows.
  • gptqmodel.__file__ was printed in every log to prove which tree ran.
  • The comparison checks every saved tensor byte for byte, plus exact bytes of every other file. The exception is quant_log.csv, compared as sorted rows without time.
Case (definition, release path) Tensors Other files Result
Qwen/Qwen2-VL-2B-Instruct (BaseQwen2VLGPTQ, layout method, start order changed, offload_to_disk=True) 1317 7 bit-identical
llava-hf/llava-interleave-qwen-0.5b-hf (LlavaQModel tuple, offload_to_disk=True) 1219 7 bit-identical
LiquidAI/LFM2-VL-450M (LFM2VLQModel tuple, offload_to_disk=False, CPU release) 627 7 bit-identical
Qwen/Qwen2.5-0.5B-Instruct (text control, unaffected definition) 794 6 bit-identical

SmolVLM2 could not run here because its required num2words package is not installed. It is covered by the real-model unit test and the structural A/B.

Measured Impact

Not applicable: no claimed issue. Peak VRAM was equal in every A/B pair: Qwen2-VL 1821 MiB, llava 1105 MiB, LFM2-VL 402 MiB, Qwen2.5 416 MiB.

Model Support / Module Plan

Not applicable. No MODEL_MAP entry, alias, module_tree or fusion profile changes; only the calibration side-module hooks of existing definitions move. The real-model unit test above pins the staged paths per definition.

Model test node IDs and results: see Tests.

AWQ onboarding safety

Not applicable: no AWQ grouping, search, replay or fold code is touched. AWQ reaches these hooks only through the shared input capture, whose staging is unchanged (structural A/B).

Logic Flow Documentation

  • This change does not alter a major logic flow, or the required diagrams and docs page are included below.
  • New-flow Mermaid diagram(s) describe the shipped code using real symbol names.
  • The removed/replaced mechanism is shown or tabulated with file:line evidence.
  • Failure and ambiguity paths are marked and visually distinct from success.
  • A reference page under docs/ repeats the diagrams, titled for the mechanism, and is linked from README.md (docs/input-capture-cleanup-lifecycle.md, linked from docs/README.md).

The flow replaces a decision mechanism: per-definition code becomes declared paths.

flowchart TD
    A["StageInputsCapture.cache_inputs()"] --> B["pre_quantize_generate_hook_start()"]
    B --> C["calibration_device_module_paths()<br/>default: calibration_device_modules"]
    C --> D["_get_parent_and_leaf_by_path(self.model, path)"]
    D --> E["shell_module_materialize(module, quantize_config.device, module_path=path)"]
    E --> F["capture forward, StopForward at layer 0"]
    F --> G["finally: pre_quantize_generate_hook_end()"]
    G --> H{"quantize_config.offload_to_disk"}
    H -- True --> I["offload_to_disk(model=parent, module)"]
    H -- False --> J["setattr(parent, name, move_to(module, CPU))"]
    D -. "missing path" .-> X["AttributeError, as the old attribute access"]
    J -. "partially meta module" .-> Y["move_to raises, logged by cache_inputs if a capture error is already propagating"]
    style X fill:#fdd
    style Y fill:#fdd
Loading
flowchart LR
    R["ModuleLooper._reusable_initial_capture()"] --> S{"_model_initial_capture_is_generic()"}
    S --> T{"declares calibration_device_modules<br/>or overrides calibration_device_module_paths?"}
    T -- yes --> N["not generic: second capture runs"]
    T -- no --> U{"any _CAPTURE_REUSE_GUARDED_HOOKS overridden?"}
    U -- yes --> N
    U -- no --> V["reuse GPTQ native capture"]
Loading
Decision Old (origin/main 1c51b32) New
Which modules are staged hand-written list per definition, e.g. smolvlm.py:58-89, llava.py:91-128, gemma3.py:238-282, base_qwen2_vl.py:141-179, mllama.py:142-177 calibration_device_modules / calibration_device_module_paths()
Materialize call shell_module_materialize(module, device), sometimes with module_path (llava, lfm3_*, openvla, zdtaichu5, unlimited_ocr) always with module_path=path (verified equal to the qualified name for all 21 real models)
Test-only _turtle_lock shim base_qwen2_vl.py:143, base_qwen3_vl.py:243, mllama.py:147, nemotron_omni.py:88 removed; stubs set _turtle_lock/turtle_model=None
Release per definition offload_to_disk(model=<parent>, ...) or move_to(..., CPU) BaseQModel.pre_quantize_generate_hook_end(), same parent and order
Base hooks base.py:5312-5316 pass shared implementation
Capture reuse hook identity only (module_looper.py:2009) plus declared-modules check

Failure paths:

Situation Before After
Declared module missing at start AttributeError from attribute access AttributeError from get_submodule/getattr
Optional tower absent (Nemotron-Omni, LFM3-Omni, MLlama, MiniCPM-o tts) skipped skipped (filtered in calibration_device_module_paths() / kept in the override)
Partially meta module at end (start raised mid-move) move_to raises; remaining releases skipped unchanged (not total; ERNIE keeps its own total release)

Review Requirements

I or an AI agent (such as Codex or Claude) have:

  • Reviewed this PR.
  • Checked that the code matches existing project structure, APIs, and conventions.
  • Avoided unnecessary monkeypatching and used the project's normal extension points where possible.
  • Minimized and compacted the impacted code surface.
  • Considered and eliminated potential regressions.

Kernel Accuracy Requirements

Not applicable: no kernel, packer, dispatch or fusion code is touched.

Notes

  • Only ordering change: Qwen2-VL/Qwen2.5-VL now materialize visual after embed_tokens/rotary_emb, matching the release order. Each materialization loads a disjoint module, and the Qwen2-VL-2B A/B is bit-identical.
  • Base now installs the module returned by shell_module_materialize. Some removed hooks did this and others did not. The production materializer returns the same object on the default role, so the extra setattr is a no-op there.
  • Pre-existing gaps, left alone (not part of this refactor):
    • The 28 converted definitions never had the total release that docs/input-capture-cleanup-lifecycle.md asks of a definition. A partially materialized module makes move_to() raise and stops the remaining releases, or is skipped by offload_to_disk(). The base keeps that behavior, and the doc now says so. Moving ERNIE's _release_module into the base would be a separate behavior-change PR.
    • apertus/hunyuan_vl stage on cuda:0 while the other VL definitions stage on the current device of the DEVICE family (see What Changed).

🤖 Generated with Claude Code

…r-model hook pairs

Twenty-eight definitions hand-wrote the same pre_quantize_generate_hook_start/_end
pair: materialize a fixed list of non-decoder modules (embeddings, final norm,
rotary, vision/audio towers, projectors) onto the quantize device, then either
offload each one to disk relative to its parent or move it back to CPU. Seven
`_materialize_*` helper copies and four test-only `_turtle_lock` shims came
with them.

BaseQModel now owns that pair, driven by data:

- `calibration_device_modules`: dotted paths under `self.model`, in
  materialize/release order.
- `calibration_device_module_paths()`: override only when a path depends on
  the loaded layout (Qwen2/3-VL prefix, MLlama language model, OpenVLA norm
  name, optional Nemotron-Omni/LFM3-Omni towers, Unlimited-OCR base modules).

The base start hook passes each path as `module_path` to
`shell_module_materialize` and installs the returned module. The base end hook
offloads with `model=<immediate parent>` (same offload directory names as
before) or moves the module to CPU. Definitions with extra work keep a short
override around `super()` (deepstack/replay-mask/outer capture, DeepSeek-VL2 and
Unlimited-OCR direct parameters, Inkling2-Loop counters, MiniCPM-o `tts`,
LocateAnything's `pre_quantize` staging). The Qwen2-VL/Qwen2.5-VL text classes
reset `calibration_device_module_paths` instead of the two hooks.

`ModuleLooper._model_initial_capture_is_generic` also treats a non-empty
declaration or an overridden `calibration_device_module_paths` as
model-specific, so converted VLMs do not become eligible for GPTAQ/FOEM capture
reuse.

Behavior is unchanged: the same modules are staged on the same device and
released in the same order to the same offload directories. The one exception is
Qwen2-VL/Qwen2.5-VL, whose start hook used to materialize `visual` first; it now
uses the release order. The GPU A/B is bit-identical. Definitions whose staging
differs (pre_quantize staging, non-parent offload roots, no release, ERNIE's
total release, a device pinned through `normalize_device_like`) keep their hooks.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@Qubitium
Qubitium marked this pull request as ready for review November 30, 2026 02:29
@Qubitium
Qubitium merged commit 1afbae2 into main Nov 30, 2026
6 checks passed
@Qubitium
Qubitium deleted the refactor/defs-declared-side-modules branch November 30, 2026 02:29
Qubitium added a commit that referenced this pull request Nov 30, 2026
…d teardown

Rebased fix/6148-issue onto origin/main 94ceaf7 (after #6464, #6465,
#6467, #6469, #6470). Three conflicts:
- gptqmodel/looper/forward_executor.py: import block. Main dropped the
  unused resolve_calibration_keep_mask import; kept only the PR's
  replay_records import.
- gptqmodel/looper/module_looper.py: #6465 moved the failed-run teardown
  into InflightLayerTracker (inflight_layer.py). Kept main's structure and
  re-applied the PR's release_looped_capture() as a ModuleLooper override
  of _release_failed_run_processors that calls super() first.
- gptqmodel/models/definitions/inkling2_loop.py: #6464 reduced
  pre_quantize_generate_hook_start to the batch-index/bank reset plus
  super(); the PR removes that reset, so the override is deleted.

Earlier rebase (onto 81ac176):
Rebased fix/6148-issue onto origin/main 81ac176. Two conflicts:
- gptqmodel/models/definitions/inkling2_loop.py: import block. Kept the
  PR's replay_records imports; dropped the PR's get_op_name import
  because main removed its last use and the rebased file does not use it.
- tests/module_tree/test_inkling2_loop_plan.py: main added the AWQ
  declaration block where the PR deletes _capture_inkling2_forward.
  Kept all of main's AWQ tests, removed only the helper the PR replaced
  with record-owned head banks.

Tests: 135 passed, 1 skipped on CPU (main baseline for the pre-existing
files: 124 passed).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Qubitium added a commit that referenced this pull request Dec 1, 2026
…d teardown

Rebased fix/6148-issue onto origin/main 94ceaf7 (after #6464, #6465,
#6467, #6469, #6470). Three conflicts:
- gptqmodel/looper/forward_executor.py: import block. Main dropped the
  unused resolve_calibration_keep_mask import; kept only the PR's
  replay_records import.
- gptqmodel/looper/module_looper.py: #6465 moved the failed-run teardown
  into InflightLayerTracker (inflight_layer.py). Kept main's structure and
  re-applied the PR's release_looped_capture() as a ModuleLooper override
  of _release_failed_run_processors that calls super() first.
- gptqmodel/models/definitions/inkling2_loop.py: #6464 reduced
  pre_quantize_generate_hook_start to the batch-index/bank reset plus
  super(); the PR removes that reset, so the override is deleted.

Earlier rebase (onto 81ac176):
Rebased fix/6148-issue onto origin/main 81ac176. Two conflicts:
- gptqmodel/models/definitions/inkling2_loop.py: import block. Kept the
  PR's replay_records imports; dropped the PR's get_op_name import
  because main removed its last use and the rebased file does not use it.
- tests/module_tree/test_inkling2_loop_plan.py: main added the AWQ
  declaration block where the PR deletes _capture_inkling2_forward.
  Kept all of main's AWQ tests, removed only the helper the PR replaced
  with record-owned head banks.

Tests: 135 passed, 1 skipped on CPU (main baseline for the pre-existing
files: 124 passed).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
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