diff --git a/asian_ai/performance/SGLang/test/registered/ascend/basic_function/quant/test_npu_gptq_moe.py b/asian_ai/performance/SGLang/test/registered/ascend/basic_function/quant/test_npu_gptq_moe.py new file mode 100644 index 0000000000000000000000000000000000000000..c84f10b798074aa6b4bc344c5b7ab74af56c2deb --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/ascend/basic_function/quant/test_npu_gptq_moe.py @@ -0,0 +1,83 @@ +import logging +import unittest +from types import SimpleNamespace +from urllib.parse import urlparse + +from sglang.srt.utils import kill_process_tree +from sglang.test.ascend.test_ascend_utils import ( + QWEN3_30B_A3B_GPTQ_2507_INT4_WEIGHTS_PATH, +) +from sglang.test.ci.ci_register import register_npu_ci +from sglang.test.few_shot_gsm8k import run_eval as run_eval_few_shot_gsm8k +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="stage-b-test-1-npu-a2", nightly=False) +register_npu_ci(est_time=400, suite="nightly-1-npu-a3", nightly=True) + +logger = logging.getLogger(__name__) + +TEST_MODEL_MATRIX = { + QWEN3_30B_A3B_GPTQ_2507_INT4_WEIGHTS_PATH: { + "accuracy": 0.85, + }, +} + + +class TestAscendGPTQMoEInt4(CustomTestCase): + + @classmethod + def setUpClass(cls): + cls.models = TEST_MODEL_MATRIX.keys() + cls.base_url = DEFAULT_URL_FOR_TEST + cls.url = urlparse(DEFAULT_URL_FOR_TEST) + cls.common_args = [ + "--trust-remote-code", + "--mem-fraction-static", + 0.8, + "--attention-backend", + "ascend", + "--quantization", + "gptq", + ] + + def test_a_gsm8k(self): + for model in self.models: + with self.subTest(model=model): + logger.info(f"##=== Testing accuracy: {model} ===##") + + process = popen_launch_server( + model, + self.base_url, + timeout=DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH, + other_args=[ + *self.common_args, + ], + ) + + try: + args = SimpleNamespace( + num_shots=5, + data_path=None, + num_questions=1319, + max_new_tokens=512, + parallel=128, + host=f"http://{self.url.hostname}", + port=int(self.url.port), + ) + + metrics = run_eval_few_shot_gsm8k(args) + self.assertGreaterEqual( + metrics["accuracy"], + TEST_MODEL_MATRIX[model]["accuracy"], + ) + finally: + kill_process_tree(process.pid) + + +if __name__ == "__main__": + unittest.main() diff --git a/asian_ai/performance/SGLang/test/registered/ascend/basic_function/quant/test_npu_w4a4_quantization.py b/asian_ai/performance/SGLang/test/registered/ascend/basic_function/quant/test_npu_w4a4_quantization.py new file mode 100644 index 0000000000000000000000000000000000000000..ab19e6b418a7321c8a1e03d2342061842463af5e --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/ascend/basic_function/quant/test_npu_w4a4_quantization.py @@ -0,0 +1,82 @@ +""" +Usage: +python3 -m unittest test_ascend_w4a4_quantization.TestAscendW4A4.test_gsm8k +""" + +import os +import time +import unittest + +import requests + +from sglang.test.ascend.gsm8k_ascend_mixin import GSM8KAscendMixin +from sglang.test.ascend.test_ascend_utils import ( + ECO_TECH_QWEN3_32B_W4A4_LAOS_WEIGHTS_PATH, +) +from sglang.test.ci.ci_register import register_npu_ci +from sglang.test.test_utils import CustomTestCase, is_in_ci, write_github_step_summary + +register_npu_ci(est_time=400, suite="stage-b-test-4-npu-a3", nightly=False) +register_npu_ci(est_time=400, suite="nightly-4-npu-a3", nightly=True) + + +class TestAscendW4A4(GSM8KAscendMixin, CustomTestCase): + + model = ECO_TECH_QWEN3_32B_W4A4_LAOS_WEIGHTS_PATH + other_args = [ + "--trust-remote-code", + "--device", + "npu", + "--attention-backend", + "ascend", + "--tp-size", + "4", + "--mem-fraction-static", + "0.8", + "--cuda-graph-bs", + "64", + "--disable-radix-cache", + ] + + env = { + **os.environ, + } + + # GSM8K Configs + accuracy = 0.80 # GSM8K accuracy ≥0.80 + num_questions = 1319 + gsm8k_num_shots = 5 + output_throughput = 1000 # GSM8K output throughput ≥1000 tokens/s + gsm8k_parallel = 64 + + def run_decode(self, max_new_tokens): + response = requests.post( + self.base_url + "/generate", + json={ + "text": "The capital of France is", + "sampling_params": { + "temperature": 0, + "max_new_tokens": max_new_tokens, + }, + "ignore_eos": True, + }, + ) + return response.json() + + def test_throughput(self): + max_tokens = 256 + + tic = time.perf_counter() + res = self.run_decode(max_tokens) + tok = time.perf_counter() + throughput = max_tokens / (tok - tic) + summary = res["text"] + f"\nThroughput: {throughput} tokens/s" + print(summary) + + if is_in_ci(): + write_github_step_summary(summary + "\nThroughput threshold: 35 tokens/s") + self.assertGreaterEqual(throughput, 35) + + +if __name__ == "__main__": + unittest.main() diff --git a/asian_ai/performance/SGLang/test/registered/ascend/basic_function/runtime_opts/test_npu_mla_fia_w8a8int8.py b/asian_ai/performance/SGLang/test/registered/ascend/basic_function/runtime_opts/test_npu_mla_fia_w8a8int8.py new file mode 100644 index 0000000000000000000000000000000000000000..2c9783567738ba9fb6431925af915722e29d8273 --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/ascend/basic_function/runtime_opts/test_npu_mla_fia_w8a8int8.py @@ -0,0 +1,83 @@ +import os +import unittest +from types import SimpleNamespace +from urllib.parse import urlparse + +from sglang.srt.utils import kill_process_tree +from sglang.test.ci.ci_register import register_npu_ci +from sglang.test.few_shot_gsm8k import run_eval as run_eval_few_shot_gsm8k +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="stage-b-test-2-npu-a2", nightly=False) +register_npu_ci(est_time=400, suite="nightly-2-npu-a3", nightly=True) + +TEST_MODEL_MATRIX = { + "/root/.cache/modelscope/hub/models/vllm-ascend/DeepSeek-V2-Lite-W8A8": { + "accuracy": 0.34, + "latency": 1000, + "output_throughput": 6, + }, +} + + +class TestAscendMlaW8A8Int8(CustomTestCase): + + @classmethod + def setUpClass(cls): + cls.models = TEST_MODEL_MATRIX.keys() + cls.base_url = DEFAULT_URL_FOR_TEST + cls.url = urlparse(DEFAULT_URL_FOR_TEST) + cls.common_args = [ + "--trust-remote-code", + "--disable-cuda-graph", + "--mem-fraction-static", + 0.8, + "--attention-backend", + "ascend", + "--tp-size", + 2, + "--disable-radix-cache", + ] + + def test_a_gsm8k(self): + os.environ["ASCEND_USE_FIA"] = "true" + for model in self.models: + with self.subTest(model=model): + print(f"##=== Testing accuracy: {model} ===##") + + process = popen_launch_server( + model, + self.base_url, + timeout=DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH, + other_args=[ + *self.common_args, + ], + ) + + try: + args = SimpleNamespace( + num_shots=5, + data_path=None, + num_questions=1319, + max_new_tokens=512, + parallel=128, + host=f"http://{self.url.hostname}", + port=int(self.url.port), + ) + + metrics = run_eval_few_shot_gsm8k(args) + self.assertGreaterEqual( + metrics["accuracy"], + TEST_MODEL_MATRIX[model]["accuracy"], + ) + finally: + kill_process_tree(process.pid) + + +if __name__ == "__main__": + unittest.main() diff --git a/asian_ai/performance/SGLang/test/registered/ascend/basic_function/runtime_opts/test_npu_mla_w8a8int8.py b/asian_ai/performance/SGLang/test/registered/ascend/basic_function/runtime_opts/test_npu_mla_w8a8int8.py new file mode 100644 index 0000000000000000000000000000000000000000..b65d03b60c806bf83afaf45cd1f4c8794b0ecf86 --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/ascend/basic_function/runtime_opts/test_npu_mla_w8a8int8.py @@ -0,0 +1,81 @@ +import unittest +from types import SimpleNamespace +from urllib.parse import urlparse + +from sglang.srt.utils import kill_process_tree +from sglang.test.ci.ci_register import register_npu_ci +from sglang.test.few_shot_gsm8k import run_eval as run_eval_few_shot_gsm8k +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="stage-b-test-4-npu-a3", nightly=False) +register_npu_ci(est_time=400, suite="nightly-4-npu-a3", nightly=True) + +TEST_MODEL_MATRIX = { + "/root/.cache/modelscope/hub/models/vllm-ascend/DeepSeek-V2-Lite-W8A8": { + "accuracy": 0.34, + "latency": 1000, + "output_throughput": 6, + }, +} + + +class TestAscendMlaW8A8Int8(CustomTestCase): + + @classmethod + def setUpClass(cls): + cls.models = TEST_MODEL_MATRIX.keys() + cls.base_url = DEFAULT_URL_FOR_TEST + cls.url = urlparse(DEFAULT_URL_FOR_TEST) + cls.common_args = [ + "--trust-remote-code", + "--disable-cuda-graph", + "--mem-fraction-static", + 0.8, + "--attention-backend", + "ascend", + "--tp-size", + 4, + "--disable-radix-cache", + ] + + def test_a_gsm8k(self): + for model in self.models: + with self.subTest(model=model): + print(f"##=== Testing accuracy: {model} ===##") + + process = popen_launch_server( + model, + self.base_url, + timeout=DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH, + other_args=[ + *self.common_args, + ], + ) + + try: + args = SimpleNamespace( + num_shots=5, + data_path=None, + num_questions=1319, + max_new_tokens=512, + parallel=128, + host=f"http://{self.url.hostname}", + port=int(self.url.port), + ) + + metrics = run_eval_few_shot_gsm8k(args) + self.assertGreaterEqual( + metrics["accuracy"], + TEST_MODEL_MATRIX[model]["accuracy"], + ) + finally: + kill_process_tree(process.pid) + + +if __name__ == "__main__": + unittest.main() diff --git a/asian_ai/performance/SGLang/test/registered/ascend/basic_function/runtime_opts/test_npu_tp1_bf16.py b/asian_ai/performance/SGLang/test/registered/ascend/basic_function/runtime_opts/test_npu_tp1_bf16.py new file mode 100644 index 0000000000000000000000000000000000000000..de70fed3d26dddc3751a3a7272221fafb3addd67 --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/ascend/basic_function/runtime_opts/test_npu_tp1_bf16.py @@ -0,0 +1,78 @@ +import unittest +from types import SimpleNamespace +from urllib.parse import urlparse + +from sglang.srt.utils import kill_process_tree +from sglang.test.ci.ci_register import register_npu_ci +from sglang.test.few_shot_gsm8k import run_eval as run_eval_few_shot_gsm8k +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="stage-b-test-1-npu-a2", nightly=False) +register_npu_ci(est_time=400, suite="nightly-1-npu-a3", nightly=True) + +TEST_MODEL_MATRIX = { + "/root/.cache/modelscope/hub/models/Qwen/Qwen2.5-7B-Instruct": { + "accuracy": 0.84, + "latency": 150, + "output_throughput": 30, + }, +} + + +class TestAscendTp1Bf16(CustomTestCase): + + @classmethod + def setUpClass(cls): + cls.models = TEST_MODEL_MATRIX.keys() + cls.base_url = DEFAULT_URL_FOR_TEST + cls.url = urlparse(DEFAULT_URL_FOR_TEST) + cls.common_args = [ + "--trust-remote-code", + "--disable-cuda-graph", + "--mem-fraction-static", + 0.8, + "--attention-backend", + "ascend", + ] + + def test_a_gsm8k(self): + for model in self.models: + with self.subTest(model=model): + print(f"##=== Testing accuracy: {model} ===##") + + process = popen_launch_server( + model, + self.base_url, + timeout=DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH, + other_args=[ + *self.common_args, + ], + ) + + try: + args = SimpleNamespace( + num_shots=5, + data_path=None, + num_questions=1319, + max_new_tokens=512, + parallel=128, + host=f"http://{self.url.hostname}", + port=int(self.url.port), + ) + + metrics = run_eval_few_shot_gsm8k(args) + self.assertGreaterEqual( + metrics["accuracy"], + TEST_MODEL_MATRIX[model]["accuracy"], + ) + finally: + kill_process_tree(process.pid) + + +if __name__ == "__main__": + unittest.main() diff --git a/asian_ai/performance/SGLang/test/registered/ascend/basic_function/runtime_opts/test_npu_tp2_bf16.py b/asian_ai/performance/SGLang/test/registered/ascend/basic_function/runtime_opts/test_npu_tp2_bf16.py new file mode 100644 index 0000000000000000000000000000000000000000..b773fc8df21c6ce5849a441dceecb4d9ab21b203 --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/ascend/basic_function/runtime_opts/test_npu_tp2_bf16.py @@ -0,0 +1,80 @@ +import unittest +from types import SimpleNamespace +from urllib.parse import urlparse + +from sglang.srt.utils import kill_process_tree +from sglang.test.ci.ci_register import register_npu_ci +from sglang.test.few_shot_gsm8k import run_eval as run_eval_few_shot_gsm8k +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="stage-b-test-2-npu-a2", nightly=False) +register_npu_ci(est_time=400, suite="nightly-2-npu-a3", nightly=True) + +TEST_MODEL_MATRIX = { + "/root/.cache/modelscope/hub/models/Qwen/Qwen2.5-7B-Instruct": { + "accuracy": 0.85, + "latency": 180, + "output_throughput": 20, + }, +} + + +class TestAscendTp2Bf16(CustomTestCase): + + @classmethod + def setUpClass(cls): + cls.models = TEST_MODEL_MATRIX.keys() + cls.base_url = DEFAULT_URL_FOR_TEST + cls.url = urlparse(DEFAULT_URL_FOR_TEST) + cls.common_args = [ + "--trust-remote-code", + "--disable-cuda-graph", + "--mem-fraction-static", + 0.8, + "--attention-backend", + "ascend", + "--tp-size", + 2, + ] + + def test_a_gsm8k(self): + for model in self.models: + with self.subTest(model=model): + print(f"##=== Testing accuracy: {model} ===##") + + process = popen_launch_server( + model, + self.base_url, + timeout=DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH, + other_args=[ + *self.common_args, + ], + ) + + try: + args = SimpleNamespace( + num_shots=5, + data_path=None, + num_questions=1319, + max_new_tokens=512, + parallel=128, + host=f"http://{self.url.hostname}", + port=int(self.url.port), + ) + + metrics = run_eval_few_shot_gsm8k(args) + self.assertGreaterEqual( + metrics["accuracy"], + TEST_MODEL_MATRIX[model]["accuracy"], + ) + finally: + kill_process_tree(process.pid) + + +if __name__ == "__main__": + unittest.main() diff --git a/asian_ai/performance/SGLang/test/registered/ascend/basic_function/runtime_opts/test_npu_tp2_fia_bf16.py b/asian_ai/performance/SGLang/test/registered/ascend/basic_function/runtime_opts/test_npu_tp2_fia_bf16.py new file mode 100644 index 0000000000000000000000000000000000000000..435d2ab38a09c45859e8209ffa67890350341a75 --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/ascend/basic_function/runtime_opts/test_npu_tp2_fia_bf16.py @@ -0,0 +1,83 @@ +import os +import unittest +from types import SimpleNamespace +from urllib.parse import urlparse + +from sglang.srt.utils import kill_process_tree +from sglang.test.ci.ci_register import register_npu_ci +from sglang.test.few_shot_gsm8k import run_eval as run_eval_few_shot_gsm8k +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="stage-b-test-2-npu-a2", nightly=False) +register_npu_ci(est_time=400, suite="nightly-2-npu-a3", nightly=True) + +TEST_MODEL_MATRIX = { + "/root/.cache/modelscope/hub/models/Qwen/Qwen2.5-7B-Instruct": { + "accuracy": 0.85, + "latency": 180, + "output_throughput": 20, + }, +} + + +class TestAscendTp2Bf16(CustomTestCase): + + @classmethod + def setUpClass(cls): + cls.models = TEST_MODEL_MATRIX.keys() + cls.base_url = DEFAULT_URL_FOR_TEST + cls.url = urlparse(DEFAULT_URL_FOR_TEST) + cls.common_args = [ + "--trust-remote-code", + "--disable-cuda-graph", + "--mem-fraction-static", + 0.8, + "--attention-backend", + "ascend", + "--tp-size", + 2, + "--disable-radix-cache", + ] + + def test_a_gsm8k(self): + os.environ["ASCEND_USE_FIA"] = "true" + for model in self.models: + with self.subTest(model=model): + print(f"##=== Testing accuracy: {model} ===##") + + process = popen_launch_server( + model, + self.base_url, + timeout=DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH, + other_args=[ + *self.common_args, + ], + ) + + try: + args = SimpleNamespace( + num_shots=5, + data_path=None, + num_questions=1319, + max_new_tokens=512, + parallel=128, + host=f"http://{self.url.hostname}", + port=int(self.url.port), + ) + + metrics = run_eval_few_shot_gsm8k(args) + self.assertGreaterEqual( + metrics["accuracy"], + TEST_MODEL_MATRIX[model]["accuracy"], + ) + finally: + kill_process_tree(process.pid) + + +if __name__ == "__main__": + unittest.main() diff --git a/asian_ai/performance/SGLang/test/registered/ascend/basic_function/runtime_opts/test_npu_tp4_bf16.py b/asian_ai/performance/SGLang/test/registered/ascend/basic_function/runtime_opts/test_npu_tp4_bf16.py new file mode 100644 index 0000000000000000000000000000000000000000..8572c55f9cafbbb8f7a2282590e8b6467eeca338 --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/ascend/basic_function/runtime_opts/test_npu_tp4_bf16.py @@ -0,0 +1,83 @@ +import unittest +from types import SimpleNamespace +from urllib.parse import urlparse + +from sglang.srt.utils import kill_process_tree +from sglang.test.ci.ci_register import register_npu_ci +from sglang.test.few_shot_gsm8k import run_eval as run_eval_few_shot_gsm8k +from sglang.test.test_utils import ( + DEFAULT_URL_FOR_TEST, + CustomTestCase, + popen_launch_server, +) + +register_npu_ci(est_time=400, suite="stage-b-test-4-npu-a3", nightly=False) +register_npu_ci(est_time=400, suite="nightly-4-npu-a3", nightly=True) + +TEST_MODEL_MATRIX = { + "Qwen/Qwen3-30B-A3B-Instruct-2507": { + "accuracy": 0.90, + "latency": 180, + "output_throughput": 20, + }, +} + + +class TestAscendTp4Bf16(CustomTestCase): + + @classmethod + def setUpClass(cls): + cls.models = TEST_MODEL_MATRIX.keys() + cls.base_url = DEFAULT_URL_FOR_TEST + cls.url = urlparse(DEFAULT_URL_FOR_TEST) + cls.common_args = [ + "--trust-remote-code", + "--mem-fraction-static", + 0.7, + "--max-running-requests", + 32, + "--attention-backend", + "ascend", + "--disable-radix-cache", + "--cuda-graph-max-bs-decode", + 32, + "--tp-size", + 4, + ] + + def test_a_gsm8k(self): + for model in self.models: + with self.subTest(model=model): + print(f"##=== Testing accuracy: {model} ===##") + + process = popen_launch_server( + model, + self.base_url, + timeout=1800, + other_args=[ + *self.common_args, + ], + ) + + try: + args = SimpleNamespace( + num_shots=5, + data_path=None, + num_questions=1319, + max_new_tokens=512, + parallel=128, + host=f"http://{self.url.hostname}", + port=int(self.url.port), + ) + + metrics = run_eval_few_shot_gsm8k(args) + self.assertGreaterEqual( + metrics["accuracy"], + TEST_MODEL_MATRIX[model]["accuracy"], + ) + finally: + kill_process_tree(process.pid) + + +if __name__ == "__main__": + unittest.main() diff --git a/asian_ai/performance/SGLang/test/registered/ascend/basic_function/speculative_inference/test_npu_eagle3.py b/asian_ai/performance/SGLang/test/registered/ascend/basic_function/speculative_inference/test_npu_eagle3.py new file mode 100644 index 0000000000000000000000000000000000000000..f3fb4288d3ac954a6fdc62cbb54091d4e94c9a19 --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/ascend/basic_function/speculative_inference/test_npu_eagle3.py @@ -0,0 +1,62 @@ +import os +import unittest + +from sglang.test.ascend.gsm8k_ascend_mixin import GSM8KAscendMixin +from sglang.test.ascend.test_ascend_utils import ( + QWEN3_8B_EAGLE3_WEIGHTS_PATH, + QWEN3_8B_WEIGHTS_PATH, +) +from sglang.test.ci.ci_register import register_npu_ci +from sglang.test.test_utils import CustomTestCase + +register_npu_ci(est_time=400, suite="nightly-1-npu-a3", nightly=True) + + +class TestNpuEagle3(GSM8KAscendMixin, CustomTestCase): + """Testcase: Verify GSM8K inference accuracy ≥0.81 for model with specified EAGLE3 speculative inference parameters. + + [Test Category] Speculative Decoding + [Test Target] --speculative-draft-model-quantization; --speculative-algorithm; --speculative-draft-model-path; --speculative-num-steps; --speculative-eagle-topk; --speculative-num-draft-tokens; --speculative-attention-mode + """ + + model = QWEN3_8B_WEIGHTS_PATH + timeout_for_server_launch = 1500 + other_args = [ + "--trust-remote-code", + "--attention-backend", + "ascend", + "--disable-radix-cache", + "--speculative-draft-model-quantization", + "unquant", + "--speculative-algorithm", + "EAGLE3", + "--speculative-draft-model-path", + QWEN3_8B_EAGLE3_WEIGHTS_PATH, + "--speculative-num-steps", + "4", + "--speculative-eagle-topk", + "1", + "--speculative-num-draft-tokens", + "5", + "--speculative-attention-mode", + "decode", + "--tp-size", + "1", + "--mem-fraction-static", + "0.7", + "--disable-cuda-graph", + "--dtype", + "bfloat16", + ] + + env = { + **os.environ, + "SGLANG_ENABLE_OVERLAP_PLAN_STREAM": "1", + } + + accuracy = 0.81 + num_questions = 1319 + + +if __name__ == "__main__": + unittest.main() diff --git a/asian_ai/performance/SGLang/test/registered/ascend/embedding_models/test_npu_bge_large_en_v1_5.py b/asian_ai/performance/SGLang/test/registered/ascend/embedding_models/test_npu_bge_large_en_v1_5.py new file mode 100644 index 0000000000000000000000000000000000000000..c50dbec40b159418aff27e74cc70cb34acd7f920 --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/ascend/embedding_models/test_npu_bge_large_en_v1_5.py @@ -0,0 +1,112 @@ +import multiprocessing as mp +import unittest +from typing import Optional + +import torch +from transformers import AutoConfig, AutoTokenizer + +from sglang.test.ci.ci_register import register_npu_ci +from sglang.test.runners import HFRunner, SRTRunner +from sglang.test.test_utils import CustomTestCase, get_similarities + +register_npu_ci( + est_time=400, + suite="full-1-npu-a3", + nightly=True, + disabled="embeddings are not all close", +) + +DEFAULT_PROMPTS = [ + "The capital of the United Kingdom is", + "Today is a sunny day and I like", + "AI is a field of computer science focused on", +] + +MODELS = [ + ("/root/.cache/modelscope/hub/models/bge-large-en-v1.5", 1, 1e-5), +] +TORCH_DTYPES = [torch.float16] + + +class TestEmbeddingModels(CustomTestCase): + + @classmethod + def setUpClass(cls): + mp.set_start_method("spawn", force=True) + + def _truncate_prompts(self, prompts, model_path): + config = AutoConfig.from_pretrained(model_path) + max_length = getattr(config, "max_position_embeddings", 2048) + + tokenizer = AutoTokenizer.from_pretrained(model_path) + + truncated_prompts = [] + for prompt in prompts: + tokens = tokenizer(prompt, return_tensors="pt", truncation=False) + if len(tokens.input_ids[0]) > max_length: + truncated_text = tokenizer.decode( + tokens.input_ids[0][: max_length - 1], skip_special_tokens=True + ) + truncated_prompts.append(truncated_text) + else: + truncated_prompts.append(prompt) + return truncated_prompts + + def assert_close_prefill_logits( + self, + prompts, + model_path, + tp_size, + torch_dtype, + prefill_tolerance, + matryoshka_dim: Optional[int] = None, + ) -> None: + truncated_prompts = self._truncate_prompts(prompts, model_path) + + with HFRunner( + model_path, + torch_dtype=torch_dtype, + model_type="embedding", + matryoshka_dim=matryoshka_dim, + ) as hf_runner: + hf_outputs = hf_runner.forward(truncated_prompts) + + attention_backend = "ascend" + with SRTRunner( + model_path, + tp_size=tp_size, + torch_dtype=torch_dtype, + model_type="embedding", + attention_backend=attention_backend, + json_model_override_args=( + {"matryoshka_dimensions": [matryoshka_dim]} if matryoshka_dim else None + ), + ) as srt_runner: + srt_outputs = srt_runner.forward( + truncated_prompts, dimensions=matryoshka_dim + ) + + for i in range(len(prompts)): + hf_logits = torch.Tensor(hf_outputs.embed_logits[i]) + srt_logits = torch.Tensor(srt_outputs.embed_logits[i]) + + similarity = torch.tensor(get_similarities(hf_logits, srt_logits)) + print("similarity diff", abs(similarity - 1)) + + if len(prompts[i]) <= 1000: + assert torch.all( + abs(similarity - 1) < prefill_tolerance + ), "embeddings are not all close" + + def test_prefill_logits(self): + models_to_test = MODELS + + for model, tp_size, prefill_tolerance in models_to_test: + for torch_dtype in TORCH_DTYPES: + self.assert_close_prefill_logits( + DEFAULT_PROMPTS, model, tp_size, torch_dtype, prefill_tolerance + ) + + +if __name__ == "__main__": + unittest.main() diff --git a/asian_ai/performance/SGLang/test/registered/ascend/interface/test_npu_api.py b/asian_ai/performance/SGLang/test/registered/ascend/interface/test_npu_api.py new file mode 100644 index 0000000000000000000000000000000000000000..3612d9e81a2e008c80ce25756c8612bed5cffd8f --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/ascend/interface/test_npu_api.py @@ -0,0 +1,735 @@ +import json +import logging +import os +import shutil +import unittest + +import requests +from transformers import AutoTokenizer + +from sglang.srt.environ import envs +from sglang.srt.utils import kill_process_tree +from sglang.test.ascend.test_ascend_utils import LLAMA_3_2_1B_INSTRUCT_WEIGHTS_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, +) + +# Global variables: Manage server process and initialization status +GLOBAL_SERVER_PROCESS = None +GLOBAL_SERVER_INITIALIZED = False +OUTPUT_DIR = "./profiler_dir" + +register_npu_ci(est_time=1600, suite="nightly-npu-a3-merged", nightly=True) + + +class TestNpuApi(CustomTestCase): + """Testcase: Verify that the basic functions of the API interfaces work properly and the returned parameters are consistent with the configurations. + + [Test Category] Interface + [Test Target] /health; /health_generate; /ping; /model_info; /server_info; /v1/loads; /v1/models; /v1/models/{model:path}; /generate + """ + + @classmethod + def setUpClass(cls): + global GLOBAL_SERVER_PROCESS, GLOBAL_SERVER_INITIALIZED + # Start server only if not initialized + if not GLOBAL_SERVER_INITIALIZED: + cls.model = LLAMA_3_2_1B_INSTRUCT_WEIGHTS_PATH + other_args = [ + "--attention-backend", + "ascend", + "--enable-return-hidden-states", + ] + # Start server and save to global variable + GLOBAL_SERVER_PROCESS = popen_launch_server( + cls.model, + DEFAULT_URL_FOR_TEST, + timeout=DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH, + other_args=other_args, + ) + GLOBAL_SERVER_INITIALIZED = True + cls.base_url = DEFAULT_URL_FOR_TEST + + @classmethod + def tearDownClass(cls): + # First class does not terminate server + pass + + def test_api_health(self): + response = requests.get(f"{self.base_url}/health") + self.assertEqual(response.status_code, 200) + + def test_api_health_generate(self): + response = requests.get(f"{self.base_url}/health_generate") + self.assertEqual(response.status_code, 200) + + def test_api_ping(self): + response = requests.get(f"{self.base_url}/ping") + self.assertEqual(response.status_code, 200) + + def test_api_model_info(self): + response = requests.get(f"{self.base_url}/model_info") + self.assertEqual(response.status_code, 200) + self.assertEqual(response.json()["model_path"], self.model) + self.assertEqual(response.json()["tokenizer_path"], self.model) + self.assertTrue(response.json()["is_generation"]) + self.assertIsNone(response.json()["preferred_sampling_params"]) + self.assertEqual(response.json()["weight_version"], "default") + self.assertFalse(response.json()["has_image_understanding"]) + self.assertFalse(response.json()["has_audio_understanding"]) + self.assertEqual(response.json()["model_type"], "llama") + self.assertEqual(response.json()["architectures"][0], "LlamaForCausalLM") + + def test_api_server_info(self): + response = requests.get(f"{self.base_url}/server_info") + self.assertEqual(response.status_code, 200) + self.assertEqual(response.json()["model_path"], self.model) + self.assertEqual(response.json()["tokenizer_path"], self.model) + + def test_api_v1_loads(self): + response = requests.get(f"{self.base_url}/v1/loads") + self.assertEqual(response.status_code, 200) + body = response.json() + self.assertIn("loads", body) + self.assertIn("aggregate", body) + self.assertGreaterEqual(len(body["loads"]), 1) + load = body["loads"][0] + self.assertGreaterEqual(load["num_running_reqs"], 0) + self.assertGreaterEqual(load["num_waiting_reqs"], 0) + self.assertGreaterEqual(load["num_used_tokens"], 0) + self.assertGreaterEqual(load["num_total_tokens"], 0) + + def test_api_v1_models(self): + response = requests.get(f"{self.base_url}/v1/models") + self.assertEqual(response.status_code, 200) + self.assertEqual(response.json()["data"][0]["id"], self.model) + self.assertEqual(response.json()["data"][0]["object"], "model") + self.assertEqual(response.json()["data"][0]["owned_by"], "sglang") + self.assertEqual(response.json()["data"][0]["root"], self.model) + self.assertEqual(response.json()["data"][0]["max_model_len"], 131072) + + def test_api_v1_models_path(self): + response = requests.get(f"{self.base_url}/v1/models/{self.model}") + self.assertEqual(response.status_code, 200) + self.assertEqual(response.json()["id"], self.model) + self.assertEqual(response.json()["object"], "model") + self.assertEqual(response.json()["owned_by"], "sglang") + self.assertEqual(response.json()["root"], self.model) + self.assertEqual(response.json()["max_model_len"], 131072) + + def test_api_generate_single_text(self): + response = requests.post( + f"{self.base_url}/generate", + json={ + "rid": "req_001", + "text": "The capital of France is", + "sampling_params": { + "temperature": 0, + "max_new_tokens": 20, + }, + "return_logprob": True, + "stream": False, + "return_hidden_states": True, + }, + ) + self.assertEqual(response.status_code, 200) + meta_info_keys = response.json()["meta_info"].keys() + self.assertEqual("req_001", response.json()["meta_info"]["id"]) + self.assertIn("Paris", response.json()["text"]) + self.assertEqual(20, response.json()["meta_info"]["completion_tokens"]) + self.assertIn("input_token_logprobs", meta_info_keys) + self.assertIn("output_token_logprobs", meta_info_keys) + self.assertIn("hidden_states", meta_info_keys) + + def test_api_generate_batch_texts(self): + rids = ["req_1", "req_2"] + texts = [ + "The capital of France is", + "What is the best time of year to visit Japan for cherry blossoms?", + ] + response = requests.post( + f"{self.base_url}/generate", + json={ + "rid": rids, + "text": texts, + "sampling_params": { + "temperature": 0, + "max_new_tokens": 20, + }, + "return_logprob": False, + "stream": False, + "return_hidden_states": False, + }, + ) + self.assertEqual(response.status_code, 200) + self.assertEqual("req_1", response.json()[0]["meta_info"]["id"]) + self.assertIn("Paris", response.json()[0]["text"]) + self.assertEqual("req_2", response.json()[1]["meta_info"]["id"]) + self.assertIn("Japan", response.json()[1]["text"]) + + def test_api_generate_temperature(self): + response = requests.post( + f"{self.base_url}/generate", + json={ + "text": "The capital of France is", + "sampling_params": { + "temperature": 5, + "max_new_tokens": 20, + }, + }, + ) + self.assertEqual(response.status_code, 200) + text1 = response.json()["text"] + response = requests.post( + f"{self.base_url}/generate", + json={ + "text": "The capital of France is", + "sampling_params": { + "temperature": 5, + "max_new_tokens": 20, + }, + }, + ) + self.assertEqual(response.status_code, 200) + text2 = response.json()["text"] + self.assertNotEqual(text2, text1) + + def test_api_generate_input_ids(self): + text = "The capital of France is" + tokenizer = AutoTokenizer.from_pretrained(self.model) + input_ids = tokenizer(text, return_tensors="pt")["input_ids"][0].tolist() + response = requests.post( + f"{self.base_url}/generate", + json={ + "rid": "req_002", + "input_ids": input_ids, + "sampling_params": { + "temperature": 0, + "max_new_tokens": 10, + }, + "return_logprob": False, + "stream": True, + "return_hidden_states": False, + }, + ) + self.assertEqual(response.status_code, 200) + lines = response.text.strip().split("\n") + self.assertGreaterEqual(len(lines), 10) + json_data = lines[-3][6:] + data = json.loads(json_data) + meta_info_keys = data["meta_info"].keys() + self.assertEqual("req_002", data["meta_info"]["id"]) + self.assertIn("Paris", data["text"]) + self.assertEqual(10, data["meta_info"]["completion_tokens"]) + self.assertNotIn("input_token_logprobs", meta_info_keys) + self.assertNotIn("output_token_logprobs", meta_info_keys) + self.assertNotIn("hidden_states", meta_info_keys) + + +class TestChatCompletionsInterface(CustomTestCase): + """Testcase: The test is to verify whether the functions of each parameter of the v1/chat/completions interface are normal. + + [Test Category] Interface + [Test Target] v1/chat/completions + """ + + @classmethod + def setUpClass(cls): + # Skip initialization, directly reuse global server + cls.model = LLAMA_3_2_1B_INSTRUCT_WEIGHTS_PATH + cls.base_url = DEFAULT_URL_FOR_TEST + cls.additional_chat_kwargs = {} + + @classmethod + def tearDownClass(cls): + # Do not terminate server + pass + + def test_model_and_messages(self): + response = requests.post( + f"{self.base_url}/v1/chat/completions", + json={ + "model": self.model, + "messages": [{"role": "user", "content": "Hello"}], + }, + ) + self.assertEqual(response.status_code, 200, f"Failed with: {response.text}") + data = response.json() + self.assertEqual(data["model"], self.model) + self.assertIsNotNone(data["choices"][0]["message"]["reasoning_content"]) + + response = requests.post( + f"{self.base_url}/v1/chat/completions", + json={ + "messages": [{"role": "user", "content": "Hello"}], + }, + ) + self.assertEqual(response.status_code, 200, f"Failed with: {response.text}") + data = response.json() + self.assertEqual(data["model"], "default") + self.assertIsNotNone(data["choices"][0]["message"]["reasoning_content"]) + + def test_max_completion_tokens(self): + response = requests.post( + f"{self.base_url}/v1/chat/completions", + json={ + "messages": [{"role": "user", "content": "Hello"}], + "max_completion_tokens": 1, + }, + ) + self.assertEqual(response.status_code, 200, f"Failed with: {response.text}") + self.assertEqual(response.json()["choices"][0]["finish_reason"], "length") + + def test_stream(self): + response = requests.post( + f"{self.base_url}/v1/chat/completions", + json={ + "model": self.model, + "messages": [{"role": "user", "content": "Hello"}], + "stream": True, + }, + ) + self.assertEqual(response.status_code, 200, f"Failed with: {response.text}") + has_reasoning = False + has_content = False + + for line in response.iter_lines(): + if line: + line = line.decode("utf-8") + if line.startswith("data:") and not line.startswith("data: [DONE]"): + data = json.loads(line[6:]) + if "choices" in data and len(data["choices"]) > 0: + delta = data["choices"][0].get("delta", {}) + if "reasoning_content" in delta and delta["reasoning_content"]: + has_reasoning = True + if "content" in delta and delta["content"]: + has_content = True + + self.assertTrue( + has_reasoning, "Reasoning content not included in stream response" + ) + self.assertTrue(has_content, "Normal content not included in stream response") + + def test_temperature(self): + response1 = requests.post( + f"{self.base_url}/v1/chat/completions", + json={ + "model": self.model, + "messages": [ + { + "role": "user", + "content": "Please write a five-character quatrain for me.", + } + ], + "temperature": 0, + }, + ) + self.assertEqual(response1.status_code, 200, f"Failed with: {response1.text}") + content1 = response1.json()["choices"][0]["message"]["content"] + + response2 = requests.post( + f"{self.base_url}/v1/chat/completions", + json={ + "model": self.model, + "messages": [ + { + "role": "user", + "content": "Please write a five-character quatrain for me.", + } + ], + "temperature": 0, + }, + ) + self.assertEqual(response2.status_code, 200, f"Failed with: {response2.text}") + content2 = response2.json()["choices"][0]["message"]["content"] + self.assertEqual(content1, content2) + + response3 = requests.post( + f"{self.base_url}/v1/chat/completions", + json={ + "model": self.model, + "messages": [ + { + "role": "user", + "content": "Please write a five-character quatrain for me.", + } + ], + "temperature": 2, + }, + ) + self.assertEqual(response3.status_code, 200, f"Failed with: {response3.text}") + content3 = response3.json()["choices"][0]["message"]["content"] + + response4 = requests.post( + f"{self.base_url}/v1/chat/completions", + json={ + "model": self.model, + "messages": [ + { + "role": "user", + "content": "Please write a five-character quatrain for me.", + } + ], + "temperature": 2, + }, + ) + self.assertEqual(response4.status_code, 200, f"Failed with: {response4.text}") + content4 = response4.json()["choices"][0]["message"]["content"] + self.assertNotEqual(content3, content4) + + def test_return_hidden_states(self): + response = requests.post( + f"{self.base_url}/v1/chat/completions", + json={ + "model": self.model, + "messages": [{"role": "user", "content": "Hello"}], + "return_hidden_states": True, + }, + ) + self.assertEqual(response.status_code, 200, f"Failed with: {response.text}") + self.assertIn("hidden_states", response.json()["choices"][0]) + + response = requests.post( + f"{self.base_url}/v1/chat/completions", + json={ + "model": self.model, + "messages": [{"role": "user", "content": "Hello"}], + }, + ) + self.assertEqual(response.status_code, 200, f"Failed with: {response.text}") + self.assertNotIn("hidden_states", response.json()["choices"][0]) + + def test_top_k(self): + response1 = requests.post( + f"{self.base_url}/v1/chat/completions", + json={ + "model": self.model, + "messages": [ + { + "role": "user", + "content": "Please write a five-character quatrain for me.", + } + ], + "top_k": 20, + }, + ) + self.assertEqual(response1.status_code, 200, f"Failed with: {response1.text}") + content1 = response1.json()["choices"][0]["message"]["content"] + + response2 = requests.post( + f"{self.base_url}/v1/chat/completions", + json={ + "model": self.model, + "messages": [ + { + "role": "user", + "content": "Please write a five-character quatrain for me.", + } + ], + "top_k": 20, + }, + ) + self.assertEqual(response2.status_code, 200, f"Failed with: {response2.text}") + content2 = response2.json()["choices"][0]["message"]["content"] + self.assertNotEqual(content1, content2) + + def test_stop_token_ids(self): + response = requests.post( + f"{self.base_url}/v1/chat/completions", + json={ + "model": self.model, + "messages": [{"role": "user", "content": "Hello"}], + "stop_token_ids": [1, 13], + }, + ) + self.assertEqual(response.status_code, 200, f"Failed with: {response.text}") + self.assertEqual(response.json()["choices"][0]["matched_stop"], 13) + + def test_rid(self): + response = requests.post( + f"{self.base_url}/v1/chat/completions", + json={ + "model": self.model, + "messages": [{"role": "user", "content": "Hello"}], + "rid": "sssss", + }, + ) + self.assertEqual(response.status_code, 200, f"Failed with: {response.text}") + self.assertEqual(response.json()["id"], "sssss") + + +class TestEnableThinking(CustomTestCase): + """Testcase: The test is to verify whether the functions of each parameter of the v1/completions interface are normal. + + [Test Category] Interface + [Test Target] v1/completions + """ + + @classmethod + def setUpClass(cls): + # Skip initialization, directly reuse global server + cls.model = LLAMA_3_2_1B_INSTRUCT_WEIGHTS_PATH + cls.base_url = DEFAULT_URL_FOR_TEST + cls.additional_chat_kwargs = {} + logging.basicConfig(level=logging.INFO) # Initialize logging + + @classmethod + def tearDownClass(cls): + # Do not terminate server + pass + + def test_model_parameters_model(self): + response = requests.post( + f"{self.base_url}/v1/completions", + json={"model": self.model, "prompt": "who are you?"}, + ) + logging.info(f"response.json:{response.json()}") + self.assertEqual(response.status_code, 200, f"Failed with: {response.text}") + data = response.json() + self.assertEqual(data["model"], self.model) + + def test_model_parameters_prompt(self): + # str format + response = requests.post( + f"{self.base_url}/v1/completions", + json={"prompt": "who are you?"}, + ) + logging.info(f"response.json:{response.json()}") + self.assertEqual(response.status_code, 200, f"Failed with: {response.text}") + + # list[int] format + list_int = [1, 2, 3, 4] + response1 = requests.post( + f"{self.base_url}/v1/completions", + json={"prompt": list_int}, + ) + logging.info(f"response1.json:{response1.json()}") + self.assertEqual(response1.status_code, 200, f"Failed with: {response1.text}") + + # list[str] format + list_str = ["who is you", "hello world", "ABChello"] + response2 = requests.post( + f"{self.base_url}/v1/completions", + json={"prompt": list_str}, + ) + logging.info(f"response2.json:{response2.json()}") + self.assertEqual(response2.status_code, 200, f"Failed with: {response2.text}") + + # list[list[int]] format + list_list_int = [[14990], [1350, 445, 14990, 1879, 899], [14623, 525, 498, 30]] + response3 = requests.post( + f"{self.base_url}/v1/completions", + json={"prompt": list_list_int}, + ) + logging.info(f"response3.json:{response3.json()}") + self.assertEqual(response3.status_code, 200, f"Failed with: {response3.text}") + + def test_model_parameters_max_tokens(self): + response = requests.post( + f"{self.base_url}/v1/completions", + json={"prompt": "who are you?", "max_tokens": 1}, + ) + logging.info(f"response.json:{response.json()}") + self.assertEqual(response.status_code, 200, f"Failed with: {response.text}") + logging.info(f"finish_reason:{response.json()['choices'][0]['finish_reason']}") + self.assertEqual(response.json()["choices"][0]["finish_reason"], "length") + + def test_model_parameters_stream(self): + response = requests.post( + f"{self.base_url}/v1/completions", + json={"prompt": "who are you?", "stream": True}, + ) + logging.info(f"response.text:{response.text}") + self.assertEqual(response.status_code, 200, f"Failed with: {response.text}") + + has_text = False + logging.info("\n=== Stream With Reasoning ===") + for line in response.iter_lines(): + if line: + line = line.decode("utf-8") + if line.startswith("data:") and not line.startswith("data: [DONE]"): + data = json.loads(line[6:]) + if "choices" in data and len(data["choices"]) > 0: + if "text" in data["choices"][0]: + has_text = True + self.assertTrue(has_text, "Text content not included in stream response") + + def test_model_parameters_temperature(self): + response = requests.post( + f"{self.base_url}/v1/completions", + json={"prompt": "who are you?", "temperature": 0}, + ) + logging.info(f"response.json:{response.json()}") + self.assertEqual(response.status_code, 200, f"Failed with: {response.text}") + + response1 = requests.post( + f"{self.base_url}/v1/completions", + json={"prompt": "who are you?", "temperature": 0}, + ) + logging.info(f"response1.json:{response1.json()}") + self.assertEqual(response1.status_code, 200, f"Failed with: {response1.text}") + self.assertEqual( + response.json()["choices"][0]["text"], + response1.json()["choices"][0]["text"], + ) + + response2 = requests.post( + f"{self.base_url}/v1/completions", + json={"prompt": "who are you?", "temperature": 2}, + ) + logging.info(f"response2.json:{response2.json()}") + self.assertEqual(response2.status_code, 200, f"Failed with: {response2.text}") + + response3 = requests.post( + f"{self.base_url}/v1/completions", + json={"prompt": "who are you?", "temperature": 2}, + ) + logging.info(f"response3.json:{response3.json()}") + self.assertEqual(response3.status_code, 200, f"Failed with: {response3.text}") + self.assertNotEqual( + response2.json()["choices"][0]["text"], + response3.json()["choices"][0]["text"], + ) + + def test_model_parameters_hidden_states(self): + response = requests.post( + f"{self.base_url}/v1/completions", + json={"prompt": "who are you?", "return_hidden_states": True}, + ) + logging.info(f"response.json:{response.json()}") + self.assertEqual(response.status_code, 200, f"Failed with: {response.text}") + self.assertIn("hidden_states", response.json()["choices"][0]) + + def test_model_parameters_top_k(self): + response = requests.post( + f"{self.base_url}/v1/completions", + json={"prompt": "who are you?", "top_k": 20}, + ) + logging.info(f"response.json:{response.json()}") + logging.info(f"response.text:{response.text}") + self.assertEqual(response.status_code, 200, f"Failed with: {response.text}") + + response1 = requests.post( + f"{self.base_url}/v1/completions", + json={"prompt": "who are you?", "top_k": 20}, + ) + logging.info(f"response1.json:{response1.json()}") + logging.info(f"response1.text:{response1.text}") + self.assertEqual(response1.status_code, 200, f"Failed with: {response1.text}") + self.assertNotEqual( + response.json()["choices"][0]["text"], + response1.json()["choices"][0]["text"], + ) + + def test_model_parameters_stop_token_ids(self): + list_ids = [13] + response = requests.post( + f"{self.base_url}/v1/completions", + json={ + "prompt": "who are you?", + "stop_token_ids": list_ids, + "max_tokens": 1024, + }, + ) + logging.info(f"response.json:{response.json()}") + self.assertEqual(response.status_code, 200, f"Failed with: {response.text}") + self.assertEqual(response.json()["choices"][0]["matched_stop"], 13) + + def test_model_parameters_rid(self): + response = requests.post( + f"{self.base_url}/v1/completions", + json={"prompt": "who are you?", "rid": "10086"}, + ) + logging.info(f"response.json:{response.json()}") + self.assertEqual(response.status_code, 200, f"Failed with: {response.text}") + self.assertEqual(response.json()["id"], "10086") + + +class TestStartProfile(CustomTestCase): + """Testcase: Verify the correctness of /start_profile API with different parameter combinations (start_step/num_steps) on Ascend NPU backend. + + [Test Category] Interface + [Test Target] /start_profile + """ + + @classmethod + def setUpClass(cls): + # Skip initialization, reuse global server + configure profiler directory + envs.SGLANG_TORCH_PROFILER_DIR.set(OUTPUT_DIR) + cls.model = LLAMA_3_2_1B_INSTRUCT_WEIGHTS_PATH + cls.base_url = DEFAULT_URL_FOR_TEST + cls.additional_chat_kwargs = {} + + @classmethod + def tearDownClass(cls): + # Terminate server in last class + global GLOBAL_SERVER_PROCESS + if GLOBAL_SERVER_PROCESS: + kill_process_tree(GLOBAL_SERVER_PROCESS.pid) + GLOBAL_SERVER_PROCESS = None + + def setUp(self): + self._clear_profile_dir() + + def test_start_profile_1(self): + self._start_profile(start_step="15", num_steps=5) + self._post_request() + self._check_non_empty_profile_dir() + + def test_start_profile_2(self): + self._clear_profile_dir() + self._check_empty_profile_dir() + self._start_profile() + self._post_request() + requests.post(f"{self.base_url}/stop_profile") + self._check_non_empty_profile_dir() + + def test_start_profile_3(self): + self._start_profile(num_steps=5) + self._post_request() + self._check_non_empty_profile_dir() + + def _start_profile(self, **kwargs): + response = requests.post( + f"{self.base_url}/start_profile", + json=kwargs if kwargs else None, + ) + self.assertEqual(response.status_code, 200) + return response + + def _post_request(self): + response = requests.post( + f"{self.base_url}/generate", + json={ + "text": "The capital of France is", + "sampling_params": { + "temperature": 0, + "max_new_tokens": 32, + }, + }, + ) + self.assertEqual(response.status_code, 200) + + def _clear_profile_dir(self): + if os.path.isdir(OUTPUT_DIR): + shutil.rmtree(OUTPUT_DIR) + + def _check_non_empty_profile_dir(self): + self.assertTrue(os.path.isdir(OUTPUT_DIR), "Profiler directory does not exist") + self.assertNotEqual( + len(os.listdir(OUTPUT_DIR)), 0, "Profiler directory is empty" + ) + + def _check_empty_profile_dir(self): + if os.path.isdir(OUTPUT_DIR): + self.assertEqual( + len(os.listdir(OUTPUT_DIR)), 0, "Profiler directory is not empty" + ) + + +if __name__ == "__main__": + unittest.main() diff --git a/asian_ai/performance/SGLang/test/registered/ascend/interface/test_npu_api_abort_request.py b/asian_ai/performance/SGLang/test/registered/ascend/interface/test_npu_api_abort_request.py new file mode 100644 index 0000000000000000000000000000000000000000..22093cbd947e332e91440abf07d350e534ba89b3 --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/ascend/interface/test_npu_api_abort_request.py @@ -0,0 +1,78 @@ +import threading +import time +import unittest + +import requests + +from sglang.srt.utils import kill_process_tree +from sglang.test.ascend.test_ascend_utils import LLAMA_3_2_1B_INSTRUCT_WEIGHTS_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, +) + +responses = [] + + +def send_requests(url, **kwargs): + response = requests.post(DEFAULT_URL_FOR_TEST + url, json=kwargs) + responses.append(response) + + +register_npu_ci(est_time=400, suite="nightly-1-npu-a3", nightly=True) + + +class TestNpuApi(CustomTestCase): + """Testcase: Verify the functionality of /abort_request API to terminate a running /generate request on Ascend backend. + + [Test Category] Interface + [Test Target] /abort_request + """ + + @classmethod + def setUpClass(cls): + cls.model = LLAMA_3_2_1B_INSTRUCT_WEIGHTS_PATH + other_args = [ + "--attention-backend", + "ascend", + ] + cls.process = popen_launch_server( + cls.model, + DEFAULT_URL_FOR_TEST, + timeout=DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH, + other_args=other_args, + ) + + @classmethod + def tearDownClass(cls): + kill_process_tree(cls.process.pid) + + def test_api_abort_request(self): + # Create thread 1: Send a long-running /generate request with rid=10086 + thread1 = threading.Thread( + target=send_requests, + args=("/generate",), + kwargs={ + "rid": "10086", + "text": "who are you?", + "sampling_params": {"temperature": 0.0, "max_new_tokens": 1024}, + }, + ) + # Create thread 2: Send an /abort_request to terminate the request with rid=10086 + thread2 = threading.Thread( + target=send_requests, args=("/abort_request",), kwargs={"rid": "10086"} + ) + thread1.start() + time.sleep(0.5) + thread2.start() + thread1.join() + thread2.join() + print(responses[1].text) + + +if __name__ == "__main__": + + unittest.main() diff --git a/asian_ai/performance/SGLang/test/registered/ascend/interface/test_npu_api_encode.py b/asian_ai/performance/SGLang/test/registered/ascend/interface/test_npu_api_encode.py new file mode 100644 index 0000000000000000000000000000000000000000..da1128fa5fe2c740e7bc4c1a8e3afca2ea174ff9 --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/ascend/interface/test_npu_api_encode.py @@ -0,0 +1,134 @@ +import logging +import unittest + +import requests + +from sglang.srt.utils import kill_process_tree +from sglang.test.ascend.test_ascend_utils import QWEN3_VL_4B_INSTRUCT_WEIGHTS_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, +) + +logging.basicConfig( + level=logging.INFO, + format="%(asctime)s - %(name)s - %(levelname)s - %(message)s", + handlers=[logging.StreamHandler()], +) +logger = logging.getLogger(__name__) + +register_npu_ci(est_time=400, suite="nightly-1-npu-a3", nightly=True) + + +class TestNpuApi(CustomTestCase): + """Testcase: Verify the availability and correctness of the /encode API on Ascend backend with GME_QWEN2_VL_2B_INSTRUCT model. + + [Test Category] Interface + [Test Target] /encode + """ + + @classmethod + def setUpClass(cls): + cls.model = QWEN3_VL_4B_INSTRUCT_WEIGHTS_PATH + other_args = [ + "--attention-backend", + "ascend", + "--disable-cuda-graph", + "--tp-size", + 2, + "--is-embedding", + ] + cls.process = popen_launch_server( + cls.model, + DEFAULT_URL_FOR_TEST, + timeout=DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH, + other_args=other_args, + ) + + @classmethod + def tearDownClass(cls): + kill_process_tree(cls.process.pid) + + def test_api_encode_01(self): + # Test Scenario 1: Call /encode API with plain text parameter + response = requests.post( + f"{DEFAULT_URL_FOR_TEST}/encode", + json={ + "rid": "2", + "text": "what is the capital of France", + "sampling_params": { + "temperature": 0, + "max_new_tokens": 200, + "top_p": 1, + }, + }, + ) + logger.info("Test 01 response keys: %s", response.json().keys()) + self.assertEqual(response.status_code, 200) + self.assertEqual(response.json()["meta_info"]["id"], "2") + + def test_api_encode_02(self): + # Test Scenario 2: Call /encode API with input_ids parameter + response = requests.post( + f"{DEFAULT_URL_FOR_TEST}/encode", + json={ + "rid": "3", + "input_ids": [101, 7592, 2088, 102], + "sampling_params": {"temperature": 0, "max_new_tokens": 200}, + }, + ) + self.assertEqual(response.status_code, 200) + self.assertEqual(response.json()["meta_info"]["id"], "3") + + def test_api_encode_03(self): + # Test Scenario 3: Call /encode API with text and image parameters (multimodal capability verification) + response = requests.post( + f"{DEFAULT_URL_FOR_TEST}/encode", + json={ + "rid": "4", + "text": "show me the words", + "image_data": "https://miaobi-lite.bj.bcebos.com/miaobi/5mao/b%27b2Ny6K%2BG5Yir5Luj56CBXzE3MzQ2MzcyNjAuMzgxNDk5NQ%3D%3D%27/0.png", + "sampling_params": {"temperature": 0, "max_new_tokens": 200}, + }, + ) + logger.info("Test 03 response keys: %s", response.json().keys()) + self.assertEqual(response.status_code, 200) + self.assertEqual(response.json()["meta_info"]["id"], "4") + + def test_api_encode_04(self): + # Test Scenario 4: Call /encode API with list of rids (multiple requests) - text input + request_rids = ["5", "6", "7"] + response = requests.post( + f"{DEFAULT_URL_FOR_TEST}/encode", + json={ + "rid": request_rids, + "text": [ + "what is the capital of UK", + "what is the capital of Germany", + "what is the capital of Japan", + ], + "sampling_params": { + "temperature": 0, + "max_new_tokens": 200, + "top_p": 1, + }, + }, + ) + response_json = response.json() + logger.info( + "Test 04 response type: %s, first item meta_info: %s", + type(response_json), + response_json[0].get("meta_info", {}), + ) + + self.assertEqual(response.status_code, 200) + self.assertEqual(len(response_json), len(request_rids)) + for idx, result in enumerate(response_json): + self.assertEqual(result["meta_info"]["id"], request_rids[idx]) + + +if __name__ == "__main__": + unittest.main() diff --git a/asian_ai/performance/SGLang/test/registered/ascend/interface/test_npu_enable_thinking.py b/asian_ai/performance/SGLang/test/registered/ascend/interface/test_npu_enable_thinking.py new file mode 100644 index 0000000000000000000000000000000000000000..147e3ffec58062e8fa8ff1885eed39f38e70b80c --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/ascend/interface/test_npu_enable_thinking.py @@ -0,0 +1,195 @@ +import json +import unittest + +import requests + +from sglang.srt.utils import kill_process_tree +from sglang.test.ascend.test_ascend_utils import QWEN3_30B_A3B_WEIGHTS_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, +) + + +class TestEnableThinking(CustomTestCase): + """Testcase: Testing with the 'enable_thinking' feature enabled/disabled, + both streaming and non-streaming input requests successful + + [Test Category] Interface + [Test Target] /v1/chat/completions + """ + + @classmethod + def setUpClass(cls): + cls.model = QWEN3_30B_A3B_WEIGHTS_PATH + cls.base_url = DEFAULT_URL_FOR_TEST + cls.other_args = [ + "--attention-backend", + "ascend", + "--disable-cuda-graph", + "--mem-fraction-static", + 0.95, + "--tp", + 2, + "--reasoning-parser", + "qwen3", + ] + cls.process = popen_launch_server( + cls.model, + cls.base_url, + timeout=DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH, + other_args=cls.other_args, + ) + cls.additional_chat_kwargs = {} + + @classmethod + def tearDownClass(cls): + kill_process_tree(cls.process.pid) + + def test_chat_completion_with_reasoning(self): + # Test non-streaming with "enable_thinking": True, reasoning_content should not be empty + client = requests.post( + f"{self.base_url}/v1/chat/completions", + json={ + "model": self.model, + "messages": [{"role": "user", "content": "Hello"}], + "temperature": 0, + "separate_reasoning": True, + "chat_template_kwargs": {"enable_thinking": True}, + **self.additional_chat_kwargs, + }, + ) + + self.assertEqual(client.status_code, 200, f"Failed with: {client.text}") + data = client.json() + + self.assertIn("choices", data) + self.assertTrue(len(data["choices"]) > 0) + self.assertIn("message", data["choices"][0]) + self.assertIn("reasoning_content", data["choices"][0]["message"]) + self.assertIsNotNone(data["choices"][0]["message"]["reasoning_content"]) + + def test_chat_completion_without_reasoning(self): + # Test non-streaming with "enable_thinking": False, reasoning_content should be empty + client = requests.post( + f"{self.base_url}/v1/chat/completions", + json={ + "model": self.model, + "messages": [{"role": "user", "content": "Hello"}], + "temperature": 0, + "separate_reasoning": True, + "chat_template_kwargs": {"enable_thinking": False}, + **self.additional_chat_kwargs, + }, + ) + + self.assertEqual(client.status_code, 200, f"Failed with: {client.text}") + data = client.json() + + self.assertIn("choices", data) + self.assertTrue(len(data["choices"]) > 0) + self.assertIn("message", data["choices"][0]) + + if "reasoning_content" in data["choices"][0]["message"]: + self.assertIsNone(data["choices"][0]["message"]["reasoning_content"]) + + def test_stream_chat_completion_with_reasoning(self): + # Test streaming with "enable_thinking": True, reasoning_content should not be empty + response = requests.post( + f"{self.base_url}/v1/chat/completions", + json={ + "model": self.model, + "messages": [{"role": "user", "content": "Hello"}], + "temperature": 0, + "separate_reasoning": True, + "stream": True, + "chat_template_kwargs": {"enable_thinking": True}, + **self.additional_chat_kwargs, + }, + stream=True, + ) + + self.assertEqual(response.status_code, 200, f"Failed with: {response.text}") + + has_reasoning = False + has_content = False + + print("\n=== Stream With Reasoning ===") + for line in response.iter_lines(): + if line: + line = line.decode("utf-8") + if line.startswith("data:") and not line.startswith("data: [DONE]"): + data = json.loads(line[6:]) + if "choices" in data and len(data["choices"]) > 0: + delta = data["choices"][0].get("delta", {}) + + if "reasoning_content" in delta and delta["reasoning_content"]: + has_reasoning = True + + if "content" in delta and delta["content"]: + has_content = True + + self.assertTrue( + has_reasoning, + "The reasoning content is not included in the stream response", + ) + self.assertTrue( + has_content, "The stream response does not contain normal content" + ) + + def test_stream_chat_completion_without_reasoning(self): + # Test streaming with "enable_thinking": False, reasoning_content should be empty + response = requests.post( + f"{self.base_url}/v1/chat/completions", + json={ + "model": self.model, + "messages": [{"role": "user", "content": "Hello"}], + "temperature": 0, + "separate_reasoning": True, + "stream": True, + "chat_template_kwargs": {"enable_thinking": False}, + **self.additional_chat_kwargs, + }, + stream=True, + ) + + self.assertEqual(response.status_code, 200, f"Failed with: {response.text}") + + has_reasoning = False + has_content = False + + print("\n=== Stream Without Reasoning ===") + for line in response.iter_lines(): + if line: + line = line.decode("utf-8") + if line.startswith("data:") and not line.startswith("data: [DONE]"): + data = json.loads(line[6:]) + if "choices" in data and len(data["choices"]) > 0: + delta = data["choices"][0].get("delta", {}) + + if "reasoning_content" in delta and delta["reasoning_content"]: + has_reasoning = True + + if "content" in delta and delta["content"]: + has_content = True + + self.assertFalse( + has_reasoning, + "The reasoning content should not be included in the stream response", + ) + self.assertTrue( + has_content, "The stream response does not contain normal content" + ) + + +if __name__ == "__main__": + unittest.main() diff --git a/asian_ai/performance/SGLang/test/registered/ascend/interface/test_npu_matched_stop.py b/asian_ai/performance/SGLang/test/registered/ascend/interface/test_npu_matched_stop.py new file mode 100644 index 0000000000000000000000000000000000000000..beb99367770dd288914865c428da965ca2c8b649 --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/ascend/interface/test_npu_matched_stop.py @@ -0,0 +1,163 @@ +import json +import unittest + +import requests + +from sglang.srt.utils import kill_process_tree +from sglang.test.ascend.test_ascend_utils import LLAMA_3_1_8B_INSTRUCT_WEIGHTS_PATH +from sglang.test.ci.ci_register import register_npu_ci +from sglang.test.test_utils import ( + DEFAULT_URL_FOR_TEST, + CustomTestCase, + popen_launch_server, +) + +MANY_NEW_TOKENS_PROMPT = """ +Please write an extremely detailed and vivid fantasy story, set in a world full of intricate magic systems, political intrigue, and complex characters. +Ensure that you thoroughly describe every scene, character's motivations, and the environment. Include long, engaging dialogues and elaborate on the inner thoughts of the characters. +Each section should be as comprehensive as possible to create a rich and immersive experience for the reader. +The story should span multiple events, challenges, and character developments over time. Aim to make the story at least 3,000 words long. +""" + +register_npu_ci(est_time=400, suite="nightly-1-npu-a3", nightly=True) + + +class TestMatchedStop(CustomTestCase): + """Testcase: Test configuring 'matched_stop' to different values(string, EOS token, length) correctly identifies + it as a stop signal. + + [Test Category] Interface + [Test Target] /v1/chat/completions; /v1/completions + """ + + @classmethod + def setUpClass(cls): + cls.model = LLAMA_3_1_8B_INSTRUCT_WEIGHTS_PATH + cls.base_url = DEFAULT_URL_FOR_TEST + cls.other_args = [ + "--max-running-requests", + 10, + "--attention-backend", + "ascend", + "--disable-cuda-graph", + "--mem-fraction-static", + 0.8, + ] + cls.process = popen_launch_server( + cls.model, cls.base_url, timeout=300, other_args=cls.other_args + ) + + @classmethod + def tearDownClass(cls): + kill_process_tree(cls.process.pid) + + def run_completions_generation( + self, + prompt=MANY_NEW_TOKENS_PROMPT, + max_tokens=1, + stop=None, + finish_reason=None, + matched_stop=None, + ): + # Configure matched_stop to None, and use the '/v1/completions' interface + # verify that the actual termination reason matches the configured value. + payload = { + "prompt": prompt, + "model": self.model, + "temperature": 0, + "top_p": 1, + "max_tokens": max_tokens, + } + + if stop is not None: + payload["stop"] = stop + + response_completions = requests.post( + self.base_url + "/v1/completions", + json=payload, + ) + print(json.dumps(response_completions.json())) + print("=" * 100) + + assert ( + response_completions.json()["choices"][0]["finish_reason"] == finish_reason + ) + assert response_completions.json()["choices"][0]["matched_stop"] == matched_stop + + def run_chat_completions_generation( + self, + prompt=MANY_NEW_TOKENS_PROMPT, + max_tokens=1, + stop=None, + finish_reason=None, + matched_stop=None, + ): + # Configure matched_stop to None, and use the '/v1/chat/completions' interface + # verify that the actual termination reason matches the configured value. + chat_payload = { + "model": self.model, + "messages": [ + {"role": "system", "content": "You are a helpful AI assistant"}, + {"role": "user", "content": prompt}, + ], + "temperature": 0, + "top_p": 1, + "max_tokens": max_tokens, + } + + if stop is not None: + chat_payload["stop"] = stop + + response_chat = requests.post( + self.base_url + "/v1/chat/completions", + json=chat_payload, + ) + print(json.dumps(response_chat.json())) + print("=" * 100) + + assert response_chat.json()["choices"][0]["finish_reason"] == finish_reason + assert response_chat.json()["choices"][0]["matched_stop"] == matched_stop + + def test_finish_stop_str(self): + # Setting finish_reason="stop",'matched_stop="\n"' allows for correct termination + self.run_completions_generation( + max_tokens=1000, stop="\n", finish_reason="stop", matched_stop="\n" + ) + self.run_chat_completions_generation( + max_tokens=1000, stop="\n", finish_reason="stop", matched_stop="\n" + ) + + def test_finish_stop_eos(self): + # Setting matched_stop is a specific EOS end flagallows for correct identification and termination of signal + llama_format_prompt = """ + <|begin_of_text|><|start_header_id|>system<|end_header_id|> + You are a helpful assistant.<|eot_id|><|start_header_id|>user<|end_header_id|> + + What is 2 + 2?<|eot_id|><|start_header_id|>assistant<|end_header_id|> + """ + eos_token_id = 128009 + self.run_completions_generation( + prompt=llama_format_prompt, + max_tokens=1000, + finish_reason="stop", + matched_stop=eos_token_id, + ) + self.run_chat_completions_generation( + prompt="What is 2 + 2?", + max_tokens=1000, + finish_reason="stop", + matched_stop=eos_token_id, + ) + + def test_finish_length(self): + # Setting finish_reason="length",'matched_stop="\n"' allows for correct termination + self.run_completions_generation( + max_tokens=5, finish_reason="length", matched_stop=None + ) + self.run_chat_completions_generation( + max_tokens=5, finish_reason="length", matched_stop=None + ) + + +if __name__ == "__main__": + unittest.main() diff --git a/asian_ai/performance/SGLang/test/registered/ascend/interface/test_npu_openai_function_calling.py b/asian_ai/performance/SGLang/test/registered/ascend/interface/test_npu_openai_function_calling.py new file mode 100644 index 0000000000000000000000000000000000000000..026f0f9d7ddb84ff42d9ccaca1edbd68b764791f --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/ascend/interface/test_npu_openai_function_calling.py @@ -0,0 +1,940 @@ +import json +import unittest + +import openai + +from sglang.srt.utils import kill_process_tree +from sglang.srt.utils.hf_transformers_utils import get_tokenizer +from sglang.test.ascend.test_ascend_utils import LLAMA_3_2_1B_INSTRUCT_WEIGHTS_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-1-npu-a3", + nightly=True, +) + + +class TestOpenAIServerFunctionCalling(CustomTestCase): + """Testcase:Verify the correctness of full-scenario OpenAI-style function calling with llama3 parser for Llama-3.2-1B-Instruct model. + Cover: Single/multi-turn calls, streaming/non-streaming returns, multi-parameter verification of tool_choice, and JSON parsing validity of function parameters. + + [Test Category] Interface + [Test Target] /v1/chat/completions + """ + + # NOTE: this system_message is for Llama3.2 system prompt. Without this, + # sometimes Llama3.2 gives a different tool call format such as: + # '<|python_tag|>{"type": "function", "function": "add", "parameters": {"a": "3", "b": "5"}}' + SYSTEM_MESSAGE = ( + "You are a helpful assistant with tool calling capabilities. " + "Only reply with a tool call if the function exists in the library provided by the user. " + "If it doesn't exist, just reply directly in natural language. " + "When you receive a tool call response, use the output to format an answer to the original user question. " + "You have access to the following functions. " + "To call a function, please respond with JSON for a function call. " + 'Respond in the format {"name": function name, "parameters": dictionary of argument name and its value}. ' + "Do not use variables.\n\n" + ) + + @classmethod + def setUpClass(cls): + # Replace with the model name needed for testing + cls.model = LLAMA_3_2_1B_INSTRUCT_WEIGHTS_PATH + cls.base_url = DEFAULT_URL_FOR_TEST + cls.api_key = "sk-123456" + + # Start the local OpenAI Server. If necessary, you can add other parameters such as --enable-tools. + cls.process = popen_launch_server( + cls.model, + cls.base_url, + timeout=DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH, + api_key=cls.api_key, + other_args=[ + # If your server needs extra parameters to test function calling, please add them here. + "--attention-backend", + "ascend", + "--disable-cuda-graph", + "--tool-call-parser", + "llama3", + ], + ) + cls.base_url += "/v1" + cls.tokenizer = get_tokenizer(cls.model) + + @classmethod + def tearDownClass(cls): + kill_process_tree(cls.process.pid) + + def test_function_calling_format(self): + """ + Test: Whether the function call format returned by the AI is correct. + When returning a tool call, message.content should be None, and tool_calls should be a list. + """ + client = openai.Client(api_key=self.api_key, base_url=self.base_url) + + tools = [ + { + "type": "function", + "function": { + "name": "add", + "description": "Compute the sum of two numbers", + "parameters": { + "type": "object", + "properties": { + "a": { + "type": "integer", + "description": "A number", + }, + "b": { + "type": "integer", + "description": "A number", + }, + }, + "required": ["a", "b"], + }, + }, + } + ] + + messages = [ + {"role": "system", "content": self.SYSTEM_MESSAGE}, + {"role": "user", "content": "Compute (3+5)"}, + ] + response = client.chat.completions.create( + model=self.model, + max_tokens=2048, + messages=messages, + temperature=0.8, + top_p=0.8, + stream=False, + tools=tools, + ) + + tool_calls = response.choices[0].message.tool_calls + + assert ( + isinstance(tool_calls, list) and len(tool_calls) > 0 + ), "tool_calls should be a non-empty list" + + function_name = tool_calls[0].function.name + assert function_name == "add", "Function name should be 'add'" + + # This unit test is too difficult for default model. Mark it as optional unit tests so it won't trigger unless specified. + def _test_function_calling_multiturn(self): + """ + Test: Whether the function call format returned by the AI is correct. + When returning a tool call, message.content should be None, and tool_calls should be a list. + """ + client = openai.Client(api_key=self.api_key, base_url=self.base_url) + + tools = [ + { + "type": "function", + "function": { + "name": "add", + "description": "Compute the sum of two numbers", + "parameters": { + "type": "object", + "properties": { + "a": { + "type": "integer", + "description": "A number", + }, + "b": { + "type": "integer", + "description": "A number", + }, + }, + "required": ["a", "b"], + }, + }, + } + ] + + messages = [{"role": "user", "content": "Compute (3+5)"}] + + response = client.chat.completions.create( + model=self.model, + max_tokens=2048, + messages=messages, + temperature=0.8, + top_p=0.8, + stream=False, + tools=tools, + ) + + tool_call = response.choices[0].message.tool_calls[0] + function_name = tool_call.function.name + assert function_name == "add", "Function name should be 'add'" + function_arguments = json.loads(tool_call.function.arguments) + assert function_arguments in [ + {"a": 3, "b": 5}, + {"a": "3", "b": "5"}, + ], f"Unexpected function arguments: {function_arguments}" + + messages.append(response.choices[0].message) + messages.append( + { + "role": "tool", + "tool_call_id": tool_call.id, + "content": "8", + "name": function_name, + } + ) + + final_response = client.chat.completions.create( + model=self.model, + max_tokens=2048, + messages=messages, + temperature=0.8, + top_p=0.8, + stream=False, + tools=tools, + ) + + assert ( + "8" in final_response.choices[0].message.content + ), "tool_call response should have the sum 8 in the content" + + def test_function_calling_streaming_simple(self): + """ + Test: Whether the function name can be correctly recognized in streaming mode. + - Expect a function call to be found, and the function name to be correct. + - Verify that streaming mode returns at least multiple chunks. + """ + client = openai.Client(api_key=self.api_key, base_url=self.base_url) + + tools = [ + { + "type": "function", + "function": { + "name": "get_current_weather", + "description": "Get the current weather in a given location", + "parameters": { + "type": "object", + "properties": { + "city": { + "type": "string", + "description": "The city to find the weather for", + }, + "unit": { + "type": "string", + "description": "Weather unit (celsius or fahrenheit)", + "enum": ["celsius", "fahrenheit"], + }, + }, + "required": ["city", "unit"], + }, + }, + } + ] + + messages = [ + {"role": "system", "content": self.SYSTEM_MESSAGE}, + { + "role": "user", + "content": "What is the temperature in Paris in celsius??", + }, + ] + + response_stream = client.chat.completions.create( + model=self.model, + max_tokens=2048, + messages=messages, + temperature=0.8, + top_p=0.8, + stream=True, + tools=tools, + ) + + chunks = list(response_stream) + self.assertTrue(len(chunks) > 0, "Streaming should return at least one chunk") + + found_function_name = False + for chunk in chunks: + choice = chunk.choices[0] + # Check whether the current chunk contains tool_calls + if choice.delta.tool_calls: + tool_call = choice.delta.tool_calls[0] + if tool_call.function.name: + self.assertEqual( + tool_call.function.name, + "get_current_weather", + "Function name should be 'get_current_weather'", + ) + found_function_name = True + break + + self.assertTrue( + found_function_name, + "Target function name 'get_current_weather' was not found in the streaming chunks", + ) + + finish_reason = chunks[-1].choices[0].finish_reason + self.assertEqual( + finish_reason, + "tool_calls", + "Final response of function calling should have finish_reason 'tool_calls'", + ) + + def test_function_calling_streaming_args_parsing(self): + """ + Test: Whether the function call arguments returned in streaming mode can be correctly concatenated into valid JSON. + - The user request requires multiple parameters. + - AI may return the arguments in chunks that need to be concatenated. + """ + client = openai.Client(api_key=self.api_key, base_url=self.base_url) + + tools = [ + { + "type": "function", + "function": { + "name": "add", + "description": "Compute the sum of two integers", + "parameters": { + "type": "object", + "properties": { + "a": { + "type": "integer", + "description": "First integer", + }, + "b": { + "type": "integer", + "description": "Second integer", + }, + }, + "required": ["a", "b"], + }, + "strict": True, # Llama-3.2-1B is flaky in tool call. It won't always respond with parameters unless we set strict. + }, + } + ] + + messages = [ + {"role": "system", "content": self.SYSTEM_MESSAGE}, + {"role": "user", "content": "Please sum 5 and 7, just call the function."}, + ] + + response_stream = client.chat.completions.create( + model=self.model, + max_tokens=2048, + messages=messages, + temperature=0.9, + top_p=0.9, + stream=True, + tools=tools, + ) + + argument_fragments = [] + chunks = list(response_stream) + function_name = None + for chunk in chunks: + choice = chunk.choices[0] + if choice.delta.tool_calls: + tool_call = choice.delta.tool_calls[0] + # Record the function name on first occurrence + function_name = tool_call.function.name or function_name + # In case of multiple chunks, JSON fragments may need to be concatenated + if tool_call.function.arguments is not None: + argument_fragments.append(tool_call.function.arguments) + + self.assertEqual(function_name, "add", "Function name should be 'add'") + joined_args = "".join(argument_fragments) + self.assertTrue( + len(joined_args) > 0, + "No parameter fragments were returned in the function call", + ) + + finish_reason = chunks[-1].choices[0].finish_reason + self.assertEqual( + finish_reason, + "tool_calls", + "Final response of function calling should have finish_reason 'tool_calls'", + ) + + # Check whether the concatenated JSON is valid + try: + args_obj = json.loads(joined_args) + except json.JSONDecodeError: + self.fail( + "The concatenated tool call arguments are not valid JSON, parsing failed" + ) + + self.assertIn("a", args_obj, "Missing parameter 'a'") + self.assertIn("b", args_obj, "Missing parameter 'b'") + self.assertEqual(str(args_obj["a"]), "5", "Parameter a should be 5") + self.assertEqual(str(args_obj["b"]), "7", "Parameter b should be 7") + + def test_function_call_strict(self): + """ + Test: Whether the strict mode of function calling works as expected. + - When strict mode is enabled, the AI should not return a function call if the function name is not recognized. + """ + client = openai.Client(api_key=self.api_key, base_url=self.base_url) + + tools = [ + { + "type": "function", + "function": { + "name": "sub", + "description": "Compute the difference of two integers", + "parameters": { + "type": "object", + "properties": { + "int_a": { + "type": "integer", + "description": "First integer", + }, + "int_b": { + "type": "integer", + "description": "Second integer", + }, + }, + "required": ["int_a", "int_b"], + }, + "strict": True, + }, + } + ] + + messages = [ + {"role": "user", "content": "Please compute 5 - 7, using your tool."} + ] + response = client.chat.completions.create( + model=self.model, + max_tokens=2048, + messages=messages, + temperature=0.8, + top_p=0.8, + stream=False, + tools=tools, + ) + + tool_calls = response.choices[0].message.tool_calls + function_name = tool_calls[0].function.name + arguments = tool_calls[0].function.arguments + args_obj = json.loads(arguments) + + self.assertEqual(function_name, "sub", "Function name should be 'sub'") + self.assertEqual(str(args_obj["int_a"]), "5", "Parameter int_a should be 5") + self.assertEqual(str(args_obj["int_b"]), "7", "Parameter int_b should be 7") + + def test_function_call_required(self): + """ + Test: Whether tool_choice: "required" works as expected. + - When tool_choice == "required", the model MUST return one or more tool_calls. + - The model may choose ANY of the provided tools; we only verify that + a tool call exists and the selected name is among the candidates. + """ + client = openai.Client(api_key=self.api_key, base_url=self.base_url) + + tools = [ + { + "type": "function", + "function": { + "name": "sub", + "description": "Compute the difference of two integers", + "parameters": { + "type": "object", + "properties": { + "int_a": { + "type": "integer", + "description": "First integer", + }, + "int_b": { + "type": "integer", + "description": "Second integer", + }, + }, + "required": ["int_a", "int_b"], + }, + "strict": True, + }, + }, + { + "type": "function", + "function": { + "name": "get_weather", + "description": "use this to get latest weather information for a city given its name", + "parameters": { + "type": "object", + "properties": { + "city": { + "type": "string", + "description": "name of the city to get weather for", + } + }, + "required": ["city"], + }, + "strict": True, + }, + }, + ] + + valid_tool_names = {t["function"]["name"] for t in tools} + + messages = [{"role": "user", "content": "Tell me about Paris"}] + response = client.chat.completions.create( + model=self.model, + max_tokens=2048, + messages=messages, + temperature=0, + stream=False, + tools=tools, + tool_choice="required", + ) + + tool_calls = response.choices[0].message.tool_calls + self.assertIsNotNone( + tool_calls, "tool_choice='required' must produce tool_calls" + ) + self.assertGreater(len(tool_calls), 0, "tool_calls list should be non-empty") + + function_name = tool_calls[0].function.name + self.assertIn( + function_name, + valid_tool_names, + f"Function name '{function_name}' is not among the provided tools: {valid_tool_names}", + ) + + # Verify the arguments are parseable JSON + arguments = tool_calls[0].function.arguments + args_obj = json.loads(arguments) + self.assertIsInstance( + args_obj, dict, "Function arguments should be a JSON object" + ) + + def test_function_call_specific(self): + """ + Test: Whether tool_choice: ToolChoice works as expected + - When tool_choice is a specific ToolChoice, the model should return one or more tool_calls. + """ + client = openai.Client(api_key=self.api_key, base_url=self.base_url) + + tools = [ + { + "type": "function", + "function": { + "name": "sub", + "description": "Compute the difference of two integers", + "parameters": { + "type": "object", + "properties": { + "int_a": { + "type": "integer", + "description": "First integer", + }, + "int_b": { + "type": "integer", + "description": "Second integer", + }, + }, + "required": ["int_a", "int_b"], + }, + "strict": True, + }, + }, + { + "type": "function", + "function": { + "name": "get_weather", + "description": "use this to get latest weather information for a city given its name", + "parameters": { + "type": "object", + "properties": { + "city": { + "type": "string", + "description": "name of the city to get weather for", + } + }, + "required": ["city"], + }, + "strict": True, + }, + }, + ] + + messages = [{"role": "user", "content": "What is the capital of France?"}] + response = client.chat.completions.create( + model=self.model, + max_tokens=2048, + messages=messages, + temperature=0.8, + top_p=0.8, + stream=False, + tools=tools, + tool_choice={"type": "function", "function": {"name": "get_weather"}}, + ) + + tool_calls = response.choices[0].message.tool_calls + self.assertIsNotNone(tool_calls, "No tool_calls in the response") + function_name = tool_calls[0].function.name + arguments = tool_calls[0].function.arguments + args_obj = json.loads(arguments) + + self.assertEqual( + function_name, "get_weather", "Function name should be 'get_weather'" + ) + self.assertIn("city", args_obj, "Function arguments should have 'city'") + + def test_streaming_multiple_choices_finish_reason(self): + """ + Test: Verify that each choice gets its own finish_reason chunk in streaming mode with n > 1. + This tests the fix for the bug where only the last index got a finish_reason chunk. + """ + client = openai.Client(api_key=self.api_key, base_url=self.base_url) + + tools = [ + { + "type": "function", + "function": { + "name": "get_current_weather", + "description": "Get the current weather in a given location", + "parameters": { + "type": "object", + "properties": { + "location": { + "type": "string", + "description": "The city and state, e.g. San Francisco, CA", + }, + "unit": { + "type": "string", + "enum": ["celsius", "fahrenheit"], + }, + }, + "required": ["location"], + }, + }, + } + ] + + messages = [ + {"role": "user", "content": "What is the weather like in Los Angeles?"} + ] + + # Request with n=2 to get multiple choices + response_stream = client.chat.completions.create( + model=self.model, + messages=messages, + max_tokens=2048, + temperature=0.8, + stream=True, + tools=tools, + tool_choice="required", # Force tool calls + n=2, # Multiple choices + ) + + chunks = list(response_stream) + + # Track finish_reason chunks for each index + finish_reason_chunks = {} + for chunk in chunks: + if chunk.choices: + for choice in chunk.choices: + if choice.finish_reason is not None: + index = choice.index + if index not in finish_reason_chunks: + finish_reason_chunks[index] = [] + finish_reason_chunks[index].append(choice.finish_reason) + + # Verify we got finish_reason chunks for both indices + self.assertEqual( + len(finish_reason_chunks), + 2, + f"Expected finish_reason chunks for 2 indices, got {len(finish_reason_chunks)}", + ) + + # Verify both index 0 and 1 have finish_reason + self.assertIn( + 0, finish_reason_chunks, "Missing finish_reason chunk for index 0" + ) + self.assertIn( + 1, finish_reason_chunks, "Missing finish_reason chunk for index 1" + ) + + # Verify the finish_reason is "tool_calls" since we forced tool calls + for index, reasons in finish_reason_chunks.items(): + self.assertEqual( + reasons[-1], # Last finish_reason for this index + "tool_calls", + f"Expected finish_reason 'tool_calls' for index {index}, got {reasons[-1]}", + ) + + def test_function_calling_streaming_no_tool_call(self): + """ + Test: Whether the finish_reason is stop in streaming mode when no tool call is given. + - Expect no function call to be found. + - Verify that finish_reason is stop + """ + client = openai.Client(api_key=self.api_key, base_url=self.base_url) + + tools = [ + { + "type": "function", + "function": { + "name": "get_current_weather", + "description": "Get the current weather in a given location", + "parameters": { + "type": "object", + "properties": { + "city": { + "type": "string", + "description": "The city to find the weather for", + }, + "unit": { + "type": "string", + "description": "Weather unit (celsius or fahrenheit)", + "enum": ["celsius", "fahrenheit"], + }, + }, + "required": ["city", "unit"], + }, + }, + } + ] + + messages = [{"role": "user", "content": "Who are you?"}] + + response_stream = client.chat.completions.create( + model=self.model, + max_tokens=2048, + messages=messages, + temperature=0.8, + top_p=0.8, + stream=True, + tools=tools, + tool_choice="none", + ) + + chunks = list(response_stream) + self.assertTrue(len(chunks) > 0, "Streaming should return at least one chunk") + + found_tool_call = False + for chunk in chunks: + choice = chunk.choices[0] + # Check whether the current chunk contains tool_calls + found_tool_call = choice.delta.tool_calls is not None + + self.assertFalse( + found_tool_call, + "Shouldn't have any tool_call in the streaming chunks", + ) + + finish_reason = chunks[-1].choices[0].finish_reason + self.assertEqual( + finish_reason, + "stop", + "Final response of no function calling should have finish_reason 'stop'", + ) + + def test_streaming_multiple_choices_without_tools(self): + """ + Test: Verify that each choice gets its own finish_reason chunk without tool calls. + This tests the fix for regular content streaming with multiple choices. + """ + client = openai.Client(api_key=self.api_key, base_url=self.base_url) + + messages = [{"role": "user", "content": "Say hello in one word."}] + + # Request with n=2 to get multiple choices, no tools + response_stream = client.chat.completions.create( + model=self.model, + messages=messages, + temperature=0.8, + stream=True, + max_tokens=10, # Keep it short + n=2, # Multiple choices + ) + + chunks = list(response_stream) + + # Track finish_reason chunks for each index + finish_reason_chunks = {} + for chunk in chunks: + if chunk.choices: + for choice in chunk.choices: + if choice.finish_reason is not None: + index = choice.index + if index not in finish_reason_chunks: + finish_reason_chunks[index] = [] + finish_reason_chunks[index].append(choice.finish_reason) + + # Verify we got finish_reason chunks for both indices + self.assertEqual( + len(finish_reason_chunks), + 2, + f"Expected finish_reason chunks for 2 indices, got {len(finish_reason_chunks)}", + ) + + # Verify both index 0 and 1 have finish_reason + self.assertIn( + 0, finish_reason_chunks, "Missing finish_reason chunk for index 0" + ) + self.assertIn( + 1, finish_reason_chunks, "Missing finish_reason chunk for index 1" + ) + + # Verify the finish_reason is "stop" (regular completion) + for index, reasons in finish_reason_chunks.items(): + self.assertIn( + reasons[-1], + ["stop", "length"], # Could be either depending on how model responds + f"Expected finish_reason 'stop' or 'length' for index {index}, got {reasons[-1]}", + ) + + +class TestOpenAIPythonicFunctionCalling(CustomTestCase): + """Testcase:Verify the functionality of Python-style list-format function calling with pythonic parser for Llama-3.2-1B-Instruct model on Ascend NPU backend. + Cover: Explicit format prompt verification, streaming call index integrity, and return validity of parallel tool calls. + + [Test Category] Interface + [Test Target] /v1/chat/completions + """ + + PYTHONIC_TOOLS = [ + { + "type": "function", + "function": { + "name": "get_weather", + "description": "Get the current weather for a given location.", + "parameters": { + "type": "object", + "properties": { + "location": { + "type": "string", + "description": "The name of the city or location.", + } + }, + "required": ["location"], + }, + }, + }, + { + "type": "function", + "function": { + "name": "get_tourist_attractions", + "description": "Get a list of top tourist attractions for a given city.", + "parameters": { + "type": "object", + "properties": { + "city": { + "type": "string", + "description": "The name of the city to find attractions for.", + } + }, + "required": ["city"], + }, + }, + }, + ] + + PYTHONIC_MESSAGES = [ + { + "role": "system", + "content": ( + "You are a travel assistant. " + "When asked to call functions, ALWAYS respond ONLY with a python list of function calls, " + "using this format: [func_name1(param1=value1, param2=value2), func_name2(param=value)]. " + "Do NOT use JSON, do NOT use variables, do NOT use any other format. " + "Here is an example:\n" + '[get_weather(location="Paris"), get_tourist_attractions(city="Paris")]' + ), + }, + { + "role": "user", + "content": ( + "I'm planning a trip to Tokyo next week. What's the weather like and what are some top tourist attractions? " + "Propose parallel tool calls at once, using the python list of function calls format as shown above." + ), + }, + ] + + @classmethod + def setUpClass(cls): + cls.model = LLAMA_3_2_1B_INSTRUCT_WEIGHTS_PATH + cls.base_url = DEFAULT_URL_FOR_TEST + cls.api_key = "sk-123456" + cls.process = popen_launch_server( + cls.model, + cls.base_url, + timeout=DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH, + api_key=cls.api_key, + other_args=[ + "--attention-backend", + "ascend", + "--disable-cuda-graph", + "--tool-call-parser", + "pythonic", + ], + ) + cls.base_url += "/v1" + cls.tokenizer = get_tokenizer(cls.model) + + @classmethod + def tearDownClass(cls): + kill_process_tree(cls.process.pid) + + def test_pythonic_tool_call_prompt(self): + """ + Test: Explicit prompt for pythonic tool call format without chat template. + """ + client = openai.Client(api_key=self.api_key, base_url=self.base_url) + response = client.chat.completions.create( + model=self.model, + messages=self.PYTHONIC_MESSAGES, + tools=self.PYTHONIC_TOOLS, + temperature=0.1, + stream=False, + ) + tool_calls = response.choices[0].message.tool_calls + self.assertIsInstance(tool_calls, list, "No tool_calls found") + self.assertGreaterEqual(len(tool_calls), 1) + names = [tc.function.name for tc in tool_calls] + self.assertTrue( + "get_weather" in names or "get_tourist_attractions" in names, + f"Function name '{names}' should container either 'get_weather' or 'get_tourist_attractions'", + ) + + def test_pythonic_tool_call_streaming(self): + """ + Test: Streaming pythonic tool call format; assert tool_call index is present. + """ + client = openai.Client(api_key=self.api_key, base_url=self.base_url) + response_stream = client.chat.completions.create( + model=self.model, + messages=self.PYTHONIC_MESSAGES, + tools=self.PYTHONIC_TOOLS, + temperature=0.1, + stream=True, + ) + found_tool_calls = False + found_index = False + found_names = set() + for chunk in response_stream: + choice = chunk.choices[0] + if getattr(choice.delta, "tool_calls", None): + found_tool_calls = True + tool_call = choice.delta.tool_calls[0] + if hasattr(tool_call, "index") or ( + isinstance(tool_call, dict) and "index" in tool_call + ): + found_index = True + found_names.add(str(tool_call.function.name)) + + self.assertTrue(found_tool_calls, "No tool_calls found in streaming response") + self.assertTrue(found_index, "No index field found in any streamed tool_call") + self.assertTrue( + "get_weather" in found_names or "get_tourist_attractions" in found_names, + f"Function name '{found_names}' should container either 'get_weather' or 'get_tourist_attractions'", + ) + + +if __name__ == "__main__": + unittest.main() diff --git a/asian_ai/performance/SGLang/test/registered/ascend/interface/test_npu_openai_server_ignore_eos.py b/asian_ai/performance/SGLang/test/registered/ascend/interface/test_npu_openai_server_ignore_eos.py new file mode 100644 index 0000000000000000000000000000000000000000..aab1d3c831934d2d94b143ed64d4c27509b9eb00 --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/ascend/interface/test_npu_openai_server_ignore_eos.py @@ -0,0 +1,101 @@ +import unittest + +import openai + +from sglang.srt.utils import kill_process_tree +from sglang.srt.utils.hf_transformers_utils import get_tokenizer +from sglang.test.ascend.test_ascend_utils import LLAMA_3_2_1B_INSTRUCT_WEIGHTS_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) + + +class TestOpenAIServerIgnoreEOS(CustomTestCase): + """Testcase: Test 'ignore_eos' is True, the EOS is ignored and continue reasoning + + [Test Category] Interface + [Test Target] ignore_eos + """ + + @classmethod + def setUpClass(cls): + cls.model = LLAMA_3_2_1B_INSTRUCT_WEIGHTS_PATH + cls.base_url = DEFAULT_URL_FOR_TEST + cls.api_key = "sk-123456" + cls.other_args = [ + "--attention-backend", + "ascend", + "--disable-cuda-graph", + ] + cls.process = popen_launch_server( + cls.model, + cls.base_url, + timeout=DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH, + api_key=cls.api_key, + other_args=cls.other_args, + ) + cls.base_url += "/v1" + cls.tokenizer = get_tokenizer(cls.model) + + @classmethod + def tearDownClass(cls): + kill_process_tree(cls.process.pid) + + def test_ignore_eos(self): + client = openai.Client(api_key=self.api_key, base_url=self.base_url) + + max_tokens = 200 + + response_default = client.chat.completions.create( + model=self.model, + messages=[ + {"role": "system", "content": "You are a helpful assistant."}, + {"role": "user", "content": "Count from 1 to 20."}, + ], + temperature=0, + max_tokens=max_tokens, + extra_body={"ignore_eos": False}, + ) + + response_ignore_eos = client.chat.completions.create( + model=self.model, + messages=[ + {"role": "system", "content": "You are a helpful assistant."}, + {"role": "user", "content": "Count from 1 to 20."}, + ], + temperature=0, + max_tokens=max_tokens, + extra_body={"ignore_eos": True}, + ) + + default_tokens = len( + self.tokenizer.encode(response_default.choices[0].message.content) + ) + ignore_eos_tokens = len( + self.tokenizer.encode(response_ignore_eos.choices[0].message.content) + ) + + # Check if ignore_eos resulted in more tokens or exactly max_tokens + # The ignore_eos response should either: + # 1. Have more tokens than the default response (if default stopped at EOS before max_tokens) + # 2. Have exactly max_tokens (if it reached the max_tokens limit) + self.assertTrue( + ignore_eos_tokens > default_tokens or ignore_eos_tokens >= max_tokens, + f"ignore_eos did not generate more tokens: {ignore_eos_tokens} vs {default_tokens}", + ) + + self.assertEqual( + response_ignore_eos.choices[0].finish_reason, + "length", + f"Expected finish_reason='length' for ignore_eos=True, got {response_ignore_eos.choices[0].finish_reason}", + ) + + +if __name__ == "__main__": + unittest.main() diff --git a/asian_ai/performance/SGLang/test/registered/ascend/interface/test_npu_penalty.py b/asian_ai/performance/SGLang/test/registered/ascend/interface/test_npu_penalty.py new file mode 100644 index 0000000000000000000000000000000000000000..f53be2af162714f2581c78e4d916bbeb5d9ddc38 --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/ascend/interface/test_npu_penalty.py @@ -0,0 +1,111 @@ +import json +import random +import unittest +from concurrent.futures import ThreadPoolExecutor + +import requests + +from sglang.srt.utils import kill_process_tree +from sglang.test.ascend.test_ascend_utils import LLAMA_3_2_1B_INSTRUCT_WEIGHTS_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-1-npu-a3", nightly=True) + + +class TestPenalty(CustomTestCase): + """Testcase:Verify successful processing of inference requests with three specific mechanisms(frequency_penalty, presence_penalty, min_new_tokens). + + [Test Category] Interface + [Test Target] /generate + """ + + @classmethod + def setUpClass(cls): + cls.model = LLAMA_3_2_1B_INSTRUCT_WEIGHTS_PATH + other_args = [ + "--attention-backend", + "ascend", + "--disable-cuda-graph", + ] + cls.base_url = DEFAULT_URL_FOR_TEST + cls.process = popen_launch_server( + cls.model, + cls.base_url, + timeout=DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH, + other_args=other_args, + ) + + @classmethod + def tearDownClass(cls): + kill_process_tree(cls.process.pid) + + def run_decode(self, sampling_params): + # Send inference request with specified sampling/penalty parameters. + + return_logprob = True + top_logprobs_num = 5 + return_text = True + n = 1 + + response = requests.post( + self.base_url + "/generate", + json={ + # prompt that is supposed to generate < 32 tokens + "text": "<|start_header_id|>user<|end_header_id|>\n\nWhat is the answer for 1 + 1 = ?<|eot_id|><|start_header_id|>assistant<|end_header_id|>\n\n", + "sampling_params": { + "max_new_tokens": 48, + "n": n, + **sampling_params, + }, + "return_logprob": return_logprob, + "top_logprobs_num": top_logprobs_num, + "return_text_in_logprobs": return_text, + "logprob_start_len": 0, + }, + ) + self.assertEqual(response.status_code, 200) + print(json.dumps(response.json())) + print("=" * 100) + + def test_default_values(self): + self.run_decode({}) + + def test_frequency_penalty(self): + self.run_decode({"frequency_penalty": 2}) + + def test_min_new_tokens(self): + self.run_decode({"min_new_tokens": 16}) + + def test_presence_penalty(self): + self.run_decode({"presence_penalty": 2}) + + def test_penalty_mixed(self): + args = [ + {}, + {}, + {}, + {"frequency_penalty": 2}, + {"presence_penalty": 1}, + {"min_new_tokens": 16}, + {"frequency_penalty": 0.2}, + {"presence_penalty": 0.4}, + {"min_new_tokens": 8}, + {"frequency_penalty": 0.4, "presence_penalty": 0.8}, + {"frequency_penalty": 0.4, "min_new_tokens": 12}, + {"presence_penalty": 0.8, "min_new_tokens": 12}, + {"presence_penalty": -0.3, "frequency_penalty": 1.3, "min_new_tokens": 32}, + {"presence_penalty": 0.3, "frequency_penalty": -1.3, "min_new_tokens": 32}, + ] + random.shuffle(args * 5) + with ThreadPoolExecutor(8) as executor: + list(executor.map(self.run_decode, args)) + + +if __name__ == "__main__": + unittest.main(verbosity=3) diff --git a/asian_ai/performance/SGLang/test/registered/ascend/llm_models/test_ascend_dbrx_instruct.py b/asian_ai/performance/SGLang/test/registered/ascend/llm_models/test_ascend_dbrx_instruct.py new file mode 100644 index 0000000000000000000000000000000000000000..a698abd5bfc3210ce5ea7c28f93ac35995da96f3 --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/ascend/llm_models/test_ascend_dbrx_instruct.py @@ -0,0 +1,26 @@ +import unittest + +from sglang.test.ascend.gsm8k_ascend_mixin import GSM8KAscendMixin +from sglang.test.ci.ci_register import register_npu_ci +from sglang.test.test_utils import CustomTestCase + +register_npu_ci(est_time=400, suite="nightly-8-npu-a3", nightly=True) + + +class TestDbrx(GSM8KAscendMixin, CustomTestCase): + model = "/root/.cache/modelscope/hub/models/AI-ModelScope/dbrx-instruct" + accuracy = 0.735 + other_args = [ + "--trust-remote-code", + "--mem-fraction-static", + "0.8", + "--attention-backend", + "ascend", + "--disable-cuda-graph", + "--tp-size", + "8", + ] + + +if __name__ == "__main__": + unittest.main() diff --git a/asian_ai/performance/SGLang/test/registered/ascend/llm_models/test_ascend_minimax_m2.py b/asian_ai/performance/SGLang/test/registered/ascend/llm_models/test_ascend_minimax_m2.py new file mode 100644 index 0000000000000000000000000000000000000000..9f18369532a3add9f558d0e48ba7a02872715429 --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/ascend/llm_models/test_ascend_minimax_m2.py @@ -0,0 +1,44 @@ +import unittest + +from sglang.test.ascend.gsm8k_ascend_mixin import GSM8KAscendMixin +from sglang.test.ascend.test_ascend_utils import MINIMAX_M2_WEIGHTS_PATH +from sglang.test.ci.ci_register import register_npu_ci +from sglang.test.test_utils import CustomTestCase + +register_npu_ci( + est_time=400, + suite="nightly-8-npu-a3", + nightly=True, +) + + +class TestMiniMaxM2(GSM8KAscendMixin, CustomTestCase): + """Testcase: Verify that the inference accuracy of the cyankiwi/MiniMax-M2-BF16 model on the GSM8K dataset is no less than 0.9. + + [Test Category] Model + [Test Target] cyankiwi/MiniMax-M2-BF16 + """ + + model = MINIMAX_M2_WEIGHTS_PATH + accuracy = 0.9 + other_args = [ + "--trust-remote-code", + "--mem-fraction-static", + "0.9", + "--attention-backend", + "ascend", + "--tp-size", + "8", + "--disable-cuda-graph", + "--disable-radix-cache", + "--disable-overlap-schedule", + "--max-running-requests", + "64", + "--chunked-prefill-size", + "-1", + ] + timeout_for_server_launch = 1800 + + +if __name__ == "__main__": + unittest.main() diff --git a/asian_ai/performance/SGLang/test/registered/ascend/llm_models/test_ascend_trinity_mini.py b/asian_ai/performance/SGLang/test/registered/ascend/llm_models/test_ascend_trinity_mini.py new file mode 100644 index 0000000000000000000000000000000000000000..6ebeb1dc7fdb38804632fc8d0b2d12f43aad34ad --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/ascend/llm_models/test_ascend_trinity_mini.py @@ -0,0 +1,47 @@ +import unittest + +from sglang.test.ascend.gsm8k_ascend_mixin import GSM8KAscendMixin +from sglang.test.ascend.test_ascend_utils import TRINITY_MINI_WEIGHTS_PATH +from sglang.test.ci.ci_register import register_npu_ci +from sglang.test.test_utils import CustomTestCase + +register_npu_ci( + est_time=400, + suite="nightly-2-npu-a3", + nightly=True, +) + + +class TestTrinityMini(GSM8KAscendMixin, CustomTestCase): + """Testcase: Verify that the inference accuracy of the arcee-ai/Trinity-Mini model on the GSM8K dataset is no less than 0.85. + + [Test Category] Model + [Test Target] arcee-ai/Trinity-Mini + """ + + model = TRINITY_MINI_WEIGHTS_PATH + accuracy = 0.85 + other_args = [ + "--trust-remote-code", + "--mem-fraction-static", + "0.8", + "--attention-backend", + "ascend", + "--tp-size", + "2", + "--disable-cuda-graph", + "--disable-radix-cache", + "--disable-overlap-schedule", + "--context-length", + "4096", + "--max-running-requests", + "128", + "--chunked-prefill-size", + "-1", + "--chat-template", + f"{model}/chat_template.jinja", + ] + + +if __name__ == "__main__": + unittest.main() diff --git a/asian_ai/performance/SGLang/test/registered/ascend/llm_models/test_npu_afm_4_5b.py b/asian_ai/performance/SGLang/test/registered/ascend/llm_models/test_npu_afm_4_5b.py new file mode 100644 index 0000000000000000000000000000000000000000..0de084d89d9287f6c47a049e3dba583963d9c69b --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/ascend/llm_models/test_npu_afm_4_5b.py @@ -0,0 +1,23 @@ +import unittest + +from sglang.test.ascend.gsm8k_ascend_mixin import GSM8KAscendMixin +from sglang.test.ascend.test_ascend_utils import AFM_4_5B_BASE_WEIGHTS_PATH +from sglang.test.ci.ci_register import register_npu_ci +from sglang.test.test_utils import CustomTestCase + +register_npu_ci(est_time=400, suite="full-1-npu-a3", nightly=True) + + +class TestAFM(GSM8KAscendMixin, CustomTestCase): + """Testcase: Verify that the inference accuracy of the arcee-ai/AFM-4.5B-Base model on the GSM8K dataset is no less than 0.375. + + [Test Category] Model + [Test Target] arcee-ai/AFM-4.5B-Base + """ + + model = AFM_4_5B_BASE_WEIGHTS_PATH + accuracy = 0.375 + + +if __name__ == "__main__": + unittest.main() diff --git a/asian_ai/performance/SGLang/test/registered/ascend/llm_models/test_npu_baichuan2_13b_chat.py b/asian_ai/performance/SGLang/test/registered/ascend/llm_models/test_npu_baichuan2_13b_chat.py new file mode 100644 index 0000000000000000000000000000000000000000..83538433fc20aa3256ccdd2c8cd1657722b30baa --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/ascend/llm_models/test_npu_baichuan2_13b_chat.py @@ -0,0 +1,37 @@ +import unittest + +from sglang.test.ascend.gsm8k_ascend_mixin import GSM8KAscendMixin +from sglang.test.ascend.test_ascend_utils import BAICHUAN2_13B_CHAT_WEIGHTS_PATH +from sglang.test.ci.ci_register import register_npu_ci +from sglang.test.test_utils import CustomTestCase + +register_npu_ci(est_time=400, suite="nightly-1-npu-a3", nightly=True) + + +class TestBaichuan(GSM8KAscendMixin, CustomTestCase): + """Testcase: Verify that the inference accuracy of the baichuan-inc/Baichuan2-13B-Chat model on the GSM8K dataset is no less than 0.48. + + [Test Category] Model + [Test Target] baichuan-inc/Baichuan2-13B-Chat + """ + + model = BAICHUAN2_13B_CHAT_WEIGHTS_PATH + accuracy = 0.48 + other_args = [ + "--trust-remote-code", + "--mem-fraction-static", + "0.8", + "--attention-backend", + "ascend", + "--disable-cuda-graph", + "--max-running-requests", + "128", + "--disable-radix-cache", + "--chunked-prefill-size", + "-1", + ] + gsm8k_num_shots = 1 + + +if __name__ == "__main__": + unittest.main() diff --git a/asian_ai/performance/SGLang/test/registered/ascend/llm_models/test_npu_c4ai_command_r_v01.py b/asian_ai/performance/SGLang/test/registered/ascend/llm_models/test_npu_c4ai_command_r_v01.py new file mode 100644 index 0000000000000000000000000000000000000000..95067d5480d1b0a9d0b00b052b10195174e216f9 --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/ascend/llm_models/test_npu_c4ai_command_r_v01.py @@ -0,0 +1,40 @@ +import unittest + +from sglang.test.ascend.gsm8k_ascend_mixin import GSM8KAscendMixin +from sglang.test.ascend.test_ascend_utils import ( + C4AI_COMMAND_R_V01_CHAT_TEMPLATE_PATH, + C4AI_COMMAND_R_V01_WEIGHTS_PATH, +) +from sglang.test.ci.ci_register import register_npu_ci +from sglang.test.test_utils import CustomTestCase + +register_npu_ci(est_time=400, suite="full-2-npu-a3", nightly=True) + + +class TestC4AI(GSM8KAscendMixin, CustomTestCase): + """Testcase: Verify that the inference accuracy of the CohereForAI/c4ai-command-r-v01 model on the GSM8K dataset is no less than 0.55. + + [Test Category] Model + [Test Target] CohereForAI/c4ai-command-r-v01 + """ + + model = C4AI_COMMAND_R_V01_WEIGHTS_PATH + accuracy = 0.55 + other_args = [ + "--trust-remote-code", + "--mem-fraction-static", + "0.8", + "--attention-backend", + "ascend", + "--disable-cuda-graph", + "--chat-template", + C4AI_COMMAND_R_V01_CHAT_TEMPLATE_PATH, + "--tp-size", + "2", + "--dtype", + "bfloat16", + ] + + +if __name__ == "__main__": + unittest.main() diff --git a/asian_ai/performance/SGLang/test/registered/ascend/llm_models/test_npu_chatglm2_6b.py b/asian_ai/performance/SGLang/test/registered/ascend/llm_models/test_npu_chatglm2_6b.py new file mode 100644 index 0000000000000000000000000000000000000000..df5acb740456b14049908edf0ea510d48f2abb63 --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/ascend/llm_models/test_npu_chatglm2_6b.py @@ -0,0 +1,33 @@ +import unittest + +from sglang.test.ascend.gsm8k_ascend_mixin import GSM8KAscendMixin +from sglang.test.ascend.test_ascend_utils import CHATGLM2_6B_WEIGHTS_PATH +from sglang.test.ci.ci_register import register_npu_ci +from sglang.test.test_utils import CustomTestCase + +register_npu_ci(est_time=400, suite="nightly-1-npu-a3", nightly=True) + + +class TestChatGlm2(GSM8KAscendMixin, CustomTestCase): + """Testcase: Verify that the inference accuracy of the ZhipuAI/chatglm2-6b model on the GSM8K dataset is no less than 0.25. + + [Test Category] Model + [Test Target] ZhipuAI/chatglm2-6b + """ + + model = CHATGLM2_6B_WEIGHTS_PATH + accuracy = 0.25 + other_args = [ + "--trust-remote-code", + "--mem-fraction-static", + "0.8", + "--attention-backend", + "ascend", + "--disable-cuda-graph", + "--dtype", + "bfloat16", + ] + + +if __name__ == "__main__": + unittest.main() diff --git a/asian_ai/performance/SGLang/test/registered/ascend/llm_models/test_npu_deepseek_v3_2_exp_w8a8.py b/asian_ai/performance/SGLang/test/registered/ascend/llm_models/test_npu_deepseek_v3_2_exp_w8a8.py new file mode 100644 index 0000000000000000000000000000000000000000..9b89dccef283c19c0b56ff5e1760fd8098341aaf --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/ascend/llm_models/test_npu_deepseek_v3_2_exp_w8a8.py @@ -0,0 +1,37 @@ +import unittest + +from sglang.test.ascend.gsm8k_ascend_mixin import GSM8KAscendMixin +from sglang.test.ascend.test_ascend_utils import DEEPSEEK_V3_2_EXP_W8A8_WEIGHTS_PATH +from sglang.test.ci.ci_register import register_npu_ci +from sglang.test.test_utils import CustomTestCase + +register_npu_ci(est_time=400, suite="nightly-16-npu-a3", nightly=True) + + +class TestDeepSeekV32(GSM8KAscendMixin, CustomTestCase): + """Testcase: Verify that the inference accuracy of the vllm-ascend/DeepSeek-V3.2-Exp-W8A8 model on the GSM8K dataset is no less than 0.5. + + [Test Category] Model + [Test Target] vllm-ascend/DeepSeek-V3.2-Exp-W8A8 + """ + + model = DEEPSEEK_V3_2_EXP_W8A8_WEIGHTS_PATH + accuracy = 0.5 + timeout_for_server_launch = 3000 + other_args = [ + "--trust-remote-code", + "--mem-fraction-static", + "0.9", + "--attention-backend", + "ascend", + "--disable-cuda-graph", + "--tp-size", + "16", + "--quantization", + "modelslim", + "--disable-radix-cache", + ] + + +if __name__ == "__main__": + unittest.main() diff --git a/asian_ai/performance/SGLang/test/registered/ascend/llm_models/test_npu_exaone_3.py b/asian_ai/performance/SGLang/test/registered/ascend/llm_models/test_npu_exaone_3.py new file mode 100644 index 0000000000000000000000000000000000000000..a0d68d94d71ac5e58506fd1c61c5069c6909a047 --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/ascend/llm_models/test_npu_exaone_3.py @@ -0,0 +1,34 @@ +import unittest + +from sglang.test.ascend.gsm8k_ascend_mixin import GSM8KAscendMixin +from sglang.test.ascend.test_ascend_utils import EXAONE_3_5_7_8B_INSTRUCT_WEIGHTS_PATH +from sglang.test.ci.ci_register import register_npu_ci +from sglang.test.test_utils import CustomTestCase + +register_npu_ci(est_time=400, suite="full-1-npu-a3", nightly=True) + + +class TestEXAONE(GSM8KAscendMixin, CustomTestCase): + """Testcase: Verify that the inference accuracy of the LGAI-EXAONE/EXAONE-3.5-7.8B-Instruct model on the GSM8K dataset is no less than 0.8. + + [Test Category] Model + [Test Target] LGAI-EXAONE/EXAONE-3.5-7.8B-Instruct + """ + + model = EXAONE_3_5_7_8B_INSTRUCT_WEIGHTS_PATH + # Allow 1% tolerance for the accuracy threshold + accuracy = round(0.8 * 0.99, 3) + other_args = [ + "--trust-remote-code", + "--mem-fraction-static", + "0.8", + "--attention-backend", + "ascend", + "--disable-cuda-graph", + "--dtype", + "bfloat16", + ] + + +if __name__ == "__main__": + unittest.main() diff --git a/asian_ai/performance/SGLang/test/registered/ascend/llm_models/test_npu_gemma_3_4b_it_llm.py b/asian_ai/performance/SGLang/test/registered/ascend/llm_models/test_npu_gemma_3_4b_it_llm.py new file mode 100644 index 0000000000000000000000000000000000000000..05853394ba0ac02e0e9a18494aaa7bef2978f5dd --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/ascend/llm_models/test_npu_gemma_3_4b_it_llm.py @@ -0,0 +1,38 @@ +import unittest + +from sglang.test.ascend.gsm8k_ascend_mixin import GSM8KAscendMixin +from sglang.test.ascend.test_ascend_utils import GEMMA_3_4B_IT_WEIGHTS_PATH +from sglang.test.ci.ci_register import register_npu_ci +from sglang.test.test_utils import CustomTestCase + +register_npu_ci( + est_time=400, + suite="nightly-1-npu-a3", + nightly=True, +) + + +class TestGemma34B(GSM8KAscendMixin, CustomTestCase): + """Testcase: Verify that the inference accuracy of the google/gemma-3-4b-it model on the GSM8K dataset is no less than 0.7. + + [Test Category] Model + [Test Target] google/gemma-3-4b-it + """ + + model = GEMMA_3_4B_IT_WEIGHTS_PATH + accuracy = 0.7 + other_args = [ + "--trust-remote-code", + "--mem-fraction-static", + "0.8", + "--attention-backend", + "ascend", + "--disable-cuda-graph", + "--disable-radix-cache", + "--chunked-prefill-size", + "-1", + ] + + +if __name__ == "__main__": + unittest.main() diff --git a/asian_ai/performance/SGLang/test/registered/ascend/llm_models/test_npu_glm4_9b_chat.py b/asian_ai/performance/SGLang/test/registered/ascend/llm_models/test_npu_glm4_9b_chat.py new file mode 100644 index 0000000000000000000000000000000000000000..d4ec2e24aaaa3be0c91ecc84cd2e060fab91bf15 --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/ascend/llm_models/test_npu_glm4_9b_chat.py @@ -0,0 +1,27 @@ +import unittest + +from sglang.test.ascend.gsm8k_ascend_mixin import GSM8KAscendMixin +from sglang.test.ascend.test_ascend_utils import GLM_4_9B_CHAT_WEIGHTS_PATH +from sglang.test.ci.ci_register import register_npu_ci +from sglang.test.test_utils import CustomTestCase + +register_npu_ci( + est_time=400, + suite="nightly-1-npu-a3", + nightly=True, +) + + +class TestGLM49BChat(GSM8KAscendMixin, CustomTestCase): + """Testcase: Verify that the inference accuracy of the ZhipuAI/glm-4-9b-chat model on the GSM8K dataset is no less than 0.77. + + [Test Category] Model + [Test Target] ZhipuAI/glm-4-9b-chat + """ + + model = GLM_4_9B_CHAT_WEIGHTS_PATH + accuracy = 0.77 + + +if __name__ == "__main__": + unittest.main() diff --git a/asian_ai/performance/SGLang/test/registered/ascend/llm_models/test_npu_granite_3_0_3b_a800m.py b/asian_ai/performance/SGLang/test/registered/ascend/llm_models/test_npu_granite_3_0_3b_a800m.py new file mode 100644 index 0000000000000000000000000000000000000000..694c19574f0e6ef154268eee2bdb575823090e0f --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/ascend/llm_models/test_npu_granite_3_0_3b_a800m.py @@ -0,0 +1,25 @@ +import unittest + +from sglang.test.ascend.gsm8k_ascend_mixin import GSM8KAscendMixin +from sglang.test.ascend.test_ascend_utils import ( + GRANITE_3_0_3B_A800M_INSTRUCT_WEIGHTS_PATH, +) +from sglang.test.ci.ci_register import register_npu_ci +from sglang.test.test_utils import CustomTestCase + +register_npu_ci(est_time=400, suite="full-1-npu-a3", nightly=True) + + +class TestGranite(GSM8KAscendMixin, CustomTestCase): + """Testcase: Verify that the inference accuracy of the ibm-granite/granite-3.0-3b-a800m-instruct model on the GSM8K dataset is no less than 0.38. + + [Test Category] Model + [Test Target] ibm-granite/granite-3.0-3b-a800m-instruct + """ + + model = GRANITE_3_0_3B_A800M_INSTRUCT_WEIGHTS_PATH + accuracy = 0.38 + + +if __name__ == "__main__": + unittest.main() diff --git a/asian_ai/performance/SGLang/test/registered/ascend/llm_models/test_npu_granite_3_1_8b.py b/asian_ai/performance/SGLang/test/registered/ascend/llm_models/test_npu_granite_3_1_8b.py new file mode 100644 index 0000000000000000000000000000000000000000..0a8ce28803d180013f7bcbbd8c371605aa09dfc8 --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/ascend/llm_models/test_npu_granite_3_1_8b.py @@ -0,0 +1,23 @@ +import unittest + +from sglang.test.ascend.gsm8k_ascend_mixin import GSM8KAscendMixin +from sglang.test.ascend.test_ascend_utils import GRANITE_3_1_8B_INSTRUCT_WEIGHTS_PATH +from sglang.test.ci.ci_register import register_npu_ci +from sglang.test.test_utils import CustomTestCase + +register_npu_ci(est_time=400, suite="full-1-npu-a3", nightly=True) + + +class TestGranite(GSM8KAscendMixin, CustomTestCase): + """Testcase: Verify that the inference accuracy of the ibm-granite/granite-3.1-8b-instruct model on the GSM8K dataset is no less than 0.695. + + [Test Category] Model + [Test Target] ibm-granite/granite-3.1-8b-instruct + """ + + model = GRANITE_3_1_8B_INSTRUCT_WEIGHTS_PATH + accuracy = 0.695 + + +if __name__ == "__main__": + unittest.main() diff --git a/asian_ai/performance/SGLang/test/registered/ascend/llm_models/test_npu_grok_2.py b/asian_ai/performance/SGLang/test/registered/ascend/llm_models/test_npu_grok_2.py new file mode 100644 index 0000000000000000000000000000000000000000..f23fbf3ed6cea80a9aa51ae6be509720251be1a1 --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/ascend/llm_models/test_npu_grok_2.py @@ -0,0 +1,33 @@ +import unittest + +from sglang.test.ascend.gsm8k_ascend_mixin import GSM8KAscendMixin +from sglang.test.ci.ci_register import register_npu_ci +from sglang.test.test_utils import CustomTestCase + +register_npu_ci( + est_time=400, + suite="full-16-npu-a3", + nightly=True, +) + + +class TestGrok2(GSM8KAscendMixin, CustomTestCase): + model = "/root/.cache/modelscope/hub/models/huihui-ai/grok-2" + accuracy = 0.91 + other_args = [ + "--trust-remote-code", + "--mem-fraction-static", + "0.8", + "--attention-backend", + "ascend", + "--disable-radix-cache", + "--disable-cuda-graph", + "--tokenizer-path", + "/root/.cache/modelscope/hub/models/huihui-ai/grok-2/tokenizer.tok.json", + "--tp-size", + "16", + ] + + +if __name__ == "__main__": + unittest.main() diff --git a/asian_ai/performance/SGLang/test/registered/ascend/llm_models/test_npu_internlm2_7b.py b/asian_ai/performance/SGLang/test/registered/ascend/llm_models/test_npu_internlm2_7b.py new file mode 100644 index 0000000000000000000000000000000000000000..621e1d5fb36a31232aea9aea01498c3dc9d84ada --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/ascend/llm_models/test_npu_internlm2_7b.py @@ -0,0 +1,29 @@ +import os +import unittest + +from sglang.test.ascend.gsm8k_ascend_mixin import GSM8KAscendMixin +from sglang.test.ascend.test_ascend_utils import INTERNLM2_7B_WEIGHTS_PATH +from sglang.test.ci.ci_register import register_npu_ci +from sglang.test.test_utils import CustomTestCase + +register_npu_ci( + est_time=400, + suite="nightly-1-npu-a3", + nightly=True, +) + + +class TestInternlm2(GSM8KAscendMixin, CustomTestCase): + """Testcase: Verify that the inference accuracy of the Shanghai_AI_Laboratory/internlm2-7b model on the GSM8K dataset is no less than 0.585. + + [Test Category] Model + [Test Target] Shanghai_AI_Laboratory/internlm2-7b + """ + + os.environ["PROTOCOL_BUFFERS_PYTHON_IMPLEMENTATION"] = "python" + model = INTERNLM2_7B_WEIGHTS_PATH + accuracy = 0.585 + + +if __name__ == "__main__": + unittest.main() diff --git a/asian_ai/performance/SGLang/test/registered/ascend/llm_models/test_npu_ling_lite.py b/asian_ai/performance/SGLang/test/registered/ascend/llm_models/test_npu_ling_lite.py new file mode 100644 index 0000000000000000000000000000000000000000..932dfc814c794a8c10db2d4480da9aa570e50176 --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/ascend/llm_models/test_npu_ling_lite.py @@ -0,0 +1,33 @@ +import unittest + +from sglang.test.ascend.gsm8k_ascend_mixin import GSM8KAscendMixin +from sglang.test.ascend.test_ascend_utils import LING_LITE_WEIGHTS_PATH +from sglang.test.ci.ci_register import register_npu_ci +from sglang.test.test_utils import CustomTestCase + +register_npu_ci(est_time=400, suite="full-2-npu-a3", nightly=True) + + +class TestLingLite(GSM8KAscendMixin, CustomTestCase): + """Testcase: Verify that the inference accuracy of the inclusionAI/Ling-lite model on the GSM8K dataset is no less than 0.75. + + [Test Category] Model + [Test Target] inclusionAI/Ling-lite + """ + + model = LING_LITE_WEIGHTS_PATH + accuracy = 0.75 + other_args = [ + "--trust-remote-code", + "--mem-fraction-static", + "0.8", + "--attention-backend", + "ascend", + "--disable-cuda-graph", + "--tp-size", + "2", + ] + + +if __name__ == "__main__": + unittest.main() diff --git a/asian_ai/performance/SGLang/test/registered/ascend/llm_models/test_npu_llama4_scount_17b_16e.py b/asian_ai/performance/SGLang/test/registered/ascend/llm_models/test_npu_llama4_scount_17b_16e.py new file mode 100644 index 0000000000000000000000000000000000000000..76e9abd01bf07e0b60bc1b1401a98bc2d0dade8f --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/ascend/llm_models/test_npu_llama4_scount_17b_16e.py @@ -0,0 +1,40 @@ +import unittest + +from sglang.test.ascend.gsm8k_ascend_mixin import GSM8KAscendMixin +from sglang.test.ascend.test_ascend_utils import ( + LLAMA_4_SCOUT_17B_16E_INSTRUCT_WEIGHTS_PATH, +) +from sglang.test.ci.ci_register import register_npu_ci +from sglang.test.test_utils import CustomTestCase + +register_npu_ci(est_time=400, suite="nightly-4-npu-a3", nightly=True) + + +class TestLlama4(GSM8KAscendMixin, CustomTestCase): + """Testcase: Verify that the inference accuracy of the meta-llama/Llama-4-Scout-17B-16E-Instruct model on the GSM8K dataset is no less than 0.9. + + [Test Category] Model + [Test Target] meta-llama/Llama-4-Scout-17B-16E-Instruct + """ + + model = LLAMA_4_SCOUT_17B_16E_INSTRUCT_WEIGHTS_PATH + accuracy = 0.9 + timeout_for_server_launch = 1000 + other_args = [ + "--chat-template", + "llama-4", + "--tp-size", + 4, + "--mem-fraction-static", + "0.9", + "--context-length", + "8192", + "--attention-backend", + "ascend", + "--disable-cuda-graph", + "--disable-radix-cache", + ] + + +if __name__ == "__main__": + unittest.main() diff --git a/asian_ai/performance/SGLang/test/registered/ascend/llm_models/test_npu_llama_2_7b.py b/asian_ai/performance/SGLang/test/registered/ascend/llm_models/test_npu_llama_2_7b.py new file mode 100644 index 0000000000000000000000000000000000000000..0e83fbd310d3878ef9e3f48858a7f3a6dc32e4fa --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/ascend/llm_models/test_npu_llama_2_7b.py @@ -0,0 +1,23 @@ +import unittest + +from sglang.test.ascend.gsm8k_ascend_mixin import GSM8KAscendMixin +from sglang.test.ascend.test_ascend_utils import LLAMA_2_7B_WEIGHTS_PATH +from sglang.test.ci.ci_register import register_npu_ci +from sglang.test.test_utils import CustomTestCase + +register_npu_ci(est_time=400, suite="nightly-1-npu-a3", nightly=True) + + +class TestLlama(GSM8KAscendMixin, CustomTestCase): + """Testcase: Verify that the inference accuracy of the LLM-Research/Llama-2-7B model on the GSM8K dataset is no less than 0.18. + + [Test Category] Model + [Test Target] LLM-Research/Llama-2-7B + """ + + model = LLAMA_2_7B_WEIGHTS_PATH + accuracy = 0.18 + + +if __name__ == "__main__": + unittest.main() diff --git a/asian_ai/performance/SGLang/test/registered/ascend/llm_models/test_npu_llama_2_7b_communications_compression.py b/asian_ai/performance/SGLang/test/registered/ascend/llm_models/test_npu_llama_2_7b_communications_compression.py new file mode 100644 index 0000000000000000000000000000000000000000..00762e9ed620f2a3fb3af12b409db5df8c9fe169 --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/ascend/llm_models/test_npu_llama_2_7b_communications_compression.py @@ -0,0 +1,37 @@ +import unittest + +from sglang.test.ascend.gsm8k_ascend_mixin import GSM8KAscendMixin +from sglang.test.ascend.test_ascend_utils import LLAMA_2_7B_WEIGHTS_PATH +from sglang.test.ci.ci_register import register_npu_ci +from sglang.test.test_utils import CustomTestCase + +register_npu_ci(est_time=400, suite="nightly-2-npu-a3") + + +class TestLlama(GSM8KAscendMixin, CustomTestCase): + """Testcase: Verify that the inference accuracy of the LLM-Research/Llama-2-7B model on the GSM8K dataset with tp communications quantization is no less than 0.18. + + [Test Category] Model + [Test Target] LLM-Research/Llama-2-7B + """ + + model = LLAMA_2_7B_WEIGHTS_PATH + accuracy = 0.18 + other_args = [ + "--trust-remote-code", + "--mem-fraction-static", + 0.8, + "--max-running-requests", + 32, + "--attention-backend", + "ascend", + "--cuda-graph-max-bs-decode", + 32, + "--tp-size", + 2, + "--enable-quant-communications", + ] + + +if __name__ == "__main__": + unittest.main() diff --git a/asian_ai/performance/SGLang/test/registered/ascend/llm_models/test_npu_mimo_7b_rl.py b/asian_ai/performance/SGLang/test/registered/ascend/llm_models/test_npu_mimo_7b_rl.py new file mode 100644 index 0000000000000000000000000000000000000000..ddfbbc952d0fd03dc96ac4e988ca04ca3277d22e --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/ascend/llm_models/test_npu_mimo_7b_rl.py @@ -0,0 +1,23 @@ +import unittest + +from sglang.test.ascend.gsm8k_ascend_mixin import GSM8KAscendMixin +from sglang.test.ascend.test_ascend_utils import MIMO_7B_RL_WEIGHTS_PATH +from sglang.test.ci.ci_register import register_npu_ci +from sglang.test.test_utils import CustomTestCase + +register_npu_ci(est_time=400, suite="full-1-npu-a3", nightly=True) + + +class TestMiMo7BRL(GSM8KAscendMixin, CustomTestCase): + """Testcase: Verify that the inference accuracy of the XiaomiMiMo/MiMo-7B-RL model on the GSM8K dataset is no less than 0.75. + + [Test Category] Model + [Test Target] XiaomiMiMo/MiMo-7B-RL + """ + + model = MIMO_7B_RL_WEIGHTS_PATH + accuracy = 0.75 + + +if __name__ == "__main__": + unittest.main() diff --git a/asian_ai/performance/SGLang/test/registered/ascend/llm_models/test_npu_minicpm3_4b.py b/asian_ai/performance/SGLang/test/registered/ascend/llm_models/test_npu_minicpm3_4b.py new file mode 100644 index 0000000000000000000000000000000000000000..902c21546febc321c1a51d129ae3cfeca823a1ef --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/ascend/llm_models/test_npu_minicpm3_4b.py @@ -0,0 +1,37 @@ +import unittest + +from sglang.test.ascend.gsm8k_ascend_mixin import GSM8KAscendMixin +from sglang.test.ascend.test_ascend_utils import MINICPM3_4B_WEIGHTS_PATH +from sglang.test.ci.ci_register import register_npu_ci +from sglang.test.test_utils import CustomTestCase + +register_npu_ci(est_time=400, suite="nightly-1-npu-a3", nightly=True) + + +class TestMiniCPM3(GSM8KAscendMixin, CustomTestCase): + """Testcase: Verify that the inference accuracy of the OpenBMB/MiniCPM3-4B model on the GSM8K dataset is no less than 0.69. + + [Test Category] Model + [Test Target] OpenBMB/MiniCPM3-4B + """ + + model = MINICPM3_4B_WEIGHTS_PATH + accuracy = 0.69 + other_args = [ + "--trust-remote-code", + "--mem-fraction-static", + "0.8", + "--attention-backend", + "ascend", + "--disable-cuda-graph", + "--disable-radix-cache", + "--disable-overlap-schedule", + "--max-running-requests", + "128", + "--chunked-prefill-size", + "-1", + ] + + +if __name__ == "__main__": + unittest.main() diff --git a/asian_ai/performance/SGLang/test/registered/ascend/llm_models/test_npu_mistral_7b.py b/asian_ai/performance/SGLang/test/registered/ascend/llm_models/test_npu_mistral_7b.py new file mode 100644 index 0000000000000000000000000000000000000000..509bae7b73e9fd882984fd8ba0b7d7eb93026b5a --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/ascend/llm_models/test_npu_mistral_7b.py @@ -0,0 +1,23 @@ +import unittest + +from sglang.test.ascend.gsm8k_ascend_mixin import GSM8KAscendMixin +from sglang.test.ascend.test_ascend_utils import MISTRAL_7B_INSTRUCT_V0_2_WEIGHTS_PATH +from sglang.test.ci.ci_register import register_npu_ci +from sglang.test.test_utils import CustomTestCase + +register_npu_ci(est_time=400, suite="nightly-1-npu-a3", nightly=True) + + +class TestMistral7B(GSM8KAscendMixin, CustomTestCase): + """Testcase: Verify that the inference accuracy of the mistralai/Mistral-7B-Instruct-v0.2 model on the GSM8K dataset is no less than 0.375. + + [Test Category] Model + [Test Target] mistralai/Mistral-7B-Instruct-v0.2 + """ + + model = MISTRAL_7B_INSTRUCT_V0_2_WEIGHTS_PATH + accuracy = 0.375 + + +if __name__ == "__main__": + unittest.main() diff --git a/asian_ai/performance/SGLang/test/registered/ascend/llm_models/test_npu_persimmon_8b_chat.py b/asian_ai/performance/SGLang/test/registered/ascend/llm_models/test_npu_persimmon_8b_chat.py new file mode 100644 index 0000000000000000000000000000000000000000..9ff337e89011e9f79948b172e1da923927012100 --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/ascend/llm_models/test_npu_persimmon_8b_chat.py @@ -0,0 +1,29 @@ +import os +import unittest + +from sglang.test.ascend.gsm8k_ascend_mixin import GSM8KAscendMixin +from sglang.test.ascend.test_ascend_utils import PERSIMMON_8B_CHAT_WEIGHTS_PATH +from sglang.test.ci.ci_register import register_npu_ci +from sglang.test.test_utils import CustomTestCase + +register_npu_ci( + est_time=400, + suite="full-1-npu-a3", + nightly=True, +) + + +class TestPersimmon8BChat(GSM8KAscendMixin, CustomTestCase): + """Testcase: Verify that the inference accuracy of the Howeee/persimmon-8b-chat model on the GSM8K dataset is no less than 0.17. + + [Test Category] Model + [Test Target] Howeee/persimmon-8b-chat + """ + + os.environ["PROTOCOL_BUFFERS_PYTHON_IMPLEMENTATION"] = "python" + model = PERSIMMON_8B_CHAT_WEIGHTS_PATH + accuracy = 0.17 + + +if __name__ == "__main__": + unittest.main() diff --git a/asian_ai/performance/SGLang/test/registered/ascend/llm_models/test_npu_phi_4_multimodal_llm.py b/asian_ai/performance/SGLang/test/registered/ascend/llm_models/test_npu_phi_4_multimodal_llm.py new file mode 100644 index 0000000000000000000000000000000000000000..5fc3ae05bf6320b0dd1aa4215a47d0ecd60311d5 --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/ascend/llm_models/test_npu_phi_4_multimodal_llm.py @@ -0,0 +1,23 @@ +import unittest + +from sglang.test.ascend.gsm8k_ascend_mixin import GSM8KAscendMixin +from sglang.test.ascend.test_ascend_utils import PHI_4_MULTIMODAL_INSTRUCT_WEIGHTS_PATH +from sglang.test.ci.ci_register import register_npu_ci +from sglang.test.test_utils import CustomTestCase + +register_npu_ci(est_time=400, suite="nightly-1-npu-a3", nightly=True) + + +class TestPhi4(GSM8KAscendMixin, CustomTestCase): + """Testcase: Verify that the inference accuracy of the microsoft/Phi-4-multimodal-instruct model on the GSM8K dataset is no less than 0.8. + + [Test Category] Model + [Test Target] microsoft/Phi-4-multimodal-instruct + """ + + model = PHI_4_MULTIMODAL_INSTRUCT_WEIGHTS_PATH + accuracy = 0.8 + + +if __name__ == "__main__": + unittest.main() diff --git a/asian_ai/performance/SGLang/test/registered/ascend/llm_models/test_npu_qwen3_0_6b.py b/asian_ai/performance/SGLang/test/registered/ascend/llm_models/test_npu_qwen3_0_6b.py new file mode 100644 index 0000000000000000000000000000000000000000..daa76dfa538cb4053ef2616506ae6279be9b3fc3 --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/ascend/llm_models/test_npu_qwen3_0_6b.py @@ -0,0 +1,30 @@ +import unittest + +from sglang.test.ascend.gsm8k_ascend_mixin import GSM8KAscendMixin +from sglang.test.ascend.test_ascend_utils import QWEN3_0_6B_WEIGHTS_PATH +from sglang.test.ci.ci_register import register_npu_ci +from sglang.test.test_utils import CustomTestCase + +register_npu_ci(est_time=400, suite="nightly-1-npu-a3", nightly=True) + + +class TestQwen306B(GSM8KAscendMixin, CustomTestCase): + """Testcase: Verify that the inference accuracy of the Qwen/Qwen3-0.6B model on the GSM8K dataset is no less than 0.38. + + [Test Category] Model + [Test Target] Qwen/Qwen3-0.6B + """ + + model = QWEN3_0_6B_WEIGHTS_PATH + accuracy = 0.38 + other_args = [ + "--chunked-prefill-size", + 256, + "--attention-backend", + "ascend", + "--disable-cuda-graph", + ] + + +if __name__ == "__main__": + unittest.main() diff --git a/asian_ai/performance/SGLang/test/registered/ascend/llm_models/test_npu_qwen3_1_7b_gptq_int8.py b/asian_ai/performance/SGLang/test/registered/ascend/llm_models/test_npu_qwen3_1_7b_gptq_int8.py new file mode 100644 index 0000000000000000000000000000000000000000..207f7899de7f05f2caeb5d6ff14d1f9113d62a58 --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/ascend/llm_models/test_npu_qwen3_1_7b_gptq_int8.py @@ -0,0 +1,32 @@ +import unittest + +from sglang.test.ascend.gsm8k_ascend_mixin import GSM8KAscendMixin +from sglang.test.ascend.test_ascend_utils import QWEN3_1_7B_GPTQ_INT8_WEIGHTS_PATH +from sglang.test.ci.ci_register import register_npu_ci +from sglang.test.test_utils import CustomTestCase + +register_npu_ci(est_time=400, suite="per-commit-1-npu-a2") + + +class TestQwen317BGPTQInt8(GSM8KAscendMixin, CustomTestCase): + """Testcase: Verify that the inference accuracy of the Qwen/Qwen3-1.7B-GPTQ-Int8 model on the GSM8K dataset is no less than 0.65. + + [Test Category] Model + [Test Target] Qwen/Qwen3-1.7B-GPTQ-Int8 + """ + + model = QWEN3_1_7B_GPTQ_INT8_WEIGHTS_PATH + accuracy = 0.65 + other_args = [ + "--trust-remote-code", + "--mem-fraction-static", + "0.8", + "--attention-backend", + "ascend", + "--quantization", + "gptq", + ] + + +if __name__ == "__main__": + unittest.main() diff --git a/asian_ai/performance/SGLang/test/registered/ascend/llm_models/test_npu_qwen3_235b_a22b_w8a8.py b/asian_ai/performance/SGLang/test/registered/ascend/llm_models/test_npu_qwen3_235b_a22b_w8a8.py new file mode 100644 index 0000000000000000000000000000000000000000..fe7abd488b9eb4a2836783e70512f961cd2ed54a --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/ascend/llm_models/test_npu_qwen3_235b_a22b_w8a8.py @@ -0,0 +1,36 @@ +import unittest + +from sglang.test.ascend.gsm8k_ascend_mixin import GSM8KAscendMixin +from sglang.test.ascend.test_ascend_utils import QWEN3_235B_A22B_W8A8_WEIGHTS_PATH +from sglang.test.ci.ci_register import register_npu_ci +from sglang.test.test_utils import CustomTestCase + +register_npu_ci(est_time=400, suite="nightly-8-npu-a3", nightly=True) + + +class TestQwen3235BA22BW8A8(GSM8KAscendMixin, CustomTestCase): + """Testcase: Verify that the inference accuracy of the vllm-ascend/Qwen3-235B-A22B-W8A8 model on the GSM8K dataset is no less than 0.955. + + [Test Category] Model + [Test Target] vllm-ascend/Qwen3-235B-A22B-W8A8 + """ + + model = QWEN3_235B_A22B_W8A8_WEIGHTS_PATH + accuracy = 0.955 + timeout_for_server_launch = 3000 + other_args = [ + "--trust-remote-code", + "--mem-fraction-static", + "0.8", + "--attention-backend", + "ascend", + "--disable-cuda-graph", + "--tp-size", + "8", + "--quantization", + "modelslim", + ] + + +if __name__ == "__main__": + unittest.main() diff --git a/asian_ai/performance/SGLang/test/registered/ascend/llm_models/test_npu_qwen3_30b.py b/asian_ai/performance/SGLang/test/registered/ascend/llm_models/test_npu_qwen3_30b.py new file mode 100644 index 0000000000000000000000000000000000000000..9ccc8185aff2ddb38507762bfea00c1541ba5ff0 --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/ascend/llm_models/test_npu_qwen3_30b.py @@ -0,0 +1,39 @@ +import unittest + +from sglang.test.ascend.gsm8k_ascend_mixin import GSM8KAscendMixin +from sglang.test.ascend.test_ascend_utils import ( + QWEN3_30B_A3B_INSTRUCT_2507_WEIGHTS_PATH, +) +from sglang.test.ci.ci_register import register_npu_ci +from sglang.test.test_utils import CustomTestCase + +register_npu_ci(est_time=400, suite="nightly-2-npu-a3", nightly=True) + + +class TestQwen330B(GSM8KAscendMixin, CustomTestCase): + """Testcase: Verify that the inference accuracy of the Qwen/Qwen3-30B-A3B-Instruct-2507 model on the GSM8K dataset is no less than 0.90. + + [Test Category] Model + [Test Target] Qwen/Qwen3-30B-A3B-Instruct-2507 + """ + + model = QWEN3_30B_A3B_INSTRUCT_2507_WEIGHTS_PATH + accuracy = 0.90 + other_args = [ + "--trust-remote-code", + "--mem-fraction-static", + 0.7, + "--max-running-requests", + 32, + "--attention-backend", + "ascend", + "--disable-cuda-graph", + "--cuda-graph-max-bs-decode", + 32, + "--tp-size", + 2, + ] + + +if __name__ == "__main__": + unittest.main() diff --git a/asian_ai/performance/SGLang/test/registered/ascend/llm_models/test_npu_qwen3_30b_attn_cp.py b/asian_ai/performance/SGLang/test/registered/ascend/llm_models/test_npu_qwen3_30b_attn_cp.py new file mode 100644 index 0000000000000000000000000000000000000000..69aaf3d6e1df77af13966869516cc45552b276b3 --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/ascend/llm_models/test_npu_qwen3_30b_attn_cp.py @@ -0,0 +1,55 @@ +import os +import unittest + +from sglang.test.ascend.gsm8k_ascend_mixin import GSM8KAscendMixin +from sglang.test.ascend.test_ascend_utils import QWEN3_30B_A3B_WEIGHTS_PATH +from sglang.test.ci.ci_register import register_npu_ci +from sglang.test.test_utils import CustomTestCase + +register_npu_ci(est_time=500, suite="nightly-4-npu-a3", nightly=True) + + +class TestQwen330BAttnCP(GSM8KAscendMixin, CustomTestCase): + """GSM8K accuracy test for Qwen3-30B-A3B mixed deployment on 4 NPUs. + + The test uses: + - TP = 4 + - MOE_DP = 2 + - ATTN_CP = 2 + - prefill context parallel enabled + + This is the mixed/co-located deployment variant and reuses the Ascend + environment variables from the PD GSM8K test. + """ + + model = QWEN3_30B_A3B_WEIGHTS_PATH + other_args = [ + "--trust-remote-code", + "--mem-fraction-static", + "0.7", + "--max-running-requests", + "32", + "--attention-backend", + "ascend", + "--tp-size", + "4", + "--moe-dp-size", + "2", + "--attn-cp-size", + "2", + "--cuda-graph-max-bs-decode", + "32", + "--enable-prefill-context-parallel", + ] + + env = {**os.environ, "ASCEND_USE_FIA": "1"} + + # GSM8K Configs + accuracy = 0.92 # GSM8K accuracy ≥0.92 + gsm8k_parallel = 32 + num_questions = 100 + gsm8k_num_shots = 5 + + +if __name__ == "__main__": + unittest.main() diff --git a/asian_ai/performance/SGLang/test/registered/ascend/llm_models/test_npu_qwen3_30b_w4a4.py b/asian_ai/performance/SGLang/test/registered/ascend/llm_models/test_npu_qwen3_30b_w4a4.py new file mode 100644 index 0000000000000000000000000000000000000000..e0f012b6fbdc86f33b5edb5ff35ba6fb89031646 --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/ascend/llm_models/test_npu_qwen3_30b_w4a4.py @@ -0,0 +1,37 @@ +import unittest + +from sglang.test.ascend.gsm8k_ascend_mixin import GSM8KAscendMixin +from sglang.test.ascend.test_ascend_utils import QWEN3_30B_MODELSLIM_INT4_WEIGHTS_PATH +from sglang.test.ci.ci_register import register_npu_ci +from sglang.test.test_utils import CustomTestCase + +register_npu_ci(est_time=400, suite="per-commit-2-npu-a2") + + +class TestQwen317BGPTQInt8(GSM8KAscendMixin, CustomTestCase): + """Testcase: Verify that the inference accuracy of the Eco-Tech/Qwen3-30B-A3B-w4a4-LAOS model on the GSM8K dataset is no less than 0.85. + + [Test Category] Model + [Test Target] Qwen/Qwen3-1.7B-GPTQ-Int8 + """ + + model = QWEN3_30B_MODELSLIM_INT4_WEIGHTS_PATH + accuracy = 0.85 + other_args = [ + "--trust-remote-code", + "--mem-fraction-static", + 0.8, + "--max-running-requests", + 32, + "--attention-backend", + "ascend", + "--disable-cuda-graph", + "--cuda-graph-max-bs-decode", + 32, + "--tp-size", + 2, + ] + + +if __name__ == "__main__": + unittest.main() diff --git a/asian_ai/performance/SGLang/test/registered/ascend/llm_models/test_npu_qwen3_32b.py b/asian_ai/performance/SGLang/test/registered/ascend/llm_models/test_npu_qwen3_32b.py new file mode 100644 index 0000000000000000000000000000000000000000..582f004ab08718eb7ffa7cf29e4391a89bd218ce --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/ascend/llm_models/test_npu_qwen3_32b.py @@ -0,0 +1,37 @@ +import unittest + +from sglang.test.ascend.gsm8k_ascend_mixin import GSM8KAscendMixin +from sglang.test.ascend.test_ascend_utils import QWEN3_32B_WEIGHTS_PATH +from sglang.test.ci.ci_register import register_npu_ci +from sglang.test.test_utils import CustomTestCase + +register_npu_ci( + est_time=400, + suite="nightly-4-npu-a3", + nightly=True, +) + + +class TestQwen332B(GSM8KAscendMixin, CustomTestCase): + """Testcase: Verify that the inference accuracy of the Qwen/Qwen3-32B model on the GSM8K dataset is no less than 0.86. + + [Test Category] Model + [Test Target] Qwen/Qwen3-32B + """ + + model = QWEN3_32B_WEIGHTS_PATH + accuracy = 0.86 + other_args = [ + "--trust-remote-code", + "--mem-fraction-static", + "0.8", + "--attention-backend", + "ascend", + "--disable-cuda-graph", + "--tp-size", + "4", + ] + + +if __name__ == "__main__": + unittest.main() diff --git a/asian_ai/performance/SGLang/test/registered/ascend/llm_models/test_npu_qwen3_8b_communications_quantization.py b/asian_ai/performance/SGLang/test/registered/ascend/llm_models/test_npu_qwen3_8b_communications_quantization.py new file mode 100644 index 0000000000000000000000000000000000000000..7587c7374885ff1012d6e8752751bb9b41738f02 --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/ascend/llm_models/test_npu_qwen3_8b_communications_quantization.py @@ -0,0 +1,37 @@ +import unittest + +from sglang.test.ascend.gsm8k_ascend_mixin import GSM8KAscendMixin +from sglang.test.ascend.test_ascend_utils import QWEN3_8B_WEIGHTS_PATH +from sglang.test.ci.ci_register import register_npu_ci +from sglang.test.test_utils import CustomTestCase + +register_npu_ci(est_time=400, suite="nightly-2-npu-a3") + + +class TestQwen38BCommQuantization(GSM8KAscendMixin, CustomTestCase): + """Testcase: Verify that the inference accuracy of the Qwen/Qwen3-8B model with TP communications quantization on the GSM8K dataset is no less than 0.85. + + [Test Category] Model + [Test Target] Qwen/Qwen3-8B + """ + + model = QWEN3_8B_WEIGHTS_PATH + accuracy = 0.85 + other_args = [ + "--trust-remote-code", + "--mem-fraction-static", + 0.8, + "--max-running-requests", + 32, + "--attention-backend", + "ascend", + "--cuda-graph-max-bs-decode", + 32, + "--tp-size", + 2, + "--enable-quant-communications", + ] + + +if __name__ == "__main__": + unittest.main() diff --git a/asian_ai/performance/SGLang/test/registered/ascend/llm_models/test_npu_qwen3_coder_480b_a35b.py b/asian_ai/performance/SGLang/test/registered/ascend/llm_models/test_npu_qwen3_coder_480b_a35b.py new file mode 100644 index 0000000000000000000000000000000000000000..a4189c49781c021b70bd1b5ae1e33c1425f4ca9b --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/ascend/llm_models/test_npu_qwen3_coder_480b_a35b.py @@ -0,0 +1,42 @@ +import unittest + +from sglang.test.ascend.gsm8k_ascend_mixin import GSM8KAscendMixin +from sglang.test.ascend.test_ascend_utils import ( + QWEN3_CODER_480B_A35B_INSTRUCT_W8A8_QUAROT_WEIGHTS_PATH, +) +from sglang.test.ci.ci_register import register_npu_ci +from sglang.test.test_utils import CustomTestCase + +register_npu_ci( + est_time=400, + suite="nightly-16-npu-a3", + nightly=True, +) + + +class TestQwen3Coder480BA35B(GSM8KAscendMixin, CustomTestCase): + """Testcase: Verify that the inference accuracy of the Qwen3-Coder-480B-A35B-Instruct-w8a8-QuaRot model on the GSM8K dataset is no less than 0.94. + + [Test Category] Model + [Test Target] Qwen3-Coder-480B-A35B-Instruct-w8a8-QuaRot + """ + + model = QWEN3_CODER_480B_A35B_INSTRUCT_W8A8_QUAROT_WEIGHTS_PATH + accuracy = 0.94 + timeout_for_server_launch = 3000 + other_args = [ + "--trust-remote-code", + "--mem-fraction-static", + "0.8", + "--attention-backend", + "ascend", + "--disable-cuda-graph", + "--tp-size", + "16", + "--quantization", + "modelslim", + ] + + +if __name__ == "__main__": + unittest.main() diff --git a/asian_ai/performance/SGLang/test/registered/ascend/llm_models/test_npu_qwq_32b_w8a8.py b/asian_ai/performance/SGLang/test/registered/ascend/llm_models/test_npu_qwq_32b_w8a8.py new file mode 100644 index 0000000000000000000000000000000000000000..3fc60b48ca5ce8285da1d280b2e067e3256760d9 --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/ascend/llm_models/test_npu_qwq_32b_w8a8.py @@ -0,0 +1,37 @@ +import os +import unittest + +from sglang.test.ascend.gsm8k_ascend_mixin import GSM8KAscendMixin +from sglang.test.ascend.test_ascend_utils import QWQ_32B_W8A8_WEIGHTS_PATH +from sglang.test.ci.ci_register import register_npu_ci +from sglang.test.test_utils import CustomTestCase + +register_npu_ci(est_time=400, suite="nightly-2-npu-a3", nightly=True) + + +class TestQWQ32BW8A8(GSM8KAscendMixin, CustomTestCase): + """Testcase: Verify that the inference accuracy of the vllm-ascend/QWQ-32B-W8A8 model on the GSM8K dataset is no less than 0.59. + + [Test Category] Model + [Test Target] vllm-ascend/QWQ-32B-W8A8 + """ + + model = QWQ_32B_W8A8_WEIGHTS_PATH + accuracy = 0.59 + other_args = [ + "--trust-remote-code", + "--mem-fraction-static", + "0.8", + "--attention-backend", + "ascend", + "--disable-cuda-graph", + "--tp-size", + "2", + "--quantization", + "modelslim", + ] + os.environ["TRANSFORMERS_VERBOSITY"] = "error" + + +if __name__ == "__main__": + unittest.main() diff --git a/asian_ai/performance/SGLang/test/registered/ascend/llm_models/test_npu_smollm_1_7b.py b/asian_ai/performance/SGLang/test/registered/ascend/llm_models/test_npu_smollm_1_7b.py new file mode 100644 index 0000000000000000000000000000000000000000..9c7aa9fdce4352a15b0eae6e2e776d805c21ed8e --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/ascend/llm_models/test_npu_smollm_1_7b.py @@ -0,0 +1,33 @@ +import unittest + +from sglang.test.ascend.gsm8k_ascend_mixin import GSM8KAscendMixin +from sglang.test.ascend.test_ascend_utils import SMOLLM_1_7B_WEIGHTS_PATH +from sglang.test.ci.ci_register import register_npu_ci +from sglang.test.test_utils import CustomTestCase + +register_npu_ci(est_time=400, suite="full-1-npu-a3", nightly=True) + + +class TestSmolLM(GSM8KAscendMixin, CustomTestCase): + """Testcase: Verify that the inference accuracy of the HuggingFaceTB/SmolLM-1.7B model on the GSM8K dataset is no less than 0.05. + + [Test Category] Model + [Test Target] HuggingFaceTB/SmolLM-1.7B + """ + + model = SMOLLM_1_7B_WEIGHTS_PATH + accuracy = 0.05 + other_args = [ + "--trust-remote-code", + "--mem-fraction-static", + "0.8", + "--attention-backend", + "ascend", + "--disable-cuda-graph", + "--dtype", + "bfloat16", + ] + + +if __name__ == "__main__": + unittest.main() diff --git a/asian_ai/performance/SGLang/test/registered/ascend/llm_models/test_npu_stablelm_2_1_6b.py b/asian_ai/performance/SGLang/test/registered/ascend/llm_models/test_npu_stablelm_2_1_6b.py new file mode 100644 index 0000000000000000000000000000000000000000..89ffa145bb230ac088caf7dcbe93f3924fa1b4ac --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/ascend/llm_models/test_npu_stablelm_2_1_6b.py @@ -0,0 +1,34 @@ +import unittest + +from sglang.test.ascend.gsm8k_ascend_mixin import GSM8KAscendMixin +from sglang.test.ascend.test_ascend_utils import STABLELM_2_1_6B_WEIGHTS_PATH +from sglang.test.ci.ci_register import register_npu_ci +from sglang.test.test_utils import CustomTestCase + +register_npu_ci(est_time=400, suite="full-1-npu-a3", nightly=True) + + +class TestStablelm(GSM8KAscendMixin, CustomTestCase): + """Testcase: Verify that the inference accuracy of the stabilityai/stablelm-2-1_6b model on the GSM8K dataset is no less than 0.195. + + [Test Category] Model + [Test Target] stabilityai/stablelm-2-1_6b + """ + + model = STABLELM_2_1_6B_WEIGHTS_PATH + accuracy = 0.195 + other_args = [ + "--trust-remote-code", + "--mem-fraction-static", + "0.8", + "--attention-backend", + "ascend", + "--disable-cuda-graph", + "--tp-size", + 1, + "--enable-torch-compile", + ] + + +if __name__ == "__main__": + unittest.main() diff --git a/asian_ai/performance/SGLang/test/registered/ascend/llm_models/tool_chat_template_c4ai_command_r_v01.jinja b/asian_ai/performance/SGLang/test/registered/ascend/llm_models/tool_chat_template_c4ai_command_r_v01.jinja new file mode 100644 index 0000000000000000000000000000000000000000..347c3635551a9890713e465e9a2a72540beb9e35 --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/ascend/llm_models/tool_chat_template_c4ai_command_r_v01.jinja @@ -0,0 +1 @@ +{{ bos_token }}{% if messages[0]['role'] == 'system' %}{% set loop_messages = messages[1:] %}{% set system_message = messages[0]['content'] %}{% elif false == true %}{% set loop_messages = messages %}{% set system_message = 'You are Command-R, a brilliant, sophisticated, AI-assistant trained to assist human users by providing thorough responses. You are trained by Cohere.' %}{% else %}{% set loop_messages = messages %}{% set system_message = false %}{% endif %}{% if system_message != false %}{{ '<|START_OF_TURN_TOKEN|><|SYSTEM_TOKEN|>' + system_message + '<|END_OF_TURN_TOKEN|>' }}{% endif %}{% for message in loop_messages %}{% if (message['role'] == 'user') != (loop.index0 % 2 == 0) %}{{ raise_exception('Conversation roles must alternate user/assistant/user/assistant/...') }}{% endif %}{% set content = message['content'] %}{% if message['role'] == 'user' %}{{ '<|START_OF_TURN_TOKEN|><|USER_TOKEN|>' + content.strip() + '<|END_OF_TURN_TOKEN|>' }}{% elif message['role'] == 'assistant' %}{{ '<|START_OF_TURN_TOKEN|><|CHATBOT_TOKEN|>' + content.strip() + '<|END_OF_TURN_TOKEN|>' }}{% endif %}{% endfor %}{% if add_generation_prompt %}{{ '<|START_OF_TURN_TOKEN|><|CHATBOT_TOKEN|>' }}{% endif %} diff --git a/asian_ai/performance/SGLang/test/registered/ascend/performance/glm5_1/test_npu_glm5_1_w4a8_1p1d_32p_in64k_out1k_50ms_aime26.py b/asian_ai/performance/SGLang/test/registered/ascend/performance/glm5_1/test_npu_glm5_1_w4a8_1p1d_32p_in64k_out1k_50ms_aime26.py new file mode 100644 index 0000000000000000000000000000000000000000..59222a5d078bfd573330eb1de9e268b7fc3f6987 --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/ascend/performance/glm5_1/test_npu_glm5_1_w4a8_1p1d_32p_in64k_out1k_50ms_aime26.py @@ -0,0 +1,198 @@ +import unittest + +from sglang.test.ascend.e2e.test_npu_accuracy_utils import ( + TestNpuAccuracyMultiNodePdSepTestCaseBase, +) +from sglang.test.ascend.e2e.test_npu_multi_node_utils import NIC_NAME +from sglang.test.ascend.e2e.test_npu_performance_utils import ( + AISBENCHMARK_DATASET_DEFAULT, + BENCHMARK_TOOL_DEFAULT, + GLM_5_1_W4A8_MODEL_PATH, + TestNpuPerfMultiNodePdSepTestCaseBase, +) +from sglang.test.ci.ci_register import register_npu_ci + +register_npu_ci( + est_time=3600, + suite="", + nightly=True, + disabled="performance testcase", +) + +GLM_5_1_PD_SEP_PREFILL_ENVS = { + "SGLANG_SET_CPU_AFFINITY": "1", + "PYTORCH_NPU_ALLOC_CONF": "expandable_segments:True", + "STREAMS_PER_DEVICE": "32", + "SGLANG_DISAGGREGATION_BOOTSTRAP_TIMEOUT": "1200", + "SGLANG_DISAGGREGATION_WAITING_TIMEOUT": "1200", + "HCCL_BUFFSIZE": "1200", + "DEEPEP_NORMAL_LONG_SEQ_ROUND": "72", + "DEEPEP_NORMAL_LONG_SEQ_PER_ROUND_TOKENS": "1024", + "DEEPEP_NORMAL_COMBINE_ENABLE_LONG_SEQ": "1", + "DEEP_NORMAL_MODE_USE_INT8_QUANT": "1", + "TASK_QUEUE_ENABLE": "2", + "ENABLE_PROFILING": "0", + "HCCL_SOCKET_IFNAME": NIC_NAME, + "GLOO_SOCKET_IFNAME": NIC_NAME, +} + +GLM_5_1_PD_SEP_DECODE_ENVS = { + "SGLANG_SET_CPU_AFFINITY": "1", + "PYTORCH_NPU_ALLOC_CONF": "expandable_segments:True", + "STREAMS_PER_DEVICE": "32", + "SGLANG_DISAGGREGATION_BOOTSTRAP_TIMEOUT": "1200", + "SGLANG_DISAGGREGATION_WAITING_TIMEOUT": "1200", + "SGLANG_SPEC_ENABLE_OVERLAP_REFLOW": "1", + "SGLANG_ENABLE_OVERLAP_PLAN_STREAM": "1", + "SGLANG_ENABLE_SPEC_V2": "1", + "HCCL_BUFFSIZE": "200", + "SGLANG_DEEPEP_NUM_MAX_DISPATCH_TOKENS_PER_RANK": "16", + "TASK_QUEUE_ENABLE": "0", + "HCCL_SOCKET_IFNAME": NIC_NAME, + "GLOO_SOCKET_IFNAME": NIC_NAME, +} + +GLM_5_1_PD_SEP_PREFILL_ARGS = [ + "--disaggregation-mode", + "prefill", + "--tp-size", + 4, + "--nnodes", + 2, + "--mem-fraction-static", + 0.72, + "--attention-backend", + "ascend", + "--device", + "npu", + "--quantization", + "modelslim", + "--disaggregation-transfer-backend", + "ascend", + "--max-running-requests", + 16, + "--served-model-name", + "glm-5", + "--chunked-prefill-size", + 16384, + "--max-prefill-tokens", + 180000, + "--moe-a2a-backend", + "deepep", + "--deepep-mode", + "normal", + "--disable-shared-experts-fusion", + "--disable-cuda-graph", + "--dtype", + "bfloat16", + "--speculative-draft-model-quantization", + "unquant", + "--enable-nsa-prefill-context-parallel", + "--nsa-prefill-cp-mode", + "in-seq-split", + "--attn-cp-size", + 4, + "--enable-dp-lm-head", + "--moe-dense-tp", + 1, + "--pp-size", + 8, +] + +GLM_5_1_PD_SEP_DECODE_ARGS = [ + "--disaggregation-mode", + "decode", + "--tp-size", + 32, + "--nnodes", + 2, + "--dp-size", + 32, + "--enable-dp-attention", + "--ep-size", + 32, + "--mem-fraction-static", + 0.85, + "--max-running-requests", + 32, + "--attention-backend", + "ascend", + "--device", + "npu", + "--quantization", + "modelslim", + "--served-model-name", + "glm-5", + "--moe-a2a-backend", + "deepep", + "--deepep-mode", + "low_latency", + "--cuda-graph-bs", + 1, + 2, + 3, + "--disaggregation-transfer-backend", + "ascend", + "--watchdog-timeout", + 9000, + "--context-length", + 180000, + "--tokenizer-worker-num", + 16, + "--prefill-round-robin-balance", + "--disable-shared-experts-fusion", + "--dtype", + "bfloat16", + "--load-balance-method", + "round_robin", + "--speculative-draft-model-quantization", + "unquant", +] + +GLM_5_1_PD_SEP_MODEL_CONFIG = { + "model_path": GLM_5_1_W4A8_MODEL_PATH, + "prefill_args": GLM_5_1_PD_SEP_PREFILL_ARGS, + "decode_args": GLM_5_1_PD_SEP_DECODE_ARGS, + "prefill_envs": GLM_5_1_PD_SEP_PREFILL_ENVS, + "decode_envs": GLM_5_1_PD_SEP_DECODE_ENVS, + "router_args": ["--policy", "round_robin"], + "router_envs": {}, +} + + +class TestNPUGLM5_1_W4A8_PD_SEP_AIME2026(TestNpuAccuracyMultiNodePdSepTestCaseBase): + """Test NPU accuracy for GLM-5.1-w4a8 PD separation on AIME2026""" + + model_config = GLM_5_1_PD_SEP_MODEL_CONFIG + accuracy = 0.953 + datasets = ["aime26"] + eval_batch_size = 64 + generation_config = {"max_tokens": 65536, "temperature": 1.0} + + def test_npu_glm5_1_w4a8_pd_sep_aime2026(self): + """Run NPU accuracy test for GLM-5.1-w4a8 PD separation on AIME2026""" + self.run_accuracy() + + +class TestNPUGLM5_1_W4A8_PD_SEP_In3k5_Out1k5(TestNpuPerfMultiNodePdSepTestCaseBase): + """Test NPU performance for GLM-5.1-w4a8 PD separation 4 nodes in3k5 out1k5""" + + model_config = GLM_5_1_PD_SEP_MODEL_CONFIG + benchmark_tool = BENCHMARK_TOOL_DEFAULT + dataset_type = AISBENCHMARK_DATASET_DEFAULT + dataset_name = "random" + max_concurrency = 1 + num_prompts = 1 + input_len = 65536 + output_len = 1024 + random_range_ratio = 1 + tpot = 50 + output_token_throughput = 16 + + def test_npu_glm5_1_w4a8_pd_sep_in3k5_out1k5(self): + """Run NPU performance test for GLM-5.1-w4a8 PD separation""" + self.run_throughput() + + +if __name__ == "__main__": + unittest.main() diff --git a/asian_ai/performance/SGLang/test/registered/ascend/performance/kimi_k2_6/test_npu_kimi_k2_6_w4a8_16p_in64k_out1k_100ms_aime25.py b/asian_ai/performance/SGLang/test/registered/ascend/performance/kimi_k2_6/test_npu_kimi_k2_6_w4a8_16p_in64k_out1k_100ms_aime25.py new file mode 100644 index 0000000000000000000000000000000000000000..6e16a6418fabef11c021ab22cc0163983e867d27 --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/ascend/performance/kimi_k2_6/test_npu_kimi_k2_6_w4a8_16p_in64k_out1k_100ms_aime25.py @@ -0,0 +1,125 @@ +import unittest + +from sglang.test.ascend.e2e.test_npu_accuracy_utils import ( + TestNpuAccuracyMultiNodePdMixTestCaseBase, +) +from sglang.test.ascend.e2e.test_npu_multi_node_utils import NIC_NAME +from sglang.test.ascend.e2e.test_npu_performance_utils import ( + AISBENCHMARK_DATASET_DEFAULT, + BENCHMARK_TOOL_DEFAULT, + KIMI_K2_6_EAGLE3_MODEL_PATH, + KIMI_K2_6_W4A8_MODEL_PATH, + TestNpuPerfMultiNodePdMixTestCaseBase, +) +from sglang.test.ci.ci_register import register_npu_ci + +register_npu_ci( + est_time=1800, + suite="nightly-8-npu-a3", + nightly=True, + disabled="Currently it is executed by the npu performance workflow.", +) + +ENVS = { + "PYTORCH_NPU_ALLOC_CONF": "expandable_segments:True", + "SGLANG_SET_CPU_AFFINITY": "1", + "STREAMS_PER_DEVICE": "32", + "DEEP_NORMAL_MODE_USE_INT8_QUANT": "1", + "SGLANG_DEEPEP_NUM_MAX_DISPATCH_TOKENS_PER_RANK": "64", + "HCCL_BUFFSIZE": "4400", + "SGLANG_ENABLE_SPEC_V2": "1", + "SGLANG_ENABLE_OVERLAP_PLAN_STREAM": "1", + "HCCL_SOCKET_IFNAME": NIC_NAME, + "GLOO_SOCKET_IFNAME": NIC_NAME, +} + +OTHER_ARGS = [ + "--trust-remote-code", + "--attention-backend", + "ascend", + "--device", + "npu", + "--quantization", + "modelslim", + "--dtype", + "bfloat16", + "--tp-size", + 32, + "--nnodes", + 2, + "--mem-fraction-static", + 0.55, + "--max-running-requests", + 32, + "--chunked-prefill-size", + 262144, + "--context-length", + 75000, + "--enable-multimodal", + "--mm-attention-backend", + "ascend_attn", + "--sampling-backend", + "ascend", + "--enable-dp-attention", + "--dp-size", + 32, + "--moe-a2a-backend", + "deepep", + "--deepep-mode", + "auto", + "--cuda-graph-bs", + 1, + "--disable-radix-cache", + "--speculative-algorithm", + "EAGLE3", + "--speculative-draft-model-path", + KIMI_K2_6_EAGLE3_MODEL_PATH, + "--speculative-num-steps", + 3, + "--speculative-eagle-topk", + 1, + "--speculative-num-draft-tokens", + 4, + "--speculative-draft-model-quantization", + "unquant", +] + +MODEL_CONFIG = { + "model_path": KIMI_K2_6_W4A8_MODEL_PATH, + "other_args": OTHER_ARGS, + "node_envs": ENVS, +} + + +class TestNPUKimiK2_6_W4A8_16P_AIME2025(TestNpuAccuracyMultiNodePdMixTestCaseBase): + + model_config = MODEL_CONFIG + accuracy = 0.961 + datasets = ["aime25"] + few_shot_num = 0 + eval_batch_size = 64 + generation_config = {"max_tokens": 65536, "temperature": 1.0} + + def test_aime2025(self): + self.run_accuracy() + + +class TestNPUKimiK2_6_W4A8_16P_In64k_Out1k_100ms(TestNpuPerfMultiNodePdMixTestCaseBase): + benchmark_tool = BENCHMARK_TOOL_DEFAULT + dataset_type = AISBENCHMARK_DATASET_DEFAULT + model_config = MODEL_CONFIG + dataset_name = "random" + max_concurrency = 32 + num_prompts = 32 + input_len = 64000 + output_len = 1000 + random_range_ratio = 1 + tpot = 100 + output_token_throughput = 160 + + def test_npu_kimi_k2_6_w4a8_16p_in64k_out1k_100ms(self): + self.run_throughput() + + +if __name__ == "__main__": + unittest.main() diff --git a/asian_ai/performance/SGLang/test/registered/ascend/performance/minimax_m2_5/test_npu_minimax_m2_5_w8a8_4p_in64k_out1k_prefix90_50ms_gpqa.py b/asian_ai/performance/SGLang/test/registered/ascend/performance/minimax_m2_5/test_npu_minimax_m2_5_w8a8_4p_in64k_out1k_prefix90_50ms_gpqa.py new file mode 100644 index 0000000000000000000000000000000000000000..51ab5906fc97753897c7360a03e2bee327b2c822 --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/ascend/performance/minimax_m2_5/test_npu_minimax_m2_5_w8a8_4p_in64k_out1k_prefix90_50ms_gpqa.py @@ -0,0 +1,132 @@ +import os +import unittest + +from sglang.test.ascend.e2e.test_npu_accuracy_utils import ( + TestNpuAccuracyTestCaseBase, +) +from sglang.test.ascend.e2e.test_npu_performance_utils import ( + BENCHMARK_TOOL_DEFAULT, + MINIMAX_M2_5_EAGLE3_MODEL_PATH, + MINIMAX_M2_5_W8A8_MODEL_PATH, + TestNpuPerformanceTestCaseBase, +) +from sglang.test.ci.ci_register import register_npu_ci + +register_npu_ci( + est_time=3600, + suite="npu-performance", + nightly=True, +) + +MINIMAX_M2_5_W8A8_4P_IN64K_OUT1K_PREFIX90_ENVS = { + "PYTORCH_NPU_ALLOC_CONF": "expandable_segments:True", + "STREAMS_PER_DEVICE": "32", + "HCCL_SOCKET_IFNAME": "lo", + "GLOO_SOCKET_IFNAME": "lo", + "TASK_QUEUE_ENABLE": "1", + "ASCEND_USE_FIA": "1", + "SGLANG_SET_CPU_AFFINITY": "1", + "SGLANG_ENABLE_SPEC_V2": "1", + "SGLANG_ENABLE_OVERLAP_PLAN_STREAM": "1", + "SGLANG_NPU_FUSED_MOE_MODE": "2", + "SGLANG_DEEPEP_NUM_MAX_DISPATCH_TOKENS_PER_RANK": "140000", + "DEEP_NORMAL_MODE_USE_INT8_QUANT": "1", + "HCCL_BUFFSIZE": "1024", + "SGLANG_EXTERNAL_MODEL_PACKAGE": "custom_eagle3", + "PYTHONPATH": f"{MINIMAX_M2_5_EAGLE3_MODEL_PATH}:{os.environ.get('PYTHONPATH', '')}", +} + +MINIMAX_M2_5_W8A8_4P_IN64K_OUT1K_PREFIX90_OTHER_ARGS = [ + "--tp-size", + 8, + "--mem-fraction-static", + 0.63, + "--max-running-requests", + 26, + "--reasoning-parser", + "minimax-append-think", + "--tool-call-parser", + "minimax-m2", + "--enable-prefill-delayer", + "--prefill-max-requests", + 10, + "--chunked-prefill-size", + 67072, + "--max-prefill-token", + 67000, + "--cuda-graph-bs", + 2, + 4, + 8, + 12, + 16, + 18, + 20, + 22, + 24, + 26, + "--moe-a2a-backend", + "ascend_fuseep", + "--deepep-mode", + "auto", + "--quantization", + "modelslim", + "--speculative-algorithm", + "EAGLE3", + "--speculative-draft-model-path", + MINIMAX_M2_5_EAGLE3_MODEL_PATH, + "--speculative-num-steps", + 3, + "--speculative-eagle-topk", + 1, + "--speculative-num-draft-tokens", + 4, + "--speculative-draft-model-quantization", + "unquant", + "--dtype", + "bfloat16", + "--trust-remote-code", +] + + +class TestNPUMiniMaxM2_5W8A8_4P_In64k_Out1k_Prefix90_50ms( + TestNpuPerformanceTestCaseBase +): + """MiniMax-M2.5-w8a8 4p (4 cards) 64k input 1k output with 90% prefix cache performance test""" + + benchmark_tool = BENCHMARK_TOOL_DEFAULT + model = MINIMAX_M2_5_W8A8_MODEL_PATH + other_args = MINIMAX_M2_5_W8A8_4P_IN64K_OUT1K_PREFIX90_OTHER_ARGS + envs = MINIMAX_M2_5_W8A8_4P_IN64K_OUT1K_PREFIX90_ENVS + dataset_name = "generated-shared-prefix" + max_concurrency = 26 + num_prompts = 104 + input_len = 65536 + output_len = 1024 + random_range_ratio = 1 + repeat_rate = 0.9 + tpot = 50 + output_token_throughput = 390.5839 + request_rate = float("inf") + + def test_npu_minimax_m2_5_w8a8_4p_in64k_out1k_prefix90_50ms(self): + """Run MiniMax-M2.5-w8a8 4p 64k/1k prefix90 performance test""" + self.run_throughput() + + +class TestNPUMiniMaxM2_5_W8A8_4P_In3k5_Out1k5_GPQA(TestNpuAccuracyTestCaseBase): + model = MINIMAX_M2_5_W8A8_MODEL_PATH + other_args = MINIMAX_M2_5_W8A8_4P_IN64K_OUT1K_PREFIX90_OTHER_ARGS + envs = MINIMAX_M2_5_W8A8_4P_IN64K_OUT1K_PREFIX90_ENVS + accuracy = 0.852 + datasets = ["gpqa_diamond"] + few_shot_num = 0 + generation_config = {"max_tokens": 65536, "temperature": 1.0} + max_concurrency = 64 + + def test_accuracy(self): + self.run_accuracy() + + +if __name__ == "__main__": + unittest.main() diff --git a/asian_ai/performance/SGLang/test/registered/ascend/performance/minimax_m2_5/test_npu_minimax_m2_5_w8a8_8p_in3k5_out1k5_50ms_gpqa.py b/asian_ai/performance/SGLang/test/registered/ascend/performance/minimax_m2_5/test_npu_minimax_m2_5_w8a8_8p_in3k5_out1k5_50ms_gpqa.py new file mode 100644 index 0000000000000000000000000000000000000000..b351962d0b4355e5dcf7c7b2cee3870977df9ee6 --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/ascend/performance/minimax_m2_5/test_npu_minimax_m2_5_w8a8_8p_in3k5_out1k5_50ms_gpqa.py @@ -0,0 +1,132 @@ +import os +import unittest + +from sglang.test.ascend.e2e.test_npu_accuracy_utils import ( + TestNpuAccuracyTestCaseBase, +) +from sglang.test.ascend.e2e.test_npu_performance_utils import ( + AISBENCHMARK_DATASET_DEFAULT, + BENCHMARK_TOOL_DEFAULT, + MINIMAX_M2_5_EAGLE3_MODEL_PATH, + MINIMAX_M2_5_W8A8_MODEL_PATH, + TestNpuPerformanceTestCaseBase, +) +from sglang.test.ci.ci_register import register_npu_ci + +register_npu_ci( + est_time=3600, + suite="full-16-npu-a3", + nightly=True, + disabled="performance testcase", +) + +MINIMAX_M2_5_HIGH_THROUGHPUT_ENVS = { + "PYTORCH_NPU_ALLOC_CONF": "expandable_segments:True", + "STREAMS_PER_DEVICE": "32", + "HCCL_SOCKET_IFNAME": "lo", + "GLOO_SOCKET_IFNAME": "lo", + "TASK_QUEUE_ENABLE": "1", + "HCCL_BUFFSIZE": "1024", + "ASCEND_USE_FIA": "1", + "SGLANG_SET_CPU_AFFINITY": "1", + "SGLANG_ENABLE_SPEC_V2": "1", + "SGLANG_ENABLE_OVERLAP_PLAN_STREAM": "1", + "SGLANG_NPU_FUSED_MOE_MODE": "2", + "SGLANG_DEEPEP_NUM_MAX_DISPATCH_TOKENS_PER_RANK": "204800", + "PYTHONPATH": f"{MINIMAX_M2_5_EAGLE3_MODEL_PATH}:{os.environ.get('PYTHONPATH', '')}", + "SGLANG_EXTERNAL_MODEL_PACKAGE": "custom_eagle3", +} + +MINIMAX_M2_5_HIGH_THROUGHPUT_OTHER_ARGS = [ + "--tp-size", + 16, + "--enable-dp-attention", + "--dp-size", + 16, + "--mem-fraction-static", + 0.75, + "--max-running-requests", + 320, + "--disable-radix-cache", + "--reasoning-parser", + "minimax-append-think", + "--tool-call-parser", + "minimax-m2", + "--prefill-delayer-max-delay-passes", + 500, + "--enable-prefill-delayer", + "--chunked-prefill-size", + -1, + "--max-prefill-token", + 8192, + "--cuda-graph-bs", + 1, + 2, + 4, + 8, + 12, + 16, + 20, + "--moe-a2a-backend", + "ascend_fuseep", + "--deepep-mode", + "auto", + "--quantization", + "modelslim", + "--speculative-algorithm", + "EAGLE3", + "--speculative-draft-model-path", + MINIMAX_M2_5_EAGLE3_MODEL_PATH, + "--speculative-num-steps", + 3, + "--speculative-eagle-topk", + 1, + "--speculative-num-draft-tokens", + 4, + "--speculative-draft-model-quantization", + "unquant", + "--dtype", + "bfloat16", +] + + +class TestNPUMiniMaxM2_5_W8A8_8P_In3k5_Out1k5_HighThroughput( + TestNpuPerformanceTestCaseBase +): + """Test NPU performance for MiniMax-M2.5-w8a8 8p single node high throughput in3k5 out1k5""" + + benchmark_tool = BENCHMARK_TOOL_DEFAULT + dataset_type = AISBENCHMARK_DATASET_DEFAULT + model = MINIMAX_M2_5_W8A8_MODEL_PATH + other_args = MINIMAX_M2_5_HIGH_THROUGHPUT_OTHER_ARGS + envs = MINIMAX_M2_5_HIGH_THROUGHPUT_ENVS + dataset_name = "random" + max_concurrency = 320 + num_prompts = 1280 + input_len = 3500 + output_len = 1500 + random_range_ratio = 1 + tpot = 50 + output_token_throughput = 5717.58 + + def test_npu_minimax_m2_5_w8a8_8p_in3k5_out1k5_high_throughput(self): + """Run NPU performance test for MiniMax-M2.5-w8a8 high throughput""" + self.run_throughput() + + +class TestNPUMiniMaxM2_5_W8A8_8P_In3k5_Out1k5_GPQA(TestNpuAccuracyTestCaseBase): + model = MINIMAX_M2_5_W8A8_MODEL_PATH + envs = MINIMAX_M2_5_HIGH_THROUGHPUT_ENVS + other_args = MINIMAX_M2_5_HIGH_THROUGHPUT_OTHER_ARGS + accuracy = 0.852 + datasets = ["gpqa_diamond"] + few_shot_num = 0 + generation_config = {"max_tokens": 65536, "temperature": 1.0} + max_concurrency = 64 + + def test_accuracy(self): + self.run_accuracy() + + +if __name__ == "__main__": + unittest.main() diff --git a/asian_ai/performance/SGLang/test/registered/ascend/performance/qwen3-8b/test_npu_qwen3_8b_w8a8_1p_in3k5_out1k5_50ms_gpqa.py b/asian_ai/performance/SGLang/test/registered/ascend/performance/qwen3-8b/test_npu_qwen3_8b_w8a8_1p_in3k5_out1k5_50ms_gpqa.py new file mode 100644 index 0000000000000000000000000000000000000000..26b1a905732d060e50a48215e3d2f36d3eb522f0 --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/ascend/performance/qwen3-8b/test_npu_qwen3_8b_w8a8_1p_in3k5_out1k5_50ms_gpqa.py @@ -0,0 +1,122 @@ +import unittest + +from sglang.test.ascend.e2e.test_npu_accuracy_utils import ( + TestNpuAccuracyTestCaseBase, +) +from sglang.test.ascend.e2e.test_npu_performance_utils import ( + AISBENCHMARK_DATASET_DEFAULT, + BENCHMARK_TOOL_DEFAULT, + QWEN3_8B_EAGLE_MODEL_PATH, + QWEN3_8B_W8A8_MODEL_PATH, + TestNpuPerformanceTestCaseBase, +) +from sglang.test.ci.ci_register import register_npu_ci + +register_npu_ci( + est_time=3600, + suite="", + nightly=True, + disabled="performance testcase", +) + +QWEN3_8B_ENVS = { + "SGLANG_DISAGGREGATION_BOOTSTRAP_TIMEOUT": "600", + "PYTORCH_NPU_ALLOC_CONF": "expandable_segments:True", + "HCCL_SOCKET_IFNAME": "lo", + "GLOO_SOCKET_IFNAME": "lo", + "HCCL_OP_EXPANSION_MODE": "AIV", + "SGLANG_ENABLE_OVERLAP_PLAN_STREAM": "1", + "SGLANG_ENABLE_SPEC_V2": "1", + "SGLANG_SCHEDULER_DECREASE_PREFILL_IDLE": "1", + "SGLANG_PREFILL_DELAYER_MAX_DELAY_PASSES": "50", +} + +QWEN3_8B_OTHER_ARGS = [ + "--trust-remote-code", + "--nnodes", + "1", + "--node-rank", + "0", + "--attention-backend", + "ascend", + "--device", + "npu", + "--quantization", + "modelslim", + "--max-running-requests", + 70, + "--max-prefill-tokens", + 16384, + "--disable-radix-cache", + "--chunked-prefill-size", + 16384, + "--tp-size", + 1, + "--mem-fraction-static", + 0.85, + "--cuda-graph-bs", + 8, + 12, + 24, + 36, + 48, + 51, + 55, + 60, + 63, + 64, + 66, + 68, + 70, + "--dtype", + "bfloat16", + "--speculative-draft-model-quantization", + "unquant", + "--speculative-algorithm", + "EAGLE3", + "--speculative-draft-model-path", + QWEN3_8B_EAGLE_MODEL_PATH, + "--speculative-num-steps", + 3, + "--speculative-eagle-topk", + 1, + "--speculative-num-draft-tokens", + 4, +] + + +class TestQwen8B(TestNpuPerformanceTestCaseBase): + benchmark_tool = BENCHMARK_TOOL_DEFAULT + dataset_type = AISBENCHMARK_DATASET_DEFAULT + model = QWEN3_8B_W8A8_MODEL_PATH + other_args = QWEN3_8B_OTHER_ARGS + envs = QWEN3_8B_ENVS + dataset_name = "random" + max_concurrency = 64 + num_prompts = 256 + input_len = 3500 + output_len = 1500 + random_range_ratio = 1 + tpot = 37 + output_token_throughput = 1586 + + def test_qwen3_8b(self): + self.run_throughput() + + +class TestQwen8B_gpqa(TestNpuAccuracyTestCaseBase): + model = QWEN3_8B_W8A8_MODEL_PATH + envs = QWEN3_8B_ENVS + other_args = QWEN3_8B_OTHER_ARGS + accuracy = 0.4444 + datasets = ["gpqa_diamond"] + few_shot_num = 0 + eval_batch_size = 64 + generation_config = {"max_tokens": 40000, "temperature": 1.0} + + def test_accuracy(self): + self.run_accuracy() + + +if __name__ == "__main__": + unittest.main() diff --git a/asian_ai/performance/SGLang/test/registered/ascend/performance/qwen3-8b/test_npu_qwen3_8b_w8a8_1p_in6k_out1k5_bs16_gpqa.py b/asian_ai/performance/SGLang/test/registered/ascend/performance/qwen3-8b/test_npu_qwen3_8b_w8a8_1p_in6k_out1k5_bs16_gpqa.py new file mode 100644 index 0000000000000000000000000000000000000000..a158aaa09cbfc2c983b7449d7c84e2d13c037e3b --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/ascend/performance/qwen3-8b/test_npu_qwen3_8b_w8a8_1p_in6k_out1k5_bs16_gpqa.py @@ -0,0 +1,108 @@ +import unittest + +from sglang.test.ascend.e2e.test_npu_accuracy_utils import ( + TestNpuAccuracyTestCaseBase, +) +from sglang.test.ascend.e2e.test_npu_performance_utils import ( + QWEN3_8B_EAGLE_MODEL_PATH, + QWEN3_8B_W8A8_MODEL_PATH, + TestNpuPerformanceTestCaseBase, +) +from sglang.test.ci.ci_register import register_npu_ci + +register_npu_ci( + est_time=3600, + suite="", + nightly=True, + disabled="performance testcase", +) + +QWEN3_8B_ENVS = { + "SGLANG_DISAGGREGATION_BOOTSTRAP_TIMEOUT": "600", + "PYTORCH_NPU_ALLOC_CONF": "expandable_segments:True", + "HCCL_SOCKET_IFNAME": "lo", + "GLOO_SOCKET_IFNAME": "lo", + "HCCL_OP_EXPANSION_MODE": "AIV", + "SGLANG_ENABLE_OVERLAP_PLAN_STREAM": "1", + "SGLANG_ENABLE_SPEC_V2": "1", +} + +QWEN3_8B_OTHER_ARGS = [ + "--trust-remote-code", + "--nnodes", + "1", + "--node-rank", + "0", + "--attention-backend", + "ascend", + "--device", + "npu", + "--quantization", + "modelslim", + "--max-running-requests", + 16, + "--max-prefill-tokens", + 16384, + "--disable-radix-cache", + "--chunked-prefill-size", + -1, + "--tp-size", + 2, + "--mem-fraction-static", + 0.894, + "--cuda-graph-bs", + 1, + 5, + 15, + 16, + "--dtype", + "bfloat16", + "--speculative-draft-model-quantization", + "unquant", + "--speculative-algorithm", + "EAGLE3", + "--speculative-draft-model-path", + QWEN3_8B_EAGLE_MODEL_PATH, + "--speculative-num-steps", + 4, + "--speculative-eagle-topk", + 1, + "--speculative-num-draft-tokens", + 5, +] + + +class TestQwen8B(TestNpuPerformanceTestCaseBase): + max_attempts = 5 + model = QWEN3_8B_W8A8_MODEL_PATH + other_args = QWEN3_8B_OTHER_ARGS + envs = QWEN3_8B_ENVS + dataset_name = "random" + max_concurrency = 16 + num_prompts = 16 + input_len = 6144 + output_len = 1500 + random_range_ratio = 1 + tpot = 11.79 + output_token_throughput = 930 + + def test_qwen3_8b(self): + self.run_throughput() + + +class TestQwen8B_gpqa(TestNpuAccuracyTestCaseBase): + model = QWEN3_8B_W8A8_MODEL_PATH + envs = QWEN3_8B_ENVS + other_args = QWEN3_8B_OTHER_ARGS + accuracy = 0.4444 + datasets = ["gpqa_diamond"] + few_shot_num = 0 + generation_config = {"max_tokens": 32768, "temperature": 1.0} + eval_batch_size = 16 + + def test_accuracy(self): + self.run_accuracy() + + +if __name__ == "__main__": + unittest.main() diff --git a/asian_ai/performance/SGLang/test/registered/ascend/performance/qwen3_30b_a3b/test_npu_qwen3_30b_w8a8_1p_in3k5_out1k5_50ms_aime25.py b/asian_ai/performance/SGLang/test/registered/ascend/performance/qwen3_30b_a3b/test_npu_qwen3_30b_w8a8_1p_in3k5_out1k5_50ms_aime25.py new file mode 100644 index 0000000000000000000000000000000000000000..68e8a722632be3237830c7a94759d8f1bdc254be --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/ascend/performance/qwen3_30b_a3b/test_npu_qwen3_30b_w8a8_1p_in3k5_out1k5_50ms_aime25.py @@ -0,0 +1,127 @@ +import unittest + +from sglang.test.ascend.e2e.test_npu_accuracy_utils import ( + TestNpuAccuracyTestCaseBase, +) +from sglang.test.ascend.e2e.test_npu_performance_utils import ( + AISBENCHMARK_DATASET_DEFAULT, + BENCHMARK_TOOL_DEFAULT, + QWEN3_30B_A3B_W8A8_VLLM_MODEL_PATH, + QWEN3_A3B_EAGLE_MODEL_PATH, + TestNpuPerformanceTestCaseBase, +) +from sglang.test.ci.ci_register import register_npu_ci + +register_npu_ci( + est_time=3600, + suite="", + nightly=True, + disabled="performance testcase", +) + +QWEN3_30B_A3B_ENVS = { + "ASCEND_LAUNCH_BLOCKING": "0", + "SGLANG_DISAGGREGATION_BOOTSTRAP_TIMEOUT": "600", + "PYTORCH_NPU_ALLOC_CONF": "expandable_segments:True", + "HCCL_SOCKET_IFNAME": "lo", + "GLOO_SOCKET_IFNAME": "lo", + "HCCL_OP_EXPANSION_MODE": "AIV", + "SGLANG_ENABLE_OVERLAP_PLAN_STREAM": "1", + "SGLANG_ENABLE_SPEC_V2": "1", + "SGLANG_SCHEDULER_DECREASE_PREFILL_IDLE": "1", + "SGLANG_PREFILL_DELAYER_MAX_DELAY_PASSES": "200", + "HCCL_BUFFSIZE": "400", +} + +QWEN3_30B_A3B_OTHER_ARGS = [ + "--trust-remote-code", + "--nnodes", + "1", + "--node-rank", + "0", + "--attention-backend", + "ascend", + "--device", + "npu", + "--quantization", + "modelslim", + "--max-running-requests", + 162, + "--disable-radix-cache", + "--speculative-draft-model-quantization", + "unquant", + "--chunked-prefill-size", + -1, + "--max-prefill-tokens", + 35000, + "--speculative-algorithm", + "EAGLE3", + "--speculative-draft-model-path", + QWEN3_A3B_EAGLE_MODEL_PATH, + "--speculative-num-steps", + 3, + "--speculative-eagle-topk", + 1, + "--speculative-num-draft-tokens", + 4, + "--tp-size", + 2, + "--mem-fraction-static", + 0.87, + "--cuda-graph-bs", + 1, + 5, + 15, + 40, + 70, + 100, + 120, + 130, + 140, + 146, + 150, + 154, + 156, + 158, + 160, + 162, + "--dtype", + "bfloat16", +] + + +class TestQwen30B(TestNpuPerformanceTestCaseBase): + benchmark_tool = BENCHMARK_TOOL_DEFAULT + dataset_type = AISBENCHMARK_DATASET_DEFAULT + model = QWEN3_30B_A3B_W8A8_VLLM_MODEL_PATH + other_args = QWEN3_30B_A3B_OTHER_ARGS + envs = QWEN3_30B_A3B_ENVS + dataset_name = "random" + max_concurrency = 160 + num_prompts = int(max_concurrency) * 4 + input_len = 3500 + output_len = 1500 + random_range_ratio = 1 + tpot = 50 + output_token_throughput = 3200 + + def test_qwen3_30b(self): + self.run_throughput() + + +class TestQwen30B_A3B_aime25(TestNpuAccuracyTestCaseBase): + model = QWEN3_30B_A3B_W8A8_VLLM_MODEL_PATH + envs = QWEN3_30B_A3B_ENVS + other_args = QWEN3_30B_A3B_OTHER_ARGS + accuracy = 0.613 + datasets = ["aime25"] + few_shot_num = 0 + generation_config = {"max_tokens": 32768, "temperature": 1.0} + eval_batch_size = 16 + + def test_accuracy(self): + self.run_accuracy() + + +if __name__ == "__main__": + unittest.main() diff --git a/asian_ai/performance/SGLang/test/registered/ascend/performance/qwen3_32b/test_npu_qwen3_32b_bf16_8p_in18k_out4k_6ms.py b/asian_ai/performance/SGLang/test/registered/ascend/performance/qwen3_32b/test_npu_qwen3_32b_bf16_8p_in18k_out4k_6ms.py new file mode 100644 index 0000000000000000000000000000000000000000..9f1caf477866a7a1002f49d8d21b96fb98b6ebce --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/ascend/performance/qwen3_32b/test_npu_qwen3_32b_bf16_8p_in18k_out4k_6ms.py @@ -0,0 +1,91 @@ +import unittest + +from sglang.test.ascend.e2e.test_npu_performance_utils import ( + AISBENCHMARK_DATASET_DEFAULT, + BENCHMARK_TOOL_DEFAULT, + QWEN3_32B_EAGLE_MODEL_PATH, + QWEN3_32B_MODEL_PATH, + TestNpuPerformanceTestCaseBase, +) +from sglang.test.ci.ci_register import register_npu_ci + +register_npu_ci( + est_time=3600, + suite="", + nightly=True, + disabled="performance testcase", +) + +QWEN3_32B_ENVS = { + "SGLANG_DISAGGREGATION_BOOTSTRAP_TIMEOUT": "600", + "PYTORCH_NPU_ALLOC_CONF": "expandable_segments:True", + "HCCL_SOCKET_IFNAME": "lo", + "GLOO_SOCKET_IFNAME": "lo", + "HCCL_OP_EXPANSION_MODE": "AIV", + "SGLANG_ENABLE_OVERLAP_PLAN_STREAM": "1", + "SGLANG_ENABLE_SPEC_V2": "1", + "SGLANG_SCHEDULER_DECREASE_PREFILL_IDLE": "1", + "SGLANG_PREFILL_DELAYER_MAX_DELAY_PASSES": "200", +} + +QWEN3_32B_OTHER_ARGS = [ + "--trust-remote-code", + "--nnodes", + "1", + "--node-rank", + "0", + "--attention-backend", + "ascend", + "--device", + "npu", + "--max-running-requests", + 1, + "--disable-radix-cache", + "--speculative-draft-model-quantization", + "unquant", + "--chunked-prefill-size", + -1, + "--max-prefill-tokens", + 65536, + "--speculative-algorithm", + "EAGLE3", + "--speculative-draft-model-path", + QWEN3_32B_EAGLE_MODEL_PATH, + "--speculative-num-steps", + 4, + "--speculative-eagle-topk", + 1, + "--speculative-num-draft-tokens", + 5, + "--tp-size", + 16, + "--mem-fraction-static", + 0.72, + "--cuda-graph-bs", + 1, + "--dtype", + "bfloat16", +] + + +class TestQwen32B(TestNpuPerformanceTestCaseBase): + benchmark_tool = BENCHMARK_TOOL_DEFAULT + aisbench_dataset_type = AISBENCHMARK_DATASET_DEFAULT + model = QWEN3_32B_MODEL_PATH + other_args = QWEN3_32B_OTHER_ARGS + envs = QWEN3_32B_ENVS + dataset_name = "random" + max_concurrency = 1 + num_prompts = 1 + input_len = 18000 + output_len = 4000 + random_range_ratio = 1 + tpot = 6 + output_token_throughput = 171 + + def test_qwen3_32b(self): + self.run_throughput() + + +if __name__ == "__main__": + unittest.main() diff --git a/asian_ai/performance/SGLang/test/registered/ascend/performance/qwen3_32b/test_npu_qwen3_32b_w8a8_2p_in3k5_out1k5_50ms_a2.py b/asian_ai/performance/SGLang/test/registered/ascend/performance/qwen3_32b/test_npu_qwen3_32b_w8a8_2p_in3k5_out1k5_50ms_a2.py new file mode 100644 index 0000000000000000000000000000000000000000..0b84c1bdea40c9c9a9c95997634f8b746f34ea14 --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/ascend/performance/qwen3_32b/test_npu_qwen3_32b_w8a8_2p_in3k5_out1k5_50ms_a2.py @@ -0,0 +1,135 @@ +import unittest + +from sglang.test.ascend.e2e.test_npu_accuracy_utils import ( + TestNpuAccuracyTestCaseBase, +) +from sglang.test.ascend.e2e.test_npu_performance_utils import ( + AISBENCHMARK_DATASET_DEFAULT, + DEFAULT_URL_FOR_TEST, + QWEN3_32B_EAGLE_MODEL_PATH, + QWEN3_32B_W8A8_MODEL_PATH, + TestNpuPerformanceTestCaseBase, +) +from sglang.test.ci.ci_register import register_npu_ci + +register_npu_ci( + est_time=3600, + suite="", + nightly=True, + disabled="performance testcase", +) + +QWEN3_32B_ENVS = { + "SGLANG_DISAGGREGATION_BOOTSTRAP_TIMEOUT": "600", + "PYTORCH_NPU_ALLOC_CONF": "expandable_segments:True", + "HCCL_SOCKET_IFNAME": "lo", + "GLOO_SOCKET_IFNAME": "lo", + "HCCL_OP_EXPANSION_MODE": "AIV", + "SGLANG_ENABLE_OVERLAP_PLAN_STREAM": "1", + "SGLANG_ENABLE_SPEC_V2": "1", + "SGLANG_SCHEDULER_DECREASE_PREFILL_IDLE": "1", + "SGLANG_PREFILL_DELAYER_MAX_DELAY_PASSES": "100", + "SGLANG_NPU_USE_DEEPGEMM": "1", +} + +QWEN3_32B_OTHER_ARGS = [ + "--trust-remote-code", + "--nnodes", + "1", + "--node-rank", + "0", + "--attention-backend", + "ascend", + "--device", + "npu", + "--quantization", + "modelslim", + "--max-running-requests", + 101, + "--disable-radix-cache", + "--speculative-draft-model-quantization", + "unquant", + "--chunked-prefill-size", + -1, + "--max-prefill-tokens", + 35000, + "--speculative-algorithm", + "EAGLE3", + "--speculative-draft-model-path", + QWEN3_32B_EAGLE_MODEL_PATH, + "--speculative-num-steps", + 3, + "--speculative-eagle-topk", + 1, + "--speculative-num-draft-tokens", + 4, + "--tp-size", + 4, + "--mem-fraction-static", + 0.845, + "--cuda-graph-bs", + 16, + 32, + 64, + 72, + 88, + 90, + 92, + 94, + 96, + 97, + 98, + 99, + 100, + 101, + "--dtype", + "bfloat16", +] + + +class TestQwen32B_GPQA(TestNpuAccuracyTestCaseBase): + """Test NPU accuracy for Qwen3-32B-W8A8 on qpqa""" + + model = QWEN3_32B_W8A8_MODEL_PATH + other_args = QWEN3_32B_OTHER_ARGS + envs = QWEN3_32B_ENVS + accuracy = 0.516 + datasets = ["gpqa_diamond"] + few_shot_num = 0 + eval_batch_size = 64 + generation_config = {"max_tokens": 40000, "temperature": 1.0} + + @classmethod + def tearDownClass(cls): + pass + + def test_qwen3_32b_qpqa(self): + """Run NPU accuracy test for Qwen3-32B-W8A8 on qpqa""" + self.run_accuracy() + + +class TestQwen32B(TestNpuPerformanceTestCaseBase): + base_url = DEFAULT_URL_FOR_TEST + aisbench_dataset_type = AISBENCHMARK_DATASET_DEFAULT + model = QWEN3_32B_W8A8_MODEL_PATH + other_args = QWEN3_32B_OTHER_ARGS + envs = QWEN3_32B_ENVS + dataset_name = "random" + max_concurrency = 100 + num_prompts = 400 + input_len = 3584 + output_len = 1536 + random_range_ratio = 1 + tpot = 50 + output_token_throughput = 1600 + + @classmethod + def setUpClass(cls): + pass + + def test_qwen3_32b(self): + self.run_throughput() + + +if __name__ == "__main__": + unittest.main() diff --git a/asian_ai/performance/SGLang/test/registered/ascend/performance/qwen3_32b/test_npu_qwen3_32b_w8a8_2p_in3k5_out1k5_50ms_gpqa.py b/asian_ai/performance/SGLang/test/registered/ascend/performance/qwen3_32b/test_npu_qwen3_32b_w8a8_2p_in3k5_out1k5_50ms_gpqa.py new file mode 100644 index 0000000000000000000000000000000000000000..dbb9e2fbe1288c19ab1db53eb78ccc1126353345 --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/ascend/performance/qwen3_32b/test_npu_qwen3_32b_w8a8_2p_in3k5_out1k5_50ms_gpqa.py @@ -0,0 +1,124 @@ +import unittest + +from sglang.test.ascend.e2e.test_npu_accuracy_utils import ( + TestNpuAccuracyTestCaseBase, +) +from sglang.test.ascend.e2e.test_npu_performance_utils import ( + AISBENCHMARK_DATASET_DEFAULT, + BENCHMARK_TOOL_DEFAULT, + QWEN3_32B_EAGLE_MODEL_PATH, + QWEN3_32B_W8A8_MODEL_PATH, + TestNpuPerformanceTestCaseBase, +) +from sglang.test.ci.ci_register import register_npu_ci + +register_npu_ci( + est_time=3600, + suite="", + nightly=True, + disabled="performance testcase", +) + +QWEN3_32B_ENVS = { + "SGLANG_DISAGGREGATION_BOOTSTRAP_TIMEOUT": "600", + "PYTORCH_NPU_ALLOC_CONF": "expandable_segments:True", + "HCCL_SOCKET_IFNAME": "lo", + "GLOO_SOCKET_IFNAME": "lo", + "HCCL_OP_EXPANSION_MODE": "AIV", + "SGLANG_ENABLE_OVERLAP_PLAN_STREAM": "1", + "SGLANG_ENABLE_SPEC_V2": "1", + "SGLANG_SCHEDULER_DECREASE_PREFILL_IDLE": "1", + "SGLANG_PREFILL_DELAYER_MAX_DELAY_PASSES": "100", + "SGLANG_NPU_USE_DEEPGEMM": "1", +} + +QWEN3_32B_OTHER_ARGS = [ + "--trust-remote-code", + "--nnodes", + "1", + "--node-rank", + "0", + "--attention-backend", + "ascend", + "--device", + "npu", + "--quantization", + "modelslim", + "--max-running-requests", + 101, + "--disable-radix-cache", + "--speculative-draft-model-quantization", + "unquant", + "--chunked-prefill-size", + -1, + "--max-prefill-tokens", + 35000, + "--speculative-algorithm", + "EAGLE3", + "--speculative-draft-model-path", + QWEN3_32B_EAGLE_MODEL_PATH, + "--speculative-num-steps", + 3, + "--speculative-eagle-topk", + 1, + "--speculative-num-draft-tokens", + 4, + "--tp-size", + 4, + "--mem-fraction-static", + 0.845, + "--cuda-graph-bs", + 16, + 32, + 64, + 72, + 88, + 90, + 92, + 94, + 96, + 97, + 98, + 99, + 100, + 101, + "--dtype", + "bfloat16", +] + + +class TestQwen32B(TestNpuPerformanceTestCaseBase): + benchmark_tool = BENCHMARK_TOOL_DEFAULT + dataset_type = AISBENCHMARK_DATASET_DEFAULT + model = QWEN3_32B_W8A8_MODEL_PATH + other_args = QWEN3_32B_OTHER_ARGS + envs = QWEN3_32B_ENVS + dataset_name = "random" + max_concurrency = 100 + num_prompts = 400 + input_len = 3584 + output_len = 1536 + random_range_ratio = 1 + tpot = 50 + output_token_throughput = 1600 + + def test_qwen3_32b(self): + self.run_throughput() + + +class TestQwen32B_mmlupro(TestNpuAccuracyTestCaseBase): + model = QWEN3_32B_W8A8_MODEL_PATH + envs = QWEN3_32B_ENVS + other_args = QWEN3_32B_OTHER_ARGS + accuracy = 0.4949 + datasets = ["gpqa_diamond"] + few_shot_num = 0 + eval_batch_size = 64 + generation_config = {"max_tokens": 40000, "temperature": 1.0} + + def test_accuracy(self): + self.run_accuracy() + + +if __name__ == "__main__": + unittest.main() diff --git a/asian_ai/performance/SGLang/test/registered/ascend/performance/qwen3_6_27b/test_npu_qwen3_6_27b_1p_in1024x1024_30_out1024_50ms.py b/asian_ai/performance/SGLang/test/registered/ascend/performance/qwen3_6_27b/test_npu_qwen3_6_27b_1p_in1024x1024_30_out1024_50ms.py new file mode 100644 index 0000000000000000000000000000000000000000..c40b24ffa216159dc4b2e7920f7e856b20da57a1 --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/ascend/performance/qwen3_6_27b/test_npu_qwen3_6_27b_1p_in1024x1024_30_out1024_50ms.py @@ -0,0 +1,111 @@ +import unittest + +from sglang.test.ascend.e2e.test_npu_performance_utils import ( + AISBENCHMARK_DATASET_MM_CUSTOM_GEN, + BENCHMARK_TOOL_DEFAULT, + QWEN3_6_27B_MODEL_PATH, + TestNpuPerformanceTestCaseBase, +) +from sglang.test.ci.ci_register import register_npu_ci + +register_npu_ci( + est_time=3600, + suite="full-2-npu-a3", + nightly=True, + disabled="performance case", +) + +QWEN3_6_27B_1024_ENVS = { + "PYTORCH_NPU_ALLOC_CONF": "expandable_segments:True", + "STREAMS_PER_DEVICE": "32", + "HCCL_SOCKET_IFNAME": "lo", + "GLOO_SOCKET_IFNAME": "lo", + "HCCL_OP_EXPANSION_MODE": "AIV", + "SGLANG_SET_CPU_AFFINITY": "1", + "SGLANG_VIT_ENABLE_CUDA_GRAPH": "1", + "SGLANG_ENABLE_SPEC_V2": "1", + "SGLANG_NPU_PROFILING": "1", + "SGLANG_NPU_PROFILING_STAGE": "prefill", + "SGLANG_ENABLE_OVERLAP_PLAN_STREAM": "1", + "SGLANG_SCHEDULER_DECREASE_PREFILL_IDLE": "1", + "SGLANG_PREFILL_DELAYER_MAX_DELAY_PASSES": "150", + "ASCEND_USE_FIA": "1", +} + +QWEN3_6_27B_1024_OTHER_ARGS = [ + "--tp-size", + 2, + "--nnodes", + 1, + "--attention-backend", + "ascend", + "--device", + "npu", + "--chunked-prefill-size", + -1, + "--max-prefill-tokens", + 52000, + "--disable-radix-cache", + "--trust-remote-code", + "--max-running-requests", + 50, + "--max-mamba-cache-size", + 60, + "--mem-fraction-static", + 0.76, + "--cuda-graph-bs", + 2, + 4, + 8, + 16, + 24, + 32, + 40, + 42, + 45, + 50, + "--enable-multimodal", + "--mm-attention-backend", + "ascend_attn", + "--dtype", + "bfloat16", + "--mamba-ssm-dtype", + "bfloat16", + "--speculative-algorithm", + "NEXTN", + "--speculative-num-steps", + 3, + "--speculative-eagle-topk", + 1, + "--speculative-num-draft-tokens", + 4, + "--mm-enable-dp-encoder", +] + + +class TestNPUQwen3_6_27B_1P_In1024x1024_30_Out1024_50ms(TestNpuPerformanceTestCaseBase): + """Test NPU performance for Qwen3.6-27B 1p in1024x1024 30 out1024 50ms""" + + benchmark_tool = BENCHMARK_TOOL_DEFAULT + aisbench_dataset_type = AISBENCHMARK_DATASET_MM_CUSTOM_GEN + model = QWEN3_6_27B_MODEL_PATH + other_args = QWEN3_6_27B_1024_OTHER_ARGS + envs = QWEN3_6_27B_1024_ENVS + dataset_name = "random" + max_concurrency = 48 + num_prompts = 48 + input_len = 30 + output_len = 1024 + random_range_ratio = 1 + image_resolution = "1024x1024" + image_count = 1 + tpot = 50 + output_token_throughput = 800.8 + + def test_npu_qwen3_6_27b_1p_in1024x1024_30_out1024_50ms(self): + """Run NPU performance test for Qwen3.6-27B in1024x1024 30 out1024 50ms""" + self.run_throughput() + + +if __name__ == "__main__": + unittest.main() diff --git a/asian_ai/performance/SGLang/test/registered/ascend/performance/qwen3_6_27b/test_npu_qwen3_6_27b_1p_in1080p_30_out256_50ms.py b/asian_ai/performance/SGLang/test/registered/ascend/performance/qwen3_6_27b/test_npu_qwen3_6_27b_1p_in1080p_30_out256_50ms.py new file mode 100644 index 0000000000000000000000000000000000000000..9e0bc74d17db4e79a2fbfe3b7c3b1c4999ca4824 --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/ascend/performance/qwen3_6_27b/test_npu_qwen3_6_27b_1p_in1080p_30_out256_50ms.py @@ -0,0 +1,108 @@ +import unittest + +from sglang.test.ascend.e2e.test_npu_performance_utils import ( + AISBENCHMARK_DATASET_MM_CUSTOM_GEN, + BENCHMARK_TOOL_DEFAULT, + QWEN3_6_27B_MODEL_PATH, + TestNpuPerformanceTestCaseBase, +) +from sglang.test.ci.ci_register import register_npu_ci + +register_npu_ci( + est_time=3600, + suite="full-2-npu-a3", + nightly=True, + disabled="performance testcase", +) + +QWEN3_6_27B_1080P_ENVS = { + "PYTORCH_NPU_ALLOC_CONF": "expandable_segments:True", + "STREAMS_PER_DEVICE": "32", + "HCCL_SOCKET_IFNAME": "lo", + "GLOO_SOCKET_IFNAME": "lo", + "HCCL_OP_EXPANSION_MODE": "AIV", + "SGLANG_SET_CPU_AFFINITY": "1", + "SGLANG_VIT_ENABLE_CUDA_GRAPH": "1", + "SGLANG_ENABLE_SPEC_V2": "1", + "SGLANG_NPU_PROFILING": "1", + "SGLANG_NPU_PROFILING_STAGE": "prefill", + "SGLANG_ENABLE_OVERLAP_PLAN_STREAM": "1", + "SGLANG_SCHEDULER_DECREASE_PREFILL_IDLE": "1", + "SGLANG_PREFILL_DELAYER_MAX_DELAY_PASSES": "150", + "ASCEND_USE_FIA": "1", +} + +QWEN3_6_27B_1080P_OTHER_ARGS = [ + "--tp-size", + 2, + "--nnodes", + 1, + "--attention-backend", + "ascend", + "--device", + "npu", + "--chunked-prefill-size", + -1, + "--max-prefill-tokens", + 48000, + "--disable-radix-cache", + "--trust-remote-code", + "--max-running-requests", + 30, + "--max-mamba-cache-size", + 40, + "--mem-fraction-static", + 0.76, + "--cuda-graph-bs", + 2, + 4, + 8, + 16, + 24, + 28, + 30, + "--enable-multimodal", + "--mm-attention-backend", + "ascend_attn", + "--dtype", + "bfloat16", + "--mamba-ssm-dtype", + "bfloat16", + "--speculative-algorithm", + "NEXTN", + "--speculative-num-steps", + 3, + "--speculative-eagle-topk", + 1, + "--speculative-num-draft-tokens", + 4, + "--mm-enable-dp-encoder", +] + + +class TestNPUQwen3_6_27B_1P_In1080p_30_Out256_50ms(TestNpuPerformanceTestCaseBase): + """Test NPU performance for Qwen3.6-27B 1p in1080p 30 out256 50ms""" + + benchmark_tool = BENCHMARK_TOOL_DEFAULT + aisbench_dataset_type = AISBENCHMARK_DATASET_MM_CUSTOM_GEN + model = QWEN3_6_27B_MODEL_PATH + other_args = QWEN3_6_27B_1080P_OTHER_ARGS + envs = QWEN3_6_27B_1080P_ENVS + dataset_name = "random" + max_concurrency = 30 + num_prompts = 120 + input_len = 30 + output_len = 256 + random_range_ratio = 1 + image_resolution = "1920x1080" + image_count = 1 + tpot = 50 + output_token_throughput = 226 + + def test_npu_qwen3_6_27b_1p_in1080p_30_out256_50ms(self): + """Run NPU performance test for Qwen3.6-27B in1080p 30 out256 50ms""" + self.run_throughput() + + +if __name__ == "__main__": + unittest.main() diff --git a/asian_ai/performance/SGLang/test/registered/ascend/performance/qwen3_6_27b/test_npu_qwen3_6_27b_2p_in64k_out1k_prefix90_50ms.py b/asian_ai/performance/SGLang/test/registered/ascend/performance/qwen3_6_27b/test_npu_qwen3_6_27b_2p_in64k_out1k_prefix90_50ms.py new file mode 100644 index 0000000000000000000000000000000000000000..80041d747a8530abb187ac17e50df5ad47b63e65 --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/ascend/performance/qwen3_6_27b/test_npu_qwen3_6_27b_2p_in64k_out1k_prefix90_50ms.py @@ -0,0 +1,106 @@ +import unittest + +from sglang.test.ascend.e2e.test_npu_performance_utils import ( + BENCHMARK_TOOL_DEFAULT, + QWEN3_6_27B_MODEL_PATH, + TestNpuPerformanceTestCaseBase, +) +from sglang.test.ci.ci_register import register_npu_ci + +register_npu_ci( + est_time=3600, + suite="", + nightly=True, + disabled="performance testcase", +) + +QWEN3_6_27B_64K_PREFIX_ENVS = { + "PYTORCH_NPU_ALLOC_CONF": "expandable_segments:True", + "SGLANG_SET_CPU_AFFINITY": "1", + "STREAMS_PER_DEVICE": "32", + "HCCL_SOCKET_IFNAME": "lo", + "GLOO_SOCKET_IFNAME": "lo", + "HCCL_OP_EXPANSION_MODE": "AIV", + "SGLANG_ENABLE_SPEC_V2": "1", + "SGLANG_ENABLE_OVERLAP_PLAN_STREAM": "1", + "ASCEND_USE_FIA": "1", + "GDN_ATTN_BACKEND_TRITON": "1", +} + +QWEN3_6_27B_64K_PREFIX_OTHER_ARGS = [ + "--tp-size", + 2, + "--nnodes", + 1, + "--attention-backend", + "ascend", + "--device", + "npu", + "--chunked-prefill-size", + 32768, + "--max-prefill-tokens", + 32768, + "--mamba-scheduler-strategy", + "extra_buffer", + "--trust-remote-code", + "--max-running-requests", + 20, + "--max-mamba-cache-size", + 120, + "--mem-fraction-static", + 0.8, + "--cuda-graph-bs", + 1, + 2, + 4, + 8, + 10, + 12, + 16, + 18, + 20, + "--enable-prefill-delayer", + "--prefill-delayer-queue-min-ratio", + 0.5, + "--prefill-delayer-max-delay-ms", + 30000, + "--dtype", + "bfloat16", + "--mamba-ssm-dtype", + "bfloat16", + "--speculative-algorithm", + "NEXTN", + "--speculative-num-steps", + 3, + "--speculative-eagle-topk", + 1, + "--speculative-num-draft-tokens", + 4, +] + + +class TestNPUQwen3_6_27B_2P_In64k_Out1k_Prefix90_50ms(TestNpuPerformanceTestCaseBase): + """Test NPU performance for Qwen3.6-27B-w8a8 2p in64k out1k prefix90 50ms""" + + benchmark_tool = BENCHMARK_TOOL_DEFAULT + model = QWEN3_6_27B_MODEL_PATH + other_args = QWEN3_6_27B_64K_PREFIX_OTHER_ARGS + envs = QWEN3_6_27B_64K_PREFIX_ENVS + dataset_name = "generated-shared-prefix" + max_concurrency = 20 + num_prompts = 80 + input_len = 64000 + output_len = 1000 + random_range_ratio = 1 + repeat_rate = 0.9 + request_rate = float("inf") + tpot = 50 + output_token_throughput = 225 + + def test_npu_qwen3_6_27b_2p_in64k_out1k_prefix90_50ms(self): + """Run NPU performance test for Qwen3.6-27B-w8a8 in64k out1k prefix90 50ms""" + self.run_throughput() + + +if __name__ == "__main__": + unittest.main() diff --git a/asian_ai/performance/SGLang/test/registered/ascend/performance/qwen3_6_27b/test_npu_qwen3_6_27b_w8a8_1p_in3k5_out1k5_50ms_gpqa.py b/asian_ai/performance/SGLang/test/registered/ascend/performance/qwen3_6_27b/test_npu_qwen3_6_27b_w8a8_1p_in3k5_out1k5_50ms_gpqa.py new file mode 100644 index 0000000000000000000000000000000000000000..b191598a1fccc06e14db52a28b9e377342738b03 --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/ascend/performance/qwen3_6_27b/test_npu_qwen3_6_27b_w8a8_1p_in3k5_out1k5_50ms_gpqa.py @@ -0,0 +1,120 @@ +import unittest + +from sglang.test.ascend.e2e.test_npu_accuracy_utils import ( + TestNpuAccuracyTestCaseBase, +) +from sglang.test.ascend.e2e.test_npu_performance_utils import ( + AISBENCHMARK_DATASET_DEFAULT, + BENCHMARK_TOOL_DEFAULT, + QWEN3_6_27B_W8A8_MODEL_PATH, + TestNpuPerformanceTestCaseBase, +) +from sglang.test.ci.ci_register import register_npu_ci + +register_npu_ci( + est_time=3600, + suite="full-2-npu-a3", + nightly=True, + disabled="performance testcase", +) + +QWEN3_6_27B_3K5_1K5_ENVS = { + "PYTORCH_NPU_ALLOC_CONF": "expandable_segments:True", + "STREAMS_PER_DEVICE": "32", + "HCCL_SOCKET_IFNAME": "lo", + "GLOO_SOCKET_IFNAME": "lo", + "HCCL_OP_EXPANSION_MODE": "AIV", + "SGLANG_SET_CPU_AFFINITY": "1", + "SGLANG_ENABLE_SPEC_V2": "1", + "SGLANG_ENABLE_OVERLAP_PLAN_STREAM": "0", + "SGLANG_SCHEDULER_DECREASE_PREFILL_IDLE": "1", + "SGLANG_PREFILL_DELAYER_MAX_DELAY_PASSES": "130", + "ASCEND_USE_FIA": "1", +} + +QWEN3_6_27B_3K5_1K5_OTHER_ARGS = [ + "--tp-size", + 2, + "--nnodes", + 1, + "--attention-backend", + "ascend", + "--device", + "npu", + "--chunked-prefill-size", + -1, + "--max-prefill-tokens", + 60000, + "--disable-radix-cache", + "--trust-remote-code", + "--max-running-requests", + 64, + "--max-mamba-cache-size", + 74, + "--mem-fraction-static", + 0.7, + "--cuda-graph-bs", + 2, + 8, + 16, + 32, + 48, + 64, + "--enable-multimodal", + "--quantization", + "modelslim", + "--mm-attention-backend", + "ascend_attn", + "--dtype", + "bfloat16", + "--mamba-ssm-dtype", + "bfloat16", + "--speculative-algorithm", + "NEXTN", + "--speculative-num-steps", + 3, + "--speculative-eagle-topk", + 1, + "--speculative-num-draft-tokens", + 4, +] + + +class TestNPUQwen3_6_27B_1P_In3k5_Out1k5_50ms(TestNpuPerformanceTestCaseBase): + """Test NPU performance for Qwen3.6-27B-w8a8 1p in3k5 out1k5 50ms""" + + benchmark_tool = BENCHMARK_TOOL_DEFAULT + dataset_type = AISBENCHMARK_DATASET_DEFAULT + model = QWEN3_6_27B_W8A8_MODEL_PATH + other_args = QWEN3_6_27B_3K5_1K5_OTHER_ARGS + envs = QWEN3_6_27B_3K5_1K5_ENVS + dataset_name = "random" + max_concurrency = 54 + num_prompts = 216 + input_len = 3500 + output_len = 1500 + random_range_ratio = 1 + tpot = 50 + output_token_throughput = 786.69 + + def test_npu_qwen3_6_27b_1p_in3k5_out1k5_50ms(self): + """Run NPU performance test for Qwen3.6-27B-w8a8 in3k5 out1k5 50ms""" + self.run_throughput() + + +class TestNPUQwen3_6_27B_1P_In3k5_Out1k5_gpqa(TestNpuAccuracyTestCaseBase): + model = QWEN3_6_27B_W8A8_MODEL_PATH + envs = QWEN3_6_27B_3K5_1K5_ENVS + other_args = QWEN3_6_27B_3K5_1K5_OTHER_ARGS + accuracy = 0.855 + datasets = ["gpqa_diamond"] + few_shot_num = 0 + eval_batch_size = 8 + generation_config = {"max_tokens": 81920, "temperature": 1.0} + + def test_accuracy(self): + self.run_accuracy() + + +if __name__ == "__main__": + unittest.main() diff --git a/asian_ai/performance/SGLang/test/registered/ascend/performance/qwen3_6_27b/test_npu_qwen3_6_27b_w8a8_2p_in128k_out1k_50ms.py b/asian_ai/performance/SGLang/test/registered/ascend/performance/qwen3_6_27b/test_npu_qwen3_6_27b_w8a8_2p_in128k_out1k_50ms.py new file mode 100644 index 0000000000000000000000000000000000000000..a82d3e411d392919c3debada5cc1747aa8d78354 --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/ascend/performance/qwen3_6_27b/test_npu_qwen3_6_27b_w8a8_2p_in128k_out1k_50ms.py @@ -0,0 +1,94 @@ +import unittest + +from sglang.test.ascend.e2e.test_npu_performance_utils import ( + AISBENCHMARK_DATASET_DEFAULT, + BENCHMARK_TOOL_DEFAULT, + QWEN3_6_27B_W8A8_MODEL_PATH, + TestNpuPerformanceTestCaseBase, +) +from sglang.test.ci.ci_register import register_npu_ci + +register_npu_ci( + est_time=3600, + suite="", + nightly=True, + disabled="performance testcase", +) + +QWEN3_6_27B_128K_ENVS = { + "PYTORCH_NPU_ALLOC_CONF": "expandable_segments:True", + "STREAMS_PER_DEVICE": "32", + "HCCL_SOCKET_IFNAME": "lo", + "GLOO_SOCKET_IFNAME": "lo", + "HCCL_OP_EXPANSION_MODE": "AIV", + "SGLANG_SET_CPU_AFFINITY": "1", + "SGLANG_ENABLE_SPEC_V2": "1", + "SGLANG_ENABLE_OVERLAP_PLAN_STREAM": "1", + "SGLANG_SCHEDULER_DECREASE_PREFILL_IDLE": "1", + "SGLANG_PREFILL_DELAYER_MAX_DELAY_PASSES": "20", + "ASCEND_USE_FIA": "1", +} + +QWEN3_6_27B_128K_OTHER_ARGS = [ + "--tp-size", + 4, + "--nnodes", + 1, + "--attention-backend", + "ascend", + "--device", + "npu", + "--chunked-prefill-size", + -1, + "--max-prefill-tokens", + 74000, + "--disable-radix-cache", + "--trust-remote-code", + "--max-running-requests", + 6, + "--max-mamba-cache-size", + 7, + "--mem-fraction-static", + 0.63, + "--cuda-graph-bs", + 1, + 2, + 4, + 5, + 6, + "--enable-multimodal", + "--quantization", + "modelslim", + "--mm-attention-backend", + "ascend_attn", + "--dtype", + "bfloat16", + "--mamba-ssm-dtype", + "bfloat16", +] + + +class TestNPUQwen3_6_27B_2P_In128k_Out1k_50ms(TestNpuPerformanceTestCaseBase): + """Test NPU performance for Qwen3.6-27B-w8a8 2p in128k out1k 50ms""" + + benchmark_tool = BENCHMARK_TOOL_DEFAULT + aisbench_dataset_type = AISBENCHMARK_DATASET_DEFAULT + model = QWEN3_6_27B_W8A8_MODEL_PATH + other_args = QWEN3_6_27B_128K_OTHER_ARGS + envs = QWEN3_6_27B_128K_ENVS + dataset_name = "random" + max_concurrency = 4 + num_prompts = 16 + input_len = 128000 + output_len = 1000 + random_range_ratio = 1 + tpot = 50 + output_token_throughput = 41.39 + + def test_npu_qwen3_6_27b_2p_in128k_out1k_50ms(self): + """Run NPU performance test for Qwen3.6-27B-w8a8 in128k out1k 50ms""" + self.run_throughput() + + +if __name__ == "__main__": + unittest.main() diff --git a/asian_ai/performance/SGLang/test/registered/ascend/performance/qwen3_6_27b/test_npu_qwen3_6_27b_w8a8_2p_in16k_out1k_50ms.py b/asian_ai/performance/SGLang/test/registered/ascend/performance/qwen3_6_27b/test_npu_qwen3_6_27b_w8a8_2p_in16k_out1k_50ms.py new file mode 100644 index 0000000000000000000000000000000000000000..cddfab0bbb31283fb174f264e598443a369f93d8 --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/ascend/performance/qwen3_6_27b/test_npu_qwen3_6_27b_w8a8_2p_in16k_out1k_50ms.py @@ -0,0 +1,104 @@ +import unittest + +from sglang.test.ascend.e2e.test_npu_performance_utils import ( + AISBENCHMARK_DATASET_DEFAULT, + BENCHMARK_TOOL_DEFAULT, + QWEN3_6_27B_W8A8_MODEL_PATH, + TestNpuPerformanceTestCaseBase, +) +from sglang.test.ci.ci_register import register_npu_ci + +register_npu_ci( + est_time=3600, + suite="", + nightly=True, + disabled="performance testcase", +) + +QWEN3_6_27B_16K_1k_ENVS = { + "PYTORCH_NPU_ALLOC_CONF": "expandable_segments:True", + "STREAMS_PER_DEVICE": "32", + "HCCL_SOCKET_IFNAME": "lo", + "GLOO_SOCKET_IFNAME": "lo", + "HCCL_OP_EXPANSION_MODE": "AIV", + "SGLANG_SET_CPU_AFFINITY": "1", + "SGLANG_ENABLE_SPEC_V2": "1", + "SGLANG_ENABLE_OVERLAP_PLAN_STREAM": "1", + "SGLANG_SCHEDULER_DECREASE_PREFILL_IDLE": "1", + "SGLANG_PREFILL_DELAYER_MAX_DELAY_PASSES": "30", + "ASCEND_USE_FIA": "1", +} + +QWEN3_6_27B_16K_1k_OTHER_ARGS = [ + "--tp-size", + 4, + "--nnodes", + 1, + "--attention-backend", + "ascend", + "--device", + "npu", + "--chunked-prefill-size", + -1, + "--max-prefill-tokens", + 50000, + "--disable-radix-cache", + "--trust-remote-code", + "--max-running-requests", + 28, + "--max-mamba-cache-size", + 50, + "--mem-fraction-static", + 0.7, + "--cuda-graph-bs", + 2, + 8, + 12, + 16, + 20, + 24, + 28, + "--enable-multimodal", + "--quantization", + "modelslim", + "--mm-attention-backend", + "ascend_attn", + "--dtype", + "bfloat16", + "--mamba-ssm-dtype", + "bfloat16", + "--speculative-algorithm", + "NEXTN", + "--speculative-num-steps", + 3, + "--speculative-eagle-topk", + 1, + "--speculative-num-draft-tokens", + 4, +] + + +class TestNPUQwen3_6_27B_2P_In16k_Out1k_50ms(TestNpuPerformanceTestCaseBase): + """Test NPU performance for Qwen3.6-27B-w8a8 2p in16k out1k 50ms""" + + benchmark_tool = BENCHMARK_TOOL_DEFAULT + aisbench_dataset_type = AISBENCHMARK_DATASET_DEFAULT + model = QWEN3_6_27B_W8A8_MODEL_PATH + other_args = QWEN3_6_27B_16K_1k_OTHER_ARGS + envs = QWEN3_6_27B_16K_1k_ENVS + dataset_name = "random" + max_concurrency = 28 + num_prompts = 112 + input_len = 16000 + output_len = 1000 + random_range_ratio = 1 + tpot = 50 + output_token_throughput = 426.1 + + def test_npu_qwen3_6_27b_2p_in16k_out1k_50ms(self): + """Run NPU performance test for Qwen3.6-27B-w8a8 in16k out1k 50ms""" + self.run_throughput() + + +if __name__ == "__main__": + unittest.main() diff --git a/asian_ai/performance/SGLang/test/registered/ascend/performance/qwen3_6_27b/test_npu_qwen3_6_27b_w8a8_2p_in64k_out1k_50ms.py b/asian_ai/performance/SGLang/test/registered/ascend/performance/qwen3_6_27b/test_npu_qwen3_6_27b_w8a8_2p_in64k_out1k_50ms.py new file mode 100644 index 0000000000000000000000000000000000000000..aab26db6df2e20f5d185f0c886717d55755cdd49 --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/ascend/performance/qwen3_6_27b/test_npu_qwen3_6_27b_w8a8_2p_in64k_out1k_50ms.py @@ -0,0 +1,100 @@ +import unittest + +from sglang.test.ascend.e2e.test_npu_performance_utils import ( + AISBENCHMARK_DATASET_DEFAULT, + BENCHMARK_TOOL_DEFAULT, + QWEN3_6_27B_W8A8_MODEL_PATH, + TestNpuPerformanceTestCaseBase, +) +from sglang.test.ci.ci_register import register_npu_ci + +register_npu_ci( + est_time=3600, + suite="", + nightly=True, + disabled="performance testcase", +) + +QWEN3_6_27B_64K_1K_ENVS = { + "PYTORCH_NPU_ALLOC_CONF": "expandable_segments:True", + "STREAMS_PER_DEVICE": "32", + "HCCL_SOCKET_IFNAME": "lo", + "GLOO_SOCKET_IFNAME": "lo", + "HCCL_OP_EXPANSION_MODE": "AIV", + "SGLANG_SET_CPU_AFFINITY": "1", + "SGLANG_ENABLE_SPEC_V2": "1", + "SGLANG_ENABLE_OVERLAP_PLAN_STREAM": "1", + "SGLANG_SCHEDULER_DECREASE_PREFILL_IDLE": "1", + "SGLANG_PREFILL_DELAYER_MAX_DELAY_PASSES": "30", + "ASCEND_USE_FIA": "1", +} + +QWEN3_6_27B_64K_1K_OTHER_ARGS = [ + "--tp-size", + 4, + "--nnodes", + 1, + "--attention-backend", + "ascend", + "--device", + "npu", + "--chunked-prefill-size", + -1, + "--max-prefill-tokens", + 50000, + "--disable-radix-cache", + "--trust-remote-code", + "--max-running-requests", + 28, + "--max-mamba-cache-size", + 50, + "--mem-fraction-static", + 0.7, + "--cuda-graph-bs", + 2, + 4, + 6, + "--enable-multimodal", + "--quantization", + "modelslim", + "--mm-attention-backend", + "ascend_attn", + "--dtype", + "bfloat16", + "--mamba-ssm-dtype", + "bfloat16", + "--speculative-algorithm", + "NEXTN", + "--speculative-num-steps", + 3, + "--speculative-eagle-topk", + 1, + "--speculative-num-draft-tokens", + 4, +] + + +class TestNPUQwen3_6_27B_2P_In64k_Out1k_50ms(TestNpuPerformanceTestCaseBase): + """Test NPU performance for Qwen3.6-27B-w8a8 2p in64k out1k 50ms""" + + benchmark_tool = BENCHMARK_TOOL_DEFAULT + aisbench_dataset_type = AISBENCHMARK_DATASET_DEFAULT + model = QWEN3_6_27B_W8A8_MODEL_PATH + other_args = QWEN3_6_27B_64K_1K_OTHER_ARGS + envs = QWEN3_6_27B_64K_1K_ENVS + dataset_name = "random" + max_concurrency = 6 + num_prompts = 24 + input_len = 64000 + output_len = 1000 + random_range_ratio = 1 + tpot = 50 + output_token_throughput = 122.6 + + def test_npu_qwen3_6_27b_2p_in64k_out1k_50ms(self): + """Run NPU performance test for Qwen3.6-27B-w8a8 in64k out1k 50ms""" + self.run_throughput() + + +if __name__ == "__main__": + unittest.main() diff --git a/asian_ai/performance/SGLang/test/registered/ascend/performance/qwen3_6_35b_a3b/test_npu_qwen3_6_35b_a3b_1p_in128k_out1k_50ms.py b/asian_ai/performance/SGLang/test/registered/ascend/performance/qwen3_6_35b_a3b/test_npu_qwen3_6_35b_a3b_1p_in128k_out1k_50ms.py new file mode 100644 index 0000000000000000000000000000000000000000..0ed5fdbf281abea152caed89f6868758457e32dc --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/ascend/performance/qwen3_6_35b_a3b/test_npu_qwen3_6_35b_a3b_1p_in128k_out1k_50ms.py @@ -0,0 +1,99 @@ +import unittest + +from sglang.test.ascend.e2e.test_npu_performance_utils import ( + AISBENCHMARK_DATASET_DEFAULT, + BENCHMARK_TOOL_DEFAULT, + QWEN3_6_35B_A3B_MODEL_PATH, + TestNpuPerformanceTestCaseBase, +) +from sglang.test.ci.ci_register import register_npu_ci + +register_npu_ci( + est_time=3600, + suite="", + nightly=True, + disabled="performance testcase", +) + +QWEN3_6_35B_A3B_128K_1K_ENVS = { + "PYTORCH_NPU_ALLOC_CONF": "expandable_segments:True", + "STREAMS_PER_DEVICE": "32", + "HCCL_SOCKET_IFNAME": "lo", + "GLOO_SOCKET_IFNAME": "lo", + "HCCL_OP_EXPANSION_MODE": "AIV", + "SGLANG_SET_CPU_AFFINITY": "1", + "SGLANG_ENABLE_SPEC_V2": "1", + "SGLANG_ENABLE_OVERLAP_PLAN_STREAM": "1", + "ASCEND_USE_FIA": "1", + "SGLANG_PREFILL_DELAYER_MAX_DELAY_PASSES": "20", +} + +QWEN3_6_35B_A3B_128K_1K_OTHER_ARGS = [ + "--tp-size", + 2, + "--nnodes", + 1, + "--attention-backend", + "ascend", + "--device", + "npu", + "--chunked-prefill-size", + -1, + "--max-total-tokens", + 600000, + "--max-prefill-tokens", + 65536, + "--disable-radix-cache", + "--trust-remote-code", + "--enable-prefill-delayer", + "--max-running-requests", + 4, + "--max-mamba-cache-size", + 12, + "--mem-fraction-static", + 0.6, + "--max-mamba-cache-size", + 20, + "--disable-cuda-graph", + "--enable-multimodal", + "--mm-attention-backend", + "ascend_attn", + "--dtype", + "bfloat16", + "--mamba-ssm-dtype", + "bfloat16", + "--speculative-algorithm", + "NEXTN", + "--speculative-num-steps", + 3, + "--speculative-eagle-topk", + 1, + "--speculative-num-draft-tokens", + 4, +] + + +class TestNPUQwen3_6_35BA3B_1P_In128k_Out1k_50ms(TestNpuPerformanceTestCaseBase): + """Test NPU performance for Qwen3.6-35B-A3B 1p in128k out1k 50ms""" + + benchmark_tool = BENCHMARK_TOOL_DEFAULT + aisbench_dataset_type = AISBENCHMARK_DATASET_DEFAULT + model = QWEN3_6_35B_A3B_MODEL_PATH + other_args = QWEN3_6_35B_A3B_128K_1K_OTHER_ARGS + envs = QWEN3_6_35B_A3B_128K_1K_ENVS + dataset_name = "random" + max_concurrency = 4 + num_prompts = 16 + input_len = 128000 + output_len = 1000 + random_range_ratio = 1 + tpot = 50 + output_token_throughput = 60.57 + + def test_npu_qwen3_6_35b_a3b_1p_in128k_out1k_50ms(self): + """Run NPU performance test for Qwen3.6-35B-A3B in128k out1k 50ms""" + self.run_throughput() + + +if __name__ == "__main__": + unittest.main() diff --git a/asian_ai/performance/SGLang/test/registered/ascend/performance/qwen3_6_35b_a3b/test_npu_qwen3_6_35b_a3b_1p_in128k_out1k_prefix90_50ms.py b/asian_ai/performance/SGLang/test/registered/ascend/performance/qwen3_6_35b_a3b/test_npu_qwen3_6_35b_a3b_1p_in128k_out1k_prefix90_50ms.py new file mode 100644 index 0000000000000000000000000000000000000000..233cba12cdeabd8fadfe8e3ce0321c894228d779 --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/ascend/performance/qwen3_6_35b_a3b/test_npu_qwen3_6_35b_a3b_1p_in128k_out1k_prefix90_50ms.py @@ -0,0 +1,108 @@ +import unittest + +from sglang.test.ascend.e2e.test_npu_performance_utils import ( + BENCHMARK_TOOL_DEFAULT, + QWEN3_6_35B_A3B_MODEL_PATH, + TestNpuPerformanceTestCaseBase, +) +from sglang.test.ci.ci_register import register_npu_ci + +register_npu_ci( + est_time=3600, + suite="", + nightly=True, + disabled="performance testcase", +) + +QWEN3_6_35B_A3B_128K_PREFIX_ENVS = { + "PYTORCH_NPU_ALLOC_CONF": "expandable_segments:True", + "STREAMS_PER_DEVICE": "32", + "HCCL_SOCKET_IFNAME": "lo", + "GLOO_SOCKET_IFNAME": "lo", + "HCCL_OP_EXPANSION_MODE": "AIV", + "SGLANG_SET_CPU_AFFINITY": "1", + "SGLANG_ENABLE_SPEC_V2": "1", + "SGLANG_ENABLE_OVERLAP_PLAN_STREAM": "1", + "ASCEND_USE_FIA": "1", + "SGLANG_PREFILL_DELAYER_MAX_DELAY_PASSES": "30", +} + +QWEN3_6_35B_A3B_128K_PREFIX_OTHER_ARGS = [ + "--tp-size", + 2, + "--nnodes", + 1, + "--attention-backend", + "ascend", + "--device", + "npu", + "--chunked-prefill-size", + 16384, + "--max-prefill-tokens", + 65536, + "--trust-remote-code", + "--enable-prefill-delayer", + "--mamba-scheduler-strategy", + "extra_buffer", + "--max-running-requests", + 103, + "--max-mamba-cache-size", + 85, + "--mem-fraction-static", + 0.85, + "--cuda-graph-bs", + 2, + 4, + 8, + 16, + 32, + 48, + 64, + 80, + 96, + 103, + "--enable-multimodal", + "--mm-attention-backend", + "ascend_attn", + "--dtype", + "bfloat16", + "--mamba-ssm-dtype", + "bfloat16", + "--speculative-algorithm", + "NEXTN", + "--speculative-num-steps", + 3, + "--speculative-eagle-topk", + 1, + "--speculative-num-draft-tokens", + 4, +] + + +class TestNPUQwen3_6_35BA3B_1P_In128k_Out1k_Prefix90_50ms( + TestNpuPerformanceTestCaseBase +): + """Test NPU performance for Qwen3.6-35B-A3B 1p in128k out1k prefix90 50ms""" + + benchmark_tool = BENCHMARK_TOOL_DEFAULT + model = QWEN3_6_35B_A3B_MODEL_PATH + other_args = QWEN3_6_35B_A3B_128K_PREFIX_OTHER_ARGS + envs = QWEN3_6_35B_A3B_128K_PREFIX_ENVS + dataset_name = "generated-shared-prefix" + max_concurrency = 103 + num_prompts = 412 + input_len = 64000 + output_len = 1000 + random_range_ratio = 1 + repeat_rate = 0.9 + tpot = 50 + request_rate = float("inf") + output_token_throughput = 308.2 + + def test_npu_qwen3_6_35b_a3b_1p_in128k_out1k_prefix90_50ms(self): + """Run NPU performance test for Qwen3.6-35B-A3B in128k out1k prefix90 50ms""" + self.run_throughput() + + +if __name__ == "__main__": + unittest.main() diff --git a/asian_ai/performance/SGLang/test/registered/ascend/performance/qwen3_6_35b_a3b/test_npu_qwen3_6_35b_a3b_1p_in3k5_out1k5_50ms.py b/asian_ai/performance/SGLang/test/registered/ascend/performance/qwen3_6_35b_a3b/test_npu_qwen3_6_35b_a3b_1p_in3k5_out1k5_50ms.py new file mode 100644 index 0000000000000000000000000000000000000000..9607434fb7d80ae6a30a150922e1173d70c5dd11 --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/ascend/performance/qwen3_6_35b_a3b/test_npu_qwen3_6_35b_a3b_1p_in3k5_out1k5_50ms.py @@ -0,0 +1,103 @@ +import unittest + +from sglang.test.ascend.e2e.test_npu_performance_utils import ( + AISBENCHMARK_DATASET_DEFAULT, + BENCHMARK_TOOL_DEFAULT, + QWEN3_6_35B_A3B_MODEL_PATH, + TestNpuPerformanceTestCaseBase, +) +from sglang.test.ci.ci_register import register_npu_ci + +register_npu_ci( + est_time=3600, + suite="full-2-npu-a3", + nightly=True, + disabled="performance testcase", +) + +QWEN3_6_35B_A3B_3K5_1K5_ENVS = { + "PYTORCH_NPU_ALLOC_CONF": "expandable_segments:True", + "STREAMS_PER_DEVICE": "32", + "HCCL_BUFFSIZE": "800", + "HCCL_SOCKET_IFNAME": "lo", + "GLOO_SOCKET_IFNAME": "lo", + "HCCL_OP_EXPANSION_MODE": "AIV", + "SGLANG_SET_CPU_AFFINITY": "1", + "SGLANG_ENABLE_SPEC_V2": "1", + "SGLANG_ENABLE_OVERLAP_PLAN_STREAM": "0", + "ASCEND_USE_FIA": "1", + "SGLANG_PREFILL_DELAYER_MAX_DELAY_PASSES": "50", +} + +QWEN3_6_35B_A3B_3K5_1K5_OTHER_ARGS = [ + "--tp-size", + 2, + "--nnodes", + 1, + "--attention-backend", + "ascend", + "--device", + "npu", + "--chunked-prefill-size", + -1, + "--max-prefill-tokens", + 35000, + "--disable-radix-cache", + "--trust-remote-code", + "--enable-prefill-delayer", + "--max-running-requests", + 110, + "--max-mamba-cache-size", + 115, + "--mem-fraction-static", + 0.78, + "--cuda-graph-bs", + 4, + 16, + 32, + 64, + 84, + 105, + 110, + "--enable-multimodal", + "--mm-attention-backend", + "ascend_attn", + "--dtype", + "bfloat16", + "--mamba-ssm-dtype", + "bfloat16", + "--speculative-algorithm", + "NEXTN", + "--speculative-num-steps", + 3, + "--speculative-eagle-topk", + 1, + "--speculative-num-draft-tokens", + 4, +] + + +class TestNPUQwen3_6_35BA3B_1P_In3k5_Out1k5_50ms(TestNpuPerformanceTestCaseBase): + """Test NPU performance for Qwen3.6-35B-A3B 1p in3k5 out1k5 50ms""" + + benchmark_tool = BENCHMARK_TOOL_DEFAULT + aisbench_dataset_type = AISBENCHMARK_DATASET_DEFAULT + model = QWEN3_6_35B_A3B_MODEL_PATH + other_args = QWEN3_6_35B_A3B_3K5_1K5_OTHER_ARGS + envs = QWEN3_6_35B_A3B_3K5_1K5_ENVS + dataset_name = "random" + max_concurrency = 110 + num_prompts = 440 + input_len = 3500 + output_len = 1500 + random_range_ratio = 1 + tpot = 50 + output_token_throughput = 2031.71 + + def test_npu_qwen3_6_35b_a3b_1p_in3k5_out1k5_50ms(self): + """Run NPU performance test for Qwen3.6-35B-A3B in3k5 out1k5 50ms""" + self.run_throughput() + + +if __name__ == "__main__": + unittest.main() diff --git a/asian_ai/performance/SGLang/test/registered/ascend/performance/qwen3_6_35b_a3b/test_npu_qwen3_6_35b_a3b_1p_in64k_out1k_50ms.py b/asian_ai/performance/SGLang/test/registered/ascend/performance/qwen3_6_35b_a3b/test_npu_qwen3_6_35b_a3b_1p_in64k_out1k_50ms.py new file mode 100644 index 0000000000000000000000000000000000000000..48883a7a58698fddc6b4f8a8bb0d12c0b4778cc4 --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/ascend/performance/qwen3_6_35b_a3b/test_npu_qwen3_6_35b_a3b_1p_in64k_out1k_50ms.py @@ -0,0 +1,103 @@ +import unittest + +from sglang.test.ascend.e2e.test_npu_performance_utils import ( + AISBENCHMARK_DATASET_DEFAULT, + BENCHMARK_TOOL_DEFAULT, + QWEN3_6_35B_A3B_MODEL_PATH, + TestNpuPerformanceTestCaseBase, +) +from sglang.test.ci.ci_register import register_npu_ci + +register_npu_ci( + est_time=3600, + suite="full-2-npu-a3", + nightly=True, + disabled="performance testcase", +) + +QWEN3_6_35B_A3B_64K_1K_ENVS = { + "PYTORCH_NPU_ALLOC_CONF": "expandable_segments:True", + "STREAMS_PER_DEVICE": "32", + "HCCL_SOCKET_IFNAME": "lo", + "GLOO_SOCKET_IFNAME": "lo", + "HCCL_OP_EXPANSION_MODE": "AIV", + "SGLANG_SET_CPU_AFFINITY": "1", + "SGLANG_ENABLE_SPEC_V2": "1", + "SGLANG_ENABLE_OVERLAP_PLAN_STREAM": "1", + "ASCEND_USE_FIA": "1", + "SGLANG_PREFILL_DELAYER_MAX_DELAY_PASSES": "1", +} + +QWEN3_6_35B_A3B_64K_1K_OTHER_ARGS = [ + "--tp-size", + 2, + "--nnodes", + 1, + "--attention-backend", + "ascend", + "--device", + "npu", + "--chunked-prefill-size", + -1, + "--max-total-tokens", + 600000, + "--max-prefill-tokens", + 65536, + "--disable-radix-cache", + "--trust-remote-code", + "--enable-prefill-delayer", + "--max-running-requests", + 10, + "--max-mamba-cache-size", + 20, + "--mem-fraction-static", + 0.65, + "--cuda-graph-bs", + 2, + 4, + 8, + 12, + 14, + 16, + "--enable-multimodal", + "--mm-attention-backend", + "ascend_attn", + "--dtype", + "bfloat16", + "--mamba-ssm-dtype", + "bfloat16", + "--speculative-algorithm", + "NEXTN", + "--speculative-num-steps", + 3, + "--speculative-eagle-topk", + 1, + "--speculative-num-draft-tokens", + 4, +] + + +class TestNPUQwen3_6_35BA3B_1P_In64k_Out1k_50ms(TestNpuPerformanceTestCaseBase): + """Test NPU performance for Qwen3.6-35B-A3B 1p in64k out1k 50ms""" + + benchmark_tool = BENCHMARK_TOOL_DEFAULT + aisbench_dataset_type = AISBENCHMARK_DATASET_DEFAULT + model = QWEN3_6_35B_A3B_MODEL_PATH + other_args = QWEN3_6_35B_A3B_64K_1K_OTHER_ARGS + envs = QWEN3_6_35B_A3B_64K_1K_ENVS + dataset_name = "random" + max_concurrency = 10 + num_prompts = 40 + input_len = 64000 + output_len = 1000 + random_range_ratio = 1 + tpot = 50 + output_token_throughput = 141.72 + + def test_npu_qwen3_6_35b_a3b_1p_in64k_out1k_50ms(self): + """Run NPU performance test for Qwen3.6-35B-A3B in64k out1k 50ms""" + self.run_throughput() + + +if __name__ == "__main__": + unittest.main() diff --git a/asian_ai/performance/SGLang/test/registered/ascend/performance/qwen3_6_35b_a3b/test_npu_qwen3_6_35b_a3b_1p_in64k_out1k_prefix90_50ms_aime26.py b/asian_ai/performance/SGLang/test/registered/ascend/performance/qwen3_6_35b_a3b/test_npu_qwen3_6_35b_a3b_1p_in64k_out1k_prefix90_50ms_aime26.py new file mode 100644 index 0000000000000000000000000000000000000000..4a842796a93f1c68e71836c53878e27cfec76b0a --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/ascend/performance/qwen3_6_35b_a3b/test_npu_qwen3_6_35b_a3b_1p_in64k_out1k_prefix90_50ms_aime26.py @@ -0,0 +1,141 @@ +import unittest + +from sglang.test.ascend.e2e.test_npu_accuracy_utils import ( + TestNpuAccuracyTestCaseBase, +) +from sglang.test.ascend.e2e.test_npu_performance_utils import ( + BENCHMARK_TOOL_DEFAULT, + DEFAULT_URL_FOR_TEST, + QWEN3_6_35B_A3B_MODEL_PATH, + TestNpuPerformanceTestCaseBase, +) +from sglang.test.ci.ci_register import register_npu_ci + +register_npu_ci( + est_time=3600, + suite="", + nightly=True, + disabled="performance testcase", +) + +QWEN3_6_35B_A3B_64K_PREFIX_ENVS = { + "PYTORCH_NPU_ALLOC_CONF": "expandable_segments:True", + "STREAMS_PER_DEVICE": "32", + "HCCL_BUFFSIZE": "300", + "HCCL_SOCKET_IFNAME": "lo", + "GLOO_SOCKET_IFNAME": "lo", + "HCCL_OP_EXPANSION_MODE": "AIV", + "SGLANG_SET_CPU_AFFINITY": "1", + "SGLANG_ENABLE_SPEC_V2": "1", + "SGLANG_ENABLE_OVERLAP_PLAN_STREAM": "0", + "ASCEND_USE_FIA": "1", + "GDN_ATTN_BACKEND_TRITON": "1", +} + +QWEN3_6_35B_A3B_64K_PREFIX_OTHER_ARGS = [ + "--tp-size", + 2, + "--nnodes", + 1, + "--attention-backend", + "ascend", + "--device", + "npu", + "--chunked-prefill-size", + -1, + "--max-prefill-tokens", + 65536, + "--trust-remote-code", + "--enable-prefill-delayer", + "--mamba-scheduler-strategy", + "extra_buffer", + "--max-running-requests", + 42, + "--max-mamba-cache-size", + 210, + "--mem-fraction-static", + 0.71, + "--cuda-graph-bs", + 2, + 8, + 16, + 24, + 32, + 36, + 40, + 42, + "--enable-multimodal", + "--mm-attention-backend", + "ascend_attn", + "--dtype", + "bfloat16", + "--mamba-ssm-dtype", + "bfloat16", + "--speculative-algorithm", + "NEXTN", + "--speculative-num-steps", + 3, + "--speculative-eagle-topk", + 1, + "--speculative-num-draft-tokens", + 4, +] + + +class TestNPUQwen3_6_35BA3B_1P_AIME2026(TestNpuAccuracyTestCaseBase): + """Test NPU accuracy for Qwen3.6-35B-A3B 1p on AIME2026""" + + model = QWEN3_6_35B_A3B_MODEL_PATH + other_args = QWEN3_6_35B_A3B_64K_PREFIX_OTHER_ARGS + envs = QWEN3_6_35B_A3B_64K_PREFIX_ENVS + accuracy = 0.927 + datasets = ["aime26"] + few_shot_num = 0 + eval_batch_size = 64 + generation_config = { + "max_tokens": 65536, + "temperature": 0.2, + "repetition_penalty": 1.08, + } + + @classmethod + def tearDownClass(cls): + pass + + def test_npu_qwen3_6_35b_a3b_1p_aime2026(self): + """Run NPU accuracy test for Qwen3.6-35B-A3B on AIME2026""" + self.run_accuracy() + + +class TestNPUQwen3_6_35BA3B_1P_In64k_Out1k_Prefix90_50ms( + TestNpuPerformanceTestCaseBase +): + """Test NPU performance for Qwen3.6-35B-A3B 1p in64k out1k prefix90 50ms""" + + base_url = DEFAULT_URL_FOR_TEST + benchmark_tool = BENCHMARK_TOOL_DEFAULT + model = QWEN3_6_35B_A3B_MODEL_PATH + other_args = QWEN3_6_35B_A3B_64K_PREFIX_OTHER_ARGS + envs = QWEN3_6_35B_A3B_64K_PREFIX_ENVS + dataset_name = "generated-shared-prefix" + max_concurrency = 42 + num_prompts = 42 + input_len = 65536 + output_len = 1024 + random_range_ratio = 1 + repeat_rate = 0.9 + tpot = 50 + request_rate = float("inf") + output_token_throughput = 660 + + @classmethod + def setUpClass(cls): + pass + + def test_npu_qwen3_6_35b_a3b_1p_in64k_out1k_prefix90_50ms(self): + """Run NPU performance test for Qwen3.6-35B-A3B in64k out1k prefix90 50ms""" + self.run_throughput() + + +if __name__ == "__main__": + unittest.main() diff --git a/asian_ai/performance/SGLang/test/registered/ascend/performance/qwen3_next_80b_a3b_instruct/test_npu_qwen3_next_80b_w8a8_2p_in6k_out1k5_bs16_aime25.py b/asian_ai/performance/SGLang/test/registered/ascend/performance/qwen3_next_80b_a3b_instruct/test_npu_qwen3_next_80b_w8a8_2p_in6k_out1k5_bs16_aime25.py new file mode 100644 index 0000000000000000000000000000000000000000..d153cc3613a7dce3cda120e0b3bf5558d41ac07c --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/ascend/performance/qwen3_next_80b_a3b_instruct/test_npu_qwen3_next_80b_w8a8_2p_in6k_out1k5_bs16_aime25.py @@ -0,0 +1,135 @@ +import unittest + +from sglang.test.ascend.e2e.test_npu_accuracy_utils import ( + TestNpuAccuracyTestCaseBase, +) +from sglang.test.ascend.e2e.test_npu_performance_utils import ( + QWEN3_NEXT_80B_A3B_MODEL_PATH, + QWEN3_NEXT_80B_A3B_W8A8_MODEL_PATH, + TestNpuPerformanceTestCaseBase, +) +from sglang.test.ci.ci_register import register_npu_ci + +register_npu_ci( + est_time=3600, + suite="", + nightly=True, + disabled="performance testcase", +) + +QWEN3_NEXT_80B_A3B_ENVS = { + "PYTORCH_NPU_ALLOC_CONF": "expandable_segments:True", + "STREAMS_PER_DEVICE": "32", + "HCCL_SOCKET_IFNAME": "lo", + "GLOO_SOCKET_IFNAME": "lo", + "DEEP_NORMAL_MODE_USE_INT8_QUANT": "1", + "SGLANG_DEEPEP_NUM_MAX_DISPATCH_TOKENS_PER_RANK": "400", + "DEEPEP_NORMAL_LONG_SEQ_ROUND": "10", + "DEEPEP_NORMAL_LONG_SEQ_PER_ROUND_TOKENS": "2048", + "HCCL_OP_EXPANSION_MODE": "AIV", + "TASK_QUEUE_ENABLE": "1", + "ASCEND_USE_FIA": "1", + "SGLANG_NPU_USE_MULTI_STREAM": "0", + "SGLANG_WARMUP_TIMEOUT": "3600", + "SGLANG_ENABLE_SPEC_V2": "1", + "SGLANG_ENABLE_OVERLAP_PLAN_STREAM": "1", + "FORCE_DRAFT_MODEL_NON_QUANT": "1", + "HCCL_BUFFSIZE": "2000", + "ZBCCL_LOCAL_MEM_SIZE": "60416", + "SGLANG_ENABLE_TP_MEMORY_INBALANCE_CHECK": "0", + "ZBCCL_BOOTSTRAP_URL": "tcp://127.0.0.1:24669", + "ZBCCL_NPU_ALLOC_CONF": "use_vmm_for_static_memory:True", + "ZBCCL_ENABLE_GRAPH": "1", +} + +QWEN3_NEXT_80B_A3B_OTHER_ARGS = [ + "--trust-remote-code", + "--attention-backend", + "ascend", + "--device", + "npu", + "--quantization", + "modelslim", + "--page-size", + 128, + "--tp-size", + 4, + "--watchdog-timeout", + 9000, + "--mem-fraction-static", + 0.85, + "--disable-radix-cache", + "--max-prefill-tokens", + 28672, + "--context-length", + 81920, + "--max-total-tokens", + 122304, + "--dp-size", + 2, + "--enable-dp-attention", + "--enable-dp-lm-head", + "--speculative-algorithm", + "NEXTN", + "--speculative-num-steps", + 3, + "--speculative-eagle-topk", + 1, + "--speculative-num-draft-tokens", + 4, + "--speculative-draft-model-quantization", + "unquant", + "--chunked-prefill-size", + -1, + "--max-running-requests", + 16, + "--cuda-graph-bs", + 2, + 4, + 8, + "--mamba-ssm-dtype", + "bfloat16", + "--speculative-draft-model-path", + QWEN3_NEXT_80B_A3B_MODEL_PATH, +] + + +class TestQwen3Next80BA3B(TestNpuPerformanceTestCaseBase): + max_attempts = 5 + model = QWEN3_NEXT_80B_A3B_W8A8_MODEL_PATH + other_args = QWEN3_NEXT_80B_A3B_OTHER_ARGS + envs = QWEN3_NEXT_80B_A3B_ENVS + dataset_name = "random" + max_concurrency = 16 + num_prompts = 16 + input_len = 6144 + output_len = 1500 + random_range_ratio = 1 + tpot = 15.62 + + def test_qwen3_next_80b_a3b(self): + self.run_throughput() + + +class TestQwen3Next80BA3B_aime25(TestNpuAccuracyTestCaseBase): + model = QWEN3_NEXT_80B_A3B_W8A8_MODEL_PATH + envs = QWEN3_NEXT_80B_A3B_ENVS + other_args = QWEN3_NEXT_80B_A3B_OTHER_ARGS + accuracy = 0.695 + datasets = ["aime25"] + few_shot_num = 0 + generation_config = { + "max_tokens": 65536, + "temperature": 0.7, + "top_p": 0.8, + "top_k": 20, + "extra_body": {"chat_template_kwargs": {"enable_thinking": True}}, + } + max_concurrency = 16 + + def test_aime25(self): + self.run_accuracy() + + +if __name__ == "__main__": + unittest.main() diff --git a/asian_ai/performance/SGLang/test/registered/ascend/rerank_models/test_npu_bge_reranker_v2_m3.py b/asian_ai/performance/SGLang/test/registered/ascend/rerank_models/test_npu_bge_reranker_v2_m3.py new file mode 100644 index 0000000000000000000000000000000000000000..8e1a97d64f2695085db60aa8df59036d55e888c2 --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/ascend/rerank_models/test_npu_bge_reranker_v2_m3.py @@ -0,0 +1,98 @@ +import multiprocessing as mp +import unittest + +import torch + +from sglang.test.ascend.test_ascend_utils import BGE_RERANKER_V2_M3_WEIGHTS_PATH +from sglang.test.ci.ci_register import register_npu_ci +from sglang.test.runners import TEST_RERANK_QUERY_DOCS, HFRunner, SRTRunner +from sglang.test.test_utils import CustomTestCase + +register_npu_ci( + est_time=400, + suite="nightly-1-npu-a3", + nightly=True, +) + +MODELS = [ + (BGE_RERANKER_V2_M3_WEIGHTS_PATH, 1, 1e-2), +] +ATTENTION_BACKEND = ["ascend"] +TORCH_DTYPES = [torch.bfloat16] + + +class TestBgeReranker(CustomTestCase): + """Testcase: This test case validates that the cross-encoder scores from the BAAI/bge-reranker-v2-m3 model in the + SGLang framework are less than 1e-2 different from the Hugging Face implementation. + + [Test Category] Model + [Test Target] BAAI/bge-reranker-v2-m3 + """ + + @classmethod + def setUpClass(cls): + mp.set_start_method("spawn", force=True) + + def assert_close_prefill_logits( + self, + prompts, + model_path, + tp_size, + torch_dtype, + score_tolerance, + attention_backend, + ) -> None: + with HFRunner( + model_path, + torch_dtype=torch_dtype, + model_type="cross_encoder", + ) as hf_runner: + hf_scores = hf_runner.forward(prompts).scores + + with SRTRunner( + model_path, + tp_size=tp_size, + torch_dtype=torch_dtype, + model_type="cross_encoder", + attention_backend=attention_backend, + chunked_prefill_size=-1, + disable_radix_cache=True, + ) as srt_runner: + srt_scores = srt_runner.forward(prompts).scores + + for i in range(len(srt_scores)): + score_difference = abs(hf_scores[i] - srt_scores[i]) + + assert ( + score_difference < score_tolerance + ), "cross encoder scores are not all close" + + def preprocess_prompts(self, prompt): + processed_prompts = [] + query = prompt["query"] + documents = prompt["documents"] + for document in documents: + processed_prompts.append([query, document]) + + return processed_prompts + + def test_prefill_logits(self): + models_to_test = MODELS + + for model, tp_size, prefill_tolerance in models_to_test: + for attention_backend in ATTENTION_BACKEND: + for queryDocs in TEST_RERANK_QUERY_DOCS: + prompts = self.preprocess_prompts(queryDocs) + for torch_dtype in TORCH_DTYPES: + self.assert_close_prefill_logits( + prompts, + model, + tp_size, + torch_dtype, + prefill_tolerance, + attention_backend, + ) + + +if __name__ == "__main__": + unittest.main() diff --git a/asian_ai/performance/SGLang/test/registered/ascend/reward_models/test_npu_gemma_2_27b_v0_2.py b/asian_ai/performance/SGLang/test/registered/ascend/reward_models/test_npu_gemma_2_27b_v0_2.py new file mode 100644 index 0000000000000000000000000000000000000000..1c1ef36bb6068bf6766f661d018b1cf37f9602fe --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/ascend/reward_models/test_npu_gemma_2_27b_v0_2.py @@ -0,0 +1,88 @@ +import logging +import multiprocessing as mp +import os +import unittest + +import torch + +from sglang.test.ci.ci_register import register_npu_ci +from sglang.test.runners import HFRunner, SRTRunner +from sglang.test.test_utils import CustomTestCase + +logger = logging.getLogger(__name__) +register_npu_ci(est_time=400, suite="full-1-npu-a3", nightly=True) + +MODELS = [ + ( + "/root/.cache/modelscope/hub/models/AI-ModelScope/Skywork-Reward-Gemma-2-27B-v0.2", + 1, + 4e-2, + ), +] +TORCH_DTYPES = [torch.bfloat16] + +PROMPT = ( + "What is the range of the numeric output of a sigmoid node in a neural network?" +) +RESPONSE1 = "The output of a sigmoid node is bounded between -1 and 1." +RESPONSE2 = "The output of a sigmoid node is bounded between 0 and 1." + +CONVS = [ + [{"role": "user", "content": PROMPT}, {"role": "assistant", "content": RESPONSE1}], + [{"role": "user", "content": PROMPT}, {"role": "assistant", "content": RESPONSE2}], +] + + +class TestRewardModels(CustomTestCase): + + @classmethod + def setUpClass(cls): + mp.set_start_method("spawn", force=True) + + def assert_close_reward_scores( + self, + convs, + model_path, + tp_size, + torch_dtype, + tolerance, + ) -> None: + with HFRunner( + model_path, + torch_dtype=torch_dtype, + model_type="reward", + ) as hf_runner: + hf_outputs = hf_runner.forward(convs) + + with SRTRunner( + model_path, + torch_dtype=torch_dtype, + model_type="reward", + mem_fraction_static=0.95, + ) as srt_runner: + prompts = srt_runner.tokenizer.apply_chat_template( + convs, tokenize=False, return_dict=False + ) + srt_outputs = srt_runner.forward(prompts) + + hf_scores = torch.tensor(hf_outputs.scores) + srt_scores = torch.tensor(srt_outputs.scores) + logger.info(f"{hf_scores=}") + logger.info(f"{srt_scores=}") + + assert torch.all( + abs(hf_scores - srt_scores) < tolerance + ), "reward scores are not all close" + + def test_reward_scores(self): + for model, tp_size, tolerance in MODELS: + for torch_dtype in TORCH_DTYPES: + self.assert_close_reward_scores( + CONVS, model, tp_size, torch_dtype, tolerance + ) + + +if __name__ == "__main__": + os.environ["SGLANG_NPU_FORWARD_NATIVE_GELUTANH"] = "1" + os.environ["SGLANG_NPU_FORWARD_NATIVE_GEMMA_RMS_NORM"] = "1" + unittest.main() diff --git a/asian_ai/performance/SGLang/test/registered/ascend/reward_models/test_npu_internlm2_7b_reward.py b/asian_ai/performance/SGLang/test/registered/ascend/reward_models/test_npu_internlm2_7b_reward.py new file mode 100644 index 0000000000000000000000000000000000000000..dbcb196ab49b2408226904a7d5640e38fb2e6cf0 --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/ascend/reward_models/test_npu_internlm2_7b_reward.py @@ -0,0 +1,65 @@ +import os + +os.environ["PROTOCOL_BUFFERS_PYTHON_IMPLEMENTATION"] = "python" +import multiprocessing as mp +import unittest + +import torch + +from sglang.test.ascend.test_ascend_utils import INTERNLM2_7B_REWARD_WEIGHTS_PATH +from sglang.test.ci.ci_register import register_npu_ci +from sglang.test.runners import SRTRunner +from sglang.test.test_utils import CustomTestCase + +register_npu_ci( + est_time=400, + suite="full-4-npu-a3", + nightly=True, +) + +PROMPT = ( + "What is the range of the numeric output of a sigmoid node in a neural network?" +) +RESPONSE1 = "The output of a sigmoid node is bounded between -1 and 1." +RESPONSE2 = "The output of a sigmoid node is bounded between 0 and 1." + +CONVS = [ + [{"role": "user", "content": PROMPT}, {"role": "assistant", "content": RESPONSE1}], + [{"role": "user", "content": PROMPT}, {"role": "assistant", "content": RESPONSE2}], +] + + +class TestInternlm2(CustomTestCase): + """Testcase: This test case verifies that the Shanghai_AI_Laboratory/internlm2-7b-reward model can successfully generate reward + scores for different conversational responses using the SGLang framework, without comparing to a reference implementation. + + [Test Category] Model + [Test Target] Shanghai_AI_Laboratory/internlm2-7b-reward + """ + + model_path = INTERNLM2_7B_REWARD_WEIGHTS_PATH + torch_dtype = torch.float16 + + @classmethod + def setUpClass(cls): + mp.set_start_method("spawn", force=True) + + def test_assert_close_reward_scores(self): + with SRTRunner( + self.model_path, + torch_dtype=self.torch_dtype, + model_type="reward", + trust_remote_code=True, + disable_cuda_graph=True, + tp_size=4, + mem_fraction_static=0.8, + ) as srt_runner: + prompts = srt_runner.tokenizer.apply_chat_template(CONVS, tokenize=False) + srt_outputs = srt_runner.forward(prompts) + srt_scores = torch.tensor(srt_outputs.scores) + print(f"accuracy: {srt_scores}") + self.assertIsInstance(srt_scores, torch.Tensor) + + +if __name__ == "__main__": + unittest.main() diff --git a/asian_ai/performance/SGLang/test/registered/ascend/reward_models/test_npu_llama_3_1_8b_v0_2.py b/asian_ai/performance/SGLang/test/registered/ascend/reward_models/test_npu_llama_3_1_8b_v0_2.py new file mode 100644 index 0000000000000000000000000000000000000000..530a21430c78b50a79a98ff24e467d672ee788fd --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/ascend/reward_models/test_npu_llama_3_1_8b_v0_2.py @@ -0,0 +1,86 @@ +import multiprocessing as mp +import unittest + +import torch + +from sglang.test.ascend.test_ascend_utils import ( + SKYWORK_REWARD_LLAMA_3_1_8B_V0_2_WEIGHTS_PATH, +) +from sglang.test.ci.ci_register import register_npu_ci +from sglang.test.runners import HFRunner, SRTRunner +from sglang.test.test_utils import CustomTestCase + +register_npu_ci(est_time=400, suite="full-1-npu-a3", nightly=True) + +MODELS = [ + (SKYWORK_REWARD_LLAMA_3_1_8B_V0_2_WEIGHTS_PATH, 1, 4e-2), +] +TORCH_DTYPES = [torch.float16] + +PROMPT = ( + "What is the range of the numeric output of a sigmoid node in a neural network?" +) +RESPONSE1 = "The output of a sigmoid node is bounded between -1 and 1." +RESPONSE2 = "The output of a sigmoid node is bounded between 0 and 1." + +CONVS = [ + [{"role": "user", "content": PROMPT}, {"role": "assistant", "content": RESPONSE1}], + [{"role": "user", "content": PROMPT}, {"role": "assistant", "content": RESPONSE2}], +] + + +class TestLlama(CustomTestCase): + """Testcase: This test case validates that the reward scores from the Skywork/Skywork-Reward-Llama-3.1-8B-v0.2 model + in the SGLang framework are less than 4e-2 different from the Hugging Face implementation. + + [Test Category] Model + [Test Target] Skywork/Skywork-Reward-Llama-3.1-8B-v0.2 + """ + + @classmethod + def setUpClass(cls): + mp.set_start_method("spawn", force=True) + + def assert_close_reward_scores( + self, + convs, + model_path, + tp_size, + torch_dtype, + tolerance, + ) -> None: + with HFRunner( + model_path, + torch_dtype=torch_dtype, + model_type="reward", + ) as hf_runner: + hf_outputs = hf_runner.forward(convs) + + with SRTRunner( + model_path, + tp_size=tp_size, + torch_dtype=torch_dtype, + model_type="reward", + ) as srt_runner: + prompts = srt_runner.tokenizer.apply_chat_template(convs, tokenize=False) + srt_outputs = srt_runner.forward(prompts) + + hf_scores = torch.tensor(hf_outputs.scores) + srt_scores = torch.tensor(srt_outputs.scores) + print(f"{hf_scores=}") + print(f"{srt_scores=}") + + assert torch.all( + abs(hf_scores - srt_scores) < tolerance + ), "reward scores are not all close" + + def test_reward_scores(self): + for model, tp_size, tolerance in MODELS: + for torch_dtype in TORCH_DTYPES: + self.assert_close_reward_scores( + CONVS, model, tp_size, torch_dtype, tolerance + ) + + +if __name__ == "__main__": + unittest.main() diff --git a/asian_ai/performance/SGLang/test/registered/ascend/test_npu_memory_consumption.py b/asian_ai/performance/SGLang/test/registered/ascend/test_npu_memory_consumption.py new file mode 100644 index 0000000000000000000000000000000000000000..5f68c777a6b4b611d256791354e0e927b6a58ec2 --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/ascend/test_npu_memory_consumption.py @@ -0,0 +1,83 @@ +""" +Usage: +python3 -m unittest test_ascend_memory_consumption.TestMemoryConsumptionAscend.test_memory_consumption +""" + +import os +import unittest + +import torch + +from sglang.srt.utils import kill_process_tree +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, +) + +if "ASCEND_RT_VISIBLE_DEVICES" not in os.environ: + os.environ["ASCEND_RT_VISIBLE_DEVICES"] = "0,1" +DEFAULT_PORT_FOR_SRT_TEST_RUNNER = ( + 8000 + int(os.environ.get("ASCEND_RT_VISIBLE_DEVICES", "0")[0]) * 100 +) +DEFAULT_URL_FOR_TEST = f"http://127.0.0.1:{DEFAULT_PORT_FOR_SRT_TEST_RUNNER + 1000}" + + +class TestMemoryConsumptionAscend(CustomTestCase): + + def test_memory_consumption(self): + + model = "/root/.cache/modelscope/hub/models/Qwen/Qwen3-30B-A3B-w8a8" + base_url = DEFAULT_URL_FOR_TEST + + ### Calculate initial used memory + free_npu_memory, total_npu_memory = torch.npu.mem_get_info() + initial_used_memory = total_npu_memory - free_npu_memory + + process = popen_launch_server( + model, + base_url, + timeout=DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH, + other_args=[ + "--trust-remote-code", + "--device", + "npu", + "--attention-backend", + "ascend", + "--tp-size", + "2", + "--mem-fraction-static", + "0.8", + "--cuda-graph-bs", + "1", + "--max-total-tokens", + "1024", + "--disable-radix-cache", + "--disable-cuda-graph", + ], + env={ + "TRANSFORMERS_VERBOSITY": "error", + }, + ) + + ### Calculate initial used memory + free_npu_memory, total_npu_memory = torch.npu.mem_get_info() + used_memory_after_server_starting = ( + total_npu_memory - free_npu_memory - initial_used_memory + ) / (1 << 30) + self.assertLessEqual(float(used_memory_after_server_starting), 17.00) + + # Clean up everything + kill_process_tree(process.pid) + + +if __name__ == "__main__": + unittest.main() diff --git a/asian_ai/performance/SGLang/test/registered/ascend/vlm_models/mmmu-val.yaml b/asian_ai/performance/SGLang/test/registered/ascend/vlm_models/mmmu-val.yaml new file mode 100644 index 0000000000000000000000000000000000000000..fa2c4fbcf7b4ee6c2c96e94c7711741093158e58 --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/ascend/vlm_models/mmmu-val.yaml @@ -0,0 +1 @@ +dataset_path: /root/.cache/huggingface/hub/datasets--lmms-lab--MMMU/snapshots/364f2e2eb107b36e07ff4c5a15f5947a759cef47 diff --git a/asian_ai/performance/SGLang/test/registered/ascend/vlm_models/test_ascend_glm_4_5v.py b/asian_ai/performance/SGLang/test/registered/ascend/vlm_models/test_ascend_glm_4_5v.py new file mode 100644 index 0000000000000000000000000000000000000000..7862df605380d739ca2a3be7aa3db153b8110ca4 --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/ascend/vlm_models/test_ascend_glm_4_5v.py @@ -0,0 +1,33 @@ +import unittest + +from sglang.test.ascend.vlm_utils import TestVLMModels +from sglang.test.ci.ci_register import register_npu_ci + +register_npu_ci(est_time=400, suite="nightly-8-npu-a3", nightly=True) + + +class TestGLM4Models(TestVLMModels): + model = "/root/.cache/modelscope/hub/models/ZhipuAI/GLM-4.5V" + mmmu_accuracy = 0.2 + other_args = [ + "--trust-remote-code", + "--cuda-graph-max-bs-decode", + "32", + "--enable-multimodal", + "--mem-fraction-static", + 0.7, + "--log-level", + "info", + "--attention-backend", + "ascend", + "--disable-cuda-graph", + "--tp-size", + 8, + ] + + def test_vlm_mmmu_benchmark(self): + self._run_vlm_mmmu_test() + + +if __name__ == "__main__": + unittest.main() diff --git a/asian_ai/performance/SGLang/test/registered/ascend/vlm_models/test_npu_deepseek_vl2.py b/asian_ai/performance/SGLang/test/registered/ascend/vlm_models/test_npu_deepseek_vl2.py new file mode 100644 index 0000000000000000000000000000000000000000..f62702bd9a4203414ab78b2d570b45282ac3846e --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/ascend/vlm_models/test_npu_deepseek_vl2.py @@ -0,0 +1,29 @@ +import unittest + +from sglang.test.ascend.test_ascend_utils import DEEPSEEK_VL2_WEIGHTS_PATH +from sglang.test.ascend.vlm_utils import TestVLMModels +from sglang.test.ci.ci_register import register_npu_ci + +register_npu_ci( + est_time=400, + suite="nightly-4-npu-a3", + nightly=True, +) + + +class TestDeepseekVl2(TestVLMModels): + """Testcase: Verify that the inference accuracy of the deepseek-ai/deepseek-vl2 model on the MMMU dataset is no less than 0.2. + + [Test Category] Model + [Test Target] deepseek-ai/deepseek-vl2 + """ + + model = DEEPSEEK_VL2_WEIGHTS_PATH + mmmu_accuracy = 0.2 + + def test_vlm_mmmu_benchmark(self): + self._run_vlm_mmmu_test() + + +if __name__ == "__main__": + unittest.main() diff --git a/asian_ai/performance/SGLang/test/registered/ascend/vlm_models/test_npu_gemma_3_4b_it.py b/asian_ai/performance/SGLang/test/registered/ascend/vlm_models/test_npu_gemma_3_4b_it.py new file mode 100644 index 0000000000000000000000000000000000000000..bc2d1e825aaa5a9eb1278e2ac1b912ae7b7150f3 --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/ascend/vlm_models/test_npu_gemma_3_4b_it.py @@ -0,0 +1,25 @@ +import unittest + +from sglang.test.ascend.test_ascend_utils import GEMMA_3_4B_IT_WEIGHTS_PATH +from sglang.test.ascend.vlm_utils import TestVLMModels +from sglang.test.ci.ci_register import register_npu_ci + +register_npu_ci(est_time=400, suite="nightly-4-npu-a3", nightly=True) + + +class TestGemma34bModels(TestVLMModels): + """Testcase: Verify that the inference accuracy of the google/gemma-3-4b-it model on the MMMU dataset is no less than 0.2. + + [Test Category] Model + [Test Target] google/gemma-3-4b-it + """ + + model = GEMMA_3_4B_IT_WEIGHTS_PATH + mmmu_accuracy = 0.2 + + def test_vlm_mmmu_benchmark(self): + self._run_vlm_mmmu_test() + + +if __name__ == "__main__": + unittest.main() diff --git a/asian_ai/performance/SGLang/test/registered/ascend/vlm_models/test_npu_janus_pro_1b.py b/asian_ai/performance/SGLang/test/registered/ascend/vlm_models/test_npu_janus_pro_1b.py new file mode 100644 index 0000000000000000000000000000000000000000..cb8cbf86565003c4b74763aa7ca6d20b6cd03d4d --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/ascend/vlm_models/test_npu_janus_pro_1b.py @@ -0,0 +1,25 @@ +import unittest + +from sglang.test.ascend.test_ascend_utils import JANUS_PRO_1B_WEIGHTS_PATH +from sglang.test.ascend.vlm_utils import TestVLMModels +from sglang.test.ci.ci_register import register_npu_ci + +register_npu_ci(est_time=400, suite="nightly-4-npu-a3", nightly=True) + + +class TestJanusPro1B(TestVLMModels): + """Testcase: Verify that the inference accuracy of the deepseek-ai/Janus-Pro-1B model on the MMMU dataset is no less than 0.2. + + [Test Category] Model + [Test Target] deepseek-ai/Janus-Pro-1B + """ + + model = JANUS_PRO_1B_WEIGHTS_PATH + mmmu_accuracy = 0.2 + + def test_vlm_mmmu_benchmark(self): + self._run_vlm_mmmu_test() + + +if __name__ == "__main__": + unittest.main() diff --git a/asian_ai/performance/SGLang/test/registered/ascend/vlm_models/test_npu_janus_pro_7b.py b/asian_ai/performance/SGLang/test/registered/ascend/vlm_models/test_npu_janus_pro_7b.py new file mode 100644 index 0000000000000000000000000000000000000000..c6b933ab63fc590271a20353d67715bc872838cc --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/ascend/vlm_models/test_npu_janus_pro_7b.py @@ -0,0 +1,25 @@ +import unittest + +from sglang.test.ascend.test_ascend_utils import JANUS_PRO_7B_WEIGHTS_PATH +from sglang.test.ascend.vlm_utils import TestVLMModels +from sglang.test.ci.ci_register import register_npu_ci + +register_npu_ci(est_time=400, suite="nightly-4-npu-a3", nightly=True) + + +class TestJanusPro7B(TestVLMModels): + """Testcase: Verify that the inference accuracy of the deepseek-ai/Janus-Pro-7B model on the MMMU dataset is no less than 0.2. + + [Test Category] Model + [Test Target] deepseek-ai/Janus-Pro-7B + """ + + model = JANUS_PRO_7B_WEIGHTS_PATH + mmmu_accuracy = 0.2 + + def test_vlm_mmmu_benchmark(self): + self._run_vlm_mmmu_test() + + +if __name__ == "__main__": + unittest.main() diff --git a/asian_ai/performance/SGLang/test/registered/ascend/vlm_models/test_npu_kimi_vl_a3b_instruct.py b/asian_ai/performance/SGLang/test/registered/ascend/vlm_models/test_npu_kimi_vl_a3b_instruct.py new file mode 100644 index 0000000000000000000000000000000000000000..908eed0b8d4f6832e6d4500857b64d2fe87651bb --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/ascend/vlm_models/test_npu_kimi_vl_a3b_instruct.py @@ -0,0 +1,29 @@ +import unittest + +from sglang.test.ascend.test_ascend_utils import KIMI_VL_A3B_INSTRUCT_WEIGHTS_PATH +from sglang.test.ascend.vlm_utils import TestVLMModels +from sglang.test.ci.ci_register import register_npu_ci + +register_npu_ci( + est_time=400, + suite="nightly-4-npu-a3", + nightly=True, +) + + +class TestKimiVLA3BInstruct(TestVLMModels): + """Testcase: Verify that the inference accuracy of the moonshotai/Kimi-VL-A3B-Instruct model on the MMMU dataset is no less than 0.2. + + [Test Category] Model + [Test Target] moonshotai/Kimi-VL-A3B-Instruct + """ + + model = KIMI_VL_A3B_INSTRUCT_WEIGHTS_PATH + mmmu_accuracy = 0.2 + + def test_vlm_mmmu_benchmark(self): + self._run_vlm_mmmu_test() + + +if __name__ == "__main__": + unittest.main() diff --git a/asian_ai/performance/SGLang/test/registered/ascend/vlm_models/test_npu_llama_3_2_11b_vision_instruct.py b/asian_ai/performance/SGLang/test/registered/ascend/vlm_models/test_npu_llama_3_2_11b_vision_instruct.py new file mode 100644 index 0000000000000000000000000000000000000000..b34febfe75528a144dd658d346ae589b26efe36c --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/ascend/vlm_models/test_npu_llama_3_2_11b_vision_instruct.py @@ -0,0 +1,36 @@ +import unittest + +from sglang.test.ascend.test_ascend_utils import ( + LLAMA_3_2_11B_VISION_INSTRUCT_WEIGHTS_PATH, +) +from sglang.test.ascend.vlm_utils import TestVLMModels +from sglang.test.ci.ci_register import register_npu_ci + +register_npu_ci(est_time=400, suite="nightly-1-npu-a3", nightly=True) + + +class TestLlama3211BVisionInstruct(TestVLMModels): + """Testcase: Verify that the inference accuracy of the LLM-Research/Llama-3.2-11B-Vision-Instruct model on the MMMU dataset is no less than 0.2. + + [Test Category] Model + [Test Target] LLM-Research/Llama-3.2-11B-Vision-Instruct + """ + + model = LLAMA_3_2_11B_VISION_INSTRUCT_WEIGHTS_PATH + mmmu_accuracy = 0.2 + other_args = [ + "--trust-remote-code", + "--mem-fraction-static", + "0.8", + "--attention-backend", + "ascend", + "--disable-cuda-graph", + "--disable-radix-cache", + ] + + def test_vlm_mmmu_benchmark(self): + self._run_vlm_mmmu_test() + + +if __name__ == "__main__": + unittest.main() diff --git a/asian_ai/performance/SGLang/test/registered/ascend/vlm_models/test_npu_mimo_vl_7b_rl.py b/asian_ai/performance/SGLang/test/registered/ascend/vlm_models/test_npu_mimo_vl_7b_rl.py new file mode 100644 index 0000000000000000000000000000000000000000..b94ed5c8e634b6252989829e19cccf45caed5ec4 --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/ascend/vlm_models/test_npu_mimo_vl_7b_rl.py @@ -0,0 +1,25 @@ +import unittest + +from sglang.test.ascend.test_ascend_utils import MIMO_VL_7B_RL_WEIGHTS_PATH +from sglang.test.ascend.vlm_utils import TestVLMModels +from sglang.test.ci.ci_register import register_npu_ci + +register_npu_ci(est_time=400, suite="nightly-4-npu-a3", nightly=True) + + +class TestMiMoModels(TestVLMModels): + """Testcase: Verify that the inference accuracy of the XiaomiMiMo/MiMo-VL-7B-RL model on the MMMU dataset is no less than 0.2. + + [Test Category] Model + [Test Target] XiaomiMiMo/MiMo-VL-7B-RL + """ + + model = MIMO_VL_7B_RL_WEIGHTS_PATH + mmmu_accuracy = 0.2 + + def test_vlm_mmmu_benchmark(self): + self._run_vlm_mmmu_test() + + +if __name__ == "__main__": + unittest.main() diff --git a/asian_ai/performance/SGLang/test/registered/ascend/vlm_models/test_npu_minicpm_o_2_6.py b/asian_ai/performance/SGLang/test/registered/ascend/vlm_models/test_npu_minicpm_o_2_6.py new file mode 100644 index 0000000000000000000000000000000000000000..d7f10e6ea473eb7fcbe6faf567f615b479c783aa --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/ascend/vlm_models/test_npu_minicpm_o_2_6.py @@ -0,0 +1,29 @@ +import unittest + +from sglang.test.ascend.test_ascend_utils import MINICPM_O_2_6_WEIGHTS_PATH +from sglang.test.ascend.vlm_utils import TestVLMModels +from sglang.test.ci.ci_register import register_npu_ci + +register_npu_ci( + est_time=400, + suite="nightly-4-npu-a3", + nightly=True, +) + + +class TestMiniCPMModelsO(TestVLMModels): + """Testcase: Verify that the inference accuracy of the openbmb/MiniCPM-o-2_6 model on the MMMU dataset is no less than 0.2. + + [Test Category] Model + [Test Target] openbmb/MiniCPM-o-2_6 + """ + + model = MINICPM_O_2_6_WEIGHTS_PATH + mmmu_accuracy = 0.2 + + def test_vlm_mmmu_benchmark(self): + self._run_vlm_mmmu_test() + + +if __name__ == "__main__": + unittest.main() diff --git a/asian_ai/performance/SGLang/test/registered/ascend/vlm_models/test_npu_minicpm_v_2_6.py b/asian_ai/performance/SGLang/test/registered/ascend/vlm_models/test_npu_minicpm_v_2_6.py new file mode 100644 index 0000000000000000000000000000000000000000..4414b24f8cef7d5c2bdf285dbb3e9d5903ba40e7 --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/ascend/vlm_models/test_npu_minicpm_v_2_6.py @@ -0,0 +1,25 @@ +import unittest + +from sglang.test.ascend.test_ascend_utils import MINICPM_V_2_6_WEIGHTS_PATH +from sglang.test.ascend.vlm_utils import TestVLMModels +from sglang.test.ci.ci_register import register_npu_ci + +register_npu_ci(est_time=400, suite="nightly-4-npu-a3", nightly=True) + + +class TestMiniCPMModelsV(TestVLMModels): + """Testcase: Verify that the inference accuracy of the openbmb/MiniCPM-V-2_6 model on the MMMU dataset is no less than 0.2. + + [Test Category] Model + [Test Target] openbmb/MiniCPM-V-2_6 + """ + + model = MINICPM_V_2_6_WEIGHTS_PATH + mmmu_accuracy = 0.2 + + def test_vlm_mmmu_benchmark(self): + self._run_vlm_mmmu_test() + + +if __name__ == "__main__": + unittest.main() diff --git a/asian_ai/performance/SGLang/test/registered/ascend/vlm_models/test_npu_mistral_small_3_1_24b_instruct_2503.py b/asian_ai/performance/SGLang/test/registered/ascend/vlm_models/test_npu_mistral_small_3_1_24b_instruct_2503.py new file mode 100644 index 0000000000000000000000000000000000000000..90c8b71b1c10edcfa9dc7a5e0ddfec34f8a3249b --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/ascend/vlm_models/test_npu_mistral_small_3_1_24b_instruct_2503.py @@ -0,0 +1,27 @@ +import unittest + +from sglang.test.ascend.test_ascend_utils import ( + MISTRAL_SMALL_3_1_24B_INSTRUCT_2503_WEIGHTS_PATH, +) +from sglang.test.ascend.vlm_utils import TestVLMModels +from sglang.test.ci.ci_register import register_npu_ci + +register_npu_ci(est_time=400, suite="nightly-4-npu-a3", nightly=True) + + +class TestMistralModels(TestVLMModels): + """Testcase: Verify that the inference accuracy of the mistralai/Mistral-Small-3.1-24B-Instruct-2503 model on the MMMU dataset is no less than 0.2. + + [Test Category] Model + [Test Target] mistralai/Mistral-Small-3.1-24B-Instruct-2503 + """ + + model = MISTRAL_SMALL_3_1_24B_INSTRUCT_2503_WEIGHTS_PATH + mmmu_accuracy = 0.2 + + def test_vlm_mmmu_benchmark(self): + self._run_vlm_mmmu_test() + + +if __name__ == "__main__": + unittest.main() diff --git a/asian_ai/performance/SGLang/test/registered/ascend/vlm_models/test_npu_phi4_multimodal_instruct.py b/asian_ai/performance/SGLang/test/registered/ascend/vlm_models/test_npu_phi4_multimodal_instruct.py new file mode 100644 index 0000000000000000000000000000000000000000..c709942654ab6f5ada28b5de533be94602f6fdd7 --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/ascend/vlm_models/test_npu_phi4_multimodal_instruct.py @@ -0,0 +1,25 @@ +import unittest + +from sglang.test.ascend.test_ascend_utils import PHI_4_MULTIMODAL_INSTRUCT_WEIGHTS_PATH +from sglang.test.ascend.vlm_utils import TestVLMModels +from sglang.test.ci.ci_register import register_npu_ci + +register_npu_ci(est_time=400, suite="nightly-4-npu-a3", nightly=True) + + +class TestPhi4Multimodal(TestVLMModels): + """Testcase: Verify that the inference accuracy of the microsoft/Phi-4-multimodal-instruct model on the MMMU dataset is no less than 0.2. + + [Test Category] Model + [Test Target] microsoft/Phi-4-multimodal-instruct + """ + + model = PHI_4_MULTIMODAL_INSTRUCT_WEIGHTS_PATH + mmmu_accuracy = 0.2 + + def test_vlm_mmmu_benchmark(self): + self._run_vlm_mmmu_test() + + +if __name__ == "__main__": + unittest.main() diff --git a/asian_ai/performance/SGLang/test/registered/ascend/vlm_models/test_npu_qwen2_5_vl_3b_instruct.py b/asian_ai/performance/SGLang/test/registered/ascend/vlm_models/test_npu_qwen2_5_vl_3b_instruct.py new file mode 100644 index 0000000000000000000000000000000000000000..4d5483ca63742f29ea4334830b79d1eed5257df9 --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/ascend/vlm_models/test_npu_qwen2_5_vl_3b_instruct.py @@ -0,0 +1,25 @@ +import unittest + +from sglang.test.ascend.test_ascend_utils import QWEN2_5_VL_3B_INSTRUCT_WEIGHTS_PATH +from sglang.test.ascend.vlm_utils import TestVLMModels +from sglang.test.ci.ci_register import register_npu_ci + +register_npu_ci(est_time=400, suite="nightly-4-npu-a3", nightly=True) + + +class TestQwen25VL3B(TestVLMModels): + """Testcase: Verify that the inference accuracy of the Qwen/Qwen2.5-VL-3B-Instruct model on the MMMU dataset is no less than 0.2. + + [Test Category] Model + [Test Target] Qwen/Qwen2.5-VL-3B-Instruct + """ + + model = QWEN2_5_VL_3B_INSTRUCT_WEIGHTS_PATH + mmmu_accuracy = 0.2 + + def test_vlm_mmmu_benchmark(self): + self._run_vlm_mmmu_test() + + +if __name__ == "__main__": + unittest.main() diff --git a/asian_ai/performance/SGLang/test/registered/ascend/vlm_models/test_npu_qwen2_5_vl_72b_instruct.py b/asian_ai/performance/SGLang/test/registered/ascend/vlm_models/test_npu_qwen2_5_vl_72b_instruct.py new file mode 100644 index 0000000000000000000000000000000000000000..3a6960f22b5de87f5fe079fec01f1e15ee2afecc --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/ascend/vlm_models/test_npu_qwen2_5_vl_72b_instruct.py @@ -0,0 +1,40 @@ +import unittest + +from sglang.test.ascend.test_ascend_utils import QWEN2_5_VL_72B_INSTRUCT_WEIGHTS_PATH +from sglang.test.ascend.vlm_utils import TestVLMModels +from sglang.test.ci.ci_register import register_npu_ci + +register_npu_ci(est_time=400, suite="nightly-8-npu-a3", nightly=True) + + +class TestQwen25VL72B(TestVLMModels): + """Testcase: Verify that the inference accuracy of the Qwen/Qwen2.5-VL-72B-Instruct model on the MMMU dataset is no less than 0.2. + + [Test Category] Model + [Test Target] Qwen/Qwen2.5-VL-72B-Instruct + """ + + model = QWEN2_5_VL_72B_INSTRUCT_WEIGHTS_PATH + mmmu_accuracy = 0.2 + other_args = [ + "--trust-remote-code", + "--cuda-graph-max-bs-decode", + "32", + "--enable-multimodal", + "--mem-fraction-static", + 0.6, + "--log-level", + "info", + "--attention-backend", + "ascend", + "--disable-cuda-graph", + "--tp-size", + 8, + ] + + def test_vlm_mmmu_benchmark(self): + self._run_vlm_mmmu_test() + + +if __name__ == "__main__": + unittest.main() diff --git a/asian_ai/performance/SGLang/test/registered/ascend/vlm_models/test_npu_qwen3_vl_235b_a22b_instruct.py b/asian_ai/performance/SGLang/test/registered/ascend/vlm_models/test_npu_qwen3_vl_235b_a22b_instruct.py new file mode 100644 index 0000000000000000000000000000000000000000..9e3c8c3199ac843b19248281c19d8aab09a12d7f --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/ascend/vlm_models/test_npu_qwen3_vl_235b_a22b_instruct.py @@ -0,0 +1,41 @@ +import unittest + +from sglang.test.ascend.test_ascend_utils import ( + QWEN3_VL_235B_A22B_INSTRUCT_WEIGHTS_PATH, +) +from sglang.test.ascend.vlm_utils import TestVLMModels +from sglang.test.ci.ci_register import register_npu_ci + +register_npu_ci(est_time=400, suite="nightly-16-npu-a3", nightly=True) + + +class TestQwen3VL235BA22B(TestVLMModels): + """Testcase: Verify that the inference accuracy of the Qwen/Qwen3-VL-235B-A22B-Instruct model on the MMMU dataset is no less than 0.2. + + [Test Category] Model + [Test Target] Qwen/Qwen3-VL-235B-A22B-Instruct + """ + + model = QWEN3_VL_235B_A22B_INSTRUCT_WEIGHTS_PATH + mmmu_accuracy = 0.2 + other_args = [ + "--trust-remote-code", + "--cuda-graph-max-bs-decode", + "32", + "--enable-multimodal", + "--mem-fraction-static", + 0.8, + "--attention-backend", + "ascend", + "--disable-cuda-graph", + "--tp-size", + 16, + ] + timeout_for_server_launch = 3000 + + def test_vlm_mmmu_benchmark(self): + self._run_vlm_mmmu_test() + + +if __name__ == "__main__": + unittest.main() diff --git a/asian_ai/performance/SGLang/test/registered/ascend/vlm_models/test_npu_qwen3_vl_30b_a3b_instruct.py b/asian_ai/performance/SGLang/test/registered/ascend/vlm_models/test_npu_qwen3_vl_30b_a3b_instruct.py new file mode 100644 index 0000000000000000000000000000000000000000..2fa5d5e55b59a9f57e0393976dfa1e70426f784b --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/ascend/vlm_models/test_npu_qwen3_vl_30b_a3b_instruct.py @@ -0,0 +1,25 @@ +import unittest + +from sglang.test.ascend.test_ascend_utils import QWEN3_VL_30B_A3B_INSTRUCT_WEIGHTS_PATH +from sglang.test.ascend.vlm_utils import TestVLMModels +from sglang.test.ci.ci_register import register_npu_ci + +register_npu_ci(est_time=400, suite="nightly-4-npu-a3", nightly=True) + + +class TestQwen3VL30BA3B(TestVLMModels): + """Testcase: Verify that the inference accuracy of the Qwen/Qwen3-VL-30B-A3B-Instruct model on the MMMU dataset is no less than 0.2. + + [Test Category] Model + [Test Target] Qwen/Qwen3-VL-30B-A3B-Instruct + """ + + model = QWEN3_VL_30B_A3B_INSTRUCT_WEIGHTS_PATH + mmmu_accuracy = 0.2 + + def test_vlm_mmmu_benchmark(self): + self._run_vlm_mmmu_test() + + +if __name__ == "__main__": + unittest.main() diff --git a/asian_ai/performance/SGLang/test/registered/ascend/vlm_models/test_npu_qwen3_vl_4b_instruct.py b/asian_ai/performance/SGLang/test/registered/ascend/vlm_models/test_npu_qwen3_vl_4b_instruct.py new file mode 100644 index 0000000000000000000000000000000000000000..9a1848c8355e19b034de7039da7123134c0c82c1 --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/ascend/vlm_models/test_npu_qwen3_vl_4b_instruct.py @@ -0,0 +1,25 @@ +import unittest + +from sglang.test.ascend.test_ascend_utils import QWEN3_VL_4B_INSTRUCT_WEIGHTS_PATH +from sglang.test.ascend.vlm_utils import TestVLMModels +from sglang.test.ci.ci_register import register_npu_ci + +register_npu_ci(est_time=400, suite="full-4-npu-a3", nightly=True) + + +class TestQwen3VL4B(TestVLMModels): + """Testcase: Verify that the inference accuracy of the Qwen/Qwen3-VL-4B-Instruct model on the MMMU dataset is no less than 0.2. + + [Test Category] Model + [Test Target] Qwen/Qwen3-VL-4B-Instruct + """ + + model = QWEN3_VL_4B_INSTRUCT_WEIGHTS_PATH + mmmu_accuracy = 0.2 + + def test_vlm_mmmu_benchmark(self): + self._run_vlm_mmmu_test() + + +if __name__ == "__main__": + unittest.main() diff --git a/asian_ai/performance/SGLang/test/registered/ascend/vlm_models/test_npu_qwen3_vl_8b_instruct.py b/asian_ai/performance/SGLang/test/registered/ascend/vlm_models/test_npu_qwen3_vl_8b_instruct.py new file mode 100644 index 0000000000000000000000000000000000000000..695ac00a2fa0fc1b049dfc2a5c9bff6c65deb4a6 --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/ascend/vlm_models/test_npu_qwen3_vl_8b_instruct.py @@ -0,0 +1,25 @@ +import unittest + +from sglang.test.ascend.test_ascend_utils import QWEN3_VL_8B_INSTRUCT_WEIGHTS_PATH +from sglang.test.ascend.vlm_utils import TestVLMModels +from sglang.test.ci.ci_register import register_npu_ci + +register_npu_ci(est_time=400, suite="nightly-4-npu-a3", nightly=True) + + +class TestQwen3VL8B(TestVLMModels): + """Testcase: Verify that the inference accuracy of the Qwen/Qwen3-VL-8B-Instruct model on the MMMU dataset is no less than 0.2. + + [Test Category] Model + [Test Target] Qwen/Qwen3-VL-8B-Instruct + """ + + model = QWEN3_VL_8B_INSTRUCT_WEIGHTS_PATH + mmmu_accuracy = 0.2 + + def test_vlm_mmmu_benchmark(self): + self._run_vlm_mmmu_test() + + +if __name__ == "__main__": + unittest.main() diff --git a/asian_ai/performance/SGLang/test/registered/attention/test_chunk_gated_delta_rule.py b/asian_ai/performance/SGLang/test/registered/attention/test_chunk_gated_delta_rule.py new file mode 100644 index 0000000000000000000000000000000000000000..2b9cea2c200b4d705f2a5e48f449cc55948a97b0 --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/attention/test_chunk_gated_delta_rule.py @@ -0,0 +1,289 @@ +import unittest + +import torch + +from sglang.srt.layers.attention.fla.chunk import chunk_gated_delta_rule +from sglang.srt.layers.attention.fla.fused_recurrent import ( + fused_recurrent_gated_delta_rule, +) +from sglang.srt.utils import get_device +from sglang.test.ci.ci_register import register_cuda_ci, register_xpu_ci + +register_cuda_ci(est_time=11, stage="base-b", runner_config="1-gpu-large") +register_xpu_ci(est_time=900, suite="stage-b-test-1-gpu-xpu") + + +@unittest.skipIf( + not (torch.cuda.is_available() or torch.xpu.is_available()), + "Test requires CUDA or XPU", +) +class TestChunkGatedDeltaRule(unittest.TestCase): + """Test chunk_gated_delta_rule against token-by-token fused_recurrent reference.""" + + ATOL = 2e-2 + RTOL = 1e-2 + + def _run_reference(self, pool_init, cache_indices, q, k, v, g, beta): + """Per-batch token-by-token reference using fused_recurrent_gated_delta_rule. + + initial_state shape: [N, H, V, K] (native layout on this branch). + """ + B = cache_indices.shape[0] + T_per_seq = q.shape[1] // B + pool = pool_init.clone() + h_cur = pool[cache_indices].contiguous().clone() + + o_list = [] + for b in range(B): + sl = slice(b * T_per_seq, (b + 1) * T_per_seq) + o_b, h_b = fused_recurrent_gated_delta_rule( + q=q[0, sl].unsqueeze(0), + k=k[0, sl].unsqueeze(0), + v=v[0, sl].unsqueeze(0), + g=g[0, sl].unsqueeze(0), + beta=beta[0, sl].unsqueeze(0), + initial_state=h_cur[b : b + 1], + output_final_state=True, + use_qk_l2norm_in_kernel=True, + ) + o_list.append(o_b) + h_cur[b] = h_b[0] + + pool[cache_indices] = h_cur + return torch.cat(o_list, dim=1), pool + + def _run_chunk(self, pool_init, cache_indices, q, k, v, g, beta, cu_seqlens): + """Run chunk_gated_delta_rule with native [V, K] pool.""" + pool = pool_init.clone() + o, _, _ = chunk_gated_delta_rule( + q=q, + k=k, + v=v, + g=g, + beta=beta, + initial_state=pool, + initial_state_indices=cache_indices, + cu_seqlens=cu_seqlens, + head_first=False, + use_qk_l2norm_in_kernel=True, + ) + return o, pool + + def _check_shape( + self, B, T_per_seq, H, K, V, pool_size, sequential_indices=False, seed=42 + ): + """Run correctness check for one (B, T_per_seq, H, K, V, pool_size) config.""" + device = get_device() + dtype = torch.bfloat16 + T = B * T_per_seq + + torch.manual_seed(seed) + + if sequential_indices: + cache_indices = torch.arange(B, dtype=torch.int32, device=device) + else: + perm = torch.randperm(pool_size, device=device)[:B] + cache_indices = perm.to(torch.int32) + + pool_init = ( + torch.randn(pool_size, H, V, K, dtype=torch.float32, device=device) * 0.1 + ) + cu_seqlens = torch.zeros(B + 1, dtype=torch.long, device=device) + cu_seqlens[1:] = ( + torch.arange(1, B + 1, dtype=torch.long, device=device) * T_per_seq + ) + + q = torch.randn(1, T, H, K, dtype=dtype, device=device) + k = torch.randn(1, T, H, K, dtype=dtype, device=device) + v = torch.randn(1, T, H, V, dtype=dtype, device=device) + g = torch.nn.functional.logsigmoid( + torch.randn(1, T, H, dtype=dtype, device=device) + ) + beta = torch.sigmoid(torch.randn(1, T, H, dtype=dtype, device=device)) + + o_ref, pool_ref = self._run_reference( + pool_init, cache_indices, q, k, v, g, beta + ) + o_new, pool_new = self._run_chunk( + pool_init, cache_indices, q, k, v, g, beta, cu_seqlens + ) + + self.assertTrue( + torch.allclose( + o_ref.float(), o_new.float(), atol=self.ATOL, rtol=self.RTOL + ), + f"Output mismatch: max_diff=" + f"{(o_ref.float() - o_new.float()).abs().max().item():.2e}", + ) + + ref_slots = pool_ref[cache_indices].contiguous() + new_slots = pool_new[cache_indices].contiguous() + self.assertTrue( + torch.allclose( + ref_slots.float(), new_slots.float(), atol=self.ATOL, rtol=self.RTOL + ), + f"State mismatch: max_diff=" + f"{(ref_slots.float() - new_slots.float()).abs().max().item():.2e}", + ) + + # ------------------------------------------------------------------ + # Production-style configs (Qwen3-Next) + # ------------------------------------------------------------------ + def test_production_nt1(self): + self._check_shape(B=4, T_per_seq=64, H=16, K=128, V=128, pool_size=32) + + def test_production_nt2(self): + self._check_shape(B=4, T_per_seq=128, H=16, K=128, V=128, pool_size=32) + + def test_production_nt4(self): + self._check_shape(B=4, T_per_seq=256, H=16, K=128, V=128, pool_size=32) + + # ------------------------------------------------------------------ + # Batch size sweep + # ------------------------------------------------------------------ + def test_batch_1(self): + self._check_shape(B=1, T_per_seq=128, H=16, K=128, V=128, pool_size=32) + + def test_batch_2(self): + self._check_shape(B=2, T_per_seq=128, H=16, K=128, V=128, pool_size=32) + + def test_batch_8(self): + self._check_shape(B=8, T_per_seq=128, H=16, K=128, V=128, pool_size=64) + + def test_batch_16(self): + self._check_shape(B=16, T_per_seq=64, H=16, K=128, V=128, pool_size=128) + + def test_batch_32(self): + self._check_shape(B=32, T_per_seq=32, H=16, K=128, V=128, pool_size=256) + + # ------------------------------------------------------------------ + # Head count sweep + # ------------------------------------------------------------------ + def test_heads_4(self): + self._check_shape(B=4, T_per_seq=128, H=4, K=128, V=128, pool_size=32) + + def test_heads_8(self): + self._check_shape(B=4, T_per_seq=128, H=8, K=128, V=128, pool_size=32) + + def test_heads_32(self): + self._check_shape(B=4, T_per_seq=128, H=32, K=128, V=128, pool_size=32) + + def test_heads_64(self): + self._check_shape(B=4, T_per_seq=128, H=64, K=128, V=128, pool_size=32) + + # ------------------------------------------------------------------ + # K != V (exercises that [V,K] != [K,V] byte-order matters) + # ------------------------------------------------------------------ + def test_dim_64x64(self): + self._check_shape(B=4, T_per_seq=128, H=16, K=64, V=64, pool_size=32) + + def test_dim_k_lt_v(self): + self._check_shape(B=4, T_per_seq=128, H=16, K=64, V=128, pool_size=32) + + def test_dim_k_gt_v(self): + self._check_shape(B=4, T_per_seq=128, H=16, K=128, V=64, pool_size=32) + + def test_dim_256x256(self): + self._check_shape(B=4, T_per_seq=128, H=16, K=256, V=256, pool_size=32) + + # ------------------------------------------------------------------ + # Short sequences (T < chunk_size=64) + # ------------------------------------------------------------------ + def test_seqlen_1(self): + self._check_shape(B=4, T_per_seq=1, H=16, K=128, V=128, pool_size=32) + + def test_seqlen_7(self): + self._check_shape(B=4, T_per_seq=7, H=16, K=128, V=128, pool_size=32) + + def test_seqlen_16(self): + self._check_shape(B=4, T_per_seq=16, H=16, K=128, V=128, pool_size=32) + + def test_seqlen_32(self): + self._check_shape(B=4, T_per_seq=32, H=16, K=128, V=128, pool_size=32) + + # ------------------------------------------------------------------ + # Multi-chunk and large pool + # ------------------------------------------------------------------ + def test_multi_chunk_nt8(self): + self._check_shape(B=4, T_per_seq=512, H=16, K=128, V=128, pool_size=32) + + def test_large_pool(self): + self._check_shape(B=4, T_per_seq=128, H=16, K=128, V=128, pool_size=512) + + # ------------------------------------------------------------------ + # Long prompts (many chunks; regression test for cross-chunk errors) + # ------------------------------------------------------------------ + def test_long_prompt(self): + for B, T_per_seq in [(1, 1024), (1, 1536), (1, 2048), (2, 1024)]: + with self.subTest(T_per_seq=T_per_seq): + self._check_shape( + B=B, T_per_seq=T_per_seq, H=16, K=128, V=128, pool_size=32 + ) + + # ------------------------------------------------------------------ + # Combined stress + # ------------------------------------------------------------------ + def test_stress(self): + self._check_shape(B=32, T_per_seq=128, H=32, K=128, V=128, pool_size=256) + + # ------------------------------------------------------------------ + # Sequential-index variants (pool_size == B, indices = 0..B-1) + # ------------------------------------------------------------------ + def test_seq_idx_b4(self): + self._check_shape( + B=4, + T_per_seq=128, + H=16, + K=128, + V=128, + pool_size=4, + sequential_indices=True, + ) + + def test_seq_idx_b8(self): + self._check_shape( + B=8, + T_per_seq=128, + H=16, + K=128, + V=128, + pool_size=8, + sequential_indices=True, + ) + + def test_seq_idx_h32(self): + self._check_shape( + B=4, + T_per_seq=128, + H=32, + K=128, + V=128, + pool_size=4, + sequential_indices=True, + ) + + def test_seq_idx_h64(self): + self._check_shape( + B=4, + T_per_seq=128, + H=64, + K=128, + V=128, + pool_size=4, + sequential_indices=True, + ) + + def test_seq_idx_stress(self): + self._check_shape( + B=32, + T_per_seq=128, + H=32, + K=128, + V=128, + pool_size=32, + sequential_indices=True, + ) + + +if __name__ == "__main__": + unittest.main() diff --git a/asian_ai/performance/SGLang/test/registered/attention/test_create_kvindices.py b/asian_ai/performance/SGLang/test/registered/attention/test_create_kvindices.py new file mode 100644 index 0000000000000000000000000000000000000000..078692d67d0dbd07c7b8b6615f8edc5c7c36f118 --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/attention/test_create_kvindices.py @@ -0,0 +1,80 @@ +import unittest + +import numpy as np +import torch + +from sglang.srt.layers.attention.utils import create_flashinfer_kv_indices_triton +from sglang.srt.utils import get_device +from sglang.test.ci.ci_register import register_amd_ci, register_cuda_ci +from sglang.test.test_utils import CustomTestCase + +# Triton kernel unit test for KV indices creation +register_cuda_ci(est_time=7, stage="base-b", runner_config="1-gpu-small") +register_amd_ci(est_time=10, suite="stage-b-test-1-gpu-small-amd") + + +class TestCreateKvIndices(CustomTestCase): + @classmethod + def setUpClass(cls): + torch.set_default_device(get_device()) + + def _run_test(self, batch, max_batch, max_context_len): + req_to_token = torch.arange( + max_batch * max_context_len, dtype=torch.int32, device=get_device() + ).reshape((max_batch, max_context_len)) + req_pool_indices = torch.tensor( + torch.from_numpy( + np.random.choice(range(max_batch), size=batch, replace=False) + ), + dtype=torch.int32, + device=get_device(), + ) + paged_kernel_lens = torch.tensor( + torch.from_numpy( + np.random.choice(range(max_context_len), size=batch, replace=False) + ), + dtype=torch.int32, + device=get_device(), + ) + + kv_indptr = torch.zeros((batch + 1,), dtype=torch.int32, device=get_device()) + kv_indptr[1:] = torch.cumsum(paged_kernel_lens, dim=0) + + # ref + req_pool_indices_cpu = req_pool_indices.cpu().numpy() + paged_kernel_lens_cpu = paged_kernel_lens.cpu().numpy() + kv_indices_ref = torch.cat( + [ + req_to_token[req_pool_indices_cpu[i], : paged_kernel_lens_cpu[i]] + for i in range(batch) + ], + dim=0, + ).contiguous() + + # triton + kv_indices_triton = torch.empty( + kv_indptr[-1], dtype=torch.int32, device=get_device() + ) + create_flashinfer_kv_indices_triton[(batch,)]( + req_to_token, + req_pool_indices, + paged_kernel_lens, + kv_indptr, + None, + kv_indices_triton, + req_to_token.size(1), + ) + + # Check + self.assertTrue(torch.equal(kv_indices_ref, kv_indices_triton)) + + def test_create_kvindices(self): + BATCH = [1, 37, 1786] + MAX_BATCH = 4096 + MAX_CONTEXT_LEN = 4096 + for batch in BATCH: + self._run_test(batch, MAX_BATCH, MAX_CONTEXT_LEN) + + +if __name__ == "__main__": + unittest.main() diff --git a/asian_ai/performance/SGLang/test/registered/attention/test_deepseek_v3_deterministic.py b/asian_ai/performance/SGLang/test/registered/attention/test_deepseek_v3_deterministic.py new file mode 100644 index 0000000000000000000000000000000000000000..57d5e81a89ef028b35ba359c5397c62ddb2df924 --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/attention/test_deepseek_v3_deterministic.py @@ -0,0 +1,57 @@ +""" +Usage: +cd test/srt +python3 -m unittest test_deepseek_v3_deterministic.TestFa3Deterministic +""" + +import unittest + +from sglang.test.ci.ci_register import register_cuda_ci +from sglang.test.test_deterministic_utils import ( + COMMON_SERVER_ARGS, + TestDeterministicBase, +) + +register_cuda_ci(est_time=240, suite="nightly-1-gpu", nightly=True) + +DEEPSEEK_MODEL = "lmsys/sglang-ci-dsv3-test" + + +class TestFa3Deterministic(TestDeterministicBase): + @classmethod + def get_model(cls): + return DEEPSEEK_MODEL + + # Test with fa3 attention backend + @classmethod + def get_server_args(cls): + args = COMMON_SERVER_ARGS + args.extend( + [ + "--attention-backend", + "fa3", + ] + ) + return args + + +class TestTritonDeterministic(TestDeterministicBase): + @classmethod + def get_model(cls): + return DEEPSEEK_MODEL + + # Test with triton attention backend + @classmethod + def get_server_args(cls): + args = COMMON_SERVER_ARGS + args.extend( + [ + "--attention-backend", + "triton", + ] + ) + return args + + +if __name__ == "__main__": + unittest.main() diff --git a/asian_ai/performance/SGLang/test/registered/attention/test_deterministic.py b/asian_ai/performance/SGLang/test/registered/attention/test_deterministic.py new file mode 100644 index 0000000000000000000000000000000000000000..955cc9c876432e90583341d38b53d5d6e34bc0ff --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/attention/test_deterministic.py @@ -0,0 +1,68 @@ +""" +Usage: +cd test/srt +python3 -m unittest test_deterministic.TestDeterministic.TESTCASE + +Note that there is also `python/sglang/test/test_deterministic.py` as an interactive test. We are converting that +test into unit tests so that's easily reproducible in CI. +""" + +import unittest + +from sglang.test.ci.ci_register import register_amd_ci, register_cuda_ci +from sglang.test.test_deterministic_utils import ( + COMMON_SERVER_ARGS, + TestDeterministicBase, +) +from sglang.test.test_utils import is_in_amd_ci + +register_cuda_ci(est_time=207, stage="base-b", runner_config="1-gpu-large") +register_amd_ci(est_time=278, suite="stage-b-test-1-gpu-small-amd") + + +@unittest.skipIf(is_in_amd_ci(), "Skip for AMD CI.") +class TestFlashinferDeterministic(TestDeterministicBase): + # Test with flashinfer attention backend + @classmethod + def get_server_args(cls): + args = COMMON_SERVER_ARGS + args.extend( + [ + "--attention-backend", + "flashinfer", + ] + ) + return args + + +@unittest.skipIf(is_in_amd_ci(), "Skip for AMD CI.") +class TestFa3Deterministic(TestDeterministicBase): + # Test with fa3 attention backend + @classmethod + def get_server_args(cls): + args = COMMON_SERVER_ARGS + args.extend( + [ + "--attention-backend", + "fa3", + ] + ) + return args + + +class TestTritonDeterministic(TestDeterministicBase): + # Test with triton attention backend + @classmethod + def get_server_args(cls): + args = COMMON_SERVER_ARGS + args.extend( + [ + "--attention-backend", + "triton", + ] + ) + return args + + +if __name__ == "__main__": + unittest.main() diff --git a/asian_ai/performance/SGLang/test/registered/attention/test_flash_attention_4.py b/asian_ai/performance/SGLang/test/registered/attention/test_flash_attention_4.py new file mode 100644 index 0000000000000000000000000000000000000000..1ddaa5dbe2ca02019aff4daf41f9fae02bce8e88 --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/attention/test_flash_attention_4.py @@ -0,0 +1,118 @@ +import unittest +from types import SimpleNamespace + +import requests + +from sglang.srt.utils import get_device_sm, kill_process_tree +from sglang.test.ci.ci_register import register_cuda_ci +from sglang.test.run_eval import run_eval +from sglang.test.test_utils import ( + DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH, + DEFAULT_URL_FOR_TEST, + popen_launch_server, +) + +# FlashAttention4 integration test (requires SM 100+ / Blackwell B200) +register_cuda_ci(est_time=260, stage="base-b", runner_config="4-gpu-b200") + + +@unittest.skipIf(get_device_sm() < 100, "Test requires CUDA SM 100 or higher") +class TestFlashAttention4(unittest.TestCase): + @classmethod + def setUpClass(cls): + cls.model = "Qwen/Qwen3-8B" + cls.base_url = DEFAULT_URL_FOR_TEST + other_args = [ + "--trust-remote-code", + "--attention-backend", + "fa4", + ] + cls.process = popen_launch_server( + cls.model, + cls.base_url, + timeout=DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH, + other_args=other_args, + ) + + @classmethod + def tearDownClass(cls): + kill_process_tree(cls.process.pid) + + def test_gsm8k(self): + args = SimpleNamespace( + base_url=self.base_url, + model=self.model, + eval_name="gsm8k", + api="completion", + max_tokens=512, + num_examples=1319, + num_threads=200, + ) + metrics = run_eval(args) + print(metrics) + + self.assertGreater(metrics["score"], 0.89) + + +@unittest.skipIf(get_device_sm() < 100, "Test requires CUDA SM 100 or higher") +class TestFlashAttention4SpeculativeDecodeTopk(unittest.TestCase): + """Test FlashAttention4 with EAGLE3 speculative decoding (topk > 1). + + Verifies that FA4 + EAGLE3 topk > 1 produces correct outputs and + achieves meaningful speculative acceptance length. + """ + + @classmethod + def setUpClass(cls): + cls.model = "Qwen/Qwen3-30B-A3B-Instruct-2507" + cls.base_url = DEFAULT_URL_FOR_TEST + other_args = [ + "--trust-remote-code", + "--attention-backend", + "fa4", + "--speculative-algorithm", + "EAGLE3", + "--speculative-draft-model-path", + "lmsys/SGLang-EAGLE3-Qwen3-30B-A3B-Instruct-2507-SpecForge-Nex", + "--speculative-num-steps", + "5", + "--speculative-eagle-topk", + "4", + "--speculative-num-draft-tokens", + "8", + ] + cls.process = popen_launch_server( + cls.model, + cls.base_url, + timeout=DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH, + other_args=other_args, + ) + + @classmethod + def tearDownClass(cls): + kill_process_tree(cls.process.pid) + + def test_gsm8k(self): + args = SimpleNamespace( + base_url=self.base_url, + model=self.model, + eval_name="gsm8k", + api="completion", + max_tokens=512, + num_examples=1319, + num_threads=200, + ) + metrics = run_eval(args) + print(metrics) + self.assertGreater(metrics["score"], 0.89) + + server_info = requests.get(self.base_url + "/server_info").json() + avg_spec_accept_length = server_info["internal_states"][0][ + "avg_spec_accept_length" + ] + print(f"{avg_spec_accept_length=}") + self.assertGreater(avg_spec_accept_length, 1.5) + + +if __name__ == "__main__": + unittest.main() diff --git a/asian_ai/performance/SGLang/test/registered/attention/test_gdn_noncontiguous_stride.py b/asian_ai/performance/SGLang/test/registered/attention/test_gdn_noncontiguous_stride.py new file mode 100644 index 0000000000000000000000000000000000000000..1cc104c11472f3182937cb1181a786c71ab126f9 --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/attention/test_gdn_noncontiguous_stride.py @@ -0,0 +1,255 @@ +""" +Tests that fused_gdn_gating and fused_sigmoid_gating_delta_rule_update +produce correct results when a/b inputs are non-contiguous, +as happens with Qwen3.5-27B (v_per_group=3) via mixed_ba.split(). +""" + +import unittest + +import torch + +from sglang.srt.layers.attention.fla.fused_gdn_gating import fused_gdn_gating +from sglang.srt.layers.attention.fla.fused_sigmoid_gating_recurrent import ( + fused_sigmoid_gating_delta_rule_update, +) +from sglang.test.ci.ci_register import register_cuda_ci + +register_cuda_ci(est_time=7, stage="base-b", runner_config="1-gpu-large") + + +def _make_noncontiguous_ab(batch, num_heads, dtype=torch.bfloat16, device="cuda"): + """ + Simulate Qwen3.5 fallback: mixed_ba.split([nv_tp, nv_tp], dim=-1). + Returns (b, a) as split views with stride(0) = 2 * num_heads. + Also returns contiguous copies for reference comparison. + """ + mixed_ba = torch.randn(batch, 2 * num_heads, dtype=dtype, device=device) + b, a = mixed_ba.split([num_heads, num_heads], dim=-1) + + # For batch=1, PyTorch may still report contiguous even when split keeps + # a widened leading stride. Validate stride semantics unconditionally. + if batch > 1: + assert not a.is_contiguous(), "a should be non-contiguous from split" + assert not b.is_contiguous(), "b should be non-contiguous from split" + assert a.stride(0) == 2 * num_heads + assert b.stride(0) == 2 * num_heads + return b, a, b.contiguous(), a.contiguous() + + +@unittest.skipIf(not torch.cuda.is_available(), "Test requires CUDA") +class TestFusedGdnGatingNonContiguous(unittest.TestCase): + """Test fused_gdn_gating with non-contiguous a/b.""" + + def _run_test(self, batch, num_heads): + A_log = torch.randn(num_heads, dtype=torch.float32, device="cuda") + dt_bias = torch.randn(num_heads, dtype=torch.bfloat16, device="cuda") + + b, a, b_contig, a_contig = _make_noncontiguous_ab(batch, num_heads) + + g_ref, beta_ref = fused_gdn_gating(A_log, a_contig, b_contig, dt_bias) + g_test, beta_test = fused_gdn_gating(A_log, a, b, dt_bias) + + self.assertTrue( + torch.allclose(g_test, g_ref, rtol=0, atol=0), + f"g mismatch: max diff = {(g_test - g_ref).abs().max().item()}", + ) + self.assertTrue( + torch.allclose(beta_test, beta_ref, rtol=0, atol=0), + f"beta mismatch: max diff = {(beta_test - beta_ref).abs().max().item()}", + ) + + def test_small(self): + self._run_test(batch=4, num_heads=8) + + def test_qwen35_27b_tp1(self): + """Qwen3.5-27B TP=1: nv_tp=48.""" + self._run_test(batch=16, num_heads=48) + + def test_qwen35_27b_tp2(self): + """Qwen3.5-27B TP=2: nv_tp=24.""" + self._run_test(batch=32, num_heads=24) + + def test_single_batch(self): + self._run_test(batch=1, num_heads=48) + + +@unittest.skipIf(not torch.cuda.is_available(), "Test requires CUDA") +class TestFusedSigmoidGatingDeltaRuleUpdateNonContiguous(unittest.TestCase): + """Test fused_sigmoid_gating_delta_rule_update with non-contiguous a/b.""" + + def _run_test(self, batch, T, num_v_heads, head_k_dim, head_v_dim): + num_k_heads = num_v_heads # simplification for GDN + HV = num_v_heads + K = head_k_dim + V = head_v_dim + + A_log = torch.randn(HV, dtype=torch.float32, device="cuda") + dt_bias = torch.randn(HV, dtype=torch.bfloat16, device="cuda") + + q = torch.randn(batch, T, num_k_heads, K, dtype=torch.bfloat16, device="cuda") + k = torch.randn(batch, T, num_k_heads, K, dtype=torch.bfloat16, device="cuda") + v = torch.randn(batch, T, HV, V, dtype=torch.bfloat16, device="cuda") + + # Simulate non-contiguous a/b from split + mixed_ba = torch.randn(batch * T, 2 * HV, dtype=torch.bfloat16, device="cuda") + b_nc, a_nc = mixed_ba.split([HV, HV], dim=-1) + b_c, a_c = b_nc.contiguous(), a_nc.contiguous() + + # Build cu_seqlens for varlen (one token per sequence) + cu_seqlens = torch.arange(0, batch * T + 1, T, dtype=torch.int32, device="cuda") + + cache_len = batch + 4 + ssm_states = torch.zeros( + cache_len, HV, K, V, dtype=torch.float32, device="cuda" + ) + state_indices = torch.arange(batch, dtype=torch.int32, device="cuda") + + # Reference: contiguous a/b + ssm_ref = ssm_states.clone() + out_ref = fused_sigmoid_gating_delta_rule_update( + A_log=A_log, + dt_bias=dt_bias, + q=q, + k=k, + v=v, + a=a_c, + b=b_c, + initial_state_source=ssm_ref, + initial_state_indices=state_indices, + cu_seqlens=cu_seqlens, + softplus_beta=1.0, + softplus_threshold=20.0, + is_kda=False, + ) + + # Test: non-contiguous a/b + ssm_test = ssm_states.clone() + out_test = fused_sigmoid_gating_delta_rule_update( + A_log=A_log, + dt_bias=dt_bias, + q=q, + k=k, + v=v, + a=a_nc, + b=b_nc, + initial_state_source=ssm_test, + initial_state_indices=state_indices, + cu_seqlens=cu_seqlens, + softplus_beta=1.0, + softplus_threshold=20.0, + is_kda=False, + ) + + max_out_diff = (out_test - out_ref).abs().max().item() + max_state_diff = (ssm_test - ssm_ref).abs().max().item() + + self.assertTrue( + torch.allclose(out_test, out_ref, rtol=0, atol=0), + f"output mismatch: max diff = {max_out_diff}", + ) + self.assertTrue( + torch.allclose(ssm_test, ssm_ref, rtol=0, atol=0), + f"state mismatch: max diff = {max_state_diff}", + ) + + def test_decode_single_token(self): + """Standard decode: T=1, batch>1.""" + self._run_test(batch=4, T=1, num_v_heads=8, head_k_dim=64, head_v_dim=32) + + def test_qwen35_decode(self): + """Qwen3.5-27B like config: HV=48.""" + self._run_test(batch=8, T=1, num_v_heads=48, head_k_dim=128, head_v_dim=128) + + def test_multi_token(self): + """target_verify style: T>1.""" + self._run_test(batch=4, T=4, num_v_heads=8, head_k_dim=64, head_v_dim=32) + + +@unittest.skipIf(not torch.cuda.is_available(), "Test requires CUDA") +class TestFusedSigmoidGatingKDAStride(unittest.TestCase): + """Regression test: KDA path handles non-contiguous a/b after stride_a refactor.""" + + def test_kda_noncontiguous_matches_contiguous(self): + """KDA path should produce identical outputs/states for contiguous vs non-contiguous a/b.""" + token_num = 4 + num_heads = 8 + head_dim = 128 + HV = num_heads + K = head_dim + + A_log = torch.randn(1, 1, HV, 1, dtype=torch.float32, device="cuda") + dt_bias = torch.randn(HV * K, dtype=torch.bfloat16, device="cuda") + + mixed_a = torch.randn( + token_num, 2 * HV * K, dtype=torch.bfloat16, device="cuda" + ) + a_nc, _ = mixed_a.split([HV * K, HV * K], dim=-1) + a_c = a_nc.contiguous() + self.assertFalse(a_nc.is_contiguous()) + + mixed_b = torch.randn(1, token_num, 2 * HV, dtype=torch.bfloat16, device="cuda") + b_nc, _ = mixed_b.split([HV, HV], dim=-1) + b_c = b_nc.contiguous() + self.assertFalse(b_nc.is_contiguous()) + + q = torch.randn(1, token_num, HV, K, dtype=torch.bfloat16, device="cuda") + k = torch.randn(1, token_num, HV, K, dtype=torch.bfloat16, device="cuda") + v = torch.randn(1, token_num, HV, K, dtype=torch.bfloat16, device="cuda") + + cu_seqlens = torch.tensor([0, 1, 2, 3, 4], device="cuda", dtype=torch.int32) + cache_len = 64 + ssm_states = torch.zeros( + cache_len, HV, K, K, dtype=torch.float32, device="cuda" + ) + cache_indices = torch.tensor([0, 2, 5, 8], device="cuda", dtype=torch.int32) + + # Reference: contiguous a/b + ssm_ref = ssm_states.clone() + out_ref = fused_sigmoid_gating_delta_rule_update( + A_log=A_log, + dt_bias=dt_bias, + q=q, + k=k, + v=v, + a=a_c, + b=b_c, + initial_state_source=ssm_ref, + initial_state_indices=cache_indices, + cu_seqlens=cu_seqlens, + use_qk_l2norm_in_kernel=True, + softplus_beta=1.0, + softplus_threshold=20.0, + is_kda=True, + ) + + # Test: non-contiguous a/b from split + ssm_test = ssm_states.clone() + out_test = fused_sigmoid_gating_delta_rule_update( + A_log=A_log, + dt_bias=dt_bias, + q=q, + k=k, + v=v, + a=a_nc, + b=b_nc, + initial_state_source=ssm_test, + initial_state_indices=cache_indices, + cu_seqlens=cu_seqlens, + use_qk_l2norm_in_kernel=True, + softplus_beta=1.0, + softplus_threshold=20.0, + is_kda=True, + ) + + self.assertTrue( + torch.allclose(out_test, out_ref, rtol=0, atol=0), + f"KDA output mismatch: max diff = {(out_test - out_ref).abs().max().item()}", + ) + self.assertTrue( + torch.allclose(ssm_test, ssm_ref, rtol=0, atol=0), + f"KDA state mismatch: max diff = {(ssm_test - ssm_ref).abs().max().item()}", + ) + + +if __name__ == "__main__": + unittest.main() diff --git a/asian_ai/performance/SGLang/test/registered/attention/test_gdn_prefill_cutedsl.py b/asian_ai/performance/SGLang/test/registered/attention/test_gdn_prefill_cutedsl.py new file mode 100644 index 0000000000000000000000000000000000000000..42f468432504b72100c9d53146e5a4ffedba059b --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/attention/test_gdn_prefill_cutedsl.py @@ -0,0 +1,178 @@ +"""Correctness test for the SM100 CuTe DSL GDN prefill kernel. + +Ported from vLLM PR https://github.com/vllm-project/vllm/pull/43273. +Validates ``chunk_gated_delta_rule_cutedsl`` against the +``fused_recurrent_gated_delta_rule`` Triton reference. +""" + +import math + +import pytest +import torch +import torch.nn.functional as F + +from sglang.test.ci.ci_register import register_cuda_ci + +# CuteDSL prefill kernel only exists on Blackwell. Single-GPU kernel-unit +# suite is the right slot (matches existing jit_kernel test_*.py pattern). +register_cuda_ci(est_time=60, stage="base-b-kernel-unit", runner_config="4-gpu-b200") + +if not (torch.cuda.is_available() and torch.cuda.get_device_capability()[0] >= 10): + pytest.skip( + "GDN CuteDSL prefill requires CUDA SM10x (Blackwell).", + allow_module_level=True, + ) + +from sglang.srt.layers.attention.fla.fused_recurrent import ( # noqa: E402 + fused_recurrent_gated_delta_rule, +) +from sglang.srt.layers.attention.fla.index import ( # noqa: E402 + prepare_chunk_indices, + prepare_chunk_offsets, +) +from sglang.srt.layers.attention.linear.kernels.gdn_blackwell import ( # noqa: E402 + chunk_gated_delta_rule_cutedsl, + prepare_metadata_cutedsl, +) + + +@pytest.mark.parametrize("num_seqs", [1, 5, 257]) +@pytest.mark.parametrize("state_dtype", [torch.bfloat16, torch.float32]) +def test_gdn_chunk_cutedsl_correctness(num_seqs: int, state_dtype: torch.dtype): + seq_lens = torch.randint(1, 130, (num_seqs,), dtype=torch.int32) + cu_seqlens = torch.zeros(num_seqs + 1, device="cuda", dtype=torch.int32) + cu_seqlens[1:] = seq_lens.to(device="cuda").cumsum(0) + total_tokens = int(cu_seqlens[-1].item()) + + num_k_heads = 4 + num_v_heads = 8 + head_k_dim = 128 + head_v_dim = 128 + dtype = torch.bfloat16 + + q = torch.randn( + 1, total_tokens, num_k_heads, head_k_dim, device="cuda", dtype=dtype + ) + k = torch.randn_like(q) + v = torch.randn( + 1, total_tokens, num_v_heads, head_v_dim, device="cuda", dtype=dtype + ) + q = F.normalize(q.float(), p=2, dim=-1).to(dtype) + k = F.normalize(k.float(), p=2, dim=-1).to(dtype) + a = torch.randn(1, total_tokens, num_v_heads, device="cuda", dtype=dtype) + b = torch.randn(1, total_tokens, num_v_heads, device="cuda", dtype=dtype) + + # Match upstream FLA GatedDeltaNet synthetic init. + A = torch.empty(num_v_heads, device="cuda", dtype=torch.float32).uniform_(0, 16) + A_log = torch.log(A) + dt = torch.exp( + torch.rand(num_v_heads, device="cuda", dtype=torch.float32) + * (math.log(0.1) - math.log(0.001)) + + math.log(0.001) + ) + dt = torch.clamp(dt, min=1e-4) + dt_bias = dt + torch.log(-torch.expm1(-dt)) + g = -A_log.exp().view(1, 1, num_v_heads) * F.softplus( + a.float() + dt_bias.view(1, 1, num_v_heads) + ) + beta = torch.sigmoid(b.float()) + initial_state = ( + torch.randn( + num_seqs, + num_v_heads, + head_v_dim, + head_k_dim, + device="cuda", + dtype=state_dtype, + ) + * 0.05 + ) + + # Metadata kernel matches the FLA reference helpers. + chunk_indices, chunk_offsets = prepare_metadata_cutedsl(cu_seqlens, total_tokens) + torch.cuda.synchronize() + + expected_indices = prepare_chunk_indices(cu_seqlens, 64) + expected_offsets = prepare_chunk_offsets(cu_seqlens, 64) + total_chunks = int(expected_offsets[-1].item()) + + torch.testing.assert_close(chunk_offsets, expected_offsets.to(torch.int32)) + torch.testing.assert_close(chunk_indices[:total_chunks], expected_indices) + + # Reference: token-by-token recurrent kernel returns (o, final_state). + # Recurrent path needs float32 state, so cast initial_state for the call. + ref_o, ref_state = fused_recurrent_gated_delta_rule( + q=q, + k=k, + v=v, + g=g, + beta=beta, + initial_state=initial_state.to(torch.float32), + output_final_state=True, + cu_seqlens=cu_seqlens.to(torch.int64), + use_qk_l2norm_in_kernel=False, + ) + + actual_core_attn_out = torch.empty( + total_tokens, num_v_heads, head_v_dim, device="cuda", dtype=dtype + ) + actual_o, actual_state = chunk_gated_delta_rule_cutedsl( + q=q, + k=k, + v=v, + g=g, + beta=beta, + initial_state=initial_state, + cu_seqlens=cu_seqlens, + chunk_indices=chunk_indices, + chunk_offsets=chunk_offsets, + core_attn_out=actual_core_attn_out, + ) + torch.cuda.synchronize() + + o_error = (actual_o.float() - ref_o.float()).abs() + state_error = ( + actual_state.float() - ref_state.to(actual_state.dtype).float() + ).abs() + assert o_error.max().item() < 2e-3 + assert o_error.mean().item() < 6e-5 + assert state_error.max().item() < 2e-2 + assert state_error.mean().item() < 6e-4 + core_attn_out_error = ( + actual_core_attn_out.float() - actual_o.squeeze(0).float() + ).abs() + assert core_attn_out_error.max().item() == 0 + + no_buffer_o, no_buffer_state = chunk_gated_delta_rule_cutedsl( + q=q, + k=k, + v=v, + g=g, + beta=beta, + initial_state=initial_state, + cu_seqlens=cu_seqlens, + chunk_indices=chunk_indices, + chunk_offsets=chunk_offsets, + ) + torch.cuda.synchronize() + + no_buffer_o_error = (no_buffer_o.float() - ref_o.float()).abs() + no_buffer_state_error = ( + no_buffer_state.float() - ref_state.to(no_buffer_state.dtype).float() + ).abs() + buffer_o_error = (no_buffer_o.float() - actual_o.float()).abs() + buffer_state_error = ( + no_buffer_state.float() - actual_state.to(no_buffer_state.dtype).float() + ).abs() + assert no_buffer_o_error.max().item() < 2e-3 + assert no_buffer_o_error.mean().item() < 6e-5 + assert no_buffer_state_error.max().item() < 2e-2 + assert no_buffer_state_error.mean().item() < 6e-4 + assert buffer_o_error.max().item() == 0 + assert buffer_state_error.max().item() == 0 + + +if __name__ == "__main__": + import sys + + sys.exit(pytest.main([__file__, "-v"])) diff --git a/asian_ai/performance/SGLang/test/registered/attention/test_gemma4_swa_triton_oob_regression.py b/asian_ai/performance/SGLang/test/registered/attention/test_gemma4_swa_triton_oob_regression.py new file mode 100644 index 0000000000000000000000000000000000000000..0b1547dfb673a49c3333d77f2563ca4028c64a11 --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/attention/test_gemma4_swa_triton_oob_regression.py @@ -0,0 +1,124 @@ +"""Regression test for issue #24394. + +`--enable-deterministic-inference` with `--attention-backend triton` on a +hybrid `SWAKVPool` model (Gemma4 family) used to crash with +`CUDA error: an illegal memory access` inside `_fwd_kernel_unified`: the +unified extend kernel read the new tokens at `out_cache_loc` (full-pool +index space) while `SWAKVPool.set_kv_buffer` had written them at the +SWA-translated indices. With diverse prompts the OOB never materialises; +the repro is same-prompt × high-concurrency, which is what this test fires. +""" + +import concurrent.futures +import unittest + +import requests + +from sglang.srt.utils import kill_process_tree +from sglang.test.ci.ci_register import register_amd_ci, register_cuda_ci +from sglang.test.test_utils import ( + DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH, + DEFAULT_URL_FOR_TEST, + CustomTestCase, + popen_launch_server, +) + +register_cuda_ci(est_time=107, stage="base-b", runner_config="2-gpu-large") +register_amd_ci(est_time=160, suite="stage-b-test-2-gpu-large-amd") + + +PROMPT = ( + "Question: Janet's ducks lay 16 eggs per day. She eats three for breakfast " + "every morning and bakes muffins for her friends every day with four. She " + "sells the remainder at the farmers' market daily for $2 per fresh duck " + "egg. How much in dollars does she make every day at the farmers' market?\n" + "Answer:" +) +NUM_REQUESTS = 180 +CONCURRENCY = 128 +MAX_TOKENS = 256 + + +class TestGemma4SwaTritonOobRegression(CustomTestCase): + @classmethod + def setUpClass(cls): + cls.model = "google/gemma-4-26B-A4B-it" + cls.base_url = DEFAULT_URL_FOR_TEST + cls.process = popen_launch_server( + cls.model, + cls.base_url, + timeout=DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH, + other_args=[ + "--tp-size", + "2", + "--attention-backend", + "triton", + "--enable-deterministic-inference", + "--dtype", + "bfloat16", + "--mem-fraction-static", + "0.55", + "--max-running-requests", + "16", + "--context-length", + "2048", + "--max-total-tokens", + "32768", + "--skip-server-warmup", + "--random-seed", + "0", + ], + ) + + @classmethod + def tearDownClass(cls): + if hasattr(cls, "process") and cls.process: + kill_process_tree(cls.process.pid) + + def _fire_one(self): + try: + r = requests.post( + self.base_url + "/v1/completions", + json={ + "model": self.model, + "prompt": PROMPT, + "max_tokens": MAX_TOKENS, + "temperature": 0.0, + "top_k": 1, + }, + timeout=300, + ) + r.raise_for_status() + return True, "" + except Exception as e: + return False, repr(e) + + def test_no_ima_under_concurrent_load(self): + try: + requests.get(self.base_url + "/flush_cache", timeout=30) + except Exception: + pass + + n_ok = n_fail = 0 + first_fail = "" + with concurrent.futures.ThreadPoolExecutor(max_workers=CONCURRENCY) as ex: + futs = [ex.submit(self._fire_one) for _ in range(NUM_REQUESTS)] + for f in concurrent.futures.as_completed(futs): + ok, msg = f.result() + if ok: + n_ok += 1 + else: + if n_fail == 0: + first_fail = msg + n_fail += 1 + + print(f"n_ok={n_ok} n_fail={n_fail} first_fail={first_fail!r}") + self.assertEqual( + n_fail, + 0, + f"{n_fail}/{NUM_REQUESTS} requests failed; first error: {first_fail}", + ) + + +if __name__ == "__main__": + unittest.main() diff --git a/asian_ai/performance/SGLang/test/registered/attention/test_hybrid_attn_backend.py b/asian_ai/performance/SGLang/test/registered/attention/test_hybrid_attn_backend.py new file mode 100644 index 0000000000000000000000000000000000000000..dc8813fb33ac315d36207738ef941feb9fe2602c --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/attention/test_hybrid_attn_backend.py @@ -0,0 +1,68 @@ +import unittest + +from sglang.test.ci.ci_register import register_cuda_ci +from sglang.test.server_fixtures.hybrid_attn_backend_fixture import ( + TestHybridAttnBackendBase, +) +from sglang.test.test_utils import ( + DEFAULT_DRAFT_MODEL_EAGLE, + DEFAULT_MODEL_NAME_FOR_TEST_MLA, +) + +# Hybrid attention backend tests (FA3 prefill + FlashInfer decode, requires SM 90+ / H100) +# Multiple test classes: base, MLA, TorchCompile, SpecDecode variants +register_cuda_ci(est_time=407, stage="extra-a", runner_config="1-gpu-large") + + +class TestHybridAttnBackendMLA(TestHybridAttnBackendBase): + accuracy_threshold = 0.60 + model = DEFAULT_MODEL_NAME_FOR_TEST_MLA + + +class TestHybridAttnBackendTorchCompile(TestHybridAttnBackendBase): + accuracy_threshold = 0.65 + extra_args = ["--enable-torch-compile"] + + +class TestHybridAttnBackendSpeculativeDecodingPrefillBackend(TestHybridAttnBackendBase): + speculative_decode = True + # This eagle test uses a very small model, so the accuracy is low. + accuracy_threshold = 0.2 + extra_args = [ + "--speculative-algorithm", + "EAGLE", + "--speculative-draft-model-path", + DEFAULT_DRAFT_MODEL_EAGLE, + "--speculative-num-steps", + "3", + "--speculative-eagle-topk", + "2", + "--speculative-num-draft-tokens", + "4", + "--speculative-attention-mode", + "prefill", + ] + + +class TestHybridAttnBackendSpeculativeDecodingDecodeBackend(TestHybridAttnBackendBase): + speculative_decode = True + # This eagle test uses a very small model, so the accuracy is low. + accuracy_threshold = 0.2 + extra_args = [ + "--speculative-algorithm", + "EAGLE", + "--speculative-draft-model-path", + DEFAULT_DRAFT_MODEL_EAGLE, + "--speculative-num-steps", + "3", + "--speculative-eagle-topk", + "2", + "--speculative-num-draft-tokens", + "4", + "--speculative-attention-mode", + "decode", + ] + + +if __name__ == "__main__": + unittest.main() diff --git a/asian_ai/performance/SGLang/test/registered/attention/test_kda_kernels.py b/asian_ai/performance/SGLang/test/registered/attention/test_kda_kernels.py new file mode 100644 index 0000000000000000000000000000000000000000..60a0381a7c4c79556c8ac1e373f907535519dc19 --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/attention/test_kda_kernels.py @@ -0,0 +1,452 @@ +import unittest + +import torch + +from sglang.srt.layers.attention.fla.cumsum import chunk_local_cumsum +from sglang.srt.layers.attention.fla.fused_recurrent import ( + fused_recurrent_kda_packed_decode, +) +from sglang.srt.layers.attention.fla.fused_sigmoid_gating_recurrent import ( + fused_sigmoid_gating_delta_rule_update, +) +from sglang.srt.layers.attention.fla.index import prepare_chunk_indices +from sglang.srt.layers.attention.fla.kda import ( + fused_recurrent_kda, + kda_gate_chunk_cumsum, +) +from sglang.srt.utils.common import get_device +from sglang.test.ci.ci_register import register_cuda_ci + +register_cuda_ci(est_time=12, stage="base-b", runner_config="1-gpu-large") + + +@unittest.skipIf( + not (torch.cuda.is_available() or torch.xpu.is_available()), + "Test requires CUDA or XPU", +) +class TestKDAFusedSigmoidGatingRecurrent(unittest.TestCase): + def setUp(self): + self.device = get_device() + self.token_num = 4 + self.query_start_loc = torch.tensor([0, 1, 2, 3, 4], device=self.device) + self.cache_indices = torch.tensor([0, 2, 5, 8], device=self.device) + self.local_num_heads = 8 + self.head_dim = 128 + self.cache_len = 64 + + self.A_log = torch.randn( + 1, 1, self.local_num_heads, 1, dtype=torch.float32, device=self.device + ) + self.a = torch.randn( + 1, + self.token_num, + self.local_num_heads * self.head_dim, + dtype=torch.bfloat16, + device=self.device, + ) + self.dt_bias = torch.randn( + self.local_num_heads * self.head_dim, + dtype=torch.bfloat16, + device=self.device, + ) + self.softplus_beta = 1.0 + self.softplus_threshold = 20.0 + self.q = torch.randn( + 1, + self.token_num, + self.local_num_heads, + self.head_dim, + dtype=torch.bfloat16, + device=self.device, + ) + self.k = torch.randn( + 1, + self.token_num, + self.local_num_heads, + self.head_dim, + dtype=torch.bfloat16, + device=self.device, + ) + self.v = torch.randn( + 1, + self.token_num, + self.local_num_heads, + self.head_dim, + dtype=torch.bfloat16, + device=self.device, + ) + self.beta = torch.randn( + 1, + self.token_num, + self.local_num_heads, + dtype=torch.bfloat16, + device=self.device, + ) + + self.ssm_states = torch.zeros( + self.cache_len, + self.local_num_heads, + self.head_dim, + self.head_dim, + dtype=torch.float32, + device=self.device, + ) + + def run_fused(self): + ssm_states = self.ssm_states.clone() + core_attn_out = fused_sigmoid_gating_delta_rule_update( + A_log=self.A_log, + dt_bias=self.dt_bias, + q=self.q, + k=self.k, + v=self.v, + a=self.a, + b=self.beta, + initial_state_source=ssm_states, + initial_state_indices=self.cache_indices, + cu_seqlens=self.query_start_loc, + use_qk_l2norm_in_kernel=True, + softplus_beta=self.softplus_beta, + softplus_threshold=self.softplus_threshold, + is_kda=True, + ) + return core_attn_out, ssm_states[self.cache_indices] + + def run_kda(self): + b = self.beta.float().sigmoid() + # Reference gate activation using torch ops: + # g = -exp(A_log) * softplus(raw_g + dt_bias) + H, K = self.local_num_heads, self.head_dim + raw_g = self.a.float() # [1, T, H*K] + if self.dt_bias is not None: + raw_g = raw_g + self.dt_bias.float() + g = -torch.exp( + self.A_log.float().view(1, 1, H, 1) + ) * torch.nn.functional.softplus(raw_g.view(1, -1, H, K)) + initial_state = self.ssm_states[self.cache_indices].clone() + core_attn_out, last_state = fused_recurrent_kda( + q=self.q, + k=self.k, + v=self.v, + g=g, + beta=b, + initial_state=initial_state, + use_qk_l2norm_in_kernel=True, + cu_seqlens=self.query_start_loc, + ) + return core_attn_out, last_state + + def test_kda_fused_sigmoid_gating_recurrent(self): + core_attn_out, last_state = self.run_fused() + core_attn_out_ref, last_state_ref = self.run_kda() + abs_diff_out = (core_attn_out - core_attn_out_ref).abs().max() + abs_diff_state = (last_state - last_state_ref).abs().max() + print(f"{abs_diff_out=}, {abs_diff_state=}") + self.assertTrue( + torch.allclose(core_attn_out, core_attn_out_ref, rtol=1e-3, atol=1e-4) + ) + self.assertTrue(torch.allclose(last_state, last_state_ref)) + + +@unittest.skipIf(not torch.cuda.is_available(), "Test requires CUDA") +class TestKDAGateChunkCumsum(unittest.TestCase): + """Test kda_gate_chunk_cumsum against torch reference (gate activation + cumsum).""" + + CHUNK_SIZE = 64 + + def _ref_gate_cumsum(self, raw_g, A_log, dt_bias, cu_seqlens, chunk_size): + """Reference: torch gate activation then chunk_local_cumsum.""" + B, T, H, K = raw_g.shape + g = raw_g.float() + if dt_bias is not None: + g = g + dt_bias.float().view(1, 1, H, K) + g = -torch.exp(A_log.float().view(1, 1, H, 1)) * torch.nn.functional.softplus(g) + chunk_indices = ( + prepare_chunk_indices(cu_seqlens, chunk_size) + if cu_seqlens is not None + else None + ) + return chunk_local_cumsum( + g, chunk_size=chunk_size, cu_seqlens=cu_seqlens, chunk_indices=chunk_indices + ) + + def _run_case(self, B, T_per_seq, H, K, use_bias, use_varlen): + T = B * T_per_seq + torch.manual_seed(42) + raw_g = torch.randn(1, T, H, K, dtype=torch.bfloat16, device="cuda") + A_log = torch.randn(H, dtype=torch.float32, device="cuda") * 0.5 + dt_bias = ( + torch.randn(H * K, dtype=torch.float32, device="cuda") * 0.1 + if use_bias + else None + ) + cu_seqlens = ( + torch.arange( + 0, (B + 1) * T_per_seq, T_per_seq, dtype=torch.long, device="cuda" + ) + if use_varlen + else None + ) + + out_fused = kda_gate_chunk_cumsum( + raw_g, + A_log=A_log, + chunk_size=self.CHUNK_SIZE, + dt_bias=dt_bias, + cu_seqlens=cu_seqlens, + ) + out_ref = self._ref_gate_cumsum( + raw_g, A_log, dt_bias, cu_seqlens, self.CHUNK_SIZE + ) + + max_diff = (out_fused - out_ref).abs().max().item() + rel_diff = max_diff / (out_ref.abs().mean().item() + 1e-8) + return max_diff, rel_diff + + def test_varlen_with_bias(self): + max_diff, rel_diff = self._run_case( + B=4, T_per_seq=256, H=16, K=128, use_bias=True, use_varlen=True + ) + self.assertLess( + max_diff, 1e-3, f"max_diff={max_diff:.2e}, rel_diff={rel_diff:.2e}" + ) + + def test_varlen_no_bias(self): + max_diff, rel_diff = self._run_case( + B=4, T_per_seq=256, H=16, K=128, use_bias=False, use_varlen=True + ) + self.assertLess( + max_diff, 1e-3, f"max_diff={max_diff:.2e}, rel_diff={rel_diff:.2e}" + ) + + def test_fixed_len_with_bias(self): + max_diff, rel_diff = self._run_case( + B=4, T_per_seq=256, H=16, K=128, use_bias=True, use_varlen=False + ) + self.assertLess( + max_diff, 1e-3, f"max_diff={max_diff:.2e}, rel_diff={rel_diff:.2e}" + ) + + def test_single_seq_long(self): + max_diff, rel_diff = self._run_case( + B=1, T_per_seq=2048, H=16, K=128, use_bias=True, use_varlen=True + ) + self.assertLess( + max_diff, 1e-3, f"max_diff={max_diff:.2e}, rel_diff={rel_diff:.2e}" + ) + + def test_small_head_dim(self): + max_diff, rel_diff = self._run_case( + B=4, T_per_seq=128, H=8, K=64, use_bias=True, use_varlen=True + ) + self.assertLess( + max_diff, 1e-3, f"max_diff={max_diff:.2e}, rel_diff={rel_diff:.2e}" + ) + + +@unittest.skipIf(not torch.cuda.is_available(), "Test requires CUDA") +class TestKDAPackedDecode(unittest.TestCase): + """Verify ``fused_recurrent_kda_packed_decode`` matches the existing decode + path (split + unflatten + ``fused_sigmoid_gating_delta_rule_update``).""" + + @staticmethod + def _make_inputs(B, H, HV, K, V, pool_size, dtype, device, seed=42): + torch.manual_seed(seed) + qkv_dim = 2 * H * K + HV * V + mixed_qkv = ( + torch.randn(B, qkv_dim, dtype=dtype, device=device) * 0.1 + ).contiguous() + a = ( + torch.randn(B, HV * K, dtype=dtype, device=device) * 0.5 - 1.0 + ).contiguous() + b = (torch.randn(B, HV, dtype=dtype, device=device) * 0.5).contiguous() + A_log = torch.randn(HV, dtype=torch.float32, device=device) * 0.2 + dt_bias = torch.randn(HV * K, dtype=torch.float32, device=device) * 0.1 + ssm_states = ( + torch.randn(pool_size, HV, V, K, dtype=dtype, device=device) * 0.01 + ).contiguous() + cache_indices = torch.arange(B, device=device, dtype=torch.int32) + return mixed_qkv, a, b, A_log, dt_bias, ssm_states, cache_indices + + @staticmethod + def _run_baseline( + mixed_qkv, a, b, A_log, dt_bias, ssm_states, cache_indices, H, HV, K, V + ): + B = mixed_qkv.shape[0] + q_flat, k_flat, v_flat = torch.split(mixed_qkv, [H * K, H * K, HV * V], dim=-1) + q = q_flat.view(1, B, H, K) + k = k_flat.view(1, B, H, K) + v = v_flat.view(1, B, HV, V) + # The real backend passes query_start_loc = [0, 1, ..., B] so that + # each of the B tokens becomes its own length-1 sequence with an + # independent state; without this the kernel would share state. + cu_seqlens = torch.arange(B + 1, device=mixed_qkv.device, dtype=torch.int32) + return fused_sigmoid_gating_delta_rule_update( + A_log=A_log, + dt_bias=dt_bias, + softplus_beta=1.0, + softplus_threshold=20.0, + q=q, + k=k, + v=v, + a=a, + b=b, + initial_state_source=ssm_states, + initial_state_indices=cache_indices, + cu_seqlens=cu_seqlens, + scale=K**-0.5, + use_qk_l2norm_in_kernel=True, + is_kda=True, + ) + + @staticmethod + def _run_packed( + mixed_qkv, a, b, A_log, dt_bias, ssm_states, cache_indices, HV, K, V + ): + B = mixed_qkv.shape[0] + out = mixed_qkv.new_empty(B, 1, HV, V) + fused_recurrent_kda_packed_decode( + mixed_qkv=mixed_qkv, + a=a, + b=b, + A_log=A_log, + dt_bias=dt_bias, + scale=K**-0.5, + initial_state=ssm_states, + out=out, + ssm_state_indices=cache_indices, + use_qk_l2norm_in_kernel=True, + ) + return out.transpose(0, 1) + + def _check(self, B, H, HV, K, V): + device = get_device() + dtype = torch.bfloat16 + pool_size = B + 4 + mixed_qkv, a, b, A_log, dt_bias, ssm_states, cache_indices = self._make_inputs( + B, H, HV, K, V, pool_size, dtype, device + ) + s_packed = ssm_states.clone() + s_baseline = ssm_states.clone() + + o_packed = self._run_packed( + mixed_qkv, a, b, A_log, dt_bias, s_packed, cache_indices, HV, K, V + ) + o_baseline = self._run_baseline( + mixed_qkv, a, b, A_log, dt_bias, s_baseline, cache_indices, H, HV, K, V + ) + + torch.testing.assert_close( + o_packed.float(), o_baseline.float(), atol=2e-2, rtol=1e-2 + ) + torch.testing.assert_close( + s_packed[cache_indices].float(), + s_baseline[cache_indices].float(), + atol=2e-2, + rtol=1e-2, + ) + + def test_b1(self): + self._check(B=1, H=16, HV=16, K=128, V=128) + + def test_b4(self): + self._check(B=4, H=16, HV=16, K=128, V=128) + + def test_b32(self): + self._check(B=32, H=16, HV=16, K=128, V=128) + + def test_b128(self): + self._check(B=128, H=16, HV=16, K=128, V=128) + + def test_asymmetric_heads(self): + # Common KDA config with HV > H (grouped query). + self._check(B=8, H=8, HV=16, K=128, V=128) + + def test_pad_slot(self): + """Entries with state_idx == -1 must produce zero output and skip state writeback.""" + device = get_device() + dtype = torch.bfloat16 + B, H, HV, K, V = 8, 16, 16, 128, 128 + pool_size = B + 4 + mixed_qkv, a, b, A_log, dt_bias, ssm_states, cache_indices = self._make_inputs( + B, H, HV, K, V, pool_size, dtype, device + ) + # Mark every other request as padded. + cache_indices = cache_indices.clone() + cache_indices[::2] = -1 + + s_packed = ssm_states.clone() + s_baseline = ssm_states.clone() + o_packed = self._run_packed( + mixed_qkv, a, b, A_log, dt_bias, s_packed, cache_indices, HV, K, V + ) + o_baseline = self._run_baseline( + mixed_qkv, a, b, A_log, dt_bias, s_baseline, cache_indices, H, HV, K, V + ) + torch.testing.assert_close( + o_packed.float(), o_baseline.float(), atol=2e-2, rtol=1e-2 + ) + + def test_production_shapes_through_dispatcher(self): + """Go through ``TritonKDAKernel.packed_decode`` with the exact tensor + shapes the KimiDeltaAttention model produces at decode time, so the + a/b/A_log/dt_bias reshape-normalization is unit-tested (not only E2E). + + Production decode shapes (see kimi_linear.py forward + __init__): + - a (forget_gate): [B, HV*K] (2D, not unflattened in decode) + - b (beta): [1, B, HV] (unsqueeze(0), pre-sigmoid) + - A_log: [1, 1, HV, 1] + - dt_bias: [HV*K] + """ + from sglang.srt.layers.attention.linear.kernels.kda_triton import ( + TritonKDAKernel, + ) + + device = get_device() + dtype = torch.bfloat16 + B, H, HV, K, V = 4, 16, 16, 128, 128 + pool_size = B + 4 + mixed_qkv, a, b, A_log, dt_bias, ssm_states, cache_indices = self._make_inputs( + B, H, HV, K, V, pool_size, dtype, device + ) + + # Reshape the flat reference tensors into the production layouts. + b_prod = b.unsqueeze(0) # [B, HV] -> [1, B, HV] + A_log_prod = A_log.view(1, 1, HV, 1) # [HV] -> [1, 1, HV, 1] + + kernel = TritonKDAKernel() + self.assertTrue(kernel.supports_packed_decode) + + s_packed = ssm_states.clone() + out = kernel.packed_decode( + mixed_qkv, + a, + b_prod, + A_log=A_log_prod, + dt_bias=dt_bias, + scale=K**-0.5, + ssm_states=s_packed, + cache_indices=cache_indices, + num_v_heads=HV, + head_v_dim=V, + ) + + s_baseline = ssm_states.clone() + o_baseline = self._run_baseline( + mixed_qkv, a, b, A_log, dt_bias, s_baseline, cache_indices, H, HV, K, V + ) + + # Dispatcher returns [1, B, HV, V], same layout as the baseline. + torch.testing.assert_close( + out.float(), o_baseline.float(), atol=2e-2, rtol=1e-2 + ) + torch.testing.assert_close( + s_packed[cache_indices].float(), + s_baseline[cache_indices].float(), + atol=2e-2, + rtol=1e-2, + ) + + +if __name__ == "__main__": + unittest.main() diff --git a/asian_ai/performance/SGLang/test/registered/attention/test_kda_prefill_cutedsl.py b/asian_ai/performance/SGLang/test/registered/attention/test_kda_prefill_cutedsl.py new file mode 100644 index 0000000000000000000000000000000000000000..b3c1118bbda6b0b78fdc0c5bebb1bea766c69a80 --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/attention/test_kda_prefill_cutedsl.py @@ -0,0 +1,226 @@ +"""Correctness test for the SM100 CuTe DSL KDA prefill pipeline. + +Validates ``chunk_kda_cutedsl`` (the ``kda_blackwell`` package: fused Triton +prologue -> kkt_inv_uw -> h -> o) against the token-by-token +``fused_recurrent_kda`` Triton reference. Mirrors ``test_gdn_prefill_cutedsl.py``. + +KDA differs from GDN by a PER-CHANNEL decay gate (g is [T, H, K], not scalar +[T, H]); otherwise the chunk pipeline, head dims, and recurrent-state layout +[N, H, V, K] are identical. +""" + +import pytest +import torch +import torch.nn.functional as F + +from sglang.test.ci.ci_register import register_cuda_ci + +# CuteDSL prefill kernel only exists on Blackwell. Single-GPU kernel-unit suite, +# same slot as the GDN prefill test. +register_cuda_ci(est_time=60, stage="base-b-kernel-unit", runner_config="4-gpu-b200") + +if not (torch.cuda.is_available() and torch.cuda.get_device_capability()[0] >= 10): + pytest.skip( + "KDA CuteDSL prefill requires CUDA SM10x (Blackwell).", + allow_module_level=True, + ) + +from sglang.srt.layers.attention.fla.index import ( # noqa: E402 + prepare_chunk_indices, + prepare_chunk_offsets, +) +from sglang.srt.layers.attention.fla.kda import fused_recurrent_kda # noqa: E402 +from sglang.srt.layers.attention.linear.kernels.kda_blackwell import ( # noqa: E402 + chunk_kda_cutedsl, + prepare_metadata, +) + + +def _l2norm(x: torch.Tensor) -> torch.Tensor: + return F.normalize(x.float(), p=2, dim=-1) + + +@pytest.mark.parametrize("num_seqs", [1, 5, 257]) +def test_kda_chunk_cutedsl_correctness(num_seqs: int): + torch.manual_seed(num_seqs) + seq_lens = torch.randint(1, 130, (num_seqs,), dtype=torch.int32) + cu_seqlens = torch.zeros(num_seqs + 1, device="cuda", dtype=torch.int32) + cu_seqlens[1:] = seq_lens.to("cuda").cumsum(0) + total_tokens = int(cu_seqlens[-1].item()) + + # KDA shares the head count across q/k/v (G=1). CuteDSL prefill hard-requires + # head_k_dim == head_v_dim == 128. + num_heads = 8 + head_dim = 128 + scale = head_dim**-0.5 + + q = _l2norm(torch.randn(1, total_tokens, num_heads, head_dim, device="cuda")) + k = _l2norm(torch.randn(1, total_tokens, num_heads, head_dim, device="cuda")) + v = torch.randn(1, total_tokens, num_heads, head_dim, device="cuda") + + # Per-channel KDA gate. Mild gates keep the kernel's externalized per-channel + # pre-scaling (qg2 = scale*q*exp(g_cu - g_last), unbounded >= 1) inside fp32 + # range -- this matches real Kimi-Linear retention gates. Large per-chunk gate + # spans are a known limitation (B2 TODO: clamp / sub-chunk normalize). + A_log = torch.randn(num_heads, device="cuda") * 0.5 - 1.5 + dt_bias = torch.randn(num_heads, head_dim, device="cuda") * 0.1 + g_raw = torch.randn(1, total_tokens, num_heads, head_dim, device="cuda") + g_act = -A_log.exp().view(1, 1, num_heads, 1) * F.softplus( + g_raw + dt_bias.view(1, 1, num_heads, head_dim) + ) + beta = torch.sigmoid(torch.randn(1, total_tokens, num_heads, device="cuda")).float() + + # Recurrent-state layout [N, H, V, K] (V-major) -- identical for the recurrent + # reference and the cutedsl ht output (no transpose needed). + initial_state = ( + torch.randn(num_seqs, num_heads, head_dim, head_dim, device="cuda") * 0.05 + ).float() + + # --- metadata helper must match the FLA chunkers the Triton path uses --- + chunk_indices, chunk_offsets, _, total_chunks = prepare_metadata(cu_seqlens) + torch.cuda.synchronize() + expected_indices = prepare_chunk_indices(cu_seqlens, 64) + expected_offsets = prepare_chunk_offsets(cu_seqlens, 64) + torch.testing.assert_close(chunk_offsets, expected_offsets.to(torch.int32)) + torch.testing.assert_close(chunk_indices[:total_chunks], expected_indices) + + # --- reference: token-by-token recurrent kernel (ground truth) --- + ref_o, ref_state = fused_recurrent_kda( + q=q, + k=k, + v=v, + g=g_act, + beta=beta, + scale=scale, + initial_state=initial_state.clone(), + inplace_final_state=False, + use_qk_l2norm_in_kernel=False, + cu_seqlens=cu_seqlens.long(), + ) + + # --- cutedsl chunk prefill (q/k already L2-normed; pass g_act directly) --- + o, ht = chunk_kda_cutedsl( + q[0].bfloat16(), + k[0].bfloat16(), + v[0].bfloat16(), + g_act[0].float(), + beta[0].float(), + initial_state.clone(), + cu_seqlens, + scale, + ) + torch.cuda.synchronize() + + assert torch.isfinite(o).all(), "cutedsl output has non-finite values" + assert torch.isfinite(ht).all(), "cutedsl final state has non-finite values" + + o_error = (o.float() - ref_o[0].float()).abs() + state_error = (ht.float() - ref_state.float()).abs() + # bf16 MMA + Newton-Schulz inverse noise; matches the B200 e2e validation + # (o ~5e-4, ht ~4e-3) with margin. + assert o_error.max().item() < 1e-2 + assert o_error.mean().item() < 1e-3 + assert state_error.max().item() < 5e-2 + assert state_error.mean().item() < 5e-3 + + +def test_kda_chunk_cutedsl_internal_gate_activation(): + """The A_log/dt_bias gate activation inside chunk_kda_cutedsl must match + feeding a pre-activated gate.""" + torch.manual_seed(0) + T = 256 + num_heads = 8 + head_dim = 128 + scale = head_dim**-0.5 + + cu_seqlens = torch.tensor([0, T], dtype=torch.int32, device="cuda") + q = _l2norm(torch.randn(1, T, num_heads, head_dim, device="cuda")).bfloat16() + k = _l2norm(torch.randn(1, T, num_heads, head_dim, device="cuda")).bfloat16() + v = torch.randn(1, T, num_heads, head_dim, device="cuda").bfloat16() + A_log = torch.randn(num_heads, device="cuda") * 0.5 - 1.5 + dt_bias = torch.randn(num_heads, head_dim, device="cuda") * 0.1 + g_raw = torch.randn(1, T, num_heads, head_dim, device="cuda") + beta = torch.sigmoid(torch.randn(1, T, num_heads, device="cuda")).float() + h0 = torch.zeros(1, num_heads, head_dim, head_dim, device="cuda") + + g_pre = -A_log.exp().view(1, num_heads, 1) * F.softplus( + g_raw[0] + dt_bias.view(1, num_heads, head_dim) + ) + o_pre, ht_pre = chunk_kda_cutedsl( + q[0], k[0], v[0], g_pre.float(), beta[0], h0.clone(), cu_seqlens, scale + ) + o_int, ht_int = chunk_kda_cutedsl( + q[0], + k[0], + v[0], + g_raw[0].float(), + beta[0], + h0.clone(), + cu_seqlens, + scale, + A_log=A_log, + dt_bias=dt_bias, + ) + torch.cuda.synchronize() + torch.testing.assert_close(o_int.float(), o_pre.float(), atol=2e-3, rtol=1e-2) + torch.testing.assert_close(ht_int.float(), ht_pre.float(), atol=2e-3, rtol=1e-2) + + +def test_kda_chunk_cutedsl_realistic_gate(): + """Real Kimi-Linear retention gates are far stronger than the mild gates in + the tests above (exp(A_log) ~ 0.2 there vs up to ~200 in the model). Strong + gates make the per-chunk cumulative decay span large; a chunk-global g_last + reference would overflow the externalized exp(g_cu - g_last) pre-scaling. + The intra-chunk matrices use a sub-chunk-normalized path instead, so this + must stay finite and match the recurrent reference.""" + torch.manual_seed(0) + num_heads = 8 + head_dim = 128 + scale = head_dim**-0.5 + T = 128 + cu_seqlens = torch.tensor([0, T], dtype=torch.int32, device="cuda") + + q = _l2norm(torch.randn(1, T, num_heads, head_dim, device="cuda")) + k = _l2norm(torch.randn(1, T, num_heads, head_dim, device="cuda")) + v = torch.randn(1, T, num_heads, head_dim, device="cuda") + # exp(A_log) ~ exp(1.5) ~ 4.5 mean (real model reaches ~200), vs ~0.22 above. + A_log = torch.randn(num_heads, device="cuda") * 0.5 + 1.5 + dt_bias = torch.randn(num_heads, head_dim, device="cuda") * 0.1 + g_raw = torch.randn(1, T, num_heads, head_dim, device="cuda") + g_act = -A_log.exp().view(1, 1, num_heads, 1) * F.softplus( + g_raw + dt_bias.view(1, 1, num_heads, head_dim) + ) + beta = torch.sigmoid(torch.randn(1, T, num_heads, device="cuda")).float() + h0 = torch.zeros(1, num_heads, head_dim, head_dim, device="cuda").float() + + ref_o, _ = fused_recurrent_kda( + q=q, + k=k, + v=v, + g=g_act, + beta=beta, + scale=scale, + initial_state=h0.clone(), + inplace_final_state=False, + use_qk_l2norm_in_kernel=False, + cu_seqlens=cu_seqlens.long(), + ) + o, ht = chunk_kda_cutedsl( + q[0].bfloat16(), + k[0].bfloat16(), + v[0].bfloat16(), + g_act[0].float(), + beta[0].float(), + h0.clone(), + cu_seqlens, + scale, + ) + torch.cuda.synchronize() + assert torch.isfinite(o).all() and torch.isfinite(ht).all() + assert (o.float() - ref_o[0].float()).abs().max().item() < 1e-2 + + +if __name__ == "__main__": + import sys + + sys.exit(pytest.main([__file__, "-v"])) diff --git a/asian_ai/performance/SGLang/test/registered/attention/test_kda_prefill_flashkda.py b/asian_ai/performance/SGLang/test/registered/attention/test_kda_prefill_flashkda.py new file mode 100644 index 0000000000000000000000000000000000000000..270dab193ab2b2bf012b781b3d6d67f46c798ac1 --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/attention/test_kda_prefill_flashkda.py @@ -0,0 +1,201 @@ +"""Correctness test for the FlashKDA prefill backend (safe-gate KDA). + +Validates ``FlashKDAKernel`` (the external ``flash_kda`` fused CUTLASS kernel) +against the production Triton ``chunk_kda`` safe-gate reference. FlashKDA only +implements the safe/bounded gate, so this exercises ``lower_bound=-5``. + +Requires an SM90+ GPU and the ``flash_kda`` package +(``pip install git+https://github.com/MoonshotAI/FlashKDA.git``); skips +otherwise. Mirrors ``test_kda_prefill_cutedsl.py``. +""" + +import pytest +import torch + +from sglang.test.ci.ci_register import register_cuda_ci + +# SM90+ single-GPU kernel-unit suite. Disabled in CI: flash_kda is not in the +# public runner image, and the module-level pytest.skip aborts non-zero under +# `python3 file.py`. Drop `disabled=` once flash_kda ships in the runner image; +# still runs locally / on internal CI where it is installed. +register_cuda_ci( + est_time=20, + stage="base-b", + runner_config="1-gpu-large", + disabled="flash_kda not in public CI runner image (only on Ant-internal PyPI)", +) + +if not (torch.cuda.is_available() and torch.cuda.get_device_capability()[0] >= 9): + pytest.skip( + "FlashKDA requires CUDA SM90+ (Hopper or newer).", + allow_module_level=True, + ) +try: + import flash_kda # noqa: F401 +except ImportError: + pytest.skip( + "flash_kda not installed " + "(pip install git+https://github.com/MoonshotAI/FlashKDA.git).", + allow_module_level=True, + ) + +from sglang.srt.layers.attention.fla.kda import chunk_kda # noqa: E402 +from sglang.srt.layers.attention.linear.kernels.kda_flashkda import ( # noqa: E402 + FlashKDAKernel, +) + +LOWER_BOUND = -5.0 +H, K, V = 16, 128, 128 # FlashKDA requires K == V == 128, HV == H + + +def _cos(a: torch.Tensor, b: torch.Tensor) -> float: + return torch.nn.functional.cosine_similarity( + a.float().flatten(), b.float().flatten(), dim=0 + ).item() + + +def _make_inputs(seq_lens): + n = len(seq_lens) + cu = torch.zeros(n + 1, device="cuda", dtype=torch.int32) + cu[1:] = torch.tensor(seq_lens, device="cuda").cumsum(0) + total = int(cu[-1].item()) + idx = torch.arange(n, device="cuda", dtype=torch.int32) + return dict( + cu=cu, + idx=idx, + # RAW q/k (FlashKDA L2-norms internally; chunk_kda via use_qk_l2norm). + q=torch.randn(1, total, H, K, device="cuda", dtype=torch.bfloat16) * 0.5, + k=torch.randn(1, total, H, K, device="cuda", dtype=torch.bfloat16) * 0.5, + v=torch.randn(1, total, H, V, device="cuda", dtype=torch.bfloat16) * 0.5, + g=torch.randn(1, total, H, K, device="cuda", dtype=torch.bfloat16) * 0.5, + # post-sigmoid beta in [0.1, 0.9] (FlashKDA inverts to logits internally). + beta=(torch.rand(1, total, H, device="cuda") * 0.8 + 0.1).to(torch.bfloat16), + A_log=torch.randn(1, 1, H, 1, device="cuda", dtype=torch.float32) * 0.5, + dt_bias=torch.randn(H * K, device="cuda", dtype=torch.float32) * 0.1, + pool=torch.randn(n, H, V, K, device="cuda", dtype=torch.float32) * 0.1, + ) + + +def _chunk_kda_ref(d, lower_bound): + """Triton chunk_kda reference. chunk_kda mutates g/v and the state in place, + so feed clones; returns (output, updated_state_slots).""" + st = d["pool"].clone() + out = chunk_kda( + q=d["q"].clone(), + k=d["k"].clone(), + v=d["v"].clone(), + g=d["g"].clone(), + beta=d["beta"].clone(), + initial_state=st, + initial_state_indices=d["idx"], + use_qk_l2norm_in_kernel=True, + cu_seqlens=d["cu"], + A_log=d["A_log"], + dt_bias=d["dt_bias"], + lower_bound=lower_bound, + ) + return out, st[d["idx"]] + + +@pytest.mark.parametrize("seq_lens", [[128], [128, 384, 512], [96] * 4]) +def test_flashkda_matches_triton_safe_gate(seq_lens): + torch.manual_seed(len(seq_lens)) + d = _make_inputs(seq_lens) + + ref_out, ref_state = _chunk_kda_ref(d, LOWER_BOUND) + + st_fk = d["pool"].clone() + out = FlashKDAKernel().extend( + d["q"].clone(), + d["k"].clone(), + d["v"].clone(), + d["g"].clone(), + d["beta"].clone(), + ssm_states=st_fk, + cache_indices=d["idx"], + query_start_loc=d["cu"], + A_log=d["A_log"], + dt_bias=d["dt_bias"], + lower_bound=LOWER_BOUND, + extend_seq_lens_cpu=seq_lens, + ) + torch.cuda.synchronize() + + assert torch.isfinite(out).all(), "FlashKDA output has non-finite values" + assert torch.isfinite(st_fk).all(), "FlashKDA final state has non-finite values" + # bf16 cross-implementation noise (chunk=16 CUTLASS vs chunk=64 Triton); + # measured cos ~0.985 output / ~0.9999 state on H20-3e and B200. + assert _cos(ref_out, out) > 0.95, f"output cos too low: {_cos(ref_out, out):.4f}" + assert ( + _cos(ref_state, st_fk[d["idx"]]) > 0.99 + ), f"state cos too low: {_cos(ref_state, st_fk[d['idx']]):.4f}" + + +def test_flashkda_falls_back_without_lower_bound(): + """Unbounded gate (lower_bound=None): FlashKDA must route to the Triton + chunk_kda fallback (it only supports the safe gate).""" + torch.manual_seed(0) + d = _make_inputs([256]) + + ref_out, _ = _chunk_kda_ref(d, None) + + st_fk = d["pool"].clone() + out = FlashKDAKernel().extend( + d["q"].clone(), + d["k"].clone(), + d["v"].clone(), + d["g"].clone(), + d["beta"].clone(), + ssm_states=st_fk, + cache_indices=d["idx"], + query_start_loc=d["cu"], + A_log=d["A_log"], + dt_bias=d["dt_bias"], + lower_bound=None, + extend_seq_lens_cpu=[256], + ) + torch.cuda.synchronize() + + assert torch.isfinite(out).all() + # Same Triton code path as the reference -> matches closely. + assert _cos(ref_out, out) > 0.999, f"fallback cos too low: {_cos(ref_out, out):.4f}" + + +def test_flashkda_spec_verify_falls_back(): + """Speculative verify / draft-extend (is_spec_decode=True) must route to the + Triton fallback even with a safe gate and in-range seqs -- FlashKDA commits + the recurrent state in place, which would break draft rollback.""" + torch.manual_seed(0) + d = _make_inputs([256]) + ref_out, _ = _chunk_kda_ref(d, LOWER_BOUND) + + st_fk = d["pool"].clone() + out = FlashKDAKernel().extend( + d["q"].clone(), + d["k"].clone(), + d["v"].clone(), + d["g"].clone(), + d["beta"].clone(), + ssm_states=st_fk, + cache_indices=d["idx"], + query_start_loc=d["cu"], + A_log=d["A_log"], + dt_bias=d["dt_bias"], + lower_bound=LOWER_BOUND, + extend_seq_lens_cpu=[256], + is_spec_decode=True, + ) + torch.cuda.synchronize() + + assert torch.isfinite(out).all() + # Took the Triton fallback (not FlashKDA) -> matches chunk_kda closely. If + # FlashKDA had run, the cross-impl cos would be ~0.985 and this would fail. + assert ( + _cos(ref_out, out) > 0.999 + ), f"spec-decode did not fall back: {_cos(ref_out, out):.4f}" + + +if __name__ == "__main__": + import sys + + sys.exit(pytest.main([__file__, "-v"])) diff --git a/asian_ai/performance/SGLang/test/registered/attention/test_normal_decode_set_metadata.py b/asian_ai/performance/SGLang/test/registered/attention/test_normal_decode_set_metadata.py new file mode 100644 index 0000000000000000000000000000000000000000..e1c7a5154a0fa3af5f9158ada5cae31e60f16b3d --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/attention/test_normal_decode_set_metadata.py @@ -0,0 +1,419 @@ +""" +Unit tests for the fused Triton kernel in normal_decode_set_metadata. + +This test suite verifies: +1. Correctness against reference PyTorch implementation +2. Different page sizes (1, 16, 64) +3. With and without Sliding Window Attention (SWA) +4. Various batch sizes and sequence lengths +5. Edge cases +""" + +import unittest + +import torch + +from sglang.srt.layers.attention.flashattention_backend import ( + normal_decode_set_metadata, +) +from sglang.srt.mem_cache.swa_memory_pool import SWAKVPool +from sglang.test.ci.ci_register import register_amd_ci, register_cuda_ci +from sglang.test.test_utils import CustomTestCase + +# Register this test for CUDA CI in base-b (fast attention/kernel tests) +register_cuda_ci(est_time=11, stage="base-b", runner_config="1-gpu-large") +register_amd_ci(est_time=17, suite="stage-b-test-1-gpu-large-amd") + + +def reference_normal_decode_set_metadata( + cache_seqlens_int32: torch.Tensor, + cu_seqlens_k: torch.Tensor, + page_table: torch.Tensor, + req_to_token: torch.Tensor, + req_pool_indices: torch.Tensor, + strided_indices: torch.Tensor, + max_seq_pages: int, + seq_lens: torch.Tensor, + seq_len_delta: int, + page_size: int, + swa_page_table: torch.Tensor = None, + token_to_kv_pool=None, +): + """ + Reference implementation using original PyTorch operations. + This is the pre-Triton version for correctness comparison. + """ + cache_seqlens_int32.copy_(seq_lens + seq_len_delta) + cu_seqlens_k[1:].copy_(torch.cumsum(cache_seqlens_int32, dim=0, dtype=torch.int32)) + page_indices = req_to_token[ + req_pool_indices[:, None], + strided_indices[:max_seq_pages][None, :], + ] + page_table[:, :max_seq_pages].copy_(page_indices // page_size) + + if swa_page_table is not None and token_to_kv_pool is not None: + swa_page_indices = token_to_kv_pool.translate_loc_from_full_to_swa(page_indices) + swa_page_table[:, :max_seq_pages].copy_(swa_page_indices // page_size) + + +@unittest.skipIf(not torch.cuda.is_available(), "Test requires CUDA") +class TestNormalDecodeSetMetadata(CustomTestCase): + """Test fused Triton kernel in normal_decode_set_metadata.""" + + def setUp(self): + self.device = "cuda" + self.dtype = torch.int32 + + def _create_test_data( + self, + batch_size: int, + max_seq_len: int, + page_size: int, + has_swa: bool = False, + seq_len_delta: int = 0, + ): + """Create test data for normal_decode_set_metadata.""" + # Random sequence lengths for each batch + seq_lens = torch.randint( + max_seq_len // 2, + max_seq_len + 1, + (batch_size,), + dtype=torch.int64, + device=self.device, + ) + + # Calculate max_seq_pages + max_len = seq_lens.max().item() + max_seq_pages = (max_len + seq_len_delta + page_size - 1) // page_size + + # Create req_pool_indices (maps batch index to pool index) + req_pool_indices = torch.arange( + batch_size, dtype=torch.int32, device=self.device + ) + + # Create strided_indices for page table indexing + if page_size == 1: + strided_indices = torch.arange( + max_seq_len * 2, dtype=torch.int32, device=self.device + ) + else: + strided_indices = torch.arange( + 0, max_seq_len * 2, page_size, dtype=torch.int32, device=self.device + ) + + # Create req_to_token pool (simulates token locations in KV cache) + pool_size = batch_size + max_tokens = max_seq_len * 2 + req_to_token = torch.randint( + 0, 10000, (pool_size, max_tokens), dtype=torch.int32, device=self.device + ) + + # Output tensors (to be filled by the function) + cache_seqlens_int32 = torch.zeros( + batch_size, dtype=torch.int32, device=self.device + ) + cu_seqlens_k = torch.zeros( + batch_size + 1, dtype=torch.int32, device=self.device + ) + page_table = torch.zeros( + (batch_size, max_seq_pages + 10), dtype=torch.int32, device=self.device + ) + + # SWA setup if needed + swa_page_table = None + token_to_kv_pool = None + if has_swa: + swa_page_table = torch.zeros( + (batch_size, max_seq_pages + 10), dtype=torch.int32, device=self.device + ) + # Create a simple SWA KV pool for testing + token_to_kv_pool = self._create_swa_kv_pool(10000, page_size) + + return { + "cache_seqlens_int32": cache_seqlens_int32, + "cu_seqlens_k": cu_seqlens_k, + "page_table": page_table, + "req_to_token": req_to_token, + "req_pool_indices": req_pool_indices, + "strided_indices": strided_indices, + "max_seq_pages": max_seq_pages, + "seq_lens": seq_lens, + "seq_len_delta": seq_len_delta, + "page_size": page_size, + "swa_page_table": swa_page_table, + "token_to_kv_pool": token_to_kv_pool, + } + + def _create_swa_kv_pool(self, size: int, page_size: int): + """Create a mock SWA KV pool for testing that inherits from SWAKVPool.""" + + # Create a minimal mock that inherits from SWAKVPool to pass isinstance check + class MinimalSWAKVPool(SWAKVPool): + def __init__(self, size, device): + # Don't call super().__init__() to avoid complex initialization + # Just set the minimal attributes needed for the test + self.full_to_swa_index_mapping = torch.arange( + size, dtype=torch.int32, device=device + ) + # Add some randomness to simulate real SWA mapping + self.full_to_swa_index_mapping = ( + self.full_to_swa_index_mapping + + torch.randint(0, 100, (size,), device=device) + ) % size + self.device = device + + def translate_loc_from_full_to_swa(self, page_indices): + """Mock translation method.""" + return self.full_to_swa_index_mapping[page_indices] + + return MinimalSWAKVPool(size, self.device) + + def _run_test( + self, + batch_size: int, + max_seq_len: int, + page_size: int, + has_swa: bool = False, + seq_len_delta: int = 0, + ): + """Run a single test configuration.""" + # Create test data + test_data = self._create_test_data( + batch_size, max_seq_len, page_size, has_swa, seq_len_delta + ) + + # Clone data for reference implementation + ref_data = { + "cache_seqlens_int32": test_data["cache_seqlens_int32"].clone(), + "cu_seqlens_k": test_data["cu_seqlens_k"].clone(), + "page_table": test_data["page_table"].clone(), + "swa_page_table": test_data["swa_page_table"].clone() if has_swa else None, + } + + # Run reference implementation + reference_normal_decode_set_metadata( + ref_data["cache_seqlens_int32"], + ref_data["cu_seqlens_k"], + ref_data["page_table"], + test_data["req_to_token"], + test_data["req_pool_indices"], + test_data["strided_indices"], + test_data["max_seq_pages"], + test_data["seq_lens"], + test_data["seq_len_delta"], + test_data["page_size"], + ref_data["swa_page_table"], + test_data["token_to_kv_pool"], + ) + + # Run fused Triton implementation + normal_decode_set_metadata( + test_data["cache_seqlens_int32"], + test_data["cu_seqlens_k"], + test_data["page_table"], + test_data["req_to_token"], + test_data["req_pool_indices"], + test_data["strided_indices"], + test_data["max_seq_pages"], + test_data["seq_lens"], + test_data["seq_len_delta"], + test_data["page_size"], + test_data["swa_page_table"], + test_data["token_to_kv_pool"], + ) + + # Compare results + self.assertTrue( + torch.equal( + test_data["cache_seqlens_int32"], ref_data["cache_seqlens_int32"] + ), + f"cache_seqlens_int32 mismatch. Expected:\n{ref_data['cache_seqlens_int32']}\nGot:\n{test_data['cache_seqlens_int32']}", + ) + + self.assertTrue( + torch.equal(test_data["cu_seqlens_k"], ref_data["cu_seqlens_k"]), + f"cu_seqlens_k mismatch. Expected:\n{ref_data['cu_seqlens_k']}\nGot:\n{test_data['cu_seqlens_k']}", + ) + + self.assertTrue( + torch.equal(test_data["page_table"], ref_data["page_table"]), + f"page_table mismatch at bs={batch_size}, page_size={page_size}", + ) + + if has_swa: + self.assertTrue( + torch.equal(test_data["swa_page_table"], ref_data["swa_page_table"]), + f"swa_page_table mismatch at bs={batch_size}, page_size={page_size}", + ) + + # Test cases for page_size=1 (uses specialized kernel _fused_metadata_kernel_ps1_no_swa) + def test_page_size_1_small_batch(self): + """Test with page_size=1, small batch.""" + self._run_test(batch_size=2, max_seq_len=128, page_size=1, has_swa=False) + + def test_page_size_1_medium_batch(self): + """Test with page_size=1, medium batch.""" + self._run_test(batch_size=16, max_seq_len=256, page_size=1, has_swa=False) + + def test_page_size_1_large_batch(self): + """Test with page_size=1, large batch.""" + self._run_test(batch_size=64, max_seq_len=512, page_size=1, has_swa=False) + + def test_page_size_1_with_seq_len_delta(self): + """Test with page_size=1 and seq_len_delta > 0.""" + self._run_test( + batch_size=8, max_seq_len=200, page_size=1, has_swa=False, seq_len_delta=5 + ) + + # Test cases for page_size > 1 (uses general kernel _fused_metadata_kernel_general) + def test_page_size_16_small_batch(self): + """Test with page_size=16, small batch.""" + self._run_test(batch_size=4, max_seq_len=256, page_size=16, has_swa=False) + + def test_page_size_16_medium_batch(self): + """Test with page_size=16, medium batch.""" + self._run_test(batch_size=16, max_seq_len=512, page_size=16, has_swa=False) + + def test_page_size_64_small_batch(self): + """Test with page_size=64, small batch.""" + self._run_test(batch_size=4, max_seq_len=512, page_size=64, has_swa=False) + + def test_page_size_64_medium_batch(self): + """Test with page_size=64, medium batch.""" + self._run_test(batch_size=32, max_seq_len=1024, page_size=64, has_swa=False) + + def test_page_size_64_with_seq_len_delta(self): + """Test with page_size=64 and seq_len_delta > 0.""" + self._run_test( + batch_size=8, max_seq_len=512, page_size=64, has_swa=False, seq_len_delta=3 + ) + + # Test cases with Sliding Window Attention (SWA) + def test_page_size_16_with_swa(self): + """Test with page_size=16 and SWA enabled.""" + self._run_test(batch_size=8, max_seq_len=256, page_size=16, has_swa=True) + + def test_page_size_64_with_swa(self): + """Test with page_size=64 and SWA enabled.""" + self._run_test(batch_size=16, max_seq_len=512, page_size=64, has_swa=True) + + def test_page_size_64_with_swa_and_delta(self): + """Test with page_size=64, SWA, and seq_len_delta.""" + self._run_test( + batch_size=8, max_seq_len=400, page_size=64, has_swa=True, seq_len_delta=2 + ) + + # Edge cases + def test_batch_size_1(self): + """Test with single batch.""" + self._run_test(batch_size=1, max_seq_len=128, page_size=1, has_swa=False) + self._run_test(batch_size=1, max_seq_len=256, page_size=64, has_swa=False) + + def test_max_seq_pages_small(self): + """Test edge case where max_seq_pages could be very small.""" + # This tests when sequences are very short + test_data = self._create_test_data( + batch_size=2, max_seq_len=10, page_size=64, has_swa=False + ) + + # Run fused implementation (should handle gracefully) + normal_decode_set_metadata( + test_data["cache_seqlens_int32"], + test_data["cu_seqlens_k"], + test_data["page_table"], + test_data["req_to_token"], + test_data["req_pool_indices"], + test_data["strided_indices"], + test_data["max_seq_pages"], + test_data["seq_lens"], + test_data["seq_len_delta"], + test_data["page_size"], + test_data["swa_page_table"], + test_data["token_to_kv_pool"], + ) + + # Verify no crashes and basic properties + self.assertEqual( + test_data["cache_seqlens_int32"].sum().item(), + test_data["seq_lens"].sum().item(), + ) + + def test_power_of_two_page_sizes(self): + """Test various power-of-2 page sizes.""" + page_sizes = [1, 2, 4, 8, 16, 32, 64, 128] + for page_size in page_sizes: + with self.subTest(page_size=page_size): + self._run_test( + batch_size=4, max_seq_len=256, page_size=page_size, has_swa=False + ) + + def test_varied_sequence_lengths(self): + """Test with highly varied sequence lengths in the same batch.""" + batch_size = 8 + max_seq_len = 512 + page_size = 64 + + test_data = self._create_test_data( + batch_size, max_seq_len, page_size, has_swa=False + ) + + # Manually set varied sequence lengths + test_data["seq_lens"] = torch.tensor( + [10, 50, 100, 200, 300, 450, 500, 512], + dtype=torch.int64, + device=self.device, + ) + test_data["max_seq_pages"] = ( + test_data["seq_lens"].max().item() + page_size - 1 + ) // page_size + + # Run both implementations + ref_data = { + "cache_seqlens_int32": test_data["cache_seqlens_int32"].clone(), + "cu_seqlens_k": test_data["cu_seqlens_k"].clone(), + "page_table": test_data["page_table"].clone(), + } + + reference_normal_decode_set_metadata( + ref_data["cache_seqlens_int32"], + ref_data["cu_seqlens_k"], + ref_data["page_table"], + test_data["req_to_token"], + test_data["req_pool_indices"], + test_data["strided_indices"], + test_data["max_seq_pages"], + test_data["seq_lens"], + 0, + page_size, + None, + None, + ) + + normal_decode_set_metadata( + test_data["cache_seqlens_int32"], + test_data["cu_seqlens_k"], + test_data["page_table"], + test_data["req_to_token"], + test_data["req_pool_indices"], + test_data["strided_indices"], + test_data["max_seq_pages"], + test_data["seq_lens"], + 0, + page_size, + None, + None, + ) + + self.assertTrue( + torch.equal( + test_data["cache_seqlens_int32"], ref_data["cache_seqlens_int32"] + ) + ) + self.assertTrue( + torch.equal(test_data["cu_seqlens_k"], ref_data["cu_seqlens_k"]) + ) + self.assertTrue(torch.equal(test_data["page_table"], ref_data["page_table"])) + + +if __name__ == "__main__": + unittest.main() diff --git a/asian_ai/performance/SGLang/test/registered/attention/test_qwen35_deterministic.py b/asian_ai/performance/SGLang/test/registered/attention/test_qwen35_deterministic.py new file mode 100644 index 0000000000000000000000000000000000000000..d27186b88f32879d0ec310f6f6275ebe34288746 --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/attention/test_qwen35_deterministic.py @@ -0,0 +1,44 @@ +""" +Usage: +cd test/srt +python3 -m unittest test_qwen35_deterministic.TestQwen35Fa3Deterministic +""" + +import unittest + +from sglang.test.ci.ci_register import register_cuda_ci +from sglang.test.test_deterministic_utils import ( + COMMON_SERVER_ARGS, + TestDeterministicBase, +) + +register_cuda_ci(est_time=360, stage="extra-b", runner_config="4-gpu-h100") + +QWEN35 = "Qwen/Qwen3.5-35B-A3B" + + +class TestQwen35Fa3Deterministic(TestDeterministicBase): + @classmethod + def get_model(cls): + return QWEN35 + + @classmethod + def get_server_args(cls): + return list(COMMON_SERVER_ARGS) + [ + "--tp", + "4", + "--attention-backend", + "fa3", + "--skip-server-warmup", + "--mamba-scheduler-strategy", + "extra_buffer", + "--enable-flashinfer-allreduce-fusion", + "--tokenizer-worker-num", + "6", + "--mem-fraction-static", + "0.8", + ] + + +if __name__ == "__main__": + unittest.main() diff --git a/asian_ai/performance/SGLang/test/registered/attention/test_qwen3_next_deterministic.py b/asian_ai/performance/SGLang/test/registered/attention/test_qwen3_next_deterministic.py new file mode 100644 index 0000000000000000000000000000000000000000..c30a98b21742405649bd33836bf5a798a38feed7 --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/attention/test_qwen3_next_deterministic.py @@ -0,0 +1,47 @@ +""" +Usage: +cd test/srt +python3 -m unittest test_qwen3_next_deterministic.TestFlashInferDeterministic +""" + +import unittest + +from sglang.test.ci.ci_register import register_cuda_ci +from sglang.test.test_deterministic_utils import ( + COMMON_SERVER_ARGS, + TestDeterministicBase, +) + +register_cuda_ci(est_time=200, suite="nightly-4-gpu", nightly=True) + +QWEN3_NEXT = "Qwen/Qwen3-Next-80B-A3B-Instruct" + + +class TestFlashInferDeterministic(TestDeterministicBase): + @classmethod + def get_model(cls): + return QWEN3_NEXT + + # Test with flashinfer attention backend + @classmethod + def get_server_args(cls): + args = COMMON_SERVER_ARGS + args.extend(["--attention-backend", "flashinfer", "--tp", "4"]) + return args + + +class TestTritonDeterministic(TestDeterministicBase): + @classmethod + def get_model(cls): + return QWEN3_NEXT + + # Test with triton attention backend + @classmethod + def get_server_args(cls): + args = COMMON_SERVER_ARGS + args.extend(["--attention-backend", "triton", "--tp", "4"]) + return args + + +if __name__ == "__main__": + unittest.main() diff --git a/asian_ai/performance/SGLang/test/registered/attention/test_torch_native_attention_backend.py b/asian_ai/performance/SGLang/test/registered/attention/test_torch_native_attention_backend.py new file mode 100644 index 0000000000000000000000000000000000000000..8fffc1c9efe03e1efe2b732227416bcbc7541afc --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/attention/test_torch_native_attention_backend.py @@ -0,0 +1,52 @@ +""" +Usage: +python3 -m unittest test_torch_native_attention_backend.TestTorchNativeAttnBackend.test_mmlu +""" + +import unittest +from types import SimpleNamespace + +from sglang.srt.utils import kill_process_tree +from sglang.test.ci.ci_register import register_amd_ci, register_cuda_ci +from sglang.test.run_eval import run_eval +from sglang.test.test_utils import ( + DEFAULT_MODEL_NAME_FOR_TEST, + DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH, + DEFAULT_URL_FOR_TEST, + CustomTestCase, + popen_launch_server, +) + +# Torch native attention backend integration test with MMLU eval +register_cuda_ci(est_time=140, stage="extra-a", runner_config="1-gpu-small") +register_amd_ci(est_time=150, suite="stage-b-test-1-gpu-small-amd") + + +class TestTorchNativeAttnBackend(CustomTestCase): + def test_mmlu(self): + model = DEFAULT_MODEL_NAME_FOR_TEST + base_url = DEFAULT_URL_FOR_TEST + process = popen_launch_server( + model, + base_url, + timeout=DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH, + other_args=["--attention-backend", "torch_native"], + ) + + try: + args = SimpleNamespace( + base_url=base_url, + model=model, + eval_name="mmlu", + num_examples=64, + num_threads=32, + ) + + metrics = run_eval(args) + self.assertGreaterEqual(metrics["score"], 0.65) + finally: + kill_process_tree(process.pid) + + +if __name__ == "__main__": + unittest.main() diff --git a/asian_ai/performance/SGLang/test/registered/attention/test_triton_attention_backend.py b/asian_ai/performance/SGLang/test/registered/attention/test_triton_attention_backend.py new file mode 100644 index 0000000000000000000000000000000000000000..fab82390e90745a2133198cdc1aafca9079c504a --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/attention/test_triton_attention_backend.py @@ -0,0 +1,71 @@ +""" +Usage: +python3 -m unittest test_triton_attention_backend.TestTritonAttnBackend.test_mmlu +""" + +import unittest +from types import SimpleNamespace + +from sglang.srt.utils import kill_process_tree +from sglang.test.ci.ci_register import register_amd_ci, register_cuda_ci +from sglang.test.run_eval import run_eval +from sglang.test.test_utils import ( + DEFAULT_MODEL_NAME_FOR_TEST, + DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH, + DEFAULT_URL_FOR_TEST, + CustomTestCase, + is_in_ci, + popen_launch_server, + run_bench_offline_throughput, +) + +# Triton attention backend integration test with latency benchmark and MMLU eval +register_cuda_ci(est_time=177, stage="base-b", runner_config="1-gpu-large") +register_amd_ci(est_time=1400, suite="stage-b-test-1-gpu-small-amd") + + +class TestTritonAttnBackend(CustomTestCase): + def test_latency(self): + output_throughput = run_bench_offline_throughput( + DEFAULT_MODEL_NAME_FOR_TEST, + [ + "--attention-backend", + "triton", + "--enable-torch-compile", + "--cuda-graph-max-bs-decode", + 4, + ], + ) + + print(f"{output_throughput=}") + + if is_in_ci(): + self.assertGreater(output_throughput, 153) + + def test_mmlu(self): + model = DEFAULT_MODEL_NAME_FOR_TEST + base_url = DEFAULT_URL_FOR_TEST + process = popen_launch_server( + model, + base_url, + timeout=DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH, + other_args=["--attention-backend", "triton"], + ) + + try: + args = SimpleNamespace( + base_url=base_url, + model=model, + eval_name="mmlu", + num_examples=64, + num_threads=32, + ) + + metrics = run_eval(args) + self.assertGreaterEqual(metrics["score"], 0.65) + finally: + kill_process_tree(process.pid) + + +if __name__ == "__main__": + unittest.main() diff --git a/asian_ai/performance/SGLang/test/registered/attention/test_triton_attention_kernels.py b/asian_ai/performance/SGLang/test/registered/attention/test_triton_attention_kernels.py new file mode 100644 index 0000000000000000000000000000000000000000..c825645f5be8c4c0050579f79eab0a864bd2d11e --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/attention/test_triton_attention_kernels.py @@ -0,0 +1,890 @@ +import random +import unittest + +import torch +import torch.nn.functional as F + +from sglang.srt.layers.attention.triton_ops.decode_attention import ( + decode_attention_fwd, + decode_attention_fwd_grouped, + decode_attention_fwd_normal, +) +from sglang.srt.layers.attention.triton_ops.extend_attention import ( + build_unified_kv_indices, + extend_attention_fwd, + extend_attention_fwd_unified, + redundant_attention, +) +from sglang.srt.layers.attention.triton_ops.prefill_attention import ( + context_attention_fwd, +) +from sglang.srt.utils import get_device +from sglang.test.ci.ci_register import register_amd_ci, register_cuda_ci +from sglang.test.test_utils import CustomTestCase, is_in_amd_ci + +# Triton attention kernel unit tests (decode, extend, prefill) +register_cuda_ci(est_time=19, stage="base-b", runner_config="1-gpu-large") +register_amd_ci(est_time=30, suite="stage-b-test-1-gpu-small-amd") + + +def extend_attention_fwd_torch( + q: torch.Tensor, # [extend_tokens, H_Q, D] + k: torch.Tensor, # [extend_tokens, H_KV, D] + v: torch.Tensor, # [extend_tokens, H_KV, D] + o: torch.Tensor, # [extend_tokens, H_Q, D] + k_cache: torch.Tensor, # [total_tokens, H_KV, D] + v_cache: torch.Tensor, # [total_tokens, H_KV, D] + qo_indptr: torch.Tensor, # [B+1] + kv_indptr: torch.Tensor, # [B+1] + kv_indices: torch.Tensor, # [prefix_tokens] + sliding_window_size: int, +): + B = qo_indptr.size(0) - 1 + _, H_Q, D = q.shape + _, H_KV, _ = k.shape + + group_size = H_Q // H_KV + scale = 1.0 / D**0.5 + + for i in range(B): + q_start = int(qo_indptr[i].item()) + q_end = int(qo_indptr[i + 1].item()) + kv_start = int(kv_indptr[i].item()) + kv_end = int(kv_indptr[i + 1].item()) + + prefix_indices = kv_indices[kv_start:kv_end] + k_prefix = k_cache[prefix_indices] # [prefix_len, H_KV, D] + v_prefix = v_cache[prefix_indices] # [prefix_len, H_KV, D] + + k_extend = k[q_start:q_end] # [extend_len, H_KV, D] + v_extend = v[q_start:q_end] # [extend_len, H_KV, D] + q_extend = q[q_start:q_end] # [extend_len, H_Q, D] + + k_full = torch.cat([k_prefix, k_extend], dim=0) # [total_len, H_KV, D] + v_full = torch.cat([v_prefix, v_extend], dim=0) # [total_len, H_KV, D] + + if group_size != 1: + k_full_hq = k_full.repeat_interleave( + group_size, dim=1 + ) # [total_len, H_Q, D] + v_full_hq = v_full.repeat_interleave( + group_size, dim=1 + ) # [total_len, H_Q, D] + else: + k_full_hq = k_full + v_full_hq = v_full + + prefix_len = k_prefix.size(0) + extend_len = k_extend.size(0) + total_len = prefix_len + extend_len + + # causal + pos_keys = torch.arange(total_len, device=q.device) + t = prefix_len + torch.arange(extend_len, device=q.device) # [extend_len] + causal_mask = pos_keys.unsqueeze(0) <= t.unsqueeze(1) + + # sliding window + if sliding_window_size is not None and sliding_window_size > 0: + start = (t - (sliding_window_size)).clamp_min(0) # [extend_len] + else: + start = torch.zeros_like(t) + window_mask = pos_keys.unsqueeze(0) >= start.unsqueeze(1) + + final_mask = causal_mask & window_mask + + attn_scores = ( + torch.einsum("qhd,khd->qhk", q_extend, k_full_hq) * scale + ) # [extend_len, H_Q, total_len] + attn_scores = attn_scores.masked_fill(~final_mask.unsqueeze(1), float("-inf")) + + attn_weights = F.softmax(attn_scores, dim=-1) + o[q_start:q_end] = torch.einsum("qhk,khd->qhd", attn_weights, v_full_hq) + + +def decode_attention_fwd_torch( + q: torch.Tensor, # [B, H_Q, D] + k_buffer: torch.Tensor, # [total_tokens, H_KV, D] + v_buffer: torch.Tensor, # [total_tokens, H_KV, D] + kv_indptr: torch.Tensor, # [B+1] + kv_indices: torch.Tensor, # [prefix_tokens] + sm_scale: float, +): + """ + Torch reference implementation for decode attention with stable softmax. + Supports both MHA and GQA configurations. + """ + B = kv_indptr.size(0) - 1 + _, H_Q, D = q.shape + _, H_KV, _ = k_buffer.shape + + assert H_Q % H_KV == 0, "H_Q must be divisible by H_KV for GQA" + group_size = H_Q // H_KV + + o_ref = torch.empty((B, H_Q, D), dtype=torch.float32, device=q.device) + + for b in range(B): + start = int(kv_indptr[b].item()) + end = int(kv_indptr[b + 1].item()) + idx = kv_indices[start:end] + + k_seq = k_buffer.index_select(0, idx) # [L, H_KV, D] + v_seq = v_buffer.index_select(0, idx) # [L, H_KV, D] + + if H_KV != H_Q: + k_seq = k_seq.repeat_interleave(group_size, dim=1) # [L, H_Q, D] + v_seq = v_seq.repeat_interleave(group_size, dim=1) # [L, H_Q, D] + + q_f32 = q[b].to(torch.float32) # [H_Q, D] + k_f32 = k_seq.to(torch.float32) # [L, H_Q, D] + v_f32 = v_seq.to(torch.float32) # [L, H_Q, D] + + # logits: [H_Q, L] + logits = torch.einsum("hd,lhd->hl", q_f32, k_f32) * float(sm_scale) + logits = logits - logits.max(dim=-1, keepdim=True).values + p = torch.softmax(logits, dim=-1) # [H_Q, L] + + # out: [H_Q, D] + o_ref[b] = torch.einsum("hl,lhd->hd", p, v_f32) + + return o_ref + + +class TestTritonAttention(CustomTestCase): + + def _set_all_seeds(self, seed): + """Set all random seeds for reproducibility.""" + random.seed(seed) + torch.manual_seed(seed) + torch.cuda.manual_seed(seed) + torch.cuda.manual_seed_all(seed) + torch.backends.cudnn.deterministic = True + torch.backends.cudnn.benchmark = False + + def setUp(self): + # Set seeds before each test method + self._set_all_seeds(42) + + def _test_extend_attention_once(self, B, N_CTX, H_Q, H_KV, D): + dtype = torch.bfloat16 + device = get_device() + + b_seq_len_prefix = torch.randint( + 1, N_CTX // 2, (B,), dtype=torch.int32, device=device + ) + b_seq_len_extend = torch.randint( + 1, N_CTX // 2, (B,), dtype=torch.int32, device=device + ) + b_seq_len = b_seq_len_prefix + b_seq_len_extend + max_len_in_batch = torch.max(b_seq_len, 0)[0].item() + + b_req_idx = torch.arange(B, dtype=torch.int32, device=device) + b_start_loc = torch.zeros((B,), dtype=torch.int32, device=device) + b_start_loc[1:] = torch.cumsum(b_seq_len[:-1], 0) + b_start_loc_extend = torch.zeros((B,), dtype=torch.int32, device=device) + b_start_loc_extend[1:] = torch.cumsum(b_seq_len_extend[:-1], 0) + + kv_indptr = torch.zeros((B + 1,), dtype=torch.int32, device=device) + kv_indptr[1 : B + 1] = torch.cumsum(b_seq_len_prefix[:B], dim=0) + kv_indices = torch.zeros( + (b_seq_len_prefix.sum().item(),), dtype=torch.int32, device=device + ) + + for i in range(B): + kv_indices[kv_indptr[i] : kv_indptr[i + 1]] = torch.arange( + b_start_loc[i], b_start_loc[i] + b_seq_len_prefix[i] + ) + + total_token_num = torch.sum(b_seq_len).item() + extend_token_num = torch.sum(b_seq_len_extend).item() + k_buffer = torch.empty( + (total_token_num, H_KV, D), dtype=dtype, device=device + ).normal_(mean=0.1, std=0.2) + v_buffer = torch.empty( + (total_token_num, H_KV, D), dtype=dtype, device=device + ).normal_(mean=0.1, std=0.2) + + k_extend = torch.empty((extend_token_num, H_KV, D), dtype=dtype, device=device) + v_extend = torch.empty((extend_token_num, H_KV, D), dtype=dtype, device=device) + q_extend = torch.empty((extend_token_num, H_Q, D), dtype=dtype, device=device) + for i in range(B): + extend_start_in_buffer = b_start_loc[i] + b_seq_len_prefix[i] + extend_end_in_buffer = b_start_loc[i] + b_seq_len[i] + extend_start = b_start_loc_extend[i] + extend_end = b_start_loc_extend[i] + b_seq_len_extend[i] + k_extend[extend_start:extend_end] = k_buffer[ + extend_start_in_buffer:extend_end_in_buffer + ] + v_extend[extend_start:extend_end] = v_buffer[ + extend_start_in_buffer:extend_end_in_buffer + ] + q_extend[extend_start:extend_end] = torch.empty( + (b_seq_len_extend[i], H_Q, D), dtype=dtype, device=device + ).normal_(mean=0.1, std=0.2) + + o_extend = torch.empty((extend_token_num, H_Q, D), dtype=dtype, device=device) + o_extend_mask = torch.empty( + (extend_token_num, H_Q, D), dtype=dtype, device=device + ) + o_redundant = torch.empty( + (extend_token_num, H_Q, D), dtype=dtype, device=device + ) + + b_seq_len_extend = b_seq_len - b_seq_len_prefix + max_len_extend = torch.max(b_seq_len_extend, 0)[0].item() + qo_indptr = torch.zeros((B + 1,), dtype=torch.int32, device=device) + qo_indptr[1 : B + 1] = torch.cumsum(b_seq_len_extend[:B], dim=0) + + custom_mask = None + mask_indptr = None + + extend_attention_fwd( + q_extend, + k_extend, + v_extend, + o_extend, + k_buffer, + v_buffer, + qo_indptr, + kv_indptr, + kv_indices, + custom_mask, + True, + mask_indptr, + max_len_extend, + 1.0, + 1.0, + ) + + b_seq_mask_len = b_seq_len_extend * b_seq_len + custom_mask = torch.ones( + (b_seq_mask_len.sum().item(),), dtype=torch.bool, device=device + ) + mask_indptr = torch.zeros((B + 1,), dtype=torch.int64, device=device) + mask_indptr[1 : B + 1] = torch.cumsum(b_seq_mask_len[:B], dim=0) + for i in range(B): + causal_mask = ( + torch.tril( + torch.ones(b_seq_len_extend[i], b_seq_len_extend[i]), diagonal=0 + ) + == 1 + ) + prefix_mask = torch.ones( + b_seq_len_extend[i], b_seq_len_prefix[i], dtype=torch.bool + ) + mask_flatten = torch.cat([prefix_mask, causal_mask], dim=1).flatten() + custom_mask[mask_indptr[i] : mask_indptr[i + 1]] = mask_flatten + + extend_attention_fwd( + q_extend, + k_extend, + v_extend, + o_extend_mask, + k_buffer, + v_buffer, + qo_indptr, + kv_indptr, + kv_indices, + custom_mask, + True, + mask_indptr, + max_len_extend, + 1.0, + 1.0, + ) + + redundant_attention( + q_extend, + o_redundant, + k_buffer, + v_buffer, + b_req_idx, + b_start_loc, + b_seq_len, + b_seq_len_prefix, + max_len_in_batch, + ) + + self.assertTrue(torch.allclose(o_extend, o_redundant, rtol=1e-2, atol=1e-3)) + self.assertTrue( + torch.allclose(o_extend_mask, o_redundant, rtol=1e-2, atol=1e-3) + ) + + def test_extend_attention(self): + + # Define the varying parameter values + # 256 covers the head_dim > 128 block-size branch (tuned on gfx95) + attention_values = [256, 128, 96, 80, 13] + + # Loop through the values and call the method + for value in attention_values: + self._test_extend_attention_once(19, 12331, 12, 4, value) + + def test_extend_attention_block_sizes(self): + from sglang.srt.layers.attention.triton_ops import extend_attention as ea + + if not ea._is_hip: + self.skipTest("HIP-only block-size selection") + # head_dim <= 128 keeps the default config on all HIP archs + self.assertEqual( + ea._get_block_sizes_for_extend_attention(128, 128)[3:], (64, 64, 4) + ) + # 128 < head_dim <= 256: tuned tile on gfx95, default elsewhere + expected = (128, 64, 8) if ea._is_gfx95 else (64, 64, 4) + self.assertEqual( + ea._get_block_sizes_for_extend_attention(256, 256)[3:], expected + ) + # head_dim > 256: falls back to the default on all HIP archs + self.assertEqual( + ea._get_block_sizes_for_extend_attention(576, 576)[3:], (64, 64, 4) + ) + + def _test_extend_attention_sliding_window_once( + self, B, N_CTX, H_Q, H_KV, D, WINDOW_SIZE + ): + dtype = torch.bfloat16 + device = get_device() + + b_seq_len_prefix = torch.randint( + 1, N_CTX // 2, (B,), dtype=torch.int32, device=device + ) + b_seq_len_extend = torch.randint( + 1, N_CTX // 2, (B,), dtype=torch.int32, device=device + ) + b_seq_len = b_seq_len_prefix + b_seq_len_extend + + b_start_loc = torch.zeros((B,), dtype=torch.int32, device=device) + b_start_loc[1:] = torch.cumsum(b_seq_len[:-1], 0) + b_start_loc_extend = torch.zeros((B,), dtype=torch.int32, device=device) + b_start_loc_extend[1:] = torch.cumsum(b_seq_len_extend[:-1], 0) + + kv_indptr = torch.zeros((B + 1,), dtype=torch.int32, device=device) + kv_indptr[1 : B + 1] = torch.cumsum(b_seq_len_prefix[:B], dim=0) + kv_indices = torch.zeros( + (b_seq_len_prefix.sum().item(),), dtype=torch.int32, device=device + ) + + for i in range(B): + kv_indices[kv_indptr[i] : kv_indptr[i + 1]] = torch.arange( + b_start_loc[i], b_start_loc[i] + b_seq_len_prefix[i] + ) + + total_token_num = torch.sum(b_seq_len).item() + extend_token_num = torch.sum(b_seq_len_extend).item() + k_buffer = torch.empty( + (total_token_num, H_KV, D), dtype=dtype, device=device + ).normal_(mean=0.1, std=0.2) + v_buffer = torch.empty( + (total_token_num, H_KV, D), dtype=dtype, device=device + ).normal_(mean=0.1, std=0.2) + + k_extend = torch.empty((extend_token_num, H_KV, D), dtype=dtype, device=device) + v_extend = torch.empty((extend_token_num, H_KV, D), dtype=dtype, device=device) + q_extend = torch.empty((extend_token_num, H_Q, D), dtype=dtype, device=device) + for i in range(B): + extend_start_in_buffer = b_start_loc[i] + b_seq_len_prefix[i] + extend_end_in_buffer = b_start_loc[i] + b_seq_len[i] + extend_start = b_start_loc_extend[i] + extend_end = b_start_loc_extend[i] + b_seq_len_extend[i] + k_extend[extend_start:extend_end] = k_buffer[ + extend_start_in_buffer:extend_end_in_buffer + ] + v_extend[extend_start:extend_end] = v_buffer[ + extend_start_in_buffer:extend_end_in_buffer + ] + q_extend[extend_start:extend_end] = torch.empty( + (b_seq_len_extend[i], H_Q, D), dtype=dtype, device=device + ).normal_(mean=0.1, std=0.2) + + o_extend_triton = torch.empty( + (extend_token_num, H_Q, D), dtype=dtype, device=device + ) + o_extend_torch = torch.empty( + (extend_token_num, H_Q, D), dtype=dtype, device=device + ) + + b_seq_len_extend = b_seq_len - b_seq_len_prefix + max_len_extend = torch.max(b_seq_len_extend, 0)[0].item() + qo_indptr = torch.zeros((B + 1,), dtype=torch.int32, device=device) + qo_indptr[1 : B + 1] = torch.cumsum(b_seq_len_extend[:B], dim=0) + + extend_attention_fwd( + q_extend, + k_extend, + v_extend, + o_extend_triton, + k_buffer, + v_buffer, + qo_indptr, + kv_indptr, + kv_indices, + custom_mask=None, + is_causal=True, + mask_indptr=None, + max_len_extend=max_len_extend, + k_scale=1.0, + v_scale=1.0, + sliding_window_size=WINDOW_SIZE, + ) + + extend_attention_fwd_torch( + q_extend, + k_extend, + v_extend, + o_extend_torch, + k_buffer, + v_buffer, + qo_indptr, + kv_indptr, + kv_indices, + WINDOW_SIZE, + ) + + self.assertTrue( + torch.allclose(o_extend_triton, o_extend_torch, rtol=1e-3, atol=1e-3) + ) + + def test_extend_attention_sliding_window(self): + window_sizes = [-1, 127] + for window_size in window_sizes: + self._test_extend_attention_sliding_window_once( + 19, 12331, 64, 8, 128, window_size + ) + + def _test_context_attention_once(self, head_dim, is_causal): + # Set up a simple test case + device = get_device() + num_heads = 4 + seq_lens = [8, 12] + max_seq_len = max(seq_lens) + + # Create random input tensors + q = torch.randn(sum(seq_lens), num_heads, head_dim, device=device) + k = torch.randn(sum(seq_lens), num_heads, head_dim, device=device) + v = torch.randn(sum(seq_lens), num_heads, head_dim, device=device) + o = torch.zeros(sum(seq_lens), num_heads, head_dim, device=device) + + # Create b_start_loc and b_seq_len tensors + b_start_loc = torch.tensor([0, seq_lens[0]], device=device) + b_seq_len = torch.tensor(seq_lens, device=device) + + context_attention_fwd( + q, k, v, o, b_start_loc, b_seq_len, max_seq_len, is_causal=is_causal + ) + + cu_seq_lens = [0] * (len(seq_lens) + 1) + for i, seq_len in enumerate(seq_lens): + cu_seq_lens[i + 1] = cu_seq_lens[i] + seq_len + + for i in range(len(seq_lens)): + start, end = cu_seq_lens[i], cu_seq_lens[i + 1] + o_torch = torch.nn.functional.scaled_dot_product_attention( + q[start:end].permute(1, 0, 2), + k[start:end].permute(1, 0, 2), + v[start:end].permute(1, 0, 2), + is_causal=is_causal, + ).permute(1, 0, 2) + + cos_sim = torch.nn.functional.cosine_similarity( + o[start:end].flatten(), o_torch.flatten(), dim=0 + ) + self.assertTrue(cos_sim.item() > 1 - (1e-5)) + self.assertTrue(torch.allclose(o[start:end], o_torch, atol=1e-2)) + + def test_context_attention(self): + head_dim = [128, 96, 80, 13] + + for dim in head_dim: + for is_causal in [True, False]: + self._test_context_attention_once(dim, is_causal) + + def _test_decode_attention_once(self, B, H_Q, H_KV, D): + device = get_device() + dtype = torch.bfloat16 + seq_len = 10 # This represents the number of tokens already in the sequence + total_tokens = B * seq_len + sm_scale = 1.0 / (D**0.5) + max_kv_splits = 8 + num_kv_splits = torch.full((B,), 4, dtype=torch.int32, device=device) + + # q represents the new token being generated, one per batch + q = torch.randn(B, H_Q, D, dtype=dtype, device=device) + + # k_buffer and v_buffer represent all previous tokens + k_buffer = torch.randn(total_tokens, H_KV, D, dtype=dtype, device=device) + v_buffer = torch.randn(total_tokens, H_KV, D, dtype=dtype, device=device) + + # o will have the same shape as q + o = torch.zeros(B, H_Q, D, dtype=dtype, device=device) + + b_seq_len = torch.full((B,), seq_len, device=device) + + kv_indptr = torch.zeros((B + 1,), dtype=torch.int32, device=device) + kv_indptr[1 : B + 1] = torch.cumsum(b_seq_len[:B], dim=0) + kv_indices = torch.arange(total_tokens, device=device) + + attn_logits = torch.empty( + (B, H_Q, max_kv_splits, D), + dtype=torch.float32, + device=device, + ) + attn_lse = torch.empty( + (B, H_Q, max_kv_splits), + dtype=torch.float32, + device=device, + ) + + decode_attention_fwd( + q, + k_buffer, + v_buffer, + o, + kv_indptr, + kv_indices, + attn_logits, + attn_lse, + num_kv_splits, + max_kv_splits, + sm_scale, + 1.0, + 1.0, + ) + + # Correctness reference (float32, stable softmax) + o_ref = decode_attention_fwd_torch( + q, k_buffer, v_buffer, kv_indptr, kv_indices, sm_scale + ) + + max_abs_err = (o.to(torch.float32) - o_ref).abs().max().item() + self.assertTrue( + torch.allclose(o.to(torch.float32), o_ref, atol=1e-2, rtol=1e-2), + msg=f"decode_attention mismatch, max_abs_err={max_abs_err}", + ) + + def test_decode_attention(self): + # Test configurations + configs = [ + (2, 4, 4, 64), # MHA + (2, 4, 2, 64), # GQA + (2, 4, 4, 80), # Non-standard head dim + (2, 4, 4, 13), # Prime number head dim + ] + + for B, H_Q, H_KV, D in configs: + self._test_decode_attention_once(B, H_Q, H_KV, D) + + def _test_grouped_decode_attention_once(self, B, S, H_Q, H_KV, D, D_V): + dtype = torch.bfloat16 + device = get_device() + seq_len = S # This represents the number of tokens already in the sequence + total_tokens = B * seq_len + sm_scale = 1.0 / (D**0.5) + max_kv_splits = 8 + num_kv_splits = torch.full((B,), 4, dtype=torch.int32, device=device) + + # q represents the new token being generated, one per batch + q = torch.randn(B, H_Q, D, dtype=dtype, device=device) + + # k_buffer and v_buffer represent all previous tokens + k_buffer = torch.randn(total_tokens, H_KV, D, dtype=dtype, device=device) + v_buffer = torch.randn(total_tokens, H_KV, D_V, dtype=dtype, device=device) + + # o will have the same shape as q + o = torch.zeros(B, H_Q, D_V, dtype=dtype, device=device) + o_grouped = torch.zeros(B, H_Q, D_V, dtype=dtype, device=device) + + b_seq_len = torch.full((B,), seq_len, device=device) + + kv_indptr = torch.zeros((B + 1,), dtype=torch.int32, device=device) + kv_indptr[1 : B + 1] = torch.cumsum(b_seq_len[:B], dim=0) + kv_indices = torch.arange(total_tokens, device=device) + + attn_logits = torch.empty( + (B, H_Q, max_kv_splits, D_V), + dtype=torch.float32, + device=device, + ) + attn_lse = torch.empty( + (B, H_Q, max_kv_splits), + dtype=torch.float32, + device=device, + ) + + decode_attention_fwd_normal( + q, + k_buffer, + v_buffer, + o, + kv_indptr, + kv_indices, + attn_logits, + attn_lse, + num_kv_splits, + max_kv_splits, + sm_scale, + 1.0, + ) + + attn_logits1 = torch.empty( + (B, H_Q, max_kv_splits, D_V), + dtype=torch.float32, + device=device, + ) + attn_lse1 = torch.empty( + (B, H_Q, max_kv_splits, D_V), + dtype=torch.float32, + device=device, + ) + + decode_attention_fwd_grouped( + q, + k_buffer, + v_buffer, + o_grouped, + kv_indptr, + kv_indices, + attn_logits1, + attn_lse1, + num_kv_splits, + max_kv_splits, + sm_scale, + 1.0, + ) + + cos_sim = torch.nn.functional.cosine_similarity( + o.flatten(), o_grouped.flatten(), dim=0 + ) + print(cos_sim.item()) + self.assertTrue(cos_sim.item() > 0.99) + if is_in_amd_ci(): + self.assertTrue(torch.allclose(o, o_grouped, atol=5e-2)) + else: + self.assertTrue(torch.allclose(o, o_grouped, atol=3e-2)) + + def test_grouped_decode_attention(self): + seq_lens = [5, 100, 128, 500] + configs = [ + (2, 16, 16, 64, 64), + (2, 16, 1, 64, 64), + (2, 64, 1, 13, 13), + (2, 128, 1, 80, 80), + (2, 128, 2, 512, 512), + (2, 128, 1, 576, 512), + ] + + for S in seq_lens: + for B, H_Q, H_KV, D, D_V in configs: + self._test_grouped_decode_attention_once(B, S, H_Q, H_KV, D, D_V) + + def _test_extend_attention_unified_vs_regular_once(self, B, N_CTX, H_Q, H_KV, D): + """Test that unified kernel produces same results as 2-stage kernel.""" + dtype = torch.bfloat16 + device = get_device() + + b_seq_len_prefix = torch.randint( + 1, N_CTX // 2, (B,), dtype=torch.int32, device=device + ) + b_seq_len_extend = torch.randint( + 1, N_CTX // 2, (B,), dtype=torch.int32, device=device + ) + b_seq_len = b_seq_len_prefix + b_seq_len_extend + + b_start_loc = torch.zeros((B,), dtype=torch.int32, device=device) + b_start_loc[1:] = torch.cumsum(b_seq_len[:-1], 0) + b_start_loc_extend = torch.zeros((B,), dtype=torch.int32, device=device) + b_start_loc_extend[1:] = torch.cumsum(b_seq_len_extend[:-1], 0) + + # Setup prefix KV indices + kv_indptr = torch.zeros((B + 1,), dtype=torch.int32, device=device) + kv_indptr[1 : B + 1] = torch.cumsum(b_seq_len_prefix[:B], dim=0) + kv_indices = torch.zeros( + (b_seq_len_prefix.sum().item(),), dtype=torch.int64, device=device + ) + + for i in range(B): + kv_indices[kv_indptr[i] : kv_indptr[i + 1]] = torch.arange( + b_start_loc[i], b_start_loc[i] + b_seq_len_prefix[i] + ) + + total_token_num = torch.sum(b_seq_len).item() + extend_token_num = torch.sum(b_seq_len_extend).item() + k_buffer = torch.empty( + (total_token_num, H_KV, D), dtype=dtype, device=device + ).normal_(mean=0.1, std=0.2) + v_buffer = torch.empty( + (total_token_num, H_KV, D), dtype=dtype, device=device + ).normal_(mean=0.1, std=0.2) + + k_extend = torch.empty((extend_token_num, H_KV, D), dtype=dtype, device=device) + v_extend = torch.empty((extend_token_num, H_KV, D), dtype=dtype, device=device) + q_extend = torch.empty((extend_token_num, H_Q, D), dtype=dtype, device=device) + + for i in range(B): + extend_start_in_buffer = b_start_loc[i] + b_seq_len_prefix[i] + extend_end_in_buffer = b_start_loc[i] + b_seq_len[i] + extend_start = b_start_loc_extend[i] + extend_end = b_start_loc_extend[i] + b_seq_len_extend[i] + k_extend[extend_start:extend_end] = k_buffer[ + extend_start_in_buffer:extend_end_in_buffer + ] + v_extend[extend_start:extend_end] = v_buffer[ + extend_start_in_buffer:extend_end_in_buffer + ] + q_extend[extend_start:extend_end] = torch.empty( + (b_seq_len_extend[i], H_Q, D), dtype=dtype, device=device + ).normal_(mean=0.1, std=0.2) + + # Setup for extend attention + max_len_extend = torch.max(b_seq_len_extend, 0)[0].item() + qo_indptr = torch.zeros((B + 1,), dtype=torch.int32, device=device) + qo_indptr[1 : B + 1] = torch.cumsum(b_seq_len_extend[:B], dim=0) + + # Run 2-stage kernel + o_regular = torch.empty((extend_token_num, H_Q, D), dtype=dtype, device=device) + extend_attention_fwd( + q_extend, + k_extend, + v_extend, + o_regular, + k_buffer, + v_buffer, + qo_indptr, + kv_indptr, + kv_indices, + custom_mask=None, + is_causal=True, + mask_indptr=None, + max_len_extend=max_len_extend, + k_scale=1.0, + v_scale=1.0, + ) + + # Build unified KV indices + extend_kv_indices = torch.arange( + total_token_num - extend_token_num, + total_token_num, + dtype=torch.int64, + device=device, + ) + extend_start_loc = torch.zeros((B,), dtype=torch.int32, device=device) + extend_start_loc[1:] = torch.cumsum(b_seq_len_extend[:-1], 0) + + unified_kv_indptr, unified_kv_indices, prefix_lens = build_unified_kv_indices( + kv_indptr, + kv_indices, + extend_start_loc, + b_seq_len_extend, + extend_kv_indices, + B, + ) + + # Run unified kernel + o_unified = torch.empty((extend_token_num, H_Q, D), dtype=dtype, device=device) + extend_attention_fwd_unified( + q_extend, + o_unified, + k_buffer, + v_buffer, + 1.0, + 1.0, + qo_indptr, + unified_kv_indptr, + unified_kv_indices, + prefix_lens, + max_len_extend=max_len_extend, + custom_mask=None, + mask_indptr=None, + sm_scale=None, + logit_cap=0.0, + is_causal=True, + ) + + # Compare results + if is_in_amd_ci(): + self.assertTrue( + torch.allclose(o_regular, o_unified, rtol=0.15, atol=0.17), + f"Unified kernel output differs from 2-stage kernel. " + f"Max diff: {(o_regular - o_unified).abs().max()}", + ) + else: + self.assertTrue( + torch.allclose(o_regular, o_unified, rtol=0.15, atol=0.15), + f"Unified kernel output differs from 2-stage kernel. " + f"Max diff: {(o_regular - o_unified).abs().max()}", + ) + + def test_extend_attention_unified_vs_regular(self): + """Test unified kernel matches 2-stage kernel across different configs.""" + configs = [ + (4, 512, 32, 8, 128), # Standard config + (2, 2048, 32, 8, 128), # Long sequence (test 2048 specifically) + (8, 256, 64, 8, 80), # Non-standard head dim + ] + + for B, N_CTX, H_Q, H_KV, D in configs: + with self.subTest(B=B, N_CTX=N_CTX, H_Q=H_Q, H_KV=H_KV, D=D): + self._test_extend_attention_unified_vs_regular_once( + B, N_CTX, H_Q, H_KV, D + ) + + def test_build_unified_kv_indices(self): + """Test build_unified_kv_indices correctness.""" + B = 4 + dtype = torch.int64 + device = get_device() + + # Setup test data + prefix_lens = torch.tensor([10, 20, 15, 25], dtype=torch.int32, device=device) + extend_lens = torch.tensor([5, 3, 7, 4], dtype=torch.int32, device=device) + + # Build prefix indices + prefix_kv_indptr = torch.zeros((B + 1,), dtype=torch.int32, device=device) + prefix_kv_indptr[1:] = torch.cumsum(prefix_lens, dim=0) + prefix_kv_indices = torch.arange( + prefix_lens.sum().item(), dtype=dtype, device=device + ) + + # Build extend indices + extend_start_loc = torch.zeros((B,), dtype=torch.int32, device=device) + extend_start_loc[1:] = torch.cumsum(extend_lens[:-1], dim=0) + extend_kv_indices = torch.arange( + prefix_lens.sum().item(), + prefix_lens.sum().item() + extend_lens.sum().item(), + dtype=dtype, + device=device, + ) + + # Build unified indices + unified_kv_indptr, unified_kv_indices, returned_prefix_lens = ( + build_unified_kv_indices( + prefix_kv_indptr, + prefix_kv_indices, + extend_start_loc, + extend_lens, + extend_kv_indices, + B, + ) + ) + + # Verify unified_kv_indptr + expected_lens = prefix_lens + extend_lens + expected_indptr = torch.zeros((B + 1,), dtype=torch.int32, device=device) + expected_indptr[1:] = torch.cumsum(expected_lens, dim=0) + self.assertTrue(torch.equal(unified_kv_indptr, expected_indptr)) + + # Verify prefix_lens + self.assertTrue(torch.equal(returned_prefix_lens, prefix_lens)) + + # Verify unified_kv_indices structure + for i in range(B): + start_idx = int(unified_kv_indptr[i]) + end_idx = int(unified_kv_indptr[i + 1]) + prefix_len = int(prefix_lens[i]) + extend_len = int(extend_lens[i]) + + # Check that prefix and extend are concatenated correctly + unified_seq = unified_kv_indices[start_idx:end_idx] + self.assertEqual(len(unified_seq), prefix_len + extend_len) + + +if __name__ == "__main__": + unittest.main() diff --git a/asian_ai/performance/SGLang/test/registered/attention/test_triton_sliding_window.py b/asian_ai/performance/SGLang/test/registered/attention/test_triton_sliding_window.py new file mode 100644 index 0000000000000000000000000000000000000000..db699118a8dccb7fb7388ef2e161bc32ce58ebd7 --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/attention/test_triton_sliding_window.py @@ -0,0 +1,135 @@ +import unittest +from types import SimpleNamespace + +import requests + +from sglang.srt.utils import kill_process_tree +from sglang.test.ci.ci_register import register_amd_ci, register_cuda_ci +from sglang.test.run_eval import run_eval +from sglang.test.test_utils import ( + DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH, + DEFAULT_URL_FOR_TEST, + CustomTestCase, + is_in_amd_ci, + is_in_ci, + popen_launch_server, +) + +# Sliding window attention with Triton backend (Gemma-3 model) +register_cuda_ci(est_time=93, stage="extra-a", runner_config="1-gpu-large") +register_amd_ci(est_time=200, suite="stage-b-test-1-gpu-small-amd") + + +class TestSlidingWindowAttentionTriton(CustomTestCase): + """Test sliding window attention functionality with triton backend.""" + + @classmethod + def setUpClass(cls): + """Set up the test server with Gemma3 model and triton backend.""" + # Gemma3 model supports sliding window attention + cls.model = "google/gemma-3-4b-it" + cls.base_url = DEFAULT_URL_FOR_TEST + + cls.common_args = [ + "--trust-remote-code", + "--attention-backend", + "triton", + "--context-length", + "8192", + "--random-seed", + "42", + ] + + cls.short_context_prompt = "The capital of France is" + + # Test prompt longer than window size + cls.long_context_prompt = """ + Once upon a time, there was a mountain. In the mountain, there was a temple. In the temple, there was an old monk telling a story. The story was: + """ * 100 + cls.long_context_prompt += "\nNow, summarize the story in one sentence:" + + def _test_mmlu(self): + args = SimpleNamespace( + base_url=self.base_url, + model=self.model, + eval_name="mmlu", + num_examples=200, + num_threads=32, + ) + + metrics = run_eval(args) + print(f"MMLU metrics with sliding window: {metrics}") + + if is_in_amd_ci(): + self.assertGreaterEqual(metrics["score"], 0.55) + else: + self.assertGreaterEqual(metrics["score"], 0.60) + + def _test_short_context_generation(self): + response = requests.post( + self.base_url + "/generate", + json={ + "text": self.short_context_prompt, + "sampling_params": { + "temperature": 0, + "max_new_tokens": 256, + }, + }, + ) + + self.assertEqual(response.status_code, 200) + result = response.json() + self.assertIn("paris", result["text"].lower()) + print(f"Short context generation result: {result['text']}") + + def _test_long_context_generation(self): + response = requests.post( + self.base_url + "/generate", + json={ + "text": self.long_context_prompt, + "sampling_params": { + "temperature": 0, + "max_new_tokens": 256, + }, + }, + ) + + self.assertEqual(response.status_code, 200) + result = response.json() + self.assertGreater(len(result["text"].strip()), 0) + print(f"Long context generation result: {result['text'][:100]}...") + + @unittest.skipIf(is_in_ci(), "To reduce the CI execution time.") + def test_no_cuda_graph(self): + self.no_cuda_graph_process = popen_launch_server( + self.model, + self.base_url, + timeout=DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH, + other_args=self.common_args + ["--disable-cuda-graph"], + ) + + try: + self._test_short_context_generation() + self._test_long_context_generation() + self._test_mmlu() + finally: + kill_process_tree(self.no_cuda_graph_process.pid) + + def test_cuda_graph(self): + self.cuda_graph_process = popen_launch_server( + self.model, + self.base_url, + timeout=DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH, + other_args=self.common_args, + ) + + try: + self._test_short_context_generation() + self._test_long_context_generation() + self._test_mmlu() + finally: + kill_process_tree(self.cuda_graph_process.pid) + + +if __name__ == "__main__": + unittest.main() diff --git a/asian_ai/performance/SGLang/test/registered/attention/test_trtllm_mha_page_table.py b/asian_ai/performance/SGLang/test/registered/attention/test_trtllm_mha_page_table.py new file mode 100644 index 0000000000000000000000000000000000000000..ec9ddb84e319db25c2feb3085a889f5456104015 --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/attention/test_trtllm_mha_page_table.py @@ -0,0 +1,229 @@ +"""Unit test for the device-side page-table build used by trtllm_mha. + +trtllm_mha builds its CUDA-graph block table on-device from ``seq_lens`` (via +``create_trtllm_mha_kv_indices_triton``) instead of a host-max PyTorch gather, so +it never reads a runtime max (no D2H sync). This test checks the device build is +bit-identical to the legacy gather for the columns each request uses, for both +the full page table and the SWA-translated page table, across context lengths, +page sizes, and batch sizes. + +It also pins the invariant that lets the no-host-max (GPU-only) path hand the +kernel a static ``max_num_pages``-wide buffer: every column past a request's +page count must be left untouched, i.e. the kernel bounds its writes by the +device-side ``cache_seqlens`` alone. +""" + +import unittest +from typing import Optional + +import torch + +from sglang.srt.layers.attention.triton_ops.trtllm_mha_page_table import ( + build_trtllm_mha_page_table, +) +from sglang.test.ci.ci_register import register_cuda_ci +from sglang.test.test_utils import CustomTestCase + +# Triton kernel unit test for the trtllm_mha device-side page-table build. +register_cuda_ci(est_time=14, stage="base-b", runner_config="1-gpu-small") + + +def _build_page_table_reference( + req_to_token: torch.Tensor, + req_pool_indices: torch.Tensor, + cache_seqlens: torch.Tensor, + page_size: int, + full_to_swa: Optional[torch.Tensor] = None, +) -> tuple[torch.Tensor, Optional[torch.Tensor]]: + """Reference impl: host-side strided gather, then // page_size. + + Sized to the batch max (uses a host-side ``.max()``, which the kernel path + avoids). Returns the same (page_table, swa_page_table) block-id tables as + ``_build_page_table_kernel`` for the columns each request uses. + """ + max_len = int(cache_seqlens.max().item()) + max_seq_pages = (max_len + page_size - 1) // page_size + strided = torch.arange( + 0, req_to_token.shape[1], page_size, device=req_to_token.device + )[:max_seq_pages] + slots = req_to_token[req_pool_indices[:, None], strided[None, :]] # token slots + page_table = slots // page_size + swa_page_table = ( + full_to_swa[slots] // page_size if full_to_swa is not None else None + ) + return page_table, swa_page_table + + +def _build_page_table_kernel( + req_to_token: torch.Tensor, + req_pool_indices: torch.Tensor, + cache_seqlens: torch.Tensor, + page_size: int, + max_num_pages: int, + full_to_swa: Optional[torch.Tensor] = None, +) -> tuple[torch.Tensor, Optional[torch.Tensor]]: + """Device-side impl.""" + dev = req_to_token.device + bs = req_pool_indices.shape[0] + page_table = torch.zeros((bs, max_num_pages), dtype=torch.int32, device=dev) + swa_page_table = ( + torch.zeros((bs, max_num_pages), dtype=torch.int32, device=dev) + if full_to_swa is not None + else None + ) + build_trtllm_mha_page_table( + req_to_token=req_to_token, + req_pool_indices=req_pool_indices, + cache_seqlens=cache_seqlens, + page_table=page_table, + page_size=page_size, + swa_page_table=swa_page_table, + full_to_swa=full_to_swa, + ) + return page_table, swa_page_table + + +@unittest.skipUnless(torch.cuda.is_available(), "needs CUDA") +class TestTrtllmMhaPageTable(CustomTestCase): + def _run_case(self, max_context_len, page_size, num_reqs, bs, swa=False): + torch.manual_seed(0) + dev = "cuda" + max_num_pages = (max_context_len + page_size - 1) // page_size + n_slots = num_reqs * max_context_len + req_to_token = torch.randint( + 0, n_slots, (num_reqs, max_context_len), dtype=torch.int32, device=dev + ) + req_pool_indices = torch.randperm(num_reqs, device=dev)[:bs].to(torch.int32) + cache_seqlens = torch.randint( + 1, max_context_len + 1, (bs,), dtype=torch.int32, device=dev + ) + full_to_swa = None + if swa: + # Arbitrary full-slot -> SWA-slot lookup table. + full_to_swa = torch.randint( + 0, n_slots, (n_slots,), dtype=torch.int32, device=dev + ) + + pt_kernel, swa_kernel = _build_page_table_kernel( + req_to_token, + req_pool_indices, + cache_seqlens, + page_size, + max_num_pages, + full_to_swa=full_to_swa, + ) + pt_ref, swa_ref = _build_page_table_reference( + req_to_token, + req_pool_indices, + cache_seqlens, + page_size, + full_to_swa=full_to_swa, + ) + + for i in range(bs): + npages = (int(cache_seqlens[i].item()) + page_size - 1) // page_size + self.assertTrue( + torch.equal(pt_kernel[i, :npages], pt_ref[i, :npages]), + f"page_table mismatch req={i} max_ctx={max_context_len} " + f"page_size={page_size} bs={bs} swa={swa}", + ) + if swa: + self.assertTrue( + torch.equal(swa_kernel[i, :npages], swa_ref[i, :npages]), + f"swa_page_table mismatch req={i} max_ctx={max_context_len} " + f"page_size={page_size} bs={bs}", + ) + + def test_matches_reference_gather(self): + for max_ctx in (2048, 4096, 131072): + for page_size in (1, 32, 64, 128, 256): + for bs in (1, 7, 32): + self._run_case(max_ctx, page_size, num_reqs=max(64, bs), bs=bs) + + def test_swa_matches_reference(self): + for max_ctx in (2048, 4096): + for page_size in (1, 64, 128): + for bs in (1, 7, 32): + self._run_case( + max_ctx, page_size, num_reqs=max(64, bs), bs=bs, swa=True + ) + + def _run_self_guard_case(self, max_context_len, page_size, bs, swa=False): + """Short sequences against a full static buffer -- the GPU-only shape. + + Pre-fill the page table with a sentinel and run the kernel with the + static ``max_num_pages`` width (no host max to tighten it). Used columns + must hold the right block ids; every tail column must keep the sentinel, + proving the kernel never writes past the device-side ``cache_seqlens``. + """ + torch.manual_seed(0) + dev = "cuda" + num_reqs = max(64, bs) + max_num_pages = (max_context_len + page_size - 1) // page_size + n_slots = num_reqs * max_context_len + req_to_token = torch.randint( + 0, n_slots, (num_reqs, max_context_len), dtype=torch.int32, device=dev + ) + req_pool_indices = torch.randperm(num_reqs, device=dev)[:bs].to(torch.int32) + # Cap lengths well below max_context_len so most tail columns stay unused. + hi = max(2, max_context_len // 8) + cache_seqlens = torch.randint(1, hi + 1, (bs,), dtype=torch.int32, device=dev) + full_to_swa = ( + torch.randint(0, n_slots, (n_slots,), dtype=torch.int32, device=dev) + if swa + else None + ) + + SENTINEL = -1 + page_table = torch.full( + (bs, max_num_pages), SENTINEL, dtype=torch.int32, device=dev + ) + swa_page_table = ( + torch.full((bs, max_num_pages), SENTINEL, dtype=torch.int32, device=dev) + if swa + else None + ) + build_trtllm_mha_page_table( + req_to_token=req_to_token, + req_pool_indices=req_pool_indices, + cache_seqlens=cache_seqlens, + page_table=page_table, + page_size=page_size, + swa_page_table=swa_page_table, + full_to_swa=full_to_swa, + ) + pt_ref, swa_ref = _build_page_table_reference( + req_to_token, req_pool_indices, cache_seqlens, page_size, full_to_swa + ) + + tag = f"max_ctx={max_context_len} page_size={page_size} bs={bs} swa={swa}" + for i in range(bs): + npages = (int(cache_seqlens[i].item()) + page_size - 1) // page_size + self.assertTrue( + torch.equal(page_table[i, :npages], pt_ref[i, :npages]), + f"used-column mismatch req={i} {tag}", + ) + self.assertTrue( + torch.all(page_table[i, npages:] == SENTINEL), + f"kernel wrote past cache_seqlens req={i} npages={npages} {tag}", + ) + if swa: + self.assertTrue( + torch.equal(swa_page_table[i, :npages], swa_ref[i, :npages]), + f"swa used-column mismatch req={i} {tag}", + ) + self.assertTrue( + torch.all(swa_page_table[i, npages:] == SENTINEL), + f"swa wrote past cache_seqlens req={i} npages={npages} {tag}", + ) + + def test_writes_bounded_by_cache_seqlens(self): + for max_ctx in (4096, 131072): + for page_size in (1, 64, 256): + for bs in (1, 8): + self._run_self_guard_case(max_ctx, page_size, bs=bs) + self._run_self_guard_case(max_ctx, page_size, bs=bs, swa=True) + + +if __name__ == "__main__": + unittest.main() diff --git a/asian_ai/performance/SGLang/test/registered/attention/test_verify_splitkv.py b/asian_ai/performance/SGLang/test/registered/attention/test_verify_splitkv.py new file mode 100644 index 0000000000000000000000000000000000000000..50ec082e9aee8d18efe821eb03484f836cc3eadb --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/attention/test_verify_splitkv.py @@ -0,0 +1,239 @@ +"""Correctness tests for the split-KV EAGLE-verify attention kernel. + +``verify_splitkv_fwd`` is a drop-in for ``extend_attention_fwd`` on the topk=1 +causal (target-verify) path. These tests check: + (a) numerical parity with ``extend_attention_fwd`` on the pure-causal path + (the operative case at topk=1), across head dims / GQA ratios / prefix + lengths / extend lengths / KV scales; + (b) ``can_handle()`` rejects cases the kernel cannot serve bit-equivalently + (non-causal, sinks, sliding-window, logit-cap, ragged extend), so the + backend falls back to ``extend_attention_fwd``. + +The topk>1 case is gated off in the backend (TritonAttnBackend enables this path +only when ``self.topk == 1``), since the kernel ignores the tree custom_mask; +that gate is exercised end-to-end by the nightly ROCm spec accuracy test. + +GPU + Triton required. Runs on the CUDA PR lane and the AMD MI35x lane. +""" + +import unittest + +import torch + +from sglang.srt.layers.attention.triton_ops.extend_attention import ( + extend_attention_fwd, +) +from sglang.srt.layers.attention.triton_ops.verify_splitkv import ( + can_handle, + verify_splitkv_fwd, +) +from sglang.test.ci.ci_register import register_amd_ci, register_cuda_ci +from sglang.test.test_utils import CustomTestCase + +register_cuda_ci(est_time=30, stage="base-b", runner_config="1-gpu-small") +register_amd_ci(est_time=30, suite="stage-b-test-1-gpu-small-amd-mi35x") + +# Split-KV accumulates the prefix in parallel splits and merges via log-sum-exp; +# it differs from the single-pass extend kernel only by reduction order. On-GPU +# (gfx950) the max abs diff across these shapes was ~2e-3 (rising to ~6e-2 only +# at much longer ctx); 2e-2 keeps a ~10x margin over the observed noise. +ATOL = 2e-2 +RTOL = 1e-2 + + +def _build_verify_inputs( + prefix_lens, l_ext, h_q, h_kv, head_dim, v_head_dim, dtype, device +): + """Build a verify-shaped problem: a constant extend length ``l_ext`` per + sequence, with the prefix cache addressed contiguously by ``kv_indices``. + Returns the positional args shared by extend_attention_fwd / verify_splitkv_fwd. + """ + B = len(prefix_lens) + prefix_lens_t = torch.tensor(prefix_lens, dtype=torch.int32, device=device) + total_prefix = int(prefix_lens_t.sum()) + + # Prefix KV cache laid out contiguously; kv_indices is just arange over it. + # kv_indices is int64 in production (TritonAttnBackend allocates int64) -- match it. + k_buffer = torch.randn(total_prefix, h_kv, head_dim, dtype=dtype, device=device) + v_buffer = torch.randn(total_prefix, h_kv, v_head_dim, dtype=dtype, device=device) + kv_indptr = torch.zeros(B + 1, dtype=torch.int32, device=device) + kv_indptr[1:] = torch.cumsum(prefix_lens_t, 0) + kv_indices = torch.arange(total_prefix, dtype=torch.int64, device=device) + + # Draft (extend) tensors: constant l_ext rows per sequence. + n_ext = B * l_ext + q_extend = torch.randn(n_ext, h_q, head_dim, dtype=dtype, device=device) + k_extend = torch.randn(n_ext, h_kv, head_dim, dtype=dtype, device=device) + v_extend = torch.randn(n_ext, h_kv, v_head_dim, dtype=dtype, device=device) + qo_indptr = torch.arange(0, n_ext + 1, l_ext, dtype=torch.int32, device=device) + + return ( + q_extend, + k_extend, + v_extend, + k_buffer, + v_buffer, + qo_indptr, + kv_indptr, + kv_indices, + l_ext, + ) + + +@unittest.skipIf(not torch.cuda.is_available(), "GPU required") +class TestVerifySplitKV(CustomTestCase): + def _run_parity( + self, + prefix_lens, + l_ext=4, + h_q=16, + h_kv=2, + head_dim=256, + v_head_dim=256, + k_scale=1.0, + v_scale=1.0, + dtype=torch.bfloat16, + ): + device = "cuda" + q, k, v, kb, vb, qo, kvp, kvi, mle = _build_verify_inputs( + prefix_lens, l_ext, h_q, h_kv, head_dim, v_head_dim, dtype, device + ) + sm_scale = 1.0 / (head_dim**0.5) + + # Reference: extend_attention_fwd, pure causal (custom_mask=None) -- the + # topk=1 operative case, with the same KV scales. + o_ref = torch.empty(q.shape[0], h_q, v_head_dim, dtype=dtype, device=device) + extend_attention_fwd( + q, + k, + v, + o_ref, + kb, + vb, + qo, + kvp, + kvi, + None, + True, + None, + mle, + k_scale, + v_scale, + sm_scale=sm_scale, + ) + + o_split = torch.empty_like(o_ref) + ran = verify_splitkv_fwd( + q, + k, + v, + o_split, + kb, + vb, + qo, + kvp, + kvi, + None, + True, + None, + mle, + k_scale, + v_scale, + sm_scale=sm_scale, + ) + self.assertTrue(ran, "verify_splitkv_fwd must handle the topk=1 causal case") + torch.testing.assert_close(o_split, o_ref, atol=ATOL, rtol=RTOL) + + def test_numerics_head_dim_256(self): + # head_dim=256 is the validated Qwen3 value (the tuned block config). + for prefix_lens in ([512, 512, 512], [768, 1536, 3072], [4096, 8192]): + with self.subTest(prefix_lens=prefix_lens): + self._run_parity(prefix_lens) + + def test_numerics_head_dim_128(self): + # A head_dim without a tuned block entry must still be correct (default). + self._run_parity([1024, 2048], head_dim=128, v_head_dim=128) + + def test_numerics_gqa_ratios(self): + # Sweep GQA group sizes incl. MQA (h_kv=1); the kv_group_num arithmetic + # in the kernel must be correct across ratios. + for h_q, h_kv in ((16, 1), (8, 1), (8, 2), (8, 4), (8, 8)): + with self.subTest(h_q=h_q, h_kv=h_kv): + self._run_parity([1024, 2048], h_q=h_q, h_kv=h_kv) + + def test_numerics_extend_len_variants(self): + for l_ext in (1, 2, 4, 8): + with self.subTest(l_ext=l_ext): + self._run_parity([1024, 1024], l_ext=l_ext) + + def test_numerics_with_kv_scales(self): + # Exercise the k_scale/v_scale dequant-multiplier path (same multipliers + # the fp8 KV-cache path applies); both kernels must apply them identically. + self._run_parity([1024, 2048], k_scale=0.5, v_scale=0.25) + + # --- fallback: can_handle() must reject what the kernel can't serve -------- + # (topk>1 is gated off in the backend, not here -- can_handle never inspects + # the tree custom_mask; see verify_splitkv.can_handle docstring.) + def _inputs(self): + return _build_verify_inputs( + [512, 512], 4, 16, 2, 256, 256, torch.bfloat16, "cuda" + ) + + def test_fallback_non_causal(self): + q, k, v, kb, vb, qo, kvp, kvi, mle = self._inputs() + self.assertFalse( + can_handle(q, k, v, kb, vb, qo, kvp, kvi, None, False, None, mle) + ) + + def test_fallback_exotic_features(self): + q, k, v, kb, vb, qo, kvp, kvi, mle = self._inputs() + self.assertFalse( + can_handle( + q, + k, + v, + kb, + vb, + qo, + kvp, + kvi, + None, + True, + None, + mle, + sinks=torch.zeros(16, device="cuda"), + ) + ) + self.assertFalse( + can_handle( + q, + k, + v, + kb, + vb, + qo, + kvp, + kvi, + None, + True, + None, + mle, + sliding_window_size=128, + ) + ) + self.assertFalse( + can_handle( + q, k, v, kb, vb, qo, kvp, kvi, None, True, None, mle, logit_cap=30.0 + ) + ) + + def test_fallback_ragged_extend(self): + # q rows (bs*l_ext) inconsistent with the claimed max_len_extend -> reject. + q, k, v, kb, vb, qo, kvp, kvi, mle = self._inputs() + self.assertFalse( + can_handle(q, k, v, kb, vb, qo, kvp, kvi, None, True, None, mle + 1) + ) + + +if __name__ == "__main__": + unittest.main() diff --git a/asian_ai/performance/SGLang/test/registered/attention/test_wave_attention_kernels.py b/asian_ai/performance/SGLang/test/registered/attention/test_wave_attention_kernels.py new file mode 100644 index 0000000000000000000000000000000000000000..f819fe3d89986448d44245a341860bd24cc38acc --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/attention/test_wave_attention_kernels.py @@ -0,0 +1,354 @@ +import random +import unittest + +import torch + +from sglang.srt.layers.attention.triton_ops.decode_attention import ( + decode_attention_fwd_grouped as triton_decode_attention_fwd_grouped, +) +from sglang.srt.layers.attention.triton_ops.extend_attention import ( + extend_attention_fwd, + redundant_attention, +) +from sglang.srt.layers.attention.triton_ops.prefill_attention import ( + context_attention_fwd, +) +from sglang.srt.layers.attention.wave_ops.decode_attention import ( + decode_attention_intermediate_arrays_shapes, + decode_attention_wave, +) +from sglang.srt.layers.attention.wave_ops.extend_attention import extend_attention_wave +from sglang.srt.layers.attention.wave_ops.prefill_attention import ( + prefill_attention_wave, +) +from sglang.srt.utils import get_device +from sglang.test.ci.ci_register import register_amd_ci + +# Wave attention kernel unit tests (AMD only - requires wave_lang) +register_amd_ci(est_time=60, suite="stage-a-test-1-gpu-small-amd") + + +class TestWaveAttention(unittest.TestCase): + + def _set_all_seeds(self, seed): + """Set all random seeds for reproducibility.""" + random.seed(seed) + torch.manual_seed(seed) + torch.cuda.manual_seed(seed) + torch.cuda.manual_seed_all(seed) + torch.backends.cudnn.deterministic = True + torch.backends.cudnn.benchmark = False + + def setUp(self): + # Set seeds before each test method + self._set_all_seeds(42) + + def _test_extend_attention_once(self, B, N_CTX, H_Q, H_KV, D): + dtype = torch.float16 + extend_seq_len = 1024 + + b_seq_len_prefix = torch.full( + (B,), N_CTX // B, dtype=torch.int32, device=get_device() + ) + b_seq_len_extend = torch.full( + (B,), extend_seq_len, dtype=torch.int32, device=get_device() + ) + b_seq_len = b_seq_len_prefix + b_seq_len_extend + max_len_in_batch = torch.max(b_seq_len, 0)[0].item() + + b_req_idx = torch.arange(B, dtype=torch.int32, device=get_device()) + b_start_loc = torch.zeros((B,), dtype=torch.int32, device=get_device()) + b_start_loc[1:] = torch.cumsum(b_seq_len[:-1], 0) + b_start_loc_extend = torch.zeros((B,), dtype=torch.int32, device=get_device()) + b_start_loc_extend[1:] = torch.cumsum(b_seq_len_extend[:-1], 0) + + kv_indptr = torch.zeros((B + 1,), dtype=torch.int32, device=get_device()) + kv_indptr[1 : B + 1] = torch.cumsum(b_seq_len_prefix[:B], dim=0) + kv_indices = torch.zeros( + (b_seq_len_prefix.sum().item(),), dtype=torch.int32, device=get_device() + ) + + for i in range(B): + kv_indices[kv_indptr[i] : kv_indptr[i + 1]] = torch.arange( + b_start_loc[i], b_start_loc[i] + b_seq_len_prefix[i] + ) + + total_token_num = torch.sum(b_seq_len).item() + extend_token_num = torch.sum(b_seq_len_extend).item() + k_buffer = torch.empty( + (total_token_num, H_KV, D), dtype=dtype, device=get_device() + ).normal_(mean=0.1, std=0.2) + v_buffer = torch.empty( + (total_token_num, H_KV, D), dtype=dtype, device=get_device() + ).normal_(mean=0.1, std=0.2) + + k_extend = torch.empty( + (extend_token_num, H_KV, D), dtype=dtype, device=get_device() + ) + v_extend = torch.empty( + (extend_token_num, H_KV, D), dtype=dtype, device=get_device() + ) + q_extend = torch.empty( + (extend_token_num, H_Q, D), dtype=dtype, device=get_device() + ) + for i in range(B): + extend_start_in_buffer = b_start_loc[i] + b_seq_len_prefix[i] + extend_end_in_buffer = b_start_loc[i] + b_seq_len[i] + extend_start = b_start_loc_extend[i] + extend_end = b_start_loc_extend[i] + b_seq_len_extend[i] + k_extend[extend_start:extend_end] = k_buffer[ + extend_start_in_buffer:extend_end_in_buffer + ] + v_extend[extend_start:extend_end] = v_buffer[ + extend_start_in_buffer:extend_end_in_buffer + ] + q_extend[extend_start:extend_end] = torch.empty( + (b_seq_len_extend[i], H_Q, D), dtype=dtype, device=get_device() + ).normal_(mean=0.1, std=0.2) + + o_extend = torch.empty( + (extend_token_num, H_Q, D), dtype=dtype, device=get_device() + ) + o_extend_mask = torch.empty( + (extend_token_num, H_Q, D), dtype=dtype, device=get_device() + ) + o_redundant = torch.empty( + (extend_token_num, H_Q, D), dtype=dtype, device=get_device() + ) + + b_seq_len_extend = b_seq_len - b_seq_len_prefix + max_len_extend = torch.max(b_seq_len_extend, 0)[0].item() + qo_indptr = torch.zeros((B + 1,), dtype=torch.int32, device=get_device()) + qo_indptr[1 : B + 1] = torch.cumsum(b_seq_len_extend[:B], dim=0) + + custom_mask = None + mask_indptr = None + + redundant_attention( + q_extend, + o_redundant, + k_buffer, + v_buffer, + b_req_idx, + b_start_loc, + b_seq_len, + b_seq_len_prefix, + max_len_in_batch, + ) + + is_causal = True + + o_extend = torch.empty( + (extend_token_num, H_Q, D), dtype=dtype, device=get_device() + ) + extend_attention_fwd( + q_extend, + k_extend, + v_extend, + o_extend, + k_buffer, + v_buffer, + qo_indptr, + kv_indptr, + kv_indices, + custom_mask, + is_causal, + mask_indptr, + max_len_extend, + 1.0, + 1.0, + ) + + o_wave = torch.empty( + (extend_token_num, H_Q, D), dtype=dtype, device=get_device() + ) + extend_attention_wave( + q_extend, + k_extend, + v_extend, + k_buffer, + v_buffer, + qo_indptr, + kv_indptr, + kv_indices, + custom_mask, + mask_indptr, + max_len_extend, + o_wave, + is_causal=is_causal, + ) + + self.assertTrue(torch.allclose(o_extend, o_redundant, rtol=1e-2)) + self.assertTrue(torch.allclose(o_wave, o_redundant, rtol=1e-2)) + + def test_extend_attention(self): + + # Define the varying parameter values + attention_values = [128] + + # Loop through the values and call the method + for value in attention_values: + self._test_extend_attention_once(32, 16384, 6, 1, value) + + def _test_grouped_decode_attention_once(self, B, S, H_Q, H_KV, D, D_V): + dtype = torch.float16 + seq_len = S # This represents the number of tokens already in the sequence + total_tokens = B * seq_len + sm_scale = 1.0 / (D**0.5) + max_kv_splits = 8 + num_kv_splits = torch.full((B,), 4, dtype=torch.int32, device=get_device()) + + # q represents the new token being generated, one per batch + q = torch.randn(B, H_Q, D, dtype=dtype, device=get_device()) + + # k_buffer and v_buffer represent all previous tokens + k_buffer = torch.randn(total_tokens, H_KV, D, dtype=dtype, device=get_device()) + v_buffer = torch.randn( + total_tokens, H_KV, D_V, dtype=dtype, device=get_device() + ) + + # o will have the same shape as q + o_triton = torch.zeros(B, H_Q, D_V, dtype=dtype, device=get_device()) + o = torch.zeros(B, H_Q, D_V, dtype=dtype, device=get_device()) + + req_to_token = torch.arange( + total_tokens, device=get_device(), dtype=torch.int32 + ) + b_req_idx = torch.zeros(B + 1, device=get_device(), dtype=torch.int32) + b_seq_len = torch.full((B,), seq_len, device=get_device(), dtype=torch.int32) + b_req_idx[1 : B + 1] = torch.cumsum(b_seq_len, dim=0) + + attn_logits = torch.empty( + (B, H_Q, max_kv_splits, D_V + 1), + dtype=torch.float32, + device=get_device(), + ) + attn_lse = torch.empty( + (B, H_Q, max_kv_splits), + dtype=torch.float32, + device=get_device(), + ) + + logit_cap = 0.0 + triton_decode_attention_fwd_grouped( + q, + k_buffer, + v_buffer, + o_triton, + b_req_idx, + req_to_token, + attn_logits, + attn_lse, + num_kv_splits, + max_kv_splits, + sm_scale, + 1.0, + logit_cap, + ) + + attn_logits_shape, attn_logits_max_shape = ( + decode_attention_intermediate_arrays_shapes(B, D_V, H_Q, max_kv_splits) + ) + + attn_logits = torch.empty( + attn_logits_shape, + dtype=torch.float32, + device=get_device(), + ) + + attn_logits_max = torch.empty( + attn_logits_max_shape, + dtype=torch.float32, + device=get_device(), + ) + + decode_attention_wave( + q, + k_buffer, + v_buffer, + o, + b_req_idx, + req_to_token, + attn_logits, + attn_logits_max, + num_kv_splits, + max_kv_splits, + sm_scale, + logit_cap, + ) + + cos_sim = torch.nn.functional.cosine_similarity( + o.flatten(), o_triton.flatten(), dim=0 + ) + print(cos_sim.item()) + self.assertTrue(cos_sim.item() > 0.99) + self.assertTrue(torch.allclose(o, o_triton, atol=3e-2)) + + def test_grouped_decode_attention(self): + seq_lens = [5, 100, 128, 500] + configs = [ + (2, 16, 16, 64, 64), + (2, 16, 1, 64, 64), + (2, 128, 1, 80, 80), + (32, 128, 2, 512, 512), + (2, 128, 2, 512, 512), + (2, 128, 1, 576, 512), + ] + + for S in seq_lens: + for B, H_Q, H_KV, D, D_V in configs: + self._test_grouped_decode_attention_once(B, S, H_Q, H_KV, D, D_V) + + def _test_context_attention_once(self, head_dim, is_causal): + # Set up a simple test case + dtype = torch.float16 + num_heads = 4 + kv_heads = 1 + seq_lens = [128, 256] + max_seq_len = max(seq_lens) + + # Create random input tensors + q = torch.randn( + sum(seq_lens), num_heads, head_dim, dtype=dtype, device=get_device() + ) + k = torch.randn( + sum(seq_lens), kv_heads, head_dim, dtype=dtype, device=get_device() + ) + v = torch.randn( + sum(seq_lens), kv_heads, head_dim, dtype=dtype, device=get_device() + ) + o_triton = torch.zeros( + sum(seq_lens), num_heads, head_dim, dtype=dtype, device=get_device() + ) + o = torch.zeros( + sum(seq_lens), num_heads, head_dim, dtype=dtype, device=get_device() + ) + + # Create b_start_loc and b_seq_len tensors + b_start_loc = torch.tensor([0, seq_lens[0]], device=get_device()) + b_seq_len = torch.tensor(seq_lens, device=get_device()) + + context_attention_fwd( + q, k, v, o_triton, b_start_loc, b_seq_len, max_seq_len, is_causal=is_causal + ) + prefill_attention_wave( + q, k, v, o, b_start_loc, b_seq_len, max_seq_len, is_causal=is_causal + ) + cos_sim = torch.nn.functional.cosine_similarity( + o.flatten(), o_triton.flatten(), dim=0 + ) + + print(cos_sim.item()) + self.assertTrue(torch.allclose(o, o_triton, atol=3e-2)) + self.assertTrue(cos_sim.item() > 1 - (1e-5)) + + def test_context_attention(self): + head_dim = [128, 96] + + for dim in head_dim: + for is_causal in [False]: + self._test_context_attention_once(dim, is_causal) + + +if __name__ == "__main__": + unittest.main() diff --git a/asian_ai/performance/SGLang/test/registered/attention/unittests/KNOWN_FAILURES.md b/asian_ai/performance/SGLang/test/registered/attention/unittests/KNOWN_FAILURES.md new file mode 100644 index 0000000000000000000000000000000000000000..9e28bfc34f32d458ffa62270b173c2b598da085c --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/attention/unittests/KNOWN_FAILURES.md @@ -0,0 +1,256 @@ +# Known Failures — Attention Backend Unit Tests + +This file catalogs every backend issue (production-side bug, structural +reject, container gap, or hardware-architecture gate) that affects the +unit-test suite, **organized by the action needed to address it**. + +Anything failing that is not listed here should be treated as a regression. + +Last updated: 2026-06-05 + +## Reference runs + +| Host | Hardware | Result | +|---|---|---| +| H200 | SM 9.0 (Hopper) | **172 passed, 23 skipped, 0 failures, 536 subtests passed** in ~51 s | +| GB300 | SM 10.3 (Grace-Blackwell) | After `cf482d662`: all §A/§B/§C.3-Blackwell failures now skip cleanly with documented reasons. Previously: 21 failed, 160 passed, 87 skipped, 436 subtests passed in ~215 s. | + +## Top-level structure + +| § | Category | Action needed | +|---|---|---| +| **A** | Container dependency missing | **Re-image** with SM10.x-compatible wheels | +| **B** | Hardware-architecture gate | None — tests skip cleanly when SM doesn't match; correctly designed | +| **C** | Backend production-side bug or structural reject | **Production code change** in `python/sglang/srt/layers/attention/` | +| **D** | Production-design constraint | None — these are intentional rejects (page-size pins, topk limits) | + +Within **C**, sub-sections by bug category (layout / speculative / graph-runner / +split-op / sparse-kernel / DSA-specific). Each entry tags its current test +status: `[gated]` (skipTest gate fires today), `[no test]` (no test attempts +it; documented in per-method README), or `[gated on X]` (gate fires only on +hardware/version X). + +--- + +# A. Container re-image required + +## A.1. `flash_attn` SM10.x wheel missing + +**Affected**: `dual_chunk/test_dual_chunk_flash_attn.py` (entire class — 5 +test methods, ~18 subtests) + +**Symptom on GB300**: +``` +ImportError: cannot import name 'flash_attn_varlen_func' from 'flash_attn' +``` + +**Root cause**: `DualChunkFlashAttentionBackend` calls `flash_attn_varlen_func` +via `sglang.jit_kernel.flash_attention`. On SM 8.x / 9.x that resolves to +sgl-kernel's FA3 build (works on H200). On other SMs, the JIT kernel falls +back to the upstream `flash_attn` (FA2) wheel — but the +`lmsysorg/sglang:nightly-dev-cu13` container's `flash_attn` package on +SM10.x is missing `flash_attn_varlen_func`. + +**Gate**: `_dual_chunk_fa_supported()` in +`dual_chunk/test_dual_chunk_flash_attn.py` skips the whole class on the +fallback-broken path. Hopper passes through unchanged. + +**Fix**: Re-image with an SM10.x-compiled `flash_attn` wheel. + +## A.2. tilelang `wait_wgmma` template missing on SM10.x + +**Affected**: +- `dsa/test_dsa.py::test_sparse_tilelang_prefill_case` (1 test) +- `dsa/test_dsa.py::test_sparse_tilelang_decode_case` (1 test) +- `tilelang` rows in `test_sparse_{prefill,decode,cuda_graph_decode}_impl_variants` + +**Symptom on GB300**: +``` +RuntimeError: namespace "tl" has no member "wait_wgmma" +``` + +**Root cause**: tilelang JIT generates `wait_wgmma` (a Blackwell WGMMA-sync +intrinsic) on SM10.x, but the container's MMA template library is missing +it. PTX compilation fails. + +**Gate**: `dsa_impl_capability("tilelang")` in +`common/attention_methods/dsa_attention.py` skips on `major >= 10`. Override +with `SGLANG_TEST_DSA_TILELANG_FORCE=1` after re-imaging. + +**Fix**: Re-image with an SM10.x-compatible tilelang version. + +--- + +# B. Hardware-architecture gates (no action needed) + +These tests skip cleanly when the running SM doesn't match the backend's +required architecture. The gates are correct as designed; the table is here +so that "skipped: ..." results have a quick lookup. + +| Backend | Required SM | Gate location | Error if unguarded | +|---|---|---|---| +| `cutlass_mla` | exactly SM 10.0 (B200) | `mla/test_cutlass_mla.py::_supported` | `cutlass_mla_decode is only supported on compute capability 10.0, but found sm version 103` | +| `flashmla` decode/verify | SM 9.0 (Hopper) only | `mla/test_flashmla.py:_DECODE_REQUIRES_SM90A` | `Dense decode MLA is only supported on SM90a architecture` | +| `trtllm_mla` | SM 12.0a / 12.1a | `mla/test_trtllm_mla.py::_supported` | FlashInfer XQA MLA dispatch reject | +| `tokenspeed_mla` | SM ≥ 10.0 + FP8 KV + pkg | `mla/test_tokenspeed_mla.py::_supported` | `tokenspeed_mla` import or kernel dispatch | +| `trtllm_mha` prefill | SM ≥ 10.0 | `dense/test_trtllm_mha.py` decode-only matrix | FlashInfer TRT-LLM Gen FMHA reject (`Unsupported architecture`) | +| `dsa` `fa3` impl | SM 9.x only | `dsa_impl_capability("fa3")` | `flash_attn at sgl-kernel is only supported on sm90 and above` | +| `dsa` `trtllm` impl | exactly SM 10.0 | `dsa_impl_capability("trtllm")` | `Missing TRTLLM-GEN kernel` (compiled for SM10.0) | +| `fa3` (non-MLA) | SM 80 or SM 90 | `_is_fa3_supported` in `flash_attention_v3.py` | `attention_registry.py:177-180` reject | + +**SM10.3 vs SM10.0**: GB300 is SM10.3. Gates that require exactly SM10.0 +(cutlass_mla, dsa trtllm) intentionally skip on GB300 because the kernel +binaries in the container aren't compiled for sm_103. Flip the gates to +`major == 10` (drop the `minor == 0`) once GB300-compiled binaries land. + +--- + +# C. Backend bugs needing production code fixes + +## C.1. Layout-handling bugs (gated via `LAYOUT_KNOWN_FAILURES`) + +Surfaced by the layout-robustness arc. The default layout for every test +is now `shuffled_pages`; the more aggressive `interleaved_pages` and +`non_monotonic_extend` are exercised by per-backend `test_layout_robustness_cases` +methods that record each backend's failure mode inline as +`LAYOUT_KNOWN_FAILURES`. Each entry below `[gated]` and skips cleanly. + +### FA dense + +| Test | Layout | Root cause | +|---|---|---| +| `dense/test_fa3.py::test_layout_robustness_cases` (extend) | `non_monotonic_extend` | FA3 prefill metadata assumes `out_cache_loc` is monotonic within an extend. | +| `dense/test_fa4.py::test_layout_robustness_cases` (extend) | `non_monotonic_extend` | FA4 inherits FA3's assumption. | + +### MLA + +| Test | Mode / layout | Root cause | +|---|---|---| +| `mla/test_flashinfer.py::test_layout_robustness_cases` (extend) | `interleaved_pages` | FlashInfer MLA paged-prefill metadata assumes tidy page-table layout; trips illegal memory access. | +| `mla/test_flashinfer.py::test_layout_robustness_cases` (extend) | `non_monotonic_extend` | FlashInfer MLA paged-prefill metadata assumes monotonic `out_cache_loc`; trips illegal memory access. | +| `mla/test_flashinfer.py::test_layout_robustness_cases` (decode) | `interleaved_pages` | FlashInfer MLA paged-decode raises `CUBLAS_STATUS_EXECUTION_FAILED`. | +| `mla/test_flashmla.py::test_layout_robustness_cases` (extend) | `interleaved_pages` | FlashMLA extend raises CUDA illegal memory access. | +| `mla/test_flashmla.py::test_layout_robustness_cases` (extend) | `non_monotonic_extend` | FlashMLA extend raises CUDA illegal memory access. | +| `mla/test_flashmla.py::test_layout_robustness_cases` (decode) | `interleaved_pages` | FlashMLA decode raises `shape '[-1, 64, 1, 32]' is invalid for input of size N`. | + +### Dual-chunk + +| Test | Layout | Root cause | +|---|---|---| +| `dual_chunk/test_dual_chunk_flash_attn.py::test_layout_robustness_cases` (extend) | `non_monotonic_extend` | `_dual_chunk_flash_attn_prefill_func` uses `cu_seqlens_*` indexing into contiguous K slots (`dual_chunk_flashattention_backend.py:834+`); scattered extend-token slots break that contiguity. | + +**Total**: 9 layout-handling production bugs documented. + +## C.2. Speculative-mode rejects + +Mix of `[gated]` (skipTest fires today) and `[no test]` (probed during +fixture investigation; no test in the suite). + +| Backend | Spec mode/kind | Status | Root cause | +|---|---|---|---| +| Mamba2 | tree verify (`topk > 1`) | `[gated]` `speculative_target_verify_runner.py:1214,1276` | SSM kernel ignores tree masks and processes drafts linearly | +| FlashInfer MLA | non-EAGLE chain verify (frozen_kv_mtp / dflash / ngram) | `[no test]` (`mla/README.md`) | `forward_extend` reads EAGLE-specific `spec_info` attrs; trips CUDA illegal-memory access on non-EAGLE attrs | +| FlashMLA | non-EAGLE chain verify | `[no test]` (`mla/README.md`) | Same as FlashInfer MLA (inherits) | +| FlashInfer SWA | non-EAGLE chain verify | `[no test]` (`swa/README.md`) | `FlashInferIndicesUpdaterPrefill.update_sliding_window` rejects `prefix_lens=None` which non-EAGLE paths supply (`flashinfer_backend.py:742,754,1316`) | +| KDA | non-EAGLE chain verify | `[no test]` (`kda/test_triton.py`, per-case `atol=0.2` attempted) | 1/384 elements at ~0.11 max diff vs `KDA_ATOL=0.1`; needs kind-specific reference tolerance | +| Lightning | tree verify (`topk > 1`) | `[no test]` (`lightning/README.md`) | `linear/seg_la.py` has no parent-indices / retrieve-index plumbing | +| FA3 / FA4 | EAGLE tree verify (`topk = 2`) | `[no test]` (`dense/README.md`) | ~0.16 abs-diff bf16 eager-path drift; kernel-level numerical | +| DSV4 | tree verify (`topk > 1`) | `[no test]` (`dsv4/README.md`) | `assert self.topk in [0, 1]` at `deepseek_v4_backend.py:369` | + +## C.3. Graph-runner / CG-capture rejects + +| Backend | Mode | Status | Root cause | +|---|---|---|---| +| FlashInfer MLA | EAGLE draft CG, chain | `[gated on SM≥10]` `mla/test_flashinfer.py::test_runner_mode_eagle_draft_cuda_graph_runner_cases` | FlashInfer MLA decode kernel in container targets SM9x; on Blackwell falls back to a generic path that doesn't restore metadata buffers under graph replay (~22 abs-diff vs reference) | +| FlashMLA | MLA `DRAFT_EXTEND` CUDA-graph replay | `[no test]` (`mla/README.md` Next Work) | Capture falls through to `FlashInferMLAAttnBackend.init_forward_metadata_capture_cuda_graph` (1D `cuda_graph_kv_indices`); FlashMLA decode uses 2D `[max_bs, (max_context + PAGE_SIZE) // PAGE_SIZE]` layout — buffer mismatch | +| GDN / KDA / Lightning / Mamba2 | `DRAFT_EXTEND` and `DRAFT_EXTEND_V2` graph capture | `[no test]` for CG; eager-only paths covered | `HybridLinearAttnBackend` raises `ValueError("Invalid forward mode")` at `hybrid_linear_attn_backend.py:509,572` | +| DSV4 | EAGLE draft_extend with `compress_ratio != 0` | `[no test]` (runner asserts `case.compress_ratio == 0`) | `DeepseekV4ModelNextN` hardcodes `compress_ratio_override=0`, making C4/C128 draft_extend production-unreachable | + +## C.4. Split-op (PCG / BCG) rejects + +All four have the adapter helpers wired so the test can be enabled the +moment production is fixed; no test method invokes them today. + +| Backend | Status | Root cause | +|---|---|---| +| Lightning | `[no test]` (`lightning/README.md`) | Backend returns flat `[T, num_heads * head_dim]` at `lightning_backend.py:335`; `RadixAttention` piecewise writes per-head (`radix_attention.py:124-137`). Shape mismatch eager vs piecewise | +| Mamba2 | `[no test]` (`mamba/README.md`) | `MambaMixer2.forward` projects ALL rows of `hidden_states` before per-layer `num_token_non_padded_cpu` slicing (`mamba.py:467`); trips assert under token-padding | +| DSV4 | `[no test]` (`dsv4/README.md`) | `flash_mla.flash_mla_with_kvcache` asserts `indices.shape == (b, s_q, topk)`; metadata sized for live batch, q is static-token-padded | +| DSA MHA_ONE_SHOT dense fallback | `[no test]` (`dsa/README.md`) | DSA passes K as concatenated `prefix + extend` to `module.attn(save_kv_cache=False)`; `unified_attention_with_output` (`radix_attention.py:170-208`) slices K to `num_token_non_padded_cpu`, dropping the prefix portion — piecewise CG diverges from eager ~50% mismatch (~0.35 max diff) | + +## C.5. Sparse-kernel production bugs + +| Citation | Symptom | Trigger | Status | +|---|---|---|---| +| Triton dense `DRAFT_EXTEND` (non-V2) | Eager fixture/reference mismatch on narrow accepted-token layouts | Test omitted | `[no test]` (`dense/README.md`) | + +## C.6. DSA-specific structural gaps + +| Item | Status | Root cause | +|---|---|---| +| DSA EAGLE tree draft (`topk > 1`) | `[no test]` (`dsa/README.md`); chain-only (`topk=1`) covered | `_DSAEagleDraftForward.__call__` synthesizes `topk_indices` on-GPU (trailing-topk in token-position space); tree draft needs parent-indices plumbing through that synthesis (production sources them from the DSA indexer that lives outside attention) | +| DSA HiSparse coordinator path | `[no test]` (`dsa/README.md` Next Work) | `set_dsa_prefill_impl` forces `use_mha=False` when `hisparse_coordinator is not None`. Mocking the coordinator needs to mirror the fast-drifting production page-table contract | + +--- + +# D. Production-design constraints (intentional, not bugs) + +These are documented for context — they make many "natural" test shapes +impossible because production rejects the combination at construction time. +No action needed; just useful for fixture authors to know what shapes will +fail at backend init. + +## D.1. Backend page-size hard-pins + +| Backend | Required page size(s) | Citation | +|---|---|---| +| FlashMLA | `64` only | `server_args.py:2767-2770` | +| Cutlass MLA | `128` only | `server_args.py:2776-2779`, `cutlass_mla_backend.py:31` | +| TRT-LLM MLA | `{32, 64}` | `server_args.py:2790-2794` | +| Tokenspeed MLA | `{32, 64}` | `server_args.py:2809-2813`, `tokenspeed_mla_backend.py:111-113` | +| TRT-LLM MHA | `{16, 32, 64}` | `server_args.py:2849-2853` | +| FA4 (non-MLA) | `128` when default-selected | `server_args.py:2862-2870` | +| DSV4 | `256` only | `deepseek_v4_backend.py:355`, `dsv4/metadata.py:134` | +| DSA indexer | `1` (HIP) or `64` (CUDA) | `dsa/dsa_indexer.py:547-548, 550, 724-725, 727, 946, 1095` | +| Intel XPU MLA decode | `{16, 32, 64, 128}` | `server_args.py:2906` | +| Intel XPU non-MLA decode | `{64, 128}` | `server_args.py:2909` | + +## D.2. Speculative `topk` hard-rejects + +| Backend | Allowed `topk` | Citation | +|---|---|---| +| `flashinfer_mla` | `1` only | `flashinfer_mla_backend.py:910-913` | +| `flashmla` | `1` only | `flashmla_backend.py:555-558` | +| `trtllm_mla` | `1` only | `trtllm_mla_backend.py:1223-1229` (inherits) | +| `tokenspeed_mla` | `1` only | `tokenspeed_mla_backend.py:341-347` (inherits) | +| `dsv4` | `0` or `1` | `deepseek_v4_backend.py:369`, `:363` (HIP) | +| `trtllm_mha` (graph replay) | `1` only | `trtllm_mha_backend.py:459,492`; `server_args.py:2391-2392` | + +## D.3. KV cache dtype restrictions + +| Backend | Allowed dtype | Citation | +|---|---|---| +| `tokenspeed_mla` | `fp8_e4m3` only | `server_args.py:2814-2818` | +| `trtllm_mla` | `{fp8_e4m3, fp4_e2m1, bf16, auto}` | `server_args.py:2796-2799` | +| `fa3` | not `fp8_e5m2` (silently falls back to `triton`) | `server_args.py:2855-2860` | +| `dsv4` | Packed FP8/BF16 layout enforced by `DeepSeekV4TokenToKVPool` | `deepseek_v4_backend.py:363` | + +--- + +# Quick lookup — by test file + +| Test file | Failure type | Section | +|---|---|---| +| `dual_chunk/test_dual_chunk_flash_attn.py` | Container: `flash_attn` SM10.x wheel | §A.1 | +| `dual_chunk/test_dual_chunk_flash_attn.py::test_layout_robustness_cases` (non_monotonic_extend) | Layout-handling bug | §C.1 | +| `dsa/test_dsa.py::test_sparse_tilelang_*` | Container: tilelang `wait_wgmma` | §A.2 | +| `dsa/test_dsa.py::test_sparse_*_impl_variants` (tilelang row) | Container: tilelang `wait_wgmma` | §A.2 | +| `dsa/test_dsa.py::test_sparse_*_impl_variants` (fa3 / trtllm rows) | Hardware gate | §B | +| `mla/test_cutlass_mla.py` (all) | Hardware gate (SM 10.0 exactly) | §B | +| `mla/test_flashmla.py` (DECODE/verify subtests) | Hardware gate (SM 9.0 Hopper) | §B | +| `mla/test_flashinfer.py::test_runner_mode_eagle_draft_cuda_graph_runner_cases` | Backend bug gated on SM≥10 | §C.3 | +| `mla/test_flashinfer.py::test_layout_robustness_cases` | Layout-handling bug | §C.1 | +| `mla/test_flashmla.py::test_layout_robustness_cases` | Layout-handling bug | §C.1 | +| `dense/test_fa3.py::test_layout_robustness_cases` (non_monotonic_extend) | Layout-handling bug | §C.1 | +| `dense/test_fa4.py::test_layout_robustness_cases` (non_monotonic_extend) | Layout-handling bug | §C.1 | +| `mamba/test_mamba2.py` spec verify tree (topk>1) | Speculative reject | §C.2 | diff --git a/asian_ai/performance/SGLang/test/registered/attention/unittests/__init__.py b/asian_ai/performance/SGLang/test/registered/attention/unittests/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..ce3f51272cd920d276432aaa58591c166d87b941 --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/attention/unittests/__init__.py @@ -0,0 +1 @@ +"""Manual attention backend unit tests.""" diff --git a/asian_ai/performance/SGLang/test/registered/attention/unittests/conftest.py b/asian_ai/performance/SGLang/test/registered/attention/unittests/conftest.py new file mode 100644 index 0000000000000000000000000000000000000000..b967006f303d7ce18ace375e96d82391f2588c51 --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/attention/unittests/conftest.py @@ -0,0 +1,10 @@ +import sys +from pathlib import Path + +# Add this directory to sys.path so that test files can do +# `sys.path.insert(0, str(Path(__file__).resolve().parents[1]))` equivalently, +# and so pytest can import subpackages (dense/, mla/, etc.) without +# confusing this directory with the Python stdlib `unittest` module. +_here = str(Path(__file__).resolve().parent) +if _here not in sys.path: + sys.path.insert(0, _here) diff --git a/asian_ai/performance/SGLang/test/registered/attention/unittests/dense/README.md b/asian_ai/performance/SGLang/test/registered/attention/unittests/dense/README.md new file mode 100644 index 0000000000000000000000000000000000000000..f45f80e55416ecb0616c8b2546c112510171eb6b --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/attention/unittests/dense/README.md @@ -0,0 +1,83 @@ +# Dense Attention Capability Matrix + +This folder covers standard dense MHA/GQA/MQA attention through `RadixAttention`. +Expected outputs come from independent HF-style PyTorch reference modules with +copied random projection weights, not from another SGLang attention backend. + +## Coverage Matrix + +Columns are runner modes; rows are attention backends. Cells use: +- **✓ \** — exercised, with the config variants listed in the cell +- **—** — not applicable (no production path for this combination) +- **blocked: \** — production-unsupported, not a follow-up +- **deferred: \** — could land later, currently disabled + +| Backend | Eager Phase 2 | CG decode | PCG extend | BCG extend | Verify eager | Verify CG | DE eager | DE CG | DE-V2 CG | EAGLE-draft runner | EAGLE-DE runner | FKVMTP runner | +|---|---|---|---|---|---|---|---|---|---|---|---|---| +| `torch_native` | ✓ full MHA/GQA/MQA input sweep + decode/extend runner-eager cases | — (no `init_cuda_graph_state` / capture / replay hooks) | — (no CG path) | — (no CG path) | deferred: extend-metadata mismatch in `TARGET_VERIFY` reference | — | — | — | — | — | — | — | +| `triton` | ✓ MHA/GQA/MQA + 10 input layouts (page 1/16/32, prefix/decode edges) | ✓ MHA/GQA/MQA decode page-boundary | ✓ MHA ragged, GQA cross-page | ✓ MHA ragged, GQA cross-page | ✓ EAGLE chain+tree, Frozen-KV-MTP chain, DFlash chain, NGRAM chain | ✓ EAGLE tree, DFlash chain, NGRAM chain | deferred: Triton `DRAFT_EXTEND` HF-ref mismatch on narrow accept layouts | — (V1 not enabled; Triton uses V2) | ✓ fixed-tokens-per-req | ✓ chain (topk=1) + tree (topk=2) | ✓ via `DRAFT_EXTEND_V2` graph runner | — (production dispatcher only wires Frozen-KV-MTP through FlashInfer-style draft backends) | +| `flashinfer` | ✓ MHA/GQA/MQA + 10 input layouts (`head_dim=64` for SM90 prefill constraints) | ✓ MHA/GQA/MQA decode page-boundary | ✓ MHA ragged, GQA cross-page | ✓ MHA ragged, GQA cross-page | ✓ EAGLE chain+tree, Frozen-KV-MTP chain, DFlash chain, NGRAM chain | ✓ EAGLE tree, Frozen-KV-MTP chain, DFlash chain | ✓ EAGLE ragged-accept, Frozen-KV-MTP ragged-accept | ✓ EAGLE ragged-accept, Frozen-KV-MTP ragged-accept | blocked: `is_draft_extend()` default `include_v2=False` → `raise ValueError` (`flashinfer_backend.py:651,748`) | ✓ chain (topk=1) + tree (topk=2) | ✓ EAGLE ragged-accept (V1) | ✓ chain (topk=1) | +| `fa3` | ✓ MHA/GQA/MQA input sweep (FA-friendly `head_dim=64`) | ✓ MHA decode page-boundary | ✓ MHA ragged, GQA cross-page | ✓ MHA ragged, GQA cross-page | deferred: EAGLE tree (topk=2) eager diffs ~0.16 vs the bf16 HF reference — kernel-level drift, not a CG issue | deferred: same kernel-level drift | — | — | ✓ fixed-tokens-per-req | — | ✓ via `DRAFT_EXTEND_V2` graph runner | — | +| `fa4` | ✓ MHA/GQA/MQA input sweep (FA-friendly `head_dim=64`) | ✓ MHA decode page-boundary | ✓ MHA ragged, GQA cross-page | ✓ MHA ragged, GQA cross-page | deferred: same EAGLE tree eager drift as fa3 | deferred: same | — | — | ✓ fixed-tokens-per-req | — | ✓ via `DRAFT_EXTEND_V2` graph runner | — | +| `flex_attention` | ✓ MHA/GQA/MQA input sweep | blocked: no `init_cuda_graph_state` / capture / replay hooks (`torch_flex_backend.py`) | ✓ MHA ragged, GQA cross-page | ✓ MHA ragged, GQA cross-page | blocked: no CG capture/replay path | blocked: no CG capture/replay path | — | blocked: no CG capture/replay path | blocked: no CG capture/replay path | blocked: no CG capture/replay path | blocked: no CG capture/replay path | blocked: no CG capture/replay path | +| `trtllm_mha` | ✓ decode-only MHA/GQA/MQA + page-32 boundary (prefill blocked by `Unsupported architecture`) | deferred: replay mismatches HF-ref on SM90 | — (no extend backend) | — (no extend backend) | blocked: `topk=1` only (`server_args.py:2391-2392`, `trtllm_mha_backend.py:459,492`) | blocked: same `topk=1` constraint | — | — | — | ✓ chain (topk=1) | — | — | + +### Wrapper backends (smoke tests only) + +| Wrapper | Coverage | +|---|---| +| `hybrid_attn` (`prefill=triton`, `decode=flashinfer`) | ✓ EXTEND dispatches to prefill backend; ✓ DECODE dispatches to decode backend. No CG / spec coverage — the wrapper just forwards to the chosen child. | +| `tbo` (children=`[triton, triton]`) | ✓ EXTEND with no `tbo_children` set: delegates to `primary`. Sub-batched orchestration through TBO children needs scheduler-level batch splitting and is deferred. | + +## Input And Config Coverage + +- Page size 1, page size 16, and representative page size 32. +- Zero-prefix exact page, prefix exact page, total exact page, and page-boundary crossing. +- Ragged batches with lengths below/equal/above a page. +- Decode page-boundary batches and batch-size-1 decode. +- Attention config coverage for MHA, GQA, and MQA is separate from input-layout coverage. + +## Notes on the "—" cells + +- **`torch_native` graph rows** — `TorchNativeAttnBackend` does not override + `init_cuda_graph_state` / `init_forward_metadata_capture_cuda_graph` / + `init_forward_metadata_replay_cuda_graph`; the base class raises + `NotImplementedError` (`base_attn_backend.py:24-55`). +- **`flex_attention` graph rows** — `TorchFlexAttnBackend` also has no CG hooks. + It additionally rejects non-causal (`torch_flex_backend.py:151`) and cross / + encoder-only attention (`torch_flex_backend.py:267-270`). +- **`trtllm_mha` extend rows** — backend exposes decode only; prefill currently + reports `Unsupported architecture` and page sizes are restricted to + `{16, 32, 64}` (`server_args.py:2849-2853`). +- **`triton` FKVMTP runner** — `FrozenKVMTPMultiStepDraftBackend` dispatch wires + Triton through the FlashInfer-style draft path; the dedicated runner case is + only enabled where production routes that draft worker. + +## Capture-vs-replay test contract + +The CUDA graph runner tests treat the capture-time forward as a JIT +warmup (matching production semantics): the captured graph records +kernel launches against metadata buffers that *will* be populated by +`init_forward_metadata_replay_cuda_graph` at replay time. Only the +replay output is asserted against the reference and against the eager +result. Capture-time output is discarded. + +Earlier iterations of this test asserted capture-time output too, +which only worked for backends that happen to populate metadata +buffers *during* their `init_forward_metadata_capture_cuda_graph` +(Triton/FlashInfer populate `kv_indices` via +`create_flashinfer_kv_indices_triton` at capture). FlashAttention +v3/v4 assign buffer slices but don't write valid values at capture — +that's intentional and correct for production where capture output is +discarded. Dropping the capture-output assertion aligns the test with +production and unblocks FA CG decode coverage without backend-specific +shims. + +## Next Work + +- Debug torch-native target-verify extend metadata. +- Debug Triton `DRAFT_EXTEND` metadata/reference mismatch. +- Debug remaining FA3/FA4 speculative-graph mismatches: EAGLE tree + verify (eager) diffs ~0.16 vs the bf16 HF reference (kernel-level + drift, NOT a CG issue — fires before any capture/replay). +- Add backend-specific graph coverage for `trtllm_mha` once local hardware and metadata behavior allow it. diff --git a/asian_ai/performance/SGLang/test/registered/attention/unittests/dense/__init__.py b/asian_ai/performance/SGLang/test/registered/attention/unittests/dense/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..44165446dd610df4474a381c505c8d7ca5f181b3 --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/attention/unittests/dense/__init__.py @@ -0,0 +1 @@ +"""Dense attention backend tests.""" diff --git a/asian_ai/performance/SGLang/test/registered/attention/unittests/dense/test_extend_init_contract.py b/asian_ai/performance/SGLang/test/registered/attention/unittests/dense/test_extend_init_contract.py new file mode 100644 index 0000000000000000000000000000000000000000..98427a091db2e44a6679928bdd062e162668a3a5 --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/attention/unittests/dense/test_extend_init_contract.py @@ -0,0 +1,147 @@ +"""Unit tests for the init contract that piecewise + breakable cuda graph +capture rely on with ``forward_mode=EXTEND``. + +The piecewise + breakable runners (unlike the full ``cuda_graph_runner``) +capture prefill chunks, which means their capture path passes +``forward_mode=ForwardMode.EXTEND`` to ``attn_backend.init_forward_metadata*``. + +Backends like FlashInfer and FA3 implement two separate init bodies: + +- ``init_forward_metadata(fb)`` — the eager entry. Handles all modes + including plain ``EXTEND`` (full prefill / chunked prefill). +- ``init_forward_metadata_out_graph(fb, in_capture=True)`` — the + bucket-keyed wrapper prep used by the full cuda graph runner. Only + handles modes the full runner captures: ``DECODE`` / ``IDLE`` / + ``TARGET_VERIFY`` / ``DRAFT_EXTEND`` / ``DLLM_EXTEND``. Plain + ``EXTEND`` is not in scope here and the body raises on it. + +These tests pin both halves of that contract so a future refactor that +incorrectly routes piecewise/breakable capture through ``_out_graph(in_capture=True)`` +fails at unit-test time instead of at GPU CI / e2e time. This is the +specific regression #26735 introduced and then fixed +(see ``piecewise_cuda_graph_runner.py`` / +``breakable_cuda_graph_runner.py`` capture sites). +""" + +import sys +import unittest +from pathlib import Path + +import torch + +from sglang.srt.model_executor.forward_batch_info import ForwardMode +from sglang.srt.utils import get_device_sm +from sglang.test.test_utils import CustomTestCase + +sys.path.insert(0, str(Path(__file__).resolve().parents[1])) + +from sglang.test.ci.ci_register import register_cuda_ci +from sglang.test.kits.attention_unittest.attention_methods.dense_attention import ( + DenseAttentionCase, + build_dense_attention_fixture, +) + +register_cuda_ci(est_time=10, stage="base-a", runner_config="1-gpu-small") + +_EXTEND_CASE = DenseAttentionCase( + name="extend_no_prefix_smoke", + backend="fa3", # overridden per backend below + forward_mode=ForwardMode.EXTEND, + num_heads=4, + num_kv_heads=4, + page_size=16, + prefix_lens=(0,), + extend_lens=(16,), +) + + +@unittest.skipIf(not torch.cuda.is_available(), "CUDA is required") +class TestExtendInitContract(CustomTestCase): + + def _make_case(self, backend: str) -> DenseAttentionCase: + return DenseAttentionCase( + name=f"extend_no_prefix_{backend}", + backend=backend, + forward_mode=_EXTEND_CASE.forward_mode, + num_heads=_EXTEND_CASE.num_heads, + num_kv_heads=_EXTEND_CASE.num_kv_heads, + page_size=_EXTEND_CASE.page_size, + prefix_lens=_EXTEND_CASE.prefix_lens, + extend_lens=_EXTEND_CASE.extend_lens, + ) + + def _build_fixture(self, backend: str, *, head_dim: int = 16): + case = self._make_case(backend) + try: + return build_dense_attention_fixture(self, case, head_dim=head_dim) + except (AssertionError, ImportError, ModuleNotFoundError) as exc: + self.skipTest(f"backend {backend} unavailable: {exc}") + + def _assert_extend_eager_init_well_formed( + self, backend: str, *, head_dim: int = 16 + ): + fixture = self._build_fixture(backend, head_dim=head_dim) + fixture.backend.init_forward_metadata(fixture.forward_batch) + meta = fixture.backend.forward_metadata + self.assertIsNotNone( + meta, + f"{backend}: init_forward_metadata(EXTEND) left forward_metadata as None — " + "piecewise/breakable capture would crash on the first forward_extend call.", + ) + page_table = getattr(meta, "page_table", None) + if page_table is not None: + self.assertIsInstance(page_table, torch.Tensor) + + @unittest.skipIf( + get_device_sm() >= 100 or get_device_sm() < 80, + "FA3 backend requires SM 80-90", + ) + def test_fa3_extend_eager_init(self): + self._assert_extend_eager_init_well_formed("fa3") + + def test_flashinfer_extend_eager_init(self): + # FlashInfer's JIT prefill kernel needs head_dim ≥ 64. + self._assert_extend_eager_init_well_formed("flashinfer", head_dim=128) + + def test_triton_extend_eager_init(self): + self._assert_extend_eager_init_well_formed("triton") + + def _assert_out_graph_in_capture_rejects_extend( + self, backend: str, *, head_dim: int = 16 + ): + """``init_forward_metadata_out_graph(fb, in_capture=True)`` is the + bucket-prep path. Plain EXTEND mode isn't in its supported set — + piecewise/breakable capture used to route through here and crash. + This pins the constraint: if the path starts handling EXTEND + (raises become passes), revisit the piecewise/breakable capture + wiring and consider unifying the API. + """ + fixture = self._build_fixture(backend, head_dim=head_dim) + try: + fixture.backend.init_forward_metadata_out_graph( + fixture.forward_batch, in_capture=True + ) + except (ValueError, AttributeError, KeyError, AssertionError): + return + meta = fixture.backend.forward_metadata + self.assertIsNotNone( + meta, + f"{backend}: _out_graph(in_capture=True) accepted EXTEND but left " + "forward_metadata as None — this is the specific bug pattern that " + "broke piecewise capture (FA3._apply_cuda_graph_metadata falls " + "through for unsupported modes and sets self.forward_metadata = None).", + ) + + @unittest.skipIf( + get_device_sm() >= 100 or get_device_sm() < 80, + "FA3 backend requires SM 80-90", + ) + def test_fa3_out_graph_capture_rejects_extend(self): + self._assert_out_graph_in_capture_rejects_extend("fa3") + + def test_flashinfer_out_graph_capture_rejects_extend(self): + self._assert_out_graph_in_capture_rejects_extend("flashinfer", head_dim=128) + + +if __name__ == "__main__": + unittest.main() diff --git a/asian_ai/performance/SGLang/test/registered/attention/unittests/dense/test_fa3.py b/asian_ai/performance/SGLang/test/registered/attention/unittests/dense/test_fa3.py new file mode 100644 index 0000000000000000000000000000000000000000..143471009a5613e5d3896b4a9aa6d80e6ce07e01 --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/attention/unittests/dense/test_fa3.py @@ -0,0 +1,444 @@ +import sys +import unittest +from pathlib import Path + +import torch + +from sglang.srt.model_executor.forward_batch_info import ForwardMode +from sglang.srt.utils import get_device_sm +from sglang.test.test_utils import CustomTestCase + +sys.path.insert(0, str(Path(__file__).resolve().parents[1])) + +from sglang.test.ci.ci_register import register_cuda_ci +from sglang.test.kits.attention_unittest.attention_methods.dense_attention import ( + DenseAttentionCase, + make_dense_cases, + run_dense_attention_case, +) +from sglang.test.kits.attention_unittest.runner_modes.cuda_graph_decode_runner import ( + run_dense_cuda_graph_decode_case, +) +from sglang.test.kits.attention_unittest.runner_modes.speculative_draft_extend_runner import ( + run_dense_draft_extend_v2_cuda_graph_case, + run_dense_eagle_draft_extend_v2_cuda_graph_runner_case, +) +from sglang.test.kits.attention_unittest.runner_modes.speculative_draft_runner import ( + run_dense_eagle_draft_cuda_graph_runner_case, + run_dense_frozen_kv_mtp_cuda_graph_runner_case, +) +from sglang.test.kits.attention_unittest.runner_modes.speculative_target_verify_runner import ( + run_dense_spec_verify_case, + run_dense_spec_verify_cuda_graph_case, +) +from sglang.test.kits.attention_unittest.runner_modes.split_op_runner import ( + run_dense_split_op_extend_case, +) + +register_cuda_ci(est_time=25, stage="base-b", runner_config="4-gpu-b200") +register_cuda_ci(est_time=25, stage="base-b", runner_config="1-gpu-large") + + +@unittest.skipIf(not torch.cuda.is_available(), "CUDA is required") +@unittest.skipIf( + get_device_sm() >= 100, + "FA3 backend requires SM 80-90; skipping on Blackwell+ (B200/GB200/GB300)", +) +class TestFA3DenseAttentionBackendCorrectness(CustomTestCase): + # FlashAttention kernels are most stable in this harness with FA-friendly dims. + HEAD_DIM = 64 + HIDDEN_SIZE = 256 + + CASES = make_dense_cases("fa3") + CUDA_GRAPH_CASES = ( + DenseAttentionCase( + name="runner_cuda_graph_fa3_mha_decode_page_boundary", + backend="fa3", + forward_mode=ForwardMode.DECODE, + num_heads=4, + num_kv_heads=4, + page_size=16, + prefix_lens=(14, 15, 16), + ), + ) + DRAFT_EXTEND_V2_CUDA_GRAPH_CASES = ( + DenseAttentionCase( + name="runner_cuda_graph_fa3_eagle_draft_extend_v2_fixed_tokens", + backend="fa3", + forward_mode=ForwardMode.DRAFT_EXTEND_V2, + num_heads=4, + num_kv_heads=4, + page_size=16, + prefix_lens=(4, 7), + extend_lens=(3, 3), + ), + ) + # EAGLE chain verify (topk=1) — tree (topk=2) drifts ~0.16 vs the bf16 + # HF reference at the kernel level (not a CG mechanic) so it stays + # deferred. See PLAN.md "Latest verification". + # + # The non-EAGLE spec kinds (frozen_kv_mtp, dflash, ngram) are also + # chain-only on FA; they pass the same shape through + # `_make_spec_verify_input` with a different `spec_kind` tag. + SPEC_VERIFY_CHAIN_CASES = ( + ( + DenseAttentionCase( + name="runner_fa3_eagle_verify_chain", + backend="fa3", + forward_mode=ForwardMode.TARGET_VERIFY, + num_heads=4, + num_kv_heads=4, + page_size=16, + prefix_lens=(4, 7), + extend_lens=(3, 3), + ), + "eagle", + ), + ( + DenseAttentionCase( + name="runner_fa3_frozen_kv_mtp_verify_chain", + backend="fa3", + forward_mode=ForwardMode.TARGET_VERIFY, + num_heads=4, + num_kv_heads=4, + page_size=16, + prefix_lens=(4, 7), + extend_lens=(3, 3), + ), + "frozen_kv_mtp", + ), + ( + DenseAttentionCase( + name="runner_fa3_dflash_verify_chain", + backend="fa3", + forward_mode=ForwardMode.TARGET_VERIFY, + num_heads=4, + num_kv_heads=4, + page_size=16, + prefix_lens=(4, 7), + extend_lens=(3, 3), + ), + "dflash", + ), + ( + DenseAttentionCase( + name="runner_fa3_ngram_verify_chain", + backend="fa3", + forward_mode=ForwardMode.TARGET_VERIFY, + num_heads=4, + num_kv_heads=4, + page_size=16, + prefix_lens=(4, 7), + extend_lens=(3, 3), + ), + "ngram", + ), + ) + SPEC_VERIFY_CHAIN_CUDA_GRAPH_CASES = ( + ( + DenseAttentionCase( + name="runner_cuda_graph_fa3_eagle_verify_chain", + backend="fa3", + forward_mode=ForwardMode.TARGET_VERIFY, + num_heads=4, + num_kv_heads=4, + page_size=16, + prefix_lens=(4, 7), + extend_lens=(3, 3), + ), + "eagle", + ), + ( + DenseAttentionCase( + name="runner_cuda_graph_fa3_frozen_kv_mtp_verify_chain", + backend="fa3", + forward_mode=ForwardMode.TARGET_VERIFY, + num_heads=4, + num_kv_heads=4, + page_size=16, + prefix_lens=(4, 7), + extend_lens=(3, 3), + ), + "frozen_kv_mtp", + ), + ( + DenseAttentionCase( + name="runner_cuda_graph_fa3_dflash_verify_chain", + backend="fa3", + forward_mode=ForwardMode.TARGET_VERIFY, + num_heads=4, + num_kv_heads=4, + page_size=16, + prefix_lens=(4, 7), + extend_lens=(3, 3), + ), + "dflash", + ), + ( + DenseAttentionCase( + name="runner_cuda_graph_fa3_ngram_verify_chain", + backend="fa3", + forward_mode=ForwardMode.TARGET_VERIFY, + num_heads=4, + num_kv_heads=4, + page_size=16, + prefix_lens=(4, 7), + extend_lens=(3, 3), + ), + "ngram", + ), + ) + EAGLE_DRAFT_EXTEND_V2_RUNNER_CASES = ( + DenseAttentionCase( + name="runner_fa3_eagle_draft_extend_v2_cuda_graph_runner_fixed_tokens", + backend="fa3", + forward_mode=ForwardMode.DRAFT_EXTEND_V2, + num_heads=4, + num_kv_heads=4, + page_size=16, + prefix_lens=(4, 7), + extend_lens=(3, 3), + ), + ) + EAGLE_DRAFT_RUNNER_CASES = ( + ( + DenseAttentionCase( + name="runner_fa3_eagle_draft_decode_cuda_graph_chain", + backend="fa3", + forward_mode=ForwardMode.DECODE, + num_heads=4, + num_kv_heads=4, + page_size=16, + prefix_lens=(4, 7), + ), + 1, + 3, + ), + ) + FROZEN_KV_MTP_RUNNER_CASES = ( + DenseAttentionCase( + name="runner_fa3_frozen_kv_mtp_decode_cuda_graph", + backend="fa3", + forward_mode=ForwardMode.DECODE, + num_heads=4, + num_kv_heads=4, + page_size=16, + prefix_lens=(4, 7), + ), + ) + SPLIT_OP_CASES = ( + ( + DenseAttentionCase( + name="runner_split_op_mha_extend_ragged_page_boundary", + backend="fa3", + forward_mode=ForwardMode.EXTEND, + num_heads=4, + num_kv_heads=4, + page_size=16, + prefix_lens=(0, 8, 16), + extend_lens=(15, 8, 1), + ), + 32, + ), + ( + DenseAttentionCase( + name="runner_split_op_gqa_extend_cross_page_boundary", + backend="fa3", + forward_mode=ForwardMode.EXTEND, + num_heads=4, + num_kv_heads=2, + page_size=16, + prefix_lens=(15,), + extend_lens=(2,), + ), + 4, + ), + ) + + # Layout-robustness: catches backend bugs in page-table derivation + # from non-tidy (req_to_token, out_cache_loc) mappings. See + # dense/test_triton.py for the full rationale. FA3 passes + # shuffled_pages and interleaved_pages but FAILS on + # non_monotonic_extend for EXTEND — FA3's prefill metadata appears + # to assume out_cache_loc is monotonic within an extend, so when + # the test scatters extend-token slots inside a request the kernel + # reads stale K from the wrong physical positions. Documented as a + # known production limitation that fragmented allocator state + # could surface. + LAYOUT_ROBUSTNESS_CASES = ( + DenseAttentionCase( + name="layout_extend_two_request_ragged", + backend="fa3", + forward_mode=ForwardMode.EXTEND, + num_heads=12, + num_kv_heads=12, + page_size=16, + prefix_lens=(8, 16), + extend_lens=(8, 16), + ), + DenseAttentionCase( + name="layout_decode_page_boundary", + backend="fa3", + forward_mode=ForwardMode.DECODE, + num_heads=12, + num_kv_heads=12, + page_size=16, + prefix_lens=(15, 16, 17), + ), + ) + LAYOUT_KNOWN_FAILURES = { + ("layout_extend_two_request_ragged", "non_monotonic_extend"): ( + "FA3 prefill metadata assumes out_cache_loc is monotonic " + "within an extend; a fragmented allocator could trip this." + ), + } + + def test_layout_robustness_cases(self): + for case in self.LAYOUT_ROBUSTNESS_CASES: + # shuffled_pages is the default and already covered. + for layout in ( + "interleaved_pages", + "non_monotonic_extend", + ): + if layout == "non_monotonic_extend" and case.forward_mode.is_decode(): + continue + reason = self.LAYOUT_KNOWN_FAILURES.get((case.name, layout)) + if reason is not None: + print( + f"[layout-known-failure] {case.name} x {layout}: {reason}", + flush=True, + ) + continue + with self.subTest(case=case.name, layout=layout): + run_dense_attention_case( + self, + case, + head_dim=self.HEAD_DIM, + hidden_size=self.HIDDEN_SIZE, + loc_layout=layout, + ) + + def test_projected_dense_attention_cases(self): + for case in self.CASES: + with self.subTest(case=case.name, backend=case.backend): + run_dense_attention_case( + self, + case, + head_dim=self.HEAD_DIM, + hidden_size=self.HIDDEN_SIZE, + ) + + def test_runner_mode_cuda_graph_decode_cases(self): + for case in self.CUDA_GRAPH_CASES: + with self.subTest(case=case.name, backend=case.backend): + run_dense_cuda_graph_decode_case( + self, + case, + head_dim=self.HEAD_DIM, + hidden_size=self.HIDDEN_SIZE, + ) + + def test_runner_mode_split_op_extend_cases(self): + for case, static_num_tokens in self.SPLIT_OP_CASES: + for breakable in (False, True): + runner = "bcg" if breakable else "pcg" + with self.subTest( + case=case.name, + backend=case.backend, + runner=runner, + ): + run_dense_split_op_extend_case( + self, + case, + breakable=breakable, + static_num_tokens=static_num_tokens, + head_dim=self.HEAD_DIM, + hidden_size=self.HIDDEN_SIZE, + ) + + def test_runner_mode_eagle_draft_extend_v2_cuda_graph_cases(self): + for case in self.DRAFT_EXTEND_V2_CUDA_GRAPH_CASES: + for pad_style in ("small_real", "prod_fill"): + for capture_bs in ( + case.batch_size, + case.batch_size * 2, + case.batch_size * 4, + ): + with self.subTest( + case=case.name, + backend=case.backend, + pad_style=pad_style, + capture_bs=capture_bs, + ): + run_dense_draft_extend_v2_cuda_graph_case( + self, + case, + head_dim=self.HEAD_DIM, + hidden_size=self.HIDDEN_SIZE, + cuda_graph_capture_batch_size=capture_bs, + pad_style=pad_style, + ) + + def test_runner_mode_eagle_draft_extend_v2_cuda_graph_runner_cases(self): + for case in self.EAGLE_DRAFT_EXTEND_V2_RUNNER_CASES: + with self.subTest(case=case.name, backend=case.backend): + run_dense_eagle_draft_extend_v2_cuda_graph_runner_case( + self, + case, + head_dim=self.HEAD_DIM, + hidden_size=self.HIDDEN_SIZE, + ) + + def test_runner_mode_eagle_draft_cuda_graph_runner_cases(self): + for case, topk, num_draft_tokens in self.EAGLE_DRAFT_RUNNER_CASES: + with self.subTest(case=case.name, backend=case.backend, topk=topk): + run_dense_eagle_draft_cuda_graph_runner_case( + self, + case, + topk=topk, + speculative_num_draft_tokens=num_draft_tokens, + head_dim=self.HEAD_DIM, + hidden_size=self.HIDDEN_SIZE, + ) + + def test_runner_mode_frozen_kv_mtp_cuda_graph_runner_cases(self): + for case in self.FROZEN_KV_MTP_RUNNER_CASES: + with self.subTest(case=case.name, backend=case.backend): + run_dense_frozen_kv_mtp_cuda_graph_runner_case( + self, + case, + head_dim=self.HEAD_DIM, + hidden_size=self.HIDDEN_SIZE, + ) + + def test_runner_mode_spec_verify_cases(self): + for case, spec_kind in self.SPEC_VERIFY_CHAIN_CASES: + with self.subTest( + case=case.name, backend=case.backend, spec_kind=spec_kind + ): + run_dense_spec_verify_case( + self, + case, + topk=1, + spec_kind=spec_kind, + head_dim=self.HEAD_DIM, + hidden_size=self.HIDDEN_SIZE, + ) + + def test_runner_mode_spec_verify_cuda_graph_cases(self): + for case, spec_kind in self.SPEC_VERIFY_CHAIN_CUDA_GRAPH_CASES: + with self.subTest( + case=case.name, backend=case.backend, spec_kind=spec_kind + ): + run_dense_spec_verify_cuda_graph_case( + self, + case, + topk=1, + spec_kind=spec_kind, + head_dim=self.HEAD_DIM, + hidden_size=self.HIDDEN_SIZE, + ) + + +if __name__ == "__main__": + unittest.main() diff --git a/asian_ai/performance/SGLang/test/registered/attention/unittests/dense/test_fa4.py b/asian_ai/performance/SGLang/test/registered/attention/unittests/dense/test_fa4.py new file mode 100644 index 0000000000000000000000000000000000000000..4724c672fd195cc4ddfce7cd6fafe9603b207666 --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/attention/unittests/dense/test_fa4.py @@ -0,0 +1,433 @@ +import sys +import unittest +from pathlib import Path + +import torch + +from sglang.srt.model_executor.forward_batch_info import ForwardMode +from sglang.test.test_utils import CustomTestCase + +sys.path.insert(0, str(Path(__file__).resolve().parents[1])) + +from sglang.test.ci.ci_register import register_cuda_ci +from sglang.test.kits.attention_unittest.attention_methods.dense_attention import ( + DenseAttentionCase, + make_dense_cases, + run_dense_attention_case, +) +from sglang.test.kits.attention_unittest.runner_modes.cuda_graph_decode_runner import ( + run_dense_cuda_graph_decode_case, +) +from sglang.test.kits.attention_unittest.runner_modes.speculative_draft_extend_runner import ( + run_dense_draft_extend_v2_cuda_graph_case, + run_dense_eagle_draft_extend_v2_cuda_graph_runner_case, +) +from sglang.test.kits.attention_unittest.runner_modes.speculative_draft_runner import ( + run_dense_eagle_draft_cuda_graph_runner_case, + run_dense_frozen_kv_mtp_cuda_graph_runner_case, +) +from sglang.test.kits.attention_unittest.runner_modes.speculative_target_verify_runner import ( + run_dense_spec_verify_case, + run_dense_spec_verify_cuda_graph_case, +) +from sglang.test.kits.attention_unittest.runner_modes.split_op_runner import ( + run_dense_split_op_extend_case, +) + +register_cuda_ci(est_time=45, stage="base-b", runner_config="4-gpu-b200") +register_cuda_ci(est_time=45, stage="base-b", runner_config="1-gpu-large") + + +@unittest.skipIf(not torch.cuda.is_available(), "CUDA is required") +class TestFA4DenseAttentionBackendCorrectness(CustomTestCase): + # FlashAttention kernels are most stable in this harness with FA-friendly dims. + HEAD_DIM = 64 + HIDDEN_SIZE = 256 + + CASES = make_dense_cases("fa4") + CUDA_GRAPH_CASES = ( + DenseAttentionCase( + name="runner_cuda_graph_fa4_mha_decode_page_boundary", + backend="fa4", + forward_mode=ForwardMode.DECODE, + num_heads=4, + num_kv_heads=4, + page_size=16, + prefix_lens=(14, 15, 16), + ), + ) + DRAFT_EXTEND_V2_CUDA_GRAPH_CASES = ( + DenseAttentionCase( + name="runner_cuda_graph_fa4_eagle_draft_extend_v2_fixed_tokens", + backend="fa4", + forward_mode=ForwardMode.DRAFT_EXTEND_V2, + num_heads=4, + num_kv_heads=4, + page_size=16, + prefix_lens=(4, 7), + extend_lens=(3, 3), + ), + ) + # EAGLE chain verify (topk=1) — tree (topk=2) drifts ~0.16 vs the bf16 + # HF reference at the kernel level (not a CG mechanic) so it stays + # deferred. See PLAN.md "Latest verification". + # + # The non-EAGLE spec kinds (frozen_kv_mtp, dflash, ngram) are also + # chain-only on FA; they pass the same shape through + # `_make_spec_verify_input` with a different `spec_kind` tag. + SPEC_VERIFY_CHAIN_CASES = ( + ( + DenseAttentionCase( + name="runner_fa4_eagle_verify_chain", + backend="fa4", + forward_mode=ForwardMode.TARGET_VERIFY, + num_heads=4, + num_kv_heads=4, + page_size=16, + prefix_lens=(4, 7), + extend_lens=(3, 3), + ), + "eagle", + ), + ( + DenseAttentionCase( + name="runner_fa4_frozen_kv_mtp_verify_chain", + backend="fa4", + forward_mode=ForwardMode.TARGET_VERIFY, + num_heads=4, + num_kv_heads=4, + page_size=16, + prefix_lens=(4, 7), + extend_lens=(3, 3), + ), + "frozen_kv_mtp", + ), + ( + DenseAttentionCase( + name="runner_fa4_dflash_verify_chain", + backend="fa4", + forward_mode=ForwardMode.TARGET_VERIFY, + num_heads=4, + num_kv_heads=4, + page_size=16, + prefix_lens=(4, 7), + extend_lens=(3, 3), + ), + "dflash", + ), + ( + DenseAttentionCase( + name="runner_fa4_ngram_verify_chain", + backend="fa4", + forward_mode=ForwardMode.TARGET_VERIFY, + num_heads=4, + num_kv_heads=4, + page_size=16, + prefix_lens=(4, 7), + extend_lens=(3, 3), + ), + "ngram", + ), + ) + SPEC_VERIFY_CHAIN_CUDA_GRAPH_CASES = ( + ( + DenseAttentionCase( + name="runner_cuda_graph_fa4_eagle_verify_chain", + backend="fa4", + forward_mode=ForwardMode.TARGET_VERIFY, + num_heads=4, + num_kv_heads=4, + page_size=16, + prefix_lens=(4, 7), + extend_lens=(3, 3), + ), + "eagle", + ), + ( + DenseAttentionCase( + name="runner_cuda_graph_fa4_frozen_kv_mtp_verify_chain", + backend="fa4", + forward_mode=ForwardMode.TARGET_VERIFY, + num_heads=4, + num_kv_heads=4, + page_size=16, + prefix_lens=(4, 7), + extend_lens=(3, 3), + ), + "frozen_kv_mtp", + ), + ( + DenseAttentionCase( + name="runner_cuda_graph_fa4_dflash_verify_chain", + backend="fa4", + forward_mode=ForwardMode.TARGET_VERIFY, + num_heads=4, + num_kv_heads=4, + page_size=16, + prefix_lens=(4, 7), + extend_lens=(3, 3), + ), + "dflash", + ), + ( + DenseAttentionCase( + name="runner_cuda_graph_fa4_ngram_verify_chain", + backend="fa4", + forward_mode=ForwardMode.TARGET_VERIFY, + num_heads=4, + num_kv_heads=4, + page_size=16, + prefix_lens=(4, 7), + extend_lens=(3, 3), + ), + "ngram", + ), + ) + EAGLE_DRAFT_EXTEND_V2_RUNNER_CASES = ( + DenseAttentionCase( + name="runner_fa4_eagle_draft_extend_v2_cuda_graph_runner_fixed_tokens", + backend="fa4", + forward_mode=ForwardMode.DRAFT_EXTEND_V2, + num_heads=4, + num_kv_heads=4, + page_size=16, + prefix_lens=(4, 7), + extend_lens=(3, 3), + ), + ) + EAGLE_DRAFT_RUNNER_CASES = ( + ( + DenseAttentionCase( + name="runner_fa4_eagle_draft_decode_cuda_graph_chain", + backend="fa4", + forward_mode=ForwardMode.DECODE, + num_heads=4, + num_kv_heads=4, + page_size=16, + prefix_lens=(4, 7), + ), + 1, + 3, + ), + ) + FROZEN_KV_MTP_RUNNER_CASES = ( + DenseAttentionCase( + name="runner_fa4_frozen_kv_mtp_decode_cuda_graph", + backend="fa4", + forward_mode=ForwardMode.DECODE, + num_heads=4, + num_kv_heads=4, + page_size=16, + prefix_lens=(4, 7), + ), + ) + SPLIT_OP_CASES = ( + ( + DenseAttentionCase( + name="runner_split_op_mha_extend_ragged_page_boundary", + backend="fa4", + forward_mode=ForwardMode.EXTEND, + num_heads=4, + num_kv_heads=4, + page_size=16, + prefix_lens=(0, 8, 16), + extend_lens=(15, 8, 1), + ), + 32, + ), + ( + DenseAttentionCase( + name="runner_split_op_gqa_extend_cross_page_boundary", + backend="fa4", + forward_mode=ForwardMode.EXTEND, + num_heads=4, + num_kv_heads=2, + page_size=16, + prefix_lens=(15,), + extend_lens=(2,), + ), + 4, + ), + ) + + # Layout-robustness. See dense/test_triton.py for full rationale and + # dense/test_fa3.py for the FA-family non_monotonic_extend known + # failure. FA4 inherits FA3's prefill metadata convention and shows + # the same divergence on scattered extend-token slots. + LAYOUT_ROBUSTNESS_CASES = ( + DenseAttentionCase( + name="layout_extend_two_request_ragged", + backend="fa4", + forward_mode=ForwardMode.EXTEND, + num_heads=12, + num_kv_heads=12, + page_size=16, + prefix_lens=(8, 16), + extend_lens=(8, 16), + ), + DenseAttentionCase( + name="layout_decode_page_boundary", + backend="fa4", + forward_mode=ForwardMode.DECODE, + num_heads=12, + num_kv_heads=12, + page_size=16, + prefix_lens=(15, 16, 17), + ), + ) + LAYOUT_KNOWN_FAILURES = { + ("layout_extend_two_request_ragged", "non_monotonic_extend"): ( + "FA4 inherits FA3's prefill metadata assumption that " + "out_cache_loc is monotonic within an extend." + ), + } + + def test_layout_robustness_cases(self): + for case in self.LAYOUT_ROBUSTNESS_CASES: + # shuffled_pages is the default and already covered. + for layout in ( + "interleaved_pages", + "non_monotonic_extend", + ): + if layout == "non_monotonic_extend" and case.forward_mode.is_decode(): + continue + reason = self.LAYOUT_KNOWN_FAILURES.get((case.name, layout)) + if reason is not None: + print( + f"[layout-known-failure] {case.name} x {layout}: {reason}", + flush=True, + ) + continue + with self.subTest(case=case.name, layout=layout): + run_dense_attention_case( + self, + case, + head_dim=self.HEAD_DIM, + hidden_size=self.HIDDEN_SIZE, + loc_layout=layout, + ) + + def test_projected_dense_attention_cases(self): + for case in self.CASES: + with self.subTest(case=case.name, backend=case.backend): + run_dense_attention_case( + self, + case, + head_dim=self.HEAD_DIM, + hidden_size=self.HIDDEN_SIZE, + ) + + def test_runner_mode_cuda_graph_decode_cases(self): + for case in self.CUDA_GRAPH_CASES: + with self.subTest(case=case.name, backend=case.backend): + run_dense_cuda_graph_decode_case( + self, + case, + head_dim=self.HEAD_DIM, + hidden_size=self.HIDDEN_SIZE, + ) + + def test_runner_mode_split_op_extend_cases(self): + for case, static_num_tokens in self.SPLIT_OP_CASES: + for breakable in (False, True): + runner = "bcg" if breakable else "pcg" + with self.subTest( + case=case.name, + backend=case.backend, + runner=runner, + ): + run_dense_split_op_extend_case( + self, + case, + breakable=breakable, + static_num_tokens=static_num_tokens, + head_dim=self.HEAD_DIM, + hidden_size=self.HIDDEN_SIZE, + ) + + def test_runner_mode_eagle_draft_extend_v2_cuda_graph_cases(self): + for case in self.DRAFT_EXTEND_V2_CUDA_GRAPH_CASES: + for pad_style in ("small_real", "prod_fill"): + for capture_bs in ( + case.batch_size, + case.batch_size * 2, + case.batch_size * 4, + ): + with self.subTest( + case=case.name, + backend=case.backend, + pad_style=pad_style, + capture_bs=capture_bs, + ): + run_dense_draft_extend_v2_cuda_graph_case( + self, + case, + head_dim=self.HEAD_DIM, + hidden_size=self.HIDDEN_SIZE, + cuda_graph_capture_batch_size=capture_bs, + pad_style=pad_style, + ) + + def test_runner_mode_eagle_draft_extend_v2_cuda_graph_runner_cases(self): + for case in self.EAGLE_DRAFT_EXTEND_V2_RUNNER_CASES: + with self.subTest(case=case.name, backend=case.backend): + run_dense_eagle_draft_extend_v2_cuda_graph_runner_case( + self, + case, + head_dim=self.HEAD_DIM, + hidden_size=self.HIDDEN_SIZE, + ) + + def test_runner_mode_eagle_draft_cuda_graph_runner_cases(self): + for case, topk, num_draft_tokens in self.EAGLE_DRAFT_RUNNER_CASES: + with self.subTest(case=case.name, backend=case.backend, topk=topk): + run_dense_eagle_draft_cuda_graph_runner_case( + self, + case, + topk=topk, + speculative_num_draft_tokens=num_draft_tokens, + head_dim=self.HEAD_DIM, + hidden_size=self.HIDDEN_SIZE, + ) + + def test_runner_mode_frozen_kv_mtp_cuda_graph_runner_cases(self): + for case in self.FROZEN_KV_MTP_RUNNER_CASES: + with self.subTest(case=case.name, backend=case.backend): + run_dense_frozen_kv_mtp_cuda_graph_runner_case( + self, + case, + head_dim=self.HEAD_DIM, + hidden_size=self.HIDDEN_SIZE, + ) + + def test_runner_mode_spec_verify_cases(self): + for case, spec_kind in self.SPEC_VERIFY_CHAIN_CASES: + with self.subTest( + case=case.name, backend=case.backend, spec_kind=spec_kind + ): + run_dense_spec_verify_case( + self, + case, + topk=1, + spec_kind=spec_kind, + head_dim=self.HEAD_DIM, + hidden_size=self.HIDDEN_SIZE, + ) + + def test_runner_mode_spec_verify_cuda_graph_cases(self): + for case, spec_kind in self.SPEC_VERIFY_CHAIN_CUDA_GRAPH_CASES: + with self.subTest( + case=case.name, backend=case.backend, spec_kind=spec_kind + ): + run_dense_spec_verify_cuda_graph_case( + self, + case, + topk=1, + spec_kind=spec_kind, + head_dim=self.HEAD_DIM, + hidden_size=self.HIDDEN_SIZE, + ) + + +if __name__ == "__main__": + unittest.main() diff --git a/asian_ai/performance/SGLang/test/registered/attention/unittests/dense/test_flashinfer.py b/asian_ai/performance/SGLang/test/registered/attention/unittests/dense/test_flashinfer.py new file mode 100644 index 0000000000000000000000000000000000000000..f3a513818991fba12592842ccb0f0a5dd901f673 --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/attention/unittests/dense/test_flashinfer.py @@ -0,0 +1,429 @@ +import sys +import unittest +from pathlib import Path + +import torch + +from sglang.srt.model_executor.forward_batch_info import ForwardMode +from sglang.srt.utils import is_flashinfer_available +from sglang.test.test_utils import CustomTestCase + +sys.path.insert(0, str(Path(__file__).resolve().parents[1])) + +from sglang.test.ci.ci_register import register_cuda_ci +from sglang.test.kits.attention_unittest.attention_methods.dense_attention import ( + DenseAttentionCase, + make_dense_cases, + run_dense_attention_case, +) +from sglang.test.kits.attention_unittest.runner_modes.cuda_graph_decode_runner import ( + run_dense_cuda_graph_decode_case, +) +from sglang.test.kits.attention_unittest.runner_modes.speculative_draft_runner import ( + run_dense_eagle_draft_cuda_graph_runner_case, + run_dense_frozen_kv_mtp_cuda_graph_runner_case, +) +from sglang.test.kits.attention_unittest.runner_modes.speculative_target_verify_runner import ( + run_dense_spec_verify_case, + run_dense_spec_verify_cuda_graph_case, +) +from sglang.test.kits.attention_unittest.runner_modes.split_op_runner import ( + run_dense_split_op_extend_case, +) + +register_cuda_ci(est_time=25, stage="base-b", runner_config="4-gpu-b200") +register_cuda_ci(est_time=25, stage="base-b", runner_config="1-gpu-large") + + +@unittest.skipIf( + not torch.cuda.is_available() or not is_flashinfer_available(), + "CUDA + flashinfer are required", +) +class TestFlashInferDenseAttentionBackendCorrectness(CustomTestCase): + # FlashInfer SM90 prefill kernels require value head dim in {64, 128, 256}. + HEAD_DIM = 64 + HIDDEN_SIZE = 256 + + CASES = make_dense_cases("flashinfer") + CUDA_GRAPH_CASES = ( + DenseAttentionCase( + name="runner_cuda_graph_decode_page_boundary", + backend="flashinfer", + forward_mode=ForwardMode.DECODE, + num_heads=4, + num_kv_heads=4, + page_size=16, + prefix_lens=(14, 15, 16), + ), + DenseAttentionCase( + name="runner_cuda_graph_gqa_decode_page_boundary", + backend="flashinfer", + forward_mode=ForwardMode.DECODE, + num_heads=4, + num_kv_heads=2, + page_size=16, + prefix_lens=(14, 15, 16), + ), + DenseAttentionCase( + name="runner_cuda_graph_mqa_decode_bsz1", + backend="flashinfer", + forward_mode=ForwardMode.DECODE, + num_heads=4, + num_kv_heads=1, + page_size=16, + prefix_lens=(7,), + ), + ) + SPLIT_OP_CASES = ( + ( + DenseAttentionCase( + name="runner_split_op_mha_extend_ragged_page_boundary", + backend="flashinfer", + forward_mode=ForwardMode.EXTEND, + num_heads=4, + num_kv_heads=4, + page_size=16, + prefix_lens=(0, 8, 16), + extend_lens=(15, 8, 1), + ), + 32, + ), + ( + DenseAttentionCase( + name="runner_split_op_gqa_extend_cross_page_boundary", + backend="flashinfer", + forward_mode=ForwardMode.EXTEND, + num_heads=4, + num_kv_heads=2, + page_size=16, + prefix_lens=(15,), + extend_lens=(2,), + ), + 4, + ), + ) + SPEC_VERIFY_CASES = ( + ( + DenseAttentionCase( + name="runner_eagle_verify_chain", + backend="flashinfer", + forward_mode=ForwardMode.TARGET_VERIFY, + num_heads=4, + num_kv_heads=4, + page_size=16, + prefix_lens=(4, 7), + extend_lens=(3, 3), + ), + 1, + "eagle", + ), + ( + DenseAttentionCase( + name="runner_eagle_verify_tree", + backend="flashinfer", + forward_mode=ForwardMode.TARGET_VERIFY, + num_heads=4, + num_kv_heads=4, + page_size=16, + prefix_lens=(5, 6), + extend_lens=(3, 3), + ), + 2, + "eagle", + ), + ( + DenseAttentionCase( + name="runner_frozen_kv_mtp_verify_chain", + backend="flashinfer", + forward_mode=ForwardMode.TARGET_VERIFY, + num_heads=4, + num_kv_heads=4, + page_size=16, + prefix_lens=(4, 7), + extend_lens=(3, 3), + ), + 1, + "frozen_kv_mtp", + ), + ( + DenseAttentionCase( + name="runner_dflash_verify_chain", + backend="flashinfer", + forward_mode=ForwardMode.TARGET_VERIFY, + num_heads=4, + num_kv_heads=4, + page_size=16, + prefix_lens=(4, 7), + extend_lens=(3, 3), + ), + 1, + "dflash", + ), + ( + DenseAttentionCase( + name="runner_ngram_verify_chain", + backend="flashinfer", + forward_mode=ForwardMode.TARGET_VERIFY, + num_heads=4, + num_kv_heads=4, + page_size=16, + prefix_lens=(4, 7), + extend_lens=(3, 3), + ), + 1, + "ngram", + ), + ) + SPEC_VERIFY_CUDA_GRAPH_CASES = ( + ( + DenseAttentionCase( + name="runner_cuda_graph_eagle_verify_chain", + backend="flashinfer", + forward_mode=ForwardMode.TARGET_VERIFY, + num_heads=4, + num_kv_heads=4, + page_size=16, + prefix_lens=(4, 7), + extend_lens=(3, 3), + ), + 1, + "eagle", + ), + ( + DenseAttentionCase( + name="runner_cuda_graph_eagle_verify_tree", + backend="flashinfer", + forward_mode=ForwardMode.TARGET_VERIFY, + num_heads=4, + num_kv_heads=4, + page_size=16, + prefix_lens=(4, 7), + extend_lens=(3, 3), + ), + 2, + "eagle", + ), + ( + DenseAttentionCase( + name="runner_cuda_graph_frozen_kv_mtp_verify_chain", + backend="flashinfer", + forward_mode=ForwardMode.TARGET_VERIFY, + num_heads=4, + num_kv_heads=4, + page_size=16, + prefix_lens=(4, 7), + extend_lens=(3, 3), + ), + 1, + "frozen_kv_mtp", + ), + ( + DenseAttentionCase( + name="runner_cuda_graph_dflash_verify_chain", + backend="flashinfer", + forward_mode=ForwardMode.TARGET_VERIFY, + num_heads=4, + num_kv_heads=4, + page_size=16, + prefix_lens=(4, 7), + extend_lens=(3, 3), + ), + 1, + "dflash", + ), + ( + DenseAttentionCase( + name="runner_cuda_graph_ngram_verify_chain", + backend="flashinfer", + forward_mode=ForwardMode.TARGET_VERIFY, + num_heads=4, + num_kv_heads=4, + page_size=16, + prefix_lens=(4, 7), + extend_lens=(3, 3), + ), + 1, + "ngram", + ), + ) + EAGLE_DRAFT_RUNNER_CASES = ( + ( + DenseAttentionCase( + name="runner_eagle_draft_decode_cuda_graph_chain", + backend="flashinfer", + forward_mode=ForwardMode.DECODE, + num_heads=4, + num_kv_heads=4, + page_size=16, + prefix_lens=(4, 7), + ), + 1, + 3, + ), + ( + DenseAttentionCase( + name="runner_eagle_draft_decode_cuda_graph_tree", + backend="flashinfer", + forward_mode=ForwardMode.DECODE, + num_heads=4, + num_kv_heads=4, + page_size=1, + prefix_lens=(4, 7), + ), + 2, + 4, + ), + ) + FROZEN_KV_MTP_RUNNER_CASES = ( + DenseAttentionCase( + name="runner_frozen_kv_mtp_decode_cuda_graph_chain", + backend="flashinfer", + forward_mode=ForwardMode.DECODE, + num_heads=4, + num_kv_heads=4, + page_size=16, + prefix_lens=(4, 7), + ), + ) + + def test_projected_dense_attention_cases(self): + for case in self.CASES: + with self.subTest(case=case.name, backend=case.backend): + run_dense_attention_case( + self, + case, + head_dim=self.HEAD_DIM, + hidden_size=self.HIDDEN_SIZE, + ) + + # Layout-robustness: see dense/test_triton.py for full rationale. + # Re-runs a representative extend + decode under non-tidy + # (req_to_token, out_cache_loc) mappings to catch backend bugs in + # page-table derivation that the default contiguous layout hides. + LAYOUT_ROBUSTNESS_CASES = ( + DenseAttentionCase( + name="layout_extend_two_request_ragged", + backend="flashinfer", + forward_mode=ForwardMode.EXTEND, + num_heads=12, + num_kv_heads=12, + page_size=16, + prefix_lens=(8, 16), + extend_lens=(8, 16), + ), + DenseAttentionCase( + name="layout_decode_page_boundary", + backend="flashinfer", + forward_mode=ForwardMode.DECODE, + num_heads=12, + num_kv_heads=12, + page_size=16, + prefix_lens=(15, 16, 17), + ), + ) + + def test_layout_robustness_cases(self): + for case in self.LAYOUT_ROBUSTNESS_CASES: + # shuffled_pages is the default and already covered. + for layout in ( + "interleaved_pages", + "non_monotonic_extend", + ): + if layout == "non_monotonic_extend" and case.forward_mode.is_decode(): + continue + with self.subTest(case=case.name, layout=layout): + run_dense_attention_case( + self, + case, + head_dim=self.HEAD_DIM, + hidden_size=self.HIDDEN_SIZE, + loc_layout=layout, + ) + + def test_runner_mode_cuda_graph_decode_cases(self): + for case in self.CUDA_GRAPH_CASES: + with self.subTest(case=case.name, backend=case.backend): + run_dense_cuda_graph_decode_case( + self, + case, + head_dim=self.HEAD_DIM, + hidden_size=self.HIDDEN_SIZE, + ) + + def test_runner_mode_split_op_extend_cases(self): + for case, static_num_tokens in self.SPLIT_OP_CASES: + for breakable in (False, True): + runner = "bcg" if breakable else "pcg" + with self.subTest( + case=case.name, + backend=case.backend, + runner=runner, + ): + run_dense_split_op_extend_case( + self, + case, + breakable=breakable, + static_num_tokens=static_num_tokens, + head_dim=self.HEAD_DIM, + hidden_size=self.HIDDEN_SIZE, + ) + + def test_runner_mode_spec_verify_cases(self): + for case, topk, spec_kind in self.SPEC_VERIFY_CASES: + with self.subTest( + case=case.name, + backend=case.backend, + topk=topk, + spec_kind=spec_kind, + ): + run_dense_spec_verify_case( + self, + case, + topk=topk, + spec_kind=spec_kind, + head_dim=self.HEAD_DIM, + hidden_size=self.HIDDEN_SIZE, + ) + + def test_runner_mode_spec_verify_cuda_graph_cases(self): + for case, topk, spec_kind in self.SPEC_VERIFY_CUDA_GRAPH_CASES: + with self.subTest( + case=case.name, + backend=case.backend, + topk=topk, + spec_kind=spec_kind, + ): + run_dense_spec_verify_cuda_graph_case( + self, + case, + topk=topk, + spec_kind=spec_kind, + head_dim=self.HEAD_DIM, + hidden_size=self.HIDDEN_SIZE, + ) + + def test_runner_mode_eagle_draft_cuda_graph_runner_cases(self): + for case, topk, num_draft_tokens in self.EAGLE_DRAFT_RUNNER_CASES: + with self.subTest(case=case.name, backend=case.backend, topk=topk): + run_dense_eagle_draft_cuda_graph_runner_case( + self, + case, + topk=topk, + speculative_num_draft_tokens=num_draft_tokens, + head_dim=self.HEAD_DIM, + hidden_size=self.HIDDEN_SIZE, + ) + + def test_runner_mode_frozen_kv_mtp_cuda_graph_runner_cases(self): + for case in self.FROZEN_KV_MTP_RUNNER_CASES: + with self.subTest(case=case.name, backend=case.backend): + run_dense_frozen_kv_mtp_cuda_graph_runner_case( + self, + case, + head_dim=self.HEAD_DIM, + hidden_size=self.HIDDEN_SIZE, + ) + + +if __name__ == "__main__": + unittest.main() diff --git a/asian_ai/performance/SGLang/test/registered/attention/unittests/dense/test_flex_attention.py b/asian_ai/performance/SGLang/test/registered/attention/unittests/dense/test_flex_attention.py new file mode 100644 index 0000000000000000000000000000000000000000..ed8cadffbb63a4cc97b8bac2f4cdf55185252762 --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/attention/unittests/dense/test_flex_attention.py @@ -0,0 +1,118 @@ +import sys +import unittest +from pathlib import Path + +import torch + +from sglang.srt.model_executor.forward_batch_info import ForwardMode +from sglang.test.test_utils import CustomTestCase + +sys.path.insert(0, str(Path(__file__).resolve().parents[1])) + +from sglang.test.ci.ci_register import register_cuda_ci +from sglang.test.kits.attention_unittest.attention_methods.dense_attention import ( + DenseAttentionCase, + make_dense_cases, + run_dense_attention_case, +) +from sglang.test.kits.attention_unittest.runner_modes.split_op_runner import ( + run_dense_split_op_extend_case, +) + +register_cuda_ci(est_time=25, stage="base-b", runner_config="4-gpu-b200") +register_cuda_ci(est_time=25, stage="base-b", runner_config="1-gpu-large") + + +@unittest.skipIf(not torch.cuda.is_available(), "CUDA is required") +class TestFlexDenseAttentionBackendCorrectness(CustomTestCase): + CASES = make_dense_cases("flex_attention") + SPLIT_OP_CASES = ( + ( + DenseAttentionCase( + name="runner_split_op_mha_extend_ragged_page_boundary", + backend="flex_attention", + forward_mode=ForwardMode.EXTEND, + num_heads=4, + num_kv_heads=4, + page_size=16, + prefix_lens=(0, 8, 16), + extend_lens=(15, 8, 1), + ), + 32, + ), + ( + DenseAttentionCase( + name="runner_split_op_gqa_extend_cross_page_boundary", + backend="flex_attention", + forward_mode=ForwardMode.EXTEND, + num_heads=4, + num_kv_heads=2, + page_size=16, + prefix_lens=(15,), + extend_lens=(2,), + ), + 4, + ), + ) + + def test_projected_dense_attention_cases(self): + for case in self.CASES: + with self.subTest(case=case.name, backend=case.backend): + run_dense_attention_case(self, case) + + # Layout-robustness. See dense/test_triton.py for full rationale. + # Flex attention uses PyTorch flex_attention which builds the mask + # from logical positions, so it's robust to all non-tidy layouts. + LAYOUT_ROBUSTNESS_CASES = ( + DenseAttentionCase( + name="layout_extend_two_request_ragged", + backend="flex_attention", + forward_mode=ForwardMode.EXTEND, + num_heads=12, + num_kv_heads=12, + page_size=16, + prefix_lens=(8, 16), + extend_lens=(8, 16), + ), + DenseAttentionCase( + name="layout_decode_page_boundary", + backend="flex_attention", + forward_mode=ForwardMode.DECODE, + num_heads=12, + num_kv_heads=12, + page_size=16, + prefix_lens=(15, 16, 17), + ), + ) + + def test_layout_robustness_cases(self): + for case in self.LAYOUT_ROBUSTNESS_CASES: + # shuffled_pages is the default and already covered. + for layout in ( + "interleaved_pages", + "non_monotonic_extend", + ): + if layout == "non_monotonic_extend" and case.forward_mode.is_decode(): + continue + with self.subTest(case=case.name, layout=layout): + run_dense_attention_case(self, case, loc_layout=layout) + + def test_runner_mode_split_op_extend_cases(self): + for case, static_num_tokens in self.SPLIT_OP_CASES: + for breakable in (False, True): + runner = "bcg" if breakable else "pcg" + with self.subTest( + case=case.name, + backend=case.backend, + runner=runner, + ): + run_dense_split_op_extend_case( + self, + case, + breakable=breakable, + static_num_tokens=static_num_tokens, + ) + + +if __name__ == "__main__": + unittest.main() diff --git a/asian_ai/performance/SGLang/test/registered/attention/unittests/dense/test_hybrid_attn.py b/asian_ai/performance/SGLang/test/registered/attention/unittests/dense/test_hybrid_attn.py new file mode 100644 index 0000000000000000000000000000000000000000..c209dadd5d4acad765fce49f12bc480a918e4d34 --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/attention/unittests/dense/test_hybrid_attn.py @@ -0,0 +1,95 @@ +import sys +import unittest +from pathlib import Path + +import torch + +from sglang.srt.layers.attention.attention_registry import ATTENTION_BACKENDS +from sglang.srt.layers.attention.hybrid_attn_backend import HybridAttnBackend +from sglang.srt.model_executor.forward_batch_info import ForwardMode +from sglang.srt.utils import is_flashinfer_available +from sglang.test.test_utils import CustomTestCase + +sys.path.insert(0, str(Path(__file__).resolve().parents[1])) + +from sglang.test.ci.ci_register import register_cuda_ci +from sglang.test.kits.attention_unittest.attention_methods.dense_attention import ( + DENSE_ATOL, + DENSE_RTOL, + DenseAttentionCase, + build_dense_attention_fixture, + expected_dense_fixture_output, + replace_backend, + run_dense_fixture_eager, +) + +register_cuda_ci(est_time=20, stage="base-b", runner_config="4-gpu-b200") +register_cuda_ci(est_time=20, stage="base-b", runner_config="1-gpu-large") + + +@unittest.skipIf( + not torch.cuda.is_available() or not is_flashinfer_available(), + "CUDA + flashinfer are required", +) +class TestHybridAttnDenseAttentionBackendCorrectness(CustomTestCase): + """Compose HybridAttnBackend(prefill=triton, decode=flashinfer) and verify + dispatch produces the dense reference for both EXTEND and DECODE.""" + + # FlashInfer SM90 prefill kernels require value head dim in {64, 128, 256}. + HEAD_DIM = 64 + HIDDEN_SIZE = 256 + + EXTEND_CASE = DenseAttentionCase( + name="hybrid_extend_no_prefix", + backend="triton", + forward_mode=ForwardMode.EXTEND, + num_heads=4, + num_kv_heads=4, + page_size=16, + prefix_lens=(0,), + extend_lens=(16,), + ) + DECODE_CASE = DenseAttentionCase( + name="hybrid_decode_nonzero_prefix", + backend="flashinfer", + forward_mode=ForwardMode.DECODE, + num_heads=4, + num_kv_heads=4, + page_size=16, + prefix_lens=(7,), + ) + + def _build_and_wrap(self, case: DenseAttentionCase): + fixture = build_dense_attention_fixture( + self, + case, + head_dim=self.HEAD_DIM, + hidden_size=self.HIDDEN_SIZE, + ) + try: + prefill_backend = ATTENTION_BACKENDS["triton"](fixture.runner) + decode_backend = ATTENTION_BACKENDS["flashinfer"](fixture.runner) + except (AssertionError, ImportError, ModuleNotFoundError) as exc: + self.skipTest(f"hybrid_attn child backend unavailable: {exc}") + wrapper = HybridAttnBackend( + fixture.runner, + prefill_backend=prefill_backend, + decode_backend=decode_backend, + ) + return replace_backend(fixture, wrapper) + + def test_hybrid_extend_dispatches_prefill_backend(self): + fixture = self._build_and_wrap(self.EXTEND_CASE) + actual = run_dense_fixture_eager(fixture) + expected = expected_dense_fixture_output(fixture) + torch.testing.assert_close(actual, expected, atol=DENSE_ATOL, rtol=DENSE_RTOL) + + def test_hybrid_decode_dispatches_decode_backend(self): + fixture = self._build_and_wrap(self.DECODE_CASE) + actual = run_dense_fixture_eager(fixture) + expected = expected_dense_fixture_output(fixture) + torch.testing.assert_close(actual, expected, atol=DENSE_ATOL, rtol=DENSE_RTOL) + + +if __name__ == "__main__": + unittest.main() diff --git a/asian_ai/performance/SGLang/test/registered/attention/unittests/dense/test_tbo.py b/asian_ai/performance/SGLang/test/registered/attention/unittests/dense/test_tbo.py new file mode 100644 index 0000000000000000000000000000000000000000..7a58fa04d22ff51fe203e7d5fd580b4f6ed00739 --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/attention/unittests/dense/test_tbo.py @@ -0,0 +1,226 @@ +import sys +import unittest +from pathlib import Path + +import torch + +from sglang.srt.layers.attention.attention_registry import ATTENTION_BACKENDS +from sglang.srt.layers.attention.tbo_backend import TboAttnBackend +from sglang.srt.model_executor.forward_batch_info import ForwardMode +from sglang.srt.utils import get_device_sm +from sglang.test.test_utils import CustomTestCase + +sys.path.insert(0, str(Path(__file__).resolve().parents[1])) + +from sglang.test.ci.ci_register import register_cuda_ci +from sglang.test.kits.attention_unittest.attention_methods.dense_attention import ( + DENSE_ATOL, + DENSE_RTOL, + DenseAttentionCase, + build_dense_attention_fixture, + expected_dense_fixture_output, + replace_backend, + run_dense_fixture_eager, +) +from sglang.test.kits.attention_unittest.runner_modes.speculative_target_verify_runner import ( + _prepare_spec_verify_batch, +) + +register_cuda_ci(est_time=20, stage="base-b", runner_config="4-gpu-b200") +register_cuda_ci(est_time=20, stage="base-b", runner_config="1-gpu-large") + + +@unittest.skipIf(not torch.cuda.is_available(), "CUDA is required") +class TestTboAttnDenseAttentionBackendCorrectness(CustomTestCase): + """Compose TboAttnBackend(primary=triton, children=[triton, triton]) and + verify the eager dispatch matches the dense reference. + + The TBO wrapper only orchestrates two-batch splitting when + ``forward_batch.tbo_children`` is set (driven by the scheduler and CUDA + graph capture paths). Without children, ``init_forward_metadata`` and + ``forward`` delegate to ``self.primary``, so composition correctness is + what's covered here. Sub-batched orchestration through the TBO children + requires scheduler-level batch splitting and CUDA-graph helpers + (``two_batch_overlap.compute_split_indices_for_cuda_graph_replay``) that + aren't present in the unit fixture; that path stays for Phase 3 graph + expansion. + """ + + EXTEND_CASE = DenseAttentionCase( + name="tbo_extend_no_prefix", + backend="triton", + forward_mode=ForwardMode.EXTEND, + num_heads=4, + num_kv_heads=4, + page_size=16, + prefix_lens=(0,), + extend_lens=(16,), + ) + + # Mirrors ``runner_fa3_eagle_verify_chain`` in test_fa3.py — the smallest + # case shape that drives a real TARGET_VERIFY CUDA-graph capture through + # FlashAttention's per-bs metadata dicts. + TARGET_VERIFY_CAPTURE_CASE = DenseAttentionCase( + name="tbo_fa3_target_verify_chain_capture", + backend="fa3", + forward_mode=ForwardMode.TARGET_VERIFY, + num_heads=4, + num_kv_heads=4, + page_size=16, + prefix_lens=(4, 7), + extend_lens=(3, 3), + ) + + def _build_and_wrap(self, case: DenseAttentionCase): + fixture = build_dense_attention_fixture(self, case) + try: + primary = ATTENTION_BACKENDS[case.backend](fixture.runner) + children = [ + ATTENTION_BACKENDS[case.backend](fixture.runner) for _ in range(2) + ] + except (AssertionError, ImportError, ModuleNotFoundError) as exc: + self.skipTest(f"tbo child backend unavailable: {exc}") + wrapper = TboAttnBackend(primary=primary, children=children) + return replace_backend(fixture, wrapper) + + def test_tbo_extend_delegates_to_primary(self): + fixture = self._build_and_wrap(self.EXTEND_CASE) + actual = run_dense_fixture_eager(fixture) + expected = expected_dense_fixture_output(fixture) + torch.testing.assert_close(actual, expected, atol=DENSE_ATOL, rtol=DENSE_RTOL) + + @unittest.skipIf( + get_device_sm() >= 100 or get_device_sm() < 80, + "FA3 backend requires SM 80-90", + ) + def test_tbo_target_verify_cuda_graph_capture_delegates_to_primary_capture(self): + """TBO capture must dispatch primary's + ``init_forward_metadata_out_graph(fb, in_capture=True)`` (the capture + path), not the replay path. + + Backends like FlashAttention store per-bs metadata in dicts populated + only by the in_capture=True branch (via ``_bind_metadata_buffers``). + If TBO short-circuits its capture to its own replay path, those dicts + are empty and replay raises ``KeyError: bs``. Reproduces the + deepep-4-gpu-h100 failure where + ``flashattention_backend.target_verify_metadata[bs]`` lookup blew up + during ``init_device_graphs``. + + Asserts capture completes without raising — numerical correctness of + the captured graph is covered by per-backend spec-verify tests. + """ + case = self.TARGET_VERIFY_CAPTURE_CASE + fixture = self._build_and_wrap(case) + wrapper = fixture.backend + batch = fixture.forward_batch + + # Wire TARGET_VERIFY batch state + EAGLE chain (topk=1) spec_info, + # mirroring what the per-backend spec-verify runner sets up. + _prepare_spec_verify_batch( + case, + batch, + topk=1, + spec_kind="eagle", + device=str(batch.seq_lens.device), + ) + + capture_bs = case.batch_size + num_tokens = sum(case.extend_lens) + wrapper.init_cuda_graph_state(max_bs=capture_bs, max_num_tokens=num_tokens) + wrapper.init_forward_metadata_out_graph(batch, in_capture=True) + + @unittest.skipIf( + get_device_sm() >= 100 or get_device_sm() < 80, + "FA3 backend requires SM 80-90", + ) + def test_tbo_target_verify_cuda_graph_replay_splits_children(self): + """TBO replay must split the padded capture-time buffers into per-child + views before dispatching to ``init_forward_metadata_out_graph(fb_view, + in_capture=False)``. + + ``cuda_graph_runner.replay_prepare`` constructs a ``SimpleNamespace`` + fb_view via ``build_replay_fb_view`` — it has no ``tbo_children`` + attribute because ``tbo_plugin.replay_prepare`` does not call + ``prepare_raw``. Without the in-line split, TBO either crashes + (AttributeError on ``fb_view.tbo_children``) or silently leaves child + metadata stale. + + Asserts both children's ``init_forward_metadata_out_graph`` is invoked + with sliced ``req_pool_indices`` / ``seq_lens`` / ``seq_lens_cpu`` + whose lengths match the split derived from + ``compute_split_indices_for_cuda_graph_replay``. + """ + from types import SimpleNamespace + from unittest.mock import MagicMock + + from sglang.srt.batch_overlap.two_batch_overlap import ( + compute_split_indices_for_cuda_graph_replay, + ) + + case = self.TARGET_VERIFY_CAPTURE_CASE + fixture = self._build_and_wrap(case) + wrapper = fixture.backend + batch = fixture.forward_batch + _prepare_spec_verify_batch( + case, + batch, + topk=1, + spec_kind="eagle", + device=str(batch.seq_lens.device), + ) + + capture_bs = case.batch_size + num_tokens_per_bs = sum(case.extend_lens) // capture_bs + num_tokens = capture_bs * num_tokens_per_bs + split_seq_index, split_token_index = ( + compute_split_indices_for_cuda_graph_replay( + forward_mode=batch.forward_mode, + cuda_graph_num_tokens=num_tokens, + spec_info=batch.spec_info, + ) + ) + self.assertGreater(split_seq_index, 0) + self.assertLess(split_seq_index, capture_bs) + + # fb_view shaped like build_replay_fb_view's output: a SimpleNamespace + # with no tbo_children attribute. + fb_view = SimpleNamespace( + batch_size=capture_bs, + forward_mode=batch.forward_mode, + actual_forward_mode=batch.forward_mode, + input_ids=batch.input_ids, + req_pool_indices=batch.req_pool_indices, + seq_lens=batch.seq_lens, + seq_lens_sum=int(batch.seq_lens_cpu.sum()), + seq_lens_cpu=batch.seq_lens_cpu, + encoder_lens=None, + out_cache_loc=batch.out_cache_loc, + spec_info=batch.spec_info, + ) + + # Pure mocks (no `wraps=...`) so the dispatcher's slicing/contract is + # observed without invoking real backend bodies. + primary_mock = MagicMock() + child_mocks = [MagicMock(), MagicMock()] + wrapper.primary = primary_mock + wrapper.children = child_mocks + + wrapper.init_forward_metadata_out_graph(fb_view, in_capture=False) + + primary_mock.init_forward_metadata_out_graph.assert_called_once() + for child_mock in child_mocks: + child_mock.init_forward_metadata_out_graph.assert_called_once() + child_fbs = [ + m.init_forward_metadata_out_graph.call_args.kwargs["forward_batch"] + for m in child_mocks + ] + self.assertEqual(child_fbs[0].batch_size, split_seq_index) + self.assertEqual(child_fbs[1].batch_size, capture_bs - split_seq_index) + self.assertEqual(child_fbs[0].req_pool_indices.shape[0], split_seq_index) + self.assertEqual( + child_fbs[1].req_pool_indices.shape[0], capture_bs - split_seq_index + ) + + +if __name__ == "__main__": + unittest.main() diff --git a/asian_ai/performance/SGLang/test/registered/attention/unittests/dense/test_torch_native.py b/asian_ai/performance/SGLang/test/registered/attention/unittests/dense/test_torch_native.py new file mode 100644 index 0000000000000000000000000000000000000000..94c3cbf0b39871727ab250116cdffffbe0114c93 --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/attention/unittests/dense/test_torch_native.py @@ -0,0 +1,116 @@ +import sys +import unittest +from pathlib import Path + +import torch + +from sglang.srt.model_executor.forward_batch_info import ForwardMode +from sglang.test.test_utils import CustomTestCase + +sys.path.insert(0, str(Path(__file__).resolve().parents[1])) + +from sglang.test.ci.ci_register import register_amd_ci, register_cuda_ci +from sglang.test.kits.attention_unittest.attention_methods.dense_attention import ( + DenseAttentionCase, + make_dense_cases, + run_dense_attention_case, +) + +register_cuda_ci(est_time=20, stage="base-b", runner_config="4-gpu-b200") +register_cuda_ci(est_time=20, stage="base-b", runner_config="1-gpu-large") +register_amd_ci(est_time=20, suite="stage-b-test-1-gpu-large-amd") + + +@unittest.skipIf(not torch.cuda.is_available(), "CUDA is required") +class TestTorchNativeDenseAttentionBackendCorrectness(CustomTestCase): + CASES = make_dense_cases("torch_native") + RUNNER_EAGER_CASES = ( + DenseAttentionCase( + name="runner_eager_decode_page_boundary", + backend="torch_native", + forward_mode=ForwardMode.DECODE, + num_heads=4, + num_kv_heads=4, + page_size=16, + prefix_lens=(14, 15, 16), + ), + DenseAttentionCase( + name="runner_eager_extend_ragged_page_boundary", + backend="torch_native", + forward_mode=ForwardMode.EXTEND, + num_heads=4, + num_kv_heads=4, + page_size=16, + prefix_lens=(0, 8, 16), + extend_lens=(15, 8, 1), + ), + DenseAttentionCase( + name="runner_eager_gqa_decode_page_boundary", + backend="torch_native", + forward_mode=ForwardMode.DECODE, + num_heads=4, + num_kv_heads=2, + page_size=16, + prefix_lens=(14, 15, 16), + ), + DenseAttentionCase( + name="runner_eager_mqa_decode_bsz1", + backend="torch_native", + forward_mode=ForwardMode.DECODE, + num_heads=4, + num_kv_heads=1, + page_size=16, + prefix_lens=(7,), + ), + ) + + def test_projected_dense_attention_cases(self): + for case in self.CASES: + with self.subTest(case=case.name, backend=case.backend): + run_dense_attention_case(self, case) + + def test_runner_mode_eager_cases(self): + for case in self.RUNNER_EAGER_CASES: + with self.subTest(case=case.name, backend=case.backend): + run_dense_attention_case(self, case) + + # Layout-robustness. See dense/test_triton.py for full rationale. + # torch_native uses PyTorch SDPA on per-token-loc K/V gathered from + # the cache, so all non-tidy layouts pass. + LAYOUT_ROBUSTNESS_CASES = ( + DenseAttentionCase( + name="layout_extend_two_request_ragged", + backend="torch_native", + forward_mode=ForwardMode.EXTEND, + num_heads=12, + num_kv_heads=12, + page_size=16, + prefix_lens=(8, 16), + extend_lens=(8, 16), + ), + DenseAttentionCase( + name="layout_decode_page_boundary", + backend="torch_native", + forward_mode=ForwardMode.DECODE, + num_heads=12, + num_kv_heads=12, + page_size=16, + prefix_lens=(15, 16, 17), + ), + ) + + def test_layout_robustness_cases(self): + for case in self.LAYOUT_ROBUSTNESS_CASES: + # shuffled_pages is the default and already covered. + for layout in ( + "interleaved_pages", + "non_monotonic_extend", + ): + if layout == "non_monotonic_extend" and case.forward_mode.is_decode(): + continue + with self.subTest(case=case.name, layout=layout): + run_dense_attention_case(self, case, loc_layout=layout) + + +if __name__ == "__main__": + unittest.main() diff --git a/asian_ai/performance/SGLang/test/registered/attention/unittests/dense/test_triton.py b/asian_ai/performance/SGLang/test/registered/attention/unittests/dense/test_triton.py new file mode 100644 index 0000000000000000000000000000000000000000..902832724fe6fb929211f528311511fe236f97f1 --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/attention/unittests/dense/test_triton.py @@ -0,0 +1,467 @@ +import sys +import unittest +from pathlib import Path + +import torch + +from sglang.srt.model_executor.forward_batch_info import ForwardMode +from sglang.srt.utils import is_hip +from sglang.test.test_utils import CustomTestCase + +sys.path.insert(0, str(Path(__file__).resolve().parents[1])) + +from sglang.test.ci.ci_register import register_amd_ci, register_cuda_ci +from sglang.test.kits.attention_unittest.attention_methods.dense_attention import ( + DenseAttentionCase, + make_dense_cases, + run_dense_attention_case, +) +from sglang.test.kits.attention_unittest.runner_modes.cuda_graph_decode_runner import ( + run_dense_cuda_graph_decode_case, +) +from sglang.test.kits.attention_unittest.runner_modes.speculative_draft_extend_runner import ( + run_dense_draft_extend_v2_cuda_graph_case, + run_dense_eagle_draft_extend_v2_cuda_graph_runner_case, +) +from sglang.test.kits.attention_unittest.runner_modes.speculative_draft_runner import ( + run_dense_eagle_draft_cuda_graph_runner_case, + run_dense_frozen_kv_mtp_cuda_graph_runner_case, +) +from sglang.test.kits.attention_unittest.runner_modes.speculative_target_verify_runner import ( + run_dense_spec_verify_case, + run_dense_spec_verify_cuda_graph_case, +) +from sglang.test.kits.attention_unittest.runner_modes.split_op_runner import ( + run_dense_split_op_extend_case, +) + +register_cuda_ci(est_time=25, stage="base-b", runner_config="4-gpu-b200") +register_cuda_ci(est_time=25, stage="base-b", runner_config="1-gpu-large") +register_amd_ci(est_time=25, suite="stage-b-test-1-gpu-large-amd") + + +@unittest.skipIf(not torch.cuda.is_available(), "CUDA is required") +class TestTritonDenseAttentionBackendCorrectness(CustomTestCase): + CASES = make_dense_cases("triton") + CUDA_GRAPH_CASES = ( + DenseAttentionCase( + name="runner_cuda_graph_decode_page_boundary", + backend="triton", + forward_mode=ForwardMode.DECODE, + num_heads=4, + num_kv_heads=4, + page_size=16, + prefix_lens=(14, 15, 16), + ), + DenseAttentionCase( + name="runner_cuda_graph_gqa_decode_page_boundary", + backend="triton", + forward_mode=ForwardMode.DECODE, + num_heads=4, + num_kv_heads=2, + page_size=16, + prefix_lens=(14, 15, 16), + ), + DenseAttentionCase( + name="runner_cuda_graph_mqa_decode_bsz1", + backend="triton", + forward_mode=ForwardMode.DECODE, + num_heads=4, + num_kv_heads=1, + page_size=16, + prefix_lens=(7,), + ), + ) + SPLIT_OP_CASES = ( + ( + DenseAttentionCase( + name="runner_split_op_mha_extend_ragged_page_boundary", + backend="triton", + forward_mode=ForwardMode.EXTEND, + num_heads=4, + num_kv_heads=4, + page_size=16, + prefix_lens=(0, 8, 16), + extend_lens=(15, 8, 1), + ), + 32, + ), + ( + DenseAttentionCase( + name="runner_split_op_gqa_extend_cross_page_boundary", + backend="triton", + forward_mode=ForwardMode.EXTEND, + num_heads=4, + num_kv_heads=2, + page_size=16, + prefix_lens=(15,), + extend_lens=(2,), + ), + 4, + ), + ) + SPEC_VERIFY_CASES = ( + ( + DenseAttentionCase( + name="runner_eagle_verify_chain", + backend="triton", + forward_mode=ForwardMode.TARGET_VERIFY, + num_heads=4, + num_kv_heads=4, + page_size=16, + prefix_lens=(4, 7), + extend_lens=(3, 3), + ), + 1, + "eagle", + ), + ( + DenseAttentionCase( + name="runner_eagle_verify_tree", + backend="triton", + forward_mode=ForwardMode.TARGET_VERIFY, + num_heads=4, + num_kv_heads=4, + page_size=16, + prefix_lens=(5, 6), + extend_lens=(3, 3), + ), + 2, + "eagle", + ), + ( + DenseAttentionCase( + name="runner_frozen_kv_mtp_verify_chain", + backend="triton", + forward_mode=ForwardMode.TARGET_VERIFY, + num_heads=4, + num_kv_heads=4, + page_size=16, + prefix_lens=(4, 7), + extend_lens=(3, 3), + ), + 1, + "frozen_kv_mtp", + ), + ( + DenseAttentionCase( + name="runner_dflash_verify_chain", + backend="triton", + forward_mode=ForwardMode.TARGET_VERIFY, + num_heads=4, + num_kv_heads=4, + page_size=16, + prefix_lens=(4, 7), + extend_lens=(3, 3), + ), + 1, + "dflash", + ), + ( + DenseAttentionCase( + name="runner_ngram_verify_chain", + backend="triton", + forward_mode=ForwardMode.TARGET_VERIFY, + num_heads=4, + num_kv_heads=4, + page_size=16, + prefix_lens=(4, 7), + extend_lens=(3, 3), + ), + 1, + "ngram", + ), + ) + SPEC_VERIFY_CUDA_GRAPH_CASES = ( + ( + DenseAttentionCase( + name="runner_cuda_graph_eagle_verify_chain", + backend="triton", + forward_mode=ForwardMode.TARGET_VERIFY, + num_heads=4, + num_kv_heads=4, + page_size=16, + prefix_lens=(4, 7), + extend_lens=(3, 3), + ), + 1, + "eagle", + ), + ( + DenseAttentionCase( + name="runner_cuda_graph_eagle_verify_tree", + backend="triton", + forward_mode=ForwardMode.TARGET_VERIFY, + num_heads=4, + num_kv_heads=4, + page_size=16, + prefix_lens=(4, 7), + extend_lens=(3, 3), + ), + 2, + "eagle", + ), + ( + DenseAttentionCase( + name="runner_cuda_graph_frozen_kv_mtp_verify_chain", + backend="triton", + forward_mode=ForwardMode.TARGET_VERIFY, + num_heads=4, + num_kv_heads=4, + page_size=16, + prefix_lens=(4, 7), + extend_lens=(3, 3), + ), + 1, + "frozen_kv_mtp", + ), + ( + DenseAttentionCase( + name="runner_cuda_graph_dflash_verify_chain", + backend="triton", + forward_mode=ForwardMode.TARGET_VERIFY, + num_heads=4, + num_kv_heads=4, + page_size=16, + prefix_lens=(4, 7), + extend_lens=(3, 3), + ), + 1, + "dflash", + ), + ( + DenseAttentionCase( + name="runner_cuda_graph_ngram_verify_chain", + backend="triton", + forward_mode=ForwardMode.TARGET_VERIFY, + num_heads=4, + num_kv_heads=4, + page_size=16, + prefix_lens=(4, 7), + extend_lens=(3, 3), + ), + 1, + "ngram", + ), + ) + DRAFT_EXTEND_V2_CUDA_GRAPH_CASES = ( + DenseAttentionCase( + name="runner_cuda_graph_eagle_draft_extend_v2_fixed_tokens", + backend="triton", + forward_mode=ForwardMode.DRAFT_EXTEND_V2, + num_heads=4, + num_kv_heads=4, + page_size=16, + prefix_lens=(4, 7), + extend_lens=(3, 3), + ), + ) + EAGLE_DRAFT_EXTEND_V2_RUNNER_CASES = ( + DenseAttentionCase( + name="runner_eagle_draft_extend_v2_cuda_graph_runner_fixed_tokens", + backend="triton", + forward_mode=ForwardMode.DRAFT_EXTEND_V2, + num_heads=4, + num_kv_heads=4, + page_size=16, + prefix_lens=(4, 7), + extend_lens=(3, 3), + ), + ) + EAGLE_DRAFT_RUNNER_CASES = ( + ( + DenseAttentionCase( + name="runner_eagle_draft_decode_cuda_graph_chain", + backend="triton", + forward_mode=ForwardMode.DECODE, + num_heads=4, + num_kv_heads=4, + page_size=16, + prefix_lens=(4, 7), + ), + 1, + 3, + ), + ( + DenseAttentionCase( + name="runner_eagle_draft_decode_cuda_graph_tree", + backend="triton", + forward_mode=ForwardMode.DECODE, + num_heads=4, + num_kv_heads=4, + page_size=1, + prefix_lens=(4, 7), + ), + 2, + 4, + ), + ) + FROZEN_KV_MTP_RUNNER_CASES = ( + DenseAttentionCase( + name="runner_frozen_kv_mtp_decode_cuda_graph", + backend="triton", + forward_mode=ForwardMode.DECODE, + num_heads=4, + num_kv_heads=4, + page_size=16, + prefix_lens=(4, 7), + ), + ) + + def test_projected_dense_attention_cases(self): + for case in self.CASES: + with self.subTest(case=case.name, backend=case.backend): + run_dense_attention_case(self, case) + + # Layout-robustness: re-run a representative extend + decode under + # non-tidy `(req_to_token, out_cache_loc)` mappings. The fixture's + # default contiguous layout uses + # `_token_loc(req_idx, pos) = page_size + req_idx * max_ctx + pos`, + # which is affine in `pos` — it hides any backend bug that assumes + # `out_cache_loc` is monotonic within a request, or that a request's + # pages occupy a contiguous physical range. Production allocators + # routinely produce non-tidy `out_cache_loc` after fragmentation, + # so these layouts catch a class of metadata-derivation bugs the + # default layout doesn't exercise. The reference doesn't change — + # it computes attention from projected Q/K/V directly without + # reading the cache. + LAYOUT_ROBUSTNESS_CASES = ( + DenseAttentionCase( + name="layout_extend_two_request_ragged", + backend="triton", + forward_mode=ForwardMode.EXTEND, + num_heads=12, + num_kv_heads=12, + page_size=16, + prefix_lens=(8, 16), + extend_lens=(8, 16), + ), + DenseAttentionCase( + name="layout_decode_page_boundary", + backend="triton", + forward_mode=ForwardMode.DECODE, + num_heads=12, + num_kv_heads=12, + page_size=16, + prefix_lens=(15, 16, 17), + ), + ) + + def test_layout_robustness_cases(self): + for case in self.LAYOUT_ROBUSTNESS_CASES: + # shuffled_pages is the default for all tests now, so it's + # already covered by `test_projected_dense_attention_cases`. + # The opt-in matrix here exercises the more aggressive + # interleaved_pages + non_monotonic_extend layouts. + for layout in ( + "interleaved_pages", + "non_monotonic_extend", + ): + if layout == "non_monotonic_extend" and case.forward_mode.is_decode(): + # decode has no extend tokens to scatter + continue + with self.subTest(case=case.name, layout=layout): + run_dense_attention_case(self, case, loc_layout=layout) + + def test_runner_mode_cuda_graph_decode_cases(self): + for case in self.CUDA_GRAPH_CASES: + with self.subTest(case=case.name, backend=case.backend): + run_dense_cuda_graph_decode_case(self, case) + + @unittest.skipIf( + is_hip(), + "split-op extend runner exercises the piecewise-CUDA-graph path " + "(TcPiecewiseForwardContext.num_tokens), which is not wired on ROCm.", + ) + def test_runner_mode_split_op_extend_cases(self): + for case, static_num_tokens in self.SPLIT_OP_CASES: + for breakable in (False, True): + runner = "bcg" if breakable else "pcg" + with self.subTest( + case=case.name, + backend=case.backend, + runner=runner, + ): + run_dense_split_op_extend_case( + self, + case, + breakable=breakable, + static_num_tokens=static_num_tokens, + ) + + def test_runner_mode_spec_verify_cases(self): + for case, topk, spec_kind in self.SPEC_VERIFY_CASES: + with self.subTest( + case=case.name, + backend=case.backend, + topk=topk, + spec_kind=spec_kind, + ): + run_dense_spec_verify_case( + self, + case, + topk=topk, + spec_kind=spec_kind, + ) + + def test_runner_mode_spec_verify_cuda_graph_cases(self): + for case, topk, spec_kind in self.SPEC_VERIFY_CUDA_GRAPH_CASES: + with self.subTest( + case=case.name, + backend=case.backend, + topk=topk, + spec_kind=spec_kind, + ): + run_dense_spec_verify_cuda_graph_case( + self, + case, + topk=topk, + spec_kind=spec_kind, + ) + + def test_runner_mode_eagle_draft_extend_v2_cuda_graph_cases(self): + # pad_ratio is expressed as the captured batch size relative to the + # case's real batch size: 1.0x = no padding, 2.0x = 50% padded, etc. + for case in self.DRAFT_EXTEND_V2_CUDA_GRAPH_CASES: + for pad_style in ("small_real", "prod_fill"): + for capture_bs in ( + case.batch_size, + case.batch_size * 2, + case.batch_size * 4, + ): + with self.subTest( + case=case.name, + backend=case.backend, + pad_style=pad_style, + capture_bs=capture_bs, + ): + run_dense_draft_extend_v2_cuda_graph_case( + self, + case, + cuda_graph_capture_batch_size=capture_bs, + pad_style=pad_style, + ) + + def test_runner_mode_eagle_draft_extend_v2_cuda_graph_runner_cases(self): + for case in self.EAGLE_DRAFT_EXTEND_V2_RUNNER_CASES: + with self.subTest(case=case.name, backend=case.backend): + run_dense_eagle_draft_extend_v2_cuda_graph_runner_case(self, case) + + def test_runner_mode_eagle_draft_cuda_graph_runner_cases(self): + for case, topk, num_draft_tokens in self.EAGLE_DRAFT_RUNNER_CASES: + with self.subTest(case=case.name, backend=case.backend, topk=topk): + run_dense_eagle_draft_cuda_graph_runner_case( + self, + case, + topk=topk, + speculative_num_draft_tokens=num_draft_tokens, + ) + + def test_runner_mode_frozen_kv_mtp_cuda_graph_runner_cases(self): + for case in self.FROZEN_KV_MTP_RUNNER_CASES: + with self.subTest(case=case.name, backend=case.backend): + run_dense_frozen_kv_mtp_cuda_graph_runner_case(self, case) + + +if __name__ == "__main__": + unittest.main() diff --git a/asian_ai/performance/SGLang/test/registered/attention/unittests/dense/test_trtllm_mha.py b/asian_ai/performance/SGLang/test/registered/attention/unittests/dense/test_trtllm_mha.py new file mode 100644 index 0000000000000000000000000000000000000000..8bf4a617ad41eaebb0e4f70e21467f7276fdc6db --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/attention/unittests/dense/test_trtllm_mha.py @@ -0,0 +1,180 @@ +import sys +import unittest +from pathlib import Path + +import torch + +from sglang.srt.model_executor.forward_batch_info import ForwardMode +from sglang.srt.utils import is_flashinfer_available +from sglang.srt.utils.common import is_sm90_supported, is_sm120_supported +from sglang.test.test_utils import CustomTestCase + +sys.path.insert(0, str(Path(__file__).resolve().parents[1])) + +from sglang.test.ci.ci_register import register_cuda_ci +from sglang.test.kits.attention_unittest.attention_methods.dense_attention import ( + DenseAttentionCase, + run_dense_attention_case, +) +from sglang.test.kits.attention_unittest.runner_modes.cuda_graph_decode_runner import ( + run_dense_cuda_graph_decode_case, +) +from sglang.test.kits.attention_unittest.runner_modes.speculative_draft_runner import ( + run_dense_eagle_draft_cuda_graph_runner_case, +) + +register_cuda_ci(est_time=20, stage="base-b", runner_config="4-gpu-b200") +register_cuda_ci(est_time=20, stage="base-b", runner_config="1-gpu-large") + + +@unittest.skipIf( + not torch.cuda.is_available() + or not is_flashinfer_available() + or not (is_sm90_supported() or is_sm120_supported()), + "CUDA + FlashInfer TRT-LLM MHA decode support are required", +) +class TestTRTLLMMHADenseAttentionBackendCorrectness(CustomTestCase): + HEAD_DIM = 64 + HIDDEN_SIZE = 256 + + DECODE_CASES = ( + DenseAttentionCase( + name="trtllm_mha_decode_page_boundary", + backend="trtllm_mha", + forward_mode=ForwardMode.DECODE, + num_heads=4, + num_kv_heads=4, + page_size=16, + prefix_lens=(14, 15, 16), + ), + DenseAttentionCase( + name="trtllm_mha_gqa_decode_page_boundary", + backend="trtllm_mha", + forward_mode=ForwardMode.DECODE, + num_heads=4, + num_kv_heads=2, + page_size=16, + prefix_lens=(14, 15, 16), + ), + DenseAttentionCase( + name="trtllm_mha_mqa_decode_bsz1", + backend="trtllm_mha", + forward_mode=ForwardMode.DECODE, + num_heads=4, + num_kv_heads=1, + page_size=16, + prefix_lens=(7,), + ), + DenseAttentionCase( + name="trtllm_mha_decode_page32_boundary", + backend="trtllm_mha", + forward_mode=ForwardMode.DECODE, + num_heads=4, + num_kv_heads=4, + page_size=32, + prefix_lens=(31, 32), + ), + ) + + # CG decode replay across MHA/GQA/MQA layouts and a page-32 case. + # Previously documented as "currently mismatches on replay"; the + # FlashInfer TRT-LLM Gen FMHA decode backend has since stabilized + # the capture/replay metadata path and all four shapes match the + # HF-style dense reference. + CUDA_GRAPH_DECODE_CASES = ( + DenseAttentionCase( + name="runner_cuda_graph_trtllm_mha_decode_page_boundary", + backend="trtllm_mha", + forward_mode=ForwardMode.DECODE, + num_heads=4, + num_kv_heads=4, + page_size=16, + prefix_lens=(14, 15, 16), + ), + DenseAttentionCase( + name="runner_cuda_graph_trtllm_mha_gqa_decode_page_boundary", + backend="trtllm_mha", + forward_mode=ForwardMode.DECODE, + num_heads=4, + num_kv_heads=2, + page_size=16, + prefix_lens=(14, 15, 16), + ), + DenseAttentionCase( + name="runner_cuda_graph_trtllm_mha_mqa_decode_bsz1", + backend="trtllm_mha", + forward_mode=ForwardMode.DECODE, + num_heads=4, + num_kv_heads=1, + page_size=16, + prefix_lens=(7,), + ), + DenseAttentionCase( + name="runner_cuda_graph_trtllm_mha_decode_page32_boundary", + backend="trtllm_mha", + forward_mode=ForwardMode.DECODE, + num_heads=4, + num_kv_heads=4, + page_size=32, + prefix_lens=(31, 32), + ), + ) + + # EAGLE draft CG runner — chain only (topk=1). trtllm_mha is constrained + # to topk=1 via `trtllm_mha_backend.py:459,492` so tree-mode tests don't + # apply. This test exercises the draft-decode CG capture/replay path + # (`init_forward_metadata_capture_cuda_graph` line 320 and + # `init_forward_metadata_replay_cuda_graph` line 460) — the same path + # patched by PR #26521 (capture-time NaN fix) and PR #26655 (replay-time + # slice rebind). + EAGLE_DRAFT_RUNNER_CASES = ( + ( + DenseAttentionCase( + name="runner_eagle_draft_decode_trtllm_mha_cuda_graph_chain", + backend="trtllm_mha", + forward_mode=ForwardMode.DECODE, + num_heads=4, + num_kv_heads=4, + page_size=16, + prefix_lens=(4, 7), + ), + 1, # topk + 3, # num_draft_tokens + ), + ) + + def test_projected_dense_decode_cases(self): + for case in self.DECODE_CASES: + with self.subTest(case=case.name, backend=case.backend): + run_dense_attention_case( + self, + case, + head_dim=self.HEAD_DIM, + hidden_size=self.HIDDEN_SIZE, + ) + + def test_runner_mode_cuda_graph_decode_cases(self): + for case in self.CUDA_GRAPH_DECODE_CASES: + with self.subTest(case=case.name, backend=case.backend): + run_dense_cuda_graph_decode_case( + self, + case, + head_dim=self.HEAD_DIM, + hidden_size=self.HIDDEN_SIZE, + ) + + def test_runner_mode_eagle_draft_cuda_graph_runner_cases(self): + for case, topk, num_draft_tokens in self.EAGLE_DRAFT_RUNNER_CASES: + with self.subTest(case=case.name, backend=case.backend, topk=topk): + run_dense_eagle_draft_cuda_graph_runner_case( + self, + case, + topk=topk, + speculative_num_draft_tokens=num_draft_tokens, + head_dim=self.HEAD_DIM, + hidden_size=self.HIDDEN_SIZE, + ) + + +if __name__ == "__main__": + unittest.main() diff --git a/asian_ai/performance/SGLang/test/registered/attention/unittests/dsa/README.md b/asian_ai/performance/SGLang/test/registered/attention/unittests/dsa/README.md new file mode 100644 index 0000000000000000000000000000000000000000..aaa616a836a8008e8dff46229c50e82b107287c4 --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/attention/unittests/dsa/README.md @@ -0,0 +1,151 @@ +# DSA Attention Capability Matrix + +This folder tracks DeepSeek Sparse Attention style unit tests. The existing +registered/model tests exercise DSA at a higher level; this unit matrix covers +small deterministic backend slices with independent PyTorch references. + +## Coverage Matrix + +Columns are runner modes; rows are the two DSA sub-paths exercised through the +`dsa` backend (selection is by case shape, not backend choice). Cells use: +- **✓ \** — exercised, with the config variants listed in the cell +- **—** — not applicable / not exercised +- **blocked: \** — production-unsupported, not a follow-up +- **deferred: \** — could land later, currently disabled + +| DSA sub-path | Eager Phase 2 | CG decode | PCG extend | BCG extend | Verify eager | Verify CG | DE eager | DE CG | DE-V2 CG | EAGLE-draft runner | EAGLE-DE runner | FKVMTP runner | +|---|---|---|---|---|---|---|---|---|---|---|---|---| +| `dsa` MHA_ONE_SHOT dense prefill fallback | ✓ 8 dense-fallback extend layouts: no-prefix ragged, no-prefix exact-page, no-prefix seq-below-page, prefix ragged, cross-page-boundary, prefix-exact-page, total-exact-page, ragged below/at/above page | deferred: graph metadata parity not scoped | blocked: K-slice mismatch | blocked | — | — | — | — | — | — | — | — | +| `dsa` sparse top-k (`flashmla_sparse` prefill + `flashmla_kv` decode) | ✓ 7 sparse top-k layouts: long-prefix bsz=1 prefill, long-prefix multi-token prefill, multi-request long-prefix prefill, decode with bsz=2 trailing-topk, decode with sub-topk prefix padding, ragged 3-request decode, long-prefix decode | ✓ flashmla_kv + FP8 flashmla_kv | — | — | ✓ TARGET_VERIFY eager | — | ✓ DRAFT_EXTEND eager | — | ✓ DRAFT_EXTEND_V2 eager | — | — | — | + +## Implementation Variant Matrix (`--dsa-prefill-backend` / `--dsa-decode-backend`) + +DSA has multiple kernel impls; `dsa_impl_capability(impl)` gates each per +hardware/SDK. The variant tests live in `test_dsa.py` as +`test_sparse_prefill_impl_variants`, `test_sparse_decode_impl_variants`, and +`test_sparse_cuda_graph_decode_impl_variants`. + +| Impl | Prefill | Decode | CG decode | Hardware gate (test box: H200 SM9.0) | +|---|---|---|---|---| +| `flashmla_sparse` | ✓ | ✓ | ✓ | SM>=9.0 + `sgl_kernel.flash_mla` | +| `flashmla_kv` | ✓ | ✓ | ✓ | SM>=9.0 + `sgl_kernel.flash_mla` | +| `fa3` | ✓ | ✓ | ✓ | SM>=9.0 + `sglang.jit_kernel.flash_attention` | +| `tilelang` | ✓ (topk=2048 dedicated fixture) | ✓ (topk=2048 dedicated fixture) | skipped: not yet wired into CG runner | `tilelang_sparse_fwd` asserts `topk == 2048`; the topk=2048 fixture instance (`build_dsa_sparse_attention_fixture(..., index_topk=2048)`) is used by `test_sparse_tilelang_prefill_case` / `test_sparse_tilelang_decode_case`. The default-topk impl-variant matrix still skips tilelang with the same reason. **SM10.x container gate**: on Blackwell the tilelang JIT generates `wait_wgmma` which the container's MMA template doesn't ship (`KNOWN_FAILURES.md §2`); `dsa_impl_capability("tilelang")` skips on `major >= 10`. Set `SGLANG_TEST_DSA_TILELANG_FORCE=1` to override after re-imaging. | +| `trtllm` | skipped: SM<10 | skipped: SM<10 | skipped: SM<10 | TRT-LLM Gen FMHA/MLA requires Blackwell (SM>=10.0). | +| `aiter` | skipped: not HIP | skipped: not HIP | skipped: not HIP | AMD-only kernel library. | +| `flashmla_auto` (default) | ✓ (resolves to `flashmla_sparse` for bf16, `flashmla_kv` for FP8) | ✓ | ✓ | covered indirectly by all sparse cases | + +## Input And Config Coverage + +- DSA page-size-64 extend and decode batches. +- Dense fallback: no-prefix ragged, no-prefix exact-page, no-prefix + seq-below-page (seq_len=63), prefix ragged, cross-page-boundary + (seq_len=65), prefix-exact-page, total-exact-page, and a ragged batch + whose three requests span below / exactly at / above the page boundary + (seq_lens=63/64/65). Together these cover the PLAN.md "Required input + cases" page-boundary partition (seq_len < page, == page, > page). Page + size 1 is `blocked` here — DSA's CUDA indexer hard-asserts + `page_size == 64` (`dsa/dsa_indexer.py:550, 727, 946, 1095`). +- Sparse top-k: uses `qk_nope=512`, `qk_rope=64`, and `topk=128` to match local + FlashMLA kernel constraints. +- Sparse prefill spans single-request, multi-token extend, and multi-request + long-prefix layouts above the dense one-shot threshold so the backend selects + `flashmla_sparse`. +- Sparse decode spans (key_count < topk), (key_count == topk), and + (key_count >> topk) so the per-request topk slicing varies, plus long-prefix + decode that walks the trailing topk window deep into the KV cache. + +## Production-Unsupported + +- **Page size other than 1 (HIP legacy) or 64 (CUDA)** — the DSA indexer + hard-asserts the page size: HIP legacy at `dsa/dsa_indexer.py:547-548, + 724-725` (`assert page_size == 1`); CUDA at `dsa/dsa_indexer.py:550, 727, + 946, 1095` and `dsa/index_buf_accessor.py:436` (`assert page_size == 64`). + The `dsa/transform_index.py:53, 79, 100, 121` helpers also assert + `page_size == 1`. +- **`Unsupported {forward_batch.forward_mode=}`** — `forward_extend` + fall-through asserts `False` (`dsa_backend.py:629`) for anything not in + `is_decode_or_idle` / `is_extend()` (incl. `MIXED`, `DRAFT_EXTEND`, + `TARGET_VERIFY`, `SPLIT_PREFILL`, `DLLM_EXTEND`) / `is_draft_extend(include_v2=True)`. +- **PCG/BCG split-op extend on the MHA_ONE_SHOT dense fallback path** — + structurally incompatible with `unified_attention_with_output`. DSA's + dense fallback passes K as concatenated `prefix + extend` (shape + `[sum(seq_lens), num_kv_heads, head_dim]`) to `module.attn(q, k, v, + forward_batch, save_kv_cache=False)`, but `unified_attention_with_output` + (`radix_attention.py:170-208`, which RadixAttention routes to under + piecewise CG) slices K to `forward_batch.num_token_non_padded_cpu` (= + live extend-token count) on the per-token K convention used by + Triton/FlashInfer/FA. The slice removes the prefix portion, so a + piecewise CG run diverges from the eager DSA dense fallback by ~50% + mismatch (~0.35 max diff) vs the HF reference. Unblocking needs + either (a) the DSA dense fallback rewritten to write K to cache + (`save_kv_cache=True`) and pass extend-only K to `module.attn` (so + the slicing is a no-op), or (b) a backend-hint on `RadixAttention` to + skip the K-slice when the kernel expects prefix-concatenated K. + +## Required Fixture Work + +- Extend the sparse reference to additional block/index layouts that diverge + from the trailing-`topk` row builder (e.g., non-trailing or interleaved + index patterns). +- Decide hardware gates for TileLang / FA / FlashMLA-sparse paths before + enabling default tests. +- Runner-mode integration is now plumbed at the fixture level: + `DSAMockModelRunner` accepts `disable_cuda_graph`, + `disable_piecewise_cuda_graph`, and `runner_batch_size` kwargs; + `build_dsa_attention_fixture` passes them through; and + `dsa_attention.py` exposes the standard adapter callbacks + (`make_dsa_case_with_prefix_lens`, `dsa_fixture_inputs`, + `make_dsa_random_inputs`, `make_dsa_token_padded_inputs`, + `prepare_dsa_runner_inputs`, `run_dsa_forward`, + `expected_dsa_output_from_inputs`, `dsa_attention_layers`, + `_clone_dsa_cache`, `_restore_dsa_cache`). The dense fallback path + still can't actually exercise piecewise CG (see + "Production-Unsupported"); CG decode through the sparse fixture is + the natural next target once the sparse-fixture topk-indices + threading is added to the adapter contract. + +## Next Work + +- **HiSparse coordinator path (genuine follow-up — needs HiSparse infra)** — + `set_dsa_prefill_impl` forces `use_mha=False` when + `self.hisparse_coordinator is not None`; the fixture sets it to `None`. + Wiring HiSparse coverage would exercise `_forward_flashmla_kv`'s + `translate_loc_to_hisparse_device` branch and `swap_in_selected_pages` + during decode. This needs a real `HiSparseCoordinator` instance — a + production-side singleton owned by the model runner, not a single flag. + Building a unit-fixture version requires either: + 1. **Mock the coordinator** — supply a tiny stand-in object that + exposes the methods the DSA backend calls + (`translate_loc_to_hisparse_device`, `swap_in_selected_pages`, + `selected_pages`, etc.). The mock must produce page mappings the + existing `DSATokenToKVPool` honors, which means mirroring the + production page-table contract. Deferred — the contract changes + fast enough that a stable mock isn't cheap. + 2. **Bring up a real HiSparse coordinator in the fixture** — requires + loading the HiSparse memory layout, allocating the swap-in/swap-out + page tables, and wiring page-eviction policy. Out of scope for + module-level unit tests. +- **Non-trailing index layouts**: `_make_dsa_sparse_topk_rows` now + supports `pattern in {"trailing", "strided", "head_tail"}` and the + fixture+runner thread `index_pattern` through. `test_sparse_topk_cases` + keeps the trailing default; `test_sparse_non_trailing_index_cases` + exercises strided + head_tail on a long-prefix decode. The reference + gathers via `fixture.topk_rows`, so any valid permutation of keys in + `[0, key_count)` produces a matching reference. + +## Production Runner Integration + +- **DSA EAGLE draft CUDA-graph runner**: wired via the shared + `EagleDraftCudaGraphRunnerAdapter`. Chain-only (topk=1). + `_DSAEagleDraftForward.__call__` synthesizes `topk_indices` on-GPU + (trailing-topk in token-position space) since production gets them + from the DSA indexer that's outside attention. Tree draft requires + parent-indices plumbing through the topk_indices synthesis and is + deferred. +- **DSA EAGLE draft-extend CUDA-graph runner**: wired via the shared + `EagleDraftExtendCudaGraphRunnerAdapter`. Multi-query-per-request, + routes through `forward_extend` with the `is_draft_extend(include_v2)` + branch selecting `dsa_decode_impl`. `_DSAEagleDraftExtendForward` + uses `batch.positions` (not `batch.seq_lens`) to compute per-token + trailing-topk indices. Chain-only. diff --git a/asian_ai/performance/SGLang/test/registered/attention/unittests/dsa/__init__.py b/asian_ai/performance/SGLang/test/registered/attention/unittests/dsa/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..f75516e900679ec9452725c092b2859a4b7e2f46 --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/attention/unittests/dsa/__init__.py @@ -0,0 +1 @@ +"""DSA attention unit-test package.""" diff --git a/asian_ai/performance/SGLang/test/registered/attention/unittests/dsa/test_dsa.py b/asian_ai/performance/SGLang/test/registered/attention/unittests/dsa/test_dsa.py new file mode 100644 index 0000000000000000000000000000000000000000..51dda95d710f89097f7ddece302cc1a41bfe5b85 --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/attention/unittests/dsa/test_dsa.py @@ -0,0 +1,405 @@ +import sys +import unittest +from pathlib import Path + +import torch + +from sglang.srt.model_executor.forward_batch_info import ForwardMode +from sglang.test.test_utils import CustomTestCase + +sys.path.insert(0, str(Path(__file__).resolve().parents[1])) + +from sglang.test.ci.ci_register import register_cuda_ci +from sglang.test.kits.attention_unittest.attention_methods.dsa_attention import ( + DSA_DECODE_IMPL_VARIANTS, + DSA_PAGE_SIZE, + DSA_PREFILL_IMPL_VARIANTS, + DSAAttentionCase, + make_dsa_dense_fallback_cases, + make_dsa_sparse_cases, + run_dsa_attention_case, + run_dsa_sparse_attention_case, + run_dsa_sparse_cuda_graph_decode_impl_variant_case, + run_dsa_sparse_decode_impl_variant_case, + run_dsa_sparse_fp8_decode_case, + run_dsa_sparse_fp8_prefill_case, + run_dsa_sparse_prefill_impl_variant_case, + run_dsa_sparse_speculative_forward_mode_case, + run_dsa_sparse_tilelang_decode_case, + run_dsa_sparse_tilelang_prefill_case, +) +from sglang.test.kits.attention_unittest.runner_modes.cuda_graph_decode_runner import ( + run_dsa_sparse_cuda_graph_decode_case, +) +from sglang.test.kits.attention_unittest.runner_modes.speculative_draft_runner import ( + run_dsa_eagle_draft_cuda_graph_runner_case, +) + +register_cuda_ci(est_time=25, stage="base-b", runner_config="4-gpu-b200") +register_cuda_ci(est_time=25, stage="base-b", runner_config="1-gpu-large") + + +@unittest.skipIf(not torch.cuda.is_available(), "CUDA is required") +class TestDSAAttentionBackendCorrectness(CustomTestCase): + CASES = make_dsa_dense_fallback_cases("dsa") + SPARSE_CASES = make_dsa_sparse_cases("dsa") + # PCG/BCG split-op extend coverage is *not* added here — DSA's + # MHA_ONE_SHOT dense fallback passes K as concatenated prefix+extend + # (length = sum(seq_lens)) to `module.attn`, but + # `unified_attention_with_output` (`radix_attention.py:170-208`) slices + # K to `forward_batch.num_token_non_padded_cpu` (= live extend-token + # count), under the per-token K convention used by Triton/FlashInfer/ + # FA. The K-slice removes the prefix portion, so DSA's dense fallback + # output diverges by ~50% mismatch under piecewise CG. See + # dsa/README.md "Production-Unsupported" for the path forward. + + def test_mha_one_shot_dense_fallback_cases(self): + for case in self.CASES: + with self.subTest(case=case.name, backend=case.backend): + # GB300 (SM10.x) kernel requires 128-dim query/value; + # use head_dim=128 rather than the generic DEFAULT_HEAD_DIM=16. + run_dsa_attention_case(self, case, head_dim=128) + + def test_sparse_topk_cases(self): + for case in self.SPARSE_CASES: + with self.subTest(case=case.name, backend=case.backend): + run_dsa_sparse_attention_case(self, case) + + # Non-trailing index layouts. The reference gathers Q/K via + # `fixture.topk_rows`, so any valid permutation of keys in + # `[0, key_count)` produces a matching reference. These layouts + # exercise the kernel's non-contiguous gather path (production + # top-k by attention score is not naturally trailing for long + # prefixes). Use long-prefix decode where `key_count > index_topk` + # so the pattern actually subsamples (with key_count <= topk, + # strided/head_tail collapse back to the trailing case). + NON_TRAILING_INDEX_CASES = ( + ( + DSAAttentionCase( + name="dsa_sparse_decode_strided_index_long_prefix", + backend="dsa", + forward_mode=ForwardMode.DECODE, + num_heads=4, + num_kv_heads=1, + page_size=DSA_PAGE_SIZE, + prefix_lens=(2048,), + ), + "strided", + ), + ( + DSAAttentionCase( + name="dsa_sparse_decode_head_tail_index_long_prefix", + backend="dsa", + forward_mode=ForwardMode.DECODE, + num_heads=4, + num_kv_heads=1, + page_size=DSA_PAGE_SIZE, + prefix_lens=(2048,), + ), + "head_tail", + ), + ) + + def test_sparse_non_trailing_index_cases(self): + for case, pattern in self.NON_TRAILING_INDEX_CASES: + with self.subTest(case=case.name, backend=case.backend, pattern=pattern): + run_dsa_sparse_attention_case(self, case, index_pattern=pattern) + + # Layout-robustness. See dense/test_triton.py for the rationale. + # shuffled_pages is the default for all DSA tests via + # build_dsa_attention_fixture / build_dsa_sparse_attention_fixture; + # this method opts into the more aggressive interleaved_pages + + # non_monotonic_extend layouts on representative dense fallback and + # sparse top-k cases. + LAYOUT_DENSE_CASES = ( + DSAAttentionCase( + name="layout_dsa_dense_fallback_two_request", + backend="dsa", + forward_mode=ForwardMode.EXTEND, + num_heads=4, + num_kv_heads=4, + page_size=DSA_PAGE_SIZE, + prefix_lens=(0, 32), + extend_lens=(32, 16), + ), + ) + LAYOUT_SPARSE_CASES = ( + DSAAttentionCase( + name="layout_dsa_sparse_decode_long_prefix", + backend="dsa", + forward_mode=ForwardMode.DECODE, + num_heads=4, + num_kv_heads=1, + page_size=DSA_PAGE_SIZE, + prefix_lens=(2048,), + ), + ) + + def test_layout_robustness_dense_cases(self): + for case in self.LAYOUT_DENSE_CASES: + for layout in ("interleaved_pages", "non_monotonic_extend"): + with self.subTest(case=case.name, layout=layout): + run_dsa_attention_case(self, case, head_dim=128, loc_layout=layout) + + def test_layout_robustness_sparse_cases(self): + for case in self.LAYOUT_SPARSE_CASES: + for layout in ("interleaved_pages",): + with self.subTest(case=case.name, layout=layout): + run_dsa_sparse_attention_case(self, case, loc_layout=layout) + + # CG decode replay via the sparse `flashmla_kv` path (cached MLA latent + # KV, written by `_populate_dsa_sparse_prefix_kv` at fixture build). + # Unlike the MHA_ONE_SHOT dense fallback (where K is passed inline as + # prefix+extend and `unified_attention_with_output` slicing breaks + # piecewise CG), sparse decode reads cached K and is CG-compatible. + CUDA_GRAPH_DECODE_CASES = ( + DSAAttentionCase( + name="runner_cuda_graph_dsa_sparse_decode_flashmla_kv", + backend="dsa", + forward_mode=ForwardMode.DECODE, + num_heads=4, + num_kv_heads=1, + page_size=DSA_PAGE_SIZE, + prefix_lens=(127, 128), + ), + ) + + def test_runner_mode_cuda_graph_decode_cases(self): + for case in self.CUDA_GRAPH_DECODE_CASES: + with self.subTest(case=case.name, backend=case.backend): + run_dsa_sparse_cuda_graph_decode_case(self, case) + + # DSA implementation-variant matrix. DSA exposes multiple kernel + # implementations (`flashmla_sparse`, `flashmla_kv`, `fa3`, `tilelang`, + # `trtllm`, `aiter`) selected by `--dsa-prefill-backend` / + # `--dsa-decode-backend`. Each variant maps to a distinct kernel path + # in `dsa_backend.py`; `dsa_impl_capability` gates per hardware/SDK so + # impls unavailable on the test box (e.g., `trtllm` requires SM100+, + # `aiter` requires HIP) emit a clean `skipTest` with a reason rather + # than spuriously failing. + PREFILL_IMPL_CASE = DSAAttentionCase( + name="dsa_sparse_prefill_impl_variant", + backend="dsa", + forward_mode=ForwardMode.EXTEND, + num_heads=4, + num_kv_heads=1, + page_size=DSA_PAGE_SIZE, + # Long prefix keeps the backend on the MLA path (above the + # MHA_ONE_SHOT short-sequence threshold) so the impl override + # actually routes through `dsa_prefill_impl`. + prefix_lens=(2048,), + extend_lens=(1,), + ) + DECODE_IMPL_CASE = DSAAttentionCase( + name="dsa_sparse_decode_impl_variant", + backend="dsa", + forward_mode=ForwardMode.DECODE, + num_heads=4, + num_kv_heads=1, + page_size=DSA_PAGE_SIZE, + prefix_lens=(128,), + ) + + def test_sparse_prefill_impl_variants(self): + for impl in DSA_PREFILL_IMPL_VARIANTS: + with self.subTest(impl=impl): + run_dsa_sparse_prefill_impl_variant_case( + self, self.PREFILL_IMPL_CASE, impl + ) + + def test_sparse_decode_impl_variants(self): + for impl in DSA_DECODE_IMPL_VARIANTS: + with self.subTest(impl=impl): + run_dsa_sparse_decode_impl_variant_case( + self, self.DECODE_IMPL_CASE, impl + ) + + # Speculative forward-mode coverage. TARGET_VERIFY and + # DRAFT_EXTEND_V2 both route through the `dsa_decode_impl` + # dispatcher (the same kernel selection as plain DECODE) but + # produce different `seqlens_expanded` and `cu_seqlens_q` from + # `dsa_backend.py:469-529`. `DSAMockModelRunner.__init__` derives + # `speculative_num_draft_tokens` from `case.extend_lens` so deep_gemm + # JIT-compiles with a non-zero aligned batch size. + SPECULATIVE_FORWARD_MODE_CASES = ( + DSAAttentionCase( + name="dsa_sparse_target_verify", + backend="dsa", + forward_mode=ForwardMode.TARGET_VERIFY, + num_heads=4, + num_kv_heads=1, + page_size=DSA_PAGE_SIZE, + prefix_lens=(128,), + extend_lens=(3,), + ), + DSAAttentionCase( + name="dsa_sparse_draft_extend_v2", + backend="dsa", + forward_mode=ForwardMode.DRAFT_EXTEND_V2, + num_heads=4, + num_kv_heads=1, + page_size=DSA_PAGE_SIZE, + prefix_lens=(128,), + extend_lens=(3,), + ), + ) + + def test_sparse_speculative_forward_mode_cases(self): + for case in self.SPECULATIVE_FORWARD_MODE_CASES: + with self.subTest(case=case.name, mode=case.forward_mode.name): + run_dsa_sparse_speculative_forward_mode_case(self, case) + + # FP8 KV cache (`dsa_kv_cache_store_fp8=True`) — the production + # deployment dtype. Switches `DSATokenToKVPool` to packed + # FP8-nope/BF16-rope storage at 656 bytes/token; `set_mla_kv_buffer` + # routes through `quantize_k_cache_separate` and the kernel reads + # FP8 directly. The reference stays on BF16 K (independent of the + # cache bytes), and `DSA_SPARSE_FP8_ATOL=0.2` absorbs FP8 quant + # noise — same separation principle as the DSV4 SWA fixture so a + # silent pack/write bug cannot corrupt both paths identically. + # + # FP8 + `flashmla_sparse` prefill + EXTEND + non-empty prefix is the + # only combo that hits `TopkTransformMethod.RAGGED` + # (`get_topk_transform_method`), which exercises + # `dequantize_k_cache_paged` and the `topk_indices_offset` shift — + # paths that the BF16 default suite never reaches. + FP8_PREFILL_RAGGED_CASE = DSAAttentionCase( + name="dsa_sparse_fp8_prefill_ragged_topk", + backend="dsa", + forward_mode=ForwardMode.EXTEND, + num_heads=4, + num_kv_heads=1, + page_size=DSA_PAGE_SIZE, + # Long prefix → above MHA threshold, RAGGED topk transform + prefix_lens=(2048,), + extend_lens=(1,), + ) + FP8_PREFILL_PAGED_CASE = DSAAttentionCase( + name="dsa_sparse_fp8_prefill_paged_topk", + backend="dsa", + forward_mode=ForwardMode.EXTEND, + num_heads=4, + num_kv_heads=1, + page_size=DSA_PAGE_SIZE, + prefix_lens=(2048,), + extend_lens=(1,), + ) + FP8_DECODE_CASE = DSAAttentionCase( + name="dsa_sparse_fp8_decode", + backend="dsa", + forward_mode=ForwardMode.DECODE, + num_heads=4, + num_kv_heads=1, + page_size=DSA_PAGE_SIZE, + prefix_lens=(128,), + ) + + def test_sparse_fp8_prefill_cases(self): + for impl in DSA_PREFILL_IMPL_VARIANTS: + with self.subTest(impl=impl): + # Each impl that isn't in `DSA_FP8_COMPATIBLE_PREFILL_IMPLS` + # emits skipTest from the helper with the reason. The + # `flashmla_sparse` impl hits the RAGGED-topk path; the + # others stay on PAGED. + case = ( + self.FP8_PREFILL_RAGGED_CASE + if impl == "flashmla_sparse" + else self.FP8_PREFILL_PAGED_CASE + ) + run_dsa_sparse_fp8_prefill_case(self, case, dsa_prefill_backend=impl) + + def test_sparse_fp8_decode_cases(self): + for impl in DSA_DECODE_IMPL_VARIANTS: + with self.subTest(impl=impl): + run_dsa_sparse_fp8_decode_case( + self, self.FP8_DECODE_CASE, dsa_decode_backend=impl + ) + + # Tilelang sparse cases — dedicated topk=2048 fixture. + # `tilelang_sparse_fwd` asserts `topk == 2048` at + # `dsa/tilelang_kernel.py:1345`, so this fixture variant carries a + # 2048-wide trailing-topk row builder. Prefix length must be >= 2048 + # to produce a real (non-padded) topk row. + TILELANG_PREFILL_CASE = DSAAttentionCase( + name="dsa_sparse_tilelang_prefill", + backend="dsa", + forward_mode=ForwardMode.EXTEND, + num_heads=4, + num_kv_heads=1, + page_size=DSA_PAGE_SIZE, + prefix_lens=(4096,), + extend_lens=(1,), + ) + TILELANG_DECODE_CASE = DSAAttentionCase( + name="dsa_sparse_tilelang_decode", + backend="dsa", + forward_mode=ForwardMode.DECODE, + num_heads=4, + num_kv_heads=1, + page_size=DSA_PAGE_SIZE, + prefix_lens=(4096,), + ) + + def test_sparse_tilelang_prefill_case(self): + run_dsa_sparse_tilelang_prefill_case(self, self.TILELANG_PREFILL_CASE) + + def test_sparse_tilelang_decode_case(self): + run_dsa_sparse_tilelang_decode_case(self, self.TILELANG_DECODE_CASE) + + # EAGLE production draft CUDA-graph runner integration. Wires DSA + # through `speculative_draft_runner.py`'s shared + # `EagleDraftCudaGraphRunnerAdapter` (same lifecycle as DSV4 / + # dense / MLA). DSA's chain-only constraint comes from the + # synthesized topk_indices path — tree draft needs parent-indices + # plumbing through that synthesis; deferred. + EAGLE_DRAFT_CASES = ( + DSAAttentionCase( + name="runner_eagle_draft_decode_cuda_graph_dsa_chain", + backend="dsa", + forward_mode=ForwardMode.DECODE, + num_heads=4, + num_kv_heads=1, + page_size=DSA_PAGE_SIZE, + prefix_lens=(128, 192), + ), + ) + + def test_runner_mode_eagle_draft_cuda_graph_runner_cases(self): + for case in self.EAGLE_DRAFT_CASES: + with self.subTest(case=case.name, backend=case.backend): + run_dsa_eagle_draft_cuda_graph_runner_case(self, case) + + # CG decode replay with FP8 KV cache. Captures and replays through + # `flashmla_kv` (the only FP8-compatible decode kernel). The + # `_clone_dsa_sparse_cache` hook is reused as-is — it snapshots the + # raw uint8 K buffer bytes, which round-trip correctly across + # capture/replay regardless of bf16 vs FP8 packing. + def test_sparse_fp8_cuda_graph_decode_case(self): + from sglang.test.kits.attention_unittest.runner_modes.cuda_graph_decode_runner import ( + run_dsa_sparse_cuda_graph_decode_case, + ) + + run_dsa_sparse_cuda_graph_decode_case( + self, + self.FP8_DECODE_CASE, + dsa_decode_backend="flashmla_kv", + fp8_kv_cache=True, + ) + + # CG decode replay parametrized over `dsa_decode_backend` impl. The + # `flashmla_kv` baseline is already covered by + # `test_runner_mode_cuda_graph_decode_cases`; this method extends the + # CG matrix to every supported decode impl (`flashmla_sparse` / + # `flashmla_kv` / `fa3` on H200, with `tilelang` / `trtllm` / `aiter` + # skip-gated). Each impl re-builds the fixture with the impl forced + # so the captured graph uses that specific kernel. + def test_sparse_cuda_graph_decode_impl_variants(self): + for impl in DSA_DECODE_IMPL_VARIANTS: + with self.subTest(impl=impl): + run_dsa_sparse_cuda_graph_decode_impl_variant_case( + self, self.CUDA_GRAPH_DECODE_CASES[0], impl + ) + + +if __name__ == "__main__": + unittest.main() diff --git a/asian_ai/performance/SGLang/test/registered/attention/unittests/dsv4/README.md b/asian_ai/performance/SGLang/test/registered/attention/unittests/dsv4/README.md new file mode 100644 index 0000000000000000000000000000000000000000..01ecd4067555252c0dee9f88e9a554cd56a2f129 --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/attention/unittests/dsv4/README.md @@ -0,0 +1,155 @@ +# DSV4 Attention Capability Matrix + +This folder tracks DeepSeek-V4 attention tests. DSV4 has method-specific +sparse/indexer metadata and a packed FP8/BF16 KV cache layout, so it is not +folded into the dense, MLA, or DSA folders. The single attention backend +here is `dsv4` (which dispatches through `flash_mla`); the rows below +distinguish the **`compress_ratio` mode** that each test exercises. + +## Coverage Matrix + +Columns are runner modes; rows are `compress_ratio` modes of the single +`dsv4` backend. Cells use: +- **✓ \** — exercised, with the config variants listed in the cell +- **—** — not applicable / not exercised +- **production-unreachable: \** — production never invokes this + combination, so the test runner asserts against it at the call site +- **blocked: \** — would crash on a hard assertion if attempted; + also asserted against at the call site +- **deferred: \** — could land later, currently disabled + +| `compress_ratio` | Eager Phase 2 | CG decode | PCG extend | BCG extend | Verify eager | Verify CG | DE eager | DE CG | DE-V2 CG | EAGLE-draft runner | EAGLE-DE runner | FKVMTP runner | +|---|---|---|---|---|---|---|---|---|---|---|---|---| +| `0` (SWA-only) | ✓ EXTEND no-prefix / prefix-within-window / nonzero `attn_sink` / above-window / seq_len==SWA_WINDOW / seq_len below-page / seq_len at-page / seq_len above-page / prefix-exact-page / total-exact-page + DECODE within-window / multi-request / above-window | ✓ DECODE within-window + multi-request | — | — | ✓ EAGLE chain (topk=1) `prefix_lens=(64,96)` | ✓ EAGLE chain CG `prefix_lens=(64,96)` | ✓ EAGLE ragged-accept | ✓ EAGLE uniform `extend_lens=(4,4)` | — | ✓ chain `prefix_lens=(32,64)`, `num_steps=3` (`DeepseekV4MultiStepBackend` capture/replay vs. per-step-init eager) | ✓ uniform `extend_lens=(4,4)`, `prefix_lens=(64,96)` (production `EAGLEDraftExtendCudaGraphRunner` through `_create_dsv4_prefill_backend`; uses loose `DSV4_GRAPH_ATOL=1e-1` and skips strict `topk_index` exact-match to absorb CG accumulation drift) | — | +| `4` (C4) | ✓ EXTEND `prefix_lens=(64,)`, `extend_lens=(16,)` + DECODE `prefix_lens=(64,)` (extra K cache written directly via `set_extra_key_buffer`; `c4_sparse_page_indices` seeded manually because indexer is bypassed) | ✓ DECODE `prefix_lens=(64,)` | — | — | ✓ EAGLE chain (topk=1) `prefix_lens=(64,96)` | ✓ EAGLE chain CG `prefix_lens=(64,96)` | production-unreachable: draft layer is SWA-only | production-unreachable: draft layer is SWA-only | — | — | — | — | +| `128` (C128) | ✓ EXTEND `prefix_lens=(128,)`, `extend_lens=(16,)` + DECODE `prefix_lens=(128,)` | ✓ DECODE `prefix_lens=(128,)` | — | — | ✓ EAGLE chain (topk=1) `prefix_lens=(128,160)` | ✓ EAGLE chain CG `prefix_lens=(128,160)` | production-unreachable: draft layer is SWA-only | production-unreachable: draft layer is SWA-only | — | — | — | — | + +## Input And Config Coverage + +- `num_heads=64` (matches DSV4 production; `flash_mla.sparse_decode_fwd` + constrains `h_q` to specific values like 16/32/64/128). +- DeepSeek-V4 shape metadata: `qk_nope_head_dim=448`, `qk_rope_head_dim=64`, + `kv_lora_rank=448`, `head_dim=512`. +- `page_size=256` (the DSV4 backend asserts this exactly — + `deepseek_v4_backend.py:355`, `dsv4/metadata.py:134`). Per-page-boundary + coverage uses this hardcoded page size: `seq_len=255` (one below page), + `seq_len=256` (exactly one page), `seq_len=257` (one above page), + `prefix_lens=256+extend_lens=4` (prefix equals one page), and + `prefix_lens=240+extend_lens=16` (prefix + extend exactly equals one + page). `seq_len=128` covers the SWA-window-boundary `seq_len == + SWA_WINDOW` case. The fixture auto-scales `max_context_len` for the + larger sequences so `req_to_token` has room. +- Packed FP8 nope + BF16 rope SWA cache layout (584 bytes/token) comes from + `DeepSeekV4TokenToKVPool`. +- SWA window = 128 (`SWA_WINDOW` constant in `deepseek_v4_backend.py:67`). +- Tolerance is held loose (`DSV4_ATOL = DSV4_RTOL = 5e-2`) to absorb + `flash_mla` FP8 GEMM accumulation variance against the dequantized reference. + +## Reference Implementation Notes + +- The reference is a **vanilla PyTorch softmax** over the projected BF16 K + the fixture stashes on `fixture._swa_bf16_k_per_req` (and + `fixture._extra_bf16_k` for the C4/C128 cases). It does NOT read bytes + back from the production cache — that would couple the test to + `quant_to_nope_fp8_rope_bf16_pack_triton` / `set_swa_key_buffer_radix` + and a silent pack/write bug would corrupt both paths identically. The + vanilla BF16 K diverges from the FP8-dequantized K that `flash_mla` + reads by the FP8 quant noise; the `DSV4_ATOL = DSV4_RTOL = 5e-2` + tolerance absorbs that (graph-replay cases use a slightly looser + `DSV4_GRAPH_ATOL = 1e-1` to absorb the additional accumulation drift + introduced by `use_prefill_cuda_graph=True` padding). +- For C4/C128, the reference reads the upgraded `DSV4AttnMetadata`'s + per-q-token `swa_page_indices` / `c4_sparse_page_indices` / + `c128_page_indices` to learn which entries the kernel attends to. The + reference rebuilds metadata for the current batch on every call (the + speculative graph runner invokes `expected_output` before + `init_forward_metadata*`) and reseeds `c4_sparse_page_indices` after + `on_after_cuda_graph_warmup` so it observes the same indices the + backend forward saw. +- The attention-sink correction is applied by appending a virtual key with + per-head score `attn_sink` and value `0`. With the default + `attn_sink_value=-1e30` this is a numerical no-op; the + `dsv4_swa_extend_nonzero_attn_sink` case exercises the correction with + `attn_sink_value=0.0`. + +## Production-Unsupported + +- **`compress_ratio in {4, 128}` + `DRAFT_EXTEND` (eager OR CUDA-graph)** — + *production-unreachable*, not "broken". The DSV4 draft model + (`deepseek_v4_nextn.DeepseekV4ModelNextN`) is a single decoder layer + built with `compress_ratio_override=COMPRESS_RATIO_NEXTN_LAYER = 0` + (`python/sglang/srt/models/deepseek_v4_nextn.py:47,105`), which flows + through `MQALayer.__init__` at `deepseek_v4.py:232-237` and forces the + draft layer to SWA-only regardless of `config.compress_ratios`. + Production therefore never invokes `forward(compress_ratio=4 or 128, + forward_mode=DRAFT_EXTEND)`; the target model uses C4/C128 only in + DECODE / TARGET_VERIFY paths (which DO populate the C4/C128 metadata + via `need_compress=True`). If a test were to attempt the combination, + `init_forward_metadata_draft_extend` at `deepseek_v4_backend.py:636-663` + hardcodes `need_compress=False`, leaving `c4_sparse_page_indices` / + `c128_flashmla_metadata` at None and `forward(compress_ratio=4)` would + trip `extra_indices.shape[-1]` / `forward(compress_ratio=128)` would + trip a flash_mla `tile_scheduler_metadata` assert. The runner asserts + `case.compress_ratio == 0` at the call site for both + `run_dsv4_draft_extend_attention_case` and + `run_dsv4_eagle_draft_extend_cuda_graph_case` to make this unreachable + state loud at the test level. +- **MTP `topk > 1`** — `deepseek_v4_backend.py:369` asserts `self.topk in [0, 1]`. + Same in the HIP radix variant (`deepseek_v4_backend_hip_radix.py:363`). DSV4 + speculative draft-extend / target-verify is *always* chain (`topk=1`); + tree spec is structurally impossible. **DE-V2 CG, EAGLE-draft tree runner, + EAGLE-DE tree runner, FKVMTP runner** are therefore "—" not "deferred". +- **Non-256 page size** — `deepseek_v4_backend.py:355` (and HIP radix variant + `:349`, `dsv4/metadata.py:134`) asserts `page_size == 256`. +- **Non-512 head_dim** — `deepseek_v4_backend.py:345-347` asserts + `head_dim == 512`. DSV4 is hard-wired to `qk_nope=448 + qk_rope=64`. +- **Unknown `compress_ratio`** — `DSV4AttnMetadata.get_flashmla_metadata` + raises `ValueError(f"invalid {compress_ratio=}")` for anything outside + `Literal[0, 4, 128]` (`deepseek_v4_backend.py:125-133`). +- **Forward modes outside the `_GraphBucket` set** — + `deepseek_v4_backend.py:320-328` raises `NotImplementedError` for anything + not in `{decode_or_idle, target_verify, draft_extend(v1 or v2)}`. Same in + `init_forward_metadata` at `deepseek_v4_backend.py:713-714`. PCG/BCG + split-op extend is therefore structurally unreachable. + +## Compressor / C4Indexer — intentionally out of scope for this matrix + +`Compressor` and `C4Indexer` are `nn.Module` instances owned by the DSV4 +**model** (`models/deepseek_v4.py:296-311`), not by the attention backend. +The model's forward calls `self.indexer(...)` and +`attn_backend.forward_core_compressor(x, ..., self.compressor)` *before* +attention; their only outputs that flow into the attention backend are: + +- **Compressor**: writes bytes into `extra_k_cache` at the + `c4_out_loc` / `c128_out_loc` positions. The locations come from the + backend's `init_compression_metadata` Triton kernel + (`deepseek_v4_backend.py:182`), not from the Compressor. +- **C4Indexer**: writes the `c4_sparse_page_indices` field that the + backend's `forward_extend` / `forward_decode` then read. + +The attention backend's contract with both is purely: "I gave you a place +to write; you wrote something there; I'll read what you wrote." The +current fixture verifies exactly that contract by supplying known-good +synthetic bytes/indices through the **same production pack + store path** +(`quant_to_nope_fp8_rope_bf16_pack_triton` + `set_extra_key_buffer` at +`common/attention_methods/dsv4_attention.py:1193-1195`) and stashing the +unquantized BF16 K on the fixture for the reference. The +`init_compression_metadata` Triton kernel that produces page metadata IS +exercised; what's skipped is only the Compressor and C4Indexer +**`nn.Module` forward math** (`x → compressed_kv` and +`x, q_lora → page_indices`). + +Compressor / C4Indexer math correctness belongs at the **component +level** — `test/srt/test_dsv4_compressor.py` and +`test/srt/test_dsv4_c4_indexer.py` are the natural homes, against +pure-PyTorch references of those modules' math. Same rationale as why +RoPE is out of scope for the attention-backend matrix (PLAN.md "RoPE +handling"): pre-processing modules whose outputs are inputs to the +attention backend. + +## Next Work + +- Component-level Compressor / C4Indexer correctness tests at + `test/srt/` (separate from this matrix). Optional — the attention + backend already verifies its end of the contract via known-good + synthetic inputs. diff --git a/asian_ai/performance/SGLang/test/registered/attention/unittests/dsv4/__init__.py b/asian_ai/performance/SGLang/test/registered/attention/unittests/dsv4/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e1fb338fb4e5ba7f75e5e4ec35284fd3083be04c --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/attention/unittests/dsv4/__init__.py @@ -0,0 +1 @@ +"""DSV4 attention unit-test package.""" diff --git a/asian_ai/performance/SGLang/test/registered/attention/unittests/dsv4/test_deepseek_v4.py b/asian_ai/performance/SGLang/test/registered/attention/unittests/dsv4/test_deepseek_v4.py new file mode 100644 index 0000000000000000000000000000000000000000..056860a30559e56b741f05842b798f4987d328ce --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/attention/unittests/dsv4/test_deepseek_v4.py @@ -0,0 +1,601 @@ +"""DSV4 attention correctness — SWA + C4/C128 coverage. + +Covers eager EXTEND/DECODE plus CUDA-graph-style capture/replay for the +SWA-only (compress_ratio=0) path of `DeepseekV4AttnBackend` through flash_mla +with the production packed FP8-nope/BF16-rope SWA cache, plus math-faithful +EAGER coverage for the C4 (compress_ratio=4) and C128 (compress_ratio=128) +paths. The C4/C128 cases bypass the production `Compressor`/`C4Indexer` +modules (writing the extra K cache directly via the pack+set path and +seeding `c4_sparse_page_indices` for the un-run indexer) but compare the +flash_mla `extra_k_cache` integration against an independent PyTorch SWA + +extra-K softmax reference. Compressor math correctness (i.e. verifying the +gate+norm+rotate compression itself) is a deferred follow-up. +""" + +import importlib.util +import sys +import unittest +from pathlib import Path +from types import SimpleNamespace +from unittest import mock + +import torch + +from sglang.srt.model_executor.forward_batch_info import ForwardMode +from sglang.test.test_utils import CustomTestCase + +sys.path.insert(0, str(Path(__file__).resolve().parents[1])) + +_FLASH_MLA_AVAILABLE = importlib.util.find_spec("flash_mla") is not None + +from sglang.test.ci.ci_register import register_cuda_ci +from sglang.test.kits.attention_unittest.attention_methods.dsv4_attention import ( # noqa: E402 + DSV4_PAGE_SIZE, + DSV4AttentionCase, + make_dsv4_cases, + run_dsv4_attention_case, + run_dsv4_compress_attention_case, + run_dsv4_target_verify_attention_case, +) +from sglang.test.kits.attention_unittest.runner_modes.cuda_graph_decode_runner import ( # noqa: E402 + run_dsv4_cuda_graph_decode_case, +) +from sglang.test.kits.attention_unittest.runner_modes.speculative_draft_runner import ( # noqa: E402 + run_dsv4_eagle_draft_cuda_graph_runner_case, +) +from sglang.test.kits.attention_unittest.runner_modes.speculative_target_verify_runner import ( # noqa: E402 + run_dsv4_eagle_verify_cuda_graph_case, +) + +register_cuda_ci(est_time=25, stage="base-b", runner_config="4-gpu-b200") +register_cuda_ci(est_time=25, stage="base-b", runner_config="1-gpu-large") + + +@unittest.skipIf(not torch.cuda.is_available(), "CUDA is required") +@unittest.skipIf(not _FLASH_MLA_AVAILABLE, "flash_mla is required for DSV4 SWA") +class TestDSV4AttentionBackendCorrectness(CustomTestCase): + CASES = make_dsv4_cases("dsv4") + CUDA_GRAPH_DECODE_CASES = ( + DSV4AttentionCase( + name="runner_cuda_graph_dsv4_decode_within_window", + backend="dsv4", + forward_mode=ForwardMode.DECODE, + num_heads=64, + page_size=DSV4_PAGE_SIZE, + prefix_lens=(64,), + ), + DSV4AttentionCase( + name="runner_cuda_graph_dsv4_decode_multi_request", + backend="dsv4", + forward_mode=ForwardMode.DECODE, + num_heads=64, + page_size=DSV4_PAGE_SIZE, + prefix_lens=(32, 96), + ), + DSV4AttentionCase( + name="runner_cuda_graph_dsv4_c4_decode", + backend="dsv4", + forward_mode=ForwardMode.DECODE, + num_heads=64, + page_size=DSV4_PAGE_SIZE, + prefix_lens=(64,), + compress_ratio=4, + ), + DSV4AttentionCase( + name="runner_cuda_graph_dsv4_c128_decode", + backend="dsv4", + forward_mode=ForwardMode.DECODE, + num_heads=64, + page_size=DSV4_PAGE_SIZE, + prefix_lens=(128,), + compress_ratio=128, + ), + ) + # SWA + C4 / SWA + C128 cases. Each pre-populates the extra K cache directly + # via `set_extra_key_buffer`, lets `init_forward_metadata` populate the + # compression metadata (and seeds `c4_sparse_page_indices` manually for C4 + # since the un-run indexer leaves it at -1), then compares the flash_mla + # output to an independent PyTorch SWA + extra-K softmax reference. + COMPRESS_CASES = ( + DSV4AttentionCase( + name="dsv4_c4_extend", + backend="dsv4", + forward_mode=ForwardMode.EXTEND, + num_heads=64, + page_size=DSV4_PAGE_SIZE, + prefix_lens=(64,), + extend_lens=(16,), + compress_ratio=4, + ), + DSV4AttentionCase( + name="dsv4_c4_decode", + backend="dsv4", + forward_mode=ForwardMode.DECODE, + num_heads=64, + page_size=DSV4_PAGE_SIZE, + prefix_lens=(64,), + compress_ratio=4, + ), + DSV4AttentionCase( + name="dsv4_c128_extend", + backend="dsv4", + forward_mode=ForwardMode.EXTEND, + num_heads=64, + page_size=DSV4_PAGE_SIZE, + prefix_lens=(128,), + extend_lens=(16,), + compress_ratio=128, + ), + DSV4AttentionCase( + name="dsv4_c128_decode", + backend="dsv4", + forward_mode=ForwardMode.DECODE, + num_heads=64, + page_size=DSV4_PAGE_SIZE, + prefix_lens=(128,), + compress_ratio=128, + ), + ) + + def test_swa_only_cases(self): + for case in self.CASES: + with self.subTest(case=case.name, backend=case.backend): + run_dsv4_attention_case(self, case) + + def test_runner_mode_cuda_graph_decode_cases(self): + for case in self.CUDA_GRAPH_DECODE_CASES: + with self.subTest(case=case.name, backend=case.backend): + run_dsv4_cuda_graph_decode_case(self, case) + + # EAGLE target_verify (chain only — DSV4 asserts topk <= 1). One case per + # compress_ratio so SWA, SWA+C4, and SWA+C128 all run through the + # per-draft-token causal-within-SWA + extra-K reference. + TARGET_VERIFY_CASES = ( + DSV4AttentionCase( + name="dsv4_swa_eagle_verify_chain", + backend="dsv4", + forward_mode=ForwardMode.TARGET_VERIFY, + num_heads=64, + page_size=DSV4_PAGE_SIZE, + prefix_lens=(64, 96), + extend_lens=(3, 3), + ), + DSV4AttentionCase( + name="dsv4_c4_eagle_verify_chain", + backend="dsv4", + forward_mode=ForwardMode.TARGET_VERIFY, + num_heads=64, + page_size=DSV4_PAGE_SIZE, + prefix_lens=(64, 96), + extend_lens=(3, 3), + compress_ratio=4, + ), + DSV4AttentionCase( + name="dsv4_c128_eagle_verify_chain", + backend="dsv4", + forward_mode=ForwardMode.TARGET_VERIFY, + num_heads=64, + page_size=DSV4_PAGE_SIZE, + prefix_lens=(128, 160), + extend_lens=(3, 3), + compress_ratio=128, + ), + ) + + def test_compress_attention_cases(self): + # Pinned to the dense extend path; the sparse prefill path is covered + # by test_compress_attention_cases_sparse_prefill below. + for case in self.COMPRESS_CASES: + with self.subTest( + case=case.name, + backend=case.backend, + compress_ratio=case.compress_ratio, + ): + run_dsv4_compress_attention_case(self, case, sparse_prefill=False) + + def test_compress_attention_cases_sparse_prefill(self): + # `_forward_prefill_sparse` extend path; decode never reaches it. + for case in self.COMPRESS_CASES: + if not case.forward_mode.is_extend_without_speculative(): + continue + with self.subTest( + case=case.name, + backend=case.backend, + compress_ratio=case.compress_ratio, + ): + run_dsv4_compress_attention_case(self, case, sparse_prefill=True) + + def test_eagle_target_verify_chain_cases(self): + for case in self.TARGET_VERIFY_CASES: + with self.subTest( + case=case.name, + backend=case.backend, + compress_ratio=case.compress_ratio, + ): + run_dsv4_target_verify_attention_case(self, case, topk=1) + + # CUDA-graph capture/replay for EAGLE target_verify across SWA + C4 + C128. + EAGLE_VERIFY_CUDA_GRAPH_CASES = ( + DSV4AttentionCase( + name="runner_cuda_graph_dsv4_swa_eagle_verify_chain", + backend="dsv4", + forward_mode=ForwardMode.TARGET_VERIFY, + num_heads=64, + page_size=DSV4_PAGE_SIZE, + prefix_lens=(64, 96), + extend_lens=(3, 3), + ), + DSV4AttentionCase( + name="runner_cuda_graph_dsv4_c4_eagle_verify_chain", + backend="dsv4", + forward_mode=ForwardMode.TARGET_VERIFY, + num_heads=64, + page_size=DSV4_PAGE_SIZE, + prefix_lens=(64, 96), + extend_lens=(3, 3), + compress_ratio=4, + ), + DSV4AttentionCase( + name="runner_cuda_graph_dsv4_c128_eagle_verify_chain", + backend="dsv4", + forward_mode=ForwardMode.TARGET_VERIFY, + num_heads=64, + page_size=DSV4_PAGE_SIZE, + prefix_lens=(128, 160), + extend_lens=(3, 3), + compress_ratio=128, + ), + ) + + def test_runner_mode_eagle_verify_cuda_graph_cases(self): + for case in self.EAGLE_VERIFY_CUDA_GRAPH_CASES: + with self.subTest( + case=case.name, + backend=case.backend, + compress_ratio=case.compress_ratio, + ): + run_dsv4_eagle_verify_cuda_graph_case(self, case, topk=1) + + # Production EAGLE draft graph runner (chain only, SWA only). The runner + # routes through `DeepseekV4MultiStepBackend` (one `DeepseekV4AttnBackend` + # per draft step), captures a fixed batch, and replays distinct request + # metadata. The fixture's `ProjectedDSV4Attention.forward` writes K via + # `set_swa_key_buffer_radix` exactly like the production model. + PRODUCTION_EAGLE_DRAFT_RUNNER_CASES = ( + DSV4AttentionCase( + name="runner_production_eagle_draft_dsv4_swa_chain", + backend="dsv4", + forward_mode=ForwardMode.DECODE, + num_heads=64, + page_size=DSV4_PAGE_SIZE, + prefix_lens=(32, 64), + ), + ) + + def test_runner_mode_production_eagle_draft_cuda_graph_runner_cases(self): + for case in self.PRODUCTION_EAGLE_DRAFT_RUNNER_CASES: + with self.subTest(case=case.name, backend=case.backend): + run_dsv4_eagle_draft_cuda_graph_runner_case(self, case) + + +class TestDSV4BreakableCudaGraphMetadataContract(CustomTestCase): + """CPU-only checks for the DSV4 BCG metadata replay contract.""" + + @staticmethod + def _make_sparse_prefill_cache(max_seq_len): + from sglang.srt.layers.attention.dsv4.sparse_prefill_utils import ( + SparsePrefillChunkCache, + ) + + int32 = dict(dtype=torch.int32) + return SparsePrefillChunkCache( + num_reqs=2, + num_qo_tokens=2, + max_seq_len=max_seq_len, + swa_window_size=128, + swa_page_size=128, + seq_lens=torch.tensor([max_seq_len, max_seq_len], **int32), + query_start_loc=torch.tensor([0, 1, 2], **int32), + swa_token_ids=torch.empty(0, **int32), + swa_first_pos=torch.zeros(2, **int32), + swa_gather_lens=torch.zeros(2, **int32), + swa_offsets=torch.zeros(3, **int32), + ) + + def _make_core_metadata(self, base: int): + from sglang.srt.layers.attention.deepseek_v4_backend import DSV4AttnMetadata + + metadata = DSV4AttnMetadata( + page_size=256, + page_table=torch.tensor( + [[base + 1, base + 2], [base + 3, base + 4]], dtype=torch.int32 + ), + raw_out_loc=torch.tensor([base + 5, base + 6], dtype=torch.int32), + cuda_int32_kwargs={"dtype": torch.int32}, + seq_lens_casual=torch.tensor([base + 7, base + 8], dtype=torch.int32), + positions_casual=torch.tensor([base + 9, base + 10], dtype=torch.int32), + swa_page_indices=torch.tensor( + [[base + 11, base + 12], [base + 13, base + 14]], dtype=torch.int32 + ), + swa_topk_lengths=torch.tensor([base + 15, base + 16], dtype=torch.int32), + c4_sparse_topk=128, + ) + metadata.c4_out_loc = torch.tensor([base + 17, base + 18], dtype=torch.int32) + metadata.c128_out_loc = torch.tensor([base + 19, base + 20], dtype=torch.int32) + metadata.c4_topk_lengths_raw = torch.tensor( + [base + 21, base + 22], dtype=torch.int32 + ) + metadata.c4_topk_lengths_clamp1 = torch.tensor( + [base + 23, base + 24], dtype=torch.int32 + ) + metadata.c4_sparse_topk_lengths = torch.tensor( + [base + 25, base + 26], dtype=torch.int32 + ) + metadata.c4_sparse_page_indices = torch.tensor( + [[base + 27, base + 28], [base + 29, base + 30]], dtype=torch.int32 + ) + metadata.c4_sparse_raw_indices = torch.tensor( + [[base + 31, base + 32], [base + 33, base + 34]], dtype=torch.int32 + ) + metadata.c128_page_indices = torch.tensor( + [[base + 35, base + 36], [base + 37, base + 38]], dtype=torch.int32 + ) + metadata.c128_topk_lengths_clamp1 = torch.tensor( + [base + 39, base + 40], dtype=torch.int32 + ) + metadata.c1_flashmla_metadata = object() + metadata.c4_flashmla_metadata = object() + metadata.c128_flashmla_metadata = object() + return metadata + + def test_bcg_is_explicit_and_dsv4_backend_opt_in_only(self): + from sglang.srt.layers.attention.base_attn_backend import AttentionBackend + from sglang.srt.layers.attention.deepseek_v4_backend import ( + DeepseekV4AttnBackend, + ) + from sglang.srt.server_args import ServerArgs + + # cg-refactor folded the legacy enable_breakable_cuda_graph flag + # into cuda_graph_config. Verify the per-phase backend selectors + # default to None (i.e. nothing opted into BREAKABLE without an + # explicit CLI flag). + sa = ServerArgs(model_path="dummy") + self.assertNotEqual(sa.cuda_graph_backend_decode, "breakable") + self.assertNotEqual(sa.cuda_graph_backend_prefill, "breakable") + self.assertFalse( + AttentionBackend.use_captured_forward_metadata_for_breakable_cuda_graph + ) + self.assertTrue( + DeepseekV4AttnBackend.use_captured_forward_metadata_for_breakable_cuda_graph + ) + + def test_refresh_replay_metadata_preserves_captured_tensor_storage(self): + capture_metadata = self._make_core_metadata(0) + replay_metadata = self._make_core_metadata(1000) + + tensor_copy_fields = [ + "raw_out_loc", + "seq_lens_casual", + "positions_casual", + "c4_out_loc", + "c128_out_loc", + "c4_topk_lengths_raw", + "c4_topk_lengths_clamp1", + "c4_sparse_topk_lengths", + ] + reference_assign_fields = [ + "page_table", + "swa_page_indices", + "swa_topk_lengths", + "c128_page_indices", + "c128_topk_lengths_clamp1", + "c1_flashmla_metadata", + "c4_flashmla_metadata", + "c128_flashmla_metadata", + ] + + captured_tensor_objects = { + field: getattr(capture_metadata, field) for field in tensor_copy_fields + } + captured_sparse_pages = capture_metadata.c4_sparse_page_indices + captured_sparse_pages_value = captured_sparse_pages.clone() + + capture_metadata.refresh_for_breakable_cuda_graph_replay_(replay_metadata) + + for field in tensor_copy_fields: + self.assertIs( + getattr(capture_metadata, field), captured_tensor_objects[field] + ) + self.assertTrue( + torch.equal( + getattr(capture_metadata, field), getattr(replay_metadata, field) + ), + f"{field} should be copied from the replay metadata", + ) + + for field in reference_assign_fields: + self.assertIs( + getattr(capture_metadata, field), + getattr(replay_metadata, field), + f"{field} should use the replay metadata reference", + ) + + self.assertIs(capture_metadata.c4_sparse_page_indices, captured_sparse_pages) + self.assertTrue( + torch.equal( + capture_metadata.c4_sparse_page_indices, captured_sparse_pages_value + ) + ) + + def test_backend_replay_keeps_captured_metadata_active(self): + from sglang.srt.layers.attention.deepseek_v4_backend import ( + DeepseekV4AttnBackend, + DSV4Metadata, + ) + + capture_metadata = DSV4Metadata( + self._make_core_metadata(0), indexer_metadata=None + ) + capture_metadata.sparse_prefill_cache = object() + replay_metadata = DSV4Metadata( + self._make_core_metadata(1000), indexer_metadata=None + ) + backend = object.__new__(DeepseekV4AttnBackend) + backend.MAX_SEQ_LEN_FOR_CAPTURE = 4096 + calls = [] + + def fake_build_forward_metadata( + forward_batch, *, max_seq_len_override, use_prefill_cuda_graph + ): + calls.append((forward_batch, max_seq_len_override, use_prefill_cuda_graph)) + return replay_metadata + + backend._build_forward_metadata = fake_build_forward_metadata + forward_batch = SimpleNamespace(name="live") + static_forward_batch = SimpleNamespace(name="static") + + backend.prepare_forward_metadata_for_breakable_cuda_graph_replay( + capture_metadata, + forward_batch, + static_forward_batch=static_forward_batch, + ) + + self.assertIs(calls[0][0], static_forward_batch) + self.assertEqual(calls[0][1], backend.MAX_SEQ_LEN_FOR_CAPTURE) + self.assertTrue(calls[0][2]) + self.assertIs(backend.forward_metadata, capture_metadata) + self.assertIsNone(capture_metadata.sparse_prefill_cache) + self.assertTrue( + torch.equal( + capture_metadata.core_attn_metadata.seq_lens_casual, + replay_metadata.core_attn_metadata.seq_lens_casual, + ) + ) + + def test_sparse_prefill_workspace_reuses_and_grows(self): + from sglang.srt.layers.attention.dsv4.sparse_prefill_utils import ( + SparsePrefillWorkspace, + ) + + workspace = SparsePrefillWorkspace(torch.device("cpu")) + first = workspace.get(3) + reused = workspace.get(2) + grown = workspace.get(7) + + self.assertEqual(first.shape, (3, 1, 512)) + self.assertEqual(reused.data_ptr(), first.data_ptr()) + self.assertEqual(grown.shape, (7, 1, 512)) + self.assertNotEqual(grown.data_ptr(), first.data_ptr()) + self.assertEqual(workspace._buffer.data_ptr(), grown.data_ptr()) + + def test_sparse_prefill_c4_uses_live_extent(self): + page_table = torch.zeros((2, 4096), dtype=torch.int32) + for max_seq_len in (3, 4, 255, 256, 259, 260): + with self.subTest(max_seq_len=max_seq_len): + cache = self._make_sparse_prefill_cache(max_seq_len) + cache.ensure_c4(page_table, c4_page_size=64) + expected_extent = max(max_seq_len // 4, 1) + self.assertEqual(cache.c4_flat_token_ids.numel(), 2 * expected_extent) + self.assertEqual( + cache.c4_compressed_base.tolist(), [0, expected_extent] + ) + + def test_sparse_prefill_c128_uses_live_extent(self): + from sglang.srt.layers.attention.dsv4 import sparse_prefill_utils + + page_indices = torch.full((2, 8192), -1, dtype=torch.int32) + for max_seq_len in (127, 128, 255, 256): + with self.subTest(max_seq_len=max_seq_len): + cache = self._make_sparse_prefill_cache(max_seq_len) + expected_extent = max(max_seq_len // 128, 1) + combined = ( + torch.empty((2, 256), dtype=torch.int32), + torch.empty(2, dtype=torch.int32), + ) + with mock.patch.object( + sparse_prefill_utils, + "combine_topk_swa_indices", + return_value=combined, + ) as combine: + cache.ensure_c128(page_indices) + + self.assertEqual(cache.c128_flat_token_ids.numel(), 2 * expected_extent) + self.assertEqual(combine.call_args.kwargs["topk"], expected_extent) + self.assertEqual( + combine.call_args.kwargs["topk_indices"].shape, + (2, expected_extent), + ) + + +class TestDSV4SwaOutCacheLocResolution(CustomTestCase): + """`get_swa_out_cache_loc`: cached fast path vs store-time fallback. + + The KV-store consumers run in paths that never invoke + `init_forward_metadata_in_graph` (eager idle, runners that only run the + out-graph prep) or whose batch is re-padded after init (DP attention). + The resolver must use the per-forward cached value only when it is + provably current and fall back to translating `out_cache_loc` otherwise. + """ + + def _make_backend(self, mapping: torch.Tensor): + from sglang.srt.layers.attention.deepseek_v4_backend import ( + DeepseekV4AttnBackend, + ) + + backend = object.__new__(DeepseekV4AttnBackend) + backend.forward_metadata = None + backend.token_to_kv_pool = SimpleNamespace( + translate_loc_from_full_to_swa=lambda loc: mapping[loc] + ) + return backend + + @staticmethod + def _make_fb(out_cache_loc: torch.Tensor, forward_mode: ForwardMode): + return SimpleNamespace(out_cache_loc=out_cache_loc, forward_mode=forward_mode) + + @staticmethod + def _set_cached(backend, cached: torch.Tensor): + backend.forward_metadata = SimpleNamespace( + core_attn_metadata=SimpleNamespace(swa_out_cache_loc=cached) + ) + + def test_no_metadata_falls_back_to_translate(self): + mapping = torch.arange(10, dtype=torch.int64) * 2 + backend = self._make_backend(mapping) + fb = self._make_fb(torch.tensor([3, 4]), ForwardMode.DECODE) + out = backend.get_swa_out_cache_loc(fb) + self.assertEqual(out.dtype, torch.int32) + self.assertEqual(out.tolist(), [6, 8]) + + def test_current_cached_value_is_used(self): + mapping = torch.arange(10, dtype=torch.int64) * 2 + backend = self._make_backend(mapping) + cached = torch.tensor([6, 8], dtype=torch.int32) + self._set_cached(backend, cached) + fb = self._make_fb(torch.tensor([3, 4]), ForwardMode.DECODE) + self.assertIs(backend.get_swa_out_cache_loc(fb), cached) + + def test_stale_shape_falls_back_to_translate(self): + # DP padding rebinds out_cache_loc to a longer tensor after init; + # a pre-pad cached value must not be used. + mapping = torch.arange(10, dtype=torch.int64) * 2 + backend = self._make_backend(mapping) + self._set_cached(backend, torch.tensor([6, 8], dtype=torch.int32)) + fb = self._make_fb(torch.tensor([3, 4, 0, 0]), ForwardMode.DRAFT_EXTEND_V2) + out = backend.get_swa_out_cache_loc(fb) + self.assertEqual(out.tolist(), [6, 8, 0, 0]) + + def test_idle_never_uses_cached_value(self): + # Idle forwards skip attn init, so any metadata is left over from a + # previous forward; writing dummy tokens to its locations would + # corrupt live KV. Idle must translate the zero-padded out_cache_loc. + mapping = torch.arange(10, dtype=torch.int64) * 2 + backend = self._make_backend(mapping) + self._set_cached(backend, torch.tensor([6, 8], dtype=torch.int32)) + fb = self._make_fb(torch.tensor([0, 0]), ForwardMode.IDLE) + out = backend.get_swa_out_cache_loc(fb) + self.assertEqual(out.tolist(), [0, 0]) + + +if __name__ == "__main__": + unittest.main() diff --git a/asian_ai/performance/SGLang/test/registered/attention/unittests/dual_chunk/README.md b/asian_ai/performance/SGLang/test/registered/attention/unittests/dual_chunk/README.md new file mode 100644 index 0000000000000000000000000000000000000000..aed67fc4dbdfb63baf569947aed45b17392c12ad --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/attention/unittests/dual_chunk/README.md @@ -0,0 +1,90 @@ +# Dual-Chunk Attention Capability Matrix + +This folder covers dual-chunk attention tests. `dual_chunk_flash_attn` is not +a dense backend swap: it expects a packed five-way query projection (`query`, +`succ`, `inter`, and critical variants), so the dense Q/K/V harness is +structurally wrong for this method. The single attention backend here is +`dual_chunk_flash_attn`; the rows below distinguish kernel-path modes. + +## Coverage Matrix + +Columns are runner modes; rows are kernel-path modes of the single +`dual_chunk_flash_attn` backend. Cells use: +- **✓ \** — exercised, with the config variants listed in the cell +- **—** — not applicable / not exercised +- **blocked: \** — production-unsupported, not a follow-up +- **deferred: \** — could land later, currently disabled + +| Kernel path | Eager Phase 2 | CG decode | PCG extend | BCG extend | Verify eager | Verify CG | DE eager | DE CG | DE-V2 CG | EAGLE-draft runner | EAGLE-DE runner | FKVMTP runner | +|---|---|---|---|---|---|---|---|---|---|---|---|---| +| Non-sparse | ✓ first-window, successor-chunk, inter-chunk extend/decode layouts + GQA decode | deferred: graph metadata for dual-chunk not scoped | deferred | deferred | blocked: `init_forward_metadata` asserts `is_prefill() or is_decode()` (`dual_chunk_flashattention_backend.py:179`); `TARGET_VERIFY` falls under `is_prefill()` but the wrapper hasn't been wired through | deferred | deferred | deferred | blocked: `DRAFT_EXTEND_V2` excluded from `is_prefill()` alias (see Production-Unsupported below) | deferred | deferred | — | +| Sparse all-column (`vertical_size`/`slash_size` chosen so every key in the first chunk is selected) | ✓ single-request first-chunk, multi-request first-chunk, page-boundary first-chunk | — | — | — | blocked: same `is_prefill` assertion | — | — | — | blocked: same | — | — | — | +| Sparse sub-window (`vertical_size=4`, `slash_size=4`, `seq_len=128`) | ✓ independent DCA top-k/split/fallback reference + torch sparse-kernel reference | — | — | — | — | — | — | — | — | — | — | — | +| Threshold-gated sparse (`sparse_attention_threshold=100`, seq_len=16 → gate disables sparse, falls back to dense) | ✓ verifies `current_orig_seq_len > threshold` gate semantics | — | — | — | — | — | — | — | — | — | — | — | + +## Input And Config Coverage + +- Page size 1 extend, exact-page extend, page-boundary crossing extend, and + ragged extend batches. +- Decode page-boundary coverage and GQA decode coverage. +- Successor-chunk and inter-chunk extend/decode layouts where `query_succ` + and `query_inter` are active and use independent projection weights. +- Sparse all-column prefill uses `head_dim=128` to match the local sparse + FlashAttention build and selects every column in the first chunk + (≤16 tokens) so the dense reference remains valid. +- Multi-request sparse and page-boundary sparse variants exercise per-request + `cu_seqlens_*` slicing inside `_dual_chunk_flash_attn_prefill_func`. +- Sub-window sparse prefill uses `vertical_size=4`, `slash_size=4`, and + `seq_len=128` to verify the DCA-specific content-aware top-k split and + empty-stage fallback against an independent reference, then verifies the + sparse output against a torch sparse-kernel reference that consumes the + production block/column metadata. +- Threshold-gated sparse uses `sparse_attention_threshold=100` so a 16-token + prompt bypasses the sparse kernel and falls through to the dense chunk + flash path, exercising the gate semantics in the wrapper. + +## Container Gate (SM10.x) + +`DualChunkFlashAttentionBackend` calls `flash_attn_varlen_func` via +`sglang.jit_kernel.flash_attention`. On SM8.x / SM9.x that resolves to sgl-kernel's +FA3 build; on SM != {8, 9} (notably SM10.x / GB300) the JIT kernel falls back +to the upstream `flash_attn` (FA2) wheel, which the +`lmsysorg/sglang:nightly-dev-cu13` container ships without an SM10.x-compiled +`flash_attn_varlen_func`. `test_dual_chunk_flash_attn.py` probes both paths at +module import: if FA3 is supported (`major in {8, 9}`) it runs unconditionally; +otherwise it tries `from flash_attn import flash_attn_varlen_func` and skips the +whole class with the documented reason if the symbol is missing. Re-image with +an SM10.x-compiled flash_attn wheel to clear; no test-code change needed. + +See `KNOWN_FAILURES.md` §1 for the full root cause + fix. + +## Production-Unsupported + +- **Non-prefill / non-decode forward modes** — + `dual_chunk_flashattention_backend.py:179` asserts + `forward_mode.is_prefill() or forward_mode.is_decode()`. `is_prefill()` + aliases to `is_extend()` (`forward_batch_info.py:103-104`) and covers + `EXTEND` / `MIXED` / `DRAFT_EXTEND` / `TARGET_VERIFY` / `SPLIT_PREFILL` / + `DLLM_EXTEND`, but `DRAFT_EXTEND_V2` is excluded by default. So + `DRAFT_EXTEND_V2` is structurally unreachable for `dual_chunk_flash_attn`. +- **Non-causal / windowed-attention requests** — `forward_extend` raises + `ValueError("Dual Chunk Attention does not support causal=False")` + (`dual_chunk_flashattention_backend.py:698`) and + `ValueError("Dual Chunk Attention does not support window_size")` + (`dual_chunk_flashattention_backend.py:700`). +- **Sparse mode `chunk_len % block_size != 0`** — raises + `ValueError("chunk_len must be divisible by block_size.")` + (`dual_chunk_flashattention_backend.py:860, 1491`). The current fixture + picks divisible values. +- **Unsupported `head_dim`** — only `head_dim in {16, 32, 64, 128, 256, 512}` + is accepted (`dual_chunk_flashattention_backend.py:1611`). + +## Next Work + +- Populate CUDA graph and PCG/BCG runner metadata after eager non-sparse + coverage is stable across more chunk layouts. +- **Broaden sub-window sparse coverage** — the current regression case covers + `prefix_lens=(0,)`, `extend_lens=(128,)`, and no GQA. Add + multi-request batches, nonzero prefixes, GQA, and more sparse config variants + once those paths need explicit sparse pruning coverage. The 64x64 + vertical/slash converter remains covered at the sgl-kernel layer. diff --git a/asian_ai/performance/SGLang/test/registered/attention/unittests/dual_chunk/__init__.py b/asian_ai/performance/SGLang/test/registered/attention/unittests/dual_chunk/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..1290d850031d339572bd16641b944783dff21ef0 --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/attention/unittests/dual_chunk/__init__.py @@ -0,0 +1 @@ +"""Dual-chunk attention unit-test package.""" diff --git a/asian_ai/performance/SGLang/test/registered/attention/unittests/dual_chunk/test_dual_chunk_flash_attn.py b/asian_ai/performance/SGLang/test/registered/attention/unittests/dual_chunk/test_dual_chunk_flash_attn.py new file mode 100644 index 0000000000000000000000000000000000000000..b4afcc5c4943ccb64183ce5844ecfd8aeb9e19f4 --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/attention/unittests/dual_chunk/test_dual_chunk_flash_attn.py @@ -0,0 +1,182 @@ +import sys +import unittest +from pathlib import Path + +import torch + +from sglang.srt.model_executor.forward_batch_info import ForwardMode +from sglang.test.test_utils import CustomTestCase + +sys.path.insert(0, str(Path(__file__).resolve().parents[1])) + +from sglang.test.kits.attention_unittest.attention_methods.dual_chunk_attention import ( + DualChunkAttentionCase, + make_dual_chunk_cases, + make_dual_chunk_sparse_cases, + make_dual_chunk_sparse_sub_window_cases, + make_dual_chunk_sparse_threshold_gated_cases, + run_dual_chunk_attention_case, + run_dual_chunk_sparse_attention_case, + run_dual_chunk_sparse_sub_window_case, + run_dual_chunk_sparse_threshold_gated_case, +) +from sglang.test.kits.attention_unittest.runner_modes.cuda_graph_decode_runner import ( + run_dual_chunk_cuda_graph_decode_case, +) + + +# Container gate (KNOWN_FAILURES.md §1): `DualChunkFlashAttentionBackend` calls +# `flash_attn_varlen_func` on every forward via +# `sglang.jit_kernel.flash_attention`. On SM8x/SM9x, that resolves to sgl-kernel's +# FA3 build (which works). On SM != {8, 9} (notably SM10.3 / GB300), the JIT +# kernel falls back to the upstream `flash_attn` (FA2) wheel — but the +# `lmsysorg/sglang:nightly-dev-cu13` container's `flash_attn` package ships +# without `flash_attn_varlen_func` on SM10.x, so every dual-chunk forward +# fails at import time inside the fallback. Skip the whole suite only when +# that fallback path is actually broken (not on Hopper, where we never enter it). +# Re-image the container with an SM10.3-compiled flash_attn wheel to clear. +def _dual_chunk_fa_supported() -> tuple[bool, str]: + if not torch.cuda.is_available(): + return False, "CUDA is required" + major, _minor = torch.cuda.get_device_capability() + # FA3 path is taken when sm major is 8 or 9 (see + # `sglang.jit_kernel.flash_attention_v3._is_fa3_supported`). On that path + # the upstream `flash_attn` fallback is never invoked. + if major in (8, 9): + return True, "" + # Otherwise (sm 7.x or sm >= 10.x) the JIT kernel falls back to upstream + # `flash_attn.flash_attn_varlen_func`. Probe it; if missing, skip. + try: + from flash_attn import ( # noqa: F401 + flash_attn_varlen_func as _flash_attn_varlen_func, + ) + + return True, "" + except ImportError as exc: + return False, ( + f"flash_attn_varlen_func is not available in upstream `flash_attn` " + f"(SM{major}.x JIT-kernel fallback): {exc}. " + f"Re-image the container with an SM{major}.x-compiled flash_attn wheel." + ) + + +_DUAL_CHUNK_FLASH_ATTN_AVAILABLE, _DUAL_CHUNK_SKIP_REASON = _dual_chunk_fa_supported() + + +from sglang.test.ci.ci_register import register_cuda_ci + +register_cuda_ci(est_time=20, stage="base-b", runner_config="4-gpu-b200") +register_cuda_ci(est_time=20, stage="base-b", runner_config="1-gpu-large") + + +@unittest.skipIf(not torch.cuda.is_available(), "CUDA is required") +@unittest.skipIf(not _DUAL_CHUNK_FLASH_ATTN_AVAILABLE, _DUAL_CHUNK_SKIP_REASON) +class TestDualChunkFlashAttentionBackendCorrectness(CustomTestCase): + CASES = make_dual_chunk_cases("dual_chunk_flash_attn") + SPARSE_CASES = make_dual_chunk_sparse_cases("dual_chunk_flash_attn") + SPARSE_THRESHOLD_GATED_CASES = make_dual_chunk_sparse_threshold_gated_cases( + "dual_chunk_flash_attn" + ) + SPARSE_SUB_WINDOW_CASES = make_dual_chunk_sparse_sub_window_cases( + "dual_chunk_flash_attn" + ) + # Replay prefix_lens must each be >= capture_prefix_len (= fill-value - 1). + # Dual-chunk's `get_cuda_graph_seq_len_fill_value()` returns 1, so capture + # uses prefix=0. We pick a 3-request batch with varied lengths to exercise + # both the page-boundary and within-page slots. + CUDA_GRAPH_DECODE_CASES = ( + DualChunkAttentionCase( + name="runner_cuda_graph_dual_chunk_decode_page_boundary", + backend="dual_chunk_flash_attn", + forward_mode=ForwardMode.DECODE, + num_heads=4, + num_kv_heads=4, + page_size=16, + prefix_lens=(14, 15, 16), + ), + ) + + def test_projected_dual_chunk_attention_cases(self): + for case in self.CASES: + with self.subTest(case=case.name, backend=case.backend): + run_dual_chunk_attention_case(self, case) + + def test_sparse_dual_chunk_attention_cases(self): + for case in self.SPARSE_CASES: + with self.subTest(case=case.name, backend=case.backend): + run_dual_chunk_sparse_attention_case(self, case) + + def test_sparse_dual_chunk_threshold_gated_cases(self): + for case in self.SPARSE_THRESHOLD_GATED_CASES: + with self.subTest(case=case.name, backend=case.backend): + run_dual_chunk_sparse_threshold_gated_case(self, case) + + def test_sparse_dual_chunk_sub_window_cases(self): + for case in self.SPARSE_SUB_WINDOW_CASES: + with self.subTest(case=case.name, backend=case.backend): + run_dual_chunk_sparse_sub_window_case(self, case) + + def test_runner_mode_cuda_graph_decode_cases(self): + for case in self.CUDA_GRAPH_DECODE_CASES: + with self.subTest(case=case.name, backend=case.backend): + run_dual_chunk_cuda_graph_decode_case(self, case) + + # Layout-robustness. See dense/test_triton.py for the rationale. + # dual_chunk_flash_attn EXTEND fails on non_monotonic_extend with + # ~67% mismatch and max abs diff ~1.1. The dual-chunk prefill path + # uses `cu_seqlens_*` indexing into a contiguous K layout + # (see `_dual_chunk_flash_attn_prefill_func` in + # dual_chunk_flashattention_backend.py:834+), which assumes K for + # the new extend tokens is laid out contiguously in + # `[begin, end)` slot order. Scattering extend-token slots within a + # request breaks that contiguity. Documented as a known production + # limitation. + LAYOUT_ROBUSTNESS_CASES = ( + DualChunkAttentionCase( + name="layout_dual_chunk_extend_two_request", + backend="dual_chunk_flash_attn", + forward_mode=ForwardMode.EXTEND, + num_heads=4, + num_kv_heads=4, + page_size=16, + prefix_lens=(0, 0), + extend_lens=(16, 32), + ), + DualChunkAttentionCase( + name="layout_dual_chunk_decode_page_boundary", + backend="dual_chunk_flash_attn", + forward_mode=ForwardMode.DECODE, + num_heads=4, + num_kv_heads=4, + page_size=16, + prefix_lens=(14, 15, 16), + ), + ) + LAYOUT_KNOWN_FAILURES = { + ("layout_dual_chunk_extend_two_request", "non_monotonic_extend"): ( + "dual_chunk_flash_attn prefill uses cu_seqlens_* indexing " + "into contiguous K slots within an extend " + "(`_dual_chunk_flash_attn_prefill_func` in " + "dual_chunk_flashattention_backend.py:834+); scattered " + "extend-token slots break that contiguity." + ), + } + + def test_layout_robustness_cases(self): + for case in self.LAYOUT_ROBUSTNESS_CASES: + for layout in ("interleaved_pages", "non_monotonic_extend"): + if layout == "non_monotonic_extend" and case.forward_mode.is_decode(): + continue + reason = self.LAYOUT_KNOWN_FAILURES.get((case.name, layout)) + if reason is not None: + print( + f"[layout-known-failure] {case.name} x {layout}: {reason}", + flush=True, + ) + continue + with self.subTest(case=case.name, layout=layout): + run_dual_chunk_attention_case(self, case, loc_layout=layout) + + +if __name__ == "__main__": + unittest.main() diff --git a/asian_ai/performance/SGLang/test/registered/attention/unittests/gdn/README.md b/asian_ai/performance/SGLang/test/registered/attention/unittests/gdn/README.md new file mode 100644 index 0000000000000000000000000000000000000000..b7a483325438754b91a05e2e960c0b28ed8d9492 --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/attention/unittests/gdn/README.md @@ -0,0 +1,74 @@ +# GDN Attention Capability Matrix + +This folder covers GDN hybrid-linear attention with a full-attention backend +plus the Triton GDN linear-attention kernel. The backend in the column header +is the **full-attention** backend; the **linear-attention** kernel is always +the Triton GDN kernel. Expected outputs use a separate pure-PyTorch gated-delta +recurrence reference, not Triton/FLA GDN kernels. + +## Coverage Matrix + +Columns are runner modes; rows are full-attention backends (linear-attention +kernel = `triton` for all rows). Cells use: +- **✓ \** — exercised, with the config variants listed in the cell +- **—** — not applicable (no production path for this combination) +- **blocked: \** — production-unsupported, not a follow-up +- **deferred: \** — could land later, currently disabled + +| Full-attn backend | Eager Phase 2 | CG decode | PCG extend | BCG extend | Verify eager | Verify CG | DE eager | DE CG | DE-V2 CG | EAGLE-draft runner | EAGLE-DE runner | FKVMTP runner | +|---|---|---|---|---|---|---|---|---|---|---|---|---| +| `torch_native` | ✓ full representative GDN input sweep | — (no CG hooks on `TorchNativeAttnBackend`) | ✓ ragged page-boundary extend | ✓ ragged page-boundary extend | — | — | — | — | — | — | — | — | +| `triton` | ✓ full representative GDN input sweep | ✓ decode page-boundary | ✓ ragged page-boundary extend | ✓ ragged page-boundary extend | ✓ EAGLE chain (topk=1) + EAGLE tree (topk=2) | ✓ EAGLE chain + EAGLE tree (tree uses scoped `5e-2` atol for bf16 recurrent accumulation) | — | blocked: HybridLinearAttnBackend `_replay_metadata` rejects modes outside `DECODE_OR_IDLE` / `TARGET_VERIFY` (`hybrid_linear_attn_backend.py:509,572`) | blocked: same `_replay_metadata` reject | — | blocked: same `_replay_metadata` reject | — | +| `flashinfer` | ✓ full GDN sweep with `head_dim=64` (FlashInfer SM90 prefill constraint) | ✓ decode page-boundary | ✓ ragged page-boundary extend | ✓ ragged page-boundary extend | ✓ EAGLE chain (topk=1) + EAGLE tree (topk=2) | ✓ EAGLE chain + EAGLE tree (scoped `5e-2` atol) | — | blocked: same `_replay_metadata` reject | blocked: same `_replay_metadata` reject | — | blocked: same `_replay_metadata` reject | — | + +## Hybrid dispatch fan-out tests (Triton only, MagicMock-based) + +These cover the `HybridLinearAttnBackend` dispatch layer itself (not numerical +correctness). Each test constructs a `HybridLinearAttnBackend` with two +`MagicMock` sub-backends and asserts both receive the matching call. + +| Test | Mutation covered | +|---|---| +| `test_hybrid_dispatch_eager_init_forward_metadata_fan_out` | M20 — `attn_backend_list[1:]` slice in `init_forward_metadata` (`hybrid_linear_attn_backend.py:825-827`) | +| `test_hybrid_dispatch_replay_init_forward_metadata_fan_out` | M19 — `attn_backend_list[:1]` slice in `init_forward_metadata_replay_cuda_graph` (`hybrid_linear_attn_backend.py:879-900`) | +| `test_hybrid_dispatch_capture_init_forward_metadata_fan_out` | Symmetric capture coverage (not in mutation journal) | + +## Input And Config Coverage + +- Page size 1, exact-page, crossing-page, ragged page-boundary, page-size-32 + crossing, decode boundary, and batch-size-1 decode cases. +- GDN uses speculative Mamba state buffers for target verify coverage. +- The split-op tests verify live-token slicing with a larger static token + buffer. + +## Production-Unsupported + +- **HybridLinearAttnBackend CUDA-graph capture/replay outside + `DECODE_OR_IDLE` / `TARGET_VERIFY`** — `MambaAttnBackendBase._capture_metadata` + / `_replay_metadata` (`hybrid_linear_attn_backend.py:493-572`) raise + `ValueError(f"Invalid forward mode: {forward_mode=}")` for anything else. + This is the underlying contract for GDN's `Mamba2AttnBackend`, KDA, + Lightning, and Mamba2. So `DRAFT_EXTEND` / `DRAFT_EXTEND_V2` CUDA-graph + capture/replay is structurally unreachable for the GDN linear-attention + side. +- **HybridLinearAttnBackend `_forward_metadata` modes** — same file + (`hybrid_linear_attn_backend.py:246`): non-decode, non-extend modes raise + `ValueError`. Legal modes are `is_decode_or_idle`, plus + `is_extend(include_draft_extend_v2=True)` (which subsumes `EXTEND` / + `MIXED` / `DRAFT_EXTEND` / `DRAFT_EXTEND_V2` / `TARGET_VERIFY` / + `SPLIT_PREFILL` / `DLLM_EXTEND` per `forward_batch_info.py:106-115`). + +## Caveats + +- **Initial SSM state is always zero.** `build_gdn_attention_fixture` does not + run prefix tokens through the actual module like dense's `_populate_prefix_kv` + does. The SSM state buffer stays at the runner's init zero state. Cases with + `prefix_lens > 0` therefore start from zero in both actual and reference + paths, so they match trivially — nonzero `prefix_lens` exercise metadata + paths only, not recurrent-state continuation. + +## Next Work + +- Add additional linear-attention kernel backend variants when available. +- Consider broader speculative worker tags only after EAGLE chain/tree remains + stable across kernels. diff --git a/asian_ai/performance/SGLang/test/registered/attention/unittests/gdn/__init__.py b/asian_ai/performance/SGLang/test/registered/attention/unittests/gdn/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/asian_ai/performance/SGLang/test/registered/attention/unittests/gdn/test_flashinfer.py b/asian_ai/performance/SGLang/test/registered/attention/unittests/gdn/test_flashinfer.py new file mode 100644 index 0000000000000000000000000000000000000000..f772665af275ce85d3a9a8f674333350d89d0315 --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/attention/unittests/gdn/test_flashinfer.py @@ -0,0 +1,326 @@ +import sys +import unittest +from pathlib import Path + +import torch + +from sglang.srt.model_executor.forward_batch_info import ForwardMode +from sglang.srt.utils import is_flashinfer_available +from sglang.test.test_utils import CustomTestCase + +sys.path.insert(0, str(Path(__file__).resolve().parents[1])) + +from sglang.test.ci.ci_register import register_cuda_ci +from sglang.test.kits.attention_unittest.attention_methods.gdn_attention import ( + GDNAttentionCase, + make_gdn_cases, + run_gdn_attention_case, +) +from sglang.test.kits.attention_unittest.runner_modes.cuda_graph_decode_runner import ( + run_gdn_cuda_graph_decode_case, +) +from sglang.test.kits.attention_unittest.runner_modes.speculative_target_verify_runner import ( + run_gdn_eagle_verify_case, + run_gdn_eagle_verify_cuda_graph_case, +) +from sglang.test.kits.attention_unittest.runner_modes.split_op_runner import ( + run_gdn_split_op_extend_case, +) + +register_cuda_ci(est_time=20, stage="base-b", runner_config="4-gpu-b200") +register_cuda_ci(est_time=20, stage="base-b", runner_config="1-gpu-large") + + +@unittest.skipIf( + not torch.cuda.is_available() or not is_flashinfer_available(), + "CUDA + flashinfer are required", +) +class TestFlashInferGDNBackendCorrectness(CustomTestCase): + # FlashInfer SM90 prefill kernels require value head dim in {64, 128, 256}. + HEAD_K_DIM = 64 + HEAD_V_DIM = 64 + + CASES = make_gdn_cases("flashinfer") + CUDA_GRAPH_CASES = ( + GDNAttentionCase( + name="runner_cuda_graph_gdn_decode_page_boundary", + backend="flashinfer", + forward_mode=ForwardMode.DECODE, + num_k_heads=2, + num_v_heads=2, + page_size=16, + prefix_lens=(14, 15, 16), + ), + ) + SPLIT_OP_CASES = ( + ( + GDNAttentionCase( + name="runner_split_op_gdn_extend_ragged_page_boundary", + backend="flashinfer", + forward_mode=ForwardMode.EXTEND, + num_k_heads=2, + num_v_heads=2, + page_size=16, + prefix_lens=(0, 8, 16), + extend_lens=(15, 8, 1), + ), + 32, + ), + ) + EAGLE_VERIFY_CASES = ( + ( + GDNAttentionCase( + name="runner_eagle_verify_gdn_chain", + backend="flashinfer", + forward_mode=ForwardMode.TARGET_VERIFY, + num_k_heads=2, + num_v_heads=2, + page_size=16, + prefix_lens=(4, 7), + extend_lens=(3, 3), + ), + 1, + "eagle", + ), + ( + GDNAttentionCase( + name="runner_eagle_verify_gdn_tree", + backend="flashinfer", + forward_mode=ForwardMode.TARGET_VERIFY, + num_k_heads=2, + num_v_heads=2, + page_size=16, + prefix_lens=(5, 6), + extend_lens=(3, 3), + ), + 2, + "eagle", + ), + ( + GDNAttentionCase( + name="runner_frozen_kv_mtp_verify_gdn_chain", + backend="flashinfer", + forward_mode=ForwardMode.TARGET_VERIFY, + num_k_heads=2, + num_v_heads=2, + page_size=16, + prefix_lens=(4, 7), + extend_lens=(3, 3), + ), + 1, + "frozen_kv_mtp", + ), + ( + GDNAttentionCase( + name="runner_dflash_verify_gdn_chain", + backend="flashinfer", + forward_mode=ForwardMode.TARGET_VERIFY, + num_k_heads=2, + num_v_heads=2, + page_size=16, + prefix_lens=(4, 7), + extend_lens=(3, 3), + ), + 1, + "dflash", + ), + ( + GDNAttentionCase( + name="runner_ngram_verify_gdn_chain", + backend="flashinfer", + forward_mode=ForwardMode.TARGET_VERIFY, + num_k_heads=2, + num_v_heads=2, + page_size=16, + prefix_lens=(4, 7), + extend_lens=(3, 3), + ), + 1, + "ngram", + ), + ) + EAGLE_VERIFY_CUDA_GRAPH_CASES = ( + ( + GDNAttentionCase( + name="runner_cuda_graph_eagle_verify_gdn_chain", + backend="flashinfer", + forward_mode=ForwardMode.TARGET_VERIFY, + num_k_heads=2, + num_v_heads=2, + page_size=16, + prefix_lens=(4, 7), + extend_lens=(3, 3), + ), + 1, + "eagle", + ), + ( + GDNAttentionCase( + name="runner_cuda_graph_eagle_verify_gdn_tree", + backend="flashinfer", + forward_mode=ForwardMode.TARGET_VERIFY, + num_k_heads=2, + num_v_heads=2, + page_size=16, + prefix_lens=(5, 6), + extend_lens=(3, 3), + ), + 2, + "eagle", + ), + ( + GDNAttentionCase( + name="runner_cuda_graph_frozen_kv_mtp_verify_gdn_chain", + backend="flashinfer", + forward_mode=ForwardMode.TARGET_VERIFY, + num_k_heads=2, + num_v_heads=2, + page_size=16, + prefix_lens=(4, 7), + extend_lens=(3, 3), + ), + 1, + "frozen_kv_mtp", + ), + ( + GDNAttentionCase( + name="runner_cuda_graph_dflash_verify_gdn_chain", + backend="flashinfer", + forward_mode=ForwardMode.TARGET_VERIFY, + num_k_heads=2, + num_v_heads=2, + page_size=16, + prefix_lens=(4, 7), + extend_lens=(3, 3), + ), + 1, + "dflash", + ), + ( + GDNAttentionCase( + name="runner_cuda_graph_ngram_verify_gdn_chain", + backend="flashinfer", + forward_mode=ForwardMode.TARGET_VERIFY, + num_k_heads=2, + num_v_heads=2, + page_size=16, + prefix_lens=(4, 7), + extend_lens=(3, 3), + ), + 1, + "ngram", + ), + ) + + def test_projected_gdn_attention_cases(self): + for case in self.CASES: + with self.subTest(case=case.name, backend=case.backend): + run_gdn_attention_case( + self, + case, + head_k_dim=self.HEAD_K_DIM, + head_v_dim=self.HEAD_V_DIM, + ) + + # Layout-robustness. See dense/test_triton.py for the rationale. + LAYOUT_ROBUSTNESS_CASES = ( + GDNAttentionCase( + name="layout_gdn_extend_two_request", + backend="flashinfer", + forward_mode=ForwardMode.EXTEND, + num_k_heads=4, + num_v_heads=4, + page_size=16, + prefix_lens=(0, 0), + extend_lens=(16, 16), + ), + GDNAttentionCase( + name="layout_gdn_decode_page_boundary", + backend="flashinfer", + forward_mode=ForwardMode.DECODE, + num_k_heads=4, + num_v_heads=4, + page_size=16, + prefix_lens=(14, 15, 16), + ), + ) + + def test_layout_robustness_cases(self): + for case in self.LAYOUT_ROBUSTNESS_CASES: + for layout in ("interleaved_pages", "non_monotonic_extend"): + if layout == "non_monotonic_extend" and case.forward_mode.is_decode(): + continue + with self.subTest(case=case.name, layout=layout): + run_gdn_attention_case( + self, + case, + head_k_dim=self.HEAD_K_DIM, + head_v_dim=self.HEAD_V_DIM, + loc_layout=layout, + ) + + def test_runner_mode_cuda_graph_decode_cases(self): + for case in self.CUDA_GRAPH_CASES: + with self.subTest(case=case.name, backend=case.backend): + run_gdn_cuda_graph_decode_case( + self, + case, + head_k_dim=self.HEAD_K_DIM, + head_v_dim=self.HEAD_V_DIM, + ) + + def test_runner_mode_split_op_extend_cases(self): + for case, static_num_tokens in self.SPLIT_OP_CASES: + for breakable in (False, True): + runner = "bcg" if breakable else "pcg" + with self.subTest( + case=case.name, + backend=case.backend, + runner=runner, + ): + run_gdn_split_op_extend_case( + self, + case, + breakable=breakable, + static_num_tokens=static_num_tokens, + head_k_dim=self.HEAD_K_DIM, + head_v_dim=self.HEAD_V_DIM, + ) + + def test_runner_mode_eagle_verify_cases(self): + for case, topk, spec_kind in self.EAGLE_VERIFY_CASES: + with self.subTest( + case=case.name, + backend=case.backend, + topk=topk, + spec_kind=spec_kind, + ): + run_gdn_eagle_verify_case( + self, + case, + topk=topk, + spec_kind=spec_kind, + head_k_dim=self.HEAD_K_DIM, + head_v_dim=self.HEAD_V_DIM, + ) + + def test_runner_mode_eagle_verify_cuda_graph_cases(self): + for case, topk, spec_kind in self.EAGLE_VERIFY_CUDA_GRAPH_CASES: + with self.subTest( + case=case.name, + backend=case.backend, + topk=topk, + spec_kind=spec_kind, + ): + run_gdn_eagle_verify_cuda_graph_case( + self, + case, + topk=topk, + spec_kind=spec_kind, + head_k_dim=self.HEAD_K_DIM, + head_v_dim=self.HEAD_V_DIM, + ) + + +if __name__ == "__main__": + unittest.main() diff --git a/asian_ai/performance/SGLang/test/registered/attention/unittests/gdn/test_linear_replayssm_decode.py b/asian_ai/performance/SGLang/test/registered/attention/unittests/gdn/test_linear_replayssm_decode.py new file mode 100644 index 0000000000000000000000000000000000000000..d43a3a9a6b59a99f3d2b501e12b8f1eee1a635e9 --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/attention/unittests/gdn/test_linear_replayssm_decode.py @@ -0,0 +1,344 @@ +"""Correctness test for the buffered output-only linear-attention decode kernel +(ReplaySSM Part A), implemented in +``python/sglang/srt/layers/attention/fla/fused_recurrent_linear_replayssm.py``. + +One kernel, two gate granularities (selected by ``is_kda``): + * GDN (``is_kda=False``): per-head SCALAR gate. Ground truth = + ``fused_recurrent_gated_delta_rule_packed_decode`` (fused_recurrent.py:186). + * KDA (``is_kda=True``): per-K-channel gate. Ground truth = + ``fused_recurrent_kda_packed_decode`` (fused_recurrent.py:406). The KDA + baseline takes the per-K gate flattened (``a``=[B, HV*K], ``dt_bias``=[HV*K]); + the ReplaySSM kernel takes it as [B, HV, K] / [HV, K]. Same memory layout, + so we build [B, HV, K] / [HV, K] and reshape for the baseline. + +We run a multi-step decode through BOTH kernels and assert: + * per-step outputs ``y`` match, AND + * the ground-truth full state matches the ReplaySSM checkpoint *after a flush* + (folding the ring buffer into S0). At a non-flush step the ReplaySSM + checkpoint legitimately lags (the update lives in the ring), so we only + compare state at flush boundaries / after a forced flush. + +L sweep: + * L=1 (flush every step): the ring is always empty and ``write_pos == L-1`` + every step, so the reconstruction term is zero, the total decay is 1, and + the kernel reduces to the packed decode. For GDN the only fp difference is a + scalar ``alpha*(sum x)`` vs ``sum(alpha*x)`` reorder, so we assert ~bit-exact + (atol 2e-6). For KDA the analogous reorder is per-K (``alpha[k]`` folded into + q/k vs into S0), bounded by ~K*eps, so KDA uses the same (tighter-than-L>1) + tensor-core tolerances rather than 2e-6. + * L in {4,8,16}: algebraically equivalent but floating-point reordered (cumsum + of gates, replay-decay scaling, the d@k reconstruction dot on tensor cores + vs. the materialized recurrence). Tight fp tolerance, see ``_tols``. + +Runnable as ``pytest`` and as ``__main__``. +""" + +import sys +import unittest +from pathlib import Path + +import torch + +from sglang.test.test_utils import CustomTestCase + +# Mirror sibling GDN unittests: register for CUDA/AMD CI. This is a kernel-math +# unit test; it lives with the other linear-attention kernel correctness tests. +# The registry calls MUST be module-level (the CI collector / check-registered- +# tests hook parses them statically via AST and only scans top-level statements +# -- a try/except wrapper hides them and fails the hook). +sys.path.insert(0, str(Path(__file__).resolve().parents[1])) +from sglang.test.ci.ci_register import register_amd_ci, register_cuda_ci + +register_cuda_ci(est_time=20, stage="base-b", runner_config="1-gpu-large") +register_amd_ci(est_time=20, suite="stage-b-test-1-gpu-large-amd") + + +def _build_inputs(B, H, HV, K, V, dtype, device, seed=0, is_kda=False): + """Random packed-decode inputs for one step. + + Returns a packed ``mixed_qkv`` [B, 2*H*K + HV*V] plus the per-row gate + inputs. ``b`` (beta) is [B, HV] for both gate types. ``a`` is [B, HV] for + the GDN scalar gate and [B, HV, K] for the KDA per-K gate. + """ + g = torch.Generator(device=device).manual_seed(seed) + qk_dim = 2 * H * K + v_dim = HV * V + mixed_qkv = torch.randn(B, qk_dim + v_dim, generator=g, device=device, dtype=dtype) + # Keep gate input `a` modest so softplus / decay stay in a stable range. + if is_kda: + a = ( + torch.randn(B, HV, K, generator=g, device=device, dtype=dtype) * 0.5 + ).contiguous() + else: + a = torch.randn(B, HV, generator=g, device=device, dtype=dtype) * 0.5 + b = torch.randn(B, HV, generator=g, device=device, dtype=dtype) + return mixed_qkv, a, b + + +def _tols(dtype): + # L>1 reconstructs the state via a tensor-core tl.dot (TF32 for fp32 inputs, + # bf16 tensor cores for bf16) -- the performance-critical path that keeps the + # L-deep reconstruction hidden under the reduced memory traffic. TF32 carries + # ~4e-4 error, bf16 ~1e-3, both benign end-to-end (ReplaySSM GSM8K parity); + # vLLM's own ReplaySSM test uses fp32 atol 1e-4. GDN L=1 has an empty buffer + # (dot == 0) and is asserted bit-exact separately. + if dtype == torch.float32: + return dict(atol=1e-4, rtol=1e-3) + return dict(atol=1e-3, rtol=1e-2) # bf16 + + +@unittest.skipIf(not torch.cuda.is_available(), "CUDA is required") +class TestLinearReplaySSMDecode(CustomTestCase): + # Small config: HV=8 or 16 heads, K=V=128, batch B=4. + CONFIGS = ( + dict(B=4, H=4, HV=8, K=128, V=128), + dict(B=4, H=8, HV=16, K=128, V=128), + ) + NUM_STEPS = 40 # > 16 -> multiple flush cycles for L in {4,8,16} + L_SWEEP = (1, 4, 8, 16) + + def _run_one(self, cfg, L, dtype, force_flush_steps=(), is_kda=False): + from sglang.srt.layers.attention.fla.fused_recurrent import ( + fused_recurrent_gated_delta_rule_packed_decode, + fused_recurrent_kda_packed_decode, + ) + from sglang.srt.layers.attention.fla.fused_recurrent_linear_replayssm import ( + fused_recurrent_linear_replayssm_decode, + ) + + device = "cuda" + B, H, HV, K, V = (cfg[x] for x in ("B", "H", "HV", "K", "V")) + scale = K**-0.5 + + # Shared static params across steps. A_log is per-head [HV] for both + # gate types; dt_bias is per-head [HV] (GDN) or per-K [HV, K] (KDA). + A_log = (torch.randn(HV, device=device, dtype=torch.float32) * 0.3).contiguous() + if is_kda: + dt_bias = ( + torch.randn(HV, K, device=device, dtype=torch.float32) * 0.1 + ).contiguous() + else: + dt_bias = ( + torch.randn(HV, device=device, dtype=torch.float32) * 0.1 + ).contiguous() + + # Two independent state pools (same init), one per kernel. One slot/req. + num_slots = B + # Seed the state init so the marginal bf16 flush-state element is + # reproducible run-to-run (otherwise the pass/fail at the tolerance + # boundary flickers with the global RNG). + sg = torch.Generator(device=device).manual_seed(2024) + ref_state = torch.randn( + num_slots, HV, V, K, generator=sg, device=device, dtype=torch.float32 + ) + rep_state = ref_state.clone() + cache_indices = torch.arange(B, device=device, dtype=torch.int32) + + # ReplaySSM ring tensors (caller-owned; this increment's caller == test). + # g_cache is per-step scalar [HV, L] for GDN, per-K [HV, L, K] for KDA. + d_cache = torch.zeros(num_slots, HV, L, V, device=device, dtype=dtype) + k_cache = torch.zeros(num_slots, H, L, K, device=device, dtype=dtype) + if is_kda: + g_cache = torch.zeros( + num_slots, HV, L, K, device=device, dtype=torch.float32 + ) + else: + g_cache = torch.zeros(num_slots, HV, L, device=device, dtype=torch.float32) + write_pos = torch.zeros(B, device=device, dtype=torch.int32) + + tols = _tols(dtype) + flush_step_seen = False + + for step in range(self.NUM_STEPS): + mixed_qkv, a, b = _build_inputs( + B, H, HV, K, V, dtype, device, seed=1000 + step, is_kda=is_kda + ) + + # ---- ground truth: packed decode, full-state write every step ---- + ref_out = mixed_qkv.new_empty(B, 1, HV, V) + if is_kda: + # KDA baseline takes the per-K gate flattened: a=[B, HV*K], + # dt_bias=[HV*K] (same memory as our [B, HV, K] / [HV, K]). + fused_recurrent_kda_packed_decode( + mixed_qkv=mixed_qkv, + a=a.reshape(B, HV * K).contiguous(), + b=b, + A_log=A_log, + dt_bias=dt_bias.reshape(HV * K).contiguous(), + scale=scale, + initial_state=ref_state, + out=ref_out, + ssm_state_indices=cache_indices, + use_qk_l2norm_in_kernel=True, + ) + else: + fused_recurrent_gated_delta_rule_packed_decode( + mixed_qkv=mixed_qkv, + a=a, + b=b, + A_log=A_log, + dt_bias=dt_bias, + scale=scale, + initial_state=ref_state, + out=ref_out, + ssm_state_indices=cache_indices, + use_qk_l2norm_in_kernel=True, + ) + + # ---- ReplaySSM buffered decode for this L ---- + rep_out = mixed_qkv.new_empty(B, 1, HV, V) + # slice 2: force a flush at a radix track boundary even mid-buffer. + force_now = step in force_flush_steps + ff_tensor = ( + torch.ones(B, device=device, dtype=torch.int32) if force_now else None + ) + is_flush = bool((write_pos[0].item()) == L - 1) or force_now + flush_step_seen = flush_step_seen or is_flush + fused_recurrent_linear_replayssm_decode( + mixed_qkv=mixed_qkv, + a=a, + b=b, + A_log=A_log, + dt_bias=dt_bias, + scale=scale, + initial_state=rep_state, + d_cache=d_cache, + k_cache=k_cache, + g_cache=g_cache, + out=rep_out, + ssm_state_indices=cache_indices, + write_pos=write_pos, + force_flush=ff_tensor, + use_qk_l2norm_in_kernel=True, + is_kda=is_kda, + # nk=1 at L=1 keeps the K-reduction in a single tile (no + # K-tiling), matching the reference's single-pass reduction; + # nk=2 for L>1 exercises the K-tiled reconstruction path. + nk=1 if L == 1 else 2, + ) + + # Output must match every step. + if dtype == torch.float32 and L == 1 and not is_kda: + # GDN L=1: essentially bit-exact -- only an alpha*(sum) vs + # sum(alpha*) scalar-multiply reordering separates this from the + # reference. (KDA L=1 has the analogous per-K reorder, bounded by + # ~K*eps, so it uses the regular tensor-core tolerance below.) + torch.testing.assert_close( + rep_out, + ref_out, + atol=2e-6, + rtol=1e-5, + msg=f"GDN L=1 step={step} out", + ) + else: + torch.testing.assert_close( + rep_out, + ref_out, + msg=f"is_kda={is_kda} L={L} step={step} out", + **tols, + ) + + # On a flush step the ReplaySSM checkpoint is brought fully + # up-to-date and the ring logically clears -> compare states. + if is_flush: + if dtype == torch.float32 and L == 1 and not is_kda: + torch.testing.assert_close( + rep_state, + ref_state, + atol=2e-6, + rtol=1e-5, + msg=f"GDN L=1 step={step} state", + ) + else: + # The flush state is reconstructed via the tensor-core dot, + # so it carries tensor-core precision: ~tf32 (~4e-4, measured + # max_abs ~7e-4) for fp32, ~bf16 (measured max_abs ~1.9e-3) + # for bf16 -- looser than the per-step OUTPUT, which passes at + # the tighter output tol because the tf32/bf16 error partly + # cancels in the q-reduction. The per-step decay (alpha<1) + # attenuates old reconstruction error so it does not + # accumulate across flushes over a long decode; e2e accuracy + # is unaffected (ReplaySSM GSM8K parity). + state_tols = ( + dict(atol=1.5e-3, rtol=1e-3) + if dtype == torch.float32 + else dict(atol=3e-3, rtol=1e-2) + ) + torch.testing.assert_close( + rep_state, + ref_state, + msg=f"is_kda={is_kda} L={L} step={step} state(flush)", + **state_tols, + ) + + # Advance the ring cursor (caller's responsibility in this phase): + # wrap to 0 after a flush (natural L-1 OR a forced track-boundary + # flush), otherwise increment. + if force_now: + write_pos = torch.zeros_like(write_pos) + else: + write_pos = torch.where( + write_pos == L - 1, + torch.zeros_like(write_pos), + write_pos + 1, + ) + + # Explicit wrap/flush boundary must have been exercised for L>1; for + # L=1 every step is a flush. + self.assertTrue(flush_step_seen, f"flush boundary never hit for L={L}") + + # ---- GDN (scalar gate) ---- + def test_replayssm_matches_gdn_packed_decode_fp32(self): + for cfg in self.CONFIGS: + for L in self.L_SWEEP: + with self.subTest(cfg=cfg, L=L, dtype="fp32"): + self._run_one(cfg, L, torch.float32) + + def test_replayssm_matches_gdn_packed_decode_bf16(self): + for cfg in self.CONFIGS: + for L in self.L_SWEEP: + with self.subTest(cfg=cfg, L=L, dtype="bf16"): + self._run_one(cfg, L, torch.bfloat16) + + # ---- KDA (per-K gate) ---- + def test_replayssm_matches_kda_packed_decode_fp32(self): + for cfg in self.CONFIGS: + for L in self.L_SWEEP: + with self.subTest(cfg=cfg, L=L, dtype="fp32"): + self._run_one(cfg, L, torch.float32, is_kda=True) + + def test_replayssm_matches_kda_packed_decode_bf16(self): + for cfg in self.CONFIGS: + for L in self.L_SWEEP: + with self.subTest(cfg=cfg, L=L, dtype="bf16"): + self._run_one(cfg, L, torch.bfloat16, is_kda=True) + + # ---- forced (radix track-boundary) flush, both gate types ---- + def test_force_flush_matches_reference(self): + """A radix track-boundary forces a flush mid-buffer (write_pos != L-1). + The kernel must fold the partial ring + current token into the + checkpoint so an external snapshot reads an up-to-date state; output + every step and the forced-flush checkpoint must still match the running + recurrence -- for both the GDN scalar gate and the KDA per-K gate.""" + cfg = dict(B=4, H=8, HV=16, K=128, V=128) + for is_kda in (False, True): + for dtype in (torch.float32, torch.bfloat16): + with self.subTest(is_kda=is_kda, dtype=str(dtype)): + self._run_one( + cfg, + L=8, + dtype=dtype, + force_flush_steps=(3, 5, 11, 20), + is_kda=is_kda, + ) + + def test_flush_boundary_state_exact_l1(self): + """At L=1 (GDN) every step is a flush; the kernel is algebraically the + packed decode. Each step reproduces the reference output AND the full + state to atol 2e-6 / rtol 1e-5 (essentially bit-exact) in fp32. This also + exercises the ``write_pos == L-1`` flush boundary on every step.""" + self._run_one(dict(B=4, H=4, HV=8, K=128, V=128), L=1, dtype=torch.float32) + + +if __name__ == "__main__": + unittest.main() diff --git a/asian_ai/performance/SGLang/test/registered/attention/unittests/gdn/test_torch_native.py b/asian_ai/performance/SGLang/test/registered/attention/unittests/gdn/test_torch_native.py new file mode 100644 index 0000000000000000000000000000000000000000..8fc377905b479f009584038902fb1ff29f0b1f1e --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/attention/unittests/gdn/test_torch_native.py @@ -0,0 +1,106 @@ +import sys +import unittest +from pathlib import Path + +import torch + +from sglang.srt.model_executor.forward_batch_info import ForwardMode +from sglang.srt.utils import is_hip +from sglang.test.test_utils import CustomTestCase + +sys.path.insert(0, str(Path(__file__).resolve().parents[1])) + +from sglang.test.ci.ci_register import register_amd_ci, register_cuda_ci +from sglang.test.kits.attention_unittest.attention_methods.gdn_attention import ( + GDNAttentionCase, + make_gdn_cases, + run_gdn_attention_case, +) +from sglang.test.kits.attention_unittest.runner_modes.split_op_runner import ( + run_gdn_split_op_extend_case, +) + +register_cuda_ci(est_time=20, stage="base-b", runner_config="4-gpu-b200") +register_cuda_ci(est_time=20, stage="base-b", runner_config="1-gpu-large") +register_amd_ci(est_time=20, suite="stage-b-test-1-gpu-large-amd") + + +@unittest.skipIf(not torch.cuda.is_available(), "CUDA is required") +class TestTorchNativeGDNBackendCorrectness(CustomTestCase): + CASES = make_gdn_cases("torch_native") + SPLIT_OP_CASES = ( + ( + GDNAttentionCase( + name="runner_split_op_gdn_extend_ragged_page_boundary", + backend="torch_native", + forward_mode=ForwardMode.EXTEND, + num_k_heads=2, + num_v_heads=2, + page_size=16, + prefix_lens=(0, 8, 16), + extend_lens=(15, 8, 1), + ), + 32, + ), + ) + + def test_projected_gdn_attention_cases(self): + for case in self.CASES: + with self.subTest(case=case.name, backend=case.backend): + run_gdn_attention_case(self, case) + + # Layout-robustness. See dense/test_triton.py for the rationale. + LAYOUT_ROBUSTNESS_CASES = ( + GDNAttentionCase( + name="layout_gdn_extend_two_request", + backend="torch_native", + forward_mode=ForwardMode.EXTEND, + num_k_heads=4, + num_v_heads=4, + page_size=16, + prefix_lens=(0, 0), + extend_lens=(16, 16), + ), + GDNAttentionCase( + name="layout_gdn_decode_page_boundary", + backend="torch_native", + forward_mode=ForwardMode.DECODE, + num_k_heads=4, + num_v_heads=4, + page_size=16, + prefix_lens=(14, 15, 16), + ), + ) + + def test_layout_robustness_cases(self): + for case in self.LAYOUT_ROBUSTNESS_CASES: + for layout in ("interleaved_pages", "non_monotonic_extend"): + if layout == "non_monotonic_extend" and case.forward_mode.is_decode(): + continue + with self.subTest(case=case.name, layout=layout): + run_gdn_attention_case(self, case, loc_layout=layout) + + @unittest.skipIf( + is_hip(), + "split-op extend runner exercises the piecewise-CUDA-graph path " + "(TcPiecewiseForwardContext.num_tokens), which is not wired on ROCm.", + ) + def test_runner_mode_split_op_extend_cases(self): + for case, static_num_tokens in self.SPLIT_OP_CASES: + for breakable in (False, True): + runner = "bcg" if breakable else "pcg" + with self.subTest( + case=case.name, + backend=case.backend, + runner=runner, + ): + run_gdn_split_op_extend_case( + self, + case, + breakable=breakable, + static_num_tokens=static_num_tokens, + ) + + +if __name__ == "__main__": + unittest.main() diff --git a/asian_ai/performance/SGLang/test/registered/attention/unittests/gdn/test_triton.py b/asian_ai/performance/SGLang/test/registered/attention/unittests/gdn/test_triton.py new file mode 100644 index 0000000000000000000000000000000000000000..51c14dc4eea213c0710b089bdfc3c4864541b31f --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/attention/unittests/gdn/test_triton.py @@ -0,0 +1,411 @@ +import sys +import unittest +from pathlib import Path +from types import SimpleNamespace +from unittest.mock import MagicMock + +import torch + +from sglang.srt.layers.attention.hybrid_linear_attn_backend import ( + HybridLinearAttnBackend, + MambaAttnBackendBase, +) +from sglang.srt.model_executor.forward_batch_info import ForwardMode +from sglang.srt.utils import is_hip +from sglang.test.test_utils import CustomTestCase + +sys.path.insert(0, str(Path(__file__).resolve().parents[1])) + +from sglang.test.ci.ci_register import register_amd_ci, register_cuda_ci +from sglang.test.kits.attention_unittest.attention_methods.gdn_attention import ( + GDNAttentionCase, + make_gdn_cases, + run_gdn_attention_case, +) +from sglang.test.kits.attention_unittest.runner_modes.cuda_graph_decode_runner import ( + run_gdn_cuda_graph_decode_case, +) +from sglang.test.kits.attention_unittest.runner_modes.speculative_target_verify_runner import ( + run_gdn_eagle_verify_case, + run_gdn_eagle_verify_cuda_graph_case, +) +from sglang.test.kits.attention_unittest.runner_modes.split_op_runner import ( + run_gdn_split_op_extend_case, +) + +register_cuda_ci(est_time=20, stage="base-b", runner_config="4-gpu-b200") +register_cuda_ci(est_time=20, stage="base-b", runner_config="1-gpu-large") +register_amd_ci(est_time=20, suite="stage-b-test-1-gpu-large-amd") + + +@unittest.skipIf(not torch.cuda.is_available(), "CUDA is required") +class TestTritonGDNBackendCorrectness(CustomTestCase): + CASES = make_gdn_cases("triton") + CUDA_GRAPH_CASES = ( + GDNAttentionCase( + name="runner_cuda_graph_gdn_decode_page_boundary", + backend="triton", + forward_mode=ForwardMode.DECODE, + num_k_heads=2, + num_v_heads=2, + page_size=16, + prefix_lens=(14, 15, 16), + ), + ) + SPLIT_OP_CASES = ( + ( + GDNAttentionCase( + name="runner_split_op_gdn_extend_ragged_page_boundary", + backend="triton", + forward_mode=ForwardMode.EXTEND, + num_k_heads=2, + num_v_heads=2, + page_size=16, + prefix_lens=(0, 8, 16), + extend_lens=(15, 8, 1), + ), + 32, + ), + ) + # GDN verify covers EAGLE chain/tree plus the non-EAGLE chain spec + # kinds (frozen_kv_mtp, dflash, ngram). All three pass against the + # pure-PyTorch gated-delta recurrence reference; the GDN backend + # treats them uniformly via the spec_info custom/tree mask. + EAGLE_VERIFY_CASES = ( + ( + GDNAttentionCase( + name="runner_eagle_verify_gdn_chain", + backend="triton", + forward_mode=ForwardMode.TARGET_VERIFY, + num_k_heads=2, + num_v_heads=2, + page_size=16, + prefix_lens=(4, 7), + extend_lens=(3, 3), + ), + 1, + "eagle", + ), + ( + GDNAttentionCase( + name="runner_eagle_verify_gdn_tree", + backend="triton", + forward_mode=ForwardMode.TARGET_VERIFY, + num_k_heads=2, + num_v_heads=2, + page_size=16, + prefix_lens=(5, 6), + extend_lens=(3, 3), + ), + 2, + "eagle", + ), + ( + GDNAttentionCase( + name="runner_frozen_kv_mtp_verify_gdn_chain", + backend="triton", + forward_mode=ForwardMode.TARGET_VERIFY, + num_k_heads=2, + num_v_heads=2, + page_size=16, + prefix_lens=(4, 7), + extend_lens=(3, 3), + ), + 1, + "frozen_kv_mtp", + ), + ( + GDNAttentionCase( + name="runner_dflash_verify_gdn_chain", + backend="triton", + forward_mode=ForwardMode.TARGET_VERIFY, + num_k_heads=2, + num_v_heads=2, + page_size=16, + prefix_lens=(4, 7), + extend_lens=(3, 3), + ), + 1, + "dflash", + ), + ( + GDNAttentionCase( + name="runner_ngram_verify_gdn_chain", + backend="triton", + forward_mode=ForwardMode.TARGET_VERIFY, + num_k_heads=2, + num_v_heads=2, + page_size=16, + prefix_lens=(4, 7), + extend_lens=(3, 3), + ), + 1, + "ngram", + ), + ) + EAGLE_VERIFY_CUDA_GRAPH_CASES = ( + ( + GDNAttentionCase( + name="runner_cuda_graph_eagle_verify_gdn_chain", + backend="triton", + forward_mode=ForwardMode.TARGET_VERIFY, + num_k_heads=2, + num_v_heads=2, + page_size=16, + prefix_lens=(4, 7), + extend_lens=(3, 3), + ), + 1, + "eagle", + ), + ( + GDNAttentionCase( + name="runner_cuda_graph_eagle_verify_gdn_tree", + backend="triton", + forward_mode=ForwardMode.TARGET_VERIFY, + num_k_heads=2, + num_v_heads=2, + page_size=16, + prefix_lens=(5, 6), + extend_lens=(3, 3), + ), + 2, + "eagle", + ), + ( + GDNAttentionCase( + name="runner_cuda_graph_frozen_kv_mtp_verify_gdn_chain", + backend="triton", + forward_mode=ForwardMode.TARGET_VERIFY, + num_k_heads=2, + num_v_heads=2, + page_size=16, + prefix_lens=(4, 7), + extend_lens=(3, 3), + ), + 1, + "frozen_kv_mtp", + ), + ( + GDNAttentionCase( + name="runner_cuda_graph_dflash_verify_gdn_chain", + backend="triton", + forward_mode=ForwardMode.TARGET_VERIFY, + num_k_heads=2, + num_v_heads=2, + page_size=16, + prefix_lens=(4, 7), + extend_lens=(3, 3), + ), + 1, + "dflash", + ), + ( + GDNAttentionCase( + name="runner_cuda_graph_ngram_verify_gdn_chain", + backend="triton", + forward_mode=ForwardMode.TARGET_VERIFY, + num_k_heads=2, + num_v_heads=2, + page_size=16, + prefix_lens=(4, 7), + extend_lens=(3, 3), + ), + 1, + "ngram", + ), + ) + + def test_projected_gdn_attention_cases(self): + for case in self.CASES: + with self.subTest(case=case.name, backend=case.backend): + run_gdn_attention_case(self, case) + + # Layout-robustness. See dense/test_triton.py for the rationale. + # shuffled_pages is the default for all tests; this method opts + # into the more aggressive interleaved_pages + non_monotonic_extend. + # GDN Triton handles all non-tidy layouts cleanly. + LAYOUT_ROBUSTNESS_CASES = ( + GDNAttentionCase( + name="layout_gdn_extend_two_request", + backend="triton", + forward_mode=ForwardMode.EXTEND, + num_k_heads=4, + num_v_heads=4, + page_size=16, + prefix_lens=(0, 0), + extend_lens=(16, 16), + ), + GDNAttentionCase( + name="layout_gdn_decode_page_boundary", + backend="triton", + forward_mode=ForwardMode.DECODE, + num_k_heads=4, + num_v_heads=4, + page_size=16, + prefix_lens=(14, 15, 16), + ), + ) + + def test_layout_robustness_cases(self): + for case in self.LAYOUT_ROBUSTNESS_CASES: + for layout in ("interleaved_pages", "non_monotonic_extend"): + if layout == "non_monotonic_extend" and case.forward_mode.is_decode(): + continue + with self.subTest(case=case.name, layout=layout): + run_gdn_attention_case(self, case, loc_layout=layout) + + def test_runner_mode_cuda_graph_decode_cases(self): + for case in self.CUDA_GRAPH_CASES: + with self.subTest(case=case.name, backend=case.backend): + run_gdn_cuda_graph_decode_case(self, case) + + @unittest.skipIf( + is_hip(), + "split-op extend runner exercises the piecewise-CUDA-graph path " + "(TcPiecewiseForwardContext.num_tokens), which is not wired on ROCm.", + ) + def test_runner_mode_split_op_extend_cases(self): + for case, static_num_tokens in self.SPLIT_OP_CASES: + for breakable in (False, True): + runner = "bcg" if breakable else "pcg" + with self.subTest( + case=case.name, + backend=case.backend, + runner=runner, + ): + run_gdn_split_op_extend_case( + self, + case, + breakable=breakable, + static_num_tokens=static_num_tokens, + ) + + def test_runner_mode_eagle_verify_cases(self): + for case, topk, spec_kind in self.EAGLE_VERIFY_CASES: + with self.subTest( + case=case.name, + backend=case.backend, + topk=topk, + spec_kind=spec_kind, + ): + run_gdn_eagle_verify_case(self, case, topk=topk, spec_kind=spec_kind) + + def test_runner_mode_eagle_verify_cuda_graph_cases(self): + for case, topk, spec_kind in self.EAGLE_VERIFY_CUDA_GRAPH_CASES: + with self.subTest( + case=case.name, + backend=case.backend, + topk=topk, + spec_kind=spec_kind, + ): + run_gdn_eagle_verify_cuda_graph_case( + self, case, topk=topk, spec_kind=spec_kind + ) + + # Spy directly on each sub-backend's `init_forward_metadata*` so + # dispatch-layer slice mutations show up as a missing call, which + # forward-output assertions can miss when the fixture happens to + # use identical capture/replay metadata. + + def _make_dispatch_spy_backend(self): + full_attn_backend = MagicMock(name="full_attn_backend") + # `HybridLinearAttnBackend.__init__` aliases these buffer refs. + full_attn_backend.token_to_kv_pool = object() + full_attn_backend.req_to_token_pool = object() + + linear_attn_backend = MagicMock( + spec=MambaAttnBackendBase, name="linear_attn_backend" + ) + + backend = HybridLinearAttnBackend( + full_attn_backend, + linear_attn_backend, + full_attn_layers=[], + ) + return backend, full_attn_backend, linear_attn_backend + + @staticmethod + def _assert_fanout_forwarded(method_mock, *sentinels): + """Assert `method_mock` was called exactly once and that each sentinel + object identity is present in the call's positional or keyword args. + Tolerates production switching between positional / keyword arg + forwarding (the previous `assert_called_once_with(*positional)` form + would silently break on such a refactor).""" + method_mock.assert_called_once() + call = method_mock.call_args + forwarded = list(call.args) + list(call.kwargs.values()) + for sentinel in sentinels: + if not any(v is sentinel for v in forwarded): + raise AssertionError( + f"sentinel {sentinel!r} not forwarded by " + f"{method_mock._mock_name or method_mock}; call_args={call}" + ) + + def test_hybrid_dispatch_eager_init_forward_metadata_fan_out(self): + backend, full_attn_backend, linear_attn_backend = ( + self._make_dispatch_spy_backend() + ) + # Sentinel exposes the attribute production reads at the dispatch + # gate (`forward_mode.is_draft_extend_v2()`); returns False so the + # fan-out path that delegates to both children is exercised, which + # is what these spy tests assert. + sentinel_forward_batch = SimpleNamespace( + forward_mode=SimpleNamespace(is_draft_extend_v2=lambda: False) + ) + backend.init_forward_metadata(sentinel_forward_batch) + self._assert_fanout_forwarded( + full_attn_backend.init_forward_metadata, sentinel_forward_batch + ) + self._assert_fanout_forwarded( + linear_attn_backend.init_forward_metadata, sentinel_forward_batch + ) + + def _make_sentinel_fb(self): + return SimpleNamespace( + batch_size=3, + forward_mode=ForwardMode.DECODE, + req_pool_indices=object(), + seq_lens=object(), + seq_lens_cpu=object(), + seq_lens_sum=42, + spec_info=object(), + encoder_lens=None, + positions=object(), + input_ids=object(), + out_cache_loc=None, + ) + + def test_hybrid_dispatch_replay_init_forward_metadata_fan_out(self): + backend, full_attn_backend, linear_attn_backend = ( + self._make_dispatch_spy_backend() + ) + + fb = self._make_sentinel_fb() + backend.init_forward_metadata_out_graph(fb) + + # We assert sentinel identity rather than exact (args, kwargs) shape + # so a positional↔keyword refactor inside `HybridLinearAttnBackend` + # doesn't trip the test as long as the fb still flows through. + for sub_backend in (full_attn_backend, linear_attn_backend): + self._assert_fanout_forwarded( + sub_backend.init_forward_metadata_out_graph, fb + ) + + def test_hybrid_dispatch_capture_init_forward_metadata_fan_out(self): + # Capture mirrors the eager/replay loop shape; a slice mutation + # there would silently miss without a spy. + backend, full_attn_backend, linear_attn_backend = ( + self._make_dispatch_spy_backend() + ) + fb = self._make_sentinel_fb() + backend.init_forward_metadata_out_graph(fb, in_capture=True) + + for sub_backend in (full_attn_backend, linear_attn_backend): + self._assert_fanout_forwarded( + sub_backend.init_forward_metadata_out_graph, fb + ) + + +if __name__ == "__main__": + unittest.main() diff --git a/asian_ai/performance/SGLang/test/registered/attention/unittests/hybrid_linear/README.md b/asian_ai/performance/SGLang/test/registered/attention/unittests/hybrid_linear/README.md new file mode 100644 index 0000000000000000000000000000000000000000..3b69362fdd92ad04951e73eddff5b869ec16e1dc --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/attention/unittests/hybrid_linear/README.md @@ -0,0 +1,64 @@ +# Hybrid linear-attention backend unit tests + +These tests cover `HybridLinearAttnBackend` — the wrapper that combines a +**full-attention** backend (DeepSeek-style MLA, e.g. `FlashInferMLAAttnBackend`) +with a **linear-attention** backend (GDN / Mamba2 / KDA / Lightning) for hybrid +models such as Ring/Ling (`bailing_moe_linear`), Qwen3-Next, NemotronH, etc. + +## Why this folder exists (the coverage gap) + +The per-method suites under `../mla`, `../gdn`, `../mamba`, ... each test one +backend in isolation. None of them exercise the **interaction** between the +wrapper and a real MLA full-attention backend during prefill: + +- `../mla/*` drives a **bare** `FlashInferMLAAttnBackend`, never the hybrid + wrapper. It also builds its mock runner with + `disable_chunked_prefix_cache=True` + `flashinfer_mla_disable_ragged=True` + (`kits/attention_unittest/attention_methods/mla_attention.py`), so the + `MHA_ONE_SHOT` / `MHA_CHUNKED_KV` prefill paths are never run. +- `../gdn`, `../kda`, ... *do* wrap in `HybridLinearAttnBackend`, but with + `full_attn_layers=[]` — so the full-attention (MLA) path inside the wrapper is + never reached. + +That gap hid a real production crash: the MLA prefill path plans its flashinfer +ragged wrapper via + +```python +if hasattr(get_attn_backend(), "init_mha_chunk_metadata"): + get_attn_backend().init_mha_chunk_metadata(forward_batch) +``` + +For a hybrid model `get_attn_backend()` returns the **wrapper**. The wrapper did +not expose `init_mha_chunk_metadata`, so the guard was silently False, the +`qo_indptr` / `kv_indptr` were never planned, and flashinfer aborted with: + +``` +ValueError: q.shape[0] (8218) does not match qo_indptr[-1] (800). +``` + +Fix: `HybridLinearAttnBackend.init_mha_chunk_metadata` delegates to the +full-attention backend (`hybrid_linear_attn_backend.py`). + +## Tests + +| File | What it pins | +|---|---| +| `test_flashinfer_mla_chunk_metadata.py` | Wraps a real chunk-KV-enabled `FlashInferMLAAttnBackend` (`full_attn_layers=[0]`) and asserts (1) the wrapper exposes `init_mha_chunk_metadata` and (2) the delegated call plans `qo_indptr[-1]` to the true extend-token count. | + +Run on a CUDA host: + +```bash +FLASHINFER_DISABLE_VERSION_CHECK=1 \ + python -m pytest test/registered/attention/unittests/hybrid_linear/ -v +``` + +## Next work + +- Reusable `kits/attention_unittest/attention_methods/hybrid_linear_attention.py` + helper that composes `full=MLA + linear=` with a + non-empty `full_attn_layers`, then drives a real + `DeepseekV2AttentionMLA.forward_normal_one_shot_core` / + `forward_normal_chunked_kv_core` prefill end-to-end (with numerical reference) + rather than asserting on planned metadata alone. The tiny `kv_lora_rank=32` + MLA config used here is too small for the flashinfer *ragged* prefill kernel's + head-dim constraints, so a true e2e variant needs production-sized head dims. diff --git a/asian_ai/performance/SGLang/test/registered/attention/unittests/hybrid_linear/__init__.py b/asian_ai/performance/SGLang/test/registered/attention/unittests/hybrid_linear/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/asian_ai/performance/SGLang/test/registered/attention/unittests/hybrid_linear/test_flashinfer_mla_chunk_metadata.py b/asian_ai/performance/SGLang/test/registered/attention/unittests/hybrid_linear/test_flashinfer_mla_chunk_metadata.py new file mode 100644 index 0000000000000000000000000000000000000000..fe36cd6d7ca26c81dd63d92e373d60465add4c50 --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/attention/unittests/hybrid_linear/test_flashinfer_mla_chunk_metadata.py @@ -0,0 +1,145 @@ +"""Regression test: HybridLinearAttnBackend delegates init_mha_chunk_metadata. + +Hybrid MLA models (Ring/Ling, Kimi-Linear) run DeepSeek-style MLA on their +full-attention layers. Prefill plans the flashinfer ragged wrapper via +``hasattr(get_attn_backend(), "init_mha_chunk_metadata")`` (forward_mha.py). +For a hybrid model ``get_attn_backend()`` is the HybridLinearAttnBackend wrapper; +when it lacked the hook the guard was False, qo_indptr/kv_indptr were never +planned, and flashinfer raised "q.shape[0] does not match qo_indptr[-1]". + +The per-method MLA suite misses this: it drives the bare backend, and its mock +runner sets disable_chunked_prefix_cache=True + flashinfer_mla_disable_ragged=True +so the chunked-MHA path never runs. +""" + +import unittest +from pathlib import Path +from types import SimpleNamespace + +import torch + +from sglang.srt.layers.attention.hybrid_linear_attn_backend import ( + HybridLinearAttnBackend, +) +from sglang.srt.model_executor.forward_batch_info import ForwardMode +from sglang.srt.server_args import set_global_server_args_for_scheduler +from sglang.test.ci.ci_register import register_cuda_ci +from sglang.test.kits.attention_unittest.attention_methods.mla_attention import ( + DEFAULT_KV_LORA_RANK, + DEFAULT_MAX_CONTEXT_LEN, + MLAAttentionCase, + MockMLAModelRunner, + TinyMLAModelConfig, + _make_forward_batch, +) +from sglang.test.test_utils import CustomTestCase + +register_cuda_ci(est_time=10, stage="base-b", runner_config="1-gpu-large") + + +_KV_LORA_RANK = DEFAULT_KV_LORA_RANK +_QK_ROPE_HEAD_DIM = 0 + + +class _ChunkKVMLARunner(MockMLAModelRunner): + """MLA mock runner with chunked-prefix-cache (ragged MHA) enabled.""" + + def __init__(self, **kwargs): + super().__init__(**kwargs) + self.server_args.disable_chunked_prefix_cache = False + self.server_args.flashinfer_mla_disable_ragged = False + set_global_server_args_for_scheduler(self.server_args) + + +def _make_case() -> MLAAttentionCase: + return MLAAttentionCase( + name="hybrid_one_shot_prefix", + backend="flashinfer", + forward_mode=ForwardMode.EXTEND, + num_heads=4, + page_size=1, + prefix_lens=(8, 4), + extend_lens=(5, 3), + ) + + +def _build_hybrid_backend(testcase, case: MLAAttentionCase): + model_config = TinyMLAModelConfig( + num_heads=case.num_heads, + kv_lora_rank=_KV_LORA_RANK, + qk_rope_head_dim=_QK_ROPE_HEAD_DIM, + hidden_size=64, + context_len=DEFAULT_MAX_CONTEXT_LEN, + ) + runner = _ChunkKVMLARunner( + case=case, + model_config=model_config, + dtype=torch.float16, + device="cuda", + max_context_len=DEFAULT_MAX_CONTEXT_LEN, + kv_lora_rank=_KV_LORA_RANK, + qk_rope_head_dim=_QK_ROPE_HEAD_DIM, + disable_cuda_graph=True, + disable_piecewise_cuda_graph=True, + runner_batch_size=None, + fp8_kv_cache=False, + ) + try: + from sglang.srt.layers.attention.flashinfer_mla_backend import ( + FlashInferMLAAttnBackend, + ) + + full_backend = FlashInferMLAAttnBackend(runner) + except (AssertionError, ImportError, ModuleNotFoundError) as exc: + testcase.skipTest(f"flashinfer MLA backend is not available: {exc}") + + if not getattr(full_backend, "enable_chunk_kv", False): + testcase.skipTest("chunk-KV path not enabled on this build") + + # full_attn_layers=[0] routes layer 0 through the MLA backend, as a hybrid + # model's full-attention layers do. The linear backend is unused here. + hybrid = HybridLinearAttnBackend( + full_backend, SimpleNamespace(), full_attn_layers=[0] + ) + return runner, full_backend, hybrid + + +@unittest.skipIf(not torch.cuda.is_available(), "CUDA is required") +class TestHybridLinearChunkMetadataDelegation(CustomTestCase): + def test_wrapper_exposes_chunk_metadata_hook(self): + _, full_backend, hybrid = _build_hybrid_backend(self, _make_case()) + self.assertTrue(hasattr(hybrid, "init_mha_chunk_metadata")) + self.assertTrue(hasattr(full_backend, "init_mha_chunk_metadata")) + + def test_delegation_plans_qo_indptr(self): + case = _make_case() + runner, full_backend, hybrid = _build_hybrid_backend(self, case) + + forward_batch = _make_forward_batch( + case, + runner, + max_context_len=DEFAULT_MAX_CONTEXT_LEN, + device="cuda", + ) + forward_batch.num_prefix_chunks = 0 + + bs = case.batch_size + sentinel = 999 + full_backend.qo_indptr[bs] = sentinel + + # disable_flashinfer_ragged=True plans qo_indptr without flashinfer calls. + hybrid.init_mha_chunk_metadata(forward_batch, disable_flashinfer_ragged=True) + + # qo_indptr[-1] must equal the extend (query) token count; a stale value + # here is the root cause of the q.shape[0] != qo_indptr[-1] crash. + planned = full_backend.mha_chunk_kv_cache.qo_indptr[bs].item() + self.assertEqual(planned, case.num_input_tokens) + self.assertNotEqual(planned, sentinel) + + +if __name__ == "__main__": + sys_path_parent = str(Path(__file__).resolve().parents[1]) + import sys + + sys.path.insert(0, sys_path_parent) + unittest.main() diff --git a/asian_ai/performance/SGLang/test/registered/attention/unittests/kda/README.md b/asian_ai/performance/SGLang/test/registered/attention/unittests/kda/README.md new file mode 100644 index 0000000000000000000000000000000000000000..797a54889bcc6b60fb63f49f06a3da70dc7514de --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/attention/unittests/kda/README.md @@ -0,0 +1,45 @@ +# KDA Attention Capability Matrix + +This folder covers KDA (Kimi Delta Attention) linear attention. The actual +path drives `KDAAttnBackend` through `HybridLinearAttnBackend` on a +`RadixLinearAttention` layer. Expected outputs come from an independent +pure-PyTorch sigmoid-gated delta-rule reference using +`KimiLinearCacheParams` / `KimiLinearStateShape` (per-head-channel `dt_bias`, +`silu` activation on conv1d output, per-channel gate broadcast), not the KDA +Triton kernel. + +## Coverage Matrix + +Columns are runner modes; rows are the linear-attention kernel backend +(`triton` is the only one wired today). Cells use: +- **✓ \** — exercised, with the config variants listed in the cell +- **—** — not applicable / not exercised +- **blocked: \** — production-unsupported, not a follow-up +- **deferred: \** — could land later, currently disabled + +| Linear-attn kernel | Eager Phase 2 | CG decode | PCG extend | BCG extend | Verify eager | Verify CG | DE eager | DE CG | DE-V2 CG | EAGLE-draft runner | EAGLE-DE runner | FKVMTP runner | +|---|---|---|---|---|---|---|---|---|---|---|---|---| +| `triton` | ✓ 10 input layouts (page 1/16/32, prefix/decode edges) | ✓ decode page-boundary (uses `KDA_GRAPH_ATOL=1e-1` to absorb Triton recurrent-kernel CG-replay drift; eager `KDA_ATOL=3e-2` kept for non-graph cases) | ✓ ragged page-boundary extend | ✓ ragged page-boundary extend | ✓ EAGLE chain (topk=1) + EAGLE tree (topk=2) (`atol=1e-1` because the verify reference's pure-Python per-token recurrence drifts ~0.07 vs the Triton kernel even before CG capture/replay) | ✓ EAGLE chain CG + EAGLE tree CG (same `1e-1` tolerance) | — | blocked: HybridLinearAttnBackend `_replay_metadata` rejects modes outside `DECODE_OR_IDLE` / `TARGET_VERIFY` (`hybrid_linear_attn_backend.py:509,572`) | blocked: same `_replay_metadata` reject | deferred | blocked: same `_replay_metadata` reject | — | + +## Input And Config Coverage + +- 10 input variants from `make_kda_cases('triton')`: page 1, exact-page, + crossing-page, ragged page-boundary, page-size-32 crossing, decode + page-boundary, batch-size-1 decode. +- `num_k_heads=2, num_v_heads=2` with head dims defaulted by + `DEFAULT_HEAD_K_DIM = DEFAULT_HEAD_V_DIM = 32`. + +## Production-Unsupported + +- **CUDA-graph capture/replay outside `DECODE_OR_IDLE` / `TARGET_VERIFY`** — + KDA inherits the same `MambaAttnBackendBase` capture/replay path as GDN, + so `ValueError("Invalid forward mode")` at + `hybrid_linear_attn_backend.py:509, 572` rejects `DRAFT_EXTEND` / + `DRAFT_EXTEND_V2` / `EXTEND` graph runners. Any Phase 4 KDA draft-extend + graph runner is structurally unreachable. + +## Next Work + +- Consider additional KDA kernel backend variants when available. CG + decode, PCG/BCG split-op extend, and EAGLE chain/tree verify + (eager + CG) are all wired (see matrix above). diff --git a/asian_ai/performance/SGLang/test/registered/attention/unittests/kda/__init__.py b/asian_ai/performance/SGLang/test/registered/attention/unittests/kda/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/asian_ai/performance/SGLang/test/registered/attention/unittests/kda/test_triton.py b/asian_ai/performance/SGLang/test/registered/attention/unittests/kda/test_triton.py new file mode 100644 index 0000000000000000000000000000000000000000..f46a921a0c544c653f38694c1b57c16100939c84 --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/attention/unittests/kda/test_triton.py @@ -0,0 +1,263 @@ +import sys +import unittest +from pathlib import Path + +import torch + +from sglang.srt.model_executor.forward_batch_info import ForwardMode +from sglang.srt.utils import is_hip +from sglang.test.test_utils import CustomTestCase + +sys.path.insert(0, str(Path(__file__).resolve().parents[1])) + +from sglang.test.ci.ci_register import register_amd_ci, register_cuda_ci +from sglang.test.kits.attention_unittest.attention_methods.kda_attention import ( + KDAAttentionCase, + make_kda_cases, + run_kda_attention_case, +) +from sglang.test.kits.attention_unittest.runner_modes.cuda_graph_decode_runner import ( + run_kda_cuda_graph_decode_case, +) +from sglang.test.kits.attention_unittest.runner_modes.speculative_target_verify_runner import ( + run_kda_eagle_verify_case, + run_kda_eagle_verify_cuda_graph_case, +) +from sglang.test.kits.attention_unittest.runner_modes.split_op_runner import ( + run_kda_split_op_extend_case, +) + +register_cuda_ci(est_time=20, stage="base-b", runner_config="4-gpu-b200") +register_cuda_ci(est_time=20, stage="base-b", runner_config="1-gpu-large") +register_amd_ci(est_time=20, suite="stage-b-test-1-gpu-large-amd") + + +@unittest.skipIf(not torch.cuda.is_available(), "CUDA is required") +class TestTritonKDABackendCorrectness(CustomTestCase): + CASES = make_kda_cases("triton") + # KDA inherits the same `MambaAttnBackendBase` capture/replay path as GDN + # through `HybridLinearAttnBackend`. See kda/README.md. + CUDA_GRAPH_CASES = ( + KDAAttentionCase( + name="runner_cuda_graph_kda_decode_page_boundary", + backend="triton", + forward_mode=ForwardMode.DECODE, + num_k_heads=2, + num_v_heads=2, + page_size=16, + prefix_lens=(14, 15, 16), + ), + ) + # KDA verify covers EAGLE chain/tree plus the three non-EAGLE chain + # spec kinds (frozen_kv_mtp / dflash / ngram). The non-EAGLE kinds + # use a slightly different draft-token mask layout — same recurrent + # math, but the per-token state replay accumulates enough drift that + # 1 / 384 elements lands at ~0.11 max diff against the default + # `KDA_ATOL=1e-1` tolerance. Use a looser `2e-1` tolerance for the + # non-EAGLE kinds (kernel-side correctness is unchanged; only the + # numerical headroom differs) so the matrix is complete. + EAGLE_VERIFY_CASES = ( + ( + KDAAttentionCase( + name="runner_eagle_verify_kda_chain", + backend="triton", + forward_mode=ForwardMode.TARGET_VERIFY, + num_k_heads=2, + num_v_heads=2, + page_size=16, + prefix_lens=(4, 7), + extend_lens=(3, 3), + ), + 1, + "eagle", + None, + ), + ( + KDAAttentionCase( + name="runner_eagle_verify_kda_tree", + backend="triton", + forward_mode=ForwardMode.TARGET_VERIFY, + num_k_heads=2, + num_v_heads=2, + page_size=16, + prefix_lens=(5, 6), + extend_lens=(3, 3), + ), + 2, + "eagle", + None, + ), + ( + KDAAttentionCase( + name="runner_frozen_kv_mtp_verify_kda_chain", + backend="triton", + forward_mode=ForwardMode.TARGET_VERIFY, + num_k_heads=2, + num_v_heads=2, + page_size=16, + prefix_lens=(4, 7), + extend_lens=(3, 3), + ), + 1, + "frozen_kv_mtp", + 2e-1, + ), + ( + KDAAttentionCase( + name="runner_dflash_verify_kda_chain", + backend="triton", + forward_mode=ForwardMode.TARGET_VERIFY, + num_k_heads=2, + num_v_heads=2, + page_size=16, + prefix_lens=(4, 7), + extend_lens=(3, 3), + ), + 1, + "dflash", + 2e-1, + ), + ( + KDAAttentionCase( + name="runner_ngram_verify_kda_chain", + backend="triton", + forward_mode=ForwardMode.TARGET_VERIFY, + num_k_heads=2, + num_v_heads=2, + page_size=16, + prefix_lens=(4, 7), + extend_lens=(3, 3), + ), + 1, + "ngram", + 2e-1, + ), + ) + EAGLE_VERIFY_CUDA_GRAPH_CASES = ( + ( + KDAAttentionCase( + name="runner_cuda_graph_eagle_verify_kda_chain", + backend="triton", + forward_mode=ForwardMode.TARGET_VERIFY, + num_k_heads=2, + num_v_heads=2, + page_size=16, + prefix_lens=(4, 7), + extend_lens=(3, 3), + ), + 1, + ), + ( + KDAAttentionCase( + name="runner_cuda_graph_eagle_verify_kda_tree", + backend="triton", + forward_mode=ForwardMode.TARGET_VERIFY, + num_k_heads=2, + num_v_heads=2, + page_size=16, + prefix_lens=(5, 6), + extend_lens=(3, 3), + ), + 2, + ), + ) + + def test_projected_kda_attention_cases(self): + for case in self.CASES: + with self.subTest(case=case.name, backend=case.backend): + run_kda_attention_case(self, case) + + # Layout-robustness. See dense/test_triton.py for the rationale. + LAYOUT_ROBUSTNESS_CASES = ( + KDAAttentionCase( + name="layout_kda_extend_two_request", + backend="triton", + forward_mode=ForwardMode.EXTEND, + num_k_heads=2, + num_v_heads=2, + page_size=16, + prefix_lens=(0, 0), + extend_lens=(16, 16), + ), + KDAAttentionCase( + name="layout_kda_decode_page_boundary", + backend="triton", + forward_mode=ForwardMode.DECODE, + num_k_heads=2, + num_v_heads=2, + page_size=16, + prefix_lens=(14, 15, 16), + ), + ) + + def test_layout_robustness_cases(self): + for case in self.LAYOUT_ROBUSTNESS_CASES: + for layout in ("interleaved_pages", "non_monotonic_extend"): + if layout == "non_monotonic_extend" and case.forward_mode.is_decode(): + continue + with self.subTest(case=case.name, layout=layout): + run_kda_attention_case(self, case, loc_layout=layout) + + def test_runner_mode_cuda_graph_decode_cases(self): + for case in self.CUDA_GRAPH_CASES: + with self.subTest(case=case.name, backend=case.backend): + run_kda_cuda_graph_decode_case(self, case) + + def test_runner_mode_eagle_verify_cases(self): + for case, topk, spec_kind, atol_override in self.EAGLE_VERIFY_CASES: + with self.subTest( + case=case.name, + backend=case.backend, + topk=topk, + spec_kind=spec_kind, + ): + kwargs = dict(topk=topk, spec_kind=spec_kind) + if atol_override is not None: + kwargs.update(atol=atol_override, rtol=atol_override) + run_kda_eagle_verify_case(self, case, **kwargs) + + def test_runner_mode_eagle_verify_cuda_graph_cases(self): + for case, topk in self.EAGLE_VERIFY_CUDA_GRAPH_CASES: + with self.subTest(case=case.name, backend=case.backend, topk=topk): + run_kda_eagle_verify_cuda_graph_case(self, case, topk=topk) + + SPLIT_OP_CASES = ( + ( + KDAAttentionCase( + name="runner_split_op_kda_extend_ragged_page_boundary", + backend="triton", + forward_mode=ForwardMode.EXTEND, + num_k_heads=2, + num_v_heads=2, + page_size=16, + prefix_lens=(0, 8, 16), + extend_lens=(15, 8, 1), + ), + 32, + ), + ) + + @unittest.skipIf( + is_hip(), + "split-op extend runner exercises the piecewise-CUDA-graph path " + "(TcPiecewiseForwardContext.num_tokens), which is not wired on ROCm.", + ) + def test_runner_mode_split_op_extend_cases(self): + for case, static_num_tokens in self.SPLIT_OP_CASES: + for breakable in (False, True): + runner = "bcg" if breakable else "pcg" + with self.subTest( + case=case.name, + backend=case.backend, + runner=runner, + ): + run_kda_split_op_extend_case( + self, + case, + breakable=breakable, + static_num_tokens=static_num_tokens, + ) + + +if __name__ == "__main__": + unittest.main() diff --git a/asian_ai/performance/SGLang/test/registered/attention/unittests/lightning/README.md b/asian_ai/performance/SGLang/test/registered/attention/unittests/lightning/README.md new file mode 100644 index 0000000000000000000000000000000000000000..0e34fa0399b4cd0a15df74c44dfbbf81ed345f05 --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/attention/unittests/lightning/README.md @@ -0,0 +1,75 @@ +# Lightning Attention Capability Matrix + +This folder covers Bailing-style segmented linear attention (`seg_la`). The +actual path wraps `RadixAttention` and installs `LightningAttentionBackend` +directly via `ForwardContext`, since Lightning's layer wrapper is plain +`RadixAttention` and `HybridLinearAttnBackend` would route it to the full +backend. Expected outputs come from an independent pure-PyTorch per-token +`seg_la` recurrence reference (`state_t = state_{t-1} * exp(-slope_h) + +outer(k_t, v_t)`, `o_t = q_t @ state_t * head_dim**-0.5`). + +## Coverage Matrix + +Columns are runner modes; rows are the linear-attention kernel backend +(`triton` is the only one wired today). Cells use: +- **✓ \** — exercised, with the config variants listed in the cell +- **—** — not applicable / not exercised +- **blocked: \** — production-unsupported, not a follow-up +- **deferred: \** — could land later, currently disabled + +| Linear-attn kernel | Eager Phase 2 | CG decode | PCG extend | BCG extend | Verify eager | Verify CG | DE eager | DE CG | DE-V2 CG | EAGLE-draft runner | EAGLE-DE runner | FKVMTP runner | +|---|---|---|---|---|---|---|---|---|---|---|---|---| +| `triton` | ✓ 10 input layouts (page 1/16/32, prefix/decode edges) | ✓ decode page-boundary (uses `LIGHTNING_GRAPH_ATOL=1e-1` to absorb seg_la kernel CG-replay drift; eager `LIGHTNING_ATOL=3e-2` kept for non-graph cases) | deferred: piecewise CG path returns per-head shape via `RadixAttention.forward`'s `empty_like(q)`, but Lightning backend's `forward_extend` flattens to `[T, num_heads * head_dim]`; eager vs piecewise actuals don't share a shape. See "Production-Unsupported" below. | deferred (same reason) | ✓ EAGLE chain (topk=1) only — see "Production-Unsupported" below for why tree is omitted. Uses `atol=1e-1` because the verify reference's pure-Python per-token recurrence drifts ~0.07 vs the seg_la Triton kernel. | ✓ EAGLE chain CG (same `1e-1` tolerance) | — | blocked: HybridLinearAttnBackend `_replay_metadata` rejects modes outside `DECODE_OR_IDLE` / `TARGET_VERIFY` (`hybrid_linear_attn_backend.py:509,572`) | blocked: same `_replay_metadata` reject | deferred | blocked: same `_replay_metadata` reject | — | + +## Input And Config Coverage + +- 10 input variants from `make_lightning_cases('triton')`: page 1, + exact-page, crossing-page, ragged page-boundary, page-size-32 crossing, + decode page-boundary, batch-size-1 decode. +- `num_heads=2` with `DEFAULT_HEAD_DIM=128`. Head dim is intentionally 128 + because the `seg_la` Triton kernels constrain it: + - decode (`seg_la_d_kernel`): `K_SPLIT_DIM=128`, so `head_dim >= 128`. + - prefill with `bs > 2` (`seg_la_p_kernel`): `V_SPLIT_DIM=64`, so + `head_dim >= 64`. + +## Production-Unsupported + +- **`raise ValueError` paths in `LightningAttentionBackend`** — + `lightning_backend.py:332, 369` reject configurations the seg_la kernels + do not support; the head-dim constraints above are the practical + entry-point guards. +- **CUDA-graph capture/replay outside `DECODE_OR_IDLE` / `TARGET_VERIFY`** — + Lightning inherits the `MambaAttnBackendBase` capture/replay contract, so + `ValueError("Invalid forward mode")` at `hybrid_linear_attn_backend.py:509, + 572` applies. Draft-extend graph runners are structurally unreachable. +- **EAGLE tree (topk>1) verify** — `seg_la.py` has no parent-indices / + retrieve-index plumbing; the kernel processes draft tokens as a chain + regardless of the input tree shape. A tree-shaped verify produces + large divergence (~5x off) vs the parent-indices-aware reference. The + `intermediate_state_indices` / `intermediate_ssm` plumbing in + `lightning_backend.py:307-329` is per-request, not per-token, so it + cannot replay parent state forks. Only chain (topk=1) is covered. +- **PCG / BCG split-op extend** — Lightning's `forward_extend` flattens + to `[T, num_heads * head_dim]` at `lightning_backend.py:335`, but + under piecewise CG `RadixAttention.forward` + (`radix_attention.py:124-137`) writes through `output = + torch.empty_like(q)` of per-head shape `[T, num_heads, head_dim]`, + ignoring the backend's intended flatten. The shared + `_run_split_op_extend_case` compares eager vs piecewise actuals, + which then trip a shape mismatch. KDA and GDN avoid this because + their backends keep the per-head shape on the return path. Fixing + needs either a Lightning-specific split-op runner that reshapes + actual to flat, or a Lightning backend change to keep per-head shape + under piecewise CG. + +## Next Work + +- PCG/BCG split-op extend needs either a Lightning-specific split-op + runner that reshapes piecewise actual to flat, or a backend-side + change to keep per-head shape under piecewise CG. See + "Production-Unsupported" above. +- EAGLE tree verify is gated by the `seg_la` kernel itself (no + parent-indices support); landing it requires a kernel-side change to + thread parent indices through `intermediate_ssm` so each draft token + forks from its parent's saved state rather than the prior chain + position. Out of scope for unit tests. diff --git a/asian_ai/performance/SGLang/test/registered/attention/unittests/lightning/__init__.py b/asian_ai/performance/SGLang/test/registered/attention/unittests/lightning/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/asian_ai/performance/SGLang/test/registered/attention/unittests/lightning/test_triton.py b/asian_ai/performance/SGLang/test/registered/attention/unittests/lightning/test_triton.py new file mode 100644 index 0000000000000000000000000000000000000000..804c0391a6ae21291d92bb6dbf06faf31c6d9b75 --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/attention/unittests/lightning/test_triton.py @@ -0,0 +1,202 @@ +import sys +import unittest +from pathlib import Path + +import torch + +from sglang.srt.model_executor.forward_batch_info import ForwardMode +from sglang.test.test_utils import CustomTestCase + +sys.path.insert(0, str(Path(__file__).resolve().parents[1])) + +from sglang.test.ci.ci_register import register_amd_ci, register_cuda_ci +from sglang.test.kits.attention_unittest.attention_methods.lightning_attention import ( + LightningAttentionCase, + make_lightning_cases, + run_lightning_attention_case, +) +from sglang.test.kits.attention_unittest.runner_modes.cuda_graph_decode_runner import ( + run_lightning_cuda_graph_decode_case, +) +from sglang.test.kits.attention_unittest.runner_modes.speculative_target_verify_runner import ( + run_lightning_eagle_verify_case, + run_lightning_eagle_verify_cuda_graph_case, +) + +register_cuda_ci(est_time=20, stage="base-b", runner_config="4-gpu-b200") +register_cuda_ci(est_time=20, stage="base-b", runner_config="1-gpu-large") +register_amd_ci(est_time=20, suite="stage-b-test-1-gpu-large-amd") + + +@unittest.skipIf(not torch.cuda.is_available(), "CUDA is required") +class TestTritonLightningBackendCorrectness(CustomTestCase): + CASES = make_lightning_cases("triton") + # Lightning installs `LightningAttentionBackend` directly via + # `ForwardContext` (not through `HybridLinearAttnBackend`), but the + # `MambaAttnBackendBase` capture/replay contract still applies. See + # lightning/README.md. + CUDA_GRAPH_CASES = ( + LightningAttentionCase( + name="runner_cuda_graph_lightning_decode_page_boundary", + backend="triton", + forward_mode=ForwardMode.DECODE, + num_heads=2, + page_size=16, + prefix_lens=(14, 15, 16), + ), + ) + # Lightning's `seg_la` kernel processes draft tokens as a chain — it + # has no parent-indices / retrieve-index plumbing for tree-shaped + # drafts (see `linear/seg_la.py`). Tree verify (topk>1) is therefore + # structurally unsupported and intentionally omitted; only the + # chain (topk=1) shape is covered. The non-EAGLE chain spec kinds + # (frozen_kv_mtp, dflash, ngram) match the chain-only contract and + # pass against the seg_la recurrence reference. + EAGLE_VERIFY_CASES = ( + ( + LightningAttentionCase( + name="runner_eagle_verify_lightning_chain", + backend="triton", + forward_mode=ForwardMode.TARGET_VERIFY, + num_heads=2, + page_size=16, + prefix_lens=(4, 7), + extend_lens=(3, 3), + ), + 1, + "eagle", + ), + ( + LightningAttentionCase( + name="runner_frozen_kv_mtp_verify_lightning_chain", + backend="triton", + forward_mode=ForwardMode.TARGET_VERIFY, + num_heads=2, + page_size=16, + prefix_lens=(4, 7), + extend_lens=(3, 3), + ), + 1, + "frozen_kv_mtp", + ), + ( + LightningAttentionCase( + name="runner_dflash_verify_lightning_chain", + backend="triton", + forward_mode=ForwardMode.TARGET_VERIFY, + num_heads=2, + page_size=16, + prefix_lens=(4, 7), + extend_lens=(3, 3), + ), + 1, + "dflash", + ), + ( + LightningAttentionCase( + name="runner_ngram_verify_lightning_chain", + backend="triton", + forward_mode=ForwardMode.TARGET_VERIFY, + num_heads=2, + page_size=16, + prefix_lens=(4, 7), + extend_lens=(3, 3), + ), + 1, + "ngram", + ), + ) + EAGLE_VERIFY_CUDA_GRAPH_CASES = ( + ( + LightningAttentionCase( + name="runner_cuda_graph_eagle_verify_lightning_chain", + backend="triton", + forward_mode=ForwardMode.TARGET_VERIFY, + num_heads=2, + page_size=16, + prefix_lens=(4, 7), + extend_lens=(3, 3), + ), + 1, + "eagle", + ), + ) + + def test_projected_lightning_attention_cases(self): + for case in self.CASES: + with self.subTest(case=case.name, backend=case.backend): + run_lightning_attention_case(self, case) + + # Layout-robustness. See dense/test_triton.py for the rationale. + LAYOUT_ROBUSTNESS_CASES = ( + LightningAttentionCase( + name="layout_lightning_extend_two_request", + backend="triton", + forward_mode=ForwardMode.EXTEND, + num_heads=2, + page_size=16, + prefix_lens=(0, 0), + extend_lens=(16, 16), + ), + LightningAttentionCase( + name="layout_lightning_decode_page_boundary", + backend="triton", + forward_mode=ForwardMode.DECODE, + num_heads=2, + page_size=16, + prefix_lens=(14, 15, 16), + ), + ) + + def test_layout_robustness_cases(self): + for case in self.LAYOUT_ROBUSTNESS_CASES: + for layout in ("interleaved_pages", "non_monotonic_extend"): + if layout == "non_monotonic_extend" and case.forward_mode.is_decode(): + continue + with self.subTest(case=case.name, layout=layout): + run_lightning_attention_case(self, case, loc_layout=layout) + + def test_runner_mode_cuda_graph_decode_cases(self): + for case in self.CUDA_GRAPH_CASES: + with self.subTest(case=case.name, backend=case.backend): + run_lightning_cuda_graph_decode_case(self, case) + + def test_runner_mode_eagle_verify_cases(self): + for case, topk, spec_kind in self.EAGLE_VERIFY_CASES: + with self.subTest( + case=case.name, + backend=case.backend, + topk=topk, + spec_kind=spec_kind, + ): + run_lightning_eagle_verify_case( + self, case, topk=topk, spec_kind=spec_kind + ) + + def test_runner_mode_eagle_verify_cuda_graph_cases(self): + for case, topk, spec_kind in self.EAGLE_VERIFY_CUDA_GRAPH_CASES: + with self.subTest( + case=case.name, + backend=case.backend, + topk=topk, + spec_kind=spec_kind, + ): + run_lightning_eagle_verify_cuda_graph_case(self, case, topk=topk) + + # PCG/BCG split-op extend is deliberately NOT covered. Lightning's + # backend `forward_extend` flattens the output via `o.view(-1, + # tp_q_head_num * v_head_dim)` (`lightning_backend.py:335`), so eager + # forward returns flat `[T, num_heads * head_dim]`. But under + # piecewise CG (the split-op path), `RadixAttention.forward` writes + # through `output = torch.empty_like(q)` of per-head shape + # `[T, num_heads, head_dim]`, ignoring the backend's intended + # flatten. The split-op runner compares eager_actual to the + # piecewise actual, which then trips a shape mismatch. KDA and GDN + # avoid this because their backends keep the per-head shape on the + # return path. Fixing requires either a Lightning-specific split-op + # runner that reshapes actual to flat, or a Lightning backend + # change to keep per-head shape under piecewise CG. + + +if __name__ == "__main__": + unittest.main() diff --git a/asian_ai/performance/SGLang/test/registered/attention/unittests/mamba/README.md b/asian_ai/performance/SGLang/test/registered/attention/unittests/mamba/README.md new file mode 100644 index 0000000000000000000000000000000000000000..01639f133a0d2be01678cad024b4d08b38ec4c7b --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/attention/unittests/mamba/README.md @@ -0,0 +1,126 @@ +# Mamba2 / SSM Attention Capability Matrix + +This folder covers Mamba2 state-space-model attention. The actual path +constructs a real `MambaMixer2` and drives it through `Mamba2AttnBackend` via +`ForwardContext`. Expected outputs come from a pure-PyTorch per-token SSM scan +reference (`state_t = exp(A*dt_t) * state_{t-1} + dt_t * B_t * x_t`, +`y_t = C_t * state_t + D * x_t`) that reuses the actual `in_proj` / `conv1d` / +`norm` / `out_proj` modules through shared random weights but recomputes the +SSM core entirely in pure torch. + +## Coverage Matrix + +Columns are runner modes; rows are the SSM kernel backend +(`triton` `Mamba2AttnBackend` is the only one wired today). Cells use: +- **✓ \** — exercised, with the config variants listed in the cell +- **metadata-only** — backend exercised through the metadata path only (no + forward), used to cover specific mutation surfaces +- **—** — not applicable / not exercised +- **blocked: \** — production-unsupported, not a follow-up +- **deferred: \** — could land later, currently disabled + +| SSM kernel | Eager Phase 2 | CG decode | PCG extend | BCG extend | Verify eager | Verify CG | DE eager | DE CG | DE-V2 CG | EAGLE-draft runner | EAGLE-DE runner | FKVMTP runner | +|---|---|---|---|---|---|---|---|---|---|---|---|---| +| `triton` (`Mamba2AttnBackend`) | ✓ EXTEND zero-prefix exact-page / below-page / above-page / page-edges (15/16/17), with-prefix, total-exact-page (prefix=8 + extend=8), cross-page-boundary (prefix=15 + extend=2), multi-request zero-prefix / ragged / ragged-page-boundary (prefix=(0,8,16) + extend=(15,8,1)), page_size=1, page_size=32 cross-boundary (12 variants) + DECODE page-boundary + DECODE bsz=1 nonzero-prefix (14 variants total) | ✓ decode page-boundary (full forward replay with SSM+conv state snapshot/restore via `_clone_mamba2_cache`/`_restore_mamba2_cache`; uses `MAMBA2_GRAPH_ATOL=1e-1` to absorb chunked-scan kernel CG-replay drift; eager `MAMBA2_ATOL=5e-2` kept for non-graph cases). Plus the M21 metadata-only padding test (`seq_lens_cpu=[5,1,1]`). | blocked: `MambaMixer2.forward` asserts `num_actual_tokens == projected_states.shape[0]` (`mamba.py:467`) — the in-mixer projection requires `hidden_states.shape[0]` to equal the LIVE token count exactly, no padding tolerance. The shared split-op runner pads `hidden_states` to a fixed static upper bound, so Mamba2 trips this assert. See "Production-Unsupported". | blocked: same | deferred | deferred | — | blocked: HybridLinearAttnBackend `_replay_metadata` rejects modes outside `DECODE_OR_IDLE` / `TARGET_VERIFY` (`hybrid_linear_attn_backend.py:509,572`) | blocked: same `_replay_metadata` reject | deferred | blocked: same `_replay_metadata` reject | — | + +## Hybrid dispatch fan-out tests (MagicMock-based) + +Same shape as the GDN dispatch tests. Mamba2 inherits the +`MambaAttnBackendBase` capture/replay contract through +`HybridLinearAttnBackend`, so a dispatch-layer slice mutation (e.g. +`attn_backend_list[1:]` vs `[:1]`) would silently break Mamba2 dispatch +without explicit spies. Each test constructs a `HybridLinearAttnBackend` +with two `MagicMock` sub-backends and asserts both receive the matching +call. + +| Test | Mutation covered | +|---|---| +| `test_hybrid_dispatch_eager_init_forward_metadata_fan_out` | M20 — `attn_backend_list[1:]` slice in `init_forward_metadata` (`hybrid_linear_attn_backend.py:825-827`) | +| `test_hybrid_dispatch_replay_init_forward_metadata_fan_out` | M19 — `attn_backend_list[:1]` slice in `init_forward_metadata_replay_cuda_graph` (`hybrid_linear_attn_backend.py:879-900`) | +| `test_hybrid_dispatch_capture_init_forward_metadata_fan_out` | Symmetric capture coverage (not in mutation journal) | + +## Input And Config Coverage + +- 14 input layouts via `make_mamba2_cases('triton')`: + - **EXTEND (12):** zero-prefix exact-page (16 tokens), zero-prefix + below-page (8 tokens), zero-prefix above-page (32 tokens, + cross-page), zero-prefix input page edges (`extend=(15, 16, 17)` + — sequence length one below / exactly at / one above a page), + with-prefix (`prefix=16, extend=16`), total-exact-page + (`prefix=8, extend=8`), cross-page-boundary (`prefix=15, extend=2`), + multi-request zero-prefix (`extend=(16, 16)`), multi-request ragged + (`prefix=(0, 16), extend=(16, 16)`), ragged-page-boundary + (`prefix=(0, 8, 16), extend=(15, 8, 1)` — requests below / at / above + page), `page_size=1` (16 tokens), and `page_size=32` cross-boundary + (`prefix=31, extend=2`). + - **DECODE (2):** page-boundary (`prefix_lens=(14, 15, 16)`) and + bsz=1 nonzero-prefix (`prefix_lens=(7,)`). The fixture's + `MockMamba2ModelRunner.__init__` calls + `initialize_mamba_selective_state_update_backend(server_args)` + (mirroring scheduler startup) so `MambaMixer2.forward_decode` + finds the global selective-state-update backend. +- Page-size variants (`page_size=1`, `page_size=16`, `page_size=32`) + test the req-pool / token-pool indexing layout under different page + sizes; the Mamba2 backend itself is an SSM scan and does not read + paged KV, so different page sizes mainly exercise the metadata path. +- `num_heads=DEFAULT_NUM_HEADS=2`, `head_dim=DEFAULT_HEAD_DIM=16`, + `state_size=16`, `n_groups=1`, `conv_kernel=4`, + `mamba_chunk_size=DEFAULT_MAMBA_CHUNK_SIZE=16`, `hidden_size=32`. +- Dims chosen as the minimum that satisfies `MambaMixer2`'s TP/chunk asserts. +- Replay metadata test uses `prefix_lens=(4, 0, 0)` and feeds + `seq_lens_cpu=[5, 1, 1]` directly so two trailing rows match the + CUDA-graph fill value (`1`). + +## Production-Unsupported + +- **`Mamba2AttnBackend.forward_decode` / `forward_extend` raise** — + `hybrid_linear_attn_backend.py:743-749` raises `NotImplementedError` for + direct calls. Production dispatches through `HybridLinearAttnBackend`'s + forward (`hybrid_linear_attn_backend.py:899-917, 868-886`). +- **CUDA-graph capture/replay outside `DECODE_OR_IDLE` / `TARGET_VERIFY`** — + the underlying `MambaAttnBackendBase` capture/replay rejects all other + modes (`hybrid_linear_attn_backend.py:509, 572`). +- **PCG / BCG split-op extend** — `MambaMixer2.forward` asserts + `num_actual_tokens == projected_states.shape[0]` + (`mamba.py:467`) at the projection step, BEFORE the + `num_token_non_padded_cpu` slicing kicks in at the attention + dispatch. The shared `_run_split_op_extend_case` pads + `hidden_states` to a fixed `static_num_tokens` upper bound to + exercise the per-layer slicing contract, but Mamba2 trips this + assert because its mixer projects all the padded rows. Landing + Mamba2 split-op needs either a mixer-side change to accept padded + `hidden_states` (project only `num_actual_tokens` rows), or a + split-op runner variant that passes unpadded `hidden_states` while + still padding `forward_batch.input_ids` / `out_cache_loc`. +- **Per-mixer head_dim / chunk constraints** — `MambaMixer2.__init__` asserts + weight dim sums (`mamba.py:92`), TP head divisibility (`mamba.py:217, 221, + 226`), and ssd kernels reject mismatched group / chunk shapes + (`ops/ssd_chunk_state.py:448-509, 576-583`). The fixture sets dims to + satisfy these. + +## Known Baseline Issue + +- The fixture mock now sets `enable_symm_mem=False` on the + `server_args` `SimpleNamespace` and calls + `set_global_server_args_for_scheduler` so production's + `is_symmetric_memory_enabled()` reads a sane value inside + `MambaMixer2.in_proj` / `out_proj`. Earlier failures with + `'SimpleNamespace' object has no attribute 'enable_symm_mem'` are + resolved. + +## Required Fixture Work + +- Wire the `HybridLinearAttnBackend` dispatch wrapper into the fixture so + production `init_forward_metadata*` paths and per-layer dispatch are + actually exercised (today the fixture installs `Mamba2AttnBackend` + directly via `ForwardContext`). +- Add a CUDA graph decode fixture with explicit recurrent cache snapshot / + restore between capture and replay, matching the GDN runner-mode shape. + +## Next Work + +- PCG/BCG split-op extend is gated by the `MambaMixer2.forward` + projection-step assert; see "Production-Unsupported" above. Landing + this needs a mixer-side change to project only `num_actual_tokens` + rows from a padded `hidden_states`, or a split-op runner variant + that decouples token-count padding from `hidden_states` padding. diff --git a/asian_ai/performance/SGLang/test/registered/attention/unittests/mamba/__init__.py b/asian_ai/performance/SGLang/test/registered/attention/unittests/mamba/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/asian_ai/performance/SGLang/test/registered/attention/unittests/mamba/test_mamba2.py b/asian_ai/performance/SGLang/test/registered/attention/unittests/mamba/test_mamba2.py new file mode 100644 index 0000000000000000000000000000000000000000..d573517e7a5593ba06f7cd0e7bcb37477e4ffac3 --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/attention/unittests/mamba/test_mamba2.py @@ -0,0 +1,335 @@ +import sys +import unittest +from pathlib import Path +from types import SimpleNamespace +from unittest.mock import MagicMock + +import torch + +from sglang.srt.layers.attention.hybrid_linear_attn_backend import ( + HybridLinearAttnBackend, + MambaAttnBackendBase, +) +from sglang.srt.model_executor.forward_batch_info import ForwardMode +from sglang.test.test_utils import CustomTestCase + +sys.path.insert(0, str(Path(__file__).resolve().parents[1])) + +from sglang.test.ci.ci_register import register_cuda_ci +from sglang.test.kits.attention_unittest.attention_methods.mamba2_attention import ( + DEFAULT_CONV_KERNEL, + DEFAULT_HEAD_DIM, + DEFAULT_HIDDEN_SIZE, + DEFAULT_MAMBA_CHUNK_SIZE, + DEFAULT_N_GROUPS, + DEFAULT_NUM_HEADS, + DEFAULT_STATE_SIZE, + Mamba2AttentionCase, + build_mamba2_attention_fixture, + make_mamba2_cases, + run_mamba2_attention_case, +) +from sglang.test.kits.attention_unittest.runner_modes.cuda_graph_decode_runner import ( + run_mamba2_cuda_graph_decode_case, +) +from sglang.test.kits.attention_unittest.runner_modes.speculative_target_verify_runner import ( + run_mamba2_eagle_verify_case, + run_mamba2_eagle_verify_cuda_graph_case, +) + +register_cuda_ci(est_time=20, stage="base-b", runner_config="4-gpu-b200") +register_cuda_ci(est_time=20, stage="base-b", runner_config="1-gpu-large") + + +@unittest.skipIf(not torch.cuda.is_available(), "CUDA is required") +class TestTritonMamba2BackendCorrectness(CustomTestCase): + CASES = make_mamba2_cases("triton") + # `seq_lens_cpu=[5, 1, 1]` mixes a live row with two cuda-graph + # fill-value rows so the replay padding count is non-trivial. + REPLAY_METADATA_CASE = Mamba2AttentionCase( + name="mamba2_decode_replay_metadata_padding", + backend="triton", + forward_mode=ForwardMode.DECODE, + num_heads=DEFAULT_NUM_HEADS, + head_dim=DEFAULT_HEAD_DIM, + state_size=DEFAULT_STATE_SIZE, + n_groups=DEFAULT_N_GROUPS, + conv_kernel=DEFAULT_CONV_KERNEL, + mamba_chunk_size=DEFAULT_MAMBA_CHUNK_SIZE, + hidden_size=DEFAULT_HIDDEN_SIZE, + page_size=16, + prefix_lens=(4, 0, 0), + ) + + CUDA_GRAPH_CASES = ( + Mamba2AttentionCase( + name="runner_cuda_graph_mamba2_decode_page_boundary", + backend="triton", + forward_mode=ForwardMode.DECODE, + num_heads=DEFAULT_NUM_HEADS, + head_dim=DEFAULT_HEAD_DIM, + state_size=DEFAULT_STATE_SIZE, + n_groups=DEFAULT_N_GROUPS, + conv_kernel=DEFAULT_CONV_KERNEL, + mamba_chunk_size=DEFAULT_MAMBA_CHUNK_SIZE, + hidden_size=DEFAULT_HIDDEN_SIZE, + page_size=16, + prefix_lens=(14, 15, 16), + ), + ) + # Chain verify (topk=1) across EAGLE plus the three non-EAGLE chain + # spec kinds (frozen_kv_mtp / dflash / ngram). Mamba2's SSM kernel + # processes draft tokens linearly regardless of the spec_info tree + # mask, so the EXTEND-style recurrence reference doubles as the + # chain verify reference across all kinds. Tree verify (topk>1) is + # structurally unsupported and skip-gated at the runner. + EAGLE_VERIFY_CASES = tuple( + ( + Mamba2AttentionCase( + name=f"runner_{spec_kind}_verify_mamba2_chain", + backend="triton", + forward_mode=ForwardMode.TARGET_VERIFY, + num_heads=DEFAULT_NUM_HEADS, + head_dim=DEFAULT_HEAD_DIM, + state_size=DEFAULT_STATE_SIZE, + n_groups=DEFAULT_N_GROUPS, + conv_kernel=DEFAULT_CONV_KERNEL, + mamba_chunk_size=DEFAULT_MAMBA_CHUNK_SIZE, + hidden_size=DEFAULT_HIDDEN_SIZE, + page_size=16, + prefix_lens=(4, 7), + extend_lens=(3, 3), + ), + 1, + spec_kind, + ) + for spec_kind in ("eagle", "frozen_kv_mtp", "dflash", "ngram") + ) + EAGLE_VERIFY_CUDA_GRAPH_CASES = ( + ( + Mamba2AttentionCase( + name="runner_cuda_graph_eagle_verify_mamba2_chain", + backend="triton", + forward_mode=ForwardMode.TARGET_VERIFY, + num_heads=DEFAULT_NUM_HEADS, + head_dim=DEFAULT_HEAD_DIM, + state_size=DEFAULT_STATE_SIZE, + n_groups=DEFAULT_N_GROUPS, + conv_kernel=DEFAULT_CONV_KERNEL, + mamba_chunk_size=DEFAULT_MAMBA_CHUNK_SIZE, + hidden_size=DEFAULT_HIDDEN_SIZE, + page_size=16, + prefix_lens=(4, 7), + extend_lens=(3, 3), + ), + 1, + ), + ) + + def test_projected_mamba2_attention_cases(self): + for case in self.CASES: + with self.subTest(case=case.name, backend=case.backend): + run_mamba2_attention_case(self, case) + + # Layout-robustness. See dense/test_triton.py for the rationale. + # Reuse the case generator's first two cases to avoid duplicating + # all the Mamba2-specific config fields. + def test_layout_robustness_cases(self): + cases = [ + self.CASES[0], # extend exact-page (zero-prefix, multi-token) + self.CASES[3], # extend with prefix (`prefix=16, extend=16`) + ] + for case in cases: + for layout in ("interleaved_pages", "non_monotonic_extend"): + with self.subTest(case=case.name, layout=layout): + run_mamba2_attention_case(self, case, loc_layout=layout) + + def test_runner_mode_cuda_graph_decode_cases(self): + for case in self.CUDA_GRAPH_CASES: + with self.subTest(case=case.name, backend=case.backend): + run_mamba2_cuda_graph_decode_case(self, case) + + def test_runner_mode_eagle_verify_cases(self): + for case, topk, spec_kind in self.EAGLE_VERIFY_CASES: + with self.subTest( + case=case.name, + backend=case.backend, + topk=topk, + spec_kind=spec_kind, + ): + run_mamba2_eagle_verify_case(self, case, topk=topk, spec_kind=spec_kind) + + def test_runner_mode_eagle_verify_cuda_graph_cases(self): + for case, topk in self.EAGLE_VERIFY_CUDA_GRAPH_CASES: + with self.subTest(case=case.name, backend=case.backend, topk=topk): + run_mamba2_eagle_verify_cuda_graph_case(self, case, topk=topk) + + # PCG/BCG split-op extend is deliberately NOT covered. The + # `MambaMixer2.forward` asserts `num_actual_tokens == + # projected_states.shape[0]` (`mamba.py:467`) — the projection step + # requires `hidden_states.shape[0]` to equal the LIVE token count + # exactly, with no padding tolerance. The shared split-op runner + # pads `hidden_states` to a fixed `static_num_tokens` upper bound + # and then relies on the backend's per-layer slicing contract via + # `num_token_non_padded_cpu`. Mamba2 doesn't support this padding + # because its mixer projects BEFORE the attention dispatch sees + # `num_token_non_padded_cpu`. Landing this needs either a Mamba2 + # mixer change to accept padded `hidden_states`, or a split-op + # runner variant that passes unpadded `hidden_states` while still + # padding the `forward_batch.input_ids` / `out_cache_loc`. + + def test_mamba2_replay_metadata_padding_indices(self): + # Drive `init_forward_metadata_out_graph` (replay path) directly with + # `seq_lens_cpu=[5, 1, 1]` (two trailing rows at the cuda-graph + # fill value 1) so the padding-row count is observable in + # `state_indices_list[bs - 1]`. + case = self.REPLAY_METADATA_CASE + fixture = build_mamba2_attention_fixture( + self, + case, + disable_cuda_graph=False, + runner_batch_size=case.batch_size, + ) + backend = fixture.backend + bs = case.batch_size + + backend.init_cuda_graph_state(max_bs=bs, max_num_tokens=bs) + + # Sentinel distinguishes "never written" from "overwritten with -1". + backend.state_indices_list[bs - 1].fill_(99) + + device = fixture.runner.device + req_pool_indices = torch.arange(bs, dtype=torch.int32, device=device) + seq_lens_cpu = torch.tensor([5, 1, 1], dtype=torch.int32, device="cpu") + seq_lens = seq_lens_cpu.to(device=device) + + # Slot 7 on req 0 must survive; the trailing two rows must be -1. + fixture.runner.req_to_token_pool.req_index_to_mamba_index_mapping[ + req_pool_indices + ] = torch.tensor([7, 0, 0], dtype=torch.int32, device=device) + + fb = SimpleNamespace( + batch_size=bs, + forward_mode=ForwardMode.DECODE, + req_pool_indices=req_pool_indices, + seq_lens=seq_lens, + seq_lens_cpu=seq_lens_cpu, + seq_lens_sum=int(seq_lens_cpu.sum().item()), + spec_info=None, + encoder_lens=None, + ) + backend.init_forward_metadata_out_graph(fb) + + state_indices = backend.state_indices_list[bs - 1].cpu().tolist() + self.assertEqual( + state_indices, + [7, -1, -1], + "`MambaAttnBackendBase._replay_metadata` must use the " + "unmutated `seq_lens_cpu` to count cuda-graph padding rows " + "(== fill value 1). With `seq_lens_cpu - 1` (M21) the " + "padding count for `[5, 1, 1]` drops from 2 to 0, leaving " + "the trailing rows holding the real mamba indices instead " + "of -1.", + ) + + # Hybrid dispatch fan-out tests (MagicMock-based) — same pattern as + # GDN. `Mamba2AttnBackend` inherits the `MambaAttnBackendBase` + # capture/replay contract through `HybridLinearAttnBackend`, so a + # dispatch-layer slice mutation (e.g. `attn_backend_list[1:]` vs + # `[:1]`) would silently break Mamba2 dispatch without these spies. + + def _make_dispatch_spy_backend(self): + full_attn_backend = MagicMock(name="full_attn_backend") + # `HybridLinearAttnBackend.__init__` aliases these buffer refs. + full_attn_backend.token_to_kv_pool = object() + full_attn_backend.req_to_token_pool = object() + + linear_attn_backend = MagicMock( + spec=MambaAttnBackendBase, name="linear_attn_backend" + ) + + backend = HybridLinearAttnBackend( + full_attn_backend, + linear_attn_backend, + full_attn_layers=[], + ) + return backend, full_attn_backend, linear_attn_backend + + @staticmethod + def _assert_fanout_forwarded(method_mock, *sentinels): + """Assert `method_mock` was called exactly once and that each + sentinel object identity appears in the call's positional or + keyword args (tolerates positional↔keyword refactors inside + `HybridLinearAttnBackend`).""" + method_mock.assert_called_once() + call = method_mock.call_args + forwarded = list(call.args) + list(call.kwargs.values()) + for sentinel in sentinels: + if not any(v is sentinel for v in forwarded): + raise AssertionError( + f"sentinel {sentinel!r} not forwarded by " + f"{method_mock._mock_name or method_mock}; call_args={call}" + ) + + def test_hybrid_dispatch_eager_init_forward_metadata_fan_out(self): + backend, full_attn_backend, linear_attn_backend = ( + self._make_dispatch_spy_backend() + ) + # Sentinel exposes the attribute production reads at the dispatch + # gate (`forward_mode.is_draft_extend_v2()`); returns False so the + # fan-out path that delegates to both children is exercised, which + # is what these spy tests assert. + sentinel_forward_batch = SimpleNamespace( + forward_mode=SimpleNamespace(is_draft_extend_v2=lambda: False) + ) + backend.init_forward_metadata(sentinel_forward_batch) + self._assert_fanout_forwarded( + full_attn_backend.init_forward_metadata, sentinel_forward_batch + ) + self._assert_fanout_forwarded( + linear_attn_backend.init_forward_metadata, sentinel_forward_batch + ) + + def _make_sentinel_fb(self): + return SimpleNamespace( + batch_size=3, + forward_mode=ForwardMode.DECODE, + req_pool_indices=object(), + seq_lens=object(), + seq_lens_cpu=object(), + seq_lens_sum=42, + spec_info=object(), + encoder_lens=None, + positions=object(), + input_ids=object(), + out_cache_loc=None, + ) + + def test_hybrid_dispatch_replay_init_forward_metadata_fan_out(self): + backend, full_attn_backend, linear_attn_backend = ( + self._make_dispatch_spy_backend() + ) + + fb = self._make_sentinel_fb() + backend.init_forward_metadata_out_graph(fb) + + for sub_backend in (full_attn_backend, linear_attn_backend): + self._assert_fanout_forwarded( + sub_backend.init_forward_metadata_out_graph, fb + ) + + def test_hybrid_dispatch_capture_init_forward_metadata_fan_out(self): + backend, full_attn_backend, linear_attn_backend = ( + self._make_dispatch_spy_backend() + ) + fb = self._make_sentinel_fb() + backend.init_forward_metadata_out_graph(fb, in_capture=True) + + for sub_backend in (full_attn_backend, linear_attn_backend): + self._assert_fanout_forwarded( + sub_backend.init_forward_metadata_out_graph, fb + ) + + +if __name__ == "__main__": + unittest.main() diff --git a/asian_ai/performance/SGLang/test/registered/attention/unittests/mla/README.md b/asian_ai/performance/SGLang/test/registered/attention/unittests/mla/README.md new file mode 100644 index 0000000000000000000000000000000000000000..d9f1aee7c8a61206a4d804fadad40ea48a6af684 --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/attention/unittests/mla/README.md @@ -0,0 +1,99 @@ +# MLA Attention Capability Matrix + +This folder covers absorb-style DeepSeek MLA attention. The actual path writes +latent KV through `get_token_to_kv_pool()` before calling `attn_mqa`; expected +outputs come from a separate HF-style PyTorch MLA reference with copied random +weights and no SGLang backend calls. + +## Coverage Matrix + +Columns are runner modes; rows are attention backends. Cells use: +- **✓ \** — exercised, with the config variants listed in the cell +- **—** — not applicable (no production path for this combination) +- **blocked: \** — production-unsupported, not a follow-up +- **deferred: \** — could land later, currently disabled +- **skip:hw** — hardware-gated; skipped on this environment but enabled when + the gating predicate passes + +| Backend | Eager Phase 2 | CG decode | PCG extend | BCG extend | Verify eager | Verify CG | DE eager | DE CG | DE-V2 CG | EAGLE-draft runner | EAGLE-DE runner | FKVMTP runner | +|---|---|---|---|---|---|---|---|---|---|---|---|---| +| `triton` | ✓ 10 input layouts (page 1/16/32, prefix/decode edges) | ✓ MLA decode page-boundary | ✓ ragged page-boundary extend | ✓ ragged page-boundary extend | ✓ EAGLE chain (topk=1) | ✓ EAGLE tree (topk=2) | — (V1 DE not enabled for Triton MLA; Triton uses V2 path) | — | ✓ fixed-tokens-per-req | ✓ chain (topk=1) + tree (topk=2) | ✓ via `DRAFT_EXTEND_V2` graph runner | — (no FKVMTP wiring for MLA) | +| `flashinfer` | ✓ 10 input layouts with DeepSeek-like `kv_lora_rank=512`, `qk_rope_head_dim=64` | ✓ MLA decode page-boundary | ✓ ragged page-boundary extend | ✓ ragged page-boundary extend | ✓ EAGLE chain (topk=1) | ✓ EAGLE chain (topk=1) | ✓ EAGLE ragged-accept | ✓ EAGLE ragged-accept | blocked: `is_draft_extend()` default `include_v2=False` (`flashinfer_mla_backend.py:432,501,454-455,512`) | ✓ chain (topk=1) only — tree blocked by `topk=1` reject (`flashinfer_mla_backend.py:910-913`) | ✓ EAGLE ragged-accept (V1) | — (no FKVMTP wiring for MLA) | +| `flashmla` | ✓ FlashMLA-compatible page-size-64 cases (zero-prefix exact page, input page edges 63/64/65, prefix exact page, total exact page, cross page, ragged, decode page-boundary, decode bsz=1 nonzero prefix) | ✓ page-size-64 decode page-boundary | ✓ ragged page-boundary extend | ✓ ragged page-boundary extend | ✓ EAGLE chain (topk=1) | ✓ EAGLE chain (topk=1) | ✓ EAGLE ragged-accept | deferred: parent FlashInfer-MLA capture path expects 1D `cuda_graph_kv_indices`, FlashMLA allocates 2D `[max_bs, (max_context+PAGE_SIZE)//PAGE_SIZE]` (`flashmla_backend.py:347-348` + parent `init_forward_metadata_capture_cuda_graph`) | — (FlashMLA does not implement V2) | ✓ chain (topk=1) only — tree blocked by `topk=1` reject (`flashmla_backend.py:555-558`) | — (DE CG deferred above) | — | +| `cutlass_mla` | skip:hw — needs SM 10.0+ (Blackwell); current 1 case uses `ForwardMode.EXTEND` but `CutlassMLABackend` only overrides `forward_decode` (`cutlass_mla_backend.py:226`) and falls through to FlashInfer MLA for other modes → **case should be DECODE**; PAGE_SIZE fixed at 128 (`cutlass_mla_backend.py:31`) | — (decode-only backend; no extend/CG) | — | — | blocked: tree via `topk=1` reject inherited from FlashInfer MLA parent | — | — | — | — | — | — | — | +| `trtllm_mla` | skip:hw — needs SM 12.0a / 12.1a (`is_sm120_supported`) | — | — | — | blocked: `topk=1` only (`trtllm_mla_backend.py:1223-1229` inherits from FlashInfer MLA) | — | — | — | — | — | — | — | +| `tokenspeed_mla` | skip:hw — needs `find_spec("tokenspeed_mla")`, SM 10.0+, and `kv_cache_dtype=fp8_e4m3` (`server_args.py:2814-2818`); current MLA fixture does not emit FP8 KV cache | — | — | — | blocked: `topk=1` only (`tokenspeed_mla_backend.py:341-347` inherits from TRT-LLM MLA) | — | — | — | — | — | — | — | + +## Input And Config Coverage + +- Page size 1, page-boundary decode, exact-page and crossing-page extend cases. +- Ragged page-boundary extend batches. +- Representative page-size-32 crossing case (`triton`, `flashinfer`). +- FlashMLA cases use `page_size=64` because `FlashMLABackend` forces that size + (`server_args.py:2767-2770`). The 8 FlashMLA EXTEND/DECODE input + variants cover zero-prefix exact-page, input page edges + (`extend=(63, 64, 65)`), prefix exact-page (`prefix=64`), total + exact-page (`prefix=32, extend=32`), cross-page-boundary + (`prefix=63, extend=2`), ragged page-boundary + (`prefix=(0, 32, 64), extend=(63, 32, 1)`), decode page-boundary, + and decode bsz=1 nonzero-prefix. +- Nonzero MLA rope dimension support is present in the fixture, but RoPE math + is intentionally orthogonal to the runner/backend matrix. + +## Production-Unsupported + +These combinations are explicitly rejected by the production speculative +multi-step draft backends and cannot ever appear at runtime. + +- **FlashInfer MLA tree verify / draft-extend with `topk > 1`** — raised by + `FlashInferMLAMultiStepDraftBackend.__init__` at + `python/sglang/srt/layers/attention/flashinfer_mla_backend.py:910-913`: + `if topk > 1: raise ValueError("Currently Flashinfer MLA only supports topk=1 + for speculative decoding")`. Dispatcher: `draft_utils.py:126-132`. +- **FlashMLA tree verify / draft-extend with `topk > 1`** — raised by + `FlashMLAMultiStepDraftBackend.__init__` at + `python/sglang/srt/layers/attention/flashmla_backend.py:555-558`. Dispatcher: + `draft_utils.py:173-180`. +- **TRT-LLM MLA tree verify / draft-extend with `topk > 1`** — + `TRTLLMMLAMultiStepDraftBackend` inherits from + `FlashInferMLAMultiStepDraftBackend` (`trtllm_mla_backend.py:1223-1229`). +- **Tokenspeed MLA tree verify / draft-extend with `topk > 1`** — + `TokenspeedMLAMultiStepDraftBackend` inherits from + `TRTLLMMLAMultiStepDraftBackend` (`tokenspeed_mla_backend.py:341-347`). +- **Cutlass MLA extend / verify / draft-extend** — `CutlassMLABackend` only + overrides `forward_decode` (`cutlass_mla_backend.py:226`) and only handles + `is_decode_or_idle` in `init_forward_metadata*` (`cutlass_mla_backend.py:86, + 156, 197`). Anything else falls through to FlashInfer MLA. +- **FlashInfer-MLA `DRAFT_EXTEND_V2` graph capture/replay** — + `flashinfer_mla_backend.py:432,501` only route through `is_draft_extend()` + (default `include_v2=False`); `else: raise ValueError("Invalid mode")` at + `flashinfer_mla_backend.py:454-455,512`. +- **All MLA backends fixed page size** — FlashMLA forces `page_size=64`, + Cutlass MLA forces `page_size=128`, TRT-LLM MLA and Tokenspeed MLA force + `page_size in {32, 64}`. + +## Backend Container Gate (SM10.x) + +`test_flashinfer.py::test_runner_mode_eagle_draft_cuda_graph_runner_cases` +skips on `major >= 10`. The FlashInfer MLA multi-step draft backend +(`FlashInferMLAMultiStepDraftBackend`) ships with an SM9x-targeted decode +kernel in the current container; on SM10.x it falls back to a generic path +that doesn't restore metadata buffers correctly under graph replay, producing +~22 abs-diff vs the reference. The eager and DRAFT_EXTEND paths are +unaffected; only this CG decode runner regresses. Update FlashInfer to a +version that ships an SM10.x-compiled MLA multi-step decode kernel to clear. + +See `KNOWN_FAILURES.md` §3 for the full root cause + fix. + +## Next Work + +- Fix or work around the FlashMLA `DRAFT_EXTEND` graph capture path (either + override capture/replay in `FlashMLABackend` to use its 2D layout, or + allocate both parent-style 1D and FlashMLA-style 2D buffers and route + `DRAFT_EXTEND` to the parent path). +- Switch `mla/test_cutlass_mla.py` to `ForwardMode.DECODE` so it actually + exercises `CutlassMLABackend.forward_decode` instead of falling through to + FlashInfer MLA when SM 10.0+ is available. +- Add hardware-gated tests for `cutlass_mla`, `trtllm_mla`, and `tokenspeed_mla` + decode (chain spec only) when the appropriate hardware/KV dtype fixtures are + available. diff --git a/asian_ai/performance/SGLang/test/registered/attention/unittests/mla/__init__.py b/asian_ai/performance/SGLang/test/registered/attention/unittests/mla/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/asian_ai/performance/SGLang/test/registered/attention/unittests/mla/test_cutlass_mla.py b/asian_ai/performance/SGLang/test/registered/attention/unittests/mla/test_cutlass_mla.py new file mode 100644 index 0000000000000000000000000000000000000000..f433c5429c0f49710f0d824532101c27a6d27f08 --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/attention/unittests/mla/test_cutlass_mla.py @@ -0,0 +1,103 @@ +import sys +import unittest +from pathlib import Path + +import torch + +from sglang.srt.model_executor.forward_batch_info import ForwardMode +from sglang.test.test_utils import CustomTestCase + +sys.path.insert(0, str(Path(__file__).resolve().parents[1])) + +from sglang.test.kits.attention_unittest.attention_methods.mla_attention import ( + MLAAttentionCase, + run_mla_attention_case, +) + +# Cutlass MLA requires exactly Blackwell SM 10.0. The sgl-kernel +# `cutlass_mla_decode` checks `sm_version == 100` (major*10+minor), so +# SM 10.3 (GB300) reports sm_version=103 and is rejected by the kernel. +# PAGE_SIZE is fixed to 128 in the backend. +_REQUIRED_SM_MAJOR = 10 +_REQUIRED_SM_MINOR = 0 + +MLA_SHAPE_KWARGS = dict( + kv_lora_rank=512, + qk_rope_head_dim=64, + hidden_size=1024, + max_context_len=256, +) + + +def _supported() -> tuple[bool, str]: + if not torch.cuda.is_available(): + return False, "CUDA is required" + major, minor = torch.cuda.get_device_capability() + if major != _REQUIRED_SM_MAJOR or minor != _REQUIRED_SM_MINOR: + return ( + False, + f"cutlass_mla requires exactly SM {_REQUIRED_SM_MAJOR}.{_REQUIRED_SM_MINOR} " + f"(B200 Blackwell); got SM {major}.{minor}", + ) + return True, "" + + +_SUPPORTED, _SKIP_REASON = _supported() + + +from sglang.test.ci.ci_register import register_cuda_ci + +register_cuda_ci(est_time=15, stage="base-b", runner_config="4-gpu-b200") +register_cuda_ci(est_time=15, stage="base-b", runner_config="1-gpu-large") + + +@unittest.skipIf(not _SUPPORTED, _SKIP_REASON) +class TestCutlassMLAAttentionBackendCorrectness(CustomTestCase): + # CutlassMLABackend only overrides `forward_decode`; EXTEND falls through + # to the FlashInferMLAAttnBackend parent and bypasses cutlass code + # entirely. Use DECODE so the test actually exercises the cutlass kernel + # on Blackwell. Page size is fixed to PAGE_SIZE=128 (server_args.py + # forces this for cutlass_mla). + CASES = ( + MLAAttentionCase( + name="mla_decode_cutlass_page_boundary", + backend="cutlass_mla", + forward_mode=ForwardMode.DECODE, + num_heads=4, + page_size=128, + prefix_lens=(126, 127, 128), + ), + MLAAttentionCase( + name="mla_decode_cutlass_bsz1_nonzero_prefix", + backend="cutlass_mla", + forward_mode=ForwardMode.DECODE, + num_heads=4, + page_size=128, + prefix_lens=(63,), + ), + MLAAttentionCase( + name="mla_decode_cutlass_above_page", + backend="cutlass_mla", + forward_mode=ForwardMode.DECODE, + num_heads=4, + page_size=128, + prefix_lens=(128, 129, 130), + ), + MLAAttentionCase( + name="mla_decode_cutlass_multi_page", + backend="cutlass_mla", + forward_mode=ForwardMode.DECODE, + num_heads=4, + page_size=128, + prefix_lens=(127, 200, 255), + ), + ) + + def test_projected_mla_attention_cases(self): + for case in self.CASES: + with self.subTest(case=case.name, backend=case.backend): + run_mla_attention_case(self, case, **MLA_SHAPE_KWARGS) + + +if __name__ == "__main__": + unittest.main() diff --git a/asian_ai/performance/SGLang/test/registered/attention/unittests/mla/test_flashinfer.py b/asian_ai/performance/SGLang/test/registered/attention/unittests/mla/test_flashinfer.py new file mode 100644 index 0000000000000000000000000000000000000000..e8e8fabfbbf63ff8af3f5c3753a4a6f6849248d3 --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/attention/unittests/mla/test_flashinfer.py @@ -0,0 +1,255 @@ +import sys +import unittest +from pathlib import Path + +import torch + +from sglang.srt.model_executor.forward_batch_info import ForwardMode +from sglang.test.test_utils import CustomTestCase + +sys.path.insert(0, str(Path(__file__).resolve().parents[1])) + +from sglang.test.kits.attention_unittest.attention_methods.mla_attention import ( + MLAAttentionCase, + make_mla_cases, + run_mla_attention_case, +) +from sglang.test.kits.attention_unittest.runner_modes.cuda_graph_decode_runner import ( + run_mla_cuda_graph_decode_case, +) +from sglang.test.kits.attention_unittest.runner_modes.speculative_draft_runner import ( + run_mla_eagle_draft_cuda_graph_runner_case, +) +from sglang.test.kits.attention_unittest.runner_modes.speculative_target_verify_runner import ( + run_mla_eagle_verify_case, + run_mla_eagle_verify_cuda_graph_case, +) +from sglang.test.kits.attention_unittest.runner_modes.split_op_runner import ( + run_mla_split_op_extend_case, +) + +MLA_SHAPE_KWARGS = dict( + kv_lora_rank=512, + qk_rope_head_dim=64, + hidden_size=1024, +) + + +from sglang.test.ci.ci_register import register_cuda_ci + +register_cuda_ci(est_time=25, stage="base-b", runner_config="4-gpu-b200") +register_cuda_ci(est_time=25, stage="base-b", runner_config="1-gpu-large") + + +@unittest.skipIf(not torch.cuda.is_available(), "CUDA is required") +class TestFlashInferMLAAttentionBackendCorrectness(CustomTestCase): + CASES = make_mla_cases("flashinfer") + CUDA_GRAPH_CASES = ( + MLAAttentionCase( + name="runner_cuda_graph_decode_page_boundary", + backend="flashinfer", + forward_mode=ForwardMode.DECODE, + num_heads=4, + page_size=16, + prefix_lens=(14, 15, 16), + ), + ) + SPLIT_OP_CASES = ( + ( + MLAAttentionCase( + name="runner_split_op_mla_extend_ragged_page_boundary", + backend="flashinfer", + forward_mode=ForwardMode.EXTEND, + num_heads=4, + page_size=16, + prefix_lens=(0, 8, 16), + extend_lens=(15, 8, 1), + ), + 32, + ), + ) + EAGLE_VERIFY_CASES = ( + ( + MLAAttentionCase( + name="runner_eagle_verify_mla_chain", + backend="flashinfer", + forward_mode=ForwardMode.TARGET_VERIFY, + num_heads=4, + page_size=16, + prefix_lens=(4, 7), + extend_lens=(3, 3), + ), + 1, + ), + ) + EAGLE_VERIFY_CUDA_GRAPH_CASES = ( + ( + MLAAttentionCase( + name="runner_cuda_graph_eagle_verify_mla_chain", + backend="flashinfer", + forward_mode=ForwardMode.TARGET_VERIFY, + num_heads=4, + page_size=16, + prefix_lens=(4, 7), + extend_lens=(3, 3), + ), + 1, + ), + ) + EAGLE_DRAFT_RUNNER_CASES = ( + ( + MLAAttentionCase( + name="runner_eagle_draft_decode_mla_cuda_graph_chain", + backend="flashinfer", + forward_mode=ForwardMode.DECODE, + num_heads=4, + page_size=16, + prefix_lens=(4, 7), + ), + 1, + 3, + ), + ) + + def test_tiny_deepseek_mla_attention_cases(self): + for case in self.CASES: + with self.subTest(case=case.name, backend=case.backend): + run_mla_attention_case(self, case, **MLA_SHAPE_KWARGS) + + # Layout-robustness. See dense/test_triton.py for the full + # rationale. FlashInfer MLA crashes with + # `AcceleratorError: an illegal memory access was encountered` + # on both EXTEND under interleaved_pages and non_monotonic_extend, + # and crashes with `CUBLAS_STATUS_EXECUTION_FAILED` on DECODE under + # interleaved_pages. The crashes happen inside FlashInfer's MLA + # paged-prefill / paged-decode metadata; the kernel assumes a + # tidy page-table layout that the non-tidy variants violate. + # Documented as LAYOUT_KNOWN_FAILURES so the test method records + # the production-side cause for future readers. + LAYOUT_ROBUSTNESS_CASES = ( + MLAAttentionCase( + name="layout_mla_extend_prefix_exact_page", + backend="flashinfer", + forward_mode=ForwardMode.EXTEND, + num_heads=4, + page_size=16, + prefix_lens=(16,), + extend_lens=(2,), + ), + MLAAttentionCase( + name="layout_mla_decode_page_boundary", + backend="flashinfer", + forward_mode=ForwardMode.DECODE, + num_heads=4, + page_size=16, + prefix_lens=(14, 15, 16), + ), + ) + LAYOUT_KNOWN_FAILURES = { + ("layout_mla_extend_prefix_exact_page", "interleaved_pages"): ( + "FlashInfer MLA paged-prefill metadata assumes a tidy " + "page-table layout; interleaved pages trip an illegal " + "memory access inside the kernel." + ), + ("layout_mla_extend_prefix_exact_page", "non_monotonic_extend"): ( + "FlashInfer MLA paged-prefill metadata assumes monotonic " + "out_cache_loc within an extend; scattered extend slots " + "trip an illegal memory access." + ), + ("layout_mla_decode_page_boundary", "interleaved_pages"): ( + "FlashInfer MLA paged-decode metadata raises " + "CUBLAS_STATUS_EXECUTION_FAILED on interleaved-page layouts." + ), + } + + def test_layout_robustness_cases(self): + for case in self.LAYOUT_ROBUSTNESS_CASES: + for layout in ("interleaved_pages", "non_monotonic_extend"): + if layout == "non_monotonic_extend" and case.forward_mode.is_decode(): + continue + reason = self.LAYOUT_KNOWN_FAILURES.get((case.name, layout)) + if reason is not None: + print( + f"[layout-known-failure] {case.name} x {layout}: {reason}", + flush=True, + ) + continue + with self.subTest(case=case.name, layout=layout): + run_mla_attention_case( + self, case, loc_layout=layout, **MLA_SHAPE_KWARGS + ) + + def test_runner_mode_cuda_graph_decode_cases(self): + for case in self.CUDA_GRAPH_CASES: + with self.subTest(case=case.name, backend=case.backend): + run_mla_cuda_graph_decode_case(self, case, **MLA_SHAPE_KWARGS) + + def test_runner_mode_split_op_extend_cases(self): + for case, static_num_tokens in self.SPLIT_OP_CASES: + for breakable in (False, True): + runner = "bcg" if breakable else "pcg" + with self.subTest( + case=case.name, + backend=case.backend, + runner=runner, + ): + run_mla_split_op_extend_case( + self, + case, + breakable=breakable, + static_num_tokens=static_num_tokens, + **MLA_SHAPE_KWARGS, + ) + + def test_runner_mode_eagle_verify_cases(self): + for case, topk in self.EAGLE_VERIFY_CASES: + with self.subTest(case=case.name, backend=case.backend, topk=topk): + run_mla_eagle_verify_case( + self, + case, + topk=topk, + **MLA_SHAPE_KWARGS, + ) + + def test_runner_mode_eagle_verify_cuda_graph_cases(self): + for case, topk in self.EAGLE_VERIFY_CUDA_GRAPH_CASES: + with self.subTest(case=case.name, backend=case.backend, topk=topk): + run_mla_eagle_verify_cuda_graph_case( + self, + case, + topk=topk, + **MLA_SHAPE_KWARGS, + ) + + def test_runner_mode_eagle_draft_cuda_graph_runner_cases(self): + # Backend gate (KNOWN_FAILURES.md §3): FlashInfer MLA multi-step + # draft CG capture/replay produces numerically wrong outputs on + # Blackwell (SM10.x) — observed max abs diff ~22 vs reference on + # GB300. Cause: the FlashInfer MLA decode kernel in the container + # targets SM9x and falls back to a generic path on SM10.x that + # does not restore metadata buffers correctly under graph replay. + # The eager and DRAFT_EXTEND paths are unaffected; only this CG + # decode runner regresses. Skip on SM10.x until FlashInfer ships + # an SM10.x-compiled MLA multi-step decode kernel. + major, minor = torch.cuda.get_device_capability() + if major >= 10: + self.skipTest( + f"FlashInfer MLA EAGLE draft CG produces wrong outputs on " + f"SM{major}.{minor} — FlashInfer MLA decode kernel falls back " + f"to a generic path that breaks under graph replay. See " + f"KNOWN_FAILURES.md §3. Update FlashInfer to a version that " + f"ships an SM{major}.x-compiled MLA multi-step decode kernel." + ) + for case, topk, num_draft_tokens in self.EAGLE_DRAFT_RUNNER_CASES: + with self.subTest(case=case.name, backend=case.backend, topk=topk): + run_mla_eagle_draft_cuda_graph_runner_case( + self, + case, + topk=topk, + speculative_num_draft_tokens=num_draft_tokens, + **MLA_SHAPE_KWARGS, + ) + + +if __name__ == "__main__": + unittest.main() diff --git a/asian_ai/performance/SGLang/test/registered/attention/unittests/mla/test_flashmla.py b/asian_ai/performance/SGLang/test/registered/attention/unittests/mla/test_flashmla.py new file mode 100644 index 0000000000000000000000000000000000000000..147ab4cba8de1a6844d3c7a12054b20cd9a0047d --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/attention/unittests/mla/test_flashmla.py @@ -0,0 +1,445 @@ +import sys +import unittest +from pathlib import Path + +import torch +import triton + +from sglang.srt.model_executor.forward_batch_info import ForwardMode +from sglang.srt.model_executor.forward_context import ForwardContext, forward_context +from sglang.test.test_utils import CustomTestCase + +sys.path.insert(0, str(Path(__file__).resolve().parents[1])) + +from sglang.test.kits.attention_unittest.attention_methods.mla_attention import ( + MLAAttentionCase, + build_mla_attention_fixture, + run_mla_attention_case, +) +from sglang.test.kits.attention_unittest.runner_modes.cuda_graph_decode_runner import ( + _init_cuda_graph_capture_metadata, + _init_cuda_graph_replay_metadata, + run_mla_cuda_graph_decode_case, +) +from sglang.test.kits.attention_unittest.runner_modes.speculative_draft_runner import ( + run_mla_eagle_draft_cuda_graph_runner_case, +) +from sglang.test.kits.attention_unittest.runner_modes.speculative_target_verify_runner import ( + _make_eagle_verify_input, + _prepare_target_verify_batch, + run_mla_eagle_verify_case, + run_mla_eagle_verify_cuda_graph_case, +) +from sglang.test.kits.attention_unittest.runner_modes.split_op_runner import ( + run_mla_split_op_extend_case, +) + +MLA_SHAPE_KWARGS = dict( + kv_lora_rank=512, + qk_rope_head_dim=64, + hidden_size=1024, + max_context_len=256, +) + +# FlashMLA's KV cache is paginated with PAGE_SIZE=64 +# (see `python/sglang/srt/layers/attention/flashmla_backend.py`). +FLASHMLA_PAGE_SIZE = 64 + +# FlashMLABackend.forward_decode and forward_target_verify require SM90a +# (Hopper architecture — H100/H200). On Blackwell (SM10.x) those paths +# raise "Dense decode MLA is only supported on SM90a architecture". +# EXTEND falls through to the FlashInferMLAAttnBackend parent and works +# on any SM >= 9. +_DECODE_REQUIRES_SM90A = ( + not torch.cuda.is_available() or torch.cuda.get_device_capability()[0] >= 10 +) +_DECODE_SKIP_REASON = ( + "FlashMLA decode/target-verify requires SM90a (Hopper); " + f"got SM{torch.cuda.get_device_capability()[0]}.x" + if _DECODE_REQUIRES_SM90A and torch.cuda.is_available() + else "CUDA unavailable" +) + + +from sglang.test.ci.ci_register import register_cuda_ci + +register_cuda_ci(est_time=25, stage="base-b", runner_config="4-gpu-b200") +register_cuda_ci(est_time=25, stage="base-b", runner_config="1-gpu-large") + + +@unittest.skipIf(not torch.cuda.is_available(), "CUDA is required") +class TestFlashMLAAttentionBackendCorrectness(CustomTestCase): + CASES = ( + MLAAttentionCase( + name="mla_extend_zero_prefix_exact_flashmla_page", + backend="flashmla", + forward_mode=ForwardMode.EXTEND, + num_heads=4, + page_size=64, + prefix_lens=(0,), + extend_lens=(64,), + ), + # Sequence length one below / exactly at / one above the page + # boundary with zero prefix (Required input case: "Sequence length + # one token below and one token above a page boundary"). + MLAAttentionCase( + name="mla_extend_flashmla_input_page_edges", + backend="flashmla", + forward_mode=ForwardMode.EXTEND, + num_heads=4, + page_size=64, + prefix_lens=(0, 0, 0), + extend_lens=(63, 64, 65), + ), + # Prefix length exactly equal to one page (Required input case). + MLAAttentionCase( + name="mla_extend_prefix_exact_flashmla_page", + backend="flashmla", + forward_mode=ForwardMode.EXTEND, + num_heads=4, + page_size=64, + prefix_lens=(64,), + extend_lens=(2,), + ), + # Prefix plus extend length exactly equal to one page (Required + # input case). + MLAAttentionCase( + name="mla_extend_total_exact_flashmla_page", + backend="flashmla", + forward_mode=ForwardMode.EXTEND, + num_heads=4, + page_size=64, + prefix_lens=(32,), + extend_lens=(32,), + ), + MLAAttentionCase( + name="mla_extend_cross_flashmla_page_boundary", + backend="flashmla", + forward_mode=ForwardMode.EXTEND, + num_heads=4, + page_size=64, + prefix_lens=(63,), + extend_lens=(2,), + ), + MLAAttentionCase( + name="mla_extend_ragged_flashmla_page_boundary", + backend="flashmla", + forward_mode=ForwardMode.EXTEND, + num_heads=4, + page_size=64, + prefix_lens=(0, 32, 64), + extend_lens=(63, 32, 1), + ), + MLAAttentionCase( + name="mla_decode_flashmla_page_boundary", + backend="flashmla", + forward_mode=ForwardMode.DECODE, + num_heads=4, + page_size=64, + prefix_lens=(61, 62, 63), + ), + # Decode with nonzero prefix at batch-size 1 (Required input case). + MLAAttentionCase( + name="mla_decode_flashmla_bsz1_nonzero_prefix", + backend="flashmla", + forward_mode=ForwardMode.DECODE, + num_heads=4, + page_size=64, + prefix_lens=(31,), + ), + ) + CUDA_GRAPH_CASES = ( + MLAAttentionCase( + name="runner_cuda_graph_decode_flashmla_page_boundary", + backend="flashmla", + forward_mode=ForwardMode.DECODE, + num_heads=4, + page_size=64, + prefix_lens=(61, 62, 63), + ), + ) + SPLIT_OP_CASES = ( + ( + MLAAttentionCase( + name="runner_split_op_mla_flashmla_ragged_page_boundary", + backend="flashmla", + forward_mode=ForwardMode.EXTEND, + num_heads=4, + page_size=64, + prefix_lens=(0, 32, 64), + extend_lens=(63, 32, 1), + ), + 96, + ), + ) + EAGLE_VERIFY_CASES = ( + ( + MLAAttentionCase( + name="runner_eagle_verify_mla_flashmla_chain", + backend="flashmla", + forward_mode=ForwardMode.TARGET_VERIFY, + num_heads=4, + page_size=64, + prefix_lens=(4, 7), + extend_lens=(3, 3), + ), + 1, + ), + ) + EAGLE_VERIFY_CUDA_GRAPH_CASES = ( + ( + MLAAttentionCase( + name="runner_cuda_graph_eagle_verify_mla_flashmla_chain", + backend="flashmla", + forward_mode=ForwardMode.TARGET_VERIFY, + num_heads=4, + page_size=64, + prefix_lens=(4, 7), + extend_lens=(3, 3), + ), + 1, + ), + ) + EAGLE_DRAFT_RUNNER_CASES = ( + ( + MLAAttentionCase( + name="runner_eagle_draft_decode_mla_flashmla_cuda_graph_chain", + backend="flashmla", + forward_mode=ForwardMode.DECODE, + num_heads=4, + page_size=64, + prefix_lens=(4, 7), + ), + 1, + 3, + ), + ) + + def test_tiny_deepseek_mla_attention_cases(self): + for case in self.CASES: + with self.subTest(case=case.name, backend=case.backend): + if case.forward_mode == ForwardMode.DECODE and _DECODE_REQUIRES_SM90A: + self.skipTest(_DECODE_SKIP_REASON) + run_mla_attention_case(self, case, **MLA_SHAPE_KWARGS) + + # Layout-robustness. See dense/test_triton.py for the full + # rationale. FlashMLA crashes on both EXTEND layouts (illegal + # memory access) and on DECODE with interleaved_pages (shape + # mismatch). Documented as LAYOUT_KNOWN_FAILURES. + LAYOUT_ROBUSTNESS_CASES = ( + MLAAttentionCase( + name="layout_mla_extend_prefix_exact_page", + backend="flashmla", + forward_mode=ForwardMode.EXTEND, + num_heads=4, + page_size=64, + prefix_lens=(64,), + extend_lens=(2,), + ), + MLAAttentionCase( + name="layout_mla_decode_page_boundary", + backend="flashmla", + forward_mode=ForwardMode.DECODE, + num_heads=4, + page_size=64, + prefix_lens=(62, 63, 64), + ), + ) + LAYOUT_KNOWN_FAILURES = { + ("layout_mla_extend_prefix_exact_page", "interleaved_pages"): ( + "FlashMLA extend path raises CUDA illegal memory access on " + "interleaved-page layouts; the kernel assumes a tidy " + "page-table layout." + ), + ("layout_mla_extend_prefix_exact_page", "non_monotonic_extend"): ( + "FlashMLA extend path raises CUDA illegal memory access on " + "non-monotonic out_cache_loc within an extend." + ), + ("layout_mla_decode_page_boundary", "interleaved_pages"): ( + "FlashMLA decode path raises a shape mismatch " + "(`shape '[-1, 64, 1, 32]' is invalid for input of size N`) " + "on interleaved-page layouts." + ), + } + + def test_layout_robustness_cases(self): + for case in self.LAYOUT_ROBUSTNESS_CASES: + for layout in ("interleaved_pages", "non_monotonic_extend"): + if layout == "non_monotonic_extend" and case.forward_mode.is_decode(): + continue + reason = self.LAYOUT_KNOWN_FAILURES.get((case.name, layout)) + if reason is not None: + print( + f"[layout-known-failure] {case.name} x {layout}: {reason}", + flush=True, + ) + continue + with self.subTest(case=case.name, layout=layout): + run_mla_attention_case( + self, case, loc_layout=layout, **MLA_SHAPE_KWARGS + ) + + @unittest.skipIf(_DECODE_REQUIRES_SM90A, _DECODE_SKIP_REASON) + def test_runner_mode_cuda_graph_decode_cases(self): + for case in self.CUDA_GRAPH_CASES: + with self.subTest(case=case.name, backend=case.backend): + run_mla_cuda_graph_decode_case(self, case, **MLA_SHAPE_KWARGS) + + def test_runner_mode_split_op_extend_cases(self): + for case, static_num_tokens in self.SPLIT_OP_CASES: + for breakable in (False, True): + runner = "bcg" if breakable else "pcg" + with self.subTest( + case=case.name, + backend=case.backend, + runner=runner, + ): + run_mla_split_op_extend_case( + self, + case, + breakable=breakable, + static_num_tokens=static_num_tokens, + **MLA_SHAPE_KWARGS, + ) + + @unittest.skipIf(_DECODE_REQUIRES_SM90A, _DECODE_SKIP_REASON) + def test_runner_mode_eagle_verify_cases(self): + for case, topk in self.EAGLE_VERIFY_CASES: + with self.subTest(case=case.name, backend=case.backend, topk=topk): + run_mla_eagle_verify_case( + self, + case, + topk=topk, + **MLA_SHAPE_KWARGS, + ) + + @unittest.skipIf(_DECODE_REQUIRES_SM90A, _DECODE_SKIP_REASON) + def test_runner_mode_eagle_verify_cuda_graph_cases(self): + for case, topk in self.EAGLE_VERIFY_CUDA_GRAPH_CASES: + with self.subTest(case=case.name, backend=case.backend, topk=topk): + run_mla_eagle_verify_cuda_graph_case( + self, + case, + topk=topk, + **MLA_SHAPE_KWARGS, + ) + + @unittest.skipIf(_DECODE_REQUIRES_SM90A, _DECODE_SKIP_REASON) + def test_runner_mode_eagle_draft_cuda_graph_runner_cases(self): + for case, topk, num_draft_tokens in self.EAGLE_DRAFT_RUNNER_CASES: + with self.subTest(case=case.name, backend=case.backend, topk=topk): + run_mla_eagle_draft_cuda_graph_runner_case( + self, + case, + topk=topk, + speculative_num_draft_tokens=num_draft_tokens, + **MLA_SHAPE_KWARGS, + ) + + # `prefix_lens=(61, 63)` with `draft=3` straddles PAGE_SIZE=64 so the + # constructed `block_kv_indices` shape/population differs between + # correct, +1, and dropped-draft variants. + METADATA_VERIFY_CASE = MLAAttentionCase( + name="metadata_eagle_verify_flashmla_page_boundary", + backend="flashmla", + forward_mode=ForwardMode.TARGET_VERIFY, + num_heads=4, + page_size=FLASHMLA_PAGE_SIZE, + prefix_lens=(61, 63), + extend_lens=(3, 3), + ) + + @staticmethod + def _expected_block_kv_layout( + prefix_lens: tuple[int, ...], + num_draft_tokens: int, + ) -> tuple[int, int, list[int]]: + """Return (bs, expected_max_seqlen_pad, per_row_valid_pages).""" + bs = len(prefix_lens) + per_row_seq_lens = [p + num_draft_tokens for p in prefix_lens] + max_seqlen_pad = triton.cdiv(max(per_row_seq_lens), FLASHMLA_PAGE_SIZE) + per_row_valid = [triton.cdiv(s, FLASHMLA_PAGE_SIZE) for s in per_row_seq_lens] + return bs, max_seqlen_pad, per_row_valid + + def _build_target_verify_metadata_fixture(self, case): + fixture = build_mla_attention_fixture( + self, + case, + **MLA_SHAPE_KWARGS, + ) + _prepare_target_verify_batch(fixture.forward_batch, case, fixture.runner.device) + fixture.forward_batch.spec_info = _make_eagle_verify_input( + case, + fixture.forward_batch, + topk=1, + device=fixture.runner.device, + ) + return fixture + + def test_eager_target_verify_block_kv_indices_metadata(self): + case = self.METADATA_VERIFY_CASE + num_draft_tokens = case.extend_lens[0] + bs, expected_pad, expected_valid_pages = self._expected_block_kv_layout( + case.prefix_lens, num_draft_tokens + ) + + fixture = self._build_target_verify_metadata_fixture(case) + with torch.no_grad(), forward_context( + ForwardContext(attn_backend=fixture.backend) + ): + fixture.backend.init_forward_metadata(fixture.forward_batch) + + block_kv_indices = fixture.backend.forward_metadata.block_kv_indices + self.assertEqual( + tuple(block_kv_indices.shape), + (bs, expected_pad), + "FlashMLA eager target_verify `block_kv_indices` shape must encode " + "`max(seq_lens + num_draft_tokens)` rounded up to PAGE_SIZE. " + "A `+1` mutation (M14) or a dropped `+ num_draft_tokens` " + "(M15) will produce a different shape with the configured " + "page-boundary prefix lens.", + ) + valid_per_row = (block_kv_indices >= 0).sum(dim=1).cpu().tolist() + self.assertEqual( + valid_per_row, + expected_valid_pages, + "Per-request page-count populated in `block_kv_indices` must " + "match `cdiv((prefix + num_draft_tokens) / PAGE_SIZE)`. " + "M14 (+1) or M15 (drop num_draft_tokens) skews this count " + "even when the overall shape happens to coincide.", + ) + + def test_replay_target_verify_block_kv_indices_metadata(self): + # Replay-only assertion: the `cuda_graph_kv_indices` buffer is + # initialised to `1` (not `-1`), so we can only check the slice + # shape, not per-row populated counts. + case = self.METADATA_VERIFY_CASE + num_draft_tokens = case.extend_lens[0] + bs, expected_pad, _ = self._expected_block_kv_layout( + case.prefix_lens, num_draft_tokens + ) + + fixture = self._build_target_verify_metadata_fixture(case) + backend = fixture.backend + with torch.no_grad(), forward_context(ForwardContext(attn_backend=backend)): + backend.init_cuda_graph_state( + max_bs=bs, + max_num_tokens=bs * num_draft_tokens, + ) + _init_cuda_graph_capture_metadata(backend, bs, fixture.forward_batch) + _init_cuda_graph_replay_metadata(backend, bs, fixture.forward_batch) + + block_kv_indices = backend.forward_metadata.block_kv_indices + self.assertEqual( + tuple(block_kv_indices.shape), + (bs, expected_pad), + "FlashMLA replay target_verify `block_kv_indices` slice must " + "encode `max(seq_lens + num_draft_tokens)` rounded up to " + "PAGE_SIZE. Dropping `+ num_draft_tokens` in the replay " + "branch (M16) reduces the slice width below this expected " + "value for the configured page-boundary prefix lens.", + ) + + +if __name__ == "__main__": + unittest.main() diff --git a/asian_ai/performance/SGLang/test/registered/attention/unittests/mla/test_tokenspeed_mla.py b/asian_ai/performance/SGLang/test/registered/attention/unittests/mla/test_tokenspeed_mla.py new file mode 100644 index 0000000000000000000000000000000000000000..44ad6a8502672fa7c788423d499407f65a47a834 --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/attention/unittests/mla/test_tokenspeed_mla.py @@ -0,0 +1,190 @@ +import importlib.util +import sys +import unittest +from pathlib import Path + +import torch + +from sglang.srt.model_executor.forward_batch_info import ForwardMode +from sglang.test.test_utils import CustomTestCase + +sys.path.insert(0, str(Path(__file__).resolve().parents[1])) + +from sglang.test.kits.attention_unittest.attention_methods.mla_attention import ( + MLAAttentionCase, + run_mla_attention_case, +) + +# tokenspeed_mla is a CuTe DSL backend for Blackwell (SM100). It additionally +# enforces: +# - kv_cache_dtype == torch.float8_e4m3fn (kv_cache_dtype=fp8_e4m3) +# - page_size in {32, 64} +# See python/sglang/srt/layers/attention/tokenspeed_mla_backend.py and +# is_tokenspeed_mla_available() in python/sglang/srt/utils/common.py. +# +# The shared MLAAttentionCase fixture now supports `fp8_kv_cache=True`: +# `MockMLAModelRunner` decouples `kv_cache_dtype` from the model `dtype` +# and routes K writes through the FP8 quantize path. The reference still +# computes against BF16 K (independent of the cache bytes) and tolerates +# FP8 quant noise via a looser tolerance. +_MIN_SM = 100 + + +def _supported() -> tuple[bool, str]: + if not torch.cuda.is_available(): + return False, "CUDA is required" + if importlib.util.find_spec("tokenspeed_mla") is None: + return False, "tokenspeed_mla python package is not installed" + major, minor = torch.cuda.get_device_capability() + sm = major * 10 + minor + if sm < _MIN_SM: + return ( + False, + f"tokenspeed_mla requires SM {_MIN_SM // 10}.{_MIN_SM % 10}+ (Blackwell), " + f"got SM {major}.{minor}", + ) + return True, "" + + +_SUPPORTED, _SKIP_REASON = _supported() + + +MLA_SHAPE_KWARGS = dict( + kv_lora_rank=512, + qk_rope_head_dim=64, + hidden_size=1024, + max_context_len=256, +) + + +from sglang.test.ci.ci_register import register_cuda_ci + +register_cuda_ci(est_time=15, stage="base-b", runner_config="4-gpu-b200") +register_cuda_ci(est_time=15, stage="base-b", runner_config="1-gpu-large") + + +@unittest.skipIf(not _SUPPORTED, _SKIP_REASON) +class TestTokenspeedMLAAttentionBackendCorrectness(CustomTestCase): + # tokenspeed_mla allows page_size in {32, 64} (server_args.py:2809-2813) + # and requires kv_cache_dtype==fp8_e4m3 (server_args.py:2814-2818). + # Cover both page sizes, with extend + decode + ragged + page-boundary. + CASES = ( + # ----- page_size=64 ----- + MLAAttentionCase( + name="mla_extend_tokenspeed_zero_prefix_exact_page_64", + backend="tokenspeed_mla", + forward_mode=ForwardMode.EXTEND, + num_heads=4, + page_size=64, + prefix_lens=(0,), + extend_lens=(64,), + ), + MLAAttentionCase( + name="mla_extend_tokenspeed_zero_prefix_below_page_64", + backend="tokenspeed_mla", + forward_mode=ForwardMode.EXTEND, + num_heads=4, + page_size=64, + prefix_lens=(0,), + extend_lens=(63,), + ), + MLAAttentionCase( + name="mla_extend_tokenspeed_zero_prefix_above_page_64", + backend="tokenspeed_mla", + forward_mode=ForwardMode.EXTEND, + num_heads=4, + page_size=64, + prefix_lens=(0,), + extend_lens=(65,), + ), + MLAAttentionCase( + name="mla_extend_tokenspeed_prefix_exact_page_64", + backend="tokenspeed_mla", + forward_mode=ForwardMode.EXTEND, + num_heads=4, + page_size=64, + prefix_lens=(64,), + extend_lens=(4,), + ), + MLAAttentionCase( + name="mla_extend_tokenspeed_cross_page_boundary_64", + backend="tokenspeed_mla", + forward_mode=ForwardMode.EXTEND, + num_heads=4, + page_size=64, + prefix_lens=(63,), + extend_lens=(2,), + ), + MLAAttentionCase( + name="mla_extend_tokenspeed_ragged_page_boundary_64", + backend="tokenspeed_mla", + forward_mode=ForwardMode.EXTEND, + num_heads=4, + page_size=64, + prefix_lens=(0, 32, 64), + extend_lens=(63, 32, 1), + ), + MLAAttentionCase( + name="mla_decode_tokenspeed_page_boundary_64", + backend="tokenspeed_mla", + forward_mode=ForwardMode.DECODE, + num_heads=4, + page_size=64, + prefix_lens=(62, 63, 64), + ), + MLAAttentionCase( + name="mla_decode_tokenspeed_bsz1_nonzero_prefix_64", + backend="tokenspeed_mla", + forward_mode=ForwardMode.DECODE, + num_heads=4, + page_size=64, + prefix_lens=(31,), + ), + # ----- page_size=32 ----- + MLAAttentionCase( + name="mla_extend_tokenspeed_zero_prefix_exact_page_32", + backend="tokenspeed_mla", + forward_mode=ForwardMode.EXTEND, + num_heads=4, + page_size=32, + prefix_lens=(0,), + extend_lens=(32,), + ), + MLAAttentionCase( + name="mla_extend_tokenspeed_cross_page_boundary_32", + backend="tokenspeed_mla", + forward_mode=ForwardMode.EXTEND, + num_heads=4, + page_size=32, + prefix_lens=(31,), + extend_lens=(2,), + ), + MLAAttentionCase( + name="mla_decode_tokenspeed_page_boundary_32", + backend="tokenspeed_mla", + forward_mode=ForwardMode.DECODE, + num_heads=4, + page_size=32, + prefix_lens=(30, 31, 32), + ), + ) + + def test_projected_mla_attention_cases(self): + for case in self.CASES: + with self.subTest(case=case.name, backend=case.backend): + # Looser tolerance to absorb FP8 quant noise (the reference + # reads BF16 K independent of the FP8 cache, so per-element + # drift from the BF16->FP8 cast accumulates through the + # attention reduction). + run_mla_attention_case( + self, + case, + fp8_kv_cache=True, + atol=2e-1, + rtol=2e-1, + **MLA_SHAPE_KWARGS, + ) + + +if __name__ == "__main__": + unittest.main() diff --git a/asian_ai/performance/SGLang/test/registered/attention/unittests/mla/test_triton.py b/asian_ai/performance/SGLang/test/registered/attention/unittests/mla/test_triton.py new file mode 100644 index 0000000000000000000000000000000000000000..3fbe4d21d07268f606d728b3ae60a86bfe2589e9 --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/attention/unittests/mla/test_triton.py @@ -0,0 +1,375 @@ +import sys +import unittest +from pathlib import Path + +import torch + +from sglang.srt.model_executor.forward_batch_info import ForwardMode +from sglang.test.test_utils import CustomTestCase + +sys.path.insert(0, str(Path(__file__).resolve().parents[1])) + +from sglang.test.ci.ci_register import register_cuda_ci +from sglang.test.kits.attention_unittest.attention_methods.mla_attention import ( + MLAAttentionCase, + make_mla_cases, + run_mla_attention_case, +) +from sglang.test.kits.attention_unittest.runner_modes.cuda_graph_decode_runner import ( + run_mla_cuda_graph_decode_case, +) +from sglang.test.kits.attention_unittest.runner_modes.speculative_draft_extend_runner import ( + run_mla_draft_extend_v2_cuda_graph_case, + run_mla_eagle_draft_extend_v2_cuda_graph_runner_case, +) +from sglang.test.kits.attention_unittest.runner_modes.speculative_draft_runner import ( + run_mla_eagle_draft_cuda_graph_runner_case, +) +from sglang.test.kits.attention_unittest.runner_modes.speculative_target_verify_runner import ( + run_mla_eagle_verify_case, + run_mla_eagle_verify_cuda_graph_case, +) +from sglang.test.kits.attention_unittest.runner_modes.split_op_runner import ( + run_mla_split_op_extend_case, +) + +register_cuda_ci(est_time=25, stage="base-b", runner_config="4-gpu-b200") +register_cuda_ci(est_time=25, stage="base-b", runner_config="1-gpu-large") + + +@unittest.skipIf(not torch.cuda.is_available(), "CUDA is required") +class TestTritonMLAAttentionBackendCorrectness(CustomTestCase): + CASES = make_mla_cases("triton") + CUDA_GRAPH_CASES = ( + MLAAttentionCase( + name="runner_cuda_graph_decode_page_boundary", + backend="triton", + forward_mode=ForwardMode.DECODE, + num_heads=4, + page_size=16, + prefix_lens=(14, 15, 16), + ), + ) + SPLIT_OP_CASES = ( + ( + MLAAttentionCase( + name="runner_split_op_mla_extend_ragged_page_boundary", + backend="triton", + forward_mode=ForwardMode.EXTEND, + num_heads=4, + page_size=16, + prefix_lens=(0, 8, 16), + extend_lens=(15, 8, 1), + ), + 32, + ), + ) + # Spec verify covers EAGLE chain + tree plus the non-EAGLE chain + # spec kinds (frozen_kv_mtp, dflash, ngram). FlashInfer MLA and + # FlashMLA only support EAGLE — their forward_extend reads + # EAGLE-specific spec_info attrs and trips a CUDA illegal-memory + # access on the other kinds — so this matrix is Triton-only. + EAGLE_VERIFY_CASES = ( + ( + MLAAttentionCase( + name="runner_eagle_verify_mla_chain", + backend="triton", + forward_mode=ForwardMode.TARGET_VERIFY, + num_heads=4, + page_size=16, + prefix_lens=(4, 7), + extend_lens=(3, 3), + ), + 1, + "eagle", + ), + ( + MLAAttentionCase( + name="runner_eagle_verify_mla_tree", + backend="triton", + forward_mode=ForwardMode.TARGET_VERIFY, + num_heads=4, + page_size=16, + prefix_lens=(4, 7), + extend_lens=(3, 3), + ), + 2, + "eagle", + ), + ( + MLAAttentionCase( + name="runner_frozen_kv_mtp_verify_mla_chain", + backend="triton", + forward_mode=ForwardMode.TARGET_VERIFY, + num_heads=4, + page_size=16, + prefix_lens=(4, 7), + extend_lens=(3, 3), + ), + 1, + "frozen_kv_mtp", + ), + ( + MLAAttentionCase( + name="runner_dflash_verify_mla_chain", + backend="triton", + forward_mode=ForwardMode.TARGET_VERIFY, + num_heads=4, + page_size=16, + prefix_lens=(4, 7), + extend_lens=(3, 3), + ), + 1, + "dflash", + ), + ( + MLAAttentionCase( + name="runner_ngram_verify_mla_chain", + backend="triton", + forward_mode=ForwardMode.TARGET_VERIFY, + num_heads=4, + page_size=16, + prefix_lens=(4, 7), + extend_lens=(3, 3), + ), + 1, + "ngram", + ), + ) + EAGLE_VERIFY_CUDA_GRAPH_CASES = ( + ( + MLAAttentionCase( + name="runner_cuda_graph_eagle_verify_mla_chain", + backend="triton", + forward_mode=ForwardMode.TARGET_VERIFY, + num_heads=4, + page_size=16, + prefix_lens=(4, 7), + extend_lens=(3, 3), + ), + 1, + "eagle", + ), + ( + MLAAttentionCase( + name="runner_cuda_graph_eagle_verify_mla_tree", + backend="triton", + forward_mode=ForwardMode.TARGET_VERIFY, + num_heads=4, + page_size=16, + prefix_lens=(4, 7), + extend_lens=(3, 3), + ), + 2, + "eagle", + ), + ( + MLAAttentionCase( + name="runner_cuda_graph_frozen_kv_mtp_verify_mla_chain", + backend="triton", + forward_mode=ForwardMode.TARGET_VERIFY, + num_heads=4, + page_size=16, + prefix_lens=(4, 7), + extend_lens=(3, 3), + ), + 1, + "frozen_kv_mtp", + ), + ( + MLAAttentionCase( + name="runner_cuda_graph_dflash_verify_mla_chain", + backend="triton", + forward_mode=ForwardMode.TARGET_VERIFY, + num_heads=4, + page_size=16, + prefix_lens=(4, 7), + extend_lens=(3, 3), + ), + 1, + "dflash", + ), + ( + MLAAttentionCase( + name="runner_cuda_graph_ngram_verify_mla_chain", + backend="triton", + forward_mode=ForwardMode.TARGET_VERIFY, + num_heads=4, + page_size=16, + prefix_lens=(4, 7), + extend_lens=(3, 3), + ), + 1, + "ngram", + ), + ) + DRAFT_EXTEND_V2_CUDA_GRAPH_CASES = ( + MLAAttentionCase( + name="runner_cuda_graph_eagle_draft_extend_v2_mla_fixed_tokens", + backend="triton", + forward_mode=ForwardMode.DRAFT_EXTEND_V2, + num_heads=4, + page_size=16, + prefix_lens=(4, 7), + extend_lens=(3, 3), + ), + ) + EAGLE_DRAFT_EXTEND_V2_RUNNER_CASES = ( + MLAAttentionCase( + name="runner_eagle_draft_extend_v2_mla_cuda_graph_runner_fixed_tokens", + backend="triton", + forward_mode=ForwardMode.DRAFT_EXTEND_V2, + num_heads=4, + page_size=16, + prefix_lens=(4, 7), + extend_lens=(3, 3), + ), + ) + EAGLE_DRAFT_RUNNER_CASES = ( + ( + MLAAttentionCase( + name="runner_eagle_draft_decode_mla_cuda_graph_chain", + backend="triton", + forward_mode=ForwardMode.DECODE, + num_heads=4, + page_size=16, + prefix_lens=(4, 7), + ), + 1, + 3, + ), + ( + MLAAttentionCase( + name="runner_eagle_draft_decode_mla_cuda_graph_tree", + backend="triton", + forward_mode=ForwardMode.DECODE, + num_heads=4, + page_size=1, + prefix_lens=(4, 7), + ), + 2, + 4, + ), + ) + + def test_tiny_deepseek_mla_attention_cases(self): + for case in self.CASES: + with self.subTest(case=case.name, backend=case.backend): + run_mla_attention_case(self, case) + + # Layout-robustness. See dense/test_triton.py for the full + # rationale. shuffled_pages is the default for all tests via + # build_mla_attention_fixture; this method opts into the more + # aggressive interleaved_pages + non_monotonic_extend layouts on a + # representative MLA extend + decode case. MLA Triton handles all + # non-tidy layouts cleanly. + LAYOUT_ROBUSTNESS_CASES = ( + MLAAttentionCase( + name="layout_mla_extend_prefix_exact_page", + backend="triton", + forward_mode=ForwardMode.EXTEND, + num_heads=4, + page_size=16, + prefix_lens=(16,), + extend_lens=(2,), + ), + MLAAttentionCase( + name="layout_mla_decode_page_boundary", + backend="triton", + forward_mode=ForwardMode.DECODE, + num_heads=4, + page_size=16, + prefix_lens=(14, 15, 16), + ), + ) + + def test_layout_robustness_cases(self): + for case in self.LAYOUT_ROBUSTNESS_CASES: + for layout in ("interleaved_pages", "non_monotonic_extend"): + if layout == "non_monotonic_extend" and case.forward_mode.is_decode(): + continue + with self.subTest(case=case.name, layout=layout): + run_mla_attention_case(self, case, loc_layout=layout) + + def test_runner_mode_cuda_graph_decode_cases(self): + for case in self.CUDA_GRAPH_CASES: + with self.subTest(case=case.name, backend=case.backend): + run_mla_cuda_graph_decode_case(self, case) + + def test_runner_mode_split_op_extend_cases(self): + for case, static_num_tokens in self.SPLIT_OP_CASES: + for breakable in (False, True): + runner = "bcg" if breakable else "pcg" + with self.subTest( + case=case.name, + backend=case.backend, + runner=runner, + ): + run_mla_split_op_extend_case( + self, + case, + breakable=breakable, + static_num_tokens=static_num_tokens, + ) + + def test_runner_mode_eagle_verify_cases(self): + for case, topk, spec_kind in self.EAGLE_VERIFY_CASES: + with self.subTest( + case=case.name, + backend=case.backend, + topk=topk, + spec_kind=spec_kind, + ): + run_mla_eagle_verify_case(self, case, topk=topk, spec_kind=spec_kind) + + def test_runner_mode_eagle_verify_cuda_graph_cases(self): + for case, topk, spec_kind in self.EAGLE_VERIFY_CUDA_GRAPH_CASES: + with self.subTest( + case=case.name, + backend=case.backend, + topk=topk, + spec_kind=spec_kind, + ): + run_mla_eagle_verify_cuda_graph_case( + self, case, topk=topk, spec_kind=spec_kind + ) + + def test_runner_mode_eagle_draft_extend_v2_cuda_graph_cases(self): + for case in self.DRAFT_EXTEND_V2_CUDA_GRAPH_CASES: + for pad_style in ("small_real", "prod_fill"): + for capture_bs in ( + case.batch_size, + case.batch_size * 2, + case.batch_size * 4, + ): + with self.subTest( + case=case.name, + backend=case.backend, + pad_style=pad_style, + capture_bs=capture_bs, + ): + run_mla_draft_extend_v2_cuda_graph_case( + self, + case, + cuda_graph_capture_batch_size=capture_bs, + pad_style=pad_style, + ) + + def test_runner_mode_eagle_draft_extend_v2_cuda_graph_runner_cases(self): + for case in self.EAGLE_DRAFT_EXTEND_V2_RUNNER_CASES: + with self.subTest(case=case.name, backend=case.backend): + run_mla_eagle_draft_extend_v2_cuda_graph_runner_case(self, case) + + def test_runner_mode_eagle_draft_cuda_graph_runner_cases(self): + for case, topk, num_draft_tokens in self.EAGLE_DRAFT_RUNNER_CASES: + with self.subTest(case=case.name, backend=case.backend, topk=topk): + run_mla_eagle_draft_cuda_graph_runner_case( + self, + case, + topk=topk, + speculative_num_draft_tokens=num_draft_tokens, + ) + + +if __name__ == "__main__": + unittest.main() diff --git a/asian_ai/performance/SGLang/test/registered/attention/unittests/mla/test_trtllm_mla.py b/asian_ai/performance/SGLang/test/registered/attention/unittests/mla/test_trtllm_mla.py new file mode 100644 index 0000000000000000000000000000000000000000..987c3fe6c57e3343d66342050d35426d052363b8 --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/attention/unittests/mla/test_trtllm_mla.py @@ -0,0 +1,166 @@ +import sys +import unittest +from pathlib import Path + +import torch + +from sglang.srt.model_executor.forward_batch_info import ForwardMode +from sglang.test.test_utils import CustomTestCase + +sys.path.insert(0, str(Path(__file__).resolve().parents[1])) + +from sglang.test.kits.attention_unittest.attention_methods.mla_attention import ( + MLAAttentionCase, + run_mla_attention_case, +) + +# trtllm_mla goes through FlashInfer's XQA MLA path. Per PLAN.md and the +# project's is_sm120_supported helper (device_capability_majors=[12]), the +# decode path requires SM120a / SM121a (Blackwell variants), i.e. major==12. +# The backend itself has no hard gate — failure surfaces inside FlashInfer at +# kernel-dispatch time — so we mirror is_sm120_supported here. +_REQUIRED_MAJOR = 12 + +MLA_SHAPE_KWARGS = dict( + kv_lora_rank=512, + qk_rope_head_dim=64, + hidden_size=1024, + max_context_len=256, +) + + +def _supported() -> tuple[bool, str]: + if not torch.cuda.is_available(): + return False, "CUDA is required" + major, minor = torch.cuda.get_device_capability() + if major != _REQUIRED_MAJOR: + return ( + False, + f"trtllm_mla requires SM 12.0a / 12.1a (FlashInfer XQA MLA), " + f"got SM {major}.{minor}", + ) + return True, "" + + +_SUPPORTED, _SKIP_REASON = _supported() + + +from sglang.test.ci.ci_register import register_cuda_ci + +register_cuda_ci(est_time=15, stage="base-b", runner_config="4-gpu-b200") +register_cuda_ci(est_time=15, stage="base-b", runner_config="1-gpu-large") + + +@unittest.skipIf(not _SUPPORTED, _SKIP_REASON) +class TestTRTLLMMLAAttentionBackendCorrectness(CustomTestCase): + # trtllm_mla allows page_size in {32, 64} (server_args.py:2790-2794). + # Cover both, with extend + decode + ragged + page-boundary layouts. + CASES = ( + # ----- page_size=64 ----- + MLAAttentionCase( + name="mla_extend_trtllm_zero_prefix_exact_page_64", + backend="trtllm_mla", + forward_mode=ForwardMode.EXTEND, + num_heads=4, + page_size=64, + prefix_lens=(0,), + extend_lens=(64,), + ), + MLAAttentionCase( + name="mla_extend_trtllm_zero_prefix_below_page_64", + backend="trtllm_mla", + forward_mode=ForwardMode.EXTEND, + num_heads=4, + page_size=64, + prefix_lens=(0,), + extend_lens=(63,), + ), + MLAAttentionCase( + name="mla_extend_trtllm_zero_prefix_above_page_64", + backend="trtllm_mla", + forward_mode=ForwardMode.EXTEND, + num_heads=4, + page_size=64, + prefix_lens=(0,), + extend_lens=(65,), + ), + MLAAttentionCase( + name="mla_extend_trtllm_prefix_exact_page_64", + backend="trtllm_mla", + forward_mode=ForwardMode.EXTEND, + num_heads=4, + page_size=64, + prefix_lens=(64,), + extend_lens=(4,), + ), + MLAAttentionCase( + name="mla_extend_trtllm_cross_page_boundary_64", + backend="trtllm_mla", + forward_mode=ForwardMode.EXTEND, + num_heads=4, + page_size=64, + prefix_lens=(63,), + extend_lens=(2,), + ), + MLAAttentionCase( + name="mla_extend_trtllm_ragged_page_boundary_64", + backend="trtllm_mla", + forward_mode=ForwardMode.EXTEND, + num_heads=4, + page_size=64, + prefix_lens=(0, 32, 64), + extend_lens=(63, 32, 1), + ), + MLAAttentionCase( + name="mla_decode_trtllm_page_boundary_64", + backend="trtllm_mla", + forward_mode=ForwardMode.DECODE, + num_heads=4, + page_size=64, + prefix_lens=(62, 63, 64), + ), + MLAAttentionCase( + name="mla_decode_trtllm_bsz1_nonzero_prefix_64", + backend="trtllm_mla", + forward_mode=ForwardMode.DECODE, + num_heads=4, + page_size=64, + prefix_lens=(31,), + ), + # ----- page_size=32 ----- + MLAAttentionCase( + name="mla_extend_trtllm_zero_prefix_exact_page_32", + backend="trtllm_mla", + forward_mode=ForwardMode.EXTEND, + num_heads=4, + page_size=32, + prefix_lens=(0,), + extend_lens=(32,), + ), + MLAAttentionCase( + name="mla_extend_trtllm_cross_page_boundary_32", + backend="trtllm_mla", + forward_mode=ForwardMode.EXTEND, + num_heads=4, + page_size=32, + prefix_lens=(31,), + extend_lens=(2,), + ), + MLAAttentionCase( + name="mla_decode_trtllm_page_boundary_32", + backend="trtllm_mla", + forward_mode=ForwardMode.DECODE, + num_heads=4, + page_size=32, + prefix_lens=(30, 31, 32), + ), + ) + + def test_projected_mla_attention_cases(self): + for case in self.CASES: + with self.subTest(case=case.name, backend=case.backend): + run_mla_attention_case(self, case, **MLA_SHAPE_KWARGS) + + +if __name__ == "__main__": + unittest.main() diff --git a/asian_ai/performance/SGLang/test/registered/attention/unittests/swa/README.md b/asian_ai/performance/SGLang/test/registered/attention/unittests/swa/README.md new file mode 100644 index 0000000000000000000000000000000000000000..ced0da30d03427643540018f08e1f2b33077486a --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/attention/unittests/swa/README.md @@ -0,0 +1,63 @@ +# Sliding Window Attention Capability Matrix + +This folder covers dense attention with a finite `sliding_window_size`. +Expected outputs use the dense HF-style PyTorch reference with sliding-window +masking, not a second backend call. The SWA fixture is the dense fixture +reused with `sliding_window_size != None`. + +## Coverage Matrix + +Columns are runner modes; rows are attention backends. Cells use: +- **✓ \** — exercised, with the config variants listed in the cell +- **—** — not applicable (no production path for this combination) +- **blocked: \** — production-unsupported, not a follow-up +- **deferred: \** — could land later, currently disabled + +| Backend | Eager Phase 2 | CG decode | PCG extend | BCG extend | Verify eager | Verify CG | DE eager | DE CG | DE-V2 CG | EAGLE-draft runner | EAGLE-DE runner | FKVMTP runner | +|---|---|---|---|---|---|---|---|---|---|---|---|---| +| `torch_native` | ✓ no-prefix + prefix window edges, MHA + GQA decode window edges (uses explicit SDPA local-attention mask) | — (no CG hooks) | — (no CG path) | — (no CG path) | — | — | — | — | — | — | — | — | +| `triton` | ✓ no-prefix lengths below/equal/above window + prefix lengths below/equal/above window | ✓ within-window decode (`prefix_lens=(1,2,3)`, `window=4`) + above-window decode (`prefix_lens=(7,8,9)`, `window=4`) | ✓ no-prefix window edges, prefix-within-window MHA extend | ✓ same as PCG | ✓ EAGLE chain (topk=1) + EAGLE tree (topk=2), `window=4` | ✓ EAGLE tree within-window + EAGLE chain above-window (`prefix_lens=(6,8)`, `window=4`) | — | — | — | — | — | — | +| `flashinfer` | ✓ no-prefix lengths below/equal/above window (`head_dim=64` for SM90) | ✓ within-window decode | ✓ no-prefix window edges (MHA extend) | ✓ same as PCG | ✓ DFLASH chain (`topk=1`, `window=4`) | ✓ DFLASH chain (`topk=1`, `window=4`) | — | — | — | — | — | — | + +## Input And Config Coverage + +- No-prefix lengths below / equal / above the configured `sliding_window_size`. +- For `triton`: matching prefix-length cases. +- For `torch_native`: extra MHA + GQA decode cases at the window edge. +- CG decode covers both within-window (`min(seq_lens, window)` clipped) and + above-window (full window clip) for `triton`. + +## Notes on the "—" cells + +- **`torch_native` graph rows** — same as dense: no CUDA-graph capture/replay + hooks (`base_attn_backend.py:24-55` raises `NotImplementedError`). +- **SWA-only methods** — DSV4 SWA, DSA dense fallback, and other SWA-shaped + paths live in their own folders. This folder is strictly the dense MHA/GQA + backend with a finite window. + +## Mutation Coverage Notes + +- The CG-decode above-window case (`runner_cuda_graph_swa_decode_above_window`) + exists specifically to expose the `sliding_window_size + 1` mutation at + `triton_backend.py:786` (M5). The dense reference picks the matching SWA mask + rule based on `case.backend in _SWA_AWARE_DECODE_BACKENDS` and + `case.forward_mode.is_decode()`. +- The Verify CG above-window case + (`runner_cuda_graph_eagle_verify_swa_above_window`) extends above-window + coverage to the verify replay path, but does not catch M6 by itself — the + extend kernel re-masks `kv_id >= q_id - sliding_window_size` so the +1 shift + the mutation introduces is dropped. See `MUTATION_FIXES.md`. + +## Production-Unsupported + +- **FlashInfer SWA `DRAFT_EXTEND`** — not covered here. The FlashInfer SWA + coverage added for this path is limited to DFLASH `TARGET_VERIFY`. +- **`torch_native` SWA speculative / CUDA graph** — no CG hooks; all graph + integration is structurally unsupported. + +## Next Work + +- Investigate the Triton above-window decode/reference numerical detail + separately (the above-window case currently asserts within tolerance with the + matching reference rule; if a real backend regression appears, lower the + tolerance). diff --git a/asian_ai/performance/SGLang/test/registered/attention/unittests/swa/__init__.py b/asian_ai/performance/SGLang/test/registered/attention/unittests/swa/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..85cb705d06897932badee1c9887a196f37adced3 --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/attention/unittests/swa/__init__.py @@ -0,0 +1 @@ +"""Sliding-window attention backend tests.""" diff --git a/asian_ai/performance/SGLang/test/registered/attention/unittests/swa/test_flashinfer.py b/asian_ai/performance/SGLang/test/registered/attention/unittests/swa/test_flashinfer.py new file mode 100644 index 0000000000000000000000000000000000000000..27d81d3871e5880cbe6c26b9c27fb8a28f0c0c2f --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/attention/unittests/swa/test_flashinfer.py @@ -0,0 +1,248 @@ +import sys +import unittest +from pathlib import Path + +import torch + +from sglang.srt.model_executor.forward_batch_info import ForwardMode +from sglang.srt.utils import is_flashinfer_available +from sglang.test.test_utils import CustomTestCase + +sys.path.insert(0, str(Path(__file__).resolve().parents[1])) + +from sglang.test.ci.ci_register import register_cuda_ci +from sglang.test.kits.attention_unittest.attention_methods.dense_attention import ( + DenseAttentionCase, + make_swa_no_prefix_input_config_cases, + make_swa_prefix_input_config_cases, + run_dense_attention_case, +) +from sglang.test.kits.attention_unittest.runner_modes.cuda_graph_decode_runner import ( + run_dense_cuda_graph_decode_case, +) +from sglang.test.kits.attention_unittest.runner_modes.speculative_target_verify_runner import ( + run_dense_spec_verify_case, + run_dense_spec_verify_cuda_graph_case, +) +from sglang.test.kits.attention_unittest.runner_modes.split_op_runner import ( + run_dense_split_op_extend_case, +) + +register_cuda_ci(est_time=20, stage="base-b", runner_config="4-gpu-b200") +register_cuda_ci(est_time=20, stage="base-b", runner_config="1-gpu-large") + + +@unittest.skipIf( + not torch.cuda.is_available() or not is_flashinfer_available(), + "CUDA + flashinfer are required", +) +class TestFlashInferSWAAttentionBackendCorrectness(CustomTestCase): + # FlashInfer SM90 prefill kernels require value head dim in {64, 128, 256}. + HEAD_DIM = 64 + HIDDEN_SIZE = 256 + + CASES = make_swa_no_prefix_input_config_cases( + "flashinfer" + ) + make_swa_prefix_input_config_cases("flashinfer") + # Above-window decode case requires the `extend_window` reference rule + # (window+1 keys), not the `min_seq_len_window` rule — FlashInfer's + # decode metadata uses `clamp(seq_lens, max=window+1)` per + # `flashinfer_backend.py:1031`. See `_SWA_DECODE_EXTEND_WINDOW` in + # `common/attention_methods/dense_attention.py`. + CUDA_GRAPH_CASES = ( + DenseAttentionCase( + name="runner_cuda_graph_swa_decode_within_window", + backend="flashinfer", + forward_mode=ForwardMode.DECODE, + num_heads=4, + num_kv_heads=4, + page_size=16, + prefix_lens=(1, 2, 3), + sliding_window_size=4, + ), + DenseAttentionCase( + name="runner_cuda_graph_swa_decode_above_window", + backend="flashinfer", + forward_mode=ForwardMode.DECODE, + num_heads=4, + num_kv_heads=4, + page_size=16, + prefix_lens=(7, 8, 9), + sliding_window_size=4, + ), + ) + # NOTE: a `runner_split_op_swa_extend_prefix_within_window` clone of the + # triton SWA test fails on flashinfer (~0.21 max diff). FlashInfer's + # prefill-split path does not handle SWA prefix the same way as triton; + # the projected EXTEND covers the prefix path through the unsplit kernel + # which does match the reference. Investigate before adding split_op + # prefix to flashinfer SWA. + SPLIT_OP_CASES = ( + ( + DenseAttentionCase( + name="runner_split_op_swa_extend_no_prefix_window_edges", + backend="flashinfer", + forward_mode=ForwardMode.EXTEND, + num_heads=4, + num_kv_heads=4, + page_size=16, + prefix_lens=(0, 0, 0), + extend_lens=(3, 4, 5), + sliding_window_size=4, + ), + 16, + ), + ) + SPEC_VERIFY_CASES = ( + ( + DenseAttentionCase( + name="runner_dflash_verify_swa_chain", + backend="flashinfer", + forward_mode=ForwardMode.TARGET_VERIFY, + num_heads=4, + num_kv_heads=4, + page_size=16, + prefix_lens=(3, 5), + extend_lens=(3, 3), + sliding_window_size=4, + ), + 1, + "dflash", + ), + ) + SPEC_VERIFY_CUDA_GRAPH_CASES = ( + ( + DenseAttentionCase( + name="runner_cuda_graph_dflash_verify_swa_chain", + backend="flashinfer", + forward_mode=ForwardMode.TARGET_VERIFY, + num_heads=4, + num_kv_heads=4, + page_size=16, + prefix_lens=(3, 5), + extend_lens=(3, 3), + sliding_window_size=4, + ), + 1, + "dflash", + ), + ) + + def test_projected_swa_attention_cases(self): + for case in self.CASES: + with self.subTest(case=case.name, backend=case.backend): + run_dense_attention_case( + self, + case, + head_dim=self.HEAD_DIM, + hidden_size=self.HIDDEN_SIZE, + ) + + # Layout-robustness. See dense/test_triton.py for the full rationale. + # The default `shuffled_pages` is already exercised by + # test_projected_swa_attention_cases on the existing case list. + # This method opts into the more aggressive interleaved_pages + + # non_monotonic_extend on within-window extend + decode. + LAYOUT_ROBUSTNESS_CASES = ( + DenseAttentionCase( + name="layout_swa_extend_below_window", + backend="flashinfer", + forward_mode=ForwardMode.EXTEND, + num_heads=8, + num_kv_heads=4, + page_size=16, + prefix_lens=(0,), + extend_lens=(10,), + sliding_window_size=12, + ), + DenseAttentionCase( + name="layout_swa_decode_within_window", + backend="flashinfer", + forward_mode=ForwardMode.DECODE, + num_heads=8, + num_kv_heads=4, + page_size=16, + prefix_lens=(8, 10), + sliding_window_size=12, + ), + ) + + def test_layout_robustness_cases(self): + for case in self.LAYOUT_ROBUSTNESS_CASES: + for layout in ("interleaved_pages", "non_monotonic_extend"): + if layout == "non_monotonic_extend" and case.forward_mode.is_decode(): + continue + with self.subTest(case=case.name, layout=layout): + run_dense_attention_case( + self, + case, + head_dim=self.HEAD_DIM, + hidden_size=self.HIDDEN_SIZE, + loc_layout=layout, + ) + + def test_runner_mode_cuda_graph_decode_cases(self): + for case in self.CUDA_GRAPH_CASES: + with self.subTest(case=case.name, backend=case.backend): + run_dense_cuda_graph_decode_case( + self, + case, + head_dim=self.HEAD_DIM, + hidden_size=self.HIDDEN_SIZE, + ) + + def test_runner_mode_split_op_extend_cases(self): + for case, static_num_tokens in self.SPLIT_OP_CASES: + for breakable in (False, True): + runner = "bcg" if breakable else "pcg" + with self.subTest( + case=case.name, + backend=case.backend, + runner=runner, + ): + run_dense_split_op_extend_case( + self, + case, + breakable=breakable, + static_num_tokens=static_num_tokens, + head_dim=self.HEAD_DIM, + hidden_size=self.HIDDEN_SIZE, + ) + + def test_runner_mode_spec_verify_cases(self): + for case, topk, spec_kind in self.SPEC_VERIFY_CASES: + with self.subTest( + case=case.name, + backend=case.backend, + topk=topk, + spec_kind=spec_kind, + ): + run_dense_spec_verify_case( + self, + case, + topk=topk, + spec_kind=spec_kind, + head_dim=self.HEAD_DIM, + hidden_size=self.HIDDEN_SIZE, + ) + + def test_runner_mode_spec_verify_cuda_graph_cases(self): + for case, topk, spec_kind in self.SPEC_VERIFY_CUDA_GRAPH_CASES: + with self.subTest( + case=case.name, + backend=case.backend, + topk=topk, + spec_kind=spec_kind, + ): + run_dense_spec_verify_cuda_graph_case( + self, + case, + topk=topk, + spec_kind=spec_kind, + head_dim=self.HEAD_DIM, + hidden_size=self.HIDDEN_SIZE, + ) + + +if __name__ == "__main__": + unittest.main() diff --git a/asian_ai/performance/SGLang/test/registered/attention/unittests/swa/test_swa_out_cache_loc.py b/asian_ai/performance/SGLang/test/registered/attention/unittests/swa/test_swa_out_cache_loc.py new file mode 100644 index 0000000000000000000000000000000000000000..456c6e65a29662e608aea60153d232b9488f857e --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/attention/unittests/swa/test_swa_out_cache_loc.py @@ -0,0 +1,88 @@ +"""Unit coverage for SWAKVPool.set_kv_buffer with a pre-translated swa_loc. + +The attention backend translates out_cache_loc once per forward and passes it +in via a ``KVWriteLoc`` (loc + swa_loc) on the loc_info argument; set_kv_buffer +uses swa_loc directly for SWA layers and asserts it is provided. The per-backend +cuda-graph buffer plumbing is covered by the backend SWA integration tests. +""" + +import sys +import unittest +from pathlib import Path +from types import SimpleNamespace + +import torch + +from sglang.srt.mem_cache.memory_pool import KVWriteLoc +from sglang.srt.mem_cache.swa_memory_pool import SWAKVPool +from sglang.test.test_utils import CustomTestCase + +sys.path.insert(0, str(Path(__file__).resolve().parents[1])) + +from sglang.test.ci.ci_register import register_cpu_ci + +register_cpu_ci(est_time=5, suite="base-a-test-cpu") + + +class TestSWAKVPoolSetKVBuffer(CustomTestCase): + """set_kv_buffer: SWA layers require a pre-translated swa_loc; full layers + use loc unchanged.""" + + def _pool_and_record(self): + pool = object.__new__(SWAKVPool) + # layer 0 -> full pool, layer 1 -> swa pool + pool.layers_mapping = {0: (0, False), 1: (0, True)} + recorded = {} + + def _swa_set(layer, loc, k, v, k_scale, v_scale, layer_id_override): + recorded["swa_loc"] = loc + + def _full_set(layer, loc, k, v, k_scale, v_scale, layer_id_override): + recorded["full_loc"] = loc + + pool.swa_kv_pool = SimpleNamespace(set_kv_buffer=_swa_set) + pool.full_kv_pool = SimpleNamespace(set_kv_buffer=_full_set) + return pool, recorded + + def test_swa_layer_uses_swa_loc_directly(self): + pool, recorded = self._pool_and_record() + swa_loc = torch.tensor([7, 8]) + pool.set_kv_buffer( + SimpleNamespace(layer_id=1), + KVWriteLoc(torch.tensor([3, 4]), swa_loc), + None, + None, + ) + self.assertIs(recorded["swa_loc"], swa_loc) + + def test_swa_layer_requires_swa_loc(self): + # set_kv_buffer never translates internally; SWA layers must be given a + # pre-translated swa_loc (loc_info without swa_loc, or a bare loc). + pool, _ = self._pool_and_record() + with self.assertRaises(AssertionError): + pool.set_kv_buffer( + SimpleNamespace(layer_id=1), torch.tensor([3, 4]), None, None + ) + with self.assertRaises(AssertionError): + pool.set_kv_buffer( + SimpleNamespace(layer_id=1), + KVWriteLoc(torch.tensor([3, 4])), + None, + None, + ) + + def test_full_layer_ignores_swa_loc(self): + pool, recorded = self._pool_and_record() + loc = torch.tensor([3, 4]) + # Full layer: swa_loc supplied but ignored; loc is used. + pool.set_kv_buffer( + SimpleNamespace(layer_id=0), + KVWriteLoc(loc, torch.tensor([99, 99])), + None, + None, + ) + self.assertIs(recorded["full_loc"], loc) + + +if __name__ == "__main__": + unittest.main() diff --git a/asian_ai/performance/SGLang/test/registered/attention/unittests/swa/test_torch_native.py b/asian_ai/performance/SGLang/test/registered/attention/unittests/swa/test_torch_native.py new file mode 100644 index 0000000000000000000000000000000000000000..2daa2955109b566ce64dcd3347c5d3aa4ae1f92b --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/attention/unittests/swa/test_torch_native.py @@ -0,0 +1,140 @@ +import sys +import unittest +from pathlib import Path + +import torch + +from sglang.srt.model_executor.forward_batch_info import ForwardMode +from sglang.test.test_utils import CustomTestCase + +sys.path.insert(0, str(Path(__file__).resolve().parents[1])) + +from sglang.test.ci.ci_register import register_amd_ci, register_cuda_ci +from sglang.test.kits.attention_unittest.attention_methods.dense_attention import ( + DenseAttentionCase, + make_swa_no_prefix_input_config_cases, + make_swa_prefix_input_config_cases, + run_dense_attention_case, +) + +register_cuda_ci(est_time=20, stage="base-b", runner_config="4-gpu-b200") +register_cuda_ci(est_time=20, stage="base-b", runner_config="1-gpu-large") +register_amd_ci(est_time=20, suite="stage-b-test-1-gpu-large-amd") + + +@unittest.skipIf(not torch.cuda.is_available(), "CUDA is required") +class TestTorchNativeSWAAttentionBackendCorrectness(CustomTestCase): + CASES = ( + make_swa_no_prefix_input_config_cases("torch_native") + + make_swa_prefix_input_config_cases("torch_native") + + ( + DenseAttentionCase( + name="swa_decode_window_edges", + backend="torch_native", + forward_mode=ForwardMode.DECODE, + num_heads=4, + num_kv_heads=4, + page_size=16, + prefix_lens=(3, 4, 5), + sliding_window_size=4, + ), + DenseAttentionCase( + name="swa_gqa_decode_window_edges", + backend="torch_native", + forward_mode=ForwardMode.DECODE, + num_heads=4, + num_kv_heads=2, + page_size=16, + prefix_lens=(3, 4, 5), + sliding_window_size=4, + ), + ) + ) + # Eager runner-mode cases mirroring `dense/test_torch_native.py`. + # `torch_native` is the only SWA backend with no CG / split-op + # support (it raises `NotImplementedError` from + # `BaseAttnBackend.init_*_cuda_graph`), so the eager path is the + # only runner mode worth exercising. Cases pick up the SWA window + # via `sliding_window_size`. + RUNNER_EAGER_CASES = ( + DenseAttentionCase( + name="runner_eager_swa_decode_window_edges", + backend="torch_native", + forward_mode=ForwardMode.DECODE, + num_heads=4, + num_kv_heads=4, + page_size=16, + prefix_lens=(3, 4, 5), + sliding_window_size=4, + ), + DenseAttentionCase( + name="runner_eager_swa_extend_within_window", + backend="torch_native", + forward_mode=ForwardMode.EXTEND, + num_heads=4, + num_kv_heads=4, + page_size=16, + prefix_lens=(0,), + extend_lens=(3,), + sliding_window_size=4, + ), + DenseAttentionCase( + name="runner_eager_swa_gqa_decode_window_edges", + backend="torch_native", + forward_mode=ForwardMode.DECODE, + num_heads=4, + num_kv_heads=2, + page_size=16, + prefix_lens=(3, 4, 5), + sliding_window_size=4, + ), + ) + + def test_projected_swa_attention_cases(self): + for case in self.CASES: + with self.subTest(case=case.name, backend=case.backend): + run_dense_attention_case(self, case) + + def test_runner_mode_eager_cases(self): + for case in self.RUNNER_EAGER_CASES: + with self.subTest(case=case.name, backend=case.backend): + run_dense_attention_case(self, case) + + # Layout-robustness. See dense/test_triton.py for the rationale. + # torch_native SWA gathers K/V via cache locs without page-table + # arithmetic, so it's robust to all non-tidy layouts. + LAYOUT_ROBUSTNESS_CASES = ( + DenseAttentionCase( + name="layout_swa_extend_within_window", + backend="torch_native", + forward_mode=ForwardMode.EXTEND, + num_heads=8, + num_kv_heads=4, + page_size=16, + prefix_lens=(8, 16), + extend_lens=(8, 16), + sliding_window_size=12, + ), + DenseAttentionCase( + name="layout_swa_decode_page_boundary", + backend="torch_native", + forward_mode=ForwardMode.DECODE, + num_heads=8, + num_kv_heads=4, + page_size=16, + prefix_lens=(15, 16, 17), + sliding_window_size=12, + ), + ) + + def test_layout_robustness_cases(self): + for case in self.LAYOUT_ROBUSTNESS_CASES: + for layout in ("interleaved_pages", "non_monotonic_extend"): + if layout == "non_monotonic_extend" and case.forward_mode.is_decode(): + continue + with self.subTest(case=case.name, layout=layout): + run_dense_attention_case(self, case, loc_layout=layout) + + +if __name__ == "__main__": + unittest.main() diff --git a/asian_ai/performance/SGLang/test/registered/attention/unittests/swa/test_triton.py b/asian_ai/performance/SGLang/test/registered/attention/unittests/swa/test_triton.py new file mode 100644 index 0000000000000000000000000000000000000000..b1d5d0f18d32f3bc70db5ce3c5947de423c90f03 --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/attention/unittests/swa/test_triton.py @@ -0,0 +1,350 @@ +import sys +import unittest +from pathlib import Path + +import torch + +from sglang.srt.model_executor.forward_batch_info import ForwardMode +from sglang.srt.utils import is_hip +from sglang.test.test_utils import CustomTestCase + +sys.path.insert(0, str(Path(__file__).resolve().parents[1])) + +from sglang.test.ci.ci_register import register_amd_ci, register_cuda_ci +from sglang.test.kits.attention_unittest.attention_methods.dense_attention import ( + DenseAttentionCase, + make_swa_no_prefix_input_config_cases, + make_swa_prefix_input_config_cases, + run_dense_attention_case, +) +from sglang.test.kits.attention_unittest.runner_modes.cuda_graph_decode_runner import ( + run_dense_cuda_graph_decode_case, +) +from sglang.test.kits.attention_unittest.runner_modes.speculative_target_verify_runner import ( + run_dense_spec_verify_case, + run_dense_spec_verify_cuda_graph_case, +) +from sglang.test.kits.attention_unittest.runner_modes.split_op_runner import ( + run_dense_split_op_extend_case, +) + +register_cuda_ci(est_time=20, stage="base-b", runner_config="4-gpu-b200") +register_cuda_ci(est_time=20, stage="base-b", runner_config="1-gpu-large") +register_amd_ci(est_time=20, suite="stage-b-test-1-gpu-large-amd") + + +@unittest.skipIf(not torch.cuda.is_available(), "CUDA is required") +class TestTritonSWAAttentionBackendCorrectness(CustomTestCase): + CASES = make_swa_no_prefix_input_config_cases( + "triton" + ) + make_swa_prefix_input_config_cases("triton") + CUDA_GRAPH_CASES = ( + DenseAttentionCase( + name="runner_cuda_graph_swa_decode_within_window", + backend="triton", + forward_mode=ForwardMode.DECODE, + num_heads=4, + num_kv_heads=4, + page_size=16, + prefix_lens=(1, 2, 3), + sliding_window_size=4, + ), + # Above-window decode exercises the `min(seq_lens, window)` + # clipping in the replay metadata builder. + DenseAttentionCase( + name="runner_cuda_graph_swa_decode_above_window", + backend="triton", + forward_mode=ForwardMode.DECODE, + num_heads=4, + num_kv_heads=4, + page_size=16, + prefix_lens=(7, 8, 9), + sliding_window_size=4, + ), + ) + SPLIT_OP_CASES = ( + ( + DenseAttentionCase( + name="runner_split_op_swa_extend_no_prefix_window_edges", + backend="triton", + forward_mode=ForwardMode.EXTEND, + num_heads=4, + num_kv_heads=4, + page_size=16, + prefix_lens=(0, 0, 0), + extend_lens=(3, 4, 5), + sliding_window_size=4, + ), + 16, + ), + ( + DenseAttentionCase( + name="runner_split_op_swa_extend_prefix_within_window", + backend="triton", + forward_mode=ForwardMode.EXTEND, + num_heads=4, + num_kv_heads=4, + page_size=16, + prefix_lens=(1, 2, 3), + extend_lens=(1, 1, 1), + sliding_window_size=4, + ), + 4, + ), + ) + SPEC_VERIFY_CASES = ( + ( + DenseAttentionCase( + name="runner_eagle_verify_swa_chain", + backend="triton", + forward_mode=ForwardMode.TARGET_VERIFY, + num_heads=4, + num_kv_heads=4, + page_size=16, + prefix_lens=(3, 5), + extend_lens=(3, 3), + sliding_window_size=4, + ), + 1, + "eagle", + ), + ( + DenseAttentionCase( + name="runner_eagle_verify_swa_tree", + backend="triton", + forward_mode=ForwardMode.TARGET_VERIFY, + num_heads=4, + num_kv_heads=4, + page_size=16, + prefix_lens=(3, 5), + extend_lens=(3, 3), + sliding_window_size=4, + ), + 2, + "eagle", + ), + # Non-EAGLE chain spec kinds. The verify-path math under a + # sliding window is identical across kinds; only the draft + # tag in `_make_spec_verify_input` differs. + ( + DenseAttentionCase( + name="runner_frozen_kv_mtp_verify_swa_chain", + backend="triton", + forward_mode=ForwardMode.TARGET_VERIFY, + num_heads=4, + num_kv_heads=4, + page_size=16, + prefix_lens=(3, 5), + extend_lens=(3, 3), + sliding_window_size=4, + ), + 1, + "frozen_kv_mtp", + ), + ( + DenseAttentionCase( + name="runner_dflash_verify_swa_chain", + backend="triton", + forward_mode=ForwardMode.TARGET_VERIFY, + num_heads=4, + num_kv_heads=4, + page_size=16, + prefix_lens=(3, 5), + extend_lens=(3, 3), + sliding_window_size=4, + ), + 1, + "dflash", + ), + ( + DenseAttentionCase( + name="runner_ngram_verify_swa_chain", + backend="triton", + forward_mode=ForwardMode.TARGET_VERIFY, + num_heads=4, + num_kv_heads=4, + page_size=16, + prefix_lens=(3, 5), + extend_lens=(3, 3), + sliding_window_size=4, + ), + 1, + "ngram", + ), + ) + SPEC_VERIFY_CUDA_GRAPH_CASES = ( + ( + DenseAttentionCase( + name="runner_cuda_graph_eagle_verify_swa_tree", + backend="triton", + forward_mode=ForwardMode.TARGET_VERIFY, + num_heads=4, + num_kv_heads=4, + page_size=16, + prefix_lens=(3, 5), + extend_lens=(3, 3), + sliding_window_size=4, + ), + 2, + "eagle", + ), + # Above-window verify exercises the `min(seq_lens, window)` + # clipping in the verify-path replay metadata builder. + ( + DenseAttentionCase( + name="runner_cuda_graph_eagle_verify_swa_above_window", + backend="triton", + forward_mode=ForwardMode.TARGET_VERIFY, + num_heads=4, + num_kv_heads=4, + page_size=16, + prefix_lens=(6, 8), + extend_lens=(3, 3), + sliding_window_size=4, + ), + 1, + "eagle", + ), + ( + DenseAttentionCase( + name="runner_cuda_graph_frozen_kv_mtp_verify_swa_chain", + backend="triton", + forward_mode=ForwardMode.TARGET_VERIFY, + num_heads=4, + num_kv_heads=4, + page_size=16, + prefix_lens=(3, 5), + extend_lens=(3, 3), + sliding_window_size=4, + ), + 1, + "frozen_kv_mtp", + ), + ( + DenseAttentionCase( + name="runner_cuda_graph_dflash_verify_swa_chain", + backend="triton", + forward_mode=ForwardMode.TARGET_VERIFY, + num_heads=4, + num_kv_heads=4, + page_size=16, + prefix_lens=(3, 5), + extend_lens=(3, 3), + sliding_window_size=4, + ), + 1, + "dflash", + ), + ( + DenseAttentionCase( + name="runner_cuda_graph_ngram_verify_swa_chain", + backend="triton", + forward_mode=ForwardMode.TARGET_VERIFY, + num_heads=4, + num_kv_heads=4, + page_size=16, + prefix_lens=(3, 5), + extend_lens=(3, 3), + sliding_window_size=4, + ), + 1, + "ngram", + ), + ) + + def test_projected_swa_attention_cases(self): + for case in self.CASES: + with self.subTest(case=case.name, backend=case.backend): + run_dense_attention_case(self, case) + + # Layout-robustness. See dense/test_triton.py for full rationale. + # The default `shuffled_pages` layout is already exercised by + # test_projected_swa_attention_cases; this method opts into the + # more aggressive interleaved_pages + non_monotonic_extend on a + # representative SWA extend + decode case. + LAYOUT_ROBUSTNESS_CASES = ( + DenseAttentionCase( + name="layout_swa_extend_within_window", + backend="triton", + forward_mode=ForwardMode.EXTEND, + num_heads=8, + num_kv_heads=4, + page_size=16, + prefix_lens=(8, 16), + extend_lens=(8, 16), + sliding_window_size=12, + ), + DenseAttentionCase( + name="layout_swa_decode_page_boundary", + backend="triton", + forward_mode=ForwardMode.DECODE, + num_heads=8, + num_kv_heads=4, + page_size=16, + prefix_lens=(15, 16, 17), + sliding_window_size=12, + ), + ) + + def test_layout_robustness_cases(self): + for case in self.LAYOUT_ROBUSTNESS_CASES: + for layout in ("interleaved_pages", "non_monotonic_extend"): + if layout == "non_monotonic_extend" and case.forward_mode.is_decode(): + continue + with self.subTest(case=case.name, layout=layout): + run_dense_attention_case(self, case, loc_layout=layout) + + def test_runner_mode_cuda_graph_decode_cases(self): + for case in self.CUDA_GRAPH_CASES: + with self.subTest(case=case.name, backend=case.backend): + run_dense_cuda_graph_decode_case(self, case) + + @unittest.skipIf( + is_hip(), + "split-op extend runner exercises the piecewise-CUDA-graph path " + "(TcPiecewiseForwardContext.num_tokens), which is not wired on ROCm.", + ) + def test_runner_mode_split_op_extend_cases(self): + for case, static_num_tokens in self.SPLIT_OP_CASES: + for breakable in (False, True): + runner = "bcg" if breakable else "pcg" + with self.subTest( + case=case.name, + backend=case.backend, + runner=runner, + ): + run_dense_split_op_extend_case( + self, + case, + breakable=breakable, + static_num_tokens=static_num_tokens, + ) + + def test_runner_mode_spec_verify_cases(self): + for case, topk, spec_kind in self.SPEC_VERIFY_CASES: + with self.subTest( + case=case.name, + backend=case.backend, + topk=topk, + spec_kind=spec_kind, + ): + run_dense_spec_verify_case(self, case, topk=topk, spec_kind=spec_kind) + + def test_runner_mode_spec_verify_cuda_graph_cases(self): + for case, topk, spec_kind in self.SPEC_VERIFY_CUDA_GRAPH_CASES: + with self.subTest( + case=case.name, + backend=case.backend, + topk=topk, + spec_kind=spec_kind, + ): + run_dense_spec_verify_cuda_graph_case( + self, + case, + topk=topk, + spec_kind=spec_kind, + ) + + +if __name__ == "__main__": + unittest.main() diff --git a/asian_ai/performance/SGLang/test/registered/backends/test_deepseek_r1_fp8_trtllm_backend.py b/asian_ai/performance/SGLang/test/registered/backends/test_deepseek_r1_fp8_trtllm_backend.py new file mode 100644 index 0000000000000000000000000000000000000000..4f7c07463a5ecfb735116f59f2cf987a23eee905 --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/backends/test_deepseek_r1_fp8_trtllm_backend.py @@ -0,0 +1,90 @@ +import unittest +from types import SimpleNamespace + +from sglang.srt.utils import kill_process_tree +from sglang.test.ci.ci_register import register_cuda_ci +from sglang.test.run_eval import run_eval +from sglang.test.test_utils import ( + DEFAULT_URL_FOR_TEST, + CustomTestCase, + popen_launch_server, + try_cached_model, +) + +register_cuda_ci(est_time=3600, suite="nightly-8-gpu-b200", nightly=True) + +FULL_DEEPSEEK_V3_MODEL_PATH = "deepseek-ai/DeepSeek-V3-0324" +SERVER_LAUNCH_TIMEOUT = 1000 + + +class TestDeepseekR1Fp8Flashinfer(CustomTestCase): + @classmethod + def setUpClass(cls): + cls.model = try_cached_model(FULL_DEEPSEEK_V3_MODEL_PATH) + cls.base_url = DEFAULT_URL_FOR_TEST + other_args = [ + "--trust-remote-code", + "--disable-radix-cache", + "--max-running-requests", + "512", + "--chunked-prefill-size", + "8192", + "--mem-fraction-static", + "0.9", + "--cuda-graph-max-bs-decode", + "128", + "--max-prefill-tokens", + "8192", + "--kv-cache-dtype", + "fp8_e4m3", + "--quantization", + "fp8", + "--tensor-parallel-size", + "8", + "--data-parallel-size", + "1", + "--expert-parallel-size", + "1", + "--scheduler-recv-interval", + "10", + "--stream-interval", + "10", + "--attention-backend", + "trtllm_mla", + "--fp8-gemm-backend", + "flashinfer_trtllm", + "--moe-runner-backend", + "flashinfer_trtllm", + "--enable-symm-mem", + "--model-loader-extra-config", + '{"enable_multithread_load": true,"num_threads": 64}', + ] + cls.process = popen_launch_server( + cls.model, + cls.base_url, + timeout=SERVER_LAUNCH_TIMEOUT, + other_args=other_args, + ) + + @classmethod + def tearDownClass(cls): + kill_process_tree(cls.process.pid) + + def test_gsm8k(self): + args = SimpleNamespace( + base_url=self.base_url, + model=self.model, + eval_name="gsm8k", + api="completion", + max_tokens=512, + num_examples=512, + num_threads=512, + ) + metrics = run_eval(args) + print(f"Eval accuracy of GSM8K: {metrics=}") + + self.assertGreater(metrics["score"], 0.92) + + +if __name__ == "__main__": + unittest.main() diff --git a/asian_ai/performance/SGLang/test/registered/backends/test_deepseek_v3_fp4_cutedsl_moe.py b/asian_ai/performance/SGLang/test/registered/backends/test_deepseek_v3_fp4_cutedsl_moe.py new file mode 100644 index 0000000000000000000000000000000000000000..13ce462cdefbc7d77adbd46c8e36b5cd63cd48e0 --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/backends/test_deepseek_v3_fp4_cutedsl_moe.py @@ -0,0 +1,149 @@ +"""Backend tests for CuteDSL MoE (FusedMoE + moe_runner, moe_a2a=none). + +Exercises the CuteDSL moe_runner path with ModelOpt FP4 by launching a +server with --moe-runner-backend flashinfer_cutedsl. + +Two configurations are tested: + - EP=1, TP=4: each GPU holds all experts with TP-sharded intermediate dim + - EP=4, TP=4: each GPU holds 1/4 of experts at full intermediate width, + partial results combined via all-reduce (no A2A dispatch) + +Requires 4 GPUs. Run from repo root with: + python -m pytest test/registered/backends/test_deepseek_v3_fp4_cutedsl_moe.py -v -s +Or via the nightly suite: + python test/run_suite.py --hw cuda --suite nightly-4-gpu-b200 --nightly +""" + +import unittest +from types import SimpleNamespace + +from sglang.srt.utils import kill_process_tree +from sglang.test.ci.ci_register import register_cuda_ci +from sglang.test.few_shot_gsm8k import run_eval as run_eval_few_shot_gsm8k +from sglang.test.test_utils import ( + DEFAULT_URL_FOR_TEST, + CustomTestCase, + is_in_ci, + popen_launch_server, + write_github_step_summary, +) + +register_cuda_ci(est_time=900, suite="nightly-4-gpu-b200", nightly=True) + +FULL_DEEPSEEK_V3_FP4_MODEL_PATH = "nvidia/DeepSeek-V3-0324-FP4" +SERVER_LAUNCH_TIMEOUT = 1000 +GSM8K_ACCURACY_THRESHOLD = 0.935 + + +class TestDeepseekV3FP4CuteDSLMoE(CustomTestCase): + """CuteDSL standard moe_runner path: flashinfer_cutedsl + modelopt_fp4, EP=1.""" + + @classmethod + def setUpClass(cls): + cls.model = FULL_DEEPSEEK_V3_FP4_MODEL_PATH + cls.base_url = DEFAULT_URL_FOR_TEST + other_args = [ + "--tp", + "4", + "--ep", + "1", + "--mem-fraction-static", + "0.75", + "--attention-backend", + "trtllm_mla", + "--moe-runner-backend", + "flashinfer_cutedsl", + "--quantization", + "modelopt_fp4", + "--model-loader-extra-config", + '{"enable_multithread_load": true}', + ] + cls.process = popen_launch_server( + cls.model, + cls.base_url, + timeout=SERVER_LAUNCH_TIMEOUT, + other_args=other_args, + ) + + @classmethod + def tearDownClass(cls): + kill_process_tree(cls.process.pid) + + def test_a_gsm8k( + self, + ): # Append an "a" to make this test run first (alphabetically) to warm up the server + args = SimpleNamespace( + num_shots=8, + data_path=None, + num_questions=1319, + parallel=1319, + max_new_tokens=512, + host="http://127.0.0.1", + port=int(self.base_url.split(":")[-1]), + ) + metrics = run_eval_few_shot_gsm8k(args) + if is_in_ci(): + write_github_step_summary( + f"### test_gsm8k (deepseek-v3-fp4-cutedsl-moe)\n" + f'{metrics["accuracy"]=:.3f}\n' + ) + self.assertGreater(metrics["accuracy"], GSM8K_ACCURACY_THRESHOLD) + + +class TestDeepseekV3FP4CuteDSLMoEEP4(CustomTestCase): + """CuteDSL standard moe_runner path: flashinfer_cutedsl + modelopt_fp4, EP=TP=4.""" + + @classmethod + def setUpClass(cls): + cls.model = FULL_DEEPSEEK_V3_FP4_MODEL_PATH + cls.base_url = DEFAULT_URL_FOR_TEST + other_args = [ + "--tp", + "4", + "--ep", + "4", + "--mem-fraction-static", + "0.75", + "--attention-backend", + "trtllm_mla", + "--moe-runner-backend", + "flashinfer_cutedsl", + "--moe-a2a-backend", + "none", + "--quantization", + "modelopt_fp4", + "--model-loader-extra-config", + '{"enable_multithread_load": true}', + ] + cls.process = popen_launch_server( + cls.model, + cls.base_url, + timeout=SERVER_LAUNCH_TIMEOUT, + other_args=other_args, + ) + + @classmethod + def tearDownClass(cls): + kill_process_tree(cls.process.pid) + + def test_a_gsm8k(self): + args = SimpleNamespace( + num_shots=8, + data_path=None, + num_questions=1319, + parallel=1319, + max_new_tokens=512, + host="http://127.0.0.1", + port=int(self.base_url.split(":")[-1]), + ) + metrics = run_eval_few_shot_gsm8k(args) + if is_in_ci(): + write_github_step_summary( + f"### test_gsm8k (deepseek-v3-fp4-cutedsl-moe-ep4)\n" + f'{metrics["accuracy"]=:.3f}\n' + ) + self.assertGreater(metrics["accuracy"], GSM8K_ACCURACY_THRESHOLD) + + +if __name__ == "__main__": + unittest.main() diff --git a/asian_ai/performance/SGLang/test/registered/backends/test_deepseek_v3_fp4_cutlass_moe.py b/asian_ai/performance/SGLang/test/registered/backends/test_deepseek_v3_fp4_cutlass_moe.py new file mode 100644 index 0000000000000000000000000000000000000000..22c8f4bd0beb915e6a118c4b5bc8fe53bb450999 --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/backends/test_deepseek_v3_fp4_cutlass_moe.py @@ -0,0 +1,76 @@ +import unittest +from types import SimpleNamespace + +from sglang.srt.utils import kill_process_tree +from sglang.test.ci.ci_register import register_cuda_ci +from sglang.test.run_eval import run_eval +from sglang.test.test_utils import ( + DEFAULT_URL_FOR_TEST, + CustomTestCase, + is_in_ci, + popen_launch_server, + write_github_step_summary, +) + +register_cuda_ci(est_time=900, suite="nightly-4-gpu-b200", nightly=True) + +FULL_DEEPSEEK_V3_FP4_MODEL_PATH = "nvidia/DeepSeek-V3-0324-FP4" +SERVER_LAUNCH_TIMEOUT = 1000 + + +class TestDeepseekV3FP4CutlassMoE(CustomTestCase): + @classmethod + def setUpClass(cls): + cls.model = FULL_DEEPSEEK_V3_FP4_MODEL_PATH + cls.base_url = DEFAULT_URL_FOR_TEST + other_args = [ + "--tp", + "4", + "--ep", + "4", + "--attention-backend", + "trtllm_mla", + "--moe-runner-backend", + "flashinfer_cutlass", + "--quantization", + "modelopt_fp4", + "--model-loader-extra-config", + '{"enable_multithread_load": true}', + ] + cls.process = popen_launch_server( + cls.model, + cls.base_url, + timeout=SERVER_LAUNCH_TIMEOUT, + other_args=other_args, + ) + + @classmethod + def tearDownClass(cls): + kill_process_tree(cls.process.pid) + + def test_a_gsm8k( + self, + ): # Append an "a" to make this test run first (alphabetically) to warm up the server + args = SimpleNamespace( + base_url=self.base_url, + model=self.model, + eval_name="gsm8k", + api="completion", + max_tokens=512, + num_examples=1319, + num_threads=1319, + num_shots=8, + ) + metrics = run_eval(args) + print(f"{metrics=}") + + if is_in_ci(): + write_github_step_summary( + f"### test_gsm8k (deepseek-v3-fp4-cutlass-moe)\n" + f'{metrics["score"]=:.3f}\n' + ) + self.assertGreater(metrics["score"], 0.935) + + +if __name__ == "__main__": + unittest.main() diff --git a/asian_ai/performance/SGLang/test/registered/backends/test_flashinfer_fusion_preflight.py b/asian_ai/performance/SGLang/test/registered/backends/test_flashinfer_fusion_preflight.py new file mode 100644 index 0000000000000000000000000000000000000000..717ecca0d7167d9b60cf5fe692e847d5d1fcf55a --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/backends/test_flashinfer_fusion_preflight.py @@ -0,0 +1,163 @@ +"""Distributed tests for FlashInfer allreduce-fusion workspace preflight.""" + +import multiprocessing as mp +import os +import socket +import unittest + +import torch + +from sglang.srt.utils import get_cuda_driver_bindings, is_flashinfer_available +from sglang.test.ci.ci_register import register_cuda_ci +from sglang.test.test_utils import CustomTestCase + +register_cuda_ci(est_time=30, stage="base-b", runner_config="2-gpu-large") + +WORLD_SIZE = 2 + + +def _get_free_port(): + with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock: + sock.bind(("127.0.0.1", 0)) + return sock.getsockname()[1] + + +def _run_rank(rank, world_size, port, scenario, result_q): + held = None + cuda_driver = None + try: + os.environ["MASTER_ADDR"] = "127.0.0.1" + os.environ["MASTER_PORT"] = str(port) + os.environ["RANK"] = str(rank) + os.environ["WORLD_SIZE"] = str(world_size) + os.environ["LOCAL_RANK"] = str(rank) + + torch.cuda.set_device(rank) + + import torch.distributed as dist + + dist.init_process_group( + backend="gloo", + rank=rank, + world_size=world_size, + ) + cpu_group = dist.group.WORLD + + from sglang.srt.layers.flashinfer_comm_fusion import ( + _make_flashinfer_workspace_allocation_prop, + _preflight_check_workspace_memory, + ) + + probe_kwargs = dict( + world_size=8, + max_token_num=2048, + hidden_dim=12288, + dtype=torch.bfloat16, + cpu_group=cpu_group, + ) + + if scenario == "rank0_starved" and rank == 0: + cuda_driver = get_cuda_driver_bindings() + prop = _make_flashinfer_workspace_allocation_prop(cuda_driver) + + free, _total = torch.cuda.mem_get_info(rank) + target = max(free - (1 << 30), 0) + granularity_flag = ( + cuda_driver.CUmemAllocationGranularity_flags.CU_MEM_ALLOC_GRANULARITY_RECOMMENDED + ) + err, gran = cuda_driver.cuMemGetAllocationGranularity( + prop, + granularity_flag, + ) + assert err == cuda_driver.CUresult.CUDA_SUCCESS, err + aligned = (target // gran) * gran + assert aligned > 0, "not enough free memory to starve the preflight" + err, held = cuda_driver.cuMemCreate(aligned, prop, 0) + assert err == cuda_driver.CUresult.CUDA_SUCCESS, (err, aligned) + + decision = _preflight_check_workspace_memory(**probe_kwargs) + result_q.put((rank, "ok", bool(decision))) + except Exception as e: # pragma: no cover - debug path + result_q.put((rank, "err", repr(e))) + finally: + if held is not None: + cuda_driver.cuMemRelease(held) + try: + import torch.distributed as dist + + if dist.is_initialized(): + dist.destroy_process_group() + except Exception: + pass + + +def _spawn_and_collect(scenario, world_size=WORLD_SIZE): + ctx = mp.get_context("spawn") + q = ctx.Queue() + port = _get_free_port() + procs = [] + for rank in range(world_size): + proc = ctx.Process( + target=_run_rank, + args=(rank, world_size, port, scenario, q), + ) + proc.start() + procs.append(proc) + + try: + results = {} + for _ in range(world_size): + rank, status, payload = q.get(timeout=300) + results[rank] = (status, payload) + + for proc in procs: + proc.join(timeout=60) + assert proc.exitcode == 0, f"rank exited with {proc.exitcode}" + finally: + for proc in procs: + if proc.is_alive(): + proc.terminate() + proc.join(timeout=10) + + return results + + +class TestFlashInferPreflightDistributed(CustomTestCase): + @classmethod + def setUpClass(cls): + if not torch.cuda.is_available() or torch.cuda.device_count() < WORLD_SIZE: + raise unittest.SkipTest( + f"Need {WORLD_SIZE} CUDA devices, got {torch.cuda.device_count()}" + ) + if not is_flashinfer_available(): + raise unittest.SkipTest("FlashInfer is not available") + try: + from sglang.srt.layers.flashinfer_comm_fusion import ( + _make_flashinfer_workspace_allocation_prop, + ) + + cuda_driver = get_cuda_driver_bindings() + _make_flashinfer_workspace_allocation_prop(cuda_driver) + except Exception as e: + raise unittest.SkipTest( + f"FlashInfer preflight dependencies unavailable: {e}" + ) + + def test_happy_path_votes_proceed(self): + results = _spawn_and_collect("normal") + for rank, (status, payload) in results.items(): + self.assertEqual(status, "ok", f"rank {rank}: {payload}") + self.assertTrue(payload, f"rank {rank} voted SKIP unexpectedly") + + def test_starved_rank_broadcasts_skip(self): + results = _spawn_and_collect("rank0_starved") + for rank, (status, payload) in results.items(): + self.assertEqual(status, "ok", f"rank {rank}: {payload}") + self.assertFalse( + payload, + f"rank {rank} voted PROCEED but rank 0 was starved", + ) + + +if __name__ == "__main__": + unittest.main(verbosity=2) diff --git a/asian_ai/performance/SGLang/test/registered/backends/test_flashinfer_trtllm_gen_attn_backend.py b/asian_ai/performance/SGLang/test/registered/backends/test_flashinfer_trtllm_gen_attn_backend.py new file mode 100644 index 0000000000000000000000000000000000000000..3cfb428584f16b4063ee625eb7e954bf75405a9a --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/backends/test_flashinfer_trtllm_gen_attn_backend.py @@ -0,0 +1,65 @@ +import os +import unittest +from types import SimpleNamespace + +from sglang.srt.utils import kill_process_tree +from sglang.test.ci.ci_register import register_cuda_ci +from sglang.test.run_eval import run_eval +from sglang.test.test_utils import ( + DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH, + DEFAULT_URL_FOR_TEST, + CustomTestCase, + popen_launch_server, +) + +register_cuda_ci(est_time=300, suite="nightly-4-gpu-b200", nightly=True) + + +class TestFlashinferTrtllmGenAttnBackend(CustomTestCase): + @classmethod + def setUpClass(cls): + cls.model = "Qwen/Qwen3-Next-80B-A3B-Instruct" + cls.base_url = DEFAULT_URL_FOR_TEST + cls.process = popen_launch_server( + cls.model, + cls.base_url, + timeout=DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH, + env={**os.environ, "SGLANG_ENABLE_JIT_DEEPGEMM": "False"}, + other_args=[ + "--attention-backend", + "trtllm_mha", + "--cuda-graph-max-bs-decode", + "512", + "--tp-size", + "4", + "--ep-size", + "4", + "--mem-fraction-static", + "0.7", + "--mamba-ssm-dtype", + "bfloat16", + "--disable-radix-cache", + ], + ) + + @classmethod + def tearDownClass(cls): + kill_process_tree(cls.process.pid) + + def test_gsm8k(self): + args = SimpleNamespace( + base_url=self.base_url, + model=self.model, + eval_name="gsm8k", + api="completion", + max_tokens=512, + num_examples=200, + num_threads=128, + ) + metrics = run_eval(args) + print(f"{metrics=}") + self.assertGreater(metrics["score"], 0.93) + + +if __name__ == "__main__": + unittest.main() diff --git a/asian_ai/performance/SGLang/test/registered/backends/test_flashinfer_trtllm_gen_moe_backend.py b/asian_ai/performance/SGLang/test/registered/backends/test_flashinfer_trtllm_gen_moe_backend.py new file mode 100644 index 0000000000000000000000000000000000000000..6faa322b0b50b2f656152de3531cd716aa61d79b --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/backends/test_flashinfer_trtllm_gen_moe_backend.py @@ -0,0 +1,352 @@ +import os +import unittest +from types import SimpleNamespace + +from sglang.srt.utils import kill_process_tree +from sglang.test.ci.ci_register import register_cuda_ci +from sglang.test.run_eval import run_eval +from sglang.test.test_utils import ( + DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH, + DEFAULT_URL_FOR_TEST, + CustomTestCase, + popen_launch_server, +) + +register_cuda_ci(est_time=800, suite="nightly-4-gpu-b200", nightly=True) + + +class FlashinferTrtllmGenMoeBackendFP8Base: + backend = None + + @classmethod + def setUpClass(cls): + cls.model = "Qwen/Qwen3-Next-80B-A3B-Instruct-FP8" + cls.base_url = DEFAULT_URL_FOR_TEST + cls.process = popen_launch_server( + cls.model, + cls.base_url, + timeout=DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH, + env={**os.environ, "SGLANG_ENABLE_JIT_DEEPGEMM": "False"}, + other_args=[ + "--attention-backend", + "triton", + "--moe-runner-backend", + cls.backend, + "--tp-size", + "4", + "--ep-size", + "4", + "--mem-fraction-static", + "0.7", + "--mamba-ssm-dtype", + "bfloat16", + ], + ) + + @classmethod + def tearDownClass(cls): + kill_process_tree(cls.process.pid) + + def test_gsm8k(self): + args = SimpleNamespace( + base_url=self.base_url, + model=self.model, + eval_name="gsm8k", + api="completion", + max_tokens=512, + num_examples=200, + num_threads=128, + ) + metrics = run_eval(args) + print(f"{metrics=}") + self.assertGreater(metrics["score"], 0.89) + + +class FlashinferTrtllmGenMoeBackendBF16Base: + backend = None + + @classmethod + def setUpClass(cls): + cls.model = "Qwen/Qwen3-Next-80B-A3B-Instruct" + cls.base_url = DEFAULT_URL_FOR_TEST + cls.process = popen_launch_server( + cls.model, + cls.base_url, + timeout=DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH, + other_args=[ + "--attention-backend", + "triton", + "--moe-runner-backend", + cls.backend, + "--cuda-graph-max-bs-decode", + "512", + "--tp-size", + "4", + "--ep-size", + "4", + "--mem-fraction-static", + "0.7", + "--mamba-ssm-dtype", + "bfloat16", + ], + ) + + @classmethod + def tearDownClass(cls): + kill_process_tree(cls.process.pid) + + def test_gsm8k(self): + args = SimpleNamespace( + base_url=self.base_url, + model=self.model, + eval_name="gsm8k", + api="completion", + max_tokens=512, + num_examples=200, + num_threads=128, + ) + metrics = run_eval(args) + print(f"{metrics=}") + self.assertGreater(metrics["score"], 0.93) + + +class FlashinferTrtllmGenMoeBackendMXFP8Base: + backend = None + + @classmethod + def setUpClass(cls): + cls.model = "zianglih/Qwen3-30B-A3B-Instruct-2507-MXFP8" + cls.base_url = DEFAULT_URL_FOR_TEST + cls.process = popen_launch_server( + cls.model, + cls.base_url, + timeout=DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH, + env={**os.environ, "SGLANG_ENABLE_JIT_DEEPGEMM": "False"}, + other_args=[ + "--fp8-gemm-backend", + "flashinfer_cutlass", + "--moe-runner-backend", + cls.backend, + "--tp-size", + "4", + "--ep-size", + "4", + "--mem-fraction-static", + "0.7", + ], + ) + + @classmethod + def tearDownClass(cls): + kill_process_tree(cls.process.pid) + + def test_gsm8k(self): + args = SimpleNamespace( + base_url=self.base_url, + model=self.model, + eval_name="gsm8k", + api="completion", + max_tokens=512, + num_examples=200, + num_threads=128, + ) + metrics = run_eval(args) + print(f"{metrics=}") + self.assertGreater(metrics["score"], 0.93) + + +class FlashinferTrtllmGenMoeBackendMXFP8MixedBF16Base: + backend = None + + @classmethod + def setUpClass(cls): + cls.model = "zianglih/JoyAI-LLM-Flash-MXFP8-last-6-BF16" + cls.base_url = DEFAULT_URL_FOR_TEST + cls.process = popen_launch_server( + cls.model, + cls.base_url, + timeout=DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH, + env={**os.environ, "SGLANG_ENABLE_JIT_DEEPGEMM": "False"}, + other_args=[ + "--kv-cache-dtype", + "bf16", + "--fp8-gemm-backend", + "flashinfer_trtllm", + "--moe-runner-backend", + cls.backend, + "--tp-size", + "4", + "--trust-remote-code", + ], + ) + + @classmethod + def tearDownClass(cls): + kill_process_tree(cls.process.pid) + + def test_gsm8k(self): + args = SimpleNamespace( + base_url=self.base_url, + model=self.model, + eval_name="gsm8k", + api="completion", + max_tokens=512, + num_examples=200, + num_threads=128, + ) + metrics = run_eval(args) + print(f"{metrics=}") + self.assertGreater(metrics["score"], 0.92) + + +class FlashinferTrtllmGenMoeBackendNVFP4Base: + backend = None + extra_env = {} + + @classmethod + def setUpClass(cls): + cls.model = "nvidia/Qwen3-30B-A3B-NVFP4" + cls.base_url = DEFAULT_URL_FOR_TEST + cls.process = popen_launch_server( + cls.model, + cls.base_url, + timeout=DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH, + env={**os.environ, **cls.extra_env, "SGLANG_ENABLE_JIT_DEEPGEMM": "False"}, + other_args=[ + "--moe-runner-backend", + cls.backend, + "--tp-size", + "4", + "--ep-size", + "4", + "--mem-fraction-static", + "0.7", + ], + ) + + @classmethod + def tearDownClass(cls): + kill_process_tree(cls.process.pid) + + def test_gsm8k(self): + args = SimpleNamespace( + base_url=self.base_url, + model=self.model, + eval_name="gsm8k", + api="completion", + max_tokens=512, + num_examples=200, + num_threads=128, + ) + metrics = run_eval(args) + print(f"{metrics=}") + self.assertGreater(metrics["score"], 0.89) + + +class FlashinferTrtllmGenMoeBackendNvFp4OnlineBase: + backend = None + extra_env = {} + + @classmethod + def setUpClass(cls): + cls.model = "Qwen/Qwen3-Next-80B-A3B-Instruct-FP8" + cls.base_url = DEFAULT_URL_FOR_TEST + cls.process = popen_launch_server( + cls.model, + cls.base_url, + timeout=DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH, + env={**os.environ, **cls.extra_env, "SGLANG_ENABLE_JIT_DEEPGEMM": "False"}, + other_args=[ + "--attention-backend", + "triton", + "--moe-runner-backend", + cls.backend, + "--cuda-graph-max-bs-decode", + "128", + "--tp-size", + "4", + "--ep-size", + "2", + "--quantization", + "nvfp4_online", + "--mem-fraction-static", + "0.7", + "--mamba-ssm-dtype", + "bfloat16", + ], + ) + + @classmethod + def tearDownClass(cls): + kill_process_tree(cls.process.pid) + + def test_gsm8k(self): + args = SimpleNamespace( + base_url=self.base_url, + model=self.model, + eval_name="gsm8k", + api="completion", + max_tokens=512, + num_examples=200, + num_threads=128, + ) + metrics = run_eval(args) + print(f"{metrics=}") + self.assertGreater(metrics["score"], 0.90) + + +class TestFlashinferTrtllmGenMoeBackendFP8( + FlashinferTrtllmGenMoeBackendFP8Base, CustomTestCase +): + backend = "flashinfer_trtllm" + + +class TestFlashinferTrtllmGenMoeBackendNVFP4( + FlashinferTrtllmGenMoeBackendNVFP4Base, CustomTestCase +): + backend = "flashinfer_trtllm" + + +class TestFlashinferTrtllmGenMoeBackendMXFP8Routed( + FlashinferTrtllmGenMoeBackendMXFP8Base, CustomTestCase +): + backend = "flashinfer_trtllm_routed" + + +class TestFlashinferTrtllmRoutedMxfp8MixedBF16( + FlashinferTrtllmGenMoeBackendMXFP8MixedBF16Base, CustomTestCase +): + backend = "flashinfer_trtllm_routed" + + +class TestFlashinferTrtllmGenMoeBackendBF16Routed( + FlashinferTrtllmGenMoeBackendBF16Base, CustomTestCase +): + backend = "flashinfer_trtllm_routed" + + +class TestFlashinferTrtllmGenMoeBackendNvFp4PerTokenActivationRouted( + FlashinferTrtllmGenMoeBackendNVFP4Base, CustomTestCase +): + extra_env = {"SGLANG_FLASHINFER_NVFP4_PER_TOKEN_ACTIVATION": "1"} + backend = "flashinfer_trtllm_routed" + + +class TestFlashinferTrtllmGenMoeBackendNvFp4Online( + FlashinferTrtllmGenMoeBackendNvFp4OnlineBase, CustomTestCase +): + extra_env = { + "FLASHINFER_NVFP4_4OVER6": "1", + "FLASHINFER_NVFP4_4OVER6_ERR_MODE": "MSE", + "FLASHINFER_NVFP4_4OVER6_ERR_USE_FAST_MATH": "1", + "FLASHINFER_NVFP4_4OVER6_E4M3_USE_256": "1", + "SGLANG_FP4_IGNORED_LAYERS": ",".join( + ["shared_expert"] + + [f"model.layers.{layer_id}" for layer_id in range(40, 48)] + ), + } + backend = "flashinfer_trtllm" + + +if __name__ == "__main__": + unittest.main() diff --git a/asian_ai/performance/SGLang/test/registered/backends/test_qwen3_fp4_trtllm_gen_moe.py b/asian_ai/performance/SGLang/test/registered/backends/test_qwen3_fp4_trtllm_gen_moe.py new file mode 100644 index 0000000000000000000000000000000000000000..ae672037c8bd80e0c74c4aa4ac2c5578cff6b9dd --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/backends/test_qwen3_fp4_trtllm_gen_moe.py @@ -0,0 +1,69 @@ +import unittest +from types import SimpleNamespace + +from sglang.srt.utils import get_device_sm, kill_process_tree +from sglang.test.ci.ci_register import register_cuda_ci +from sglang.test.run_eval import run_eval +from sglang.test.test_utils import ( + DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH, + DEFAULT_URL_FOR_TEST, + CustomTestCase, + popen_launch_server, +) + +# modelopt_fp4 requires SM 100+ (Blackwell) +register_cuda_ci(est_time=300, suite="nightly-1-gpu", nightly=True) + + +@unittest.skipIf( + get_device_sm() < 100, "Test requires CUDA SM 100 or higher (Blackwell)" +) +class TestFlashinferTrtllmGenMoeBackend(CustomTestCase): + @classmethod + def setUpClass(cls): + cls.model = "nvidia/Qwen3-30B-A3B-NVFP4" + cls.base_url = DEFAULT_URL_FOR_TEST + cls.process = popen_launch_server( + cls.model, + cls.base_url, + timeout=DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH, + other_args=[ + "--moe-runner-backend", + "flashinfer_trtllm", + "--quantization", + "modelopt_fp4", + "--trust-remote-code", + "--disable-radix-cache", + "--max-running-requests", + "1024", + "--chunked-prefill-size", + "16384", + "--mem-fraction-static", + "0.89", + "--max-prefill-tokens", + "16384", + ], + ) + + @classmethod + def tearDownClass(cls): + kill_process_tree(cls.process.pid) + + def test_gsm8k(self): + args = SimpleNamespace( + base_url=self.base_url, + model=self.model, + eval_name="gsm8k", + api="completion", + max_tokens=512, + num_examples=1319, + num_threads=1319, + num_shots=8, + ) + metrics = run_eval(args) + print(f"{metrics=}") + self.assertGreater(metrics["score"], 0.88) + + +if __name__ == "__main__": + unittest.main() diff --git a/asian_ai/performance/SGLang/test/registered/backends/test_torch_compile.py b/asian_ai/performance/SGLang/test/registered/backends/test_torch_compile.py new file mode 100644 index 0000000000000000000000000000000000000000..2fca02cd9004afd913caa7e4945a669043093cda --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/backends/test_torch_compile.py @@ -0,0 +1,75 @@ +import time +import unittest + +import requests + +from sglang.srt.utils import kill_process_tree +from sglang.test.ci.ci_register import register_amd_ci, register_cuda_ci +from sglang.test.kits.eval_accuracy_kit import MMLUMixin +from sglang.test.test_utils import ( + DEFAULT_MODEL_NAME_FOR_TEST, + DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH, + DEFAULT_URL_FOR_TEST, + CustomTestCase, + is_in_amd_ci, + popen_launch_server, +) + +register_cuda_ci(est_time=126, stage="extra-a", runner_config="1-gpu-large") +register_amd_ci(est_time=1100, suite="stage-b-test-1-gpu-small-amd") + + +class TestTorchCompile(CustomTestCase, MMLUMixin): + mmlu_score_threshold = 0.65 + mmlu_num_examples = 64 + mmlu_num_threads = 32 + + @classmethod + def setUpClass(cls): + cls.model = DEFAULT_MODEL_NAME_FOR_TEST + cls.base_url = DEFAULT_URL_FOR_TEST + cls.process = popen_launch_server( + cls.model, + cls.base_url, + timeout=DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH, + other_args=["--enable-torch-compile", "--cuda-graph-max-bs-decode", "4"], + ) + + @classmethod + def tearDownClass(cls): + kill_process_tree(cls.process.pid) + + def run_decode(self, max_new_tokens): + response = requests.post( + self.base_url + "/generate", + json={ + "text": "The capital of France is", + "sampling_params": { + "temperature": 0, + "max_new_tokens": max_new_tokens, + "ignore_eos": True, + }, + }, + ) + return response.json() + + def test_throughput(self): + # Warmup + res = self.run_decode(16) + + max_tokens = 256 + tic = time.perf_counter() + res = self.run_decode(max_tokens) + tok = time.perf_counter() + print(f"{res=}") + throughput = max_tokens / (tok - tic) + print(f"Throughput: {throughput} tokens/s") + + if is_in_amd_ci(): + self.assertGreaterEqual(throughput, 145) + else: + self.assertGreaterEqual(throughput, 152) + + +if __name__ == "__main__": + unittest.main() diff --git a/asian_ai/performance/SGLang/test/registered/bench_fn/test_bench_serving_functionality.py b/asian_ai/performance/SGLang/test/registered/bench_fn/test_bench_serving_functionality.py new file mode 100644 index 0000000000000000000000000000000000000000..05ae968bc3234214ef996652c0d0c80b82b82ae4 --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/bench_fn/test_bench_serving_functionality.py @@ -0,0 +1,191 @@ +import json +import tempfile +import threading +import time +import unittest +from http.server import BaseHTTPRequestHandler, HTTPServer +from pathlib import Path + +from sglang.benchmark.serving import run_benchmark +from sglang.benchmark.utils import parse_custom_headers +from sglang.srt.constants import HEALTH_CHECK_RID_PREFIX +from sglang.srt.utils import kill_process_tree +from sglang.test.ci.ci_register import register_amd_ci, register_cuda_ci +from sglang.test.test_utils import ( + DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH, + DEFAULT_URL_FOR_TEST, + CustomTestCase, + get_benchmark_args, + popen_launch_server, +) + +register_cuda_ci(est_time=300, suite="nightly-1-gpu", nightly=True) +register_amd_ci(est_time=300, suite="nightly-amd-1-gpu", nightly=True) + +MODEL = "Qwen/Qwen3-0.6B" +NUM_CONVERSATIONS, NUM_TURNS = 4, 3 + + +class TestBenchServingFunctionality(CustomTestCase): + def test_gsp_multi_turn(self): + with tempfile.TemporaryDirectory() as temp_dir: + process = popen_launch_server( + MODEL, + DEFAULT_URL_FOR_TEST, + timeout=DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH, + other_args=[ + "--mem-fraction-static", + "0.7", + "--log-requests", + "--log-requests-level", + "3", + "--log-requests-format", + "json", + "--log-requests-target", + "stdout", + temp_dir, + ], + ) + try: + args = get_benchmark_args( + base_url=DEFAULT_URL_FOR_TEST, + backend="sglang-oai-chat", + tokenizer=MODEL, + dataset_name="generated-shared-prefix", + num_prompts=NUM_CONVERSATIONS, + request_rate=float("inf"), + gsp_num_groups=2, + gsp_prompts_per_group=2, + gsp_system_prompt_len=64, + gsp_question_len=16, + gsp_output_len=16, + gsp_num_turns=NUM_TURNS, + ) + args.warmup_requests = 0 + res = run_benchmark(args) + self.assertEqual(res["completed"], NUM_CONVERSATIONS * NUM_TURNS) + + time.sleep(1) + logs = "".join(f.read_text() for f in Path(temp_dir).glob("*.log")) + self._verify_multi_turn_logs(logs) + finally: + kill_process_tree(process.pid) + + def _verify_multi_turn_logs(self, content: str): + reqs = [] + for line in content.splitlines(): + idx = line.find("{") + if idx == -1: + continue + try: + obj = json.loads(line[idx:]) + except json.JSONDecodeError: + continue + if obj.get("event") != "request.finished": + continue + text = obj.get("obj", {}).get("text") + rid = obj.get("rid", "") + if text and not rid.startswith(HEALTH_CHECK_RID_PREFIX): + reqs.append(text) + + self.assertGreaterEqual(len(reqs), NUM_CONVERSATIONS * NUM_TURNS) + + # Verify prefix relationships + reqs_sorted = sorted(reqs, key=len) + prefix_count = 0 + for i, text in enumerate(reqs_sorted): + for j in range(i + 1, len(reqs_sorted)): + if reqs_sorted[j].startswith(text): + prefix_count += 1 + break + + expected = NUM_CONVERSATIONS * (NUM_TURNS - 1) + self.assertGreaterEqual( + prefix_count, expected, f"Expected at least {expected} prefix pairs" + ) + + +class TestBenchServingCustomHeaders(CustomTestCase): + def test_parse_custom_headers(self): + headers = parse_custom_headers(["MyHeader=MY_VALUE", "Another=value=hello"]) + self.assertEqual(headers, {"MyHeader": "MY_VALUE", "Another": "value=hello"}) + + headers = parse_custom_headers(["InvalidNoEquals"]) + self.assertEqual(headers, {}) + + headers = parse_custom_headers(["=NoKey"]) + self.assertEqual(headers, {}) + + # TODO: Using well-implemented mock server, e.g. the on in sgl-router + def test_custom_headers_sent_to_server(self): + import queue + + received_requests = queue.Queue() + + class HeaderEchoHandler(BaseHTTPRequestHandler): + def _handle(self): + received_requests.put( + { + "method": self.command, + "path": self.path, + "headers": dict(self.headers), + } + ) + self.send_response(200) + self.send_header("Content-Type", "application/json") + self.end_headers() + if self.path == "/v1/models": + self.wfile.write(json.dumps({"data": [{"id": "gpt2"}]}).encode()) + elif self.path == "/generate": + self.wfile.write( + json.dumps( + {"text": "ok", "meta_info": {"completion_tokens": 1}} + ).encode() + ) + else: + self.wfile.write(json.dumps({}).encode()) + + do_GET = do_POST = _handle + + server = HTTPServer(("127.0.0.1", 0), HeaderEchoHandler) + port = server.server_address[1] + server_thread = threading.Thread(target=server.serve_forever) + server_thread.daemon = True + server_thread.start() + + try: + args = get_benchmark_args( + base_url=f"http://127.0.0.1:{port}", + backend="sglang", + dataset_name="random", + tokenizer="gpt2", + num_prompts=1, + random_input_len=8, + random_output_len=8, + header=["X-Custom-Test=TestValue123", "X-Another=AnotherVal"], + ) + args.warmup_requests = 0 + args.disable_tqdm = True + run_benchmark(args) + except Exception: + pass + finally: + server.shutdown() + + all_reqs = [] + while not received_requests.empty(): + all_reqs.append(received_requests.get_nowait()) + + generate_reqs = [r for r in all_reqs if r["path"] == "/generate"] + self.assertGreater( + len(generate_reqs), + 0, + f"No /generate request. All: {[r['path'] for r in all_reqs]}", + ) + headers = generate_reqs[0]["headers"] + self.assertEqual(headers.get("X-Custom-Test"), "TestValue123") + self.assertEqual(headers.get("X-Another"), "AnotherVal") + + +if __name__ == "__main__": + unittest.main() diff --git a/asian_ai/performance/SGLang/test/registered/bench_fn/test_bench_serving_reasoning_stream.py b/asian_ai/performance/SGLang/test/registered/bench_fn/test_bench_serving_reasoning_stream.py new file mode 100644 index 0000000000000000000000000000000000000000..9cdce98eeeff621bcd06d2dc83389c5b305f0632 --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/bench_fn/test_bench_serving_reasoning_stream.py @@ -0,0 +1,334 @@ +"""Unit tests for bench_serving streaming with reasoning_content chunks. + +Reasoning models (DeepSeek-R1, MiMo, Qwen3 reasoning, Kimi-K2, ...) stream their +chain-of-thought via OpenAI's `delta.reasoning_content` field. Without explicit +support, bench_serving only inspects `delta.content` and silently reports zero +TTFT / ITL and an empty `generated_text`, which then retokenizes to 0 tokens +even though the backend completed real work. +""" + +import asyncio +import json +import socket +import threading +import time +import unittest +from argparse import Namespace +from http.server import BaseHTTPRequestHandler, HTTPServer + +from sglang.benchmark.serving import ( + RequestFuncInput, + async_request_openai_chat_completions, + calculate_metrics, + set_global_args, +) +from sglang.test.ci.ci_register import register_cpu_ci +from sglang.test.test_utils import CustomTestCase + +register_cpu_ci(est_time=10, suite="base-a-test-cpu") + + +def _free_port() -> int: + with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s: + s.bind(("127.0.0.1", 0)) + return s.getsockname()[1] + + +class _SSEHandler(BaseHTTPRequestHandler): + """Streams a fixed sequence of OpenAI-compatible SSE chunks per test.""" + + chunks: list = [] + chunk_delay_s: float = 0.02 + + def do_POST(self): # noqa: N802 (BaseHTTPRequestHandler interface) + length = int(self.headers.get("Content-Length", "0")) + if length: + self.rfile.read(length) + self.send_response(200) + self.send_header("Content-Type", "text/event-stream") + self.send_header("Cache-Control", "no-cache") + self.end_headers() + for chunk in self.chunks: + self.wfile.write(b"data: " + json.dumps(chunk).encode() + b"\n\n") + self.wfile.flush() + time.sleep(self.chunk_delay_s) + self.wfile.write(b"data: [DONE]\n\n") + self.wfile.flush() + + def log_message(self, fmt, *args): # silence access logs + return + + +class _JSONHandler(BaseHTTPRequestHandler): + response_body: dict = {} + request_bodies: list = [] + + def do_POST(self): # noqa: N802 (BaseHTTPRequestHandler interface) + length = int(self.headers.get("Content-Length", "0")) + if length: + self.request_bodies.append(json.loads(self.rfile.read(length))) + self.send_response(200) + self.send_header("Content-Type", "application/json") + self.end_headers() + self.wfile.write(json.dumps(self.response_body).encode()) + self.wfile.flush() + + def log_message(self, fmt, *args): + return + + +def _make_chunk(content=None, reasoning_content=None, completion_tokens=None): + delta = {} + if content is not None: + delta["content"] = content + if reasoning_content is not None: + delta["reasoning_content"] = reasoning_content + chunk = {"choices": [{"index": 0, "delta": delta}]} + if completion_tokens is not None: + chunk["usage"] = {"completion_tokens": completion_tokens} + return chunk + + +def _make_response(content=None, reasoning_content=None, completion_tokens=1): + message = {"role": "assistant", "content": content} + if reasoning_content is not None: + message["reasoning_content"] = reasoning_content + return { + "choices": [{"index": 0, "message": message, "finish_reason": "length"}], + "usage": {"completion_tokens": completion_tokens}, + } + + +class _StrictStringTokenizer: + def encode(self, text, add_special_tokens=False): + if not isinstance(text, str): + raise ValueError("text input must be of type `str`") + return text.split() + + +class TestBenchServingReasoningStream(CustomTestCase): + @classmethod + def setUpClass(cls): + set_global_args( + Namespace( + disable_stream=False, + disable_ignore_eos=True, + print_requests=False, + tokenizer="", + header=None, + ) + ) + + def _run(self, chunks): + port = _free_port() + + class Handler(_SSEHandler): + pass + + Handler.chunks = list(chunks) + server = HTTPServer(("127.0.0.1", port), Handler) + thread = threading.Thread(target=server.serve_forever, daemon=True) + thread.start() + try: + req = RequestFuncInput( + prompt="hello", + api_url=f"http://127.0.0.1:{port}/v1/chat/completions", + prompt_len=1, + output_len=64, + model="dummy-model", + lora_name="", + image_data=None, + extra_request_body={}, + ) + return asyncio.run(async_request_openai_chat_completions(req)) + finally: + server.shutdown() + server.server_close() + + def test_reasoning_only_stream_populates_metrics(self): + chunks = [ + _make_chunk(reasoning_content="Let "), + _make_chunk(reasoning_content="me "), + _make_chunk(reasoning_content="think."), + _make_chunk(completion_tokens=3), + ] + out = self._run(chunks) + + self.assertTrue(out.success, msg=f"request failed: {out.error}") + self.assertEqual(out.generated_text, "Let me think.") + self.assertGreater(out.ttft, 0.0) + self.assertEqual(len(out.itl), 2, msg="should record ITL for chunks 2..N") + for v in out.itl: + self.assertGreater(v, 0.0) + self.assertEqual(out.text_chunks, ["me ", "think."]) + self.assertEqual(out.output_len, 3) + + def test_reasoning_then_content_accounts_both(self): + chunks = [ + _make_chunk(reasoning_content="step1 "), + _make_chunk(reasoning_content="step2 "), + _make_chunk(content="answer "), + _make_chunk(content="here"), + _make_chunk(completion_tokens=4), + ] + out = self._run(chunks) + + self.assertTrue(out.success, msg=f"request failed: {out.error}") + self.assertEqual(out.generated_text, "step1 step2 answer here") + self.assertGreater(out.ttft, 0.0) + self.assertEqual(len(out.itl), 3) + self.assertEqual(out.text_chunks, ["step2 ", "answer ", "here"]) + self.assertEqual(out.output_len, 4) + + def test_single_delta_preserves_reasoning_before_content(self): + chunks = [ + _make_chunk(content="answer", reasoning_content="thought "), + _make_chunk(completion_tokens=2), + ] + out = self._run(chunks) + + self.assertTrue(out.success, msg=f"request failed: {out.error}") + self.assertEqual(out.generated_text, "thought answer") + self.assertGreater(out.ttft, 0.0) + self.assertEqual(out.output_len, 2) + + def test_usage_only_stream_chunk_does_not_break(self): + chunks = [ + _make_chunk(reasoning_content="thinking"), + {"choices": [], "usage": {"completion_tokens": 1}}, + ] + out = self._run(chunks) + + self.assertTrue(out.success, msg=f"request failed: {out.error}") + self.assertEqual(out.generated_text, "thinking") + self.assertGreater(out.ttft, 0.0) + self.assertEqual(out.output_len, 1) + + def test_content_only_stream_unchanged(self): + chunks = [ + _make_chunk(content="hi "), + _make_chunk(content="there"), + _make_chunk(completion_tokens=2), + ] + out = self._run(chunks) + + self.assertTrue(out.success, msg=f"request failed: {out.error}") + self.assertEqual(out.generated_text, "hi there") + self.assertGreater(out.ttft, 0.0) + self.assertEqual(len(out.itl), 1) + self.assertEqual(out.text_chunks, ["there"]) + self.assertEqual(out.output_len, 2) + + def test_null_reasoning_field_does_not_break(self): + # Mirrors sglang's _StreamDelta: reasoning_content is always emitted, + # serialized as null when only content is present. + chunks = [ + { + "choices": [ + {"index": 0, "delta": {"content": "ok", "reasoning_content": None}} + ] + }, + { + "choices": [ + {"index": 0, "delta": {"content": None, "reasoning_content": None}} + ], + "usage": {"completion_tokens": 1}, + }, + ] + out = self._run(chunks) + + self.assertTrue(out.success, msg=f"request failed: {out.error}") + self.assertEqual(out.generated_text, "ok") + self.assertGreater(out.ttft, 0.0) + + +class TestBenchServingReasoningNonStream(CustomTestCase): + def _run(self, response_body): + set_global_args( + Namespace( + disable_stream=True, + disable_ignore_eos=False, + print_requests=False, + tokenizer="", + header=None, + ) + ) + port = _free_port() + + class Handler(_JSONHandler): + pass + + Handler.response_body = response_body + Handler.request_bodies = [] + server = HTTPServer(("127.0.0.1", port), Handler) + thread = threading.Thread(target=server.serve_forever, daemon=True) + thread.start() + try: + req = RequestFuncInput( + prompt="hello", + api_url=f"http://127.0.0.1:{port}/v1/chat/completions", + prompt_len=1, + output_len=64, + model="dummy-model", + lora_name="", + image_data=None, + extra_request_body={}, + ) + return ( + asyncio.run(async_request_openai_chat_completions(req)), + Handler.request_bodies, + ) + finally: + server.shutdown() + server.server_close() + + def test_reasoning_only_non_stream_metrics_retokenize_text(self): + out, request_bodies = self._run( + _make_response( + content=None, + reasoning_content="Let me think.", + completion_tokens=3, + ) + ) + + self.assertTrue(out.success, msg=f"request failed: {out.error}") + self.assertEqual(out.generated_text, "Let me think.") + self.assertEqual(out.output_len, 3) + self.assertFalse(request_bodies[0]["stream"]) + + metrics, output_lens = calculate_metrics( + input_requests=None, + outputs=[out], + dur_s=1.0, + tokenizer=_StrictStringTokenizer(), + backend="sglang-oai-chat", + ) + self.assertEqual(metrics.completed, 1) + self.assertEqual(output_lens, [3]) + self.assertEqual(metrics.total_output_retokenized, 3) + + def test_reasoning_then_content_non_stream_accounts_both(self): + out, _ = self._run( + _make_response( + content="answer", + reasoning_content="thought ", + completion_tokens=2, + ) + ) + + self.assertTrue(out.success, msg=f"request failed: {out.error}") + self.assertEqual(out.generated_text, "thought answer") + self.assertGreater(out.ttft, 0.0) + self.assertEqual(out.output_len, 2) + + def test_content_only_non_stream_unchanged(self): + out, _ = self._run(_make_response(content="answer", completion_tokens=1)) + + self.assertTrue(out.success, msg=f"request failed: {out.error}") + self.assertEqual(out.generated_text, "answer") + self.assertGreater(out.ttft, 0.0) + self.assertEqual(out.output_len, 1) + + +if __name__ == "__main__": + unittest.main() diff --git a/asian_ai/performance/SGLang/test/registered/bench_fn/test_benchmark_datasets_api.py b/asian_ai/performance/SGLang/test/registered/bench_fn/test_benchmark_datasets_api.py new file mode 100644 index 0000000000000000000000000000000000000000..ce4645fcc3057c435968e7ce10714adeee9721f4 --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/bench_fn/test_benchmark_datasets_api.py @@ -0,0 +1,1093 @@ +import asyncio +import json +import pickle +import random +import subprocess +import sys +import tempfile +import unittest +from collections import Counter +from pathlib import Path +from types import SimpleNamespace +from unittest.mock import patch + +import numpy as np +from PIL import Image +from tokenizers import Tokenizer +from tokenizers.models import WordLevel +from tokenizers.pre_tokenizers import Whitespace +from transformers import PreTrainedTokenizerFast + +from sglang.benchmark.datasets import DATASET_MAPPING, get_dataset +from sglang.benchmark.datasets.common import DatasetRow, gen_mm_prompt +from sglang.benchmark.datasets.custom import sample_custom_requests +from sglang.benchmark.datasets.generated_shared_prefix import ( + GeneratedSharedPrefixDataset, + _zipf_group_probs, + get_gen_prefix_cache_path, + sample_generated_shared_prefix_requests, +) +from sglang.benchmark.datasets.image import sample_image_requests +from sglang.benchmark.datasets.mmmu import sample_mmmu_requests +from sglang.benchmark.datasets.mooncake import get_mooncake_request_over_time +from sglang.benchmark.datasets.openai_dataset import sample_openai_requests +from sglang.benchmark.datasets.random import sample_random_requests +from sglang.benchmark.datasets.sharegpt import sample_sharegpt_requests +from sglang.test.ci.ci_register import register_cpu_ci + +register_cpu_ci(est_time=40, suite="base-a-test-cpu") +register_cpu_ci(est_time=7, suite="base-c-test-cpu") + + +class _DummyTokenTensor: + def __init__(self, value: int): + self.value = value + + def numel(self) -> int: + return self.value + + +def create_lightweight_tokenizer() -> PreTrainedTokenizerFast: + """Create a local lightweight tokenizer for CPU-only dataset tests.""" + vocab = {"[UNK]": 0, "[PAD]": 1, "[BOS]": 2, "[EOS]": 3} + vocab.update({f"tok_{i}": i + 4 for i in range(2048)}) + + tokenizer = Tokenizer(WordLevel(vocab=vocab, unk_token="[UNK]")) + tokenizer.pre_tokenizer = Whitespace() + + hf_tokenizer = PreTrainedTokenizerFast( + tokenizer_object=tokenizer, + unk_token="[UNK]", + pad_token="[PAD]", + bos_token="[BOS]", + eos_token="[EOS]", + ) + hf_tokenizer.chat_template = ( + "{% for message in messages %}" + "{{ message['role'] }}:" + "{% if message['content'] is string %}" + "{{ message['content'] }}" + "{% else %}" + "{% for item in message['content'] %}" + "{% if item['type'] == 'text' %}{{ item['text'] }}{% else %}[IMAGE]{% endif %}" + "{% endfor %}" + "{% endif %}\n" + "{% endfor %}" + "{% if add_generation_prompt %}assistant:{% endif %}" + ) + return hf_tokenizer + + +class DummyProcessor: + def __init__(self, tokenizer: PreTrainedTokenizerFast): + self.tokenizer = tokenizer + self.image_token_id = None + + def apply_chat_template(self, messages, add_generation_prompt=True, tokenize=False): + return self.tokenizer.apply_chat_template( + messages, + add_generation_prompt=add_generation_prompt, + tokenize=tokenize, + return_dict=False, + ) + + def __call__(self, text, images=None, padding=False, return_tensors="pt"): + text_len = len(self.tokenizer.encode(text[0])) + image_tokens = 4 * len(images) if images else 0 + return {"input_ids": _DummyTokenTensor(text_len + image_tokens)} + + +class _FakeMMMUDataset: + def __init__(self, records): + self.records = records + + def __len__(self): + return len(self.records) + + def select(self, indices): + if isinstance(indices, range): + indices = list(indices) + return _FakeMMMUDataset([self.records[i] for i in indices]) + + def __iter__(self): + return iter(self.records) + + +def make_args(**overrides): + args = { + "dataset_name": "sharegpt", + "dataset_path": "", + "num_prompts": 2, + "sharegpt_output_len": None, + "sharegpt_context_len": None, + "prompt_suffix": "", + "apply_chat_template": False, + "tokenize_prompt": False, + "random_input_len": 8, + "random_output_len": 4, + "random_range_ratio": 0.0, + "image_count": 1, + "random_image_count": False, + "image_format": "png", + "image_content": "blank", + "image_resolution": "8x8", + "backend": "sglang", + "gsp_num_groups": 2, + "gsp_prompts_per_group": 2, + "gsp_system_prompt_len": 8, + "gsp_question_len": 4, + "gsp_output_len": 4, + "gsp_range_ratio": 0.0, + "gsp_fast_prepare": False, + "gsp_send_routing_key": False, + "gsp_num_turns": 1, + "gsp_ordered": False, + "gsp_group_distribution": "uniform", + "gsp_zipf_alpha": None, + "seed": 1, + "mooncake_workload": "conversation", + "speed_bench_category": None, + "speed_bench_output_len": 512, + } + args.update(overrides) + return SimpleNamespace(**args) + + +class TestBenchmarkDatasetsAPI(unittest.TestCase): + def setUp(self): + self.tokenizer = create_lightweight_tokenizer() + self.processor = DummyProcessor(self.tokenizer) + self.tmpdir = tempfile.TemporaryDirectory() + self.tmpdir_path = Path(self.tmpdir.name) + # Redirect ~ for the GSP on-disk cache to the per-test tempdir, so + # tests never read/write the real ~/.cache/sglang/benchmark. The Zipf + # tests in particular compare freshly generated rows against the + # uniform path, and a stale cache file from prior runs would silently + # short-circuit the uniform path and break that comparison. + self._home_patch = patch( + "sglang.benchmark.datasets.generated_shared_prefix.Path.home", + return_value=self.tmpdir_path, + ) + self._home_patch.start() + + def tearDown(self): + self._home_patch.stop() + self.tmpdir.cleanup() + + def _write_sharegpt_json(self): + data = [ + { + "conversations": [ + {"value": "hello world"}, + {"value": "answer one"}, + ] + }, + { + "conversations": [ + {"value": "how are you"}, + {"value": "answer two"}, + ] + }, + { + "conversations": [ + {"value": "third prompt"}, + {"value": "answer three"}, + ] + }, + ] + path = self.tmpdir_path / "sharegpt.json" + with open(path, "w") as f: + json.dump(data, f) + return str(path) + + def _write_custom_jsonl(self): + rows = [ + { + "conversations": [ + {"content": "custom prompt 1"}, + {"content": "custom answer 1"}, + ] + }, + { + "conversations": [ + {"value": "custom prompt 2"}, + {"value": "custom answer 2"}, + ] + }, + ] + path = self.tmpdir_path / "custom.jsonl" + with open(path, "w") as f: + for row in rows: + f.write(json.dumps(row) + "\n") + return str(path) + + def _write_openai_jsonl(self): + rows = [ + { + "messages": [{"role": "user", "content": "What is 1+1?"}], + "max_tokens": 7, + "temperature": 0.3, + }, + { + "messages": [{"role": "user", "content": "What is 2+2?"}], + "max_tokens": 8, + "tools": [{"type": "function", "function": {"name": "tool_a"}}], + }, + ] + path = self.tmpdir_path / "openai.jsonl" + with open(path, "w") as f: + for row in rows: + f.write(json.dumps(row) + "\n") + return str(path) + + def _write_speed_bench_jsonl(self): + rows = [ + { + "question_id": "sb_001", + "category": "low_entropy", + "turns": ["Complete this Python function: def add(a, b):"], + }, + { + "question_id": "sb_002", + "category": "mixed", + "turns": [ + "Explain the concept of attention mechanisms in transformers." + ], + }, + { + "question_id": "sb_003", + "category": "high_entropy", + "turns": ["Write a short story about a robot discovering music."], + }, + { + "question_id": "sb_004", + "category": "low_entropy", + "turns": [ + "Sort the following list in ascending order: [5, 2, 8, 1, 9]" + ], + }, + ] + path = self.tmpdir_path / "speed_bench.jsonl" + with open(path, "w") as f: + for row in rows: + f.write(json.dumps(row) + "\n") + return str(path) + + def _write_mooncake_jsonl(self): + rows = [ + {"timestamp": 1000, "hash_ids": [1, 2], "output_length": 5}, + {"timestamp": 2000, "hash_ids": [3, 4], "output_length": 6}, + ] + path = self.tmpdir_path / "mooncake.jsonl" + with open(path, "w") as f: + for row in rows: + f.write(json.dumps(row) + "\n") + return str(path) + + async def _collect_mooncake_rows(self, records): + out = [] + async for row in get_mooncake_request_over_time( + input_requests=records, + tokenizer=self.tokenizer, + slowdown_factor=0.0, + num_rounds=1, + ): + out.append(row) + return out + + def test_sharegpt_sampler(self): + dataset_path = self._write_sharegpt_json() + rows = sample_sharegpt_requests( + dataset_path=dataset_path, + num_requests=2, + tokenizer=self.tokenizer, + ) + self.assertEqual(len(rows), 2) + self.assertTrue(all(isinstance(row, DatasetRow) for row in rows)) + + def test_random_sampler(self): + dataset_path = self._write_sharegpt_json() + rows_text = sample_random_requests( + input_len=8, + output_len=4, + num_prompts=2, + range_ratio=0.0, + tokenizer=self.tokenizer, + dataset_path=dataset_path, + random_sample=False, + return_text=True, + ) + rows_ids = sample_random_requests( + input_len=8, + output_len=4, + num_prompts=2, + range_ratio=0.0, + tokenizer=self.tokenizer, + dataset_path=dataset_path, + random_sample=False, + return_text=False, + ) + self.assertTrue(all(isinstance(row, DatasetRow) for row in rows_text)) + self.assertTrue(all(isinstance(row.prompt, list) for row in rows_ids)) + + def test_custom_sampler(self): + dataset_path = self._write_custom_jsonl() + rows = sample_custom_requests( + dataset_path=dataset_path, + num_requests=2, + tokenizer=self.tokenizer, + ) + self.assertEqual(len(rows), 2) + self.assertTrue(all(isinstance(row, DatasetRow) for row in rows)) + + def test_openai_sampler(self): + dataset_path = self._write_openai_jsonl() + rows = sample_openai_requests( + dataset_path=dataset_path, + num_requests=2, + tokenizer=self.tokenizer, + ) + self.assertEqual(len(rows), 2) + self.assertIn("temperature", rows[0].extra_request_body) + self.assertIn("tools", rows[1].extra_request_body) + + def test_generated_shared_prefix_sampler(self): + args = make_args(gsp_num_groups=2, gsp_prompts_per_group=2) + rows = sample_generated_shared_prefix_requests( + num_groups=args.gsp_num_groups, + prompts_per_group=args.gsp_prompts_per_group, + system_prompt_len=args.gsp_system_prompt_len, + question_len=args.gsp_question_len, + output_len=args.gsp_output_len, + range_ratio=args.gsp_range_ratio, + tokenizer=self.tokenizer, + seed=args.seed, + ) + self.assertEqual(len(rows), 4) + self.assertTrue(all(isinstance(row, DatasetRow) for row in rows)) + + def test_image_sampler(self): + rows = sample_image_requests( + num_requests=2, + image_count=1, + input_len=8, + output_len=4, + range_ratio=0.0, + processor=self.processor, + image_content="blank", + image_format="png", + image_resolution="8x8", + backend="sglang", + random_image_count=False, + ) + self.assertEqual(len(rows), 2) + self.assertTrue(all(isinstance(row, DatasetRow) for row in rows)) + self.assertTrue(all(row.image_data for row in rows)) + + def test_gen_mm_prompt_excludes_special_tokens(self): + tokenizer = create_lightweight_tokenizer() + multimodal_special_tokens = [ + "<|image_pad|>", + "<|video_pad|>", + "<|vision_start|>", + "<|vision_end|>", + "<|vision_pad|>", + ] + tokenizer.add_special_tokens( + {"additional_special_tokens": multimodal_special_tokens} + ) + special_token_ids = set( + tokenizer.convert_tokens_to_ids(multimodal_special_tokens) + ) + image_pad_id = tokenizer.convert_tokens_to_ids("<|image_pad|>") + captured_population = {} + + def fake_choices(population, k): + captured_population["tokens"] = population + return population[:k] + + with patch( + "sglang.benchmark.datasets.common.random.choices", + side_effect=fake_choices, + ): + gen_mm_prompt(tokenizer, image_pad_id, token_num=8) + + sampled_pool = set(captured_population["tokens"]) + self.assertFalse(special_token_ids & sampled_pool) + self.assertTrue(sampled_pool) + + def test_mmmu_sampler(self): + fake_records = [ + {"image_1": Image.new("RGB", (4, 4), color="white"), "question": "q1"}, + {"image_1": Image.new("RGB", (4, 4), color="white"), "question": "q2"}, + {"image_1": Image.new("RGB", (4, 4), color="white"), "question": "q3"}, + ] + fake_dataset = _FakeMMMUDataset(fake_records) + with patch( + "sglang.benchmark.datasets.mmmu.load_dataset", return_value=fake_dataset + ): + rows = sample_mmmu_requests( + num_requests=2, + processor=self.processor, + backend="sglang", + fixed_output_len=6, + random_sample=False, + ) + self.assertEqual(len(rows), 2) + self.assertTrue(all(isinstance(row, DatasetRow) for row in rows)) + + def test_mooncake_scheduler(self): + records = [ + {"timestamp": 1000, "hash_ids": [1], "output_length": 5}, + {"timestamp": 2000, "hash_ids": [2], "output_length": 6}, + ] + rows = asyncio.run(self._collect_mooncake_rows(records)) + self.assertEqual(len(rows), 2) + self.assertTrue(all(isinstance(row, DatasetRow) for row in rows)) + + def test_speed_bench_sampler(self): + dataset_path = self._write_speed_bench_jsonl() + args = make_args( + dataset_name="speed-bench", + dataset_path=dataset_path, + num_prompts=3, + ) + from sglang.benchmark.datasets.speed_bench import SpeedBenchDataset + + dataset = SpeedBenchDataset.from_args(args) + rows = dataset.load(self.tokenizer) + self.assertEqual(len(rows), 3) + self.assertTrue(all(isinstance(row, DatasetRow) for row in rows)) + self.assertTrue(all(row.output_len == 512 for row in rows)) + self.assertTrue(all(row.prompt_len > 0 for row in rows)) + + def test_speed_bench_category_filter(self): + dataset_path = self._write_speed_bench_jsonl() + args = make_args( + dataset_name="speed-bench", + dataset_path=dataset_path, + num_prompts=2, + speed_bench_category="low_entropy", + ) + from sglang.benchmark.datasets.speed_bench import SpeedBenchDataset + + dataset = SpeedBenchDataset.from_args(args) + rows = dataset.load(self.tokenizer) + # Only 2 low_entropy rows in the fixture, num_prompts=2 + self.assertEqual(len(rows), 2) + self.assertTrue(all(isinstance(row, DatasetRow) for row in rows)) + + def test_speed_bench_output_len_override(self): + dataset_path = self._write_speed_bench_jsonl() + args = make_args( + dataset_name="speed-bench", + dataset_path=dataset_path, + num_prompts=2, + speed_bench_output_len=128, + ) + from sglang.benchmark.datasets.speed_bench import SpeedBenchDataset + + dataset = SpeedBenchDataset.from_args(args) + rows = dataset.load(self.tokenizer) + self.assertEqual(len(rows), 2) + self.assertTrue(all(row.output_len == 128 for row in rows)) + + def test_speed_bench_empty_category_raises(self): + dataset_path = self._write_speed_bench_jsonl() + args = make_args( + dataset_name="speed-bench", + dataset_path=dataset_path, + num_prompts=1, + speed_bench_category="nonexistent_category", + ) + from sglang.benchmark.datasets.speed_bench import SpeedBenchDataset + + dataset = SpeedBenchDataset.from_args(args) + with self.assertRaises(ValueError): + dataset.load(self.tokenizer) + + def test_speed_bench_no_path_raises(self): + args = make_args( + dataset_name="speed-bench", + dataset_path="", + num_prompts=1, + ) + from sglang.benchmark.datasets.speed_bench import SpeedBenchDataset + + with self.assertRaises(ValueError): + SpeedBenchDataset.from_args(args) + + def test_dataset_mapping_and_dispatch(self): + expected = { + "sharegpt", + "custom", + "openai", + "random", + "random-ids", + "generated-shared-prefix", + "mmmu", + "image", + "mooncake", + "speed-bench", + } + self.assertTrue(expected.issubset(set(DATASET_MAPPING.keys()))) + + sharegpt_path = self._write_sharegpt_json() + mooncake_path = self._write_mooncake_jsonl() + + random_args = make_args(dataset_name="random-ids", tokenize_prompt=True) + random_rows = get_dataset(random_args, self.tokenizer, model_id="dummy-model") + self.assertEqual(len(random_rows), random_args.num_prompts) + self.assertTrue(all(isinstance(row.prompt, list) for row in random_rows)) + + sharegpt_args = make_args(dataset_name="sharegpt", dataset_path=sharegpt_path) + sharegpt_rows = get_dataset( + sharegpt_args, self.tokenizer, model_id="dummy-model" + ) + self.assertEqual(len(sharegpt_rows), sharegpt_args.num_prompts) + + mooncake_args = make_args( + dataset_name="mooncake", + dataset_path=mooncake_path, + num_prompts=1, + ) + mooncake_rows = get_dataset( + mooncake_args, self.tokenizer, model_id="dummy-model" + ) + self.assertEqual(len(mooncake_rows), 1) + self.assertIsInstance(mooncake_rows[0], dict) + + with patch( + "sglang.benchmark.datasets.image.get_processor", + return_value=self.processor, + ): + image_args = make_args(dataset_name="image") + image_rows = get_dataset(image_args, self.tokenizer, model_id="dummy-model") + self.assertEqual(len(image_rows), image_args.num_prompts) + + fake_mmmu_dataset = _FakeMMMUDataset( + [{"image_1": Image.new("RGB", (4, 4), color="white"), "question": "q"}] + ) + with ( + patch( + "sglang.benchmark.datasets.mmmu.get_processor", + return_value=self.processor, + ), + patch( + "sglang.benchmark.datasets.mmmu.load_dataset", + return_value=fake_mmmu_dataset, + ), + ): + mmmu_args = make_args(dataset_name="mmmu", num_prompts=1) + mmmu_rows = get_dataset(mmmu_args, self.tokenizer, model_id="dummy-model") + self.assertEqual(len(mmmu_rows), 1) + + gsp_args = make_args( + dataset_name="generated-shared-prefix", + gsp_num_groups=2, + gsp_prompts_per_group=2, + ) + gsp_rows = get_dataset(gsp_args, self.tokenizer, model_id="dummy-model") + self.assertEqual(len(gsp_rows), 4) + self.assertTrue(all(isinstance(row, DatasetRow) for row in gsp_rows)) + + speed_bench_path = self._write_speed_bench_jsonl() + speed_bench_args = make_args( + dataset_name="speed-bench", + dataset_path=speed_bench_path, + num_prompts=2, + ) + speed_bench_rows = get_dataset( + speed_bench_args, self.tokenizer, model_id="dummy-model" + ) + self.assertEqual(len(speed_bench_rows), 2) + self.assertTrue(all(isinstance(row, DatasetRow) for row in speed_bench_rows)) + + def test_get_dataset_unknown_dataset(self): + args = make_args(dataset_name="not-a-dataset") + with self.assertRaises(ValueError): + get_dataset(args, self.tokenizer, model_id="dummy-model") + + # ------------------------------------------------------------------ + # Generated-shared-prefix Zipf sampling + # ------------------------------------------------------------------ + + def _run_gsp( + self, + *, + mode="uniform", + alpha=None, + seed=42, + num_groups=4, + prompts_per_group=5, + num_turns=1, + send_routing_key=False, + ordered=True, + range_ratio=1.0, + system_prompt_len=4, + question_len=3, + output_len=2, + fast_prepare=True, + global_seed=None, + ): + # GSP's own `seed` kwarg only feeds the cache filename; reproducibility + # of compute_random_lens / gen_prompt comes from seeding the module + # globals before calling. Tests must seed both random and numpy here. + seed_for_globals = global_seed if global_seed is not None else seed + random.seed(seed_for_globals) + np.random.seed(seed_for_globals) + return sample_generated_shared_prefix_requests( + num_groups=num_groups, + prompts_per_group=prompts_per_group, + system_prompt_len=system_prompt_len, + question_len=question_len, + output_len=output_len, + range_ratio=range_ratio, + tokenizer=self.tokenizer, + seed=seed, + send_routing_key=send_routing_key, + num_turns=num_turns, + fast_prepare=fast_prepare, + ordered=ordered, + group_distribution=mode, + zipf_alpha=alpha, + ) + + @staticmethod + def _row_fields(rows): + return [(r.prompt, r.prompt_len, r.output_len, r.routing_key) for r in rows] + + def test_gsp_uniform_default_unchanged(self): + # Uniform mode returns the documented number of rows and is + # bit-reproducible under fixed seeding of the global RNGs. + rows_a = self._run_gsp( + mode="uniform", num_groups=3, prompts_per_group=4, seed=7 + ) + rows_b = self._run_gsp( + mode="uniform", num_groups=3, prompts_per_group=4, seed=7 + ) + self.assertEqual(len(rows_a), 3 * 4) + self.assertEqual(self._row_fields(rows_a), self._row_fields(rows_b)) + + def test_gsp_uniform_cache_path_format_unchanged(self): + # The uniform-mode cache filename keeps its existing + # gen_shared_prefix___

____.pkl + # shape. The trailing class name is a transformers/tokenizers internal + # detail (TokenizersBackend / PreTrainedTokenizerFast depending on + # version), so we only pin the deterministic numeric portion. + path = get_gen_prefix_cache_path( + seed=7, + num_groups=3, + prompts_per_group=4, + system_prompt_len=16, + question_len=8, + output_len=4, + tokenizer=self.tokenizer, + ) + self.assertTrue(path.name.startswith("gen_shared_prefix_7_3_4_16_8_4_")) + self.assertTrue(path.name.endswith(".pkl")) + self.assertEqual(path.parent, Path.home() / ".cache" / "sglang" / "benchmark") + + def test_zipf_group_probs_helper(self): + # Rank-based probability vector: weight(rank) = 1 / rank ** alpha, + # normalized to sum to 1, with rank starting at 1. + probs_n3_a1 = _zipf_group_probs(3, 1.0) + expected_n3_a1 = np.array([6.0, 3.0, 2.0]) / 11.0 + np.testing.assert_allclose(probs_n3_a1, expected_n3_a1, atol=1e-12) + self.assertAlmostEqual(float(probs_n3_a1.sum()), 1.0, places=12) + + probs_n4_a15 = _zipf_group_probs(4, 1.5) + ranks = np.arange(1, 5, dtype=np.float64) + ref = 1.0 / ranks**1.5 + ref = ref / ref.sum() + np.testing.assert_allclose(probs_n4_a15, ref, atol=1e-12) + # Three-decimal pin against a hand-computable reference. + np.testing.assert_allclose( + np.round(probs_n4_a15, 3), + np.array([0.598, 0.212, 0.115, 0.075]), + atol=1e-3, + ) + + def test_zipf_group_probs_not_lora_skewed_formula(self): + # The helper must NOT use the LoRA `skewed` alpha**-i exponential + # formula; for alpha=1.5, N=4 the two formulas differ noticeably. + actual = _zipf_group_probs(4, 1.5) + lora_weights = np.array([1.5**-i for i in range(4)], dtype=np.float64) + lora_probs = lora_weights / lora_weights.sum() + self.assertFalse( + np.allclose(actual, lora_probs, atol=1e-3), + "Zipf helper must use rank-based 1/rank**alpha, not LoRA alpha**-i", + ) + + def test_zipf_reproducible_with_seed(self): + # Same seed + same args -> identical rows, including order, under + # both the in-order and shuffled paths. + kwargs = dict( + mode="zipf", alpha=1.7, seed=11, num_groups=4, prompts_per_group=10 + ) + rows_a = self._run_gsp(**kwargs) + rows_b = self._run_gsp(**kwargs) + self.assertEqual(len(rows_a), 4 * 10) + self.assertEqual(self._row_fields(rows_a), self._row_fields(rows_b)) + + # Also under the shuffled path. + rows_c = self._run_gsp(ordered=False, **kwargs) + rows_d = self._run_gsp(ordered=False, **kwargs) + self.assertEqual(self._row_fields(rows_c), self._row_fields(rows_d)) + + def test_zipf_different_seeds_differ(self): + # Different seeds -> at least one differing slot under Zipf sampling. + base = dict(mode="zipf", alpha=1.7, num_groups=4, prompts_per_group=10) + rows_a = self._run_gsp(seed=11, **base) + rows_b = self._run_gsp(seed=12, **base) + self.assertEqual(len(rows_a), len(rows_b)) + self.assertNotEqual(self._row_fields(rows_a), self._row_fields(rows_b)) + + def test_zipf_does_not_perturb_global_random_state(self): + # The Zipf branch must consume zero draws from the global random / + # numpy.random state. Therefore the per-slot generated questions and + # system prompts under uniform and Zipf modes for the same args and + # the same global seed are byte-equal. + common = dict( + num_groups=4, + prompts_per_group=6, + system_prompt_len=4, + question_len=3, + output_len=2, + range_ratio=1.0, + seed=99, + ordered=True, + send_routing_key=False, + fast_prepare=True, + global_seed=99, + ) + uniform_rows = self._run_gsp(mode="uniform", **common) + zipf_rows = self._run_gsp(mode="zipf", alpha=1.3, **common) + + # Slot i in uniform mode pairs system_prompts[i // P] with + # questions[i // P][i % P], so the question substring after the + # delimiter is exactly the i-th question. Same construction is used by + # the Zipf branch (only the system prompt changes per slot), so the + # question substrings must match slot-by-slot under the same global + # seed. + delim = "\n\n" + + def question_of(prompt): + return prompt.split(delim, 1)[1] + + uniform_questions = [question_of(r.prompt) for r in uniform_rows] + zipf_questions = [question_of(r.prompt) for r in zipf_rows] + self.assertEqual(uniform_questions, zipf_questions) + + # The set of system prompts (which the gen_prompt path generates) must + # also match between modes (set equality, since Zipf reuses prefixes). + def system_of(prompt): + return prompt.split(delim, 1)[0] + + self.assertEqual( + set(system_of(r.prompt) for r in uniform_rows), + set(system_of(r.prompt) for r in zipf_rows), + ) + + def test_zipf_deterministic_per_group_counts(self): + # The per-group counts are deterministic and pinned for a known + # (num_groups, prompts_per_group, alpha, seed) tuple. Any drift in + # the Zipf sampling implementation will trip this assertion. + rows = self._run_gsp( + mode="zipf", + alpha=2.0, + seed=0, + num_groups=4, + prompts_per_group=25, + send_routing_key=True, + ordered=True, + ) + self.assertEqual(len(rows), 4 * 25) + # routing_key format is "__". + per_group = Counter(int(r.routing_key.rsplit("_", 1)[-1]) for r in rows) + # Pinned counts derived from the implementation for + # (N=4, P=25, alpha=2.0, seed=0) using numpy.random.default_rng(seed) + # and rng.choice over _zipf_group_probs(N, alpha). + self.assertEqual( + dict(per_group), + {0: 63, 1: 18, 2: 12, 3: 7}, + ) + # Independent skew sanity check: rank-1 (hottest) > rank-N (coldest). + self.assertGreater(per_group[0], per_group[3]) + + def test_zipf_uses_distinct_cache_from_uniform(self): + # The on-disk cache key includes group_distribution and zipf_alpha, + # so uniform mode, zipf alpha=1.0, and zipf alpha=2.0 each get their + # own file. Uniform mode never reads a zipf cache and vice versa. + from sglang.benchmark.datasets import generated_shared_prefix as gsp_mod + + fake_home = self.tmpdir_path / "fakehome" + fake_home.mkdir() + + common = dict( + num_groups=2, + prompts_per_group=3, + system_prompt_len=4, + question_len=3, + output_len=2, + range_ratio=1.0, + seed=5, + send_routing_key=False, + num_turns=1, + fast_prepare=True, + ordered=True, + ) + + with patch.object(gsp_mod.Path, "home", return_value=fake_home): + uniform_path = get_gen_prefix_cache_path( + seed=common["seed"], + num_groups=common["num_groups"], + prompts_per_group=common["prompts_per_group"], + system_prompt_len=common["system_prompt_len"], + question_len=common["question_len"], + output_len=common["output_len"], + tokenizer=self.tokenizer, + ) + zipf_path_a = get_gen_prefix_cache_path( + seed=common["seed"], + num_groups=common["num_groups"], + prompts_per_group=common["prompts_per_group"], + system_prompt_len=common["system_prompt_len"], + question_len=common["question_len"], + output_len=common["output_len"], + tokenizer=self.tokenizer, + group_distribution="zipf", + zipf_alpha=1.5, + ) + zipf_path_b = get_gen_prefix_cache_path( + seed=common["seed"], + num_groups=common["num_groups"], + prompts_per_group=common["prompts_per_group"], + system_prompt_len=common["system_prompt_len"], + question_len=common["question_len"], + output_len=common["output_len"], + tokenizer=self.tokenizer, + group_distribution="zipf", + zipf_alpha=2.0, + ) + self.assertNotEqual(uniform_path, zipf_path_a) + self.assertNotEqual(zipf_path_a, zipf_path_b) + + # Run each mode; each writes its own cache file. + self._run_gsp(mode="uniform", **common) + self._run_gsp(mode="zipf", alpha=1.5, **common) + self._run_gsp(mode="zipf", alpha=2.0, **common) + self.assertTrue(uniform_path.exists()) + self.assertTrue(zipf_path_a.exists()) + self.assertTrue(zipf_path_b.exists()) + + # Sentinel into the uniform cache: zipf must not read it. + sentinel = [DatasetRow(prompt="SENTINEL", prompt_len=1, output_len=1)] + with open(uniform_path, "wb") as f: + pickle.dump(sentinel, f) + zipf_rows = self._run_gsp(mode="zipf", alpha=1.5, **common) + self.assertNotEqual(zipf_rows, sentinel) + + # Second zipf call with same args must load from cache (no + # regeneration). Mutate the zipf cache to a sentinel and confirm. + zipf_sentinel = [ + DatasetRow(prompt="ZIPF_SENTINEL", prompt_len=1, output_len=1) + ] + with open(zipf_path_a, "wb") as f: + pickle.dump(zipf_sentinel, f) + reloaded = self._run_gsp(mode="zipf", alpha=1.5, **common) + self.assertEqual(reloaded, zipf_sentinel) + + def test_zipf_total_rows_and_unique_prompts(self): + # Total returned row count under Zipf equals num_groups * + # prompts_per_group (identical to uniform mode) and every prompt + # string is unique even when groups repeat. + rows = self._run_gsp( + mode="zipf", + alpha=2.5, + seed=3, + num_groups=4, + prompts_per_group=10, + send_routing_key=False, + ) + self.assertEqual(len(rows), 4 * 10) + self.assertEqual(len({r.prompt for r in rows}), len(rows)) + + def test_zipf_ordered_preserves_generation_order(self): + # With ordered=True, output preserves the sampled order and matches + # an independently re-derived group sequence from default_rng(seed). + rows = self._run_gsp( + mode="zipf", + alpha=1.5, + seed=21, + num_groups=3, + prompts_per_group=8, + send_routing_key=True, + ordered=True, + ) + observed_groups = [int(r.routing_key.rsplit("_", 1)[-1]) for r in rows] + + # Independently reproduce the expected group sequence: an isolated + # default_rng(seed) over _zipf_group_probs(N, alpha) sampling + # N * P slots. + expected_rng = np.random.default_rng(21) + expected_probs = _zipf_group_probs(3, 1.5) + expected_groups = expected_rng.choice( + 3, size=3 * 8, replace=True, p=expected_probs + ).tolist() + self.assertEqual(observed_groups, expected_groups) + + def test_zipf_shuffle_path_matches_uniform_shuffle(self): + # When ordered=False, both modes go through random.shuffle on a list + # of equal length, so the same global RNG seed yields the same + # permutation. Verified indirectly: two Zipf calls with the same + # global seed produce identical orderings. + kwargs = dict( + mode="zipf", + alpha=1.2, + seed=8, + num_groups=4, + prompts_per_group=6, + send_routing_key=False, + ordered=False, + global_seed=8, + ) + rows_a = self._run_gsp(**kwargs) + rows_b = self._run_gsp(**kwargs) + self.assertEqual(self._row_fields(rows_a), self._row_fields(rows_b)) + + # ------------------------------------------------------------------ + # CLI / from_args validation + # ------------------------------------------------------------------ + + def test_from_args_rejects_invalid_distribution_and_alpha(self): + # Defensive validation in from_args protects in-process callers + # that build a Namespace by hand and bypass the argparse boundary + # in bench_serving.py. Covers: unknown distribution, zipf without + # alpha, uniform with alpha, and non-finite/non-positive alpha. + cases = [ + {"gsp_group_distribution": "not-a-distribution", "gsp_zipf_alpha": None}, + {"gsp_group_distribution": "zipf", "gsp_zipf_alpha": None}, + {"gsp_group_distribution": "uniform", "gsp_zipf_alpha": 1.0}, + {"gsp_group_distribution": "zipf", "gsp_zipf_alpha": 0.0}, + {"gsp_group_distribution": "zipf", "gsp_zipf_alpha": -0.5}, + {"gsp_group_distribution": "zipf", "gsp_zipf_alpha": float("nan")}, + {"gsp_group_distribution": "zipf", "gsp_zipf_alpha": float("inf")}, + {"gsp_group_distribution": "zipf", "gsp_zipf_alpha": float("-inf")}, + ] + for case in cases: + args = make_args(dataset_name="generated-shared-prefix", **case) + with self.assertRaises(ValueError, msg=f"case={case}"): + GeneratedSharedPrefixDataset.from_args(args) + + def test_bench_serving_help_and_invalid_choice_argparse(self): + # Subprocess-driven coverage of the live CLI: --help advertises both + # flags with the rank-based Zipf formula and the alpha constraint, + # and argparse rejects an unknown distribution choice. + help_res = subprocess.run( + [sys.executable, "-m", "sglang.benchmark.serving", "--help"], + capture_output=True, + text=True, + timeout=90, + ) + self.assertEqual(help_res.returncode, 0, help_res.stderr) + out = help_res.stdout + # Both new flags appear. + self.assertIn("--gsp-group-distribution", out) + self.assertIn("--gsp-zipf-alpha", out) + # Rank-based Zipf formula and alpha constraint are documented. + self.assertIn("1/rank**alpha", out) + self.assertIn("rank starts at 1", out) + self.assertIn("finite float", out) + + # Argparse rejects unknown distribution choice. + bad_choice_res = subprocess.run( + [ + sys.executable, + "-m", + "sglang.benchmark.serving", + "--dataset-name", + "generated-shared-prefix", + "--gsp-group-distribution", + "invalid_name", + ], + capture_output=True, + text=True, + timeout=90, + ) + self.assertNotEqual(bad_choice_res.returncode, 0) + self.assertIn("invalid choice", (bad_choice_res.stderr + bad_choice_res.stdout)) + + def test_bench_serving_cli_rejects_zipf_without_alpha_before_server(self): + # Malformed CLI combinations (zipf with no alpha) must fail at + # argparse time so users see the GSP-flag error directly, not a + # downstream connection or model-fetch failure. + res = subprocess.run( + [ + sys.executable, + "-m", + "sglang.benchmark.serving", + "--dataset-name", + "generated-shared-prefix", + "--gsp-group-distribution", + "zipf", + "--ready-check-timeout-sec", + "0", + ], + capture_output=True, + text=True, + timeout=90, + ) + # parser.error() exits with code 2 (argparse convention). + self.assertEqual(res.returncode, 2, res.stderr) + stderr = res.stderr + res.stdout + self.assertIn("--gsp-group-distribution", stderr) + self.assertIn("--gsp-zipf-alpha", stderr) + # The error must mention the GSP flags directly, not a network or + # model-discovery problem masquerading as the failure. + for forbidden in [ + "HTTPConnectionPool", + "HTTPSConnectionPool", + "Connection refused", + "Failed to fetch model", + "Traceback", + ]: + self.assertNotIn(forbidden, stderr) + + def test_bench_serving_cli_rejects_uniform_with_alpha_before_server(self): + # The complementary malformation: uniform distribution with an + # explicit alpha value. Must also fail at argparse time. + res = subprocess.run( + [ + sys.executable, + "-m", + "sglang.benchmark.serving", + "--dataset-name", + "generated-shared-prefix", + "--gsp-group-distribution", + "uniform", + "--gsp-zipf-alpha", + "1.0", + "--ready-check-timeout-sec", + "0", + ], + capture_output=True, + text=True, + timeout=90, + ) + self.assertEqual(res.returncode, 2, res.stderr) + stderr = res.stderr + res.stdout + self.assertIn("--gsp-group-distribution", stderr) + self.assertIn("--gsp-zipf-alpha", stderr) + for forbidden in [ + "HTTPConnectionPool", + "HTTPSConnectionPool", + "Connection refused", + "Failed to fetch model", + "Traceback", + ]: + self.assertNotIn(forbidden, stderr) + + +if __name__ == "__main__": + unittest.main() diff --git a/asian_ai/performance/SGLang/test/registered/chunked_prefill/test_scripted_core_1gpu.py b/asian_ai/performance/SGLang/test/registered/chunked_prefill/test_scripted_core_1gpu.py new file mode 100644 index 0000000000000000000000000000000000000000..4a1409953a061e2cf198c238022a162457524509 --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/chunked_prefill/test_scripted_core_1gpu.py @@ -0,0 +1,189 @@ +import unittest + +from sglang.test.ci.ci_register import register_amd_ci, register_cuda_ci +from sglang.test.scripted_runtime.context import ScriptedContext +from sglang.test.scripted_runtime.test_case import ScriptedTestCase +from sglang.test.scripted_runtime_chunked_helpers import ( + LIFECYCLE_STAGES, + advance_to_lifecycle_stage, + base_engine_kwargs, + run_until_finished, +) + +register_cuda_ci(est_time=300, stage="extra-a", runner_config="1-gpu-small") +register_amd_ci(est_time=198, stage="extra-a", runner_config="1-gpu-small-amd") + + +_CHUNK_SIZE = 64 +_PROMPT_LEN = 4 * _CHUNK_SIZE - 3 + +_NUM_MIDDLE_CHUNKS = (_PROMPT_LEN - 1) // _CHUNK_SIZE +_LIFECYCLE_MAX_NEW_TOKENS = 4 + + +def _advance_to_stage(r, stage: str): + yield from advance_to_lifecycle_stage( + r, + stage, + num_middle_chunks=_NUM_MIDDLE_CHUNKS, + max_new_tokens=_LIFECYCLE_MAX_NEW_TOKENS, + ) + + +class TestScriptedCore(ScriptedTestCase): + ENGINE_KWARGS = base_engine_kwargs(chunked_prefill_size=_CHUNK_SIZE) + + def test_chunked_prefill_smoke(self): + self.server.execute_script(self._script_chunked_prefill_smoke) + + @staticmethod + def _script_chunked_prefill_smoke(t: ScriptedContext): + r = t.start_req(prompt_len=_PROMPT_LEN, max_new_tokens=3) + yield from run_until_finished(r) + assert r.finished, "req did not finish" + + def test_chunked_prefill_smoke_at_chunk_boundary_offsets(self): + for offset in (-2, -1, 1, 2): + prompt_len = 2 * _CHUNK_SIZE + offset + with self.subTest(offset=offset, prompt_len=prompt_len): + self.server.execute_script( + self._script_chunked_prefill_smoke_at_offset, + args=(prompt_len,), + ) + + @staticmethod + def _script_chunked_prefill_smoke_at_offset(t: ScriptedContext, prompt_len: int): + r = t.start_req(prompt_len=prompt_len, max_new_tokens=3) + yield from run_until_finished(r) + assert r.finished, f"req with prompt_len={prompt_len} did not finish" + + def test_pause_retract_at_lifecycle_points_then_resume(self): + for stage in LIFECYCLE_STAGES: + with self.subTest(stage=stage): + self.server.execute_script( + self._script_pause_retract_at_stage, + args=(stage,), + ) + + @staticmethod + def _script_pause_retract_at_stage(t: ScriptedContext, stage: str): + r = t.start_req( + prompt_len=_PROMPT_LEN, max_new_tokens=_LIFECYCLE_MAX_NEW_TOKENS + ) + yield from _advance_to_stage(r, stage) + + assert r.req is not None, f"stage={stage}: req vanished before pause" + + t.pause_generation(mode="retract") + yield + + # At the last_decode stage the final decode can complete during the + # retract; a finished req is removed from the scheduler, so its + # output_ids are no longer observable through the harness. That case's + # only observable consequence — clean completion — is covered by the + # run_until_finished tail below. When the req is not finished, + # pause(retract) must park it back in the waiting_queue and the paused + # engine must not advance it. + if not r.finished: + req = r.req + assert req is not None and req in t.scheduler.waiting_queue, ( + f"stage={stage}: pause(retract) should park the req back in " + f"waiting_queue; found={req!r}" + ) + output_tokens_after_pause = len(req.output_ids) + for _ in range(3): + yield + req = r.req + assert ( + req is not None and len(req.output_ids) == output_tokens_after_pause + ), ( + f"stage={stage}: paused engine advanced the req " + f"({len(req.output_ids) if req is not None else None} output " + f"tokens, expected {output_tokens_after_pause})" + ) + + t.continue_generation() + yield from run_until_finished(r) + assert r.finished, f"stage={stage}: req did not finish after pause/continue" + + def test_abort_all_at_lifecycle_points(self): + for stage in LIFECYCLE_STAGES: + with self.subTest(stage=stage): + self.server.execute_script( + self._script_abort_all_at_stage, args=(stage,) + ) + + @staticmethod + def _script_abort_all_at_stage(t: ScriptedContext, stage: str): + r = t.start_req( + prompt_len=_PROMPT_LEN, max_new_tokens=_LIFECYCLE_MAX_NEW_TOKENS + ) + yield from _advance_to_stage(r, stage) + + t.abort_all() + for _ in range(8): + yield + if r.finished: + break + + assert r.finished, f"stage={stage}: req did not finish after abort_all" + + def test_chunked_req_single_decode_finishes(self): + self.server.execute_script(self._script_chunked_req_single_decode_finishes) + + @staticmethod + def _script_chunked_req_single_decode_finishes(t: ScriptedContext): + r = t.start_req(prompt_len=_PROMPT_LEN, max_new_tokens=1) + yield from run_until_finished(r) + assert r.finished, "single-decode chunked req did not finish" + + def test_chunked_prefill_radix_hit_count(self): + self.server.execute_script(self._script_chunked_prefill_radix_hit_count) + + @staticmethod + def _script_chunked_prefill_radix_hit_count(t: ScriptedContext): + r = t.start_req(prompt_len=_PROMPT_LEN, max_new_tokens=2) + yield from run_until_finished(r) + assert r.finished + _assert_prefill_twice_decode_once(t, prompt_len=_PROMPT_LEN) + + def test_nonchunked_prefill_radix_hit_count(self): + self.server.execute_script(self._script_nonchunked_prefill_radix_hit_count) + + @staticmethod + def _script_nonchunked_prefill_radix_hit_count(t: ScriptedContext): + prompt_len = _CHUNK_SIZE - 20 + r = t.start_req(prompt_len=prompt_len, max_new_tokens=2) + yield from run_until_finished(r) + assert r.finished + _assert_prefill_twice_decode_once(t, prompt_len=prompt_len) + + +def _assert_prefill_twice_decode_once(t: ScriptedContext, *, prompt_len: int) -> None: + root = t.scheduler.tree_cache.root_node + prefill_hits: list[int] = [] + decode_hits: list[int] = [] + stack = [(child, len(child.key)) for child in root.children.values()] + while stack: + node, end_index = stack.pop() + bucket = prefill_hits if end_index <= prompt_len else decode_hits + bucket.append(node.hit_count) + for child in node.children.values(): + stack.append((child, end_index + len(child.key))) + + assert prefill_hits and decode_hits, ( + f"expected both prefill and decode radix nodes; " + f"prefill={prefill_hits}, decode={decode_hits}, prompt_len={prompt_len}" + ) + assert all(h == 2 for h in prefill_hits), ( + f"each prefill node must be hit exactly twice; " + f"prefill={prefill_hits}, decode={decode_hits}" + ) + assert all(h == 1 for h in decode_hits), ( + f"each decode node must be hit exactly once; " + f"prefill={prefill_hits}, decode={decode_hits}" + ) + + +if __name__ == "__main__": + unittest.main() diff --git a/asian_ai/performance/SGLang/test/registered/chunked_prefill/test_scripted_core_4gpu.py b/asian_ai/performance/SGLang/test/registered/chunked_prefill/test_scripted_core_4gpu.py new file mode 100644 index 0000000000000000000000000000000000000000..59397663f7f37db18a659faeecf2669b64934c14 --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/chunked_prefill/test_scripted_core_4gpu.py @@ -0,0 +1,95 @@ +import unittest + +from sglang.test.ci.ci_register import register_cuda_ci +from sglang.test.scripted_runtime.context import ScriptedContext +from sglang.test.scripted_runtime.test_case import ScriptedTestCase +from sglang.test.scripted_runtime_chunked_helpers import ( + DEFAULT_MAX_STEPS, + SMALL_MODEL, + base_engine_kwargs, + run_until_all_finished, + run_until_finished, +) + +register_cuda_ci(est_time=900, stage="extra-b", runner_config="4-gpu-h100") + + +_CHUNK_SIZE = 64 + + +class TestScriptedPpChunkSweep(ScriptedTestCase): + ENGINE_KWARGS = base_engine_kwargs( + model_path=SMALL_MODEL, + tp_size=1, + dp_size=1, + pp_size=4, + pp_async_batch_depth=2, + chunked_prefill_size=_CHUNK_SIZE, + ) + + _PP_LOOP_SIZE = ENGINE_KWARGS["pp_size"] + ENGINE_KWARGS["pp_async_batch_depth"] + assert _PP_LOOP_SIZE == 6 + + _NUM_CHUNKS_VALUES = (2, 4, 6, 8) + _NUM_CONC_REQS_VALUES = (1, 2, 4) + + def test_pp_chunk_sweep(self): + for num_chunks in self._NUM_CHUNKS_VALUES: + for num_conc_reqs in self._NUM_CONC_REQS_VALUES: + with self.subTest(num_chunks=num_chunks, num_conc_reqs=num_conc_reqs): + self.server.execute_script( + self._script_pp_one_combo, + args=(num_chunks, num_conc_reqs), + ) + + @staticmethod + def _script_pp_one_combo(t: ScriptedContext, num_chunks: int, num_conc_reqs: int): + prompt_len = num_chunks * _CHUNK_SIZE - 3 + reqs = [ + t.start_req(prompt_len=prompt_len, max_new_tokens=2) + for _ in range(num_conc_reqs) + ] + yield from run_until_all_finished(reqs, max_steps=DEFAULT_MAX_STEPS) + for r in reqs: + assert r.finished, ( + f"combo num_chunks={num_chunks}, num_conc_reqs={num_conc_reqs}: " + f"req {r.rid!r} did not finish" + ) + + def test_pp_flush_cache_during_inflight_chunk_results(self): + """flush_cache landing after the last chunk dispatch but before its batch result is processed must not corrupt the radix tree.""" + self.server.execute_script(self._script_flush_during_inflight_chunk_results) + + @staticmethod + def _script_flush_during_inflight_chunk_results(t: ScriptedContext): + scheduler = t.scheduler + r = t.start_req(prompt_len=2 * _CHUNK_SIZE - 3, max_new_tokens=2) + + # Wait for the window where the queues and the current microbatch slot + # bindings are all clear, yet dispatched chunk batch results are still + # in flight in the PP pipeline, then post flush_cache into that window. + flushed = False + for _ in range(DEFAULT_MAX_STEPS): + in_flight = any( + mb is not None and not mb.is_empty() for mb in scheduler.mbs + ) + queues_clear = ( + scheduler.chunked_req is None + and len(scheduler.waiting_queue) == 0 + and all(x.is_empty() for x in scheduler.running_mbs) + and (scheduler.cur_batch is None or scheduler.cur_batch.is_empty()) + and (scheduler.last_batch is None or scheduler.last_batch.is_empty()) + ) + if in_flight and queues_clear: + t.flush_cache() + flushed = True + break + yield + assert flushed, "never observed in-flight chunk results with clear queues" + + yield from run_until_finished(r, max_steps=DEFAULT_MAX_STEPS) + assert r.finished, f"req {r.rid!r} did not finish after flush_cache" + + +if __name__ == "__main__": + unittest.main() diff --git a/asian_ai/performance/SGLang/test/registered/chunked_prefill/test_scripted_swa_1gpu.py b/asian_ai/performance/SGLang/test/registered/chunked_prefill/test_scripted_swa_1gpu.py new file mode 100644 index 0000000000000000000000000000000000000000..275d5c853d185ab481d596c1bbf99076af17a7fd --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/chunked_prefill/test_scripted_swa_1gpu.py @@ -0,0 +1,107 @@ +import unittest + +from sglang.test.ci.ci_register import register_cuda_ci +from sglang.test.scripted_runtime.context import ScriptedContext +from sglang.test.scripted_runtime.test_case import ScriptedTestCase +from sglang.test.scripted_runtime_chunked_helpers import base_engine_kwargs + +register_cuda_ci(est_time=400, stage="extra-a", runner_config="1-gpu-large") + + +_SWA_MODEL = "openai/gpt-oss-20b" + +_MAX_TOTAL_TOKENS = 4096 +_SWA_FULL_TOKENS_RATIO = 0.1 +_CHUNK_SIZE = 64 + +_N_DECODERS = 6 +_DECODER_PROMPT = 64 +_DECODER_MAX_NEW = 512 +_DECODER_WARMUP_RUNNING = 3 + +_CHUNKED_PROMPT = 384 +_CHUNKED_MAX_NEW = 2 +_N_CANDIDATES = 24 +_STEPS_PER_CANDIDATE = 120 +_DECODER_WARMUP_STEPS = 60 +_DRAIN_STEPS = 400 + + +class TestScriptedSwaChunkedReqEarlyReturn(ScriptedTestCase): + ENGINE_KWARGS = base_engine_kwargs( + model_path=_SWA_MODEL, + chunked_prefill_size=_CHUNK_SIZE, + max_total_tokens=_MAX_TOTAL_TOKENS, + swa_full_tokens_ratio=_SWA_FULL_TOKENS_RATIO, + page_size=1, + mem_fraction_static=0.70, + ) + + def test_swa_chunked_req_early_return_no_double_free(self): + self.server.execute_script( + self._script_swa_chunked_req_early_return_no_double_free + ) + + @staticmethod + def _script_swa_chunked_req_early_return_no_double_free(t: ScriptedContext): + s = t.scheduler + + for i in range(_N_DECODERS): + t.start_req( + prompt_len=_DECODER_PROMPT, + max_new_tokens=_DECODER_MAX_NEW, + ignore_eos=True, + prompt_token=10 + i, + ) + for _ in range(_DECODER_WARMUP_STEPS): + if len(s.running_batch.reqs) >= _DECODER_WARMUP_RUNNING: + break + yield + + candidates = [] + parked = False + for _ in range(_N_CANDIDATES): + candidates.append( + t.start_req( + prompt_len=_CHUNKED_PROMPT, + max_new_tokens=_CHUNKED_MAX_NEW, + prompt_token=2, + ) + ) + for _ in range(_STEPS_PER_CANDIDATE): + if any(t.chunked_parks(c.rid) > 0 for c in candidates): + parked = True + break + if candidates[-1].finished: + break + yield + if parked: + break + + parked = parked or any(t.chunked_parks(c.rid) > 0 for c in candidates) + assert parked, ( + "no chunked candidate was ever parked by add_chunked_req's hybrid-SWA " + "early-return; the test never exercised the stash gate" + ) + + t.abort_all() + for _ in range(_DRAIN_STEPS): + if ( + s.chunked_req is None + and len(s.waiting_queue) == 0 + and s.running_batch.is_empty() + ): + break + yield + for _ in range(20): + yield + + locked = {nid: lr for nid, lr in t.get_all_node_lock_refs().items() if lr != 0} + assert not locked, ( + f"radix nodes left locked after drain {locked} -- stash gate let an " + "un-scheduled chunked req commit partial KV" + ) + + +if __name__ == "__main__": + unittest.main() diff --git a/asian_ai/performance/SGLang/test/registered/constrained_decoding/test_constrained_decoding.py b/asian_ai/performance/SGLang/test/registered/constrained_decoding/test_constrained_decoding.py new file mode 100644 index 0000000000000000000000000000000000000000..88e92b3a5c143f39281da3e1b0b7a49e863bb4d1 --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/constrained_decoding/test_constrained_decoding.py @@ -0,0 +1,73 @@ +import unittest + +from sglang.srt.utils import kill_process_tree +from sglang.test.ci.ci_register import register_amd_ci, register_cuda_ci +from sglang.test.kits.ebnf_constrained_kit import EBNFConstrainedMixin +from sglang.test.kits.json_constrained_kit import JSONConstrainedMixin +from sglang.test.kits.regex_constrained_kit import RegexConstrainedMixin +from sglang.test.test_utils import ( + DEFAULT_SMALL_MODEL_NAME_FOR_TEST, + DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH, + DEFAULT_URL_FOR_TEST, + CustomTestCase, + popen_launch_server, +) + +register_cuda_ci(est_time=120, stage="base-b", runner_config="1-gpu-small") +register_amd_ci(est_time=179, suite="stage-b-test-1-gpu-small-amd") + + +class ServerWithGrammar(CustomTestCase): + backend = "xgrammar" + disable_overlap = False + + @classmethod + def setUpClass(cls): + cls.model = DEFAULT_SMALL_MODEL_NAME_FOR_TEST + cls.base_url = DEFAULT_URL_FOR_TEST + launch_args = [ + "--max-running-requests", + "10", + "--grammar-backend", + cls.backend, + ] + + if cls.disable_overlap: + launch_args += ["--disable-overlap-schedule"] + + cls.process = popen_launch_server( + cls.model, + cls.base_url, + timeout=DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH, + other_args=launch_args, + ) + + @classmethod + def tearDownClass(cls): + kill_process_tree(cls.process.pid) + + +class TestXGrammarBackend( + ServerWithGrammar, + JSONConstrainedMixin, + EBNFConstrainedMixin, + RegexConstrainedMixin, +): + backend = "xgrammar" + + +class TestOutlinesBackend(ServerWithGrammar, JSONConstrainedMixin): + backend = "outlines" + + +class TestLLGuidanceBackend( + ServerWithGrammar, + JSONConstrainedMixin, + EBNFConstrainedMixin, + RegexConstrainedMixin, +): + backend = "llguidance" + + +if __name__ == "__main__": + unittest.main() diff --git a/asian_ai/performance/SGLang/test/registered/core/test_basic_sanity.py b/asian_ai/performance/SGLang/test/registered/core/test_basic_sanity.py new file mode 100644 index 0000000000000000000000000000000000000000..df5bcb4f1c576027e6141909af96f79b91cf1e78 --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/core/test_basic_sanity.py @@ -0,0 +1,66 @@ +"""Stage-a basic sanity: small-but-broad server coverage that downstream +stages depend on. Multiple sanity-kit mixins driving one shared server, +covering protocol, decode correctness, scheduler stress, occupancy, and +hellaswag accuracy.""" + +import unittest + +from sglang.srt.utils import is_hip, kill_process_tree +from sglang.test.ci.ci_register import register_amd_ci, register_cuda_ci +from sglang.test.kits.basic_api_contract_kit import BasicAPIContractMixin +from sglang.test.kits.basic_decode_correctness_kit import BasicDecodeCorrectnessMixin +from sglang.test.kits.basic_scheduler_stress_kit import BasicSchedulerStressMixin +from sglang.test.kits.fwd_occupancy_kit import FwdOccupancyMixin +from sglang.test.kits.hellaswag_kit import HellaswagMixin +from sglang.test.test_utils import ( + DEFAULT_MODEL_NAME_FOR_TEST, + DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH, + DEFAULT_URL_FOR_TEST, + CustomTestCase, + popen_launch_server, +) + +register_cuda_ci(est_time=160, stage="base-a", runner_config="1-gpu-small") +register_amd_ci(est_time=160, suite="stage-a-test-1-gpu-small-amd") + + +class TestBasicSanity( + BasicAPIContractMixin, + BasicDecodeCorrectnessMixin, + BasicSchedulerStressMixin, + FwdOccupancyMixin, + HellaswagMixin, + CustomTestCase, +): + served_model_name = DEFAULT_MODEL_NAME_FOR_TEST + # 5090 + Llama-3.1-8B single-batch decode with overlap scheduler + + # cuda graph measured ~99 median in CI; async-assert probes are off in + # base-a, so the threshold can sit right under the measured median. + # AMD also measures ~99 but with less headroom; keep ~1pp of margin + # there so small per-step changes don't flake the gate. + fwd_occupancy_threshold = 98.0 if is_hip() else 99.0 + + @classmethod + def setUpClass(cls): + cls.base_url = DEFAULT_URL_FOR_TEST + cls.process = popen_launch_server( + DEFAULT_MODEL_NAME_FOR_TEST, + cls.base_url, + timeout=DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH, + other_args=[ + "--cuda-graph-max-bs-decode", + "4", + "--mem-fraction-static", + "0.7", + "--enable-metrics", + ], + env={"SGLANG_ENABLE_METRICS_DEVICE_TIMER": "1"}, + ) + + @classmethod + def tearDownClass(cls): + kill_process_tree(cls.process.pid) + + +if __name__ == "__main__": + unittest.main() diff --git a/asian_ai/performance/SGLang/test/registered/core/test_basic_sanity_dflash.py b/asian_ai/performance/SGLang/test/registered/core/test_basic_sanity_dflash.py new file mode 100644 index 0000000000000000000000000000000000000000..e5d262401d27dd450d0eacb204b04ba968a2e820 --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/core/test_basic_sanity_dflash.py @@ -0,0 +1,82 @@ +"""Stage-a basic sanity with DFLASH spec decoding enabled. Mirrors +test_basic_sanity.py / test_basic_sanity_eagle3.py with the DFLASH path active +(overlap scheduling on by default).""" + +import unittest + +from sglang.srt.utils import kill_process_tree +from sglang.test.ci.ci_register import register_cuda_ci +from sglang.test.kits.basic_api_contract_kit import BasicAPIContractMixin +from sglang.test.kits.basic_decode_correctness_kit import BasicDecodeCorrectnessMixin +from sglang.test.kits.basic_scheduler_stress_kit import BasicSchedulerStressMixin +from sglang.test.kits.eval_accuracy_kit import GSM8KMixin +from sglang.test.kits.fwd_occupancy_kit import FwdOccupancyMixin +from sglang.test.test_utils import ( + DEFAULT_DRAFT_MODEL_DFLASH, + DEFAULT_TARGET_MODEL_DFLASH, + DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH, + DEFAULT_URL_FOR_TEST, + CustomTestCase, + popen_launch_server, +) + +register_cuda_ci(est_time=200, stage="base-a", runner_config="1-gpu-small") + + +class TestBasicSanityDFlash( + BasicAPIContractMixin, + BasicDecodeCorrectnessMixin, + BasicSchedulerStressMixin, + FwdOccupancyMixin, + GSM8KMixin, + CustomTestCase, +): + served_model_name = DEFAULT_TARGET_MODEL_DFLASH + fwd_occupancy_threshold = 97.5 + fwd_occupancy_max_new_tokens = 4096 + # DFLASH accepts a full block per verify, so its acc length runs well above + # EAGLE3's; keep a safe lower bound here. + fwd_occupancy_acc_length_threshold: float = 2.0 + + model = DEFAULT_TARGET_MODEL_DFLASH + gsm8k_num_questions = 1400 + gsm8k_accuracy_thres = 0.74 + gsm8k_accept_length_thres = 2.8 + + attention_backend = "triton" + draft_attention_backend = "triton" + + @classmethod + def setUpClass(cls): + cls.base_url = DEFAULT_URL_FOR_TEST + cls.process = popen_launch_server( + DEFAULT_TARGET_MODEL_DFLASH, + cls.base_url, + timeout=DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH, + other_args=[ + "--trust-remote-code", + "--attention-backend", + cls.attention_backend, + "--speculative-draft-attention-backend", + cls.draft_attention_backend, + "--speculative-algorithm", + "DFLASH", + "--speculative-draft-model-path", + DEFAULT_DRAFT_MODEL_DFLASH, + "--cuda-graph-max-bs", + "4", + "--mem-fraction-static", + "0.7", + "--enable-metrics", + "--disable-piecewise-cuda-graph", + ], + env={"SGLANG_ENABLE_METRICS_DEVICE_TIMER": "1"}, + ) + + @classmethod + def tearDownClass(cls): + kill_process_tree(cls.process.pid) + + +if __name__ == "__main__": + unittest.main() diff --git a/asian_ai/performance/SGLang/test/registered/core/test_basic_sanity_eagle3.py b/asian_ai/performance/SGLang/test/registered/core/test_basic_sanity_eagle3.py new file mode 100644 index 0000000000000000000000000000000000000000..8ff47333b71844d5485a311e7e906f44c4a2c4d6 --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/core/test_basic_sanity_eagle3.py @@ -0,0 +1,89 @@ +"""Stage-a basic sanity with EAGLE3 spec decoding enabled. Mirrors +test_basic_sanity.py with the spec-decoding path active.""" + +import unittest + +from sglang.srt.utils import kill_process_tree +from sglang.test.ci.ci_register import register_amd_ci, register_cuda_ci +from sglang.test.kits.basic_api_contract_kit import BasicAPIContractMixin +from sglang.test.kits.basic_decode_correctness_kit import BasicDecodeCorrectnessMixin +from sglang.test.kits.basic_scheduler_stress_kit import BasicSchedulerStressMixin +from sglang.test.kits.eval_accuracy_kit import GSM8KMixin +from sglang.test.kits.fwd_occupancy_kit import FwdOccupancyMixin +from sglang.test.test_utils import ( + DEFAULT_DRAFT_MODEL_EAGLE3, + DEFAULT_TARGET_MODEL_EAGLE3, + DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH, + DEFAULT_URL_FOR_TEST, + CustomTestCase, + is_in_amd_ci, + popen_launch_server, +) + +register_cuda_ci(est_time=200, stage="base-a", runner_config="1-gpu-small") +register_amd_ci(est_time=200, suite="stage-a-test-1-gpu-small-amd") + + +class TestBasicSanityEagle3( + BasicAPIContractMixin, + BasicDecodeCorrectnessMixin, + BasicSchedulerStressMixin, + FwdOccupancyMixin, + GSM8KMixin, + CustomTestCase, +): + served_model_name = DEFAULT_TARGET_MODEL_EAGLE3 + # CUDA 5090 + Llama-3.1-8B measured ~99 median in CI with async-assert + # probes off in base-a. AMD EAGLE3 currently sustains lower single-batch + # occupancy and needs a longer measurement window to avoid too few + # non-NaN samples. + fwd_occupancy_threshold = 80.0 if is_in_amd_ci() else 98.0 + fwd_occupancy_max_new_tokens = 4096 if is_in_amd_ci() else 2048 + fwd_occupancy_acc_length_threshold: float = 1.6 + + model = DEFAULT_TARGET_MODEL_EAGLE3 + gsm8k_num_questions = 1400 + gsm8k_accuracy_thres = 0.74 + + @classmethod + def setUpClass(cls): + cls.base_url = DEFAULT_URL_FOR_TEST + cls.process = popen_launch_server( + DEFAULT_TARGET_MODEL_EAGLE3, + cls.base_url, + timeout=DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH, + other_args=[ + # Canonical EAGLE3 sglang config: fp16 + triton attention. + # bf16 + flashinfer cutlass RMSNorm hits a SM120 dtype + # mismatch on the draft model's input_layernorm. + "--dtype", + "float16", + "--attention-backend", + "triton", + "--speculative-algorithm", + "EAGLE3", + "--speculative-draft-model-path", + DEFAULT_DRAFT_MODEL_EAGLE3, + "--speculative-num-steps", + "1", + "--speculative-eagle-topk", + "1", + "--speculative-num-draft-tokens", + "2", + "--cuda-graph-max-bs-decode", + "4", + "--mem-fraction-static", + "0.7", + "--enable-metrics", + "--disable-piecewise-cuda-graph", + ], + env={"SGLANG_ENABLE_METRICS_DEVICE_TIMER": "1"}, + ) + + @classmethod + def tearDownClass(cls): + kill_process_tree(cls.process.pid) + + +if __name__ == "__main__": + unittest.main() diff --git a/asian_ai/performance/SGLang/test/registered/core/test_engine_child_pids.py b/asian_ai/performance/SGLang/test/registered/core/test_engine_child_pids.py new file mode 100644 index 0000000000000000000000000000000000000000..460d9675bbfad5bae580cc2c23b44a4f532560db --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/core/test_engine_child_pids.py @@ -0,0 +1,80 @@ +""" +Unit tests for Engine.get_all_child_pids(). + +Verifies that launching an Engine exposes the PIDs of all child processes +(schedulers, detokenizer) and that those PIDs correspond to live processes. + +Usage: + python -m unittest test_engine_child_pids -v +""" + +import os +import unittest + +import psutil + +import sglang as sgl +from sglang.test.ci.ci_register import register_amd_ci, register_cuda_ci +from sglang.test.test_utils import ( + DEFAULT_SMALL_MODEL_NAME_FOR_TEST, + CustomTestCase, +) + +register_cuda_ci(est_time=77, stage="base-b", runner_config="1-gpu-small") +register_amd_ci(est_time=77, suite="stage-b-test-1-gpu-small-amd") + + +class TestEngineChildPids(CustomTestCase): + @classmethod + def setUpClass(cls): + cls.engine = sgl.Engine( + model_path=DEFAULT_SMALL_MODEL_NAME_FOR_TEST, + random_seed=42, + ) + + @classmethod + def tearDownClass(cls): + cls.engine.shutdown() + + def test_get_all_child_pids_returns_live_pids(self): + pids = self.engine.get_all_child_pids() + + self.assertIsInstance(pids, list) + self.assertGreater(len(pids), 0, "Expected at least one child PID") + + for pid in pids: + self.assertIsInstance(pid, int) + self.assertTrue( + psutil.pid_exists(pid), + f"PID {pid} does not correspond to a running process", + ) + + current_proc = psutil.Process(os.getpid()) + child_pids = {c.pid for c in current_proc.children(recursive=True)} + for pid in pids: + self.assertIn( + pid, + child_pids, + f"PID {pid} is not a child of the current process", + ) + + def test_child_pids_include_scheduler_and_detokenizer(self): + pids = self.engine.get_all_child_pids() + # dp_size=1 gives one scheduler + one detokenizer = at least 2 PIDs + self.assertGreaterEqual( + len(pids), + 2, + "Expected at least 2 child PIDs (scheduler + detokenizer)", + ) + + def test_child_pids_no_duplicates(self): + pids = self.engine.get_all_child_pids() + self.assertEqual( + len(pids), + len(set(pids)), + f"Duplicate PIDs found: {pids}", + ) + + +if __name__ == "__main__": + unittest.main() diff --git a/asian_ai/performance/SGLang/test/registered/core/test_hidden_states.py b/asian_ai/performance/SGLang/test/registered/core/test_hidden_states.py new file mode 100644 index 0000000000000000000000000000000000000000..c09bd47fb498635fe2d648ce5d58473c6398deb9 --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/core/test_hidden_states.py @@ -0,0 +1,143 @@ +import unittest + +import torch +from transformers import AutoModelForCausalLM, AutoTokenizer + +import sglang as sgl +from sglang.srt.utils import get_device, is_hip +from sglang.test.ci.ci_register import register_amd_ci, register_cuda_ci +from sglang.test.test_utils import DEFAULT_SMALL_MODEL_NAME_FOR_TEST, CustomTestCase + +register_cuda_ci(est_time=45, stage="base-b", runner_config="1-gpu-small") +register_amd_ci(est_time=55, suite="stage-b-test-1-gpu-small-amd") + +_is_hip = is_hip() +if _is_hip: + import os + + os.environ["SGLANG_USE_AITER"] = "0" + + +class TestHiddenState(CustomTestCase): + @classmethod + def setUpClass(cls): + cls.model_path = DEFAULT_SMALL_MODEL_NAME_FOR_TEST + cls.tokenizer = AutoTokenizer.from_pretrained(cls.model_path) + cls.prompts = ["Today is", "Today is a sunny day and I like"] + cls.input_ids = cls.tokenizer(cls.prompts).input_ids + cls.sampling_params = {"temperature": 0, "max_new_tokens": 8} + # mem_fraction_static=0.7 leaves headroom for the HF reference + # model that test_return_hidden_states loads on the same GPU. + cls.engine = sgl.Engine( + model_path=cls.model_path, + random_seed=42, + skip_tokenizer_init=True, + enable_return_hidden_states=True, + mem_fraction_static=0.7, + ) + + @classmethod + def tearDownClass(cls): + cls.engine.shutdown() + + def setUp(self): + # Tests share one Engine; flush radix cache so each test sees a + # cold prefill (test_return_hidden_states asserts on the prefill + # hidden-state shape, which collapses to 0 on a full cache hit). + self.engine.flush_cache() + + def test_return_hidden_states(self): + outputs = self.engine.generate( + input_ids=self.input_ids, + sampling_params=self.sampling_params, + return_hidden_states=True, + ) + + for output in outputs: + self.assertEqual(len(output["meta_info"]["hidden_states"]), 8) + for i in range(len(output["meta_info"]["hidden_states"])): + assert isinstance(output["meta_info"]["hidden_states"][i], list) + output["meta_info"]["hidden_states"][i] = torch.tensor( + output["meta_info"]["hidden_states"][i], dtype=torch.bfloat16 + ) + # Checks that splicing of the batch was done correctly + self.assertGreater( + outputs[1]["meta_info"]["hidden_states"][0].shape[0], + outputs[0]["meta_info"]["hidden_states"][0].shape[0], + ) + + model = AutoModelForCausalLM.from_pretrained( + self.model_path, torch_dtype=torch.bfloat16, device_map=get_device() + ) + + for input_id, output in zip(self.input_ids, outputs): + with torch.inference_mode(): + hf_out = model( + torch.tensor( + [input_id + output["output_ids"][:-1]], device=model.device + ), + output_hidden_states=True, + ) + print("=== HF Hiddens ===") + print(hf_out["hidden_states"][-1][0]) + sg_hidden_states = torch.cat( + [ + i.unsqueeze(0) if len(i.shape) == 1 else i + for i in output["meta_info"]["hidden_states"] + ] + ).to(get_device()) + print("=== SRT Hiddens ===") + print(sg_hidden_states) + + print( + f"Max diff: {torch.max(torch.abs(hf_out['hidden_states'][-1][0] - sg_hidden_states))}" + ) + + atol = 0.8 + self.assertTrue( + torch.allclose( + hf_out["hidden_states"][-1][0], + sg_hidden_states, + atol=atol, + rtol=0, + ) + ) + + def test_repeatedly_changes_hidden_states(self): + outputs_completion_first_round = self.engine.generate( + input_ids=self.input_ids, + sampling_params=self.sampling_params, + return_hidden_states=True, + ) + outputs_hidden_state = self.engine.generate( + input_ids=self.input_ids, + sampling_params=self.sampling_params, + return_hidden_states=False, + ) + + outputs_completion_last_round = self.engine.generate( + input_ids=self.input_ids, + sampling_params=self.sampling_params, + return_hidden_states=True, + ) + + for ( + output_completion_first_round, + output_hidden_state, + output_completion_last_round, + ) in zip( + outputs_completion_first_round, + outputs_hidden_state, + outputs_completion_last_round, + ): + self.assertEqual( + len(output_completion_first_round["meta_info"]["hidden_states"]), 8 + ) + self.assertNotIn("hidden_states", output_hidden_state["meta_info"]) + self.assertEqual( + len(output_completion_last_round["meta_info"]["hidden_states"]), 8 + ) + + +if __name__ == "__main__": + unittest.main() diff --git a/asian_ai/performance/SGLang/test/registered/core/test_no_extra_forked_cuda_context.py b/asian_ai/performance/SGLang/test/registered/core/test_no_extra_forked_cuda_context.py new file mode 100644 index 0000000000000000000000000000000000000000..d1a25728e83d620ea4f56b6cb412a3f285180c4a --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/core/test_no_extra_forked_cuda_context.py @@ -0,0 +1,139 @@ +import shutil +import subprocess +import time +import unittest + +import psutil + +from sglang.srt.utils import kill_process_tree +from sglang.test.ci.ci_register import register_cuda_ci +from sglang.test.test_utils import ( + DEFAULT_SMALL_MODEL_NAME_FOR_TEST, + DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH, + DEFAULT_URL_FOR_TEST, + CustomTestCase, + popen_launch_server, +) + +register_cuda_ci(est_time=120, stage="base-b", runner_config="2-gpu-large") + + +class TestTPServerGPUProcesses(CustomTestCase): + tp_size = 2 + + @classmethod + def setUpClass(cls): + cls.model = DEFAULT_SMALL_MODEL_NAME_FOR_TEST + cls.base_url = DEFAULT_URL_FOR_TEST + cls.process = popen_launch_server( + cls.model, + cls.base_url, + timeout=DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH, + other_args=[ + "--tp-size", + str(cls.tp_size), + "--mem-fraction-static", + "0.70", + "--cuda-graph-backend-decode", + "disabled", + "--cuda-graph-backend-prefill", + "disabled", + ], + ) + + @classmethod + def tearDownClass(cls): + if hasattr(cls, "process") and cls.process: + kill_process_tree(cls.process.pid) + + def test_tp_server_has_only_worker_gpu_processes(self): + if shutil.which("nvidia-smi") is None: + self.skipTest("nvidia-smi is required for GPU process assertions") + + rows = self._wait_for_server_gpu_processes() + gpu_pids = {row["pid"] for row in rows} + + self.assertNotIn( + self.process.pid, + gpu_pids, + f"server parent process unexpectedly holds a GPU context: " + f"{self._format_rows(rows)}", + ) + self.assertEqual( + len(gpu_pids), + self.tp_size, + f"TP={self.tp_size} server should have exactly {self.tp_size} " + f"GPU worker processes, got {len(gpu_pids)}: {self._format_rows(rows)}", + ) + + def _wait_for_server_gpu_processes(self): + deadline = time.monotonic() + 60 + stable_since = None + last_rows = [] + + while time.monotonic() < deadline: + tree_pids = self._server_process_tree_pids() + rows = [ + row for row in self._query_gpu_processes() if row["pid"] in tree_pids + ] + last_rows = rows + + if len({row["pid"] for row in rows}) >= self.tp_size: + if stable_since is None: + stable_since = time.monotonic() + elif time.monotonic() - stable_since >= 3: + return rows + else: + stable_since = None + + time.sleep(0.5) + + self.fail( + f"Timed out waiting for TP={self.tp_size} GPU worker processes. " + f"Last observed rows: {self._format_rows(last_rows)}" + ) + + def _server_process_tree_pids(self): + pids = {self.process.pid} + try: + parent = psutil.Process(self.process.pid) + pids.update(child.pid for child in parent.children(recursive=True)) + except psutil.NoSuchProcess: + pass + return pids + + def _query_gpu_processes(self): + result = subprocess.run( + [ + "nvidia-smi", + "--query-compute-apps=gpu_uuid,pid,process_name", + "--format=csv,noheader,nounits", + ], + check=True, + capture_output=True, + text=True, + ) + + rows = [] + for line in result.stdout.splitlines(): + fields = [field.strip() for field in line.split(",", maxsplit=2)] + if len(fields) != 3: + continue + gpu_uuid, pid, process_name = fields + rows.append( + { + "gpu_uuid": gpu_uuid, + "pid": int(pid), + "process_name": process_name, + } + ) + return rows + + def _format_rows(self, rows): + if not rows: + return "[]" + return "[" + ", ".join(str(row) for row in rows) + "]" + + +if __name__ == "__main__": + unittest.main() diff --git a/asian_ai/performance/SGLang/test/registered/core/test_request_queue_validation.py b/asian_ai/performance/SGLang/test/registered/core/test_request_queue_validation.py new file mode 100644 index 0000000000000000000000000000000000000000..72a52aff318cbd9b5b54b89eed9e61663cff9776 --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/core/test_request_queue_validation.py @@ -0,0 +1,92 @@ +import asyncio +import os +import re +import unittest + +from sglang.srt.utils import kill_process_tree +from sglang.test.ci.ci_register import register_amd_ci, register_cuda_ci +from sglang.test.test_utils import ( + DEFAULT_SMALL_MODEL_NAME_FOR_TEST, + DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH, + DEFAULT_URL_FOR_TEST, + STDERR_FILENAME, + STDOUT_FILENAME, + CustomTestCase, + popen_launch_server, + send_concurrent_generate_requests, + send_generate_requests, +) + +register_cuda_ci(est_time=53, stage="base-b", runner_config="1-gpu-small") +register_amd_ci(est_time=70, suite="stage-b-test-1-gpu-small-amd") + + +class TestMaxQueuedRequests(CustomTestCase): + @classmethod + def setUpClass(cls): + cls.model = DEFAULT_SMALL_MODEL_NAME_FOR_TEST + cls.base_url = DEFAULT_URL_FOR_TEST + + cls.stdout = open(STDOUT_FILENAME, "w") + cls.stderr = open(STDERR_FILENAME, "w") + + cls.base_url = DEFAULT_URL_FOR_TEST + cls.process = popen_launch_server( + cls.model, + cls.base_url, + timeout=DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH, + other_args=( + "--max-running-requests", # Enforce max request concurrency is 1 + "1", + "--max-queued-requests", # Enforce max queued request number is 1 + "1", + "--attention-backend", + "triton", + ), + return_stdout_stderr=(cls.stdout, cls.stderr), + ) + + @classmethod + def tearDownClass(cls): + kill_process_tree(cls.process.pid) + cls.stdout.close() + cls.stderr.close() + os.remove(STDOUT_FILENAME) + os.remove(STDERR_FILENAME) + + def test_max_queued_requests_validation_with_serial_requests(self): + """Verify request is not throttled when the max concurrency is 1.""" + status_codes = send_generate_requests( + self.base_url, + num_requests=10, + ) + + for status_code in status_codes: + assert status_code == 200 # request shouldn't be throttled + + def test_max_queued_requests_validation_with_concurrent_requests(self): + """Verify request throttling with concurrent requests.""" + status_codes = asyncio.run( + send_concurrent_generate_requests(self.base_url, num_requests=10) + ) + self.assertLessEqual(status_codes.count(200), 2) + + # expected_status_codes = [200, 200, 503, 503, 503, 503, 503, 503, 503, 503] + # self.assertEqual(status_codes, expected_status_codes) + + def test_max_running_requests_and_max_queued_request_validation(self): + """Verify running request and queued request numbers based on server logs.""" + rr_pattern = re.compile(r"#running-req:\s*(\d+)") + qr_pattern = re.compile(r"#queue-req:\s*(\d+)") + + with open(STDERR_FILENAME) as lines: + for line in lines: + rr_match, qr_match = rr_pattern.search(line), qr_pattern.search(line) + if rr_match: + assert int(rr_match.group(1)) <= 1 + if qr_match: + assert int(qr_match.group(1)) <= 1 + + +if __name__ == "__main__": + unittest.main() diff --git a/asian_ai/performance/SGLang/test/registered/core/test_srt_endpoint.py b/asian_ai/performance/SGLang/test/registered/core/test_srt_endpoint.py new file mode 100644 index 0000000000000000000000000000000000000000..1f7a415176b308a46c9348de537586a17e03a4ac --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/core/test_srt_endpoint.py @@ -0,0 +1,804 @@ +""" +python3 -m unittest test_srt_endpoint.TestSRTEndpoint.test_simple_decode +python3 -m unittest test_srt_endpoint.TestSRTEndpoint.test_logprob_with_chunked_prefill +python3 -m unittest test_srt_endpoint.TestTokenizeDetokenize +""" + +import json +import random +import time +import unittest +from concurrent.futures import ThreadPoolExecutor +from functools import partial +from typing import Optional + +import numpy as np +import requests + +from sglang.srt.sampling.custom_logit_processor import CustomLogitProcessor +from sglang.srt.utils import kill_process_tree +from sglang.srt.utils.hf_transformers_utils import get_tokenizer +from sglang.test.ci.ci_register import register_amd_ci, register_cuda_ci +from sglang.test.test_utils import ( + DEFAULT_SMALL_MODEL_NAME_FOR_TEST, + DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH, + DEFAULT_URL_FOR_TEST, + CustomTestCase, + popen_launch_server, + run_logprob_check, +) + +register_cuda_ci(est_time=134, stage="base-b", runner_config="1-gpu-small") +register_amd_ci(est_time=130, suite="stage-b-test-1-gpu-small-amd") + +SERVER_ENV = {"SGLANG_USE_PICKLE_IPC": "0"} + + +class TestSRTEndpoint(CustomTestCase): + @classmethod + def setUpClass(cls): + cls.model = DEFAULT_SMALL_MODEL_NAME_FOR_TEST + cls.base_url = DEFAULT_URL_FOR_TEST + cls.process = popen_launch_server( + cls.model, + cls.base_url, + timeout=DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH, + env=SERVER_ENV, + other_args=( + "--enable-custom-logit-processor", + "--mem-fraction-static", + "0.7", + "--cuda-graph-max-bs-decode", + "8", + ), + ) + + @classmethod + def tearDownClass(cls): + kill_process_tree(cls.process.pid) + + def run_decode( + self, + return_logprob=False, + top_logprobs_num=0, + return_text=False, + n=1, + stream=False, + batch=False, + ): + if batch: + text = ["The capital of France is"] + else: + text = "The capital of France is" + + response = requests.post( + self.base_url + "/generate", + json={ + "text": text, + "sampling_params": { + "temperature": 0 if n == 1 else 0.5, + "max_new_tokens": 16, + "n": n, + }, + "stream": stream, + "return_logprob": return_logprob, + "top_logprobs_num": top_logprobs_num, + "return_text_in_logprobs": return_text, + "logprob_start_len": 0, + }, + ) + if not stream: + response_json = response.json() + else: + response_json = [] + for line in response.iter_lines(): + if line.startswith(b"data: ") and line[6:] != b"[DONE]": + response_json.append(json.loads(line[6:])) + + print(json.dumps(response_json, indent=2)) + print("=" * 100) + + def test_logprob(self): + self.run_decode( + return_logprob=True, + top_logprobs_num=5, + return_text=True, + ) + + def test_logprob_start_len(self): + logprob_start_len = 4 + new_tokens = 4 + prompts = [ + "I have a very good idea on", + "Today is a sunndy day and", + ] + + response = requests.post( + self.base_url + "/generate", + json={ + "text": prompts, + "sampling_params": { + "temperature": 0, + "max_new_tokens": new_tokens, + }, + "return_logprob": True, + "top_logprobs_num": 5, + "return_text_in_logprobs": True, + "logprob_start_len": logprob_start_len, + }, + ) + response_json = response.json() + print(json.dumps(response_json, indent=2)) + + for i, res in enumerate(response_json): + self.assertEqual( + res["meta_info"]["prompt_tokens"], + logprob_start_len + len(res["meta_info"]["input_token_logprobs"]), + ) + assert prompts[i].endswith( + "".join([x[-1] for x in res["meta_info"]["input_token_logprobs"]]) + ) + + self.assertEqual(res["meta_info"]["completion_tokens"], new_tokens) + self.assertEqual(len(res["meta_info"]["output_token_logprobs"]), new_tokens) + self.assertEqual( + res["text"], + "".join([x[-1] for x in res["meta_info"]["output_token_logprobs"]]), + ) + + def test_logprob_with_chunked_prefill(self): + """Test a long prompt that requests output logprobs will not hit OOM.""" + new_tokens = 4 + prompts = "I have a very good idea on this. " * 8000 + + response = requests.post( + self.base_url + "/generate", + json={ + "text": prompts, + "sampling_params": { + "temperature": 0, + "max_new_tokens": new_tokens, + }, + "return_logprob": True, + "logprob_start_len": -1, + "top_logprobs_num": 5, + }, + ) + response_json = response.json() + # print(json.dumps(response_json, indent=2)) + + res = response_json + self.assertEqual(res["meta_info"]["completion_tokens"], new_tokens) + + # Test the number of tokens are correct + self.assertEqual(len(res["meta_info"]["output_token_logprobs"]), new_tokens) + self.assertEqual(len(res["meta_info"]["output_top_logprobs"]), new_tokens) + + # Test the top-1 tokens are the same as output tokens (because temp = 0.0) + for i in range(new_tokens): + self.assertListEqual( + res["meta_info"]["output_token_logprobs"][i], + res["meta_info"]["output_top_logprobs"][i][0], + ) + self.assertEqual(len(res["meta_info"]["output_top_logprobs"][i]), 5) + + def test_logprob_match(self): + """Test the output logprobs are close to the input logprobs if we run a prefill again.""" + + def run_generate( + prompt, return_logprob=False, max_new_tokens=512, logprob_start_len=-1 + ): + + if isinstance(prompt, str): + prompt_kwargs = {"text": prompt} + else: + prompt_kwargs = {"input_ids": prompt} + + response = requests.post( + self.base_url + "/generate", + json={ + **prompt_kwargs, + "sampling_params": { + "temperature": 1.0, + "max_new_tokens": max_new_tokens, + "ignore_eos": True, + }, + "return_logprob": return_logprob, + "return_text_in_logprobs": True, + "logprob_start_len": logprob_start_len, + }, + ) + return response.json() + + prompt = "I have a very good idea on how to" + + gen = run_generate(prompt, return_logprob=True, logprob_start_len=0) + output_logprobs = np.array( + [x[0] for x in gen["meta_info"]["output_token_logprobs"]] + ) + num_prompts_tokens = gen["meta_info"]["prompt_tokens"] + + input_tokens = [x[1] for x in gen["meta_info"]["input_token_logprobs"]] + output_tokens = [x[1] for x in gen["meta_info"]["output_token_logprobs"]] + + new_prompt = input_tokens + output_tokens + score = run_generate( + new_prompt, return_logprob=True, logprob_start_len=0, max_new_tokens=0 + ) + output_logprobs_score = np.array( + [ + x[0] + for x in score["meta_info"]["input_token_logprobs"][num_prompts_tokens:] + ] + ) + + print(f"{output_logprobs[-10:]=}") + print(f"{output_logprobs_score[-10:]=}") + + diff = np.abs(output_logprobs - output_logprobs_score) + max_diff = np.max(diff) + self.assertLess(max_diff, 0.35) + + def test_logprob_mixed(self): + args = [] + temperature = 0 + # input_len, output_len, temperature, logprob_start_len, return_logprob, top_logprobs_num + for input_len in [1000, 5000, 10000, 50000]: + for output_len in [4, 8]: + for logprob_start_len in [0, 500, 2500, 5000, 25000]: + for return_logprob in [True, False]: + for top_logprobs_num in [0, 5]: + + if logprob_start_len >= input_len: + continue + + args.append( + ( + input_len, + output_len, + temperature, + logprob_start_len, + return_logprob, + top_logprobs_num, + ) + ) + + random.shuffle(args) + + func = partial(run_logprob_check, self) + with ThreadPoolExecutor(8) as executor: + list(executor.map(func, args)) + + def test_logprob_grammar(self): + prompts = "Question: Is Paris the Capital of France? Answer:" + allowed_tokens = [" Yes", " No"] + + response = requests.post( + self.base_url + "/generate", + json={ + "text": prompts, + "sampling_params": { + "temperature": 1.0, + "max_new_tokens": 1, + "regex": "( Yes| No)", + }, + "return_logprob": True, + "top_logprobs_num": 5, # The grammar constraint allows all prefix tokens so we need to use a larger top_k. + "return_text_in_logprobs": True, + }, + ) + response_json = response.json() + output_top_logprobs = response_json["meta_info"]["output_top_logprobs"][0] + print(f"{output_top_logprobs=}") + + # Parse results + # This is because the grammar constraint allows all prefix tokens + logprobs = [None] * 2 + for i in range(len(output_top_logprobs)): + try: + idx = allowed_tokens.index(output_top_logprobs[i][2]) + except ValueError: + # Not found + continue + logprobs[idx] = output_top_logprobs[i][0] + + self.assertTrue(all(x is not None for x in logprobs)) + + def run_custom_logit_processor(self, target_token_id: Optional[int] = None): + """Test custom logit processor with custom params. + + If target_token_id is None, the custom logit processor won't be passed in. + """ + + custom_params = {"token_id": target_token_id} + + class DeterministicLogitProcessor(CustomLogitProcessor): + """A dummy logit processor that changes the logits to always + sample the given token id. + """ + + def __call__(self, logits, custom_param_list): + assert logits.shape[0] == len(custom_param_list) + key = "token_id" + + for i, param_dict in enumerate(custom_param_list): + # Mask all other tokens + logits[i, :] = -float("inf") + # Assign highest probability to the specified token + logits[i, param_dict[key]] = 0.0 + return logits + + prompts = "Question: Is Paris the Capital of France? Answer:" + + # Base case json data to be posted to the server. + base_json = { + "text": prompts, + "sampling_params": {"temperature": 0.0}, + "return_logprob": True, + } + + # Custom json data with custom logit processor and params. + custom_json = base_json.copy() + # Only set the custom logit processor if target_token_id is not None. + if target_token_id is not None: + custom_json["custom_logit_processor"] = DeterministicLogitProcessor.to_str() + custom_json["sampling_params"]["custom_params"] = custom_params + + custom_response = requests.post( + self.base_url + "/generate", + json=custom_json, + ).json() + + output_token_logprobs = custom_response["meta_info"]["output_token_logprobs"] + sampled_tokens = [x[1] for x in output_token_logprobs] + + # The logit processor should always sample the given token as the logits is deterministic. + if target_token_id is not None: + self.assertTrue( + all(x == custom_params["token_id"] for x in sampled_tokens), + # Print the detailed test case info if the test fails. + f"{target_token_id=}\n{sampled_tokens=}\n{custom_response=}", + ) + + def run_stateful_custom_logit_processor( + self, first_token_id: int | None, delay: int = 2 + ): + """Test custom logit processor with custom params and state. + + Should sample the first `delay` tokens normally, then output first_token_id and consecutive tokens after that. + If first_token_id is None, the custom logit processor won't be passed in. + """ + custom_params = {"token_id": first_token_id, "delay": 2} + + class DeterministicStatefulLogitProcessor(CustomLogitProcessor): + """A dummy logit processor that changes the logits to always + sample the given token id. + """ + + def __call__(self, logits, custom_param_list): + assert logits.shape[0] == len(custom_param_list) + + for i, param_dict in enumerate(custom_param_list): + if param_dict["delay"] > 0: + param_dict["delay"] -= 1 + continue + if param_dict["delay"] == 0: + param_dict["delay"] -= 1 + force_token = param_dict["token_id"] + else: + output_ids = param_dict["__req__"].output_ids + force_token = output_ids[-1] + 1 + # Mask all other tokens + logits[i, :] = -float("inf") + # Assign highest probability to the specified token + logits[i, force_token] = 0.0 + return logits + + prompts = "Question: Is Paris the Capital of France? Answer:" + + # Base case json data to be posted to the server. + base_json = { + "text": prompts, + "sampling_params": {"temperature": 0.0}, + "return_logprob": True, + } + + # Custom json data with custom logit processor and params. + custom_json = base_json.copy() + # Only set the custom logit processor if target_token_id is not None. + if first_token_id is not None: + custom_json["custom_logit_processor"] = ( + DeterministicStatefulLogitProcessor().to_str() + ) + custom_json["sampling_params"]["custom_params"] = custom_params + + custom_response = requests.post( + self.base_url + "/generate", + json=custom_json, + ).json() + + output_token_logprobs = custom_response["meta_info"]["output_token_logprobs"] + sampled_tokens = [x[1] for x in output_token_logprobs] + # The logit processor should always sample the given token as the logits is deterministic. + if first_token_id is not None: + self.assertTrue( + all( + x == custom_params["token_id"] + k + for k, x in enumerate(sampled_tokens[custom_params["delay"] :]) + ), + # Print the detailed test case info if the test fails. + f"{first_token_id=}\n{sampled_tokens=}\n{custom_response=}", + ) + + def test_custom_logit_processor(self): + """Test custom logit processor with a single request.""" + self.run_custom_logit_processor(target_token_id=5) + + def test_custom_logit_processor_batch_mixed(self): + """Test a batch of requests mixed of requests with and without custom logit processor.""" + target_token_ids = list(range(32)) + [None] * 16 + random.shuffle(target_token_ids) + with ThreadPoolExecutor(len(target_token_ids)) as executor: + list(executor.map(self.run_custom_logit_processor, target_token_ids)) + + @unittest.skip("Skip this test because this feature has a bug. See comments below.") + def test_stateful_custom_logit_processor(self): + """Test custom logit processor with a single request.""" + + """ + NOTE: This feature has a race condition bug. + This line https://github.com/sgl-project/sglang/blob/ef8ec07b2ce4c70c2a33ec5acda4ce529bc3cda4/test/srt/test_srt_endpoint.py#L395-L396 can be accessed by two concurrent threads at the same time. The access order is not guaranteed. + In sglang, we use two python threads to overlap the GPU computation and CPU scheduling. + Thread 1 (the CPU scheduling thread) will update the `param_dict["__req__"].output_ids`. + Thread 2 (the GPU computation thread) will call `DeterministicStatefulLogitProcessor` because sampling is considered as GPU computation. + We can fix this by moving the call of DeterministicStatefulLogitProcessor to the CPU scheduling thread. + """ + + self.run_stateful_custom_logit_processor(first_token_id=5) + + @unittest.skip("Skip this test because this feature has a bug. See comments above.") + def test_stateful_custom_logit_processor_batch_mixed(self): + """Test a batch of requests mixed of requests with and without custom logit processor.""" + target_token_ids = list(range(32)) + [None] * 16 + random.shuffle(target_token_ids) + with ThreadPoolExecutor(len(target_token_ids)) as executor: + list( + executor.map(self.run_stateful_custom_logit_processor, target_token_ids) + ) + + def test_cache_tokens(self): + for _ in range(2): + time.sleep(1) + response = requests.post(self.base_url + "/flush_cache") + assert response.status_code == 200 + + server_info = requests.get(self.base_url + "/server_info").json() + page_size = server_info.get("page_size") or 1 + + def align_down(num_tokens): + return num_tokens // page_size * page_size + + def send_and_check_cached_tokens(input_ids): + response = requests.post( + self.base_url + "/generate", + json={ + "input_ids": list(input_ids), + "sampling_params": { + "max_new_tokens": 1, + }, + }, + ) + response_json = response.json() + return response_json["meta_info"]["cached_tokens"] + + self.assertEqual(send_and_check_cached_tokens(range(0, 100)), 0) + self.assertEqual(send_and_check_cached_tokens(range(0, 10000)), align_down(100)) + self.assertEqual( + send_and_check_cached_tokens(range(0, 10000)), align_down(9999) + ) + self.assertEqual(send_and_check_cached_tokens(range(0, 1000)), align_down(999)) + self.assertEqual( + send_and_check_cached_tokens(range(0, 11000)), align_down(10000) + ) + + def test_get_server_info(self): + response = requests.get(self.base_url + "/server_info") + response_json = response.json() + + max_total_num_tokens = response_json["max_total_num_tokens"] + self.assertIsInstance(max_total_num_tokens, int) + + version = response_json["version"] + self.assertIsInstance(version, str) + + def test_logit_bias(self): + """Test that a very high logit bias forces sampling of a specific token.""" + # Choose a token ID to bias (using 5 as an example) + target_token_id = 60704 # Paris for meta-llama/Llama-3.2-1B-Instruct, DEFAULT_SMALL_MODEL_NAME_FOR_TEST + logit_bias = {str(target_token_id): 100.0} # Very high positive bias + + response = requests.post( + self.base_url + "/generate", + json={ + "text": "The capital of France is", + "sampling_params": { + "temperature": 1.0, # Use high temperature to encourage exploration + "max_new_tokens": 4, + "logit_bias": logit_bias, + }, + "return_logprob": True, + }, + ) + response_json = response.json() + + # Extract the sampled token IDs from the output + output_token_logprobs = response_json["meta_info"]["output_token_logprobs"] + sampled_tokens = [x[1] for x in output_token_logprobs] + + # Verify that all sampled tokens are the target token + self.assertTrue( + all(x == target_token_id for x in sampled_tokens), + f"Expected all tokens to be {target_token_id}, but got {sampled_tokens}", + ) + + def test_forbidden_token(self): + """Test that a forbidden token (very negative logit bias) doesn't appear in the output.""" + # Choose a token ID to forbid (using 10 as an example) + forbidden_token_id = 23994 # rice for meta-llama/Llama-3.2-1B-Instruct, DEFAULT_SMALL_MODEL_NAME_FOR_TEST + logit_bias = { + str(forbidden_token_id): -100.0 + } # Very negative bias to forbid the token + + response = requests.post( + self.base_url + "/generate", + json={ + "text": "Only output 'rice' exactly like this, in lowercase ONLY: rice", + "sampling_params": { + "temperature": 1.0, # Use high temperature to encourage diverse output + "max_new_tokens": 50, # Generate enough tokens to likely include numbers + "logit_bias": logit_bias, + }, + "return_logprob": True, + }, + ) + response_json = response.json() + + # Extract the sampled token IDs from the output + output_token_logprobs = response_json["meta_info"]["output_token_logprobs"] + sampled_tokens = [x[1] for x in output_token_logprobs] + + # Verify that the forbidden token doesn't appear in the output + self.assertNotIn( + forbidden_token_id, + sampled_tokens, + f"Expected forbidden token {forbidden_token_id} not to be present, but it was found", + ) + + def test_logit_bias_isolation(self): + """Test that logit_bias applied to one request doesn't affect other requests in batch.""" + # Choose a token ID to bias in first request only + biased_token_id = 60704 # Paris for meta-llama/Llama-3.2-1B-Instruct, DEFAULT_SMALL_MODEL_NAME_FOR_TEST + + # Prepare batch requests - one with logit_bias and one without + requests_data = [ + { + "text": "The capital of France is", + "sampling_params": { + "temperature": 1.0, + "max_new_tokens": 4, + "logit_bias": {str(biased_token_id): 100.0}, # Strong bias + }, + "return_logprob": True, + }, + { + "text": "The capital of France is", + "sampling_params": { + "temperature": 1.0, + "max_new_tokens": 4, + }, + "return_logprob": True, + }, + ] + + # Send both requests + responses = [] + for req in requests_data: + response = requests.post(self.base_url + "/generate", json=req) + responses.append(response.json()) + + # Extract token IDs from each response + biased_tokens = [ + x[1] for x in responses[0]["meta_info"]["output_token_logprobs"] + ] + unbiased_tokens = [ + x[1] for x in responses[1]["meta_info"]["output_token_logprobs"] + ] + + # Verify first response contains only biased tokens + self.assertTrue( + all(x == biased_token_id for x in biased_tokens), + f"Expected all tokens to be {biased_token_id} in first response, but got {biased_tokens}", + ) + + # Verify second response contains at least some different tokens + # (We can't guarantee exactly what tokens will be generated, but they shouldn't all be the biased token) + self.assertTrue( + any(x != biased_token_id for x in unbiased_tokens), + f"Expected some tokens to be different from {biased_token_id} in second response, but got {unbiased_tokens}", + ) + + def test_get_server_info_concurrent(self): + """Make sure the concurrent get_server_info doesn't crash the server.""" + tp = ThreadPoolExecutor(max_workers=30) + + def s(): + server_info = requests.get(self.base_url + "/server_info") + server_info.json() + + futures = [] + for _ in range(4): + futures.append(tp.submit(s)) + + for f in futures: + f.result() + + +# ------------------------------------------------------------------------- +# /tokenize, /v1/tokenize & /detokenize Test Class: TestTokenizeDetokenize +# ------------------------------------------------------------------------- + + +class TestTokenizeDetokenize(CustomTestCase): + @classmethod + def setUpClass(cls): + cls.model = DEFAULT_SMALL_MODEL_NAME_FOR_TEST + cls.base_url = DEFAULT_URL_FOR_TEST + cls.tokenize_url = f"{cls.base_url}/tokenize" + cls.openai_tokenize_url = f"{cls.base_url}/v1/tokenize" + cls.detokenize_url = f"{cls.base_url}/detokenize" + cls.session = requests.Session() + cls.process = popen_launch_server( + cls.model, + cls.base_url, + timeout=DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH, + env=SERVER_ENV, + ) + cls.tokenizer = get_tokenizer(cls.model) + + @classmethod + def tearDownClass(cls): + kill_process_tree(cls.process.pid) + cls.session.close() + + def _post_json(self, url, payload): + r = self.session.post(url, json=payload) + r.raise_for_status() + return r.json() + + def test_tokenize_various_inputs(self): + single = "Hello SGLang world! 123 😊, ಪರ್ವತದ ಮೇಲೆ ಹಿಮ." + multi = ["First sentence.", "Second, with 中文."] + scenarios = [ + {"prompt": single, "add_special_tokens": True}, + {"prompt": single, "add_special_tokens": False}, + {"prompt": multi, "add_special_tokens": True}, + {"prompt": multi, "add_special_tokens": False}, + {"prompt": "", "add_special_tokens": False}, + ] + for case in scenarios: + payload = {"model": self.model, "prompt": case["prompt"]} + if "add_special_tokens" in case: + payload["add_special_tokens"] = case["add_special_tokens"] + resp = self._post_json(self.tokenize_url, payload) + tokens = resp["tokens"] + count = resp["count"] + self.assertIsInstance(tokens, list) + if not tokens: + self.assertEqual(count, 0) + else: + if isinstance(tokens[0], list): + total = sum(len(t) for t in tokens) + expected = sum(count) if isinstance(count, list) else count + else: + total = len(tokens) + expected = count + self.assertEqual(total, expected) + + def test_tokenize_invalid_type(self): + r = self.session.post( + self.tokenize_url, json={"model": self.model, "prompt": 12345} + ) + self.assertEqual(r.status_code, 400) + + def test_openai_tokenize_chat_messages(self): + messages = [{"role": "user", "content": "What is the weather in Paris?"}] + resp = self._post_json( + self.openai_tokenize_url, + {"model": self.model, "messages": messages}, + ) + expected_tokens = self.tokenizer.apply_chat_template( + messages, + tokenize=True, + add_generation_prompt=True, + ) + if not isinstance(expected_tokens, list): + expected_tokens = expected_tokens["input_ids"] + if hasattr(expected_tokens, "tolist"): + expected_tokens = expected_tokens.tolist() + self.assertEqual(resp["tokens"], expected_tokens) + self.assertEqual(resp["count"], len(expected_tokens)) + + tools = [ + { + "type": "function", + "function": { + "name": "get_weather", + "description": "Get weather for a city.", + "parameters": { + "type": "object", + "properties": {"city": {"type": "string"}}, + "required": ["city"], + }, + }, + } + ] + tools_resp = self._post_json( + self.openai_tokenize_url, + {"model": self.model, "messages": messages, "tools": tools}, + ) + self.assertIsInstance(tools_resp["tokens"], list) + self.assertEqual(tools_resp["count"], len(tools_resp["tokens"])) + self.assertNotEqual(tools_resp["tokens"], resp["tokens"]) + + no_tools_resp = self._post_json( + self.openai_tokenize_url, + { + "model": self.model, + "messages": messages, + "tools": tools, + "tool_choice": "none", + }, + ) + self.assertEqual(no_tools_resp["tokens"], resp["tokens"]) + self.assertEqual(no_tools_resp["count"], resp["count"]) + + def test_detokenize_roundtrip(self): + text = "Verify detokenization round trip. यह डिटोकेनाइजेशन है" + t0 = self._post_json( + self.tokenize_url, + {"model": self.model, "prompt": text, "add_special_tokens": False}, + )["tokens"] + t1 = self._post_json( + self.tokenize_url, + {"model": self.model, "prompt": text, "add_special_tokens": True}, + )["tokens"] + cases = [ + {"tokens": t0, "skip_special_tokens": True, "expected": text}, + {"tokens": t1, "skip_special_tokens": True, "expected": text}, + {"tokens": t1, "skip_special_tokens": False, "expected": None}, + {"tokens": [], "skip_special_tokens": True, "expected": ""}, + ] + for case in cases: + payload = {"model": self.model, "tokens": case["tokens"]} + if "skip_special_tokens" in case: + payload["skip_special_tokens"] = case["skip_special_tokens"] + resp = self._post_json(self.detokenize_url, payload) + text_out = resp["text"] + if case["expected"] is not None: + self.assertEqual(text_out, case["expected"]) + else: + self.assertIsInstance(text_out, str) + + def test_detokenize_invalid_tokens(self): + r = self.session.post( + self.detokenize_url, json={"model": self.model, "tokens": ["a", "b"]} + ) + self.assertEqual(r.status_code, 400) + r2 = self.session.post( + self.detokenize_url, json={"model": self.model, "tokens": [1, -1, 2]} + ) + self.assertEqual(r2.status_code, 500) + + +if __name__ == "__main__": + unittest.main() diff --git a/asian_ai/performance/SGLang/test/registered/core/test_srt_engine.py b/asian_ai/performance/SGLang/test/registered/core/test_srt_engine.py new file mode 100644 index 0000000000000000000000000000000000000000..ce829cebc1d52fe5ca7627e8e8910881261e6cde --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/core/test_srt_engine.py @@ -0,0 +1,159 @@ +""" +Usage: +python3 -m unittest test_srt_engine.TestSRTEngine.test_4_sync_async_stream_combination +""" + +import asyncio +import json +import unittest + +import torch + +import sglang as sgl +from sglang.benchmark.offline_throughput import BenchArgs, throughput_test +from sglang.srt.server_args import ServerArgs +from sglang.srt.utils.hf_transformers_utils import get_tokenizer +from sglang.test.ci.ci_register import register_amd_ci, register_cuda_ci +from sglang.test.test_utils import ( + DEFAULT_SMALL_EMBEDDING_MODEL_NAME_FOR_TEST, + DEFAULT_SMALL_MODEL_NAME_FOR_TEST, + CustomTestCase, +) + +register_cuda_ci(est_time=387, stage="base-b", runner_config="1-gpu-large") +register_amd_ci(est_time=261, suite="stage-b-test-1-gpu-small-amd") + + +class TestSRTEngine(CustomTestCase): + + def test_1_engine_runtime_consistency(self): + prompt = "Today is a sunny day and I like" + model_path = DEFAULT_SMALL_MODEL_NAME_FOR_TEST + + sampling_params = {"temperature": 0, "max_new_tokens": 8} + + engine = sgl.Engine(model_path=model_path, random_seed=42) + out1 = engine.generate(prompt, sampling_params)["text"] + engine.shutdown() + + runtime = sgl.Runtime(model_path=model_path, random_seed=42) + out2 = json.loads(runtime.generate(prompt, sampling_params))["text"] + runtime.shutdown() + + print("==== Answer 1 ====") + print(out1) + + print("==== Answer 2 ====") + print(out2) + self.assertEqual(out1, out2) + + def test_2_engine_runtime_encode_consistency(self): + prompt = "Today is a sunny day and I like" + model_path = DEFAULT_SMALL_EMBEDDING_MODEL_NAME_FOR_TEST + + engine = sgl.Engine(model_path=model_path, is_embedding=True, random_seed=42) + out1 = torch.tensor(engine.encode(prompt)["embedding"]) + engine.shutdown() + + runtime = sgl.Runtime(model_path=model_path, is_embedding=True, random_seed=42) + out2 = torch.tensor(json.loads(runtime.encode(prompt))["embedding"]) + runtime.shutdown() + + self.assertTrue(torch.allclose(out1, out2, atol=1e-5, rtol=1e-3)) + + def test_3_engine_token_ids_consistency(self): + # just to ensure there is no issue running multiple generate calls + prompt = "Today is a sunny day and I like" + model_path = DEFAULT_SMALL_MODEL_NAME_FOR_TEST + sampling_params = {"temperature": 0, "max_new_tokens": 8} + + engine = sgl.Engine( + model_path=model_path, random_seed=42, disable_radix_cache=True + ) + out1 = engine.generate(prompt, sampling_params)["text"] + + tokenizer = get_tokenizer(model_path) + token_ids = tokenizer.encode(prompt) + out2 = engine.generate(input_ids=token_ids, sampling_params=sampling_params)[ + "text" + ] + + engine.shutdown() + + print("==== Answer 1 ====") + print(out1) + + print("==== Answer 2 ====") + print(out2) + self.assertEqual(out1, out2) + + def test_6_engine_cpu_offload(self): + prompt = "Today is a sunny day and I like" + model_path = DEFAULT_SMALL_MODEL_NAME_FOR_TEST + + sampling_params = {"temperature": 0, "max_new_tokens": 8} + + engine = sgl.Engine( + model_path=model_path, + random_seed=42, + max_total_tokens=128, + ) + out1 = engine.generate(prompt, sampling_params)["text"] + engine.shutdown() + + engine = sgl.Engine( + model_path=model_path, + random_seed=42, + max_total_tokens=128, + cpu_offload_gb=3, + ) + out2 = engine.generate(prompt, sampling_params)["text"] + engine.shutdown() + + print("==== Answer 1 ====") + print(out1) + + print("==== Answer 2 ====") + print(out2) + self.assertEqual(out1, out2) + + def test_7_engine_offline_throughput(self): + server_args = ServerArgs( + model_path=DEFAULT_SMALL_MODEL_NAME_FOR_TEST, + ) + bench_args = BenchArgs(num_prompts=10) + result = throughput_test(server_args=server_args, bench_args=bench_args) + self.assertGreater(result["total_throughput"], 3000) + + def test_8_engine_async_encode_consistency(self): + prompt = "Today is a sunny day and I like" + model_path = DEFAULT_SMALL_EMBEDDING_MODEL_NAME_FOR_TEST + + engine = sgl.Engine( + model_path=model_path, + is_embedding=True, + random_seed=42, + disable_radix_cache=True, + ) + + # Get sync and async embeddings + out1 = torch.tensor(engine.encode(prompt)["embedding"]) + loop = asyncio.get_event_loop() + out2 = torch.tensor( + loop.run_until_complete(engine.async_encode(prompt))["embedding"] + ) + + engine.shutdown() + + print("\n==== Shapes ====") + print(f"sync shape: {out1.shape}") + print(f"async shape: {out2.shape}") + + self.assertTrue( + torch.allclose(out1, out2, atol=1e-5, rtol=1e-3), + "Sync and async embeddings are not equal within tolerance", + ) + + +if __name__ == "__main__": + unittest.main() diff --git a/asian_ai/performance/SGLang/test/registered/cp/test_cp_strategy_unit.py b/asian_ai/performance/SGLang/test/registered/cp/test_cp_strategy_unit.py new file mode 100644 index 0000000000000000000000000000000000000000..1ea3ec493df7f471d437417ab34ab871613c13bc --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/cp/test_cp_strategy_unit.py @@ -0,0 +1,459 @@ +import unittest +from types import SimpleNamespace +from unittest.mock import patch + +import torch + +from sglang.srt.layers.cp.base import ( + ContextParallelStrategyKind, + get_cp_strategy, + get_cp_strategy_kind, + init_cp_strategy, + is_cp_enabled, + is_interleave, + is_zigzag, +) +from sglang.srt.layers.cp.utils import ( + cp_split_before_forward, + enable_cp_v2, + is_cp_v2_active, +) +from sglang.srt.layers.cp.zigzag import ZigzagCPStrategy +from sglang.srt.runtime_context import get_parallel +from sglang.test.ci.ci_register import register_cpu_ci +from sglang.test.test_utils import CustomTestCase + +register_cpu_ci(est_time=5, suite="base-a-test-cpu") + + +class _ExtendMode: + def is_context_parallel_extend(self): + return True + + +class _FakeCPGroup: + def __init__(self, all_rank_tensors): + self.all_rank_tensors = all_rank_tensors + + def cp_all_gather_into_tensor_async(self, output, input_tensor, stream): + del input_tensor, stream + torch.cat(self.all_rank_tensors, dim=0, out=output) + + +class TestCPStrategyUnit(CustomTestCase): + def tearDown(self): + init_cp_strategy(SimpleNamespace(enable_prefill_cp=False)) + + def test_strategy_kind_maps_cli_values(self): + self.assertEqual(ContextParallelStrategyKind.NONE.value, 0) + self.assertEqual( + ContextParallelStrategyKind.from_string("zigzag"), + ContextParallelStrategyKind.ZIGZAG, + ) + self.assertEqual( + ContextParallelStrategyKind.from_string("interleave"), + ContextParallelStrategyKind.INTERLEAVE, + ) + self.assertEqual(ContextParallelStrategyKind.ZIGZAG.cli_value, "zigzag") + self.assertEqual(ContextParallelStrategyKind.INTERLEAVE.cli_value, "interleave") + + def test_init_cp_strategy_binds_zigzag_strategy(self): + init_cp_strategy( + SimpleNamespace( + enable_prefill_cp=True, + cp_strategy="zigzag", + attn_cp_size=4, + ) + ) + + self.assertTrue(is_cp_enabled()) + self.assertTrue(is_zigzag()) + self.assertFalse(is_interleave()) + self.assertEqual(get_cp_strategy_kind(), ContextParallelStrategyKind.ZIGZAG) + + def test_get_cp_strategy_is_initialized_under_cp_v1_and_cp_v2(self): + init_cp_strategy( + SimpleNamespace( + enable_prefill_cp=True, + cp_strategy="interleave", + attn_cp_size=4, + ) + ) + + with patch( + "sglang.srt.environ.envs.SGLANG_ENABLE_CP_V2.get", return_value=False + ): + self.assertIsNotNone(get_cp_strategy()) + self.assertTrue(is_cp_enabled()) + self.assertTrue(is_interleave()) + + with patch( + "sglang.srt.environ.envs.SGLANG_ENABLE_CP_V2.get", return_value=True + ): + self.assertIsNotNone(get_cp_strategy()) + + +class TestCPZigzagStrategy(CustomTestCase): + def setUp(self): + init_cp_strategy( + SimpleNamespace( + enable_prefill_cp=True, + cp_strategy="zigzag", + attn_cp_size=4, + attention_backend="fa3", + ) + ) + + def tearDown(self): + init_cp_strategy(SimpleNamespace(enable_prefill_cp=False)) + + def _metadata_for_rank(self, rank, *, cp_size, seq_lens, extend_seq_lens): + strategy = ZigzagCPStrategy(cp_size=cp_size) + with get_parallel().override(attn_cp_rank=rank): + return strategy.build_metadata( + num_tokens=sum(extend_seq_lens), + seqs_len=seq_lens, + extend_seqs_len=extend_seq_lens, + ) + + def _forward_batch(self, metadata, extend_seq_lens): + return SimpleNamespace( + input_ids=torch.arange(sum(extend_seq_lens)), + forward_mode=_ExtendMode(), + extend_seq_lens_cpu=extend_seq_lens, + attn_cp_metadata=metadata, + ) + + def test_enable_cp_v2_and_is_cp_v2_active(self): + active_batch = SimpleNamespace( + input_ids=torch.arange(8), + forward_mode=_ExtendMode(), + extend_seq_lens_cpu=[8], + ) + inactive_batch = SimpleNamespace( + input_ids=torch.arange(7), + forward_mode=_ExtendMode(), + extend_seq_lens_cpu=[7], + ) + + with patch( + "sglang.srt.environ.envs.SGLANG_ENABLE_CP_V2.get", return_value=False + ): + self.assertFalse(enable_cp_v2()) + self.assertFalse(is_cp_v2_active(active_batch)) + + with patch( + "sglang.srt.environ.envs.SGLANG_ENABLE_CP_V2.get", return_value=True + ): + self.assertTrue(enable_cp_v2()) + self.assertTrue(is_cp_v2_active(active_batch)) + self.assertFalse(is_cp_v2_active(inactive_batch)) + + def _expected_metadata(self, *, rank, cp_size, seq_lens, extend_seq_lens): + bs = len(extend_seq_lens) + cp_segment_num = cp_size * 2 + prefix_offsets = [ + max(int(seq_lens[i]) - int(extend_seq_lens[i]), 0) for i in range(bs) + ] + + per_seq_block_sizes = [] + split_list = [] + for length in extend_seq_lens: + base = length // cp_segment_num + rem = length % cp_segment_num + block_sizes = [ + base + 1 if block_id < rem else base + for block_id in range(cp_segment_num) + ] + per_seq_block_sizes.append(block_sizes) + split_list.extend(block_sizes) + + per_rank_actual_token = [ + sum( + block_sizes[rank_id] + block_sizes[cp_segment_num - 1 - rank_id] + for block_sizes in per_seq_block_sizes + ) + for rank_id in range(cp_size) + ] + max_rank_len = [max(per_rank_actual_token)] * cp_size + + zigzag_index = list(range(rank, rank + bs * cp_segment_num, cp_segment_num)) + zigzag_index += list( + range(cp_segment_num - rank - 1, bs * cp_segment_num, cp_segment_num) + ) + + cp_reverse_index = [] + for batch_id in range(bs): + cp_reverse_index.extend( + list(range(batch_id, cp_segment_num * bs, 2 * bs)) + + list(range((cp_segment_num - 1) * bs + batch_id, 0, -2 * bs)) + ) + + reverse_split_len = [] + for rank_id in range(cp_size): + for batch_id in range(bs): + reverse_split_len.append(per_seq_block_sizes[batch_id][rank_id]) + for batch_id in range(bs): + reverse_split_len.append( + per_seq_block_sizes[batch_id][cp_segment_num - 1 - rank_id] + ) + + kv_len_prev_list = [] + kv_len_next_list = [] + actual_seq_q_prev_list = [] + actual_seq_q_next_list = [] + for batch_id, block_sizes in enumerate(per_seq_block_sizes): + kv_len_prev_list.append( + prefix_offsets[batch_id] + sum(block_sizes[: rank + 1]) + ) + kv_len_next_list.append( + prefix_offsets[batch_id] + sum(block_sizes[: cp_segment_num - rank]) + ) + actual_seq_q_prev_list.append(block_sizes[rank]) + actual_seq_q_next_list.append(block_sizes[cp_segment_num - rank - 1]) + + return { + "bs": bs, + "total_seq_lens": sum(extend_seq_lens), + "split_list": split_list, + "zigzag_index": zigzag_index, + "per_rank_actual_token": per_rank_actual_token, + "max_rank_len": max_rank_len, + "reverse_split_len": reverse_split_len, + "cp_reverse_index": cp_reverse_index, + "kv_len_prev_list": kv_len_prev_list, + "kv_len_next_list": kv_len_next_list, + "actual_seq_q_prev_list": actual_seq_q_prev_list, + "actual_seq_q_next_list": actual_seq_q_next_list, + } + + def _assert_metadata_matches(self, metadata, expected): + self.assertEqual(metadata.bs, expected["bs"]) + self.assertEqual(metadata.total_seq_lens, expected["total_seq_lens"]) + self.assertEqual(metadata.split_list, expected["split_list"]) + self.assertEqual(metadata.zigzag_index, expected["zigzag_index"]) + self.assertEqual( + metadata.per_rank_actual_token, expected["per_rank_actual_token"] + ) + self.assertEqual(metadata.max_rank_len, expected["max_rank_len"]) + self.assertEqual(metadata.reverse_split_len, expected["reverse_split_len"]) + self.assertEqual(metadata.cp_reverse_index, expected["cp_reverse_index"]) + self.assertEqual(metadata.kv_len_prev_list, expected["kv_len_prev_list"]) + self.assertEqual(metadata.kv_len_next_list, expected["kv_len_next_list"]) + self.assertEqual( + metadata.actual_seq_q_prev_list, expected["actual_seq_q_prev_list"] + ) + self.assertEqual( + metadata.actual_seq_q_next_list, expected["actual_seq_q_next_list"] + ) + self.assertEqual( + metadata.cu_seqlens_q_prev_tensor.cpu().tolist(), + [0] + + list( + torch.tensor(expected["actual_seq_q_prev_list"]).cumsum(dim=0).tolist() + ), + ) + self.assertEqual( + metadata.cu_seqlens_q_next_tensor.cpu().tolist(), + [0] + + list( + torch.tensor(expected["actual_seq_q_next_list"]).cumsum(dim=0).tolist() + ), + ) + + def _padded_rank_tensors(self, x, *, cp_size, seq_lens, extend_seq_lens): + per_rank = [] + metas = [] + for rank in range(cp_size): + metadata = self._metadata_for_rank( + rank, + cp_size=cp_size, + seq_lens=seq_lens, + extend_seq_lens=extend_seq_lens, + ) + metas.append(metadata) + fb = self._forward_batch(metadata, extend_seq_lens) + local = ZigzagCPStrategy(cp_size=cp_size).shard_hidden_states(x, fb) + pad = metadata.max_rank_len[0] - local.shape[0] + if pad: + local = torch.nn.functional.pad( + local, + [0, 0] * (local.ndim - 1) + [0, pad], + ) + per_rank.append(local) + return metas, per_rank + + def test_zigzag_metadata_for_batched_sequences(self): + cases = [ + (4, [11, 13], [9, 10]), + (2, [8], [8]), + (4, [100000, 200000, 80], [100000, 200000, 64]), + (4, [100005, 200011, 25], [100000, 200000, 16]), + ] + + for cp_size, seq_lens, extend_seq_lens in cases: + for rank in range(cp_size): + with self.subTest( + cp_size=cp_size, + rank=rank, + seq_lens=seq_lens, + extend_seq_lens=extend_seq_lens, + ): + metadata = self._metadata_for_rank( + rank, + cp_size=cp_size, + seq_lens=seq_lens, + extend_seq_lens=extend_seq_lens, + ) + expected = self._expected_metadata( + rank=rank, + cp_size=cp_size, + seq_lens=seq_lens, + extend_seq_lens=extend_seq_lens, + ) + self._assert_metadata_matches(metadata, expected) + + def test_zigzag_shards_hidden_states_and_position_ids(self): + cp_size = 4 + seq_lens = [11, 13] + extend_seq_lens = [9, 10] + x = torch.arange(sum(extend_seq_lens) * 2).view(sum(extend_seq_lens), 2) + positions = torch.arange(sum(extend_seq_lens)) + + for rank in range(cp_size): + metadata = self._metadata_for_rank( + rank, + cp_size=cp_size, + seq_lens=seq_lens, + extend_seq_lens=extend_seq_lens, + ) + fb = self._forward_batch(metadata, extend_seq_lens) + strategy = ZigzagCPStrategy(cp_size=cp_size) + chunks = torch.split(x, metadata.split_list, dim=0) + position_chunks = torch.split(positions, metadata.split_list, dim=-1) + expected_x = torch.cat([chunks[i] for i in metadata.zigzag_index], dim=0) + expected_positions = torch.cat( + [position_chunks[i] for i in metadata.zigzag_index], dim=-1 + ) + + local_x = strategy.shard_hidden_states(x, fb) + local_positions = strategy.shard_position_ids(positions, fb) + with patch( + "sglang.srt.environ.envs.SGLANG_ENABLE_CP_V2.get", return_value=True + ): + helper_x, helper_positions = cp_split_before_forward( + x, + positions, + fb, + ) + + self.assertTrue(torch.equal(local_x, expected_x)) + self.assertTrue(torch.equal(local_positions, expected_positions)) + self.assertTrue(torch.equal(helper_x, expected_x)) + self.assertTrue(torch.equal(helper_positions, expected_positions)) + + def test_zigzag_gathers_hidden_states_to_original_order(self): + cp_size = 4 + seq_lens = [11, 13] + extend_seq_lens = [9, 10] + x = torch.arange(sum(extend_seq_lens) * 2).view(sum(extend_seq_lens), 2) + metas, padded_rank_tensors = self._padded_rank_tensors( + x, + cp_size=cp_size, + seq_lens=seq_lens, + extend_seq_lens=extend_seq_lens, + ) + + for rank in range(cp_size): + local_x = padded_rank_tensors[rank][ + : metas[rank].per_rank_actual_token[rank] + ] + fb = self._forward_batch(metas[rank], extend_seq_lens) + + with ( + patch( + "sglang.srt.layers.cp.zigzag.get_attention_cp_group", + return_value=_FakeCPGroup(padded_rank_tensors), + ), + patch( + "sglang.srt.distributed.device_communicators.pynccl_allocator.use_symmetric_memory", + return_value=torch.no_grad(), + ), + ): + gathered = ZigzagCPStrategy(cp_size=cp_size).gather_hidden_states( + local_x, fb, stream=None + ) + + self.assertTrue(torch.equal(gathered, x)) + + def test_zigzag_gathers_kv_cache_to_original_order(self): + cp_size = 4 + seq_lens = [11, 13] + extend_seq_lens = [9, 10] + kv = torch.arange(sum(extend_seq_lens) * 2 * 3).view(sum(extend_seq_lens), 2, 3) + metas, padded_rank_tensors = self._padded_rank_tensors( + kv, + cp_size=cp_size, + seq_lens=seq_lens, + extend_seq_lens=extend_seq_lens, + ) + + for rank in range(cp_size): + local_kv = padded_rank_tensors[rank][ + : metas[rank].per_rank_actual_token[rank] + ] + fb = self._forward_batch(metas[rank], extend_seq_lens) + + with ( + patch( + "sglang.srt.layers.cp.zigzag.get_attention_cp_group", + return_value=_FakeCPGroup(padded_rank_tensors), + ), + patch( + "sglang.srt.distributed.device_communicators.pynccl_allocator.use_symmetric_memory", + return_value=torch.no_grad(), + ), + ): + gathered = ZigzagCPStrategy(cp_size=cp_size).gather_kv_cache( + local_kv, fb, stream=None + ) + + self.assertTrue(torch.equal(gathered, kv)) + + def test_zigzag_attention_dispatch_runs_prev_then_next(self): + cp_size = 2 + seq_lens = [8] + extend_seq_lens = [8] + metadata = self._metadata_for_rank( + 0, + cp_size=cp_size, + seq_lens=seq_lens, + extend_seq_lens=extend_seq_lens, + ) + fb = SimpleNamespace(attn_cp_metadata=metadata) + q = torch.arange(4 * 2).view(4, 2) + calls = [] + + def attn_fn(q_chunk, cu_seqlens_q, cache_seqlens, max_seqlen_q): + calls.append( + ( + q_chunk.clone(), + cu_seqlens_q.clone(), + cache_seqlens.clone(), + max_seqlen_q, + ) + ) + return q_chunk + 100 + + out = ZigzagCPStrategy(cp_size=cp_size).run_attention( + q, fb, device=torch.device("cpu"), attn_fn=attn_fn + ) + + self.assertEqual(len(calls), 2) + self.assertTrue(torch.equal(calls[0][0], q[:2])) + self.assertTrue(torch.equal(calls[1][0], q[2:])) + self.assertTrue(torch.equal(out, q + 100)) + + +if __name__ == "__main__": + unittest.main() diff --git a/asian_ai/performance/SGLang/test/registered/cp/test_deepseek_v32_cp_single_node.py b/asian_ai/performance/SGLang/test/registered/cp/test_deepseek_v32_cp_single_node.py new file mode 100644 index 0000000000000000000000000000000000000000..c9ce647d9b90ab37b1179eeccdf2fb81ed7bbe96 --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/cp/test_deepseek_v32_cp_single_node.py @@ -0,0 +1,156 @@ +import unittest +from types import SimpleNamespace + +from sglang.srt.utils import kill_process_tree +from sglang.test.ci.ci_register import register_cuda_ci +from sglang.test.run_eval import run_eval +from sglang.test.test_utils import ( + DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH, + DEFAULT_URL_FOR_TEST, + CustomTestCase, + is_in_ci, + popen_launch_server, + write_github_step_summary, +) + +register_cuda_ci(est_time=616, stage="extra-b", runner_config="deepep-8-gpu-h200") +DEEPSEEK_V32_MODEL_PATH = "deepseek-ai/DeepSeek-V3.2" + + +class TestDeepseekV32CPInSeqSplit(CustomTestCase): + @classmethod + def setUpClass(cls): + cls.model = DEEPSEEK_V32_MODEL_PATH + cls.base_url = DEFAULT_URL_FOR_TEST + other_args = [ + "--trust-remote-code", + "--tp", + "8", + "--enable-dp-attention", + "--dp", + "2", + "--attn-cp-size", + "4", + "--enable-dsa-prefill-context-parallel", + "--dsa-prefill-cp-mode", + "in-seq-split", + "--speculative-algorithm", + "EAGLE", + "--speculative-num-steps", + "3", + "--speculative-eagle-topk", + "1", + "--speculative-num-draft-tokens", + "4", + "--mem-frac", + "0.85", + "--cuda-graph-max-bs-decode", + "32", + "--max-running-requests", + "32", + "--model-loader-extra-config", + '{"enable_multithread_load": true, "num_threads": 64}', + ] + cls.process = popen_launch_server( + cls.model, + cls.base_url, + timeout=DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH, + other_args=other_args, + ) + + @classmethod + def tearDownClass(cls): + kill_process_tree(cls.process.pid) + + def test_a_gsm8k( + self, + ): # Append an "a" to make this test run first (alphabetically) to warm up the server + args = SimpleNamespace( + base_url=self.base_url, + model=self.model, + eval_name="gsm8k", + api="completion", + max_tokens=512, + num_examples=500, + num_threads=32, + num_shots=20, + ) + metrics = run_eval(args) + print(f"{metrics=}") + + if is_in_ci(): + write_github_step_summary( + f"### test_a_gsm8k (deepseek-v32-cp-in-seq-split)\n" + f'{metrics["score"]=:.3f}\n' + ) + self.assertGreater(metrics["score"], 0.935) + + +class TestDeepseekV32CPRoundRobinSplit(CustomTestCase): + @classmethod + def setUpClass(cls): + cls.model = DEEPSEEK_V32_MODEL_PATH + cls.base_url = DEFAULT_URL_FOR_TEST + other_args = [ + "--trust-remote-code", + "--tp", + "8", + "--attn-cp-size", + "8", + "--enable-dsa-prefill-context-parallel", + "--dsa-prefill-cp-mode", + "round-robin-split", + "--speculative-algorithm", + "EAGLE", + "--speculative-num-steps", + "3", + "--speculative-eagle-topk", + "1", + "--speculative-num-draft-tokens", + "4", + "--mem-frac", + "0.85", + "--cuda-graph-max-bs-decode", + "32", + "--max-running-requests", + "32", + "--model-loader-extra-config", + '{"enable_multithread_load": true, "num_threads": 64}', + ] + cls.process = popen_launch_server( + cls.model, + cls.base_url, + timeout=DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH, + other_args=other_args, + ) + + @classmethod + def tearDownClass(cls): + kill_process_tree(cls.process.pid) + + def test_a_gsm8k( + self, + ): # Append an "a" to make this test run first (alphabetically) to warm up the server + args = SimpleNamespace( + base_url=self.base_url, + model=self.model, + eval_name="gsm8k", + api="completion", + max_tokens=512, + num_examples=500, + num_threads=32, + num_shots=20, + ) + metrics = run_eval(args) + print(f"{metrics=}") + + if is_in_ci(): + write_github_step_summary( + f"### test_a_gsm8k (deepseek-v32-cp-in-seq-split)\n" + f'{metrics["score"]=:.3f}\n' + ) + self.assertGreater(metrics["score"], 0.935) + + +if __name__ == "__main__": + unittest.main() diff --git a/asian_ai/performance/SGLang/test/registered/cp/test_deepseek_v3_cp_single_node.py b/asian_ai/performance/SGLang/test/registered/cp/test_deepseek_v3_cp_single_node.py new file mode 100644 index 0000000000000000000000000000000000000000..402825ab3b46793f726a231a4786a17c73d0f47c --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/cp/test_deepseek_v3_cp_single_node.py @@ -0,0 +1,89 @@ +import unittest +from types import SimpleNamespace + +from sglang.srt.utils import kill_process_tree +from sglang.test.ci.ci_register import register_cuda_ci +from sglang.test.run_eval import run_eval +from sglang.test.test_utils import ( + DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH, + DEFAULT_URL_FOR_TEST, + CustomTestCase, + is_in_ci, + popen_launch_server, + write_github_step_summary, +) + +register_cuda_ci(est_time=500, stage="extra-b", runner_config="deepep-8-gpu-h200") + +DEEPSEEK_V3_MODEL_PATH = "deepseek-ai/DeepSeek-V3-0324" + +# Matches the non-CP DSv3 production baseline in +# ``test_deepseek_v3_basic.py`` / ``test_deepseek_v3_mtp.py``. Pinning +# MLA CP to the same threshold makes this test double as a regression +# gate against the known production accuracy. +GSM8K_ACCURACY_THRESHOLD = 0.935 + + +class TestDeepseekV3CPInSeqSplit(CustomTestCase): + """tp=8, dp=2, attn-cp=4 — DP attention + DeepEP MoE + MLA CP.""" + + @classmethod + def setUpClass(cls): + cls.model = DEEPSEEK_V3_MODEL_PATH + cls.base_url = DEFAULT_URL_FOR_TEST + other_args = [ + "--trust-remote-code", + "--tp", + "8", + "--dp", + "2", + "--enable-prefill-context-parallel", + "--attention-backend", + "fa3", + "--mem-frac", + "0.7", + "--cuda-graph-max-bs-decode", + "32", + "--max-running-requests", + "32", + "--model-loader-extra-config", + '{"enable_multithread_load": true, "num_threads": 64}', + ] + cls.process = popen_launch_server( + cls.model, + cls.base_url, + timeout=DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH * 5, + other_args=other_args, + ) + + @classmethod + def tearDownClass(cls): + if hasattr(cls, "process") and cls.process: + kill_process_tree(cls.process.pid) + + # "test_a_" prefix pins alphabetical first-run ordering so this + # warms up the server before any follow-up sibling test methods. + def test_a_gsm8k(self): + args = SimpleNamespace( + base_url=self.base_url, + model=self.model, + eval_name="gsm8k", + api="completion", + max_tokens=512, + num_examples=500, + num_threads=32, + num_shots=20, + ) + metrics = run_eval(args) + print(f"{metrics=}") + + if is_in_ci(): + write_github_step_summary( + f"### test_a_gsm8k (deepseek-v3-mla-cp-in-seq-split)\n" + f'{metrics["score"]=:.3f}\n' + ) + self.assertGreater(metrics["score"], GSM8K_ACCURACY_THRESHOLD) + + +if __name__ == "__main__": + unittest.main() diff --git a/asian_ai/performance/SGLang/test/registered/cp/test_deepseek_v4_flash_fp4_b200_cp.py b/asian_ai/performance/SGLang/test/registered/cp/test_deepseek_v4_flash_fp4_b200_cp.py new file mode 100644 index 0000000000000000000000000000000000000000..dffc778141a61d81bf06eb767812e8a00b893c88 --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/cp/test_deepseek_v4_flash_fp4_b200_cp.py @@ -0,0 +1,137 @@ +"""B200 extra CI: DeepSeek-V4-Flash FP4 with attn-CP (DSA prefill CP). + +Balanced recipe (TP=4, DeepEP, EAGLE) plus --attn-cp-size=4 with the +DSA prefill-CP round-robin-split mode. Split out of +models_e2e/test_deepseek_v4_flash_fp4_b200.py so the `cp` group covers +all context-parallel tests. + +Registry: extra-b-test-4-gpu-b200 (label-gated extra CI, 4x B200) +""" + +import unittest + +from sglang.srt.utils import kill_process_tree +from sglang.test.ci.ci_register import register_cuda_ci +from sglang.test.kits.basic_decode_correctness_kit import BasicDecodeCorrectnessMixin +from sglang.test.kits.eval_accuracy_kit import GSM8KMixin +from sglang.test.kits.spec_decoding_kit import SpecDecodingMixin +from sglang.test.test_utils import ( + DEFAULT_URL_FOR_TEST, + CustomTestCase, + popen_launch_server, + try_cached_model, +) + +register_cuda_ci(est_time=235, stage="extra-b", runner_config="deepep-4-gpu-b200") + +MODEL = "deepseek-ai/DeepSeek-V4-Flash" +SERVER_LAUNCH_TIMEOUT = 3600 +DEEPEP_CONFIG = '{"normal_dispatch":{"num_sms":96},"normal_combine":{"num_sms":96}}' + +_DEEPEP_ENV = { + "SGLANG_DEEPEP_NUM_MAX_DISPATCH_TOKENS_PER_RANK": "1024", +} + + +class TestDSV4FlashFP4B200Balanced_CP( + SpecDecodingMixin, + BasicDecodeCorrectnessMixin, + GSM8KMixin, + CustomTestCase, +): + """Balanced recipe: TP=4, DP=4, DeepEP, EAGLE (1-step spec).""" + + gsm8k_accuracy_thres = 0.93 + accept_length_thres = 1.8 + bs_1_speed_thres = 100 + + @classmethod + def setUpClass(cls): + cls.model = try_cached_model(MODEL) + cls.base_url = DEFAULT_URL_FOR_TEST + cls.process = popen_launch_server( + cls.model, + cls.base_url, + timeout=SERVER_LAUNCH_TIMEOUT, + other_args=[ + "--trust-remote-code", + "--tp", + "4", + "--attn-cp-size", + "4", + "--enable-dp-attention", + "--moe-a2a-backend", + "deepep", + "--speculative-algorithm", + "EAGLE", + "--speculative-num-steps", + "1", + "--speculative-eagle-topk", + "1", + "--speculative-num-draft-tokens", + "2", + "--enable-dsa-prefill-context-parallel", + "--dsa-prefill-cp-mode", + "round-robin-split", + "--deepep-config", + DEEPEP_CONFIG, + ], + env=_DEEPEP_ENV, + ) + + @classmethod + def tearDownClass(cls): + if hasattr(cls, "process") and cls.process: + kill_process_tree(cls.process.pid) + + +class TestDSV4FlashFP4B200Balanced_CP_NonDeepEP( + SpecDecodingMixin, + BasicDecodeCorrectnessMixin, + GSM8KMixin, + CustomTestCase, +): + """Balanced recipe: TP=4, DP=4, EAGLE (1-step spec).""" + + gsm8k_accuracy_thres = 0.93 + accept_length_thres = 1.8 + bs_1_speed_thres = 100 + + @classmethod + def setUpClass(cls): + cls.model = try_cached_model(MODEL) + cls.base_url = DEFAULT_URL_FOR_TEST + cls.process = popen_launch_server( + cls.model, + cls.base_url, + timeout=SERVER_LAUNCH_TIMEOUT, + other_args=[ + "--trust-remote-code", + "--tp", + "4", + "--attn-cp-size", + "4", + "--speculative-algorithm", + "EAGLE", + "--speculative-num-steps", + "1", + "--speculative-eagle-topk", + "1", + "--speculative-num-draft-tokens", + "2", + "--enable-dsa-prefill-context-parallel", + "--dsa-prefill-cp-mode", + "round-robin-split", + "--moe-runner-backend", # for fp4 checkpoint + "flashinfer_mxfp4", + ], + ) + + @classmethod + def tearDownClass(cls): + if hasattr(cls, "process") and cls.process: + kill_process_tree(cls.process.pid) + + +if __name__ == "__main__": + unittest.main() diff --git a/asian_ai/performance/SGLang/test/registered/cp/test_gqa_prefill_cp_legacy.py b/asian_ai/performance/SGLang/test/registered/cp/test_gqa_prefill_cp_legacy.py new file mode 100644 index 0000000000000000000000000000000000000000..b9c0ae5a4e32a4a1c4409cf5defc9029bac738f5 --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/cp/test_gqa_prefill_cp_legacy.py @@ -0,0 +1,136 @@ +import unittest +from types import SimpleNamespace + +from sglang.test.ci.ci_register import register_cuda_ci +from sglang.test.run_eval import run_eval +from sglang.test.test_utils import ( + DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH, + DEFAULT_URL_FOR_TEST, + CustomTestCase, + kill_process_tree, + popen_launch_server, +) + +register_cuda_ci(est_time=260, stage="extra-b", runner_config="4-gpu-h100") + +GQA_MODEL_PATH = "Qwen/Qwen3-30B-A3B-FP8" + +GSM8K_BASELINE_ACCURACY = 0.93 + + +class TestGQACP2TP2EP2(CustomTestCase): + @classmethod + def setUpClass(cls): + cls.model = GQA_MODEL_PATH + cls.base_url = DEFAULT_URL_FOR_TEST + cls.process = popen_launch_server( + cls.model, + cls.base_url, + timeout=DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH, + other_args=[ + "--tp-size", + "4", + "--moe-dp-size", + "2", + "--ep-size", + "2", + "--attn-cp-size", + "2", + "--enable-prefill-context-parallel", + "--cuda-graph-max-bs-decode", + "32", + "--max-running-requests", + "32", + "--trust-remote-code", + "--disable-piecewise-cuda-graph", + "--model-loader-extra-config", + '{"enable_multithread_load": true, "num_threads": 64}', + ], + env={"SGLANG_ENABLE_CP_V2": "0"}, + ) + + @classmethod + def tearDownClass(cls): + if hasattr(cls, "process") and cls.process: + kill_process_tree(cls.process.pid) + + def test_gsm8k(self): + args = SimpleNamespace( + model=self.model, + eval_name="gsm8k", + num_shots=5, + num_examples=200, + max_tokens=16000, + num_threads=128, + repeat=1, + temperature=0.6, + top_p=0.95, + top_k=20, + base_url=self.base_url, + host="http://127.0.0.1", + port=int(self.base_url.split(":")[-1]), + ) + metrics = run_eval(args) + print(f"{metrics=}") + self.assertGreaterEqual(metrics["score"], GSM8K_BASELINE_ACCURACY) + + +class TestGQACPTP2CP2EP4(CustomTestCase): + @classmethod + def setUpClass(cls): + cls.model = GQA_MODEL_PATH + cls.base_url = DEFAULT_URL_FOR_TEST + cls.process = popen_launch_server( + cls.model, + cls.base_url, + timeout=DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH, + other_args=[ + "--tp-size", + "4", + "--moe-dp-size", + "1", + "--ep-size", + "4", + "--attn-cp-size", + "2", + "--enable-prefill-context-parallel", + "--cuda-graph-max-bs-decode", + "32", + "--max-running-requests", + "32", + "--trust-remote-code", + "--disable-piecewise-cuda-graph", + "--model-loader-extra-config", + '{"enable_multithread_load": true, "num_threads": 64}', + ], + env={"SGLANG_ENABLE_CP_V2": "0"}, + ) + + @classmethod + def tearDownClass(cls): + if hasattr(cls, "process") and cls.process: + kill_process_tree(cls.process.pid) + + def test_gsm8k(self): + args = SimpleNamespace( + model=self.model, + eval_name="gsm8k", + num_shots=5, + num_examples=200, + max_tokens=16000, + num_threads=128, + repeat=1, + temperature=0.6, + top_p=0.95, + top_k=20, + base_url=self.base_url, + host="http://127.0.0.1", + port=int(self.base_url.split(":")[-1]), + ) + metrics = run_eval(args) + print(f"{metrics=}") + self.assertGreaterEqual(metrics["score"], GSM8K_BASELINE_ACCURACY) + + +if __name__ == "__main__": + unittest.main() diff --git a/asian_ai/performance/SGLang/test/registered/cp/test_gqa_preill_cp.py b/asian_ai/performance/SGLang/test/registered/cp/test_gqa_preill_cp.py new file mode 100644 index 0000000000000000000000000000000000000000..5443b862b77c24b18e7d21247b62d22f4b1edefc --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/cp/test_gqa_preill_cp.py @@ -0,0 +1,200 @@ +import unittest +from types import SimpleNamespace + +from sglang.test.ci.ci_register import register_cuda_ci +from sglang.test.run_eval import run_eval +from sglang.test.test_utils import ( + DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH, + DEFAULT_URL_FOR_TEST, + CustomTestCase, + kill_process_tree, + popen_launch_server, +) + +register_cuda_ci(est_time=500, stage="extra-b", runner_config="4-gpu-h100") + +GQA_MODEL_PATH = "Qwen/Qwen3-30B-A3B-FP8" + +GSM8K_BASELINE_ACCURACY = 0.93 + + +class TestGQACP2TP2EP2(CustomTestCase): + @classmethod + def setUpClass(cls): + cls.model = GQA_MODEL_PATH + cls.base_url = DEFAULT_URL_FOR_TEST + cls.process = popen_launch_server( + cls.model, + cls.base_url, + timeout=DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH, + other_args=[ + "--tp-size", + "4", + "--moe-dp-size", + "2", + "--ep-size", + "2", + "--attn-cp-size", + "2", + "--enable-prefill-cp", + "--cp-strategy", + "zigzag", + "--cuda-graph-max-bs-decode", + "32", + "--max-running-requests", + "32", + "--trust-remote-code", + "--disable-piecewise-cuda-graph", + "--model-loader-extra-config", + '{"enable_multithread_load": true, "num_threads": 64}', + ], + env={"SGLANG_ENABLE_CP_V2": "1"}, + ) + + @classmethod + def tearDownClass(cls): + if hasattr(cls, "process") and cls.process: + kill_process_tree(cls.process.pid) + + def test_gsm8k(self): + args = SimpleNamespace( + model=self.model, + eval_name="gsm8k", + num_shots=5, + num_examples=200, + max_tokens=16000, + num_threads=128, + repeat=1, + temperature=0.6, + top_p=0.95, + top_k=20, + base_url=self.base_url, + host="http://127.0.0.1", + port=int(self.base_url.split(":")[-1]), + ) + metrics = run_eval(args) + print(f"{metrics=}") + self.assertGreaterEqual(metrics["score"], GSM8K_BASELINE_ACCURACY) + + +class TestGQACPTP2CP2EP4(CustomTestCase): + @classmethod + def setUpClass(cls): + cls.model = GQA_MODEL_PATH + cls.base_url = DEFAULT_URL_FOR_TEST + cls.process = popen_launch_server( + cls.model, + cls.base_url, + timeout=DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH, + other_args=[ + "--tp-size", + "4", + "--moe-dp-size", + "1", + "--ep-size", + "4", + "--attn-cp-size", + "2", + "--enable-prefill-cp", + "--cp-strategy", + "zigzag", + "--cuda-graph-max-bs-decode", + "32", + "--max-running-requests", + "32", + "--trust-remote-code", + "--disable-piecewise-cuda-graph", + "--model-loader-extra-config", + '{"enable_multithread_load": true, "num_threads": 64}', + ], + env={"SGLANG_ENABLE_CP_V2": "1"}, + ) + + @classmethod + def tearDownClass(cls): + if hasattr(cls, "process") and cls.process: + kill_process_tree(cls.process.pid) + + def test_gsm8k(self): + args = SimpleNamespace( + model=self.model, + eval_name="gsm8k", + num_shots=5, + num_examples=200, + max_tokens=16000, + num_threads=128, + repeat=1, + temperature=0.6, + top_p=0.95, + top_k=20, + base_url=self.base_url, + host="http://127.0.0.1", + port=int(self.base_url.split(":")[-1]), + ) + metrics = run_eval(args) + print(f"{metrics=}") + self.assertGreaterEqual(metrics["score"], GSM8K_BASELINE_ACCURACY) + + +class TestGQACPCP4EP4(CustomTestCase): + @classmethod + def setUpClass(cls): + cls.model = GQA_MODEL_PATH + cls.base_url = DEFAULT_URL_FOR_TEST + cls.process = popen_launch_server( + cls.model, + cls.base_url, + timeout=DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH, + other_args=[ + "--tp-size", + "4", + "--ep", + "4", + "--attn-cp-size", + "4", + "--enable-prefill-cp", + "--cp-strategy", + "zigzag", + "--moe-a2a-backend", + "deepep", + "--attention-backend", + "fa3", + "--cuda-graph-max-bs-decode", + "32", + "--max-running-requests", + "32", + "--trust-remote-code", + "--disable-piecewise-cuda-graph", + "--model-loader-extra-config", + '{"enable_multithread_load": true, "num_threads": 64}', + ], + ) + + @classmethod + def tearDownClass(cls): + if hasattr(cls, "process") and cls.process: + kill_process_tree(cls.process.pid) + + def test_gsm8k(self): + args = SimpleNamespace( + model=self.model, + eval_name="gsm8k", + num_shots=5, + num_examples=200, + max_tokens=16000, + num_threads=128, + repeat=1, + temperature=0.6, + top_p=0.95, + top_k=20, + base_url=self.base_url, + host="http://127.0.0.1", + port=int(self.base_url.split(":")[-1]), + ) + metrics = run_eval(args) + print(f"{metrics=}") + self.assertGreaterEqual(metrics["score"], GSM8K_BASELINE_ACCURACY) + + +if __name__ == "__main__": + unittest.main() diff --git a/asian_ai/performance/SGLang/test/registered/cpu/arm64/test_moe.py b/asian_ai/performance/SGLang/test/registered/cpu/arm64/test_moe.py new file mode 100644 index 0000000000000000000000000000000000000000..b4f082173def5aba14bf4b8660b9c148abd65c8e --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/cpu/arm64/test_moe.py @@ -0,0 +1,122 @@ +"""Arm64 MoE test. + +Tests fused_experts_cpu with W8A8 INT8 quantization, which is supported +on Arm64 via aarch64/moe.cpp (PR #16045). Additional quantization paths +(BF16, INT4) will be added here as Arm kernels land. +""" + +from sglang.test.ci.ci_register import register_cpu_ci + +register_cpu_ci(est_time=10, suite="base-b-test-cpu-arm64") + +import itertools +import math +import os +import platform +import sys +import unittest + +import torch + +# Add parent dir (test/srt/cpu/) to path for utils import +sys.path.insert(0, os.path.join(os.path.dirname(__file__), "..")) + +from sglang.srt.layers.amx_utils import CPUQuantMethod +from sglang.test.test_utils import CustomTestCase + +kernel = torch.ops.sgl_kernel +IS_ARM64 = platform.machine().lower() in ("aarch64", "arm64") + +torch.manual_seed(128) + +from utils import ( + precision, + torch_w8a8_per_column_fused_moe, +) + + +class TestFusedExpertsInt8(CustomTestCase): + M = [1, 6, 32, 64] + N = [256, 512] + K = [256, 512] + E = [8] + topk = [4] + + def _int8_moe(self, M, N, K, E, topk): + dtype = torch.bfloat16 + # Arm64 INT8 MoE currently uses the unpacked, out-of-place path. + prepack = not IS_ARM64 + + int8_factor_for_scale = 1e-2 + int8_max = 127 + int8_min = -128 + + a = torch.randn((M, K), dtype=dtype) / math.sqrt(K) + + w1_fp32 = (torch.rand((E, 2 * N, K), dtype=torch.float32) - 0.5) * 2 + w1 = (w1_fp32 * int8_max).clamp(min=int8_min, max=int8_max).to(torch.int8) + + w2_fp32 = (torch.rand((E, K, N), dtype=torch.float32) - 0.5) * 2 + w2 = (w2_fp32 * int8_max).clamp(min=int8_min, max=int8_max).to(torch.int8) + + w1_s = torch.rand(E, 2 * N, device=w1_fp32.device) * int8_factor_for_scale + w2_s = torch.rand(E, K, device=w2_fp32.device) * int8_factor_for_scale + + score = torch.randn((M, E), dtype=dtype) + score = torch.softmax(score, dim=-1, dtype=torch.float32) + topk_weight, topk_ids = torch.topk(score, topk) + + ref_out = torch_w8a8_per_column_fused_moe( + a, w1, w2, w1_s, w2_s, topk_weight, topk_ids, topk + ) + + inplace = not IS_ARM64 + packed_w1 = kernel.convert_weight_packed(w1) if prepack else w1 + packed_w2 = kernel.convert_weight_packed(w2) if prepack else w2 + out = kernel.fused_experts_cpu( + a, + packed_w1, + packed_w2, + topk_weight, + topk_ids.to(torch.int32), + inplace, + CPUQuantMethod.INT8_W8A8, + w1_s, + w2_s, + None, + None, + None, + None, + None, + None, + None, + prepack, + ) + + atol = rtol = precision[ref_out.dtype] + if IS_ARM64: + atol = rtol = 0.03 + elif M > 35: + atol = rtol = 0.02 + torch.testing.assert_close(ref_out, out, atol=atol, rtol=rtol) + + def test_int8_moe(self): + for params in itertools.product( + self.M, + self.N, + self.K, + self.E, + self.topk, + ): + with self.subTest( + M=params[0], + N=params[1], + K=params[2], + E=params[3], + topk=params[4], + ): + self._int8_moe(*params) + + +if __name__ == "__main__": + unittest.main() diff --git a/asian_ai/performance/SGLang/test/registered/cpu/test_activation.py b/asian_ai/performance/SGLang/test/registered/cpu/test_activation.py new file mode 100644 index 0000000000000000000000000000000000000000..cbb6c721a020f348b50399d8f19d0759e92c8490 --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/cpu/test_activation.py @@ -0,0 +1,74 @@ +import sys + +import pytest +import torch +from utils import GeluAndMul, SiluAndMul, precision + +from sglang.srt.server_args import ServerArgs, set_global_server_args_for_scheduler +from sglang.test.ci.ci_register import register_cpu_ci + +register_cpu_ci(est_time=10, suite="base-b-test-cpu") +register_cpu_ci(est_time=10, suite="base-b-test-cpu-arm64") + +torch.manual_seed(1234) + +M = [128, 129, 257] +N = [22016, 22018] +DTYPES = [torch.float16, torch.bfloat16] + + +def _assert_close(ref_out, out): + atol = rtol = precision[ref_out.dtype] + torch.testing.assert_close(ref_out, out, atol=atol, rtol=rtol) + + +@pytest.mark.parametrize("dtype", DTYPES) +@pytest.mark.parametrize("n", N) +@pytest.mark.parametrize("m", M) +def test_activation(m, n, dtype): + set_global_server_args_for_scheduler(ServerArgs(model_path="dummy")) + + x = torch.randn([m, n], dtype=dtype) + _assert_close(SiluAndMul(x), torch.ops.sgl_kernel.silu_and_mul_cpu(x)) + + x = torch.randn([m, n], dtype=dtype) + _assert_close( + GeluAndMul(x, approximate="none"), torch.ops.sgl_kernel.gelu_and_mul_cpu(x) + ) + + x = torch.randn([m, n], dtype=dtype) + _assert_close( + GeluAndMul(x, approximate="tanh"), + torch.ops.sgl_kernel.gelu_tanh_and_mul_cpu(x), + ) + + +@pytest.mark.parametrize("gate_3d", [False, True]) +@pytest.mark.parametrize("dtype", DTYPES) +@pytest.mark.parametrize("head_dim", [256]) +@pytest.mark.parametrize("num_heads", [16]) +@pytest.mark.parametrize("m", [1, 17, 128]) +def test_fused_sigmoid_mul(m, num_heads, head_dim, dtype, gate_3d): + x = torch.randn([m, num_heads * head_dim], dtype=dtype) + if gate_3d: + gate_storage = torch.randn([m, num_heads, head_dim * 2], dtype=dtype) + gate = gate_storage[..., :head_dim] + assert not gate.is_contiguous() + else: + gate = torch.randn_like(x) + + gate_ref = gate.reshape(m, -1) if gate_3d else gate + _assert_close( + x * torch.sigmoid(gate_ref), + torch.ops.sgl_kernel.fused_sigmoid_mul_cpu(x, gate, False), + ) + + x_inplace = x.clone() + ref_inplace = x_inplace * torch.sigmoid(gate_ref) + out_inplace = torch.ops.sgl_kernel.fused_sigmoid_mul_cpu(x_inplace, gate, True) + assert out_inplace.data_ptr() == x_inplace.data_ptr() + _assert_close(ref_inplace, x_inplace) + + +if __name__ == "__main__": + sys.exit(pytest.main([__file__])) diff --git a/asian_ai/performance/SGLang/test/registered/cpu/test_binding.py b/asian_ai/performance/SGLang/test/registered/cpu/test_binding.py new file mode 100644 index 0000000000000000000000000000000000000000..48682bfde3ddc6452f77eb98f20d6f9c6981ddff --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/cpu/test_binding.py @@ -0,0 +1,30 @@ +import re +import unittest + +import torch + +kernel = torch.ops.sgl_kernel + +from sglang.test.ci.ci_register import register_cpu_ci +from sglang.test.test_utils import CustomTestCase + +register_cpu_ci(est_time=10, suite="base-b-test-cpu") + + +class TestBinding(CustomTestCase): + def test_binding(self): + start_id = 1 + n_cpu = 6 + + expected_cores = list(map(str, range(start_id, start_id + n_cpu))) + cpu_ids = ",".join(expected_cores) + output = kernel.init_cpu_threads_env(cpu_ids) + + bindings = re.findall(r"OMP tid: \d+, core (\d+)", output) + self.assertEqual(len(bindings), n_cpu) + + self.assertEqual(bindings, expected_cores) + + +if __name__ == "__main__": + unittest.main() diff --git a/asian_ai/performance/SGLang/test/registered/cpu/test_bmm.py b/asian_ai/performance/SGLang/test/registered/cpu/test_bmm.py new file mode 100644 index 0000000000000000000000000000000000000000..5423d93e9d40b4b688e0e35a7b51da9b56f9c7ca --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/cpu/test_bmm.py @@ -0,0 +1,98 @@ +import itertools +import unittest + +# TODO: use interface in cpu.py +import torch +import torch.nn as nn +from utils import precision + +from sglang.srt.layers.quantization.fp8_utils import input_to_float8 +from sglang.test.ci.ci_register import register_cpu_ci +from sglang.test.test_utils import CustomTestCase + +register_cpu_ci(est_time=10, suite="base-b-test-cpu") + +torch.manual_seed(1234) + + +class Mod(nn.Module): + def __init__(self, input_channel, output_channel, has_bias): + super(Mod, self).__init__() + self.linear = torch.nn.Linear(input_channel, output_channel, has_bias) + + def forward(self, x): + return self.linear(x) + + +class TestBmm(CustomTestCase): + M = [1, 2, 11, 111] + N = [128 + 32, 512] + K = [512 + 32, 128 + 32] + B = [1, 16, 17] + chunk = [True, False] + + def _get_bmm_inputs(self, B, M, N, K, chunk, dtype): + if chunk: + mat1 = ( + torch.randn(M, B, K + 64, dtype=dtype).narrow(2, 0, K).transpose_(0, 1) + ) + mat2 = torch.randn(B, N, K, dtype=dtype).transpose_(1, 2) + mat3 = ( + torch.randn(M, B, N + 64, dtype=dtype).narrow(2, 0, N).transpose_(0, 1) + ) + else: + mat1 = torch.randn(M, B, K, dtype=dtype).transpose_(0, 1) + mat2 = torch.randn(B, N, K, dtype=dtype).transpose_(1, 2) + mat3 = torch.randn(M, B, N, dtype=dtype).transpose_(0, 1) + return mat1, mat2, mat3 + + def _bf16_bmm(self, B, M, N, K, chunk, dtype=torch.bfloat16): + mat1, mat2, mat3 = self._get_bmm_inputs(B, M, N, K, chunk, dtype) + ref = torch.bmm(mat1, mat2) + mat2_t = mat2.transpose_(1, 2) + mat3.zero_() + torch.ops.sgl_kernel.bmm_cpu(mat3, mat1, mat2, False, None) + atol = rtol = precision[ref.dtype] + torch.testing.assert_close(ref, mat3, atol=atol, rtol=rtol) + + packed_B = torch.ops.sgl_kernel.convert_weight_packed(mat2_t) + mat3.zero_() + torch.ops.sgl_kernel.bmm_cpu(mat3, mat1, packed_B, True, None) + torch.testing.assert_close(ref, mat3, atol=atol, rtol=rtol) + + def _fp8_bmm(self, B, M, N, K, chunk, dtype=torch.bfloat16): + mat1, mat2, mat3 = self._get_bmm_inputs(B, M, N, K, chunk, dtype) + mat2_q, mat2_s = input_to_float8(mat2) + ref = torch.bmm(mat1, mat2_q.to(torch.bfloat16)) * mat2_s + mat2_q_t = mat2_q.transpose_(1, 2).contiguous() + mat3.zero_() + atol = rtol = precision[ref.dtype] + torch.ops.sgl_kernel.bmm_cpu(mat3, mat1, mat2_q_t, False, mat2_s) + torch.testing.assert_close(ref, mat3, atol=atol, rtol=rtol) + + packed_B_q = torch.ops.sgl_kernel.convert_weight_packed(mat2_q_t) + mat3.zero_() + torch.ops.sgl_kernel.bmm_cpu(mat3, mat1, packed_B_q, True, mat2_s) + torch.testing.assert_close(ref, mat3, atol=atol, rtol=rtol) + + def test_bmm(self): + for params in itertools.product( + self.B, + self.M, + self.N, + self.K, + self.chunk, + ): + with self.subTest( + B=params[0], + M=params[1], + N=params[2], + K=params[3], + chunk=params[4], + ): + self._bf16_bmm(*params) + self._fp8_bmm(*params) + + +if __name__ == "__main__": + unittest.main() diff --git a/asian_ai/performance/SGLang/test/registered/cpu/test_causal_conv1d.py b/asian_ai/performance/SGLang/test/registered/cpu/test_causal_conv1d.py new file mode 100644 index 0000000000000000000000000000000000000000..4336307ec36102051abf3af4819f226cfadcf012 --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/cpu/test_causal_conv1d.py @@ -0,0 +1,330 @@ +import unittest +from typing import Optional + +import sgl_kernel # noqa: F401 +import torch +import torch.nn.functional as F +from utils import parametrize, precision + +from sglang.test.ci.ci_register import register_cpu_ci +from sglang.test.test_utils import CustomTestCase + +register_cpu_ci(est_time=10, suite="base-b-test-cpu") + +causal_conv1d_weight_pack = torch.ops.sgl_kernel.causal_conv1d_weight_pack +causal_conv1d_fwd = torch.ops.sgl_kernel.causal_conv1d_fwd_cpu +causal_conv1d_update = torch.ops.sgl_kernel.causal_conv1d_update_cpu + + +torch.manual_seed(1234) + +PAD_SLOT_ID = -1 + + +def causal_conv1d_ref( + x: torch.Tensor, + weight: torch.Tensor, + bias: Optional[torch.Tensor] = None, + initial_states: Optional[torch.Tensor] = None, + return_final_states: bool = False, + final_states_out: Optional[torch.Tensor] = None, + activation: Optional[str] = "silu", +): + """ + x: (batch, dim, seqlen) + weight: (dim, width) + bias: (dim,) + initial_states: (batch, dim, width - 1) + final_states_out: (batch, dim, width - 1) + + out: (batch, dim, seqlen) + """ + if activation not in [None, "silu", "swish"]: + raise NotImplementedError("activation must be None, silu, or swish") + dtype_in = x.dtype + x = x.to(weight.dtype) + seqlen = x.shape[-1] + dim, width = weight.shape + if initial_states is None: + out = F.conv1d(x, weight.unsqueeze(1), bias, padding=width - 1, groups=dim) + else: + x = torch.cat([initial_states, x], dim=-1) + out = F.conv1d(x, weight.unsqueeze(1), bias, padding=0, groups=dim) + out = out[..., :seqlen] + if return_final_states: + final_states = F.pad(x, (width - 1 - x.shape[-1], 0)).to( + dtype_in + ) # (batch, dim, width - 1) + if final_states_out is not None: + final_states_out.copy_(final_states) + else: + final_states_out = final_states + out = (out if activation is None else F.silu(out)).to(dtype=dtype_in) + return (out, None) if not return_final_states else (out, final_states_out) + + +def causal_conv1d_update_ref( + x, conv_state, weight, bias=None, activation=None, cache_seqlens=None +): + """ + x: (batch, dim) or (batch, dim, seqlen) + conv_state: (batch, dim, state_len), where state_len >= width - 1 + weight: (dim, width) + bias: (dim,) + cache_seqlens: (batch,), dtype int32. + If not None, the conv_state is treated as a circular buffer. + The conv_state will be updated by copying x to the + conv_state starting at the index + @cache_seqlens % state_len before performing the convolution. + + out: (batch, dim) or (batch, dim, seqlen) + """ + if activation not in [None, "silu", "swish"]: + raise NotImplementedError("activation must be None, silu, or swish") + + x = x.unsqueeze(-1) + batch, dim, seqlen = x.shape + width = weight.shape[1] + state_len = conv_state.shape[-1] + + x_new = torch.cat([conv_state, x], dim=-1) + conv_state.copy_(x_new[:, :, -state_len:]) + out = F.conv1d(x_new, weight.unsqueeze(1), bias, padding=0, groups=dim)[ + :, :, -seqlen: + ] + + out = out.squeeze(-1) + return out if activation is None else F.silu(out) + + +class TestCausalConv1d(CustomTestCase): + activation = "silu" + + @parametrize( + batch=[1, 1024], + dim=[96, 512], + seqlen=[2, 36], + width=[4], + has_bias=[True, False], + has_initial_state=[True, False], + ) + def test_causal_conv1d( + self, + batch, + dim, + seqlen, + width, + has_bias, + has_initial_state, + dtype=torch.bfloat16, + prepack=True, + ): + x = torch.randn(batch, seqlen, dim).to(dtype).transpose_(-1, -2) + weight = torch.randn(dim, width).to(dtype) + bias = torch.randn(dim).to(dtype) if has_bias else None + + if has_initial_state: + initial_states = torch.randn(batch, dim, width - 1, dtype=dtype) + has_initial_state_tensor = torch.ones(batch, dtype=torch.bool) + else: + initial_states = None + has_initial_state_tensor = None + + packed_weight = causal_conv1d_weight_pack(weight) if prepack else weight + + out_ref, final_states_ref = causal_conv1d_ref( + x, + weight, + bias, + initial_states, + return_final_states=has_initial_state, + activation=self.activation, + ) + + out = causal_conv1d_fwd( + x, + packed_weight, + bias, + initial_states, + None, + None, + has_initial_state_tensor, + self.activation in ["silu"], + PAD_SLOT_ID, + prepack, + ) + + atol = rtol = precision[dtype] + torch.testing.assert_close(out_ref, out, atol=atol, rtol=rtol) + torch.testing.assert_close( + final_states_ref, initial_states, atol=atol, rtol=rtol + ) + + @parametrize( + batch=[11], + dim=[96], + max_seqlen=[66], + width=[4], + ) + def test_causal_conv1d_varlen( + self, + batch, + dim, + max_seqlen, + width, + has_bias=False, + dtype=torch.bfloat16, + prepack=False, + ): + total_entries = batch + 3 + + seqlens = torch.randint(1, max_seqlen, (batch + 1,)) + seqlens[0] = 0 + # 1 or 2 must test + seqlens[-2] = 2 + + query_start_loc = torch.cumsum(seqlens, dim=0).to(torch.int32) + + seqlen = query_start_loc[-1].item() + x = torch.randn(seqlen, dim, dtype=dtype).transpose_(-1, -2) + weight = torch.randn(dim, width, dtype=dtype) + bias = torch.randn(dim, dtype=dtype) if has_bias else None + + final_states = torch.randn(total_entries, dim, width - 1, dtype=dtype) + final_states_ref = final_states.clone() + + has_initial_states = torch.randint(0, 2, (batch,), dtype=torch.bool).fill_( + False + ) + state_indices = torch.randperm(total_entries, dtype=torch.int32)[:batch] + + out_ref = [] + out_ref_b = [] + + return_final_states = final_states is not None + splits = torch.split(x, seqlens[1:].tolist(), dim=1) + for i, x_s in enumerate(splits): + out_ref_b.append( + causal_conv1d_ref( + x_s.unsqueeze(0), + weight, + bias, + activation=self.activation, + return_final_states=return_final_states, + final_states_out=( + final_states_ref[state_indices[i]].unsqueeze(0) + if return_final_states + else None + ), + initial_states=( + final_states_ref[state_indices[i]].unsqueeze(0) + if has_initial_states[i] + else None + ), + ) + ) + out_ref.append(torch.cat([t[0] for t in out_ref_b], dim=2)) + out_ref_tensor = torch.cat(out_ref, dim=0).squeeze(0) + + out = causal_conv1d_fwd( + x, + weight, + bias, + final_states, + query_start_loc, + state_indices, + has_initial_states, + self.activation in ["silu"], + PAD_SLOT_ID, + prepack, + ) + + atol = rtol = precision[dtype] + torch.testing.assert_close(out_ref_tensor, out, atol=atol, rtol=rtol) + torch.testing.assert_close(final_states_ref, final_states, atol=atol, rtol=rtol) + + @parametrize( + batch=[11], + dim=[32, 64, 96], + width=[4], + ) + def test_causal_conv1d_update( + self, batch, dim, width, has_bias=False, dtype=torch.bfloat16, prepack=True + ): + x = torch.randn(batch, dim).to(dtype) + conv_state = torch.randn(batch, dim, width - 1, dtype=dtype) + weight = torch.randn(dim, width).to(dtype) + bias = torch.randn(dim).to(dtype) if has_bias else None + + packed_weight = causal_conv1d_weight_pack(weight) if prepack else weight + + conv_state_ref = conv_state.clone() + out_ref = causal_conv1d_update_ref( + x, conv_state_ref, weight, bias, activation=self.activation + ) + + cache_seqlens = None + conv_state_indices = None + out = causal_conv1d_update( + x, + conv_state, + packed_weight, + bias, + self.activation in ["silu"], + cache_seqlens, + conv_state_indices, + PAD_SLOT_ID, + prepack, + ) + + atol = rtol = precision[dtype] + torch.testing.assert_close(out_ref, out, atol=atol, rtol=rtol) + torch.testing.assert_close(conv_state_ref, conv_state, atol=atol, rtol=rtol) + + @parametrize( + batch=[7], + dim=[96], + width=[4], + ) + def test_causal_conv1d_update_with_batch_gather( + self, batch, dim, width, has_bias=False, dtype=torch.bfloat16, prepack=True + ): + total_entries = batch + 3 + + x = torch.randn(batch, dim).to(dtype=dtype) + + conv_state_indices = torch.randperm(total_entries)[:batch].to(dtype=torch.int32) + conv_state = torch.randn(total_entries, dim, width - 1, dtype=dtype) + + weight = torch.randn(dim, width).to(dtype=dtype) + bias = torch.randn(dim).to(dtype=dtype) if has_bias else None + conv_state_ref = conv_state[conv_state_indices, :] + + packed_weight = causal_conv1d_weight_pack(weight) if prepack else weight + + out_ref = causal_conv1d_update_ref( + x, conv_state_ref, weight, bias, activation=self.activation + ) + + cache_seqlens = None + out = causal_conv1d_update( + x, + conv_state, + packed_weight, + bias, + self.activation in ["silu"], + cache_seqlens, + conv_state_indices, + PAD_SLOT_ID, + prepack, + ) + + atol = rtol = precision[dtype] + torch.testing.assert_close(out_ref, out, atol=atol, rtol=rtol) + torch.testing.assert_close( + conv_state_ref, conv_state[conv_state_indices, :], atol=atol, rtol=rtol + ) + + +if __name__ == "__main__": + unittest.main() diff --git a/asian_ai/performance/SGLang/test/registered/cpu/test_cpu_graph.py b/asian_ai/performance/SGLang/test/registered/cpu/test_cpu_graph.py new file mode 100644 index 0000000000000000000000000000000000000000..8afba93fe3a9630ad420673fd54dd7cbe62fc02a --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/cpu/test_cpu_graph.py @@ -0,0 +1,91 @@ +""" +Usage: +python3 -m unittest test_cpu_graph.TestCPUGraph.test_mmlu_torch_compile_cpu +""" + +import copy +import os +import unittest +from types import SimpleNamespace + +from sglang.srt.utils import get_cpu_ids_by_node, kill_process_tree +from sglang.test.ci.ci_register import register_cpu_ci +from sglang.test.run_eval import run_eval +from sglang.test.test_utils import ( + DEFAULT_MLA_MODEL_NAME_FOR_TEST, + DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH, + DEFAULT_URL_FOR_TEST, + CustomTestCase, + intel_amx_benchmark, + is_in_ci, + popen_launch_server, +) + +register_cpu_ci(est_time=10, suite="base-b-test-cpu") + + +class TestCPUGraph(CustomTestCase): + + @intel_amx_benchmark( + extra_args=[ + "--batch-size", + "1", + "--mem-fraction-static", + "0.05", + "--enable-torch-compile", + "--torch-compile-max-bs", + "2", + "--cuda-graph-bs", + "2", + ], + min_throughput=7, + ) + def test_latency_torch_compile_cpu(self): + return DEFAULT_MLA_MODEL_NAME_FOR_TEST + + def test_mmlu_torch_compile_cpu(self): + model = DEFAULT_MLA_MODEL_NAME_FOR_TEST + base_url = DEFAULT_URL_FOR_TEST + cpu_ids_by_node = get_cpu_ids_by_node() + n_numa_node = len(cpu_ids_by_node) + env = copy.deepcopy(os.environ) + env["SGLANG_CPU_OMP_THREADS_BIND"] = "all" + process = popen_launch_server( + model, + base_url, + timeout=DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH, + other_args=[ + "--attention-backend", + "intel_amx", + "--mem-fraction-static", + "0.05", + "--disable-radix", + "--trust-remote-code", + "--disable-overlap-schedule", + "--enable-torch-compile", + "--cuda-graph-bs", + "2", + "--tp", + f"{n_numa_node}", + ], + env=env, + ) + + try: + args = SimpleNamespace( + base_url=base_url, + model=model, + eval_name="mmlu", + num_examples=64, + num_threads=32, + ) + + metrics = run_eval(args) + if is_in_ci(): + self.assertGreater(metrics["score"], 0.45) + finally: + kill_process_tree(process.pid) + + +if __name__ == "__main__": + unittest.main() diff --git a/asian_ai/performance/SGLang/test/registered/cpu/test_decode.py b/asian_ai/performance/SGLang/test/registered/cpu/test_decode.py new file mode 100644 index 0000000000000000000000000000000000000000..2bf01483503ab9c392dfa5bb1b272a7e619e9ca6 --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/cpu/test_decode.py @@ -0,0 +1,312 @@ +import unittest + +import torch +from torch.nn.functional import scaled_dot_product_attention + +from sglang.test.ci.ci_register import register_cpu_ci +from sglang.test.test_utils import CustomTestCase + +register_cpu_ci(est_time=10, suite="base-b-test-cpu") +register_cpu_ci(est_time=10, suite="base-b-test-cpu-arm64") + +torch.manual_seed(1234) + + +class TestDecodeAttention(CustomTestCase): + def _scaled_dot_product_attention(self, Q, K, V, S, scaling, sliding_window): + # sliding_window <= 0 means no sliding window + # Q: [n_tokens_q, n_heads, q_mult, d_head] + # K: [n_tokens_kv, n_heads, d_head] + # V: [n_tokens_kv, n_heads, d_head] + n_tokens_q, n_heads, q_mult, d_head = Q.shape + n_tokens_kv = K.shape[0] + assert K.shape == (n_tokens_kv, n_heads, d_head) + assert V.shape == (n_tokens_kv, n_heads, d_head) + K = K[:, :, None, :].expand(-1, -1, q_mult, -1) + V = V[:, :, None, :].expand(-1, -1, q_mult, -1) + S = S.reshape(n_heads, q_mult, 1, 1).expand(-1, -1, n_tokens_q, -1) + if n_tokens_q == n_tokens_kv: # Prefill + mask = torch.triu( + Q.new_full((n_tokens_q, n_tokens_kv), -float("inf")), diagonal=1 + ) + else: # Decode + mask = Q.new_zeros((n_tokens_q, n_tokens_kv)) + if sliding_window is not None and sliding_window > 0: + mask += torch.tril( + mask.new_full((n_tokens_q, n_tokens_kv), -float("inf")), + diagonal=n_tokens_kv - n_tokens_q - sliding_window, + ) + QK = torch.einsum("qhmd,khmd->hmqk", Q, K) + QK *= scaling + QK += mask[None, None, :, :] + QK = torch.cat([QK, S], dim=-1) + W = torch.softmax(QK, dim=-1) + W = W[..., :-1] + attn = torch.einsum("hmqk,khmd->qhmd", W, V) + return attn.reshape(n_tokens_q, -1) + + def _run_sdpa_forward_decode_sink( + self, + query: torch.Tensor, + output: torch.Tensor, + k_cache: torch.Tensor, + v_cache: torch.Tensor, + req_to_token: torch.Tensor, + req_pool_indices: torch.Tensor, + seq_lens: torch.Tensor, + num_kv_heads: int, + q_mult: int, + scaling=None, + sliding_window=None, + attention_sinks=None, + enable_gqa=False, + causal=False, + ): + # [num_tokens, num_heads, head_size] -> [num_heads, num_tokens, head_size] + query = query.movedim(0, query.dim() - 2) + start_q, start_kv = 0, 0 + for seq_idx in range(seq_lens.shape[0]): + # TODO: this loop process a sequence per iter, this is inefficient. + # Need optimize the performance later. + seq_len_q = 1 + seq_len_kv = seq_lens[seq_idx] + end_q = start_q + seq_len_q + end_kv = start_kv + seq_len_kv + per_req_query = query[:, start_q:end_q, :] + # get key and value from cache. per_req_tokens contains the kv cache + # index for each token in the sequence. + req_pool_idx = req_pool_indices[seq_idx] + per_req_tokens = req_to_token[req_pool_idx, :seq_len_kv] + + per_req_query = per_req_query.permute(1, 0, 2).reshape( + seq_len_q, num_kv_heads, q_mult, per_req_query.shape[-1] + ) + per_req_key = k_cache[per_req_tokens].movedim(0, query.dim() - 2) + per_req_value = v_cache[per_req_tokens].movedim(0, query.dim() - 2) + per_req_key = per_req_key.permute(1, 0, 2) + per_req_value = per_req_value.permute(1, 0, 2) + + per_req_out = self._scaled_dot_product_attention( + per_req_query, + per_req_key, + per_req_value, + attention_sinks, + scaling=scaling, + sliding_window=sliding_window, + ).reshape(seq_len_q, -1, per_req_value.shape[-1]) + output[start_q:end_q, :, :] = per_req_out + start_q, start_kv = end_q, end_kv + return output + + def _run_sdpa_forward_decode( + self, + query: torch.Tensor, + output: torch.Tensor, + k_cache: torch.Tensor, + v_cache: torch.Tensor, + req_to_token: torch.Tensor, + req_pool_indices: torch.Tensor, + seq_lens: torch.Tensor, + encoder_lens=None, + scaling=None, + enable_gqa=False, + causal=False, + is_cross_attn=False, + ): + # [num_tokens, num_heads, head_size] -> [num_heads, num_tokens, head_size] + query = query.movedim(0, query.dim() - 2) + + start_q, start_kv = 0, 0 + for seq_idx in range(seq_lens.shape[0]): + seq_len_q = 1 + seq_len_kv = seq_lens[seq_idx] + end_q = start_q + seq_len_q + if encoder_lens is not None: + start_kv = 0 if is_cross_attn else encoder_lens[seq_idx] + end_kv = ( + encoder_lens[seq_idx] if is_cross_attn else start_kv + seq_len_kv + ) + else: + start_kv = 0 + end_kv = start_kv + seq_len_kv + + per_req_query = query[:, start_q:end_q, :] + + # get key and value from cache. per_req_tokens contains the kv cache + # index for each token in the sequence. + req_pool_idx = req_pool_indices[seq_idx] + per_req_tokens = req_to_token[req_pool_idx, start_kv:end_kv] + per_req_key = k_cache[per_req_tokens].movedim(0, query.dim() - 2) + per_req_value = v_cache[per_req_tokens].movedim(0, query.dim() - 2) + + per_req_out = ( + scaled_dot_product_attention( + per_req_query.unsqueeze(0), + per_req_key.unsqueeze(0), + per_req_value.unsqueeze(0), + enable_gqa=enable_gqa, + scale=scaling, + is_causal=causal, + ) + .squeeze(0) + .movedim(query.dim() - 2, 0) + ) + output[start_q:end_q, :, :] = per_req_out + start_q, start_kv = end_q, end_kv + + return output + + def _test_grouped_decode_attention_once( + self, B, H_Q, H_KV, D, D_V, sliding_window, sink, is_cross_attn, dtype, device + ): + # This represents the number of tokens already in the sequence + seq_len = 1024 + encoder_len = 0 if sink else 10 + total_tokens = B * (seq_len + encoder_len) + sm_scale = 1.0 / (D**0.5) + logit_cap = 0.0 + num_kv_splits = 8 + enable_gqa = H_Q != H_KV + + # q represents the new token being generated, one per batch + q = torch.randn(B, H_Q, D, dtype=dtype, device=device) + sinks = torch.rand(H_Q, dtype=dtype, device=device) * 10 + + # k_buffer and v_buffer represent all previous tokens + k_buffer = torch.randn(total_tokens, H_KV, D, dtype=dtype, device=device) + v_buffer = torch.randn(total_tokens, H_KV, D_V, dtype=dtype, device=device) + + key = torch.randn(B, H_KV, D, dtype=dtype) + value = torch.randn(B, H_KV, D_V, dtype=dtype) + loc = torch.randint(0, 10, (B,)).to(torch.int64) + + # set kv cache + k_buffer[loc] = key + v_buffer[loc] = value + + # o will have the same shape as q + o = torch.zeros(B, H_Q, D_V, dtype=dtype, device=device) + o_grouped = torch.zeros(B, H_Q, D_V, dtype=dtype, device=device) + + req_to_token = ( + torch.arange(total_tokens, device=device) + .reshape(B, seq_len + encoder_len) + .to(torch.int32) + ) + b_req_idx = torch.arange(B, device=device).to(torch.int64) + b_seq_len = torch.full((B,), seq_len, device=device).to(torch.int64) + encoder_lens = torch.full((B,), encoder_len, device=device).to(torch.int64) + + attn_logits = torch.empty( + (B, H_Q, num_kv_splits, D_V + 1), + dtype=torch.float32, + device=device, + ) + + # k_buffer, v_buffer, query, key and value supports non-contiguous tensors + k_buffer = k_buffer.transpose(0, 1).contiguous().transpose(0, 1) + v_buffer = v_buffer.transpose(0, 1).contiguous().transpose(0, 1) + q = q.transpose(0, 1).contiguous().transpose(0, 1) + key = key.transpose(0, 1).contiguous().transpose(0, 1) + value = value.transpose(0, 1).contiguous().transpose(0, 1) + torch.ops.sgl_kernel.decode_attention_cpu( + q, + k_buffer, + v_buffer, + o, + key if not is_cross_attn else None, + value if not is_cross_attn else None, + loc, + attn_logits, + req_to_token, + b_req_idx, + b_seq_len, + sm_scale, + logit_cap, + is_cross_attn, + sliding_window if sliding_window is not None else 0, + encoder_lens, + sinks if sink else None, + ) + + if sink: + self._run_sdpa_forward_decode_sink( + q, + o_grouped, + k_buffer, + v_buffer, + req_to_token, + b_req_idx, + b_seq_len, + num_kv_heads=H_KV, + q_mult=H_Q // H_KV if enable_gqa else 1, + scaling=sm_scale, + sliding_window=sliding_window if sliding_window is not None else None, + attention_sinks=sinks, + enable_gqa=enable_gqa, + ) + else: + self._run_sdpa_forward_decode( + q, + o_grouped, + k_buffer, + v_buffer, + req_to_token, + b_req_idx, + b_seq_len, + scaling=sm_scale, + enable_gqa=enable_gqa, + encoder_lens=encoder_lens, + is_cross_attn=is_cross_attn, + ) + cos_sim = torch.nn.functional.cosine_similarity( + o.flatten(), o_grouped.flatten(), dim=0 + ) + self.assertGreater(cos_sim.item(), 0.99) + torch.testing.assert_close(o, o_grouped, atol=3e-2, rtol=1e-6) + + def _test_grouped_decode_attention(self, device="cuda"): + configs = [ + (2, 16, 16, 64, 64), + (2, 16, 1, 16, 16), + (2, 32, 8, 33, 55), + (2, 16, 1, 64, 64), + (2, 64, 1, 13, 13), + (2, 128, 1, 80, 80), + (2, 128, 2, 512, 512), + (1, 16, 1, 576, 512), + (1, 16, 16, 576, 512), + (1, 22, 1, 576, 512), + (1, 40, 8, 128, 128), + ] + + for B, H_Q, H_KV, D, D_V in configs: + for dtype in [torch.bfloat16, torch.float16]: + for sink in [True, False]: + if D != D_V and sink: + continue + for sliding_window in [None, 10]: + if sliding_window is not None and not sink: + continue + self._test_grouped_decode_attention_once( + B, + H_Q, + H_KV, + D, + D_V, + sliding_window, + sink, + False, + dtype=dtype, + device=device, + ) + self._test_grouped_decode_attention_once( + B, H_Q, H_KV, D, D_V, None, False, True, dtype=dtype, device=device + ) + + def test_grouped_decode_attention(self): + self._test_grouped_decode_attention("cpu") + + +if __name__ == "__main__": + unittest.main() diff --git a/asian_ai/performance/SGLang/test/registered/cpu/test_extend.py b/asian_ai/performance/SGLang/test/registered/cpu/test_extend.py new file mode 100644 index 0000000000000000000000000000000000000000..41b106fd9e9eccfe4d1da0ad65e750d90fdf9a4f --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/cpu/test_extend.py @@ -0,0 +1,403 @@ +import unittest + +import torch +from torch.nn.functional import scaled_dot_product_attention + +from sglang.test.ci.ci_register import register_cpu_ci +from sglang.test.test_utils import CustomTestCase + +register_cpu_ci(est_time=10, suite="base-b-test-cpu") + +torch.manual_seed(1234) + + +class TestExtendAttention(CustomTestCase): + def _scaled_dot_product_attention(self, Q, K, V, S, scaling, sliding_window): + # sliding_window <= 0 means no sliding window + # Q: [n_tokens_q, n_heads, q_mult, d_head] + # K: [n_tokens_kv, n_heads, d_head] + # V: [n_tokens_kv, n_heads, d_head] + n_tokens_q, n_heads, q_mult, d_head = Q.shape + n_tokens_kv = K.shape[0] + assert K.shape == (n_tokens_kv, n_heads, d_head) + assert V.shape == (n_tokens_kv, n_heads, d_head) + K = K[:, :, None, :].expand(-1, -1, q_mult, -1) + V = V[:, :, None, :].expand(-1, -1, q_mult, -1) + S = S.reshape(n_heads, q_mult, 1, 1).expand(-1, -1, n_tokens_q, -1) + if n_tokens_q == n_tokens_kv: # Prefill + mask = torch.triu( + Q.new_full((n_tokens_q, n_tokens_kv), -float("inf")), diagonal=1 + ) + else: # Decode + mask = Q.new_zeros((n_tokens_q, n_tokens_kv)) + if sliding_window is not None and sliding_window > 0: + mask += torch.tril( + mask.new_full((n_tokens_q, n_tokens_kv), -float("inf")), + diagonal=n_tokens_kv - n_tokens_q - sliding_window, + ) + QK = torch.einsum("qhmd,khmd->hmqk", Q, K) + QK *= scaling + QK += mask[None, None, :, :] + QK = torch.cat([QK, S], dim=-1) + W = torch.softmax(QK, dim=-1) + W = W[..., :-1] + attn = torch.einsum("hmqk,khmd->qhmd", W, V) + return attn.reshape(n_tokens_q, -1) + + def _run_sdpa_forward_extend( + self, + query: torch.Tensor, + output: torch.Tensor, + k_cache: torch.Tensor, + v_cache: torch.Tensor, + req_to_token: torch.Tensor, + req_pool_indices: torch.Tensor, + seq_lens: torch.Tensor, + extend_prefix_lens: torch.Tensor, + extend_seq_lens: torch.Tensor, + encoder_lens=None, + scaling=None, + enable_gqa=False, + causal=False, + is_cross_attn=False, + ): + + assert seq_lens.shape[0] == extend_prefix_lens.shape[0] + assert seq_lens.shape[0] == extend_seq_lens.shape[0] + + # [num_tokens, num_heads, head_size] -> [num_heads, num_tokens, head_size] + query = query.movedim(0, query.dim() - 2) + + start_q, start_kv = 0, 0 + for seq_idx in range(seq_lens.shape[0]): + + extend_seq_len_q = extend_seq_lens[seq_idx] + prefill_seq_len_q = extend_prefix_lens[seq_idx] + + seq_len_kv = seq_lens[seq_idx] + end_q = start_q + extend_seq_len_q + if encoder_lens is not None: + start_kv = 0 if is_cross_attn else encoder_lens[seq_idx] + end_kv = ( + encoder_lens[seq_idx] if is_cross_attn else start_kv + seq_len_kv + ) + else: + start_kv = 0 + end_kv = start_kv + seq_len_kv + + per_req_query = query[:, start_q:end_q, :] + per_req_query_redudant = torch.empty( + (per_req_query.shape[0], seq_len_kv, per_req_query.shape[2]), + dtype=per_req_query.dtype, + device=per_req_query.device, + ) + + per_req_query_redudant[:, prefill_seq_len_q:, :] = per_req_query + + # get key and value from cache. per_req_tokens contains the kv cache + # index for each token in the sequence. + req_pool_idx = req_pool_indices[seq_idx] + per_req_tokens = req_to_token[req_pool_idx, start_kv:end_kv] + per_req_key = k_cache[per_req_tokens].movedim(0, query.dim() - 2) + per_req_value = v_cache[per_req_tokens].movedim(0, query.dim() - 2) + + per_req_out_redudant = ( + scaled_dot_product_attention( + per_req_query_redudant.unsqueeze(0), + per_req_key.unsqueeze(0), + per_req_value.unsqueeze(0), + enable_gqa=enable_gqa, + scale=scaling, + is_causal=causal, + ) + .squeeze(0) + .movedim(query.dim() - 2, 0) + ) + output[start_q:end_q, :, :] = per_req_out_redudant[prefill_seq_len_q:, :, :] + start_q, start_kv = end_q, end_kv + return output + + def _run_sdpa_forward_extend_sink( + self, + query: torch.Tensor, + output: torch.Tensor, + k_cache: torch.Tensor, + v_cache: torch.Tensor, + req_to_token: torch.Tensor, + req_pool_indices: torch.Tensor, + seq_lens: torch.Tensor, + extend_prefix_lens: torch.Tensor, + extend_seq_lens: torch.Tensor, + num_kv_heads: int, + q_mult: int, + scaling=None, + sliding_window=None, + attention_sinks=None, + enable_gqa=False, + causal=False, + ): + assert seq_lens.shape[0] == extend_prefix_lens.shape[0] + assert seq_lens.shape[0] == extend_seq_lens.shape[0] + # [num_tokens, num_heads, head_size] -> [num_heads, num_tokens, head_size] + query = query.movedim(0, query.dim() - 2) + start_q, start_kv = 0, 0 + for seq_idx in range(seq_lens.shape[0]): + # TODO: this loop process a sequence per iter, this is inefficient. + # Need optimize the performance later. + extend_seq_len_q = extend_seq_lens[seq_idx] + prefill_seq_len_q = extend_prefix_lens[seq_idx] + seq_len_kv = seq_lens[seq_idx] + end_q = start_q + extend_seq_len_q + end_kv = start_kv + seq_len_kv + per_req_query = query[:, start_q:end_q, :] + per_req_query_redudant = torch.empty( + (per_req_query.shape[0], seq_len_kv, per_req_query.shape[2]), + dtype=per_req_query.dtype, + device=per_req_query.device, + ) + per_req_query_redudant[:, prefill_seq_len_q:, :] = per_req_query + + # get key and value from cache. per_req_tokens contains the kv cache + # index for each token in the sequence. + req_pool_idx = req_pool_indices[seq_idx] + per_req_tokens = req_to_token[req_pool_idx, :seq_len_kv] + per_req_key = k_cache[per_req_tokens].movedim(0, query.dim() - 2) + per_req_value = v_cache[per_req_tokens].movedim(0, query.dim() - 2) + + per_req_query_redudant = per_req_query_redudant.permute(1, 0, 2).reshape( + seq_len_kv, num_kv_heads, q_mult, per_req_query_redudant.shape[-1] + ) + per_req_key = per_req_key.permute(1, 0, 2) + per_req_value = per_req_value.permute(1, 0, 2) + per_req_out_redudant = self._scaled_dot_product_attention( + per_req_query_redudant, + per_req_key, + per_req_value, + attention_sinks, + scaling=scaling, + sliding_window=sliding_window, + ).reshape(seq_len_kv, -1, per_req_value.shape[-1]) + output[start_q:end_q, :, :] = per_req_out_redudant[prefill_seq_len_q:, :, :] + start_q, start_kv = end_q, end_kv + return output + + def _test_extend_attention_once( + self, + B, + N_CTX, + H_Q, + H_KV, + D, + DV, + sliding_window=None, + has_sink=False, + mla=False, + is_cross_attn=False, + *, + b_seq_len_prefix=None, + b_seq_len_extend=None, + ): + dtype = torch.bfloat16 + + if b_seq_len_prefix is None: + b_seq_len_prefix = torch.randint(1, N_CTX // 2, (B,), dtype=torch.int32) + else: + b_seq_len_prefix = torch.as_tensor(b_seq_len_prefix, dtype=torch.int32) + + encoder_lens = torch.randint(1, N_CTX // 2, (B,), dtype=torch.int64) + scale = 20 + if mla: + b_seq_len_prefix.zero_() + encoder_lens.zero_() + if has_sink: + encoder_lens.zero_() + scale = 1 + + if b_seq_len_extend is None: + b_seq_len_extend = torch.randint(1, N_CTX // 2, (B,), dtype=torch.int32) + else: + b_seq_len_extend = torch.as_tensor(b_seq_len_extend, dtype=torch.int32) + b_seq_len = b_seq_len_prefix + b_seq_len_extend + max_len_in_batch = ( + torch.max(b_seq_len, 0)[0].item() + torch.max(encoder_lens, 0)[0].item() + ) + + b_req_idx = torch.arange(B, dtype=torch.int32) + req_to_tokens = torch.empty((B, max_len_in_batch), dtype=torch.int32) + b_start_loc = torch.zeros((B,), dtype=torch.int32) + b_start_loc[1:] = torch.cumsum(b_seq_len[:-1] + encoder_lens[:-1], 0) + b_start_loc_extend = torch.zeros((B,), dtype=torch.int32) + b_start_loc_extend[1:] = torch.cumsum(b_seq_len_extend[:-1], 0) + + for i in range(B): + req_to_tokens[i, : b_seq_len[i] + encoder_lens[i]] = torch.arange( + b_start_loc[i], b_start_loc[i] + b_seq_len[i] + encoder_lens[i] + ) + + total_token_num = torch.sum(b_seq_len).item() + torch.sum(encoder_lens).item() + extend_token_num = torch.sum(b_seq_len_extend).item() + + H_BUF = 1 if mla else H_KV + k_buffer = torch.randn((total_token_num, H_BUF, D), dtype=dtype) + v_buffer = torch.randn((total_token_num, H_BUF, DV), dtype=dtype) + + k_extend = torch.empty((extend_token_num, H_KV, D), dtype=dtype) + v_extend = torch.empty((extend_token_num, H_KV, DV), dtype=dtype) + q_extend = torch.empty((extend_token_num, H_Q, D), dtype=dtype) + sinks = torch.rand(H_Q, dtype=dtype) + + for i in range(B): + extend_start_in_buffer = ( + b_start_loc[i] + b_seq_len_prefix[i] + encoder_lens[i] + ) + extend_end_in_buffer = b_start_loc[i] + b_seq_len[i] + encoder_lens[i] + extend_start = b_start_loc_extend[i] + extend_end = b_start_loc_extend[i] + b_seq_len_extend[i] + k_extend[extend_start:extend_end] = k_buffer[ + extend_start_in_buffer:extend_end_in_buffer + ] + v_extend[extend_start:extend_end] = v_buffer[ + extend_start_in_buffer:extend_end_in_buffer + ] + q_extend[extend_start:extend_end] = ( + torch.randn((b_seq_len_extend[i], H_Q, D), dtype=dtype) * scale + ) + + # q_extend, k_extend, v_extend, k_buffer and v_buffer supports non-contiguous tensors + q_extend = q_extend.transpose(0, 1).contiguous().transpose(0, 1) + k_extend = k_extend.transpose(0, 1).contiguous().transpose(0, 1) + v_extend = v_extend.transpose(0, 1).contiguous().transpose(0, 1) + k_buffer = k_buffer.transpose(0, 1).contiguous().transpose(0, 1) + v_buffer = v_buffer.transpose(0, 1).contiguous().transpose(0, 1) + + b_seq_len_extend = b_seq_len - b_seq_len_prefix + b_start_loc_extend = torch.zeros_like(b_seq_len) + b_start_loc_extend[1:] = torch.cumsum(b_seq_len_extend[:-1], 0) + max_len_extend = torch.max(b_seq_len_extend, 0)[0].item() + + sm_scale = 1.0 / (D**0.5) + logit_cap = 0.0 + + # handle index type + b_req_idx = b_req_idx.to(torch.int64) + b_seq_len = b_seq_len.to(torch.int64) + + enable_gqa = H_Q != H_KV + o_ref = torch.empty((extend_token_num, H_Q, DV), dtype=dtype) + if has_sink: + self._run_sdpa_forward_extend_sink( + q_extend, + o_ref, + k_buffer, + v_buffer, + req_to_tokens, + b_req_idx, + b_seq_len, + b_seq_len_prefix, + b_seq_len_extend, + H_KV, + H_Q // H_KV if enable_gqa else 1, + scaling=sm_scale, + sliding_window=sliding_window, + attention_sinks=sinks, + ) + else: + self._run_sdpa_forward_extend( + q_extend, + o_ref, + k_buffer, + v_buffer, + req_to_tokens, + b_req_idx, + b_seq_len, + b_seq_len_prefix, + b_seq_len_extend, + scaling=sm_scale, + enable_gqa=enable_gqa, + causal=not is_cross_attn, + is_cross_attn=is_cross_attn, + encoder_lens=encoder_lens, + ) + + o_extend = torch.empty((extend_token_num, H_Q, DV), dtype=dtype) + torch.ops.sgl_kernel.extend_attention_cpu( + q_extend, + k_extend, + v_extend, + o_extend, + k_buffer, + v_buffer, + req_to_tokens, + b_req_idx, + b_seq_len, + b_seq_len_extend, + b_start_loc_extend, + max_len_extend, + sm_scale, + logit_cap, + is_cross_attn, + sliding_window if sliding_window is not None else 0, + encoder_lens, + sinks if has_sink else None, + ) + + torch.testing.assert_close(o_ref, o_extend, atol=1e-2, rtol=1e-2) + + def test_extend_attention(self): + for is_mla in [True, False]: + for is_cross_attn in [True, False]: + if is_mla and is_cross_attn: + continue + self._test_extend_attention_once( + 1, 123, 1, 1, 128, 96, None, False, is_mla, is_cross_attn + ) + self._test_extend_attention_once( + 1, 123, 16, 1, 128, 96, None, False, is_mla, is_cross_attn + ) + self._test_extend_attention_once( + 4, 1230, 16, 4, 128, 96, None, False, is_mla, is_cross_attn + ) + self._test_extend_attention_once( + 1, 9000, 16, 1, 32, 32, None, False, is_mla, is_cross_attn + ) + for has_sink in [True, False]: + for sliding_window in [None, 10, 128]: + if not has_sink and sliding_window is not None: + continue + self._test_extend_attention_once( + 1, 123, 16, 4, 64, 64, sliding_window, has_sink, False, False + ) + self._test_extend_attention_once( + 1, 20, 16, 1, 64, 64, sliding_window, has_sink, False, False + ) + self._test_extend_attention_once( + 1, 20, 1, 1, 64, 64, sliding_window, has_sink, False, False + ) + + def test_extend_attention_large_seq_causal_mask(self): + self._test_extend_attention_once( + B=1, + N_CTX=5001, + H_Q=8, + H_KV=2, + D=64, + DV=64, + b_seq_len_prefix=[0], + b_seq_len_extend=[5000], + ) + + def test_extend_attention_gqa_partial_extend_with_prefix(self): + self._test_extend_attention_once( + B=1, + N_CTX=256, + H_Q=16, + H_KV=4, + D=128, + DV=96, + b_seq_len_prefix=[97], + b_seq_len_extend=[37], + ) + + +if __name__ == "__main__": + unittest.main() diff --git a/asian_ai/performance/SGLang/test/registered/cpu/test_flash_attn.py b/asian_ai/performance/SGLang/test/registered/cpu/test_flash_attn.py new file mode 100644 index 0000000000000000000000000000000000000000..b09ac003ba1123ea213c498b4c76b34e431073ea --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/cpu/test_flash_attn.py @@ -0,0 +1,245 @@ +import unittest + +import sgl_kernel # noqa: F401 +import torch +import torch.nn.functional as F +from utils import parametrize, precision + +from sglang.test.ci.ci_register import register_cpu_ci +from sglang.test.test_utils import CustomTestCase + +register_cpu_ci(est_time=10, suite="base-b-test-cpu") + +flash_attn_varlen_func = torch.ops.sgl_kernel.flash_attn_varlen_func + +torch.manual_seed(1234) + + +def flash_attn_varlen_ref( + q, + k, + v, + cu_seqlens_q, + cu_seqlens_k, + is_causal, + enable_gqa, +): + cu_q = cu_seqlens_q.tolist() + cu_k = cu_seqlens_k.tolist() + batch = len(cu_k) - 1 + + # [T, H, D] -> [1, H, T, D] + q, k, v = [x.unsqueeze(0).transpose(1, 2) for x in [q, k, v]] + + B, H, T, D = q.shape + out = torch.empty(B, H, T, v.size(-1), dtype=q.dtype) + for b in range(batch): + start_q, end_q = cu_q[b], cu_q[b + 1] + start_k, end_k = cu_k[b], cu_k[b + 1] + + out[:, :, start_q:end_q, :] = F.scaled_dot_product_attention( + q[:, :, start_q:end_q, :], + k[:, :, start_k:end_k, :], + v[:, :, start_k:end_k, :], + is_causal=is_causal, + enable_gqa=enable_gqa, + ) + + # [1, H, T, D] -> [T, H, D] + return out.transpose(1, 2).squeeze(0) + + +# faster version ref kernel for non varlen case +def flash_attn_non_varlen_ref( + q, + k, + v, + cu_seqlens_q, + cu_seqlens_k, + is_causal, + enable_gqa, +): + cu_q = cu_seqlens_q.tolist() + cu_k = cu_seqlens_k.tolist() + batch = len(cu_k) - 1 + + B_T, H, D = q.shape + T = B_T // batch + + # [T, H, D] -> [1, H, T, D] + q, k, v = [x.reshape(batch, T, H, D).transpose(1, 2) for x in [q, k, v]] + + out = F.scaled_dot_product_attention( + q, + k, + v, + is_causal=is_causal, + enable_gqa=enable_gqa, + ) + # [B, H, T, D] -> [B * T, H, D] + return out.transpose(1, 2).reshape(batch * T, H, D) + + +class TestFlashAttn(CustomTestCase): + + @parametrize( + batch=[4], + max_seqlen_q=[35, 96], + max_seqlen_k=[35, 96], + num_heads=[16], + num_heads_kv=[16, 2], + head_dim=[32, 48], # test when D is not 32x + head_dim_v=[32], + is_causal=[True, False], + ) + def test_flash_attn_varlen( + self, + batch, + max_seqlen_q, + max_seqlen_k, + num_heads, + num_heads_kv, + head_dim, + head_dim_v, + is_causal, + ): + dtype = torch.bfloat16 + + # random seqlens for k and kv + seqlens_q = torch.randint(1, max_seqlen_q, (batch,), dtype=torch.int32) + seqlens_k = torch.randint(1, max_seqlen_k, (batch,), dtype=torch.int32) + cu_seqlens_q = torch.zeros((batch + 1,), dtype=torch.int32) + cu_seqlens_k = torch.zeros((batch + 1,), dtype=torch.int32) + cu_seqlens_q[1:] = torch.cumsum(seqlens_q, 0) + cu_seqlens_k[1:] = torch.cumsum(seqlens_k, 0) + + sum_seqlen_q = seqlens_q.sum().item() + sum_seqlen_k = seqlens_k.sum().item() + q = torch.randn(sum_seqlen_q, num_heads, head_dim).to(dtype) + k = torch.randn(sum_seqlen_k, num_heads_kv, head_dim).to(dtype) + v = torch.randn(sum_seqlen_k, num_heads_kv, head_dim_v).to(dtype) + + out_ref = flash_attn_varlen_ref( + q, + k, + v, + cu_seqlens_q, + cu_seqlens_k, + is_causal=is_causal, + enable_gqa=num_heads != num_heads_kv, + ) + + out = flash_attn_varlen_func( + q, + k, + v, + cu_seqlens_q, + cu_seqlens_k, + seqlens_q.max().item(), + seqlens_k.max().item(), + is_causal, + ) + + atol = rtol = precision[dtype] + torch.testing.assert_close(out_ref, out, atol=atol, rtol=rtol) + + # test with large size to capture overflow issue + @parametrize( + batch=[4097], + max_seqlen_q=[4097], + max_seqlen_k=[4097], + num_heads=[4], + num_heads_kv=[4], + head_dim=[32], + head_dim_v=[32], + is_causal=[False], + ) + def test_flash_attn_large_size( + self, + batch, + max_seqlen_q, + max_seqlen_k, + num_heads, + num_heads_kv, + head_dim, + head_dim_v, + is_causal, + ): + dtype = torch.bfloat16 + + # test the non varlen case + seqlens_q = torch.full((batch,), max_seqlen_q, dtype=torch.int32) + seqlens_k = torch.full((batch,), max_seqlen_k, dtype=torch.int32) + + cu_seqlens_q = torch.zeros((batch + 1,), dtype=torch.int32) + cu_seqlens_k = torch.zeros((batch + 1,), dtype=torch.int32) + cu_seqlens_q[1:] = torch.cumsum(seqlens_q, 0) + cu_seqlens_k[1:] = torch.cumsum(seqlens_k, 0) + + sum_seqlen_q = seqlens_q.sum().item() + sum_seqlen_k = seqlens_k.sum().item() + q = torch.randn(sum_seqlen_q, num_heads, head_dim).to(dtype) + k = torch.randn(sum_seqlen_k, num_heads_kv, head_dim).to(dtype) + v = torch.randn(sum_seqlen_k, num_heads_kv, head_dim_v).to(dtype) + + out_ref = flash_attn_non_varlen_ref( + q, + k, + v, + cu_seqlens_q, + cu_seqlens_k, + is_causal=is_causal, + enable_gqa=num_heads != num_heads_kv, + ) + + out = flash_attn_varlen_func( + q, + k, + v, + cu_seqlens_q, + cu_seqlens_k, + seqlens_q.max().item(), + seqlens_k.max().item(), + is_causal, + ) + + atol = rtol = precision[dtype] + torch.testing.assert_close(out_ref, out, atol=atol, rtol=rtol) + + def _test_flash_attn_large_seq_causal_mask_once(self, seqlens): + dtype = torch.bfloat16 + num_heads = 8 + num_heads_kv = 2 + head_dim = 64 + + seqlens_t = torch.tensor(seqlens, dtype=torch.int32) + cu_seqlens = torch.zeros(len(seqlens) + 1, dtype=torch.int32) + cu_seqlens[1:] = torch.cumsum(seqlens_t, 0) + total = cu_seqlens[-1].item() + max_seqlen = seqlens_t.max().item() + + q = torch.randn(total, num_heads, head_dim, dtype=dtype) + k = torch.randn(total, num_heads_kv, head_dim, dtype=dtype) + v = torch.randn(total, num_heads_kv, head_dim, dtype=dtype) + + out_ref = flash_attn_varlen_ref( + q, k, v, cu_seqlens, cu_seqlens, is_causal=True, enable_gqa=True + ) + out = flash_attn_varlen_func( + q, k, v, cu_seqlens, cu_seqlens, max_seqlen, max_seqlen, True + ) + + atol = rtol = precision[dtype] + torch.testing.assert_close(out_ref, out, atol=atol, rtol=rtol) + + def test_flash_attn_large_seq_causal_mask(self): + # Non-varlen path: single sequence, has_varlen_sequences returns False + # → dispatches to flash_attn_kernel_impl. + self._test_flash_attn_large_seq_causal_mask_once([5000]) + # Varlen path: sequences with different lengths, has_varlen_sequences + # returns True → dispatches to flash_attn_varlen_kernel_impl + self._test_flash_attn_large_seq_causal_mask_once([5000, 4999]) + + +if __name__ == "__main__": + unittest.main() diff --git a/asian_ai/performance/SGLang/test/registered/cpu/test_gemm.py b/asian_ai/performance/SGLang/test/registered/cpu/test_gemm.py new file mode 100644 index 0000000000000000000000000000000000000000..fd709e987d54b7923b4d71cb08bfe1ab98cb3dea --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/cpu/test_gemm.py @@ -0,0 +1,288 @@ +import unittest + +# TODO: use interface in cpu.py +import torch +import torch.nn as nn +from utils import ( + MXFP4QuantizeUtil, + convert_weight, + native_w8a8_per_token_matmul, + parametrize, + per_token_quant_int8, + precision, + unpack_and_dequant_awq, + unpack_and_dequant_gptq, +) + +from sglang.test.ci.ci_register import register_cpu_ci +from sglang.test.test_utils import CustomTestCase + +register_cpu_ci(est_time=10, suite="base-b-test-cpu") + +torch.manual_seed(1234) + + +class Mod(nn.Module): + def __init__(self, input_channel, output_channel, has_bias): + super(Mod, self).__init__() + self.linear = torch.nn.Linear(input_channel, output_channel, has_bias) + + def forward(self, x): + return self.linear(x) + + +class TestGemm(CustomTestCase): + + @parametrize( + M=[1, 101], + N=[16, 32 * 13], + K=[32 * 16], + has_bias=[False, True], + dim=[2, 3, 4, 5], + ) + def test_bf16_gemm(self, M, N, K, has_bias, dim): + mat1 = torch.randn(M, K, dtype=torch.bfloat16) + mat2 = torch.randn(N, K, dtype=torch.bfloat16) + if dim == 3: + mat1 = mat1.unsqueeze(0).repeat(2, 1, 1) + if dim == 4: + mat1 = mat1.unsqueeze(0).unsqueeze(0).repeat(2, 2, 1, 1) + if dim == 5: + mat1 = mat1.unsqueeze(0).unsqueeze(0).unsqueeze(0).repeat(2, 2, 2, 1, 1) + + ref = torch.matmul(mat1.float(), mat2.float().t()) + if has_bias: + bias = torch.randn(N, dtype=torch.float32) + ref.add_(bias.bfloat16()) + + ref = ref.bfloat16() + + out = torch.ops.sgl_kernel.weight_packed_linear( + mat1, mat2, bias if has_bias else None, False + ) + + packed_mat2 = torch.ops.sgl_kernel.convert_weight_packed(mat2) + out2 = torch.ops.sgl_kernel.weight_packed_linear( + mat1, packed_mat2, bias if has_bias else None, True + ) + + atol = rtol = precision[ref.dtype] + torch.testing.assert_close(ref, out, atol=atol, rtol=rtol) + torch.testing.assert_close(ref, out2, atol=atol, rtol=rtol) + + @parametrize( + M=[1, 8, 32, 1024], + N=[12, 1], + K=[32 * 16], + has_bias=[False, True], + use_post_sigmul=[False, True], + ) + def bf16_gemm_with_small_oc(self, M, N, K, has_bias, use_post_sigmul): + use_post_sigmul = use_post_sigmul and N == 1 + mat_mul = ( + None if not use_post_sigmul else torch.randn(M, 2 * K, dtype=torch.bfloat16) + ) + mat1 = torch.randn(M, K, dtype=torch.bfloat16) + mat2 = torch.randn(N, K, dtype=torch.bfloat16) + + ref = torch.nn.functional.linear(mat1, mat2) + if has_bias: + bias = torch.randn(N, dtype=torch.float32) + ref.add_(bias) + if use_post_sigmul: + ref = torch.nn.functional.sigmoid(ref) * mat_mul + out = torch.ops.sgl_kernel.fused_linear_sigmoid_mul( + mat1, + torch.ops.sgl_kernel.convert_weight_packed(mat2), + bias if has_bias else None, + True, + mat_mul if use_post_sigmul else None, + ) + else: + out = torch.ops.sgl_kernel.weight_packed_linear( + mat1, + torch.ops.sgl_kernel.convert_weight_packed(mat2), + bias if has_bias else None, + True, + ) + atol = rtol = precision[ref.dtype] + torch.testing.assert_close(ref, out, atol=atol, rtol=rtol) + + @parametrize(M=[2, 128], N=[32 * 12], K=[32 * 17], has_bias=[False, True]) + def test_int8_gemm(self, M, N, K, has_bias): + dtype = torch.bfloat16 + A = torch.randn((M, K), dtype=dtype) / 10 + Aq, As = per_token_quant_int8(A) + + factor_for_scale = 1e-2 + int8_max = 127 + int8_min = -128 + + B = (torch.rand((N, K), dtype=torch.float32) - 0.5) * 2 + Bq = (B * int8_max).clamp(min=int8_min, max=int8_max).to(torch.int8) + Bs = torch.rand(N) * factor_for_scale + + bias = torch.randn(N) if has_bias else None + ref_out = native_w8a8_per_token_matmul(Aq, Bq, As, Bs, bias, dtype) + + atol = rtol = precision[ref_out.dtype] + + Aq2, As2 = torch.ops.sgl_kernel.per_token_quant_int8_cpu(A) + out = torch.ops.sgl_kernel.int8_scaled_mm_cpu( + Aq2, Bq, As2, Bs, bias if has_bias else None, torch.bfloat16, False + ) + torch.testing.assert_close(ref_out, out, atol=atol, rtol=rtol) + + # test the fused version + fused_out = torch.ops.sgl_kernel.int8_scaled_mm_with_quant( + A, Bq, Bs, bias if has_bias else None, torch.bfloat16, False + ) + torch.testing.assert_close(ref_out, fused_out, atol=atol, rtol=rtol) + + @parametrize(M=[1, 11], N=[128, 224], K=[512, 576], has_bias=[False, True]) + def test_fp8_gemm(self, M, N, K, has_bias): + prepack = True + chunk = False + scale_block_size_N = 64 + scale_block_size_K = 128 + assert scale_block_size_N <= N + assert scale_block_size_K <= K + dtype = torch.bfloat16 + + model = Mod(K, N, has_bias).eval() + if chunk: + data = torch.randn(M, K + 6, dtype=dtype).narrow(1, 0, K) + else: + data = torch.randn(M, K, dtype=dtype) + + weight = model.linear.weight # (N, K) + + if has_bias: + bias = model.linear.bias + + fp8_weight, scales, dq_weight = convert_weight( + weight, [scale_block_size_N, scale_block_size_K], dtype + ) + + if has_bias: + ref = torch.matmul(data.to(dtype), dq_weight.T) + bias.to(dtype) + else: + ref = torch.matmul(data.to(dtype), dq_weight.T) + + if prepack: + fp8_weight = torch.ops.sgl_kernel.convert_weight_packed(fp8_weight) + + out = torch.ops.sgl_kernel.fp8_scaled_mm_cpu( + data, + fp8_weight, + scales, + [scale_block_size_N, scale_block_size_K], + bias if has_bias else None, + data.dtype, + prepack, + ) + atol = rtol = precision[ref.dtype] + torch.testing.assert_close(ref, out, atol=atol, rtol=rtol) + + @parametrize(M=[1, 11], N=[128, 224], K=[512, 576], has_bias=[False, True]) + def test_mxfp4_gemm(self, M, N, K, has_bias): + prepack = True + dtype = torch.bfloat16 + + A = torch.randn((M, K), dtype=dtype) / 10 + + # we randomly generate Bq and Bs, then dequantize it to BFloat16 as reference + Bq = torch.randint(0, 256, (N, K // 2), dtype=torch.uint8) + Bs = torch.randint(126, 127, (N, K // 32), dtype=torch.uint8) + + Bdq = MXFP4QuantizeUtil.dequantize(Bq, dtype, Bs) + + B_packed = torch.ops.sgl_kernel.convert_weight_packed(Bq) + Bs_packed = torch.ops.sgl_kernel.convert_scale_packed(Bs) + + bias = torch.randn(N) if has_bias else None + + ref = torch.matmul(A.float(), Bdq.float().t()).bfloat16() + if bias is not None: + ref.add_(bias.view(1, -1)) + + out = torch.ops.sgl_kernel.mxfp4_scaled_mm_cpu( + A, B_packed, Bs_packed, bias, prepack + ) + + atol = rtol = precision[ref.dtype] + torch.testing.assert_close(ref, out, atol=atol, rtol=rtol) + + @parametrize( + M=[1, 32], N=[4096], K=[4096], group_size=[128], has_bias=[False, True] + ) + def test_int4_awq_gemm(self, M, N, K, group_size, has_bias): + awq_weight = torch.randint(-128, 128, (K, N // 8)).to(torch.int) + awq_zero = torch.randint(0, 10, (K // group_size, N // 8)).to(torch.int) + awq_scales = torch.rand(int(K // group_size), N).to(torch.bfloat16) + bf16_weight, _ = unpack_and_dequant_awq( + awq_weight, awq_zero, awq_scales, 4, 128 + ) + if has_bias: + bias = torch.rand(bf16_weight.shape[0]).to(torch.float) + else: + bias = None + x = torch.rand(M, bf16_weight.size(-1)).to(torch.bfloat16) + ref_res = torch.nn.functional.linear( + x, bf16_weight, bias=bias.to(torch.bfloat16) if has_bias else None + ) + + packed_weight, packed_zero, packed_scales = ( + torch.ops.sgl_kernel.convert_weight_packed_scale_zp( + awq_weight, awq_zero, awq_scales, 0 + ) + ) + target_res = torch.ops.sgl_kernel.int4_scaled_mm_cpu( + x, + packed_weight, + packed_zero, + packed_scales, + bias, + ) + + atol = rtol = precision[ref_res.dtype] + torch.testing.assert_close(ref_res, target_res, atol=atol, rtol=rtol) + + @parametrize( + M=[1, 32], N=[4096], K=[4096], group_size=[128], has_bias=[False, True] + ) + def test_int4_gptq_gemm(self, M, N, K, group_size, has_bias): + torch.manual_seed(127) + gptq_weight = torch.randint(-128, 128, (K // 8, N)).to(torch.int) + gptq_zero = torch.randint(0, 10, (K // group_size, N // 8)).to(torch.int) + gptq_scales = torch.rand(int(K // group_size), N).to(torch.bfloat16) // 10 + + bf16_weight = unpack_and_dequant_gptq(gptq_weight, gptq_zero, gptq_scales) + if has_bias: + bias = torch.rand(bf16_weight.shape[0]).to(torch.float) + else: + bias = None + x = torch.rand(M, bf16_weight.size(-1)).to(torch.bfloat16) + ref_res = torch.nn.functional.linear( + x, bf16_weight, bias=bias.to(torch.bfloat16) if has_bias else None + ) + + packed_weight, packed_zero, packed_scales = ( + torch.ops.sgl_kernel.convert_weight_packed_scale_zp( + gptq_weight, gptq_zero, gptq_scales, 1 + ) + ) + target_res = torch.ops.sgl_kernel.int4_scaled_mm_cpu( + x, + packed_weight, + packed_zero, + packed_scales, + bias, + ) + + atol = rtol = precision[ref_res.dtype] + torch.testing.assert_close(ref_res, target_res, atol=atol, rtol=rtol) + + +if __name__ == "__main__": + unittest.main() diff --git a/asian_ai/performance/SGLang/test/registered/cpu/test_intel_amx_attention_backend_a.py b/asian_ai/performance/SGLang/test/registered/cpu/test_intel_amx_attention_backend_a.py new file mode 100644 index 0000000000000000000000000000000000000000..17bbd50b782a2e4fbacfa3a20ad0910cef1995c1 --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/cpu/test_intel_amx_attention_backend_a.py @@ -0,0 +1,76 @@ +""" +Usage: +python3 -m unittest test_intel_amx_attention_backend.TestIntelAMXAttnBackend.test_latency_default_model +""" + +import unittest +from types import SimpleNamespace + +from sglang.srt.utils import kill_process_tree +from sglang.test.ci.ci_register import register_cpu_ci +from sglang.test.run_eval import run_eval +from sglang.test.test_utils import ( + DEFAULT_MLA_MODEL_NAME_FOR_TEST, + DEFAULT_MODEL_NAME_FOR_TEST, + DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH, + DEFAULT_URL_FOR_TEST, + CustomTestCase, + intel_amx_benchmark, + is_in_ci, + popen_launch_server, +) + +register_cpu_ci(est_time=10, suite="base-b-test-cpu") + + +class TestIntelAMXAttnBackend(CustomTestCase): + + @intel_amx_benchmark( + extra_args=["--batch-size", "4", "--mem-fraction-static", "0.3"], + min_throughput=10, + ) + def test_latency_mla_model(self): + return DEFAULT_MLA_MODEL_NAME_FOR_TEST + + @intel_amx_benchmark( + extra_args=["--batch-size", "4", "--mem-fraction-static", "0.1"], + min_throughput=40, + ) + def test_latency_default_model(self): + return DEFAULT_MODEL_NAME_FOR_TEST + + def test_mmlu(self): + model = DEFAULT_MLA_MODEL_NAME_FOR_TEST + base_url = DEFAULT_URL_FOR_TEST + process = popen_launch_server( + model, + base_url, + timeout=DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH, + other_args=[ + "--attention-backend", + "intel_amx", + "--mem-fraction-static", + "0.3", + "--disable-radix", + "--trust-remote-code", + "--disable-overlap-schedule", + ], + ) + + try: + args = SimpleNamespace( + base_url=base_url, + model=model, + eval_name="mmlu", + num_examples=64, + num_threads=32, + ) + metrics = run_eval(args) + if is_in_ci(): + self.assertGreater(metrics["score"], 0.45) + finally: + kill_process_tree(process.pid) + + +if __name__ == "__main__": + unittest.main() diff --git a/asian_ai/performance/SGLang/test/registered/cpu/test_intel_amx_attention_backend_b.py b/asian_ai/performance/SGLang/test/registered/cpu/test_intel_amx_attention_backend_b.py new file mode 100644 index 0000000000000000000000000000000000000000..48aa0f6aa70e579777412e2643089d84930defac --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/cpu/test_intel_amx_attention_backend_b.py @@ -0,0 +1,38 @@ +""" +For intel_amx attention backend FP8 tests +Usage: +python3 -m unittest test_intel_amx_attention_backend_1.TestIntelAMXAttnBackendQuant.test_latency_fp8_qwen +""" + +import unittest + +from sglang.test.ci.ci_register import register_cpu_ci +from sglang.test.test_utils import ( + DEFAULT_MODEL_NAME_FOR_TEST_FP8_WITH_MOE, + DEFAULT_MODEL_NAME_FOR_TEST_QWEN_FP8, + CustomTestCase, + intel_amx_benchmark, +) + +register_cpu_ci(est_time=10, suite="base-b-test-cpu") + + +class TestIntelAMXAttnBackendQuant(CustomTestCase): + + @intel_amx_benchmark( + extra_args=["--batch-size", "4", "--mem-fraction-static", "0.1"], + min_throughput=150, + ) + def test_latency_fp8_qwen(self): + return DEFAULT_MODEL_NAME_FOR_TEST_QWEN_FP8 + + @intel_amx_benchmark( + extra_args=["--batch-size", "4", "--mem-fraction-static", "0.1"], + min_throughput=50, + ) + def test_latency_fp8_moe_model(self): + return DEFAULT_MODEL_NAME_FOR_TEST_FP8_WITH_MOE + + +if __name__ == "__main__": + unittest.main() diff --git a/asian_ai/performance/SGLang/test/registered/cpu/test_intel_amx_attention_backend_c.py b/asian_ai/performance/SGLang/test/registered/cpu/test_intel_amx_attention_backend_c.py new file mode 100644 index 0000000000000000000000000000000000000000..0eff553391e8b13b43f90da42551db6e678321a6 --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/cpu/test_intel_amx_attention_backend_c.py @@ -0,0 +1,56 @@ +""" +For intel_amx attention backend w8a8 tests +Usage: +python3 -m unittest test_intel_amx_attention_backend_2.TestIntelAMXAttnBackendQuant.test_latency_w8a8_default_model +""" + +import unittest + +from sglang.test.ci.ci_register import register_cpu_ci +from sglang.test.test_utils import ( + DEFAULT_MODEL_NAME_FOR_TEST_W8A8, + DEFAULT_MODEL_NAME_FOR_TEST_W8A8_WITH_MOE, + CustomTestCase, + intel_amx_benchmark, +) + +register_cpu_ci(est_time=10, suite="base-b-test-cpu") + + +class TestIntelAMXAttnBackendQuant(CustomTestCase): + + @intel_amx_benchmark( + extra_args=[ + "--batch-size", + "4", + "--quantization", + "w8a8_int8", + "--mem-fraction-static", + "0.1", + ], + min_throughput=100, + ) + def test_latency_w8a8_default_model(self): + return DEFAULT_MODEL_NAME_FOR_TEST_W8A8 + + @intel_amx_benchmark( + extra_args=[ + "--batch-size", + "4", + "--quantization", + "w8a8_int8", + "--mem-fraction-static", + "0.9", + "--max-total-tokens", + "65536", + "--tp", + "6", + ], + min_throughput=100, + ) + def test_latency_w8a8_moe_model(self): + return DEFAULT_MODEL_NAME_FOR_TEST_W8A8_WITH_MOE + + +if __name__ == "__main__": + unittest.main() diff --git a/asian_ai/performance/SGLang/test/registered/cpu/test_mamba.py b/asian_ai/performance/SGLang/test/registered/cpu/test_mamba.py new file mode 100644 index 0000000000000000000000000000000000000000..ec2f33e5a68bdfda0ea298d7e80b4687d7626ea5 --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/cpu/test_mamba.py @@ -0,0 +1,448 @@ +import unittest + +import torch +import torch.nn.functional as F +from torch.nn.functional import softplus +from utils import parametrize, precision + +from sglang.test.ci.ci_register import register_cpu_ci +from sglang.test.test_utils import CustomTestCase + +register_cpu_ci(est_time=10, suite="base-b-test-cpu") + +torch.manual_seed(1234) + +# [NB]: State-layout convention for this test file: +# - CPU kernel path in fla.cpp uses VK state layout, same as triton impl. +# - Torch naive reference follows KV semantics from: +# https://github.com/fla-org/flash-linear-attention/blob/main/fla/ops/gated_delta_rule/naive.py +# - Transposes in these tests only bridge VK (kernel-facing) and KV (ref-facing) views. + + +def l2norm(x: torch.Tensor, dim: int = -1, eps: float = 1e-6): + """This function is intended to align with the l2norm implementation in the FLA library.""" + inv_norm = torch.rsqrt((x * x).sum(dim=dim, keepdim=True) + eps) + return x * inv_norm + + +def torch_chunk_gated_delta_rule( + query, + key, + value, + g, + beta, + chunk_size=64, + initial_state=None, + output_final_state=False, + use_qk_l2norm_in_kernel=False, +): + initial_dtype = query.dtype + if use_qk_l2norm_in_kernel: + query = l2norm(query, dim=-1, eps=1e-6) + key = l2norm(key, dim=-1, eps=1e-6) + query, key, value, beta, g = [ + x.transpose(1, 2).contiguous().to(torch.float32) + for x in (query, key, value, beta, g) + ] + + batch_size, sequence_length, num_heads, k_head_dim = key.shape + v_head_dim = value.shape[-1] + pad_size = (chunk_size - num_heads % chunk_size) % chunk_size + query = F.pad(query, (0, 0, 0, pad_size)) + key = F.pad(key, (0, 0, 0, pad_size)) + value = F.pad(value, (0, 0, 0, pad_size)) + beta = F.pad(beta, (0, pad_size)) + g = F.pad(g, (0, pad_size)) + tot_heads = num_heads + pad_size + scale = 1 / (query.shape[-1] ** 0.5) + query = query * scale + + v_beta = value * beta.unsqueeze(-1) + k_beta = key * beta.unsqueeze(-1) + # reshape to chunks + query, key, value, k_beta, v_beta = [ + x.reshape(x.shape[0], x.shape[1], -1, chunk_size, x.shape[-1]) + for x in (query, key, value, k_beta, v_beta) + ] + g = g.reshape(g.shape[0], g.shape[1], -1, chunk_size) + mask = torch.triu( + torch.ones(chunk_size, chunk_size, dtype=torch.bool, device=query.device), + diagonal=0, + ) + + # chunk decay + g = g.cumsum(dim=-1) + decay_mask = ((g.unsqueeze(-1) - g.unsqueeze(-2)).tril().exp().float()).tril() + attn = -((k_beta @ key.transpose(-1, -2)) * decay_mask).masked_fill(mask, 0) + for i in range(1, chunk_size): + row = attn[..., i, :i].clone() + sub = attn[..., :i, :i].clone() + attn[..., i, :i] = row + (row.unsqueeze(-1) * sub).sum(-2) + attn = attn + torch.eye(chunk_size, dtype=attn.dtype, device=attn.device) + value = attn @ v_beta + k_cumdecay = attn @ (k_beta * g.exp().unsqueeze(-1)) + last_recurrent_state = ( + torch.zeros(batch_size, sequence_length, k_head_dim, v_head_dim).to(value) + if initial_state is None + else initial_state.to(value) + ) + core_attn_out = torch.zeros_like(value) + mask = torch.triu( + torch.ones(chunk_size, chunk_size, dtype=torch.bool, device=query.device), + diagonal=1, + ) + + # for each chunk + for i in range(0, tot_heads // chunk_size): + q_i, k_i, v_i = query[:, :, i], key[:, :, i], value[:, :, i] + attn = (q_i @ k_i.transpose(-1, -2) * decay_mask[:, :, i]).masked_fill_(mask, 0) + v_prime = (k_cumdecay[:, :, i]) @ last_recurrent_state + v_new = v_i - v_prime + attn_inter = (q_i * g[:, :, i, :, None].exp()) @ last_recurrent_state + core_attn_out[:, :, i] = attn_inter + attn @ v_new + last_recurrent_state = ( + last_recurrent_state * g[:, :, i, -1, None, None].exp() + + (k_i * (g[:, :, i, -1, None] - g[:, :, i]).exp()[..., None]).transpose( + -1, -2 + ) + @ v_new + ) + + if not output_final_state: + last_recurrent_state = None + core_attn_out = core_attn_out.reshape( + core_attn_out.shape[0], core_attn_out.shape[1], -1, core_attn_out.shape[-1] + ) + core_attn_out = core_attn_out[:, :, :num_heads] + core_attn_out = core_attn_out.transpose(1, 2).contiguous().to(initial_dtype) + return core_attn_out, last_recurrent_state + + +def chunk_gated_delta_rule_update( + query, # [B, T, HK, K] + key, # [B, T, HK, K] + value, # [B, T, HV, V] + g, # [B, T, HV] + beta, # [B, T, HV] + cu_seqlens, # [N+1] + initial_state, # [N, HV, V, K] + use_qk_l2norm_in_kernel, # True +): + num_heads = query.shape[2] + num_value_heads = value.shape[2] + batch_size = initial_state.shape[0] + initial_state_kv = initial_state.transpose(-1, -2).contiguous() + if num_value_heads // num_heads > 1: + query = query.repeat_interleave(num_value_heads // num_heads, dim=2) + key = key.repeat_interleave(num_value_heads // num_heads, dim=2) + output = torch.empty_like(value) + final_state = torch.empty_like(initial_state) + start_q = 0 + for i in range(batch_size): + end_q = cu_seqlens[i + 1] + core_attn_outi, last_recurrent_state = torch_chunk_gated_delta_rule( + query=query[:, start_q:end_q, :, :], + key=key[:, start_q:end_q, :, :], + value=value[:, start_q:end_q, :, :], + g=g[:, start_q:end_q, :], + beta=beta[:, start_q:end_q, :], + initial_state=initial_state_kv[i], + output_final_state=True, + use_qk_l2norm_in_kernel=use_qk_l2norm_in_kernel, + ) + output[:, start_q:end_q, :, :] = core_attn_outi + final_state[i] = last_recurrent_state.transpose(-1, -2).contiguous() + start_q = end_q + return output, final_state + + +def torch_recurrent_gated_delta_rule( + query, + key, + value, + g, + beta, + initial_state, + output_final_state, + use_qk_l2norm_in_kernel=False, +): + initial_dtype = query.dtype + if use_qk_l2norm_in_kernel: + query = l2norm(query, dim=-1, eps=1e-6) + key = l2norm(key, dim=-1, eps=1e-6) + query, key, value, beta, g = [ + x.transpose(1, 2).contiguous().to(torch.float32) + for x in (query, key, value, beta, g) + ] + + batch_size, num_heads, sequence_length, k_head_dim = key.shape + v_head_dim = value.shape[-1] + scale = 1 / (query.shape[-1] ** 0.5) + query = query * scale + + core_attn_out = torch.zeros(batch_size, num_heads, sequence_length, v_head_dim).to( + value + ) + last_recurrent_state = ( + torch.zeros(batch_size, num_heads, k_head_dim, v_head_dim).to(value) + if initial_state is None + else initial_state.to(value) + ) + + for i in range(sequence_length): + q_t = query[:, :, i] + k_t = key[:, :, i] + v_t = value[:, :, i] + g_t = g[:, :, i].exp().unsqueeze(-1).unsqueeze(-1) + beta_t = beta[:, :, i].unsqueeze(-1) + + last_recurrent_state = last_recurrent_state * g_t + kv_mem = (last_recurrent_state * k_t.unsqueeze(-1)).sum(dim=-2) + delta = (v_t - kv_mem) * beta_t + last_recurrent_state = last_recurrent_state + k_t.unsqueeze( + -1 + ) * delta.unsqueeze(-2) + core_attn_out[:, :, i] = (last_recurrent_state * q_t.unsqueeze(-1)).sum(dim=-2) + + if not output_final_state: + last_recurrent_state = None + core_attn_out = core_attn_out.transpose(1, 2).contiguous().to(initial_dtype) + return core_attn_out, last_recurrent_state + + +def sigmoid_gating_delta_rule_update( + query, + key, + value, + A_log, + a, + dt_bias, + b, + initial_state, + output_final_state, + use_qk_l2norm_in_kernel=False, +): + beta = b.sigmoid() + g = -A_log.float().exp() * softplus(a.float() + dt_bias) + initial_state_kv = ( + initial_state.transpose(-1, -2).contiguous() + if initial_state is not None + else None + ) + core_attn_out, last_recurrent_state = torch_recurrent_gated_delta_rule( + query, + key, + value, + g.unsqueeze(1), + beta.unsqueeze(1), + initial_state_kv, + output_final_state, + use_qk_l2norm_in_kernel=use_qk_l2norm_in_kernel, + ) + if last_recurrent_state is not None: + last_recurrent_state = last_recurrent_state.transpose(-1, -2).contiguous() + return core_attn_out, last_recurrent_state + + +def torch_gdn_gating(A_log, a, b, dt_bias): + return -A_log.float().exp() * softplus(a.float() + dt_bias).unsqueeze( + 0 + ), b.sigmoid().unsqueeze(0) + + +class TestMambaAttention(CustomTestCase): + def test_chunk_gated_delta_rule(self): + B, T_PER_SEQ, HK, HV, K, V, POOL_SIZE = 1, 128, 16, 32, 128, 128, 17 + seq_lens = torch.tensor( + [T_PER_SEQ - 7, T_PER_SEQ + 11, T_PER_SEQ - 13, T_PER_SEQ + 9], + dtype=torch.int32, + ) + cu_seqlens_ = torch.cat( + [ + torch.zeros(1, dtype=torch.int32), + seq_lens.cumsum(dim=0, dtype=torch.int32), + ] + ) + T = cu_seqlens_[-1].item() + cache_indices = torch.tensor([3, 11, 15, 7], dtype=torch.int32) + state_slots = cache_indices + query_ = torch.randn((B, T, HK, K), dtype=torch.bfloat16) + key_ = torch.randn((B, T, HK, K), dtype=torch.bfloat16) + value_ = torch.randn((B, T, HV, V), dtype=torch.bfloat16) + g_ = F.logsigmoid(torch.randn((B, T, HV), dtype=torch.float32)) + beta_ = torch.sigmoid(torch.randn((B, T, HV), dtype=torch.bfloat16)) + initial_state_ = torch.randn((POOL_SIZE, HV, V, K), dtype=torch.float32) * 0.1 + + # skip `use_qk_l2norm_in_kernel=False` case since it's not numerically stable in bfloat16 + for use_qk_l2norm_in_kernel in [True]: + core_attn_out_ref, last_recurrent_state_ref = chunk_gated_delta_rule_update( + query=query_, + key=key_, + value=value_, + g=g_, + beta=beta_, + cu_seqlens=cu_seqlens_, + initial_state=initial_state_[state_slots], + use_qk_l2norm_in_kernel=use_qk_l2norm_in_kernel, + ) + + query = query_.clone() + key = key_.clone() + value = value_.clone() + g = g_.clone() + beta = beta_.clone() + cu_seqlens = cu_seqlens_.clone() + initial_state = initial_state_.clone().transpose(-1, -2).contiguous() + initial_state_before = initial_state.clone() + + core_attn_out, returned_state = ( + torch.ops.sgl_kernel.chunk_gated_delta_rule_cpu( + query=query, + key=key, + value=value, + g=g, + beta=beta, + initial_state=initial_state, + output_final_state=True, + cu_seqlens=cu_seqlens, + head_first=False, + use_qk_l2norm_in_kernel=use_qk_l2norm_in_kernel, + initial_state_indices=cache_indices, + ) + ) + last_recurrent_state = ( + initial_state[state_slots].transpose(-1, -2).contiguous() + ) + untouched_slots = torch.ones(POOL_SIZE, dtype=torch.bool) + untouched_slots[state_slots] = False + atol = rtol = precision[core_attn_out.dtype] + torch.testing.assert_close( + core_attn_out, core_attn_out_ref, atol=atol, rtol=rtol + ) + torch.testing.assert_close( + last_recurrent_state, last_recurrent_state_ref, atol=atol, rtol=rtol + ) + torch.testing.assert_close(returned_state, initial_state) + torch.testing.assert_close( + initial_state[untouched_slots], initial_state_before[untouched_slots] + ) + + def test_fused_gdn_gating(self): + dims = [6, 32] + for dim in dims: + for A_log_dtype in [torch.float32, torch.bfloat16]: + A_log = torch.rand(dim, dtype=A_log_dtype) + a = torch.rand(1024, dim, dtype=torch.bfloat16) + b = torch.rand(1024, dim, dtype=torch.bfloat16) + dt_bias = torch.rand(dim, dtype=torch.bfloat16) + + g, beta = torch_gdn_gating(A_log, a, b, dt_bias) + g_sgl, beta_sgl = torch.ops.sgl_kernel.fused_gdn_gating_cpu( + A_log, a, b, dt_bias + ) + atol = rtol = precision[g.dtype] + atol2 = rtol2 = precision[beta.dtype] + torch.testing.assert_close(g, g_sgl, atol=atol, rtol=rtol) + torch.testing.assert_close(beta, beta_sgl, atol=atol2, rtol=rtol2) + + @parametrize( + batch_size=[1, 4], + num_value_heads=[32], + head_k_dim=[128], + head_v_dim=[128], + num_heads=[16], + seq_len=[1], + attn_tp_size=[1], + ) + def test_fused_sigmoid_gating_delta_rule_update( + self, + batch_size, + num_value_heads, + head_k_dim, + head_v_dim, + num_heads, + seq_len, + attn_tp_size, + ): + key_dim = head_k_dim * num_heads + value_dim = head_v_dim * num_value_heads + mixed_qkv_dim = (key_dim * 2 + value_dim) // attn_tp_size + mixed_qkv = torch.rand( + seq_len * batch_size, mixed_qkv_dim, dtype=torch.bfloat16 + ) + query, key, value = torch.split( + mixed_qkv, + [ + key_dim // attn_tp_size, + key_dim // attn_tp_size, + value_dim // attn_tp_size, + ], + dim=-1, + ) + query = query.view(1, batch_size, num_heads, head_k_dim) + key = key.view(1, batch_size, num_heads, head_k_dim) + value = value.view(1, batch_size, num_value_heads, head_v_dim) + A_log = torch.rand(num_value_heads, dtype=torch.float32) + a = torch.rand(batch_size, num_value_heads, dtype=torch.bfloat16) + b = torch.rand(batch_size, num_value_heads, dtype=torch.bfloat16) + dt_bias = torch.rand(num_value_heads, dtype=torch.bfloat16) + ssm_states_kv = torch.rand( + 513, num_value_heads, head_k_dim, head_v_dim, dtype=torch.float32 + ) + cache_indices = torch.randint(0, 513, (batch_size,), dtype=torch.int32) + query_start_loc = torch.arange(batch_size + 1, dtype=torch.int32) + use_qk_l2norm_in_kernel = True + query_ref = query.clone() + key_ref = key.clone() + if num_value_heads // num_heads > 1: + query_ref = query_ref.repeat_interleave(num_value_heads // num_heads, dim=2) + key_ref = key_ref.repeat_interleave(num_value_heads // num_heads, dim=2) + for A_log_dtype in [torch.float32, torch.bfloat16]: + A_log = A_log.to(A_log_dtype) + core_attn_out_ref, last_recurrent_state_ref = ( + sigmoid_gating_delta_rule_update( + query_ref.transpose(0, 1), + key_ref.transpose(0, 1), + value.transpose(0, 1), + A_log, + a, + dt_bias, + b, + initial_state=ssm_states_kv[cache_indices] + .transpose(-1, -2) + .contiguous(), + output_final_state=True, + use_qk_l2norm_in_kernel=use_qk_l2norm_in_kernel, + ) + ) + core_attn_out = ( + torch.ops.sgl_kernel.fused_sigmoid_gating_delta_rule_update_cpu( + A_log=A_log, + dt_bias=dt_bias, + q=query, + k=key, + v=value, + a=a, + b=b, + initial_state_source=ssm_states_kv, + initial_state_indices=cache_indices, + cu_seqlens=query_start_loc, + use_qk_l2norm_in_kernel=use_qk_l2norm_in_kernel, + softplus_beta=1.0, + softplus_threshold=20.0, + ) + ) + last_recurrent_state = ( + ssm_states_kv[cache_indices].transpose(-1, -2).contiguous() + ) + atol = rtol = precision[core_attn_out.dtype] + torch.testing.assert_close( + core_attn_out, core_attn_out_ref, atol=atol, rtol=rtol + ) + torch.testing.assert_close( + last_recurrent_state, last_recurrent_state_ref, atol=atol, rtol=rtol + ) + + +if __name__ == "__main__": + unittest.main() diff --git a/asian_ai/performance/SGLang/test/registered/cpu/test_mla.py b/asian_ai/performance/SGLang/test/registered/cpu/test_mla.py new file mode 100644 index 0000000000000000000000000000000000000000..77f889f7a8ebc56a0b912f1002f781244c9f128d --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/cpu/test_mla.py @@ -0,0 +1,162 @@ +import unittest + +import torch +from torch.nn.functional import scaled_dot_product_attention +from utils import precision + +from sglang.test.ci.ci_register import register_cpu_ci +from sglang.test.test_utils import CustomTestCase + +register_cpu_ci(est_time=10, suite="base-b-test-cpu") + +torch.manual_seed(1234) + + +class TestMLA(CustomTestCase): + def _run_sdpa_forward_decode( + self, + query: torch.Tensor, + output: torch.Tensor, + k_cache: torch.Tensor, + v_cache: torch.Tensor, + key: torch.Tensor, + loc: torch.Tensor, + req_to_token: torch.Tensor, + req_pool_indices: torch.Tensor, + seq_lens: torch.Tensor, + scaling=None, + enable_gqa=False, + causal=False, + ): + # set kv cache + k_cache[loc] = key + + # [num_tokens, num_heads, head_size] -> [num_heads, num_tokens, head_size] + query = query.movedim(0, query.dim() - 2) + + start_q, start_kv = 0, 0 + for seq_idx in range(seq_lens.shape[0]): + seq_len_q = 1 + seq_len_kv = seq_lens[seq_idx] + end_q = start_q + seq_len_q + end_kv = start_kv + seq_len_kv + + per_req_query = query[:, start_q:end_q, :] + + # get key and value from cache. per_req_tokens contains the kv cache + # index for each token in the sequence. + req_pool_idx = req_pool_indices[seq_idx] + per_req_tokens = req_to_token[req_pool_idx, :seq_len_kv] + per_req_key = k_cache[per_req_tokens].movedim(0, query.dim() - 2) + per_req_value = v_cache[per_req_tokens].movedim(0, query.dim() - 2) + + per_req_out = ( + scaled_dot_product_attention( + per_req_query.unsqueeze(0), + per_req_key.unsqueeze(0), + per_req_value.unsqueeze(0), + enable_gqa=enable_gqa, + scale=scaling, + is_causal=causal, + ) + .squeeze(0) + .movedim(query.dim() - 2, 0) + ) + output[start_q:end_q, :, :] = per_req_out + start_q, start_kv = end_q, end_kv + + return output + + def _test_grouped_decode_attention_once(self, B, H_Q, H_KV, D, D_V, seq_len): + dtype = torch.bfloat16 + + total_tokens = B * seq_len + sm_scale = 1.0 / (D**0.5) + logit_cap = 0.0 + num_kv_splits = 8 + enable_gqa = H_Q != H_KV + + # q represents the new token being generated, one per batch + q = torch.randn(B, H_Q, D, dtype=dtype) + + # k_buffer and v_buffer represent all previous tokens + k_buffer = torch.randn(total_tokens, H_KV, D, dtype=dtype) + v_buffer = k_buffer.narrow(2, 0, D_V) + + key = torch.randn(B, H_KV, D, dtype=dtype) + value = key.narrow(2, 0, D_V) + # make sure no duplicates in loc + loc = torch.randperm(total_tokens)[:B].to(torch.int64) + + k_buffer2 = k_buffer.clone() + v_buffer2 = k_buffer2.narrow(2, 0, D_V) + + # o will have the same shape as q + o = torch.zeros(B, H_Q, D_V, dtype=dtype) + o_grouped = torch.zeros(B, H_Q, D_V, dtype=dtype) + + req_to_token = torch.arange(total_tokens).reshape(B, seq_len).to(torch.int32) + b_req_idx = torch.arange(B).to(torch.int64) + b_seq_len = torch.full((B,), seq_len).to(torch.int64) + + attn_logits = torch.empty( + (B, H_Q, num_kv_splits, D_V + 1), + dtype=torch.float32, + ) + + torch.ops.sgl_kernel.decode_attention_cpu( + q, + k_buffer2, + v_buffer2, + o, + key, + value, + loc, + attn_logits, + req_to_token, + b_req_idx, + b_seq_len, + sm_scale, + logit_cap, + False, + 0, + None, + None, + ) + + self._run_sdpa_forward_decode( + q, + o_grouped, + k_buffer, + v_buffer, + key, + loc, + req_to_token, + b_req_idx, + b_seq_len, + scaling=sm_scale, + enable_gqa=enable_gqa, + ) + + cos_sim = torch.nn.functional.cosine_similarity( + o.flatten(), o_grouped.flatten(), dim=0 + ) + atol = rtol = precision[q.dtype] + self.assertGreater(cos_sim.item(), 0.99) + torch.testing.assert_close(o, o_grouped, atol=atol, rtol=rtol) + torch.testing.assert_close(k_buffer, k_buffer2, atol=atol, rtol=rtol) + torch.testing.assert_close(v_buffer, v_buffer2, atol=atol, rtol=rtol) + + def test_grouped_decode_attention(self): + configs = [ + (1, 22, 1, 576, 512, 8 * 111), + (4, 22, 1, 576, 512, 8 * 128), + (40, 22, 1, 576, 512, 8 * 133), + ] + + for B, H_Q, H_KV, D, D_V, seqlen in configs: + self._test_grouped_decode_attention_once(B, H_Q, H_KV, D, D_V, seqlen) + + +if __name__ == "__main__": + unittest.main() diff --git a/asian_ai/performance/SGLang/test/registered/cpu/test_moe.py b/asian_ai/performance/SGLang/test/registered/cpu/test_moe.py new file mode 100644 index 0000000000000000000000000000000000000000..3c85fddeb83a2a746f3a70f8d20e539cf6541478 --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/cpu/test_moe.py @@ -0,0 +1,440 @@ +import math +import unittest + +# TODO: use interface in cpu.py +import torch + +from sglang.srt.layers.amx_utils import CPUQuantMethod + +kernel = torch.ops.sgl_kernel + +torch.manual_seed(1183) + +from utils import ( + BLOCK_K, + BLOCK_N, + MXFP4QuantizeUtil, + factor_for_scale, + fp8_max, + fp8_min, + native_fp8_fused_moe, + parametrize, + precision, + scaled_weight, + torch_naive_fused_moe, + torch_naive_fused_moe_gptoss, + torch_w8a8_per_column_fused_moe, + unpack_and_dequant_awq, +) + +from sglang.test.ci.ci_register import register_cpu_ci +from sglang.test.test_utils import CustomTestCase + +register_cpu_ci(est_time=10, suite="base-b-test-cpu") + + +def fused_moe(a, w1, w2, score, topk, renormalize, prepack): + + G = 1 + topk_group = 1 + + B, D = a.shape + topk_weights = torch.empty(B, topk, dtype=torch.float32) + topk_ids = torch.empty(B, topk, dtype=torch.int32) + topk_weights, topk_ids = kernel.grouped_topk_cpu( + a, score, topk, renormalize, G, topk_group, 0, None, None + ) + + packed_w1 = kernel.convert_weight_packed(w1) if prepack else w1 + packed_w2 = kernel.convert_weight_packed(w2) if prepack else w2 + + inplace = True + return kernel.fused_experts_cpu( + a, + packed_w1, + packed_w2, + topk_weights, + topk_ids, + inplace, + CPUQuantMethod.UNQUANT, + None, + None, + None, + None, + None, + None, + None, + None, + None, + prepack, + ) + + +class TestFusedExperts(CustomTestCase): + + @parametrize(m=[2, 114], n=[32], k=[32], e=[4], topk=[2], renormalize=[False, True]) + def test_bf16_moe(self, m, n, k, e, topk, renormalize): + dtype = torch.bfloat16 + prepack = True + + a = torch.randn((m, k), device="cpu", dtype=dtype) / 10 + w1 = torch.randn((e, 2 * n, k), device="cpu", dtype=dtype) / 10 + w2 = torch.randn((e, k, n), device="cpu", dtype=dtype) / 10 + score = torch.randn((m, e), device="cpu", dtype=dtype) + + torch_output = torch_naive_fused_moe(a, w1, w2, score, topk, renormalize) + fused_output = fused_moe(a, w1, w2, score, topk, renormalize, prepack) + + atol = rtol = precision[torch_output.dtype] + torch.testing.assert_close(torch_output, fused_output, atol=atol, rtol=rtol) + + @parametrize( + m=[1, 32], n=[128, 64], k=[128, 64], e=[4], topk=[2], renormalize=[False] + ) + def test_bf16_moe_bias(self, m, n, k, e, topk, renormalize): + dtype = torch.bfloat16 + + a = torch.randn((m, k), device="cpu", dtype=dtype) / 10 + w1 = torch.randn((e, 2 * n, k), device="cpu", dtype=dtype) / 10 + w1_b = torch.randn((e, 2 * n), device="cpu", dtype=torch.float) / 10 + w2 = torch.randn((e, k, n), device="cpu", dtype=dtype) / 10 + w2_b = torch.randn((e, k), device="cpu", dtype=torch.float) / 10 + score = torch.randn((m, e), device="cpu", dtype=dtype) + score = torch.softmax(score, dim=-1, dtype=torch.float32) + topk_weight, topk_ids = torch.topk(score, topk) + alpha = 1.702 + limit = 7.0 + torch_output = torch_naive_fused_moe_gptoss( + a, w1, w2, w1_b, w2_b, topk_weight, topk_ids, renormalize, alpha, limit, e + ) + packed_w1 = kernel.convert_weight_packed(w1) + packed_w2 = kernel.convert_weight_packed(w2) + fused_output = torch.ops.sgl_kernel.fused_experts_cpu( + a, + packed_w1, + packed_w2, + topk_weight, + topk_ids.to(torch.int), + False, # inplace # See [Note] inplace should be False in fused_experts. + CPUQuantMethod.UNQUANT, + None, # w1_scale + None, # w2_scale + None, # w1_zp + None, # w2_zp + None, # block_size + w1_b, + w2_b, + alpha, + limit, + True, # is_vnni + ) + atol = rtol = precision[torch_output.dtype] + torch.testing.assert_close(torch_output, fused_output, atol=atol, rtol=rtol) + + @parametrize(M=[1, 39], N=[128], K=[256], E=[8], topk=[3]) + def test_int8_moe(self, M, N, K, E, topk): + dtype = torch.bfloat16 + prepack = True + + # Initialize int8 quantization parameters + int8_factor_for_scale = 1e-2 + int8_max = 127 + int8_min = -128 + + # Input tensor + # M * K + a = torch.randn((M, K), dtype=dtype) / math.sqrt(K) + + # Generate int8 weights + w1_fp32 = (torch.rand((E, 2 * N, K), dtype=torch.float32) - 0.5) * 2 + w1 = (w1_fp32 * int8_max).clamp(min=int8_min, max=int8_max).to(torch.int8) + + w2_fp32 = (torch.rand((E, K, N), dtype=torch.float32) - 0.5) * 2 + w2 = (w2_fp32 * int8_max).clamp(min=int8_min, max=int8_max).to(torch.int8) + + # Generate scale for each column (per-column quantization) + w1_s = torch.rand(E, 2 * N, device=w1_fp32.device) * int8_factor_for_scale + w2_s = torch.rand(E, K, device=w2_fp32.device) * int8_factor_for_scale + + # Calculate routing + score = torch.randn((M, E), dtype=dtype) + score = torch.softmax(score, dim=-1, dtype=torch.float32) + topk_weight, topk_ids = torch.topk(score, topk) + + ref_out = torch_w8a8_per_column_fused_moe( + a, w1, w2, w1_s, w2_s, topk_weight, topk_ids, topk + ) + + inplace = True + packed_w1 = kernel.convert_weight_packed(w1) if prepack else w1 + packed_w2 = kernel.convert_weight_packed(w2) if prepack else w2 + out = kernel.fused_experts_cpu( + a, + packed_w1, + packed_w2, + topk_weight, + topk_ids.to(torch.int32), + inplace, + CPUQuantMethod.INT8_W8A8, + w1_s, + w2_s, + None, + None, + None, + None, + None, + None, + None, + prepack, + ) + + atol = rtol = precision[ref_out.dtype] + # Increase the tolerance for large input shapes + if M > 35: + atol = rtol = 0.02 + torch.testing.assert_close(ref_out, out, atol=atol, rtol=rtol) + + @parametrize(M=[2, 121], N=[352, 512], K=[256, 320], E=[8], topk=[4]) + def test_fp8_moe(self, M, N, K, E, topk): + dtype = torch.bfloat16 + + a = torch.randn(M, K, dtype=dtype) / math.sqrt(K) + + w1_fp32 = torch.randn(E, 2 * N, K) + w1 = (w1_fp32 * fp8_max).clamp(min=fp8_min, max=fp8_max).to(torch.float8_e4m3fn) + + w2_fp32 = torch.randn(E, K, N) + w2 = (w2_fp32 * fp8_max).clamp(min=fp8_min, max=fp8_max).to(torch.float8_e4m3fn) + + w1s = ( + torch.randn(E, math.ceil(2 * N / BLOCK_N), math.ceil(K / BLOCK_K)) + * factor_for_scale + ) + w2s = ( + torch.randn(E, math.ceil(K / BLOCK_N), math.ceil(N / BLOCK_K)) + * factor_for_scale + ) + + w1_scaled = scaled_weight(w1, w1s) + w2_scaled = scaled_weight(w2, w2s) + + score = torch.randn((M, E), dtype=dtype) + score = torch.softmax(score, dim=-1, dtype=torch.float32) + topk_weight, topk_ids = torch.topk(score, topk) + + w1 = kernel.convert_weight_packed(w1) + w2 = kernel.convert_weight_packed(w2) + + ref_out = native_fp8_fused_moe( + a, w1_scaled, w2_scaled, topk_weight, topk_ids, topk + ) + out = kernel.fused_experts_cpu( + a, + w1, + w2, + topk_weight, + topk_ids.to(torch.int32), + False, + CPUQuantMethod.FP8_W8A16, + w1s, + w2s, + None, + None, + [BLOCK_N, BLOCK_K], + None, + None, + None, + None, + True, + ) + + atol = rtol = precision[dtype] + torch.testing.assert_close(ref_out.bfloat16(), out, atol=atol, rtol=rtol) + + @parametrize(M=[2, 121], N=[352, 512], K=[256, 320], E=[8], topk=[4]) + def test_mxfp4_moe(self, M, N, K, E, topk): + dtype = torch.bfloat16 + + a = torch.randn(M, K, dtype=dtype) / 10 + + w1_bf16 = torch.randn((E, 2 * N, K), dtype=dtype) / 10 + w1q, w1s = MXFP4QuantizeUtil.quantize(w1_bf16) + w1s = w1s.reshape(E, 2 * N, K // 32) + w1dq = MXFP4QuantizeUtil.dequantize(w1q, dtype, w1s) + + w2_bf16 = torch.randn((E, K, N), dtype=dtype) / 10 + w2q, w2s = MXFP4QuantizeUtil.quantize(w2_bf16) + w2s = w2s.reshape(E, K, N // 32) + w2dq = MXFP4QuantizeUtil.dequantize(w2q, dtype, w2s) + + score = torch.randn((M, E), dtype=dtype) + score = torch.softmax(score, dim=-1, dtype=torch.float32) + topk_weight, topk_ids = torch.topk(score, topk) + + w1 = kernel.convert_weight_packed(w1q) + w2 = kernel.convert_weight_packed(w2q) + w1s = kernel.convert_scale_packed(w1s) + w2s = kernel.convert_scale_packed(w2s) + + ref_out = native_fp8_fused_moe( + a, w1dq.float(), w2dq.float(), topk_weight, topk_ids, topk + ) + out = kernel.fused_experts_cpu( + a, + w1, + w2, + topk_weight, + topk_ids.to(torch.int32), + False, + CPUQuantMethod.MXFP4, + w1s, + w2s, + None, + None, + None, + None, + None, + None, + None, + True, + ) + + atol = rtol = precision[dtype] + torch.testing.assert_close(ref_out.bfloat16(), out, atol=atol, rtol=rtol) + + @parametrize( + m=[1, 32], n=[128, 64], k=[128, 64], e=[4], topk=[2], renormalize=[False] + ) + def test_mxfp4_moe_bias(self, m, n, k, e, topk, renormalize): + dtype = torch.bfloat16 + + a = torch.randn((m, k), device="cpu", dtype=dtype) / 10 + w1_bf16 = torch.randn((e, 2 * n, k), device="cpu", dtype=dtype) / 10 + w1q, w1s = MXFP4QuantizeUtil.quantize(w1_bf16) + w1s = w1s.reshape(e, 2 * n, k // 32) + w1dq = MXFP4QuantizeUtil.dequantize(w1q, dtype, w1s) + w1_b = torch.randn((e, 2 * n), device="cpu", dtype=torch.float32) / 10 + w2_bf16 = torch.randn((e, k, n), device="cpu", dtype=dtype) / 10 + w2q, w2s = MXFP4QuantizeUtil.quantize(w2_bf16) + w2s = w2s.reshape(e, k, n // 32) + w2dq = MXFP4QuantizeUtil.dequantize(w2q, dtype, w2s) + w2_b = torch.randn((e, k), device="cpu", dtype=torch.float32) / 10 + score = torch.randn((m, e), device="cpu", dtype=dtype) + score = torch.softmax(score, dim=-1, dtype=torch.float32) + topk_weight, topk_ids = torch.topk(score, topk) + alpha = 1.702 + limit = 7.0 + torch_output = torch_naive_fused_moe_gptoss( + a, + w1dq, + w2dq, + w1_b, + w2_b, + topk_weight, + topk_ids, + renormalize, + alpha, + limit, + e, + ) + + w1 = kernel.convert_weight_packed(w1q) + w2 = kernel.convert_weight_packed(w2q) + w1s = kernel.convert_scale_packed(w1s) + w2s = kernel.convert_scale_packed(w2s) + + fused_output = torch.ops.sgl_kernel.fused_experts_cpu( + a, + w1, + w2, + topk_weight, + topk_ids.to(torch.int32), + False, # inplace # See [Note] inplace should be False in fused_experts. + CPUQuantMethod.MXFP4, # use_mxfp4 + w1s, # w1_scale + w2s, # w2_scale + None, # w1_zp + None, # w2_zp + None, # block_size + w1_b, + w2_b, + alpha, + limit, + True, # is_vnni + ) + atol = rtol = precision[torch_output.dtype] + torch.testing.assert_close(torch_output, fused_output, atol=atol, rtol=rtol) + + @parametrize(M=[1, 6], N=[512], K=[256], E=[8], topk=[4]) + def test_int4_moe(self, M, N, K, E, topk, group_size=128): + dtype = torch.bfloat16 + + a = torch.rand(M, K, dtype=dtype) / math.sqrt(K) + + awq_w13_weight = torch.randint(-127, 128, (E, K, 2 * N // 8)).to(torch.int) + awq_w13_zero = torch.randint(0, 10, (E, K // group_size, 2 * N // 8)).to( + torch.int + ) + awq_w13_scales = torch.rand(E, int(K // group_size), 2 * N).to(torch.bfloat16) + + awq_w2_weight = torch.randint(-127, 128, (E, N, K // 8)).to(torch.int) + awq_w2_zero = torch.randint(0, 10, (E, N // group_size, K // 8)).to(torch.int) + awq_w2_scales = torch.rand(E, int(N // group_size), K).to(torch.bfloat16) + bf16_w13_weight = [] + bf16_w2_weight = [] + for i in range(E): + bf16_w13_weight_i, _ = unpack_and_dequant_awq( + awq_w13_weight[i], awq_w13_zero[i], awq_w13_scales[i], 4, 128 + ) + bf16_w2_weight_i, _ = unpack_and_dequant_awq( + awq_w2_weight[i], awq_w2_zero[i], awq_w2_scales[i], 4, 128 + ) + bf16_w13_weight.append(bf16_w13_weight_i) + bf16_w2_weight.append(bf16_w2_weight_i) + bf16_w13_weight = torch.stack(bf16_w13_weight).detach() + bf16_w2_weight = torch.stack(bf16_w2_weight).detach() + + score = torch.rand((M, E), dtype=dtype) + + ref_out = torch_naive_fused_moe( + a, bf16_w13_weight, bf16_w2_weight, score, topk, False + ) + score = torch.softmax(score, dim=-1, dtype=torch.float32) + topk_weight, topk_ids = torch.topk(score, topk) + awq_w13_weight_pack, awq_w13_zero_pack, awq_w13_scales_pack = ( + torch.ops.sgl_kernel.convert_weight_packed_scale_zp( + awq_w13_weight, awq_w13_zero, awq_w13_scales, 0 + ) + ) + awq_w2_weight_pack, awq_w2_zero_pack, awq_w2_scales_pack = ( + torch.ops.sgl_kernel.convert_weight_packed_scale_zp( + awq_w2_weight, awq_w2_zero, awq_w2_scales, 0 + ) + ) + + out = kernel.fused_experts_cpu( + a, + awq_w13_weight_pack, + awq_w2_weight_pack, + topk_weight, + topk_ids.to(torch.int32), + False, + CPUQuantMethod.INT4_W4A8, + awq_w13_scales_pack, + awq_w2_scales_pack, + awq_w13_zero_pack, + awq_w2_zero_pack, + None, + None, + None, + None, + None, + True, + ) + + atol = rtol = precision[dtype] + torch.testing.assert_close(ref_out.bfloat16(), out, atol=atol, rtol=rtol) + + +if __name__ == "__main__": + unittest.main() diff --git a/asian_ai/performance/SGLang/test/registered/cpu/test_norm.py b/asian_ai/performance/SGLang/test/registered/cpu/test_norm.py new file mode 100644 index 0000000000000000000000000000000000000000..669b4005892c7c0a840793c6d0bfc8d1e4562343 --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/cpu/test_norm.py @@ -0,0 +1,436 @@ +import itertools +import unittest +from typing import Optional, Tuple, Union + +import torch +from utils import make_non_contiguous, parametrize, precision + +from sglang.test.ci.ci_register import register_cpu_ci +from sglang.test.test_utils import CustomTestCase + +register_cpu_ci(est_time=10, suite="base-b-test-cpu") +register_cpu_ci(est_time=10, suite="base-b-test-cpu-arm64") + +torch.manual_seed(1234) + + +class TestNorm(CustomTestCase): + + def _forward_native( + self, + x: torch.Tensor, + weight: torch.Tensor, + variance_epsilon: float = 1e-6, + residual: Optional[torch.Tensor] = None, + ) -> Union[torch.Tensor, Tuple[torch.Tensor, torch.Tensor]]: + orig_dtype = x.dtype + x = x.to(torch.float32) + if residual is not None: + x = x + residual.to(torch.float32) + residual = x.to(orig_dtype) + + variance = x.pow(2).mean(dim=-1, keepdim=True) + x = x * torch.rsqrt(variance + variance_epsilon) + x = x.to(orig_dtype) * weight + if residual is None: + return x + else: + return x, residual + + def _norm(self, x, eps): + return x * torch.rsqrt(x.pow(2).mean(-1, keepdim=True) + eps) + + def _gemma3_rmsnorm_native( + self, x: torch.Tensor, weight: torch.Tensor, variance_epsilon: float = 1e-6 + ): + output = self._norm(x.float(), variance_epsilon) + output = output * (1.0 + weight.float()) + return output.type_as(x) + + def _gemma_rmsnorm_native( + self, + x: torch.Tensor, + weight: torch.Tensor, + variance_epsilon: float = 1e-6, + residual: Optional[torch.Tensor] = None, + ) -> Union[torch.Tensor, Tuple[torch.Tensor, torch.Tensor]]: + orig_dtype = x.dtype + if residual is not None: + x = x + residual + residual = x + + x = x.float() + variance = x.pow(2).mean(dim=-1, keepdim=True) + x = x * torch.rsqrt(variance + variance_epsilon) + x = x * (1.0 + weight.float()) + x = x.to(orig_dtype) + return x if residual is None else (x, residual) + + @parametrize( + m=[4096, 1024], + n=[4096, 4109], + dtype=[torch.float16, torch.bfloat16], + ) + def test_norm(self, m, n, dtype): + + x = torch.randn([m, n], dtype=dtype) + x = make_non_contiguous(x) + hidden_size = x.size(-1) + weight = torch.randn(hidden_size, dtype=dtype) + variance_epsilon = 1e-6 + + out = torch.ops.sgl_kernel.rmsnorm_cpu(x, weight, variance_epsilon) + ref_out = self._forward_native(x, weight, variance_epsilon) + + atol = rtol = precision[ref_out.dtype] + torch.testing.assert_close(ref_out, out, atol=atol, rtol=rtol) + + ref_x = x.clone() + residual = torch.randn([m, hidden_size], dtype=dtype) + ref_residual = residual.clone() + + torch.ops.sgl_kernel.fused_add_rmsnorm_cpu( + x, residual, weight, variance_epsilon + ) + + ref_x, ref_residual = self._forward_native( + ref_x, weight, variance_epsilon, ref_residual + ) + + torch.testing.assert_close(x, ref_x, atol=atol, rtol=rtol) + torch.testing.assert_close(residual, ref_residual, atol=atol, rtol=rtol) + + @parametrize( + l=[1, 2], + m=[4096, 1024], + n=[4096, 4109], + dtype=[torch.float16, torch.bfloat16], + ) + def test_norm_3d(self, l, m, n, dtype): + + x = torch.randn([l, m, n], dtype=dtype) + x = make_non_contiguous(x) + hidden_size = x.size(-1) + weight = torch.randn(hidden_size, dtype=dtype) + variance_epsilon = 1e-6 + + out = torch.ops.sgl_kernel.rmsnorm_cpu(x, weight, variance_epsilon) + ref_out = self._forward_native(x, weight, variance_epsilon) + + atol = rtol = precision[ref_out.dtype] + torch.testing.assert_close(ref_out, out, atol=atol, rtol=rtol) + + ref_x = x.clone() + residual = torch.randn([l, m, hidden_size], dtype=dtype) + ref_residual = residual.clone() + + torch.ops.sgl_kernel.fused_add_rmsnorm_cpu( + x, residual, weight, variance_epsilon + ) + + ref_x, ref_residual = self._forward_native( + ref_x, weight, variance_epsilon, ref_residual + ) + + torch.testing.assert_close(x, ref_x, atol=atol, rtol=rtol) + torch.testing.assert_close(residual, ref_residual, atol=atol, rtol=rtol) + + @parametrize( + m=[4096, 1024], + n=[4096, 4109], + dtype=[torch.float16, torch.bfloat16], + ) + def test_l2norm(self, m, n, dtype): + + x = torch.randn([m, n], dtype=dtype) + hidden_size = x.size(-1) + fake_ones_weight = torch.ones(hidden_size, dtype=dtype) + variance_epsilon = 1e-6 + + out = torch.ops.sgl_kernel.l2norm_cpu(x, variance_epsilon) + ref_out = self._forward_native(x, fake_ones_weight, variance_epsilon) + + atol = rtol = precision[ref_out.dtype] + torch.testing.assert_close(ref_out, out, atol=atol, rtol=rtol) + + @parametrize( + m=[4096, 1024], + n=[4096, 4109], + dtype=[torch.float16, torch.bfloat16], + ) + def test_gemma_rmsnorm(self, m, n, dtype): + + x = torch.randn([m, n], dtype=dtype) + x = make_non_contiguous(x) + hidden_size = x.size(-1) + weight = torch.randn(hidden_size, dtype=dtype) + variance_epsilon = 1e-6 + + out = torch.ops.sgl_kernel.gemma_rmsnorm_cpu(x, weight, variance_epsilon) + ref_out = self._gemma_rmsnorm_native(x, weight, variance_epsilon) + + atol = rtol = precision[ref_out.dtype] + torch.testing.assert_close(ref_out, out, atol=atol, rtol=rtol) + + ref_x = x.clone() + residual = torch.randn([m, hidden_size], dtype=dtype) + ref_residual = residual.clone() + + torch.ops.sgl_kernel.gemma_fused_add_rmsnorm_cpu( + x, residual, weight, variance_epsilon + ) + + ref_x, ref_residual = self._gemma_rmsnorm_native( + ref_x, weight, variance_epsilon, ref_residual + ) + + torch.testing.assert_close(x, ref_x, atol=atol, rtol=rtol) + torch.testing.assert_close(residual, ref_residual, atol=atol, rtol=rtol) + + @parametrize( + m=[4096, 1024], + n=[4096, 4109], + dtype=[torch.float16, torch.bfloat16], + ) + def test_gemma3_rmsnorm(self, m, n, dtype): + x_list = [ + torch.randn([m, n], dtype=dtype), + torch.randn([1, m, 2, n], dtype=dtype), + ] + for x in x_list: + x = make_non_contiguous(x) + hidden_size = x.size(-1) + weight = torch.randn(hidden_size, dtype=dtype) + variance_epsilon = 1e-6 + out = torch.ops.sgl_kernel.gemma3_rmsnorm_cpu(x, weight, variance_epsilon) + ref_out = self._gemma3_rmsnorm_native(x, weight, variance_epsilon) + + atol = rtol = precision[ref_out.dtype] + torch.testing.assert_close(ref_out, out, atol=atol, rtol=rtol) + + def _gemma4_rmsnorm_native( + self, + x: torch.Tensor, + weight: torch.Tensor, + variance_epsilon: float = 1e-6, + scale_shift: float = 0.0, + with_scale: bool = True, + ): + output = self._norm(x.float(), variance_epsilon) + if with_scale: + output = output * (weight.float() + scale_shift) + return output.type_as(x) + + @parametrize( + m=[4096, 1024], + n=[4096, 4109], + dtype=[torch.float16, torch.bfloat16], + ) + def test_gemma4_rmsnorm(self, m, n, dtype): + for scale_shift, with_scale in [ + (0.0, True), + (1.0, True), + (0.0, False), + (1.0, False), + ]: + x_list = [ + torch.randn([m, n], dtype=dtype), + torch.randn([4, m, n], dtype=dtype), + ] + # Add non-block-contiguous 3D input + base = torch.randn([4, 2 * m, n], dtype=dtype) + x_list.append(base[:, :m, :]) + + for x in x_list: + x = make_non_contiguous(x) + hidden_size = x.size(-1) + weight = torch.randn(hidden_size, dtype=dtype) + variance_epsilon = 1e-6 + + out = torch.ops.sgl_kernel.gemma4_rmsnorm_cpu( + x, weight, variance_epsilon, scale_shift, with_scale + ) + ref_out = self._gemma4_rmsnorm_native( + x, weight, variance_epsilon, scale_shift, with_scale + ) + + atol = rtol = precision[ref_out.dtype] + torch.testing.assert_close(ref_out, out, atol=atol, rtol=rtol) + + +class TestFusedRMSNormGated(CustomTestCase): + M = [4096, 1024] + N = [4096, 4096 + 13] + dtype = [torch.float16, torch.bfloat16] + + def _forward_native( + self, + hidden_states: torch.Tensor, + weight: torch.Tensor, + variance_epsilon: float = 1e-6, + gate: Optional[torch.Tensor] = None, + ) -> torch.Tensor: + input_dtype = hidden_states.dtype + hidden_states = hidden_states.to(torch.float32) + variance = hidden_states.pow(2).mean(-1, keepdim=True) + # Norm before gate + hidden_states = hidden_states * torch.rsqrt(variance + variance_epsilon) + hidden_states = weight * hidden_states.to(input_dtype) + hidden_states = hidden_states * torch.nn.functional.silu(gate.to(torch.float32)) + + return hidden_states.to(input_dtype) + + def _norm_test(self, m, n, dtype): + + x = torch.randn([m, n], dtype=dtype) + x = make_non_contiguous(x) + batch_size = x.size(0) + hidden_size = x.size(-1) + weight = torch.randn(hidden_size, dtype=dtype) + variance_epsilon = 1e-6 + gate = torch.randn([batch_size, hidden_size], dtype=dtype) + + out = torch.ops.sgl_kernel.fused_rmsnorm_gated_cpu( + x, weight, gate, variance_epsilon + ) + ref_out = self._forward_native(x, weight, variance_epsilon, gate) + + atol = rtol = precision[ref_out.dtype] * 2 + torch.testing.assert_close(ref_out, out, atol=atol, rtol=rtol) + + def test_norm(self): + for params in itertools.product(self.M, self.N, self.dtype): + with self.subTest(m=params[0], n=params[1], dtype=params[2]): + self._norm_test(*params) + + +class TestLayerNorm(CustomTestCase): + + def _forward_native( + self, + x: torch.Tensor, + weight: torch.Tensor, + variance_epsilon: float, + residual: Optional[torch.Tensor] = None, + bias: Optional[torch.Tensor] = None, + ) -> Union[torch.Tensor, Tuple[torch.Tensor, torch.Tensor]]: + orig_dtype = x.dtype + x = x.to(torch.float32) + if residual is not None: + x = x + residual.to(torch.float32) + residual = x.to(orig_dtype) + + variance, mean = torch.var_mean(x, dim=-1, keepdim=True, correction=0) + x = (x - mean) * torch.rsqrt(variance + variance_epsilon) + x = x * weight.to(torch.float32) + if bias is not None: + x = x + bias.to(torch.float32) + x = x.to(orig_dtype) + return x if residual is None else (x, residual) + + @parametrize( + m=[4096, 1024], + n=[4096, 4109], + dtype=[torch.float16, torch.bfloat16], + ) + def test_norm_input_2d(self, m: int, n: int, dtype: torch.dtype) -> None: + x = torch.randn([m, n], dtype=dtype) + x = make_non_contiguous(x) + hidden_size = x.size(-1) + weight = torch.randn(hidden_size, dtype=dtype) + bias = torch.randn(hidden_size, dtype=dtype) + variance_epsilon = 1e-6 + + ln_out = torch.ops.sgl_kernel.layernorm_cpu(x, weight, None, variance_epsilon) + ref_ln_out = self._forward_native(x, weight, variance_epsilon) + + atol = rtol = precision[ref_ln_out.dtype] + torch.testing.assert_close(ln_out, ref_ln_out, atol=atol, rtol=rtol) + + ln_out = torch.ops.sgl_kernel.layernorm_cpu(x, weight, bias, variance_epsilon) + ref_ln_out = self._forward_native( + x, weight, variance_epsilon, residual=None, bias=bias + ) + torch.testing.assert_close(ln_out, ref_ln_out, atol=atol, rtol=rtol) + + residual = torch.randn([m, hidden_size], dtype=dtype) + ref_residual = residual.clone() + + add_ln_out = torch.ops.sgl_kernel.fused_add_layernorm_cpu( + x, residual, weight, None, variance_epsilon + ) + ref_add_ln_out, ref_residual = self._forward_native( + x, weight, variance_epsilon, residual=ref_residual + ) + + torch.testing.assert_close(add_ln_out, ref_add_ln_out, atol=atol, rtol=rtol) + torch.testing.assert_close(residual, ref_residual, atol=atol, rtol=rtol) + + residual = torch.randn([m, hidden_size], dtype=dtype) + ref_residual = residual.clone() + + add_ln_out = torch.ops.sgl_kernel.fused_add_layernorm_cpu( + x, residual, weight, bias, variance_epsilon + ) + ref_add_ln_out, ref_residual = self._forward_native( + x, weight, variance_epsilon, residual=ref_residual, bias=bias + ) + + torch.testing.assert_close(add_ln_out, ref_add_ln_out, atol=atol, rtol=rtol) + torch.testing.assert_close(residual, ref_residual, atol=atol, rtol=rtol) + + @parametrize( + l=[4096, 1024], + m=[1, 4], + n=[4096, 4109, 2304], + dtype=[torch.float16, torch.bfloat16], + ) + def test_norm_input_3d(self, l: int, m: int, n: int, dtype: torch.dtype) -> None: + x = torch.randn([l, m, n], dtype=dtype) + x = make_non_contiguous(x) + hidden_size = x.size(-1) + weight = torch.randn(hidden_size, dtype=dtype) + bias = torch.randn(hidden_size, dtype=dtype) + variance_epsilon = 1e-6 + + ln_out = torch.ops.sgl_kernel.layernorm_cpu(x, weight, None, variance_epsilon) + ref_ln_out = self._forward_native(x, weight, variance_epsilon) + + atol = rtol = precision[ref_ln_out.dtype] + torch.testing.assert_close(ln_out, ref_ln_out, atol=atol, rtol=rtol) + + ln_out = torch.ops.sgl_kernel.layernorm_cpu(x, weight, bias, variance_epsilon) + ref_ln_out = self._forward_native( + x, weight, variance_epsilon, residual=None, bias=bias + ) + torch.testing.assert_close(ln_out, ref_ln_out, atol=atol, rtol=rtol) + + residual = torch.randn([l, m, hidden_size], dtype=dtype) + ref_residual = residual.clone() + + add_ln_out = torch.ops.sgl_kernel.fused_add_layernorm_cpu( + x, residual, weight, None, variance_epsilon + ) + ref_add_ln_out, ref_residual = self._forward_native( + x, weight, variance_epsilon, ref_residual + ) + + torch.testing.assert_close(add_ln_out, ref_add_ln_out, atol=atol, rtol=rtol) + torch.testing.assert_close(residual, ref_residual, atol=atol, rtol=rtol) + + residual = torch.randn([l, m, hidden_size], dtype=dtype) + ref_residual = residual.clone() + + add_ln_out = torch.ops.sgl_kernel.fused_add_layernorm_cpu( + x, residual, weight, bias, variance_epsilon + ) + ref_add_ln_out, ref_residual = self._forward_native( + x, weight, variance_epsilon, residual=ref_residual, bias=bias + ) + + torch.testing.assert_close(add_ln_out, ref_add_ln_out, atol=atol, rtol=rtol) + torch.testing.assert_close(residual, ref_residual, atol=atol, rtol=rtol) + + +if __name__ == "__main__": + unittest.main() diff --git a/asian_ai/performance/SGLang/test/registered/cpu/test_qkv_proj_with_rope.py b/asian_ai/performance/SGLang/test/registered/cpu/test_qkv_proj_with_rope.py new file mode 100644 index 0000000000000000000000000000000000000000..11de3320b2a75499bc31b9ed73cf7f653726a2c5 --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/cpu/test_qkv_proj_with_rope.py @@ -0,0 +1,443 @@ +import unittest + +import torch +from utils import ( + convert_weight, + native_w8a8_per_token_matmul, + per_token_quant_int8, + precision, +) + +from sglang.srt.layers.quantization.fp8_utils import input_to_float8 +from sglang.srt.layers.rotary_embedding.utils import apply_rotary_emb +from sglang.test.ci.ci_register import register_cpu_ci +from sglang.test.test_utils import CustomTestCase + +register_cpu_ci(est_time=10, suite="base-b-test-cpu") + +convert_weight_packed = torch.ops.sgl_kernel.convert_weight_packed +qkv_proj_with_rope = torch.ops.sgl_kernel.qkv_proj_with_rope +qkv_proj_with_rope_fused_weight = torch.ops.sgl_kernel.qkv_proj_with_rope_fused_weight +torch.manual_seed(1234) +# constants +kv_lora_rank = 512 +qk_head_dim = 192 +qk_nope_head_dim = 128 +qk_rope_head_dim = 64 +rotary_dim = qk_rope_head_dim +num_heads = 22 +q_lora_rank = 1536 +hidden_size = 7168 +B = 1 +eps = 1e-6 + + +def layernorm(x, weight, variance_epsilon=1e-6, residual=None): + orig_dtype = x.dtype + x = x.to(torch.float32) + variance = x.pow(2).mean(dim=-1, keepdim=True) + x = x * torch.rsqrt(variance + variance_epsilon) + return (x * weight).to(orig_dtype) + + +def rotary_emb(q_pe, k_pe, pos, cos_sin_cache): + orig_dtype = q_pe.dtype + q_pe = q_pe.float() + k_pe = k_pe.float() + cos_sin_cache = cos_sin_cache.float() + + query_rot = q_pe[..., :rotary_dim] + key_rot = k_pe[..., :rotary_dim] + cos_sin = cos_sin_cache[pos] + cos, sin = cos_sin.chunk(2, dim=-1) + query_rot = apply_rotary_emb(query_rot, cos, sin, False) + key_rot = apply_rotary_emb(key_rot, cos, sin, False) + return query_rot.to(orig_dtype), key_rot.to(orig_dtype) + + +def native_torch( + q_input, + hidden_states, + q_a_proj_weight, + norm_weight1, + q_b_proj_weight, + w_kc, + kv_a_proj_weight, + norm_weight2, + pos, + cos_sin_cache, +): + + q = torch.matmul(hidden_states, q_a_proj_weight.t()) + q = layernorm(q, norm_weight1) + q = torch.matmul(q, q_b_proj_weight.t()).view(-1, num_heads, qk_head_dim) + + q_nope, q_pe = q.split([qk_nope_head_dim, qk_rope_head_dim], dim=-1) + q_nope_out = torch.bmm(q_nope.transpose(0, 1), w_kc) + + q_input[..., :kv_lora_rank] = q_nope_out.transpose(0, 1) + latent_cache = torch.matmul(hidden_states, kv_a_proj_weight.t()) + v_input = latent_cache[..., :kv_lora_rank] + v_input = layernorm(v_input.contiguous(), norm_weight2).unsqueeze(1) + k_input = latent_cache.unsqueeze(1) + k_input[..., :kv_lora_rank] = v_input + k_pe = k_input[..., kv_lora_rank:] + + q_pe, k_pe = rotary_emb(q_pe, k_pe, pos, cos_sin_cache) + q_input[..., kv_lora_rank:] = q_pe + k_input[..., kv_lora_rank:] = k_pe + + return q_input, k_input, v_input + + +def native_torch_int8( + q_input, + hidden_states, + w1_q, + w1_s, + norm_weight1, + w2_q, + w2_s, + w_kc, + w3_q, + w3_s, + norm_weight2, + pos, + cos_sin_cache, +): + + a_q, a_s = per_token_quant_int8(hidden_states) + q = native_w8a8_per_token_matmul(a_q, w1_q, a_s, w1_s, None, torch.bfloat16) + q = layernorm(q, norm_weight1) + + a_q, a_s = per_token_quant_int8(q) + q = native_w8a8_per_token_matmul(a_q, w2_q, a_s, w2_s, None, torch.bfloat16).view( + -1, num_heads, qk_head_dim + ) + + q_nope, q_pe = q.split([qk_nope_head_dim, qk_rope_head_dim], dim=-1) + q_nope_out = torch.bmm(q_nope.transpose(0, 1), w_kc) + + q_input[..., :kv_lora_rank] = q_nope_out.transpose(0, 1) + a_q, a_s = per_token_quant_int8(hidden_states) + latent_cache = native_w8a8_per_token_matmul( + a_q, w3_q, a_s, w3_s, None, torch.bfloat16 + ) + v_input = latent_cache[..., :kv_lora_rank] + v_input = layernorm(v_input.contiguous(), norm_weight2).unsqueeze(1) + k_input = latent_cache.unsqueeze(1) + k_input[..., :kv_lora_rank] = v_input + k_pe = k_input[..., kv_lora_rank:] + + q_pe, k_pe = rotary_emb(q_pe, k_pe, pos, cos_sin_cache) + q_input[..., kv_lora_rank:] = q_pe + k_input[..., kv_lora_rank:] = k_pe + + return q_input, k_input, v_input + + +class TestQKVProjWithROPE(CustomTestCase): + def test_bf16_qkv_proj_with_rope(self): + dtype = torch.bfloat16 + hidden_states = torch.randn(B, hidden_size, dtype=dtype) / hidden_size + q_input = torch.empty( + B, num_heads, kv_lora_rank + qk_rope_head_dim, dtype=dtype + ) + q_a_proj_weight = torch.randn(q_lora_rank, hidden_size, dtype=dtype) * 0.1 + norm_weight1 = torch.randn(q_lora_rank, dtype=dtype) + q_b_proj_weight = ( + torch.randn(num_heads * qk_head_dim, q_lora_rank, dtype=dtype) * 0.1 + ) + w_kc = torch.randn(num_heads, kv_lora_rank, qk_nope_head_dim, dtype=dtype) * 0.1 + kv_a_proj_weight = ( + torch.randn(kv_lora_rank + qk_rope_head_dim, hidden_size, dtype=dtype) * 0.1 + ) + fused_weight = torch.cat([q_a_proj_weight, kv_a_proj_weight], dim=0) + norm_weight2 = torch.randn(kv_lora_rank, dtype=dtype) + pos = torch.randint(10, 100, (B,)) + cos_sin_cache = torch.randn(100, rotary_dim, dtype=dtype) + q_ref, k_ref, v_ref = native_torch( + q_input, + hidden_states, + q_a_proj_weight, + norm_weight1, + q_b_proj_weight, + w_kc.transpose(1, 2), + kv_a_proj_weight, + norm_weight2, + pos, + cos_sin_cache, + ) + qa_packed = convert_weight_packed(q_a_proj_weight) + qb_packed = convert_weight_packed(q_b_proj_weight) + kva_packed = convert_weight_packed(kv_a_proj_weight) + wkc_packed = convert_weight_packed(w_kc) + fused_weight_packed = convert_weight_packed(fused_weight) + + q_out, k_out, v_out = qkv_proj_with_rope( + hidden_states, + qa_packed, + qb_packed, + kva_packed, + wkc_packed, + norm_weight1, + norm_weight2, + pos, + cos_sin_cache, + eps, + False, + False, + None, + None, + None, + None, + True, + None, + ) + fused_q_out, fused_k_out, fused_v_out = qkv_proj_with_rope_fused_weight( + hidden_states, + fused_weight_packed, + qb_packed, + wkc_packed, + norm_weight1, + norm_weight2, + pos, + cos_sin_cache, + eps, + False, + False, + None, + None, + None, + True, + None, + q_lora_rank, + kv_lora_rank, + qk_rope_head_dim, + ) + atol = rtol = precision[q_ref.dtype] + torch.testing.assert_close(q_ref, q_out, atol=atol, rtol=rtol) + torch.testing.assert_close(k_ref, k_out, atol=atol, rtol=rtol) + torch.testing.assert_close(v_ref, v_out, atol=atol, rtol=rtol) + torch.testing.assert_close(fused_q_out, q_out) + torch.testing.assert_close(fused_k_out, k_out) + torch.testing.assert_close(fused_v_out, v_out) + + def test_int8_qkv_proj_with_rope(self): + dtype = torch.bfloat16 + hidden_states = torch.randn(B, hidden_size, dtype=dtype) / hidden_size + q_input = torch.empty( + B, num_heads, kv_lora_rank + qk_rope_head_dim, dtype=dtype + ) + q_a_proj_weight = torch.randn(q_lora_rank, hidden_size, dtype=dtype) * 0.1 + norm_weight1 = torch.randn(q_lora_rank, dtype=dtype) + q_b_proj_weight = ( + torch.randn(num_heads * qk_head_dim, q_lora_rank, dtype=dtype) * 0.1 + ) + w_kc = torch.randn(num_heads, kv_lora_rank, qk_nope_head_dim, dtype=dtype) * 0.1 + kv_a_proj_weight = ( + torch.randn(kv_lora_rank + qk_rope_head_dim, hidden_size, dtype=dtype) * 0.1 + ) + norm_weight2 = torch.randn(kv_lora_rank, dtype=dtype) + pos = torch.randint(10, 100, (B,)) + cos_sin_cache = torch.randn(100, rotary_dim, dtype=dtype) + + w1_q, w1_s = per_token_quant_int8(q_a_proj_weight) + w2_q, w2_s = per_token_quant_int8(q_b_proj_weight) + w3_q, w3_s = per_token_quant_int8(kv_a_proj_weight) + q_ref, k_ref, v_ref = native_torch_int8( + q_input, + hidden_states, + w1_q, + w1_s, + norm_weight1, + w2_q, + w2_s, + w_kc.transpose(1, 2), + w3_q, + w3_s, + norm_weight2, + pos, + cos_sin_cache, + ) + w1_q_packed = convert_weight_packed(w1_q) + w2_q_packed = convert_weight_packed(w2_q) + w3_q_packed = convert_weight_packed(w3_q) + wkc_packed = convert_weight_packed(w_kc) + q_out, k_out, v_out = qkv_proj_with_rope( + hidden_states, + w1_q_packed, + w2_q_packed, + w3_q_packed, + wkc_packed, + norm_weight1, + norm_weight2, + pos, + cos_sin_cache, + eps, + True, + False, + w1_s, + w2_s, + w3_s, + None, + True, + None, + ) + fused_weight = torch.cat([w1_q, w3_q], dim=0) + fused_weight_s = torch.cat([w1_s, w3_s], dim=0) + w_fused_q_packed = convert_weight_packed(fused_weight) + fused_q_out, fused_k_out, fused_v_out = qkv_proj_with_rope_fused_weight( + hidden_states, + w_fused_q_packed, + w2_q_packed, + wkc_packed, + norm_weight1, + norm_weight2, + pos, + cos_sin_cache, + eps, + True, + False, + fused_weight_s, + w2_s, + None, + True, + None, + q_lora_rank, + kv_lora_rank, + qk_rope_head_dim, + ) + atol = rtol = precision[q_ref.dtype] + torch.testing.assert_close(q_ref, q_out, atol=atol, rtol=rtol) + torch.testing.assert_close(k_ref, k_out, atol=atol, rtol=rtol) + torch.testing.assert_close(v_ref, v_out, atol=atol, rtol=rtol) + torch.testing.assert_close(fused_q_out, q_out) + torch.testing.assert_close(fused_k_out, k_out) + torch.testing.assert_close(fused_v_out, v_out) + + def test_fp8_qkv_proj_with_rope(self): + dtype = torch.bfloat16 + hidden_states = torch.randn(B, hidden_size, dtype=dtype) / hidden_size + q_input = torch.empty( + B, num_heads, kv_lora_rank + qk_rope_head_dim, dtype=dtype + ) + q_a_proj_weight = torch.randn(q_lora_rank, hidden_size, dtype=dtype) * 0.1 + norm_weight1 = torch.randn(q_lora_rank, dtype=dtype) + q_b_proj_weight = ( + torch.randn(num_heads * qk_head_dim, q_lora_rank, dtype=dtype) * 0.1 + ) + w_kc = torch.randn(num_heads, kv_lora_rank, qk_nope_head_dim, dtype=dtype) * 0.1 + w_kc_q, w_kc_s = input_to_float8(w_kc) + kv_a_proj_weight = ( + torch.randn(kv_lora_rank + qk_rope_head_dim, hidden_size, dtype=dtype) * 0.1 + ) + norm_weight2 = torch.randn(kv_lora_rank, dtype=dtype) + pos = torch.randint(10, 100, (B,)) + cos_sin_cache = torch.randn(100, rotary_dim, dtype=dtype) + + scale_block_size_N = 128 + scale_block_size_K = 128 + fp8_q_a_proj_weight, q_a_proj_weight_scale_inv, q_a_proj_weight_dq = ( + convert_weight( + q_a_proj_weight, + [scale_block_size_N, scale_block_size_K], + torch.bfloat16, + ) + ) + fp8_q_b_proj_weight, q_b_proj_weight_scale_inv, q_b_proj_weight_dq = ( + convert_weight( + q_b_proj_weight, + [scale_block_size_N, scale_block_size_K], + torch.bfloat16, + ) + ) + ( + fp8_kv_a_proj_with_mqa_weight, + kv_a_proj_with_mqa_weight_scale_inv, + kv_a_proj_with_mqa_weight_dq, + ) = convert_weight( + kv_a_proj_weight, [scale_block_size_N, scale_block_size_K], torch.bfloat16 + ) + w_kc_dq = w_kc_q.to(torch.bfloat16) * w_kc_s + q_ref, k_ref, v_ref = native_torch( + q_input, + hidden_states, + q_a_proj_weight_dq, + norm_weight1, + q_b_proj_weight_dq, + w_kc_dq.transpose(1, 2), + kv_a_proj_with_mqa_weight_dq, + norm_weight2, + pos, + cos_sin_cache, + ) + fp8_q_a_proj_weight_packed = convert_weight_packed(fp8_q_a_proj_weight) + fp8_q_b_proj_weight_packed = convert_weight_packed(fp8_q_b_proj_weight) + fp8_kv_a_proj_with_mqa_weight_packed = convert_weight_packed( + fp8_kv_a_proj_with_mqa_weight + ) + w_kc_q = convert_weight_packed(w_kc_q) + q_out, k_out, v_out = qkv_proj_with_rope( + hidden_states, + fp8_q_a_proj_weight_packed, + fp8_q_b_proj_weight_packed, + fp8_kv_a_proj_with_mqa_weight_packed, + w_kc_q, + norm_weight1, + norm_weight2, + pos, + cos_sin_cache, + eps, + False, + True, + q_a_proj_weight_scale_inv.float(), + q_b_proj_weight_scale_inv.float(), + kv_a_proj_with_mqa_weight_scale_inv.float(), + w_kc_s, + True, + [scale_block_size_N, scale_block_size_K], + ) + + fused_weight = torch.cat( + [fp8_q_a_proj_weight, fp8_kv_a_proj_with_mqa_weight], dim=0 + ) + fused_weight_s = torch.cat( + [q_a_proj_weight_scale_inv, kv_a_proj_with_mqa_weight_scale_inv], dim=0 + ) + fused_weight_packed = convert_weight_packed(fused_weight) + fused_q_out, fused_k_out, fused_v_out = qkv_proj_with_rope_fused_weight( + hidden_states, + fused_weight_packed, + fp8_q_b_proj_weight_packed, + w_kc_q, + norm_weight1, + norm_weight2, + pos, + cos_sin_cache, + eps, + False, + True, + fused_weight_s.float(), + q_b_proj_weight_scale_inv.float(), + w_kc_s, + True, + [scale_block_size_N, scale_block_size_K], + q_lora_rank, + kv_lora_rank, + qk_rope_head_dim, + ) + atol = rtol = precision[q_ref.dtype] + # Due to the change in multiplication order, the error is amplified. + # In the model, with fewer layers, this doesn't cause issues, but in + # tests with more layers, we need to enlarge the tolerance to pass the tests. + torch.testing.assert_close(q_ref, q_out, atol=1e-1, rtol=1e-1) + torch.testing.assert_close(k_ref, k_out, atol=atol, rtol=rtol) + torch.testing.assert_close(v_ref, v_out, atol=atol, rtol=rtol) + torch.testing.assert_close(fused_q_out, q_out) + torch.testing.assert_close(fused_k_out, k_out) + torch.testing.assert_close(fused_v_out, v_out) + + +if __name__ == "__main__": + unittest.main() diff --git a/asian_ai/performance/SGLang/test/registered/cpu/test_qwen3.py b/asian_ai/performance/SGLang/test/registered/cpu/test_qwen3.py new file mode 100644 index 0000000000000000000000000000000000000000..4d9dea448098ed3006bc1e348069d1ef7cc48995 --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/cpu/test_qwen3.py @@ -0,0 +1,153 @@ +import unittest + +import torch +from utils import precision + +from sglang.test.ci.ci_register import register_cpu_ci +from sglang.test.test_utils import CustomTestCase + +register_cpu_ci(est_time=10, suite="base-b-test-cpu") +register_cpu_ci(est_time=10, suite="base-b-test-cpu-arm64") + +torch.manual_seed(1234) + + +def fix_query_key_value_ordering_reshape_cat( + mixed_qkvz, mixed_ba, num_k_heads, num_v_heads, attn_tp_size, head_k_dim, head_v_dim +): + new_tensor_shape_qkvz = mixed_qkvz.size()[:-1] + ( + num_k_heads // attn_tp_size, + ( + head_k_dim + + head_k_dim + + (head_v_dim + head_v_dim) * num_v_heads // num_k_heads + ), + ) + new_tensor_shape_ba = mixed_ba.size()[:-1] + ( + num_k_heads // attn_tp_size, + 2 * num_v_heads // num_k_heads, + ) + + mixed_qkvz = mixed_qkvz.view(*new_tensor_shape_qkvz) + mixed_ba = mixed_ba.view(*new_tensor_shape_ba) + + split_arg_list_qkvz = [ + head_k_dim, + head_k_dim, + (num_v_heads // num_k_heads * head_v_dim), + (num_v_heads // num_k_heads * head_v_dim), + ] + split_arg_list_ba = [ + num_v_heads // num_k_heads, + num_v_heads // num_k_heads, + ] + # [b, sq, ng, (hn + hn + np/ng * hn + np/ng + np/ng)] + # --> [b, sq, ng, hn], [b, sq, ng, hn], [b, sq, ng, np/ng * hn], [b, sq, ng, np/ng * hn], [b, sq, ng, np/ng], [b, sq, ng, np/ng] + query, key, value, z = torch.split(mixed_qkvz, split_arg_list_qkvz, dim=2) + b, a = torch.split(mixed_ba, split_arg_list_ba, dim=2) + + # [b, sq, ng, np/ng * hn] -> [b, sq, np, hn] + value = value.reshape(value.size(0), -1, head_v_dim) + z = z.reshape(z.size(0), -1, head_v_dim) + b = b.reshape(b.size(0), num_v_heads // attn_tp_size) + a = a.reshape(a.size(0), num_v_heads // attn_tp_size) + query, key, value = map(lambda x: x.reshape(x.shape[0], -1), (query, key, value)) + mixed_qkv = torch.cat((query, key, value), dim=-1) + + return mixed_qkv, z, b, a + + +def fix_query_key_value_ordering_reshape_cat_contiguous( + mixed_qkvz: torch.Tensor, + mixed_ba: torch.Tensor, + key_dim: int, + value_dim: int, + num_v_heads: int, + head_v_dim: int, + attn_tp_size: int, +): + """ + Derives `query`, `key` and `value` tensors from `mixed_qkvzba`. + """ + k_tp = key_dim // attn_tp_size + v_tp = value_dim // attn_tp_size + nv_tp = num_v_heads // attn_tp_size + + # Directly split, no head group reshape + query, key, value, z = mixed_qkvz.split([k_tp, k_tp, v_tp, v_tp], dim=-1) + b, a = mixed_ba.split([nv_tp, nv_tp], dim=-1) + + # value / z reshape to (seq, num_v_heads/tp, head_v_dim) + value = value.reshape(value.size(0), -1, head_v_dim) + z = z.reshape(z.size(0), -1, head_v_dim) + query, key, value = map(lambda x: x.reshape(x.shape[0], -1), (query, key, value)) + mixed_qkv = torch.cat((query, key, value), dim=-1) + return mixed_qkv, z, b, a + + +class TestQwen3(CustomTestCase): + def test_fused_qkvzba_split_reshape_cat(self): + mixed_qkvz = torch.rand(1024, 12288, dtype=torch.bfloat16) + mixed_ba = torch.rand(1024, 64, dtype=torch.bfloat16) + head_k_dim = 128 + head_v_dim = 128 + num_v_heads = 32 + num_k_heads = 16 + attn_tp_size = 1 + mixed_qkv_ref, z_ref, b_ref, a_ref = fix_query_key_value_ordering_reshape_cat( + mixed_qkvz, + mixed_ba, + num_k_heads, + num_v_heads, + attn_tp_size, + head_k_dim, + head_v_dim, + ) + num_heads_qk = num_k_heads // attn_tp_size + num_heads_v = num_v_heads // attn_tp_size + mixed_qkv, z, b, a = torch.ops.sgl_kernel.fused_qkvzba_split_reshape_cat_cpu( + mixed_qkvz, mixed_ba, num_heads_qk, num_heads_v, head_k_dim, head_v_dim + ) + atol = rtol = precision[mixed_qkv.dtype] + torch.testing.assert_close(mixed_qkv, mixed_qkv_ref, atol=atol, rtol=rtol) + torch.testing.assert_close(z, z_ref, atol=atol, rtol=rtol) + torch.testing.assert_close(b, b_ref, atol=atol, rtol=rtol) + torch.testing.assert_close(a, a_ref, atol=atol, rtol=rtol) + + def test_fused_qkvzba_split_reshape_cat_contiguous(self): + mixed_qkvz = torch.rand(1, 12288, dtype=torch.bfloat16) + mixed_ba = torch.rand(1, 64, dtype=torch.bfloat16) + head_k_dim = 128 + head_v_dim = 128 + num_v_heads = 32 + num_k_heads = 16 + attn_tp_size = 1 + key_dim = head_k_dim * num_k_heads + value_dim = head_v_dim * num_v_heads + mixed_qkv_ref, z_ref, b_ref, a_ref = ( + fix_query_key_value_ordering_reshape_cat_contiguous( + mixed_qkvz, + mixed_ba, + key_dim, + value_dim, + num_v_heads, + head_v_dim, + attn_tp_size, + ) + ) + num_heads_qk = num_k_heads // attn_tp_size + num_heads_v = num_v_heads // attn_tp_size + mixed_qkv, z, b, a = ( + torch.ops.sgl_kernel.fused_qkvzba_split_reshape_cat_contiguous_cpu( + mixed_qkvz, mixed_ba, num_heads_qk, num_heads_v, head_k_dim, head_v_dim + ) + ) + atol = rtol = precision[mixed_qkv.dtype] + torch.testing.assert_close(mixed_qkv, mixed_qkv_ref, atol=atol, rtol=rtol) + torch.testing.assert_close(z, z_ref, atol=atol, rtol=rtol) + torch.testing.assert_close(b, b_ref, atol=atol, rtol=rtol) + torch.testing.assert_close(a, a_ref, atol=atol, rtol=rtol) + + +if __name__ == "__main__": + unittest.main() diff --git a/asian_ai/performance/SGLang/test/registered/cpu/test_request_decompression.py b/asian_ai/performance/SGLang/test/registered/cpu/test_request_decompression.py new file mode 100644 index 0000000000000000000000000000000000000000..1a8b4c1aca068499956eee41a94f1284d022cdc6 --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/cpu/test_request_decompression.py @@ -0,0 +1,116 @@ +import asyncio +import unittest + +import zstandard + +from sglang.srt.entrypoints.http_request_decompression import ( + RequestDecompressionMiddleware, +) +from sglang.test.ci.ci_register import register_cpu_ci + +register_cpu_ci(est_time=10, suite="base-b-test-cpu") + +PAYLOAD = b'{"text":"hello world","n":7}' +COMPRESSED = zstandard.ZstdCompressor().compress(PAYLOAD) + + +def _drive(scope, body_chunks): + """Drive the middleware once. Returns (seen, sent): `seen` is what the inner + app received ({scope, body}) or None if the app was never called; `sent` is + the list of ASGI messages the middleware emitted directly.""" + seen = {} + sent = [] + chunks = list(body_chunks) + + async def receive(): + if chunks: + chunk, more = chunks.pop(0) + return {"type": "http.request", "body": chunk, "more_body": more} + return {"type": "http.disconnect"} + + async def send(message): + sent.append(message) + + async def app(inner_scope, inner_receive, inner_send): + body = b"" + more = True + while more: + message = await inner_receive() + if message["type"] != "http.request": + break + body += message.get("body", b"") + more = message.get("more_body", False) + seen["scope"] = inner_scope + seen["body"] = body + + asyncio.run(RequestDecompressionMiddleware(app)(scope, receive, send)) + return (seen or None), sent + + +class TestRequestDecompressionMiddleware(unittest.TestCase): + def test_passthrough_when_header_absent(self): + scope = {"type": "http", "headers": [(b"content-length", b"4")]} + seen, sent = _drive(scope, [(b"abcd", False)]) + self.assertEqual(seen["body"], b"abcd") + self.assertEqual(seen["scope"]["headers"], [(b"content-length", b"4")]) + self.assertEqual(sent, []) + + def test_decompresses_zstd_body(self): + scope = { + "type": "http", + "headers": [ + (b"x-body-compressed", b"zstd"), + (b"content-length", str(len(COMPRESSED)).encode()), + ], + } + seen, sent = _drive(scope, [(COMPRESSED, False)]) + self.assertEqual(seen["body"], PAYLOAD) + self.assertEqual(sent, []) + + def test_strips_header_and_fixes_content_length(self): + scope = { + "type": "http", + "headers": [ + (b"x-body-compressed", b"zstd"), + (b"content-length", str(len(COMPRESSED)).encode()), + (b"content-type", b"application/json"), + ], + } + seen, _ = _drive(scope, [(COMPRESSED, False)]) + self.assertEqual( + seen["scope"]["headers"], + [ + (b"content-type", b"application/json"), + (b"content-length", str(len(PAYLOAD)).encode()), + ], + ) + + def test_unsupported_method_returns_400(self): + scope = {"type": "http", "headers": [(b"x-body-compressed", b"gzip")]} + seen, sent = _drive(scope, [(b"abcd", False)]) + self.assertIsNone(seen) + self.assertEqual(sent[0]["type"], "http.response.start") + self.assertEqual(sent[0]["status"], 400) + + def test_chunked_body_reassembled(self): + half = len(COMPRESSED) // 2 + scope = {"type": "http", "headers": [(b"x-body-compressed", b"zstd")]} + seen, _ = _drive(scope, [(COMPRESSED[:half], True), (COMPRESSED[half:], False)]) + self.assertEqual(seen["body"], PAYLOAD) + + def test_bad_body_returns_400(self): + scope = {"type": "http", "headers": [(b"x-body-compressed", b"zstd")]} + seen, sent = _drive(scope, [(b"not-zstd-data", False)]) + self.assertIsNone(seen) + self.assertEqual(sent[0]["type"], "http.response.start") + self.assertEqual(sent[0]["status"], 400) + + def test_non_http_scope_passthrough(self): + scope = {"type": "lifespan", "headers": []} + seen, sent = _drive(scope, []) + self.assertEqual(seen["scope"]["type"], "lifespan") + self.assertEqual(sent, []) + + +if __name__ == "__main__": + unittest.main() diff --git a/asian_ai/performance/SGLang/test/registered/cpu/test_request_headers.py b/asian_ai/performance/SGLang/test/registered/cpu/test_request_headers.py new file mode 100644 index 0000000000000000000000000000000000000000..8ba637e96b88fd0088ccdbad1652c071c00b30fd --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/cpu/test_request_headers.py @@ -0,0 +1,81 @@ +import unittest +from types import SimpleNamespace + +from fastapi import HTTPException +from starlette.datastructures import Headers + +from sglang.srt.entrypoints.request_headers import apply_header_overrides +from sglang.test.ci.ci_register import register_cpu_ci + +register_cpu_ci(est_time=10, suite="base-b-test-cpu") + + +def _obj(): + return SimpleNamespace( + rid=None, + bootstrap_host=None, + bootstrap_port=None, + bootstrap_room=None, + conversation_id=None, + routed_dp_rank=None, + disagg_prefill_dp_rank=None, + ) + + +class TestApplyRoutingHeaders(unittest.TestCase): + def test_sets_all_fields_with_types(self): + obj = _obj() + apply_header_overrides( + obj, + Headers( + { + "x-override-rid": "r1", + "x-override-bootstrap-host": "prefill1", + "x-override-bootstrap-port": "8998", + "x-override-bootstrap-room": "18446744073709551615", + "x-override-conversation-id": "c1", + "x-override-routed-dp-rank": "3", + "x-override-disagg-prefill-dp-rank": "5", + } + ), + ) + self.assertEqual(obj.rid, "r1") + self.assertEqual(obj.bootstrap_host, "prefill1") + self.assertEqual(obj.bootstrap_port, 8998) + self.assertEqual(obj.bootstrap_room, 18446744073709551615) + self.assertEqual(obj.conversation_id, "c1") + self.assertEqual(obj.routed_dp_rank, 3) + self.assertEqual(obj.disagg_prefill_dp_rank, 5) + + def test_absent_headers_leave_obj_unchanged(self): + obj = _obj() + apply_header_overrides(obj, Headers({})) + self.assertIsNone(obj.rid) + self.assertIsNone(obj.bootstrap_host) + self.assertIsNone(obj.routed_dp_rank) + + def test_header_overrides_existing_value(self): + obj = _obj() + obj.rid = "from-body" + apply_header_overrides(obj, Headers({"x-override-rid": "from-header"})) + self.assertEqual(obj.rid, "from-header") + + def test_partial_headers_set_only_present(self): + obj = _obj() + apply_header_overrides( + obj, Headers({"x-override-rid": "r1", "x-override-routed-dp-rank": "2"}) + ) + self.assertEqual(obj.rid, "r1") + self.assertEqual(obj.routed_dp_rank, 2) + self.assertIsNone(obj.bootstrap_host) + + def test_invalid_int_fails_loud(self): + obj = _obj() + with self.assertRaises(HTTPException): + apply_header_overrides( + obj, Headers({"x-override-bootstrap-port": "not-an-int"}) + ) + + +if __name__ == "__main__": + unittest.main() diff --git a/asian_ai/performance/SGLang/test/registered/cpu/test_rope.py b/asian_ai/performance/SGLang/test/registered/cpu/test_rope.py new file mode 100644 index 0000000000000000000000000000000000000000..d8b2110a3b3b65f0f6be748f4249a6b519026699 --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/cpu/test_rope.py @@ -0,0 +1,286 @@ +import unittest + +import torch +from utils import precision + +from sglang.srt.layers.rotary_embedding import ( + MRotaryEmbedding, + RotaryEmbedding, +) +from sglang.srt.layers.rotary_embedding.rope_variant import ( + DeepseekScalingRotaryEmbedding, + apply_rotary_pos_emb_native, +) +from sglang.srt.server_args import ServerArgs, set_global_server_args_for_scheduler +from sglang.test.ci.ci_register import register_cpu_ci +from sglang.test.test_utils import CustomTestCase + +register_cpu_ci(est_time=10, suite="base-b-test-cpu") +register_cpu_ci(est_time=10, suite="base-b-test-cpu-arm64") + +torch.manual_seed(1234) + + +class TestROPE(CustomTestCase): + def test_mrope(self): + torch.manual_seed(100) + head_size = 128 + seq_len = 512 + num_heads = 16 + num_kv_heads = 1 + rotary_dim = 128 + max_pos = 262144 + base = 5000000 + is_neox_style = True + dtype = torch.bfloat16 + mrope_section = [24, 20, 20] + mrope_interleaved = True + positions_mrope = torch.randint(0, max_pos, (3, seq_len)) + positions_text = torch.randint(0, max_pos, (seq_len,)) + set_global_server_args_for_scheduler(ServerArgs(model_path="dummy")) + + test_config = [ + # (dtype, is_neox_stype, mrope_interleaved, positions, mrope_section) + (torch.bfloat16, False, True, positions_mrope, mrope_section), + (torch.bfloat16, False, False, positions_mrope, mrope_section), + (torch.bfloat16, False, False, positions_text, None), + (torch.bfloat16, True, True, positions_mrope, mrope_section), + (torch.bfloat16, True, False, positions_mrope, mrope_section), + (torch.bfloat16, True, False, positions_text, None), + ] + for ( + dtype, + is_neox_style, + mrope_interleaved, + positions, + mrope_section, + ) in test_config: + rope = MRotaryEmbedding( + head_size, + rotary_dim, + max_pos, + base, + is_neox_style, + dtype, + mrope_section, + mrope_interleaved, + ) + enable_autocast = True + + with torch.no_grad(), torch.amp.autocast("cpu", enabled=enable_autocast): + q = torch.randn(seq_len, num_heads * head_size, dtype=dtype) + q_clone = q.clone() + k = torch.randn(seq_len, num_kv_heads * head_size, dtype=dtype) + k_clone = k.clone() + + # ref kernel + q_ref, k_ref = rope.forward_native( + query=q, + key=k, + positions=positions, + ) + # fused rope kernel + q_sgl, k_sgl = torch.ops.sgl_kernel.multimodal_rotary_embedding_cpu( + positions, + q_clone, + k_clone, + rope.head_size, + rope.cos_sin_cache, + rope.mrope_section, + rope.mrope_interleaved, + is_neox_style, + ) + atol = rtol = precision[q_ref.dtype] + torch.testing.assert_close(q_ref, q_sgl, atol=atol, rtol=rtol) + torch.testing.assert_close(k_ref, k_sgl, atol=atol, rtol=rtol) + + def test_deepseek_v2_rope(self): + num_head = 16 + seq_len = 1024 + q_head_dim = 192 + qk_nope_head_dim = 128 + qk_rope_head_dim = 64 + max_pos = 256 + k_dim = 576 + rotary_dim = 64 + is_neox_style = False + set_global_server_args_for_scheduler(ServerArgs(model_path="dummy")) + + # Create cos_sin_cache + freqs = torch.rand(max_pos, qk_rope_head_dim // 2) + cos = freqs.cos() * 0.7 + sin = freqs.sin() * 0.7 + cos_sin_cache = torch.cat((cos, sin), dim=-1).to(torch.bfloat16) + positions = torch.randint(0, max_pos, (seq_len,)) + + rope = DeepseekScalingRotaryEmbedding( + qk_rope_head_dim, + rotary_dim, + max_pos, + 16, # not used since cos_sin_cache is provided + is_neox_style, + 1.0, + torch.bfloat16, + device="cpu", + ) + rope.register_buffer("cos_sin_cache", cos_sin_cache) + + for dtype in [torch.bfloat16]: + enable_autocast = True + + with torch.no_grad(), torch.amp.autocast("cpu", enabled=enable_autocast): + q = torch.randn(seq_len, num_head, q_head_dim, dtype=dtype) + q_clone = q.clone() + k = torch.randn(seq_len, 1, k_dim, dtype=dtype) + k_clone = k.clone() + _, q_pe = q.split([qk_nope_head_dim, qk_rope_head_dim], dim=-1) + _, q_pe_clone = q_clone.split( + [qk_nope_head_dim, qk_rope_head_dim], dim=-1 + ) + k_pe = k[:, :, k_dim - qk_rope_head_dim :] + k_pe_clone = k_clone[:, :, k_dim - qk_rope_head_dim :] + + # ref kernel + q_pe, k_pe = rope.forward_native( + query=q_pe, + key=k_pe, + positions=positions, + ) + + # fused rope kernel + q_pe_clone, k_pe_clone = torch.ops.sgl_kernel.rotary_embedding_cpu( + positions, + q_pe_clone, + k_pe_clone, + rope.head_size, + cos_sin_cache, + False, + ) + + atol = rtol = precision[q_pe.dtype] + torch.testing.assert_close(q_pe, q_pe_clone, atol=atol, rtol=rtol) + torch.testing.assert_close(k_pe, k_pe_clone, atol=atol, rtol=rtol) + torch.testing.assert_close(k_pe, k_pe_clone) + + def test_origin_rope(self): + def single_test( + head_size: int, + rotary_dim: int, + max_position_embeddings: int, + base: int, + dims: int, + is_neox_style: bool, + dtype: torch.dtype, + device: str, + batch_size: int, + seq_len: int, + num_q_heads: int, + num_kv_heads: int, + ): + set_global_server_args_for_scheduler(ServerArgs(model_path="dummy")) + torch.manual_seed(1234) + rope_ref = RotaryEmbedding( + head_size, + rotary_dim, + max_position_embeddings, + base, + is_neox_style, + dtype, + ).to(device) + pos_ids = torch.arange(seq_len, device=device).repeat(batch_size) + query = torch.randn( + batch_size * seq_len, + num_q_heads * head_size, + dtype=dtype, + device=device, + ) + key = torch.randn( + batch_size * seq_len, + num_kv_heads * head_size, + dtype=dtype, + device=device, + ) + if dims == 4: + query = query.view(batch_size, seq_len, num_q_heads, head_size) + key = key.view(batch_size, seq_len, num_kv_heads, head_size) + query_ref, key_ref = query.clone(), key.clone() + query_cpu, key_cpu = query.clone(), key.clone() + + query_ref_out, key_ref_out = rope_ref.forward_native( + pos_ids, query_ref, key_ref + ) + query_cpu_out, key_cpu_out = torch.ops.sgl_kernel.rotary_embedding_cpu( + pos_ids, + query_cpu, + key_cpu, + rope_ref.head_size, + rope_ref.cos_sin_cache.to(query.dtype), + rope_ref.is_neox_style, + ) + torch.testing.assert_close( + query_ref_out, query_cpu_out, atol=1e-2, rtol=1e-2 + ) + torch.testing.assert_close(key_ref_out, key_cpu_out, atol=1e-2, rtol=1e-2) + + test_config = [ + (64, 64, 32, 8000, True, torch.bfloat16, "cpu", 32, 32, 1, 1), + (256, 128, 4096, 10000, True, torch.bfloat16, "cpu", 2, 512, 32, 8), + (512, 128, 311, 10000, True, torch.bfloat16, "cpu", 3, 39, 4, 2), + (128, 128, 2048, 10000, False, torch.bfloat16, "cpu", 2, 512, 32, 8), + (128, 128, 2048, 10000, False, torch.bfloat16, "cpu", 2, 512, 16, 4), + (512, 128, 311, 10000, False, torch.bfloat16, "cpu", 3, 39, 4, 2), + ] + + for ( + head_size, + rotary_dim, + max_position_embeddings, + base, + is_neox_style, + dtype, + device, + batch_size, + seq_len, + num_q_heads, + num_kv_heads, + ) in test_config: + for dim in [2, 4]: + single_test( + head_size, + rotary_dim, + max_position_embeddings, + base, + dim, + is_neox_style, + dtype, + device, + batch_size, + seq_len, + num_q_heads, + num_kv_heads, + ) + + def test_apply_rotary_pos_emb(self): + num_tokens = 1024 + num_heads = 8 + head_size = 72 + qkv = torch.randn(num_tokens, num_heads * head_size * 3).to(torch.bfloat16) + query, key, _ = qkv.split( + [num_heads * head_size, num_heads * head_size, num_heads * head_size], + dim=-1, + ) + query = query.view(num_tokens, num_heads, head_size) + key = key.view(num_tokens, num_heads, head_size) + for sincos_dtype in [torch.float32, torch.bfloat16]: + cos = torch.rand(num_tokens, head_size).to(sincos_dtype) + sin = torch.rand(num_tokens, head_size).to(sincos_dtype) + q_out_ref, k_out_ref = apply_rotary_pos_emb_native(query, key, cos, sin) + q_out_sgl, k_out_sgl = torch.ops.sgl_kernel.apply_rotary_pos_emb_cpu( + query, key, cos, sin + ) + torch.testing.assert_close(q_out_ref, q_out_sgl, atol=1e-2, rtol=1e-2) + torch.testing.assert_close(k_out_ref, k_out_sgl, atol=1e-2, rtol=1e-2) + + +if __name__ == "__main__": + unittest.main() diff --git a/asian_ai/performance/SGLang/test/registered/cpu/test_server_args_backend.py b/asian_ai/performance/SGLang/test/registered/cpu/test_server_args_backend.py new file mode 100644 index 0000000000000000000000000000000000000000..bf6559259412f85194b22e5ee23a570a8542f434 --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/cpu/test_server_args_backend.py @@ -0,0 +1,100 @@ +import json +import os +import tempfile +import unittest +from unittest.mock import patch + +from sglang.srt.server_args import ServerArgs +from sglang.test.ci.ci_register import register_cpu_ci + +register_cpu_ci(est_time=10, suite="base-b-test-cpu") +register_cpu_ci(est_time=10, suite="base-b-test-cpu-arm64") + + +class TestServerArgsCPUBackend(unittest.TestCase): + def _make_server_args(self, attention_backend=None): + server_args = ServerArgs.__new__(ServerArgs) + server_args.device = "cpu" + server_args.attention_backend = attention_backend + server_args.sampling_backend = None + return server_args + + @patch("sglang.srt.server_args.is_host_cpu_arm64", return_value=True) + def test_arm_cpu_defaults_to_torch_native(self, _mock_is_arm64): + server_args = self._make_server_args() + + ServerArgs._handle_cpu_backends(server_args) + + self.assertEqual(server_args.attention_backend, "torch_native") + self.assertEqual(server_args.sampling_backend, "pytorch") + + @patch("sglang.srt.server_args.is_host_cpu_arm64", return_value=False) + def test_x86_cpu_defaults_to_intel_amx(self, _mock_is_arm64): + server_args = self._make_server_args() + + ServerArgs._handle_cpu_backends(server_args) + + self.assertEqual(server_args.attention_backend, "intel_amx") + self.assertEqual(server_args.sampling_backend, "pytorch") + + +class TestServerArgsIBDeviceValidation(unittest.TestCase): + def _validate_ib_devices(self, device_str, available_devices=None): + server_args = ServerArgs.__new__(ServerArgs) + available_devices = available_devices or [ + "mlx5_0", + "mlx5_1", + "mlx5_2", + "mlx5_3", + ] + real_isdir = os.path.isdir + real_listdir = os.listdir + + with patch( + "sglang.srt.server_args.os.path.isdir", + side_effect=lambda path: ( + True if path == "/sys/class/infiniband" else real_isdir(path) + ), + ), patch( + "sglang.srt.server_args.os.listdir", + side_effect=lambda path: ( + available_devices + if path == "/sys/class/infiniband" + else real_listdir(path) + ), + ): + return ServerArgs._validate_ib_devices(server_args, device_str) + + def test_validate_ib_devices_accepts_comma_separated(self): + self.assertEqual( + self._validate_ib_devices("mlx5_0, mlx5_1"), + "mlx5_0,mlx5_1", + ) + + def test_validate_ib_devices_accepts_json_object(self): + result = self._validate_ib_devices( + '{"0": "mlx5_0, mlx5_1", "1": "mlx5_2, mlx5_3"}' + ) + self.assertEqual( + json.loads(result), + {"0": "mlx5_0,mlx5_1", "1": "mlx5_2,mlx5_3"}, + ) + + def test_validate_ib_devices_accepts_json_file(self): + with tempfile.NamedTemporaryFile("w", suffix=".json", delete=False) as file: + json.dump({"0": "mlx5_0, mlx5_1", "1": "mlx5_2"}, file) + json_file = file.name + + try: + result = self._validate_ib_devices(json_file) + finally: + os.unlink(json_file) + + self.assertEqual( + json.loads(result), + {"0": "mlx5_0,mlx5_1", "1": "mlx5_2"}, + ) + + +if __name__ == "__main__": + unittest.main() diff --git a/asian_ai/performance/SGLang/test/registered/cpu/test_shared_expert.py b/asian_ai/performance/SGLang/test/registered/cpu/test_shared_expert.py new file mode 100644 index 0000000000000000000000000000000000000000..ebac248fd34e43c2a24afb37aa1e4f8109b7e6ac --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/cpu/test_shared_expert.py @@ -0,0 +1,235 @@ +import itertools +import math +import unittest + +import torch +from utils import ( + BLOCK_K, + BLOCK_N, + factor_for_scale, + fp8_max, + fp8_min, + per_token_quant_int8, + precision, + scaled_weight, + torch_naive_moe, + torch_w8a8_per_column_moe, +) + +from sglang.test.ci.ci_register import register_cpu_ci +from sglang.test.test_utils import CustomTestCase + +register_cpu_ci(est_time=10, suite="base-b-test-cpu") + +torch.manual_seed(1234) + + +class TestSharedExpert(CustomTestCase): + M = [2, 121] + N = [32, 32 * 4] + K = [32, 32 * 2] + routed_scaling_factor = [16] + apply_scaling_factor = [True, False] + + M_fp8 = [2, 12] + N_fp8 = [512] + K_fp8 = [256] + + def _bf16_shared_expert(self, m, n, k, routed_scaling_factor, apply_scaling_factor): + dtype = torch.bfloat16 + + hidden_states = torch.randn(m, k, dtype=dtype) / k + w1 = torch.randn(2 * n, k, dtype=dtype) + w2 = torch.randn(k, n, dtype=dtype) + fused_output = ( + torch.randn(m, k, dtype=dtype) / k if apply_scaling_factor else None + ) + routed_scaling_factor = routed_scaling_factor if apply_scaling_factor else None + + # fused moe mutates content in hs + hidden_states2 = hidden_states.clone() + + # bfloat16 + ref = torch_naive_moe( + hidden_states, + w1, + w2, + fused_output, + routed_scaling_factor, + output_dtype=dtype, + ) + out = torch.ops.sgl_kernel.shared_expert_cpu( + hidden_states2, + w1, + w2, + fused_output, + routed_scaling_factor, + True, + False, + False, + None, + None, + None, + False, + ) + + atol = rtol = precision[ref.dtype] + torch.testing.assert_close(ref, out, atol=atol, rtol=rtol) + + def test_bf16_shared_expert(self): + for params in itertools.product( + self.M, + self.N, + self.K, + self.routed_scaling_factor, + self.apply_scaling_factor, + ): + with self.subTest( + m=params[0], + n=params[1], + k=params[2], + routed_scaling_factor=params[3], + apply_scaling_factor=params[4], + ): + self._bf16_shared_expert(*params) + + def _int8_shared_expert(self, m, n, k, routed_scaling_factor, apply_scaling_factor): + dtype = torch.bfloat16 + + hidden_states = torch.randn(m, k, dtype=dtype) / k + w1 = torch.randn(2 * n, k, dtype=dtype) + w2 = torch.randn(k, n, dtype=dtype) + fused_output = ( + torch.randn(m, k, dtype=dtype) / k if apply_scaling_factor else None + ) + routed_scaling_factor = routed_scaling_factor if apply_scaling_factor else None + + # fused moe mutates content in hs + hidden_states2 = hidden_states.clone() + + w1_q, w1_s = per_token_quant_int8(w1) + w2_q, w2_s = per_token_quant_int8(w2) + ref = torch_w8a8_per_column_moe( + hidden_states, + w1_q, + w2_q, + w1_s, + w2_s, + fused_output, + routed_scaling_factor, + ) + out = torch.ops.sgl_kernel.shared_expert_cpu( + hidden_states2, + w1_q, + w2_q, + fused_output, + routed_scaling_factor, + True, + True, + False, + w1_s, + w2_s, + None, + False, + ) + + atol = rtol = precision[ref.dtype] + torch.testing.assert_close(ref, out, atol=atol, rtol=rtol) + + def test_int8_shared_expert(self): + for params in itertools.product( + self.M, + self.N, + self.K, + self.routed_scaling_factor, + self.apply_scaling_factor, + ): + with self.subTest( + m=params[0], + n=params[1], + k=params[2], + routed_scaling_factor=params[3], + apply_scaling_factor=params[4], + ): + self._int8_shared_expert(*params) + + def _fp8_shared_expert(self, m, n, k, routed_scaling_factor, apply_scaling_factor): + dtype = torch.bfloat16 + + hidden_states = torch.randn(m, k, dtype=dtype) / math.sqrt(k) + + w1_fp32 = torch.randn(1, 2 * n, k) + w1 = (w1_fp32 * fp8_max).clamp(min=fp8_min, max=fp8_max).to(torch.float8_e4m3fn) + + w2_fp32 = torch.randn(1, k, n) + w2 = (w2_fp32 * fp8_max).clamp(min=fp8_min, max=fp8_max).to(torch.float8_e4m3fn) + + w1s = torch.randn(1, 2 * n // BLOCK_N, k // BLOCK_K) * factor_for_scale + w2s = torch.randn(1, k // BLOCK_N, n // BLOCK_K) * factor_for_scale + + w1_scaled = scaled_weight(w1, w1s).view(2 * n, k) + w2_scaled = scaled_weight(w2, w2s).view(k, n) + + # change back to 2D + w1, w2 = w1.squeeze(0), w2.squeeze(0) + w1s, w2s = w1s.squeeze(0), w2s.squeeze(0) + w1_scaled, w2_scaled = w1_scaled.squeeze(0), w2_scaled.squeeze(0) + + fused_output = ( + torch.randn(m, k, dtype=dtype) / math.sqrt(k) + if apply_scaling_factor + else None + ) + routed_scaling_factor = routed_scaling_factor if apply_scaling_factor else None + hidden_states2 = hidden_states.clone() + + # ref with bfloat16 + ref = torch_naive_moe( + hidden_states, + w1_scaled, + w2_scaled, + fused_output, + routed_scaling_factor, + output_dtype=dtype, + ) + + w1 = torch.ops.sgl_kernel.convert_weight_packed(w1) # [2N, K] + w2 = torch.ops.sgl_kernel.convert_weight_packed(w2) # [K, N] + out = torch.ops.sgl_kernel.shared_expert_cpu( + hidden_states2, + w1, + w2, + fused_output, + routed_scaling_factor, + True, + False, + True, + w1s, + w2s, + [BLOCK_N, BLOCK_K], + True, + ) + + atol = rtol = precision[ref.dtype] + torch.testing.assert_close(ref, out, atol=atol, rtol=rtol) + + def test_fp8_shared_expert(self): + for params in itertools.product( + self.M_fp8, + self.N_fp8, + self.K_fp8, + self.routed_scaling_factor, + self.apply_scaling_factor, + ): + with self.subTest( + m=params[0], + n=params[1], + k=params[2], + routed_scaling_factor=params[3], + apply_scaling_factor=params[4], + ): + self._fp8_shared_expert(*params) + + +if __name__ == "__main__": + unittest.main() diff --git a/asian_ai/performance/SGLang/test/registered/cpu/test_store_cache.py b/asian_ai/performance/SGLang/test/registered/cpu/test_store_cache.py new file mode 100644 index 0000000000000000000000000000000000000000..32ba1af31e459f05ec6b5c37033c0db34062f47a --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/cpu/test_store_cache.py @@ -0,0 +1,83 @@ +import sys + +import pytest +import torch + +from sglang.test.ci.ci_register import register_cpu_ci + +register_cpu_ci(est_time=25, suite="base-b-test-cpu") + +torch.manual_seed(42) + +DEVICE = "cpu" +CACHE_SIZE = 4096 + +# for fp8 KV stored as uint8, e.g. float8_e4m3fn and float8_e5m2 +DTYPES = [torch.float16, torch.bfloat16, torch.uint8] +DTYPE_IDS = ["float16", "bfloat16", "uint8"] + + +def _store_cache_cpu(k, v, k_cache, v_cache, indices): + row_dim = k.size(1) * k.size(2) + torch.ops.sgl_kernel.store_cache_cpu(k, v, k_cache, v_cache, indices, row_dim) + + +def _random_tensor(shape, dtype): + """FP8 KV is stored as uint8; randn is not implemented for Byte.""" + if dtype == torch.uint8: + return torch.randint(0, 256, shape, dtype=torch.uint8, device=DEVICE) + return torch.randn(shape, dtype=dtype, device=DEVICE) + + +@pytest.mark.parametrize("dtype", DTYPES, ids=DTYPE_IDS) +@pytest.mark.parametrize("head_dim", [64, 128]) +@pytest.mark.parametrize("num_heads", [1, 8, 16, 32]) +@pytest.mark.parametrize("batch_size", [1, 7, 133]) +def test_store_cache(batch_size, num_heads, head_dim, dtype): + shape = (batch_size, num_heads, head_dim) + cache_shape = (CACHE_SIZE, num_heads, head_dim) + k = _random_tensor(shape, dtype) + v = _random_tensor(shape, dtype) + k_cache = _random_tensor(cache_shape, dtype) + v_cache = _random_tensor(cache_shape, dtype) + indices = torch.randperm(CACHE_SIZE, device=DEVICE, dtype=torch.int64)[:batch_size] + + k_cache_ref = k_cache.clone() + v_cache_ref = v_cache.clone() + k_cache_ref[indices] = k + v_cache_ref[indices] = v + + _store_cache_cpu(k, v, k_cache, v_cache, indices) + + assert torch.equal(k_cache, k_cache_ref) + assert torch.equal(v_cache, v_cache_ref) + + +@pytest.mark.parametrize("dtype", DTYPES, ids=DTYPE_IDS) +@pytest.mark.parametrize("head_dim", [64, 128]) +@pytest.mark.parametrize("num_heads", [1, 8]) +@pytest.mark.parametrize("batch_size", [11]) +def test_store_cache_int32_indices(batch_size, num_heads, head_dim, dtype): + shape = (batch_size, num_heads, head_dim) + cache_shape = (CACHE_SIZE, num_heads, head_dim) + k = _random_tensor(shape, dtype) + v = _random_tensor(shape, dtype) + k_cache = _random_tensor(cache_shape, dtype) + v_cache = _random_tensor(cache_shape, dtype) + indices = torch.randperm(CACHE_SIZE, device=DEVICE, dtype=torch.int64)[ + :batch_size + ].to(torch.int32) + + k_cache_ref = k_cache.clone() + v_cache_ref = v_cache.clone() + k_cache_ref[indices.long()] = k + v_cache_ref[indices.long()] = v + + _store_cache_cpu(k, v, k_cache, v_cache, indices) + + assert torch.equal(k_cache, k_cache_ref) + assert torch.equal(v_cache, v_cache_ref) + + +if __name__ == "__main__": + sys.exit(pytest.main([__file__])) diff --git a/asian_ai/performance/SGLang/test/registered/cpu/test_topk.py b/asian_ai/performance/SGLang/test/registered/cpu/test_topk.py new file mode 100644 index 0000000000000000000000000000000000000000..440a0c3a9a59b7c387ad547498f195ed56439af1 --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/cpu/test_topk.py @@ -0,0 +1,256 @@ +import unittest + +import torch + +from sglang.srt.eplb.expert_location_dispatch import ExpertLocationDispatchInfo +from sglang.srt.layers.moe.topk import ( + biased_grouped_topk_impl as native_biased_grouped_topk, +) +from sglang.srt.layers.moe.topk import biased_topk_impl as native_biased_topk +from sglang.srt.layers.moe.topk import fused_topk_torch_native as native_fused_topk +from sglang.srt.layers.moe.topk import grouped_topk_gpu as native_grouped_topk +from sglang.srt.models.llama4 import Llama4MoE +from sglang.test.ci.ci_register import register_cpu_ci +from sglang.test.test_utils import CustomTestCase + +register_cpu_ci(est_time=10, suite="base-b-test-cpu") +register_cpu_ci(est_time=10, suite="base-b-test-cpu-arm64") + + +# This is used by the Deepseek-V2 model +class TestGroupedTopK(CustomTestCase): + def _run_single_test(self, M, E, G, topk, topk_group, renormalize, dtype): + torch.manual_seed(12) + + # expand gating_output by M, otherwise bfloat16 fall into same value aftering truncating + hidden_states = torch.randn(M, 100, dtype=dtype) + gating_output = torch.randn(M, E, dtype=dtype) * 2 * M + + ref_topk_weights, ref_topk_ids = native_grouped_topk( + hidden_states.float(), + gating_output.float(), + topk, + renormalize, + G, + topk_group, + ) + + # fused version + topk_weights, topk_ids = torch.ops.sgl_kernel.grouped_topk_cpu( + hidden_states, + gating_output, + topk, + renormalize, + G, + topk_group, + 0, + None, + None, + ) + + res = torch.zeros(M, E, dtype=torch.float) + ref = torch.zeros(M, E, dtype=torch.float) + res.scatter_(1, topk_ids.long(), topk_weights) + ref.scatter_(1, ref_topk_ids.long(), ref_topk_weights) + torch.testing.assert_close(res, ref) + + def test_grouped_topk(self): + for renormalize in [True, False]: + self._run_single_test(123, 8, 2, 2, 1, renormalize, torch.bfloat16) + self._run_single_test(123, 16, 4, 3, 2, renormalize, torch.bfloat16) + self._run_single_test(123, 32, 4, 3, 2, renormalize, torch.bfloat16) + self._run_single_test(1123, 32, 4, 3, 2, renormalize, torch.bfloat16) + self._run_single_test(123, 64, 1, 6, 1, renormalize, torch.bfloat16) + self._run_single_test(123, 256, 8, 4, 8, renormalize, torch.bfloat16) + self._run_single_test(123, 160, 8, 6, 2, renormalize, torch.bfloat16) + + +# DeepSeek V2/V3/R1 uses biased_grouped_top +class TestBiasedGroupedTopK(CustomTestCase): + def _run_single_test( + self, + M, + E, + G, + topk, + topk_group, + renormalize, + gating_dtype, + bias_dtype, + routed_scaling_factor, + ): + torch.manual_seed(1024) + + # expand gating_output by M, otherwise bfloat16 fall into same value aftering truncating + hidden_states = torch.randn(M, 100, dtype=torch.bfloat16) + gating_output = torch.randn(M, E, dtype=gating_dtype) * 2 * M + correction_bias = torch.randn(E, dtype=bias_dtype) + + ref_topk_weights, ref_topk_ids = native_biased_grouped_topk( + hidden_states.float(), + gating_output.float(), + correction_bias.float(), + topk, + renormalize, + G, + topk_group, + ) + ref_topk_weights = ( + ref_topk_weights * routed_scaling_factor + if routed_scaling_factor is not None + else ref_topk_weights + ) + # fused version + topk_weights, topk_ids = torch.ops.sgl_kernel.biased_grouped_topk_cpu( + hidden_states, + gating_output, + correction_bias, + topk, + renormalize, + G, + topk_group, + 0, + routed_scaling_factor, + None, + ) + + res = torch.zeros(M, E, dtype=torch.float) + ref = torch.zeros(M, E, dtype=torch.float) + res.scatter_(1, topk_ids.long(), topk_weights) + ref.scatter_(1, ref_topk_ids.long(), ref_topk_weights) + torch.testing.assert_close(res, ref) + + def test_biased_grouped_topk(self): + for renormalize in [False]: + for bias_dtype in [torch.float32, torch.bfloat16]: + for gating_dtype in [torch.float32, torch.bfloat16]: + for routed_scaling_factor in [None, 1.125]: + for E_num in [128, 192, 256, 384]: + self._run_single_test( + 34, + E_num, + 8, + 8, + 2, + renormalize, + gating_dtype, + bias_dtype, + routed_scaling_factor, + ) + + +class TestBiasedTopK(CustomTestCase): + def test_biased_topk_returns_logical_ids_with_eplb_info(self): + hidden_states = torch.ones(1, 4) + gating_output = torch.tensor([[10.0, 9.0, 1.0, 0.0]]) + correction_bias = torch.zeros(4) + dispatch_info = ExpertLocationDispatchInfo( + ep_dispatch_algorithm="static", + partial_logical_to_rank_dispatch_physical_map=torch.tensor( + [2, 3, 0, 1], dtype=torch.int64 + ), + partial_logical_to_all_physical_map=torch.tensor( + [[2], [3], [0], [1]], dtype=torch.int64 + ), + partial_logical_to_all_physical_map_num_valid=torch.ones( + 4, dtype=torch.int64 + ), + num_physical_experts=4, + ) + + _, topk_ids = native_biased_topk( + hidden_states=hidden_states, + gating_output=gating_output, + correction_bias=correction_bias, + topk=2, + renormalize=False, + scoring_func="sqrtsoftplus", + expert_location_dispatch_info=dispatch_info, + ) + + torch.testing.assert_close(topk_ids, torch.tensor([[0, 1]], dtype=torch.int32)) + + +class TestTopK(CustomTestCase): + def _run_single_test(self, M, E, topk, renormalize, dtype): + torch.manual_seed(1998) + + # expand gating_output by M, otherwise bfloat16 fall into same value aftering truncating + hidden_states = torch.randn(M, 100, dtype=dtype) + gating_output = torch.randn(M, E, dtype=dtype) * 2 * M + + ref_topk_weights, ref_topk_ids = native_fused_topk( + hidden_states.float(), + gating_output.float(), + topk, + renormalize, + ) + + # fused version + topk_weights, topk_ids = torch.ops.sgl_kernel.topk_softmax_cpu( + hidden_states, gating_output, topk, renormalize + ) + + res = torch.zeros(M, E, dtype=torch.float) + ref = torch.zeros(M, E, dtype=torch.float) + res.scatter_(1, topk_ids.long(), topk_weights) + ref.scatter_(1, ref_topk_ids.long(), ref_topk_weights) + torch.testing.assert_close(res, ref) + + def test_topk(self): + for renormalize in [True, False]: + self._run_single_test(123, 8, 2, renormalize, torch.bfloat16) + self._run_single_test(123, 16, 3, renormalize, torch.bfloat16) + self._run_single_test(123, 32, 3, renormalize, torch.bfloat16) + self._run_single_test(123, 32, 3, renormalize, torch.bfloat16) + self._run_single_test(123, 64, 6, renormalize, torch.bfloat16) + self._run_single_test(123, 256, 4, renormalize, torch.bfloat16) + self._run_single_test(123, 160, 6, renormalize, torch.bfloat16) + + +class TestCustomTopK(CustomTestCase): + def _run_single_test( + self, M, E, topk, renormalize, dtype, native_custom_f, fused_custom_f + ): + torch.manual_seed(16) + + # expand gating_output by M, otherwise bfloat16 fall into same value aftering truncating + hidden_states = torch.randn(M, 100, dtype=dtype) + gating_output = torch.randn(M, E, dtype=dtype) * 2 * M + + ref_topk_weights, ref_topk_ids = native_custom_f( + hidden_states.float(), + gating_output.float(), + topk, + renormalize, + ) + + # fused version + topk_weights, topk_ids = fused_custom_f( + hidden_states, gating_output, topk, renormalize + ) + + res = torch.zeros(M, E, dtype=torch.float) + ref = torch.zeros(M, E, dtype=torch.float) + res.scatter_(1, topk_ids.long(), topk_weights) + ref.scatter_(1, ref_topk_ids.long(), ref_topk_weights) + torch.testing.assert_close(res, ref) + + def test_custom_topk(self): + test_custom_functions = [ + (Llama4MoE.custom_routing_function, torch.ops.sgl_kernel.topk_sigmoid_cpu) + ] + for native_custom_f, fused_custom_f in test_custom_functions: + self._run_single_test( + 123, 8, 1, False, torch.bfloat16, native_custom_f, fused_custom_f + ) + self._run_single_test( + 123, 16, 1, False, torch.bfloat16, native_custom_f, fused_custom_f + ) + self._run_single_test( + 123, 32, 1, False, torch.bfloat16, native_custom_f, fused_custom_f + ) + + +if __name__ == "__main__": + unittest.main() diff --git a/asian_ai/performance/SGLang/test/registered/cpu/utils.py b/asian_ai/performance/SGLang/test/registered/cpu/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..e9ab3bc89b997babc737b7f122e80c554e95a57e --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/cpu/utils.py @@ -0,0 +1,656 @@ +import itertools +import math + +import torch +import torch.nn.functional as F + +precision = { + torch.bfloat16: 1e-2, + torch.float16: 1e-3, + torch.float32: 1e-5, +} + + +BLOCK_N, BLOCK_K = 64, 128 +factor_for_scale = 1e-3 +fp8_max, fp8_min = 400, -400 + + +def parametrize(**params): + def decorator(func): + def wrapper(self): + for combo in itertools.product(*params.values()): + kwargs = dict(zip(params.keys(), combo)) + with self.subTest(**kwargs): + func(self, **kwargs) + + return wrapper + + return decorator + + +def SiluAndMul(x: torch.Tensor) -> torch.Tensor: + d = x.shape[-1] // 2 + return F.silu(x[..., :d]) * x[..., d:] + + +def GeluAndMul(x: torch.Tensor, approximate="tanh") -> torch.Tensor: + d = x.shape[-1] // 2 + return F.gelu(x[..., :d], approximate=approximate) * x[..., d:] + + +def per_token_quant_int8(x): + x = x.float() + absmax = x.abs().max(dim=-1).values + absmax = absmax.clamp_min(1e-10).unsqueeze(-1) + scale_x = absmax / 127 + x_q = x.mul(127 / absmax) + x_q = torch.round(x_q).to(torch.int8) + + return x_q, scale_x + + +def convert_weight(weight, scale_block_size, A_dtype): + N, K = weight.size() + fp8_max = 448.0 + scale_block_size_N, scale_block_size_K = scale_block_size # (128, 128) + + pad_N = (scale_block_size_N - (N % scale_block_size_N)) % scale_block_size_N + pad_K = (scale_block_size_K - (K % scale_block_size_K)) % scale_block_size_K + + if pad_N > 0 or pad_K > 0: + weight = torch.nn.functional.pad(weight, (0, pad_K, 0, pad_N)) + + weight_blocks = weight.view( + math.ceil(N / scale_block_size_N), + scale_block_size_N, + math.ceil(K / scale_block_size_K), + scale_block_size_K, + ) # (8, 128, 8, 128) + weight_blocks = weight_blocks.permute(0, 2, 1, 3).contiguous() # (8, 8, 128, 128) + + # Step 2: compute per-block max abs values → scale + abs_max = weight_blocks.abs().amax(dim=(-2, -1), keepdim=True) # (8, 8, 1, 1) + scales = abs_max / fp8_max + scales = torch.where( + scales == 0, torch.ones_like(scales), scales + ) # avoid division by zero + + q_fp8 = (weight_blocks / scales).to(torch.float8_e4m3fn) + q_fp8_reshape = q_fp8.permute(0, 2, 1, 3).contiguous() + + if pad_N > 0 or pad_K > 0: + q_fp8_reshape = q_fp8_reshape.view(N + pad_N, K + pad_K) + q_fp8_reshape = q_fp8_reshape[:N, :K].contiguous() + else: + q_fp8_reshape = q_fp8_reshape.view(N, K) + + dq_weight = q_fp8.float() * scales + dq_weight = dq_weight.permute(0, 2, 1, 3).contiguous() # (8, 128, 8, 128) + + if pad_N > 0 or pad_K > 0: + w_dq = dq_weight.view(N + pad_N, K + pad_K).to(A_dtype) + w_dq = w_dq[:N, :K].contiguous() + else: + w_dq = dq_weight.view(N, K).to(A_dtype) + + scales = scales.view( + math.ceil(N / scale_block_size_N), math.ceil(K / scale_block_size_K) + ) + + return q_fp8_reshape, scales, w_dq + + +def native_w8a8_per_token_matmul(A, B, As, Bs, bias, output_dtype=torch.bfloat16): + """Matrix multiplication function that supports per-token input quantization and per-column weight quantization""" + A = A.to(torch.float32) + B = B.to(torch.float32) + + assert A.shape[-1] == B.shape[-1], "Dimension mismatch" + assert B.ndim == 2 and B.is_contiguous(), "B must be a 2D contiguous tensor" + + # Reshape input + M = A.numel() // A.shape[-1] + B = B.t() # Transpose weight matrix + N, K = B.shape + origin_C_shape = A.shape[:-1] + (K,) + A = A.reshape(M, N) + + # As is per-token [M, 1], Bs is per-column [1, K] + C = torch.matmul(A, B) # [M, K] + C = As * C * Bs.view(1, -1) # Broadcast per-column scale + + if bias is not None: + C.add_(bias.view(1, -1)) + + return C.reshape(origin_C_shape).to(output_dtype) + + +def torch_naive_moe(a, w1, w2, b, routed_scaling_factor, output_dtype=torch.bfloat16): + + a = a.to(torch.float32) + w1 = w1.to(torch.float32) + w2 = w2.to(torch.float32) + b = b.to(torch.float32) if b is not None else None + + ic1 = torch.matmul(a, w1.transpose(0, 1)) + ic2 = SiluAndMul(ic1) + ic3 = torch.matmul(ic2, w2.transpose(0, 1)) + + out = ic3 if b is None else ic3 + b * routed_scaling_factor + + return out.to(output_dtype) + + +def torch_w8a8_per_column_moe( + a, w1_q, w2_q, w1_s, w2_s, b, routed_scaling_factor, output_dtype=torch.bfloat16 +): + + a = a.to(torch.float32) + b = b.to(torch.float32) if b is not None else None + + # Perform per-token quantization + a_q, a_s = per_token_quant_int8(a) + + ic1 = native_w8a8_per_token_matmul( + a_q, w1_q, a_s, w1_s, bias=None, output_dtype=torch.float32 + ) + ic2 = SiluAndMul(ic1) + + a1_q, a1_s = per_token_quant_int8(ic2) + ic3 = native_w8a8_per_token_matmul( + a1_q, w2_q, a1_s, w2_s, bias=None, output_dtype=torch.float32 + ) + + out = ic3 if b is None else ic3 + b * routed_scaling_factor + + return out.to(output_dtype) + + +def scaled_weight(weight, scales): + E, N, K = weight.shape + pad_N = (BLOCK_N - (N % BLOCK_N)) % BLOCK_N + pad_K = (BLOCK_K - (K % BLOCK_K)) % BLOCK_K + + if pad_N > 0 or pad_K > 0: + weight = torch.nn.functional.pad(weight, (0, pad_K, 0, pad_N)) + + weight_block = ( + weight.view(E, math.ceil(N / BLOCK_N), BLOCK_N, math.ceil(K / BLOCK_K), BLOCK_K) + .permute(0, 1, 3, 2, 4) + .float() + .contiguous() + ) + + weight_scaled = ( + ( + weight_block + * scales.view(E, math.ceil(N / BLOCK_N), math.ceil(K / BLOCK_K), 1, 1) + ) + .permute(0, 1, 3, 2, 4) + .contiguous() + ) + if pad_N > 0 or pad_K > 0: + weight_scaled = weight_scaled.view(E, N + pad_N, K + pad_K) + weight_scaled = weight_scaled[..., :N, :K].contiguous() + else: + weight_scaled = weight_scaled.view(E, N, K) + return weight_scaled + + +def torch_naive_fused_moe(a, w1, w2, score, topk, renormalize): + B, D = a.shape + a = a.view(B, -1, D).repeat(1, topk, 1).reshape(-1, D) + out = torch.zeros(B * topk, w2.shape[1], dtype=a.dtype, device=a.device) + score = torch.softmax(score, dim=-1, dtype=torch.float32) + topk_weight, topk_ids = torch.topk(score, topk) + + if renormalize: + topk_weight = topk_weight / topk_weight.sum(dim=-1, keepdim=True) + + topk_weight = topk_weight.view(-1) + topk_ids = topk_ids.view(-1) + for i in range(w1.shape[0]): + mask = topk_ids == i + if mask.sum(): + out[mask] = SiluAndMul(a[mask] @ w1[i].transpose(0, 1)) @ w2[i].transpose( + 0, 1 + ) + return ( + out.view(B, -1, w2.shape[1]) * topk_weight.view(B, -1, 1).to(out.dtype) + ).sum(dim=1) + + +def moe_gptoss_act(x, alpha: float = 1.702, limit: float = 7.0): + x_glu, x_linear = x[..., ::2], x[..., 1::2] + # Clamp the input values + x_glu = x_glu.clamp(min=None, max=limit) + x_linear = x_linear.clamp(min=-limit, max=limit) + out_glu = x_glu * torch.sigmoid(alpha * x_glu) + # Note we add an extra bias of 1 to the linear layer + return out_glu * (x_linear + 1.0) + + +def torch_naive_gptoss_fused_moe( + x, + w1, + w2, + w1_bias, + w2_bias, + topk_weights, + topk_ids, + activation_alpha, + swiglu_limit, + len_experts, +) -> torch.Tensor: + + # Ref code from https://huggingface.co/deepseek-ai/DeepSeek-V2/blob/e0828e3cc0a03408724b80c3cc92c8e072db8d01/modeling_deepseek.py#L589 + cnts = topk_ids.new_zeros((topk_ids.shape[0], len_experts)) + cnts.scatter_(1, topk_ids.to(torch.int64), 1) + tokens_per_expert = cnts.sum(dim=0) + idxs = topk_ids.view(-1).argsort() + + sorted_tokens = x[idxs // topk_ids.shape[1]] + tokens_per_expert = tokens_per_expert.cpu().numpy() + + outputs = [] + start_idx = 0 + for i, num_tokens in enumerate(tokens_per_expert): + end_idx = start_idx + num_tokens + if num_tokens == 0: + continue + tokens_for_this_expert = sorted_tokens[start_idx:end_idx] + + layer_w13_weight = w1[i] + layer_w13_weight_bias = w1_bias[i] + layer_w2_weight_bias = w2_bias[i] + layer_w2_weight = w2[i] + + gate_up = F.linear( + tokens_for_this_expert, + layer_w13_weight, + bias=layer_w13_weight_bias.to(torch.bfloat16), + ) + gate_up = moe_gptoss_act(gate_up, activation_alpha, swiglu_limit) + expert_out = F.linear( + gate_up, layer_w2_weight, bias=layer_w2_weight_bias.to(torch.bfloat16) + ) + outputs.append(expert_out) + start_idx = end_idx + + outs = torch.cat(outputs, dim=0) if len(outputs) else sorted_tokens.new_empty(0) + new_x = torch.empty_like(outs) + + new_x[idxs] = outs + final_out = ( + new_x.view(*topk_ids.shape, -1) + .type(topk_weights.dtype) + .mul_(topk_weights.unsqueeze(dim=-1)) + .sum(dim=1) + .type(new_x.dtype) + ) + return final_out + + +def torch_naive_fused_moe_gptoss( + a, + w1, + w2, + w1_bias, + w2_bias, + topk_weight, + topk_ids, + renormalize, + activation_alpha, + swiglu_limit, + len_experts, +): + if renormalize: + topk_weight = topk_weight / topk_weight.sum(dim=-1, keepdim=True) + + return torch_naive_gptoss_fused_moe( + a, + w1, + w2, + w1_bias, + w2_bias, + topk_weight, + topk_ids, + activation_alpha, + swiglu_limit, + len_experts, + ) + + +def torch_w8a8_per_column_fused_moe(a, w1, w2, w1_s, w2_s, topk_weight, topk_ids, topk): + """This function performs fused moe with per-column int8 quantization using native torch.""" + + B, D = a.shape + # Perform per-token quantization + a_q, a_s = per_token_quant_int8(a) + # Repeat tokens to match topk + a_q = a_q.view(B, -1, D).repeat(1, topk, 1).reshape(-1, D) + # Also repeat the scale + a_s = a_s.view(B, -1, 1).repeat(1, topk, 1).reshape(-1, 1) # [B*topk, 1] + + out = torch.zeros(B * topk, w2.shape[1], dtype=torch.float32, device=a.device) + + # Calculate routing + topk_weight = topk_weight.view(-1) + topk_ids = topk_ids.view(-1) + # Process each expert + for i in range(w1.shape[0]): + mask = topk_ids == i + if mask.sum(): + # First MLP layer: note that a_s is now per-token + inter_out = native_w8a8_per_token_matmul( + a_q[mask], + w1[i], + a_s[mask], + w1_s[i], + bias=None, + output_dtype=torch.float32, + ) + # Activation function + act_out = SiluAndMul(inter_out) + # Quantize activation output with per-token + act_out_q, act_out_s = per_token_quant_int8(act_out) + # Second MLP layer + out[mask] = native_w8a8_per_token_matmul( + act_out_q, + w2[i], + act_out_s, + w2_s[i], + bias=None, + output_dtype=torch.float32, + ) + # Apply routing weights and sum + return ( + (out.view(B, -1, w2.shape[1]) * topk_weight.view(B, -1, 1).to(out.dtype)) + .sum(dim=1) + .to(a.dtype) + ) + + +def native_fp8_fused_moe(a, w1, w2, topk_weight, topk_ids, topk): + B, D = a.shape + a = a.view(B, -1, D).repeat(1, topk, 1).reshape(-1, D).float() + out = torch.zeros(B * topk, w2.shape[1], dtype=torch.float32, device=a.device) + + # Calculate routing + topk_weight = topk_weight.view(-1) + topk_ids = topk_ids.view(-1) + + for i in range(w1.shape[0]): + mask = topk_ids == i + if mask.sum(): + ic0 = torch.matmul(a[mask], w1[i].transpose(0, 1)) + ic1 = SiluAndMul(ic0) + out[mask] = torch.matmul(ic1, w2[i].transpose(0, 1)) + + return ( + (out.view(B, -1, w2.shape[1]) * topk_weight.view(B, -1, 1).to(out.dtype)) + .sum(dim=1) + .to(a.dtype) + ) + + +# https://github.com/NVIDIA/TensorRT-Model-Optimizer/blob/main/modelopt/torch/quantization/qtensor/mxfp4_tensor.py +class MXFP4QuantizeUtil: + E2M1_max = 6.0 + + E2M1_values = [0, 0.5, 1, 1.5, 2, 3, 4, 6] + E2M1_bounds = torch.tensor([0.25, 0.75, 1.25, 1.75, 2.5, 3.5, 5]) + + block_size = 32 + + @classmethod + def quantize(cls, input: torch.Tensor) -> tuple: + """Converting a tensor to a quantized format based on MXFP4 quantization. Only E4M3 is supported. + Args: + input (torch.Tensor): The input tensor to be quantized. + """ + + def cast_fp4(x): + sign = torch.sign(x) + sign_bit = (2 - sign) // 2 + ord_ = torch.sum( + (x.abs().unsqueeze(-1) - cls.E2M1_bounds.to(x.device)) > 0, dim=-1 + ) + fp4_val = (sign_bit * 0b1000 + ord_).to(torch.uint8) + return fp4_val + + def fuse_uint4_to_uint8(x): + # If the last dimension is odd, pad with zeros + # If this behavior is not desired, please modify the code accordingly + left_side = x[..., 0::2] # Even indices (0, 2, 4...) + right_side = x[..., 1::2] # Odd indices (1, 3, 5...) + new_data = ( + right_side.clone() << 4 + ) # Put odd indices (higher addresses) in high bits + new_data[ + ..., : left_side.shape[-1] + ] += left_side # Put even indices in low bits + return new_data + + original_shape = input.shape + original_dtype = input.dtype + input = input.view(-1, cls.block_size) + # get scales + input_amax = input.abs().max(dim=-1, keepdim=True).values + descale = input_amax / cls.E2M1_max + min_value = torch.tensor(-127.0, device=descale.device) + e8m0_scale = torch.ceil(torch.maximum(torch.log2(descale), min_value)) + + input = (input / torch.exp2(e8m0_scale)).view(original_shape) + input_q = cast_fp4(input) + input_q = fuse_uint4_to_uint8(input_q) + e8m0_scale = (e8m0_scale + 127).to(torch.uint8) + return input_q, e8m0_scale + + @classmethod + def dequantize(cls, quantized_data, dtype: torch.dtype, scale): + """Dequantze MXFP4 packed tensor to a target dtype.""" + + def unfuse_uint8_to_uint4(x): + """Unfuse uint8 values back to uint4 values. + This is the inverse operation of fuse_uint4_to_uint8. + """ + # Extract the lower 4 bits (even indices) + left_side = x & 0x0F + + # Extract the upper 4 bits (odd indices) + right_side = (x >> 4) & 0x0F + + # Create a new tensor with alternating values + shape = list(x.shape) + shape[-1] = shape[-1] * 2 + result = torch.zeros(shape, dtype=torch.uint8, device=x.device) + + # Fill in the values - even indices get low bits, odd indices get high bits + result[..., 0::2] = left_side # Even indices from low bits + result[..., 1::2] = right_side # Odd indices from high bits + + return result + + e8m0_scale = scale + + # Unfuse the uint8 values back to uint4 + x_unfused = unfuse_uint8_to_uint4(quantized_data) + # print("@@@ x_unfused: ", x_unfused) + # Extract sign and magnitude + sign = 1 - 2 * ((x_unfused & 0b1000) >> 3).to( + torch.float32 + ) # Extract sign bit and convert to +1/-1 + magnitude = x_unfused & 0b0111 # Extract magnitude bits + magnitude = magnitude.to(torch.long) + + # Create a tensor with the E2M1 values + values = torch.tensor(cls.E2M1_values, device=quantized_data.device) + + # Use gather to index the values tensor properly + # We need to reshape magnitude to match the dimensions we want to gather along + original_shape = magnitude.shape + x_float = values[magnitude.reshape(-1)].reshape(original_shape) + + # Apply sign and scale + x_float = sign.float() * x_float + + # Reshape to apply block-wise scaling + x_float = x_float.reshape(-1, cls.block_size) + + # Apply the E8M0 scale + scale_factor = torch.exp2(e8m0_scale.float() - 127) + scale_factor = scale_factor.reshape(-1, 1) # Reshape for proper broadcasting + + # Apply scaling and reshape back to original shape + x_float = x_float * scale_factor + + # Reshape back to the original shape + return x_float.reshape(original_shape).to(dtype) + + +def make_non_contiguous(x: torch.Tensor) -> torch.Tensor: + """ + Make a tensor non-contiguous by slicing it via last dimension. + """ + last_dim = x.shape[-1] + return x[..., : last_dim // 2] if x.is_contiguous() else x + + +def awq_reverse_reorder_int_tensor(int_tensor, bits: int): + assert bits == 4 + + int_tensor = int_tensor.T.contiguous() + compress_ratio = 32 // bits + assert int_tensor.shape[-1] % compress_ratio == 0 + + order_map = [0, 2, 4, 6, 1, 3, 5, 7] + order_tensor = torch.tensor( + order_map, dtype=torch.int32, device=int_tensor.device + ).reshape(1, -1) + order_tensor = order_tensor.repeat(int_tensor.shape[1] // compress_ratio, 1) + order_tensor = order_tensor + torch.arange( + 0, + int_tensor.shape[1], + compress_ratio, + dtype=torch.int32, + device=int_tensor.device, + ).reshape(-1, 1) + order_tensor = order_tensor.reshape(-1) + + reverse_order_tensor = torch.arange(order_tensor.shape[0])[order_tensor] + reverse_order_tensor = reverse_order_tensor[order_tensor] + int_tensor = int_tensor[:, reverse_order_tensor] + return int_tensor + + +def unpack_and_dequant_awq( + awq_qweight: torch.Tensor, + awq_qzeros: torch.Tensor, + awq_scales: torch.Tensor, + bits: int, + group_size: int, +): + """ + Args: + awq_qweight (`torch.LongTensor`): + Expected shape: (in_features, out_features // (32 // bits)) + awq_qzeros (`torch.LongTensor`): + Expected shape: (in_features // group_size, out_features // (32 // bits)) + awq_scales (`torch.LongTensor`): + Expected shape: (in_features // group_size, out_features) + + Returns: + fp16_weight (`torch.LongTensor`): + With shape (in_features, out_features). + zeros (`torch.LongTensor`): + With shape (in_features // group_size, out_features). + """ + assert bits == 4 + + qzeros = awq_qzeros + qweight = awq_qweight + qweight = qweight.T.contiguous() + + scales = awq_scales + scales = scales.reshape(-1, 1, scales.shape[-1]) + + infeatures = awq_qweight.shape[0] + + wf = torch.tensor( + list(range(0, 32, bits)), dtype=torch.int32, device=qzeros.device + ).unsqueeze(0) + zeros = torch.bitwise_right_shift(torch.unsqueeze(qzeros, 2), wf.unsqueeze(0)).to( + torch.int16 if bits == 8 else torch.int8 + ) + + torch.bitwise_and(zeros, (2**bits) - 1, out=zeros) + + zeros = zeros.reshape(-1, 1, zeros.shape[1] * zeros.shape[2]) + + weight = torch.bitwise_right_shift( + torch.unsqueeze(qweight, 1), wf.unsqueeze(-1) + ).to(torch.int16 if bits == 8 else torch.int8) + torch.bitwise_and(weight, (2**bits) - 1, out=weight) + weight = weight.reshape(-1, group_size, weight.shape[2]) + + weight = weight.view(-1, weight.shape[-1]) + zeros = zeros.view(-1, zeros.shape[-1]) + + zeros = zeros.T.contiguous() + zeros = awq_reverse_reorder_int_tensor(zeros, bits) + weight = awq_reverse_reorder_int_tensor(weight, bits) + + # Dequantize weights. + scales = awq_scales + zeros = zeros.contiguous() + scale_zeros = zeros * scales + + g_idx = torch.tensor( + [i // group_size for i in range(infeatures)], dtype=torch.int32 + ) + scale_mat = scales[g_idx] + scale_zeros_mat = scale_zeros[g_idx].to(torch.bfloat16) + + qdq_weight_T = weight * scale_mat - scale_zeros_mat.to(torch.bfloat16) + + fp16_weight = qdq_weight_T.T + + return fp16_weight, zeros + + +def unpack_4bit_to_32bit_signed(qweight, qzeros): + # Unpack 4-bit values and interpret them as signed integers + unpacked_weights = torch.zeros( + (qweight.shape[0] * 8, qweight.shape[1]), + dtype=torch.int8, + device=qweight.device, + requires_grad=False, + ) + unpacked_zeros = torch.zeros( + (qzeros.shape[0], qzeros.shape[1] * 8), + dtype=torch.int8, + device=qzeros.device, + requires_grad=False, + ) + + for row in range(unpacked_weights.shape[0]): + i = row % 8 + unpacked_weights[row, :] = (qweight[row // 8, :] >> (4 * i)) & 0xF + + for col in range(unpacked_zeros.shape[1]): + i = col % 8 + unpacked_zeros[:, col] = (qzeros[:, col // 8] >> (4 * i)) & 0xF + + return unpacked_weights, unpacked_zeros + 1 + + +def unpack_and_dequant_gptq(qweight, qzeros, scales): + unpacked_qweight, unpacked_qzeros = unpack_4bit_to_32bit_signed(qweight, qzeros) + group_size = unpacked_qweight.shape[0] // scales.shape[0] + scales = scales.repeat_interleave(group_size, dim=0) + unpacked_qzeros = unpacked_qzeros.repeat_interleave(group_size, dim=0) + unpacked_qweight = (unpacked_qweight - unpacked_qzeros) * scales + + return unpacked_qweight.T diff --git a/asian_ai/performance/SGLang/test/registered/cuda_graph/breakable/test_bcg_with_speculative_decoding.py b/asian_ai/performance/SGLang/test/registered/cuda_graph/breakable/test_bcg_with_speculative_decoding.py new file mode 100644 index 0000000000000000000000000000000000000000..6a034d009c6592fb041f5fad5d55fc8c2577f68e --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/cuda_graph/breakable/test_bcg_with_speculative_decoding.py @@ -0,0 +1,46 @@ +"""Test breakable CUDA graph (BCG) coexisting with EAGLE3 speculative +decoding. Sibling of test_pcg_with_speculative_decoding.py — same +target/draft pair, only flips the prefill backend from tc_piecewise to +breakable. Verifies the draft-side BCG plumbing in PrefillCudaGraphRunner +stays wired (capture_hidden_mode for EAGLE, static_draft_hidden_states +buffer sized from the draft's fc input, EagleDraftInput at capture, and +the load_batch refresh). +""" + +import unittest + +from sglang.test.ci.ci_register import register_cuda_ci +from sglang.test.server_fixtures.pcg_spec_fixture import PCGSpecBase + +register_cuda_ci(est_time=531, stage="base-b", runner_config="2-gpu-large") + + +class TestBCGWithEAGLE3(PCGSpecBase, unittest.TestCase): + """BCG + EAGLE3 on Qwen3-30B-A3B-Instruct-2507.""" + + model = "Qwen/Qwen3-30B-A3B-Instruct-2507" + server_args = [ + "--tp", + "2", + "--trust-remote-code", + "--cuda-graph-backend-prefill=breakable", + "--mem-fraction-static", + "0.6", + "--speculative-algorithm", + "EAGLE3", + "--speculative-draft-model-path", + "lmsys/SGLang-EAGLE3-Qwen3-30B-A3B-Instruct-2507-SpecForge-Nex", + "--speculative-num-steps", + "5", + "--speculative-eagle-topk", + "4", + "--speculative-num-draft-tokens", + "8", + ] + timeout_mult = 3 + server_env = {"SGLANG_ALLOW_OVERWRITE_LONGER_CONTEXT_LEN": "1"} + accuracy_threshold = 0.75 + + +if __name__ == "__main__": + unittest.main() diff --git a/asian_ai/performance/SGLang/test/registered/cuda_graph/breakable/test_breakable_cuda_graph.py b/asian_ai/performance/SGLang/test/registered/cuda_graph/breakable/test_breakable_cuda_graph.py new file mode 100644 index 0000000000000000000000000000000000000000..9d4d1521fcc9e6af43a09b1e157af9efb2f05b39 --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/cuda_graph/breakable/test_breakable_cuda_graph.py @@ -0,0 +1,305 @@ +"""Tests for the breakable CUDA graph (BCG) runner. + +Two test classes: +- TestBreakableCUDAGraphBasic / TestCopyOutput / TestBreakGraphHelper: + unit tests for the core capture / replay mechanism (simple tensor ops). +- TestBreakableCudaGraph: integration test — spin up Qwen3-8B with + --enable-breakable-cuda-graph and check mgsm_en accuracy. +""" + +import unittest + +import torch + +from sglang.srt.utils import kill_process_tree +from sglang.test.ci.ci_register import register_amd_ci, register_cuda_ci +from sglang.test.run_eval import run_eval +from sglang.test.test_utils import ( + DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH, + DEFAULT_URL_FOR_TEST, + CustomTestCase, + SimpleNamespace, + popen_launch_server, +) + +# CI Registration — large suite to fit the integration test's server startup. +register_cuda_ci(est_time=79, stage="base-b", runner_config="1-gpu-large") +register_amd_ci(est_time=200, suite="stage-c-test-large-8-gpu-amd-mi35x") + + +class TestBreakableCUDAGraphBasic(CustomTestCase): + """Test basic breakable CUDA graph capture and replay.""" + + @classmethod + def setUpClass(cls): + if not torch.cuda.is_available(): + raise unittest.SkipTest("CUDA not available") + + from sglang.srt.model_executor.runner_backend_utils.breakable_cuda_graph.breakable_cuda_graph import ( + BreakableCUDAGraph, + BreakableCUDAGraphCapture, + eager_on_graph, + ) + + cls.BreakableCUDAGraph = BreakableCUDAGraph + cls.BreakableCUDAGraphCapture = BreakableCUDAGraphCapture + cls.eager_on_graph = staticmethod(eager_on_graph) + cls.device = torch.device("cuda:0") + + def test_no_break_capture_replay(self): + """Capture and replay without any graph breaks should work like normal CUDA graph.""" + x = torch.zeros(4, device=self.device) + y = torch.zeros(4, device=self.device) + + graph = self.BreakableCUDAGraph() + stream = torch.cuda.Stream(self.device) + with self.BreakableCUDAGraphCapture(graph, stream=stream): + y.copy_(x + 1.0) + + # Replay with new input + x.fill_(5.0) + graph.replay() + torch.cuda.synchronize() + self.assertTrue(torch.allclose(y, torch.full((4,), 6.0, device=self.device))) + + def test_single_break(self): + """A single graph break should split capture into two segments.""" + x = torch.zeros(4, device=self.device) + intermediate = torch.zeros(4, device=self.device) + y = torch.zeros(4, device=self.device) + + @self.eager_on_graph(enable=True) + def eager_op(src): + return src * 2.0 + + graph = self.BreakableCUDAGraph() + stream = torch.cuda.Stream(self.device) + with self.BreakableCUDAGraphCapture(graph, stream=stream): + intermediate.copy_(x + 1.0) + broken = eager_op(intermediate) + y.copy_(broken + 3.0) + + # Replay with new input + x.fill_(10.0) + graph.replay() + torch.cuda.synchronize() + # x=10 -> intermediate=11 -> eager: 11*2=22 -> y=22+3=25 + self.assertTrue(torch.allclose(y, torch.full((4,), 25.0, device=self.device))) + + def test_multiple_breaks(self): + """Multiple graph breaks should produce correct chained results.""" + x = torch.zeros(4, device=self.device) + y = torch.zeros(4, device=self.device) + + @self.eager_on_graph(enable=True) + def add_one(src): + return src + 1.0 + + @self.eager_on_graph(enable=True) + def double(src): + return src * 2.0 + + graph = self.BreakableCUDAGraph() + stream = torch.cuda.Stream(self.device) + with self.BreakableCUDAGraphCapture(graph, stream=stream): + t1 = x + 1.0 # graph segment 1 + t2 = add_one(t1) # break 1: eager + t3 = t2 + 1.0 # graph segment 2 + t4 = double(t3) # break 2: eager + y.copy_(t4) # graph segment 3 + + # Replay: x=5 -> +1=6 -> add_one=7 -> +1=8 -> double=16 + x.fill_(5.0) + graph.replay() + torch.cuda.synchronize() + self.assertTrue(torch.allclose(y, torch.full((4,), 16.0, device=self.device))) + + def test_eager_on_graph_disabled(self): + """@eager_on_graph(enable=False) should be a no-op passthrough.""" + + @self.eager_on_graph(enable=False) + def my_fn(x): + return x + 1.0 + + # Should just be the original function + t = torch.tensor([1.0, 2.0], device=self.device) + result = my_fn(t) + self.assertTrue( + torch.allclose(result, torch.tensor([2.0, 3.0], device=self.device)) + ) + + def test_eager_on_graph_outside_capture(self): + """@eager_on_graph called outside capture should run the function directly.""" + + @self.eager_on_graph(enable=True) + def my_fn(x): + return x + 1.0 + + t = torch.tensor([1.0, 2.0], device=self.device) + result = my_fn(t) + self.assertTrue( + torch.allclose(result, torch.tensor([2.0, 3.0], device=self.device)) + ) + + def test_replay_updates_output(self): + """Replay should produce different results when input buffers change.""" + x = torch.zeros(4, device=self.device) + y = torch.zeros(4, device=self.device) + + @self.eager_on_graph(enable=True) + def scale(src): + return src * 3.0 + + graph = self.BreakableCUDAGraph() + stream = torch.cuda.Stream(self.device) + with self.BreakableCUDAGraphCapture(graph, stream=stream): + t = x + 1.0 + t2 = scale(t) + y.copy_(t2) + + # First replay: x=0 -> 0+1=1 -> 1*3=3 + graph.replay() + torch.cuda.synchronize() + self.assertTrue(torch.allclose(y, torch.full((4,), 3.0, device=self.device))) + + # Second replay: x=10 -> 10+1=11 -> 11*3=33 + x.fill_(10.0) + graph.replay() + torch.cuda.synchronize() + self.assertTrue(torch.allclose(y, torch.full((4,), 33.0, device=self.device))) + + +class TestCopyOutput(CustomTestCase): + """Test the _copy_output helper for structured output writeback.""" + + @classmethod + def setUpClass(cls): + if not torch.cuda.is_available(): + raise unittest.SkipTest("CUDA not available") + + from sglang.srt.model_executor.runner_backend_utils.breakable_cuda_graph.breakable_cuda_graph import ( + _copy_output, + ) + + cls._copy_output = staticmethod(_copy_output) + cls.device = torch.device("cuda:0") + + def test_tensor_copy(self): + dst = torch.zeros(4, device=self.device) + src = torch.ones(4, device=self.device) * 5.0 + result = self._copy_output(dst, src) + self.assertIs(result, dst) + self.assertTrue(torch.allclose(dst, src)) + + def test_dict_copy(self): + dst = { + "a": torch.zeros(4, device=self.device), + "b": torch.zeros(4, device=self.device), + } + src = { + "a": torch.ones(4, device=self.device), + "b": torch.ones(4, device=self.device) * 2.0, + } + result = self._copy_output(dst, src) + self.assertIs(result, dst) + self.assertTrue(torch.allclose(dst["a"], torch.ones(4, device=self.device))) + self.assertTrue( + torch.allclose(dst["b"], torch.ones(4, device=self.device) * 2.0) + ) + + def test_object_copy(self): + class FakeOutput: + def __init__(self, t, label): + self.tensor = t + self.label = label + + dst = FakeOutput(torch.zeros(4, device=self.device), "old") + src = FakeOutput(torch.ones(4, device=self.device) * 3.0, "new") + result = self._copy_output(dst, src) + self.assertIs(result, dst) + self.assertTrue( + torch.allclose(dst.tensor, torch.ones(4, device=self.device) * 3.0) + ) + self.assertEqual(dst.label, "new") + + def test_non_tensor_fallback(self): + result = self._copy_output(42, 99) + self.assertEqual(result, 99) + + +class TestBreakGraphHelper(CustomTestCase): + """Test the break_graph() convenience function.""" + + @classmethod + def setUpClass(cls): + if not torch.cuda.is_available(): + raise unittest.SkipTest("CUDA not available") + + from sglang.srt.model_executor.runner_backend_utils.breakable_cuda_graph.breakable_cuda_graph import ( + BreakableCUDAGraph, + BreakableCUDAGraphCapture, + break_graph, + ) + + cls.BreakableCUDAGraph = BreakableCUDAGraph + cls.BreakableCUDAGraphCapture = BreakableCUDAGraphCapture + cls.break_graph = staticmethod(break_graph) + cls.device = torch.device("cuda:0") + + def test_break_graph_inserts_segment(self): + """break_graph() should insert a graph break even though it does nothing.""" + x = torch.zeros(4, device=self.device) + y = torch.zeros(4, device=self.device) + + graph = self.BreakableCUDAGraph() + stream = torch.cuda.Stream(self.device) + with self.BreakableCUDAGraphCapture(graph, stream=stream): + t = x + 1.0 + self.break_graph() + y.copy_(t + 2.0) + + x.fill_(10.0) + graph.replay() + torch.cuda.synchronize() + # x=10 -> +1=11 -> break -> +2=13 + self.assertTrue(torch.allclose(y, torch.full((4,), 13.0, device=self.device))) + + +class TestBreakableCudaGraph(CustomTestCase): + """Integration: Qwen3-8B with --enable-breakable-cuda-graph on mgsm_en.""" + + @classmethod + def setUpClass(cls): + cls.model = "Qwen/Qwen3-8B" + cls.base_url = DEFAULT_URL_FOR_TEST + cls.process = popen_launch_server( + cls.model, + cls.base_url, + timeout=DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH, + other_args=[ + "--cuda-graph-backend-prefill=breakable", + ], + ) + + @classmethod + def tearDownClass(cls): + kill_process_tree(cls.process.pid) + + def test_gsm8k_accuracy(self): + args = SimpleNamespace( + base_url=self.base_url, + model=self.model, + eval_name="mgsm_en", + num_examples=1319, + num_threads=1024, + ) + + metrics = run_eval(args) + score = metrics["score"] + print(f"mgsm_en accuracy with breakable CUDA graph: {score:.3f}") + + self.assertGreaterEqual(score, 0.80) + + +if __name__ == "__main__": + unittest.main() diff --git a/asian_ai/performance/SGLang/test/registered/cuda_graph/piecewise/test_pcg_glm52_fp4.py b/asian_ai/performance/SGLang/test/registered/cuda_graph/piecewise/test_pcg_glm52_fp4.py new file mode 100644 index 0000000000000000000000000000000000000000..24a0c53d7a61aa501e07f241f0a5849b603b01a6 --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/cuda_graph/piecewise/test_pcg_glm52_fp4.py @@ -0,0 +1,71 @@ +import unittest +from types import SimpleNamespace + +from sglang.srt.utils import kill_process_tree +from sglang.test.ci.ci_register import register_cuda_ci +from sglang.test.run_eval import run_eval +from sglang.test.test_utils import ( + DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH, + DEFAULT_URL_FOR_TEST, + CustomTestCase, + popen_launch_server, +) + +register_cuda_ci(est_time=900, stage="base-c", runner_config="4-gpu-b200") + +GLM52_FP4_MODEL = "nvidia/GLM-5.2-NVFP4" + + +class TestPCGGlm52Fp4(CustomTestCase): + """PCG prefill on GLM-5.2-NVFP4 (DSA model, TP=4, B200). + + GLM-5.2 uses GlmMoeDsaForCausalLM (DSA attention). This test verifies that + piecewise CUDA graph works correctly after the DSA indexer was updated to + cache k_fp8/k_scale for PCG-compatible prefill. + """ + + @classmethod + def setUpClass(cls): + cls.model = GLM52_FP4_MODEL + cls.base_url = DEFAULT_URL_FOR_TEST + cls.process = popen_launch_server( + cls.model, + cls.base_url, + timeout=DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH, + other_args=[ + "--tp-size", + "4", + "--trust-remote-code", + "--reasoning-parser", + "glm45", + "--tool-call-parser", + "glm47", + "--quantization", + "modelopt_fp4", + "--disable-flashinfer-autotune", + "--cuda-graph-backend-prefill=tc_piecewise", + "--model-loader-extra-config", + '{"enable_multithread_load": true, "num_threads": 64}', + ], + ) + + @classmethod + def tearDownClass(cls): + kill_process_tree(cls.process.pid) + + def test_gsm8k(self): + args = SimpleNamespace( + base_url=self.base_url, + model=self.model, + eval_name="gsm8k", + num_examples=200, + num_threads=200, + max_tokens=4096, + ) + metrics = run_eval(args) + print(f"{metrics=}") + self.assertGreater(metrics["score"], 0.92) + + +if __name__ == "__main__": + unittest.main() diff --git a/asian_ai/performance/SGLang/test/registered/cuda_graph/piecewise/test_pcg_glm52_fp8_tp8.py b/asian_ai/performance/SGLang/test/registered/cuda_graph/piecewise/test_pcg_glm52_fp8_tp8.py new file mode 100644 index 0000000000000000000000000000000000000000..6892e90d18b13306e0655bbbbfa648f3dce0e8b2 --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/cuda_graph/piecewise/test_pcg_glm52_fp8_tp8.py @@ -0,0 +1,75 @@ +import unittest +from types import SimpleNamespace + +from sglang.srt.utils import kill_process_tree +from sglang.test.ci.ci_register import register_cuda_ci +from sglang.test.run_eval import run_eval +from sglang.test.test_utils import ( + DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH, + DEFAULT_URL_FOR_TEST, + CustomTestCase, + popen_launch_server, +) + +register_cuda_ci(est_time=900, stage="base-c", runner_config="8-gpu-h200") + +GLM52_FP8_MODEL = "zai-org/GLM-5.2-FP8" + + +class TestBCGGlm52Fp8TP8(CustomTestCase): + """Breakable CUDA graph prefill on GLM-5.2-FP8 (DSA model, TP=8, H200).""" + + @classmethod + def setUpClass(cls): + cls.model = GLM52_FP8_MODEL + cls.base_url = DEFAULT_URL_FOR_TEST + cls.process = popen_launch_server( + cls.model, + cls.base_url, + timeout=DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH, + other_args=[ + "--tp-size", + "8", + "--trust-remote-code", + "--reasoning-parser", + "glm45", + "--tool-call-parser", + "glm47", + "--mem-fraction-static", + "0.8", + "--disable-flashinfer-autotune", + "--cuda-graph-backend-prefill=breakable", + # Small chunks => many prefill iterations, each <= the 2048 + # capture max, so every prefill batch replays the BCG graph and + # exercises the DSA split-op / dual-stream / MLA-fusion paths. + "--chunked-prefill-size", + "512", + "--model-loader-extra-config", + '{"enable_multithread_load": true, "num_threads": 64}', + ], + env={ + "SGLANG_ENABLE_PCG_DSV2_DUAL_STREAM": "1", + }, + ) + + @classmethod + def tearDownClass(cls): + if hasattr(cls, "process") and cls.process: + kill_process_tree(cls.process.pid) + + def test_gsm8k(self): + args = SimpleNamespace( + base_url=self.base_url, + model=self.model, + eval_name="gsm8k", + num_examples=200, + num_threads=200, + max_tokens=4096, + ) + metrics = run_eval(args) + print(f"{metrics=}") + self.assertGreater(metrics["score"], 0.92) + + +if __name__ == "__main__": + unittest.main() diff --git a/asian_ai/performance/SGLang/test/registered/cuda_graph/piecewise/test_pcg_with_speculative_decoding.py b/asian_ai/performance/SGLang/test/registered/cuda_graph/piecewise/test_pcg_with_speculative_decoding.py new file mode 100644 index 0000000000000000000000000000000000000000..3ecbe8eca9c41537b6d843e353017fc2aad2aab9 --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/cuda_graph/piecewise/test_pcg_with_speculative_decoding.py @@ -0,0 +1,45 @@ +"""Test piecewise CUDA graph coexisting with speculative decoding (EAGLE3). + +PCG handles prefill/extend path while speculative decoding (EAGLE3) uses +decode CUDA graphs. This test verifies they don't interfere with each +other. MTP / STANDALONE / NGRAM variants moved to the sibling file +test_pcg_with_speculative_decoding_extra.py. +""" + +import unittest + +from sglang.test.ci.ci_register import register_cuda_ci +from sglang.test.server_fixtures.pcg_spec_fixture import PCGSpecBase + +register_cuda_ci(est_time=531, stage="base-b", runner_config="2-gpu-large") + + +class TestPCGWithEAGLE3(PCGSpecBase, unittest.TestCase): + """PCG + EAGLE3 on Qwen3-30B-A3B-Instruct-2507.""" + + model = "Qwen/Qwen3-30B-A3B-Instruct-2507" + server_args = [ + "--tp", + "2", + "--trust-remote-code", + "--cuda-graph-backend-prefill=tc_piecewise", + "--mem-fraction-static", + "0.6", + "--speculative-algorithm", + "EAGLE3", + "--speculative-draft-model-path", + "lmsys/SGLang-EAGLE3-Qwen3-30B-A3B-Instruct-2507-SpecForge-Nex", + "--speculative-num-steps", + "5", + "--speculative-eagle-topk", + "4", + "--speculative-num-draft-tokens", + "8", + ] + timeout_mult = 3 + server_env = {"SGLANG_ALLOW_OVERWRITE_LONGER_CONTEXT_LEN": "1"} + accuracy_threshold = 0.75 + + +if __name__ == "__main__": + unittest.main() diff --git a/asian_ai/performance/SGLang/test/registered/cuda_graph/piecewise/test_pcg_with_speculative_decoding_dflash.py b/asian_ai/performance/SGLang/test/registered/cuda_graph/piecewise/test_pcg_with_speculative_decoding_dflash.py new file mode 100644 index 0000000000000000000000000000000000000000..3d92bde10d9493d7a2626b4a3b3628ff58a60d4e --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/cuda_graph/piecewise/test_pcg_with_speculative_decoding_dflash.py @@ -0,0 +1,52 @@ +"""Test piecewise CUDA graph coexisting with speculative decoding (DFLASH). + +PCG handles prefill/extend path while DFlash needs target aux hidden states +from prefill to materialize draft KV cache. This verifies PCG captures that +path with the DFlash hidden-state variant enabled. +""" + +import unittest + +from sglang.test.ci.ci_register import register_cuda_ci +from sglang.test.server_fixtures.pcg_spec_fixture import PCGSpecBase +from sglang.test.test_utils import ( + DEFAULT_DRAFT_MODEL_DFLASH, + DEFAULT_TARGET_MODEL_DFLASH, + CustomTestCase, +) + +register_cuda_ci(est_time=531, stage="base-b", runner_config="1-gpu-small") + + +class TestPCGWithDFlash(PCGSpecBase, CustomTestCase): + """PCG + DFLASH on Llama-3.1-8B-Instruct.""" + + model = DEFAULT_TARGET_MODEL_DFLASH + server_args = [ + "--trust-remote-code", + "--attention-backend", + "flashinfer", + "--cuda-graph-backend-prefill", + "tc_piecewise", + "--speculative-algorithm", + "DFLASH", + "--speculative-draft-model-path", + DEFAULT_DRAFT_MODEL_DFLASH, + "--page-size", + "1", + "--max-running-requests", + "64", + # Keep headroom for the draft KV pool + piecewise cuda graph + # private pools on 32GB CI cards. + "--mem-fraction-static", + "0.7", + "--cuda-graph-bs-decode", + *[str(i) for i in range(1, 65)], + ] + server_env = {"SGLANG_ALLOW_OVERWRITE_LONGER_CONTEXT_LEN": "1"} + accuracy_threshold = 0.75 + speedup_threshold = 2.8 + + +if __name__ == "__main__": + unittest.main() diff --git a/asian_ai/performance/SGLang/test/registered/cuda_graph/piecewise/test_pcg_with_speculative_decoding_extra.py b/asian_ai/performance/SGLang/test/registered/cuda_graph/piecewise/test_pcg_with_speculative_decoding_extra.py new file mode 100644 index 0000000000000000000000000000000000000000..e7ccc84e7d339a18604141fb7ffaaae2ed383ecc --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/cuda_graph/piecewise/test_pcg_with_speculative_decoding_extra.py @@ -0,0 +1,80 @@ +"""Extra: PCG coexistence with non-EAGLE3 speculative decoding variants. + +EAGLE3 stays per-commit in the sibling file +test_pcg_with_speculative_decoding.py. +""" + +import unittest + +from sglang.test.ci.ci_register import register_cuda_ci +from sglang.test.server_fixtures.pcg_spec_fixture import PCGSpecBase + +register_cuda_ci(est_time=531, stage="extra-a", runner_config="2-gpu-large") + + +class TestPCGWithMTP(PCGSpecBase, unittest.TestCase): + """PCG + MTP (NEXTN) on Qwen3.5-35B-A3B with FP8.""" + + model = "Qwen/Qwen3.5-35B-A3B" + server_args = [ + "--tp", + "2", + "--trust-remote-code", + "--quantization", + "fp8", + "--mamba-scheduler-strategy", + "extra_buffer", + "--speculative-algorithm", + "NEXTN", + "--reasoning-parser", + "qwen3", + ] + timeout_mult = 3 + max_tokens = 8192 + thinking_mode = "qwen3" + accuracy_threshold = 0.75 + + +class TestPCGWithSTANDALONE(PCGSpecBase, unittest.TestCase): + """PCG + STANDALONE on Llama-3.1-8B-Instruct + Llama-3.2-1B-Instruct.""" + + model = "meta-llama/Llama-3.1-8B-Instruct" + server_args = [ + "--trust-remote-code", + "--cuda-graph-backend-prefill=tc_piecewise", + "--mem-fraction-static", + "0.5", + "--speculative-algorithm", + "STANDALONE", + "--speculative-draft-model-path", + "meta-llama/Llama-3.2-1B-Instruct", + "--speculative-num-steps", + "3", + "--speculative-eagle-topk", + "1", + "--speculative-num-draft-tokens", + "4", + ] + accuracy_threshold = 0.50 + + +class TestPCGWithNGRAM(PCGSpecBase, unittest.TestCase): + """PCG + NGRAM on Qwen2.5-Coder-7B-Instruct.""" + + model = "Qwen/Qwen2.5-Coder-7B-Instruct" + server_args = [ + "--trust-remote-code", + "--cuda-graph-backend-prefill=tc_piecewise", + "--speculative-algorithm", + "NGRAM", + "--speculative-num-draft-tokens", + "16", + "--cuda-graph-max-bs-decode", + "8", + "--mem-fraction-static", + "0.8", + ] + + +if __name__ == "__main__": + unittest.main() diff --git a/asian_ai/performance/SGLang/test/registered/cuda_graph/piecewise/test_piecewise_cuda_graph_support_1_gpu.py b/asian_ai/performance/SGLang/test/registered/cuda_graph/piecewise/test_piecewise_cuda_graph_support_1_gpu.py new file mode 100644 index 0000000000000000000000000000000000000000..d3239fd4fb8fc3085f21386d7f53adf9bc0f9d9e --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/cuda_graph/piecewise/test_piecewise_cuda_graph_support_1_gpu.py @@ -0,0 +1,113 @@ +import unittest + +import torch + +from sglang import Engine +from sglang.lang.chat_template import get_chat_template_by_model_path +from sglang.srt.utils import kill_process_tree +from sglang.test.ci.ci_register import register_amd_ci, register_cuda_ci +from sglang.test.run_eval import run_eval +from sglang.test.test_utils import ( + DEFAULT_IMAGE_URL, + DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH, + DEFAULT_URL_FOR_TEST, + CustomTestCase, + SimpleNamespace, + popen_launch_server, +) + +# CI Registration +register_cuda_ci(est_time=180, stage="base-b", runner_config="1-gpu-large") +register_amd_ci(est_time=180, suite="stage-b-test-1-gpu-large-amd") + + +class TestPiecewiseCudaGraphQwen25VL(CustomTestCase): + """Test piecewise CUDA graph with Qwen2.5-VL-7B-Instruct model""" + + @classmethod + def setUpClass(cls): + cls.model = "Qwen/Qwen2.5-VL-7B-Instruct" + cls.base_url = DEFAULT_URL_FOR_TEST + cls.process = popen_launch_server( + cls.model, + cls.base_url, + timeout=DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH, + other_args=[ + "--cuda-graph-backend-prefill=tc_piecewise", + "--disable-radix-cache", + ], + ) + + @classmethod + def tearDownClass(cls): + kill_process_tree(cls.process.pid) + + def test_gsm8k_accuracy(self): + args = SimpleNamespace( + base_url=self.base_url, + model=self.model, + eval_name="gsm8k", + num_examples=None, + num_threads=1024, + ) + + metrics = run_eval(args) + print(f"GSM8K Accuracy: {metrics['score']:.3f}") + + self.assertGreaterEqual(metrics["score"], 0.80) + + +class TestPiecewiseCudaGraphQwen25VLEmbedding(CustomTestCase): + """Test piecewise CUDA graph with Qwen2.5-VL-3B-Instruct embedding model""" + + def test_embedding(self): + model_path = "Qwen/Qwen2.5-VL-3B-Instruct" + chat_template = get_chat_template_by_model_path(model_path) + text = f"{chat_template.image_token}What is in this picture? Answer: " + + engine = Engine( + model_path=model_path, + enable_multimodal=True, + is_embedding=True, + cuda_graph_backend_prefill="tc_piecewise", + ) + out = engine.encode([text], image_data=[DEFAULT_IMAGE_URL])[0]["embedding"] + engine.shutdown() + self.assertGreater(len(out), 0) + + engine = Engine( + model_path=model_path, + enable_multimodal=True, + is_embedding=True, + cuda_graph_backend_prefill="disabled", + ) + out_without_pcg = engine.encode([text], image_data=[DEFAULT_IMAGE_URL])[0][ + "embedding" + ] + engine.shutdown() + self.assertGreater(len(out_without_pcg), 0) + + t_out = torch.tensor(out) + t_out_without_pcg = torch.tensor(out_without_pcg) + max_abs_diff = (t_out - t_out_without_pcg).abs().max().item() + max_rel_diff = ( + ((t_out - t_out_without_pcg).abs() / (t_out_without_pcg.abs() + 1e-8)) + .max() + .item() + ) + print( + f"PCG embedding diff: max_abs={max_abs_diff:.6f}, max_rel={max_rel_diff:.6f}" + ) + self.assertTrue( + torch.allclose( + t_out, + t_out_without_pcg, + atol=1e-2, + rtol=1e-2, + ), + f"Piecewise CUDA graph embedding mismatch: max_abs_diff={max_abs_diff}, max_rel_diff={max_rel_diff}", + ) + + +if __name__ == "__main__": + unittest.main() diff --git a/asian_ai/performance/SGLang/test/registered/dcp/test_dcp_layout_unit.py b/asian_ai/performance/SGLang/test/registered/dcp/test_dcp_layout_unit.py new file mode 100644 index 0000000000000000000000000000000000000000..a4687d4aaadd99df3dbd9cf471a3419b22e61c53 --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/dcp/test_dcp_layout_unit.py @@ -0,0 +1,91 @@ +"""CPU unit test for the decode-context-parallel (DCP) per-rank KV-length math. + +Pins ``get_dcp_lens`` (the single, superset implementation in +``layers/dcp/layout.py``) to a brute-force owner-count reference, and proves +it is bit-identical to the legacy in-place formula that +``update_local_kv_lens_for_dcp`` used before it was collapsed into a wrapper: + + floor((len - rank - 1) / N) + 1 == len // N + (rank < len % N) (len >= 0) + +Usage: + python -m pytest test_dcp_layout_unit.py -v + python test_dcp_layout_unit.py +""" + +import unittest + +import torch + +from sglang.srt.layers.dcp.layout import get_dcp_lens +from sglang.test.ci.ci_register import register_cpu_ci + +register_cpu_ci(est_time=10, suite="base-a-test-cpu") + +DCP_SIZES = [1, 2, 3, 4, 8] +LENS = list(range(0, 41)) +STARTS = [0, 1, 2, 5, 7, 13, 31] + + +def _owner_count(length: int, n: int, rank: int, start: int) -> int: + """Ground truth: # of absolute positions p in [start, start+length) with p % n == rank.""" + return sum(1 for p in range(start, start + length) if p % n == rank) + + +def _legacy_inplace_formula(length: int, n: int, rank: int) -> int: + """The pre-refactor update_local_kv_lens_for_dcp body (start == 0 case).""" + return (length - rank - 1) // n + 1 + + +class TestGetDcpLens(unittest.TestCase): + def test_start_none_matches_owner_count(self): + for n in DCP_SIZES: + for rank in range(n): + lens = torch.tensor(LENS, dtype=torch.int32) + got = get_dcp_lens(lens, n, rank) + expected = torch.tensor( + [_owner_count(L, n, rank, 0) for L in LENS], dtype=torch.int32 + ) + self.assertTrue( + torch.equal(got.to(torch.int32), expected), + f"start=None mismatch at n={n}, rank={rank}: {got.tolist()} != {expected.tolist()}", + ) + + def test_start_none_matches_legacy_inplace_formula(self): + # The collapse claim: get_dcp_lens (start=None) == legacy floor((L-rank-1)/N)+1. + for n in DCP_SIZES: + for rank in range(n): + lens = torch.tensor(LENS, dtype=torch.int64) + got = get_dcp_lens(lens, n, rank) + legacy = torch.tensor( + [_legacy_inplace_formula(L, n, rank) for L in LENS], + dtype=torch.int64, + ) + self.assertTrue( + torch.equal(got.to(torch.int64), legacy), + f"legacy-formula mismatch at n={n}, rank={rank}", + ) + + def test_start_tensor_matches_owner_count(self): + for n in DCP_SIZES: + for rank in range(n): + for start in STARTS: + lens = torch.tensor(LENS, dtype=torch.int64) + start_t = torch.full_like(lens, start) + got = get_dcp_lens(lens, n, rank, start=start_t) + expected = torch.tensor( + [_owner_count(L, n, rank, start) for L in LENS], + dtype=torch.int64, + ) + self.assertTrue( + torch.equal(got.to(torch.int64), expected), + f"start={start} mismatch at n={n}, rank={rank}: " + f"{got.tolist()} != {expected.tolist()}", + ) + + def test_dcp_size_one_is_identity(self): + lens = torch.tensor(LENS, dtype=torch.int32) + self.assertTrue(torch.equal(get_dcp_lens(lens, 1, 0), lens)) + + +if __name__ == "__main__": + unittest.main() diff --git a/asian_ai/performance/SGLang/test/registered/dcp/test_dsv31_dcp8_gsm8k.py b/asian_ai/performance/SGLang/test/registered/dcp/test_dsv31_dcp8_gsm8k.py new file mode 100644 index 0000000000000000000000000000000000000000..7d601c6ae415cadbd8e87f37c269f4146c75882a --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/dcp/test_dsv31_dcp8_gsm8k.py @@ -0,0 +1,421 @@ +""" +DCP (Decode Context Parallelism) correctness tests for DeepSeek-V3.1. + +Test classes: + TestDSV31DCP8TP8GSM8K — CI gate: DCP=8 + TP=8 GSM8K accuracy + decode sanity + TestDSV31DCP8LogprobParity — (manual) DCP=8 vs non-DCP logprob equivalence + TestDSV31DCP4TP8GSM8K — (manual) DCP=4 + TP=8, different all-gather path + +CI coverage & known gaps +------------------------ +What the CI test (TestDSV31DCP8TP8GSM8K) covers: + - DCP=8 decode path: 8-way KV-shard all-gather + LSE correction + reduce-scatter + - DCP=8 extend path: prefix KV all-gather for MLA models (DeepSeek-V3.1) + - Basic decode correctness: factual recall, math, no-repetition, temp=0 determinism, + max_new_tokens=1 edge case (catches CUDA graph capture bugs) + - GSM8K accuracy gate (200 questions, 5-shot, completion API) + - DCP activation verification (max_total_num_tokens scaled by dcp_world_size) + +What the CI test does NOT cover (and the manual tests address): + - Exact parity with non-DCP outputs (TestDSV31DCP8LogprobParity) + - DCP=4 code path (different all-gather pattern; TestDSV31DCP4TP8GSM8K) + - MHA extend path (all_gather_kv_cache_for_mha_extend / mha_chunk_extend) + — DeepSeek-V3.1 uses MLA, so these paths are never exercised + +Future improvements: + - Add dcp_world_size to /server_info so tests can assert DCP is active without + comparing max_total_num_tokens + - Add an MHA model DCP test (e.g., a small non-DeepSeek model) once MHA+DCP + is supported, or test with DeepSeek-V3's MHA attention fallback path + - Tighten gsm8k_accuracy_thres to 0.92+ once baseline numbers are established. + The non-DCP V3.1 baseline on 200 questions typically scores ~0.93–0.94; the + current 0.90 threshold provides ~3–4% headroom for initial DCP validation. + The manual TestDSV31DCP8LogprobParity provides much tighter per-token + verification once a non-DCP baseline is available for comparison. +""" + +import os +import time +import unittest + +import requests + +from sglang.srt.utils import kill_process_tree +from sglang.test.ci.ci_register import register_cuda_ci +from sglang.test.kits.basic_decode_correctness_kit import BasicDecodeCorrectnessMixin +from sglang.test.kits.eval_accuracy_kit import GSM8KMixin +from sglang.test.test_utils import ( + DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH, + DEFAULT_URL_FOR_TEST, + CustomTestCase, + is_in_ci, + popen_launch_server, +) + +# --------------------------------------------------------------------------- +# CI registration — only TestDSV31DCP8TP8GSM8K runs in CI +# --------------------------------------------------------------------------- +register_cuda_ci(est_time=600, stage="extra-b", runner_config="8-gpu-h200") + +DEEPSEEK_V31_MODEL_PATH = "deepseek-ai/DeepSeek-V3.1" + +_COMMON_SERVER_ARGS = [ + "--tp-size", + "8", + "--enable-cache-report", + "--enable-metrics", + "--random-seed", + "0", + "--trust-remote-code", + "--mem-fraction-static", + "0.88", + "--chunked-prefill-size", + "16384", + "--max-running-requests", + "256", + "--cuda-graph-max-bs-decode", + "256", + "--attention-backend", + "flashinfer", + "--disable-piecewise-cuda-graph", + "--log-level", + "info", + "--log-requests", + "--log-requests-level", + "3", +] + +_DCP8_ARGS = [ + "--dcp-size", + "8", +] +_DCP4_ARGS = [ + "--dcp-size", + "4", +] + +# Prompts used for logprob parity verification between DCP and non-DCP. +_LOGPROB_PARITY_PROMPTS = [ + "The capital city of France is", + "What is 2 + 3? The answer is", + "In the year 1492, Christopher Columbus", + "The largest planet in our solar system is", + "Water boils at", +] + + +def _get_max_total_num_tokens(base_url: str) -> int: + """Fetch max_total_num_tokens from /server_info. + + When DCP is enabled, max_total_num_tokens is multiplied by dcp_world_size + (see model_runner_kv_cache_mixin.py), so this value can be used to verify + that DCP is actually active. + """ + resp = requests.get(f"{base_url}/server_info", timeout=30) + resp.raise_for_status() + info = resp.json() + # scheduler_info is flattened into the top-level response + return info["max_total_num_tokens"] + + +# --------------------------------------------------------------------------- +# Test 1: CI accuracy gate + decode sanity (DCP=8, TP=8) +# --------------------------------------------------------------------------- +class TestDSV31DCP8TP8GSM8K(GSM8KMixin, BasicDecodeCorrectnessMixin, CustomTestCase): + """DCP=8 with TP=8 on DeepSeek-V3.1 — CI accuracy gate + basic decode probes. + + This test exercises the full DCP decode and extend paths: + - Decode: query all-gather → attention on local KV shard → LSE + correction via cp_lse_ag_out_rs_mla → reduce-scatter + - Extend (prefill): all-gather prefix KV cache across DCP ranks, + attend with full context + + Inherits: + - GSM8KMixin.test_gsm8k: accuracy gate (threshold 0.90) + - BasicDecodeCorrectnessMixin: cheap sanity probes (factual recall, + no-repetition, temp=0 determinism, max_new_tokens=1) + """ + + model = DEEPSEEK_V31_MODEL_PATH + base_url = DEFAULT_URL_FOR_TEST + + # Non-DCP V3.1 baseline on 200 questions typically scores ~0.93–0.94. + # The 0.90 threshold provides ~3–4% headroom for initial DCP validation. + # For tighter verification, run TestDSV31DCP8LogprobParity manually. + gsm8k_accuracy_thres = 0.90 + gsm8k_num_questions = 200 + gsm8k_num_threads = 128 + gsm8k_num_shots = 5 + + @classmethod + def setUpClass(cls): + cls.process = popen_launch_server( + cls.model, + cls.base_url, + timeout=DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH * 5, + other_args=_DCP8_ARGS + _COMMON_SERVER_ARGS, + ) + # Store max_total_num_tokens so we can verify DCP is active. + # With DCP=8, this value should be ~8x the non-DCP value for the + # same model and mem-fraction-static. + cls._dcp_max_total_num_tokens = _get_max_total_num_tokens(cls.base_url) + + @classmethod + def tearDownClass(cls): + kill_process_tree(cls.process.pid, wait_timeout=60) + + def test_dcp_activation_check(self): + """Verify that DCP is actually active by checking that + max_total_num_tokens is nonzero (basic liveness). + + A stronger check that compares DCP vs non-DCP max_total_num_tokens + is in TestDSV31DCP8LogprobParity.test_logprob_parity. + """ + # If DCP were silently disabled, the server would still report a + # valid max_total_num_tokens. This basic check just ensures the + # /server_info endpoint is responsive and the value is sane. + self.assertGreater( + self._dcp_max_total_num_tokens, + 0, + "max_total_num_tokens should be positive", + ) + + +# --------------------------------------------------------------------------- +# Test 2: DCP=8 vs non-DCP logprob parity (manual-only, too expensive for CI) +# --------------------------------------------------------------------------- +@unittest.skipIf( + is_in_ci(), + "Requires two server launches (~20 min); run locally for DCP correctness verification.", +) +class TestDSV31DCP8LogprobParity(BasicDecodeCorrectnessMixin, CustomTestCase): + """Verify DCP=8 produces output-equivalent results to non-DCP TP=8. + + Strategy: + 1. Launch a non-DCP (TP=8) baseline server on port 31500. + 2. Record max_total_num_tokens (baseline reference for DCP check). + 3. Warm up with a temp=0 request, then collect deterministic outputs + + logprobs for several prompts. + 4. Kill the baseline, launch a DCP=8 (TP=8) server on the same port. + 5. Verify max_total_num_tokens is ~8x the baseline (DCP activation check). + 6. Warm up and collect outputs + logprobs for the same prompts. + 7. Assert: + - Output text matches exactly (temperature=0 must be deterministic) + - Token logprobs are within tolerance (floating-point all-gather + introduces small numerical differences) + + This catches subtle correctness bugs in the DCP LSE correction path + (cp_lse_ag_out_rs_mla) that a coarse GSM8K accuracy gate cannot detect. + For example, if exp2/exp mismatch causes a systematic bias in the + attention output, logprobs will diverge by more than the tolerance. + """ + + # Maximum per-token logprob difference between DCP and non-DCP. + # DCP introduces additional all-gather/reduce-scatter operations; + # a tolerance of 0.1 accounts for floating-point reordering while + # still catching systematic bugs (which would cause divergence >> 0.1). + LOGPROB_TOLERANCE = 1.0 + base_url = "http://127.0.0.1:31500" + + model = DEEPSEEK_V31_MODEL_PATH + + @classmethod + def setUpClass(cls): + # Launch non-DCP baseline server first + env = os.environ.copy() + env["SGLANG_JIT_DEEPGEMM_PRECOMPILE"] = "0" + cls._baseline_process = popen_launch_server( + DEEPSEEK_V31_MODEL_PATH, + cls.base_url, + timeout=DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH * 5, + other_args=_COMMON_SERVER_ARGS, + env=env, + ) + cls._processes = [cls._baseline_process] + + @classmethod + def tearDownClass(cls): + for proc in cls._processes: + try: + kill_process_tree(proc.pid, wait_timeout=60) + except Exception: + pass + + @staticmethod + def _generate_with_logprobs(base_url, prompt, max_new_tokens=8): + """Send a temp=0 generation request and return output text + logprobs.""" + resp = requests.post( + f"{base_url}/generate", + json={ + "text": prompt, + "sampling_params": { + "temperature": 0, + "max_new_tokens": max_new_tokens, + }, + "return_logprob": True, + "top_logprobs_num": 1, + "logprob_start_len": 0, + }, + timeout=120, + ) + if resp.status_code != 200: + raise RuntimeError( + f"Generate request failed (status {resp.status_code}): {resp.text[:500]}" + ) + data = resp.json() + meta = data["meta_info"] + # output_token_logprobs is a list of (logprob, token_id, token_text) + output_logprobs = meta.get("output_token_logprobs", []) + return { + "text": data["text"], + "output_logprobs": output_logprobs, + } + + @staticmethod + def _warmup_request(base_url): + """Send a warmup request to trigger CUDA graph capture and JIT compilation.""" + requests.post( + f"{base_url}/generate", + json={ + "text": "Hello", + "sampling_params": {"temperature": 0, "max_new_tokens": 4}, + }, + timeout=60, + ) + + def test_logprob_parity(self): + # --- Phase 1: collect baseline (non-DCP) outputs --- + self._warmup_request(self.base_url) + + baseline_results = [] + for prompt in _LOGPROB_PARITY_PROMPTS: + baseline_results.append(self._generate_with_logprobs(self.base_url, prompt)) + + # --- Phase 2: switch to DCP=8 --- + kill_process_tree(self._baseline_process.pid, wait_timeout=60) + # Allow OS to release the port + time.sleep(5) + + env = os.environ.copy() + env["SGLANG_JIT_DEEPGEMM_PRECOMPILE"] = "0" + dcp_process = popen_launch_server( + DEEPSEEK_V31_MODEL_PATH, + self.base_url, + timeout=DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH * 5, + other_args=_DCP8_ARGS + _COMMON_SERVER_ARGS, + env=env, + ) + self._processes.append(dcp_process) + self._warmup_request(self.base_url) + + dcp_results = [] + for prompt in _LOGPROB_PARITY_PROMPTS: + dcp_results.append(self._generate_with_logprobs(self.base_url, prompt)) + + # --- Phase 3: compare --- + for i, (baseline, dcp) in enumerate(zip(baseline_results, dcp_results)): + prompt_short = _LOGPROB_PARITY_PROMPTS[i][:50] + # Output text must be identical at temperature=0 + self.assertEqual( + baseline["text"], + dcp["text"], + f"Prompt '{prompt_short}...': output text differs between non-DCP and DCP=8.\n" + f" non-DCP: {baseline['text']!r}\n" + f" DCP=8: {dcp['text']!r}", + ) + # Token logprobs must be within tolerance + b_probs = baseline["output_logprobs"] + d_probs = dcp["output_logprobs"] + n_tokens = min(len(b_probs), len(d_probs)) + self.assertGreater( + n_tokens, + 0, + f"Prompt '{prompt_short}...': no output tokens produced", + ) + self.assertEqual( + len(b_probs), + len(d_probs), + f"Prompt '{prompt_short}...': token count differs " + f"(non-DCP={len(b_probs)}, DCP={len(d_probs)})", + ) + for j in range(n_tokens): + # output_token_logprobs format: (logprob, token_id, token_text) + b_lp = ( + b_probs[j][0] + if isinstance(b_probs[j], (list, tuple)) + else b_probs[j] + ) + d_lp = ( + d_probs[j][0] + if isinstance(d_probs[j], (list, tuple)) + else d_probs[j] + ) + self.assertAlmostEqual( + b_lp, + d_lp, + delta=self.LOGPROB_TOLERANCE, + msg=( + f"Prompt '{prompt_short}...', token {j}: " + f"logprob diff > {self.LOGPROB_TOLERANCE} " + f"(non-DCP={b_lp:.4f}, DCP={d_lp:.4f}, " + f"diff={abs(b_lp - d_lp):.4f})" + ), + ) + + +# --------------------------------------------------------------------------- +# Test 3: DCP=4 variant (manual-only, exercises different all-gather pattern) +# --------------------------------------------------------------------------- +@unittest.skipIf( + is_in_ci(), "Requires 8 GPUs; run locally for additional DCP coverage." +) +class TestDSV31DCP4TP8GSM8K(GSM8KMixin, BasicDecodeCorrectnessMixin, CustomTestCase): + """DCP=4 with TP=8 — exercises a different all-gather pattern than DCP=8. + + With DCP=4, each rank stores 1/4 of the KV cache (vs 1/8 for DCP=8). + The 4-way all-gather uses a different GroupCoordinator configuration, + and the token-to-shard mapping (position % 4 vs position % 8) exercises + different edge cases in: + - update_local_kv_lens_for_dcp (different div/mod arithmetic) + - plan_dcp_decode_metadata (different local_kv_lens distribution) + - create_dcp_kv_indices (different padding/alignment) + - all_gather_kv_cache_for_dcp (4-way vs 8-way interleave pattern) + """ + + model = DEEPSEEK_V31_MODEL_PATH + base_url = "http://127.0.0.1:31501" + + gsm8k_accuracy_thres = 0.90 + gsm8k_num_questions = 200 + gsm8k_num_threads = 128 + gsm8k_num_shots = 5 + + @classmethod + def setUpClass(cls): + env = os.environ.copy() + cls.process = popen_launch_server( + cls.model, + cls.base_url, + timeout=DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH * 5, + other_args=_DCP4_ARGS + _COMMON_SERVER_ARGS, + env=env, + ) + # Store max_total_num_tokens for DCP activation verification. + # With DCP=4, this should be ~4x the non-DCP value. + cls._dcp_max_total_num_tokens = _get_max_total_num_tokens(cls.base_url) + + @classmethod + def tearDownClass(cls): + kill_process_tree(cls.process.pid, wait_timeout=60) + + def test_dcp_activation_check(self): + """Verify DCP is active by checking max_total_num_tokens is nonzero.""" + self.assertGreater( + self._dcp_max_total_num_tokens, + 0, + "max_total_num_tokens should be positive", + ) + + +if __name__ == "__main__": + unittest.main() diff --git a/asian_ai/performance/SGLang/test/registered/dcp/test_reduce_scatter_along_dim.py b/asian_ai/performance/SGLang/test/registered/dcp/test_reduce_scatter_along_dim.py new file mode 100644 index 0000000000000000000000000000000000000000..02e1234df4f7ad47b3cd4a1a91a478772b761707 --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/dcp/test_reduce_scatter_along_dim.py @@ -0,0 +1,231 @@ +""" +Correctness test for ``GroupCoordinator.reduce_scatter_along_dim``. + +The test compares the ``reduce_scatter_along_dim`` output against PyTorch's +native ``dist.reduce_scatter_tensor`` for various tensor shapes, dims, and +dtypes, exercising both positive and negative dim indexing. + +Usage: + python -m pytest test_reduce_scatter_along_dim.py -v + +This file doubles as the torchrun worker script. The test class launches + torchrun --nproc_per_node=N +and asserts that all worker processes exit successfully. +""" + +from __future__ import annotations + +import os +import subprocess +import sys +from typing import List, Optional, Tuple + +import pytest +import torch +import torch.distributed as dist + +import sglang.srt.distributed.parallel_state as ps +from sglang.test.ci.ci_register import register_cuda_ci + +register_cuda_ci( + est_time=120, + stage="extra-b", + runner_config="8-gpu-h200", +) + +# --------------------------------------------------------------------------- +# Test parameters +# --------------------------------------------------------------------------- + +# (head_num, batch_size, head_dim) shapes +TEST_SHAPES = [ + (8, 16, 32), + (16, 64, 128), + (4, 1024, 512), + (16, 3, 128), + (64, 5, 512), + (128, 7, 512), +] + + +# For each shape we test several dim values (both positive and negative) +def _dims_for_shape(shape: Tuple[int, ...]) -> List[int]: + ndim = len(shape) + pos_dims = list(range(ndim)) + neg_dims = [-d - 1 for d in range(ndim)] + return pos_dims + neg_dims + + +TEST_DTYPES = [torch.float16, torch.bfloat16, torch.float32] +TEST_LOOP = 8 + + +# --------------------------------------------------------------------------- +# Helpers for multiprocess launch (shared between test and worker) +# --------------------------------------------------------------------------- + + +def multiprocess_test(file: str, nproc: int, timeout: int = 120) -> None: + cmd = [ + "torchrun", + f"--nproc_per_node={nproc}", + file, + ] + try: + result = subprocess.run( + cmd, + stdout=subprocess.PIPE, + stderr=subprocess.STDOUT, + text=True, + timeout=timeout, + ) + except subprocess.TimeoutExpired as e: + raise RuntimeError( + f"torchrun (nproc={nproc}) timed out after {timeout}s\n{e.stdout}" + ) from e + + assert result.returncode == 0, ( + f"torchrun (nproc={nproc}) failed with rc={result.returncode}\n" + f"{result.stdout}" + ) + + +def multiprocess_main(file: str, main_fn) -> None: + if "LOCAL_RANK" in os.environ: + main_fn() + else: + sys.exit(pytest.main([file, "-v", "-s"])) + + +# --------------------------------------------------------------------------- +# Test class (runs via pytest, launches torchrun subprocesses) +# --------------------------------------------------------------------------- + + +@pytest.mark.parametrize("nproc", [2, 4, 8]) +def test_reduce_scatter_along_dim(nproc: int) -> None: + device_count = torch.cuda.device_count() + if device_count < nproc: + pytest.skip( + f"Requires at least {nproc} GPUs, but only {device_count} available" + ) + multiprocess_test(__file__, nproc) + + +# --------------------------------------------------------------------------- +# Worker logic (executed by each torchrun process) +# --------------------------------------------------------------------------- + + +def init_distributed(): + """Initialize distributed groups via torchrun env vars.""" + local_rank = int(os.environ["LOCAL_RANK"]) + world_size = int(os.environ["WORLD_SIZE"]) + rank = local_rank + device = torch.device(f"cuda:{rank}") + torch.cuda.set_device(device) + + dist.init_process_group(backend="gloo") + ps._WORLD = coord = ps.init_world_group( + ranks=list(range(world_size)), + local_rank=local_rank, + backend="nccl", + ) + + cpu_group = coord.cpu_group + nccl_group = coord.device_group + assert nccl_group is not None + + return rank, device, cpu_group, nccl_group, coord + + +def _reference_reduce_scatter_along_dim( + input_: torch.Tensor, + dim: int, + world_size: int, + group: dist.ProcessGroup, +) -> torch.Tensor: + """Reference implementation using torch.distributed.reduce_scatter_tensor.""" + if dim < 0: + dim += input_.dim() + + # Move target dim to position 0 and make contiguous + input_tensor = input_.movedim(dim, 0).contiguous() + + assert input_tensor.shape[0] % world_size == 0 + chunk_size = input_tensor.shape[0] // world_size + output_shape = (chunk_size,) + input_tensor.shape[1:] + + output_tensor = torch.empty( + output_shape, + dtype=input_tensor.dtype, + device=input_tensor.device, + ) + + dist.reduce_scatter_tensor(output_tensor, input_tensor, group=group) + + # Move dim back + return output_tensor.movedim(0, dim) + + +@torch.inference_mode() +def worker_test( + device: torch.device, + nccl_group: dist.ProcessGroup, + coord: ps.GroupCoordinator, + shape: Tuple[int, ...], + dim: int, + dtype: torch.dtype, + world_size: int, +) -> Optional[RuntimeError]: + """Run a single (shape, dim, dtype) configuration and compare against reference.""" + for _ in range(TEST_LOOP): + inp = torch.randint(0, 16, shape, dtype=dtype, device=device) + + # Our implementation + out = coord.reduce_scatter_along_dim(inp, dim=dim) + + # Reference + ref = _reference_reduce_scatter_along_dim(inp, dim, world_size, nccl_group) + + if not torch.all(out == ref): + return RuntimeError(f"Mismatch for shape={shape}, dim={dim}, dtype={dtype}") + return None + + +def worker_main() -> None: + """Entry point for each torchrun worker process.""" + rank, device, cpu_group, nccl_group, coord = init_distributed() + world_size = coord.world_size + + torch.cuda.set_stream(torch.cuda.Stream()) + + errors: List[str] = [] + for shape in TEST_SHAPES: + # Only test dims where shape[dim] is divisible by world_size + for dim in _dims_for_shape(shape): + actual_dim = dim if dim >= 0 else dim + len(shape) + if shape[actual_dim] % world_size != 0: + continue + + for dtype in TEST_DTYPES: + error = worker_test( + device, nccl_group, coord, shape, dim, dtype, world_size + ) + if error is not None: + errors.append(str(error)) + + # Synchronize across ranks – if any rank fails, all fail + result = torch.tensor([int(error is not None)], device="cpu") + dist.all_reduce(result, group=cpu_group) + if result.item(): + raise RuntimeError( + f"Rank {rank} failed for shape={shape}, dim={dim}, " + f"dtype={dtype}. Errors: {'; '.join(errors)}" + ) + + dist.destroy_process_group() + + +if __name__ == "__main__": + multiprocess_main(__file__, worker_main) diff --git a/asian_ai/performance/SGLang/test/registered/debug_utils/comparator/__init__.py b/asian_ai/performance/SGLang/test/registered/debug_utils/comparator/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/asian_ai/performance/SGLang/test/registered/debug_utils/comparator/aligner/__init__.py b/asian_ai/performance/SGLang/test/registered/debug_utils/comparator/aligner/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391