cmvr-visual/docs/design/2026-11-26-h3-tp2-runtime-contract.md

215 lines
20 KiB
Markdown
Raw Normal View History

# H3 TP2 三阶段运行合同:实现前代码审查
> 后续实施与当前开放范围见 [双卡加速验收](2026-11-26-h3-tp2-validation.md);本文保留当时的调查结论。
2026-11-26。当前任务仅核对代码与官方接口;未改业务源代码、安装依赖、启动模型或运行 GPU 测试。新版视频已交付,多卡开发按用户授权进入下一阶段。本文的容量数字是静态权重计算,不是显存实测。
候选固定 Diffusers v0.43.0 / `423ab90580b2847998591669b8326f47b6d14d8b`,模型继续使用 `MiniMaxAI/MiniMax-H3` revision `12253298adb81e36757eabebb81d2ba1c0cc70cc` 的本地 FL2VA 权重。新 profile 首轮采用 **v1 帧数对齐后裁剪、仅首帧条件、无 GPU upscale**;旧 v1/v2 和旧 runtime 不改。
## 本仓库接入切点
| 当前位置 | 新路径的实现要求 |
|---|---|
| `inference/llm_services/h3.py:26` `_verified_model` | 可复用纯文件校验;仍核对官方 repo/revision、manifest 和 shard 完整性。不要复用 `h3.run` 的旧 runtime 常量或旧 metadata。 |
| `h3.py:86` `run` | 保持单卡实现;新增独立 TP2 adapter,不把旧 transformer group offload 改成 TP。 |
| `h3.py:16` `select_video_frames` | 新 profile 沿用 requested→native 对齐与输出裁剪,并在裁剪前验证完整 native 帧数;输入首帧,禁止 last_image 与 upscale。 |
| `adapters.py:108` `budgeted_child_environment` | 现有 sitecustomize 在任何 Python 子进程启动时执行 exactly-one-visible;TP rank 不能继承这份 bootstrap。新 runtime 单独构造阶段环境。 |
| `adapters.py:80` `configure_gpu_budget` | 不全局放宽检查;prepare/decode 保持一张可见卡,TP rank 使用专门 bootstrap:可见两卡,先 set_device(LOCAL_RANK),只给本 rank 设备设置 68 GiB allocator cap。 |
| `adapters.py:450` `run_stage` | 明确识别新 profile,路由新 supervisor;旧 H3、Wan 等路由保留。 |
| `runner.py:267` `execute`、`:321` `main` | 当前默认 runner_python、bootstrap 和 `--stage` 路径都偏向旧运行时;新 profile 必须在重型 import 前进入候选环境/专用 supervisor。 |
| `runner.py:212` `_run_child` | 可参考其进程身份追踪与同 PGID 子进程语义;双 rank 应同时监控,任何一方失败就清理双方,不能顺序 `_run_child(rank0)` 再 `_run_child(rank1)`。 |
父 worker 持有两卡组租约和 job/attempt。supervisor 自身不初始化 CUDA,顺序运行 prepare 子进程、两个同时运行的 TP rank、decode 子进程。prepare/decode 的 CUDA_VISIBLE_DEVICES 仅为组内主卡 UUID;两个 rank 的 CUDA_VISIBLE_DEVICES 是固定顺序的两 UUID,LOCAL_RANK=0/1。所有阶段继承同一 job PGID,不使用 torchrun/elastic 启动新 session。
## 已核对的拼装与加载 API
以下为接口示意,写入文档不表示已经实现。
```python
from diffusers.modular_pipelines.modular_pipeline import (
PipelineState, SequentialPipelineBlocks,
)
from diffusers.modular_pipelines.minimax_h3.modular_pipeline import (
MiniMaxH3ModularPipeline,
)
blocks = SequentialPipelineBlocks.from_blocks_dict(blocks_dict)
pipe = MiniMaxH3ModularPipeline(
blocks=blocks,
pretrained_model_name_or_path=model,
local_files_only=True,
)
pipe.load_components(
names=required_names,
dtype=torch.bfloat16,
pretrained_model_name_or_path=model,
local_files_only=True,
)
```
`from_blocks_dict` 接收保持插入顺序的 `{name: block_class_or_instance}`。不要对这个 generic `SequentialPipelineBlocks` 直接调用 `init_pipeline`:该方法依赖 `blocks.model_name` 的类映射;显式构造 `MiniMaxH3ModularPipeline` 最清楚。自拼阶段不传 `workflow="fl2va"`,因为它没有完整 H3 blocks 的 `_workflow_map`。`load_components` 的 `names` 与 `workflow` 不能同时传。
只有 `default_creation_method="from_pretrained"` 的组件需要加载;image_processor/video_processor 等 from_config 组件由 pipeline 构造时创建。`load_components` 会捕获组件加载异常并记录 warning,因此返回后必须逐项断言 required_names 对应属性非 None,不能把“函数返回”当作加载成功。[官方通用模块接口](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/modular_pipelines/modular_pipeline.py)
手动加载的 TP transformer 使用 `pipe.update_components(transformer=transformer)` 注入。不要在 pipeline 构造函数传 `transformer=...`:该构造函数的额外 kwargs 是配置加载参数,不能按普通 DiffusionPipeline 的组件注入方式假定行为。也不要在已注入后无条件再次 `load_components(names=["transformer"])`。
## Prepare 精确块顺序与组件
类分别来自 `minimax_h3.before_encoder`、`encoders`、`before_denoise`:
| 顺序/建议块名 | 官方类 | 作用 |
|---|---|---|
| 1 `resize` | `MiniMaxH3ResizeStep` | 尺寸处理、`keyframes` 与 `keyframe_anchors`;本 profile 只允许首帧。 |
| 2 `text_encoder` | `MiniMaxH3FL2VATextEncoderStep` | 图文联合 Qwen3-VL 编码;读取第 50 层未归一化 hidden state;不能换成纯文本编码块。 |
| 3 `vae_encoder` | `MiniMaxH3KeyframeVaeEncoderStep` | 条件帧 latent 编码。 |
| 4 `prepare_layout` | `MiniMaxH3PrepareLayoutStep` | 完整 packed layout、帧数和条件行计数。 |
| 5 `prepare_condition_latents` | `MiniMaxH3PrepareConditionLatentsStep` | 在 request generator 下加入条件噪声。 |
| 6 `prepare_latents` | `MiniMaxH3PrepareLatentsStep` | 先生成视频噪声,再生成音频噪声;转为 row layout。 |
| 7 `prepare_latents_fl2va` | `MiniMaxH3FL2VAPrepareLatentsStep` | 把条件行接到生成视频行之前。 |
prepare 的 required_names **仅为** `text_encoder, tokenizer, processor, vae, scheduler`;不加载 transformer、transformer_ref 或 audio_vae。布局相关属性在没有 transformer 时有官方 fallback,必须把本地 transformer/config.json 中 `(patch_size, in_channels)` 及 VAE 配置与这些 fallback 作断言,不能依赖未核对的默认值。
编码器保留当前已经验证的 `apply_group_offloading(pipe.text_encoder.model, offload_type="leaf_level", use_stream=False, low_cpu_mem_usage=False, record_stream=False, ...)`;VAE 用设备移动、保留 loader 的混合精度。不能让整个 pipeline 的 auto offload 接管未来 TP transformer。prepare 进程退出后才启动两个 rank,进程退出是释放整份编码器/CPU allocator 的屏障。[官方 encoder 源码](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/modular_pipelines/minimax_h3/encoders.py)
必须保留两个不同随机过程:条件 VAE posterior 使用独立 seed=42,并按官方先转 FP16 再 FP32/归一化的步骤;request generator 用请求 seed,消耗顺序是条件噪声→生成视频噪声→生成音频噪声。禁止重写为 VAE posterior mean,也禁止在 rank 再次生成这些随机张量。
prepare **停在 FL2VAPrepareLatentsStep 后,不执行 SetTimesteps**。两个新 rank 的 scheduler 实例必须各自 `set_timesteps`,以创建 sigmas 和初始 step 状态;只传一个 timesteps tensor 不能初始化新的 scheduler。
## Prepare→TP 状态白名单
落盘使用 CPU contiguous safetensors 加严格 JSON;不序列化整个 PipelineState、PIL、生成器或组件实例。保存并验证 schema version、profile、runtime/model revisions、job/attempt/group token、原包摘要、每个 tensor 的 dtype/shape、文件完整性和相对路径。原子发布 state manifest,rank 只读。
| 字段 | shape / 类型 / 语义 |
|---|---|
| `prompt_embeds` | BF16 `[1, Ntext, 5120]`;包括首帧视觉 token 的 conditioner 输出。 |
| `latents` | FP32 `[Ncondition_video + Ntarget_video, 96]`;这里已是 packed rows,不是 `[1,24,T,H,W]`。 |
| `audio_latents` | FP32 `[2 * Naudio, 32]`;已经 channel-major 的 rows。 |
| `position_ids` | FP64 `[S,3]`,H100 可原样传入;transformer RoPE 自行转 FP32。 |
| `token_tags` | int64 `[S]`。 |
| `video_indices` | int64 `[Ncondition_video + Ntarget_video]`。 |
| `audio_indices` | int64 `[2 * Naudio]`。 |
| `text_indices` | int64 `[Ntext]`。 |
| `height, width, num_frames` | int,均为 resolved/native 值;另存 requested_frames 供最后裁剪。 |
| `num_latent_frames, latent_height, latent_width, num_audio_latents` | int;供 AfterDenoise 恢复几何。 |
| `num_condition_video_rows, num_condition_audio_rows` | int;FL2VA 的 audio 条件行应为 0。 |
| `num_inference_steps` | int;显式保存,不依赖 50 的默认值。 |
| `attention_kwargs` | 首版固定 None;不接受任意 LoRA/scale 或对象。 |
`S=Ncondition_video+Ntarget_video+2*Naudio+Ntext`。视频 patch 是 `(1,2,2)`,所以 row width=24×4=96。`latent_height=height/16`、`latent_width=width/16`;原生帧数 `F=17n+5` 对应 `num_latent_frames=5n+2`。不要从原请求的非 native num_frames 重新猜这些值。
**必须恢复 kwargs_mapping:** `PipelineState` 有 `values` 与 `kwargs_mapping` 两部分。对 `position_ids, token_tags, video_indices, audio_indices, text_indices` 逐项调用 `state.set(name, tensor, kwargs_type="denoiser_input_fields")`;其余 `state.set(name,value)`。只用 `PipelineState(values=tensors)` 会丢失布局分类,官方 `MiniMaxH3LoopDenoiser` 将拿不到 transformer 必需参数。不是在 values 里新增一个普通的 `denoiser_input_fields` 字典就自动等价。
CPU state 读回后必须把每一个 tensor 显式搬到本 rank 的设备,包括五个 layout tensor。SetTimesteps 仅搬它新生成的 schedule/plan,不负责给已有 latents、prompt_embeds 或 layout 搬设备;也不能在不同 rank 间沿用 `cuda:0` 字样。保持各字段原 dtype,只有 device 改变。
推荐在明确 `torch.inference_mode()` 的外层执行 `_, state = pipe.blocks(pipe, state)`,可避免通用 `pipe(state=state)` 会对已恢复 state 做 deepcopy 的额外张量副本。首版禁用 stateful cache,因此没有缓存重置状态;若后来启用缓存必须补同样的 finally 清理。若实现选择公开 `state = pipe(state=state)` 也可以,但必须接住返回的新 state,并移除旧引用,不能执行后继续读取旧 state 或长期同时持有两份 GPU state。[准备阶段源码](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/modular_pipelines/minimax_h3/before_denoise.py)
## TP rank 精确块与加载
每个 rank 的 blocks 为:
1. `MiniMaxH3SetTimestepsStep`(`before_denoise`)。
2. `MiniMaxH3DenoiseStep`(`denoise`,内部为 `MiniMaxH3LoopDenoiser` + `MiniMaxH3LoopSchedulerStep`)。
3. `MiniMaxH3AfterDenoiseStep`(`decoders`)。
required_names 仅 `scheduler, audio_scheduler`。transformer 手工加载,先设置本地设备和初始化 process group:
```python
transformer = MiniMaxH3Transformer3DModel.from_pretrained(
model, subfolder="transformer", dtype=torch.bfloat16,
parallel_config=TensorParallelConfig(tp_degree=2),
local_files_only=True, use_safetensors=True,
low_cpu_mem_usage=True,
)
pipe.update_components(transformer=transformer)
```
不能传 device_map、quantization_config,不能先加载全 CPU transformer 再 enable_parallelism,不能给 transformer group offload,也不能对最终 pipeline `.to(device)` / `.to(dtype=...)`。两个 rank 都执行每一步及 scheduler 更新;TP 输出已是每 rank 可消费的完整结果,不额外跨 rank 拼接 video rows。
SetTimesteps 生成本 rank 的 `timesteps, audio_timesteps, row_timestep_plan`。Denoise 使用 full layout;只更新生成行,保持前面的条件行固定。AfterDenoise 删除条件行,恢复 video `[1,24,T,Hlat,Wlat]`、audio `[2,32,Naudio]`。rank0 保存 unpacked FP32 video latent(以及验证需要时的 audio latent),两个 rank 全部退出之后才能进入 decode。GPU/host 参数摘要、每 rank dtype 与内存读数须绑定同一 job/attempt。[官方去噪循环](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/modular_pipelines/minimax_h3/denoise.py)
## Decode 切点
只构造 `MiniMaxH3VideoDecodeStep`(来自 `minimax_h3.decoders`),只加载 `names=["vae"]`。组件 `video_processor` 自动创建,其 `do_normalize=False`;不得复用默认会重复反归一化的 VideoProcessor。输入 unpacked `latents` 和 `output_type="np"`;先把输入 latent 显式搬到主卡(该块本身不会替调用者搬输入),执行后取 `videos`,调用现有完整帧数/数值检查和 `select_video_frames`,再 `encode_video(fps=24)`。
此产品合同不封装原生音轨,因此 **不必加载 audio_vae,也不必调用 AudioDecodeStep**。音频 latent 仍必须参加 TP 去噪,联合生成语义不能删。若后来开放原生音轨,再独立认证 audio decode 和采样率。[官方 decoder 源码](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/modular_pipelines/minimax_h3/decoders.py)
## 68 GiB 容量与 RoPE/FC 精度检查
静态结论:**两卡各 68 GiB allocator budget 足够容纳 TP2 transformer 权重;实际 forward 峰值仍须实测。** 官方固定 revision 的 transformer 索引 `metadata.total_size=66,280,430,080` bytes,638 个张量、14 个 shard。按该 config 和官方 plan 计算:
- 全模型原始参数数据:约 61.728 GiB。
- 可按 TP2 对半切分的 BF16 matrix:66,087,813,120 bytes。
- 其余复制参数:192,616,960 bytes。
- 每 rank 参数数据:`66,087,813,120/2 + 192,616,960 = 33,236,523,520` bytes,约 **30.954 GiB**。
- 68 GiB 减去上述参数数据,约余 **37.046 GiB**;这不是可承诺的激活空间,尚需扣除 allocator 碎片、workspace、DTensor/通信暂存等。
计算采用 `h=5376, inner=56*128, ffn=14336, time=2688`:52 个 attention/FFN 组的矩阵元素为 `52*(4*inner*h+3*ffn*h)`,50 个 AdaLN 矩阵为 `50*(6*3*h*time)`,乘 BF16 的 2 bytes,其余由 total_size 相减。该计算未把编码器或 VAE放入 rank,因此 prepare/decode 退出屏障是容量论证的一部分。不是“整管线常驻31GiB”。[固定模型索引](https://huggingface.co/MiniMaxAI/MiniMax-H3/blob/12253298adb81e36757eabebb81d2ba1c0cc70cc/transformer/diffusion_pytorch_model.safetensors.index.json)
**不需要自创 shared-model 的全 FC FP32 特判。需要严格执行官方保留精度并断言:**
| 对象 | 必须检查 |
|---|---|
| `proj_in, audio_proj_in, time_embedder, proj_out, audio_proj_out` | 参数均 FP32、位于该 rank 的 CUDA 设备;这是官方 `_keep_in_fp32_modules` 合同。 |
| `rope.inv_freq` | 非 persistent buffer,FP32、非 meta、位于该 rank CUDA;数值与同 config 的 FP32 RoPE 基准相符。 |
| attention Q/K/V/out、FFN、各块 `adaln_proj.linear` | BF16;planned matrix 必须是 DTensor 且 local shard 形状确实为 TP2,不能只有 parallel_config 标签。 |
| AdaLN rowwise bias | 复制 bias 可能仍是 DTensor Replicate,不能粗暴断言所有 DTensor 都 Shard;权重输入维才对半。 |
| `norm_out.linear`、`context_embedder`、norms | 按官方 loader BF16 与复制策略;不要把所有 `Linear` 强转 FP32。 |
| VAE | 与本类官方 `_keep_in_fp32_modules` 对照;encoder、quant_conv、norm1/2/out、scale1/2 保留 FP32,其余遵循加载 dtype。不能宣称整个 VAE 全 FP32。 |
官方 v0.43.0 TP loader 对复制参数传递显式 dtype,包含 #15147 修复;模型加载结束还把非 persistent buffer 搬到 tp_device,保留 dtype,所以 RoPE 不需要 monkeypatch。断言失败就视为运行时版本/精度缺陷,不静默修补全模型。[TP 切片与 dtype 加载](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/models/model_loading_utils.py)、[非 persistent buffer 搬运](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/models/modeling_utils.py)、[官方 H3 plan 与精度名单](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/models/transformers/transformer_minimax_h3.py)
GPU allocator cap 只限制 PyTorch allocator;NCCL/CUDA context 可能在 cap 外。准入仍逐卡要求 budget+reserve,运行监测仍看逐卡 NVML。主机保持一个逻辑 job 288 GiB+16 GiB 全局余量;两个 rank 不能各带完整 encoder/VAEs,不能把 288×2塞进384 GiB硬限,也不能降低预留强行通过。
## 最小验证命令与明确前置条件
以下命令没有在本次审查执行。第一条只用标准库读取现有本地元数据,可直接在推理容器使用,不加载模型:
```bash
python - <<'PY'
import json
from pathlib import Path
p = Path('/workspace/models/minimax-h3-fl2va/transformer')
c = json.loads((p/'config.json').read_text())
i = json.loads((p/'diffusion_pytorch_model.safetensors.index.json').read_text())
h=c['hidden_size']; a=c['num_attention_heads']*c['attention_head_dim']
f=c['ffn_dim']; t=c['time_embed_dim']; n=c['num_layers']; r=c['num_refiner_layers']
sharded=2*((n+r)*(4*a*h+3*f*h)+n*18*h*t)
total=i['metadata']['total_size']; replicated=total-sharded
print({'full_bytes':total,'replicated_bytes':replicated,
'tp2_weight_gib':(sharded//2+replicated)/2**30})
assert c['num_attention_heads']%2 == 0
assert (sharded//2+replicated) < 68*2**30
PY
```
候选环境建立后,可用第二条执行纯 CPU 的真实 API 检查。`H3_TP2_PYTHON` 必须显式指向新环境解释器;不要替换现网 runner_python。
```bash
CUDA_VISIBLE_DEVICES='' HF_HUB_OFFLINE=1 TRANSFORMERS_OFFLINE=1 \
"$H3_TP2_PYTHON" - <<'PY'
import diffusers
from diffusers.modular_pipelines.modular_pipeline import SequentialPipelineBlocks, PipelineState
from diffusers.modular_pipelines.minimax_h3.modular_pipeline import MiniMaxH3ModularPipeline
from diffusers.modular_pipelines.minimax_h3.before_denoise import MiniMaxH3SetTimestepsStep
from diffusers.modular_pipelines.minimax_h3.denoise import MiniMaxH3DenoiseStep
from diffusers.modular_pipelines.minimax_h3.decoders import MiniMaxH3AfterDenoiseStep
assert diffusers.__version__ == '0.43.0'
b=SequentialPipelineBlocks.from_blocks_dict({
'set_timesteps':MiniMaxH3SetTimestepsStep,
'denoise':MiniMaxH3DenoiseStep,'after_denoise':MiniMaxH3AfterDenoiseStep})
p=MiniMaxH3ModularPipeline(blocks=b,
pretrained_model_name_or_path='/workspace/models/minimax-h3-fl2va',local_files_only=True)
assert set(p.components)=={'scheduler','audio_scheduler','transformer'}
assert all(x is None for x in p.components.values())
s=PipelineState(); s.set('token_tags',None,kwargs_type='denoiser_input_fields')
assert s.kwargs_mapping['denoiser_input_fields']==['token_tags']
print(diffusers.__version__,list(p.blocks.sub_blocks),list(p.components))
PY
```
GPU 最小流程应由新增 supervisor 的真实 CLI 提供,不能在尚无组租约/回收实现时伪造“已经可运行”的服务命令。建议 CLI 明确提供 `prepare-only → tp-load-only → tp-one-step → full-generate` 模式,复用同一受控 request/lease 文件和状态 schema;这些是待实现合同,不是当前已有命令。第一次先只验证双 rank 权重加载、dtype/local-shape、NVML/cgroup峰值和两进程退出;再同一 prepared state 对比新 runtime 的 TP1/TP2 一步 velocity;最后验证完整 native 帧数、最终裁剪和端到端耗时。每次都必须在 worker 获得两卡租约之后执行,并由全组 timeout/cancel/抢占监控覆盖。
## 阻碍与实施判定
没有发现必须更换或重新下载完整模型的静态阻碍。官方 API 足以组装三阶段,resident TP2 参数容量合理。当前仍阻碍直接上线的是:新环境尚需独立建立并固定依赖;新多卡 bootstrap/同 PGID supervisor/成组租约必须先落地;PipelineState 布局标记与各 rank scheduler 初始化需有 CPU 合同测试;H100 CUDA 真模数值、真实帧数激活、PCIe 通信、主机384 GiB和抢占回收还没有本机证据。完成这些验证前,新 profile 保持关闭。