Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
Show all changes
16 commits
Select commit Hold shift + click to select a range
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
83 changes: 82 additions & 1 deletion tests/kernels/moe/test_moe_weight_loading_padded.py
Original file line number Diff line number Diff line change
Expand Up @@ -106,9 +106,90 @@ def test_w2_per_channel_scale_is_untouched(self):
def test_block_scale_is_untouched(self):
# Block scales are [experts, 2 * intermediate / block, hidden / block]
scale = torch.randn(8, 16, 24)
result = RoutedExperts._orient_fused_weight(scale, "w1", self.HIDDEN)
result = RoutedExperts._orient_fused_weight(
scale,
"w1",
self.HIDDEN,
target_shape=torch.Size((8, 16, 24)),
)
assert result.shape == (8, 16, 24)

def test_padded_target_does_not_guess_block_scale_orientation(self):
# Both orientations fit inside a target padded on both axes. Without
# quantization-layout metadata there is no sound way to choose one.
scale = torch.randn(8, 6, 16)
result = RoutedExperts._orient_fused_weight(
scale,
"w2",
unpadded_hidden=2048,
target_shape=torch.Size((8, 24, 24)),
)
assert result.shape == (8, 6, 16)

def test_square_target_does_not_guess_orientation(self):
scale = torch.arange(8 * 16 * 16).reshape(8, 16, 16)
result = RoutedExperts._orient_fused_weight(
scale,
"w1",
unpadded_hidden=2048,
target_shape=torch.Size((8, 16, 16)),
)
assert result.data_ptr() == scale.data_ptr()
torch.testing.assert_close(result, scale)

@pytest.mark.parametrize(
("shard_id", "checkpoint_shape", "target_shape"),
[
# Qwen3-VL stores block scales in checkpoint weight orientation.
("w1", (8, 16, 12), (8, 12, 16)),
("w2", (8, 6, 16), (8, 16, 6)),
],
)
def test_qwen3_vl_transposed_block_scale_matches_target(
self,
shard_id: str,
checkpoint_shape: tuple[int, ...],
target_shape: tuple[int, ...],
):
scale = torch.arange(torch.tensor(checkpoint_shape).prod()).reshape(
checkpoint_shape
)
result = RoutedExperts._orient_fused_weight(
scale,
shard_id,
unpadded_hidden=2048,
target_shape=torch.Size(target_shape),
)
assert result.shape == target_shape
torch.testing.assert_close(result, scale.transpose(-1, -2))

@pytest.mark.parametrize(
("shard_id", "checkpoint_shape", "target_shape"),
[
("w1", (8, 16, 12), (8, 6, 16)),
("w2", (8, 6, 16), (8, 16, 3)),
],
)
def test_qwen3_vl_transposed_block_scale_matches_tp_shard(
self,
shard_id: str,
checkpoint_shape: tuple[int, ...],
target_shape: tuple[int, ...],
):
scale = torch.arange(torch.tensor(checkpoint_shape).prod()).reshape(
checkpoint_shape
)
result = RoutedExperts._orient_fused_weight(
scale,
shard_id,
unpadded_hidden=2048,
target_shape=torch.Size(target_shape),
tp_size=2,
)
expected_shape = (8, 12, 16) if shard_id == "w1" else (8, 16, 6)
assert result.shape == expected_shape
torch.testing.assert_close(result, scale.transpose(-1, -2))


class TestNarrowExpertDataForPadding:
"""Unit tests for _narrow_expert_data_for_padding."""
Expand Down
47 changes: 43 additions & 4 deletions vllm/model_executor/layers/fused_moe/routed_experts.py
Original file line number Diff line number Diff line change
Expand Up @@ -423,14 +423,19 @@ def _get_hidden_dim(shard_dim: int, ndim: int) -> int:

@staticmethod
def _orient_fused_weight(
fused_weight: torch.Tensor, shard_id: str, unpadded_hidden: int
fused_weight: torch.Tensor,
shard_id: str,
unpadded_hidden: int,
target_shape: torch.Size | None = None,
tp_size: int = 1,
) -> torch.Tensor:
"""Normalise a fused expert tensor from either checkpoint orientation
to (intermediate, hidden) for w1/w3 and (hidden, intermediate) for w2.

Only transposes when the hidden dim is definitively on the wrong axis,
leaving tensors that have no hidden dim alone (e.g. a fused per-channel
scale, (2 * intermediate, 1)).
or when the transposed shape exactly matches the target parameter. The
latter resolves block scales, whose dimensions are both divided by the
block size and therefore do not contain the hidden size directly.
"""
if shard_id == "w2":
hidden_axis, intermediate_axis = -2, -1
Expand All @@ -441,6 +446,24 @@ def _orient_fused_weight(
and fused_weight.shape[intermediate_axis] == unpadded_hidden
):
return fused_weight.transpose(-1, -2)

if target_shape is not None and len(target_shape) >= 2:
# The caller only supplies canonical, TP-sharded block-scale
# targets. ``param`` is TP-local, whereas a fused checkpoint tensor
# contains the global intermediate dimension. Reconstruct that
# global shape: w1/w3 shard their first data axis and w2 its second.
expected_global_shape = list(target_shape[-2:])
tp_shard_axis = 1 if shard_id == "w2" else 0

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.

expected_global_shape[tp_shard_axis] *= tp_size
checkpoint_shape = list(fused_weight.shape[-2:])
# This is only a tie-breaker: require an exact reversed-shape
# match so padded, square, or otherwise ambiguous layouts are
# never guessed.
if (
checkpoint_shape != expected_global_shape
and checkpoint_shape[::-1] == expected_global_shape
):
return fused_weight.transpose(-1, -2)
return fused_weight

@staticmethod
Expand Down Expand Up @@ -938,11 +961,27 @@ def load_weights(
param_name = weight_name.removeprefix(f"{self.layer_name}.")
param = getattr(self, param_name)
if is_fused:
# PR #50137's hidden-axis heuristic cannot orient block
# scales because both dimensions are divided by the block
# size. Use the exact destination shape only for canonical,
# TP-sharded BLOCK parameters. Other quant formats may use
# transposed storage or replicated/full axes, for which
# shard_id alone does not describe the target layout.
can_match_block_target = (
getattr(param, "quant_method", None)
== FusedMoeWeightScaleSupported.BLOCK.value
and not getattr(param, "is_transposed", False)
and not getattr(param, "load_full_w2", False)
)
# w1 and w3 share one fused tensor; use a local copy so the
# transpose below doesn't mutate loaded_weight across
# iterations (else w3 is transposed twice and wrongly chunked)
fused_weight = self._orient_fused_weight(
loaded_weight, shard_id, unpadded_hidden
loaded_weight,
shard_id,
unpadded_hidden,
target_shape=param.shape if can_match_block_target else None,
tp_size=self.moe_config.tp_size,
)
if shard_id in {"w1", "w3"}:
# Repurpose expert_id for deconcatenating w1 and w3
Expand Down
Loading