Instructions to use luclima/mythos-models with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Notebooks
- Google Colab
- Kaggle
- Local Apps Settings
- llama.cpp
How to use luclima/mythos-models with llama.cpp:
Install (macOS, Linux)
curl -LsSf https://llama.app/install.sh | sh # Start a local OpenAI-compatible server with a web UI: llama serve -hf luclima/mythos-models:Q4_K_M # Run inference directly in the terminal: llama cli -hf luclima/mythos-models:Q4_K_M
Install from WinGet (Windows)
winget install llama.cpp # Start a local OpenAI-compatible server with a web UI: llama serve -hf luclima/mythos-models:Q4_K_M # Run inference directly in the terminal: llama cli -hf luclima/mythos-models:Q4_K_M
Build from source code
git clone https://github.com/ggml-org/llama.cpp.git cd llama.cpp cmake -B build cmake --build build -j --target llama-app # Start a local OpenAI-compatible server with a web UI: ./build/bin/llama serve -hf luclima/mythos-models:Q4_K_M # Run inference directly in the terminal: ./build/bin/llama cli -hf luclima/mythos-models:Q4_K_M
Use Docker
docker model run hf.co/luclima/mythos-models:Q4_K_M
- Llama new
- LM Studio
- Jan
- Ollama
How to use luclima/mythos-models with Ollama:
ollama run hf.co/luclima/mythos-models:Q4_K_M
- Unsloth Desktop
- Docker Model Runner
How to use luclima/mythos-models with Docker Model Runner:
docker model run hf.co/luclima/mythos-models:Q4_K_M
- Lemonade
How to use luclima/mythos-models with Lemonade:
Pull the model
# Download Lemonade from https://lemonade-server.ai/ lemonade pull luclima/mythos-models:Q4_K_M
Run and chat with the model
lemonade run user.mythos-models-Q4_K_M
List all available models
lemonade list
- Atomic Chat
Upload folder using huggingface_hub (part 47)
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
- asian_ai/performance/SGLang/test/README.md +114 -0
- asian_ai/performance/SGLang/test/manual/ascend/test_ascend_deepseek_mtp.py +93 -0
- asian_ai/performance/SGLang/test/manual/ascend/test_ascend_vocab_mask.py +81 -0
- asian_ai/performance/SGLang/test/manual/ascend/test_ascend_w8a8_quantization.py +102 -0
- asian_ai/performance/SGLang/test/manual/ascend/test_mindspore_models.py +64 -0
- asian_ai/performance/SGLang/test/manual/ascend/vlm_models/test_npu_gemma_4_26b_a4b_it.py +22 -0
- asian_ai/performance/SGLang/test/manual/ascend/vlm_models/test_npu_gemma_4_31b.py +22 -0
- asian_ai/performance/SGLang/test/manual/ascend/vlm_models/test_npu_gemma_4_e2b.py +22 -0
- asian_ai/performance/SGLang/test/manual/ascend/vlm_models/test_npu_gemma_4_e4b.py +22 -0
- asian_ai/performance/SGLang/test/manual/attention/test_fa3.py +263 -0
- asian_ai/performance/SGLang/test/manual/attention/test_flashattn_backend.py +592 -0
- asian_ai/performance/SGLang/test/manual/attention/test_flashattn_mla_backend.py +332 -0
- asian_ai/performance/SGLang/test/manual/attention/test_local_attn.py +74 -0
- asian_ai/performance/SGLang/test/manual/attention/test_prefix_chunk_info.py +238 -0
- asian_ai/performance/SGLang/test/manual/attention/test_trtllm_mla_backend.py +1438 -0
- asian_ai/performance/SGLang/test/manual/chunked_prefill/__init__.py +0 -0
- asian_ai/performance/SGLang/test/manual/chunked_prefill/test_e2e_disagg.py +13 -0
- asian_ai/performance/SGLang/test/manual/chunked_prefill/test_e2e_dp_attention.py +23 -0
- asian_ai/performance/SGLang/test/manual/chunked_prefill/test_e2e_hybrid_swa.py +22 -0
- asian_ai/performance/SGLang/test/manual/chunked_prefill/test_e2e_lora.py +25 -0
- asian_ai/performance/SGLang/test/manual/chunked_prefill/test_e2e_lora_overlap.py +26 -0
- asian_ai/performance/SGLang/test/manual/chunked_prefill/test_e2e_page_size.py +18 -0
- asian_ai/performance/SGLang/test/manual/chunked_prefill/test_e2e_pd_pp.py +25 -0
- asian_ai/performance/SGLang/test/manual/chunked_prefill/test_e2e_piecewise_cuda_graph.py +16 -0
- asian_ai/performance/SGLang/test/manual/chunked_prefill/test_e2e_pp.py +19 -0
- asian_ai/performance/SGLang/test/manual/chunked_prefill/test_e2e_priority.py +21 -0
- asian_ai/performance/SGLang/test/manual/chunked_prefill/test_e2e_radix.py +20 -0
- asian_ai/performance/SGLang/test/manual/chunked_prefill/test_e2e_spec.py +28 -0
- asian_ai/performance/SGLang/test/manual/chunked_prefill/test_scripted_abort.py +643 -0
- asian_ai/performance/SGLang/test/manual/chunked_prefill/test_scripted_chunk_size.py +361 -0
- asian_ai/performance/SGLang/test/manual/chunked_prefill/test_scripted_http_smoke.py +49 -0
- asian_ai/performance/SGLang/test/manual/chunked_prefill/test_scripted_hybrid_swa.py +180 -0
- asian_ai/performance/SGLang/test/manual/chunked_prefill/test_scripted_invariants.py +512 -0
- asian_ai/performance/SGLang/test/manual/chunked_prefill/test_scripted_kv_pressure.py +550 -0
- asian_ai/performance/SGLang/test/manual/chunked_prefill/test_scripted_lifecycle.py +440 -0
- asian_ai/performance/SGLang/test/manual/chunked_prefill/test_scripted_lora.py +240 -0
- asian_ai/performance/SGLang/test/manual/chunked_prefill/test_scripted_lora_overlap.py +191 -0
- asian_ai/performance/SGLang/test/manual/chunked_prefill/test_scripted_max_new_tokens.py +167 -0
- asian_ai/performance/SGLang/test/manual/chunked_prefill/test_scripted_multi_req.py +537 -0
- asian_ai/performance/SGLang/test/manual/chunked_prefill/test_scripted_page_size.py +106 -0
- asian_ai/performance/SGLang/test/manual/chunked_prefill/test_scripted_piecewise_cuda_graph.py +67 -0
- asian_ai/performance/SGLang/test/manual/chunked_prefill/test_scripted_pp.py +246 -0
- asian_ai/performance/SGLang/test/manual/chunked_prefill/test_scripted_priority.py +309 -0
- asian_ai/performance/SGLang/test/manual/chunked_prefill/test_scripted_radix.py +741 -0
- asian_ai/performance/SGLang/test/manual/chunked_prefill/test_scripted_regression.py +524 -0
- asian_ai/performance/SGLang/test/manual/chunked_prefill/test_scripted_sampling.py +274 -0
- asian_ai/performance/SGLang/test/manual/chunked_prefill/test_scripted_spec.py +67 -0
- asian_ai/performance/SGLang/test/manual/chunked_prefill/test_scripted_special_case.py +1254 -0
- asian_ai/performance/SGLang/test/manual/core/test_dynamic_grad_mode.py +58 -0
- asian_ai/performance/SGLang/test/manual/core/test_gpt_oss_1gpu.py +31 -0
asian_ai/performance/SGLang/test/README.md
ADDED
|
@@ -0,0 +1,114 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Test and Continuous Integration (CI) System in SGLang
|
| 2 |
+
|
| 3 |
+
This page covers principles and essentials: folder layout, how to run tests, registration, and suite selection. For complete references, see the skill guides:
|
| 4 |
+
|
| 5 |
+
- **Writing tests** — templates, fixtures, model selection, complete suite tables, checklist: [`.claude/skills/write-sglang-test/SKILL.md`](../.claude/skills/write-sglang-test/SKILL.md)
|
| 6 |
+
- **CI pipeline internals** — stage flow diagrams, fast-fail layers, gating, partitioning, execution modes, debugging failures: [`.claude/skills/ci-workflow-guide/SKILL.md`](../.claude/skills/ci-workflow-guide/SKILL.md)
|
| 7 |
+
|
| 8 |
+
## CI Pipeline Overview
|
| 9 |
+
|
| 10 |
+
The CI pipeline runs in three sequential stages: **A** (pre-flight, ~3 min) → **B** (basic, ~30 min) → **C** (advanced, ~30 min). Kernel and multimodal-gen tests run in parallel with stage B. For details on stage gating, fast-fail mechanisms, execution modes (PR vs scheduled vs `/rerun-stage`), and debugging CI failures, see the [CI workflow guide](../.claude/skills/ci-workflow-guide/SKILL.md).
|
| 11 |
+
|
| 12 |
+
## Folder Organization
|
| 13 |
+
|
| 14 |
+
- `registered/`: CI test files, auto-discovered by `run_suite.py`. Most tests live here. JIT kernel tests are an exception (see below).
|
| 15 |
+
- `manual/`: Non-CI tests for local debugging or special setups.
|
| 16 |
+
- `run_suite.py`: CI runner — scans `registered/` and JIT kernel directories.
|
| 17 |
+
|
| 18 |
+
The system supports both [unittest](https://docs.python.org/3/library/unittest.html) and [pytest](https://docs.pytest.org/en/stable/). The launcher runs `python filename.py -f` with **failfast enabled by default**.
|
| 19 |
+
|
| 20 |
+
Make sure your file ends with **exactly** one of:
|
| 21 |
+
|
| 22 |
+
```python
|
| 23 |
+
# for unittest
|
| 24 |
+
if __name__ == "__main__":
|
| 25 |
+
unittest.main()
|
| 26 |
+
```
|
| 27 |
+
|
| 28 |
+
```python
|
| 29 |
+
# for pytest
|
| 30 |
+
if __name__ == "__main__":
|
| 31 |
+
import sys
|
| 32 |
+
sys.exit(pytest.main([__file__]))
|
| 33 |
+
```
|
| 34 |
+
|
| 35 |
+
Do not add custom `argparse` or modify `sys.argv` before these calls — the CI runner appends `-f` for failfast.
|
| 36 |
+
|
| 37 |
+
## Run Tests Locally
|
| 38 |
+
|
| 39 |
+
```bash
|
| 40 |
+
# Single file
|
| 41 |
+
python3 test/registered/core/test_srt_endpoint.py
|
| 42 |
+
|
| 43 |
+
# Single test method
|
| 44 |
+
python3 test/registered/core/test_srt_endpoint.py TestSRTEndpoint.test_simple_decode
|
| 45 |
+
|
| 46 |
+
# Single JIT kernel test
|
| 47 |
+
python3 test/registered/jit/test_add_constant.py
|
| 48 |
+
|
| 49 |
+
# Run a suite
|
| 50 |
+
python3 test/run_suite.py --hw cpu --suite base-a-test-cpu
|
| 51 |
+
python3 test/run_suite.py --hw cuda --suite base-a-test-1-gpu-small
|
| 52 |
+
|
| 53 |
+
# Nightly tests
|
| 54 |
+
python3 test/run_suite.py --hw cuda --suite nightly-1-gpu --nightly
|
| 55 |
+
|
| 56 |
+
# With auto-partitioning (for parallel CI jobs)
|
| 57 |
+
python3 test/run_suite.py --hw cuda --suite base-b-test-1-gpu-small \
|
| 58 |
+
--auto-partition-id 0 --auto-partition-size 4
|
| 59 |
+
```
|
| 60 |
+
|
| 61 |
+
## CI Registration
|
| 62 |
+
|
| 63 |
+
Every CI-discovered test file must call a registration function at module level:
|
| 64 |
+
|
| 65 |
+
```python
|
| 66 |
+
from sglang.test.ci.ci_register import register_cuda_ci
|
| 67 |
+
|
| 68 |
+
register_cuda_ci(est_time=80, stage="base-b", runner_config="1-gpu-small")
|
| 69 |
+
```
|
| 70 |
+
|
| 71 |
+
Parameters: `est_time` (seconds), `stage` + `runner_config` (target stage and runner pool from `scripts/ci/runner_configs.yml`), `nightly=True` (nightly-only), `disabled="reason"` (temporarily disable).
|
| 72 |
+
|
| 73 |
+
Keep `est_time`, `stage`, `runner_config` as **literal values** — `run_suite.py` collects them by AST parsing.
|
| 74 |
+
|
| 75 |
+
JIT kernel correctness tests and benchmarks live under `test/registered/jit/`, same as other registered tests (their helpers stay alongside the kernel source under `python/sglang/jit_kernel/` and are imported by absolute path):
|
| 76 |
+
- Correctness tests: `test/registered/jit/test_*.py` → `base-b-kernel-unit-test-1-gpu-large`
|
| 77 |
+
- Benchmarks: `test/registered/jit/benchmark/bench_*.py` → `base-b-kernel-benchmark-test-1-gpu-large`
|
| 78 |
+
|
| 79 |
+
## Choosing a Suite
|
| 80 |
+
|
| 81 |
+
Use the lightest suite that meets your test's needs. Full suite tables are in the [write-sglang-test skill](../.claude/skills/write-sglang-test/SKILL.md#all-ci-suites).
|
| 82 |
+
|
| 83 |
+
| Need | Suite |
|
| 84 |
+
|------|-------|
|
| 85 |
+
| No GPU required | `base-a-test-cpu` |
|
| 86 |
+
| Small GPU (fits 5090, 32GB) | `base-b-test-1-gpu-small` (most tests go here) |
|
| 87 |
+
| Large GPU memory or Hopper features | `base-b-test-1-gpu-large` |
|
| 88 |
+
| JIT kernel correctness | `base-b-kernel-unit-test-1-gpu-large` |
|
| 89 |
+
| JIT kernel benchmarks | `base-b-kernel-benchmark-test-1-gpu-large` |
|
| 90 |
+
| Multi-GPU (2/4/8) | `base-b-test-2-gpu-large`, `base-c-test-*` |
|
| 91 |
+
| Long-running or experimental | `nightly-*` suites |
|
| 92 |
+
|
| 93 |
+
## Steps for Adding a Test
|
| 94 |
+
|
| 95 |
+
See the [write-sglang-test skill](../.claude/skills/write-sglang-test/SKILL.md) for templates, fixtures, model selection, and a complete checklist.
|
| 96 |
+
|
| 97 |
+
## Multi-Hardware Backends
|
| 98 |
+
|
| 99 |
+
This README mostly describes the NVIDIA GPU CI pipeline. Other hardware backends (AMD, NPU) follow the same practices and use the multi-backend registry system. A scheduled job summarizes test coverage across all backends; [here is an example run](https://github.com/sgl-project/sglang/actions/runs/23424304300).
|
| 100 |
+
|
| 101 |
+
## Tips
|
| 102 |
+
|
| 103 |
+
- Learn from existing examples in [test/registered](https://github.com/sgl-project/sglang/tree/main/test/registered).
|
| 104 |
+
- Reuse servers — launching is expensive. Share one server across many test methods via `setUpClass`.
|
| 105 |
+
- Use as few GPUs as possible. Prefer 1-GPU runners.
|
| 106 |
+
- Each test file should take < 500 seconds; split if longer.
|
| 107 |
+
- Each GitHub Actions job should take < 30 minutes; split if longer.
|
| 108 |
+
- If tests are too slow for per-commit, consider nightly suites.
|
| 109 |
+
|
| 110 |
+
## Other Notes
|
| 111 |
+
|
| 112 |
+
### Adding New Models to Nightly CI
|
| 113 |
+
- **Text models**: Extend the [global model list variables](https://github.com/sgl-project/sglang/blob/85c1f7937781199203b38bb46325a2840f353a04/python/sglang/test/test_utils.py#L104) in `test_utils.py`.
|
| 114 |
+
- **VLMs**: Extend the `MODEL_THRESHOLDS` dictionary in `test/registered/eval/test_vlms_mmmu_eval.py`.
|
asian_ai/performance/SGLang/test/manual/ascend/test_ascend_deepseek_mtp.py
ADDED
|
@@ -0,0 +1,93 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import unittest
|
| 2 |
+
from types import SimpleNamespace
|
| 3 |
+
from urllib.parse import urlparse
|
| 4 |
+
|
| 5 |
+
from sglang.srt.environ import envs
|
| 6 |
+
from sglang.srt.utils import kill_process_tree
|
| 7 |
+
from sglang.test.few_shot_gsm8k import run_eval as run_eval_few_shot_gsm8k
|
| 8 |
+
from sglang.test.test_utils import (
|
| 9 |
+
DEFAULT_URL_FOR_TEST,
|
| 10 |
+
CustomTestCase,
|
| 11 |
+
popen_launch_server,
|
| 12 |
+
)
|
| 13 |
+
|
| 14 |
+
TEST_MODEL_MATRIX = {
|
| 15 |
+
"/root/.cache/modelscope/hub/models/vllm-ascend/DeepSeek-R1-0528-W8A8": {
|
| 16 |
+
"accuracy": 0.95,
|
| 17 |
+
"latency": 1000,
|
| 18 |
+
"output_throughput": 6,
|
| 19 |
+
},
|
| 20 |
+
}
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
class TestAscendDeepSeekMTP(CustomTestCase):
|
| 24 |
+
|
| 25 |
+
@classmethod
|
| 26 |
+
def setUpClass(cls):
|
| 27 |
+
cls.models = TEST_MODEL_MATRIX.keys()
|
| 28 |
+
cls.base_url = DEFAULT_URL_FOR_TEST
|
| 29 |
+
cls.url = urlparse(DEFAULT_URL_FOR_TEST)
|
| 30 |
+
|
| 31 |
+
cls.common_args = [
|
| 32 |
+
"--trust-remote-code",
|
| 33 |
+
"--attention-backend",
|
| 34 |
+
"ascend",
|
| 35 |
+
"--mem-fraction-static",
|
| 36 |
+
0.8,
|
| 37 |
+
"--disable-radix-cache",
|
| 38 |
+
"--chunked-prefill-size",
|
| 39 |
+
32768,
|
| 40 |
+
"--tp-size",
|
| 41 |
+
16,
|
| 42 |
+
"--dp-size",
|
| 43 |
+
2,
|
| 44 |
+
"--enable-dp-attention",
|
| 45 |
+
"--speculative-algorithm",
|
| 46 |
+
"NEXTN",
|
| 47 |
+
"--speculative-num-steps",
|
| 48 |
+
1,
|
| 49 |
+
"--speculative-eagle-topk",
|
| 50 |
+
1,
|
| 51 |
+
"--speculative-num-draft-tokens",
|
| 52 |
+
2,
|
| 53 |
+
]
|
| 54 |
+
|
| 55 |
+
envs.SGLANG_NPU_USE_MLAPO.set(True)
|
| 56 |
+
envs.SGLANG_ENABLE_OVERLAP_PLAN_STREAM.set(True)
|
| 57 |
+
|
| 58 |
+
def test_a_gsm8k(self):
|
| 59 |
+
for model in self.models:
|
| 60 |
+
with self.subTest(model=model):
|
| 61 |
+
print(f"##=== Testing accuracy: {model} ===##")
|
| 62 |
+
|
| 63 |
+
process = popen_launch_server(
|
| 64 |
+
model,
|
| 65 |
+
self.base_url,
|
| 66 |
+
timeout=2400,
|
| 67 |
+
other_args=[
|
| 68 |
+
*self.common_args,
|
| 69 |
+
],
|
| 70 |
+
)
|
| 71 |
+
|
| 72 |
+
try:
|
| 73 |
+
args = SimpleNamespace(
|
| 74 |
+
num_shots=5,
|
| 75 |
+
data_path=None,
|
| 76 |
+
num_questions=1319,
|
| 77 |
+
max_new_tokens=512,
|
| 78 |
+
parallel=128,
|
| 79 |
+
host=f"http://{self.url.hostname}",
|
| 80 |
+
port=int(self.url.port),
|
| 81 |
+
)
|
| 82 |
+
|
| 83 |
+
metrics = run_eval_few_shot_gsm8k(args)
|
| 84 |
+
self.assertGreaterEqual(
|
| 85 |
+
metrics["accuracy"],
|
| 86 |
+
TEST_MODEL_MATRIX[model]["accuracy"],
|
| 87 |
+
)
|
| 88 |
+
finally:
|
| 89 |
+
kill_process_tree(process.pid)
|
| 90 |
+
|
| 91 |
+
|
| 92 |
+
if __name__ == "__main__":
|
| 93 |
+
unittest.main()
|
asian_ai/performance/SGLang/test/manual/ascend/test_ascend_vocab_mask.py
ADDED
|
@@ -0,0 +1,81 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import math
|
| 2 |
+
|
| 3 |
+
import pytest
|
| 4 |
+
import torch
|
| 5 |
+
|
| 6 |
+
from sglang.srt.constrained import xgrammar_backend as xb
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
def _pack_mask(allowed_ids, vocab_size, batch_size=1):
|
| 10 |
+
nwords = math.ceil(vocab_size / 32)
|
| 11 |
+
m = torch.zeros((batch_size, nwords), dtype=torch.int32)
|
| 12 |
+
for b in range(batch_size):
|
| 13 |
+
for tid in allowed_ids[b]:
|
| 14 |
+
m[b, tid // 32] |= 1 << (tid % 32)
|
| 15 |
+
return m
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
def _apply_ref_cpu(logits, vocab_mask):
|
| 19 |
+
vocab_size = logits.shape[-1]
|
| 20 |
+
token_ids = torch.arange(vocab_size, device="cpu", dtype=torch.int64)
|
| 21 |
+
word_idx = token_ids // 32
|
| 22 |
+
bit_idx = (token_ids % 32).to(torch.int32)
|
| 23 |
+
words = vocab_mask.cpu()[:, word_idx].to(torch.int32)
|
| 24 |
+
allowed = ((words >> bit_idx) & 1).bool().to(logits.device)
|
| 25 |
+
out = logits.clone()
|
| 26 |
+
out.masked_fill_(~allowed, float("-inf"))
|
| 27 |
+
return out
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
@pytest.mark.skipif(
|
| 31 |
+
not hasattr(torch, "npu") or not torch.npu.is_available(), reason="NPU required"
|
| 32 |
+
)
|
| 33 |
+
def test_mask_blocks_disallowed_token_on_npu():
|
| 34 |
+
device = "npu:0"
|
| 35 |
+
vocab_size = 64
|
| 36 |
+
|
| 37 |
+
logits = torch.zeros((1, vocab_size), device=device, dtype=torch.float32)
|
| 38 |
+
logits[0, 16] = 22.125
|
| 39 |
+
logits[0, 5] = 10.0
|
| 40 |
+
|
| 41 |
+
allowed = [[5, 6, 7, 8]]
|
| 42 |
+
vocab_mask = _pack_mask(allowed, vocab_size).to(device=device, dtype=torch.int32)
|
| 43 |
+
|
| 44 |
+
g = xb.XGrammarGrammar.__new__(xb.XGrammarGrammar)
|
| 45 |
+
out = logits.clone()
|
| 46 |
+
g.apply_vocab_mask(out, vocab_mask)
|
| 47 |
+
|
| 48 |
+
assert not torch.isfinite(out[0, 16])
|
| 49 |
+
assert int(torch.argmax(out[0]).item()) != 16
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
@pytest.mark.skipif(
|
| 53 |
+
not hasattr(torch, "npu") or not torch.npu.is_available(), reason="NPU required"
|
| 54 |
+
)
|
| 55 |
+
def test_npu_path_matches_reference_random():
|
| 56 |
+
device = "npu:0"
|
| 57 |
+
B, V = 4, 257
|
| 58 |
+
torch.manual_seed(0)
|
| 59 |
+
|
| 60 |
+
logits = torch.randn(B, V, device=device, dtype=torch.float32)
|
| 61 |
+
|
| 62 |
+
allowed = []
|
| 63 |
+
for _ in range(B):
|
| 64 |
+
ids = torch.randperm(V)[: V // 4].tolist()
|
| 65 |
+
allowed.append(ids)
|
| 66 |
+
vocab_mask = _pack_mask(allowed, V, B).to(device=device, dtype=torch.int32)
|
| 67 |
+
|
| 68 |
+
g = xb.XGrammarGrammar.__new__(xb.XGrammarGrammar)
|
| 69 |
+
out_npu = logits.clone()
|
| 70 |
+
g.apply_vocab_mask(out_npu, vocab_mask)
|
| 71 |
+
|
| 72 |
+
out_ref = _apply_ref_cpu(logits, vocab_mask)
|
| 73 |
+
|
| 74 |
+
assert torch.equal(torch.isfinite(out_npu), torch.isfinite(out_ref))
|
| 75 |
+
diff = (
|
| 76 |
+
torch.nan_to_num(out_npu - out_ref, nan=0.0, posinf=0.0, neginf=0.0)
|
| 77 |
+
.abs()
|
| 78 |
+
.max()
|
| 79 |
+
.item()
|
| 80 |
+
)
|
| 81 |
+
assert diff < 1e-5
|
asian_ai/performance/SGLang/test/manual/ascend/test_ascend_w8a8_quantization.py
ADDED
|
@@ -0,0 +1,102 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Usage:
|
| 3 |
+
python3 -m unittest test_ascend_w8a8_quantization.TestAscendW8A8.test_gsm8k
|
| 4 |
+
"""
|
| 5 |
+
|
| 6 |
+
import os
|
| 7 |
+
import time
|
| 8 |
+
import unittest
|
| 9 |
+
from types import SimpleNamespace
|
| 10 |
+
from urllib.parse import urlparse
|
| 11 |
+
|
| 12 |
+
import requests
|
| 13 |
+
|
| 14 |
+
from sglang.srt.utils import kill_process_tree
|
| 15 |
+
from sglang.test.few_shot_gsm8k import run_eval
|
| 16 |
+
from sglang.test.test_utils import (
|
| 17 |
+
DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH,
|
| 18 |
+
DEFAULT_URL_FOR_TEST,
|
| 19 |
+
CustomTestCase,
|
| 20 |
+
is_in_ci,
|
| 21 |
+
popen_launch_server,
|
| 22 |
+
)
|
| 23 |
+
|
| 24 |
+
if "ASCEND_RT_VISIBLE_DEVICES" not in os.environ:
|
| 25 |
+
os.environ["ASCEND_RT_VISIBLE_DEVICES"] = "0,1"
|
| 26 |
+
DEFAULT_PORT_FOR_SRT_TEST_RUNNER = (
|
| 27 |
+
7000 + int(os.environ.get("ASCEND_RT_VISIBLE_DEVICES", "0")[0]) * 100
|
| 28 |
+
)
|
| 29 |
+
DEFAULT_URL_FOR_TEST = f"http://127.0.0.1:{DEFAULT_PORT_FOR_SRT_TEST_RUNNER + 1000}"
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
class TestAscendW8A8(CustomTestCase):
|
| 33 |
+
@classmethod
|
| 34 |
+
def setUpClass(cls):
|
| 35 |
+
cls.model = "vllm-ascend/Qwen2.5-0.5B-Instruct-w8a8"
|
| 36 |
+
cls.base_url = DEFAULT_URL_FOR_TEST
|
| 37 |
+
cls.process = popen_launch_server(
|
| 38 |
+
cls.model,
|
| 39 |
+
cls.base_url,
|
| 40 |
+
timeout=DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH,
|
| 41 |
+
other_args=[
|
| 42 |
+
"--trust-remote-code",
|
| 43 |
+
"--disable-cuda-graph",
|
| 44 |
+
"--device",
|
| 45 |
+
"npu",
|
| 46 |
+
"--attention-backend",
|
| 47 |
+
"ascend",
|
| 48 |
+
],
|
| 49 |
+
)
|
| 50 |
+
|
| 51 |
+
@classmethod
|
| 52 |
+
def tearDownClass(cls):
|
| 53 |
+
kill_process_tree(cls.process.pid)
|
| 54 |
+
|
| 55 |
+
def test_gsm8k(self):
|
| 56 |
+
base_url = DEFAULT_URL_FOR_TEST
|
| 57 |
+
url = urlparse(base_url)
|
| 58 |
+
args = SimpleNamespace(
|
| 59 |
+
num_shots=5,
|
| 60 |
+
data_path=None,
|
| 61 |
+
num_questions=200,
|
| 62 |
+
max_new_tokens=512,
|
| 63 |
+
parallel=128,
|
| 64 |
+
host=f"http://{url.hostname}",
|
| 65 |
+
port=int(url.port),
|
| 66 |
+
)
|
| 67 |
+
metrics = run_eval(args)
|
| 68 |
+
print(metrics)
|
| 69 |
+
|
| 70 |
+
self.assertGreaterEqual(metrics["accuracy"], 0.25)
|
| 71 |
+
self.assertGreaterEqual(metrics["output_throughput"], 1000)
|
| 72 |
+
|
| 73 |
+
def run_decode(self, max_new_tokens):
|
| 74 |
+
response = requests.post(
|
| 75 |
+
self.base_url + "/generate",
|
| 76 |
+
json={
|
| 77 |
+
"text": "The capital of France is",
|
| 78 |
+
"sampling_params": {
|
| 79 |
+
"temperature": 0,
|
| 80 |
+
"max_new_tokens": max_new_tokens,
|
| 81 |
+
},
|
| 82 |
+
"ignore_eos": True,
|
| 83 |
+
},
|
| 84 |
+
)
|
| 85 |
+
return response.json()
|
| 86 |
+
|
| 87 |
+
def test_throughput(self):
|
| 88 |
+
max_tokens = 256
|
| 89 |
+
|
| 90 |
+
tic = time.perf_counter()
|
| 91 |
+
res = self.run_decode(max_tokens)
|
| 92 |
+
tok = time.perf_counter()
|
| 93 |
+
print(res["text"])
|
| 94 |
+
throughput = max_tokens / (tok - tic)
|
| 95 |
+
print(f"Throughput: {throughput} tokens/s")
|
| 96 |
+
|
| 97 |
+
if is_in_ci():
|
| 98 |
+
self.assertGreaterEqual(throughput, 25)
|
| 99 |
+
|
| 100 |
+
|
| 101 |
+
if __name__ == "__main__":
|
| 102 |
+
unittest.main()
|
asian_ai/performance/SGLang/test/manual/ascend/test_mindspore_models.py
ADDED
|
@@ -0,0 +1,64 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Usage:
|
| 3 |
+
python3 -m unittest test_mindspore_models.TestMindSporeQwen3.test_gsm8k
|
| 4 |
+
"""
|
| 5 |
+
|
| 6 |
+
import unittest
|
| 7 |
+
from types import SimpleNamespace
|
| 8 |
+
|
| 9 |
+
from sglang.srt.utils import kill_process_tree
|
| 10 |
+
from sglang.test.few_shot_gsm8k import run_eval
|
| 11 |
+
from sglang.test.test_utils import (
|
| 12 |
+
DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH,
|
| 13 |
+
DEFAULT_URL_FOR_TEST,
|
| 14 |
+
CustomTestCase,
|
| 15 |
+
popen_launch_server,
|
| 16 |
+
)
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
class TestMindSporeQwen3(CustomTestCase):
|
| 20 |
+
@classmethod
|
| 21 |
+
def setUpClass(cls):
|
| 22 |
+
cls.model = "Qwen/Qwen3-8B"
|
| 23 |
+
cls.base_url = DEFAULT_URL_FOR_TEST
|
| 24 |
+
cls.process = popen_launch_server(
|
| 25 |
+
cls.model,
|
| 26 |
+
cls.base_url,
|
| 27 |
+
timeout=DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH,
|
| 28 |
+
other_args=[
|
| 29 |
+
"--device",
|
| 30 |
+
"npu",
|
| 31 |
+
"--model-impl",
|
| 32 |
+
"mindspore",
|
| 33 |
+
"--attention-backend",
|
| 34 |
+
"ascend",
|
| 35 |
+
"--tp-size",
|
| 36 |
+
"1",
|
| 37 |
+
"--dp-size",
|
| 38 |
+
"1",
|
| 39 |
+
"--mem-fraction-static",
|
| 40 |
+
0.8,
|
| 41 |
+
],
|
| 42 |
+
)
|
| 43 |
+
|
| 44 |
+
@classmethod
|
| 45 |
+
def tearDownClass(cls):
|
| 46 |
+
kill_process_tree(cls.process.pid)
|
| 47 |
+
|
| 48 |
+
def test_gsm8k(self):
|
| 49 |
+
args = SimpleNamespace(
|
| 50 |
+
num_shots=5,
|
| 51 |
+
data_path=None,
|
| 52 |
+
num_questions=200,
|
| 53 |
+
max_new_tokens=512,
|
| 54 |
+
parallel=128,
|
| 55 |
+
host="http://127.0.0.1",
|
| 56 |
+
port=int(self.base_url.split(":")[-1]),
|
| 57 |
+
)
|
| 58 |
+
metrics = run_eval(args)
|
| 59 |
+
print(f"{metrics=}")
|
| 60 |
+
self.assertGreater(metrics["accuracy"], 0.78)
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
if __name__ == "__main__":
|
| 64 |
+
unittest.main()
|
asian_ai/performance/SGLang/test/manual/ascend/vlm_models/test_npu_gemma_4_26b_a4b_it.py
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import unittest
|
| 2 |
+
|
| 3 |
+
from sglang.test.ascend.test_ascend_utils import GEMMA_4_26B_A4B_IT_WEIGHTS_PATH
|
| 4 |
+
from sglang.test.ascend.vlm_utils import TestVLMModels
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
class TestGemma426BA4BIt(TestVLMModels):
|
| 8 |
+
"""Testcase: Verify that the inference accuracy of the google/gemma-4-26B-A4B-it model on the MMMU dataset is no less than 0.40.
|
| 9 |
+
|
| 10 |
+
[Test Category] Model
|
| 11 |
+
[Test Target] google/gemma-4-26B-A4B-it
|
| 12 |
+
"""
|
| 13 |
+
|
| 14 |
+
model = GEMMA_4_26B_A4B_IT_WEIGHTS_PATH
|
| 15 |
+
mmmu_accuracy = 0.40
|
| 16 |
+
|
| 17 |
+
def test_vlm_mmmu_benchmark(self):
|
| 18 |
+
self._run_vlm_mmmu_test()
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
if __name__ == "__main__":
|
| 22 |
+
unittest.main()
|
asian_ai/performance/SGLang/test/manual/ascend/vlm_models/test_npu_gemma_4_31b.py
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import unittest
|
| 2 |
+
|
| 3 |
+
from sglang.test.ascend.test_ascend_utils import GEMMA_4_31B_WEIGHTS_PATH
|
| 4 |
+
from sglang.test.ascend.vlm_utils import TestVLMModels
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
class TestGemma431B(TestVLMModels):
|
| 8 |
+
"""Testcase: Verify that the inference accuracy of the google/gemma-4-31B-it model on the MMMU dataset is no less than 0.50.
|
| 9 |
+
|
| 10 |
+
[Test Category] Model
|
| 11 |
+
[Test Target] google/gemma-4-31B-it
|
| 12 |
+
"""
|
| 13 |
+
|
| 14 |
+
model = GEMMA_4_31B_WEIGHTS_PATH
|
| 15 |
+
mmmu_accuracy = 0.50
|
| 16 |
+
|
| 17 |
+
def test_vlm_mmmu_benchmark(self):
|
| 18 |
+
self._run_vlm_mmmu_test()
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
if __name__ == "__main__":
|
| 22 |
+
unittest.main()
|
asian_ai/performance/SGLang/test/manual/ascend/vlm_models/test_npu_gemma_4_e2b.py
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import unittest
|
| 2 |
+
|
| 3 |
+
from sglang.test.ascend.test_ascend_utils import GEMMA_4_E2B_WEIGHTS_PATH
|
| 4 |
+
from sglang.test.ascend.vlm_utils import TestVLMModels
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
class TestGemma4E2B(TestVLMModels):
|
| 8 |
+
"""Testcase: Verify that the inference accuracy of the google/gemma-4-E2B-it model on the MMMU dataset is no less than 0.15.
|
| 9 |
+
|
| 10 |
+
[Test Category] Model
|
| 11 |
+
[Test Target] google/gemma-4-E2B-it
|
| 12 |
+
"""
|
| 13 |
+
|
| 14 |
+
model = GEMMA_4_E2B_WEIGHTS_PATH
|
| 15 |
+
mmmu_accuracy = 0.15
|
| 16 |
+
|
| 17 |
+
def test_vlm_mmmu_benchmark(self):
|
| 18 |
+
self._run_vlm_mmmu_test()
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
if __name__ == "__main__":
|
| 22 |
+
unittest.main()
|
asian_ai/performance/SGLang/test/manual/ascend/vlm_models/test_npu_gemma_4_e4b.py
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import unittest
|
| 2 |
+
|
| 3 |
+
from sglang.test.ascend.test_ascend_utils import GEMMA_4_E4B_WEIGHTS_PATH
|
| 4 |
+
from sglang.test.ascend.vlm_utils import TestVLMModels
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
class TestGemma4E4B(TestVLMModels):
|
| 8 |
+
"""Testcase: Verify that the inference accuracy of the google/gemma-4-E4B-it model on the MMMU dataset is no less than 0.30.
|
| 9 |
+
|
| 10 |
+
[Test Category] Model
|
| 11 |
+
[Test Target] google/gemma-4-E4B-it
|
| 12 |
+
"""
|
| 13 |
+
|
| 14 |
+
model = GEMMA_4_E4B_WEIGHTS_PATH
|
| 15 |
+
mmmu_accuracy = 0.30
|
| 16 |
+
|
| 17 |
+
def test_vlm_mmmu_benchmark(self):
|
| 18 |
+
self._run_vlm_mmmu_test()
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
if __name__ == "__main__":
|
| 22 |
+
unittest.main()
|
asian_ai/performance/SGLang/test/manual/attention/test_fa3.py
ADDED
|
@@ -0,0 +1,263 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import unittest
|
| 2 |
+
from types import SimpleNamespace
|
| 3 |
+
|
| 4 |
+
import requests
|
| 5 |
+
|
| 6 |
+
from sglang.srt.environ import envs
|
| 7 |
+
from sglang.srt.utils import get_device_sm, kill_process_tree
|
| 8 |
+
from sglang.test.run_eval import run_eval
|
| 9 |
+
from sglang.test.test_utils import (
|
| 10 |
+
DEFAULT_DRAFT_MODEL_EAGLE3,
|
| 11 |
+
DEFAULT_MODEL_NAME_FOR_TEST,
|
| 12 |
+
DEFAULT_MODEL_NAME_FOR_TEST_MLA,
|
| 13 |
+
DEFAULT_MODEL_NAME_FOR_TEST_MLA_NEXTN,
|
| 14 |
+
DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH,
|
| 15 |
+
DEFAULT_URL_FOR_TEST,
|
| 16 |
+
CustomTestCase,
|
| 17 |
+
popen_launch_server,
|
| 18 |
+
)
|
| 19 |
+
|
| 20 |
+
# FlashAttention3 integration tests (requires SM 90+ / H100)
|
| 21 |
+
# Multiple test classes: FA3, FA3+MLA, FA3+SpecDecode variants
|
| 22 |
+
GSM_DATASET_PATH = None
|
| 23 |
+
|
| 24 |
+
# In case of some machine lack internet connection, we can set OFFLINE_MODE to True.
|
| 25 |
+
OFFLINE_MODE = False
|
| 26 |
+
|
| 27 |
+
# Change the path below when OFFLINE_MODE is True.
|
| 28 |
+
OFFLINE_PATH_DICT = {
|
| 29 |
+
DEFAULT_MODEL_NAME_FOR_TEST: "/shared/public/elr-models/meta-llama/Meta-Llama-3.1-8B-Instruct",
|
| 30 |
+
DEFAULT_DRAFT_MODEL_EAGLE3: "/shared/public/elr-models/jamesliu1/sglang-EAGLE3-Llama-3.1-Instruct-8B",
|
| 31 |
+
DEFAULT_MODEL_NAME_FOR_TEST_MLA: "/shared/public/sharing/deepseek/dsv3-test/snapshots/",
|
| 32 |
+
DEFAULT_MODEL_NAME_FOR_TEST_MLA_NEXTN: "/shared/public/sharing/deepseek/dsv3-test-NextN/snapshots/",
|
| 33 |
+
GSM_DATASET_PATH: "/shared/public/data/gsm8k/test.jsonl",
|
| 34 |
+
}
|
| 35 |
+
|
| 36 |
+
if OFFLINE_MODE:
|
| 37 |
+
DEFAULT_MODEL_NAME_FOR_TEST = OFFLINE_PATH_DICT[DEFAULT_MODEL_NAME_FOR_TEST]
|
| 38 |
+
DEFAULT_DRAFT_MODEL_EAGLE3 = OFFLINE_PATH_DICT[DEFAULT_DRAFT_MODEL_EAGLE3]
|
| 39 |
+
DEFAULT_MODEL_NAME_FOR_TEST_MLA = OFFLINE_PATH_DICT[DEFAULT_MODEL_NAME_FOR_TEST_MLA]
|
| 40 |
+
DEFAULT_MODEL_NAME_FOR_TEST_MLA_NEXTN = OFFLINE_PATH_DICT[
|
| 41 |
+
DEFAULT_MODEL_NAME_FOR_TEST_MLA_NEXTN
|
| 42 |
+
]
|
| 43 |
+
GSM_DATASET_PATH = OFFLINE_PATH_DICT[GSM_DATASET_PATH]
|
| 44 |
+
|
| 45 |
+
# Default server arguments shared across all tests
|
| 46 |
+
DEFAULT_SERVER_ARGS = [
|
| 47 |
+
"--trust-remote-code",
|
| 48 |
+
"--cuda-graph-max-bs-decode",
|
| 49 |
+
"8",
|
| 50 |
+
"--attention-backend",
|
| 51 |
+
"fa3",
|
| 52 |
+
]
|
| 53 |
+
|
| 54 |
+
"""
|
| 55 |
+
Integration test for python/sglang/srt/layers/attention/flashattention_backend.py
|
| 56 |
+
"""
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
@unittest.skipIf(get_device_sm() < 90, "Test requires CUDA SM 90 or higher")
|
| 60 |
+
class BaseFlashAttentionTest(CustomTestCase):
|
| 61 |
+
"""Base class for testing FlashAttention3."""
|
| 62 |
+
|
| 63 |
+
model = DEFAULT_MODEL_NAME_FOR_TEST
|
| 64 |
+
base_url = DEFAULT_URL_FOR_TEST
|
| 65 |
+
accuracy_threshold = 0.65 # derived tests need to override this
|
| 66 |
+
speculative_decode = False
|
| 67 |
+
spec_decode_threshold = 1.0 # derived spec decoding tests need to override this
|
| 68 |
+
|
| 69 |
+
@classmethod
|
| 70 |
+
def get_server_args(cls):
|
| 71 |
+
"""Return the arguments for the server launch. Override in subclasses."""
|
| 72 |
+
return DEFAULT_SERVER_ARGS
|
| 73 |
+
|
| 74 |
+
@classmethod
|
| 75 |
+
def setUpClass(cls):
|
| 76 |
+
# disable deep gemm precompile to make launch server faster
|
| 77 |
+
# please don't do this if you want to make your inference workload faster
|
| 78 |
+
with (
|
| 79 |
+
envs.SGLANG_JIT_DEEPGEMM_PRECOMPILE.override(False),
|
| 80 |
+
envs.SGLANG_ENABLE_JIT_DEEPGEMM.override(False),
|
| 81 |
+
):
|
| 82 |
+
cls.process = popen_launch_server(
|
| 83 |
+
cls.model,
|
| 84 |
+
cls.base_url,
|
| 85 |
+
timeout=DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH,
|
| 86 |
+
other_args=cls.get_server_args(),
|
| 87 |
+
)
|
| 88 |
+
|
| 89 |
+
@classmethod
|
| 90 |
+
def tearDownClass(cls):
|
| 91 |
+
kill_process_tree(cls.process.pid)
|
| 92 |
+
|
| 93 |
+
def test_gsm8k(self):
|
| 94 |
+
requests.get(self.base_url + "/flush_cache")
|
| 95 |
+
|
| 96 |
+
args = SimpleNamespace(
|
| 97 |
+
base_url=self.base_url,
|
| 98 |
+
model=self.model,
|
| 99 |
+
eval_name="gsm8k",
|
| 100 |
+
api="completion",
|
| 101 |
+
max_tokens=512,
|
| 102 |
+
num_examples=100,
|
| 103 |
+
num_threads=128,
|
| 104 |
+
num_shots=4,
|
| 105 |
+
gsm8k_data_path=GSM_DATASET_PATH,
|
| 106 |
+
)
|
| 107 |
+
metrics = run_eval(args)
|
| 108 |
+
print(f"{metrics=}")
|
| 109 |
+
|
| 110 |
+
# Use the appropriate metric key based on the test class
|
| 111 |
+
metric_key = "score"
|
| 112 |
+
self.assertGreater(metrics[metric_key], self.accuracy_threshold)
|
| 113 |
+
|
| 114 |
+
if self.speculative_decode:
|
| 115 |
+
server_info = requests.get(self.base_url + "/server_info").json()
|
| 116 |
+
avg_spec_accept_length = server_info["internal_states"][0][
|
| 117 |
+
"avg_spec_accept_length"
|
| 118 |
+
]
|
| 119 |
+
print(f"{avg_spec_accept_length=}")
|
| 120 |
+
self.assertGreater(avg_spec_accept_length, self.spec_decode_threshold)
|
| 121 |
+
|
| 122 |
+
|
| 123 |
+
class TestFlashAttention3MLA(BaseFlashAttentionTest):
|
| 124 |
+
"""Test FlashAttention3 with MLA, e.g. deepseek v3 test model"""
|
| 125 |
+
|
| 126 |
+
accuracy_threshold = 0.60
|
| 127 |
+
model = DEFAULT_MODEL_NAME_FOR_TEST_MLA
|
| 128 |
+
|
| 129 |
+
@classmethod
|
| 130 |
+
def get_server_args(cls):
|
| 131 |
+
return DEFAULT_SERVER_ARGS
|
| 132 |
+
|
| 133 |
+
|
| 134 |
+
class TestFlashAttention3SpeculativeDecode(BaseFlashAttentionTest):
|
| 135 |
+
"""Test FlashAttention3 with speculative decode enabled with Llama 3.1 8B and its eagle3 model"""
|
| 136 |
+
|
| 137 |
+
model = DEFAULT_MODEL_NAME_FOR_TEST
|
| 138 |
+
accuracy_threshold = 0.65
|
| 139 |
+
speculative_decode = True
|
| 140 |
+
spec_decode_threshold = 1.5
|
| 141 |
+
|
| 142 |
+
@classmethod
|
| 143 |
+
def get_server_args(cls):
|
| 144 |
+
args = DEFAULT_SERVER_ARGS
|
| 145 |
+
args.extend(
|
| 146 |
+
[
|
| 147 |
+
"--cuda-graph-max-bs-decode",
|
| 148 |
+
"4",
|
| 149 |
+
"--speculative-algorithm",
|
| 150 |
+
"EAGLE3",
|
| 151 |
+
"--speculative-draft-model-path",
|
| 152 |
+
DEFAULT_DRAFT_MODEL_EAGLE3,
|
| 153 |
+
"--speculative-num-steps",
|
| 154 |
+
"3",
|
| 155 |
+
"--speculative-eagle-topk",
|
| 156 |
+
"1",
|
| 157 |
+
"--speculative-num-draft-tokens",
|
| 158 |
+
"4",
|
| 159 |
+
"--dtype",
|
| 160 |
+
"float16",
|
| 161 |
+
]
|
| 162 |
+
)
|
| 163 |
+
return args
|
| 164 |
+
|
| 165 |
+
|
| 166 |
+
class TestFlashAttention3SpeculativeDecodeTopk(BaseFlashAttentionTest):
|
| 167 |
+
"""Tests FlashAttention3 with enhanced speculative decoding using Llama 3.1 8B and EAGLE3.
|
| 168 |
+
This test will be using top-k value > 1 which would verify the other branches of the FA3 code
|
| 169 |
+
"""
|
| 170 |
+
|
| 171 |
+
model = DEFAULT_MODEL_NAME_FOR_TEST
|
| 172 |
+
accuracy_threshold = 0.65
|
| 173 |
+
speculative_decode = True
|
| 174 |
+
spec_decode_threshold = 1.6
|
| 175 |
+
|
| 176 |
+
@classmethod
|
| 177 |
+
def get_server_args(cls):
|
| 178 |
+
args = DEFAULT_SERVER_ARGS
|
| 179 |
+
args.extend(
|
| 180 |
+
[
|
| 181 |
+
"--cuda-graph-max-bs-decode",
|
| 182 |
+
"4",
|
| 183 |
+
"--speculative-algorithm",
|
| 184 |
+
"EAGLE3",
|
| 185 |
+
"--speculative-draft-model-path",
|
| 186 |
+
DEFAULT_DRAFT_MODEL_EAGLE3,
|
| 187 |
+
"--speculative-num-steps",
|
| 188 |
+
"5",
|
| 189 |
+
"--speculative-eagle-topk",
|
| 190 |
+
"4",
|
| 191 |
+
"--speculative-num-draft-tokens",
|
| 192 |
+
"8",
|
| 193 |
+
"--dtype",
|
| 194 |
+
"float16",
|
| 195 |
+
]
|
| 196 |
+
)
|
| 197 |
+
return args
|
| 198 |
+
|
| 199 |
+
|
| 200 |
+
class TestFlashAttention3MLASpeculativeDecode(BaseFlashAttentionTest):
|
| 201 |
+
"""Test FlashAttention3 with speculative decode enabled with deepseek v3 test model and its nextN model"""
|
| 202 |
+
|
| 203 |
+
model = DEFAULT_MODEL_NAME_FOR_TEST_MLA
|
| 204 |
+
accuracy_threshold = 0.60
|
| 205 |
+
speculative_decode = True
|
| 206 |
+
spec_decode_threshold = 2.5
|
| 207 |
+
|
| 208 |
+
@classmethod
|
| 209 |
+
def get_server_args(cls):
|
| 210 |
+
args = DEFAULT_SERVER_ARGS
|
| 211 |
+
args.extend(
|
| 212 |
+
[
|
| 213 |
+
"--cuda-graph-max-bs-decode",
|
| 214 |
+
"4",
|
| 215 |
+
"--speculative-algorithm",
|
| 216 |
+
"EAGLE",
|
| 217 |
+
"--speculative-draft-model-path",
|
| 218 |
+
DEFAULT_MODEL_NAME_FOR_TEST_MLA_NEXTN,
|
| 219 |
+
"--speculative-num-steps",
|
| 220 |
+
"3",
|
| 221 |
+
"--speculative-eagle-topk",
|
| 222 |
+
"1",
|
| 223 |
+
"--speculative-num-draft-tokens",
|
| 224 |
+
"4",
|
| 225 |
+
]
|
| 226 |
+
)
|
| 227 |
+
return args
|
| 228 |
+
|
| 229 |
+
|
| 230 |
+
class TestFlashAttention3MLASpeculativeDecodeTopk(BaseFlashAttentionTest):
|
| 231 |
+
"""Test FlashAttention3 with speculative decode enabled with deepseek v3 test model and its nextN model
|
| 232 |
+
This test will be using top-k value > 1 which would verify the other branches of the FA3 code
|
| 233 |
+
"""
|
| 234 |
+
|
| 235 |
+
model = DEFAULT_MODEL_NAME_FOR_TEST_MLA
|
| 236 |
+
accuracy_threshold = 0.60
|
| 237 |
+
speculative_decode = True
|
| 238 |
+
spec_decode_threshold = 2.95
|
| 239 |
+
|
| 240 |
+
@classmethod
|
| 241 |
+
def get_server_args(cls):
|
| 242 |
+
args = DEFAULT_SERVER_ARGS
|
| 243 |
+
args.extend(
|
| 244 |
+
[
|
| 245 |
+
"--cuda-graph-max-bs-decode",
|
| 246 |
+
"4",
|
| 247 |
+
"--speculative-algorithm",
|
| 248 |
+
"EAGLE",
|
| 249 |
+
"--speculative-draft-model-path",
|
| 250 |
+
DEFAULT_MODEL_NAME_FOR_TEST_MLA_NEXTN,
|
| 251 |
+
"--speculative-num-steps",
|
| 252 |
+
"5",
|
| 253 |
+
"--speculative-eagle-topk",
|
| 254 |
+
"4",
|
| 255 |
+
"--speculative-num-draft-tokens",
|
| 256 |
+
"8",
|
| 257 |
+
]
|
| 258 |
+
)
|
| 259 |
+
return args
|
| 260 |
+
|
| 261 |
+
|
| 262 |
+
if __name__ == "__main__":
|
| 263 |
+
unittest.main()
|
asian_ai/performance/SGLang/test/manual/attention/test_flashattn_backend.py
AD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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import unittest
|
| 2 |
+
|
| 3 |
+
import torch
|
| 4 |
+
|
| 5 |
+
from sglang.srt.configs.model_config import AttentionArch
|
| 6 |
+
from sglang.srt.layers.attention.flashattention_backend import (
|
| 7 |
+
FlashAttentionBackend,
|
| 8 |
+
draft_decode_set_expand_metadata,
|
| 9 |
+
)
|
| 10 |
+
from sglang.srt.layers.attention.torch_native_backend import TorchNativeAttnBackend
|
| 11 |
+
from sglang.srt.layers.radix_attention import RadixAttention
|
| 12 |
+
from sglang.srt.mem_cache.memory_pool import MHATokenToKVPool
|
| 13 |
+
from sglang.srt.model_executor.forward_batch_info import ForwardBatch, ForwardMode
|
| 14 |
+
from sglang.srt.model_executor.forward_context import (
|
| 15 |
+
ForwardContext,
|
| 16 |
+
set_forward_context,
|
| 17 |
+
)
|
| 18 |
+
from sglang.test.test_utils import CustomTestCase
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
class MockModelRunner:
|
| 22 |
+
def __init__(
|
| 23 |
+
self,
|
| 24 |
+
page_size=1,
|
| 25 |
+
num_heads=2,
|
| 26 |
+
head_dim=8,
|
| 27 |
+
):
|
| 28 |
+
self.device = "cuda"
|
| 29 |
+
self.dtype = torch.float16
|
| 30 |
+
self.kv_cache_dtype = torch.float16
|
| 31 |
+
self.is_hybrid_swa = False
|
| 32 |
+
self.attention_chunk_size = None
|
| 33 |
+
attention_arch = AttentionArch.MHA
|
| 34 |
+
# Max batch size for the test.
|
| 35 |
+
max_batch_size = 160
|
| 36 |
+
# Total tokens(prefix + extend + decode) in the test should not exceed this length.
|
| 37 |
+
max_context_len = 2048
|
| 38 |
+
self.model_config = type(
|
| 39 |
+
"ModelConfig",
|
| 40 |
+
(),
|
| 41 |
+
{
|
| 42 |
+
"context_len": max_context_len,
|
| 43 |
+
"is_multimodal": False,
|
| 44 |
+
"attention_arch": attention_arch,
|
| 45 |
+
"is_encoder_decoder": False,
|
| 46 |
+
"is_local_attention_model": False,
|
| 47 |
+
},
|
| 48 |
+
)()
|
| 49 |
+
self.sliding_window_size = None
|
| 50 |
+
self.kv_cache_dtype = (
|
| 51 |
+
self.dtype
|
| 52 |
+
) # torch dtype, required by FlashAttentionBackend
|
| 53 |
+
|
| 54 |
+
# server_args is still needed for string-based config (kv_cache_dtype_str)
|
| 55 |
+
self.server_args = type(
|
| 56 |
+
"ServerArgs",
|
| 57 |
+
(),
|
| 58 |
+
{
|
| 59 |
+
"kv_cache_dtype": "auto", # string version for kv_cache_dtype_str
|
| 60 |
+
"speculative_eagle_topk": None,
|
| 61 |
+
"speculative_num_draft_tokens": 0,
|
| 62 |
+
"enable_deterministic_inference": False,
|
| 63 |
+
},
|
| 64 |
+
)
|
| 65 |
+
self.attn_cp_size = 1
|
| 66 |
+
# Create a large enough req_to_token_pool to fit the test usage.
|
| 67 |
+
self.req_to_token_pool = type(
|
| 68 |
+
"TokenPool",
|
| 69 |
+
(),
|
| 70 |
+
{
|
| 71 |
+
# A typical max_bs * max_context_len for cuda graph decode
|
| 72 |
+
"size": max_batch_size,
|
| 73 |
+
# Add req_to_token attribute
|
| 74 |
+
"req_to_token": torch.zeros(
|
| 75 |
+
max_batch_size,
|
| 76 |
+
max_context_len,
|
| 77 |
+
dtype=torch.int32,
|
| 78 |
+
device=self.device,
|
| 79 |
+
),
|
| 80 |
+
},
|
| 81 |
+
)()
|
| 82 |
+
self.page_size = page_size
|
| 83 |
+
max_total_num_tokens = max_batch_size * max_context_len
|
| 84 |
+
self.token_to_kv_pool = MHATokenToKVPool(
|
| 85 |
+
size=max_total_num_tokens,
|
| 86 |
+
page_size=page_size,
|
| 87 |
+
dtype=self.dtype,
|
| 88 |
+
head_num=num_heads,
|
| 89 |
+
head_dim=head_dim,
|
| 90 |
+
layer_num=1, # only consider layer=1 for unit test
|
| 91 |
+
device=self.device,
|
| 92 |
+
enable_memory_saver=False,
|
| 93 |
+
)
|
| 94 |
+
self.hisparse_coordinator = None
|
| 95 |
+
|
| 96 |
+
|
| 97 |
+
@unittest.skipIf(not torch.cuda.is_available(), "Test requires CUDA")
|
| 98 |
+
class TestFlashAttentionBackend(CustomTestCase):
|
| 99 |
+
def setUp(self):
|
| 100 |
+
# Test parameters
|
| 101 |
+
self.batch_size = 2
|
| 102 |
+
self.seq_len = 256
|
| 103 |
+
self.num_heads = 2
|
| 104 |
+
self.head_dim = 8
|
| 105 |
+
self.device = "cuda"
|
| 106 |
+
self.dtype = torch.float16
|
| 107 |
+
|
| 108 |
+
def _init_model_runner(self, page_size=1):
|
| 109 |
+
self.model_runner = MockModelRunner(
|
| 110 |
+
page_size=page_size,
|
| 111 |
+
num_heads=self.num_heads,
|
| 112 |
+
head_dim=self.head_dim,
|
| 113 |
+
)
|
| 114 |
+
self.backend = FlashAttentionBackend(self.model_runner)
|
| 115 |
+
self.ref_backend = TorchNativeAttnBackend(self.model_runner)
|
| 116 |
+
self.model_runner.model_config.num_attention_heads = self.num_heads
|
| 117 |
+
# Publish the backend for any RadixAttention.forward path the tests
|
| 118 |
+
# exercise; tearDown is unnecessary here since each test re-inits.
|
| 119 |
+
set_forward_context(ForwardContext(attn_backend=self.backend))
|
| 120 |
+
|
| 121 |
+
def _mock_write_to_req_to_token_pool(self, batch_size, seq_len, page_size):
|
| 122 |
+
# if page_size > 1, the token pool stores the index to the page.
|
| 123 |
+
# so we need to multiply the index by page_size.
|
| 124 |
+
self.req_to_token = (
|
| 125 |
+
torch.arange(0, batch_size, dtype=torch.int32, device=self.device)[:, None]
|
| 126 |
+
* seq_len
|
| 127 |
+
+ torch.arange(0, seq_len, dtype=torch.int32, device=self.device)[None, :]
|
| 128 |
+
+ page_size
|
| 129 |
+
)
|
| 130 |
+
self.model_runner.req_to_token_pool.req_to_token[:batch_size, :seq_len] = (
|
| 131 |
+
self.req_to_token
|
| 132 |
+
)
|
| 133 |
+
|
| 134 |
+
def _create_attention_layer(self):
|
| 135 |
+
"""Create attention layer for testing."""
|
| 136 |
+
return RadixAttention(
|
| 137 |
+
num_heads=self.num_heads,
|
| 138 |
+
head_dim=self.head_dim,
|
| 139 |
+
scaling=1.0,
|
| 140 |
+
num_kv_heads=self.num_heads,
|
| 141 |
+
layer_id=0,
|
| 142 |
+
)
|
| 143 |
+
|
| 144 |
+
def _create_qkv_tensors(self, tokens_len):
|
| 145 |
+
"""Create q, k, v tensors for testing."""
|
| 146 |
+
shape = (tokens_len, self.num_heads, self.head_dim)
|
| 147 |
+
return (
|
| 148 |
+
torch.randn(shape, dtype=self.dtype, device=self.device),
|
| 149 |
+
torch.randn(shape, dtype=self.dtype, device=self.device),
|
| 150 |
+
torch.randn(shape, dtype=self.dtype, device=self.device),
|
| 151 |
+
)
|
| 152 |
+
|
| 153 |
+
def _run_reference_forward(
|
| 154 |
+
self, mode, q, k, v, layer, forward_batch, expected_shape
|
| 155 |
+
):
|
| 156 |
+
"""Run reference forward pass using native backend."""
|
| 157 |
+
if mode == ForwardMode.EXTEND:
|
| 158 |
+
output = self.ref_backend.forward_extend(q, k, v, layer, forward_batch)
|
| 159 |
+
else: # ForwardMode.DECODE
|
| 160 |
+
output = self.ref_backend.forward_decode(q, k, v, layer, forward_batch)
|
| 161 |
+
return output.view(expected_shape)
|
| 162 |
+
|
| 163 |
+
def _verify_output(self, output, expected_shape, output_ref=None):
|
| 164 |
+
"""Verify output tensor shape, dtype, and values."""
|
| 165 |
+
self.assertEqual(
|
| 166 |
+
output.shape,
|
| 167 |
+
expected_shape,
|
| 168 |
+
f"Expected shape {expected_shape}, got {output.shape}",
|
| 169 |
+
)
|
| 170 |
+
self.assertEqual(output.dtype, self.dtype)
|
| 171 |
+
self.assertEqual(output.device.type, "cuda")
|
| 172 |
+
self.assertEqual(
|
| 173 |
+
torch.isnan(output).sum().item(), 0, "Output contains NaN values"
|
| 174 |
+
)
|
| 175 |
+
|
| 176 |
+
if output_ref is not None:
|
| 177 |
+
if not torch.allclose(output, output_ref, atol=1e-1, rtol=0.0):
|
| 178 |
+
# Check where the values differ beyond the given tolerances
|
| 179 |
+
diff_mask = ~torch.isclose(output, output_ref, atol=1e-1, rtol=0.0)
|
| 180 |
+
|
| 181 |
+
# Find the first index where the difference occurs
|
| 182 |
+
if diff_mask.any():
|
| 183 |
+
first_mismatch_idx = diff_mask.nonzero()[0]
|
| 184 |
+
print(
|
| 185 |
+
"First mismatch at index:", tuple(first_mismatch_idx.tolist())
|
| 186 |
+
)
|
| 187 |
+
print("output:", output[tuple(first_mismatch_idx.tolist())])
|
| 188 |
+
print("output_ref:", output_ref[tuple(first_mismatch_idx.tolist())])
|
| 189 |
+
raise AssertionError(
|
| 190 |
+
"Attention output is not close to the torch native backend output"
|
| 191 |
+
)
|
| 192 |
+
|
| 193 |
+
def _create_forward_batch(
|
| 194 |
+
self, mode, q_len=None, prefix_len=0, page_size=1, attn_cp_size=1
|
| 195 |
+
):
|
| 196 |
+
"""Create a forward batch for testing based on mode and lengths."""
|
| 197 |
+
self._init_model_runner(page_size=page_size)
|
| 198 |
+
|
| 199 |
+
# Default to self.seq_len if not specified
|
| 200 |
+
q_len = q_len or self.seq_len
|
| 201 |
+
|
| 202 |
+
if mode == ForwardMode.EXTEND:
|
| 203 |
+
total_len = prefix_len + q_len
|
| 204 |
+
out_cache_start = prefix_len * self.batch_size
|
| 205 |
+
out_cache_end = total_len * self.batch_size
|
| 206 |
+
|
| 207 |
+
forward_batch = ForwardBatch(
|
| 208 |
+
batch_size=self.batch_size,
|
| 209 |
+
input_ids=torch.randint(
|
| 210 |
+
0, 100, (self.batch_size, q_len), device=self.device
|
| 211 |
+
),
|
| 212 |
+
out_cache_loc=torch.arange(
|
| 213 |
+
out_cache_start, out_cache_end, device=self.device
|
| 214 |
+
),
|
| 215 |
+
seq_lens_sum=self.batch_size * total_len,
|
| 216 |
+
forward_mode=mode,
|
| 217 |
+
req_pool_indices=torch.arange(self.batch_size, device=self.device),
|
| 218 |
+
seq_lens=torch.tensor(
|
| 219 |
+
[total_len] * self.batch_size, device=self.device
|
| 220 |
+
),
|
| 221 |
+
seq_lens_cpu=torch.tensor([total_len] * self.batch_size, device="cpu"),
|
| 222 |
+
extend_prefix_lens=torch.tensor(
|
| 223 |
+
[prefix_len] * self.batch_size, device=self.device
|
| 224 |
+
),
|
| 225 |
+
extend_prefix_lens_cpu=torch.tensor(
|
| 226 |
+
[prefix_len] * self.batch_size, device="cpu"
|
| 227 |
+
),
|
| 228 |
+
extend_seq_lens=torch.tensor(
|
| 229 |
+
[q_len] * self.batch_size, device=self.device
|
| 230 |
+
),
|
| 231 |
+
extend_seq_lens_cpu=torch.tensor(
|
| 232 |
+
[q_len] * self.batch_size, device="cpu"
|
| 233 |
+
),
|
| 234 |
+
)
|
| 235 |
+
if attn_cp_size > 1:
|
| 236 |
+
forward_batch.attn_cp_metadata = type(
|
| 237 |
+
"AttnCPMetadata",
|
| 238 |
+
(),
|
| 239 |
+
{
|
| 240 |
+
"kv_len_prev_tensor": torch.tensor(
|
| 241 |
+
[q_len // 2] * self.batch_size,
|
| 242 |
+
dtype=torch.int32,
|
| 243 |
+
device=self.device,
|
| 244 |
+
),
|
| 245 |
+
"kv_len_next_tensor": torch.tensor(
|
| 246 |
+
[q_len] * self.batch_size,
|
| 247 |
+
dtype=torch.int32,
|
| 248 |
+
device=self.device,
|
| 249 |
+
),
|
| 250 |
+
"actual_seq_q_prev": q_len // 2,
|
| 251 |
+
"actual_seq_q_next": q_len // 2,
|
| 252 |
+
},
|
| 253 |
+
)
|
| 254 |
+
else: # ForwardMode.DECODE
|
| 255 |
+
decode_len = q_len # Assuming 1 for decode testing
|
| 256 |
+
total_len = self.seq_len + decode_len
|
| 257 |
+
if mode == ForwardMode.DECODE and page_size > 1:
|
| 258 |
+
# Get next page_size multiple of self.seq_len
|
| 259 |
+
out_cache_start = (
|
| 260 |
+
self.batch_size * self.seq_len // page_size + 1
|
| 261 |
+
) * page_size
|
| 262 |
+
# out_cache_end is the start of the next block
|
| 263 |
+
out_cache_end = out_cache_start + decode_len * page_size
|
| 264 |
+
else:
|
| 265 |
+
out_cache_start = self.batch_size * self.seq_len
|
| 266 |
+
out_cache_end = self.batch_size * total_len
|
| 267 |
+
|
| 268 |
+
forward_batch = ForwardBatch(
|
| 269 |
+
batch_size=self.batch_size,
|
| 270 |
+
input_ids=torch.randint(
|
| 271 |
+
0, 100, (self.batch_size, decode_len), device=self.device
|
| 272 |
+
),
|
| 273 |
+
out_cache_loc=torch.tensor(
|
| 274 |
+
[out_cache_start, out_cache_end], device=self.device
|
| 275 |
+
),
|
| 276 |
+
seq_lens_sum=self.batch_size * total_len,
|
| 277 |
+
forward_mode=mode,
|
| 278 |
+
req_pool_indices=torch.arange(self.batch_size, device=self.device),
|
| 279 |
+
seq_lens=torch.tensor(
|
| 280 |
+
[total_len] * self.batch_size, device=self.device
|
| 281 |
+
),
|
| 282 |
+
seq_lens_cpu=torch.tensor([total_len] * self.batch_size, device="cpu"),
|
| 283 |
+
)
|
| 284 |
+
|
| 285 |
+
# Pool refs are resolved via the active ForwardContext (published in
|
| 286 |
+
# setUp). Write the test fixture's req_to_token mapping.
|
| 287 |
+
self._mock_write_to_req_to_token_pool(self.batch_size, total_len, page_size)
|
| 288 |
+
|
| 289 |
+
return forward_batch
|
| 290 |
+
|
| 291 |
+
def _setup_kv_cache(self, forward_batch, layer, cache_len):
|
| 292 |
+
# Create constant values for the prefix cache for easy debugging
|
| 293 |
+
cache_k = torch.ones(
|
| 294 |
+
self.batch_size * cache_len,
|
| 295 |
+
self.num_heads,
|
| 296 |
+
self.head_dim,
|
| 297 |
+
dtype=self.dtype,
|
| 298 |
+
device=self.device,
|
| 299 |
+
)
|
| 300 |
+
cache_v = (
|
| 301 |
+
torch.ones(
|
| 302 |
+
self.batch_size * cache_len,
|
| 303 |
+
self.num_heads,
|
| 304 |
+
self.head_dim,
|
| 305 |
+
dtype=self.dtype,
|
| 306 |
+
device=self.device,
|
| 307 |
+
)
|
| 308 |
+
* 2
|
| 309 |
+
)
|
| 310 |
+
|
| 311 |
+
# Set the prefix KV cache
|
| 312 |
+
self.model_runner.token_to_kv_pool.set_kv_buffer(
|
| 313 |
+
layer,
|
| 314 |
+
torch.arange(self.batch_size * cache_len, device=self.device),
|
| 315 |
+
cache_k,
|
| 316 |
+
cache_v,
|
| 317 |
+
layer.k_scale,
|
| 318 |
+
layer.v_scale,
|
| 319 |
+
)
|
| 320 |
+
|
| 321 |
+
def _run_attention_test(self, mode, q_len, prefix_len=0, page_size=1):
|
| 322 |
+
"""
|
| 323 |
+
Run an attention test with the specified parameters.
|
| 324 |
+
Args:
|
| 325 |
+
mode: ForwardMode.EXTEND or ForwardMode.DECODE
|
| 326 |
+
q_len: Length of the query sequence. For decode mode, q_len is 1.
|
| 327 |
+
prefix_len: Length of the prefix sequence for extend mode
|
| 328 |
+
page_size: Page size for the KV cache
|
| 329 |
+
"""
|
| 330 |
+
layer = self._create_attention_layer()
|
| 331 |
+
|
| 332 |
+
# Create forward batch and set up
|
| 333 |
+
forward_batch = self._create_forward_batch(mode, q_len, prefix_len, page_size)
|
| 334 |
+
|
| 335 |
+
# Create QKV tensors for the input
|
| 336 |
+
q, k, v = self._create_qkv_tensors(self.batch_size * q_len)
|
| 337 |
+
|
| 338 |
+
# KV cache for prefixed extend is prefix_len
|
| 339 |
+
# KV cache for decode is same as seq_len
|
| 340 |
+
# No KV cache for extend without prefix
|
| 341 |
+
if mode == ForwardMode.EXTEND:
|
| 342 |
+
if prefix_len > 0:
|
| 343 |
+
self._setup_kv_cache(forward_batch, layer, prefix_len)
|
| 344 |
+
else:
|
| 345 |
+
self._setup_kv_cache(forward_batch, layer, self.seq_len)
|
| 346 |
+
|
| 347 |
+
self.backend.init_forward_metadata(forward_batch)
|
| 348 |
+
|
| 349 |
+
if mode == ForwardMode.EXTEND:
|
| 350 |
+
expected_shape = (
|
| 351 |
+
self.batch_size * q_len,
|
| 352 |
+
self.num_heads * self.head_dim,
|
| 353 |
+
)
|
| 354 |
+
output = self.backend.forward_extend(q, k, v, layer, forward_batch)
|
| 355 |
+
else:
|
| 356 |
+
expected_shape = (self.batch_size, self.num_heads * self.head_dim)
|
| 357 |
+
output = self.backend.forward_decode(q, k, v, layer, forward_batch)
|
| 358 |
+
|
| 359 |
+
output_ref = self._run_reference_forward(
|
| 360 |
+
mode, q, k, v, layer, forward_batch, expected_shape
|
| 361 |
+
)
|
| 362 |
+
|
| 363 |
+
self._verify_output(output, expected_shape, output_ref)
|
| 364 |
+
|
| 365 |
+
return output
|
| 366 |
+
|
| 367 |
+
def _run_attention_cp_test(self, mode, q_len, prefix_len=0, page_size=1):
|
| 368 |
+
layer = self._create_attention_layer()
|
| 369 |
+
|
| 370 |
+
# Create forward batch and set up
|
| 371 |
+
forward_batch = self._create_forward_batch(
|
| 372 |
+
mode, q_len, prefix_len, page_size, attn_cp_size=2
|
| 373 |
+
)
|
| 374 |
+
self.backend.attn_cp_size = 2
|
| 375 |
+
|
| 376 |
+
# Create QKV tensors for the input
|
| 377 |
+
q, k, v = self._create_qkv_tensors(self.batch_size * q_len)
|
| 378 |
+
|
| 379 |
+
# KV cache for prefixed extend is prefix_len
|
| 380 |
+
# KV cache for decode is same as seq_len
|
| 381 |
+
# No KV cache for extend without prefix
|
| 382 |
+
# Setup KV cache for CP testing - need KV cache to have actual values
|
| 383 |
+
# For extend with CP, we need KV cache populated so attention has something to attend to
|
| 384 |
+
self._setup_kv_cache(forward_batch, layer, q_len)
|
| 385 |
+
|
| 386 |
+
self.backend.init_forward_metadata(forward_batch)
|
| 387 |
+
|
| 388 |
+
# if mode == ForwardMode.EXTEND:
|
| 389 |
+
expected_shape = (
|
| 390 |
+
self.batch_size * q_len,
|
| 391 |
+
self.num_heads * self.head_dim,
|
| 392 |
+
)
|
| 393 |
+
|
| 394 |
+
output = self.backend.forward_extend(q, k, v, layer, forward_batch)
|
| 395 |
+
# else:
|
| 396 |
+
# expected_shape = (self.batch_size, self.num_heads * self.head_dim)
|
| 397 |
+
# output = self.backend.forward_decode(q, k, v, layer, forward_batch)
|
| 398 |
+
|
| 399 |
+
output_ref = self._run_reference_forward(
|
| 400 |
+
mode, q, k, v, layer, forward_batch, expected_shape
|
| 401 |
+
)
|
| 402 |
+
|
| 403 |
+
self._verify_output(output, expected_shape, output_ref)
|
| 404 |
+
|
| 405 |
+
return output
|
| 406 |
+
|
| 407 |
+
def test_forward_extend_cp(self):
|
| 408 |
+
"""Test the standard extend operation with context parallel."""
|
| 409 |
+
self._run_attention_cp_test(ForwardMode.EXTEND, q_len=self.seq_len)
|
| 410 |
+
|
| 411 |
+
# def test_forward_extend_cp_with_prefix(self):
|
| 412 |
+
# """Test the standard extend operation with context parallel and prefix."""
|
| 413 |
+
# prefix_len = self.seq_len // 2
|
| 414 |
+
# extend_len = self.seq_len - prefix_len
|
| 415 |
+
# self._run_attention_cp_test(ForwardMode.EXTEND, q_len=extend_len, prefix_len=prefix_len)
|
| 416 |
+
|
| 417 |
+
# def test_forward_extend(self):
|
| 418 |
+
# """Test the standard extend operation."""
|
| 419 |
+
# self._run_attention_test(ForwardMode.EXTEND, q_len=self.seq_len)
|
| 420 |
+
|
| 421 |
+
# def test_forward_decode(self):
|
| 422 |
+
# """Test the decode operation with cached tokens."""
|
| 423 |
+
# self._run_attention_test(ForwardMode.DECODE, q_len=1)
|
| 424 |
+
|
| 425 |
+
# def test_forward_extend_with_prefix(self):
|
| 426 |
+
# """Test extending from cached prefix tokens."""
|
| 427 |
+
# prefix_len = self.seq_len // 2
|
| 428 |
+
# extend_len = self.seq_len - prefix_len
|
| 429 |
+
# self._run_attention_test(
|
| 430 |
+
# ForwardMode.EXTEND, q_len=extend_len, prefix_len=prefix_len
|
| 431 |
+
# )
|
| 432 |
+
|
| 433 |
+
# def test_forward_extend_with_page_size_greater_than_1(self):
|
| 434 |
+
# """Test extending from cached prefix tokens with page size greater than 1."""
|
| 435 |
+
# self._run_attention_test(ForwardMode.EXTEND, q_len=self.seq_len, page_size=64)
|
| 436 |
+
|
| 437 |
+
# def test_forward_decode_with_page_size_greater_than_1(self):
|
| 438 |
+
# """Test decode operation with page size greater than 1."""
|
| 439 |
+
# self._run_attention_test(ForwardMode.DECODE, q_len=1, page_size=64)
|
| 440 |
+
|
| 441 |
+
|
| 442 |
+
class TestUpdateDraftDecodeSetExpandMetadata(CustomTestCase):
|
| 443 |
+
"""
|
| 444 |
+
All the test cases examples have 1 additional cache location than the decode length.
|
| 445 |
+
This is to align with the current allocation logic. It does not affect the correctness.
|
| 446 |
+
"""
|
| 447 |
+
|
| 448 |
+
def test_draft_decode_set_expand_metadata(self):
|
| 449 |
+
bs, topk, page_size = 1, 2, 4
|
| 450 |
+
|
| 451 |
+
cases = [
|
| 452 |
+
(
|
| 453 |
+
torch.tensor(
|
| 454 |
+
[
|
| 455 |
+
[23, 24],
|
| 456 |
+
[31, 32],
|
| 457 |
+
],
|
| 458 |
+
dtype=torch.int32,
|
| 459 |
+
),
|
| 460 |
+
torch.tensor(
|
| 461 |
+
[
|
| 462 |
+
[5, 6],
|
| 463 |
+
[7, 8],
|
| 464 |
+
],
|
| 465 |
+
dtype=torch.int32,
|
| 466 |
+
),
|
| 467 |
+
1,
|
| 468 |
+
),
|
| 469 |
+
# Decode span multiple pages:
|
| 470 |
+
# duplicated kv cache: 24, 25, 26
|
| 471 |
+
# decode locations: 27, 28, 29, 30, 31, 32
|
| 472 |
+
# We need 3 pages in total.
|
| 473 |
+
(
|
| 474 |
+
torch.tensor(
|
| 475 |
+
[
|
| 476 |
+
[27, 28, 29, 30, 31, 32],
|
| 477 |
+
[35, 36, 37, 38, 39, 40],
|
| 478 |
+
],
|
| 479 |
+
dtype=torch.int32,
|
| 480 |
+
),
|
| 481 |
+
torch.tensor(
|
| 482 |
+
[
|
| 483 |
+
[6, 7, 8, 0, 0, 0],
|
| 484 |
+
[8, 9, 10, 0, 0, 0],
|
| 485 |
+
],
|
| 486 |
+
dtype=torch.int32,
|
| 487 |
+
),
|
| 488 |
+
5,
|
| 489 |
+
),
|
| 490 |
+
]
|
| 491 |
+
|
| 492 |
+
last_page_lens = torch.tensor([3], dtype=torch.int32)
|
| 493 |
+
for cache_loc, expected_page_table, decode_length in cases:
|
| 494 |
+
cache_seqlens_int32 = torch.zeros(bs * topk, dtype=torch.int32)
|
| 495 |
+
page_table = torch.zeros_like(cache_loc, dtype=torch.int32)
|
| 496 |
+
draft_decode_set_expand_metadata(
|
| 497 |
+
cache_seqlens_int32=cache_seqlens_int32,
|
| 498 |
+
page_table=page_table,
|
| 499 |
+
last_page_lens=last_page_lens,
|
| 500 |
+
decode_length=decode_length,
|
| 501 |
+
cache_loc=cache_loc,
|
| 502 |
+
topk=topk,
|
| 503 |
+
page_size=page_size,
|
| 504 |
+
)
|
| 505 |
+
|
| 506 |
+
expected_cache_seqlens = torch.tensor(
|
| 507 |
+
[decode_length + 3, decode_length + 3], dtype=torch.int32
|
| 508 |
+
)
|
| 509 |
+
self.assertTrue(torch.equal(cache_seqlens_int32, expected_cache_seqlens))
|
| 510 |
+
self.assertTrue(torch.equal(page_table, expected_page_table))
|
| 511 |
+
|
| 512 |
+
def test_draft_decode_set_expand_metadata_page_crossing(self):
|
| 513 |
+
"""
|
| 514 |
+
Regression for fa3 EAGLE draft decode with topk > 1 and page_size > 1.
|
| 515 |
+
cache_loc arrives num_steps-wide; callers pre-slice it to `decode_length`
|
| 516 |
+
(the live draft tokens) before this helper runs, so the dedup'd scatter
|
| 517 |
+
never writes past the (decode_length + 1)-wide expand page_table row even
|
| 518 |
+
when consecutive draft tokens land on distinct pages.
|
| 519 |
+
"""
|
| 520 |
+
bs, topk, page_size = 1, 2, 4
|
| 521 |
+
decode_length = 2
|
| 522 |
+
last_page_lens = torch.tensor([3], dtype=torch.int32)
|
| 523 |
+
# 2 live draft tokens per (batch, topk) crossing into distinct pages.
|
| 524 |
+
cache_loc = torch.tensor([[23, 28], [31, 36]], dtype=torch.int32)
|
| 525 |
+
cache_seqlens_int32 = torch.zeros(bs * topk, dtype=torch.int32)
|
| 526 |
+
# page_table is (decode_length + 1) wide (extra slot for the last partial
|
| 527 |
+
# page); the trailing column must stay zero.
|
| 528 |
+
page_table = torch.zeros(bs * topk, decode_length + 1, dtype=torch.int32)
|
| 529 |
+
draft_decode_set_expand_metadata(
|
| 530 |
+
cache_seqlens_int32=cache_seqlens_int32,
|
| 531 |
+
page_table=page_table,
|
| 532 |
+
last_page_lens=last_page_lens,
|
| 533 |
+
decode_length=decode_length,
|
| 534 |
+
cache_loc=cache_loc,
|
| 535 |
+
topk=topk,
|
| 536 |
+
page_size=page_size,
|
| 537 |
+
)
|
| 538 |
+
expected_page_table = torch.tensor([[5, 7, 0], [7, 9, 0]], dtype=torch.int32)
|
| 539 |
+
expected_cache_seqlens = torch.tensor([5, 5], dtype=torch.int32)
|
| 540 |
+
self.assertTrue(torch.equal(page_table, expected_page_table))
|
| 541 |
+
self.assertTrue(torch.equal(cache_seqlens_int32, expected_cache_seqlens))
|
| 542 |
+
|
| 543 |
+
def test_update_draft_decode_set_expand_metadata_multi_batch(self):
|
| 544 |
+
"""
|
| 545 |
+
Ensure expand metadata works when batch size > 1 and last pages differ.
|
| 546 |
+
"""
|
| 547 |
+
bs, topk, decode_length, page_size = 3, 2, 3, 4
|
| 548 |
+
cache_loc = torch.tensor(
|
| 549 |
+
[
|
| 550 |
+
# First batch: last page duplicate is 1, consecutive pages
|
| 551 |
+
[1, 2, 3, 4],
|
| 552 |
+
[6, 7, 8, 9],
|
| 553 |
+
# Second batch: last page duplicate is 3, non-consecutive pages
|
| 554 |
+
[3, 8, 9, 10],
|
| 555 |
+
[14, 15, 16, 17],
|
| 556 |
+
# Third batch: last page duplicate is 0, consecutive pages
|
| 557 |
+
[0, 1, 2, 3],
|
| 558 |
+
[4, 5, 6, 7],
|
| 559 |
+
],
|
| 560 |
+
dtype=torch.int32,
|
| 561 |
+
)
|
| 562 |
+
cache_seqlens_int32 = torch.zeros(bs * topk, dtype=torch.int32)
|
| 563 |
+
last_page_lens = torch.tensor([1, 3, 0], dtype=torch.int32)
|
| 564 |
+
page_table = torch.zeros_like(cache_loc, dtype=torch.int32)
|
| 565 |
+
draft_decode_set_expand_metadata(
|
| 566 |
+
cache_seqlens_int32=cache_seqlens_int32,
|
| 567 |
+
page_table=page_table,
|
| 568 |
+
last_page_lens=last_page_lens,
|
| 569 |
+
decode_length=decode_length,
|
| 570 |
+
cache_loc=cache_loc,
|
| 571 |
+
topk=topk,
|
| 572 |
+
page_size=page_size,
|
| 573 |
+
)
|
| 574 |
+
|
| 575 |
+
expected_cache_seqlens = torch.tensor([4, 4, 6, 6, 3, 3], dtype=torch.int32)
|
| 576 |
+
expected_page_table = torch.tensor(
|
| 577 |
+
[
|
| 578 |
+
[0, 1, 0, 0],
|
| 579 |
+
[1, 2, 0, 0],
|
| 580 |
+
[0, 2, 0, 0],
|
| 581 |
+
[3, 4, 0, 0],
|
| 582 |
+
[0, 0, 0, 0],
|
| 583 |
+
[1, 0, 0, 0],
|
| 584 |
+
],
|
| 585 |
+
dtype=torch.int32,
|
| 586 |
+
)
|
| 587 |
+
self.assertTrue(torch.equal(cache_seqlens_int32, expected_cache_seqlens))
|
| 588 |
+
self.assertTrue(torch.equal(page_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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import unittest
|
| 2 |
+
|
| 3 |
+
import torch
|
| 4 |
+
|
| 5 |
+
from sglang.srt.configs.model_config import AttentionArch
|
| 6 |
+
from sglang.srt.layers.attention.flashattention_backend import FlashAttentionBackend
|
| 7 |
+
from sglang.srt.layers.attention.torch_native_backend import TorchNativeAttnBackend
|
| 8 |
+
from sglang.srt.layers.radix_attention import RadixAttention
|
| 9 |
+
from sglang.srt.mem_cache.memory_pool import MLATokenToKVPool
|
| 10 |
+
from sglang.srt.model_executor.forward_batch_info import ForwardBatch, ForwardMode
|
| 11 |
+
from sglang.srt.model_executor.forward_context import (
|
| 12 |
+
ForwardContext,
|
| 13 |
+
set_forward_context,
|
| 14 |
+
)
|
| 15 |
+
from sglang.test.test_utils import CustomTestCase
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
class MockModelRunner:
|
| 19 |
+
def __init__(
|
| 20 |
+
self,
|
| 21 |
+
kv_lora_rank,
|
| 22 |
+
qk_rope_head_dim,
|
| 23 |
+
):
|
| 24 |
+
attention_arch = AttentionArch.MLA
|
| 25 |
+
self.device = "cuda"
|
| 26 |
+
self.dtype = torch.float16
|
| 27 |
+
self.is_hybrid_swa = False
|
| 28 |
+
context_len = 2048
|
| 29 |
+
self.model_config = type(
|
| 30 |
+
"ModelConfig",
|
| 31 |
+
(),
|
| 32 |
+
{
|
| 33 |
+
"context_len": context_len,
|
| 34 |
+
"attention_arch": attention_arch,
|
| 35 |
+
"is_encoder_decoder": False,
|
| 36 |
+
"is_local_attention_model": False,
|
| 37 |
+
},
|
| 38 |
+
)
|
| 39 |
+
self.sliding_window_size = None
|
| 40 |
+
# Add server_args attribute
|
| 41 |
+
self.server_args = type(
|
| 42 |
+
"ServerArgs",
|
| 43 |
+
(),
|
| 44 |
+
{
|
| 45 |
+
"kv_cache_dtype": torch.float16,
|
| 46 |
+
"speculative_eagle_topk": None,
|
| 47 |
+
"speculative_num_draft_tokens": 0,
|
| 48 |
+
"enable_deterministic_inference": False,
|
| 49 |
+
},
|
| 50 |
+
)
|
| 51 |
+
self.kv_cache_dtype = self.server_args.kv_cache_dtype
|
| 52 |
+
|
| 53 |
+
batch_size = 160
|
| 54 |
+
# Create a proper req_to_token_pool with the req_to_token attribute
|
| 55 |
+
self.req_to_token_pool = type(
|
| 56 |
+
"TokenPool",
|
| 57 |
+
(),
|
| 58 |
+
{
|
| 59 |
+
# A typical max_bs * max_context_len for cuda graph decode
|
| 60 |
+
"size": batch_size,
|
| 61 |
+
# Add req_to_token attribute
|
| 62 |
+
"req_to_token": torch.zeros(
|
| 63 |
+
batch_size, context_len, dtype=torch.int32, device=self.device
|
| 64 |
+
),
|
| 65 |
+
},
|
| 66 |
+
)
|
| 67 |
+
self.page_size = 1
|
| 68 |
+
max_total_num_tokens = batch_size * context_len
|
| 69 |
+
self.token_to_kv_pool = MLATokenToKVPool(
|
| 70 |
+
size=max_total_num_tokens,
|
| 71 |
+
page_size=self.page_size,
|
| 72 |
+
dtype=self.kv_cache_dtype,
|
| 73 |
+
kv_lora_rank=kv_lora_rank,
|
| 74 |
+
qk_rope_head_dim=qk_rope_head_dim,
|
| 75 |
+
layer_num=1, # only consider layer=1 for unit test
|
| 76 |
+
device=self.device,
|
| 77 |
+
enable_memory_saver=False,
|
| 78 |
+
)
|
| 79 |
+
self.hisparse_coordinator = None
|
| 80 |
+
|
| 81 |
+
|
| 82 |
+
class MockReqToTokenPool:
|
| 83 |
+
def __init__(self, batch_size, seq_len, device):
|
| 84 |
+
self.req_to_token = (
|
| 85 |
+
torch.arange(batch_size * seq_len, device=device)
|
| 86 |
+
.reshape(batch_size, seq_len)
|
| 87 |
+
.to(torch.int32)
|
| 88 |
+
)
|
| 89 |
+
|
| 90 |
+
|
| 91 |
+
@unittest.skipIf(not torch.cuda.is_available(), "Test requires CUDA")
|
| 92 |
+
class TestFlashAttentionMLABackend(CustomTestCase):
|
| 93 |
+
def setUp(self):
|
| 94 |
+
# MLA with different V headdim requires Hopper architecture (compute capability >= 9.0)
|
| 95 |
+
if torch.cuda.is_available():
|
| 96 |
+
compute_capability = torch.cuda.get_device_capability()
|
| 97 |
+
if compute_capability[0] < 9:
|
| 98 |
+
self.skipTest(
|
| 99 |
+
f"MLA requires Hopper GPU (compute capability >= 9.0), "
|
| 100 |
+
f"but found compute capability {compute_capability[0]}.{compute_capability[1]}"
|
| 101 |
+
)
|
| 102 |
+
|
| 103 |
+
# Test parameters
|
| 104 |
+
self.batch_size = 2
|
| 105 |
+
self.seq_len = 360
|
| 106 |
+
self.num_heads = 2
|
| 107 |
+
self.device = "cuda"
|
| 108 |
+
self.dtype = torch.float16
|
| 109 |
+
self.kv_lora_rank = 512
|
| 110 |
+
self.q_lora_rank = 128
|
| 111 |
+
self.qk_rope_head_dim = 64
|
| 112 |
+
self.qk_head_dim = self.qk_rope_head_dim + self.kv_lora_rank
|
| 113 |
+
# Assume no rope scaling
|
| 114 |
+
self.scaling = self.qk_head_dim**-0.5
|
| 115 |
+
# Initialize model runner and backend
|
| 116 |
+
self._init_model_runner()
|
| 117 |
+
self.backend = FlashAttentionBackend(self.model_runner)
|
| 118 |
+
self.ref_backend = TorchNativeAttnBackend(self.model_runner)
|
| 119 |
+
self.num_local_heads = 2
|
| 120 |
+
# Publish the backend so RadixAttention.forward resolves correctly.
|
| 121 |
+
set_forward_context(ForwardContext(attn_backend=self.backend))
|
| 122 |
+
|
| 123 |
+
def _init_model_runner(self):
|
| 124 |
+
self.model_runner = MockModelRunner(
|
| 125 |
+
kv_lora_rank=self.kv_lora_rank,
|
| 126 |
+
qk_rope_head_dim=self.qk_rope_head_dim,
|
| 127 |
+
)
|
| 128 |
+
|
| 129 |
+
def _create_attention_layer(self):
|
| 130 |
+
"""Create attention layer for testing."""
|
| 131 |
+
self.attn_mqa = RadixAttention(
|
| 132 |
+
num_heads=self.num_local_heads,
|
| 133 |
+
head_dim=self.kv_lora_rank + self.qk_rope_head_dim,
|
| 134 |
+
scaling=self.scaling,
|
| 135 |
+
num_kv_heads=1,
|
| 136 |
+
layer_id=0,
|
| 137 |
+
v_head_dim=self.kv_lora_rank,
|
| 138 |
+
prefix="attn_mqa",
|
| 139 |
+
)
|
| 140 |
+
return self.attn_mqa
|
| 141 |
+
|
| 142 |
+
def _run_reference_forward(
|
| 143 |
+
self, mode, q, k, v, layer, forward_batch, expected_shape
|
| 144 |
+
):
|
| 145 |
+
"""Run reference forward pass using native backend."""
|
| 146 |
+
if mode == ForwardMode.EXTEND:
|
| 147 |
+
output = self.ref_backend.forward_extend(q, k, v, layer, forward_batch)
|
| 148 |
+
else: # ForwardMode.DECODE
|
| 149 |
+
output = self.ref_backend.forward_decode(q, k, v, layer, forward_batch)
|
| 150 |
+
return output.view(expected_shape)
|
| 151 |
+
|
| 152 |
+
def _verify_output(self, output, expected_shape):
|
| 153 |
+
"""Verify output tensor shape, dtype, and values."""
|
| 154 |
+
self.assertEqual(
|
| 155 |
+
output.shape,
|
| 156 |
+
expected_shape,
|
| 157 |
+
f"Expected shape {expected_shape}, got {output.shape}",
|
| 158 |
+
)
|
| 159 |
+
self.assertEqual(output.dtype, self.dtype)
|
| 160 |
+
self.assertEqual(output.device.type, "cuda")
|
| 161 |
+
self.assertEqual(
|
| 162 |
+
torch.isnan(output).sum().item(), 0, "Output contains NaN values"
|
| 163 |
+
)
|
| 164 |
+
|
| 165 |
+
def _create_forward_batch(self, mode, q_len=None, prefix_len=0):
|
| 166 |
+
"""Create a forward batch for testing based on mode and lengths."""
|
| 167 |
+
# Default to self.seq_len if not specified
|
| 168 |
+
q_len = q_len or self.seq_len
|
| 169 |
+
|
| 170 |
+
if mode == ForwardMode.EXTEND:
|
| 171 |
+
total_len = prefix_len + q_len
|
| 172 |
+
out_cache_start = prefix_len * self.batch_size
|
| 173 |
+
out_cache_end = total_len * self.batch_size
|
| 174 |
+
|
| 175 |
+
forward_batch = ForwardBatch(
|
| 176 |
+
batch_size=self.batch_size,
|
| 177 |
+
input_ids=torch.randint(
|
| 178 |
+
0, 100, (self.batch_size, q_len), device=self.device
|
| 179 |
+
),
|
| 180 |
+
out_cache_loc=torch.arange(
|
| 181 |
+
out_cache_start, out_cache_end, device=self.device
|
| 182 |
+
),
|
| 183 |
+
seq_lens_sum=self.batch_size * total_len,
|
| 184 |
+
forward_mode=mode,
|
| 185 |
+
req_pool_indices=torch.arange(self.batch_size, device=self.device),
|
| 186 |
+
seq_lens=torch.tensor(
|
| 187 |
+
[total_len] * self.batch_size, device=self.device
|
| 188 |
+
),
|
| 189 |
+
seq_lens_cpu=torch.tensor([total_len] * self.batch_size, device="cpu"),
|
| 190 |
+
extend_prefix_lens=torch.tensor(
|
| 191 |
+
[prefix_len] * self.batch_size, device=self.device
|
| 192 |
+
),
|
| 193 |
+
extend_prefix_lens_cpu=torch.tensor(
|
| 194 |
+
[prefix_len] * self.batch_size, device="cpu"
|
| 195 |
+
),
|
| 196 |
+
extend_seq_lens=torch.tensor(
|
| 197 |
+
[q_len] * self.batch_size, device=self.device
|
| 198 |
+
),
|
| 199 |
+
extend_seq_lens_cpu=torch.tensor(
|
| 200 |
+
[q_len] * self.batch_size, device="cpu"
|
| 201 |
+
),
|
| 202 |
+
)
|
| 203 |
+
|
| 204 |
+
else: # ForwardMode.DECODE
|
| 205 |
+
decode_len = q_len # typically 1 for decode mode
|
| 206 |
+
total_len = self.seq_len + decode_len
|
| 207 |
+
out_cache_start = self.batch_size * self.seq_len
|
| 208 |
+
out_cache_end = self.batch_size * total_len
|
| 209 |
+
|
| 210 |
+
forward_batch = ForwardBatch(
|
| 211 |
+
batch_size=self.batch_size,
|
| 212 |
+
input_ids=torch.randint(
|
| 213 |
+
0, 100, (self.batch_size, decode_len), device=self.device
|
| 214 |
+
),
|
| 215 |
+
out_cache_loc=torch.arange(
|
| 216 |
+
out_cache_start, out_cache_end, device=self.device
|
| 217 |
+
),
|
| 218 |
+
seq_lens_sum=self.batch_size * total_len,
|
| 219 |
+
forward_mode=mode,
|
| 220 |
+
req_pool_indices=torch.arange(self.batch_size, device=self.device),
|
| 221 |
+
seq_lens=torch.tensor(
|
| 222 |
+
[total_len] * self.batch_size, device=self.device
|
| 223 |
+
),
|
| 224 |
+
seq_lens_cpu=torch.tensor([total_len] * self.batch_size, device="cpu"),
|
| 225 |
+
)
|
| 226 |
+
|
| 227 |
+
# Pool refs are resolved via the active ForwardContext (published in
|
| 228 |
+
# setUp); the fixture no longer needs to attach them to forward_batch.
|
| 229 |
+
return forward_batch
|
| 230 |
+
|
| 231 |
+
def _setup_kv_cache(self, forward_batch, layer, cache_len):
|
| 232 |
+
"""Set up KV cache with prefix tokens."""
|
| 233 |
+
if cache_len <= 0:
|
| 234 |
+
return
|
| 235 |
+
|
| 236 |
+
# For MLA, create separate nope and rope caches
|
| 237 |
+
cache_k_nope = torch.ones(
|
| 238 |
+
self.batch_size * cache_len,
|
| 239 |
+
1, # latent cache has only one head in MQA
|
| 240 |
+
self.kv_lora_rank,
|
| 241 |
+
dtype=self.dtype,
|
| 242 |
+
device=self.device,
|
| 243 |
+
)
|
| 244 |
+
|
| 245 |
+
cache_k_rope = torch.ones(
|
| 246 |
+
self.batch_size * cache_len,
|
| 247 |
+
1, # latent cache has only one head in MQA
|
| 248 |
+
self.qk_rope_head_dim,
|
| 249 |
+
dtype=self.dtype,
|
| 250 |
+
device=self.device,
|
| 251 |
+
)
|
| 252 |
+
|
| 253 |
+
# Set the prefix KV cache using MLA-specific method
|
| 254 |
+
self.model_runner.token_to_kv_pool.set_mla_kv_buffer(
|
| 255 |
+
layer,
|
| 256 |
+
torch.arange(self.batch_size * cache_len, device=self.device),
|
| 257 |
+
cache_k_nope,
|
| 258 |
+
cache_k_rope,
|
| 259 |
+
)
|
| 260 |
+
|
| 261 |
+
def _run_attention_test(self, mode, q_len, prefix_len=0):
|
| 262 |
+
"""
|
| 263 |
+
Run an attention test with the specified parameters.
|
| 264 |
+
Args:
|
| 265 |
+
mode: ForwardMode.EXTEND or ForwardMode.DECODE
|
| 266 |
+
q_len: Length of the query sequence. For decode mode, q_len is 1.
|
| 267 |
+
prefix_len: Length of the prefix sequence for extend mode
|
| 268 |
+
"""
|
| 269 |
+
layer = self._create_attention_layer()
|
| 270 |
+
|
| 271 |
+
# Create forward batch and set up
|
| 272 |
+
forward_batch = self._create_forward_batch(mode, q_len, prefix_len)
|
| 273 |
+
|
| 274 |
+
# Create q, kv_compressed for testing
|
| 275 |
+
q_shape = (self.batch_size * q_len, self.num_heads, self.qk_head_dim)
|
| 276 |
+
kv_shape = (self.batch_size * q_len, self.qk_head_dim)
|
| 277 |
+
q = torch.randn(q_shape, dtype=self.dtype, device=self.device)
|
| 278 |
+
kv_compressed = torch.randn(kv_shape, dtype=self.dtype, device=self.device)
|
| 279 |
+
|
| 280 |
+
# For MLA, split kv_compressed into k_nope and k_rope
|
| 281 |
+
# k_nope has dimension kv_lora_rank, k_rope has dimension qk_rope_head_dim
|
| 282 |
+
k_nope = kv_compressed[:, : self.kv_lora_rank]
|
| 283 |
+
k_rope = kv_compressed[:, self.kv_lora_rank :]
|
| 284 |
+
|
| 285 |
+
# k_nope needs to be unsqueezed for the num_heads dimension
|
| 286 |
+
k = k_nope.unsqueeze(1)
|
| 287 |
+
# k_rope also needs to be unsqueezed
|
| 288 |
+
k_rope = k_rope.unsqueeze(1)
|
| 289 |
+
|
| 290 |
+
# v is not used for mqa
|
| 291 |
+
v = torch.randn((1), dtype=self.dtype, device=self.device)
|
| 292 |
+
|
| 293 |
+
self._setup_kv_cache(forward_batch, layer, prefix_len)
|
| 294 |
+
|
| 295 |
+
self.backend.init_forward_metadata(forward_batch)
|
| 296 |
+
|
| 297 |
+
expected_shape = (
|
| 298 |
+
self.batch_size * q_len,
|
| 299 |
+
self.num_heads * self.kv_lora_rank,
|
| 300 |
+
)
|
| 301 |
+
|
| 302 |
+
if mode == ForwardMode.EXTEND:
|
| 303 |
+
output = self.backend.forward_extend(
|
| 304 |
+
q, k, v, layer, forward_batch, k_rope=k_rope
|
| 305 |
+
)
|
| 306 |
+
else:
|
| 307 |
+
output = self.backend.forward_decode(
|
| 308 |
+
q, k, v, layer, forward_batch, k_rope=k_rope
|
| 309 |
+
)
|
| 310 |
+
|
| 311 |
+
self._verify_output(output, expected_shape)
|
| 312 |
+
return output
|
| 313 |
+
|
| 314 |
+
def test_forward_extend(self):
|
| 315 |
+
"""Test the standard extend operation."""
|
| 316 |
+
self._run_attention_test(ForwardMode.EXTEND, q_len=self.seq_len)
|
| 317 |
+
|
| 318 |
+
def test_forward_decode(self):
|
| 319 |
+
"""Test the decode operation with cached tokens."""
|
| 320 |
+
self._run_attention_test(ForwardMode.DECODE, q_len=1)
|
| 321 |
+
|
| 322 |
+
def test_forward_extend_with_prefix(self):
|
| 323 |
+
"""Test extending from cached prefix tokens."""
|
| 324 |
+
prefix_len = self.seq_len // 2
|
| 325 |
+
extend_len = self.seq_len - prefix_len
|
| 326 |
+
self._run_attention_test(
|
| 327 |
+
ForwardMode.EXTEND, q_len=extend_len, prefix_len=prefix_len
|
| 328 |
+
)
|
| 329 |
+
|
| 330 |
+
|
| 331 |
+
if __name__ == "__main__":
|
| 332 |
+
unittest.main()
|
asian_ai/performance/SGLang/test/manual/attention/test_local_attn.py
ADDED
|
@@ -0,0 +1,74 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import unittest
|
| 3 |
+
from types import SimpleNamespace
|
| 4 |
+
|
| 5 |
+
import requests
|
| 6 |
+
|
| 7 |
+
from sglang.srt.utils import get_device_sm, kill_process_tree
|
| 8 |
+
from sglang.test.run_eval import run_eval
|
| 9 |
+
from sglang.test.test_utils import (
|
| 10 |
+
DEFAULT_MODEL_NAME_FOR_TEST_LOCAL_ATTENTION,
|
| 11 |
+
DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH,
|
| 12 |
+
DEFAULT_URL_FOR_TEST,
|
| 13 |
+
CustomTestCase,
|
| 14 |
+
popen_launch_server,
|
| 15 |
+
)
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
# Local attention with FA3 (requires SM 90+ / H100, tp=4)
|
| 19 |
+
@unittest.skipIf(get_device_sm() < 90, "Test requires CUDA SM 90 or higher")
|
| 20 |
+
class TestFlashAttention3LocalAttn(CustomTestCase):
|
| 21 |
+
model = DEFAULT_MODEL_NAME_FOR_TEST_LOCAL_ATTENTION
|
| 22 |
+
base_url = DEFAULT_URL_FOR_TEST
|
| 23 |
+
accuracy_threshold = 0.90
|
| 24 |
+
|
| 25 |
+
@classmethod
|
| 26 |
+
def get_server_args(cls):
|
| 27 |
+
return [
|
| 28 |
+
"--cuda-graph-max-bs-decode",
|
| 29 |
+
"2",
|
| 30 |
+
"--attention-backend",
|
| 31 |
+
"fa3",
|
| 32 |
+
"--tp",
|
| 33 |
+
"4",
|
| 34 |
+
"--context-length",
|
| 35 |
+
"1000000",
|
| 36 |
+
]
|
| 37 |
+
|
| 38 |
+
@classmethod
|
| 39 |
+
def setUpClass(cls):
|
| 40 |
+
cls.process = popen_launch_server(
|
| 41 |
+
cls.model,
|
| 42 |
+
cls.base_url,
|
| 43 |
+
timeout=DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH,
|
| 44 |
+
other_args=cls.get_server_args(),
|
| 45 |
+
env=os.environ,
|
| 46 |
+
)
|
| 47 |
+
|
| 48 |
+
@classmethod
|
| 49 |
+
def tearDownClass(cls):
|
| 50 |
+
kill_process_tree(cls.process.pid)
|
| 51 |
+
|
| 52 |
+
def test_gsm8k(self):
|
| 53 |
+
requests.get(self.base_url + "/flush_cache")
|
| 54 |
+
|
| 55 |
+
args = SimpleNamespace(
|
| 56 |
+
base_url=self.base_url,
|
| 57 |
+
model=self.model,
|
| 58 |
+
eval_name="gsm8k",
|
| 59 |
+
api="completion",
|
| 60 |
+
max_tokens=512,
|
| 61 |
+
num_examples=100,
|
| 62 |
+
num_threads=128,
|
| 63 |
+
num_shots=4,
|
| 64 |
+
)
|
| 65 |
+
metrics = run_eval(args)
|
| 66 |
+
print(f"{metrics=}")
|
| 67 |
+
|
| 68 |
+
# Use the appropriate metric key based on the test class
|
| 69 |
+
metric_key = "score"
|
| 70 |
+
self.assertGreater(metrics[metric_key], self.accuracy_threshold)
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
if __name__ == "__main__":
|
| 74 |
+
unittest.main()
|
asian_ai/performance/SGLang/test/manual/attention/test_prefix_chunk_info.py
ADDED
|
@@ -0,0 +1,238 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import unittest
|
| 2 |
+
|
| 3 |
+
import torch
|
| 4 |
+
|
| 5 |
+
from sglang.srt.mem_cache.memory_pool import MLATokenToKVPool
|
| 6 |
+
from sglang.srt.model_executor.forward_batch_info import ForwardBatch, ForwardMode
|
| 7 |
+
from sglang.srt.utils.common import get_device
|
| 8 |
+
from sglang.test.test_utils import CustomTestCase
|
| 9 |
+
|
| 10 |
+
TEST_CASES = [
|
| 11 |
+
# Sequence with same prefix lens
|
| 12 |
+
{
|
| 13 |
+
"batch_size": 3,
|
| 14 |
+
"prefix_lens": [64, 64, 64],
|
| 15 |
+
"max_chunk_capacity": 48,
|
| 16 |
+
"prefix_chunk_len": 16,
|
| 17 |
+
"num_prefix_chunks": 4,
|
| 18 |
+
"prefix_chunk_starts": torch.tensor(
|
| 19 |
+
[
|
| 20 |
+
[0, 0, 0],
|
| 21 |
+
[16, 16, 16],
|
| 22 |
+
[32, 32, 32],
|
| 23 |
+
[48, 48, 48],
|
| 24 |
+
],
|
| 25 |
+
dtype=torch.int32,
|
| 26 |
+
),
|
| 27 |
+
"prefix_chunk_seq_lens": torch.tensor(
|
| 28 |
+
[
|
| 29 |
+
[16, 16, 16],
|
| 30 |
+
[16, 16, 16],
|
| 31 |
+
[16, 16, 16],
|
| 32 |
+
[16, 16, 16],
|
| 33 |
+
],
|
| 34 |
+
dtype=torch.int32,
|
| 35 |
+
),
|
| 36 |
+
},
|
| 37 |
+
# Sequence with different prefix lens
|
| 38 |
+
{
|
| 39 |
+
"batch_size": 4,
|
| 40 |
+
"prefix_lens": [16, 32, 48, 64],
|
| 41 |
+
"max_chunk_capacity": 64,
|
| 42 |
+
"prefix_chunk_len": 16,
|
| 43 |
+
"num_prefix_chunks": 4,
|
| 44 |
+
"prefix_chunk_starts": torch.tensor(
|
| 45 |
+
[
|
| 46 |
+
[0, 0, 0, 0],
|
| 47 |
+
[16, 16, 16, 16],
|
| 48 |
+
[32, 32, 32, 32],
|
| 49 |
+
[48, 48, 48, 48],
|
| 50 |
+
],
|
| 51 |
+
dtype=torch.int32,
|
| 52 |
+
),
|
| 53 |
+
"prefix_chunk_seq_lens": torch.tensor(
|
| 54 |
+
[
|
| 55 |
+
[16, 16, 16, 16],
|
| 56 |
+
[0, 16, 16, 16],
|
| 57 |
+
[0, 0, 16, 16],
|
| 58 |
+
[0, 0, 0, 16],
|
| 59 |
+
],
|
| 60 |
+
dtype=torch.int32,
|
| 61 |
+
),
|
| 62 |
+
},
|
| 63 |
+
# Sequence with irregular shapes
|
| 64 |
+
{
|
| 65 |
+
"batch_size": 2,
|
| 66 |
+
"prefix_lens": [1, 64],
|
| 67 |
+
"max_chunk_capacity": 31,
|
| 68 |
+
"prefix_chunk_len": 15,
|
| 69 |
+
"num_prefix_chunks": 5,
|
| 70 |
+
"prefix_chunk_starts": torch.tensor(
|
| 71 |
+
[
|
| 72 |
+
[0, 0],
|
| 73 |
+
[15, 15],
|
| 74 |
+
[30, 30],
|
| 75 |
+
[45, 45],
|
| 76 |
+
[60, 60],
|
| 77 |
+
],
|
| 78 |
+
dtype=torch.int32,
|
| 79 |
+
),
|
| 80 |
+
"prefix_chunk_seq_lens": torch.tensor(
|
| 81 |
+
[
|
| 82 |
+
[1, 15],
|
| 83 |
+
[0, 15],
|
| 84 |
+
[0, 15],
|
| 85 |
+
[0, 15],
|
| 86 |
+
[0, 4],
|
| 87 |
+
],
|
| 88 |
+
dtype=torch.int32,
|
| 89 |
+
),
|
| 90 |
+
},
|
| 91 |
+
]
|
| 92 |
+
|
| 93 |
+
|
| 94 |
+
class MockForwardBatch(ForwardBatch):
|
| 95 |
+
def __init__(self, max_chunk_capacity: int, *args, **kwargs):
|
| 96 |
+
super().__init__(*args, **kwargs)
|
| 97 |
+
self.max_chunk_capacity = max_chunk_capacity
|
| 98 |
+
|
| 99 |
+
def get_max_chunk_capacity(self):
|
| 100 |
+
return self.max_chunk_capacity
|
| 101 |
+
|
| 102 |
+
|
| 103 |
+
class MockReqToTokenPool:
|
| 104 |
+
def __init__(self, batch_size, seq_len, device):
|
| 105 |
+
self.req_to_token = (
|
| 106 |
+
torch.arange(batch_size * seq_len, device=device)
|
| 107 |
+
.reshape(batch_size, seq_len)
|
| 108 |
+
.to(torch.int32)
|
| 109 |
+
)
|
| 110 |
+
|
| 111 |
+
|
| 112 |
+
# Test correctness of triton kernel for computing kv indices
|
| 113 |
+
def check_kv_indices(forward_batch, req_to_token_pool):
|
| 114 |
+
for i in range(forward_batch.num_prefix_chunks):
|
| 115 |
+
computed_kv_indices = forward_batch.prefix_chunk_kv_indices[i]
|
| 116 |
+
req_to_token = req_to_token_pool.req_to_token[: forward_batch.batch_size, :]
|
| 117 |
+
ref_kv_indices = torch.empty(
|
| 118 |
+
forward_batch.prefix_chunk_num_tokens[i],
|
| 119 |
+
dtype=torch.int32,
|
| 120 |
+
device=computed_kv_indices.device,
|
| 121 |
+
)
|
| 122 |
+
running_ptr = 0
|
| 123 |
+
for j in range(forward_batch.batch_size):
|
| 124 |
+
seq_start = forward_batch.prefix_chunk_starts[i, j].item()
|
| 125 |
+
seq_len = forward_batch.prefix_chunk_seq_lens[i, j].item()
|
| 126 |
+
ref_kv_indices[running_ptr : running_ptr + seq_len].copy_(
|
| 127 |
+
req_to_token[j, seq_start : seq_start + seq_len]
|
| 128 |
+
)
|
| 129 |
+
running_ptr += seq_len
|
| 130 |
+
assert torch.allclose(computed_kv_indices, ref_kv_indices)
|
| 131 |
+
|
| 132 |
+
|
| 133 |
+
@unittest.skipIf(
|
| 134 |
+
not (torch.cuda.is_available() or torch.xpu.is_available()),
|
| 135 |
+
"Test requires CUDA or XPU",
|
| 136 |
+
)
|
| 137 |
+
class TestPrefixChunkInfo(CustomTestCase):
|
| 138 |
+
def setUp(self):
|
| 139 |
+
# Common test parameters
|
| 140 |
+
self.num_local_heads = 128
|
| 141 |
+
self.kv_lora_rank = 512
|
| 142 |
+
self.qk_rope_head_dim = 64
|
| 143 |
+
self.device = get_device()
|
| 144 |
+
self.dtype = torch.bfloat16
|
| 145 |
+
self.extend_len = 64
|
| 146 |
+
self.max_bs = 4
|
| 147 |
+
self.max_seq_len = 128
|
| 148 |
+
|
| 149 |
+
# req_to_token_pool
|
| 150 |
+
self.req_to_token_pool = MockReqToTokenPool(
|
| 151 |
+
self.max_bs,
|
| 152 |
+
self.max_seq_len,
|
| 153 |
+
self.device,
|
| 154 |
+
)
|
| 155 |
+
|
| 156 |
+
# token_to_kv_pool
|
| 157 |
+
self.token_to_kv_pool = MLATokenToKVPool(
|
| 158 |
+
size=self.max_bs * self.max_seq_len,
|
| 159 |
+
page_size=1, # only consider page=1 for unit test
|
| 160 |
+
dtype=self.dtype,
|
| 161 |
+
kv_lora_rank=self.kv_lora_rank,
|
| 162 |
+
qk_rope_head_dim=self.qk_rope_head_dim,
|
| 163 |
+
layer_num=1, # only consider layer=1 for unit test
|
| 164 |
+
device=self.device,
|
| 165 |
+
enable_memory_saver=False,
|
| 166 |
+
)
|
| 167 |
+
|
| 168 |
+
def test_prefix_chunk_info(self):
|
| 169 |
+
"""Test the standard extend operation."""
|
| 170 |
+
|
| 171 |
+
for test_case in TEST_CASES:
|
| 172 |
+
print(
|
| 173 |
+
f"Test case with batch_size={test_case['batch_size']}, prefix_lens={test_case['prefix_lens']}, max_chunk_capacity={test_case['max_chunk_capacity']}"
|
| 174 |
+
)
|
| 175 |
+
batch_size = test_case["batch_size"]
|
| 176 |
+
prefix_lens_cpu = test_case["prefix_lens"]
|
| 177 |
+
assert len(prefix_lens_cpu) == batch_size
|
| 178 |
+
prefix_lens = torch.tensor(prefix_lens_cpu, device=self.device)
|
| 179 |
+
max_chunk_capacity = test_case["max_chunk_capacity"]
|
| 180 |
+
seq_lens_cpu = [
|
| 181 |
+
self.extend_len + prefix_lens_cpu[i] for i in range(batch_size)
|
| 182 |
+
]
|
| 183 |
+
seq_lens = torch.tensor(seq_lens_cpu, device=self.device)
|
| 184 |
+
|
| 185 |
+
# Create forward batch
|
| 186 |
+
# input_ids and out_cache_loc are dummy tensors in this test
|
| 187 |
+
forward_batch = MockForwardBatch(
|
| 188 |
+
max_chunk_capacity=max_chunk_capacity,
|
| 189 |
+
batch_size=batch_size,
|
| 190 |
+
input_ids=torch.randint(
|
| 191 |
+
0, 100, (batch_size, self.extend_len), device=self.device
|
| 192 |
+
),
|
| 193 |
+
out_cache_loc=torch.arange(
|
| 194 |
+
self.max_bs * self.max_seq_len - batch_size * self.extend_len,
|
| 195 |
+
self.max_bs * self.max_seq_len,
|
| 196 |
+
device=self.device,
|
| 197 |
+
),
|
| 198 |
+
seq_lens_sum=sum(seq_lens_cpu),
|
| 199 |
+
forward_mode=ForwardMode.EXTEND,
|
| 200 |
+
req_pool_indices=torch.arange(batch_size, device=self.device),
|
| 201 |
+
seq_lens=seq_lens,
|
| 202 |
+
seq_lens_cpu=seq_lens_cpu,
|
| 203 |
+
extend_prefix_lens=prefix_lens,
|
| 204 |
+
extend_prefix_lens_cpu=prefix_lens_cpu,
|
| 205 |
+
)
|
| 206 |
+
# Pool refs are resolved via the active ForwardContext; mock an
|
| 207 |
+
# attn_backend that carries the pools (Pattern A invariant).
|
| 208 |
+
from types import SimpleNamespace
|
| 209 |
+
|
| 210 |
+
from sglang.srt.model_executor.forward_context import (
|
| 211 |
+
ForwardContext,
|
| 212 |
+
set_forward_context,
|
| 213 |
+
)
|
| 214 |
+
|
| 215 |
+
mock_backend = SimpleNamespace(
|
| 216 |
+
req_to_token_pool=self.req_to_token_pool,
|
| 217 |
+
token_to_kv_pool=self.token_to_kv_pool,
|
| 218 |
+
)
|
| 219 |
+
set_forward_context(ForwardContext(attn_backend=mock_backend))
|
| 220 |
+
|
| 221 |
+
forward_batch.prepare_chunked_prefix_cache_info(self.device)
|
| 222 |
+
assert forward_batch.get_max_chunk_capacity() == max_chunk_capacity
|
| 223 |
+
assert forward_batch.prefix_chunk_len == test_case["prefix_chunk_len"]
|
| 224 |
+
assert forward_batch.num_prefix_chunks == test_case["num_prefix_chunks"]
|
| 225 |
+
assert torch.allclose(
|
| 226 |
+
forward_batch.prefix_chunk_starts,
|
| 227 |
+
test_case["prefix_chunk_starts"].to(self.device),
|
| 228 |
+
)
|
| 229 |
+
assert torch.allclose(
|
| 230 |
+
forward_batch.prefix_chunk_seq_lens,
|
| 231 |
+
test_case["prefix_chunk_seq_lens"].to(self.device),
|
| 232 |
+
)
|
| 233 |
+
|
| 234 |
+
check_kv_indices(forward_batch, self.req_to_token_pool)
|
| 235 |
+
|
| 236 |
+
|
| 237 |
+
if __name__ == "__main__":
|
| 238 |
+
unittest.main()
|
asian_ai/performance/SGLang/test/manual/attention/test_trtllm_mla_backend.py
ADDED
|
@@ -0,0 +1,1438 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import math
|
| 2 |
+
import unittest
|
| 3 |
+
from types import SimpleNamespace
|
| 4 |
+
|
| 5 |
+
import numpy as np
|
| 6 |
+
import torch
|
| 7 |
+
|
| 8 |
+
from sglang.srt.runtime_context import get_parallel
|
| 9 |
+
|
| 10 |
+
_parallel_override = get_parallel().override(attn_tp_size=1)
|
| 11 |
+
_parallel_override.__enter__()
|
| 12 |
+
|
| 13 |
+
from sglang.srt.configs.model_config import AttentionArch
|
| 14 |
+
from sglang.srt.layers.attention.flashinfer_mla_backend import FlashInferMLAAttnBackend
|
| 15 |
+
from sglang.srt.layers.attention.trtllm_mla_backend import (
|
| 16 |
+
TRTLLMMLABackend,
|
| 17 |
+
TRTLLMMLADecodeMetadata,
|
| 18 |
+
)
|
| 19 |
+
from sglang.srt.layers.attention.utils import get_num_page_per_block_flashmla
|
| 20 |
+
from sglang.srt.layers.radix_attention import RadixAttention
|
| 21 |
+
from sglang.srt.mem_cache.memory_pool import MLATokenToKVPool
|
| 22 |
+
from sglang.srt.model_executor.forward_batch_info import ForwardBatch, ForwardMode
|
| 23 |
+
from sglang.srt.model_executor.forward_context import (
|
| 24 |
+
ForwardContext,
|
| 25 |
+
set_forward_context,
|
| 26 |
+
)
|
| 27 |
+
from sglang.srt.server_args import (
|
| 28 |
+
ServerArgs,
|
| 29 |
+
get_global_server_args,
|
| 30 |
+
set_global_server_args_for_scheduler,
|
| 31 |
+
)
|
| 32 |
+
from sglang.srt.utils import is_flashinfer_available
|
| 33 |
+
from sglang.test.test_utils import CustomTestCase
|
| 34 |
+
|
| 35 |
+
# Global configuration for all tests
|
| 36 |
+
DEFAULT_CONFIG = {
|
| 37 |
+
"device": "cuda",
|
| 38 |
+
"dtype": torch.bfloat16,
|
| 39 |
+
"kv_cache_dtype": torch.bfloat16,
|
| 40 |
+
"context_len": 2048,
|
| 41 |
+
"max_bs": 64,
|
| 42 |
+
"tolerance": 1e-2,
|
| 43 |
+
"seed_cache": 42,
|
| 44 |
+
"seed_qkv": 123,
|
| 45 |
+
# MLA model config (TRTLLM MLA has fixed constraints)
|
| 46 |
+
"num_attention_heads": 128,
|
| 47 |
+
"kv_lora_rank": 512,
|
| 48 |
+
"qk_nope_head_dim": 128,
|
| 49 |
+
"qk_rope_head_dim": 64,
|
| 50 |
+
"v_head_dim": 512,
|
| 51 |
+
"num_kv_heads": 1,
|
| 52 |
+
"layer_id": 0,
|
| 53 |
+
"tp_q_head_num": 128,
|
| 54 |
+
"tp_k_head_num": 128,
|
| 55 |
+
"prefill_head_dim": 192,
|
| 56 |
+
"prefill_v_head_dim": 128,
|
| 57 |
+
}
|
| 58 |
+
|
| 59 |
+
ROPE_BASE = 10000
|
| 60 |
+
ROPE_SCALING_CONFIG = {
|
| 61 |
+
"beta_fast": 32,
|
| 62 |
+
"beta_slow": 1,
|
| 63 |
+
"factor": 40,
|
| 64 |
+
"mscale": 1.0,
|
| 65 |
+
"mscale_all_dim": 1.0,
|
| 66 |
+
"original_max_position_embeddings": 4096,
|
| 67 |
+
"type": "yarn",
|
| 68 |
+
"rope_type": "deepseek_yarn",
|
| 69 |
+
}
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
def build_rotary_emb(config, device=None):
|
| 73 |
+
from sglang.srt.layers.rotary_embedding import get_rope_wrapper
|
| 74 |
+
|
| 75 |
+
dev = device or config["device"]
|
| 76 |
+
rope_scaling = config.get("rope_scaling", ROPE_SCALING_CONFIG)
|
| 77 |
+
rotary = get_rope_wrapper(
|
| 78 |
+
head_size=config["qk_rope_head_dim"],
|
| 79 |
+
rotary_dim=config["qk_rope_head_dim"],
|
| 80 |
+
max_position=config["context_len"],
|
| 81 |
+
base=ROPE_BASE,
|
| 82 |
+
rope_scaling=rope_scaling,
|
| 83 |
+
is_neox_style=False,
|
| 84 |
+
device=dev,
|
| 85 |
+
)
|
| 86 |
+
rotary.cos_sin_cache = rotary.cos_sin_cache.to(dev)
|
| 87 |
+
return rotary
|
| 88 |
+
|
| 89 |
+
|
| 90 |
+
# Centralized test cases for different test scenarios
|
| 91 |
+
TEST_CASES = {
|
| 92 |
+
"basic_functionality": [
|
| 93 |
+
{
|
| 94 |
+
"name": "single",
|
| 95 |
+
"batch_size": 1,
|
| 96 |
+
"max_seq_len": 32,
|
| 97 |
+
"page_size": 32,
|
| 98 |
+
"description": "Minimal sanity check",
|
| 99 |
+
},
|
| 100 |
+
{
|
| 101 |
+
"name": "batch",
|
| 102 |
+
"batch_size": 32,
|
| 103 |
+
"max_seq_len": 128,
|
| 104 |
+
"page_size": 32,
|
| 105 |
+
"description": "Medium-scale batch",
|
| 106 |
+
},
|
| 107 |
+
],
|
| 108 |
+
"output_match": [
|
| 109 |
+
{
|
| 110 |
+
"name": "single_fp16",
|
| 111 |
+
"batch_size": 1,
|
| 112 |
+
"max_seq_len": 64,
|
| 113 |
+
"page_size": 32,
|
| 114 |
+
"description": "Single FP16 vs reference",
|
| 115 |
+
},
|
| 116 |
+
# {
|
| 117 |
+
# "name": "single_fp8",
|
| 118 |
+
# "batch_size": 1,
|
| 119 |
+
# "max_seq_len": 64,
|
| 120 |
+
# "page_size": 64,
|
| 121 |
+
# "tolerance": 1e-1,
|
| 122 |
+
# "kv_cache_dtype": torch.float8_e4m3fn,
|
| 123 |
+
# "description": "Single FP8 vs reference",
|
| 124 |
+
# },
|
| 125 |
+
{
|
| 126 |
+
"name": "batch_fp16",
|
| 127 |
+
"batch_size": 32,
|
| 128 |
+
"max_seq_len": 64,
|
| 129 |
+
"page_size": 32,
|
| 130 |
+
"description": "Batch FP16 vs reference",
|
| 131 |
+
},
|
| 132 |
+
# {
|
| 133 |
+
# "name": "batch_fp8",
|
| 134 |
+
# "batch_size": 32,
|
| 135 |
+
# "max_seq_len": 64,
|
| 136 |
+
# "page_size": 64,
|
| 137 |
+
# "tolerance": 1e-1,
|
| 138 |
+
# "kv_cache_dtype": torch.float8_e4m3fn,
|
| 139 |
+
# "description": "Batch FP8 vs reference",
|
| 140 |
+
# },
|
| 141 |
+
],
|
| 142 |
+
"page_size_consistency": [
|
| 143 |
+
# Only 32 and 64 supported for now in flashinfer TRTLLM-GEN MLA kernel
|
| 144 |
+
{
|
| 145 |
+
"name": "page_32",
|
| 146 |
+
"batch_size": 8,
|
| 147 |
+
"max_seq_len": 128,
|
| 148 |
+
"page_size": 32,
|
| 149 |
+
"description": "32-token pages",
|
| 150 |
+
},
|
| 151 |
+
{
|
| 152 |
+
"name": "page_64",
|
| 153 |
+
"batch_size": 8,
|
| 154 |
+
"max_seq_len": 128,
|
| 155 |
+
"page_size": 64,
|
| 156 |
+
"description": "64-token pages",
|
| 157 |
+
},
|
| 158 |
+
],
|
| 159 |
+
"shape_sanity_tests": [
|
| 160 |
+
{
|
| 161 |
+
"name": "basic",
|
| 162 |
+
"batch_size": 1,
|
| 163 |
+
"max_seq_len": 128,
|
| 164 |
+
"page_size": 32,
|
| 165 |
+
"description": "Single sequence",
|
| 166 |
+
},
|
| 167 |
+
{
|
| 168 |
+
"name": "basic_different_pagesize",
|
| 169 |
+
"batch_size": 1,
|
| 170 |
+
"max_seq_len": 128,
|
| 171 |
+
"page_size": 64,
|
| 172 |
+
"description": "Different page size",
|
| 173 |
+
},
|
| 174 |
+
{
|
| 175 |
+
"name": "batch",
|
| 176 |
+
"batch_size": 8,
|
| 177 |
+
"max_seq_len": 128,
|
| 178 |
+
"page_size": 32,
|
| 179 |
+
"description": "Batch shapes",
|
| 180 |
+
},
|
| 181 |
+
],
|
| 182 |
+
"metadata_tests": [
|
| 183 |
+
{
|
| 184 |
+
"name": "single_sequence",
|
| 185 |
+
"batch_size": 1,
|
| 186 |
+
"max_seq_len": 64,
|
| 187 |
+
"page_size": 32,
|
| 188 |
+
"description": "Single sequence metadata",
|
| 189 |
+
},
|
| 190 |
+
{
|
| 191 |
+
"name": "batch_mixed_lengths",
|
| 192 |
+
"batch_size": 8,
|
| 193 |
+
"max_seq_len": 128,
|
| 194 |
+
"page_size": 32,
|
| 195 |
+
"description": "Mixed sequence lengths",
|
| 196 |
+
},
|
| 197 |
+
{
|
| 198 |
+
"name": "large_batch",
|
| 199 |
+
"batch_size": 32,
|
| 200 |
+
"max_seq_len": 256,
|
| 201 |
+
"page_size": 64,
|
| 202 |
+
"description": "Large batch stress test",
|
| 203 |
+
},
|
| 204 |
+
{
|
| 205 |
+
"name": "edge_case_short",
|
| 206 |
+
"batch_size": 4,
|
| 207 |
+
"max_seq_len": 16,
|
| 208 |
+
"page_size": 32,
|
| 209 |
+
"description": "Sub-page sequences",
|
| 210 |
+
},
|
| 211 |
+
],
|
| 212 |
+
}
|
| 213 |
+
|
| 214 |
+
|
| 215 |
+
class MockModelRunner:
|
| 216 |
+
"""Minimal fake ModelRunner for testing MLA backends."""
|
| 217 |
+
|
| 218 |
+
def __init__(self, config):
|
| 219 |
+
self.device = config["device"]
|
| 220 |
+
self.dtype = config["dtype"]
|
| 221 |
+
self.kv_cache_dtype = config["kv_cache_dtype"]
|
| 222 |
+
self.page_size = config["page_size"]
|
| 223 |
+
|
| 224 |
+
# Server args stub - needed by attention backends
|
| 225 |
+
self.server_args = get_global_server_args()
|
| 226 |
+
|
| 227 |
+
# Model-config stub with MLA attributes
|
| 228 |
+
self.model_config = type(
|
| 229 |
+
"ModelConfig",
|
| 230 |
+
(),
|
| 231 |
+
{
|
| 232 |
+
"context_len": config["context_len"],
|
| 233 |
+
"attention_arch": AttentionArch.MLA,
|
| 234 |
+
"num_attention_heads": config["num_attention_heads"],
|
| 235 |
+
"kv_lora_rank": config["kv_lora_rank"],
|
| 236 |
+
"qk_nope_head_dim": config["qk_nope_head_dim"],
|
| 237 |
+
"qk_rope_head_dim": config["qk_rope_head_dim"],
|
| 238 |
+
"v_head_dim": config["v_head_dim"],
|
| 239 |
+
"scaling": 1.0
|
| 240 |
+
/ ((config["qk_nope_head_dim"] + config["qk_rope_head_dim"]) ** 0.5),
|
| 241 |
+
"get_num_kv_heads": staticmethod(lambda _: config["num_kv_heads"]),
|
| 242 |
+
},
|
| 243 |
+
)
|
| 244 |
+
|
| 245 |
+
# Req-to-token pool
|
| 246 |
+
max_bs = config["max_bs"]
|
| 247 |
+
max_ctx = self.model_config.context_len
|
| 248 |
+
req_to_token = torch.arange(
|
| 249 |
+
max_bs * max_ctx, dtype=torch.int32, device=self.device
|
| 250 |
+
).reshape(max_bs, max_ctx)
|
| 251 |
+
self.req_to_token_pool = type(
|
| 252 |
+
"TokenPool",
|
| 253 |
+
(),
|
| 254 |
+
{
|
| 255 |
+
"size": max_bs,
|
| 256 |
+
"req_to_token": req_to_token,
|
| 257 |
+
},
|
| 258 |
+
)
|
| 259 |
+
|
| 260 |
+
# KV-token pool (MLA)
|
| 261 |
+
self.token_to_kv_pool = MLATokenToKVPool(
|
| 262 |
+
size=max_bs * max_ctx,
|
| 263 |
+
page_size=config["page_size"],
|
| 264 |
+
dtype=self.kv_cache_dtype,
|
| 265 |
+
kv_lora_rank=config["kv_lora_rank"],
|
| 266 |
+
qk_rope_head_dim=config["qk_rope_head_dim"],
|
| 267 |
+
layer_num=1,
|
| 268 |
+
device=self.device,
|
| 269 |
+
enable_memory_saver=False,
|
| 270 |
+
)
|
| 271 |
+
self.hisparse_coordinator = None
|
| 272 |
+
|
| 273 |
+
|
| 274 |
+
def compare_outputs(trtllm_out, reference_out, tolerance=1e-2):
|
| 275 |
+
"""Compare outputs with detailed analysis."""
|
| 276 |
+
|
| 277 |
+
# Basic checks
|
| 278 |
+
assert (
|
| 279 |
+
trtllm_out.shape == reference_out.shape
|
| 280 |
+
), f"Shape mismatch: {trtllm_out.shape} vs {reference_out.shape}"
|
| 281 |
+
assert (
|
| 282 |
+
trtllm_out.dtype == reference_out.dtype
|
| 283 |
+
), f"Dtype mismatch: {trtllm_out.dtype} vs {reference_out.dtype}"
|
| 284 |
+
|
| 285 |
+
# Check for NaN/Inf
|
| 286 |
+
assert not torch.isnan(trtllm_out).any(), "TRTLLM output contains NaN"
|
| 287 |
+
assert not torch.isnan(reference_out).any(), "Reference output contains NaN"
|
| 288 |
+
assert not torch.isinf(trtllm_out).any(), "TRTLLM output contains Inf"
|
| 289 |
+
assert not torch.isinf(reference_out).any(), "Reference output contains Inf"
|
| 290 |
+
|
| 291 |
+
# Element-wise differences
|
| 292 |
+
diff = (trtllm_out - reference_out).abs()
|
| 293 |
+
max_diff = diff.max().item()
|
| 294 |
+
mean_diff = diff.mean().item()
|
| 295 |
+
|
| 296 |
+
# Check numerical equivalence
|
| 297 |
+
all_close = torch.allclose(
|
| 298 |
+
trtllm_out, reference_out, rtol=tolerance, atol=tolerance
|
| 299 |
+
)
|
| 300 |
+
|
| 301 |
+
if not all_close:
|
| 302 |
+
print(
|
| 303 |
+
f"Comparison failed: max_diff={max_diff:.6f}, mean_diff={mean_diff:.6f}, tolerance={tolerance}"
|
| 304 |
+
)
|
| 305 |
+
# Find top differences for debugging
|
| 306 |
+
flat_diff = diff.flatten()
|
| 307 |
+
top_diff_indices = torch.topk(flat_diff, k=min(5, flat_diff.numel())).indices
|
| 308 |
+
print("Top 5 differences:")
|
| 309 |
+
for i, idx in enumerate(top_diff_indices):
|
| 310 |
+
idx_tuple = np.unravel_index(idx.cpu().numpy(), trtllm_out.shape)
|
| 311 |
+
trt_val = trtllm_out[idx_tuple].item()
|
| 312 |
+
ref_val = reference_out[idx_tuple].item()
|
| 313 |
+
print(
|
| 314 |
+
f" [{idx_tuple}]: TRTLLM={trt_val:.6f}, Reference={ref_val:.6f}, diff={abs(trt_val-ref_val):.6f}"
|
| 315 |
+
)
|
| 316 |
+
|
| 317 |
+
return all_close
|
| 318 |
+
|
| 319 |
+
|
| 320 |
+
@unittest.skipIf(
|
| 321 |
+
not torch.cuda.is_available() or not is_flashinfer_available(),
|
| 322 |
+
"CUDA + flashinfer required",
|
| 323 |
+
)
|
| 324 |
+
class TestTRTLLMMLA(CustomTestCase):
|
| 325 |
+
"""Test suite for TRTLLM MLA backend with centralized configuration."""
|
| 326 |
+
|
| 327 |
+
@classmethod
|
| 328 |
+
def setUpClass(cls):
|
| 329 |
+
"""Set up global server args for testing."""
|
| 330 |
+
server_args = ServerArgs(model_path="dummy")
|
| 331 |
+
server_args.enable_dp_attention = False
|
| 332 |
+
set_global_server_args_for_scheduler(server_args)
|
| 333 |
+
|
| 334 |
+
@classmethod
|
| 335 |
+
def tearDownClass(cls):
|
| 336 |
+
pass
|
| 337 |
+
|
| 338 |
+
def _merge_config(self, test_case):
|
| 339 |
+
"""Merge test case with default configuration."""
|
| 340 |
+
config = DEFAULT_CONFIG.copy()
|
| 341 |
+
config.update(test_case)
|
| 342 |
+
return config
|
| 343 |
+
|
| 344 |
+
def _create_model_components(self, config, is_prefill=False):
|
| 345 |
+
"""Create model runners, backends, and layer for testing."""
|
| 346 |
+
# Create model runners
|
| 347 |
+
model_runner_trtllm = MockModelRunner(config)
|
| 348 |
+
model_runner_reference = MockModelRunner(config)
|
| 349 |
+
|
| 350 |
+
# Create backends
|
| 351 |
+
trtllm_backend = TRTLLMMLABackend(model_runner_trtllm)
|
| 352 |
+
reference_backend = FlashInferMLAAttnBackend(model_runner_reference)
|
| 353 |
+
|
| 354 |
+
head_dim = (
|
| 355 |
+
config["kv_lora_rank"] + config["qk_rope_head_dim"]
|
| 356 |
+
if not is_prefill
|
| 357 |
+
else config["prefill_head_dim"]
|
| 358 |
+
)
|
| 359 |
+
v_head_dim = (
|
| 360 |
+
config["v_head_dim"] if not is_prefill else config["prefill_v_head_dim"]
|
| 361 |
+
)
|
| 362 |
+
|
| 363 |
+
# Create RadixAttention layer
|
| 364 |
+
layer = RadixAttention(
|
| 365 |
+
num_heads=config["num_attention_heads"],
|
| 366 |
+
head_dim=head_dim,
|
| 367 |
+
scaling=model_runner_trtllm.model_config.scaling,
|
| 368 |
+
num_kv_heads=config["num_kv_heads"],
|
| 369 |
+
layer_id=config["layer_id"],
|
| 370 |
+
v_head_dim=v_head_dim,
|
| 371 |
+
prefix="attn_mqa",
|
| 372 |
+
)
|
| 373 |
+
|
| 374 |
+
return (
|
| 375 |
+
model_runner_trtllm,
|
| 376 |
+
model_runner_reference,
|
| 377 |
+
trtllm_backend,
|
| 378 |
+
reference_backend,
|
| 379 |
+
layer,
|
| 380 |
+
)
|
| 381 |
+
|
| 382 |
+
def _create_qkv_tensors(self, batch_size, config, dtype_override=None):
|
| 383 |
+
"""Create Q, K, V random tensors for given batch size with separate MLA components.
|
| 384 |
+
|
| 385 |
+
Args:
|
| 386 |
+
batch_size: Batch size.
|
| 387 |
+
config: Configuration dict with model dims and device.
|
| 388 |
+
dtype_override: Optional torch dtype to override config["dtype"].
|
| 389 |
+
|
| 390 |
+
Returns:
|
| 391 |
+
Tuple of (q_nope, q_rope, k_nope, k_rope, v, cos_sin_cache)
|
| 392 |
+
"""
|
| 393 |
+
device = config["device"]
|
| 394 |
+
target_dtype = dtype_override or config["dtype"]
|
| 395 |
+
|
| 396 |
+
# Create separate nope and rope components for Q
|
| 397 |
+
q_nope = torch.randn(
|
| 398 |
+
(batch_size, config["num_attention_heads"], config["kv_lora_rank"]),
|
| 399 |
+
dtype=config["dtype"],
|
| 400 |
+
device=device,
|
| 401 |
+
)
|
| 402 |
+
q_rope = torch.randn(
|
| 403 |
+
(batch_size, config["num_attention_heads"], config["qk_rope_head_dim"]),
|
| 404 |
+
dtype=config["dtype"],
|
| 405 |
+
device=device,
|
| 406 |
+
)
|
| 407 |
+
|
| 408 |
+
# Create separate nope and rope components for K
|
| 409 |
+
k_nope = torch.randn(
|
| 410 |
+
(batch_size, config["num_kv_heads"], config["kv_lora_rank"]),
|
| 411 |
+
dtype=config["dtype"],
|
| 412 |
+
device=device,
|
| 413 |
+
)
|
| 414 |
+
k_rope = torch.randn(
|
| 415 |
+
(batch_size, config["num_kv_heads"], config["qk_rope_head_dim"]),
|
| 416 |
+
dtype=config["dtype"],
|
| 417 |
+
device=device,
|
| 418 |
+
)
|
| 419 |
+
|
| 420 |
+
# V tensor (unchanged)
|
| 421 |
+
v = torch.randn(
|
| 422 |
+
(batch_size, config["num_kv_heads"], config["v_head_dim"]),
|
| 423 |
+
dtype=config["dtype"],
|
| 424 |
+
device=device,
|
| 425 |
+
)
|
| 426 |
+
|
| 427 |
+
return q_nope, q_rope, k_nope, k_rope, v
|
| 428 |
+
|
| 429 |
+
def _create_forward_batch(
|
| 430 |
+
self, batch_size, seq_lens, backend, model_runner, config
|
| 431 |
+
):
|
| 432 |
+
"""Create a forward batch for the given backend."""
|
| 433 |
+
fb = ForwardBatch(
|
| 434 |
+
batch_size=batch_size,
|
| 435 |
+
input_ids=torch.randint(0, 100, (batch_size, 1), device=config["device"]),
|
| 436 |
+
out_cache_loc=torch.arange(batch_size, device=config["device"]),
|
| 437 |
+
seq_lens_sum=int(seq_lens.sum().item()),
|
| 438 |
+
forward_mode=ForwardMode.DECODE,
|
| 439 |
+
req_pool_indices=torch.arange(batch_size, device=config["device"]),
|
| 440 |
+
seq_lens=seq_lens,
|
| 441 |
+
seq_lens_cpu=seq_lens.cpu(),
|
| 442 |
+
)
|
| 443 |
+
# Publish backend for RadixAttention dispatch.
|
| 444 |
+
set_forward_context(ForwardContext(attn_backend=backend))
|
| 445 |
+
|
| 446 |
+
# Add position information for RoPE
|
| 447 |
+
fb.positions = torch.arange(batch_size, device=config["device"])
|
| 448 |
+
|
| 449 |
+
return fb
|
| 450 |
+
|
| 451 |
+
def _populate_kv_cache(self, batch_size, seq_lens, model_runners, layer, config):
|
| 452 |
+
"""Populate KV cache with identical data for both backends."""
|
| 453 |
+
torch.manual_seed(config["seed_cache"]) # Fixed seed for reproducible cache
|
| 454 |
+
|
| 455 |
+
for model_runner in model_runners:
|
| 456 |
+
torch.manual_seed(config["seed_cache"]) # Reset seed for each backend
|
| 457 |
+
for i in range(batch_size):
|
| 458 |
+
seq_len = int(seq_lens[i].item())
|
| 459 |
+
for token_idx in range(seq_len - 1):
|
| 460 |
+
# Create random K components for MLA
|
| 461 |
+
cache_k_nope = torch.randn(
|
| 462 |
+
(1, config["kv_lora_rank"]),
|
| 463 |
+
dtype=config["dtype"],
|
| 464 |
+
device=config["device"],
|
| 465 |
+
)
|
| 466 |
+
cache_k_rope = torch.randn(
|
| 467 |
+
(1, config["qk_rope_head_dim"]),
|
| 468 |
+
dtype=config["dtype"],
|
| 469 |
+
device=config["device"],
|
| 470 |
+
)
|
| 471 |
+
|
| 472 |
+
# Calculate cache location
|
| 473 |
+
cache_loc = model_runner.req_to_token_pool.req_to_token[
|
| 474 |
+
i, token_idx
|
| 475 |
+
]
|
| 476 |
+
|
| 477 |
+
# Save to KV cache
|
| 478 |
+
model_runner.token_to_kv_pool.set_mla_kv_buffer(
|
| 479 |
+
layer,
|
| 480 |
+
cache_loc.unsqueeze(0),
|
| 481 |
+
cache_k_nope.squeeze(0),
|
| 482 |
+
cache_k_rope.squeeze(0),
|
| 483 |
+
)
|
| 484 |
+
|
| 485 |
+
def test_basic_functionality(self):
|
| 486 |
+
"""Test basic functionality with minimal setup."""
|
| 487 |
+
print(f"\nRunning basic functionality tests...")
|
| 488 |
+
|
| 489 |
+
for test_case in TEST_CASES["basic_functionality"]:
|
| 490 |
+
with self.subTest(test_case=test_case["name"]):
|
| 491 |
+
print(f" Testing {test_case['name']}: {test_case['description']}")
|
| 492 |
+
|
| 493 |
+
config = self._merge_config(test_case)
|
| 494 |
+
batch_size = config["batch_size"]
|
| 495 |
+
max_seq_len = config["max_seq_len"]
|
| 496 |
+
|
| 497 |
+
# Create components
|
| 498 |
+
model_runner_trtllm, _, trtllm_backend, _, layer = (
|
| 499 |
+
self._create_model_components(config)
|
| 500 |
+
)
|
| 501 |
+
|
| 502 |
+
# Create sequence lengths - properly handle different batch sizes
|
| 503 |
+
if batch_size == 2:
|
| 504 |
+
seq_lens = torch.tensor(
|
| 505 |
+
[max_seq_len, max_seq_len // 2], device=config["device"]
|
| 506 |
+
)
|
| 507 |
+
else:
|
| 508 |
+
# For larger batch sizes, create varied sequence lengths
|
| 509 |
+
torch.manual_seed(config["seed_cache"])
|
| 510 |
+
seq_lens = torch.randint(
|
| 511 |
+
max_seq_len // 2,
|
| 512 |
+
max_seq_len + 1,
|
| 513 |
+
(batch_size,),
|
| 514 |
+
device=config["device"],
|
| 515 |
+
)
|
| 516 |
+
seq_lens[0] = max_seq_len # Ensure at least one max length
|
| 517 |
+
|
| 518 |
+
# Create forward batch
|
| 519 |
+
fb = self._create_forward_batch(
|
| 520 |
+
batch_size, seq_lens, trtllm_backend, model_runner_trtllm, config
|
| 521 |
+
)
|
| 522 |
+
trtllm_backend.init_forward_metadata(fb)
|
| 523 |
+
|
| 524 |
+
# Populate KV cache
|
| 525 |
+
self._populate_kv_cache(
|
| 526 |
+
batch_size, seq_lens, [model_runner_trtllm], layer, config
|
| 527 |
+
)
|
| 528 |
+
|
| 529 |
+
# Create Q, K, V tensors with separate MLA components
|
| 530 |
+
torch.manual_seed(config["seed_qkv"])
|
| 531 |
+
q_nope, q_rope, k_nope, k_rope, v = self._create_qkv_tensors(
|
| 532 |
+
batch_size, config
|
| 533 |
+
)
|
| 534 |
+
|
| 535 |
+
# Run forward decode with separate MLA components
|
| 536 |
+
output = trtllm_backend.forward_decode(
|
| 537 |
+
q_nope, k_nope, None, layer, fb, q_rope=q_rope, k_rope=k_rope
|
| 538 |
+
)
|
| 539 |
+
|
| 540 |
+
# Basic checks
|
| 541 |
+
expected_shape = (
|
| 542 |
+
batch_size,
|
| 543 |
+
config["num_attention_heads"] * config["v_head_dim"],
|
| 544 |
+
)
|
| 545 |
+
self.assertEqual(output.shape, expected_shape)
|
| 546 |
+
self.assertEqual(output.dtype, config["dtype"])
|
| 547 |
+
self.assertFalse(torch.isnan(output).any())
|
| 548 |
+
self.assertFalse(torch.isinf(output).any())
|
| 549 |
+
|
| 550 |
+
def test_decode_output_match(self):
|
| 551 |
+
"""Test that TRTLLM and FlashInfer MLA backends produce matching outputs."""
|
| 552 |
+
print(f"\nRunning decode output matching tests...")
|
| 553 |
+
|
| 554 |
+
for test_case in TEST_CASES["output_match"]:
|
| 555 |
+
with self.subTest(test_case=test_case["name"]):
|
| 556 |
+
print(f" Testing {test_case['name']}: {test_case['description']}")
|
| 557 |
+
|
| 558 |
+
config = self._merge_config(test_case)
|
| 559 |
+
batch_size = config["batch_size"]
|
| 560 |
+
max_seq_len = config["max_seq_len"]
|
| 561 |
+
use_fp8 = config["kv_cache_dtype"] == torch.float8_e4m3fn
|
| 562 |
+
|
| 563 |
+
# Create components
|
| 564 |
+
(
|
| 565 |
+
model_runner_trtllm,
|
| 566 |
+
model_runner_reference,
|
| 567 |
+
trtllm_backend,
|
| 568 |
+
reference_backend,
|
| 569 |
+
layer,
|
| 570 |
+
) = self._create_model_components(config)
|
| 571 |
+
|
| 572 |
+
# Create identical sequence lengths for both backends
|
| 573 |
+
torch.manual_seed(config["seed_cache"])
|
| 574 |
+
seq_lens = torch.randint(
|
| 575 |
+
1, max_seq_len, (batch_size,), device=config["device"]
|
| 576 |
+
)
|
| 577 |
+
seq_lens[0] = max_seq_len # Ensure at least one max length
|
| 578 |
+
|
| 579 |
+
# Create forward batches with identical inputs
|
| 580 |
+
fb_trtllm = self._create_forward_batch(
|
| 581 |
+
batch_size,
|
| 582 |
+
seq_lens.clone(),
|
| 583 |
+
trtllm_backend,
|
| 584 |
+
model_runner_trtllm,
|
| 585 |
+
config,
|
| 586 |
+
)
|
| 587 |
+
fb_reference = self._create_forward_batch(
|
| 588 |
+
batch_size,
|
| 589 |
+
seq_lens.clone(),
|
| 590 |
+
reference_backend,
|
| 591 |
+
model_runner_reference,
|
| 592 |
+
config,
|
| 593 |
+
)
|
| 594 |
+
|
| 595 |
+
# Initialize metadata for both backends
|
| 596 |
+
trtllm_backend.init_forward_metadata(fb_trtllm)
|
| 597 |
+
reference_backend.init_forward_metadata(fb_reference)
|
| 598 |
+
|
| 599 |
+
# Populate both KV caches identically
|
| 600 |
+
self._populate_kv_cache(
|
| 601 |
+
batch_size,
|
| 602 |
+
seq_lens,
|
| 603 |
+
[model_runner_trtllm, model_runner_reference],
|
| 604 |
+
layer,
|
| 605 |
+
config,
|
| 606 |
+
)
|
| 607 |
+
|
| 608 |
+
# Create Q, K, V tensors for current decode step
|
| 609 |
+
torch.manual_seed(config["seed_qkv"])
|
| 610 |
+
|
| 611 |
+
q_nope_ref, q_rope_ref, k_nope_ref, k_rope_ref, v_ref = (
|
| 612 |
+
self._create_qkv_tensors(batch_size, config)
|
| 613 |
+
)
|
| 614 |
+
q_nope_trt, q_rope_trt, k_nope_trt, k_rope_trt, v_trt = (
|
| 615 |
+
q_nope_ref.clone(),
|
| 616 |
+
q_rope_ref.clone(),
|
| 617 |
+
k_nope_ref.clone(),
|
| 618 |
+
k_rope_ref.clone(),
|
| 619 |
+
v_ref.clone(),
|
| 620 |
+
)
|
| 621 |
+
tolerance = config["tolerance"]
|
| 622 |
+
|
| 623 |
+
extra_args = {}
|
| 624 |
+
if use_fp8:
|
| 625 |
+
# TRT kernel applies RoPE + FP8 quantization internally
|
| 626 |
+
# pre-apply RoPE on the reference (FlashInfer) path here so
|
| 627 |
+
# both paths share the same rope params/cache while keeping
|
| 628 |
+
# the TRT path unrotated.
|
| 629 |
+
rotary_emb = build_rotary_emb(config)
|
| 630 |
+
q_rope_ref, k_rope_ref = rotary_emb(
|
| 631 |
+
fb_reference.positions, q_rope_ref, k_rope_ref
|
| 632 |
+
)
|
| 633 |
+
extra_args = {
|
| 634 |
+
"cos_sin_cache": rotary_emb.cos_sin_cache,
|
| 635 |
+
"is_neox": rotary_emb.is_neox_style,
|
| 636 |
+
}
|
| 637 |
+
|
| 638 |
+
dtype = q_rope_ref.dtype
|
| 639 |
+
q_rope_ref = q_rope_ref.to(torch.float8_e4m3fn).to(dtype)
|
| 640 |
+
q_nope_ref = q_nope_ref.to(torch.float8_e4m3fn).to(dtype)
|
| 641 |
+
k_rope_ref = k_rope_ref.to(torch.float8_e4m3fn).to(dtype)
|
| 642 |
+
k_nope_ref = k_nope_ref.to(torch.float8_e4m3fn).to(dtype)
|
| 643 |
+
|
| 644 |
+
# Run forward decode on both backends
|
| 645 |
+
out_trtllm = trtllm_backend.forward_decode(
|
| 646 |
+
q_nope_trt,
|
| 647 |
+
k_nope_trt,
|
| 648 |
+
None,
|
| 649 |
+
layer,
|
| 650 |
+
fb_trtllm,
|
| 651 |
+
q_rope=q_rope_trt,
|
| 652 |
+
k_rope=k_rope_trt,
|
| 653 |
+
**extra_args,
|
| 654 |
+
)
|
| 655 |
+
|
| 656 |
+
# Reference backend should also take separate components, not concatenated
|
| 657 |
+
out_reference = reference_backend.forward_decode(
|
| 658 |
+
q_nope_ref,
|
| 659 |
+
k_nope_ref,
|
| 660 |
+
v_ref,
|
| 661 |
+
layer,
|
| 662 |
+
fb_reference,
|
| 663 |
+
q_rope=q_rope_ref,
|
| 664 |
+
k_rope=k_rope_ref,
|
| 665 |
+
)
|
| 666 |
+
|
| 667 |
+
# Compare outputs
|
| 668 |
+
comparison_passed = compare_outputs(
|
| 669 |
+
out_trtllm, out_reference, tolerance=tolerance
|
| 670 |
+
)
|
| 671 |
+
|
| 672 |
+
self.assertTrue(
|
| 673 |
+
comparison_passed,
|
| 674 |
+
f"TRTLLM and Reference outputs differ beyond tolerance. "
|
| 675 |
+
f"Config: {test_case['name']}, "
|
| 676 |
+
f"Max diff: {(out_trtllm - out_reference).abs().max().item()}",
|
| 677 |
+
)
|
| 678 |
+
|
| 679 |
+
def test_page_size_consistency(self):
|
| 680 |
+
"""Test output consistency across different page sizes."""
|
| 681 |
+
print(f"\nRunning page size consistency tests...")
|
| 682 |
+
|
| 683 |
+
for test_case in TEST_CASES["page_size_consistency"]:
|
| 684 |
+
with self.subTest(test_case=test_case["name"]):
|
| 685 |
+
print(f" Testing {test_case['name']}: {test_case['description']}")
|
| 686 |
+
|
| 687 |
+
config = self._merge_config(test_case)
|
| 688 |
+
batch_size = config["batch_size"]
|
| 689 |
+
max_seq_len = config["max_seq_len"]
|
| 690 |
+
|
| 691 |
+
# Create components
|
| 692 |
+
model_runner, _, backend, _, layer = self._create_model_components(
|
| 693 |
+
config
|
| 694 |
+
)
|
| 695 |
+
|
| 696 |
+
# Create sequence lengths
|
| 697 |
+
torch.manual_seed(config["seed_cache"])
|
| 698 |
+
seq_lens = torch.randint(
|
| 699 |
+
1, max_seq_len, (batch_size,), device=config["device"]
|
| 700 |
+
)
|
| 701 |
+
seq_lens[0] = max_seq_len
|
| 702 |
+
|
| 703 |
+
# Create forward batch
|
| 704 |
+
fb = self._create_forward_batch(
|
| 705 |
+
batch_size, seq_lens, backend, model_runner, config
|
| 706 |
+
)
|
| 707 |
+
backend.init_forward_metadata(fb)
|
| 708 |
+
|
| 709 |
+
# Populate KV cache
|
| 710 |
+
self._populate_kv_cache(
|
| 711 |
+
batch_size, seq_lens, [model_runner], layer, config
|
| 712 |
+
)
|
| 713 |
+
|
| 714 |
+
# Create Q, K, V tensors with separate MLA components
|
| 715 |
+
torch.manual_seed(config["seed_qkv"])
|
| 716 |
+
q_nope, q_rope, k_nope, k_rope, v = self._create_qkv_tensors(
|
| 717 |
+
batch_size, config
|
| 718 |
+
)
|
| 719 |
+
|
| 720 |
+
# Run forward decode with separate MLA components
|
| 721 |
+
output = backend.forward_decode(
|
| 722 |
+
q_nope, k_nope, None, layer, fb, q_rope=q_rope, k_rope=k_rope
|
| 723 |
+
)
|
| 724 |
+
|
| 725 |
+
expected_shape = (
|
| 726 |
+
batch_size,
|
| 727 |
+
config["num_attention_heads"] * config["v_head_dim"],
|
| 728 |
+
)
|
| 729 |
+
self.assertEqual(
|
| 730 |
+
output.shape,
|
| 731 |
+
expected_shape,
|
| 732 |
+
f"Output shape mismatch: {output.shape} vs {expected_shape}",
|
| 733 |
+
)
|
| 734 |
+
self.assertFalse(torch.isnan(output).any(), "Output contains NaN")
|
| 735 |
+
self.assertFalse(torch.isinf(output).any(), "Output contains Inf")
|
| 736 |
+
|
| 737 |
+
def test_shape_sanity(self):
|
| 738 |
+
"""Check decode shapes across several configurations."""
|
| 739 |
+
print(f"\nRunning shape sanity tests...")
|
| 740 |
+
|
| 741 |
+
for test_case in TEST_CASES["shape_sanity_tests"]:
|
| 742 |
+
with self.subTest(test_case=test_case["name"]):
|
| 743 |
+
print(f" Testing {test_case['name']}: {test_case['description']}")
|
| 744 |
+
|
| 745 |
+
config = self._merge_config(test_case)
|
| 746 |
+
batch_size = config["batch_size"]
|
| 747 |
+
max_seq_len = config["max_seq_len"]
|
| 748 |
+
|
| 749 |
+
model_runner, _, backend, _, layer = self._create_model_components(
|
| 750 |
+
config
|
| 751 |
+
)
|
| 752 |
+
|
| 753 |
+
# Random seq lens (ensure one matches max)
|
| 754 |
+
torch.manual_seed(config["seed_cache"])
|
| 755 |
+
seq_lens = torch.randint(
|
| 756 |
+
1, max_seq_len, (batch_size,), device=config["device"]
|
| 757 |
+
)
|
| 758 |
+
seq_lens[0] = max_seq_len
|
| 759 |
+
|
| 760 |
+
fb = self._create_forward_batch(
|
| 761 |
+
batch_size, seq_lens, backend, model_runner, config
|
| 762 |
+
)
|
| 763 |
+
backend.init_forward_metadata(fb)
|
| 764 |
+
|
| 765 |
+
# Create Q, K, V tensors with separate MLA components
|
| 766 |
+
torch.manual_seed(config["seed_qkv"])
|
| 767 |
+
q_nope = torch.randn(
|
| 768 |
+
(batch_size, config["num_attention_heads"], config["kv_lora_rank"]),
|
| 769 |
+
dtype=config["dtype"],
|
| 770 |
+
device=config["device"],
|
| 771 |
+
)
|
| 772 |
+
k_nope = torch.randn(
|
| 773 |
+
(batch_size, config["num_kv_heads"], config["kv_lora_rank"]),
|
| 774 |
+
dtype=config["dtype"],
|
| 775 |
+
device=config["device"],
|
| 776 |
+
)
|
| 777 |
+
q_rope = torch.randn(
|
| 778 |
+
(
|
| 779 |
+
batch_size,
|
| 780 |
+
config["num_attention_heads"],
|
| 781 |
+
config["qk_rope_head_dim"],
|
| 782 |
+
),
|
| 783 |
+
dtype=config["dtype"],
|
| 784 |
+
device=config["device"],
|
| 785 |
+
)
|
| 786 |
+
k_rope = torch.randn(
|
| 787 |
+
(batch_size, config["num_kv_heads"], config["qk_rope_head_dim"]),
|
| 788 |
+
dtype=config["dtype"],
|
| 789 |
+
device=config["device"],
|
| 790 |
+
)
|
| 791 |
+
v = None # Test with None v
|
| 792 |
+
|
| 793 |
+
# Run forward decode
|
| 794 |
+
output = backend.forward_decode(
|
| 795 |
+
q_nope, k_nope, v, layer, fb, q_rope=q_rope, k_rope=k_rope
|
| 796 |
+
)
|
| 797 |
+
|
| 798 |
+
# Shape and sanity checks
|
| 799 |
+
expected_shape = (
|
| 800 |
+
batch_size,
|
| 801 |
+
config["num_attention_heads"] * config["v_head_dim"],
|
| 802 |
+
)
|
| 803 |
+
self.assertEqual(
|
| 804 |
+
output.shape,
|
| 805 |
+
expected_shape,
|
| 806 |
+
f"Output shape mismatch for {test_case['name']}",
|
| 807 |
+
)
|
| 808 |
+
self.assertEqual(output.dtype, config["dtype"])
|
| 809 |
+
self.assertEqual(output.device.type, "cuda")
|
| 810 |
+
self.assertFalse(
|
| 811 |
+
torch.isnan(output).any(),
|
| 812 |
+
f"Output contains NaN for {test_case['name']}",
|
| 813 |
+
)
|
| 814 |
+
self.assertFalse(
|
| 815 |
+
torch.isinf(output).any(),
|
| 816 |
+
f"Output contains Inf for {test_case['name']}",
|
| 817 |
+
)
|
| 818 |
+
|
| 819 |
+
def test_metadata_initialization(self):
|
| 820 |
+
"""Test TRTLLM MLA metadata initialization and structure."""
|
| 821 |
+
print(f"\nRunning metadata initialization tests...")
|
| 822 |
+
|
| 823 |
+
for test_case in TEST_CASES["metadata_tests"]:
|
| 824 |
+
with self.subTest(test_case=test_case["name"]):
|
| 825 |
+
print(f" Testing {test_case['name']}: {test_case['description']}")
|
| 826 |
+
|
| 827 |
+
config = self._merge_config(test_case)
|
| 828 |
+
batch_size = config["batch_size"]
|
| 829 |
+
max_seq_len = config["max_seq_len"]
|
| 830 |
+
|
| 831 |
+
# Create components
|
| 832 |
+
model_runner, _, backend, _, layer = self._create_model_components(
|
| 833 |
+
config
|
| 834 |
+
)
|
| 835 |
+
|
| 836 |
+
# Create varied sequence lengths
|
| 837 |
+
torch.manual_seed(config["seed_cache"])
|
| 838 |
+
if batch_size == 1:
|
| 839 |
+
seq_lens = torch.tensor([max_seq_len], device=config["device"])
|
| 840 |
+
else:
|
| 841 |
+
seq_lens = torch.randint(
|
| 842 |
+
max(1, max_seq_len // 4),
|
| 843 |
+
max_seq_len + 1,
|
| 844 |
+
(batch_size,),
|
| 845 |
+
device=config["device"],
|
| 846 |
+
)
|
| 847 |
+
seq_lens[0] = max_seq_len # Ensure at least one max length
|
| 848 |
+
|
| 849 |
+
# Create forward batch
|
| 850 |
+
fb = self._create_forward_batch(
|
| 851 |
+
batch_size, seq_lens, backend, model_runner, config
|
| 852 |
+
)
|
| 853 |
+
|
| 854 |
+
# Initialize metadata
|
| 855 |
+
backend.init_forward_metadata(fb)
|
| 856 |
+
|
| 857 |
+
# Verify metadata exists
|
| 858 |
+
self.assertIsNotNone(backend.forward_decode_metadata)
|
| 859 |
+
self.assertIsInstance(
|
| 860 |
+
backend.forward_decode_metadata, TRTLLMMLADecodeMetadata
|
| 861 |
+
)
|
| 862 |
+
|
| 863 |
+
# Test metadata structure
|
| 864 |
+
metadata = backend.forward_decode_metadata
|
| 865 |
+
self.assertIsNotNone(
|
| 866 |
+
metadata.block_kv_indices, "Block KV indices should be created"
|
| 867 |
+
)
|
| 868 |
+
|
| 869 |
+
# Test block KV indices properties
|
| 870 |
+
self.assertEqual(metadata.block_kv_indices.device.type, "cuda")
|
| 871 |
+
self.assertEqual(metadata.block_kv_indices.dtype, torch.int32)
|
| 872 |
+
self.assertEqual(metadata.block_kv_indices.shape[0], batch_size)
|
| 873 |
+
|
| 874 |
+
# Verify block indices are valid (>= -1, since -1 is padding)
|
| 875 |
+
self.assertTrue(
|
| 876 |
+
(metadata.block_kv_indices >= -1).all(),
|
| 877 |
+
"All block indices should be >= -1 (with -1 as padding)",
|
| 878 |
+
)
|
| 879 |
+
|
| 880 |
+
def test_metadata_block_calculation(self):
|
| 881 |
+
"""Test block count calculation logic."""
|
| 882 |
+
print(f"\nRunning metadata block calculation tests...")
|
| 883 |
+
|
| 884 |
+
test_scenarios = [
|
| 885 |
+
{"seq_len": 31, "page_size": 32, "expected_min_blocks": 1},
|
| 886 |
+
{"seq_len": 32, "page_size": 32, "expected_min_blocks": 1},
|
| 887 |
+
{"seq_len": 33, "page_size": 32, "expected_min_blocks": 2},
|
| 888 |
+
{"seq_len": 128, "page_size": 32, "expected_min_blocks": 4},
|
| 889 |
+
{"seq_len": 128, "page_size": 64, "expected_min_blocks": 2},
|
| 890 |
+
]
|
| 891 |
+
|
| 892 |
+
for scenario in test_scenarios:
|
| 893 |
+
with self.subTest(scenario=scenario):
|
| 894 |
+
config = self._merge_config(
|
| 895 |
+
{
|
| 896 |
+
"batch_size": 1,
|
| 897 |
+
"max_seq_len": scenario["seq_len"],
|
| 898 |
+
"page_size": scenario["page_size"],
|
| 899 |
+
}
|
| 900 |
+
)
|
| 901 |
+
|
| 902 |
+
model_runner, _, backend, _, _ = self._create_model_components(config)
|
| 903 |
+
|
| 904 |
+
# Test internal block calculation
|
| 905 |
+
calculated_blocks = backend._calc_padded_blocks(scenario["seq_len"])
|
| 906 |
+
|
| 907 |
+
# Should be at least the minimum required
|
| 908 |
+
self.assertGreaterEqual(
|
| 909 |
+
calculated_blocks,
|
| 910 |
+
scenario["expected_min_blocks"],
|
| 911 |
+
f"Calculated blocks ({calculated_blocks}) should be >= minimum required ({scenario['expected_min_blocks']})",
|
| 912 |
+
)
|
| 913 |
+
|
| 914 |
+
# Should satisfy page_size constraint
|
| 915 |
+
total_tokens = calculated_blocks * scenario["page_size"]
|
| 916 |
+
self.assertGreaterEqual(
|
| 917 |
+
total_tokens,
|
| 918 |
+
scenario["seq_len"],
|
| 919 |
+
f"Total tokens ({total_tokens}) should cover sequence length ({scenario['seq_len']})",
|
| 920 |
+
)
|
| 921 |
+
|
| 922 |
+
# Should satisfy TRT-LLM and Triton constraints
|
| 923 |
+
trtllm_constraint = 128 // scenario["page_size"]
|
| 924 |
+
triton_constraint = get_num_page_per_block_flashmla(
|
| 925 |
+
scenario["page_size"]
|
| 926 |
+
)
|
| 927 |
+
constraint_lcm = math.lcm(trtllm_constraint, triton_constraint)
|
| 928 |
+
self.assertEqual(
|
| 929 |
+
calculated_blocks % constraint_lcm,
|
| 930 |
+
0,
|
| 931 |
+
f"Block count should be multiple of LCM of constraints ({constraint_lcm})",
|
| 932 |
+
)
|
| 933 |
+
|
| 934 |
+
def test_metadata_kv_indices_correctness(self):
|
| 935 |
+
"""Test KV indices creation and correctness."""
|
| 936 |
+
print(f"\nRunning KV indices correctness tests...")
|
| 937 |
+
|
| 938 |
+
for test_case in TEST_CASES["metadata_tests"][
|
| 939 |
+
:2
|
| 940 |
+
]: # Test subset for performance
|
| 941 |
+
with self.subTest(test_case=test_case["name"]):
|
| 942 |
+
print(f" Testing {test_case['name']}: {test_case['description']}")
|
| 943 |
+
|
| 944 |
+
config = self._merge_config(test_case)
|
| 945 |
+
batch_size = config["batch_size"]
|
| 946 |
+
max_seq_len = config["max_seq_len"]
|
| 947 |
+
|
| 948 |
+
model_runner, _, backend, _, layer = self._create_model_components(
|
| 949 |
+
config
|
| 950 |
+
)
|
| 951 |
+
|
| 952 |
+
# Create known sequence lengths
|
| 953 |
+
torch.manual_seed(config["seed_cache"])
|
| 954 |
+
if batch_size == 1:
|
| 955 |
+
seq_lens = torch.tensor([max_seq_len], device=config["device"])
|
| 956 |
+
else:
|
| 957 |
+
seq_lens = torch.randint(
|
| 958 |
+
max_seq_len // 2,
|
| 959 |
+
max_seq_len + 1,
|
| 960 |
+
(batch_size,),
|
| 961 |
+
device=config["device"],
|
| 962 |
+
)
|
| 963 |
+
|
| 964 |
+
fb = self._create_forward_batch(
|
| 965 |
+
batch_size, seq_lens, backend, model_runner, config
|
| 966 |
+
)
|
| 967 |
+
|
| 968 |
+
# Populate some KV cache to have valid indices
|
| 969 |
+
self._populate_kv_cache(
|
| 970 |
+
batch_size, seq_lens, [model_runner], layer, config
|
| 971 |
+
)
|
| 972 |
+
|
| 973 |
+
# Initialize metadata
|
| 974 |
+
backend.init_forward_metadata(fb)
|
| 975 |
+
metadata = backend.forward_decode_metadata
|
| 976 |
+
|
| 977 |
+
# Verify KV indices structure
|
| 978 |
+
block_kv_indices = metadata.block_kv_indices
|
| 979 |
+
|
| 980 |
+
for i in range(batch_size):
|
| 981 |
+
seq_len = seq_lens[i].item()
|
| 982 |
+
expected_blocks = backend._calc_padded_blocks(seq_len)
|
| 983 |
+
|
| 984 |
+
# Count valid (non -1) indices for this sequence
|
| 985 |
+
valid_indices = (block_kv_indices[i] >= 0).sum().item()
|
| 986 |
+
|
| 987 |
+
# Should have at least enough blocks for the sequence
|
| 988 |
+
min_required_blocks = (seq_len + config["page_size"] - 1) // config[
|
| 989 |
+
"page_size"
|
| 990 |
+
]
|
| 991 |
+
self.assertGreaterEqual(
|
| 992 |
+
valid_indices,
|
| 993 |
+
min_required_blocks,
|
| 994 |
+
f"Sequence {i} should have at least {min_required_blocks} valid blocks, got {valid_indices}",
|
| 995 |
+
)
|
| 996 |
+
|
| 997 |
+
# Verify indices are within valid range
|
| 998 |
+
valid_block_indices = block_kv_indices[i][block_kv_indices[i] >= 0]
|
| 999 |
+
if len(valid_block_indices) > 0:
|
| 1000 |
+
max_possible_blocks = (
|
| 1001 |
+
model_runner.token_to_kv_pool.size // config["page_size"]
|
| 1002 |
+
)
|
| 1003 |
+
self.assertTrue(
|
| 1004 |
+
(valid_block_indices < max_possible_blocks).all(),
|
| 1005 |
+
f"All block indices should be < {max_possible_blocks}",
|
| 1006 |
+
)
|
| 1007 |
+
|
| 1008 |
+
def test_metadata_cuda_graph_compatibility(self):
|
| 1009 |
+
"""Test metadata compatibility with CUDA graph capture/replay."""
|
| 1010 |
+
print(f"\nRunning CUDA graph compatibility tests...")
|
| 1011 |
+
|
| 1012 |
+
config = self._merge_config(
|
| 1013 |
+
{"batch_size": 4, "max_seq_len": 64, "page_size": 32}
|
| 1014 |
+
)
|
| 1015 |
+
|
| 1016 |
+
model_runner, _, backend, _, layer = self._create_model_components(config)
|
| 1017 |
+
batch_size = config["batch_size"]
|
| 1018 |
+
|
| 1019 |
+
# Initialize CUDA graph state
|
| 1020 |
+
backend.init_cuda_graph_state(
|
| 1021 |
+
max_bs=batch_size, max_num_tokens=config["max_seq_len"] * batch_size
|
| 1022 |
+
)
|
| 1023 |
+
|
| 1024 |
+
# Verify CUDA graph buffers are allocated
|
| 1025 |
+
self.assertIsNotNone(backend.decode_cuda_graph_kv_indices)
|
| 1026 |
+
|
| 1027 |
+
# Test capture metadata
|
| 1028 |
+
seq_lens = torch.full(
|
| 1029 |
+
(batch_size,), config["max_seq_len"], device=config["device"]
|
| 1030 |
+
)
|
| 1031 |
+
req_pool_indices = torch.arange(batch_size, device=config["device"])
|
| 1032 |
+
|
| 1033 |
+
capture_fb = SimpleNamespace(
|
| 1034 |
+
batch_size=batch_size,
|
| 1035 |
+
forward_mode=ForwardMode.DECODE,
|
| 1036 |
+
req_pool_indices=req_pool_indices,
|
| 1037 |
+
seq_lens=seq_lens,
|
| 1038 |
+
positions=torch.arange(batch_size, device=config["device"]),
|
| 1039 |
+
spec_info=None,
|
| 1040 |
+
)
|
| 1041 |
+
backend.init_forward_metadata_out_graph(capture_fb, in_capture=True)
|
| 1042 |
+
|
| 1043 |
+
# Verify capture metadata
|
| 1044 |
+
self.assertIn(batch_size, backend.decode_cuda_graph_metadata)
|
| 1045 |
+
capture_metadata = backend.decode_cuda_graph_metadata[batch_size]
|
| 1046 |
+
|
| 1047 |
+
self.assertIsNotNone(capture_metadata.block_kv_indices)
|
| 1048 |
+
|
| 1049 |
+
# Test replay with different sequence lengths
|
| 1050 |
+
new_seq_lens = torch.randint(
|
| 1051 |
+
config["max_seq_len"] // 2,
|
| 1052 |
+
config["max_seq_len"] + 1,
|
| 1053 |
+
(batch_size,),
|
| 1054 |
+
device=config["device"],
|
| 1055 |
+
)
|
| 1056 |
+
|
| 1057 |
+
replay_fb = SimpleNamespace(
|
| 1058 |
+
batch_size=batch_size,
|
| 1059 |
+
forward_mode=ForwardMode.DECODE,
|
| 1060 |
+
req_pool_indices=req_pool_indices,
|
| 1061 |
+
seq_lens=new_seq_lens,
|
| 1062 |
+
seq_lens_cpu=new_seq_lens.cpu(),
|
| 1063 |
+
spec_info=None,
|
| 1064 |
+
)
|
| 1065 |
+
backend.init_forward_metadata_out_graph(replay_fb)
|
| 1066 |
+
|
| 1067 |
+
# Verify replay updated the metadata
|
| 1068 |
+
replay_metadata = backend.forward_decode_metadata
|
| 1069 |
+
self.assertIsNotNone(replay_metadata)
|
| 1070 |
+
|
| 1071 |
+
def test_metadata_consistency_across_calls(self):
|
| 1072 |
+
"""Test metadata consistency across multiple forward calls."""
|
| 1073 |
+
print(f"\nRunning metadata consistency tests...")
|
| 1074 |
+
|
| 1075 |
+
config = self._merge_config(
|
| 1076 |
+
{"batch_size": 2, "max_seq_len": 64, "page_size": 32}
|
| 1077 |
+
)
|
| 1078 |
+
|
| 1079 |
+
model_runner, _, backend, _, layer = self._create_model_components(config)
|
| 1080 |
+
|
| 1081 |
+
# First call
|
| 1082 |
+
seq_lens_1 = torch.tensor([32, 48], device=config["device"])
|
| 1083 |
+
fb_1 = self._create_forward_batch(
|
| 1084 |
+
config["batch_size"], seq_lens_1, backend, model_runner, config
|
| 1085 |
+
)
|
| 1086 |
+
backend.init_forward_metadata(fb_1)
|
| 1087 |
+
metadata_1 = backend.forward_decode_metadata
|
| 1088 |
+
|
| 1089 |
+
# Second call with same sequence lengths
|
| 1090 |
+
seq_lens_2 = torch.tensor([32, 48], device=config["device"])
|
| 1091 |
+
fb_2 = self._create_forward_batch(
|
| 1092 |
+
config["batch_size"], seq_lens_2, backend, model_runner, config
|
| 1093 |
+
)
|
| 1094 |
+
backend.init_forward_metadata(fb_2)
|
| 1095 |
+
metadata_2 = backend.forward_decode_metadata
|
| 1096 |
+
|
| 1097 |
+
# Metadata structure should be consistent
|
| 1098 |
+
self.assertEqual(
|
| 1099 |
+
metadata_1.block_kv_indices.shape, metadata_2.block_kv_indices.shape
|
| 1100 |
+
)
|
| 1101 |
+
|
| 1102 |
+
# Third call with different sequence lengths
|
| 1103 |
+
seq_lens_3 = torch.tensor([16, 64], device=config["device"])
|
| 1104 |
+
fb_3 = self._create_forward_batch(
|
| 1105 |
+
config["batch_size"], seq_lens_3, backend, model_runner, config
|
| 1106 |
+
)
|
| 1107 |
+
backend.init_forward_metadata(fb_3)
|
| 1108 |
+
metadata_3 = backend.forward_decode_metadata
|
| 1109 |
+
|
| 1110 |
+
# Should still have valid structure
|
| 1111 |
+
self.assertIsNotNone(metadata_3.block_kv_indices)
|
| 1112 |
+
self.assertEqual(metadata_3.block_kv_indices.shape[0], config["batch_size"])
|
| 1113 |
+
|
| 1114 |
+
def test_prefill_output_match_self_attention(self):
|
| 1115 |
+
"""Test prefill (forward) behavior of TRTLLM MLA backend vs reference."""
|
| 1116 |
+
print(f"\nRunning prefill output tests...")
|
| 1117 |
+
|
| 1118 |
+
for test_case in TEST_CASES["output_match"][:2]: # Just a subset for speed
|
| 1119 |
+
with self.subTest(test_case=test_case["name"]):
|
| 1120 |
+
print(
|
| 1121 |
+
f"Prefill Testing {test_case['name']}: {test_case['description']}"
|
| 1122 |
+
)
|
| 1123 |
+
|
| 1124 |
+
config = self._merge_config(test_case)
|
| 1125 |
+
batch_size = config["batch_size"]
|
| 1126 |
+
max_seq_len = config["max_seq_len"]
|
| 1127 |
+
|
| 1128 |
+
# Create components
|
| 1129 |
+
(
|
| 1130 |
+
model_runner_trtllm,
|
| 1131 |
+
model_runner_reference,
|
| 1132 |
+
trtllm_backend,
|
| 1133 |
+
reference_backend,
|
| 1134 |
+
layer,
|
| 1135 |
+
) = self._create_model_components(config, is_prefill=True)
|
| 1136 |
+
|
| 1137 |
+
# Prefill uses full sequences
|
| 1138 |
+
seq_lens = torch.full(
|
| 1139 |
+
(batch_size,), max_seq_len, device=config["device"]
|
| 1140 |
+
)
|
| 1141 |
+
|
| 1142 |
+
def _create_forward_batch_prefill(
|
| 1143 |
+
batch_size,
|
| 1144 |
+
seq_lens,
|
| 1145 |
+
extend_prefix_lens,
|
| 1146 |
+
backend,
|
| 1147 |
+
model_runner,
|
| 1148 |
+
config,
|
| 1149 |
+
):
|
| 1150 |
+
"""Create a forward batch for the given backend."""
|
| 1151 |
+
|
| 1152 |
+
fb = ForwardBatch(
|
| 1153 |
+
batch_size=batch_size,
|
| 1154 |
+
input_ids=torch.randint(
|
| 1155 |
+
0, 100, (batch_size, 1), device=config["device"]
|
| 1156 |
+
),
|
| 1157 |
+
out_cache_loc=torch.arange(batch_size, device=config["device"]),
|
| 1158 |
+
seq_lens_sum=int(seq_lens.sum().item()),
|
| 1159 |
+
extend_prefix_lens=extend_prefix_lens,
|
| 1160 |
+
extend_prefix_lens_cpu=extend_prefix_lens.cpu().int().tolist(),
|
| 1161 |
+
extend_seq_lens_cpu=(seq_lens - extend_prefix_lens)
|
| 1162 |
+
.cpu()
|
| 1163 |
+
.int()
|
| 1164 |
+
.tolist(),
|
| 1165 |
+
forward_mode=ForwardMode.EXTEND,
|
| 1166 |
+
req_pool_indices=torch.arange(
|
| 1167 |
+
batch_size, device=config["device"]
|
| 1168 |
+
),
|
| 1169 |
+
seq_lens=seq_lens,
|
| 1170 |
+
seq_lens_cpu=seq_lens.cpu(),
|
| 1171 |
+
attn_attend_prefix_cache=False,
|
| 1172 |
+
mha_return_lse=False,
|
| 1173 |
+
)
|
| 1174 |
+
# Publish backend for RadixAttention dispatch.
|
| 1175 |
+
set_forward_context(ForwardContext(attn_backend=backend))
|
| 1176 |
+
|
| 1177 |
+
# Add position information for RoPE
|
| 1178 |
+
fb.positions = torch.arange(batch_size, device=config["device"])
|
| 1179 |
+
|
| 1180 |
+
return fb
|
| 1181 |
+
|
| 1182 |
+
# Create forward batches
|
| 1183 |
+
fb_trtllm = _create_forward_batch_prefill(
|
| 1184 |
+
batch_size,
|
| 1185 |
+
seq_lens.clone(),
|
| 1186 |
+
torch.zeros(batch_size, device=config["device"], dtype=torch.int32),
|
| 1187 |
+
trtllm_backend,
|
| 1188 |
+
model_runner_trtllm,
|
| 1189 |
+
config,
|
| 1190 |
+
)
|
| 1191 |
+
fb_reference = _create_forward_batch_prefill(
|
| 1192 |
+
batch_size,
|
| 1193 |
+
seq_lens.clone(),
|
| 1194 |
+
torch.zeros(batch_size, device=config["device"], dtype=torch.int32),
|
| 1195 |
+
reference_backend,
|
| 1196 |
+
model_runner_reference,
|
| 1197 |
+
config,
|
| 1198 |
+
)
|
| 1199 |
+
|
| 1200 |
+
# Initialize metadata for both backends
|
| 1201 |
+
trtllm_backend.init_forward_metadata(fb_trtllm)
|
| 1202 |
+
reference_backend.init_forward_metadata(fb_reference)
|
| 1203 |
+
|
| 1204 |
+
# Create Q, K, V tensors for prefill
|
| 1205 |
+
torch.manual_seed(config["seed_qkv"])
|
| 1206 |
+
|
| 1207 |
+
def _create_qkv_tensors_prefill(
|
| 1208 |
+
batch_size, seq_len, config, dtype_override=None
|
| 1209 |
+
):
|
| 1210 |
+
"""Create Q, K, V tensors for prefill, using config for head_num and head_dim."""
|
| 1211 |
+
device = config["device"]
|
| 1212 |
+
dtype = dtype_override or config["dtype"]
|
| 1213 |
+
|
| 1214 |
+
total_tokens = batch_size * seq_len
|
| 1215 |
+
|
| 1216 |
+
tp_q_head_num = config["tp_q_head_num"]
|
| 1217 |
+
tp_k_head_num = config["tp_k_head_num"]
|
| 1218 |
+
head_dim = config["prefill_head_dim"]
|
| 1219 |
+
v_head_dim = config["prefill_v_head_dim"]
|
| 1220 |
+
|
| 1221 |
+
q = torch.randn(
|
| 1222 |
+
(total_tokens, tp_q_head_num * head_dim),
|
| 1223 |
+
dtype=dtype,
|
| 1224 |
+
device=device,
|
| 1225 |
+
)
|
| 1226 |
+
k = torch.randn(
|
| 1227 |
+
(total_tokens, tp_k_head_num * head_dim),
|
| 1228 |
+
dtype=dtype,
|
| 1229 |
+
device=device,
|
| 1230 |
+
)
|
| 1231 |
+
v = torch.randn(
|
| 1232 |
+
(total_tokens, tp_k_head_num * v_head_dim),
|
| 1233 |
+
dtype=dtype,
|
| 1234 |
+
device=device,
|
| 1235 |
+
)
|
| 1236 |
+
|
| 1237 |
+
# Reshape as requested
|
| 1238 |
+
q = q.view(-1, tp_q_head_num, head_dim)
|
| 1239 |
+
k = k.view(-1, tp_k_head_num, head_dim)
|
| 1240 |
+
v = v.view(-1, tp_k_head_num, v_head_dim)
|
| 1241 |
+
|
| 1242 |
+
return q, k, v
|
| 1243 |
+
|
| 1244 |
+
q, k, v = _create_qkv_tensors_prefill(batch_size, max_seq_len, config)
|
| 1245 |
+
# Run prefill on both backends
|
| 1246 |
+
out_trtllm = trtllm_backend.forward_extend(
|
| 1247 |
+
q, k, v, layer, fb_trtllm, False
|
| 1248 |
+
).view(-1, layer.tp_q_head_num * layer.v_head_dim)
|
| 1249 |
+
out_reference = reference_backend.forward_extend(
|
| 1250 |
+
q, k, v, layer, fb_reference, False
|
| 1251 |
+
)
|
| 1252 |
+
|
| 1253 |
+
tolerance = config.get("tolerance", 1e-2)
|
| 1254 |
+
comparison_passed = compare_outputs(
|
| 1255 |
+
out_trtllm, out_reference, tolerance=tolerance
|
| 1256 |
+
)
|
| 1257 |
+
self.assertTrue(
|
| 1258 |
+
comparison_passed,
|
| 1259 |
+
f"TRTLLM and Reference prefill outputs differ beyond tolerance. "
|
| 1260 |
+
f"Config: {test_case['name']}, "
|
| 1261 |
+
f"Max diff: {(out_trtllm - out_reference).abs().max().item()}",
|
| 1262 |
+
)
|
| 1263 |
+
|
| 1264 |
+
def test_draft_extend_padding_unpadding_kernels(self):
|
| 1265 |
+
"""Test TRTLLM MLA Triton kernels: pad_draft_extend_query_kernel and unpad_draft_extend_output_kernel."""
|
| 1266 |
+
|
| 1267 |
+
# Import the kernels
|
| 1268 |
+
from sglang.srt.layers.attention.trtllm_mla_backend import (
|
| 1269 |
+
pad_draft_extend_query_kernel,
|
| 1270 |
+
unpad_draft_extend_output_kernel,
|
| 1271 |
+
)
|
| 1272 |
+
|
| 1273 |
+
def _create_test_data(
|
| 1274 |
+
self, batch_size, max_seq_len, num_heads, head_dim, dtype=torch.float32
|
| 1275 |
+
):
|
| 1276 |
+
"""Create test data for kernel testing."""
|
| 1277 |
+
device = torch.device("cuda")
|
| 1278 |
+
|
| 1279 |
+
# Create sequence lengths (varying lengths for each batch)
|
| 1280 |
+
seq_lens = torch.randint(
|
| 1281 |
+
1, max_seq_len + 1, (batch_size,), device=device, dtype=torch.int32
|
| 1282 |
+
)
|
| 1283 |
+
|
| 1284 |
+
# Create cumulative sequence lengths
|
| 1285 |
+
cum_seq_lens = torch.zeros(batch_size + 1, device=device, dtype=torch.int32)
|
| 1286 |
+
cum_seq_lens[1:] = torch.cumsum(seq_lens, dim=0)
|
| 1287 |
+
|
| 1288 |
+
# Create input query tensor (flattened format)
|
| 1289 |
+
total_tokens = cum_seq_lens[-1].item()
|
| 1290 |
+
q_input = torch.randn(
|
| 1291 |
+
total_tokens, num_heads, head_dim, device=device, dtype=dtype
|
| 1292 |
+
)
|
| 1293 |
+
|
| 1294 |
+
# Create padded query tensor (batch format)
|
| 1295 |
+
padded_q = torch.zeros(
|
| 1296 |
+
batch_size, max_seq_len, num_heads, head_dim, device=device, dtype=dtype
|
| 1297 |
+
)
|
| 1298 |
+
|
| 1299 |
+
return q_input, padded_q, seq_lens, cum_seq_lens
|
| 1300 |
+
|
| 1301 |
+
def _create_test_output_data(
|
| 1302 |
+
self,
|
| 1303 |
+
batch_size,
|
| 1304 |
+
token_per_batch,
|
| 1305 |
+
tp_q_head_num,
|
| 1306 |
+
v_head_dim,
|
| 1307 |
+
dtype=torch.float32,
|
| 1308 |
+
):
|
| 1309 |
+
"""Create test data for unpad kernel testing."""
|
| 1310 |
+
device = torch.device("cuda")
|
| 1311 |
+
|
| 1312 |
+
# Create accept lengths (varying lengths for each batch)
|
| 1313 |
+
num_accept_tokens_per_req = torch.randint(
|
| 1314 |
+
1, token_per_batch + 1, (batch_size,), device=device, dtype=torch.int32
|
| 1315 |
+
)
|
| 1316 |
+
|
| 1317 |
+
# Create cumulative accept lengths
|
| 1318 |
+
cum_accept_lengths = torch.zeros(
|
| 1319 |
+
batch_size + 1, device=device, dtype=torch.int32
|
| 1320 |
+
)
|
| 1321 |
+
cum_accept_lengths[1:] = torch.cumsum(num_accept_tokens_per_req, dim=0)
|
| 1322 |
+
|
| 1323 |
+
# Create raw output tensor (batch format)
|
| 1324 |
+
raw_out = torch.randn(
|
| 1325 |
+
batch_size,
|
| 1326 |
+
token_per_batch,
|
| 1327 |
+
tp_q_head_num,
|
| 1328 |
+
v_head_dim,
|
| 1329 |
+
device=device,
|
| 1330 |
+
dtype=dtype,
|
| 1331 |
+
)
|
| 1332 |
+
|
| 1333 |
+
# Create output tensor (flattened format)
|
| 1334 |
+
total_tokens = cum_accept_lengths[-1].item()
|
| 1335 |
+
output = torch.empty(
|
| 1336 |
+
total_tokens, tp_q_head_num, v_head_dim, device=device, dtype=dtype
|
| 1337 |
+
)
|
| 1338 |
+
|
| 1339 |
+
return raw_out, output, num_accept_tokens_per_req, cum_accept_lengths
|
| 1340 |
+
|
| 1341 |
+
# Test 1: pad_draft_extend_query_kernel basic functionality
|
| 1342 |
+
with self.subTest(test="pad_kernel_basic"):
|
| 1343 |
+
batch_size = 4
|
| 1344 |
+
max_seq_len = 8
|
| 1345 |
+
num_heads = 16
|
| 1346 |
+
head_dim = 64
|
| 1347 |
+
|
| 1348 |
+
q_input, padded_q, seq_lens, cum_seq_lens = _create_test_data(
|
| 1349 |
+
self, batch_size, max_seq_len, num_heads, head_dim
|
| 1350 |
+
)
|
| 1351 |
+
|
| 1352 |
+
# Launch kernel
|
| 1353 |
+
BLOCK_SIZE = 64
|
| 1354 |
+
grid = (batch_size * max_seq_len,)
|
| 1355 |
+
|
| 1356 |
+
pad_draft_extend_query_kernel[grid](
|
| 1357 |
+
q_ptr=q_input,
|
| 1358 |
+
padded_q_ptr=padded_q,
|
| 1359 |
+
seq_lens_q_ptr=seq_lens,
|
| 1360 |
+
cumsum_ptr=cum_seq_lens,
|
| 1361 |
+
batch_size=batch_size,
|
| 1362 |
+
max_seq_len=max_seq_len,
|
| 1363 |
+
num_heads=num_heads,
|
| 1364 |
+
head_dim=head_dim,
|
| 1365 |
+
BLOCK_SIZE=BLOCK_SIZE,
|
| 1366 |
+
)
|
| 1367 |
+
|
| 1368 |
+
# Verify the padding worked correctly
|
| 1369 |
+
for i in range(batch_size):
|
| 1370 |
+
seq_len = seq_lens[i].item()
|
| 1371 |
+
|
| 1372 |
+
# Check that valid positions are copied correctly
|
| 1373 |
+
for pos in range(seq_len):
|
| 1374 |
+
input_start = cum_seq_lens[i].item()
|
| 1375 |
+
input_pos = input_start + pos
|
| 1376 |
+
|
| 1377 |
+
# Compare input and output for valid positions
|
| 1378 |
+
input_data = q_input[input_pos]
|
| 1379 |
+
output_data = padded_q[i, pos]
|
| 1380 |
+
|
| 1381 |
+
torch.testing.assert_close(
|
| 1382 |
+
input_data, output_data, rtol=1e-5, atol=1e-6
|
| 1383 |
+
)
|
| 1384 |
+
|
| 1385 |
+
# Check that invalid positions are zero
|
| 1386 |
+
for pos in range(seq_len, max_seq_len):
|
| 1387 |
+
output_data = padded_q[i, pos]
|
| 1388 |
+
self.assertTrue(
|
| 1389 |
+
torch.allclose(output_data, torch.zeros_like(output_data)),
|
| 1390 |
+
f"Position {pos} in batch {i} should be zero",
|
| 1391 |
+
)
|
| 1392 |
+
|
| 1393 |
+
# Test 2: unpad_draft_extend_output_kernel basic functionality
|
| 1394 |
+
with self.subTest(test="unpad_kernel_basic"):
|
| 1395 |
+
batch_size = 4
|
| 1396 |
+
token_per_batch = 8
|
| 1397 |
+
tp_q_head_num = 16
|
| 1398 |
+
v_head_dim = 64
|
| 1399 |
+
|
| 1400 |
+
raw_out, output, num_accept_tokens_per_req, cum_accept_lengths = (
|
| 1401 |
+
_create_test_output_data(
|
| 1402 |
+
self, batch_size, token_per_batch, tp_q_head_num, v_head_dim
|
| 1403 |
+
)
|
| 1404 |
+
)
|
| 1405 |
+
|
| 1406 |
+
# Launch kernel
|
| 1407 |
+
BLOCK_SIZE = 64
|
| 1408 |
+
grid = (batch_size * token_per_batch,)
|
| 1409 |
+
|
| 1410 |
+
unpad_draft_extend_output_kernel[grid](
|
| 1411 |
+
raw_out_ptr=raw_out,
|
| 1412 |
+
output_ptr=output,
|
| 1413 |
+
num_accept_tokens_ptr=num_accept_tokens_per_req,
|
| 1414 |
+
cumsum_ptr=cum_accept_lengths,
|
| 1415 |
+
batch_size=batch_size,
|
| 1416 |
+
token_per_batch=token_per_batch,
|
| 1417 |
+
tp_q_head_num=tp_q_head_num,
|
| 1418 |
+
v_head_dim=v_head_dim,
|
| 1419 |
+
BLOCK_SIZE=BLOCK_SIZE,
|
| 1420 |
+
)
|
| 1421 |
+
|
| 1422 |
+
# Verify the unpadding worked correctly
|
| 1423 |
+
for i in range(batch_size):
|
| 1424 |
+
accept_len = num_accept_tokens_per_req[i].item()
|
| 1425 |
+
output_start = cum_accept_lengths[i].item()
|
| 1426 |
+
|
| 1427 |
+
# Check that valid positions are copied correctly
|
| 1428 |
+
for pos in range(accept_len):
|
| 1429 |
+
input_data = raw_out[i, pos]
|
| 1430 |
+
output_data = output[output_start + pos]
|
| 1431 |
+
|
| 1432 |
+
torch.testing.assert_close(
|
| 1433 |
+
input_data, output_data, rtol=1e-5, atol=1e-6
|
| 1434 |
+
)
|
| 1435 |
+
|
| 1436 |
+
|
| 1437 |
+
if __name__ == "__main__":
|
| 1438 |
+
unittest.main()
|
asian_ai/performance/SGLang/test/manual/chunked_prefill/__init__.py
ADDED
|
File without changes
|
asian_ai/performance/SGLang/test/manual/chunked_prefill/test_e2e_disagg.py
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import unittest
|
| 2 |
+
|
| 3 |
+
from sglang.test.chunked_prefill_test_utils import ChunkedTestPDBase
|
| 4 |
+
|
| 5 |
+
|
| 6 |
+
class TestChunkedFeatureDisagg(ChunkedTestPDBase):
|
| 7 |
+
__test__ = True
|
| 8 |
+
use_kv_canary = False
|
| 9 |
+
gsm8k_threshold = 0.50
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
if __name__ == "__main__":
|
| 13 |
+
unittest.main()
|
asian_ai/performance/SGLang/test/manual/chunked_prefill/test_e2e_dp_attention.py
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import unittest
|
| 2 |
+
|
| 3 |
+
from sglang.test.chunked_prefill_test_utils import ChunkedTestBase
|
| 4 |
+
from sglang.test.test_utils import DEFAULT_MLA_MODEL_NAME_FOR_TEST
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
class TestChunkedFeatureDPAttention(ChunkedTestBase):
|
| 8 |
+
__test__ = True
|
| 9 |
+
use_kv_canary = False
|
| 10 |
+
model = DEFAULT_MLA_MODEL_NAME_FOR_TEST
|
| 11 |
+
gsm8k_threshold = 0.50
|
| 12 |
+
feature_args = [
|
| 13 |
+
"--trust-remote-code",
|
| 14 |
+
"--tp",
|
| 15 |
+
"2",
|
| 16 |
+
"--enable-dp-attention",
|
| 17 |
+
"--dp",
|
| 18 |
+
"2",
|
| 19 |
+
]
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
if __name__ == "__main__":
|
| 23 |
+
unittest.main()
|
asian_ai/performance/SGLang/test/manual/chunked_prefill/test_e2e_hybrid_swa.py
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import unittest
|
| 2 |
+
|
| 3 |
+
from sglang.test.chunked_prefill_test_utils import (
|
| 4 |
+
LONG_PROMPT_NUM_SHOTS,
|
| 5 |
+
ChunkedTestBase,
|
| 6 |
+
)
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
class TestChunkedFeatureHybridSWA(ChunkedTestBase):
|
| 10 |
+
__test__ = True
|
| 11 |
+
model = "openai/gpt-oss-20b"
|
| 12 |
+
num_shots = LONG_PROMPT_NUM_SHOTS
|
| 13 |
+
gsm8k_threshold = 0.50
|
| 14 |
+
feature_args = [
|
| 15 |
+
"--mem-fraction-static",
|
| 16 |
+
"0.70",
|
| 17 |
+
"--disable-piecewise-cuda-graph",
|
| 18 |
+
]
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
if __name__ == "__main__":
|
| 22 |
+
unittest.main()
|
asian_ai/performance/SGLang/test/manual/chunked_prefill/test_e2e_lora.py
ADDED
|
@@ -0,0 +1,25 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import unittest
|
| 2 |
+
|
| 3 |
+
from sglang.test.chunked_prefill_test_utils import ChunkedTestBase
|
| 4 |
+
|
| 5 |
+
|
| 6 |
+
class TestChunkedFeatureLoRA(ChunkedTestBase):
|
| 7 |
+
__test__ = True
|
| 8 |
+
model = "meta-llama/Llama-3.2-1B-Instruct"
|
| 9 |
+
gsm8k_threshold = 0.20
|
| 10 |
+
feature_args = [
|
| 11 |
+
"--enable-lora",
|
| 12 |
+
"--lora-paths",
|
| 13 |
+
"nicoboss/Llama-3.2-1B-Instruct-Uncensored-Lora",
|
| 14 |
+
"codelion/Llama-3.2-1B-Instruct-tool-calling-lora",
|
| 15 |
+
"--max-loras-per-batch",
|
| 16 |
+
"2",
|
| 17 |
+
"--max-loaded-loras",
|
| 18 |
+
"4",
|
| 19 |
+
"--mem-fraction-static",
|
| 20 |
+
"0.75",
|
| 21 |
+
]
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
if __name__ == "__main__":
|
| 25 |
+
unittest.main()
|
asian_ai/performance/SGLang/test/manual/chunked_prefill/test_e2e_lora_overlap.py
ADDED
|
@@ -0,0 +1,26 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import unittest
|
| 2 |
+
|
| 3 |
+
from sglang.test.chunked_prefill_test_utils import ChunkedTestBase
|
| 4 |
+
|
| 5 |
+
|
| 6 |
+
class TestChunkedFeatureLoRAOverlap(ChunkedTestBase):
|
| 7 |
+
__test__ = True
|
| 8 |
+
model = "meta-llama/Llama-3.2-1B-Instruct"
|
| 9 |
+
gsm8k_threshold = 0.20
|
| 10 |
+
feature_args = [
|
| 11 |
+
"--enable-lora",
|
| 12 |
+
"--enable-lora-overlap-loading",
|
| 13 |
+
"--lora-paths",
|
| 14 |
+
"nicoboss/Llama-3.2-1B-Instruct-Uncensored-Lora",
|
| 15 |
+
"codelion/Llama-3.2-1B-Instruct-tool-calling-lora",
|
| 16 |
+
"--max-loras-per-batch",
|
| 17 |
+
"2",
|
| 18 |
+
"--max-loaded-loras",
|
| 19 |
+
"4",
|
| 20 |
+
"--mem-fraction-static",
|
| 21 |
+
"0.75",
|
| 22 |
+
]
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
if __name__ == "__main__":
|
| 26 |
+
unittest.main()
|
asian_ai/performance/SGLang/test/manual/chunked_prefill/test_e2e_page_size.py
ADDED
|
@@ -0,0 +1,18 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import unittest
|
| 2 |
+
|
| 3 |
+
from sglang.test.chunked_prefill_test_utils import ChunkedTestBase
|
| 4 |
+
from sglang.test.test_utils import DEFAULT_SMALL_MODEL_NAME_FOR_TEST
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
class TestChunkedFeaturePageSize(ChunkedTestBase):
|
| 8 |
+
__test__ = True
|
| 9 |
+
model = DEFAULT_SMALL_MODEL_NAME_FOR_TEST
|
| 10 |
+
gsm8k_threshold = 0.30
|
| 11 |
+
feature_args = [
|
| 12 |
+
"--page-size",
|
| 13 |
+
"16",
|
| 14 |
+
]
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
if __name__ == "__main__":
|
| 18 |
+
unittest.main()
|
asian_ai/performance/SGLang/test/manual/chunked_prefill/test_e2e_pd_pp.py
ADDED
|
@@ -0,0 +1,25 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import unittest
|
| 2 |
+
|
| 3 |
+
from sglang.test.chunked_prefill_test_utils import ChunkedTestPDBase
|
| 4 |
+
|
| 5 |
+
|
| 6 |
+
class TestChunkedFeaturePDPP(ChunkedTestPDBase):
|
| 7 |
+
__test__ = True
|
| 8 |
+
gsm8k_threshold = 0.50
|
| 9 |
+
feature_args = [
|
| 10 |
+
"--tp-size",
|
| 11 |
+
"2",
|
| 12 |
+
"--pp-size",
|
| 13 |
+
"2",
|
| 14 |
+
"--disable-overlap-schedule",
|
| 15 |
+
]
|
| 16 |
+
decode_feature_args = [
|
| 17 |
+
"--tp-size",
|
| 18 |
+
"2",
|
| 19 |
+
"--base-gpu-id",
|
| 20 |
+
"4",
|
| 21 |
+
]
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
if __name__ == "__main__":
|
| 25 |
+
unittest.main()
|
asian_ai/performance/SGLang/test/manual/chunked_prefill/test_e2e_piecewise_cuda_graph.py
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import unittest
|
| 2 |
+
|
| 3 |
+
from sglang.test.chunked_prefill_test_utils import ChunkedTestBase
|
| 4 |
+
from sglang.test.test_utils import DEFAULT_SMALL_MODEL_NAME_FOR_TEST
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
class TestChunkedFeaturePiecewiseCudaGraph(ChunkedTestBase):
|
| 8 |
+
__test__ = True
|
| 9 |
+
use_kv_canary = False
|
| 10 |
+
model = DEFAULT_SMALL_MODEL_NAME_FOR_TEST
|
| 11 |
+
gsm8k_threshold = 0.30
|
| 12 |
+
feature_args = []
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
if __name__ == "__main__":
|
| 16 |
+
unittest.main()
|
asian_ai/performance/SGLang/test/manual/chunked_prefill/test_e2e_pp.py
ADDED
|
@@ -0,0 +1,19 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import unittest
|
| 2 |
+
|
| 3 |
+
from sglang.test.chunked_prefill_test_utils import ChunkedTestBase
|
| 4 |
+
|
| 5 |
+
|
| 6 |
+
class TestChunkedFeaturePP(ChunkedTestBase):
|
| 7 |
+
__test__ = True
|
| 8 |
+
gsm8k_threshold = 0.50
|
| 9 |
+
feature_args = [
|
| 10 |
+
"--tp-size",
|
| 11 |
+
"2",
|
| 12 |
+
"--pp-size",
|
| 13 |
+
"2",
|
| 14 |
+
"--enable-dynamic-chunking",
|
| 15 |
+
]
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
if __name__ == "__main__":
|
| 19 |
+
unittest.main()
|
asian_ai/performance/SGLang/test/manual/chunked_prefill/test_e2e_priority.py
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import unittest
|
| 2 |
+
|
| 3 |
+
from sglang.test.chunked_prefill_test_utils import ChunkedTestBase
|
| 4 |
+
from sglang.test.test_utils import DEFAULT_SMALL_MODEL_NAME_FOR_TEST
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
class TestChunkedFeaturePriority(ChunkedTestBase):
|
| 8 |
+
__test__ = True
|
| 9 |
+
model = DEFAULT_SMALL_MODEL_NAME_FOR_TEST
|
| 10 |
+
gsm8k_threshold = 0.30
|
| 11 |
+
feature_args = [
|
| 12 |
+
"--enable-priority-scheduling",
|
| 13 |
+
"--max-running-requests",
|
| 14 |
+
"8",
|
| 15 |
+
"--max-queued-requests",
|
| 16 |
+
"128",
|
| 17 |
+
]
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
if __name__ == "__main__":
|
| 21 |
+
unittest.main()
|
asian_ai/performance/SGLang/test/manual/chunked_prefill/test_e2e_radix.py
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import unittest
|
| 2 |
+
|
| 3 |
+
from sglang.test.chunked_prefill_test_utils import ChunkedTestBase
|
| 4 |
+
from sglang.test.test_utils import DEFAULT_SMALL_MODEL_NAME_FOR_TEST
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
class TestChunkedFeatureRadix(ChunkedTestBase):
|
| 8 |
+
__test__ = True
|
| 9 |
+
model = DEFAULT_SMALL_MODEL_NAME_FOR_TEST
|
| 10 |
+
gsm8k_threshold = 0.30
|
| 11 |
+
feature_args = [
|
| 12 |
+
"--max-total-tokens",
|
| 13 |
+
"20000",
|
| 14 |
+
"--schedule-policy",
|
| 15 |
+
"fcfs",
|
| 16 |
+
]
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
if __name__ == "__main__":
|
| 20 |
+
unittest.main()
|
asian_ai/performance/SGLang/test/manual/chunked_prefill/test_e2e_spec.py
ADDED
|
@@ -0,0 +1,28 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import unittest
|
| 2 |
+
|
| 3 |
+
from sglang.test.chunked_prefill_test_utils import ChunkedTestBase
|
| 4 |
+
|
| 5 |
+
|
| 6 |
+
class TestChunkedFeatureSpec(ChunkedTestBase):
|
| 7 |
+
__test__ = True
|
| 8 |
+
use_kv_canary = False
|
| 9 |
+
model = "Qwen/Qwen3-8B"
|
| 10 |
+
gsm8k_threshold = 0.50
|
| 11 |
+
feature_args = [
|
| 12 |
+
"--speculative-algorithm",
|
| 13 |
+
"EAGLE3",
|
| 14 |
+
"--speculative-draft-model-path",
|
| 15 |
+
"Tengyunw/qwen3_8b_eagle3",
|
| 16 |
+
"--speculative-num-steps",
|
| 17 |
+
"5",
|
| 18 |
+
"--speculative-eagle-topk",
|
| 19 |
+
"8",
|
| 20 |
+
"--speculative-num-draft-tokens",
|
| 21 |
+
"64",
|
| 22 |
+
"--mem-fraction-static",
|
| 23 |
+
"0.7",
|
| 24 |
+
]
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
if __name__ == "__main__":
|
| 28 |
+
unittest.main()
|
asian_ai/performance/SGLang/test/manual/chunked_prefill/test_scripted_abort.py
ADDED
|
@@ -0,0 +1,643 @@
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import unittest
|
| 2 |
+
|
| 3 |
+
from sglang.srt.environ import envs
|
| 4 |
+
from sglang.test.scripted_runtime.context import ScriptedContext
|
| 5 |
+
from sglang.test.scripted_runtime.req_handle import ScriptedReqHandle
|
| 6 |
+
from sglang.test.scripted_runtime.test_case import ScriptedTestCase
|
| 7 |
+
from sglang.test.scripted_runtime_chunked_helpers import (
|
| 8 |
+
DEFAULT_CHUNK_SIZE,
|
| 9 |
+
DEFAULT_MAX_STEPS,
|
| 10 |
+
SMALL_KV_POOL_BALLAST_MAX_NEW_TOKENS,
|
| 11 |
+
SMALL_KV_POOL_BALLAST_PROMPT_LEN,
|
| 12 |
+
SMALL_KV_POOL_MAX_TOTAL_TOKENS,
|
| 13 |
+
VERY_LONG_PROMPT_LEN,
|
| 14 |
+
base_engine_kwargs,
|
| 15 |
+
run_until,
|
| 16 |
+
run_until_all_finished,
|
| 17 |
+
run_until_finished,
|
| 18 |
+
)
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
def _drain_until_released(t: ScriptedContext, *handles: ScriptedReqHandle):
|
| 22 |
+
for _ in range(12):
|
| 23 |
+
if all(
|
| 24 |
+
h.kv_pages == 0
|
| 25 |
+
and h.lock_refs == 0
|
| 26 |
+
and (h.req is None or h.req.req_pool_idx is None)
|
| 27 |
+
for h in handles
|
| 28 |
+
):
|
| 29 |
+
return
|
| 30 |
+
yield
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
class TestAbortBasic(ScriptedTestCase):
|
| 34 |
+
ENGINE_KWARGS = base_engine_kwargs(chunked_prefill_size=DEFAULT_CHUNK_SIZE)
|
| 35 |
+
|
| 36 |
+
def test_abort_waiting_chunked_resume(self):
|
| 37 |
+
self.server.execute_script(self._script_abort_waiting_chunked_resume)
|
| 38 |
+
|
| 39 |
+
@staticmethod
|
| 40 |
+
def _script_abort_waiting_chunked_resume(t: ScriptedContext):
|
| 41 |
+
r = t.start_req(
|
| 42 |
+
prompt_len=VERY_LONG_PROMPT_LEN, max_new_tokens=2, prompt_token=100
|
| 43 |
+
)
|
| 44 |
+
yield from run_until(r, lambda h: h.is_chunking)
|
| 45 |
+
|
| 46 |
+
pages_before = r.kv_pages
|
| 47 |
+
assert pages_before > 0, "chunked req should own KV pages mid-chunk"
|
| 48 |
+
|
| 49 |
+
t.abort(r)
|
| 50 |
+
yield from _drain_until_released(t, r)
|
| 51 |
+
|
| 52 |
+
assert r.status in (
|
| 53 |
+
"finished",
|
| 54 |
+
"unknown",
|
| 55 |
+
), f"after abort r should be finished/unknown, got {r.status}"
|
| 56 |
+
assert (
|
| 57 |
+
r.kv_pages == 0
|
| 58 |
+
), f"abort must release KV; r.kv_pages={r.kv_pages} after abort"
|
| 59 |
+
assert (
|
| 60 |
+
r.req is None or r.req.req_pool_idx is None
|
| 61 |
+
), f"abort must release row; r.req={r.req} after abort"
|
| 62 |
+
assert (
|
| 63 |
+
r.lock_refs == 0
|
| 64 |
+
), f"abort must release lock_refs; r.lock_refs={r.lock_refs}"
|
| 65 |
+
|
| 66 |
+
def test_abort_at_chunk_0(self):
|
| 67 |
+
self.server.execute_script(self._script_abort_at_chunk_0)
|
| 68 |
+
|
| 69 |
+
@staticmethod
|
| 70 |
+
def _script_abort_at_chunk_0(t: ScriptedContext):
|
| 71 |
+
r = t.start_req(
|
| 72 |
+
prompt_len=VERY_LONG_PROMPT_LEN, max_new_tokens=2, prompt_token=110
|
| 73 |
+
)
|
| 74 |
+
yield
|
| 75 |
+
yield from run_until(r, lambda h: h.is_chunking)
|
| 76 |
+
|
| 77 |
+
t.abort(r)
|
| 78 |
+
yield from _drain_until_released(t, r)
|
| 79 |
+
|
| 80 |
+
assert r.kv_pages == 0
|
| 81 |
+
assert r.req is None or r.req.req_pool_idx is None
|
| 82 |
+
|
| 83 |
+
def test_abort_at_chunk_mid(self):
|
| 84 |
+
self.server.execute_script(self._script_abort_at_chunk_mid)
|
| 85 |
+
|
| 86 |
+
@staticmethod
|
| 87 |
+
def _script_abort_at_chunk_mid(t: ScriptedContext):
|
| 88 |
+
r = t.start_req(
|
| 89 |
+
prompt_len=VERY_LONG_PROMPT_LEN, max_new_tokens=2, prompt_token=120
|
| 90 |
+
)
|
| 91 |
+
yield from run_until(r, lambda h: h.chunks_done >= 2 and h.is_chunking)
|
| 92 |
+
|
| 93 |
+
t.abort(r)
|
| 94 |
+
yield from _drain_until_released(t, r)
|
| 95 |
+
|
| 96 |
+
assert r.kv_pages == 0
|
| 97 |
+
|
| 98 |
+
def test_abort_one_does_not_disturb_other(self):
|
| 99 |
+
self.server.execute_script(self._script_abort_one_does_not_disturb_other)
|
| 100 |
+
|
| 101 |
+
@staticmethod
|
| 102 |
+
def _script_abort_one_does_not_disturb_other(t: ScriptedContext):
|
| 103 |
+
r1 = t.start_req(
|
| 104 |
+
prompt_len=VERY_LONG_PROMPT_LEN, max_new_tokens=2, prompt_token=130
|
| 105 |
+
)
|
| 106 |
+
r2 = t.start_req(
|
| 107 |
+
prompt_len=VERY_LONG_PROMPT_LEN, max_new_tokens=2, prompt_token=131
|
| 108 |
+
)
|
| 109 |
+
yield from run_until(r1, lambda h: h.is_chunking)
|
| 110 |
+
|
| 111 |
+
t.abort(r1)
|
| 112 |
+
yield from _drain_until_released(t, r1)
|
| 113 |
+
|
| 114 |
+
assert r1.kv_pages == 0
|
| 115 |
+
yield from run_until_finished(r2)
|
| 116 |
+
assert r2.finished, "r2 should still complete after r1 is aborted"
|
| 117 |
+
|
| 118 |
+
def test_abort_with_zero_yield(self):
|
| 119 |
+
self.server.execute_script(self._script_abort_with_zero_yield)
|
| 120 |
+
|
| 121 |
+
@staticmethod
|
| 122 |
+
def _script_abort_with_zero_yield(t: ScriptedContext):
|
| 123 |
+
r = t.start_req(prompt_len=VERY_LONG_PROMPT_LEN, max_new_tokens=2)
|
| 124 |
+
t.abort(r)
|
| 125 |
+
yield from _drain_until_released(t, r)
|
| 126 |
+
assert r.kv_pages == 0
|
| 127 |
+
assert r.req is None or r.req.req_pool_idx is None
|
| 128 |
+
assert r.lock_refs == 0
|
| 129 |
+
|
| 130 |
+
def test_abort_at_admission_step(self):
|
| 131 |
+
self.server.execute_script(self._script_abort_at_admission_step)
|
| 132 |
+
|
| 133 |
+
@staticmethod
|
| 134 |
+
def _script_abort_at_admission_step(t: ScriptedContext):
|
| 135 |
+
r = t.start_req(prompt_len=VERY_LONG_PROMPT_LEN, max_new_tokens=2)
|
| 136 |
+
yield
|
| 137 |
+
t.abort(r)
|
| 138 |
+
yield from _drain_until_released(t, r)
|
| 139 |
+
assert r.kv_pages == 0
|
| 140 |
+
assert r.req is None or r.req.req_pool_idx is None
|
| 141 |
+
|
| 142 |
+
def test_abort_then_start_same_step_new_rid(self):
|
| 143 |
+
self.server.execute_script(self._script_abort_then_start_same_step_new_rid)
|
| 144 |
+
|
| 145 |
+
@staticmethod
|
| 146 |
+
def _script_abort_then_start_same_step_new_rid(t: ScriptedContext):
|
| 147 |
+
r1 = t.start_req(
|
| 148 |
+
prompt_len=VERY_LONG_PROMPT_LEN, max_new_tokens=2, prompt_token=140
|
| 149 |
+
)
|
| 150 |
+
yield from run_until(r1, lambda h: h.is_chunking)
|
| 151 |
+
t.abort(r1)
|
| 152 |
+
r2 = t.start_req(
|
| 153 |
+
prompt_len=VERY_LONG_PROMPT_LEN, max_new_tokens=2, prompt_token=141
|
| 154 |
+
)
|
| 155 |
+
yield from run_until_finished(r2)
|
| 156 |
+
assert r2.finished
|
| 157 |
+
assert r1.kv_pages == 0
|
| 158 |
+
|
| 159 |
+
def test_abort_then_start_same_step_same_rid(self):
|
| 160 |
+
self.server.execute_script(self._script_abort_then_start_same_step_same_rid)
|
| 161 |
+
|
| 162 |
+
@staticmethod
|
| 163 |
+
def _script_abort_then_start_same_step_same_rid(t: ScriptedContext):
|
| 164 |
+
r1 = t.start_req(
|
| 165 |
+
prompt_len=VERY_LONG_PROMPT_LEN,
|
| 166 |
+
max_new_tokens=2,
|
| 167 |
+
rid="abort-reuse",
|
| 168 |
+
prompt_token=150,
|
| 169 |
+
)
|
| 170 |
+
yield from run_until(r1, lambda h: h.is_chunking)
|
| 171 |
+
t.abort(r1)
|
| 172 |
+
yield
|
| 173 |
+
r2 = t.start_req(prompt_len=16, max_new_tokens=2, rid="abort-reuse")
|
| 174 |
+
yield from run_until_finished(r2)
|
| 175 |
+
assert r2.finished
|
| 176 |
+
|
| 177 |
+
def test_abort_five_chunked_in_a_row(self):
|
| 178 |
+
self.server.execute_script(self._script_abort_five_chunked_in_a_row)
|
| 179 |
+
|
| 180 |
+
@staticmethod
|
| 181 |
+
def _script_abort_five_chunked_in_a_row(t: ScriptedContext):
|
| 182 |
+
reqs = [
|
| 183 |
+
t.start_req(
|
| 184 |
+
prompt_len=VERY_LONG_PROMPT_LEN, max_new_tokens=2, prompt_token=160 + i
|
| 185 |
+
)
|
| 186 |
+
for i in range(5)
|
| 187 |
+
]
|
| 188 |
+
yield from run_until(reqs[0], lambda h: h.is_chunking)
|
| 189 |
+
for r in reqs:
|
| 190 |
+
t.abort(r)
|
| 191 |
+
yield from _drain_until_released(t, *reqs)
|
| 192 |
+
for r in reqs:
|
| 193 |
+
assert r.kv_pages == 0
|
| 194 |
+
assert r.req is None or r.req.req_pool_idx is None
|
| 195 |
+
|
| 196 |
+
def test_abort_unknown_rid_noop(self):
|
| 197 |
+
self.server.execute_script(self._script_abort_unknown_rid_noop)
|
| 198 |
+
|
| 199 |
+
@staticmethod
|
| 200 |
+
def _script_abort_unknown_rid_noop(t: ScriptedContext):
|
| 201 |
+
bogus = ScriptedReqHandle(rid="never-submitted-rid", context=t)
|
| 202 |
+
t.abort(bogus, await_arrival=False)
|
| 203 |
+
yield
|
| 204 |
+
r = t.start_req(prompt_len=16, max_new_tokens=2)
|
| 205 |
+
yield from run_until_finished(r)
|
| 206 |
+
assert r.finished
|
| 207 |
+
for _ in range(12):
|
| 208 |
+
if r.kv_pages == 0 and r.lock_refs == 0:
|
| 209 |
+
break
|
| 210 |
+
yield
|
| 211 |
+
assert r.kv_pages == 0
|
| 212 |
+
assert r.lock_refs == 0
|
| 213 |
+
|
| 214 |
+
def test_abort_after_finish_noop(self):
|
| 215 |
+
self.server.execute_script(self._script_abort_after_finish_noop)
|
| 216 |
+
|
| 217 |
+
@staticmethod
|
| 218 |
+
def _script_abort_after_finish_noop(t: ScriptedContext):
|
| 219 |
+
r = t.start_req(prompt_len=16, max_new_tokens=2)
|
| 220 |
+
yield from run_until_finished(r)
|
| 221 |
+
assert r.finished
|
| 222 |
+
|
| 223 |
+
for _ in range(12):
|
| 224 |
+
if t.is_fully_idle:
|
| 225 |
+
break
|
| 226 |
+
yield
|
| 227 |
+
assert r.kv_pages == 0
|
| 228 |
+
assert r.lock_refs == 0
|
| 229 |
+
kv_pool_free_before = t.engine_stats()["kv_pool_free"]
|
| 230 |
+
|
| 231 |
+
t.abort(r, await_arrival=False)
|
| 232 |
+
yield
|
| 233 |
+
assert r.kv_pages == 0
|
| 234 |
+
assert r.lock_refs == 0
|
| 235 |
+
kv_pool_free_after = t.engine_stats()["kv_pool_free"]
|
| 236 |
+
assert kv_pool_free_after == kv_pool_free_before, (
|
| 237 |
+
f"abort-after-finish must not move KV pool; "
|
| 238 |
+
f"before={kv_pool_free_before} after={kv_pool_free_after}"
|
| 239 |
+
)
|
| 240 |
+
|
| 241 |
+
def test_abort_chunk_last(self):
|
| 242 |
+
self.server.execute_script(self._script_abort_chunk_last)
|
| 243 |
+
|
| 244 |
+
@staticmethod
|
| 245 |
+
def _script_abort_chunk_last(t: ScriptedContext):
|
| 246 |
+
r = t.start_req(
|
| 247 |
+
prompt_len=2 * DEFAULT_CHUNK_SIZE, max_new_tokens=4, prompt_token=170
|
| 248 |
+
)
|
| 249 |
+
yield from run_until(r, lambda h: h.chunks_done >= 1 and h.is_chunking)
|
| 250 |
+
t.abort(r)
|
| 251 |
+
yield from _drain_until_released(t, r)
|
| 252 |
+
assert r.kv_pages == 0
|
| 253 |
+
assert r.req is None or r.req.inflight_middle_chunks == 0
|
| 254 |
+
|
| 255 |
+
def test_abort_penultimate_chunk(self):
|
| 256 |
+
self.server.execute_script(self._script_abort_penultimate_chunk)
|
| 257 |
+
|
| 258 |
+
@staticmethod
|
| 259 |
+
def _script_abort_penultimate_chunk(t: ScriptedContext):
|
| 260 |
+
r = t.start_req(
|
| 261 |
+
prompt_len=4 * DEFAULT_CHUNK_SIZE, max_new_tokens=2, prompt_token=180
|
| 262 |
+
)
|
| 263 |
+
yield from run_until(r, lambda h: h.chunks_done >= 2 and h.is_chunking)
|
| 264 |
+
t.abort(r)
|
| 265 |
+
yield from _drain_until_released(t, r)
|
| 266 |
+
assert r.kv_pages == 0
|
| 267 |
+
assert r.req is None or r.req.req_pool_idx is None
|
| 268 |
+
assert r.lock_refs == 0
|
| 269 |
+
|
| 270 |
+
def test_double_abort_idempotent(self):
|
| 271 |
+
self.server.execute_script(self._script_double_abort_idempotent)
|
| 272 |
+
|
| 273 |
+
@staticmethod
|
| 274 |
+
def _script_double_abort_idempotent(t: ScriptedContext):
|
| 275 |
+
r = t.start_req(
|
| 276 |
+
prompt_len=VERY_LONG_PROMPT_LEN, max_new_tokens=2, prompt_token=190
|
| 277 |
+
)
|
| 278 |
+
yield from run_until(r, lambda h: h.is_chunking)
|
| 279 |
+
t.abort(r)
|
| 280 |
+
t.abort(r)
|
| 281 |
+
yield from _drain_until_released(t, r)
|
| 282 |
+
assert r.kv_pages == 0
|
| 283 |
+
assert r.lock_refs == 0
|
| 284 |
+
|
| 285 |
+
def test_abort_during_decode(self):
|
| 286 |
+
self.server.execute_script(self._script_abort_during_decode)
|
| 287 |
+
|
| 288 |
+
@staticmethod
|
| 289 |
+
def _script_abort_during_decode(t: ScriptedContext):
|
| 290 |
+
r = t.start_req(prompt_len=16, max_new_tokens=64)
|
| 291 |
+
yield from run_until(r, lambda h: h.status == "running")
|
| 292 |
+
assert r.kv_pages > 0, "decode req must own KV before abort"
|
| 293 |
+
t.abort(r)
|
| 294 |
+
yield from _drain_until_released(t, r)
|
| 295 |
+
assert r.kv_pages == 0
|
| 296 |
+
assert r.lock_refs == 0
|
| 297 |
+
|
| 298 |
+
def test_abort_one_of_three_others_finish(self):
|
| 299 |
+
self.server.execute_script(self._script_abort_one_of_three_others_finish)
|
| 300 |
+
|
| 301 |
+
@staticmethod
|
| 302 |
+
def _script_abort_one_of_three_others_finish(t: ScriptedContext):
|
| 303 |
+
r1 = t.start_req(prompt_len=16, max_new_tokens=4)
|
| 304 |
+
r2 = t.start_req(prompt_len=16, max_new_tokens=4)
|
| 305 |
+
r3 = t.start_req(prompt_len=16, max_new_tokens=4)
|
| 306 |
+
yield from run_until(r2, lambda h: h.status == "running")
|
| 307 |
+
t.abort(r2)
|
| 308 |
+
yield from run_until_all_finished([r1, r3])
|
| 309 |
+
assert r2.kv_pages == 0
|
| 310 |
+
|
| 311 |
+
def test_abort_in_separate_yields(self):
|
| 312 |
+
self.server.execute_script(self._script_abort_in_separate_yields)
|
| 313 |
+
|
| 314 |
+
@staticmethod
|
| 315 |
+
def _script_abort_in_separate_yields(t: ScriptedContext):
|
| 316 |
+
reqs = [
|
| 317 |
+
t.start_req(
|
| 318 |
+
prompt_len=VERY_LONG_PROMPT_LEN, max_new_tokens=2, prompt_token=200 + i
|
| 319 |
+
)
|
| 320 |
+
for i in range(3)
|
| 321 |
+
]
|
| 322 |
+
yield from run_until(reqs[0], lambda h: h.is_chunking)
|
| 323 |
+
for r in reqs:
|
| 324 |
+
t.abort(r)
|
| 325 |
+
yield
|
| 326 |
+
yield from _drain_until_released(t, *reqs)
|
| 327 |
+
for r in reqs:
|
| 328 |
+
assert r.kv_pages == 0
|
| 329 |
+
|
| 330 |
+
def test_abort_at_chunk_boundary_race(self):
|
| 331 |
+
self.server.execute_script(self._script_abort_at_chunk_boundary_race)
|
| 332 |
+
|
| 333 |
+
@staticmethod
|
| 334 |
+
def _script_abort_at_chunk_boundary_race(t: ScriptedContext):
|
| 335 |
+
r = t.start_req(
|
| 336 |
+
prompt_len=VERY_LONG_PROMPT_LEN, max_new_tokens=2, prompt_token=210
|
| 337 |
+
)
|
| 338 |
+
yield from run_until(r, lambda h: h.is_chunking)
|
| 339 |
+
yield from run_until(r, lambda h: h.chunks_done >= 1 and h.is_chunking)
|
| 340 |
+
|
| 341 |
+
t.abort(r)
|
| 342 |
+
yield from _drain_until_released(t, r)
|
| 343 |
+
|
| 344 |
+
assert r.kv_pages == 0
|
| 345 |
+
|
| 346 |
+
chunks_after_abort = r.chunks_done
|
| 347 |
+
yield
|
| 348 |
+
yield
|
| 349 |
+
assert not r.is_chunking, "aborted req must not resume chunking"
|
| 350 |
+
assert r.chunks_done == chunks_after_abort, (
|
| 351 |
+
f"aborted req revived and ran another chunk; "
|
| 352 |
+
f"chunks_done went {chunks_after_abort} -> {r.chunks_done}"
|
| 353 |
+
)
|
| 354 |
+
assert r.req is None or r.req.req_pool_idx is None
|
| 355 |
+
|
| 356 |
+
def test_abort_mid_chunk_no_extra_radix_node(self):
|
| 357 |
+
self.server.execute_script(self._script_abort_mid_chunk_no_extra_radix_node)
|
| 358 |
+
|
| 359 |
+
@staticmethod
|
| 360 |
+
def _script_abort_mid_chunk_no_extra_radix_node(
|
| 361 |
+
t: ScriptedContext,
|
| 362 |
+
):
|
| 363 |
+
r = t.start_req(
|
| 364 |
+
prompt_len=VERY_LONG_PROMPT_LEN, max_new_tokens=2, prompt_token=220
|
| 365 |
+
)
|
| 366 |
+
yield from run_until(r, lambda h: h.is_chunking)
|
| 367 |
+
|
| 368 |
+
t.abort(r)
|
| 369 |
+
yield from _drain_until_released(t, r)
|
| 370 |
+
|
| 371 |
+
assert r.kv_pages == 0
|
| 372 |
+
assert r.req is None or r.req.req_pool_idx is None
|
| 373 |
+
chunks_after_release = r.chunks_done
|
| 374 |
+
for _ in range(4):
|
| 375 |
+
yield
|
| 376 |
+
assert r.chunks_done == chunks_after_release, (
|
| 377 |
+
f"aborted mid-chunk req revived after release; chunks_done went "
|
| 378 |
+
f"{chunks_after_release} -> {r.chunks_done}"
|
| 379 |
+
)
|
| 380 |
+
|
| 381 |
+
lock_refs_after = t.get_all_node_lock_refs()
|
| 382 |
+
assert all(ref == 0 for ref in lock_refs_after.values()), (
|
| 383 |
+
f"abort mid-chunk left a locked radix node behind; "
|
| 384 |
+
f"node lock_refs={lock_refs_after!r}"
|
| 385 |
+
)
|
| 386 |
+
|
| 387 |
+
def test_abort_then_resubmit_same_rid_same_step(self):
|
| 388 |
+
self.server.execute_script(self._script_abort_then_resubmit_same_rid_same_step)
|
| 389 |
+
|
| 390 |
+
@staticmethod
|
| 391 |
+
def _script_abort_then_resubmit_same_rid_same_step(t: ScriptedContext):
|
| 392 |
+
r1 = t.start_req(
|
| 393 |
+
prompt_len=VERY_LONG_PROMPT_LEN,
|
| 394 |
+
max_new_tokens=2,
|
| 395 |
+
rid="abort-resubmit-same-step",
|
| 396 |
+
prompt_token=230,
|
| 397 |
+
)
|
| 398 |
+
yield from run_until(r1, lambda h: h.is_chunking)
|
| 399 |
+
t.abort(r1)
|
| 400 |
+
r2 = t.start_req(
|
| 401 |
+
prompt_len=16,
|
| 402 |
+
max_new_tokens=2,
|
| 403 |
+
rid="abort-resubmit-same-step",
|
| 404 |
+
)
|
| 405 |
+
yield
|
| 406 |
+
yield from run_until_finished(r2)
|
| 407 |
+
assert r2.finished, "resubmit under same rid must complete independently"
|
| 408 |
+
assert r1.kv_pages == 0, "aborted r1 must release KV before resubmit"
|
| 409 |
+
assert r1.req is None or r1.req.req_pool_idx is None
|
| 410 |
+
assert r1.lock_refs == 0
|
| 411 |
+
|
| 412 |
+
def test_abort_during_gap_inflight_middle_chunks_positive(self):
|
| 413 |
+
self.server.execute_script(
|
| 414 |
+
self._script_abort_during_gap_inflight_middle_chunks_positive
|
| 415 |
+
)
|
| 416 |
+
|
| 417 |
+
@staticmethod
|
| 418 |
+
def _script_abort_during_gap_inflight_middle_chunks_positive(t: ScriptedContext):
|
| 419 |
+
r = t.start_req(
|
| 420 |
+
prompt_len=2 * DEFAULT_CHUNK_SIZE, max_new_tokens=2, prompt_token=240
|
| 421 |
+
)
|
| 422 |
+
yield from run_until(
|
| 423 |
+
r,
|
| 424 |
+
lambda h: h.is_chunking and h.chunks_done >= 1,
|
| 425 |
+
)
|
| 426 |
+
assert r.req.inflight_middle_chunks > 0
|
| 427 |
+
|
| 428 |
+
t.abort(r)
|
| 429 |
+
yield from _drain_until_released(t, r)
|
| 430 |
+
|
| 431 |
+
assert r.kv_pages == 0
|
| 432 |
+
assert r.req is None or r.req.req_pool_idx is None
|
| 433 |
+
|
| 434 |
+
assert not r.is_chunking, "aborted gap req must not re-enter chunking"
|
| 435 |
+
yield
|
| 436 |
+
assert not r.is_chunking, "aborted gap req must stay out of chunking"
|
| 437 |
+
|
| 438 |
+
if r.req is not None:
|
| 439 |
+
assert (
|
| 440 |
+
r.req.inflight_middle_chunks == 0
|
| 441 |
+
), f"inflight_middle_chunks not cleared; got {r.req.inflight_middle_chunks}"
|
| 442 |
+
|
| 443 |
+
def test_abort_when_chunked_only_then_idle(self):
|
| 444 |
+
self.server.execute_script(self._script_abort_when_chunked_only_then_idle)
|
| 445 |
+
|
| 446 |
+
@staticmethod
|
| 447 |
+
def _script_abort_when_chunked_only_then_idle(t: ScriptedContext):
|
| 448 |
+
r = t.start_req(
|
| 449 |
+
prompt_len=VERY_LONG_PROMPT_LEN, max_new_tokens=2, prompt_token=250
|
| 450 |
+
)
|
| 451 |
+
yield from run_until(r, lambda h: h.is_chunking)
|
| 452 |
+
assert (1 if t.scheduler.chunked_req is not None else 0) == 1
|
| 453 |
+
|
| 454 |
+
t.abort(r)
|
| 455 |
+
yield from _drain_until_released(t, r)
|
| 456 |
+
|
| 457 |
+
for _ in range(12):
|
| 458 |
+
if t.scheduler.chunked_req is None and t.is_idle:
|
| 459 |
+
break
|
| 460 |
+
yield
|
| 461 |
+
|
| 462 |
+
assert r.kv_pages == 0
|
| 463 |
+
assert (1 if t.scheduler.chunked_req is not None else 0) == 0
|
| 464 |
+
assert t.is_idle, "engine must be idle after the only chunked req is aborted"
|
| 465 |
+
|
| 466 |
+
def test_chunked_req_then_abort_then_new_short_in_one_yield(self):
|
| 467 |
+
self.server.execute_script(
|
| 468 |
+
self._script_chunked_req_then_abort_then_new_short_in_one_yield
|
| 469 |
+
)
|
| 470 |
+
|
| 471 |
+
@staticmethod
|
| 472 |
+
def _script_chunked_req_then_abort_then_new_short_in_one_yield(t: ScriptedContext):
|
| 473 |
+
r1 = t.start_req(
|
| 474 |
+
prompt_len=VERY_LONG_PROMPT_LEN, max_new_tokens=2, prompt_token=260
|
| 475 |
+
)
|
| 476 |
+
yield from run_until(r1, lambda h: h.is_chunking)
|
| 477 |
+
assert (
|
| 478 |
+
t.scheduler.chunked_req.rid if t.scheduler.chunked_req is not None else None
|
| 479 |
+
) == r1.rid, (
|
| 480 |
+
f"r1 should hold the chunked slot before abort; got "
|
| 481 |
+
f"{(t.scheduler.chunked_req.rid if t.scheduler.chunked_req is not None else None)!r}"
|
| 482 |
+
)
|
| 483 |
+
|
| 484 |
+
t.abort(r1)
|
| 485 |
+
r2 = t.start_req(prompt_len=16, max_new_tokens=2)
|
| 486 |
+
yield from _drain_until_released(t, r1)
|
| 487 |
+
|
| 488 |
+
cur = (
|
| 489 |
+
t.scheduler.chunked_req.rid if t.scheduler.chunked_req is not None else None
|
| 490 |
+
)
|
| 491 |
+
assert cur != r1.rid, f"chunked slot still points to aborted r1; got {cur!r}"
|
| 492 |
+
assert r1.kv_pages == 0
|
| 493 |
+
yield from run_until_finished(r2)
|
| 494 |
+
assert r2.finished, "fresh r2 must admit and complete after combo step"
|
| 495 |
+
|
| 496 |
+
def test_force_retract_then_abort_same_yield(self):
|
| 497 |
+
self.server.execute_script(self._script_force_retract_then_abort_same_yield)
|
| 498 |
+
|
| 499 |
+
@staticmethod
|
| 500 |
+
def _script_force_retract_then_abort_same_yield(t: ScriptedContext):
|
| 501 |
+
r1 = t.start_req(
|
| 502 |
+
prompt_len=VERY_LONG_PROMPT_LEN, max_new_tokens=2, prompt_token=270
|
| 503 |
+
)
|
| 504 |
+
yield from run_until(r1, lambda h: h.is_chunking)
|
| 505 |
+
assert r1.kv_pages > 0
|
| 506 |
+
|
| 507 |
+
t.pause_generation(mode="retract")
|
| 508 |
+
t.abort(r1)
|
| 509 |
+
yield from _drain_until_released(t, r1)
|
| 510 |
+
|
| 511 |
+
assert r1.kv_pages == 0, (
|
| 512 |
+
f"force_retract + abort same yield must release KV; got " f"{r1.kv_pages}"
|
| 513 |
+
)
|
| 514 |
+
assert r1.req is None or r1.req.req_pool_idx is None, (
|
| 515 |
+
f"force_retract + abort same yield must release row; got " f"{r1.req}"
|
| 516 |
+
)
|
| 517 |
+
assert r1.lock_refs == 0, (
|
| 518 |
+
f"force_retract + abort same yield must release lock_refs; "
|
| 519 |
+
f"got {r1.lock_refs}"
|
| 520 |
+
)
|
| 521 |
+
yield
|
| 522 |
+
t.continue_generation()
|
| 523 |
+
|
| 524 |
+
def test_abort_chunked_with_baton_handoff(self):
|
| 525 |
+
self.server.execute_script(self._script_abort_chunked_with_baton_handoff)
|
| 526 |
+
|
| 527 |
+
@staticmethod
|
| 528 |
+
def _script_abort_chunked_with_baton_handoff(t: ScriptedContext):
|
| 529 |
+
r1 = t.start_req(
|
| 530 |
+
prompt_len=VERY_LONG_PROMPT_LEN, max_new_tokens=2, prompt_token=280
|
| 531 |
+
)
|
| 532 |
+
r2 = t.start_req(
|
| 533 |
+
prompt_len=VERY_LONG_PROMPT_LEN, max_new_tokens=2, prompt_token=281
|
| 534 |
+
)
|
| 535 |
+
yield from run_until(r1, lambda h: h.is_chunking)
|
| 536 |
+
assert (1 if t.scheduler.chunked_req is not None else 0) == 1
|
| 537 |
+
|
| 538 |
+
t.abort(r1)
|
| 539 |
+
yield from _drain_until_released(t, r1)
|
| 540 |
+
|
| 541 |
+
yield from run_until(r2, lambda h: h.is_chunking)
|
| 542 |
+
assert r1.kv_pages == 0
|
| 543 |
+
assert r1.req is None or r1.req.req_pool_idx is None
|
| 544 |
+
assert r1.lock_refs == 0
|
| 545 |
+
yield from run_until_finished(r2)
|
| 546 |
+
assert r2.finished, "baton handoff must let r2 complete"
|
| 547 |
+
assert r2.lock_refs == 0
|
| 548 |
+
|
| 549 |
+
|
| 550 |
+
class TestAbortPP(ScriptedTestCase):
|
| 551 |
+
ENGINE_KWARGS = base_engine_kwargs(
|
| 552 |
+
chunked_prefill_size=DEFAULT_CHUNK_SIZE,
|
| 553 |
+
pp_size=2,
|
| 554 |
+
)
|
| 555 |
+
|
| 556 |
+
def test_abort_at_last_chunk_in_flight_pp(self):
|
| 557 |
+
self.server.execute_script(self._script_abort_at_last_chunk_in_flight_pp)
|
| 558 |
+
|
| 559 |
+
@staticmethod
|
| 560 |
+
def _script_abort_at_last_chunk_in_flight_pp(t: ScriptedContext):
|
| 561 |
+
r = t.start_req(
|
| 562 |
+
prompt_len=2 * DEFAULT_CHUNK_SIZE, max_new_tokens=4, prompt_token=290
|
| 563 |
+
)
|
| 564 |
+
yield from run_until(
|
| 565 |
+
r,
|
| 566 |
+
lambda h: h.chunks_done >= 1 and h.is_chunking,
|
| 567 |
+
)
|
| 568 |
+
|
| 569 |
+
t.abort(r)
|
| 570 |
+
yield from _drain_until_released(t, r)
|
| 571 |
+
|
| 572 |
+
assert r.kv_pages == 0
|
| 573 |
+
assert r.req is None or r.req.req_pool_idx is None
|
| 574 |
+
assert r.lock_refs == 0
|
| 575 |
+
assert r.finished
|
| 576 |
+
|
| 577 |
+
|
| 578 |
+
class TestAbortSmallPool(ScriptedTestCase):
|
| 579 |
+
ENGINE_KWARGS = base_engine_kwargs(
|
| 580 |
+
chunked_prefill_size=DEFAULT_CHUNK_SIZE,
|
| 581 |
+
max_total_tokens=SMALL_KV_POOL_MAX_TOTAL_TOKENS,
|
| 582 |
+
)
|
| 583 |
+
|
| 584 |
+
def test_waiting_timeout_sweep_aborts_pressured_waiting_req(self):
|
| 585 |
+
self.server.execute_script(
|
| 586 |
+
self._script_waiting_timeout_sweep_aborts_pressured_waiting_req
|
| 587 |
+
)
|
| 588 |
+
|
| 589 |
+
@staticmethod
|
| 590 |
+
def _script_waiting_timeout_sweep_aborts_pressured_waiting_req(t: ScriptedContext):
|
| 591 |
+
|
| 592 |
+
b1 = t.start_req(
|
| 593 |
+
prompt_len=SMALL_KV_POOL_BALLAST_PROMPT_LEN,
|
| 594 |
+
max_new_tokens=SMALL_KV_POOL_BALLAST_MAX_NEW_TOKENS,
|
| 595 |
+
ignore_eos=True,
|
| 596 |
+
prompt_token=300,
|
| 597 |
+
)
|
| 598 |
+
b2 = t.start_req(
|
| 599 |
+
prompt_len=SMALL_KV_POOL_BALLAST_PROMPT_LEN,
|
| 600 |
+
max_new_tokens=SMALL_KV_POOL_BALLAST_MAX_NEW_TOKENS,
|
| 601 |
+
ignore_eos=True,
|
| 602 |
+
prompt_token=301,
|
| 603 |
+
)
|
| 604 |
+
yield from run_until(b1, lambda h: h.status == "running")
|
| 605 |
+
yield from run_until(b2, lambda h: h.status == "running")
|
| 606 |
+
|
| 607 |
+
r = t.start_req(prompt_len=16, max_new_tokens=2)
|
| 608 |
+
|
| 609 |
+
def waiting_rids():
|
| 610 |
+
return {req.rid for req in t.scheduler.waiting_queue}
|
| 611 |
+
|
| 612 |
+
yield from run_until(r, lambda h: r.rid in waiting_rids())
|
| 613 |
+
assert r.kv_pages == 0, "pressured waiting req must not own KV before admission"
|
| 614 |
+
|
| 615 |
+
with envs.SGLANG_REQ_WAITING_TIMEOUT.override(1e-6):
|
| 616 |
+
for _ in range(DEFAULT_MAX_STEPS):
|
| 617 |
+
if r.rid not in waiting_rids():
|
| 618 |
+
break
|
| 619 |
+
yield
|
| 620 |
+
else:
|
| 621 |
+
raise AssertionError(
|
| 622 |
+
f"waiting-timeout sweep never removed the req from "
|
| 623 |
+
f"waiting_queue after {DEFAULT_MAX_STEPS} steps; "
|
| 624 |
+
f"waiting_rids={waiting_rids()!r}"
|
| 625 |
+
)
|
| 626 |
+
|
| 627 |
+
assert r.rid not in waiting_rids(), (
|
| 628 |
+
f"the loop's waiting-timeout sweep must drop the timed-out waiting "
|
| 629 |
+
f"req from waiting_queue; got {waiting_rids()!r}"
|
| 630 |
+
)
|
| 631 |
+
assert r.status in ("finished", "unknown"), (
|
| 632 |
+
f"swept-out req must be aborted (gone from every live scheduler "
|
| 633 |
+
f"structure); got status={r.status!r}"
|
| 634 |
+
)
|
| 635 |
+
assert r.kv_pages == 0, "timeout-abort of an unadmitted req owns no KV"
|
| 636 |
+
|
| 637 |
+
t.abort(b1)
|
| 638 |
+
t.abort(b2)
|
| 639 |
+
yield from _drain_until_released(t, b1, b2)
|
| 640 |
+
|
| 641 |
+
|
| 642 |
+
if __name__ == "__main__":
|
| 643 |
+
unittest.main()
|
asian_ai/performance/SGLang/test/manual/chunked_prefill/test_scripted_chunk_size.py
ADDED
|
@@ -0,0 +1,361 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import unittest
|
| 2 |
+
|
| 3 |
+
from sglang.test.scripted_runtime.context import ScriptedContext
|
| 4 |
+
from sglang.test.scripted_runtime.test_case import ScriptedTestCase
|
| 5 |
+
from sglang.test.scripted_runtime_chunked_helpers import (
|
| 6 |
+
DEFAULT_CHUNK_SIZE,
|
| 7 |
+
base_engine_kwargs,
|
| 8 |
+
run_until,
|
| 9 |
+
run_until_finished,
|
| 10 |
+
)
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
def _expected_chunks(prompt_len: int, chunk_size: int) -> int:
|
| 14 |
+
if prompt_len <= chunk_size:
|
| 15 |
+
return 0
|
| 16 |
+
return (prompt_len + chunk_size - 1) // chunk_size
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
class TestChunkSizeDefault(ScriptedTestCase):
|
| 20 |
+
ENGINE_KWARGS = base_engine_kwargs(chunked_prefill_size=DEFAULT_CHUNK_SIZE)
|
| 21 |
+
|
| 22 |
+
def test_exact_chunk_size(self):
|
| 23 |
+
self.server.execute_script(self._script_exact_chunk_size)
|
| 24 |
+
|
| 25 |
+
@staticmethod
|
| 26 |
+
def _script_exact_chunk_size(t: ScriptedContext):
|
| 27 |
+
r = t.start_req(prompt_len=DEFAULT_CHUNK_SIZE, max_new_tokens=2)
|
| 28 |
+
yield from run_until_finished(r)
|
| 29 |
+
assert r.finished
|
| 30 |
+
assert r.chunks_done == 0, (
|
| 31 |
+
f"prompt_len == chunk_size completes in one non-chunked shot, "
|
| 32 |
+
f"got chunks_done={r.chunks_done}"
|
| 33 |
+
)
|
| 34 |
+
|
| 35 |
+
def test_one_token_over(self):
|
| 36 |
+
self.server.execute_script(self._script_one_token_over)
|
| 37 |
+
|
| 38 |
+
@staticmethod
|
| 39 |
+
def _script_one_token_over(t: ScriptedContext):
|
| 40 |
+
r = t.start_req(prompt_len=DEFAULT_CHUNK_SIZE + 1, max_new_tokens=2)
|
| 41 |
+
yield from run_until_finished(r)
|
| 42 |
+
assert r.finished
|
| 43 |
+
assert r.chunks_done == 2, (
|
| 44 |
+
f"prompt_len == chunk_size + 1 expected exactly 2 chunks, "
|
| 45 |
+
f"got chunks_done={r.chunks_done}"
|
| 46 |
+
)
|
| 47 |
+
|
| 48 |
+
def test_two_chunks_exact(self):
|
| 49 |
+
self.server.execute_script(self._script_two_chunks_exact)
|
| 50 |
+
|
| 51 |
+
@staticmethod
|
| 52 |
+
def _script_two_chunks_exact(t: ScriptedContext):
|
| 53 |
+
r = t.start_req(prompt_len=2 * DEFAULT_CHUNK_SIZE, max_new_tokens=2)
|
| 54 |
+
yield from run_until_finished(r)
|
| 55 |
+
assert r.finished
|
| 56 |
+
assert r.chunks_done == 2
|
| 57 |
+
|
| 58 |
+
def test_three_chunks_one_decode(self):
|
| 59 |
+
self.server.execute_script(self._script_three_chunks_one_decode)
|
| 60 |
+
|
| 61 |
+
@staticmethod
|
| 62 |
+
def _script_three_chunks_one_decode(t: ScriptedContext):
|
| 63 |
+
r = t.start_req(prompt_len=3 * DEFAULT_CHUNK_SIZE, max_new_tokens=1)
|
| 64 |
+
yield from run_until_finished(r)
|
| 65 |
+
assert r.finished
|
| 66 |
+
assert r.chunks_done == 3
|
| 67 |
+
|
| 68 |
+
def test_tiny_prompt(self):
|
| 69 |
+
self.server.execute_script(self._script_tiny_prompt)
|
| 70 |
+
|
| 71 |
+
@staticmethod
|
| 72 |
+
def _script_tiny_prompt(t: ScriptedContext):
|
| 73 |
+
r = t.start_req(prompt_len=1, max_new_tokens=2)
|
| 74 |
+
yield from run_until_finished(r)
|
| 75 |
+
assert r.finished
|
| 76 |
+
assert (
|
| 77 |
+
r.chunks_done == 0
|
| 78 |
+
), f"single-token prompt should not chunk, got chunks_done={r.chunks_done}"
|
| 79 |
+
|
| 80 |
+
def test_chunk_size_256_prompt_100x(self):
|
| 81 |
+
self.server.execute_script(self._script_chunk_size_256_prompt_100x)
|
| 82 |
+
|
| 83 |
+
@staticmethod
|
| 84 |
+
def _script_chunk_size_256_prompt_100x(t: ScriptedContext):
|
| 85 |
+
r = t.start_req(prompt_len=100 * 256, max_new_tokens=2)
|
| 86 |
+
yield from run_until(r, lambda h: h.finished, max_steps=4000)
|
| 87 |
+
assert r.finished
|
| 88 |
+
assert r.chunks_done == 100
|
| 89 |
+
|
| 90 |
+
def test_prompt_n_chunks_plus_minus_1(self):
|
| 91 |
+
self.server.execute_script(self._script_prompt_n_chunks_plus_minus_1)
|
| 92 |
+
|
| 93 |
+
@staticmethod
|
| 94 |
+
def _script_prompt_n_chunks_plus_minus_1(t: ScriptedContext):
|
| 95 |
+
for n in range(1, 6):
|
| 96 |
+
prompt_minus = n * DEFAULT_CHUNK_SIZE - 1
|
| 97 |
+
r_minus = t.start_req(
|
| 98 |
+
prompt_len=prompt_minus, max_new_tokens=1, prompt_token=2 * n
|
| 99 |
+
)
|
| 100 |
+
yield from run_until_finished(r_minus, max_steps=800)
|
| 101 |
+
assert r_minus.finished
|
| 102 |
+
expected_minus = _expected_chunks(prompt_minus, DEFAULT_CHUNK_SIZE)
|
| 103 |
+
assert r_minus.chunks_done == expected_minus, (
|
| 104 |
+
f"N={n} prompt_len={prompt_minus}: "
|
| 105 |
+
f"expected chunks_done={expected_minus}, got {r_minus.chunks_done}"
|
| 106 |
+
)
|
| 107 |
+
|
| 108 |
+
prompt_plus = n * DEFAULT_CHUNK_SIZE + 1
|
| 109 |
+
r_plus = t.start_req(
|
| 110 |
+
prompt_len=prompt_plus, max_new_tokens=1, prompt_token=2 * n + 1
|
| 111 |
+
)
|
| 112 |
+
yield from run_until_finished(r_plus, max_steps=800)
|
| 113 |
+
assert r_plus.finished
|
| 114 |
+
expected_plus = _expected_chunks(prompt_plus, DEFAULT_CHUNK_SIZE)
|
| 115 |
+
assert r_plus.chunks_done == expected_plus, (
|
| 116 |
+
f"N={n} prompt_len={prompt_plus}: "
|
| 117 |
+
f"expected chunks_done={expected_plus}, got {r_plus.chunks_done}"
|
| 118 |
+
)
|
| 119 |
+
|
| 120 |
+
|
| 121 |
+
class TestChunkSizeDefaultRadixExplicit(ScriptedTestCase):
|
| 122 |
+
ENGINE_KWARGS = base_engine_kwargs(
|
| 123 |
+
chunked_prefill_size=DEFAULT_CHUNK_SIZE,
|
| 124 |
+
disable_radix_cache=False,
|
| 125 |
+
)
|
| 126 |
+
|
| 127 |
+
def test_radix_hit_minus_one(self):
|
| 128 |
+
self.server.execute_script(self._script_radix_hit_minus_one)
|
| 129 |
+
|
| 130 |
+
@staticmethod
|
| 131 |
+
def _script_radix_hit_minus_one(t: ScriptedContext):
|
| 132 |
+
r_warm = t.start_req(prompt_len=DEFAULT_CHUNK_SIZE - 1, max_new_tokens=1)
|
| 133 |
+
yield from run_until_finished(r_warm)
|
| 134 |
+
assert r_warm.finished
|
| 135 |
+
|
| 136 |
+
yield
|
| 137 |
+
|
| 138 |
+
r = t.start_req(prompt_len=DEFAULT_CHUNK_SIZE, max_new_tokens=1)
|
| 139 |
+
yield from run_until_finished(r)
|
| 140 |
+
assert r.finished
|
| 141 |
+
assert r.chunks_done == 0, (
|
| 142 |
+
f"radix hit should leave only 1 fresh token; chunked path should "
|
| 143 |
+
f"not engage. Got chunks_done={r.chunks_done}"
|
| 144 |
+
)
|
| 145 |
+
|
| 146 |
+
|
| 147 |
+
class TestChunkSize1(ScriptedTestCase):
|
| 148 |
+
ENGINE_KWARGS = base_engine_kwargs(chunked_prefill_size=1)
|
| 149 |
+
|
| 150 |
+
def test_chunk_size_one_token(self):
|
| 151 |
+
self.server.execute_script(self._script_chunk_size_one_token)
|
| 152 |
+
|
| 153 |
+
@staticmethod
|
| 154 |
+
def _script_chunk_size_one_token(t: ScriptedContext):
|
| 155 |
+
r = t.start_req(prompt_len=8, max_new_tokens=2)
|
| 156 |
+
yield from run_until_finished(r)
|
| 157 |
+
assert r.finished
|
| 158 |
+
assert r.chunks_done == 8, f"expected 8 chunks, got {r.chunks_done}"
|
| 159 |
+
|
| 160 |
+
def test_chunks_done_monotone_under_chunk_size_1(self):
|
| 161 |
+
self.server.execute_script(self._script_chunks_done_monotone_under_chunk_size_1)
|
| 162 |
+
|
| 163 |
+
@staticmethod
|
| 164 |
+
def _script_chunks_done_monotone_under_chunk_size_1(t: ScriptedContext):
|
| 165 |
+
r = t.start_req(prompt_len=16, max_new_tokens=2)
|
| 166 |
+
yield from run_until_finished(r)
|
| 167 |
+
assert r.finished
|
| 168 |
+
assert r.chunks_done == 16, (
|
| 169 |
+
f"chunk_size=1 with prompt_len=16 chunks one token at a time "
|
| 170 |
+
f"(ceil(16/1)=16), got chunks_done={r.chunks_done}"
|
| 171 |
+
)
|
| 172 |
+
|
| 173 |
+
def test_chunk_size_one_long_prompt(self):
|
| 174 |
+
self.server.execute_script(self._script_chunk_size_one_long_prompt)
|
| 175 |
+
|
| 176 |
+
@staticmethod
|
| 177 |
+
def _script_chunk_size_one_long_prompt(t: ScriptedContext):
|
| 178 |
+
r = t.start_req(prompt_len=64, max_new_tokens=2)
|
| 179 |
+
yield from run_until(r, lambda h: h.finished, max_steps=500)
|
| 180 |
+
assert r.finished
|
| 181 |
+
assert r.chunks_done == 64
|
| 182 |
+
|
| 183 |
+
|
| 184 |
+
class TestChunkSize2(ScriptedTestCase):
|
| 185 |
+
ENGINE_KWARGS = base_engine_kwargs(chunked_prefill_size=2)
|
| 186 |
+
|
| 187 |
+
def test_chunk_size_two_prompt_two(self):
|
| 188 |
+
self.server.execute_script(self._script_chunk_size_two_prompt_two)
|
| 189 |
+
|
| 190 |
+
@staticmethod
|
| 191 |
+
def _script_chunk_size_two_prompt_two(t: ScriptedContext):
|
| 192 |
+
r = t.start_req(prompt_len=2, max_new_tokens=2)
|
| 193 |
+
yield from run_until_finished(r)
|
| 194 |
+
assert r.finished
|
| 195 |
+
assert r.chunks_done == 0
|
| 196 |
+
|
| 197 |
+
def test_chunk_size_two_prompt_five(self):
|
| 198 |
+
self.server.execute_script(self._script_chunk_size_two_prompt_five)
|
| 199 |
+
|
| 200 |
+
@staticmethod
|
| 201 |
+
def _script_chunk_size_two_prompt_five(t: ScriptedContext):
|
| 202 |
+
r = t.start_req(prompt_len=5, max_new_tokens=2)
|
| 203 |
+
yield from run_until_finished(r)
|
| 204 |
+
assert r.finished
|
| 205 |
+
assert r.chunks_done == 3, f"expected 3 chunks, got {r.chunks_done}"
|
| 206 |
+
|
| 207 |
+
|
| 208 |
+
class TestChunkSize4(ScriptedTestCase):
|
| 209 |
+
ENGINE_KWARGS = base_engine_kwargs(chunked_prefill_size=4)
|
| 210 |
+
|
| 211 |
+
def test_chunk_size_4_prompt_4(self):
|
| 212 |
+
self.server.execute_script(self._script_chunk_size_4_prompt_4)
|
| 213 |
+
|
| 214 |
+
@staticmethod
|
| 215 |
+
def _script_chunk_size_4_prompt_4(t: ScriptedContext):
|
| 216 |
+
r = t.start_req(prompt_len=4, max_new_tokens=2)
|
| 217 |
+
yield from run_until_finished(r)
|
| 218 |
+
assert r.finished
|
| 219 |
+
assert r.chunks_done == 0
|
| 220 |
+
|
| 221 |
+
def test_chunk_size_4_prompt_5(self):
|
| 222 |
+
self.server.execute_script(self._script_chunk_size_4_prompt_5)
|
| 223 |
+
|
| 224 |
+
@staticmethod
|
| 225 |
+
def _script_chunk_size_4_prompt_5(t: ScriptedContext):
|
| 226 |
+
r = t.start_req(prompt_len=5, max_new_tokens=2)
|
| 227 |
+
yield from run_until_finished(r)
|
| 228 |
+
assert r.finished
|
| 229 |
+
assert r.chunks_done == 2
|
| 230 |
+
|
| 231 |
+
|
| 232 |
+
class TestChunkSize16(ScriptedTestCase):
|
| 233 |
+
ENGINE_KWARGS = base_engine_kwargs(chunked_prefill_size=16)
|
| 234 |
+
|
| 235 |
+
def test_chunk_size_16_prompt_1024(self):
|
| 236 |
+
self.server.execute_script(self._script_chunk_size_16_prompt_1024)
|
| 237 |
+
|
| 238 |
+
@staticmethod
|
| 239 |
+
def _script_chunk_size_16_prompt_1024(t: ScriptedContext):
|
| 240 |
+
r = t.start_req(prompt_len=1024, max_new_tokens=2)
|
| 241 |
+
yield from run_until(r, lambda h: h.finished, max_steps=1000)
|
| 242 |
+
assert r.finished
|
| 243 |
+
assert r.chunks_done == 64
|
| 244 |
+
|
| 245 |
+
|
| 246 |
+
class TestChunkSize32(ScriptedTestCase):
|
| 247 |
+
ENGINE_KWARGS = base_engine_kwargs(chunked_prefill_size=32)
|
| 248 |
+
|
| 249 |
+
def test_chunk_size_32_prompt_33(self):
|
| 250 |
+
self.server.execute_script(self._script_chunk_size_32_prompt_33)
|
| 251 |
+
|
| 252 |
+
@staticmethod
|
| 253 |
+
def _script_chunk_size_32_prompt_33(t: ScriptedContext):
|
| 254 |
+
r = t.start_req(prompt_len=33, max_new_tokens=2)
|
| 255 |
+
yield from run_until_finished(r)
|
| 256 |
+
assert r.finished
|
| 257 |
+
assert r.chunks_done == 2
|
| 258 |
+
|
| 259 |
+
|
| 260 |
+
class TestChunkSize64(ScriptedTestCase):
|
| 261 |
+
ENGINE_KWARGS = base_engine_kwargs(chunked_prefill_size=64)
|
| 262 |
+
|
| 263 |
+
def test_chunk_size_64_prompt_129(self):
|
| 264 |
+
self.server.execute_script(self._script_chunk_size_64_prompt_129)
|
| 265 |
+
|
| 266 |
+
@staticmethod
|
| 267 |
+
def _script_chunk_size_64_prompt_129(t: ScriptedContext):
|
| 268 |
+
r = t.start_req(prompt_len=129, max_new_tokens=2)
|
| 269 |
+
yield from run_until_finished(r)
|
| 270 |
+
assert r.finished
|
| 271 |
+
assert r.chunks_done == 3
|
| 272 |
+
|
| 273 |
+
|
| 274 |
+
class TestChunkSize128(ScriptedTestCase):
|
| 275 |
+
ENGINE_KWARGS = base_engine_kwargs(chunked_prefill_size=128)
|
| 276 |
+
|
| 277 |
+
def test_chunk_size_128_prompt_512(self):
|
| 278 |
+
self.server.execute_script(self._script_chunk_size_128_prompt_512)
|
| 279 |
+
|
| 280 |
+
@staticmethod
|
| 281 |
+
def _script_chunk_size_128_prompt_512(t: ScriptedContext):
|
| 282 |
+
r = t.start_req(prompt_len=512, max_new_tokens=2)
|
| 283 |
+
yield from run_until_finished(r)
|
| 284 |
+
assert r.finished
|
| 285 |
+
assert r.chunks_done == 4
|
| 286 |
+
|
| 287 |
+
|
| 288 |
+
class TestChunkSize1024(ScriptedTestCase):
|
| 289 |
+
ENGINE_KWARGS = base_engine_kwargs(chunked_prefill_size=1024)
|
| 290 |
+
|
| 291 |
+
def test_chunk_size_1024_prompt_4096(self):
|
| 292 |
+
self.server.execute_script(self._script_chunk_size_1024_prompt_4096)
|
| 293 |
+
|
| 294 |
+
@staticmethod
|
| 295 |
+
def _script_chunk_size_1024_prompt_4096(t: ScriptedContext):
|
| 296 |
+
r = t.start_req(prompt_len=4096, max_new_tokens=2)
|
| 297 |
+
yield from run_until(r, lambda h: h.finished, max_steps=1000)
|
| 298 |
+
assert r.finished
|
| 299 |
+
assert r.chunks_done == 4
|
| 300 |
+
|
| 301 |
+
|
| 302 |
+
class TestChunkSize4096(ScriptedTestCase):
|
| 303 |
+
ENGINE_KWARGS = base_engine_kwargs(chunked_prefill_size=4096)
|
| 304 |
+
|
| 305 |
+
def test_chunk_size_4096_prompt_4097(self):
|
| 306 |
+
self.server.execute_script(self._script_chunk_size_4096_prompt_4097)
|
| 307 |
+
|
| 308 |
+
@staticmethod
|
| 309 |
+
def _script_chunk_size_4096_prompt_4097(t: ScriptedContext):
|
| 310 |
+
r = t.start_req(prompt_len=4097, max_new_tokens=2)
|
| 311 |
+
yield from run_until_finished(r)
|
| 312 |
+
assert r.finished
|
| 313 |
+
assert r.chunks_done == 2
|
| 314 |
+
|
| 315 |
+
|
| 316 |
+
class TestChunkSize1024MaxPrefill1024(ScriptedTestCase):
|
| 317 |
+
ENGINE_KWARGS = base_engine_kwargs(
|
| 318 |
+
chunked_prefill_size=1024, max_prefill_tokens=1024
|
| 319 |
+
)
|
| 320 |
+
|
| 321 |
+
def test_chunk_size_equals_max_prefill_tokens(self):
|
| 322 |
+
self.server.execute_script(self._script_chunk_size_equals_max_prefill_tokens)
|
| 323 |
+
|
| 324 |
+
@staticmethod
|
| 325 |
+
def _script_chunk_size_equals_max_prefill_tokens(t: ScriptedContext):
|
| 326 |
+
r = t.start_req(prompt_len=1024, max_new_tokens=2)
|
| 327 |
+
yield from run_until_finished(r)
|
| 328 |
+
assert r.finished
|
| 329 |
+
assert r.chunks_done == 0
|
| 330 |
+
|
| 331 |
+
|
| 332 |
+
class TestChunkSize2048MaxPrefill1024(ScriptedTestCase):
|
| 333 |
+
ENGINE_KWARGS = base_engine_kwargs(
|
| 334 |
+
chunked_prefill_size=2048, max_prefill_tokens=1024
|
| 335 |
+
)
|
| 336 |
+
|
| 337 |
+
def test_chunk_size_exceeds_max_prefill_tokens(self):
|
| 338 |
+
self.server.execute_script(self._script_chunk_size_exceeds_max_prefill_tokens)
|
| 339 |
+
|
| 340 |
+
@staticmethod
|
| 341 |
+
def _script_chunk_size_exceeds_max_prefill_tokens(t: ScriptedContext):
|
| 342 |
+
r = t.start_req(prompt_len=512, max_new_tokens=2)
|
| 343 |
+
yield from run_until_finished(r)
|
| 344 |
+
assert r.finished
|
| 345 |
+
assert r.chunks_done == 0
|
| 346 |
+
|
| 347 |
+
def test_prompt_between_max_prefill_and_chunk_size(self):
|
| 348 |
+
self.server.execute_script(
|
| 349 |
+
self._script_prompt_between_max_prefill_and_chunk_size
|
| 350 |
+
)
|
| 351 |
+
|
| 352 |
+
@staticmethod
|
| 353 |
+
def _script_prompt_between_max_prefill_and_chunk_size(t: ScriptedContext):
|
| 354 |
+
r = t.start_req(prompt_len=1536, max_new_tokens=2)
|
| 355 |
+
yield from run_until_finished(r)
|
| 356 |
+
assert r.finished
|
| 357 |
+
assert r.chunks_done == 0
|
| 358 |
+
|
| 359 |
+
|
| 360 |
+
if __name__ == "__main__":
|
| 361 |
+
unittest.main()
|
asian_ai/performance/SGLang/test/manual/chunked_prefill/test_scripted_http_smoke.py
ADDED
|
@@ -0,0 +1,49 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import unittest
|
| 2 |
+
|
| 3 |
+
from sglang.test.scripted_runtime.context import ScriptedContext
|
| 4 |
+
from sglang.test.scripted_runtime.test_case import ScriptedTestCase
|
| 5 |
+
from sglang.test.scripted_runtime_chunked_helpers import (
|
| 6 |
+
DEFAULT_CHUNK_SIZE,
|
| 7 |
+
base_engine_kwargs,
|
| 8 |
+
run_until_finished,
|
| 9 |
+
)
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
class TestScriptedHttpSmoke(ScriptedTestCase):
|
| 13 |
+
ENGINE_KWARGS = base_engine_kwargs(chunked_prefill_size=DEFAULT_CHUNK_SIZE)
|
| 14 |
+
|
| 15 |
+
def test_chunked_req_is_chunking_then_finishes(self):
|
| 16 |
+
self.server.execute_script(self._script_chunked_req_is_chunking_then_finishes)
|
| 17 |
+
|
| 18 |
+
@staticmethod
|
| 19 |
+
def _script_chunked_req_is_chunking_then_finishes(t: ScriptedContext):
|
| 20 |
+
r = t.start_req(prompt_len=4 * DEFAULT_CHUNK_SIZE, max_new_tokens=2)
|
| 21 |
+
saw_chunking = False
|
| 22 |
+
for _ in range(800):
|
| 23 |
+
if r.is_chunking:
|
| 24 |
+
saw_chunking = True
|
| 25 |
+
if r.finished:
|
| 26 |
+
break
|
| 27 |
+
yield
|
| 28 |
+
assert r.finished
|
| 29 |
+
assert (
|
| 30 |
+
saw_chunking
|
| 31 |
+
), "expected the req to hold the chunked_req slot at least once"
|
| 32 |
+
|
| 33 |
+
def test_two_reqs_finish(self):
|
| 34 |
+
self.server.execute_script(self._script_two_reqs_finish)
|
| 35 |
+
|
| 36 |
+
@staticmethod
|
| 37 |
+
def _script_two_reqs_finish(t: ScriptedContext):
|
| 38 |
+
r1 = t.start_req(prompt_len=8, max_new_tokens=4)
|
| 39 |
+
yield from run_until_finished(r1)
|
| 40 |
+
r2 = t.start_req(prompt_len=2 * DEFAULT_CHUNK_SIZE, max_new_tokens=2)
|
| 41 |
+
yield from run_until_finished(r2)
|
| 42 |
+
assert r1.finished
|
| 43 |
+
assert r2.finished
|
| 44 |
+
assert r1.chunks_done == 0
|
| 45 |
+
assert r2.chunks_done == 2
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
if __name__ == "__main__":
|
| 49 |
+
unittest.main()
|
asian_ai/performance/SGLang/test/manual/chunked_prefill/test_scripted_hybrid_swa.py
ADDED
|
@@ -0,0 +1,180 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import unittest
|
| 2 |
+
|
| 3 |
+
from sglang.test.scripted_runtime.context import ScriptedContext
|
| 4 |
+
from sglang.test.scripted_runtime.test_case import ScriptedTestCase
|
| 5 |
+
from sglang.test.scripted_runtime_chunked_helpers import (
|
| 6 |
+
DEFAULT_CHUNK_SIZE,
|
| 7 |
+
VERY_LONG_PROMPT_LEN,
|
| 8 |
+
base_engine_kwargs,
|
| 9 |
+
run_until,
|
| 10 |
+
run_until_finished,
|
| 11 |
+
)
|
| 12 |
+
|
| 13 |
+
_SWA_MODEL = "openai/gpt-oss-20b"
|
| 14 |
+
_SWA_WINDOW = 4096
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
class TestSWABasic(ScriptedTestCase):
|
| 18 |
+
ENGINE_KWARGS = base_engine_kwargs(
|
| 19 |
+
model_path=_SWA_MODEL,
|
| 20 |
+
chunked_prefill_size=DEFAULT_CHUNK_SIZE,
|
| 21 |
+
mem_fraction_static=0.70,
|
| 22 |
+
disable_piecewise_cuda_graph=True,
|
| 23 |
+
)
|
| 24 |
+
|
| 25 |
+
def test_naive_swa_chunked(self):
|
| 26 |
+
self.server.execute_script(self._script_naive_swa_chunked)
|
| 27 |
+
|
| 28 |
+
@staticmethod
|
| 29 |
+
def _script_naive_swa_chunked(t: ScriptedContext):
|
| 30 |
+
r = t.start_req(prompt_len=VERY_LONG_PROMPT_LEN + 4096, max_new_tokens=4)
|
| 31 |
+
yield from run_until_finished(r)
|
| 32 |
+
assert r.finished
|
| 33 |
+
assert r.chunks_done >= 24
|
| 34 |
+
assert len(r.req.output_ids) == 4
|
| 35 |
+
|
| 36 |
+
def test_swa_prompt_equals_window(self):
|
| 37 |
+
self.server.execute_script(self._script_swa_prompt_equals_window)
|
| 38 |
+
|
| 39 |
+
@staticmethod
|
| 40 |
+
def _script_swa_prompt_equals_window(t: ScriptedContext):
|
| 41 |
+
r = t.start_req(prompt_len=_SWA_WINDOW, max_new_tokens=4)
|
| 42 |
+
yield from run_until_finished(r, max_steps=800)
|
| 43 |
+
assert r.finished
|
| 44 |
+
assert r.chunks_done >= 2
|
| 45 |
+
assert r.kv_pages == 0
|
| 46 |
+
assert r.lock_refs == 0
|
| 47 |
+
|
| 48 |
+
def test_swa_budget_for_chunked_req_math(self):
|
| 49 |
+
self.server.execute_script(self._script_swa_budget_for_chunked_req_math)
|
| 50 |
+
|
| 51 |
+
@staticmethod
|
| 52 |
+
def _script_swa_budget_for_chunked_req_math(t: ScriptedContext):
|
| 53 |
+
baseline_free = t.engine_stats()["kv_pool_free"]
|
| 54 |
+
r = t.start_req(prompt_len=_SWA_WINDOW + 13, max_new_tokens=2)
|
| 55 |
+
yield from run_until_finished(r, max_steps=800)
|
| 56 |
+
assert r.finished
|
| 57 |
+
assert r.chunks_done >= 2
|
| 58 |
+
assert r.kv_pages == 0
|
| 59 |
+
assert r.lock_refs == 0
|
| 60 |
+
for _ in range(40):
|
| 61 |
+
if t.is_fully_idle:
|
| 62 |
+
break
|
| 63 |
+
yield
|
| 64 |
+
t.flush_cache()
|
| 65 |
+
yield
|
| 66 |
+
assert t.engine_stats()["kv_pool_free"] >= baseline_free, (
|
| 67 |
+
"SWA pool failed to recover after a window-straddling chunked req: "
|
| 68 |
+
f"baseline={baseline_free}, "
|
| 69 |
+
f"final={t.engine_stats()['kv_pool_free']}"
|
| 70 |
+
)
|
| 71 |
+
|
| 72 |
+
def test_swa_chunked_resume_under_swa_pressure(self):
|
| 73 |
+
self.server.execute_script(self._script_swa_chunked_resume_under_swa_pressure)
|
| 74 |
+
|
| 75 |
+
@staticmethod
|
| 76 |
+
def _script_swa_chunked_resume_under_swa_pressure(t: ScriptedContext):
|
| 77 |
+
r = t.start_req(prompt_len=_SWA_WINDOW + VERY_LONG_PROMPT_LEN, max_new_tokens=2)
|
| 78 |
+
yield from run_until(r, lambda h: h.is_chunking and h.chunks_done >= 1)
|
| 79 |
+
chunks_at_pressure = r.chunks_done
|
| 80 |
+
t.exhaust_kv(leave_pages=1000)
|
| 81 |
+
yield from run_until_finished(r, max_steps=2000)
|
| 82 |
+
assert r.finished
|
| 83 |
+
assert r.chunks_done > chunks_at_pressure, (
|
| 84 |
+
f"chunked prefill stalled under SWA pressure: chunks_done="
|
| 85 |
+
f"{r.chunks_done} did not advance past chunks_at_pressure="
|
| 86 |
+
f"{chunks_at_pressure}"
|
| 87 |
+
)
|
| 88 |
+
assert r.kv_pages == 0
|
| 89 |
+
assert r.lock_refs == 0
|
| 90 |
+
|
| 91 |
+
def test_swa_chunked_resume_kv_committed_bound(self):
|
| 92 |
+
self.server.execute_script(self._script_swa_chunked_resume_kv_committed_bound)
|
| 93 |
+
|
| 94 |
+
@staticmethod
|
| 95 |
+
def _script_swa_chunked_resume_kv_committed_bound(t: ScriptedContext):
|
| 96 |
+
r = t.start_req(prompt_len=VERY_LONG_PROMPT_LEN, max_new_tokens=2)
|
| 97 |
+
for _ in range(400):
|
| 98 |
+
if r.is_chunking:
|
| 99 |
+
assert len(r.req.prefix_indices) <= r.req.kv_committed_len, (
|
| 100 |
+
f"prefix_indices must be bounded by kv_committed_len, "
|
| 101 |
+
f"got prefix_indices_len={len(r.req.prefix_indices)}, "
|
| 102 |
+
f"kv_committed_len={r.req.kv_committed_len}"
|
| 103 |
+
)
|
| 104 |
+
if r.finished:
|
| 105 |
+
break
|
| 106 |
+
yield
|
| 107 |
+
assert r.finished
|
| 108 |
+
|
| 109 |
+
|
| 110 |
+
class TestSWAHalfWindowChunk(ScriptedTestCase):
|
| 111 |
+
ENGINE_KWARGS = base_engine_kwargs(
|
| 112 |
+
model_path=_SWA_MODEL,
|
| 113 |
+
chunked_prefill_size=_SWA_WINDOW // 2,
|
| 114 |
+
mem_fraction_static=0.70,
|
| 115 |
+
disable_piecewise_cuda_graph=True,
|
| 116 |
+
)
|
| 117 |
+
|
| 118 |
+
def test_swa_prompt_2x_window_half_chunks(self):
|
| 119 |
+
self.server.execute_script(self._script_swa_prompt_2x_window_half_chunks)
|
| 120 |
+
|
| 121 |
+
@staticmethod
|
| 122 |
+
def _script_swa_prompt_2x_window_half_chunks(t: ScriptedContext):
|
| 123 |
+
r = t.start_req(prompt_len=2 * _SWA_WINDOW, max_new_tokens=4)
|
| 124 |
+
yield from run_until_finished(r, max_steps=800)
|
| 125 |
+
assert r.finished
|
| 126 |
+
assert (
|
| 127 |
+
r.chunks_done >= 4
|
| 128 |
+
), f"expected >=4 chunks for 2*window / (window/2), got {r.chunks_done}"
|
| 129 |
+
assert len(r.req.output_ids) == 4
|
| 130 |
+
|
| 131 |
+
|
| 132 |
+
class TestSWAChunkSizeExceedsWindow(ScriptedTestCase):
|
| 133 |
+
ENGINE_KWARGS = base_engine_kwargs(
|
| 134 |
+
model_path=_SWA_MODEL,
|
| 135 |
+
chunked_prefill_size=_SWA_WINDOW * 2,
|
| 136 |
+
mem_fraction_static=0.70,
|
| 137 |
+
disable_piecewise_cuda_graph=True,
|
| 138 |
+
)
|
| 139 |
+
|
| 140 |
+
def test_swa_chunk_size_exceeds_window(self):
|
| 141 |
+
self.server.execute_script(self._script_swa_chunk_size_exceeds_window)
|
| 142 |
+
|
| 143 |
+
@staticmethod
|
| 144 |
+
def _script_swa_chunk_size_exceeds_window(t: ScriptedContext):
|
| 145 |
+
r = t.start_req(prompt_len=3 * _SWA_WINDOW, max_new_tokens=2)
|
| 146 |
+
yield from run_until_finished(r, max_steps=800)
|
| 147 |
+
assert r.finished
|
| 148 |
+
assert r.chunks_done >= 2
|
| 149 |
+
assert len(r.req.output_ids) == 2
|
| 150 |
+
|
| 151 |
+
|
| 152 |
+
class TestSWARadix(ScriptedTestCase):
|
| 153 |
+
ENGINE_KWARGS = base_engine_kwargs(
|
| 154 |
+
model_path=_SWA_MODEL,
|
| 155 |
+
chunked_prefill_size=DEFAULT_CHUNK_SIZE,
|
| 156 |
+
mem_fraction_static=0.70,
|
| 157 |
+
disable_radix_cache=False,
|
| 158 |
+
disable_piecewise_cuda_graph=True,
|
| 159 |
+
)
|
| 160 |
+
|
| 161 |
+
def test_swa_radix_partial_hit_straddles_window(self):
|
| 162 |
+
self.server.execute_script(self._script_swa_radix_partial_hit_straddles_window)
|
| 163 |
+
|
| 164 |
+
@staticmethod
|
| 165 |
+
def _script_swa_radix_partial_hit_straddles_window(t: ScriptedContext):
|
| 166 |
+
r1 = t.start_req(prompt_len=_SWA_WINDOW + DEFAULT_CHUNK_SIZE, max_new_tokens=2)
|
| 167 |
+
yield from run_until_finished(r1, max_steps=800)
|
| 168 |
+
assert r1.finished
|
| 169 |
+
r2 = t.start_req(
|
| 170 |
+
prompt_len=_SWA_WINDOW + DEFAULT_CHUNK_SIZE * 2, max_new_tokens=2
|
| 171 |
+
)
|
| 172 |
+
yield from run_until_finished(r2, max_steps=800)
|
| 173 |
+
assert r2.finished
|
| 174 |
+
assert (
|
| 175 |
+
r2.req.cached_tokens > 0
|
| 176 |
+
), f"r2 must hit the radix prefix, got cached_tokens={r2.req.cached_tokens}"
|
| 177 |
+
|
| 178 |
+
|
| 179 |
+
if __name__ == "__main__":
|
| 180 |
+
unittest.main()
|
asian_ai/performance/SGLang/test/manual/chunked_prefill/test_scripted_invariants.py
ADDED
|
@@ -0,0 +1,512 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import unittest
|
| 2 |
+
|
| 3 |
+
from sglang.test.scripted_runtime.context import ScriptedContext
|
| 4 |
+
from sglang.test.scripted_runtime.test_case import ScriptedTestCase
|
| 5 |
+
from sglang.test.scripted_runtime_chunked_helpers import (
|
| 6 |
+
DEFAULT_CHUNK_SIZE,
|
| 7 |
+
DEFAULT_MAX_STEPS,
|
| 8 |
+
VERY_LONG_PROMPT_LEN,
|
| 9 |
+
base_engine_kwargs,
|
| 10 |
+
run_until,
|
| 11 |
+
run_until_all_finished,
|
| 12 |
+
run_until_finished,
|
| 13 |
+
)
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
class TestInvariantsBasic(ScriptedTestCase):
|
| 17 |
+
ENGINE_KWARGS = base_engine_kwargs(chunked_prefill_size=DEFAULT_CHUNK_SIZE)
|
| 18 |
+
|
| 19 |
+
def test_kv_pages_zero_after_finish(self):
|
| 20 |
+
self.server.execute_script(self._script_kv_pages_zero_after_finish)
|
| 21 |
+
|
| 22 |
+
@staticmethod
|
| 23 |
+
def _script_kv_pages_zero_after_finish(t: ScriptedContext):
|
| 24 |
+
r = t.start_req(prompt_len=VERY_LONG_PROMPT_LEN, max_new_tokens=2)
|
| 25 |
+
yield from run_until_finished(r)
|
| 26 |
+
assert r.kv_pages == 0
|
| 27 |
+
|
| 28 |
+
def test_kv_pages_positive_continuously_mid_chunk(self):
|
| 29 |
+
self.server.execute_script(
|
| 30 |
+
self._script_kv_pages_positive_continuously_mid_chunk
|
| 31 |
+
)
|
| 32 |
+
|
| 33 |
+
@staticmethod
|
| 34 |
+
def _script_kv_pages_positive_continuously_mid_chunk(t: ScriptedContext):
|
| 35 |
+
r = t.start_req(prompt_len=VERY_LONG_PROMPT_LEN, max_new_tokens=2)
|
| 36 |
+
yield from run_until(r, lambda h: h.is_chunking)
|
| 37 |
+
observed_chunking = False
|
| 38 |
+
for _ in range(DEFAULT_MAX_STEPS):
|
| 39 |
+
if r.is_chunking:
|
| 40 |
+
observed_chunking = True
|
| 41 |
+
assert (
|
| 42 |
+
r.kv_pages > 0
|
| 43 |
+
), f"kv_pages must be > 0 while is_chunking; got {r.kv_pages}"
|
| 44 |
+
if r.finished:
|
| 45 |
+
break
|
| 46 |
+
yield
|
| 47 |
+
assert observed_chunking, "test must observe at least one mid-chunk iter"
|
| 48 |
+
assert r.finished
|
| 49 |
+
|
| 50 |
+
def test_batch_composition_consistent_with_status(self):
|
| 51 |
+
self.server.execute_script(
|
| 52 |
+
self._script_batch_composition_consistent_with_status
|
| 53 |
+
)
|
| 54 |
+
|
| 55 |
+
@staticmethod
|
| 56 |
+
def _script_batch_composition_consistent_with_status(t: ScriptedContext):
|
| 57 |
+
r = t.start_req(prompt_len=VERY_LONG_PROMPT_LEN, max_new_tokens=2)
|
| 58 |
+
for _ in range(DEFAULT_MAX_STEPS):
|
| 59 |
+
if r.status == "running":
|
| 60 |
+
comp = t.batch_composition()
|
| 61 |
+
all_rids = (
|
| 62 |
+
comp.get("prefill", [])
|
| 63 |
+
+ comp.get("decode", [])
|
| 64 |
+
+ comp.get("chunked", [])
|
| 65 |
+
)
|
| 66 |
+
assert (
|
| 67 |
+
r.rid in all_rids
|
| 68 |
+
), f"running but not in batch_composition: {comp}"
|
| 69 |
+
if r.finished:
|
| 70 |
+
return
|
| 71 |
+
yield
|
| 72 |
+
raise AssertionError("req never finished")
|
| 73 |
+
|
| 74 |
+
def test_active_reqs_listing(self):
|
| 75 |
+
self.server.execute_script(self._script_active_reqs_listing)
|
| 76 |
+
|
| 77 |
+
@staticmethod
|
| 78 |
+
def _script_active_reqs_listing(t: ScriptedContext):
|
| 79 |
+
r1 = t.start_req(prompt_len=16, max_new_tokens=4)
|
| 80 |
+
r2 = t.start_req(prompt_len=16, max_new_tokens=4)
|
| 81 |
+
yield
|
| 82 |
+
actives = t.list_active_reqs()
|
| 83 |
+
rids = {h.rid for h in actives}
|
| 84 |
+
assert r1.rid in rids or r2.rid in rids
|
| 85 |
+
yield from run_until_all_finished([r1, r2])
|
| 86 |
+
for _ in range(12):
|
| 87 |
+
actives_after = t.list_active_reqs()
|
| 88 |
+
if all(h.rid not in (r1.rid, r2.rid) for h in actives_after):
|
| 89 |
+
break
|
| 90 |
+
yield
|
| 91 |
+
actives_after = t.list_active_reqs()
|
| 92 |
+
assert all(h.rid not in (r1.rid, r2.rid) for h in actives_after)
|
| 93 |
+
|
| 94 |
+
def test_finished_means_chunks_done_stable(self):
|
| 95 |
+
self.server.execute_script(self._script_finished_means_chunks_done_stable)
|
| 96 |
+
|
| 97 |
+
@staticmethod
|
| 98 |
+
def _script_finished_means_chunks_done_stable(t: ScriptedContext):
|
| 99 |
+
r = t.start_req(prompt_len=VERY_LONG_PROMPT_LEN, max_new_tokens=2)
|
| 100 |
+
yield from run_until_finished(r)
|
| 101 |
+
snap = r.chunks_done
|
| 102 |
+
for _ in range(10):
|
| 103 |
+
yield
|
| 104 |
+
assert r.chunks_done == snap
|
| 105 |
+
|
| 106 |
+
def test_finished_means_kv_pages_stays_zero(self):
|
| 107 |
+
self.server.execute_script(self._script_finished_means_kv_pages_stays_zero)
|
| 108 |
+
|
| 109 |
+
@staticmethod
|
| 110 |
+
def _script_finished_means_kv_pages_stays_zero(t: ScriptedContext):
|
| 111 |
+
r = t.start_req(prompt_len=VERY_LONG_PROMPT_LEN, max_new_tokens=2)
|
| 112 |
+
yield from run_until_finished(r)
|
| 113 |
+
for _ in range(10):
|
| 114 |
+
yield
|
| 115 |
+
assert r.kv_pages == 0
|
| 116 |
+
|
| 117 |
+
def test_engine_stats_keys_present(self):
|
| 118 |
+
self.server.execute_script(self._script_engine_stats_keys_present)
|
| 119 |
+
|
| 120 |
+
@staticmethod
|
| 121 |
+
def _script_engine_stats_keys_present(t: ScriptedContext):
|
| 122 |
+
stats = t.engine_stats()
|
| 123 |
+
assert isinstance(stats, dict)
|
| 124 |
+
assert "kv_pool_free" in stats
|
| 125 |
+
assert "req_pool_free" in stats
|
| 126 |
+
yield
|
| 127 |
+
|
| 128 |
+
def test_kv_pool_recovers_to_baseline(self):
|
| 129 |
+
self.server.execute_script(self._script_kv_pool_recovers_to_baseline)
|
| 130 |
+
|
| 131 |
+
@staticmethod
|
| 132 |
+
def _script_kv_pool_recovers_to_baseline(t: ScriptedContext):
|
| 133 |
+
before = t.engine_stats()["kv_pool_free"]
|
| 134 |
+
reqs = [t.start_req(prompt_len=16, max_new_tokens=2) for _ in range(8)]
|
| 135 |
+
yield from run_until_all_finished(reqs)
|
| 136 |
+
for _ in range(40):
|
| 137 |
+
if t.is_fully_idle:
|
| 138 |
+
break
|
| 139 |
+
yield
|
| 140 |
+
t.flush_cache()
|
| 141 |
+
yield
|
| 142 |
+
after = t.engine_stats()["kv_pool_free"]
|
| 143 |
+
assert after >= before
|
| 144 |
+
|
| 145 |
+
def test_hundred_reqs_no_leak(self):
|
| 146 |
+
self.server.execute_script(self._script_hundred_reqs_no_leak)
|
| 147 |
+
|
| 148 |
+
@staticmethod
|
| 149 |
+
def _script_hundred_reqs_no_leak(t: ScriptedContext):
|
| 150 |
+
baseline = t.engine_stats()
|
| 151 |
+
reqs = [t.start_req(prompt_len=16, max_new_tokens=2) for _ in range(100)]
|
| 152 |
+
yield from run_until_all_finished(reqs, max_steps=4000)
|
| 153 |
+
for _ in range(40):
|
| 154 |
+
if t.is_fully_idle:
|
| 155 |
+
break
|
| 156 |
+
yield
|
| 157 |
+
t.flush_cache()
|
| 158 |
+
yield
|
| 159 |
+
final = t.engine_stats()
|
| 160 |
+
assert (
|
| 161 |
+
final["kv_pool_free"] >= baseline["kv_pool_free"]
|
| 162 |
+
), f"KV leak: {baseline['kv_pool_free']} -> {final['kv_pool_free']}"
|
| 163 |
+
assert final["req_pool_free"] >= baseline["req_pool_free"]
|
| 164 |
+
|
| 165 |
+
def test_long_lived_engine_reps_chunked(self):
|
| 166 |
+
self.server.execute_script(self._script_long_lived_engine_reps_chunked)
|
| 167 |
+
|
| 168 |
+
@staticmethod
|
| 169 |
+
def _script_long_lived_engine_reps_chunked(t: ScriptedContext):
|
| 170 |
+
baseline = t.engine_stats()
|
| 171 |
+
for _ in range(20):
|
| 172 |
+
reqs = [
|
| 173 |
+
t.start_req(prompt_len=VERY_LONG_PROMPT_LEN, max_new_tokens=2)
|
| 174 |
+
for _ in range(5)
|
| 175 |
+
]
|
| 176 |
+
yield from run_until_all_finished(reqs, max_steps=2000)
|
| 177 |
+
for r in reqs:
|
| 178 |
+
assert r.finished
|
| 179 |
+
for _ in range(40):
|
| 180 |
+
if t.is_fully_idle:
|
| 181 |
+
break
|
| 182 |
+
yield
|
| 183 |
+
t.flush_cache()
|
| 184 |
+
yield
|
| 185 |
+
final = t.engine_stats()
|
| 186 |
+
assert final["kv_pool_free"] >= baseline["kv_pool_free"]
|
| 187 |
+
|
| 188 |
+
def test_sustained_long_chunked_load(self):
|
| 189 |
+
self.server.execute_script(self._script_sustained_long_chunked_load)
|
| 190 |
+
|
| 191 |
+
@staticmethod
|
| 192 |
+
def _script_sustained_long_chunked_load(t: ScriptedContext):
|
| 193 |
+
expected_chunks_done = VERY_LONG_PROMPT_LEN // DEFAULT_CHUNK_SIZE
|
| 194 |
+
baseline_kv = t.engine_stats()["kv_pool_free"]
|
| 195 |
+
reqs = [
|
| 196 |
+
t.start_req(
|
| 197 |
+
prompt_len=VERY_LONG_PROMPT_LEN, max_new_tokens=2, prompt_token=10 + i
|
| 198 |
+
)
|
| 199 |
+
for i in range(30)
|
| 200 |
+
]
|
| 201 |
+
yield from run_until_all_finished(reqs, max_steps=DEFAULT_MAX_STEPS * 20)
|
| 202 |
+
for r in reqs:
|
| 203 |
+
assert r.finished
|
| 204 |
+
assert r.chunks_done == expected_chunks_done, (
|
| 205 |
+
f"VERY_LONG_PROMPT_LEN must take exactly {expected_chunks_done} "
|
| 206 |
+
f"chunks; got chunks_done={r.chunks_done}"
|
| 207 |
+
)
|
| 208 |
+
for _ in range(40):
|
| 209 |
+
if t.is_fully_idle:
|
| 210 |
+
break
|
| 211 |
+
yield
|
| 212 |
+
t.flush_cache()
|
| 213 |
+
yield
|
| 214 |
+
final_kv = t.engine_stats()["kv_pool_free"]
|
| 215 |
+
assert (
|
| 216 |
+
final_kv >= baseline_kv
|
| 217 |
+
), f"KV leak after sustained chunked load: {baseline_kv} -> {final_kv}"
|
| 218 |
+
|
| 219 |
+
def test_round_robin_short_and_chunked(self):
|
| 220 |
+
self.server.execute_script(self._script_round_robin_short_and_chunked)
|
| 221 |
+
|
| 222 |
+
@staticmethod
|
| 223 |
+
def _script_round_robin_short_and_chunked(t: ScriptedContext):
|
| 224 |
+
baseline = t.engine_stats()
|
| 225 |
+
for _ in range(5):
|
| 226 |
+
shorts = [t.start_req(prompt_len=16, max_new_tokens=2) for _ in range(10)]
|
| 227 |
+
chunked = [
|
| 228 |
+
t.start_req(prompt_len=VERY_LONG_PROMPT_LEN, max_new_tokens=2)
|
| 229 |
+
for _ in range(1)
|
| 230 |
+
]
|
| 231 |
+
yield from run_until_all_finished(shorts + chunked, max_steps=2000)
|
| 232 |
+
for r in shorts + chunked:
|
| 233 |
+
assert r.finished
|
| 234 |
+
for _ in range(40):
|
| 235 |
+
if t.is_fully_idle:
|
| 236 |
+
break
|
| 237 |
+
yield
|
| 238 |
+
t.flush_cache()
|
| 239 |
+
yield
|
| 240 |
+
final = t.engine_stats()
|
| 241 |
+
assert final["kv_pool_free"] >= baseline["kv_pool_free"]
|
| 242 |
+
|
| 243 |
+
def test_long_decode_then_many_short(self):
|
| 244 |
+
self.server.execute_script(self._script_long_decode_then_many_short)
|
| 245 |
+
|
| 246 |
+
@staticmethod
|
| 247 |
+
def _script_long_decode_then_many_short(t: ScriptedContext):
|
| 248 |
+
expected_chunks_done = VERY_LONG_PROMPT_LEN // DEFAULT_CHUNK_SIZE
|
| 249 |
+
long_max_new_tokens = 256
|
| 250 |
+
long_decode = t.start_req(
|
| 251 |
+
prompt_len=VERY_LONG_PROMPT_LEN,
|
| 252 |
+
max_new_tokens=long_max_new_tokens,
|
| 253 |
+
ignore_eos=True,
|
| 254 |
+
)
|
| 255 |
+
shorts = [t.start_req(prompt_len=8, max_new_tokens=2) for _ in range(50)]
|
| 256 |
+
all_reqs = [long_decode] + shorts
|
| 257 |
+
yield from run_until_all_finished(all_reqs, max_steps=DEFAULT_MAX_STEPS * 20)
|
| 258 |
+
for r in all_reqs:
|
| 259 |
+
assert r.finished
|
| 260 |
+
assert long_decode.chunks_done == expected_chunks_done, (
|
| 261 |
+
f"long req must chunk across exactly {expected_chunks_done} chunks; "
|
| 262 |
+
f"got chunks_done={long_decode.chunks_done}"
|
| 263 |
+
)
|
| 264 |
+
assert len(long_decode.req.output_ids) == long_max_new_tokens, (
|
| 265 |
+
f"ignore_eos long req must decode exactly {long_max_new_tokens} "
|
| 266 |
+
f"tokens; got len(output_ids)={len(long_decode.req.output_ids)}"
|
| 267 |
+
)
|
| 268 |
+
|
| 269 |
+
def test_engine_stats_monotone_after_each_batch(self):
|
| 270 |
+
self.server.execute_script(self._script_engine_stats_monotone_after_each_batch)
|
| 271 |
+
|
| 272 |
+
@staticmethod
|
| 273 |
+
def _script_engine_stats_monotone_after_each_batch(t: ScriptedContext):
|
| 274 |
+
last = None
|
| 275 |
+
for _ in range(10):
|
| 276 |
+
reqs = [t.start_req(prompt_len=16, max_new_tokens=2) for _ in range(8)]
|
| 277 |
+
yield from run_until_all_finished(reqs)
|
| 278 |
+
for _ in range(40):
|
| 279 |
+
if t.is_fully_idle:
|
| 280 |
+
break
|
| 281 |
+
yield
|
| 282 |
+
t.flush_cache()
|
| 283 |
+
yield
|
| 284 |
+
cur = t.engine_stats()["kv_pool_free"]
|
| 285 |
+
if last is not None:
|
| 286 |
+
assert cur >= last - 1, f"KV pool drifted: {last} -> {cur}"
|
| 287 |
+
last = cur
|
| 288 |
+
|
| 289 |
+
def test_inflight_middle_chunks_caps_at_one(self):
|
| 290 |
+
self.server.execute_script(self._script_inflight_middle_chunks_caps_at_one)
|
| 291 |
+
|
| 292 |
+
@staticmethod
|
| 293 |
+
def _script_inflight_middle_chunks_caps_at_one(t: ScriptedContext):
|
| 294 |
+
r = t.start_req(prompt_len=VERY_LONG_PROMPT_LEN, max_new_tokens=2)
|
| 295 |
+
running_max = 0
|
| 296 |
+
running_max_post_finish = 0
|
| 297 |
+
post_finish_samples = 0
|
| 298 |
+
for _ in range(DEFAULT_MAX_STEPS):
|
| 299 |
+
yield
|
| 300 |
+
req = r.req
|
| 301 |
+
cur = req.inflight_middle_chunks if req is not None else 0
|
| 302 |
+
running_max = max(running_max, cur)
|
| 303 |
+
if r.finished:
|
| 304 |
+
running_max_post_finish = max(running_max_post_finish, cur)
|
| 305 |
+
post_finish_samples += 1
|
| 306 |
+
if post_finish_samples >= 5:
|
| 307 |
+
break
|
| 308 |
+
assert r.finished, "req never finished"
|
| 309 |
+
assert running_max == 1, (
|
| 310 |
+
f"inflight_middle_chunks must reach exactly 1 across the chunked "
|
| 311 |
+
f"lifecycle (the cap from revert e875cd36e4); observed max={running_max}"
|
| 312 |
+
)
|
| 313 |
+
assert running_max_post_finish == 0, (
|
| 314 |
+
f"inflight_middle_chunks must be reset to 0 after finish; "
|
| 315 |
+
f"observed max post-finish={running_max_post_finish}"
|
| 316 |
+
)
|
| 317 |
+
|
| 318 |
+
def test_chunks_done_strictly_increases_no_plateaus(self):
|
| 319 |
+
self.server.execute_script(
|
| 320 |
+
self._script_chunks_done_strictly_increases_no_plateaus
|
| 321 |
+
)
|
| 322 |
+
|
| 323 |
+
@staticmethod
|
| 324 |
+
def _script_chunks_done_strictly_increases_no_plateaus(t: ScriptedContext):
|
| 325 |
+
r = t.start_req(prompt_len=VERY_LONG_PROMPT_LEN, max_new_tokens=2)
|
| 326 |
+
yield from run_until(r, lambda h: h.is_chunking)
|
| 327 |
+
prev_chunks_done = r.chunks_done
|
| 328 |
+
prev_was_chunking = r.is_chunking
|
| 329 |
+
for _ in range(DEFAULT_MAX_STEPS):
|
| 330 |
+
yield
|
| 331 |
+
if r.finished:
|
| 332 |
+
return
|
| 333 |
+
cur_chunks_done = r.chunks_done
|
| 334 |
+
cur_is_chunking = r.is_chunking
|
| 335 |
+
if prev_was_chunking and cur_is_chunking:
|
| 336 |
+
assert cur_chunks_done > prev_chunks_done, (
|
| 337 |
+
f"chunks_done plateau between consecutive mid-chunk "
|
| 338 |
+
f"yields: {prev_chunks_done} -> {cur_chunks_done}"
|
| 339 |
+
)
|
| 340 |
+
prev_chunks_done = cur_chunks_done
|
| 341 |
+
prev_was_chunking = cur_is_chunking
|
| 342 |
+
raise AssertionError("req never finished")
|
| 343 |
+
|
| 344 |
+
def test_output_tokens_len_equals_max_new_tokens_chunked(self):
|
| 345 |
+
self.server.execute_script(
|
| 346 |
+
self._script_output_tokens_len_equals_max_new_tokens_chunked
|
| 347 |
+
)
|
| 348 |
+
|
| 349 |
+
@staticmethod
|
| 350 |
+
def _script_output_tokens_len_equals_max_new_tokens_chunked(t: ScriptedContext):
|
| 351 |
+
n: int = 8
|
| 352 |
+
r = t.start_req(
|
| 353 |
+
prompt_len=VERY_LONG_PROMPT_LEN,
|
| 354 |
+
max_new_tokens=n,
|
| 355 |
+
ignore_eos=True,
|
| 356 |
+
)
|
| 357 |
+
yield from run_until_finished(r)
|
| 358 |
+
assert r.finished
|
| 359 |
+
assert (
|
| 360 |
+
r.chunks_done >= 2
|
| 361 |
+
), f"VERY_LONG_PROMPT_LEN should chunk; got chunks_done={r.chunks_done}"
|
| 362 |
+
assert len(r.req.output_ids) == n, (
|
| 363 |
+
f"ignore_eos=True + max_new_tokens={n} must produce exactly "
|
| 364 |
+
f"{n} output tokens; got len(output_tokens)={len(r.req.output_ids)}"
|
| 365 |
+
)
|
| 366 |
+
|
| 367 |
+
def test_num_input_tokens_equals_prompt_len_for_chunked(self):
|
| 368 |
+
self.server.execute_script(
|
| 369 |
+
self._script_num_input_tokens_equals_prompt_len_for_chunked
|
| 370 |
+
)
|
| 371 |
+
|
| 372 |
+
@staticmethod
|
| 373 |
+
def _script_num_input_tokens_equals_prompt_len_for_chunked(t: ScriptedContext):
|
| 374 |
+
prompt_len: int = VERY_LONG_PROMPT_LEN
|
| 375 |
+
r = t.start_req(prompt_len=prompt_len, max_new_tokens=2)
|
| 376 |
+
yield from run_until_finished(r)
|
| 377 |
+
assert r.finished
|
| 378 |
+
assert r.chunks_done >= 2, (
|
| 379 |
+
f"VERY_LONG_PROMPT_LEN should chunk so this invariant is exercised "
|
| 380 |
+
f"on a real multi-chunk prefill; got chunks_done={r.chunks_done}"
|
| 381 |
+
)
|
| 382 |
+
assert r.remaining_prompt_tokens == 0, (
|
| 383 |
+
f"the whole prompt must be committed after a chunked finish; "
|
| 384 |
+
f"remaining_prompt_tokens={r.remaining_prompt_tokens}"
|
| 385 |
+
)
|
| 386 |
+
|
| 387 |
+
def test_chunked_in_flight_count_exactly_zero_after_finish(self):
|
| 388 |
+
self.server.execute_script(
|
| 389 |
+
self._script_chunked_in_flight_count_exactly_zero_after_finish
|
| 390 |
+
)
|
| 391 |
+
|
| 392 |
+
@staticmethod
|
| 393 |
+
def _script_chunked_in_flight_count_exactly_zero_after_finish(t: ScriptedContext):
|
| 394 |
+
r = t.start_req(prompt_len=VERY_LONG_PROMPT_LEN, max_new_tokens=2)
|
| 395 |
+
yield from run_until(r, lambda h: h.is_chunking)
|
| 396 |
+
assert (1 if t.scheduler.chunked_req is not None else 0) == 1, (
|
| 397 |
+
f"chunked_in_flight_count should be 1 mid-chunk; got "
|
| 398 |
+
f"{(1 if t.scheduler.chunked_req is not None else 0)}"
|
| 399 |
+
)
|
| 400 |
+
yield from run_until_finished(r)
|
| 401 |
+
for _ in range(3):
|
| 402 |
+
yield
|
| 403 |
+
assert (1 if t.scheduler.chunked_req is not None else 0) == 0, (
|
| 404 |
+
f"chunked_in_flight_count must be 0 after finish; got "
|
| 405 |
+
f"{(1 if t.scheduler.chunked_req is not None else 0)}"
|
| 406 |
+
)
|
| 407 |
+
|
| 408 |
+
def test_extend_batch_idx_monotonic_invariant(self):
|
| 409 |
+
self.server.execute_script(self._script_extend_batch_idx_monotonic_invariant)
|
| 410 |
+
|
| 411 |
+
@staticmethod
|
| 412 |
+
def _script_extend_batch_idx_monotonic_invariant(t: ScriptedContext):
|
| 413 |
+
r = t.start_req(prompt_len=VERY_LONG_PROMPT_LEN, max_new_tokens=64)
|
| 414 |
+
observed_regression: bool = False
|
| 415 |
+
|
| 416 |
+
yield from run_until(
|
| 417 |
+
r,
|
| 418 |
+
lambda h: (
|
| 419 |
+
h.req is not None
|
| 420 |
+
and not h.req.is_retracted
|
| 421 |
+
and h.req.extend_batch_idx > 0
|
| 422 |
+
and h.remaining_prompt_tokens == 0
|
| 423 |
+
and not h.finished
|
| 424 |
+
),
|
| 425 |
+
)
|
| 426 |
+
pre_retract_idx: int = r.req.extend_batch_idx
|
| 427 |
+
assert not r.req.is_retracted
|
| 428 |
+
|
| 429 |
+
t.pause_generation(mode="retract")
|
| 430 |
+
retracted = t.find_req_by_rid(r.rid)
|
| 431 |
+
assert retracted is not None, "retracted req must stay live in the queue"
|
| 432 |
+
if retracted.extend_batch_idx < pre_retract_idx:
|
| 433 |
+
observed_regression = True
|
| 434 |
+
assert retracted.is_retracted, (
|
| 435 |
+
f"extend_batch_idx regressed without retract flag: "
|
| 436 |
+
f"{pre_retract_idx} -> {retracted.extend_batch_idx}"
|
| 437 |
+
)
|
| 438 |
+
t.continue_generation()
|
| 439 |
+
|
| 440 |
+
prev_extend_batch_idx: int = -1
|
| 441 |
+
regressions: int = 0
|
| 442 |
+
for _ in range(DEFAULT_MAX_STEPS):
|
| 443 |
+
req = t.find_req_by_rid(r.rid)
|
| 444 |
+
if req is not None:
|
| 445 |
+
cur_extend_batch_idx = req.extend_batch_idx
|
| 446 |
+
if (
|
| 447 |
+
prev_extend_batch_idx >= 0
|
| 448 |
+
and cur_extend_batch_idx < prev_extend_batch_idx
|
| 449 |
+
):
|
| 450 |
+
regressions += 1
|
| 451 |
+
observed_regression = True
|
| 452 |
+
assert regressions == 1, (
|
| 453 |
+
f"extend_batch_idx regressed more than once for a single "
|
| 454 |
+
f"retract episode: "
|
| 455 |
+
f"{prev_extend_batch_idx} -> {cur_extend_batch_idx}"
|
| 456 |
+
)
|
| 457 |
+
prev_extend_batch_idx = cur_extend_batch_idx
|
| 458 |
+
if r.finished:
|
| 459 |
+
break
|
| 460 |
+
yield
|
| 461 |
+
assert r.finished, "req never finished"
|
| 462 |
+
assert observed_regression, (
|
| 463 |
+
"retract must reset extend_batch_idx, producing the regression this "
|
| 464 |
+
"test guards"
|
| 465 |
+
)
|
| 466 |
+
|
| 467 |
+
def test_inflight_decrement_only_on_final_invariant(self):
|
| 468 |
+
self.server.execute_script(
|
| 469 |
+
self._script_inflight_decrement_only_on_final_invariant
|
| 470 |
+
)
|
| 471 |
+
|
| 472 |
+
@staticmethod
|
| 473 |
+
def _script_inflight_decrement_only_on_final_invariant(t: ScriptedContext):
|
| 474 |
+
r = t.start_req(prompt_len=VERY_LONG_PROMPT_LEN, max_new_tokens=2)
|
| 475 |
+
prev_inflight: int = 0
|
| 476 |
+
prev_was_chunked_slot: bool = False
|
| 477 |
+
prev_finished: bool = False
|
| 478 |
+
observed_decrement: bool = False
|
| 479 |
+
for _ in range(DEFAULT_MAX_STEPS):
|
| 480 |
+
s = t.scheduler
|
| 481 |
+
req = t.find_req_by_rid(r.rid)
|
| 482 |
+
cur_inflight = req.inflight_middle_chunks if req is not None else 0
|
| 483 |
+
cur_is_chunked_slot = (
|
| 484 |
+
s.chunked_req is not None and s.chunked_req.rid == r.rid
|
| 485 |
+
)
|
| 486 |
+
cur_finished = req.finished() if req is not None else True
|
| 487 |
+
if cur_inflight < prev_inflight:
|
| 488 |
+
observed_decrement = True
|
| 489 |
+
slot_just_released = prev_was_chunked_slot and not cur_is_chunked_slot
|
| 490 |
+
finish_just_happened = (not prev_finished) and cur_finished
|
| 491 |
+
assert slot_just_released or finish_just_happened, (
|
| 492 |
+
f"inflight_middle_chunks decreased ({prev_inflight} -> "
|
| 493 |
+
f"{cur_inflight}) without chunked slot release or req "
|
| 494 |
+
f"finish; prev_was_chunked_slot={prev_was_chunked_slot}, "
|
| 495 |
+
f"cur_is_chunked_slot={cur_is_chunked_slot}, "
|
| 496 |
+
f"prev_finished={prev_finished}, cur_finished={cur_finished}"
|
| 497 |
+
)
|
| 498 |
+
prev_inflight = cur_inflight
|
| 499 |
+
prev_was_chunked_slot = cur_is_chunked_slot
|
| 500 |
+
prev_finished = cur_finished
|
| 501 |
+
if r.finished:
|
| 502 |
+
break
|
| 503 |
+
yield
|
| 504 |
+
assert r.finished
|
| 505 |
+
assert observed_decrement, (
|
| 506 |
+
"test must observe at least one inflight_middle_chunks decrement "
|
| 507 |
+
"across the chunked lifecycle"
|
| 508 |
+
)
|
| 509 |
+
|
| 510 |
+
|
| 511 |
+
if __name__ == "__main__":
|
| 512 |
+
unittest.main()
|
asian_ai/performance/SGLang/test/manual/chunked_prefill/test_scripted_kv_pressure.py
ADDED
|
@@ -0,0 +1,550 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import unittest
|
| 2 |
+
|
| 3 |
+
from sglang.test.scripted_runtime.context import ScriptedContext
|
| 4 |
+
from sglang.test.scripted_runtime.test_case import ScriptedTestCase
|
| 5 |
+
from sglang.test.scripted_runtime_chunked_helpers import (
|
| 6 |
+
BALLAST_MAX_NEW_TOKENS,
|
| 7 |
+
DEFAULT_CHUNK_SIZE,
|
| 8 |
+
DEFAULT_MAX_STEPS,
|
| 9 |
+
SMALL_KV_POOL_BALLAST_MAX_NEW_TOKENS,
|
| 10 |
+
SMALL_KV_POOL_BALLAST_PROMPT_LEN,
|
| 11 |
+
SMALL_KV_POOL_MAX_TOTAL_TOKENS,
|
| 12 |
+
VERY_LONG_PROMPT_LEN,
|
| 13 |
+
base_engine_kwargs,
|
| 14 |
+
run_until,
|
| 15 |
+
run_until_all_finished,
|
| 16 |
+
run_until_finished,
|
| 17 |
+
)
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
class TestKVPressureBasic(ScriptedTestCase):
|
| 21 |
+
ENGINE_KWARGS = base_engine_kwargs(chunked_prefill_size=DEFAULT_CHUNK_SIZE)
|
| 22 |
+
|
| 23 |
+
def test_lock_refs_tight_concurrent_prefix(self):
|
| 24 |
+
self.server.execute_script(self._script_lock_refs_tight_concurrent_prefix)
|
| 25 |
+
|
| 26 |
+
@staticmethod
|
| 27 |
+
def _script_lock_refs_tight_concurrent_prefix(t: ScriptedContext):
|
| 28 |
+
warm_token = 7
|
| 29 |
+
warm_len = DEFAULT_CHUNK_SIZE
|
| 30 |
+
r_warm = t.start_req(
|
| 31 |
+
prompt_len=warm_len, max_new_tokens=1, prompt_token=warm_token
|
| 32 |
+
)
|
| 33 |
+
yield from run_until_finished(r_warm)
|
| 34 |
+
r_warm2 = t.start_req(prompt_len=warm_len, max_new_tokens=1, prompt_token=8)
|
| 35 |
+
yield from run_until_finished(r_warm2)
|
| 36 |
+
assert r_warm.finished
|
| 37 |
+
for _ in range(12):
|
| 38 |
+
if r_warm.lock_refs == 0:
|
| 39 |
+
break
|
| 40 |
+
yield
|
| 41 |
+
assert r_warm.lock_refs == 0
|
| 42 |
+
|
| 43 |
+
baseline_lock_refs = t.get_all_node_lock_refs()
|
| 44 |
+
|
| 45 |
+
t.exhaust_lock_refs(leave_refs=1)
|
| 46 |
+
yield
|
| 47 |
+
pinned_lock_refs = t.get_all_node_lock_refs()
|
| 48 |
+
assert any(
|
| 49 |
+
pinned_lock_refs.get(node_id, 0) > baseline_lock_refs.get(node_id, 0)
|
| 50 |
+
for node_id in pinned_lock_refs
|
| 51 |
+
), "exhaust_lock_refs(leave_refs=1) must pin at least one warm-prefix node"
|
| 52 |
+
|
| 53 |
+
r_long = t.start_req(
|
| 54 |
+
prompt_len=VERY_LONG_PROMPT_LEN,
|
| 55 |
+
max_new_tokens=2,
|
| 56 |
+
prompt_token=warm_token,
|
| 57 |
+
)
|
| 58 |
+
yield from run_until(r_long, lambda h: h.is_chunking)
|
| 59 |
+
yield from run_until_finished(r_long, max_steps=2000)
|
| 60 |
+
assert r_long.finished
|
| 61 |
+
assert r_long.chunks_done >= 2, (
|
| 62 |
+
f"long req must really chunk under pinned cache; got chunks_done="
|
| 63 |
+
f"{r_long.chunks_done}"
|
| 64 |
+
)
|
| 65 |
+
assert (
|
| 66 |
+
r_long.lock_refs == 0
|
| 67 |
+
), f"req {r_long.rid} leaked {r_long.lock_refs} lock_refs after finish"
|
| 68 |
+
|
| 69 |
+
t._release_exhausted_pools()
|
| 70 |
+
final_lock_refs = t.get_all_node_lock_refs()
|
| 71 |
+
for node_id, baseline in baseline_lock_refs.items():
|
| 72 |
+
assert final_lock_refs.get(node_id, 0) == baseline, (
|
| 73 |
+
f"node {node_id} lock_ref leaked: baseline={baseline}, "
|
| 74 |
+
f"final={final_lock_refs.get(node_id, 0)}"
|
| 75 |
+
)
|
| 76 |
+
|
| 77 |
+
def test_kv_pressure_with_retract_resume(self):
|
| 78 |
+
self.server.execute_script(self._script_kv_pressure_with_retract_resume)
|
| 79 |
+
|
| 80 |
+
@staticmethod
|
| 81 |
+
def _script_kv_pressure_with_retract_resume(t: ScriptedContext):
|
| 82 |
+
baseline = t.engine_stats()["kv_pool_free"]
|
| 83 |
+
r = t.start_req(
|
| 84 |
+
prompt_len=VERY_LONG_PROMPT_LEN, max_new_tokens=2, prompt_token=60
|
| 85 |
+
)
|
| 86 |
+
yield from run_until(r, lambda h: h.is_chunking)
|
| 87 |
+
chunks_before_retract = r.chunks_done
|
| 88 |
+
t.pause_generation(mode="retract")
|
| 89 |
+
yield
|
| 90 |
+
t.continue_generation()
|
| 91 |
+
yield from run_until(
|
| 92 |
+
r,
|
| 93 |
+
lambda h: h.chunks_done > chunks_before_retract,
|
| 94 |
+
max_steps=2000,
|
| 95 |
+
)
|
| 96 |
+
yield from run_until_finished(r, max_steps=2000)
|
| 97 |
+
assert r.finished
|
| 98 |
+
assert r.kv_pages == 0
|
| 99 |
+
for _ in range(40):
|
| 100 |
+
if t.is_fully_idle:
|
| 101 |
+
break
|
| 102 |
+
yield
|
| 103 |
+
t.flush_cache()
|
| 104 |
+
yield
|
| 105 |
+
final = t.engine_stats()["kv_pool_free"]
|
| 106 |
+
assert final >= baseline, (
|
| 107 |
+
f"KV pool failed to recover after retract+resume: "
|
| 108 |
+
f"baseline={baseline}, final={final}"
|
| 109 |
+
)
|
| 110 |
+
|
| 111 |
+
def test_chunked_batch_recovers_pools_to_steady_state(self):
|
| 112 |
+
self.server.execute_script(
|
| 113 |
+
self._script_chunked_batch_recovers_pools_to_steady_state
|
| 114 |
+
)
|
| 115 |
+
|
| 116 |
+
@staticmethod
|
| 117 |
+
def _script_chunked_batch_recovers_pools_to_steady_state(t: ScriptedContext):
|
| 118 |
+
before = t.engine_stats()
|
| 119 |
+
reqs = [
|
| 120 |
+
t.start_req(
|
| 121 |
+
prompt_len=DEFAULT_CHUNK_SIZE + 1,
|
| 122 |
+
max_new_tokens=2,
|
| 123 |
+
prompt_token=500 + i,
|
| 124 |
+
)
|
| 125 |
+
for i in range(50)
|
| 126 |
+
]
|
| 127 |
+
yield from run_until_all_finished(reqs, max_steps=2000)
|
| 128 |
+
for r in reqs:
|
| 129 |
+
assert r.finished
|
| 130 |
+
assert r.kv_pages == 0, f"req {r.rid} kept {r.kv_pages} pages after finish"
|
| 131 |
+
for _ in range(40):
|
| 132 |
+
if t.is_fully_idle:
|
| 133 |
+
break
|
| 134 |
+
yield
|
| 135 |
+
t.flush_cache()
|
| 136 |
+
yield
|
| 137 |
+
after = t.engine_stats()
|
| 138 |
+
assert after["kv_pool_free"] >= before["kv_pool_free"], (
|
| 139 |
+
f"50 chunked reqs leaked KV: baseline={before['kv_pool_free']}, "
|
| 140 |
+
f"final={after['kv_pool_free']}"
|
| 141 |
+
)
|
| 142 |
+
assert after["req_pool_free"] >= before["req_pool_free"], (
|
| 143 |
+
f"50 chunked reqs leaked req-pool rows: "
|
| 144 |
+
f"baseline={before['req_pool_free']}, final={after['req_pool_free']}"
|
| 145 |
+
)
|
| 146 |
+
|
| 147 |
+
def test_chunked_retract_at_chunk_first_mid_last(self):
|
| 148 |
+
self.server.execute_script(self._script_chunked_retract_at_chunk_first_mid_last)
|
| 149 |
+
|
| 150 |
+
@staticmethod
|
| 151 |
+
def _script_chunked_retract_at_chunk_first_mid_last(t: ScriptedContext):
|
| 152 |
+
expected_chunks = VERY_LONG_PROMPT_LEN // DEFAULT_CHUNK_SIZE
|
| 153 |
+
mid_chunk = expected_chunks // 2
|
| 154 |
+
last_minus_one = max(1, expected_chunks - 1)
|
| 155 |
+
|
| 156 |
+
r_first = t.start_req(
|
| 157 |
+
prompt_len=VERY_LONG_PROMPT_LEN, max_new_tokens=2, prompt_token=31
|
| 158 |
+
)
|
| 159 |
+
yield from run_until(r_first, lambda h: h.is_chunking)
|
| 160 |
+
t.pause_generation(mode="retract")
|
| 161 |
+
yield
|
| 162 |
+
t.continue_generation()
|
| 163 |
+
yield from run_until_finished(r_first, max_steps=2000)
|
| 164 |
+
assert r_first.finished
|
| 165 |
+
assert r_first.kv_pages == 0
|
| 166 |
+
|
| 167 |
+
r_mid = t.start_req(
|
| 168 |
+
prompt_len=VERY_LONG_PROMPT_LEN, max_new_tokens=2, prompt_token=32
|
| 169 |
+
)
|
| 170 |
+
yield from run_until(r_mid, lambda h: h.chunks_done >= mid_chunk)
|
| 171 |
+
t.pause_generation(mode="retract")
|
| 172 |
+
yield
|
| 173 |
+
t.continue_generation()
|
| 174 |
+
yield from run_until_finished(r_mid, max_steps=2000)
|
| 175 |
+
assert r_mid.finished
|
| 176 |
+
assert r_mid.kv_pages == 0
|
| 177 |
+
|
| 178 |
+
r_last = t.start_req(
|
| 179 |
+
prompt_len=VERY_LONG_PROMPT_LEN, max_new_tokens=2, prompt_token=33
|
| 180 |
+
)
|
| 181 |
+
yield from run_until(r_last, lambda h: h.chunks_done >= last_minus_one)
|
| 182 |
+
t.pause_generation(mode="retract")
|
| 183 |
+
yield
|
| 184 |
+
t.continue_generation()
|
| 185 |
+
yield from run_until_finished(r_last, max_steps=2000)
|
| 186 |
+
assert r_last.finished
|
| 187 |
+
assert r_last.kv_pages == 0
|
| 188 |
+
|
| 189 |
+
def test_flush_cache_during_chunked_in_flight(self):
|
| 190 |
+
self.server.execute_script(self._script_flush_cache_during_chunked_in_flight)
|
| 191 |
+
|
| 192 |
+
@staticmethod
|
| 193 |
+
def _script_flush_cache_during_chunked_in_flight(t: ScriptedContext):
|
| 194 |
+
r_warm = t.start_req(
|
| 195 |
+
prompt_len=VERY_LONG_PROMPT_LEN, max_new_tokens=1, prompt_token=41
|
| 196 |
+
)
|
| 197 |
+
yield from run_until_finished(r_warm)
|
| 198 |
+
assert r_warm.finished
|
| 199 |
+
|
| 200 |
+
r = t.start_req(
|
| 201 |
+
prompt_len=VERY_LONG_PROMPT_LEN, max_new_tokens=2, prompt_token=42
|
| 202 |
+
)
|
| 203 |
+
yield from run_until(r, lambda h: h.is_chunking and h.chunks_done >= 1)
|
| 204 |
+
t.flush_cache()
|
| 205 |
+
yield from run_until_finished(r, max_steps=2000)
|
| 206 |
+
assert r.finished
|
| 207 |
+
assert r.kv_pages == 0
|
| 208 |
+
|
| 209 |
+
def test_chunked_oscillation_three_force_retracts(self):
|
| 210 |
+
self.server.execute_script(
|
| 211 |
+
self._script_chunked_oscillation_three_force_retracts
|
| 212 |
+
)
|
| 213 |
+
|
| 214 |
+
@staticmethod
|
| 215 |
+
def _script_chunked_oscillation_three_force_retracts(t: ScriptedContext):
|
| 216 |
+
r = t.start_req(
|
| 217 |
+
prompt_len=VERY_LONG_PROMPT_LEN, max_new_tokens=2, prompt_token=70
|
| 218 |
+
)
|
| 219 |
+
yield from run_until(r, lambda h: h.is_chunking)
|
| 220 |
+
chunks_at_first = r.chunks_done
|
| 221 |
+
t.pause_generation(mode="retract")
|
| 222 |
+
yield
|
| 223 |
+
t.continue_generation()
|
| 224 |
+
yield from run_until(
|
| 225 |
+
r,
|
| 226 |
+
lambda h: h.is_chunking and h.chunks_done >= chunks_at_first,
|
| 227 |
+
max_steps=800,
|
| 228 |
+
)
|
| 229 |
+
chunks_after_first_resume = r.chunks_done
|
| 230 |
+
assert chunks_after_first_resume >= chunks_at_first, (
|
| 231 |
+
f"chunks_done regressed across retract: "
|
| 232 |
+
f"before={chunks_at_first}, after={chunks_after_first_resume}"
|
| 233 |
+
)
|
| 234 |
+
|
| 235 |
+
t.pause_generation(mode="retract")
|
| 236 |
+
yield
|
| 237 |
+
t.continue_generation()
|
| 238 |
+
yield from run_until(
|
| 239 |
+
r,
|
| 240 |
+
lambda h: h.is_chunking and h.chunks_done >= chunks_after_first_resume,
|
| 241 |
+
max_steps=800,
|
| 242 |
+
)
|
| 243 |
+
chunks_after_second_resume = r.chunks_done
|
| 244 |
+
assert chunks_after_second_resume >= chunks_after_first_resume
|
| 245 |
+
|
| 246 |
+
t.pause_generation(mode="retract")
|
| 247 |
+
yield
|
| 248 |
+
t.continue_generation()
|
| 249 |
+
yield from run_until_finished(r, max_steps=2000)
|
| 250 |
+
assert r.finished
|
| 251 |
+
assert r.chunks_done >= chunks_after_second_resume
|
| 252 |
+
|
| 253 |
+
|
| 254 |
+
class TestKVPressureSmallRowPool(ScriptedTestCase):
|
| 255 |
+
ENGINE_KWARGS = base_engine_kwargs(
|
| 256 |
+
chunked_prefill_size=DEFAULT_CHUNK_SIZE,
|
| 257 |
+
max_running_requests=8,
|
| 258 |
+
)
|
| 259 |
+
|
| 260 |
+
def test_row_pool_tight_admits_after_release(self):
|
| 261 |
+
self.server.execute_script(self._script_row_pool_tight_admits_after_release)
|
| 262 |
+
|
| 263 |
+
@staticmethod
|
| 264 |
+
def _script_row_pool_tight_admits_after_release(t: ScriptedContext):
|
| 265 |
+
baseline_rows_used = (
|
| 266 |
+
t.scheduler.req_to_token_pool.size
|
| 267 |
+
- t.scheduler.req_to_token_pool.available_size()
|
| 268 |
+
)
|
| 269 |
+
row_pool_size = t.scheduler.req_to_token_pool.size
|
| 270 |
+
ballast = [
|
| 271 |
+
t.start_req(
|
| 272 |
+
prompt_len=1, max_new_tokens=BALLAST_MAX_NEW_TOKENS, ignore_eos=True
|
| 273 |
+
)
|
| 274 |
+
for _ in range(row_pool_size)
|
| 275 |
+
]
|
| 276 |
+
for _ in range(DEFAULT_MAX_STEPS):
|
| 277 |
+
if t.scheduler.req_to_token_pool.available_size() == 0:
|
| 278 |
+
break
|
| 279 |
+
yield
|
| 280 |
+
assert t.scheduler.req_to_token_pool.available_size() == 0, (
|
| 281 |
+
f"ballast must hold every row; "
|
| 282 |
+
f"available={t.scheduler.req_to_token_pool.available_size()}"
|
| 283 |
+
)
|
| 284 |
+
|
| 285 |
+
reqs = [
|
| 286 |
+
t.start_req(prompt_len=8, max_new_tokens=1, prompt_token=50 + i)
|
| 287 |
+
for i in range(5)
|
| 288 |
+
]
|
| 289 |
+
for _ in range(6):
|
| 290 |
+
yield
|
| 291 |
+
for r in reqs:
|
| 292 |
+
assert r.status == "waiting", (
|
| 293 |
+
f"fresh req must be unschedulable under a full row pool; "
|
| 294 |
+
f"rid={r.rid}, status={r.status}"
|
| 295 |
+
)
|
| 296 |
+
|
| 297 |
+
for b in ballast:
|
| 298 |
+
t.abort(b)
|
| 299 |
+
yield from run_until_all_finished(reqs, max_steps=2000)
|
| 300 |
+
for r in reqs:
|
| 301 |
+
assert r.finished, f"req {r.rid} did not finish after release"
|
| 302 |
+
assert r.kv_pages == 0, (
|
| 303 |
+
f"row-pool pressure must not leave KV held: rid={r.rid}, "
|
| 304 |
+
f"kv_pages={r.kv_pages}"
|
| 305 |
+
)
|
| 306 |
+
|
| 307 |
+
for _ in range(40):
|
| 308 |
+
if t.is_fully_idle:
|
| 309 |
+
break
|
| 310 |
+
yield
|
| 311 |
+
final_rows_used = (
|
| 312 |
+
t.scheduler.req_to_token_pool.size
|
| 313 |
+
- t.scheduler.req_to_token_pool.available_size()
|
| 314 |
+
)
|
| 315 |
+
assert final_rows_used <= baseline_rows_used, (
|
| 316 |
+
f"row pool leak after admit-after-release: baseline used="
|
| 317 |
+
f"{baseline_rows_used}, final used={final_rows_used}"
|
| 318 |
+
)
|
| 319 |
+
|
| 320 |
+
|
| 321 |
+
class TestKVPressureSmallPool(ScriptedTestCase):
|
| 322 |
+
ENGINE_KWARGS = base_engine_kwargs(
|
| 323 |
+
chunked_prefill_size=DEFAULT_CHUNK_SIZE,
|
| 324 |
+
max_total_tokens=SMALL_KV_POOL_MAX_TOTAL_TOKENS,
|
| 325 |
+
)
|
| 326 |
+
|
| 327 |
+
@staticmethod
|
| 328 |
+
def _start_ballast(t: ScriptedContext, *, prompt_token: int):
|
| 329 |
+
return t.start_req(
|
| 330 |
+
prompt_len=SMALL_KV_POOL_BALLAST_PROMPT_LEN,
|
| 331 |
+
max_new_tokens=SMALL_KV_POOL_BALLAST_MAX_NEW_TOKENS,
|
| 332 |
+
ignore_eos=True,
|
| 333 |
+
prompt_token=prompt_token,
|
| 334 |
+
)
|
| 335 |
+
|
| 336 |
+
def test_chunked_completes_when_ballast_retracted(self):
|
| 337 |
+
self.server.execute_script(
|
| 338 |
+
self._script_chunked_completes_when_ballast_retracted
|
| 339 |
+
)
|
| 340 |
+
|
| 341 |
+
@staticmethod
|
| 342 |
+
def _script_chunked_completes_when_ballast_retracted(t: ScriptedContext):
|
| 343 |
+
baseline = t.engine_stats()["kv_pool_free"]
|
| 344 |
+
r_chunk = t.start_req(
|
| 345 |
+
prompt_len=VERY_LONG_PROMPT_LEN, max_new_tokens=2, prompt_token=600
|
| 346 |
+
)
|
| 347 |
+
yield from run_until(r_chunk, lambda h: h.is_chunking and h.chunks_done >= 1)
|
| 348 |
+
|
| 349 |
+
ballast = TestKVPressureSmallPool._start_ballast(t, prompt_token=601)
|
| 350 |
+
|
| 351 |
+
ballast_retracted = False
|
| 352 |
+
for _ in range(2000):
|
| 353 |
+
if ballast.status == "waiting":
|
| 354 |
+
ballast_retracted = True
|
| 355 |
+
if r_chunk.finished:
|
| 356 |
+
break
|
| 357 |
+
yield
|
| 358 |
+
assert r_chunk.finished, (
|
| 359 |
+
f"chunked req must complete once the engine retracts the ballast under "
|
| 360 |
+
f"real KV pressure; status={r_chunk.status}, kv_pages={r_chunk.kv_pages}"
|
| 361 |
+
)
|
| 362 |
+
assert r_chunk.kv_pages == 0, f"kv_pages={r_chunk.kv_pages}"
|
| 363 |
+
assert r_chunk.lock_refs == 0, f"lock_refs={r_chunk.lock_refs}"
|
| 364 |
+
|
| 365 |
+
ballast_resolved = (
|
| 366 |
+
ballast_retracted
|
| 367 |
+
or ballast.finished
|
| 368 |
+
or ballast.status in ("waiting", "finished", "unknown")
|
| 369 |
+
)
|
| 370 |
+
assert ballast_resolved, (
|
| 371 |
+
f"ballast must be retracted/aborted under pressure; "
|
| 372 |
+
f"status={ballast.status}, retracted={ballast_retracted}"
|
| 373 |
+
)
|
| 374 |
+
|
| 375 |
+
t.abort(ballast)
|
| 376 |
+
for _ in range(200):
|
| 377 |
+
if t.is_fully_idle:
|
| 378 |
+
break
|
| 379 |
+
yield
|
| 380 |
+
t.flush_cache()
|
| 381 |
+
yield
|
| 382 |
+
final = t.engine_stats()["kv_pool_free"]
|
| 383 |
+
assert final >= baseline, (
|
| 384 |
+
f"KV pool not recovered after ballast-retract pressure: "
|
| 385 |
+
f"baseline={baseline}, final={final}"
|
| 386 |
+
)
|
| 387 |
+
|
| 388 |
+
def test_chunked_completes_under_ballast_then_aborts_chunked(self):
|
| 389 |
+
self.server.execute_script(
|
| 390 |
+
self._script_chunked_completes_under_ballast_then_aborts_chunked
|
| 391 |
+
)
|
| 392 |
+
|
| 393 |
+
@staticmethod
|
| 394 |
+
def _script_chunked_completes_under_ballast_then_aborts_chunked(
|
| 395 |
+
t: ScriptedContext,
|
| 396 |
+
):
|
| 397 |
+
baseline = t.engine_stats()["kv_pool_free"]
|
| 398 |
+
r_chunk = t.start_req(
|
| 399 |
+
prompt_len=VERY_LONG_PROMPT_LEN, max_new_tokens=2, prompt_token=610
|
| 400 |
+
)
|
| 401 |
+
yield from run_until(r_chunk, lambda h: h.is_chunking and h.chunks_done >= 1)
|
| 402 |
+
|
| 403 |
+
ballast = TestKVPressureSmallPool._start_ballast(t, prompt_token=611)
|
| 404 |
+
for _ in range(6):
|
| 405 |
+
yield
|
| 406 |
+
|
| 407 |
+
t.abort(r_chunk)
|
| 408 |
+
for _ in range(12):
|
| 409 |
+
if (
|
| 410 |
+
r_chunk.kv_pages == 0
|
| 411 |
+
and r_chunk.lock_refs == 0
|
| 412 |
+
and (r_chunk.req is None or r_chunk.req.req_pool_idx is None)
|
| 413 |
+
):
|
| 414 |
+
break
|
| 415 |
+
yield
|
| 416 |
+
assert r_chunk.kv_pages == 0, f"kv_pages={r_chunk.kv_pages}"
|
| 417 |
+
assert r_chunk.lock_refs == 0, f"lock_refs={r_chunk.lock_refs}"
|
| 418 |
+
assert r_chunk.req is None or r_chunk.req.req_pool_idx is None
|
| 419 |
+
|
| 420 |
+
t.abort(ballast)
|
| 421 |
+
for _ in range(200):
|
| 422 |
+
if t.is_fully_idle:
|
| 423 |
+
break
|
| 424 |
+
yield
|
| 425 |
+
t.flush_cache()
|
| 426 |
+
yield
|
| 427 |
+
final = t.engine_stats()["kv_pool_free"]
|
| 428 |
+
assert final >= baseline, (
|
| 429 |
+
f"KV pool not recovered after abort-under-pressure: "
|
| 430 |
+
f"baseline={baseline}, final={final}"
|
| 431 |
+
)
|
| 432 |
+
|
| 433 |
+
def test_kv_recovery_after_full(self):
|
| 434 |
+
self.server.execute_script(self._script_kv_recovery_after_full)
|
| 435 |
+
|
| 436 |
+
@staticmethod
|
| 437 |
+
def _script_kv_recovery_after_full(t: ScriptedContext):
|
| 438 |
+
baseline = t.engine_stats()["kv_pool_free"]
|
| 439 |
+
b1 = t.start_req(
|
| 440 |
+
prompt_len=SMALL_KV_POOL_BALLAST_PROMPT_LEN,
|
| 441 |
+
max_new_tokens=SMALL_KV_POOL_BALLAST_MAX_NEW_TOKENS,
|
| 442 |
+
ignore_eos=True,
|
| 443 |
+
prompt_token=620,
|
| 444 |
+
)
|
| 445 |
+
yield from run_until(b1, lambda h: h.status == "running")
|
| 446 |
+
|
| 447 |
+
big = t.start_req(prompt_len=2048, max_new_tokens=2, prompt_token=621)
|
| 448 |
+
yield from run_until(big, lambda h: h.is_chunking and h.chunks_done >= 2)
|
| 449 |
+
|
| 450 |
+
r = t.start_req(prompt_len=16, max_new_tokens=2)
|
| 451 |
+
yield
|
| 452 |
+
assert r.status == "waiting", (
|
| 453 |
+
f"16-token req must be unschedulable while the ballast and the "
|
| 454 |
+
f"mid-chunk req own the pool; status={r.status}"
|
| 455 |
+
)
|
| 456 |
+
|
| 457 |
+
t.abort(b1)
|
| 458 |
+
yield from run_until(big, lambda h: h.finished, max_steps=3000)
|
| 459 |
+
yield from run_until(r, lambda h: h.finished, max_steps=3000)
|
| 460 |
+
assert r.finished
|
| 461 |
+
assert r.kv_pages == 0
|
| 462 |
+
assert r.lock_refs == 0
|
| 463 |
+
|
| 464 |
+
for _ in range(40):
|
| 465 |
+
if t.is_fully_idle:
|
| 466 |
+
break
|
| 467 |
+
yield
|
| 468 |
+
t.flush_cache()
|
| 469 |
+
yield
|
| 470 |
+
final = t.engine_stats()["kv_pool_free"]
|
| 471 |
+
assert final >= baseline, (
|
| 472 |
+
f"pool must recover to baseline after release: "
|
| 473 |
+
f"baseline={baseline}, final={final}"
|
| 474 |
+
)
|
| 475 |
+
|
| 476 |
+
|
| 477 |
+
class TestKVPressurePriority(ScriptedTestCase):
|
| 478 |
+
ENGINE_KWARGS = base_engine_kwargs(
|
| 479 |
+
chunked_prefill_size=DEFAULT_CHUNK_SIZE,
|
| 480 |
+
enable_priority_scheduling=True,
|
| 481 |
+
)
|
| 482 |
+
|
| 483 |
+
def test_priority_preempt_multiple_chunked(self):
|
| 484 |
+
self.server.execute_script(self._script_priority_preempt_multiple_chunked)
|
| 485 |
+
|
| 486 |
+
@staticmethod
|
| 487 |
+
def _script_priority_preempt_multiple_chunked(t: ScriptedContext):
|
| 488 |
+
baseline = t.engine_stats()["kv_pool_free"]
|
| 489 |
+
r1 = t.start_req(
|
| 490 |
+
prompt_len=VERY_LONG_PROMPT_LEN, max_new_tokens=2, prompt_token=11
|
| 491 |
+
)
|
| 492 |
+
yield from run_until(r1, lambda h: h.is_chunking)
|
| 493 |
+
|
| 494 |
+
r2 = t.start_req(
|
| 495 |
+
prompt_len=VERY_LONG_PROMPT_LEN,
|
| 496 |
+
max_new_tokens=2,
|
| 497 |
+
priority=10,
|
| 498 |
+
prompt_token=12,
|
| 499 |
+
)
|
| 500 |
+
done = {r1.rid: False, r2.rid: False}
|
| 501 |
+
for _ in range(DEFAULT_MAX_STEPS * 4):
|
| 502 |
+
assert not (r1.is_chunking and r2.is_chunking), (
|
| 503 |
+
f"two reqs cannot share the chunked slot; "
|
| 504 |
+
f"r1.is_chunking={r1.is_chunking}, r2.is_chunking={r2.is_chunking}"
|
| 505 |
+
)
|
| 506 |
+
done[r1.rid] = done[r1.rid] or r1.finished
|
| 507 |
+
done[r2.rid] = done[r2.rid] or r2.finished
|
| 508 |
+
if all(done.values()):
|
| 509 |
+
break
|
| 510 |
+
yield
|
| 511 |
+
assert done[r1.rid] and done[r2.rid]
|
| 512 |
+
assert r1.kv_pages == 0
|
| 513 |
+
assert r2.kv_pages == 0
|
| 514 |
+
for _ in range(40):
|
| 515 |
+
if t.is_fully_idle:
|
| 516 |
+
break
|
| 517 |
+
yield
|
| 518 |
+
t.flush_cache()
|
| 519 |
+
yield
|
| 520 |
+
final = t.engine_stats()["kv_pool_free"]
|
| 521 |
+
assert final >= baseline, (
|
| 522 |
+
f"KV pool not fully released after preemption: "
|
| 523 |
+
f"baseline={baseline}, final={final}"
|
| 524 |
+
)
|
| 525 |
+
|
| 526 |
+
|
| 527 |
+
class TestKVPressurePageSize(ScriptedTestCase):
|
| 528 |
+
ENGINE_KWARGS = base_engine_kwargs(
|
| 529 |
+
chunked_prefill_size=DEFAULT_CHUNK_SIZE,
|
| 530 |
+
page_size=16,
|
| 531 |
+
)
|
| 532 |
+
|
| 533 |
+
def test_strict_mem_check_handles_chunked_tail(self):
|
| 534 |
+
self.server.execute_script(self._script_strict_mem_check_handles_chunked_tail)
|
| 535 |
+
|
| 536 |
+
@staticmethod
|
| 537 |
+
def _script_strict_mem_check_handles_chunked_tail(t: ScriptedContext):
|
| 538 |
+
r = t.start_req(prompt_len=VERY_LONG_PROMPT_LEN + 17, max_new_tokens=2)
|
| 539 |
+
yield from run_until(r, lambda h: h.is_chunking and h.chunks_done >= 1)
|
| 540 |
+
t.pause_generation(mode="retract")
|
| 541 |
+
yield
|
| 542 |
+
t.continue_generation()
|
| 543 |
+
yield from run_until_finished(r, max_steps=2000)
|
| 544 |
+
assert r.finished
|
| 545 |
+
assert r.kv_pages == 0
|
| 546 |
+
assert r.lock_refs == 0
|
| 547 |
+
|
| 548 |
+
|
| 549 |
+
if __name__ == "__main__":
|
| 550 |
+
unittest.main()
|
asian_ai/performance/SGLang/test/manual/chunked_prefill/test_scripted_lifecycle.py
AD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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import unittest
|
| 2 |
+
|
| 3 |
+
from sglang.srt.managers.schedule_batch import FINISH_ABORT
|
| 4 |
+
from sglang.test.scripted_runtime.context import ScriptedContext
|
| 5 |
+
from sglang.test.scripted_runtime.test_case import ScriptedTestCase
|
| 6 |
+
from sglang.test.scripted_runtime_chunked_helpers import (
|
| 7 |
+
DEFAULT_CHUNK_SIZE,
|
| 8 |
+
DEFAULT_MAX_STEPS,
|
| 9 |
+
VERY_LONG_PROMPT_LEN,
|
| 10 |
+
base_engine_kwargs,
|
| 11 |
+
run_until,
|
| 12 |
+
run_until_finished,
|
| 13 |
+
)
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
def _drain_until_released(t, *handles):
|
| 17 |
+
for _ in range(12):
|
| 18 |
+
if all(
|
| 19 |
+
h.kv_pages == 0
|
| 20 |
+
and h.lock_refs == 0
|
| 21 |
+
and (h.req is None or h.req.req_pool_idx is None)
|
| 22 |
+
for h in handles
|
| 23 |
+
):
|
| 24 |
+
return
|
| 25 |
+
yield
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
class TestLifecycleBasic(ScriptedTestCase):
|
| 29 |
+
ENGINE_KWARGS = base_engine_kwargs(chunked_prefill_size=DEFAULT_CHUNK_SIZE)
|
| 30 |
+
|
| 31 |
+
def test_small_prompt_short_decode(self):
|
| 32 |
+
self.server.execute_script(self._script_small_prompt_short_decode)
|
| 33 |
+
|
| 34 |
+
@staticmethod
|
| 35 |
+
def _script_small_prompt_short_decode(t: ScriptedContext):
|
| 36 |
+
r = t.start_req(prompt_len=8, max_new_tokens=2, ignore_eos=True)
|
| 37 |
+
yield from run_until_finished(r)
|
| 38 |
+
assert r.finished
|
| 39 |
+
assert r.chunks_done == 0
|
| 40 |
+
assert len(r.req.output_ids) == 2
|
| 41 |
+
|
| 42 |
+
def test_medium_prompt_medium_decode(self):
|
| 43 |
+
self.server.execute_script(self._script_medium_prompt_medium_decode)
|
| 44 |
+
|
| 45 |
+
@staticmethod
|
| 46 |
+
def _script_medium_prompt_medium_decode(t: ScriptedContext):
|
| 47 |
+
r = t.start_req(
|
| 48 |
+
prompt_len=DEFAULT_CHUNK_SIZE, max_new_tokens=16, ignore_eos=True
|
| 49 |
+
)
|
| 50 |
+
yield from run_until_finished(r)
|
| 51 |
+
assert r.finished
|
| 52 |
+
assert r.chunks_done == 0
|
| 53 |
+
assert len(r.req.output_ids) == 16
|
| 54 |
+
|
| 55 |
+
def test_long_prompt_short_decode(self):
|
| 56 |
+
self.server.execute_script(self._script_long_prompt_short_decode)
|
| 57 |
+
|
| 58 |
+
@staticmethod
|
| 59 |
+
def _script_long_prompt_short_decode(t: ScriptedContext):
|
| 60 |
+
r = t.start_req(
|
| 61 |
+
prompt_len=VERY_LONG_PROMPT_LEN, max_new_tokens=2, ignore_eos=True
|
| 62 |
+
)
|
| 63 |
+
yield from run_until_finished(r)
|
| 64 |
+
assert r.finished
|
| 65 |
+
assert r.chunks_done == 8
|
| 66 |
+
assert len(r.req.output_ids) == 2
|
| 67 |
+
|
| 68 |
+
def test_long_prompt_long_decode(self):
|
| 69 |
+
self.server.execute_script(self._script_long_prompt_long_decode)
|
| 70 |
+
|
| 71 |
+
@staticmethod
|
| 72 |
+
def _script_long_prompt_long_decode(t: ScriptedContext):
|
| 73 |
+
r = t.start_req(
|
| 74 |
+
prompt_len=VERY_LONG_PROMPT_LEN, max_new_tokens=64, ignore_eos=True
|
| 75 |
+
)
|
| 76 |
+
yield from run_until(r, lambda h: h.finished, max_steps=1000)
|
| 77 |
+
assert r.finished
|
| 78 |
+
assert r.chunks_done == 8
|
| 79 |
+
assert len(r.req.output_ids) == 64
|
| 80 |
+
|
| 81 |
+
def test_tiny_prompt_long_decode(self):
|
| 82 |
+
self.server.execute_script(self._script_tiny_prompt_long_decode)
|
| 83 |
+
|
| 84 |
+
@staticmethod
|
| 85 |
+
def _script_tiny_prompt_long_decode(t: ScriptedContext):
|
| 86 |
+
r = t.start_req(prompt_len=1, max_new_tokens=64, ignore_eos=True)
|
| 87 |
+
yield from run_until(r, lambda h: h.finished, max_steps=500)
|
| 88 |
+
assert r.finished
|
| 89 |
+
assert r.chunks_done == 0
|
| 90 |
+
assert len(r.req.output_ids) == 64
|
| 91 |
+
|
| 92 |
+
def test_chunk_size_minus_one_prompt(self):
|
| 93 |
+
self.server.execute_script(self._script_chunk_size_minus_one_prompt)
|
| 94 |
+
|
| 95 |
+
@staticmethod
|
| 96 |
+
def _script_chunk_size_minus_one_prompt(t: ScriptedContext):
|
| 97 |
+
r = t.start_req(
|
| 98 |
+
prompt_len=DEFAULT_CHUNK_SIZE - 1, max_new_tokens=4, ignore_eos=True
|
| 99 |
+
)
|
| 100 |
+
yield from run_until_finished(r)
|
| 101 |
+
assert r.finished
|
| 102 |
+
assert r.chunks_done == 0
|
| 103 |
+
assert len(r.req.output_ids) == 4
|
| 104 |
+
|
| 105 |
+
def test_chunk_size_plus_two_prompt(self):
|
| 106 |
+
self.server.execute_script(self._script_chunk_size_plus_two_prompt)
|
| 107 |
+
|
| 108 |
+
@staticmethod
|
| 109 |
+
def _script_chunk_size_plus_two_prompt(t: ScriptedContext):
|
| 110 |
+
r = t.start_req(
|
| 111 |
+
prompt_len=DEFAULT_CHUNK_SIZE + 2, max_new_tokens=4, ignore_eos=True
|
| 112 |
+
)
|
| 113 |
+
yield from run_until_finished(r)
|
| 114 |
+
assert r.finished
|
| 115 |
+
assert r.chunks_done == 2
|
| 116 |
+
assert len(r.req.output_ids) == 4
|
| 117 |
+
|
| 118 |
+
def test_just_over_2x_chunk_size(self):
|
| 119 |
+
self.server.execute_script(self._script_just_over_2x_chunk_size)
|
| 120 |
+
|
| 121 |
+
@staticmethod
|
| 122 |
+
def _script_just_over_2x_chunk_size(t: ScriptedContext):
|
| 123 |
+
r = t.start_req(
|
| 124 |
+
prompt_len=2 * DEFAULT_CHUNK_SIZE + 1, max_new_tokens=4, ignore_eos=True
|
| 125 |
+
)
|
| 126 |
+
yield from run_until_finished(r)
|
| 127 |
+
assert r.finished
|
| 128 |
+
assert r.chunks_done == 3
|
| 129 |
+
assert len(r.req.output_ids) == 4
|
| 130 |
+
|
| 131 |
+
def test_five_x_chunk_size(self):
|
| 132 |
+
self.server.execute_script(self._script_five_x_chunk_size)
|
| 133 |
+
|
| 134 |
+
@staticmethod
|
| 135 |
+
def _script_five_x_chunk_size(t: ScriptedContext):
|
| 136 |
+
r = t.start_req(
|
| 137 |
+
prompt_len=5 * DEFAULT_CHUNK_SIZE, max_new_tokens=4, ignore_eos=True
|
| 138 |
+
)
|
| 139 |
+
yield from run_until_finished(r)
|
| 140 |
+
assert r.finished
|
| 141 |
+
assert r.chunks_done == 5
|
| 142 |
+
assert len(r.req.output_ids) == 4
|
| 143 |
+
|
| 144 |
+
def test_ten_x_chunk_size(self):
|
| 145 |
+
self.server.execute_script(self._script_ten_x_chunk_size)
|
| 146 |
+
|
| 147 |
+
@staticmethod
|
| 148 |
+
def _script_ten_x_chunk_size(t: ScriptedContext):
|
| 149 |
+
r = t.start_req(
|
| 150 |
+
prompt_len=10 * DEFAULT_CHUNK_SIZE, max_new_tokens=2, ignore_eos=True
|
| 151 |
+
)
|
| 152 |
+
yield from run_until(r, lambda h: h.finished, max_steps=1000)
|
| 153 |
+
assert r.finished
|
| 154 |
+
assert r.chunks_done == 10
|
| 155 |
+
assert len(r.req.output_ids) == 2
|
| 156 |
+
|
| 157 |
+
def test_status_progression_happy_path(self):
|
| 158 |
+
self.server.execute_script(self._script_status_progression_happy_path)
|
| 159 |
+
|
| 160 |
+
@staticmethod
|
| 161 |
+
def _script_status_progression_happy_path(t: ScriptedContext):
|
| 162 |
+
r = t.start_req(prompt_len=16, max_new_tokens=2, ignore_eos=True)
|
| 163 |
+
seen = []
|
| 164 |
+
for _ in range(DEFAULT_MAX_STEPS):
|
| 165 |
+
seen.append(r.status)
|
| 166 |
+
if r.finished:
|
| 167 |
+
break
|
| 168 |
+
yield
|
| 169 |
+
else:
|
| 170 |
+
raise AssertionError("req did not finish within DEFAULT_MAX_STEPS")
|
| 171 |
+
assert "running" in seen, f"never observed running status; seen={seen}"
|
| 172 |
+
assert seen[-1] == "finished", f"final status must be finished; seen={seen}"
|
| 173 |
+
finished_idx = seen.index("finished")
|
| 174 |
+
assert all(
|
| 175 |
+
s in ("finished",) for s in seen[finished_idx:]
|
| 176 |
+
), f"status regressed after finish; seen={seen}"
|
| 177 |
+
|
| 178 |
+
def test_long_prompt_only_one_decode(self):
|
| 179 |
+
self.server.execute_script(self._script_long_prompt_only_one_decode)
|
| 180 |
+
|
| 181 |
+
@staticmethod
|
| 182 |
+
def _script_long_prompt_only_one_decode(t: ScriptedContext):
|
| 183 |
+
r = t.start_req(
|
| 184 |
+
prompt_len=VERY_LONG_PROMPT_LEN, max_new_tokens=1, ignore_eos=True
|
| 185 |
+
)
|
| 186 |
+
yield from run_until_finished(r)
|
| 187 |
+
assert r.finished
|
| 188 |
+
assert r.chunks_done == 8
|
| 189 |
+
assert len(r.req.output_ids) == 1
|
| 190 |
+
|
| 191 |
+
def test_kv_pages_consistent_during_run(self):
|
| 192 |
+
self.server.execute_script(self._script_kv_pages_consistent_during_run)
|
| 193 |
+
|
| 194 |
+
@staticmethod
|
| 195 |
+
def _script_kv_pages_consistent_during_run(t: ScriptedContext):
|
| 196 |
+
r = t.start_req(
|
| 197 |
+
prompt_len=VERY_LONG_PROMPT_LEN, max_new_tokens=4, ignore_eos=True
|
| 198 |
+
)
|
| 199 |
+
saw_positive = False
|
| 200 |
+
for _ in range(DEFAULT_MAX_STEPS):
|
| 201 |
+
pages = r.kv_pages
|
| 202 |
+
if pages > 0:
|
| 203 |
+
saw_positive = True
|
| 204 |
+
elif saw_positive and not r.finished:
|
| 205 |
+
raise AssertionError(
|
| 206 |
+
f"kv_pages collapsed to 0 mid-run before finish; "
|
| 207 |
+
f"saw_positive={saw_positive}, status={r.status!r}"
|
| 208 |
+
)
|
| 209 |
+
if r.finished:
|
| 210 |
+
break
|
| 211 |
+
yield
|
| 212 |
+
else:
|
| 213 |
+
raise AssertionError("req did not finish within DEFAULT_MAX_STEPS")
|
| 214 |
+
assert saw_positive
|
| 215 |
+
assert r.kv_pages == 0
|
| 216 |
+
assert len(r.req.output_ids) == 4
|
| 217 |
+
|
| 218 |
+
def test_row_idx_recycled_after_finish(self):
|
| 219 |
+
self.server.execute_script(self._script_row_idx_recycled_after_finish)
|
| 220 |
+
|
| 221 |
+
@staticmethod
|
| 222 |
+
def _script_row_idx_recycled_after_finish(t: ScriptedContext):
|
| 223 |
+
r = t.start_req(prompt_len=16, max_new_tokens=2, ignore_eos=True)
|
| 224 |
+
yield from run_until_finished(r)
|
| 225 |
+
assert r.finished
|
| 226 |
+
assert r.req.req_pool_idx is None
|
| 227 |
+
assert r.kv_pages == 0
|
| 228 |
+
assert r.lock_refs == 0
|
| 229 |
+
|
| 230 |
+
def test_two_seq_clean_handoff(self):
|
| 231 |
+
self.server.execute_script(self._script_two_seq_clean_handoff)
|
| 232 |
+
|
| 233 |
+
@staticmethod
|
| 234 |
+
def _script_two_seq_clean_handoff(t: ScriptedContext):
|
| 235 |
+
r1 = t.start_req(prompt_len=16, max_new_tokens=2, ignore_eos=True)
|
| 236 |
+
yield from run_until_finished(r1)
|
| 237 |
+
yield from _drain_until_released(t, r1)
|
| 238 |
+
assert r1.req.req_pool_idx is None and r1.kv_pages == 0 and r1.lock_refs == 0
|
| 239 |
+
r1_output_len = len(r1.req.output_ids)
|
| 240 |
+
|
| 241 |
+
r2 = t.start_req(prompt_len=16, max_new_tokens=2, ignore_eos=True)
|
| 242 |
+
yield from run_until_finished(r2)
|
| 243 |
+
yield from _drain_until_released(t, r2)
|
| 244 |
+
assert r1.finished and r2.finished
|
| 245 |
+
assert r1_output_len == 2 and len(r2.req.output_ids) == 2
|
| 246 |
+
assert r2.req.req_pool_idx is None and r2.kv_pages == 0 and r2.lock_refs == 0
|
| 247 |
+
|
| 248 |
+
def test_five_seq_clean(self):
|
| 249 |
+
self.server.execute_script(self._script_five_seq_clean)
|
| 250 |
+
|
| 251 |
+
@staticmethod
|
| 252 |
+
def _script_five_seq_clean(t: ScriptedContext):
|
| 253 |
+
reqs = []
|
| 254 |
+
for _ in range(5):
|
| 255 |
+
r = t.start_req(prompt_len=16, max_new_tokens=2, ignore_eos=True)
|
| 256 |
+
yield from run_until_finished(r)
|
| 257 |
+
assert r.finished
|
| 258 |
+
assert len(r.req.output_ids) == 2
|
| 259 |
+
assert r.req.req_pool_idx is None
|
| 260 |
+
assert r.kv_pages == 0
|
| 261 |
+
assert r.lock_refs == 0
|
| 262 |
+
reqs.append(r)
|
| 263 |
+
for r in reqs:
|
| 264 |
+
assert r.finished
|
| 265 |
+
|
| 266 |
+
def test_radix_partial_seq(self):
|
| 267 |
+
self.server.execute_script(self._script_radix_partial_seq)
|
| 268 |
+
|
| 269 |
+
@staticmethod
|
| 270 |
+
def _script_radix_partial_seq(t: ScriptedContext):
|
| 271 |
+
r1 = t.start_req(
|
| 272 |
+
prompt_len=DEFAULT_CHUNK_SIZE, max_new_tokens=1, ignore_eos=True
|
| 273 |
+
)
|
| 274 |
+
yield from run_until_finished(r1)
|
| 275 |
+
r2 = t.start_req(
|
| 276 |
+
prompt_len=DEFAULT_CHUNK_SIZE + 32, max_new_tokens=2, ignore_eos=True
|
| 277 |
+
)
|
| 278 |
+
yield from run_until_finished(r2)
|
| 279 |
+
assert r1.finished and r2.finished
|
| 280 |
+
assert r2.chunks_done == 0
|
| 281 |
+
assert r2.req.cached_tokens > 0, (
|
| 282 |
+
f"r2 must hit r1's radix prefix; got cached_tokens="
|
| 283 |
+
f"{r2.req.cached_tokens}"
|
| 284 |
+
)
|
| 285 |
+
assert len(r2.req.output_ids) == 2
|
| 286 |
+
|
| 287 |
+
def test_alternating_short_long_seq(self):
|
| 288 |
+
self.server.execute_script(self._script_alternating_short_long_seq)
|
| 289 |
+
|
| 290 |
+
@staticmethod
|
| 291 |
+
def _script_alternating_short_long_seq(t: ScriptedContext):
|
| 292 |
+
for i in range(6):
|
| 293 |
+
prompt = 8 if i % 2 == 0 else VERY_LONG_PROMPT_LEN
|
| 294 |
+
r = t.start_req(
|
| 295 |
+
prompt_len=prompt,
|
| 296 |
+
max_new_tokens=2,
|
| 297 |
+
ignore_eos=True,
|
| 298 |
+
prompt_token=10 + i,
|
| 299 |
+
)
|
| 300 |
+
yield from run_until_finished(r)
|
| 301 |
+
assert r.finished
|
| 302 |
+
assert len(r.req.output_ids) == 2
|
| 303 |
+
assert r.req.req_pool_idx is None and r.kv_pages == 0 and r.lock_refs == 0
|
| 304 |
+
if prompt == VERY_LONG_PROMPT_LEN:
|
| 305 |
+
assert r.chunks_done == 8
|
| 306 |
+
else:
|
| 307 |
+
assert r.chunks_done == 0
|
| 308 |
+
|
| 309 |
+
def test_seq_with_growing_prompt(self):
|
| 310 |
+
self.server.execute_script(self._script_seq_with_growing_prompt)
|
| 311 |
+
|
| 312 |
+
@staticmethod
|
| 313 |
+
def _script_seq_with_growing_prompt(t: ScriptedContext):
|
| 314 |
+
for idx, L in enumerate([8, 32, 128, 512, 1024]):
|
| 315 |
+
r = t.start_req(
|
| 316 |
+
prompt_len=L, max_new_tokens=1, ignore_eos=True, prompt_token=10 + idx
|
| 317 |
+
)
|
| 318 |
+
yield from run_until_finished(r)
|
| 319 |
+
assert r.finished
|
| 320 |
+
assert len(r.req.output_ids) == 1
|
| 321 |
+
yield from _drain_until_released(t, r)
|
| 322 |
+
assert r.req is None or r.req.req_pool_idx is None
|
| 323 |
+
assert r.kv_pages == 0 and r.lock_refs == 0
|
| 324 |
+
if L > DEFAULT_CHUNK_SIZE:
|
| 325 |
+
assert (
|
| 326 |
+
r.chunks_done == (L + DEFAULT_CHUNK_SIZE - 1) // DEFAULT_CHUNK_SIZE
|
| 327 |
+
)
|
| 328 |
+
else:
|
| 329 |
+
assert r.chunks_done == 0
|
| 330 |
+
|
| 331 |
+
def test_seq_with_shrinking_prompt(self):
|
| 332 |
+
self.server.execute_script(self._script_seq_with_shrinking_prompt)
|
| 333 |
+
|
| 334 |
+
@staticmethod
|
| 335 |
+
def _script_seq_with_shrinking_prompt(t: ScriptedContext):
|
| 336 |
+
for idx, L in enumerate([1024, 512, 128, 32, 8]):
|
| 337 |
+
r = t.start_req(
|
| 338 |
+
prompt_len=L, max_new_tokens=1, ignore_eos=True, prompt_token=10 + idx
|
| 339 |
+
)
|
| 340 |
+
yield from run_until_finished(r)
|
| 341 |
+
assert r.finished
|
| 342 |
+
assert len(r.req.output_ids) == 1
|
| 343 |
+
yield from _drain_until_released(t, r)
|
| 344 |
+
assert r.req is None or r.req.req_pool_idx is None
|
| 345 |
+
assert r.kv_pages == 0 and r.lock_refs == 0
|
| 346 |
+
if L > DEFAULT_CHUNK_SIZE:
|
| 347 |
+
assert (
|
| 348 |
+
r.chunks_done == (L + DEFAULT_CHUNK_SIZE - 1) // DEFAULT_CHUNK_SIZE
|
| 349 |
+
)
|
| 350 |
+
else:
|
| 351 |
+
assert r.chunks_done == 0
|
| 352 |
+
|
| 353 |
+
def test_seq_with_idle_yields_between(self):
|
| 354 |
+
self.server.execute_script(self._script_seq_with_idle_yields_between)
|
| 355 |
+
|
| 356 |
+
@staticmethod
|
| 357 |
+
def _script_seq_with_idle_yields_between(t: ScriptedContext):
|
| 358 |
+
for _ in range(4):
|
| 359 |
+
r = t.start_req(prompt_len=16, max_new_tokens=2, ignore_eos=True)
|
| 360 |
+
yield from run_until_finished(r)
|
| 361 |
+
assert r.finished
|
| 362 |
+
assert len(r.req.output_ids) == 2
|
| 363 |
+
assert r.req.req_pool_idx is None and r.kv_pages == 0 and r.lock_refs == 0
|
| 364 |
+
for _ in range(20):
|
| 365 |
+
yield
|
| 366 |
+
|
| 367 |
+
def test_chunked_then_short_seq(self):
|
| 368 |
+
self.server.execute_script(self._script_chunked_then_short_seq)
|
| 369 |
+
|
| 370 |
+
@staticmethod
|
| 371 |
+
def _script_chunked_then_short_seq(t: ScriptedContext):
|
| 372 |
+
seq = [VERY_LONG_PROMPT_LEN, 8, VERY_LONG_PROMPT_LEN, 8]
|
| 373 |
+
for idx, L in enumerate(seq):
|
| 374 |
+
r = t.start_req(
|
| 375 |
+
prompt_len=L, max_new_tokens=2, ignore_eos=True, prompt_token=10 + idx
|
| 376 |
+
)
|
| 377 |
+
yield from run_until_finished(r)
|
| 378 |
+
assert r.finished
|
| 379 |
+
assert len(r.req.output_ids) == 2
|
| 380 |
+
assert r.req.req_pool_idx is None and r.kv_pages == 0 and r.lock_refs == 0
|
| 381 |
+
if L == VERY_LONG_PROMPT_LEN:
|
| 382 |
+
assert r.chunks_done == 8
|
| 383 |
+
else:
|
| 384 |
+
assert r.chunks_done == 0
|
| 385 |
+
|
| 386 |
+
def test_seq_engine_stats_stable(self):
|
| 387 |
+
self.server.execute_script(self._script_seq_engine_stats_stable)
|
| 388 |
+
|
| 389 |
+
@staticmethod
|
| 390 |
+
def _script_seq_engine_stats_stable(t: ScriptedContext):
|
| 391 |
+
baseline = t.engine_stats()["kv_pool_free"]
|
| 392 |
+
for _ in range(5):
|
| 393 |
+
r = t.start_req(prompt_len=16, max_new_tokens=2, ignore_eos=True)
|
| 394 |
+
yield from run_until_finished(r)
|
| 395 |
+
assert r.finished
|
| 396 |
+
assert len(r.req.output_ids) == 2
|
| 397 |
+
assert r.req.req_pool_idx is None and r.kv_pages == 0 and r.lock_refs == 0
|
| 398 |
+
for _ in range(5):
|
| 399 |
+
yield
|
| 400 |
+
t.flush_cache()
|
| 401 |
+
yield
|
| 402 |
+
final = t.engine_stats()["kv_pool_free"]
|
| 403 |
+
assert (
|
| 404 |
+
final >= baseline - 1
|
| 405 |
+
), f"KV pool drift: baseline={baseline}, final={final}"
|
| 406 |
+
|
| 407 |
+
def test_abort_all_during_chunked(self):
|
| 408 |
+
self.server.execute_script(self._script_abort_all_during_chunked)
|
| 409 |
+
|
| 410 |
+
@staticmethod
|
| 411 |
+
def _script_abort_all_during_chunked(t: ScriptedContext):
|
| 412 |
+
r = t.start_req(prompt_len=VERY_LONG_PROMPT_LEN, max_new_tokens=4)
|
| 413 |
+
yield from run_until(r, lambda h: h.is_chunking and h.chunks_done >= 1)
|
| 414 |
+
t.abort_all()
|
| 415 |
+
|
| 416 |
+
def _error_message(h):
|
| 417 |
+
if h.req is None:
|
| 418 |
+
return None
|
| 419 |
+
return (
|
| 420 |
+
h.req.finished_reason.message
|
| 421 |
+
if isinstance(h.req.finished_reason, FINISH_ABORT)
|
| 422 |
+
else None
|
| 423 |
+
)
|
| 424 |
+
|
| 425 |
+
for _ in range(DEFAULT_MAX_STEPS):
|
| 426 |
+
if r.finished or _error_message(r) is not None:
|
| 427 |
+
break
|
| 428 |
+
yield
|
| 429 |
+
else:
|
| 430 |
+
raise AssertionError(
|
| 431 |
+
"chunked req did not terminate after abort_all within DEFAULT_MAX_STEPS"
|
| 432 |
+
)
|
| 433 |
+
assert r.finished or _error_message(r) is not None
|
| 434 |
+
assert r.kv_pages == 0
|
| 435 |
+
assert r.req is None or r.req.req_pool_idx is None
|
| 436 |
+
assert r.lock_refs == 0
|
| 437 |
+
|
| 438 |
+
|
| 439 |
+
if __name__ == "__main__":
|
| 440 |
+
unittest.main()
|
asian_ai/performance/SGLang/test/manual/chunked_prefill/test_scripted_lora.py
ADDED
|
@@ -0,0 +1,240 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import unittest
|
| 2 |
+
|
| 3 |
+
from sglang.test.scripted_runtime.context import ScriptedContext
|
| 4 |
+
from sglang.test.scripted_runtime.test_case import ScriptedTestCase
|
| 5 |
+
from sglang.test.scripted_runtime_chunked_helpers import (
|
| 6 |
+
DEFAULT_CHUNK_SIZE,
|
| 7 |
+
VERY_LONG_PROMPT_LEN,
|
| 8 |
+
base_engine_kwargs,
|
| 9 |
+
run_until,
|
| 10 |
+
run_until_all_finished,
|
| 11 |
+
run_until_finished,
|
| 12 |
+
)
|
| 13 |
+
|
| 14 |
+
_LORA_BASE_MODEL = "meta-llama/Llama-3.2-1B-Instruct"
|
| 15 |
+
_LORA_ADAPTER = "codelion/Llama-3.2-1B-Instruct-tool-calling-lora"
|
| 16 |
+
_LORA_ADAPTER_B = "nicoboss/Llama-3.2-1B-Instruct-Uncensored-Lora"
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
class TestLoRASingleAdapter(ScriptedTestCase):
|
| 20 |
+
ENGINE_KWARGS = base_engine_kwargs(
|
| 21 |
+
model_path=_LORA_BASE_MODEL,
|
| 22 |
+
chunked_prefill_size=DEFAULT_CHUNK_SIZE,
|
| 23 |
+
enable_lora=True,
|
| 24 |
+
lora_paths=[_LORA_ADAPTER],
|
| 25 |
+
)
|
| 26 |
+
|
| 27 |
+
def test_naive_lora_chunked(self):
|
| 28 |
+
self.server.execute_script(self._script_naive_lora_chunked)
|
| 29 |
+
|
| 30 |
+
@staticmethod
|
| 31 |
+
def _script_naive_lora_chunked(t: ScriptedContext):
|
| 32 |
+
r = t.start_req(
|
| 33 |
+
prompt_len=VERY_LONG_PROMPT_LEN,
|
| 34 |
+
max_new_tokens=4,
|
| 35 |
+
lora_path=_LORA_ADAPTER,
|
| 36 |
+
)
|
| 37 |
+
yield from run_until_finished(r)
|
| 38 |
+
assert r.finished
|
| 39 |
+
assert r.chunks_done >= 2
|
| 40 |
+
assert r.kv_pages == 0
|
| 41 |
+
assert r.lock_refs == 0
|
| 42 |
+
assert len(r.req.output_ids) == 4
|
| 43 |
+
|
| 44 |
+
def test_lora_logprob_chunked_pass_idx(self):
|
| 45 |
+
self.server.execute_script(self._script_lora_logprob_chunked_pass_idx)
|
| 46 |
+
|
| 47 |
+
@staticmethod
|
| 48 |
+
def _script_lora_logprob_chunked_pass_idx(t: ScriptedContext):
|
| 49 |
+
prompt_len: int = VERY_LONG_PROMPT_LEN
|
| 50 |
+
r = t.start_req(
|
| 51 |
+
prompt_len=prompt_len,
|
| 52 |
+
max_new_tokens=2,
|
| 53 |
+
lora_path=_LORA_ADAPTER,
|
| 54 |
+
return_logprob=True,
|
| 55 |
+
logprob_start_len=0,
|
| 56 |
+
)
|
| 57 |
+
yield from run_until_finished(r)
|
| 58 |
+
assert r.finished
|
| 59 |
+
assert r.chunks_done == prompt_len // DEFAULT_CHUNK_SIZE
|
| 60 |
+
assert len(r.req.logprob.input_token_logprobs_val) == prompt_len
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
class TestLoRADrainerBypass(ScriptedTestCase):
|
| 64 |
+
ENGINE_KWARGS = base_engine_kwargs(
|
| 65 |
+
model_path=_LORA_BASE_MODEL,
|
| 66 |
+
chunked_prefill_size=DEFAULT_CHUNK_SIZE,
|
| 67 |
+
enable_lora=True,
|
| 68 |
+
lora_paths=[_LORA_ADAPTER, _LORA_ADAPTER_B],
|
| 69 |
+
max_loras_per_batch=1,
|
| 70 |
+
)
|
| 71 |
+
|
| 72 |
+
def test_lora_drainer_does_not_block_chunked_resume(self):
|
| 73 |
+
self.server.execute_script(
|
| 74 |
+
self._script_lora_drainer_does_not_block_chunked_resume
|
| 75 |
+
)
|
| 76 |
+
|
| 77 |
+
@staticmethod
|
| 78 |
+
def _script_lora_drainer_does_not_block_chunked_resume(t: ScriptedContext):
|
| 79 |
+
r_a = t.start_req(
|
| 80 |
+
prompt_len=VERY_LONG_PROMPT_LEN,
|
| 81 |
+
max_new_tokens=2,
|
| 82 |
+
lora_path=_LORA_ADAPTER,
|
| 83 |
+
)
|
| 84 |
+
yield from run_until(r_a, lambda h: h.is_chunking and h.chunks_done >= 1)
|
| 85 |
+
chunks_before = r_a.chunks_done
|
| 86 |
+
|
| 87 |
+
r_b = t.start_req(
|
| 88 |
+
prompt_len=DEFAULT_CHUNK_SIZE // 2,
|
| 89 |
+
max_new_tokens=2,
|
| 90 |
+
lora_path=_LORA_ADAPTER_B,
|
| 91 |
+
)
|
| 92 |
+
|
| 93 |
+
for _ in range(200):
|
| 94 |
+
if r_a.chunks_done > chunks_before:
|
| 95 |
+
break
|
| 96 |
+
yield
|
| 97 |
+
else:
|
| 98 |
+
raise AssertionError(
|
| 99 |
+
f"chunked-resume r_a starved by LoRA drainer; "
|
| 100 |
+
f"chunks_done stuck at {chunks_before}"
|
| 101 |
+
)
|
| 102 |
+
|
| 103 |
+
yield from run_until_all_finished(handles=[r_a, r_b])
|
| 104 |
+
assert r_a.finished and r_b.finished
|
| 105 |
+
|
| 106 |
+
|
| 107 |
+
class TestLoRAAdapterSwitch(ScriptedTestCase):
|
| 108 |
+
ENGINE_KWARGS = base_engine_kwargs(
|
| 109 |
+
model_path=_LORA_BASE_MODEL,
|
| 110 |
+
chunked_prefill_size=DEFAULT_CHUNK_SIZE,
|
| 111 |
+
enable_lora=True,
|
| 112 |
+
lora_paths=[_LORA_ADAPTER, _LORA_ADAPTER_B],
|
| 113 |
+
max_loras_per_batch=2,
|
| 114 |
+
)
|
| 115 |
+
|
| 116 |
+
def test_lora_adapter_switch_mid_chunk(self):
|
| 117 |
+
self.server.execute_script(self._script_lora_adapter_switch_mid_chunk)
|
| 118 |
+
|
| 119 |
+
@staticmethod
|
| 120 |
+
def _script_lora_adapter_switch_mid_chunk(t: ScriptedContext):
|
| 121 |
+
r_a = t.start_req(
|
| 122 |
+
prompt_len=VERY_LONG_PROMPT_LEN,
|
| 123 |
+
max_new_tokens=2,
|
| 124 |
+
lora_path=_LORA_ADAPTER,
|
| 125 |
+
)
|
| 126 |
+
r_b = t.start_req(
|
| 127 |
+
prompt_len=VERY_LONG_PROMPT_LEN,
|
| 128 |
+
max_new_tokens=2,
|
| 129 |
+
lora_path=_LORA_ADAPTER_B,
|
| 130 |
+
)
|
| 131 |
+
yield from run_until_all_finished(handles=[r_a, r_b])
|
| 132 |
+
assert r_a.finished and r_b.finished
|
| 133 |
+
expected_chunks = VERY_LONG_PROMPT_LEN // DEFAULT_CHUNK_SIZE
|
| 134 |
+
assert r_a.chunks_done == expected_chunks
|
| 135 |
+
assert r_b.chunks_done == expected_chunks
|
| 136 |
+
|
| 137 |
+
|
| 138 |
+
class TestLoRAAllDistinctAdapters(ScriptedTestCase):
|
| 139 |
+
ENGINE_KWARGS = base_engine_kwargs(
|
| 140 |
+
model_path=_LORA_BASE_MODEL,
|
| 141 |
+
chunked_prefill_size=DEFAULT_CHUNK_SIZE,
|
| 142 |
+
enable_lora=True,
|
| 143 |
+
lora_paths=[_LORA_ADAPTER, _LORA_ADAPTER_B],
|
| 144 |
+
max_loras_per_batch=2,
|
| 145 |
+
max_loaded_loras=4,
|
| 146 |
+
)
|
| 147 |
+
|
| 148 |
+
def test_lora_all_distinct_adapters_chunked(self):
|
| 149 |
+
self.server.execute_script(self._script_lora_all_distinct_adapters_chunked)
|
| 150 |
+
|
| 151 |
+
@staticmethod
|
| 152 |
+
def _script_lora_all_distinct_adapters_chunked(t: ScriptedContext):
|
| 153 |
+
adapters = [_LORA_ADAPTER, _LORA_ADAPTER_B, _LORA_ADAPTER, _LORA_ADAPTER_B]
|
| 154 |
+
reqs = [
|
| 155 |
+
t.start_req(
|
| 156 |
+
prompt_len=VERY_LONG_PROMPT_LEN,
|
| 157 |
+
max_new_tokens=2,
|
| 158 |
+
lora_path=adapter,
|
| 159 |
+
)
|
| 160 |
+
for adapter in adapters
|
| 161 |
+
]
|
| 162 |
+
yield from run_until_all_finished(handles=reqs, max_steps=2000)
|
| 163 |
+
assert all(r.finished for r in reqs)
|
| 164 |
+
for r in reqs:
|
| 165 |
+
assert r.kv_pages == 0
|
| 166 |
+
assert r.lock_refs == 0
|
| 167 |
+
expected_first_chunks = VERY_LONG_PROMPT_LEN // DEFAULT_CHUNK_SIZE
|
| 168 |
+
assert reqs[0].chunks_done == expected_first_chunks
|
| 169 |
+
assert reqs[1].chunks_done == expected_first_chunks
|
| 170 |
+
assert reqs[2].chunks_done < expected_first_chunks
|
| 171 |
+
assert reqs[3].chunks_done < expected_first_chunks
|
| 172 |
+
|
| 173 |
+
|
| 174 |
+
class TestLoRAAdapterEviction(ScriptedTestCase):
|
| 175 |
+
ENGINE_KWARGS = base_engine_kwargs(
|
| 176 |
+
model_path=_LORA_BASE_MODEL,
|
| 177 |
+
chunked_prefill_size=DEFAULT_CHUNK_SIZE,
|
| 178 |
+
enable_lora=True,
|
| 179 |
+
lora_paths=[_LORA_ADAPTER, _LORA_ADAPTER_B],
|
| 180 |
+
max_loras_per_batch=1,
|
| 181 |
+
max_loaded_loras=2,
|
| 182 |
+
)
|
| 183 |
+
|
| 184 |
+
def test_lora_adapter_eviction_between_chunks(self):
|
| 185 |
+
self.server.execute_script(self._script_lora_adapter_eviction_between_chunks)
|
| 186 |
+
|
| 187 |
+
@staticmethod
|
| 188 |
+
def _script_lora_adapter_eviction_between_chunks(t: ScriptedContext):
|
| 189 |
+
r_a = t.start_req(
|
| 190 |
+
prompt_len=VERY_LONG_PROMPT_LEN,
|
| 191 |
+
max_new_tokens=2,
|
| 192 |
+
lora_path=_LORA_ADAPTER,
|
| 193 |
+
)
|
| 194 |
+
yield from run_until(r_a, lambda h: h.is_chunking and h.chunks_done >= 1)
|
| 195 |
+
|
| 196 |
+
r_b = t.start_req(
|
| 197 |
+
prompt_len=DEFAULT_CHUNK_SIZE // 2,
|
| 198 |
+
max_new_tokens=2,
|
| 199 |
+
lora_path=_LORA_ADAPTER_B,
|
| 200 |
+
)
|
| 201 |
+
yield from run_until_all_finished(handles=[r_a, r_b], max_steps=800)
|
| 202 |
+
assert r_a.finished and r_b.finished
|
| 203 |
+
|
| 204 |
+
def test_lora_chunked_abort_during_eviction(self):
|
| 205 |
+
self.server.execute_script(self._script_lora_chunked_abort_during_eviction)
|
| 206 |
+
|
| 207 |
+
@staticmethod
|
| 208 |
+
def _script_lora_chunked_abort_during_eviction(t: ScriptedContext):
|
| 209 |
+
r_a = t.start_req(
|
| 210 |
+
prompt_len=VERY_LONG_PROMPT_LEN,
|
| 211 |
+
max_new_tokens=2,
|
| 212 |
+
lora_path=_LORA_ADAPTER,
|
| 213 |
+
)
|
| 214 |
+
yield from run_until(r_a, lambda h: h.is_chunking and h.chunks_done >= 1)
|
| 215 |
+
|
| 216 |
+
r_b = t.start_req(
|
| 217 |
+
prompt_len=DEFAULT_CHUNK_SIZE // 2,
|
| 218 |
+
max_new_tokens=2,
|
| 219 |
+
lora_path=_LORA_ADAPTER_B,
|
| 220 |
+
)
|
| 221 |
+
yield
|
| 222 |
+
|
| 223 |
+
t.abort(r_a)
|
| 224 |
+
for _ in range(12):
|
| 225 |
+
if r_a.kv_pages == 0 and (r_a.req is None or r_a.req.req_pool_idx is None):
|
| 226 |
+
break
|
| 227 |
+
yield
|
| 228 |
+
|
| 229 |
+
assert r_a.status in ("finished", "unknown")
|
| 230 |
+
if r_a.req is not None:
|
| 231 |
+
assert r_a.kv_pages == 0
|
| 232 |
+
assert r_a.lock_refs == 0
|
| 233 |
+
yield from run_until_finished(r_b)
|
| 234 |
+
assert r_b.finished
|
| 235 |
+
assert r_b.kv_pages == 0
|
| 236 |
+
assert r_b.lock_refs == 0
|
| 237 |
+
|
| 238 |
+
|
| 239 |
+
if __name__ == "__main__":
|
| 240 |
+
unittest.main()
|
asian_ai/performance/SGLang/test/manual/chunked_prefill/test_scripted_lora_overlap.py
ADDED
|
@@ -0,0 +1,191 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import unittest
|
| 2 |
+
|
| 3 |
+
from sglang.srt.lora.lora_registry import LoRARef
|
| 4 |
+
from sglang.test.scripted_runtime.context import ScriptedContext
|
| 5 |
+
from sglang.test.scripted_runtime.test_case import ScriptedTestCase
|
| 6 |
+
from sglang.test.scripted_runtime_chunked_helpers import (
|
| 7 |
+
DEFAULT_CHUNK_SIZE,
|
| 8 |
+
VERY_LONG_PROMPT_LEN,
|
| 9 |
+
base_engine_kwargs,
|
| 10 |
+
run_until,
|
| 11 |
+
run_until_all_finished,
|
| 12 |
+
run_until_finished,
|
| 13 |
+
)
|
| 14 |
+
|
| 15 |
+
_LORA_BASE_MODEL = "meta-llama/Llama-3.2-1B-Instruct"
|
| 16 |
+
_LORA_ADAPTER = "codelion/Llama-3.2-1B-Instruct-tool-calling-lora"
|
| 17 |
+
_LORA_ADAPTER_B = "nicoboss/Llama-3.2-1B-Instruct-Uncensored-Lora"
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
def _expected_lora_id(adapter_path: str) -> str:
|
| 21 |
+
return LoRARef.deterministic_id(adapter_path, adapter_path)
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
class TestLoRAOverlapSingleAdapter(ScriptedTestCase):
|
| 25 |
+
ENGINE_KWARGS = base_engine_kwargs(
|
| 26 |
+
model_path=_LORA_BASE_MODEL,
|
| 27 |
+
chunked_prefill_size=DEFAULT_CHUNK_SIZE,
|
| 28 |
+
enable_lora=True,
|
| 29 |
+
lora_paths=[_LORA_ADAPTER],
|
| 30 |
+
enable_lora_overlap_loading=True,
|
| 31 |
+
max_loras_per_batch=1,
|
| 32 |
+
max_loaded_loras=1,
|
| 33 |
+
)
|
| 34 |
+
|
| 35 |
+
def test_naive_lora_overlap_chunked(self):
|
| 36 |
+
self.server.execute_script(self._script_naive_lora_overlap_chunked)
|
| 37 |
+
|
| 38 |
+
@staticmethod
|
| 39 |
+
def _script_naive_lora_overlap_chunked(t: ScriptedContext):
|
| 40 |
+
r = t.start_req(
|
| 41 |
+
prompt_len=VERY_LONG_PROMPT_LEN,
|
| 42 |
+
max_new_tokens=4,
|
| 43 |
+
lora_path=_LORA_ADAPTER,
|
| 44 |
+
)
|
| 45 |
+
yield from run_until_finished(r)
|
| 46 |
+
assert r.finished
|
| 47 |
+
assert r.chunks_done == VERY_LONG_PROMPT_LEN // DEFAULT_CHUNK_SIZE
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
class TestLoRAOverlapH2dDuringChunk(ScriptedTestCase):
|
| 51 |
+
ENGINE_KWARGS = base_engine_kwargs(
|
| 52 |
+
model_path=_LORA_BASE_MODEL,
|
| 53 |
+
chunked_prefill_size=DEFAULT_CHUNK_SIZE,
|
| 54 |
+
enable_lora=True,
|
| 55 |
+
lora_paths=[_LORA_ADAPTER, _LORA_ADAPTER_B],
|
| 56 |
+
enable_lora_overlap_loading=True,
|
| 57 |
+
max_loras_per_batch=2,
|
| 58 |
+
max_loaded_loras=2,
|
| 59 |
+
)
|
| 60 |
+
|
| 61 |
+
def test_lora_overlap_h2d_during_chunk_admit(self):
|
| 62 |
+
self.server.execute_script(self._script_lora_overlap_h2d_during_chunk_admit)
|
| 63 |
+
|
| 64 |
+
@staticmethod
|
| 65 |
+
def _script_lora_overlap_h2d_during_chunk_admit(t: ScriptedContext):
|
| 66 |
+
r_a = t.start_req(
|
| 67 |
+
prompt_len=VERY_LONG_PROMPT_LEN,
|
| 68 |
+
max_new_tokens=2,
|
| 69 |
+
lora_path=_LORA_ADAPTER,
|
| 70 |
+
)
|
| 71 |
+
yield from run_until(r_a, lambda h: h.is_chunking and h.chunks_done >= 1)
|
| 72 |
+
|
| 73 |
+
r_b = t.start_req(
|
| 74 |
+
prompt_len=VERY_LONG_PROMPT_LEN,
|
| 75 |
+
max_new_tokens=2,
|
| 76 |
+
lora_path=_LORA_ADAPTER_B,
|
| 77 |
+
)
|
| 78 |
+
yield from run_until_all_finished(handles=[r_a, r_b], max_steps=1200)
|
| 79 |
+
assert r_a.finished and r_b.finished
|
| 80 |
+
expected_chunks = VERY_LONG_PROMPT_LEN // DEFAULT_CHUNK_SIZE
|
| 81 |
+
assert r_a.chunks_done == expected_chunks
|
| 82 |
+
assert r_b.chunks_done == expected_chunks
|
| 83 |
+
assert r_a.req.lora_id == _expected_lora_id(_LORA_ADAPTER)
|
| 84 |
+
assert r_b.req.lora_id == _expected_lora_id(_LORA_ADAPTER_B)
|
| 85 |
+
|
| 86 |
+
|
| 87 |
+
class TestLoRAOverlapAbortDuringH2d(ScriptedTestCase):
|
| 88 |
+
ENGINE_KWARGS = base_engine_kwargs(
|
| 89 |
+
model_path=_LORA_BASE_MODEL,
|
| 90 |
+
chunked_prefill_size=DEFAULT_CHUNK_SIZE,
|
| 91 |
+
enable_lora=True,
|
| 92 |
+
lora_paths=[_LORA_ADAPTER, _LORA_ADAPTER_B],
|
| 93 |
+
enable_lora_overlap_loading=True,
|
| 94 |
+
max_loras_per_batch=2,
|
| 95 |
+
max_loaded_loras=2,
|
| 96 |
+
)
|
| 97 |
+
|
| 98 |
+
def test_lora_overlap_abort_during_h2d(self):
|
| 99 |
+
self.server.execute_script(self._script_lora_overlap_abort_during_h2d)
|
| 100 |
+
|
| 101 |
+
@staticmethod
|
| 102 |
+
def _script_lora_overlap_abort_during_h2d(t: ScriptedContext):
|
| 103 |
+
r_a = t.start_req(
|
| 104 |
+
prompt_len=VERY_LONG_PROMPT_LEN,
|
| 105 |
+
max_new_tokens=2,
|
| 106 |
+
lora_path=_LORA_ADAPTER,
|
| 107 |
+
)
|
| 108 |
+
yield from run_until(r_a, lambda h: h.is_chunking and h.chunks_done >= 1)
|
| 109 |
+
|
| 110 |
+
r_b = t.start_req(
|
| 111 |
+
prompt_len=VERY_LONG_PROMPT_LEN,
|
| 112 |
+
max_new_tokens=2,
|
| 113 |
+
lora_path=_LORA_ADAPTER_B,
|
| 114 |
+
)
|
| 115 |
+
yield
|
| 116 |
+
b_loader = t.scheduler.lora_overlap_loader
|
| 117 |
+
b_lora_id = _expected_lora_id(_LORA_ADAPTER_B)
|
| 118 |
+
assert (
|
| 119 |
+
b_lora_id in b_loader.lora_to_overlap_load_event
|
| 120 |
+
or b_lora_id in b_loader.lora_manager.memory_pool.uid_to_buffer_id
|
| 121 |
+
), "adapter B never entered H2D; the abort would not exercise the H2D path"
|
| 122 |
+
|
| 123 |
+
t.abort(r_b)
|
| 124 |
+
yield
|
| 125 |
+
|
| 126 |
+
assert r_b.chunks_done == 0
|
| 127 |
+
assert r_b.req is None
|
| 128 |
+
assert r_b.status in ("finished", "unknown")
|
| 129 |
+
yield from run_until_finished(r_a, max_steps=800)
|
| 130 |
+
assert r_a.finished
|
| 131 |
+
assert r_a.req.lora_id == _expected_lora_id(_LORA_ADAPTER)
|
| 132 |
+
|
| 133 |
+
|
| 134 |
+
class TestLoRAOverlapAdapterRotation(ScriptedTestCase):
|
| 135 |
+
ENGINE_KWARGS = base_engine_kwargs(
|
| 136 |
+
model_path=_LORA_BASE_MODEL,
|
| 137 |
+
chunked_prefill_size=DEFAULT_CHUNK_SIZE,
|
| 138 |
+
enable_lora=True,
|
| 139 |
+
lora_paths=[_LORA_ADAPTER, _LORA_ADAPTER_B],
|
| 140 |
+
enable_lora_overlap_loading=True,
|
| 141 |
+
max_loras_per_batch=1,
|
| 142 |
+
max_loaded_loras=2,
|
| 143 |
+
)
|
| 144 |
+
|
| 145 |
+
def test_lora_overlap_back_to_back_adapters_chunked(self):
|
| 146 |
+
self.server.execute_script(
|
| 147 |
+
self._script_lora_overlap_back_to_back_adapters_chunked
|
| 148 |
+
)
|
| 149 |
+
|
| 150 |
+
@staticmethod
|
| 151 |
+
def _script_lora_overlap_back_to_back_adapters_chunked(t: ScriptedContext):
|
| 152 |
+
adapters = [_LORA_ADAPTER, _LORA_ADAPTER_B, _LORA_ADAPTER, _LORA_ADAPTER_B]
|
| 153 |
+
reqs = [
|
| 154 |
+
t.start_req(
|
| 155 |
+
prompt_len=VERY_LONG_PROMPT_LEN,
|
| 156 |
+
max_new_tokens=2,
|
| 157 |
+
lora_path=adapter,
|
| 158 |
+
)
|
| 159 |
+
for adapter in adapters
|
| 160 |
+
]
|
| 161 |
+
expected_ids = [_expected_lora_id(adapter) for adapter in adapters]
|
| 162 |
+
lora_id_by_rid: dict = {}
|
| 163 |
+
done = [False] * len(reqs)
|
| 164 |
+
for _ in range(2400):
|
| 165 |
+
for i, r in enumerate(reqs):
|
| 166 |
+
req = r.req
|
| 167 |
+
if req is not None:
|
| 168 |
+
lora_id_by_rid[r.rid] = req.lora_id
|
| 169 |
+
done[i] = done[i] or r.finished
|
| 170 |
+
if all(done):
|
| 171 |
+
break
|
| 172 |
+
yield
|
| 173 |
+
assert all(done)
|
| 174 |
+
expected_first_chunks = VERY_LONG_PROMPT_LEN // DEFAULT_CHUNK_SIZE
|
| 175 |
+
chunk_counts = [r.chunks_done for r in reqs]
|
| 176 |
+
a_counts = sorted([reqs[0].chunks_done, reqs[2].chunks_done])
|
| 177 |
+
b_counts = sorted([reqs[1].chunks_done, reqs[3].chunks_done])
|
| 178 |
+
assert a_counts == [0, expected_first_chunks], (
|
| 179 |
+
f"adapter A pair must be one cold full prefill + one full prefix "
|
| 180 |
+
f"hit; per-req chunks_done={chunk_counts}"
|
| 181 |
+
)
|
| 182 |
+
assert b_counts == [0, expected_first_chunks], (
|
| 183 |
+
f"adapter B pair must be one cold full prefill + one full prefix "
|
| 184 |
+
f"hit; per-req chunks_done={chunk_counts}"
|
| 185 |
+
)
|
| 186 |
+
for r, expected_id in zip(reqs, expected_ids):
|
| 187 |
+
assert lora_id_by_rid.get(r.rid) == expected_id
|
| 188 |
+
|
| 189 |
+
|
| 190 |
+
if __name__ == "__main__":
|
| 191 |
+
unittest.main()
|
asian_ai/performance/SGLang/test/manual/chunked_prefill/test_scripted_max_new_tokens.py
ADDED
|
@@ -0,0 +1,167 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import unittest
|
| 2 |
+
from typing import List
|
| 3 |
+
|
| 4 |
+
from sglang.test.scripted_runtime.context import ScriptedContext
|
| 5 |
+
from sglang.test.scripted_runtime.scheduler_hook import ScriptedBatchRecord
|
| 6 |
+
from sglang.test.scripted_runtime.test_case import ScriptedTestCase
|
| 7 |
+
from sglang.test.scripted_runtime_chunked_helpers import (
|
| 8 |
+
DEFAULT_CHUNK_SIZE,
|
| 9 |
+
base_engine_kwargs,
|
| 10 |
+
run_until,
|
| 11 |
+
run_until_finished,
|
| 12 |
+
)
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
def _records_for_rid(
|
| 16 |
+
batch_log: List[ScriptedBatchRecord], rid: str
|
| 17 |
+
) -> List[ScriptedBatchRecord]:
|
| 18 |
+
return [rec for rec in batch_log if rid in rec.rids]
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
def _decode_records(
|
| 22 |
+
batch_log: List[ScriptedBatchRecord], rid: str
|
| 23 |
+
) -> List[ScriptedBatchRecord]:
|
| 24 |
+
return [rec for rec in _records_for_rid(batch_log, rid) if rec.mode == "decode"]
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
def _extend_records(
|
| 28 |
+
batch_log: List[ScriptedBatchRecord], rid: str
|
| 29 |
+
) -> List[ScriptedBatchRecord]:
|
| 30 |
+
return [rec for rec in _records_for_rid(batch_log, rid) if rec.mode == "extend"]
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
class TestMaxNewTokensDecodeForwardLaw(ScriptedTestCase):
|
| 34 |
+
ENGINE_KWARGS = base_engine_kwargs(chunked_prefill_size=DEFAULT_CHUNK_SIZE)
|
| 35 |
+
|
| 36 |
+
def test_decode_forward_count_equals_mnt(self):
|
| 37 |
+
self.server.execute_script(self._script_decode_forward_count_law)
|
| 38 |
+
|
| 39 |
+
@staticmethod
|
| 40 |
+
def _script_decode_forward_count_law(t: ScriptedContext):
|
| 41 |
+
for max_new_tokens in (1, 2, 3, 4):
|
| 42 |
+
r = t.start_req(
|
| 43 |
+
prompt_len=2 * DEFAULT_CHUNK_SIZE,
|
| 44 |
+
max_new_tokens=max_new_tokens,
|
| 45 |
+
ignore_eos=True,
|
| 46 |
+
prompt_token=10 + max_new_tokens,
|
| 47 |
+
)
|
| 48 |
+
yield from run_until_finished(r)
|
| 49 |
+
assert r.finished
|
| 50 |
+
|
| 51 |
+
output_ids = r.req.output_ids
|
| 52 |
+
assert len(output_ids) == max_new_tokens, (
|
| 53 |
+
f"max_new_tokens={max_new_tokens} must produce exactly "
|
| 54 |
+
f"{max_new_tokens} tokens; got {len(output_ids)}"
|
| 55 |
+
)
|
| 56 |
+
|
| 57 |
+
batch_log = t._scheduler_hook._batch_log
|
| 58 |
+
decode_records = _decode_records(batch_log, r.rid)
|
| 59 |
+
extend_records = _extend_records(batch_log, r.rid)
|
| 60 |
+
|
| 61 |
+
assert len(decode_records) == max_new_tokens, (
|
| 62 |
+
f"max_new_tokens={max_new_tokens} expected "
|
| 63 |
+
f"{max_new_tokens} decode forward batches, got "
|
| 64 |
+
f"{len(decode_records)}"
|
| 65 |
+
)
|
| 66 |
+
assert len(extend_records) >= 2, (
|
| 67 |
+
f"max_new_tokens={max_new_tokens} expected >= 2 extend (chunk) "
|
| 68 |
+
f"records, got {len(extend_records)}"
|
| 69 |
+
)
|
| 70 |
+
|
| 71 |
+
yield
|
| 72 |
+
|
| 73 |
+
|
| 74 |
+
class TestMaxNewTokensOneSkipsDecode(ScriptedTestCase):
|
| 75 |
+
ENGINE_KWARGS = base_engine_kwargs(chunked_prefill_size=DEFAULT_CHUNK_SIZE)
|
| 76 |
+
|
| 77 |
+
def test_mnt_one_emits_token_on_prefill_then_one_dead_decode(self):
|
| 78 |
+
self.server.execute_script(self._script_mnt_one_skips_decode)
|
| 79 |
+
|
| 80 |
+
@staticmethod
|
| 81 |
+
def _script_mnt_one_skips_decode(t: ScriptedContext):
|
| 82 |
+
r = t.start_req(
|
| 83 |
+
prompt_len=3 * DEFAULT_CHUNK_SIZE,
|
| 84 |
+
max_new_tokens=1,
|
| 85 |
+
ignore_eos=True,
|
| 86 |
+
)
|
| 87 |
+
yield from run_until_finished(r)
|
| 88 |
+
assert r.finished
|
| 89 |
+
assert r.chunks_done >= 2, (
|
| 90 |
+
f"prompt spanning >=3 chunks should chunk at least twice, got "
|
| 91 |
+
f"chunks_done={r.chunks_done}"
|
| 92 |
+
)
|
| 93 |
+
assert len(r.req.output_ids) == 1, (
|
| 94 |
+
f"max_new_tokens=1 must produce exactly 1 token, got "
|
| 95 |
+
f"{len(r.req.output_ids)}"
|
| 96 |
+
)
|
| 97 |
+
|
| 98 |
+
batch_log = t._scheduler_hook._batch_log
|
| 99 |
+
decode_records = _decode_records(batch_log, r.rid)
|
| 100 |
+
assert len(decode_records) == 1, (
|
| 101 |
+
f"max_new_tokens=1 under overlap launches exactly ONE trailing decode "
|
| 102 |
+
f"forward whose token is discarded; got {len(decode_records)}"
|
| 103 |
+
)
|
| 104 |
+
|
| 105 |
+
rid_records = _records_for_rid(batch_log, r.rid)
|
| 106 |
+
assert rid_records, "expected at least one batch record for the req"
|
| 107 |
+
rid_modes = [rec.mode for rec in rid_records]
|
| 108 |
+
first_decode_pos = rid_modes.index("decode")
|
| 109 |
+
assert first_decode_pos >= 1, (
|
| 110 |
+
f"the lone decode must be preceded by an extend chunk; rid_modes="
|
| 111 |
+
f"{rid_modes}"
|
| 112 |
+
)
|
| 113 |
+
assert rid_modes[first_decode_pos - 1] in ("extend", "mixed"), (
|
| 114 |
+
f"the record immediately before the lone decode must be the final "
|
| 115 |
+
f"prefill chunk that emits the only token; got "
|
| 116 |
+
f"{rid_modes[first_decode_pos - 1]!r}, rid_modes={rid_modes}"
|
| 117 |
+
)
|
| 118 |
+
|
| 119 |
+
|
| 120 |
+
class TestMaxNewTokensFirstDecodeAdjacent(ScriptedTestCase):
|
| 121 |
+
ENGINE_KWARGS = base_engine_kwargs(chunked_prefill_size=DEFAULT_CHUNK_SIZE)
|
| 122 |
+
|
| 123 |
+
def test_first_decode_immediately_follows_last_chunk(self):
|
| 124 |
+
self.server.execute_script(self._script_first_decode_adjacent)
|
| 125 |
+
|
| 126 |
+
@staticmethod
|
| 127 |
+
def _script_first_decode_adjacent(t: ScriptedContext):
|
| 128 |
+
max_new_tokens = 16
|
| 129 |
+
r = t.start_req(
|
| 130 |
+
prompt_len=3 * DEFAULT_CHUNK_SIZE,
|
| 131 |
+
max_new_tokens=max_new_tokens,
|
| 132 |
+
ignore_eos=True,
|
| 133 |
+
)
|
| 134 |
+
yield from run_until(r, lambda h: h.finished, max_steps=400)
|
| 135 |
+
assert r.finished
|
| 136 |
+
assert len(r.req.output_ids) == max_new_tokens, (
|
| 137 |
+
f"max_new_tokens={max_new_tokens} must produce exactly "
|
| 138 |
+
f"{max_new_tokens} tokens; got {len(r.req.output_ids)}"
|
| 139 |
+
)
|
| 140 |
+
|
| 141 |
+
batch_log = t._scheduler_hook._batch_log
|
| 142 |
+
rid_records = _records_for_rid(batch_log, r.rid)
|
| 143 |
+
|
| 144 |
+
decode_records = _decode_records(batch_log, r.rid)
|
| 145 |
+
assert len(decode_records) == max_new_tokens, (
|
| 146 |
+
f"expected {max_new_tokens} decode forwards, got " f"{len(decode_records)}"
|
| 147 |
+
)
|
| 148 |
+
|
| 149 |
+
rid_modes = [rec.mode for rec in rid_records]
|
| 150 |
+
first_decode_pos = rid_modes.index("decode")
|
| 151 |
+
assert first_decode_pos >= 1, (
|
| 152 |
+
f"first decode must be preceded by an extend chunk; rid_modes="
|
| 153 |
+
f"{rid_modes}"
|
| 154 |
+
)
|
| 155 |
+
assert rid_modes[first_decode_pos - 1] == "extend", (
|
| 156 |
+
f"record immediately before the first decode (in this rid's "
|
| 157 |
+
f"subsequence) must be the last extend chunk; got "
|
| 158 |
+
f"{rid_modes[first_decode_pos - 1]!r}, rid_modes={rid_modes}"
|
| 159 |
+
)
|
| 160 |
+
assert all(mode == "extend" for mode in rid_modes[:first_decode_pos]), (
|
| 161 |
+
f"all records before the first decode must be extend chunks; "
|
| 162 |
+
f"rid_modes={rid_modes}"
|
| 163 |
+
)
|
| 164 |
+
|
| 165 |
+
|
| 166 |
+
if __name__ == "__main__":
|
| 167 |
+
unittest.main()
|
asian_ai/performance/SGLang/test/manual/chunked_prefill/test_scripted_multi_req.py
ADDED
|
@@ -0,0 +1,537 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import unittest
|
| 2 |
+
|
| 3 |
+
from sglang.test.scripted_runtime.context import ScriptedContext
|
| 4 |
+
from sglang.test.scripted_runtime.test_case import ScriptedTestCase
|
| 5 |
+
from sglang.test.scripted_runtime_chunked_helpers import (
|
| 6 |
+
BALLAST_MAX_NEW_TOKENS,
|
| 7 |
+
DEFAULT_CHUNK_SIZE,
|
| 8 |
+
DEFAULT_MAX_STEPS,
|
| 9 |
+
VERY_LONG_PROMPT_LEN,
|
| 10 |
+
base_engine_kwargs,
|
| 11 |
+
run_until,
|
| 12 |
+
run_until_all_finished,
|
| 13 |
+
run_until_finished,
|
| 14 |
+
)
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
def _drain_flush_then_assert_no_kv_leak(t: ScriptedContext, baseline: dict):
|
| 18 |
+
for _ in range(5):
|
| 19 |
+
yield
|
| 20 |
+
t.flush_cache()
|
| 21 |
+
yield
|
| 22 |
+
final = t.engine_stats()
|
| 23 |
+
assert (
|
| 24 |
+
final["kv_pool_free"] >= baseline["kv_pool_free"]
|
| 25 |
+
), f"KV leak: {baseline['kv_pool_free']} -> {final['kv_pool_free']}"
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
class TestMultiReqBasic(ScriptedTestCase):
|
| 29 |
+
ENGINE_KWARGS = base_engine_kwargs(chunked_prefill_size=DEFAULT_CHUNK_SIZE)
|
| 30 |
+
|
| 31 |
+
def test_second_chunked_waits(self):
|
| 32 |
+
self.server.execute_script(self._script_second_chunked_waits)
|
| 33 |
+
|
| 34 |
+
@staticmethod
|
| 35 |
+
def _script_second_chunked_waits(t: ScriptedContext):
|
| 36 |
+
r1 = t.start_req(prompt_len=VERY_LONG_PROMPT_LEN, max_new_tokens=2)
|
| 37 |
+
yield from run_until(r1, lambda h: h.is_chunking)
|
| 38 |
+
r2 = t.start_req(prompt_len=VERY_LONG_PROMPT_LEN, max_new_tokens=2)
|
| 39 |
+
yield
|
| 40 |
+
|
| 41 |
+
assert r1.is_chunking, "r1 should still be chunking"
|
| 42 |
+
assert (
|
| 43 |
+
not r2.is_chunking
|
| 44 |
+
), "r2 must wait for r1's chunk loop to clear before chunking"
|
| 45 |
+
|
| 46 |
+
yield from run_until_all_finished([r1, r2])
|
| 47 |
+
assert r1.finished and r2.finished
|
| 48 |
+
|
| 49 |
+
def test_hundred_short_reqs(self):
|
| 50 |
+
self.server.execute_script(self._script_hundred_short_reqs)
|
| 51 |
+
|
| 52 |
+
@staticmethod
|
| 53 |
+
def _script_hundred_short_reqs(t: ScriptedContext):
|
| 54 |
+
baseline = t.engine_stats()
|
| 55 |
+
reqs = [t.start_req(prompt_len=16, max_new_tokens=2) for _ in range(100)]
|
| 56 |
+
yield from run_until_all_finished(reqs, max_steps=2000)
|
| 57 |
+
for r in reqs:
|
| 58 |
+
assert r.finished
|
| 59 |
+
yield from _drain_flush_then_assert_no_kv_leak(t, baseline)
|
| 60 |
+
|
| 61 |
+
def test_five_hundred_short_reqs(self):
|
| 62 |
+
self.server.execute_script(self._script_five_hundred_short_reqs)
|
| 63 |
+
|
| 64 |
+
@staticmethod
|
| 65 |
+
def _script_five_hundred_short_reqs(t: ScriptedContext):
|
| 66 |
+
baseline = t.engine_stats()
|
| 67 |
+
reqs = [t.start_req(prompt_len=8, max_new_tokens=1) for _ in range(500)]
|
| 68 |
+
yield from run_until_all_finished(reqs, max_steps=20000)
|
| 69 |
+
for r in reqs:
|
| 70 |
+
assert r.finished
|
| 71 |
+
yield from _drain_flush_then_assert_no_kv_leak(t, baseline)
|
| 72 |
+
|
| 73 |
+
def test_mixed_ten_chunked_ten_short(self):
|
| 74 |
+
self.server.execute_script(self._script_mixed_ten_chunked_ten_short)
|
| 75 |
+
|
| 76 |
+
@staticmethod
|
| 77 |
+
def _script_mixed_ten_chunked_ten_short(t: ScriptedContext):
|
| 78 |
+
baseline = t.engine_stats()
|
| 79 |
+
chunked = [
|
| 80 |
+
t.start_req(
|
| 81 |
+
prompt_len=VERY_LONG_PROMPT_LEN, max_new_tokens=2, prompt_token=100 + i
|
| 82 |
+
)
|
| 83 |
+
for i in range(10)
|
| 84 |
+
]
|
| 85 |
+
shorts = [t.start_req(prompt_len=8, max_new_tokens=2) for _ in range(10)]
|
| 86 |
+
all_reqs = chunked + shorts
|
| 87 |
+
finished = False
|
| 88 |
+
for _ in range(DEFAULT_MAX_STEPS * 20):
|
| 89 |
+
assert sum(1 for r in all_reqs if r.is_chunking) <= 1
|
| 90 |
+
if all(r.finished for r in all_reqs):
|
| 91 |
+
finished = True
|
| 92 |
+
break
|
| 93 |
+
yield
|
| 94 |
+
if not finished:
|
| 95 |
+
raise AssertionError("not all reqs finished")
|
| 96 |
+
for r in chunked:
|
| 97 |
+
assert r.chunks_done >= 2
|
| 98 |
+
yield from _drain_flush_then_assert_no_kv_leak(t, baseline)
|
| 99 |
+
|
| 100 |
+
def test_submit_during_chunk_mid(self):
|
| 101 |
+
self.server.execute_script(self._script_submit_during_chunk_mid)
|
| 102 |
+
|
| 103 |
+
@staticmethod
|
| 104 |
+
def _script_submit_during_chunk_mid(t: ScriptedContext):
|
| 105 |
+
r1 = t.start_req(prompt_len=VERY_LONG_PROMPT_LEN, max_new_tokens=2)
|
| 106 |
+
yield from run_until(r1, lambda h: h.is_chunking)
|
| 107 |
+
r2 = t.start_req(prompt_len=VERY_LONG_PROMPT_LEN, max_new_tokens=2)
|
| 108 |
+
yield
|
| 109 |
+
r3 = t.start_req(prompt_len=16, max_new_tokens=2)
|
| 110 |
+
yield
|
| 111 |
+
|
| 112 |
+
assert r1.is_chunking, "r1 must still hold the single chunked slot"
|
| 113 |
+
assert not r2.is_chunking, "r2 must wait until r1's chunk loop clears"
|
| 114 |
+
assert not r3.is_chunking, "r3 must wait until r1's chunk loop clears"
|
| 115 |
+
|
| 116 |
+
yield from run_until_all_finished([r1, r2, r3])
|
| 117 |
+
assert r1.finished and r2.finished and r3.finished
|
| 118 |
+
|
| 119 |
+
def test_five_identical_prompts(self):
|
| 120 |
+
self.server.execute_script(self._script_five_identical_prompts)
|
| 121 |
+
|
| 122 |
+
@staticmethod
|
| 123 |
+
def _script_five_identical_prompts(t: ScriptedContext):
|
| 124 |
+
r1 = t.start_req(prompt_len=VERY_LONG_PROMPT_LEN, max_new_tokens=2)
|
| 125 |
+
yield from run_until_finished(r1)
|
| 126 |
+
|
| 127 |
+
others = [
|
| 128 |
+
t.start_req(prompt_len=VERY_LONG_PROMPT_LEN, max_new_tokens=2)
|
| 129 |
+
for _ in range(4)
|
| 130 |
+
]
|
| 131 |
+
yield from run_until_all_finished(others)
|
| 132 |
+
for r in others:
|
| 133 |
+
assert r.finished
|
| 134 |
+
assert r.chunks_done == 0
|
| 135 |
+
assert r1.finished
|
| 136 |
+
|
| 137 |
+
def test_sibling_shared_prefix(self):
|
| 138 |
+
self.server.execute_script(self._script_sibling_shared_prefix)
|
| 139 |
+
|
| 140 |
+
@staticmethod
|
| 141 |
+
def _script_sibling_shared_prefix(t: ScriptedContext):
|
| 142 |
+
r1 = t.start_req(prompt_len=VERY_LONG_PROMPT_LEN, max_new_tokens=2)
|
| 143 |
+
yield from run_until_finished(r1)
|
| 144 |
+
r2 = t.start_req(prompt_len=VERY_LONG_PROMPT_LEN + 8, max_new_tokens=2)
|
| 145 |
+
yield from run_until_finished(r2)
|
| 146 |
+
assert r1.finished and r2.finished
|
| 147 |
+
assert (
|
| 148 |
+
r2.chunks_done < r1.chunks_done
|
| 149 |
+
), "r2 reuses r1's cached prefix, so it should chunk fewer times"
|
| 150 |
+
|
| 151 |
+
def test_trickle_per_yield_50(self):
|
| 152 |
+
self.server.execute_script(self._script_trickle_per_yield_50)
|
| 153 |
+
|
| 154 |
+
@staticmethod
|
| 155 |
+
def _script_trickle_per_yield_50(t: ScriptedContext):
|
| 156 |
+
baseline = t.engine_stats()
|
| 157 |
+
reqs = []
|
| 158 |
+
for _ in range(50):
|
| 159 |
+
reqs.append(t.start_req(prompt_len=8, max_new_tokens=2))
|
| 160 |
+
yield
|
| 161 |
+
yield from run_until_all_finished(reqs, max_steps=2000)
|
| 162 |
+
for r in reqs:
|
| 163 |
+
assert r.finished
|
| 164 |
+
yield from _drain_flush_then_assert_no_kv_leak(t, baseline)
|
| 165 |
+
|
| 166 |
+
def test_submit_then_immediate_abort(self):
|
| 167 |
+
self.server.execute_script(self._script_submit_then_immediate_abort)
|
| 168 |
+
|
| 169 |
+
@staticmethod
|
| 170 |
+
def _script_submit_then_immediate_abort(t: ScriptedContext):
|
| 171 |
+
r = t.start_req(prompt_len=VERY_LONG_PROMPT_LEN, max_new_tokens=2)
|
| 172 |
+
t.abort(r)
|
| 173 |
+
for _ in range(5):
|
| 174 |
+
yield
|
| 175 |
+
assert r.kv_pages == 0
|
| 176 |
+
assert r.req is None or r.req.req_pool_idx is None
|
| 177 |
+
|
| 178 |
+
def test_rid_reuse_after_finish(self):
|
| 179 |
+
self.server.execute_script(self._script_rid_reuse_after_finish)
|
| 180 |
+
|
| 181 |
+
@staticmethod
|
| 182 |
+
def _script_rid_reuse_after_finish(t: ScriptedContext):
|
| 183 |
+
baseline = t.engine_stats()
|
| 184 |
+
r1 = t.start_req(prompt_len=16, max_new_tokens=2, rid="reuse-rid")
|
| 185 |
+
yield from run_until_finished(r1)
|
| 186 |
+
r2 = t.start_req(prompt_len=16, max_new_tokens=2, rid="reuse-rid")
|
| 187 |
+
yield from run_until_finished(r2)
|
| 188 |
+
assert r1.finished and r2.finished
|
| 189 |
+
yield from _drain_flush_then_assert_no_kv_leak(t, baseline)
|
| 190 |
+
|
| 191 |
+
def test_submit_pause_n_resubmit_same_rid(self):
|
| 192 |
+
self.server.execute_script(self._script_submit_pause_n_resubmit_same_rid)
|
| 193 |
+
|
| 194 |
+
@staticmethod
|
| 195 |
+
def _script_submit_pause_n_resubmit_same_rid(t: ScriptedContext):
|
| 196 |
+
baseline = t.engine_stats()
|
| 197 |
+
r1 = t.start_req(prompt_len=16, max_new_tokens=2, rid="reuse-200")
|
| 198 |
+
yield from run_until_finished(r1)
|
| 199 |
+
for _ in range(200):
|
| 200 |
+
assert (1 if t.scheduler.chunked_req is not None else 0) == 0
|
| 201 |
+
yield
|
| 202 |
+
r2 = t.start_req(prompt_len=16, max_new_tokens=2, rid="reuse-200")
|
| 203 |
+
yield from run_until_finished(r2)
|
| 204 |
+
assert r2.finished
|
| 205 |
+
yield from _drain_flush_then_assert_no_kv_leak(t, baseline)
|
| 206 |
+
|
| 207 |
+
def test_submit_during_decode_of_other(self):
|
| 208 |
+
self.server.execute_script(self._script_submit_during_decode_of_other)
|
| 209 |
+
|
| 210 |
+
@staticmethod
|
| 211 |
+
def _script_submit_during_decode_of_other(t: ScriptedContext):
|
| 212 |
+
r1 = t.start_req(prompt_len=16, max_new_tokens=16)
|
| 213 |
+
yield from run_until(r1, lambda h: h.status == "running")
|
| 214 |
+
r2 = t.start_req(prompt_len=VERY_LONG_PROMPT_LEN, max_new_tokens=2)
|
| 215 |
+
yield from run_until(r2, lambda h: h.is_chunking)
|
| 216 |
+
|
| 217 |
+
comp = t.batch_composition()
|
| 218 |
+
chunked_set = set(comp.get("chunked", []))
|
| 219 |
+
prefill_set = set(comp.get("prefill", []))
|
| 220 |
+
decode_set = set(comp.get("decode", []))
|
| 221 |
+
assert r2.rid in chunked_set, f"r2 should be the chunked req; got {comp}"
|
| 222 |
+
assert chunked_set.isdisjoint(prefill_set)
|
| 223 |
+
assert chunked_set.isdisjoint(decode_set)
|
| 224 |
+
|
| 225 |
+
yield from run_until_all_finished([r1, r2], max_steps=DEFAULT_MAX_STEPS * 5)
|
| 226 |
+
assert r1.finished and r2.finished
|
| 227 |
+
|
| 228 |
+
def test_two_small_parallel(self):
|
| 229 |
+
self.server.execute_script(self._script_two_small_parallel)
|
| 230 |
+
|
| 231 |
+
@staticmethod
|
| 232 |
+
def _script_two_small_parallel(t: ScriptedContext):
|
| 233 |
+
r1 = t.start_req(prompt_len=16, max_new_tokens=4)
|
| 234 |
+
r2 = t.start_req(prompt_len=16, max_new_tokens=4)
|
| 235 |
+
for _ in range(DEFAULT_MAX_STEPS):
|
| 236 |
+
assert (
|
| 237 |
+
t.scheduler.chunked_req.rid
|
| 238 |
+
if t.scheduler.chunked_req is not None
|
| 239 |
+
else None
|
| 240 |
+
) is None
|
| 241 |
+
if r1.finished and r2.finished:
|
| 242 |
+
break
|
| 243 |
+
yield
|
| 244 |
+
assert r1.finished and r2.finished
|
| 245 |
+
|
| 246 |
+
def test_one_chunked_plus_many_short(self):
|
| 247 |
+
self.server.execute_script(self._script_one_chunked_plus_many_short)
|
| 248 |
+
|
| 249 |
+
@staticmethod
|
| 250 |
+
def _script_one_chunked_plus_many_short(t: ScriptedContext):
|
| 251 |
+
chunked = t.start_req(prompt_len=VERY_LONG_PROMPT_LEN, max_new_tokens=2)
|
| 252 |
+
shorts = [t.start_req(prompt_len=16, max_new_tokens=2) for _ in range(5)]
|
| 253 |
+
for _ in range(DEFAULT_MAX_STEPS * 5):
|
| 254 |
+
assert (1 if t.scheduler.chunked_req is not None else 0) <= 1
|
| 255 |
+
if chunked.finished and all(s.finished for s in shorts):
|
| 256 |
+
break
|
| 257 |
+
yield
|
| 258 |
+
assert chunked.chunks_done >= 2
|
| 259 |
+
assert chunked.finished
|
| 260 |
+
for s in shorts:
|
| 261 |
+
assert s.finished
|
| 262 |
+
|
| 263 |
+
def test_multiple_chunked_staggered(self):
|
| 264 |
+
self.server.execute_script(self._script_multiple_chunked_staggered)
|
| 265 |
+
|
| 266 |
+
@staticmethod
|
| 267 |
+
def _script_multiple_chunked_staggered(t: ScriptedContext):
|
| 268 |
+
reqs = []
|
| 269 |
+
for i in range(4):
|
| 270 |
+
reqs.append(
|
| 271 |
+
t.start_req(
|
| 272 |
+
prompt_len=VERY_LONG_PROMPT_LEN,
|
| 273 |
+
max_new_tokens=2,
|
| 274 |
+
prompt_token=100 + i,
|
| 275 |
+
)
|
| 276 |
+
)
|
| 277 |
+
yield
|
| 278 |
+
assert sum(1 for r in reqs if r.is_chunking) <= 1
|
| 279 |
+
yield
|
| 280 |
+
for _ in range(DEFAULT_MAX_STEPS * 10):
|
| 281 |
+
assert sum(1 for r in reqs if r.is_chunking) <= 1
|
| 282 |
+
if all(r.finished for r in reqs):
|
| 283 |
+
break
|
| 284 |
+
yield
|
| 285 |
+
for r in reqs:
|
| 286 |
+
assert r.finished
|
| 287 |
+
assert r.chunks_done >= 2
|
| 288 |
+
|
| 289 |
+
def test_eight_concurrent_chunked(self):
|
| 290 |
+
self.server.execute_script(self._script_eight_concurrent_chunked)
|
| 291 |
+
|
| 292 |
+
@staticmethod
|
| 293 |
+
def _script_eight_concurrent_chunked(t: ScriptedContext):
|
| 294 |
+
reqs = [
|
| 295 |
+
t.start_req(
|
| 296 |
+
prompt_len=VERY_LONG_PROMPT_LEN, max_new_tokens=2, prompt_token=100 + i
|
| 297 |
+
)
|
| 298 |
+
for i in range(8)
|
| 299 |
+
]
|
| 300 |
+
finished = False
|
| 301 |
+
for _ in range(DEFAULT_MAX_STEPS * 5):
|
| 302 |
+
assert sum(1 for r in reqs if r.is_chunking) <= 1
|
| 303 |
+
if all(r.finished for r in reqs):
|
| 304 |
+
finished = True
|
| 305 |
+
break
|
| 306 |
+
yield
|
| 307 |
+
if not finished:
|
| 308 |
+
raise AssertionError("not all reqs finished")
|
| 309 |
+
for r in reqs:
|
| 310 |
+
assert r.chunks_done >= 2
|
| 311 |
+
|
| 312 |
+
def test_decode_only_batch(self):
|
| 313 |
+
self.server.execute_script(self._script_decode_only_batch)
|
| 314 |
+
|
| 315 |
+
@staticmethod
|
| 316 |
+
def _script_decode_only_batch(t: ScriptedContext):
|
| 317 |
+
reqs = [t.start_req(prompt_len=4, max_new_tokens=8) for _ in range(10)]
|
| 318 |
+
for _ in range(DEFAULT_MAX_STEPS * 3):
|
| 319 |
+
assert (
|
| 320 |
+
t.scheduler.chunked_req.rid
|
| 321 |
+
if t.scheduler.chunked_req is not None
|
| 322 |
+
else None
|
| 323 |
+
) is None, "pure decode workload must never populate chunked_req"
|
| 324 |
+
assert (1 if t.scheduler.chunked_req is not None else 0) == 0
|
| 325 |
+
if all(r.finished for r in reqs):
|
| 326 |
+
return
|
| 327 |
+
yield
|
| 328 |
+
raise AssertionError("not all reqs finished")
|
| 329 |
+
|
| 330 |
+
def test_mixed_prefill_lengths(self):
|
| 331 |
+
self.server.execute_script(self._script_mixed_prefill_lengths)
|
| 332 |
+
|
| 333 |
+
@staticmethod
|
| 334 |
+
def _script_mixed_prefill_lengths(t: ScriptedContext):
|
| 335 |
+
lens = [8, 16, 32, 64, 128, 256, 512, 1024]
|
| 336 |
+
reqs = [t.start_req(prompt_len=L, max_new_tokens=2) for L in lens]
|
| 337 |
+
by_len = dict(zip(lens, reqs))
|
| 338 |
+
for _ in range(DEFAULT_MAX_STEPS * 10):
|
| 339 |
+
assert sum(1 for r in reqs if r.is_chunking) <= 1
|
| 340 |
+
if all(r.finished for r in reqs):
|
| 341 |
+
break
|
| 342 |
+
yield
|
| 343 |
+
for r in reqs:
|
| 344 |
+
assert r.finished
|
| 345 |
+
for L in (8, 16, 32, 64, 128):
|
| 346 |
+
assert by_len[L].chunks_done <= 1, f"prompt_len={L} should not chunk"
|
| 347 |
+
for L in (512, 1024):
|
| 348 |
+
assert by_len[L].chunks_done >= 2, f"prompt_len={L} should chunk >=2"
|
| 349 |
+
|
| 350 |
+
def test_chunked_req_exclusive_of_batch_invariant(self):
|
| 351 |
+
self.server.execute_script(
|
| 352 |
+
self._script_chunked_req_exclusive_of_batch_invariant
|
| 353 |
+
)
|
| 354 |
+
|
| 355 |
+
@staticmethod
|
| 356 |
+
def _script_chunked_req_exclusive_of_batch_invariant(t: ScriptedContext):
|
| 357 |
+
r1 = t.start_req(prompt_len=VERY_LONG_PROMPT_LEN, max_new_tokens=2)
|
| 358 |
+
r2 = t.start_req(prompt_len=VERY_LONG_PROMPT_LEN, max_new_tokens=2)
|
| 359 |
+
for _ in range(DEFAULT_MAX_STEPS * 5):
|
| 360 |
+
s = t.scheduler
|
| 361 |
+
chunked = s.chunked_req
|
| 362 |
+
running = s.running_batch
|
| 363 |
+
if chunked is not None and running is not None:
|
| 364 |
+
assert chunked not in running.reqs, (
|
| 365 |
+
f"chunked_req must be exclusive of running_batch.reqs; "
|
| 366 |
+
f"chunked.rid={chunked.rid!r} appears in running_batch"
|
| 367 |
+
)
|
| 368 |
+
if r1.finished and r2.finished:
|
| 369 |
+
return
|
| 370 |
+
yield
|
| 371 |
+
raise AssertionError("r1 and r2 did not both finish within step budget")
|
| 372 |
+
|
| 373 |
+
def test_two_chunked_one_decode(self):
|
| 374 |
+
self.server.execute_script(self._script_two_chunked_one_decode)
|
| 375 |
+
|
| 376 |
+
@staticmethod
|
| 377 |
+
def _script_two_chunked_one_decode(t: ScriptedContext):
|
| 378 |
+
chunked1 = t.start_req(prompt_len=VERY_LONG_PROMPT_LEN, max_new_tokens=2)
|
| 379 |
+
chunked2 = t.start_req(prompt_len=VERY_LONG_PROMPT_LEN, max_new_tokens=2)
|
| 380 |
+
short = t.start_req(prompt_len=8, max_new_tokens=4)
|
| 381 |
+
all_reqs = [chunked1, chunked2, short]
|
| 382 |
+
for _ in range(DEFAULT_MAX_STEPS * 10):
|
| 383 |
+
comp = t.batch_composition()
|
| 384 |
+
prefill_set = set(comp.get("prefill", []))
|
| 385 |
+
decode_set = set(comp.get("decode", []))
|
| 386 |
+
chunked_set = set(comp.get("chunked", []))
|
| 387 |
+
assert prefill_set.isdisjoint(decode_set)
|
| 388 |
+
assert prefill_set.isdisjoint(chunked_set)
|
| 389 |
+
assert decode_set.isdisjoint(chunked_set)
|
| 390 |
+
if all(r.finished for r in all_reqs):
|
| 391 |
+
break
|
| 392 |
+
yield
|
| 393 |
+
assert chunked1.finished and chunked2.finished and short.finished
|
| 394 |
+
|
| 395 |
+
def test_batch_state_query_during_run(self):
|
| 396 |
+
self.server.execute_script(self._script_batch_state_query_during_run)
|
| 397 |
+
|
| 398 |
+
@staticmethod
|
| 399 |
+
def _script_batch_state_query_during_run(t: ScriptedContext):
|
| 400 |
+
reqs = [t.start_req(prompt_len=16, max_new_tokens=4) for _ in range(4)]
|
| 401 |
+
for _ in range(DEFAULT_MAX_STEPS):
|
| 402 |
+
comp = t.batch_composition()
|
| 403 |
+
prefill = set(comp.get("prefill", []))
|
| 404 |
+
decode = set(comp.get("decode", []))
|
| 405 |
+
assert prefill & decode == set()
|
| 406 |
+
if all(r.finished for r in reqs):
|
| 407 |
+
return
|
| 408 |
+
yield
|
| 409 |
+
raise AssertionError("not all reqs finished")
|
| 410 |
+
|
| 411 |
+
|
| 412 |
+
class TestMultiReqPriority(ScriptedTestCase):
|
| 413 |
+
ENGINE_KWARGS = base_engine_kwargs(
|
| 414 |
+
chunked_prefill_size=DEFAULT_CHUNK_SIZE,
|
| 415 |
+
enable_priority_scheduling=True,
|
| 416 |
+
)
|
| 417 |
+
|
| 418 |
+
def test_parallel_with_priority(self):
|
| 419 |
+
self.server.execute_script(self._script_parallel_with_priority)
|
| 420 |
+
|
| 421 |
+
@staticmethod
|
| 422 |
+
def _script_parallel_with_priority(t: ScriptedContext):
|
| 423 |
+
normal = [
|
| 424 |
+
t.start_req(
|
| 425 |
+
prompt_len=16,
|
| 426 |
+
max_new_tokens=BALLAST_MAX_NEW_TOKENS,
|
| 427 |
+
ignore_eos=True,
|
| 428 |
+
priority=0,
|
| 429 |
+
)
|
| 430 |
+
for _ in range(4)
|
| 431 |
+
]
|
| 432 |
+
yield from run_until(normal[-1], lambda h: h.status == "running")
|
| 433 |
+
|
| 434 |
+
t.exhaust_kv(leave_pages=0)
|
| 435 |
+
high = t.start_req(prompt_len=16, max_new_tokens=2, priority=100)
|
| 436 |
+
|
| 437 |
+
preempted = False
|
| 438 |
+
for _ in range(DEFAULT_MAX_STEPS * 5):
|
| 439 |
+
if any(r.status == "waiting" for r in normal):
|
| 440 |
+
preempted = True
|
| 441 |
+
if high.finished:
|
| 442 |
+
break
|
| 443 |
+
yield
|
| 444 |
+
assert high.finished, "high-priority req must run to completion"
|
| 445 |
+
assert preempted, "a normal req must be preempted back to the waiting queue"
|
| 446 |
+
|
| 447 |
+
t.abort_all()
|
| 448 |
+
for _ in range(DEFAULT_MAX_STEPS):
|
| 449 |
+
if all(r.finished for r in normal):
|
| 450 |
+
break
|
| 451 |
+
yield
|
| 452 |
+
|
| 453 |
+
|
| 454 |
+
class TestMultiReqMixedChunk(ScriptedTestCase):
|
| 455 |
+
ENGINE_KWARGS = base_engine_kwargs(
|
| 456 |
+
chunked_prefill_size=DEFAULT_CHUNK_SIZE,
|
| 457 |
+
enable_mixed_chunk=True,
|
| 458 |
+
)
|
| 459 |
+
|
| 460 |
+
def test_long_prefill_chunks_more_with_concurrent_decode(self):
|
| 461 |
+
self.server.execute_script(
|
| 462 |
+
self._script_long_prefill_chunks_more_with_concurrent_decode
|
| 463 |
+
)
|
| 464 |
+
|
| 465 |
+
@staticmethod
|
| 466 |
+
def _script_long_prefill_chunks_more_with_concurrent_decode(t: ScriptedContext):
|
| 467 |
+
decoder = t.start_req(prompt_len=16, max_new_tokens=64)
|
| 468 |
+
yield from run_until(decoder, lambda h: h.status == "running")
|
| 469 |
+
|
| 470 |
+
long_req = t.start_req(prompt_len=4 * DEFAULT_CHUNK_SIZE, max_new_tokens=2)
|
| 471 |
+
yield from run_until(long_req, lambda h: h.is_chunking)
|
| 472 |
+
|
| 473 |
+
saw_mixed_batch: bool = False
|
| 474 |
+
for _ in range(DEFAULT_MAX_STEPS * 5):
|
| 475 |
+
if t.last_batch_forward_mode == "MIXED":
|
| 476 |
+
saw_mixed_batch = True
|
| 477 |
+
if long_req.finished and decoder.finished:
|
| 478 |
+
break
|
| 479 |
+
yield
|
| 480 |
+
assert long_req.finished and decoder.finished
|
| 481 |
+
|
| 482 |
+
assert saw_mixed_batch, "expected at least one MIXED (prefill+decode) batch"
|
| 483 |
+
assert long_req.chunks_done >= 4, (
|
| 484 |
+
f"a 4-chunk prompt must chunk >= 4 times under concurrent decode; "
|
| 485 |
+
f"got {long_req.chunks_done}"
|
| 486 |
+
)
|
| 487 |
+
|
| 488 |
+
def test_chunked_plus_decode_in_batch(self):
|
| 489 |
+
self.server.execute_script(self._script_chunked_plus_decode_in_batch)
|
| 490 |
+
|
| 491 |
+
@staticmethod
|
| 492 |
+
def _script_chunked_plus_decode_in_batch(t: ScriptedContext):
|
| 493 |
+
r2 = t.start_req(prompt_len=8, max_new_tokens=64, ignore_eos=True)
|
| 494 |
+
yield from run_until(
|
| 495 |
+
r2, lambda h: h.status == "running" and len(h.req.output_ids) >= 1
|
| 496 |
+
)
|
| 497 |
+
|
| 498 |
+
r1 = t.start_req(prompt_len=VERY_LONG_PROMPT_LEN, max_new_tokens=2)
|
| 499 |
+
yield from run_until(r1, lambda h: h.is_chunking)
|
| 500 |
+
|
| 501 |
+
r2_out_before = len(r2.req.output_ids)
|
| 502 |
+
saw_chunked_r1 = False
|
| 503 |
+
saw_r2_decode_during_chunking = False
|
| 504 |
+
for _ in range(DEFAULT_MAX_STEPS):
|
| 505 |
+
comp = t.batch_composition()
|
| 506 |
+
if r1.rid in comp.get("chunked", []):
|
| 507 |
+
saw_chunked_r1 = True
|
| 508 |
+
if r2.rid in comp.get("decode", []) + comp.get("prefill", []):
|
| 509 |
+
saw_r2_decode_during_chunking = True
|
| 510 |
+
chunked_set = set(comp.get("chunked", []))
|
| 511 |
+
assert chunked_set.isdisjoint(set(comp.get("prefill", [])))
|
| 512 |
+
assert chunked_set.isdisjoint(set(comp.get("decode", [])))
|
| 513 |
+
if not r1.is_chunking:
|
| 514 |
+
break
|
| 515 |
+
yield
|
| 516 |
+
assert saw_chunked_r1, "r1 was never observed in the chunked subset"
|
| 517 |
+
r2_out_after = len(r2.req.output_ids) if r2.req is not None else 64
|
| 518 |
+
assert r2_out_after > r2_out_before, (
|
| 519 |
+
f"r2's decode must progress while r1 chunks; output_ids stayed at "
|
| 520 |
+
f"{r2_out_before}"
|
| 521 |
+
)
|
| 522 |
+
assert saw_r2_decode_during_chunking, (
|
| 523 |
+
"r2 was never observed co-batched (decode/mixed) while r1 held "
|
| 524 |
+
"the chunked slot"
|
| 525 |
+
)
|
| 526 |
+
|
| 527 |
+
t.abort(r2)
|
| 528 |
+
yield from run_until_finished(r1)
|
| 529 |
+
for _ in range(40):
|
| 530 |
+
if t.is_fully_idle:
|
| 531 |
+
break
|
| 532 |
+
yield
|
| 533 |
+
assert r1.finished
|
| 534 |
+
|
| 535 |
+
|
| 536 |
+
if __name__ == "__main__":
|
| 537 |
+
unittest.main()
|
asian_ai/performance/SGLang/test/manual/chunked_prefill/test_scripted_page_size.py
ADDED
|
@@ -0,0 +1,106 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import unittest
|
| 2 |
+
|
| 3 |
+
from sglang.test.scripted_runtime.context import ScriptedContext
|
| 4 |
+
from sglang.test.scripted_runtime.test_case import ScriptedTestCase
|
| 5 |
+
from sglang.test.scripted_runtime_chunked_helpers import (
|
| 6 |
+
base_engine_kwargs,
|
| 7 |
+
run_until_finished,
|
| 8 |
+
)
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
class TestPageSize16ChunkSize16(ScriptedTestCase):
|
| 12 |
+
ENGINE_KWARGS = base_engine_kwargs(chunked_prefill_size=16, page_size=16)
|
| 13 |
+
|
| 14 |
+
def test_chunk_size_equals_page_size(self):
|
| 15 |
+
self.server.execute_script(self._script_chunk_size_equals_page_size)
|
| 16 |
+
|
| 17 |
+
@staticmethod
|
| 18 |
+
def _script_chunk_size_equals_page_size(t: ScriptedContext):
|
| 19 |
+
r = t.start_req(prompt_len=8 * 16, max_new_tokens=2)
|
| 20 |
+
yield from run_until_finished(r, max_steps=400)
|
| 21 |
+
assert r.finished
|
| 22 |
+
assert r.chunks_done == 8
|
| 23 |
+
assert r.kv_pages == 0
|
| 24 |
+
|
| 25 |
+
def test_chunk_size_equals_page_size_plus_one(self):
|
| 26 |
+
self.server.execute_script(self._script_chunk_size_equals_page_size_plus_one)
|
| 27 |
+
|
| 28 |
+
@staticmethod
|
| 29 |
+
def _script_chunk_size_equals_page_size_plus_one(t: ScriptedContext):
|
| 30 |
+
r = t.start_req(prompt_len=129, max_new_tokens=2)
|
| 31 |
+
yield from run_until_finished(r, max_steps=400)
|
| 32 |
+
assert r.finished
|
| 33 |
+
assert r.chunks_done == 9
|
| 34 |
+
assert r.kv_pages == 0
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
class TestPageSize16ChunkSize16NonMultiplePrompt(ScriptedTestCase):
|
| 38 |
+
ENGINE_KWARGS = base_engine_kwargs(chunked_prefill_size=16, page_size=16)
|
| 39 |
+
|
| 40 |
+
def test_non_page_multiple_prompt_advances_in_page_steps(self):
|
| 41 |
+
self.server.execute_script(
|
| 42 |
+
self._script_non_page_multiple_prompt_advances_in_page_steps
|
| 43 |
+
)
|
| 44 |
+
|
| 45 |
+
@staticmethod
|
| 46 |
+
def _script_non_page_multiple_prompt_advances_in_page_steps(t: ScriptedContext):
|
| 47 |
+
r = t.start_req(prompt_len=60, max_new_tokens=2)
|
| 48 |
+
yield from run_until_finished(r, max_steps=400)
|
| 49 |
+
assert r.finished
|
| 50 |
+
assert r.chunks_done == 4
|
| 51 |
+
assert r.kv_pages == 0
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
class TestPageSize16ChunkSize64(ScriptedTestCase):
|
| 55 |
+
ENGINE_KWARGS = base_engine_kwargs(chunked_prefill_size=64, page_size=16)
|
| 56 |
+
|
| 57 |
+
def test_chunk_spans_multiple_pages_exact(self):
|
| 58 |
+
self.server.execute_script(self._script_chunk_spans_multiple_pages_exact)
|
| 59 |
+
|
| 60 |
+
@staticmethod
|
| 61 |
+
def _script_chunk_spans_multiple_pages_exact(t: ScriptedContext):
|
| 62 |
+
r = t.start_req(prompt_len=4 * 64, max_new_tokens=2)
|
| 63 |
+
yield from run_until_finished(r, max_steps=400)
|
| 64 |
+
assert r.finished
|
| 65 |
+
assert r.chunks_done == 4
|
| 66 |
+
assert r.kv_pages == 0
|
| 67 |
+
|
| 68 |
+
def test_chunk_spans_multiple_pages_plus_one_page(self):
|
| 69 |
+
self.server.execute_script(
|
| 70 |
+
self._script_chunk_spans_multiple_pages_plus_one_page
|
| 71 |
+
)
|
| 72 |
+
|
| 73 |
+
@staticmethod
|
| 74 |
+
def _script_chunk_spans_multiple_pages_plus_one_page(t: ScriptedContext):
|
| 75 |
+
r = t.start_req(prompt_len=4 * 64 + 16, max_new_tokens=2)
|
| 76 |
+
yield from run_until_finished(r, max_steps=400)
|
| 77 |
+
assert r.finished
|
| 78 |
+
assert r.chunks_done == 5
|
| 79 |
+
assert r.kv_pages == 0
|
| 80 |
+
|
| 81 |
+
|
| 82 |
+
class TestPageSize16RadixHit(ScriptedTestCase):
|
| 83 |
+
ENGINE_KWARGS = base_engine_kwargs(
|
| 84 |
+
chunked_prefill_size=16, page_size=16, disable_radix_cache=False
|
| 85 |
+
)
|
| 86 |
+
|
| 87 |
+
def test_radix_hit_on_page_boundary(self):
|
| 88 |
+
self.server.execute_script(self._script_radix_hit_on_page_boundary)
|
| 89 |
+
|
| 90 |
+
@staticmethod
|
| 91 |
+
def _script_radix_hit_on_page_boundary(t: ScriptedContext):
|
| 92 |
+
r_warm = t.start_req(prompt_len=4 * 16, max_new_tokens=1)
|
| 93 |
+
yield from run_until_finished(r_warm, max_steps=400)
|
| 94 |
+
assert r_warm.finished
|
| 95 |
+
|
| 96 |
+
yield
|
| 97 |
+
|
| 98 |
+
r = t.start_req(prompt_len=8 * 16, max_new_tokens=1)
|
| 99 |
+
yield from run_until_finished(r, max_steps=400)
|
| 100 |
+
assert r.finished
|
| 101 |
+
assert r.chunks_done == 4
|
| 102 |
+
assert r.kv_pages == 0
|
| 103 |
+
|
| 104 |
+
|
| 105 |
+
if __name__ == "__main__":
|
| 106 |
+
unittest.main()
|
asian_ai/performance/SGLang/test/manual/chunked_prefill/test_scripted_piecewise_cuda_graph.py
ADDED
|
@@ -0,0 +1,67 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import unittest
|
| 2 |
+
|
| 3 |
+
from sglang.test.scripted_runtime.context import ScriptedContext
|
| 4 |
+
from sglang.test.scripted_runtime.test_case import ScriptedTestCase
|
| 5 |
+
from sglang.test.scripted_runtime_chunked_helpers import (
|
| 6 |
+
DEFAULT_CHUNK_SIZE,
|
| 7 |
+
VERY_LONG_PROMPT_LEN,
|
| 8 |
+
base_engine_kwargs,
|
| 9 |
+
run_until,
|
| 10 |
+
run_until_finished,
|
| 11 |
+
)
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
class TestPiecewiseBasic(ScriptedTestCase):
|
| 15 |
+
ENGINE_KWARGS = base_engine_kwargs(
|
| 16 |
+
chunked_prefill_size=DEFAULT_CHUNK_SIZE,
|
| 17 |
+
disable_cuda_graph=False,
|
| 18 |
+
)
|
| 19 |
+
|
| 20 |
+
def test_naive_piecewise_cg_chunked(self):
|
| 21 |
+
self.server.execute_script(self._script_naive_piecewise_cg_chunked)
|
| 22 |
+
|
| 23 |
+
@staticmethod
|
| 24 |
+
def _script_naive_piecewise_cg_chunked(t: ScriptedContext):
|
| 25 |
+
r = t.start_req(prompt_len=VERY_LONG_PROMPT_LEN, max_new_tokens=8)
|
| 26 |
+
yield from run_until_finished(r)
|
| 27 |
+
assert r.finished
|
| 28 |
+
assert r.chunks_done >= 2
|
| 29 |
+
|
| 30 |
+
def test_piecewise_cg_tail_chunk_tiny(self):
|
| 31 |
+
self.server.execute_script(self._script_piecewise_cg_tail_chunk_tiny)
|
| 32 |
+
|
| 33 |
+
@staticmethod
|
| 34 |
+
def _script_piecewise_cg_tail_chunk_tiny(t: ScriptedContext):
|
| 35 |
+
r = t.start_req(
|
| 36 |
+
prompt_len=4 * DEFAULT_CHUNK_SIZE + 1,
|
| 37 |
+
max_new_tokens=2,
|
| 38 |
+
)
|
| 39 |
+
yield from run_until_finished(r, max_steps=800)
|
| 40 |
+
assert r.finished
|
| 41 |
+
assert r.chunks_done == 5
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
class TestPiecewiseRetractResume(ScriptedTestCase):
|
| 45 |
+
ENGINE_KWARGS = base_engine_kwargs(
|
| 46 |
+
chunked_prefill_size=DEFAULT_CHUNK_SIZE,
|
| 47 |
+
disable_cuda_graph=False,
|
| 48 |
+
)
|
| 49 |
+
|
| 50 |
+
def test_piecewise_cg_retract_resume(self):
|
| 51 |
+
self.server.execute_script(self._script_piecewise_cg_retract_resume)
|
| 52 |
+
|
| 53 |
+
@staticmethod
|
| 54 |
+
def _script_piecewise_cg_retract_resume(t: ScriptedContext):
|
| 55 |
+
r = t.start_req(prompt_len=VERY_LONG_PROMPT_LEN, max_new_tokens=4)
|
| 56 |
+
yield from run_until(r, lambda h: h.is_chunking and h.chunks_done >= 1)
|
| 57 |
+
t.pause_generation(mode="retract")
|
| 58 |
+
yield
|
| 59 |
+
t.continue_generation()
|
| 60 |
+
yield from run_until_finished(r, max_steps=800)
|
| 61 |
+
assert r.finished
|
| 62 |
+
assert r.kv_pages == 0
|
| 63 |
+
assert r.lock_refs == 0
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
if __name__ == "__main__":
|
| 67 |
+
unittest.main()
|
asian_ai/performance/SGLang/test/manual/chunked_prefill/test_scripted_pp.py
ADDED
|
@@ -0,0 +1,246 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import unittest
|
| 2 |
+
from typing import Any, Dict
|
| 3 |
+
|
| 4 |
+
from sglang.test.scripted_runtime.context import ScriptedContext
|
| 5 |
+
from sglang.test.scripted_runtime.test_case import ScriptedTestCase
|
| 6 |
+
from sglang.test.scripted_runtime_chunked_helpers import (
|
| 7 |
+
DEFAULT_CHUNK_SIZE,
|
| 8 |
+
VERY_LONG_PROMPT_LEN,
|
| 9 |
+
base_engine_kwargs,
|
| 10 |
+
run_until,
|
| 11 |
+
run_until_all_finished,
|
| 12 |
+
run_until_finished,
|
| 13 |
+
)
|
| 14 |
+
from sglang.test.test_utils import DEFAULT_MODEL_NAME_FOR_TEST
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
def _pp_engine_kwargs(*, pp_size: int = 2, **overrides: Any) -> Dict[str, Any]:
|
| 18 |
+
return base_engine_kwargs(
|
| 19 |
+
model_path=DEFAULT_MODEL_NAME_FOR_TEST,
|
| 20 |
+
pp_size=pp_size,
|
| 21 |
+
**overrides,
|
| 22 |
+
)
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
def _expected_chunks(prompt_len: int, chunk_size: int) -> int:
|
| 26 |
+
if prompt_len <= chunk_size:
|
| 27 |
+
return 0
|
| 28 |
+
return (prompt_len + chunk_size - 1) // chunk_size
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
def _drain_until_released(t, *handles):
|
| 32 |
+
for _ in range(16):
|
| 33 |
+
if all(
|
| 34 |
+
h.kv_pages == 0 and (h.req is None or h.req.req_pool_idx is None)
|
| 35 |
+
for h in handles
|
| 36 |
+
):
|
| 37 |
+
return
|
| 38 |
+
yield
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
class TestPPBasic(ScriptedTestCase):
|
| 42 |
+
ENGINE_KWARGS = _pp_engine_kwargs()
|
| 43 |
+
|
| 44 |
+
def test_pp_abort_during_inflight_chunk(self):
|
| 45 |
+
self.server.execute_script(self._script_pp_abort_during_inflight_chunk)
|
| 46 |
+
|
| 47 |
+
@staticmethod
|
| 48 |
+
def _script_pp_abort_during_inflight_chunk(t: ScriptedContext):
|
| 49 |
+
r = t.start_req(prompt_len=VERY_LONG_PROMPT_LEN, max_new_tokens=4)
|
| 50 |
+
yield from run_until(r, lambda h: h.is_chunking and h.chunks_done >= 1)
|
| 51 |
+
t.abort(r)
|
| 52 |
+
yield from _drain_until_released(t, r)
|
| 53 |
+
assert r.kv_pages == 0
|
| 54 |
+
assert r.lock_refs == 0
|
| 55 |
+
|
| 56 |
+
def test_pp_last_chunk_cross_mb_kv_correctness(self):
|
| 57 |
+
self.server.execute_script(self._script_pp_last_chunk_cross_mb_kv_correctness)
|
| 58 |
+
|
| 59 |
+
@staticmethod
|
| 60 |
+
def _script_pp_last_chunk_cross_mb_kv_correctness(t: ScriptedContext):
|
| 61 |
+
r = t.start_req(
|
| 62 |
+
prompt_len=VERY_LONG_PROMPT_LEN,
|
| 63 |
+
max_new_tokens=8,
|
| 64 |
+
prompt_token=7,
|
| 65 |
+
ignore_eos=True,
|
| 66 |
+
)
|
| 67 |
+
yield from run_until_finished(r, max_steps=800)
|
| 68 |
+
assert r.finished
|
| 69 |
+
expected_chunks = _expected_chunks(VERY_LONG_PROMPT_LEN, DEFAULT_CHUNK_SIZE)
|
| 70 |
+
assert r.chunks_done == expected_chunks, (
|
| 71 |
+
f"cross-mb chunked prefill must complete all {expected_chunks} chunks, "
|
| 72 |
+
f"got chunks_done={r.chunks_done}"
|
| 73 |
+
)
|
| 74 |
+
|
| 75 |
+
def test_pp_static_chunk_size_predictor_returns_none(self):
|
| 76 |
+
self.server.execute_script(
|
| 77 |
+
self._script_pp_static_chunk_size_predictor_returns_none
|
| 78 |
+
)
|
| 79 |
+
|
| 80 |
+
@staticmethod
|
| 81 |
+
def _script_pp_static_chunk_size_predictor_returns_none(t: ScriptedContext):
|
| 82 |
+
sched = t.scheduler
|
| 83 |
+
assert sched.enable_dynamic_chunking is False
|
| 84 |
+
assert sched.predict_next_chunk_size(0) is None
|
| 85 |
+
assert sched.predict_next_chunk_size(VERY_LONG_PROMPT_LEN // 2) is None
|
| 86 |
+
r = t.start_req(prompt_len=VERY_LONG_PROMPT_LEN, max_new_tokens=2)
|
| 87 |
+
yield from run_until_finished(r, max_steps=800)
|
| 88 |
+
assert r.finished
|
| 89 |
+
expected = _expected_chunks(VERY_LONG_PROMPT_LEN, DEFAULT_CHUNK_SIZE)
|
| 90 |
+
assert r.chunks_done == expected, (
|
| 91 |
+
f"static chunked_prefill_size must produce exactly {expected} chunks, "
|
| 92 |
+
f"got {r.chunks_done}"
|
| 93 |
+
)
|
| 94 |
+
|
| 95 |
+
def test_pp_multi_microbatch_chunks_done_aggregation(self):
|
| 96 |
+
self.server.execute_script(
|
| 97 |
+
self._script_pp_multi_microbatch_chunks_done_aggregation
|
| 98 |
+
)
|
| 99 |
+
|
| 100 |
+
@staticmethod
|
| 101 |
+
def _script_pp_multi_microbatch_chunks_done_aggregation(t: ScriptedContext):
|
| 102 |
+
r = t.start_req(prompt_len=4 * DEFAULT_CHUNK_SIZE, max_new_tokens=2)
|
| 103 |
+
yield from run_until_finished(r, max_steps=800)
|
| 104 |
+
assert r.finished
|
| 105 |
+
assert r.chunks_done >= 4, (
|
| 106 |
+
f"PP=2 multi-chunk req should aggregate >=4 chunks_done across "
|
| 107 |
+
f"microbatches, got {r.chunks_done}"
|
| 108 |
+
)
|
| 109 |
+
|
| 110 |
+
def test_pp_two_chunked_one_per_mb_simultaneous(self):
|
| 111 |
+
self.server.execute_script(self._script_pp_two_chunked_one_per_mb_simultaneous)
|
| 112 |
+
|
| 113 |
+
@staticmethod
|
| 114 |
+
def _script_pp_two_chunked_one_per_mb_simultaneous(t: ScriptedContext):
|
| 115 |
+
r1 = t.start_req(
|
| 116 |
+
prompt_len=VERY_LONG_PROMPT_LEN, max_new_tokens=2, prompt_token=1
|
| 117 |
+
)
|
| 118 |
+
r2 = t.start_req(
|
| 119 |
+
prompt_len=VERY_LONG_PROMPT_LEN, max_new_tokens=2, prompt_token=2
|
| 120 |
+
)
|
| 121 |
+
yield from run_until_all_finished(handles=[r1, r2], max_steps=800)
|
| 122 |
+
assert r1.finished and r2.finished
|
| 123 |
+
assert r1.chunks_done >= 2 and r2.chunks_done >= 2
|
| 124 |
+
assert r1.kv_pages == 0 and r2.kv_pages == 0
|
| 125 |
+
assert r1.lock_refs == 0 and r2.lock_refs == 0
|
| 126 |
+
|
| 127 |
+
def test_pp_retract_chunked_in_middle_mb(self):
|
| 128 |
+
self.server.execute_script(self._script_pp_retract_chunked_in_middle_mb)
|
| 129 |
+
|
| 130 |
+
@staticmethod
|
| 131 |
+
def _script_pp_retract_chunked_in_middle_mb(t: ScriptedContext):
|
| 132 |
+
r = t.start_req(prompt_len=VERY_LONG_PROMPT_LEN, max_new_tokens=2)
|
| 133 |
+
yield from run_until(r, lambda h: h.is_chunking and h.chunks_done >= 1)
|
| 134 |
+
t.pause_generation(mode="retract")
|
| 135 |
+
yield
|
| 136 |
+
t.continue_generation()
|
| 137 |
+
yield from run_until_finished(r, max_steps=800)
|
| 138 |
+
assert r.finished
|
| 139 |
+
assert r.kv_pages == 0
|
| 140 |
+
assert r.lock_refs == 0
|
| 141 |
+
|
| 142 |
+
def test_pp_chunked_req_to_exclude_pp_context(self):
|
| 143 |
+
self.server.execute_script(self._script_pp_chunked_req_to_exclude_pp_context)
|
| 144 |
+
|
| 145 |
+
@staticmethod
|
| 146 |
+
def _script_pp_chunked_req_to_exclude_pp_context(t: ScriptedContext):
|
| 147 |
+
r = t.start_req(prompt_len=VERY_LONG_PROMPT_LEN, max_new_tokens=2)
|
| 148 |
+
yield from run_until(r, lambda h: h.is_chunking)
|
| 149 |
+
t.abort(r)
|
| 150 |
+
r2 = t.start_req(prompt_len=DEFAULT_CHUNK_SIZE * 2, max_new_tokens=2)
|
| 151 |
+
yield from run_until_finished(r2, max_steps=400)
|
| 152 |
+
assert r2.finished
|
| 153 |
+
assert r2.kv_pages == 0
|
| 154 |
+
assert r2.lock_refs == 0
|
| 155 |
+
|
| 156 |
+
|
| 157 |
+
@unittest.skip(
|
| 158 |
+
"PD-Multiplexing is mutually exclusive with pipeline parallelism: ServerArgs "
|
| 159 |
+
"asserts pp_size == 1 (server_args.py:7284-7287, 'PD-Multiplexing is only "
|
| 160 |
+
"supported with pipeline parallelism disabled'). It further requires "
|
| 161 |
+
"chunked_prefill_size == -1 and disable_overlap_schedule, both of which the PP "
|
| 162 |
+
"chunked scripted-runtime harness mandates the opposite of. enable_pdmux=True "
|
| 163 |
+
"with pp_size=2 therefore cannot launch -- the spawned server dies on that "
|
| 164 |
+
"assert and setUpClass times out on the handshake. This is a genuine engine "
|
| 165 |
+
"config constraint, not a test bug, so the pdmux-under-PP scenario is not a "
|
| 166 |
+
"valid combination to exercise here."
|
| 167 |
+
)
|
| 168 |
+
class TestPPPdmux(ScriptedTestCase):
|
| 169 |
+
ENGINE_KWARGS = _pp_engine_kwargs(enable_pdmux=True)
|
| 170 |
+
|
| 171 |
+
def test_pp_split_prefill_chunked_no_merge_assert(self):
|
| 172 |
+
self.server.execute_script(
|
| 173 |
+
self._script_pp_split_prefill_chunked_no_merge_assert
|
| 174 |
+
)
|
| 175 |
+
|
| 176 |
+
@staticmethod
|
| 177 |
+
def _script_pp_split_prefill_chunked_no_merge_assert(t: ScriptedContext):
|
| 178 |
+
r = t.start_req(prompt_len=VERY_LONG_PROMPT_LEN, max_new_tokens=2)
|
| 179 |
+
yield from run_until_finished(r, max_steps=800)
|
| 180 |
+
assert (
|
| 181 |
+
r.finished
|
| 182 |
+
), "engine died before req finished — merge_batch assert may have tripped"
|
| 183 |
+
assert r.chunks_done >= 2, (
|
| 184 |
+
f"pdmux + chunked path must produce >=2 chunks to exercise "
|
| 185 |
+
f"split_prefill_batch filter; got chunks_done={r.chunks_done}"
|
| 186 |
+
)
|
| 187 |
+
|
| 188 |
+
|
| 189 |
+
class TestPPDynamic(ScriptedTestCase):
|
| 190 |
+
ENGINE_KWARGS = _pp_engine_kwargs(enable_dynamic_chunking=True)
|
| 191 |
+
|
| 192 |
+
def test_naive_pp_chunked(self):
|
| 193 |
+
self.server.execute_script(self._script_naive_pp_chunked)
|
| 194 |
+
|
| 195 |
+
@staticmethod
|
| 196 |
+
def _script_naive_pp_chunked(t: ScriptedContext):
|
| 197 |
+
r = t.start_req(
|
| 198 |
+
prompt_len=VERY_LONG_PROMPT_LEN,
|
| 199 |
+
max_new_tokens=4,
|
| 200 |
+
prompt_token=3,
|
| 201 |
+
ignore_eos=True,
|
| 202 |
+
)
|
| 203 |
+
yield from run_until_finished(r, max_steps=800)
|
| 204 |
+
assert r.finished
|
| 205 |
+
assert r.chunks_done >= 2, f"expected >=2 chunks, got {r.chunks_done}"
|
| 206 |
+
|
| 207 |
+
def test_pp_dynamic_chunk_size_recompute_branch_taken(self):
|
| 208 |
+
self.server.execute_script(
|
| 209 |
+
self._script_pp_dynamic_chunk_size_recompute_branch_taken
|
| 210 |
+
)
|
| 211 |
+
|
| 212 |
+
@staticmethod
|
| 213 |
+
def _script_pp_dynamic_chunk_size_recompute_branch_taken(t: ScriptedContext):
|
| 214 |
+
sched = t.scheduler
|
| 215 |
+
assert sched.enable_dynamic_chunking is True
|
| 216 |
+
assert sched.length_predictor is not None
|
| 217 |
+
assert sched.length_predictor.is_ready is True
|
| 218 |
+
dynamic_size = sched.predict_next_chunk_size(0)
|
| 219 |
+
assert dynamic_size is not None
|
| 220 |
+
assert isinstance(dynamic_size, int) and dynamic_size > 0
|
| 221 |
+
r = t.start_req(
|
| 222 |
+
prompt_len=VERY_LONG_PROMPT_LEN, max_new_tokens=2, prompt_token=4
|
| 223 |
+
)
|
| 224 |
+
yield from run_until_finished(r, max_steps=800)
|
| 225 |
+
assert r.finished
|
| 226 |
+
assert r.chunks_done >= 2, f"expected >=2 chunks, got {r.chunks_done}"
|
| 227 |
+
|
| 228 |
+
|
| 229 |
+
class TestPPSize4(ScriptedTestCase):
|
| 230 |
+
ENGINE_KWARGS = _pp_engine_kwargs(pp_size=4)
|
| 231 |
+
|
| 232 |
+
def test_pp_size_4_chunked_completes(self):
|
| 233 |
+
self.server.execute_script(self._script_pp_size_4_chunked_completes)
|
| 234 |
+
|
| 235 |
+
@staticmethod
|
| 236 |
+
def _script_pp_size_4_chunked_completes(t: ScriptedContext):
|
| 237 |
+
r = t.start_req(prompt_len=VERY_LONG_PROMPT_LEN, max_new_tokens=4)
|
| 238 |
+
yield from run_until_finished(r, max_steps=800)
|
| 239 |
+
assert r.finished
|
| 240 |
+
assert r.chunks_done >= 4
|
| 241 |
+
assert r.kv_pages == 0
|
| 242 |
+
assert r.lock_refs == 0
|
| 243 |
+
|
| 244 |
+
|
| 245 |
+
if __name__ == "__main__":
|
| 246 |
+
unittest.main()
|
asian_ai/performance/SGLang/test/manual/chunked_prefill/test_scripted_priority.py
ADDED
|
@@ -0,0 +1,309 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import unittest
|
| 2 |
+
|
| 3 |
+
from sglang.test.scripted_runtime.context import ScriptedContext
|
| 4 |
+
from sglang.test.scripted_runtime.test_case import ScriptedTestCase
|
| 5 |
+
from sglang.test.scripted_runtime_chunked_helpers import (
|
| 6 |
+
BALLAST_MAX_NEW_TOKENS,
|
| 7 |
+
DEFAULT_CHUNK_SIZE,
|
| 8 |
+
VERY_LONG_PROMPT_LEN,
|
| 9 |
+
base_engine_kwargs,
|
| 10 |
+
run_until,
|
| 11 |
+
run_until_all_finished,
|
| 12 |
+
run_until_finished,
|
| 13 |
+
)
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
class TestPriorityBasic(ScriptedTestCase):
|
| 17 |
+
ENGINE_KWARGS = base_engine_kwargs(chunked_prefill_size=DEFAULT_CHUNK_SIZE)
|
| 18 |
+
|
| 19 |
+
def test_retract_mid_chunk_releases_kv(self):
|
| 20 |
+
self.server.execute_script(self._script_retract_mid_chunk_releases_kv)
|
| 21 |
+
|
| 22 |
+
@staticmethod
|
| 23 |
+
def _script_retract_mid_chunk_releases_kv(t: ScriptedContext):
|
| 24 |
+
r = t.start_req(prompt_len=VERY_LONG_PROMPT_LEN, max_new_tokens=2)
|
| 25 |
+
yield from run_until(r, lambda h: h.is_chunking and h.chunks_done >= 1)
|
| 26 |
+
|
| 27 |
+
pages_before = r.kv_pages
|
| 28 |
+
assert pages_before > 0
|
| 29 |
+
|
| 30 |
+
t.pause_generation(mode="retract")
|
| 31 |
+
yield
|
| 32 |
+
|
| 33 |
+
assert (
|
| 34 |
+
r.status == "waiting"
|
| 35 |
+
), f"force-retracted chunked req must be back in waiting; got {r.status}"
|
| 36 |
+
assert r.kv_pages == 0, f"retract must release KV; got {r.kv_pages}"
|
| 37 |
+
|
| 38 |
+
t.continue_generation()
|
| 39 |
+
yield from run_until_finished(r)
|
| 40 |
+
assert r.finished
|
| 41 |
+
assert r.kv_pages == 0
|
| 42 |
+
assert r.lock_refs == 0
|
| 43 |
+
|
| 44 |
+
def test_retract_and_resume(self):
|
| 45 |
+
self.server.execute_script(self._script_retract_and_resume)
|
| 46 |
+
|
| 47 |
+
@staticmethod
|
| 48 |
+
def _script_retract_and_resume(t: ScriptedContext):
|
| 49 |
+
r = t.start_req(prompt_len=VERY_LONG_PROMPT_LEN, max_new_tokens=2)
|
| 50 |
+
yield from run_until(r, lambda h: h.is_chunking and h.chunks_done >= 1)
|
| 51 |
+
|
| 52 |
+
t.pause_generation(mode="retract")
|
| 53 |
+
yield
|
| 54 |
+
assert r.status == "waiting"
|
| 55 |
+
assert r.kv_pages == 0
|
| 56 |
+
|
| 57 |
+
t.continue_generation()
|
| 58 |
+
yield from run_until_finished(r)
|
| 59 |
+
assert r.finished
|
| 60 |
+
|
| 61 |
+
def test_force_retract_at_chunk_0(self):
|
| 62 |
+
self.server.execute_script(self._script_force_retract_at_chunk_0)
|
| 63 |
+
|
| 64 |
+
@staticmethod
|
| 65 |
+
def _script_force_retract_at_chunk_0(t: ScriptedContext):
|
| 66 |
+
r = t.start_req(prompt_len=VERY_LONG_PROMPT_LEN, max_new_tokens=2)
|
| 67 |
+
yield from run_until(r, lambda h: h.is_chunking and h.chunks_done <= 1)
|
| 68 |
+
t.pause_generation(mode="retract")
|
| 69 |
+
yield
|
| 70 |
+
assert r.kv_pages == 0
|
| 71 |
+
t.continue_generation()
|
| 72 |
+
yield from run_until_finished(r, max_steps=800)
|
| 73 |
+
assert r.finished
|
| 74 |
+
|
| 75 |
+
def test_force_retract_at_chunk_mid(self):
|
| 76 |
+
self.server.execute_script(self._script_force_retract_at_chunk_mid)
|
| 77 |
+
|
| 78 |
+
@staticmethod
|
| 79 |
+
def _script_force_retract_at_chunk_mid(t: ScriptedContext):
|
| 80 |
+
r = t.start_req(prompt_len=VERY_LONG_PROMPT_LEN, max_new_tokens=2)
|
| 81 |
+
yield from run_until(r, lambda h: h.chunks_done >= 2 and h.is_chunking)
|
| 82 |
+
t.pause_generation(mode="retract")
|
| 83 |
+
yield
|
| 84 |
+
assert r.kv_pages == 0
|
| 85 |
+
t.continue_generation()
|
| 86 |
+
yield from run_until_finished(r, max_steps=800)
|
| 87 |
+
assert r.finished
|
| 88 |
+
assert r.lock_refs == 0
|
| 89 |
+
|
| 90 |
+
def test_force_retract_at_last_chunk(self):
|
| 91 |
+
self.server.execute_script(self._script_force_retract_at_last_chunk)
|
| 92 |
+
|
| 93 |
+
@staticmethod
|
| 94 |
+
def _script_force_retract_at_last_chunk(t: ScriptedContext):
|
| 95 |
+
r = t.start_req(prompt_len=2 * DEFAULT_CHUNK_SIZE, max_new_tokens=4)
|
| 96 |
+
yield from run_until(r, lambda h: h.chunks_done >= 1 and h.is_chunking)
|
| 97 |
+
t.pause_generation(mode="retract")
|
| 98 |
+
yield
|
| 99 |
+
assert r.kv_pages == 0
|
| 100 |
+
t.continue_generation()
|
| 101 |
+
yield from run_until_finished(r, max_steps=800)
|
| 102 |
+
assert r.finished
|
| 103 |
+
assert r.kv_pages == 0
|
| 104 |
+
assert r.lock_refs == 0
|
| 105 |
+
|
| 106 |
+
def test_force_retract_then_readmit(self):
|
| 107 |
+
self.server.execute_script(self._script_force_retract_then_readmit)
|
| 108 |
+
|
| 109 |
+
@staticmethod
|
| 110 |
+
def _script_force_retract_then_readmit(t: ScriptedContext):
|
| 111 |
+
r = t.start_req(prompt_len=VERY_LONG_PROMPT_LEN, max_new_tokens=2)
|
| 112 |
+
yield from run_until(r, lambda h: h.is_chunking)
|
| 113 |
+
t.pause_generation(mode="retract")
|
| 114 |
+
yield
|
| 115 |
+
assert r.kv_pages == 0, "retract must release KV before re-admission"
|
| 116 |
+
t.continue_generation()
|
| 117 |
+
yield from run_until_finished(r, max_steps=800)
|
| 118 |
+
assert r.finished
|
| 119 |
+
assert r.kv_pages == 0
|
| 120 |
+
assert r.lock_refs == 0
|
| 121 |
+
|
| 122 |
+
def test_retract_one_admit_one(self):
|
| 123 |
+
self.server.execute_script(self._script_retract_one_admit_one)
|
| 124 |
+
|
| 125 |
+
@staticmethod
|
| 126 |
+
def _script_retract_one_admit_one(t: ScriptedContext):
|
| 127 |
+
r1 = t.start_req(prompt_len=VERY_LONG_PROMPT_LEN, max_new_tokens=2)
|
| 128 |
+
yield from run_until(r1, lambda h: h.is_chunking)
|
| 129 |
+
r2 = t.start_req(prompt_len=8, max_new_tokens=2)
|
| 130 |
+
t.pause_generation(mode="retract")
|
| 131 |
+
yield
|
| 132 |
+
t.continue_generation()
|
| 133 |
+
yield from run_until_finished(r2)
|
| 134 |
+
assert r2.finished
|
| 135 |
+
assert r2.kv_pages == 0
|
| 136 |
+
yield from run_until_finished(r1)
|
| 137 |
+
assert r1.finished
|
| 138 |
+
assert r1.kv_pages == 0
|
| 139 |
+
assert r1.lock_refs == 0
|
| 140 |
+
|
| 141 |
+
def test_retract_during_decode(self):
|
| 142 |
+
self.server.execute_script(self._script_retract_during_decode)
|
| 143 |
+
|
| 144 |
+
@staticmethod
|
| 145 |
+
def _script_retract_during_decode(t: ScriptedContext):
|
| 146 |
+
r = t.start_req(prompt_len=8, max_new_tokens=32)
|
| 147 |
+
yield from run_until(r, lambda h: h.status == "running")
|
| 148 |
+
assert r.kv_pages > 0, "decode-state req must own KV before retract"
|
| 149 |
+
t.pause_generation(mode="retract")
|
| 150 |
+
yield
|
| 151 |
+
assert r.kv_pages == 0, f"retract must release KV; got {r.kv_pages}"
|
| 152 |
+
t.continue_generation()
|
| 153 |
+
yield from run_until_finished(r)
|
| 154 |
+
assert r.finished
|
| 155 |
+
assert r.kv_pages == 0
|
| 156 |
+
assert r.lock_refs == 0
|
| 157 |
+
|
| 158 |
+
def test_retract_then_abort_idempotent(self):
|
| 159 |
+
self.server.execute_script(self._script_retract_then_abort_idempotent)
|
| 160 |
+
|
| 161 |
+
@staticmethod
|
| 162 |
+
def _script_retract_then_abort_idempotent(t: ScriptedContext):
|
| 163 |
+
r = t.start_req(prompt_len=VERY_LONG_PROMPT_LEN, max_new_tokens=2)
|
| 164 |
+
yield from run_until(r, lambda h: h.is_chunking)
|
| 165 |
+
t.pause_generation(mode="retract")
|
| 166 |
+
t.abort(r)
|
| 167 |
+
for _ in range(12):
|
| 168 |
+
if (
|
| 169 |
+
r.kv_pages == 0
|
| 170 |
+
and r.lock_refs == 0
|
| 171 |
+
and (r.req is None or r.req.req_pool_idx is None)
|
| 172 |
+
):
|
| 173 |
+
break
|
| 174 |
+
yield
|
| 175 |
+
assert r.kv_pages == 0
|
| 176 |
+
assert r.lock_refs == 0
|
| 177 |
+
assert r.req is None or r.req.req_pool_idx is None
|
| 178 |
+
t.continue_generation()
|
| 179 |
+
yield
|
| 180 |
+
assert r.kv_pages == 0 and r.lock_refs == 0
|
| 181 |
+
|
| 182 |
+
def test_retract_chunked_resume_in_waiting(self):
|
| 183 |
+
self.server.execute_script(self._script_retract_chunked_resume_in_waiting)
|
| 184 |
+
|
| 185 |
+
@staticmethod
|
| 186 |
+
def _script_retract_chunked_resume_in_waiting(t: ScriptedContext):
|
| 187 |
+
r = t.start_req(prompt_len=VERY_LONG_PROMPT_LEN, max_new_tokens=2)
|
| 188 |
+
yield from run_until(r, lambda h: h.is_chunking)
|
| 189 |
+
t.pause_generation(mode="retract")
|
| 190 |
+
yield
|
| 191 |
+
assert r.kv_pages == 0
|
| 192 |
+
assert r.status == "waiting"
|
| 193 |
+
t.continue_generation()
|
| 194 |
+
yield from run_until_finished(r, max_steps=800)
|
| 195 |
+
assert r.finished
|
| 196 |
+
|
| 197 |
+
def test_two_retracts_same_yield(self):
|
| 198 |
+
self.server.execute_script(self._script_two_retracts_same_yield)
|
| 199 |
+
|
| 200 |
+
@staticmethod
|
| 201 |
+
def _script_two_retracts_same_yield(t: ScriptedContext):
|
| 202 |
+
r1 = t.start_req(prompt_len=VERY_LONG_PROMPT_LEN, max_new_tokens=2)
|
| 203 |
+
r2 = t.start_req(prompt_len=VERY_LONG_PROMPT_LEN, max_new_tokens=2)
|
| 204 |
+
yield from run_until(r1, lambda h: h.is_chunking)
|
| 205 |
+
t.pause_generation(mode="retract")
|
| 206 |
+
yield
|
| 207 |
+
assert r1.kv_pages == 0
|
| 208 |
+
assert r2.kv_pages == 0
|
| 209 |
+
t.continue_generation()
|
| 210 |
+
yield from run_until_all_finished([r1, r2])
|
| 211 |
+
assert r1.finished and r2.finished
|
| 212 |
+
assert r1.lock_refs == 0
|
| 213 |
+
assert r2.lock_refs == 0
|
| 214 |
+
|
| 215 |
+
def test_retract_then_re_chunk(self):
|
| 216 |
+
self.server.execute_script(self._script_retract_then_re_chunk)
|
| 217 |
+
|
| 218 |
+
@staticmethod
|
| 219 |
+
def _script_retract_then_re_chunk(t: ScriptedContext):
|
| 220 |
+
r = t.start_req(prompt_len=2 * DEFAULT_CHUNK_SIZE, max_new_tokens=2)
|
| 221 |
+
yield from run_until(r, lambda h: h.chunks_done >= 1)
|
| 222 |
+
t.pause_generation(mode="retract")
|
| 223 |
+
yield
|
| 224 |
+
assert r.kv_pages == 0, "retract must release KV"
|
| 225 |
+
t.continue_generation()
|
| 226 |
+
yield from run_until_finished(r, max_steps=800)
|
| 227 |
+
assert r.finished
|
| 228 |
+
assert r.lock_refs == 0
|
| 229 |
+
assert r.kv_pages == 0
|
| 230 |
+
|
| 231 |
+
|
| 232 |
+
class TestPriorityPriority(ScriptedTestCase):
|
| 233 |
+
ENGINE_KWARGS = base_engine_kwargs(
|
| 234 |
+
chunked_prefill_size=DEFAULT_CHUNK_SIZE,
|
| 235 |
+
enable_priority_scheduling=True,
|
| 236 |
+
)
|
| 237 |
+
|
| 238 |
+
def test_naive_priority_chunked(self):
|
| 239 |
+
self.server.execute_script(self._script_naive_priority_chunked)
|
| 240 |
+
|
| 241 |
+
@staticmethod
|
| 242 |
+
def _script_naive_priority_chunked(t: ScriptedContext):
|
| 243 |
+
low = t.start_req(prompt_len=VERY_LONG_PROMPT_LEN, max_new_tokens=4, priority=0)
|
| 244 |
+
yield from run_until(low, lambda h: h.is_chunking)
|
| 245 |
+
|
| 246 |
+
high = t.start_req(prompt_len=8, max_new_tokens=2, priority=10)
|
| 247 |
+
|
| 248 |
+
yield from run_until_finished(high)
|
| 249 |
+
assert high.finished
|
| 250 |
+
assert not low.finished
|
| 251 |
+
|
| 252 |
+
yield from run_until_all_finished([low, high])
|
| 253 |
+
assert low.finished and high.finished
|
| 254 |
+
|
| 255 |
+
|
| 256 |
+
class TestPriorityPreempt(ScriptedTestCase):
|
| 257 |
+
ENGINE_KWARGS = base_engine_kwargs(
|
| 258 |
+
chunked_prefill_size=DEFAULT_CHUNK_SIZE,
|
| 259 |
+
enable_priority_scheduling=True,
|
| 260 |
+
max_running_requests=1,
|
| 261 |
+
priority_scheduling_preemption_threshold=0,
|
| 262 |
+
)
|
| 263 |
+
|
| 264 |
+
def test_priority_preempt_decode_victim_to_waiting(self):
|
| 265 |
+
self.server.execute_script(
|
| 266 |
+
self._script_priority_preempt_decode_victim_to_waiting
|
| 267 |
+
)
|
| 268 |
+
|
| 269 |
+
@staticmethod
|
| 270 |
+
def _script_priority_preempt_decode_victim_to_waiting(t: ScriptedContext):
|
| 271 |
+
low = t.start_req(
|
| 272 |
+
prompt_len=8,
|
| 273 |
+
max_new_tokens=BALLAST_MAX_NEW_TOKENS,
|
| 274 |
+
priority=0,
|
| 275 |
+
ignore_eos=True,
|
| 276 |
+
)
|
| 277 |
+
yield from run_until(low, lambda h: h.status == "running")
|
| 278 |
+
assert low.kv_pages > 0
|
| 279 |
+
|
| 280 |
+
high = t.start_req(prompt_len=8, max_new_tokens=2, priority=10)
|
| 281 |
+
yield from run_until(low, lambda h: h.status == "waiting")
|
| 282 |
+
|
| 283 |
+
assert low.status == "waiting"
|
| 284 |
+
assert low.kv_pages == 0
|
| 285 |
+
yield from run_until_finished(high)
|
| 286 |
+
assert high.finished
|
| 287 |
+
|
| 288 |
+
def test_priority_preempt_release_invariant(self):
|
| 289 |
+
self.server.execute_script(self._script_priority_preempt_release_invariant)
|
| 290 |
+
|
| 291 |
+
@staticmethod
|
| 292 |
+
def _script_priority_preempt_release_invariant(t: ScriptedContext):
|
| 293 |
+
r_low = t.start_req(
|
| 294 |
+
prompt_len=8,
|
| 295 |
+
max_new_tokens=BALLAST_MAX_NEW_TOKENS,
|
| 296 |
+
priority=0,
|
| 297 |
+
ignore_eos=True,
|
| 298 |
+
)
|
| 299 |
+
yield from run_until(r_low, lambda h: h.status == "running")
|
| 300 |
+
pages_before = r_low.kv_pages
|
| 301 |
+
assert pages_before > 0
|
| 302 |
+
|
| 303 |
+
r_high = t.start_req(prompt_len=8, max_new_tokens=2, priority=10)
|
| 304 |
+
yield from run_until(r_low, lambda h: h.status == "waiting")
|
| 305 |
+
assert r_low.kv_pages == 0
|
| 306 |
+
|
| 307 |
+
|
| 308 |
+
if __name__ == "__main__":
|
| 309 |
+
unittest.main()
|
asian_ai/performance/SGLang/test/manual/chunked_prefill/test_scripted_radix.py
ADDED
|
@@ -0,0 +1,741 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import unittest
|
| 2 |
+
|
| 3 |
+
from sglang.test.scripted_runtime.context import ScriptedContext
|
| 4 |
+
from sglang.test.scripted_runtime.test_case import ScriptedTestCase
|
| 5 |
+
from sglang.test.scripted_runtime_chunked_helpers import (
|
| 6 |
+
DEFAULT_CHUNK_SIZE,
|
| 7 |
+
DEFAULT_MAX_STEPS,
|
| 8 |
+
VERY_LONG_PROMPT_LEN,
|
| 9 |
+
base_engine_kwargs,
|
| 10 |
+
run_until,
|
| 11 |
+
run_until_all_finished,
|
| 12 |
+
run_until_finished,
|
| 13 |
+
)
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
class TestRadixBasic(ScriptedTestCase):
|
| 17 |
+
ENGINE_KWARGS = base_engine_kwargs(chunked_prefill_size=DEFAULT_CHUNK_SIZE)
|
| 18 |
+
|
| 19 |
+
def test_radix_full_prefix_hit_nine_reqs(self):
|
| 20 |
+
self.server.execute_script(self._script_radix_full_prefix_hit_nine_reqs)
|
| 21 |
+
|
| 22 |
+
@staticmethod
|
| 23 |
+
def _script_radix_full_prefix_hit_nine_reqs(t: ScriptedContext):
|
| 24 |
+
r1 = t.start_req(prompt_len=VERY_LONG_PROMPT_LEN, max_new_tokens=2)
|
| 25 |
+
yield from run_until_finished(r1)
|
| 26 |
+
|
| 27 |
+
others = [
|
| 28 |
+
t.start_req(prompt_len=VERY_LONG_PROMPT_LEN, max_new_tokens=2)
|
| 29 |
+
for _ in range(9)
|
| 30 |
+
]
|
| 31 |
+
yield from run_until_all_finished(others)
|
| 32 |
+
for r in others:
|
| 33 |
+
assert r.chunks_done == 0
|
| 34 |
+
|
| 35 |
+
def test_radix_hit_full_prefix(self):
|
| 36 |
+
self.server.execute_script(self._script_radix_hit_full_prefix)
|
| 37 |
+
|
| 38 |
+
@staticmethod
|
| 39 |
+
def _script_radix_hit_full_prefix(t: ScriptedContext):
|
| 40 |
+
r1 = t.start_req(prompt_len=DEFAULT_CHUNK_SIZE, max_new_tokens=1)
|
| 41 |
+
yield from run_until_finished(r1)
|
| 42 |
+
|
| 43 |
+
r2 = t.start_req(prompt_len=DEFAULT_CHUNK_SIZE + 1, max_new_tokens=1)
|
| 44 |
+
yield from run_until_finished(r2)
|
| 45 |
+
assert r2.chunks_done == 0
|
| 46 |
+
|
| 47 |
+
def test_radix_hit_partial_then_chunk_tail(self):
|
| 48 |
+
self.server.execute_script(self._script_radix_hit_partial_then_chunk_tail)
|
| 49 |
+
|
| 50 |
+
@staticmethod
|
| 51 |
+
def _script_radix_hit_partial_then_chunk_tail(t: ScriptedContext):
|
| 52 |
+
r1 = t.start_req(prompt_len=2 * DEFAULT_CHUNK_SIZE, max_new_tokens=1)
|
| 53 |
+
yield from run_until_finished(r1)
|
| 54 |
+
|
| 55 |
+
r2 = t.start_req(prompt_len=3 * DEFAULT_CHUNK_SIZE + 1, max_new_tokens=1)
|
| 56 |
+
yield from run_until_finished(r2)
|
| 57 |
+
assert r2.chunks_done == 2
|
| 58 |
+
|
| 59 |
+
def test_radix_evict_then_resubmit_rechunks(self):
|
| 60 |
+
self.server.execute_script(self._script_radix_evict_then_resubmit_rechunks)
|
| 61 |
+
|
| 62 |
+
@staticmethod
|
| 63 |
+
def _script_radix_evict_then_resubmit_rechunks(t: ScriptedContext):
|
| 64 |
+
r1 = t.start_req(prompt_len=VERY_LONG_PROMPT_LEN, max_new_tokens=2)
|
| 65 |
+
yield from run_until_finished(r1)
|
| 66 |
+
assert r1.finished
|
| 67 |
+
for _ in range(5):
|
| 68 |
+
yield
|
| 69 |
+
t.evict_radix(prefix_tokens=None)
|
| 70 |
+
yield
|
| 71 |
+
|
| 72 |
+
r2 = t.start_req(prompt_len=VERY_LONG_PROMPT_LEN, max_new_tokens=2)
|
| 73 |
+
yield from run_until_finished(r2)
|
| 74 |
+
assert r2.finished
|
| 75 |
+
assert r2.chunks_done >= 2, (
|
| 76 |
+
f"after eviction r2 must re-chunk from scratch; "
|
| 77 |
+
f"chunks_done={r2.chunks_done} cached_tokens={r2.req.cached_tokens}"
|
| 78 |
+
)
|
| 79 |
+
assert (
|
| 80 |
+
r2.req.cached_tokens == 0
|
| 81 |
+
), f"eviction must clear r1's prefix; cached_tokens={r2.req.cached_tokens}"
|
| 82 |
+
assert r2.kv_pages == 0
|
| 83 |
+
assert r2.lock_refs == 0
|
| 84 |
+
|
| 85 |
+
def test_radix_resume_init_next_round_path(self):
|
| 86 |
+
self.server.execute_script(self._script_radix_resume_init_next_round_path)
|
| 87 |
+
|
| 88 |
+
@staticmethod
|
| 89 |
+
def _script_radix_resume_init_next_round_path(t: ScriptedContext):
|
| 90 |
+
r1 = t.start_req(prompt_len=VERY_LONG_PROMPT_LEN, max_new_tokens=1)
|
| 91 |
+
yield from run_until_finished(r1)
|
| 92 |
+
assert r1.finished
|
| 93 |
+
|
| 94 |
+
r2 = t.start_req(
|
| 95 |
+
prompt_len=VERY_LONG_PROMPT_LEN + 2 * DEFAULT_CHUNK_SIZE, max_new_tokens=2
|
| 96 |
+
)
|
| 97 |
+
yield from run_until_finished(r2)
|
| 98 |
+
assert r2.finished
|
| 99 |
+
assert r2.req.cached_tokens > 0, (
|
| 100 |
+
f"r2 must hit r1's prefix to exercise the partial-hit chunked-"
|
| 101 |
+
f"resume branch; got cached_tokens={r2.req.cached_tokens}"
|
| 102 |
+
)
|
| 103 |
+
assert r2.chunks_done >= 1, (
|
| 104 |
+
f"residual tail beyond cached prefix should still chunk; got "
|
| 105 |
+
f"chunks_done={r2.chunks_done}"
|
| 106 |
+
)
|
| 107 |
+
|
| 108 |
+
def test_radix_lock_ref_concurrent_chunked(self):
|
| 109 |
+
self.server.execute_script(self._script_radix_lock_ref_concurrent_chunked)
|
| 110 |
+
|
| 111 |
+
@staticmethod
|
| 112 |
+
def _script_radix_lock_ref_concurrent_chunked(t: ScriptedContext):
|
| 113 |
+
r_warm = t.start_req(prompt_len=DEFAULT_CHUNK_SIZE * 4, max_new_tokens=1)
|
| 114 |
+
yield from run_until_finished(r_warm)
|
| 115 |
+
reqs = [
|
| 116 |
+
t.start_req(prompt_len=DEFAULT_CHUNK_SIZE * 4 + 8, max_new_tokens=2)
|
| 117 |
+
for _ in range(5)
|
| 118 |
+
]
|
| 119 |
+
yield from run_until_all_finished(reqs)
|
| 120 |
+
for r in reqs:
|
| 121 |
+
assert r.finished
|
| 122 |
+
assert r.req.cached_tokens > 0
|
| 123 |
+
assert r.lock_refs == 0
|
| 124 |
+
|
| 125 |
+
def test_radix_partial_hit_exact_chunk_boundary(self):
|
| 126 |
+
self.server.execute_script(self._script_radix_partial_hit_exact_chunk_boundary)
|
| 127 |
+
|
| 128 |
+
@staticmethod
|
| 129 |
+
def _script_radix_partial_hit_exact_chunk_boundary(t: ScriptedContext):
|
| 130 |
+
r1 = t.start_req(prompt_len=DEFAULT_CHUNK_SIZE, max_new_tokens=1)
|
| 131 |
+
yield from run_until_finished(r1)
|
| 132 |
+
r2 = t.start_req(prompt_len=2 * DEFAULT_CHUNK_SIZE, max_new_tokens=1)
|
| 133 |
+
yield from run_until_finished(r2)
|
| 134 |
+
assert r2.chunks_done == 0, (
|
| 135 |
+
f"residual of exactly chunk_size must not chunk; "
|
| 136 |
+
f"chunks_done={r2.chunks_done} cached_tokens={r2.req.cached_tokens}"
|
| 137 |
+
)
|
| 138 |
+
|
| 139 |
+
def test_radix_two_distinct_prefixes(self):
|
| 140 |
+
self.server.execute_script(self._script_radix_two_distinct_prefixes)
|
| 141 |
+
|
| 142 |
+
@staticmethod
|
| 143 |
+
def _script_radix_two_distinct_prefixes(t: ScriptedContext):
|
| 144 |
+
r_a = t.start_req(
|
| 145 |
+
prompt_len=DEFAULT_CHUNK_SIZE * 2, max_new_tokens=1, prompt_token=11
|
| 146 |
+
)
|
| 147 |
+
yield from run_until_finished(r_a)
|
| 148 |
+
r_b = t.start_req(
|
| 149 |
+
prompt_len=DEFAULT_CHUNK_SIZE * 2, max_new_tokens=1, prompt_token=22
|
| 150 |
+
)
|
| 151 |
+
yield from run_until_finished(r_b)
|
| 152 |
+
|
| 153 |
+
r_a2 = t.start_req(
|
| 154 |
+
prompt_len=DEFAULT_CHUNK_SIZE * 2, max_new_tokens=1, prompt_token=11
|
| 155 |
+
)
|
| 156 |
+
yield from run_until_finished(r_a2)
|
| 157 |
+
assert r_a2.chunks_done == 0
|
| 158 |
+
assert r_a2.req.cached_tokens > 0
|
| 159 |
+
|
| 160 |
+
r_b2 = t.start_req(
|
| 161 |
+
prompt_len=DEFAULT_CHUNK_SIZE * 2, max_new_tokens=1, prompt_token=22
|
| 162 |
+
)
|
| 163 |
+
yield from run_until_finished(r_b2)
|
| 164 |
+
assert r_b2.chunks_done == 0
|
| 165 |
+
assert r_b2.req.cached_tokens > 0
|
| 166 |
+
|
| 167 |
+
def test_radix_full_prefix_minus_one(self):
|
| 168 |
+
self.server.execute_script(self._script_radix_full_prefix_minus_one)
|
| 169 |
+
|
| 170 |
+
@staticmethod
|
| 171 |
+
def _script_radix_full_prefix_minus_one(t: ScriptedContext):
|
| 172 |
+
r1 = t.start_req(prompt_len=DEFAULT_CHUNK_SIZE - 1, max_new_tokens=1)
|
| 173 |
+
yield from run_until_finished(r1)
|
| 174 |
+
r2 = t.start_req(prompt_len=DEFAULT_CHUNK_SIZE, max_new_tokens=1)
|
| 175 |
+
yield from run_until_finished(r2)
|
| 176 |
+
assert r2.chunks_done == 0
|
| 177 |
+
|
| 178 |
+
def test_radix_hit_changes_between_chunks(self):
|
| 179 |
+
self.server.execute_script(self._script_radix_hit_changes_between_chunks)
|
| 180 |
+
|
| 181 |
+
@staticmethod
|
| 182 |
+
def _script_radix_hit_changes_between_chunks(t: ScriptedContext):
|
| 183 |
+
r1 = t.start_req(prompt_len=VERY_LONG_PROMPT_LEN, max_new_tokens=2)
|
| 184 |
+
yield from run_until(r1, lambda h: h.is_chunking and h.chunks_done >= 1)
|
| 185 |
+
r2 = t.start_req(prompt_len=VERY_LONG_PROMPT_LEN, max_new_tokens=2)
|
| 186 |
+
yield from run_until_finished(r1, max_steps=800)
|
| 187 |
+
yield from run_until_finished(r2, max_steps=800)
|
| 188 |
+
assert r1.finished and r2.finished
|
| 189 |
+
assert r2.chunks_done < r1.chunks_done, (
|
| 190 |
+
f"r2 should hit r1's committed prefix; r2.chunks_done="
|
| 191 |
+
f"{r2.chunks_done} not < r1.chunks_done={r1.chunks_done}"
|
| 192 |
+
)
|
| 193 |
+
assert r2.req.cached_tokens > 0
|
| 194 |
+
|
| 195 |
+
def test_radix_evict_during_inflight_chunk(self):
|
| 196 |
+
self.server.execute_script(self._script_radix_evict_during_inflight_chunk)
|
| 197 |
+
|
| 198 |
+
@staticmethod
|
| 199 |
+
def _script_radix_evict_during_inflight_chunk(t: ScriptedContext):
|
| 200 |
+
r = t.start_req(prompt_len=VERY_LONG_PROMPT_LEN, max_new_tokens=2)
|
| 201 |
+
yield from run_until(r, lambda h: h.is_chunking and h.chunks_done >= 1)
|
| 202 |
+
t.evict_radix(prefix_tokens=None)
|
| 203 |
+
yield
|
| 204 |
+
yield from run_until_finished(r, max_steps=800)
|
| 205 |
+
assert r.finished
|
| 206 |
+
assert r.kv_pages == 0
|
| 207 |
+
assert r.lock_refs == 0
|
| 208 |
+
|
| 209 |
+
def test_radix_full_hit_no_chunked_path(self):
|
| 210 |
+
self.server.execute_script(self._script_radix_full_hit_no_chunked_path)
|
| 211 |
+
|
| 212 |
+
@staticmethod
|
| 213 |
+
def _script_radix_full_hit_no_chunked_path(t: ScriptedContext):
|
| 214 |
+
prompt_len: int = 16 * DEFAULT_CHUNK_SIZE
|
| 215 |
+
r_warm = t.start_req(prompt_len=prompt_len, max_new_tokens=1)
|
| 216 |
+
yield from run_until_finished(r_warm, max_steps=1200)
|
| 217 |
+
assert r_warm.finished
|
| 218 |
+
|
| 219 |
+
r = t.start_req(prompt_len=prompt_len, max_new_tokens=2)
|
| 220 |
+
yield from run_until_finished(r, max_steps=400)
|
| 221 |
+
assert r.finished
|
| 222 |
+
assert (
|
| 223 |
+
r.chunks_done == 0
|
| 224 |
+
), f"full prefix hit must skip chunked path; got chunks_done={r.chunks_done}"
|
| 225 |
+
|
| 226 |
+
def test_radix_evict_race_concurrent_chunked_admit(self):
|
| 227 |
+
self.server.execute_script(
|
| 228 |
+
self._script_radix_evict_race_concurrent_chunked_admit
|
| 229 |
+
)
|
| 230 |
+
|
| 231 |
+
@staticmethod
|
| 232 |
+
def _script_radix_evict_race_concurrent_chunked_admit(t: ScriptedContext):
|
| 233 |
+
warm_len: int = 4 * DEFAULT_CHUNK_SIZE
|
| 234 |
+
r_warm = t.start_req(prompt_len=warm_len, max_new_tokens=1)
|
| 235 |
+
yield from run_until_finished(r_warm, max_steps=400)
|
| 236 |
+
assert r_warm.finished
|
| 237 |
+
|
| 238 |
+
for _ in range(5):
|
| 239 |
+
yield
|
| 240 |
+
t.evict_radix(prefix_tokens=None)
|
| 241 |
+
r = t.start_req(
|
| 242 |
+
prompt_len=warm_len + DEFAULT_CHUNK_SIZE * 2,
|
| 243 |
+
max_new_tokens=2,
|
| 244 |
+
)
|
| 245 |
+
yield from run_until_finished(r, max_steps=800)
|
| 246 |
+
assert r.finished
|
| 247 |
+
assert r.req.cached_tokens == 0, (
|
| 248 |
+
f"eviction must clear the warm prefix; "
|
| 249 |
+
f"cached_tokens={r.req.cached_tokens} chunks_done={r.chunks_done}"
|
| 250 |
+
)
|
| 251 |
+
assert r.chunks_done >= 2
|
| 252 |
+
assert r.kv_pages == 0
|
| 253 |
+
assert r.lock_refs == 0
|
| 254 |
+
|
| 255 |
+
def test_chunked_req_re_chunked_after_resume_same_prefix(self):
|
| 256 |
+
self.server.execute_script(
|
| 257 |
+
self._script_chunked_req_re_chunked_after_resume_same_prefix
|
| 258 |
+
)
|
| 259 |
+
|
| 260 |
+
@staticmethod
|
| 261 |
+
def _script_chunked_req_re_chunked_after_resume_same_prefix(t: ScriptedContext):
|
| 262 |
+
prompt_len: int = 4 * DEFAULT_CHUNK_SIZE
|
| 263 |
+
r = t.start_req(prompt_len=prompt_len, max_new_tokens=2)
|
| 264 |
+
yield from run_until(r, lambda h: h.is_chunking and h.chunks_done >= 1)
|
| 265 |
+
|
| 266 |
+
t.pause_generation(mode="retract")
|
| 267 |
+
yield
|
| 268 |
+
assert r.kv_pages == 0, f"retract must release KV; got {r.kv_pages}"
|
| 269 |
+
|
| 270 |
+
t.continue_generation()
|
| 271 |
+
yield from run_until_finished(r, max_steps=800)
|
| 272 |
+
assert r.finished
|
| 273 |
+
expected_total: int = prompt_len // DEFAULT_CHUNK_SIZE
|
| 274 |
+
assert r.chunks_done >= expected_total, (
|
| 275 |
+
f"lifetime chunks_done after retract+resume must cover the "
|
| 276 |
+
f"whole prompt; expected >= {expected_total}, got "
|
| 277 |
+
f"{r.chunks_done}"
|
| 278 |
+
)
|
| 279 |
+
assert r.chunks_done < 2 * expected_total, (
|
| 280 |
+
f"lifetime chunks_done after retract+resume should not double "
|
| 281 |
+
f"the prompt's chunk count; expected < {2 * expected_total}, "
|
| 282 |
+
f"got {r.chunks_done}"
|
| 283 |
+
)
|
| 284 |
+
|
| 285 |
+
|
| 286 |
+
class TestRadixNoTailChunked(ScriptedTestCase):
|
| 287 |
+
ENGINE_KWARGS = base_engine_kwargs(chunked_prefill_size=DEFAULT_CHUNK_SIZE)
|
| 288 |
+
|
| 289 |
+
def test_page_size_one_chunked_has_no_partial_page_tail(self):
|
| 290 |
+
self.server.execute_script(
|
| 291 |
+
self._script_page_size_one_chunked_has_no_partial_page_tail
|
| 292 |
+
)
|
| 293 |
+
|
| 294 |
+
@staticmethod
|
| 295 |
+
def _script_page_size_one_chunked_has_no_partial_page_tail(t: ScriptedContext):
|
| 296 |
+
s = t.scheduler
|
| 297 |
+
prompt_len: int = 4 * DEFAULT_CHUNK_SIZE
|
| 298 |
+
r = t.start_req(prompt_len=prompt_len, max_new_tokens=2)
|
| 299 |
+
yield from run_until(r, lambda h: h.is_chunking and h.chunks_done >= 1)
|
| 300 |
+
|
| 301 |
+
observed_mid_chunk: bool = False
|
| 302 |
+
for _ in range(800):
|
| 303 |
+
req = s.chunked_req
|
| 304 |
+
if req is not None and req.rid == r.rid:
|
| 305 |
+
observed_mid_chunk = True
|
| 306 |
+
prefix_len: int = len(req.prefix_indices)
|
| 307 |
+
protected_len: int = req.cache_protected_len
|
| 308 |
+
assert prefix_len == protected_len, (
|
| 309 |
+
f"page_size=1 must take the no-tail else branch: "
|
| 310 |
+
f"len(prefix_indices)={prefix_len} != "
|
| 311 |
+
f"cache_protected_len={protected_len} (a partial-page tail "
|
| 312 |
+
f"was appended, which only happens for page_size > 1)"
|
| 313 |
+
)
|
| 314 |
+
if r.finished:
|
| 315 |
+
break
|
| 316 |
+
yield
|
| 317 |
+
assert r.finished
|
| 318 |
+
assert observed_mid_chunk, (
|
| 319 |
+
"test must observe r as the in-flight chunked_req at least once; the "
|
| 320 |
+
"no-tail else branch was never exercised"
|
| 321 |
+
)
|
| 322 |
+
assert (
|
| 323 |
+
r.kv_pages == 0
|
| 324 |
+
), f"finished chunked req must release KV; got {r.kv_pages}"
|
| 325 |
+
|
| 326 |
+
|
| 327 |
+
class TestRadixHitCountInvariant(ScriptedTestCase):
|
| 328 |
+
ENGINE_KWARGS = base_engine_kwargs(chunked_prefill_size=DEFAULT_CHUNK_SIZE)
|
| 329 |
+
|
| 330 |
+
def test_chunked_stash_no_hit_count_inflation_invariant(self):
|
| 331 |
+
self.server.execute_script(
|
| 332 |
+
self._script_chunked_stash_no_hit_count_inflation_invariant
|
| 333 |
+
)
|
| 334 |
+
|
| 335 |
+
@staticmethod
|
| 336 |
+
def _script_chunked_stash_no_hit_count_inflation_invariant(t: ScriptedContext):
|
| 337 |
+
def _snapshot_hit_counts(root) -> dict:
|
| 338 |
+
snapshot: dict = {}
|
| 339 |
+
stack = [root]
|
| 340 |
+
while stack:
|
| 341 |
+
node = stack.pop()
|
| 342 |
+
snapshot[node.id] = node.hit_count
|
| 343 |
+
stack.extend(node.children.values())
|
| 344 |
+
return snapshot
|
| 345 |
+
|
| 346 |
+
s = t.scheduler
|
| 347 |
+
r = t.start_req(prompt_len=VERY_LONG_PROMPT_LEN, max_new_tokens=2)
|
| 348 |
+
yield from run_until(r, lambda h: h.is_chunking and h.chunks_done >= 1)
|
| 349 |
+
baseline = _snapshot_hit_counts(s.tree_cache.root_node)
|
| 350 |
+
|
| 351 |
+
prev_chunks: int = r.chunks_done
|
| 352 |
+
observed_chunk_admissions: int = 0
|
| 353 |
+
for _ in range(800):
|
| 354 |
+
cur_chunks: int = r.chunks_done
|
| 355 |
+
if cur_chunks > prev_chunks:
|
| 356 |
+
observed_chunk_admissions += 1
|
| 357 |
+
cur = _snapshot_hit_counts(s.tree_cache.root_node)
|
| 358 |
+
for node_id, base_count in baseline.items():
|
| 359 |
+
if node_id in cur:
|
| 360 |
+
assert cur[node_id] == base_count, (
|
| 361 |
+
f"_inc_hit_count(chunked=True) inflated existing "
|
| 362 |
+
f"node id={node_id} hit_count: baseline={base_count}, "
|
| 363 |
+
f"now={cur[node_id]}"
|
| 364 |
+
)
|
| 365 |
+
prev_chunks = cur_chunks
|
| 366 |
+
if r.finished:
|
| 367 |
+
break
|
| 368 |
+
yield
|
| 369 |
+
assert r.finished
|
| 370 |
+
assert observed_chunk_admissions >= 2, (
|
| 371 |
+
f"test must exercise at least 2 chunk admissions after baseline; "
|
| 372 |
+
f"observed {observed_chunk_admissions}"
|
| 373 |
+
)
|
| 374 |
+
|
| 375 |
+
|
| 376 |
+
class TestRadixHitCountNonChunked(ScriptedTestCase):
|
| 377 |
+
ENGINE_KWARGS = base_engine_kwargs(chunked_prefill_size=DEFAULT_CHUNK_SIZE)
|
| 378 |
+
|
| 379 |
+
def test_non_chunked_prefix_hit_increments_hit_count_by_one(self):
|
| 380 |
+
self.server.execute_script(
|
| 381 |
+
self._script_non_chunked_prefix_hit_increments_hit_count_by_one
|
| 382 |
+
)
|
| 383 |
+
|
| 384 |
+
@staticmethod
|
| 385 |
+
def _script_non_chunked_prefix_hit_increments_hit_count_by_one(t: ScriptedContext):
|
| 386 |
+
def _snapshot_hit_counts(root) -> dict:
|
| 387 |
+
snapshot: dict = {}
|
| 388 |
+
stack = [root]
|
| 389 |
+
while stack:
|
| 390 |
+
node = stack.pop()
|
| 391 |
+
snapshot[node.id] = node.hit_count
|
| 392 |
+
stack.extend(node.children.values())
|
| 393 |
+
return snapshot
|
| 394 |
+
|
| 395 |
+
s = t.scheduler
|
| 396 |
+
|
| 397 |
+
r_warm = t.start_req(
|
| 398 |
+
prompt_len=2 * DEFAULT_CHUNK_SIZE, max_new_tokens=1, prompt_token=11
|
| 399 |
+
)
|
| 400 |
+
yield from run_until_finished(r_warm)
|
| 401 |
+
assert r_warm.finished
|
| 402 |
+
|
| 403 |
+
baseline = _snapshot_hit_counts(s.tree_cache.root_node)
|
| 404 |
+
|
| 405 |
+
r2 = t.start_req(
|
| 406 |
+
prompt_len=2 * DEFAULT_CHUNK_SIZE + 1, max_new_tokens=1, prompt_token=11
|
| 407 |
+
)
|
| 408 |
+
yield from run_until_finished(r2)
|
| 409 |
+
assert r2.finished
|
| 410 |
+
assert r2.chunks_done == 0, (
|
| 411 |
+
f"residual past the warm prefix is one token and must not chunk; "
|
| 412 |
+
f"got chunks_done={r2.chunks_done}"
|
| 413 |
+
)
|
| 414 |
+
assert r2.req.cached_tokens > 0, (
|
| 415 |
+
f"r2 must hit the warm 2-chunk prefix to drive the non-chunked "
|
| 416 |
+
f"hit_count increment; got cached_tokens={r2.req.cached_tokens}"
|
| 417 |
+
)
|
| 418 |
+
|
| 419 |
+
cur = _snapshot_hit_counts(s.tree_cache.root_node)
|
| 420 |
+
incremented_by_one = 0
|
| 421 |
+
for node_id, base_count in baseline.items():
|
| 422 |
+
if node_id not in cur:
|
| 423 |
+
continue
|
| 424 |
+
delta: int = cur[node_id] - base_count
|
| 425 |
+
assert delta in (0, 1), (
|
| 426 |
+
f"non-chunked insert moved existing node id={node_id} hit_count "
|
| 427 |
+
f"by {delta} (expected 0 or 1): baseline={base_count}, "
|
| 428 |
+
f"now={cur[node_id]}"
|
| 429 |
+
)
|
| 430 |
+
if delta == 1:
|
| 431 |
+
incremented_by_one += 1
|
| 432 |
+
assert incremented_by_one >= 1, (
|
| 433 |
+
f"_inc_hit_count(chunked=False) at radix_cache.py:672 must bump at "
|
| 434 |
+
f"least one matched warm-prefix node by exactly 1; saw "
|
| 435 |
+
f"{incremented_by_one} such nodes"
|
| 436 |
+
)
|
| 437 |
+
|
| 438 |
+
|
| 439 |
+
class TestRadixPartialPage(ScriptedTestCase):
|
| 440 |
+
ENGINE_KWARGS = base_engine_kwargs(
|
| 441 |
+
chunked_prefill_size=DEFAULT_CHUNK_SIZE,
|
| 442 |
+
page_size=4,
|
| 443 |
+
)
|
| 444 |
+
|
| 445 |
+
def test_partial_page_tail_no_double_free_invariant(self):
|
| 446 |
+
self.server.execute_script(
|
| 447 |
+
self._script_partial_page_tail_no_double_free_invariant
|
| 448 |
+
)
|
| 449 |
+
|
| 450 |
+
@staticmethod
|
| 451 |
+
def _script_partial_page_tail_no_double_free_invariant(t: ScriptedContext):
|
| 452 |
+
s = t.scheduler
|
| 453 |
+
allocator = s.token_to_kv_pool_allocator
|
| 454 |
+
free_before: int = allocator.available_size()
|
| 455 |
+
prompt_len: int = 4 * DEFAULT_CHUNK_SIZE + 7
|
| 456 |
+
r = t.start_req(prompt_len=prompt_len, max_new_tokens=2)
|
| 457 |
+
yield from run_until(r, lambda h: h.is_chunking and h.chunks_done >= 1)
|
| 458 |
+
|
| 459 |
+
for _ in range(800):
|
| 460 |
+
req = s.chunked_req
|
| 461 |
+
if req is not None and req.rid == r.rid:
|
| 462 |
+
prefix_len: int = len(req.prefix_indices)
|
| 463 |
+
protected_len: int = req.cache_protected_len
|
| 464 |
+
assert prefix_len >= protected_len, (
|
| 465 |
+
f"len(prefix_indices)={prefix_len} dropped below "
|
| 466 |
+
f"cache_protected_len={protected_len}: tail was freed "
|
| 467 |
+
f"prematurely"
|
| 468 |
+
)
|
| 469 |
+
if r.finished:
|
| 470 |
+
break
|
| 471 |
+
yield
|
| 472 |
+
assert r.finished
|
| 473 |
+
for _ in range(40):
|
| 474 |
+
if t.is_fully_idle:
|
| 475 |
+
break
|
| 476 |
+
yield
|
| 477 |
+
t.flush_cache()
|
| 478 |
+
yield
|
| 479 |
+
free_after: int = allocator.available_size()
|
| 480 |
+
assert free_after == free_before, (
|
| 481 |
+
f"KV pool free count delta on chunked req lifecycle must be 0; "
|
| 482 |
+
f"got free_before={free_before}, free_after={free_after} "
|
| 483 |
+
f"(double-free or leak of partial-page tail)"
|
| 484 |
+
)
|
| 485 |
+
|
| 486 |
+
|
| 487 |
+
class TestRadixFcfs(ScriptedTestCase):
|
| 488 |
+
ENGINE_KWARGS = base_engine_kwargs(
|
| 489 |
+
chunked_prefill_size=DEFAULT_CHUNK_SIZE,
|
| 490 |
+
schedule_policy="fcfs",
|
| 491 |
+
)
|
| 492 |
+
|
| 493 |
+
def test_naive_radix_chunked(self):
|
| 494 |
+
self.server.execute_script(self._script_naive_radix_chunked)
|
| 495 |
+
|
| 496 |
+
@staticmethod
|
| 497 |
+
def _script_naive_radix_chunked(t: ScriptedContext):
|
| 498 |
+
r1 = t.start_req(prompt_len=VERY_LONG_PROMPT_LEN, max_new_tokens=2)
|
| 499 |
+
yield from run_until_finished(r1)
|
| 500 |
+
assert r1.finished
|
| 501 |
+
|
| 502 |
+
r2 = t.start_req(
|
| 503 |
+
prompt_len=VERY_LONG_PROMPT_LEN + DEFAULT_CHUNK_SIZE * 2,
|
| 504 |
+
max_new_tokens=2,
|
| 505 |
+
)
|
| 506 |
+
yield from run_until_finished(r2)
|
| 507 |
+
assert r2.finished
|
| 508 |
+
assert r2.req.cached_tokens > 0
|
| 509 |
+
assert r2.chunks_done >= 1
|
| 510 |
+
|
| 511 |
+
|
| 512 |
+
class TestRadixDisabled(ScriptedTestCase):
|
| 513 |
+
ENGINE_KWARGS = base_engine_kwargs(
|
| 514 |
+
chunked_prefill_size=DEFAULT_CHUNK_SIZE,
|
| 515 |
+
disable_radix_cache=True,
|
| 516 |
+
kv_canary="none",
|
| 517 |
+
kv_canary_real_data="none",
|
| 518 |
+
kv_canary_sweep_interval=0,
|
| 519 |
+
)
|
| 520 |
+
|
| 521 |
+
def test_radix_disabled_chunks_every_time(self):
|
| 522 |
+
self.server.execute_script(self._script_radix_disabled_chunks_every_time)
|
| 523 |
+
|
| 524 |
+
@staticmethod
|
| 525 |
+
def _script_radix_disabled_chunks_every_time(t: ScriptedContext):
|
| 526 |
+
r1 = t.start_req(prompt_len=VERY_LONG_PROMPT_LEN, max_new_tokens=2)
|
| 527 |
+
yield from run_until_finished(r1)
|
| 528 |
+
assert r1.chunks_done >= 2
|
| 529 |
+
|
| 530 |
+
r2 = t.start_req(prompt_len=VERY_LONG_PROMPT_LEN, max_new_tokens=2)
|
| 531 |
+
yield from run_until_finished(r2)
|
| 532 |
+
assert r2.chunks_done >= 2
|
| 533 |
+
|
| 534 |
+
|
| 535 |
+
class TestRadixLpm(ScriptedTestCase):
|
| 536 |
+
ENGINE_KWARGS = base_engine_kwargs(
|
| 537 |
+
chunked_prefill_size=DEFAULT_CHUNK_SIZE,
|
| 538 |
+
schedule_policy="lpm",
|
| 539 |
+
)
|
| 540 |
+
|
| 541 |
+
def test_radix_lpm_policy_chunked_priority(self):
|
| 542 |
+
self.server.execute_script(self._script_radix_lpm_policy_chunked_priority)
|
| 543 |
+
|
| 544 |
+
@staticmethod
|
| 545 |
+
def _script_radix_lpm_policy_chunked_priority(t: ScriptedContext):
|
| 546 |
+
r_warm = t.start_req(
|
| 547 |
+
prompt_len=DEFAULT_CHUNK_SIZE * 2, max_new_tokens=1, prompt_token=1
|
| 548 |
+
)
|
| 549 |
+
yield from run_until_finished(r_warm)
|
| 550 |
+
assert r_warm.finished
|
| 551 |
+
for _ in range(5):
|
| 552 |
+
yield
|
| 553 |
+
|
| 554 |
+
r_long = t.start_req(
|
| 555 |
+
prompt_len=DEFAULT_CHUNK_SIZE * 4, max_new_tokens=1, prompt_token=1
|
| 556 |
+
)
|
| 557 |
+
r_short = t.start_req(
|
| 558 |
+
prompt_len=DEFAULT_CHUNK_SIZE * 4, max_new_tokens=1, prompt_token=7
|
| 559 |
+
)
|
| 560 |
+
|
| 561 |
+
first_admitted = None
|
| 562 |
+
cached_tokens_by_rid: dict = {}
|
| 563 |
+
for _ in range(DEFAULT_MAX_STEPS):
|
| 564 |
+
comp = t.batch_composition()
|
| 565 |
+
active = (
|
| 566 |
+
comp.get("chunked", [])
|
| 567 |
+
+ comp.get("prefill", [])
|
| 568 |
+
+ comp.get("running", [])
|
| 569 |
+
)
|
| 570 |
+
if first_admitted is None and active:
|
| 571 |
+
first_admitted = active[0]
|
| 572 |
+
for r in (r_long, r_short):
|
| 573 |
+
if r.req is not None:
|
| 574 |
+
cached_tokens_by_rid[r.rid] = r.req.cached_tokens
|
| 575 |
+
if r_long.finished and r_short.finished:
|
| 576 |
+
break
|
| 577 |
+
yield
|
| 578 |
+
assert r_long.finished and r_short.finished
|
| 579 |
+
assert first_admitted == r_long.rid, (
|
| 580 |
+
f"LPM must admit the longest-prefix-match req first; first admitted "
|
| 581 |
+
f"rid was {first_admitted!r}, expected r_long={r_long.rid!r}"
|
| 582 |
+
)
|
| 583 |
+
assert cached_tokens_by_rid.get(r_long.rid, 0) > 0
|
| 584 |
+
assert cached_tokens_by_rid.get(r_short.rid, 0) == 0
|
| 585 |
+
for r in (r_long, r_short):
|
| 586 |
+
assert r.kv_pages == 0
|
| 587 |
+
assert r.lock_refs == 0
|
| 588 |
+
|
| 589 |
+
|
| 590 |
+
class TestRadixDfsWeight(ScriptedTestCase):
|
| 591 |
+
ENGINE_KWARGS = base_engine_kwargs(
|
| 592 |
+
chunked_prefill_size=DEFAULT_CHUNK_SIZE,
|
| 593 |
+
schedule_policy="dfs-weight",
|
| 594 |
+
)
|
| 595 |
+
|
| 596 |
+
def test_radix_dfs_weight_policy_chunked(self):
|
| 597 |
+
self.server.execute_script(self._script_radix_dfs_weight_policy_chunked)
|
| 598 |
+
|
| 599 |
+
@staticmethod
|
| 600 |
+
def _script_radix_dfs_weight_policy_chunked(t: ScriptedContext):
|
| 601 |
+
warm_a = t.start_req(
|
| 602 |
+
prompt_len=DEFAULT_CHUNK_SIZE * 2, max_new_tokens=1, prompt_token=3
|
| 603 |
+
)
|
| 604 |
+
yield from run_until_finished(warm_a)
|
| 605 |
+
warm_b = t.start_req(
|
| 606 |
+
prompt_len=DEFAULT_CHUNK_SIZE * 2, max_new_tokens=1, prompt_token=4
|
| 607 |
+
)
|
| 608 |
+
yield from run_until_finished(warm_b)
|
| 609 |
+
|
| 610 |
+
heavy = [
|
| 611 |
+
t.start_req(
|
| 612 |
+
prompt_len=DEFAULT_CHUNK_SIZE * 4, max_new_tokens=1, prompt_token=3
|
| 613 |
+
)
|
| 614 |
+
for _ in range(3)
|
| 615 |
+
]
|
| 616 |
+
light = t.start_req(
|
| 617 |
+
prompt_len=DEFAULT_CHUNK_SIZE * 4, max_new_tokens=1, prompt_token=4
|
| 618 |
+
)
|
| 619 |
+
all_reqs = heavy + [light]
|
| 620 |
+
|
| 621 |
+
finish_order: list = []
|
| 622 |
+
cached_tokens_by_rid: dict = {}
|
| 623 |
+
for _ in range(DEFAULT_MAX_STEPS * 4):
|
| 624 |
+
for r in all_reqs:
|
| 625 |
+
if r.req is not None:
|
| 626 |
+
cached_tokens_by_rid[r.rid] = r.req.cached_tokens
|
| 627 |
+
if r.finished and r.rid not in finish_order:
|
| 628 |
+
finish_order.append(r.rid)
|
| 629 |
+
if all(r.finished for r in all_reqs):
|
| 630 |
+
break
|
| 631 |
+
yield
|
| 632 |
+
assert all(r.finished for r in all_reqs)
|
| 633 |
+
assert finish_order[-1] == light.rid, (
|
| 634 |
+
f"dfs-weight must drain the heavier branch-A subtree before the "
|
| 635 |
+
f"lighter branch-B req; finish order was {finish_order!r}, "
|
| 636 |
+
f"light={light.rid!r}"
|
| 637 |
+
)
|
| 638 |
+
for r in heavy:
|
| 639 |
+
assert cached_tokens_by_rid.get(r.rid, 0) > 0
|
| 640 |
+
assert cached_tokens_by_rid.get(light.rid, 0) > 0
|
| 641 |
+
for r in all_reqs:
|
| 642 |
+
assert r.kv_pages == 0
|
| 643 |
+
assert r.lock_refs == 0
|
| 644 |
+
|
| 645 |
+
|
| 646 |
+
class TestRadixPriority(ScriptedTestCase):
|
| 647 |
+
ENGINE_KWARGS = base_engine_kwargs(
|
| 648 |
+
chunked_prefill_size=DEFAULT_CHUNK_SIZE,
|
| 649 |
+
enable_priority_scheduling=True,
|
| 650 |
+
)
|
| 651 |
+
|
| 652 |
+
def test_radix_prefix_match_with_priority(self):
|
| 653 |
+
self.server.execute_script(self._script_radix_prefix_match_with_priority)
|
| 654 |
+
|
| 655 |
+
@staticmethod
|
| 656 |
+
def _script_radix_prefix_match_with_priority(t: ScriptedContext):
|
| 657 |
+
r_warm = t.start_req(prompt_len=DEFAULT_CHUNK_SIZE * 2, max_new_tokens=1)
|
| 658 |
+
yield from run_until_finished(r_warm)
|
| 659 |
+
assert r_warm.finished
|
| 660 |
+
for _ in range(5):
|
| 661 |
+
yield
|
| 662 |
+
|
| 663 |
+
r_low = t.start_req(
|
| 664 |
+
prompt_len=DEFAULT_CHUNK_SIZE * 4, max_new_tokens=1, priority=0
|
| 665 |
+
)
|
| 666 |
+
r_high = t.start_req(
|
| 667 |
+
prompt_len=DEFAULT_CHUNK_SIZE * 4, max_new_tokens=1, priority=10
|
| 668 |
+
)
|
| 669 |
+
|
| 670 |
+
first_admitted = None
|
| 671 |
+
low_done = False
|
| 672 |
+
high_done = False
|
| 673 |
+
cached_tokens_by_rid: dict = {}
|
| 674 |
+
for _ in range(DEFAULT_MAX_STEPS):
|
| 675 |
+
comp = t.batch_composition()
|
| 676 |
+
active = (
|
| 677 |
+
comp.get("chunked", [])
|
| 678 |
+
+ comp.get("prefill", [])
|
| 679 |
+
+ comp.get("running", [])
|
| 680 |
+
)
|
| 681 |
+
if first_admitted is None and active:
|
| 682 |
+
first_admitted = active[0]
|
| 683 |
+
for r in (r_low, r_high):
|
| 684 |
+
if r.req is not None:
|
| 685 |
+
cached_tokens_by_rid[r.rid] = r.req.cached_tokens
|
| 686 |
+
low_done = low_done or r_low.finished
|
| 687 |
+
high_done = high_done or r_high.finished
|
| 688 |
+
if low_done and high_done:
|
| 689 |
+
break
|
| 690 |
+
yield
|
| 691 |
+
assert low_done and high_done
|
| 692 |
+
assert first_admitted == r_high.rid, (
|
| 693 |
+
f"higher-priority req must be admitted first; first admitted rid "
|
| 694 |
+
f"was {first_admitted!r}, expected r_high={r_high.rid!r}"
|
| 695 |
+
)
|
| 696 |
+
for r in (r_low, r_high):
|
| 697 |
+
assert cached_tokens_by_rid.get(r.rid, 0) > 0
|
| 698 |
+
assert r.kv_pages == 0
|
| 699 |
+
assert r.lock_refs == 0
|
| 700 |
+
|
| 701 |
+
def test_radix_calc_priority_skip_chunked_resume(self):
|
| 702 |
+
self.server.execute_script(self._script_radix_calc_priority_skip_chunked_resume)
|
| 703 |
+
|
| 704 |
+
@staticmethod
|
| 705 |
+
def _script_radix_calc_priority_skip_chunked_resume(t: ScriptedContext):
|
| 706 |
+
r1 = t.start_req(prompt_len=VERY_LONG_PROMPT_LEN, max_new_tokens=2, priority=10)
|
| 707 |
+
yield from run_until(r1, lambda h: h.is_chunking)
|
| 708 |
+
r2 = t.start_req(prompt_len=VERY_LONG_PROMPT_LEN, max_new_tokens=2, priority=0)
|
| 709 |
+
|
| 710 |
+
prev_chunks_done = r1.chunks_done
|
| 711 |
+
r1_fin_step = None
|
| 712 |
+
r2_fin_step = None
|
| 713 |
+
step = 0
|
| 714 |
+
while not (r1.finished and r2.finished):
|
| 715 |
+
assert r1.chunks_done >= prev_chunks_done, (
|
| 716 |
+
f"r1 chunked prefill was preempted by lower-priority r2: "
|
| 717 |
+
f"chunks_done regressed {prev_chunks_done} -> {r1.chunks_done}"
|
| 718 |
+
)
|
| 719 |
+
prev_chunks_done = r1.chunks_done
|
| 720 |
+
if r1.finished and r1_fin_step is None:
|
| 721 |
+
r1_fin_step = step
|
| 722 |
+
if r2.finished and r2_fin_step is None:
|
| 723 |
+
r2_fin_step = step
|
| 724 |
+
step += 1
|
| 725 |
+
yield
|
| 726 |
+
if r1.finished and r1_fin_step is None:
|
| 727 |
+
r1_fin_step = step
|
| 728 |
+
if r2.finished and r2_fin_step is None:
|
| 729 |
+
r2_fin_step = step
|
| 730 |
+
|
| 731 |
+
assert r1.finished and r2.finished
|
| 732 |
+
assert r1_fin_step is not None and r2_fin_step is not None
|
| 733 |
+
assert r1_fin_step <= r2_fin_step, (
|
| 734 |
+
f"high-priority r1 must finish its chunked prefill no later than "
|
| 735 |
+
f"low-priority r2; r1 finished at step {r1_fin_step}, r2 at step "
|
| 736 |
+
f"{r2_fin_step} (lower-priority r2 jumped ahead of r1's resume)"
|
| 737 |
+
)
|
| 738 |
+
|
| 739 |
+
|
| 740 |
+
if __name__ == "__main__":
|
| 741 |
+
unittest.main()
|
asian_ai/performance/SGLang/test/manual/chunked_prefill/test_scripted_regression.py
ADDED
|
@@ -0,0 +1,524 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import unittest
|
| 2 |
+
|
| 3 |
+
from sglang.test.scripted_runtime.context import ScriptedContext
|
| 4 |
+
from sglang.test.scripted_runtime.test_case import ScriptedTestCase
|
| 5 |
+
from sglang.test.scripted_runtime_chunked_helpers import (
|
| 6 |
+
DEFAULT_CHUNK_SIZE,
|
| 7 |
+
DEFAULT_MAX_STEPS,
|
| 8 |
+
VERY_LONG_PROMPT_LEN,
|
| 9 |
+
base_engine_kwargs,
|
| 10 |
+
run_until,
|
| 11 |
+
run_until_all_finished,
|
| 12 |
+
run_until_finished,
|
| 13 |
+
warmup_radix,
|
| 14 |
+
)
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
def _drain_until_released(t, *handles):
|
| 18 |
+
for _ in range(12):
|
| 19 |
+
if all(
|
| 20 |
+
h.kv_pages == 0
|
| 21 |
+
and h.lock_refs == 0
|
| 22 |
+
and (h.req is None or h.req.req_pool_idx is None)
|
| 23 |
+
for h in handles
|
| 24 |
+
):
|
| 25 |
+
return
|
| 26 |
+
yield
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
class TestRegressionBasic(ScriptedTestCase):
|
| 30 |
+
ENGINE_KWARGS = base_engine_kwargs(chunked_prefill_size=DEFAULT_CHUNK_SIZE)
|
| 31 |
+
|
| 32 |
+
def test_abort_waiting_releases_all(self):
|
| 33 |
+
self.server.execute_script(self._script_abort_waiting_releases_all)
|
| 34 |
+
|
| 35 |
+
@staticmethod
|
| 36 |
+
def _script_abort_waiting_releases_all(t: ScriptedContext):
|
| 37 |
+
r = t.start_req(prompt_len=VERY_LONG_PROMPT_LEN, max_new_tokens=2)
|
| 38 |
+
yield from run_until(r, lambda h: h.is_chunking)
|
| 39 |
+
|
| 40 |
+
t.abort(r)
|
| 41 |
+
yield from _drain_until_released(t, r)
|
| 42 |
+
|
| 43 |
+
assert r.kv_pages == 0
|
| 44 |
+
assert r.req.req_pool_idx is None
|
| 45 |
+
assert r.lock_refs == 0
|
| 46 |
+
assert not r.is_chunking
|
| 47 |
+
assert r.req.inflight_middle_chunks == 0
|
| 48 |
+
|
| 49 |
+
def test_pause_covers_waiting_chunked(self):
|
| 50 |
+
self.server.execute_script(self._script_pause_covers_waiting_chunked)
|
| 51 |
+
|
| 52 |
+
@staticmethod
|
| 53 |
+
def _script_pause_covers_waiting_chunked(t: ScriptedContext):
|
| 54 |
+
r = t.start_req(prompt_len=VERY_LONG_PROMPT_LEN, max_new_tokens=2)
|
| 55 |
+
yield from run_until(r, lambda h: h.is_chunking)
|
| 56 |
+
|
| 57 |
+
t.pause_generation(mode="retract")
|
| 58 |
+
yield
|
| 59 |
+
|
| 60 |
+
assert r.kv_pages == 0
|
| 61 |
+
assert r.req.req_pool_idx is None
|
| 62 |
+
assert r.lock_refs == 0
|
| 63 |
+
assert not r.is_chunking
|
| 64 |
+
|
| 65 |
+
t.continue_generation()
|
| 66 |
+
|
| 67 |
+
def test_inflight_middle_chunks_invariant(self):
|
| 68 |
+
self.server.execute_script(self._script_inflight_middle_chunks_invariant)
|
| 69 |
+
|
| 70 |
+
@staticmethod
|
| 71 |
+
def _script_inflight_middle_chunks_invariant(t: ScriptedContext):
|
| 72 |
+
r = t.start_req(
|
| 73 |
+
prompt_len=2 * DEFAULT_CHUNK_SIZE, max_new_tokens=4, ignore_eos=True
|
| 74 |
+
)
|
| 75 |
+
|
| 76 |
+
observed_max = 0
|
| 77 |
+
saw_chunking_bump = False
|
| 78 |
+
cleared_inflight = False
|
| 79 |
+
for _ in range(DEFAULT_MAX_STEPS):
|
| 80 |
+
req = r.req
|
| 81 |
+
if req is not None:
|
| 82 |
+
observed_max = max(observed_max, req.inflight_middle_chunks)
|
| 83 |
+
if r.chunks_done >= 1 and r.is_chunking:
|
| 84 |
+
saw_chunking_bump = saw_chunking_bump or (
|
| 85 |
+
req.inflight_middle_chunks > 0
|
| 86 |
+
)
|
| 87 |
+
if not r.is_chunking and r.chunks_done >= 2:
|
| 88 |
+
cleared_inflight = req.inflight_middle_chunks == 0
|
| 89 |
+
break
|
| 90 |
+
if r.finished:
|
| 91 |
+
cleared_inflight = True
|
| 92 |
+
break
|
| 93 |
+
yield
|
| 94 |
+
else:
|
| 95 |
+
raise AssertionError("chunk loop did not clear within DEFAULT_MAX_STEPS")
|
| 96 |
+
|
| 97 |
+
assert saw_chunking_bump, "last-chunk admit must bump inflight_middle_chunks"
|
| 98 |
+
assert observed_max == 1, (
|
| 99 |
+
f"e875cd36e4: inflight_middle_chunks must be a 0/1 latch; "
|
| 100 |
+
f"observed max={observed_max} (pre-fix bug would bump to 2 "
|
| 101 |
+
f"at the last-chunk admit boundary)"
|
| 102 |
+
)
|
| 103 |
+
assert (
|
| 104 |
+
cleared_inflight
|
| 105 |
+
), "inflight_middle_chunks should be 0 once the chunk loop clears"
|
| 106 |
+
|
| 107 |
+
yield from run_until_finished(r)
|
| 108 |
+
assert r.finished
|
| 109 |
+
assert r.chunks_done >= 2
|
| 110 |
+
|
| 111 |
+
@unittest.skip(
|
| 112 |
+
"dbdcdde245 mamba_pool_idx cleanup-skip is mamba-architecture-specific. "
|
| 113 |
+
"The shared test fixture does not configure a mamba model; running this "
|
| 114 |
+
"regression against the default transformer model would not exercise the "
|
| 115 |
+
"mamba NO_TOKEN cleanup path, so the body would be a check "
|
| 116 |
+
"with no real protection. Re-enable when a mamba fixture is wired in."
|
| 117 |
+
)
|
| 118 |
+
def test_mamba_chunked_resume_no_token(self):
|
| 119 |
+
self.server.execute_script(self._script_mamba_chunked_resume_no_token)
|
| 120 |
+
|
| 121 |
+
@staticmethod
|
| 122 |
+
def _script_mamba_chunked_resume_no_token(t: ScriptedContext):
|
| 123 |
+
r = t.start_req(prompt_len=VERY_LONG_PROMPT_LEN, max_new_tokens=2)
|
| 124 |
+
yield from run_until_finished(r)
|
| 125 |
+
assert r.finished
|
| 126 |
+
|
| 127 |
+
def test_merge_batch_assert_widened(self):
|
| 128 |
+
self.server.execute_script(self._script_merge_batch_assert_widened)
|
| 129 |
+
|
| 130 |
+
@staticmethod
|
| 131 |
+
def _script_merge_batch_assert_widened(t: ScriptedContext):
|
| 132 |
+
r1 = t.start_req(
|
| 133 |
+
prompt_len=VERY_LONG_PROMPT_LEN, max_new_tokens=2, ignore_eos=True
|
| 134 |
+
)
|
| 135 |
+
r2 = t.start_req(prompt_len=16, max_new_tokens=2, ignore_eos=True)
|
| 136 |
+
yield from run_until_all_finished([r1, r2])
|
| 137 |
+
assert r1.finished and r2.finished
|
| 138 |
+
assert r1.chunks_done >= 2 and r2.chunks_done == 0
|
| 139 |
+
assert len(r1.req.output_ids) == 2 and len(r2.req.output_ids) == 2
|
| 140 |
+
|
| 141 |
+
def test_chunked_pending_tokens_subtract_prefix(self):
|
| 142 |
+
self.server.execute_script(self._script_chunked_pending_tokens_subtract_prefix)
|
| 143 |
+
|
| 144 |
+
@staticmethod
|
| 145 |
+
def _script_chunked_pending_tokens_subtract_prefix(t: ScriptedContext):
|
| 146 |
+
r1 = t.start_req(prompt_len=DEFAULT_CHUNK_SIZE * 4, max_new_tokens=2)
|
| 147 |
+
yield from run_until(r1, lambda h: h.is_chunking and h.chunks_done >= 1)
|
| 148 |
+
|
| 149 |
+
r2 = t.start_req(prompt_len=DEFAULT_CHUNK_SIZE, max_new_tokens=2)
|
| 150 |
+
yield from run_until(r2, lambda h: h.status == "waiting")
|
| 151 |
+
|
| 152 |
+
r1_prefix = len(r1.req.prefix_indices)
|
| 153 |
+
assert r1.is_chunking, "r1 must still be the in-flight chunked req"
|
| 154 |
+
assert r1_prefix > 0, "r1 must hold a committed prefix as the chunked req"
|
| 155 |
+
|
| 156 |
+
observed_pending = t.scheduler.load_inquirer._get_num_pending_tokens()
|
| 157 |
+
|
| 158 |
+
r1_seqlen = r1.req.seqlen
|
| 159 |
+
r2_seqlen = r2.req.seqlen
|
| 160 |
+
expected_post_fix = (r1_seqlen - r1_prefix) + r2_seqlen
|
| 161 |
+
pre_fix_bad = r1_seqlen + r2_seqlen
|
| 162 |
+
|
| 163 |
+
assert observed_pending == expected_post_fix, (
|
| 164 |
+
f"c79a73bec4: load_inquirer must subtract the chunked req's "
|
| 165 |
+
f"prefix_indices_len from its pending-token contribution; "
|
| 166 |
+
f"observed={observed_pending}, expected_post_fix="
|
| 167 |
+
f"{expected_post_fix}, pre_fix_bad={pre_fix_bad}"
|
| 168 |
+
)
|
| 169 |
+
assert observed_pending < pre_fix_bad, (
|
| 170 |
+
f"c79a73bec4: observed pending tokens did not subtract the chunked "
|
| 171 |
+
f"prefix (matches the no-subtraction sum {pre_fix_bad}) — fix is regressed"
|
| 172 |
+
)
|
| 173 |
+
|
| 174 |
+
yield from run_until_all_finished([r1, r2])
|
| 175 |
+
assert r1.finished and r2.finished
|
| 176 |
+
|
| 177 |
+
def test_chunked_admission_reuse_branch_balanced(self):
|
| 178 |
+
self.server.execute_script(self._script_chunked_admission_reuse_branch_balanced)
|
| 179 |
+
|
| 180 |
+
@staticmethod
|
| 181 |
+
def _script_chunked_admission_reuse_branch_balanced(t: ScriptedContext):
|
| 182 |
+
baseline_refs = sum(t.get_all_node_lock_refs().values())
|
| 183 |
+
r = t.start_req(prompt_len=VERY_LONG_PROMPT_LEN, max_new_tokens=2)
|
| 184 |
+
|
| 185 |
+
for target_chunk in (3, 4, 5):
|
| 186 |
+
yield from run_until(
|
| 187 |
+
r, lambda h: h.chunks_done >= target_chunk and h.is_chunking
|
| 188 |
+
)
|
| 189 |
+
assert r.lock_refs == 1, (
|
| 190 |
+
f"reuse branch re-acquired lock_ref on the chunked req's node at "
|
| 191 |
+
f"chunk {target_chunk}: r.lock_refs={r.lock_refs} (expected 1)"
|
| 192 |
+
)
|
| 193 |
+
per_node = t.get_all_node_lock_refs()
|
| 194 |
+
assert max(per_node.values(), default=0) <= 1, (
|
| 195 |
+
f"reuse branch double-locked a single node at chunk "
|
| 196 |
+
f"{target_chunk}: per-node lock_refs={per_node}"
|
| 197 |
+
)
|
| 198 |
+
|
| 199 |
+
yield from run_until_finished(r)
|
| 200 |
+
final_refs = sum(t.get_all_node_lock_refs().values())
|
| 201 |
+
assert final_refs == baseline_refs, (
|
| 202 |
+
f"chunked lifecycle must net to zero lock_ref delta; "
|
| 203 |
+
f"baseline={baseline_refs}, final={final_refs}"
|
| 204 |
+
)
|
| 205 |
+
assert r.lock_refs == 0
|
| 206 |
+
|
| 207 |
+
def test_multiturn_full_hit_no_reuse_branch(self):
|
| 208 |
+
self.server.execute_script(self._script_multiturn_full_hit_no_reuse_branch)
|
| 209 |
+
|
| 210 |
+
@staticmethod
|
| 211 |
+
def _script_multiturn_full_hit_no_reuse_branch(t: ScriptedContext):
|
| 212 |
+
baseline_refs = sum(t.get_all_node_lock_refs().values())
|
| 213 |
+
r1 = t.start_req(prompt_len=64, max_new_tokens=2)
|
| 214 |
+
yield from run_until_finished(r1)
|
| 215 |
+
|
| 216 |
+
r2 = t.start_req(prompt_len=64, max_new_tokens=2)
|
| 217 |
+
yield from run_until_finished(r2)
|
| 218 |
+
|
| 219 |
+
assert not r2.is_chunking
|
| 220 |
+
assert r2.req.cached_tokens > 0, (
|
| 221 |
+
f"follow-up req must fully hit the warm prefix to exercise the "
|
| 222 |
+
f"no-reuse path; got cached_tokens={r2.req.cached_tokens}"
|
| 223 |
+
)
|
| 224 |
+
for _ in range(5):
|
| 225 |
+
yield
|
| 226 |
+
assert sum(t.get_all_node_lock_refs().values()) == baseline_refs, (
|
| 227 |
+
f"full-prefix-hit follow-up must not take the chunked reuse "
|
| 228 |
+
f"branch; lock_refs drifted from {baseline_refs} to "
|
| 229 |
+
f"{sum(t.get_all_node_lock_refs().values())}"
|
| 230 |
+
)
|
| 231 |
+
|
| 232 |
+
def test_abort_chunked_resume_releases_all_resources(self):
|
| 233 |
+
self.server.execute_script(
|
| 234 |
+
self._script_abort_chunked_resume_releases_all_resources
|
| 235 |
+
)
|
| 236 |
+
|
| 237 |
+
@staticmethod
|
| 238 |
+
def _script_abort_chunked_resume_releases_all_resources(t: ScriptedContext):
|
| 239 |
+
baseline_refs = sum(t.get_all_node_lock_refs().values())
|
| 240 |
+
r = t.start_req(prompt_len=VERY_LONG_PROMPT_LEN, max_new_tokens=2)
|
| 241 |
+
yield from run_until(r, lambda h: h.is_chunking and h.chunks_done >= 1)
|
| 242 |
+
|
| 243 |
+
assert r.req.req_pool_idx is not None, "row must be held mid-chunk"
|
| 244 |
+
assert r.kv_pages > 0, "committed KV must be held mid-chunk"
|
| 245 |
+
assert r.lock_refs >= 1, "radix lock_ref must be held mid-chunk"
|
| 246 |
+
|
| 247 |
+
t.abort(r)
|
| 248 |
+
yield from _drain_until_released(t, r)
|
| 249 |
+
|
| 250 |
+
assert (
|
| 251 |
+
r.req.req_pool_idx is None
|
| 252 |
+
), f"96d4749094: abort must release row; got row_idx={r.req.req_pool_idx!r}"
|
| 253 |
+
assert (
|
| 254 |
+
r.kv_pages == 0
|
| 255 |
+
), f"96d4749094: abort must release KV; got kv_pages={r.kv_pages}"
|
| 256 |
+
assert (
|
| 257 |
+
r.lock_refs == 0
|
| 258 |
+
), f"96d4749094: abort must release lock_ref; got lock_refs={r.lock_refs}"
|
| 259 |
+
assert not r.is_chunking
|
| 260 |
+
assert r.req.inflight_middle_chunks == 0
|
| 261 |
+
assert sum(t.get_all_node_lock_refs().values()) == baseline_refs
|
| 262 |
+
|
| 263 |
+
def test_pause_retract_releases_waiting_chunked_resume(self):
|
| 264 |
+
self.server.execute_script(
|
| 265 |
+
self._script_pause_retract_releases_waiting_chunked_resume
|
| 266 |
+
)
|
| 267 |
+
|
| 268 |
+
@staticmethod
|
| 269 |
+
def _script_pause_retract_releases_waiting_chunked_resume(t: ScriptedContext):
|
| 270 |
+
r = t.start_req(prompt_len=VERY_LONG_PROMPT_LEN, max_new_tokens=2)
|
| 271 |
+
yield from run_until(r, lambda h: h.is_chunking and h.chunks_done >= 1)
|
| 272 |
+
assert r.req.req_pool_idx is not None and r.kv_pages > 0 and r.lock_refs >= 1
|
| 273 |
+
|
| 274 |
+
t.pause_generation(mode="retract")
|
| 275 |
+
yield
|
| 276 |
+
|
| 277 |
+
assert r.req.req_pool_idx is None, (
|
| 278 |
+
f"f38e69f87d: pause(retract) must release waiting "
|
| 279 |
+
f"chunked-resume row; got row_idx={r.req.req_pool_idx!r}"
|
| 280 |
+
)
|
| 281 |
+
assert r.kv_pages == 0
|
| 282 |
+
assert r.lock_refs == 0
|
| 283 |
+
assert not r.is_chunking
|
| 284 |
+
assert r.status == "waiting", (
|
| 285 |
+
f"f38e69f87d: pause(retract) must re-queue the retracted "
|
| 286 |
+
f"chunked-resume req; got status={r.status!r}"
|
| 287 |
+
)
|
| 288 |
+
assert t.scheduler.chunked_req is None
|
| 289 |
+
assert t.scheduler.running_batch.is_empty()
|
| 290 |
+
|
| 291 |
+
t.continue_generation()
|
| 292 |
+
yield from run_until_finished(r)
|
| 293 |
+
assert r.finished
|
| 294 |
+
assert len(r.req.output_ids) == 2
|
| 295 |
+
|
| 296 |
+
def test_retract_all_clears_batch_with_chunked(self):
|
| 297 |
+
self.server.execute_script(self._script_retract_all_clears_batch_with_chunked)
|
| 298 |
+
|
| 299 |
+
@staticmethod
|
| 300 |
+
def _script_retract_all_clears_batch_with_chunked(t: ScriptedContext):
|
| 301 |
+
r1 = t.start_req(prompt_len=VERY_LONG_PROMPT_LEN, max_new_tokens=2)
|
| 302 |
+
r2 = t.start_req(prompt_len=VERY_LONG_PROMPT_LEN, max_new_tokens=2)
|
| 303 |
+
yield from run_until(r1, lambda h: h.is_chunking and h.chunks_done >= 1)
|
| 304 |
+
yield from run_until(r2, lambda h: h.status == "waiting")
|
| 305 |
+
|
| 306 |
+
t.pause_generation(mode="retract")
|
| 307 |
+
yield
|
| 308 |
+
|
| 309 |
+
assert len(t.scheduler.running_batch.reqs) == 0, (
|
| 310 |
+
f"f0388931bf: retract_all must clear batch; got batch_size="
|
| 311 |
+
f"{len(t.scheduler.running_batch.reqs)}"
|
| 312 |
+
)
|
| 313 |
+
assert (
|
| 314 |
+
t.scheduler.chunked_req.rid if t.scheduler.chunked_req is not None else None
|
| 315 |
+
) is None
|
| 316 |
+
for r in (r1, r2):
|
| 317 |
+
assert r.status == "waiting"
|
| 318 |
+
assert r.kv_pages == 0
|
| 319 |
+
assert not r.is_chunking
|
| 320 |
+
|
| 321 |
+
t.continue_generation()
|
| 322 |
+
yield from run_until_all_finished([r1, r2])
|
| 323 |
+
|
| 324 |
+
|
| 325 |
+
class TestRegressionPp(ScriptedTestCase):
|
| 326 |
+
ENGINE_KWARGS = base_engine_kwargs(
|
| 327 |
+
chunked_prefill_size=DEFAULT_CHUNK_SIZE,
|
| 328 |
+
tp_size=2,
|
| 329 |
+
pp_size=2,
|
| 330 |
+
)
|
| 331 |
+
|
| 332 |
+
def test_pp_abort_dedup(self):
|
| 333 |
+
self.server.execute_script(self._script_pp_abort_dedup)
|
| 334 |
+
|
| 335 |
+
@staticmethod
|
| 336 |
+
def _script_pp_abort_dedup(t: ScriptedContext):
|
| 337 |
+
r = t.start_req(prompt_len=2 * DEFAULT_CHUNK_SIZE, max_new_tokens=4)
|
| 338 |
+
|
| 339 |
+
yield from run_until(r, lambda h: h.chunks_done >= 1 and h.is_chunking)
|
| 340 |
+
|
| 341 |
+
t.abort(r)
|
| 342 |
+
yield
|
| 343 |
+
|
| 344 |
+
rids_after_abort = [req.rid for req in t.scheduler.running_batch.reqs]
|
| 345 |
+
occurrences = sum(1 for rid in rids_after_abort if rid == r.rid)
|
| 346 |
+
assert occurrences <= 1, (
|
| 347 |
+
f"b823c16e60: batch_rids must dedup across mbs + "
|
| 348 |
+
f"waiting_queue; got {occurrences} occurrences of rid="
|
| 349 |
+
f"{r.rid} (pre-fix bug would yield 3)"
|
| 350 |
+
)
|
| 351 |
+
yield from _drain_until_released(t, r)
|
| 352 |
+
assert r.finished
|
| 353 |
+
|
| 354 |
+
|
| 355 |
+
class TestRegressionPriority(ScriptedTestCase):
|
| 356 |
+
ENGINE_KWARGS = base_engine_kwargs(
|
| 357 |
+
chunked_prefill_size=DEFAULT_CHUNK_SIZE,
|
| 358 |
+
enable_priority_scheduling=True,
|
| 359 |
+
)
|
| 360 |
+
|
| 361 |
+
def test_priority_skips_chunked_in_prefix_match(self):
|
| 362 |
+
self.server.execute_script(self._script_priority_skips_chunked_in_prefix_match)
|
| 363 |
+
|
| 364 |
+
@staticmethod
|
| 365 |
+
def _script_priority_skips_chunked_in_prefix_match(t: ScriptedContext):
|
| 366 |
+
r1 = t.start_req(
|
| 367 |
+
prompt_len=VERY_LONG_PROMPT_LEN,
|
| 368 |
+
max_new_tokens=2,
|
| 369 |
+
priority=0,
|
| 370 |
+
ignore_eos=True,
|
| 371 |
+
)
|
| 372 |
+
yield from run_until(r1, lambda h: h.is_chunking and h.chunks_done >= 1)
|
| 373 |
+
r1_host_hit_before = r1.req.host_hit_length
|
| 374 |
+
|
| 375 |
+
r2 = t.start_req(
|
| 376 |
+
prompt_len=VERY_LONG_PROMPT_LEN,
|
| 377 |
+
max_new_tokens=2,
|
| 378 |
+
priority=10,
|
| 379 |
+
ignore_eos=True,
|
| 380 |
+
)
|
| 381 |
+
prev_chunks = r1.chunks_done
|
| 382 |
+
while not (r1.finished and r2.finished):
|
| 383 |
+
assert r1.req is None or r1.req.host_hit_length == r1_host_hit_before, (
|
| 384 |
+
f"aaf3752d2b: priority calc re-matched the chunked-resume req; "
|
| 385 |
+
f"host_hit_length changed {r1_host_hit_before} -> "
|
| 386 |
+
f"{r1.req.host_hit_length}"
|
| 387 |
+
)
|
| 388 |
+
assert r1.chunks_done >= prev_chunks, (
|
| 389 |
+
f"r1 chunked prefill was preempted by higher-priority r2: "
|
| 390 |
+
f"chunks_done regressed {prev_chunks} -> {r1.chunks_done}"
|
| 391 |
+
)
|
| 392 |
+
prev_chunks = r1.chunks_done
|
| 393 |
+
yield
|
| 394 |
+
|
| 395 |
+
assert r1.finished and r2.finished
|
| 396 |
+
assert r1.chunks_done >= 2
|
| 397 |
+
assert len(r1.req.output_ids) == 2 and len(r2.req.output_ids) == 2
|
| 398 |
+
|
| 399 |
+
|
| 400 |
+
class TestRegressionLpm(ScriptedTestCase):
|
| 401 |
+
ENGINE_KWARGS = base_engine_kwargs(
|
| 402 |
+
chunked_prefill_size=DEFAULT_CHUNK_SIZE,
|
| 403 |
+
schedule_policy="lpm",
|
| 404 |
+
)
|
| 405 |
+
|
| 406 |
+
def test_chunked_resume_priority_in_sort(self):
|
| 407 |
+
self.server.execute_script(self._script_chunked_resume_priority_in_sort)
|
| 408 |
+
|
| 409 |
+
@staticmethod
|
| 410 |
+
def _script_chunked_resume_priority_in_sort(t: ScriptedContext):
|
| 411 |
+
r_long = t.start_req(prompt_len=VERY_LONG_PROMPT_LEN, max_new_tokens=2)
|
| 412 |
+
yield from run_until(r_long, lambda h: h.is_chunking)
|
| 413 |
+
|
| 414 |
+
shorts = [t.start_req(prompt_len=4, max_new_tokens=1) for _ in range(8)]
|
| 415 |
+
|
| 416 |
+
initial_chunks = r_long.chunks_done
|
| 417 |
+
for _ in range(200):
|
| 418 |
+
if r_long.chunks_done > initial_chunks:
|
| 419 |
+
break
|
| 420 |
+
yield
|
| 421 |
+
else:
|
| 422 |
+
raise AssertionError(
|
| 423 |
+
f"chunked req starved by short req flood; "
|
| 424 |
+
f"chunks_done stuck at {initial_chunks}"
|
| 425 |
+
)
|
| 426 |
+
|
| 427 |
+
all_reqs = [r_long, *shorts]
|
| 428 |
+
done = {r.rid: False for r in all_reqs}
|
| 429 |
+
for _ in range(DEFAULT_MAX_STEPS):
|
| 430 |
+
for r in all_reqs:
|
| 431 |
+
done[r.rid] = done[r.rid] or r.finished
|
| 432 |
+
if all(done.values()):
|
| 433 |
+
break
|
| 434 |
+
yield
|
| 435 |
+
else:
|
| 436 |
+
raise AssertionError(
|
| 437 |
+
f"reqs did not all finish; done={done}, "
|
| 438 |
+
f"long_chunks={r_long.chunks_done}"
|
| 439 |
+
)
|
| 440 |
+
assert r_long.finished
|
| 441 |
+
assert r_long.chunks_done >= 2
|
| 442 |
+
|
| 443 |
+
def test_lpm_skips_chunked_resume_prefix_match(self):
|
| 444 |
+
self.server.execute_script(self._script_lpm_skips_chunked_resume_prefix_match)
|
| 445 |
+
|
| 446 |
+
@staticmethod
|
| 447 |
+
def _script_lpm_skips_chunked_resume_prefix_match(t: ScriptedContext):
|
| 448 |
+
yield from warmup_radix(t, [1] * (2 * DEFAULT_CHUNK_SIZE))
|
| 449 |
+
|
| 450 |
+
r1 = t.start_req(prompt_len=VERY_LONG_PROMPT_LEN, max_new_tokens=2)
|
| 451 |
+
yield from run_until(r1, lambda h: h.chunks_done >= 1 and h.is_chunking)
|
| 452 |
+
|
| 453 |
+
host_hit_before = r1.req.host_hit_length
|
| 454 |
+
|
| 455 |
+
r2 = t.start_req(prompt_len=2 * DEFAULT_CHUNK_SIZE, max_new_tokens=2)
|
| 456 |
+
while not (r1.finished and r2.finished):
|
| 457 |
+
assert r1.req is None or r1.req.host_hit_length == host_hit_before, (
|
| 458 |
+
f"calc_priority re-matched the chunked-resume req; host_hit_length "
|
| 459 |
+
f"changed {host_hit_before} -> {r1.req.host_hit_length}"
|
| 460 |
+
)
|
| 461 |
+
yield
|
| 462 |
+
|
| 463 |
+
def test_chunked_resume_priority_under_lpm(self):
|
| 464 |
+
self.server.execute_script(self._script_chunked_resume_priority_under_lpm)
|
| 465 |
+
|
| 466 |
+
@staticmethod
|
| 467 |
+
def _script_chunked_resume_priority_under_lpm(t: ScriptedContext):
|
| 468 |
+
long_prefix_tokens = [1] * (3 * DEFAULT_CHUNK_SIZE)
|
| 469 |
+
yield from warmup_radix(t, long_prefix_tokens)
|
| 470 |
+
|
| 471 |
+
r1 = t.start_req(prompt_len=VERY_LONG_PROMPT_LEN, max_new_tokens=2)
|
| 472 |
+
yield from run_until(r1, lambda h: h.is_chunking and h.chunks_done >= 1)
|
| 473 |
+
|
| 474 |
+
competitors = [
|
| 475 |
+
t.start_req(prompt_len=3 * DEFAULT_CHUNK_SIZE + 32, max_new_tokens=2)
|
| 476 |
+
for _ in range(6)
|
| 477 |
+
]
|
| 478 |
+
|
| 479 |
+
baseline_chunks = r1.chunks_done
|
| 480 |
+
for _ in range(50):
|
| 481 |
+
if r1.chunks_done > baseline_chunks:
|
| 482 |
+
break
|
| 483 |
+
yield
|
| 484 |
+
else:
|
| 485 |
+
raise AssertionError(
|
| 486 |
+
f"bf5b4e9a10: chunked-resume starved under LPM by "
|
| 487 |
+
f"long-prefix competitors; chunks_done stuck at "
|
| 488 |
+
f"{baseline_chunks}"
|
| 489 |
+
)
|
| 490 |
+
|
| 491 |
+
yield from run_until_all_finished([r1, *competitors])
|
| 492 |
+
|
| 493 |
+
|
| 494 |
+
class TestRegressionGptOss(ScriptedTestCase):
|
| 495 |
+
ENGINE_KWARGS = base_engine_kwargs(
|
| 496 |
+
chunked_prefill_size=DEFAULT_CHUNK_SIZE,
|
| 497 |
+
model_path="openai/gpt-oss-20b",
|
| 498 |
+
mem_fraction_static=0.70,
|
| 499 |
+
disable_piecewise_cuda_graph=True,
|
| 500 |
+
)
|
| 501 |
+
|
| 502 |
+
def test_chunked_stash_bounded_by_kv_committed_len(self):
|
| 503 |
+
self.server.execute_script(
|
| 504 |
+
self._script_chunked_stash_bounded_by_kv_committed_len
|
| 505 |
+
)
|
| 506 |
+
|
| 507 |
+
@staticmethod
|
| 508 |
+
def _script_chunked_stash_bounded_by_kv_committed_len(t: ScriptedContext):
|
| 509 |
+
r = t.start_req(prompt_len=VERY_LONG_PROMPT_LEN, max_new_tokens=2)
|
| 510 |
+
yield from run_until(r, lambda h: h.is_chunking and h.chunks_done >= 1)
|
| 511 |
+
|
| 512 |
+
committed = r.req.kv_committed_len
|
| 513 |
+
assert committed > 0
|
| 514 |
+
|
| 515 |
+
assert len(r.req.prefix_indices) <= committed, (
|
| 516 |
+
f"cache_unfinished_req over-read past kv_committed_len: "
|
| 517 |
+
f"prefix_indices_len={len(r.req.prefix_indices)}, "
|
| 518 |
+
f"kv_committed_len={committed}"
|
| 519 |
+
)
|
| 520 |
+
yield from run_until_finished(r)
|
| 521 |
+
|
| 522 |
+
|
| 523 |
+
if __name__ == "__main__":
|
| 524 |
+
unittest.main()
|
asian_ai/performance/SGLang/test/manual/chunked_prefill/test_scripted_sampling.py
ADDED
|
@@ -0,0 +1,274 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import unittest
|
| 2 |
+
|
| 3 |
+
from sglang.srt.managers.schedule_batch import FINISH_LENGTH, FINISH_MATCHED_TOKEN
|
| 4 |
+
from sglang.test.scripted_runtime.context import ScriptedContext
|
| 5 |
+
from sglang.test.scripted_runtime.test_case import ScriptedTestCase
|
| 6 |
+
from sglang.test.scripted_runtime_chunked_helpers import (
|
| 7 |
+
DEFAULT_CHUNK_SIZE,
|
| 8 |
+
VERY_LONG_PROMPT_LEN,
|
| 9 |
+
base_engine_kwargs,
|
| 10 |
+
run_until,
|
| 11 |
+
run_until_finished,
|
| 12 |
+
)
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
class TestSamplingBasic(ScriptedTestCase):
|
| 16 |
+
ENGINE_KWARGS = base_engine_kwargs(chunked_prefill_size=DEFAULT_CHUNK_SIZE)
|
| 17 |
+
|
| 18 |
+
def test_max_new_tokens_zero_prefill_only(self):
|
| 19 |
+
self.server.execute_script(self._script_max_new_tokens_zero_prefill_only)
|
| 20 |
+
|
| 21 |
+
@staticmethod
|
| 22 |
+
def _script_max_new_tokens_zero_prefill_only(t: ScriptedContext):
|
| 23 |
+
r = t.start_req(prompt_len=VERY_LONG_PROMPT_LEN, max_new_tokens=0)
|
| 24 |
+
yield from run_until_finished(r)
|
| 25 |
+
assert r.finished
|
| 26 |
+
assert r.chunks_done >= 2
|
| 27 |
+
assert len(r.req.output_ids) == 1, (
|
| 28 |
+
f"max_new_tokens=0 finishes on the prefill chunk with one sampled "
|
| 29 |
+
f"token; got {len(r.req.output_ids)}"
|
| 30 |
+
)
|
| 31 |
+
decode_records = [
|
| 32 |
+
rec
|
| 33 |
+
for rec in t._scheduler_hook._batch_log
|
| 34 |
+
if r.rid in rec.rids and rec.mode == "decode"
|
| 35 |
+
]
|
| 36 |
+
assert len(decode_records) == 0, (
|
| 37 |
+
f"max_new_tokens=0 must run zero decode forwards; got "
|
| 38 |
+
f"{len(decode_records)}"
|
| 39 |
+
)
|
| 40 |
+
|
| 41 |
+
def test_max_new_tokens_one_long_chunked(self):
|
| 42 |
+
self.server.execute_script(self._script_max_new_tokens_one_long_chunked)
|
| 43 |
+
|
| 44 |
+
@staticmethod
|
| 45 |
+
def _script_max_new_tokens_one_long_chunked(t: ScriptedContext):
|
| 46 |
+
r = t.start_req(prompt_len=VERY_LONG_PROMPT_LEN, max_new_tokens=1)
|
| 47 |
+
yield from run_until_finished(r)
|
| 48 |
+
assert r.finished
|
| 49 |
+
assert r.chunks_done >= 2
|
| 50 |
+
assert len(r.req.output_ids) == 1, (
|
| 51 |
+
f"max_new_tokens=1 must produce exactly 1 token, got "
|
| 52 |
+
f"{len(r.req.output_ids)}"
|
| 53 |
+
)
|
| 54 |
+
|
| 55 |
+
def test_max_new_tokens_1000_long_chunked(self):
|
| 56 |
+
self.server.execute_script(self._script_max_new_tokens_1000_long_chunked)
|
| 57 |
+
|
| 58 |
+
@staticmethod
|
| 59 |
+
def _script_max_new_tokens_1000_long_chunked(t: ScriptedContext):
|
| 60 |
+
r = t.start_req(
|
| 61 |
+
prompt_len=VERY_LONG_PROMPT_LEN,
|
| 62 |
+
max_new_tokens=1000,
|
| 63 |
+
ignore_eos=True,
|
| 64 |
+
)
|
| 65 |
+
yield from run_until(r, lambda h: h.finished, max_steps=2000)
|
| 66 |
+
assert r.finished
|
| 67 |
+
assert r.chunks_done >= 2
|
| 68 |
+
assert len(r.req.output_ids) == 1000, (
|
| 69 |
+
f"ignore_eos=True + max_new_tokens=1000 must produce 1000 "
|
| 70 |
+
f"output tokens; got {len(r.req.output_ids)}"
|
| 71 |
+
)
|
| 72 |
+
|
| 73 |
+
def test_return_logprob_chunked(self):
|
| 74 |
+
self.server.execute_script(self._script_return_logprob_chunked)
|
| 75 |
+
|
| 76 |
+
@staticmethod
|
| 77 |
+
def _script_return_logprob_chunked(t: ScriptedContext):
|
| 78 |
+
r = t.start_req(
|
| 79 |
+
prompt_len=VERY_LONG_PROMPT_LEN,
|
| 80 |
+
max_new_tokens=4,
|
| 81 |
+
return_logprob=True,
|
| 82 |
+
ignore_eos=True,
|
| 83 |
+
)
|
| 84 |
+
yield from run_until_finished(r)
|
| 85 |
+
assert r.finished
|
| 86 |
+
assert r.chunks_done >= 2
|
| 87 |
+
assert r.req.logprob is not None
|
| 88 |
+
assert len(r.req.logprob.output_token_logprobs_val) == 4
|
| 89 |
+
|
| 90 |
+
def test_ignore_eos_chunked(self):
|
| 91 |
+
self.server.execute_script(self._script_ignore_eos_chunked)
|
| 92 |
+
|
| 93 |
+
@staticmethod
|
| 94 |
+
def _script_ignore_eos_chunked(t: ScriptedContext):
|
| 95 |
+
r = t.start_req(
|
| 96 |
+
prompt_len=VERY_LONG_PROMPT_LEN, max_new_tokens=16, ignore_eos=True
|
| 97 |
+
)
|
| 98 |
+
yield from run_until_finished(r)
|
| 99 |
+
assert r.finished
|
| 100 |
+
assert r.chunks_done >= 2
|
| 101 |
+
assert len(r.req.output_ids) == 16
|
| 102 |
+
assert isinstance(r.req.finished_reason, FINISH_LENGTH), (
|
| 103 |
+
f"ignore_eos=True must finish via length cap; got "
|
| 104 |
+
f"{r.req.finished_reason!r}"
|
| 105 |
+
)
|
| 106 |
+
|
| 107 |
+
def test_return_logprob_top_logprobs_chunked(self):
|
| 108 |
+
self.server.execute_script(self._script_return_logprob_top_logprobs_chunked)
|
| 109 |
+
|
| 110 |
+
@staticmethod
|
| 111 |
+
def _script_return_logprob_top_logprobs_chunked(t: ScriptedContext):
|
| 112 |
+
top_k = 5
|
| 113 |
+
r = t.start_req(
|
| 114 |
+
prompt_len=VERY_LONG_PROMPT_LEN,
|
| 115 |
+
max_new_tokens=4,
|
| 116 |
+
return_logprob=True,
|
| 117 |
+
top_logprobs_num=top_k,
|
| 118 |
+
ignore_eos=True,
|
| 119 |
+
)
|
| 120 |
+
yield from run_until_finished(r)
|
| 121 |
+
assert r.finished
|
| 122 |
+
assert r.chunks_done >= 2
|
| 123 |
+
assert r.req.logprob is not None
|
| 124 |
+
top = r.req.logprob.output_top_logprobs_val
|
| 125 |
+
assert len(top) == 4, (
|
| 126 |
+
f"top logprobs must be reported once per output token; "
|
| 127 |
+
f"got {len(top)} entries for 4 tokens"
|
| 128 |
+
)
|
| 129 |
+
for step_entries in top:
|
| 130 |
+
assert len(step_entries) == top_k, (
|
| 131 |
+
f"each step must carry exactly top_logprobs_num={top_k} "
|
| 132 |
+
f"entries; got {len(step_entries)}"
|
| 133 |
+
)
|
| 134 |
+
|
| 135 |
+
def test_explicit_rid_chunked(self):
|
| 136 |
+
self.server.execute_script(self._script_explicit_rid_chunked)
|
| 137 |
+
|
| 138 |
+
@staticmethod
|
| 139 |
+
def _script_explicit_rid_chunked(t: ScriptedContext):
|
| 140 |
+
r = t.start_req(
|
| 141 |
+
prompt_len=VERY_LONG_PROMPT_LEN,
|
| 142 |
+
max_new_tokens=2,
|
| 143 |
+
rid="custom-rid-1",
|
| 144 |
+
ignore_eos=True,
|
| 145 |
+
)
|
| 146 |
+
yield from run_until_finished(r)
|
| 147 |
+
assert r.rid == "custom-rid-1"
|
| 148 |
+
assert r.finished
|
| 149 |
+
assert r.chunks_done >= 2
|
| 150 |
+
assert len(r.req.output_ids) == 2
|
| 151 |
+
|
| 152 |
+
def test_default_sampling_short(self):
|
| 153 |
+
self.server.execute_script(self._script_default_sampling_short)
|
| 154 |
+
|
| 155 |
+
@staticmethod
|
| 156 |
+
def _script_default_sampling_short(t: ScriptedContext):
|
| 157 |
+
r = t.start_req(prompt_len=8, max_new_tokens=2, ignore_eos=True)
|
| 158 |
+
yield from run_until_finished(r)
|
| 159 |
+
assert r.finished
|
| 160 |
+
assert r.chunks_done == 0
|
| 161 |
+
assert len(r.req.output_ids) == 2
|
| 162 |
+
|
| 163 |
+
def test_chunked_logprob_input_accumulates_across_chunks(self):
|
| 164 |
+
self.server.execute_script(
|
| 165 |
+
self._script_chunked_logprob_input_accumulates_across_chunks
|
| 166 |
+
)
|
| 167 |
+
|
| 168 |
+
@staticmethod
|
| 169 |
+
def _script_chunked_logprob_input_accumulates_across_chunks(t: ScriptedContext):
|
| 170 |
+
prompt_len = VERY_LONG_PROMPT_LEN
|
| 171 |
+
r = t.start_req(
|
| 172 |
+
prompt_len=prompt_len,
|
| 173 |
+
max_new_tokens=4,
|
| 174 |
+
return_logprob=True,
|
| 175 |
+
logprob_start_len=0,
|
| 176 |
+
)
|
| 177 |
+
yield from run_until_finished(r)
|
| 178 |
+
assert r.finished
|
| 179 |
+
assert (
|
| 180 |
+
r.chunks_done >= 2
|
| 181 |
+
), f"prompt should span multiple chunks, got chunks_done={r.chunks_done}"
|
| 182 |
+
assert r.req.logprob is not None
|
| 183 |
+
input_lp = r.req.logprob.input_token_logprobs_val
|
| 184 |
+
assert len(input_lp) == prompt_len, (
|
| 185 |
+
f"expected {prompt_len} input logprobs (one per prompt token), "
|
| 186 |
+
f"got {len(input_lp)}"
|
| 187 |
+
)
|
| 188 |
+
|
| 189 |
+
def test_logprob_start_len_inside_chunk_2(self):
|
| 190 |
+
self.server.execute_script(self._script_logprob_start_len_inside_chunk_2)
|
| 191 |
+
|
| 192 |
+
@staticmethod
|
| 193 |
+
def _script_logprob_start_len_inside_chunk_2(t: ScriptedContext):
|
| 194 |
+
prompt_len = 4 * DEFAULT_CHUNK_SIZE
|
| 195 |
+
start_len = DEFAULT_CHUNK_SIZE + 50
|
| 196 |
+
r = t.start_req(
|
| 197 |
+
prompt_len=prompt_len,
|
| 198 |
+
max_new_tokens=4,
|
| 199 |
+
return_logprob=True,
|
| 200 |
+
logprob_start_len=start_len,
|
| 201 |
+
)
|
| 202 |
+
yield from run_until_finished(r)
|
| 203 |
+
assert r.finished
|
| 204 |
+
assert (
|
| 205 |
+
r.chunks_done >= 3
|
| 206 |
+
), f"prompt should span 3+ chunks, got chunks_done={r.chunks_done}"
|
| 207 |
+
assert r.req.logprob is not None
|
| 208 |
+
input_lp = r.req.logprob.input_token_logprobs_val
|
| 209 |
+
assert len(input_lp) == prompt_len - start_len, (
|
| 210 |
+
f"expected {prompt_len - start_len} input logprobs for tokens "
|
| 211 |
+
f">= logprob_start_len={start_len}, got {len(input_lp)}"
|
| 212 |
+
)
|
| 213 |
+
|
| 214 |
+
def test_finish_reason_value_eos_vs_length_chunked(self):
|
| 215 |
+
self.server.execute_script(
|
| 216 |
+
self._script_finish_reason_value_eos_vs_length_chunked
|
| 217 |
+
)
|
| 218 |
+
|
| 219 |
+
@staticmethod
|
| 220 |
+
def _script_finish_reason_value_eos_vs_length_chunked(t: ScriptedContext):
|
| 221 |
+
probe = t.start_req(
|
| 222 |
+
prompt_len=VERY_LONG_PROMPT_LEN,
|
| 223 |
+
max_new_tokens=1,
|
| 224 |
+
ignore_eos=True,
|
| 225 |
+
prompt_token=7,
|
| 226 |
+
temperature=0.0,
|
| 227 |
+
)
|
| 228 |
+
yield from run_until_finished(probe)
|
| 229 |
+
assert probe.finished
|
| 230 |
+
first_token = probe.req.output_ids[0]
|
| 231 |
+
|
| 232 |
+
for _ in range(40):
|
| 233 |
+
if t.is_fully_idle:
|
| 234 |
+
break
|
| 235 |
+
yield
|
| 236 |
+
t.flush_cache()
|
| 237 |
+
yield
|
| 238 |
+
|
| 239 |
+
r_eos = t.start_req(
|
| 240 |
+
prompt_len=VERY_LONG_PROMPT_LEN,
|
| 241 |
+
max_new_tokens=999,
|
| 242 |
+
ignore_eos=False,
|
| 243 |
+
prompt_token=7,
|
| 244 |
+
stop_token_ids=[first_token],
|
| 245 |
+
temperature=0.0,
|
| 246 |
+
)
|
| 247 |
+
yield from run_until_finished(r_eos, max_steps=2000)
|
| 248 |
+
assert r_eos.finished
|
| 249 |
+
assert (
|
| 250 |
+
r_eos.chunks_done >= 2
|
| 251 |
+
), f"scenario 1 should chunk; got chunks_done={r_eos.chunks_done}"
|
| 252 |
+
assert isinstance(r_eos.req.finished_reason, FINISH_MATCHED_TOKEN), (
|
| 253 |
+
f"a stop token the model deterministically produces under greedy must "
|
| 254 |
+
f"finish via the matched-token path; got {r_eos.req.finished_reason!r}"
|
| 255 |
+
)
|
| 256 |
+
|
| 257 |
+
r_length = t.start_req(
|
| 258 |
+
prompt_len=VERY_LONG_PROMPT_LEN,
|
| 259 |
+
max_new_tokens=4,
|
| 260 |
+
ignore_eos=True,
|
| 261 |
+
)
|
| 262 |
+
yield from run_until_finished(r_length)
|
| 263 |
+
assert r_length.finished
|
| 264 |
+
assert (
|
| 265 |
+
r_length.chunks_done >= 2
|
| 266 |
+
), f"scenario 2 should chunk; got chunks_done={r_length.chunks_done}"
|
| 267 |
+
assert isinstance(r_length.req.finished_reason, FINISH_LENGTH), (
|
| 268 |
+
f"ignore_eos=True + max_new_tokens=4 chunked must finish via "
|
| 269 |
+
f"length cap; got {r_length.req.finished_reason!r}"
|
| 270 |
+
)
|
| 271 |
+
|
| 272 |
+
|
| 273 |
+
if __name__ == "__main__":
|
| 274 |
+
unittest.main()
|
asian_ai/performance/SGLang/test/manual/chunked_prefill/test_scripted_spec.py
ADDED
|
@@ -0,0 +1,67 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import unittest
|
| 2 |
+
|
| 3 |
+
from sglang.test.scripted_runtime.context import ScriptedContext
|
| 4 |
+
from sglang.test.scripted_runtime.test_case import ScriptedTestCase
|
| 5 |
+
from sglang.test.scripted_runtime_chunked_helpers import (
|
| 6 |
+
DEFAULT_CHUNK_SIZE,
|
| 7 |
+
VERY_LONG_PROMPT_LEN,
|
| 8 |
+
base_engine_kwargs,
|
| 9 |
+
run_until,
|
| 10 |
+
run_until_finished,
|
| 11 |
+
)
|
| 12 |
+
|
| 13 |
+
_SPEC_MODEL = "Qwen/Qwen3-8B"
|
| 14 |
+
_SPEC_DRAFT = "Tengyunw/qwen3_8b_eagle3"
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
def _spec_engine_kwargs(**overrides):
|
| 18 |
+
return base_engine_kwargs(
|
| 19 |
+
model_path=_SPEC_MODEL,
|
| 20 |
+
chunked_prefill_size=DEFAULT_CHUNK_SIZE,
|
| 21 |
+
speculative_algorithm="EAGLE3",
|
| 22 |
+
speculative_draft_model_path=_SPEC_DRAFT,
|
| 23 |
+
speculative_num_steps=6,
|
| 24 |
+
speculative_eagle_topk=10,
|
| 25 |
+
speculative_num_draft_tokens=32,
|
| 26 |
+
kv_canary="none",
|
| 27 |
+
kv_canary_real_data="none",
|
| 28 |
+
kv_canary_sweep_interval=0,
|
| 29 |
+
**overrides,
|
| 30 |
+
)
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
class TestSpecBasic(ScriptedTestCase):
|
| 34 |
+
ENGINE_KWARGS = _spec_engine_kwargs()
|
| 35 |
+
|
| 36 |
+
def test_spec_chunked_handoff_first_verify(self):
|
| 37 |
+
self.server.execute_script(self._script_spec_chunked_handoff_first_verify)
|
| 38 |
+
|
| 39 |
+
@staticmethod
|
| 40 |
+
def _script_spec_chunked_handoff_first_verify(t: ScriptedContext):
|
| 41 |
+
r = t.start_req(prompt_len=VERY_LONG_PROMPT_LEN, max_new_tokens=16)
|
| 42 |
+
yield from run_until_finished(r, max_steps=800)
|
| 43 |
+
assert r.finished
|
| 44 |
+
assert r.chunks_done >= 2
|
| 45 |
+
assert r.req.spec_verify_ct >= 1, (
|
| 46 |
+
f"expected >=1 spec verify after chunked handoff, got "
|
| 47 |
+
f"{r.req.spec_verify_ct}"
|
| 48 |
+
)
|
| 49 |
+
|
| 50 |
+
def test_spec_abort_during_chunked_prepare(self):
|
| 51 |
+
self.server.execute_script(self._script_spec_abort_during_chunked_prepare)
|
| 52 |
+
|
| 53 |
+
@staticmethod
|
| 54 |
+
def _script_spec_abort_during_chunked_prepare(t: ScriptedContext):
|
| 55 |
+
r = t.start_req(prompt_len=VERY_LONG_PROMPT_LEN, max_new_tokens=16)
|
| 56 |
+
yield from run_until(r, lambda h: h.is_chunking and h.chunks_done >= 1)
|
| 57 |
+
t.abort(r)
|
| 58 |
+
for _ in range(40):
|
| 59 |
+
if t.is_fully_idle:
|
| 60 |
+
break
|
| 61 |
+
yield
|
| 62 |
+
assert r.kv_pages == 0
|
| 63 |
+
assert r.lock_refs == 0
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
if __name__ == "__main__":
|
| 67 |
+
unittest.main()
|
asian_ai/performance/SGLang/test/manual/chunked_prefill/test_scripted_special_case.py
ADDED
|
@@ -0,0 +1,1254 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
import unittest
|
| 2 |
+
from typing import Optional
|
| 3 |
+
|
| 4 |
+
from sglang.test.scripted_runtime.context import ScriptedContext
|
| 5 |
+
from sglang.test.scripted_runtime.test_case import ScriptedTestCase
|
| 6 |
+
from sglang.test.scripted_runtime_chunked_helpers import (
|
| 7 |
+
DEFAULT_CHUNK_SIZE,
|
| 8 |
+
DEFAULT_MAX_STEPS,
|
| 9 |
+
SMALL_KV_POOL_BALLAST_MAX_NEW_TOKENS,
|
| 10 |
+
SMALL_KV_POOL_BALLAST_PROMPT_LEN,
|
| 11 |
+
SMALL_KV_POOL_MAX_TOTAL_TOKENS,
|
| 12 |
+
VERY_LONG_PROMPT_LEN,
|
| 13 |
+
advance_to_decode_step,
|
| 14 |
+
base_engine_kwargs,
|
| 15 |
+
exhaust_row_pool,
|
| 16 |
+
run_until,
|
| 17 |
+
run_until_finished,
|
| 18 |
+
)
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
def _load_inquirer_pending_for_rid(t: ScriptedContext, rid: str) -> int:
|
| 22 |
+
s = t.scheduler
|
| 23 |
+
chunked = s.chunked_req
|
| 24 |
+
if chunked is not None and chunked.rid == rid:
|
| 25 |
+
return chunked.seqlen - len(chunked.prefix_indices)
|
| 26 |
+
for req in s.waiting_queue:
|
| 27 |
+
if req.rid == rid:
|
| 28 |
+
return req.seqlen
|
| 29 |
+
return 0
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
class TestSpecialCaseBasic(ScriptedTestCase):
|
| 33 |
+
ENGINE_KWARGS = base_engine_kwargs(chunked_prefill_size=DEFAULT_CHUNK_SIZE)
|
| 34 |
+
|
| 35 |
+
def test_chunked_in_flight_no_idle(self):
|
| 36 |
+
self.server.execute_script(self._script_chunked_in_flight_no_idle)
|
| 37 |
+
|
| 38 |
+
@staticmethod
|
| 39 |
+
def _script_chunked_in_flight_no_idle(t: ScriptedContext):
|
| 40 |
+
r = t.start_req(
|
| 41 |
+
prompt_len=VERY_LONG_PROMPT_LEN, max_new_tokens=2, prompt_token=100
|
| 42 |
+
)
|
| 43 |
+
yield from run_until(r, lambda h: h.is_chunking)
|
| 44 |
+
saw_chunking = False
|
| 45 |
+
for _ in range(DEFAULT_MAX_STEPS):
|
| 46 |
+
if r.is_chunking:
|
| 47 |
+
saw_chunking = True
|
| 48 |
+
assert (
|
| 49 |
+
not t.is_idle
|
| 50 |
+
), "scheduler must not idle while chunked_req is in flight"
|
| 51 |
+
if r.finished:
|
| 52 |
+
break
|
| 53 |
+
yield
|
| 54 |
+
assert r.finished
|
| 55 |
+
assert saw_chunking, "test must observe r mid-chunk at least once"
|
| 56 |
+
|
| 57 |
+
def test_add_chunked_req_path(self):
|
| 58 |
+
self.server.execute_script(self._script_add_chunked_req_path)
|
| 59 |
+
|
| 60 |
+
@staticmethod
|
| 61 |
+
def _script_add_chunked_req_path(t: ScriptedContext):
|
| 62 |
+
r = t.start_req(
|
| 63 |
+
prompt_len=VERY_LONG_PROMPT_LEN, max_new_tokens=2, prompt_token=110
|
| 64 |
+
)
|
| 65 |
+
yield from run_until_finished(r)
|
| 66 |
+
assert r.finished
|
| 67 |
+
assert r.chunks_done >= 2
|
| 68 |
+
|
| 69 |
+
def test_admission_with_chunked_in_flight(self):
|
| 70 |
+
self.server.execute_script(self._script_admission_with_chunked_in_flight)
|
| 71 |
+
|
| 72 |
+
@staticmethod
|
| 73 |
+
def _script_admission_with_chunked_in_flight(t: ScriptedContext):
|
| 74 |
+
r_chunk = t.start_req(
|
| 75 |
+
prompt_len=VERY_LONG_PROMPT_LEN, max_new_tokens=2, prompt_token=120
|
| 76 |
+
)
|
| 77 |
+
yield from run_until(r_chunk, lambda h: h.is_chunking)
|
| 78 |
+
|
| 79 |
+
r_small = t.start_req(prompt_len=4, max_new_tokens=2)
|
| 80 |
+
yield
|
| 81 |
+
|
| 82 |
+
comp = t.batch_composition()
|
| 83 |
+
assert r_chunk.rid in comp.get("chunked", [])
|
| 84 |
+
|
| 85 |
+
yield from run_until_finished(r_small)
|
| 86 |
+
yield from run_until_finished(r_chunk)
|
| 87 |
+
assert r_small.finished and r_chunk.finished
|
| 88 |
+
|
| 89 |
+
def test_abort_excludes_chunked_req(self):
|
| 90 |
+
self.server.execute_script(self._script_abort_excludes_chunked_req)
|
| 91 |
+
|
| 92 |
+
@staticmethod
|
| 93 |
+
def _script_abort_excludes_chunked_req(t: ScriptedContext):
|
| 94 |
+
r = t.start_req(
|
| 95 |
+
prompt_len=VERY_LONG_PROMPT_LEN, max_new_tokens=2, prompt_token=130
|
| 96 |
+
)
|
| 97 |
+
yield from run_until(r, lambda h: h.is_chunking)
|
| 98 |
+
|
| 99 |
+
t.abort(r)
|
| 100 |
+
for _ in range(12):
|
| 101 |
+
if t.scheduler.chunked_req is None and r.kv_pages == 0 and r.lock_refs == 0:
|
| 102 |
+
break
|
| 103 |
+
yield
|
| 104 |
+
|
| 105 |
+
assert (
|
| 106 |
+
t.scheduler.chunked_req is None
|
| 107 |
+
), f"abort must clear the chunked slot; got {t.scheduler.chunked_req!r}"
|
| 108 |
+
assert r.kv_pages == 0
|
| 109 |
+
assert r.lock_refs == 0
|
| 110 |
+
|
| 111 |
+
def test_get_chunked_req_lambda_getter(self):
|
| 112 |
+
self.server.execute_script(self._script_get_chunked_req_lambda_getter)
|
| 113 |
+
|
| 114 |
+
@staticmethod
|
| 115 |
+
def _script_get_chunked_req_lambda_getter(t: ScriptedContext):
|
| 116 |
+
r = t.start_req(
|
| 117 |
+
prompt_len=VERY_LONG_PROMPT_LEN, max_new_tokens=2, prompt_token=140
|
| 118 |
+
)
|
| 119 |
+
yield from run_until(r, lambda h: h.is_chunking)
|
| 120 |
+
saw_match = False
|
| 121 |
+
for _ in range(DEFAULT_MAX_STEPS):
|
| 122 |
+
if r.is_chunking:
|
| 123 |
+
cur = (
|
| 124 |
+
t.scheduler.chunked_req.rid
|
| 125 |
+
if t.scheduler.chunked_req is not None
|
| 126 |
+
else None
|
| 127 |
+
)
|
| 128 |
+
assert cur in (None, r.rid), (
|
| 129 |
+
f"getter returned unrelated rid: got {cur!r}, expected "
|
| 130 |
+
f"None or {r.rid!r}"
|
| 131 |
+
)
|
| 132 |
+
if cur == r.rid:
|
| 133 |
+
saw_match = True
|
| 134 |
+
if r.finished:
|
| 135 |
+
break
|
| 136 |
+
yield
|
| 137 |
+
assert r.finished
|
| 138 |
+
assert saw_match, "getter must return r.rid at least once while r.is_chunking"
|
| 139 |
+
assert (
|
| 140 |
+
t.scheduler.chunked_req.rid if t.scheduler.chunked_req is not None else None
|
| 141 |
+
) is None
|
| 142 |
+
|
| 143 |
+
@unittest.skip(
|
| 144 |
+
"requires real disaggregation prefill/decode split — single-engine "
|
| 145 |
+
"ScriptedContext cannot exercise the decode-side waiting_queue "
|
| 146 |
+
"KV-hold path. Belongs in test_scripted_disagg.py with D3 counter "
|
| 147 |
+
"wiring once disagg topology is available."
|
| 148 |
+
)
|
| 149 |
+
def test_disagg_decode_waiting_queue_kv_held(self):
|
| 150 |
+
pass
|
| 151 |
+
|
| 152 |
+
@unittest.skip(
|
| 153 |
+
"requires DLLM model + staging mixin — single-engine cannot drive "
|
| 154 |
+
"both DLLM staging AND chunked admission incrementing "
|
| 155 |
+
"inflight_middle_chunks from two sources. Belongs in DLLM-specific "
|
| 156 |
+
"test file."
|
| 157 |
+
)
|
| 158 |
+
def test_dllm_staging_double_inflight_middle_chunks(self):
|
| 159 |
+
pass
|
| 160 |
+
|
| 161 |
+
@unittest.skip(
|
| 162 |
+
"requires real disaggregation topology — single-engine cannot "
|
| 163 |
+
"exercise staging_handler chunked path."
|
| 164 |
+
)
|
| 165 |
+
def test_staging_handler_chunked(self):
|
| 166 |
+
pass
|
| 167 |
+
|
| 168 |
+
@unittest.skip(
|
| 169 |
+
"requires mooncake KV transport backend — single-engine cannot "
|
| 170 |
+
"drive the conn layer chunked path."
|
| 171 |
+
)
|
| 172 |
+
def test_mooncake_conn_chunked(self):
|
| 173 |
+
pass
|
| 174 |
+
|
| 175 |
+
@unittest.skip(
|
| 176 |
+
"requires NIXL KV transport backend — single-engine cannot drive "
|
| 177 |
+
"the NIXL conn layer chunked path."
|
| 178 |
+
)
|
| 179 |
+
def test_nixl_conn_chunked(self):
|
| 180 |
+
pass
|
| 181 |
+
|
| 182 |
+
def test_filter_batch_exclude_chunked_flag(self):
|
| 183 |
+
self.server.execute_script(self._script_filter_batch_exclude_chunked_flag)
|
| 184 |
+
|
| 185 |
+
@staticmethod
|
| 186 |
+
def _script_filter_batch_exclude_chunked_flag(t: ScriptedContext):
|
| 187 |
+
r1 = t.start_req(
|
| 188 |
+
prompt_len=VERY_LONG_PROMPT_LEN, max_new_tokens=2, prompt_token=150
|
| 189 |
+
)
|
| 190 |
+
r2 = t.start_req(prompt_len=16, max_new_tokens=2)
|
| 191 |
+
saw_r1_chunking = False
|
| 192 |
+
for _ in range(DEFAULT_MAX_STEPS * 2):
|
| 193 |
+
if r1.is_chunking:
|
| 194 |
+
saw_r1_chunking = True
|
| 195 |
+
comp = t.batch_composition()
|
| 196 |
+
assert r1.rid in comp.get(
|
| 197 |
+
"chunked", []
|
| 198 |
+
), f"mid-chunk r1 must occupy the chunked role; got {comp!r}"
|
| 199 |
+
assert r1.rid not in comp.get(
|
| 200 |
+
"running", []
|
| 201 |
+
), f"chunked r1 must be excluded from the running role; got {comp!r}"
|
| 202 |
+
if r1.finished and r2.finished:
|
| 203 |
+
break
|
| 204 |
+
yield
|
| 205 |
+
assert r1.finished and r2.finished
|
| 206 |
+
assert (
|
| 207 |
+
saw_r1_chunking
|
| 208 |
+
), "r1 must have chunked at some point to exercise the exclude branch"
|
| 209 |
+
|
| 210 |
+
@unittest.skip(
|
| 211 |
+
"pdmux split_prefill_batch requires the pdmux topology — "
|
| 212 |
+
"single-engine ScriptedContext cannot drive the split path. "
|
| 213 |
+
"Belongs in a pdmux-specific test once that lane is wired up."
|
| 214 |
+
)
|
| 215 |
+
def test_pdmux_split_prefill_batch(self):
|
| 216 |
+
pass
|
| 217 |
+
|
| 218 |
+
def test_streaming_session_kv_committed_bound(self):
|
| 219 |
+
self.server.execute_script(self._script_streaming_session_kv_committed_bound)
|
| 220 |
+
|
| 221 |
+
@staticmethod
|
| 222 |
+
def _script_streaming_session_kv_committed_bound(t: ScriptedContext):
|
| 223 |
+
r = t.start_req(
|
| 224 |
+
prompt_len=VERY_LONG_PROMPT_LEN, max_new_tokens=2, prompt_token=160
|
| 225 |
+
)
|
| 226 |
+
for _ in range(DEFAULT_MAX_STEPS):
|
| 227 |
+
if r.is_chunking:
|
| 228 |
+
assert len(r.req.prefix_indices) <= r.req.kv_committed_len, (
|
| 229 |
+
f"streaming-session chunked stash must stay bounded by "
|
| 230 |
+
f"kv_committed_len; prefix_indices_len={len(r.req.prefix_indices)}, "
|
| 231 |
+
f"kv_committed_len={r.req.kv_committed_len}"
|
| 232 |
+
)
|
| 233 |
+
if r.finished:
|
| 234 |
+
break
|
| 235 |
+
yield
|
| 236 |
+
assert r.finished
|
| 237 |
+
|
| 238 |
+
@unittest.skip(
|
| 239 |
+
"mamba_pool_idx cleanup applies only to mamba-class models — "
|
| 240 |
+
"single-engine with a non-mamba model cannot drive the NO_TOKEN "
|
| 241 |
+
"chunked-resume cleanup-skip branch. Belongs in a mamba-specific "
|
| 242 |
+
"test file once mamba scripted coverage is added."
|
| 243 |
+
)
|
| 244 |
+
def test_mamba_pool_idx_cleanup_skip_chunked_resume(self):
|
| 245 |
+
pass
|
| 246 |
+
|
| 247 |
+
def test_pause_retract_clears_chunked_req(self):
|
| 248 |
+
self.server.execute_script(self._script_pause_retract_clears_chunked_req)
|
| 249 |
+
|
| 250 |
+
@staticmethod
|
| 251 |
+
def _script_pause_retract_clears_chunked_req(t: ScriptedContext):
|
| 252 |
+
r = t.start_req(
|
| 253 |
+
prompt_len=VERY_LONG_PROMPT_LEN, max_new_tokens=2, prompt_token=170
|
| 254 |
+
)
|
| 255 |
+
yield from run_until(r, lambda h: h.is_chunking)
|
| 256 |
+
|
| 257 |
+
t.pause_generation(mode="retract")
|
| 258 |
+
yield
|
| 259 |
+
|
| 260 |
+
assert (
|
| 261 |
+
t.scheduler.chunked_req is None
|
| 262 |
+
), f"pause(retract) must clear chunked_req; got {t.scheduler.chunked_req!r}"
|
| 263 |
+
assert not r.finished, "retract must re-queue r, not finish or abort it"
|
| 264 |
+
assert r.status == "waiting", (
|
| 265 |
+
f"retracted chunked req must return to the waiting queue; "
|
| 266 |
+
f"got status={r.status!r}"
|
| 267 |
+
)
|
| 268 |
+
|
| 269 |
+
t.continue_generation()
|
| 270 |
+
yield from run_until_finished(r)
|
| 271 |
+
assert (
|
| 272 |
+
r.finished
|
| 273 |
+
), "continue_generation must drive the re-queued req to completion"
|
| 274 |
+
|
| 275 |
+
def test_retract_during_gap_inflight_middle_chunks_positive(self):
|
| 276 |
+
self.server.execute_script(
|
| 277 |
+
self._script_retract_during_gap_inflight_middle_chunks_positive
|
| 278 |
+
)
|
| 279 |
+
|
| 280 |
+
@staticmethod
|
| 281 |
+
def _script_retract_during_gap_inflight_middle_chunks_positive(t: ScriptedContext):
|
| 282 |
+
r = t.start_req(
|
| 283 |
+
prompt_len=3 * DEFAULT_CHUNK_SIZE, max_new_tokens=2, prompt_token=180
|
| 284 |
+
)
|
| 285 |
+
yield from run_until(r, lambda h: h.is_chunking and h.chunks_done >= 1)
|
| 286 |
+
assert r.req.inflight_middle_chunks > 0
|
| 287 |
+
assert r.is_chunking
|
| 288 |
+
|
| 289 |
+
t.pause_generation(mode="retract")
|
| 290 |
+
yield
|
| 291 |
+
|
| 292 |
+
assert r.kv_pages == 0, f"retract must release KV; got kv_pages={r.kv_pages}"
|
| 293 |
+
assert not r.finished, "retract must re-queue r, not finish or abort it"
|
| 294 |
+
assert not r.is_chunking, "retract must release the chunked slot"
|
| 295 |
+
assert r.status == "waiting", (
|
| 296 |
+
f"retracted chunked req must return to the waiting queue; "
|
| 297 |
+
f"got status={r.status!r}"
|
| 298 |
+
)
|
| 299 |
+
req = t.find_req_by_rid(r.rid)
|
| 300 |
+
assert req is not None and req.inflight_middle_chunks == 0, (
|
| 301 |
+
f"retract must reset inflight_middle_chunks; got "
|
| 302 |
+
f"{req.inflight_middle_chunks if req is not None else None}"
|
| 303 |
+
)
|
| 304 |
+
|
| 305 |
+
t.continue_generation()
|
| 306 |
+
yield from run_until_finished(r, max_steps=2000)
|
| 307 |
+
assert (
|
| 308 |
+
r.finished
|
| 309 |
+
), "continue_generation must drive the re-queued req to completion"
|
| 310 |
+
assert r.kv_pages == 0
|
| 311 |
+
assert len(r.req.output_ids) == 2
|
| 312 |
+
|
| 313 |
+
def test_load_inquirer_pending_tokens_dedup_chunked(self):
|
| 314 |
+
self.server.execute_script(
|
| 315 |
+
self._script_load_inquirer_pending_tokens_dedup_chunked
|
| 316 |
+
)
|
| 317 |
+
|
| 318 |
+
@staticmethod
|
| 319 |
+
def _script_load_inquirer_pending_tokens_dedup_chunked(t: ScriptedContext):
|
| 320 |
+
r = t.start_req(
|
| 321 |
+
prompt_len=VERY_LONG_PROMPT_LEN, max_new_tokens=2, prompt_token=190
|
| 322 |
+
)
|
| 323 |
+
yield from run_until(r, lambda h: h.is_chunking)
|
| 324 |
+
saw_chunking = False
|
| 325 |
+
saw_dedup = False
|
| 326 |
+
for _ in range(DEFAULT_MAX_STEPS):
|
| 327 |
+
chunked = t.scheduler.chunked_req
|
| 328 |
+
if r.is_chunking and chunked is not None and chunked.rid == r.rid:
|
| 329 |
+
saw_chunking = True
|
| 330 |
+
pending = _load_inquirer_pending_for_rid(t, r.rid)
|
| 331 |
+
expected = chunked.seqlen - len(chunked.prefix_indices)
|
| 332 |
+
assert pending == expected, (
|
| 333 |
+
f"load_inquirer chunked contribution must equal the prefix-"
|
| 334 |
+
f"subtracting formula seqlen - len(prefix_indices) = {expected}; "
|
| 335 |
+
f"got {pending}"
|
| 336 |
+
)
|
| 337 |
+
assert pending <= chunked.seqlen, (
|
| 338 |
+
f"chunked contribution must never exceed its full seqlen "
|
| 339 |
+
f"{chunked.seqlen}; got {pending} — dual-queue dedup violated"
|
| 340 |
+
)
|
| 341 |
+
if len(chunked.prefix_indices) > 0:
|
| 342 |
+
saw_dedup = pending < chunked.seqlen
|
| 343 |
+
if r.finished:
|
| 344 |
+
break
|
| 345 |
+
yield
|
| 346 |
+
assert r.finished
|
| 347 |
+
assert (
|
| 348 |
+
saw_chunking
|
| 349 |
+
), "test must observe the dual-queue chunked state at least once"
|
| 350 |
+
assert saw_dedup, (
|
| 351 |
+
"test must observe the chunked req with a committed prefix so the "
|
| 352 |
+
"dedup subtraction is actually exercised"
|
| 353 |
+
)
|
| 354 |
+
|
| 355 |
+
def test_load_inquirer_chunked_contribution_exact_remainder(self):
|
| 356 |
+
self.server.execute_script(
|
| 357 |
+
self._script_load_inquirer_chunked_contribution_exact_remainder
|
| 358 |
+
)
|
| 359 |
+
|
| 360 |
+
@staticmethod
|
| 361 |
+
def _script_load_inquirer_chunked_contribution_exact_remainder(t: ScriptedContext):
|
| 362 |
+
s = t.scheduler
|
| 363 |
+
r = t.start_req(
|
| 364 |
+
prompt_len=VERY_LONG_PROMPT_LEN, max_new_tokens=2, prompt_token=200
|
| 365 |
+
)
|
| 366 |
+
yield from run_until(r, lambda h: h.is_chunking)
|
| 367 |
+
saw_chunking = False
|
| 368 |
+
for _ in range(DEFAULT_MAX_STEPS):
|
| 369 |
+
chunked = s.chunked_req
|
| 370 |
+
if r.is_chunking and chunked is not None and chunked.rid == r.rid:
|
| 371 |
+
assert len(s.waiting_queue) == 0, (
|
| 372 |
+
"test requires an empty waiting_queue so the chunked req is "
|
| 373 |
+
f"the sole pending-token contributor; got {len(s.waiting_queue)}"
|
| 374 |
+
)
|
| 375 |
+
expected = chunked.seqlen - len(chunked.prefix_indices)
|
| 376 |
+
observed = s.load_inquirer._get_num_pending_tokens()
|
| 377 |
+
assert observed == expected, (
|
| 378 |
+
f"chunked contribution must equal remainder "
|
| 379 |
+
f"seqlen - len(prefix_indices) = {expected}, got {observed}; "
|
| 380 |
+
f"a value of {chunked.seqlen} would mean the committed prefix "
|
| 381 |
+
"is being double-counted"
|
| 382 |
+
)
|
| 383 |
+
saw_chunking = True
|
| 384 |
+
if r.finished:
|
| 385 |
+
break
|
| 386 |
+
yield
|
| 387 |
+
assert r.finished
|
| 388 |
+
assert saw_chunking, "test must observe the chunked req mid-flight"
|
| 389 |
+
|
| 390 |
+
def test_load_inquirer_chunk_deduct_subtracts_planned_chunk(self):
|
| 391 |
+
self.server.execute_script(
|
| 392 |
+
self._script_load_inquirer_chunk_deduct_subtracts_planned_chunk
|
| 393 |
+
)
|
| 394 |
+
|
| 395 |
+
@staticmethod
|
| 396 |
+
def _script_load_inquirer_chunk_deduct_subtracts_planned_chunk(t: ScriptedContext):
|
| 397 |
+
s = t.scheduler
|
| 398 |
+
r = t.start_req(
|
| 399 |
+
prompt_len=VERY_LONG_PROMPT_LEN, max_new_tokens=2, prompt_token=210
|
| 400 |
+
)
|
| 401 |
+
yield from run_until(r, lambda h: h.is_chunking)
|
| 402 |
+
saw_chunking = False
|
| 403 |
+
for _ in range(DEFAULT_MAX_STEPS):
|
| 404 |
+
chunked = s.chunked_req
|
| 405 |
+
if (
|
| 406 |
+
r.is_chunking
|
| 407 |
+
and chunked is not None
|
| 408 |
+
and chunked.rid == r.rid
|
| 409 |
+
and chunked.extend_range.length > 0
|
| 410 |
+
):
|
| 411 |
+
deduct = chunked.extend_range.length
|
| 412 |
+
base = s.load_inquirer._get_num_pending_tokens()
|
| 413 |
+
deducted = s.load_inquirer._get_num_pending_tokens(chunk_deduct=deduct)
|
| 414 |
+
assert deducted == base - deduct, (
|
| 415 |
+
f"chunk_deduct must subtract the planned chunk exactly: "
|
| 416 |
+
f"base={base}, deducted={deducted}, expected={base - deduct}"
|
| 417 |
+
)
|
| 418 |
+
saw_chunking = True
|
| 419 |
+
if r.finished:
|
| 420 |
+
break
|
| 421 |
+
yield
|
| 422 |
+
assert r.finished
|
| 423 |
+
assert saw_chunking, "test must observe the chunked req with a planned chunk"
|
| 424 |
+
|
| 425 |
+
def test_stage_a_inflight_middle_chunks_sync_invariant(self):
|
| 426 |
+
self.server.execute_script(
|
| 427 |
+
self._script_stage_a_inflight_middle_chunks_sync_invariant
|
| 428 |
+
)
|
| 429 |
+
|
| 430 |
+
@staticmethod
|
| 431 |
+
def _script_stage_a_inflight_middle_chunks_sync_invariant(t: ScriptedContext):
|
| 432 |
+
def assert_invariant() -> None:
|
| 433 |
+
req = t.find_req_by_rid(r.rid)
|
| 434 |
+
if req is not None and req.inflight_middle_chunks > 0:
|
| 435 |
+
assert r.is_chunking, (
|
| 436 |
+
f"invariant violated: inflight_middle_chunks="
|
| 437 |
+
f"{req.inflight_middle_chunks} but is_chunking={r.is_chunking}"
|
| 438 |
+
)
|
| 439 |
+
|
| 440 |
+
r = t.start_req(
|
| 441 |
+
prompt_len=VERY_LONG_PROMPT_LEN, max_new_tokens=4, prompt_token=220
|
| 442 |
+
)
|
| 443 |
+
yield from run_until(r, lambda h: h.is_chunking and h.chunks_done >= 1)
|
| 444 |
+
assert_invariant()
|
| 445 |
+
|
| 446 |
+
t.pause_generation(mode="retract")
|
| 447 |
+
yield
|
| 448 |
+
assert_invariant()
|
| 449 |
+
|
| 450 |
+
t.continue_generation()
|
| 451 |
+
for _ in range(DEFAULT_MAX_STEPS):
|
| 452 |
+
assert_invariant()
|
| 453 |
+
if r.finished:
|
| 454 |
+
return
|
| 455 |
+
yield
|
| 456 |
+
raise AssertionError("req did not finish")
|
| 457 |
+
|
| 458 |
+
def test_init_next_round_input_resets_chunk_state(self):
|
| 459 |
+
self.server.execute_script(
|
| 460 |
+
self._script_init_next_round_input_resets_chunk_state
|
| 461 |
+
)
|
| 462 |
+
|
| 463 |
+
@staticmethod
|
| 464 |
+
def _script_init_next_round_input_resets_chunk_state(t: ScriptedContext):
|
| 465 |
+
r = t.start_req(
|
| 466 |
+
prompt_len=3 * DEFAULT_CHUNK_SIZE, max_new_tokens=2, prompt_token=230
|
| 467 |
+
)
|
| 468 |
+
yield from run_until(r, lambda h: h.chunks_done >= 1 and h.is_chunking)
|
| 469 |
+
saw_mid_chunk = False
|
| 470 |
+
for _ in range(DEFAULT_MAX_STEPS):
|
| 471 |
+
req = r.req
|
| 472 |
+
if (
|
| 473 |
+
r.is_chunking
|
| 474 |
+
and r.chunks_done >= 1
|
| 475 |
+
and req is not None
|
| 476 |
+
and req.extend_range is not None
|
| 477 |
+
):
|
| 478 |
+
saw_mid_chunk = True
|
| 479 |
+
assert (
|
| 480 |
+
req.extend_range.end
|
| 481 |
+
== len(req.prefix_indices) + req.extend_range.length
|
| 482 |
+
), (
|
| 483 |
+
f"init_next_round_input must rebuild fill_ids to the committed "
|
| 484 |
+
f"prefix plus the in-flight chunk; "
|
| 485 |
+
f"fill_ids_len={req.extend_range.end}, "
|
| 486 |
+
f"prefix_indices_len={len(req.prefix_indices)}, "
|
| 487 |
+
f"extend_input_len={req.extend_range.length}, "
|
| 488 |
+
f"chunks_done={r.chunks_done}"
|
| 489 |
+
)
|
| 490 |
+
if r.finished:
|
| 491 |
+
break
|
| 492 |
+
yield
|
| 493 |
+
assert r.finished
|
| 494 |
+
assert (
|
| 495 |
+
saw_mid_chunk
|
| 496 |
+
), "test must observe the fill_ids reset boundary at least once"
|
| 497 |
+
assert r.finished
|
| 498 |
+
|
| 499 |
+
def test_chunked_req_slot_cleared_when_chunk_completes(self):
|
| 500 |
+
self.server.execute_script(
|
| 501 |
+
self._script_chunked_req_slot_cleared_when_chunk_completes
|
| 502 |
+
)
|
| 503 |
+
|
| 504 |
+
@staticmethod
|
| 505 |
+
def _script_chunked_req_slot_cleared_when_chunk_completes(t: ScriptedContext):
|
| 506 |
+
s = t.scheduler
|
| 507 |
+
r = t.start_req(
|
| 508 |
+
prompt_len=2 * DEFAULT_CHUNK_SIZE, max_new_tokens=2, prompt_token=240
|
| 509 |
+
)
|
| 510 |
+
saw_chunking = False
|
| 511 |
+
for _ in range(DEFAULT_MAX_STEPS):
|
| 512 |
+
if r.is_chunking:
|
| 513 |
+
saw_chunking = True
|
| 514 |
+
if r.finished:
|
| 515 |
+
break
|
| 516 |
+
yield
|
| 517 |
+
assert r.finished
|
| 518 |
+
assert saw_chunking, "req should have occupied the chunked_req slot mid-chunk"
|
| 519 |
+
assert (
|
| 520 |
+
s.chunked_req is None
|
| 521 |
+
), f"chunked_req slot must clear after last chunk; got {s.chunked_req!r}"
|
| 522 |
+
|
| 523 |
+
def test_second_chunked_admit_blocked_when_chunked_req_set(self):
|
| 524 |
+
self.server.execute_script(
|
| 525 |
+
self._script_second_chunked_admit_blocked_when_chunked_req_set
|
| 526 |
+
)
|
| 527 |
+
|
| 528 |
+
@staticmethod
|
| 529 |
+
def _script_second_chunked_admit_blocked_when_chunked_req_set(t: ScriptedContext):
|
| 530 |
+
r1 = t.start_req(
|
| 531 |
+
prompt_len=VERY_LONG_PROMPT_LEN, max_new_tokens=2, prompt_token=10
|
| 532 |
+
)
|
| 533 |
+
r2 = t.start_req(
|
| 534 |
+
prompt_len=VERY_LONG_PROMPT_LEN, max_new_tokens=2, prompt_token=11
|
| 535 |
+
)
|
| 536 |
+
saw_r1_chunking = False
|
| 537 |
+
saw_r2_chunking = False
|
| 538 |
+
for _ in range(DEFAULT_MAX_STEPS * 2):
|
| 539 |
+
both = r1.is_chunking and r2.is_chunking
|
| 540 |
+
assert not both, (
|
| 541 |
+
f"only one chunked-resume slot allowed; r1.is_chunking="
|
| 542 |
+
f"{r1.is_chunking}, r2.is_chunking={r2.is_chunking}"
|
| 543 |
+
)
|
| 544 |
+
if r1.is_chunking:
|
| 545 |
+
saw_r1_chunking = True
|
| 546 |
+
if r2.is_chunking:
|
| 547 |
+
saw_r2_chunking = True
|
| 548 |
+
if r1.finished and r2.finished:
|
| 549 |
+
break
|
| 550 |
+
yield
|
| 551 |
+
assert r1.finished and r2.finished
|
| 552 |
+
assert saw_r1_chunking and saw_r2_chunking, (
|
| 553 |
+
f"both reqs should chunk over their lifetime; saw_r1="
|
| 554 |
+
f"{saw_r1_chunking}, saw_r2={saw_r2_chunking}"
|
| 555 |
+
)
|
| 556 |
+
|
| 557 |
+
def test_scheduler_continues_with_only_chunked_req_no_waiting(self):
|
| 558 |
+
self.server.execute_script(
|
| 559 |
+
self._script_scheduler_continues_with_only_chunked_req_no_waiting
|
| 560 |
+
)
|
| 561 |
+
|
| 562 |
+
@staticmethod
|
| 563 |
+
def _script_scheduler_continues_with_only_chunked_req_no_waiting(
|
| 564 |
+
t: ScriptedContext,
|
| 565 |
+
):
|
| 566 |
+
r = t.start_req(
|
| 567 |
+
prompt_len=VERY_LONG_PROMPT_LEN, max_new_tokens=2, prompt_token=250
|
| 568 |
+
)
|
| 569 |
+
yield from run_until(r, lambda h: h.is_chunking)
|
| 570 |
+
prev_chunks_done = r.chunks_done
|
| 571 |
+
progressed = False
|
| 572 |
+
for _ in range(DEFAULT_MAX_STEPS):
|
| 573 |
+
if r.is_chunking:
|
| 574 |
+
assert (
|
| 575 |
+
not t.is_idle
|
| 576 |
+
), "scheduler must not go idle while a chunked req is in flight"
|
| 577 |
+
cur_chunks_done = r.chunks_done
|
| 578 |
+
if cur_chunks_done > prev_chunks_done:
|
| 579 |
+
progressed = True
|
| 580 |
+
prev_chunks_done = cur_chunks_done
|
| 581 |
+
if r.finished:
|
| 582 |
+
break
|
| 583 |
+
yield
|
| 584 |
+
assert r.finished
|
| 585 |
+
assert progressed, (
|
| 586 |
+
"chunks_done must keep advancing without any waiter; pre-fix "
|
| 587 |
+
"an empty waiting_queue could cause the loop to skip continuation"
|
| 588 |
+
)
|
| 589 |
+
|
| 590 |
+
|
| 591 |
+
class TestSpecialCaseRowPoolExhaustion(ScriptedTestCase):
|
| 592 |
+
ENGINE_KWARGS = base_engine_kwargs(
|
| 593 |
+
chunked_prefill_size=DEFAULT_CHUNK_SIZE,
|
| 594 |
+
max_running_requests=8,
|
| 595 |
+
)
|
| 596 |
+
|
| 597 |
+
def test_chunked_req_bypasses_req_pool_exhaustion(self):
|
| 598 |
+
self.server.execute_script(
|
| 599 |
+
self._script_chunked_req_bypasses_req_pool_exhaustion
|
| 600 |
+
)
|
| 601 |
+
|
| 602 |
+
@staticmethod
|
| 603 |
+
def _script_chunked_req_bypasses_req_pool_exhaustion(t: ScriptedContext):
|
| 604 |
+
r = t.start_req(prompt_len=VERY_LONG_PROMPT_LEN, max_new_tokens=2)
|
| 605 |
+
yield from run_until(r, lambda h: h.is_chunking)
|
| 606 |
+
chunks_before_pressure = r.chunks_done
|
| 607 |
+
|
| 608 |
+
yield from exhaust_row_pool(t, leave_rows=0)
|
| 609 |
+
|
| 610 |
+
progressed_under_pressure = False
|
| 611 |
+
for _ in range(DEFAULT_MAX_STEPS * 2):
|
| 612 |
+
if r.chunks_done > chunks_before_pressure:
|
| 613 |
+
progressed_under_pressure = True
|
| 614 |
+
if r.finished:
|
| 615 |
+
break
|
| 616 |
+
yield
|
| 617 |
+
assert r.finished
|
| 618 |
+
assert progressed_under_pressure, (
|
| 619 |
+
"chunked req must advance even when get_num_allocatable_reqs "
|
| 620 |
+
"returns 0; pre-fix the bypass would block forever"
|
| 621 |
+
)
|
| 622 |
+
assert r.kv_pages == 0
|
| 623 |
+
|
| 624 |
+
|
| 625 |
+
class TestSpecialCaseMixedChunk(ScriptedTestCase):
|
| 626 |
+
ENGINE_KWARGS = base_engine_kwargs(
|
| 627 |
+
chunked_prefill_size=DEFAULT_CHUNK_SIZE,
|
| 628 |
+
enable_mixed_chunk=True,
|
| 629 |
+
)
|
| 630 |
+
|
| 631 |
+
def test_mix_with_running_chunked_plus_decode(self):
|
| 632 |
+
self.server.execute_script(self._script_mix_with_running_chunked_plus_decode)
|
| 633 |
+
|
| 634 |
+
@staticmethod
|
| 635 |
+
def _script_mix_with_running_chunked_plus_decode(t: ScriptedContext):
|
| 636 |
+
decodes = [t.start_req(prompt_len=8, max_new_tokens=16) for _ in range(3)]
|
| 637 |
+
for d in decodes:
|
| 638 |
+
yield from advance_to_decode_step(d, 1)
|
| 639 |
+
|
| 640 |
+
r_chunk = t.start_req(
|
| 641 |
+
prompt_len=VERY_LONG_PROMPT_LEN, max_new_tokens=4, prompt_token=300
|
| 642 |
+
)
|
| 643 |
+
yield from run_until(r_chunk, lambda h: h.is_chunking)
|
| 644 |
+
|
| 645 |
+
comp = t.batch_composition()
|
| 646 |
+
assert r_chunk.rid in comp.get("chunked", [])
|
| 647 |
+
|
| 648 |
+
saw_mixed_with_decode = False
|
| 649 |
+
all_reqs = [r_chunk, *decodes]
|
| 650 |
+
for _ in range(DEFAULT_MAX_STEPS * 2):
|
| 651 |
+
comp = t.batch_composition()
|
| 652 |
+
batch_rids = (
|
| 653 |
+
set(comp.get("prefill", []))
|
| 654 |
+
| set(comp.get("decode", []))
|
| 655 |
+
| set(comp.get("running", []))
|
| 656 |
+
)
|
| 657 |
+
if (
|
| 658 |
+
t.last_batch_forward_mode == "MIXED"
|
| 659 |
+
and r_chunk.rid in comp.get("chunked", [])
|
| 660 |
+
and any(d.rid in batch_rids for d in decodes)
|
| 661 |
+
):
|
| 662 |
+
saw_mixed_with_decode = True
|
| 663 |
+
if all(x.finished for x in all_reqs):
|
| 664 |
+
break
|
| 665 |
+
yield
|
| 666 |
+
assert all(x.finished for x in all_reqs)
|
| 667 |
+
assert saw_mixed_with_decode, (
|
| 668 |
+
"enable_mixed_chunk should merge running decode reqs into the chunked "
|
| 669 |
+
"prefill iter (MIXED forward_mode) at least once"
|
| 670 |
+
)
|
| 671 |
+
|
| 672 |
+
def test_mixed_chunk_with_logprob_falls_back(self):
|
| 673 |
+
self.server.execute_script(self._script_mixed_chunk_with_logprob_falls_back)
|
| 674 |
+
|
| 675 |
+
@staticmethod
|
| 676 |
+
def _script_mixed_chunk_with_logprob_falls_back(t: ScriptedContext):
|
| 677 |
+
r = t.start_req(
|
| 678 |
+
prompt_len=VERY_LONG_PROMPT_LEN,
|
| 679 |
+
max_new_tokens=2,
|
| 680 |
+
return_logprob=True,
|
| 681 |
+
prompt_token=310,
|
| 682 |
+
)
|
| 683 |
+
yield from run_until(r, lambda h: h.is_chunking)
|
| 684 |
+
assert (
|
| 685 |
+
t.last_batch_forward_mode != "MIXED"
|
| 686 |
+
), f"return_logprob must disable mixed-chunk path; got {t.last_batch_forward_mode!r}"
|
| 687 |
+
yield from run_until_finished(r)
|
| 688 |
+
|
| 689 |
+
def test_mixed_chunk_with_running_batch(self):
|
| 690 |
+
self.server.execute_script(self._script_mixed_chunk_with_running_batch)
|
| 691 |
+
|
| 692 |
+
@staticmethod
|
| 693 |
+
def _script_mixed_chunk_with_running_batch(t: ScriptedContext):
|
| 694 |
+
r_dec = t.start_req(prompt_len=8, max_new_tokens=32)
|
| 695 |
+
yield from run_until(r_dec, lambda h: h.status == "running")
|
| 696 |
+
|
| 697 |
+
r_chunk = t.start_req(
|
| 698 |
+
prompt_len=VERY_LONG_PROMPT_LEN, max_new_tokens=2, prompt_token=320
|
| 699 |
+
)
|
| 700 |
+
yield
|
| 701 |
+
yield from run_until(r_chunk, lambda h: h.is_chunking)
|
| 702 |
+
|
| 703 |
+
assert (
|
| 704 |
+
t.last_batch_forward_mode == "MIXED"
|
| 705 |
+
), f"chunked admission with running batch must enter MIXED; got {t.last_batch_forward_mode!r}"
|
| 706 |
+
for _ in range(DEFAULT_MAX_STEPS * 2):
|
| 707 |
+
if r_chunk.finished and r_dec.finished:
|
| 708 |
+
break
|
| 709 |
+
yield
|
| 710 |
+
assert r_chunk.finished and r_dec.finished
|
| 711 |
+
|
| 712 |
+
|
| 713 |
+
class TestSpecialCaseTransformers(ScriptedTestCase):
|
| 714 |
+
ENGINE_KWARGS = base_engine_kwargs(
|
| 715 |
+
chunked_prefill_size=DEFAULT_CHUNK_SIZE,
|
| 716 |
+
model_impl="transformers",
|
| 717 |
+
)
|
| 718 |
+
|
| 719 |
+
def test_transformers_text_model_still_chunks(self):
|
| 720 |
+
self.server.execute_script(self._script_transformers_text_model_still_chunks)
|
| 721 |
+
|
| 722 |
+
@staticmethod
|
| 723 |
+
def _script_transformers_text_model_still_chunks(t: ScriptedContext):
|
| 724 |
+
r = t.start_req(
|
| 725 |
+
prompt_len=VERY_LONG_PROMPT_LEN, max_new_tokens=2, prompt_token=10
|
| 726 |
+
)
|
| 727 |
+
yield from run_until_finished(r)
|
| 728 |
+
assert r.finished
|
| 729 |
+
expected = _expected_chunks(VERY_LONG_PROMPT_LEN, DEFAULT_CHUNK_SIZE)
|
| 730 |
+
assert r.chunks_done == expected, (
|
| 731 |
+
f"a text model on the Transformers backend must chunk like the native "
|
| 732 |
+
f"backend ({expected} chunks); got chunks_done={r.chunks_done}"
|
| 733 |
+
)
|
| 734 |
+
|
| 735 |
+
|
| 736 |
+
class TestSpecialCaseNoChunking(ScriptedTestCase):
|
| 737 |
+
ENGINE_KWARGS = base_engine_kwargs(chunked_prefill_size=-1)
|
| 738 |
+
|
| 739 |
+
def test_chunk_size_negative_disables_chunking(self):
|
| 740 |
+
self.server.execute_script(self._script_chunk_size_negative_disables_chunking)
|
| 741 |
+
|
| 742 |
+
@staticmethod
|
| 743 |
+
def _script_chunk_size_negative_disables_chunking(t: ScriptedContext):
|
| 744 |
+
r = t.start_req(prompt_len=VERY_LONG_PROMPT_LEN, max_new_tokens=2)
|
| 745 |
+
for _ in range(DEFAULT_MAX_STEPS):
|
| 746 |
+
assert (
|
| 747 |
+
not r.is_chunking
|
| 748 |
+
), "chunked_prefill_size=-1 should disable chunked path"
|
| 749 |
+
if r.finished:
|
| 750 |
+
return
|
| 751 |
+
yield
|
| 752 |
+
raise AssertionError("req did not finish under disabled chunking")
|
| 753 |
+
|
| 754 |
+
|
| 755 |
+
DETERMINISTIC_ALIGN_SIZE = 4096
|
| 756 |
+
|
| 757 |
+
|
| 758 |
+
class TestSpecialCaseDeterministicFlashInfer(ScriptedTestCase):
|
| 759 |
+
ENGINE_KWARGS = base_engine_kwargs(
|
| 760 |
+
chunked_prefill_size=DETERMINISTIC_ALIGN_SIZE,
|
| 761 |
+
page_size=16,
|
| 762 |
+
attention_backend="flashinfer",
|
| 763 |
+
enable_deterministic_inference=True,
|
| 764 |
+
kv_canary="none",
|
| 765 |
+
kv_canary_sweep_interval=0,
|
| 766 |
+
)
|
| 767 |
+
|
| 768 |
+
def test_chunked_truncation_align_size(self):
|
| 769 |
+
self.server.execute_script(self._script_chunked_truncation_align_size)
|
| 770 |
+
|
| 771 |
+
@staticmethod
|
| 772 |
+
def _script_chunked_truncation_align_size(t: ScriptedContext):
|
| 773 |
+
r = t.start_req(
|
| 774 |
+
prompt_len=DETERMINISTIC_ALIGN_SIZE + 1024,
|
| 775 |
+
max_new_tokens=2,
|
| 776 |
+
prompt_token=10,
|
| 777 |
+
)
|
| 778 |
+
page_size = 16
|
| 779 |
+
saw_chunking = False
|
| 780 |
+
for _ in range(DEFAULT_MAX_STEPS):
|
| 781 |
+
if r.is_chunking and r.req.extend_range is not None:
|
| 782 |
+
saw_chunking = True
|
| 783 |
+
assert r.req.extend_range.length % page_size == 0, (
|
| 784 |
+
f"deterministic chunk boundary must be page-aligned; "
|
| 785 |
+
f"got extend_input_len={r.req.extend_range.length}, page_size={page_size}"
|
| 786 |
+
)
|
| 787 |
+
if r.finished:
|
| 788 |
+
break
|
| 789 |
+
yield
|
| 790 |
+
assert r.finished, "chunked req did not finish"
|
| 791 |
+
assert saw_chunking, "test must observe the req mid-chunk at least once"
|
| 792 |
+
|
| 793 |
+
|
| 794 |
+
class TestSpecialCaseHiCache(ScriptedTestCase):
|
| 795 |
+
ENGINE_KWARGS = base_engine_kwargs(
|
| 796 |
+
chunked_prefill_size=DEFAULT_CHUNK_SIZE,
|
| 797 |
+
enable_hierarchical_cache=True,
|
| 798 |
+
kv_canary="none",
|
| 799 |
+
kv_canary_sweep_interval=0,
|
| 800 |
+
)
|
| 801 |
+
|
| 802 |
+
def test_hicache_breakdown_only_first_chunk(self):
|
| 803 |
+
self.server.execute_script(self._script_hicache_breakdown_only_first_chunk)
|
| 804 |
+
|
| 805 |
+
@staticmethod
|
| 806 |
+
def _script_hicache_breakdown_only_first_chunk(t: ScriptedContext):
|
| 807 |
+
r = t.start_req(
|
| 808 |
+
prompt_len=VERY_LONG_PROMPT_LEN, max_new_tokens=2, prompt_token=400
|
| 809 |
+
)
|
| 810 |
+
first_chunk_snap = None
|
| 811 |
+
saw_chunking = False
|
| 812 |
+
for _ in range(DEFAULT_MAX_STEPS):
|
| 813 |
+
if r.is_chunking:
|
| 814 |
+
saw_chunking = True
|
| 815 |
+
if r.is_chunking and r.chunks_done >= 1 and first_chunk_snap is None:
|
| 816 |
+
first_chunk_snap = r.req.cached_tokens
|
| 817 |
+
if first_chunk_snap is not None and r.is_chunking:
|
| 818 |
+
cur = r.req.cached_tokens
|
| 819 |
+
assert cur == first_chunk_snap, (
|
| 820 |
+
f"HiCache cached_tokens_* must freeze after first chunk; "
|
| 821 |
+
f"first={first_chunk_snap!r}, now={cur!r}"
|
| 822 |
+
)
|
| 823 |
+
if r.finished:
|
| 824 |
+
break
|
| 825 |
+
yield
|
| 826 |
+
assert r.finished
|
| 827 |
+
assert saw_chunking, "test must observe r mid-chunk at least once"
|
| 828 |
+
assert (
|
| 829 |
+
first_chunk_snap is not None
|
| 830 |
+
), "test must snapshot cached_tokens at the first chunk boundary"
|
| 831 |
+
|
| 832 |
+
def test_hicache_cached_tokens_set_once_invariant(self):
|
| 833 |
+
self.server.execute_script(
|
| 834 |
+
self._script_hicache_cached_tokens_set_once_invariant
|
| 835 |
+
)
|
| 836 |
+
|
| 837 |
+
@staticmethod
|
| 838 |
+
def _script_hicache_cached_tokens_set_once_invariant(t: ScriptedContext):
|
| 839 |
+
r = t.start_req(
|
| 840 |
+
prompt_len=VERY_LONG_PROMPT_LEN, max_new_tokens=2, prompt_token=410
|
| 841 |
+
)
|
| 842 |
+
snap: Optional[tuple] = None
|
| 843 |
+
saw_chunking = False
|
| 844 |
+
for _ in range(DEFAULT_MAX_STEPS):
|
| 845 |
+
req = t.find_req_by_rid(r.rid)
|
| 846 |
+
if req is not None and r.is_chunking and r.chunks_done >= 1:
|
| 847 |
+
saw_chunking = True
|
| 848 |
+
cur = (
|
| 849 |
+
req.cached_tokens_device,
|
| 850 |
+
req.cached_tokens_host,
|
| 851 |
+
req.cached_tokens_storage,
|
| 852 |
+
)
|
| 853 |
+
if snap is None:
|
| 854 |
+
snap = cur
|
| 855 |
+
else:
|
| 856 |
+
assert cur == snap, (
|
| 857 |
+
f"HiCache cached_tokens_* fields must be set exactly "
|
| 858 |
+
f"once on first chunk; values changed: snap={snap}, "
|
| 859 |
+
f"cur={cur}"
|
| 860 |
+
)
|
| 861 |
+
if r.finished:
|
| 862 |
+
break
|
| 863 |
+
yield
|
| 864 |
+
assert r.finished
|
| 865 |
+
assert (
|
| 866 |
+
saw_chunking
|
| 867 |
+
), "test must observe the req mid-chunk (chunks_done >= 1) at least once"
|
| 868 |
+
assert snap is not None, "test must snapshot the cached_tokens_* breakdown"
|
| 869 |
+
|
| 870 |
+
|
| 871 |
+
def _expected_chunks(prompt_len: int, chunk_size: int) -> int:
|
| 872 |
+
if prompt_len <= chunk_size:
|
| 873 |
+
return 0
|
| 874 |
+
return (prompt_len + chunk_size - 1) // chunk_size
|
| 875 |
+
|
| 876 |
+
|
| 877 |
+
class TestSpecialCaseDynamicChunkingPP1(ScriptedTestCase):
|
| 878 |
+
ENGINE_KWARGS = base_engine_kwargs(
|
| 879 |
+
chunked_prefill_size=DEFAULT_CHUNK_SIZE,
|
| 880 |
+
enable_dynamic_chunking=True,
|
| 881 |
+
)
|
| 882 |
+
|
| 883 |
+
def test_dynamic_chunking_forced_off_on_pp1(self):
|
| 884 |
+
self.server.execute_script(self._script_dynamic_chunking_forced_off_on_pp1)
|
| 885 |
+
|
| 886 |
+
@staticmethod
|
| 887 |
+
def _script_dynamic_chunking_forced_off_on_pp1(t: ScriptedContext):
|
| 888 |
+
assert t.scheduler.enable_dynamic_chunking is False, (
|
| 889 |
+
"pp_size==1 must force enable_dynamic_chunking off even when the "
|
| 890 |
+
"server arg is True (the 'and ps.pp_size > 1' conjunct)"
|
| 891 |
+
)
|
| 892 |
+
r = t.start_req(
|
| 893 |
+
prompt_len=VERY_LONG_PROMPT_LEN, max_new_tokens=2, prompt_token=10
|
| 894 |
+
)
|
| 895 |
+
yield from run_until_finished(r)
|
| 896 |
+
assert r.finished
|
| 897 |
+
expected = _expected_chunks(VERY_LONG_PROMPT_LEN, DEFAULT_CHUNK_SIZE)
|
| 898 |
+
assert r.chunks_done == expected, (
|
| 899 |
+
f"uniform chunked_prefill_size must yield exactly {expected} chunks "
|
| 900 |
+
f"(no dynamic-size prediction on pp1); got {r.chunks_done}"
|
| 901 |
+
)
|
| 902 |
+
|
| 903 |
+
|
| 904 |
+
class TestSpecialCaseSmallPool(ScriptedTestCase):
|
| 905 |
+
ENGINE_KWARGS = base_engine_kwargs(
|
| 906 |
+
chunked_prefill_size=DEFAULT_CHUNK_SIZE,
|
| 907 |
+
max_total_tokens=SMALL_KV_POOL_MAX_TOTAL_TOKENS,
|
| 908 |
+
)
|
| 909 |
+
|
| 910 |
+
@staticmethod
|
| 911 |
+
def _start_ballast(t: ScriptedContext, *, prompt_token: int):
|
| 912 |
+
return t.start_req(
|
| 913 |
+
prompt_len=SMALL_KV_POOL_BALLAST_PROMPT_LEN,
|
| 914 |
+
max_new_tokens=SMALL_KV_POOL_BALLAST_MAX_NEW_TOKENS,
|
| 915 |
+
ignore_eos=True,
|
| 916 |
+
prompt_token=prompt_token,
|
| 917 |
+
)
|
| 918 |
+
|
| 919 |
+
@staticmethod
|
| 920 |
+
def _run_force_readd_then_complete(
|
| 921 |
+
t: ScriptedContext, *, chunk_token: int, ballast_token: int
|
| 922 |
+
):
|
| 923 |
+
r = t.start_req(
|
| 924 |
+
prompt_len=VERY_LONG_PROMPT_LEN, max_new_tokens=2, prompt_token=chunk_token
|
| 925 |
+
)
|
| 926 |
+
yield from run_until(r, lambda h: h.is_chunking and h.chunks_done >= 1)
|
| 927 |
+
|
| 928 |
+
ballast = TestSpecialCaseSmallPool._start_ballast(t, prompt_token=ballast_token)
|
| 929 |
+
|
| 930 |
+
ballast_retracted = False
|
| 931 |
+
for _ in range(2000):
|
| 932 |
+
if ballast.status == "waiting":
|
| 933 |
+
ballast_retracted = True
|
| 934 |
+
if r.finished:
|
| 935 |
+
break
|
| 936 |
+
yield
|
| 937 |
+
assert r.finished, (
|
| 938 |
+
"force-re-added chunked resume must complete once the engine retracts "
|
| 939 |
+
f"the ballast; status={r.status} kv_pages={r.kv_pages}"
|
| 940 |
+
)
|
| 941 |
+
assert r.kv_pages == 0, f"kv_pages={r.kv_pages}"
|
| 942 |
+
assert r.lock_refs == 0, f"lock_refs={r.lock_refs}"
|
| 943 |
+
assert (
|
| 944 |
+
ballast_retracted
|
| 945 |
+
or ballast.finished
|
| 946 |
+
or ballast.status in ("waiting", "finished", "unknown")
|
| 947 |
+
), f"ballast must be retracted/aborted under pressure; status={ballast.status}"
|
| 948 |
+
|
| 949 |
+
t.abort(ballast)
|
| 950 |
+
for _ in range(200):
|
| 951 |
+
if t.is_fully_idle:
|
| 952 |
+
break
|
| 953 |
+
yield
|
| 954 |
+
|
| 955 |
+
def test_add_chunked_req_rem_nonpositive_forces_rem_chunk_tokens(self):
|
| 956 |
+
self.server.execute_script(
|
| 957 |
+
self._script_add_chunked_req_rem_nonpositive_forces_rem_chunk_tokens
|
| 958 |
+
)
|
| 959 |
+
|
| 960 |
+
@staticmethod
|
| 961 |
+
def _script_add_chunked_req_rem_nonpositive_forces_rem_chunk_tokens(
|
| 962 |
+
t: ScriptedContext,
|
| 963 |
+
):
|
| 964 |
+
yield from TestSpecialCaseSmallPool._run_force_readd_then_complete(
|
| 965 |
+
t, chunk_token=700, ballast_token=701
|
| 966 |
+
)
|
| 967 |
+
|
| 968 |
+
def test_chunked_forced_admission_avoids_leak(self):
|
| 969 |
+
self.server.execute_script(self._script_chunked_forced_admission_avoids_leak)
|
| 970 |
+
|
| 971 |
+
@staticmethod
|
| 972 |
+
def _script_chunked_forced_admission_avoids_leak(t: ScriptedContext):
|
| 973 |
+
yield from TestSpecialCaseSmallPool._run_force_readd_then_complete(
|
| 974 |
+
t, chunk_token=710, ballast_token=711
|
| 975 |
+
)
|
| 976 |
+
|
| 977 |
+
def test_add_chunked_req_non_swa_forced_admit_on_rem_zero(self):
|
| 978 |
+
self.server.execute_script(
|
| 979 |
+
self._script_add_chunked_req_non_swa_forced_admit_on_rem_zero
|
| 980 |
+
)
|
| 981 |
+
|
| 982 |
+
@staticmethod
|
| 983 |
+
def _script_add_chunked_req_non_swa_forced_admit_on_rem_zero(t: ScriptedContext):
|
| 984 |
+
yield from TestSpecialCaseSmallPool._run_force_readd_then_complete(
|
| 985 |
+
t, chunk_token=720, ballast_token=721
|
| 986 |
+
)
|
| 987 |
+
|
| 988 |
+
|
| 989 |
+
class TestSpecialCaseRetractMerge(ScriptedTestCase):
|
| 990 |
+
ENGINE_KWARGS = base_engine_kwargs(chunked_prefill_size=DEFAULT_CHUNK_SIZE)
|
| 991 |
+
|
| 992 |
+
def test_retract_merges_extend_chunk_batch_before_retract_all(self):
|
| 993 |
+
self.server.execute_script(
|
| 994 |
+
self._script_retract_merges_extend_chunk_batch_before_retract_all
|
| 995 |
+
)
|
| 996 |
+
|
| 997 |
+
@staticmethod
|
| 998 |
+
def _script_retract_merges_extend_chunk_batch_before_retract_all(
|
| 999 |
+
t: ScriptedContext,
|
| 1000 |
+
):
|
| 1001 |
+
s = t.scheduler
|
| 1002 |
+
r = t.start_req(prompt_len=VERY_LONG_PROMPT_LEN, max_new_tokens=2)
|
| 1003 |
+
yield from run_until(r, lambda h: h.is_chunking)
|
| 1004 |
+
|
| 1005 |
+
assert s.last_batch is not None, "last_batch must be set while chunking"
|
| 1006 |
+
assert s.last_batch.forward_mode.is_extend(), (
|
| 1007 |
+
f"last_batch must be the extend/chunk batch; got "
|
| 1008 |
+
f"{s.last_batch.forward_mode!r}"
|
| 1009 |
+
)
|
| 1010 |
+
|
| 1011 |
+
t.pause_generation(mode="retract")
|
| 1012 |
+
yield
|
| 1013 |
+
|
| 1014 |
+
assert (
|
| 1015 |
+
s.last_batch is None
|
| 1016 |
+
), "retract must clear last_batch after merging the extend chunk batch"
|
| 1017 |
+
assert len(s.running_batch.reqs) == 0, (
|
| 1018 |
+
"the merged extend chunk batch must be retracted out of running_batch, "
|
| 1019 |
+
f"not stranded; got {len(s.running_batch.reqs)} reqs"
|
| 1020 |
+
)
|
| 1021 |
+
assert (
|
| 1022 |
+
r.status == "waiting"
|
| 1023 |
+
), f"retracted chunked req must return to the waiting queue; got {r.status!r}"
|
| 1024 |
+
assert r.kv_pages == 0
|
| 1025 |
+
|
| 1026 |
+
t.continue_generation()
|
| 1027 |
+
yield from run_until_finished(r)
|
| 1028 |
+
assert r.finished
|
| 1029 |
+
assert len(r.req.output_ids) == 2, (
|
| 1030 |
+
f"resumed req must emit exactly max_new_tokens; got "
|
| 1031 |
+
f"{len(r.req.output_ids)}"
|
| 1032 |
+
)
|
| 1033 |
+
|
| 1034 |
+
|
| 1035 |
+
class TestSpecialCaseChunkBudgetDefer(ScriptedTestCase):
|
| 1036 |
+
ENGINE_KWARGS = base_engine_kwargs(chunked_prefill_size=DEFAULT_CHUNK_SIZE)
|
| 1037 |
+
|
| 1038 |
+
def test_co_submitted_waiter_deferred_when_chunk_budget_zero(self):
|
| 1039 |
+
self.server.execute_script(
|
| 1040 |
+
self._script_co_submitted_waiter_deferred_when_chunk_budget_zero
|
| 1041 |
+
)
|
| 1042 |
+
|
| 1043 |
+
@staticmethod
|
| 1044 |
+
def _script_co_submitted_waiter_deferred_when_chunk_budget_zero(
|
| 1045 |
+
t: ScriptedContext,
|
| 1046 |
+
):
|
| 1047 |
+
r_chunk = t.start_req(prompt_len=VERY_LONG_PROMPT_LEN, max_new_tokens=2)
|
| 1048 |
+
r_wait = t.start_req(prompt_len=DEFAULT_CHUNK_SIZE + 8, max_new_tokens=2)
|
| 1049 |
+
yield from run_until(r_chunk, lambda h: h.is_chunking)
|
| 1050 |
+
|
| 1051 |
+
saw_deferred = False
|
| 1052 |
+
for _ in range(DEFAULT_MAX_STEPS * 2):
|
| 1053 |
+
comp = t.batch_composition()
|
| 1054 |
+
chunk_active = r_chunk.rid in comp.get("chunked", [])
|
| 1055 |
+
wait_idle = (
|
| 1056 |
+
r_wait.status == "waiting"
|
| 1057 |
+
and r_wait.rid not in comp.get("chunked", [])
|
| 1058 |
+
and r_wait.rid not in comp.get("running", [])
|
| 1059 |
+
and r_wait.rid not in comp.get("decode", [])
|
| 1060 |
+
)
|
| 1061 |
+
if chunk_active and wait_idle:
|
| 1062 |
+
saw_deferred = True
|
| 1063 |
+
assert r_wait.kv_pages == 0, (
|
| 1064 |
+
f"deferred waiter (rem_chunk_tokens<=0 -> OTHER) must hold no KV; "
|
| 1065 |
+
f"got kv_pages={r_wait.kv_pages}"
|
| 1066 |
+
)
|
| 1067 |
+
if r_chunk.finished and r_wait.finished:
|
| 1068 |
+
break
|
| 1069 |
+
yield
|
| 1070 |
+
assert r_chunk.finished and r_wait.finished
|
| 1071 |
+
assert saw_deferred, (
|
| 1072 |
+
"second waiter must be deferred for >=1 iter while the chunk-token "
|
| 1073 |
+
"budget was driven to 0 by the in-flight chunked req"
|
| 1074 |
+
)
|
| 1075 |
+
|
| 1076 |
+
|
| 1077 |
+
class TestSpecialCaseIgnoreEosNoRadix(ScriptedTestCase):
|
| 1078 |
+
ENGINE_KWARGS = base_engine_kwargs(
|
| 1079 |
+
chunked_prefill_size=DEFAULT_CHUNK_SIZE,
|
| 1080 |
+
disable_radix_cache=True,
|
| 1081 |
+
kv_canary="none",
|
| 1082 |
+
kv_canary_sweep_interval=0,
|
| 1083 |
+
)
|
| 1084 |
+
|
| 1085 |
+
def test_ignore_eos_chunked_truncate_path(self):
|
| 1086 |
+
self.server.execute_script(self._script_ignore_eos_chunked_truncate_path)
|
| 1087 |
+
|
| 1088 |
+
@staticmethod
|
| 1089 |
+
def _script_ignore_eos_chunked_truncate_path(t: ScriptedContext):
|
| 1090 |
+
r = t.start_req(
|
| 1091 |
+
prompt_len=VERY_LONG_PROMPT_LEN, max_new_tokens=2, ignore_eos=True
|
| 1092 |
+
)
|
| 1093 |
+
yield from run_until(r, lambda h: h.is_chunking)
|
| 1094 |
+
yield from run_until_finished(r)
|
| 1095 |
+
assert r.finished
|
| 1096 |
+
expected = _expected_chunks(VERY_LONG_PROMPT_LEN, DEFAULT_CHUNK_SIZE)
|
| 1097 |
+
assert r.chunks_done == expected, (
|
| 1098 |
+
f"ignore_eos chunk-truncation path must carry the prompt as new_chunked_req "
|
| 1099 |
+
f"for {expected} chunks; got {r.chunks_done}"
|
| 1100 |
+
)
|
| 1101 |
+
|
| 1102 |
+
def test_ignore_eos_nonchunked_fits_chunk_budget(self):
|
| 1103 |
+
self.server.execute_script(self._script_ignore_eos_nonchunked_fits_chunk_budget)
|
| 1104 |
+
|
| 1105 |
+
@staticmethod
|
| 1106 |
+
def _script_ignore_eos_nonchunked_fits_chunk_budget(t: ScriptedContext):
|
| 1107 |
+
r = t.start_req(prompt_len=8, max_new_tokens=2, ignore_eos=True)
|
| 1108 |
+
for _ in range(DEFAULT_MAX_STEPS):
|
| 1109 |
+
assert not r.is_chunking, (
|
| 1110 |
+
"a prompt that fits the chunk budget must admit non-chunked via the "
|
| 1111 |
+
"ignore_eos path, never entering is_chunking"
|
| 1112 |
+
)
|
| 1113 |
+
if r.finished:
|
| 1114 |
+
break
|
| 1115 |
+
yield
|
| 1116 |
+
assert r.finished
|
| 1117 |
+
assert r.chunks_done == 0, (
|
| 1118 |
+
f"prompt fitting the chunk budget completes non-chunked; got "
|
| 1119 |
+
f"chunks_done={r.chunks_done}"
|
| 1120 |
+
)
|
| 1121 |
+
|
| 1122 |
+
def test_ignore_eos_second_long_waiter_deferred_on_chunk_budget_zero(self):
|
| 1123 |
+
self.server.execute_script(
|
| 1124 |
+
self._script_ignore_eos_second_long_waiter_deferred_on_chunk_budget_zero
|
| 1125 |
+
)
|
| 1126 |
+
|
| 1127 |
+
@staticmethod
|
| 1128 |
+
def _script_ignore_eos_second_long_waiter_deferred_on_chunk_budget_zero(
|
| 1129 |
+
t: ScriptedContext,
|
| 1130 |
+
):
|
| 1131 |
+
r1 = t.start_req(
|
| 1132 |
+
prompt_len=VERY_LONG_PROMPT_LEN, max_new_tokens=2, ignore_eos=True
|
| 1133 |
+
)
|
| 1134 |
+
r2 = t.start_req(
|
| 1135 |
+
prompt_len=VERY_LONG_PROMPT_LEN, max_new_tokens=2, ignore_eos=True
|
| 1136 |
+
)
|
| 1137 |
+
yield from run_until(r1, lambda h: h.is_chunking)
|
| 1138 |
+
|
| 1139 |
+
saw_deferred = False
|
| 1140 |
+
for _ in range(DEFAULT_MAX_STEPS * 2):
|
| 1141 |
+
comp = t.batch_composition()
|
| 1142 |
+
r1_active = r1.rid in comp.get("chunked", [])
|
| 1143 |
+
r2_idle = (
|
| 1144 |
+
r2.status == "waiting"
|
| 1145 |
+
and r2.rid not in comp.get("chunked", [])
|
| 1146 |
+
and r2.rid not in comp.get("running", [])
|
| 1147 |
+
and r2.rid not in comp.get("decode", [])
|
| 1148 |
+
)
|
| 1149 |
+
if r1_active and r2_idle:
|
| 1150 |
+
saw_deferred = True
|
| 1151 |
+
assert r2.kv_pages == 0, (
|
| 1152 |
+
f"deferred ignore_eos waiter must hold no KV; got "
|
| 1153 |
+
f"kv_pages={r2.kv_pages}"
|
| 1154 |
+
)
|
| 1155 |
+
if r1.finished and r2.finished:
|
| 1156 |
+
break
|
| 1157 |
+
yield
|
| 1158 |
+
assert r1.finished and r2.finished
|
| 1159 |
+
assert saw_deferred, (
|
| 1160 |
+
"second long ignore_eos waiter must be deferred for >=1 iter while the "
|
| 1161 |
+
"chunk-token budget was driven to 0 (nested rem_chunk_tokens<=0 OTHER)"
|
| 1162 |
+
)
|
| 1163 |
+
|
| 1164 |
+
|
| 1165 |
+
class TestSpecialCaseRetractedStain(ScriptedTestCase):
|
| 1166 |
+
ENGINE_KWARGS = base_engine_kwargs(chunked_prefill_size=DEFAULT_CHUNK_SIZE)
|
| 1167 |
+
|
| 1168 |
+
def test_retracted_stain_suppresses_cached_token_recount(self):
|
| 1169 |
+
self.server.execute_script(
|
| 1170 |
+
self._script_retracted_stain_suppresses_cached_token_recount
|
| 1171 |
+
)
|
| 1172 |
+
|
| 1173 |
+
@staticmethod
|
| 1174 |
+
def _script_retracted_stain_suppresses_cached_token_recount(t: ScriptedContext):
|
| 1175 |
+
r = t.start_req(prompt_len=2 * DEFAULT_CHUNK_SIZE, max_new_tokens=2)
|
| 1176 |
+
yield from run_until(r, lambda h: h.is_chunking and h.chunks_done >= 1)
|
| 1177 |
+
cached_before = r.req.cached_tokens
|
| 1178 |
+
|
| 1179 |
+
t.pause_generation(mode="retract")
|
| 1180 |
+
yield
|
| 1181 |
+
t.continue_generation()
|
| 1182 |
+
yield from run_until_finished(r, max_steps=2000)
|
| 1183 |
+
assert r.finished
|
| 1184 |
+
|
| 1185 |
+
req = r.req
|
| 1186 |
+
assert (
|
| 1187 |
+
req.retracted_stain is True
|
| 1188 |
+
), "retract must set retracted_stain so the cached-token recount is suppressed"
|
| 1189 |
+
assert req.cached_tokens == cached_before, (
|
| 1190 |
+
f"retracted_stain must suppress re-adding pre_len-already_computed on "
|
| 1191 |
+
f"resume; cached_tokens grew from {cached_before} to {req.cached_tokens}"
|
| 1192 |
+
)
|
| 1193 |
+
|
| 1194 |
+
|
| 1195 |
+
class TestSpecialCaseResultSkipRetracted(ScriptedTestCase):
|
| 1196 |
+
ENGINE_KWARGS = base_engine_kwargs(chunked_prefill_size=DEFAULT_CHUNK_SIZE)
|
| 1197 |
+
|
| 1198 |
+
def test_result_skip_retracted_emits_no_stray_token(self):
|
| 1199 |
+
self.server.execute_script(
|
| 1200 |
+
self._script_result_skip_retracted_emits_no_stray_token
|
| 1201 |
+
)
|
| 1202 |
+
|
| 1203 |
+
@staticmethod
|
| 1204 |
+
def _script_result_skip_retracted_emits_no_stray_token(t: ScriptedContext):
|
| 1205 |
+
r = t.start_req(
|
| 1206 |
+
prompt_len=VERY_LONG_PROMPT_LEN, max_new_tokens=2, ignore_eos=True
|
| 1207 |
+
)
|
| 1208 |
+
yield from run_until(r, lambda h: h.is_chunking)
|
| 1209 |
+
|
| 1210 |
+
t.pause_generation(mode="retract")
|
| 1211 |
+
yield
|
| 1212 |
+
t.continue_generation()
|
| 1213 |
+
yield from run_until_finished(r, max_steps=2000)
|
| 1214 |
+
assert r.finished
|
| 1215 |
+
assert len(r.req.output_ids) == 2, (
|
| 1216 |
+
f"the skipped retracted entry must not append a stray output token; "
|
| 1217 |
+
f"got output_ids len {len(r.req.output_ids)}"
|
| 1218 |
+
)
|
| 1219 |
+
|
| 1220 |
+
|
| 1221 |
+
class TestSpecialCaseMiddleChunkNoToken(ScriptedTestCase):
|
| 1222 |
+
ENGINE_KWARGS = base_engine_kwargs(chunked_prefill_size=DEFAULT_CHUNK_SIZE)
|
| 1223 |
+
|
| 1224 |
+
def test_middle_chunk_appends_no_token_no_finish(self):
|
| 1225 |
+
self.server.execute_script(self._script_middle_chunk_appends_no_token_no_finish)
|
| 1226 |
+
|
| 1227 |
+
@staticmethod
|
| 1228 |
+
def _script_middle_chunk_appends_no_token_no_finish(t: ScriptedContext):
|
| 1229 |
+
r = t.start_req(prompt_len=VERY_LONG_PROMPT_LEN, max_new_tokens=2)
|
| 1230 |
+
yield from run_until(r, lambda h: h.is_chunking)
|
| 1231 |
+
|
| 1232 |
+
saw_middle_chunk = False
|
| 1233 |
+
for _ in range(DEFAULT_MAX_STEPS * 2):
|
| 1234 |
+
if r.is_chunking:
|
| 1235 |
+
saw_middle_chunk = True
|
| 1236 |
+
assert len(r.req.output_ids) == 0, (
|
| 1237 |
+
f"middle chunk must not append an output token; got "
|
| 1238 |
+
f"output_ids len {len(r.req.output_ids)}"
|
| 1239 |
+
)
|
| 1240 |
+
assert (
|
| 1241 |
+
r.status != "finished"
|
| 1242 |
+
), "middle chunk must not finish the req (skip_stream_req)"
|
| 1243 |
+
if r.finished:
|
| 1244 |
+
break
|
| 1245 |
+
yield
|
| 1246 |
+
assert r.finished
|
| 1247 |
+
assert saw_middle_chunk, "test must observe r mid-chunk at least once"
|
| 1248 |
+
assert (
|
| 1249 |
+
len(r.req.output_ids) >= 1
|
| 1250 |
+
), "output tokens must appear only after the chunked prefill completes"
|
| 1251 |
+
|
| 1252 |
+
|
| 1253 |
+
if __name__ == "__main__":
|
| 1254 |
+
unittest.main()
|
asian_ai/performance/SGLang/test/manual/core/test_dynamic_grad_mode.py
ADDED
|
@@ -0,0 +1,58 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import unittest
|
| 2 |
+
|
| 3 |
+
import torch
|
| 4 |
+
|
| 5 |
+
from sglang.srt.utils import DynamicGradMode
|
| 6 |
+
from sglang.test.test_utils import CustomTestCase
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
class TestDynamicGradMode(CustomTestCase):
|
| 10 |
+
def test_inference(self):
|
| 11 |
+
# Test inference_mode
|
| 12 |
+
DynamicGradMode.set_inference_mode(True)
|
| 13 |
+
|
| 14 |
+
@DynamicGradMode()
|
| 15 |
+
def create_tensor_x():
|
| 16 |
+
return torch.empty(0)
|
| 17 |
+
|
| 18 |
+
X = create_tensor_x()
|
| 19 |
+
self.assertTrue(not X.requires_grad and X.is_inference())
|
| 20 |
+
|
| 21 |
+
def test_no_grad(self):
|
| 22 |
+
# Test no_grad
|
| 23 |
+
DynamicGradMode.set_inference_mode(False)
|
| 24 |
+
|
| 25 |
+
@DynamicGradMode()
|
| 26 |
+
def create_tensor_y():
|
| 27 |
+
return torch.empty(0)
|
| 28 |
+
|
| 29 |
+
Y = create_tensor_y()
|
| 30 |
+
self.assertTrue(not Y.requires_grad and not Y.is_inference())
|
| 31 |
+
|
| 32 |
+
def test_nested_inference(self):
|
| 33 |
+
# Test no_grad nested inference_mode, inference_mode should has higher priority
|
| 34 |
+
DynamicGradMode.set_inference_mode(False)
|
| 35 |
+
|
| 36 |
+
@DynamicGradMode()
|
| 37 |
+
def create_tensor_z():
|
| 38 |
+
with torch.inference_mode():
|
| 39 |
+
return torch.empty(0)
|
| 40 |
+
|
| 41 |
+
Z = create_tensor_z()
|
| 42 |
+
self.assertTrue(not Z.requires_grad and Z.is_inference())
|
| 43 |
+
|
| 44 |
+
def test_nested_no_grad(self):
|
| 45 |
+
# Test inference_mode nested no_grad, inference_mode should has higher priority
|
| 46 |
+
DynamicGradMode.set_inference_mode(True)
|
| 47 |
+
|
| 48 |
+
@DynamicGradMode()
|
| 49 |
+
def create_tensor_w():
|
| 50 |
+
with torch.no_grad():
|
| 51 |
+
return torch.empty(0)
|
| 52 |
+
|
| 53 |
+
W = create_tensor_w()
|
| 54 |
+
self.assertTrue(not W.requires_grad and W.is_inference())
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
if __name__ == "__main__":
|
| 58 |
+
unittest.main(verbosity=2)
|
asian_ai/performance/SGLang/test/manual/core/test_gpt_oss_1gpu.py
ADDED
|
@@ -0,0 +1,31 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import unittest
|
| 2 |
+
|
| 3 |
+
from sglang.test.gpt_oss_common import BaseTestGptOss
|
| 4 |
+
|
| 5 |
+
|
| 6 |
+
class TestGptOss1Gpu(BaseTestGptOss):
|
| 7 |
+
def test_mxfp4_20b(self):
|
| 8 |
+
self.run_test(
|
| 9 |
+
model_variant="20b",
|
| 10 |
+
quantization="mxfp4",
|
| 11 |
+
expected_score_of_reasoning_effort={
|
| 12 |
+
"low": 0.34,
|
| 13 |
+
"medium": 0.34,
|
| 14 |
+
"high": 0.27, # TODO investigate
|
| 15 |
+
},
|
| 16 |
+
)
|
| 17 |
+
|
| 18 |
+
def test_bf16_20b(self):
|
| 19 |
+
self.run_test(
|
| 20 |
+
model_variant="20b",
|
| 21 |
+
quantization="bf16",
|
| 22 |
+
expected_score_of_reasoning_effort={
|
| 23 |
+
"low": 0.34,
|
| 24 |
+
"medium": 0.34,
|
| 25 |
+
"high": 0.27, # TODO investigate
|
| 26 |
+
},
|
| 27 |
+
)
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
if __name__ == "__main__":
|
| 31 |
+
unittest.main()
|