diff --git a/tests/e2e/nightly/single_node/ops/singlecard_ops/triton/test_qwen4_exp_qsa.py b/tests/e2e/nightly/single_node/ops/singlecard_ops/triton/test_qwen4_exp_qsa.py index 334bcdbdb79f..e8bd8b2c536e 100644 --- a/tests/e2e/nightly/single_node/ops/singlecard_ops/triton/test_qwen4_exp_qsa.py +++ b/tests/e2e/nightly/single_node/ops/singlecard_ops/triton/test_qwen4_exp_qsa.py @@ -8,7 +8,6 @@ from vllm_ascend.device.device_config import get_ascend_device_type from vllm_ascend.device.hardware import AscendDeviceType from vllm_ascend.models.qwen4_exp.gbsa import qsa_gbsa_attention -from vllm_ascend.ops.triton.qwen4_exp.fia import QSAFIAMaskWorkspace, build_qsa_fia_mask from vllm_ascend.ops.triton.qwen4_exp.gbsa import prepare_qsa_gbsa_inputs from vllm_ascend.ops.triton.qwen4_exp.qsa import pack_qsa_group_indices_npu @@ -42,26 +41,6 @@ def test_qsa_pack_supports_non_power_of_two_output_width() -> None: torch.testing.assert_close(actual.cpu(), expected, rtol=0, atol=0) -@requires_a3 -@torch.inference_mode() -def test_qsa_fia_workspace_wide_to_narrow_reuse() -> None: - workspace = QSAFIAMaskWorkspace(torch.device("npu:0"), max_rows=2, max_bytes=4096, max_update_width=520) - compact = torch.full((2, 131), -1, dtype=torch.int32, device="npu") - compact[0, :2] = torch.tensor([1, 5], dtype=torch.int32, device="npu") - compact[1, :2] = torch.tensor([2, 9], dtype=torch.int32, device="npu") - visible = torch.tensor([256, 256], dtype=torch.int32, device="npu") - - actual, selected = build_qsa_fia_mask(compact, visible, kv_length=256, mask_width=256, workspace=workspace) - - expected = torch.ones((2, 256), dtype=torch.bool) - expected[0, 4:8] = False - expected[0, 20:24] = False - expected[1, 8:12] = False - expected[1, 36:40] = False - torch.testing.assert_close(actual.cpu(), expected, rtol=0, atol=0) - torch.testing.assert_close(selected.cpu(), torch.ones(2, dtype=torch.bool), rtol=0, atol=0) - - @requires_a3 @torch.inference_mode() def test_qsa_gbsa_preparation_ragged_noncontiguous_table() -> None: diff --git a/tests/e2e/pull_request/two_card/ops/triton/test_qwen4_exp_qsa.py b/tests/e2e/pull_request/two_card/ops/triton/test_qwen4_exp_qsa.py index c76542a376a2..3271eddc2599 100644 --- a/tests/e2e/pull_request/two_card/ops/triton/test_qwen4_exp_qsa.py +++ b/tests/e2e/pull_request/two_card/ops/triton/test_qwen4_exp_qsa.py @@ -4,7 +4,6 @@ from vllm_ascend.device.device_config import get_ascend_device_type from vllm_ascend.device.hardware import AscendDeviceType -from vllm_ascend.ops.triton.qwen4_exp.fia import QSAFIAMaskWorkspace, build_qsa_fia_mask from vllm_ascend.ops.triton.qwen4_exp.gbsa import prepare_qsa_gbsa_inputs from vllm_ascend.ops.triton.qwen4_exp.qsa import pack_qsa_group_indices_npu @@ -39,25 +38,6 @@ def test_qsa_pack_supports_non_power_of_two_output_width() -> None: torch.testing.assert_close(actual.cpu(), expected, rtol=0, atol=0) -@torch.inference_mode() -def test_qsa_fia_workspace_wide_to_narrow_reuse() -> None: - workspace = QSAFIAMaskWorkspace(torch.device("npu:0"), max_rows=2, max_bytes=4096, max_update_width=520) - compact = torch.full((2, 131), -1, dtype=torch.int32, device="npu") - compact[0, :2] = torch.tensor([1, 5], dtype=torch.int32, device="npu") - compact[1, :2] = torch.tensor([2, 9], dtype=torch.int32, device="npu") - visible = torch.tensor([256, 256], dtype=torch.int32, device="npu") - - actual, selected = build_qsa_fia_mask(compact, visible, kv_length=256, mask_width=256, workspace=workspace) - - expected = torch.ones((2, 256), dtype=torch.bool) - expected[0, 4:8] = False - expected[0, 20:24] = False - expected[1, 8:12] = False - expected[1, 36:40] = False - torch.testing.assert_close(actual.cpu(), expected, rtol=0, atol=0) - torch.testing.assert_close(selected.cpu(), torch.ones(2, dtype=torch.bool), rtol=0, atol=0) - - @torch.inference_mode() def test_qsa_gbsa_preparation_ragged_noncontiguous_table() -> None: compact = torch.tensor( diff --git a/tests/ut/models/qwen4_exp/test_attention_dispatch.py b/tests/ut/models/qwen4_exp/test_attention_dispatch.py new file mode 100644 index 000000000000..8fdfda1c38d6 --- /dev/null +++ b/tests/ut/models/qwen4_exp/test_attention_dispatch.py @@ -0,0 +1,250 @@ +# SPDX-License-Identifier: Apache-2.0 +"""QSA request planning and dispatch coverage without requiring a native NPU.""" + +import ast +from dataclasses import dataclass, replace +from pathlib import Path +from types import SimpleNamespace +from typing import Any + +import pytest +import torch + +MODEL_DIR = Path(__file__).resolve().parents[4] / "vllm_ascend/models/qwen4_exp" + + +def _load_source(filename, namespace): + source = MODEL_DIR / filename + module = ast.parse(source.read_text()) + module.body = [node for node in module.body if not isinstance(node, (ast.Import, ast.ImportFrom))] + exec(compile(module, str(source), "exec"), namespace) + + +@pytest.fixture +def implementation(): + namespace = {"torch": torch, "dataclass": dataclass, "replace": replace, "__name__": __name__} + _load_source("attention_dispatch.py", namespace) + return namespace + + +def run_stub_batch(implementation, phases, query_lengths, kv_lengths): + starts = [0] + for length in query_lengths: + starts.append(starts[-1] + length) + total = starts[-1] + q = torch.arange(total, dtype=torch.float32).reshape(total, 1, 1) + out = torch.zeros_like(q) + calls = [] + + def gbsa(q, k, v, idx, table, requests, positions, lengths, out): + calls.append(("gbsa", q.flatten().tolist())) + out.fill_(7) + return out + + def union(q, k, v, idx, table, requests, positions, lengths, out, *, request_index, prepared): + assert torch.all(requests == request_index) + calls.append(("union", q.flatten().tolist())) + out.fill_(7) + return out + + def union_batch(q, k, v, idx, table, requests, positions, lengths, out, *, query_starts, request_indices, prepared): + assert query_starts[0] == 0 and query_starts[-1] == q.shape[0] + for start, end, request in zip(query_starts, query_starts[1:], request_indices): + assert torch.all(requests[start:end] == request) + calls.append(("union_batch", q.flatten().tolist())) + out.fill_(7) + return out + + implementation.update( + qsa_gbsa_attention=gbsa, + qsa_union_gbsa_attention=union, + qsa_union_gbsa_attention_batch=union_batch, + ) + plan = implementation["build_qsa_request_plan"](torch.tensor(starts), total, torch.tensor(phases)) + plan = implementation["prepare_qsa_union_batches"]( + plan, + torch.arange(total, dtype=torch.int32), + torch.tensor(kv_lengths), + torch.zeros(len(phases), 256), + ) + requests = torch.repeat_interleave(torch.arange(len(phases)), torch.tensor(query_lengths)) + implementation["dispatch_qsa_attention"]( + q, + q, + q, + torch.zeros(total, 7), + torch.zeros(len(phases), 256), + requests, + torch.arange(total), + torch.tensor(kv_lengths), + out, + plan, + ) + torch.testing.assert_close(out, torch.full_like(out, 7)) + return calls + + +def test_prefill_uses_union_for_first_crossing_and_cached_chunks(implementation): + calls = run_stub_batch(implementation, [True, True, True], [2, 4, 1], [2, 24578, 24577]) + assert calls == [("union_batch", list(range(7)))] + + +def test_pure_decode_is_one_gbsa_call_including_mtp(implementation): + calls = run_stub_batch(implementation, [False, False, False], [1, 4, 8], [1, 8192, 32768]) + assert calls == [("gbsa", list(range(13)))] + + +def test_eight_prefill_requests_share_one_union_launch(implementation): + query_lengths = [1, 7, 8, 9, 15, 16, 17, 19] + calls = run_stub_batch(implementation, [True] * 8, query_lengths, [32768] * 8) + assert calls == [("union_batch", list(range(sum(query_lengths))))] + + +def test_empty_requests_preserve_original_page_table_indices(implementation): + calls = run_stub_batch(implementation, [True, True, True], [5, 0, 7], [32768, 0, 65536]) + assert calls == [("union_batch", list(range(12)))] + + +def test_union_batches_do_not_include_decode_rows(implementation): + calls = run_stub_batch( + implementation, + [True, True, False, True, True, True], + [5, 7, 1, 9, 4, 8], + [32768, 65536, 131072, 32768, 4096, 65536], + ) + assert calls == [ + ("union_batch", list(range(12))), + ("union_batch", list(range(13, 34))), + ("gbsa", [12]), + ] + + +def test_union_group_row_map_pads_each_request_independently(implementation): + actual = implementation["build_qsa_union_group_row_map"]((0, 5, 12, 20)) + assert actual == ( + (0, 1, 2, 3, 4, -1, -1, -1), + (5, 6, 7, 8, 9, 10, 11, -1), + (12, 13, 14, 15, 16, 17, 18, 19), + ) + + +def test_prepare_union_batches_reuses_views_and_gathers_request_gaps(implementation): + plan = implementation["build_qsa_request_plan"]( + torch.tensor([0, 5, 5, 12]), + 12, + torch.tensor([True, True, True]), + ) + visible = torch.arange(12, dtype=torch.int32) + seq_lens = torch.tensor([32768, 0, 65536], dtype=torch.int32) + table = torch.arange(12, dtype=torch.int32).reshape(3, 4) + prepared_plan = implementation["prepare_qsa_union_batches"](plan, visible, seq_lens, table) + prepared = prepared_plan.prepared_union_batches[0] + assert prepared.visible_lengths.data_ptr() == visible.data_ptr() + assert prepared.cu_q.tolist() == [0, 5, 12] + assert prepared.seq_lens.tolist() == [32768, 65536] + assert prepared.block_table.tolist() == [table[0].tolist(), table[2].tolist()] + assert prepared.group_row_map.tolist() == [ + [0, 1, 2, 3, 4, -1, -1, -1], + [5, 6, 7, 8, 9, 10, 11, -1], + ] + assert prepared.max_query_length == 7 + + +def test_mixed_batch_runs_prefill_first_then_contiguous_decode_spans(implementation): + calls = run_stub_batch( + implementation, + [False, True, True, False, False, True, False], + [1, 2, 1, 1, 4, 1, 1], + [4096, 24576, 24577, 16384, 12, 1, 8192], + ) + assert calls == [ + ("union_batch", [1, 2, 3]), + ("union", [9]), + ("gbsa", [0]), + ("gbsa", [4, 5, 6, 7, 8]), + ("gbsa", [10]), + ] + + +def test_decode_sentinel_bypasses_request_planner(implementation): + calls = [] + + def gbsa(*args): + calls.append(args) + return args[-1] + + implementation["qsa_gbsa_attention"] = gbsa + q = torch.zeros(4, 3, 8) + implementation["dispatch_qsa_attention"]( + q, q, q, torch.zeros(4, 7), torch.zeros(1, 1), torch.zeros(4), torch.arange(4), torch.tensor([4]), q, None + ) + assert len(calls) == 1 and calls[0][0] is q + + +def test_padding_requests_are_ignored(implementation): + plan = implementation["build_qsa_request_plan"](torch.tensor([0, 1, 3, 8]), 3, torch.tensor([False, True, False])) + assert [(r.query_start, r.query_end, r.is_prefill) for r in plan] == [(0, 1, False), (1, 3, True)] + + +def test_phase_metadata_required_to_cover_requests(implementation): + with pytest.raises(ValueError, match="every request"): + implementation["build_qsa_request_plan"](torch.tensor([0, 1, 2]), 2, torch.tensor([False])) + + +def load_builder(): + source = MODEL_DIR / "qsa.py" + builder = next( + n + for n in ast.parse(source.read_text(encoding="utf-8")).body + if isinstance(n, ast.ClassDef) and n.name == "AscendQSAMetadataBuilder" + ) + + class Base: + def build(self, *args, **kwargs): + return SimpleNamespace(block_table="kept") + + plans = [] + + def plan(*args): + plans.append(args) + return ("prefill-plan",) + + namespace: dict[str, Any] = dict( + Any=Any, + upstream_qsa=SimpleNamespace(Qwen4ExpQSAMetadataBuilder=Base), + AttentionCGSupport=SimpleNamespace(UNIFORM_BATCH="uniform"), + CommonAttentionMetadata=object, + build_qsa_request_plan=plan, + ) + exec(compile(ast.Module(body=[builder], type_ignores=[]), str(source), "exec"), namespace) + return namespace["AscendQSAMetadataBuilder"](), plans + + +def test_metadata_builder_keeps_decode_capture_on_gbsa(): + builder, plans = load_builder() + assert builder._cudagraph_support == "uniform" + common = SimpleNamespace(is_prefilling=torch.tensor([False])) + assert builder.build(0, common).qsa_request_plan is None + # Capture dummy inputs can look like prefills; the decode capture contract + # must not freeze the prefill request plan into the graph. + common.is_prefilling = torch.tensor([True]) + assert builder.build_for_cudagraph_capture(common).qsa_request_plan is None + assert plans == [] + + +def test_metadata_builder_uses_phase_flags_for_prefill(): + builder, plans = load_builder() + common = SimpleNamespace( + is_prefilling=torch.tensor([True]), + query_start_loc_cpu=torch.tensor([0, 4096]), + num_actual_tokens=4096, + ) + meta = builder.build(0, common) + assert meta.block_table == "kept" and meta.qsa_request_plan == ("prefill-plan",) + assert plans[0][-1] is common.is_prefilling + + +def test_metadata_builder_rejects_unknown_phase_instead_of_guessing(): + builder, _ = load_builder() + with pytest.raises(ValueError, match="is_prefilling"): + builder.build(0, SimpleNamespace(is_prefilling=None)) diff --git a/tests/ut/models/qwen4_exp/test_fia_dispatch.py b/tests/ut/models/qwen4_exp/test_fia_dispatch.py deleted file mode 100644 index 8c5ca03b9929..000000000000 --- a/tests/ut/models/qwen4_exp/test_fia_dispatch.py +++ /dev/null @@ -1,463 +0,0 @@ -# SPDX-License-Identifier: Apache-2.0 -"""Mask semantics and scheduler-shape coverage without requiring a native NPU.""" - -import ast -from dataclasses import dataclass, replace -from pathlib import Path -from types import SimpleNamespace -from typing import Any - -import pytest -import torch - -MODEL_DIR = Path(__file__).resolve().parents[4] / "vllm_ascend/models/qwen4_exp" - - -def _load_source(filename, namespace): - source = MODEL_DIR / filename - module = ast.parse(source.read_text()) - module.body = [node for node in module.body if not isinstance(node, (ast.Import, ast.ImportFrom))] - exec(compile(module, str(source), "exec"), namespace) - - -@pytest.fixture -def implementation(): - namespace = {"torch": torch, "dataclass": dataclass, "replace": replace, "__name__": __name__} - _load_source("gbsa.py", namespace) - _load_source("fia.py", namespace) - _load_source("attention_dispatch.py", namespace) - return namespace - - -def test_mask_discards_invalid_and_duplicate_indices(implementation): - indices = torch.tensor([[[0, 2, 5, -1], [1, 3, 7, -1], [0, 4, -1, -1], [2, 2, 5, -1]]]) - mask = implementation["build_selected_token_mask"](indices, 6, 8) - expected = torch.tensor( - [[1, 0, 1, 0, 0, 1, 0, 0], [0, 1, 0, 1, 0, 0, 0, 0], [1, 0, 0, 0, 1, 0, 0, 0], [0, 0, 1, 0, 0, 1, 0, 0]], - dtype=torch.bool, - ) - torch.testing.assert_close(mask[0, 0], expected) - - -def test_mask_broadcasts_one_effective_length_per_batch(implementation): - indices = torch.tensor( - [ - [[0, 2, 4], [1, 3, 5]], - [[0, 2, 4], [1, 3, 5]], - ] - ) - mask = implementation["build_selected_token_mask"](indices, torch.tensor([3, 5]), 6) - expected = torch.tensor( - [ - [[1, 0, 1, 0, 0, 0], [0, 1, 0, 0, 0, 0]], - [[1, 0, 1, 0, 1, 0], [0, 1, 0, 1, 0, 0]], - ], - dtype=torch.bool, - ) - torch.testing.assert_close(mask[:, 0], expected) - - -@pytest.mark.parametrize("visible", range(12)) -def test_compact_groups_and_implicit_tail_respect_each_query_position(implementation, visible): - # Deliberately poison explicit tail slots: GBSA derives its tail from visibility. - compact = torch.tensor([[0, 1, 8, -1, 999, 999, 999]], dtype=torch.int32) - selected = implementation["expand_qsa_selected_tokens"](compact, torch.tensor([visible])) - allowed = implementation["build_selected_token_mask"](selected[None], torch.tensor([[visible]]), 16) - expected = torch.zeros(16, dtype=torch.bool) - expected[: min(visible // 4 * 4, 8)] = True - expected[visible // 4 * 4 : visible] = True - torch.testing.assert_close(allowed[0, 0, 0], expected) - - -def test_fia_passes_gqa_heads_causal_mask_and_zeroes_empty_rows(implementation): - calls = [] - - def fia(**kwargs): - calls.append(kwargs) - return torch.ones_like(kwargs["query"]), None - - implementation["torch_npu"] = SimpleNamespace(npu_fused_infer_attention_score_v2=fia) - query = torch.zeros(4, 4, 8, dtype=torch.bfloat16) - key = torch.zeros(4, 1, 8, dtype=torch.bfloat16) - compact = torch.tensor([[0, -1, -1, -1]] * 4) - result = implementation["qsa_fia_attention"]( - query, - key, - key, - compact, - torch.tensor([0, 2, 3, 4]), - 4, - torch.empty_like(query), - ) - assert calls[0]["num_query_heads"] == 4 - assert calls[0]["num_key_value_heads"] == 1 - assert calls[0]["block_table"] is None - assert calls[0]["atten_mask"][0, 0, 1].tolist() == [False, False, True, True] - assert torch.all(result[0] == 0) - assert torch.all(result[1:] == 1) - - -@pytest.mark.parametrize("groups", [31, 128, 511, 512]) -@pytest.mark.parametrize("tail", range(4)) -@pytest.mark.parametrize("holes", [False, True]) -def test_fia_mask_matches_latest_gbsa_explicit_tail_policy(implementation, groups, tail, holes): - from tests.ut.models.qwen4_exp.gbsa_reference import reference_prepare - - visible = 4096 + tail - indices = torch.full((1, groups + 3), -1, dtype=torch.int32) - indices[0, :groups] = torch.arange(groups - 1, -1, -1) - if holes: - indices[0, 2:groups:7] = -1 - lengths = torch.tensor([visible], dtype=torch.int32) - packed, counts, *_ = reference_prepare( - indices, - torch.tensor([visible - 1]), - lengths, - torch.tensor([0]), - torch.arange(33, dtype=torch.int32)[None], - 1, - ) - expected = torch.zeros(visible, dtype=torch.bool) - for group in packed[0, 0, : counts[0, 0]].tolist(): - expected[group * 4 : min(group * 4 + 4, visible)] = True - selected = implementation["expand_qsa_selected_tokens"](indices, lengths) - actual = implementation["build_selected_token_mask"](selected[None], lengths[None], visible) - torch.testing.assert_close(actual[0, 0, 0], expected) - - -def test_fia_descriptor_page_mapping_is_zero_copy(implementation): - storage = torch.arange(8 * 128 * 2 * 4).reshape(8, 128, 2, 4) - cache = storage.as_strided((3, 128, 2, 4), (2 * 128 * 8, 8, 4, 1)) - key, value, table, width = implementation["prepare_qsa_fia_paged_kv"]( - cache, - cache, - torch.tensor([[2, 0, -1]], dtype=torch.int32), - 257, - ) - assert key.data_ptr() == cache.data_ptr() - assert value.data_ptr() == cache.data_ptr() - assert table.tolist() == [[4, 0, 0]] - assert width == 384 - torch.testing.assert_close(key[4], cache[2].flatten(1)) - - -@pytest.mark.parametrize( - "query_length,kv_length,prefill", - [ - (1, 1, True), - (1, 32768, True), - (4096, 4096, True), - (4096, 32768, True), - (1, 128, False), - (4, 16383, False), - (8, 32768, False), - ], -) -def test_route_uses_explicit_phase_not_query_or_kv_length(implementation, query_length, kv_length, prefill): - plan = implementation["build_qsa_request_plan"]( - torch.tensor([0, query_length]), torch.tensor([kv_length]), query_length, torch.tensor([prefill]) - ) - assert plan[0].is_prefill is prefill - assert plan[0].use_paged_kv is (query_length != kv_length) - if not prefill: - assert not plan[0].use_fia - - -@pytest.mark.parametrize( - "query_length,kv_length,expected_fia", - [ - (1, 24575, True), - (1, 24576, True), - (1, 24577, False), - (4, 24578, True), - (4096, 24576, True), - (4096, 28671, True), - (4096, 28672, False), - (4096, 32768, False), - (131072, 131072, True), - ], -) -def test_chunk_start_policy_including_large_initial_prefill(implementation, query_length, kv_length, expected_fia): - plan = implementation["build_qsa_request_plan"]( - torch.tensor([0, query_length]), torch.tensor([kv_length]), query_length, torch.tensor([True]) - ) - request = plan[0] - assert request.use_fia is expected_fia - assert request.fia_query_end == (query_length if expected_fia else 0) - assert request.gbsa_query_start == (query_length if expected_fia else 0) - - -def run_stub_batch(implementation, phases, query_lengths, kv_lengths): - starts = [0] - for length in query_lengths: - starts.append(starts[-1] + length) - total = starts[-1] - q = torch.arange(total, dtype=torch.float32).reshape(total, 1, 1) - out = torch.zeros_like(q) - calls = [] - - def prepare(k, v, table, kv): - return k, v, table, kv - - def fia(q, k, v, idx, visible, kv, out, **kwargs): - calls.append(("fia", q.flatten().tolist())) - out.fill_(3) - - def gbsa(q, k, v, idx, table, requests, positions, lengths, out): - calls.append(("gbsa", q.flatten().tolist())) - out.fill_(7) - return out - - def union(q, k, v, idx, table, requests, positions, lengths, out, *, request_index, prepared): - assert torch.all(requests == request_index) - calls.append(("union", q.flatten().tolist())) - out.fill_(7) - return out - - def union_batch(q, k, v, idx, table, requests, positions, lengths, out, *, query_starts, request_indices, prepared): - assert query_starts[0] == 0 and query_starts[-1] == q.shape[0] - for start, end, request in zip(query_starts, query_starts[1:], request_indices): - assert torch.all(requests[start:end] == request) - calls.append(("union_batch", q.flatten().tolist())) - out.fill_(7) - return out - - implementation.update( - prepare_qsa_fia_paged_kv=prepare, - qsa_fia_attention=fia, - qsa_gbsa_attention=gbsa, - qsa_union_gbsa_attention=union, - qsa_union_gbsa_attention_batch=union_batch, - ) - plan = implementation["build_qsa_request_plan"]( - torch.tensor(starts), torch.tensor(kv_lengths), total, torch.tensor(phases) - ) - plan = implementation["prepare_qsa_union_batches"]( - plan, - torch.arange(total, dtype=torch.int32), - torch.tensor(kv_lengths), - torch.zeros(len(phases), 256), - ) - requests = torch.repeat_interleave(torch.arange(len(phases)), torch.tensor(query_lengths)) - implementation["dispatch_qsa_attention"]( - q, - q, - q, - q, - q, - torch.zeros(total, 7), - torch.zeros(len(phases), 256), - requests, - torch.arange(total), - torch.tensor(kv_lengths), - out, - plan, - ) - expected = [] - for phase, query_length, kv_length in zip(phases, query_lengths, kv_lengths): - fia_rows = 0 - if phase: - kv_before_query = kv_length - query_length - fia_rows = query_length if kv_before_query < 24576 else 0 - expected.extend([3] * fia_rows) - expected.extend([7] * (query_length - fia_rows)) - torch.testing.assert_close(out.flatten(), torch.tensor(expected, dtype=torch.float32)) - return calls - - -def test_pure_prefill_routes_by_logical_kv_length(implementation): - calls = run_stub_batch(implementation, [True, True, True], [2, 4, 1], [4096, 24578, 24577]) - assert calls == [("fia", [0, 1]), ("fia", [2, 3, 4, 5]), ("union", [6])] - - -def test_pure_decode_is_one_gbsa_call_including_mtp(implementation): - calls = run_stub_batch(implementation, [False, False, False], [1, 4, 8], [1, 8192, 32768]) - assert calls == [("gbsa", list(range(13)))] - - -def test_eight_prefill_requests_share_one_union_launch(implementation): - query_lengths = [1, 7, 8, 9, 15, 16, 17, 19] - calls = run_stub_batch(implementation, [True] * 8, query_lengths, [32768] * 8) - assert calls == [("union_batch", list(range(sum(query_lengths))))] - - -def test_empty_requests_preserve_original_page_table_indices(implementation): - calls = run_stub_batch(implementation, [True, True, True], [5, 0, 7], [32768, 0, 65536]) - assert calls == [("union_batch", list(range(12)))] - - -def test_union_batches_do_not_include_decode_or_fia_rows(implementation): - calls = run_stub_batch( - implementation, - [True, True, False, True, True, True], - [5, 7, 1, 9, 4, 8], - [32768, 65536, 131072, 32768, 4096, 65536], - ) - assert calls == [ - ("fia", list(range(22, 26))), - ("union_batch", list(range(12))), - ("union", list(range(13, 22))), - ("union", list(range(26, 34))), - ("gbsa", [12]), - ] - - -def test_union_group_row_map_pads_each_request_independently(implementation): - actual = implementation["build_qsa_union_group_row_map"]((0, 5, 12, 20)) - assert actual == ( - (0, 1, 2, 3, 4, -1, -1, -1), - (5, 6, 7, 8, 9, 10, 11, -1), - (12, 13, 14, 15, 16, 17, 18, 19), - ) - - -def test_prepare_union_batches_reuses_views_and_gathers_request_gaps(implementation): - plan = implementation["build_qsa_request_plan"]( - torch.tensor([0, 5, 5, 12]), - torch.tensor([32768, 0, 65536]), - 12, - torch.tensor([True, True, True]), - ) - visible = torch.arange(12, dtype=torch.int32) - seq_lens = torch.tensor([32768, 0, 65536], dtype=torch.int32) - table = torch.arange(12, dtype=torch.int32).reshape(3, 4) - prepared_plan = implementation["prepare_qsa_union_batches"](plan, visible, seq_lens, table) - prepared = prepared_plan.prepared_union_batches[0] - assert prepared.visible_lengths.data_ptr() == visible.data_ptr() - assert prepared.cu_q.tolist() == [0, 5, 12] - assert prepared.seq_lens.tolist() == [32768, 65536] - assert prepared.block_table.tolist() == [table[0].tolist(), table[2].tolist()] - assert prepared.group_row_map.tolist() == [ - [0, 1, 2, 3, 4, -1, -1, -1], - [5, 6, 7, 8, 9, 10, 11, -1], - ] - assert prepared.max_query_length == 7 - - -def test_mixed_batch_runs_prefill_first_then_contiguous_decode_spans(implementation): - calls = run_stub_batch( - implementation, - [False, True, True, False, False, True, False], - [1, 2, 1, 1, 4, 1, 1], - [4096, 24576, 24577, 16384, 12, 1, 8192], - ) - assert calls == [ - ("fia", [1, 2]), - ("fia", [9]), - ("union", [3]), - ("gbsa", [0]), - ("gbsa", [4, 5, 6, 7, 8]), - ("gbsa", [10]), - ] - - -def test_decode_sentinel_bypasses_request_planner(implementation): - calls = [] - - def gbsa(*args): - calls.append(args) - return args[-1] - - implementation["qsa_gbsa_attention"] = gbsa - q = torch.zeros(4, 3, 8) - implementation["dispatch_qsa_attention"]( - q, q, q, q, q, torch.zeros(4, 7), torch.zeros(1, 1), torch.zeros(4), torch.arange(4), torch.tensor([4]), q, None - ) - assert len(calls) == 1 and calls[0][0] is q - - -def test_padding_requests_are_ignored(implementation): - plan = implementation["build_qsa_request_plan"]( - torch.tensor([0, 1, 3, 8]), torch.tensor([4096, 32768, 0]), 3, torch.tensor([False, True, False]) - ) - assert [(r.query_start, r.query_end, r.is_prefill) for r in plan] == [(0, 1, False), (1, 3, True)] - - -def test_phase_metadata_required_to_cover_requests(implementation): - with pytest.raises(ValueError, match="every request"): - implementation["build_qsa_request_plan"]( - torch.tensor([0, 1, 2]), torch.tensor([10, 20]), 2, torch.tensor([False]) - ) - - -def load_builder(): - source = MODEL_DIR / "qsa.py" - builder = next( - n - for n in ast.parse(source.read_text(encoding="utf-8")).body - if isinstance(n, ast.ClassDef) and n.name == "AscendQSAMetadataBuilder" - ) - - class Base: - def build(self, *args, **kwargs): - return SimpleNamespace(block_table="kept") - - plans = [] - - def plan(*args): - plans.append(args) - return ("prefill-plan",) - - namespace: dict[str, Any] = dict( - Any=Any, - upstream_qsa=SimpleNamespace(Qwen4ExpQSAMetadataBuilder=Base), - AttentionCGSupport=SimpleNamespace(UNIFORM_BATCH="uniform"), - CommonAttentionMetadata=object, - build_qsa_request_plan=plan, - ) - exec(compile(ast.Module(body=[builder], type_ignores=[]), str(source), "exec"), namespace) - return namespace["AscendQSAMetadataBuilder"](), plans - - -def test_metadata_builder_keeps_decode_capture_on_gbsa(): - builder, plans = load_builder() - assert builder._cudagraph_support == "uniform" - common = SimpleNamespace(is_prefilling=torch.tensor([False]), seq_lens_cpu_upper_bound=None) - assert builder.build(0, common).qsa_request_plan is None - # Capture dummy inputs can look like prefills; the decode capture contract - # must not freeze FIA or host KV lengths into the graph. - common.is_prefilling = torch.tensor([True]) - assert builder.build_for_cudagraph_capture(common).qsa_request_plan is None - assert plans == [] - - -def test_metadata_builder_uses_phase_flags_and_host_lengths_for_prefill(): - builder, plans = load_builder() - common = SimpleNamespace( - is_prefilling=torch.tensor([True]), - seq_lens_cpu_upper_bound=torch.tensor([32768]), - query_start_loc_cpu=torch.tensor([0, 4096]), - num_actual_tokens=4096, - ) - meta = builder.build(0, common) - assert meta.block_table == "kept" and meta.qsa_request_plan == ("prefill-plan",) - assert plans[0][-1] is common.is_prefilling - - -def test_metadata_builder_rejects_unknown_phase_instead_of_guessing(): - builder, _ = load_builder() - with pytest.raises(ValueError, match="is_prefilling"): - builder.build(0, SimpleNamespace(is_prefilling=None)) - - -def test_fia_helper_tiles_mask_memory_for_eligible_prefill(implementation): - calls = [] - implementation["QSA_FIA_MASK_BUDGET_BYTES"] = 64 - - def fia(**kwargs): - calls.append(kwargs) - return torch.ones_like(kwargs["query"]), None - - implementation["torch_npu"] = SimpleNamespace(npu_fused_infer_attention_score_v2=fia) - query = torch.zeros(5, 2, 4, dtype=torch.bfloat16) - key = torch.zeros(32, 1, 4, dtype=query.dtype) - implementation["qsa_fia_attention"]( - query, - key, - key, - torch.tensor([[0, -1, -1, -1]] * 5), - torch.tensor([28, 29, 30, 31, 32]), - 32, - torch.empty_like(query), - ) - assert [c["query"].shape[1] for c in calls] == [2, 2, 1] diff --git a/vllm_ascend/models/qwen4_exp/attention_dispatch.py b/vllm_ascend/models/qwen4_exp/attention_dispatch.py index 374eed3ae0c6..c74260fe3752 100644 --- a/vllm_ascend/models/qwen4_exp/attention_dispatch.py +++ b/vllm_ascend/models/qwen4_exp/attention_dispatch.py @@ -1,56 +1,21 @@ # SPDX-License-Identifier: Apache-2.0 -"""Request dispatch for Qwen4Exp: bounded FIA prefill and GBSA fallback.""" +"""Request dispatch for Qwen4Exp: Union GBSA prefill and standard GBSA decode.""" from dataclasses import dataclass, replace import torch -from .fia import prepare_qsa_fia_paged_kv, qsa_fia_attention from .gbsa import qsa_gbsa_attention from .gbsa_union import qsa_union_gbsa_attention, qsa_union_gbsa_attention_batch -QSA_FIA_MAX_LOGICAL_KV_LENGTH = 24 * 1024 - @dataclass(frozen=True) class QSARequest: request_index: int query_start: int query_end: int - kv_length: int is_prefill: bool - @property - def use_paged_kv(self) -> bool: - return self.kv_length != self.query_end - self.query_start - - @property - def use_fia(self) -> bool: - """Whether this Prefill chunk starts below the FIA KV limit.""" - return self.fia_query_end > self.query_start - - @property - def fia_query_end(self) -> int: - """Keep a chunk crossing 24K on FIA; switch subsequent chunks.""" - if not self.is_prefill: - return self.query_start - query_length = self.query_end - self.query_start - # Scheduler seq_lens already includes the current query chunk. - total_logical_kv_length = self.kv_length - fits_fia_limit = total_logical_kv_length <= QSA_FIA_MAX_LOGICAL_KV_LENGTH - crosses_fia_limit = ( - total_logical_kv_length > QSA_FIA_MAX_LOGICAL_KV_LENGTH - and total_logical_kv_length - query_length < QSA_FIA_MAX_LOGICAL_KV_LENGTH - ) - if fits_fia_limit or crosses_fia_limit: - return self.query_end - return self.query_start - - @property - def gbsa_query_start(self) -> int: - """First row routed to GBSA; Decode starts at the request boundary.""" - return self.fia_query_end - @dataclass(frozen=True) class QSAUnionBatch: @@ -77,7 +42,6 @@ class QSARequestPlan: """Precomputed operator routing shared by every QSA layer in one step.""" requests: tuple[QSARequest, ...] - fia_requests: tuple[QSARequest, ...] union_batches: tuple[QSAUnionBatch, ...] decode_spans: tuple[tuple[int, int], ...] prepared_union_batches: tuple[QSAUnionPreparedBatch, ...] = () @@ -94,34 +58,27 @@ def __len__(self) -> int: def build_qsa_request_plan( query_start_loc_cpu: torch.Tensor, - seq_lens_cpu: torch.Tensor, num_actual_tokens: int, is_prefilling_cpu: torch.Tensor, ) -> QSARequestPlan: """Classify mixed-batch rows once for reuse by every QSA layer.""" - if any(t.device.type != "cpu" for t in (query_start_loc_cpu, seq_lens_cpu, is_prefilling_cpu)): + if any(t.device.type != "cpu" for t in (query_start_loc_cpu, is_prefilling_cpu)): raise ValueError("QSA dispatch requires scheduler CPU metadata") starts = query_start_loc_cpu.tolist() - lengths = seq_lens_cpu.tolist() phases = is_prefilling_cpu.tolist() - if len(lengths) < len(starts) - 1 or len(phases) < len(starts) - 1: - raise ValueError("QSA phase and KV metadata must cover every request") + if len(phases) < len(starts) - 1: + raise ValueError("QSA phase metadata must cover every request") requests: list[QSARequest] = [] for request_index, (start, end) in enumerate(zip(starts, starts[1:])): start = min(max(start, 0), num_actual_tokens) end = min(max(end, start), num_actual_tokens) if end > start: - requests.append( - QSARequest(request_index, start, end, int(lengths[request_index]), bool(phases[request_index])) - ) + requests.append(QSARequest(request_index, start, end, bool(phases[request_index]))) requests_tuple = tuple(requests) - fia_requests = tuple(request for request in requests_tuple if request.use_fia) union_requests: list[list[QSARequest]] = [] decode_spans: list[tuple[int, int]] = [] for request in requests_tuple: - start = request.gbsa_query_start - if start >= request.query_end: - continue + start = request.query_start if request.is_prefill: if union_requests and union_requests[-1][-1].query_end == start: union_requests[-1].append(request) @@ -133,14 +90,14 @@ def build_qsa_request_plan( decode_spans.append((start, request.query_end)) union_batches = tuple( QSAUnionBatch( - batch[0].gbsa_query_start, + batch[0].query_start, batch[-1].query_end, - (0,) + tuple(request.query_end - batch[0].gbsa_query_start for request in batch), + (0,) + tuple(request.query_end - batch[0].query_start for request in batch), tuple(request.request_index for request in batch), ) for batch in union_requests ) - return QSARequestPlan(requests_tuple, fia_requests, union_batches, tuple(decode_spans)) + return QSARequestPlan(requests_tuple, union_batches, tuple(decode_spans)) def build_qsa_union_group_row_map(query_starts: tuple[int, ...]) -> tuple[tuple[int, ...], ...]: @@ -207,8 +164,6 @@ def prepare_qsa_union_batches( def dispatch_qsa_attention( query: torch.Tensor, - key: torch.Tensor | None, - value: torch.Tensor | None, key_cache: torch.Tensor, value_cache: torch.Tensor, compact_indices: torch.Tensor, @@ -220,7 +175,7 @@ def dispatch_qsa_attention( request_plan: QSARequestPlan | None, ) -> torch.Tensor: # None is the decode-only metadata sentinel, including graph capture. - # This branch contains no host length decisions or FIA launches; device KV + # Device KV # lengths, positions and page tables may change between graph replays. if request_plan is None: return qsa_gbsa_attention( @@ -235,40 +190,6 @@ def dispatch_qsa_attention( output, ) - for request in request_plan.fia_requests: - rows = slice(request.query_start, request.fia_query_end) - fia_kv_length = request.kv_length - visible_lens = torch.minimum( - logical_positions[rows].add(1).clamp_min(0), - seq_lens[request.request_index].clamp_max(fia_kv_length), - ) - # Callers whose ABI does not carry the freshly projected K/V pass None; - # the rows were already stored, so gather them from the paged cache. - if request.use_paged_kv or key is None or value is None: - keys, values, table, _ = prepare_qsa_fia_paged_kv( - key_cache, - value_cache, - block_table[request.request_index : request.request_index + 1], - fia_kv_length, - ) - else: - keys, values, table = key[rows], value[rows], None - qsa_fia_attention( - query[rows], - keys, - values, - compact_indices[rows], - visible_lens, - fia_kv_length, - output[rows], - block_table=table, - ) - - # Every Decode row and each Prefill chunk starting at/above the logical-KV - # limit uses GBSA. Coalesce consecutive rows without gathering/copying K/V or - # changing the original request IDs used to address block tables and lengths. - # Union groups must never cross request boundaries. Keep the decode-only - # sentinel above unchanged, including graph capture and replay. for batch_index, batch in enumerate(request_plan.union_batches): rows = slice(batch.query_start, batch.query_end) prepared = request_plan.prepared_union_batches[batch_index] diff --git a/vllm_ascend/models/qwen4_exp/fia.py b/vllm_ascend/models/qwen4_exp/fia.py deleted file mode 100644 index dae28bb81628..000000000000 --- a/vllm_ascend/models/qwen4_exp/fia.py +++ /dev/null @@ -1,186 +0,0 @@ -# SPDX-License-Identifier: Apache-2.0 -"""Selected-token FIA for Qwen3.8-Flash-Next prefill.""" - -import torch -import torch_npu - -from .gbsa import GBSA_COMPRESS_RATIO, GBSA_PAGE_SIZE, GBSA_RESIDUAL_TOKENS - -# Bound temporary mask memory even for long-context prefills. -QSA_FIA_QUERY_TILE = 4096 -QSA_FIA_MASK_BUDGET_BYTES = 64 * 1024 * 1024 - - -def build_selected_token_mask( - selected_token_indices: torch.Tensor, - effective_kv_length: int | torch.Tensor, - kv_length: int, -) -> torch.Tensor: - """Return [B, 1, Tq, KV] allowed positions, discarding invalid indices.""" - if selected_token_indices.ndim != 3 or kv_length <= 0: - raise ValueError("Selected indices must be [B, Tq, K] and KV length must be positive") - if isinstance(effective_kv_length, int) and not 0 <= effective_kv_length <= kv_length: - raise ValueError("effective_kv_length must be between zero and kv_length") - lengths = torch.as_tensor(effective_kv_length, device=selected_token_indices.device) - lengths = lengths.reshape(lengths.shape + (1,) * (selected_token_indices.ndim - lengths.ndim)) - valid = (selected_token_indices >= 0) & (selected_token_indices < lengths) - valid &= selected_token_indices < kv_length - scatter_indices = torch.where(valid, selected_token_indices, kv_length).long() - mask = torch.zeros( - (*selected_token_indices.shape[:-1], kv_length + 1), - dtype=torch.bool, - device=selected_token_indices.device, - ) - mask.scatter_(-1, scatter_indices, True) - return mask[..., :kv_length].unsqueeze(1) - - -def expand_qsa_selected_tokens(compact_indices: torch.Tensor, visible_lens: torch.Tensor) -> torch.Tensor: - """Expand complete groups and reconstruct the implicit GBSA residual group.""" - if compact_indices.ndim != 2 or compact_indices.shape[1] <= GBSA_RESIDUAL_TOKENS: - raise ValueError("Expected compact QSA group indices followed by three residual slots") - groups = compact_indices[:, :-GBSA_RESIDUAL_TOKENS] - full_groups = visible_lens.floor_divide(GBSA_COMPRESS_RATIO) - valid = (groups >= 0) & (groups < full_groups.unsqueeze(-1)) - if groups.shape[1] >= 512: - capacity = groups.shape[1] - visible_lens.remainder(GBSA_COMPRESS_RATIO).ne(0).to(torch.int32) - valid &= valid.to(torch.int32).cumsum(-1) <= capacity.unsqueeze(-1) - offsets = torch.arange(GBSA_COMPRESS_RATIO, device=groups.device, dtype=groups.dtype) - tokens = groups.unsqueeze(-1) * GBSA_COMPRESS_RATIO + offsets - tokens = torch.where(valid.unsqueeze(-1), tokens, -1).flatten(1) - tail_offsets = torch.arange(GBSA_RESIDUAL_TOKENS, device=groups.device, dtype=groups.dtype) - tail = full_groups.unsqueeze(-1) * GBSA_COMPRESS_RATIO + tail_offsets - tail = torch.where(tail < visible_lens.unsqueeze(-1), tail, -1) - return torch.cat((tokens, tail), dim=-1) - - -def prepare_qsa_fia_paged_kv( - key_cache: torch.Tensor, - value_cache: torch.Tensor, - block_table: torch.Tensor, - kv_length: int, -) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor, int]: - """Expose descriptor-backed KV as zero-copy FIA pages and remap the table.""" - if key_cache.shape != value_cache.shape or key_cache.ndim != 4: - raise ValueError("QSA FIA requires matching 4-D K/V cache shapes") - if key_cache.stride() != value_cache.stride(): - raise ValueError("QSA FIA requires matching K/V cache page strides") - blocks, page_size, heads, dim = key_cache.shape - if min(key_cache.shape) == 0 or page_size != GBSA_PAGE_SIZE: - raise ValueError("QSA FIA requires nonempty 128-token paged KV cache") - row_elements = heads * dim - page_elements = page_size * row_elements - for cache in (key_cache, value_cache): - if ( - cache.stride(3) != 1 - or (heads > 1 and cache.stride(2) != dim) - or cache.stride(1) != row_elements - or cache.stride(0) < page_elements - or cache.stride(0) % page_elements - ): - raise ValueError("QSA FIA requires dense, non-overlapping pages with whole-page gaps") - block_stride = key_cache.stride(0) // page_elements - physical_pages = (blocks - 1) * block_stride + 1 - # Include descriptor padding as unreferenced pages; no KV data copy is needed. - keys = key_cache.as_strided((physical_pages, page_size, row_elements), (page_elements, row_elements, 1)) - values = value_cache.as_strided((physical_pages, page_size, row_elements), (page_elements, row_elements, 1)) - page_count = (kv_length + GBSA_PAGE_SIZE - 1) // GBSA_PAGE_SIZE - if kv_length <= 0 or block_table.ndim != 2 or block_table.shape[1] < page_count: - raise ValueError("QSA FIA block table must cover the positive KV length") - table = block_table[:, :page_count].clamp_min(0).to(torch.int32) - if block_stride != 1: - table = table * block_stride - return keys, values, table.contiguous(), page_count * GBSA_PAGE_SIZE - - -def qsa_fia_attention( - query: torch.Tensor, - key: torch.Tensor, - value: torch.Tensor, - compact_indices: torch.Tensor, - visible_lens: torch.Tensor, - kv_length: int, - output: torch.Tensor, - *, - block_table: torch.Tensor | None = None, - kv_lengths: list[int] | None = None, -) -> torch.Tensor: - """Attend a prefill request or a batch of single-token paged Decode requests.""" - num_heads, head_dim = query.shape[1:] - batch_size = len(kv_lengths) if kv_lengths is not None else 1 - if batch_size != 1 and (block_table is None or query.shape[0] != batch_size): - raise ValueError("Batched QSA FIA requires one paged query per request") - if query.dtype not in (torch.float16, torch.bfloat16) or key.dtype != query.dtype or value.dtype != query.dtype: - raise ValueError("QSA FIA requires matching FP16/BF16 Q/K/V") - if block_table is None: - num_kv_heads = key.shape[1] - key = key.reshape(1, kv_length, num_kv_heads * head_dim).contiguous() - value = value.reshape(1, kv_length, num_kv_heads * head_dim).contiguous() - mask_kv_length = kv_length - else: - num_kv_heads = key.shape[-1] // head_dim - mask_kv_length = block_table.shape[1] * GBSA_PAGE_SIZE - if query.device.type == "npu": - mask_kv_length = (mask_kv_length + 31) // 32 * 32 - if num_heads % num_kv_heads: - raise ValueError("QSA FIA requires query heads divisible by KV heads") - - query_tile = ( - query.shape[0] - if batch_size != 1 - else min(QSA_FIA_QUERY_TILE, max(1, QSA_FIA_MASK_BUDGET_BYTES // mask_kv_length)) - ) - mask_workspace = None - if query.device.type == "npu": - # One process-local allocation is shared by all QSA layers and reused - # across every query tile and scheduler step. - from vllm_ascend.ops.triton.qwen4_exp.fia import get_qsa_fia_mask_workspace - - mask_workspace = get_qsa_fia_mask_workspace( - query.device, - QSA_FIA_QUERY_TILE, - QSA_FIA_MASK_BUDGET_BYTES, - (compact_indices.shape[1] - 2 + 7) // 8 * 8, - ) - for start in range(0, query.shape[0], query_tile): - end = min(start + query_tile, query.shape[0]) - visible = visible_lens[start:end] - if query.device.type == "npu": - # Lazy import keeps model discovery and CPU semantic tests NPU-free. - from vllm_ascend.ops.triton.qwen4_exp.fia import build_qsa_fia_mask, copy_qsa_fia_output - - assert mask_workspace is not None - atten_mask, has_selection = build_qsa_fia_mask( - compact_indices[start:end], visible, kv_length, mask_kv_length, mask_workspace - ) - else: - selected = expand_qsa_selected_tokens(compact_indices[start:end], visible.clamp(0, kv_length)) - allowed = build_selected_token_mask(selected.unsqueeze(0), visible.unsqueeze(0), mask_kv_length) - has_selection = allowed.any(dim=-1).flatten() - atten_mask = (~allowed).contiguous() - atten_mask[..., 0] &= has_selection.view_as(atten_mask[..., 0]) - query_length = (end - start) // batch_size - atten_mask = atten_mask.reshape(batch_size, 1, query_length, mask_kv_length) - result, _ = torch_npu.npu_fused_infer_attention_score_v2( - query=query[start:end].reshape(batch_size, query_length, num_heads * head_dim).contiguous(), - key=key, - value=value, - atten_mask=atten_mask, - actual_seq_qlen=[query_length] * batch_size, - actual_seq_kvlen=kv_lengths if kv_lengths is not None else [kv_length], - num_query_heads=num_heads, - num_key_value_heads=num_kv_heads, - softmax_scale=head_dim**-0.5, - input_layout="BSH", - sparse_mode=0, - inner_precise=0, - block_table=block_table, - block_size=GBSA_PAGE_SIZE if block_table is not None else 0, - return_softmax_lse=False, - ) - result = result.reshape(end - start, num_heads, head_dim) - if query.device.type == "npu": - copy_qsa_fia_output(result, has_selection, output[start:end]) - else: - output[start:end].copy_(torch.where(has_selection.reshape(-1, 1, 1), result, 0)) - return output diff --git a/vllm_ascend/models/qwen4_exp/qsa.py b/vllm_ascend/models/qwen4_exp/qsa.py index 40f73272095b..bbb383b6f517 100644 --- a/vllm_ascend/models/qwen4_exp/qsa.py +++ b/vllm_ascend/models/qwen4_exp/qsa.py @@ -507,8 +507,6 @@ def forward( # type: ignore[misc] token_to_req: torch.Tensor, logical_positions: torch.Tensor | None = None, seq_lens: torch.Tensor | None = None, - key: torch.Tensor | None = None, - value: torch.Tensor | None = None, ) -> torch.Tensor: # The base ABI forwards only `token_to_req`; the GBSA kernel also # needs the indexer-side positions/lengths, supplied by the Ascend @@ -520,8 +518,6 @@ def forward( # type: ignore[misc] return self._dispatch_qsa( layer, query, - key, - value, kv_cache, attn_metadata, output, @@ -534,8 +530,6 @@ def _dispatch_qsa( self, layer: torch.nn.Module, query: torch.Tensor, - key: torch.Tensor | None, - value: torch.Tensor | None, kv_cache: QSAKVCache, attn_metadata: QSAIndexerMetadataProtocol, output: torch.Tensor, @@ -543,7 +537,7 @@ def _dispatch_qsa( logical_positions: torch.Tensor, seq_lens: torch.Tensor, ) -> torch.Tensor: - """Run GBSA, or the FIA/GBSA split planned for this step.""" + """Run the GBSA attention path selected for this step.""" num_tokens = attn_metadata.num_actual_tokens output.zero_() if num_tokens == 0: @@ -576,13 +570,8 @@ def _dispatch_qsa( if getattr(attn_metadata, "pcp_full_graph", False): result.masked_fill_(logical_positions[:num_tokens, None, None] < 0, 0) return result - # main's ABI does not carry the freshly projected K/V; the dispatcher - # then gathers them from the paged cache that `do_kv_cache_update` - # already filled for this step. return dispatch_qsa_attention( query[:num_tokens], - None if key is None else key[:num_tokens], - None if value is None else value[:num_tokens], key_cache, value_cache, compact_indices, @@ -607,8 +596,7 @@ def update_graph_params( class AscendQSAMetadataBuilder(upstream_qsa.Qwen4ExpQSAMetadataBuilder): - # FULL_DECODE_ONLY captures a fixed GBSA path. Unlike sequence thresholds, - # decode phase cannot cross into FIA when a request grows during replay. + # FULL_DECODE_ONLY captures the standard GBSA path. _cudagraph_support = AttentionCGSupport.UNIFORM_BATCH def prepare_step_metadata( @@ -691,12 +679,8 @@ def build( if phases is None or phases.device.type != "cpu": raise ValueError("QSA phase dispatch requires scheduler CPU is_prefilling metadata") if any(phases.tolist()): - lengths = common_attn_metadata.seq_lens_cpu_upper_bound - if lengths is None: - raise ValueError("QSA prefill dispatch requires scheduler CPU KV lengths") metadata.qsa_request_plan = build_qsa_request_plan( common_attn_metadata.query_start_loc_cpu, - lengths, common_attn_metadata.num_actual_tokens, phases, ) @@ -939,8 +923,6 @@ def _run_qsa( # name and signature follow the tree's upstream ABI. impl: Any = self.impl with attention_transfer_window(): - # main's ABI drops K/V from the signature; pass them back so - # the FIA prefill path can skip the paged gather. impl.forward( self, query, @@ -950,8 +932,6 @@ def _run_qsa( token_to_req=side_metadata.token_to_req, logical_positions=side_metadata.logical_positions, seq_lens=side_metadata.seq_lens, - key=key, - value=value, ) maybe_save_kv_layer_to_connector(self.layer_name, list(self.kv_cache)) diff --git a/vllm_ascend/ops/triton/README.md b/vllm_ascend/ops/triton/README.md index 2f3b369ae1b8..a9d3343616df 100644 --- a/vllm_ascend/ops/triton/README.md +++ b/vllm_ascend/ops/triton/README.md @@ -151,7 +151,6 @@ configuration rather than the runner input or sampling interface. | [quantize_indexer_query.py](quantize_indexer_query.py) | Model/attention primitive or shared utility | | [quantize_mxfp4_indexer.py](quantize_mxfp4_indexer.py) | Model/attention primitive or shared utility | | [query_gather_prep.py](query_gather_prep.py) | Model/attention primitive or shared utility | -| [qwen4_exp/fia.py](qwen4_exp/fia.py) | Model/attention primitive or shared utility | | [qwen4_exp/gbsa.py](qwen4_exp/gbsa.py) | Model/attention primitive or shared utility | | [qwen4_exp/hc.py](qwen4_exp/hc.py) | HyperConnection glue operators; row-block `gate_mix` and final-injection `combine_final` are documented in [qwen4_exp_hc_gate_mix.md](docs/qwen4_exp_hc_gate_mix.md) and [qwen4_exp_hc_combine_final.md](docs/qwen4_exp_hc_combine_final.md). | | [qwen4_exp/qsa.py](qwen4_exp/qsa.py) | Model/attention primitive or shared utility | diff --git a/vllm_ascend/ops/triton/docs/qwen4_exp_qsa_dispatch.md b/vllm_ascend/ops/triton/docs/qwen4_exp_qsa_dispatch.md index 878fdfa9c81c..57f83f39f82c 100644 --- a/vllm_ascend/ops/triton/docs/qwen4_exp_qsa_dispatch.md +++ b/vllm_ascend/ops/triton/docs/qwen4_exp_qsa_dispatch.md @@ -4,12 +4,10 @@ | Request | Attention path | | --- | --- | -| Prefill with a cached prefix below 24K at chunk start | FIA for the entire chunk, even if it crosses 24K | -| Prefill with a cached prefix of 24K or more at chunk start | Union GBSA | +| Prefill with a request plan | Union GBSA | | Decode | Standard GBSA, including decode-only graph replay | - **Packing**: the indexer selects 2048 tokens in groups of four. A compact row therefore contains 512 complete-group IDs followed by three residual-token slots. `pack_qsa_group_indices_npu` writes the complete groups and reconstructs up to three visible residual tokens. `-1` denotes an invalid lane. -- **FIA mask**: `_prepare_qsa_mask_words_kernel` expands group IDs into four-token bit patterns. Its process-local workspace is allocated once before graph replay and reused with its real row stride; the resulting boolean mask uses `False` for visible positions and `True` for masked positions. - **Standard GBSA preparation**: `_prepare_qsa_gbsa_rows_kernel` removes invalid groups, preserves selection order, appends/replaces the residual group at the 512-entry capacity boundary, replicates sparse indices per KV head, and gathers the request block-table row. - **Shared Union preparation**: `AscendQSAMetadataBuilder.prepare_step_metadata()` computes per-query visible lengths and prepares request boundaries, row maps and block tables once per step for layers that share the same metadata. The worker invokes it after all cache metadata has been built. - **Multi-request batching**: Union Prefill requests with contiguous query rows can share one GBSA call. Each request forms its own groups of up to eight query rows. Unused lanes in the row map are set to `-1`. @@ -24,27 +22,25 @@ | sequence lengths | input | `[requests]` | int32 | | token-to-request map | input | `[query_rows]` | int32 | | block table | input | `[requests, pages]` | int32, arbitrary positive row/column stride | -| FIA mask | output | `[query_rows, mask_kv_length]` | bool; `True` masks a KV position | | GBSA sparse indices | output | `[kv_heads, query_rows, output_groups]` | int32, `-1` padding | -The Qwen3.8 LightningIndexer ABI fixes `token_topk=2048`, `compress_ratio=4`, and therefore `groups=512`. Shorter synthetic group widths are supported by the reusable FIA workspace and are covered by the wide-to-narrow stride regression. +The Qwen3.8 LightningIndexer ABI fixes `token_topk=2048`, `compress_ratio=4`, and therefore `groups=512`. ## Tiling, specialization, and graph constraints - `GROUPS`, `OUTPUT_GROUPS`, `GROUP_BLOCK`, `KV_HEADS`, `TABLE_BLOCK`, and QSA packing widths affect vector/tile shape and remain `tl.constexpr`. Their serving variant sets are model-static or bounded powers of two. - KV length, visible length, row count, tensor strides, and request IDs are runtime values and do not create per-request JIT variants. -- `WORD_BLOCK` is a bounded power-of-two mask tile (maximum 4096 words); `TABLE_BLOCK` is the bounded power-of-two capacity of the configured block table. -- The process-local FIA workspace must be sized before graph capture. It is deliberately not reallocated on the serving hot path because replacing captured device pointers would require graph recapture. +- `TABLE_BLOCK` is the bounded power-of-two capacity of the configured block table. - Triton-Ascend 3.6.0.post2 only requires power-of-two `tl.arange` ranges in SIMT mode. The A3 HACC lowering used here accepts and emits the fixed 515-lane QSA packing range; a real-NPU compile/run test and TTIR are retained with validation evidence. -Normal serving constrains each scheduler chunk with `max_num_batched_tokens` (4096 in the validated deployment). The dispatch decision is based on the cached prefix at the start of the chunk, so a chunk that crosses 24K remains wholly on FIA and the following chunk switches to GBSA. This preserves one operator per request/chunk. Direct callers that bypass scheduler chunking are outside this serving contract; FIA additionally tiles mask construction to a 64 MiB workspace budget. +PCP full-graph execution uses standard GBSA with its padded metadata. ## Validation Run CPU semantic coverage with: ```bash -pytest -q tests/ut/models/qwen4_exp/test_fia_dispatch.py tests/ut/models/qwen4_exp/test_gbsa_preparation.py +pytest -q tests/ut/models/qwen4_exp/test_attention_dispatch.py tests/ut/models/qwen4_exp/test_gbsa_preparation.py ``` Run the A3 native kernels with: @@ -53,17 +49,19 @@ Run the A3 native kernels with: pytest -q tests/e2e/nightly/single_node/ops/singlecard_ops/triton/test_qwen4_exp_qsa.py ``` -The native test is discovered by the existing `singlecard-ops-a3` nightly matrix. It compiles and executes QSA packing, FIA wide-to-narrow workspace reuse, and GBSA preparation against independent PyTorch expectations, including residual boundaries, invalid holes, ragged requests, and a non-contiguous block table. +The native test is discovered by the existing `singlecard-ops-a3` nightly matrix. It compiles and executes QSA packing and GBSA preparation against independent PyTorch expectations, including residual boundaries, invalid holes, ragged requests, and a non-contiguous block table. The production QSA-to-CANN GBSA integration path is covered by: ```bash -pytest -q tests/e2e/nightly/single_node/ops/singlecard_ops/test_qwen4_exp_gbsa.py +pytest -q \ + tests/e2e/nightly/single_node/ops/singlecard_ops/triton/test_qwen4_exp_qsa.py::test_qwen4_exp_gbsa_matches_dense_reference \ + tests/e2e/nightly/single_node/ops/singlecard_ops/triton/test_qwen4_exp_qsa.py::test_qwen4_exp_gbsa_npugraph_replays_updated_input ``` -This supplemental test passes compact LI-v2 indices through -`qsa_gbsa_attention`, compares the BF16 output with an independent dense FP32 -attention reference, and covers eager execution, `torch.compile`, and NPUGraph +These tests pass compact LI-v2 indices through +`qsa_gbsa_attention`, compare the BF16 output with an independent dense FP32 +attention reference, and cover eager execution, `torch.compile`, and NPUGraph replay after updating an input. Triton packing and metadata outputs remain exactly compared in `test_qwen4_exp_qsa.py`, as required for integer and index results. diff --git a/vllm_ascend/ops/triton/qwen4_exp/fia.py b/vllm_ascend/ops/triton/qwen4_exp/fia.py deleted file mode 100644 index 7a32e1ce08b0..000000000000 --- a/vllm_ascend/ops/triton/qwen4_exp/fia.py +++ /dev/null @@ -1,209 +0,0 @@ -# SPDX-License-Identifier: Apache-2.0 -"""Qwen4Exp masks using aligned 32-bit writes for four-token QSA groups.""" - -import torch -from vllm.triton_utils import tl, triton - -QSA_FIA_MASK_WORD_TILE = 4096 -_QSA_FIA_MASK_WORKSPACES: dict[str, "QSAFIAMaskWorkspace"] = {} - - -class QSAFIAMaskWorkspace: - """Process-local FIA mask storage shared by every QSA layer and step.""" - - def __init__(self, device: torch.device, max_rows: int, max_bytes: int, max_update_width: int) -> None: - self.device = device - self.max_rows = max_rows - self.max_update_width = max_update_width - self.mask_word_capacity = max_bytes // torch.int32.itemsize - self.word_capacity = self.mask_word_capacity + max_rows * max_update_width - self.storage = torch.empty((self.word_capacity,), dtype=torch.int32, device=device) - self.words = torch.empty((self.mask_word_capacity,), dtype=torch.int32, device=device) - self.indices = torch.empty((max_rows, max_update_width), dtype=torch.int64, device=device) - self.updates = torch.empty((max_rows, max_update_width), dtype=torch.int32, device=device) - self.selected = torch.empty((max_rows,), dtype=torch.bool, device=device) - - def views( - self, rows: int, mask_words: int, update_width: int - ) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]: - mask_size = rows * mask_words - word_stride = mask_words + update_width - storage_size = rows * word_stride - if ( - rows > self.max_rows - or mask_size > self.mask_word_capacity - or storage_size > self.word_capacity - or update_width > self.max_update_width - ): - raise ValueError( - f"QSA FIA mask workspace cannot cover rows={rows}, words={mask_words}, updates={update_width}" - ) - storage = self.storage[:storage_size].view(rows, word_stride) - words = self.words[:mask_size].view(rows, mask_words) - return ( - storage, - words, - self.indices[:rows, :update_width], - self.updates[:rows, :update_width], - self.selected[:rows], - ) - - -def get_qsa_fia_mask_workspace( - device: torch.device, max_rows: int, max_bytes: int, max_update_width: int -) -> QSAFIAMaskWorkspace: - """Allocate the process-local dense mask buffer once, then reuse it.""" - key = str(device) - workspace = _QSA_FIA_MASK_WORKSPACES.get(key) - if workspace is None: - workspace = QSAFIAMaskWorkspace(device, max_rows, max_bytes, max_update_width) - _QSA_FIA_MASK_WORKSPACES[key] = workspace - elif ( - workspace.max_rows < max_rows - or workspace.mask_word_capacity * torch.int32.itemsize < max_bytes - or workspace.max_update_width < max_update_width - ): - raise ValueError("QSA FIA mask workspace was initialized with insufficient capacity") - return workspace - - -@triton.jit(do_not_specialize=["mask_words"]) -def _initialize_qsa_mask_words_kernel( - words, - mask_words, - word_stride, - WORD_BLOCK: tl.constexpr, -): - row = tl.program_id(0) - for word_start in range(0, mask_words, WORD_BLOCK): - word = word_start + tl.arange(0, WORD_BLOCK) - tl.store(words + row * word_stride + word, 0x01010101, word < mask_words) - - -@triton.jit(do_not_specialize=["kv_length", "mask_words"]) -def _prepare_qsa_mask_words_kernel( - compact_indices, - visible_lens, - scatter_indices, - updates, - has_selection, - stride_row, - stride_column, - scatter_stride_row, - updates_stride_row, - kv_length, - mask_words, - update_width, - GROUPS: tl.constexpr, - BLOCK: tl.constexpr, -): - row = tl.program_id(0) - columns = tl.arange(0, BLOCK) - visible = tl.minimum(tl.maximum(tl.load(visible_lens + row), 0), kv_length) - group = tl.load(compact_indices + row * stride_row + columns * stride_column, columns < GROUPS, other=-1) - valid = (columns < GROUPS) & (group >= 0) & (group < visible // 4) - residual = visible % 4 - valid_count = tl.sum(valid.to(tl.int32), 0) - if GROUPS >= 512: - if residual != 0: - # GBSA replaces the final selected full group with its residual - # group only when all GROUPS entries are valid. Dropping the - # rightmost valid lane is equivalent to the old prefix cumsum, - # but avoids a full-width scan for every query row. - last_valid_column = tl.max(tl.where(valid, columns, -1), 0) - valid = valid & ((valid_count < GROUPS) | (columns != last_valid_column)) - selected = (valid_count > 0) | (residual != 0) - # Each complete four-token group is one aligned int32 mask word. Keep - # row-local targets so ScatterElementsV2 can use its efficient dim=1 path. - target = tl.where(valid, group, mask_words + columns) - tail = (columns == GROUPS) & (residual != 0) - tail_value = (0x01010101 << (residual * 8)).to(tl.int32) - target = tl.where(tail, visible // 4, target) - value = tl.where(tail, tail_value, 0) - # An empty row attends token zero and is explicitly zeroed after FIA. - dummy = (columns == 0) & (~selected) - target = tl.where(dummy, 0, target) - value = tl.where(dummy, 0x01010100, value) - store_mask = columns < update_width - tl.store(scatter_indices + row * scatter_stride_row + columns, target.to(tl.int64), store_mask) - tl.store(updates + row * updates_stride_row + columns, value, store_mask) - tl.store(has_selection + row, selected) - - -@triton.jit -def _copy_qsa_fia_output_kernel( - result, - selected, - output, - stride_row, - stride_head, - stride_dim, - HEAD_DIM: tl.constexpr, - WIDTH: tl.constexpr, - BLOCK: tl.constexpr, - CONTIGUOUS: tl.constexpr, -): - row = tl.program_id(0) - columns = tl.program_id(1) * BLOCK + tl.arange(0, BLOCK) - values = tl.load(result + row * WIDTH + columns, columns < WIDTH, other=0) - valid = tl.load(selected + row) - if CONTIGUOUS: - offset = row * WIDTH + columns - else: - offset = row * stride_row + columns // HEAD_DIM * stride_head + columns % HEAD_DIM * stride_dim - tl.store(output + offset, tl.where(valid, values, 0), columns < WIDTH) - - -def build_qsa_fia_mask( - compact_indices: torch.Tensor, - visible_lens: torch.Tensor, - kv_length: int, - mask_width: int, - workspace: QSAFIAMaskWorkspace, -) -> tuple[torch.Tensor, torch.Tensor]: - """Fill and return a reusable [T, KV] mask plus nonempty-row flags.""" - rows = compact_indices.shape[0] - # Dense DMA stores must not share a 32-byte block with another row. - mask_words = triton.cdiv(mask_width, 32) * 8 - groups = compact_indices.shape[1] - 3 - update_width = triton.cdiv(groups + 1, 8) * 8 - storage, words, indices, updates, selected = workspace.views(rows, mask_words, update_width) - word_stride = mask_words + update_width - word_block = min(QSA_FIA_MASK_WORD_TILE, triton.next_power_of_2(mask_words)) - _initialize_qsa_mask_words_kernel[(rows,)](storage, mask_words, word_stride, WORD_BLOCK=word_block) - _prepare_qsa_mask_words_kernel[(rows,)]( - compact_indices, - visible_lens, - indices, - updates, - selected, - compact_indices.stride(0), - compact_indices.stride(1), - indices.stride(0), - updates.stride(0), - kv_length=kv_length, - mask_words=mask_words, - update_width=update_width, - GROUPS=groups, - BLOCK=triton.next_power_of_2(update_width), - ) - storage.scatter_(1, indices, updates) - words.copy_(storage[:, :mask_words]) - # Ascend's little-endian int32 representation is four bool bytes. This is - # a dtype view, not a numerical conversion (which would collapse the bytes). - mask = words.view(torch.bool) - return mask[:, :mask_width], selected - - -def copy_qsa_fia_output(result: torch.Tensor, selected: torch.Tensor, output: torch.Tensor) -> None: - width = output.shape[1] * output.shape[2] - _copy_qsa_fia_output_kernel[(output.shape[0], triton.cdiv(width, 1024))]( - result, - selected, - output, - *output.stride(), - HEAD_DIM=output.shape[2], - WIDTH=width, - BLOCK=1024, - CONTIGUOUS=output.is_contiguous(), - )