[Feature] Transfer AR-to-diffusion payloads over NIXL (#6264)
Signed-off-by: yuanwu <yuan.wu@intel.com> Co-authored-by: Hongsheng Liu <liuhongsheng4@huawei.com>
This commit is contained in:
1 parent
8953d082c0
commit
cb5f508212
60 files changed
+4397
-641
No files matched your search
@@ -1588,19 +1588,32 @@ stages:
|
||||
assert "text_encoder_tp_size" not in stages[1].runtime_overrides
|
||||
assert stages[1].yaml_engine_args["parallel_config"]["tensor_parallel_size"] == 1
|
||||
|
||||
def test_minimax_h3_disaggregated_defaults_match_validated_topology(self):
|
||||
@pytest.mark.parametrize(
|
||||
"deploy_name",
|
||||
["minimax_h3_disaggregated.yaml", "minimax_h3_disaggregated_turbo.yaml"],
|
||||
)
|
||||
def test_minimax_h3_disaggregated_defaults(self, deploy_name):
|
||||
pipeline = OMNI_PIPELINES["minimax_h3_disaggregated"]
|
||||
deploy = load_deploy_config(Path(get_deploy_config_path("minimax_h3_disaggregated.yaml")))
|
||||
deploy = load_deploy_config(Path(get_deploy_config_path(deploy_name)))
|
||||
stages = merge_pipeline_deploy(pipeline, deploy)
|
||||
|
||||
assert pipeline.model_arch == "MiniMaxH3Encoder"
|
||||
assert stages[0].model_stage == "encoder"
|
||||
assert stages[0].yaml_engine_args["model_arch"] == "MiniMaxH3Encoder"
|
||||
processor = "vllm_omni.model_executor.stage_input_processors.minimax_h3"
|
||||
assert stages[0].yaml_extras["prompt_transform_func"] == f"{processor}.prepare_encoder_prompt"
|
||||
assert (
|
||||
stages[0].yaml_engine_args["custom_process_next_stage_input_func"]
|
||||
== f"{processor}.encoder2diffusion_full_payload"
|
||||
)
|
||||
assert stages[1].custom_process_input_func == f"{processor}.encoder2diffusion"
|
||||
assert tuple(stages[1].yaml_engine_args["stage_input_payload_keys"]) == ("encoder_output",)
|
||||
assert stages[1].yaml_engine_args["omni_kv_config"]["need_recv_cache"] is False
|
||||
assert stages[1].yaml_engine_args["model_arch"] == "MiniMaxH3Pipeline"
|
||||
assert stages[0].yaml_runtime["num_replicas"] == 1
|
||||
assert stages[1].yaml_runtime["num_replicas"] == 1
|
||||
assert stages[1].yaml_engine_args["model_loaded"] == {
|
||||
"text_encoder": False,
|
||||
"vae_encoder": False,
|
||||
}
|
||||
assert stages[1].yaml_engine_args["model_loaded"] == {"text_encoder": False, "vae_encoder": False}
|
||||
assert stages[0].yaml_engine_args["tensor_parallel_size"] == 2
|
||||
assert stages[0].yaml_engine_args["max_num_seqs"] == 1
|
||||
assert stages[0].yaml_engine_args["hf_overrides"]["minimax_h3_encoder_components"] == {
|
||||
"text_encoder": {"parallel_mode": "tp"},
|
||||
@@ -1614,7 +1627,12 @@ stages:
|
||||
assert parallel["ulysses_degree"] == 4
|
||||
assert parallel["vae_patch_parallel_size"] == 4
|
||||
assert stages[1].yaml_engine_args["inline_diffusion"] is True
|
||||
assert stages[1].yaml_extras["default_sampling_params"]["num_inference_steps"] == 50
|
||||
sampling = stages[1].yaml_extras["default_sampling_params"]
|
||||
if "turbo" in deploy_name:
|
||||
assert sampling["num_inference_steps"] == 5
|
||||
assert sampling["extra_args"] == {"flow_shift": 6.0, "audio_flow_shift": 3.0}
|
||||
else:
|
||||
assert sampling["num_inference_steps"] == 50
|
||||
|
||||
turbo = load_deploy_config(Path(get_deploy_config_path("minimax_h3_disaggregated_turbo.yaml")))
|
||||
turbo_stages = merge_pipeline_deploy(pipeline, turbo)
|
||||
@@ -1625,6 +1643,73 @@ stages:
|
||||
assert turbo_sampling["num_inference_steps"] == 5
|
||||
assert turbo_sampling["extra_args"] == {"flow_shift": 6.0, "audio_flow_shift": 3.0}
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"deploy_name",
|
||||
["minimax_h3_disaggregated.yaml", "minimax_h3_disaggregated_turbo.yaml"],
|
||||
)
|
||||
@pytest.mark.parametrize("shared_memory", [False, True], ids=["nixl", "shared_memory"])
|
||||
def test_minimax_h3_deploy_connector_wiring_and_roles(self, deploy_name, shared_memory):
|
||||
from vllm_omni.config.stage_config import resolve_deploy_yaml
|
||||
from vllm_omni.distributed.omni_connectors.utils.initialization import load_omni_transfer_config
|
||||
from vllm_omni.engine.stage_init_utils import get_stage_connector_spec
|
||||
|
||||
base_config = resolve_deploy_yaml(get_deploy_config_path(deploy_name))
|
||||
if not shared_memory:
|
||||
deploy_name = deploy_name.replace(".yaml", "_nixl.yaml")
|
||||
deploy_path = get_deploy_config_path(deploy_name)
|
||||
config = resolve_deploy_yaml(deploy_path)
|
||||
assert config["async_chunk"] is False
|
||||
connector_name = "shared_memory_connector" if shared_memory else "nixl_connector"
|
||||
assert connector_name in config["connectors"]
|
||||
assert config["stages"][0]["output_connectors"] == {"to_stage_1": connector_name}
|
||||
assert config["stages"][1]["input_connectors"] == {"from_stage_0": connector_name}
|
||||
load_deploy_config(deploy_path)
|
||||
for base_stage, stage in zip(base_config["stages"], config["stages"], strict=True):
|
||||
edge_keys = {"input_connectors", "output_connectors"}
|
||||
assert {key: value for key, value in stage.items() if key not in edge_keys} == {
|
||||
key: value for key, value in base_stage.items() if key not in edge_keys
|
||||
}
|
||||
transfer = load_omni_transfer_config(config_dict=config)
|
||||
assert transfer is not None
|
||||
assert set(transfer.connectors) == {("0", "1")}
|
||||
edge = transfer.connectors[("0", "1")]
|
||||
expected_name = "SharedMemoryConnector" if shared_memory else "NixlConnector"
|
||||
assert edge.name == expected_name
|
||||
assert "role" not in edge.extra
|
||||
for stage_id, role in ((0, "sender"), (1, "receiver")):
|
||||
spec = get_stage_connector_spec(transfer, stage_id, async_chunk=False)
|
||||
assert spec["name"] == expected_name
|
||||
assert spec["extra"]["role"] == role
|
||||
if shared_memory:
|
||||
assert "from_stage" not in spec["extra"]
|
||||
assert "to_stage" not in spec["extra"]
|
||||
else:
|
||||
assert spec["extra"]["from_stage"] == 0
|
||||
assert spec["extra"]["to_stage"] == 1
|
||||
assert spec["extra"]["host"] == "auto"
|
||||
assert spec["extra"]["zmq_port"] == 50071
|
||||
assert spec["extra"]["backends"] == ["UCX"]
|
||||
assert "role" not in edge.extra
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"deploy_name",
|
||||
["minimax_h3_disaggregated.yaml", "minimax_h3_disaggregated_turbo.yaml"],
|
||||
)
|
||||
def test_minimax_h3_builtin_stage_one_tp4_ulysses1_override(self, deploy_name):
|
||||
stages, _ = StageConfigFactory._create_legacy_from_registry(
|
||||
OMNI_PIPELINES["minimax_h3_disaggregated"],
|
||||
{"stage_1_tensor_parallel_size": 4, "stage_1_ulysses_degree": 1},
|
||||
deploy_config_path=get_deploy_config_path(deploy_name),
|
||||
)
|
||||
encoder_args = stages[0].to_omegaconf().engine_args
|
||||
diffusion_args = stages[1].to_omegaconf().engine_args
|
||||
assert encoder_args.tensor_parallel_size == 2
|
||||
assert "ulysses_degree" not in stages[0].runtime_overrides
|
||||
assert diffusion_args.parallel_config.tensor_parallel_size == 4
|
||||
assert diffusion_args.parallel_config.ulysses_degree == 1
|
||||
assert diffusion_args.parallel_config.vae_patch_parallel_size == 4
|
||||
assert tuple(diffusion_args.stage_input_payload_keys) == ("encoder_output",)
|
||||
|
||||
def test_minimax_h3_text_encoder_tp_alias_targets_stage_zero(self):
|
||||
pipeline = OMNI_PIPELINES["minimax_h3_disaggregated"]
|
||||
|
||||
|
||||
@@ -5,7 +5,7 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import warnings
|
||||
from dataclasses import fields
|
||||
from dataclasses import fields, replace
|
||||
from inspect import Parameter, signature
|
||||
from multiprocessing.reduction import ForkingPickler
|
||||
from pathlib import Path
|
||||
@@ -246,6 +246,12 @@ def test_vllm_omni_config_from_pipeline_config_matches_merge_pipeline_deploy(mod
|
||||
assert omni_stage.diffusion_config is not None
|
||||
assert omni_stage.diffusion_config.stage_id == legacy_stage.stage_id
|
||||
assert omni_stage.diffusion_config.model_arch == engine_args.get("model_arch")
|
||||
assert omni_stage.diffusion_config.stage_input_payload_keys == engine_args.get(
|
||||
"stage_input_payload_keys", ()
|
||||
)
|
||||
assert omni_stage.diffusion_config.stage_output_payload_keys == engine_args.get(
|
||||
"stage_output_payload_keys", ()
|
||||
)
|
||||
elif omni_stage.stage_pipeline_config.execution_type == StageExecutionType.LLM_AR:
|
||||
assert isinstance(omni_stage, VllmOmniARStageConfig)
|
||||
assert not hasattr(omni_stage, "diffusion_config")
|
||||
@@ -1725,6 +1731,58 @@ def test_from_pipeline_config_rejects_reserved_diffusion_kv_mode(tmp_path):
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("source", ["default", "topology", "deploy", "stage-cli"])
|
||||
@pytest.mark.parametrize("key_container", [list, tuple])
|
||||
def test_diffusion_stage_payload_keys_roundtrip(source, key_container):
|
||||
from vllm_omni.diffusion.data import OmniDiffusionConfig
|
||||
from vllm_omni.engine.stage_init_utils import build_engine_args_dict_from_omni_stage_config
|
||||
|
||||
topology_keys = {
|
||||
"stage_input_payload_keys": ("conditioning", "metadata"),
|
||||
"stage_output_payload_keys": ("latents",),
|
||||
}
|
||||
override_keys = {
|
||||
"stage_input_payload_keys": (),
|
||||
"stage_output_payload_keys": ("audio", "video"),
|
||||
}
|
||||
pipeline = _resolve_pipeline_or_skip("dreamzero")
|
||||
topology = pipeline.get_stage(0)
|
||||
if source != "default":
|
||||
topology = replace(topology, **topology_keys)
|
||||
pipeline = replace(pipeline, stages=(topology,))
|
||||
deploy = _load_default_deploy(pipeline)
|
||||
cli_overrides = {}
|
||||
if source == "deploy":
|
||||
deploy = replace(deploy, stages=[StageDeployConfig(stage_id=0, engine_extras=override_keys)])
|
||||
elif source == "stage-cli":
|
||||
cli_overrides = {f"stage_0_{name}": value for name, value in override_keys.items()}
|
||||
|
||||
stage = VllmOmniConfig.from_pipeline_config(
|
||||
pipeline, user_deploy_config=deploy, cli_overrides=cli_overrides
|
||||
).stage_by_id(0)
|
||||
expected = topology_keys if source == "topology" else override_keys
|
||||
if source == "default":
|
||||
expected = dict.fromkeys(topology_keys, ())
|
||||
legacy_stage = merge_pipeline_deploy(pipeline, deploy)[0]
|
||||
legacy_args = {**legacy_stage.yaml_engine_args, **(override_keys if source == "stage-cli" else {})}
|
||||
restored_stage = ForkingPickler.loads(ForkingPickler.dumps(stage))
|
||||
engine_args = build_engine_args_dict_from_omni_stage_config(restored_stage, model="test-model")
|
||||
diffusion_kwargs = omni_config_module.extract_diffusion_stage_config_kwargs(
|
||||
engine_args, stage_id=restored_stage.stage_id, include_engine_adapter_metadata=True
|
||||
)
|
||||
for name in topology_keys:
|
||||
diffusion_kwargs[name] = key_container(diffusion_kwargs[name])
|
||||
od_config = OmniDiffusionConfig.from_kwargs(**diffusion_kwargs)
|
||||
|
||||
for name, keys in expected.items():
|
||||
assert legacy_args.get(name, ()) == keys
|
||||
assert getattr(stage.diffusion_config, name) == keys
|
||||
assert engine_args[name] == keys
|
||||
assert getattr(od_config, name) == keys
|
||||
for name in topology_keys:
|
||||
assert getattr(topology, name) == (() if source == "default" else topology_keys[name])
|
||||
|
||||
|
||||
def test_diffusion_config_field_classification_covers_current_fields():
|
||||
from vllm_omni.diffusion.data import OmniDiffusionConfig
|
||||
|
||||
@@ -1745,6 +1803,8 @@ def test_diffusion_config_field_classification_covers_current_fields():
|
||||
"diffusion_kv_cache_dtype",
|
||||
"diffusion_kv_mode",
|
||||
"diffusion_kv_max_rows_per_request",
|
||||
"stage_input_payload_keys",
|
||||
"stage_output_payload_keys",
|
||||
} <= omni_config_module._DIFFUSION_ONLY_CONFIG_FIELDS
|
||||
assert {
|
||||
"revision",
|
||||
|
||||
@@ -146,3 +146,34 @@ def test_set_seq_parallel_pg_validates_sp_group_ranks(monkeypatch):
|
||||
world_size=4,
|
||||
sp_group_ranks=[[0, 2]],
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("rank", [1, 3])
|
||||
def test_tensor_dict_broadcast_preserves_subgroup_source(rank, monkeypatch):
|
||||
from vllm_omni.diffusion.distributed.group_coordinator import GroupCoordinator, TensorMetadata
|
||||
|
||||
coordinator = object.__new__(GroupCoordinator)
|
||||
coordinator.rank = rank
|
||||
coordinator.ranks = [1, 3]
|
||||
coordinator.rank_in_group = [1, 3].index(rank)
|
||||
coordinator.world_size = 2
|
||||
coordinator.device_group = object()
|
||||
coordinator.cpu_group = object()
|
||||
metadata = [("payload", TensorMetadata("cpu", torch.float32, (2,)))]
|
||||
monkeypatch.setattr(torch.distributed, "is_initialized", lambda: True)
|
||||
|
||||
def broadcast_object(value, src):
|
||||
assert src == 0
|
||||
return metadata
|
||||
|
||||
def broadcast(tensor, src, group, async_op):
|
||||
assert src == 1
|
||||
assert group is coordinator.cpu_group
|
||||
assert async_op
|
||||
tensor.fill_(7)
|
||||
return SimpleNamespace(wait=lambda: None)
|
||||
|
||||
monkeypatch.setattr(coordinator, "broadcast_object", broadcast_object)
|
||||
monkeypatch.setattr(torch.distributed, "broadcast", broadcast)
|
||||
result = coordinator.broadcast_tensor_dict({"payload": torch.full((2,), 7.0)} if rank == 1 else None)
|
||||
assert torch.equal(result["payload"], torch.full((2,), 7.0))
|
||||
@@ -89,6 +89,23 @@ def test_launch_failure_disables_runtime_key(monkeypatch):
|
||||
assert len(fused_rope._FAILED_KEYS) == 1
|
||||
|
||||
|
||||
def test_non_cuda_platform_does_not_launch_fused_kernel(monkeypatch):
|
||||
from vllm_omni.diffusion.models.ernie_image import fused_rope
|
||||
|
||||
monkeypatch.setattr(fused_rope, "HAS_TRITON", True)
|
||||
monkeypatch.setattr(fused_rope.current_omni_platform, "is_cuda", lambda: False)
|
||||
monkeypatch.setattr(torch.compiler, "is_compiling", lambda: False)
|
||||
|
||||
def unexpected_launch(*args):
|
||||
raise AssertionError("non-CUDA platforms must remain on the native path")
|
||||
|
||||
monkeypatch.setattr(fused_rope, "_launch_fused_qk_rotary_emb", unexpected_launch)
|
||||
query = torch.zeros((1, 1, 1, 128), dtype=torch.bfloat16)
|
||||
freqs = torch.zeros((1, 1, 64), dtype=torch.float32)
|
||||
assert fused_rope.try_fused_qk_rotary_emb(query, query, freqs, freqs) is None
|
||||
assert not fused_rope._FAILED_KEYS
|
||||
|
||||
|
||||
@hardware_test(res={"cuda": "L4", "rocm": "MI325"}, num_cards=1)
|
||||
def test_failed_runtime_key_cache_is_bounded():
|
||||
from vllm_omni.diffusion.models.ernie_image import fused_rope
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -10,6 +10,7 @@ import torch
|
||||
from PIL import Image
|
||||
|
||||
from vllm_omni.diffusion.models.minimax_h3 import MiniMaxH3Pipeline
|
||||
from vllm_omni.errors import OmniClientError
|
||||
from vllm_omni.inputs.data import OmniDiffusionSamplingParams
|
||||
|
||||
pytestmark = [pytest.mark.core_model, pytest.mark.cpu, pytest.mark.diffusion]
|
||||
@@ -42,8 +43,10 @@ def pipeline():
|
||||
return model
|
||||
|
||||
|
||||
def _request(task):
|
||||
def _request(task, *, payload=None):
|
||||
prompt: dict[str, Any] = {"prompt": "A person waves."}
|
||||
if payload is not None:
|
||||
prompt["additional_information"] = {"encoder_output": payload}
|
||||
if task != "t2va":
|
||||
prompt["multi_modal_data"] = {"image": Image.new("RGB", (256, 256))}
|
||||
sampling = OmniDiffusionSamplingParams(
|
||||
@@ -64,7 +67,120 @@ def test_single_stage_encodes_without_stage_zero(pipeline, task):
|
||||
torch.testing.assert_close(audio, pipeline.decode.return_value[1])
|
||||
|
||||
|
||||
def test_mixed_reference_conditioning_matches_stage_zero_handoff(pipeline, monkeypatch):
|
||||
def test_single_stage_reuses_legacy_text_but_encodes_media(pipeline):
|
||||
payload = {
|
||||
"hidden_states": torch.full((2, 5120), 3.0, dtype=torch.bfloat16),
|
||||
"token_tags": torch.ones(2, dtype=torch.long),
|
||||
}
|
||||
pipeline.forward(_request("fl2va", payload=payload))
|
||||
pipeline.encode_prompt.assert_not_called()
|
||||
pipeline.video_vae.encode_image.assert_called_once()
|
||||
torch.testing.assert_close(pipeline.diffuse.call_args.kwargs["text_embeddings"], payload["hidden_states"])
|
||||
|
||||
|
||||
def test_text_disaggregation_keeps_local_media_encoding(pipeline):
|
||||
payload = {
|
||||
"hidden_states": torch.full((2, 5120), 3.0, dtype=torch.bfloat16),
|
||||
"token_tags": torch.ones(2, dtype=torch.long),
|
||||
}
|
||||
pipeline.load_text_encoder = False
|
||||
pipeline.load_vae_encoder = True
|
||||
pipeline.forward(_request("fl2va", payload=payload))
|
||||
pipeline.encode_prompt.assert_not_called()
|
||||
pipeline.video_vae.encode_image.assert_called_once()
|
||||
|
||||
|
||||
@pytest.mark.parametrize("payload", [None, {}, {"hidden_states": torch.ones(2, 5120), "token_tags": torch.ones(2)}])
|
||||
def test_stage_one_rejects_missing_or_legacy_conditioning(pipeline, payload):
|
||||
pipeline.load_text_encoder = False
|
||||
pipeline.load_vae_encoder = False
|
||||
with pytest.raises(OmniClientError):
|
||||
pipeline.forward(_request("t2va", payload=payload))
|
||||
pipeline.encode_prompt.assert_not_called()
|
||||
pipeline.video_vae.encode_image.assert_not_called()
|
||||
pipeline.diffuse.assert_not_called()
|
||||
|
||||
|
||||
@pytest.mark.parametrize("task", ["t2va", "fl2va", "ref2va"])
|
||||
@pytest.mark.parametrize("load_text_encoder", [True, False])
|
||||
def test_prepare_encode_uses_the_same_mode_and_conditioning(pipeline, task, load_text_encoder):
|
||||
from vllm_omni.diffusion.worker.utils import StepRequestState
|
||||
|
||||
request = _request(task)
|
||||
if not load_text_encoder:
|
||||
conditioning, window_text = pipeline._prepare_local_conditioning(request.prompts[0], request.sampling_params)
|
||||
assert window_text is None
|
||||
request.prompts[0] = {"additional_information": {"encoder_output": conditioning.to_omni_payload()}}
|
||||
pipeline.encode_prompt.reset_mock()
|
||||
pipeline.video_vae.encode_image.reset_mock()
|
||||
pipeline.load_text_encoder = load_text_encoder
|
||||
pipeline.load_vae_encoder = load_text_encoder
|
||||
state = StepRequestState(request_id="step", prompt=request.prompts[0], sampling=request.sampling_params)
|
||||
assert pipeline.prepare_encode(state) is state
|
||||
assert state.latents is not None
|
||||
assert state.latents.shape[1] == 96
|
||||
assert state.total_steps == 1
|
||||
assert pipeline.encode_prompt.call_count == int(load_text_encoder)
|
||||
assert pipeline.video_vae.encode_image.call_count == int(load_text_encoder and task != "t2va")
|
||||
|
||||
|
||||
def test_stage_one_step_execution_never_falls_back(pipeline):
|
||||
from vllm_omni.diffusion.worker.utils import StepRequestState
|
||||
|
||||
pipeline.load_text_encoder = False
|
||||
pipeline.load_vae_encoder = False
|
||||
request = _request("t2va")
|
||||
with pytest.raises(OmniClientError, match="requires encoder conditioning"):
|
||||
pipeline.prepare_encode(
|
||||
StepRequestState(request_id="step", prompt=request.prompts[0], sampling=request.sampling_params)
|
||||
)
|
||||
pipeline.encode_prompt.assert_not_called()
|
||||
|
||||
|
||||
def test_multiple_outputs_encode_only_once(pipeline):
|
||||
request = _request("fl2va")
|
||||
request.sampling_params.num_outputs_per_prompt = 3
|
||||
request.sampling_params.seed = 42
|
||||
pipeline.forward(request)
|
||||
pipeline.encode_prompt.assert_called_once()
|
||||
pipeline.video_vae.encode_image.assert_called_once()
|
||||
assert [call.kwargs["seed"] for call in pipeline.diffuse.call_args_list] == [42, 43, 44]
|
||||
|
||||
|
||||
def test_ref2va_partition_preserves_image_only_implicit_task(pipeline):
|
||||
request = _request("fl2va")
|
||||
del request.sampling_params.extra_args["task"]
|
||||
pipeline.partition = "ref2va"
|
||||
pipeline.supported_tasks = frozenset({"ref2va"})
|
||||
pipeline.forward(request)
|
||||
assert pipeline.diffuse.call_args.kwargs["task"] == "ref2va"
|
||||
|
||||
|
||||
def test_invalid_legacy_text_is_not_ignored(pipeline):
|
||||
with pytest.raises(OmniClientError, match="encoder wire requires"):
|
||||
pipeline.forward(_request("fl2va", payload={"hidden_states": "invalid"}))
|
||||
pipeline.encode_prompt.assert_not_called()
|
||||
pipeline.video_vae.encode_image.assert_not_called()
|
||||
|
||||
|
||||
def test_text_weight_loading_preserves_encoder_specific_lifecycle(pipeline):
|
||||
class Encoder(torch.nn.Module):
|
||||
def load_weights(self, weights):
|
||||
return {name for name, _ in weights}
|
||||
|
||||
pipeline.text_encoder = Encoder()
|
||||
pipeline.video_vae = torch.nn.Identity()
|
||||
pipeline.audio_vae = torch.nn.Identity()
|
||||
assert pipeline.load_weights([("text_encoder.layer.weight", torch.ones(1))]) == {"text_encoder.layer.weight"}
|
||||
pipeline.load_text_encoder = False
|
||||
pipeline.load_vae_encoder = False
|
||||
pipeline.text_encoder = None
|
||||
with pytest.raises(ValueError, match="disabled in this deployment"):
|
||||
pipeline.load_weights([("text_encoder.layer.weight", torch.ones(1))])
|
||||
|
||||
|
||||
@pytest.mark.parametrize("connector_handoff", [False, True], ids=["inline", "full_payload"])
|
||||
def test_mixed_reference_conditioning_matches_stage_zero_handoff(pipeline, monkeypatch, connector_handoff):
|
||||
import numpy as np
|
||||
|
||||
from vllm_omni.data_entry_keys import flatten_payload
|
||||
@@ -74,7 +190,11 @@ def test_mixed_reference_conditioning_matches_stage_zero_handoff(pipeline, monke
|
||||
MiniMaxH3TextConditioning,
|
||||
)
|
||||
from vllm_omni.model_executor.models.minimax_h3.encoder import MiniMaxH3Encoder
|
||||
from vllm_omni.model_executor.stage_input_processors.minimax_h3 import encoder2diffusion, prepare_encoder_prompt
|
||||
from vllm_omni.model_executor.stage_input_processors.minimax_h3 import (
|
||||
encoder2diffusion,
|
||||
encoder2diffusion_full_payload,
|
||||
prepare_encoder_prompt,
|
||||
)
|
||||
|
||||
frames = np.zeros((48, 32, 32, 3), dtype=np.uint8)
|
||||
decode_frames = Mock(return_value=frames)
|
||||
@@ -110,11 +230,33 @@ def test_mixed_reference_conditioning_matches_stage_zero_handoff(pipeline, monke
|
||||
media = stage_zero._encode_media(stage_zero._media_input(transformed["additional_information"]))
|
||||
text = MiniMaxH3TextConditioning(*pipeline.encode_prompt.return_value)
|
||||
payload = MiniMaxH3EncoderConditioning.from_components(text, media).to_omni_payload()
|
||||
source = SimpleNamespace(finished=True, outputs=[SimpleNamespace(multimodal_output=flatten_payload(payload))])
|
||||
wire = flatten_payload(payload)
|
||||
source = SimpleNamespace(
|
||||
finished=True, outputs=[SimpleNamespace(multimodal_output=None if connector_handoff else wire)]
|
||||
)
|
||||
bridged = encoder2diffusion([source], request.prompts[0])
|
||||
assert bridged["multi_modal_data"] is None
|
||||
if connector_handoff:
|
||||
assert "encoder_output" not in bridged["additional_information"]
|
||||
transferred = encoder2diffusion_full_payload(pooling_output=wire)
|
||||
assert set(transferred) == {"encoder_output"}
|
||||
received = transferred["encoder_output"]
|
||||
for section, key in (
|
||||
("hidden_states", "output"),
|
||||
("meta", "token_role_ids"),
|
||||
("embed", "embedding"),
|
||||
("embed", "speech_feat"),
|
||||
("kv_metadata", "minimax_h3_encoder_layout"),
|
||||
):
|
||||
torch.testing.assert_close(received[section][key], payload[section][key])
|
||||
# Simulate the generic diffusion runner merging the received payload;
|
||||
# native NIXL transport is covered separately, not by this CPU test.
|
||||
bridged["additional_information"].update(transferred)
|
||||
pipeline.load_text_encoder = False
|
||||
pipeline.load_vae_encoder = False
|
||||
pipeline.encode_prompt.reset_mock()
|
||||
pipeline.video_vae.encode_image.reset_mock()
|
||||
pipeline.video_vae.encode_video.reset_mock()
|
||||
pipeline.forward(SimpleNamespace(prompts=[bridged], sampling_params=request.sampling_params))
|
||||
external_kwargs = pipeline.diffuse.call_args.kwargs
|
||||
for key, value in local_kwargs.items():
|
||||
@@ -123,6 +265,8 @@ def test_mixed_reference_conditioning_matches_stage_zero_handoff(pipeline, monke
|
||||
else:
|
||||
assert value == external_kwargs[key]
|
||||
pipeline.encode_prompt.assert_not_called()
|
||||
pipeline.video_vae.encode_image.assert_not_called()
|
||||
pipeline.video_vae.encode_video.assert_not_called()
|
||||
assert decode_frames.call_count == sampler.call_count == 2
|
||||
assert all(call.kwargs["decoded_frames"] is frames for call in sampler.call_args_list)
|
||||
assert [block["kind"] for block in local_kwargs["ref_blocks"]] == ["image", "video_audio", "audio"]
|
||||
|
||||
@@ -10,9 +10,17 @@ from unittest.mock import Mock
|
||||
import pytest
|
||||
import torch
|
||||
|
||||
from vllm_omni.model_executor.models.minimax_h3.conditioning import MiniMaxH3EncoderMediaInput
|
||||
|
||||
pytestmark = [pytest.mark.core_model, pytest.mark.cpu, pytest.mark.diffusion]
|
||||
|
||||
|
||||
def _media(**kwargs):
|
||||
return MiniMaxH3EncoderMediaInput(
|
||||
task="ref2va", height=768, width=1344, num_frames=124, latent_t=37, audio_t=207, **kwargs
|
||||
)
|
||||
|
||||
|
||||
def test_h3_full_pipeline_profiler_includes_local_encoding():
|
||||
from vllm_omni.diffusion.models.minimax_h3 import MiniMaxH3Pipeline
|
||||
|
||||
@@ -28,6 +36,9 @@ def test_h3_full_pipeline_profiler_includes_local_encoding():
|
||||
"denoise_step",
|
||||
"post_decode",
|
||||
]
|
||||
assert "_encode_video_conditions" not in targets
|
||||
assert "_encode_video_audio_conditions" not in targets
|
||||
assert "_encode_audio_conditions" not in targets
|
||||
|
||||
|
||||
def test_decoded_output_is_unchanged_without_active_model_offload():
|
||||
@@ -316,46 +327,6 @@ def test_h3_model_cpu_offload_registers_direct_vae_stages(monkeypatch, load_text
|
||||
remove_offload.assert_called_once_with([*dits, *stages])
|
||||
|
||||
|
||||
@pytest.mark.parametrize("decode_fails", [False, True])
|
||||
def test_h3_model_cpu_offload_scopes_direct_vae_call(monkeypatch, decode_fails):
|
||||
from vllm_omni.diffusion.models.minimax_h3 import MiniMaxH3Pipeline
|
||||
from vllm_omni.diffusion.models.minimax_h3 import pipeline_minimax_h3 as module
|
||||
|
||||
pipeline = object.__new__(MiniMaxH3Pipeline)
|
||||
torch.nn.Module.__init__(pipeline)
|
||||
component = torch.nn.Linear(2, 2)
|
||||
events: list[tuple[Any, ...]] = []
|
||||
|
||||
@contextmanager
|
||||
def record_component(value):
|
||||
events.append(("activate", value))
|
||||
try:
|
||||
yield
|
||||
finally:
|
||||
events.append(("offload", value))
|
||||
|
||||
monkeypatch.setattr(module, "sequential_offload_component", record_component)
|
||||
pipeline._model_cpu_offload_modules = [component]
|
||||
|
||||
def decode():
|
||||
with pipeline._component_on_device(component):
|
||||
events.append(("decode", component))
|
||||
if decode_fails:
|
||||
raise RuntimeError("decode failed")
|
||||
|
||||
if decode_fails:
|
||||
with pytest.raises(RuntimeError, match="decode failed"):
|
||||
decode()
|
||||
else:
|
||||
decode()
|
||||
|
||||
assert events == [
|
||||
("activate", component),
|
||||
("decode", component),
|
||||
("offload", component),
|
||||
]
|
||||
|
||||
|
||||
def test_h3_model_cpu_offload_keeps_unselected_vaes_resident(monkeypatch):
|
||||
from vllm_omni.diffusion.models.minimax_h3 import MiniMaxH3Pipeline
|
||||
from vllm_omni.diffusion.models.minimax_h3 import pipeline_minimax_h3 as module
|
||||
@@ -416,6 +387,46 @@ def test_h3_model_cpu_offload_rejects_unloaded_selected_encoder(monkeypatch):
|
||||
apply_offload.assert_not_called()
|
||||
|
||||
|
||||
@pytest.mark.parametrize("decode_fails", [False, True])
|
||||
def test_h3_model_cpu_offload_scopes_direct_vae_call(monkeypatch, decode_fails):
|
||||
from vllm_omni.diffusion.models.minimax_h3 import MiniMaxH3Pipeline
|
||||
from vllm_omni.diffusion.models.minimax_h3 import pipeline_minimax_h3 as module
|
||||
|
||||
pipeline = object.__new__(MiniMaxH3Pipeline)
|
||||
torch.nn.Module.__init__(pipeline)
|
||||
component = torch.nn.Linear(2, 2)
|
||||
events: list[tuple[Any, ...]] = []
|
||||
|
||||
@contextmanager
|
||||
def record_component(value):
|
||||
events.append(("activate", value))
|
||||
try:
|
||||
yield
|
||||
finally:
|
||||
events.append(("offload", value))
|
||||
|
||||
monkeypatch.setattr(module, "sequential_offload_component", record_component)
|
||||
pipeline._model_cpu_offload_modules = [component]
|
||||
|
||||
def decode():
|
||||
with pipeline._component_on_device(component):
|
||||
events.append(("decode", component))
|
||||
if decode_fails:
|
||||
raise RuntimeError("decode failed")
|
||||
|
||||
if decode_fails:
|
||||
with pytest.raises(RuntimeError, match="decode failed"):
|
||||
decode()
|
||||
else:
|
||||
decode()
|
||||
|
||||
assert events == [
|
||||
("activate", component),
|
||||
("decode", component),
|
||||
("offload", component),
|
||||
]
|
||||
|
||||
|
||||
def _encode_media(pipeline, **kwargs):
|
||||
from vllm_omni.model_executor.models.minimax_h3.conditioning import MiniMaxH3EncoderMediaInput
|
||||
from vllm_omni.model_executor.models.minimax_h3.encoder_processing import encode_media
|
||||
|
||||
@@ -416,7 +416,7 @@ def test_prepare_encode_seeds_runner_visible_state(monkeypatch, batch_frames):
|
||||
monkeypatch.setattr(
|
||||
mod.MiniMaxH3Pipeline,
|
||||
"_prepare_encoder_conditioning_inputs",
|
||||
lambda self, value, sampling: context,
|
||||
lambda self, value, sampling: context if value is conditioning else pytest.fail("wrong encoder handoff"),
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
mod.MiniMaxH3Pipeline,
|
||||
|
||||
@@ -15,6 +15,21 @@ from vllm_omni.diffusion.models.minimax_h3.temporal_chunks import decode_tempora
|
||||
pytestmark = [pytest.mark.core_model, pytest.mark.cpu, pytest.mark.diffusion]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("chunked", [False, True])
|
||||
def test_encode_only_video_vae_rejects_full_and_chunked_decode(chunked):
|
||||
from vllm_omni.diffusion.models.minimax_h3.vae import MiniMaxH3VideoVAE
|
||||
|
||||
vae = object.__new__(MiniMaxH3VideoVAE)
|
||||
torch.nn.Module.__init__(vae)
|
||||
vae.encode_only = True
|
||||
latent = torch.empty(1, 1, 1, 1, 1)
|
||||
with pytest.raises(RuntimeError, match="encode-only video VAE cannot decode"):
|
||||
if chunked:
|
||||
vae.decode_with_chunks(latent, on_chunk=lambda frames: None)
|
||||
else:
|
||||
vae.decode_latent(latent)
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def cpu_process_group():
|
||||
if dist.is_initialized():
|
||||
|
||||
@@ -547,6 +547,9 @@ def test_execute_stepwise_streaming_returns_chunks_at_boundaries(monkeypatch):
|
||||
runner.od_config.step_execution = True
|
||||
req = _make_request()
|
||||
req.request_id = "req"
|
||||
req.external_req_id = "external-req"
|
||||
sent = []
|
||||
runner._maybe_send_stage_payload = lambda requests, outputs: sent.append((requests[0].external_req_id, outputs))
|
||||
|
||||
monkeypatch.setattr(model_runner_module, "set_forward_context", _noop_forward_context)
|
||||
monkeypatch.setattr(model_runner_module.current_omni_platform, "reset_peak_memory_stats", lambda: None)
|
||||
@@ -560,6 +563,7 @@ def test_execute_stepwise_streaming_returns_chunks_at_boundaries(monkeypatch):
|
||||
|
||||
first = DiffusionModelRunner.execute_stepwise(runner, scheduler_output)
|
||||
assert first.get_request_output("req").result is None
|
||||
assert sent == []
|
||||
|
||||
scheduler_output = SimpleNamespace(
|
||||
finished_req_ids=set(),
|
||||
@@ -569,11 +573,13 @@ def test_execute_stepwise_streaming_returns_chunks_at_boundaries(monkeypatch):
|
||||
second = DiffusionModelRunner.execute_stepwise(runner, scheduler_output)
|
||||
assert second.get_request_output("req").result == chunks[0]
|
||||
assert second.get_request_output("req").finished is False
|
||||
assert sent == []
|
||||
|
||||
DiffusionModelRunner.execute_stepwise(runner, scheduler_output)
|
||||
fourth = DiffusionModelRunner.execute_stepwise(runner, scheduler_output)
|
||||
assert fourth.get_request_output("req").result == chunks[1]
|
||||
assert fourth.get_request_output("req").finished is True
|
||||
assert sent == [("external-req", [chunks[1]])]
|
||||
|
||||
|
||||
@pytest.mark.core_model
|
||||
@@ -733,6 +739,7 @@ def test_execute_model_passes_single_request_batch_to_non_admission_pipeline(mon
|
||||
req = _make_request()
|
||||
|
||||
monkeypatch.setattr(model_runner_module, "set_forward_context", _noop_forward_context)
|
||||
monkeypatch.setattr(model_runner_module, "current_omni_platform", _fake_platform_for_peak_memory())
|
||||
|
||||
output = DiffusionModelRunner.execute_model(runner, req)
|
||||
|
||||
@@ -749,6 +756,7 @@ def test_execute_model_accepts_bare_diffusion_output_from_single_request_pipelin
|
||||
req = _make_request()
|
||||
|
||||
monkeypatch.setattr(model_runner_module, "set_forward_context", _noop_forward_context)
|
||||
monkeypatch.setattr(model_runner_module, "current_omni_platform", _fake_platform_for_peak_memory())
|
||||
|
||||
output = DiffusionModelRunner.execute_model(runner, req)
|
||||
|
||||
|
||||
@@ -0,0 +1,785 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
|
||||
|
||||
from types import SimpleNamespace
|
||||
|
||||
import pytest
|
||||
import torch
|
||||
|
||||
from vllm_omni.diffusion.worker.diffusion_model_runner import DiffusionModelRunner
|
||||
|
||||
pytestmark = [pytest.mark.core_model, pytest.mark.cpu, pytest.mark.diffusion]
|
||||
|
||||
HANDLE_KEY = DiffusionModelRunner._STAGE_PAYLOAD_HANDLE_KEY
|
||||
|
||||
|
||||
class _FakeConnector:
|
||||
def abandon_get(self, get_key):
|
||||
pass
|
||||
|
||||
def get_with_deadline(self, from_stage, to_stage, get_key, metadata=None, *, deadline):
|
||||
return self.get(from_stage, to_stage, get_key, metadata)
|
||||
|
||||
def __init__(self, payload=None, *, raises=False, put_result=(True, 128, {"schema_version": 1})):
|
||||
self._payload = payload
|
||||
self._raises = raises
|
||||
self._put_result = put_result
|
||||
self.calls: list[tuple[str, str, str, object]] = []
|
||||
self.put_calls: list[tuple[str, str, str, object]] = []
|
||||
|
||||
def get(self, from_stage, to_stage, get_key, metadata=None):
|
||||
self.calls.append((from_stage, to_stage, get_key, metadata))
|
||||
if self._raises:
|
||||
raise RuntimeError("transfer failed")
|
||||
if self._payload is None:
|
||||
return None
|
||||
return self._payload, 0
|
||||
|
||||
def put(self, from_stage, to_stage, put_key, data):
|
||||
self.put_calls.append((from_stage, to_stage, put_key, data))
|
||||
if self._raises:
|
||||
raise RuntimeError("transfer failed")
|
||||
return self._put_result
|
||||
|
||||
|
||||
class _FakeKVTransferManager:
|
||||
from vllm_omni.distributed.omni_connectors.kv_transfer_manager import OmniKVTransferManager
|
||||
|
||||
_resolve_sender_info = OmniKVTransferManager._resolve_sender_info
|
||||
|
||||
def __init__(self, connector, recv_stages=("0", "1"), send_stages=("0", "1")):
|
||||
self.connector = connector
|
||||
self.recv_stages = recv_stages
|
||||
self.send_stages = send_stages
|
||||
self.sender_info_calls: list[tuple[dict, str | None]] = []
|
||||
|
||||
def update_sender_info(self, sender_info, sender_stage_id=None):
|
||||
self.sender_info_calls.append((sender_info, sender_stage_id))
|
||||
|
||||
|
||||
def _make_runner(connector, *, payload_keys=("text_encoder_output",), recv_stages=("0", "1")):
|
||||
runner = object.__new__(DiffusionModelRunner)
|
||||
runner.od_config = SimpleNamespace(stage_input_payload_keys=payload_keys, stage_id=1)
|
||||
runner.device = torch.device("cpu")
|
||||
runner._local_rank = 0
|
||||
runner.pipeline = None
|
||||
runner.kv_transfer_manager = _FakeKVTransferManager(connector, recv_stages=recv_stages)
|
||||
runner.init_omni_connectors(runner.od_config, runner.kv_transfer_manager, synchronous=True)
|
||||
return runner
|
||||
|
||||
|
||||
def _make_sender(connector, *, payload_keys=("prompt_embeds",), send_stages=("0", "1")):
|
||||
runner = object.__new__(DiffusionModelRunner)
|
||||
runner.od_config = SimpleNamespace(stage_output_payload_keys=payload_keys, stage_id=0)
|
||||
runner.device = torch.device("cpu")
|
||||
runner.pipeline = None
|
||||
runner.kv_transfer_manager = _FakeKVTransferManager(connector, send_stages=send_stages)
|
||||
runner.init_omni_connectors(runner.od_config, runner.kv_transfer_manager, synchronous=True)
|
||||
return runner
|
||||
|
||||
|
||||
def _make_output(**custom):
|
||||
return SimpleNamespace(custom_output=dict(custom))
|
||||
|
||||
|
||||
def _make_request(prompt, *, request_id="req-7", kv_sender_info=None, payload_sender_info=None):
|
||||
return SimpleNamespace(
|
||||
prompt=prompt,
|
||||
request_id=request_id,
|
||||
kv_sender_info=kv_sender_info,
|
||||
payload_sender_info=payload_sender_info,
|
||||
)
|
||||
|
||||
|
||||
def _conditioning():
|
||||
return {"text_encoder_output": {"hidden_states": torch.zeros(4, 8), "token_tags": torch.zeros(4)}}
|
||||
|
||||
|
||||
@pytest.mark.parametrize("shard_size,replicate_size", [(4, 1), (1, 4), (2, 2)])
|
||||
def test_standalone_hsdp_elects_one_payload_consumer(monkeypatch, shard_size, replicate_size):
|
||||
from vllm_omni.diffusion.distributed import parallel_state
|
||||
|
||||
leaders = []
|
||||
for rank in range(shard_size * replicate_size):
|
||||
shard_group = SimpleNamespace(world_size=shard_size, rank_in_group=rank % shard_size)
|
||||
replicate_group = SimpleNamespace(world_size=replicate_size, rank_in_group=rank // shard_size)
|
||||
monkeypatch.setattr(parallel_state, "get_fs_group", lambda: shard_group)
|
||||
monkeypatch.setattr(parallel_state, "get_hsdp_replicate_group", lambda: replicate_group)
|
||||
monkeypatch.setattr(parallel_state, "get_sp_group", lambda: None)
|
||||
runner = _make_runner(_FakeConnector())
|
||||
monkeypatch.setattr(runner, "_get_local_tp_group", lambda: None)
|
||||
if runner.is_data_transfer_rank():
|
||||
leaders.append(rank)
|
||||
|
||||
assert leaders == [0]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("shard_size,replicate_size", [(4, 1), (1, 4), (2, 2)])
|
||||
@pytest.mark.parametrize("delivered", [True, False])
|
||||
def test_standalone_hsdp_payload_fanout(monkeypatch, shard_size, replicate_size, delivered):
|
||||
from uuid import uuid4
|
||||
|
||||
from vllm_omni.diffusion.distributed import parallel_state
|
||||
from vllm_omni.distributed.omni_connectors.connectors.shm_connector import SharedMemoryConnector
|
||||
|
||||
packets = {}
|
||||
|
||||
class MeshGroup:
|
||||
def __init__(self, dimension, peer_rank, rank, size):
|
||||
self.key = (dimension, peer_rank)
|
||||
self.rank_in_group = rank
|
||||
self.world_size = size
|
||||
|
||||
def broadcast_object(self, value, src=0):
|
||||
if self.rank_in_group == src:
|
||||
packets[self.key, "delivered"] = value
|
||||
return packets[self.key, "delivered"]
|
||||
|
||||
def broadcast_tensor_dict(self, value, src=0):
|
||||
if self.rank_in_group == src:
|
||||
packets[self.key, "payload"] = value
|
||||
return packets[self.key, "payload"]
|
||||
|
||||
connector = SharedMemoryConnector({})
|
||||
request_id = f"hsdp-{uuid4().hex}"
|
||||
key = f"{request_id}_0_0"
|
||||
expected = torch.arange(8).reshape(2, 4)
|
||||
calls = []
|
||||
original_get = connector.get_with_deadline
|
||||
|
||||
def tracked_get(*args, **kwargs):
|
||||
calls.append(rank)
|
||||
return original_get(*args, **kwargs)
|
||||
|
||||
monkeypatch.setattr(connector, "get_with_deadline", tracked_get)
|
||||
monkeypatch.setattr(parallel_state, "get_sp_group", lambda: None)
|
||||
try:
|
||||
if delivered:
|
||||
assert connector.put("0", "1", key, {"encoder_output": expected})[0]
|
||||
for rank in range(shard_size * replicate_size):
|
||||
shard_rank = rank % shard_size
|
||||
replicate_rank = rank // shard_size
|
||||
shard_group = MeshGroup("shard", replicate_rank, shard_rank, shard_size)
|
||||
replicate_group = MeshGroup("replicate", shard_rank, replicate_rank, replicate_size)
|
||||
monkeypatch.setattr(parallel_state, "get_fs_group", lambda: shard_group)
|
||||
monkeypatch.setattr(parallel_state, "get_hsdp_replicate_group", lambda: replicate_group)
|
||||
runner = _make_runner(connector, payload_keys=("encoder_output",))
|
||||
monkeypatch.setattr(runner, "_get_local_tp_group", lambda: None)
|
||||
request = _make_request({"prompt": "test"}, request_id=request_id)
|
||||
if delivered:
|
||||
runner._maybe_recv_stage_payload(request)
|
||||
torch.testing.assert_close(request.prompt["additional_information"]["encoder_output"], expected)
|
||||
else:
|
||||
with pytest.raises(RuntimeError, match="Stage payload unavailable"):
|
||||
runner._maybe_recv_stage_payload(request)
|
||||
assert set(calls) == {0}
|
||||
if delivered:
|
||||
assert calls == [0]
|
||||
assert connector.get("0", "1", key) is None
|
||||
finally:
|
||||
connector.close()
|
||||
|
||||
|
||||
def test_key_convention_fetch_merges_into_additional_information():
|
||||
connector = _FakeConnector(_conditioning())
|
||||
runner = _make_runner(connector)
|
||||
req = _make_request({"prompt": "a cat"})
|
||||
|
||||
runner._maybe_recv_stage_payload(req)
|
||||
|
||||
assert connector.calls == [("0", "1", "req-7_0_0", None)]
|
||||
assert set(req.prompt["additional_information"]) == {"text_encoder_output"}
|
||||
assert req.prompt["additional_information"]["text_encoder_output"]["hidden_states"].shape == (4, 8)
|
||||
|
||||
|
||||
def test_handle_path_uses_its_own_key_and_metadata():
|
||||
connector = _FakeConnector(_conditioning())
|
||||
runner = _make_runner(connector, payload_keys=())
|
||||
handle = {
|
||||
"key": "custom-key",
|
||||
"from_stage": "3",
|
||||
"to_stage": "4",
|
||||
"metadata": {"schema_version": 1},
|
||||
}
|
||||
req = _make_request({"prompt": "a cat", HANDLE_KEY: handle})
|
||||
|
||||
runner._maybe_recv_stage_payload(req)
|
||||
|
||||
assert connector.calls == [("3", "4", "custom-key", {"schema_version": 1})]
|
||||
# The handle is transport bookkeeping and must not reach the pipeline.
|
||||
assert HANDLE_KEY not in req.prompt
|
||||
assert "text_encoder_output" in req.prompt["additional_information"]
|
||||
|
||||
|
||||
def test_receive_retries_until_producer_publishes(monkeypatch):
|
||||
connector = _FakeConnector(_conditioning())
|
||||
get = connector.get
|
||||
attempts = []
|
||||
|
||||
def delayed_get(*args, **kwargs):
|
||||
attempts.append(args)
|
||||
return get(*args, **kwargs) if len(attempts) == 3 else None
|
||||
|
||||
monkeypatch.setattr(connector, "get", delayed_get)
|
||||
runner = _make_runner(connector)
|
||||
request = _make_request({"prompt": "a cat"})
|
||||
|
||||
runner._maybe_recv_stage_payload(request)
|
||||
|
||||
assert len(attempts) == 3
|
||||
assert "text_encoder_output" in request.prompt["additional_information"]
|
||||
|
||||
|
||||
def test_receive_retry_budget_preserves_inline_payload(monkeypatch):
|
||||
from vllm_omni.distributed.omni_connectors.model_runner import omni_connector_payload_transport
|
||||
|
||||
clock = [0.0]
|
||||
|
||||
def advance(duration):
|
||||
clock[0] += duration
|
||||
|
||||
monkeypatch.setattr(
|
||||
omni_connector_payload_transport, "time", SimpleNamespace(monotonic=lambda: clock[0], sleep=advance)
|
||||
)
|
||||
connector = _FakeConnector(None)
|
||||
runner = _make_runner(connector)
|
||||
inline = _conditioning()
|
||||
request = _make_request({"additional_information": inline})
|
||||
|
||||
runner._maybe_recv_stage_payload(request)
|
||||
|
||||
assert 1 < len(connector.calls) <= 41
|
||||
assert clock[0] == pytest.approx(2.0)
|
||||
assert request.prompt["additional_information"] is inline
|
||||
|
||||
|
||||
def test_stage_without_declared_keys_never_touches_the_connector():
|
||||
connector = _FakeConnector(_conditioning())
|
||||
runner = _make_runner(connector, payload_keys=())
|
||||
req = _make_request({"prompt": "a cat"})
|
||||
|
||||
runner._maybe_recv_stage_payload(req)
|
||||
|
||||
assert connector.calls == []
|
||||
assert "additional_information" not in req.prompt
|
||||
|
||||
|
||||
def test_undeclared_payload_keys_are_dropped():
|
||||
connector = _FakeConnector({**_conditioning(), "debug_blob": torch.zeros(2)})
|
||||
runner = _make_runner(connector)
|
||||
req = _make_request({"prompt": "a cat"})
|
||||
|
||||
runner._maybe_recv_stage_payload(req)
|
||||
|
||||
assert set(req.prompt["additional_information"]) == {"text_encoder_output"}
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"connector",
|
||||
[
|
||||
_FakeConnector(None),
|
||||
_FakeConnector(raises=True),
|
||||
_FakeConnector("not-a-dict"),
|
||||
],
|
||||
ids=["missing", "raises", "wrong_type"],
|
||||
)
|
||||
def test_failed_transfer_falls_back_to_the_inline_prompt(connector):
|
||||
runner = _make_runner(connector)
|
||||
inline = {"text_encoder_output": {"hidden_states": torch.ones(2, 8)}}
|
||||
req = _make_request({"prompt": "a cat", "additional_information": dict(inline)})
|
||||
|
||||
runner._maybe_recv_stage_payload(req)
|
||||
|
||||
assert torch.equal(
|
||||
req.prompt["additional_information"]["text_encoder_output"]["hidden_states"],
|
||||
inline["text_encoder_output"]["hidden_states"],
|
||||
)
|
||||
|
||||
|
||||
def test_legacy_sender_info_is_passed_as_request_metadata():
|
||||
connector = _FakeConnector(_conditioning())
|
||||
runner = _make_runner(connector)
|
||||
req = _make_request({"prompt": "a cat"}, kv_sender_info={0: {"host": "10.0.0.1", "zmq_port": 50171}})
|
||||
|
||||
runner._maybe_recv_stage_payload(req)
|
||||
|
||||
assert runner.kv_transfer_manager.sender_info_calls == []
|
||||
assert connector.calls[0][3] == {"source_host": "10.0.0.1", "source_port": 50171}
|
||||
|
||||
|
||||
def test_payload_sender_info_overrides_kv_sender_info_for_full_payloads():
|
||||
connector = _FakeConnector(_conditioning())
|
||||
runner = _make_runner(connector)
|
||||
req = _make_request(
|
||||
{"prompt": "a cat"},
|
||||
kv_sender_info={0: {"host": "10.0.0.1", "zmq_port": 50171}},
|
||||
payload_sender_info={"host": "10.0.0.1", "zmq_port": 50071},
|
||||
)
|
||||
|
||||
runner._maybe_recv_stage_payload(req)
|
||||
|
||||
assert runner.kv_transfer_manager.sender_info_calls == []
|
||||
assert connector.calls[0][3] == {"source_host": "10.0.0.1", "source_port": 50071}
|
||||
|
||||
|
||||
def test_synchronous_receive_keeps_endpoints_request_scoped_and_uses_external_ids():
|
||||
connector = _FakeConnector(_conditioning())
|
||||
runner = _make_runner(connector, recv_stages=("2", "5"))
|
||||
for index in range(2):
|
||||
request = _make_request(
|
||||
{},
|
||||
request_id=f"internal-{index}",
|
||||
payload_sender_info={"host": f"10.0.0.{index + 1}", "zmq_port": 50071 + index},
|
||||
)
|
||||
request.external_req_id = f"external-{index}"
|
||||
runner._maybe_recv_stage_payload(request)
|
||||
assert "text_encoder_output" in request.prompt["additional_information"]
|
||||
assert connector.calls == [
|
||||
("2", "5", "external-0_2_0", {"source_host": "10.0.0.1", "source_port": 50071}),
|
||||
("2", "5", "external-1_2_0", {"source_host": "10.0.0.2", "source_port": 50072}),
|
||||
]
|
||||
assert runner.kv_transfer_manager.sender_info_calls == []
|
||||
assert runner._pending_load_reqs == {}
|
||||
assert runner._get_req_chunk == {}
|
||||
|
||||
|
||||
@pytest.mark.parametrize("stage_key", [2, "2"])
|
||||
@pytest.mark.parametrize("use_handle", [False, True])
|
||||
def test_sender_map_selects_actual_source_stage(stage_key, use_handle):
|
||||
connector = _FakeConnector(_conditioning())
|
||||
runner = _make_runner(connector, recv_stages=("0" if use_handle else "2", "5"))
|
||||
prompt = {}
|
||||
if use_handle:
|
||||
prompt[HANDLE_KEY] = {"key": "explicit", "from_stage": "2", "to_stage": "5"}
|
||||
request = _make_request(
|
||||
prompt,
|
||||
payload_sender_info={
|
||||
"0": {"host": "wrong", "zmq_port": 50000},
|
||||
stage_key: {"host": "right", "zmq_port": 50002},
|
||||
},
|
||||
)
|
||||
runner._maybe_recv_stage_payload(request)
|
||||
assert connector.calls[0][0:2] == ("2", "5")
|
||||
assert connector.calls[0][3] == {"source_host": "right", "source_port": 50002}
|
||||
|
||||
|
||||
def test_tp_payload_is_fetched_once_by_leader_and_broadcast_to_followers():
|
||||
connector = _FakeConnector(_conditioning())
|
||||
state = {}
|
||||
|
||||
class _FakeTPGroup:
|
||||
world_size = 4
|
||||
|
||||
def __init__(self, rank):
|
||||
self.rank_in_group = rank
|
||||
|
||||
def broadcast_object(self, value, src=0):
|
||||
if self.rank_in_group == src:
|
||||
state["delivered"] = value
|
||||
return state["delivered"]
|
||||
|
||||
def broadcast_tensor_dict(self, value, src=0):
|
||||
if self.rank_in_group == src:
|
||||
state["payload"] = value
|
||||
return state["payload"]
|
||||
|
||||
leader = _make_runner(connector)
|
||||
leader._local_rank = 0
|
||||
leader._get_local_tp_group = lambda: _FakeTPGroup(0)
|
||||
follower = _make_runner(connector)
|
||||
follower._local_rank = 1
|
||||
follower._get_local_tp_group = lambda: _FakeTPGroup(1)
|
||||
|
||||
leader_req = _make_request({"prompt": "a cat"})
|
||||
follower_req = _make_request({"prompt": "a cat"})
|
||||
leader._maybe_recv_stage_payload(leader_req)
|
||||
follower._maybe_recv_stage_payload(follower_req)
|
||||
|
||||
assert len(connector.calls) == 1
|
||||
leader_output = leader_req.prompt["additional_information"]["text_encoder_output"]["hidden_states"]
|
||||
follower_output = follower_req.prompt["additional_information"]["text_encoder_output"]["hidden_states"]
|
||||
assert torch.equal(leader_output, follower_output)
|
||||
|
||||
|
||||
def test_tp_payload_miss_is_broadcast_without_follower_connector_access():
|
||||
connector = _FakeConnector(None)
|
||||
state = {}
|
||||
|
||||
class _FakeTPGroup:
|
||||
world_size = 2
|
||||
|
||||
def __init__(self, rank):
|
||||
self.rank_in_group = rank
|
||||
|
||||
def broadcast_object(self, value, src=0):
|
||||
if self.rank_in_group == src:
|
||||
state["delivered"] = value
|
||||
return state["delivered"]
|
||||
|
||||
def broadcast_tensor_dict(self, value, src=0):
|
||||
raise AssertionError("missing payload must not be broadcast")
|
||||
|
||||
leader = _make_runner(connector)
|
||||
leader._get_local_tp_group = lambda: _FakeTPGroup(0)
|
||||
follower = _make_runner(connector)
|
||||
follower._local_rank = 1
|
||||
follower._get_local_tp_group = lambda: _FakeTPGroup(1)
|
||||
|
||||
with pytest.raises(RuntimeError, match="Stage payload unavailable"):
|
||||
leader._maybe_recv_stage_payload(_make_request({"prompt": "a cat"}))
|
||||
with pytest.raises(RuntimeError, match="Stage payload unavailable"):
|
||||
follower._maybe_recv_stage_payload(_make_request({"prompt": "a cat"}))
|
||||
|
||||
assert 1 < len(connector.calls) <= 41
|
||||
|
||||
|
||||
def test_sp_payload_is_fetched_once_by_leader_and_broadcast_to_followers():
|
||||
connector = _FakeConnector(_conditioning())
|
||||
state = {}
|
||||
|
||||
class _FakeSPGroup:
|
||||
world_size = 4
|
||||
|
||||
def __init__(self, rank):
|
||||
self.rank_in_group = rank
|
||||
|
||||
def broadcast_object(self, value, src=0):
|
||||
if self.rank_in_group == src:
|
||||
state["delivered"] = value
|
||||
return state["delivered"]
|
||||
|
||||
def broadcast_tensor_dict(self, value, src=0):
|
||||
if self.rank_in_group == src:
|
||||
state["payload"] = value
|
||||
return state["payload"]
|
||||
|
||||
leader = _make_runner(connector)
|
||||
leader._get_local_tp_group = lambda: None
|
||||
leader._stage_payload_broadcast_groups = lambda: (_FakeSPGroup(0),)
|
||||
follower = _make_runner(connector)
|
||||
follower._local_rank = 1
|
||||
follower._get_local_tp_group = lambda: None
|
||||
follower._stage_payload_broadcast_groups = lambda: (_FakeSPGroup(1),)
|
||||
|
||||
leader_req = _make_request({"prompt": "a cat"})
|
||||
follower_req = _make_request({"prompt": "a cat"})
|
||||
leader._maybe_recv_stage_payload(leader_req)
|
||||
follower._maybe_recv_stage_payload(follower_req)
|
||||
|
||||
assert len(connector.calls) == 1
|
||||
leader_output = leader_req.prompt["additional_information"]["text_encoder_output"]["hidden_states"]
|
||||
follower_output = follower_req.prompt["additional_information"]["text_encoder_output"]["hidden_states"]
|
||||
assert torch.equal(leader_output, follower_output)
|
||||
|
||||
|
||||
def test_missing_incoming_edge_is_reported_not_fetched():
|
||||
connector = _FakeConnector(_conditioning())
|
||||
runner = _make_runner(connector, recv_stages=(None, None))
|
||||
req = _make_request({"prompt": "a cat"})
|
||||
|
||||
with pytest.raises(RuntimeError, match="no incoming edge"):
|
||||
runner._maybe_recv_stage_payload(req)
|
||||
|
||||
assert connector.calls == []
|
||||
assert "additional_information" not in req.prompt
|
||||
|
||||
|
||||
@pytest.mark.parametrize("delivered", [True, False])
|
||||
def test_payload_reaches_full_tp_sp_grid_once(monkeypatch, delivered):
|
||||
from vllm_omni.diffusion.distributed import parallel_state
|
||||
|
||||
connector = _FakeConnector(_conditioning() if delivered else None)
|
||||
packets = {}
|
||||
|
||||
class GridGroup:
|
||||
world_size = 2
|
||||
|
||||
def __init__(self, dimension, peer_rank, rank):
|
||||
self.key = (dimension, peer_rank)
|
||||
self.rank_in_group = rank
|
||||
|
||||
def broadcast_object(self, value, src=0):
|
||||
if self.rank_in_group == src:
|
||||
packets[self.key, "delivered"] = value
|
||||
return packets[self.key, "delivered"]
|
||||
|
||||
def broadcast_tensor_dict(self, value, src=0):
|
||||
if self.rank_in_group == src:
|
||||
packets[self.key, "payload"] = value
|
||||
return packets[self.key, "payload"]
|
||||
|
||||
for sp_rank in range(2):
|
||||
for tp_rank in range(2):
|
||||
runner = _make_runner(connector)
|
||||
tp_group = GridGroup("tp", sp_rank, tp_rank)
|
||||
sp_group = GridGroup("sp", tp_rank, sp_rank)
|
||||
monkeypatch.setattr(runner, "_get_local_tp_group", lambda: tp_group)
|
||||
monkeypatch.setattr(parallel_state, "get_sp_group", lambda: sp_group)
|
||||
request = _make_request({"prompt": "a cat"})
|
||||
|
||||
if delivered:
|
||||
runner._maybe_recv_stage_payload(request)
|
||||
output = request.prompt["additional_information"]["text_encoder_output"]
|
||||
assert torch.equal(output["hidden_states"], connector._payload["text_encoder_output"]["hidden_states"])
|
||||
else:
|
||||
with pytest.raises(RuntimeError, match="Stage payload unavailable"):
|
||||
runner._maybe_recv_stage_payload(request)
|
||||
if delivered:
|
||||
assert len(connector.calls) == 1
|
||||
else:
|
||||
assert 1 < len(connector.calls) <= 41
|
||||
|
||||
|
||||
def test_native_kv_runner_keeps_synchronous_payload_transport(monkeypatch):
|
||||
from unittest.mock import Mock
|
||||
|
||||
from vllm_omni.diffusion.worker import diffusion_model_runner as runner_module
|
||||
|
||||
connector = _FakeConnector(_conditioning())
|
||||
manager = _FakeKVTransferManager(connector)
|
||||
config = SimpleNamespace(stage_input_payload_keys=("text_encoder_output",), stage_id=1, kv_transfer_config=object())
|
||||
monkeypatch.setattr(runner_module.OmniKVTransferManager, "from_od_config", lambda config: manager)
|
||||
monkeypatch.setattr(runner_module, "DiffusionKVModelRunnerBackend", Mock())
|
||||
runner = DiffusionModelRunner(SimpleNamespace(), config, torch.device("cpu"))
|
||||
runner._initialize_generator = Mock()
|
||||
request = _make_request({"prompt": "a cat"})
|
||||
request.sampling_params = SimpleNamespace()
|
||||
|
||||
runner._prepare_request_for_forward(request, od_config=config)
|
||||
|
||||
assert runner.kv_transfer_manager is None
|
||||
assert runner._kv_transfer_manager is manager
|
||||
assert runner._kv_connector is None
|
||||
assert not runner._kv_prefetch_enabled
|
||||
assert len(connector.calls) == 1
|
||||
assert "text_encoder_output" in request.prompt["additional_information"]
|
||||
runner._initialize_generator.assert_called_once_with(request.sampling_params)
|
||||
|
||||
|
||||
def test_step_mode_receives_payload_before_kv_and_reuses_cached_state():
|
||||
connector = _FakeConnector(_conditioning())
|
||||
runner = _make_runner(connector)
|
||||
runner.state_cache = {}
|
||||
request = _make_request({"prompt": "a cat"})
|
||||
request.sampling_params = SimpleNamespace()
|
||||
kv_calls = []
|
||||
|
||||
def receive_kv(state_request, **kwargs):
|
||||
assert "text_encoder_output" in state_request.prompt["additional_information"]
|
||||
kv_calls.append(state_request.request_id)
|
||||
|
||||
runner.kv_transfer_manager.receive_multi_kv_cache_distributed = receive_kv
|
||||
scheduled = SimpleNamespace(
|
||||
scheduled_new_reqs=[SimpleNamespace(request_id=request.request_id, req=request, diffusion_kv_metadata=None)],
|
||||
scheduled_cached_reqs=SimpleNamespace(request_ids=[]),
|
||||
)
|
||||
states, new_ids = runner._update_states(scheduled)
|
||||
assert new_ids == [request.request_id]
|
||||
assert states[0].prompt is request.prompt
|
||||
assert len(connector.calls) == 1
|
||||
assert kv_calls == [request.request_id]
|
||||
|
||||
scheduled.scheduled_new_reqs = []
|
||||
scheduled.scheduled_cached_reqs.request_ids = [request.request_id]
|
||||
cached_states, new_ids = runner._update_states(scheduled)
|
||||
assert cached_states == states
|
||||
assert new_ids == []
|
||||
assert len(connector.calls) == 1
|
||||
assert kv_calls == [request.request_id]
|
||||
|
||||
|
||||
def test_non_dict_prompt_is_left_alone():
|
||||
connector = _FakeConnector(_conditioning())
|
||||
runner = _make_runner(connector)
|
||||
req = _make_request("a cat")
|
||||
|
||||
runner._maybe_recv_stage_payload(req)
|
||||
|
||||
assert connector.calls == []
|
||||
assert req.prompt == "a cat"
|
||||
|
||||
|
||||
@pytest.mark.parametrize("request_id", ["dummy_req_id", "dummy_req_id/profile"])
|
||||
def test_warmup_never_receives_or_publishes_payload(request_id):
|
||||
connector = _FakeConnector(raises=True)
|
||||
request = _make_request({}, request_id=request_id)
|
||||
receiver = _make_runner(connector)
|
||||
receiver._maybe_recv_stage_payload(request)
|
||||
sender = _make_sender(connector)
|
||||
sender._maybe_send_stage_payload([request], [_make_output(prompt_embeds=torch.ones(1))])
|
||||
assert connector.calls == []
|
||||
assert connector.put_calls == []
|
||||
|
||||
|
||||
@pytest.mark.parametrize("inline", [{}, {"text_encoder_output": None}])
|
||||
def test_failed_transfer_requires_complete_inline_payload(inline):
|
||||
runner = _make_runner(_FakeConnector(raises=True))
|
||||
with pytest.raises(RuntimeError, match="missing keys.*text_encoder_output"):
|
||||
runner._maybe_recv_stage_payload(_make_request({"additional_information": inline}))
|
||||
|
||||
|
||||
def test_send_puts_declared_keys_and_attaches_a_handle():
|
||||
connector = _FakeConnector()
|
||||
runner = _make_sender(connector)
|
||||
req = _make_request({"prompt": "a cat"})
|
||||
output = _make_output(prompt_embeds=torch.zeros(2, 8), latents=torch.zeros(1, 4))
|
||||
|
||||
runner._maybe_send_stage_payload([req], [output])
|
||||
|
||||
from_stage, to_stage, put_key, data = connector.put_calls[0]
|
||||
assert (from_stage, to_stage, put_key) == ("0", "1", "req-7_0_0")
|
||||
# Only declared keys travel over the connector.
|
||||
assert isinstance(data, dict)
|
||||
assert set(data) == {"prompt_embeds"}
|
||||
handle = output.custom_output[HANDLE_KEY]
|
||||
assert handle["key"] == "req-7_0_0"
|
||||
assert handle["metadata"] == {"schema_version": 1}
|
||||
assert handle["payload_keys"] == ["prompt_embeds"]
|
||||
assert handle["size_bytes"] == 128
|
||||
# Transferred keys must not also travel inline through the orchestrator.
|
||||
assert "prompt_embeds" not in output.custom_output
|
||||
# Undeclared keys are untouched.
|
||||
assert "latents" in output.custom_output
|
||||
|
||||
|
||||
def test_send_key_matches_the_receive_key_convention():
|
||||
sender_connector = _FakeConnector()
|
||||
sender = _make_sender(sender_connector)
|
||||
req = _make_request({"prompt": "a cat"})
|
||||
sender._maybe_send_stage_payload([req], [_make_output(prompt_embeds=torch.zeros(2, 8))])
|
||||
|
||||
recv_connector = _FakeConnector(_conditioning())
|
||||
receiver = _make_runner(recv_connector)
|
||||
receiver._maybe_recv_stage_payload(_make_request({"prompt": "a cat"}))
|
||||
|
||||
assert sender_connector.put_calls[0][2] == recv_connector.calls[0][2]
|
||||
|
||||
|
||||
def test_stage_without_declared_output_keys_never_puts():
|
||||
connector = _FakeConnector()
|
||||
runner = _make_sender(connector, payload_keys=())
|
||||
output = _make_output(prompt_embeds=torch.zeros(2, 8))
|
||||
|
||||
runner._maybe_send_stage_payload([_make_request({"prompt": "a cat"})], [output])
|
||||
|
||||
assert connector.put_calls == []
|
||||
assert HANDLE_KEY not in output.custom_output
|
||||
|
||||
|
||||
def test_missing_outgoing_edge_is_reported_not_sent():
|
||||
connector = _FakeConnector()
|
||||
runner = _make_sender(connector, send_stages=(None, None))
|
||||
output = _make_output(prompt_embeds=torch.zeros(2, 8))
|
||||
|
||||
runner._maybe_send_stage_payload([_make_request({"prompt": "a cat"})], [output])
|
||||
|
||||
assert connector.put_calls == []
|
||||
assert HANDLE_KEY not in output.custom_output
|
||||
|
||||
|
||||
def test_output_without_the_declared_keys_is_skipped():
|
||||
connector = _FakeConnector()
|
||||
runner = _make_sender(connector)
|
||||
output = _make_output(latents=torch.zeros(1, 4))
|
||||
|
||||
runner._maybe_send_stage_payload([_make_request({"prompt": "a cat"})], [output])
|
||||
|
||||
assert connector.put_calls == []
|
||||
assert HANDLE_KEY not in output.custom_output
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"connector",
|
||||
[
|
||||
_FakeConnector(raises=True),
|
||||
_FakeConnector(put_result=(False, 0, None)),
|
||||
],
|
||||
ids=["raises", "rejected"],
|
||||
)
|
||||
def test_failed_send_leaves_the_inline_payload_unannotated(connector):
|
||||
runner = _make_sender(connector)
|
||||
output = _make_output(prompt_embeds=torch.zeros(2, 8))
|
||||
|
||||
runner._maybe_send_stage_payload([_make_request({"prompt": "a cat"})], [output])
|
||||
|
||||
assert HANDLE_KEY not in output.custom_output
|
||||
assert "prompt_embeds" in output.custom_output
|
||||
|
||||
|
||||
class _FakeTPGroup:
|
||||
def __init__(self, rank_in_group, world_size=2):
|
||||
self.rank_in_group = rank_in_group
|
||||
self.world_size = world_size
|
||||
self.broadcast_calls: list[object] = []
|
||||
self.leader_packet: object = None
|
||||
|
||||
def broadcast_object(self, obj, src=0):
|
||||
self.broadcast_calls.append(obj)
|
||||
return obj if self.rank_in_group == src else self.leader_packet
|
||||
|
||||
|
||||
@pytest.mark.parametrize("rank_in_group", [0, 1], ids=["leader", "follower"])
|
||||
def test_send_puts_only_on_the_tp_leader(monkeypatch, rank_in_group):
|
||||
connector = _FakeConnector()
|
||||
runner = _make_sender(connector)
|
||||
tp_group = _FakeTPGroup(rank_in_group)
|
||||
expected_handle = {
|
||||
"key": "req-7_0_0",
|
||||
"from_stage": "0",
|
||||
"to_stage": "1",
|
||||
"size_bytes": 128,
|
||||
"metadata": {"schema_version": 1},
|
||||
"payload_keys": ["prompt_embeds"],
|
||||
}
|
||||
tp_group.leader_packet = {"req-7": expected_handle}
|
||||
monkeypatch.setattr(DiffusionModelRunner, "_get_local_tp_group", staticmethod(lambda: tp_group))
|
||||
output = _make_output(prompt_embeds=torch.zeros(2, 8))
|
||||
|
||||
runner._maybe_send_stage_payload([_make_request({"prompt": "a cat"})], [output])
|
||||
|
||||
assert len(connector.put_calls) == (1 if rank_in_group == 0 else 0)
|
||||
# Every rank ends up reporting the same handle, leader or not.
|
||||
assert output.custom_output[HANDLE_KEY] == expected_handle
|
||||
# ...and every rank drops the inline copy, not just the sender.
|
||||
assert "prompt_embeds" not in output.custom_output
|
||||
assert len(tp_group.broadcast_calls) == 1
|
||||
|
||||
|
||||
@pytest.mark.parametrize("tp_size", [1, 2])
|
||||
@pytest.mark.parametrize("accepted", [True, False])
|
||||
def test_send_elects_one_tp_sp_leader(monkeypatch, tp_size, accepted):
|
||||
from vllm_omni.diffusion.distributed import parallel_state
|
||||
|
||||
connector = _FakeConnector(put_result=(accepted, 128, {"schema_version": 1}))
|
||||
packets = {}
|
||||
outputs = []
|
||||
|
||||
class GridGroup:
|
||||
def __init__(self, dimension, peer_rank, rank, world_size):
|
||||
self.key = (dimension, peer_rank)
|
||||
self.rank_in_group = rank
|
||||
self.world_size = world_size
|
||||
|
||||
def broadcast_object(self, value, src=0):
|
||||
if self.rank_in_group == src:
|
||||
packets[self.key] = value
|
||||
return packets[self.key]
|
||||
|
||||
for sp_rank in range(2):
|
||||
for tp_rank in range(tp_size):
|
||||
runner = _make_sender(connector)
|
||||
tp_group = GridGroup("tp", sp_rank, tp_rank, tp_size)
|
||||
sp_group = GridGroup("sp", tp_rank, sp_rank, 2)
|
||||
monkeypatch.setattr(runner, "_get_local_tp_group", lambda: tp_group)
|
||||
monkeypatch.setattr(parallel_state, "get_sp_group", lambda: sp_group)
|
||||
output = _make_output(prompt_embeds=torch.zeros(2, 8))
|
||||
|
||||
runner._maybe_send_stage_payload([_make_request({})], [output])
|
||||
|
||||
outputs.append(output.custom_output)
|
||||
assert (HANDLE_KEY in output.custom_output) == accepted
|
||||
assert ("prompt_embeds" in output.custom_output) != accepted
|
||||
|
||||
assert len(connector.put_calls) == 1
|
||||
if accepted:
|
||||
assert all(output[HANDLE_KEY] == outputs[0][HANDLE_KEY] for output in outputs)
|
||||
@@ -616,7 +616,8 @@ def test_make_batch_explicit_mapping_still_selects_and_orders_states():
|
||||
|
||||
|
||||
@pytest.mark.cpu
|
||||
def test_step_profiler_reports_denoise_step_as_diffuse():
|
||||
def test_step_profiler_reports_denoise_step_as_diffuse(monkeypatch):
|
||||
monkeypatch.setattr(current_omni_platform, "synchronize", lambda: None)
|
||||
pipeline = _AutoDenoiseProfilerPipeline()
|
||||
|
||||
assert pipeline.denoise_step() == "ok"
|
||||
@@ -629,6 +630,13 @@ def test_step_profiler_reports_denoise_step_as_diffuse():
|
||||
class TestRunner:
|
||||
"""DiffusionModelRunner.execute_stepwise"""
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def mock_platform_memory(self, monkeypatch):
|
||||
monkeypatch.setattr(model_runner_module.current_omni_platform, "is_available", lambda: True)
|
||||
monkeypatch.setattr(model_runner_module.current_omni_platform, "reset_peak_memory_stats", lambda: None)
|
||||
monkeypatch.setattr(model_runner_module.current_omni_platform, "max_memory_reserved", lambda: 0)
|
||||
monkeypatch.setattr(model_runner_module.current_omni_platform, "max_memory_allocated", lambda: 0)
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("diffusion_kv_mode", "should_cleanup"),
|
||||
[
|
||||
|
||||
@@ -87,6 +87,38 @@ async def test_inline_dispatch_request_success(client, mock_engine):
|
||||
assert output.request_id == "req-1"
|
||||
|
||||
|
||||
@pytest.mark.parametrize("streaming", [False, True])
|
||||
def test_inline_dispatch_preserves_payload_sender_info(client, mock_engine, streaming):
|
||||
async def _run_test():
|
||||
requests = []
|
||||
|
||||
async def _step_streaming(request):
|
||||
requests.append(request)
|
||||
yield [OmniRequestOutput.from_diffusion(request_id=request.request_id, images=[MagicMock()])]
|
||||
|
||||
mock_engine.step_streaming = _step_streaming
|
||||
client.od_config.streaming_output = streaming
|
||||
payload_sender_info = {"host": "10.0.0.1", "zmq_port": 50071}
|
||||
kv_transfer_params = {"remote_engine_id": "mooncake-producer", "remote_block_ids": [1, 2]}
|
||||
await client.add_request_async(
|
||||
"req-payload",
|
||||
"A test prompt",
|
||||
OmniDiffusionSamplingParams(),
|
||||
kv_transfer_params=kv_transfer_params,
|
||||
payload_sender_info=payload_sender_info,
|
||||
)
|
||||
|
||||
for _ in range(10):
|
||||
if requests:
|
||||
break
|
||||
await asyncio.sleep(0.01)
|
||||
|
||||
assert requests[0].payload_sender_info == payload_sender_info
|
||||
assert requests[0].kv_transfer_params == kv_transfer_params
|
||||
|
||||
asyncio.run(_run_test())
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_inline_non_streaming_dispatches_lifecycle_before_final(client, mock_engine):
|
||||
lifecycle = OmniRequestOutput.from_diffusion(
|
||||
|
||||
@@ -0,0 +1,68 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
|
||||
|
||||
import asyncio
|
||||
from unittest.mock import MagicMock
|
||||
|
||||
import pytest
|
||||
|
||||
from vllm_omni.diffusion.stage_diffusion_client import StageDiffusionClient
|
||||
from vllm_omni.diffusion.stage_diffusion_proc import StageDiffusionProc
|
||||
from vllm_omni.inputs.data import OmniDiffusionSamplingParams
|
||||
from vllm_omni.outputs import OmniRequestOutput
|
||||
|
||||
pytestmark = [pytest.mark.core_model, pytest.mark.diffusion, pytest.mark.cpu]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("streaming", [False, True])
|
||||
def test_subprocess_client_and_worker_preserve_both_transfer_contracts(streaming):
|
||||
"""Exercise the IPC message and both process request builders without GPUs."""
|
||||
|
||||
async def run():
|
||||
client = object.__new__(StageDiffusionClient)
|
||||
client._engine_dead = False
|
||||
client.stage_id = 1
|
||||
client.replica_id = 0
|
||||
client._encoder = MagicMock()
|
||||
client._encoder.encode.side_effect = lambda message: message
|
||||
client._request_socket = MagicMock()
|
||||
kv_params = {"remote_engine_id": "mooncake-producer", "remote_block_ids": [1, 2]}
|
||||
payload_sender = {"host": "10.0.0.1", "zmq_port": 50071}
|
||||
kv_sender = {0: {"host": "10.0.0.2", "zmq_port": 50171}}
|
||||
# Keep main's existing fifth positional argument bound to native KV.
|
||||
await client.add_request_async(
|
||||
"req-both",
|
||||
"prompt",
|
||||
OmniDiffusionSamplingParams(),
|
||||
kv_sender,
|
||||
kv_params,
|
||||
payload_sender_info=payload_sender,
|
||||
)
|
||||
message = client._request_socket.send.call_args.args[0]
|
||||
assert message["kv_transfer_params"] == kv_params
|
||||
assert message["payload_sender_info"] == payload_sender
|
||||
captured = []
|
||||
|
||||
class Engine:
|
||||
async def step_streaming(self, request):
|
||||
captured.append(request)
|
||||
yield [OmniRequestOutput.from_diffusion(request_id=request.request_id, images=[])]
|
||||
|
||||
proc = object.__new__(StageDiffusionProc)
|
||||
proc._engine = Engine()
|
||||
args = (message["request_id"], message["prompt"], message["sampling_params"])
|
||||
transfer_args = {
|
||||
"kv_sender_info": kv_sender,
|
||||
"kv_transfer_params": kv_params,
|
||||
"payload_sender_info": message["payload_sender_info"],
|
||||
}
|
||||
if streaming:
|
||||
outputs = [output async for output in proc._process_streaming_request(*args, **transfer_args)]
|
||||
else:
|
||||
outputs = [await proc._process_request(*args, **transfer_args)]
|
||||
assert outputs[0].request_id == "req-both"
|
||||
assert captured[0].kv_transfer_params == kv_params
|
||||
assert captured[0].kv_sender_info == kv_sender
|
||||
assert captured[0].payload_sender_info == payload_sender
|
||||
|
||||
asyncio.run(run())
|
||||
@@ -12,10 +12,13 @@ This module tests the WorkerWrapperBase implementation:
|
||||
- Dynamic worker class extension
|
||||
"""
|
||||
|
||||
import gc
|
||||
import weakref
|
||||
from types import SimpleNamespace
|
||||
from typing import Any
|
||||
|
||||
import pytest
|
||||
import torch
|
||||
from pytest_mock import MockerFixture
|
||||
|
||||
from vllm_omni.diffusion.worker.diffusion_worker import (
|
||||
@@ -227,12 +230,13 @@ class TestWorkerWrapperBaseDelegation:
|
||||
wrapper.worker.shutdown.assert_called_once()
|
||||
assert result is None
|
||||
|
||||
def test_worker_shutdown_disables_offloader_before_distributed_teardown(self, mocker: MockerFixture):
|
||||
@pytest.mark.parametrize("native_kv", [False, True])
|
||||
def test_worker_shutdown_disables_offloader_before_distributed_teardown(self, mocker: MockerFixture, native_kv):
|
||||
events: list[str] = []
|
||||
offload_backend = mocker.Mock()
|
||||
offload_backend.disable.side_effect = lambda: events.append("offload")
|
||||
kv_manager = mocker.Mock()
|
||||
kv_manager.shutdown_prefetch.side_effect = lambda: events.append("kv")
|
||||
kv_manager.close.side_effect = lambda: events.append("kv")
|
||||
destroy = mocker.patch(
|
||||
"vllm_omni.diffusion.worker.diffusion_worker.destroy_distributed_env",
|
||||
side_effect=lambda: events.append("distributed"),
|
||||
@@ -240,14 +244,71 @@ class TestWorkerWrapperBaseDelegation:
|
||||
worker = DiffusionWorker.__new__(DiffusionWorker)
|
||||
worker.model_runner = SimpleNamespace(
|
||||
offload_backend=offload_backend,
|
||||
kv_transfer_manager=kv_manager,
|
||||
kv_transfer_manager=None if native_kv else kv_manager,
|
||||
_kv_transfer_manager=kv_manager,
|
||||
)
|
||||
|
||||
worker.shutdown()
|
||||
|
||||
assert events == ["offload", "kv", "distributed"]
|
||||
kv_manager.close.assert_called_once_with()
|
||||
destroy.assert_called_once_with()
|
||||
|
||||
@pytest.mark.parametrize("cleanup_fails", [False, True])
|
||||
def test_worker_shutdown_releases_model_references(self, mocker: MockerFixture, cleanup_fails):
|
||||
mocker.patch("vllm_omni.diffusion.worker.diffusion_worker.destroy_distributed_env")
|
||||
mocker.patch("vllm_omni.diffusion.worker.diffusion_worker.shutdown_kv_connector")
|
||||
offload_backend = mocker.Mock()
|
||||
if cleanup_fails:
|
||||
offload_backend.disable.side_effect = RuntimeError("offload cleanup failed")
|
||||
worker = DiffusionWorker.__new__(DiffusionWorker)
|
||||
weights = torch.ones(1)
|
||||
weights_ref = weakref.ref(weights)
|
||||
pipeline = SimpleNamespace(weights=weights)
|
||||
worker.model_runner = SimpleNamespace(
|
||||
pipeline=pipeline, offload_backend=offload_backend, kv_transfer_manager=None
|
||||
)
|
||||
worker.lora_manager = SimpleNamespace(pipeline=pipeline)
|
||||
worker._sleep_saved_buffers = {"buffer": weights}
|
||||
del weights, pipeline
|
||||
|
||||
if cleanup_fails:
|
||||
with pytest.raises(RuntimeError, match="offload cleanup failed"):
|
||||
worker.shutdown()
|
||||
else:
|
||||
worker.shutdown()
|
||||
gc.collect()
|
||||
|
||||
assert worker.model_runner is None
|
||||
assert worker.lora_manager is None
|
||||
assert worker._sleep_saved_buffers == {}
|
||||
assert weights_ref() is None
|
||||
|
||||
@pytest.mark.parametrize("owns_pool", [False, True])
|
||||
@pytest.mark.parametrize("cleanup_fails", [False, True])
|
||||
def test_worker_shutdown_releases_only_owned_sleep_pool(self, mocker: MockerFixture, owns_pool, cleanup_fails):
|
||||
destroy = mocker.patch("vllm_omni.diffusion.worker.diffusion_worker.destroy_distributed_env")
|
||||
shutdown_connector = mocker.patch("vllm_omni.diffusion.worker.diffusion_worker.shutdown_kv_connector")
|
||||
allocator_class = mocker.patch("vllm_omni.diffusion.worker.diffusion_worker._get_cumem_allocator_class")
|
||||
release = allocator_class.return_value.get_instance.return_value.release_pools
|
||||
if cleanup_fails:
|
||||
release.side_effect = RuntimeError("pool release failed")
|
||||
worker = DiffusionWorker.__new__(DiffusionWorker)
|
||||
worker.model_runner = None
|
||||
worker._owns_sleep_pool = owns_pool
|
||||
|
||||
if owns_pool and cleanup_fails:
|
||||
with pytest.raises(RuntimeError, match="pool release failed"):
|
||||
worker.shutdown()
|
||||
else:
|
||||
worker.shutdown()
|
||||
|
||||
assert release.call_count == int(owns_pool)
|
||||
shutdown_connector.assert_called_once_with()
|
||||
destroy.assert_called_once_with()
|
||||
if not cleanup_fails:
|
||||
assert not worker._owns_sleep_pool
|
||||
|
||||
|
||||
# -------------------------------------------------------------------------
|
||||
# Tests: execute_method
|
||||
@@ -507,6 +568,26 @@ class TestCustomPipelineWorkerExtension:
|
||||
# Verify re_init_pipeline was called with custom_pipeline_args
|
||||
mock_worker_instance.re_init_pipeline.assert_called_once_with(custom_args)
|
||||
|
||||
@pytest.mark.parametrize("cleanup_fails", [False, True])
|
||||
def test_custom_pipeline_initialization_failure_cleans_worker(
|
||||
self, mocker: MockerFixture, mock_od_config, cleanup_fails
|
||||
):
|
||||
worker = mocker.Mock()
|
||||
worker.re_init_pipeline.side_effect = RuntimeError("custom pipeline load failed")
|
||||
if cleanup_fails:
|
||||
worker.shutdown.side_effect = RuntimeError("cleanup failed")
|
||||
worker_class = mocker.Mock(return_value=worker)
|
||||
mocker.patch.object(WorkerWrapperBase, "_prepare_worker_class", return_value=worker_class)
|
||||
|
||||
with pytest.raises(RuntimeError, match="custom pipeline load failed"):
|
||||
WorkerWrapperBase(
|
||||
gpu_id=0,
|
||||
od_config=mock_od_config,
|
||||
custom_pipeline_args={"pipeline_class": "unused"},
|
||||
)
|
||||
|
||||
worker.shutdown.assert_called_once_with()
|
||||
|
||||
def test_custom_pipeline_with_explicit_extension(self, mocker: MockerFixture, mock_od_config):
|
||||
"""Test that explicit worker_extension_cls is preserved when custom_pipeline_args is provided."""
|
||||
|
||||
|
||||
@@ -205,6 +205,25 @@ def test_start_prefetch_sweeps_orphan():
|
||||
assert "rid-next" in receiver._prefetch_futures
|
||||
|
||||
|
||||
def test_manager_close_stops_prefetch_before_connector_and_is_idempotent():
|
||||
receiver = object.__new__(OmniKVTransferManager)
|
||||
events = []
|
||||
receiver.shutdown_prefetch = lambda: events.append("prefetch")
|
||||
receiver._connector = SimpleNamespace(close=lambda: events.append("connector"))
|
||||
receiver.close()
|
||||
receiver.close()
|
||||
assert events == ["prefetch", "connector", "prefetch"]
|
||||
assert receiver.connector is None
|
||||
|
||||
|
||||
def test_manager_close_does_not_initialize_unused_connector():
|
||||
receiver = object.__new__(OmniKVTransferManager)
|
||||
receiver.shutdown_prefetch = lambda: None
|
||||
receiver._connector = None
|
||||
receiver.close()
|
||||
assert receiver.connector is None
|
||||
|
||||
|
||||
def test_shutdown_prefetch_clears_state():
|
||||
sender, receiver, _ = _make_sender_receiver()
|
||||
_seed_payload(sender, "rid-sd")
|
||||
|
||||
@@ -132,6 +132,7 @@ def test_manager_receiver_does_not_bind_shared_producer_port(producer, need_recv
|
||||
"role": "receiver",
|
||||
"host": "127.0.0.1",
|
||||
"zmq_port": PORT,
|
||||
"metadata_query_timeout_ms": 5000,
|
||||
"backends": ["UCX"],
|
||||
},
|
||||
from_stage="0",
|
||||
@@ -280,14 +281,15 @@ def test_abandoned_claim_survives_close_and_late_completion(producer, consumer,
|
||||
consumer._notify_transfer_done("abandoned", claimed)
|
||||
assert not producer._pending
|
||||
assert not producer._agent.registered
|
||||
assert producer._listener_thread.is_alive()
|
||||
producer.close()
|
||||
producer._close_thread.join(timeout=2.0)
|
||||
assert not producer._close_thread.is_alive()
|
||||
assert producer._listener_thread is None
|
||||
assert not producer._agent.registered
|
||||
assert producer._closed
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def copying_native_agent(consumer, monkeypatch):
|
||||
def ownership_copying_agent(consumer, monkeypatch):
|
||||
"""Strict fake descriptors and actual CPU copies; not native NIXL evidence."""
|
||||
calls = []
|
||||
|
||||
@@ -320,7 +322,7 @@ def copying_native_agent(consumer, monkeypatch):
|
||||
|
||||
@pytest.mark.parametrize("case", ["empty", "all_empty", "mixed", "scalar", "structured_empty", "structured_mixed"])
|
||||
@pytest.mark.usefixtures("reliable_claim_queries")
|
||||
def test_zero_byte_leaves_roundtrip_without_native_descriptors(producer, consumer, copying_native_agent, case):
|
||||
def test_zero_byte_leaves_complete_source_claim(producer, consumer, ownership_copying_agent, case):
|
||||
empty = torch.empty((2, 0, 3), dtype=torch.float64)
|
||||
other = torch.empty((0,), dtype=torch.int64)
|
||||
scalar = torch.tensor(7)
|
||||
@@ -345,7 +347,7 @@ def test_zero_byte_leaves_roundtrip_without_native_descriptors(producer, consume
|
||||
torch.testing.assert_close(actual, payload, rtol=0, atol=0)
|
||||
assert size == received_size
|
||||
if case in ("empty", "all_empty"):
|
||||
assert not copying_native_agent
|
||||
assert not ownership_copying_agent
|
||||
assert not producer._pending and not producer._agent.registered
|
||||
assert not consumer._agent.registered
|
||||
|
||||
@@ -354,7 +356,7 @@ def test_zero_byte_leaves_roundtrip_without_native_descriptors(producer, consume
|
||||
@pytest.mark.parametrize("outcome", ["done", "error", "timeout", "unknown"])
|
||||
@pytest.mark.usefixtures("reliable_claim_queries")
|
||||
def test_read_ownership_through_terminal_and_deferred_paths(
|
||||
producer, consumer, copying_native_agent, monkeypatch, direct, outcome
|
||||
producer, consumer, ownership_copying_agent, monkeypatch, direct, outcome
|
||||
):
|
||||
import threading
|
||||
|
||||
@@ -411,6 +413,7 @@ class _FakeNixlAgent:
|
||||
self.registered = []
|
||||
|
||||
def get_reg_descs(self, regions, memory_type):
|
||||
assert regions and all(region[0] > 0 and region[1] > 0 for region in regions)
|
||||
return ("reg", tuple(regions), memory_type)
|
||||
|
||||
def register_memory(self, descs, backends=None):
|
||||
@@ -548,21 +551,150 @@ def test_source_endpoint_metadata_overrides_configured_sender(consumer, monkeypa
|
||||
assert queried == [("req-tp4-rank3", "10.0.0.3", PORT + 3 * 16)]
|
||||
|
||||
|
||||
def test_unknown_key_is_queried_once(producer, consumer, monkeypatch):
|
||||
@pytest.mark.parametrize("force_timeout", [False, True], ids=["real-query", "recv-timeout"])
|
||||
def test_unknown_key_is_queried_once(producer, consumer, monkeypatch, force_timeout):
|
||||
socket = consumer._get_req_socket(f"tcp://127.0.0.1:{PORT}")
|
||||
send_count = 0
|
||||
original_send = socket.send
|
||||
|
||||
def count_send(message):
|
||||
nonlocal send_count
|
||||
assert socket.getsockopt(zmq.RCVTIMEO) == 10
|
||||
assert socket.getsockopt(zmq.SNDTIMEO) == 10
|
||||
send_count += 1
|
||||
return original_send(message)
|
||||
|
||||
monkeypatch.setattr(socket, "send", count_send)
|
||||
if force_timeout:
|
||||
|
||||
def timeout_recv():
|
||||
raise zmq.Again()
|
||||
|
||||
monkeypatch.setattr(socket, "recv", timeout_recv)
|
||||
|
||||
assert consumer._resolve_metadata("never-published", None) is None
|
||||
assert send_count == 1
|
||||
assert socket.getsockopt(zmq.RCVTIMEO) == 10
|
||||
if force_timeout:
|
||||
assert socket.closed
|
||||
|
||||
|
||||
@pytest.mark.usefixtures("reliable_claim_queries")
|
||||
def test_deadline_get_retains_active_dma_then_releases(producer, consumer, ownership_copying_agent, monkeypatch):
|
||||
producer.put("0", "1", "deadline-read", torch.ones(2))
|
||||
consumer._stop_event.set()
|
||||
consumer._transfer_wakeup.set()
|
||||
consumer._transfer_thread.join(timeout=2)
|
||||
state = ["PROC"]
|
||||
monkeypatch.setattr(consumer._agent, "check_xfer_state", lambda handle: state[0])
|
||||
started = time.monotonic()
|
||||
assert consumer.get_with_deadline("0", "1", "deadline-read", deadline=started + 0.03) is None
|
||||
assert time.monotonic() - started < 0.5
|
||||
assert producer._pending["deadline-read"].claims
|
||||
assert producer._agent.registered
|
||||
assert consumer._agent.registered
|
||||
assert consumer._deferred_transfers
|
||||
state[0] = "DONE"
|
||||
consumer._reap_deferred_transfers()
|
||||
assert not producer._pending
|
||||
assert not producer._agent.registered
|
||||
assert not consumer._agent.registered
|
||||
assert not consumer._deferred_transfers
|
||||
|
||||
|
||||
def test_receive_deadline_overrides_dma_timeout(consumer, monkeypatch):
|
||||
monkeypatch.setattr(consumer._agent, "check_xfer_state", lambda handle: "PROC", raising=False)
|
||||
consumer._transfer_timeout_s = 300
|
||||
consumer._req_local.deadline = time.monotonic() + 0.02
|
||||
started = time.monotonic()
|
||||
try:
|
||||
with pytest.raises(TimeoutError):
|
||||
consumer._wait_for_transfer(1, "bounded")
|
||||
assert time.monotonic() - started < 0.5
|
||||
finally:
|
||||
consumer._req_local.deadline = None
|
||||
|
||||
|
||||
@pytest.mark.parametrize("closing", [False, True])
|
||||
def test_abandoned_metadata_query_recovers_same_claim_without_read(producer, consumer, monkeypatch, closing):
|
||||
from vllm_omni.distributed.omni_connectors.connectors.nixl_connector import _GET_META_MSG
|
||||
|
||||
consumer._stop_event.set()
|
||||
consumer._transfer_wakeup.set()
|
||||
consumer._transfer_thread.join(timeout=2)
|
||||
producer.put("0", "1", "abandoned-query", torch.ones(1))
|
||||
messages = []
|
||||
|
||||
def send(message):
|
||||
messages.append(message)
|
||||
|
||||
def receive():
|
||||
reply = producer._handle_handshake_message(messages[-1])
|
||||
if len(messages) == 1:
|
||||
raise zmq.Again()
|
||||
return reply
|
||||
|
||||
socket = types.SimpleNamespace(send=send, recv=receive)
|
||||
monkeypatch.setattr(consumer, "_get_req_socket", lambda *args: socket)
|
||||
monkeypatch.setattr(consumer, "_invalidate_req_socket", lambda *args: None)
|
||||
assert consumer.get_with_deadline("0", "1", "abandoned-query", deadline=time.monotonic() + 1) is None
|
||||
assert not consumer._abandoned_queries
|
||||
consumer.abandon_get("abandoned-query")
|
||||
claim = next(iter(producer._pending["abandoned-query"].claims))
|
||||
if closing:
|
||||
producer._closing = True
|
||||
consumer._reap_deferred_transfers()
|
||||
assert not consumer._abandoned_queries
|
||||
assert not producer._pending
|
||||
claims = [
|
||||
msgspec.msgpack.decode(message[len(_GET_META_MSG) :])["claim_id"]
|
||||
for message in messages
|
||||
if message.startswith(_GET_META_MSG)
|
||||
]
|
||||
assert claims == [claim, claim]
|
||||
|
||||
|
||||
def test_expired_ack_is_deferred_instead_of_raising(consumer):
|
||||
consumer._req_local.deadline = time.monotonic() - 1
|
||||
try:
|
||||
assert consumer._notify_transfer_done("expired", {"source_host": "127.0.0.1", "source_port": PORT}) is False
|
||||
finally:
|
||||
consumer._req_local.deadline = None
|
||||
|
||||
|
||||
@pytest.mark.parametrize("direct", [False, True])
|
||||
@pytest.mark.parametrize("lost_replies", [1, 3])
|
||||
def test_lost_metadata_reply_retry_releases_source(producer, consumer, monkeypatch, direct, lost_replies):
|
||||
_, _, metadata = producer.put("0", "1", "lost-reply", torch.ones(1))
|
||||
replies = []
|
||||
requests = []
|
||||
|
||||
def send(message):
|
||||
requests.append(message)
|
||||
replies.append(producer._handle_handshake_message(message))
|
||||
|
||||
def recv():
|
||||
reply = replies.pop(0)
|
||||
if len(requests) <= lost_replies:
|
||||
raise zmq.Again()
|
||||
return reply
|
||||
|
||||
socket = types.SimpleNamespace(send=send, recv=recv)
|
||||
monkeypatch.setattr(consumer, "_get_req_socket", lambda *args: socket)
|
||||
forwarded = metadata if direct else None
|
||||
for attempt in range(lost_replies):
|
||||
assert consumer._resolve_metadata("lost-reply", forwarded) is None
|
||||
resolved = consumer._resolve_metadata("lost-reply", forwarded)
|
||||
assert resolved is not None
|
||||
assert producer._pending["lost-reply"].claims == {resolved["claim_id"]}
|
||||
independent = consumer._resolve_metadata("lost-reply", forwarded)
|
||||
assert independent["claim_id"] != resolved["claim_id"]
|
||||
consumer._notify_transfer_done("lost-reply", resolved)
|
||||
consumer._notify_transfer_done("lost-reply", resolved)
|
||||
assert producer._pending["lost-reply"].claims == {independent["claim_id"]}
|
||||
consumer._notify_transfer_done("lost-reply", independent)
|
||||
assert producer._pending == {}
|
||||
assert producer._registered_descs == []
|
||||
assert consumer._req_local.claims == {}
|
||||
|
||||
|
||||
@pytest.mark.usefixtures("reliable_claim_queries")
|
||||
@@ -681,6 +813,77 @@ def test_deferred_transfer_releases_exactly_once_after_done(nixl_connector_cls):
|
||||
connector.close()
|
||||
|
||||
|
||||
@pytest.mark.parametrize("poll_raises", [False, True], ids=["stuck", "poll-error"])
|
||||
def test_close_returns_without_releasing_active_dma(nixl_connector_cls, poll_raises):
|
||||
import threading
|
||||
|
||||
from vllm_omni.distributed.omni_connectors.connectors.nixl_connector import (
|
||||
_RETAINED_PRODUCERS,
|
||||
_DeferredTransfer,
|
||||
)
|
||||
|
||||
connector = nixl_connector_cls({"role": "receiver"})
|
||||
released = []
|
||||
|
||||
def check_state(handle):
|
||||
if poll_raises:
|
||||
raise RuntimeError("device unavailable")
|
||||
return "PROC"
|
||||
|
||||
connector._agent.check_xfer_state = check_state
|
||||
connector._agent.release_xfer_handle = lambda handle: released.append(("handle", handle))
|
||||
connector._agent.release_dlist_handle = lambda handle: released.append(("dlist", handle))
|
||||
connector._agent.remove_remote_agent = lambda agent: released.append(("agent", agent))
|
||||
connector._agent.deregister_memory = lambda descs: released.append(("registration", descs))
|
||||
transfer = _DeferredTransfer(
|
||||
tensors=[torch.zeros(1)],
|
||||
registrations=["registration"],
|
||||
dlists=["local", "remote"],
|
||||
handles=["transfer"],
|
||||
remote_agent="producer",
|
||||
)
|
||||
connector._defer_transfer(transfer)
|
||||
closing = threading.Thread(target=connector.close, daemon=True)
|
||||
try:
|
||||
closing.start()
|
||||
closing.join(timeout=2.0)
|
||||
assert not closing.is_alive(), "close must not wait forever for DMA completion"
|
||||
assert released == []
|
||||
assert transfer in connector._deferred_transfers
|
||||
assert transfer.tensors
|
||||
assert connector._closing
|
||||
assert connector in _RETAINED_PRODUCERS
|
||||
assert connector.health()["status"] == "unhealthy"
|
||||
cleanup_thread = connector._close_thread
|
||||
assert cleanup_thread is not None
|
||||
connector.close()
|
||||
assert connector._close_thread is cleanup_thread
|
||||
connector._agent.check_xfer_state = lambda handle: "DONE"
|
||||
cleanup_thread.join(timeout=2.0)
|
||||
assert not cleanup_thread.is_alive()
|
||||
assert connector._closed
|
||||
assert not connector._deferred_transfers
|
||||
assert not transfer.tensors
|
||||
assert connector not in _RETAINED_PRODUCERS
|
||||
finally:
|
||||
connector._agent.check_xfer_state = lambda handle: "DONE"
|
||||
closing.join(timeout=2.0)
|
||||
connector.close()
|
||||
|
||||
assert released == [
|
||||
("handle", "transfer"),
|
||||
("dlist", "local"),
|
||||
("dlist", "remote"),
|
||||
("agent", "producer"),
|
||||
("registration", "registration"),
|
||||
]
|
||||
assert not connector._deferred_transfers
|
||||
assert not transfer.tensors
|
||||
assert connector not in _RETAINED_PRODUCERS
|
||||
connector.close()
|
||||
assert len(released) == 5
|
||||
|
||||
|
||||
def test_active_sibling_transfer_requires_deferred_ownership(nixl_connector_cls):
|
||||
connector = nixl_connector_cls({"role": "receiver"})
|
||||
connector._agent.check_xfer_state = lambda handle: {"failed": "ERR", "active": "PROC"}[handle]
|
||||
@@ -691,7 +894,8 @@ def test_active_sibling_transfer_requires_deferred_ownership(nixl_connector_cls)
|
||||
connector.close()
|
||||
|
||||
|
||||
def test_get_defers_complete_ownership_when_sibling_transfer_is_active(nixl_connector_cls):
|
||||
@pytest.mark.parametrize("with_empty", [False, True])
|
||||
def test_get_defers_complete_ownership_when_sibling_transfer_is_active(nixl_connector_cls, with_empty):
|
||||
connector = nixl_connector_cls({"role": "receiver"})
|
||||
connector._agent.add_remote_agent = lambda metadata: "producer"
|
||||
connector._agent.get_xfer_descs = lambda regions, memory_type: (regions, memory_type)
|
||||
@@ -719,6 +923,9 @@ def test_get_defers_complete_ownership_when_sibling_transfer_is_active(nixl_conn
|
||||
],
|
||||
"size": 8,
|
||||
}
|
||||
if with_empty:
|
||||
metadata["tensor_specs"].insert(1, {"shape": [2, 0, 3], "dtype": "torch.int64", "device": "cpu", "size": 0})
|
||||
metadata["descriptor_groups"][1]["tensor_indices"] = [2]
|
||||
|
||||
try:
|
||||
assert connector.get("0", "1", "req-active-sibling", metadata) is None
|
||||
@@ -729,7 +936,9 @@ def test_get_defers_complete_ownership_when_sibling_transfer_is_active(nixl_conn
|
||||
assert len(deferred.registrations) == 2
|
||||
assert len(deferred.dlists) == 4
|
||||
assert deferred.remote_agent == "producer"
|
||||
assert len(deferred.tensors) == 2
|
||||
assert len(deferred.tensors) == 2 + with_empty
|
||||
if with_empty:
|
||||
assert deferred.tensors[1].shape == (2, 0, 3)
|
||||
finally:
|
||||
connector._agent.check_xfer_state = lambda handle: "DONE"
|
||||
connector.close()
|
||||
@@ -893,3 +1102,198 @@ def test_receive_device_config_wins(nixl_connector_cls):
|
||||
assert connector._resolve_receive_device("cuda:3") == torch.device("cpu")
|
||||
finally:
|
||||
connector.close()
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def copying_native_agent(consumer, monkeypatch):
|
||||
"""Enforce native nonzero descriptors and copy only the submitted regions."""
|
||||
agent = consumer._agent
|
||||
calls = {"agents": [], "descs": [], "transfers": [], "released": []}
|
||||
|
||||
def add_remote(metadata):
|
||||
calls["agents"].append(metadata)
|
||||
return "producer"
|
||||
|
||||
def descriptors(regions, memory_type):
|
||||
assert regions and all(len(region) == 3 and region[0] > 0 and region[1] > 0 for region in regions)
|
||||
calls["descs"].append((regions, memory_type))
|
||||
return regions
|
||||
|
||||
def prepare(operation, local, local_ids, remote, remote_ids):
|
||||
assert operation == "READ"
|
||||
assert local_ids == remote_ids == list(range(len(local)))
|
||||
assert len(local) == len(remote)
|
||||
pairs = list(zip(local, remote, strict=True))
|
||||
for destination, source in pairs:
|
||||
assert destination[1] == source[1] > 0
|
||||
calls["transfers"].append(pairs)
|
||||
return pairs
|
||||
|
||||
def transfer(pairs):
|
||||
for destination, source in pairs:
|
||||
ctypes.memmove(destination[0], source[0], source[1])
|
||||
|
||||
monkeypatch.setattr(agent, "add_remote_agent", add_remote, raising=False)
|
||||
monkeypatch.setattr(agent, "get_xfer_descs", descriptors, raising=False)
|
||||
monkeypatch.setattr(agent, "prep_xfer_dlist", lambda agent, descs: descs, raising=False)
|
||||
monkeypatch.setattr(agent, "make_prepped_xfer", prepare, raising=False)
|
||||
monkeypatch.setattr(agent, "transfer", transfer, raising=False)
|
||||
monkeypatch.setattr(agent, "check_xfer_state", lambda handle: "DONE", raising=False)
|
||||
for method in ("release_xfer_handle", "release_dlist_handle", "remove_remote_agent"):
|
||||
monkeypatch.setattr(
|
||||
agent, method, lambda handle, method=method: calls["released"].append((method, handle)), raising=False
|
||||
)
|
||||
return calls
|
||||
|
||||
|
||||
@pytest.mark.parametrize("case", ["empty", "all_empty", "mixed", "scalar", "structured_empty", "structured_mixed"])
|
||||
@pytest.mark.usefixtures("reliable_claim_queries")
|
||||
def test_zero_byte_leaves_roundtrip_without_native_descriptors(
|
||||
producer, consumer, copying_native_agent, monkeypatch, case
|
||||
):
|
||||
empty = torch.empty((2, 0, 3), dtype=torch.float64)
|
||||
other_empty = torch.empty((0,), dtype=torch.int64)
|
||||
scalar = torch.tensor(7, dtype=torch.int64)
|
||||
vector = torch.arange(6, dtype=torch.float32).reshape(2, 3)
|
||||
payloads = {
|
||||
"empty": empty,
|
||||
"all_empty": [empty, other_empty],
|
||||
"mixed": [empty, scalar, other_empty, vector, empty],
|
||||
"scalar": scalar,
|
||||
"structured_empty": {"leaves": (empty, [other_empty]), "label": "empty slots"},
|
||||
"structured_mixed": {"leaves": (empty, [scalar, other_empty, vector, empty]), "label": "mixed slots"},
|
||||
}
|
||||
payload = payloads[case]
|
||||
# Simulate mixed source memory groups without requiring a GPU in unit tests.
|
||||
monkeypatch.setattr(producer, "_resolve_memory_type", lambda t: "VRAM" if t.dtype == torch.int64 else "DRAM")
|
||||
# Splitting the producer's DRAM group on receipt also exercises local IDs:
|
||||
# IDs are group-relative, whereas spec/skeleton indices remain global.
|
||||
monkeypatch.setattr(consumer, "_resolve_memory_type", lambda t: "VRAM" if t.dtype == torch.float32 else "DRAM")
|
||||
consumer._receive_device = torch.device("cpu")
|
||||
success, size, metadata = producer.put("0", "1", "req-empty-slots", payload)
|
||||
assert success
|
||||
tensors = producer._pending["req-empty-slots"].tensors
|
||||
specs = metadata["tensor_specs"]
|
||||
assert len(specs) == len(tensors)
|
||||
assert size == sum(t.numel() * t.element_size() for t in tensors)
|
||||
for tensor, spec in zip(tensors, specs, strict=True):
|
||||
assert spec["shape"] == list(tensor.shape)
|
||||
assert spec["dtype"] == str(tensor.dtype)
|
||||
assert spec["device"] == str(tensor.device)
|
||||
indices = [i for group in metadata["descriptor_groups"] for i in group["tensor_indices"]]
|
||||
assert sorted(indices) == [i for i, tensor in enumerate(tensors) if tensor.numel()]
|
||||
# Verify receiver override applies to empty specs too, without trusting a
|
||||
# producer's device index. Real CUDA placement is covered by the native suite.
|
||||
for spec in specs:
|
||||
if spec["size"] == 0:
|
||||
spec["device"] = "cuda:7"
|
||||
received = consumer.get("0", "1", "req-empty-slots", metadata)
|
||||
assert received is not None
|
||||
actual, received_size = received
|
||||
assert received_size == size
|
||||
if isinstance(payload, dict):
|
||||
assert actual.keys() == payload.keys()
|
||||
assert actual["label"] == payload["label"]
|
||||
assert isinstance(actual["leaves"], tuple)
|
||||
assert isinstance(actual["leaves"][1], list)
|
||||
torch.testing.assert_close(actual["leaves"], payload["leaves"], rtol=0, atol=0)
|
||||
else:
|
||||
torch.testing.assert_close(actual, payload, rtol=0, atol=0)
|
||||
calls = copying_native_agent
|
||||
assert sum(len(pairs) for pairs in calls["transfers"]) == len(indices)
|
||||
if case in ("empty", "all_empty"):
|
||||
assert metadata["descriptor_groups"] == []
|
||||
assert calls == {"agents": [], "descs": [], "transfers": [], "released": []}
|
||||
assert size == 0
|
||||
else:
|
||||
assert len(calls["agents"]) == 1
|
||||
assert len(calls["released"]) == 3 * len(calls["transfers"]) + 1
|
||||
assert producer._pending == producer._published == {}
|
||||
assert producer._registered_descs == producer._agent.registered == []
|
||||
assert consumer._agent.registered == consumer._remote_agents == consumer._deferred_transfers == []
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"defect",
|
||||
[
|
||||
"missing_groups",
|
||||
"missing_nonempty",
|
||||
"duplicate",
|
||||
"empty_index",
|
||||
"zero_region",
|
||||
"wrong_region_size",
|
||||
"null_pointer",
|
||||
"negative_device",
|
||||
"short_region",
|
||||
"bad_region_type",
|
||||
"bool_index",
|
||||
"float_index",
|
||||
"empty_group",
|
||||
"unequal_lengths",
|
||||
"missing_memory_type",
|
||||
"fake_empty_size",
|
||||
"fake_nonempty_size",
|
||||
"negative_shape",
|
||||
"float_shape",
|
||||
"bad_dtype",
|
||||
"bad_spec",
|
||||
],
|
||||
)
|
||||
@pytest.mark.usefixtures("reliable_claim_queries")
|
||||
def test_invalid_empty_tensor_metadata_rejected_before_native_calls(producer, consumer, copying_native_agent, defect):
|
||||
success, _, metadata = producer.put(
|
||||
"0", "1", "req-invalid-empty", [torch.empty((0, 2)), torch.tensor(3.0), torch.empty((1, 0))]
|
||||
)
|
||||
assert success
|
||||
group = metadata["descriptor_groups"][0]
|
||||
region = group["regions"][0]
|
||||
if defect == "missing_groups":
|
||||
metadata.pop("descriptor_groups")
|
||||
elif defect == "missing_nonempty":
|
||||
metadata["descriptor_groups"] = []
|
||||
elif defect == "duplicate":
|
||||
group["tensor_indices"] *= 2
|
||||
group["regions"] *= 2
|
||||
elif defect == "empty_index":
|
||||
group["tensor_indices"] = [0]
|
||||
elif defect in ("zero_region", "wrong_region_size"):
|
||||
group["regions"] = [(region[0], 0 if defect == "zero_region" else 8, 0, "")]
|
||||
elif defect == "null_pointer":
|
||||
group["regions"] = [(0, 4, 0, "")]
|
||||
elif defect == "negative_device":
|
||||
group["regions"] = [(region[0], 4, -1, "")]
|
||||
elif defect == "short_region":
|
||||
group["regions"] = [(region[0], 4)]
|
||||
elif defect == "bad_region_type":
|
||||
group["regions"] = [None]
|
||||
elif defect in ("bool_index", "float_index"):
|
||||
group["tensor_indices"] = [True if defect == "bool_index" else 1.0]
|
||||
elif defect == "empty_group":
|
||||
metadata["descriptor_groups"].append({"memory_type": "DRAM", "tensor_indices": [], "regions": []})
|
||||
elif defect == "unequal_lengths":
|
||||
group["regions"] = []
|
||||
elif defect == "missing_memory_type":
|
||||
group.pop("memory_type")
|
||||
elif defect == "fake_empty_size":
|
||||
metadata["tensor_specs"][1]["size"] = 0
|
||||
metadata["descriptor_groups"] = []
|
||||
elif defect == "fake_nonempty_size":
|
||||
metadata["tensor_specs"][0]["size"] = 4
|
||||
elif defect == "negative_shape":
|
||||
metadata["tensor_specs"][0]["shape"] = [-1, 0]
|
||||
elif defect == "float_shape":
|
||||
metadata["tensor_specs"][0]["shape"] = [0.0, 2]
|
||||
elif defect == "bad_dtype":
|
||||
metadata["tensor_specs"][0]["dtype"] = "torch.not_a_dtype"
|
||||
elif defect == "bad_spec":
|
||||
metadata["tensor_specs"][0] = None
|
||||
assert consumer.get("0", "1", "req-invalid-empty", metadata) is None
|
||||
assert copying_native_agent == {"agents": [], "descs": [], "transfers": [], "released": []}
|
||||
assert consumer._agent.registered == []
|
||||
# Metadata acquisition now claims the source before validation. With no
|
||||
# submitted DMA, failure safely completes that claim instead of leaking it;
|
||||
# it must still report no successful payload receive.
|
||||
assert producer._pending == producer._published == {}
|
||||
assert producer._registered_descs == producer._agent.registered == []
|
||||
assert consumer._metrics["gets"] == 0
|
||||
assert consumer._metrics["errors"] == 1
|
||||
@@ -4,12 +4,13 @@
|
||||
import multiprocessing as mp
|
||||
import socket
|
||||
import time
|
||||
from dataclasses import fields
|
||||
from typing import Any
|
||||
|
||||
import pytest
|
||||
import torch
|
||||
|
||||
from vllm_omni.data_entry_keys import HiddenStatesStruct, MetaStruct, OmniPayloadStruct
|
||||
from vllm_omni.data_entry_keys import EmbeddingsStruct, HiddenStatesStruct, MetaStruct, OmniPayloadStruct
|
||||
from vllm_omni.platforms import current_omni_platform
|
||||
|
||||
pytestmark = [pytest.mark.core_model, pytest.mark.cuda, pytest.mark.parallel]
|
||||
@@ -29,7 +30,83 @@ def _free_port() -> int:
|
||||
return int(sock.getsockname()[1])
|
||||
|
||||
|
||||
def _producer(port: int, ready: Any, consumed: Any, result: Any, claimed: Any, proceed: Any, wire: Any) -> None:
|
||||
def _h3_conditioning(payload_kind: str, device: str = "cpu"):
|
||||
from vllm_omni.model_executor.models.minimax_h3.conditioning import MiniMaxH3EncoderConditioning
|
||||
|
||||
media = {}
|
||||
if payload_kind == "h3_ref2va":
|
||||
media = {
|
||||
"visual_condition": torch.arange(5 * 96, dtype=torch.float32).reshape(5, 96) / 8,
|
||||
"visual_condition_shapes": ((1, 2, 2), (2, 2, 4)),
|
||||
"audio_condition": torch.arange(10 * 32, dtype=torch.float32, device=device).reshape(10, 32) / 16,
|
||||
"audio_condition_lengths": (2, 3),
|
||||
"ref_blocks": (
|
||||
{"kind": "image", "latent_t": 1, "latent_h": 2, "latent_w": 2},
|
||||
{"kind": "video_audio", "ref_audio_t": 3, "latent_t": 2, "latent_h": 2, "latent_w": 4},
|
||||
),
|
||||
}
|
||||
elif payload_kind == "h3_fl2va":
|
||||
media = {
|
||||
"visual_condition": torch.arange(2 * 96, dtype=torch.float32).reshape(2, 96) / 8,
|
||||
"visual_condition_shapes": ((1, 2, 2), (1, 2, 2)),
|
||||
"keyframe_frame_indices": (0, 16),
|
||||
}
|
||||
return MiniMaxH3EncoderConditioning(
|
||||
hidden_states=(torch.arange(3 * 5120, device=device).reshape(3, 5120) % 127).to(torch.bfloat16),
|
||||
token_tags=torch.tensor([1, 0, 1], dtype=torch.int64),
|
||||
task=payload_kind.removeprefix("h3_"),
|
||||
height=256,
|
||||
width=448,
|
||||
num_frames=17,
|
||||
latent_t=5,
|
||||
audio_t=10,
|
||||
**media,
|
||||
)
|
||||
|
||||
|
||||
def _h3_structured_payload(payload_kind: str) -> OmniPayloadStruct:
|
||||
# Only adapt to the existing public Struct; NIXL owns all serialization.
|
||||
wire = _h3_conditioning(payload_kind, "cuda:0").to_omni_payload()
|
||||
# Exercise both CPU and CUDA empty leaves (T2VA has two empty slots).
|
||||
wire["embed"]["speech_feat"] = wire["embed"]["speech_feat"].to("cuda:0")
|
||||
return OmniPayloadStruct(
|
||||
hidden_states=HiddenStatesStruct(**wire["hidden_states"]),
|
||||
meta=MetaStruct(**wire["meta"]),
|
||||
embed=EmbeddingsStruct(**wire["embed"]),
|
||||
kv_metadata=wire["kv_metadata"],
|
||||
request_id="native-smoke",
|
||||
)
|
||||
|
||||
|
||||
def _assert_h3_roundtrip(payload: dict[str, Any], payload_kind: str) -> tuple:
|
||||
from vllm_omni.model_executor.models.minimax_h3.conditioning import MiniMaxH3EncoderConditioning
|
||||
|
||||
expected = _h3_conditioning(payload_kind)
|
||||
expected_wire = expected.to_omni_payload()
|
||||
tensors = []
|
||||
for section, values in expected_wire.items():
|
||||
for key, reference in values.items():
|
||||
actual = payload[section][key]
|
||||
assert actual.device == torch.device("cuda:1"), (section, key, actual.device)
|
||||
# Exact values, shapes and dtypes, including empty wire slots and layout.
|
||||
torch.testing.assert_close(actual.cpu(), reference, rtol=0, atol=0)
|
||||
tensors.append((f"{section}.{key}", str(actual.dtype), list(actual.shape), str(actual.device)))
|
||||
actual = MiniMaxH3EncoderConditioning.from_omni_payload(payload)
|
||||
for field in fields(expected):
|
||||
reference = getattr(expected, field.name)
|
||||
value = getattr(actual, field.name)
|
||||
if isinstance(reference, torch.Tensor):
|
||||
assert value.device == torch.device("cuda:1"), field.name
|
||||
torch.testing.assert_close(value.cpu(), reference, rtol=0, atol=0)
|
||||
else:
|
||||
assert value == reference, field.name
|
||||
assert payload["request_id"] == "native-smoke"
|
||||
return (payload_kind, tensors)
|
||||
|
||||
|
||||
def _producer(
|
||||
port: int, ready: Any, consumed: Any, result: Any, claimed: Any, proceed: Any, wire: Any, payload_kind: str
|
||||
) -> None:
|
||||
from vllm_omni.distributed.omni_connectors.connectors.nixl_connector import NixlConnector
|
||||
|
||||
current_omni_platform.set_device(0)
|
||||
@@ -48,6 +125,8 @@ def _producer(port: int, ready: Any, consumed: Any, result: Any, claimed: Any, p
|
||||
kv_metadata={"empty": torch.empty((2, 0, 3), device="cuda:0")},
|
||||
request_id="native-smoke",
|
||||
)
|
||||
if payload_kind != "generic":
|
||||
payload = _h3_structured_payload(payload_kind)
|
||||
success, size, metadata = connector.put("0", "1", "native-smoke", payload)
|
||||
result.put(("put", success, size, metadata["kind"] if metadata else None))
|
||||
wire.put(metadata)
|
||||
@@ -76,7 +155,15 @@ def _producer(port: int, ready: Any, consumed: Any, result: Any, claimed: Any, p
|
||||
|
||||
|
||||
def _consumer(
|
||||
port: int, ready: Any, consumed: Any, result: Any, claimed: Any, proceed: Any, wire: Any, direct: bool
|
||||
port: int,
|
||||
ready: Any,
|
||||
consumed: Any,
|
||||
result: Any,
|
||||
claimed: Any,
|
||||
proceed: Any,
|
||||
wire: Any,
|
||||
direct: bool,
|
||||
payload_kind: str,
|
||||
) -> None:
|
||||
from vllm_omni.distributed.omni_connectors.kv_transfer_manager import (
|
||||
OmniKVCacheConfig,
|
||||
@@ -133,11 +220,15 @@ def _consumer(
|
||||
if received is None:
|
||||
raise TimeoutError("native NIXL transfer did not complete")
|
||||
payload, size = received
|
||||
result.put(("native_states", states))
|
||||
if payload_kind != "generic":
|
||||
result.put(("get", size, *_assert_h3_roundtrip(payload, payload_kind)))
|
||||
consumed.set()
|
||||
return
|
||||
hidden = payload["hidden_states"]["output"]
|
||||
token_roles = payload["meta"]["token_role_ids"]
|
||||
empty = payload["kv_metadata"]["empty"]
|
||||
assert empty.shape == (2, 0, 3) and str(empty.device) == "cuda:1"
|
||||
result.put(("native_states", states))
|
||||
result.put(
|
||||
(
|
||||
"get",
|
||||
@@ -161,8 +252,9 @@ def _consumer(
|
||||
|
||||
|
||||
@pytest.mark.skipif(not _native_nixl_available(), reason="requires NIXL and at least two CUDA devices")
|
||||
@pytest.mark.parametrize("payload_kind", ["generic", "h3_ref2va", "h3_fl2va", "h3_t2va"])
|
||||
@pytest.mark.parametrize("direct", [False, True])
|
||||
def test_native_two_process_structured_mixed_device_transfer(direct):
|
||||
def test_native_two_process_structured_mixed_device_transfer(direct, payload_kind):
|
||||
context = mp.get_context("spawn")
|
||||
ready = context.Event()
|
||||
consumed = context.Event()
|
||||
@@ -171,8 +263,12 @@ def test_native_two_process_structured_mixed_device_transfer(direct):
|
||||
wire = context.Queue()
|
||||
result = context.Queue()
|
||||
port = _free_port()
|
||||
producer = context.Process(target=_producer, args=(port, ready, consumed, result, claimed, proceed, wire))
|
||||
consumer = context.Process(target=_consumer, args=(port, ready, consumed, result, claimed, proceed, wire, direct))
|
||||
producer = context.Process(
|
||||
target=_producer, args=(port, ready, consumed, result, claimed, proceed, wire, payload_kind)
|
||||
)
|
||||
consumer = context.Process(
|
||||
target=_consumer, args=(port, ready, consumed, result, claimed, proceed, wire, direct, payload_kind)
|
||||
)
|
||||
|
||||
producer.start()
|
||||
consumer.start()
|
||||
@@ -180,8 +276,10 @@ def test_native_two_process_structured_mixed_device_transfer(direct):
|
||||
consumer.join(timeout=60)
|
||||
if producer.is_alive():
|
||||
producer.terminate()
|
||||
producer.join(timeout=10)
|
||||
if consumer.is_alive():
|
||||
consumer.terminate()
|
||||
consumer.join(timeout=10)
|
||||
|
||||
records = [result.get(timeout=5) for _ in range(5)]
|
||||
print("Native ownership records:", records)
|
||||
@@ -193,12 +291,17 @@ def test_native_two_process_structured_mixed_device_transfer(direct):
|
||||
assert records[0][3] == "structured"
|
||||
get_record = next(record for record in records if record[0] == "get")
|
||||
assert get_record[1] == records[0][2]
|
||||
assert get_record[2:6] == (
|
||||
list(range(8)),
|
||||
"torch.float32",
|
||||
[8],
|
||||
"cuda:1",
|
||||
)
|
||||
assert get_record[6:] == ([1, 2, 3], "torch.int64", [3], "cuda:1")
|
||||
if payload_kind == "generic":
|
||||
assert get_record[2:6] == (
|
||||
list(range(8)),
|
||||
"torch.float32",
|
||||
[8],
|
||||
"cuda:1",
|
||||
)
|
||||
assert get_record[6:] == ([1, 2, 3], "torch.int64", [3], "cuda:1")
|
||||
else:
|
||||
assert get_record[2] == payload_kind
|
||||
assert len(get_record[3]) == 5
|
||||
print(f"Native H3 exact wire/semantic roundtrip: {get_record}")
|
||||
assert next(record for record in records if record[0] == "cleanup") == ("cleanup", 0, 0)
|
||||
assert next(record for record in records if record[0] == "source_retained") == ("source_retained", 1)
|
||||
@@ -2,7 +2,9 @@
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""Unit tests for SharedMemoryConnector focusing on TP / CFG / metadata fallback."""
|
||||
|
||||
import fcntl
|
||||
import os
|
||||
import time
|
||||
|
||||
import pytest
|
||||
import torch
|
||||
@@ -25,6 +27,15 @@ def connector():
|
||||
|
||||
|
||||
class TestKeyBasedReadWrite:
|
||||
def test_deadline_receive_does_not_wait_for_writer_lock(self, connector):
|
||||
key = "deadline_locked_payload"
|
||||
connector.put("0", "1", key, {"value": 7})
|
||||
with open(f"/dev/shm/shm_{key}_lockfile.lock", "rb+") as lock_file:
|
||||
fcntl.flock(lock_file, fcntl.LOCK_EX)
|
||||
assert connector.get_with_deadline("0", "1", key, deadline=time.monotonic() + 1) is None
|
||||
assert connector.get_with_deadline("0", "1", key, deadline=time.monotonic() - 1) is None
|
||||
assert connector.get_with_deadline("0", "1", key, deadline=time.monotonic() + 1)[0] == {"value": 7}
|
||||
|
||||
def test_put_then_get_by_key(self, connector):
|
||||
data = {"hello": "world", "n": 42}
|
||||
ok, size, meta = connector.put("s0", "s1", "test_key_1", data)
|
||||
|
||||
@@ -5,7 +5,8 @@
|
||||
Online serving smoke for ``Wan-AI/Wan2.2-T2V-A14B-Diffusers`` (text-to-video via ``/v1/videos``).
|
||||
|
||||
Uses a single ``default`` ``OmniServerParams`` row via ``_get_diffusion_feature_cases`` (no extra
|
||||
``server_args``). Multi-variant / parallel coverage lives in ``test_wan22_expansion.py`` (L4).
|
||||
``server_args``), with explicit startup budgets for loading both experts from slow storage.
|
||||
Multi-variant / parallel coverage lives in ``test_wan22_expansion.py`` (L4).
|
||||
|
||||
From ``tests/``::
|
||||
|
||||
@@ -33,7 +34,7 @@ def _get_diffusion_feature_cases(model: str):
|
||||
"""Return a single default ``OmniServerParams`` row (no extra ``server_args``)."""
|
||||
return [
|
||||
pytest.param(
|
||||
OmniServerParams(model=model),
|
||||
OmniServerParams(model=model, init_timeout=1800, stage_init_timeout=1800, startup_timeout=2100),
|
||||
id="default",
|
||||
marks=SINGLE_CARD_FEATURE_MARKS,
|
||||
),
|
||||
|
||||
@@ -43,13 +43,16 @@ class _DummyDiffusionStage:
|
||||
self.engine_input_source = engine_input_source or [0]
|
||||
self.calls = []
|
||||
|
||||
async def add_request_async(self, request_id, prompt, sampling_params, kv_sender_info=None):
|
||||
async def add_request_async(
|
||||
self, request_id, prompt, sampling_params, kv_sender_info=None, payload_sender_info=None
|
||||
):
|
||||
self.calls.append(
|
||||
{
|
||||
"request_id": request_id,
|
||||
"prompt": prompt,
|
||||
"sampling_params": sampling_params,
|
||||
"kv_sender_info": kv_sender_info,
|
||||
"payload_sender_info": payload_sender_info,
|
||||
}
|
||||
)
|
||||
|
||||
@@ -154,6 +157,31 @@ def test_payload_sender_endpoint_matches_resolver_with_unequal_replicas(outgoing
|
||||
assert sender_info["zmq_port"] != consumer.extra["sender_zmq_port"]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("initialized", [False, True])
|
||||
def test_intermediate_payload_sender_ignores_incoming_kv_endpoint(initialized):
|
||||
client = object.__new__(StageEngineCoreClient)
|
||||
client.stage_id = 1
|
||||
client.replica_id = 3
|
||||
client.vllm_config = SimpleNamespace(
|
||||
model_config=SimpleNamespace(
|
||||
stage_connector_config={
|
||||
"name": "NixlConnector",
|
||||
"extra": {
|
||||
"role": "receiver",
|
||||
"host": "10.0.0.1",
|
||||
"zmq_port": 47000,
|
||||
"from_stage": 0,
|
||||
"outgoing": {"host": "10.0.0.2", "zmq_port": 48000, "from_stage": 1},
|
||||
},
|
||||
}
|
||||
)
|
||||
)
|
||||
client._omni_kv_config = {"connector_config": {"type": "NixlConnector", "role": "receiver", "zmq_port": 47100}}
|
||||
client._kv_sender_info = {"host": "10.0.0.1", "zmq_port": 47100} if initialized else None
|
||||
|
||||
assert client._build_payload_sender_info() == {"host": "10.0.0.2", "zmq_port": 51073}
|
||||
|
||||
|
||||
def test_stage_engine_core_client_builds_kv_sender_info_from_tcp_address():
|
||||
client = object.__new__(StageEngineCoreClient)
|
||||
client.stage_id = 0
|
||||
@@ -235,6 +263,90 @@ def test_stage_engine_core_client_preserves_explicit_loopback_sender_host():
|
||||
}
|
||||
|
||||
|
||||
def test_stage_engine_core_client_payload_sender_uses_unresolved_base_port():
|
||||
client = object.__new__(StageEngineCoreClient)
|
||||
client.stage_id = 0
|
||||
client.replica_id = 0
|
||||
client.client_addresses = {"input_address": "tcp://10.20.30.40:1234"}
|
||||
client.vllm_config = SimpleNamespace(
|
||||
model_config=SimpleNamespace(
|
||||
stage_connector_config={
|
||||
"name": "NixlConnector",
|
||||
"extra": {"role": "sender", "from_stage": 0, "zmq_port": 50171},
|
||||
},
|
||||
omni_kv_config={"connector_config": {"type": "NixlConnector", "role": "sender", "zmq_port": 50171}},
|
||||
)
|
||||
)
|
||||
client._omni_kv_config = client.vllm_config.model_config.omni_kv_config
|
||||
|
||||
assert client._build_payload_sender_info() == {
|
||||
"host": "10.20.30.40",
|
||||
"zmq_port": 50071,
|
||||
}
|
||||
|
||||
|
||||
def test_stage_engine_core_client_payload_sender_preserves_stage_port_without_kv_config():
|
||||
client = object.__new__(StageEngineCoreClient)
|
||||
client.stage_id = 0
|
||||
client.replica_id = 0
|
||||
client.client_addresses = {"input_address": "tcp://10.20.30.40:1234"}
|
||||
client.vllm_config = SimpleNamespace(
|
||||
model_config=SimpleNamespace(
|
||||
stage_connector_config={
|
||||
"name": "NixlConnector",
|
||||
"extra": {"role": "sender", "from_stage": 0, "zmq_port": 50071},
|
||||
},
|
||||
omni_kv_config=None,
|
||||
)
|
||||
)
|
||||
client._omni_kv_config = None
|
||||
|
||||
assert client._build_payload_sender_info() == {
|
||||
"host": "10.20.30.40",
|
||||
"zmq_port": 50071,
|
||||
}
|
||||
|
||||
|
||||
def test_stage_engine_core_client_payload_sender_falls_back_to_kv_connector_config():
|
||||
client = object.__new__(StageEngineCoreClient)
|
||||
client.stage_id = 0
|
||||
client.replica_id = 0
|
||||
client.client_addresses = {"input_address": "tcp://10.20.30.40:1234"}
|
||||
client.vllm_config = SimpleNamespace(
|
||||
model_config=SimpleNamespace(
|
||||
stage_connector_config=None,
|
||||
omni_kv_config={
|
||||
"connector_config": {
|
||||
"type": "NixlConnector",
|
||||
"role": "sender",
|
||||
"zmq_port": 50171,
|
||||
}
|
||||
},
|
||||
)
|
||||
)
|
||||
client._omni_kv_config = client.vllm_config.model_config.omni_kv_config
|
||||
|
||||
assert client._build_payload_sender_info() == {
|
||||
"host": "10.20.30.40",
|
||||
"zmq_port": 50071,
|
||||
}
|
||||
|
||||
|
||||
def test_stage_engine_core_client_payload_sender_falls_back_to_initialized_kv_sender():
|
||||
client = object.__new__(StageEngineCoreClient)
|
||||
client.stage_id = 0
|
||||
client.replica_id = 0
|
||||
client.client_addresses = {"input_address": "tcp://10.20.30.40:1234"}
|
||||
client.vllm_config = SimpleNamespace(model_config=SimpleNamespace(stage_connector_config=None))
|
||||
client._omni_kv_config = None
|
||||
client._kv_sender_info = {"host": "10.20.30.40", "zmq_port": 50171}
|
||||
|
||||
assert client._build_payload_sender_info() == {
|
||||
"host": "10.20.30.40",
|
||||
"zmq_port": 50071,
|
||||
}
|
||||
|
||||
|
||||
def test_forward_to_diffusion_attaches_kv_sender_info():
|
||||
orchestrator = object.__new__(Orchestrator)
|
||||
diffusion_stage = _DummyDiffusionStage(engine_input_source=[0])
|
||||
@@ -263,6 +375,36 @@ def test_forward_to_diffusion_attaches_kv_sender_info():
|
||||
assert req_state.stage_submit_ts[1] > 0
|
||||
|
||||
|
||||
def test_diffusion_resubmission_preserves_sender_endpoints():
|
||||
orchestrator = object.__new__(Orchestrator)
|
||||
diffusion_stage = _DummyDiffusionStage(engine_input_source=[0])
|
||||
sender_pool = _build_sender_pool(0, {"host": "10.0.0.2", "zmq_port": 50151})
|
||||
payload_endpoint = {"host": "10.0.0.2", "zmq_port": 50071}
|
||||
sender_pool.stage_client.get_payload_sender_info = lambda: payload_endpoint
|
||||
diffusion_pool = StagePool(1, diffusion_stage)
|
||||
orchestrator.num_stages = 2
|
||||
orchestrator.stage_pools = [sender_pool, diffusion_pool]
|
||||
orchestrator._cfg_tracker = CfgCompanionTracker()
|
||||
state = OrchestratorRequestState(
|
||||
request_id="streaming",
|
||||
prompt={"prompt": "hello"},
|
||||
sampling_params_list=[SamplingParams(max_tokens=4), OmniDiffusionSamplingParams()],
|
||||
final_stage_id=1,
|
||||
)
|
||||
output = SimpleNamespace(request_id="streaming", finished=True)
|
||||
|
||||
async def forward_twice():
|
||||
await orchestrator._forward_to_next_stage("streaming", 0, output, state)
|
||||
await orchestrator._forward_to_next_stage("streaming", 0, output, state)
|
||||
|
||||
asyncio.run(forward_twice())
|
||||
|
||||
assert len(diffusion_stage.calls) == 2
|
||||
for call in diffusion_stage.calls:
|
||||
assert call["kv_sender_info"] == {0: {"host": "10.0.0.2", "zmq_port": 50151}}
|
||||
assert call["payload_sender_info"] == payload_endpoint
|
||||
|
||||
|
||||
def test_forward_to_diffusion_uses_engine_input_source_for_kv_sender_info():
|
||||
orchestrator = object.__new__(Orchestrator)
|
||||
diffusion_stage = _DummyDiffusionStage(engine_input_source=[0])
|
||||
@@ -293,7 +435,7 @@ def test_forward_to_diffusion_uses_engine_input_source_for_kv_sender_info():
|
||||
def test_forward_to_diffusion_returns_terminal_error_for_empty_custom_inputs():
|
||||
orchestrator = object.__new__(Orchestrator)
|
||||
diffusion_stage = _DummyDiffusionStage(engine_input_source=[0])
|
||||
diffusion_stage.custom_process_input_func = lambda *_args, **_kwargs: []
|
||||
setattr(diffusion_stage, "custom_process_input_func", lambda *_args, **_kwargs: [])
|
||||
sender_pool = _build_sender_pool(0, {"host": "10.0.0.2", "zmq_port": 50151})
|
||||
diffusion_pool = StagePool(1, diffusion_stage)
|
||||
|
||||
|
||||
@@ -150,6 +150,7 @@ class OmniServerParams(NamedTuple):
|
||||
use_stage_cli: bool = False
|
||||
init_timeout: int | None = None
|
||||
stage_init_timeout: int | None = None # None: fixture supplies default (600 s)
|
||||
startup_timeout: int = SERVER_STARTUP_TIMEOUT_S
|
||||
|
||||
|
||||
class OmniServer:
|
||||
@@ -163,8 +164,10 @@ class OmniServer:
|
||||
port: int | None = None,
|
||||
env_dict: dict[str, str] | None = None,
|
||||
use_omni: bool = True,
|
||||
startup_timeout: int = SERVER_STARTUP_TIMEOUT_S,
|
||||
) -> None:
|
||||
cleanup_test_environment()
|
||||
self.startup_timeout = startup_timeout
|
||||
self.model = model
|
||||
args = list(serve_args)
|
||||
self.serve_args = args
|
||||
@@ -248,7 +251,7 @@ class OmniServer:
|
||||
cwd=_omni_subprocess_cwd(),
|
||||
)
|
||||
|
||||
max_wait = SERVER_STARTUP_TIMEOUT_S
|
||||
max_wait = self.startup_timeout
|
||||
# System clock corrections must not shorten or extend startup waits.
|
||||
start_time = time.monotonic()
|
||||
while time.monotonic() - start_time < max_wait:
|
||||
@@ -442,8 +445,11 @@ class OmniServerStageCli(OmniServer):
|
||||
stage_ids: list[int] | None = None,
|
||||
port: int | None = None,
|
||||
env_dict: dict[str, str] | None = None,
|
||||
startup_timeout: int = SERVER_STARTUP_TIMEOUT_S,
|
||||
) -> None:
|
||||
super().__init__(model, serve_args or [], port=port, env_dict=env_dict, use_omni=True)
|
||||
super().__init__(
|
||||
model, serve_args or [], port=port, env_dict=env_dict, use_omni=True, startup_timeout=startup_timeout
|
||||
)
|
||||
self.stage_config_path = stage_config_path
|
||||
self.master_port = get_open_port()
|
||||
resolved_cfg = resolve_deploy_yaml(stage_config_path)
|
||||
@@ -553,7 +559,7 @@ class OmniServerStageCli(OmniServer):
|
||||
for replica_id in range(self.stage_replica_counts.get(stage_id, 1)):
|
||||
self._launch_stage(stage_id, headless=True, replica_id=replica_id)
|
||||
|
||||
max_wait = SERVER_STARTUP_TIMEOUT_S
|
||||
max_wait = self.startup_timeout
|
||||
# System clock corrections must not shorten or extend startup waits.
|
||||
start_time = time.monotonic()
|
||||
while time.monotonic() - start_time < max_wait:
|
||||
@@ -1033,6 +1039,7 @@ def iter_omni_server(
|
||||
server_args,
|
||||
port=port,
|
||||
env_dict=params.env_dict,
|
||||
startup_timeout=params.startup_timeout,
|
||||
) as server:
|
||||
if model != original_model:
|
||||
server.model = original_model
|
||||
@@ -1050,6 +1057,7 @@ def iter_omni_server(
|
||||
port=port,
|
||||
env_dict=params.env_dict,
|
||||
use_omni=params.use_omni,
|
||||
startup_timeout=params.startup_timeout,
|
||||
)
|
||||
if port
|
||||
else OmniServer(
|
||||
@@ -1057,6 +1065,7 @@ def iter_omni_server(
|
||||
server_args,
|
||||
env_dict=params.env_dict,
|
||||
use_omni=params.use_omni,
|
||||
startup_timeout=params.startup_timeout,
|
||||
)
|
||||
) as server:
|
||||
if model != original_model:
|
||||
|
||||
@@ -38,7 +38,11 @@ def startup_server(request, tmp_path, monkeypatch):
|
||||
|
||||
@pytest.mark.parametrize("wall_clock_jump", [3600, -3600])
|
||||
@pytest.mark.parametrize("becomes_ready", [True, False], ids=["ready", "timeout"])
|
||||
def test_startup_deadline_ignores_wall_clock_changes(startup_server, monkeypatch, wall_clock_jump, becomes_ready):
|
||||
@pytest.mark.parametrize("startup_timeout", [runtime.SERVER_STARTUP_TIMEOUT_S, 2100])
|
||||
def test_startup_deadline_ignores_wall_clock_changes(
|
||||
startup_server, monkeypatch, wall_clock_jump, becomes_ready, startup_timeout
|
||||
):
|
||||
startup_server.startup_timeout = startup_timeout
|
||||
elapsed = 0.0
|
||||
wall_offset = 0.0
|
||||
first_probe_at = None
|
||||
@@ -66,7 +70,7 @@ def test_startup_deadline_ignores_wall_clock_changes(startup_server, monkeypatch
|
||||
if first_probe_at is None:
|
||||
first_probe_at = elapsed
|
||||
# Even a backwards clock correction must not extend the deadline.
|
||||
assert elapsed - first_probe_at < runtime.SERVER_STARTUP_TIMEOUT_S, "startup exceeded its elapsed-time budget"
|
||||
assert elapsed - first_probe_at < startup_timeout, "startup exceeded its elapsed-time budget"
|
||||
probes += 1
|
||||
if probes == 1:
|
||||
wall_offset += wall_clock_jump
|
||||
@@ -84,7 +88,7 @@ def test_startup_deadline_ignores_wall_clock_changes(startup_server, monkeypatch
|
||||
assert first_probe_at is not None
|
||||
assert elapsed - first_probe_at == 2
|
||||
else:
|
||||
with pytest.raises(RuntimeError, match=f"failed to start within {runtime.SERVER_STARTUP_TIMEOUT_S} seconds"):
|
||||
with pytest.raises(RuntimeError, match=f"failed to start within {startup_timeout} seconds"):
|
||||
startup_server._start_server()
|
||||
assert first_probe_at is not None
|
||||
assert elapsed - first_probe_at == runtime.SERVER_STARTUP_TIMEOUT_S
|
||||
assert elapsed - first_probe_at == startup_timeout
|
||||
@@ -91,8 +91,11 @@ def test_pipeline_owns_three_encoders_then_dit_and_decoders() -> None:
|
||||
|
||||
encoder, diffusion = MINIMAX_H3_PIPELINE.stages
|
||||
assert encoder.model_arch == "MiniMaxH3Encoder"
|
||||
assert encoder.custom_process_next_stage_input_func is None
|
||||
assert encoder.custom_process_next_stage_input_func == (
|
||||
"vllm_omni.model_executor.stage_input_processors.minimax_h3.encoder2diffusion_full_payload"
|
||||
)
|
||||
assert diffusion.model_arch == "MiniMaxH3Pipeline"
|
||||
assert diffusion.stage_input_payload_keys == ("encoder_output",)
|
||||
assert diffusion.requires_multimodal_data is False
|
||||
assert diffusion.requires_full_payload_input is False
|
||||
|
||||
@@ -441,7 +444,7 @@ def test_encode_media_keeps_audio_budgets_and_component_residency_separate(
|
||||
else:
|
||||
with pytest.raises(ValueError, match="at most 15 seconds"):
|
||||
encode_media(media, **kwargs)
|
||||
assert scopes == [video_vae, audio_vae]
|
||||
assert scopes == ([video_vae, audio_vae] if valid else [])
|
||||
|
||||
|
||||
def test_encoder_output_reuses_encoder_handoff_and_round_trips(monkeypatch) -> None:
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
|
||||
"""Regression tests for MiniMax H3's disaggregated text-encoder contract."""
|
||||
"""Regression tests for MiniMax H3's disaggregated encoder contract."""
|
||||
|
||||
from types import SimpleNamespace
|
||||
from unittest.mock import Mock
|
||||
@@ -10,7 +10,7 @@ import pytest
|
||||
import torch
|
||||
from PIL import Image
|
||||
|
||||
from vllm_omni.data_entry_keys import flatten_payload
|
||||
from vllm_omni.data_entry_keys import flatten_payload, to_struct
|
||||
from vllm_omni.diffusion.models.minimax_h3.pipeline_minimax_h3 import resolve_minimax_h3_diffusion_model_path
|
||||
from vllm_omni.engine.serialization import (
|
||||
deserialize_additional_information,
|
||||
@@ -24,8 +24,10 @@ from vllm_omni.model_executor.models.minimax_h3.checkpoint import (
|
||||
)
|
||||
from vllm_omni.model_executor.models.minimax_h3.conditioning import (
|
||||
MINIMAX_H3_CONDITION_LABELS_KEY,
|
||||
MINIMAX_H3_ENCODER_LAYOUT_KEY,
|
||||
MINIMAX_H3_ENCODER_REQUEST_KEY,
|
||||
MINIMAX_H3_PRESENTATION_TASK_KEY,
|
||||
MINIMAX_H3_TEXT_CONDITIONING_SCHEMA,
|
||||
MiniMaxH3EncoderConditioning,
|
||||
)
|
||||
from vllm_omni.model_executor.models.minimax_h3.encoder_processing import _audio_items, _load_audio
|
||||
@@ -40,6 +42,7 @@ from vllm_omni.model_executor.models.minimax_h3.text_encoder import (
|
||||
from vllm_omni.model_executor.stage_input_processors.minimax_h3 import (
|
||||
_diffusion_sampling_params,
|
||||
encoder2diffusion,
|
||||
encoder2diffusion_full_payload,
|
||||
prepare_encoder_prompt,
|
||||
)
|
||||
|
||||
@@ -208,7 +211,8 @@ def test_prepare_ref2va_rejects_short_embedded_video_audio(monkeypatch):
|
||||
prepare_encoder_prompt(prompt, [sampling])
|
||||
|
||||
|
||||
def test_prepare_ref2va_keeps_embedded_and_standalone_audio_budgets_separate(monkeypatch):
|
||||
@pytest.mark.parametrize("standalone_count", [1, 2])
|
||||
def test_prepare_ref2va_uses_separate_embedded_and_standalone_audio_budgets(monkeypatch, standalone_count):
|
||||
duration_seconds = 8.0
|
||||
sample_rate = 16_000
|
||||
_mock_ref2va_video_with_audio(monkeypatch, duration_seconds=duration_seconds)
|
||||
@@ -222,16 +226,21 @@ def test_prepare_ref2va_keeps_embedded_and_standalone_audio_budgets_separate(mon
|
||||
"prompt": "hello",
|
||||
"multi_modal_data": {
|
||||
"video": "original.mp4",
|
||||
"audio": (torch.zeros(int(duration_seconds * sample_rate)), sample_rate),
|
||||
"audio": [(torch.zeros(int(duration_seconds * sample_rate)), sample_rate) for _ in range(standalone_count)],
|
||||
},
|
||||
}
|
||||
|
||||
transformed = prepare_encoder_prompt(prompt, [sampling])
|
||||
assert transformed["mm_processor_kwargs"][MINIMAX_H3_CONDITION_LABELS_KEY] == [
|
||||
("audio", 1),
|
||||
("video", 1),
|
||||
("audio", 2),
|
||||
]
|
||||
if standalone_count == 2:
|
||||
with pytest.raises(OmniClientError, match="at most 15 seconds in total"):
|
||||
prepare_encoder_prompt(prompt, [sampling])
|
||||
else:
|
||||
transformed = prepare_encoder_prompt(prompt, [sampling])
|
||||
from vllm_omni.model_executor.models.minimax_h3.encoder import MiniMaxH3Encoder
|
||||
|
||||
media = MiniMaxH3Encoder._media_input(transformed["additional_information"])
|
||||
assert len(media.video_audios) == 1 and len(media.audios) == 1
|
||||
assert media.video_audios[0][0].shape[-1] == 8 * sample_rate
|
||||
assert media.audios[0][0].shape[-1] == 8 * sample_rate
|
||||
|
||||
|
||||
def _encoder_output() -> dict:
|
||||
@@ -283,6 +292,60 @@ def test_encoder2diffusion_waits_for_one_finished_source() -> None:
|
||||
encoder2diffusion([SimpleNamespace(), SimpleNamespace()], {"prompt": "hello"})
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("case", "message"),
|
||||
[
|
||||
("hidden_width", r"hidden_states must have shape \[tokens, 5120\]"),
|
||||
("hidden_dtype", "hidden_states must have dtype torch.bfloat16"),
|
||||
("hidden_noncontiguous", "hidden_states must use contiguous strided layout"),
|
||||
("hidden_non_strided", "hidden_states must use contiguous strided layout"),
|
||||
("token_dtype", "token_tags must have dtype torch.int64"),
|
||||
("token_layout", "token_tags must use contiguous strided layout"),
|
||||
("token_count", "token_tags must align with hidden_states"),
|
||||
("token_value", "token_tags must contain only 0 and 1"),
|
||||
],
|
||||
)
|
||||
@pytest.mark.parametrize("via_connector", [False, True])
|
||||
def test_encoder2diffusion_rejects_h3_v1_contract_mismatch(case: str, message: str, via_connector: bool) -> None:
|
||||
payload = _encoder_output()
|
||||
payload["hidden_states"]["output"] = torch.zeros(4, 5120, dtype=torch.bfloat16)
|
||||
payload["meta"]["token_role_ids"] = torch.tensor([[1], [1], [0], [0]], dtype=torch.int64)
|
||||
|
||||
if case == "hidden_width":
|
||||
payload["hidden_states"]["output"] = torch.zeros(4, 5119, dtype=torch.bfloat16)
|
||||
elif case == "hidden_dtype":
|
||||
payload["hidden_states"]["output"] = torch.zeros(4, 5120, dtype=torch.float32)
|
||||
elif case == "hidden_noncontiguous":
|
||||
payload["hidden_states"]["output"] = torch.empty(5120, 4, dtype=torch.bfloat16).t()
|
||||
elif case == "hidden_non_strided":
|
||||
payload["hidden_states"]["output"] = torch.empty(
|
||||
(4, 5120),
|
||||
dtype=torch.bfloat16,
|
||||
layout=torch.sparse_coo,
|
||||
)
|
||||
elif case == "token_dtype":
|
||||
payload["meta"]["token_role_ids"] = torch.tensor([[1], [1], [0], [0]], dtype=torch.int32)
|
||||
elif case == "token_layout":
|
||||
payload["meta"]["token_role_ids"] = torch.tensor(
|
||||
[[1], [0], [1], [0], [1], [0], [1], [0]],
|
||||
dtype=torch.int64,
|
||||
)[::2]
|
||||
elif case == "token_count":
|
||||
payload["meta"]["token_role_ids"] = torch.tensor([[1], [0], [0]], dtype=torch.int64)
|
||||
elif case == "token_value":
|
||||
payload["meta"]["token_role_ids"] = torch.tensor([[1], [1], [2], [0]], dtype=torch.int64)
|
||||
else: # pragma: no cover - parameterization is exhaustive
|
||||
raise AssertionError(f"unknown test case: {case}")
|
||||
|
||||
with pytest.raises(RuntimeError, match=message) as exc_info:
|
||||
if via_connector:
|
||||
encoder2diffusion_full_payload(pooling_output=payload)
|
||||
else:
|
||||
encoder2diffusion([_source_output(payload)], {"prompt": "hello"})
|
||||
|
||||
assert MINIMAX_H3_TEXT_CONDITIONING_SCHEMA in str(exc_info.value)
|
||||
|
||||
|
||||
def test_ref2va_one_image_tokens_and_tags_match_fused_presentation():
|
||||
tokenizer = _SegmentTokenizer()
|
||||
labels = [("image", 1), ("audio", 1)]
|
||||
@@ -393,3 +456,236 @@ def test_diffusion_resolver_normalizes_partial_partition_directory(tmp_path):
|
||||
(ref2va / "text_encoder").mkdir(parents=True)
|
||||
|
||||
assert resolve_minimax_h3_diffusion_model_path(str(ref2va), None, "ref2va") == str(ref2va)
|
||||
|
||||
|
||||
def _source_output(payload) -> SimpleNamespace:
|
||||
return SimpleNamespace(
|
||||
finished=True,
|
||||
request_id="request-1",
|
||||
outputs=[SimpleNamespace(multimodal_output=payload)],
|
||||
)
|
||||
|
||||
|
||||
def _assert_same_tensor_view(actual: torch.Tensor, expected: torch.Tensor) -> None:
|
||||
torch.testing.assert_close(actual, expected, rtol=0, atol=0, check_stride=True)
|
||||
assert actual.data_ptr() == expected.data_ptr()
|
||||
assert actual.untyped_storage().data_ptr() == expected.untyped_storage().data_ptr()
|
||||
|
||||
|
||||
def _full_encoder_output() -> dict:
|
||||
return MiniMaxH3EncoderConditioning(
|
||||
hidden_states=torch.randn(4, 5120, dtype=torch.bfloat16),
|
||||
token_tags=torch.tensor([1, 1, 0, 0], dtype=torch.int64),
|
||||
task="ref2va",
|
||||
height=256,
|
||||
width=448,
|
||||
num_frames=17,
|
||||
latent_t=5,
|
||||
audio_t=10,
|
||||
visual_condition=torch.arange(12 * 96, dtype=torch.float32).reshape(12, 96),
|
||||
visual_condition_shapes=((1, 4, 4), (2, 4, 4)),
|
||||
audio_condition=torch.arange(10 * 32, dtype=torch.float32).reshape(10, 32),
|
||||
audio_condition_lengths=(3, 2),
|
||||
ref_blocks=(
|
||||
{"kind": "image", "latent_t": 1, "latent_h": 4, "latent_w": 4},
|
||||
{"kind": "video_audio", "ref_audio_t": 3, "latent_t": 2, "latent_h": 4, "latent_w": 4},
|
||||
{"kind": "audio", "ref_audio_t": 2},
|
||||
),
|
||||
keyframe_frame_indices=(0, 16),
|
||||
).to_omni_payload()
|
||||
|
||||
|
||||
def _runner_payload(payload: dict) -> dict:
|
||||
# Encoder.make_omni_output emits dotted private layout metadata. The runner
|
||||
# selects each request's media tensors and flattens its nested categories.
|
||||
payload = dict(payload)
|
||||
payload[f"kv_metadata.{MINIMAX_H3_ENCODER_LAYOUT_KEY}"] = payload.pop("kv_metadata")[MINIMAX_H3_ENCODER_LAYOUT_KEY]
|
||||
payload["meta"] = {"token_role_ids": payload["meta"]["token_role_ids"].reshape(-1, 1)}
|
||||
return flatten_payload(payload)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("representation", ["nested", "struct", "flat", "runner"])
|
||||
@pytest.mark.parametrize("with_media", [False, True])
|
||||
@pytest.mark.parametrize("via_connector", [False, True])
|
||||
def test_encoder_handoff_preserves_all_components(representation, with_media, via_connector):
|
||||
payload = _full_encoder_output() if with_media else _encoder_output()
|
||||
inputs = {
|
||||
"nested": payload,
|
||||
"struct": to_struct(payload),
|
||||
"flat": flatten_payload(payload),
|
||||
"runner": _runner_payload(payload),
|
||||
}
|
||||
if via_connector:
|
||||
result = encoder2diffusion_full_payload(pooling_output=inputs[representation], request_id="request-1")
|
||||
assert set(result) == {"encoder_output"}
|
||||
else:
|
||||
result = encoder2diffusion([_source_output(inputs[representation])], {"prompt": "hello"})[
|
||||
"additional_information"
|
||||
]
|
||||
output = result["encoder_output"]
|
||||
for group in ("hidden_states", "embed", "meta", "kv_metadata"):
|
||||
for key, tensor in payload[group].items():
|
||||
torch.testing.assert_close(output[group][key], tensor, rtol=0, atol=0)
|
||||
# Nonempty tensors must not be stripped, copied to CPU, or coerced to a
|
||||
# different dtype by the adapter. Empty FP32 optional slots remain on wire.
|
||||
assert output["hidden_states"]["output"] is payload["hidden_states"]["output"]
|
||||
if with_media:
|
||||
for key in ("embedding", "speech_feat"):
|
||||
_assert_same_tensor_view(output["embed"][key], payload["embed"][key])
|
||||
else:
|
||||
for tensor in output["embed"].values():
|
||||
assert tensor.shape == (0,)
|
||||
assert tensor.dtype == torch.float32
|
||||
for _ in range(2):
|
||||
result = deserialize_additional_information(serialize_additional_information(result))
|
||||
restored = MiniMaxH3EncoderConditioning.from_omni_payload(result["encoder_output"])
|
||||
original = MiniMaxH3EncoderConditioning.from_omni_payload(payload)
|
||||
for name in (
|
||||
"task",
|
||||
"height",
|
||||
"width",
|
||||
"num_frames",
|
||||
"latent_t",
|
||||
"audio_t",
|
||||
"visual_condition_shapes",
|
||||
"audio_condition_lengths",
|
||||
"ref_blocks",
|
||||
"keyframe_frame_indices",
|
||||
):
|
||||
assert getattr(restored, name) == getattr(original, name)
|
||||
for group, fields in output.items():
|
||||
for key, tensor in fields.items():
|
||||
torch.testing.assert_close(result["encoder_output"][group][key], tensor, rtol=0, atol=0)
|
||||
|
||||
|
||||
def test_full_payload_hook_skips_only_absent_output():
|
||||
assert encoder2diffusion_full_payload(pooling_output=None) is None
|
||||
|
||||
|
||||
@pytest.mark.parametrize("via_connector", [False, True])
|
||||
@pytest.mark.parametrize(
|
||||
("case", "message"),
|
||||
[
|
||||
("not_mapping", "no conditioning payload"),
|
||||
("text_only", "requires text, visual and audio tensors"),
|
||||
("missing_hidden", "requires text, visual and audio tensors"),
|
||||
("missing_tags", "requires text, visual and audio tensors"),
|
||||
("missing_layout", "requires private layout metadata"),
|
||||
("truncated_layout", "header is truncated"),
|
||||
("layout_dtype", "one-dimensional integer tensor"),
|
||||
("schema", "unsupported MiniMax H3 encoder wire schema"),
|
||||
("visual_shape", "visual condition must be FP32"),
|
||||
("audio_dtype", "audio condition must be FP32"),
|
||||
("empty_visual", "empty visual condition slot"),
|
||||
("empty_audio", "empty audio condition slot"),
|
||||
],
|
||||
)
|
||||
def test_encoder_handoff_rejects_invalid_full_payload(case, message, via_connector):
|
||||
payload = _full_encoder_output()
|
||||
layout = payload["kv_metadata"][MINIMAX_H3_ENCODER_LAYOUT_KEY]
|
||||
if case == "not_mapping":
|
||||
payload = []
|
||||
elif case == "text_only":
|
||||
payload.pop("embed")
|
||||
elif case == "missing_hidden":
|
||||
payload.pop("hidden_states")
|
||||
elif case == "missing_tags":
|
||||
payload["meta"] = {}
|
||||
elif case == "missing_layout":
|
||||
payload.pop("kv_metadata")
|
||||
elif case == "truncated_layout":
|
||||
payload["kv_metadata"][MINIMAX_H3_ENCODER_LAYOUT_KEY] = layout[:5]
|
||||
elif case == "layout_dtype":
|
||||
payload["kv_metadata"][MINIMAX_H3_ENCODER_LAYOUT_KEY] = layout.float()
|
||||
elif case == "schema":
|
||||
layout[1] = 99
|
||||
elif case == "visual_shape":
|
||||
payload["embed"]["embedding"] = torch.zeros(11, 96)
|
||||
elif case == "audio_dtype":
|
||||
payload["embed"]["speech_feat"] = payload["embed"]["speech_feat"].to(torch.bfloat16)
|
||||
elif case == "empty_visual":
|
||||
payload = _encoder_output()
|
||||
payload["embed"]["embedding"] = torch.empty(0, 96)
|
||||
elif case == "empty_audio":
|
||||
payload = _encoder_output()
|
||||
payload["embed"]["speech_feat"] = torch.empty(0, dtype=torch.bfloat16)
|
||||
with pytest.raises(RuntimeError, match=message):
|
||||
if via_connector:
|
||||
encoder2diffusion_full_payload(pooling_output=payload)
|
||||
else:
|
||||
encoder2diffusion([_source_output(payload)], {"prompt": "hello"})
|
||||
|
||||
|
||||
@pytest.mark.parametrize("inline", [False, True])
|
||||
def test_encoder_handoff_cleans_media_without_mutating_prompt_or_stripping_outputs(inline):
|
||||
incoming = _full_encoder_output()
|
||||
retained_hidden = torch.ones(1)
|
||||
media = torch.zeros(2)
|
||||
prompt = {
|
||||
"prompt": "hello",
|
||||
"negative_prompt": "blur",
|
||||
"multi_modal_data": {"image": object(), "audio": object(), "video": object()},
|
||||
"model_intermediate_buffer": {"media": media},
|
||||
"additional_information": {
|
||||
"global_request_id": ["request-1"],
|
||||
"private": "preserved",
|
||||
"hidden_states": {"layers": {0: media}, "output": retained_hidden},
|
||||
"meta": {MINIMAX_H3_ENCODER_REQUEST_KEY: {"task": "ref2va"}, "private": 42},
|
||||
"encoder_output": incoming,
|
||||
},
|
||||
}
|
||||
source = _source_output(_runner_payload(incoming) if inline else None)
|
||||
if not inline:
|
||||
del source.outputs[0].multimodal_output
|
||||
result = encoder2diffusion([source], [prompt])
|
||||
info = result["additional_information"]
|
||||
assert result["multi_modal_data"] is None
|
||||
assert "model_intermediate_buffer" not in result
|
||||
assert result["negative_prompt"] == "blur"
|
||||
assert info["global_request_id"] == ["request-1"]
|
||||
assert info["private"] == "preserved"
|
||||
assert info["meta"] == {"private": 42}
|
||||
assert set(info["hidden_states"]) == {"output"}
|
||||
assert info["hidden_states"]["output"] is retained_hidden
|
||||
for key in ("embedding", "speech_feat"):
|
||||
_assert_same_tensor_view(info["encoder_output"]["embed"][key], incoming["embed"][key])
|
||||
if not inline:
|
||||
assert info["encoder_output"] is incoming
|
||||
assert prompt["multi_modal_data"] is not None
|
||||
assert prompt["model_intermediate_buffer"]["media"] is media
|
||||
assert prompt["additional_information"]["hidden_states"]["layers"][0] is media
|
||||
assert MINIMAX_H3_ENCODER_REQUEST_KEY in prompt["additional_information"]["meta"]
|
||||
|
||||
|
||||
def test_connector_handoff_without_inline_output_cleans_encoder_only_information():
|
||||
prompt = {
|
||||
"prompt": "hello",
|
||||
"multi_modal_data": {"image": object()},
|
||||
"model_intermediate_buffer": {"private": object()},
|
||||
"additional_information": {
|
||||
"hidden_states": {"layers": {0: torch.zeros(1)}},
|
||||
"meta": {MINIMAX_H3_ENCODER_REQUEST_KEY: {"task": "t2va"}},
|
||||
},
|
||||
}
|
||||
result = encoder2diffusion([_source_output(None)], prompt)
|
||||
assert result == {"prompt": "hello", "multi_modal_data": None, "additional_information": {}}
|
||||
|
||||
|
||||
@pytest.mark.parametrize("payload", [None, _encoder_output()])
|
||||
@pytest.mark.parametrize("request_id", ["other", ["other"], ("other",)])
|
||||
def test_stage_wire_rejects_request_id_mismatch(payload, request_id):
|
||||
prompt = {"prompt": "hello", "additional_information": {"global_request_id": request_id}}
|
||||
with pytest.raises(RuntimeError, match="request ID does not match"):
|
||||
encoder2diffusion([_source_output(payload)], prompt)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("outputs", [None, [], (), [SimpleNamespace(), SimpleNamespace()]])
|
||||
def test_stage_wire_rejects_invalid_completion_count(outputs):
|
||||
with pytest.raises(RuntimeError, match="exactly one completion"):
|
||||
encoder2diffusion([SimpleNamespace(outputs=outputs)], {"prompt": "hello"})
|
||||
|
||||
|
||||
def test_stage_wire_empty_sources_and_invalid_prompt():
|
||||
assert encoder2diffusion([], {"prompt": "hello"}) is None
|
||||
with pytest.raises(TypeError, match="invalid MiniMax H3 prompt type"):
|
||||
encoder2diffusion([_source_output(None)], object())
|
||||
@@ -21,6 +21,7 @@ import torch
|
||||
from vllm_omni.distributed.omni_connectors.kv_transfer_manager import (
|
||||
OmniKVTransferManager,
|
||||
)
|
||||
from vllm_omni.distributed.omni_connectors.model_runner import omni_connector_runtime
|
||||
from vllm_omni.distributed.omni_connectors.utils.config import ConnectorSpec
|
||||
from vllm_omni.distributed.omni_connectors.utils.initialization import (
|
||||
resolve_connector_spec,
|
||||
@@ -59,6 +60,13 @@ class MockConnector:
|
||||
def close(self):
|
||||
pass
|
||||
|
||||
def get_with_deadline(self, from_stage, to_stage, get_key, metadata=None, *, deadline):
|
||||
self.last_deadline = deadline
|
||||
return self.get(from_stage, to_stage, get_key, metadata)
|
||||
|
||||
def abandon_get(self, get_key):
|
||||
self.abandoned_key = get_key
|
||||
|
||||
|
||||
def _make_model_config(
|
||||
stage_id: int = 0,
|
||||
@@ -91,6 +99,45 @@ class MixinHost(OmniConnectorModelRunnerMixin):
|
||||
pass
|
||||
|
||||
|
||||
def test_stage_payload_recv_spec_preserves_external_id_edge_and_handle():
|
||||
sender = {"host": "10.0.0.1", "zmq_port": "50071"}
|
||||
assert MixinHost._stage_payload_recv_spec("external", "2", "5", 3, sender) == (
|
||||
"2",
|
||||
"5",
|
||||
"external_2_3",
|
||||
{"source_host": "10.0.0.1", "source_port": 50071},
|
||||
)
|
||||
metadata = {"schema_version": 1}
|
||||
handle = {"key": "explicit", "from_stage": 7, "to_stage": 9, "metadata": metadata}
|
||||
assert MixinHost._stage_payload_recv_spec("external", "2", "5", sender_info=sender, handle=handle) == (
|
||||
"7",
|
||||
"9",
|
||||
"explicit",
|
||||
metadata,
|
||||
)
|
||||
|
||||
|
||||
def test_synchronous_payload_init_borrows_connector_without_threads_or_kv_mutation():
|
||||
host = MixinHost()
|
||||
connector = MockConnector()
|
||||
manager = SimpleNamespace(connector=connector, kv_recv_key_builder=object())
|
||||
original_state = vars(manager).copy()
|
||||
with patch.object(host, "_create_connector", side_effect=AssertionError("duplicate connector")):
|
||||
host.init_omni_connectors(_make_model_config(), manager, synchronous=True)
|
||||
assert host._omni_connector_initialized
|
||||
assert host._recv_thread is None
|
||||
assert host._save_thread is None
|
||||
assert host._pending_load_reqs == {}
|
||||
assert vars(manager) == original_state
|
||||
connector.put("2", "5", "external_2_0", {"value": 7})
|
||||
assert host.recv_stage_payload("external", "2", "5") == {"value": 7}
|
||||
assert isinstance(connector.last_deadline, float)
|
||||
assert connector.abandoned_key == "external_2_0"
|
||||
with patch.object(connector, "close") as close:
|
||||
host.shutdown_omni_connectors()
|
||||
close.assert_not_called()
|
||||
|
||||
|
||||
class _FakeTPGroup:
|
||||
def __init__(self, *, world_size: int, rank_in_group: int, follower_result: Any = None):
|
||||
self.world_size = world_size
|
||||
@@ -138,6 +185,121 @@ def test_init_payload_connector_ownership(role, custom_func, expected):
|
||||
host.shutdown_omni_connectors()
|
||||
|
||||
|
||||
@pytest.mark.parametrize("async_chunk", [False, True])
|
||||
@pytest.mark.parametrize("rank", [0, 1])
|
||||
def test_split_request_endpoint_retry_completion_and_cleanup(async_chunk, rank):
|
||||
host = MixinHost()
|
||||
host.init_omni_connectors(_make_model_config(async_chunk=async_chunk))
|
||||
# No background threads: deterministic interleaved polling.
|
||||
host._stage_id = 1
|
||||
host._omni_connector = MockConnector(stage_id=1)
|
||||
connector = host._omni_connector
|
||||
connector.sender_host = "configured-host"
|
||||
connector.sender_zmq_port = 50051
|
||||
connector.get = MagicMock(return_value=None)
|
||||
first = _make_request("r1", "external1")
|
||||
first.payload_sender_info = {"host": "producer-a", "zmq_port": "50101"}
|
||||
second = _make_request("r2", "external2")
|
||||
second.payload_sender_info = {"host": "producer-b", "zmq_port": 51101}
|
||||
tp_group = _FakeTPGroup(world_size=2, rank_in_group=rank)
|
||||
try:
|
||||
with patch.object(host, "_get_local_tp_group", return_value=tp_group):
|
||||
host.register_chunk_recv(first)
|
||||
host.register_chunk_recv(second)
|
||||
for req_id in ("r2", "r1", "r2"):
|
||||
assert not host._poll_single_request(req_id)
|
||||
if rank == 1:
|
||||
connector.get.assert_not_called()
|
||||
else:
|
||||
assert connector.get.call_args_list == [
|
||||
unittest.mock.call("0", "1", "external2_0_0", {"source_host": "producer-b", "source_port": 51101}),
|
||||
unittest.mock.call("0", "1", "external1_0_0", {"source_host": "producer-a", "source_port": 50101}),
|
||||
unittest.mock.call("0", "1", "external2_0_0", {"source_host": "producer-b", "source_port": 51101}),
|
||||
]
|
||||
connector.get.return_value = ({"ids": {"output": [1]}, "meta": {"finished": True}}, 1)
|
||||
assert host._poll_single_request("r2")
|
||||
assert "r2" not in host._pending_load_reqs
|
||||
assert "r1" in host._pending_load_reqs
|
||||
host.cleanup_finished_request("r1")
|
||||
host.cleanup_finished_request("r2")
|
||||
assert not host._pending_load_reqs
|
||||
# Reused internal ID without sender info cannot inherit either endpoint.
|
||||
replacement = _make_request("r1", "external-new")
|
||||
connector.get.reset_mock(return_value=True)
|
||||
connector.get.return_value = None
|
||||
host.register_chunk_recv(replacement)
|
||||
assert not host._poll_single_request("r1")
|
||||
if rank == 0:
|
||||
connector.get.assert_called_once_with("0", "1", "external-new_0_0")
|
||||
else:
|
||||
connector.get.assert_not_called()
|
||||
assert connector.sender_host == "configured-host"
|
||||
assert connector.sender_zmq_port == 50051
|
||||
assert first.payload_sender_info == {"host": "producer-a", "zmq_port": "50101"}
|
||||
finally:
|
||||
host.cleanup_finished_request("r1")
|
||||
host.shutdown_omni_connectors()
|
||||
|
||||
|
||||
@pytest.mark.parametrize("role", ["sender", "receiver"])
|
||||
def test_split_factory_resolves_rank_replica_without_mutating_config(role):
|
||||
extra = {"role": role, "zmq_port": 50071, "from_stage": 2, "host": "producer"}
|
||||
config = _make_model_config()
|
||||
config.stage_id = 2 if role == "sender" else 3
|
||||
config.stage_connector_config = {"name": "NixlConnector", "extra": extra}
|
||||
with (
|
||||
patch.object(omni_connector_runtime, "get_local_tp_rank", return_value=3),
|
||||
patch.object(omni_connector_runtime, "get_omni_replica_id", return_value=2),
|
||||
patch.object(omni_connector_runtime.OmniConnectorFactory, "create_connector") as create,
|
||||
):
|
||||
assert MixinHost._create_connector(config) is create.return_value
|
||||
spec = create.call_args.args[0]
|
||||
assert spec.name == "NixlConnector"
|
||||
assert spec.extra["stage_id"] == config.stage_id
|
||||
assert spec.extra["role"] == role
|
||||
assert spec.extra["zmq_port" if role == "sender" else "sender_zmq_port"] == 50071 + 2 + 3 * 16 + 2 * 1024
|
||||
if role == "receiver":
|
||||
assert "zmq_port" not in spec.extra
|
||||
assert spec.extra["sender_host"] == "producer"
|
||||
assert extra == {"role": role, "zmq_port": 50071, "from_stage": 2, "host": "producer"}
|
||||
|
||||
|
||||
@pytest.mark.parametrize("rank", [None, 0, 1])
|
||||
def test_split_transfer_rank_without_runtime_initialization(rank):
|
||||
host = MixinHost()
|
||||
group = None if rank is None else _FakeTPGroup(world_size=2, rank_in_group=rank)
|
||||
with patch.object(host, "_get_local_tp_group", return_value=group):
|
||||
assert host.is_data_transfer_rank() is (rank != 1)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("rank", [0, 1])
|
||||
def test_split_full_payload_hook_and_send_are_leader_only(rank):
|
||||
host = MixinHost()
|
||||
host.init_omni_connectors(_make_model_config())
|
||||
host._omni_connector = MockConnector()
|
||||
output = {"encoder_output": {"video": torch.ones(1), "audio": torch.zeros(1)}}
|
||||
host._custom_process_func = MagicMock(return_value=output)
|
||||
group = _FakeTPGroup(world_size=2, rank_in_group=rank)
|
||||
try:
|
||||
with patch.object(host, "_get_local_tp_group", return_value=group):
|
||||
assert host.send_full_payload_outputs(None, {"r1": (output, _make_request("r1"))}) == ["r1"]
|
||||
if rank == 1:
|
||||
host._custom_process_func.assert_not_called()
|
||||
assert not host._pending_save_reqs
|
||||
else:
|
||||
host._custom_process_func.assert_called_once()
|
||||
task = host._pending_save_reqs["r1"].popleft()
|
||||
assert task["data"] is output
|
||||
host.cleanup_finished_request("r1")
|
||||
assert "r1" in host._deferred_send_cleanup
|
||||
assert host._send_single_request(task)
|
||||
assert not host._pending_save_counts
|
||||
assert not host._deferred_send_cleanup
|
||||
assert host._omni_connector.get("0", "1", "r1_0_0")[0] is output
|
||||
finally:
|
||||
host.shutdown_omni_connectors()
|
||||
|
||||
|
||||
class TestMixinAsyncChunkSendRecv(unittest.TestCase):
|
||||
"""Test 2: Async chunk send/recv + bg threads."""
|
||||
|
||||
|
||||
Reference in new issue
Block a user