Skip to content

[Fix] GLM-4.7-Flash: Load compressed-tensors W4A16 checkpoints - #49531

Merged
BBuf merged 3 commits into
sgl-project:mainfrom
koladefaj:fix/glm47-flash-ct-w4a16
Nov 11, 2026
Merged

BBuf merged 3 commits into
sgl-project:mainfrom
koladefaj:fix/glm47-flash-ct-w4a16

Conversation

@koladefaj

@koladefaj koladefaj commented Nov 10, 2026 •

Copy link
Copy Markdown
Contributor

Motivation

Fixes #49369, reported by @HollowMan6.

cyankiwi/GLM-4.7-Flash-AWQ-4bit (compressed-tensors pack-quantized, int4 symmetric, group 32) does not load. It quantizes q_a_proj, kv_a_proj_with_mqa and kv_b_proj from layer 1 on, and keeps layer 0 and the shared experts in BF16 through its ignore list. On a real sglang serve, it fails in five places, one after the other. Each one only shows up once the one before it is fixed:

 sglang serve cyankiwi/GLM-4.7-Flash-AWQ-4bit
   build model            # (3) layer 0 + shared-expert gate_up_proj built W4A16; (4) BF16 shared expert fused into W4A16 MoE
   load_weights
-    fuse q_a + kv_a      # (1) weight_shape -> [4] -> AssertionError
+    fuse q_a + kv_a      # weight_shape -> [q_out + kv_out, in]
     post_load_weights
-      kv_b_proj.weight   # (2) AttributeError
+      dequantize kv_b_proj -> w_kc / w_vc
   process_weights_after_loading   # Marlin repack
   capture CUDA graphs
-    fused_a_gemm_weight_eligible(layer.weight)   # (5) AttributeError
+    packed layer -> regular path
   serve
  1. Fused QKV-A weight_shape. load_weights fuses q_a_proj and kv_a_proj_with_mqa by concatenating every tensor of the pair on dim 0. For weight_shape ([out, in]), that gives [q_out, in, kv_out, in] instead of [q_out + kv_out, in], and the load asserts. DeepseekV2WeightLoaderMixin has the same concatenation.
  2. kv_b_proj in post_load_weights. The MLA post-load step reads kv_b_proj.weight, which a packed layer does not have. This is the issue's AttributeError.
  3. Empty packed_modules_mapping. Glm4MoeLiteForCausalLM declares none, so ignore entries that name shards (q_a_proj, gate_proj, ...) never match the fused fused_qkv_a_proj_with_mqa and gate_up_proj. Layer 0 and the shared experts' gate_up_proj get built W4A16 over BF16 weights. With FP8 this fails silently: @HollowMan6 measured 3.4e38 outputs on unsloth/GLM-4.7-Flash-FP8-Dynamic, where 13.0 is expected.
  4. Shared-expert fusion. On CUDA SM80+, GLM fuses the shared expert into the routed FusedMoE, but this checkpoint keeps the shared experts in BF16 beside W4A16 routed experts.
  5. Fused-A GEMM eligibility. fused_a_gemm_weight_eligible reads layer.weight on the packed fused_qkv_a_proj_with_mqa during the first forward (CUDA graph capture).

