Skip to content

fix(awq): run a stateless rotary on the replay device - #6634

Merged
Qubitium merged 1 commit into
mainfrom
fix/phi4mm-awq-cuda-rotary
Dec 1, 2026
Merged

Qubitium merged 1 commit into
mainfrom
fix/phi4mm-awq-cuda-rotary

Conversation

@Qubitium

@Qubitium Qubitium commented Dec 1, 2026

Copy link
Copy Markdown
Collaborator

Summary

phi4mm (Phi-4-multimodal) AWQ quantization on CUDA crashes in the scale-search replay:

File "gptqmodel/looper/awq_processor.py", line 6851, in _invoke_replay_module
File "gptqmodel/models/ports/native/phi4_multimodal/modeling_phi4_multimodal.py", line 1216, in apply_rotary_pos_emb
RuntimeError: Expected all tensors to be on the same device, but found at least two devices, cuda:0 and cpu!

Root cause. _prepare_module_forward (and _refresh_forward_kwargs_from_cache) rebuild position_embeddings
with the root rotary and first move the replay input to the device _get_rotary_device reports. phi4mm's port rotary
(gptqmodel/models/ports/phi4/modeling_phi4.py:19 RotaryEmbedding) is stateless: no parameters, no buffers; it
derives its LongRoPE frequencies from the input on every call. _get_rotary_device fell through to
utils.device.get_device, which returns CPU for a module without tensors. The CUDA activation was copied to the CPU,
cos/sin were built there, and the CUDA attention received CPU embeddings.

The rotary is found correctly (model.rotary_emb). Declaring rotary_embedding on the definition, or moving the rotary as a
calibration side module, would not help: it owns no tensor to move. The bug is in how the shared replay helper reads
the device of a module that has none.

What Changed

  • AWQProcessor._get_rotary_device: a rotary with no parameters or buffers now returns the caller's fallback (the
    replayed module's device or the input's device) instead of CPU. ParoQuant's copy of this helper
    (paro_processor.py:1128) already returns the fallback. Rotaries with inv_freq or any other tensor resolve exactly as before.
  • AWQProcessor._get_rotary_for_device: passes the target device as that fallback, so a stateless rotary is used
    as-is. It is no longer deep-copied into the per-device cache.
  • No API or config change.
  • Out of scope, filed separately: DeepSeek-VL2 is the only other MODEL_MAP family with a stateless decoder root rotary
    (ports/deepseek_vl_v2/modeling_deepseek.py:72). Its AWQ replay crashes earlier on every device because the replay
    calls its rotary without the required seq_len: AWQ: DeepSeek-VL2 scale-search replay crashes (root rotary called without required seq_len) #6631. Once that is fixed, this change also keeps its CUDA replay
    on the device.

