Skip to content

fix(quantize): replay each layer with its own calibration context (#4150) - #4153

Merged
Qubitium merged 3 commits into
mainfrom
fix/issue-4150-replay-context
Nov 15, 2026
Merged

Qubitium merged 3 commits into
mainfrom
fix/issue-4150-replay-context

Conversation

@Qubitium

@Qubitium Qubitium commented Nov 15, 2026 •

Copy link
Copy Markdown
Collaborator

Fixes #4150

TL;DR

Two calibration replay paths gave a layer a sibling layer's mask/kwargs. Sequential TT block-float GPTQ replayed block 0's attention_mask/rotary/positions through every block (hybrid attention); parallel-branch calibration restored a branch's cache only at its first layer, so later layers used the first branch's kwargs. Both now replay every layer with the context of the block/branch that owns it. 6 files changed (one new test file); single-stack and pure full-attention behavior is unchanged.

1. The problem

A. Sequential TT block-float GPTQ reused block 0's context

_quantize_sequential (gptqmodel/utils/tt_blockfloat_quant.py:919, from #4009) pre-hooked only blocks[0], captured (args, kwargs), and then replayed that same kwargs through every block:

handle = blocks[0].register_forward_pre_hook(_capture, with_kwargs=True)
...
extras = [(args[1:], {...}) for args, kwargs in captured]

transformers 5 builds one causal mask per attention_type and passes causal_mask_mapping[config.layer_types[i]] to each layer. Capturing only layer 0 therefore gave every full-attention layer the sliding-window mask (and vice versa), with no error. Pure full-attention models were unaffected because every layer receives the same mask.

Observed on a tiny random Gemma2 (layer_types=[sliding_attention, full_attention], sliding_window=4, seqlen 16), parent commit:

layer 0 (sliding_attention): sequential mask == native mask: True
layer 1 (full_attention):    sequential mask == native mask: False; == layer0 native mask: True

B. Parallel-branch calibration restored context only at the branch's first layer

run_layer_stage (gptqmodel/looper/stage_layer.py:954, from #4126) looked up branch_first_layer_inputs only when layer_index was exactly a branch's first layer:

branch_cache = branch_caches.get(layer_index) if branch_caches else None

receive_layer_inputs() refreshes only the top-level layer_inputs; layer_input_kwargs, position_ids and attention_masks stay at the first branch's values. Later layers of a branch therefore replayed with the text decoder's attention_mask instead of the vision tower's cu_seqlens. The existing _VisionBlock ignored kwargs, so this shipped.

Observed on the repo fixture (tests/module_tree/test_parallel_branch_calibration.py), parent commit:

vision_tower.layers.0: kwarg key-sets seen -> {('cu_seqlens', 'use_cache'): ...}
vision_tower.layers.1: kwarg key-sets seen -> {('attention_mask', 'use_cache'): ...}
   sample: {'attention_mask': tensor([[1, 1, 1, 1, 1]]), 'use_cache': False}

2. The new flow

A. Capture every block's side inputs, replay each block with its own

_quantize_sequential now pre-hooks every decoder block, stops at the last block, and keeps only the side inputs per block (gptqmodel/utils/tt_blockfloat_quant.py:950-999). Hidden states are propagated exactly as before: block 0's input is the only hidden tensor captured, and each quantized block's output becomes the next block's input. Shared tensors (mask, rotary tuple) are stored as references, not copied.

flowchart TD
    W["calibration window"] --> F["dense backbone forward"]
    F --> H["pre-hook on every decoder block"]
    H --> C["captured extras i<br/>mask / rotary / position ids"]
    C --> L{"last block reached?"}
    L -->|no| F
    L -->|yes| STOP["raise _StopForward"]
    STOP --> Q["quantize block i"]
    Q --> R["replay block i with captured extras i<br/>hidden = previous quantized output"]
    R --> N{"more blocks?"}
    N -->|yes| Q
    N -->|no| DONE["report"]
    style STOP fill:#fff1b8,stroke:#ad8b00
    style R fill:#d9f7be,stroke:#237804
Loading

B. Resolve the branch that owns each layer

_branch_replay_cache() (gptqmodel/looper/stage_layer.py:79) returns the cache for the branch with the largest first-layer index at or before model_layer_index. Every layer of that branch takes its layer_input_kwargs, position_ids and attention_masks; only the branch's first layer restarts from the branch's captured layer_inputs, and later layers keep consuming the previous layer's output. Both the main replay path (stage_layer.py:958) and the packed catch-up path (stage_layer.py:808) use it.

flowchart TD
    L["run_layer_stage<br/>flat layer_index"] --> OWN["_branch_replay_cache()<br/>largest branch-first index at or before layer_index"]
    OWN --> HAS{"branch cache?"}
    HAS -->|no| TOP["historical single-stack cache<br/>layer_inputs / kwargs / masks"]
    HAS -->|yes| FIRST{"layer_index equals<br/>the branch-first index?"}
    FIRST -->|yes| RESET["layer_inputs = branch captured inputs<br/>kwargs / masks / positions = branch cache"]
    FIRST -->|no| CONT["layer_inputs = previous layer output<br/>kwargs / masks / positions = branch cache"]
    TOP --> Q["replay the layer and collect Hessians"]
    RESET --> Q
    CONT --> Q
    style HAS fill:#fff1b8,stroke:#ad8b00
    style RESET fill:#d9f7be,stroke:#237804
    style CONT fill:#d9f7be,stroke:#237804
Loading

Committed reference pages: docs/parallel-module-trees.md (per-layer branch replay context) and hw/tenstorrent.md (sequential calibration context).

3. Failure and ambiguity contract

Situation Before After
Hybrid attention, sequential=True Every block replayed block 0's mask/rotary. Each block replays its own captured kwargs.
Parallel branches, layer after the first Top-level cache (first branch) supplied kwargs/masks/positions. Owning branch's cache supplies them.
Parallel branches, branch's first layer Branch cache supplied inputs and context. Unchanged.
Single-stack model Top-level cache. Unchanged: no branch map, helper returns no branch.
Pure full-attention model, sequential=True One shared mask for every block. Every block captures the same shared mask; report is bit-identical.

4. Change inventory

Area File Purpose
TT block-float sequential GPTQ gptqmodel/utils/tt_blockfloat_quant.py Per-block capture/replay of side inputs; hidden states still propagate.
Looper branch replay gptqmodel/looper/stage_layer.py _branch_replay_cache(); use owning branch's context for every layer and in catch-up.
Regression tests tests/test_tt_blockfloat_sequential.py (new), tests/module_tree/test_parallel_branch_calibration.py Hybrid two-type mask test; branch layer-1 kwargs test; single-branch and resolver tests.
Docs docs/parallel-module-trees.md, hw/tenstorrent.md Mermaid flow and before/after contract.

5. Tests / guarantees

Test Invariant it pins
tests/test_tt_blockfloat_sequential.py::test_sequential_replay_uses_each_hybrid_layer_mask Layer 1 (full_attention) replays its native mask, not layer 0's sliding mask. Fails on parent.
tests/test_tt_blockfloat_sequential.py::test_sequential_replay_full_attention_context_unchanged Pure full-attention: every replay mask equals the one shared native mask. Passes before and after.
tests/test_tt_blockfloat_sequential.py::test_sequential_replay_uses_each_layer_position_embeddings Layer 1 replays its own per-layer position_embeddings (RoPE), not layer 0's. Fails on parent.
tests/module_tree/test_parallel_branch_calibration.py::test_parallel_branch_replays_each_layer_with_its_own_kwargs vision_tower.layers.1 (index > 0) receives cu_seqlens and no text attention_mask. Fails on parent.
tests/module_tree/test_parallel_branch_calibration.py::test_branch_replay_cache_resolves_the_owning_branch Ownership rule, including no-branch and branch-gap cases.
tests/module_tree/test_parallel_branch_calibration.py::test_single_branch_replay_context_is_unchanged Single-stack path still replays the top-level mask. Passes on parent and after.

6. Validation

All runs are CPU-only (no GPU used). Commands run from the clone root with PYTHONPATH=$PWD.

Part A, fail-before (parent d62bc9afb):

CUDA_VISIBLE_DEVICES="" /opt/venvs/cu130t/bin/python -m pytest tests/test_tt_blockfloat_sequential.py -q
# 2 failed, 1 passed
# FAILED test_sequential_replay_uses_each_hybrid_layer_mask
#   assert torch.equal(mask, native[1]) -> False
# FAILED test_sequential_replay_uses_each_layer_position_embeddings
#   assert torch.equal(embeddings, native[1]) -> False

Part A, pass-after:

CUDA_VISIBLE_DEVICES="" /opt/venvs/cu130t/bin/python -m pytest tests/test_tt_blockfloat_sequential.py -q
# 3 passed

Part B, fail-before (parent d62bc9afb):

CUDA_VISIBLE_DEVICES="" /opt/venvs/cu130t/bin/python -m pytest \
  tests/module_tree/test_parallel_branch_calibration.py::test_parallel_branch_replays_each_layer_with_its_own_kwargs -q
# 1 failed
# assert 'cu_seqlens' in {'attention_mask': tensor([[1, 1, 1, 1, 1]]), 'use_cache': False}

Part B, pass-after:

CUDA_VISIBLE_DEVICES="" /opt/venvs/cu130t/bin/python -m pytest \
  tests/module_tree/test_parallel_branch_calibration.py -q
# 6 passed

Related suites after merging origin/main (git merge --no-edit origin/main: already up to date):

CUDA_VISIBLE_DEVICES="" /opt/venvs/cu130t/bin/python -m pytest \
  tests/test_tt_blockfloat_sequential.py tests/test_tt_blockfloat_out_axis.py tests/test_tt_blockfloat_precision.py -q
# 28 passed, 4 skipped

CUDA_VISIBLE_DEVICES="" /opt/venvs/cu130t/bin/python -m pytest \
  tests/module_tree/test_parallel_branch_calibration.py tests/module_tree/test_auto_detect.py tests/module_tree/test_module_tree_variants.py -q
# 26 passed

ROCm venv (CPU execution, HIP_VISIBLE_DEVICES=1):

HIP_VISIBLE_DEVICES=1 /opt/venvs/rocm101t/bin/python -m pytest tests/test_tt_blockfloat_sequential.py -q
# 3 passed

HIP_VISIBLE_DEVICES=1 /opt/venvs/rocm101t/bin/python -m pytest tests/module_tree/test_parallel_branch_calibration.py -q
# 6 passed

Common decoder path sanity: a tiny random Llama (2 layers, sequential=True) also quantizes cleanly; both layers captured and replayed their own attention_mask, position_embeddings and position_ids (report has 14 entries).

Full-attention no-regression (numerical): ran quantize_model_blockfloat(sequential=True) on the same tiny full-attention Gemma2 on parent and on this branch and diffed the reports. diff reported no difference (FULL_ATTENTION_REPORTS_IDENTICAL), i.e. every norm_l1/bits/on_grid entry is identical.

Lint:

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

7. Cross-reference (not fixed here): AWQ token-row replay and all-zero additive masks

gptqmodel/looper/awq_processor.py:1521 classifies an additive mask as:

allowed_grid = (m >= 0) if bool((m < 0).any()) else (m > 0)

An all-zero additive [B, 1, S, S] mask (0 = allowed, no negatives) takes the (m > 0) branch, which marks every position masked. _token_row_source_structure() then returns None (flat_keep.sum() != row_count) and _token_row_replay_kwargs() falls back to a causal structure. That looks like a real bug for all-zero additive masks, but this file is owned by another worker in this batch, so it is only reported here.

8. Reviewer notes / limitations

  • Part A's capture forward now executes the dense model through every block except the last (previously it stopped before block 0). Only side inputs are retained, not per-block hidden states, but capture peak memory is closer to the default non-sequential path than to the old block-0-only stop. This is the cost of per-block correctness; a per-attention_type capture could reduce it if a model ever needs it.
  • Per-block capture assumes a block's mask/rotary/position side inputs do not depend on its weights; they are derived from the calibration inputs and the model's mask/rotary builders.
  • As in the issue, perplexity/eval impact on real checkpoints was not measured; validation is tiny random models plus the repo fixture.

)

Two replay paths reused a sibling layer's mask/kwargs:

- Sequential TT block-float GPTQ pre-hooked only blocks[0] and replayed its
  attention_mask/position_embeddings/position_ids/cache_position through every
  block. On hybrid-attention models (Gemma2/3) a full-attention layer then
  calibrated on the sliding-window mask. Capture every block's side inputs from
  one dense forward and replay each block with its own; hidden states still
  propagate through the quantized blocks.

- Parallel-branch calibration restored branch_first_layer_inputs only at a
  branch's first layer. Later layers read the top-level cache, which still held
  the first branch's kwargs, so e.g. vision_tower.layers.1 got the text
  decoder's attention_mask instead of its own cu_seqlens. Resolve the branch
  that owns layer_index (largest branch-first index <= layer_index) and take
  that branch's kwargs/masks/positions for every layer in it; only the first
  layer restarts from the branch's captured inputs.

Tests assert on branch layer 1 (not just layer 0) and on a hybrid two-type
model; single-stack and pure full-attention behavior is unchanged.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

1 participant