From f4de6abee64727d8b52bc732c589babb754df060 Mon Sep 17 00:00:00 2001 From: flb_ Date: Mon, 28 Sep 2026 14:46:45 +0800 Subject: [PATCH] feat(npu): Support returning indexer top-k results (#39060) --- .../npu/attention/ascend_dsv4_backend.py | 5 + .../modules/deepseek_v2_attention_mla_npu.py | 3 + .../sglang/srt/state_capturer/indexer_topk.py | 16 +- .../sglang/test/ascend/test_ascend_utils.py | 4 + ...est_npu_return_indexer_topk_deepseek_v4.py | 169 ++++++++++++++++++ .../test_npu_return_indexer_topk_glm52.py | 124 +++++++++++++ .../test_npu_indexer_topk_capturer.py | 115 ++++++++++++ 7 files changed, 430 insertions(+), 6 deletions(-) create mode 100644 test/registered/npu/rl/indexer_replay/test_npu_return_indexer_topk_deepseek_v4.py create mode 100644 test/registered/npu/rl/indexer_replay/test_npu_return_indexer_topk_glm52.py create mode 100644 test/registered/unit/state_capturer/test_npu_indexer_topk_capturer.py diff --git a/python/sglang/srt/hardware_backend/npu/attention/ascend_dsv4_backend.py b/python/sglang/srt/hardware_backend/npu/attention/ascend_dsv4_backend.py index ef8eeef510..81d80ebecf 100644 --- a/python/sglang/srt/hardware_backend/npu/attention/ascend_dsv4_backend.py +++ b/python/sglang/srt/hardware_backend/npu/attention/ascend_dsv4_backend.py @@ -23,6 +23,7 @@ from sglang.srt.layers.cp.base import get_cp_strategy from sglang.srt.model_executor.forward_batch_info import DSV4OutCacheLoc, ForwardMode from sglang.srt.model_executor.forward_context import get_attn_backend from sglang.srt.runtime_context import get_parallel +from sglang.srt.state_capturer.indexer_topk import maybe_capture_indexer_topk if TYPE_CHECKING: from sglang.srt.layers.radix_attention import RadixAttention @@ -899,6 +900,10 @@ class C4IndexerAscendBackendMixin: ) topk_idxs = self._forward_indexer(c4_indexer, x, q, weights, forward_batch) self.forward_metadata.c4_topk_indices = topk_idxs + compress_layer_id = self.token_to_kv_pool.layer_mapping[ + c4_indexer.layer_id + ].compress_layer_id + maybe_capture_indexer_topk(compress_layer_id, topk_idxs) def _cp_local_positions(self, forward_batch: ForwardBatch) -> torch.Tensor: """Per-rank positions under CP-v2 (the batch keeps full-length ones).""" diff --git a/python/sglang/srt/hardware_backend/npu/modules/deepseek_v2_attention_mla_npu.py b/python/sglang/srt/hardware_backend/npu/modules/deepseek_v2_attention_mla_npu.py index 37701d22ee..9905cdb07a 100644 --- a/python/sglang/srt/hardware_backend/npu/modules/deepseek_v2_attention_mla_npu.py +++ b/python/sglang/srt/hardware_backend/npu/modules/deepseek_v2_attention_mla_npu.py @@ -18,6 +18,7 @@ from sglang.srt.layers.attention.dsa.utils import ( from sglang.srt.layers.communicator import get_attn_tp_context from sglang.srt.model_executor.forward_context import get_token_to_kv_pool from sglang.srt.runtime_context import get_disagg +from sglang.srt.state_capturer.indexer_topk import maybe_capture_indexer_topk if TYPE_CHECKING: from sglang.srt.model_executor.forward_batch_info import ForwardBatch @@ -490,6 +491,8 @@ def forward_dsa_prepare_npu( else: topk_indices = prev_topk_indices + topk_indices = maybe_capture_indexer_topk(m.layer_id, topk_indices) + return ( q_pe, k_pe, diff --git a/python/sglang/srt/state_capturer/indexer_topk.py b/python/sglang/srt/state_capturer/indexer_topk.py index e31951c1f7..70a289a864 100644 --- a/python/sglang/srt/state_capturer/indexer_topk.py +++ b/python/sglang/srt/state_capturer/indexer_topk.py @@ -97,12 +97,11 @@ def create_indexer_capturer( ) -> Optional[IndexerTopkCapturer]: enable = get_exec().features.enable_return_indexer_topk - # Producer wiring is CUDA-only (Indexer.forward_cuda + MLA skip_topk - # path); other backends would create a capturer but never feed it. - if enable and device != "cuda": + # Producer wiring is CUDA/NPU-only; other backends + # would create a capturer but never feed it. + if enable and device != "cuda" and device != "npu": logger.warning( - "indexer-topk capture is CUDA-only; %s backend not yet wired. " - "Disabling capturer.", + "indexer-topk capture is not wired for %s backend. Disabling capturer.", device, ) return None @@ -130,9 +129,14 @@ def _create_indexer_capturer_raw( ) -> Optional[IndexerTopkCapturer]: if not enable: return None - if num_indexer_layers == 0: + if num_indexer_layers <= 0: logger.warning("No indexer layers found, IndexerTopkCapturer disabled") return None + if index_topk <= 0: + logger.warning( + "Invalid index_topk=%s, IndexerTopkCapturer disabled", index_topk + ) + return None return IndexerTopkCapturer( num_tokens=num_tokens, num_indexer_layers=num_indexer_layers, diff --git a/python/sglang/test/ascend/test_ascend_utils.py b/python/sglang/test/ascend/test_ascend_utils.py index a64473ea34..f061ae602c 100644 --- a/python/sglang/test/ascend/test_ascend_utils.py +++ b/python/sglang/test/ascend/test_ascend_utils.py @@ -59,6 +59,9 @@ DEEPSEEK_V3_2_EXP_W8A8_WEIGHTS_PATH = os.path.join( DEEPSEEK_V3_2_W8A8_WEIGHTS_PATH = os.path.join( MODEL_WEIGHTS_DIR, "vllm-ascend/DeepSeek-V3.2-W8A8" ) +DEEPSEEK_V4_FLASH_BF16_MODEL_PATH = os.path.join( + MODEL_WEIGHTS_DIR, "deepseek-ai/DeepSeek-V4-Flash-BF16" +) DEEPSEEK_CODER_V2_LITE_WEIGHTS_PATH = os.path.join( MODEL_WEIGHTS_DIR, "deepseek-ai/DeepSeek-Coder-V2-Lite-Instruct" ) @@ -87,6 +90,7 @@ GEMMA_4_26B_A4B_IT_WEIGHTS_PATH = os.path.join( GEMMA_4_31B_WEIGHTS_PATH = os.path.join(MODEL_WEIGHTS_DIR, "google/gemma-4-31B-it") GLM_4_9B_CHAT_WEIGHTS_PATH = os.path.join(MODEL_WEIGHTS_DIR, "ZhipuAI/glm-4-9b-chat") GLM_5_1_W4A8_MODEL_PATH = os.path.join(MODEL_WEIGHTS_DIR, "Eco-Tech/GLM-5.1-w4a8") +GLM_5_2_BF16_MODEL_PATH = os.path.join(MODEL_WEIGHTS_DIR, "ZhipuAI/GLM-5.2") GPT_OSS_120B_BF16_WEIGHTS_PATH = os.path.join( MODEL_WEIGHTS_DIR, "eigen-ai-labs/gpt-oss-120b-bf16" ) diff --git a/test/registered/npu/rl/indexer_replay/test_npu_return_indexer_topk_deepseek_v4.py b/test/registered/npu/rl/indexer_replay/test_npu_return_indexer_topk_deepseek_v4.py new file mode 100644 index 0000000000..21389a9492 --- /dev/null +++ b/test/registered/npu/rl/indexer_replay/test_npu_return_indexer_topk_deepseek_v4.py @@ -0,0 +1,169 @@ +import asyncio +import os +import subprocess +import unittest + +import aiohttp +import numpy as np + +from sglang.srt.state_capturer.indexer_topk import ( + extract_indexer_topk_from_meta_info, +) +from sglang.srt.utils import kill_process_tree +from sglang.test.ascend.test_ascend_utils import ( + DEEPSEEK_V4_FLASH_BF16_MODEL_PATH, +) +from sglang.test.ci.ci_register import register_npu_ci +from sglang.test.test_utils import ( + DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH, + DEFAULT_URL_FOR_TEST, + CustomTestCase, +) +from sglang.utils import wait_for_server + +register_npu_ci(est_time=400, suite="nightly-2-npu-a3", nightly=True) +register_npu_ci(est_time=400, suite="base-b-test-2-npu-a3") + + +# Keep the first 6 layers of the BF16 checkpoint. The first 6 V4-Flash +# layers have compress_ratios [0, 0, 4, 128, 4, 128], hence two C4 indexer layers. +NUM_INDEXER_LAYERS = 2 +INDEX_TOPK = 512 + +DEEPSEEK_V4_BF16_ENVS = { + "SGLANG_OPT_FP8_WO_A_GEMM": "0", + "SGLANG_OPT_USE_OVERLAP_STORE_CACHE": "False", + "SGLANG_DSV4_FP4_EXPERTS": "False", + "SGLANG_OPT_FUSE_WQA_WKV": "0", + "SGLANG_OPT_BF16_FP32_GEMM_ALGO": "torch", + "SGLANG_OPT_USE_FUSED_HASH_TOPK": "False", + "SGLANG_OPT_USE_TILELANG_MHC_PRE": "False", + "SGLANG_OPT_DEEPGEMM_HC_PRENORM": "False", + "SGLANG_OPT_USE_TILELANG_MHC_POST": "False", + "SGLANG_ENABLE_WAR_BARRIER": "1", + "SGLANG_FORCE_COARSE_WAR_BARRIER": "1", +} + + +@unittest.skipUnless( + os.path.isfile(os.path.join(DEEPSEEK_V4_FLASH_BF16_MODEL_PATH, "config.json")), + f"DeepSeek-V4-Flash model config not found at {DEEPSEEK_V4_FLASH_BF16_MODEL_PATH}", +) +class TestNPUDeepSeekV4ReturnIndexerTopk(CustomTestCase): + """End-to-end validation of DeepSeek-V4 C4 NPU indexer-topk responses.""" + + @classmethod + def setUpClass(cls): + cls.sampling_args = {"temperature": 0, "max_new_tokens": 16} + cls.texts = [ + "What is the capital of France?", + "Solve: 2 + 3 = ?", + ] + env = os.environ.copy() + env.update(DEEPSEEK_V4_BF16_ENVS) + _, host, port = DEFAULT_URL_FOR_TEST.split(":") + server_command = [ + "python3", + "-m", + "sglang.launch_server", + "--model-path", + DEEPSEEK_V4_FLASH_BF16_MODEL_PATH, + "--page-size", + "128", + "--device", + "npu", + "--attention-backend", + "dsv4", + "--load-format", + "dummy", + "--trust-remote-code", + "--mem-fraction-static", + "0.72", + "--tp-size", + "2", + "--dp-size", + "2", + "--enable-dp-attention", + "--enable-dp-lm-head", + "--kv-cache-dtype", + "auto", + "--disable-cuda-graph", + "--enable-return-indexer-topk", + "--json-model-override-args", + '{"num_hidden_layers": 6, "compress_ratios": [0, 0, 4, 128, 4, 128]}', + "--host", + host[2:], + "--port", + port, + ] + command = [ + "bash", + "-c", + "source /usr/local/Ascend/ascend-toolkit/latest/opp/vendors/customize/bin/set_env.bash || true; " + "source /usr/local/Ascend/ascend-toolkit/latest/opp/vendors/custom_transformer/bin/set_env.bash || true; " + 'exec "$@"', + "bash", + *server_command, + ] + cls.process = subprocess.Popen(command, env=env) + wait_for_server( + DEFAULT_URL_FOR_TEST, + timeout=DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH, + process=cls.process, + ) + try: + cls.captured = asyncio.run(cls._collect_async()) + except Exception: + kill_process_tree(cls.process.pid) + raise + + @classmethod + def tearDownClass(cls): + if hasattr(cls, "process") and cls.process: + kill_process_tree(cls.process.pid) + + def test_return_indexer_topk_shape_and_range(self): + for topk in self.captured: + self._check_shape_and_range(topk) + + def _check_shape_and_range(self, topk: np.ndarray): + self.assertEqual(topk.ndim, 3) + seqlen_minus_1, num_layers, topk_size = topk.shape + self.assertGreater(seqlen_minus_1, 0) + self.assertEqual(num_layers, NUM_INDEXER_LAYERS) + self.assertEqual(topk_size, INDEX_TOPK) + self.assertTrue((topk >= -1).all(), f"min index {topk.min()} < -1") + + @classmethod + async def _collect_async(cls): + async with aiohttp.ClientSession() as session: + tasks = [ + asyncio.create_task( + make_request( + session, + f"{DEFAULT_URL_FOR_TEST}/generate", + { + "text": text, + "sampling_params": cls.sampling_args, + "return_indexer_topk": True, + }, + ) + ) + for text in cls.texts + ] + http_results = await asyncio.gather(*tasks) + return [ + extract_indexer_topk_from_meta_info(res).reshape( + -1, NUM_INDEXER_LAYERS, INDEX_TOPK + ) + for res in http_results + ] + + +async def make_request(session, url, payload): + async with session.post(url=url, json=payload) as response: + return await response.json() + + +if __name__ == "__main__": + unittest.main() diff --git a/test/registered/npu/rl/indexer_replay/test_npu_return_indexer_topk_glm52.py b/test/registered/npu/rl/indexer_replay/test_npu_return_indexer_topk_glm52.py new file mode 100644 index 0000000000..3cc9b95527 --- /dev/null +++ b/test/registered/npu/rl/indexer_replay/test_npu_return_indexer_topk_glm52.py @@ -0,0 +1,124 @@ +import asyncio +import os +import unittest + +import aiohttp +import numpy as np + +from sglang.srt.state_capturer.indexer_topk import ( + extract_indexer_topk_from_meta_info, +) +from sglang.srt.utils import kill_process_tree +from sglang.test.ascend.test_ascend_utils import GLM_5_2_BF16_MODEL_PATH +from sglang.test.ci.ci_register import register_npu_ci +from sglang.test.test_utils import ( + DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH, + DEFAULT_URL_FOR_TEST, + CustomTestCase, + popen_launch_server, +) + +register_npu_ci(est_time=400, suite="nightly-2-npu-a3", nightly=True) +register_npu_ci(est_time=400, suite="base-b-test-2-npu-a3") + + +NUM_INDEXER_LAYERS = 6 +INDEX_TOPK = 2048 + + +@unittest.skipUnless( + os.path.isfile(os.path.join(GLM_5_2_BF16_MODEL_PATH, "config.json")), + f"GLM-5.2 model config not found at {GLM_5_2_BF16_MODEL_PATH}", +) +class TestNPUGLM52ReturnIndexerTopk(CustomTestCase): + """End-to-end validation of GLM-5.2 NPU indexer-topk responses.""" + + @classmethod + def setUpClass(cls): + cls.sampling_args = {"temperature": 0, "max_new_tokens": 16} + cls.texts = [ + "What is the capital of France?", + "Solve: 2 + 3 = ?", + ] + cls.process = popen_launch_server( + GLM_5_2_BF16_MODEL_PATH, + DEFAULT_URL_FOR_TEST, + timeout=DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH, + other_args=[ + "--device", + "npu", + "--attention-backend", + "ascend", + "--load-format", + "dummy", + "--trust-remote-code", + "--mem-fraction-static", + "0.56", + "--tp-size", + "2", + "--dp-size", + "2", + "--enable-dp-attention", + "--enable-dp-lm-head", + "--disable-cuda-graph", + "--enable-return-indexer-topk", + "--json-model-override-args", + '{"num_hidden_layers": 6}', + ], + ) + try: + cls.captured = asyncio.run(cls._collect_async()) + except Exception: + kill_process_tree(cls.process.pid) + raise + + @classmethod + def tearDownClass(cls): + if hasattr(cls, "process") and cls.process: + kill_process_tree(cls.process.pid) + + def test_return_indexer_topk_shape_and_range(self): + for topk in self.captured: + self._check_shape_and_range(topk) + + def _check_shape_and_range(self, topk: np.ndarray): + self.assertEqual(topk.ndim, 3) + seqlen_minus_1, num_layers, topk_size = topk.shape + self.assertGreater(seqlen_minus_1, 0) + self.assertEqual(num_layers, NUM_INDEXER_LAYERS) + self.assertEqual(topk_size, INDEX_TOPK) + self.assertTrue((topk >= -1).all(), f"min index {topk.min()} < -1") + + @classmethod + async def _collect_async(cls): + async with aiohttp.ClientSession() as session: + tasks = [ + asyncio.create_task( + make_request( + session, + f"{DEFAULT_URL_FOR_TEST}/generate", + { + "text": text, + "sampling_params": cls.sampling_args, + "return_indexer_topk": True, + }, + ) + ) + for text in cls.texts + ] + http_results = await asyncio.gather(*tasks) + return [ + extract_indexer_topk_from_meta_info(res).reshape( + -1, NUM_INDEXER_LAYERS, INDEX_TOPK + ) + for res in http_results + ] + + +async def make_request(session, url, payload): + async with session.post(url=url, json=payload) as response: + return await response.json() + + +if __name__ == "__main__": + unittest.main() diff --git a/test/registered/unit/state_capturer/test_npu_indexer_topk_capturer.py b/test/registered/unit/state_capturer/test_npu_indexer_topk_capturer.py new file mode 100644 index 0000000000..a3a3ce0d14 --- /dev/null +++ b/test/registered/unit/state_capturer/test_npu_indexer_topk_capturer.py @@ -0,0 +1,115 @@ +"""Indexer top-k capturer backend selection tests.""" + +import unittest +from types import SimpleNamespace +from unittest import mock + +from sglang.srt.state_capturer import indexer_topk as indexer_topk_mod +from sglang.test.ci.ci_register import register_cpu_ci +from sglang.test.test_utils import CustomTestCase + +register_cpu_ci(est_time=20, suite="base-a-test-cpu") + + +def _model_config(architecture, **attrs): + text_config = SimpleNamespace( + architectures=[architecture], + index_topk=8, + num_hidden_layers=4, + compress_ratios=[4, 0, 4, 128], + **attrs, + ) + return SimpleNamespace(hf_text_config=text_config) + + +class TestIndexerTopkNpuSupport(CustomTestCase): + def _enabled_exec(self): + return SimpleNamespace( + features=SimpleNamespace(enable_return_indexer_topk=True) + ) + + def test_npu_dsa_uses_common_capturer(self): + config = _model_config("GlmMoeDsaForCausalLM") + sentinel = object() + with ( + mock.patch.object( + indexer_topk_mod, "get_exec", return_value=self._enabled_exec() + ), + mock.patch.object( + indexer_topk_mod, + "_create_indexer_capturer_raw", + return_value=sentinel, + ) as create, + ): + result = indexer_topk_mod.create_indexer_capturer( + model_config=config, + num_tokens=32, + max_running_requests=4, + device="npu", + ) + + self.assertIs(result, sentinel) + self.assertEqual(create.call_args.kwargs["num_indexer_layers"], 4) + self.assertEqual(create.call_args.kwargs["index_topk"], 8) + + def test_npu_v4_uses_compressed_layer_count(self): + config = _model_config("DeepseekV4ForCausalLM") + sentinel = object() + with ( + mock.patch.object( + indexer_topk_mod, "get_exec", return_value=self._enabled_exec() + ), + mock.patch.object( + indexer_topk_mod, + "_create_indexer_capturer_raw", + return_value=sentinel, + ) as create, + ): + result = indexer_topk_mod.create_indexer_capturer( + model_config=config, + num_tokens=32, + max_running_requests=4, + device="npu", + ) + + self.assertIs(result, sentinel) + self.assertEqual(create.call_args.kwargs["num_indexer_layers"], 2) + + def test_non_indexer_npu_is_disabled_by_zero_layer_count(self): + config = _model_config("LlamaForCausalLM") + with ( + mock.patch.object( + indexer_topk_mod, "get_exec", return_value=self._enabled_exec() + ), + mock.patch.object( + indexer_topk_mod, + "_create_indexer_capturer_raw", + wraps=indexer_topk_mod._create_indexer_capturer_raw, + ) as create, + ): + result = indexer_topk_mod.create_indexer_capturer( + model_config=config, + num_tokens=32, + max_running_requests=4, + device="npu", + ) + + self.assertIsNone(result) + create.assert_called_once() + self.assertEqual(create.call_args.kwargs["num_indexer_layers"], 0) + + def test_invalid_topk_disables_raw_capturer(self): + self.assertIsNone( + indexer_topk_mod._create_indexer_capturer_raw( + enable=True, + num_indexer_layers=2, + index_topk=0, + num_tokens=32, + max_running_requests=4, + device="npu", + ) + ) + + +if __name__ == "__main__": + unittest.main()