luclima commited on
Commit
18f8b8e
·
verified ·
1 Parent(s): 2ceca3e

Upload folder using huggingface_hub (part 50)

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. asian_ai/performance/SGLang/test/registered/README.md +23 -0
  2. asian_ai/performance/SGLang/test/registered/moe/test_topk_padded_region.py +194 -0
  3. asian_ai/performance/SGLang/test/registered/moe/test_torch_compile_moe.py +85 -0
  4. asian_ai/performance/SGLang/test/registered/moe/test_triton_fused_moe.py +195 -0
  5. asian_ai/performance/SGLang/test/registered/moe/test_triton_moe_channel_fp8_kernel.py +187 -0
  6. asian_ai/performance/SGLang/test/registered/musa/test_llm_server_smoke_musa.py +111 -0
  7. asian_ai/performance/SGLang/test/registered/observability/test_metrics.py +598 -0
  8. asian_ai/performance/SGLang/test/registered/observability/test_priority_metrics.py +227 -0
  9. asian_ai/performance/SGLang/test/registered/observability/test_tracing.py +557 -0
  10. asian_ai/performance/SGLang/test/registered/observability/test_tracing_disaggregation.py +237 -0
  11. asian_ai/performance/SGLang/test/registered/openai_server/basic/test_anthropic_server.py +582 -0
  12. asian_ai/performance/SGLang/test/registered/openai_server/basic/test_http2_server.py +134 -0
  13. asian_ai/performance/SGLang/test/registered/openai_server/basic/test_openai_server.py +1139 -0
  14. asian_ai/performance/SGLang/test/registered/openai_server/basic/test_serving_transcription.py +230 -0
  15. asian_ai/performance/SGLang/test/registered/openai_server/features/test_json_mode.py +139 -0
  16. asian_ai/performance/SGLang/test/registered/openai_server/features/test_openai_server_ebnf.py +108 -0
  17. asian_ai/performance/SGLang/test/registered/openai_server/features/test_openai_server_hidden_states.py +358 -0
  18. asian_ai/performance/SGLang/test/registered/openai_server/function_call/test_anthropic_tool_use.py +555 -0
  19. asian_ai/performance/SGLang/test/registered/openai_server/function_call/test_openai_function_calling.py +954 -0
  20. asian_ai/performance/SGLang/test/registered/openai_server/validation/test_large_max_new_tokens.py +107 -0
  21. asian_ai/performance/SGLang/test/registered/openai_server/validation/test_matched_stop.py +35 -0
  22. asian_ai/performance/SGLang/test/registered/openai_server/validation/test_openai_server_ignore_eos.py +94 -0
  23. asian_ai/performance/SGLang/test/registered/openai_server/validation/test_request_length_validation.py +174 -0
  24. asian_ai/performance/SGLang/test/registered/ops/test_aiter_allgather_amd.py +116 -0
  25. asian_ai/performance/SGLang/test/registered/ops/test_aiter_allreduce_fusion_amd.py +480 -0
  26. asian_ai/performance/SGLang/test/registered/ops/test_aiter_greedy_sample_amd.py +289 -0
  27. asian_ai/performance/SGLang/test/registered/page_major/test_page_major_gpt_oss.py +69 -0
  28. asian_ai/performance/SGLang/test/registered/page_major/test_page_major_qwen_hybrid.py +79 -0
  29. asian_ai/performance/SGLang/test/registered/perf/test_bench_one_batch_2gpu.py +54 -0
  30. asian_ai/performance/SGLang/test/registered/perf/test_bench_serving_1gpu_large.py +84 -0
  31. asian_ai/performance/SGLang/test/registered/perf/test_bench_serving_1gpu_part1.py +261 -0
  32. asian_ai/performance/SGLang/test/registered/perf/test_bench_serving_1gpu_part2.py +202 -0
  33. asian_ai/performance/SGLang/test/registered/perf/test_bench_serving_2gpu.py +108 -0
  34. asian_ai/performance/SGLang/test/registered/perf/test_dpsk_v3_fp4_4gpu_perf.py +77 -0
  35. asian_ai/performance/SGLang/test/registered/perf/test_gpt_oss_4gpu_perf.py +60 -0
  36. asian_ai/performance/SGLang/test/registered/perf/test_text_models_perf.py +62 -0
  37. asian_ai/performance/SGLang/test/registered/perf/test_vlm_perf_5090.py +63 -0
  38. asian_ai/performance/SGLang/test/registered/perf/test_vlms_perf.py +90 -0
  39. asian_ai/performance/SGLang/test/registered/pp/test_pp_parallel_compat.py +111 -0
  40. asian_ai/performance/SGLang/test/registered/pp/test_pp_single_node.py +356 -0
  41. asian_ai/performance/SGLang/test/registered/pp/test_pp_single_node_extra.py +355 -0
  42. asian_ai/performance/SGLang/test/registered/prefill_only/test_embed_overrides.py +603 -0
  43. asian_ai/performance/SGLang/test/registered/prefill_only/test_embedding_models.py +162 -0
  44. asian_ai/performance/SGLang/test/registered/prefill_only/test_fa_skip_kv_cache_piecewise_nan.py +162 -0
  45. asian_ai/performance/SGLang/test/registered/prefill_only/test_multi_item_scoring.py +599 -0
  46. asian_ai/performance/SGLang/test/registered/prefill_only/test_openai_embedding.py +200 -0
  47. asian_ai/performance/SGLang/test/registered/prefill_only/test_pooled_hidden_states.py +433 -0
  48. asian_ai/performance/SGLang/test/registered/prefill_only/test_reward_models.py +103 -0
  49. asian_ai/performance/SGLang/test/registered/prefill_only/test_score_api.py +234 -0
  50. asian_ai/performance/SGLang/test/registered/prefill_only/test_score_engine.py +488 -0
asian_ai/performance/SGLang/test/registered/README.md ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Registered Tests
2
+
3
+ Tests under this directory are auto-discovered by `run_suite.py` via CI registration decorators.
4
+
5
+ ## Where Should I Put My New Test?
6
+
7
+ ### No server / engine launch required
8
+
9
+ | What you're testing | Directory | Requires |
10
+ |---|---|---|
11
+ | Component logic in isolation (cache, scheduler, config, parser, etc.) | [`unit/<module>/`](unit/README.md) | CPU or GPU |
12
+ | CUDA kernel correctness | `kernels/` | GPU |
13
+
14
+ ### Server / engine launch required (E2E)
15
+
16
+ | What you're testing | Directory | Requires |
17
+ |---|---|---|
18
+ | Model inference correctness | `models/`, `4-gpu-models/`, `8-gpu-models/` | GPU |
19
+ | Feature-specific (OpenAI API, LoRA, speculative, distributed, VLM, etc.) | `openai_server/`, `lora/`, `spec/`, `distributed/`, ... | GPU |
20
+ | Benchmarks (performance, accuracy, stress) | `benchmark/` | GPU |
21
+ | Platform-specific | `amd/`, `ascend/` | Vendor GPU |
22
+
23
+ See [`unit/README.md`](unit/README.md) for unit test conventions.
asian_ai/performance/SGLang/test/registered/moe/test_topk_padded_region.py ADDED
@@ -0,0 +1,194 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import unittest
2
+
3
+ import torch
4
+
5
+ import sglang.srt.layers.moe.topk as topk_mod
6
+ from sglang.srt.layers.moe.topk import (
7
+ TopKConfig,
8
+ _can_fuse_padded_region,
9
+ _fill_padded_rows,
10
+ _mask_topk_ids_padded_region,
11
+ _post_process_topk_ids,
12
+ _zero_topk_weights_padded_region,
13
+ )
14
+ from sglang.srt.utils import is_hip
15
+ from sglang.test.ci.ci_register import register_amd_ci, register_cuda_ci
16
+ from sglang.test.test_utils import CustomTestCase
17
+
18
+ register_cuda_ci(est_time=60, stage="base-b", runner_config="1-gpu-large")
19
+ register_amd_ci(est_time=60, stage="stage-b", runner_config="1-gpu-small-amd")
20
+
21
+ _IS_HIP = is_hip()
22
+
23
+ torch.manual_seed(1234)
24
+
25
+
26
+ def _eager_fill_padded_rows(x, num_token_non_padded, fill_value):
27
+ out = x.clone()
28
+ indices = torch.arange(0, x.shape[0], device=x.device)
29
+ out[indices >= num_token_non_padded, :] = fill_value
30
+ return out
31
+
32
+
33
+ @unittest.skipUnless(
34
+ torch.cuda.is_available(), "fused padded-region kernel needs a GPU"
35
+ )
36
+ class TestTopkPaddedRegion(CustomTestCase):
37
+ DEVICE = "cuda"
38
+
39
+ def test_matches_eager_across_shapes(self):
40
+ configs = [
41
+ # (n_tokens, topk, dtype, fill, helper)
42
+ (37, 9, torch.float32, 0.0, _zero_topk_weights_padded_region),
43
+ (256, 8, torch.float32, 0.0, _zero_topk_weights_padded_region),
44
+ (1, 9, torch.float32, 0.0, _zero_topk_weights_padded_region),
45
+ (37, 9, torch.int32, -1, _mask_topk_ids_padded_region),
46
+ (512, 16, torch.int32, -1, _mask_topk_ids_padded_region),
47
+ ]
48
+ for n, k, dtype, fill, helper in configs:
49
+ for n_valid in (0, 1, 5, n - 1, n):
50
+ with self.subTest(n=n, k=k, dtype=dtype, n_valid=n_valid):
51
+ if dtype.is_floating_point:
52
+ x = torch.rand((n, k), device=self.DEVICE, dtype=dtype) + 0.5
53
+ else:
54
+ x = torch.randint(
55
+ 0, 100, (n, k), device=self.DEVICE, dtype=dtype
56
+ )
57
+ self.assertTrue(_can_fuse_padded_region(x))
58
+ num_token_non_padded = torch.tensor(
59
+ n_valid, device=self.DEVICE, dtype=torch.int32
60
+ )
61
+ expected = _eager_fill_padded_rows(x, num_token_non_padded, fill)
62
+ fused = x.clone()
63
+ helper(fused, num_token_non_padded)
64
+ self.assertTrue(torch.equal(fused, expected))
65
+
66
+ def test_none_pad_count_is_noop(self):
67
+ x = torch.rand((16, 8), device=self.DEVICE, dtype=torch.float32) + 0.5
68
+ ref = x.clone()
69
+ _zero_topk_weights_padded_region(x, None)
70
+ self.assertTrue(torch.equal(x, ref))
71
+
72
+ def test_non_contiguous_falls_back_to_eager(self):
73
+ # A column slice is not row-major contiguous, so the fused path must be
74
+ # skipped while still producing the correct result via the eager branch.
75
+ base = torch.rand((32, 16), device=self.DEVICE, dtype=torch.float32) + 0.5
76
+ view = base[:, ::2]
77
+ self.assertFalse(_can_fuse_padded_region(view))
78
+ num_token_non_padded = torch.tensor(5, device=self.DEVICE, dtype=torch.int32)
79
+ expected = _eager_fill_padded_rows(view, num_token_non_padded, 0.0)
80
+ _zero_topk_weights_padded_region(view, num_token_non_padded)
81
+ self.assertTrue(torch.equal(view, expected))
82
+
83
+ def test_cuda_graph_capture_and_replay(self):
84
+ n, k = 256, 9
85
+ weights = torch.rand((n, k), device=self.DEVICE, dtype=torch.float32) + 0.5
86
+ num_token_non_padded = torch.tensor(n, device=self.DEVICE, dtype=torch.int32)
87
+
88
+ # Warmup on a side stream before capture.
89
+ side = torch.cuda.Stream()
90
+ side.wait_stream(torch.cuda.current_stream())
91
+ with torch.cuda.stream(side):
92
+ for _ in range(3):
93
+ tmp = weights.clone()
94
+ _zero_topk_weights_padded_region(tmp, num_token_non_padded)
95
+ torch.cuda.current_stream().wait_stream(side)
96
+
97
+ work = weights.clone()
98
+ graph = torch.cuda.CUDAGraph()
99
+ with torch.cuda.graph(graph):
100
+ _zero_topk_weights_padded_region(work, num_token_non_padded)
101
+
102
+ for n_valid in (n, 5, 0, 100):
103
+ work.copy_(weights)
104
+ num_token_non_padded.fill_(n_valid)
105
+ graph.replay()
106
+ torch.cuda.synchronize()
107
+ expected = _eager_fill_padded_rows(weights, num_token_non_padded, 0.0)
108
+ self.assertTrue(torch.equal(work, expected))
109
+
110
+ def test_invalid_pad_count_tensor_raises(self):
111
+ x = torch.rand((8, 8), device=self.DEVICE, dtype=torch.float32)
112
+ with self.assertRaises(TypeError):
113
+ _fill_padded_rows(x, 4, 0.0) # python int, not a tensor
114
+ with self.assertRaises(ValueError):
115
+ _fill_padded_rows(
116
+ x,
117
+ torch.tensor([1, 2], device=self.DEVICE, dtype=torch.int32),
118
+ 0.0,
119
+ )
120
+ with self.assertRaises(TypeError):
121
+ _fill_padded_rows(
122
+ x,
123
+ torch.tensor(4.0, device=self.DEVICE, dtype=torch.float32),
124
+ 0.0,
125
+ )
126
+
127
+
128
+ @unittest.skipUnless(torch.cuda.is_available(), "padded-region masking needs a GPU")
129
+ class TestZeroPaddedRegionIdempotent(CustomTestCase):
130
+ """The HIP post-process keeps a single padded-row zeroing pass. Removing the
131
+ earlier (redundant) pass is only safe if zeroing is idempotent."""
132
+
133
+ DEVICE = "cuda"
134
+
135
+ def test_zeroing_twice_equals_once(self):
136
+ for n, k in [(37, 9), (256, 8), (512, 16)]:
137
+ for n_valid in (0, 5, n - 1, n):
138
+ with self.subTest(n=n, k=k, n_valid=n_valid):
139
+ base = torch.rand((n, k), device=self.DEVICE) + 0.5
140
+ pad = torch.tensor(n_valid, device=self.DEVICE, dtype=torch.int32)
141
+
142
+ once = base.clone()
143
+ _zero_topk_weights_padded_region(once, pad)
144
+
145
+ twice = base.clone()
146
+ _zero_topk_weights_padded_region(twice, pad)
147
+ _zero_topk_weights_padded_region(twice, pad)
148
+
149
+ self.assertTrue(torch.equal(once, twice))
150
+
151
+
152
+ @unittest.skipUnless(
153
+ _IS_HIP and torch.cuda.is_available(),
154
+ "_post_process_topk_ids padded masking is HIP-only",
155
+ )
156
+ class TestPostProcessPaddedMaskingHip(CustomTestCase):
157
+ DEVICE = "cuda"
158
+
159
+ def _run(self, n=256, k=8, n_valid=5):
160
+ topk_weights = torch.rand((n, k), device=self.DEVICE, dtype=torch.float32) + 0.5
161
+ topk_ids = torch.randint(0, 64, (n, k), device=self.DEVICE, dtype=torch.int32)
162
+ router_logits = torch.rand((n, 64), device=self.DEVICE, dtype=torch.float32)
163
+ pad = torch.tensor(n_valid, device=self.DEVICE, dtype=torch.int32)
164
+ cfg = TopKConfig(top_k=k, num_fused_shared_experts=0)
165
+ _, out_weights, _ = _post_process_topk_ids(
166
+ topk_ids,
167
+ topk_weights,
168
+ cfg,
169
+ router_logits,
170
+ layer_id=0,
171
+ num_token_non_padded=pad,
172
+ )
173
+ return out_weights, n_valid
174
+
175
+ def test_padded_rows_zeroed_by_default(self):
176
+ # Flag off (default): padded rows must be fully zeroed, valid rows kept.
177
+ self.assertFalse(topk_mod._skip_hip_pad_mask)
178
+ out, n_valid = self._run()
179
+ self.assertTrue(torch.all(out[n_valid:] == 0.0))
180
+ self.assertTrue(torch.all(out[:n_valid] > 0.0))
181
+
182
+ def test_flag_skips_masking(self):
183
+ # Flag on: padded rows are left untouched (kept non-zero here).
184
+ orig = topk_mod._skip_hip_pad_mask
185
+ topk_mod._skip_hip_pad_mask = True
186
+ try:
187
+ out, n_valid = self._run()
188
+ self.assertTrue(torch.all(out[n_valid:] > 0.0))
189
+ finally:
190
+ topk_mod._skip_hip_pad_mask = orig
191
+
192
+
193
+ if __name__ == "__main__":
194
+ unittest.main()
asian_ai/performance/SGLang/test/registered/moe/test_torch_compile_moe.py ADDED
@@ -0,0 +1,85 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import time
2
+ import unittest
3
+ from types import SimpleNamespace
4
+
5
+ import requests
6
+
7
+ from sglang.srt.utils import is_cuda, kill_process_tree
8
+ from sglang.test.ci.ci_register import register_amd_ci, register_cuda_ci
9
+ from sglang.test.run_eval import run_eval
10
+ from sglang.test.test_utils import (
11
+ DEFAULT_SMALL_MOE_MODEL_NAME_FOR_TEST_BASE,
12
+ DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH,
13
+ DEFAULT_URL_FOR_TEST,
14
+ CustomTestCase,
15
+ is_in_amd_ci,
16
+ popen_launch_server,
17
+ )
18
+
19
+ register_cuda_ci(est_time=130, stage="base-b", runner_config="1-gpu-large")
20
+ register_amd_ci(est_time=1400, suite="stage-b-test-1-gpu-small-amd")
21
+
22
+
23
+ class TestTorchCompileMoe(CustomTestCase):
24
+ @classmethod
25
+ def setUpClass(cls):
26
+ cls.model = DEFAULT_SMALL_MOE_MODEL_NAME_FOR_TEST_BASE
27
+ cls.base_url = DEFAULT_URL_FOR_TEST
28
+ cls.process = popen_launch_server(
29
+ cls.model,
30
+ cls.base_url,
31
+ timeout=DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH,
32
+ other_args=["--enable-torch-compile", "--torch-compile-max-bs", "4"],
33
+ )
34
+
35
+ @classmethod
36
+ def tearDownClass(cls):
37
+ kill_process_tree(cls.process.pid)
38
+
39
+ def test_mmlu(self):
40
+ args = SimpleNamespace(
41
+ base_url=self.base_url,
42
+ model=self.model,
43
+ eval_name="mmlu",
44
+ num_examples=64,
45
+ num_threads=32,
46
+ )
47
+
48
+ metrics = run_eval(args)
49
+ self.assertGreaterEqual(metrics["score"], 0.50)
50
+
51
+ def run_decode(self, max_new_tokens):
52
+ response = requests.post(
53
+ self.base_url + "/generate",
54
+ json={
55
+ "text": "The capital of France is",
56
+ "sampling_params": {
57
+ "temperature": 0,
58
+ "max_new_tokens": max_new_tokens,
59
+ "ignore_eos": True,
60
+ },
61
+ },
62
+ )
63
+ return response.json()
64
+
65
+ def test_throughput(self):
66
+ # Warmup
67
+ res = self.run_decode(16)
68
+
69
+ max_tokens = 256
70
+ tic = time.perf_counter()
71
+ res = self.run_decode(max_tokens)
72
+ tok = time.perf_counter()
73
+ print(f"{res=}")
74
+ throughput = max_tokens / (tok - tic)
75
+ if is_cuda():
76
+ self.assertGreaterEqual(throughput, 285)
77
+ elif is_in_amd_ci():
78
+ # relax for mi300x
79
+ self.assertGreaterEqual(throughput, 240)
80
+ else:
81
+ self.assertGreaterEqual(throughput, 270)
82
+
83
+
84
+ if __name__ == "__main__":
85
+ unittest.main()
asian_ai/performance/SGLang/test/registered/moe/test_triton_fused_moe.py ADDED
@@ -0,0 +1,195 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import unittest
2
+
3
+ import torch
4
+ from tqdm import tqdm
5
+
6
+ from sglang.srt.layers.activation import SiluAndMul
7
+ from sglang.srt.layers.moe import MoeRunner, MoeRunnerBackend, MoeRunnerConfig
8
+ from sglang.srt.layers.moe.moe_runner.triton_kernels import TritonKernelsQuantInfo
9
+ from sglang.srt.layers.moe.token_dispatcher.standard import StandardDispatchOutput
10
+ from sglang.srt.layers.moe.topk import TopK, TopKOutputFormat
11
+ from sglang.srt.server_args import ServerArgs, set_global_server_args_for_scheduler
12
+ from sglang.test.ci.ci_register import register_cuda_ci
13
+ from sglang.test.test_utils import CustomTestCase
14
+
15
+ register_cuda_ci(est_time=13, stage="base-b", runner_config="1-gpu-large")
16
+
17
+
18
+ class TestFusedMOE(CustomTestCase):
19
+ NUM_EXPERTS = [8, 64]
20
+ TOP_KS = [2, 4]
21
+
22
+ @staticmethod
23
+ def create_random_cuda_tensor(shape, dtype, mean=0, std=0.01):
24
+ """Create a random CUDA tensor
25
+
26
+ Args:
27
+ shape: Tensor shape
28
+ dtype: Data type
29
+ mean: Mean value
30
+ std: Standard deviation
31
+
32
+ Returns:
33
+ torch.Tensor: Randomly initialized CUDA tensor
34
+ """
35
+ return torch.empty(shape, dtype=dtype, device="cuda").normal_(mean, std)
36
+
37
+ def get_tolerance(self, dtype):
38
+ """Get tolerance values for different data types
39
+
40
+ Args:
41
+ dtype: Data type
42
+
43
+ Returns:
44
+ tuple: (relative tolerance, absolute tolerance)
45
+ """
46
+ if dtype == torch.float32:
47
+ return 1e-5, 1e-5
48
+ elif dtype in [torch.float16, torch.bfloat16]:
49
+ return 1e-5, 1e-5
50
+ else:
51
+ return 1e-2, 1e-2 # Default values for other types
52
+
53
+ def torch_naive_moe(
54
+ self,
55
+ a,
56
+ w1,
57
+ w2,
58
+ score,
59
+ topk,
60
+ return_per_expert: bool = False,
61
+ ):
62
+ set_global_server_args_for_scheduler(ServerArgs(model_path="dummy"))
63
+
64
+ B, D = a.shape
65
+ a = a.view(B, -1, D).repeat(1, topk, 1).reshape(-1, D)
66
+ out = torch.zeros(B * topk, w2.shape[1], dtype=a.dtype, device=a.device)
67
+ score = torch.softmax(score, dim=-1, dtype=torch.float32)
68
+ topk_weight, topk_ids = torch.topk(score, topk)
69
+ topk_weight = topk_weight.view(-1)
70
+ topk_ids = topk_ids.view(-1)
71
+
72
+ if w1.dtype == torch.float8_e4m3fn:
73
+ w1_compute = w1.to(a.dtype)
74
+ w2_compute = w2.to(a.dtype)
75
+ else:
76
+ w1_compute = w1
77
+ w2_compute = w2
78
+
79
+ for i in range(w1_compute.shape[0]):
80
+ mask = topk_ids == i
81
+ if mask.sum():
82
+ out[mask] = SiluAndMul()(
83
+ a[mask] @ w1_compute[i].transpose(0, 1)
84
+ ) @ w2_compute[i].transpose(0, 1)
85
+
86
+ weighted = out.view(B, -1, w2.shape[1]) * topk_weight.view(B, -1, 1).to(
87
+ out.dtype
88
+ )
89
+
90
+ if return_per_expert:
91
+ return weighted
92
+
93
+ return weighted.sum(dim=1)
94
+
95
+ def _test_case(self, m, n, k, e, topk, dtype):
96
+ rtol, atol = self.get_tolerance(dtype)
97
+
98
+ a = self.create_random_cuda_tensor((m, k), dtype)
99
+ w1 = self.create_random_cuda_tensor((e, 2 * n, k), dtype)
100
+ w2 = self.create_random_cuda_tensor((e, k, n), dtype)
101
+ w1_tri = w1.clone()
102
+ w2_tri = w2.clone()
103
+ w1_tri = w1_tri.transpose(-2, -1).contiguous()
104
+ w2_tri = w2_tri.transpose(-2, -1).contiguous()
105
+ score = self.create_random_cuda_tensor((m, e), dtype)
106
+
107
+ topk_op = TopK(
108
+ top_k=topk,
109
+ renormalize=False,
110
+ use_grouped_topk=False,
111
+ )
112
+ topk_op.topk_config.output_format = TopKOutputFormat.TRITON_KERNEL
113
+ triton_topk_output = topk_op.forward_cuda(
114
+ hidden_states=a,
115
+ router_logits=score,
116
+ )
117
+
118
+ quant_info = TritonKernelsQuantInfo(w13_weight=w1_tri, w2_weight=w2_tri)
119
+
120
+ dispatch_output = StandardDispatchOutput(
121
+ hidden_states=a, hidden_states_scale=None, topk_output=triton_topk_output
122
+ )
123
+
124
+ torch_per_expert = self.torch_naive_moe(
125
+ a, w1, w2, score, topk, return_per_expert=True
126
+ )
127
+ torch_combined = torch_per_expert.sum(dim=1)
128
+
129
+ def run_runner(config):
130
+ runner = MoeRunner(MoeRunnerBackend.TRITON_KERNELS, config)
131
+ result = runner.run(dispatch_output, quant_info)
132
+ return result.hidden_states
133
+
134
+ # Combined output (no_combine=False)
135
+ non_fused_config = MoeRunnerConfig(inplace=False)
136
+ non_fused_output = run_runner(non_fused_config)
137
+ torch.testing.assert_close(
138
+ non_fused_output, torch_combined, rtol=rtol, atol=atol
139
+ )
140
+
141
+ # Per-expert output (no_combine=True)
142
+ non_fused_no_combine_config = MoeRunnerConfig(
143
+ inplace=False, no_combine=True, top_k=topk
144
+ )
145
+ non_fused_no_combine_output = run_runner(non_fused_no_combine_config)
146
+ torch.testing.assert_close(
147
+ non_fused_no_combine_output, torch_per_expert, rtol=rtol, atol=atol
148
+ )
149
+
150
+ def test_various_configurations(self):
151
+ m_values = [1, 32, 64, 256]
152
+ n_values = [128, 1024]
153
+ k_values = [128, 512, 1024]
154
+ dtypes = [torch.bfloat16]
155
+
156
+ # Calculate total number of tests
157
+ total_tests = (
158
+ len(m_values)
159
+ * len(n_values)
160
+ * len(k_values)
161
+ * len(self.NUM_EXPERTS)
162
+ * len(self.TOP_KS)
163
+ * len(dtypes)
164
+ )
165
+
166
+ # Create progress bar
167
+ with tqdm(total=total_tests, desc="Running MoE tests") as pbar:
168
+ for m in m_values:
169
+ for n in n_values:
170
+ for k in k_values:
171
+ for e in self.NUM_EXPERTS:
172
+ for topk in self.TOP_KS:
173
+ for dtype in dtypes:
174
+ with self.subTest(
175
+ m=m,
176
+ n=n,
177
+ k=k,
178
+ e=e,
179
+ topk=topk,
180
+ dtype=dtype,
181
+ ):
182
+ self._test_case(
183
+ m,
184
+ n,
185
+ k,
186
+ e,
187
+ topk,
188
+ dtype,
189
+ )
190
+ torch.cuda.empty_cache()
191
+ pbar.update(1)
192
+
193
+
194
+ if __name__ == "__main__":
195
+ unittest.main()
asian_ai/performance/SGLang/test/registered/moe/test_triton_moe_channel_fp8_kernel.py ADDED
@@ -0,0 +1,187 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import itertools
2
+ import unittest
3
+
4
+ import torch
5
+
6
+ from sglang.srt.layers.activation import SiluAndMul
7
+ from sglang.srt.layers.moe.moe_runner.triton_utils.fused_moe import fused_moe
8
+ from sglang.srt.layers.moe.topk import TopKConfig, select_experts
9
+ from sglang.srt.layers.quantization.fp8_kernel import scaled_fp8_quant
10
+ from sglang.srt.server_args import ServerArgs, set_global_server_args_for_scheduler
11
+ from sglang.test.ci.ci_register import register_cuda_ci
12
+ from sglang.test.test_utils import CustomTestCase
13
+
14
+ register_cuda_ci(est_time=17, stage="base-b", runner_config="1-gpu-large")
15
+
16
+
17
+ def native_w8a8_per_token_matmul(A, B, As, Bs, output_dtype=torch.float16):
18
+ """Matrix multiplication function that supports per-token input quantization and per-column weight quantization"""
19
+ A = A.to(torch.float32)
20
+ B = B.to(torch.float32)
21
+
22
+ assert A.shape[-1] == B.shape[-1], "Dimension mismatch"
23
+ assert B.ndim == 2 and B.is_contiguous(), "B must be a 2D contiguous tensor"
24
+
25
+ # Reshape input
26
+ M = A.numel() // A.shape[-1]
27
+ B = B.t() # Transpose weight matrix
28
+ N, K = B.shape
29
+ origin_C_shape = A.shape[:-1] + (K,)
30
+ A = A.reshape(M, N)
31
+
32
+ # As is per-token [M, 1], Bs is per-column [1, K]
33
+ C = torch.matmul(A, B) # [M, K]
34
+ C = As * C * Bs.view(1, -1) # Broadcast per-column scale
35
+
36
+ return C.reshape(origin_C_shape).to(output_dtype)
37
+
38
+
39
+ def fp8_mask(a, mask):
40
+ dtype = a.dtype
41
+ return a.view(torch.int8)[mask].view(dtype)
42
+
43
+
44
+ def torch_w8a8_per_column_moe(a, w1, w2, w1_s, w2_s, score, topk):
45
+ """This function performs fused moe with per-column int8 quantization using native torch."""
46
+
47
+ set_global_server_args_for_scheduler(ServerArgs(model_path="dummy"))
48
+
49
+ B, D = a.shape
50
+ # Perform per-token quantization
51
+ a_q, a_s = scaled_fp8_quant(a, use_per_token_if_dynamic=True)
52
+ # Repeat tokens to match topk
53
+ a_q = a_q.view(B, -1, D).repeat(1, topk, 1).reshape(-1, D)
54
+ # Also repeat the scale
55
+ a_s = a_s.view(B, -1, 1).repeat(1, topk, 1).reshape(-1, 1) # [B*topk, 1]
56
+
57
+ out = torch.zeros(B * topk, w2.shape[1], dtype=a.dtype, device=a.device)
58
+
59
+ # Calculate routing
60
+ score = torch.softmax(score, dim=-1, dtype=torch.float32)
61
+ topk_weight, topk_ids = torch.topk(score, topk)
62
+ topk_weight = topk_weight.view(-1)
63
+ topk_ids = topk_ids.view(-1)
64
+ # Process each expert
65
+ for i in range(w1.shape[0]):
66
+ mask = topk_ids == i
67
+ if mask.sum():
68
+ # First MLP layer: note that a_s is now per-token
69
+ inter_out = native_w8a8_per_token_matmul(
70
+ fp8_mask(a_q, mask),
71
+ w1[i],
72
+ fp8_mask(a_s, mask),
73
+ w1_s[i],
74
+ output_dtype=a.dtype,
75
+ )
76
+ # Activation function
77
+ act_out = SiluAndMul().forward_native(inter_out)
78
+ # Quantize activation output with per-token
79
+ act_out_q, act_out_s = scaled_fp8_quant(
80
+ act_out, use_per_token_if_dynamic=True
81
+ )
82
+
83
+ # Second MLP layer
84
+ out[mask] = native_w8a8_per_token_matmul(
85
+ act_out_q, w2[i], act_out_s, w2_s[i], output_dtype=a.dtype
86
+ )
87
+ # Apply routing weights and sum
88
+ return (
89
+ out.view(B, -1, w2.shape[1]) * topk_weight.view(B, -1, 1).to(out.dtype)
90
+ ).sum(dim=1)
91
+
92
+
93
+ class TestW8A8FP8FusedMoE(CustomTestCase):
94
+ DTYPES = [torch.half, torch.bfloat16]
95
+ M = [1, 33]
96
+ N = [128, 1024]
97
+ K = [256, 4096]
98
+ E = [8]
99
+ TOP_KS = [2, 6]
100
+ BLOCK_SIZE = [[64, 64], [64, 128], [128, 64], [128, 128]]
101
+ BLOCK_SIZE = [[128, 128]]
102
+ SEEDS = [0]
103
+
104
+ @classmethod
105
+ def setUpClass(cls):
106
+ if not torch.cuda.is_available():
107
+ raise unittest.SkipTest("CUDA is not available")
108
+ torch.set_default_device("cuda")
109
+
110
+ def _w8a8_fp8_fused_moe(self, M, N, K, E, topk, block_size, dtype, seed):
111
+ torch.manual_seed(seed)
112
+ # Initialize int8 quantization parameters
113
+ factor_for_scale = 1e-2
114
+ finfo = torch.finfo(torch.float8_e4m3fn)
115
+ fp8_max = finfo.max
116
+ fp8_min = finfo.min
117
+
118
+ # Input tensor
119
+ # M * K
120
+ a = torch.randn((M, K), dtype=dtype) / 10
121
+
122
+ # Generate int8 weights
123
+ w1_fp32 = (torch.rand((E, 2 * N, K), dtype=torch.float32) - 0.5) * 2
124
+ w1 = (w1_fp32 * fp8_max).clamp(min=fp8_min, max=fp8_max).to(torch.float8_e4m3fn)
125
+
126
+ w2_fp32 = (torch.rand((E, K, N), dtype=torch.float32) - 0.5) * 2
127
+ w2 = (w2_fp32 * fp8_max).clamp(min=fp8_min, max=fp8_max).to(torch.float8_e4m3fn)
128
+
129
+ # Generate scale for each column (per-column quantization)
130
+ w1_s = torch.rand(E, 2 * N, device=w1_fp32.device) * factor_for_scale
131
+ w2_s = torch.rand(E, K, device=w2_fp32.device) * factor_for_scale
132
+ score = torch.randn((M, E), dtype=dtype)
133
+
134
+ with torch.inference_mode():
135
+ ref_out = torch_w8a8_per_column_moe(a, w1, w2, w1_s, w2_s, score, topk)
136
+ topk_output = select_experts(
137
+ hidden_states=a,
138
+ router_logits=score,
139
+ topk_config=TopKConfig(top_k=topk, renormalize=False),
140
+ )
141
+ out = fused_moe(
142
+ a,
143
+ w1,
144
+ w2,
145
+ topk_output,
146
+ use_fp8_w8a8=True, # using fp8
147
+ use_int8_w8a16=False,
148
+ use_int8_w8a8=False,
149
+ per_channel_quant=True,
150
+ w1_scale=w1_s,
151
+ w2_scale=w2_s,
152
+ block_shape=None, # Not using block quantization
153
+ )
154
+
155
+ # Check results
156
+ self.assertTrue(
157
+ torch.mean(torch.abs(out.to(torch.float32) - ref_out.to(torch.float32)))
158
+ / torch.mean(torch.abs(ref_out.to(torch.float32)))
159
+ < 0.05
160
+ )
161
+
162
+ def test_w8a8_fp8_fused_moe(self):
163
+ for params in itertools.product(
164
+ self.M,
165
+ self.N,
166
+ self.K,
167
+ self.E,
168
+ self.TOP_KS,
169
+ self.BLOCK_SIZE,
170
+ self.DTYPES,
171
+ self.SEEDS,
172
+ ):
173
+ with self.subTest(
174
+ M=params[0],
175
+ N=params[1],
176
+ K=params[2],
177
+ E=params[3],
178
+ topk=params[4],
179
+ block_size=params[5],
180
+ dtype=params[6],
181
+ seed=params[7],
182
+ ):
183
+ self._w8a8_fp8_fused_moe(*params)
184
+
185
+
186
+ if __name__ == "__main__":
187
+ unittest.main(verbosity=2)
asian_ai/performance/SGLang/test/registered/musa/test_llm_server_smoke_musa.py ADDED
@@ -0,0 +1,111 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import unittest
3
+
4
+ import requests
5
+ import torch
6
+
7
+ from sglang.test.ci.ci_register import register_musa_ci
8
+ from sglang.test.server_fixtures.default_fixture import DefaultServerBase
9
+
10
+ register_musa_ci(est_time=1200, suite="nightly-musa-1-gpu", nightly=True)
11
+
12
+
13
+ _REQUEST_TIMEOUT = 60
14
+
15
+
16
+ @unittest.skipIf(
17
+ not (hasattr(torch, "musa") and torch.musa.is_available()),
18
+ "MUSA device not available",
19
+ )
20
+ class TestMusaDeepSeekV2LiteChatServerSmoke(DefaultServerBase):
21
+ """MUSA LLM server sanity check: launch, health check, and non-empty generation."""
22
+
23
+ model = os.getenv("SGLANG_MUSA_LLM_MODEL", "deepseek-ai/DeepSeek-V2-Lite-Chat")
24
+ served_model_name = "deepseek-v2-lite-chat"
25
+ other_args = [
26
+ "--trust-remote-code",
27
+ "--served-model-name",
28
+ served_model_name,
29
+ "--attention-backend",
30
+ "fa3",
31
+ "--cuda-graph-max-bs-decode",
32
+ "32",
33
+ "--tp-size",
34
+ "1",
35
+ "--chunked-prefill-size",
36
+ "-1",
37
+ "--disable-piecewise-cuda-graph",
38
+ "--context-length",
39
+ "4096",
40
+ "--max-total-tokens",
41
+ "8192",
42
+ "--max-running-requests",
43
+ "4",
44
+ ]
45
+
46
+ def test_health(self):
47
+ resp = requests.get(self.base_url + "/health", timeout=10)
48
+ self.assertEqual(resp.status_code, 200, resp.text)
49
+
50
+ def test_health_generate(self):
51
+ resp = requests.get(
52
+ self.base_url + "/health_generate", timeout=_REQUEST_TIMEOUT
53
+ )
54
+ self.assertEqual(resp.status_code, 200, resp.text)
55
+
56
+ def test_send_receive_chat_message_contains_beijing(self):
57
+ resp = requests.post(
58
+ self.base_url + "/v1/chat/completions",
59
+ json={
60
+ "model": self.served_model_name,
61
+ "messages": [
62
+ {
63
+ "role": "user",
64
+ "content": (
65
+ "What is the capital of China? Answer in one word."
66
+ ),
67
+ },
68
+ ],
69
+ "temperature": 0.0,
70
+ "max_tokens": 16,
71
+ },
72
+ timeout=_REQUEST_TIMEOUT,
73
+ )
74
+ self.assertEqual(resp.status_code, 200, resp.text)
75
+ body = resp.json()
76
+ self.assertIn("choices", body)
77
+ self.assertGreater(len(body["choices"]), 0)
78
+ content = body["choices"][0]["message"]["content"]
79
+ print(
80
+ f"[MUSA Chat Completion] prompt='What is the capital of China? Answer in one word.' response={content!r}",
81
+ flush=True,
82
+ )
83
+ self.assertIsInstance(content, str)
84
+ self.assertGreater(len(content.strip()), 0)
85
+ self.assertIn("beijing", content.strip().lower())
86
+
87
+ def test_generate(self):
88
+ resp = requests.post(
89
+ self.base_url + "/generate",
90
+ json={
91
+ "text": "The capital of France is",
92
+ "sampling_params": {
93
+ "temperature": 0.0,
94
+ "max_new_tokens": 16,
95
+ },
96
+ "stream": False,
97
+ },
98
+ timeout=_REQUEST_TIMEOUT,
99
+ )
100
+ self.assertEqual(resp.status_code, 200, resp.text)
101
+ body = resp.json()
102
+ if isinstance(body, list):
103
+ self.assertGreater(len(body), 0)
104
+ body = body[0]
105
+ self.assertIn("text", body)
106
+ self.assertIsInstance(body["text"], str)
107
+ self.assertGreater(len(body["text"].strip()), 0)
108
+
109
+
110
+ if __name__ == "__main__":
111
+ unittest.main()
asian_ai/performance/SGLang/test/registered/observability/test_metrics.py ADDED
@@ -0,0 +1,598 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+ import os
3
+ import tempfile
4
+ import unittest
5
+ from typing import Dict, List
6
+
7
+ import requests
8
+ from prometheus_client.parser import text_string_to_metric_families
9
+ from prometheus_client.samples import Sample
10
+
11
+ from sglang.srt.environ import envs
12
+ from sglang.srt.observability.metrics_collector import (
13
+ ROUTING_KEY_REQ_COUNT_BUCKET_BOUNDS,
14
+ STAT_LOGGER_ROLE_SCHEDULER,
15
+ SchedulerMetricsCollector,
16
+ compute_routing_key_stats,
17
+ )
18
+ from sglang.srt.utils import kill_process_tree
19
+ from sglang.test.ci.ci_register import register_amd_ci, register_cuda_ci
20
+ from sglang.test.test_utils import (
21
+ DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH,
22
+ DEFAULT_URL_FOR_TEST,
23
+ CustomTestCase,
24
+ is_in_ci,
25
+ popen_launch_server,
26
+ )
27
+
28
+ register_cuda_ci(est_time=74, stage="base-b", runner_config="1-gpu-small")
29
+ register_amd_ci(est_time=32, suite="stage-b-test-1-gpu-small-amd")
30
+
31
+ _MODEL_NAME = "Qwen/Qwen3-0.6B"
32
+
33
+
34
+ class TestEnableMetrics(CustomTestCase):
35
+ def test_metrics_1gpu(self):
36
+ """Test that metrics endpoint returns data when enabled"""
37
+ self._execute_core(
38
+ other_args=[],
39
+ verify_metrics_extra=None,
40
+ expect_mfu_metrics=True,
41
+ enable_mfu_metrics=True,
42
+ )
43
+
44
+ def test_mfu_metrics_gate_disabled(self):
45
+ """MFU metrics should not be emitted when the gate is disabled."""
46
+ self._execute_core(
47
+ other_args=[],
48
+ verify_metrics_extra=None,
49
+ expect_mfu_metrics=False,
50
+ enable_mfu_metrics=False,
51
+ )
52
+
53
+ def test_metrics_2gpu(self):
54
+ # TODO enable when we have 2-gpu runner in nightly CI
55
+ if is_in_ci():
56
+ print("Skip test_metrics_2gpu since in 1-gpu CI")
57
+ return
58
+
59
+ def _verify_metrics_extra(metrics):
60
+ metrics_to_check = [
61
+ (
62
+ "sglang:dp_cooperation_realtime_tokens_total",
63
+ {"mode": "prefill_compute"},
64
+ ),
65
+ (
66
+ "sglang:dp_cooperation_realtime_tokens_total",
67
+ {"mode": "decode"},
68
+ ),
69
+ (
70
+ "sglang:dp_cooperation_forward_execution_seconds_total",
71
+ {"category": "extend"},
72
+ ),
73
+ (
74
+ "sglang:dp_cooperation_forward_execution_seconds_total",
75
+ {"category": "decode"},
76
+ ),
77
+ ]
78
+ _check_metrics_positive(self, metrics, metrics_to_check)
79
+
80
+ num_prefill_ranks_values = {
81
+ s.labels["num_prefill_ranks"]
82
+ for s in metrics["sglang:dp_cooperation_realtime_tokens_total"]
83
+ }
84
+ self.assertIn("0", num_prefill_ranks_values)
85
+ self.assertIn("1", num_prefill_ranks_values)
86
+
87
+ self._execute_core(
88
+ other_args=["--tp", "2", "--dp", "2", "--enable-dp-attention"],
89
+ verify_metrics_extra=_verify_metrics_extra,
90
+ expect_mfu_metrics=True,
91
+ enable_mfu_metrics=True,
92
+ )
93
+
94
+ def _execute_core(
95
+ self,
96
+ other_args,
97
+ verify_metrics_extra,
98
+ expect_mfu_metrics: bool,
99
+ enable_mfu_metrics: bool,
100
+ ):
101
+ with (
102
+ envs.SGLANG_ENABLE_METRICS_DP_ATTENTION.override(True),
103
+ envs.SGLANG_ENABLE_METRICS_DEVICE_TIMER.override(True),
104
+ envs.SGLANG_TEST_RETRACT.override(True),
105
+ ):
106
+ launch_args = [
107
+ "--enable-metrics",
108
+ "--cuda-graph-max-bs-decode",
109
+ 2,
110
+ *other_args,
111
+ ]
112
+ if enable_mfu_metrics:
113
+ launch_args.insert(1, "--enable-mfu-metrics")
114
+ process = popen_launch_server(
115
+ _MODEL_NAME,
116
+ DEFAULT_URL_FOR_TEST,
117
+ timeout=DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH,
118
+ other_args=launch_args,
119
+ )
120
+
121
+ try:
122
+ # Make some requests to generate some metrics
123
+ response = requests.get(f"{DEFAULT_URL_FOR_TEST}/health_generate")
124
+ self.assertEqual(response.status_code, 200)
125
+
126
+ response = requests.post(
127
+ f"{DEFAULT_URL_FOR_TEST}/generate",
128
+ json={
129
+ "text": ["The capital of France is"] * 20,
130
+ "sampling_params": {
131
+ "temperature": 0,
132
+ "max_new_tokens": 50,
133
+ },
134
+ "stream": True,
135
+ "ignore_eos": True,
136
+ },
137
+ stream=True,
138
+ )
139
+ for _ in response.iter_lines(decode_unicode=False):
140
+ pass
141
+
142
+ for i in range(2):
143
+ # Send the request twice to trigger cached token metrics
144
+ response = requests.post(
145
+ f"{DEFAULT_URL_FOR_TEST}/generate",
146
+ json={
147
+ "text": "Hello, " * 100,
148
+ "sampling_params": {"temperature": 0, "max_new_tokens": 5},
149
+ },
150
+ headers={"x-smg-routing-key": "test-key"},
151
+ )
152
+ self.assertEqual(response.status_code, 200)
153
+
154
+ # Get metrics
155
+ metrics_response = requests.get(f"{DEFAULT_URL_FOR_TEST}/metrics")
156
+ self.assertEqual(metrics_response.status_code, 200)
157
+ metrics_text = metrics_response.text
158
+
159
+ print(f"metrics_text=\n{metrics_text}")
160
+
161
+ metrics = _parse_prometheus_metrics(metrics_text)
162
+ self._verify_metrics_common(metrics_text, metrics, expect_mfu_metrics)
163
+ if verify_metrics_extra is not None:
164
+ verify_metrics_extra(metrics)
165
+ finally:
166
+ kill_process_tree(process.pid)
167
+
168
+ def _verify_metrics_common(self, metrics_text, metrics, expect_mfu_metrics: bool):
169
+ essential_metrics = [
170
+ "sglang:num_running_reqs",
171
+ "sglang:num_used_tokens",
172
+ "sglang:token_usage",
173
+ "sglang:gen_throughput",
174
+ "sglang:num_queue_reqs",
175
+ "sglang:num_grammar_queue_reqs",
176
+ "sglang:cache_hit_rate",
177
+ "sglang:spec_accept_length",
178
+ "sglang:prompt_tokens_total",
179
+ "sglang:generation_tokens_total",
180
+ "sglang:cached_tokens_total",
181
+ "sglang:num_requests_total",
182
+ "sglang:time_to_first_token_seconds",
183
+ "sglang:inter_token_latency_seconds",
184
+ "sglang:e2e_request_latency_seconds",
185
+ "sglang:http_requests_active",
186
+ "sglang:routing_keys_active",
187
+ "sglang:num_unique_running_routing_keys",
188
+ "sglang:routing_key_running_req_count",
189
+ "sglang:routing_key_all_req_count",
190
+ ]
191
+ mfu_metrics = [
192
+ "sglang:estimated_flops_per_gpu_total",
193
+ "sglang:estimated_read_bytes_per_gpu_total",
194
+ "sglang:estimated_write_bytes_per_gpu_total",
195
+ ]
196
+ if expect_mfu_metrics:
197
+ essential_metrics.extend(mfu_metrics)
198
+ for metric in essential_metrics:
199
+ self.assertIn(metric, metrics_text, f"Missing metric: {metric}")
200
+
201
+ # Verify routing key GaugeHistogram buckets
202
+ expected_buckets = len(ROUTING_KEY_REQ_COUNT_BUCKET_BOUNDS) + 1
203
+ for metric_name in [
204
+ "sglang:routing_key_running_req_count",
205
+ "sglang:routing_key_all_req_count",
206
+ ]:
207
+ gt_le_pairs = set()
208
+ for sample in metrics.get(metric_name, []):
209
+ gt_le_pairs.add((sample.labels.get("gt"), sample.labels.get("le")))
210
+ self.assertEqual(
211
+ len(gt_le_pairs),
212
+ expected_buckets,
213
+ f"{metric_name}: Expected {expected_buckets} buckets, got {len(gt_le_pairs)}",
214
+ )
215
+
216
+ self.assertIn(f'model_name="{_MODEL_NAME}"', metrics_text)
217
+ self.assertIn("_sum{", metrics_text)
218
+ self.assertIn("_count{", metrics_text)
219
+ self.assertIn("_bucket{", metrics_text)
220
+
221
+ metrics_to_check = [
222
+ ("sglang:realtime_tokens_total", {"mode": "prefill_compute"}),
223
+ ("sglang:realtime_tokens_total", {"mode": "decode"}),
224
+ ("sglang:forward_execution_seconds_total", {"category": "extend"}),
225
+ ("sglang:forward_execution_seconds_total", {"category": "decode"}),
226
+ ("sglang:process_cpu_seconds_total", {"component": "tokenizer"}),
227
+ ]
228
+ _check_metrics_positive(self, metrics, metrics_to_check)
229
+
230
+ if expect_mfu_metrics:
231
+ # Estimated perf metrics may have multiple series (e.g., by rank). Ensure
232
+ # that at least one series for this model has a positive accumulated value.
233
+ for metric_name in mfu_metrics:
234
+ values = [
235
+ sample.value
236
+ for sample in metrics.get(metric_name, [])
237
+ if sample.labels.get("model_name") == _MODEL_NAME
238
+ ]
239
+ self.assertTrue(
240
+ values, f"{metric_name}: no samples for model {_MODEL_NAME}"
241
+ )
242
+ self.assertGreater(
243
+ sum(values),
244
+ 0,
245
+ f"{metric_name}: expected positive total for model {_MODEL_NAME}",
246
+ )
247
+ else:
248
+ # With only --enable-metrics (without --enable-mfu-metrics), MFU
249
+ # counters should not emit positive values.
250
+ for metric_name in mfu_metrics:
251
+ values = [
252
+ sample.value
253
+ for sample in metrics.get(metric_name, [])
254
+ if sample.labels.get("model_name") == _MODEL_NAME
255
+ ]
256
+ if values:
257
+ self.assertEqual(
258
+ sum(values),
259
+ 0,
260
+ f"{metric_name}: expected no positive samples with MFU metrics gate disabled",
261
+ )
262
+
263
+
264
+ def _parse_prometheus_metrics(metrics_text: str) -> Dict[str, List[Sample]]:
265
+ result = {}
266
+ for family in text_string_to_metric_families(metrics_text):
267
+ for sample in family.samples:
268
+ if sample.name not in result:
269
+ result[sample.name] = []
270
+ result[sample.name].append(sample)
271
+ return result
272
+
273
+
274
+ def _get_sample_value_by_labels(samples: List[Sample], labels: Dict[str, str]) -> float:
275
+ for sample in samples:
276
+ if all(sample.labels.get(k) == v for k, v in labels.items()):
277
+ return sample.value
278
+ raise KeyError(f"No sample found with labels {labels}")
279
+
280
+
281
+ def _check_metrics_positive(test_case, metrics, metrics_to_check):
282
+ for metric_name, labels in metrics_to_check:
283
+ value = _get_sample_value_by_labels(metrics[metric_name], labels)
284
+ test_case.assertGreater(value, 0, f"{metric_name} {labels}")
285
+
286
+
287
+ _DI_MARKER_PATH = "/tmp/sglang_di_test_marker"
288
+
289
+
290
+ class _MarkingSchedulerCollector(SchedulerMetricsCollector):
291
+ """Records its own instantiation to a file so the test can verify the
292
+ custom subclass was used in the scheduler subprocess.
293
+
294
+ Defined at module level so it is picklable into the scheduler process.
295
+ Cross-process signalling uses a filesystem marker because the scheduler
296
+ runs in its own subprocess and cannot share in-memory state with the
297
+ test runner.
298
+ """
299
+
300
+ def __init__(self, *args, **kwargs):
301
+ with open(_DI_MARKER_PATH, "w") as f:
302
+ f.write("scheduler_collector_initialized\n")
303
+ super().__init__(*args, **kwargs)
304
+
305
+
306
+ # Path to the cross-process marker file for the FakeRayMetric-style recording
307
+ # variant below. Distinct from ``_DI_MARKER_PATH`` so the two scheduler
308
+ # collector subclasses (instantiation-marker vs. emission-recording) cannot
309
+ # stomp on each other when both tests run in the same CI shard.
310
+ _DI_RECORDING_MARKER_PATH = os.path.join(
311
+ tempfile.gettempdir(), "sglang_stat_loggers_di_marker.jsonl"
312
+ )
313
+
314
+
315
+ class _FileRecordingMetric:
316
+ """Module-level recording metric.
317
+
318
+ Mirrors the ``FakeRayMetric`` from
319
+ ``sglang.test.observability.fake_ray`` (records ``(op, value, tags)``
320
+ triples) but exposes the prometheus_client ``.labels(...).inc/.set/
321
+ .observe(...)`` shape that ``SchedulerMetricsCollector`` calls into.
322
+
323
+ Defined at module level so the scheduler subprocess can unpickle the
324
+ ``_RecordingSchedulerCollector`` reference. Recordings are appended as
325
+ JSON lines to ``_DI_RECORDING_MARKER_PATH`` so the test runner can read
326
+ them across the process boundary.
327
+ """
328
+
329
+ def __init__(self, name="", documentation="", labelnames=(), **kwargs):
330
+ self.name = name
331
+ self.documentation = documentation
332
+ self._labelnames = tuple(labelnames or ())
333
+ # Sink for in-process introspection. The subprocess uses the file
334
+ # marker instead, since in-memory state is not visible to the test
335
+ # runner.
336
+ self.calls = []
337
+
338
+ def labels(self, **kwargs):
339
+ return _FileRecordingMetricBound(self, dict(kwargs))
340
+
341
+
342
+ class _FileRecordingMetricBound:
343
+ """The object returned by ``_FileRecordingMetric.labels(...)``.
344
+
345
+ All three terminal verbs append a JSON line to the marker file so the
346
+ test runner can verify emissions made inside the scheduler subprocess.
347
+ """
348
+
349
+ def __init__(self, parent: "_FileRecordingMetric", tags: dict):
350
+ self._parent = parent
351
+ self._tags = tags
352
+
353
+ def _record(self, op: str, value):
354
+ self._parent.calls.append((op, value, dict(self._tags)))
355
+ try:
356
+ with open(_DI_RECORDING_MARKER_PATH, "a") as f:
357
+ f.write(
358
+ json.dumps(
359
+ {
360
+ "name": self._parent.name,
361
+ "op": op,
362
+ "value": value,
363
+ "tags": self._tags,
364
+ }
365
+ )
366
+ + "\n"
367
+ )
368
+ except OSError:
369
+ # Marker file is best-effort. Never let a recording failure
370
+ # disturb the scheduler's hot path.
371
+ pass
372
+
373
+ def inc(self, amount=1):
374
+ self._record("inc", amount)
375
+
376
+ def set(self, value):
377
+ self._record("set", value)
378
+
379
+ def observe(self, value):
380
+ self._record("observe", value)
381
+
382
+
383
+ class _RecordingSchedulerCollector(SchedulerMetricsCollector):
384
+ """A custom ``SchedulerMetricsCollector`` that records every emission to
385
+ a filesystem marker.
386
+
387
+ Achieves both halves of the reviewer's request:
388
+
389
+ 1. Its mere instantiation proves that ``resolve_collector_class()``
390
+ picked the injected subclass inside the scheduler subprocess
391
+ (the marker file exists).
392
+ 2. Each emission lands on the ``_FileRecordingMetric`` double, which
393
+ writes a JSON line. The test reads the file after shutdown and
394
+ asserts that a few representative metrics received positive values.
395
+
396
+ Defined at module level so the scheduler subprocess can unpickle it.
397
+ """
398
+
399
+ _counter_cls = _FileRecordingMetric
400
+ _gauge_cls = _FileRecordingMetric
401
+ _histogram_cls = _FileRecordingMetric
402
+ _summary_cls = _FileRecordingMetric
403
+
404
+
405
+ def _clear_sglang_metrics_from_default_registry() -> None:
406
+ """Drop any ``sglang:`` metrics left in the process-global prometheus default
407
+ REGISTRY by a prior in-process Engine boot. Without this, a second in-process
408
+ ``sgl.Engine(enable_metrics=True)`` in the same test process re-registers the
409
+ same Counters and raises "Duplicated timeseries in CollectorRegistry"."""
410
+ from prometheus_client import REGISTRY
411
+
412
+ for collector in list(getattr(REGISTRY, "_collector_to_names", {})):
413
+ names = REGISTRY._collector_to_names.get(collector, set())
414
+ if any(name.startswith("sglang:") for name in names):
415
+ REGISTRY.unregister(collector)
416
+
417
+
418
+ class TestStatLoggersDI(CustomTestCase):
419
+ """Verify that a custom MetricsCollector subclass passed through
420
+ ``ServerArgs.stat_loggers`` is the one instantiated inside the
421
+ scheduler subprocess."""
422
+
423
+ def setUp(self) -> None:
424
+ _clear_sglang_metrics_from_default_registry()
425
+ try:
426
+ os.unlink(_DI_MARKER_PATH)
427
+ except FileNotFoundError:
428
+ pass
429
+
430
+ def tearDown(self) -> None:
431
+ try:
432
+ os.unlink(_DI_MARKER_PATH)
433
+ except FileNotFoundError:
434
+ pass
435
+
436
+ def test_engine_custom_scheduler_collector(self):
437
+ import sglang as sgl
438
+
439
+ engine = sgl.Engine(
440
+ model_path=_MODEL_NAME,
441
+ enable_metrics=True,
442
+ stat_loggers={
443
+ STAT_LOGGER_ROLE_SCHEDULER: _MarkingSchedulerCollector,
444
+ },
445
+ )
446
+ try:
447
+ # One small generation triggers scheduler init, which is where
448
+ # resolve_collector_class() picks the injected subclass.
449
+ engine.generate("Hello", {"max_new_tokens": 4})
450
+ finally:
451
+ engine.shutdown()
452
+
453
+ self.assertTrue(
454
+ os.path.exists(_DI_MARKER_PATH),
455
+ "Custom SchedulerMetricsCollector was not instantiated; "
456
+ "stat_loggers DI did not take effect.",
457
+ )
458
+
459
+
460
+ class TestStatLoggersDIRecording(CustomTestCase):
461
+ """Boot a real ``sgl.Engine`` with a custom scheduler collector that
462
+ swaps the four DI hook classes for a FakeRayMetric-style recording
463
+ double and verify that emissions land on the double.
464
+
465
+ Combines the discriminating power of ``_RecordingSchedulerCollector``
466
+ (proves the subclass was actually instantiated in the scheduler
467
+ subprocess) with value recording (proves emissions flow through to the
468
+ metric instance). Per the reviewer's framing, we pick a few
469
+ representative metrics rather than enumerate all of them.
470
+ """
471
+
472
+ def setUp(self) -> None:
473
+ # Avoid stale PROMETHEUS_MULTIPROC_DIR from prior in-process Engine boots.
474
+ os.environ.pop("PROMETHEUS_MULTIPROC_DIR", None)
475
+ _clear_sglang_metrics_from_default_registry()
476
+ try:
477
+ os.unlink(_DI_RECORDING_MARKER_PATH)
478
+ except FileNotFoundError:
479
+ pass
480
+
481
+ def tearDown(self) -> None:
482
+ try:
483
+ os.unlink(_DI_RECORDING_MARKER_PATH)
484
+ except FileNotFoundError:
485
+ pass
486
+
487
+ def _read_marker(self):
488
+ """Return all recorded emissions as a list of dicts.
489
+
490
+ Each entry has keys ``name`` (str), ``op`` (one of ``inc``/``set``/
491
+ ``observe``), ``value`` (numeric) and ``tags`` (dict).
492
+ """
493
+ entries = []
494
+ with open(_DI_RECORDING_MARKER_PATH) as f:
495
+ for line in f:
496
+ line = line.strip()
497
+ if not line:
498
+ continue
499
+ entries.append(json.loads(line))
500
+ return entries
501
+
502
+ def test_engine_custom_scheduler_collector_emits_through_fake_metric(self):
503
+ import sglang as sgl
504
+
505
+ engine = sgl.Engine(
506
+ model_path=_MODEL_NAME,
507
+ enable_metrics=True,
508
+ stat_loggers={
509
+ STAT_LOGGER_ROLE_SCHEDULER: _RecordingSchedulerCollector,
510
+ },
511
+ )
512
+ try:
513
+ # One small generation triggers scheduler init (which is where
514
+ # resolve_collector_class picks the injected subclass) and is
515
+ # enough to produce gauge ``.set()`` emissions on the basic
516
+ # queue-state metrics.
517
+ engine.generate("Hello", {"max_new_tokens": 4})
518
+ finally:
519
+ engine.shutdown()
520
+
521
+ # Discrimination: the marker file exists, proving the custom
522
+ # subclass was instantiated inside the scheduler subprocess.
523
+ self.assertTrue(
524
+ os.path.exists(_DI_RECORDING_MARKER_PATH),
525
+ "Custom SchedulerMetricsCollector was not instantiated; "
526
+ "stat_loggers DI did not take effect.",
527
+ )
528
+
529
+ entries = self._read_marker()
530
+ self.assertGreater(
531
+ len(entries),
532
+ 0,
533
+ "Marker file exists but contains no emissions; "
534
+ "the recording double was not wired through the DI hooks.",
535
+ )
536
+
537
+ # Value verification: pick a few representative metrics and check
538
+ # that they actually received emissions with sensible shapes. We do
539
+ # not enumerate all metrics; the reviewer's framing was "just pick
540
+ # a few".
541
+ by_name = {}
542
+ for e in entries:
543
+ by_name.setdefault(e["name"], []).append(e)
544
+
545
+ # 1) num_running_reqs: a Gauge that the scheduler ``.set()``s every
546
+ # stats tick. After one generation it should have at least one
547
+ # emission.
548
+ self.assertIn(
549
+ "sglang:num_running_reqs",
550
+ by_name,
551
+ f"Expected num_running_reqs emissions, saw: {sorted(by_name)[:10]}",
552
+ )
553
+ running_ops = {e["op"] for e in by_name["sglang:num_running_reqs"]}
554
+ self.assertIn("set", running_ops)
555
+
556
+ # 2) num_queue_reqs: same shape, different metric. Two metrics from
557
+ # the same collector firing confirm the DI hook applied uniformly.
558
+ self.assertIn("sglang:num_queue_reqs", by_name)
559
+ queue_ops = {e["op"] for e in by_name["sglang:num_queue_reqs"]}
560
+ self.assertIn("set", queue_ops)
561
+
562
+ # 3) Tag propagation: every recorded emission must carry the labels
563
+ # keys the scheduler installed (model_name, engine_type, ...).
564
+ any_running = by_name["sglang:num_running_reqs"][0]
565
+ self.assertIn("model_name", any_running["tags"])
566
+ self.assertEqual(any_running["tags"]["model_name"], _MODEL_NAME)
567
+
568
+
569
+ class TestComputeRoutingKeyStats(unittest.TestCase):
570
+ def test_empty(self):
571
+ num_unique, req_counts = compute_routing_key_stats([])
572
+ self.assertEqual(num_unique, 0)
573
+ self.assertEqual(req_counts, [])
574
+
575
+ def test_all_none(self):
576
+ num_unique, req_counts = compute_routing_key_stats([None, None, None])
577
+ self.assertEqual(num_unique, 0)
578
+ self.assertEqual(req_counts, [])
579
+
580
+ def test_with_none(self):
581
+ num_unique, req_counts = compute_routing_key_stats([None, "key1", None])
582
+ self.assertEqual(num_unique, 1)
583
+ self.assertEqual(req_counts, [1])
584
+
585
+ def test_single_key_multiple_reqs(self):
586
+ num_unique, req_counts = compute_routing_key_stats(["key1"] * 5)
587
+ self.assertEqual(num_unique, 1)
588
+ self.assertEqual(req_counts, [5])
589
+
590
+ def test_distribution(self):
591
+ routing_keys = ["key1"] * 5 + ["key2"] * 1 + ["key3"] * 15 + ["key4"] * 250
592
+ num_unique, req_counts = compute_routing_key_stats(routing_keys)
593
+ self.assertEqual(num_unique, 4)
594
+ self.assertEqual(sorted(req_counts), [1, 5, 15, 250])
595
+
596
+
597
+ if __name__ == "__main__":
598
+ unittest.main()
asian_ai/performance/SGLang/test/registered/observability/test_priority_metrics.py ADDED
@@ -0,0 +1,227 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import unittest
2
+ from typing import Dict, List
3
+ from unittest.mock import Mock
4
+
5
+ import requests
6
+ from prometheus_client.parser import text_string_to_metric_families
7
+ from prometheus_client.samples import Sample
8
+
9
+ from sglang.srt.observability.metrics_collector import QueueCount
10
+ from sglang.srt.utils import kill_process_tree
11
+ from sglang.test.ci.ci_register import (
12
+ register_amd_ci,
13
+ register_cpu_ci,
14
+ register_cuda_ci,
15
+ )
16
+ from sglang.test.test_utils import (
17
+ DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH,
18
+ DEFAULT_URL_FOR_TEST,
19
+ CustomTestCase,
20
+ popen_launch_server,
21
+ )
22
+
23
+ register_cuda_ci(
24
+ est_time=60,
25
+ stage="base-b",
26
+ runner_config="1-gpu-small",
27
+ )
28
+ register_amd_ci(est_time=60, suite="stage-b-test-1-gpu-small-amd")
29
+ register_cpu_ci(est_time=179, suite="base-c-test-cpu")
30
+
31
+ _MODEL_NAME = "Qwen/Qwen3-0.6B"
32
+
33
+
34
+ def _parse_prometheus_metrics(metrics_text: str) -> Dict[str, List[Sample]]:
35
+ result = {}
36
+ for family in text_string_to_metric_families(metrics_text):
37
+ for sample in family.samples:
38
+ if sample.name not in result:
39
+ result[sample.name] = []
40
+ result[sample.name].append(sample)
41
+ return result
42
+
43
+
44
+ def _get_samples_by_name(metrics: Dict[str, List[Sample]], name: str) -> List[Sample]:
45
+ return metrics.get(name, [])
46
+
47
+
48
+ def _get_sample_value_by_labels(samples: List[Sample], labels: Dict[str, str]) -> float:
49
+ for sample in samples:
50
+ if all(sample.labels.get(k) == v for k, v in labels.items()):
51
+ return sample.value
52
+ raise KeyError(f"No sample found with labels {labels}")
53
+
54
+
55
+ class TestQueueCount(CustomTestCase):
56
+ """Unit tests for QueueCount (no server needed)."""
57
+
58
+ def test_queue_count_from_reqs(self):
59
+ """QueueCount correctly counts per-priority breakdown."""
60
+ reqs = [
61
+ Mock(priority=1),
62
+ Mock(priority=1),
63
+ Mock(priority=5),
64
+ Mock(priority=5),
65
+ Mock(priority=10),
66
+ ]
67
+ qc = QueueCount.from_reqs(reqs, enable_priority_scheduling=True)
68
+ self.assertEqual(qc.total, 5)
69
+ self.assertEqual(qc.by_priority, {1: 2, 5: 2, 10: 1})
70
+
71
+ def test_queue_count_from_reqs_disabled(self):
72
+ """Priority scheduling disabled → no breakdown."""
73
+ reqs = [Mock(priority=1), Mock(priority=5)]
74
+ qc = QueueCount.from_reqs(reqs, enable_priority_scheduling=False)
75
+ self.assertEqual(qc.total, 2)
76
+ self.assertIsNone(qc.by_priority)
77
+
78
+ def test_queue_count_empty(self):
79
+ """Empty request list."""
80
+ qc = QueueCount.from_reqs([], enable_priority_scheduling=True)
81
+ self.assertEqual(qc.total, 0)
82
+ self.assertEqual(qc.by_priority, {})
83
+
84
+
85
+ class TestPriorityMetrics(CustomTestCase):
86
+ """Test that priority-based metrics are correctly emitted when
87
+ --enable-priority-scheduling is enabled."""
88
+
89
+ @classmethod
90
+ def setUpClass(cls):
91
+ cls.process = popen_launch_server(
92
+ _MODEL_NAME,
93
+ DEFAULT_URL_FOR_TEST,
94
+ timeout=DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH,
95
+ other_args=[
96
+ "--enable-metrics",
97
+ "--enable-priority-scheduling",
98
+ "--default-priority-value",
99
+ "0",
100
+ ],
101
+ )
102
+
103
+ @classmethod
104
+ def tearDownClass(cls):
105
+ kill_process_tree(cls.process.pid)
106
+
107
+ def test_priority_label_in_gauge_metrics(self):
108
+ """Send requests with different priorities and verify that
109
+ gauge metrics (num_running_reqs, num_queue_reqs) contain
110
+ the priority label dimension."""
111
+
112
+ # Send requests with different priorities to populate metrics
113
+ for priority in [1, 5, 10]:
114
+ response = requests.post(
115
+ f"{DEFAULT_URL_FOR_TEST}/generate",
116
+ json={
117
+ "text": "Hello",
118
+ "sampling_params": {"temperature": 0, "max_new_tokens": 5},
119
+ "priority": priority,
120
+ },
121
+ )
122
+ self.assertEqual(response.status_code, 200)
123
+
124
+ # Fetch metrics
125
+ metrics_response = requests.get(f"{DEFAULT_URL_FOR_TEST}/metrics")
126
+ self.assertEqual(metrics_response.status_code, 200)
127
+ metrics = _parse_prometheus_metrics(metrics_response.text)
128
+
129
+ # Verify priority label exists on queue gauge metrics
130
+ for metric_name in ["sglang:num_running_reqs", "sglang:num_queue_reqs"]:
131
+ samples = _get_samples_by_name(metrics, metric_name)
132
+ self.assertGreater(len(samples), 0, f"No samples found for {metric_name}")
133
+
134
+ # Should have at least one sample with a non-empty priority label
135
+ # (the total has priority="" and per-priority has priority="<int>")
136
+ priority_labels = {s.labels.get("priority", "") for s in samples}
137
+ self.assertIn(
138
+ "",
139
+ priority_labels,
140
+ f"{metric_name}: missing total (priority='') sample",
141
+ )
142
+
143
+ def test_priority_label_in_histogram_metrics(self):
144
+ """Send requests with different priorities and verify that
145
+ histogram metrics (TTFT, ITL, e2e latency) contain the priority label."""
146
+
147
+ for priority in [1, 5]:
148
+ response = requests.post(
149
+ f"{DEFAULT_URL_FOR_TEST}/generate",
150
+ json={
151
+ "text": "The capital of France is",
152
+ "sampling_params": {"temperature": 0, "max_new_tokens": 20},
153
+ "priority": priority,
154
+ },
155
+ )
156
+ self.assertEqual(response.status_code, 200)
157
+
158
+ metrics_response = requests.get(f"{DEFAULT_URL_FOR_TEST}/metrics")
159
+ self.assertEqual(metrics_response.status_code, 200)
160
+ metrics = _parse_prometheus_metrics(metrics_response.text)
161
+
162
+ # Check histogram metrics have priority label with per-priority breakdown
163
+ histogram_metrics = [
164
+ "sglang:time_to_first_token_seconds",
165
+ "sglang:e2e_request_latency_seconds",
166
+ ]
167
+ for metric_name in histogram_metrics:
168
+ # Histogram metrics are emitted as _sum, _count, _bucket
169
+ count_name = f"{metric_name}_count"
170
+ samples = _get_samples_by_name(metrics, count_name)
171
+ self.assertGreater(len(samples), 0, f"No samples found for {count_name}")
172
+ # At least one sample should have a non-empty priority label
173
+ priority_values = {s.labels.get("priority", "") for s in samples}
174
+ non_empty = priority_values - {""}
175
+ self.assertGreater(
176
+ len(non_empty),
177
+ 0,
178
+ f"{count_name}: expected per-priority samples, "
179
+ f"got priority labels: {priority_values}",
180
+ )
181
+ # Verify that both priority="1" and priority="5" have count > 0
182
+ for expected_priority in ["1", "5"]:
183
+ matching = [
184
+ s for s in samples if s.labels.get("priority") == expected_priority
185
+ ]
186
+ self.assertGreater(
187
+ len(matching),
188
+ 0,
189
+ f"{count_name}: no sample with priority='{expected_priority}'",
190
+ )
191
+ self.assertGreater(
192
+ matching[0].value,
193
+ 0,
194
+ f"{count_name}: priority='{expected_priority}' count should be > 0",
195
+ )
196
+
197
+ def test_default_priority_value(self):
198
+ """Requests without explicit priority should use --default-priority-value (0)."""
199
+
200
+ # Send request WITHOUT priority — should get default priority 0
201
+ response = requests.post(
202
+ f"{DEFAULT_URL_FOR_TEST}/generate",
203
+ json={
204
+ "text": "Hello world",
205
+ "sampling_params": {"temperature": 0, "max_new_tokens": 5},
206
+ },
207
+ )
208
+ self.assertEqual(response.status_code, 200)
209
+
210
+ metrics_response = requests.get(f"{DEFAULT_URL_FOR_TEST}/metrics")
211
+ self.assertEqual(metrics_response.status_code, 200)
212
+ metrics = _parse_prometheus_metrics(metrics_response.text)
213
+
214
+ # Check that e2e latency has samples with priority="0" (the default)
215
+ e2e_count = _get_samples_by_name(
216
+ metrics, "sglang:e2e_request_latency_seconds_count"
217
+ )
218
+ priority_values = {s.labels.get("priority", "") for s in e2e_count}
219
+ self.assertIn(
220
+ "0",
221
+ priority_values,
222
+ f"Expected priority='0' from default, got: {priority_values}",
223
+ )
224
+
225
+
226
+ if __name__ == "__main__":
227
+ unittest.main()
asian_ai/performance/SGLang/test/registered/observability/test_tracing.py ADDED
@@ -0,0 +1,557 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Integration tests for tracing with a lightweight in-process OTLP collector.
2
+
3
+ This module implements a minimal OTLP collector that receives traces via gRPC
4
+ and stores them in memory for test assertions, eliminating the need for
5
+ Docker-based opentelemetry-collector and file I/O.
6
+ """
7
+
8
+ import os
9
+
10
+ # Configure OTLP exporter for faster test execution
11
+ # Must be set before importing sglang trace module
12
+ os.environ.setdefault("SGLANG_OTLP_EXPORTER_SCHEDULE_DELAY_MILLIS", "50")
13
+ os.environ.setdefault("SGLANG_OTLP_EXPORTER_MAX_EXPORT_BATCH_SIZE", "4")
14
+
15
+ import logging
16
+ import multiprocessing as mp
17
+ import time
18
+ import unittest
19
+ from dataclasses import dataclass
20
+ from typing import List, Optional, Union
21
+
22
+ import requests
23
+ import zmq
24
+
25
+ from sglang import Engine
26
+ from sglang.srt.observability.req_time_stats import RequestStage
27
+ from sglang.srt.observability.trace import (
28
+ TraceReqContext,
29
+ TraceSliceContext,
30
+ get_cur_time_ns,
31
+ process_tracing_init,
32
+ set_global_trace_level,
33
+ trace_set_thread_info,
34
+ )
35
+ from sglang.srt.utils import kill_process_tree
36
+ from sglang.srt.utils.network import get_zmq_socket
37
+ from sglang.test.ci.ci_register import register_amd_ci, register_cuda_ci
38
+ from sglang.test.test_utils import (
39
+ DEFAULT_SMALL_MODEL_NAME_FOR_TEST,
40
+ DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH,
41
+ DEFAULT_URL_FOR_TEST,
42
+ CustomTestCase,
43
+ popen_launch_server,
44
+ )
45
+
46
+ logger = logging.getLogger(__name__)
47
+
48
+ # CI registration
49
+ register_cuda_ci(est_time=113, stage="extra-a", runner_config="1-gpu-small")
50
+ register_amd_ci(est_time=113, suite="stage-b-test-1-gpu-small-amd")
51
+
52
+
53
+ # ============================================================================
54
+ # Lightweight OTLP Collector (shared across tracing tests)
55
+ # ============================================================================
56
+
57
+ from sglang.test.otel_collector import LightweightOtlpCollector, Span # noqa: F401
58
+
59
+ # ============================================================================
60
+ # Test Helper Functions
61
+ # ============================================================================
62
+
63
+
64
+ def _get_span_names_by_level(level: int) -> List[str]:
65
+ """Get expected span names for a given trace level.
66
+
67
+ Based on RequestStage definitions in req_time_stats.py:
68
+ - Each RequestStage has a level attribute indicating minimum trace level required
69
+ - Spans with level <= current trace level will be exported
70
+ """
71
+ span_names = []
72
+ # RequestStage is a class with class attributes that are RequestStageConfig instances
73
+ for attr_name in dir(RequestStage):
74
+ if attr_name.startswith("_"):
75
+ continue
76
+ attr = getattr(RequestStage, attr_name)
77
+ # Check if it's a RequestStageConfig (has stage_name and level attributes)
78
+ if hasattr(attr, "stage_name") and hasattr(attr, "level"):
79
+ if attr.level <= level and attr.stage_name:
80
+ span_names.append(attr.stage_name)
81
+ return span_names
82
+
83
+
84
+ # Pre-computed span names by level for efficiency
85
+ SPAN_NAMES_LEVEL_1 = _get_span_names_by_level(1)
86
+ SPAN_NAMES_LEVEL_2 = _get_span_names_by_level(2)
87
+ SPAN_NAMES_LEVEL_3 = _get_span_names_by_level(3)
88
+
89
+ # Common span names expected in typical inference requests
90
+ # Level 1: Basic request lifecycle
91
+ EXPECTED_SPANS_LEVEL_1 = [
92
+ RequestStage.PREFILL_FORWARD.stage_name,
93
+ RequestStage.DECODE_FORWARD.stage_name,
94
+ ]
95
+
96
+ # Level 2: More detailed including dispatch
97
+ EXPECTED_SPANS_LEVEL_2 = EXPECTED_SPANS_LEVEL_1 + [
98
+ RequestStage.REQUEST_PROCESS.stage_name,
99
+ ]
100
+
101
+ # Level 3: Most detailed including internal operations
102
+ EXPECTED_SPANS_LEVEL_3 = EXPECTED_SPANS_LEVEL_2 + [
103
+ RequestStage.DECODE_LOOP.stage_name,
104
+ ]
105
+
106
+
107
+ @dataclass
108
+ class Req:
109
+ rid: int
110
+ req_context: Optional[Union[TraceReqContext]] = None
111
+
112
+
113
+ def _subprocess_worker():
114
+ """Worker function for subprocess trace context propagation test.
115
+ Must be at module level for pickle compatibility with spawn.
116
+ """
117
+ process_tracing_init("127.0.0.1:4317", "test")
118
+ trace_set_thread_info("Sub Process")
119
+
120
+ context = zmq.Context(2)
121
+ recv_from_main = get_zmq_socket(context, zmq.PULL, "ipc:///tmp/zmq_test.ipc", True)
122
+
123
+ try:
124
+ req = recv_from_main.recv_pyobj()
125
+ req.req_context.rebuild_thread_context()
126
+ req.req_context.trace_slice_start("work", level=1)
127
+ time.sleep(0.2)
128
+ req.req_context.trace_slice_end("work", level=1, thread_finish_flag=True)
129
+ finally:
130
+ recv_from_main.close()
131
+ context.term()
132
+
133
+
134
+ # ============================================================================
135
+ # Test Cases
136
+ # ============================================================================
137
+
138
+
139
+ class TestTracePackage(CustomTestCase):
140
+ """Unit tests for tracing package API without server/engine."""
141
+
142
+ def setUp(self):
143
+ self.collector = None
144
+
145
+ def tearDown(self):
146
+ if self.collector:
147
+ self.collector.stop()
148
+ self.collector = None
149
+
150
+ def _start_collector(self):
151
+ """Start the lightweight OTLP collector."""
152
+ self.collector = LightweightOtlpCollector()
153
+ self.collector.start()
154
+ time.sleep(0.2)
155
+
156
+ def test_slice_simple(self):
157
+ """Unit test: simple slice trace API."""
158
+ self._start_collector()
159
+
160
+ try:
161
+ process_tracing_init("127.0.0.1:4317", "test")
162
+ trace_set_thread_info("Test")
163
+ set_global_trace_level(3)
164
+ req_context = TraceReqContext(0)
165
+ req_context.trace_req_start()
166
+ req_context.trace_slice_start("test slice", level=1)
167
+ time.sleep(0.1)
168
+ req_context.trace_slice_end("test slice", level=1)
169
+ req_context.trace_req_finish()
170
+
171
+ time.sleep(0.3)
172
+
173
+ self.assertTrue(
174
+ self.collector.has_span("test slice"),
175
+ f"Expected span 'test slice', got {self.collector.get_span_names()}",
176
+ )
177
+ finally:
178
+ pass
179
+
180
+ def test_slice_complex(self):
181
+ """Unit test: complex slice trace with events."""
182
+ self._start_collector()
183
+
184
+ try:
185
+ process_tracing_init("127.0.0.1:4317", "test")
186
+ trace_set_thread_info("Test")
187
+ set_global_trace_level(3)
188
+ req_context = TraceReqContext(0)
189
+ req_context.trace_req_start()
190
+
191
+ t1 = get_cur_time_ns()
192
+ time.sleep(0.1)
193
+ req_context.trace_event("event test", 1)
194
+ t2 = get_cur_time_ns()
195
+ time.sleep(0.1)
196
+ t3 = get_cur_time_ns()
197
+
198
+ slice1 = TraceSliceContext("slice A", t1, t2)
199
+ slice2 = TraceSliceContext("slice B", t2, t3)
200
+ req_context.trace_slice(slice1)
201
+ req_context.trace_slice(slice2, thread_finish_flag=True)
202
+ req_context.trace_req_finish()
203
+
204
+ time.sleep(0.3)
205
+
206
+ self.assertTrue(
207
+ self.collector.has_all_spans(["slice A", "slice B"]),
208
+ f"Expected spans 'slice A' and 'slice B', got {self.collector.get_span_names()}",
209
+ )
210
+ finally:
211
+ pass
212
+
213
+ def test_context_propagate(self):
214
+ """Unit test: trace context propagation across processes via ZMQ."""
215
+ self._start_collector()
216
+
217
+ ctx = mp.get_context("spawn")
218
+
219
+ context = zmq.Context(2)
220
+ send_to_subproc = get_zmq_socket(
221
+ context, zmq.PUSH, "ipc:///tmp/zmq_test.ipc", False
222
+ )
223
+
224
+ try:
225
+ process_tracing_init("127.0.0.1:4317", "test")
226
+ trace_set_thread_info("Main Process")
227
+
228
+ subproc = ctx.Process(target=_subprocess_worker)
229
+ subproc.start()
230
+
231
+ time.sleep(0.3)
232
+
233
+ req = Req(rid=0)
234
+ req.req_context = TraceReqContext(0)
235
+ req.req_context.trace_req_start()
236
+ req.req_context.trace_slice_start("dispatch", level=1)
237
+ time.sleep(0.2)
238
+ send_to_subproc.send_pyobj(req)
239
+ req.req_context.trace_slice_end("dispatch", level=1)
240
+
241
+ subproc.join()
242
+ req.req_context.trace_req_finish()
243
+
244
+ time.sleep(0.5)
245
+
246
+ self.assertTrue(
247
+ self.collector.has_all_spans(["dispatch", "work"]),
248
+ f"Expected spans 'dispatch' and 'work', got {self.collector.get_span_names()}",
249
+ )
250
+ finally:
251
+ send_to_subproc.close()
252
+ context.term()
253
+
254
+
255
+ class TestTraceServer(CustomTestCase):
256
+ """Integration tests for tracing with server - starts server once for all tests."""
257
+
258
+ @classmethod
259
+ def setUpClass(cls):
260
+ """Start collector and server once for all tests."""
261
+ cls.collector = LightweightOtlpCollector()
262
+ cls.collector.start()
263
+ time.sleep(0.2)
264
+
265
+ cls.process = popen_launch_server(
266
+ DEFAULT_SMALL_MODEL_NAME_FOR_TEST,
267
+ DEFAULT_URL_FOR_TEST,
268
+ timeout=DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH,
269
+ other_args=[
270
+ "--enable-trace",
271
+ "--otlp-traces-endpoint",
272
+ "127.0.0.1:4317",
273
+ ],
274
+ )
275
+
276
+ response = requests.get(f"{DEFAULT_URL_FOR_TEST}/health_generate")
277
+ assert response.status_code == 200
278
+
279
+ # Wait for warmup spans to be exported
280
+ cls.collector.clear()
281
+
282
+ @classmethod
283
+ def tearDownClass(cls):
284
+ if cls.process:
285
+ kill_process_tree(cls.process.pid)
286
+ if cls.collector:
287
+ cls.collector.stop()
288
+
289
+ def setUp(self):
290
+ """Wait for spans to be drained before each test."""
291
+ max_wait_seconds = 10
292
+ check_interval = 0.2
293
+ elapsed = 0
294
+ consecutive_zero_count = 0
295
+ required_consecutive_zeros = 3
296
+
297
+ while elapsed < max_wait_seconds:
298
+ span_count = self.collector.count_spans()
299
+ if span_count == 0:
300
+ consecutive_zero_count += 1
301
+ if consecutive_zero_count >= required_consecutive_zeros:
302
+ break
303
+ else:
304
+ consecutive_zero_count = 0
305
+ self.collector.clear()
306
+ time.sleep(check_interval)
307
+ elapsed += check_interval
308
+ else:
309
+ raise RuntimeError(
310
+ f"Timeout waiting for spans to drain after {max_wait_seconds}s. "
311
+ f"Remaining spans: {self.collector.count_spans()}"
312
+ )
313
+
314
+ def _send_request_and_wait(
315
+ self, text, max_new_tokens=32, stream=True, trace_level=None
316
+ ):
317
+ """Helper to send a request and wait for spans."""
318
+ if trace_level is not None:
319
+ response = requests.get(
320
+ f"{DEFAULT_URL_FOR_TEST}/set_trace_level?level={trace_level}"
321
+ )
322
+ self.assertEqual(response.status_code, 200)
323
+ self.collector.clear()
324
+
325
+ response = requests.post(
326
+ f"{DEFAULT_URL_FOR_TEST}/generate",
327
+ json={
328
+ "text": text,
329
+ "sampling_params": {
330
+ "temperature": 0,
331
+ "max_new_tokens": max_new_tokens,
332
+ },
333
+ "stream": stream,
334
+ },
335
+ stream=stream,
336
+ )
337
+ if stream:
338
+ for _ in response.iter_lines(decode_unicode=False):
339
+ pass
340
+ else:
341
+ self.assertEqual(response.status_code, 200)
342
+
343
+ time.sleep(1)
344
+
345
+ def test_trace_level_0(self):
346
+ """Test trace level 0 does not export any spans."""
347
+ self._send_request_and_wait("Hello world", max_new_tokens=5, trace_level=0)
348
+ self.assertEqual(
349
+ self.collector.count_spans(),
350
+ 0,
351
+ f"Spans collected but expected none: {sorted(self.collector.get_span_names())}",
352
+ )
353
+
354
+ def test_trace_level_1(self):
355
+ """Test trace level 1 exports basic request lifecycle spans."""
356
+ self._send_request_and_wait("The capital of France is", trace_level=1)
357
+
358
+ self.assertGreater(
359
+ self.collector.count_spans(),
360
+ 0,
361
+ "No spans collected but expected some",
362
+ )
363
+
364
+ span_names = self.collector.get_span_names()
365
+ matched = [name for name in EXPECTED_SPANS_LEVEL_1 if name in span_names]
366
+ self.assertGreater(
367
+ len(matched),
368
+ 0,
369
+ f"No expected spans found. Expected any of {EXPECTED_SPANS_LEVEL_1}, "
370
+ f"got {sorted(span_names)}",
371
+ )
372
+
373
+ def test_trace_level_2(self):
374
+ """Test trace level 2 exports more detailed spans."""
375
+ self._send_request_and_wait("What is AI?", trace_level=2)
376
+
377
+ span_names = self.collector.get_span_names()
378
+ matched = [name for name in EXPECTED_SPANS_LEVEL_2 if name in span_names]
379
+ self.assertGreater(
380
+ len(matched),
381
+ 0,
382
+ f"No expected spans found. Expected any of {EXPECTED_SPANS_LEVEL_2}, "
383
+ f"got {sorted(span_names)}",
384
+ )
385
+
386
+ def test_trace_level_3(self):
387
+ """Test trace level 3 exports most detailed spans."""
388
+ self._send_request_and_wait("Explain quantum computing", trace_level=3)
389
+
390
+ span_names = self.collector.get_span_names()
391
+ matched = [name for name in EXPECTED_SPANS_LEVEL_3 if name in span_names]
392
+ self.assertGreater(
393
+ len(matched),
394
+ 0,
395
+ f"No expected spans found. Expected any of {EXPECTED_SPANS_LEVEL_3}, "
396
+ f"got {sorted(span_names)}",
397
+ )
398
+
399
+ def test_batch_request(self):
400
+ """Test tracing with batch requests (multiple prompts in one request)."""
401
+ response = requests.get(f"{DEFAULT_URL_FOR_TEST}/set_trace_level?level=1")
402
+ self.assertEqual(response.status_code, 200)
403
+ self.collector.clear()
404
+
405
+ batch_size = 4
406
+ prompts = ["The capital of France is"] * batch_size
407
+ response = requests.post(
408
+ f"{DEFAULT_URL_FOR_TEST}/generate",
409
+ json={
410
+ "text": prompts,
411
+ "sampling_params": {
412
+ "temperature": 0,
413
+ "max_new_tokens": 10,
414
+ },
415
+ "stream": False,
416
+ },
417
+ )
418
+ self.assertEqual(response.status_code, 200)
419
+
420
+ time.sleep(0.5)
421
+
422
+ self.assertGreater(
423
+ self.collector.count_spans(),
424
+ 0,
425
+ "No spans collected from batch request",
426
+ )
427
+
428
+ all_spans = self.collector.get_spans()
429
+ request_spans = [
430
+ s for s in all_spans if s.name == RequestStage.PREFILL_FORWARD.stage_name
431
+ ]
432
+ self.assertEqual(
433
+ len(request_spans),
434
+ batch_size,
435
+ f"Expected {batch_size} prefill_forward spans, got {len(request_spans)}",
436
+ )
437
+
438
+ def test_parallel_sample(self):
439
+ """Test tracing with parallel sampling (n > 1 in sampling_params)."""
440
+ response = requests.get(f"{DEFAULT_URL_FOR_TEST}/set_trace_level?level=1")
441
+ self.assertEqual(response.status_code, 200)
442
+ self.collector.clear()
443
+
444
+ # parallel_sample_num is controlled by 'n' in sampling_params
445
+ parallel_num = 4
446
+ response = requests.post(
447
+ f"{DEFAULT_URL_FOR_TEST}/generate",
448
+ json={
449
+ "text": "The capital of France is",
450
+ "sampling_params": {
451
+ "temperature": 0.5, # Need non-zero temp for parallel sampling
452
+ "max_new_tokens": 10,
453
+ "n": parallel_num,
454
+ },
455
+ "stream": False,
456
+ },
457
+ )
458
+ self.assertEqual(response.status_code, 200)
459
+
460
+ time.sleep(0.5)
461
+
462
+ self.assertGreater(
463
+ self.collector.count_spans(),
464
+ 0,
465
+ "No spans collected from parallel sample request",
466
+ )
467
+
468
+ # With parallel sampling, we expect prefill spans for each parallel sample
469
+ all_spans = self.collector.get_spans()
470
+ request_spans = [
471
+ s for s in all_spans if s.name == RequestStage.PREFILL_FORWARD.stage_name
472
+ ]
473
+ self.assertGreaterEqual(
474
+ len(request_spans),
475
+ 1,
476
+ f"Expected at least 1 prefill_forward span, got {len(request_spans)}",
477
+ )
478
+
479
+
480
+ class TestTraceEngine(CustomTestCase):
481
+ """Integration tests for tracing with Engine API - each test creates its own engine."""
482
+
483
+ def setUp(self):
484
+ self.collector = None
485
+
486
+ def tearDown(self):
487
+ if self.collector:
488
+ self.collector.stop()
489
+ self.collector = None
490
+
491
+ def _start_collector(self):
492
+ """Start the lightweight OTLP collector."""
493
+ self.collector = LightweightOtlpCollector()
494
+ self.collector.start()
495
+ time.sleep(0.2)
496
+
497
+ def test_trace_engine_enable(self):
498
+ """Test tracing with Engine API."""
499
+ self._start_collector()
500
+
501
+ prompt = "Today is a sunny day and I like"
502
+ model_path = DEFAULT_SMALL_MODEL_NAME_FOR_TEST
503
+ sampling_params = {"temperature": 0, "max_new_tokens": 8}
504
+
505
+ engine = Engine(
506
+ model_path=model_path,
507
+ random_seed=42,
508
+ enable_trace=True,
509
+ otlp_traces_endpoint="localhost:4317",
510
+ )
511
+
512
+ try:
513
+ engine.generate(prompt, sampling_params)
514
+ time.sleep(0.5)
515
+
516
+ self.assertGreater(
517
+ self.collector.count_spans(),
518
+ 0,
519
+ "No spans collected from Engine.generate",
520
+ )
521
+ self.assertTrue(
522
+ self.collector.has_any_span([RequestStage.PREFILL_FORWARD.stage_name]),
523
+ f"Expected prefill_forward span, got {self.collector.get_span_names()}",
524
+ )
525
+ finally:
526
+ engine.shutdown()
527
+
528
+ def test_trace_engine_encode(self):
529
+ """Test tracing with Engine encode API."""
530
+ self._start_collector()
531
+
532
+ prompt = "Today is a sunny day and I like"
533
+ model_path = DEFAULT_SMALL_MODEL_NAME_FOR_TEST
534
+
535
+ engine = Engine(
536
+ model_path=model_path,
537
+ random_seed=42,
538
+ enable_trace=True,
539
+ otlp_traces_endpoint="localhost:4317",
540
+ is_embedding=True,
541
+ )
542
+
543
+ try:
544
+ engine.encode(prompt)
545
+ time.sleep(0.5)
546
+
547
+ self.assertGreater(
548
+ self.collector.count_spans(),
549
+ 0,
550
+ "No spans collected from Engine.encode",
551
+ )
552
+ finally:
553
+ engine.shutdown()
554
+
555
+
556
+ if __name__ == "__main__":
557
+ unittest.main()
asian_ai/performance/SGLang/test/registered/observability/test_tracing_disaggregation.py ADDED
@@ -0,0 +1,237 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Test tracing in PD disaggregation mode."""
2
+
3
+ import os
4
+
5
+ # Configure OTLP exporter for faster test execution
6
+ # Must be set before importing sglang trace module
7
+ os.environ.setdefault("SGLANG_OTLP_EXPORTER_SCHEDULE_DELAY_MILLIS", "50")
8
+ os.environ.setdefault("SGLANG_OTLP_EXPORTER_MAX_EXPORT_BATCH_SIZE", "4")
9
+
10
+ import logging
11
+ import shlex
12
+ import time
13
+ import unittest
14
+ from urllib.parse import urlparse
15
+
16
+ import requests
17
+
18
+ from sglang.srt.observability.mooncake_trace import MooncakeRequestStage
19
+ from sglang.srt.observability.req_time_stats import RequestStage
20
+ from sglang.srt.utils import kill_process_tree
21
+ from sglang.test.ci.ci_register import register_cuda_ci
22
+ from sglang.test.otel_collector import LightweightOtlpCollector
23
+ from sglang.test.server_fixtures.disaggregation_fixture import get_rdma_devices_args
24
+ from sglang.test.test_utils import (
25
+ DEFAULT_MODEL_NAME_FOR_TEST,
26
+ DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH,
27
+ DEFAULT_URL_FOR_TEST,
28
+ CustomTestCase,
29
+ popen_launch_pd_server,
30
+ popen_with_error_check,
31
+ )
32
+ from sglang.utils import wait_for_http_ready
33
+
34
+ logger = logging.getLogger(__name__)
35
+
36
+ # CI registration - PD disaggregation requires 2 GPUs
37
+ register_cuda_ci(est_time=65, stage="base-b", runner_config="2-gpu-large")
38
+
39
+
40
+ class TestTraceDisaggregation(CustomTestCase):
41
+ """Test tracing in PD disaggregation mode."""
42
+
43
+ @classmethod
44
+ def setUpClass(cls):
45
+ # Initialize collector first
46
+ cls.collector = LightweightOtlpCollector()
47
+ cls.collector.start()
48
+ time.sleep(0.2)
49
+
50
+ # Setup PD disaggregation server addresses
51
+ parsed_url = urlparse(DEFAULT_URL_FOR_TEST)
52
+ cls.base_host = parsed_url.hostname
53
+ base_port = str(parsed_url.port)
54
+ cls.lb_port = base_port
55
+ cls.prefill_port = f"{int(base_port) + 100}"
56
+ cls.decode_port = f"{int(base_port) + 200}"
57
+ cls.bootstrap_port = f"{int(base_port) + 500}"
58
+ cls.prefill_url = f"http://{cls.base_host}:{cls.prefill_port}"
59
+ cls.decode_url = f"http://{cls.base_host}:{cls.decode_port}"
60
+ cls.lb_url = f"http://{cls.base_host}:{cls.lb_port}"
61
+ cls.process_lb = None
62
+ cls.process_decode = None
63
+ cls.process_prefill = None
64
+ cls.model = DEFAULT_MODEL_NAME_FOR_TEST
65
+
66
+ # Config transfer backend
67
+ cls.transfer_backend = ["--disaggregation-transfer-backend", "mooncake"]
68
+ cls.rdma_devices = ["--disaggregation-ib-device", get_rdma_devices_args()]
69
+
70
+ # Start prefill server with trace enabled
71
+ prefill_args = [
72
+ "--trust-remote-code",
73
+ "--disaggregation-mode",
74
+ "prefill",
75
+ "--disaggregation-bootstrap-port",
76
+ cls.bootstrap_port,
77
+ "--tp",
78
+ "1",
79
+ "--enable-trace",
80
+ "--otlp-traces-endpoint",
81
+ "localhost:4317",
82
+ "--trace-modules",
83
+ "request,mooncake",
84
+ ]
85
+ prefill_args += cls.transfer_backend + cls.rdma_devices
86
+ cls.process_prefill = popen_launch_pd_server(
87
+ cls.model,
88
+ cls.prefill_url,
89
+ timeout=DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH,
90
+ other_args=prefill_args,
91
+ )
92
+
93
+ # Start decode server with trace enabled
94
+ decode_args = [
95
+ "--trust-remote-code",
96
+ "--disaggregation-mode",
97
+ "decode",
98
+ "--disaggregation-bootstrap-port",
99
+ cls.bootstrap_port,
100
+ "--tp",
101
+ "1",
102
+ "--base-gpu-id",
103
+ "1",
104
+ "--enable-trace",
105
+ "--otlp-traces-endpoint",
106
+ "localhost:4317",
107
+ ]
108
+ decode_args += cls.transfer_backend + cls.rdma_devices
109
+ cls.process_decode = popen_launch_pd_server(
110
+ cls.model,
111
+ cls.decode_url,
112
+ timeout=DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH,
113
+ other_args=decode_args,
114
+ )
115
+
116
+ # Wait for servers to be ready
117
+ wait_for_http_ready(
118
+ url=cls.prefill_url + "/health",
119
+ timeout=DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH,
120
+ process=cls.process_prefill,
121
+ )
122
+ wait_for_http_ready(
123
+ url=cls.decode_url + "/health",
124
+ timeout=DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH,
125
+ process=cls.process_decode,
126
+ )
127
+
128
+ # Start load balancer
129
+ lb_command = [
130
+ "python3",
131
+ "-m",
132
+ "sglang_router.launch_router",
133
+ "--pd-disaggregation",
134
+ "--mini-lb",
135
+ "--prefill",
136
+ cls.prefill_url,
137
+ "--decode",
138
+ cls.decode_url,
139
+ "--host",
140
+ cls.base_host,
141
+ "--port",
142
+ cls.lb_port,
143
+ ]
144
+ print("Starting load balancer:", shlex.join(lb_command))
145
+ cls.process_lb = popen_with_error_check(lb_command)
146
+ wait_for_http_ready(url=cls.lb_url + "/health", process=cls.process_lb)
147
+
148
+ # Wait for warmup spans and clear
149
+ time.sleep(1)
150
+ cls.collector.clear()
151
+
152
+ @classmethod
153
+ def tearDownClass(cls):
154
+ for process in [cls.process_lb, cls.process_decode, cls.process_prefill]:
155
+ if process:
156
+ try:
157
+ kill_process_tree(process.pid)
158
+ except Exception as e:
159
+ print(f"Error killing process {process.pid}: {e}")
160
+ if cls.collector:
161
+ cls.collector.stop()
162
+ time.sleep(5)
163
+
164
+ def setUp(self):
165
+ """Wait for spans to be drained before each test."""
166
+ max_wait_seconds = 10
167
+ check_interval = 0.2
168
+ elapsed = 0
169
+ consecutive_zero_count = 0
170
+ required_consecutive_zeros = 3
171
+
172
+ while elapsed < max_wait_seconds:
173
+ span_count = self.collector.count_spans()
174
+ if span_count == 0:
175
+ consecutive_zero_count += 1
176
+ if consecutive_zero_count >= required_consecutive_zeros:
177
+ break
178
+ else:
179
+ consecutive_zero_count = 0
180
+ self.collector.clear()
181
+ time.sleep(check_interval)
182
+ elapsed += check_interval
183
+ else:
184
+ raise RuntimeError(
185
+ f"Timeout waiting for spans to drain after {max_wait_seconds}s. "
186
+ f"Remaining spans: {self.collector.count_spans()}"
187
+ )
188
+
189
+ def test_disaggregation_transfer_spans(self):
190
+ """Test that disaggregation produces PREFILL_TRANSFER_KV_CACHE and DECODE_TRANSFERRED spans."""
191
+ # Set trace level
192
+ response = requests.get(f"{self.prefill_url}/set_trace_level?level=2")
193
+ self.assertEqual(response.status_code, 200)
194
+ self.collector.clear()
195
+
196
+ # Send a request through load balancer
197
+ response = requests.post(
198
+ f"{self.lb_url}/generate",
199
+ json={
200
+ "text": "The capital of France is",
201
+ "sampling_params": {
202
+ "temperature": 0,
203
+ "max_new_tokens": 10,
204
+ },
205
+ "stream": False,
206
+ },
207
+ )
208
+ self.assertEqual(response.status_code, 200)
209
+
210
+ # Wait for async export
211
+ time.sleep(1)
212
+
213
+ # Verify spans were collected
214
+ self.assertGreater(
215
+ self.collector.count_spans(),
216
+ 0,
217
+ "No spans collected from disaggregation request",
218
+ )
219
+
220
+ # Verify disaggregation-specific spans exist
221
+ span_names = self.collector.get_span_names()
222
+
223
+ # Check for transfer-related spans
224
+ self.assertTrue(
225
+ self.collector.has_all_spans(
226
+ [
227
+ RequestStage.PREFILL_TRANSFER_KV_CACHE.stage_name,
228
+ RequestStage.DECODE_TRANSFERRED.stage_name,
229
+ MooncakeRequestStage.MOONCAKE_WORKER_SEND.stage_name,
230
+ ]
231
+ ),
232
+ f"Expected all disaggregation transfer spans, got {sorted(span_names)}",
233
+ )
234
+
235
+
236
+ if __name__ == "__main__":
237
+ unittest.main()
asian_ai/performance/SGLang/test/registered/openai_server/basic/test_anthropic_server.py ADDED
@@ -0,0 +1,582 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ python3 -m unittest openai_server.basic.test_anthropic_server.TestAnthropicServer.test_simple_messages
3
+ python3 -m unittest openai_server.basic.test_anthropic_server.TestAnthropicServer.test_simple_messages_stream
4
+ python3 -m unittest openai_server.basic.test_anthropic_server.TestAnthropicServer.test_multi_turn_messages
5
+ python3 -m unittest openai_server.basic.test_anthropic_server.TestAnthropicServer.test_system_message_string
6
+ python3 -m unittest openai_server.basic.test_anthropic_server.TestAnthropicServer.test_system_message_blocks
7
+ python3 -m unittest openai_server.basic.test_anthropic_server.TestAnthropicServer.test_max_tokens
8
+ python3 -m unittest openai_server.basic.test_anthropic_server.TestAnthropicServer.test_temperature
9
+ python3 -m unittest openai_server.basic.test_anthropic_server.TestAnthropicServer.test_stop_sequences
10
+ python3 -m unittest openai_server.basic.test_anthropic_server.TestAnthropicServer.test_error_invalid_max_tokens
11
+ python3 -m unittest openai_server.basic.test_anthropic_server.TestAnthropicServer.test_error_empty_messages
12
+ python3 -m unittest openai_server.basic.test_anthropic_server.TestAnthropicServer.test_raw_http_non_streaming
13
+ python3 -m unittest openai_server.basic.test_anthropic_server.TestAnthropicServer.test_raw_http_streaming
14
+ python3 -m unittest openai_server.basic.test_anthropic_server.TestAnthropicServer.test_tool_result_image_content_conversion
15
+ """
16
+
17
+ import json
18
+ import unittest
19
+
20
+ import anthropic
21
+ import requests
22
+
23
+ from sglang.srt.entrypoints.anthropic.protocol import AnthropicMessagesRequest
24
+ from sglang.srt.entrypoints.anthropic.serving import AnthropicServing
25
+ from sglang.srt.utils import kill_process_tree
26
+ from sglang.test.ci.ci_register import register_amd_ci, register_cuda_ci
27
+ from sglang.test.test_utils import (
28
+ DEFAULT_SMALL_MODEL_NAME_FOR_TEST,
29
+ DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH,
30
+ DEFAULT_URL_FOR_TEST,
31
+ CustomTestCase,
32
+ popen_launch_server,
33
+ )
34
+
35
+ register_cuda_ci(est_time=40, stage="base-b", runner_config="1-gpu-small")
36
+ register_amd_ci(est_time=140, suite="stage-b-test-1-gpu-small-amd")
37
+
38
+
39
+ class TestAnthropicServer(CustomTestCase):
40
+ @classmethod
41
+ def setUpClass(cls):
42
+ cls.model = DEFAULT_SMALL_MODEL_NAME_FOR_TEST
43
+ cls.base_url = DEFAULT_URL_FOR_TEST
44
+ cls.api_key = "sk-123456"
45
+ cls.process = popen_launch_server(
46
+ cls.model,
47
+ cls.base_url,
48
+ timeout=DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH,
49
+ api_key=cls.api_key,
50
+ )
51
+ cls.messages_url = cls.base_url + "/v1/messages"
52
+
53
+ @classmethod
54
+ def tearDownClass(cls):
55
+ kill_process_tree(cls.process.pid)
56
+
57
+ def _make_request(self, payload, stream=False):
58
+ """Send a request to the /v1/messages endpoint."""
59
+ headers = {
60
+ "Content-Type": "application/json",
61
+ "Authorization": f"Bearer {self.api_key}",
62
+ }
63
+ return requests.post(
64
+ self.messages_url,
65
+ headers=headers,
66
+ json=payload,
67
+ stream=stream,
68
+ )
69
+
70
+ def _default_payload(self, **overrides):
71
+ """Build a default Anthropic Messages request payload."""
72
+ payload = {
73
+ "model": self.model,
74
+ "max_tokens": 64,
75
+ "messages": [
76
+ {
77
+ "role": "user",
78
+ "content": "What is the capital of France? Answer in a few words.",
79
+ }
80
+ ],
81
+ }
82
+ payload.update(overrides)
83
+ return payload
84
+
85
+ # ---- Non-streaming tests ----
86
+
87
+ def test_tool_result_image_content_conversion(self):
88
+ """Tool-result image blocks should be preserved as OpenAI image_url content."""
89
+ anthropic_request = AnthropicMessagesRequest(
90
+ model=self.model,
91
+ max_tokens=64,
92
+ messages=[
93
+ {
94
+ "role": "user",
95
+ "content": "I have called read_file to get an image. What color is it?",
96
+ },
97
+ {
98
+ "role": "assistant",
99
+ "content": [
100
+ {
101
+ "type": "tool_use",
102
+ "id": "call_123",
103
+ "name": "read_file",
104
+ "input": {"file_path": "/test.png"},
105
+ }
106
+ ],
107
+ },
108
+ {
109
+ "role": "user",
110
+ "content": [
111
+ {
112
+ "type": "tool_result",
113
+ "tool_use_id": "call_123",
114
+ "content": [
115
+ {
116
+ "type": "image",
117
+ "source": {
118
+ "type": "base64",
119
+ "media_type": "image/png",
120
+ "data": "abcd",
121
+ },
122
+ }
123
+ ],
124
+ }
125
+ ],
126
+ },
127
+ ],
128
+ )
129
+
130
+ serving = AnthropicServing(openai_serving_chat=object())
131
+ chat_request = serving._convert_to_chat_completion_request(anthropic_request)
132
+ converted = chat_request.model_dump()
133
+
134
+ tool_messages = [m for m in converted["messages"] if m.get("role") == "tool"]
135
+ self.assertEqual(
136
+ len(tool_messages),
137
+ 1,
138
+ f"Expected one tool message, got: {converted['messages']}",
139
+ )
140
+
141
+ tool_message = tool_messages[0]
142
+ self.assertEqual(tool_message["tool_call_id"], "call_123")
143
+ self.assertIsInstance(tool_message["content"], list)
144
+ self.assertEqual(len(tool_message["content"]), 1)
145
+ self.assertEqual(tool_message["content"][0]["type"], "image_url")
146
+ self.assertEqual(
147
+ tool_message["content"][0]["image_url"]["url"],
148
+ "data:image/png;base64,abcd",
149
+ )
150
+
151
+ def test_simple_messages(self):
152
+ """Test basic non-streaming message request."""
153
+ payload = self._default_payload()
154
+ resp = self._make_request(payload)
155
+ self.assertEqual(resp.status_code, 200, f"Response: {resp.text}")
156
+
157
+ body = resp.json()
158
+ self.assertEqual(body["type"], "message")
159
+ self.assertEqual(body["role"], "assistant")
160
+ self.assertIn("content", body)
161
+ self.assertIsInstance(body["content"], list)
162
+ self.assertTrue(len(body["content"]) > 0)
163
+ self.assertEqual(body["content"][0]["type"], "text")
164
+ self.assertIsInstance(body["content"][0]["text"], str)
165
+ self.assertTrue(len(body["content"][0]["text"]) > 0)
166
+
167
+ # Verify stop reason
168
+ self.assertIn(body["stop_reason"], ["end_turn", "max_tokens", "stop_sequence"])
169
+
170
+ # Verify usage
171
+ self.assertIn("usage", body)
172
+ self.assertIsInstance(body["usage"]["input_tokens"], int)
173
+ self.assertIsInstance(body["usage"]["output_tokens"], int)
174
+ self.assertGreater(body["usage"]["input_tokens"], 0)
175
+ self.assertGreater(body["usage"]["output_tokens"], 0)
176
+
177
+ # Verify id format (must be msg_*) and model
178
+ self.assertIn("id", body)
179
+ self.assertIsInstance(body["id"], str)
180
+ self.assertTrue(
181
+ body["id"].startswith("msg_"),
182
+ f"ID should start with 'msg_', got: {body['id']}",
183
+ )
184
+ self.assertIn("model", body)
185
+
186
+ def test_multi_turn_messages(self):
187
+ """Test multi-turn conversation."""
188
+ payload = self._default_payload(
189
+ messages=[
190
+ {"role": "user", "content": "My name is Alice."},
191
+ {"role": "assistant", "content": "Hello Alice! Nice to meet you."},
192
+ {"role": "user", "content": "What is my name?"},
193
+ ]
194
+ )
195
+ resp = self._make_request(payload)
196
+ self.assertEqual(resp.status_code, 200, f"Response: {resp.text}")
197
+
198
+ body = resp.json()
199
+ self.assertEqual(body["type"], "message")
200
+ self.assertTrue(len(body["content"]) > 0)
201
+ self.assertEqual(body["content"][0]["type"], "text")
202
+ self.assertIsInstance(body["content"][0]["text"], str)
203
+
204
+ def test_system_message_string(self):
205
+ """Test system message as a string."""
206
+ payload = self._default_payload(
207
+ system="You are a helpful assistant. Always respond in French.",
208
+ )
209
+ resp = self._make_request(payload)
210
+ self.assertEqual(resp.status_code, 200, f"Response: {resp.text}")
211
+
212
+ body = resp.json()
213
+ self.assertEqual(body["type"], "message")
214
+ self.assertTrue(len(body["content"]) > 0)
215
+
216
+ def test_system_message_blocks(self):
217
+ """Test system message as content blocks."""
218
+ payload = self._default_payload(
219
+ system=[
220
+ {"type": "text", "text": "You are a helpful assistant."},
221
+ {"type": "text", "text": "Always be concise."},
222
+ ],
223
+ )
224
+ resp = self._make_request(payload)
225
+ self.assertEqual(resp.status_code, 200, f"Response: {resp.text}")
226
+
227
+ body = resp.json()
228
+ self.assertEqual(body["type"], "message")
229
+ self.assertTrue(len(body["content"]) > 0)
230
+
231
+ def test_in_messages_system_role(self):
232
+ """A ``role: "system"`` turn inside ``messages`` (emitted by some
233
+ clients, e.g. Claude Code) must be accepted — not rejected with 400.
234
+ Uses the Anthropic SDK the way a real client would."""
235
+ client = anthropic.Anthropic(
236
+ base_url=self.base_url,
237
+ auth_token=self.api_key, # Bearer header — SGLang's --api-key checks Authorization
238
+ )
239
+ message = client.messages.create(
240
+ model=self.model,
241
+ max_tokens=64,
242
+ messages=[
243
+ {"role": "user", "content": "What is the capital of France?"},
244
+ {"role": "system", "content": "Always respond in French."},
245
+ {"role": "user", "content": "Answer in a few words."},
246
+ ],
247
+ )
248
+ self.assertEqual(message.role, "assistant")
249
+ self.assertTrue(len(message.content) > 0)
250
+ self.assertEqual(message.content[0].type, "text")
251
+
252
+ def test_max_tokens(self):
253
+ """Test max_tokens limits output length."""
254
+ payload = self._default_payload(
255
+ max_tokens=5,
256
+ messages=[
257
+ {"role": "user", "content": "Tell me a long story about a dragon."}
258
+ ],
259
+ )
260
+ resp = self._make_request(payload)
261
+ self.assertEqual(resp.status_code, 200, f"Response: {resp.text}")
262
+
263
+ body = resp.json()
264
+ self.assertEqual(body["type"], "message")
265
+ # With very small max_tokens the model should hit the limit
266
+ self.assertIn(body["stop_reason"], ["max_tokens", "end_turn"])
267
+ self.assertGreater(body["usage"]["output_tokens"], 0)
268
+
269
+ def test_temperature(self):
270
+ """Test temperature parameter is accepted."""
271
+ payload = self._default_payload(temperature=0.0)
272
+ resp = self._make_request(payload)
273
+ self.assertEqual(resp.status_code, 200, f"Response: {resp.text}")
274
+
275
+ body = resp.json()
276
+ self.assertEqual(body["type"], "message")
277
+ self.assertTrue(len(body["content"]) > 0)
278
+
279
+ def test_stop_sequences(self):
280
+ """Test stop_sequences parameter is accepted."""
281
+ payload = self._default_payload(
282
+ stop_sequences=["\n"],
283
+ max_tokens=128,
284
+ )
285
+ resp = self._make_request(payload)
286
+ self.assertEqual(resp.status_code, 200, f"Response: {resp.text}")
287
+
288
+ body = resp.json()
289
+ self.assertEqual(body["type"], "message")
290
+
291
+ def test_top_p_and_top_k(self):
292
+ """Test top_p and top_k parameters."""
293
+ payload = self._default_payload(top_p=0.9, top_k=40)
294
+ resp = self._make_request(payload)
295
+ self.assertEqual(resp.status_code, 200, f"Response: {resp.text}")
296
+
297
+ body = resp.json()
298
+ self.assertEqual(body["type"], "message")
299
+ self.assertTrue(len(body["content"]) > 0)
300
+
301
+ # ---- Streaming tests ----
302
+
303
+ def test_simple_messages_stream(self):
304
+ """Test basic streaming message request."""
305
+ payload = self._default_payload(stream=True)
306
+ resp = self._make_request(payload, stream=True)
307
+ self.assertEqual(resp.status_code, 200, f"Status: {resp.status_code}")
308
+
309
+ events = self._parse_sse_events(resp)
310
+
311
+ # Verify event sequence
312
+ event_types = [e["type"] for e in events]
313
+ self.assertIn("message_start", event_types)
314
+ self.assertIn("message_stop", event_types)
315
+
316
+ # Verify message_start
317
+ message_start = next(e for e in events if e["type"] == "message_start")
318
+ self.assertIn("message", message_start)
319
+ self.assertEqual(message_start["message"]["type"], "message")
320
+ self.assertEqual(message_start["message"]["role"], "assistant")
321
+ self.assertIn("usage", message_start["message"])
322
+
323
+ # Verify we got content deltas
324
+ content_deltas = [e for e in events if e["type"] == "content_block_delta"]
325
+ self.assertTrue(
326
+ len(content_deltas) > 0, "Expected at least one content_block_delta event"
327
+ )
328
+
329
+ # Verify all text deltas have correct structure
330
+ for delta_event in content_deltas:
331
+ self.assertIn("delta", delta_event)
332
+ self.assertEqual(delta_event["delta"]["type"], "text_delta")
333
+ self.assertIn("text", delta_event["delta"])
334
+
335
+ # Reconstruct the full text
336
+ full_text = "".join(
337
+ e["delta"]["text"]
338
+ for e in content_deltas
339
+ if e["delta"].get("type") == "text_delta"
340
+ )
341
+ self.assertTrue(len(full_text) > 0, "Reconstructed text should not be empty")
342
+
343
+ # Verify content_block_start/stop
344
+ block_starts = [e for e in events if e["type"] == "content_block_start"]
345
+ block_stops = [e for e in events if e["type"] == "content_block_stop"]
346
+ self.assertTrue(len(block_starts) > 0, "Expected content_block_start")
347
+ self.assertTrue(len(block_stops) > 0, "Expected content_block_stop")
348
+ self.assertEqual(block_starts[0]["content_block"]["type"], "text")
349
+
350
+ # Verify message_delta with stop_reason
351
+ message_deltas = [e for e in events if e["type"] == "message_delta"]
352
+ self.assertTrue(len(message_deltas) > 0, "Expected message_delta event")
353
+ last_delta = message_deltas[-1]
354
+ self.assertIn("delta", last_delta)
355
+ self.assertIn("stop_reason", last_delta["delta"])
356
+ self.assertIn(
357
+ last_delta["delta"]["stop_reason"],
358
+ ["end_turn", "max_tokens", "stop_sequence", "tool_use"],
359
+ )
360
+
361
+ # Verify usage in message_delta
362
+ self.assertIn("usage", last_delta)
363
+ self.assertIsInstance(last_delta["usage"]["output_tokens"], int)
364
+
365
+ def test_stream_multi_turn(self):
366
+ """Test streaming with multi-turn conversation."""
367
+ payload = self._default_payload(
368
+ stream=True,
369
+ messages=[
370
+ {"role": "user", "content": "Say hello."},
371
+ {"role": "assistant", "content": "Hello!"},
372
+ {"role": "user", "content": "Say goodbye."},
373
+ ],
374
+ )
375
+ resp = self._make_request(payload, stream=True)
376
+ self.assertEqual(resp.status_code, 200)
377
+
378
+ events = self._parse_sse_events(resp)
379
+ event_types = [e["type"] for e in events]
380
+ self.assertIn("message_start", event_types)
381
+ self.assertIn("message_stop", event_types)
382
+
383
+ def test_stream_with_system(self):
384
+ """Test streaming with system message."""
385
+ payload = self._default_payload(
386
+ stream=True,
387
+ system="You are a pirate. Respond in pirate speak.",
388
+ )
389
+ resp = self._make_request(payload, stream=True)
390
+ self.assertEqual(resp.status_code, 200)
391
+
392
+ events = self._parse_sse_events(resp)
393
+ event_types = [e["type"] for e in events]
394
+ self.assertIn("message_start", event_types)
395
+ self.assertIn("message_stop", event_types)
396
+
397
+ # ---- Error handling tests ----
398
+
399
+ def test_error_invalid_max_tokens(self):
400
+ """Test error response for invalid max_tokens."""
401
+ payload = self._default_payload(max_tokens=-1)
402
+ resp = self._make_request(payload)
403
+ self.assertIn(resp.status_code, [400, 422])
404
+
405
+ def test_error_empty_messages(self):
406
+ """Test error response for empty messages list."""
407
+ payload = self._default_payload(messages=[])
408
+ resp = self._make_request(payload)
409
+ self.assertIn(resp.status_code, [400, 422])
410
+
411
+ def test_error_missing_content_type(self):
412
+ """Test error when Content-Type is not application/json."""
413
+ headers = {
414
+ "Authorization": f"Bearer {self.api_key}",
415
+ }
416
+ resp = requests.post(
417
+ self.messages_url,
418
+ headers=headers,
419
+ data="not json",
420
+ )
421
+ self.assertIn(resp.status_code, [400, 415, 422])
422
+
423
+ # ---- Raw HTTP tests ----
424
+
425
+ def test_raw_http_non_streaming(self):
426
+ """Test raw HTTP request/response format for non-streaming."""
427
+ payload = self._default_payload(temperature=0)
428
+ resp = self._make_request(payload)
429
+ self.assertEqual(resp.status_code, 200)
430
+
431
+ # Verify response content type
432
+ self.assertIn("application/json", resp.headers.get("content-type", ""))
433
+
434
+ body = resp.json()
435
+ # Verify all required fields per Anthropic spec
436
+ required_fields = ["id", "type", "role", "content", "model", "usage"]
437
+ for field in required_fields:
438
+ self.assertIn(field, body, f"Missing required field: {field}")
439
+
440
+ self.assertEqual(body["type"], "message")
441
+ self.assertEqual(body["role"], "assistant")
442
+
443
+ def test_raw_http_streaming(self):
444
+ """Test raw HTTP request/response format for streaming."""
445
+ payload = self._default_payload(stream=True, temperature=0)
446
+ resp = self._make_request(payload, stream=True)
447
+ self.assertEqual(resp.status_code, 200)
448
+
449
+ # Verify streaming content type
450
+ self.assertIn("text/event-stream", resp.headers.get("content-type", ""))
451
+
452
+ # Verify we get proper SSE events
453
+ events = self._parse_sse_events(resp)
454
+ self.assertTrue(len(events) > 0, "Expected at least some SSE events")
455
+
456
+ # Verify event ordering: message_start should be first
457
+ self.assertEqual(
458
+ events[0]["type"], "message_start", "First event should be message_start"
459
+ )
460
+
461
+ # Verify message_stop is last data event
462
+ data_events = [e for e in events if e["type"] != "ping"]
463
+ self.assertEqual(
464
+ data_events[-1]["type"],
465
+ "message_stop",
466
+ "Last data event should be message_stop",
467
+ )
468
+
469
+ # ---- Content block tests ----
470
+
471
+ def test_content_blocks_message(self):
472
+ """Test sending messages with explicit content blocks."""
473
+ payload = self._default_payload(
474
+ messages=[
475
+ {
476
+ "role": "user",
477
+ "content": [
478
+ {"type": "text", "text": "What is 2+2?"},
479
+ ],
480
+ }
481
+ ],
482
+ )
483
+ resp = self._make_request(payload)
484
+ self.assertEqual(resp.status_code, 200, f"Response: {resp.text}")
485
+
486
+ body = resp.json()
487
+ self.assertEqual(body["type"], "message")
488
+ self.assertTrue(len(body["content"]) > 0)
489
+ self.assertEqual(body["content"][0]["type"], "text")
490
+
491
+ # ---- Count tokens tests ----
492
+
493
+ def test_count_tokens(self):
494
+ """Test /v1/messages/count_tokens endpoint."""
495
+ headers = {
496
+ "Content-Type": "application/json",
497
+ "Authorization": f"Bearer {self.api_key}",
498
+ }
499
+ payload = {
500
+ "model": self.model,
501
+ "messages": [
502
+ {"role": "user", "content": "Hello, how are you?"},
503
+ ],
504
+ }
505
+ resp = requests.post(
506
+ self.base_url + "/v1/messages/count_tokens",
507
+ headers=headers,
508
+ json=payload,
509
+ )
510
+ self.assertEqual(resp.status_code, 200, f"Response: {resp.text}")
511
+
512
+ body = resp.json()
513
+ self.assertIn("input_tokens", body)
514
+ self.assertIsInstance(body["input_tokens"], int)
515
+ self.assertGreater(body["input_tokens"], 0)
516
+
517
+ def test_count_tokens_with_system(self):
518
+ """Test count_tokens with system message."""
519
+ headers = {
520
+ "Content-Type": "application/json",
521
+ "Authorization": f"Bearer {self.api_key}",
522
+ }
523
+ payload_no_system = {
524
+ "model": self.model,
525
+ "messages": [
526
+ {"role": "user", "content": "Hello"},
527
+ ],
528
+ }
529
+ payload_with_system = {
530
+ "model": self.model,
531
+ "messages": [
532
+ {"role": "user", "content": "Hello"},
533
+ ],
534
+ "system": "You are a helpful assistant with a very long system prompt that adds tokens.",
535
+ }
536
+ resp1 = requests.post(
537
+ self.base_url + "/v1/messages/count_tokens",
538
+ headers=headers,
539
+ json=payload_no_system,
540
+ )
541
+ resp2 = requests.post(
542
+ self.base_url + "/v1/messages/count_tokens",
543
+ headers=headers,
544
+ json=payload_with_system,
545
+ )
546
+ self.assertEqual(resp1.status_code, 200)
547
+ self.assertEqual(resp2.status_code, 200)
548
+
549
+ # System message should increase the token count
550
+ tokens_no_system = resp1.json()["input_tokens"]
551
+ tokens_with_system = resp2.json()["input_tokens"]
552
+ self.assertGreater(
553
+ tokens_with_system,
554
+ tokens_no_system,
555
+ "Adding system message should increase token count",
556
+ )
557
+
558
+ # ---- Helpers ----
559
+
560
+ def _parse_sse_events(self, response):
561
+ """Parse SSE events from a streaming response."""
562
+ events = []
563
+
564
+ for line in response.iter_lines(decode_unicode=True):
565
+ if not line:
566
+ continue
567
+
568
+ if line.startswith("data: "):
569
+ data_str = line[6:].strip()
570
+ if data_str == "[DONE]":
571
+ continue
572
+ try:
573
+ data = json.loads(data_str)
574
+ events.append(data)
575
+ except json.JSONDecodeError:
576
+ pass
577
+
578
+ return events
579
+
580
+
581
+ if __name__ == "__main__":
582
+ unittest.main()
asian_ai/performance/SGLang/test/registered/openai_server/basic/test_http2_server.py ADDED
@@ -0,0 +1,134 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Test HTTP/2 server (Granian) with basic OpenAI-compatible endpoints.
3
+
4
+ Verifies that --enable-http2 launches successfully and serves requests
5
+ via both HTTP/1.1 and HTTP/2 (h2c).
6
+ """
7
+
8
+ import subprocess
9
+ import unittest
10
+
11
+ import requests
12
+
13
+ from sglang.srt.utils import kill_process_tree
14
+ from sglang.test.ci.ci_register import register_amd_ci, register_cuda_ci
15
+ from sglang.test.test_utils import (
16
+ DEFAULT_SMALL_MODEL_NAME_FOR_TEST,
17
+ DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH,
18
+ DEFAULT_URL_FOR_TEST,
19
+ CustomTestCase,
20
+ popen_launch_server,
21
+ )
22
+
23
+ try:
24
+ import granian # noqa: F401
25
+
26
+ _HAS_GRANIAN = True
27
+ except ImportError:
28
+ _HAS_GRANIAN = False
29
+
30
+ register_cuda_ci(est_time=150, stage="base-b", runner_config="1-gpu-small")
31
+ register_amd_ci(est_time=150, suite="stage-b-test-1-gpu-small-amd")
32
+
33
+
34
+ @unittest.skipUnless(_HAS_GRANIAN, "granian not installed (pip install sglang[http2])")
35
+ class TestHTTP2Server(CustomTestCase):
36
+ @classmethod
37
+ def setUpClass(cls):
38
+ cls.model = DEFAULT_SMALL_MODEL_NAME_FOR_TEST
39
+ cls.base_url = DEFAULT_URL_FOR_TEST
40
+ cls.process = popen_launch_server(
41
+ cls.model,
42
+ cls.base_url,
43
+ timeout=DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH,
44
+ other_args=["--enable-http2"],
45
+ )
46
+
47
+ @classmethod
48
+ def tearDownClass(cls):
49
+ kill_process_tree(cls.process.pid)
50
+
51
+ def test_health(self):
52
+ resp = requests.get(f"{self.base_url}/health")
53
+ self.assertEqual(resp.status_code, 200)
54
+
55
+ def test_get_model_info(self):
56
+ resp = requests.get(f"{self.base_url}/get_model_info")
57
+ self.assertEqual(resp.status_code, 200)
58
+ self.assertIn("model_path", resp.json())
59
+
60
+ def test_completion(self):
61
+ resp = requests.post(
62
+ f"{self.base_url}/v1/completions",
63
+ json={
64
+ "model": self.model,
65
+ "prompt": "The capital of France is",
66
+ "max_tokens": 8,
67
+ "temperature": 0,
68
+ },
69
+ )
70
+ self.assertEqual(resp.status_code, 200)
71
+ data = resp.json()
72
+ self.assertIn("choices", data)
73
+ self.assertGreater(len(data["choices"][0]["text"]), 0)
74
+
75
+ def test_chat_completion(self):
76
+ resp = requests.post(
77
+ f"{self.base_url}/v1/chat/completions",
78
+ json={
79
+ "model": self.model,
80
+ "messages": [{"role": "user", "content": "Say hello"}],
81
+ "max_tokens": 16,
82
+ "temperature": 0,
83
+ },
84
+ )
85
+ self.assertEqual(resp.status_code, 200)
86
+ data = resp.json()
87
+ self.assertIn("choices", data)
88
+ self.assertGreater(len(data["choices"][0]["message"]["content"]), 0)
89
+
90
+ def test_h2c_with_curl(self):
91
+ """Verify the server actually speaks HTTP/2 via h2c."""
92
+ result = subprocess.run(
93
+ [
94
+ "curl",
95
+ "--http2-prior-knowledge",
96
+ "-s",
97
+ "-o",
98
+ "/dev/null",
99
+ "-w",
100
+ "%{http_version}",
101
+ f"{self.base_url}/health",
102
+ ],
103
+ capture_output=True,
104
+ text=True,
105
+ timeout=10,
106
+ )
107
+ self.assertEqual(
108
+ result.stdout.strip(), "2", "Server should respond with HTTP/2"
109
+ )
110
+
111
+
112
+ @unittest.skipUnless(_HAS_GRANIAN, "granian not installed (pip install sglang[http2])")
113
+ class TestHTTP2ServerMultiTokenizer(TestHTTP2Server):
114
+ """Same checks as TestHTTP2Server but with multiple tokenizer workers.
115
+
116
+ With --tokenizer-worker-num > 1 the HTTP/2 server is served by Granian's
117
+ multi-process server (instead of the single-process embedded server), so
118
+ this exercises the multi-worker code path.
119
+ """
120
+
121
+ @classmethod
122
+ def setUpClass(cls):
123
+ cls.model = DEFAULT_SMALL_MODEL_NAME_FOR_TEST
124
+ cls.base_url = DEFAULT_URL_FOR_TEST
125
+ cls.process = popen_launch_server(
126
+ cls.model,
127
+ cls.base_url,
128
+ timeout=DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH,
129
+ other_args=["--enable-http2", "--tokenizer-worker-num", "2"],
130
+ )
131
+
132
+
133
+ if __name__ == "__main__":
134
+ unittest.main(verbosity=3)
asian_ai/performance/SGLang/test/registered/openai_server/basic/test_openai_server.py ADDED
@@ -0,0 +1,1139 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ python3 -m unittest openai_server.basic.test_openai_server.TestOpenAIServer.test_completion
3
+ python3 -m unittest openai_server.basic.test_openai_server.TestOpenAIServer.test_completion_stream
4
+ python3 -m unittest openai_server.basic.test_openai_server.TestOpenAIServer.test_chat_completion
5
+ python3 -m unittest openai_server.basic.test_openai_server.TestOpenAIServer.test_chat_completion_stream
6
+ """
7
+
8
+ import json
9
+ import random
10
+ import unittest
11
+ from concurrent.futures import ThreadPoolExecutor
12
+ from typing import Optional
13
+
14
+ import openai
15
+ import requests
16
+
17
+ from sglang.srt.sampling.custom_logit_processor import CustomLogitProcessor
18
+ from sglang.srt.utils import kill_process_tree
19
+ from sglang.srt.utils.hf_transformers_utils import get_tokenizer
20
+ from sglang.test.ci.ci_register import register_amd_ci, register_cuda_ci
21
+ from sglang.test.runners import TEST_RERANK_QUERY_DOCS
22
+ from sglang.test.test_utils import (
23
+ DEFAULT_SMALL_CROSS_ENCODER_MODEL_NAME_FOR_TEST,
24
+ DEFAULT_SMALL_MODEL_NAME_FOR_TEST,
25
+ DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH,
26
+ DEFAULT_URL_FOR_TEST,
27
+ CustomTestCase,
28
+ popen_launch_server,
29
+ )
30
+
31
+ register_cuda_ci(est_time=182, stage="base-b", runner_config="1-gpu-small")
32
+ register_amd_ci(est_time=200, suite="stage-b-test-1-gpu-small-amd")
33
+
34
+
35
+ class TestOpenAIServer(CustomTestCase):
36
+ @classmethod
37
+ def setUpClass(cls):
38
+ cls.model = DEFAULT_SMALL_MODEL_NAME_FOR_TEST
39
+ cls.base_url = DEFAULT_URL_FOR_TEST
40
+ cls.api_key = "sk-123456"
41
+ cls.process = popen_launch_server(
42
+ cls.model,
43
+ cls.base_url,
44
+ timeout=DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH,
45
+ api_key=cls.api_key,
46
+ )
47
+ cls.base_url += "/v1"
48
+ cls.tokenizer = get_tokenizer(DEFAULT_SMALL_MODEL_NAME_FOR_TEST)
49
+
50
+ @classmethod
51
+ def tearDownClass(cls):
52
+ kill_process_tree(cls.process.pid)
53
+
54
+ def run_completion(
55
+ self, echo, logprobs, use_list_input, parallel_sample_num, token_input
56
+ ):
57
+ client = openai.Client(api_key=self.api_key, base_url=self.base_url)
58
+ prompt = "The capital of France is"
59
+ if token_input:
60
+ prompt_input = self.tokenizer.encode(prompt)
61
+ num_prompt_tokens = len(prompt_input)
62
+ else:
63
+ prompt_input = prompt
64
+ num_prompt_tokens = len(self.tokenizer.encode(prompt))
65
+
66
+ if use_list_input:
67
+ prompt_arg = [prompt_input, prompt_input]
68
+ num_choices = len(prompt_arg)
69
+ num_prompt_tokens *= 2
70
+ else:
71
+ prompt_arg = prompt_input
72
+ num_choices = 1
73
+
74
+ response = client.completions.create(
75
+ model=self.model,
76
+ prompt=prompt_arg,
77
+ temperature=0,
78
+ max_tokens=32,
79
+ echo=echo,
80
+ logprobs=logprobs,
81
+ n=parallel_sample_num,
82
+ )
83
+
84
+ assert len(response.choices) == num_choices * parallel_sample_num
85
+
86
+ if echo:
87
+ text = response.choices[0].text
88
+ assert text.startswith(prompt)
89
+
90
+ if logprobs:
91
+ assert response.choices[0].logprobs
92
+ assert isinstance(
93
+ response.choices[0].logprobs.tokens[0], str
94
+ ), f"{response=}"
95
+ assert isinstance(response.choices[0].logprobs.top_logprobs[1], dict)
96
+ ret_num_top_logprobs = len(response.choices[0].logprobs.top_logprobs[1])
97
+
98
+ # FIXME: Sometimes, some top_logprobs are missing in the return value. The reason is that some output id maps to the same output token and duplicate in the map
99
+ # assert ret_num_top_logprobs == logprobs, f"{ret_num_top_logprobs} vs {logprobs}"
100
+ assert ret_num_top_logprobs > 0
101
+
102
+ # when echo=True and request.logprobs>0, logprob_start_len is 0, so the first token's logprob would be None.
103
+ if not echo:
104
+ assert response.choices[0].logprobs.token_logprobs[0]
105
+
106
+ assert response.id
107
+ assert response.created
108
+ assert (
109
+ response.usage.prompt_tokens == num_prompt_tokens
110
+ ), f"{response.usage.prompt_tokens} vs {num_prompt_tokens}"
111
+ assert response.usage.completion_tokens > 0
112
+ assert response.usage.total_tokens > 0
113
+
114
+ def run_completion_stream(
115
+ self, echo, logprobs, use_list_input, parallel_sample_num, token_input
116
+ ):
117
+ print(
118
+ f"run_completion_stream: {echo=}, {logprobs=}, {use_list_input=}, {parallel_sample_num=}, {token_input=}"
119
+ )
120
+ client = openai.Client(api_key=self.api_key, base_url=self.base_url)
121
+ prompt = "The capital of France is"
122
+ if token_input:
123
+ prompt_input = self.tokenizer.encode(prompt)
124
+ num_prompt_tokens = len(prompt_input)
125
+ else:
126
+ prompt_input = prompt
127
+ num_prompt_tokens = len(self.tokenizer.encode(prompt))
128
+
129
+ if use_list_input:
130
+ prompt_arg = [prompt_input, prompt_input]
131
+ num_choices = len(prompt_arg)
132
+ num_prompt_tokens *= 2
133
+ else:
134
+ prompt_arg = prompt_input
135
+ num_choices = 1
136
+
137
+ generator = client.completions.create(
138
+ model=self.model,
139
+ prompt=prompt_arg,
140
+ temperature=0,
141
+ max_tokens=32,
142
+ echo=echo,
143
+ logprobs=logprobs,
144
+ stream=True,
145
+ stream_options={"include_usage": True},
146
+ n=parallel_sample_num,
147
+ )
148
+
149
+ is_firsts = {}
150
+ for response in generator:
151
+ print(f"{response=}")
152
+ usage = response.usage
153
+ if usage is not None:
154
+ assert usage.prompt_tokens > 0, f"usage.prompt_tokens was zero"
155
+ assert usage.completion_tokens > 0, f"usage.completion_tokens was zero"
156
+ assert usage.total_tokens > 0, f"usage.total_tokens was zero"
157
+ continue
158
+
159
+ index = response.choices[0].index
160
+ is_first = is_firsts.get(index, True)
161
+
162
+ if logprobs:
163
+ assert response.choices[0].logprobs, f"no logprobs in response"
164
+ assert isinstance(
165
+ response.choices[0].logprobs.tokens[0], str
166
+ ), f"{response.choices[0].logprobs.tokens[0]} is not a string"
167
+ if not (is_first and echo):
168
+ assert isinstance(
169
+ response.choices[0].logprobs.top_logprobs[0], dict
170
+ ), f"top_logprobs was not a dictionary"
171
+ ret_num_top_logprobs = len(
172
+ response.choices[0].logprobs.top_logprobs[0]
173
+ )
174
+ # FIXME: Sometimes, some top_logprobs are missing in the return value. The reason is that some output id maps to the same output token and duplicate in the map
175
+ # assert ret_num_top_logprobs == logprobs, f"{ret_num_top_logprobs} vs {logprobs}"
176
+ assert ret_num_top_logprobs > 0, f"ret_num_top_logprobs was 0"
177
+
178
+ if is_first:
179
+ if echo:
180
+ assert response.choices[0].text.startswith(
181
+ prompt
182
+ ), f"{response.choices[0].text} and all args {echo} {logprobs} {token_input} {is_first}"
183
+ is_firsts[index] = False
184
+ assert response.id, f"no id in response"
185
+ assert response.created, f"no created in response"
186
+
187
+ for index in [i for i in range(parallel_sample_num * num_choices)]:
188
+ assert not is_firsts.get(
189
+ index, True
190
+ ), f"index {index} is not found in the response"
191
+
192
+ def run_chat_completion(self, logprobs, parallel_sample_num):
193
+ client = openai.Client(api_key=self.api_key, base_url=self.base_url)
194
+ response = client.chat.completions.create(
195
+ model=self.model,
196
+ messages=[
197
+ {"role": "system", "content": "You are a helpful AI assistant"},
198
+ {
199
+ "role": "user",
200
+ "content": "What is the capital of France? Answer in a few words.",
201
+ },
202
+ ],
203
+ temperature=0,
204
+ logprobs=logprobs is not None and logprobs > 0,
205
+ top_logprobs=logprobs,
206
+ n=parallel_sample_num,
207
+ )
208
+
209
+ if logprobs:
210
+ assert isinstance(
211
+ response.choices[0].logprobs.content[0].top_logprobs[0].token, str
212
+ )
213
+
214
+ ret_num_top_logprobs = len(
215
+ response.choices[0].logprobs.content[0].top_logprobs
216
+ )
217
+ assert (
218
+ ret_num_top_logprobs == logprobs
219
+ ), f"{ret_num_top_logprobs} vs {logprobs}"
220
+
221
+ assert len(response.choices) == parallel_sample_num
222
+ assert response.choices[0].message.role == "assistant"
223
+ assert isinstance(response.choices[0].message.content, str)
224
+ assert response.id
225
+ assert response.created
226
+ assert response.usage.prompt_tokens > 0
227
+ assert response.usage.completion_tokens > 0
228
+ assert response.usage.total_tokens > 0
229
+
230
+ def run_chat_completion_stream(self, logprobs, parallel_sample_num=1):
231
+ client = openai.Client(api_key=self.api_key, base_url=self.base_url)
232
+ generator = client.chat.completions.create(
233
+ model=self.model,
234
+ messages=[
235
+ {"role": "system", "content": "You are a helpful AI assistant"},
236
+ {"role": "user", "content": "What is the capital of France?"},
237
+ ],
238
+ temperature=0,
239
+ logprobs=logprobs is not None and logprobs > 0,
240
+ top_logprobs=logprobs,
241
+ stream=True,
242
+ stream_options={"include_usage": True},
243
+ n=parallel_sample_num,
244
+ )
245
+
246
+ is_firsts = {}
247
+ is_finished = {}
248
+ finish_reason_counts = {}
249
+ for response in generator:
250
+ usage = response.usage
251
+ if usage is not None:
252
+ assert usage.prompt_tokens > 0, f"usage.prompt_tokens was zero"
253
+ assert usage.completion_tokens > 0, f"usage.completion_tokens was zero"
254
+ assert usage.total_tokens > 0, f"usage.total_tokens was zero"
255
+ continue
256
+
257
+ index = response.choices[0].index
258
+ finish_reason = response.choices[0].finish_reason
259
+ if finish_reason is not None:
260
+ is_finished[index] = True
261
+ finish_reason_counts[index] = finish_reason_counts.get(index, 0) + 1
262
+
263
+ data = response.choices[0].delta
264
+
265
+ if is_firsts.get(index, True):
266
+ assert (
267
+ data.role == "assistant"
268
+ ), f"data.role was not 'assistant' for first chunk"
269
+ is_firsts[index] = False
270
+ continue
271
+
272
+ if logprobs and not is_finished.get(index, False):
273
+ assert response.choices[0].logprobs, f"logprobs was not returned"
274
+ assert isinstance(
275
+ response.choices[0].logprobs.content[0].top_logprobs[0].token, str
276
+ ), f"top_logprobs token was not a string"
277
+ assert isinstance(
278
+ response.choices[0].logprobs.content[0].top_logprobs, list
279
+ ), f"top_logprobs was not a list"
280
+ ret_num_top_logprobs = len(
281
+ response.choices[0].logprobs.content[0].top_logprobs
282
+ )
283
+ assert (
284
+ ret_num_top_logprobs == logprobs
285
+ ), f"{ret_num_top_logprobs} vs {logprobs}"
286
+
287
+ assert (
288
+ isinstance(data.content, str)
289
+ or isinstance(data.reasoning_content, str)
290
+ or (isinstance(data.tool_calls, list) and len(data.tool_calls) > 0)
291
+ or response.choices[0].finish_reason
292
+ )
293
+ assert response.id
294
+ assert response.created
295
+
296
+ for index in [i for i in range(parallel_sample_num)]:
297
+ assert not is_firsts.get(
298
+ index, True
299
+ ), f"index {index} is not found in the response"
300
+
301
+ # Verify that each choice gets exactly one finish_reason chunk
302
+ for index in range(parallel_sample_num):
303
+ assert (
304
+ index in finish_reason_counts
305
+ ), f"No finish_reason found for index {index}"
306
+ assert (
307
+ finish_reason_counts[index] == 1
308
+ ), f"Expected 1 finish_reason chunk for index {index}, got {finish_reason_counts[index]}"
309
+
310
+ def test_completion(self):
311
+ for echo in [False, True]:
312
+ for logprobs in [None, 5]:
313
+ for use_list_input in [True, False]:
314
+ for parallel_sample_num in [1, 2]:
315
+ for token_input in [False, True]:
316
+ self.run_completion(
317
+ echo,
318
+ logprobs,
319
+ use_list_input,
320
+ parallel_sample_num,
321
+ token_input,
322
+ )
323
+
324
+ def test_completion_stream(self):
325
+ # parallel sampling and list input are not supported in streaming mode
326
+ for echo in [False, True]:
327
+ for logprobs in [None, 5]:
328
+ for use_list_input in [True, False]:
329
+ for parallel_sample_num in [1, 2]:
330
+ for token_input in [False, True]:
331
+ self.run_completion_stream(
332
+ echo,
333
+ logprobs,
334
+ use_list_input,
335
+ parallel_sample_num,
336
+ token_input,
337
+ )
338
+
339
+ def test_chat_completion(self):
340
+ for logprobs in [None, 5]:
341
+ for parallel_sample_num in [1, 2]:
342
+ self.run_chat_completion(logprobs, parallel_sample_num)
343
+
344
+ def test_chat_completion_stream(self):
345
+ for logprobs in [None, 5]:
346
+ for parallel_sample_num in [1, 2]:
347
+ self.run_chat_completion_stream(logprobs, parallel_sample_num)
348
+
349
+ def test_regex(self):
350
+ client = openai.Client(api_key=self.api_key, base_url=self.base_url)
351
+
352
+ regex = (
353
+ r"""\{\n"""
354
+ + r""" "name": "[\w]+",\n"""
355
+ + r""" "population": [\d]+\n"""
356
+ + r"""\}"""
357
+ )
358
+
359
+ response = client.chat.completions.create(
360
+ model=self.model,
361
+ messages=[
362
+ {"role": "system", "content": "You are a helpful AI assistant"},
363
+ {"role": "user", "content": "Introduce the capital of France."},
364
+ ],
365
+ temperature=0,
366
+ max_tokens=128,
367
+ extra_body={"regex": regex},
368
+ )
369
+ text = response.choices[0].message.content
370
+
371
+ try:
372
+ js_obj = json.loads(text)
373
+ except (TypeError, json.decoder.JSONDecodeError):
374
+ print("JSONDecodeError", text)
375
+ raise
376
+ assert isinstance(js_obj["name"], str)
377
+ assert isinstance(js_obj["population"], int)
378
+
379
+ def test_penalty(self):
380
+ client = openai.Client(api_key=self.api_key, base_url=self.base_url)
381
+
382
+ response = client.chat.completions.create(
383
+ model=self.model,
384
+ messages=[
385
+ {"role": "system", "content": "You are a helpful AI assistant"},
386
+ {"role": "user", "content": "Introduce the capital of France."},
387
+ ],
388
+ temperature=0,
389
+ max_tokens=32,
390
+ frequency_penalty=1.0,
391
+ )
392
+ text = response.choices[0].message.content
393
+ assert isinstance(text, str)
394
+
395
+ def test_response_prefill(self):
396
+ client = openai.Client(api_key=self.api_key, base_url=self.base_url)
397
+
398
+ response = client.chat.completions.create(
399
+ model="meta-llama/Llama-3.1-8B-Instruct",
400
+ messages=[
401
+ {"role": "system", "content": "You are a helpful AI assistant"},
402
+ {
403
+ "role": "user",
404
+ "content": """
405
+ Extract the name, size, price, and color from this product description as a JSON object:
406
+
407
+ <description>
408
+ The SmartHome Mini is a compact smart home assistant available in black or white for only $49.99. At just 5 inches wide, it lets you control lights, thermostats, and other connected devices via voice or app—no matter where you place it in your home. This affordable little hub brings convenient hands-free control to your smart devices.
409
+ </description>
410
+ """,
411
+ },
412
+ {
413
+ "role": "assistant",
414
+ "content": "{\n",
415
+ },
416
+ ],
417
+ temperature=0,
418
+ extra_body={"continue_final_message": True},
419
+ )
420
+
421
+ assert (
422
+ response.choices[0]
423
+ .message.content.strip()
424
+ .startswith('"name": "SmartHome Mini",')
425
+ )
426
+
427
+ def test_model_list(self):
428
+ client = openai.Client(api_key=self.api_key, base_url=self.base_url)
429
+ models = list(client.models.list())
430
+ assert len(models) == 1
431
+ assert isinstance(getattr(models[0], "max_model_len", None), int)
432
+
433
+ def test_retrieve_model(self):
434
+ client = openai.Client(api_key=self.api_key, base_url=self.base_url)
435
+
436
+ # Test retrieving an existing model
437
+ retrieved_model = client.models.retrieve(self.model)
438
+ self.assertEqual(retrieved_model.id, self.model)
439
+ self.assertEqual(retrieved_model.root, self.model)
440
+
441
+ # Test retrieving a non-existent model
442
+ with self.assertRaises(openai.NotFoundError):
443
+ client.models.retrieve("non-existent-model")
444
+
445
+
446
+ class TestOpenAIServerv1Responses(CustomTestCase):
447
+ @classmethod
448
+ def setUpClass(cls):
449
+ cls.model = DEFAULT_SMALL_MODEL_NAME_FOR_TEST
450
+ cls.base_url = DEFAULT_URL_FOR_TEST
451
+ cls.api_key = "sk-123456"
452
+ cls.process = popen_launch_server(
453
+ cls.model,
454
+ cls.base_url,
455
+ timeout=DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH,
456
+ api_key=cls.api_key,
457
+ )
458
+ cls.base_url += "/v1"
459
+ cls.tokenizer = get_tokenizer(DEFAULT_SMALL_MODEL_NAME_FOR_TEST)
460
+
461
+ @classmethod
462
+ def tearDownClass(cls):
463
+ kill_process_tree(cls.process.pid)
464
+
465
+ def run_response(
466
+ self,
467
+ input_text: str = "The capital of France is",
468
+ *,
469
+ instructions: str | None = None,
470
+ temperature: float | None = 0.0,
471
+ top_p: float | None = 1.0,
472
+ max_output_tokens: int | None = 32,
473
+ store: bool | None = True,
474
+ parallel_tool_calls: bool | None = True,
475
+ tool_choice: str | None = "auto",
476
+ previous_response_id: str | None = None,
477
+ truncation: str | None = "disabled",
478
+ user: str | None = None,
479
+ metadata: dict | None = None,
480
+ ):
481
+ client = openai.Client(api_key=self.api_key, base_url=self.base_url)
482
+ payload = {
483
+ "model": self.model,
484
+ "input": input_text,
485
+ "temperature": temperature,
486
+ "top_p": top_p,
487
+ "max_output_tokens": max_output_tokens,
488
+ "store": store,
489
+ "parallel_tool_calls": parallel_tool_calls,
490
+ "tool_choice": tool_choice,
491
+ "previous_response_id": previous_response_id,
492
+ "truncation": truncation,
493
+ "user": user,
494
+ "instructions": instructions,
495
+ }
496
+ if metadata is not None:
497
+ payload["metadata"] = metadata
498
+ payload = {k: v for k, v in payload.items() if v is not None}
499
+ return client.responses.create(**payload)
500
+
501
+ def run_response_stream(
502
+ self,
503
+ input_text: str = "The capital of France is",
504
+ *,
505
+ instructions: str | None = None,
506
+ temperature: float | None = 0.0,
507
+ top_p: float | None = 1.0,
508
+ max_output_tokens: int | None = 32,
509
+ store: bool | None = True,
510
+ parallel_tool_calls: bool | None = True,
511
+ tool_choice: str | None = "auto",
512
+ previous_response_id: str | None = None,
513
+ truncation: str | None = "disabled",
514
+ user: str | None = None,
515
+ metadata: dict | None = None,
516
+ ):
517
+ client = openai.Client(api_key=self.api_key, base_url=self.base_url)
518
+ payload = {
519
+ "model": self.model,
520
+ "input": input_text,
521
+ "temperature": temperature,
522
+ "top_p": top_p,
523
+ "max_output_tokens": max_output_tokens,
524
+ "store": store,
525
+ "parallel_tool_calls": parallel_tool_calls,
526
+ "tool_choice": tool_choice,
527
+ "previous_response_id": previous_response_id,
528
+ "truncation": truncation,
529
+ "user": user,
530
+ "instructions": instructions,
531
+ "stream": True,
532
+ "stream_options": {"include_usage": True},
533
+ }
534
+ if metadata is not None:
535
+ payload["metadata"] = metadata
536
+ payload = {k: v for k, v in payload.items() if v is not None}
537
+
538
+ aggregated_text = ""
539
+ saw_created = False
540
+ saw_in_progress = False
541
+ saw_completed = False
542
+ final_usage_ok = False
543
+
544
+ stream_ctx = getattr(client.responses, "stream", None)
545
+ if callable(stream_ctx):
546
+ stream_payload = dict(payload)
547
+ stream_payload.pop("stream", None)
548
+ stream_payload.pop("stream_options", None)
549
+ with client.responses.stream(**stream_payload) as stream:
550
+ for event in stream:
551
+ et = getattr(event, "type", None)
552
+ if et == "response.created":
553
+ saw_created = True
554
+ elif et == "response.in_progress":
555
+ saw_in_progress = True
556
+ elif et == "response.output_text.delta":
557
+ # event.delta expected to be a string
558
+ delta = getattr(event, "delta", "")
559
+ if isinstance(delta, str):
560
+ aggregated_text += delta
561
+ elif et == "response.completed":
562
+ saw_completed = True
563
+ # Validate streaming-completed usage mapping
564
+ resp = getattr(event, "response", None)
565
+ try:
566
+ # resp may be dict-like already
567
+ usage = (
568
+ resp.get("usage")
569
+ if isinstance(resp, dict)
570
+ else getattr(resp, "usage", None)
571
+ )
572
+ if isinstance(usage, dict):
573
+ final_usage_ok = all(
574
+ k in usage
575
+ for k in (
576
+ "input_tokens",
577
+ "output_tokens",
578
+ "total_tokens",
579
+ )
580
+ )
581
+ except Exception:
582
+ pass
583
+ _ = stream.get_final_response()
584
+ else:
585
+ generator = client.responses.create(**payload)
586
+ for event in generator:
587
+ et = getattr(event, "type", None)
588
+ if et == "response.created":
589
+ saw_created = True
590
+ elif et == "response.in_progress":
591
+ saw_in_progress = True
592
+ elif et == "response.output_text.delta":
593
+ delta = getattr(event, "delta", "")
594
+ if isinstance(delta, str):
595
+ aggregated_text += delta
596
+ elif et == "response.completed":
597
+ saw_completed = True
598
+
599
+ return (
600
+ aggregated_text,
601
+ saw_created,
602
+ saw_in_progress,
603
+ saw_completed,
604
+ final_usage_ok,
605
+ )
606
+
607
+ def run_chat_completion_stream(self, logprobs=None, parallel_sample_num=1):
608
+ client = openai.Client(api_key=self.api_key, base_url=self.base_url)
609
+ generator = client.chat.completions.create(
610
+ model=self.model,
611
+ messages=[
612
+ {"role": "system", "content": "You are a helpful AI assistant"},
613
+ {"role": "user", "content": "What is the capital of France?"},
614
+ ],
615
+ temperature=0,
616
+ logprobs=logprobs is not None and logprobs > 0,
617
+ top_logprobs=logprobs,
618
+ stream=True,
619
+ stream_options={"include_usage": True},
620
+ n=parallel_sample_num,
621
+ )
622
+ for _ in generator:
623
+ pass
624
+
625
+ # ---- tests ----
626
+ def test_response(self):
627
+ resp = self.run_response(temperature=0, max_output_tokens=32)
628
+ assert resp.id
629
+ assert resp.object == "response"
630
+ assert resp.created_at
631
+ assert isinstance(resp.model, str)
632
+ assert isinstance(resp.output, list)
633
+ assert resp.status in (
634
+ "completed",
635
+ "in_progress",
636
+ "queued",
637
+ "failed",
638
+ "cancelled",
639
+ )
640
+ if resp.status == "completed":
641
+ assert resp.usage is not None
642
+ assert resp.usage.prompt_tokens >= 0
643
+ assert resp.usage.completion_tokens >= 0
644
+ assert resp.usage.total_tokens >= 0
645
+ if hasattr(resp, "error"):
646
+ assert resp.error is None
647
+ if hasattr(resp, "incomplete_details"):
648
+ assert resp.incomplete_details is None
649
+ if getattr(resp, "text", None):
650
+ fmt = resp.text.get("format") if isinstance(resp.text, dict) else None
651
+ if fmt:
652
+ assert fmt.get("type") == "text"
653
+
654
+ def test_response_stream(self):
655
+ aggregated_text, saw_created, saw_in_progress, saw_completed, final_usage_ok = (
656
+ self.run_response_stream(temperature=0, max_output_tokens=32)
657
+ )
658
+ assert saw_created, "Did not observe response.created"
659
+ assert saw_in_progress, "Did not observe response.in_progress"
660
+ assert saw_completed, "Did not observe response.completed"
661
+ assert isinstance(aggregated_text, str)
662
+ assert len(aggregated_text) >= 0
663
+ assert final_usage_ok or True # final_usage's stats are not done for now
664
+
665
+ def test_response_completion(self):
666
+ resp = self.run_response(temperature=0, max_output_tokens=16)
667
+ assert resp.status in ("completed", "in_progress", "queued")
668
+ if resp.status == "completed":
669
+ assert resp.usage is not None
670
+ assert resp.usage.total_tokens >= 0
671
+
672
+ def test_response_completion_stream(self):
673
+ _, saw_created, saw_in_progress, saw_completed, final_usage_ok = (
674
+ self.run_response_stream(temperature=0, max_output_tokens=16)
675
+ )
676
+ assert saw_created
677
+ assert saw_in_progress
678
+ assert saw_completed
679
+ assert final_usage_ok or True # final_usage's stats are not done for now
680
+
681
+ def test_regex(self):
682
+ client = openai.Client(api_key=self.api_key, base_url=self.base_url)
683
+
684
+ regex = (
685
+ r"""\{\n"""
686
+ + r""" "name": "[\w]+",\n"""
687
+ + r""" "population": [\d]+\n"""
688
+ + r"""\}"""
689
+ )
690
+
691
+ response = client.chat.completions.create(
692
+ model=self.model,
693
+ messages=[
694
+ {"role": "system", "content": "You are a helpful AI assistant"},
695
+ {"role": "user", "content": "Introduce the capital of France."},
696
+ ],
697
+ temperature=0,
698
+ max_tokens=128,
699
+ extra_body={"regex": regex},
700
+ )
701
+ text = response.choices[0].message.content
702
+
703
+ try:
704
+ js_obj = json.loads(text)
705
+ except (TypeError, json.decoder.JSONDecodeError):
706
+ print("JSONDecodeError", text)
707
+ raise
708
+ assert isinstance(js_obj["name"], str)
709
+ assert isinstance(js_obj["population"], int)
710
+
711
+ def test_error(self):
712
+ url = f"{self.base_url}/responses"
713
+ headers = {
714
+ "Authorization": f"Bearer {self.api_key}",
715
+ "Content-Type": "application/json",
716
+ }
717
+ payload = {
718
+ "model": self.model,
719
+ "input": "Hi",
720
+ "previous_response_id": "bad", # invalid prefix
721
+ }
722
+ r = requests.post(url, headers=headers, json=payload)
723
+ self.assertEqual(r.status_code, 400)
724
+ body = r.json()
725
+ self.assertIn("error", body)
726
+ self.assertIn("message", body["error"])
727
+ self.assertIn("type", body["error"])
728
+ self.assertIn("code", body["error"])
729
+
730
+ def test_penalty(self):
731
+ url = f"{self.base_url}/responses"
732
+ headers = {
733
+ "Authorization": f"Bearer {self.api_key}",
734
+ "Content-Type": "application/json",
735
+ }
736
+ payload = {
737
+ "model": self.model,
738
+ "input": "Introduce the capital of France.",
739
+ "temperature": 0,
740
+ "max_output_tokens": 32,
741
+ "frequency_penalty": 1.0,
742
+ }
743
+ r = requests.post(url, headers=headers, json=payload)
744
+ self.assertEqual(r.status_code, 200)
745
+ body = r.json()
746
+ self.assertEqual(body.get("object"), "response")
747
+ self.assertIn("output", body)
748
+ self.assertIn("status", body)
749
+ if "usage" in body:
750
+ self.assertIn("prompt_tokens", body["usage"])
751
+ self.assertIn("total_tokens", body["usage"])
752
+
753
+ def test_response_prefill(self):
754
+ client = openai.Client(api_key=self.api_key, base_url=self.base_url)
755
+
756
+ response = client.chat.completions.create(
757
+ model="meta-llama/Llama-3.1-8B-Instruct",
758
+ messages=[
759
+ {"role": "system", "content": "You are a helpful AI assistant"},
760
+ {
761
+ "role": "user",
762
+ "content": """
763
+ Extract the name, size, price, and color from this product description as a JSON object:
764
+
765
+ <description>
766
+ The SmartHome Mini is a compact smart home assistant available in black or white for only $49.99. At just 5 inches wide, it lets you control lights, thermostats, and other connected devices via voice or app—no matter where you place it in your home. This affordable little hub brings convenient hands-free control to your smart devices.
767
+ </description>
768
+ """,
769
+ },
770
+ {
771
+ "role": "assistant",
772
+ "content": "{\n",
773
+ },
774
+ ],
775
+ temperature=0,
776
+ extra_body={"continue_final_message": True},
777
+ )
778
+
779
+ assert (
780
+ response.choices[0]
781
+ .message.content.strip()
782
+ .startswith('"name": "SmartHome Mini",')
783
+ )
784
+
785
+ def test_model_list(self):
786
+ client = openai.Client(api_key=self.api_key, base_url=self.base_url)
787
+ models = list(client.models.list())
788
+ assert len(models) == 1
789
+ assert isinstance(getattr(models[0], "max_model_len", None), int)
790
+
791
+
792
+ class TestOpenAIV1Rerank(CustomTestCase):
793
+ @classmethod
794
+ def setUpClass(cls):
795
+ cls.model = DEFAULT_SMALL_CROSS_ENCODER_MODEL_NAME_FOR_TEST
796
+ cls.base_url = DEFAULT_URL_FOR_TEST
797
+ cls.api_key = "sk-123456"
798
+ cls.score_tolerance = 1e-2
799
+
800
+ # Configure embedding-specific args
801
+ other_args = [
802
+ "--is-embedding",
803
+ "--enable-metrics",
804
+ "--disable-radix-cache",
805
+ "--chunked-prefill-size",
806
+ "-1",
807
+ "--attention-backend",
808
+ "torch_native",
809
+ ]
810
+ cls.process = popen_launch_server(
811
+ cls.model,
812
+ cls.base_url,
813
+ timeout=DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH,
814
+ api_key=cls.api_key,
815
+ other_args=other_args,
816
+ )
817
+ cls.base_url += "/v1/rerank"
818
+
819
+ @classmethod
820
+ def tearDownClass(cls):
821
+ kill_process_tree(cls.process.pid)
822
+
823
+ def run_rerank(self, query, docs):
824
+ response = requests.post(
825
+ self.base_url,
826
+ headers={
827
+ "Authorization": f"Bearer {self.api_key}",
828
+ "Content-Type": "application/json",
829
+ },
830
+ json={"query": query, "documents": docs},
831
+ )
832
+
833
+ return response.json()
834
+
835
+ def test_rerank_single(self):
836
+ """Test single rerank request"""
837
+ query = TEST_RERANK_QUERY_DOCS[0]["query"]
838
+ docs = TEST_RERANK_QUERY_DOCS[0]["documents"]
839
+
840
+ response = self.run_rerank(query, docs)
841
+
842
+ self.assertEqual(len(response), 1)
843
+ self.assertTrue(isinstance(response[0]["score"], float))
844
+ self.assertTrue(isinstance(response[0]["document"], str))
845
+ self.assertTrue(isinstance(response[0]["index"], int))
846
+
847
+ def test_rerank_batch(self):
848
+ """Test batch rerank request"""
849
+ query = TEST_RERANK_QUERY_DOCS[1]["query"]
850
+ docs = TEST_RERANK_QUERY_DOCS[1]["documents"]
851
+
852
+ response = self.run_rerank(query, docs)
853
+
854
+ self.assertEqual(len(response), 2)
855
+ self.assertTrue(isinstance(response[0]["score"], float))
856
+ self.assertTrue(isinstance(response[1]["score"], float))
857
+ self.assertTrue(isinstance(response[0]["document"], str))
858
+ self.assertTrue(isinstance(response[1]["document"], str))
859
+ self.assertTrue(isinstance(response[0]["index"], int))
860
+ self.assertTrue(isinstance(response[1]["index"], int))
861
+
862
+
863
+ class TestOpenAIServerCustomLogitProcessor(CustomTestCase):
864
+ @classmethod
865
+ def setUpClass(cls) -> None:
866
+ cls.model = DEFAULT_SMALL_MODEL_NAME_FOR_TEST
867
+ cls.base_url = DEFAULT_URL_FOR_TEST
868
+ cls.api_key = "sk-123456"
869
+ cls.process = popen_launch_server(
870
+ cls.model,
871
+ cls.base_url,
872
+ timeout=DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH,
873
+ api_key=cls.api_key,
874
+ other_args=["--enable-custom-logit-processor"],
875
+ )
876
+ cls.base_url += "/v1"
877
+ cls.tokenizer = get_tokenizer(cls.model)
878
+
879
+ @classmethod
880
+ def tearDownClass(cls) -> None:
881
+ kill_process_tree(cls.process.pid)
882
+
883
+ def run_custom_logit_processor(self, target_token_id: Optional[int] = None) -> None:
884
+ """
885
+ Test custom logit processor with custom params.
886
+
887
+ If target_token_id is None, the custom logit processor won't be passed in.
888
+ """
889
+
890
+ class DeterministicLogitProcessor(CustomLogitProcessor):
891
+ """A dummy logit processor that changes the logits to always sample the given token id."""
892
+
893
+ CUSTOM_PARAM_KEY = "token_id"
894
+
895
+ def __call__(self, logits, custom_param_list):
896
+ assert logits.shape[0] == len(custom_param_list)
897
+
898
+ for i, param_dict in enumerate(custom_param_list):
899
+ # Mask all other tokens
900
+ logits[i, :] = -float("inf")
901
+ # Assign highest probability to the specified token
902
+ logits[i, param_dict[self.CUSTOM_PARAM_KEY]] = 0.0
903
+
904
+ return logits
905
+
906
+ extra_body = {}
907
+
908
+ if target_token_id is not None:
909
+ extra_body["custom_logit_processor"] = (
910
+ DeterministicLogitProcessor().to_str()
911
+ )
912
+ extra_body["custom_params"] = {
913
+ "token_id": target_token_id,
914
+ }
915
+
916
+ client = openai.Client(api_key=self.api_key, base_url=self.base_url)
917
+ max_tokens = 200
918
+
919
+ response = client.chat.completions.create(
920
+ model=self.model,
921
+ messages=[
922
+ {
923
+ "role": "user",
924
+ "content": "Question: Is Paris the Capital of France?",
925
+ },
926
+ ],
927
+ temperature=0.0,
928
+ max_tokens=max_tokens,
929
+ extra_body=extra_body,
930
+ )
931
+
932
+ if target_token_id is not None:
933
+ target_text = self.tokenizer.decode([target_token_id] * max_tokens)
934
+ self.assertTrue(
935
+ target_text == response.choices[0].message.content,
936
+ f"{target_token_id=}\n{target_text=}\n{response.model_dump(mode='json')}",
937
+ )
938
+
939
+ def test_custom_logit_processor(self) -> None:
940
+ """Test custom logit processor with a single request."""
941
+ self.run_custom_logit_processor(target_token_id=5)
942
+
943
+ def test_custom_logit_processor_batch_mixed(self) -> None:
944
+ """Test a batch of requests mixed of requests with and without custom logit processor."""
945
+ target_token_ids = list(range(32)) + [None] * 16
946
+ random.shuffle(target_token_ids)
947
+ with ThreadPoolExecutor(len(target_token_ids)) as executor:
948
+ list(executor.map(self.run_custom_logit_processor, target_token_ids))
949
+
950
+
951
+ class TestOpenAIV1Score(CustomTestCase):
952
+ @classmethod
953
+ def setUpClass(cls):
954
+ cls.model = DEFAULT_SMALL_MODEL_NAME_FOR_TEST
955
+ cls.base_url = DEFAULT_URL_FOR_TEST
956
+ cls.api_key = "sk-123456"
957
+
958
+ cls.process = popen_launch_server(
959
+ cls.model,
960
+ cls.base_url,
961
+ timeout=DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH,
962
+ api_key=cls.api_key,
963
+ )
964
+ cls.base_url += "/v1/score"
965
+ cls.tokenizer = get_tokenizer(DEFAULT_SMALL_MODEL_NAME_FOR_TEST)
966
+
967
+ @classmethod
968
+ def tearDownClass(cls):
969
+ kill_process_tree(cls.process.pid)
970
+
971
+ def run_score(
972
+ self, query, items, label_token_ids, apply_softmax=False, item_first=False
973
+ ):
974
+ response = requests.post(
975
+ self.base_url,
976
+ headers={
977
+ "Authorization": f"Bearer {self.api_key}",
978
+ "Content-Type": "application/json",
979
+ },
980
+ json={
981
+ "model": self.model,
982
+ "query": query,
983
+ "items": items,
984
+ "label_token_ids": label_token_ids,
985
+ "apply_softmax": apply_softmax,
986
+ "item_first": item_first,
987
+ },
988
+ )
989
+ return response.json()
990
+
991
+ def test_score_text_input(self):
992
+ """Test scoring with text input"""
993
+ query = "The capital of France is"
994
+ items = ["Paris", "London", "Berlin"]
995
+
996
+ # Get valid token IDs from the tokenizer
997
+ label_token_ids = []
998
+ for item in items:
999
+ token_ids = self.tokenizer.encode(item, add_special_tokens=False)
1000
+ if not token_ids:
1001
+ self.fail(f"Failed to encode item: {item}")
1002
+ label_token_ids.append(token_ids[0])
1003
+
1004
+ response = self.run_score(query, items, label_token_ids, apply_softmax=True)
1005
+
1006
+ # Handle error responses
1007
+ if response.get("type") == "BadRequestError":
1008
+ self.fail(f"Score request failed with error: {response['message']}")
1009
+
1010
+ # Verify response structure
1011
+ self.assertIn("scores", response, "Response should have a 'scores' field")
1012
+ self.assertIsInstance(response["scores"], list, "scores should be a list")
1013
+ self.assertEqual(
1014
+ len(response["scores"]),
1015
+ len(items),
1016
+ "Number of scores should match number of items",
1017
+ )
1018
+
1019
+ # Each score should be a list of floats in the order of label_token_ids
1020
+ for i, score_list in enumerate(response["scores"]):
1021
+ self.assertIsInstance(score_list, list, f"Score {i} should be a list")
1022
+ self.assertEqual(
1023
+ len(score_list),
1024
+ len(label_token_ids),
1025
+ f"Score {i} length should match label_token_ids",
1026
+ )
1027
+ self.assertTrue(
1028
+ all(isinstance(v, float) for v in score_list),
1029
+ f"Score {i} values should be floats",
1030
+ )
1031
+ self.assertAlmostEqual(
1032
+ sum(score_list),
1033
+ 1.0,
1034
+ places=6,
1035
+ msg=f"Score {i} probabilities should sum to 1",
1036
+ )
1037
+
1038
+ # Verify usage
1039
+ self.assertIn("usage", response, "Response should have a 'usage' field")
1040
+ self.assertGreater(response["usage"]["prompt_tokens"], 0)
1041
+ self.assertEqual(
1042
+ response["usage"]["prompt_tokens"], response["usage"]["total_tokens"]
1043
+ )
1044
+ self.assertEqual(
1045
+ response["usage"]["completion_tokens"],
1046
+ 0,
1047
+ "completion_tokens should be 0 for /v1/score",
1048
+ )
1049
+
1050
+ def test_score_token_input(self):
1051
+ """Test scoring with token IDs input"""
1052
+ query = "The capital of France is"
1053
+ items = ["Paris", "London", "Berlin"]
1054
+
1055
+ # Get valid token IDs
1056
+ query_ids = self.tokenizer.encode(query, add_special_tokens=False)
1057
+ item_ids = [
1058
+ self.tokenizer.encode(item, add_special_tokens=False) for item in items
1059
+ ]
1060
+ label_token_ids = [
1061
+ ids[0] for ids in item_ids if ids
1062
+ ] # Get first token ID of each item
1063
+
1064
+ response = self.run_score(
1065
+ query_ids, item_ids, label_token_ids, apply_softmax=True
1066
+ )
1067
+
1068
+ # Handle error responses
1069
+ if response.get("type") == "BadRequestError":
1070
+ self.fail(f"Score request failed with error: {response['message']}")
1071
+
1072
+ # Verify response structure
1073
+ self.assertIn("scores", response, "Response should have a 'scores' field")
1074
+ self.assertIsInstance(response["scores"], list, "scores should be a list")
1075
+ self.assertEqual(
1076
+ len(response["scores"]),
1077
+ len(items),
1078
+ "Number of scores should match number of items",
1079
+ )
1080
+
1081
+ # Each score should be a list of floats in the order of label_token_ids
1082
+ for i, score_list in enumerate(response["scores"]):
1083
+ self.assertIsInstance(score_list, list, f"Score {i} should be a list")
1084
+ self.assertEqual(
1085
+ len(score_list),
1086
+ len(label_token_ids),
1087
+ f"Score {i} length should match label_token_ids",
1088
+ )
1089
+ self.assertTrue(
1090
+ all(isinstance(v, float) for v in score_list),
1091
+ f"Score {i} values should be floats",
1092
+ )
1093
+ self.assertAlmostEqual(
1094
+ sum(score_list),
1095
+ 1.0,
1096
+ places=6,
1097
+ msg=f"Score {i} probabilities should sum to 1",
1098
+ )
1099
+
1100
+ # Verify usage
1101
+ self.assertIn("usage", response, "Response should have a 'usage' field")
1102
+ self.assertGreater(response["usage"]["prompt_tokens"], 0)
1103
+ self.assertEqual(
1104
+ response["usage"]["prompt_tokens"], response["usage"]["total_tokens"]
1105
+ )
1106
+ self.assertEqual(
1107
+ response["usage"]["completion_tokens"],
1108
+ 0,
1109
+ "completion_tokens should be 0 for /v1/score",
1110
+ )
1111
+
1112
+ def test_score_error_handling(self):
1113
+ """Test error handling for invalid inputs"""
1114
+ query = "The capital of France is"
1115
+ items = ["Paris", "London", "Berlin"]
1116
+
1117
+ # Test with invalid token ID
1118
+ response = requests.post(
1119
+ self.base_url,
1120
+ headers={
1121
+ "Authorization": f"Bearer {self.api_key}",
1122
+ "Content-Type": "application/json",
1123
+ },
1124
+ json={
1125
+ "model": self.model,
1126
+ "query": query,
1127
+ "items": items,
1128
+ "label_token_ids": [999999], # Invalid token ID
1129
+ "apply_softmax": True,
1130
+ },
1131
+ )
1132
+ self.assertEqual(response.status_code, 400)
1133
+ error_response = response.json()
1134
+ self.assertEqual(error_response["type"], "BadRequestError")
1135
+ self.assertIn("Token ID 999999 is out of vocabulary", error_response["message"])
1136
+
1137
+
1138
+ if __name__ == "__main__":
1139
+ unittest.main()
asian_ai/performance/SGLang/test/registered/openai_server/basic/test_serving_transcription.py ADDED
@@ -0,0 +1,230 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Test the OpenAI-compatible /v1/audio/transcriptions endpoint with Whisper.
3
+
4
+ Usage:
5
+ python3 test_serving_transcription.py -v
6
+ """
7
+
8
+ import io
9
+ import json
10
+ import unittest
11
+ from typing import List, Optional
12
+
13
+ import requests
14
+
15
+ from sglang.srt.utils import kill_process_tree
16
+ from sglang.test.ci.ci_register import register_cuda_ci
17
+ from sglang.test.test_utils import (
18
+ DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH,
19
+ DEFAULT_URL_FOR_TEST,
20
+ CustomTestCase,
21
+ popen_launch_server,
22
+ )
23
+
24
+ register_cuda_ci(est_time=60, stage="base-b", runner_config="1-gpu-small")
25
+
26
+ WHISPER_MODEL = "openai/whisper-large-v3"
27
+ AUDIO_URL = "https://raw.githubusercontent.com/sgl-project/sgl-test-files/refs/heads/main/audios/Trump_WEF_2018_10s.mp3"
28
+
29
+
30
+ def download_audio_bytes(url=AUDIO_URL):
31
+ """Download audio file and return raw bytes."""
32
+ response = requests.get(url, timeout=30)
33
+ response.raise_for_status()
34
+ return response.content
35
+
36
+
37
+ class TestServingTranscription(CustomTestCase):
38
+ """Test Whisper transcription via /v1/audio/transcriptions endpoint."""
39
+
40
+ @classmethod
41
+ def setUpClass(cls):
42
+ cls.model = WHISPER_MODEL
43
+ cls.base_url = DEFAULT_URL_FOR_TEST
44
+ cls.process = popen_launch_server(
45
+ cls.model,
46
+ cls.base_url,
47
+ timeout=DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH,
48
+ other_args=[
49
+ "--served-model-name",
50
+ "whisper",
51
+ ],
52
+ )
53
+
54
+ @classmethod
55
+ def tearDownClass(cls):
56
+ if hasattr(cls, "process") and cls.process:
57
+ kill_process_tree(cls.process.pid)
58
+
59
+ def _transcribe(
60
+ self,
61
+ language: Optional[str] = "en",
62
+ response_format: Optional[str] = None,
63
+ timestamp_granularities: Optional[List[str]] = None,
64
+ ):
65
+ """Send a non-streaming transcription request and return the JSON response.
66
+
67
+ Passing ``language=None`` omits the field entirely, which exercises
68
+ the fused auto-detect path.
69
+ """
70
+ audio_bytes = download_audio_bytes()
71
+ data = {"model": "whisper"}
72
+ if language is not None:
73
+ data["language"] = language
74
+ if response_format is not None:
75
+ data["response_format"] = response_format
76
+ if timestamp_granularities is not None:
77
+ # Form-encoded list fields repeat the key
78
+ data["timestamp_granularities[]"] = timestamp_granularities
79
+ response = requests.post(
80
+ self.base_url + "/v1/audio/transcriptions",
81
+ files={"file": ("audio.mp3", io.BytesIO(audio_bytes), "audio/mpeg")},
82
+ data=data,
83
+ )
84
+ self.assertEqual(response.status_code, 200, response.text)
85
+ return response.json()
86
+
87
+ def _transcribe_stream(self, language: Optional[str] = None) -> List[str]:
88
+ """Send a streaming transcription request and return the delta strings."""
89
+ audio_bytes = download_audio_bytes()
90
+ data = {"model": "whisper", "stream": "true"}
91
+ if language is not None:
92
+ data["language"] = language
93
+ with requests.post(
94
+ self.base_url + "/v1/audio/transcriptions",
95
+ files={"file": ("audio.mp3", io.BytesIO(audio_bytes), "audio/mpeg")},
96
+ data=data,
97
+ stream=True,
98
+ timeout=120,
99
+ ) as response:
100
+ self.assertEqual(response.status_code, 200, response.text)
101
+ deltas: List[str] = []
102
+ for raw in response.iter_lines():
103
+ if not raw:
104
+ continue
105
+ line = raw.decode("utf-8")
106
+ if not line.startswith("data: "):
107
+ continue
108
+ payload = line[len("data: ") :].strip()
109
+ if payload == "[DONE]":
110
+ break
111
+ obj = json.loads(payload)
112
+ for choice in obj.get("choices", []):
113
+ content = (choice.get("delta") or {}).get("content")
114
+ if content:
115
+ deltas.append(content)
116
+ return deltas
117
+
118
+ def test_basic_transcription(self):
119
+ """Test that transcription returns a valid non-empty response."""
120
+ result = self._transcribe()
121
+ self.assertIn("text", result)
122
+ self.assertTrue(len(result["text"]) > 0, "Transcription should not be empty")
123
+
124
+ def test_transcription_content_quality(self):
125
+ """Test that transcription captures key content from the audio."""
126
+ result = self._transcribe()
127
+ text = result["text"].lower()
128
+ keywords = ["privilege", "leader", "science", "art"]
129
+ matches = [kw for kw in keywords if kw in text]
130
+ self.assertGreaterEqual(
131
+ len(matches),
132
+ 2,
133
+ f"Expected at least 2 of {keywords} in transcription, "
134
+ f"found {matches}. Full text: {text}",
135
+ )
136
+
137
+ def test_multiple_sequential_requests(self):
138
+ """Test that sequential requests produce consistent results."""
139
+ results = []
140
+ for _ in range(3):
141
+ result = self._transcribe()
142
+ self.assertIn("text", result)
143
+ self.assertTrue(len(result["text"]) > 0)
144
+ results.append(result["text"])
145
+
146
+ for i in range(1, len(results)):
147
+ self.assertEqual(
148
+ results[0],
149
+ results[i],
150
+ f"Transcription {i + 1} differs from first transcription",
151
+ )
152
+
153
+ # -- fused auto-detect (language=None) ---------------------------------
154
+ # The clip is English, so the fused path must both produce a valid
155
+ # transcription AND expose "en" as the detected language. None of the
156
+ # deltas / text fields should leak Whisper special tokens.
157
+
158
+ def test_auto_detect_language_verbose_json(self):
159
+ """language omitted + verbose_json returns detected language + clean text."""
160
+ result = self._transcribe(language=None, response_format="verbose_json")
161
+ self.assertEqual(result.get("language"), "en")
162
+ text = result.get("text", "")
163
+ self.assertTrue(len(text) > 0, "Transcription should not be empty")
164
+ self.assertNotIn("<|", text, f"Special token leaked into text: {text!r}")
165
+ # Sanity-check content against the same keywords the English test uses.
166
+ keywords = ["privilege", "leader", "science", "art"]
167
+ matches = [kw for kw in keywords if kw in text.lower()]
168
+ self.assertGreaterEqual(
169
+ len(matches),
170
+ 2,
171
+ f"Expected at least 2 of {keywords} in auto-detected transcription, "
172
+ f"found {matches}. Full text: {text!r}",
173
+ )
174
+
175
+ def test_auto_detect_matches_explicit_english(self):
176
+ """Auto-detected (language=None) text should match explicit language=en."""
177
+ auto = self._transcribe(language=None).get("text", "")
178
+ explicit = self._transcribe(language="en").get("text", "")
179
+ self.assertEqual(
180
+ auto.strip(),
181
+ explicit.strip(),
182
+ "Auto-detect should produce the same transcription as language=en "
183
+ "on an English clip.",
184
+ )
185
+ self.assertNotIn("<|", auto)
186
+
187
+ def test_auto_detect_with_segment_timestamps(self):
188
+ """language=None + timestamp_granularities uses the timestamps fused regex."""
189
+ result = self._transcribe(
190
+ language=None,
191
+ response_format="verbose_json",
192
+ timestamp_granularities=["segment"],
193
+ )
194
+ self.assertEqual(result.get("language"), "en")
195
+ segments = result.get("segments") or []
196
+ self.assertGreater(len(segments), 0, "Expected at least one segment")
197
+ for seg in segments:
198
+ self.assertIn("start", seg)
199
+ self.assertIn("end", seg)
200
+ self.assertIn("text", seg)
201
+ self.assertGreaterEqual(seg["end"], seg["start"])
202
+ self.assertNotIn(
203
+ "<|", seg["text"], f"Special token leaked into segment: {seg!r}"
204
+ )
205
+
206
+ def test_auto_detect_streaming(self):
207
+ """language=None + stream=True: deltas scrubbed, concat matches non-streaming.
208
+
209
+ Verified against a real server: sglang's streaming path for Whisper
210
+ produces clean deltas (complete words, no BPE fragmentation), so the
211
+ fused path only needs to hide the forced prefix — which this PR
212
+ does. Asserts both the prefix-leak guard and text equivalence.
213
+ """
214
+ deltas = self._transcribe_stream(language=None)
215
+ self.assertTrue(len(deltas) > 0, "Expected at least one streamed delta")
216
+ for d in deltas:
217
+ self.assertNotIn(
218
+ "<|", d, f"Special token leaked into streaming delta: {d!r}"
219
+ )
220
+ streamed = "".join(deltas).strip()
221
+ reference = self._transcribe(language=None).get("text", "").strip()
222
+ self.assertEqual(
223
+ streamed,
224
+ reference,
225
+ "Streamed auto-detect text should match the non-streaming result.",
226
+ )
227
+
228
+
229
+ if __name__ == "__main__":
230
+ unittest.main()
asian_ai/performance/SGLang/test/registered/openai_server/features/test_json_mode.py ADDED
@@ -0,0 +1,139 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+ import unittest
3
+
4
+ import openai
5
+
6
+ from sglang.srt.utils import kill_process_tree
7
+ from sglang.test.ci.ci_register import register_amd_ci, register_cuda_ci
8
+ from sglang.test.test_utils import (
9
+ DEFAULT_SMALL_MODEL_NAME_FOR_TEST,
10
+ DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH,
11
+ DEFAULT_URL_FOR_TEST,
12
+ CustomTestCase,
13
+ is_in_amd_ci,
14
+ popen_launch_server,
15
+ )
16
+
17
+ register_cuda_ci(est_time=118, stage="base-b", runner_config="1-gpu-small")
18
+ register_amd_ci(est_time=180, suite="stage-b-test-1-gpu-small-amd")
19
+
20
+
21
+ class JSONModeMixin:
22
+ """Mixin class containing JSON mode test methods"""
23
+
24
+ def test_json_mode_response(self):
25
+ """Test that response_format json_object (also known as "json mode") produces valid JSON, even without a system prompt that mentions JSON."""
26
+ response = self.client.chat.completions.create(
27
+ model=self.model,
28
+ messages=[
29
+ # We are deliberately omitting "That produces JSON" or similar phrases from the assistant prompt so that we don't have misleading test results
30
+ {
31
+ "role": "system",
32
+ "content": "You are a helpful AI assistant that gives a short answer.",
33
+ },
34
+ {"role": "user", "content": "What is the capital of Bulgaria?"},
35
+ ],
36
+ temperature=0,
37
+ max_tokens=128,
38
+ response_format={"type": "json_object"},
39
+ )
40
+ text = response.choices[0].message.content
41
+
42
+ print(f"Response ({len(text)} characters): {text}")
43
+
44
+ # Verify the response is valid JSON
45
+ try:
46
+ js_obj = json.loads(text)
47
+ except json.JSONDecodeError as e:
48
+ self.fail(f"Response is not valid JSON. Error: {e}. Response: {text}")
49
+
50
+ # Verify it's actually an object (dict)
51
+ self.assertIsInstance(js_obj, dict, f"Response is not a JSON object: {text}")
52
+
53
+ def test_json_mode_with_streaming(self):
54
+ """Test that streaming with json_object response (also known as "json mode") format works correctly, even without a system prompt that mentions JSON."""
55
+ stream = self.client.chat.completions.create(
56
+ model=self.model,
57
+ messages=[
58
+ # We are deliberately omitting "That produces JSON" or similar phrases from the assistant prompt so that we don't have misleading test results
59
+ {
60
+ "role": "system",
61
+ "content": "You are a helpful AI assistant that gives a short answer.",
62
+ },
63
+ {"role": "user", "content": "What is the capital of Bulgaria?"},
64
+ ],
65
+ temperature=0,
66
+ max_tokens=128,
67
+ response_format={"type": "json_object"},
68
+ stream=True,
69
+ )
70
+
71
+ # Collect all chunks
72
+ chunks = []
73
+ for chunk in stream:
74
+ if chunk.choices[0].delta.content is not None:
75
+ chunks.append(chunk.choices[0].delta.content)
76
+ full_response = "".join(chunks)
77
+
78
+ print(
79
+ f"Concatenated Response ({len(full_response)} characters): {full_response}"
80
+ )
81
+
82
+ # Verify the combined response is valid JSON
83
+ try:
84
+ js_obj = json.loads(full_response)
85
+ except json.JSONDecodeError as e:
86
+ self.fail(
87
+ f"Streamed response is not valid JSON. Error: {e}. Response: {full_response}"
88
+ )
89
+
90
+ self.assertIsInstance(js_obj, dict)
91
+
92
+
93
+ class ServerWithGrammarBackend(CustomTestCase):
94
+ """Base class for tests requiring a grammar backend server"""
95
+
96
+ backend = "xgrammar"
97
+
98
+ @classmethod
99
+ def setUpClass(cls):
100
+ cls.model = DEFAULT_SMALL_MODEL_NAME_FOR_TEST
101
+ cls.base_url = DEFAULT_URL_FOR_TEST
102
+
103
+ other_args = [
104
+ "--max-running-requests",
105
+ "10",
106
+ "--grammar-backend",
107
+ cls.backend,
108
+ ]
109
+
110
+ if is_in_amd_ci():
111
+ other_args.append("--constrained-json-disable-any-whitespace")
112
+
113
+ cls.process = popen_launch_server(
114
+ cls.model,
115
+ cls.base_url,
116
+ timeout=DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH,
117
+ other_args=other_args,
118
+ )
119
+ cls.client = openai.Client(api_key="EMPTY", base_url=f"{cls.base_url}/v1")
120
+
121
+ @classmethod
122
+ def tearDownClass(cls):
123
+ kill_process_tree(cls.process.pid)
124
+
125
+
126
+ class TestJSONModeXGrammar(ServerWithGrammarBackend, JSONModeMixin):
127
+ backend = "xgrammar"
128
+
129
+
130
+ class TestJSONModeOutlines(ServerWithGrammarBackend, JSONModeMixin):
131
+ backend = "outlines"
132
+
133
+
134
+ class TestJSONModeLLGuidance(ServerWithGrammarBackend, JSONModeMixin):
135
+ backend = "llguidance"
136
+
137
+
138
+ if __name__ == "__main__":
139
+ unittest.main()
asian_ai/performance/SGLang/test/registered/openai_server/features/test_openai_server_ebnf.py ADDED
@@ -0,0 +1,108 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import re
2
+
3
+ import openai
4
+
5
+ from sglang.srt.utils import kill_process_tree
6
+ from sglang.srt.utils.hf_transformers_utils import get_tokenizer
7
+ from sglang.test.ci.ci_register import register_amd_ci, register_cuda_ci
8
+ from sglang.test.test_utils import (
9
+ DEFAULT_SMALL_MODEL_NAME_FOR_TEST,
10
+ DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH,
11
+ DEFAULT_URL_FOR_TEST,
12
+ CustomTestCase,
13
+ popen_launch_server,
14
+ )
15
+
16
+ register_cuda_ci(est_time=44, stage="base-b", runner_config="1-gpu-small")
17
+ register_amd_ci(est_time=20, suite="stage-b-test-1-gpu-small-amd")
18
+
19
+
20
+ # -------------------------------------------------------------------------
21
+ # EBNF Test Class: TestOpenAIServerEBNF
22
+ # Launches the server with xgrammar, has only EBNF tests
23
+ # -------------------------------------------------------------------------
24
+ class TestOpenAIServerEBNF(CustomTestCase):
25
+ @classmethod
26
+ def setUpClass(cls):
27
+ cls.model = DEFAULT_SMALL_MODEL_NAME_FOR_TEST
28
+ cls.base_url = DEFAULT_URL_FOR_TEST
29
+ cls.api_key = "sk-123456"
30
+
31
+ # passing xgrammar specifically
32
+ other_args = ["--grammar-backend", "xgrammar"]
33
+ cls.process = popen_launch_server(
34
+ cls.model,
35
+ cls.base_url,
36
+ timeout=DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH,
37
+ api_key=cls.api_key,
38
+ other_args=other_args,
39
+ )
40
+ cls.base_url += "/v1"
41
+ cls.tokenizer = get_tokenizer(DEFAULT_SMALL_MODEL_NAME_FOR_TEST)
42
+
43
+ @classmethod
44
+ def tearDownClass(cls):
45
+ kill_process_tree(cls.process.pid)
46
+
47
+ def test_ebnf(self):
48
+ """
49
+ Ensure we can pass `ebnf` to the local openai server
50
+ and that it enforces the grammar.
51
+ """
52
+ client = openai.Client(api_key=self.api_key, base_url=self.base_url)
53
+ ebnf_grammar = r"""
54
+ root ::= "Hello" | "Hi" | "Hey"
55
+ """
56
+ pattern = re.compile(r"^(Hello|Hi|Hey)[.!?]*\s*$")
57
+
58
+ response = client.chat.completions.create(
59
+ model=self.model,
60
+ messages=[
61
+ {"role": "system", "content": "You are a helpful EBNF test bot."},
62
+ {"role": "user", "content": "Say a greeting (Hello, Hi, or Hey)."},
63
+ ],
64
+ temperature=0,
65
+ max_tokens=32,
66
+ extra_body={"ebnf": ebnf_grammar},
67
+ )
68
+ text = response.choices[0].message.content.strip()
69
+ self.assertTrue(len(text) > 0, "Got empty text from EBNF generation")
70
+ self.assertRegex(text, pattern, f"Text '{text}' doesn't match EBNF choices")
71
+
72
+ def test_ebnf_strict_json(self):
73
+ """
74
+ A stricter EBNF that produces exactly {"name":"Alice"} format
75
+ with no trailing punctuation or extra fields.
76
+ """
77
+ client = openai.Client(api_key=self.api_key, base_url=self.base_url)
78
+ ebnf_grammar = r"""
79
+ root ::= "{" pair "}"
80
+ pair ::= "\"name\"" ":" string
81
+ string ::= "\"" [A-Za-z]+ "\""
82
+ """
83
+ pattern = re.compile(r'^\{"name":"[A-Za-z]+"\}$')
84
+
85
+ response = client.chat.completions.create(
86
+ model=self.model,
87
+ messages=[
88
+ {"role": "system", "content": "EBNF mini-JSON generator."},
89
+ {
90
+ "role": "user",
91
+ "content": "Generate single key JSON with only letters.",
92
+ },
93
+ ],
94
+ temperature=0,
95
+ max_tokens=64,
96
+ extra_body={"ebnf": ebnf_grammar},
97
+ )
98
+ text = response.choices[0].message.content.strip()
99
+ self.assertTrue(len(text) > 0, "Got empty text from EBNF strict JSON test")
100
+ self.assertRegex(
101
+ text, pattern, f"Text '{text}' not matching the EBNF strict JSON shape"
102
+ )
103
+
104
+
105
+ if __name__ == "__main__":
106
+ import unittest
107
+
108
+ unittest.main()
asian_ai/performance/SGLang/test/registered/openai_server/features/test_openai_server_hidden_states.py ADDED
@@ -0,0 +1,358 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import unittest
2
+ from abc import ABC
3
+
4
+ import openai
5
+
6
+ from sglang.srt.utils import kill_process_tree
7
+ from sglang.srt.utils.hf_transformers_utils import get_tokenizer
8
+ from sglang.test.ci.ci_register import register_amd_ci, register_cuda_ci
9
+ from sglang.test.test_utils import (
10
+ DEFAULT_DRAFT_MODEL_EAGLE,
11
+ DEFAULT_SMALL_MODEL_NAME_FOR_TEST,
12
+ DEFAULT_TARGET_MODEL_EAGLE,
13
+ DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH,
14
+ DEFAULT_URL_FOR_TEST,
15
+ CustomTestCase,
16
+ popen_launch_server,
17
+ )
18
+
19
+ register_cuda_ci(est_time=222, stage="base-b", runner_config="1-gpu-small")
20
+ register_amd_ci(
21
+ est_time=186,
22
+ suite="stage-b-test-1-gpu-small-amd",
23
+ disabled="see https://github.com/sgl-project/sglang/issues/11127",
24
+ )
25
+
26
+
27
+ class BaseTestOpenAIServerWithHiddenStates(ABC):
28
+
29
+ @classmethod
30
+ def setUpClass(cls):
31
+ cls.return_hidden_states = [False, True]
32
+ cls.use_list_input = [True, False]
33
+ cls.parallel_sample_nums = [1, 2]
34
+
35
+ def test_completion(self):
36
+ for return_hidden_states in self.return_hidden_states:
37
+ for use_list_input in self.use_list_input:
38
+ for parallel_sample_num in self.parallel_sample_nums:
39
+ self.run_completion(
40
+ use_list_input,
41
+ parallel_sample_num,
42
+ return_hidden_states,
43
+ )
44
+
45
+ def test_completion_stream(self):
46
+ # parallel sampling and list input are not supported in streaming mode
47
+ for return_hidden_states in self.return_hidden_states:
48
+ for use_list_input in self.use_list_input:
49
+ for parallel_sample_num in self.parallel_sample_nums:
50
+ self.run_completion_stream(
51
+ use_list_input,
52
+ parallel_sample_num,
53
+ return_hidden_states,
54
+ )
55
+
56
+ def test_chat_completion(self):
57
+ for return_hidden_states in self.return_hidden_states:
58
+ for (
59
+ parallel_sample_num
60
+ ) in (
61
+ self.parallel_sample_nums
62
+ ): # parallel sample num 2 breaks in the adapter with a 400 for EAGLE
63
+ self.run_chat_completion(parallel_sample_num, return_hidden_states)
64
+
65
+ def test_chat_completion_stream(self):
66
+ for return_hidden_states in self.return_hidden_states:
67
+ for (
68
+ parallel_sample_num
69
+ ) in (
70
+ self.parallel_sample_nums
71
+ ): # parallel sample num > 1 breaks in the adapter with a 400 for EAGLE
72
+ self.run_chat_completion_stream(
73
+ parallel_sample_num, return_hidden_states
74
+ )
75
+
76
+ def run_completion(
77
+ self,
78
+ use_list_input,
79
+ parallel_sample_num,
80
+ return_hidden_states,
81
+ ):
82
+ client = openai.Client(api_key=self.api_key, base_url=self.base_url)
83
+ prompt = "The capital of France is"
84
+ prompt_input = prompt
85
+
86
+ if use_list_input:
87
+ prompt_arg = [prompt_input, prompt_input]
88
+ num_choices = len(prompt_arg)
89
+ else:
90
+ prompt_arg = prompt_input
91
+ num_choices = 1
92
+
93
+ response = client.completions.create(
94
+ model=self.model,
95
+ prompt=prompt_arg,
96
+ temperature=0,
97
+ max_tokens=32,
98
+ n=parallel_sample_num,
99
+ extra_body=dict(return_hidden_states=return_hidden_states),
100
+ )
101
+
102
+ for choice in response.choices:
103
+ assert hasattr(choice, "hidden_states") == return_hidden_states
104
+ if return_hidden_states:
105
+ assert choice.hidden_states is not None, "hidden_states was None"
106
+
107
+ def run_completion_stream(
108
+ self,
109
+ use_list_input,
110
+ parallel_sample_num,
111
+ return_hidden_states,
112
+ ):
113
+ client = openai.Client(api_key=self.api_key, base_url=self.base_url)
114
+ prompt = "The capital of France is"
115
+ prompt_input = prompt
116
+ num_prompt_tokens = len(self.tokenizer.encode(prompt))
117
+
118
+ if use_list_input:
119
+ prompt_arg = [prompt_input, prompt_input]
120
+ num_choices = len(prompt_arg)
121
+ num_prompt_tokens *= 2
122
+ else:
123
+ prompt_arg = prompt_input
124
+ num_choices = 1
125
+
126
+ generator = client.completions.create(
127
+ model=self.model,
128
+ prompt=prompt_arg,
129
+ temperature=0,
130
+ max_tokens=32,
131
+ stream=True,
132
+ stream_options={"include_usage": True},
133
+ n=parallel_sample_num,
134
+ extra_body=dict(return_hidden_states=return_hidden_states),
135
+ )
136
+
137
+ hidden_states_list = []
138
+ for response in generator:
139
+ usage = response.usage
140
+ for choice in response.choices:
141
+ if hasattr(choice, "hidden_states"):
142
+ assert return_hidden_states
143
+ assert choice.hidden_states is not None
144
+ hidden_states_list.append(choice.hidden_states)
145
+
146
+ if return_hidden_states:
147
+ assert (
148
+ len(hidden_states_list) == parallel_sample_num * num_choices
149
+ ), f"Expected {parallel_sample_num * num_choices} hidden states, got {len(hidden_states_list)}"
150
+ else:
151
+ assert (
152
+ hidden_states_list == []
153
+ ), "hidden_states were returned and should not have been"
154
+
155
+ def run_chat_completion(self, parallel_sample_num, return_hidden_states):
156
+ client = openai.Client(api_key=self.api_key, base_url=self.base_url)
157
+ response = client.chat.completions.create(
158
+ model=self.model,
159
+ messages=[
160
+ {"role": "system", "content": "You are a helpful AI assistant"},
161
+ {
162
+ "role": "user",
163
+ "content": "What is the capital of France? Answer in a few words.",
164
+ },
165
+ ],
166
+ temperature=0,
167
+ n=parallel_sample_num,
168
+ extra_body=dict(return_hidden_states=return_hidden_states),
169
+ )
170
+
171
+ for choice in response.choices:
172
+ assert hasattr(choice, "hidden_states") == return_hidden_states
173
+ if return_hidden_states:
174
+ assert choice.hidden_states is not None, "hidden_states was None"
175
+
176
+ def run_chat_completion_stream(
177
+ self, parallel_sample_num=1, return_hidden_states=False
178
+ ):
179
+ client = openai.Client(api_key=self.api_key, base_url=self.base_url)
180
+ generator = client.chat.completions.create(
181
+ model=self.model,
182
+ messages=[
183
+ {"role": "system", "content": "You are a helpful AI assistant"},
184
+ {"role": "user", "content": "What is the capital of France?"},
185
+ ],
186
+ temperature=0,
187
+ stream=True,
188
+ stream_options={"include_usage": True},
189
+ n=parallel_sample_num,
190
+ extra_body=dict(return_hidden_states=return_hidden_states),
191
+ )
192
+
193
+ is_firsts = {}
194
+ hidden_states_list = []
195
+
196
+ for response in generator:
197
+ for choice in response.choices:
198
+ if hasattr(choice.delta, "hidden_states"):
199
+ assert return_hidden_states
200
+ assert choice.delta.hidden_states is not None
201
+ hidden_states_list.append(choice.delta.hidden_states)
202
+
203
+ if return_hidden_states:
204
+ assert (
205
+ len(hidden_states_list) == parallel_sample_num
206
+ ), f"Expected {parallel_sample_num} hidden states, got {len(hidden_states_list)}"
207
+ else:
208
+ assert (
209
+ hidden_states_list == []
210
+ ), "hidden_states were returned and should not have been"
211
+
212
+
213
+ class TestOpenAIServerWithHiddenStatesEnabled(
214
+ CustomTestCase, BaseTestOpenAIServerWithHiddenStates
215
+ ):
216
+ @classmethod
217
+ def setUpClass(cls):
218
+ cls.model = DEFAULT_SMALL_MODEL_NAME_FOR_TEST
219
+ cls.base_url = DEFAULT_URL_FOR_TEST
220
+ cls.api_key = "sk-123456"
221
+ cls.process = popen_launch_server(
222
+ cls.model,
223
+ cls.base_url,
224
+ timeout=DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH,
225
+ api_key=cls.api_key,
226
+ other_args=["--enable-return-hidden-states"],
227
+ )
228
+ cls.base_url += "/v1"
229
+ cls.tokenizer = get_tokenizer(DEFAULT_SMALL_MODEL_NAME_FOR_TEST)
230
+ cls.return_hidden_states = [False, True]
231
+ cls.use_list_input = [True, False]
232
+ cls.parallel_sample_nums = [1, 2]
233
+
234
+ @classmethod
235
+ def tearDownClass(cls):
236
+ kill_process_tree(cls.process.pid)
237
+
238
+
239
+ class TestOpenAIServerWithHiddenStatesEnabledAndCUDAGraphDisabled(
240
+ CustomTestCase, BaseTestOpenAIServerWithHiddenStates
241
+ ):
242
+ @classmethod
243
+ def setUpClass(cls):
244
+ cls.model = DEFAULT_SMALL_MODEL_NAME_FOR_TEST
245
+ cls.base_url = DEFAULT_URL_FOR_TEST
246
+ cls.api_key = "sk-123456"
247
+ cls.process = popen_launch_server(
248
+ cls.model,
249
+ cls.base_url,
250
+ timeout=DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH,
251
+ api_key=cls.api_key,
252
+ other_args=["--enable-return-hidden-states", "--disable-cuda-graph"],
253
+ )
254
+ cls.base_url += "/v1"
255
+ cls.tokenizer = get_tokenizer(DEFAULT_SMALL_MODEL_NAME_FOR_TEST)
256
+ cls.return_hidden_states = [False, True]
257
+ cls.use_list_input = [True, False]
258
+ cls.parallel_sample_nums = [1]
259
+
260
+ @classmethod
261
+ def tearDownClass(cls):
262
+ kill_process_tree(cls.process.pid)
263
+
264
+
265
+ class TestOpenAIServerWithEAGLEAndHiddenStatesEnabled(
266
+ CustomTestCase, BaseTestOpenAIServerWithHiddenStates
267
+ ):
268
+ @classmethod
269
+ def setUpClass(cls):
270
+ cls.model = DEFAULT_TARGET_MODEL_EAGLE
271
+ cls.base_url = DEFAULT_URL_FOR_TEST
272
+ cls.api_key = "sk-123456"
273
+ cls.speculative_draft_model = DEFAULT_DRAFT_MODEL_EAGLE
274
+ cls.speculative_algorithm = "EAGLE"
275
+ cls.process = popen_launch_server(
276
+ cls.model,
277
+ cls.base_url,
278
+ timeout=DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH,
279
+ other_args=[
280
+ "--speculative-algorithm",
281
+ "EAGLE",
282
+ "--speculative-draft-model-path",
283
+ DEFAULT_DRAFT_MODEL_EAGLE,
284
+ "--speculative-num-steps",
285
+ 5,
286
+ "--speculative-eagle-topk",
287
+ 8,
288
+ "--speculative-num-draft-tokens",
289
+ 64,
290
+ "--mem-fraction-static",
291
+ 0.7,
292
+ "--chunked-prefill-size",
293
+ 128,
294
+ "--max-running-requests",
295
+ 8,
296
+ "--enable-return-hidden-states",
297
+ ],
298
+ )
299
+ cls.base_url += "/v1"
300
+ cls.tokenizer = get_tokenizer(DEFAULT_TARGET_MODEL_EAGLE)
301
+ cls.return_hidden_states = [False, True]
302
+ cls.use_list_input = [True, False]
303
+ cls.parallel_sample_nums = [1]
304
+
305
+ @classmethod
306
+ def tearDownClass(cls):
307
+ kill_process_tree(cls.process.pid)
308
+
309
+
310
+ class TestOpenAIServerWithEAGLE3AndHiddenStatesEnabled(
311
+ CustomTestCase, BaseTestOpenAIServerWithHiddenStates
312
+ ):
313
+ @classmethod
314
+ def setUpClass(cls):
315
+ cls.model = "meta-llama/Llama-3.1-8B-Instruct"
316
+ cls.base_url = DEFAULT_URL_FOR_TEST
317
+ cls.api_key = "sk-123456"
318
+ cls.speculative_algorithm = "EAGLE3"
319
+ cls.speculative_draft_model = "jamesliu1/sglang-EAGLE3-Llama-3.1-Instruct-8B"
320
+ cls.process = popen_launch_server(
321
+ cls.model,
322
+ cls.base_url,
323
+ timeout=DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH,
324
+ other_args=[
325
+ "--speculative-algorithm",
326
+ cls.speculative_algorithm,
327
+ "--speculative-draft-model-path",
328
+ cls.speculative_draft_model,
329
+ "--speculative-num-steps",
330
+ 5,
331
+ "--speculative-eagle-topk",
332
+ 16,
333
+ "--speculative-num-draft-tokens",
334
+ 64,
335
+ "--mem-fraction-static",
336
+ 0.7,
337
+ "--chunked-prefill-size",
338
+ 128,
339
+ "--max-running-requests",
340
+ 8,
341
+ "--dtype",
342
+ "float16",
343
+ "--enable-return-hidden-states",
344
+ ],
345
+ )
346
+ cls.base_url += "/v1"
347
+ cls.tokenizer = get_tokenizer(cls.model)
348
+ cls.return_hidden_states = [False, True]
349
+ cls.use_list_input = [True, False]
350
+ cls.parallel_sample_nums = [1]
351
+
352
+ @classmethod
353
+ def tearDownClass(cls):
354
+ kill_process_tree(cls.process.pid)
355
+
356
+
357
+ if __name__ == "__main__":
358
+ unittest.main()
asian_ai/performance/SGLang/test/registered/openai_server/function_call/test_anthropic_tool_use.py ADDED
@@ -0,0 +1,555 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Tests for Anthropic-compatible tool use via the /v1/messages endpoint.
3
+
4
+ python3 -m unittest openai_server.function_call.test_anthropic_tool_use.TestAnthropicToolUse.test_tool_use_format
5
+ python3 -m unittest openai_server.function_call.test_anthropic_tool_use.TestAnthropicToolUse.test_tool_use_streaming
6
+ python3 -m unittest openai_server.function_call.test_anthropic_tool_use.TestAnthropicToolUse.test_tool_use_streaming_args_parsing
7
+ python3 -m unittest openai_server.function_call.test_anthropic_tool_use.TestAnthropicToolUse.test_tool_choice_auto
8
+ python3 -m unittest openai_server.function_call.test_anthropic_tool_use.TestAnthropicToolUse.test_tool_choice_any
9
+ python3 -m unittest openai_server.function_call.test_anthropic_tool_use.TestAnthropicToolUse.test_tool_choice_specific
10
+ python3 -m unittest openai_server.function_call.test_anthropic_tool_use.TestAnthropicToolUse.test_tool_result_multi_turn
11
+ """
12
+
13
+ import json
14
+ import unittest
15
+
16
+ import requests
17
+
18
+ from sglang.srt.utils import kill_process_tree
19
+ from sglang.test.ci.ci_register import register_amd_ci, register_cuda_ci
20
+ from sglang.test.test_utils import (
21
+ DEFAULT_SMALL_MODEL_NAME_FOR_TEST,
22
+ DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH,
23
+ DEFAULT_URL_FOR_TEST,
24
+ CustomTestCase,
25
+ popen_launch_server,
26
+ )
27
+
28
+ register_cuda_ci(est_time=50, stage="base-b", runner_config="1-gpu-large")
29
+ register_amd_ci(est_time=140, suite="stage-b-test-1-gpu-small-amd")
30
+
31
+ # System message to guide Llama3.2 to produce proper tool call format
32
+ SYSTEM_MESSAGE = (
33
+ "You are a helpful assistant with tool calling capabilities. "
34
+ "Only reply with a tool call if the function exists in the library provided by the user. "
35
+ "If it doesn't exist, just reply directly in natural language. "
36
+ "When you receive a tool call response, use the output to format an answer to the original user question. "
37
+ "You have access to the following functions. "
38
+ "To call a function, please respond with JSON for a function call. "
39
+ 'Respond in the format {"name": function name, "parameters": dictionary of argument name and its value}. '
40
+ "Do not use variables.\n\n"
41
+ )
42
+
43
+ ADD_TOOL = {
44
+ "name": "add",
45
+ "description": "Compute the sum of two integers",
46
+ "input_schema": {
47
+ "type": "object",
48
+ "properties": {
49
+ "a": {"type": "integer", "description": "First integer"},
50
+ "b": {"type": "integer", "description": "Second integer"},
51
+ },
52
+ "required": ["a", "b"],
53
+ },
54
+ }
55
+
56
+ WEATHER_TOOL = {
57
+ "name": "get_current_weather",
58
+ "description": "Get the current weather in a given location",
59
+ "input_schema": {
60
+ "type": "object",
61
+ "properties": {
62
+ "city": {
63
+ "type": "string",
64
+ "description": "The city to find the weather for",
65
+ },
66
+ "unit": {
67
+ "type": "string",
68
+ "description": "Weather unit (celsius or fahrenheit)",
69
+ "enum": ["celsius", "fahrenheit"],
70
+ },
71
+ },
72
+ "required": ["city", "unit"],
73
+ },
74
+ }
75
+
76
+
77
+ class TestAnthropicToolUse(CustomTestCase):
78
+ @classmethod
79
+ def setUpClass(cls):
80
+ cls.model = DEFAULT_SMALL_MODEL_NAME_FOR_TEST
81
+ cls.base_url = DEFAULT_URL_FOR_TEST
82
+ cls.api_key = "sk-123456"
83
+ cls.process = popen_launch_server(
84
+ cls.model,
85
+ cls.base_url,
86
+ timeout=DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH,
87
+ api_key=cls.api_key,
88
+ other_args=[
89
+ "--tool-call-parser",
90
+ "llama3",
91
+ ],
92
+ )
93
+ cls.messages_url = cls.base_url + "/v1/messages"
94
+
95
+ @classmethod
96
+ def tearDownClass(cls):
97
+ kill_process_tree(cls.process.pid)
98
+
99
+ def _make_request(self, payload, stream=False):
100
+ """Send a request to the /v1/messages endpoint."""
101
+ headers = {
102
+ "Content-Type": "application/json",
103
+ "Authorization": f"Bearer {self.api_key}",
104
+ }
105
+ return requests.post(
106
+ self.messages_url,
107
+ headers=headers,
108
+ json=payload,
109
+ stream=stream,
110
+ )
111
+
112
+ def _parse_sse_events(self, response):
113
+ """Parse SSE events from a streaming response."""
114
+ events = []
115
+ for line in response.iter_lines(decode_unicode=True):
116
+ if not line:
117
+ continue
118
+ if line.startswith("data: "):
119
+ data_str = line[6:].strip()
120
+ if data_str == "[DONE]":
121
+ continue
122
+ try:
123
+ events.append(json.loads(data_str))
124
+ except json.JSONDecodeError:
125
+ pass
126
+ return events
127
+
128
+ # ---- Non-streaming tool use tests ----
129
+
130
+ def test_tool_use_format(self):
131
+ """Test that tool use returns proper Anthropic content blocks."""
132
+ payload = {
133
+ "model": self.model,
134
+ "max_tokens": 2048,
135
+ "system": SYSTEM_MESSAGE,
136
+ "messages": [
137
+ {"role": "user", "content": "Compute (3+5)"},
138
+ ],
139
+ "tools": [ADD_TOOL],
140
+ "temperature": 0.8,
141
+ "top_p": 0.8,
142
+ }
143
+ resp = self._make_request(payload)
144
+ self.assertEqual(resp.status_code, 200, f"Response: {resp.text}")
145
+
146
+ body = resp.json()
147
+ self.assertEqual(body["type"], "message")
148
+
149
+ # Find tool_use content blocks
150
+ tool_use_blocks = [b for b in body["content"] if b["type"] == "tool_use"]
151
+ self.assertTrue(
152
+ len(tool_use_blocks) > 0,
153
+ f"Expected tool_use content blocks, got: {body['content']}",
154
+ )
155
+
156
+ tool_block = tool_use_blocks[0]
157
+ self.assertEqual(tool_block["name"], "add", "Tool name should be 'add'")
158
+ self.assertIn("id", tool_block, "Tool use block should have an id")
159
+ self.assertIn("input", tool_block, "Tool use block should have input")
160
+ self.assertIsInstance(tool_block["input"], dict)
161
+
162
+ # Verify stop_reason is tool_use
163
+ self.assertEqual(
164
+ body["stop_reason"],
165
+ "tool_use",
166
+ f"Expected stop_reason 'tool_use', got: {body['stop_reason']}",
167
+ )
168
+
169
+ def test_tool_choice_auto(self):
170
+ """Test tool_choice type=auto (default when tools provided)."""
171
+ payload = {
172
+ "model": self.model,
173
+ "max_tokens": 2048,
174
+ "system": SYSTEM_MESSAGE,
175
+ "messages": [
176
+ {"role": "user", "content": "Compute (3+5)"},
177
+ ],
178
+ "tools": [ADD_TOOL],
179
+ "tool_choice": {"type": "auto"},
180
+ }
181
+ resp = self._make_request(payload)
182
+ self.assertEqual(resp.status_code, 200, f"Response: {resp.text}")
183
+
184
+ body = resp.json()
185
+ self.assertEqual(body["type"], "message")
186
+ # With auto, model may or may not use tools - just verify valid response
187
+ self.assertIsInstance(body["content"], list)
188
+
189
+ def test_tool_choice_any(self):
190
+ """Test tool_choice type=any (maps to required)."""
191
+ payload = {
192
+ "model": self.model,
193
+ "max_tokens": 2048,
194
+ "system": SYSTEM_MESSAGE,
195
+ "messages": [
196
+ {
197
+ "role": "user",
198
+ "content": "What is the weather in Paris in celsius?",
199
+ },
200
+ ],
201
+ "tools": [WEATHER_TOOL],
202
+ "tool_choice": {"type": "any"},
203
+ }
204
+ resp = self._make_request(payload)
205
+ self.assertEqual(resp.status_code, 200, f"Response: {resp.text}")
206
+
207
+ body = resp.json()
208
+ self.assertEqual(body["type"], "message")
209
+
210
+ # With 'any', the model must use a tool
211
+ tool_use_blocks = [b for b in body["content"] if b["type"] == "tool_use"]
212
+ self.assertTrue(
213
+ len(tool_use_blocks) > 0,
214
+ f"Expected tool_use blocks with tool_choice=any, got: {body['content']}",
215
+ )
216
+
217
+ def test_tool_choice_specific(self):
218
+ """Test tool_choice type=tool with specific tool name."""
219
+ payload = {
220
+ "model": self.model,
221
+ "max_tokens": 2048,
222
+ "system": SYSTEM_MESSAGE,
223
+ "messages": [
224
+ {"role": "user", "content": "What is the capital of France?"},
225
+ ],
226
+ "tools": [ADD_TOOL, WEATHER_TOOL],
227
+ "tool_choice": {"type": "tool", "name": "get_current_weather"},
228
+ }
229
+ resp = self._make_request(payload)
230
+ self.assertEqual(resp.status_code, 200, f"Response: {resp.text}")
231
+
232
+ body = resp.json()
233
+ self.assertEqual(body["type"], "message")
234
+
235
+ # With specific tool choice, the model should call that specific tool
236
+ tool_use_blocks = [b for b in body["content"] if b["type"] == "tool_use"]
237
+ self.assertTrue(
238
+ len(tool_use_blocks) > 0,
239
+ f"Expected tool_use blocks with specific tool_choice, got: {body['content']}",
240
+ )
241
+ for block in tool_use_blocks:
242
+ self.assertEqual(
243
+ block["name"],
244
+ "get_current_weather",
245
+ f"Expected tool name 'get_current_weather', got: {block['name']}",
246
+ )
247
+
248
+ def test_tool_result_multi_turn(self):
249
+ """Test multi-turn conversation with tool_result messages."""
250
+ # First turn: request a tool call
251
+ payload_1 = {
252
+ "model": self.model,
253
+ "max_tokens": 2048,
254
+ "system": SYSTEM_MESSAGE,
255
+ "messages": [
256
+ {"role": "user", "content": "Compute (3+5)"},
257
+ ],
258
+ "tools": [ADD_TOOL],
259
+ "temperature": 0.8,
260
+ }
261
+ resp_1 = self._make_request(payload_1)
262
+ self.assertEqual(resp_1.status_code, 200, f"Response: {resp_1.text}")
263
+ body_1 = resp_1.json()
264
+
265
+ # Extract tool call info
266
+ tool_use_blocks = [b for b in body_1["content"] if b["type"] == "tool_use"]
267
+ self.assertTrue(len(tool_use_blocks) > 0, "Expected tool_use in first response")
268
+ tool_call_id = tool_use_blocks[0]["id"]
269
+
270
+ # Second turn: send tool_result back
271
+ payload_2 = {
272
+ "model": self.model,
273
+ "max_tokens": 2048,
274
+ "system": SYSTEM_MESSAGE,
275
+ "messages": [
276
+ {"role": "user", "content": "Compute (3+5)"},
277
+ {
278
+ "role": "assistant",
279
+ "content": body_1["content"],
280
+ },
281
+ {
282
+ "role": "user",
283
+ "content": [
284
+ {
285
+ "type": "tool_result",
286
+ "id": tool_call_id,
287
+ "content": "8",
288
+ }
289
+ ],
290
+ },
291
+ ],
292
+ "tools": [ADD_TOOL],
293
+ }
294
+ resp_2 = self._make_request(payload_2)
295
+ self.assertEqual(resp_2.status_code, 200, f"Response: {resp_2.text}")
296
+
297
+ body_2 = resp_2.json()
298
+ self.assertEqual(body_2["type"], "message")
299
+ self.assertTrue(
300
+ len(body_2["content"]) > 0, "Second response should have content"
301
+ )
302
+
303
+ def test_tool_use_with_text_content(self):
304
+ """Test that response can contain both text and tool_use blocks."""
305
+ payload = {
306
+ "model": self.model,
307
+ "max_tokens": 2048,
308
+ "system": SYSTEM_MESSAGE,
309
+ "messages": [
310
+ {"role": "user", "content": "Compute (3+5)"},
311
+ ],
312
+ "tools": [ADD_TOOL],
313
+ "tool_choice": {"type": "auto"},
314
+ "temperature": 0.8,
315
+ }
316
+ resp = self._make_request(payload)
317
+ self.assertEqual(resp.status_code, 200, f"Response: {resp.text}")
318
+
319
+ body = resp.json()
320
+ self.assertEqual(body["type"], "message")
321
+ self.assertIsInstance(body["content"], list)
322
+ # Verify that content has valid block types
323
+ for block in body["content"]:
324
+ self.assertIn(
325
+ block["type"],
326
+ ["text", "tool_use"],
327
+ f"Unexpected content block type: {block['type']}",
328
+ )
329
+
330
+ # ---- Streaming tool use tests ----
331
+
332
+ def test_tool_use_streaming(self):
333
+ """Test streaming tool use returns proper Anthropic events."""
334
+ payload = {
335
+ "model": self.model,
336
+ "max_tokens": 2048,
337
+ "stream": True,
338
+ "system": SYSTEM_MESSAGE,
339
+ "messages": [
340
+ {
341
+ "role": "user",
342
+ "content": "What is the temperature in Paris in celsius?",
343
+ },
344
+ ],
345
+ "tools": [WEATHER_TOOL],
346
+ "tool_choice": {"type": "any"},
347
+ }
348
+ resp = self._make_request(payload, stream=True)
349
+ self.assertEqual(resp.status_code, 200)
350
+
351
+ events = self._parse_sse_events(resp)
352
+ event_types = [e["type"] for e in events]
353
+
354
+ # Verify basic event sequence
355
+ self.assertIn("message_start", event_types)
356
+ self.assertIn("message_stop", event_types)
357
+
358
+ # Check for tool use content block events
359
+ block_starts = [e for e in events if e["type"] == "content_block_start"]
360
+ tool_use_starts = [
361
+ e
362
+ for e in block_starts
363
+ if e.get("content_block", {}).get("type") == "tool_use"
364
+ ]
365
+
366
+ self.assertTrue(
367
+ len(tool_use_starts) > 0,
368
+ "Expected tool_use content_block_start events with tool_choice=any",
369
+ )
370
+
371
+ # Verify tool_use content_block_start has proper structure
372
+ tool_start = tool_use_starts[0]
373
+ self.assertIn("content_block", tool_start)
374
+ self.assertEqual(tool_start["content_block"]["type"], "tool_use")
375
+ self.assertIn("id", tool_start["content_block"])
376
+ self.assertIn("name", tool_start["content_block"])
377
+
378
+ # Check for input_json_delta events
379
+ input_deltas = [
380
+ e
381
+ for e in events
382
+ if e["type"] == "content_block_delta"
383
+ and e.get("delta", {}).get("type") == "input_json_delta"
384
+ ]
385
+ # Tool calls should have at least some argument deltas
386
+ self.assertTrue(
387
+ len(input_deltas) > 0,
388
+ "Expected input_json_delta events for tool call",
389
+ )
390
+
391
+ # Verify message_delta has stop_reason=tool_use
392
+ message_deltas = [e for e in events if e["type"] == "message_delta"]
393
+ self.assertTrue(len(message_deltas) > 0)
394
+ self.assertEqual(
395
+ message_deltas[-1]["delta"]["stop_reason"],
396
+ "tool_use",
397
+ "Expected stop_reason 'tool_use' in streaming",
398
+ )
399
+
400
+ def test_tool_use_streaming_args_parsing(self):
401
+ """Test that streaming tool call arguments can be concatenated into valid JSON."""
402
+ payload = {
403
+ "model": self.model,
404
+ "max_tokens": 2048,
405
+ "stream": True,
406
+ "system": SYSTEM_MESSAGE,
407
+ "messages": [
408
+ {
409
+ "role": "user",
410
+ "content": "Please sum 5 and 7, just call the function.",
411
+ },
412
+ ],
413
+ "tools": [
414
+ {
415
+ "name": "add",
416
+ "description": "Compute the sum of two integers",
417
+ "input_schema": {
418
+ "type": "object",
419
+ "properties": {
420
+ "a": {"type": "integer", "description": "First integer"},
421
+ "b": {"type": "integer", "description": "Second integer"},
422
+ },
423
+ "required": ["a", "b"],
424
+ },
425
+ }
426
+ ],
427
+ }
428
+ resp = self._make_request(payload, stream=True)
429
+ self.assertEqual(resp.status_code, 200)
430
+
431
+ events = self._parse_sse_events(resp)
432
+
433
+ # Collect tool call data from stream
434
+ tool_name = None
435
+ argument_fragments = []
436
+
437
+ for event in events:
438
+ if event["type"] == "content_block_start":
439
+ cb = event.get("content_block", {})
440
+ if cb.get("type") == "tool_use":
441
+ tool_name = cb.get("name")
442
+ elif event["type"] == "content_block_delta":
443
+ delta = event.get("delta", {})
444
+ if delta.get("type") == "input_json_delta":
445
+ partial = delta.get("partial_json", "")
446
+ if partial:
447
+ argument_fragments.append(partial)
448
+
449
+ if tool_name is not None:
450
+ # If we got a tool call, verify arguments are valid JSON
451
+ self.assertEqual(tool_name, "add", "Tool name should be 'add'")
452
+ joined_args = "".join(argument_fragments)
453
+ self.assertTrue(
454
+ len(joined_args) > 0,
455
+ "No argument fragments returned for tool call",
456
+ )
457
+
458
+ try:
459
+ args_obj = json.loads(joined_args)
460
+ except json.JSONDecodeError:
461
+ self.fail(
462
+ f"Concatenated tool call arguments are not valid JSON: {joined_args}"
463
+ )
464
+
465
+ self.assertIn("a", args_obj, "Missing parameter 'a'")
466
+ self.assertIn("b", args_obj, "Missing parameter 'b'")
467
+
468
+ def test_tool_use_streaming_event_sequence(self):
469
+ """Test that streaming tool use events follow the correct order."""
470
+ payload = {
471
+ "model": self.model,
472
+ "max_tokens": 2048,
473
+ "stream": True,
474
+ "system": SYSTEM_MESSAGE,
475
+ "messages": [
476
+ {"role": "user", "content": "Compute (3+5)"},
477
+ ],
478
+ "tools": [ADD_TOOL],
479
+ "tool_choice": {"type": "any"},
480
+ }
481
+ resp = self._make_request(payload, stream=True)
482
+ self.assertEqual(resp.status_code, 200)
483
+
484
+ events = self._parse_sse_events(resp)
485
+ event_types = [e["type"] for e in events]
486
+
487
+ # message_start must be first
488
+ self.assertEqual(
489
+ event_types[0],
490
+ "message_start",
491
+ "First event should be message_start",
492
+ )
493
+
494
+ # message_stop must be last
495
+ self.assertEqual(
496
+ event_types[-1],
497
+ "message_stop",
498
+ "Last event should be message_stop",
499
+ )
500
+
501
+ # message_delta should come before message_stop
502
+ self.assertIn("message_delta", event_types)
503
+ delta_idx = event_types.index("message_delta")
504
+ stop_idx = event_types.index("message_stop")
505
+ self.assertLess(
506
+ delta_idx, stop_idx, "message_delta should come before message_stop"
507
+ )
508
+
509
+ # For each content block, start should come before stop
510
+ block_start_indices = [
511
+ i for i, t in enumerate(event_types) if t == "content_block_start"
512
+ ]
513
+ block_stop_indices = [
514
+ i for i, t in enumerate(event_types) if t == "content_block_stop"
515
+ ]
516
+ self.assertEqual(
517
+ len(block_start_indices),
518
+ len(block_stop_indices),
519
+ "Number of content_block_start should equal content_block_stop",
520
+ )
521
+ for start_i, stop_i in zip(block_start_indices, block_stop_indices):
522
+ self.assertLess(
523
+ start_i,
524
+ stop_i,
525
+ "content_block_start should come before content_block_stop",
526
+ )
527
+
528
+ def test_no_tools_no_tool_use(self):
529
+ """Test that without tools, no tool_use blocks appear."""
530
+ payload = {
531
+ "model": self.model,
532
+ "max_tokens": 64,
533
+ "messages": [
534
+ {"role": "user", "content": "What is the capital of France?"},
535
+ ],
536
+ }
537
+ resp = self._make_request(payload)
538
+ self.assertEqual(resp.status_code, 200, f"Response: {resp.text}")
539
+
540
+ body = resp.json()
541
+ tool_use_blocks = [b for b in body["content"] if b["type"] == "tool_use"]
542
+ self.assertEqual(
543
+ len(tool_use_blocks),
544
+ 0,
545
+ "Should not have tool_use blocks when no tools provided",
546
+ )
547
+ self.assertIn(
548
+ body["stop_reason"],
549
+ ["end_turn", "max_tokens"],
550
+ "Stop reason should be end_turn or max_tokens without tools",
551
+ )
552
+
553
+
554
+ if __name__ == "__main__":
555
+ unittest.main()
asian_ai/performance/SGLang/test/registered/openai_server/function_call/test_openai_function_calling.py ADDED
@@ -0,0 +1,954 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+ import unittest
3
+
4
+ import openai
5
+
6
+ from sglang.srt.utils import kill_process_tree
7
+ from sglang.srt.utils.hf_transformers_utils import get_tokenizer
8
+ from sglang.test.ci.ci_register import register_amd_ci, register_cuda_ci
9
+ from sglang.test.test_utils import (
10
+ DEFAULT_SMALL_MODEL_NAME_FOR_TEST,
11
+ DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH,
12
+ DEFAULT_URL_FOR_TEST,
13
+ CustomTestCase,
14
+ popen_launch_server,
15
+ )
16
+
17
+ register_cuda_ci(est_time=100, stage="base-b", runner_config="1-gpu-large")
18
+ register_amd_ci(est_time=73, suite="stage-b-test-1-gpu-small-amd")
19
+
20
+
21
+ class TestOpenAIServerFunctionCalling(CustomTestCase):
22
+ # NOTE: this system_message is for Llama3.2 system prompt. Without this,
23
+ # sometimes Llama3.2 gives a different tool call format such as:
24
+ # '<|python_tag|>{"type": "function", "function": "add", "parameters": {"a": "3", "b": "5"}}'
25
+ SYSTEM_MESSAGE = (
26
+ "You are a helpful assistant with tool calling capabilities. "
27
+ "Only reply with a tool call if the function exists in the library provided by the user. "
28
+ "If it doesn't exist, just reply directly in natural language. "
29
+ "When you receive a tool call response, use the output to format an answer to the original user question. "
30
+ "You have access to the following functions. "
31
+ "To call a function, please respond with JSON for a function call. "
32
+ 'Respond in the format {"name": function name, "parameters": dictionary of argument name and its value}. '
33
+ "Do not use variables.\n\n"
34
+ )
35
+
36
+ @classmethod
37
+ def setUpClass(cls):
38
+ # Replace with the model name needed for testing; if not required, reuse DEFAULT_SMALL_MODEL_NAME_FOR_TEST
39
+ cls.model = DEFAULT_SMALL_MODEL_NAME_FOR_TEST
40
+ cls.base_url = DEFAULT_URL_FOR_TEST
41
+ cls.api_key = "sk-123456"
42
+
43
+ # Start the local OpenAI Server. If necessary, you can add other parameters such as --enable-tools.
44
+ cls.process = popen_launch_server(
45
+ cls.model,
46
+ cls.base_url,
47
+ timeout=DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH,
48
+ api_key=cls.api_key,
49
+ other_args=[
50
+ # If your server needs extra parameters to test function calling, please add them here.
51
+ "--tool-call-parser",
52
+ "llama3",
53
+ ],
54
+ )
55
+ cls.base_url += "/v1"
56
+ cls.tokenizer = get_tokenizer(cls.model)
57
+
58
+ @classmethod
59
+ def tearDownClass(cls):
60
+ kill_process_tree(cls.process.pid)
61
+
62
+ def test_function_calling_format(self):
63
+ """
64
+ Test: Whether the function call format returned by the AI is correct.
65
+ When returning a tool call, message.content should be None, and tool_calls should be a list.
66
+ """
67
+ client = openai.Client(api_key=self.api_key, base_url=self.base_url)
68
+
69
+ tools = [
70
+ {
71
+ "type": "function",
72
+ "function": {
73
+ "name": "add",
74
+ "description": "Compute the sum of two numbers",
75
+ "parameters": {
76
+ "type": "object",
77
+ "properties": {
78
+ "a": {
79
+ "type": "integer",
80
+ "description": "A number",
81
+ },
82
+ "b": {
83
+ "type": "integer",
84
+ "description": "A number",
85
+ },
86
+ },
87
+ "required": ["a", "b"],
88
+ },
89
+ },
90
+ }
91
+ ]
92
+
93
+ messages = [
94
+ {"role": "system", "content": self.SYSTEM_MESSAGE},
95
+ {"role": "user", "content": "Compute (3+5)"},
96
+ ]
97
+ response = client.chat.completions.create(
98
+ model=self.model,
99
+ max_tokens=2048,
100
+ messages=messages,
101
+ temperature=0.8,
102
+ top_p=0.8,
103
+ stream=False,
104
+ tools=tools,
105
+ )
106
+
107
+ tool_calls = response.choices[0].message.tool_calls
108
+
109
+ assert (
110
+ isinstance(tool_calls, list) and len(tool_calls) > 0
111
+ ), "tool_calls should be a non-empty list"
112
+
113
+ function_name = tool_calls[0].function.name
114
+ assert function_name == "add", "Function name should be 'add'"
115
+
116
+ # This unit test is too difficult for default model. Mark it as optional unit tests so it won't trigger unless specified.
117
+ def _test_function_calling_multiturn(self):
118
+ """
119
+ Test: Whether the function call format returned by the AI is correct.
120
+ When returning a tool call, message.content should be None, and tool_calls should be a list.
121
+ """
122
+ client = openai.Client(api_key=self.api_key, base_url=self.base_url)
123
+
124
+ tools = [
125
+ {
126
+ "type": "function",
127
+ "function": {
128
+ "name": "add",
129
+ "description": "Compute the sum of two numbers",
130
+ "parameters": {
131
+ "type": "object",
132
+ "properties": {
133
+ "a": {
134
+ "type": "integer",
135
+ "description": "A number",
136
+ },
137
+ "b": {
138
+ "type": "integer",
139
+ "description": "A number",
140
+ },
141
+ },
142
+ "required": ["a", "b"],
143
+ },
144
+ },
145
+ }
146
+ ]
147
+
148
+ messages = [{"role": "user", "content": "Compute (3+5)"}]
149
+
150
+ response = client.chat.completions.create(
151
+ model=self.model,
152
+ max_tokens=2048,
153
+ messages=messages,
154
+ temperature=0.8,
155
+ top_p=0.8,
156
+ stream=False,
157
+ tools=tools,
158
+ )
159
+
160
+ tool_call = response.choices[0].message.tool_calls[0]
161
+ function_name = tool_call.function.name
162
+ assert function_name == "add", "Function name should be 'add'"
163
+ function_arguments = tool_call.function.arguments
164
+ function_arguments = json.loads(tool_call.function.arguments)
165
+ assert function_arguments in [
166
+ {"a": 3, "b": 5},
167
+ {"a": "3", "b": "5"},
168
+ ], f"Unexpected function arguments: {function_arguments}"
169
+
170
+ messages.append(response.choices[0].message)
171
+ messages.append(
172
+ {
173
+ "role": "tool",
174
+ "tool_call_id": tool_call.id,
175
+ "content": "8",
176
+ "name": function_name,
177
+ }
178
+ )
179
+
180
+ final_response = client.chat.completions.create(
181
+ model=self.model,
182
+ max_tokens=2048,
183
+ messages=messages,
184
+ temperature=0.8,
185
+ top_p=0.8,
186
+ stream=False,
187
+ tools=tools,
188
+ )
189
+
190
+ assert (
191
+ "8" in final_response.choices[0].message.content
192
+ ), "tool_call response should have the sum 8 in the content"
193
+
194
+ def test_function_calling_streaming_simple(self):
195
+ """
196
+ Test: Whether the function name can be correctly recognized in streaming mode.
197
+ - Expect a function call to be found, and the function name to be correct.
198
+ - Verify that streaming mode returns at least multiple chunks.
199
+ """
200
+ client = openai.Client(api_key=self.api_key, base_url=self.base_url)
201
+
202
+ tools = [
203
+ {
204
+ "type": "function",
205
+ "function": {
206
+ "name": "get_current_weather",
207
+ "description": "Get the current weather in a given location",
208
+ "parameters": {
209
+ "type": "object",
210
+ "properties": {
211
+ "city": {
212
+ "type": "string",
213
+ "description": "The city to find the weather for",
214
+ },
215
+ "unit": {
216
+ "type": "string",
217
+ "description": "Weather unit (celsius or fahrenheit)",
218
+ "enum": ["celsius", "fahrenheit"],
219
+ },
220
+ },
221
+ "required": ["city", "unit"],
222
+ },
223
+ },
224
+ }
225
+ ]
226
+
227
+ messages = [
228
+ {"role": "system", "content": self.SYSTEM_MESSAGE},
229
+ {
230
+ "role": "user",
231
+ "content": "What is the temperature in Paris in celsius??",
232
+ },
233
+ ]
234
+
235
+ response_stream = client.chat.completions.create(
236
+ model=self.model,
237
+ max_tokens=2048,
238
+ messages=messages,
239
+ temperature=0.8,
240
+ top_p=0.8,
241
+ stream=True,
242
+ tools=tools,
243
+ )
244
+
245
+ chunks = list(response_stream)
246
+ self.assertTrue(len(chunks) > 0, "Streaming should return at least one chunk")
247
+
248
+ found_function_name = False
249
+ for chunk in chunks:
250
+ choice = chunk.choices[0]
251
+ # Check whether the current chunk contains tool_calls
252
+ if choice.delta.tool_calls:
253
+ tool_call = choice.delta.tool_calls[0]
254
+ if tool_call.function.name:
255
+ self.assertEqual(
256
+ tool_call.function.name,
257
+ "get_current_weather",
258
+ "Function name should be 'get_current_weather'",
259
+ )
260
+ found_function_name = True
261
+ break
262
+
263
+ self.assertTrue(
264
+ found_function_name,
265
+ "Target function name 'get_current_weather' was not found in the streaming chunks",
266
+ )
267
+
268
+ finish_reason = chunks[-1].choices[0].finish_reason
269
+ self.assertEqual(
270
+ finish_reason,
271
+ "tool_calls",
272
+ "Final response of function calling should have finish_reason 'tool_calls'",
273
+ )
274
+
275
+ def test_function_calling_streaming_args_parsing(self):
276
+ """
277
+ Test: Whether the function call arguments returned in streaming mode can be correctly concatenated into valid JSON.
278
+ - The user request requires multiple parameters.
279
+ - AI may return the arguments in chunks that need to be concatenated.
280
+ """
281
+ client = openai.Client(api_key=self.api_key, base_url=self.base_url)
282
+
283
+ tools = [
284
+ {
285
+ "type": "function",
286
+ "function": {
287
+ "name": "add",
288
+ "description": "Compute the sum of two integers",
289
+ "parameters": {
290
+ "type": "object",
291
+ "properties": {
292
+ "a": {
293
+ "type": "integer",
294
+ "description": "First integer",
295
+ },
296
+ "b": {
297
+ "type": "integer",
298
+ "description": "Second integer",
299
+ },
300
+ },
301
+ "required": ["a", "b"],
302
+ },
303
+ "strict": True, # Llama-3.2-1B is flaky in tool call. It won't always respond with parameters unless we set strict.
304
+ },
305
+ }
306
+ ]
307
+
308
+ messages = [
309
+ {"role": "system", "content": self.SYSTEM_MESSAGE},
310
+ {"role": "user", "content": "Please sum 5 and 7, just call the function."},
311
+ ]
312
+
313
+ response_stream = client.chat.completions.create(
314
+ model=self.model,
315
+ max_tokens=2048,
316
+ messages=messages,
317
+ temperature=0.9,
318
+ top_p=0.9,
319
+ stream=True,
320
+ tools=tools,
321
+ )
322
+
323
+ argument_fragments = []
324
+ chunks = list(response_stream)
325
+ function_name = None
326
+ for chunk in chunks:
327
+ choice = chunk.choices[0]
328
+ if choice.delta.tool_calls:
329
+ tool_call = choice.delta.tool_calls[0]
330
+ # Record the function name on first occurrence
331
+ function_name = tool_call.function.name or function_name
332
+ # In case of multiple chunks, JSON fragments may need to be concatenated
333
+ if tool_call.function.arguments is not None:
334
+ argument_fragments.append(tool_call.function.arguments)
335
+
336
+ self.assertEqual(function_name, "add", "Function name should be 'add'")
337
+ joined_args = "".join(argument_fragments)
338
+ self.assertTrue(
339
+ len(joined_args) > 0,
340
+ "No parameter fragments were returned in the function call",
341
+ )
342
+
343
+ finish_reason = chunks[-1].choices[0].finish_reason
344
+ self.assertEqual(
345
+ finish_reason,
346
+ "tool_calls",
347
+ "Final response of function calling should have finish_reason 'tool_calls'",
348
+ )
349
+
350
+ # Check whether the concatenated JSON is valid
351
+ try:
352
+ args_obj = json.loads(joined_args)
353
+ except json.JSONDecodeError:
354
+ self.fail(
355
+ "The concatenated tool call arguments are not valid JSON, parsing failed"
356
+ )
357
+
358
+ self.assertIn("a", args_obj, "Missing parameter 'a'")
359
+ self.assertIn("b", args_obj, "Missing parameter 'b'")
360
+ self.assertEqual(str(args_obj["a"]), "5", "Parameter a should be 5")
361
+ self.assertEqual(str(args_obj["b"]), "7", "Parameter b should be 7")
362
+
363
+ def test_function_call_strict(self):
364
+ """
365
+ Test: Whether the strict mode of function calling works as expected.
366
+ - When strict mode is enabled, the AI should not return a function call if the function name is not recognized.
367
+ """
368
+ client = openai.Client(api_key=self.api_key, base_url=self.base_url)
369
+
370
+ tools = [
371
+ {
372
+ "type": "function",
373
+ "function": {
374
+ "name": "sub",
375
+ "description": "Compute the difference of two integers",
376
+ "parameters": {
377
+ "type": "object",
378
+ "properties": {
379
+ "int_a": {
380
+ "type": "integer",
381
+ "description": "First integer",
382
+ },
383
+ "int_b": {
384
+ "type": "integer",
385
+ "description": "Second integer",
386
+ },
387
+ },
388
+ "required": ["int_a", "int_b"],
389
+ },
390
+ "strict": True,
391
+ },
392
+ }
393
+ ]
394
+
395
+ messages = [
396
+ {"role": "user", "content": "Please compute 5 - 7, using your tool."}
397
+ ]
398
+ response = client.chat.completions.create(
399
+ model=self.model,
400
+ max_tokens=2048,
401
+ messages=messages,
402
+ temperature=0.8,
403
+ top_p=0.8,
404
+ stream=False,
405
+ tools=tools,
406
+ )
407
+
408
+ tool_calls = response.choices[0].message.tool_calls
409
+ function_name = tool_calls[0].function.name
410
+ arguments = tool_calls[0].function.arguments
411
+ args_obj = json.loads(arguments)
412
+
413
+ self.assertEqual(function_name, "sub", "Function name should be 'sub'")
414
+ self.assertEqual(str(args_obj["int_a"]), "5", "Parameter int_a should be 5")
415
+ self.assertEqual(str(args_obj["int_b"]), "7", "Parameter int_b should be 7")
416
+
417
+ def test_function_call_required(self):
418
+ """
419
+ Test: Whether tool_choice: "required" works as expected.
420
+ - When tool_choice == "required", the model MUST return one or more tool_calls.
421
+ - The model may choose ANY of the provided tools; we only verify that
422
+ a tool call exists and the selected name is among the candidates.
423
+ """
424
+ client = openai.Client(api_key=self.api_key, base_url=self.base_url)
425
+
426
+ tools = [
427
+ {
428
+ "type": "function",
429
+ "function": {
430
+ "name": "sub",
431
+ "description": "Compute the difference of two integers",
432
+ "parameters": {
433
+ "type": "object",
434
+ "properties": {
435
+ "int_a": {
436
+ "type": "integer",
437
+ "description": "First integer",
438
+ },
439
+ "int_b": {
440
+ "type": "integer",
441
+ "description": "Second integer",
442
+ },
443
+ },
444
+ "required": ["int_a", "int_b"],
445
+ },
446
+ "strict": True,
447
+ },
448
+ },
449
+ {
450
+ "type": "function",
451
+ "function": {
452
+ "name": "get_weather",
453
+ "description": "use this to get latest weather information for a city given its name",
454
+ "parameters": {
455
+ "type": "object",
456
+ "properties": {
457
+ "city": {
458
+ "type": "string",
459
+ "description": "name of the city to get weather for",
460
+ }
461
+ },
462
+ "required": ["city"],
463
+ },
464
+ "strict": True,
465
+ },
466
+ },
467
+ ]
468
+
469
+ valid_tool_names = {t["function"]["name"] for t in tools}
470
+
471
+ messages = [{"role": "user", "content": "Tell me about Paris"}]
472
+ response = client.chat.completions.create(
473
+ model=self.model,
474
+ max_tokens=2048,
475
+ messages=messages,
476
+ temperature=0,
477
+ stream=False,
478
+ tools=tools,
479
+ tool_choice="required",
480
+ )
481
+
482
+ tool_calls = response.choices[0].message.tool_calls
483
+ self.assertIsNotNone(
484
+ tool_calls, "tool_choice='required' must produce tool_calls"
485
+ )
486
+ self.assertGreater(len(tool_calls), 0, "tool_calls list should be non-empty")
487
+
488
+ function_name = tool_calls[0].function.name
489
+ self.assertIn(
490
+ function_name,
491
+ valid_tool_names,
492
+ f"Function name '{function_name}' is not among the provided tools: {valid_tool_names}",
493
+ )
494
+
495
+ # Verify the arguments are parseable JSON
496
+ arguments = tool_calls[0].function.arguments
497
+ args_obj = json.loads(arguments)
498
+ self.assertIsInstance(
499
+ args_obj, dict, "Function arguments should be a JSON object"
500
+ )
501
+
502
+ def test_function_call_specific(self):
503
+ """
504
+ Test: Whether tool_choice: ToolChoice works as expected
505
+ - When tool_choice is a specific ToolChoice, the model should return one or more tool_calls.
506
+ """
507
+ client = openai.Client(api_key=self.api_key, base_url=self.base_url)
508
+
509
+ tools = [
510
+ {
511
+ "type": "function",
512
+ "function": {
513
+ "name": "sub",
514
+ "description": "Compute the difference of two integers",
515
+ "parameters": {
516
+ "type": "object",
517
+ "properties": {
518
+ "int_a": {
519
+ "type": "integer",
520
+ "description": "First integer",
521
+ },
522
+ "int_b": {
523
+ "type": "integer",
524
+ "description": "Second integer",
525
+ },
526
+ },
527
+ "required": ["int_a", "int_b"],
528
+ },
529
+ "strict": True,
530
+ },
531
+ },
532
+ {
533
+ "type": "function",
534
+ "function": {
535
+ "name": "get_weather",
536
+ "description": "use this to get latest weather information for a city given its name",
537
+ "parameters": {
538
+ "type": "object",
539
+ "properties": {
540
+ "city": {
541
+ "type": "string",
542
+ "description": "name of the city to get weather for",
543
+ }
544
+ },
545
+ "required": ["city"],
546
+ },
547
+ "strict": True,
548
+ },
549
+ },
550
+ ]
551
+
552
+ messages = [{"role": "user", "content": "What is the capital of France?"}]
553
+ response = client.chat.completions.create(
554
+ model=self.model,
555
+ max_tokens=2048,
556
+ messages=messages,
557
+ temperature=0.8,
558
+ top_p=0.8,
559
+ stream=False,
560
+ tools=tools,
561
+ tool_choice={"type": "function", "function": {"name": "get_weather"}},
562
+ )
563
+
564
+ tool_calls = response.choices[0].message.tool_calls
565
+ self.assertIsNotNone(tool_calls, "No tool_calls in the response")
566
+ function_name = tool_calls[0].function.name
567
+ arguments = tool_calls[0].function.arguments
568
+ args_obj = json.loads(arguments)
569
+
570
+ self.assertEqual(
571
+ function_name, "get_weather", "Function name should be 'get_weather'"
572
+ )
573
+ self.assertIn("city", args_obj, "Function arguments should have 'city'")
574
+
575
+ def test_streaming_multiple_choices_finish_reason(self):
576
+ """
577
+ Test: Verify that each choice gets its own finish_reason chunk in streaming mode with n > 1.
578
+ This tests the fix for the bug where only the last index got a finish_reason chunk.
579
+ """
580
+ client = openai.Client(api_key=self.api_key, base_url=self.base_url)
581
+
582
+ tools = [
583
+ {
584
+ "type": "function",
585
+ "function": {
586
+ "name": "get_current_weather",
587
+ "description": "Get the current weather in a given location",
588
+ "parameters": {
589
+ "type": "object",
590
+ "properties": {
591
+ "location": {
592
+ "type": "string",
593
+ "description": "The city and state, e.g. San Francisco, CA",
594
+ },
595
+ "unit": {
596
+ "type": "string",
597
+ "enum": ["celsius", "fahrenheit"],
598
+ },
599
+ },
600
+ "required": ["location"],
601
+ },
602
+ },
603
+ }
604
+ ]
605
+
606
+ messages = [
607
+ {"role": "user", "content": "What is the weather like in Los Angeles?"}
608
+ ]
609
+
610
+ # Request with n=2 to get multiple choices
611
+ response_stream = client.chat.completions.create(
612
+ model=self.model,
613
+ messages=messages,
614
+ max_tokens=2048,
615
+ temperature=0.8,
616
+ stream=True,
617
+ tools=tools,
618
+ tool_choice="required", # Force tool calls
619
+ n=2, # Multiple choices
620
+ )
621
+
622
+ chunks = list(response_stream)
623
+
624
+ # Track finish_reason chunks for each index
625
+ finish_reason_chunks = {}
626
+ for chunk in chunks:
627
+ if chunk.choices:
628
+ for choice in chunk.choices:
629
+ if choice.finish_reason is not None:
630
+ index = choice.index
631
+ if index not in finish_reason_chunks:
632
+ finish_reason_chunks[index] = []
633
+ finish_reason_chunks[index].append(choice.finish_reason)
634
+
635
+ # Verify we got finish_reason chunks for both indices
636
+ self.assertEqual(
637
+ len(finish_reason_chunks),
638
+ 2,
639
+ f"Expected finish_reason chunks for 2 indices, got {len(finish_reason_chunks)}",
640
+ )
641
+
642
+ # Verify both index 0 and 1 have finish_reason
643
+ self.assertIn(
644
+ 0, finish_reason_chunks, "Missing finish_reason chunk for index 0"
645
+ )
646
+ self.assertIn(
647
+ 1, finish_reason_chunks, "Missing finish_reason chunk for index 1"
648
+ )
649
+
650
+ # Verify the finish_reason is "tool_calls" since we forced tool calls
651
+ for index, reasons in finish_reason_chunks.items():
652
+ self.assertEqual(
653
+ reasons[-1], # Last finish_reason for this index
654
+ "tool_calls",
655
+ f"Expected finish_reason 'tool_calls' for index {index}, got {reasons[-1]}",
656
+ )
657
+
658
+ def test_function_calling_streaming_no_tool_call(self):
659
+ """
660
+ Test: Whether the finish_reason is stop in streaming mode when no tool call is given.
661
+ - Expect no function call to be found.
662
+ - Verify that finish_reason is stop
663
+ """
664
+ client = openai.Client(api_key=self.api_key, base_url=self.base_url)
665
+
666
+ tools = [
667
+ {
668
+ "type": "function",
669
+ "function": {
670
+ "name": "get_current_weather",
671
+ "description": "Get the current weather in a given location",
672
+ "parameters": {
673
+ "type": "object",
674
+ "properties": {
675
+ "city": {
676
+ "type": "string",
677
+ "description": "The city to find the weather for",
678
+ },
679
+ "unit": {
680
+ "type": "string",
681
+ "description": "Weather unit (celsius or fahrenheit)",
682
+ "enum": ["celsius", "fahrenheit"],
683
+ },
684
+ },
685
+ "required": ["city", "unit"],
686
+ },
687
+ },
688
+ }
689
+ ]
690
+
691
+ messages = [{"role": "user", "content": "Who are you?"}]
692
+
693
+ response_stream = client.chat.completions.create(
694
+ model=self.model,
695
+ max_tokens=2048,
696
+ messages=messages,
697
+ temperature=0.8,
698
+ top_p=0.8,
699
+ stream=True,
700
+ tools=tools,
701
+ tool_choice="none",
702
+ )
703
+
704
+ chunks = list(response_stream)
705
+ self.assertTrue(len(chunks) > 0, "Streaming should return at least one chunk")
706
+
707
+ found_tool_call = False
708
+ for chunk in chunks:
709
+ choice = chunk.choices[0]
710
+ # Check whether the current chunk contains tool_calls
711
+ found_tool_call = choice.delta.tool_calls is not None
712
+
713
+ self.assertFalse(
714
+ found_tool_call,
715
+ "Shouldn't have any tool_call in the streaming chunks",
716
+ )
717
+
718
+ finish_reason = chunks[-1].choices[0].finish_reason
719
+ self.assertEqual(
720
+ finish_reason,
721
+ "stop",
722
+ "Final response of no function calling should have finish_reason 'stop'",
723
+ )
724
+
725
+ def test_streaming_multiple_choices_without_tools(self):
726
+ """
727
+ Test: Verify that each choice gets its own finish_reason chunk without tool calls.
728
+ This tests the fix for regular content streaming with multiple choices.
729
+ """
730
+ client = openai.Client(api_key=self.api_key, base_url=self.base_url)
731
+
732
+ messages = [{"role": "user", "content": "Say hello in one word."}]
733
+
734
+ # Request with n=2 to get multiple choices, no tools
735
+ response_stream = client.chat.completions.create(
736
+ model=self.model,
737
+ messages=messages,
738
+ temperature=0.8,
739
+ stream=True,
740
+ max_tokens=10, # Keep it short
741
+ n=2, # Multiple choices
742
+ )
743
+
744
+ chunks = list(response_stream)
745
+
746
+ # Track finish_reason chunks for each index
747
+ finish_reason_chunks = {}
748
+ for chunk in chunks:
749
+ if chunk.choices:
750
+ for choice in chunk.choices:
751
+ if choice.finish_reason is not None:
752
+ index = choice.index
753
+ if index not in finish_reason_chunks:
754
+ finish_reason_chunks[index] = []
755
+ finish_reason_chunks[index].append(choice.finish_reason)
756
+
757
+ # Verify we got finish_reason chunks for both indices
758
+ self.assertEqual(
759
+ len(finish_reason_chunks),
760
+ 2,
761
+ f"Expected finish_reason chunks for 2 indices, got {len(finish_reason_chunks)}",
762
+ )
763
+
764
+ # Verify both index 0 and 1 have finish_reason
765
+ self.assertIn(
766
+ 0, finish_reason_chunks, "Missing finish_reason chunk for index 0"
767
+ )
768
+ self.assertIn(
769
+ 1, finish_reason_chunks, "Missing finish_reason chunk for index 1"
770
+ )
771
+
772
+ # Verify the finish_reason is "stop" (regular completion)
773
+ for index, reasons in finish_reason_chunks.items():
774
+ self.assertIn(
775
+ reasons[-1],
776
+ ["stop", "length"], # Could be either depending on how model responds
777
+ f"Expected finish_reason 'stop' or 'length' for index {index}, got {reasons[-1]}",
778
+ )
779
+
780
+
781
+ class TestOpenAIPythonicFunctionCalling(CustomTestCase):
782
+ PYTHONIC_TOOLS = [
783
+ {
784
+ "type": "function",
785
+ "function": {
786
+ "name": "get_weather",
787
+ "description": "Get the current weather for a given location.",
788
+ "parameters": {
789
+ "type": "object",
790
+ "properties": {
791
+ "location": {
792
+ "type": "string",
793
+ "description": "The name of the city or location.",
794
+ }
795
+ },
796
+ "required": ["location"],
797
+ },
798
+ },
799
+ },
800
+ {
801
+ "type": "function",
802
+ "function": {
803
+ "name": "get_tourist_attractions",
804
+ "description": "Get a list of top tourist attractions for a given city.",
805
+ "parameters": {
806
+ "type": "object",
807
+ "properties": {
808
+ "city": {
809
+ "type": "string",
810
+ "description": "The name of the city to find attractions for.",
811
+ }
812
+ },
813
+ "required": ["city"],
814
+ },
815
+ },
816
+ },
817
+ ]
818
+
819
+ PYTHONIC_MESSAGES = [
820
+ {
821
+ "role": "system",
822
+ "content": (
823
+ "You are a travel assistant. "
824
+ "When asked to call functions, ALWAYS respond ONLY with a python list of function calls, "
825
+ "using this format: [func_name1(param1=value1, param2=value2), func_name2(param=value)]. "
826
+ "Do NOT use JSON, do NOT use variables, do NOT use any other format. "
827
+ "Here is an example:\n"
828
+ '[get_weather(location="Paris"), get_tourist_attractions(city="Paris")]'
829
+ ),
830
+ },
831
+ {
832
+ "role": "user",
833
+ "content": (
834
+ "I'm planning a trip to Tokyo next week. What's the weather like and what are some top tourist attractions? "
835
+ "Propose parallel tool calls at once, using the python list of function calls format as shown above."
836
+ ),
837
+ },
838
+ ]
839
+
840
+ @classmethod
841
+ def setUpClass(cls):
842
+ cls.model = DEFAULT_SMALL_MODEL_NAME_FOR_TEST
843
+ cls.base_url = DEFAULT_URL_FOR_TEST
844
+ cls.api_key = "sk-123456"
845
+ cls.process = popen_launch_server(
846
+ cls.model,
847
+ cls.base_url,
848
+ timeout=DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH,
849
+ api_key=cls.api_key,
850
+ other_args=[
851
+ "--tool-call-parser",
852
+ "pythonic",
853
+ ],
854
+ )
855
+ cls.base_url += "/v1"
856
+ cls.tokenizer = get_tokenizer(cls.model)
857
+
858
+ @classmethod
859
+ def tearDownClass(cls):
860
+ kill_process_tree(cls.process.pid)
861
+
862
+ def test_pythonic_tool_call_prompt(self):
863
+ """
864
+ Test: Explicit prompt for pythonic tool call format without chat template.
865
+ """
866
+ client = openai.Client(api_key=self.api_key, base_url=self.base_url)
867
+ response = client.chat.completions.create(
868
+ model=self.model,
869
+ messages=self.PYTHONIC_MESSAGES,
870
+ tools=self.PYTHONIC_TOOLS,
871
+ temperature=0.1,
872
+ stream=False,
873
+ )
874
+ tool_calls = response.choices[0].message.tool_calls
875
+ self.assertIsInstance(tool_calls, list, "No tool_calls found")
876
+ self.assertGreaterEqual(len(tool_calls), 1)
877
+ names = [tc.function.name for tc in tool_calls]
878
+ self.assertTrue(
879
+ "get_weather" in names or "get_tourist_attractions" in names,
880
+ f"Function name '{names}' should container either 'get_weather' or 'get_tourist_attractions'",
881
+ )
882
+
883
+ def test_pythonic_tool_call_streaming(self):
884
+ """
885
+ Test: Streaming pythonic tool call format; assert tool_call index is present.
886
+ """
887
+ client = openai.Client(api_key=self.api_key, base_url=self.base_url)
888
+ response_stream = client.chat.completions.create(
889
+ model=self.model,
890
+ messages=self.PYTHONIC_MESSAGES,
891
+ tools=self.PYTHONIC_TOOLS,
892
+ temperature=0.1,
893
+ stream=True,
894
+ )
895
+ found_tool_calls = False
896
+ found_index = False
897
+ found_names = set()
898
+ for chunk in response_stream:
899
+ choice = chunk.choices[0]
900
+ if getattr(choice.delta, "tool_calls", None):
901
+ found_tool_calls = True
902
+ tool_call = choice.delta.tool_calls[0]
903
+ if hasattr(tool_call, "index") or (
904
+ isinstance(tool_call, dict) and "index" in tool_call
905
+ ):
906
+ found_index = True
907
+ found_names.add(str(tool_call.function.name))
908
+
909
+ self.assertTrue(found_tool_calls, "No tool_calls found in streaming response")
910
+ self.assertTrue(found_index, "No index field found in any streamed tool_call")
911
+ self.assertTrue(
912
+ "get_weather" in found_names or "get_tourist_attractions" in found_names,
913
+ f"Function name '{found_names}' should container either 'get_weather' or 'get_tourist_attractions'",
914
+ )
915
+
916
+
917
+ # Skip for ci test
918
+ # class TestGLM45ServerFunctionCalling(TestOpenAIServerFunctionCalling):
919
+ # @classmethod
920
+ # def setUpClass(cls):
921
+ # # Replace with the model name needed for testing; if not required, reuse DEFAULT_SMALL_MODEL_NAME_FOR_TEST
922
+ # cls.model = "THUDM/GLM-4.5"
923
+ # cls.base_url = DEFAULT_URL_FOR_TEST
924
+ # cls.api_key = "sk-123456"
925
+
926
+ # # Start the local OpenAI Server. If necessary, you can add other parameters such as --enable-tools.
927
+ # cls.process = popen_launch_server(
928
+ # cls.model,
929
+ # cls.base_url,
930
+ # timeout=DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH,
931
+ # api_key=cls.api_key,
932
+ # other_args=[
933
+ # # If your server needs extra parameters to test function calling, please add them here.
934
+ # "--tool-call-parser",
935
+ # "glm45",
936
+ # "--reasoning-parser",
937
+ # "glm45",
938
+ # "--tp-size",
939
+ # "8"
940
+ # ],
941
+ # )
942
+ # cls.base_url += "/v1"
943
+ # cls.tokenizer = get_tokenizer(cls.model)
944
+
945
+ # # This test is too difficult for GLM4-moe. Skip it from the UT
946
+ # def test_function_call_required(self):
947
+ # pass
948
+
949
+ # def test_function_calling_multiturn(self):
950
+ # self._test_function_calling_multiturn()
951
+
952
+
953
+ if __name__ == "__main__":
954
+ unittest.main()
asian_ai/performance/SGLang/test/registered/openai_server/validation/test_large_max_new_tokens.py ADDED
@@ -0,0 +1,107 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ python3 -m unittest openai_server.validation.test_large_max_new_tokens.TestLargeMaxNewTokens.test_chat_completion
3
+ """
4
+
5
+ import os
6
+ import time
7
+ import unittest
8
+ from concurrent.futures import ThreadPoolExecutor
9
+
10
+ import openai
11
+
12
+ from sglang.srt.utils import kill_process_tree
13
+ from sglang.srt.utils.hf_transformers_utils import get_tokenizer
14
+ from sglang.test.ci.ci_register import register_amd_ci, register_cuda_ci
15
+ from sglang.test.test_utils import (
16
+ DEFAULT_SMALL_MODEL_NAME_FOR_TEST,
17
+ DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH,
18
+ DEFAULT_URL_FOR_TEST,
19
+ STDERR_FILENAME,
20
+ STDOUT_FILENAME,
21
+ CustomTestCase,
22
+ popen_launch_server,
23
+ )
24
+
25
+ register_cuda_ci(est_time=58, stage="base-b", runner_config="1-gpu-large")
26
+ register_amd_ci(est_time=41, suite="stage-b-test-1-gpu-small-amd")
27
+
28
+
29
+ class TestLargeMaxNewTokens(CustomTestCase):
30
+ @classmethod
31
+ def setUpClass(cls):
32
+ cls.model = DEFAULT_SMALL_MODEL_NAME_FOR_TEST
33
+ cls.base_url = DEFAULT_URL_FOR_TEST
34
+ cls.api_key = "sk-123456"
35
+
36
+ cls.stdout = open(STDOUT_FILENAME, "w")
37
+ cls.stderr = open(STDERR_FILENAME, "w")
38
+
39
+ cls.process = popen_launch_server(
40
+ cls.model,
41
+ cls.base_url,
42
+ timeout=DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH,
43
+ api_key=cls.api_key,
44
+ other_args=(
45
+ "--max-total-token",
46
+ "1536",
47
+ "--context-len",
48
+ "8192",
49
+ "--decode-log-interval",
50
+ "2",
51
+ ),
52
+ env={"SGLANG_CLIP_MAX_NEW_TOKENS_ESTIMATION": "256", **os.environ},
53
+ return_stdout_stderr=(cls.stdout, cls.stderr),
54
+ )
55
+ cls.base_url += "/v1"
56
+ cls.tokenizer = get_tokenizer(DEFAULT_SMALL_MODEL_NAME_FOR_TEST)
57
+
58
+ @classmethod
59
+ def tearDownClass(cls):
60
+ kill_process_tree(cls.process.pid)
61
+ cls.stdout.close()
62
+ cls.stderr.close()
63
+ os.remove(STDOUT_FILENAME)
64
+ os.remove(STDERR_FILENAME)
65
+
66
+ def run_chat_completion(self):
67
+ client = openai.Client(api_key=self.api_key, base_url=self.base_url)
68
+ response = client.chat.completions.create(
69
+ model=self.model,
70
+ messages=[
71
+ {"role": "system", "content": "You are a helpful AI assistant"},
72
+ {
73
+ "role": "user",
74
+ "content": "Please repeat the world 'hello' for 10000 times.",
75
+ },
76
+ ],
77
+ temperature=0,
78
+ )
79
+ return response
80
+
81
+ def test_chat_completion(self):
82
+ num_requests = 4
83
+
84
+ futures = []
85
+ with ThreadPoolExecutor(num_requests) as executor:
86
+ # Send multiple requests
87
+ for i in range(num_requests):
88
+ futures.append(executor.submit(self.run_chat_completion))
89
+
90
+ # Ensure that they are running concurrently
91
+ pt = 0
92
+ while pt >= 0:
93
+ time.sleep(5)
94
+ lines = open(STDERR_FILENAME).readlines()
95
+ for line in lines[pt:]:
96
+ print(line, end="", flush=True)
97
+ if f"#running-req: {num_requests}" in line:
98
+ all_requests_running = True
99
+ pt = -1
100
+ break
101
+ pt += 1
102
+
103
+ assert all_requests_running
104
+
105
+
106
+ if __name__ == "__main__":
107
+ unittest.main()
asian_ai/performance/SGLang/test/registered/openai_server/validation/test_matched_stop.py ADDED
@@ -0,0 +1,35 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import unittest
2
+
3
+ from sglang.srt.utils import kill_process_tree
4
+ from sglang.test.ci.ci_register import register_amd_ci, register_cuda_ci
5
+ from sglang.test.kits.matched_stop_kit import MatchedStopMixin
6
+ from sglang.test.test_utils import (
7
+ DEFAULT_MODEL_NAME_FOR_TEST,
8
+ DEFAULT_URL_FOR_TEST,
9
+ CustomTestCase,
10
+ popen_launch_server,
11
+ )
12
+
13
+ register_cuda_ci(est_time=52, stage="base-b", runner_config="1-gpu-small")
14
+ register_amd_ci(est_time=60, suite="stage-b-test-1-gpu-small-amd")
15
+
16
+
17
+ class TestMatchedStop(CustomTestCase, MatchedStopMixin):
18
+ @classmethod
19
+ def setUpClass(cls):
20
+ cls.model = DEFAULT_MODEL_NAME_FOR_TEST
21
+ cls.base_url = DEFAULT_URL_FOR_TEST
22
+ cls.process = popen_launch_server(
23
+ cls.model,
24
+ cls.base_url,
25
+ timeout=300,
26
+ other_args=["--max-running-requests", "10"],
27
+ )
28
+
29
+ @classmethod
30
+ def tearDownClass(cls):
31
+ kill_process_tree(cls.process.pid)
32
+
33
+
34
+ if __name__ == "__main__":
35
+ unittest.main()
asian_ai/performance/SGLang/test/registered/openai_server/validation/test_openai_server_ignore_eos.py ADDED
@@ -0,0 +1,94 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import openai
2
+
3
+ from sglang.srt.utils import kill_process_tree
4
+ from sglang.srt.utils.hf_transformers_utils import get_tokenizer
5
+ from sglang.test.ci.ci_register import register_amd_ci, register_cuda_ci
6
+ from sglang.test.test_utils import (
7
+ DEFAULT_SMALL_MODEL_NAME_FOR_TEST,
8
+ DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH,
9
+ DEFAULT_URL_FOR_TEST,
10
+ CustomTestCase,
11
+ popen_launch_server,
12
+ )
13
+
14
+ register_cuda_ci(est_time=44, stage="base-b", runner_config="1-gpu-small")
15
+ register_amd_ci(est_time=47, suite="stage-b-test-1-gpu-small-amd")
16
+
17
+
18
+ class TestOpenAIServerIgnoreEOS(CustomTestCase):
19
+ @classmethod
20
+ def setUpClass(cls):
21
+ cls.model = DEFAULT_SMALL_MODEL_NAME_FOR_TEST
22
+ cls.base_url = DEFAULT_URL_FOR_TEST
23
+ cls.api_key = "sk-123456"
24
+ cls.process = popen_launch_server(
25
+ cls.model,
26
+ cls.base_url,
27
+ timeout=DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH,
28
+ api_key=cls.api_key,
29
+ )
30
+ cls.base_url += "/v1"
31
+ cls.tokenizer = get_tokenizer(DEFAULT_SMALL_MODEL_NAME_FOR_TEST)
32
+
33
+ @classmethod
34
+ def tearDownClass(cls):
35
+ kill_process_tree(cls.process.pid)
36
+
37
+ def test_ignore_eos(self):
38
+ """
39
+ Test that ignore_eos=True allows generation to continue beyond EOS token
40
+ and reach the max_tokens limit.
41
+ """
42
+ client = openai.Client(api_key=self.api_key, base_url=self.base_url)
43
+
44
+ max_tokens = 200
45
+
46
+ response_default = client.chat.completions.create(
47
+ model=self.model,
48
+ messages=[
49
+ {"role": "system", "content": "You are a helpful assistant."},
50
+ {"role": "user", "content": "Count from 1 to 20."},
51
+ ],
52
+ temperature=0,
53
+ max_tokens=max_tokens,
54
+ extra_body={"ignore_eos": False},
55
+ )
56
+
57
+ response_ignore_eos = client.chat.completions.create(
58
+ model=self.model,
59
+ messages=[
60
+ {"role": "system", "content": "You are a helpful assistant."},
61
+ {"role": "user", "content": "Count from 1 to 20."},
62
+ ],
63
+ temperature=0,
64
+ max_tokens=max_tokens,
65
+ extra_body={"ignore_eos": True},
66
+ )
67
+
68
+ default_tokens = len(
69
+ self.tokenizer.encode(response_default.choices[0].message.content)
70
+ )
71
+ ignore_eos_tokens = len(
72
+ self.tokenizer.encode(response_ignore_eos.choices[0].message.content)
73
+ )
74
+
75
+ # Check if ignore_eos resulted in more tokens or exactly max_tokens
76
+ # The ignore_eos response should either:
77
+ # 1. Have more tokens than the default response (if default stopped at EOS before max_tokens)
78
+ # 2. Have exactly max_tokens (if it reached the max_tokens limit)
79
+ self.assertTrue(
80
+ ignore_eos_tokens > default_tokens or ignore_eos_tokens >= max_tokens,
81
+ f"ignore_eos did not generate more tokens: {ignore_eos_tokens} vs {default_tokens}",
82
+ )
83
+
84
+ self.assertEqual(
85
+ response_ignore_eos.choices[0].finish_reason,
86
+ "length",
87
+ f"Expected finish_reason='length' for ignore_eos=True, got {response_ignore_eos.choices[0].finish_reason}",
88
+ )
89
+
90
+
91
+ if __name__ == "__main__":
92
+ import unittest
93
+
94
+ unittest.main()
asian_ai/performance/SGLang/test/registered/openai_server/validation/test_request_length_validation.py ADDED
@@ -0,0 +1,174 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import unittest
2
+
3
+ import openai
4
+ import requests
5
+
6
+ from sglang.srt.utils import kill_process_tree
7
+ from sglang.test.ci.ci_register import register_amd_ci, register_cuda_ci
8
+ from sglang.test.test_utils import (
9
+ DEFAULT_SMALL_MODEL_NAME_FOR_TEST,
10
+ DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH,
11
+ DEFAULT_URL_FOR_TEST,
12
+ CustomTestCase,
13
+ popen_launch_server,
14
+ )
15
+
16
+ register_cuda_ci(est_time=49, stage="base-b", runner_config="1-gpu-large")
17
+ register_amd_ci(est_time=31, suite="stage-b-test-1-gpu-small-amd")
18
+
19
+
20
+ class TestRequestLengthValidation(CustomTestCase):
21
+ @classmethod
22
+ def setUpClass(cls):
23
+ cls.base_url = DEFAULT_URL_FOR_TEST
24
+ cls.api_key = "sk-123456"
25
+
26
+ # Start server with auto truncate disabled
27
+ cls.process = popen_launch_server(
28
+ DEFAULT_SMALL_MODEL_NAME_FOR_TEST,
29
+ cls.base_url,
30
+ timeout=DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH,
31
+ api_key=cls.api_key,
32
+ other_args=("--max-total-tokens", "1000", "--context-length", "1000"),
33
+ )
34
+
35
+ @classmethod
36
+ def tearDownClass(cls):
37
+ kill_process_tree(cls.process.pid)
38
+
39
+ def test_input_length_longer_than_context_length(self):
40
+ client = openai.Client(api_key=self.api_key, base_url=f"{self.base_url}/v1")
41
+
42
+ long_text = "hello " * 1200 # Will tokenize to more than context length
43
+
44
+ with self.assertRaises(openai.BadRequestError) as cm:
45
+ client.chat.completions.create(
46
+ model=DEFAULT_SMALL_MODEL_NAME_FOR_TEST,
47
+ messages=[
48
+ {"role": "user", "content": long_text},
49
+ ],
50
+ temperature=0,
51
+ )
52
+
53
+ self.assertIn("is longer than the model's context length", str(cm.exception))
54
+
55
+ def test_input_length_longer_than_maximum_allowed_length(self):
56
+ client = openai.Client(api_key=self.api_key, base_url=f"{self.base_url}/v1")
57
+
58
+ long_text = "hello " * 999 # the maximum allowed length is 994 tokens
59
+
60
+ with self.assertRaises(openai.BadRequestError) as cm:
61
+ client.chat.completions.create(
62
+ model=DEFAULT_SMALL_MODEL_NAME_FOR_TEST,
63
+ messages=[
64
+ {"role": "user", "content": long_text},
65
+ ],
66
+ temperature=0,
67
+ )
68
+
69
+ self.assertIn("is longer than the model's context length", str(cm.exception))
70
+
71
+ def test_input_length_longer_than_context_length_streaming(self):
72
+ client = openai.Client(api_key=self.api_key, base_url=f"{self.base_url}/v1")
73
+
74
+ long_text = "hello " * 1200
75
+
76
+ with self.assertRaises(openai.BadRequestError) as cm:
77
+ client.chat.completions.create(
78
+ model=DEFAULT_SMALL_MODEL_NAME_FOR_TEST,
79
+ messages=[
80
+ {"role": "user", "content": long_text},
81
+ ],
82
+ temperature=0,
83
+ stream=True,
84
+ )
85
+
86
+ self.assertIn("is longer than the model's context length", str(cm.exception))
87
+
88
+ def test_max_tokens_validation(self):
89
+ client = openai.Client(api_key=self.api_key, base_url=f"{self.base_url}/v1")
90
+
91
+ long_text = "hello "
92
+
93
+ with self.assertRaises(openai.BadRequestError) as cm:
94
+ client.chat.completions.create(
95
+ model=DEFAULT_SMALL_MODEL_NAME_FOR_TEST,
96
+ messages=[
97
+ {"role": "user", "content": long_text},
98
+ ],
99
+ temperature=0,
100
+ max_tokens=1200,
101
+ )
102
+
103
+ self.assertIn(
104
+ "max_completion_tokens is too large",
105
+ str(cm.exception),
106
+ )
107
+
108
+ def test_token_ids_logprob_out_of_vocabulary(self):
109
+ headers = {"Authorization": f"Bearer {self.api_key}"}
110
+ for token_ids_logprob in ([-1], [2_000_000_000]):
111
+ response = requests.post(
112
+ f"{self.base_url}/generate",
113
+ headers=headers,
114
+ json={
115
+ "text": "hi",
116
+ "sampling_params": {"max_new_tokens": 1},
117
+ "return_logprob": True,
118
+ "token_ids_logprob": token_ids_logprob,
119
+ },
120
+ )
121
+ self.assertEqual(response.status_code, 400)
122
+ self.assertIn("out-of-vocabulary", response.text)
123
+
124
+ def test_token_ids_logprob_rejects_nested_list(self):
125
+ # Nested lists are a batch-level wire format; a single request must
126
+ # pass a flat list of ints. A ragged nested list with in-vocab ids
127
+ # would otherwise crash the scheduler in the sampler gather.
128
+ headers = {"Authorization": f"Bearer {self.api_key}"}
129
+ for token_ids_logprob in ([[0]], [[0], [1, 2]]):
130
+ response = requests.post(
131
+ f"{self.base_url}/generate",
132
+ headers=headers,
133
+ json={
134
+ "text": "hi",
135
+ "sampling_params": {"max_new_tokens": 1},
136
+ "return_logprob": True,
137
+ "token_ids_logprob": token_ids_logprob,
138
+ },
139
+ )
140
+ self.assertEqual(response.status_code, 400)
141
+ self.assertIn("flat list of integers", response.text)
142
+
143
+ def test_token_ids_logprob_batch_with_one_oov(self):
144
+ headers = {"Authorization": f"Bearer {self.api_key}"}
145
+ response = requests.post(
146
+ f"{self.base_url}/generate",
147
+ headers=headers,
148
+ json={
149
+ "text": ["hi", "hi"],
150
+ "sampling_params": {"max_new_tokens": 1},
151
+ "return_logprob": True,
152
+ "token_ids_logprob": [[0], [2_000_000_000]],
153
+ },
154
+ )
155
+ self.assertEqual(response.status_code, 400)
156
+ self.assertIn("out-of-vocabulary", response.text)
157
+
158
+ def test_token_ids_logprob_valid(self):
159
+ headers = {"Authorization": f"Bearer {self.api_key}"}
160
+ response = requests.post(
161
+ f"{self.base_url}/generate",
162
+ headers=headers,
163
+ json={
164
+ "text": "hi",
165
+ "sampling_params": {"max_new_tokens": 1},
166
+ "return_logprob": True,
167
+ "token_ids_logprob": [0],
168
+ },
169
+ )
170
+ self.assertEqual(response.status_code, 200)
171
+
172
+
173
+ if __name__ == "__main__":
174
+ unittest.main()
asian_ai/performance/SGLang/test/registered/ops/test_aiter_allgather_amd.py ADDED
@@ -0,0 +1,116 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import subprocess
3
+ import sys
4
+ import unittest
5
+ from pathlib import Path
6
+
7
+ import torch
8
+
9
+ from sglang.test.ci.ci_register import register_amd_ci
10
+
11
+ register_amd_ci(est_time=180, suite="stage-c-test-large-8-gpu-amd")
12
+
13
+
14
+ class TestAiterAllGatherAmd(unittest.TestCase):
15
+
16
+ @staticmethod
17
+ def _gpu_count():
18
+ return torch.cuda.device_count() if torch.cuda.is_available() else 0
19
+
20
+ def test_aiter_allgather_matches_rccl(self):
21
+ gpu_count = self._gpu_count()
22
+ if gpu_count < 2:
23
+ self.skipTest("This test requires at least 2 GPUs.")
24
+
25
+ repo_root = Path(__file__).resolve().parents[3]
26
+ benchmark_script = (
27
+ repo_root / "benchmark" / "kernels" / "all_gather" / "benchmark_aiter.py"
28
+ )
29
+ self.assertTrue(
30
+ benchmark_script.exists(),
31
+ f"Missing benchmark script: {benchmark_script}",
32
+ )
33
+
34
+ dtype_names = [
35
+ "float32",
36
+ "float16",
37
+ "bfloat16",
38
+ ]
39
+ # Keep the CI matrix compact: one small metadata shape and one
40
+ # medium aligned 2-D shape exercise both naive and vectorized kernels.
41
+ shapes = "16,;8,1024"
42
+ dims = "0,-1"
43
+ tp_sizes = [tp for tp in (2, 4, 8) if gpu_count >= tp]
44
+
45
+ outputs = []
46
+ for tp_size in tp_sizes:
47
+ cmd = [
48
+ sys.executable,
49
+ "-m",
50
+ "torch.distributed.run",
51
+ "--standalone",
52
+ f"--nproc_per_node={tp_size}",
53
+ str(benchmark_script),
54
+ "--dtype",
55
+ ",".join(dtype_names),
56
+ "--shapes",
57
+ shapes,
58
+ "--dims",
59
+ dims,
60
+ "--warmup",
61
+ "0",
62
+ "--iters",
63
+ "1",
64
+ "--correctness-only",
65
+ ]
66
+
67
+ env = os.environ.copy()
68
+ env.setdefault("AITER_AOT_IMPORT", "1")
69
+ result = subprocess.run(
70
+ cmd,
71
+ cwd=str(repo_root),
72
+ env=env,
73
+ stdout=subprocess.PIPE,
74
+ stderr=subprocess.STDOUT,
75
+ text=True,
76
+ timeout=240,
77
+ )
78
+ outputs.append(f"### TP={tp_size}\n{result.stdout}")
79
+
80
+ if result.returncode != 0:
81
+ self.fail(
82
+ "Aiter all-gather correctness sweep failed.\n"
83
+ f"Return code: {result.returncode}\n"
84
+ f"Command: {' '.join(cmd)}\n"
85
+ f"Output:\n{result.stdout}"
86
+ )
87
+
88
+ expected_rows = (
89
+ len(dtype_names) * len(shapes.split(";")) * len(dims.split(","))
90
+ )
91
+ rows = [
92
+ line.strip()
93
+ for line in result.stdout.splitlines()
94
+ if line.strip().startswith(tuple(dtype_names))
95
+ ]
96
+ self.assertEqual(
97
+ expected_rows,
98
+ len(rows),
99
+ f"Expected {expected_rows} rows for TP={tp_size}, got:\n{result.stdout}",
100
+ )
101
+
102
+ bad_rows = [row for row in rows if " True " not in row]
103
+ self.assertEqual(
104
+ [],
105
+ bad_rows,
106
+ f"Correctness failed for one or more all-gather rows:\n{result.stdout}",
107
+ )
108
+
109
+ if gpu_count >= 8:
110
+ self.assertEqual([2, 4, 8], tp_sizes)
111
+ else:
112
+ self.assertEqual([2, 4][: len(tp_sizes)], tp_sizes)
113
+
114
+
115
+ if __name__ == "__main__":
116
+ unittest.main()
asian_ai/performance/SGLang/test/registered/ops/test_aiter_allreduce_fusion_amd.py ADDED
@@ -0,0 +1,480 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import csv
2
+ import os
3
+ import subprocess
4
+ import sys
5
+ import tempfile
6
+ import types
7
+ import unittest
8
+ from contextlib import ExitStack
9
+ from pathlib import Path
10
+ from unittest import mock
11
+
12
+ import torch
13
+
14
+ from sglang.srt.layers import communicator as comm
15
+ from sglang.srt.layers.communicator import LayerCommunicator, ScatterMode
16
+ from sglang.test.ci.ci_register import register_amd_ci
17
+ from sglang.test.test_utils import CustomTestCase
18
+
19
+ register_amd_ci(est_time=240, suite="stage-c-test-large-8-gpu-amd")
20
+
21
+ HIDDEN_DIMS = [2880, 4096, 5120, 6144, 7168, 8192]
22
+
23
+
24
+ def _run_residual_accuracy_check():
25
+ """Distributed entry point: residual accuracy across 1-stage/2-stage paths.
26
+
27
+ Regression test for the 1-stage kernel accuracy bug (ROCm/aiter#2586):
28
+ allreduce_fusion_kernel_1stage accumulated in f32 and added the residual
29
+ before rounding to bf16, while the unfused path rounds allreduce to bf16
30
+ first. The fix (43b7379b8 in aiter) inserts a bf16 round-trip after
31
+ accumulation so the fused kernel matches the unfused path bit-for-bit.
32
+
33
+ The tolerance here is 1 bf16 ULP (atol = bf16_eps * max_magnitude ~= 0.125)
34
+ rather than 0.0, because the prebuilt aiter kernel in the CI docker image
35
+ may pre-date the fix. A diff of exactly 1 ULP indicates the unfixed
36
+ kernel; a larger diff indicates a real regression and will fail the test.
37
+
38
+ Must be launched via torchrun (multi-GPU).
39
+ """
40
+ import torch.distributed as dist
41
+
42
+ from sglang.srt.distributed.communication_op import (
43
+ tensor_model_parallel_fused_allreduce_rmsnorm,
44
+ )
45
+ from sglang.srt.distributed.parallel_state import (
46
+ destroy_distributed_environment,
47
+ destroy_model_parallel,
48
+ init_distributed_environment,
49
+ initialize_model_parallel,
50
+ set_custom_all_reduce,
51
+ )
52
+
53
+ rank = int(os.environ.get("RANK", "0"))
54
+ world_size = int(os.environ.get("WORLD_SIZE", "1"))
55
+ local_rank = int(os.environ.get("LOCAL_RANK", str(rank)))
56
+ torch.cuda.set_device(local_rank % torch.cuda.device_count())
57
+ device = torch.device(f"cuda:{local_rank % torch.cuda.device_count()}")
58
+
59
+ set_custom_all_reduce(True)
60
+ init_distributed_environment(
61
+ world_size=world_size,
62
+ rank=rank,
63
+ local_rank=local_rank,
64
+ distributed_init_method="env://",
65
+ backend="nccl",
66
+ )
67
+ initialize_model_parallel(tensor_model_parallel_size=world_size)
68
+
69
+ dtype = torch.bfloat16
70
+ eps = 1e-6
71
+ # Allow at most 1 bf16 ULP of error in the residual output.
72
+ # bf16 epsilon = 2^-7; values in practice stay below ~16, so 1 ULP <= 0.125.
73
+ # A multi-ULP error (>0.125) indicates a real regression and fails the test.
74
+ # Exactly 1 ULP indicates the prebuilt aiter kernel predates the fix in
75
+ # ROCm/aiter#2586 (43b7379b8); the test still guards against regressions.
76
+ ATOL = 0.13
77
+
78
+ all_pass = True
79
+ test_cases = [(m, n) for n in HIDDEN_DIMS for m in [1, 4, 8, 16, 32, 64, 128]]
80
+
81
+ prev_n = None
82
+ for m, n in test_cases:
83
+ if n != prev_n:
84
+ prev_n = n
85
+ weight = torch.ones((n,), dtype=dtype, device=device)
86
+ if rank == 0:
87
+ print(f"\nhidden_dim={n}:")
88
+
89
+ torch.manual_seed(1234 + rank * 17 + m)
90
+ x = torch.randn((m, n), dtype=torch.float32, device=device).to(dtype)
91
+ residual = torch.randn((m, n), dtype=torch.float32, device=device).to(dtype)
92
+ zero_res = torch.zeros((m, n), dtype=dtype, device=device)
93
+
94
+ dist.barrier()
95
+ torch.cuda.synchronize()
96
+
97
+ fused_zero = tensor_model_parallel_fused_allreduce_rmsnorm(
98
+ x.clone(), zero_res.clone(), weight, eps
99
+ )
100
+ torch.cuda.synchronize()
101
+ if fused_zero is None:
102
+ if rank == 0:
103
+ print(f" {m:>5d}x{n}: SKIP (fused unavailable)")
104
+ continue
105
+ _, fused_ar = fused_zero
106
+
107
+ dist.barrier()
108
+ torch.cuda.synchronize()
109
+
110
+ fused_random = tensor_model_parallel_fused_allreduce_rmsnorm(
111
+ x.clone(), residual.clone(), weight, eps
112
+ )
113
+ torch.cuda.synchronize()
114
+ _, fused_res = fused_random
115
+
116
+ dist.barrier()
117
+ torch.cuda.synchronize()
118
+
119
+ # Reference: fused_ar (AR rounded to bf16, zero residual) + residual.
120
+ # With the aiter fix (43b7379b8), this matches fused_res bit-for-bit.
121
+ # Without the fix, fused_res may differ by exactly 1 bf16 ULP, which
122
+ # is tolerated by ATOL but still guarded against larger regressions.
123
+ expected = fused_ar + residual
124
+ diff = (fused_res.float() - expected.float()).abs()
125
+ max_diff = diff.max().item()
126
+ frac_nonzero = (diff > 0).float().mean().item()
127
+
128
+ nbytes = m * n * dtype.itemsize
129
+ stage = "1-stage" if nbytes <= 128 * 1024 else "2-stage"
130
+ passed = max_diff <= ATOL
131
+
132
+ if not passed:
133
+ all_pass = False
134
+
135
+ if rank == 0:
136
+ status = "PASS" if passed else "FAIL"
137
+ print(
138
+ f" {m:>5d}x{n} ({stage:>7s}): max_diff={max_diff:.6e} "
139
+ f"frac_nonzero={frac_nonzero:.4f} "
140
+ f"[{status}]"
141
+ )
142
+
143
+ dist.barrier()
144
+ destroy_model_parallel()
145
+ destroy_distributed_environment()
146
+
147
+ if rank == 0:
148
+ print()
149
+ if all_pass:
150
+ print(
151
+ "ALL PASSED: fused residual output within 1 bf16 ULP of unfused path."
152
+ )
153
+ else:
154
+ print(
155
+ "FAILED: fused residual output diverges beyond 1 ULP from unfused path."
156
+ )
157
+ sys.exit(0 if all_pass else 1)
158
+
159
+
160
+ class TestAiterAllreduceFusionAmd(unittest.TestCase):
161
+
162
+ @staticmethod
163
+ def _gpu_count():
164
+ return torch.cuda.device_count() if torch.cuda.is_available() else 0
165
+
166
+ def _run_benchmark(self, nproc, prefill_shapes, decode_shapes):
167
+ """Run the benchmark subprocess and return parsed CSV rows."""
168
+ repo_root = Path(__file__).resolve().parents[3]
169
+ benchmark_script = (
170
+ repo_root
171
+ / "benchmark"
172
+ / "kernels"
173
+ / "all_reduce"
174
+ / "benchmark_fused_ar_rms_amd.py"
175
+ )
176
+ self.assertTrue(
177
+ benchmark_script.exists(),
178
+ f"Missing benchmark script: {benchmark_script}",
179
+ )
180
+
181
+ with tempfile.TemporaryDirectory(prefix="aiter_fused_ar_rms_") as tmpdir:
182
+ csv_path = Path(tmpdir) / "fused_ar_rms_check.csv"
183
+ cmd = [
184
+ sys.executable,
185
+ "-m",
186
+ "torch.distributed.run",
187
+ "--standalone",
188
+ f"--nproc_per_node={nproc}",
189
+ str(benchmark_script),
190
+ "--dtype",
191
+ "bf16",
192
+ "--prefill-shapes",
193
+ prefill_shapes,
194
+ "--decode-shapes",
195
+ decode_shapes,
196
+ "--warmup",
197
+ "3",
198
+ "--iters",
199
+ "15",
200
+ "--repeats",
201
+ "2",
202
+ "--csv-out",
203
+ str(csv_path),
204
+ ]
205
+
206
+ env = os.environ.copy()
207
+ result = subprocess.run(
208
+ cmd,
209
+ cwd=str(repo_root),
210
+ env=env,
211
+ stdout=subprocess.PIPE,
212
+ stderr=subprocess.STDOUT,
213
+ text=True,
214
+ timeout=1200,
215
+ )
216
+
217
+ if result.returncode != 0:
218
+ self.fail(
219
+ "Benchmark command failed.\n"
220
+ f"Return code: {result.returncode}\n"
221
+ f"Command: {' '.join(cmd)}\n"
222
+ f"Output:\n{result.stdout}"
223
+ )
224
+
225
+ self.assertTrue(csv_path.exists(), f"CSV output not found: {csv_path}")
226
+
227
+ with open(csv_path, "r", encoding="utf-8") as f:
228
+ rows = list(csv.DictReader(f))
229
+
230
+ self.assertGreater(len(rows), 0, "CSV contains no rows.")
231
+ return rows
232
+
233
+ def _assert_correctness(self, rows):
234
+ bad_rows = [r for r in rows if r["correctness_ok"] != "True"]
235
+ self.assertEqual(
236
+ [],
237
+ bad_rows,
238
+ f"Found correctness failures: {bad_rows}",
239
+ )
240
+
241
+ def test_fused_ar_rms_benchmark(self):
242
+ if self._gpu_count() < 8:
243
+ self.skipTest("This test requires at least 8 GPUs.")
244
+
245
+ rows = self._run_benchmark(
246
+ nproc=8,
247
+ prefill_shapes="128x7168,512x7168,2048x7168,4096x7168,5120x7168",
248
+ decode_shapes="1x7168,8x7168,64x7168,512x7168",
249
+ )
250
+
251
+ eager_rows = [r for r in rows if r["mode"] == "eager"]
252
+ graph_rows = [r for r in rows if r["mode"] == "graph"]
253
+ self.assertGreater(len(eager_rows), 0, "Missing eager rows in CSV.")
254
+ self.assertGreater(len(graph_rows), 0, "Missing graph rows in CSV.")
255
+
256
+ self._assert_correctness(rows)
257
+
258
+ self.assertTrue(
259
+ any(r["fused_available"] == "True" for r in eager_rows),
260
+ "Expected at least one eager row with fused_available=True.",
261
+ )
262
+ self.assertTrue(
263
+ any(r["fused_available"] == "True" for r in graph_rows),
264
+ "Expected at least one graph row with fused_available=True.",
265
+ )
266
+
267
+ large_eager_rows = [
268
+ r for r in eager_rows if int(r["bytes_per_rank"]) > 64 * 1024 * 1024
269
+ ]
270
+ self.assertTrue(
271
+ any(r["fused_available"] == "False" for r in large_eager_rows),
272
+ "Expected fused fallback for oversized eager shape(s) under default gate.",
273
+ )
274
+
275
+ def test_fused_ar_rms_multi_hidden_dim(self):
276
+ """Correctness across hidden_dims from various models (TP=4)."""
277
+ nproc = min(self._gpu_count(), 4)
278
+ if nproc < 2:
279
+ self.skipTest("This test requires at least 2 GPUs.")
280
+
281
+ # hidden_dims: 2880 (GPT-OSS), 4096 (Qwen3.5), 5120, 6144 (Mixtral),
282
+ # 7168 (DeepSeek), 8192 (Llama-70B)
283
+ decode = ",".join(f"{m}x{n}" for n in HIDDEN_DIMS for m in [1, 4, 16])
284
+ prefill = ",".join(f"128x{n}" for n in HIDDEN_DIMS)
285
+
286
+ rows = self._run_benchmark(
287
+ nproc=nproc,
288
+ prefill_shapes=prefill,
289
+ decode_shapes=decode,
290
+ )
291
+
292
+ self._assert_correctness(rows)
293
+
294
+ fused_rows = [r for r in rows if r["fused_available"] == "True"]
295
+ self.assertEqual(
296
+ len(fused_rows),
297
+ len(rows),
298
+ f"Expected fused available for all shapes, but {len(rows) - len(fused_rows)} "
299
+ f"rows were not fused: "
300
+ f"{[r['shape'] for r in rows if r['fused_available'] != 'True']}",
301
+ )
302
+
303
+ def test_fused_ar_rms_residual_accuracy(self):
304
+ """Residual accuracy within 1 bf16 ULP across 1-stage and 2-stage paths.
305
+
306
+ Regression test for ROCm/aiter#2586. The fused kernel must round the
307
+ allreduce result to bf16 before adding residual (fix: 43b7379b8 in aiter).
308
+ Tolerance is 1 bf16 ULP (atol=0.13) to accommodate prebuilt CI images
309
+ that may predate the fix; multi-ULP divergence indicates a regression.
310
+ Launches this file itself via torchrun with --residual-accuracy.
311
+ """
312
+ nproc = min(self._gpu_count(), 4)
313
+ if nproc < 2:
314
+ self.skipTest("This test requires at least 2 GPUs.")
315
+
316
+ cmd = [
317
+ sys.executable,
318
+ "-m",
319
+ "torch.distributed.run",
320
+ "--standalone",
321
+ f"--nproc_per_node={nproc}",
322
+ __file__,
323
+ "--residual-accuracy",
324
+ ]
325
+
326
+ result = subprocess.run(
327
+ cmd,
328
+ cwd=str(Path(__file__).resolve().parents[3]),
329
+ env=os.environ.copy(),
330
+ stdout=subprocess.PIPE,
331
+ stderr=subprocess.STDOUT,
332
+ text=True,
333
+ timeout=300,
334
+ )
335
+
336
+ if result.returncode != 0:
337
+ self.fail(
338
+ "Residual accuracy check failed.\n"
339
+ f"Return code: {result.returncode}\n"
340
+ f"Command: {' '.join(cmd)}\n"
341
+ f"Output:\n{result.stdout}"
342
+ )
343
+
344
+ self.assertIn(
345
+ "ALL PASSED",
346
+ result.stdout,
347
+ f"Expected 'ALL PASSED' in output, got:\n{result.stdout}",
348
+ )
349
+
350
+
351
+ def _fake_self(*, mlp_mode=ScatterMode.TP_ATTN_FULL, is_last_layer=False, tp_size=8):
352
+ """Minimal stand-in for a LayerCommunicator with the fields the gate reads."""
353
+ return types.SimpleNamespace(
354
+ _speculative_algo=None,
355
+ layer_scatter_modes=types.SimpleNamespace(mlp_mode=mlp_mode),
356
+ is_last_layer=is_last_layer,
357
+ _context=types.SimpleNamespace(tp_size=tp_size),
358
+ )
359
+
360
+
361
+ def _fake_forward_batch(batch_size=8):
362
+ return types.SimpleNamespace(input_ids=types.SimpleNamespace(shape=(batch_size,)))
363
+
364
+
365
+ class TestAiterAllreduceFusionGate(CustomTestCase):
366
+ """Pure-logic coverage of the aiter all-reduce + RMSNorm fusion gate.
367
+
368
+ Covers ``LayerCommunicator.should_fuse_mlp_allreduce_with_next_layer``,
369
+ specifically the AMD/aiter branch guards that disable the fused path under
370
+ DP attention or an expert-parallel A2A backend (e.g. mori). Without those
371
+ guards the fused custom all-reduce is invoked during CUDA graph capture in
372
+ those configs and crashes in ``custom_all_reduce.flush_graph_buffers``.
373
+
374
+ The gate is pure decision logic, so the test stubs out the module-level
375
+ dependencies and invokes the method on a minimal fake instance. No GPU or
376
+ distributed initialization is required.
377
+ """
378
+
379
+ def _evaluate_gate(
380
+ self,
381
+ *,
382
+ dp_attention,
383
+ a2a_is_none,
384
+ aiter_enabled=True,
385
+ use_aiter=True,
386
+ tp_world_size=8,
387
+ mlp_mode=ScatterMode.TP_ATTN_FULL,
388
+ is_last_layer=False,
389
+ tp_size=8,
390
+ ):
391
+ """Run the gate with the aiter branch isolated (flashinfer forced off)."""
392
+ server_args = types.SimpleNamespace(enable_aiter_allreduce_fusion=aiter_enabled)
393
+ a2a_backend = types.SimpleNamespace(is_none=lambda: a2a_is_none)
394
+
395
+ with ExitStack() as stack:
396
+ stack.enter_context(
397
+ mock.patch.object(comm, "is_enable_moe_cp_allgather", lambda: False)
398
+ )
399
+ stack.enter_context(
400
+ mock.patch.object(
401
+ comm,
402
+ "get_attn_tp_context",
403
+ lambda: types.SimpleNamespace(input_scattered=False),
404
+ )
405
+ )
406
+ # Force the NVIDIA/flashinfer term off so the aiter branch decides.
407
+ stack.enter_context(
408
+ mock.patch.object(
409
+ comm, "apply_flashinfer_allreduce_fusion", lambda batch_size: False
410
+ )
411
+ )
412
+ stack.enter_context(mock.patch.object(comm, "_use_aiter", use_aiter))
413
+ stack.enter_context(
414
+ mock.patch.object(
415
+ comm,
416
+ "get_parallel",
417
+ lambda: types.SimpleNamespace(tp_size=tp_world_size),
418
+ )
419
+ )
420
+ stack.enter_context(
421
+ mock.patch.object(comm, "get_global_server_args", lambda: server_args)
422
+ )
423
+ stack.enter_context(
424
+ mock.patch.object(comm, "is_dp_attention_enabled", lambda: dp_attention)
425
+ )
426
+ stack.enter_context(
427
+ mock.patch.object(comm, "get_moe_a2a_backend", lambda: a2a_backend)
428
+ )
429
+
430
+ fake_self = _fake_self(
431
+ mlp_mode=mlp_mode, is_last_layer=is_last_layer, tp_size=tp_size
432
+ )
433
+ return LayerCommunicator.should_fuse_mlp_allreduce_with_next_layer(
434
+ fake_self, _fake_forward_batch()
435
+ )
436
+
437
+ def test_dense_tp_fuses(self):
438
+ # Baseline supported path: dense TP, no DP attention, no EP backend.
439
+ self.assertTrue(self._evaluate_gate(dp_attention=False, a2a_is_none=True))
440
+
441
+ def test_dp_attention_disables_fusion(self):
442
+ # The fix: DP attention has no dense TP all-reduce to fuse.
443
+ self.assertFalse(self._evaluate_gate(dp_attention=True, a2a_is_none=True))
444
+
445
+ def test_ep_backend_disables_fusion(self):
446
+ # The fix: with an EP A2A backend (e.g. mori) the reduction lives in
447
+ # combine(), not a TP all-reduce.
448
+ self.assertFalse(self._evaluate_gate(dp_attention=False, a2a_is_none=False))
449
+
450
+ def test_dp_attention_and_ep_disables_fusion(self):
451
+ # The crashing config from the TP8+EP8+mori repro.
452
+ self.assertFalse(self._evaluate_gate(dp_attention=False, a2a_is_none=False))
453
+ self.assertFalse(self._evaluate_gate(dp_attention=True, a2a_is_none=False))
454
+
455
+ def test_flag_off_disables_fusion(self):
456
+ # Sanity: the gate still respects the opt-in flag on the dense path.
457
+ self.assertFalse(
458
+ self._evaluate_gate(
459
+ dp_attention=False, a2a_is_none=True, aiter_enabled=False
460
+ )
461
+ )
462
+
463
+ def test_last_layer_disables_fusion(self):
464
+ self.assertFalse(
465
+ self._evaluate_gate(
466
+ dp_attention=False, a2a_is_none=True, is_last_layer=True
467
+ )
468
+ )
469
+
470
+ def test_tp1_disables_fusion(self):
471
+ self.assertFalse(
472
+ self._evaluate_gate(dp_attention=False, a2a_is_none=True, tp_size=1)
473
+ )
474
+
475
+
476
+ if __name__ == "__main__":
477
+ if "--residual-accuracy" in sys.argv:
478
+ _run_residual_accuracy_check()
479
+ else:
480
+ unittest.main()
asian_ai/performance/SGLang/test/registered/ops/test_aiter_greedy_sample_amd.py ADDED
@@ -0,0 +1,289 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Unit tests for aiter greedy_sample kernel and Sampler integration.
2
+
3
+ Validates that:
4
+ 1. aiter.greedy_sample produces identical results to torch.argmax (kernel level)
5
+ 2. Sampler.forward() correctly dispatches to aiter when _use_aiter=True
6
+ 3. The fallback to torch.argmax works when _use_aiter=False
7
+ 4. return_logprob path works with the aiter greedy branch
8
+
9
+ The kernel is designed for production LLM inference (large vocab, bf16) and is
10
+ used when SGLANG_USE_AITER=1 on ROCm.
11
+ """
12
+
13
+ import unittest
14
+ from unittest import mock
15
+
16
+ import torch
17
+
18
+ from sglang.srt.utils.common import is_hip
19
+ from sglang.test.ci.ci_register import register_amd_ci
20
+
21
+ register_amd_ci(est_time=60, suite="stage-b-test-1-gpu-small-amd")
22
+
23
+
24
+ def _mock_global_server_args(backend="pytorch"):
25
+ from sglang.srt.layers import sampler as sampler_mod
26
+ from sglang.srt.server_args import ServerArgs
27
+
28
+ sampler_mod.get_global_server_args = lambda: ServerArgs(
29
+ model_path="dummy",
30
+ sampling_backend=backend,
31
+ )
32
+
33
+ class _DummyTPGroup:
34
+ device_group = None
35
+
36
+ sampler_mod.get_tp_group = lambda: _DummyTPGroup()
37
+ sampler_mod.is_dp_attention_enabled = lambda: False
38
+
39
+
40
+ def _make_sampling_info(batch_size, vocab_size, device="cuda"):
41
+ from sglang.srt.sampling.sampling_batch_info import SamplingBatchInfo
42
+
43
+ return SamplingBatchInfo(
44
+ temperatures=torch.ones(batch_size, 1, device=device, dtype=torch.float),
45
+ top_ps=torch.ones(batch_size, device=device),
46
+ top_ks=torch.zeros(batch_size, device=device, dtype=torch.int32),
47
+ min_ps=torch.zeros(batch_size, device=device),
48
+ is_all_greedy=True,
49
+ need_top_p_sampling=False,
50
+ need_top_k_sampling=False,
51
+ need_min_p_sampling=False,
52
+ vocab_size=vocab_size,
53
+ device=device,
54
+ )
55
+
56
+
57
+ @unittest.skipUnless(is_hip(), "aiter greedy_sample requires ROCm")
58
+ class TestAiterGreedySample(unittest.TestCase):
59
+ """Kernel-level correctness: aiter.greedy_sample vs torch.argmax."""
60
+
61
+ @classmethod
62
+ def setUpClass(cls):
63
+ try:
64
+ from aiter import greedy_sample
65
+
66
+ cls.greedy_sample = staticmethod(greedy_sample)
67
+ except ImportError:
68
+ raise unittest.SkipTest("aiter not installed")
69
+ cls.device = "cuda"
70
+
71
+ def setUp(self):
72
+ torch.manual_seed(42)
73
+ torch.cuda.manual_seed_all(42)
74
+
75
+ def _run_and_compare(self, batch_size, vocab_size):
76
+ logits = torch.randn(
77
+ batch_size, vocab_size, device=self.device, dtype=torch.bfloat16
78
+ )
79
+
80
+ expected = torch.argmax(logits, dim=-1)
81
+
82
+ actual = torch.empty(logits.shape[0], device=logits.device, dtype=torch.int32)
83
+ self.greedy_sample(actual, logits)
84
+
85
+ self.assertTrue(
86
+ torch.equal(actual.to(expected.dtype), expected),
87
+ f"Mismatch for shape ({batch_size}, {vocab_size}): "
88
+ f"expected={expected[:8].tolist()}, got={actual[:8].tolist()}",
89
+ )
90
+
91
+ def test_single_request(self):
92
+ self._run_and_compare(1, 32000)
93
+
94
+ def test_small_batch(self):
95
+ self._run_and_compare(4, 32000)
96
+
97
+ def test_medium_batch(self):
98
+ self._run_and_compare(32, 32000)
99
+
100
+ def test_large_batch(self):
101
+ self._run_and_compare(128, 32000)
102
+
103
+ def test_realistic_vocab_deepseek(self):
104
+ self._run_and_compare(64, 129280)
105
+
106
+ def test_realistic_vocab_llama3(self):
107
+ self._run_and_compare(64, 128256)
108
+
109
+ def test_realistic_vocab_qwen(self):
110
+ self._run_and_compare(64, 151936)
111
+
112
+ def test_various_batch_sizes(self):
113
+ configs = [
114
+ (1, 128256),
115
+ (2, 128256),
116
+ (8, 128256),
117
+ (16, 128256),
118
+ (32, 129280),
119
+ (64, 129280),
120
+ (128, 129280),
121
+ (256, 129280),
122
+ ]
123
+ for batch_size, vocab_size in configs:
124
+ with self.subTest(batch_size=batch_size, vocab_size=vocab_size):
125
+ self._run_and_compare(batch_size, vocab_size)
126
+
127
+ def test_tied_values(self):
128
+ vocab_size = 32000
129
+ logits = torch.zeros(8, vocab_size, device=self.device, dtype=torch.bfloat16)
130
+ logits[:, 0] = 1.0
131
+
132
+ expected = torch.argmax(logits, dim=-1)
133
+ actual = torch.empty(8, device=self.device, dtype=torch.int32)
134
+ self.greedy_sample(actual, logits)
135
+
136
+ self.assertTrue(torch.equal(actual.to(expected.dtype), expected))
137
+
138
+ def test_negative_logits(self):
139
+ vocab_size = 32000
140
+ logits = (
141
+ torch.randn(16, vocab_size, device=self.device, dtype=torch.bfloat16) - 5.0
142
+ )
143
+
144
+ expected = torch.argmax(logits, dim=-1)
145
+ actual = torch.empty(16, device=self.device, dtype=torch.int32)
146
+ self.greedy_sample(actual, logits)
147
+
148
+ self.assertTrue(torch.equal(actual.to(expected.dtype), expected))
149
+
150
+ def test_extreme_values(self):
151
+ vocab_size = 32000
152
+ logits = torch.randn(16, vocab_size, device=self.device, dtype=torch.bfloat16)
153
+ logits[0, 42] = 1e4
154
+ logits[1, 100] = -1e4
155
+
156
+ expected = torch.argmax(logits, dim=-1)
157
+ actual = torch.empty(16, device=self.device, dtype=torch.int32)
158
+ self.greedy_sample(actual, logits)
159
+
160
+ self.assertTrue(torch.equal(actual.to(expected.dtype), expected))
161
+
162
+
163
+ @unittest.skipUnless(is_hip(), "aiter greedy_sample requires ROCm")
164
+ class TestAiterGreedyIntegration(unittest.TestCase):
165
+ """Integration: Sampler.forward() with _use_aiter on/off."""
166
+
167
+ @classmethod
168
+ def setUpClass(cls):
169
+ try:
170
+ from aiter import greedy_sample
171
+
172
+ cls._greedy_sample_fn = staticmethod(greedy_sample)
173
+ except ImportError:
174
+ raise unittest.SkipTest("aiter not installed")
175
+ cls.device = "cuda"
176
+
177
+ def setUp(self):
178
+ torch.manual_seed(42)
179
+ torch.cuda.manual_seed_all(42)
180
+
181
+ def _run_sampler(self, use_aiter, logits, sampling_info, return_logprob=False):
182
+ from sglang.srt.layers import sampler as sampler_mod
183
+ from sglang.srt.layers.logits_processor import LogitsProcessorOutput
184
+
185
+ _mock_global_server_args()
186
+
187
+ patches = {"_use_aiter": use_aiter}
188
+ if use_aiter:
189
+ patches["_aiter_greedy_sample"] = self._greedy_sample_fn
190
+
191
+ with mock.patch.multiple(sampler_mod, **patches):
192
+ sampler = sampler_mod.Sampler()
193
+ batch_size = logits.shape[0]
194
+ positions = torch.arange(batch_size, device=self.device, dtype=torch.int32)
195
+
196
+ return sampler.forward(
197
+ logits_output=LogitsProcessorOutput(next_token_logits=logits.clone()),
198
+ sampling_info=sampling_info,
199
+ return_logprob=return_logprob,
200
+ top_logprobs_nums=[0] * batch_size,
201
+ token_ids_logprobs=[None] * batch_size,
202
+ positions=positions,
203
+ )
204
+
205
+ def test_aiter_matches_argmax_through_sampler(self):
206
+ batch_size, vocab_size = 64, 129280
207
+ logits = torch.randn(
208
+ batch_size, vocab_size, device=self.device, dtype=torch.bfloat16
209
+ )
210
+ sampling_info = _make_sampling_info(batch_size, vocab_size, self.device)
211
+
212
+ out_aiter = self._run_sampler(True, logits, sampling_info)
213
+ out_argmax = self._run_sampler(False, logits, sampling_info)
214
+
215
+ self.assertTrue(
216
+ torch.equal(out_aiter.cpu(), out_argmax.cpu()),
217
+ f"Sampler mismatch: aiter={out_aiter[:8].tolist()}, "
218
+ f"argmax={out_argmax[:8].tolist()}",
219
+ )
220
+
221
+ def test_fallback_to_argmax_when_disabled(self):
222
+ batch_size, vocab_size = 32, 32000
223
+ logits = torch.randn(
224
+ batch_size, vocab_size, device=self.device, dtype=torch.bfloat16
225
+ )
226
+ sampling_info = _make_sampling_info(batch_size, vocab_size, self.device)
227
+
228
+ out = self._run_sampler(False, logits, sampling_info)
229
+ expected = torch.argmax(logits, dim=-1)
230
+
231
+ self.assertTrue(
232
+ torch.equal(out.cpu(), expected.cpu()),
233
+ "Fallback path should produce torch.argmax results",
234
+ )
235
+
236
+ def test_aiter_greedy_with_return_logprob(self):
237
+ batch_size, vocab_size = 16, 32000
238
+ logits = torch.randn(
239
+ batch_size, vocab_size, device=self.device, dtype=torch.bfloat16
240
+ )
241
+ sampling_info = _make_sampling_info(batch_size, vocab_size, self.device)
242
+
243
+ out_aiter = self._run_sampler(True, logits, sampling_info, return_logprob=True)
244
+ out_argmax = self._run_sampler(
245
+ False, logits, sampling_info, return_logprob=True
246
+ )
247
+
248
+ self.assertTrue(
249
+ torch.equal(out_aiter.cpu(), out_argmax.cpu()),
250
+ "Token IDs should match with return_logprob=True",
251
+ )
252
+
253
+ def test_aiter_output_dtype(self):
254
+ """Document that the aiter path returns int32 (vs int64 from argmax)."""
255
+ batch_size, vocab_size = 16, 32000
256
+ logits = torch.randn(
257
+ batch_size, vocab_size, device=self.device, dtype=torch.bfloat16
258
+ )
259
+ sampling_info = _make_sampling_info(batch_size, vocab_size, self.device)
260
+
261
+ out_aiter = self._run_sampler(True, logits, sampling_info)
262
+ out_argmax = self._run_sampler(False, logits, sampling_info)
263
+
264
+ self.assertEqual(out_aiter.dtype, torch.int32)
265
+ self.assertEqual(out_argmax.dtype, torch.int64)
266
+
267
+ def test_various_batch_sizes_through_sampler(self):
268
+ vocab_size = 129280
269
+ for batch_size in [1, 4, 16, 64, 128]:
270
+ with self.subTest(batch_size=batch_size):
271
+ logits = torch.randn(
272
+ batch_size,
273
+ vocab_size,
274
+ device=self.device,
275
+ dtype=torch.bfloat16,
276
+ )
277
+ sampling_info = _make_sampling_info(batch_size, vocab_size, self.device)
278
+
279
+ out_aiter = self._run_sampler(True, logits, sampling_info)
280
+ out_argmax = self._run_sampler(False, logits, sampling_info)
281
+
282
+ self.assertTrue(
283
+ torch.equal(out_aiter.cpu(), out_argmax.cpu()),
284
+ f"Mismatch at batch_size={batch_size}",
285
+ )
286
+
287
+
288
+ if __name__ == "__main__":
289
+ unittest.main()
asian_ai/performance/SGLang/test/registered/page_major/test_page_major_gpt_oss.py ADDED
@@ -0,0 +1,69 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ End-to-end accuracy test for the page-major KV layout on a hybrid-SWA MoE model.
3
+
4
+ Launches gpt-oss-20b with ``--enable-page-major-kv-layout`` on the Triton
5
+ attention backend and checks that GSM8K accuracy holds. This exercises the
6
+ SWA + full-attention KV pools under the page-granularity envelope layout
7
+ (SWAKVPool routes both sub-pools through PageMajorMHATokenToKVPool).
8
+
9
+ Registered to the label-gated ``run-ci-extra`` suite (opt-in, not per-commit).
10
+
11
+ Usage:
12
+ python3 -m unittest test_page_major_gpt_oss
13
+ """
14
+
15
+ import unittest
16
+ from types import SimpleNamespace
17
+ from urllib.parse import urlparse
18
+
19
+ from sglang.test.ci.ci_register import register_cuda_ci
20
+ from sglang.test.server_fixtures.default_fixture import DefaultServerBase
21
+ from sglang.test.test_utils import DEFAULT_MODEL_NAME_FOR_TEST_MXFP4_WITH_MOE
22
+
23
+ register_cuda_ci(est_time=420, stage="extra-a", runner_config="1-gpu-large")
24
+
25
+
26
+ class TestPageMajorGptOss(DefaultServerBase):
27
+ """Page-major KV layout on gpt-oss-20b (hybrid-SWA MoE), Triton backend."""
28
+
29
+ model = DEFAULT_MODEL_NAME_FOR_TEST_MXFP4_WITH_MOE
30
+
31
+ gsm8k_threshold = 0.45
32
+ num_gsm8k_questions = 200
33
+ num_shots = 5
34
+ parallel = 32
35
+
36
+ other_args = [
37
+ "--enable-page-major-kv-layout",
38
+ # The envelope's strided 4-D K/V views are only read by the Triton
39
+ # attention kernels (the layout's validator enforces this).
40
+ "--attention-backend",
41
+ "triton",
42
+ "--mem-fraction-static",
43
+ "0.70",
44
+ "--cuda-graph-backend-prefill=disabled",
45
+ ]
46
+
47
+ def test_gsm8k(self):
48
+ from sglang.test.few_shot_gsm8k import run_eval as run_few_shot_gsm8k
49
+
50
+ url = urlparse(self.base_url)
51
+ args = SimpleNamespace(
52
+ num_shots=self.num_shots,
53
+ data_path=None,
54
+ num_questions=self.num_gsm8k_questions,
55
+ max_new_tokens=512,
56
+ parallel=self.parallel,
57
+ host=f"http://{url.hostname}",
58
+ port=int(url.port),
59
+ )
60
+ metrics = run_few_shot_gsm8k(args)
61
+ print(
62
+ f"[{self.__class__.__name__}] GSM8K accuracy: {metrics['accuracy']:.3f} "
63
+ f"(threshold: {self.gsm8k_threshold})"
64
+ )
65
+ self.assertGreaterEqual(metrics["accuracy"], self.gsm8k_threshold)
66
+
67
+
68
+ if __name__ == "__main__":
69
+ unittest.main()
asian_ai/performance/SGLang/test/registered/page_major/test_page_major_qwen_hybrid.py ADDED
@@ -0,0 +1,79 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ End-to-end accuracy test for the page-major KV layout on a GDN-hybrid model.
3
+
4
+ Launches Qwen3.5-4B (a gated-delta-net / linear-attention hybrid) with
5
+ ``--enable-page-major-kv-layout`` on the Triton attention + linear-attn + Mamba
6
+ backends and checks that GSM8K accuracy holds. This exercises the page-major
7
+ path most prone to subtle bugs: the Mamba conv/SSM state stored as a strided
8
+ envelope view, plus the full-attention KV pool, both read/written by the GDN
9
+ prefill and decode kernels.
10
+
11
+ Registered to the label-gated ``run-ci-extra`` suite (opt-in, not per-commit).
12
+
13
+ Usage:
14
+ python3 -m unittest test_page_major_qwen_hybrid
15
+ """
16
+
17
+ import unittest
18
+ from types import SimpleNamespace
19
+ from urllib.parse import urlparse
20
+
21
+ from sglang.test.ci.ci_register import register_cuda_ci
22
+ from sglang.test.server_fixtures.default_fixture import DefaultServerBase
23
+ from sglang.test.test_utils import DEFAULT_HYBRID_GDN_SMALL_MODEL_NAME_FOR_TEST
24
+
25
+ register_cuda_ci(est_time=300, stage="extra-a", runner_config="1-gpu-large")
26
+
27
+
28
+ class TestPageMajorQwenHybrid(DefaultServerBase):
29
+ """Page-major KV layout on Qwen3.5-4B (GDN-hybrid), Triton backends."""
30
+
31
+ model = DEFAULT_HYBRID_GDN_SMALL_MODEL_NAME_FOR_TEST
32
+
33
+ # Measured in this harness: baseline (no page-major) and page-major both
34
+ # ~0.86; the 0.80 threshold leaves margin for run-to-run noise while still
35
+ # catching the prefill-state corruption that page-major hit before the
36
+ # gather/scatter fix in gdn_backend.forward_extend (which dropped it to ~0.61).
37
+ gsm8k_threshold = 0.80
38
+ num_gsm8k_questions = 200
39
+ num_shots = 5
40
+ parallel = 32
41
+
42
+ other_args = [
43
+ "--trust-remote-code",
44
+ "--mem-fraction-static",
45
+ "0.85",
46
+ "--enable-page-major-kv-layout",
47
+ # Only the Triton attention / linear-attn / Mamba kernels read the
48
+ # strided envelope K/V and conv/SSM state (enforced by the validator).
49
+ "--attention-backend",
50
+ "triton",
51
+ "--linear-attn-backend",
52
+ "triton",
53
+ "--mamba-backend",
54
+ "triton",
55
+ ]
56
+
57
+ def test_gsm8k(self):
58
+ from sglang.test.few_shot_gsm8k import run_eval as run_few_shot_gsm8k
59
+
60
+ url = urlparse(self.base_url)
61
+ args = SimpleNamespace(
62
+ num_shots=self.num_shots,
63
+ data_path=None,
64
+ num_questions=self.num_gsm8k_questions,
65
+ max_new_tokens=512,
66
+ parallel=self.parallel,
67
+ host=f"http://{url.hostname}",
68
+ port=int(url.port),
69
+ )
70
+ metrics = run_few_shot_gsm8k(args)
71
+ print(
72
+ f"[{self.__class__.__name__}] GSM8K accuracy: {metrics['accuracy']:.3f} "
73
+ f"(threshold: {self.gsm8k_threshold})"
74
+ )
75
+ self.assertGreaterEqual(metrics["accuracy"], self.gsm8k_threshold)
76
+
77
+
78
+ if __name__ == "__main__":
79
+ unittest.main()
asian_ai/performance/SGLang/test/registered/perf/test_bench_one_batch_2gpu.py ADDED
@@ -0,0 +1,54 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import unittest
2
+
3
+ from sglang.test.ci.ci_register import register_amd_ci, register_cuda_ci
4
+ from sglang.test.test_utils import (
5
+ DEFAULT_MODEL_NAME_FOR_TEST,
6
+ DEFAULT_MOE_MODEL_NAME_FOR_TEST,
7
+ CustomTestCase,
8
+ is_in_amd_ci,
9
+ is_in_ci,
10
+ run_bench_offline_throughput,
11
+ write_github_step_summary,
12
+ )
13
+
14
+ register_cuda_ci(est_time=209, stage="extra-a", runner_config="2-gpu-large")
15
+ register_amd_ci(est_time=630, suite="stage-b-test-2-gpu-large-amd")
16
+
17
+
18
+ class TestBenchOneBatch2GPU(CustomTestCase):
19
+
20
+ def test_moe_tp2_bs1(self):
21
+ output_throughput = run_bench_offline_throughput(
22
+ DEFAULT_MOE_MODEL_NAME_FOR_TEST,
23
+ ["--tp", "2", "--cuda-graph-max-bs-decode", "2"],
24
+ )
25
+
26
+ if is_in_ci():
27
+ write_github_step_summary(
28
+ f"### test_moe_tp2_bs1 (Mixtral-8x7B)\n"
29
+ f"output_throughput: {output_throughput:.2f} token/s\n"
30
+ )
31
+ if is_in_amd_ci():
32
+ self.assertGreater(output_throughput, 85)
33
+ else:
34
+ self.assertGreater(output_throughput, 125)
35
+
36
+ def test_torch_compile_tp2_bs1(self):
37
+ output_throughput = run_bench_offline_throughput(
38
+ DEFAULT_MODEL_NAME_FOR_TEST,
39
+ ["--tp", "2", "--enable-torch-compile", "--cuda-graph-max-bs-decode", "2"],
40
+ )
41
+
42
+ if is_in_ci():
43
+ write_github_step_summary(
44
+ f"### test_torch_compile_tp2_bs1 (Mixtral-8x7B)\n"
45
+ f"output_throughput: {output_throughput:.2f} token/s\n"
46
+ )
47
+ if is_in_amd_ci():
48
+ self.assertGreater(output_throughput, 200)
49
+ else:
50
+ self.assertGreater(output_throughput, 220)
51
+
52
+
53
+ if __name__ == "__main__":
54
+ unittest.main()
asian_ai/performance/SGLang/test/registered/perf/test_bench_serving_1gpu_large.py ADDED
@@ -0,0 +1,84 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Performance tests for single GPU that need H200 (80GB) - FP8 and EAGLE tests.
3
+ """
4
+
5
+ import unittest
6
+
7
+ from sglang.srt.utils import is_hip
8
+ from sglang.test.ci.ci_register import register_amd_ci, register_cuda_ci
9
+ from sglang.test.test_utils import (
10
+ DEFAULT_DRAFT_MODEL_EAGLE,
11
+ DEFAULT_MODEL_NAME_FOR_TEST_FP8,
12
+ DEFAULT_TARGET_MODEL_EAGLE,
13
+ CustomTestCase,
14
+ is_in_amd_ci,
15
+ is_in_ci,
16
+ run_bench_serving,
17
+ write_github_step_summary,
18
+ )
19
+
20
+ register_cuda_ci(est_time=286, stage="extra-a", runner_config="1-gpu-large")
21
+ register_amd_ci(est_time=300, suite="stage-b-test-1-gpu-large-amd")
22
+
23
+
24
+ class TestBenchServing1GPULarge(CustomTestCase):
25
+ def test_offline_throughput_default_fp8(self):
26
+ res = run_bench_serving(
27
+ model=DEFAULT_MODEL_NAME_FOR_TEST_FP8,
28
+ num_prompts=500,
29
+ request_rate=float("inf"),
30
+ other_server_args=[],
31
+ )
32
+
33
+ if is_in_ci():
34
+ write_github_step_summary(
35
+ f"### test_offline_throughput_default_fp8\n"
36
+ f"Output throughput: {res['output_throughput']:.2f} token/s\n"
37
+ )
38
+ if is_in_amd_ci():
39
+ self.assertGreater(res["output_throughput"], 3500)
40
+ else:
41
+ self.assertGreater(res["output_throughput"], 4300)
42
+
43
+ @unittest.skipIf(is_hip(), "Skip Eagle test for ROCm")
44
+ def test_online_latency_eagle(self):
45
+ res = run_bench_serving(
46
+ model=DEFAULT_TARGET_MODEL_EAGLE,
47
+ num_prompts=300,
48
+ request_rate=8,
49
+ sharegpt_context_len=3072,
50
+ disable_ignore_eos=True,
51
+ dataset_name="sharegpt",
52
+ other_server_args=[
53
+ "--speculative-algorithm",
54
+ "EAGLE",
55
+ "--speculative-draft-model-path",
56
+ DEFAULT_DRAFT_MODEL_EAGLE,
57
+ "--speculative-num-steps",
58
+ "5",
59
+ "--speculative-eagle-topk",
60
+ "4",
61
+ "--speculative-num-draft-tokens",
62
+ "16",
63
+ "--mem-fraction-static",
64
+ "0.7",
65
+ ],
66
+ need_warmup=True,
67
+ seed=42,
68
+ )
69
+
70
+ if is_in_ci():
71
+ write_github_step_summary(
72
+ f"### test_online_latency_eagle\n"
73
+ f"median_e2e_latency_ms: {res['median_e2e_latency_ms']:.2f} ms\n"
74
+ f"accept_length: {res['accept_length']:.2f} \n"
75
+ )
76
+ if is_in_amd_ci():
77
+ self.assertLess(res["median_e2e_latency_ms"], 1800)
78
+ else:
79
+ self.assertLess(res["median_e2e_latency_ms"], 900)
80
+ self.assertGreater(res["accept_length"], 3.0)
81
+
82
+
83
+ if __name__ == "__main__":
84
+ unittest.main()
asian_ai/performance/SGLang/test/registered/perf/test_bench_serving_1gpu_part1.py ADDED
@@ -0,0 +1,261 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Performance tests for single GPU - LLM throughput/latency and LoRA tests.
3
+ Works on 5090 (32GB).
4
+ """
5
+
6
+ import asyncio
7
+ import itertools
8
+ import unittest
9
+
10
+ import requests
11
+
12
+ from sglang.test.ci.ci_register import register_amd_ci, register_cuda_ci
13
+ from sglang.test.test_utils import (
14
+ DEFAULT_MODEL_NAME_FOR_TEST,
15
+ CustomTestCase,
16
+ is_in_amd_ci,
17
+ is_in_ci,
18
+ run_bench_serving,
19
+ write_github_step_summary,
20
+ )
21
+
22
+ register_cuda_ci(est_time=1210, stage="extra-a", runner_config="1-gpu-large")
23
+ register_amd_ci(est_time=1100, suite="stage-b-test-1-gpu-large-amd")
24
+
25
+
26
+ class TestBenchServing1GPUPart1(CustomTestCase):
27
+ def test_offline_throughput_default(self):
28
+ res = run_bench_serving(
29
+ model=DEFAULT_MODEL_NAME_FOR_TEST,
30
+ num_prompts=500,
31
+ request_rate=float("inf"),
32
+ other_server_args=[],
33
+ )
34
+
35
+ if is_in_ci():
36
+ write_github_step_summary(
37
+ f"### test_offline_throughput_default\n"
38
+ f"Output throughput: {res['output_throughput']:.2f} token/s\n"
39
+ )
40
+ if is_in_amd_ci():
41
+ self.assertGreater(res["output_throughput"], 3050)
42
+ else:
43
+ self.assertGreater(res["output_throughput"], 3800)
44
+
45
+ def test_offline_throughput_non_stream_small_batch_size(self):
46
+ res = run_bench_serving(
47
+ model=DEFAULT_MODEL_NAME_FOR_TEST,
48
+ num_prompts=200,
49
+ request_rate=float("inf"),
50
+ other_server_args=["--max-running-requests", "10"],
51
+ dataset_name="sharegpt",
52
+ random_input_len=None,
53
+ random_output_len=None,
54
+ disable_stream=True,
55
+ need_warmup=True,
56
+ )
57
+
58
+ if is_in_ci():
59
+ write_github_step_summary(
60
+ f"### test_offline_throughput_non_stream_small_batch_size\n"
61
+ f"Output throughput: {res['output_throughput']:.2f} token/s\n"
62
+ )
63
+ if is_in_amd_ci():
64
+ self.assertGreater(res["output_throughput"], 1000)
65
+ else:
66
+ self.assertGreater(res["output_throughput"], 1050)
67
+
68
+ def test_offline_throughput_without_radix_cache(self):
69
+ res = run_bench_serving(
70
+ model=DEFAULT_MODEL_NAME_FOR_TEST,
71
+ num_prompts=500,
72
+ request_rate=float("inf"),
73
+ other_server_args=["--disable-radix-cache"],
74
+ )
75
+
76
+ if is_in_ci():
77
+ write_github_step_summary(
78
+ f"### test_offline_throughput_without_radix_cache\n"
79
+ f"Output throughput: {res['output_throughput']:.2f} token/s\n"
80
+ )
81
+ if is_in_amd_ci():
82
+ self.assertGreater(res["output_throughput"], 3050)
83
+ else:
84
+ self.assertGreater(res["output_throughput"], 3800)
85
+
86
+ def test_offline_throughput_without_chunked_prefill(self):
87
+ res = run_bench_serving(
88
+ model=DEFAULT_MODEL_NAME_FOR_TEST,
89
+ num_prompts=500,
90
+ request_rate=float("inf"),
91
+ other_server_args=["--chunked-prefill-size", "-1"],
92
+ )
93
+
94
+ if is_in_ci():
95
+ write_github_step_summary(
96
+ f"### test_offline_throughput_without_chunked_prefill\n"
97
+ f"Output throughput: {res['output_throughput']:.2f} token/s\n"
98
+ )
99
+ self.assertGreater(res["output_throughput"], 2600)
100
+
101
+ def test_offline_throughput_with_triton_attention_backend(self):
102
+ res = run_bench_serving(
103
+ model=DEFAULT_MODEL_NAME_FOR_TEST,
104
+ num_prompts=500,
105
+ request_rate=float("inf"),
106
+ other_server_args=[
107
+ "--attention-backend",
108
+ "triton",
109
+ "--context-length",
110
+ "8192",
111
+ ],
112
+ )
113
+
114
+ if is_in_ci():
115
+ write_github_step_summary(
116
+ f"### test_offline_throughput_with_triton_attention_backend\n"
117
+ f"Output throughput: {res['output_throughput']:.2f} token/s\n"
118
+ )
119
+ if is_in_amd_ci():
120
+ self.assertGreater(res["output_throughput"], 3500)
121
+ else:
122
+ self.assertGreater(res["output_throughput"], 3700)
123
+
124
+ def test_online_latency_default(self):
125
+ res = run_bench_serving(
126
+ model=DEFAULT_MODEL_NAME_FOR_TEST,
127
+ num_prompts=100,
128
+ request_rate=1,
129
+ other_server_args=[],
130
+ )
131
+
132
+ if is_in_ci():
133
+ write_github_step_summary(
134
+ f"### test_online_latency_default\n"
135
+ f"median_e2e_latency_ms: {res['median_e2e_latency_ms']:.2f} ms\n"
136
+ )
137
+ self.assertLess(res["median_e2e_latency_ms"], 11000)
138
+ if is_in_amd_ci():
139
+ self.assertLess(res["median_ttft_ms"], 115)
140
+ else:
141
+ self.assertLess(res["median_ttft_ms"], 86)
142
+ self.assertLess(res["median_itl_ms"], 10)
143
+
144
+ def test_online_lora_latency(self):
145
+ res = self._run_lora_latency_test(enable_background_task=False)
146
+
147
+ if is_in_ci():
148
+ write_github_step_summary(
149
+ f"### test_online_lora_latency\n"
150
+ f"median_e2e_latency_ms: {res['median_e2e_latency_ms']:.2f} ms\n"
151
+ f"median_ttft_ms: {res['median_ttft_ms']:.2f} ms\n"
152
+ )
153
+ self.assertLess(res["median_e2e_latency_ms"], 2400)
154
+ # relax for mi300x (LoRA TTFT ~2x slower than mi325)
155
+ if is_in_amd_ci():
156
+ self.assertLess(res["median_ttft_ms"], 100)
157
+ else:
158
+ self.assertLess(res["median_ttft_ms"], 58)
159
+
160
+ def test_online_lora_latency_with_concurrent_adapter_updates(self):
161
+ res = self._run_lora_latency_test(enable_background_task=True)
162
+
163
+ if is_in_ci():
164
+ write_github_step_summary(
165
+ f"### test_online_lora_latency_with_concurrent_adapter_updates\n"
166
+ f"median_e2e_latency_ms: {res['median_e2e_latency_ms']:.2f} ms\n"
167
+ f"median_ttft_ms: {res['median_ttft_ms']:.2f} ms\n"
168
+ )
169
+ self.assertLess(res["median_e2e_latency_ms"], 4000)
170
+ # relax for mi300x (LoRA TTFT ~2x slower than mi325)
171
+ if is_in_amd_ci():
172
+ self.assertLess(res["median_ttft_ms"], 130)
173
+ else:
174
+ self.assertLess(res["median_ttft_ms"], 80)
175
+
176
+ def _run_lora_latency_test(self, enable_background_task: bool):
177
+ """
178
+ Run a latency test for LoRA with the specified background task setting.
179
+ """
180
+
181
+ async def lora_loader_unloader_task(
182
+ base_url: str,
183
+ start_event: asyncio.Event,
184
+ stop_event: asyncio.Event,
185
+ ):
186
+ """
187
+ A background task that repeatedly loads and unloads a LoRA adapter.
188
+ """
189
+ await start_event.wait()
190
+
191
+ path_cycler = itertools.cycle(
192
+ [
193
+ "pbevan11/llama-3.1-8b-ocr-correction",
194
+ "faridlazuarda/valadapt-llama-3.1-8B-it-chinese",
195
+ "philschmid/code-llama-3-1-8b-text-to-sql-lora",
196
+ ]
197
+ )
198
+ load_url = f"{base_url}/load_lora_adapter"
199
+ unload_url = f"{base_url}/unload_lora_adapter"
200
+ num_updates = 0
201
+
202
+ while not stop_event.is_set():
203
+ lora_path = next(path_cycler)
204
+ response = await asyncio.to_thread(
205
+ requests.post,
206
+ load_url,
207
+ json={"lora_name": lora_path, "lora_path": lora_path},
208
+ )
209
+ self.assertTrue(
210
+ response.ok, f"Failed to load LoRA adapter: {response.text}"
211
+ )
212
+ num_updates += 1
213
+
214
+ if stop_event.is_set():
215
+ break
216
+
217
+ await asyncio.sleep(1)
218
+
219
+ response = await asyncio.to_thread(
220
+ requests.post,
221
+ unload_url,
222
+ json={"lora_name": lora_path},
223
+ )
224
+ self.assertTrue(
225
+ response.ok, f"Failed to unload LoRA adapter: {response.text}"
226
+ )
227
+ num_updates += 1
228
+
229
+ await asyncio.sleep(1)
230
+
231
+ background_task = lora_loader_unloader_task if enable_background_task else None
232
+ res = run_bench_serving(
233
+ model=DEFAULT_MODEL_NAME_FOR_TEST,
234
+ num_prompts=400,
235
+ request_rate=8,
236
+ other_server_args=[
237
+ "--enable-lora",
238
+ "--max-loras-per-batch",
239
+ "1",
240
+ "--disable-radix-cache",
241
+ "--random-seed",
242
+ "42",
243
+ "--mem-fraction-static",
244
+ "0.8",
245
+ "--lora-paths",
246
+ "nvidia/llama-3.1-nemoguard-8b-topic-control",
247
+ "--max-lora-rank",
248
+ "256",
249
+ ],
250
+ dataset_name="random",
251
+ random_input_len=256,
252
+ random_output_len=256,
253
+ lora_name=["nvidia/llama-3.1-nemoguard-8b-topic-control"],
254
+ background_task=background_task,
255
+ )
256
+
257
+ return res
258
+
259
+
260
+ if __name__ == "__main__":
261
+ unittest.main()
asian_ai/performance/SGLang/test/registered/perf/test_bench_serving_1gpu_part2.py ADDED
@@ -0,0 +1,202 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Performance tests for single GPU - VLM, Score API, and Embeddings API tests.
3
+ Works on 5090 (32GB).
4
+ """
5
+
6
+ import unittest
7
+
8
+ from sglang.test.ci.ci_register import register_amd_ci, register_cuda_ci
9
+ from sglang.test.test_utils import (
10
+ DEFAULT_SMALL_EMBEDDING_MODEL_NAME_FOR_TEST,
11
+ DEFAULT_SMALL_MODEL_NAME_FOR_TEST_SCORE,
12
+ DEFAULT_SMALL_VLM_MODEL_NAME_FOR_TEST,
13
+ CustomTestCase,
14
+ is_in_amd_ci,
15
+ is_in_ci,
16
+ run_bench_serving,
17
+ run_embeddings_benchmark,
18
+ run_score_benchmark,
19
+ write_github_step_summary,
20
+ )
21
+
22
+ register_cuda_ci(est_time=968, stage="extra-a", runner_config="1-gpu-large")
23
+ register_amd_ci(est_time=900, suite="stage-b-test-1-gpu-large-amd")
24
+
25
+
26
+ class TestBenchServing1GPUPart2(CustomTestCase):
27
+ def test_vlm_offline_throughput(self):
28
+ res = run_bench_serving(
29
+ model=DEFAULT_SMALL_VLM_MODEL_NAME_FOR_TEST,
30
+ num_prompts=200,
31
+ request_rate=float("inf"),
32
+ other_server_args=[
33
+ "--mem-fraction-static",
34
+ "0.7",
35
+ ],
36
+ dataset_name="mmmu",
37
+ )
38
+
39
+ if is_in_ci():
40
+ write_github_step_summary(
41
+ f"### test_vlm_offline_throughput\n"
42
+ f"Output throughput: {res['output_throughput']:.2f} token/s\n"
43
+ )
44
+ # relax for mi300x
45
+ if is_in_amd_ci():
46
+ self.assertGreater(res["output_throughput"], 900)
47
+ else:
48
+ self.assertGreater(res["output_throughput"], 2500)
49
+
50
+ def test_vlm_online_latency(self):
51
+ res = run_bench_serving(
52
+ model=DEFAULT_SMALL_VLM_MODEL_NAME_FOR_TEST,
53
+ num_prompts=250,
54
+ request_rate=1,
55
+ other_server_args=[
56
+ "--mem-fraction-static",
57
+ "0.7",
58
+ ],
59
+ dataset_name="mmmu",
60
+ )
61
+
62
+ if is_in_ci():
63
+ write_github_step_summary(
64
+ f"### test_vlm_online_latency\n"
65
+ f"median_e2e_latency_ms: {res['median_e2e_latency_ms']:.2f} ms\n"
66
+ )
67
+ self.assertLess(res["median_e2e_latency_ms"], 16500)
68
+ if is_in_amd_ci():
69
+ self.assertLess(res["median_ttft_ms"], 150)
70
+ else:
71
+ self.assertLess(res["median_ttft_ms"], 100)
72
+ self.assertLess(res["median_itl_ms"], 8)
73
+
74
+ def test_score_api_latency_throughput(self):
75
+ """Test score API latency and throughput performance"""
76
+ res = run_score_benchmark(
77
+ model=DEFAULT_SMALL_MODEL_NAME_FOR_TEST_SCORE,
78
+ num_requests=1000,
79
+ batch_size=10,
80
+ other_server_args=[],
81
+ need_warmup=True,
82
+ )
83
+
84
+ if is_in_ci():
85
+ write_github_step_summary(
86
+ f"### test_score_api_throughput\n"
87
+ f"Average latency: {res['avg_latency_ms']:.2f} ms\n"
88
+ f"P95 latency: {res['p95_latency_ms']:.2f} ms\n"
89
+ f"Score API throughput: {res['throughput']:.2f} req/s\n"
90
+ f"Successful requests: {res['successful_requests']}/{res['total_requests']}\n"
91
+ )
92
+
93
+ self.assertEqual(res["successful_requests"], res["total_requests"])
94
+ self.assertLess(res["avg_latency_ms"], 48)
95
+ self.assertLess(res["p95_latency_ms"], 50)
96
+ self.assertGreater(res["throughput"], 20)
97
+
98
+ def test_score_api_batch_scaling(self):
99
+ """Test score API performance with different batch sizes"""
100
+ batch_sizes = [10, 25, 50]
101
+
102
+ for batch_size in batch_sizes:
103
+ res = run_score_benchmark(
104
+ model=DEFAULT_SMALL_MODEL_NAME_FOR_TEST_SCORE,
105
+ num_requests=500,
106
+ batch_size=batch_size,
107
+ )
108
+
109
+ if is_in_ci():
110
+ write_github_step_summary(
111
+ f"### test_score_api_batch_scaling_size_{batch_size}\n"
112
+ f"Batch size: {batch_size}\n"
113
+ f"Average latency: {res['avg_latency_ms']:.2f} ms\n"
114
+ f"P95 latency: {res['p95_latency_ms']:.2f} ms\n"
115
+ f"Throughput: {res['throughput']:.2f} req/s\n"
116
+ f"Successful requests: {res['successful_requests']}/{res['total_requests']}\n"
117
+ )
118
+
119
+ self.assertEqual(res["successful_requests"], res["total_requests"])
120
+ # relax for mi300x
121
+ if is_in_amd_ci():
122
+ bounds = {10: (60, 65), 25: (70, 80), 50: (80, 90)}
123
+ default_bounds = (90, 90)
124
+ else:
125
+ bounds = {10: (45, 50), 25: (50, 60), 50: (60, 65)}
126
+ default_bounds = (60, 65)
127
+ avg_latency_bound, p95_latency_bound = bounds.get(
128
+ batch_size, default_bounds
129
+ )
130
+ self.assertLess(res["avg_latency_ms"], avg_latency_bound)
131
+ self.assertLess(res["p95_latency_ms"], p95_latency_bound)
132
+
133
+ def test_embeddings_api_latency_throughput(self):
134
+ """Test embeddings API latency and throughput performance"""
135
+ res = run_embeddings_benchmark(
136
+ model=DEFAULT_SMALL_EMBEDDING_MODEL_NAME_FOR_TEST,
137
+ num_requests=1000,
138
+ batch_size=1,
139
+ input_tokens=500,
140
+ other_server_args=[],
141
+ need_warmup=True,
142
+ )
143
+
144
+ if is_in_ci():
145
+ write_github_step_summary(
146
+ f"### test_embeddings_api_throughput\n"
147
+ f"Average latency: {res['avg_latency_ms']:.2f} ms\n"
148
+ f"P95 latency: {res['p95_latency_ms']:.2f} ms\n"
149
+ f"Embeddings API throughput: {res['throughput']:.2f} req/s\n"
150
+ f"Successful requests: {res['successful_requests']}/{res['total_requests']}\n"
151
+ )
152
+
153
+ self.assertEqual(res["successful_requests"], res["total_requests"])
154
+ # relax for mi300x
155
+ if is_in_amd_ci():
156
+ self.assertLess(res["avg_latency_ms"], 35)
157
+ self.assertLess(res["p95_latency_ms"], 40)
158
+ self.assertGreater(res["throughput"], 30)
159
+ else:
160
+ self.assertLess(res["avg_latency_ms"], 20)
161
+ self.assertLess(res["p95_latency_ms"], 25)
162
+ self.assertGreater(res["throughput"], 60)
163
+
164
+ def test_embeddings_api_batch_scaling(self):
165
+ """Test embeddings API performance with different batch sizes"""
166
+ batch_sizes = [10, 25, 50]
167
+
168
+ for batch_size in batch_sizes:
169
+ res = run_embeddings_benchmark(
170
+ model=DEFAULT_SMALL_EMBEDDING_MODEL_NAME_FOR_TEST,
171
+ num_requests=500,
172
+ batch_size=batch_size,
173
+ input_tokens=500,
174
+ )
175
+
176
+ if is_in_ci():
177
+ write_github_step_summary(
178
+ f"### test_embeddings_api_batch_scaling_size_{batch_size}\n"
179
+ f"Batch size: {batch_size}\n"
180
+ f"Average latency: {res['avg_latency_ms']:.2f} ms\n"
181
+ f"P95 latency: {res['p95_latency_ms']:.2f} ms\n"
182
+ f"Throughput: {res['throughput']:.2f} req/s\n"
183
+ f"Successful requests: {res['successful_requests']}/{res['total_requests']}\n"
184
+ )
185
+
186
+ self.assertEqual(res["successful_requests"], res["total_requests"])
187
+ # relax for mi300x
188
+ if is_in_amd_ci():
189
+ bounds = {10: (80, 90), 25: (140, 150), 50: (230, 240)}
190
+ default_bounds = (300, 300)
191
+ else:
192
+ bounds = {10: (60, 65), 25: (115, 120), 50: (190, 195)}
193
+ default_bounds = (250, 250)
194
+ avg_latency_bound, p95_latency_bound = bounds.get(
195
+ batch_size, default_bounds
196
+ )
197
+ self.assertLess(res["avg_latency_ms"], avg_latency_bound)
198
+ self.assertLess(res["p95_latency_ms"], p95_latency_bound)
199
+
200
+
201
+ if __name__ == "__main__":
202
+ unittest.main()
asian_ai/performance/SGLang/test/registered/perf/test_bench_serving_2gpu.py ADDED
@@ -0,0 +1,108 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Performance tests for 2-GPU that need large GPUs (H200 80GB) - MoE and Pipeline Parallel tests.
3
+ """
4
+
5
+ import unittest
6
+
7
+ from sglang.test.ci.ci_register import register_amd_ci, register_cuda_ci
8
+ from sglang.test.test_utils import (
9
+ DEFAULT_MOE_MODEL_NAME_FOR_TEST,
10
+ CustomTestCase,
11
+ is_in_amd_ci,
12
+ is_in_ci,
13
+ run_bench_serving,
14
+ write_github_step_summary,
15
+ )
16
+
17
+ register_cuda_ci(est_time=721, stage="extra-a", runner_config="2-gpu-large")
18
+ register_amd_ci(est_time=1450, suite="stage-b-test-2-gpu-large-amd")
19
+
20
+
21
+ class TestBenchServing2GPU(CustomTestCase):
22
+ def test_moe_offline_throughput_default(self):
23
+ res = run_bench_serving(
24
+ model=DEFAULT_MOE_MODEL_NAME_FOR_TEST,
25
+ num_prompts=300,
26
+ request_rate=float("inf"),
27
+ other_server_args=["--tp", "2"],
28
+ )
29
+
30
+ if is_in_ci():
31
+ write_github_step_summary(
32
+ f"### test_moe_offline_throughput_default\n"
33
+ f"Output throughput: {res['output_throughput']:.2f} token/s\n"
34
+ )
35
+ if is_in_amd_ci():
36
+ self.assertGreater(res["output_throughput"], 2100)
37
+ else:
38
+ self.assertGreater(res["output_throughput"], 2200)
39
+
40
+ def test_moe_offline_throughput_without_radix_cache(self):
41
+ res = run_bench_serving(
42
+ model=DEFAULT_MOE_MODEL_NAME_FOR_TEST,
43
+ num_prompts=300,
44
+ request_rate=float("inf"),
45
+ other_server_args=["--tp", "2", "--disable-radix-cache"],
46
+ )
47
+
48
+ if is_in_ci():
49
+ write_github_step_summary(
50
+ f"### test_moe_offline_throughput_without_radix_cache\n"
51
+ f"Output throughput: {res['output_throughput']:.2f} token/s\n"
52
+ )
53
+ if is_in_amd_ci():
54
+ self.assertGreater(res["output_throughput"], 2100)
55
+ else:
56
+ self.assertGreater(res["output_throughput"], 2200)
57
+
58
+ def test_pp_offline_throughput_default_decode(self):
59
+ res = run_bench_serving(
60
+ model=DEFAULT_MOE_MODEL_NAME_FOR_TEST,
61
+ num_prompts=1000,
62
+ request_rate=float("inf"),
63
+ random_input_len=1,
64
+ random_output_len=1024,
65
+ other_server_args=["--pp-size", "2"],
66
+ need_warmup=True,
67
+ seed=42,
68
+ )
69
+
70
+ if is_in_ci():
71
+ write_github_step_summary(
72
+ f"### test_pp_offline_throughput_default_decode\n"
73
+ f"Output throughput: {res['output_throughput']:.2f} token/s\n"
74
+ )
75
+ self.assertGreater(res["output_throughput"], 6700)
76
+
77
+ def test_pp_long_context_prefill(self):
78
+ res = run_bench_serving(
79
+ model="meta-llama/Llama-3.3-70B-Instruct",
80
+ num_prompts=4,
81
+ request_rate=float("inf"),
82
+ random_input_len=128000,
83
+ random_output_len=1,
84
+ dataset_name="random",
85
+ other_server_args=[
86
+ "--quantization",
87
+ "fp8",
88
+ "--pp-size",
89
+ "2",
90
+ ]
91
+ + (["--mem-fraction-static", "0.7"] if is_in_amd_ci() else []),
92
+ need_warmup=False,
93
+ seed=42,
94
+ )
95
+
96
+ if is_in_ci():
97
+ write_github_step_summary(
98
+ f"### test_pp_long_context_latency_prefill\n"
99
+ f"input_throughput: {res['input_throughput']:.2f} ms\n"
100
+ )
101
+ if is_in_amd_ci():
102
+ self.assertGreater(res["input_throughput"], 3000)
103
+ else:
104
+ self.assertGreater(res["input_throughput"], 4000)
105
+
106
+
107
+ if __name__ == "__main__":
108
+ unittest.main()
asian_ai/performance/SGLang/test/registered/perf/test_dpsk_v3_fp4_4gpu_perf.py ADDED
@@ -0,0 +1,77 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import unittest
2
+
3
+ from sglang.test.accuracy_test_runner import AccuracyTestParams
4
+ from sglang.test.ci.ci_register import register_cuda_ci
5
+ from sglang.test.performance_test_runner import PerformanceTestParams
6
+ from sglang.test.run_combined_tests import run_combined_tests
7
+ from sglang.test.test_utils import ModelLaunchSettings
8
+
9
+ # Runs on B200 via nightly-4-gpu-b200 suite
10
+ register_cuda_ci(est_time=2000, suite="nightly-4-gpu-b200", nightly=True)
11
+
12
+ FULL_DEEPSEEK_V3_FP4_MODEL_PATH = "nvidia/DeepSeek-V3-0324-FP4"
13
+
14
+
15
+ class TestDeepseekR1FP4Unified(unittest.TestCase):
16
+ """Unified test class for DeepSeek-V3-0324-FP4 performance and accuracy.
17
+
18
+ Two variants:
19
+ - basic: Standard TP=4
20
+ - mtp: TP=4 + EAGLE speculative decoding
21
+
22
+ Each variant runs BOTH:
23
+ - Performance test (using NightlyBenchmarkRunner)
24
+ - Accuracy test (using run_eval with mgsm_en)
25
+ """
26
+
27
+ def test_deepseek_r1_fp4_all_variants(self):
28
+ """Run performance and accuracy for all DeepSeek-R1-0528-NVFP4-v2 variants."""
29
+ # Define base arguments shared by most variants
30
+ base_args = [
31
+ "--tp=4",
32
+ "--trust-remote-code",
33
+ "--model-loader-extra-config",
34
+ '{"enable_multithread_load": true}',
35
+ ]
36
+ mtp_args = [
37
+ "--speculative-algorithm=EAGLE",
38
+ "--speculative-num-steps=3",
39
+ "--speculative-eagle-topk=1",
40
+ "--speculative-num-draft-tokens=4",
41
+ "--mem-frac=0.7",
42
+ ]
43
+
44
+ variants = [
45
+ # Variant: "basic" - Standard TP=4
46
+ ModelLaunchSettings(
47
+ FULL_DEEPSEEK_V3_FP4_MODEL_PATH,
48
+ tp_size=4,
49
+ extra_args=base_args,
50
+ variant="TP4",
51
+ ),
52
+ # Variant: "mtp" - TP=4 + EAGLE speculative decoding
53
+ ModelLaunchSettings(
54
+ FULL_DEEPSEEK_V3_FP4_MODEL_PATH,
55
+ tp_size=4,
56
+ extra_args=base_args + mtp_args,
57
+ variant="TP4+MTP",
58
+ ),
59
+ ]
60
+
61
+ run_combined_tests(
62
+ models=variants,
63
+ test_name="DeepSeek-V3-0324-FP4 Unified",
64
+ accuracy_params=AccuracyTestParams(
65
+ dataset="gsm8k",
66
+ baseline_accuracy=0.935,
67
+ num_examples=200,
68
+ api="completion",
69
+ ),
70
+ performance_params=PerformanceTestParams(
71
+ profile_dir="performance_profiles_deepseek_v3_fp4",
72
+ ),
73
+ )
74
+
75
+
76
+ if __name__ == "__main__":
77
+ unittest.main()
asian_ai/performance/SGLang/test/registered/perf/test_gpt_oss_4gpu_perf.py ADDED
@@ -0,0 +1,60 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import unittest
2
+
3
+ from sglang.test.ci.ci_register import register_cuda_ci
4
+ from sglang.test.nightly_utils import NightlyBenchmarkRunner
5
+ from sglang.test.test_utils import DEFAULT_URL_FOR_TEST
6
+
7
+ register_cuda_ci(est_time=600, suite="nightly-4-gpu-b200", nightly=True)
8
+
9
+ PROFILE_DIR = "performance_profiles_gpt_oss_4gpu"
10
+
11
+
12
+ class TestNightlyGptOss4GpuPerformance(unittest.TestCase):
13
+ @classmethod
14
+ def setUpClass(cls):
15
+ cls.models = [
16
+ (
17
+ "openai/gpt-oss-120b",
18
+ [
19
+ "--tp",
20
+ "4",
21
+ "--cuda-graph-max-bs-decode",
22
+ "200",
23
+ "--mem-fraction-static",
24
+ "0.93",
25
+ ],
26
+ ),
27
+ ]
28
+ cls.base_url = DEFAULT_URL_FOR_TEST
29
+ cls.batch_sizes = [1, 1, 8, 16, 64]
30
+ cls.input_lens = (4096,)
31
+ cls.output_lens = (512,)
32
+ cls.runner = NightlyBenchmarkRunner(PROFILE_DIR, cls.__name__, cls.base_url)
33
+ cls.runner.setup_profile_directory()
34
+
35
+ def test_bench_one_batch(self):
36
+ all_model_succeed = True
37
+
38
+ for model_path, other_args in self.models:
39
+ with self.subTest(model=model_path):
40
+ results, success, _ = self.runner.run_benchmark_for_model(
41
+ model_path=model_path,
42
+ batch_sizes=self.batch_sizes,
43
+ input_lens=self.input_lens,
44
+ output_lens=self.output_lens,
45
+ other_args=other_args,
46
+ )
47
+
48
+ if not success:
49
+ all_model_succeed = False
50
+
51
+ self.runner.add_report(results)
52
+
53
+ self.runner.write_final_report()
54
+
55
+ if not all_model_succeed:
56
+ raise AssertionError("Some models failed the perf tests.")
57
+
58
+
59
+ if __name__ == "__main__":
60
+ unittest.main()
asian_ai/performance/SGLang/test/registered/perf/test_text_models_perf.py ADDED
@@ -0,0 +1,62 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import unittest
2
+
3
+ from sglang.test.ci.ci_register import register_cuda_ci
4
+ from sglang.test.nightly_utils import NightlyBenchmarkRunner
5
+ from sglang.test.test_utils import (
6
+ DEFAULT_URL_FOR_TEST,
7
+ ModelLaunchSettings,
8
+ _parse_int_list_env,
9
+ parse_models,
10
+ )
11
+
12
+ register_cuda_ci(est_time=3600, suite="nightly-perf-text-2-gpu", nightly=True)
13
+
14
+ PROFILE_DIR = "performance_profiles_text_models"
15
+
16
+
17
+ class TestNightlyTextModelsPerformance(unittest.TestCase):
18
+ @classmethod
19
+ def setUpClass(cls):
20
+ cls.models = []
21
+ # TODO: replace with DEFAULT_MODEL_NAME_FOR_NIGHTLY_EVAL_TP1 or other model lists
22
+ for model_path in parse_models("meta-llama/Llama-3.1-8B-Instruct"):
23
+ cls.models.append(ModelLaunchSettings(model_path, tp_size=1))
24
+ for model_path in parse_models("Qwen/Qwen2-57B-A14B-Instruct"):
25
+ cls.models.append(ModelLaunchSettings(model_path, tp_size=2))
26
+ # (parse_models(DEFAULT_MODEL_NAME_FOR_NIGHTLY_EVAL_TP1), False, False),
27
+ # (parse_models(DEFAULT_MODEL_NAME_FOR_NIGHTLY_EVAL_TP2), False, True),
28
+ # (parse_models(DEFAULT_MODEL_NAME_FOR_NIGHTLY_EVAL_FP8_TP1), True, False),
29
+ # (parse_models(DEFAULT_MODEL_NAME_FOR_NIGHTLY_EVAL_FP8_TP2), True, True),
30
+ cls.base_url = DEFAULT_URL_FOR_TEST
31
+ cls.batch_sizes = [1, 1, 8, 16, 64]
32
+ cls.input_lens = tuple(_parse_int_list_env("NIGHTLY_INPUT_LENS", "4096"))
33
+ cls.output_lens = tuple(_parse_int_list_env("NIGHTLY_OUTPUT_LENS", "512"))
34
+ cls.runner = NightlyBenchmarkRunner(PROFILE_DIR, cls.__name__, cls.base_url)
35
+ cls.runner.setup_profile_directory()
36
+
37
+ def test_bench_one_batch(self):
38
+ all_model_succeed = True
39
+
40
+ for model_setup in self.models:
41
+ with self.subTest(model=model_setup.model_path):
42
+ results, success, _ = self.runner.run_benchmark_for_model(
43
+ model_path=model_setup.model_path,
44
+ batch_sizes=self.batch_sizes,
45
+ input_lens=self.input_lens,
46
+ output_lens=self.output_lens,
47
+ other_args=model_setup.extra_args,
48
+ )
49
+
50
+ if not success:
51
+ all_model_succeed = False
52
+
53
+ self.runner.add_report(results)
54
+
55
+ self.runner.write_final_report()
56
+
57
+ if not all_model_succeed:
58
+ raise AssertionError("Some models failed the perf tests.")
59
+
60
+
61
+ if __name__ == "__main__":
62
+ unittest.main()
asian_ai/performance/SGLang/test/registered/perf/test_vlm_perf_5090.py ADDED
@@ -0,0 +1,63 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ VLM Performance tests that work on 5090 (32GB) - VLM offline throughput and online latency tests.
3
+ """
4
+
5
+ import unittest
6
+
7
+ from sglang.test.ci.ci_register import register_amd_ci, register_cuda_ci
8
+ from sglang.test.test_utils import (
9
+ DEFAULT_SMALL_VLM_MODEL_NAME_FOR_TEST,
10
+ CustomTestCase,
11
+ is_in_ci,
12
+ run_bench_serving,
13
+ write_github_step_summary,
14
+ )
15
+
16
+ register_cuda_ci(est_time=406, stage="base-b", runner_config="1-gpu-small")
17
+ register_amd_ci(est_time=500, suite="stage-b-test-1-gpu-small-amd")
18
+
19
+
20
+ class TestVLMPerf5090(CustomTestCase):
21
+ def test_vlm_offline_throughput(self):
22
+ res = run_bench_serving(
23
+ model=DEFAULT_SMALL_VLM_MODEL_NAME_FOR_TEST,
24
+ num_prompts=200,
25
+ request_rate=float("inf"),
26
+ other_server_args=[
27
+ "--mem-fraction-static",
28
+ "0.7",
29
+ ],
30
+ dataset_name="mmmu",
31
+ )
32
+
33
+ if is_in_ci():
34
+ write_github_step_summary(
35
+ f"### test_vlm_offline_throughput (5090)\n"
36
+ f"Output throughput: {res['output_throughput']:.2f} token/s\n"
37
+ )
38
+ self.assertGreater(res["output_throughput"], 2000)
39
+
40
+ def test_vlm_online_latency(self):
41
+ res = run_bench_serving(
42
+ model=DEFAULT_SMALL_VLM_MODEL_NAME_FOR_TEST,
43
+ num_prompts=250,
44
+ request_rate=1,
45
+ other_server_args=[
46
+ "--mem-fraction-static",
47
+ "0.7",
48
+ ],
49
+ dataset_name="mmmu",
50
+ )
51
+
52
+ if is_in_ci():
53
+ write_github_step_summary(
54
+ f"### test_vlm_online_latency (5090)\n"
55
+ f"median_e2e_latency_ms: {res['median_e2e_latency_ms']:.2f} ms\n"
56
+ )
57
+ self.assertLess(res["median_e2e_latency_ms"], 16500)
58
+ self.assertLess(res["median_ttft_ms"], 150)
59
+ self.assertLess(res["median_itl_ms"], 8)
60
+
61
+
62
+ if __name__ == "__main__":
63
+ unittest.main()
asian_ai/performance/SGLang/test/registered/perf/test_vlms_perf.py ADDED
@@ -0,0 +1,90 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import unittest
3
+ import warnings
4
+
5
+ from sglang.test.ci.ci_register import register_cuda_ci
6
+ from sglang.test.nightly_utils import NightlyBenchmarkRunner
7
+ from sglang.test.test_utils import (
8
+ DEFAULT_URL_FOR_TEST,
9
+ ModelLaunchSettings,
10
+ _parse_int_list_env,
11
+ parse_models,
12
+ )
13
+
14
+ register_cuda_ci(est_time=7200, suite="nightly-perf-vlm-2-gpu", nightly=True)
15
+
16
+ PROFILE_DIR = "performance_profiles_vlms"
17
+
18
+ MODEL_DEFAULTS = [
19
+ # Keep conservative defaults. Can be overridden by env NIGHTLY_VLM_MODELS
20
+ ModelLaunchSettings(
21
+ "Qwen/Qwen2.5-VL-7B-Instruct",
22
+ extra_args=["--mem-fraction-static=0.7"],
23
+ ),
24
+ ModelLaunchSettings(
25
+ "google/gemma-3-27b-it",
26
+ ),
27
+ ModelLaunchSettings("Qwen/Qwen3-VL-30B-A3B-Instruct", extra_args=["--tp=2"]),
28
+ # "OpenGVLab/InternVL2_5-2B",
29
+ # buggy in official transformers impl
30
+ # "openbmb/MiniCPM-V-2_6",
31
+ ]
32
+
33
+
34
+ class TestNightlyVLMModelsPerformance(unittest.TestCase):
35
+ @classmethod
36
+ def setUpClass(cls):
37
+ warnings.filterwarnings(
38
+ "ignore", category=ResourceWarning, message="unclosed.*socket"
39
+ )
40
+
41
+ nightly_vlm_models_str = os.environ.get("NIGHTLY_VLM_MODELS")
42
+ if nightly_vlm_models_str:
43
+ cls.models = []
44
+ model_paths = parse_models(nightly_vlm_models_str)
45
+ for model_path in model_paths:
46
+ cls.models.append(ModelLaunchSettings(model_path))
47
+ else:
48
+ cls.models = MODEL_DEFAULTS
49
+
50
+ cls.base_url = DEFAULT_URL_FOR_TEST
51
+
52
+ cls.batch_sizes = _parse_int_list_env("NIGHTLY_VLM_BATCH_SIZES", "1,1,2,8,16")
53
+ cls.input_lens = tuple(_parse_int_list_env("NIGHTLY_VLM_INPUT_LENS", "4096"))
54
+ cls.output_lens = tuple(_parse_int_list_env("NIGHTLY_VLM_OUTPUT_LENS", "512"))
55
+ cls.runner = NightlyBenchmarkRunner(PROFILE_DIR, cls.__name__, cls.base_url)
56
+ cls.runner.setup_profile_directory()
57
+
58
+ def test_bench_one_batch(self):
59
+ all_model_succeed = True
60
+
61
+ for model_setup in self.models:
62
+ with self.subTest(model=model_setup.model_path):
63
+ # VLMs need additional benchmark args for dataset and trust-remote-code
64
+ extra_bench_args = [
65
+ "--trust-remote-code",
66
+ "--dataset-name=mmmu",
67
+ ]
68
+
69
+ results, success, _ = self.runner.run_benchmark_for_model(
70
+ model_path=model_setup.model_path,
71
+ batch_sizes=self.batch_sizes,
72
+ input_lens=self.input_lens,
73
+ output_lens=self.output_lens,
74
+ other_args=model_setup.extra_args,
75
+ extra_bench_args=extra_bench_args,
76
+ )
77
+
78
+ if not success:
79
+ all_model_succeed = False
80
+
81
+ self.runner.add_report(results)
82
+
83
+ self.runner.write_final_report()
84
+
85
+ if not all_model_succeed:
86
+ raise AssertionError("Some models failed the perf tests.")
87
+
88
+
89
+ if __name__ == "__main__":
90
+ unittest.main()
asian_ai/performance/SGLang/test/registered/pp/test_pp_parallel_compat.py ADDED
@@ -0,0 +1,111 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import unittest
2
+ from types import SimpleNamespace
3
+
4
+ from sglang.test.ci.ci_register import register_cuda_ci
5
+ from sglang.test.run_eval import run_eval
6
+ from sglang.test.test_utils import (
7
+ DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH,
8
+ DEFAULT_URL_FOR_TEST,
9
+ CustomTestCase,
10
+ kill_process_tree,
11
+ popen_launch_server,
12
+ )
13
+
14
+ register_cuda_ci(est_time=600, stage="extra-b", runner_config="4-gpu-h100")
15
+
16
+ QWEN3_MOE_MODEL_PATH = "Qwen/Qwen3-30B-A3B-FP8"
17
+
18
+ GSM8K_BASELINE_ACCURACY = 0.93
19
+
20
+
21
+ class _Qwen3MoePPCompatMixin:
22
+ """Launch a Qwen3 MoE server combining PP with another parallel strategy and
23
+ check GSM8K accuracy. Concrete subclasses set ``parallel_args`` (and
24
+ optionally ``server_env``); this mixin is not a TestCase so it is never
25
+ collected on its own.
26
+ """
27
+
28
+ model = QWEN3_MOE_MODEL_PATH
29
+ parallel_args: list = []
30
+ server_env = None
31
+
32
+ @classmethod
33
+ def setUpClass(cls):
34
+ cls.base_url = DEFAULT_URL_FOR_TEST
35
+ cls.process = popen_launch_server(
36
+ cls.model,
37
+ cls.base_url,
38
+ timeout=DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH,
39
+ other_args=[
40
+ *cls.parallel_args,
41
+ "--cuda-graph-max-bs-decode",
42
+ "32",
43
+ "--max-running-requests",
44
+ "32",
45
+ "--trust-remote-code",
46
+ "--disable-piecewise-cuda-graph",
47
+ "--model-loader-extra-config",
48
+ '{"enable_multithread_load": true, "num_threads": 64}',
49
+ ],
50
+ env=cls.server_env,
51
+ )
52
+
53
+ @classmethod
54
+ def tearDownClass(cls):
55
+ if hasattr(cls, "process") and cls.process:
56
+ kill_process_tree(cls.process.pid)
57
+
58
+ def test_gsm8k(self):
59
+ args = SimpleNamespace(
60
+ model=self.model,
61
+ eval_name="gsm8k",
62
+ num_shots=5,
63
+ num_examples=200,
64
+ max_tokens=16000,
65
+ num_threads=128,
66
+ repeat=1,
67
+ temperature=0.6,
68
+ top_p=0.95,
69
+ top_k=20,
70
+ base_url=self.base_url,
71
+ )
72
+ metrics = run_eval(args)
73
+ print(f"{metrics=}")
74
+ self.assertGreaterEqual(metrics["score"], GSM8K_BASELINE_ACCURACY)
75
+
76
+
77
+ class TestQwen3MoePPxCP(_Qwen3MoePPCompatMixin, CustomTestCase):
78
+ """PP x CP: pp_size=2 x attn_cp_size=2 (tp_size=2, moe_dp_size=1)."""
79
+
80
+ parallel_args = [
81
+ "--tp-size",
82
+ "2",
83
+ "--pp-size",
84
+ "2",
85
+ "--ep-size",
86
+ "2",
87
+ "--attn-cp-size",
88
+ "2",
89
+ "--enable-prefill-cp",
90
+ "--cp-strategy",
91
+ "zigzag",
92
+ ]
93
+ server_env = {"SGLANG_ENABLE_CP_V2": "1"}
94
+
95
+
96
+ class TestQwen3MoePPxDP(_Qwen3MoePPCompatMixin, CustomTestCase):
97
+ """PP x DP: pp_size=2 x dp_size=2 attention (tp_size=2)."""
98
+
99
+ parallel_args = [
100
+ "--tp-size",
101
+ "2",
102
+ "--pp-size",
103
+ "2",
104
+ "--dp-size",
105
+ "2",
106
+ "--enable-dp-attention",
107
+ ]
108
+
109
+
110
+ if __name__ == "__main__":
111
+ unittest.main()
asian_ai/performance/SGLang/test/registered/pp/test_pp_single_node.py ADDED
@@ -0,0 +1,356 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Usage:
3
+ python3 -m unittest test_pp_single_node.TestPPAccuracy.test_gsm8k
4
+ python3 -m unittest test_pp_single_node.TestDPAttentionDP2PP2.test_gsm8k
5
+ python3 -m unittest test_pp_single_node.TestGemma4PPAccuracy.test_gsm8k
6
+ python3 -m unittest test_pp_single_node.TestGemma4PPAccuracy.test_mmmu
7
+ python3 -m unittest test_pp_single_node.TestGemma4PLEPPAccuracy.test_gsm8k
8
+ python3 -m unittest test_pp_single_node.TestPPMixedChunk.test_gsm8k
9
+ python3 -m unittest test_pp_single_node.TestFixedBugs.test_chunked_prefill_with_small_bs
10
+ """
11
+
12
+ import time
13
+ import unittest
14
+ from types import SimpleNamespace
15
+
16
+ import requests
17
+
18
+ from sglang.bench_one_batch_server import BenchArgs as OneBatchBenchArgs
19
+ from sglang.srt.server_args import ServerArgs
20
+ from sglang.srt.utils import kill_process_tree
21
+ from sglang.test.ci.ci_register import register_amd_ci, register_cuda_ci
22
+ from sglang.test.run_eval import run_eval
23
+ from sglang.test.test_utils import (
24
+ DEFAULT_MLA_MODEL_NAME_FOR_TEST,
25
+ DEFAULT_MODEL_NAME_FOR_TEST,
26
+ DEFAULT_MODEL_NAME_FOR_TEST_GEMMA4_PLE_PP,
27
+ DEFAULT_MODEL_NAME_FOR_TEST_GEMMA4_PP,
28
+ DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH,
29
+ DEFAULT_URL_FOR_TEST,
30
+ CustomTestCase,
31
+ is_in_amd_ci,
32
+ is_in_ci,
33
+ popen_launch_server,
34
+ run_bench_one_batch_server,
35
+ )
36
+
37
+ register_cuda_ci(est_time=500, stage="base-c", runner_config="4-gpu-h100")
38
+ register_amd_ci(est_time=500, suite="stage-c-test-4-gpu-amd")
39
+
40
+
41
+ class TestPPAccuracy(unittest.TestCase):
42
+ @classmethod
43
+ def setUpClass(cls):
44
+ cls.base_url = "http://127.0.0.1:23333"
45
+ cls.process = popen_launch_server(
46
+ DEFAULT_MODEL_NAME_FOR_TEST,
47
+ cls.base_url,
48
+ timeout=DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH,
49
+ other_args=[
50
+ "--tp-size",
51
+ 2,
52
+ "--pp-size",
53
+ 2,
54
+ "--chunked-prefill-size",
55
+ 256,
56
+ ],
57
+ )
58
+
59
+ @classmethod
60
+ def tearDownClass(cls):
61
+ kill_process_tree(cls.process.pid)
62
+
63
+ def test_gsm8k(self):
64
+ args = SimpleNamespace(
65
+ base_url=self.base_url,
66
+ model=DEFAULT_MODEL_NAME_FOR_TEST,
67
+ eval_name="gsm8k",
68
+ api="completion",
69
+ max_tokens=512,
70
+ num_examples=200,
71
+ num_threads=128,
72
+ )
73
+ metrics = run_eval(args)
74
+ print(f"{metrics=}")
75
+
76
+ if is_in_amd_ci():
77
+ # AMD triton backend produces slightly lower accuracy than FA3 on NVIDIA
78
+ self.assertGreater(metrics["score"], 0.70)
79
+ else:
80
+ self.assertGreater(metrics["score"], 0.74)
81
+ # Wait a little bit so that the memory check happens.
82
+ time.sleep(4)
83
+
84
+ def test_logprob(self):
85
+ response = requests.post(
86
+ f"{self.base_url}/generate",
87
+ json={
88
+ "text": "The capital of France is",
89
+ "sampling_params": {
90
+ "temperature": 0,
91
+ "max_new_tokens": 16,
92
+ },
93
+ "return_logprob": True,
94
+ "top_logprobs_num": 5,
95
+ "logprob_start_len": 0,
96
+ },
97
+ )
98
+ response_json = response.json()
99
+ input_token_logprobs = response_json["meta_info"]["input_token_logprobs"]
100
+ output_token_logprobs = response_json["meta_info"]["output_token_logprobs"]
101
+ output_top_logprobs = response_json["meta_info"]["output_top_logprobs"]
102
+
103
+ assert len(input_token_logprobs) == 6
104
+ assert len(output_token_logprobs) == 16
105
+ assert len(output_top_logprobs) == 16
106
+
107
+
108
+ @unittest.skipIf(is_in_amd_ci(), "MLA model with DP attention not yet supported on AMD")
109
+ class TestDPAttentionDP2PP2(CustomTestCase):
110
+ @classmethod
111
+ def setUpClass(cls):
112
+ cls.model = DEFAULT_MLA_MODEL_NAME_FOR_TEST
113
+ cls.base_url = DEFAULT_URL_FOR_TEST
114
+ cls.process = popen_launch_server(
115
+ cls.model,
116
+ cls.base_url,
117
+ timeout=DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH,
118
+ other_args=[
119
+ "--trust-remote-code",
120
+ "--tp",
121
+ "2",
122
+ "--pp-size",
123
+ "2",
124
+ "--enable-dp-attention",
125
+ "--dp",
126
+ "2",
127
+ ],
128
+ )
129
+
130
+ @classmethod
131
+ def tearDownClass(cls):
132
+ kill_process_tree(cls.process.pid)
133
+
134
+ def test_gsm8k(self):
135
+ args = SimpleNamespace(
136
+ base_url=self.base_url,
137
+ model=self.model,
138
+ eval_name="gsm8k",
139
+ num_examples=None,
140
+ num_threads=1024,
141
+ )
142
+
143
+ metrics = run_eval(args)
144
+ print(f"{metrics=}")
145
+ self.assertGreater(metrics["score"], 0.8)
146
+
147
+
148
+ @unittest.skipIf(
149
+ is_in_amd_ci(),
150
+ "Gemma4 PP not yet validated on AMD",
151
+ )
152
+ class TestGemma4PPAccuracy(unittest.TestCase):
153
+ """End-to-end PP=2 accuracy gate for Gemma4 multimodal.
154
+
155
+ Gemma4 has full-attention layers with head_dim=512 (FA's max is 256), so
156
+ sglang auto-selects the triton attention backend; no manual flag needed.
157
+ The 26B BF16 model splits to ~26 GB per stage under PP=2, well within an
158
+ H100's 80 GB.
159
+ """
160
+
161
+ @classmethod
162
+ def setUpClass(cls):
163
+ cls.model = DEFAULT_MODEL_NAME_FOR_TEST_GEMMA4_PP
164
+ cls.base_url = "http://127.0.0.1:23333"
165
+ cls.process = popen_launch_server(
166
+ cls.model,
167
+ cls.base_url,
168
+ timeout=DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH,
169
+ other_args=[
170
+ "--tp-size",
171
+ 1,
172
+ "--pp-size",
173
+ 2,
174
+ "--trust-remote-code",
175
+ "--enable-multimodal",
176
+ ],
177
+ )
178
+
179
+ @classmethod
180
+ def tearDownClass(cls):
181
+ kill_process_tree(cls.process.pid)
182
+
183
+ def test_gsm8k(self):
184
+ # Gemma4 is instruction-tuned and doesn't follow few-shot completion
185
+ # prompts well — use the chat API (default in run_eval), which scores
186
+ # ~0.98 on this model vs ~0.44 with api="completion".
187
+ args = SimpleNamespace(
188
+ base_url=self.base_url,
189
+ model=self.model,
190
+ eval_name="gsm8k",
191
+ num_examples=200,
192
+ num_threads=32,
193
+ )
194
+ metrics = run_eval(args)
195
+ print(f"{metrics=}")
196
+
197
+ # Chat-API baseline ~0.98; gate well below to absorb sample-noise
198
+ # without missing a real PP-routing regression (pre-PP-fix the model
199
+ # produced garbage outputs scoring ≈ 0).
200
+ self.assertGreaterEqual(metrics["score"], 0.90)
201
+ # Wait a little bit so that the memory check happens.
202
+ time.sleep(4)
203
+
204
+ @unittest.skipIf(is_in_ci(), "To reduce the CI execution time.")
205
+ def test_mmmu(self):
206
+ # Multimodal accuracy gate covering the vision_tower → embed_vision
207
+ # (first rank) → PP-proxy handoff → LM tail (last rank) chain.
208
+ # Measured 0.71 on 200 examples; full eval (~900 questions) takes
209
+ # ~5-7 min on H100 so this is manual-only.
210
+ args = SimpleNamespace(
211
+ base_url=self.base_url,
212
+ model=self.model,
213
+ eval_name="mmmu",
214
+ num_examples=None,
215
+ num_threads=32,
216
+ )
217
+ metrics = run_eval(args)
218
+ print(f"{metrics=}")
219
+ # Measured 0.72 on this setup; published Gemma-4-26B MMMU lies in
220
+ # 0.69-0.73. Gate 0.65 leaves ~5 SE of headroom (SE on 900 binary
221
+ # samples ≈ 0.015) while still catching mid-grade vision/PP
222
+ # regressions, not just complete breakage.
223
+ self.assertGreater(metrics["score"], 0.65)
224
+
225
+
226
+ @unittest.skipIf(
227
+ is_in_amd_ci(),
228
+ "Gemma4 PP not yet validated on AMD",
229
+ )
230
+ class TestGemma4PLEPPAccuracy(unittest.TestCase):
231
+ """PP=2 coverage for Gemma4 PLE variants (per_layer_inputs proxy path).
232
+
233
+ 26B-A4B has ``hidden_size_per_layer_input=0`` so the default Gemma4 PP
234
+ test never crosses the PLE branch. Cuda graph + PLE corrupts outputs
235
+ (the runner's hardcoded ``{hidden_states, residual}`` PP-proxy schema
236
+ drops ``per_layer_inputs``), so this test pins the eager configuration.
237
+ """
238
+
239
+ @classmethod
240
+ def setUpClass(cls):
241
+ cls.model = DEFAULT_MODEL_NAME_FOR_TEST_GEMMA4_PLE_PP
242
+ cls.base_url = "http://127.0.0.1:23339"
243
+ cls.process = popen_launch_server(
244
+ cls.model,
245
+ cls.base_url,
246
+ timeout=DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH,
247
+ other_args=[
248
+ "--tp-size",
249
+ 1,
250
+ "--pp-size",
251
+ 2,
252
+ "--trust-remote-code",
253
+ "--enable-multimodal",
254
+ # Required for PLE under PP — see Gemma4TextModel guard.
255
+ "--disable-cuda-graph",
256
+ ],
257
+ )
258
+
259
+ @classmethod
260
+ def tearDownClass(cls):
261
+ kill_process_tree(cls.process.pid)
262
+
263
+ def test_gsm8k(self):
264
+ # Eager-path baseline ~0.92; gate 0.80 catches PLE breakage
265
+ # (corruption collapses score to ~0).
266
+ args = SimpleNamespace(
267
+ base_url=self.base_url,
268
+ model=self.model,
269
+ eval_name="gsm8k",
270
+ num_examples=100,
271
+ num_threads=32,
272
+ )
273
+ metrics = run_eval(args)
274
+ print(f"{metrics=}")
275
+ self.assertGreaterEqual(metrics["score"], 0.80)
276
+ time.sleep(4)
277
+
278
+
279
+ class TestPPMixedChunk(CustomTestCase):
280
+ @classmethod
281
+ def setUpClass(cls):
282
+ cls.model = DEFAULT_MODEL_NAME_FOR_TEST
283
+ cls.base_url = "http://127.0.0.1:23338"
284
+ cls.process = popen_launch_server(
285
+ cls.model,
286
+ cls.base_url,
287
+ timeout=DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH,
288
+ other_args=[
289
+ "--tp-size",
290
+ 2,
291
+ "--pp-size",
292
+ 2,
293
+ "--chunked-prefill-size",
294
+ 256,
295
+ "--enable-mixed-chunk",
296
+ ],
297
+ )
298
+
299
+ @classmethod
300
+ def tearDownClass(cls):
301
+ if hasattr(cls, "process"):
302
+ kill_process_tree(cls.process.pid)
303
+
304
+ def test_gsm8k(self):
305
+ args = SimpleNamespace(
306
+ base_url=self.base_url,
307
+ model=self.model,
308
+ eval_name="gsm8k",
309
+ api="completion",
310
+ max_tokens=512,
311
+ num_examples=200,
312
+ num_threads=128,
313
+ )
314
+ metrics = run_eval(args)
315
+ print(f"{metrics=}")
316
+
317
+ if is_in_amd_ci():
318
+ # AMD triton backend produces slightly lower accuracy than FA3 on NVIDIA
319
+ self.assertGreater(metrics["score"], 0.70)
320
+ else:
321
+ self.assertGreater(metrics["score"], 0.74)
322
+ # Wait a little bit so that the memory check happens.
323
+ time.sleep(4)
324
+
325
+
326
+ class TestFixedBugs(unittest.TestCase):
327
+ def test_chunked_prefill_with_small_bs(self):
328
+ model = DEFAULT_MODEL_NAME_FOR_TEST
329
+ server_args = ServerArgs(model_path=model)
330
+ bench_args = OneBatchBenchArgs(
331
+ batch_size=(1,),
332
+ input_len=(1,),
333
+ output_len=(1,),
334
+ base_url=DEFAULT_URL_FOR_TEST,
335
+ )
336
+ other_server_args = [
337
+ "--tp-size",
338
+ 2,
339
+ "--pp-size",
340
+ 2,
341
+ "--chunked-prefill-size",
342
+ 256,
343
+ "--max-running-requests",
344
+ 2,
345
+ ]
346
+ run_bench_one_batch_server(
347
+ model,
348
+ DEFAULT_URL_FOR_TEST,
349
+ server_args,
350
+ bench_args,
351
+ other_server_args,
352
+ )
353
+
354
+
355
+ if __name__ == "__main__":
356
+ unittest.main()
asian_ai/performance/SGLang/test/registered/pp/test_pp_single_node_extra.py ADDED
@@ -0,0 +1,355 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Usage:
3
+ python3 -m unittest test_pp_single_node_extra.TestQwenVLPPAccuracy.test_gsm8k
4
+ python3 -m unittest test_pp_single_node_extra.TestQwenPPAccuracy.test_pp_consistency
5
+ python3 -m unittest test_pp_single_node_extra.TestQwenPPTieWeightsAccuracy.test_pp_consistency
6
+ python3 -m unittest test_pp_single_node_extra.TestQwenMoePPAccuracy.test_pp_consistency
7
+ python3 -m unittest test_pp_single_node_extra.TestQwen35PPAccuracy.test_pp_consistency
8
+ python3 -m unittest test_pp_single_node_extra.TestGLM41VPPAccuracy.test_mmmu
9
+ """
10
+
11
+ import time
12
+ import unittest
13
+ from types import SimpleNamespace
14
+
15
+ from sglang.srt.utils import kill_process_tree
16
+ from sglang.test.ci.ci_register import register_amd_ci, register_cuda_ci
17
+ from sglang.test.run_eval import run_eval
18
+ from sglang.test.test_utils import (
19
+ DEFAULT_MODEL_NAME_FOR_TEST_GLM_41V_PP,
20
+ DEFAULT_MODEL_NAME_FOR_TEST_VL_PP,
21
+ DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH,
22
+ DEFAULT_URL_FOR_TEST,
23
+ is_in_amd_ci,
24
+ is_in_ci,
25
+ popen_launch_server,
26
+ )
27
+
28
+ register_cuda_ci(est_time=350, stage="extra-b", runner_config="4-gpu-h100")
29
+ register_amd_ci(est_time=350, suite="stage-c-test-4-gpu-amd")
30
+
31
+
32
+ @unittest.skipIf(
33
+ is_in_amd_ci(),
34
+ "VLM PP accuracy too low on AMD (0.48-0.50 with both aiter and triton)",
35
+ )
36
+ class TestQwenVLPPAccuracy(unittest.TestCase):
37
+ @classmethod
38
+ def setUpClass(cls):
39
+ cls.model = DEFAULT_MODEL_NAME_FOR_TEST_VL_PP
40
+ cls.base_url = "http://127.0.0.1:23333"
41
+ cls.process = popen_launch_server(
42
+ DEFAULT_MODEL_NAME_FOR_TEST_VL_PP,
43
+ cls.base_url,
44
+ timeout=DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH,
45
+ other_args=[
46
+ "--tp-size",
47
+ 1,
48
+ "--pp-size",
49
+ 4,
50
+ "--chunked-prefill-size",
51
+ 8192,
52
+ "--enable-multimodal",
53
+ ],
54
+ )
55
+
56
+ def test_gsm8k(self):
57
+ args = SimpleNamespace(
58
+ base_url=self.base_url,
59
+ model=self.model,
60
+ eval_name="gsm8k",
61
+ api="completion",
62
+ max_tokens=512,
63
+ num_examples=200,
64
+ num_threads=128,
65
+ )
66
+ metrics = run_eval(args)
67
+ print(f"{metrics=}")
68
+
69
+ self.assertGreaterEqual(metrics["score"], 0.65)
70
+ # Wait a little bit so that the memory check happens.
71
+ time.sleep(4)
72
+
73
+ @classmethod
74
+ def tearDownClass(cls):
75
+ kill_process_tree(cls.process.pid)
76
+
77
+ @unittest.skipIf(is_in_ci(), "To reduce the CI execution time.")
78
+ def test_mmmu(self):
79
+ args = SimpleNamespace(
80
+ base_url=self.base_url,
81
+ model=self.model,
82
+ eval_name="mmmu",
83
+ num_examples=None,
84
+ num_threads=32,
85
+ )
86
+ metrics = run_eval(args)
87
+ print(f"{metrics=}")
88
+ self.assertGreater(metrics["score"], 0.26)
89
+
90
+
91
+ class TestQwenPPAccuracy(unittest.TestCase):
92
+ @classmethod
93
+ def setUpClass(cls):
94
+ cls.base_url = "http://127.0.0.1:23334" # different ports to avoid conflicts
95
+ cls.model_name = "Qwen/Qwen3-8B" # replace with your Qwen Model if needed
96
+
97
+ def run_gsm8k_test(self, pp_size):
98
+ process = popen_launch_server(
99
+ self.model_name,
100
+ self.base_url,
101
+ timeout=DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH,
102
+ other_args=[
103
+ "--pp-size",
104
+ pp_size,
105
+ "--chunked-prefill-size",
106
+ 256,
107
+ ],
108
+ )
109
+
110
+ try:
111
+ args = SimpleNamespace(
112
+ base_url=self.base_url,
113
+ model=self.model_name,
114
+ eval_name="gsm8k",
115
+ api="completion",
116
+ max_tokens=512,
117
+ num_examples=512,
118
+ num_threads=128,
119
+ )
120
+ metrics = run_eval(args)
121
+ time.sleep(5)
122
+ return metrics
123
+ finally:
124
+ kill_process_tree(process.pid)
125
+
126
+ @unittest.skipIf(is_in_ci(), "To reduce the CI execution time.")
127
+ def test_pp_consistency(self):
128
+ baseline = self.run_gsm8k_test(pp_size=1)
129
+ pp_metrics = self.run_gsm8k_test(pp_size=2)
130
+
131
+ print(f"[Qwen PP Comparison] Baseline: {baseline} | PP: {pp_metrics}")
132
+
133
+ self.assertGreaterEqual(baseline["score"], 0.74)
134
+ self.assertGreaterEqual(
135
+ pp_metrics["score"],
136
+ baseline["score"] - 0.02,
137
+ msg=(
138
+ f"PP accuracy dropped more than 2% compared to baseline. "
139
+ f"Baseline: {baseline['score']:.2%}, PP: {pp_metrics['score']:.2%}"
140
+ ),
141
+ )
142
+
143
+
144
+ @unittest.skipIf(is_in_amd_ci(), "PP consistency too flaky on AMD 4-GPU runners")
145
+ class TestQwenPPTieWeightsAccuracy(unittest.TestCase):
146
+ @classmethod
147
+ def setUpClass(cls):
148
+ cls.base_url = "http://127.0.0.1:23335" # different ports to avoid conflicts
149
+ cls.model_name = (
150
+ "Qwen/Qwen3-0.6B" # qwen3 < 8B all have tie_word_embeddings = True
151
+ )
152
+
153
+ def run_gsm8k_test(self, pp_size):
154
+ process = popen_launch_server(
155
+ self.model_name,
156
+ self.base_url,
157
+ timeout=DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH,
158
+ other_args=[
159
+ "--pp-size",
160
+ pp_size,
161
+ "--chunked-prefill-size",
162
+ 256,
163
+ ],
164
+ )
165
+
166
+ try:
167
+ args = SimpleNamespace(
168
+ base_url=self.base_url,
169
+ model=self.model_name,
170
+ eval_name="gsm8k",
171
+ api="completion",
172
+ max_tokens=512,
173
+ num_examples=512,
174
+ num_threads=128,
175
+ )
176
+ metrics = run_eval(args)
177
+ time.sleep(5)
178
+ return metrics
179
+ finally:
180
+ kill_process_tree(process.pid)
181
+
182
+ def test_pp_consistency(self):
183
+ baseline = self.run_gsm8k_test(pp_size=1)
184
+ pp_metrics = self.run_gsm8k_test(pp_size=2)
185
+
186
+ print(f"[Qwen PP Comparison] Baseline: {baseline} | PP: {pp_metrics}")
187
+
188
+ self.assertGreaterEqual(baseline["score"], 0.38)
189
+ self.assertGreaterEqual(
190
+ pp_metrics["score"],
191
+ baseline["score"] - 0.02,
192
+ msg=(
193
+ f"PP accuracy dropped more than 2% compared to baseline. "
194
+ f"Baseline: {baseline['score']:.2%}, PP: {pp_metrics['score']:.2%}"
195
+ ),
196
+ )
197
+
198
+
199
+ class TestQwenMoePPAccuracy(unittest.TestCase):
200
+ @classmethod
201
+ def setUpClass(cls):
202
+ cls.base_url = "http://127.0.0.1:23336" # different ports to avoid conflicts
203
+ cls.model_name = "Qwen/Qwen3-30B-A3B" # replace with your Qwen Model if needed
204
+
205
+ def run_gsm8k_test(self, pp_size):
206
+ process = popen_launch_server(
207
+ self.model_name,
208
+ self.base_url,
209
+ timeout=DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH,
210
+ other_args=[
211
+ "--pp-size",
212
+ pp_size,
213
+ "--chunked-prefill-size",
214
+ 256,
215
+ ],
216
+ )
217
+
218
+ try:
219
+ args = SimpleNamespace(
220
+ base_url=self.base_url,
221
+ model=self.model_name,
222
+ eval_name="gsm8k",
223
+ api="completion",
224
+ max_tokens=512,
225
+ num_examples=512,
226
+ num_threads=128,
227
+ )
228
+ metrics = run_eval(args)
229
+ time.sleep(5)
230
+ return metrics
231
+ finally:
232
+ kill_process_tree(process.pid)
233
+
234
+ def test_pp_consistency(self):
235
+ baseline = self.run_gsm8k_test(pp_size=1)
236
+ pp_metrics = self.run_gsm8k_test(pp_size=2)
237
+
238
+ print(f"[Qwen PP Comparison] Baseline: {baseline} | PP: {pp_metrics}")
239
+
240
+ self.assertGreaterEqual(baseline["score"], 0.74)
241
+ self.assertGreaterEqual(
242
+ pp_metrics["score"],
243
+ baseline["score"] - 0.02,
244
+ msg=(
245
+ f"PP accuracy dropped more than 2% compared to baseline. "
246
+ f"Baseline: {baseline['score']:.2%}, PP: {pp_metrics['score']:.2%}"
247
+ ),
248
+ )
249
+
250
+
251
+ @unittest.skipIf(
252
+ is_in_ci(), "Qwen35 PP consistency too flaky on H100 and AMD 4-GPU runners"
253
+ )
254
+ class TestQwen35PPAccuracy(unittest.TestCase):
255
+ @classmethod
256
+ def setUpClass(cls):
257
+ cls.base_url = "http://127.0.0.1:23337" # different ports to avoid conflicts
258
+ cls.model_name = (
259
+ "Qwen/Qwen3.5-35B-A3B" # replace with your Qwen Model if needed
260
+ )
261
+
262
+ def run_gsm8k_test(self, tp_size, pp_size):
263
+ process = popen_launch_server(
264
+ self.model_name,
265
+ self.base_url,
266
+ timeout=DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH,
267
+ other_args=[
268
+ "--tp-size",
269
+ tp_size,
270
+ "--pp-size",
271
+ pp_size,
272
+ "--chunked-prefill-size",
273
+ 256,
274
+ ],
275
+ )
276
+
277
+ try:
278
+ args = SimpleNamespace(
279
+ base_url=self.base_url,
280
+ model=self.model_name,
281
+ eval_name="gsm8k",
282
+ api="completion",
283
+ max_tokens=512,
284
+ num_examples=512,
285
+ num_threads=128,
286
+ )
287
+ metrics = run_eval(args)
288
+ time.sleep(5)
289
+ return metrics
290
+ finally:
291
+ kill_process_tree(process.pid)
292
+
293
+ def test_pp_consistency(self):
294
+ baseline = self.run_gsm8k_test(tp_size=2, pp_size=1)
295
+ pp_metrics = self.run_gsm8k_test(tp_size=1, pp_size=2)
296
+
297
+ print(f"[Qwen35 PP Comparison] Baseline: {baseline} | PP: {pp_metrics}")
298
+
299
+ self.assertGreaterEqual(baseline["score"], 0.83)
300
+ self.assertGreaterEqual(
301
+ pp_metrics["score"],
302
+ baseline["score"] - 0.05,
303
+ msg=(
304
+ f"PP accuracy dropped more than 5% compared to baseline. "
305
+ f"Baseline: {baseline['score']:.2%}, PP: {pp_metrics['score']:.2%}"
306
+ ),
307
+ )
308
+
309
+
310
+ @unittest.skipIf(
311
+ is_in_ci(), "Skipping GLM41V PP accuracy test before it gets more stable"
312
+ )
313
+ class TestGLM41VPPAccuracy(unittest.TestCase):
314
+ @classmethod
315
+ def setUpClass(cls):
316
+ cls.model = DEFAULT_MODEL_NAME_FOR_TEST_GLM_41V_PP
317
+ cls.base_url = DEFAULT_URL_FOR_TEST
318
+ cls.process = popen_launch_server(
319
+ DEFAULT_MODEL_NAME_FOR_TEST_GLM_41V_PP,
320
+ cls.base_url,
321
+ timeout=DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH,
322
+ other_args=[
323
+ "--tp-size",
324
+ 1,
325
+ "--pp-size",
326
+ 2,
327
+ "--chunked-prefill-size",
328
+ 8192,
329
+ "--enable-multimodal",
330
+ "--reasoning-parser",
331
+ "glm45",
332
+ ],
333
+ )
334
+
335
+ @classmethod
336
+ def tearDownClass(cls):
337
+ kill_process_tree(cls.process.pid)
338
+
339
+ def test_mmmu(self):
340
+ args = SimpleNamespace(
341
+ base_url=self.base_url,
342
+ model=self.model,
343
+ eval_name="mmmu",
344
+ num_examples=None,
345
+ num_threads=32,
346
+ response_answer_regex=r"<\|begin_of_box\|>(.*)<\|end_of_box\|>",
347
+ )
348
+
349
+ metrics = run_eval(args)
350
+ print(f"{metrics=}")
351
+ self.assertGreater(metrics["score"], 0.45)
352
+
353
+
354
+ if __name__ == "__main__":
355
+ unittest.main()
asian_ai/performance/SGLang/test/registered/prefill_only/test_embed_overrides.py ADDED
@@ -0,0 +1,603 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Unit tests for token embedding override support.
2
+
3
+ Covers:
4
+ - PositionalEmbeds dataclass (embed_types.py)
5
+ - convert_embeds_to_tensors (utils.py)
6
+ - TokenizerManager._resolve_embed_overrides (tokenizer_manager.py)
7
+ - positional_embed_overrides on GenerateReqInput/EmbeddingReqInput (io_struct.py)
8
+ - Score mixin override resolution (tokenizer_manager_score_mixin.py)
9
+ """
10
+
11
+ import unittest
12
+ from unittest.mock import AsyncMock, MagicMock
13
+
14
+ import torch
15
+
16
+ from sglang.srt.entrypoints.openai.utils import convert_embeds_to_tensors
17
+ from sglang.srt.managers.embed_types import PositionalEmbeds
18
+ from sglang.srt.managers.io_struct import EmbeddingReqInput, GenerateReqInput
19
+ from sglang.srt.managers.tokenizer_manager import TokenizerManager
20
+ from sglang.srt.managers.tokenizer_manager_score_mixin import (
21
+ TokenizerManagerScoreMixin,
22
+ )
23
+ from sglang.srt.server_args import MIS_DELIMITER_TOKEN_ID
24
+ from sglang.test.ci.ci_register import register_amd_ci, register_cuda_ci
25
+ from sglang.test.test_utils import CustomTestCase
26
+
27
+ register_cuda_ci(est_time=9, stage="base-b", runner_config="1-gpu-small")
28
+ register_amd_ci(est_time=9, suite="stage-b-test-1-gpu-small-amd")
29
+
30
+ HIDDEN_DIM = 4
31
+
32
+
33
+ def _vec(val: float = 1.0) -> torch.Tensor:
34
+ """Create a 1-D tensor of size HIDDEN_DIM."""
35
+ return torch.full((HIDDEN_DIM,), val, dtype=torch.float32)
36
+
37
+
38
+ def _vec2d(val: float = 1.0) -> torch.Tensor:
39
+ """Create a [1, HIDDEN_DIM] tensor."""
40
+ return torch.full((1, HIDDEN_DIM), val, dtype=torch.float32)
41
+
42
+
43
+ # ========================================================================
44
+ # PositionalEmbeds
45
+ # ========================================================================
46
+
47
+
48
+ class TestPositionalEmbeds(CustomTestCase):
49
+ def test_from_list_of_1d_tensors(self):
50
+ pe = PositionalEmbeds(embeds=[_vec(1), _vec(2)], positions=[0, 5])
51
+ self.assertEqual(pe.embeds.shape, (2, HIDDEN_DIM))
52
+ self.assertAlmostEqual(pe.embeds[0, 0].item(), 1.0)
53
+ self.assertAlmostEqual(pe.embeds[1, 0].item(), 2.0)
54
+
55
+ def test_from_list_of_2d_tensors(self):
56
+ pe = PositionalEmbeds(embeds=[_vec2d(3), _vec2d(4)], positions=[1, 2])
57
+ self.assertEqual(pe.embeds.shape, (2, HIDDEN_DIM))
58
+
59
+ def test_from_pre_stacked_tensor(self):
60
+ stacked = torch.zeros(3, HIDDEN_DIM)
61
+ pe = PositionalEmbeds(embeds=stacked, positions=[0, 1, 2])
62
+ self.assertIs(pe.embeds, stacked)
63
+
64
+ def test_length_mismatch_raises(self):
65
+ with self.assertRaises(ValueError):
66
+ PositionalEmbeds(embeds=[_vec()], positions=[0, 1])
67
+
68
+ def test_empty(self):
69
+ pe = PositionalEmbeds(embeds=torch.zeros(0, HIDDEN_DIM), positions=[])
70
+ self.assertEqual(pe.embeds.shape[0], 0)
71
+
72
+
73
+ # ========================================================================
74
+ # convert_embeds_to_tensors
75
+ # ========================================================================
76
+
77
+
78
+ class TestConvertEmbedsToTensors(CustomTestCase):
79
+ def test_none_returns_none(self):
80
+ self.assertIsNone(convert_embeds_to_tensors(None))
81
+
82
+ def test_empty_list(self):
83
+ self.assertEqual(convert_embeds_to_tensors([]), [])
84
+
85
+ def test_single_input(self):
86
+ """[num_replacements][hidden_size] -> [[tensor, ...]]"""
87
+ result = convert_embeds_to_tensors([[1.0, 2.0], [3.0, 4.0]])
88
+ self.assertEqual(len(result), 1) # wrapped in outer list
89
+ self.assertEqual(len(result[0]), 2) # two replacement vectors
90
+ self.assertTrue(torch.is_tensor(result[0][0]))
91
+ self.assertEqual(result[0][0].tolist(), [1.0, 2.0])
92
+ self.assertEqual(result[0][0].dtype, torch.float32)
93
+ self.assertEqual(result[0][0].dim(), 1) # each vector is 1-D
94
+
95
+ def test_batch_input(self):
96
+ """[num_inputs][num_replacements][hidden_size] -> [[tensor, ...], ...]"""
97
+ result = convert_embeds_to_tensors(
98
+ [
99
+ [[1.0, 2.0]],
100
+ [[3.0, 4.0], [5.0, 6.0]],
101
+ ]
102
+ )
103
+ self.assertEqual(len(result), 2)
104
+ self.assertEqual(len(result[0]), 1)
105
+ self.assertEqual(len(result[1]), 2)
106
+
107
+
108
+ # ========================================================================
109
+ # TokenizerManager._resolve_embed_overrides
110
+ # ========================================================================
111
+
112
+
113
+ class TestResolveEmbedOverrides(CustomTestCase):
114
+ def test_basic_resolution(self):
115
+ embeds = [_vec(1), _vec(2)]
116
+ pe = TokenizerManager._resolve_embed_overrides(
117
+ input_ids=[10, 50, 20, 50, 30],
118
+ token_id=50,
119
+ embeds=embeds,
120
+ )
121
+ self.assertIsInstance(pe, PositionalEmbeds)
122
+ self.assertEqual(pe.positions, [1, 3])
123
+ self.assertEqual(pe.embeds.shape, (2, HIDDEN_DIM))
124
+
125
+ def test_no_placeholders_raises(self):
126
+ with self.assertRaises(ValueError):
127
+ TokenizerManager._resolve_embed_overrides(
128
+ input_ids=[10, 20, 30],
129
+ token_id=50,
130
+ embeds=[_vec()],
131
+ )
132
+
133
+ def test_count_mismatch_raises(self):
134
+ with self.assertRaises(ValueError):
135
+ TokenizerManager._resolve_embed_overrides(
136
+ input_ids=[10, 50, 20],
137
+ token_id=50,
138
+ embeds=[_vec(1), _vec(2)],
139
+ )
140
+
141
+
142
+ # ========================================================================
143
+ # io_struct: positional_embed_overrides on GenerateReqInput
144
+ # ========================================================================
145
+
146
+
147
+ class TestGenerateReqInputEmbedOverride(CustomTestCase):
148
+ def test_single_override_in_getitem(self):
149
+ """Single PositionalEmbeds is shared across all items in __getitem__."""
150
+ pe = PositionalEmbeds(embeds=[_vec()], positions=[0])
151
+ req = GenerateReqInput(
152
+ input_ids=[[1, 2], [3, 4]],
153
+ sampling_params=[{}, {}],
154
+ positional_embed_overrides=pe,
155
+ )
156
+ req.normalize_batch_and_arguments()
157
+ item = req[0]
158
+ self.assertIs(item.positional_embed_overrides, pe)
159
+
160
+ def test_batch_override_in_getitem(self):
161
+ """List[Optional[PositionalEmbeds]] is indexed per-item."""
162
+ pe0 = PositionalEmbeds(embeds=[_vec(1)], positions=[0])
163
+ pe1 = None
164
+ req = GenerateReqInput(
165
+ input_ids=[[1, 2], [3, 4]],
166
+ sampling_params=[{}, {}],
167
+ positional_embed_overrides=[pe0, pe1],
168
+ )
169
+ req.normalize_batch_and_arguments()
170
+ self.assertEqual(req[0].positional_embed_overrides, pe0)
171
+ self.assertIsNone(req[1].positional_embed_overrides)
172
+
173
+
174
+ # ========================================================================
175
+ # io_struct: embed override fields on EmbeddingReqInput
176
+ # ========================================================================
177
+
178
+
179
+ class TestEmbeddingReqInputEmbedOverride(CustomTestCase):
180
+ def test_override_fields_in_getitem(self):
181
+ """embed_override_token_id, embed_overrides, and positional_embed_overrides
182
+ are correctly sliced in __getitem__."""
183
+ pe0 = PositionalEmbeds(embeds=[_vec(1)], positions=[0])
184
+ pe1 = PositionalEmbeds(embeds=[_vec(2)], positions=[1])
185
+ req = EmbeddingReqInput(
186
+ input_ids=[[50, 10], [20, 50]],
187
+ sampling_params=[{}, {}],
188
+ embed_override_token_id=50,
189
+ embed_overrides=[[_vec(1)], [_vec(2)]],
190
+ positional_embed_overrides=[pe0, pe1],
191
+ )
192
+ req.normalize_batch_and_arguments()
193
+ item0 = req[0]
194
+ item1 = req[1]
195
+ self.assertEqual(item0.embed_override_token_id, 50)
196
+ self.assertEqual(len(item0.embed_overrides), 1)
197
+ self.assertEqual(item0.positional_embed_overrides, pe0)
198
+ self.assertEqual(item1.positional_embed_overrides, pe1)
199
+
200
+
201
+ # ========================================================================
202
+ # Score mixin: _resolve_overrides_for_sequence
203
+ # ========================================================================
204
+
205
+
206
+ class _FakeServerArgs:
207
+ """Minimal stub for server_args."""
208
+
209
+ def __init__(self, enable_mis=False):
210
+ self.enable_mis = enable_mis
211
+
212
+
213
+ class _FakeMixin(TokenizerManagerScoreMixin):
214
+ """Minimal stub to call mixin methods without a full TokenizerManager."""
215
+
216
+ def __init__(self, enable_mis=False):
217
+ self.server_args = _FakeServerArgs(enable_mis)
218
+ self.tokenizer = None
219
+ self.is_generation = True
220
+
221
+
222
+ class TestResolveOverridesForSequence(CustomTestCase):
223
+ def setUp(self):
224
+ self.mixin = _FakeMixin()
225
+
226
+ def test_none_embeds_returns_empty(self):
227
+ embeds, positions = self.mixin._resolve_overrides_for_sequence(
228
+ token_ids=[10, 50, 20],
229
+ embeds=None,
230
+ embed_override_token_id=50,
231
+ )
232
+ self.assertEqual(embeds, [])
233
+ self.assertEqual(positions, [])
234
+
235
+ def test_basic_resolution(self):
236
+ e1, e2 = _vec(1), _vec(2)
237
+ embeds, positions = self.mixin._resolve_overrides_for_sequence(
238
+ token_ids=[50, 10, 50],
239
+ embeds=[e1, e2],
240
+ embed_override_token_id=50,
241
+ )
242
+ self.assertEqual(len(embeds), 2)
243
+ self.assertEqual(positions, [0, 2])
244
+
245
+ def test_with_offset(self):
246
+ embeds, positions = self.mixin._resolve_overrides_for_sequence(
247
+ token_ids=[10, 50],
248
+ embeds=[_vec()],
249
+ embed_override_token_id=50,
250
+ position_offset=100,
251
+ )
252
+ self.assertEqual(positions, [101])
253
+
254
+ def test_empty_embeds_list(self):
255
+ """Empty embeds list with no placeholders succeeds."""
256
+ embeds, positions = self.mixin._resolve_overrides_for_sequence(
257
+ token_ids=[10, 20],
258
+ embeds=[],
259
+ embed_override_token_id=50,
260
+ )
261
+ self.assertEqual(embeds, [])
262
+ self.assertEqual(positions, [])
263
+
264
+ def test_count_mismatch_raises(self):
265
+ with self.assertRaises(ValueError):
266
+ self.mixin._resolve_overrides_for_sequence(
267
+ token_ids=[50, 50],
268
+ embeds=[_vec()],
269
+ embed_override_token_id=50,
270
+ )
271
+
272
+
273
+ # ========================================================================
274
+ # Score mixin: _resolve_embed_overrides_for_request
275
+ # ========================================================================
276
+
277
+
278
+ class TestResolveEmbedOverridesForRequest(CustomTestCase):
279
+ def setUp(self):
280
+ self.mixin = _FakeMixin()
281
+
282
+ def test_no_overrides_returns_none(self):
283
+ result = self.mixin._resolve_embed_overrides_for_request(
284
+ query=[10, 20],
285
+ item=[30, 40],
286
+ embed_override_token_id=50,
287
+ query_embed_overrides=None,
288
+ item_embeds=None,
289
+ item_position_offset=2,
290
+ item_label="items[0]",
291
+ )
292
+ self.assertIsNone(result)
293
+
294
+ def test_query_only_overrides(self):
295
+ pe = self.mixin._resolve_embed_overrides_for_request(
296
+ query=[50, 20],
297
+ item=[30, 40],
298
+ embed_override_token_id=50,
299
+ query_embed_overrides=[_vec(1)],
300
+ item_embeds=None,
301
+ item_position_offset=2,
302
+ item_label="items[0]",
303
+ )
304
+ self.assertIsInstance(pe, PositionalEmbeds)
305
+ self.assertEqual(pe.positions, [0])
306
+ self.assertEqual(pe.embeds.shape, (1, HIDDEN_DIM))
307
+
308
+ def test_item_only_overrides(self):
309
+ pe = self.mixin._resolve_embed_overrides_for_request(
310
+ query=[10, 20],
311
+ item=[50, 40],
312
+ embed_override_token_id=50,
313
+ query_embed_overrides=None,
314
+ item_embeds=[_vec(2)],
315
+ item_position_offset=2,
316
+ item_label="items[0]",
317
+ )
318
+ self.assertEqual(pe.positions, [2]) # offset applied
319
+
320
+ def test_query_and_item_overrides(self):
321
+ pe = self.mixin._resolve_embed_overrides_for_request(
322
+ query=[50, 20],
323
+ item=[30, 50],
324
+ embed_override_token_id=50,
325
+ query_embed_overrides=[_vec(1)],
326
+ item_embeds=[_vec(2)],
327
+ item_position_offset=2,
328
+ item_label="items[0]",
329
+ )
330
+ self.assertEqual(pe.positions, [0, 3]) # query pos 0, item pos 1+offset 2
331
+ self.assertEqual(pe.embeds.shape, (2, HIDDEN_DIM))
332
+
333
+
334
+ # ========================================================================
335
+ # Score mixin: _build_token_id_inputs
336
+ # ========================================================================
337
+
338
+ DELIM_TOKEN = MIS_DELIMITER_TOKEN_ID
339
+
340
+
341
+ class TestBuildTokenIdInputs(CustomTestCase):
342
+ def setUp(self):
343
+ self.mixin = _FakeMixin(enable_mis=True)
344
+
345
+ # --- single-item mode, no embeds ---
346
+
347
+ def test_single_item_no_embeds(self):
348
+ _, input_ids, positional_embed_overrides, _ = self.mixin._build_token_id_inputs(
349
+ query=[1, 2],
350
+ items=[[3, 4], [5, 6]],
351
+ item_first=False,
352
+ use_multi_item_scoring=False,
353
+ embed_override_token_id=None,
354
+ query_embed_overrides=None,
355
+ item_embed_overrides=None,
356
+ )
357
+ self.assertEqual(input_ids, [[1, 2, 3, 4], [1, 2, 5, 6]])
358
+ self.assertIsNone(positional_embed_overrides)
359
+
360
+ def test_single_item_no_embeds_item_first(self):
361
+ _, input_ids, positional_embed_overrides, _ = self.mixin._build_token_id_inputs(
362
+ query=[1, 2],
363
+ items=[[3, 4]],
364
+ item_first=True,
365
+ use_multi_item_scoring=False,
366
+ embed_override_token_id=None,
367
+ query_embed_overrides=None,
368
+ item_embed_overrides=None,
369
+ )
370
+ self.assertEqual(input_ids, [[3, 4, 1, 2]])
371
+ self.assertIsNone(positional_embed_overrides)
372
+
373
+ # --- multi-item mode, no embeds ---
374
+
375
+ def test_multi_item_no_embeds(self):
376
+ _, input_ids, positional_embed_overrides, _ = self.mixin._build_token_id_inputs(
377
+ query=[1, 2],
378
+ items=[[3, 4], [5, 6]],
379
+ item_first=False,
380
+ use_multi_item_scoring=True,
381
+ embed_override_token_id=None,
382
+ query_embed_overrides=None,
383
+ item_embed_overrides=None,
384
+ )
385
+ # query<D>item1<D>item2<D>
386
+ self.assertEqual(
387
+ input_ids, [[1, 2, DELIM_TOKEN, 3, 4, DELIM_TOKEN, 5, 6, DELIM_TOKEN]]
388
+ )
389
+ self.assertIsNone(positional_embed_overrides)
390
+
391
+ # --- single-item mode, with embeds ---
392
+
393
+ def test_single_item_query_embeds(self):
394
+ """Query placeholder overrides are resolved per item."""
395
+ _, input_ids, positional_embed_overrides, _ = self.mixin._build_token_id_inputs(
396
+ query=[50, 10],
397
+ items=[[20, 30], [40, 50]],
398
+ item_first=False,
399
+ use_multi_item_scoring=False,
400
+ embed_override_token_id=50,
401
+ query_embed_overrides=[_vec(1)],
402
+ item_embed_overrides=None,
403
+ )
404
+ self.assertEqual(input_ids, [[50, 10, 20, 30], [50, 10, 40, 50]])
405
+ self.assertIsNotNone(positional_embed_overrides)
406
+ self.assertEqual(len(positional_embed_overrides), 2)
407
+ # Each item gets its own PositionalEmbeds with query override at pos 0
408
+ self.assertEqual(positional_embed_overrides[0].positions, [0])
409
+ self.assertEqual(positional_embed_overrides[1].positions, [0])
410
+
411
+ def test_single_item_item_embeds(self):
412
+ """Per-item overrides with correct position offsets."""
413
+ _, input_ids, positional_embed_overrides, _ = self.mixin._build_token_id_inputs(
414
+ query=[10, 20],
415
+ items=[[50, 30]],
416
+ item_first=False,
417
+ use_multi_item_scoring=False,
418
+ embed_override_token_id=50,
419
+ query_embed_overrides=None,
420
+ item_embed_overrides=[[_vec(2)]],
421
+ )
422
+ self.assertEqual(input_ids, [[10, 20, 50, 30]])
423
+ self.assertIsNotNone(positional_embed_overrides)
424
+ # item placeholder at index 0 of item, offset by query length 2
425
+ self.assertEqual(positional_embed_overrides[0].positions, [2])
426
+
427
+ def test_single_item_no_override_positions_returns_none_injection(self):
428
+ """When no items have placeholders, positional_embed_overrides should be None."""
429
+ _, input_ids, positional_embed_overrides, _ = self.mixin._build_token_id_inputs(
430
+ query=[10, 20],
431
+ items=[[30, 40]],
432
+ item_first=False,
433
+ use_multi_item_scoring=False,
434
+ embed_override_token_id=50,
435
+ query_embed_overrides=None,
436
+ item_embed_overrides=[None],
437
+ )
438
+ self.assertIsNone(positional_embed_overrides)
439
+
440
+ def test_single_item_query_and_item_embeds(self):
441
+ """Single-item mode with both query and item overrides in one request."""
442
+ _, input_ids, positional_embed_overrides, _ = self.mixin._build_token_id_inputs(
443
+ query=[50, 10],
444
+ items=[[20, 50]],
445
+ item_first=False,
446
+ use_multi_item_scoring=False,
447
+ embed_override_token_id=50,
448
+ query_embed_overrides=[_vec(1)],
449
+ item_embed_overrides=[[_vec(2)]],
450
+ )
451
+ self.assertEqual(input_ids, [[50, 10, 20, 50]])
452
+ self.assertIsNotNone(positional_embed_overrides)
453
+ pe = positional_embed_overrides[0]
454
+ # query override at pos 0, item override at pos 3 (query_len=2 + idx=1)
455
+ self.assertEqual(pe.positions, [0, 3])
456
+ self.assertEqual(pe.embeds.shape, (2, HIDDEN_DIM))
457
+
458
+ def test_single_item_empty_query(self):
459
+ """Empty query with item-only overrides (valid from score_prompts)."""
460
+ _, input_ids, positional_embed_overrides, _ = self.mixin._build_token_id_inputs(
461
+ query=[],
462
+ items=[[50, 10]],
463
+ item_first=False,
464
+ use_multi_item_scoring=False,
465
+ embed_override_token_id=50,
466
+ query_embed_overrides=None,
467
+ item_embed_overrides=[[_vec(1)]],
468
+ )
469
+ self.assertEqual(input_ids, [[50, 10]])
470
+ self.assertIsNotNone(positional_embed_overrides)
471
+ # item placeholder at absolute pos 0 (offset=len([])=0)
472
+ self.assertEqual(positional_embed_overrides[0].positions, [0])
473
+
474
+ # --- multi-item mode, with embeds ---
475
+
476
+ def test_multi_item_with_query_and_item_embeds(self):
477
+ """Multi-item mode resolves query overrides once and item overrides per item."""
478
+ _, input_ids, positional_embed_overrides, _ = self.mixin._build_token_id_inputs(
479
+ query=[50, 10],
480
+ items=[[20, 50], [30, 40]],
481
+ item_first=False,
482
+ use_multi_item_scoring=True,
483
+ embed_override_token_id=50,
484
+ query_embed_overrides=[_vec(1)],
485
+ item_embed_overrides=[[_vec(2)], None],
486
+ )
487
+ # query<D>item1<D>item2<D> = [50,10, DELIM, 20,50, DELIM, 30,40, DELIM]
488
+ self.assertEqual(len(input_ids), 1)
489
+ self.assertIsNotNone(positional_embed_overrides)
490
+ self.assertEqual(
491
+ len(positional_embed_overrides), 1
492
+ ) # single PositionalEmbeds for combined sequence
493
+ pe = positional_embed_overrides[0]
494
+ # query override at pos 0, item[0] override at pos 4 (query_len=2 + delim=1 + idx=1)
495
+ self.assertIn(0, pe.positions)
496
+ self.assertIn(4, pe.positions)
497
+ self.assertEqual(pe.embeds.shape[0], 2)
498
+
499
+
500
+ # ========================================================================
501
+ # Score mixin: score_request validation
502
+ # ========================================================================
503
+
504
+
505
+ class TestScoreRequestValidation(CustomTestCase):
506
+ """Test validation guards in score_request without running full pipeline."""
507
+
508
+ def setUp(self):
509
+ self.mixin = _FakeMixin()
510
+
511
+ def _call(self, **kwargs):
512
+ """Wrapper to call score_request synchronously."""
513
+ import asyncio
514
+
515
+ return asyncio.run(self.mixin.score_request(**kwargs))
516
+
517
+ def test_generation_requires_label_token_ids(self):
518
+ self.mixin.is_generation = True
519
+ with self.assertRaisesRegex(ValueError, "label_token_ids is required"):
520
+ self._call(
521
+ query=[1, 2],
522
+ items=[[3, 4]],
523
+ label_token_ids=None,
524
+ )
525
+
526
+ def test_seq_classification_allows_none_label_token_ids(self):
527
+ """SequenceClassification models should not require label_token_ids.
528
+ Verify it passes validation and reaches generate_request."""
529
+ self.mixin.is_generation = False
530
+ mock_result = AsyncMock()
531
+ mock_result.__anext__ = AsyncMock(
532
+ return_value=[{"embedding": [0.1, 0.9], "meta_info": {"prompt_tokens": 2}}]
533
+ )
534
+ self.mixin.generate_request = MagicMock(return_value=mock_result)
535
+ result = self._call(
536
+ query=[1, 2],
537
+ items=[[3, 4]],
538
+ label_token_ids=None,
539
+ )
540
+ self.mixin.generate_request.assert_called_once()
541
+ self.assertEqual(len(result.scores), 1)
542
+
543
+ def test_items_none_raises(self):
544
+ with self.assertRaisesRegex(ValueError, "items must be provided"):
545
+ self._call(
546
+ query=[1, 2],
547
+ items=None,
548
+ label_token_ids=[100],
549
+ )
550
+
551
+ def test_empty_items_returns_empty(self):
552
+ result = self._call(
553
+ query=[1, 2],
554
+ items=[],
555
+ label_token_ids=[100],
556
+ )
557
+ self.assertEqual(result.scores, [])
558
+ self.assertEqual(result.prompt_tokens, 0)
559
+
560
+ def test_embed_override_token_id_required_with_query_embeds(self):
561
+ with self.assertRaisesRegex(ValueError, "embed_override_token_id is required"):
562
+ self._call(
563
+ query=[1, 2],
564
+ items=[[3, 4]],
565
+ label_token_ids=[100],
566
+ query_embed_overrides=[_vec(1)],
567
+ embed_override_token_id=None,
568
+ )
569
+
570
+ def test_embed_override_token_id_required_with_item_embeds(self):
571
+ with self.assertRaisesRegex(ValueError, "embed_override_token_id is required"):
572
+ self._call(
573
+ query=[1, 2],
574
+ items=[[3, 4]],
575
+ label_token_ids=[100],
576
+ item_embed_overrides=[[_vec(1)]],
577
+ embed_override_token_id=None,
578
+ )
579
+
580
+ def test_item_first_with_embeds_raises(self):
581
+ with self.assertRaisesRegex(ValueError, "item_first is not supported"):
582
+ self._call(
583
+ query=[1, 2],
584
+ items=[[3, 4]],
585
+ label_token_ids=[100],
586
+ item_first=True,
587
+ embed_override_token_id=50,
588
+ query_embed_overrides=[_vec(1)],
589
+ )
590
+
591
+ def test_item_embed_overrides_length_mismatch_raises(self):
592
+ with self.assertRaisesRegex(ValueError, "must match items length"):
593
+ self._call(
594
+ query=[1, 2],
595
+ items=[[3, 4], [5, 6]],
596
+ label_token_ids=[100],
597
+ embed_override_token_id=50,
598
+ item_embed_overrides=[[_vec(1)]], # 1 override for 2 items
599
+ )
600
+
601
+
602
+ if __name__ == "__main__":
603
+ unittest.main()
asian_ai/performance/SGLang/test/registered/prefill_only/test_embedding_models.py ADDED
@@ -0,0 +1,162 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2023-2024 SGLang Team
2
+ # Licensed under the Apache License, Version 2.0 (the "License");
3
+ # you may not use this file except in compliance with the License.
4
+ # You may obtain a copy of the License at
5
+ #
6
+ # http://www.apache.org/licenses/LICENSE-2.0
7
+ #
8
+ # Unless required by applicable law or agreed to in writing, software
9
+ # distributed under the License is distributed on an "AS IS" BASIS,
10
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11
+ # See the License for the specific language governing permissions and
12
+ # limitations under the License.
13
+ # ==============================================================================
14
+
15
+ import multiprocessing as mp
16
+ import random
17
+ import unittest
18
+ from typing import Optional
19
+
20
+ import torch
21
+ from transformers import AutoConfig, AutoTokenizer
22
+
23
+ from sglang.test.ci.ci_register import register_amd_ci, register_cuda_ci
24
+ from sglang.test.runners import DEFAULT_PROMPTS, HFRunner, SRTRunner
25
+ from sglang.test.test_utils import (
26
+ CustomTestCase,
27
+ get_similarities,
28
+ is_in_amd_ci,
29
+ is_in_ci,
30
+ )
31
+
32
+ # Embedding model tests
33
+ register_amd_ci(
34
+ est_time=73,
35
+ suite="stage-b-test-1-gpu-small-amd",
36
+ disabled="see https://github.com/sgl-project/sglang/issues/11127",
37
+ )
38
+ register_cuda_ci(est_time=136, stage="base-b", runner_config="1-gpu-small")
39
+
40
+ MODEL_TO_CONFIG = {
41
+ "Alibaba-NLP/gte-Qwen2-1.5B-instruct": (1, 1e-5),
42
+ "intfloat/e5-mistral-7b-instruct": (1, 1e-5),
43
+ "Qwen/Qwen3-Embedding-8B": (1, 1e-5),
44
+ # Temporarily disable: HF reference path in runners.py runs this Qwen2-VL
45
+ # fine-tune with bidirectional attention (the non-sentence-transformers
46
+ # branch in _get_sentence_transformer_embedding_model does not pass
47
+ # is_causal=True), while SGLang's Qwen2-VL embedding is always causal —
48
+ # producing ~0.30 cosine diffs vs HF on short prompts.
49
+ # See https://github.com/sgl-project/sglang/actions/runs/25224929325/job/73966043206
50
+ # "marco/mcdse-2b-v1": (1, 1e-5),
51
+ # Temporarily disable before this model is fixed
52
+ # "jason9693/Qwen2.5-1.5B-apeach": (1, 1e-5),
53
+ }
54
+ MODELS = [(key, *MODEL_TO_CONFIG[key]) for key in MODEL_TO_CONFIG]
55
+
56
+ TORCH_DTYPES = [torch.float16]
57
+
58
+
59
+ class TestEmbeddingModels(CustomTestCase):
60
+
61
+ @classmethod
62
+ def setUpClass(cls):
63
+ mp.set_start_method("spawn", force=True)
64
+
65
+ def _truncate_prompts(self, prompts, model_path):
66
+ config = AutoConfig.from_pretrained(model_path)
67
+ max_length = getattr(config, "max_position_embeddings", 2048)
68
+
69
+ tokenizer = AutoTokenizer.from_pretrained(model_path)
70
+
71
+ truncated_prompts = []
72
+ for prompt in prompts:
73
+ tokens = tokenizer(prompt, return_tensors="pt", truncation=False)
74
+ if len(tokens.input_ids[0]) > max_length:
75
+ truncated_text = tokenizer.decode(
76
+ tokens.input_ids[0][: max_length - 1], skip_special_tokens=True
77
+ )
78
+ truncated_prompts.append(truncated_text)
79
+ else:
80
+ truncated_prompts.append(prompt)
81
+ return truncated_prompts
82
+
83
+ def assert_close_prefill_logits(
84
+ self,
85
+ prompts,
86
+ model_path,
87
+ tp_size,
88
+ torch_dtype,
89
+ prefill_tolerance,
90
+ matryoshka_dim: Optional[int] = None,
91
+ ) -> None:
92
+ truncated_prompts = self._truncate_prompts(prompts, model_path)
93
+
94
+ with HFRunner(
95
+ model_path,
96
+ torch_dtype=torch_dtype,
97
+ model_type="embedding",
98
+ matryoshka_dim=matryoshka_dim,
99
+ ) as hf_runner:
100
+ hf_outputs = hf_runner.forward(truncated_prompts)
101
+
102
+ attention_backend = "triton" if is_in_amd_ci() else None
103
+ with SRTRunner(
104
+ model_path,
105
+ tp_size=tp_size,
106
+ torch_dtype=torch_dtype,
107
+ model_type="embedding",
108
+ attention_backend=attention_backend,
109
+ json_model_override_args=(
110
+ {"matryoshka_dimensions": [matryoshka_dim]} if matryoshka_dim else None
111
+ ),
112
+ ) as srt_runner:
113
+ srt_outputs = srt_runner.forward(
114
+ truncated_prompts, dimensions=matryoshka_dim
115
+ )
116
+
117
+ for i in range(len(prompts)):
118
+ hf_logits = torch.Tensor(hf_outputs.embed_logits[i])
119
+ srt_logits = torch.Tensor(srt_outputs.embed_logits[i])
120
+
121
+ similarity = torch.tensor(get_similarities(hf_logits, srt_logits))
122
+ print("similarity diff", abs(similarity - 1))
123
+
124
+ if len(prompts[i]) <= 1000:
125
+ assert torch.all(
126
+ abs(similarity - 1) < prefill_tolerance
127
+ ), "embeddings are not all close"
128
+
129
+ def test_prefill_logits(self):
130
+ models_to_test = MODELS
131
+
132
+ if is_in_ci():
133
+ models_to_test = [random.choice(MODELS)]
134
+
135
+ for model, tp_size, prefill_tolerance in models_to_test:
136
+ for torch_dtype in TORCH_DTYPES:
137
+ self.assert_close_prefill_logits(
138
+ DEFAULT_PROMPTS, model, tp_size, torch_dtype, prefill_tolerance
139
+ )
140
+
141
+ def test_matryoshka_embedding(self):
142
+ models_to_test = [
143
+ (
144
+ "Alibaba-NLP/gte-Qwen2-1.5B-instruct",
145
+ *MODEL_TO_CONFIG["Alibaba-NLP/gte-Qwen2-1.5B-instruct"],
146
+ )
147
+ ]
148
+
149
+ for model, tp_size, prefill_tolerance in models_to_test:
150
+ for torch_dtype in TORCH_DTYPES:
151
+ self.assert_close_prefill_logits(
152
+ DEFAULT_PROMPTS,
153
+ model,
154
+ tp_size,
155
+ torch_dtype,
156
+ prefill_tolerance,
157
+ matryoshka_dim=128,
158
+ )
159
+
160
+
161
+ if __name__ == "__main__":
162
+ unittest.main()
asian_ai/performance/SGLang/test/registered/prefill_only/test_fa_skip_kv_cache_piecewise_nan.py ADDED
@@ -0,0 +1,162 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2023-2024 SGLang Team
2
+ # Licensed under the Apache License, Version 2.0 (the "License");
3
+ # you may not use this file except in compliance with the License.
4
+ # You may obtain a copy of the License at
5
+ #
6
+ # http://www.apache.org/licenses/LICENSE-2.0
7
+ #
8
+ # Unless required by applicable law or agreed to in writing, software
9
+ # distributed under the License is distributed on an "AS IS" BASIS,
10
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11
+ # See the License for the specific language governing permissions and
12
+ # limitations under the License.
13
+ # ==============================================================================
14
+ """Regression test for the fa_skip_kv_cache embedding fast path under piecewise
15
+ CUDA graph.
16
+
17
+ PR #21971 added an embedding fast path (`fa_skip_kv_cache`) that serves attention
18
+ with `flash_attn_varlen_func` on raw K/V. Under a piecewise CUDA graph the model
19
+ forward runs at a padded token-bucket size, so `q` has more rows than
20
+ `cu_seqlens_q` covers. `flash_attn_varlen_func` requires
21
+ `q.shape[0] == cu_seqlens_q[-1]`; when that is violated the boundary query block
22
+ corrupts the **last real token's** output. Because embedding models use LAST-token
23
+ pooling, that corrupted row IS the returned embedding -> ~40% of *short* inputs
24
+ came back fully NaN (long inputs, which fill the bucket, were unaffected).
25
+
26
+ This test feeds a spread of short inputs through `fa3 + piecewise + fa_skip_kv_cache`
27
+ and asserts no embedding contains NaN, and that the embeddings match the
28
+ non-piecewise path.
29
+ """
30
+
31
+ import os
32
+ import unittest
33
+
34
+ import torch
35
+
36
+ from sglang import Engine
37
+ from sglang.srt.utils import get_device_sm
38
+ from sglang.test.ci.ci_register import register_cuda_ci
39
+ from sglang.test.test_utils import CustomTestCase
40
+
41
+ # Route to the H100 runner (1-gpu-large, SM90) -- NOT 1-gpu-small, which is an
42
+ # RTX 5090 (SM120/Blackwell) where FA3 does not exist. FA3 + the piecewise embedding
43
+ # path this regression covers only runs on Ampere/Ada/Hopper (SM 80-90), so the test
44
+ # must land on the H100 pool to actually execute (on 1-gpu-small it would skip 100%).
45
+ register_cuda_ci(est_time=600, stage="base-b", runner_config="1-gpu-large")
46
+
47
+ # Lowest/highest CUDA SM that supports the FA3 + piecewise embedding path. FA3 is
48
+ # unavailable on Blackwell (sm100 B200 / sm120 consumer e.g. RTX 5090); the gate is
49
+ # applied at RUNTIME (see setUp) so the SM is read after CUDA is initialized on the
50
+ # actual runner, never at import/collection time.
51
+ _FA3_SM_MIN, _FA3_SM_MAX = 80, 90
52
+
53
+ # Overridable so the test can run against a locally-mounted model in dev.
54
+ MODEL_PATH = os.environ.get("SGLANG_TEST_EMB_MODEL", "Qwen/Qwen3-Embedding-0.6B")
55
+
56
+ _WORDS = [
57
+ "the",
58
+ "quick",
59
+ "brown",
60
+ "fox",
61
+ "jumps",
62
+ "over",
63
+ "lazy",
64
+ "dog",
65
+ "embedding",
66
+ "vector",
67
+ "token",
68
+ "sample",
69
+ ]
70
+
71
+
72
+ def _short_prompts():
73
+ """A spread of short inputs (~1..150 tokens).
74
+
75
+ The bug only triggers when a prefill is PADDED up to a piecewise bucket, i.e.
76
+ for token counts that are not exactly a capture size. Using many lengths
77
+ guarantees several land just below a bucket boundary (80/96/112/128 ...).
78
+ """
79
+ return [" ".join(_WORDS[i % len(_WORDS)] for i in range(n)) for n in range(1, 150)]
80
+
81
+
82
+ def _embed(prompts, **engine_kwargs):
83
+ # fa_skip_kv_cache is enabled by: is_embedding + chunked_prefill_size == -1
84
+ # + disable_radix_cache (+ a non-MLA model + the FA3 backend).
85
+ engine = Engine(
86
+ model_path=MODEL_PATH,
87
+ is_embedding=True,
88
+ attention_backend="fa3",
89
+ chunked_prefill_size=-1,
90
+ disable_radix_cache=True,
91
+ **engine_kwargs,
92
+ )
93
+ try:
94
+ # Encode one request per forward (batch size 1). The bug corrupts the
95
+ # last real token, which sits exactly at the real/pad boundary; when many
96
+ # requests are batched into one forward only the tail request hits the
97
+ # boundary, which hides the per-request failure rate.
98
+ embs = []
99
+ for prompt in prompts:
100
+ out = engine.encode(prompt)
101
+ emb = out["embedding"] if isinstance(out, dict) else out[0]["embedding"]
102
+ embs.append(torch.tensor(emb, dtype=torch.float32))
103
+ return embs
104
+ finally:
105
+ engine.shutdown()
106
+
107
+
108
+ # Enables the piecewise CUDA graph for prefill the way production does. After the
109
+ # cuda-graph refactor (#23906) the piecewise config lives in cuda_graph_config; the
110
+ # convenience kwargs below fold into cuda_graph_config[prefill]:
111
+ # - cuda_graph_backend_prefill="tc_piecewise" -> prefill.backend (also the default)
112
+ # - cuda_graph_max_bs_prefill=32768 -> prefill.max_bs (for tc_piecewise
113
+ # prefill, max_bs/bs carries the captured TOKEN count -- the old
114
+ # piecewise_cuda_graph_max_tokens)
115
+ # - cuda_graph_tc_compiler="inductor" -> prefill.tc_compiler
116
+ _PIECEWISE_KWARGS = dict(
117
+ cuda_graph_backend_prefill="tc_piecewise",
118
+ cuda_graph_max_bs_prefill=32768,
119
+ cuda_graph_tc_compiler="inductor",
120
+ )
121
+
122
+
123
+ class TestFaSkipKvCachePiecewiseNoNaN(CustomTestCase):
124
+ def setUp(self):
125
+ # Gate at runtime: read the SM after CUDA is initialized on the runner. If
126
+ # the hardware can't run FA3 (e.g. SM120 RTX 5090 / SM100 B200), skip --
127
+ # a skip is NOT a CI failure, it just records the test as inapplicable here.
128
+ sm = get_device_sm()
129
+ if not (_FA3_SM_MIN <= sm <= _FA3_SM_MAX):
130
+ self.skipTest(
131
+ f"fa3 + piecewise embedding repro requires CUDA SM "
132
+ f"{_FA3_SM_MIN}-{_FA3_SM_MAX} (Ampere/Ada/Hopper); got SM {sm}"
133
+ )
134
+
135
+ def test_no_nan_with_piecewise(self):
136
+ prompts = _short_prompts()
137
+ embs = _embed(prompts, **_PIECEWISE_KWARGS)
138
+ nan_idx = [i for i, e in enumerate(embs) if torch.isnan(e).any()]
139
+ self.assertEqual(
140
+ nan_idx,
141
+ [],
142
+ f"{len(nan_idx)}/{len(embs)} short-input embeddings contain NaN under "
143
+ f"fa_skip_kv_cache + piecewise CUDA graph (e.g. prompt indices {nan_idx[:10]})",
144
+ )
145
+
146
+ def test_matches_non_piecewise(self):
147
+ prompts = _short_prompts()
148
+ with_pcg = _embed(prompts, **_PIECEWISE_KWARGS)
149
+ without_pcg = _embed(prompts, disable_prefill_cuda_graph=True)
150
+ for i, (a, b) in enumerate(zip(with_pcg, without_pcg)):
151
+ self.assertFalse(
152
+ torch.isnan(a).any(),
153
+ f"prompt {i}: NaN embedding with piecewise CUDA graph",
154
+ )
155
+ cos = torch.nn.functional.cosine_similarity(a, b, dim=0).item()
156
+ self.assertGreater(
157
+ cos, 0.99, f"prompt {i}: cosine {cos:.4f} < 0.99 vs non-piecewise"
158
+ )
159
+
160
+
161
+ if __name__ == "__main__":
162
+ unittest.main()
asian_ai/performance/SGLang/test/registered/prefill_only/test_multi_item_scoring.py ADDED
@@ -0,0 +1,599 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Tests for the Multi-Item Scoring (MIS) optimization.
2
+
3
+ MIS is a server-side optimization enabled via --enable-mis that batches
4
+ multiple items into a single forward pass using delimiter tokens (token ID 9999).
5
+ This is different from batch scoring (multiple items in one API call) which
6
+ processes items as separate requests.
7
+
8
+ The key difference:
9
+ - Batch scoring: N items -> N separate forward passes
10
+ - MIS optimization: N items -> 1 forward pass with delimiter-separated items
11
+
12
+ These tests ensure the MIS optimization produces correct results and catches
13
+ bugs in tensor shape handling (e.g., 2D tensors [num_delimiters, num_label_tokens]).
14
+ """
15
+
16
+ import asyncio
17
+ import os
18
+ import unittest
19
+
20
+ import torch
21
+ from transformers import AutoConfig, AutoTokenizer
22
+
23
+ from sglang.srt.entrypoints.engine import Engine
24
+ from sglang.test.ci.ci_register import register_cuda_ci
25
+ from sglang.test.test_utils import (
26
+ DEFAULT_SMALL_MODEL_NAME_FOR_TEST,
27
+ CustomTestCase,
28
+ )
29
+
30
+ register_cuda_ci(est_time=211, stage="base-b", runner_config="1-gpu-small")
31
+
32
+ TEST_MODEL_NAME = os.environ.get("TEST_MODEL_NAME", DEFAULT_SMALL_MODEL_NAME_FOR_TEST)
33
+ TEST_CLASSIFICATION_BASE_MODEL = os.environ.get(
34
+ "TEST_CLASSIFICATION_BASE_MODEL",
35
+ "tomaarsen/Qwen3-Reranker-0.6B-seq-cls",
36
+ )
37
+ _CLS_NUM_LABELS = AutoConfig.from_pretrained(TEST_CLASSIFICATION_BASE_MODEL).num_labels
38
+
39
+
40
+ class TestMISServerArgsValidation(unittest.TestCase):
41
+ """Test ServerArgs defaults for MIS mode."""
42
+
43
+ def test_enable_mis_default(self):
44
+ """Test that enable_mis defaults to False."""
45
+ from sglang.srt.server_args import ServerArgs
46
+
47
+ self.assertEqual(ServerArgs.enable_mis, False)
48
+
49
+
50
+ class TestMultiItemScoringOptimization(CustomTestCase):
51
+ """Test the Multi-Item Scoring (MIS) optimization with generation models."""
52
+
53
+ @classmethod
54
+ def setUpClass(cls):
55
+ cls.engine = Engine(
56
+ model_path=TEST_MODEL_NAME,
57
+ disable_radix_cache=True,
58
+ chunked_prefill_size=-1,
59
+ enable_mis=True,
60
+ attention_backend="flashinfer",
61
+ mem_fraction_static=0.15,
62
+ )
63
+ cls.non_mis_engine = Engine(
64
+ model_path=TEST_MODEL_NAME,
65
+ disable_radix_cache=True,
66
+ chunked_prefill_size=-1,
67
+ mem_fraction_static=0.15,
68
+ )
69
+
70
+ @classmethod
71
+ def tearDownClass(cls):
72
+ if cls.engine is not None:
73
+ cls.engine.shutdown()
74
+ if cls.non_mis_engine is not None:
75
+ cls.non_mis_engine.shutdown()
76
+ torch.cuda.empty_cache()
77
+
78
+ def test_mis_basic(self):
79
+ """Test basic MIS: correct shapes, valid probabilities."""
80
+ query = "Rate each option:"
81
+ items = ["Option A", "Option B", "Option C"]
82
+ label_token_ids = [9454, 2753] # "Yes" and "No" tokens
83
+
84
+ scores = self.engine.score(
85
+ query=query,
86
+ items=items,
87
+ label_token_ids=label_token_ids,
88
+ apply_softmax=True,
89
+ ).scores
90
+
91
+ self.assertEqual(len(scores), len(items))
92
+ for i, score_list in enumerate(scores):
93
+ self.assertEqual(len(score_list), len(label_token_ids))
94
+ self.assertAlmostEqual(sum(score_list), 1.0, places=5)
95
+ for score in score_list:
96
+ self.assertGreaterEqual(score, 0)
97
+ self.assertLessEqual(score, 1)
98
+
99
+ def test_mis_consistency_with_single_item(self):
100
+ """MIS with one item should match non-MIS scoring closely."""
101
+ query = "Is this a fact?\n"
102
+ items = [" The sun rises in the east"]
103
+ label_token_ids = [9454, 2753]
104
+
105
+ mis_scores = self.engine.score(
106
+ query=query,
107
+ items=items,
108
+ label_token_ids=label_token_ids,
109
+ apply_softmax=True,
110
+ ).scores
111
+
112
+ non_mis_scores = self.non_mis_engine.score(
113
+ query=query,
114
+ items=items,
115
+ label_token_ids=label_token_ids,
116
+ apply_softmax=True,
117
+ ).scores
118
+
119
+ self.assertEqual(len(mis_scores), 1)
120
+ self.assertEqual(len(non_mis_scores), 1)
121
+ for j, (m, n) in enumerate(zip(mis_scores[0], non_mis_scores[0])):
122
+ relative_diff = abs(m - n) / max(abs(n), 1e-6)
123
+ self.assertLess(
124
+ relative_diff,
125
+ 0.08,
126
+ msg=f"label {j}: MIS={m} vs non-MIS={n} (diff: {relative_diff:.3f})",
127
+ )
128
+
129
+ def test_mis_empty_query(self):
130
+ """MIS with empty query — delimiter indices start at position 0."""
131
+ items = ["alpha", "beta"]
132
+ label_token_ids = [9454, 2753]
133
+
134
+ scores = self.engine.score(
135
+ query="",
136
+ items=items,
137
+ label_token_ids=label_token_ids,
138
+ apply_softmax=True,
139
+ ).scores
140
+
141
+ self.assertEqual(len(scores), len(items))
142
+ for score_list in scores:
143
+ self.assertEqual(len(score_list), len(label_token_ids))
144
+ self.assertAlmostEqual(sum(score_list), 1.0, places=5)
145
+
146
+
147
+ class TestMultiItemScoringClassification(CustomTestCase):
148
+ """Test MIS with classification models.
149
+
150
+ Uses a pre-trained Qwen3ForSequenceClassification model so that the
151
+ classification head weights are deterministic across Engine instances.
152
+ """
153
+
154
+ NUM_LABELS = _CLS_NUM_LABELS
155
+
156
+ def setUp(self):
157
+ self.engine = Engine(
158
+ model_path=TEST_CLASSIFICATION_BASE_MODEL,
159
+ disable_radix_cache=True,
160
+ chunked_prefill_size=-1,
161
+ enable_mis=True,
162
+ attention_backend="flashinfer",
163
+ mem_fraction_static=0.15,
164
+ )
165
+
166
+ def tearDown(self):
167
+ if self.engine is not None:
168
+ self.engine.shutdown()
169
+ torch.cuda.empty_cache()
170
+
171
+ def test_classification_mis_basic(self):
172
+ """Classification MIS: correct shapes, valid softmax probabilities."""
173
+ query = "Rate each option:"
174
+ items = ["Option A", "Option B", "Option C"]
175
+
176
+ scores = self.engine.score(query=query, items=items, apply_softmax=True).scores
177
+
178
+ self.assertEqual(len(scores), len(items))
179
+ for i, score_list in enumerate(scores):
180
+ self.assertEqual(len(score_list), self.NUM_LABELS)
181
+ self.assertAlmostEqual(sum(score_list), 1.0, places=5)
182
+ for score in score_list:
183
+ self.assertGreaterEqual(score, 0)
184
+ self.assertLessEqual(score, 1)
185
+
186
+ def test_classification_mis_tokenized_input(self):
187
+ """Classification MIS with pre-tokenized query and items."""
188
+ tokenizer = AutoTokenizer.from_pretrained(TEST_CLASSIFICATION_BASE_MODEL)
189
+ query_ids = tokenizer.encode("Rate each option:", add_special_tokens=False)
190
+ items_ids = [
191
+ tokenizer.encode(item, add_special_tokens=False)
192
+ for item in ["Option A", "Option B"]
193
+ ]
194
+
195
+ scores = self.engine.score(
196
+ query=query_ids, items=items_ids, apply_softmax=True
197
+ ).scores
198
+
199
+ self.assertEqual(len(scores), len(items_ids))
200
+ for score_list in scores:
201
+ self.assertEqual(len(score_list), self.NUM_LABELS)
202
+ self.assertAlmostEqual(sum(score_list), 1.0, places=5)
203
+
204
+ def test_classification_non_mis_fallback(self):
205
+ """Classification model works correctly without --enable-mis."""
206
+ non_mis_engine = Engine(
207
+ model_path=TEST_CLASSIFICATION_BASE_MODEL,
208
+ disable_radix_cache=True,
209
+ mem_fraction_static=0.15,
210
+ )
211
+ try:
212
+ scores = non_mis_engine.score(
213
+ query="Test:", items=["A", "B"], apply_softmax=True
214
+ ).scores
215
+
216
+ self.assertEqual(len(scores), 2)
217
+ for score_list in scores:
218
+ self.assertEqual(len(score_list), self.NUM_LABELS)
219
+ self.assertAlmostEqual(sum(score_list), 1.0, places=5)
220
+ finally:
221
+ non_mis_engine.shutdown()
222
+ torch.cuda.empty_cache()
223
+
224
+
225
+ class TestMultiItemScoringParity(CustomTestCase):
226
+ """Test that MIS produces the same results as single-item scoring."""
227
+
228
+ @classmethod
229
+ def setUpClass(cls):
230
+ cls.engine_single = Engine(
231
+ model_path=TEST_MODEL_NAME,
232
+ disable_radix_cache=True,
233
+ log_level="error",
234
+ mem_fraction_static=0.15,
235
+ )
236
+ cls.engine_mis = Engine(
237
+ model_path=TEST_MODEL_NAME,
238
+ disable_radix_cache=True,
239
+ chunked_prefill_size=-1,
240
+ log_level="error",
241
+ enable_mis=True,
242
+ attention_backend="flashinfer",
243
+ mem_fraction_static=0.15,
244
+ )
245
+
246
+ @classmethod
247
+ def tearDownClass(cls):
248
+ if cls.engine_single is not None:
249
+ cls.engine_single.shutdown()
250
+ if cls.engine_mis is not None:
251
+ cls.engine_mis.shutdown()
252
+ torch.cuda.empty_cache()
253
+
254
+ def _compare_scores(
255
+ self, query, items, label_token_ids=None, apply_softmax=True, test_name=""
256
+ ):
257
+ """Compare MIS vs single-item scoring results."""
258
+ single_scores = self.engine_single.score(
259
+ query=query,
260
+ items=items,
261
+ label_token_ids=label_token_ids,
262
+ apply_softmax=apply_softmax,
263
+ ).scores
264
+
265
+ mis_scores = self.engine_mis.score(
266
+ query=query,
267
+ items=items,
268
+ label_token_ids=label_token_ids,
269
+ apply_softmax=apply_softmax,
270
+ ).scores
271
+
272
+ self.assertEqual(
273
+ len(mis_scores), len(single_scores), f"{test_name}: count mismatch"
274
+ )
275
+ for i, (ms, ss) in enumerate(zip(mis_scores, single_scores)):
276
+ self.assertEqual(len(ms), len(ss), f"{test_name}: item {i} length mismatch")
277
+ for j, (m, s) in enumerate(zip(ms, ss)):
278
+ self.assertAlmostEqual(
279
+ m,
280
+ s,
281
+ places=1,
282
+ msg=f"{test_name}: item {i} label {j}: MIS={m} vs single={s}",
283
+ )
284
+
285
+ def test_parity_basic(self):
286
+ tokenizer = AutoTokenizer.from_pretrained(TEST_MODEL_NAME)
287
+ query = "Rate this option:"
288
+ items = [" Option A", " Option B", " Option C"]
289
+ labels = [" good", " bad"]
290
+ label_ids = [tokenizer.encode(lb, add_special_tokens=False)[0] for lb in labels]
291
+ self._compare_scores(query, items, label_ids, test_name="basic")
292
+
293
+ def test_parity_tokenized_inputs(self):
294
+ tokenizer = AutoTokenizer.from_pretrained(TEST_MODEL_NAME)
295
+ query = "Rate this option:"
296
+ items = [" Option X", " Option Y"]
297
+ labels = [" good", " bad"]
298
+ query_ids = tokenizer.encode(query, add_special_tokens=False)
299
+ items_ids = [tokenizer.encode(i, add_special_tokens=False) for i in items]
300
+ label_ids = [tokenizer.encode(lb, add_special_tokens=False)[0] for lb in labels]
301
+ self._compare_scores(query_ids, items_ids, label_ids, test_name="tokenized")
302
+
303
+ def test_parity_without_softmax(self):
304
+ tokenizer = AutoTokenizer.from_pretrained(TEST_MODEL_NAME)
305
+ query = "The weather today is"
306
+ items = [" sunny", " cloudy", " rainy"]
307
+ labels = [" nice", " bad"]
308
+ label_ids = [tokenizer.encode(lb, add_special_tokens=False)[0] for lb in labels]
309
+ self._compare_scores(
310
+ query, items, label_ids, apply_softmax=False, test_name="no_softmax"
311
+ )
312
+
313
+ def test_parity_many_items(self):
314
+ tokenizer = AutoTokenizer.from_pretrained(TEST_MODEL_NAME)
315
+ query = "Rate this option from 1 to 5:"
316
+ items = [f" Option {i}" for i in range(10)]
317
+ labels = [" 1", " 2", " 3", " 4", " 5"]
318
+ label_ids = [tokenizer.encode(lb, add_special_tokens=False)[0] for lb in labels]
319
+ self._compare_scores(query, items, label_ids, test_name="many_items")
320
+
321
+
322
+ class TestMultiItemScoringClassificationParity(CustomTestCase):
323
+ """Test that MIS multi-item batching matches single-item MIS scoring.
324
+
325
+ Both paths use the MIS engine (with delimiter tokens in the attention
326
+ context). The reference scores each item individually so each gets its
327
+ own forward pass; the batched path packs all items into one pass.
328
+ This isolates the MIS batching logic from the delimiter-presence effect.
329
+ """
330
+
331
+ NUM_LABELS = _CLS_NUM_LABELS
332
+
333
+ @classmethod
334
+ def setUpClass(cls):
335
+ cls.engine = Engine(
336
+ model_path=TEST_CLASSIFICATION_BASE_MODEL,
337
+ disable_radix_cache=True,
338
+ chunked_prefill_size=-1,
339
+ enable_mis=True,
340
+ attention_backend="flashinfer",
341
+ mem_fraction_static=0.15,
342
+ )
343
+
344
+ @classmethod
345
+ def tearDownClass(cls):
346
+ if cls.engine is not None:
347
+ cls.engine.shutdown()
348
+ torch.cuda.empty_cache()
349
+
350
+ def _compare_scores(self, query, items, apply_softmax=True, test_name=""):
351
+ """Compare MIS batched vs MIS single-item scoring results."""
352
+ single_scores = []
353
+ for item in items:
354
+ result = self.engine.score(
355
+ query=query,
356
+ items=[item],
357
+ apply_softmax=apply_softmax,
358
+ ).scores
359
+ single_scores.append(result[0])
360
+
361
+ batched_scores = self.engine.score(
362
+ query=query,
363
+ items=items,
364
+ apply_softmax=apply_softmax,
365
+ ).scores
366
+
367
+ self.assertEqual(
368
+ len(batched_scores), len(single_scores), f"{test_name}: count mismatch"
369
+ )
370
+ for i, (bs, ss) in enumerate(zip(batched_scores, single_scores)):
371
+ self.assertEqual(len(bs), len(ss), f"{test_name}: item {i} length mismatch")
372
+ for j, (b, s) in enumerate(zip(bs, ss)):
373
+ self.assertAlmostEqual(
374
+ b,
375
+ s,
376
+ places=1,
377
+ msg=f"{test_name}: item {i} label {j}: batched={b} vs single={s}",
378
+ )
379
+
380
+ def test_parity_basic(self):
381
+ query = "Rate this option:"
382
+ items = [" Option A", " Option B", " Option C"]
383
+ self._compare_scores(query, items, test_name="cls_basic")
384
+
385
+ def test_parity_tokenized_inputs(self):
386
+ tokenizer = AutoTokenizer.from_pretrained(TEST_CLASSIFICATION_BASE_MODEL)
387
+ query_ids = tokenizer.encode("Rate this option:", add_special_tokens=False)
388
+ items_ids = [
389
+ tokenizer.encode(item, add_special_tokens=False)
390
+ for item in [" Option X", " Option Y"]
391
+ ]
392
+ self._compare_scores(query_ids, items_ids, test_name="cls_tokenized")
393
+
394
+ def test_parity_without_softmax(self):
395
+ query = "The weather today is"
396
+ items = [" sunny", " cloudy", " rainy"]
397
+ self._compare_scores(
398
+ query, items, apply_softmax=False, test_name="cls_no_softmax"
399
+ )
400
+
401
+ def test_parity_many_items(self):
402
+ query = "Classify this option:"
403
+ items = [f" Option {i}" for i in range(10)]
404
+ self._compare_scores(query, items, test_name="cls_many_items")
405
+
406
+
407
+ class TestMultiItemScoringClassificationMISvsNonMIS(CustomTestCase):
408
+ """Test that MIS single-item approximates non-MIS single-item.
409
+
410
+ The MIS path inserts delimiter tokens into the attention context,
411
+ which slightly perturbs hidden states. After softmax the scores
412
+ should still be close. Uses places=1 (±0.05) tolerance.
413
+
414
+ Runs as a separate class so each engine is created and destroyed
415
+ independently to avoid GPU OOM.
416
+ """
417
+
418
+ def test_mis_single_vs_non_mis(self):
419
+ non_mis_engine = Engine(
420
+ model_path=TEST_CLASSIFICATION_BASE_MODEL,
421
+ disable_radix_cache=True,
422
+ mem_fraction_static=0.15,
423
+ )
424
+ try:
425
+ query = "Rate this option:"
426
+ items = [" Option A", " Option B", " Option C"]
427
+ non_mis_scores = non_mis_engine.score(
428
+ query=query,
429
+ items=items,
430
+ apply_softmax=True,
431
+ ).scores
432
+ finally:
433
+ non_mis_engine.shutdown()
434
+ torch.cuda.empty_cache()
435
+
436
+ mis_engine = Engine(
437
+ model_path=TEST_CLASSIFICATION_BASE_MODEL,
438
+ disable_radix_cache=True,
439
+ chunked_prefill_size=-1,
440
+ enable_mis=True,
441
+ attention_backend="flashinfer",
442
+ mem_fraction_static=0.15,
443
+ )
444
+ try:
445
+ mis_scores = mis_engine.score(
446
+ query=query,
447
+ items=items,
448
+ apply_softmax=True,
449
+ ).scores
450
+ finally:
451
+ mis_engine.shutdown()
452
+ torch.cuda.empty_cache()
453
+
454
+ self.assertEqual(len(mis_scores), len(non_mis_scores))
455
+ for i, (ms, ns) in enumerate(zip(mis_scores, non_mis_scores)):
456
+ self.assertEqual(len(ms), len(ns))
457
+ for j, (m, n) in enumerate(zip(ms, ns)):
458
+ self.assertAlmostEqual(
459
+ m,
460
+ n,
461
+ places=1,
462
+ msg=f"item {i} label {j}: MIS={m} vs non-MIS={n}",
463
+ )
464
+
465
+
466
+ class TestMultiItemScoringClassificationAdvanced(CustomTestCase):
467
+ """Advanced MIS tests for classification models: score distinctness,
468
+ determinism, and concurrent request handling."""
469
+
470
+ NUM_LABELS = _CLS_NUM_LABELS
471
+
472
+ @classmethod
473
+ def setUpClass(cls):
474
+ cls.engine = Engine(
475
+ model_path=TEST_CLASSIFICATION_BASE_MODEL,
476
+ disable_radix_cache=True,
477
+ chunked_prefill_size=-1,
478
+ enable_mis=True,
479
+ attention_backend="flashinfer",
480
+ mem_fraction_static=0.15,
481
+ )
482
+
483
+ @classmethod
484
+ def tearDownClass(cls):
485
+ if cls.engine is not None:
486
+ cls.engine.shutdown()
487
+ torch.cuda.empty_cache()
488
+
489
+ def test_items_produce_distinct_scores(self):
490
+ """Different items must produce different score vectors.
491
+
492
+ Core regression test: before the delimiter-index fix, all items got
493
+ identical scores because the MIS attention mask only let delimiter
494
+ tokens attend to the query prefix.
495
+ """
496
+ query = "Rate each option:"
497
+ items = [
498
+ "Option A is about cats",
499
+ "Option B is about dogs",
500
+ "Option C is about fish",
501
+ ]
502
+
503
+ scores = self.engine.score(query=query, items=items).scores
504
+
505
+ self.assertEqual(len(scores), len(items))
506
+ all_identical = all(scores[0] == s for s in scores[1:])
507
+ self.assertFalse(
508
+ all_identical,
509
+ f"All {len(items)} items returned identical scores — "
510
+ f"MIS delimiter indexing is broken. Scores: {scores[0]}",
511
+ )
512
+
513
+ def test_many_items_distinct(self):
514
+ """Stress test: 15 items should not all produce identical scores."""
515
+ query = "Classify each city:"
516
+ items = [f"City {i}" for i in range(15)]
517
+
518
+ scores = self.engine.score(query=query, items=items).scores
519
+
520
+ self.assertEqual(len(scores), len(items))
521
+ for score_list in scores:
522
+ self.assertEqual(len(score_list), self.NUM_LABELS)
523
+
524
+ unique_count = len({tuple(s) for s in scores})
525
+ self.assertGreater(unique_count, 1, "All 15 items returned identical scores")
526
+
527
+ def test_deterministic(self):
528
+ """Identical requests should return identical scores."""
529
+ query = "Evaluate:"
530
+ items = ["alpha", "beta", "gamma"]
531
+
532
+ scores1 = self.engine.score(query=query, items=items).scores
533
+ scores2 = self.engine.score(query=query, items=items).scores
534
+
535
+ self.assertEqual(
536
+ scores1, scores2, "Identical inputs must produce identical scores"
537
+ )
538
+
539
+ def test_concurrent_requests(self):
540
+ """Concurrent MIS requests must produce the same scores as sequential.
541
+
542
+ Runs each request sequentially to get baseline scores, then runs all
543
+ concurrently and asserts the results match. This catches cross-request
544
+ contamination when multiple MIS requests share a GPU batch.
545
+ """
546
+ test_cases = [
547
+ {"query": "Is this a fruit?", "items": ["apple", "car", "banana"]},
548
+ {"query": "Is this an animal?", "items": ["dog", "table"]},
549
+ {
550
+ "query": "Is this a country?",
551
+ "items": ["France", "pizza", "Japan", "chair"],
552
+ },
553
+ {"query": "Is this a color?", "items": ["red"]},
554
+ ]
555
+
556
+ # Sequential baseline
557
+ sequential_scores = []
558
+ for tc in test_cases:
559
+ result = self.engine.score(query=tc["query"], items=tc["items"])
560
+ sequential_scores.append(result.scores)
561
+
562
+ # Concurrent execution
563
+ async def _gather():
564
+ return await asyncio.gather(
565
+ *(
566
+ self.engine.async_score(query=tc["query"], items=tc["items"])
567
+ for tc in test_cases
568
+ )
569
+ )
570
+
571
+ concurrent_results = self.engine.loop.run_until_complete(_gather())
572
+
573
+ for idx, (tc, seq_scores, conc_result) in enumerate(
574
+ zip(test_cases, sequential_scores, concurrent_results)
575
+ ):
576
+ conc_scores = conc_result.scores
577
+ self.assertEqual(
578
+ len(conc_scores),
579
+ len(seq_scores),
580
+ f"Case {idx}: count mismatch",
581
+ )
582
+ for i, (cs, ss) in enumerate(zip(conc_scores, seq_scores)):
583
+ self.assertEqual(
584
+ len(cs),
585
+ len(ss),
586
+ f"Case {idx} item {i}: label count mismatch",
587
+ )
588
+ for j, (c, s) in enumerate(zip(cs, ss)):
589
+ self.assertAlmostEqual(
590
+ c,
591
+ s,
592
+ places=1,
593
+ msg=f"Case {idx} item {i} label {j}: "
594
+ f"concurrent={c} vs sequential={s}",
595
+ )
596
+
597
+
598
+ if __name__ == "__main__":
599
+ unittest.main()
asian_ai/performance/SGLang/test/registered/prefill_only/test_openai_embedding.py ADDED
@@ -0,0 +1,200 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+ import unittest
3
+
4
+ import openai
5
+
6
+ from sglang.srt.utils import kill_process_tree
7
+ from sglang.test.ci.ci_register import register_amd_ci, register_cuda_ci
8
+ from sglang.test.test_utils import (
9
+ DEFAULT_SMALL_EMBEDDING_MODEL_NAME_FOR_TEST,
10
+ DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH,
11
+ DEFAULT_URL_FOR_TEST,
12
+ CustomTestCase,
13
+ popen_launch_server,
14
+ )
15
+
16
+ register_cuda_ci(est_time=91, stage="base-b", runner_config="1-gpu-small")
17
+ register_amd_ci(est_time=141, suite="stage-b-test-1-gpu-small-amd")
18
+
19
+
20
+ class TestOpenAIEmbedding(CustomTestCase):
21
+ @classmethod
22
+ def setUpClass(cls):
23
+ cls.model = DEFAULT_SMALL_EMBEDDING_MODEL_NAME_FOR_TEST
24
+ cls.base_url = DEFAULT_URL_FOR_TEST
25
+ cls.api_key = "sk-123456"
26
+
27
+ # Configure embedding-specific args
28
+ other_args = ["--is-embedding", "--enable-metrics"]
29
+ cls.process = popen_launch_server(
30
+ cls.model,
31
+ cls.base_url,
32
+ timeout=DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH,
33
+ api_key=cls.api_key,
34
+ other_args=other_args,
35
+ )
36
+ cls.base_url += "/v1"
37
+
38
+ @classmethod
39
+ def tearDownClass(cls):
40
+ kill_process_tree(cls.process.pid)
41
+
42
+ def test_embedding_single(self):
43
+ """Test single embedding request"""
44
+ client = openai.Client(api_key=self.api_key, base_url=self.base_url)
45
+ response = client.embeddings.create(model=self.model, input="Hello world")
46
+ self.assertEqual(len(response.data), 1)
47
+ self.assertTrue(len(response.data[0].embedding) > 0)
48
+
49
+ def test_embedding_batch(self):
50
+ """Test batch embedding request"""
51
+ client = openai.Client(api_key=self.api_key, base_url=self.base_url)
52
+ response = client.embeddings.create(
53
+ model=self.model, input=["Hello world", "Test text"]
54
+ )
55
+ self.assertEqual(len(response.data), 2)
56
+ self.assertTrue(len(response.data[0].embedding) > 0)
57
+ self.assertTrue(len(response.data[1].embedding) > 0)
58
+
59
+ def test_embedding_single_batch_str(self):
60
+ """Test embedding with a List[str] and length equals to 1"""
61
+ client = openai.Client(api_key=self.api_key, base_url=self.base_url)
62
+ response = client.embeddings.create(model=self.model, input=["Hello world"])
63
+ self.assertEqual(len(response.data), 1)
64
+ self.assertTrue(len(response.data[0].embedding) > 0)
65
+
66
+ def test_embedding_single_int_list(self):
67
+ """Test embedding with a List[int] or List[List[int]]]"""
68
+ client = openai.Client(api_key=self.api_key, base_url=self.base_url)
69
+ response = client.embeddings.create(
70
+ model=self.model,
71
+ input=[[15339, 314, 703, 284, 612, 262, 10658, 10188, 286, 2061]],
72
+ )
73
+ self.assertEqual(len(response.data), 1)
74
+ self.assertTrue(len(response.data[0].embedding) > 0)
75
+
76
+ response = client.embeddings.create(
77
+ model=self.model,
78
+ input=[15339, 314, 703, 284, 612, 262, 10658, 10188, 286, 2061],
79
+ )
80
+ self.assertEqual(len(response.data), 1)
81
+ self.assertTrue(len(response.data[0].embedding) > 0)
82
+
83
+ def test_empty_string_embedding(self):
84
+ """Test embedding an empty string."""
85
+
86
+ client = openai.Client(api_key=self.api_key, base_url=self.base_url)
87
+
88
+ # Text embedding example with empty string
89
+ text = ""
90
+ # Expect a BadRequestError for empty input
91
+ with self.assertRaises(openai.BadRequestError) as cm:
92
+ client.embeddings.create(
93
+ model=self.model,
94
+ input=text,
95
+ )
96
+ # check the status code
97
+ self.assertEqual(cm.exception.status_code, 400)
98
+
99
+ def test_embedding_with_dimensions_parameter(self):
100
+ """Test that non-Matryoshka models reject dimensions parameter."""
101
+ client = openai.Client(api_key=self.api_key, base_url=self.base_url)
102
+
103
+ # Test that specifying dimensions fails for non-Matryoshka models
104
+ with self.assertRaises(openai.BadRequestError) as cm:
105
+ client.embeddings.create(
106
+ model=self.model, input="Hello world", dimensions=512
107
+ )
108
+
109
+ self.assertEqual(cm.exception.status_code, 400)
110
+
111
+
112
+ class TestMatryoshkaEmbeddingModel(CustomTestCase):
113
+ """Test class for Model that supports Matryoshka embedding functionality, using OpenAI API."""
114
+
115
+ @classmethod
116
+ def setUpClass(cls):
117
+ cls.model = DEFAULT_SMALL_EMBEDDING_MODEL_NAME_FOR_TEST
118
+ cls.base_url = DEFAULT_URL_FOR_TEST
119
+ cls.api_key = "sk-123456"
120
+ cls.matryoshka_dims = [128, 256, 512, 768, 1024]
121
+
122
+ # Configure embedding-specific args with Matryoshka support via json_model_override_args
123
+ matryoshka_config = {
124
+ "is_matryoshka": True,
125
+ "matryoshka_dimensions": cls.matryoshka_dims,
126
+ }
127
+ other_args = [
128
+ "--is-embedding",
129
+ "--enable-metrics",
130
+ "--json-model-override-args",
131
+ json.dumps(matryoshka_config),
132
+ ]
133
+ cls.process = popen_launch_server(
134
+ cls.model,
135
+ cls.base_url,
136
+ timeout=DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH,
137
+ api_key=cls.api_key,
138
+ other_args=other_args,
139
+ )
140
+ cls.base_url += "/v1"
141
+
142
+ @classmethod
143
+ def tearDownClass(cls):
144
+ if hasattr(cls, "process"):
145
+ kill_process_tree(cls.process.pid)
146
+
147
+ def test_matryoshka_embedding_valid_dimensions(self):
148
+ """Test Matryoshka embedding with valid dimensions."""
149
+ client = openai.Client(api_key=self.api_key, base_url=self.base_url)
150
+
151
+ # Test with various valid dimensions
152
+ for dimensions in self.matryoshka_dims:
153
+ with self.subTest(dimensions=dimensions):
154
+ response = client.embeddings.create(
155
+ model=self.model, input="Hello world", dimensions=dimensions
156
+ )
157
+ self.assertEqual(len(response.data), 1)
158
+ self.assertEqual(len(response.data[0].embedding), dimensions)
159
+
160
+ def test_matryoshka_embedding_batch_same_dimensions(self):
161
+ """Test Matryoshka embedding with batch input and same dimensions."""
162
+ client = openai.Client(api_key=self.api_key, base_url=self.base_url)
163
+
164
+ response = client.embeddings.create(
165
+ model=self.model,
166
+ input=["Hello world", "Test text", "Another example"],
167
+ dimensions=256,
168
+ )
169
+
170
+ self.assertEqual(len(response.data), 3)
171
+ for embedding_data in response.data:
172
+ self.assertEqual(len(embedding_data.embedding), 256)
173
+
174
+ def test_matryoshka_embedding_no_dimensions(self):
175
+ """Test embedding without specifying dimensions (should use full size)."""
176
+ client = openai.Client(api_key=self.api_key, base_url=self.base_url)
177
+
178
+ response = client.embeddings.create(model=self.model, input="Hello world")
179
+
180
+ self.assertEqual(len(response.data), 1)
181
+
182
+ # Should return full embedding size when no dimensions specified
183
+ self.assertEqual(len(response.data[0].embedding), 1536)
184
+
185
+ def test_matryoshka_embedding_invalid_dimensions(self):
186
+ """Test Matryoshka embedding with invalid dimensions."""
187
+ client = openai.Client(api_key=self.api_key, base_url=self.base_url)
188
+
189
+ for dimensions in [100, 0, -1, 10000]:
190
+ with self.assertRaises(openai.BadRequestError) as cm:
191
+ client.embeddings.create(
192
+ model=self.model,
193
+ input="Hello world",
194
+ dimensions=dimensions,
195
+ )
196
+ self.assertEqual(cm.exception.status_code, 400)
197
+
198
+
199
+ if __name__ == "__main__":
200
+ unittest.main()
asian_ai/performance/SGLang/test/registered/prefill_only/test_pooled_hidden_states.py ADDED
@@ -0,0 +1,433 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Tests for the return_pooled_hidden_states feature on the scoring API.
2
+
3
+ Covers both Engine-level (Python API) and HTTP-level (/v1/score) integration:
4
+
5
+ TestPooledHiddenStatesEngine — SeqCls model, single-item scoring
6
+ TestPooledHiddenStatesMISEngine — SeqCls model, MIS delimiter mode
7
+ TestPooledHiddenStatesHTTP — HTTP layer serialization round-trip
8
+ TestPooledHiddenStatesCausalLMRejection — CausalLM must reject the flag
9
+
10
+ Each test class spins up its own Engine or server so GPU memory is isolated.
11
+ """
12
+
13
+ import json
14
+ import unittest
15
+
16
+ import requests
17
+ import torch
18
+
19
+ from sglang.srt.entrypoints.engine import Engine
20
+ from sglang.srt.utils import is_hip, kill_process_tree
21
+ from sglang.test.ci.ci_register import register_amd_ci, register_cuda_ci
22
+ from sglang.test.test_utils import (
23
+ DEFAULT_SMALL_MODEL_NAME_FOR_TEST,
24
+ DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH,
25
+ DEFAULT_URL_FOR_TEST,
26
+ CustomTestCase,
27
+ popen_launch_server,
28
+ )
29
+
30
+ register_cuda_ci(est_time=100, stage="base-b", runner_config="1-gpu-small")
31
+ register_amd_ci(est_time=100, suite="stage-b-test-1-gpu-small-amd")
32
+
33
+
34
+ _SEQCLS_MODEL = "Qwen/Qwen3-0.6B"
35
+ _CAUSAL_LM_MODEL = DEFAULT_SMALL_MODEL_NAME_FOR_TEST
36
+ _NUM_LABELS = 4
37
+
38
+ # Local overrides for offline testing (no network). Set to None to use HF hub.
39
+ _LOCAL_SEQCLS_MODEL = (
40
+ "/shared/public/elr-models/Qwen/Qwen3-0.6B/e6de91484c29aa9480d55605af694f39b081c455"
41
+ )
42
+ _LOCAL_CAUSAL_LM_MODEL = "/shared/public/elr-models/meta-llama/Llama-3.2-1B-Instruct/e9f8effbab1cbdc515c11ee6e098e3d5a9f51e14"
43
+
44
+ import os
45
+
46
+ if _LOCAL_SEQCLS_MODEL and os.path.isdir(_LOCAL_SEQCLS_MODEL):
47
+ _SEQCLS_MODEL = _LOCAL_SEQCLS_MODEL
48
+ if _LOCAL_CAUSAL_LM_MODEL and os.path.isdir(_LOCAL_CAUSAL_LM_MODEL):
49
+ _CAUSAL_LM_MODEL = _LOCAL_CAUSAL_LM_MODEL
50
+
51
+
52
+ # ---------------------------------------------------------------------------
53
+ # Engine — single-item scoring (no MIS)
54
+ # ---------------------------------------------------------------------------
55
+
56
+
57
+ class TestPooledHiddenStatesEngine(CustomTestCase):
58
+ """Validates return_pooled_hidden_states through the Engine Python API.
59
+
60
+ Uses Qwen3ForSequenceClassification with a random head so we only care
61
+ about shape and pipeline plumbing, not numerical accuracy.
62
+ """
63
+
64
+ @classmethod
65
+ def setUpClass(cls):
66
+ cls.engine = Engine(
67
+ model_path=_SEQCLS_MODEL,
68
+ disable_radix_cache=True,
69
+ json_model_override_args=json.dumps(
70
+ {
71
+ "architectures": ["Qwen3ForSequenceClassification"],
72
+ "num_labels": _NUM_LABELS,
73
+ }
74
+ ),
75
+ mem_fraction_static=0.15,
76
+ )
77
+
78
+ @classmethod
79
+ def tearDownClass(cls):
80
+ if hasattr(cls, "engine") and cls.engine:
81
+ cls.engine.shutdown()
82
+ torch.cuda.empty_cache()
83
+
84
+ def test_phs_returned_when_requested(self):
85
+ """Pooled hidden states are present and shaped correctly."""
86
+ result = self.engine.score(
87
+ query="Rate each:",
88
+ items=["Good", "Bad"],
89
+ return_pooled_hidden_states=True,
90
+ )
91
+ self.assertIsNotNone(result.pooled_hidden_states)
92
+ self.assertEqual(len(result.pooled_hidden_states), 2)
93
+ for phs in result.pooled_hidden_states:
94
+ self.assertIsInstance(phs, torch.Tensor)
95
+ self.assertEqual(phs.dim(), 1)
96
+ self.assertGreater(phs.shape[0], 0)
97
+
98
+ def test_phs_none_when_not_requested(self):
99
+ """Without the flag, pooled_hidden_states must be None."""
100
+ result = self.engine.score(
101
+ query="Rate each:",
102
+ items=["Good", "Bad"],
103
+ return_pooled_hidden_states=False,
104
+ )
105
+ self.assertIsNone(result.pooled_hidden_states)
106
+
107
+ def test_phs_shape_is_consistent(self):
108
+ """PHS tensors for different items share the same hidden dimension."""
109
+ result = self.engine.score(
110
+ query="Evaluate:",
111
+ items=["Alpha", "Beta", "Gamma"],
112
+ return_pooled_hidden_states=True,
113
+ )
114
+ self.assertIsNotNone(result.pooled_hidden_states)
115
+ dims = {phs.shape[0] for phs in result.pooled_hidden_states}
116
+ self.assertEqual(len(dims), 1, "All PHS vectors must share the same hidden dim")
117
+ self.assertGreater(dims.pop(), 0)
118
+
119
+ def test_phs_count_matches_items(self):
120
+ """Number of PHS tensors equals number of items for various batch sizes."""
121
+ for n in [1, 3, 5]:
122
+ with self.subTest(n=n):
123
+ result = self.engine.score(
124
+ query="Classify:",
125
+ items=[f"Item {i}" for i in range(n)],
126
+ return_pooled_hidden_states=True,
127
+ )
128
+ self.assertIsNotNone(result.pooled_hidden_states)
129
+ self.assertEqual(len(result.pooled_hidden_states), n)
130
+
131
+ def test_phs_on_cpu(self):
132
+ """Returned tensors live on CPU (no GPU references leak to caller)."""
133
+ result = self.engine.score(
134
+ query="Check device:",
135
+ items=["Test"],
136
+ return_pooled_hidden_states=True,
137
+ )
138
+ for phs in result.pooled_hidden_states:
139
+ self.assertEqual(str(phs.device), "cpu")
140
+
141
+ def test_phs_deterministic(self):
142
+ """Identical requests produce identical PHS tensors."""
143
+ kwargs = dict(
144
+ query="Evaluate:", items=["A", "B"], return_pooled_hidden_states=True
145
+ )
146
+ phs1 = self.engine.score(**kwargs).pooled_hidden_states
147
+ phs2 = self.engine.score(**kwargs).pooled_hidden_states
148
+ for t1, t2 in zip(phs1, phs2):
149
+ self.assertTrue(
150
+ torch.allclose(t1, t2, atol=1e-5),
151
+ "Pooled hidden states differ across identical requests",
152
+ )
153
+
154
+ def test_scores_unaffected_by_phs_flag(self):
155
+ """The phs flag must not change the scores themselves (fp16 tolerance)."""
156
+ kwargs = dict(query="Rate:", items=["X", "Y", "Z"], apply_softmax=True)
157
+ scores_without = self.engine.score(
158
+ **kwargs, return_pooled_hidden_states=False
159
+ ).scores
160
+ scores_with = self.engine.score(
161
+ **kwargs, return_pooled_hidden_states=True
162
+ ).scores
163
+ self.assertEqual(len(scores_without), len(scores_with))
164
+ for row_a, row_b in zip(scores_without, scores_with):
165
+ for a, b in zip(row_a, row_b):
166
+ self.assertAlmostEqual(a, b, places=2)
167
+
168
+ def test_phs_with_tokenized_inputs(self):
169
+ """Pre-tokenized inputs also return PHS correctly."""
170
+ from transformers import AutoTokenizer
171
+
172
+ tok = AutoTokenizer.from_pretrained(_SEQCLS_MODEL)
173
+ query, items = "Evaluate:", ["Alpha", "Beta"]
174
+ result = self.engine.score(
175
+ query=tok.encode(query),
176
+ items=[tok.encode(i) for i in items],
177
+ return_pooled_hidden_states=True,
178
+ )
179
+ self.assertIsNotNone(result.pooled_hidden_states)
180
+ self.assertEqual(len(result.pooled_hidden_states), 2)
181
+
182
+
183
+ # ---------------------------------------------------------------------------
184
+ # Engine — MIS delimiter mode
185
+ # ---------------------------------------------------------------------------
186
+
187
+
188
+ @unittest.skipIf(
189
+ is_hip(),
190
+ "Multi-Item Scoring (enable_mis) requires the flashinfer prefill/decode "
191
+ "backend, which is NVIDIA-only.",
192
+ )
193
+ class TestPooledHiddenStatesMISEngine(CustomTestCase):
194
+ """Validates return_pooled_hidden_states in MIS (delimiter) scoring mode.
195
+
196
+ MIS packs all items into one sequence; the PHS at each delimiter position
197
+ should be returned per-item.
198
+ """
199
+
200
+ @classmethod
201
+ def setUpClass(cls):
202
+ cls.engine = Engine(
203
+ model_path=_SEQCLS_MODEL,
204
+ disable_radix_cache=True,
205
+ chunked_prefill_size=-1,
206
+ enable_mis=True,
207
+ json_model_override_args=json.dumps(
208
+ {
209
+ "architectures": ["Qwen3ForSequenceClassification"],
210
+ "num_labels": _NUM_LABELS,
211
+ }
212
+ ),
213
+ mem_fraction_static=0.15,
214
+ )
215
+
216
+ @classmethod
217
+ def tearDownClass(cls):
218
+ if hasattr(cls, "engine") and cls.engine:
219
+ cls.engine.shutdown()
220
+ torch.cuda.empty_cache()
221
+
222
+ def test_mis_phs_count_matches_items(self):
223
+ """MIS must return one PHS tensor per item."""
224
+ items = ["Option A", "Option B", "Option C"]
225
+ result = self.engine.score(
226
+ query="Rate each:", items=items, return_pooled_hidden_states=True
227
+ )
228
+ self.assertIsNotNone(result.pooled_hidden_states)
229
+ self.assertEqual(len(result.pooled_hidden_states), len(items))
230
+
231
+ def test_mis_phs_none_when_not_requested(self):
232
+ result = self.engine.score(
233
+ query="Rate each:",
234
+ items=["A", "B"],
235
+ return_pooled_hidden_states=False,
236
+ )
237
+ self.assertIsNone(result.pooled_hidden_states)
238
+
239
+ def test_mis_phs_are_tensors_on_cpu(self):
240
+ result = self.engine.score(
241
+ query="Classify:", items=["X", "Y"], return_pooled_hidden_states=True
242
+ )
243
+ for phs in result.pooled_hidden_states:
244
+ self.assertIsInstance(phs, torch.Tensor)
245
+ self.assertEqual(str(phs.device), "cpu")
246
+
247
+ def test_mis_phs_different_items_different_hidden_states(self):
248
+ """Different items should produce distinct PHS vectors."""
249
+ items = [
250
+ "Option A is about cats",
251
+ "Option B is about dogs",
252
+ "Option C is about fish",
253
+ ]
254
+ result = self.engine.score(
255
+ query="Classify:", items=items, return_pooled_hidden_states=True
256
+ )
257
+ phs = result.pooled_hidden_states
258
+ self.assertFalse(
259
+ all(torch.allclose(phs[0], p, atol=1e-6) for p in phs[1:]),
260
+ "All MIS items returned identical hidden states",
261
+ )
262
+
263
+ def test_mis_single_item(self):
264
+ """Single item through MIS path still returns one PHS tensor."""
265
+ result = self.engine.score(
266
+ query="Evaluate:", items=["Only one"], return_pooled_hidden_states=True
267
+ )
268
+ self.assertIsNotNone(result.pooled_hidden_states)
269
+ self.assertEqual(len(result.pooled_hidden_states), 1)
270
+
271
+ def test_mis_many_items(self):
272
+ """10 items all produce PHS tensors of consistent shape."""
273
+ items = [f"Item {i}" for i in range(10)]
274
+ result = self.engine.score(
275
+ query="Classify:", items=items, return_pooled_hidden_states=True
276
+ )
277
+ self.assertIsNotNone(result.pooled_hidden_states)
278
+ self.assertEqual(len(result.pooled_hidden_states), len(items))
279
+ shapes = {phs.shape for phs in result.pooled_hidden_states}
280
+ self.assertEqual(len(shapes), 1, "MIS PHS shapes should be uniform")
281
+
282
+ def test_mis_scores_unaffected_by_phs_flag(self):
283
+ """Enabling PHS does not alter the returned scores (fp16 tolerance)."""
284
+ kwargs = dict(
285
+ query="Rate:", items=["Alpha", "Beta", "Gamma"], apply_softmax=True
286
+ )
287
+ scores_without = self.engine.score(
288
+ **kwargs, return_pooled_hidden_states=False
289
+ ).scores
290
+ scores_with = self.engine.score(
291
+ **kwargs, return_pooled_hidden_states=True
292
+ ).scores
293
+ for row_a, row_b in zip(scores_without, scores_with):
294
+ for a, b in zip(row_a, row_b):
295
+ self.assertAlmostEqual(a, b, places=2)
296
+
297
+
298
+ # ---------------------------------------------------------------------------
299
+ # CausalLM rejection
300
+ # ---------------------------------------------------------------------------
301
+
302
+
303
+ class TestPooledHiddenStatesCausalLMRejection(CustomTestCase):
304
+ """CausalLM models must reject return_pooled_hidden_states=True."""
305
+
306
+ @classmethod
307
+ def setUpClass(cls):
308
+ cls.engine = Engine(model_path=_CAUSAL_LM_MODEL)
309
+
310
+ @classmethod
311
+ def tearDownClass(cls):
312
+ if hasattr(cls, "engine") and cls.engine:
313
+ cls.engine.shutdown()
314
+ torch.cuda.empty_cache()
315
+
316
+ def test_causal_lm_rejects_phs(self):
317
+ """ValueError raised when requesting PHS from a CausalLM."""
318
+ with self.assertRaises(ValueError) as ctx:
319
+ self.engine.score(
320
+ query="Test",
321
+ items=["Item"],
322
+ label_token_ids=[1, 2],
323
+ return_pooled_hidden_states=True,
324
+ )
325
+ self.assertIn("CausalLM", str(ctx.exception))
326
+
327
+ def test_causal_lm_without_phs_still_works(self):
328
+ """Baseline: CausalLM scoring without the flag works fine."""
329
+ result = self.engine.score(
330
+ query="Test",
331
+ items=["Item"],
332
+ label_token_ids=[1, 2],
333
+ apply_softmax=True,
334
+ return_pooled_hidden_states=False,
335
+ )
336
+ self.assertEqual(len(result.scores), 1)
337
+ self.assertIsNone(result.pooled_hidden_states)
338
+
339
+
340
+ # ---------------------------------------------------------------------------
341
+ # HTTP layer
342
+ # ---------------------------------------------------------------------------
343
+
344
+
345
+ class TestPooledHiddenStatesHTTP(CustomTestCase):
346
+ """HTTP integration: /v1/score with return_pooled_hidden_states.
347
+
348
+ Validates that the Pydantic schema, JSON serialization, and ORJSONResponse
349
+ round-trip preserves the pooled hidden states as nested lists.
350
+ """
351
+
352
+ @classmethod
353
+ def setUpClass(cls):
354
+ cls.model = _SEQCLS_MODEL
355
+ cls.base_url = DEFAULT_URL_FOR_TEST
356
+ cls.process = popen_launch_server(
357
+ cls.model,
358
+ cls.base_url,
359
+ timeout=DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH,
360
+ other_args=[
361
+ "--disable-radix-cache",
362
+ "--json-model-override-args",
363
+ json.dumps(
364
+ {
365
+ "architectures": ["Qwen3ForSequenceClassification"],
366
+ "num_labels": _NUM_LABELS,
367
+ }
368
+ ),
369
+ "--mem-fraction-static",
370
+ "0.15",
371
+ ],
372
+ )
373
+
374
+ @classmethod
375
+ def tearDownClass(cls):
376
+ if hasattr(cls, "process") and cls.process:
377
+ kill_process_tree(cls.process.pid)
378
+
379
+ def _post(self, payload):
380
+ return requests.post(self.base_url + "/v1/score", json=payload)
381
+
382
+ def test_phs_in_response_json(self):
383
+ """Response includes pooled_hidden_states as nested float lists."""
384
+ resp = self._post(
385
+ {
386
+ "query": "Rate each:",
387
+ "items": ["Good", "Bad"],
388
+ "return_pooled_hidden_states": True,
389
+ "model": self.model,
390
+ }
391
+ )
392
+ self.assertEqual(resp.status_code, 200)
393
+ body = resp.json()
394
+ phs = body.get("pooled_hidden_states")
395
+ self.assertIsNotNone(phs)
396
+ self.assertEqual(len(phs), 2)
397
+ for item_phs in phs:
398
+ self.assertIsInstance(item_phs, list)
399
+ self.assertGreater(len(item_phs), 0)
400
+ for v in item_phs:
401
+ self.assertIsInstance(v, float)
402
+
403
+ def test_phs_absent_when_not_requested(self):
404
+ """Without the flag, pooled_hidden_states is null in JSON."""
405
+ resp = self._post(
406
+ {
407
+ "query": "Rate each:",
408
+ "items": ["Good"],
409
+ "model": self.model,
410
+ }
411
+ )
412
+ self.assertEqual(resp.status_code, 200)
413
+ body = resp.json()
414
+ self.assertIsNone(body.get("pooled_hidden_states"))
415
+
416
+ def test_phs_matches_item_count(self):
417
+ """Number of PHS vectors equals number of items."""
418
+ items = ["A", "B", "C", "D"]
419
+ resp = self._post(
420
+ {
421
+ "query": "Classify:",
422
+ "items": items,
423
+ "return_pooled_hidden_states": True,
424
+ "model": self.model,
425
+ }
426
+ )
427
+ self.assertEqual(resp.status_code, 200)
428
+ phs = resp.json()["pooled_hidden_states"]
429
+ self.assertEqual(len(phs), len(items))
430
+
431
+
432
+ if __name__ == "__main__":
433
+ unittest.main(verbosity=3)
asian_ai/performance/SGLang/test/registered/prefill_only/test_reward_models.py ADDED
@@ -0,0 +1,103 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import multiprocessing as mp
2
+ import unittest
3
+
4
+ import torch
5
+
6
+ from sglang.test.ci.ci_register import register_amd_ci, register_cuda_ci
7
+ from sglang.test.runners import HFRunner, SRTRunner
8
+ from sglang.test.test_utils import CustomTestCase
9
+
10
+ # Reward model tests
11
+
12
+ # Copyright 2023-2024 SGLang Team
13
+ # Licensed under the Apache License, Version 2.0 (the "License");
14
+ # you may not use this file except in compliance with the License.
15
+ # You may obtain a copy of the License at
16
+ #
17
+ # http://www.apache.org/licenses/LICENSE-2.0
18
+ #
19
+ # Unless required by applicable law or agreed to in writing, software
20
+ # distributed under the License is distributed on an "AS IS" BASIS,
21
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
22
+ # See the License for the specific language governing permissions and
23
+ # limitations under the License.
24
+ # ==============================================================================
25
+
26
+
27
+ register_cuda_ci(est_time=166, stage="base-b", runner_config="1-gpu-small")
28
+ register_amd_ci(est_time=132, suite="stage-b-test-1-gpu-small-amd-nondeterministic")
29
+
30
+ MODELS = [
31
+ ("LxzGordon/URM-LLaMa-3.1-8B", 1, 4e-2),
32
+ ("Skywork/Skywork-Reward-Llama-3.1-8B-v0.2", 1, 4e-2),
33
+ # Qwen3-based reward model (uses Qwen3ForSequenceClassification)
34
+ ("Skywork/Skywork-Reward-V2-Qwen3-0.6B", 1, 1.5e-1),
35
+ ]
36
+ TORCH_DTYPES = [torch.float16]
37
+
38
+ # PROMPT = "Jane has 12 apples. She gives 4 apples to her friend Mark, then buys 1 more apple, and finally splits all her apples equally among herself and her 2 siblings. How many apples does each person get?"
39
+ # RESPONSE1 = "1. Jane starts with 12 apples and gives 4 to Mark. 12 - 4 = 8. Jane now has 8 apples.\n2. Jane buys 1 more apple. 8 + 1 = 9. Jane now has 9 apples.\n3. Jane splits the 9 apples equally among herself and her 2 siblings (3 people in total). 9 ÷ 3 = 3 apples each. Each person gets 3 apples."
40
+ # RESPONSE2 = "1. Jane starts with 12 apples and gives 4 to Mark. 12 - 4 = 8. Jane now has 8 apples.\n2. Jane buys 1 more apple. 8 + 1 = 9. Jane now has 9 apples.\n3. Jane splits the 9 apples equally among her 2 siblings (2 people in total). 9 ÷ 2 = 4.5 apples each. Each person gets 4 apples."
41
+
42
+ PROMPT = (
43
+ "What is the range of the numeric output of a sigmoid node in a neural network?"
44
+ )
45
+ RESPONSE1 = "The output of a sigmoid node is bounded between -1 and 1."
46
+ RESPONSE2 = "The output of a sigmoid node is bounded between 0 and 1."
47
+
48
+ CONVS = [
49
+ [{"role": "user", "content": PROMPT}, {"role": "assistant", "content": RESPONSE1}],
50
+ [{"role": "user", "content": PROMPT}, {"role": "assistant", "content": RESPONSE2}],
51
+ ]
52
+
53
+
54
+ class TestRewardModels(CustomTestCase):
55
+
56
+ @classmethod
57
+ def setUpClass(cls):
58
+ mp.set_start_method("spawn", force=True)
59
+
60
+ def assert_close_reward_scores(
61
+ self,
62
+ convs,
63
+ model_path,
64
+ tp_size,
65
+ torch_dtype,
66
+ tolerance,
67
+ ) -> None:
68
+ with HFRunner(
69
+ model_path,
70
+ torch_dtype=torch_dtype,
71
+ model_type="reward",
72
+ ) as hf_runner:
73
+ hf_outputs = hf_runner.forward(convs)
74
+
75
+ with SRTRunner(
76
+ model_path,
77
+ torch_dtype=torch_dtype,
78
+ model_type="reward",
79
+ ) as srt_runner:
80
+ prompts = srt_runner.tokenizer.apply_chat_template(
81
+ convs, tokenize=False, return_dict=False
82
+ )
83
+ srt_outputs = srt_runner.forward(prompts)
84
+
85
+ hf_scores = torch.tensor(hf_outputs.scores)
86
+ srt_scores = torch.tensor(srt_outputs.scores)
87
+ print(f"{hf_scores=}")
88
+ print(f"{srt_scores=}")
89
+
90
+ assert torch.all(
91
+ abs(hf_scores - srt_scores) < tolerance
92
+ ), "reward scores are not all close"
93
+
94
+ def test_reward_scores(self):
95
+ for model, tp_size, tolerance in MODELS:
96
+ for torch_dtype in TORCH_DTYPES:
97
+ self.assert_close_reward_scores(
98
+ CONVS, model, tp_size, torch_dtype, tolerance
99
+ )
100
+
101
+
102
+ if __name__ == "__main__":
103
+ unittest.main()
asian_ai/performance/SGLang/test/registered/prefill_only/test_score_api.py ADDED
@@ -0,0 +1,234 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """HTTP layer tests for the /v1/score endpoint.
2
+
3
+ Two test classes, each with its own server instance:
4
+
5
+ TestCausalLMScoringHTTP — basic endpoint: schema defaults, response
6
+ structure, error rejection (no MIS)
7
+ TestCausalLMMISScoringHTTP — MIS mode: validates --enable-mis CLI flag
8
+ wiring and per-item output shape
9
+
10
+ Engine-level correctness (numerical accuracy, batching, edge cases) lives in
11
+ test_score_engine.py. These tests focus on the HTTP integration seam:
12
+ Pydantic schema defaults, FastAPI routing, and server argument wiring.
13
+ """
14
+
15
+ import os
16
+ import unittest
17
+
18
+ import requests
19
+
20
+ from sglang.srt.utils import kill_process_tree
21
+ from sglang.test.ci.ci_register import register_cuda_ci
22
+ from sglang.test.test_utils import (
23
+ DEFAULT_SMALL_MODEL_NAME_FOR_TEST,
24
+ DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH,
25
+ DEFAULT_URL_FOR_TEST,
26
+ CustomTestCase,
27
+ popen_launch_server,
28
+ )
29
+
30
+ register_cuda_ci(est_time=71, stage="base-b", runner_config="1-gpu-small")
31
+
32
+ _MODEL = os.environ.get("TEST_MODEL_NAME", DEFAULT_SMALL_MODEL_NAME_FOR_TEST)
33
+
34
+
35
+ # ---------------------------------------------------------------------------
36
+ # Basic scoring (no MIS delimiter)
37
+ # ---------------------------------------------------------------------------
38
+
39
+
40
+ class TestCausalLMScoringHTTP(CustomTestCase):
41
+ """Validates /v1/score HTTP integration — schema, defaults, and error handling.
42
+
43
+ Starts a plain CausalLM server (no --enable-mis) to test
44
+ the HTTP layer in isolation: response envelope shape, the apply_softmax
45
+ default (False), and Pydantic validation errors on malformed input.
46
+ """
47
+
48
+ @classmethod
49
+ def setUpClass(cls):
50
+ cls.model = _MODEL
51
+ cls.base_url = DEFAULT_URL_FOR_TEST
52
+ cls.process = popen_launch_server(
53
+ cls.model,
54
+ cls.base_url,
55
+ timeout=DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH,
56
+ )
57
+
58
+ @classmethod
59
+ def tearDownClass(cls):
60
+ if hasattr(cls, "process") and cls.process:
61
+ kill_process_tree(cls.process.pid)
62
+
63
+ def _post(self, payload):
64
+ return requests.post(self.base_url + "/v1/score", json=payload)
65
+
66
+ def test_response_envelope(self):
67
+ """Response JSON contains scores, model, and object='scoring'."""
68
+ resp = self._post(
69
+ {
70
+ "query": "The capital of France is",
71
+ "items": ["Paris", "Berlin"],
72
+ "label_token_ids": [1, 2],
73
+ "apply_softmax": True,
74
+ "model": self.model,
75
+ }
76
+ )
77
+ self.assertEqual(resp.status_code, 200)
78
+ body = resp.json()
79
+ self.assertIn("scores", body)
80
+ self.assertIn("model", body)
81
+ self.assertEqual(body["object"], "scoring")
82
+
83
+ def test_apply_softmax_false_by_default(self):
84
+ """Without apply_softmax=True, raw log-probs are returned (do not sum to 1)."""
85
+ resp = self._post(
86
+ {
87
+ "query": "The capital of France is",
88
+ "items": ["Paris"],
89
+ "label_token_ids": [1, 2],
90
+ # apply_softmax intentionally omitted — default is False
91
+ "model": self.model,
92
+ }
93
+ )
94
+ self.assertEqual(resp.status_code, 200)
95
+ scores = resp.json()["scores"]
96
+ self.assertEqual(len(scores), 1)
97
+ # Raw log-probs over a vocabulary subset do not sum to 1
98
+ self.assertNotAlmostEqual(sum(scores[0]), 1.0, places=3)
99
+
100
+ def test_apply_softmax_true_normalizes(self):
101
+ """With apply_softmax=True, scores form a valid probability distribution."""
102
+ resp = self._post(
103
+ {
104
+ "query": "The capital of France is",
105
+ "items": ["Paris", "Berlin", "Rome"],
106
+ "label_token_ids": [1, 2, 3],
107
+ "apply_softmax": True,
108
+ "model": self.model,
109
+ }
110
+ )
111
+ self.assertEqual(resp.status_code, 200)
112
+ for row in resp.json()["scores"]:
113
+ self.assertAlmostEqual(sum(row), 1.0, places=6)
114
+ for v in row:
115
+ self.assertGreaterEqual(v, 0.0)
116
+
117
+ def test_schema_rejection(self):
118
+ """Malformed payloads must be rejected with HTTP 4xx."""
119
+ bad_payloads = [
120
+ # label_token_ids must be List[int]
121
+ {
122
+ "query": "Q",
123
+ "items": ["X"],
124
+ "label_token_ids": "bad",
125
+ "model": self.model,
126
+ },
127
+ # items must be str / List[str] / List[List[int]], not int
128
+ {
129
+ "query": "Q",
130
+ "items": 42,
131
+ "label_token_ids": [1, 2],
132
+ "model": self.model,
133
+ },
134
+ ]
135
+ for payload in bad_payloads:
136
+ with self.subTest(payload=list(payload.keys())):
137
+ self.assertGreaterEqual(self._post(payload).status_code, 400)
138
+
139
+
140
+ # ---------------------------------------------------------------------------
141
+ # MIS scoring (with --enable-mis)
142
+ # ---------------------------------------------------------------------------
143
+
144
+
145
+ class TestCausalLMMISScoringHTTP(CustomTestCase):
146
+ """Validates /v1/score with --enable-mis.
147
+
148
+ Confirms that the CLI flag is correctly wired into ServerArgs and that the
149
+ endpoint returns one probability vector per item when items are
150
+ delimiter-packed into a single forward pass.
151
+ """
152
+
153
+ @classmethod
154
+ def setUpClass(cls):
155
+ cls.model = _MODEL
156
+ cls.base_url = DEFAULT_URL_FOR_TEST
157
+ cls.process = popen_launch_server(
158
+ cls.model,
159
+ cls.base_url,
160
+ timeout=DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH,
161
+ other_args=[
162
+ "--disable-radix-cache",
163
+ "--chunked-prefill-size",
164
+ "-1",
165
+ "--enable-mis",
166
+ "--attention-backend",
167
+ "flashinfer",
168
+ ],
169
+ )
170
+
171
+ @classmethod
172
+ def tearDownClass(cls):
173
+ if hasattr(cls, "process") and cls.process:
174
+ kill_process_tree(cls.process.pid)
175
+
176
+ def _score(self, query, items, label_token_ids):
177
+ resp = requests.post(
178
+ self.base_url + "/v1/score",
179
+ json={
180
+ "query": query,
181
+ "items": items,
182
+ "label_token_ids": label_token_ids,
183
+ "apply_softmax": True,
184
+ "model": self.model,
185
+ },
186
+ )
187
+ self.assertEqual(resp.status_code, 200)
188
+ return resp.json()
189
+
190
+ def test_one_probability_vector_per_item(self):
191
+ """Each item yields one softmax-normalised score vector."""
192
+ items = ["Sacramento", "San Jose", "San Francisco"]
193
+ label_token_ids = [9454, 2753]
194
+ scores = self._score("Is each the capital?", items, label_token_ids)["scores"]
195
+ self.assertEqual(len(scores), len(items))
196
+ for i, row in enumerate(scores):
197
+ self.assertEqual(len(row), len(label_token_ids))
198
+ self.assertAlmostEqual(sum(row), 1.0, places=6, msg=f"Item {i}")
199
+ for v in row:
200
+ self.assertGreaterEqual(v, 0.0)
201
+
202
+ def test_empty_items_returns_empty_scores(self):
203
+ result = self._score("Test query", [], [1, 2])
204
+ self.assertEqual(len(result["scores"]), 0)
205
+
206
+ def test_varying_item_counts(self):
207
+ """1, 2, 4, and 6 items all return the correct number of score vectors."""
208
+ label_token_ids = [1, 2, 3, 4, 5]
209
+ for items in (
210
+ ["Single item"],
211
+ ["Item 1", "Item 2"],
212
+ ["A", "B", "C", "D"],
213
+ ["X", "Y", "Z", "W", "V", "U"],
214
+ ):
215
+ with self.subTest(n=len(items)):
216
+ scores = self._score("Rate each:", items, label_token_ids)["scores"]
217
+ self.assertEqual(len(scores), len(items))
218
+ for row in scores:
219
+ self.assertEqual(len(row), len(label_token_ids))
220
+ self.assertAlmostEqual(sum(row), 1.0, places=6)
221
+
222
+ def test_deterministic(self):
223
+ """Back-to-back identical requests return identical scores."""
224
+ items, label_token_ids = ["Option A", "Option B", "Option C"], [1, 2, 3]
225
+ s1 = self._score("Choose:", items, label_token_ids)["scores"]
226
+ s2 = self._score("Choose:", items, label_token_ids)["scores"]
227
+ self.assertEqual(len(s1), len(s2))
228
+ for r1, r2 in zip(s1, s2):
229
+ for v1, v2 in zip(r1, r2):
230
+ self.assertAlmostEqual(v1, v2, places=6)
231
+
232
+
233
+ if __name__ == "__main__":
234
+ unittest.main(verbosity=3)
asian_ai/performance/SGLang/test/registered/prefill_only/test_score_engine.py ADDED
@@ -0,0 +1,488 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Engine API tests for the /v1/score scoring pipeline.
2
+
3
+ Two model types, two scoring modes:
4
+
5
+ TestCausalLMScoring — CausalLM, single-item and batched multi-item
6
+ TestSeqClsScoring — SequenceClassification, single-item mode
7
+ TestSeqClsMISScoring — SequenceClassification, MIS mode (--enable-mis)
8
+ TestSeqClsMISAdvancedScoring — SeqCls MIS with 12 labels (tensor shape stress)
9
+
10
+ The Engine (Python API) is the right layer for correctness testing: it
11
+ exercises tokenization, forward pass, pooling, and score extraction without
12
+ the HTTP serialization overhead. HTTP-layer tests live in test_score_api.py.
13
+ Thorough MIS tests (parity, concurrency, generation models) live in
14
+ test_multi_item_scoring.py.
15
+ """
16
+
17
+ import json
18
+ import os
19
+ import unittest
20
+ from unittest.mock import patch
21
+
22
+ import torch
23
+ from transformers import AutoModelForCausalLM, AutoTokenizer
24
+
25
+ from sglang.srt.entrypoints.engine import Engine
26
+ from sglang.test.ci.ci_register import register_cuda_ci
27
+ from sglang.test.test_utils import DEFAULT_SMALL_MODEL_NAME_FOR_TEST, CustomTestCase
28
+
29
+ register_cuda_ci(est_time=85, stage="base-b", runner_config="1-gpu-small")
30
+
31
+ _CAUSAL_LM_MODEL = os.environ.get("TEST_MODEL_NAME", DEFAULT_SMALL_MODEL_NAME_FOR_TEST)
32
+ _SEQCLS_MODEL = os.environ.get("TEST_CLASSIFICATION_BASE_MODEL", "Qwen/Qwen3-0.6B")
33
+
34
+
35
+ # ---------------------------------------------------------------------------
36
+ # CausalLM
37
+ # ---------------------------------------------------------------------------
38
+
39
+
40
+ class TestCausalLMScoring(CustomTestCase):
41
+ """CausalLM scoring via Engine — correctness, batching, and edge cases.
42
+
43
+ A single Engine instance is shared across all test methods (class-level
44
+ setup) so model loading happens once, not once per test.
45
+ """
46
+
47
+ @classmethod
48
+ def setUpClass(cls):
49
+ cls.engine = Engine(model_path=_CAUSAL_LM_MODEL)
50
+
51
+ @classmethod
52
+ def tearDownClass(cls):
53
+ if hasattr(cls, "engine") and cls.engine:
54
+ cls.engine.shutdown()
55
+ torch.cuda.empty_cache()
56
+
57
+ # ------------------------------------------------------------------
58
+ # Helpers
59
+ # ------------------------------------------------------------------
60
+
61
+ def _hf_scores(self, query, items, label_token_ids, item_first=False):
62
+ """Reference scores computed directly with HuggingFace (CPU inference)."""
63
+ tokenizer = AutoTokenizer.from_pretrained(
64
+ _CAUSAL_LM_MODEL, trust_remote_code=True
65
+ )
66
+ model = AutoModelForCausalLM.from_pretrained(
67
+ _CAUSAL_LM_MODEL, trust_remote_code=True
68
+ )
69
+ try:
70
+ scores = []
71
+ for item in items:
72
+ text = f"{item}{query}" if item_first else f"{query}{item}"
73
+ inputs = tokenizer(text, return_tensors="pt").to(model.device)
74
+ with torch.no_grad():
75
+ last_logits = model(**inputs).logits[0, -1]
76
+ target_probs = torch.softmax(last_logits[label_token_ids], dim=-1)
77
+ scores.append([p.item() for p in target_probs])
78
+ return scores
79
+ finally:
80
+ model.cpu()
81
+ del model, tokenizer
82
+ torch.cuda.empty_cache()
83
+
84
+ def _assert_scores_close(self, hf, sgl, tol=0.01):
85
+ self.assertEqual(len(hf), len(sgl))
86
+ for hf_row, sgl_row in zip(hf, sgl):
87
+ self.assertEqual(len(hf_row), len(sgl_row))
88
+ for h, s in zip(hf_row, sgl_row):
89
+ self.assertLessEqual(abs(h - s), tol, f"HF={h:.6f} SGLang={s:.6f}")
90
+ self.assertAlmostEqual(sum(sgl_row), 1.0, places=6)
91
+
92
+ # ------------------------------------------------------------------
93
+ # Correctness
94
+ # ------------------------------------------------------------------
95
+
96
+ def test_scores_match_hf_reference(self):
97
+ """SGLang scores agree with HuggingFace within 1% tolerance."""
98
+ label_token_ids = []
99
+ tokenizer = AutoTokenizer.from_pretrained(
100
+ _CAUSAL_LM_MODEL, trust_remote_code=True
101
+ )
102
+ for token in [" to", " the"]:
103
+ label_token_ids.append(
104
+ tokenizer(token, add_special_tokens=False)["input_ids"][0]
105
+ )
106
+ del tokenizer
107
+
108
+ for query, items, item_first in [
109
+ ("I pledge allegiance", ["", " to"], False),
110
+ (" is a city", ["Tokyo", "Japan"], True),
111
+ ]:
112
+ with self.subTest(query=query):
113
+ sgl = self.engine.score(
114
+ query=query,
115
+ items=items,
116
+ label_token_ids=label_token_ids,
117
+ apply_softmax=True,
118
+ item_first=item_first,
119
+ ).scores
120
+ hf = self._hf_scores(query, items, label_token_ids, item_first)
121
+ self._assert_scores_close(hf, sgl)
122
+
123
+ def test_request_avoids_decode_phase(self):
124
+ """Internal request must have max_new_tokens=0, logprob=True, stream=False."""
125
+ captured = []
126
+ original = self.engine.tokenizer_manager.generate_request
127
+
128
+ async def capturing_gen(req, request=None):
129
+ captured.append(req)
130
+ async for result in original(req, request):
131
+ yield result
132
+
133
+ with patch.object(
134
+ self.engine.tokenizer_manager,
135
+ "generate_request",
136
+ side_effect=capturing_gen,
137
+ ):
138
+ self.engine.score(
139
+ query="What is the capital of",
140
+ items=["France", "Germany"],
141
+ label_token_ids=[1, 2, 3],
142
+ apply_softmax=True,
143
+ )
144
+
145
+ self.assertEqual(len(captured), 1)
146
+ req = captured[0]
147
+
148
+ if isinstance(req.sampling_params, list):
149
+ max_new_tokens = req.sampling_params[0].get("max_new_tokens", 0)
150
+ elif isinstance(req.sampling_params, dict):
151
+ max_new_tokens = req.sampling_params.get("max_new_tokens", 0)
152
+ else:
153
+ max_new_tokens = getattr(req.sampling_params, "max_new_tokens", 0)
154
+
155
+ self.assertEqual(max_new_tokens, 0)
156
+ self.assertTrue(req.return_logprob)
157
+ self.assertFalse(req.stream)
158
+
159
+ # ------------------------------------------------------------------
160
+ # Multi-item / batching
161
+ # ------------------------------------------------------------------
162
+
163
+ def test_score_batch_sizes(self):
164
+ """Correct output count and shape for batch sizes 1, 2, 4, 8."""
165
+ label_token_ids = [1, 2, 3]
166
+ for n in [1, 2, 4, 8]:
167
+ with self.subTest(n=n):
168
+ scores = self.engine.score(
169
+ query="The test was",
170
+ items=[f"test {i}" for i in range(n)],
171
+ label_token_ids=label_token_ids,
172
+ apply_softmax=True,
173
+ ).scores
174
+ self.assertEqual(len(scores), n)
175
+ for row in scores:
176
+ self.assertEqual(len(row), len(label_token_ids))
177
+ self.assertTrue(all(isinstance(v, float) for v in row))
178
+ self.assertAlmostEqual(sum(row), 1.0, places=6)
179
+
180
+ def test_score_empty_items(self):
181
+ """Empty items list → empty scores and zero prompt_tokens."""
182
+ result = self.engine.score(
183
+ query="Test query", items=[], label_token_ids=[1, 2], apply_softmax=True
184
+ )
185
+ self.assertEqual(len(result.scores), 0)
186
+ self.assertEqual(result.prompt_tokens, 0)
187
+
188
+ def test_score_without_softmax(self):
189
+ """apply_softmax=False returns raw logits (not probability-constrained)."""
190
+ scores = self.engine.score(
191
+ query="Rate each:",
192
+ items=["Good", "Bad", "Neutral"],
193
+ label_token_ids=[1, 2, 3],
194
+ apply_softmax=False,
195
+ ).scores
196
+ self.assertEqual(len(scores), 3)
197
+ for row in scores:
198
+ self.assertEqual(len(row), 3)
199
+ for v in row:
200
+ self.assertIsInstance(v, (int, float))
201
+
202
+ def test_score_varying_label_token_sets(self):
203
+ """Different label_token_ids lengths all produce correct-shaped output."""
204
+ for n_labels in [1, 2, 4, 8]:
205
+ with self.subTest(n_labels=n_labels):
206
+ scores = self.engine.score(
207
+ query="Choose:",
208
+ items=["Option A", "Option B"],
209
+ label_token_ids=list(range(1, n_labels + 1)),
210
+ apply_softmax=True,
211
+ ).scores
212
+ self.assertEqual(len(scores), 2)
213
+ for row in scores:
214
+ self.assertEqual(len(row), n_labels)
215
+ self.assertAlmostEqual(sum(row), 1.0, places=6)
216
+
217
+ def test_score_unicode(self):
218
+ """Unicode query and items do not crash and produce valid scores."""
219
+ scores = self.engine.score(
220
+ query="选择最佳选项:",
221
+ items=["选项A", "选项B", "选项C"],
222
+ label_token_ids=[1, 2, 3],
223
+ apply_softmax=True,
224
+ ).scores
225
+ self.assertEqual(len(scores), 3)
226
+ for row in scores:
227
+ self.assertAlmostEqual(sum(row), 1.0, places=6)
228
+
229
+ def test_score_deterministic(self):
230
+ """Identical calls return numerically equivalent scores (within GPU float tolerance)."""
231
+ kwargs = dict(query="Choose:", items=["A", "B", "C"], label_token_ids=[1, 2, 3])
232
+ scores_a = self.engine.score(**kwargs).scores
233
+ scores_b = self.engine.score(**kwargs).scores
234
+ self.assertEqual(len(scores_a), len(scores_b))
235
+ for row_a, row_b in zip(scores_a, scores_b):
236
+ self.assertEqual(len(row_a), len(row_b))
237
+ for a, b in zip(row_a, row_b):
238
+ self.assertAlmostEqual(a, b, places=5)
239
+
240
+ def test_score_error_handling(self):
241
+ """Invalid argument types raise ValueError or TypeError."""
242
+ with self.assertRaises((ValueError, TypeError)):
243
+ self.engine.score(
244
+ query="Q", items=["X"], label_token_ids="bad", apply_softmax=True
245
+ )
246
+ with self.assertRaises((ValueError, TypeError)):
247
+ self.engine.score(
248
+ query="Q", items=None, label_token_ids=[1, 2], apply_softmax=True
249
+ )
250
+
251
+
252
+ # ---------------------------------------------------------------------------
253
+ # SequenceClassification — single-item mode
254
+ # ---------------------------------------------------------------------------
255
+
256
+
257
+ class TestSeqClsScoring(CustomTestCase):
258
+ """SequenceClassification scoring via Engine — no MIS delimiter.
259
+
260
+ Uses json_model_override_args to load Qwen3-0.6B backbone weights into
261
+ Qwen3ForSequenceClassification. The classification head is randomly
262
+ initialised; shape/pipeline correctness is what matters here.
263
+ """
264
+
265
+ NUM_LABELS = 2
266
+
267
+ @classmethod
268
+ def setUpClass(cls):
269
+ cls.engine = Engine(
270
+ model_path=_SEQCLS_MODEL,
271
+ disable_radix_cache=True,
272
+ json_model_override_args=json.dumps(
273
+ {
274
+ "architectures": ["Qwen3ForSequenceClassification"],
275
+ "num_labels": cls.NUM_LABELS,
276
+ }
277
+ ),
278
+ mem_fraction_static=0.15,
279
+ )
280
+
281
+ @classmethod
282
+ def tearDownClass(cls):
283
+ if hasattr(cls, "engine") and cls.engine:
284
+ cls.engine.shutdown()
285
+ torch.cuda.empty_cache()
286
+
287
+ def test_score_shape(self):
288
+ """Each item gets a score vector of length num_labels."""
289
+ scores = self.engine.score(
290
+ query="Rate each option:",
291
+ items=["Option A", "Option B"],
292
+ apply_softmax=True,
293
+ ).scores
294
+ self.assertEqual(len(scores), 2)
295
+ for i, row in enumerate(scores):
296
+ self.assertEqual(len(row), self.NUM_LABELS)
297
+ self.assertAlmostEqual(sum(row), 1.0, places=5)
298
+ for v in row:
299
+ self.assertGreaterEqual(v, 0.0)
300
+ self.assertLessEqual(v, 1.0)
301
+
302
+ def test_score_single_item_edge_case(self):
303
+ """Single item in the list."""
304
+ scores = self.engine.score(
305
+ query="Evaluate:", items=["Only item"], apply_softmax=True
306
+ ).scores
307
+ self.assertEqual(len(scores), 1)
308
+ self.assertEqual(len(scores[0]), self.NUM_LABELS)
309
+ self.assertAlmostEqual(sum(scores[0]), 1.0, places=5)
310
+
311
+ def test_score_without_softmax(self):
312
+ """Without softmax, returns raw logits (no probability constraints)."""
313
+ scores = self.engine.score(
314
+ query="Evaluate:", items=["Alpha", "Beta"], apply_softmax=False
315
+ ).scores
316
+ self.assertEqual(len(scores), 2)
317
+ for row in scores:
318
+ self.assertEqual(len(row), self.NUM_LABELS)
319
+ for v in row:
320
+ self.assertIsInstance(v, (int, float))
321
+
322
+ def test_score_deterministic(self):
323
+ """Identical inputs yield near-identical scores (fp16 tolerance)."""
324
+ kwargs = dict(query="Evaluate:", items=["alpha", "beta", "gamma"])
325
+ scores1 = self.engine.score(**kwargs).scores
326
+ scores2 = self.engine.score(**kwargs).scores
327
+ self.assertEqual(len(scores1), len(scores2))
328
+ for s1, s2 in zip(scores1, scores2):
329
+ for v1, v2 in zip(s1, s2):
330
+ self.assertAlmostEqual(v1, v2, places=1)
331
+
332
+ def test_score_tokenized_inputs(self):
333
+ """Pre-tokenized query/items match text input scores."""
334
+ from transformers import AutoTokenizer
335
+
336
+ tok = AutoTokenizer.from_pretrained(_SEQCLS_MODEL)
337
+ query, items = "Rate this:", ["Good", "Bad"]
338
+
339
+ text_scores = self.engine.score(
340
+ query=query, items=items, apply_softmax=True
341
+ ).scores
342
+ token_scores = self.engine.score(
343
+ query=tok.encode(query),
344
+ items=[tok.encode(i) for i in items],
345
+ apply_softmax=True,
346
+ ).scores
347
+
348
+ self.assertEqual(len(text_scores), len(token_scores))
349
+ for ts, ks in zip(text_scores, token_scores):
350
+ for t, k in zip(ts, ks):
351
+ self.assertAlmostEqual(t, k, places=4)
352
+
353
+ def test_label_token_ids_ignored(self):
354
+ """SeqCls models ignore label_token_ids — output width is always num_labels."""
355
+ scores = self.engine.score(
356
+ query="Evaluate:",
357
+ items=["Test item"],
358
+ label_token_ids=[1, 2, 3],
359
+ apply_softmax=True,
360
+ ).scores
361
+ self.assertEqual(len(scores), 1)
362
+ self.assertEqual(len(scores[0]), self.NUM_LABELS)
363
+
364
+
365
+ # ---------------------------------------------------------------------------
366
+ # SequenceClassification — MIS (delimiter) mode
367
+ # ---------------------------------------------------------------------------
368
+
369
+
370
+ class TestSeqClsMISScoring(CustomTestCase):
371
+ """SeqCls MIS: all items packed into one sequence separated by delimiter token.
372
+
373
+ Uses --enable-mis which hardcodes delimiter token ID 9999.
374
+ Basic pipeline correctness only — thorough MIS tests (parity,
375
+ concurrency, advanced) live in test_multi_item_scoring.py.
376
+ """
377
+
378
+ NUM_LABELS = 2
379
+
380
+ @classmethod
381
+ def setUpClass(cls):
382
+ cls.engine = Engine(
383
+ model_path=_SEQCLS_MODEL,
384
+ disable_radix_cache=True,
385
+ chunked_prefill_size=-1,
386
+ enable_mis=True,
387
+ attention_backend="flashinfer",
388
+ json_model_override_args=json.dumps(
389
+ {
390
+ "architectures": ["Qwen3ForSequenceClassification"],
391
+ "num_labels": cls.NUM_LABELS,
392
+ }
393
+ ),
394
+ mem_fraction_static=0.15,
395
+ )
396
+
397
+ @classmethod
398
+ def tearDownClass(cls):
399
+ if hasattr(cls, "engine") and cls.engine:
400
+ cls.engine.shutdown()
401
+ torch.cuda.empty_cache()
402
+
403
+ def test_mis_one_vector_per_item(self):
404
+ """MIS produces exactly one score vector per item."""
405
+ items = ["Option A", "Option B", "Option C"]
406
+ scores = self.engine.score(
407
+ query="Rate each option:", items=items, apply_softmax=True
408
+ ).scores
409
+ self.assertEqual(len(scores), len(items))
410
+ for i, row in enumerate(scores):
411
+ self.assertEqual(len(row), self.NUM_LABELS)
412
+ self.assertAlmostEqual(sum(row), 1.0, places=5)
413
+ for v in row:
414
+ self.assertGreaterEqual(v, 0.0)
415
+ self.assertLessEqual(v, 1.0)
416
+
417
+ def test_mis_single_item_edge_case(self):
418
+ """Single item through MIS path."""
419
+ scores = self.engine.score(
420
+ query="Evaluate:", items=["Single item"], apply_softmax=True
421
+ ).scores
422
+ self.assertEqual(len(scores), 1)
423
+ self.assertEqual(len(scores[0]), self.NUM_LABELS)
424
+ self.assertAlmostEqual(sum(scores[0]), 1.0, places=5)
425
+
426
+ def test_mis_many_items(self):
427
+ """10 items all return valid probability vectors."""
428
+ items = [f"Item {i}" for i in range(10)]
429
+ scores = self.engine.score(
430
+ query="Classify each:", items=items, apply_softmax=True
431
+ ).scores
432
+ self.assertEqual(len(scores), len(items))
433
+ for row in scores:
434
+ self.assertEqual(len(row), self.NUM_LABELS)
435
+ self.assertAlmostEqual(sum(row), 1.0, places=5)
436
+
437
+
438
+ # ---------------------------------------------------------------------------
439
+ # SequenceClassification — MIS with many labels (tensor shape stress test)
440
+ # ---------------------------------------------------------------------------
441
+
442
+
443
+ class TestSeqClsMISAdvancedScoring(CustomTestCase):
444
+ """SeqCls MIS with 12 labels — stresses the 2-D tensor path in score_and_pool.
445
+
446
+ Kept in a separate class (own Engine instance) so it doesn't fight the
447
+ 2-label class-level engine for GPU memory.
448
+ """
449
+
450
+ NUM_LABELS = 12
451
+
452
+ @classmethod
453
+ def setUpClass(cls):
454
+ cls.engine = Engine(
455
+ model_path=_SEQCLS_MODEL,
456
+ disable_radix_cache=True,
457
+ chunked_prefill_size=-1,
458
+ enable_mis=True,
459
+ attention_backend="flashinfer",
460
+ json_model_override_args=json.dumps(
461
+ {
462
+ "architectures": ["Qwen3ForSequenceClassification"],
463
+ "num_labels": cls.NUM_LABELS,
464
+ }
465
+ ),
466
+ mem_fraction_static=0.15,
467
+ )
468
+
469
+ @classmethod
470
+ def tearDownClass(cls):
471
+ if hasattr(cls, "engine") and cls.engine:
472
+ cls.engine.shutdown()
473
+ torch.cuda.empty_cache()
474
+
475
+ def test_many_labels_correct_shape(self):
476
+ """5 items × 12 labels — each score vector has the right length."""
477
+ items = [f"Item {i}" for i in range(5)]
478
+ scores = self.engine.score(
479
+ query="Classify:", items=items, apply_softmax=True
480
+ ).scores
481
+ self.assertEqual(len(scores), len(items))
482
+ for row in scores:
483
+ self.assertEqual(len(row), self.NUM_LABELS)
484
+ self.assertAlmostEqual(sum(row), 1.0, places=5)
485
+
486
+
487
+ if __name__ == "__main__":
488
+ unittest.main(verbosity=3)