Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
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
14 changes: 14 additions & 0 deletions defuser/modeling/unfused_moe/common.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,20 @@
from torch import nn


def router_logits_from_output(router_output):
"""Return raw router logits from a router tensor or the Transformers 5.22 tuple.

Transformers 5.22 routers return ``(router_logits, topk_weights,
topk_indices)``. Defuser keeps its own grouped top-k selection, so it only
needs the raw logits; the router's precomputed top-k is intentionally
discarded so the routing math stays byte-identical across Transformers
versions.
"""
if isinstance(router_output, tuple):
return router_output[0]
return router_output


def run_routed_experts(
experts: nn.ModuleList,
hidden_states: torch.Tensor,
Expand Down
17 changes: 13 additions & 4 deletions defuser/modeling/unfused_moe/glm4_moe.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@
import torch
import torch.nn as nn

from .common import router_logits_from_output

class LinearGlm4MoeMoE(nn.Module):
"""
A mixed expert module containing shared experts.
Expand Down Expand Up @@ -34,9 +36,16 @@ def __init__(self, config):
self.routed_scaling_factor = config.routed_scaling_factor
self.top_k = config.num_experts_per_tok

def route_tokens_to_experts(self, router_logits: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]:
"""Replicate GLM4's grouped expert selection and top-k weight normalization."""
def route_tokens_to_experts(self, router_logits) -> tuple[torch.Tensor, torch.Tensor]:
"""Replicate GLM4's grouped expert selection and top-k weight normalization.

Accepts either the raw logits tensor or the Transformers 5.22 router
output ``(router_logits, topk_weights, topk_indices)``. Only the logits
are used: Defuser re-derives the top-k selection below, so the router's
precomputed weights and indices would change its routing math.
"""
# Keep the expert selection identical to the upstream GLM4 MoE router.
router_logits = router_logits_from_output(router_logits)
router_logits = router_logits.sigmoid()
router_logits_for_choice = router_logits + self.gate.e_score_correction_bias
group_scores = (
Expand Down Expand Up @@ -87,8 +96,8 @@ def forward(self, hidden_states):
"""Apply routed experts plus the shared expert branch, matching upstream GLM4 MoE."""
residuals = hidden_states
orig_shape = hidden_states.shape
router_logits = self.gate(hidden_states)
topk_indices, topk_weights = self.route_tokens_to_experts(router_logits)
router_output = self.gate(hidden_states)
topk_indices, topk_weights = self.route_tokens_to_experts(router_output)
hidden_states = hidden_states.view(-1, hidden_states.shape[-1])
hidden_states = self.moe(hidden_states, topk_indices, topk_weights).view(*orig_shape)
hidden_states = hidden_states + self.shared_experts(residuals)
Expand Down
12 changes: 10 additions & 2 deletions defuser/modeling/unfused_moe/glm4_moe_lite.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,8 @@
import torch
import torch.nn as nn

from .common import router_logits_from_output

class LinearGlm4MoeLiteMoE(nn.Module):
"""
A mixed expert module containing shared experts.
Expand Down Expand Up @@ -65,6 +67,12 @@ def experts_forward(
return final_hidden_states

def route_tokens_to_experts(self, router_logits):
"""Accept raw logits or the Transformers 5.22 ``(logits, weights, indices)`` tuple.

Defuser re-derives the grouped top-k selection below, so only the logits
are used; the router's precomputed top-k would change the routing math.
"""
router_logits = router_logits_from_output(router_logits)
router_logits = router_logits.sigmoid()
router_logits_for_choice = router_logits + self.gate.e_score_correction_bias
group_scores = (
Expand Down Expand Up @@ -92,8 +100,8 @@ def route_tokens_to_experts(self, router_logits):
def forward(self, hidden_states):
residuals = hidden_states
orig_shape = hidden_states.shape
router_logits = self.gate(hidden_states)
topk_indices, topk_weights = self.route_tokens_to_experts(router_logits)
router_output = self.gate(hidden_states)
topk_indices, topk_weights = self.route_tokens_to_experts(router_output)
hidden_states = hidden_states.view(-1, hidden_states.shape[-1])
hidden_states = self.experts_forward(hidden_states, topk_indices, topk_weights).view(*orig_shape)
hidden_states = hidden_states + self.shared_experts(residuals)
Expand Down
2 changes: 1 addition & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ build-backend = "setuptools.build_meta"

[project]
name = "Defuser"
version = "0.0.30"
version = "0.0.31"
description = "Model defuser helper for HF Transformers."
readme = "README.md"
requires-python = ">=3.9"
Expand Down
55 changes: 55 additions & 0 deletions tests/test_convert_model.py
Original file line number Diff line number Diff line change
Expand Up @@ -1190,6 +1190,61 @@ def test_glm4_moe_lite_defused_forward_matches_fused_math():
hidden_states,
)


@pytest.mark.parametrize(
("config_factory", "block_cls"),
[
(_tiny_glm4_moe_config, LinearGlm4MoeMoE),
(lambda: _tiny_moe_config(Glm4MoeLiteConfig), LinearGlm4MoeLiteMoE),
],
)
def test_glm4_route_tokens_accepts_tuple_and_tensor_equivalently(config_factory, block_cls):
"""Transformers 5.22 routers return ``(logits, weights, indices)``.

The replacement block must unwrap the tuple while keeping Defuser's grouped
top-k routing math identical to the plain-logits path.
"""

config = config_factory()
block = block_cls(config).eval()
hidden_states = torch.randn(2, 3, config.hidden_size, dtype=torch.float32)
with torch.no_grad():
router_output = block.gate(hidden_states)
logits = router_output[0] if isinstance(router_output, tuple) else router_output

with torch.no_grad():
tuple_indices, tuple_weights = block.route_tokens_to_experts((logits, None, None))
tensor_indices, tensor_weights = block.route_tokens_to_experts(logits)

torch.testing.assert_close(tuple_indices, tensor_indices, rtol=0, atol=0)
torch.testing.assert_close(tuple_weights, tensor_weights, rtol=0, atol=0)


@pytest.mark.parametrize(
("model_type", "config_factory", "model_cls"),
[
("glm4_moe", _tiny_glm4_moe_config, Glm4MoeForCausalLM),
(
"glm4_moe_lite",
lambda: _tiny_moe_config(Glm4MoeLiteConfig, num_hidden_layers=2),
Glm4MoeLiteForCausalLM,
),
],
)
def test_defused_glm4_model_forward_accepts_router_tuple(model_type, config_factory, model_cls):
"""The installed Transformers router return shape must not crash a defused model."""

replace_fused_blocks(model_type)
model = model_cls(config_factory()).eval()
input_ids = torch.tensor([[1, 2, 3, 4]])

with torch.no_grad():
logits = model(input_ids=input_ids).logits

assert logits.shape == (1, 4, model.config.vocab_size)
assert torch.isfinite(logits).all()


def test_glm4v_checkpoint_mapping_splits_gate_up_proj():
from defuser.defuser import get_checkpoint_conversion_mapping

Expand Down
Loading