cmvr-visual/inference/tests/test_native_av_contract.py

286 lines
9.8 KiB
Python
Raw Normal View History

"""原生音视频合同独立于静音证书,且不改写历史请求。"""
import hashlib
import json
import pytest
from llm_services import runner, video_profiles
from llm_services.store import Settings
SINGLE = "minimax-h3-fl2va-native-av-v1"
TP2 = "minimax-h3-fl2va-native-av-tp2-v1"
def payload(tmp_path, profile=SINGLE, **parameters):
image = tmp_path / "first.png"
image.touch()
return {
"task_type": "video.generate",
"input": {"prompt": "A person says hello.", "image_path": str(image)},
"parameters": {"profile": profile, **parameters},
"output_dir": str(tmp_path / "outputs" / "job"),
}
@pytest.mark.parametrize(
"profile,frames", [(SINGLE, 124), (SINGLE, 345), (TP2, 124), (TP2, 141), (TP2, 158)]
)
def test_native_requests_keep_full_generated_frame_interval(tmp_path, profile, frames):
normalized = runner.validate_request(
payload(tmp_path, profile, num_frames=frames), workspace=tmp_path
)
assert normalized["parameters"]["num_frames"] == frames
assert normalized["parameters"]["profile"] == profile
assert normalized["parameters"]["fps"] == 24
assert normalized["parameters"]["upscale"] is False
@pytest.mark.parametrize(
"profile,frames",
[(SINGLE, 121), (SINGLE, 145), (SINGLE, 346), (TP2, 145), (TP2, 175)],
)
def test_native_rejects_crop_frame_counts_and_unqualified_tp2_capacity(
tmp_path, profile, frames
):
with pytest.raises(ValueError, match="native|158"):
runner.validate_request(
payload(tmp_path, profile, num_frames=frames), workspace=tmp_path
)
def test_native_single_keeps_last_keyframe_but_rejects_upscale(tmp_path):
data = payload(tmp_path, conditioning_mode="first_last_frame")
last = tmp_path / "last.png"
last.touch()
data["input"]["last_image_path"] = str(last)
assert runner.validate_request(data, workspace=tmp_path)["input"][
"last_image_path"
] == str(last)
data["parameters"]["upscale"] = True
with pytest.raises(ValueError, match="upscale"):
runner.validate_request(data, workspace=tmp_path)
def test_silent_flags_cannot_enable_native_av(tmp_path):
settings = Settings(
tmp_path / "app",
tmp_path,
video_generation_enabled=True,
video_generation_v2_enabled=True,
video_generation_tp2_enabled=True,
)
for profile, key in ((SINGLE, "native_av"), (TP2, "native_av_tp2")):
cap = video_profiles.capabilities(settings)[key]
assert cap["available"] is False and cap["profile"] == profile
assert (
cap["audio_output"] is True
and cap["audio_sample_rate"] == 32000
and cap["audio_channels"] == 2
)
with pytest.raises(ValueError, match="certified|enabled"):
video_profiles.validate_submission(settings, {"profile": profile})
settings.native_dialogue_enabled = settings.native_dialogue_tp2_enabled = True
assert video_profiles.capabilities(settings)["native_av"]["available"] is False
assert video_profiles.capabilities(settings)["native_av_tp2"]["available"] is False
def test_native_is_routed_to_pair_and_has_independent_safe_memory_floor(tmp_path):
from llm_services.resources import memory_reservation_gib
from llm_services.worker import Worker
settings = Settings(tmp_path / "app", tmp_path, video_generation_tp2_memory_gib=144)
assert Worker._requires_pair(payload(tmp_path, TP2))
assert not Worker._requires_pair(payload(tmp_path, SINGLE))
assert memory_reservation_gib(settings, "video.generate", {"profile": TP2}) >= 288
assert (
memory_reservation_gib(settings, "video.generate", {"profile": SINGLE}) >= 288
)
assert (
memory_reservation_gib(
settings, "video.generate", {"profile": video_profiles.H3_TP2_PROFILE}
)
== 144
)
def test_native_state_cannot_be_loaded_under_silent_profile(tmp_path, monkeypatch):
from llm_services import h3_tp2_state as state
monkeypatch.setenv("LLM_TP2_PROFILE", TP2)
state.save_state(tmp_path, "denoised", {"values": {}, "kwargs_mapping": {}})
manifest = json.loads((tmp_path / "denoised.json").read_text())
assert manifest["binding"]["profile"] == TP2
monkeypatch.delenv("LLM_TP2_PROFILE")
with pytest.raises(ValueError, match="binding"):
state.load_state(tmp_path, "denoised")
def test_native_phase_requires_full_frames_in_its_hashed_request(tmp_path, monkeypatch):
from llm_services import h3_tp2_phase as phase
data = payload(
tmp_path,
TP2,
num_frames=158,
fps=24,
upscale=False,
width=1344,
height=768,
seed=7,
num_inference_steps=2,
)
path = tmp_path / "request.json"
path.write_text(json.dumps(data))
monkeypatch.setenv(
"LLM_TP2_REQUEST_SHA256",
hashlib.sha256(
json.dumps(
data,
sort_keys=True,
separators=(",", ":"),
ensure_ascii=False,
allow_nan=False,
).encode()
).hexdigest(),
)
monkeypatch.setenv("LLM_TP2_PROFILE", TP2)
assert phase._request(path)["parameters"]["num_frames"] == 158
monkeypatch.delenv("LLM_TP2_PROFILE")
with pytest.raises(ValueError, match="profile|binding"):
phase._request(path)
def test_runner_preserves_native_av_evidence_at_top_level(tmp_path, monkeypatch):
from llm_services import adapters
data = runner.validate_request(payload(tmp_path), workspace=tmp_path)
monkeypatch.setattr(adapters, "budgeted_child_environment", lambda _: {})
monkeypatch.setattr(adapters, "admit_gpu", lambda: None)
def child(command, env, log, timeout):
output = tmp_path / "outputs" / "job"
for name in ("video_raw.mp4", "audio_native.wav"):
(output / name).write_bytes(b"fixture media")
result = command[command.index("--result") + 1]
from pathlib import Path
Path(result).write_text(
json.dumps(
{
"outputs": [
{"path": "video_raw.mp4"},
{"path": "audio_native.wav"},
],
"metadata": {
"profile": SINGLE,
"native_av": {"audio_samples": 165600},
},
}
)
)
monkeypatch.setattr(runner, "_run_child", child)
result = runner.execute(data)
assert result["metadata"]["profile"] == SINGLE
assert result["metadata"]["native_av"]["audio_samples"] == 165600
def test_tp2_runner_adds_both_final_indices_without_rewriting_adapter_metadata(
tmp_path, monkeypatch
):
from copy import deepcopy
from llm_services import h3_tp2
request = runner.validate_request(
payload(tmp_path, TP2, num_frames=158), workspace=tmp_path
)
output = tmp_path / "outputs" / "job"
output.mkdir(parents=True)
paths = [output / "video_raw.mp4", output / "audio_native.wav"]
for p in paths:
p.write_bytes(b"decoded native output")
metadata = {
"profile": TP2,
"engine": "diffusers-modular-tp2",
"native_av": {"audio_samples": 210400},
}
original, frozen_request = deepcopy(metadata), deepcopy(request)
monkeypatch.setattr(h3_tp2, "run", lambda _: (paths, metadata))
result = runner.execute(request)
assert result["metadata"]["final_output_indices"] == [0, 1]
assert [o["path"] for o in result["outputs"]] == [
"video_raw.mp4",
"audio_native.wav",
]
assert metadata == original and request == frozen_request
@pytest.mark.parametrize(
"bad", ["missing_wav", "reverse", "extra", "explicit_wrong_index"]
)
def test_tp2_runner_does_not_label_a_malformed_native_pair_as_final(
tmp_path, monkeypatch, bad
):
from llm_services import h3_tp2
request = runner.validate_request(
payload(tmp_path, TP2, num_frames=158), workspace=tmp_path
)
output = tmp_path / "outputs" / "job"
output.mkdir(parents=True)
paths = [output / "video_raw.mp4", output / "audio_native.wav"]
metadata = {"profile": TP2}
if bad == "missing_wav":
paths.pop()
elif bad == "reverse":
paths.reverse()
elif bad == "extra":
paths.append(output / "extra.wav")
else:
metadata["final_output_indices"] = [0]
for p in paths:
p.write_bytes(b"decoded native output")
monkeypatch.setattr(h3_tp2, "run", lambda _: (paths, metadata))
with pytest.raises(ValueError, match="[Nn]ative|原生"):
runner.execute(request)
def test_legacy_silent_tp2_runner_result_shape_stays_unchanged(tmp_path, monkeypatch):
from llm_services import h3_tp2
request = runner.validate_request(
payload(tmp_path, video_profiles.H3_TP2_PROFILE), workspace=tmp_path
)
output = tmp_path / "outputs" / "job"
output.mkdir(parents=True)
video = output / "video_raw.mp4"
video.write_bytes(b"legacy silent output")
metadata = {
"profile": video_profiles.H3_TP2_PROFILE,
"audio": "native audio omitted",
}
monkeypatch.setattr(h3_tp2, "run", lambda _: ([video], metadata))
result = runner.execute(request)
assert result["metadata"] == metadata
assert "final_output_indices" not in result["metadata"]
def test_old_profile_default_hash_stays_unchanged(tmp_path):
data = payload(tmp_path, video_profiles.H3_PROFILE)
result = runner.validate_request(data, workspace=tmp_path)["parameters"]
assert result == {
"profile": video_profiles.H3_PROFILE,
"width": 1344,
"height": 768,
"num_frames": 121,
"fps": 24,
"num_inference_steps": 50,
"seed": 42,
"upscale": False,
"upscale_width": 1920,
"upscale_height": 1080,
"tile_size": 128,
}