370 lines
11 KiB
Python
370 lines
11 KiB
Python
"""用假模型与真实CPU音频验证封装边界,任何测试都不加载CUDA。"""
|
||
|
||
import contextlib
|
||
import json
|
||
import sys
|
||
from types import ModuleType, SimpleNamespace
|
||
|
||
import numpy as np
|
||
import pytest
|
||
from llm_services import h3
|
||
from llm_services import h3_tp2_phase as phase
|
||
from llm_services.video_profiles import (
|
||
H3_NATIVE_AV_PROFILE,
|
||
H3_NATIVE_AV_TP2_PROFILE,
|
||
H3_TP2_PROFILE,
|
||
)
|
||
|
||
|
||
def test_single_native_pipeline_requests_audio_and_preserves_tail(
|
||
tmp_path, monkeypatch
|
||
):
|
||
class Frames:
|
||
shape, dtype = (124, 768, 1344, 3), np.dtype("float32")
|
||
|
||
def __len__(self):
|
||
return 124
|
||
|
||
def __getitem__(self, item):
|
||
assert item.stop == 124
|
||
return self
|
||
|
||
def min(self):
|
||
return 0
|
||
|
||
def max(self):
|
||
return 1
|
||
|
||
frames = Frames()
|
||
original_asarray, original_finite = np.asarray, np.isfinite
|
||
monkeypatch.setattr(
|
||
np,
|
||
"asarray",
|
||
lambda x, *a, **kw: (
|
||
x if isinstance(x, Frames) else original_asarray(x, *a, **kw)
|
||
),
|
||
)
|
||
monkeypatch.setattr(
|
||
np,
|
||
"isfinite",
|
||
lambda x: (
|
||
SimpleNamespace(all=lambda: True)
|
||
if isinstance(x, Frames)
|
||
else original_finite(x)
|
||
),
|
||
)
|
||
audio = np.zeros((1, 2, 165600), dtype=np.float32)
|
||
audio[0, :, -1] = [0.2, -0.2]
|
||
|
||
class Component:
|
||
model = object()
|
||
|
||
def requires_grad_(self, _):
|
||
pass
|
||
|
||
def to(self, _):
|
||
pass
|
||
|
||
def enable_group_offload(self, **kw):
|
||
pass
|
||
|
||
class Pipeline:
|
||
def __init__(self):
|
||
for name in (
|
||
"transformer",
|
||
"text_encoder",
|
||
"vae",
|
||
"audio_vae",
|
||
"tokenizer",
|
||
"processor",
|
||
"scheduler",
|
||
"audio_scheduler",
|
||
):
|
||
setattr(self, name, Component())
|
||
|
||
@classmethod
|
||
def from_pretrained(cls, *a, **kw):
|
||
return cls()
|
||
|
||
def load_components(self, **kw):
|
||
pass
|
||
|
||
def __call__(self, **kw):
|
||
assert kw["output"] == ["videos", "audio", "sampling_rate"]
|
||
assert kw["num_frames"] == 124
|
||
return {"videos": [frames], "audio": audio, "sampling_rate": 32000}
|
||
|
||
torch = ModuleType("torch")
|
||
torch.bfloat16, torch.device, torch.inference_mode = (
|
||
"bf16",
|
||
lambda x: x,
|
||
contextlib.nullcontext,
|
||
)
|
||
torch.cuda = SimpleNamespace(empty_cache=lambda: None)
|
||
torch.Generator = lambda _: SimpleNamespace(manual_seed=lambda _: None)
|
||
torch.from_numpy = lambda x: x
|
||
diffusers = ModuleType("diffusers")
|
||
diffusers.__path__, diffusers.__version__, diffusers.ModularPipeline = (
|
||
[],
|
||
"fixture",
|
||
Pipeline,
|
||
)
|
||
hooks, export, utils = (
|
||
ModuleType("diffusers.hooks"),
|
||
ModuleType("diffusers.utils.export_utils"),
|
||
ModuleType("diffusers.utils"),
|
||
)
|
||
hooks.apply_group_offloading = lambda *a, **kw: None
|
||
encoded = {}
|
||
|
||
def encode(array, **kw):
|
||
encoded.update(kw)
|
||
assert array is frames
|
||
assert kw["audio"].shape == (2, 165600)
|
||
assert np.allclose(kw["audio"][:, -1], [0.2, -0.2])
|
||
|
||
export.encode_video = encode
|
||
for name, mod in {
|
||
"torch": torch,
|
||
"diffusers": diffusers,
|
||
"diffusers.hooks": hooks,
|
||
"diffusers.utils": utils,
|
||
"diffusers.utils.export_utils": export,
|
||
}.items():
|
||
monkeypatch.setitem(sys.modules, name, mod)
|
||
from llm_services import adapters, native_av
|
||
|
||
monkeypatch.setattr(
|
||
native_av,
|
||
"verify_runtime",
|
||
lambda _: {"installed_source_revision": "fixture-revision"},
|
||
)
|
||
monkeypatch.setattr(adapters, "admit_gpu", lambda: None)
|
||
monkeypatch.setattr(h3, "_verified_model", lambda: "/fixture/model")
|
||
paths, meta = h3.run(
|
||
{
|
||
"task_type": "video.generate",
|
||
"input": {"prompt": "hello"},
|
||
"output_dir": str(tmp_path),
|
||
"parameters": {
|
||
"profile": H3_NATIVE_AV_PROFILE,
|
||
"num_frames": 124,
|
||
"fps": 24,
|
||
"width": 1344,
|
||
"height": 768,
|
||
"num_inference_steps": 2,
|
||
"seed": 1,
|
||
},
|
||
}
|
||
)
|
||
assert [p.name for p in paths] == ["video_raw.mp4", "audio_native.wav"]
|
||
assert (
|
||
meta["native_av"]["audio_samples"] == 165600
|
||
and meta["native_av"]["audio_trimmed"] is False
|
||
)
|
||
assert encoded["audio_sample_rate"] == 32000
|
||
|
||
|
||
def test_native_runtime_cannot_claim_revision_from_version_number_alone(
|
||
tmp_path, monkeypatch
|
||
):
|
||
from llm_services import native_av
|
||
|
||
source = tmp_path / "diffusers" / "__init__.py"
|
||
source.parent.mkdir()
|
||
source.touch()
|
||
monkeypatch.setattr(sys, "prefix", str(tmp_path))
|
||
metadata = SimpleNamespace(locate_file=lambda _: source, read_text=lambda _: None)
|
||
import importlib.metadata
|
||
|
||
monkeypatch.setattr(importlib.metadata, "distribution", lambda _: metadata)
|
||
with pytest.raises(RuntimeError, match="provenance|revision"):
|
||
native_av.verify_runtime(
|
||
SimpleNamespace(__file__=str(source), __version__="0.40.0.dev0")
|
||
)
|
||
|
||
|
||
@pytest.mark.parametrize(
|
||
"profile,audio_expected",
|
||
[(H3_NATIVE_AV_TP2_PROFILE, True), (H3_TP2_PROFILE, False)],
|
||
)
|
||
def test_tp2_denoised_state_keeps_native_audio_only_for_new_profile(
|
||
profile, audio_expected
|
||
):
|
||
latents = np.zeros((1, 24, 47, 1, 1), dtype=np.float32)
|
||
audio = np.zeros((2, 32, 263), dtype=np.float32)
|
||
torch = SimpleNamespace(float32=np.dtype("float32"), isfinite=np.isfinite)
|
||
state = SimpleNamespace(
|
||
get=lambda k: {"latents": latents, "audio_latents": audio}.get(k)
|
||
)
|
||
values = phase.denoised_values(
|
||
state, {"parameters": {"profile": profile, "num_frames": 158}}, torch
|
||
)
|
||
assert set(values) == (
|
||
{"latents", "audio_latents"} if audio_expected else {"latents"}
|
||
)
|
||
if audio_expected:
|
||
assert values["audio_latents"] is audio
|
||
|
||
|
||
def test_tp2_native_decode_refuses_missing_audio_state_before_loading_model(
|
||
tmp_path, monkeypatch
|
||
):
|
||
monkeypatch.setattr(
|
||
phase,
|
||
"load_state",
|
||
lambda *a, **kw: {"values": {"latents": object()}, "kwargs_mapping": {}},
|
||
)
|
||
monkeypatch.setattr(h3, "_verified_model", lambda: "/fixture/model")
|
||
# 外部依赖模块只提供导入名,实际pipeline不应被触发。
|
||
decoder = ModuleType("diffusers.modular_pipelines.minimax_h3.decoders")
|
||
decoder.MiniMaxH3VideoDecodeStep, decoder.MiniMaxH3AudioDecodeStep = (
|
||
object(),
|
||
object(),
|
||
)
|
||
state_mod = ModuleType("diffusers.modular_pipelines.modular_pipeline")
|
||
state_mod.PipelineState = object
|
||
export = ModuleType("diffusers.utils.export_utils")
|
||
export.encode_video = object()
|
||
for name, mod in {
|
||
decoder.__name__: decoder,
|
||
state_mod.__name__: state_mod,
|
||
export.__name__: export,
|
||
}.items():
|
||
monkeypatch.setitem(sys.modules, name, mod)
|
||
with pytest.raises(ValueError, match="denoised state"):
|
||
phase._decode(
|
||
{"parameters": {"profile": H3_NATIVE_AV_TP2_PROFILE}},
|
||
tmp_path,
|
||
object(),
|
||
"cpu",
|
||
)
|
||
|
||
|
||
def test_tp2_decode_outputs_full_video_and_audio_from_persisted_latents(
|
||
tmp_path, monkeypatch
|
||
):
|
||
from pathlib import Path
|
||
|
||
from llm_services import runner
|
||
|
||
class Frames:
|
||
shape, dtype = (158, 768, 1344, 3), np.dtype("float32")
|
||
|
||
def __len__(self):
|
||
return 158
|
||
|
||
def __getitem__(self, item):
|
||
assert item.stop == 158
|
||
return self
|
||
|
||
def min(self):
|
||
return 0
|
||
|
||
def max(self):
|
||
return 1
|
||
|
||
frames, audio = Frames(), np.zeros((1, 2, 210400), dtype=np.float32)
|
||
audio[0, :, -1] = [0.3, -0.3]
|
||
original_asarray, original_finite = np.asarray, np.isfinite
|
||
monkeypatch.setattr(
|
||
np,
|
||
"asarray",
|
||
lambda x, *a, **kw: (
|
||
x if isinstance(x, Frames) else original_asarray(x, *a, **kw)
|
||
),
|
||
)
|
||
monkeypatch.setattr(
|
||
np,
|
||
"isfinite",
|
||
lambda x: (
|
||
SimpleNamespace(all=lambda: True)
|
||
if isinstance(x, Frames)
|
||
else original_finite(x)
|
||
),
|
||
)
|
||
|
||
class State:
|
||
def __init__(self, values):
|
||
self.values = values
|
||
|
||
def get(self, k):
|
||
return self.values.get(k)
|
||
|
||
decoder = ModuleType("diffusers.modular_pipelines.minimax_h3.decoders")
|
||
decoder.MiniMaxH3VideoDecodeStep, decoder.MiniMaxH3AudioDecodeStep = (
|
||
object(),
|
||
object(),
|
||
)
|
||
state_mod = ModuleType("diffusers.modular_pipelines.modular_pipeline")
|
||
state_mod.PipelineState = State
|
||
export = ModuleType("diffusers.utils.export_utils")
|
||
|
||
def encode(array, **kwargs):
|
||
assert array is frames and kwargs["audio"].shape == (2, 210400)
|
||
assert np.allclose(kwargs["audio"][:, -1], [0.3, -0.3])
|
||
Path(kwargs["output_path"]).write_bytes(b"encoded audio and video fixture")
|
||
|
||
export.encode_video = encode
|
||
for name, mod in {
|
||
decoder.__name__: decoder,
|
||
state_mod.__name__: state_mod,
|
||
export.__name__: export,
|
||
}.items():
|
||
monkeypatch.setitem(sys.modules, name, mod)
|
||
torch = SimpleNamespace(
|
||
float32=np.dtype("float32"),
|
||
isfinite=original_finite,
|
||
inference_mode=contextlib.nullcontext,
|
||
from_numpy=lambda a: a,
|
||
)
|
||
monkeypatch.setitem(sys.modules, "torch", torch)
|
||
values = {
|
||
"latents": np.zeros((1, 24, 47, 48, 84), dtype=np.float32),
|
||
"audio_latents": np.zeros((2, 32, 263), dtype=np.float32),
|
||
}
|
||
monkeypatch.setattr(
|
||
phase, "load_state", lambda *a, **kw: {"values": values, "kwargs_mapping": {}}
|
||
)
|
||
|
||
def pipeline(blocks, model, names, _torch):
|
||
assert names == ["vae", "audio_vae"] and "audio_decode" in blocks
|
||
|
||
def decode(pipe, state):
|
||
assert state.get("audio_latents") is values["audio_latents"]
|
||
state.values.update(videos=[frames], audio=audio, sampling_rate=32000)
|
||
return pipe, state
|
||
|
||
return SimpleNamespace(
|
||
vae=SimpleNamespace(to=lambda _: None),
|
||
audio_vae=SimpleNamespace(to=lambda _: None),
|
||
blocks=decode,
|
||
)
|
||
|
||
monkeypatch.setattr(phase, "_pipeline", pipeline)
|
||
monkeypatch.setattr(phase, "_ownership", lambda: None)
|
||
monkeypatch.setattr(phase, "_parameter_dtypes", lambda *a: {})
|
||
monkeypatch.setattr(h3, "_verified_model", lambda: "/fixture/model")
|
||
monkeypatch.setattr(runner, "confined_path", lambda path: Path(path))
|
||
phase._decode(
|
||
{
|
||
"output_dir": str(tmp_path),
|
||
"parameters": {
|
||
"profile": H3_NATIVE_AV_TP2_PROFILE,
|
||
"num_frames": 158,
|
||
"height": 768,
|
||
"width": 1344,
|
||
},
|
||
},
|
||
tmp_path,
|
||
torch,
|
||
"cpu",
|
||
)
|
||
decoded = json.loads((tmp_path / "decoded.json").read_text(encoding="utf-8"))
|
||
assert [Path(p).name for p in decoded["paths"]] == [
|
||
"video_raw.mp4",
|
||
"audio_native.wav",
|
||
]
|
||
assert decoded["metadata"]["native_av"]["audio_samples"] == 210400
|
||
assert decoded["metadata"]["profile"] == H3_NATIVE_AV_TP2_PROFILE
|