180 lines
10 KiB
Python
180 lines
10 KiB
Python
"""官方 MiniMax H3 FL2VA;只在任务进程中加载模型与 CUDA 依赖。"""
|
||
from __future__ import annotations
|
||
|
||
import gc
|
||
import json
|
||
from pathlib import Path
|
||
from typing import Any
|
||
|
||
|
||
MODEL_DIRECTORY = "/workspace/models/minimax-h3-fl2va"
|
||
MODEL_REPO = "MiniMaxAI/MiniMax-H3"
|
||
MODEL_REVISION = "12253298adb81e36757eabebb81d2ba1c0cc70cc"
|
||
DIFFUSERS_REVISION = "f53d552036a0d1bd5570782a39cd40cfabf112bc"
|
||
|
||
|
||
def select_video_frames(frames, requested: int, native: int):
|
||
"""先验证完整原生输出,再裁真实帧;不足帧绝不补图或重复末帧。"""
|
||
if (type(requested) is not int or type(native) is not int
|
||
or requested < 1 or native < requested):
|
||
raise RuntimeError("Invalid H3 requested/native frame counts")
|
||
if len(frames) != native:
|
||
raise RuntimeError(f"H3 native frame count mismatch: expected {native}, got {len(frames)}")
|
||
return frames[:requested]
|
||
|
||
|
||
def _verified_model() -> str:
|
||
from .adapters import _require_model
|
||
|
||
model = Path(_require_model(MODEL_DIRECTORY))
|
||
manifest = json.loads((model / ".deployment-manifest.json").read_text(encoding="utf-8"))
|
||
if manifest.get("repo") != MODEL_REPO or manifest.get("revision") != MODEL_REVISION:
|
||
raise RuntimeError("H3 checkpoint manifest differs from explicit profile repo/revision")
|
||
if not manifest.get("verified_at"):
|
||
raise RuntimeError("H3 checkpoint manifest has not completed file verification")
|
||
files = manifest.get("files")
|
||
if not isinstance(files, list) or not files:
|
||
raise RuntimeError("H3 checkpoint verification manifest has no files")
|
||
verified_paths = set()
|
||
for item in files:
|
||
if not isinstance(item, dict):
|
||
raise RuntimeError("H3 checkpoint verification manifest has an invalid file")
|
||
# 新下载器保留官方HF元数据,旧部署清单使用path/bytes;两者都必须已经校验。
|
||
name = item.get("rfilename", item.get("path"))
|
||
if not isinstance(name, str):
|
||
raise RuntimeError("H3 checkpoint verification manifest has an invalid file")
|
||
relative = Path(name)
|
||
path = model / relative
|
||
# 校验清单不得借绝对路径、父目录或符号链接指向模型目录外。
|
||
if (relative.is_absolute() or ".." in relative.parts
|
||
or not path.resolve().is_relative_to(model.resolve())):
|
||
raise RuntimeError("H3 checkpoint manifest file escapes the model directory")
|
||
size = item.get("size", item.get("bytes"))
|
||
if size is None and isinstance(item.get("lfs"), dict):
|
||
size = item["lfs"].get("size")
|
||
if type(size) is not int or size < 1 or not path.is_file() or path.stat().st_size != size:
|
||
raise RuntimeError(f"H3 verified checkpoint file is missing or has changed: {relative}")
|
||
verified_paths.add(relative.as_posix())
|
||
|
||
required = {
|
||
"model_index.json", "modular_model_index.json",
|
||
"transformer/config.json", "transformer/diffusion_pytorch_model.safetensors.index.json",
|
||
"text_encoder/config.json", "text_encoder/model.safetensors.index.json",
|
||
"vae/config.json", "vae/diffusion_pytorch_model.safetensors.index.json",
|
||
"audio_vae/config.json", "audio_vae/diffusion_pytorch_model.safetensors",
|
||
"scheduler/scheduler_config.json", "audio_scheduler/scheduler_config.json",
|
||
"tokenizer/tokenizer.json", "tokenizer/tokenizer_config.json",
|
||
"processor/preprocessor_config.json",
|
||
}
|
||
if not required.issubset(verified_paths):
|
||
raise RuntimeError("H3 manifest must contain the complete root Diffusers FL2VA layout")
|
||
# 清单既要包含索引,也必须覆盖索引实际引用的每个权重分片。
|
||
for component, index_name in (
|
||
("transformer", "diffusion_pytorch_model.safetensors.index.json"),
|
||
("text_encoder", "model.safetensors.index.json"),
|
||
("vae", "diffusion_pytorch_model.safetensors.index.json"),
|
||
):
|
||
index = json.loads((model / component / index_name).read_text(encoding="utf-8"))
|
||
weight_map = index.get("weight_map")
|
||
if (not isinstance(weight_map, dict) or not weight_map
|
||
or any(not isinstance(name, str) or f"{component}/{name}" not in verified_paths
|
||
for name in weight_map.values())):
|
||
raise RuntimeError(f"H3 manifest does not cover every {component} weight shard")
|
||
return str(model)
|
||
|
||
|
||
def run(request: dict[str, Any]) -> tuple[list[Path], dict[str, Any]]:
|
||
from .adapters import _new_file, admit_gpu
|
||
from .video_profiles import H3_PROFILES, H3_V2_PROFILE, native_frames
|
||
|
||
parameters, inputs = request["parameters"], request["input"]
|
||
if request["task_type"] != "video.generate" or parameters.get("profile") not in H3_PROFILES:
|
||
raise ValueError("H3 adapter requires the explicit H3 video generation profile")
|
||
requested = parameters["num_frames"]
|
||
native = requested if parameters["profile"] == H3_V2_PROFILE else native_frames(requested)
|
||
if parameters["fps"] != 24 or (parameters["width"], parameters["height"]) not in {
|
||
(1344, 768), (768, 1344),
|
||
}:
|
||
raise ValueError("H3 profile requires 24 fps and the certified 768p canvas")
|
||
if inputs.get("negative_prompt") or "guidance_scale" in parameters:
|
||
raise ValueError("H3 is guidance-distilled and accepts no negative prompt or CFG scale")
|
||
model = _verified_model()
|
||
target = _new_file(Path(request["output_dir"]), "video_raw.mp4")
|
||
admit_gpu()
|
||
|
||
import numpy as np
|
||
import torch
|
||
import diffusers
|
||
from diffusers import ModularPipeline
|
||
from diffusers.hooks import apply_group_offloading
|
||
from diffusers.utils.export_utils import encode_video
|
||
from PIL import Image
|
||
|
||
pipeline = None
|
||
try:
|
||
pipeline = ModularPipeline.from_pretrained(model, local_files_only=True)
|
||
# 官方 modular 索引仍指向 Hub;显式覆盖每个 component 的仓库路径才能保证离线。
|
||
pipeline.load_components(workflow="fl2va", dtype=torch.bfloat16,
|
||
pretrained_model_name_or_path=model, local_files_only=True)
|
||
for name in ("transformer", "text_encoder", "vae", "audio_vae", "tokenizer",
|
||
"processor", "scheduler", "audio_scheduler"):
|
||
if getattr(pipeline, name, None) is None:
|
||
raise RuntimeError(f"H3 failed to load its required component: {name}")
|
||
pipeline.transformer.requires_grad_(False)
|
||
pipeline.text_encoder.requires_grad_(False)
|
||
# 加载CPU权重较慢,放入任何常驻GPU组件前重新检查外部任务优先策略。
|
||
admit_gpu()
|
||
offload = {"onload_device": torch.device("cuda:0"),
|
||
"offload_device": torch.device("cpu")}
|
||
dit_options = {"use_stream": True, "low_cpu_mem_usage": True, "record_stream": False}
|
||
text_encoder_options = {"use_stream": False, "low_cpu_mem_usage": False, "record_stream": False}
|
||
# 仅DiT流式预取:逐组临时pin并保留CPU权重副本用于回切,不预先pin整套DiT或文本编码器。
|
||
# pin池缓存及异步传输仍影响内存峰值,不能按单个block大小保证峰值;文本编码器保持同步leaf。
|
||
# 官方loader保留DiT关键投影与VAE的FP32权重,不能整体调用half/bfloat16转换。
|
||
pipeline.transformer.enable_group_offload(offload_type="block_level", num_blocks_per_group=1,
|
||
**offload, **dit_options)
|
||
apply_group_offloading(pipeline.text_encoder.model, offload_type="leaf_level",
|
||
**offload, **text_encoder_options)
|
||
pipeline.vae.to("cuda:0")
|
||
pipeline.audio_vae.to("cuda:0")
|
||
kwargs = {"prompt": inputs["prompt"], "height": parameters["height"],
|
||
"width": parameters["width"], "num_frames": native,
|
||
"num_inference_steps": parameters["num_inference_steps"],
|
||
"generator": torch.Generator("cpu").manual_seed(parameters["seed"]),
|
||
"output_type": "np", "output": ["videos"]}
|
||
if inputs.get("image_path"):
|
||
with Image.open(inputs["image_path"]) as image:
|
||
kwargs["image"] = image.convert("RGB")
|
||
if inputs.get("last_image_path"):
|
||
with Image.open(inputs["last_image_path"]) as image:
|
||
kwargs["last_image"] = image.convert("RGB")
|
||
with torch.inference_mode():
|
||
result = pipeline(**kwargs)
|
||
videos = result.get("videos")
|
||
if videos is None or len(videos) != 1:
|
||
raise RuntimeError("H3 returned no single video output")
|
||
frames = select_video_frames(videos[0], requested=requested, native=native)
|
||
array = np.asarray(frames)
|
||
if (array.shape != (requested, parameters["height"], parameters["width"], 3)
|
||
or not np.issubdtype(array.dtype, np.floating)
|
||
or not np.isfinite(array).all() or array.min() < 0 or array.max() > 1):
|
||
raise RuntimeError("H3 returned invalid video frame shape or pixel values")
|
||
# H3仍联合去噪音视频;这里只不封装原生音轨,保持现有独立配音/BGM合同。
|
||
encode_video(array, fps=24, output_path=str(target))
|
||
return [target], {
|
||
"engine": "diffusers-modular", "model": model, "stage": "generation",
|
||
"profile": parameters["profile"], "repo": MODEL_REPO, "revision": MODEL_REVISION,
|
||
"diffusers_version": diffusers.__version__, "diffusers_source_revision": DIFFUSERS_REVISION,
|
||
"native_frames": native, "requested_frames": requested,
|
||
"precision": "official mixed BF16/FP32", "parameters": parameters,
|
||
"cpu_offload": {"dit": "block_level", "text_encoder": "leaf_level",
|
||
"num_blocks_per_group": 1, "use_stream": dit_options["use_stream"],
|
||
"dit_options": dit_options, "text_encoder_options": text_encoder_options},
|
||
"audio": "native audio omitted from video; independent audio assembly",
|
||
}
|
||
finally:
|
||
if pipeline is not None:
|
||
del pipeline
|
||
gc.collect()
|
||
torch.cuda.empty_cache()
|