Modifications

  • models/deepseek_common/utils.py: a new fuse_qkv_a_proj_tensors, used by both the GLM and DeepSeek loaders.
    • weight_shape adds the output rows.
    • A shared act-order weight_g_idx is kept, and differing ones are rejected.
    • A pair of 0-d scales is shared, as before.
    • Only AWQ/GPTQ-packed tensors (qweight, qzeros, scales under awq, awq_marlin, moe_wna16, gptq, gptq_marlin or auto-round) stack on dim 1. A projection that such a checkpoint leaves unconverted keeps a plain [out, in] weight. QuantTrio/GLM-4.7-Flash-AWQ keeps self_attn in BF16, so choosing the dim from the config alone would break it. GGUF also names a tensor qweight, but it is row-major and stays on dim 0.
    • GPTQ's g_idx follows the same rule as weight_g_idx.
  • compressed_tensors_wNa16.py: CompressedTensorsWNA16.dequantize_weight unpacks the checkpoint layout to a dense weight in the scale dtype.
    • It supports symmetric quantization without act order.
    • The kernel repack marks the layer, and dequantizing a repacked layer raises. Sharded-state and remote-instance loaders copy kernel-layout tensors and then call post_load_weights. Reading those tensors would build garbage w_kc/w_vc.
  • deepseek_weight_loader.py: post_load_weights dequantizes a compressed-tensors WNA16 kv_b_proj before the w_kc/w_vc split, next to the AWQ branch. It also sets _derived_weight_cache_error on that layer: once repacked it cannot be dequantized again, so online weight updates are refused before they write any weight.
  • glm4_moe_lite.py:
    • packed_modules_mapping maps fused_qkv_a_proj_with_mqa and gate_up_proj to their shards.
    • The shared-expert fusion gate checks quant_blocks_shared_experts_fusion, as DeepSeek-V2 already does.
    • The loader pops cached QKV-A tensors even when the fused param is absent.
  • compressed_tensors.py: CompressedTensorsConfig.can_fuse_shared_expert is false when ignore gives any shared-expert projection (gate_proj, up_proj, down_proj) of a layer a different precision from the same routed-expert projection, in either direction. Each projection is resolved per MoE layer with should_ignore_layer, so names and regexes match alike. A shared_expert_gate entry does not count. It probes the layers the ignore list names; a regex, or a bare suffix that could match an expert, adds model.layers.0-255. That takes 1.3 ms on the FP8 checkpoint's 601-entry list.
  • fused_a_gemm.py: a layer without a dense weight is not eligible.

Behavior change outside GLM: can_fuse_shared_expert is also read by DeepSeek-V2/V4, MiniMax-M3 and Qwen2-MoE / Qwen3.5. For a compressed-tensors checkpoint whose ignore keeps any shared-expert projection at a different precision from the matching routed-expert projection, these now skip shared-expert fusion. Fusing such a checkpoint would load BF16 weights into the quantized expert buffers, or quantized weights into BF16 ones. A checkpoint that ignores the same projections on both sides keeps fusion.

Accuracy Tests

1x NVIDIA A40 (SM86) for the cyankiwi row and 1x NVIDIA RTX A6000 (SM86) for the QuantTrio row, image lmsysorg/sglang:nightly-dev-cu13-20261110-4a5c6b8f. Every file this PR touches is identical between the image's tree and this PR's base 533c067689. "main" is that tree unchanged, and "branch" is this PR applied to it. The launch command follows the cookbook (--tp 1 --reasoning-parser glm45):

sglang serve --model-path <model> --tp 1 --reasoning-parser glm45 --port 30000
sgl-eval run gsm8k --base-url http://127.0.0.1:30000/v1 --num-examples 200 \
  --num-threads 64 --max-tokens 4096 --chat-template-kwarg enable_thinking=false
Checkpoint main branch
cyankiwi/GLM-4.7-Flash-AWQ-4bit (this issue) fails to load GSM8K 0.850 (1/200 truncated)
QuantTrio/GLM-4.7-Flash-AWQ (regression check) GSM8K 0.910 (2/200 truncated) GSM8K 0.890 (0/200 truncated)

All runs use the command above: greedy (temperature 0, top_p 0.95), thinking off. Every server that loads answers 17*23 with 391.

SM90 run by @HollowMan6 (1x H20-3e, the same commands; comment):

Checkpoint main branch
unsloth/GLM-4.7-Flash-FP8-Dynamic GSM8K 0.000 (200/200 truncated; 17*23 answers !!!!!!!!…) GSM8K 0.890 (0/200 truncated)
cyankiwi/GLM-4.7-Flash-AWQ-4bit fails to load GSM8K 0.870 (0/200 truncated)

