Skip to content

fix(pangu): materialize non-layer replay modules for the last layer (#5135) - #5169

Merged
Qubitium merged 2 commits into
mainfrom
fix/5135-pangu-last-layer-replay
Nov 18, 2026
Merged

Qubitium merged 2 commits into
mainfrom
fix/5135-pangu-last-layer-replay

Conversation

@Qubitium

Copy link
Copy Markdown
Collaborator

Summary

Fixes #5135.

PanguAlphaQModel.prepare_layer_replay_kwargs replays PanGu-α's top-query
block with ln_f applied to the layer input and custom_query = wqe(position_ids).
Both modules live outside the quantized decoder-layer tree, so nothing had
materialized them for the last layer's replay. The hook assumed they were
resident on the layer's device:

  • Default lazy/offload (offload_to_disk=True) leaves ln_f/wqe as meta
    placeholders behind an Accelerate SequentialHook. move_to() did not
    recognize that hook and raised NotImplementedError at the last layer.
  • offload_to_disk=False materializes them on CPU, but replay runs on the
    target device, so wqe(position_ids.to(cuda:0)) indexed a CPU weight and
    raised a device-mismatch RuntimeError.

Every earlier layer was already quantized when the last layer crashed.

Root cause

gptqmodel/models/definitions/pangu_alpha.py:91-125 (pre-fix) had two
residency assumptions:

  1. move_to(norm, device=hidden_states.device) only restores a meta module when
    accelerate.utils.has_offloaded_params() sees a direct AlignDevicesHook.
    The repo's offload_to_disk() installs a SequentialHook, so a legitimately
    offloaded ln_f looked like a bare meta module.
  2. transformer.wqe(position_ids.to(target_device)) never moved wqe; a CPU
    embedding cannot be indexed by a CUDA position_ids.

The existing tests used a fully resident CPU nn.Module double or a tiny
4-layer model whose ln_f payload is below the 4 KiB offload threshold, so they
never reached either state.

Fix

_materialize_replay_module() (gptqmodel/models/definitions/pangu_alpha.py:132)
now places a non-layer module before replay:

  • meta + offload hook (including SequentialHook, via has_cpu_offload_hooks)
    → undo_offload_to_disk() from the repo's offload helpers;
  • meta lazy shell with no hook → the definition's shell_module_materialize();
  • then move_to() for any remaining device relocation.

ln_f is materialized on the hidden-state device and wqe on the resolved
replay_device (target_device, falling back to the hidden/position device).
For a resident model both calls are no-ops, so replay numerics are unchanged.

Before

flowchart TD
    A["ForwardExecutor.run_single<br/>forward_executor.py:457"] --> B["prepare_layer_replay_kwargs<br/>pangu_alpha.py:64"]
    B --> C{"last decoder layer?"}
    C -- no --> D["return cached kwargs"]
    C -- yes --> E["move_to(ln_f, hidden.device)<br/>pangu_alpha.py:101"]
    E --> F{"meta with recognized hook?"}
    F -- no --> G["NotImplementedError<br/>meta tensors without offload hooks"]
    F -- yes --> H["ln_f output"]
    H --> I["wqe(position_ids.to(target_device))<br/>pangu_alpha.py:121"]
    I --> J{"wqe on target_device?"}
    J -- no --> K["RuntimeError<br/>index cuda:0 vs weight cpu"]
    J -- yes --> L["custom_query"]
    style G fill:#ffccc7,stroke:#cf1322
    style K fill:#ffccc7,stroke:#cf1322
Loading

After

flowchart TD
    A["ForwardExecutor.run_single"] --> B["prepare_layer_replay_kwargs"]
    B --> C{"last decoder layer?"}
    C -- no --> D["return cached kwargs"]
    C -- yes --> E["_materialize_replay_module(ln_f, hidden.device)<br/>pangu_alpha.py:95"]
    E --> F{"meta?"}
    F -- no --> H["move_to(ln_f, hidden.device)"]
    F -- yes --> G{"offload hook?"}
    G -- yes --> I["undo_offload_to_disk(ln_f, device)"]
    G -- no --> J{"turtle_model?"}
    J -- yes --> K["shell_module_materialize(ln_f, device)"]
    J -- no --> L["move_to raises clear error"]
    I --> H
    K --> H
    H --> M["ln_f(hidden)"]
    M --> N["_materialize_replay_module(wqe, replay_device)<br/>pangu_alpha.py:128"]
    N --> O["wqe(position_ids.to(replay_device))"]
    O --> P["custom_query on replay_device"]
    style L fill:#ffccc7,stroke:#cf1322
    style P fill:#f6ffed,stroke:#389e0d
Loading

The same diagrams and the failure contracts are in
docs/calibration-replay.md,
linked from README.md.

Evidence

Repro fixture: 2-layer tiny PanGu built from the real
/monster/data/model/pangu_alpha_2_6B config and remote code via
tests/tiny_remote_models.build_tiny_remote_model, hidden_size=1024 so the
final norm exceeds the 4 KiB offload threshold. GPU 0 = RTX 4090.

Before (a978bf1)

Configuration Failure
device="cuda:0", offload_to_disk=True NotImplementedError: Cannot move a module that still contains meta tensors without offload hooks at pangu_alpha.py:101
device="cpu", offload_to_disk=True same NotImplementedError
device="cuda:0", offload_to_disk=False RuntimeError: Expected all tensors to be on the same device, but got index is on cuda:0, different from other tensors on cpu at pangu_alpha.py:121

After

All three configurations complete quantization, save, reload and forward with
finite logits ((1, 32, 128)), and the replayed last-layer values match a
resident HF reference:

Configuration Quantize + save + reload finite logits max abs diff ln_f out max abs diff custom_query
CUDA 0, offload default yes yes 7.153e-07 0.0
CPU, offload default yes yes 0.0 0.0
CUDA 0, offload_to_disk=False yes yes 7.153e-07 0.0

The CUDA ln_f difference is float32 CPU-vs-GPU rounding. On the resident CPU
fixture the new hook output equals the pre-fix values exactly (torch.equal).
The q_proj diff vs resident FP (~6.9e-4) is ordinary 4-bit quantization
error, not replay input drift.

Red / green tests

New regressions fail on a978bf18c and pass after:

FAILED test_last_layer_replay_materializes_disk_offloaded_modules   NotImplementedError
FAILED test_last_layer_replay_materializes_lazy_shell               NotImplementedError
FAILED test_last_layer_replay_moves_wqe_to_target_device            RuntimeError device mismatch
FAILED test_pangu_2_layer_quantize_completes[cpu-offload]           NotImplementedError
FAILED test_pangu_2_layer_quantize_completes[cuda-offload]          NotImplementedError
FAILED test_pangu_2_layer_quantize_completes[cuda-resident]         RuntimeError device mismatch

After:

tests/test_pangu_alpha_replay.py ................ 11 passed
tests/test_offload_base_modules_restored.py \
tests/test_offload_files.py \
tests/test_lazy_turtle_materialize_map.py ....... 95 passed

CPU-only collection (CUDA_VISIBLE_DEVICES=) is 7 passed, 3 skipped; the
CUDA-only regressions skip with an explicit reason.

Test plan

cd /root/work/issue-5135
CUDA_VISIBLE_DEVICES=0 PYTHONPATH=$PWD HF_HUB_OFFLINE=1 \
  /root/venv/bin/python -m pytest tests/test_pangu_alpha_replay.py -q
CUDA_VISIBLE_DEVICES=0 PYTHONPATH=$PWD HF_HUB_OFFLINE=1 \
  /root/venv/bin/python -m pytest \
    tests/test_offload_base_modules_restored.py \
    tests/test_offload_files.py \
    tests/test_lazy_turtle_materialize_map.py -q
ruff check gptqmodel/models/definitions/pangu_alpha.py tests/test_pangu_alpha_replay.py

Scope / unverified

  • Verified on the tiny 2-layer PanGu fixture built from the real checkpoint's
    config and remote code, not a full 32-layer 2.6B run (the 10.5 GB checkpoint
    is present locally but a full GPTQ pass is outside this task's budget). The
    hook-level tests are independent of checkpoint size.
  • tests/test_docs_contract_refs.py has 7 pre-existing failures on
    a978bf18c in unrelated docs (gguf-config-resolution.md,
    rocm-default-environment.md, generate-cpu-offload-autograd.md); verified
    against a clean HEAD worktree. Our docs/README edits add no new failures.

…5135)

prepare_layer_replay_kwargs replayed ln_f and wqe as if they were resident on the layer device. Under the default lazy/offload load ln_f/wqe are meta placeholders behind an Accelerate SequentialHook, and with offload_to_disk=False wqe stays on CPU while position_ids moves to the target. The last decoder layer therefore always failed after the rest of the model was quantized.

Restore each non-layer module through the looper's helpers (undo_offload_to_disk for offload hooks, shell_module_materialize for lazy shells) before move_to, and place wqe on the replay device before the embedding lookup. Resident models keep the previous code path, so replay numerics are unchanged.

Adds hook-level regressions for the offloaded, lazy-shell and cross-device cases plus an end-to-end 2-layer PanGu quantize/reload test for CPU-offload, CUDA-offload and CUDA-resident configurations.
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