From efb62ce269b499123e2d1c89005ee4cea8c31098 Mon Sep 17 00:00:00 2001
From: debanshd
Date: Mon, 5 Oct 2026 08:01:37 -0700
Subject: [PATCH] [diffusion] fix: resolve QKV layout inference for MiniMax-H3
checkpoints (#40158)
Signed-off-by: Debanshu Das
---
.../configs/models/dits/minimax_h3.py | 1 +
.../runtime/models/dits/minimax_h3.py | 47 ++++++++++---------
.../test/unit/test_comfyui_h3.py | 33 +++++++++++++
3 files changed, 58 insertions(+), 23 deletions(-)
diff --git a/python/sglang/multimodal_gen/configs/models/dits/minimax_h3.py b/python/sglang/multimodal_gen/configs/models/dits/minimax_h3.py
index 934fda1f72..4c932bb2c4 100644
--- a/python/sglang/multimodal_gen/configs/models/dits/minimax_h3.py
+++ b/python/sglang/multimodal_gen/configs/models/dits/minimax_h3.py
@@ -126,6 +126,7 @@ class MiniMaxH3DiTArchConfig(DiTArchConfig):
final_norm_eps: float = 1e-5
qkv_checkpoint_grouped: bool = True
checkpoint_uses_diffusers_layout: bool = False
+ checkpoint_qkv_layout: str | None = None
adaln_affine_input_dim: int | None = None
has_gate_compress: bool = False
# VDN-H3: None for the dense model; set from transformer/config.json
diff --git a/python/sglang/multimodal_gen/runtime/models/dits/minimax_h3.py b/python/sglang/multimodal_gen/runtime/models/dits/minimax_h3.py
index 1c83cecab7..2443c16e91 100644
--- a/python/sglang/multimodal_gen/runtime/models/dits/minimax_h3.py
+++ b/python/sglang/multimodal_gen/runtime/models/dits/minimax_h3.py
@@ -7,14 +7,15 @@ contract accepts packed inference keyword arguments and returns packed logits.
from __future__ import annotations
+import itertools
import math
import os
from collections import defaultdict
-from collections.abc import Iterable, Iterator
-from typing import Any, Callable
+from collections.abc import Callable, Iterable, Iterator
+from typing import Any
import torch
-import torch.nn as nn
+from torch import nn
from torch.distributed.tensor import DTensor
from sglang.kernels.ops.activation.activation import (
@@ -739,10 +740,7 @@ def _minimax_h3_attention_core_impl(
and impl._sparse_ready(q, k)
and any(
stop - start >= impl.schedule.min_seq_len
- for start, stop in zip(
- cu_seqlens_host[:-1],
- cu_seqlens_host[1:],
- )
+ for start, stop in itertools.pairwise(cu_seqlens_host)
)
)
if sparse_will_run and subblock_sparse_query_block_mask is None:
@@ -825,17 +823,20 @@ class MiniMaxH3Attention(nn.Module):
quant_config=quant_config,
prefix=f"{prefix}.qkv_proj",
)
- # Official safetensors interleave Q/K/V by head. Comfy BF16, Comfy
- # convrot int8, and GGUF already store [q_all, k_all, v_all].
- skip_grouped_reorder = not getattr(arch, "qkv_checkpoint_grouped", True)
- checkpoint_qkv_is_native = quant_config is not None and (
- quant_config.get_name() == "gguf"
- or quant_config.checkpoint_uses_native_qkv_layout
- )
- checkpoint_qkv_is_native = (
- checkpoint_qkv_is_native or arch.checkpoint_uses_diffusers_layout
- )
- if not skip_grouped_reorder and not checkpoint_qkv_is_native:
+ # explicit layout overrides checkpoint metadata and quantization inference
+ if arch.checkpoint_qkv_layout is not None:
+ checkpoint_qkv_is_native = arch.checkpoint_qkv_layout == "native"
+ else:
+ checkpoint_qkv_is_native = quant_config is not None and (
+ quant_config.get_name() == "gguf"
+ or quant_config.checkpoint_uses_native_qkv_layout
+ )
+ checkpoint_qkv_is_native = (
+ checkpoint_qkv_is_native
+ or arch.checkpoint_uses_diffusers_layout
+ or not arch.qkv_checkpoint_grouped
+ )
+ if not checkpoint_qkv_is_native:
self._install_qkv_weight_loader(arch)
self.q_norm = _norm(arch.attention_head_dim, eps=arch.qk_norm_eps)
self.k_norm = _norm(arch.attention_head_dim, eps=arch.qk_norm_eps)
@@ -1026,7 +1027,7 @@ class MiniMaxH3Attention(nn.Module):
else tuple(int(item) for item in cu_seqlens.tolist())
)
out = torch.empty_like(x)
- for sequence_start, sequence_stop in zip(bounds[:-1], bounds[1:]):
+ for sequence_start, sequence_stop in itertools.pairwise(bounds):
if sequence_start == sequence_stop:
continue
keys = key[sequence_start:sequence_stop].unsqueeze(0)
@@ -1711,18 +1712,18 @@ def _reject_adaln_lora(names: list[str]) -> None:
class MiniMaxH3DiTModel(SpectrumMixin, BaseDiT, LayerwiseOffloadableModuleMixin):
- _aliases = [
+ _aliases = (
"MiniMaxH3Transformer3DModel",
"MiniMaxH3PrunedTransformer3DModel",
- ]
- _fsdp_shard_conditions = [is_block]
+ )
+ _fsdp_shard_conditions = (is_block,)
# refine_prompt_embeds drives a forward pass outside __call__.
_fsdp_forward_methods = ("refine_prompt_embeds",)
# parameters mix fp32 (patch projections, timestep embedder, and output
# heads) with bf16 blocks; FSDP must gather in each parameter's own dtype
_fsdp_mixed_dtype_params = True
mps_stream_non_layer_weights = True
- _compile_conditions = [is_block]
+ _compile_conditions = (is_block,)
param_names_mapping = _ARCH_DEFAULTS.param_names_mapping
reverse_param_names_mapping = _ARCH_DEFAULTS.reverse_param_names_mapping
lora_param_names_mapping = _ARCH_DEFAULTS.lora_param_names_mapping
diff --git a/python/sglang/multimodal_gen/test/unit/test_comfyui_h3.py b/python/sglang/multimodal_gen/test/unit/test_comfyui_h3.py
index 26c016e80d..74a554235d 100644
--- a/python/sglang/multimodal_gen/test/unit/test_comfyui_h3.py
+++ b/python/sglang/multimodal_gen/test/unit/test_comfyui_h3.py
@@ -1100,6 +1100,39 @@ def test_concat_qkv_attention_skips_grouped_weight_loader() -> None:
assert grouped_weight.rank_local_weight_transform is not None
+@pytest.mark.parametrize("layout", [None, "native", "interleaved"])
+@pytest.mark.parametrize("grouped", [True, False])
+@pytest.mark.parametrize("diffusers", [True, False])
+def test_explicit_checkpoint_qkv_layout_overrides_inferred_layout(
+ layout, grouped, diffusers
+):
+ _ensure_single_process_parallel_runtime()
+ arch = MiniMaxH3DiTArchConfig(
+ hidden_size=32,
+ num_attention_heads=2,
+ attention_head_dim=16,
+ checkpoint_qkv_layout=layout,
+ qkv_checkpoint_grouped=grouped,
+ checkpoint_uses_diffusers_layout=diffusers,
+ )
+ attention = MiniMaxH3Attention(arch, None, prefix="blocks.0.attn")
+ weight = attention.qkv_proj.weight
+ loaded = torch.arange(weight.numel(), dtype=torch.float32).reshape(weight.shape)
+ weight.weight_loader(weight, loaded)
+
+ reorder = (
+ layout == "interleaved" if layout is not None else grouped and not diffusers
+ )
+ expected = (
+ _reorder_grouped_qkv_to_qkv(
+ loaded, num_query_groups=2, heads_per_group=1, head_dim=16
+ )
+ if reorder
+ else loaded
+ )
+ torch.testing.assert_close(weight, expected.to(weight))
+
+
@pytest.mark.parametrize("backend,out_features", [("comfy_kitchen", 12), ("jit", 16)])
def test_integrated_h3_int8_loader_preserves_quantized_weights(
tmp_path, monkeypatch, backend, out_features