ref2va_int8_convrot/hyperflow_h3_flash_transformer.py
18.7 KB · 404 lines · python Raw
1 # Copyright 2026 The HyperFlow authors. Licensed under the Apache License, Version 2.0.
2 #
3 # `HyperFlowH3FlashTransformer3DModel.forward` is derived from `MiniMaxH3Transformer3DModel.forward` in diffusers
4 # (`models/transformers/transformer_minimax_h3.py`), Copyright 2025 The MiniMax Team and The HuggingFace Team,
5 # Apache License 2.0. See https://github.com/Video-Rebirth/hyperflow-h3-flash/blob/main/THIRD_PARTY_NOTICES.md.
6 """The HyperFlow H3 Flash transformer: MiniMax-H3, compressed and conditioned on two times.
7
8 Four changes to `MiniMaxH3Transformer3DModel`, all driven by `config.json`:
9
10 * **Two-time conditioning.** An `endpoint_time_embedder` embeds the step's endpoint ``r`` next to the current time
11 ``t``; every AdaLN reads ``temb(t, r) = emb_t(t) + hyperflow_gate * (emb_r(r) - emb_t(t))``.
12 * **Dropped blocks** (`dropped_blocks`): those blocks are identities and have no weights.
13 * **Low-rank linears** (`lowrank_ranks`): ``W ~= up @ down``, stored as `<name>.down.weight` (rank x in) and
14 `<name>.up.weight` (out x rank). Ranks are zero-padded to multiples of 64, in the checkpoint or at load
15 (`pad_lowrank_ranks`), so both GEMMs are aligned; `set_lowrank_rank_multiple` re-pads them at run time.
16 * **INT8 linears** (`quantization`): W8A8 with a Hadamard-rotated input, see `int8.py`.
17
18 Embeddings, AdaLN, the token refiner and the output heads are the base model's, in bf16 / fp32. The block
19 feed-forwards run in token chunks (`ChunkedFeedForward`, `set_ff_chunk`), which bounds their activations;
20 `set_block_chunk` slices every token-wise op of a block.
21 """
22
23 from __future__ import annotations
24
25 import sys
26 from typing import Any, ClassVar
27
28 import torch
29 from diffusers import MiniMaxH3Transformer3DModel
30 from diffusers.configuration_utils import register_to_config
31 from diffusers.models.embeddings import TimestepEmbedding
32 from diffusers.models.modeling_utils import get_parameter_dtype
33 from diffusers.models.transformers.transformer_minimax_h3 import (
34 MINIMAX_H3_MODALITY_NUM,
35 MiniMaxH3TransformerOutput,
36 )
37 from diffusers.utils import apply_lora_scale
38 from torch import Tensor, nn
39
40 from .hyperflow_h3_flash_int8 import Int8RotLinear
41
42 #: Tokens per feed-forward chunk; a 5.2 s clip has about 38k, a 14.4 s clip about 105k.
43 FF_CHUNK_TOKENS = 16384
44 #: Low-rank ranks are padded to multiples of this at load, so both GEMMs of a low-rank linear are aligned.
45 RANK_MULTIPLE = 64
46
47
48 class LowRankLinear(nn.Module):
49 """``y = up(down(x))``, the factorized replacement of a bias-free `nn.Linear`."""
50
51 def __init__(self, in_features: int, out_features: int, rank: int) -> None:
52 super().__init__()
53 self.in_features, self.out_features, self.rank = in_features, out_features, rank
54 self.down = nn.Linear(in_features, rank, bias=False)
55 self.up = nn.Linear(rank, out_features, bias=False)
56
57 def forward(self, x: Tensor) -> Tensor:
58 return self.up(self.down(x))
59
60 @torch.no_grad()
61 def pad_rank(self, multiple: int = RANK_MULTIPLE) -> bool:
62 """Zero-pad the rank up to a multiple of ``multiple``: new rows of ``down`` and columns of ``up`` are zero, so
63 ``up @ down`` is unchanged. Returns whether the rank changed."""
64 rank = -(-self.rank // multiple) * multiple
65 if rank == self.rank:
66 return False
67 extra = rank - self.rank
68 down, up = self.down.weight, self.up.weight
69 self.down.weight = nn.Parameter(torch.cat([down, down.new_zeros(extra, down.shape[1])]), requires_grad=False)
70 self.up.weight = nn.Parameter(torch.cat([up, up.new_zeros(up.shape[0], extra)], dim=1), requires_grad=False)
71 self.down.out_features = self.up.in_features = self.rank = rank
72 return True
73
74
75 class ChunkedFeedForward(nn.Module):
76 """A block's feed-forward run over at most ``chunk_tokens`` tokens at a time; it keeps the block's ``net``.
77
78 The feed-forward is token-wise, so the chunks compute the same function; only the rounding of bf16 GEMMs can
79 change with their row count. It bounds the SwiGLU input, ``2 * ffn_dim`` wide per token (6 GiB for a 14.4 s
80 clip), to one chunk.
81 """
82
83 def __init__(self, net: nn.ModuleList, out_features: int, chunk_tokens: int) -> None:
84 super().__init__()
85 self.net, self.out_features, self.chunk_tokens = net, out_features, chunk_tokens
86
87 def _forward(self, hidden_states: Tensor) -> Tensor:
88 for module in self.net:
89 hidden_states = module(hidden_states)
90 return hidden_states
91
92 def forward(self, hidden_states: Tensor) -> Tensor:
93 if hidden_states.shape[-2] <= self.chunk_tokens:
94 return self._forward(hidden_states)
95 out = hidden_states.new_empty(*hidden_states.shape[:-1], self.out_features)
96 for start in range(0, hidden_states.shape[-2], self.chunk_tokens):
97 stop = start + self.chunk_tokens
98 out[..., start:stop, :] = self._forward(hidden_states[..., start:stop, :])
99 return out
100
101
102 class DroppedBlock(nn.Module):
103 """A removed transformer block: the hidden states go straight to the next block.
104
105 The signature is the block's own: context parallel hooks address `adaln_indices` by name.
106 """
107
108 def forward(self, hidden_states: Tensor, temb=None, adaln_indices=None, rotary_emb=None, attention_mask=None):
109 return hidden_states
110
111
112 def _replace_linear(model: nn.Module, name: str, make: type[nn.Module], *args: Any) -> None:
113 owner_name, _, attr = name.rpartition(".")
114 owner = model.get_submodule(owner_name)
115 dense = owner[int(attr)] if isinstance(owner, nn.ModuleList) else getattr(owner, attr)
116 if type(dense) is not nn.Linear or dense.bias is not None:
117 raise TypeError(f"{name} is not a bias-free nn.Linear")
118 replacement = make(dense.in_features, dense.out_features, *args)
119 if isinstance(owner, nn.ModuleList):
120 owner[int(attr)] = replacement
121 else:
122 setattr(owner, attr, replacement)
123
124
125 class HyperFlowH3FlashTransformer3DModel(MiniMaxH3Transformer3DModel):
126 """`MiniMaxH3Transformer3DModel` conditioned on ``(t, r)``, with dropped blocks, low-rank and INT8 linears."""
127
128 # Matched against whole dotted name parts at load time, so `time_embedder` does not cover the endpoint embedder.
129 _keep_in_fp32_modules: ClassVar[list[str]] = [
130 *MiniMaxH3Transformer3DModel._keep_in_fp32_modules,
131 "endpoint_time_embedder",
132 "wscale",
133 ]
134
135 @register_to_config
136 def __init__(
137 self,
138 num_attention_heads: int = 56,
139 attention_head_dim: int = 128,
140 hidden_size: int = 5376,
141 num_layers: int = 50,
142 num_refiner_layers: int = 2,
143 ffn_dim: int = 14336,
144 in_channels: int = 24,
145 audio_in_channels: int = 32,
146 patch_size: tuple[int, int, int] = (1, 2, 2),
147 text_dim: int = 5120,
148 freq_dim: int = 256,
149 time_embed_hidden_dim: int = 5376,
150 time_embed_dim: int = 16,
151 rope_freq_dim: int = 16,
152 rope_theta: float = 10000.0,
153 norm_eps: float = 1e-5,
154 qk_norm_eps: float = 1e-5,
155 final_norm_eps: float = 1e-5,
156 hyperflow_gate: float = 0.25,
157 dropped_blocks: list[int] | None = None,
158 lowrank_ranks: dict[str, int] | None = None,
159 quantization: dict[str, Any] | None = None,
160 ) -> None:
161 super().__init__(
162 num_attention_heads=num_attention_heads,
163 attention_head_dim=attention_head_dim,
164 hidden_size=hidden_size,
165 num_layers=num_layers,
166 num_refiner_layers=num_refiner_layers,
167 ffn_dim=ffn_dim,
168 in_channels=in_channels,
169 audio_in_channels=audio_in_channels,
170 patch_size=patch_size,
171 text_dim=text_dim,
172 freq_dim=freq_dim,
173 time_embed_hidden_dim=time_embed_hidden_dim,
174 time_embed_dim=time_embed_dim,
175 rope_freq_dim=rope_freq_dim,
176 rope_theta=rope_theta,
177 norm_eps=norm_eps,
178 qk_norm_eps=qk_norm_eps,
179 final_norm_eps=final_norm_eps,
180 )
181 self.endpoint_time_embedder = TimestepEmbedding(
182 in_channels=freq_dim, time_embed_dim=time_embed_hidden_dim, out_dim=time_embed_dim
183 )
184
185 dropped = set(dropped_blocks or [])
186 for index, block in enumerate(self.transformer_blocks):
187 if index in dropped:
188 self.transformer_blocks[index] = DroppedBlock()
189 else:
190 block.ff = ChunkedFeedForward(block.ff.net, block.ff.net[-1].out_features, FF_CHUNK_TOKENS)
191 for name, rank in (lowrank_ranks or {}).items():
192 if int(name.split(".")[1]) not in dropped:
193 _replace_linear(self, name, LowRankLinear, int(rank))
194 if quantization:
195 if quantization.get("method") != "int8_convrot":
196 raise ValueError(f"unsupported quantization method {quantization.get('method')!r}")
197 for name in quantization["linears"]:
198 _replace_linear(self, name, Int8RotLinear, int(quantization["group"]))
199 for block in self.transformer_blocks:
200 attn = getattr(block, "attn", None)
201 for name in ("to_q", "to_k"):
202 if isinstance(layer := getattr(attn, name, None), Int8RotLinear):
203 layer.keep_input = True
204
205 def pad_lowrank_ranks(self, multiple: int = RANK_MULTIPLE) -> int:
206 """Zero-pad every low-rank linear to a rank multiple of ``multiple`` (see `LowRankLinear.pad_rank`) for a
207 checkpoint stored at its unpadded ranks. Returns how many linears changed."""
208 ranks = dict(self.config.lowrank_ranks or {})
209 padded = 0
210 for name, module in self.named_modules():
211 if isinstance(module, LowRankLinear) and module.pad_rank(multiple):
212 ranks[name] = module.rank
213 padded += 1
214 if padded:
215 self.register_to_config(lowrank_ranks=ranks)
216 return padded
217
218 def time_embedding(self, timestep: Tensor, endpoint_timestep: Tensor) -> Tensor:
219 """``temb`` of every distinct ``(t, r)`` pair, at the time embedders' precision (fp32)."""
220 if endpoint_timestep.shape != timestep.shape:
221 raise ValueError(f"endpoint_timestep {list(endpoint_timestep.shape)} != timestep {list(timestep.shape)}")
222 dtype = get_parameter_dtype(self.time_embedder)
223 current = self.time_embedder(self.time_proj(timestep).to(dtype))
224 endpoint = self.endpoint_time_embedder(self.time_proj(endpoint_timestep).to(dtype))
225 return current + self.config.hyperflow_gate * (endpoint - current)
226
227 @apply_lora_scale("attention_kwargs")
228 def forward(
229 self,
230 hidden_states: Tensor,
231 audio_hidden_states: Tensor,
232 encoder_hidden_states: Tensor,
233 timestep: Tensor,
234 timestep_indices: Tensor,
235 token_tags: Tensor,
236 position_ids: Tensor,
237 video_indices: Tensor,
238 audio_indices: Tensor,
239 text_indices: Tensor,
240 endpoint_timestep: Tensor | None = None,
241 attention_kwargs: dict[str, Any] | None = None,
242 return_dict: bool = True,
243 ) -> MiniMaxH3TransformerOutput | tuple[Tensor, Tensor]:
244 """The base forward plus ``endpoint_timestep``: ``(timestep[i], endpoint_timestep[i])`` is the ``i``-th pair.
245
246 ``timestep_indices`` maps every row of the packed sequence to its pair. Build the pairs with
247 `hyperflow_h3_flash.schedule.build_row_time_pairs`, or run the model through `flash_blocks(...)`.
248 """
249 if endpoint_timestep is None:
250 raise ValueError(
251 "HyperFlow H3 Flash needs `endpoint_timestep`, the endpoint `r` of every `(t, r)` pair: it is a "
252 "few-step model and has no single-time mode. Run it through `hyperflow_h3_flash.flash_blocks(...)`."
253 )
254 if position_ids.ndim != 2 or position_ids.shape[-1] != 3:
255 raise ValueError(f"`position_ids` must be a `(seq_len, 3)` tensor, got {list(position_ids.shape)}.")
256 sequence_length = position_ids.shape[0]
257 if token_tags.shape != (sequence_length,) or timestep_indices.shape != (sequence_length,):
258 raise ValueError("`token_tags` and `timestep_indices` must both be `(seq_len,)` tensors.")
259
260 rotary_emb = self.rope(position_ids)
261
262 video_embeds = self.proj_in(hidden_states.to(get_parameter_dtype(self.proj_in)))
263 audio_embeds = self.audio_proj_in(audio_hidden_states.to(get_parameter_dtype(self.audio_proj_in)))
264 text_embeds = self.context_embedder(encoder_hidden_states.to(get_parameter_dtype(self.context_embedder)))
265 text_embeds = self.token_refiner(text_embeds)
266
267 hidden_states = text_embeds.new_zeros((text_embeds.shape[0], sequence_length, text_embeds.shape[-1]))
268 hidden_states = hidden_states.index_copy(1, text_indices, text_embeds)
269 hidden_states = hidden_states.index_copy(1, video_indices, video_embeds.to(text_embeds.dtype))
270 hidden_states = hidden_states.index_copy(1, audio_indices, audio_embeds.to(text_embeds.dtype))
271
272 temb = self.time_embedding(timestep, endpoint_timestep)
273 adaln_indices = timestep_indices * MINIMAX_H3_MODALITY_NUM + token_tags
274 for block in self.transformer_blocks:
275 hidden_states = block(hidden_states, temb, adaln_indices, rotary_emb)
276
277 hidden_states = self.norm_out(hidden_states, temb, timestep_indices).to(get_parameter_dtype(self.proj_out))
278 video_output = self.proj_out(hidden_states).index_select(1, video_indices)
279 audio_output = self.audio_proj_out(hidden_states).index_select(1, audio_indices)
280 if not return_dict:
281 return (video_output, audio_output)
282 return MiniMaxH3TransformerOutput(sample=video_output, audio_sample=audio_output)
283
284
285 def _used_rank(layer: LowRankLinear) -> int:
286 """The rank without the zero padding (trailing zero rows of ``down`` and columns of ``up``)."""
287 used = (layer.down.weight.detach().abs().amax(1) != 0) | (layer.up.weight.detach().abs().amax(0) != 0)
288 nonzero = used.nonzero()
289 return int(nonzero[-1]) + 1 if len(nonzero) else 1
290
291
292 def set_lowrank_rank_multiple(model: nn.Module, multiple: int) -> int:
293 """Re-pad every low-rank linear to a rank multiple of ``multiple`` (0: no padding); returns the layers changed.
294
295 Zero rows and columns add exact zeros, so any multiple computes the same function; the GEMM shapes change, and with
296 them the bf16 rounding (8 is 2 to 7 % faster than 64 on H200). Run time only: the config still lists the stored
297 ranks, so do not `save_pretrained` the re-padded model.
298 """
299 changed = 0
300 for layer in model.modules():
301 if not isinstance(layer, LowRankLinear):
302 continue
303 rank = _used_rank(layer)
304 target = -(-rank // multiple) * multiple if multiple > 0 else rank
305 if target == layer.rank:
306 continue
307 down, up = layer.down.weight.detach(), layer.up.weight.detach()
308 if target < layer.rank:
309 down, up = down[:target], up[:, :target]
310 else:
311 down = torch.cat([down, down.new_zeros(target - layer.rank, down.shape[1])])
312 up = torch.cat([up, up.new_zeros(up.shape[0], target - layer.rank)], dim=1)
313 layer.down.weight = nn.Parameter(down.contiguous(), requires_grad=False)
314 layer.up.weight = nn.Parameter(up.contiguous(), requires_grad=False)
315 layer.rank = layer.down.out_features = layer.up.in_features = target
316 changed += 1
317 return changed
318
319
320 def set_ff_chunk(model: nn.Module, tokens: int) -> None:
321 """Run every feed-forward over at most ``tokens`` tokens at a time (0: whole sequence)."""
322 for module in model.modules():
323 if isinstance(module, ChunkedFeedForward):
324 module.chunk_tokens = tokens if tokens > 0 else sys.maxsize
325
326
327 def chunk_block(block: nn.Module, chunk: int) -> None:
328 """Run every token-wise op of a transformer block over ``chunk``-token slices; only the attention sees all of q /
329 k / v.
330
331 The unchunked block holds about a dozen ``(seq, hidden)`` tensors at once (each modulation picked per token, the
332 modulated norm, the residual sums), 1.2 GB apiece at 108k tokens. Per-row results are the same up to the bf16 GEMM
333 rounding for the smaller row count. Apply before context parallelism and offloading, which hook the block.
334 """
335 import diffusers.models.transformers.transformer_minimax_h3 as h3
336
337 attn = block.attn
338
339 def forward(hidden_states, temb, adaln_indices, rotary_emb, attention_mask=None):
340 shift_msa, scale_msa, gate_msa, shift_mlp, scale_mlp, gate_mlp = block.adaln_proj(temb)
341 batch, seq, _ = hidden_states.shape
342 cos, sin = rotary_emb
343 qkv = None
344 for start in range(0, seq, chunk):
345 rows = slice(start, min(start + chunk, seq))
346 idx = adaln_indices[rows]
347 h = block.norm1(hidden_states[:, rows])
348 h = h * (1.0 + scale_msa.index_select(0, idx)) + shift_msa.index_select(0, idx)
349 parts = []
350 for proj, norm in ((attn.to_q, attn.norm_q), (attn.to_k, attn.norm_k), (attn.to_v, None)):
351 x = proj(h).unflatten(-1, (attn.heads, -1))
352 if norm is not None:
353 x = h3._apply_rotary_emb(norm(x), cos[rows], sin[rows])
354 parts.append(x)
355 if qkv is None:
356 qkv = [x.new_empty((batch, seq, *x.shape[2:])) for x in parts]
357 for full, x in zip(qkv, parts, strict=True):
358 full[:, rows] = x
359 del h, parts, x
360 out = h3.dispatch_attention_fn(
361 *qkv,
362 attn_mask=attention_mask,
363 dropout_p=0.0,
364 is_causal=False,
365 backend=attn.processor._attention_backend,
366 parallel_config=attn.processor._parallel_config,
367 )
368 dtype = qkv[0].dtype
369 del qkv
370 result = torch.empty_like(hidden_states)
371 for start in range(0, seq, chunk):
372 rows = slice(start, min(start + chunk, seq))
373 idx = adaln_indices[rows]
374 a = attn.to_out[1](attn.to_out[0](out[:, rows].flatten(2, 3).to(dtype)))
375 h = hidden_states[:, rows] + gate_msa.index_select(0, idx) * a
376 n = block.norm2(h)
377 n = n * (1.0 + scale_mlp.index_select(0, idx)) + shift_mlp.index_select(0, idx)
378 result[:, rows] = h + gate_mlp.index_select(0, idx) * block.ff(n)
379 del a, h, n
380 return result
381
382 block.forward = forward
383
384
385 def set_block_chunk(model: nn.Module, tokens: int) -> None:
386 """`chunk_block` on every kept block (0: off). Call once, before context parallelism and offloading."""
387 if tokens > 0:
388 for block in model.transformer_blocks:
389 if not isinstance(block, DroppedBlock):
390 chunk_block(block, tokens)
391
392
393 __all__ = [
394 "RANK_MULTIPLE",
395 "ChunkedFeedForward",
396 "DroppedBlock",
397 "HyperFlowH3FlashTransformer3DModel",
398 "LowRankLinear",
399 "chunk_block",
400 "set_block_chunk",
401 "set_ff_chunk",
402 "set_lowrank_rank_multiple",
403 ]
404