Skip to content

refactor(definitions): declare the vision-input cast instead of per-model move_input_capture_example overrides - #6469

Merged
Qubitium merged 1 commit into
mainfrom
refactor/defs-vision-input-cast
Nov 30, 2026
Merged

Qubitium merged 1 commit into
mainfrom
refactor/defs-vision-input-cast

Conversation

@Qubitium

Copy link
Copy Markdown
Collaborator

Summary

Five definitions overrode move_input_capture_example with the same body. Each called super(), then cast the pixel tensor to the vision tower's dtype on the tower's device. BaseQModel now runs that cast at the same point (right after finalize_input_capture_example), and each definition declares only data:

class DeepSeekVLV2QModel(BaseQModel):
    calibration_vision_module = "vision"            # attribute path under self.model
    calibration_vision_input_keys = ("images",)     # default ("pixel_values",)

This is a behavior-preserving refactor: no change to numerics, checkpoint format or public API. The structural A/B over all 210 MODEL_MAP types shows no differences. The GPU A/B checkpoints (llava-interleave-qwen-0.5b plus a Qwen2.5-0.5B text control) are bit-identical.

git diff --shortstat origin/main: 10 files changed, 127 insertions(+), 82 deletions(-).

  • Under gptqmodel/: 7 files changed, 40 insertions(+), 82 deletions(-) (net −42).
  • The remaining +87 is a 55-line test file, an 11-line guard test and a 21-line docs section.

Scope is deliberately strict. On current main, 18 definitions override move_input_capture_example. Only these 5 use the identical rule:

  • same dtype rule: tower.dtype, else the first parameter's dtype;
  • same device rule: the first parameter's device, else unchanged;
  • same gate: any tensor; the tower is read only when the key holds a tensor;
  • same ordering: after finalize_input_capture_example.

The other 13 are listed under "Kept as-is" with the rule that differs.

What Changed

  • BaseQModel (gptqmodel/models/base.py):
    • New class attributes calibration_vision_module: Optional[str] = None and calibration_vision_input_keys: Tuple[str, ...] = ("pixel_values",).
    • move_input_capture_example now ends with the cast that the five overrides each carried. It runs after finalize_input_capture_example, as before.
    • The attribute is read with getattr(self, ..., None), like calibration_inputs, so test doubles that borrow the unbound method keep working.
  • Converted to a declaration, override deleted (4):
    • deepseek_ocr2: model.vision_tower
    • deepseek_vl: model.vision_model
    • deepseek_vl_v2: vision, key images
    • llava: model.vision_tower
    • llava's extra else: pixel_values.to(device=vision_device) branch was dead code. It runs only when no dtype resolves, which means there is no first parameter, so vision_device is the tensor's own device.
  • Converted, keeps a short override (1):
    • locateanything: vision_model. It keeps its int32 image_grid_hws conversion and places it on pixel_values.device after the base cast.
    • That is the same device the old vision_device held in every branch:
      • cast happened: the tensor is now on vision_device;
      • no first parameter: vision_device was the tensor's own device.
  • ModuleLooper._model_initial_capture_is_generic (gptqmodel/looper/module_looper.py) returns False when a class declares calibration_vision_module.
  • Docs: a short "Vision-input cast at capture" section with a flow diagram in docs/vlm-calibration-input-normalization.md. That page is already linked from README.md.

Kept as-is (a different cast rule; converting would change behavior):

Definition (origin/main) Rule that differs
diffusion_gemma.py:437, inkling.py:116, inkling2_loop.py:398 dtype is the first parameter's dtype (not tower.dtype); casts floating tensors only
zdtaichu5.py:286 casts floating tensors only; a missing vision_model is tolerated (no cast); tower looked up for every row; device falls back to data_device
unlimited_ocr.py:139 next(parameters()) with no default, looked up for every row (text rows included); casts any value present under the key
internvl.py:133 dtype only, no device move
internvl_chat.py:476 dtype only; vision_model.dtype or model.dtype
openvla.py:98 dtype only; first floating parameter of vision_backbone
ovis.py:165 casts list items to visual_tokenizer.dtype inside the generic move, before finalize
lfm2_vl.py:121, minicpm_o.py:202, minicpmv.py:167, minicpmv_4_6.py:219 not a cast: four identical nested_move_to bodies replace the generic move