Stateless rotary scan (AST over gptqmodel/models/ports and transformers/models, nn.Module-based rotary classes with
no register_buffer/Buffer(/Parameter(/inv_freq): ports/phi4 RotaryEmbedding (root, fixed here),
ports/deepseek_vl_v2 DeepseekV2RotaryEmbedding (root, #6631), ports/telechat2 RotaryEmbedding (per-attention,
and the attention takes no position_embeddings, so the replay never rebuilds with it). No Transformers class matched.

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 regressions in tests/test_awq_rotary_device.py (CPU, meta stands in for the accelerator as in the existing tests
there; copying a meta tensor to the CPU raises, so the CPU move is visible without a GPU):

  • test_module_forward_runs_a_stateless_rotary_on_the_module_device: the scale-search replay path.
  • test_refresh_forward_kwargs_runs_a_stateless_rotary_on_the_input_device: the cached-kwargs refresh path.
# origin/main (4f3ba227a) with the new tests: red for the intended reason (the replay input is copied to the CPU)
CUDA_VISIBLE_DEVICES= python -P -m pytest -q tests/test_awq_rotary_device.py
# awq_processor.py:6580 / :4480  NotImplementedError: Cannot copy out of meta tensor; no data!
# FAILED tests/test_awq_rotary_device.py::test_module_forward_runs_a_stateless_rotary_on_the_module_device
# FAILED tests/test_awq_rotary_device.py::test_refresh_forward_kwargs_runs_a_stateless_rotary_on_the_input_device
# 2 failed, 8 passed

# this branch
CUDA_VISIBLE_DEVICES= python -P -m pytest -q tests/test_awq_rotary_device.py
# 10 passed

# existing tests covering the touched replay/rotary code and phi4mm
python -P -m pytest -q tests/test_awq_rotary_device.py tests/test_awq_position_kwargs.py \
  tests/test_awq_vl_rotary_resolution.py tests/test_awq_mimo_v2_rotary_selection.py \
  tests/test_awq_deepseek_v4_rotary_4695.py tests/test_hymba_awq_4891.py tests/test_awq_laguna_rotary_label_4874.py \
  tests/test_awq_shared_indexer_replay.py tests/test_awq_deepseek_v4_hash_moe_4880.py tests/test_awq_moe_bypass_4223.py \
  tests/test_awq_weight_mean.py tests/test_phi4_local_port.py
# CPU only (CUDA hidden): 215 passed, 27 skipped (all CUDA-parametrized cases), 1 failed
# GPU (one CUDA device visible): 242 passed, 1 skipped (test_awq_weight_mean_matches_legacy_impl_6_cuda0_cuda1_gs128 needs 2 GPUs)

The one failure, tests/test_awq_weight_mean.py::test_awq_pseudo_quantize_nan_guard_uses_one_host_read
(assert 4 == 1 scalar reads), fails the same way on origin/main when CUDA is hidden and passes with a GPU visible.
It is unrelated to this change (pseudo-quantize NaN guard, not the rotary path).

bash format/check.sh: All checks passed!

Measured Impact

Run (GPU A/B on one CUDA device, AWQ 4-bit, fixed seed/calibration) origin/main this PR
Qwen2.5-0.5B-Instruct, group 128, 64 wikitext rows completes completes, bit-identical to main (626 tensors + config/quant_log)
tiny phi4mm (2 layers, seeded, perturbed norms), group 16, 8 text/image/audio rows, CUDA RuntimeError cuda:0 vs cpu in apply_rotary_pos_emb completes (2 layers, 8 modules quantized, peak 46 MiB)
same tiny phi4mm, CPU completes completes, bit-identical to main (211 tensors + config/quant_log)

Model Support / Module Plan

Not applicable: no definition, alias, module tree or fusion change.

Model test node IDs and results (or "not applicable"): not applicable. tests/test_phi4_local_port.py ran in the suite above.

AWQ onboarding safety

  • Native forward evidence identifies each source, all quantized and
    non-quantized consumers, intervening operations, and complete replay scope.
  • Real-model neutral-fold and candidate-search tests cover applicable
    layouts/configs, shared branches/routers, and nontrivial scales; passing
    module-plan or width checks alone is not AWQ qualification.
  • Native context/chunk parity, failure rollback, and configured fallback/error
    behavior are tested where applicable; no-group modes still quantize all linears.
  • Each variant is AWQ-scaling qualified, tested plain-quantization-only, or
    explicitly unsupported/unverified; exact test nodes, skips and limits are recorded.

AWQ evidence and per-variant policy: not applicable (boxes left unchecked on purpose): no grouping, fold, or search change. This is replay device placement only. The rebuilt
cos/sin are the same values computed on the replay device instead of the CPU. phi4mm's AWQ policy is unchanged (norm-sourced
groups with LoRA-adapter compensation, _awq_allow_partial_replay). Its CPU output is bit-identical to main, and on CUDA it now
completes instead of crashing. The neutral-fold and chunk-parity rows are not affected by a device-placement change.
The existing phi4mm port tests above cover them.

Logic Flow Documentation

  • This change does not alter a major logic flow, or the required diagrams
    and docs page are included below.

Diagram summary: not applicable. Rotary resolution order and the rebuild decision are unchanged. Only the device reported for a
tensorless rotary changes, from CPU to the caller's fallback (awq_processor.py _get_rotary_device).

Review Requirements

  • 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

  • Not verified: a multi-GPU phi4mm quantize, and real-size Phi-4-multimodal-instruct weights. The tiny seeded fixture
    exercises the same port rotary and replay path.
  • utils.device.get_device still returns CPU for a tensorless module. It has many callers, and changing its default is out
    of scope. The fix stays in the rotary helper, which turns that answer into an input move.

🤖 Generated with Claude Code

phi4mm (Phi-4-multimodal) AWQ quantization on CUDA crashed in the scale-search
replay with `RuntimeError: Expected all tensors to be on the same device ...
cuda:0 and cpu` in `apply_rotary_pos_emb`.

Cause: `_prepare_module_forward` and `_refresh_forward_kwargs_from_cache`
rebuild `position_embeddings` with the root rotary and move the replay input
to the device `_get_rotary_device` reports. phi4mm's port rotary
(`ports/phi4/modeling_phi4.py` `RotaryEmbedding`) is stateless: it has no
parameters or buffers and derives its LongRoPE frequencies from the input on
every call. `_get_rotary_device` fell through to `utils.device.get_device`,
which returns CPU for a module without tensors, so the CUDA activation was
copied to the CPU, cos/sin were built there, and the CUDA attention received
CPU embeddings. Declaring `rotary_embedding` would not help: there is no
tensor to move.

Fix: `_get_rotary_device` returns the caller's fallback (the module/input
device) when the rotary owns no parameters or buffers, as ParoQuant's copy of
the helper already does. `_get_rotary_for_device` passes the target as that
fallback, so a stateless rotary is used as-is instead of deep-copied per
device. Rotaries with `inv_freq` or other tensors resolve exactly as before.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@Qubitium
Qubitium marked this pull request as ready for review December 1, 2026 09:49
@Qubitium
Qubitium merged commit 12abda5 into main Dec 1, 2026
6 checks passed
@Qubitium
Qubitium deleted the fix/phi4mm-awq-cuda-rotary branch December 1, 2026 09:49
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