Skip to content

fix(awq): keep deepseek_v4 o_a_proj out of the input_layernorm fold - #6454

Merged
Qubitium merged 1 commit into
mainfrom
fix/deepseek-v4-awq-o-a-proj-consumer
Nov 30, 2026
Merged

Qubitium merged 1 commit into
mainfrom
fix/deepseek-v4-awq-o-a-proj-consumer

Conversation

@Qubitium

Copy link
Copy Markdown
Collaborator

Summary

The DeepSeek V4 AWQ input_layernorm fold also scaled self_attn.o_a_proj, which does not read the normed input.

The generic planner (BaseQModel.awq_get_modules_for_scaling, _norm_scale_consumers, gptqmodel/models/base.py) treats a :! leaf declared in a quantized block as a reader of that block's input when its input width equals the norm width. It then multiplies the leaf's input columns by the fold scale. V4 declares self_attn.o_a_proj:! without a stage, so it lands in the stage-0 block with q_a_proj and kv_proj.

In the native forward (DeepseekV4Attention.forward, gptqmodel/models/ports/native/deepseek_v4/modeling_deepseek_v4.py), o_a_proj is the grouped output projection: self.o_a_proj(attn_output.reshape(..., o_groups, -1)). It reads the attention output. It still qualified because DeepseekV4GroupedLinear.in_features is the per-group width num_heads * head_dim / o_groups. That equals hidden_size on the released V4-Flash config (64 * 512 / 8 = 4096) and on the tiny parity fixture (4 * 32 / 2 = 64). So every V4-Flash AWQ run scaled o_a_proj and changed the model output.

On a tiny random model built from tests/fixtures/ports/native_parity/deepseek_v4.json (HCA layer, CSA layer), fold only (no quantization), relative logits change:

Measurement origin/main this PR
Planner group, fixed scale linspace(0.55, 1.45), layer 0 / layer 1 1.53e-1 / 1.09e-1 2.83e-7 / 1.97e-7
Real AWQProcessor._quantize_layer, searched scales, identity quantization, attention groups, cumulative after layer 0 / 1 5.75e-2 / 7.84e-2 2.76e-7 / 2.72e-7

What Changed

  • gptqmodel/models/definitions/deepseek_v4.py: o_a_proj:! becomes o_a_proj:!:noconsumer. noconsumer is the existing opt-out for a non-quantized module that runs in the fold's run but reads a different tensor (Gemma 4's router.proj uses it). Both _norm_scale_consumers and canonical_awq_folds honour it.
  • Same file: compressor.indexer.q_b_proj:! becomes compressor.indexer.q_b_proj:!:noconsumer. It reads the q latent (q_residual), and the same rule would pick it up on any config with q_lora_rank == hidden_size. No released config has that (Flash 1024 vs 4096), so today's plans are unchanged by this line. The new test covers it.
  • Quantization flags, stages and GPTQ plans are unchanged. o_a_proj and the compressor projections are still not quantized.
  • tests/module_tree/test_deepseek_v4_local_port.py: new test_awq_input_layernorm_fold_skips_width_matched_non_readers. It uses the fix(awq): fold dots3_note input_layernorm into every projection that reads it #6453 pattern on all three attention types (sliding, CSA, HCA), with num_attention_heads=4, q_lora_rank=16 so that both widths equal hidden_size=16. The test:
    • hooks the native forward and finds every linear whose input equals the input_layernorm output;
    • asserts that set is exactly q_a_proj, kv_proj and the compressor/indexer kv_proj/gate_proj/weights_proj that exist on the layer type;
    • asserts the planner's input_layernorm group (targets + consumers) equals that set and passes assert_awq_folds_neutral.
  • tests/module_tree/fixtures/awq_fold_plans.json: only the deepseek_v4 entry was regenerated, with --write --types deepseek_v4. The change: self_attn.o_a_proj is removed from the input_layernorm consumers in both layer classes (sliding/HCA layers and CSA layers). Before regenerating, --check over every type reported changed: ['deepseek_v4'] only.
  • Why the fix is in the definition rather than the shared rule: the planner sees module widths and tree order, not data flow. o_a_proj and a real block-input reader such as Laguna's g_proj:! look the same to it: an unstaged :! nn.Linear with in_features == hidden_size. Telling them apart in shared code would need runtime capture of non-quantized module inputs, which is a processor change and would touch every model. A declared opt-out keeps all other plans unchanged.

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.