Follow-ups, not in this PR:

  • The diffusion_gemma, inkling, inkling2_loop and zdtaichu5 overrides would fold into the same declaration if one rule is accepted: "cast floating tensors only, dtype from tower.dtype, else the first parameter". On real towers PreTrainedModel.dtype is the first floating parameter's dtype. The only behavior change would be for a non-floating tensor under a pixel key, which processors never emit.
  • The four identical nested_move_to bodies could become a separate declared flag.

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 (CPU):

  • tests/test_calibration_vision_input_cast.py::test_only_the_converted_definitions_declare_a_vision_tower
    • Scans all of MODEL_MAP.
    • Asserts the declared (module, keys) pairs equal EXPECTED, which is the tower path and key each removed override read on origin/main.
  • tests/test_calibration_vision_input_cast.py::test_declared_tower_casts_its_key_and_text_rows_skip_the_tower[deepseek_ocr2|deepseek_vl|deepseek_vl_v2|llava|locateanything]
    • Each node puts a bf16 tower at the old path.
    • It asserts that only the declared key is cast, with values preserved, and that other keys and non-tensors pass through.
    • It also asserts that a text-only row never resolves the tower (the model has no tower attribute at all).
  • tests/test_gptaq_foem_first_capture_5831.py::test_declared_vision_tower_disables_reuse (CPU, real tiny Qwen2 quantize).
    • Red: with the new guard removed, it fails at assert 6 == (2 * 6), meaning the capture was reused.
    • Green: with the guard, it passes.

