diff --git a/docs/design/module/model_integration.md b/docs/design/module/model_integration.md index 2e848a49c60..bd23e8f2c51 100644 --- a/docs/design/module/model_integration.md +++ b/docs/design/module/model_integration.md @@ -57,3 +57,11 @@ sufficient; an override MUST document the behavioral difference. Test registration, checkpoint loading, input conversion, and representative model execution. Test shared utilities against more than one integration. + +## Platform-specific model adapters + +Drama 3's Ascend attention compatibility, hybrid model state, and FP8 expert +adapter live under `platforms/npu/models/` and `platforms/npu/quant/`. Shared +model code selects these adapters lazily on NPU; CUDA keeps the upstream +implementations. Generic eager kernels and request-history snapshots remain +in the shared model implementation. diff --git a/docs/design/module/stage_runtime.md b/docs/design/module/stage_runtime.md index 38255880fd1..197e1b09e94 100644 --- a/docs/design/module/stage_runtime.md +++ b/docs/design/module/stage_runtime.md @@ -144,3 +144,11 @@ cleanup without duplicate stage shutdown. processes. - Obtain approval from a technical owner and an independent validation reviewer. + +## Platform preparation before stage construction + +`StageEngineCoreProc` calls `current_omni_platform.prepare_stage_engine()` +before the upstream engine constructor creates its scheduler and cache +managers. The default hook is a no-op. The NPU implementation installs its +Mamba allocator signature compatibility here, so Ascend imports and patches +remain in the NPU platform and are not applied to other platforms. diff --git a/docs/user_guide/examples/online_serving/text_to_speech.md b/docs/user_guide/examples/online_serving/text_to_speech.md index 6e3e9354302..65268b9512a 100644 --- a/docs/user_guide/examples/online_serving/text_to_speech.md +++ b/docs/user_guide/examples/online_serving/text_to_speech.md @@ -222,6 +222,7 @@ vllm serve fishaudio/drama-3 --omni --port 8091 ``` The deploy config auto-loads from `vllm_omni/deploy/fish_omni.yaml` (the HF `model_type` on the checkpoint is `fish_omni`). +On Ascend, the same command uses the `npu` profile: Model Runner V2 with tensor parallel 2 and expert parallel across two 910B cards, and the DAC stage sharing the second card. See the recipe. ### Voice cloning diff --git a/examples/online_serving/text_to_speech/README.md b/examples/online_serving/text_to_speech/README.md index 6a8a2468662..9b07dd4d88a 100644 --- a/examples/online_serving/text_to_speech/README.md +++ b/examples/online_serving/text_to_speech/README.md @@ -417,6 +417,7 @@ vllm serve fishaudio/drama-3 --omni --port 8091 ``` The deploy config auto-loads from `vllm_omni/deploy/fish_omni.yaml` (the HF `model_type` on the checkpoint is `fish_omni`). +On Ascend, the same command uses the `npu` profile: Model Runner V2 with tensor parallel 2 and expert parallel across two 910B cards, and the DAC stage sharing the second card. See the recipe. ### Voice cloning diff --git a/recipes/README.md b/recipes/README.md index d68c206d5d9..ffb91455fc5 100644 --- a/recipes/README.md +++ b/recipes/README.md @@ -63,7 +63,7 @@ for RTX 4090, RTX 5090, DGX Spark, and RTX PRO 6000 Blackwell. | [`FastVideo/FastH3-V2.md`](./FastVideo/FastH3-V2.md) | FastH3 V2 eight-step T2VA checkpoint | CUDA with FastVideo tile64 or FlashInfer on SM120/SM121; full-model qualification pending | | [`FastVideo/FastH3-Omni.md`](./FastVideo/FastH3-Omni.md) | FastH3 Omni eight-step Ref2VA, multi-GPU serving | Shared eight-GPU profile; PRO 5000 baseline in recipe | | [FastH3 RefOmni Single Card](<./FastVideo/FastH3 RefOmni Single Card.md>) | Single-card installation, serving, and generation guide | RTX 4090 / 5090 / DGX Spark / RTX PRO 6000 Blackwell | -| [`fishaudio/Drama-3.md`](./fishaudio/Drama-3.md) | Online serving for TTS | 1x H100 80GB | +| [`fishaudio/Drama-3.md`](./fishaudio/Drama-3.md) | Online serving for TTS | 1x H200 141GB / 2x Ascend 910B 64GB | | [`fishaudio/Fish-Speech-S2-Pro.md`](./fishaudio/Fish-Speech-S2-Pro.md) | Online serving for TTS | 1x A800 80GB | | [`Helios/Helios.md`](./Helios/Helios.md) | Text-to-video, image-to-video, and video-to-video generation | 1x NVIDIA H20 | | [`HiDream-ai/HiDream-O1-Image.md`](./HiDream-ai/HiDream-O1-Image.md) | Text-to-image with shared offline example | 1x or 2x H100 80GB | diff --git a/recipes/fishaudio/Drama-3.md b/recipes/fishaudio/Drama-3.md index ea012f9bc41..c6d2827a845 100644 --- a/recipes/fishaudio/Drama-3.md +++ b/recipes/fishaudio/Drama-3.md @@ -163,7 +163,9 @@ Throughput is seconds of audio generated per wall-clock second. #### Known limitations -- One tensor and pipeline rank only. +- Pipeline parallel is not supported. The CUDA deploy uses one tensor rank. + The Ascend profile shards the backbone across two cards and the routed + experts with them (see NPU below). - Prefix caching is off: prompt rows carry ten codes per audio row that token-id hashing does not see. - Some takes stop speaking after the first word or event and emit silence @@ -171,3 +173,34 @@ Throughput is seconds of audio generated per wall-clock second. that start with a filler word or a tag, and with pause-heavy references. - `previous_takes` (editing as continuation) and long-text chunking are not exposed by the speech API yet. + +## NPU + +### 2x Ascend 910B 64GB + +Stage 0 (backbone + codebook tower) uses Model Runner V2 on both cards: +tensor parallel 2 and expert parallel, replaying piecewise ACL graphs +(`enforce_eager: false`, `cudagraph_mode: PIECEWISE`). The NPU AR runner builds +Ascend input state (`AscendInputBatch` with `attn_state` and `seq_lens_np`) +and the model state builds Ascend attention metadata. Gated-delta-net stays on +the Ascend implementation. The codebook tower uses the eager norm and sampling +path. Stage 1 (DAC) shares the second card and stays eager, without ACL graphs +or MPS. +Sampling noise is broadcast from tensor-parallel rank 0 so both ranks draw +the same frame. + +```bash +ASCEND_RT_VISIBLE_DEVICES=0,1 vllm serve fishaudio/drama-3 --omni --port 8091 +``` + +`vllm_omni/deploy/fish_omni.yaml` applies this `npu` profile automatically +(`tensor_parallel_size: 2`, `enable_expert_parallel: true`, `max_num_seqs: 64`, +stage 0 `enforce_eager: false`). +Stage 0 reserves 0.72 of each card and stage 1 reserves 0.10 of the second +card. The speech request is the same as the GPU section. + +vLLM-Ascend on 910B still expands this checkpoint's block-FP8 experts to +bfloat16 (64.4 GiB for all 256 routed experts). One card cannot hold that +expansion. Expert parallel places 128 experts on each card, about 32 GiB, +plus the sharded backbone. The codec then fits in the headroom on the second +card. This profile has not been scored for WER or RTF. diff --git a/tests/config/test_omni_config.py b/tests/config/test_omni_config.py index 0b4750180f0..205cafa74dc 100644 --- a/tests/config/test_omni_config.py +++ b/tests/config/test_omni_config.py @@ -971,10 +971,37 @@ def test_deploy_model_runner_selection_propagates_to_every_stage(tmp_path: Path, assert all(stage.model_config.use_v2_model_runner is expect_v2 for stage in structured.stage_configs) -@pytest.mark.parametrize("platform", ["npu", "xpu"]) -def test_mrv2_fails_fast_on_platforms_without_native_workers(platform: str): +def test_mrv2_fails_fast_on_xpu(): with pytest.raises(NotImplementedError, match="Model Runner V2"): - _apply_platform_overrides(DeployConfig(model_runner="v2"), platform=platform) + _apply_platform_overrides(DeployConfig(model_runner="v2"), platform="xpu") + + +@pytest.mark.parametrize("stage_override", [False, True]) +def test_mrv2_config_is_allowed_on_npu(stage_override): + deploy = ( + DeployConfig(stages=[StageDeployConfig(stage_id=0, model_runner="v2")]) + if stage_override + else DeployConfig(model_runner="v2") + ) + deploy = _apply_platform_overrides(deploy, platform="npu") + if stage_override: + assert deploy.stages[0].model_runner == "v2" + else: + assert deploy.model_runner == "v2" + + +def test_fish_omni_npu_profile_is_mrv2_tp_ep(): + deploy = _apply_platform_overrides(load_deploy_config(_DEPLOY_DIR / "fish_omni.yaml"), platform="npu") + stage0, stage1 = deploy.stages + assert stage0.model_runner == "v2" + assert stage0.tensor_parallel_size == 2 + assert stage0.enable_expert_parallel is True + assert stage0.enforce_eager is False + assert stage0.gpu_memory_utilization == 0.72 + assert stage0.devices == "0,1" + assert stage1.model_runner == "v1" + assert stage1.gpu_memory_utilization == 0.1 + assert stage1.devices == "1" def _qwen3_omni_pipeline() -> PipelineConfig: diff --git a/tests/engine/test_stage_engine_core_proc.py b/tests/engine/test_stage_engine_core_proc.py index 0dc8f4f1918..3ab5cce8c77 100644 --- a/tests/engine/test_stage_engine_core_proc.py +++ b/tests/engine/test_stage_engine_core_proc.py @@ -144,3 +144,22 @@ def test_handshake_wait_is_extended_but_never_shortened(monkeypatch, timeout_s, monkeypatch.setattr(engine_core_module, "HANDSHAKE_TIMEOUT_MINS", 5) _extend_handshake_timeout(timeout_s) assert engine_core_module.HANDSHAKE_TIMEOUT_MINS == expected_minutes + + +def test_platform_compat_runs_before_engine_construction(monkeypatch): + from vllm_omni.engine import stage_engine_core_proc as module + + calls = [] + + class ConstructionStoppedError(Exception): + pass + + def construct(self, *args, **kwargs): + calls.append("engine") + raise ConstructionStoppedError + + monkeypatch.setattr(module.current_omni_platform, "prepare_stage_engine", lambda: calls.append("platform")) + monkeypatch.setattr(EngineCoreProc, "__init__", construct) + with pytest.raises(ConstructionStoppedError): + StageEngineCoreProc() + assert calls == ["platform", "engine"] diff --git a/tests/model_executor/models/fish_omni/test_fish_omni_config.py b/tests/model_executor/models/fish_omni/test_fish_omni_config.py index 5d6aeac84d0..6de43071643 100644 --- a/tests/model_executor/models/fish_omni/test_fish_omni_config.py +++ b/tests/model_executor/models/fish_omni/test_fish_omni_config.py @@ -146,3 +146,48 @@ def test_rejects_unsupported_text_values(key, value): def test_rejects_dense_backbone_layer(): with pytest.raises(ValueError, match="every backbone layer must be MoE"): _config(mlp_layer_types=["moe"] * 39 + ["dense"]) + + +def test_npu_fused_qk_rope_is_rejected_after_construction(): + import vllm_omni.platforms.npu.models.fish_omni as fish_model + + class _Eager: + use_fused_qk_norm_rope_gate = False + + class _Fused: + use_fused_qk_norm_rope_gate = True + + class _Root: + def __init__(self, children: list[object]) -> None: + self._children = children + + def modules(self) -> list[object]: + return self._children + + fish_model._require_npu_eager_qk_rope(_Root([_Eager()])) + with pytest.raises(RuntimeError, match="fused QK-norm RoPE"): + fish_model._require_npu_eager_qk_rope(_Root([_Eager(), _Fused()])) + for children in ([], [object()]): + with pytest.raises(RuntimeError, match="no attention modules expose use_fused_qk_norm_rope_gate"): + fish_model._require_npu_eager_qk_rope(_Root(children)) + + +def test_tensor_parallel_is_allowed_on_npu_only(monkeypatch): + from types import SimpleNamespace + + import vllm_omni.model_executor.models.fish_omni.fish_omni_model as fish_model + + parallel = SimpleNamespace(pipeline_parallel_size=1, prefill_context_parallel_size=1, tensor_parallel_size=2) + monkeypatch.setattr(fish_model, "current_platform", SimpleNamespace(device_type="npu")) + fish_model._reject_unsupported_fish_parallel(parallel) + monkeypatch.setattr(fish_model, "current_platform", SimpleNamespace(device_type="cuda")) + with pytest.raises(NotImplementedError, match="tensor parallel"): + fish_model._reject_unsupported_fish_parallel(parallel) + with pytest.raises(NotImplementedError, match="one pipeline rank"): + fish_model._reject_unsupported_fish_parallel( + SimpleNamespace(pipeline_parallel_size=2, prefill_context_parallel_size=1) + ) + with pytest.raises(NotImplementedError, match="prefill context"): + fish_model._reject_unsupported_fish_parallel( + SimpleNamespace(pipeline_parallel_size=1, prefill_context_parallel_size=2) + ) diff --git a/tests/model_executor/models/fish_omni/test_fish_omni_kernels_eager.py b/tests/model_executor/models/fish_omni/test_fish_omni_kernels_eager.py new file mode 100644 index 00000000000..10050e9d964 --- /dev/null +++ b/tests/model_executor/models/fish_omni/test_fish_omni_kernels_eager.py @@ -0,0 +1,170 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project +"""CPU references for the Drama 3 tower and sampling kernels used on NPU.""" + +import pytest +import torch + +from vllm_omni.model_executor.models.fish_omni.kernels import ( + draw_top_k_top_p, + gemma_rms_norm, + gemma_rms_norm_table, + sigmoid_gate, + tower_mix_norm, +) + +pytestmark = [pytest.mark.core_model, pytest.mark.cpu] + +EPS = 1e-6 + + +def _gemma(values: torch.Tensor, weight: torch.Tensor) -> torch.Tensor: + """vLLM's zero-centered Gemma RMSNorm, the reference these kernels follow.""" + return values * torch.rsqrt(values.pow(2).mean(-1, keepdim=True) + EPS) * (weight + 1) + + +def test_gemma_rms_norm_matches_zero_centered_reference(): + x = torch.tensor([[1.0, 3.0, 0.0, 2.0], [0.5, -0.5, 0.25, 0.0]]) + weight = torch.tensor([0.0, 1.0, -0.5, 0.25]) + residual = torch.tensor([[0.5, 0.0, 1.0, -1.0], [0.0, 0.25, 0.0, 0.5]]) + out, summed = gemma_rms_norm(x, weight, EPS, residual) + total = x + residual + expected = _gemma(total, weight) + torch.testing.assert_close(summed, total) + torch.testing.assert_close(out, expected) + + +def test_gemma_rms_norm_without_residual_returns_only_the_norm(): + x = torch.tensor([[1.0, 3.0, 0.0, 2.0]]) + weight = torch.tensor([0.0, 1.0, -0.5, 0.25]) + torch.testing.assert_close(gemma_rms_norm(x, weight, EPS), _gemma(x, weight)) + + +@pytest.mark.parametrize("with_extra", [False, True]) +def test_tower_mix_norm_concatenates_code_and_hidden(with_extra): + hidden = torch.tensor([[1.0, 0.0], [0.0, 2.0]]) + code = torch.tensor([1, 0]) + mask = torch.tensor([1.0, 0.0]) + table = torch.tensor([[3.0, 1.0], [0.0, 4.0]]) + extra = torch.tensor([[0.5, -1.5], [2.0, 0.25]]) if with_extra else None + enorm = torch.tensor([0.5, -0.25]) + hnorm = torch.tensor([0.0, 1.0]) + + out = tower_mix_norm(hidden, code, mask, table, extra, enorm, hnorm, EPS) + + embedded = table[code] * mask.unsqueeze(-1) + if extra is not None: + embedded = embedded + extra + torch.testing.assert_close(out, torch.cat([_gemma(embedded, enorm), _gemma(hidden, hnorm)], dim=-1)) + + +def test_gemma_rms_norm_table_adds_the_code_embedding_to_the_residual(): + x = torch.tensor([[1.0, 3.0, 0.0, 2.0], [0.5, -0.5, 0.25, 0.0]]) + code = torch.tensor([1, 0]) + mask = torch.tensor([1.0, 0.0]) + table = torch.tensor([[3.0, 1.0, 0.0, 2.0], [0.0, 4.0, -1.0, 0.5]]) + weight = torch.tensor([0.0, 1.0, -0.5, 0.25]) + + out, summed = gemma_rms_norm_table(x, code, mask, table, weight, EPS) + + total = x + table[code] * mask.unsqueeze(-1) + torch.testing.assert_close(summed, total) + torch.testing.assert_close(out, _gemma(total, weight)) + + +def test_sigmoid_gate_matches_fp32_product(): + x = torch.tensor([0.0, 1.0, -2.0]) + gate = torch.tensor([0.0, 2.0, -1.0]) + torch.testing.assert_close(sigmoid_gate(x, gate), x * torch.sigmoid(gate)) + + +def test_draw_keeps_rank_zero_when_temperature_collapses(): + logits = torch.tensor([[0.0, 5.0, 1.0, -3.0], [2.0, 2.0, 9.0, 0.0]]) + rows = logits.shape[0] + drawn = draw_top_k_top_p( + logits, + temperature=torch.zeros(rows), + top_k=torch.ones(rows, dtype=torch.int64), + top_p=torch.ones(rows), + uniform=torch.rand(rows, 2), + max_top_k=2, + ) + assert drawn.tolist() == [1, 2] + + +def test_draw_maps_column_indices_through_id_map(): + logits = torch.tensor([[0.0, 5.0, 1.0, -3.0], [2.0, 2.0, 9.0, 0.0]]) + rows = logits.shape[0] + id_map = torch.tensor([70, 71, 72, 73], dtype=torch.int64) + drawn = draw_top_k_top_p( + logits, + temperature=torch.zeros(rows), + top_k=torch.ones(rows, dtype=torch.int64), + top_p=torch.ones(rows), + uniform=torch.rand(rows, 2), + max_top_k=2, + id_map=id_map, + ) + assert drawn.tolist() == [71, 72] + + +def test_draw_reuses_a_shared_topk_result(): + logits = torch.tensor([[0.0, 5.0, 1.0, -3.0], [2.0, 2.0, 9.0, 0.0]]) + rows = logits.shape[0] + shared = torch.topk(logits, 2, dim=-1) + drawn = draw_top_k_top_p( + logits, + temperature=torch.zeros(rows), + top_k=torch.ones(rows, dtype=torch.int64), + top_p=torch.ones(rows), + uniform=torch.rand(rows, 2), + max_top_k=2, + top=shared, + ) + assert drawn.tolist() == [1, 2] + + +def test_eager_qk_rope_splits_gate_and_rotates_the_first_half(): + from vllm_omni.model_executor.models.fish_omni.kernels import eager_qk_rmsnorm_rope_gate + + head_dim, rotary_dim, heads = 4, 4, 1 + q_gate = torch.tensor([[1.0, 0.0, 0.0, 0.0, 3.0, 4.0, 5.0, 6.0]]) + k = torch.tensor([[0.0, 1.0, 0.0, 0.0]]) + weight = torch.zeros(head_dim) + cos_sin = torch.tensor([[1.0, 0.0, 0.0, 1.0]]) + positions = torch.zeros(1, dtype=torch.long) + q, k_out, gate = eager_qk_rmsnorm_rope_gate( + q_gate, + k, + weight, + weight, + cos_sin, + positions, + EPS, + heads, + heads, + head_dim, + rotary_dim, + norm_beta=1.0, + ) + torch.testing.assert_close(gate, torch.tensor([[3.0, 4.0, 5.0, 6.0]])) + assert q.shape == (1, head_dim) + assert k_out.shape == (1, head_dim) + # Identity rotation (cos=1, sin=0) leaves the normalized q direction. + assert q[0, 0] > 0 and torch.count_nonzero(q) >= 1 + + +def test_draw_restricts_to_top_p_mass(): + # Column 0 holds almost all the mass, so top_p 0.5 keeps rank 0 only and + # every draw returns it whatever the noise says. + logits = torch.tensor([[20.0, 1.0, 0.0, -1.0]]) + for _ in range(8): + drawn = draw_top_k_top_p( + logits, + temperature=torch.ones(1), + top_k=torch.full((1,), 4, dtype=torch.int64), + top_p=torch.full((1,), 0.5), + uniform=torch.rand(1, 4), + max_top_k=4, + ) + assert drawn.tolist() == [0] diff --git a/tests/model_executor/models/fish_omni/test_fish_omni_model_state.py b/tests/model_executor/models/fish_omni/test_fish_omni_model_state.py index b6e88750480..fd994e1aaa1 100644 --- a/tests/model_executor/models/fish_omni/test_fish_omni_model_state.py +++ b/tests/model_executor/models/fish_omni/test_fish_omni_model_state.py @@ -5,6 +5,7 @@ from collections.abc import Sequence from types import SimpleNamespace +from unittest.mock import patch import numpy as np import pytest @@ -96,6 +97,8 @@ def test_preempted_request_resumes_with_its_generated_frames(make_state): state.buffers.slot_history[1, :3] = codes state.buffers.slot_generated[1] = 3 state.on_request_preempted("a", 1) + assert state._suspended["a"].history.device.type == "cpu" + assert state._suspended["a"].count.device.type == "cpu" # Another request takes the slot before "a" comes back. state.buffers.slot_history[1].zero_() state.buffers.slot_generated[1] = 0 @@ -115,6 +118,8 @@ def test_preempted_request_resumes_with_its_generated_frames(make_state): assert ras[-3:] == main # The resumed slot gets its code history back, for a later preemption. assert list(state._pending_history) == [2] and torch.equal(state._pending_history[2], codes) + state.on_requests_finished({"a"}) + assert "a" not in state._suspended def test_slot_reused_before_a_step_keeps_only_the_newest_request(make_state): @@ -213,3 +218,45 @@ def test_max_top_k_is_a_power_of_two_from_the_ras_top_k_to_the_codebook(value, o else: with pytest.raises(ValueError, match="power of two"): max_top_k(config, 4096) + + +def test_npu_device_selects_ascend_model_state(monkeypatch): + sentinel = object() + from vllm_omni.platforms.npu.models import fish_omni_model_state as npu_ms + + monkeypatch.setattr(npu_ms, "NPUFishOmniModelState", lambda *args, **kwargs: sentinel) + assert ms.create_fish_omni_model_state(None, None, None, SimpleNamespace(type="npu")) is sentinel + + +def test_cuda_device_keeps_the_upstream_model_state(monkeypatch): + monkeypatch.setattr(ms.FishOmniModelState, "__init__", lambda self, *args, **kwargs: None) + state = ms.create_fish_omni_model_state(None, None, None, SimpleNamespace(type="cuda")) + assert type(state) is ms.FishOmniModelState + assert not getattr(state, "uses_ascend_attn_metadata", False) + + +def test_sampling_noise_is_broadcast_across_tensor_parallel_ranks(make_state): + state = make_state() + state.add_request(0, _request("s", seed=1)) + seen = {} + + def broadcast(tensor, src=0): + seen["src"] = src + seen["shape"] = tuple(tensor.shape) + return tensor + + with ( + patch.object(ms, "_broadcast_tp_tensor", side_effect=lambda tensor: seen.update(called=True) or None), + ): + state._draw_noise(["s"], np.array([1]), np.array([True])) + assert seen["called"] is True + + with ( + patch("vllm.distributed.parallel_state.model_parallel_is_initialized", return_value=True), + patch("vllm.distributed.parallel_state.get_tensor_model_parallel_world_size", return_value=2), + patch("vllm.distributed.parallel_state.get_tp_group") as group, + ): + group.return_value.broadcast = broadcast + ms._broadcast_tp_tensor(state.buffers.noise) + assert seen["src"] == 0 + assert seen["shape"] == tuple(state.buffers.noise.shape) diff --git a/tests/model_executor/models/fish_omni/test_fish_omni_quantization.py b/tests/model_executor/models/fish_omni/test_fish_omni_quantization.py index 1a2bae04f0f..9b02d072720 100644 --- a/tests/model_executor/models/fish_omni/test_fish_omni_quantization.py +++ b/tests/model_executor/models/fish_omni/test_fish_omni_quantization.py @@ -2,13 +2,20 @@ # SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project """CPU tests for the Drama 3 ``bsgemm-moe`` quantization config.""" +import sys +import types +from collections.abc import Mapping +from types import SimpleNamespace from unittest.mock import MagicMock import pytest +import torch from vllm.model_executor.layers.linear import LinearBase, UnquantizedLinearMethod from vllm.model_executor.layers.quantization import fp8, get_quantization_config +from vllm_omni.model_executor.models.fish_omni import quantization from vllm_omni.model_executor.models.fish_omni.quantization import QUANTIZATION_METHOD, ExpertFp8Config +from vllm_omni.platforms.npu.quant import fish_omni as npu_quantization pytestmark = [pytest.mark.core_model, pytest.mark.cpu] @@ -19,6 +26,27 @@ } +def _install_fake_ascend(monkeypatch, **modules: Mapping[str, object]) -> None: + """Stub the vllm_ascend attributes ``get_fish_omni_quant_method`` imports.""" + packages = {name.rsplit(".", 1)[0] for name in modules} + packages |= {parent for name in packages for parent in _ancestors(name)} + for name in sorted(packages): + if name not in sys.modules: + package = types.ModuleType(name) + package.__path__ = [] # mark it importable as a package + monkeypatch.setitem(sys.modules, name, package) + for module_name, attrs in modules.items(): + module = types.ModuleType(module_name) + for attr, value in attrs.items(): + setattr(module, attr, value) + monkeypatch.setitem(sys.modules, module_name, module) + + +def _ancestors(dotted: str) -> list[str]: + parts = dotted.split(".") + return [".".join(parts[:i]) for i in range(1, len(parts))] + + def test_registered_with_vllm(): assert get_quantization_config(QUANTIZATION_METHOD) is ExpertFp8Config @@ -45,13 +73,31 @@ def test_rejects_unsupported_checkpoint_config(override): ExpertFp8Config.from_config({**CHECKPOINT_QUANT_CONFIG, **override}) -def test_linear_layers_stay_unquantized(): +def test_linear_layers_stay_unquantized(monkeypatch): + monkeypatch.setattr(quantization, "current_platform", SimpleNamespace(device_type="cuda")) config = ExpertFp8Config.from_config(CHECKPOINT_QUANT_CONFIG) method = config.get_quant_method(MagicMock(spec=LinearBase), prefix="model.layers.0.self_attn.qkv_proj") assert isinstance(method, UnquantizedLinearMethod) +def test_npu_linear_layers_use_the_ascend_unquantized_method(monkeypatch): + """The generic method skips Ascend's FRACTAL_NZ conversion and GEMM op.""" + monkeypatch.setattr(quantization, "current_platform", SimpleNamespace(device_type="npu")) + + class _AscendUnquantizedLinearMethod(UnquantizedLinearMethod): + pass + + _install_fake_ascend( + monkeypatch, + **{"vllm_ascend.ops.linear": {"AscendUnquantizedLinearMethod": _AscendUnquantizedLinearMethod}}, + ) + config = ExpertFp8Config.from_config(CHECKPOINT_QUANT_CONFIG) + method = config.get_quant_method(MagicMock(spec=LinearBase), prefix="model.layers.0.self_attn.qkv_proj") + assert isinstance(method, _AscendUnquantizedLinearMethod) + + def test_routed_experts_use_fp8_moe(monkeypatch): + monkeypatch.setattr(quantization, "current_platform", SimpleNamespace(device_type="cuda")) sentinel = object() created = [] @@ -64,3 +110,90 @@ def fake_moe_method(quant_config, layer): experts = MagicMock(spec=fp8.RoutedExperts) assert config.get_quant_method(experts, prefix="model.layers.0.mlp.experts") is sentinel assert created == [(config, experts)] + + +def test_npu_routed_experts_use_ascend_fp8(monkeypatch): + monkeypatch.setattr(quantization, "current_platform", SimpleNamespace(device_type="npu")) + monkeypatch.setattr(npu_quantization, "_dequantize_npu_block_fp8_on_cpu", lambda method: None) + sentinel = object() + seen = {} + + class _AscendFp8Config: + def __init__(self, **kwargs): + seen["kwargs"] = kwargs + + def get_quant_method(self, layer, prefix, tid2eid=None): + seen["prefix"] = prefix + seen["tid2eid"] = tid2eid + return sentinel + + _install_fake_ascend( + monkeypatch, + **{ + "vllm_ascend.ops.linear": {"AscendUnquantizedLinearMethod": UnquantizedLinearMethod}, + "vllm_ascend.quantization.configs.fp8_config": {"AscendFp8Config": _AscendFp8Config}, + }, + ) + + config = ExpertFp8Config.from_config(CHECKPOINT_QUANT_CONFIG) + experts = MagicMock(spec=fp8.RoutedExperts) + tid2eid = object() + assert config.get_quant_method(experts, prefix="model.layers.0.mlp.experts", tid2eid=tid2eid) is sentinel + assert seen["prefix"] == "model.layers.0.mlp.experts" + assert seen["tid2eid"] is tid2eid + assert seen["kwargs"]["is_checkpoint_fp8_serialized"] is True + assert seen["kwargs"]["weight_block_size"] == [128, 128] + + +def _expert_layer() -> torch.nn.Module: + layer = torch.nn.Module() + layer.register_parameter("weight", torch.nn.Parameter(torch.ones(1, 2, 4), requires_grad=False)) + layer.register_parameter("scale", torch.nn.Parameter(torch.tensor([[[2.0, 3.0]]]), requires_grad=False)) + return layer + + +def test_cpu_dequant_override_is_scoped_to_selected_scheme(monkeypatch): + """One scheme instance delegates to upstream on the host; nothing else changes. + + The device round trip itself needs an Ascend card; this covers the scoping + and that the upstream expansion runs with host-resident parameters. + """ + expanded = torch.zeros(1, 2, 4, dtype=torch.bfloat16) + seen: dict[str, tuple[object, ...]] = {} + + class Scheme: + def _resolve_experts(self, layer, weight_name, scale_name): + seen["args"] = (layer, weight_name, scale_name) + seen["devices"] = (getattr(layer, weight_name).device.type, getattr(layer, scale_name).device.type) + return expanded + + selected, other = Scheme(), Scheme() + original = Scheme._resolve_experts + + class AscendConfig: + def __init__(self, **kwargs): + pass + + def get_quant_method(self, layer, prefix, tid2eid=None): + return SimpleNamespace(quant_method=selected) + + _install_fake_ascend( + monkeypatch, + **{ + "vllm_ascend.ops.linear": {"AscendUnquantizedLinearMethod": UnquantizedLinearMethod}, + "vllm_ascend.quantization.configs.fp8_config": {"AscendFp8Config": AscendConfig}, + "vllm_ascend.quantization.methods.w8a8.fp8_block": {"AscendFp8BlockFusedMoEMethod": Scheme}, + }, + ) + monkeypatch.setattr(quantization, "current_platform", SimpleNamespace(device_type="npu")) + config = ExpertFp8Config.from_config(CHECKPOINT_QUANT_CONFIG) + config.get_quant_method(torch.nn.Module(), "model.layers.0.mlp.experts") + + assert Scheme._resolve_experts is original + assert other._resolve_experts(_expert_layer(), "weight", "scale") is expanded + + layer = _expert_layer() + assert torch.equal(selected._resolve_experts(layer, "weight", "scale"), expanded) + assert seen["args"] == (layer, "weight", "scale") + assert seen["devices"] == ("cpu", "cpu") + npu_quantization._dequantize_npu_block_fp8_on_cpu(None) diff --git a/tests/platforms/npu/test_fish_omni_preemption.py b/tests/platforms/npu/test_fish_omni_preemption.py new file mode 100644 index 00000000000..666d27f0774 --- /dev/null +++ b/tests/platforms/npu/test_fish_omni_preemption.py @@ -0,0 +1,33 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project +"""Exercise Drama 3 preemption with native NPU history buffers.""" + +import pytest +import torch + +pytest.importorskip("torch_npu") + +from tests.helpers.mark import hardware_marks +from tests.model_executor.models.fish_omni.test_fish_omni_model_state import ( + make_state as make_state, +) +from tests.model_executor.models.fish_omni.test_fish_omni_model_state import ( + test_preempted_request_resumes_with_its_generated_frames as check_resume, +) + +pytestmark = [pytest.mark.core_model, *hardware_marks(res={"npu": "A2"}, num_cards=1)] + + +def test_npu_history_survives_preemption_and_slot_reuse(make_state): # noqa: F811 - imported pytest fixture + if not torch.npu.is_available(): + pytest.skip("NPU is unavailable") + + def make_npu_state(): + state = make_state() + state.device = torch.device("npu") + state.buffers.slot_history = state.buffers.slot_history.to(state.device) + state.buffers.slot_generated = state.buffers.slot_generated.to(state.device) + assert not state.buffers.slot_history.is_cuda + return state + + check_resume(make_npu_state) diff --git a/tests/platforms/npu/test_mamba_compat.py b/tests/platforms/npu/test_mamba_compat.py new file mode 100644 index 00000000000..ffbb809ae11 --- /dev/null +++ b/tests/platforms/npu/test_mamba_compat.py @@ -0,0 +1,75 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project + +import builtins +from typing import Any + +import pytest + +from vllm_omni.platforms.npu.mamba_compat import _install_prefill_end_shim + +pytestmark = [pytest.mark.core_model, pytest.mark.cpu] + + +@pytest.mark.parametrize("error_type", [ImportError, RuntimeError]) +def test_mamba_import_only_ignores_missing_dependencies(monkeypatch, error_type): + from vllm_omni.platforms.npu import mamba_compat + + original_import = builtins.__import__ + error = error_type("Ascend allocator import failed") + + def import_module(name, *args, **kwargs): + if name == "vllm_ascend.patch.platform.patch_mamba_manager": + raise error + return original_import(name, *args, **kwargs) + + with monkeypatch.context() as context: + context.setattr(builtins, "__import__", import_module) + if error_type is ImportError: + mamba_compat._install_ascend_mamba_prefill_end_compat() + else: + with pytest.raises(RuntimeError) as caught: + mamba_compat._install_ascend_mamba_prefill_end_compat() + assert caught.value is error + + +def test_prefill_end_shim_wraps_only_the_old_signature(): + class _Old: + def get_num_blocks_to_allocate(self, num_tokens: int) -> int: + return num_tokens + + class _Named: + def get_num_blocks_to_allocate(self, num_tokens: int, prefill_end: int = 0) -> int: + return num_tokens + prefill_end + + class _VarKeyword: + def get_num_blocks_to_allocate(self, num_tokens: int, **kwargs: Any) -> int: + return num_tokens + int(kwargs["prefill_end"]) + + assert _install_prefill_end_shim(_Old) is True + # The wrapper accepts the keyword the original method rejects. + assert getattr(_Old(), "get_num_blocks_to_allocate")(4, prefill_end=7) == 4 + # A second install must not stack another wrapper around the one that already drops the argument. + assert _install_prefill_end_shim(_Old) is False + assert getattr(_Old(), "get_num_blocks_to_allocate")(4, prefill_end=7) == 4 + + assert _install_prefill_end_shim(_Named) is False + assert _Named().get_num_blocks_to_allocate(4, prefill_end=7) == 11 + + assert _install_prefill_end_shim(_VarKeyword) is False + assert _VarKeyword().get_num_blocks_to_allocate(4, prefill_end=7) == 11 + + +def test_only_npu_platform_installs_mamba_compat(monkeypatch): + from vllm_omni.platforms.interface import OmniPlatform + from vllm_omni.platforms.npu import mamba_compat + + pytest.importorskip("vllm_ascend") + from vllm_omni.platforms.npu.platform import NPUOmniPlatform + + calls = [] + monkeypatch.setattr(mamba_compat, "_install_ascend_mamba_prefill_end_compat", lambda: calls.append("npu")) + OmniPlatform.prepare_stage_engine() + assert calls == [] + NPUOmniPlatform.prepare_stage_engine() + assert calls == ["npu"] diff --git a/tests/platforms/npu/test_npu_v2_moe_comm_context.py b/tests/platforms/npu/test_npu_v2_moe_comm_context.py new file mode 100644 index 00000000000..e6813188fc9 --- /dev/null +++ b/tests/platforms/npu/test_npu_v2_moe_comm_context.py @@ -0,0 +1,46 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project +"""V2 MoE communication fields survive being stored on the forward context.""" + +from types import SimpleNamespace + +import pytest + +pytest.importorskip("vllm_ascend") + +from vllm_omni.platforms.npu.worker.npu_omni_v2_model_runner import ( + resolve_registered_moe_comm_method, + v2_extra_forward_attr, +) + +pytestmark = [pytest.mark.core_model, pytest.mark.cpu] + +_EXTRA = ("moe_comm_type", "moe_comm_method", "in_profile_run") + + +def test_v2_extra_reads_attribute_when_the_dict_omits_it(): + ctx = SimpleNamespace(additional_kwargs={}, moe_comm_type="alltoall") + assert v2_extra_forward_attr(ctx, "moe_comm_type", _EXTRA) == "alltoall" + + +def test_v2_extra_prefers_an_explicit_dict_value(): + ctx = SimpleNamespace(additional_kwargs={"moe_comm_type": "mc2"}, moe_comm_type="alltoall") + assert v2_extra_forward_attr(ctx, "moe_comm_type", _EXTRA) == "mc2" + + +def test_unshaped_lookup_uses_the_only_registered_method(): + method = object() + methods = {("alltoall", (256, 128)): method} + assert resolve_registered_moe_comm_method(methods, "alltoall", (0, 0)) is method + assert resolve_registered_moe_comm_method(methods, "allgather", (0, 0)) is None + + +def test_unshaped_lookup_stays_unset_when_shapes_differ(): + methods = {("alltoall", (256, 128)): object(), ("alltoall", (64, 32)): object()} + assert resolve_registered_moe_comm_method(methods, "alltoall", (0, 0)) is None + + +def test_v2_extra_rejects_unknown_names(): + ctx = SimpleNamespace(additional_kwargs={}) + with pytest.raises(AttributeError, match="not extra"): + v2_extra_forward_attr(ctx, "not_an_extra", _EXTRA) diff --git a/tests/platforms/npu/test_npu_worker_runner_selection.py b/tests/platforms/npu/test_npu_worker_runner_selection.py new file mode 100644 index 00000000000..e68001b6960 --- /dev/null +++ b/tests/platforms/npu/test_npu_worker_runner_selection.py @@ -0,0 +1,30 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project +"""The stage runner selection overrides the upstream environment default.""" + +from types import SimpleNamespace + +import pytest + +pytest.importorskip("vllm_ascend") + +from vllm_omni.platforms.npu.worker.base import NPUWorker, OmniNPUWorkerBase + +pytestmark = [pytest.mark.core_model, pytest.mark.cpu] + + +@pytest.mark.parametrize("upstream_v2", [False, True]) +@pytest.mark.parametrize("stage_v2", [False, True, None]) +def test_stage_runner_overrides_upstream_default(monkeypatch, upstream_v2, stage_v2): + model_config = SimpleNamespace() + if stage_v2 is not None: + model_config.use_v2_model_runner = stage_v2 + config = SimpleNamespace(model_config=model_config, profiler_config=None) + + def init_upstream(worker): + worker.vllm_config = config + worker.use_v2_model_runner = upstream_v2 + + monkeypatch.setattr(NPUWorker, "__init__", init_upstream) + worker = OmniNPUWorkerBase() + assert worker.use_v2_model_runner is (stage_v2 is True) diff --git a/vllm_omni/config/stage_config.py b/vllm_omni/config/stage_config.py index 9b2a71bab6d..ee0297be4e6 100644 --- a/vllm_omni/config/stage_config.py +++ b/vllm_omni/config/stage_config.py @@ -1132,6 +1132,14 @@ def _extract_platform_overrides(ps: dict[str, Any]) -> PlatformOverrides: return PlatformOverrides(overrides, ps.get("devices"), ps.get("env")) +# Why a platform still rejects Model Runner V2. CUDA API aliases alone do not +# adapt a platform worker, so an entry is removed only with the real integration. +# NPU AR stages use the Ascend V2 runner (attention metadata and input state). +_MRV2_UNSUPPORTED_PLATFORMS = { + "xpu": "the platform worker still uses the legacy chunk-transfer data plane", +} + + def _apply_platform_overrides( deploy: DeployConfig, platform: str | None = None, @@ -1208,11 +1216,9 @@ def _apply_platform_overrides( if stage.model_runner is not None and stage.model_runner not in ("v1", "v2"): raise ValueError(f"stage {stage.stage_id}: model_runner must be 'v1' or 'v2', got {stage.model_runner!r}") uses_v2 = deploy.model_runner == "v2" or any(stage.model_runner == "v2" for stage in deploy.stages) - if uses_v2 and platform in {"npu", "xpu"}: - raise NotImplementedError( - f"Model Runner V2 is not supported on {platform.upper()}: " - "the platform worker still uses the legacy chunk-transfer data plane." - ) + reason = _MRV2_UNSUPPORTED_PLATFORMS.get(platform) if uses_v2 else None + if reason is not None: + raise NotImplementedError(f"Model Runner V2 is not supported on {platform.upper()}: {reason}.") return deploy diff --git a/vllm_omni/deploy/fish_omni.yaml b/vllm_omni/deploy/fish_omni.yaml index 97f3cb79539..c962214289b 100644 --- a/vllm_omni/deploy/fish_omni.yaml +++ b/vllm_omni/deploy/fish_omni.yaml @@ -98,3 +98,31 @@ stages: platforms: cuda: cuda_mps: true + # Stage 0 stays on Model Runner V2. The NPU AR worker builds Ascend input + # state and attention metadata. Tensor parallel shards the backbone; expert + # parallel puts 128 of the 256 routed experts on each card. vLLM-Ascend + # expands those block-FP8 experts to bf16: 256 x 40 x (2 x 512 x 2048 + + # 512 x 2048) = 32.2B params, 64.4 GiB in all, 32.2 GiB on each rank, plus + # a few GiB of sharded non-expert weights. 0.72 of a 64 GB card is 46 GiB, + # so each rank still has KV and activation headroom. The DAC stage shares + # the second card; its 0.10 budget (6.4 GiB) fits in the 18 GiB that 0.72 + # leaves there. Stage 0 replays piecewise ACL graphs. V2 must see the + # MoE communication method that set_ascend_forward_context stores on the + # forward context, or expert-parallel capture asserts. No MPS on NPU. + npu: + stages: + - stage_id: 0 + gpu_memory_utilization: 0.72 + enforce_eager: false + tensor_parallel_size: 2 + enable_expert_parallel: true + max_num_seqs: 64 + max_num_batched_tokens: 4096 + compilation_config: + cudagraph_mode: PIECEWISE + devices: "0,1" + - stage_id: 1 + gpu_memory_utilization: 0.10 + enforce_eager: true + max_num_seqs: 64 + devices: "1" diff --git a/vllm_omni/engine/stage_engine_core_proc.py b/vllm_omni/engine/stage_engine_core_proc.py index 6c14202d4d2..707f705b44a 100644 --- a/vllm_omni/engine/stage_engine_core_proc.py +++ b/vllm_omni/engine/stage_engine_core_proc.py @@ -40,6 +40,7 @@ maybe_apply_cfg_scheduler_patches, set_death_signal, ) +from vllm_omni.platforms import current_omni_platform logger = init_logger(__name__) @@ -139,6 +140,7 @@ class StageEngineCoreProc(EngineCoreProc): """ def __init__(self, *args: Any, **kwargs: Any) -> None: + current_omni_platform.prepare_stage_engine() super().__init__(*args, **kwargs) _bind_first_audio_sink(self.model_executor, self.output_queue, self.scheduler) if _bind_native_data_plane_ready_sink(self.model_executor, self.scheduler): diff --git a/vllm_omni/model_executor/models/fish_omni/codebook_tower.py b/vllm_omni/model_executor/models/fish_omni/codebook_tower.py index 0e310a66d01..1bfd8edcf40 100644 --- a/vllm_omni/model_executor/models/fish_omni/codebook_tower.py +++ b/vllm_omni/model_executor/models/fish_omni/codebook_tower.py @@ -31,9 +31,11 @@ from vllm.model_executor.layers.activation import SiluAndMul from vllm.model_executor.layers.attention import Attention from vllm.model_executor.layers.fused_qk_norm_rope import fused_qk_rmsnorm_rope_gate +from vllm.platforms import current_platform from vllm_omni.model_executor.models.fish_omni.configuration_fish_omni import FishOmniAudioDecoderConfig from vllm_omni.model_executor.models.fish_omni.kernels import ( + eager_qk_rmsnorm_rope_gate, gemma_rms_norm, gemma_rms_norm_table, sigmoid_gate, @@ -186,7 +188,8 @@ def forward( normed = gemma_rms_norm(mixed, self.input_layernorm.weight, eps) qkv = self.qkv_proj(normed) q_gate, k, v = qkv.split([2 * self.q_size, self.kv_size, self.kv_size], dim=-1) - q, k, gate = fused_qk_rmsnorm_rope_gate( + qk_rope = eager_qk_rmsnorm_rope_gate if current_platform.device_type == "npu" else fused_qk_rmsnorm_rope_gate + q, k, gate = qk_rope( q_gate, k, self.q_norm.weight, diff --git a/vllm_omni/model_executor/models/fish_omni/fish_omni_model.py b/vllm_omni/model_executor/models/fish_omni/fish_omni_model.py index 72c1ce7d873..9441e8582f9 100644 --- a/vllm_omni/model_executor/models/fish_omni/fish_omni_model.py +++ b/vllm_omni/model_executor/models/fish_omni/fish_omni_model.py @@ -40,6 +40,7 @@ from vllm.model_executor.models.interfaces import HasInnerState, IsHybrid from vllm.model_executor.models.qwen3_5 import Qwen3_5ForCausalLMBase, Qwen3_5Model from vllm.model_executor.models.utils import maybe_prefix +from vllm.platforms import current_platform from vllm.sequence import IntermediateTensors from vllm_omni.model_executor.models.fish_speech.dac_encoder import ( @@ -165,6 +166,21 @@ def __init__( self.noise: torch.Tensor +def _reject_unsupported_fish_parallel(parallel_config: Any) -> None: + """Drama 3 can shard the Qwen3.5 backbone (tensor parallel) and its routed + experts (expert parallel) on NPU. CUDA tensor parallel, pipeline parallel, + and prefill-context parallelism are not wired through the Omni V2 runner. + """ + if parallel_config.pipeline_parallel_size != 1: + raise NotImplementedError("fish_omni runs with one pipeline rank") + if getattr(parallel_config, "prefill_context_parallel_size", 1) != 1: + raise NotImplementedError("fish_omni does not support prefill context parallelism") + # Packed GDN decode, the replicated tower, and the per-step noise broadcast + # have been run at TP=2 only on NPU. CUDA stays single-rank until then. + if parallel_config.tensor_parallel_size != 1 and current_platform.device_type != "npu": + raise NotImplementedError("fish_omni tensor parallel is supported on NPU only") + + # The tower and frame sampling compile with the backbone (its own decorator # inlines), so mixed steps replay them in PIECEWISE graphs. @support_torch_compile( @@ -180,11 +196,7 @@ class FishOmniForConditionalGeneration(nn.Module, HasInnerState, IsHybrid): def __init__(self, *, vllm_config: VllmConfig, prefix: str = "") -> None: super().__init__() config: FishOmniConfig = vllm_config.model_config.hf_config # type: ignore[assignment] - if ( - vllm_config.parallel_config.tensor_parallel_size != 1 - or vllm_config.parallel_config.pipeline_parallel_size != 1 - ): - raise NotImplementedError("fish_omni runs with one tensor and pipeline rank") + _reject_unsupported_fish_parallel(vllm_config.parallel_config) self.vllm_config = vllm_config self.config = config self.model_path = vllm_config.model_config.model @@ -202,21 +214,33 @@ def __init__(self, *, vllm_config: VllmConfig, prefix: str = "") -> None: self.embedding_scale = 1.0 / math.sqrt(1.0 + self.backbone_codebooks) hidden_size = text_config.hidden_size + if current_platform.device_type == "npu": + # Before the backbone is built, so construction and the memory + # profile both miss the fused Triton kernel. + from vllm_omni.platforms.npu.models.fish_omni import _install_npu_eager_qk_rope + + _install_npu_eager_qk_rope() self.model = Qwen3_5Model(vllm_config=vllm_config, prefix=maybe_prefix(prefix, "model")) - if vllm_config.speculative_config is None: - # vLLM routes GDN decode through the fused-norm packed wrapper by - # default (VLLM_GDN_DECODE_KERNEL=cuda). Without speculative decoding - # it never reaches its MTP kernel and only adds copies and an - # unfusable gated norm around the standard path (vllm-project/vllm#59735): - # RTF 0.520 -> 0.512 at 128 streams with the standard path. - for module in self.model.modules(): - if getattr(module, "enable_fused_gdn_decode", False): - module.enable_fused_gdn_decode = False - # Steps with prefills: packed decode kernel, FlashInfer on the state - # pool in place, outputs written straight into the buffer. - from .gdn import install_drama3_gdn - - install_drama3_gdn(self.model) + if current_platform.device_type == "npu": + from vllm_omni.platforms.npu.models.fish_omni import _require_npu_eager_qk_rope + + _require_npu_eager_qk_rope(self.model) + # Triton tower / GDN kernels build on CUDA and ROCm; Ascend patches the Qwen class itself. + if current_platform.is_cuda_alike(): + if vllm_config.speculative_config is None: + # vLLM routes GDN decode through the fused-norm packed wrapper by + # default (VLLM_GDN_DECODE_KERNEL=cuda). Without speculative decoding + # it never reaches its MTP kernel and only adds copies and an + # unfusable gated norm around the standard path (vllm-project/vllm#59735): + # RTF 0.520 -> 0.512 at 128 streams with the standard path. + for module in self.model.modules(): + if getattr(module, "enable_fused_gdn_decode", False): + module.enable_fused_gdn_decode = False + # Steps with prefills: packed decode kernel, FlashInfer on the state + # pool in place, outputs written straight into the buffer. + from .gdn import install_drama3_gdn + + install_drama3_gdn(self.model) # Only end-of-speech and the semantic band are ever sampled: keep those # lm_head rows, which cuts the per-frame head read from 1 GB to 16 MB. @@ -292,9 +316,9 @@ def get_mamba_state_copy_func(cls): return Qwen3_5ForCausalLMBase.get_mamba_state_copy_func() def create_mrv2_model_state(self, vllm_config, encoder_cache, device): - from .model_state import FishOmniModelState + from .model_state import create_fish_omni_model_state - return FishOmniModelState(vllm_config, self, encoder_cache, device) + return create_fish_omni_model_state(vllm_config, self, encoder_cache, device) # ------------------------------------------------------------------ # Prompt diff --git a/vllm_omni/model_executor/models/fish_omni/kernels.py b/vllm_omni/model_executor/models/fish_omni/kernels.py index 9dce1af3bfc..1782b671e89 100644 --- a/vllm_omni/model_executor/models/fish_omni/kernels.py +++ b/vllm_omni/model_executor/models/fish_omni/kernels.py @@ -16,6 +16,76 @@ from vllm.triton_utils import tl, triton +def _triton_device(tensor: torch.Tensor) -> bool: + """Triton tower and sampling kernels are compiled for CUDA.""" + return tensor.device.type == "cuda" + + +def eager_qk_rmsnorm_rope_gate( + q_gate: torch.Tensor, + k: torch.Tensor, + q_weight: torch.Tensor, + k_weight: torch.Tensor, + cos_sin_cache: torch.Tensor, + positions: torch.Tensor, + eps: float, + num_q_heads: int, + num_kv_heads: int, + head_dim: int, + rotary_dim: int, + mrope_section: list[int] | tuple[int, int, int] | None = None, + norm_beta: float = 0.0, +) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]: + """Torch QK-norm + NeoX RoPE + gate split. + + The fused Triton kernel does not compile on 910B. Per-head layout is + ``[q | gate]``, RMSNorm is Gemma-style (``weight + norm_beta``), and RoPE + covers the first ``rotary_dim`` channels. + """ + tokens = q_gate.shape[0] + q_heads = q_gate.view(tokens, num_q_heads, 2 * head_dim) + query = q_heads[..., :head_dim] + gate = q_heads[..., head_dim:] + key = k.view(tokens, num_kv_heads, head_dim) + + def norm(x: torch.Tensor, weight: torch.Tensor) -> torch.Tensor: + xf = x.float() + inv_rms = torch.rsqrt(xf.pow(2).mean(dim=-1, keepdim=True) + eps) + return (xf * inv_rms * (weight.float() + norm_beta)).to(dtype=x.dtype) + + def rope(x: torch.Tensor) -> torch.Tensor: + half = rotary_dim // 2 + rot = x[..., :rotary_dim].float() + tail = x[..., rotary_dim:] + x1, x2 = rot[..., :half], rot[..., half:] + if positions.ndim == 1: + picked = cos_sin_cache.index_select(0, positions.to(torch.long)) + cos = picked[:, :half].float()[:, None, :] + sin = picked[:, half:rotary_dim].float()[:, None, :] + else: + index = torch.arange(half, device=x.device) + section_h = 0 if mrope_section is None else int(mrope_section[1]) + section_w = 0 if mrope_section is None else int(mrope_section[2]) + is_h = (index % 3 == 1) & (index < 3 * section_h) + is_w = (index % 3 == 2) & (index < 3 * section_w) + pos = positions[0].to(torch.long)[:, None].expand(tokens, half).clone() + pos[:, is_h] = positions[1].to(torch.long)[:, None] + pos[:, is_w] = positions[2].to(torch.long)[:, None] + picked = cos_sin_cache.index_select(0, pos.reshape(-1)).view(tokens, half, rotary_dim) + cos = picked[..., :half].float() + sin = picked[..., half:rotary_dim].float() + rotated = torch.cat((x1 * cos - x2 * sin, x2 * cos + x1 * sin), dim=-1).to(dtype=x.dtype) + return torch.cat((rotated, tail), dim=-1) + + query = rope(norm(query, q_weight)) + key = rope(norm(key, k_weight)) + return ( + query.reshape(tokens, num_q_heads * head_dim).contiguous(), + key.reshape(tokens, num_kv_heads * head_dim).contiguous(), + gate.reshape(tokens, num_q_heads * head_dim).contiguous(), + ) + + @triton.jit def _gemma_norm_row(x, w_ptr, offs, mask, n: tl.constexpr, eps): var = tl.sum(x * x, axis=0) / n @@ -75,6 +145,8 @@ def tower_mix_norm( out = torch.empty((rows, 2 * dim), dtype=hidden.dtype, device=hidden.device) if rows == 0: return out + if not _triton_device(hidden): + return _eager_tower_mix_norm(hidden, code, code_mask, table, extra, enorm_weight, hnorm_weight, eps, out) _mix_norm_kernel[(rows,)]( hidden, hidden.stride(0), @@ -129,6 +201,8 @@ def gemma_rms_norm( rows, dim = x.shape out = torch.empty_like(x) residual_out = torch.empty_like(x) if residual is not None else out + if rows and not _triton_device(x): + return _eager_gemma_rms_norm(x, weight, eps, residual, out, residual_out) if rows: _gemma_norm_kernel[(rows,)]( x, @@ -187,6 +261,8 @@ def gemma_rms_norm_table( rows, dim = x.shape out = torch.empty((rows, dim), dtype=x.dtype, device=x.device) residual_out = torch.empty_like(out) + if rows and not _triton_device(x): + return _eager_gemma_rms_norm_table(x, code, code_mask, table, weight, eps, out, residual_out) if rows: _table_norm_kernel[(rows,)]( x, @@ -217,8 +293,10 @@ def _sigmoid_gate_kernel(x_ptr, gate_ptr, out_ptr, n, BLOCK: tl.constexpr): def sigmoid_gate(x: torch.Tensor, gate: torch.Tensor) -> torch.Tensor: """``x * sigmoid(gate)`` for contiguous tensors of one shape.""" - out = torch.empty_like(x) n = x.numel() + if n and not _triton_device(x): + return (x.float() * torch.sigmoid(gate.float())).to(dtype=x.dtype) + out = torch.empty_like(x) if n: block = 2048 _sigmoid_gate_kernel[(triton.cdiv(n, block),)](x, gate, out, n, BLOCK=block, num_warps=4) @@ -291,6 +369,10 @@ def draw_top_k_top_p( out = torch.empty(rows, dtype=torch.int64, device=logits.device) if rows == 0: return out + if not _triton_device(logits): + return _eager_draw_top_k_top_p( + logits, temperature, top_k, top_p, uniform, max_top_k, id_map, top, min_temperature + ) if top is None: top = torch.topk(logits, max_top_k, dim=-1) values, ids = top @@ -317,4 +399,94 @@ def draw_top_k_top_p( return out +def _gemma_from_fp32(values: torch.Tensor, weight: torch.Tensor, eps: float, dtype: torch.dtype) -> torch.Tensor: + variance = (values * values).sum(dim=-1, keepdim=True) / values.shape[-1] + return (values * torch.rsqrt(variance + eps) * (weight.float() + 1.0)).to(dtype=dtype) + + +def _eager_tower_mix_norm( + hidden: torch.Tensor, + code: torch.Tensor, + code_mask: torch.Tensor, + table: torch.Tensor, + extra: torch.Tensor | None, + enorm_weight: torch.Tensor, + hnorm_weight: torch.Tensor, + eps: float, + out: torch.Tensor, +) -> torch.Tensor: + dim = hidden.shape[-1] + kept = table[code.clamp(0, table.shape[0] - 1)].float() * code_mask.float().unsqueeze(-1) + if extra is not None: + kept = kept.to(dtype=out.dtype).float() + extra.float() + kept = kept.to(dtype=out.dtype).float() + out[:, :dim] = _gemma_from_fp32(kept, enorm_weight, eps, out.dtype) + out[:, dim:] = _gemma_from_fp32(hidden.float(), hnorm_weight, eps, out.dtype) + return out + + +def _eager_gemma_rms_norm( + x: torch.Tensor, + weight: torch.Tensor, + eps: float, + residual: torch.Tensor | None, + out: torch.Tensor, + residual_out: torch.Tensor, +) -> torch.Tensor | tuple[torch.Tensor, torch.Tensor]: + summed = x.float() + if residual is not None: + summed = summed + residual.float() + residual_out.copy_(summed.to(dtype=residual_out.dtype)) + out.copy_(_gemma_from_fp32(summed, weight, eps, out.dtype)) + return (out, residual_out) if residual is not None else out + + +def _eager_gemma_rms_norm_table( + x: torch.Tensor, + code: torch.Tensor, + code_mask: torch.Tensor, + table: torch.Tensor, + weight: torch.Tensor, + eps: float, + out: torch.Tensor, + residual_out: torch.Tensor, +) -> tuple[torch.Tensor, torch.Tensor]: + kept = code_mask.float().unsqueeze(-1) + summed = x.float() + table[code.clamp(0, table.shape[0] - 1)].float() * kept + residual_out.copy_(summed.to(dtype=residual_out.dtype)) + out.copy_(_gemma_from_fp32(summed, weight, eps, out.dtype)) + return out, residual_out + + +def _eager_draw_top_k_top_p( + logits: torch.Tensor, + temperature: torch.Tensor, + top_k: torch.Tensor, + top_p: torch.Tensor, + uniform: torch.Tensor, + max_top_k: int, + id_map: torch.Tensor | None, + top: tuple[torch.Tensor, torch.Tensor] | None, + min_temperature: float, +) -> torch.Tensor: + scaled_temperature = temperature.float().clamp_min(min_temperature).unsqueeze(-1) + logits_f = logits.float() / scaled_temperature + row_max = logits_f.amax(dim=-1, keepdim=True) + total = torch.exp(logits_f - row_max).sum(dim=-1, keepdim=True) + if top is None: + values, ids = torch.topk(logits, max_top_k, dim=-1) + else: + values, ids = top + probs = torch.exp(values.float() / scaled_temperature - row_max) / total + cumulative = torch.cumsum(probs, dim=-1) + ranks = torch.arange(max_top_k, device=logits.device) + keep = ((cumulative <= top_p.float().unsqueeze(-1)) & (ranks < top_k.unsqueeze(-1))) | (ranks == 0) + noise = -torch.log(uniform[:, :max_top_k].clamp_min(1e-30)) + score = torch.where(keep, probs / noise, torch.full_like(probs, -1.0)) + token = ids.gather(-1, score.argmax(dim=-1, keepdim=True)).squeeze(-1) + if id_map is not None: + token = id_map[token] + return token.to(dtype=torch.int64) + + __all__ = ["draw_top_k_top_p", "gemma_rms_norm", "gemma_rms_norm_table", "sigmoid_gate", "tower_mix_norm"] diff --git a/vllm_omni/model_executor/models/fish_omni/model_state.py b/vllm_omni/model_executor/models/fish_omni/model_state.py index f412b106a30..819f959b2ad 100644 --- a/vllm_omni/model_executor/models/fish_omni/model_state.py +++ b/vllm_omni/model_executor/models/fish_omni/model_state.py @@ -39,6 +39,21 @@ _MASK64 = (1 << 64) - 1 +def _broadcast_tp_tensor(tensor: torch.Tensor) -> None: + """Copy ``tensor`` from tensor-parallel rank 0 when that group exists.""" + from vllm.distributed.parallel_state import ( + get_tensor_model_parallel_world_size, + get_tp_group, + model_parallel_is_initialized, + ) + + if not model_parallel_is_initialized(): + return + if get_tensor_model_parallel_world_size() <= 1: + return + get_tp_group().broadcast(tensor, src=0) + + def _frame_seed(seed: int, frame: int) -> int: """Seed of a request's ``frame``-th sampled frame (splitmix64 of seed and index).""" x = (seed * 0x9E3779B97F4A7C15 + frame + 1) & _MASK64 @@ -223,7 +238,11 @@ def on_request_preempted(self, req_id: str, req_index: int) -> None: event = torch.cuda.Event() event.record() else: - host_history, host_count = history.clone(), count.clone() + # Native NPU tensors are not CUDA tensors. Blocking host copies + # complete before the slot can be reused; copy=True also keeps CPU + # snapshots independent of the original slot storage. + host_history = history.to(device="cpu", non_blocking=False, copy=True) + host_count = count.to(device="cpu", non_blocking=False, copy=True) self._suspended[req_id] = _SuspendedRequest(host_history, host_count, event) def on_requests_finished(self, req_ids: set[str]) -> None: @@ -308,16 +327,18 @@ def _draw_noise(self, req_ids: list[str], frames: np.ndarray, sampling: np.ndarr batch row) that samples frame ``frames[row]`` draws from that frame's seed.""" noise = self.buffers.noise noise.uniform_() - if not self._seeds: - return - for row, req_id in enumerate(req_ids): - seed = self._seeds.get(req_id) - if seed is None or not sampling[row]: - continue - if self._seed_generator is None: - self._seed_generator = torch.Generator(device=noise.device) - self._seed_generator.manual_seed(_frame_seed(seed, int(frames[row]))) - noise[row].uniform_(generator=self._seed_generator) + if self._seeds: + for row, req_id in enumerate(req_ids): + seed = self._seeds.get(req_id) + if seed is None or not sampling[row]: + continue + if self._seed_generator is None: + self._seed_generator = torch.Generator(device=noise.device) + self._seed_generator.manual_seed(_frame_seed(seed, int(frames[row]))) + noise[row].uniform_(generator=self._seed_generator) + # Each tensor-parallel rank samples inside the forward. Device RNG is + # not shared, so rank 0's noise is the one every rank uses. + _broadcast_tp_tensor(noise) def run_postprocess(self, hidden_states, input_batch) -> None: self.model.num_sample_rows = None @@ -403,4 +424,13 @@ def postprocess_model_output(self, model_output: Any, input_batch, req_states): return hidden, _FrameRowsSnapshot(frames, valid, partitioned=self._partitioned) -__all__ = ["FishOmniModelState"] +def create_fish_omni_model_state(vllm_config, model, encoder_cache, device): + """CUDA keeps the upstream hybrid state; NPU builds Ascend attention metadata.""" + if getattr(device, "type", None) == "npu": + from vllm_omni.platforms.npu.models.fish_omni_model_state import NPUFishOmniModelState + + return NPUFishOmniModelState(vllm_config, model, encoder_cache, device) + return FishOmniModelState(vllm_config, model, encoder_cache, device) + + +__all__ = ["FishOmniModelState", "create_fish_omni_model_state"] diff --git a/vllm_omni/model_executor/models/fish_omni/quantization.py b/vllm_omni/model_executor/models/fish_omni/quantization.py index b0590c9737a..79a6706922c 100644 --- a/vllm_omni/model_executor/models/fish_omni/quantization.py +++ b/vllm_omni/model_executor/models/fish_omni/quantization.py @@ -11,6 +11,7 @@ from vllm.model_executor.layers.quantization import register_quantization_config from vllm.model_executor.layers.quantization.base_config import QuantizeMethodBase from vllm.model_executor.layers.quantization.fp8 import Fp8Config +from vllm.platforms import current_platform QUANTIZATION_METHOD = "bsgemm-moe" @@ -39,7 +40,13 @@ def from_config(cls, config: dict[str, Any]) -> ExpertFp8Config: raise ValueError(f"{QUANTIZATION_METHOD} needs a 2-int weight_block_size, got {block!r}") return cls(weight_block_size=[int(b) for b in block]) - def get_quant_method(self, layer: torch.nn.Module, prefix: str) -> QuantizeMethodBase | None: + def get_quant_method( + self, layer: torch.nn.Module, prefix: str, tid2eid: torch.Tensor | None = None + ) -> QuantizeMethodBase | None: + if current_platform.device_type == "npu": + from vllm_omni.platforms.npu.quant.fish_omni import get_fish_omni_quant_method + + return get_fish_omni_quant_method(self, layer, prefix, tid2eid) if isinstance(layer, LinearBase): return UnquantizedLinearMethod() return super().get_quant_method(layer, prefix) diff --git a/vllm_omni/platforms/interface.py b/vllm_omni/platforms/interface.py index dd20ddbcfc0..76d84a65ae7 100644 --- a/vllm_omni/platforms/interface.py +++ b/vllm_omni/platforms/interface.py @@ -58,6 +58,11 @@ def is_musa(self) -> bool: def is_out_of_tree(self) -> bool: return self._omni_enum == OmniPlatformEnum.OOT + @classmethod + def prepare_stage_engine(cls) -> None: + """Install platform runtime compatibility before constructing a stage engine.""" + return None + @classmethod def get_omni_ar_worker_cls(cls) -> str: raise NotImplementedError diff --git a/vllm_omni/platforms/npu/mamba_compat.py b/vllm_omni/platforms/npu/mamba_compat.py new file mode 100644 index 00000000000..0bf797682cf --- /dev/null +++ b/vllm_omni/platforms/npu/mamba_compat.py @@ -0,0 +1,58 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project +"""Ascend Mamba allocator compatibility, installed before engine construction.""" + +from typing import Any + + +def _accepts_prefill_end(method: Any) -> bool: + """Whether ``method`` can take vLLM's ``prefill_end`` keyword.""" + if getattr(method, "_omni_accepts_prefill_end", False): + return True + import inspect + + try: + parameters = inspect.signature(method).parameters + except (TypeError, ValueError): + return False + return "prefill_end" in parameters or any( + parameter.kind == inspect.Parameter.VAR_KEYWORD for parameter in parameters.values() + ) + + +def _install_prefill_end_shim(manager_cls: Any) -> bool: + """Drop ``prefill_end`` only when ``manager_cls`` would reject it. + + Returns whether a wrapper was installed. Current vLLM-Ascend accepts the + argument and forwards it; wrapping that method would change the block + count. The v0.30 signature raises on the keyword, so it still needs the shim. + """ + current = manager_cls.get_num_blocks_to_allocate + if _accepts_prefill_end(current): + return False + + def get_num_blocks_to_allocate(self: Any, *args: Any, prefill_end: int = 0, **kwargs: Any) -> int: + del prefill_end + return current(self, *args, **kwargs) + + get_num_blocks_to_allocate._omni_accepts_prefill_end = True # type: ignore[attr-defined] + manager_cls.get_num_blocks_to_allocate = get_num_blocks_to_allocate # type: ignore[method-assign] + return True + + +def _install_ascend_mamba_prefill_end_compat() -> None: + """Let an older Ascend mamba allocator accept vLLM's ``prefill_end``. + + vLLM passes ``prefill_end`` into every cache manager. Ascend's override + before that argument rejects the call, so the first Drama 3 schedule dies + before any forward. Builds that already accept the argument are left alone. + Missing imports are optional for compatibility across Ascend versions. + Other initialization failures intentionally propagate on NPU, rather than + silently continuing with a potentially broken allocator. Other platforms + do not invoke this installer. + """ + try: + from vllm_ascend.patch.platform.patch_mamba_manager import AscendMambaManager + except ImportError: + return + _install_prefill_end_shim(AscendMambaManager) diff --git a/vllm_omni/platforms/npu/models/fish_omni.py b/vllm_omni/platforms/npu/models/fish_omni.py new file mode 100644 index 00000000000..d6bf8a1a3af --- /dev/null +++ b/vllm_omni/platforms/npu/models/fish_omni.py @@ -0,0 +1,66 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project +"""Ascend-specific Drama 3 attention compatibility.""" + +from typing import Any + +from vllm.logger import init_logger + +logger = init_logger(__name__) + + +def _install_npu_eager_qk_rope() -> None: + """Keep Qwen3.5 attention off the fused Triton kernel on Ascend. + + The codebook tower selects the torch implementation itself. The backbone + takes upstream's non-fused branch: forcing the flag off in ``__init__`` + means forward never calls ``fused_qk_rmsnorm_rope_gate``. The NPU worker + reports a CUDA-like platform, so the stock constructor would otherwise + enable that kernel. The patch is process-wide on ``Qwen3NextAttention``; + this stage process builds the Drama 3 backbone, and the Triton kernel is + not valid on Ascend. + """ + import vllm.model_executor.models.qwen3_next as qwen_next + + attention = qwen_next.Qwen3NextAttention + if getattr(attention.__init__, "_fish_omni_npu_eager", False): + return + original_init = attention.__init__ + + def _eager_qk_rope_init(attn, *args, **kwargs): + original_init(attn, *args, **kwargs) + attn.use_fused_qk_norm_rope_gate = False + + _eager_qk_rope_init._fish_omni_npu_eager = True # type: ignore[attr-defined] + attention.__init__ = _eager_qk_rope_init + + +def _require_npu_eager_qk_rope(model: Any) -> None: + """Fail if any module still takes the fused Triton QK-norm path. + + The ``__init__`` patch covers ``Qwen3NextAttention``. A subclass that sets + the flag again after ``super().__init__``, or a different class that owns + the same flag, would otherwise reach the Triton kernel on Ascend. One + check after construction keeps that guarantee without a forward hook + inside the compiled region. No matching modules means the upstream flag + may have changed, so eager execution cannot be verified either. + """ + enabled: list[str] = [] + armed = 0 + for module in model.modules(): + if not hasattr(module, "use_fused_qk_norm_rope_gate"): + continue + armed += 1 + if module.use_fused_qk_norm_rope_gate: + enabled.append(type(module).__name__) + if enabled: + names = ", ".join(sorted(set(enabled))) + raise RuntimeError( + f"fish_omni: fused QK-norm RoPE stayed enabled on NPU ({names}). The Triton kernel is not valid on Ascend." + ) + if armed == 0: + raise RuntimeError( + "fish_omni: no attention modules expose use_fused_qk_norm_rope_gate on NPU. " + "Cannot verify eager QK-norm RoPE; check the upstream attention implementation." + ) + logger.info("fish_omni: eager QK-norm RoPE on NPU (%d attention modules)", armed) diff --git a/vllm_omni/platforms/npu/models/fish_omni_model_state.py b/vllm_omni/platforms/npu/models/fish_omni_model_state.py new file mode 100644 index 00000000000..981527476b4 --- /dev/null +++ b/vllm_omni/platforms/npu/models/fish_omni_model_state.py @@ -0,0 +1,34 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project +"""Drama 3 request state with Ascend hybrid attention metadata.""" + +from typing import Any + +from vllm_omni.model_executor.models.fish_omni.model_state import FishOmniModelState + + +class NPUFishOmniModelState(FishOmniModelState): + """Drama 3 request state whose attention metadata is the Ascend V2 one. + + Request slots, frame rows and sampling stay on ``FishOmniModelState``. + ``prepare_attn`` and the GDN align pre-copy come from the Ascend hybrid + state, which reads ``attn_state`` and ``seq_lens_np`` off the Ascend batch. + """ + + uses_ascend_attn_metadata = True + + def __init__(self, vllm_config, model, encoder_cache, device) -> None: + super().__init__(vllm_config, model, encoder_cache, device) + # AscendMambaHybridModelState fields used by its preprocess_state. + self._layerwise_mamba_copy = None + self._layer_state_ranges = None + + def prepare_attn(self, *args: Any, **kwargs: Any): + from vllm_ascend.worker.v2.model_states.mamba_hybrid import AscendMambaHybridModelState + + return AscendMambaHybridModelState.prepare_attn(self, *args, **kwargs) + + def preprocess_state(self, *args: Any, **kwargs: Any): + from vllm_ascend.worker.v2.model_states.mamba_hybrid import AscendMambaHybridModelState + + return AscendMambaHybridModelState.preprocess_state(self, *args, **kwargs) diff --git a/vllm_omni/platforms/npu/platform.py b/vllm_omni/platforms/npu/platform.py index 2f421c76229..d4da7f6cce3 100644 --- a/vllm_omni/platforms/npu/platform.py +++ b/vllm_omni/platforms/npu/platform.py @@ -159,6 +159,12 @@ def set_device(cls, device: torch.device) -> None: # is preserved for fused NPU kernels. torch.npu.config.allow_internal_format = True + @classmethod + def prepare_stage_engine(cls) -> None: + from vllm_omni.platforms.npu.mamba_compat import _install_ascend_mamba_prefill_end_compat + + _install_ascend_mamba_prefill_end_compat() + @classmethod def get_omni_ar_worker_cls(cls) -> str: return "vllm_omni.platforms.npu.worker.npu_ar_worker.NPUARWorker" diff --git a/vllm_omni/platforms/npu/quant/fish_omni.py b/vllm_omni/platforms/npu/quant/fish_omni.py new file mode 100644 index 00000000000..7a589e04f3b --- /dev/null +++ b/vllm_omni/platforms/npu/quant/fish_omni.py @@ -0,0 +1,75 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project +"""Ascend block-FP8 experts and linear methods for Drama 3.""" + +from types import MethodType + +import torch +from vllm.model_executor.layers.linear import LinearBase +from vllm.model_executor.layers.quantization.base_config import QuantizeMethodBase +from vllm.model_executor.layers.quantization.fp8 import Fp8Config + + +def _resolve_experts_on_cpu(self, layer: torch.nn.Module, weight_name: str, scale_name: str) -> torch.Tensor: + """Expand this method's expert tensor on the host, then return it on the device. + + Upstream expands in place on the device, so the FP8 expert stack and its + bfloat16 expansion are resident together; on a 64 GB 910B that peak aborts + the load. Moving both parameters to the host first releases the FP8 device + storage before the expansion allocates, leaving only the expanded tensor on + the device. The expansion itself stays with the upstream implementation, + which keeps its block-scale shape validation and its bounded FP32 staging. + """ + from vllm_ascend.quantization.methods.w8a8.fp8_block import AscendFp8BlockFusedMoEMethod + + weight_param = getattr(layer, weight_name) + scale_param = getattr(layer, scale_name) + device = weight_param.device + weight_param.data = weight_param.data.to("cpu") + scale_param.data = scale_param.data.to("cpu") + if device.type == "npu": + torch.npu.empty_cache() + resolved = AscendFp8BlockFusedMoEMethod._resolve_experts(self, layer, weight_name, scale_name) + return resolved.to(device=device) + + +def _dequantize_npu_block_fp8_on_cpu(method: QuantizeMethodBase | None) -> None: + """Scope the CPU expansion workaround to this Drama 3 quantization method. + + Ascend's adapter owns the block-FP8 scheme in ``quant_method``. Override + only that instance; other models and the Atlas 950 MXFP8 path retain + their upstream implementation. + """ + from vllm_ascend.quantization.methods.w8a8.fp8_block import AscendFp8BlockFusedMoEMethod + + scheme = getattr(method, "quant_method", None) + if isinstance(scheme, AscendFp8BlockFusedMoEMethod): + scheme._resolve_experts = MethodType(_resolve_experts_on_cpu, scheme) + + +def get_fish_omni_quant_method( + config: Fp8Config, layer: torch.nn.Module, prefix: str, tid2eid: torch.Tensor | None +) -> QuantizeMethodBase | None: + """Ascend's own methods: block-FP8 routed experts, bf16 Ascend linears. + + CUDA's ``Fp8MoEMethod`` selects no Ascend kernel (``Fp8MoeBackend.NONE``), + and the generic ``UnquantizedLinearMethod`` would skip the FRACTAL_NZ + weight conversion and the Ascend GEMM that ``AscendLinearBase`` installs + for an unquantized checkpoint, so both sides need the vLLM-Ascend + implementation. + """ + # Delayed imports: vllm_ascend exists only on an Ascend host. + if isinstance(layer, LinearBase): + from vllm_ascend.ops.linear import AscendUnquantizedLinearMethod + + return AscendUnquantizedLinearMethod() + from vllm_ascend.quantization.configs.fp8_config import AscendFp8Config + + npu_config = AscendFp8Config( + is_checkpoint_fp8_serialized=config.is_checkpoint_fp8_serialized, + activation_scheme=config.activation_scheme, + weight_block_size=config.weight_block_size, + ) + method = npu_config.get_quant_method(layer, prefix, tid2eid=tid2eid) + _dequantize_npu_block_fp8_on_cpu(method) + return method diff --git a/vllm_omni/platforms/npu/worker/base.py b/vllm_omni/platforms/npu/worker/base.py index ec376421adc..98f6bf06fdf 100644 --- a/vllm_omni/platforms/npu/worker/base.py +++ b/vllm_omni/platforms/npu/worker/base.py @@ -23,6 +23,12 @@ class OmniNPUWorkerBase(NPUWorker): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) + # Ascend inherits vLLM's global runner default (V2 in vLLM 0.32), + # while Omni resolves the runner independently for each deploy stage. + # Keep runner construction and inherited worker lifecycle methods on + # the same stage-selected path, including mixed V2 AR / V1 DAC deploys. + self.use_v2_model_runner = bool(getattr(self.vllm_config.model_config, "use_v2_model_runner", False)) + # Replace vllm-ascend's profiler with OmniProfiler profiler_config = self.vllm_config.profiler_config if profiler_config and profiler_config.profiler == "torch": diff --git a/vllm_omni/platforms/npu/worker/npu_ar_worker.py b/vllm_omni/platforms/npu/worker/npu_ar_worker.py index 6a0b5424755..17ccccd4bee 100644 --- a/vllm_omni/platforms/npu/worker/npu_ar_worker.py +++ b/vllm_omni/platforms/npu/worker/npu_ar_worker.py @@ -1,6 +1,7 @@ # SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project +from vllm.logger import init_logger from vllm.v1.worker.workspace import init_workspace_manager from vllm_omni.platforms.npu.ascend_warmup_patch import apply_ascend_warmup_patch @@ -8,6 +9,8 @@ from vllm_omni.platforms.npu.worker.npu_ar_model_runner import NPUARModelRunner from vllm_omni.worker.mixins import OmniWorkerMixin +logger = init_logger(__name__) + # Install at import time: this module is imported while the stage worker is # built, which is earlier than the ascend Triton kernel warmup (that runs # after load_model in the same process). The guard resolves the SoC per call, @@ -26,4 +29,10 @@ def init_device(self): num_ubatches = 1 init_workspace_manager(self.device, num_ubatches) - self.model_runner = self.model_runner_cls(self.vllm_config, self.device) + if self.use_v2_model_runner: + from vllm_omni.platforms.npu.worker.npu_omni_v2_model_runner import NPUOmniARModelRunner + + logger.info("Using MR v2 NPUOmniARModelRunner on NPU.") + self.model_runner = NPUOmniARModelRunner(self.vllm_config, self.device) + else: + self.model_runner = self.model_runner_cls(self.vllm_config, self.device) diff --git a/vllm_omni/platforms/npu/worker/npu_generation_worker.py b/vllm_omni/platforms/npu/worker/npu_generation_worker.py index fad66915df5..75fe44e6856 100644 --- a/vllm_omni/platforms/npu/worker/npu_generation_worker.py +++ b/vllm_omni/platforms/npu/worker/npu_generation_worker.py @@ -19,6 +19,14 @@ class NPUGenerationWorker(OmniWorkerMixin, OmniNPUWorkerBase): model_runner_cls = NPUGenerationModelRunner def init_device(self): + # vLLM 0.32 treats an unset VLLM_USE_V2_MODEL_RUNNER as V2. The stage + # deploy field is stored on the Omni model config, so read that instead + # of the platform-wide property. + if bool(getattr(self.vllm_config.model_config, "use_v2_model_runner", False)): + raise NotImplementedError( + "NPU generation stages do not support model_runner v2; set model_runner: v1 for this stage" + ) + self.device = self._init_device() num_ubatches = 1 init_workspace_manager(self.device, num_ubatches) diff --git a/vllm_omni/platforms/npu/worker/npu_omni_v2_model_runner.py b/vllm_omni/platforms/npu/worker/npu_omni_v2_model_runner.py new file mode 100644 index 00000000000..f770ddb55a4 --- /dev/null +++ b/vllm_omni/platforms/npu/worker/npu_omni_v2_model_runner.py @@ -0,0 +1,230 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project +"""Omni autoregressive runner on Ascend Model Runner V2. + +``OmniARModelRunner`` owns the speech lifecycle (frame outputs, connectors). +``NPUModelRunner`` owns Ascend input state (``AscendRequestState``, +``AscendInputBuffers``, ``AscendInputBatch``) and puts ``attn_state`` plus +``seq_lens_np`` on that batch. The model's NPU state reads those fields when +it builds attention metadata, and the forward runs under +``set_ascend_forward_context`` so MoE communication and Ascend attention see +the same step. +""" + +from __future__ import annotations + +from collections.abc import Callable +from typing import Any + +from vllm.logger import init_logger +from vllm_ascend.worker.v2.model_runner import NPUModelRunner + +from vllm_omni.worker_v2.omni_ar_model_runner import OmniARModelRunner +from vllm_omni.worker_v2.omni_model_runner import OmniGPUModelRunner + +logger = init_logger(__name__) + + +def _call_without_unknown_kwargs(function: Callable[..., Any], *args: Any, **kwargs: Any) -> Any: + """Drop keyword arguments ``function`` does not accept. + + vLLM 0.32 takes graph-support info as ``additional_attn_cg_support``. + vLLM-Ascend v0.30 also passed ``attn_cg_support``, a different object + (the narrowed backend support). That name is obsolete and is dropped. + Renaming it onto ``additional_attn_cg_support`` would overwrite the tuple + the caller already passes under the accepted name. + """ + import inspect + + accepted = inspect.signature(function).parameters + if any(parameter.kind == inspect.Parameter.VAR_KEYWORD for parameter in accepted.values()): + return function(*args, **kwargs) + return function(*args, **{name: value for name, value in kwargs.items() if name in accepted}) + + +def _install_pcp_partition_stub() -> None: + """No-op PCP partition when this vLLM build has no helper. + + Ascend's V2 ``prepare_inputs`` always calls + ``pcp.maybe_partition_pcp_batch``. Drama 3 does not use prefill context + parallel, so returning the batch unchanged is the right behavior when the + helper is absent. + """ + import vllm.v1.worker.gpu.model_runner as model_runner + + pcp = getattr(model_runner, "pcp", None) + if pcp is None or hasattr(pcp, "maybe_partition_pcp_batch"): + return + + def maybe_partition_pcp_batch(pcp_manager: Any, input_batch: Any, batch_desc: Any = None) -> Any: + del pcp_manager, batch_desc + return input_batch + + pcp.maybe_partition_pcp_batch = maybe_partition_pcp_batch + + +def v2_extra_forward_attr(ctx: Any, name: str, extra_attrs: tuple[str, ...]) -> Any: + """Read an Ascend extra from the V2 dict, then from the context object. + + ``set_ascend_forward_context`` assigns ``moe_comm_type`` on the forward + context. Model Runner V2's proxy only consults ``additional_kwargs``, so + expert-parallel MoE sees no communication method while an ACL graph is + captured and aborts. A value stored in the dict still wins. + """ + if name not in extra_attrs: + raise AttributeError( + f"{name} is not extra forward context attribute, please get/set it from vllm's _forward_context directly." + ) + extra = getattr(ctx, "additional_kwargs", None) + if isinstance(extra, dict) and name in extra: + return extra[name] + return getattr(ctx, name, None) + + +def resolve_registered_moe_comm_method( + methods: dict[tuple[Any, tuple[int, ...]], Any], + moe_comm_type: Any, + expert_shape: tuple[int, ...], +) -> Any: + """Find the comm implementation for this expert shape. + + The forward context asks before it has a layer, so the shape is ``(0, 0)``. + One registered shape for that communication type is unambiguous. Several + shapes stay unresolved and the layer looks itself up with its own config. + """ + found = methods.get((moe_comm_type, expert_shape)) + if found is not None or expert_shape != (0, 0): + return found + matches = [method for (comm_type, _shape), method in methods.items() if comm_type == moe_comm_type] + if len(matches) == 1: + return matches[0] + return None + + +def _install_v2_moe_comm_context() -> None: + """Let V2 reads see MoE fields assigned on the forward context.""" + import vllm_ascend.ops.fused_moe.moe_comm_method as moe_comm + from vllm_ascend.ascend_forward_context import _ExtraForwardContextProxy + + if not getattr(_ExtraForwardContextProxy.__getattr__, "_omni_moe_comm_fallback", False): + extra_attrs = _ExtraForwardContextProxy.extra_attrs + + def _proxy_getattr(self: Any, name: str) -> Any: + return v2_extra_forward_attr(self._ctx(), name, extra_attrs) + + _proxy_getattr._omni_moe_comm_fallback = True # type: ignore[attr-defined] + _ExtraForwardContextProxy.__getattr__ = _proxy_getattr # type: ignore[method-assign] + + if getattr(moe_comm.get_moe_comm_method, "_omni_shape_fallback", False): + return + original = moe_comm.get_moe_comm_method + + def get_moe_comm_method(moe_comm_type: Any, moe_config: Any = None) -> Any: + resolved = original(moe_comm_type, moe_config) + if resolved is not None or moe_config is not None: + return resolved + return resolve_registered_moe_comm_method(moe_comm._MoECommMethods, moe_comm_type, (0, 0)) + + get_moe_comm_method._omni_shape_fallback = True # type: ignore[attr-defined] + moe_comm.get_moe_comm_method = get_moe_comm_method + + +def _default_ascend_decode_graph_flag() -> None: + """Ascend's input batch predates vLLM's required ``decode_graph_eligible``.""" + from vllm_ascend.worker.v2.input_batch import AscendInputBatch + + init = AscendInputBatch.__init__ + if getattr(init, "_omni_default_graph_flag", False): + return + + def wrapped(self, *args: Any, **kwargs: Any) -> None: + kwargs.setdefault("decode_graph_eligible", False) + init(self, *args, **kwargs) + + wrapped._omni_default_graph_flag = True # type: ignore[attr-defined] + AscendInputBatch.__init__ = wrapped # type: ignore[method-assign] + + +class NPUOmniARModelRunner(OmniARModelRunner, NPUModelRunner): + """Drama 3 (and any other NPU-ready AR model) on Model Runner V2.""" + + def __init__(self, *args: Any, **kwargs: Any) -> None: + _default_ascend_decode_graph_flag() + _install_pcp_partition_stub() + _install_v2_moe_comm_context() + super().__init__(*args, **kwargs) + + def prepare_inputs( + self, + scheduler_output: Any, + batch_req_state: Any, + batch_desc: Any, + num_active_loras: int = 0, + ) -> Any: + # vLLM 0.32's Ascend batch builder takes the LoRA count itself. + return NPUModelRunner.prepare_inputs( + self, + scheduler_output, + batch_req_state, + batch_desc, + num_active_loras, + ) + + def _make_dummy_input_batch( + self, + num_reqs: int, + num_tokens: int, + *, + max_query_len: int | None, + is_padding: bool, + ) -> Any: + del is_padding # Ascend's dummy batch marks itself and fills seq_lens_np. + from vllm_ascend.worker.v2.input_batch import AscendInputBatch + + return AscendInputBatch.make_dummy( + num_reqs, + num_tokens, + self.input_buffers, + max_query_len=max_query_len, + ) + + def _forward_context(self, attn_metadata: Any, vllm_config: Any, **kwargs: Any): + from vllm_ascend.ascend_forward_context import set_ascend_forward_context + + if "cudagraph_runtime_mode" in kwargs: + kwargs["aclgraph_runtime_mode"] = kwargs.pop("cudagraph_runtime_mode") + # Slot maps live in the Ascend attention metadata, not this context. + kwargs.pop("slot_mapping", None) + kwargs.pop("is_padding", None) + kwargs.setdefault("model_instance", getattr(self, "model", None)) + return set_ascend_forward_context(attn_metadata, vllm_config, **kwargs) + + def initialize_kv_cache(self, kv_cache_config: Any, *args: Any, **kwargs: Any) -> None: + import vllm.v1.worker.gpu.model_runner as model_runner + + original = model_runner.maybe_create_adaptive_verification_manager + + def _compatible(*call_args: Any, **call_kwargs: Any) -> Any: + return _call_without_unknown_kwargs(original, *call_args, **call_kwargs) + + model_runner.maybe_create_adaptive_verification_manager = _compatible + try: + NPUModelRunner.initialize_kv_cache(self, kv_cache_config, *args, **kwargs) + finally: + model_runner.maybe_create_adaptive_verification_manager = original + + def _close_omni_aux_output(self) -> None: + """V1 aux-output streams are not used by this runner.""" + + def load_model(self, *args: Any, **kwargs: Any) -> None: + OmniGPUModelRunner.load_model(self, *args, **kwargs) + if not getattr(self.model_state, "uses_ascend_attn_metadata", False): + raise NotImplementedError( + "NPU Model Runner V2 needs a model state that builds Ascend attention " + f"metadata; {type(self.model_state).__name__} does not. Keep this stage " + "on model_runner v1, or provide an NPU state (Drama 3 does)." + ) + logger.info( + "NPU Model Runner V2 loaded %s with Ascend attention metadata.", + type(self.model).__name__, + ) diff --git a/vllm_omni/worker_v2/omni_model_runner.py b/vllm_omni/worker_v2/omni_model_runner.py index 4ae6c97ee7d..1bd9283d6f8 100644 --- a/vllm_omni/worker_v2/omni_model_runner.py +++ b/vllm_omni/worker_v2/omni_model_runner.py @@ -518,6 +518,30 @@ def _dispatch_mtp_batch_descriptor(self, num_mtp_reqs: int) -> Any: 0, ) + def _make_dummy_input_batch( + self, + num_reqs: int, + num_tokens: int, + *, + max_query_len: int | None, + is_padding: bool, + ) -> Any: + from vllm.v1.worker.gpu.input_batch import InputBatch + + return InputBatch.make_dummy( + num_reqs, + num_tokens, + self.input_buffers, + max_query_len=max_query_len, + is_padding=is_padding, + ) + + def _forward_context(self, attn_metadata: Any, vllm_config: Any, **kwargs: Any): + """Forward-context scope. NPU replaces this with the Ascend context.""" + kwargs.pop("in_profile_run", None) + kwargs.pop("num_actual_tokens", None) + return set_forward_context(attn_metadata, vllm_config, **kwargs) + def _dispatch_batch_descriptor( self, *, @@ -666,12 +690,9 @@ def execute_model( ) self._set_active_loras(*lora_inputs) else: - from vllm.v1.worker.gpu.input_batch import InputBatch - - input_batch = InputBatch.make_dummy( + input_batch = self._make_dummy_input_batch( batch_desc.num_reqs or num_reqs, batch_desc.num_tokens, - self.input_buffers, max_query_len=batch_desc.max_query_len, is_padding=not is_profile, ) @@ -766,10 +787,12 @@ def execute_model( self.model.set_runner_assisted_full_attention_metadata_context( enabled=True, num_reqs=input_batch.num_reqs ) - with set_forward_context( + with self._forward_context( attn_metadata, self.vllm_config, num_tokens=input_batch.num_tokens_after_padding, + num_actual_tokens=input_batch.num_tokens, + in_profile_run=is_profile, cudagraph_runtime_mode=CUDAGraphMode.FULL if runner_assisted_full_attn else batch_desc.cg_mode, num_tokens_across_dp=dp_sync.num_tokens_across_dp if dp_sync is not None else None, batch_descriptor=batch_descriptor,