Environment: CPU only, /root/venv/bin/python (torch 2.15.0, transformers 5.23.0), python -P, PYTHONPATH=<tree>, HF_HUB_OFFLINE=1. Base: origin/main 452550d.

# New regression test on origin/main (test added, fix not applied): FAILS for the intended reason
python -P -m pytest -q tests/module_tree/test_deepseek_v4_local_port.py -k width_matched
# [sliding_attention]            E AssertionError: ...input_layernorm -> ['self_attn.q_a_proj', 'self_attn.kv_proj'] changed the layer output by 4.742e-02
# [compressed_sparse_attention]  ... changed the layer output by 4.955e-02
# [heavily_compressed_attention] ... changed the layer output by 4.839e-02
# 3 failed
# Branch with only the o_a_proj opt-out (indexer line reverted): 1 failed ([compressed_sparse_attention]), 2 passed

# Branch
python -P -m pytest -q tests/module_tree/test_deepseek_v4_local_port.py -k width_matched
# 3 passed

# Fold inventory
python -P tests/module_tree/awq_fold_inventory.py --check            # before regenerating: changed: ['deepseek_v4']
python -P tests/module_tree/awq_fold_inventory.py --write --types deepseek_v4
python -P -m pytest -q -n 32 tests/module_tree/test_awq_fold_inventory.py
# 501 passed

# AWQ onboarding baseline + module_tree + V4/port/registry tests
python -P -m pytest -q -n 32 tests/module_tree tests/test_awq_scale_search_safety.py tests/test_awq_moe_router_scaling.py \
  tests/test_awq_empty_groups.py tests/test_awq_position_kwargs.py tests/test_awq_scale_search_memory.py \
  tests/test_bloom_awq_replay.py tests/test_awq_scaling_groups.py tests/test_deepseek_v4_local_port.py \
  tests/test_native_definition_loading_0.py tests/test_native_auto_registry.py tests/test_model_port_policy.py
# origin/main: 4523 passed, 815 skipped, 2 xfailed
# branch:      4526 passed, 815 skipped, 2 xfailed   (+3 new tests)
# The skip count is the same on both revisions. Skips include CUDA/ROCm-only kernels, the opt-in meta_coverage marker,
# and opt350/muse_glimmer "not exercised as a buildable CausalLM family" in test_awq_scaling_groups.py.

bash format/check.sh   # ruff 0.14.2: All checks passed!

Measured Impact

End-to-end A/B on CPU: GPTQModel.load(...).quantize(...) then save. The model is a tiny random V4 (parity-fixture config, 2 layers HCA + CSA, routed MoE, non-unit input_layernorm gains). Calibration is 8 x 24 random tokens, 4-bit, group_size 16. Every saved tensor was compared.

Run Saved tensors equal main vs PR In-memory quantized logits
GPTQ 200 / 200 bit-identical equal (max abs diff 0.0)
AWQ (fallback=None) differ, as intended differ (max abs diff 0.107)

AWQ check: self_attn.o_a_proj.weight in the saved checkpoint equals the source attn.wo_a.weight on this PR and differs from it on main, in both layers. The other differences follow from that: the attention outputs differ, so downstream calibration differs.

No VRAM/performance impact: only module-tree flags changed.

Model Support / Module Plan

  • Every new MODEL_MAP entry has an explicit registry plan case. (Not applicable: no new entry.)
  • A new model-specific module-plan unit test builds the real model class and verifies declared paths, checkpoint weight ownership/tags, roles, and applicable consumers, including layout variants and method overrides. (The AWQ consumer test above covers all three attention layouts. Ownership/tags are unchanged and covered by the existing test_exact_native_and_defused_checkpoint_owners.)
  • Runtime-created tensors are distinguished from checkpoint-owned weights. (Not applicable: no ownership change.)
  • Fusion eligibility is recorded in fusable_models.json. (Not applicable: no change.)
  • Fusion modules/parents resolve through model.module_plan(). (Not applicable.)
  • Composed fusion configs... (Not applicable.)
  • New fusion qualifications... (Not applicable.)
  • Registry and model-specific tests passed; any dependency skips and their precise coverage limits are listed below.

