Skip to content

fix(looper): capture calibration inputs per parallel branch (#4116) - #4126

Merged
Qubitium merged 2 commits into
mainfrom
fix/issue-4116-branch-calibration
Nov 15, 2026
Merged

Qubitium merged 2 commits into
mainfrom
fix/issue-4116-branch-calibration

Conversation

@Qubitium

Copy link
Copy Markdown
Collaborator

Part of #4116 (item 1)

Root cause

#4111 made module_tree="auto" return one variant per concurrent stack
(model.layers, vision_tower.layers), but the looper still treated the
flattened variants as one sequential stack:

  • gptqmodel/looper/module_looper.py:1872 calls get_layers_with_prefixes(),
    which concatenates every variant's layers into a single list.
  • gptqmodel/looper/stage_inputs_capture.py:155 (first_layer = layers[0])
    hooked only the first TEXT layer and raised StopForward, so no later branch
    ever executed during capture.
  • gptqmodel/looper/stage_layer.py:911 (and the catch-up path at :1293) then
    replayed each layer on the previous layer's output.

Result: vision_tower.layers.0 was calibrated on the text decoder's last
hidden state
, with the text attention mask/position ids. No warning. A real
vision input was never captured. On a width mismatch the run died mid-quantize
with a shape error instead.

Fix

Capture calibration inputs per branch and restart the replay chain at each
branch boundary.

  • gptqmodel/looper/stage_inputs_capture.py
    • _branch_first_layer_indices(layer_names) derives branch boundaries from
      the prefix change in the flattened layer names.
    • Single branch: historical early-stop hook on layers[0] — unchanged.
    • Multi-branch: materialize all decoder layers, register one pre-hook on each
      branch's first layer, run the full calibration forward, capture each
      branch's layer_inputs / attention_masks / position_ids /
      layer_input_kwargs, and stop once all branches are captured.
    • If a branch's first layer is not reached for a batch, raise an actionable
      ValueError naming the branch and batch instead of calibrating it on
      another branch's activations.
  • gptqmodel/looper/stage_layer.py
    • Main replay and catch-up paths check
      InputCache.branch_first_layer_inputs[layer_index] and restore that
      branch's captured inputs/kwargs/position ids/masks at a branch boundary;
      subsequent layers in the branch continue from the branch's own output.
  • gptqmodel/looper/input_cache.py
    • branch_first_layer_inputs field; cleanup() clears branch caches.
  • docs/parallel-module-trees.md
    • Corrected the overclaim; documents per-branch capture/replay, the fail-loud
      contract, cost, and unsupported cases.
  • docs/model-tree-resolution.md
    • Test table row for the new test.
  • tests/module_tree/test_parallel_branch_calibration.py (new)
    • Synthetic 2 text layers + sibling vision_tower.layers with
      self_attn.{q,k,v,o}_proj and mlp.fc1/fc2, 8 calibration rows,
      module_tree="auto"; parametrized over vision_hidden=[896, 512].

Before / after repro

Reporter-style synthetic model: 2 text layers + 2 ViT blocks, 8 calibration
rows, module_tree="auto". pixel_values shape [1,8,16]; vision hidden width
896 vs 512 (text width 896).

Case origin/main @ 4000d2ae5 this branch
VISION_H=896 error: None; vision inputs recorded 24; 24/24 equal a text last-layer output; 12 vision + 14 text modules quantized error: None; vision inputs recorded 32; 0/32 equal a text last-layer output; 12 vision + 14 text modules quantized
VISION_H=512 RuntimeError: mat1 and mat2 shapes cannot be multiplied (6x896 and 512x512); 1 vision input recorded (= text output); 0 vision modules quantized error: None; 0/32 equal a text last-layer output; 12 vision + 14 text modules quantized
calibration omits pixel_values silently calibrates vision on text outputs ValueError: ModuleLooper: the calibration forward never reached the first layer of module-tree branch(es) ['vision_tower.layers.0'] for calibration batch 1. Refusing to calibrate a branch on another branch's activations. ...

Real output, VISION_H=896 (this branch):

error: None
text outputs recorded: 16
vision inputs recorded: 32
vision inputs equal to a text last-layer output: 0/32
quantized vision modules: 12
quantized text modules: 14

Real output, VISION_H=512 (this branch):

error: None
text outputs recorded: 16
vision inputs recorded: 32
vision inputs equal to a text last-layer output: 0/32
quantized vision modules: 12
quantized text modules: 14

Real output, unreachable branch (this branch):

error: ValueError: ModuleLooper: the calibration forward never reached the first layer of module-tree branch(es) ['vision_tower.layers.0'] for calibration batch 1. Refusing to calibrate a branch on another branch's activations. Provide calibration data that exercises every declared branch, or remove the unreachable branch from module_tree.

The new test file fails 3/3 on origin/main and passes 3/3 here.

Per-branch capture and replay

flowchart TD
    G["get_layers_with_prefixes()"] --> B["_branch_first_layer_indices(layer_names)"]
    B --> N{"branch count"}
    N -->|1| OLD["historical path:<br/>hook layers[0], early stop"]
    N -->|N| MAT["materialize every decoder layer"]
    MAT --> H["pre-hook each branch first layer"]
    H --> F["run full calibration forward"]
    F --> C{"all branch first layers captured?"}
    C -->|no| ERR["ValueError:<br/>branch never reached<br/>name branch + batch"]
    C -->|yes| CACHE["InputCache.branch_first_layer_inputs"]
    CACHE --> REPLAY["run_layer_stage()"]
    REPLAY --> R{"layer is a branch first layer?"}
    R -->|yes| RESET["restore branch layer_inputs / kwargs / masks"]
    R -->|no| PREV["use previous layer output"]
    RESET --> Q["quantize branch layers"]
    PREV --> Q
    style ERR fill:#ffa39e,stroke:#a8071a
    style CACHE fill:#d9f7be,stroke:#237804
Loading

No-regression

Single-branch resolution is unchanged. I dumped extract_layers_node,
get_base_modules, simple_layer_modules, full_layer_modules for
LlamaQModel and Qwen2QModel on origin/main and on this branch and diffed
them:

diff main.json branch.json  ->  empty (content identical; only a trailing
newline difference in the raw file, normalized away)

Registered multi-variant trees (HrmTextQModel, MLlamaQModel,
Qwen2_5_OmniGPTQ, Qwen3OmniMoeGPTQ): extract_layers_node +
ModulePlan.from_tree(module_tree).to_dict() diff between main and this branch:

MULTI_DIFF_EMPTY

These are layout alternatives with a single live stack, so they take the
single-stack path and are unaffected.

Tests

# new test alone
PYTHONPATH=$PWD /opt/venvs/cu130t/bin/python -m pytest tests/module_tree/test_parallel_branch_calibration.py -q
-> 3 passed, 1 warning

# focused suite
PYTHONPATH=$PWD /opt/venvs/cu130t/bin/python -m pytest \
  tests/module_tree/test_auto_detect.py \
  tests/module_tree/test_module_tree_variants.py \
  tests/module_tree/test_parallel_branch_calibration.py \
  tests/test_tiny_moe_quant_smoke.py \
  tests/module_tree/test_registered_module_plans.py -q
-> 443 passed, 1 warning

# ROCm
PYTHONPATH=$PWD /opt/venvs/rocm101t/bin/python -m pytest tests/module_tree/test_parallel_branch_calibration.py -q
-> 3 passed, 1 warning

ruff check gptqmodel docs/eora tests setup.py
-> All checks passed!

Pre-existing failure, unrelated and present on origin/main too:
tests/module_tree/test_definition_subset_ordering.py::test_consumer_is_quantized_after_its_producer[minimax-expected4].

Hardware: CPU only. No GPU used.

Unsupported / limits

  • A branch whose first layer the calibration forward never reaches is now a
    hard error. There is no silent fallback and no way to calibrate it without
    calibration data that exercises that branch.
  • Several variants that share one decoder prefix still fall back to the
    historical merged declaration rather than picking an alternative (fix(looper): resolve concurrent module-tree branches (#1998) #4111
    behavior, unchanged).
  • Multi-branch capture gives up the early-stop optimization: all decoder layers
    are materialized and the full forward runs once per calibration batch, so
    peak memory and per-step time are higher for concurrent models.
  • A recurrent branch that invokes its first layer more than once per sample is
    captured once per batch at the first invocation.
  • No new GPTQMODEL_* environment switch.

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