Repository navigation
refactor(definitions): declare calibration side modules instead of per-model hook pairs - #6464
Merged
Merged
Conversation
…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
marked this pull request as ready for review
November 30, 2026 02:29
This was referenced Nov 30, 2026
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]>
This was referenced Nov 30, 2026
Merged
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]>
Merged
12 tasks done
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
Twenty-eight model definitions hand-wrote the same
pre_quantize_generate_hook_start/_endpair. 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_lockshims came along with the pairs.BaseQModelnow owns that pair, and each definition supplies data: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(-). Undergptqmodel/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):calibration_device_modules: Tuple[str, ...] = ().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 thepassstub. For each path it callsshell_module_materialize(module, quantize_config.device, module_path=path)and installs the returned module.pre_quantize_generate_hook_end()replaces thepassstub. For each path it callsoffload_to_disk(model=<immediate parent>, module)(same offload directory names as before) orsetattr(parent, name, move_to(module, CPU)).calibration_device_module_paths():model.or root prefix.normvsfinal_layernorm.get_base_modules.super()wrapper for real per-model work:BaseQModeldirectly to skipLFM3QModel's text-only hooks, as before.position_ids.ttsmove.pre_quantizestaging and uses the base release.Qwen2VLTextQModel/Qwen2_5_VLTextQModelnow resetcalibration_device_module_pathsto 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 declarescalibration_device_modulesor overridescalibration_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/input-capture-cleanup-lifecycle.md. That page is already linked fromdocs/README.md.Kept as-is (out of scope, deliberately):
normalize_device_like(qcfg.device). That pins an index-lessDEVICE.CUDAtocuda: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._resolve_offload_entryduring save.pre_quantize.Follow-ups, not in this PR:
quantize_config.device. This is a placement change.Tests
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).metafrom 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.EXPECTED.EXPECTEDis the release order recorded from the removed hooks onorigin/main.quantize_config.device;offload_to_diskreceives the immediate parent and the same directory name;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).assert 6 == (2 * 6), meaning the capture was reused.Updated tests (they patched the definition-module
offload_to_disk/move_to, used materialize fakes withoutmodule_path, or relied on the removed_turtle_lockshim). Each now patchesgptqmodel.models.base, acceptsmodule_path(and asserts it in the cohere/deepseek cases), or gives its stub_turtle_lock/turtle_model=Noneand annn.Moduletree: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.origin/mainand are unrelated:models/test_cohere_compass.py::test_cohere_compass_model_type_selects_definitionandmodels/test_llava.py::test_llava_model_type_selects_image_text_definition:gptqmodel.models.autohas noAutoConfig.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.gptqmodel[minicpm-o]./monster/data/model/LFM3-*checkpoints.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.pycovers 58MODEL_MAPtypes: every type whose MRO defines either hook or the new attribute or method on either tree. That includes the unconverted ones as controls.offload_to_diskFalse and True, on two shells per type:metafrom its native-parity fixture (29 types);nn.Moduleshell where every path exists (all 58).shell_module_materialize(effective LazyTurtle path and device), eachoffload_to_disk(module, root, directory name), eachmove_to, the per-model extras (capture start/stop, direct parameters,pre_quantize) and any raise.The capture-reuse guard A/B evaluates
ModuleLooper._model_initial_capture_is_generic()for all 210MODEL_MAPentries on both trees. Result: 140 generic on both, 0 differences.GPU A/B: bit-identical saved checkpoints
Setup:
CUDA_DEVICE_ORDER=PCI_BUS_ID,trust_remote_code=False.origin/main1c51b32 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.quant_log.csv, compared as sorted rows withouttime.BaseQwen2VLGPTQ, layout method, start order changed,offload_to_disk=True)LlavaQModeltuple,offload_to_disk=True)LFM2VLQModeltuple,offload_to_disk=False, CPU release)SmolVLM2 could not run here because its required
num2wordspackage 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_MAPentry, alias,module_treeor 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
file:lineevidence.docs/repeats the diagrams, titled for the mechanism, and is linked fromREADME.md(docs/input-capture-cleanup-lifecycle.md, linked fromdocs/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:#fddflowchart 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"]smolvlm.py:58-89,llava.py:91-128,gemma3.py:238-282,base_qwen2_vl.py:141-179,mllama.py:142-177calibration_device_modules/calibration_device_module_paths()shell_module_materialize(module, device), sometimes withmodule_path(llava, lfm3_*, openvla, zdtaichu5, unlimited_ocr)module_path=path(verified equal to the qualified name for all 21 real models)_turtle_lockshimbase_qwen2_vl.py:143,base_qwen3_vl.py:243,mllama.py:147,nemotron_omni.py:88_turtle_lock/turtle_model=Noneoffload_to_disk(model=<parent>, ...)ormove_to(..., CPU)BaseQModel.pre_quantize_generate_hook_end(), same parent and orderbase.py:5312-5316passmodule_looper.py:2009)Failure paths:
AttributeErrorfrom attribute accessAttributeErrorfromget_submodule/getattrtts)calibration_device_module_paths()/ kept in the override)move_toraises; remaining releases skippedReview Requirements
I or an AI agent (such as Codex or Claude) have:
Kernel Accuracy Requirements
Not applicable: no kernel, packer, dispatch or fusion code is touched.
Notes
visualafterembed_tokens/rotary_emb, matching the release order. Each materialization loads a disjoint module, and the Qwen2-VL-2B A/B is bit-identical.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 extrasetattris a no-op there.docs/input-capture-cleanup-lifecycle.mdasks of a definition. A partially materialized module makesmove_to()raise and stops the remaining releases, or is skipped byoffload_to_disk(). The base keeps that behavior, and the doc now says so. Moving ERNIE's_release_moduleinto the base would be a separate behavior-change PR.cuda:0while the other VL definitions stage on the current device of theDEVICEfamily (see What Changed).🤖 Generated with Claude Code