Model test node IDs and results:

  • tests/module_tree/test_deepseek_v4_local_port.py (28 passed, including the 3 new test_awq_input_layernorm_fold_skips_width_matched_non_readers[...])
  • tests/test_deepseek_v4_local_port.py, tests/module_tree/test_flash_model_tree_consumption.py, tests/module_tree/test_registered_module_plans.py: passed (the registered plan fixture does not record noconsumer, so it is unchanged)

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. (Not changed by this PR. Replay and fallback paths are untouched.)
  • 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: the input_layernorm output is read by q_a_proj, kv_proj and, when the layer has them, compressor.kv_proj/gate_proj (HCA, CSA) and compressor.indexer.kv_proj/gate_proj/scorer.weights_proj (CSA). All of these read hidden_states in DeepseekV4Attention.forward and the compressor/indexer forwards. The new test checks this set against the hooked native forward for sliding, CSA and HCA layers and requires the fold to be neutral. o_a_proj reads the de-rotated attention output, and compressor.indexer.q_b_proj reads q_residual. Neither is a consumer. The post-attention MoE group and the per-expert up -> down groups are unchanged and still covered by test_awq_scale_folds_preserve_real_hyper_connected_layer_output.

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. The change only adds an existing flag to two module-tree leaves; no control flow changes.

Review Requirements

I or an AI agent (such as Codex or Claude) have:

  • 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.
  • Not applicable: no fusion change.
  • Not applicable: no kernel inventory change.

Notes

  • Bug (found in the fix(awq): fold dots3_note input_layernorm into every projection that reads it #6453 work, fixed here): for deepseek_v4, the generic AWQ planner added self_attn.o_a_proj as a scale consumer of the input_layernorm group. o_a_proj reads the attention output; it was selected only because its per-group input width num_heads*head_dim/o_groups equals hidden_size (64*512/8 = 4096 on V4-Flash). Fold-only logits change on the tiny fixture: 1.5e-1 / 1.1e-1 -> 2.8e-7 / 2.0e-7.
  • Shared weakness, not changed here: _norm_scale_consumers (and canonical_awq_folds) admit any :! 2-D-weight leaf in the block whose input width equals the norm width. I checked every non-MoE consumer in the current fold inventory against its port's forward:
    • Correct readers of the normed hidden state: in_proj_a/in_proj_b/in_proj_ba (agnes, qwen3_5*, qwen3_next, intern_s2_preview, minicpmv4_6, zdtaichu5_0, ovis2_6_next), b_proj/f_a_proj/g_a_proj (glm5_next, solar_open2), g_proj (laguna, brumby, lfm3_vl), indexer.weights_proj (deepseek_v32) and phi4mm's qkv_proj.lora_A.*.
    • A native-reader sweep over the 95 native_parity fixtures that build and run found deepseek_v4's o_a_proj as the only width-coincidence consumer.
    • Types without a buildable parity fixture were checked by reading their forwards only.
  • A general fix would need runtime data flow: checking that a candidate consumer's captured input is the source output. That is out of scope here.

🤖 Generated with Claude Code

The generic AWQ planner treats every width-matched `:!` leaf declared in a
quantized block as a reader of that block's normed input and multiplies its
input columns by the fold scale. DeepSeek V4 declares `self_attn.o_a_proj:!`
without a stage, so it lands in the stage-0 block next to q_a_proj and
kv_proj. o_a_proj is the grouped output projection: it reads the attention
output, not the input_layernorm output. It still qualified because its
per-group input width num_heads * head_dim / o_groups equals hidden_size
(64 * 512 / 8 == 4096 on V4-Flash, and on the tiny parity fixture), so
every V4 AWQ run scaled it and changed the model output. On the tiny
fixture the fold alone (identity quantization) changed logits by 1.5e-1 /
1.1e-1 per layer.

Declare o_a_proj `:noconsumer`, the existing opt-out for a non-quantized
module in the run that reads a different tensor. Do the same for
compressor.indexer.q_b_proj, which reads the q latent and would be selected
the same way by any config with q_lora_rank == hidden_size.

The regression test builds tiny native V4 layers of all three attention
types with these widths matching, hooks the native forward to find the
linears that really read the input_layernorm output, and requires the
planner's group to equal that set and to fold neutrally.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@Qubitium
Qubitium marked this pull request as ready for review November 30, 2026 00:18
@Qubitium
Qubitium merged commit 1d4420a into main Nov 30, 2026
6 checks passed
@Qubitium
Qubitium deleted the fix/deepseek-v4-awq-o-a-proj-consumer branch November 30, 2026 00:18
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