Affected-family run: 45 test files, i.e. every test file that references move_input_capture_example, the capture-reuse guard, or a converted definition, plus test_stage_inputs_capture.py and test_mixed_modality_calibration_rows_6355.py. The seven tests/models/*::Test* full-model eval classes are deselected; the GPU A/B below covers end to end.

export PYTHONPATH=$PWD HF_HOME=/root/.cache/huggingface HF_HUB_OFFLINE=1 CUDA_DEVICE_ORDER=PCI_BUS_ID CUDA_VISIBLE_DEVICES=2
python -P -m pytest -o addopts="" -q -rs -p no:cacheprovider -n 8 \
  --deselect models/test_{deepseek_ocr2,deepseek_vl,deepseek_vl_v2,internvl_chat,llava,locateanything,unlimited_ocr}.py::Test* <45 files>
# origin/main 8d52eb918: 2 failed, 1175 passed, 11 skipped
# branch:                2 failed, 1182 passed, 11 skipped   (+7 = the new nodes)
  • The 2 failures happen identically on origin/main and are unrelated:
    • models/test_llava.py::test_llava_model_type_selects_image_text_definition: gptqmodel.models.auto has no AutoConfig.
    • test_unlimited_ocr_support.py::test_unlimited_ocr_prepares_native_image_layout_and_retries: a cpu/cuda index tensor mismatch when a GPU is visible.
  • The 11 skips are the same on both trees and leave these paths unverified:
    • 6 test_calibration_data_device.py cases need at least 2 CUDA devices.
    • 5 test_locateanything_cleanroom_fixtures.py cases are HF greedy-id references recorded for sdpa on non-sliding variants only.
  • The branch was rebased onto 2863a6b after this run. That commit changes only .agents/ and docs.
bash format/check.sh   # ruff 0.14.2: All checks passed!  (temporary no-op pip shim; venv ruff 0.14.2)

Structural A/B 1: every MODEL_MAP definition, synthetic towers, CPU and CUDA

record_cast.py covers all 210 MODEL_MAP types; the unconverted ones act as controls.

  • It calls each class's move_input_capture_example with a stub self.model that has a tower at the path the old override read. Tower variants:
    • plain bf16 nn.Module and plain fp16 nn.Module (no dtype attribute);
    • a PreTrainedModel-like tower whose first parameter is int8 and whose dtype property returns the first floating parameter;
    • a tower with no parameters;
    • no tower at all.
  • Tower on cpu and cuda:0, data_device cpu and cuda:0.
  • 8 rows:
    • fp32 pixel_values/images/pixel_values_local/pixel_values_videos/input_features;
    • int image_grid_thw/video_grid_thw/image_sizes, a list image_grid_hws, bool masks, a 1-D position_ids;
    • lists of tensors, str/None/float values;
    • 1-D pixels, bf16 pixels, uint8/int64/int32 pixel keys, non-tensor pixel values;
    • text-only and 1-D text rows.
  • It records, per output key, the type, dtype, device, shape and values, plus the in-place state of the input dict and any raised exception.
PYTHONPATH=<tree> python -P record_cast.py cast_<tree>.pt        # once on origin/main, once on the branch
python -P compare_cast.py cast_base.pt cast_new.pt
# runs compared: 8640; model types: 210; differing runs: 0
# converted-type runs whose pixel key left fp32/int and came out fp16/bf16 (cast exercised): 36 per converted type
# runs that raised identically on both trees: 356 (missing-tower rows that carry a pixel tensor; ovis/unlimited_ocr controls)

Structural A/B 2: real vendored towers

record_real.py builds each converted model on meta from its repository fixture:

  • native_parity/{llava,deepseek_vl,deepseek_ocr2}.json;
  • deepseek_vl_v2 from tests/test_deepseek_vl_v2_local_port.py::tiny_config;
  • locateanything from the released checkpoint_config.json.

It allocates only the old tower (to_empty, then a bf16 or fp16 cast) on cpu or cuda:0. Then it feeds image, text-only and uint8-pixel rows with data_device cpu or cuda:0. Towers: CLIPVisionModel, SiglipVisionModel, DeepseekOcr2VisionModel, MoonViTPreTrainedModel (all PreTrainedModel), and deepseek_vl_v2's plain-nn.Module VisionTransformer.

runs compared: 120  differing: 0  raised: 0
image/integer rows whose pixel key came out in the tower dtype: 80 of 80

GPU A/B: bit-identical saved checkpoints

Setup:

  • GPU 2 (RTX 5090), CUDA_DEVICE_ORDER=PCI_BUS_ID, trust_remote_code=False.
  • Each case was quantized on origin/main 8d52eb9 and on this branch with an identical config (GPTQConfig(bits=4, group_size=128), FP16), seed and calibration rows.
  • VL rows: 8 deterministic synthetic 224×224 images with fixed captions, given as chat conversations. Text rows: 32 wikitext rows.
  • gptqmodel.__file__ was printed in every log.
  • The comparison checks every saved tensor byte for byte and every other file byte for byte. The exception is quant_log.csv, compared as sorted rows without time.
Case Tensors Other files Result
llava-hf/llava-interleave-qwen-0.5b-hf (LlavaQModel, converted) 1219 7 bit-identical
Qwen/Qwen2.5-0.5B-Instruct (text control) 794 6 bit-identical

On both trees, a probe of the same llava calibration row shows:

  • before the move: pixel_values torch.float32 on cpu, shape (1, 3, 384, 384);
  • after move_input_capture_example, with the tower staged on cuda:0: torch.float16 on cuda:0.

So the declared cast is the one that runs in the GPU A/B.

Measured Impact

Not applicable. This is a behavior-preserving refactor and no issue is claimed. The GPU A/B is bit-identical.

Model Support / Module Plan

Not applicable. No MODEL_MAP entry, module tree, checkpoint ownership or fusion declaration changes. Only the capture-input cast moves from five definitions into BaseQModel data.

Model test node IDs and results: see Tests. tests/models/test_{deepseek_ocr2,deepseek_vl,deepseek_vl_v2,llava,locateanything}.py non-eval nodes passed on both trees, except the pre-existing llava AutoConfig failure.

AWQ onboarding safety

Not applicable. No AWQ grouping, search, replay or fold change. The cast acts only on capture inputs, and AWQ sees the same capture.

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.
flowchart TD
    A["StageInputsCapture / LoopedLayerCaptureMixin"] --> B["BaseQModel.move_input_capture_example"]
    B --> C["move tensors to data_device<br/>unsqueeze 1-D, tensor_kwargs cast"]
    C --> D["finalize_input_capture_example"]
    D --> E{"calibration_vision_module set and<br/>a calibration_vision_input_keys value is a tensor?"}
    E -- no --> H["example unchanged"]
    E -- yes --> F["resolve tower by attribute path<br/>dtype: tower.dtype, else first parameter"]
    F --> G{"dtype resolved?"}
    G -- yes --> I["value.to(first-parameter device<br/>or own device, dtype)"]
    G -- "no: no parameters, no dtype" --> H
    F -.->|"path missing: AttributeError, as before"| X["raise"]
Loading
Decision Before (origin/main 8d52eb9) After
Which key, which tower per-definition override body: deepseek_ocr2.py:120, deepseek_vl.py:88, deepseek_vl_v2.py:204, llava.py:121, locateanything.py:129 calibration_vision_module / calibration_vision_input_keys read in BaseQModel.move_input_capture_example (base.py:4591)
Order vs finalize_input_capture_example super() (which finalizes), then cast finalize (base.py:4589), then cast
dtype / device / gate tower.dtype, else first parameter; first-parameter device, else own device; any tensor; no dtype means no cast identical
Text-only rows tower never read tower never read
GPTAQ/FOEM capture reuse the override made the model non-generic declared tower makes it non-generic (module_looper.py:1838)
LocateAnything image_grid_hws int32 on vision_device int32 on the cast pixel_values.device (same value)

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, packing or dispatch change.

Notes

  • The net change is negative only under gptqmodel/ (−42). With tests and docs it is +45, because the strict same-rule scope converts 5 of the 18 overrides. The follow-up above would fold 4 more, roughly −60 lines, if the floating-only rule is accepted.
  • git merge-tree against the stale refactor/defs-declared-side-modules branch reports a conflict in tests/test_gptaq_foem_first_capture_5831.py. That is only because refactor(definitions): declare calibration side modules instead of per-model hook pairs #6464 was squash-merged and this branch already contains it. Against current origin/main the branch is a fast-forward descendant.

🤖 Generated with Claude Code

…odel move_input_capture_example overrides

Five definitions (deepseek_ocr2, deepseek_vl, deepseek_vl_v2, llava,
locateanything) overrode move_input_capture_example with the same body: call
super(), then, if the pixel key holds a tensor, cast it to the vision tower's
dtype (tower.dtype, falling back to the first parameter's dtype) on the
tower's first-parameter device (unchanged when the tower has no parameters).

BaseQModel now owns that cast, after finalize_input_capture_example exactly
where the overrides ran it, driven by two class attributes:

    calibration_vision_module: Optional[str] = None      # path under self.model
    calibration_vision_input_keys = ("pixel_values",)

The tower is still resolved only when a declared key holds a tensor, so
text-only rows never touch it. LocateAnything keeps a short override for its
int32 image_grid_hws, now placed on the cast pixel_values device (the same
device the old code used). ModuleLooper._model_initial_capture_is_generic
treats a declared tower like an override, so first-capture reuse eligibility
is unchanged.

The other 13 overrides use a different rule (dtype only, first-parameter
dtype with a floating-only gate, eager tower lookup, list items, or nested
moves) and are left as they are.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@Qubitium
Qubitium marked this pull request as ready for review November 30, 2026 02:59
@Qubitium
Qubitium merged commit 94ceaf7 into main Nov 30, 2026
6 checks passed
@Qubitium
Qubitium deleted the refactor/defs-vision-input-cast branch November 30, 2026 02:59
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