Skip to content

[BUG] Calibration replay uses another layer's mask/kwargs: sequential TT block-float GPTQ reuses block 0 context (#4009), parallel-branch calibration restores branch context only at first layer (#4126) #4150

Closed

Description

@devin-ai-integration

Summary

Two in-window changes replay a decoder layer with a mask / position / kwargs context that belongs to a different layer. The code paths and fixes are separate, but the bug class and the missing test are the same: each layer must replay with its own context.

A. Sequential TT block-float GPTQ reuses block 0's mask and RoPE kwargs for every layer

  • Commit d62dfae (feat(tt-blockfloat): sequential block-by-block GPTQ calibration #4009). Code:
    # backbone passes alongside (rotary embeddings, masks, cache positions) --
    # by stopping the forward at its entry. Those side inputs do not depend on
    # the weights being quantized, so they are reused for every block.
    captured = []
    def _capture(_module, args, kwargs):
    captured.append((args, kwargs))
    raise _StopForward
    backbone = getattr(model, "model", None)
    runner = backbone if isinstance(backbone, nn.Module) and type(backbone).forward is not nn.Module.forward else model
    handle = blocks[0].register_forward_pre_hook(_capture, with_kwargs=True)
    model.eval()
    try:
    with torch.no_grad():
    for window in windows:
    try:
    runner(window)
    except _StopForward:
    # Expected: pre-hook raises this to stop forward once inputs are captured.
    continue
    finally:
    handle.remove()
    if len(captured) != len(windows):
    raise RuntimeError("failed to capture the first decoder block's inputs")
    hidden = [args[0] for args, _ in captured]
    extras = [(args[1:], {k: v for k, v in kwargs.items() if k not in ("hidden_states", "past_key_values", "past_key_value", "use_cache")}) for args, kwargs in captured]
    def _run(block, index):
    args, kwargs = extras[index]
    out = block(hidden[index], *args, use_cache=False, **kwargs)
    return out[0] if isinstance(out, tuple) else out
  • Trigger: quantize_model_blockfloat(sequential=True) / scripts/tt_quantize_blockfloat.py --sequential on a hybrid-attention model (sliding + full layers, e.g. Gemma2/3).
  • Expected: each layer gets its own causal_mask_mapping[attention_type] and RoPE.
  • Actual: _quantize_sequential hooks only blocks[0] and replays those kwargs (attention_mask, position_embeddings, position_ids, cache_position) through every block.
  • Impact: Hessians and propagated hidden states come from attention the deployed model never computes. Accuracy drops with no error. Pure full-attention models are not affected.
  • Evidence (tiny random Gemma2, layer_types=[sliding_attention, full_attention], sliding_window=4, seqlen 16):
layer 0 (sliding_attention): sequential mask == native mask: True
layer 1 (full_attention): sequential mask == native mask: False; == layer0 native mask: True
  • Fix: capture kwargs per block or per attention_type, or reject sequential=True when layer types differ. Add a two-layer-type toy test.

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

  • Commit f385a94 (fix(looper): capture calibration inputs per parallel branch (#4116) #4126, for [BUG] Follow-up on #4111/#4102: concurrent module-tree branches calibrated on the text decoder's output (vision tower silently mis-quantized / crash), CPU BF16x3 matmul guard still un-refcounted #4116). Code:
    branch_caches = getattr(cache, "branch_first_layer_inputs", None)
    branch_cache = branch_caches.get(layer_index) if branch_caches else None
    if branch_cache is not None:
    layer_inputs = branch_cache.layer_inputs
    layer_input_kwargs = branch_cache.layer_input_kwargs
    position_ids = branch_cache.position_ids
    attention_masks = branch_cache.attention_masks
    else:
    layer_inputs = cache.layer_inputs
    layer_input_kwargs = cache.layer_input_kwargs
    position_ids = cache.position_ids
    attention_masks = cache.attention_masks
    looper._prepare_layer_direct_state_for_forward(
    module,
    cur_layer_device,
    projection_modules=full,
    )
    # Recovery must use the same forward topology as the original
    # capture. In particular, DeepSeek's router can make different
    # low-bit decisions when a batch that was originally split over
    # two GPUs is replayed serially on one GPU. Let ForwardExecutor
    # honor the run's immutable auto-forward-data-parallel policy.
    layer_outputs = _replay_layer_outputs(
    looper,
    module=module,
    processor=processor,
    layer_inputs=layer_inputs,
    layer_input_kwargs=layer_input_kwargs,
    position_ids=position_ids,
    attention_masks=attention_masks,
    cur_layer_device=cur_layer_device,
    is_lm_head_module=False,
    shared_kv_cache_dict=shared_kv_cache_dict,
    layer_index=layer_index,
    layer_descriptor=layer_descriptor,
    full=full,
    log=log,
    region_timer=region_timer,
    replay_plan=None,
    force_serial=False,
    )
    if not layer_outputs:
    raise RuntimeError(
    f"packed catch-up produced no output for layer {layer_index}"
    )
    output_requirement = getattr(
    looper.gptq_model, "quantization_layer_output_required", None
    )
    if callable(output_requirement) and output_requirement(
    layer_index=layer_index,
    layer_name=layer_name,
    layer_count=layer_count,
    ):
    output_receiver = getattr(
    looper.gptq_model,
    "receive_quantization_layer_outputs",
    None,
    )
    if not callable(output_receiver):
    raise RuntimeError(
    "model requested quantization layer outputs without a receiver"
    )
    output_receiver(
    layer_index=layer_index,
    layer_name=layer_name,
    layer_outputs=layer_outputs,
    layer_input_kwargs=layer_input_kwargs,
    position_ids=position_ids,
    attention_masks=attention_masks,
    )
    # Native source state was materialized only to execute this one
    # recovery forward. Rehome the complete materialized layer before
    # packed leaves become disk-backed META shells again. The generic
    # ``post_quantize`` path is intentionally skipped: it is for float
    # layers and rejects valid disk-offloaded EXL3 buffers.
    module.to(device=CPU)
    finalize_catchup = getattr(
    layer_boundary_checkpoint, "finalize_catchup_layer", None
    )
    if not callable(finalize_catchup):
    raise TypeError(
    "quantization layer-boundary catch-up has no "
    "finalize_catchup_layer() method"
    )
    finalize_catchup(
    model=looper.gptq_model,
    processor=processor,
    layer_index=layer_index,
    )
    layers[layer_index] = module
    processor.clear_cache_data()
    processor.receive_layer_inputs(layer_outputs)
    torch_sync()
    looper._emit_layer_complete(
    layer_idx=layer_index,
    submodule_finalized=False,
    raise_in_place=True,
    )
    looper._emit_layer_complete(
    layer_idx=layer_index,
    submodule_finalized=True,
    raise_in_place=True,
    )
    commit_boundary = getattr(
    layer_boundary_checkpoint, "commit_layer", None
    )
    if not callable(commit_boundary):
    raise TypeError(
    "quantization layer-boundary checkpoint has no commit_layer() method"
    )
    commit_boundary(
    model=looper.gptq_model,
    processor=processor,
    layer_index=layer_index,
    layer_name=layer_descriptor,
    )
    if durable_progress_logs:
    log.info(
    "StageLayer: packed catch-up boundary committed for layer=%s",
    layer_index,
    )
    continue
    for p_index, processor in enumerate(looper.processors):
    if looper.gptq_model.quantize_config.activation_mode in {"w4afp8", "w4a_nvfp4"}:
    from ..nn_modules.qlinear.w4a_llama_replay import set_w4a_replay_enabled
    from .native_processor import NativeProcessor
    set_w4a_replay_enabled(module, not isinstance(processor, NativeProcessor))
    # Each processor contributes a quantization phase; walk them in
    # order so their caches and side effects line up with the pipeline.
    processor.log_call_count = 0 # reset
    processor.collect_memory_info(layer_index)
    # Read the replay policy once per processor so the layer stage uses
    # one forward config instead of a group of unrelated flags.
    forward = processor.forward
    branch_caches = getattr(
    processor.inputs_cache, "branch_first_layer_inputs", None
    )
    branch_cache = (
    branch_caches.get(layer_index)
    if branch_caches and not is_embeddings_module and not is_lm_head_module
    else None
    )
    if branch_cache is not None:
    # Concurrent module-tree branches restart from their own
    # captured first-layer inputs instead of the previous branch's
    # final hidden state.
    layer_inputs = branch_cache.layer_inputs
    layer_input_kwargs = branch_cache.layer_input_kwargs
    position_ids = branch_cache.position_ids
    attention_masks = branch_cache.attention_masks
    else:
    if is_input_embeddings_module:
    layer_inputs = processor.inputs_cache.src_inputs
    else:
    layer_inputs = processor.inputs_cache.layer_inputs
    layer_input_kwargs = processor.inputs_cache.layer_input_kwargs
    position_ids = processor.inputs_cache.position_ids
    attention_masks = processor.inputs_cache.attention_masks
  • Trigger: quantize(module_tree="auto") on a model with concurrent stacks (text decoder + vision/audio tower).
  • Expected: every layer of branch N replays with branch N's kwargs, masks and positions (as docs/parallel-module-trees.md implies).
  • Actual: run_layer_stage swaps in branch_first_layer_inputs only when layer_index is a branch's first layer. Later layers read the top-level inputs_cache fields, which still hold the first branch's values (receive_layer_inputs only updates layer_inputs).
  • Impact: a shape error, or silently wrong activations feeding GPTQ Hessians and AWQ search for encoder layers. The existing test's _VisionBlock ignores kwargs, so this is not covered.
  • Evidence (repo fixture tests/module_tree/test_parallel_branch_calibration.py, vision layers changed to take cu_seqlens and no attention_mask):
vision_tower.layers.0: kwarg key-sets seen -> {('cu_seqlens', 'use_cache'): 24}
vision_tower.layers.1: kwarg key-sets seen -> {('attention_mask', 'use_cache'): 16}
   sample: {'attention_mask': (1, 5), 'use_cache': False}
  • Fix: resolve the branch that owns layer_index (largest branch-first index <= layer_index) and use that branch's cache for every layer in it. Add a test that asserts on branch layers past index 0.

Validation limits

CPU-only, GIL enabled, torch 2.13.0 CPU, transformers 5.20.2, tiny random models. The wrong replay context was observed directly; perplexity/eval impact on real checkpoints was not measured.

Related (not runtime-validated): AWQ token-row replay (#4131, awq_processor.py L1530-L1615) appears to read an all-zero additive [B,1,S,S] mask as fully masked and fall back to a causal structure.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions