[Model] Add circlestone-labs/Anima (#4083)
Signed-off-by: akshatvishu <akshatnayak197@gmail.com>
This commit is contained in:
1 parent
698f716012
commit
415005be22
33 files changed
+3127
-46
No files matched your search
@@ -0,0 +1,2 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
|
||||
@@ -0,0 +1,454 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
|
||||
|
||||
import json
|
||||
from pathlib import Path
|
||||
from shutil import rmtree
|
||||
from types import SimpleNamespace
|
||||
|
||||
import pytest
|
||||
import torch
|
||||
from safetensors.torch import save_file
|
||||
|
||||
from tests.model_tests.diffusion.anima_builder import CHECKPOINT_FILENAME, tiny_anima_builder
|
||||
from vllm_omni.diffusion.attention import selector
|
||||
from vllm_omni.diffusion.attention.backends.sdpa import SDPABackend
|
||||
from vllm_omni.diffusion.data import DiffusionOutput, OmniDiffusionConfig
|
||||
from vllm_omni.diffusion.distributed.autoencoders.autoencoder_kl_qwenimage import DistributedAutoencoderKLQwenImage
|
||||
from vllm_omni.diffusion.models.anima import pipeline_anima
|
||||
from vllm_omni.diffusion.models.anima.anima_text_conditioner import AnimaTextConditioner
|
||||
from vllm_omni.diffusion.models.anima.anima_transformer import AnimaTransformer3DModel
|
||||
from vllm_omni.diffusion.models.anima.pipeline_anima import AnimaPipeline
|
||||
from vllm_omni.diffusion.request import OmniDiffusionRequest
|
||||
from vllm_omni.diffusion.worker.request_batch import DiffusionRequestBatch
|
||||
from vllm_omni.inputs.data import OmniDiffusionSamplingParams
|
||||
from vllm_omni.platforms import current_omni_platform
|
||||
|
||||
pytestmark = [pytest.mark.core_model, pytest.mark.cpu, pytest.mark.diffusion]
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"offload_args",
|
||||
[
|
||||
{"enable_cpu_offload": True},
|
||||
{"enable_layerwise_offload": True},
|
||||
{"enable_distributed_layerwise_offload": True},
|
||||
{"diffusion_offload_config": {"mode": "module", "components": ["dit"]}},
|
||||
{
|
||||
"diffusion_offload_config": {
|
||||
"mode": "layer",
|
||||
"components": ["dit"],
|
||||
"layer_options": {"dit": {"weight_transfer": "rank-local"}},
|
||||
}
|
||||
},
|
||||
],
|
||||
)
|
||||
def test_native_anima_rejects_offload(offload_args):
|
||||
config = OmniDiffusionConfig(model="anima.safetensors", **offload_args)
|
||||
with pytest.raises(NotImplementedError, match="offload"):
|
||||
AnimaPipeline(od_config=config, device=torch.device("cpu"))
|
||||
|
||||
|
||||
def test_native_anima_initializes_without_offload():
|
||||
config = OmniDiffusionConfig(model="anima.safetensors")
|
||||
AnimaPipeline(od_config=config, device=torch.device("cpu"))
|
||||
|
||||
|
||||
def test_anima_registration() -> None:
|
||||
"""The native Anima pipeline is registered and importable."""
|
||||
from vllm_omni.diffusion.registry import DiffusionModelRegistry
|
||||
|
||||
assert DiffusionModelRegistry._try_load_model_cls("AnimaPipeline") is not None
|
||||
|
||||
|
||||
@pytest.mark.parametrize("model_class_name", ["AnimaPipeline", "AnimaModularPipeline"])
|
||||
def test_enrich_config_native_anima_checkpoint(tmp_path: Path, model_class_name: str) -> None:
|
||||
"""Native and reference Anima class names resolve to AnimaPipeline."""
|
||||
dummy_checkpoint = tmp_path / "model.safetensors"
|
||||
dummy_checkpoint.write_text("dummy")
|
||||
|
||||
config = OmniDiffusionConfig(
|
||||
model=str(dummy_checkpoint),
|
||||
model_class_name=model_class_name,
|
||||
)
|
||||
config.enrich_config()
|
||||
|
||||
assert config.diffusion_load_format == "default"
|
||||
assert config.model_class_name == "AnimaPipeline"
|
||||
assert config.diffusers_pipeline_cls is None
|
||||
|
||||
|
||||
def test_native_anima_component_paths_use_custom_pipeline_args() -> None:
|
||||
"""Anima resolves shared and component-specific paths from native args."""
|
||||
pipeline = AnimaPipeline.__new__(AnimaPipeline)
|
||||
pipeline.od_config = SimpleNamespace(
|
||||
custom_pipeline_args={
|
||||
"components_path": "/tmp/anima-components",
|
||||
"vae_path": "/tmp/anima-vae",
|
||||
"text_encoder_model": "/tmp/anima-text-encoder",
|
||||
}
|
||||
)
|
||||
|
||||
assert pipeline._component_path("vae", "/tmp/default") == "/tmp/anima-vae"
|
||||
assert pipeline._component_path("text_encoder", "/tmp/default") == "/tmp/anima-text-encoder"
|
||||
assert pipeline._component_path("tokenizer", "/tmp/default") == "/tmp/default"
|
||||
|
||||
|
||||
def test_native_anima_converts_original_cosmos_transformer_keys() -> None:
|
||||
"""Original Cosmos checkpoint names map to native module names."""
|
||||
converted = AnimaPipeline._convert_original_transformer_state_dict(
|
||||
{
|
||||
"net.x_embedder.proj.1.weight": "patch",
|
||||
"net.blocks.0.self_attn.q_proj.weight": "q",
|
||||
"net.blocks.0.self_attn.q_norm.weight": "q_norm",
|
||||
"net.blocks.0.mlp.layer1.weight": "mlp",
|
||||
"net.final_layer.linear.weight": "out",
|
||||
"net.accum_iteration": "drop",
|
||||
}
|
||||
)
|
||||
|
||||
assert converted == {
|
||||
"patch_embed.proj.weight": "patch",
|
||||
"transformer_blocks.0.attn1.to_q.weight": "q",
|
||||
"transformer_blocks.0.attn1.norm_q.weight": "q_norm",
|
||||
"transformer_blocks.0.ff.net.0.proj.weight": "mlp",
|
||||
"proj_out.weight": "out",
|
||||
}
|
||||
|
||||
|
||||
def test_native_anima_resolves_vae_scale_factor_from_loaded_vae() -> None:
|
||||
"""The loaded VAE determines the spatial scale factor."""
|
||||
from vllm_omni.diffusion.models.anima.pipeline_anima import _anima_vae_scale_factor_from_vae
|
||||
|
||||
vae = SimpleNamespace(config=SimpleNamespace(spatial_compression_ratio=16))
|
||||
|
||||
assert _anima_vae_scale_factor_from_vae(vae) == 16
|
||||
|
||||
|
||||
@pytest.mark.parametrize("use_config_file", [False, True])
|
||||
def test_native_anima_loads_synthetic_checkpoint(
|
||||
tmp_path: Path, monkeypatch: pytest.MonkeyPatch, use_config_file: bool
|
||||
) -> None:
|
||||
"""Native modules load exact weights from an Anima safetensors checkpoint."""
|
||||
tiny_transformer_config = {
|
||||
"in_channels": 1,
|
||||
"out_channels": 1,
|
||||
"num_attention_heads": 1,
|
||||
"attention_head_dim": 12,
|
||||
"num_layers": 1,
|
||||
"mlp_ratio": 1.0,
|
||||
"text_embed_dim": 4,
|
||||
"adaln_lora_dim": 3,
|
||||
"max_size": (1, 2, 2),
|
||||
"patch_size": (1, 1, 1),
|
||||
"rope_scale": (1.0, 1.0, 1.0),
|
||||
"concat_padding_mask": True,
|
||||
"extra_pos_embed_type": None,
|
||||
}
|
||||
tiny_text_conditioner_config = {
|
||||
"source_dim": 4,
|
||||
"target_dim": 4,
|
||||
"model_dim": 4,
|
||||
"num_layers": 1,
|
||||
"num_attention_heads": 1,
|
||||
"target_vocab_size": 8,
|
||||
"min_sequence_length": 4,
|
||||
}
|
||||
if use_config_file:
|
||||
(tmp_path / "anima.json").write_text(
|
||||
json.dumps({"transformer": tiny_transformer_config, "text_conditioner": tiny_text_conditioner_config})
|
||||
)
|
||||
else:
|
||||
monkeypatch.setattr(pipeline_anima, "ANIMA_TRANSFORMER_CONFIG", tiny_transformer_config)
|
||||
monkeypatch.setattr(pipeline_anima, "ANIMA_TEXT_CONDITIONER_CONFIG", tiny_text_conditioner_config)
|
||||
|
||||
monkeypatch.setattr(selector, "_cached_get_backend_cls", lambda *_args, **_kwargs: SDPABackend)
|
||||
transformer = AnimaTransformer3DModel(**tiny_transformer_config)
|
||||
text_conditioner = AnimaTextConditioner(**tiny_text_conditioner_config)
|
||||
transformer_state = {name: tensor.detach().clone() for name, tensor in transformer.state_dict().items()}
|
||||
text_conditioner_state = {name: tensor.detach().clone() for name, tensor in text_conditioner.state_dict().items()}
|
||||
checkpoint_state = {
|
||||
**{f"transformer.{name}": tensor for name, tensor in transformer_state.items()},
|
||||
**{f"text_conditioner.{name}": tensor for name, tensor in text_conditioner_state.items()},
|
||||
}
|
||||
|
||||
checkpoint_path = tmp_path / "anima.safetensors"
|
||||
save_file(checkpoint_state, str(checkpoint_path))
|
||||
|
||||
pipeline = AnimaPipeline.__new__(AnimaPipeline)
|
||||
pipeline.od_config = SimpleNamespace(model=str(checkpoint_path), dtype=torch.float32)
|
||||
pipeline.device = torch.device("cpu")
|
||||
|
||||
def assert_loaded(loaded_transformer, loaded_text_conditioner):
|
||||
for name, tensor in transformer_state.items():
|
||||
assert torch.equal(loaded_transformer.state_dict()[name], tensor)
|
||||
for name, tensor in text_conditioner_state.items():
|
||||
assert torch.equal(loaded_text_conditioner.state_dict()[name], tensor)
|
||||
|
||||
loaded_transformer, loaded_text_conditioner = pipeline._load_native_denoiser_components(dict(checkpoint_state))
|
||||
assert_loaded(loaded_transformer, loaded_text_conditioner)
|
||||
|
||||
loaded_transformer, loaded_text_conditioner = pipeline._load_native_denoiser_components()
|
||||
assert_loaded(loaded_transformer, loaded_text_conditioner)
|
||||
|
||||
if use_config_file:
|
||||
tiny_transformer_config["num_layers"] = 2
|
||||
(tmp_path / "anima.json").write_text(
|
||||
json.dumps({"transformer": tiny_transformer_config, "text_conditioner": tiny_text_conditioner_config})
|
||||
)
|
||||
with pytest.raises(RuntimeError, match="Missing key"):
|
||||
pipeline._load_native_denoiser_components()
|
||||
|
||||
|
||||
def test_tiny_anima_generates_images(monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
"""Load every saved component and exercise CFG, decoding, and multiple outputs on CPU."""
|
||||
monkeypatch.setattr(selector, "_cached_get_backend_cls", lambda *_args, **_kwargs: SDPABackend)
|
||||
monkeypatch.setattr(current_omni_platform, "is_available", lambda: False)
|
||||
monkeypatch.setattr(
|
||||
DistributedAutoencoderKLQwenImage,
|
||||
"init_distributed",
|
||||
lambda self: setattr(self, "distributed_executor", SimpleNamespace(parallel_size=1)),
|
||||
)
|
||||
model_dir = tiny_anima_builder()
|
||||
try:
|
||||
config = OmniDiffusionConfig(
|
||||
model=str(Path(model_dir) / CHECKPOINT_FILENAME), model_class_name="AnimaPipeline", dtype=torch.float32
|
||||
)
|
||||
pipeline = AnimaPipeline(od_config=config, device=torch.device("cpu"))
|
||||
pipeline.load_weights()
|
||||
pipeline.eval()
|
||||
outputs = []
|
||||
with torch.inference_mode():
|
||||
for _ in range(2):
|
||||
request = OmniDiffusionRequest(
|
||||
prompt="Dummy prompt",
|
||||
request_id="tiny-anima",
|
||||
sampling_params=OmniDiffusionSamplingParams(
|
||||
height=32,
|
||||
width=32,
|
||||
num_inference_steps=2,
|
||||
guidance_scale=4.0,
|
||||
num_outputs_per_prompt=2,
|
||||
generator=torch.Generator(device="cpu").manual_seed(42),
|
||||
),
|
||||
)
|
||||
outputs.append(pipeline(DiffusionRequestBatch([request]))[0].output)
|
||||
assert outputs[0].shape == (2, 3, 32, 32)
|
||||
assert torch.isfinite(outputs[0]).all()
|
||||
assert torch.equal(outputs[0], outputs[1])
|
||||
assert not torch.equal(outputs[0][0], outputs[0][1])
|
||||
finally:
|
||||
rmtree(model_dir)
|
||||
|
||||
|
||||
def test_native_anima_profiler_setup_is_deferred_and_idempotent(monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
"""Profiler targets are wrapped once, after deferred components are loaded."""
|
||||
pipeline = AnimaPipeline.__new__(AnimaPipeline)
|
||||
pipeline.od_config = SimpleNamespace(enable_diffusion_pipeline_profiler=True)
|
||||
pipeline._profiler_initialized = False
|
||||
pipeline.vae = SimpleNamespace(decode=lambda: "decoded")
|
||||
pipeline.text_encoder = SimpleNamespace(forward=lambda: "encoded")
|
||||
|
||||
monkeypatch.setattr(current_omni_platform, "is_available", lambda: False)
|
||||
pipeline._setup_profiler()
|
||||
wrapped_decode = pipeline.vae.decode
|
||||
wrapped_text_encoder = pipeline.text_encoder.forward
|
||||
pipeline._setup_profiler()
|
||||
|
||||
assert pipeline.vae.decode is wrapped_decode
|
||||
assert pipeline.text_encoder.forward is wrapped_text_encoder
|
||||
assert pipeline.vae.decode() == "decoded"
|
||||
assert pipeline.text_encoder.forward() == "encoded"
|
||||
assert "AnimaPipeline.vae.decode" in pipeline.stage_durations
|
||||
assert "AnimaPipeline.text_encoder.forward" in pipeline.stage_durations
|
||||
|
||||
|
||||
def _make_anima_forward_probe():
|
||||
pipeline = AnimaPipeline.__new__(AnimaPipeline)
|
||||
pipeline.device = torch.device("cpu")
|
||||
pipeline.vae_scale_factor = 8
|
||||
pipeline.transformer = SimpleNamespace(dtype=torch.float32)
|
||||
pipeline.text_encoder = SimpleNamespace(dtype=torch.float32)
|
||||
pipeline._current_timestep = None
|
||||
pipeline._num_timesteps = 0
|
||||
pipeline._guidance_scale = 0.0
|
||||
captured = {}
|
||||
|
||||
def encode_prompt(**_kwargs):
|
||||
return {
|
||||
"qwen_prompt_embeds": torch.zeros(1, 2, 4),
|
||||
"qwen_attention_mask": torch.ones(1, 2),
|
||||
"t5_input_ids": torch.ones(1, 2, dtype=torch.long),
|
||||
"t5_attention_mask": torch.ones(1, 2),
|
||||
"negative_qwen_prompt_embeds": torch.zeros(1, 2, 4),
|
||||
"negative_qwen_attention_mask": torch.ones(1, 2),
|
||||
"negative_t5_input_ids": torch.ones(1, 2, dtype=torch.long),
|
||||
"negative_t5_attention_mask": torch.ones(1, 2),
|
||||
}
|
||||
|
||||
def condition_prompt_embeds(**_kwargs):
|
||||
return torch.zeros(1, 2, 4)
|
||||
|
||||
def prepare_latents(**kwargs):
|
||||
captured["prepare_latents"] = kwargs
|
||||
return torch.zeros(1, 16, 1, kwargs["height"] // 8, kwargs["width"] // 8)
|
||||
|
||||
def diffuse(**kwargs):
|
||||
captured["diffuse"] = kwargs
|
||||
return kwargs["latents"]
|
||||
|
||||
pipeline.encode_prompt = encode_prompt
|
||||
pipeline.condition_prompt_embeds = condition_prompt_embeds
|
||||
pipeline.prepare_latents = prepare_latents
|
||||
pipeline.prepare_timesteps = lambda **_kwargs: (torch.ones(1), 1)
|
||||
pipeline.diffuse = diffuse
|
||||
|
||||
def decode_latents(latents, output_type="pil"):
|
||||
captured["output_type"] = output_type
|
||||
return DiffusionOutput(output=latents)
|
||||
|
||||
pipeline.decode_latents = decode_latents
|
||||
return pipeline, captured
|
||||
|
||||
|
||||
def test_native_anima_forward_uses_official_default_resolution() -> None:
|
||||
"""Forward uses Anima's reference resolution when none is requested."""
|
||||
pipeline, captured = _make_anima_forward_probe()
|
||||
req = OmniDiffusionRequest(
|
||||
prompt="a red cube",
|
||||
sampling_params=OmniDiffusionSamplingParams(),
|
||||
request_id="anima-defaults",
|
||||
)
|
||||
|
||||
pipeline.forward(DiffusionRequestBatch([req]))
|
||||
|
||||
assert captured["prepare_latents"]["height"] == 1024
|
||||
assert captured["prepare_latents"]["width"] == 1024
|
||||
|
||||
|
||||
def test_native_anima_forward_honors_sampling_output_type() -> None:
|
||||
"""Request-level output type controls Anima decoding."""
|
||||
pipeline, captured = _make_anima_forward_probe()
|
||||
req = OmniDiffusionRequest(
|
||||
prompt="a red cube",
|
||||
sampling_params=OmniDiffusionSamplingParams(output_type="latent"),
|
||||
request_id="anima-output-type",
|
||||
)
|
||||
|
||||
outputs = pipeline.forward(DiffusionRequestBatch([req]))
|
||||
|
||||
assert len(outputs) == 1
|
||||
assert isinstance(outputs[0], DiffusionOutput)
|
||||
assert outputs[0].output.shape == (1, 16, 1, 128, 128)
|
||||
assert captured["output_type"] == "latent"
|
||||
|
||||
|
||||
@pytest.mark.parametrize("request_count", [0, 2])
|
||||
def test_native_anima_forward_rejects_non_single_request_batches(request_count: int) -> None:
|
||||
pipeline, captured = _make_anima_forward_probe()
|
||||
requests = [
|
||||
OmniDiffusionRequest(
|
||||
prompt="a red cube",
|
||||
sampling_params=OmniDiffusionSamplingParams(),
|
||||
request_id=f"anima-{index}",
|
||||
)
|
||||
for index in range(request_count)
|
||||
]
|
||||
|
||||
with pytest.raises(ValueError, match="supports one request per forward"):
|
||||
pipeline.forward(DiffusionRequestBatch(requests))
|
||||
|
||||
assert captured == {}
|
||||
|
||||
|
||||
def test_native_anima_explicit_guidance_scale_drives_cfg_multiplier() -> None:
|
||||
"""An explicit guidance scale controls native classifier-free guidance."""
|
||||
pipeline, captured = _make_anima_forward_probe()
|
||||
req = OmniDiffusionRequest(
|
||||
prompt="a red cube",
|
||||
sampling_params=OmniDiffusionSamplingParams(guidance_scale=5.0),
|
||||
request_id="anima-guidance",
|
||||
)
|
||||
|
||||
pipeline.forward(DiffusionRequestBatch([req]))
|
||||
|
||||
assert captured["diffuse"]["do_true_cfg"] is True
|
||||
assert captured["diffuse"]["true_cfg_scale"] == 5.0
|
||||
|
||||
|
||||
def test_native_anima_true_cfg_scale_overrides_guidance_multiplier() -> None:
|
||||
"""An explicit true-CFG scale overrides the guidance-scale multiplier."""
|
||||
pipeline, captured = _make_anima_forward_probe()
|
||||
req = OmniDiffusionRequest(
|
||||
prompt="a red cube",
|
||||
sampling_params=OmniDiffusionSamplingParams(guidance_scale=5.0, true_cfg_scale=3.0),
|
||||
request_id="anima-true-cfg",
|
||||
)
|
||||
|
||||
pipeline.forward(DiffusionRequestBatch([req]))
|
||||
|
||||
assert captured["diffuse"]["do_true_cfg"] is True
|
||||
assert captured["diffuse"]["true_cfg_scale"] == 3.0
|
||||
|
||||
|
||||
def test_native_anima_cfg_equation() -> None:
|
||||
"""The denoising loop applies the standard true-CFG equation."""
|
||||
pipeline = AnimaPipeline.__new__(AnimaPipeline)
|
||||
pipeline.device = torch.device("cpu")
|
||||
pipeline._interrupt = False
|
||||
|
||||
class MockProgressBar:
|
||||
def __enter__(self):
|
||||
return self
|
||||
|
||||
def __exit__(self, exc_type, exc_val, exc_tb):
|
||||
pass
|
||||
|
||||
def update(self):
|
||||
pass
|
||||
|
||||
pipeline.progress_bar = lambda **_kwargs: MockProgressBar()
|
||||
|
||||
class MockTransformer:
|
||||
dtype = torch.float32
|
||||
|
||||
def __call__(self, hidden_states, timestep, encoder_hidden_states, padding_mask, return_dict=False):
|
||||
# Return double the encoder_hidden_states to simulate transformer output
|
||||
return (encoder_hidden_states * 2.0,)
|
||||
|
||||
pipeline.transformer = MockTransformer()
|
||||
|
||||
class MockScheduler:
|
||||
def set_begin_index(self, index):
|
||||
pass
|
||||
|
||||
def step(self, noise_pred, t, latents, return_dict=False):
|
||||
# Return the noise_pred itself to inspect it
|
||||
return (noise_pred,)
|
||||
|
||||
pipeline.scheduler = MockScheduler()
|
||||
|
||||
prompt_embeds = torch.tensor([[[2.0, 3.0]]])
|
||||
negative_prompt_embeds = torch.tensor([[[1.0, 2.0]]])
|
||||
latents = torch.zeros(1, 16, 1, 16, 16)
|
||||
padding_mask = torch.zeros(1, 1, 16, 16)
|
||||
timesteps = torch.tensor([500.0])
|
||||
|
||||
# Cond = prompt_embeds * 2.0 = [4.0, 6.0]
|
||||
# Uncond = negative_prompt_embeds * 2.0 = [2.0, 4.0]
|
||||
# Expected noise_pred = uncond + true_cfg_scale * (cond - uncond)
|
||||
# = [2.0, 4.0] + 4.0 * ([4.0, 6.0] - [2.0, 4.0])
|
||||
# = [2.0, 4.0] + 4.0 * [2.0, 2.0]
|
||||
# = [2.0, 4.0] + [8.0, 8.0] = [10.0, 12.0]
|
||||
out_latents = pipeline.diffuse(
|
||||
prompt_embeds=prompt_embeds,
|
||||
negative_prompt_embeds=negative_prompt_embeds,
|
||||
latents=latents,
|
||||
padding_mask=padding_mask,
|
||||
timesteps=timesteps,
|
||||
do_true_cfg=True,
|
||||
true_cfg_scale=4.0,
|
||||
)
|
||||
|
||||
expected = torch.tensor([[[10.0, 12.0]]])
|
||||
assert torch.allclose(out_latents, expected)
|
||||
@@ -100,6 +100,28 @@ class TestWorkerWrapperBaseInitialization:
|
||||
skip_load_model=False,
|
||||
)
|
||||
|
||||
def test_custom_pipeline_args_without_pipeline_class_loads_normally(self, mocker: MockerFixture, mock_od_config):
|
||||
"""Test native pipeline args do not trigger custom pipeline re-initialization."""
|
||||
custom_args = {"components_path": "/tmp/anima-components"}
|
||||
mock_worker_init = mocker.patch.object(DiffusionWorker, "__init__", return_value=None)
|
||||
|
||||
wrapper = WorkerWrapperBase(
|
||||
gpu_id=0,
|
||||
od_config=mock_od_config,
|
||||
base_worker_class=DiffusionWorker,
|
||||
custom_pipeline_args=custom_args,
|
||||
)
|
||||
|
||||
assert wrapper.worker_extension_cls is None
|
||||
assert CustomPipelineWorkerExtension not in wrapper.worker.__class__.__bases__
|
||||
assert not hasattr(wrapper.worker, "re_init_pipeline")
|
||||
mock_worker_init.assert_called_once_with(
|
||||
local_rank=0,
|
||||
rank=0,
|
||||
od_config=mock_od_config,
|
||||
skip_load_model=False,
|
||||
)
|
||||
|
||||
|
||||
# -------------------------------------------------------------------------
|
||||
# Tests: Worker Extension Functionality
|
||||
@@ -476,6 +498,12 @@ class TestCustomPipelineWorkerExtension:
|
||||
custom_pipeline_args=custom_args,
|
||||
)
|
||||
|
||||
mock_worker_class.assert_called_once_with(
|
||||
local_rank=0,
|
||||
rank=0,
|
||||
od_config=mock_od_config,
|
||||
skip_load_model=True,
|
||||
)
|
||||
# Verify re_init_pipeline was called with custom_pipeline_args
|
||||
mock_worker_instance.re_init_pipeline.assert_called_once_with(custom_args)
|
||||
|
||||
|
||||
@@ -0,0 +1,63 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
|
||||
|
||||
"""Offline e2e smoke test for native Anima single-file checkpoints."""
|
||||
|
||||
import os
|
||||
|
||||
import pytest
|
||||
|
||||
from tests.helpers.mark import hardware_test
|
||||
from tests.helpers.runtime import OmniRunner, OmniRunnerHandler
|
||||
from vllm_omni.inputs.data import OmniDiffusionSamplingParams
|
||||
|
||||
CHECKPOINT_ENV = "ANIMA_CHECKPOINT_PATH"
|
||||
COMPONENTS_ENV = "ANIMA_COMPONENTS_PATH"
|
||||
CHECKPOINT_REPO = "circlestone-labs/Anima"
|
||||
CHECKPOINT_FILENAME = "split_files/diffusion_models/anima-base-v1.0.safetensors"
|
||||
COMPONENTS_REPO = "circlestone-labs/Anima-Base-v1.0-Diffusers"
|
||||
PROMPT = "A cinematic close-up of a glass teapot on a wooden table."
|
||||
|
||||
|
||||
def _resolve_anima_assets() -> tuple[str, str]:
|
||||
checkpoint = os.environ.get(CHECKPOINT_ENV)
|
||||
components = os.environ.get(COMPONENTS_ENV)
|
||||
if checkpoint and components:
|
||||
return checkpoint, components
|
||||
|
||||
from huggingface_hub import hf_hub_download, snapshot_download
|
||||
|
||||
if checkpoint is None:
|
||||
checkpoint = hf_hub_download(
|
||||
repo_id=CHECKPOINT_REPO,
|
||||
filename=CHECKPOINT_FILENAME,
|
||||
)
|
||||
if components is None:
|
||||
components = snapshot_download(repo_id=COMPONENTS_REPO)
|
||||
return checkpoint, components
|
||||
|
||||
|
||||
@pytest.mark.full_model
|
||||
@pytest.mark.diffusion
|
||||
@hardware_test(res={"cuda": "L4", "rocm": "MI325"}, num_cards=1)
|
||||
@pytest.mark.parametrize("guidance_scale", [1.0, 4.0])
|
||||
def test_anima_text_to_image(guidance_scale):
|
||||
checkpoint, components = _resolve_anima_assets()
|
||||
request_config = {
|
||||
"model": checkpoint,
|
||||
"prompt": PROMPT,
|
||||
"sampling_params": OmniDiffusionSamplingParams(
|
||||
height=256,
|
||||
width=256,
|
||||
num_inference_steps=1,
|
||||
guidance_scale=guidance_scale,
|
||||
seed=42,
|
||||
),
|
||||
}
|
||||
with OmniRunner(
|
||||
checkpoint,
|
||||
seed=42,
|
||||
model_class_name="AnimaPipeline",
|
||||
custom_pipeline_args={"components_path": components},
|
||||
) as runner:
|
||||
OmniRunnerHandler(runner).send_diffusion_request(request_config)
|
||||
@@ -0,0 +1,77 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
|
||||
|
||||
"""Online e2e smoke test for native Anima single-file checkpoints."""
|
||||
|
||||
import json
|
||||
import os
|
||||
|
||||
import pytest
|
||||
|
||||
from tests.helpers.mark import hardware_test
|
||||
from tests.helpers.runtime import OmniServer, OpenAIClientHandler, dummy_messages_from_mix_data
|
||||
|
||||
CHECKPOINT_ENV = "ANIMA_CHECKPOINT_PATH"
|
||||
COMPONENTS_ENV = "ANIMA_COMPONENTS_PATH"
|
||||
CHECKPOINT_REPO = "circlestone-labs/Anima"
|
||||
CHECKPOINT_FILENAME = "split_files/diffusion_models/anima-base-v1.0.safetensors"
|
||||
COMPONENTS_REPO = "circlestone-labs/Anima-Base-v1.0-Diffusers"
|
||||
PROMPT = "A cinematic close-up of a glass teapot on a wooden table."
|
||||
|
||||
|
||||
def _resolve_anima_assets() -> tuple[str, str]:
|
||||
checkpoint = os.environ.get(CHECKPOINT_ENV)
|
||||
components = os.environ.get(COMPONENTS_ENV)
|
||||
if checkpoint and components:
|
||||
return checkpoint, components
|
||||
|
||||
from huggingface_hub import hf_hub_download, snapshot_download
|
||||
|
||||
if checkpoint is None:
|
||||
checkpoint = hf_hub_download(
|
||||
repo_id=CHECKPOINT_REPO,
|
||||
filename=CHECKPOINT_FILENAME,
|
||||
)
|
||||
if components is None:
|
||||
components = snapshot_download(repo_id=COMPONENTS_REPO)
|
||||
return checkpoint, components
|
||||
|
||||
|
||||
@pytest.mark.full_model
|
||||
@pytest.mark.diffusion
|
||||
@hardware_test(res={"cuda": "L4", "rocm": "MI325"}, num_cards=1)
|
||||
@pytest.mark.parametrize("guidance_scale", [1.0, 4.0])
|
||||
def test_anima_text_to_image(guidance_scale):
|
||||
checkpoint, components = _resolve_anima_assets()
|
||||
server_args = [
|
||||
"--model-class-name",
|
||||
"AnimaPipeline",
|
||||
"--custom-pipeline-args",
|
||||
json.dumps({"components_path": components}),
|
||||
]
|
||||
with OmniServer(checkpoint, server_args) as omni_server:
|
||||
openai_client = OpenAIClientHandler(
|
||||
host=omni_server.host,
|
||||
port=omni_server.port,
|
||||
api_key="EMPTY",
|
||||
run_level="full_model",
|
||||
log_stats=omni_server.log_stats,
|
||||
)
|
||||
_send_text_to_image_request(omni_server, openai_client, guidance_scale)
|
||||
|
||||
|
||||
def _send_text_to_image_request(omni_server: OmniServer, openai_client: OpenAIClientHandler, guidance_scale: float):
|
||||
messages = dummy_messages_from_mix_data(content_text=PROMPT)
|
||||
request_config = {
|
||||
"model": omni_server.model,
|
||||
"messages": messages,
|
||||
"extra_body": {
|
||||
"height": 256,
|
||||
"width": 256,
|
||||
"num_inference_steps": 1,
|
||||
"guidance_scale": guidance_scale,
|
||||
"seed": 42,
|
||||
},
|
||||
}
|
||||
|
||||
openai_client.send_diffusion_request(request_config)
|
||||
@@ -152,6 +152,37 @@ def test_omni_serve_accepts_explicit_model(argv: list[str], mocker: MockerFixtur
|
||||
cmd.validate(args)
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"model_class,exists,native",
|
||||
[
|
||||
("AnimaPipeline", True, True),
|
||||
("AnimaModularPipeline", True, True),
|
||||
("AnimaPipeline", False, False),
|
||||
("FluxPipeline", True, False),
|
||||
(None, True, False),
|
||||
],
|
||||
)
|
||||
def test_serve_native_checkpoint_validation(model_class, exists, native, tmp_path, mocker):
|
||||
checkpoint = tmp_path / "anima.safetensors"
|
||||
if exists:
|
||||
checkpoint.touch()
|
||||
argv = ["serve", str(checkpoint), "--omni"]
|
||||
if model_class is not None:
|
||||
argv.extend(["--model-class-name", model_class])
|
||||
args = _parse_serve_args(argv)
|
||||
detect_model = mocker.patch("vllm_omni.diffusion.utils.hf_utils.is_diffusion_model", return_value=False)
|
||||
validate_llm = mocker.patch("vllm_omni.entrypoints.cli.serve.validate_parsed_serve_args")
|
||||
|
||||
OmniServeCommand().validate(args)
|
||||
|
||||
if native:
|
||||
detect_model.assert_not_called()
|
||||
validate_llm.assert_not_called()
|
||||
else:
|
||||
detect_model.assert_called_once_with(str(checkpoint))
|
||||
validate_llm.assert_called_once_with(args)
|
||||
|
||||
|
||||
def test_serve_parser_accepts_strategy_config() -> None:
|
||||
"""``--strategy-config`` must parse onto the ``strategy_config`` dest and be
|
||||
forwarded as an explicit kwarg so the engine can overlay the strategy."""
|
||||
@@ -215,14 +246,23 @@ def test_tracking_namespace_is_picklable_for_spawned_api_workers() -> None:
|
||||
assert restored._omni_stage_client_configs == args._omni_stage_client_configs
|
||||
|
||||
|
||||
def test_serve_validate_rejects_multiple_api_servers_for_diffusion(mocker: MockerFixture) -> None:
|
||||
@pytest.mark.parametrize("native_checkpoint", [False, True])
|
||||
def test_serve_validate_rejects_multiple_api_servers_for_diffusion(
|
||||
mocker: MockerFixture, tmp_path, native_checkpoint: bool
|
||||
) -> None:
|
||||
parser = TrackingArgumentParser()
|
||||
subparsers = parser.add_subparsers(dest="subcommand")
|
||||
cmd = OmniServeCommand()
|
||||
cmd.subparser_init(subparsers)
|
||||
args = parser.parse_args(["serve", "fake-diffusion-model", "--omni", "--api-server-count", "2"])
|
||||
argv = ["serve", "fake-diffusion-model", "--omni", "--api-server-count", "2"]
|
||||
if native_checkpoint:
|
||||
checkpoint = tmp_path / "anima.safetensors"
|
||||
checkpoint.touch()
|
||||
argv[1] = str(checkpoint)
|
||||
argv.extend(["--model-class-name", "AnimaPipeline"])
|
||||
args = parser.parse_args(argv)
|
||||
|
||||
mocker.patch("vllm_omni.diffusion.utils.hf_utils.is_diffusion_model", return_value=True)
|
||||
mocker.patch("vllm_omni.diffusion.utils.hf_utils.is_diffusion_model", return_value=not native_checkpoint)
|
||||
validate = mocker.patch("vllm_omni.entrypoints.cli.serve.validate_parsed_serve_args")
|
||||
|
||||
with pytest.raises(ValueError, match="not supported for diffusion"):
|
||||
|
||||
@@ -303,6 +303,70 @@ class TestFilterDataclassKwargs:
|
||||
|
||||
|
||||
class TestResolveOmniConfig:
|
||||
@pytest.mark.parametrize("model_class_name", ["AnimaPipeline", "AnimaModularPipeline"])
|
||||
def test_native_anima_checkpoint_uses_default_diffusion_stage_without_model_config(
|
||||
self, tmp_path, mocker: MockerFixture, model_class_name: str
|
||||
):
|
||||
checkpoint = tmp_path / "anima.safetensors"
|
||||
checkpoint.write_text("dummy")
|
||||
custom_args = {"components_path": "/tmp/anima-components"}
|
||||
mocker.patch(
|
||||
"vllm_omni.config.resolver.StageConfigFactory.create_from_model",
|
||||
side_effect=AssertionError("native Anima checkpoints should not require model config discovery"),
|
||||
)
|
||||
|
||||
resolved = resolve_omni_config(
|
||||
str(checkpoint),
|
||||
trust_remote_code=False,
|
||||
deploy_config_path=None,
|
||||
cli_overrides={"model_class_name": model_class_name, "custom_pipeline_args": custom_args},
|
||||
stage_overrides=None,
|
||||
strategy_config_path=None,
|
||||
)
|
||||
|
||||
assert resolved.config_path is None
|
||||
assert len(resolved.stage_configs) == 1
|
||||
stage_config = resolved.stage_configs[0]
|
||||
assert stage_config.model_stage == "diffusion"
|
||||
assert stage_config.diffusion_config.model_class_name == "AnimaPipeline"
|
||||
assert stage_config.diffusion_config.custom_pipeline_args == custom_args
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("model_class_name", "checkpoint_exists", "deploy_config_path"),
|
||||
[
|
||||
("AnimaPipeline", True, "deploy.yaml"),
|
||||
("AnimaPipeline", False, None),
|
||||
("FluxPipeline", True, None),
|
||||
],
|
||||
)
|
||||
def test_native_single_file_fallback_preserves_config_discovery(
|
||||
self, tmp_path, mocker: MockerFixture, model_class_name, checkpoint_exists, deploy_config_path
|
||||
):
|
||||
checkpoint = tmp_path / "model.safetensors"
|
||||
if checkpoint_exists:
|
||||
checkpoint.write_text("dummy")
|
||||
create_from_model = mocker.patch(
|
||||
"vllm_omni.config.resolver.StageConfigFactory.create_from_model", return_value=None
|
||||
)
|
||||
|
||||
resolved = resolve_omni_config(
|
||||
str(checkpoint),
|
||||
trust_remote_code=False,
|
||||
deploy_config_path=deploy_config_path,
|
||||
cli_overrides={"model_class_name": model_class_name},
|
||||
stage_overrides=None,
|
||||
strategy_config_path=None,
|
||||
)
|
||||
|
||||
create_from_model.assert_called_once_with(
|
||||
str(checkpoint),
|
||||
trust_remote_code=False,
|
||||
cli_overrides={"model_class_name": model_class_name, "trust_remote_code": False},
|
||||
deploy_config_path=deploy_config_path,
|
||||
strategy_specs=None,
|
||||
)
|
||||
assert resolved.config_path == deploy_config_path
|
||||
|
||||
def test_bare_deploy_name_returns_packaged_resolved_path(self, tmp_path, mocker: MockerFixture):
|
||||
deploy_name = "qwen3_omni_moe.yaml"
|
||||
deploy_path = tmp_path / deploy_name
|
||||
|
||||
@@ -0,0 +1,28 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
|
||||
|
||||
import pytest
|
||||
|
||||
from tools.pre_commit import check_test_marks
|
||||
|
||||
pytestmark = [pytest.mark.cpu, pytest.mark.core_model]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("kind", ["offline", "online"])
|
||||
def test_common_diffusion_marks_are_checked_in_helper(kind, monkeypatch):
|
||||
path = f"tests/model_tests/diffusion/test_common_{kind}.py"
|
||||
assert check_test_marks.get_files_missing_markers([path]) == {}
|
||||
|
||||
read_file = check_test_marks.read_test_file
|
||||
monkeypatch.setattr(
|
||||
check_test_marks,
|
||||
"read_test_file",
|
||||
lambda filename: "" if filename.endswith("case_filtering.py") else read_file(filename),
|
||||
)
|
||||
assert check_test_marks.get_files_missing_markers([path]) == {path: ["Level", "Hardware"]}
|
||||
|
||||
|
||||
def test_unrelated_tests_cannot_inherit_diffusion_marks(monkeypatch):
|
||||
path = "tests/test_missing_marks.py"
|
||||
monkeypatch.setattr(check_test_marks, "read_test_file", lambda filename: "get_parametrized_options(settings)")
|
||||
assert check_test_marks.get_files_missing_markers([path]) == {path: ["Level", "Hardware"]}
|
||||
@@ -1,3 +1,6 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
|
||||
|
||||
import json
|
||||
from shutil import rmtree
|
||||
|
||||
@@ -12,7 +15,7 @@ def tiny_model_paths(request, run_level, tmp_path_factory):
|
||||
"""Build or download the tiny models for the selected tests.
|
||||
|
||||
At core_model level, builds tiny models via the builder function.
|
||||
At advanced_model / full_model level, uses the real HF model path.
|
||||
At advanced_model / full_model level, uses the real HF model path or asset resolver.
|
||||
|
||||
NOTE: this is session scoped to avoid churn in tiny model creation,
|
||||
but will ensure all the tiny models you need are created for the selected tests
|
||||
@@ -45,7 +48,11 @@ def tiny_model_paths(request, run_level, tmp_path_factory):
|
||||
built_paths.append(path)
|
||||
else:
|
||||
print(f"Run level is {run_level}; {model_name} will use the full model")
|
||||
path = settings.model
|
||||
if callable(settings.model):
|
||||
path = settings.model()
|
||||
built_paths.append(path)
|
||||
else:
|
||||
path = settings.model
|
||||
model_paths[model_name] = path
|
||||
data_file.write_text(json.dumps(model_paths))
|
||||
|
||||
|
||||
@@ -0,0 +1,116 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
|
||||
|
||||
"""Local random-weight Anima assets and real-checkpoint assets for common tests."""
|
||||
|
||||
import json
|
||||
import tempfile
|
||||
from pathlib import Path
|
||||
|
||||
import torch
|
||||
from diffusers import AutoencoderKLQwenImage, FlowMatchEulerDiscreteScheduler
|
||||
from huggingface_hub import hf_hub_download, snapshot_download
|
||||
from safetensors.torch import save_file
|
||||
from tokenizers import Tokenizer
|
||||
from tokenizers.models import Unigram, WordLevel
|
||||
from tokenizers.pre_tokenizers import Whitespace
|
||||
from tokenizers.processors import TemplateProcessing
|
||||
from transformers import PreTrainedTokenizerFast, Qwen3Config, Qwen3Model, T5TokenizerFast
|
||||
|
||||
from vllm_omni.diffusion.models.anima.anima_text_conditioner import (
|
||||
ANIMA_TEXT_CONDITIONER_CONFIG,
|
||||
AnimaTextConditioner,
|
||||
)
|
||||
from vllm_omni.diffusion.models.anima.anima_transformer import ANIMA_TRANSFORMER_CONFIG, AnimaTransformer3DModel
|
||||
|
||||
CHECKPOINT_FILENAME = "anima.safetensors"
|
||||
|
||||
|
||||
def tiny_anima_builder() -> str:
|
||||
"""Build all components locally, without downloading any model weights or tokenizers."""
|
||||
model_dir = Path(tempfile.mkdtemp(prefix="tiny-anima-"))
|
||||
transformer_config = {
|
||||
**ANIMA_TRANSFORMER_CONFIG,
|
||||
"num_attention_heads": 2,
|
||||
"attention_head_dim": 32,
|
||||
"num_layers": 1,
|
||||
"mlp_ratio": 1.0,
|
||||
"text_embed_dim": 32,
|
||||
"adaln_lora_dim": 8,
|
||||
"max_size": (1, 64, 64),
|
||||
}
|
||||
conditioner_config = {
|
||||
**ANIMA_TEXT_CONDITIONER_CONFIG,
|
||||
"source_dim": 32,
|
||||
"target_dim": 32,
|
||||
"model_dim": 32,
|
||||
"num_layers": 1,
|
||||
"num_attention_heads": 2,
|
||||
"mlp_ratio": 1.0,
|
||||
"target_vocab_size": 8,
|
||||
"min_sequence_length": 8,
|
||||
}
|
||||
transformer = AnimaTransformer3DModel(**transformer_config).to(torch.bfloat16)
|
||||
conditioner = AnimaTextConditioner(**conditioner_config).to(torch.bfloat16)
|
||||
save_file(
|
||||
{
|
||||
**{f"transformer.{name}": tensor for name, tensor in transformer.state_dict().items()},
|
||||
**{f"text_conditioner.{name}": tensor for name, tensor in conditioner.state_dict().items()},
|
||||
},
|
||||
str(model_dir / CHECKPOINT_FILENAME),
|
||||
)
|
||||
(model_dir / "anima.json").write_text(
|
||||
json.dumps({"transformer": transformer_config, "text_conditioner": conditioner_config})
|
||||
)
|
||||
Qwen3Model(
|
||||
Qwen3Config(
|
||||
vocab_size=8,
|
||||
hidden_size=32,
|
||||
intermediate_size=64,
|
||||
num_hidden_layers=1,
|
||||
num_attention_heads=2,
|
||||
num_key_value_heads=2,
|
||||
head_dim=16,
|
||||
)
|
||||
).to(torch.bfloat16).save_pretrained(model_dir / "text_encoder")
|
||||
AutoencoderKLQwenImage(
|
||||
base_dim=4,
|
||||
z_dim=16,
|
||||
dim_mult=[1, 1, 1, 1],
|
||||
num_res_blocks=1,
|
||||
latents_mean=[0.0] * 16,
|
||||
latents_std=[1.0] * 16,
|
||||
).to(torch.bfloat16).save_pretrained(model_dir / "vae")
|
||||
tokenizer = Tokenizer(WordLevel({"<pad>": 0, "</s>": 1, "<unk>": 2, "Dummy": 3, "prompt": 4}, unk_token="<unk>"))
|
||||
tokenizer.pre_tokenizer = Whitespace()
|
||||
tokenizer.post_processor = TemplateProcessing(single="$A </s>", special_tokens=[("</s>", 1)])
|
||||
PreTrainedTokenizerFast(
|
||||
tokenizer_object=tokenizer, pad_token="<pad>", eos_token="</s>", unk_token="<unk>"
|
||||
).save_pretrained(model_dir / "tokenizer")
|
||||
t5_tokenizer = Tokenizer(
|
||||
Unigram(
|
||||
[("<pad>", 0.0), ("</s>", 0.0), ("<unk>", 0.0), ("▁", -1.0), ("Dummy", -1.0), ("prompt", -1.0)], unk_id=2
|
||||
)
|
||||
)
|
||||
T5TokenizerFast(tokenizer_object=t5_tokenizer, extra_ids=0).save_pretrained(model_dir / "t5_tokenizer")
|
||||
FlowMatchEulerDiscreteScheduler(shift=3.0).save_pretrained(model_dir / "scheduler")
|
||||
return str(model_dir)
|
||||
|
||||
|
||||
def real_anima_model() -> str:
|
||||
"""Keep cached real assets intact; return a disposable directory of links."""
|
||||
components = Path(
|
||||
snapshot_download(
|
||||
"circlestone-labs/Anima-Base-v1.0-Diffusers",
|
||||
allow_patterns=["text_encoder/*", "vae/*", "tokenizer/*", "t5_tokenizer/*", "scheduler/*"],
|
||||
)
|
||||
)
|
||||
checkpoint = hf_hub_download(
|
||||
"circlestone-labs/Anima", filename="split_files/diffusion_models/anima-base-v1.0.safetensors"
|
||||
)
|
||||
model_dir = Path(tempfile.mkdtemp(prefix="real-anima-"))
|
||||
(model_dir / CHECKPOINT_FILENAME).symlink_to(checkpoint)
|
||||
for name in ("text_encoder", "vae", "tokenizer", "t5_tokenizer", "scheduler"):
|
||||
if (components / name).is_dir():
|
||||
(model_dir / name).symlink_to(components / name, target_is_directory=True)
|
||||
return str(model_dir)
|
||||
@@ -1,10 +1,13 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
|
||||
|
||||
"""
|
||||
Common definitions for controlling what tests run where.
|
||||
"""
|
||||
|
||||
from collections.abc import Callable
|
||||
from enum import Enum
|
||||
from typing import NamedTuple, TypeAlias
|
||||
from typing import Any, NamedTuple, TypeAlias
|
||||
|
||||
from pytest import MarkDecorator
|
||||
|
||||
@@ -45,7 +48,9 @@ class DiffusionModelTestOpts(NamedTuple):
|
||||
# HF model name for real-weight tests (advanced_model / full_model level).
|
||||
# For now, whether we use the real weights vs tiny weights in the common tests
|
||||
# depends on the run level.
|
||||
model: str
|
||||
# A callable may assemble native assets in a temporary directory; the fixture
|
||||
# removes that directory after the tests, so it must not return a cache root.
|
||||
model: str | Callable[[], str]
|
||||
|
||||
# Creates a tiny model for the given architecture. We should always use tiny
|
||||
# model weights for tests that do not require us to check the model quality.
|
||||
@@ -81,9 +86,12 @@ class DiffusionModelTestOpts(NamedTuple):
|
||||
# set False for pipelines that mandate an image and fail closed without one (SANA-Video I2V).
|
||||
check_i2v_t2v_divergence: bool = True
|
||||
|
||||
# Native single-file models: builders/resolvers return the containing directory.
|
||||
checkpoint_filename: str | None = None
|
||||
|
||||
|
||||
### Mappings & utils for building offline Omni() instances given a list of enabled accelerations
|
||||
ACC_OMNI_KWARGS = {
|
||||
ACC_OMNI_KWARGS: dict[DiffusionAccs, dict[str, Any]] = {
|
||||
DiffusionAccs.VAE_PATCH_PARALLEL: {"vae_use_tiling": True},
|
||||
DiffusionAccs.CPU_OFFLOAD: {"enable_cpu_offload": True},
|
||||
DiffusionAccs.LAYERWISE_OFFLOAD: {"enable_layerwise_offload": True},
|
||||
|
||||
@@ -1,4 +1,8 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
|
||||
|
||||
from tests.model_tests.diffusion import diff_model_builders
|
||||
from tests.model_tests.diffusion.anima_builder import CHECKPOINT_FILENAME, real_anima_model, tiny_anima_builder
|
||||
from tests.model_tests.diffusion.config_types import (
|
||||
DiffusionAccs,
|
||||
DiffusionModelTestOpts,
|
||||
@@ -29,6 +33,12 @@ from tests.model_tests.diffusion.config_types import (
|
||||
# $ pytest test_common_offline.py -k test_pipeline_on_supported_tasks[Flux2KleinPipeline
|
||||
# ^ Runs all test groups for Flux2KleinPipeline only
|
||||
DIFFUSION_TEST_SETTINGS = {
|
||||
"AnimaPipeline": DiffusionModelTestOpts(
|
||||
model=real_anima_model,
|
||||
builder=tiny_anima_builder,
|
||||
supported_tasks=[DiffusionTasks.TEXT_TO_IMAGE],
|
||||
checkpoint_filename=CHECKPOINT_FILENAME,
|
||||
),
|
||||
"Flux2KleinPipeline": DiffusionModelTestOpts(
|
||||
model="black-forest-labs/FLUX.2-klein-4B",
|
||||
builder=diff_model_builders.tiny_flux2_klein_builder,
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
|
||||
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
from tests.model_tests.diffusion.case_filtering import get_parametrized_options
|
||||
@@ -47,10 +49,17 @@ def test_pipeline_on_supported_tasks(
|
||||
# since starting the server can take 10+ seconds, even for tiny models.
|
||||
#
|
||||
# NOTE: Be sure to install pytest-subtests if you're running on pytest < 9
|
||||
settings = DIFFUSION_TEST_SETTINGS[model_name]
|
||||
model_path = tiny_model_paths[model_name]
|
||||
model_kwargs = {}
|
||||
if settings.checkpoint_filename is not None:
|
||||
model_path = str(Path(model_path) / settings.checkpoint_filename)
|
||||
model_kwargs["model_class_name"] = model_name
|
||||
omni = build_omni_from_diff_accelerations(
|
||||
accelerations=accelerations,
|
||||
model=tiny_model_paths[model_name],
|
||||
model=model_path,
|
||||
enforce_eager=True,
|
||||
**model_kwargs,
|
||||
)
|
||||
try:
|
||||
for task_type in supported_tasks:
|
||||
|
||||
@@ -7,6 +7,8 @@ online serving stack (CLI arg parsing, subprocess, API routing, response
|
||||
encoding) using tiny models.
|
||||
"""
|
||||
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
from xdist import is_xdist_worker
|
||||
|
||||
@@ -68,6 +70,10 @@ def test_online_on_supported_tasks(
|
||||
model_path = tiny_model_paths[model_name]
|
||||
server_args = build_server_args_from_diff_accelerations(accelerations)
|
||||
server_args.append("--enforce-eager")
|
||||
settings = DIFFUSION_TEST_SETTINGS[model_name]
|
||||
if settings.checkpoint_filename is not None:
|
||||
model_path = str(Path(model_path) / settings.checkpoint_filename)
|
||||
server_args.extend(["--model-class-name", model_name])
|
||||
|
||||
with OmniServer(model_path, server_args) as server:
|
||||
# TODO: We may want to revisit run_level validation here,
|
||||
|
||||
@@ -0,0 +1,66 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
|
||||
|
||||
from contextlib import nullcontext
|
||||
from pathlib import Path
|
||||
from shutil import rmtree
|
||||
from types import SimpleNamespace
|
||||
from unittest.mock import MagicMock
|
||||
|
||||
import pytest
|
||||
|
||||
from tests.model_tests.diffusion import anima_builder, test_common_offline, test_common_online
|
||||
from tests.model_tests.diffusion.config_types import DiffusionTasks
|
||||
|
||||
pytestmark = [pytest.mark.cpu, pytest.mark.core_model, pytest.mark.diffusion]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("model_name", ["AnimaPipeline", "FluxPipeline"])
|
||||
def test_common_runners_resolve_native_checkpoint(model_name, tmp_path, monkeypatch):
|
||||
"""Both entry points receive the file and class; directory models keep their existing arguments."""
|
||||
paths = {model_name: str(tmp_path)}
|
||||
subtests = SimpleNamespace(test=lambda **kwargs: nullcontext())
|
||||
build_omni = MagicMock()
|
||||
monkeypatch.setattr(test_common_offline, "build_omni_from_diff_accelerations", build_omni)
|
||||
monkeypatch.setattr(test_common_offline, "run_and_validate_text_to_image_request", MagicMock())
|
||||
test_common_offline.test_pipeline_on_supported_tasks(
|
||||
model_name, None, [DiffusionTasks.TEXT_TO_IMAGE], False, False, False, paths, subtests
|
||||
)
|
||||
server = MagicMock()
|
||||
monkeypatch.setattr(test_common_online, "OmniServer", server)
|
||||
monkeypatch.setattr(test_common_online, "OnlineOmniClient", MagicMock())
|
||||
monkeypatch.setattr(test_common_online, "run_and_validate_online_text_to_image_request", MagicMock())
|
||||
test_common_online.test_online_on_supported_tasks(
|
||||
model_name, None, [DiffusionTasks.TEXT_TO_IMAGE], False, False, paths, "core_model", subtests
|
||||
)
|
||||
if model_name == "AnimaPipeline":
|
||||
checkpoint = str(tmp_path / anima_builder.CHECKPOINT_FILENAME)
|
||||
build_omni.assert_called_once_with(
|
||||
accelerations=None, model=checkpoint, enforce_eager=True, model_class_name=model_name
|
||||
)
|
||||
server.assert_called_once_with(checkpoint, ["--enforce-eager", "--model-class-name", model_name])
|
||||
else:
|
||||
build_omni.assert_called_once_with(accelerations=None, model=str(tmp_path), enforce_eager=True)
|
||||
server.assert_called_once_with(str(tmp_path), ["--enforce-eager"])
|
||||
|
||||
|
||||
def test_real_anima_assets_leave_cache_intact(tmp_path, monkeypatch):
|
||||
"""The fixture may delete the assembled directory without deleting cached model assets."""
|
||||
components = tmp_path / "components"
|
||||
for name in ("text_encoder", "vae", "tokenizer", "t5_tokenizer"):
|
||||
(components / name).mkdir(parents=True)
|
||||
(components / name / "asset").write_text(name)
|
||||
checkpoint = tmp_path / "real.safetensors"
|
||||
checkpoint.write_bytes(b"checkpoint")
|
||||
monkeypatch.setattr(anima_builder, "snapshot_download", lambda *args, **kwargs: str(components))
|
||||
monkeypatch.setattr(anima_builder, "hf_hub_download", lambda *args, **kwargs: str(checkpoint))
|
||||
directory = Path(anima_builder.real_anima_model())
|
||||
try:
|
||||
assert (directory / anima_builder.CHECKPOINT_FILENAME).read_bytes() == b"checkpoint"
|
||||
assert (directory / "vae" / "asset").read_text() == "vae"
|
||||
# Missing scheduler is supported by Anima's default scheduler fallback.
|
||||
assert not (directory / "scheduler").exists()
|
||||
finally:
|
||||
rmtree(directory)
|
||||
assert checkpoint.read_bytes() == b"checkpoint"
|
||||
assert (components / "vae" / "asset").read_text() == "vae"
|
||||
@@ -1,8 +1,12 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
|
||||
|
||||
"""
|
||||
Utilities for resolving real models to their tiny model equivalents.
|
||||
"""
|
||||
|
||||
import logging
|
||||
from pathlib import Path
|
||||
|
||||
from tests.model_tests.diffusion.model_settings import DIFFUSION_TEST_SETTINGS
|
||||
from vllm_omni.diffusion.data import resolve_model_class_name
|
||||
@@ -30,4 +34,7 @@ def resolve_tiny_model_path(model: str) -> str:
|
||||
)
|
||||
return model
|
||||
|
||||
return test_opts.builder()
|
||||
model_path = test_opts.builder()
|
||||
if test_opts.checkpoint_filename is not None:
|
||||
return str(Path(model_path) / test_opts.checkpoint_filename)
|
||||
return model_path
|
||||
Reference in new issue
Block a user