This covers the FP8 case that SM86 cannot run, and the fused-A GEMM path, which is eligible on SM90.

  1. Truncations are generations that hit the 4096-token cap. They happen on unpatched main too (2/200 with the AWQ checkpoint), so they are not caused by this PR. The cookbook's 0.845 is BF16 on H100 with the same sgl-eval command and 200 examples. It's a sanity reference, not a like-for-like comparison. An earlier A6000 run of the cyankiwi checkpoint on this branch is consistent: 0.874 thinking-off and 0.969 thinking-on, both partial runs without a token cap.
  2. The AWQ runs: both trees build the same model: 17.52 GB of weights, the same KV size, the awq_marlin kernel and the same CUDA graphs. Answers flip both ways (10 questions right only on main, 6 only on the branch), and 51/200 greedy generations match word for word. That looks like batching nondeterminism, though I did not run main twice to confirm.
  3. FP8 (unsloth/GLM-4.7-Flash-FP8-Dynamic) cannot run on SM86 on either tree (bmm_fp8 does not support backend 'cublas' with capability 86); see the SM90 table above.
Before: main, cyankiwi/GLM-4.7-Flash-AWQ-4bit (the same assert on A6000 and A40)
  File ".../sglang/srt/model_loader/loader.py", line 1048, in load_model
    self.load_weights_and_postprocess(
  File ".../sglang/srt/model_loader/loader.py", line 1057, in load_weights_and_postprocess
    DefaultModelLoader.load_weights_only(model, weights, target_device)
  File ".../sglang/srt/model_loader/loader.py", line 1091, in load_weights_only
    model.load_weights(weights)
  File ".../sglang/srt/models/glm4_moe_lite.py", line 1043, in load_weights
    weight_loader(param, fused_weight)
  File ".../sglang/srt/layers/linear.py", line 377, in weight_loader
AssertionError: param.shape=torch.Size([2]) param.dtype=torch.int64 loaded_weight.shape=torch.Size([4]) loaded_weight.dtype=torch.int64

With fixes 1–4 applied but not 5, loading completes and the first forward fails:

  File ".../sglang/srt/models/deepseek_v2.py", line 2621, in prepare_qkv_latent
    and fused_a_gemm_weight_eligible(
  File ".../sglang/kernels/ops/gemm/fused_a_gemm.py", line 52, in fused_a_gemm_weight_eligible
    layer.weight.dtype == torch.bfloat16
AttributeError: 'ReplicatedLinear' object has no attribute 'weight'
After: this branch, cyankiwi/GLM-4.7-Flash-AWQ-4bit (A40)
[2026-11-10 09:11:58] Quantization keeps shared experts at a higher precision than the routed experts, so they cannot be fused into the quantized routed-expert path. Shared experts fusion optimization is disabled.
[2026-11-10 09:12:18] Load weight end. elapsed=20.65 s, type=Glm4MoeLiteForCausalLM, quant=compressed-tensors, avail mem=26.22 GB, mem usage=17.86 GB.
[2026-11-10 09:12:25] KV Cache is allocated. dtype: torch.bfloat16, #tokens: 360675, KV size: 18.19 GB
[2026-11-10 09:25:22] Capture target prefill CUDA graph end. elapsed=777.75 s, mem usage=1.73 GB, avail mem=4.63 GB.
[2026-11-10 09:25:34] Capture target decode CUDA graph end. bs=[1, 2, 4, 8, 12, 16, 24, 32], elapsed=11.78 s, mem usage=0.29 GB, avail mem=4.35 GB.
[2026-11-10 09:25:51] The server is fired up and ready to roll!

The 778 s prefill capture was the first serve on a fresh pod. The same code captured in 26 s on the A6000 pod after an earlier serve there, so this is most likely cold kernel caches; the log does not show the cause.

$ curl .../v1/chat/completions  # "What is 17*23? Answer with just the number."
"content": "391"
sgl-eval gsm8k (A40, 200 examples, 64 threads, max_tokens 4096, thinking off):
score 0.85, stop_rate 0.995, truncated_rate 0.005, error_rate 0.0

Unit tests

New CPU file test/registered/unit/models/test_mla_compressed_tensors_wna16_loading.py (base-a-test-cpu), plus a GLM case in test_shared_experts_fusion_gates.py. I checked each regression case: it fails with its fix reverted and passes with it. The cases:

  • The GLM and DeepSeek loaders fuse weight_shape / weight_packed / weight_scale.
  • GLM stacks AWQ qweight on dim 1 and keeps unconverted BF16 attention on dim 0.
  • dequantize_weight matches compressed-tensors' own pack_to_int32 exactly (4-bit group, 4-bit channel, 8-bit).
  • The real process_weights_after_loading marks the layer, and dequantizing it afterwards raises.
  • post_load_weights builds w_kc/w_vc from a packed kv_b_proj, and online weight updates are then refused.
  • Layer 0's fused layers, and an FP8 checkpoint's ignored layer-1 attention, resolve to their ignored shards.
  • can_fuse_shared_expert covers the checkpoint's own ignore list, gate-only, a single shared up_proj / down_proj, routed-only, the same projection on both sides, both-ignored, regex (including re:.*mlp\.shared.* and a layer-anchored regex) and bare-suffix cases.
  • GPTQ / AutoRound qweight stacks on dim 1, GGUF's stays on dim 0, and GPTQ g_idx follows the act-order rule.
  • fused_a_gemm_weight_eligible is false on a packed layer.
test_mla_compressed_tensors_wna16_loading.py + test_shared_experts_fusion_gates.py + test_deepseek_quark_block_fp8_loading.py:
67 passed on the A40 pod at 0a7a7e4175; 69 passed locally at f542238650

f542238 leaves the fusion decision of both real checkpoints unchanged (cyankiwi: off, unsloth FP8: on), so the accuracy runs above still apply.

Merge Danger

Door: two-way. Code-only, no format, config or API changes; a revert restores the old behavior.

Blast radius: MLA checkpoint loading.

  • Every GLM-4.7-Flash and DeepSeek-family load goes through the new QKV-A fusion helper. Only weight_shape, weight_g_idx and the AWQ qweight/qzeros/scales choice of dimension behave differently; every other tensor concatenates exactly as before. The unconverted-attention AWQ case is covered by the QuantTrio row above.
  • Shared-expert fusion turns off for compressed-tensors checkpoints whose ignore keeps any shared-expert projection at a different precision from its routed counterpart (see "Behavior change outside GLM"). That costs throughput where fusion used to run, but such checkpoints loaded weights into buffers of the wrong precision.
  • A packed compressed-tensors kv_b_proj reloaded through the sharded-state or remote-instance loaders now raises NotImplementedError instead of computing silently wrong w_kc/w_vc.
  • Online weight updates on a compressed-tensors WNA16 MLA checkpoint are refused up front with a message, instead of failing in post_load_weights after the new weights were written.

Speed Tests and Profiling

No kernel changes. The fused-A GEMM change only makes packed layers take their regular path (before, they crashed). On this checkpoint, disabling shared-expert fusion is required for correctness.

Checklist


CI States

Latest PR Test (Base): ✅ Run #42961238841
Latest PR Test (Extra): ❌ Run #42961237769
Latest PR Test (AMD ROCm 10): ⏳ Run #42961238099

Tip

Base CI only covers the core cases, and its workload may not exercise your change. Use /rerun-test to run the tests your change touches, or copy this prompt for an agent:

Find the registered tests this PR affects and run them with /rerun-test, following https://github.com/sgl-project/sglang/blob/main/.agents/skills/rerun-test/SKILL.md

@claude claude Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Claude Code Review

This pull request is from a fork — automated review is disabled. A repository maintainer can comment @claude review to run a one-time review.

@HollowMan6

Copy link
Copy Markdown

Tested on 1x H20-3e (SM90), both gaps from the description.

Setup: "main" is the PR's base 533c067689, "branch" is 0a7a7e4175, each tree's python/ first on PYTHONPATH over the same environment (sglang-kernel 0.4.10, flashinfer-python 0.7.3, the base's pins). Your commands, one GPU per server:

sglang serve --model-path <model> --tp 1 --reasoning-parser glm45 --port <port>
sgl-eval run gsm8k --base-url http://127.0.0.1:<port>/v1 --num-examples 200 \
  --num-threads 64 --max-tokens 4096 --chat-template-kwarg enable_thinking=false
Checkpoint main branch
unsloth/GLM-4.7-Flash-FP8-Dynamic GSM8K 0.000 (200/200 truncated at 4096 tokens; 17*23 answers !!!!!!!!…) GSM8K 0.890 (0/200 truncated; 17*23 -> 391)
cyankiwi/GLM-4.7-Flash-AWQ-4bit fails to load: AssertionError: param.shape=torch.Size([2]) ... loaded_weight.shape=torch.Size([4]) GSM8K 0.870 (0/200 truncated; 17*23 -> 391)

So the FP8 case from the issue is fixed by the packed_modules_mapping change, and the AWQ checkpoint serves on SM90 with the fused-A GEMM path present: no AttributeError during CUDA graph capture, and the log shows the shared-expert fusion turned off ("Quantization keeps shared experts at a higher precision than the routed experts ...").

A few comments from reading the diff:

  1. fuse_qkv_a_proj_tensors: packed_outputs_last only matches awq, awq_marlin and moe_wna16. GPTQ's qweight ([in // pack, out]), qzeros and scales also keep the output dim last, and the comment says "AWQ/GPTQ-packed", so a GPTQ-packed MLA checkpoint would still be concatenated on dim 0. Adding gptq and gptq_marlin to the tuple (or deciding from the tensor names alone, since .qweight / .qzeros / .scales only exist in these layouts) would cover it.
  2. can_fuse_shared_expert scans ignore entries for the substring shared_expert, so an entry that matches the shared experts without containing it (for example re:.*mlp\.shared.*) is not seen. Resolving one concrete shared-expert module name and one routed-expert module name per MoE layer with should_ignore_layer and comparing the two answers would handle names and regexes the same way. Not blocking for these checkpoints, whose ignore lists name the modules.
  3. dequantize_weight looks right to me: (code - 2^(b-1)) is exact in the scale dtype, so the product rounds once, the same as computing in FP32 and casting.

@koladefaj

Copy link
Copy Markdown
Contributor Author

@HollowMan6 thank you for running both, and for the review. The FP8 numbers are the evidence this PR was missing.

Addressed in 930d78d:

  1. GPTQ. fuse_qkv_a_proj_tensors now stacks qweight / qzeros / scales on dim 1 for gptq, gptq_marlin and auto-round too (AutoRound packs as auto_gptq or auto_awq). I kept the format check instead of deciding from the names alone, because GGUF also names its tensors qweight with a row-major layout. GPTQ's g_idx now follows the same rule as weight_g_idx: it's kept when both projections share it, and rejected otherwise.
  2. can_fuse_shared_expert. The check now resolves <prefix>.experts.0.gate_proj and <prefix>.shared_expert(s).gate_proj per MoE layer with should_ignore_layer, so names and regexes go through the same matcher. The layers it probes are the ones the ignore list names. A regex, or a bare suffix that could match an expert, adds model.layers.0-255. re:.*mlp\.shared.* and a layer-anchored regex are now in the tests. On your FP8 checkpoint's 601-entry ignore list the check takes 0.4 ms, and it still allows fusion there, since the routed and shared experts are ignored together.
  3. Thanks for checking the dequant rounding.

Both changes come with regression cases that fail on 0a7a7e4 and pass now. Your H20 table is in the description, credited to you.

@BBuf BBuf left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[BBuf Review Agent] A few things to fix before this can go in.

@BBuf

BBuf commented Nov 11, 2026

Copy link
Copy Markdown
Collaborator

[BBuf Review Agent] @koladefaj At 930d78d the fusion check still probes only gate_proj, so ignoring just model.layers.1.mlp.shared_experts.down_proj still allows fusion and the BF16 weight gets skipped during loading. Could we check every shared projection against its routed counterpart before allowing fusion?

…online updates

can_fuse_shared_expert compared only gate_proj, so a checkpoint that
ignored just shared_experts.down_proj (or up_proj) still fused, and the
BF16 down weight was skipped during loading. Compare gate_proj, up_proj
and down_proj of the shared expert with the same projection of the
routed experts, and refuse fusion on a mismatch in either direction.

A loaded compressed-tensors WNA16 kv_b_proj is repacked for the kernel
and cannot be dequantized again, so an online weight update wrote the
new weights and then failed in post_load_weights. Mark the layer with
_derived_weight_cache_error so updates are refused before they write.
@koladefaj

Copy link
Copy Markdown
Contributor Author

Thanks @BBuf, both fixed in f542238.

  1. Shared-expert fusion. can_fuse_shared_expert now compares gate_proj, up_proj and down_proj of the shared expert with the same projection of the routed experts. It refuses fusion on a mismatch in either direction, so a BF16 shared projection beside a quantized routed one, or the reverse, no longer fuses. Ignoring only model.layers.1.mlp.shared_experts.down_proj now returns False. New cases cover a single shared up_proj / down_proj (also as a bare suffix), routed-only ignores, and the same projection on both sides. Both real checkpoints keep the same decision (cyankiwi: off, unsloth FP8: on), so the accuracy runs still apply.
  2. Online weight updates. post_load_weights now sets _derived_weight_cache_error on a compressed-tensors WNA16 kv_b_proj, so begin_weight_update and the other update paths refuse before writing any weight, instead of failing in post_load_weights afterwards. Supporting the update would need the checkpoint layout restored and w_kc/w_vc rebuilt, which I've left out of this PR. A test checks the update is refused.

69 tests pass locally across the three test files.

@BBuf

BBuf commented Nov 11, 2026

Copy link
Copy Markdown
Collaborator

[BBuf Review Agent] @koladefaj Checked f542238: the fusion guard now compares each shared projection with its routed counterpart, covering the down_proj case I raised. The WNA16 cache marker is also checked before online updates mutate weights, including begin_weight_update.

@BBuf

BBuf commented Nov 11, 2026

Copy link
Copy Markdown
Collaborator

/tag-and-rerun-ci

@github-actions github-actions Bot added the run-ci CI: run the baseline test suite on this PR label Nov 11, 2026

@BBuf BBuf left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[BBuf Review Agent] LGTM. Both earlier issues are addressed.

@BBuf
BBuf merged commit aef6cf1 into sgl-project:main Nov 11, 2026
252 of 284 checks passed
SKRohit added a commit to SKRohit/rohit-sglang-fork that referenced this pull request Nov 17, 2026
…ling3-vl-fp4

703e763 is the sglang commit in intel/sglang-dev 01ddedc3414a, on which the
branch was re-validated. Conflicts:

- models/glm4_moe_lite.py: take main. sgl-project#49531 added the same
  packed_modules_mapping, and fuse_qkv_a_proj_tensors already concatenates
  packed GPTQ/AWQ/AutoRound tensors on the output dim.
- model_runner_components/moe_ep_setup.py: keep both skips, main's
  quant_method != "fp8" (Fp8MoEMethod decides at weight creation) and this
  branch's is_fp4_experts.
sogalin pushed a commit that referenced this pull request Dec 1, 2026
…zation ignore lists (partial cherry-pick #49531) (#54134)

Co-authored-by: Claude Opus 5.5 (1M context) <[email protected]>
@akao-amd akao-amd mentioned this pull request Dec 3, 2026
3 of 5 tasks
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

deepseek jit-kernel run-ci CI: run the baseline test suite on this PR

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug] GLM-4.7-Flash compressed-tensors W4A16: MLA post-load step reads kv_b_proj.weight, which a packed layer does not have

3 participants