[Feature][MiniMax-H3] Complete VSA and Ulysses support (#6909)

Signed-off-by: princepride <wangzhipeng628@gmail.com>
Signed-off-by: 汪志鹏 <wangzhipeng628@gmail.com>
This commit is contained in:
汪志鹏 authored and GitHub committed 2026-09-02 07:19:21 -04:00
1 parent 57c08d34c3
commit c59b48b47e
17 files changed
+953 -35

No files matched your search

@@ -136,7 +136,23 @@ class MiniMaxH3DenoiseBranch:
)
for span in raw_spans
)
self.static_kwargs["video_token_layout"] = VideoTokenLayout(used_len=int(cu[1]), video_spans=spans)
target_start = next(span.start for span in reversed(spans) if span.role == "target")
prefix_tags = token_tags[:target_start]
prefix_segments: list[int] = []
if prefix_tags.numel():
# Run-lengths preserve modality/reference boundaries without
# carrying CUDA tensors into every attention layer.
boundaries = torch.nonzero(prefix_tags[1:] != prefix_tags[:-1]).flatten().tolist()
starts = [0, *(index + 1 for index in boundaries)]
stops = [*(index + 1 for index in boundaries), target_start]
prefix_segments = [stop - start for start, stop in zip(starts, stops, strict=True)]
self.static_kwargs["video_token_layout"] = VideoTokenLayout(
used_len=int(cu[1]),
video_spans=spans,
)
# FastH3-specific prefix geometry belongs to MiniMax-H3's packed
# attention contract, not the shared VideoTokenLayout interface.
self.static_kwargs["packed_seq_params"]["vsa_prefix_segments"] = tuple(prefix_segments)
else:
grid = packed["latent_grid"].tolist()
self.static_kwargs["video_token_layout"] = VideoTokenLayout(
+87 -11
View File
@@ -114,6 +114,7 @@ _BLOCK_TARGETS = {
"attn.to_k": ("attn.qkv_proj", _QKV_K),
"attn.to_v": ("attn.qkv_proj", _QKV_V),
"attn.to_out.0": ("attn.out_proj", _PLAIN),
"attn.to_gate_compress": ("attn.to_gate_compress", _PLAIN),
"ff.net.0.proj": ("mlp.fc1", _SWAP_HALVES),
"ff.net.2": ("mlp.fc2", _PLAIN),
"adaln_proj.linear": ("adaln_proj.linear", _PLAIN),
@@ -121,6 +122,11 @@ _BLOCK_TARGETS = {
"norm2": ("norm2", _PLAIN),
}
# The attention role MiniMaxH3Attention gives its 50 DiT blocks. The
# compression gates live on exactly these layers, so this is the role whose
# resolved backend decides whether the artifact runs sparse.
_H3_DIT_ATTENTION_ROLE = "self"
# Adapter block prefix -> native block prefix.
_BLOCK_PREFIXES = (
("token_refiner.refiner_blocks.", "token_refiner.blocks."),
@@ -128,6 +134,26 @@ _BLOCK_PREFIXES = (
)
def _resolve_dit_attention_backend(od_config: Any) -> str:
"""The backend the 50-block H3 DiT will actually resolve to.
The DiT's attention layers carry role ``"self"``, so a ``per_role`` entry
overrides the default for exactly the layers the compression gates live on.
Reading only the default would accept a config that runs the sparse student
dense, and reject a per-role-only config that is correct.
"""
attention_config = getattr(od_config, "diffusion_attention_config", None)
per_role = getattr(attention_config, "per_role", None) or {}
spec = per_role.get(_H3_DIT_ATTENTION_ROLE)
if spec is not None:
return str(getattr(spec, "backend", "") or "").upper()
backend = str(getattr(od_config, "diffusion_attention_backend", "") or "").upper()
if backend:
return backend
default_spec = getattr(attention_config, "default", None)
return str(getattr(default_spec, "backend", "") or "").upper()
class FastH3AdapterError(ValueError):
"""The artifact is a FastH3 adapter, but it cannot be applied as one."""
@@ -305,11 +331,16 @@ class FastH3WeightFusion:
patches: Mapping[str, _ParamPatch],
head_dim: int,
requires_vsa: bool,
injections: Mapping[str, torch.Tensor] | None = None,
) -> None:
self._source = source
self._patches = dict(patches)
self._head_dim = head_dim
self.requires_vsa = requires_vsa
# Parameters the base checkpoint does not carry, assigned into the
# stream instead of fused onto an existing weight.
self._injections = dict(injections or {})
self._injected: set[str] = set()
self._applied: set[str] = set()
self._device: torch.device | None = None
@@ -352,6 +383,7 @@ class FastH3WeightFusion:
patches: dict[str, _ParamPatch] = {}
gate_tensors: list[str] = []
injections: dict[str, torch.Tensor] = {}
unmapped: list[str] = []
blocks_seen: dict[str, set[int]] = {}
counted = {"low_rank_tensors": 0, "diff_tensors": 0}
@@ -365,12 +397,20 @@ class FastH3WeightFusion:
unmapped.append(name)
continue
module, role = split
if role == "set_weight":
# A VSA compression gate: a module the base transformer does
# not have, so there is nothing to fuse it into.
gate_tensors.append(name)
continue
target = _resolve_native_target(module)
if role == "set_weight":
# A VSA compression gate. The base transformer has no such
# parameter, so this is assigned into the stream rather than
# fused onto an existing weight.
if target is None:
unmapped.append(name)
continue
native_module, _, block = target
if block is not None:
blocks_seen.setdefault(block[0], set()).add(block[1])
gate_tensors.append(name)
injections[f"{native_module}.weight"] = checkpoint.get_tensor(name)
continue
if target is None:
unmapped.append(name)
continue
@@ -422,6 +462,7 @@ class FastH3WeightFusion:
patches=patches,
head_dim=head_dim,
requires_vsa=bool(gate_tensors),
injections=injections,
)
logger.info(
"FastH3 adapter %s: rank=%s, parameters patched=%d, low-rank=%s, diff=%s, set_weight=%d",
@@ -510,24 +551,48 @@ class FastH3WeightFusion:
# server would serve base H3 weights on the student's ladder.
raise FastH3AdapterError(f"{self._source} has already been fused into this checkpoint")
for name, weight in weights:
if name in self._injections:
raise FastH3AdapterError(
f"the checkpoint already provides {name}, which this adapter assigns; "
"assigning it would discard the checkpoint's own weight"
)
yield name, self.fuse(name, weight)
# The VSA gates have no counterpart in the base checkpoint, so they join
# the stream after it rather than being folded into one of its tensors.
for name, weight in self._injections.items():
self._injected.add(name)
yield name, weight
def validate_fully_applied(self) -> None:
def validate_fully_applied(self, loaded: Iterable[str] | None = None) -> None:
"""Close the fusion: every edit must have met its parameter.
A silently unapplied delta is the failure mode that matters here: the
model would load and generate, just not as the distilled student. The
weights are loaded once, so the mapped payloads are dropped afterwards
rather than held for the life of the process.
``loaded`` is the set of parameter names ``load_weights`` actually
consumed. A gate is assigned rather than fused, so it lands on a module
the base transformer does not have; if that module was never built,
``load_weights`` only logs a skip and the server would serve a
zero-initialized gate. Yielding a tensor is not evidence it arrived, so
the injections are closed against that set when it is available.
"""
missing = sorted(set(self._patches) - self._applied)
if missing:
raise FastH3AdapterError(
f"FastH3 adapter edits {len(missing)} parameters the checkpoint never provided: {missing[:5]}"
)
arrived = self._injected if loaded is None else set(loaded)
uninjected = sorted(set(self._injections) - arrived)
if uninjected:
raise FastH3AdapterError(
f"FastH3 adapter assigns {len(uninjected)} parameters that never reached the model: {uninjected[:5]}"
)
for patch in self._patches.values():
patch.low_rank.clear()
patch.diff = None
self._injections.clear()
def check_serving_contract(
self,
@@ -555,11 +620,22 @@ class FastH3WeightFusion:
f"{sorted(offloads)}. Serve it without offload."
)
if self.requires_vsa:
raise ValueError(
f"{self.source} is a Video Sparse Attention variant of FastH3, and its "
"compression gates have no counterpart in vLLM-Omni's dense H3 attention. Use the "
"release's Dense variant until VSA lands for H3's packed sequence."
)
backend = _resolve_dit_attention_backend(od_config)
if backend != "FASTVIDEO_VSA":
raise ValueError(
f"{self.source} is a Video Sparse Attention variant of FastH3. Its compression "
"gates only mean anything to the VSA kernel, and any other backend would run it "
f"as dense attention on a student distilled for 90% sparsity (got {backend or 'default'}). "
"Serve it with --diffusion-attention-backend FASTVIDEO_VSA."
)
parallel_config = getattr(od_config, "parallel_config", None)
ring_degree = int(getattr(parallel_config, "ring_degree", 1) or 1)
allgather_degree = int(getattr(parallel_config, "allgather_degree", 1) or 1)
if ring_degree != 1 or allgather_degree != 1:
raise ValueError(
"FastH3 VSA supports local attention or pure Ulysses sequence parallelism; "
"ring/all-gather SP does not give the block-sparse kernel the complete packed sequence."
)
logger.info(
"FastH3 adapter active: sigma points %s for %d transformer forwards, "
"flow_shift=%g, audio_flow_shift=%g, tasks=%s",
@@ -422,6 +422,13 @@ class MiniMaxH3Attention(nn.Module):
quant_config=quant_config,
prefix=f"{prefix}.out_proj",
)
# VSA compression gate. A FastH3 VSA artifact assigns this projection
# with ``.set_weight``; the dense path never builds it, so the module is
# created only once the loader knows a VSA artifact is coming.
self.to_gate_compress: ColumnParallelLinear | None = None
self._gate_hidden_size = arch.hidden_size
self._gate_quant_config = quant_config
self._gate_prefix = f"{prefix}.to_gate_compress"
self.attention = Attention(
num_heads=self.num_heads,
num_kv_heads=self.num_kv_heads,
@@ -436,6 +443,26 @@ class MiniMaxH3Attention(nn.Module):
prefix=prefix,
)
def enable_vsa_gate(self) -> None:
"""Build the VSA compression gate this attention would otherwise lack.
Called before ``load_weights`` so the artifact's ``.set_weight`` tensor
has a parameter to land on. Zero-initialized like the Wan VSA layers, so
a gate that never receives weights degrades to sparse-only selection
rather than to garbage.
"""
if self.to_gate_compress is not None:
return
self.to_gate_compress = ColumnParallelLinear(
self._gate_hidden_size,
self.total_num_heads * self.head_dim,
bias=False,
params_dtype=_BF16_DTYPE,
quant_config=self._gate_quant_config,
prefix=self._gate_prefix,
)
nn.init.zeros_(self.to_gate_compress.weight)
def _apply_rope(self, x: torch.Tensor, freqs: torch.Tensor) -> torch.Tensor:
"""Rotate the first rot_dim head dims; pass the rest through.
@@ -461,6 +488,8 @@ class MiniMaxH3Attention(nn.Module):
packed_total: int,
num_requests: int = 1,
video_layout: VideoTokenLayout | None = None,
vsa_prefix_segments: tuple[int, ...] = (),
gate_compress: torch.Tensor | None = None,
) -> torch.Tensor:
"""Run packed attention as a small eager island.
@@ -539,6 +568,16 @@ class MiniMaxH3Attention(nn.Module):
# (see MINIMAX_H3_LASER_INPUT_SCALE). Ignored by every other
# backend/path.
"laser_input_scale": MINIMAX_H3_LASER_INPUT_SCALE,
# Present only for a VSA artifact; the VSA backend reads it as
# the learned compression gate and every other backend ignores it.
**({"gate_compress": gate_compress.unsqueeze(0)} if gate_compress is not None else {}),
# FastH3 uses segment-pure prefix chunks. The target video and
# its true 3-D shape remain in the shared typed video layout.
**(
{"vsa_h3_prefix_segments": vsa_prefix_segments}
if gate_compress is not None and video_layout is not None and video_layout.video_spans
else {}
),
},
video_layout=video_layout,
)
@@ -560,6 +599,7 @@ class MiniMaxH3Attention(nn.Module):
num_requests: int = 1,
sp_seq_lens: list[int] | None = None,
video_layout: VideoTokenLayout | None = None,
vsa_prefix_segments: tuple[int, ...] = (),
) -> torch.Tensor:
"""x: [T, hidden] packed thd rows -> [T, hidden].
@@ -593,6 +633,15 @@ class MiniMaxH3Attention(nn.Module):
self.q_norm.variance_epsilon,
)
# The gate is projected from the same local rows as Q. Pure Ulysses
# reshards it alongside Q/K/V in UlyssesParallelAttention so each VSA
# rank receives the full sequence for its local head shard.
gate_compress = None
if self.to_gate_compress is not None:
gate_result = self.to_gate_compress(x)
gate_compress = gate_result[0] if isinstance(gate_result, tuple) else gate_result
gate_compress = gate_compress.view(total, self.num_heads, self.head_dim)
# Each request contributes a document for its rows plus one for any
# nonempty alignment padding. Local/Ulysses backends unpad it, while
# Ring keeps aligned rows for fixed-size P2P buffers.
@@ -608,6 +657,8 @@ class MiniMaxH3Attention(nn.Module):
packed_total=packed_total if packed_total is not None else q.shape[0],
num_requests=num_requests,
video_layout=video_layout,
vsa_prefix_segments=vsa_prefix_segments,
gate_compress=gate_compress,
)
out = out.reshape(total, self.num_heads * self.head_dim)
out, _ = self.out_proj(out)
@@ -826,6 +877,7 @@ class MiniMaxH3DiTBlock(nn.Module):
num_requests: int = 1,
sp_seq_lens: list[int] | None = None,
video_layout: VideoTokenLayout | None = None,
vsa_prefix_segments: tuple[int, ...] = (),
) -> torch.Tensor:
"""x: [T, H]; t_emb: [M, t_dim]; combined_indices: [T]
(= inverse_indices * modality_num + token_tags.clamp(min=0)).
@@ -861,6 +913,7 @@ class MiniMaxH3DiTBlock(nn.Module):
num_requests=num_requests,
sp_seq_lens=sp_seq_lens,
video_layout=video_layout,
vsa_prefix_segments=vsa_prefix_segments,
)
x, h = indexed_gate_rms_norm_scale_shift(
residual,
@@ -1130,6 +1183,7 @@ class MiniMaxH3DiTModel(nn.Module):
self.sp_prepare = MiniMaxH3SPPrepare()
self.local_sp_prepare = MiniMaxH3SPPrepare()
self.sp_gather = MiniMaxH3SPGather()
self.vsa_gates_enabled = False
self.final_layer = MiniMaxH3FinalLayer(
arch,
quant_config,
@@ -1137,6 +1191,20 @@ class MiniMaxH3DiTModel(nn.Module):
)
self._mark_missing_params_required()
def enable_vsa_gates(self) -> None:
"""Give every DiT block's attention a VSA compression gate.
A FastH3 VSA artifact assigns these projections rather than adding to
them, so they have to exist before the weight stream reaches them. The
token refiner is left alone: the artifact carries gates for the 50 DiT
blocks only.
"""
if self.vsa_gates_enabled:
return
for block in self.blocks:
block.attn.enable_vsa_gate()
self.vsa_gates_enabled = True
def _mark_missing_params_required(self) -> None:
for _, param in self.named_parameters():
param.missing_param_init = "error"
@@ -1399,6 +1467,7 @@ class MiniMaxH3DiTModel(nn.Module):
# attention never reads cu_seqlens scalars off the device; a producer
# that omits it is packing a single request.
num_requests = int(self._psp_optional(psp, "num_requests", 1))
vsa_prefix_segments = tuple(int(length) for length in self._psp_optional(psp, "vsa_prefix_segments", ()))
refiner_psp = _required_kwarg(kwargs, "refiner_packed_seq_params")
refiner_cu = self._psp_field(refiner_psp, "refiner_packed_seq_params", "cu_seqlens_q").to(torch.int32)
refiner_max = int(self._psp_field(refiner_psp, "refiner_packed_seq_params", "max_seqlen_q"))
@@ -1480,6 +1549,7 @@ class MiniMaxH3DiTModel(nn.Module):
packed_total=seq_len,
num_requests=num_requests,
video_layout=video_layout,
vsa_prefix_segments=vsa_prefix_segments,
)
if local_len == seq_len:
hidden = self.sp_gather(hidden)
@@ -959,6 +959,13 @@ class MiniMaxH3Pipeline(
)
self._fasth3 = resolve_fasth3_fusion(od_config, self.transformer)
if self._fasth3 is not None and self._fasth3.requires_vsa:
# The artifact assigns a compression gate per DiT block, so those
# modules have to exist before load_weights streams them in. Only
# the ``transformer.`` stream is fused, and ``check_task`` admits
# T2VA only, so the Ref2VA DiT would carry 50 gates that nothing
# ever fills or reads.
self.transformer.enable_vsa_gates()
if self._fasth3 is not None:
self._fasth3.check_serving_contract(
partition=self.partition,
@@ -1070,6 +1077,7 @@ class MiniMaxH3Pipeline(
loaded_with_prefix: set[str] = set()
loaded_prefixes: set[str] = set()
transformer_loaded: set[str] = set()
for prefix, grouped_weights in groupby(weights, key=source_prefix):
if prefix in loaded_prefixes:
raise ValueError(f"MiniMax-H3 weight source {prefix!r} is not contiguous")
@@ -1081,6 +1089,8 @@ class MiniMaxH3Pipeline(
# point where the checkpoint's fused QKV/MLP layouts are intact.
stream = self._fasth3.apply(stream)
loaded = component.load_weights(stream)
if prefix == "transformer.":
transformer_loaded = set(loaded)
if prefix != "text_encoder.":
component.post_load_weights()
loaded_with_prefix.update(prefix + name for name in loaded)
@@ -1094,7 +1104,9 @@ class MiniMaxH3Pipeline(
continue
loaded_with_prefix.update(f"{component_name}.{name}" for name, _ in component.named_parameters())
if self._fasth3 is not None:
self._fasth3.validate_fully_applied()
# load_weights only warns on a parameter the model does not have, so
# close the adapter against what the DiT actually consumed.
self._fasth3.validate_fully_applied(transformer_loaded)
return loaded_with_prefix
@property