Skip to content
Closed
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
87 changes: 87 additions & 0 deletions tests/models/glm5next/test_nvfp4_attn_proj_load.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,87 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""Loading ModelOpt NVFP4 MLA projections into GLM-5.x's BF16 fused_qkv_a_proj."""

import torch

from vllm.models.glm5next.common.model import _try_load_nvfp4_attn_proj

E2M1 = torch.tensor(
[0, 0.5, 1, 1.5, 2, 3, 4, 6, -0.0, -0.5, -1, -1.5, -2, -3, -4, -6],
dtype=torch.float32,
)
PREFIX = "model.layers.3.self_attn"


class _RecordingParam:
def __init__(self):
self.calls: list = []

def weight_loader(self, param, weight, shard_id=None):
self.calls.append((weight, shard_id))


def _nvfp4(out_dim: int, in_dim: int, seed: int):
g = torch.Generator().manual_seed(seed)
packed = torch.randint(
0, 256, (out_dim, in_dim // 2), dtype=torch.uint8, generator=g
)
scale = (torch.rand(out_dim, in_dim // 16, generator=g) * 4 + 0.25).to(
torch.float8_e4m3fn
)
gscale = torch.tensor(0.0123, dtype=torch.float32)
codes = torch.stack([packed & 0xF, packed >> 4], dim=-1).reshape(out_dim, -1).long()
vals = E2M1[codes].view(out_dim, -1, 16)
ref = (vals * (scale.float() * gscale).unsqueeze(-1)).reshape(out_dim, -1)
return packed, scale, gscale, ref.to(torch.bfloat16)


def _feed(proj, packed, scale, gscale, params, buf, loaded, pad=0):
names = [
(f"{PREFIX}.{proj}.weight_scale", scale),
(f"{PREFIX}.{proj}.weight", packed),
(f"{PREFIX}.{proj}.weight_scale_2", gscale),
]
return [_try_load_nvfp4_attn_proj(n, t, buf, params, loaded, pad) for n, t in names]


def test_nvfp4_q_a_and_kv_a_dequantize_into_bf16_fused_shards():
fused = _RecordingParam()
params = {f"{PREFIX}.fused_qkv_a_proj.weight": fused}
buf: dict = {}
loaded: set[str] = set()

q_packed, q_scale, q_gs, q_ref = _nvfp4(64, 128, seed=0)
kv_packed, kv_scale, kv_gs, kv_ref = _nvfp4(32, 128, seed=1)
assert all(_feed("q_a_proj", q_packed, q_scale, q_gs, params, buf, loaded, 8))
assert all(
_feed("kv_a_proj_with_mqa", kv_packed, kv_scale, kv_gs, params, buf, loaded, 8)
)

(q_w, q_shard), (kv_w, kv_shard) = fused.calls
assert (q_shard, kv_shard) == (0, 1)
assert q_w.dtype == torch.bfloat16
torch.testing.assert_close(q_w, q_ref)
# NoPE models pad the kv_a rope rows with zeros; q_a is not padded.
torch.testing.assert_close(kv_w[:32], kv_ref)
assert kv_w.shape == (40, 128) and not kv_w[32:].any()
assert loaded == {f"{PREFIX}.fused_qkv_a_proj.weight"}


def test_nvfp4_projection_with_quantized_target_uses_normal_path():
params = {
f"{PREFIX}.q_b_proj.weight": _RecordingParam(),
f"{PREFIX}.q_b_proj.weight_scale": _RecordingParam(),
}
packed, scale, gscale, _ = _nvfp4(64, 128, seed=2)
assert not any(_feed("q_b_proj", packed, scale, gscale, params, {}, set()))


def test_fp8_and_bf16_tensors_are_left_alone():
params = {f"{PREFIX}.fused_qkv_a_proj.weight": _RecordingParam()}
fp8 = torch.zeros(64, 128, dtype=torch.float8_e4m3fn)
bf16 = torch.zeros(64, 128, dtype=torch.bfloat16)
for t in (fp8, bf16):
assert not _try_load_nvfp4_attn_proj(
f"{PREFIX}.q_a_proj.weight", t, {}, params, set(), 0
)
96 changes: 94 additions & 2 deletions vllm/models/glm5next/common/model.py
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,9 @@
hc_expand,
)
from vllm.model_executor.layers.quantization import QuantizationConfig
from vllm.model_executor.layers.quantization.utils.nvfp4_emulation_utils import (
dequantize_to_dtype,
)
from vllm.model_executor.layers.quantization.utils.quant_utils import (
GroupShape,
scaled_dequantize,
Expand Down Expand Up @@ -880,6 +883,18 @@ def load_weights(self, weights: Iterable[tuple[str, torch.Tensor]]) -> set[str]:
):
continue

# NVFP4 checkpoint: same for MLA projections quantized to NVFP4.
# Runs first because the FP8 path also claims ``.weight_scale``.
if _try_load_nvfp4_attn_proj(
name,
loaded_weight,
_pending_wk_fp8,
params_dict,
loaded_params,
kv_a_pad_size,
):
continue

# FP8 checkpoint: dequantize BF16-kept MLA projections
# (q_a_proj / kv_a_proj_with_mqa / o_proj) to BF16.
if _try_load_fp8_attn_proj(
Expand Down Expand Up @@ -1344,6 +1359,24 @@ def _try_load_fp8_attn_proj(
buf[layer_prefix].pop(key, None)
block_size = weight_fp8.shape[1] // scale_inv.shape[1]
weight_bf16 = _dequant_fp8_block(weight_fp8, scale_inv, block_size)
_load_bf16_attn_proj(
weight_bf16,
params_dict[target_w],
shard_id,
is_kva,
kv_a_pad_size,
)
loaded_params.add(target_w)
return True


def _load_bf16_attn_proj(
weight_bf16: torch.Tensor,
param,
shard_id: int | None,
is_kva: bool,
kv_a_pad_size: int,
) -> None:
# NoPE: pad kv_a rope portion (kv_lora_rank -> kv_lora_rank + qk_rope_head_dim).
if is_kva and kv_a_pad_size > 0:
pad = torch.zeros(
Expand All @@ -1353,11 +1386,70 @@ def _try_load_fp8_attn_proj(
device=weight_bf16.device,
)
weight_bf16 = torch.cat([weight_bf16, pad], dim=0)

param = params_dict[target_w]
if shard_id is None:
param.weight_loader(param, weight_bf16)
else:
param.weight_loader(param, weight_bf16, shard_id)


def _try_load_nvfp4_attn_proj(
name,
tensor,
buf,
params_dict,
loaded_params,
kv_a_pad_size: int,
) -> bool:
"""Dequantize ModelOpt NVFP4 MLA projections that the model keeps in BF16.

NVFP4 checkpoints that quantize the MLA projections store a packed e2m1
``weight`` (uint8), e4m3 per-16 ``weight_scale`` and an fp32
``weight_scale_2``. ``fused_qkv_a_proj`` is always BF16, so when the target
has no ``weight_scale`` param these are dequantized to BF16; otherwise we
return False and the normal path loads the NVFP4 tensors as-is.
"""
matched = None
for suffix, info in _FP8_ATTN_PROJS.items():
if suffix in name:
matched = (suffix, info)
break
if matched is None:
return False
suffix, (key, target_base, shard_id, is_kva) = matched
if name.endswith(".weight") and tensor.dtype == torch.uint8:
part = "weight"
elif name.endswith(".weight_scale") and tensor.dtype == torch.float8_e4m3fn:
part = "scale"
elif name.endswith(".weight_scale_2"):
part = "weight_scale_2"
else:
return False

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Could we also ignore input_scale when the target projection is kept in BF16? vroomfondel/GLM-5.3-Flash-NVFP4-W4A4 stores it for q_b_proj and o_proj. Both are built with quant_config=None, so their weights are dequantized here, but input_scale falls through to params_dict[name] and raises a KeyError.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Fixed in be8e956. The shared main-model/MTP helper now consumes input_scale when the target has no activation-scale parameter. Quantized targets and registered scales keep the normal loader path.

The regression suite covers q_b_proj, o_proj and the fused projections, with activation scales before and after weight loading: 6 passed. The added BF16 cases failed before the fix. A separate CPU reproducer through both public loaders raised the reported KeyError in all 8 baseline cases; all 8 patched cases loaded and matched the BF16 weight and projection-output references exactly. Pre-commit and mypy-3.12 passed.

I have not rerun full serving of vroomfondel/GLM-5.3-Flash-NVFP4-W4A4.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Confirmed in be8e956a69; the input_scale case is covered now.


layer_prefix = name.rsplit(suffix, 1)[0]
target_w = f"{layer_prefix}.{target_base}.weight"
if target_w not in params_dict or (
f"{layer_prefix}.{target_base}.weight_scale" in params_dict
):
return False
entry = buf.setdefault(layer_prefix, {}).setdefault(f"nvfp4_{key}", {})
entry[part] = tensor
if not all(p in entry for p in ("weight", "scale", "weight_scale_2")):
return True

buf[layer_prefix].pop(f"nvfp4_{key}", None)
weight_bf16 = dequantize_to_dtype(
entry["weight"],
entry["scale"],
entry["weight_scale_2"].float(),
dtype=torch.bfloat16,
swizzle=False,
)
_load_bf16_attn_proj(
weight_bf16,
params_dict[target_w],
shard_id,
is_kva,
kv_a_pad_size,
)
loaded_params.add(target_w)
return True
10 changes: 10 additions & 0 deletions vllm/models/glm5next/common/mtp.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@
Glm5NextMoE,
_try_load_fp8_attn_proj,
_try_load_fp8_indexer_wk,
_try_load_nvfp4_attn_proj,
get_spec_layer_idx_from_weight_name,
)

Expand Down Expand Up @@ -343,6 +344,15 @@ def load_weights(self, weights: Iterable[tuple[str, torch.Tensor]]) -> set[str]:
# target model. The model holds fused_qkv_a_proj / o_proj in BF16,
# so the checkpoint's block-FP8 weight + weight_scale_inv for these
# has no param home and would KeyError without this dequant.
if _try_load_nvfp4_attn_proj(
name,
loaded_weight,
_pending_wk_fp8,
params_dict,
loaded_params,
kv_a_pad_size,
):
continue
if _try_load_fp8_attn_proj(
name,
loaded_weight,
Expand Down
Loading