test_sglang.py 18.1 KB
Newer Older
1
# SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
2
3
# SPDX-License-Identifier: Apache-2.0

4
import dataclasses
5
6
import logging
import os
7
from dataclasses import dataclass, field
8
9
10

import pytest

Alec's avatar
Alec committed
11
12
from tests.serve.common import (
    SERVE_TEST_DIR,
13
    WORKSPACE_DIR,
Alec's avatar
Alec committed
14
15
16
    params_with_model_mark,
    run_serve_deployment,
)
17
from tests.utils.constants import DefaultPort
18
from tests.utils.engine_process import EngineConfig
19
from tests.utils.payload_builder import (
20
21
    anthropic_messages_payload_default,
    anthropic_messages_stream_payload_default,
22
23
24
    chat_payload,
    chat_payload_default,
    completion_payload_default,
25
26
    embedding_payload,
    embedding_payload_default,
27
    metric_payload_default,
28
29
    responses_payload_default,
    responses_stream_payload_default,
30
)
31
32
33
34

logger = logging.getLogger(__name__)


35
36
37
38
39
def _is_cuda13() -> bool:
    v = os.environ.get("CUDA_VERSION", "")
    return v.startswith("13")


40
@dataclass
41
class SGLangConfig(EngineConfig):
42
43
    """Configuration for SGLang test scenarios"""

44
    stragglers: list[str] = field(default_factory=lambda: ["SGLANG:EngineCore"])
45
46


47
sglang_dir = os.environ.get("SGLANG_DIR") or os.path.join(
48
    WORKSPACE_DIR, "examples/backends/sglang"
49
)
50
51
52
REMOTE_VIDEO_TEST_URI = (
    "https://qianwen-res.oss-cn-beijing.aliyuncs.com/Qwen3-Omni/demo/draw.mp4"
)
53

54
55
# SGLang test configurations
# NOTE: pytest.mark.gpu_1 tests take ~167s (2m 47s) total to run sequentially (with models pre-cached)
56
# TODO: Now that these tests use dynamic ports and each config has a profiled_vram_gib marker,
57
# optimize the runtime by bin-packing multiple engine deployments in parallel on the same GPU.
58
# A future collector/launcher can sum profiled_vram_gib values to decide how many tests fit
59
# concurrently without exceeding available VRAM.
60
61
sglang_configs = {
    "aggregated": SGLangConfig(
62
63
        # Uses backend agg.sh (with metrics enabled) for testing standard
        # aggregated deployment with metrics collection
64
        name="aggregated",
65
66
        directory=sglang_dir,
        script_name="agg.sh",
67
68
        marks=[
            pytest.mark.gpu_1,
69
70
71
72
73
74
75
            pytest.mark.profiled_vram_gib(
                3.7
            ),  # actual peak at recommended token count
            pytest.mark.requested_sglang_kv_tokens(
                96
            ),  # KV cache cap (2x safety over min=48)
            pytest.mark.timeout(195),  # profiled 33s on RTX 6000 Ada
76
77
            pytest.mark.pre_merge,
        ],
78
        model="Qwen/Qwen3-0.6B",
79
        env={},
80
        frontend_port=DefaultPort.FRONTEND.value,
81
82
83
        request_payloads=[
            chat_payload_default(),
            completion_payload_default(),
84
85
            responses_payload_default(),
            responses_stream_payload_default(),
86
            metric_payload_default(min_num_requests=6, backend="sglang"),
87
        ],
88
89
    ),
    "disaggregated": SGLangConfig(
90
91
92
        name="disaggregated",
        directory=sglang_dir,
        script_name="disagg.sh",
Dmitry Tokarev's avatar
Dmitry Tokarev committed
93
94
        marks=[
            pytest.mark.gpu_2,
95
            pytest.mark.pre_merge,
96
        ],  # TODO(gpu_2): profile max_vram, timeout, add markers (separate PR)
97
98
        model="Qwen/Qwen3-0.6B",
        env={},
99
        frontend_port=DefaultPort.FRONTEND.value,
100
101
102
103
        request_payloads=[
            chat_payload_default(),
            completion_payload_default(),
        ],
104
    ),
105
106
    "disaggregated_same_gpu": SGLangConfig(
        # Uses disagg_same_gpu.sh for single-GPU disaggregated testing
107
108
        # Validates metrics from both prefill (DefaultPort.SYSTEM1) and decode
        # (DefaultPort.SYSTEM2) workers
109
110
111
        name="disaggregated_same_gpu",
        directory=sglang_dir,
        script_name="disagg_same_gpu.sh",
112
113
        marks=[
            pytest.mark.gpu_1,
114
115
116
117
118
119
120
            pytest.mark.profiled_vram_gib(9.9),  # actual profiled peak with kv-tokens
            pytest.mark.requested_sglang_kv_tokens(
                37472
            ),  # KV cache cap (2x safety over min=18736)
            # Local repro took ~289s wall time with worker readiness reaching
            # "ready" at ~176s on a warm-cache RTX 6000 Ada.
            pytest.mark.timeout(420),
121
            pytest.mark.pre_merge,
122
123
124
125
            pytest.mark.skipif(
                _is_cuda13(),
                reason="torch-memory-saver preload .so links libcudart.so.12, missing in cuda13 images",
            ),
126
        ],
127
        model="Qwen/Qwen3-0.6B",
128
129
        delayed_start=10,
        health_check_workers=True,
130
        env={},
131
        frontend_port=DefaultPort.FRONTEND.value,
132
133
134
        request_payloads=[
            chat_payload_default(),
            completion_payload_default(),
135
136
            # Disagg workers expose fewer sglang:* metrics (~14 vs ~25 for aggregated)
            # because each only runs half the scheduler pipeline.
137
138
            metric_payload_default(
                min_num_requests=6,
139
                backend="sglang_disagg",
140
141
142
143
                port=DefaultPort.SYSTEM1.value,
            ),
            metric_payload_default(
                min_num_requests=6,
144
                backend="sglang_disagg",
145
146
                port=DefaultPort.SYSTEM2.value,
            ),
147
148
        ],
    ),
149
    "kv_events": SGLangConfig(
150
151
152
        name="kv_events",
        directory=sglang_dir,
        script_name="agg_router.sh",
Dmitry Tokarev's avatar
Dmitry Tokarev committed
153
154
        marks=[
            pytest.mark.gpu_2,
155
            pytest.mark.pre_merge,
156
        ],  # TODO(gpu_2): profile max_vram, timeout, add markers (separate PR)
157
158
        model="Qwen/Qwen3-0.6B",
        env={
159
            "DYN_LOG": "dynamo_llm::kv_router::publisher=trace,dynamo_kv_router::scheduling::selector=info",
160
        },
161
        frontend_port=DefaultPort.FRONTEND.value,
162
163
164
        request_payloads=[
            chat_payload_default(
                expected_log=[
165
                    r"ZMQ listener .* received batch with \d+ events \(engine_seq=\d+(?:, [^)]*)?\)",
166
                    r"Event processor for worker_id \d+ processing event: Stored\(",
167
                    r"Selected worker: worker_type=\w+, worker_id=\d+ dp_rank=.*?, logit: ",
168
169
170
                ]
            )
        ],
171
    ),
172
173
174
175
176
    "template_verification": SGLangConfig(
        # Tests custom jinja template preprocessing by verifying the template
        # marker 'CUSTOM_TEMPLATE_ACTIVE|' is applied to user messages.
        # The backend (launch/template_verifier.*) checks for this marker
        # and returns "Successfully Applied Chat Template" if found.
177
178
        # Uses SERVE_TEST_DIR (not sglang_dir) because template_verifier.sh/.py
        # are test-specific mock scripts in tests/serve/launch/
179
        name="template_verification",
180
        directory=SERVE_TEST_DIR,  # special directory for test-specific scripts
181
        script_name="template_verifier.sh",
182
183
        marks=[
            pytest.mark.gpu_1,
184
185
            pytest.mark.profiled_vram_gib(0.0),  # no GPU model load
            pytest.mark.timeout(120),  # profiled 12s on RTX 6000 Ada
186
187
188
            pytest.mark.pre_merge,
            pytest.mark.nightly,
        ],
189
190
        model="Qwen/Qwen3-0.6B",
        env={},
191
        frontend_port=DefaultPort.FRONTEND.value,
192
193
194
195
196
197
        request_payloads=[
            chat_payload_default(
                expected_response=["Successfully Applied Chat Template"]
            )
        ],
    ),
198
199
    # NOTE: Pack all workers on 1 GPU for lower CI resource requirements.
    # NOTE: multimodal_epd.sh uses explicit --mem-fraction-static via DYN_ENCODE_GPU_MEM
200
201
    # / DYN_WORKER_GPU_MEM env vars. The profiler override distributes proportionally
    # but workers combined consistently use ~23.6 GiB regardless of fraction overrides.
202
    "multimodal_e_pd_qwen": SGLangConfig(
203
        # E/P/D architecture: Encode, Prefill, Decode workers all on GPU 0
204
        name="multimodal_e_pd_qwen",
205
        directory=sglang_dir,
206
        script_name="multimodal_epd.sh",
207
208
        marks=[
            pytest.mark.gpu_1,
209
210
211
            # No profiled_vram_gib: uses hard-coded --mem-fraction-static via
            # DYN_ENCODE_GPU_MEM / DYN_WORKER_GPU_MEM, so VRAM scales with GPU size.
            pytest.mark.timeout(210),  # profiled 35s on RTX 6000 Ada
212
213
            pytest.mark.pre_merge,
        ],
214
215
        model="Qwen/Qwen3-VL-2B-Instruct",
        script_args=["--model", "Qwen/Qwen3-VL-2B-Instruct", "--single-gpu"],
216
        timeout=360,
217
218
219
220
        env={
            "DYN_ENCODE_GPU_MEM": "0.1",
            "DYN_WORKER_GPU_MEM": "0.4",
        },
221
        frontend_port=DefaultPort.FRONTEND.value,
222
223
224
225
226
227
228
229
230
231
232
233
        request_payloads=[
            chat_payload(
                [
                    {"type": "text", "text": "What is in this image?"},
                    {
                        "type": "image_url",
                        "image_url": {
                            "url": "http://images.cocodataset.org/test2017/000000155781.jpg"
                        },
                    },
                ],
                repeat_count=1,
234
235
236
                # NOTE: The response text may mention 'bus', 'train', 'streetcar', etc.
                # so we need something consistently found in the response, or a different
                # approach to validation for this test to be stable.
237
                expected_response=["image"],
238
                temperature=0.0,
239
                max_tokens=100,
240
241
242
            )
        ],
    ),
243
244
245
246
247
248
249
    "multimodal_disagg_qwen": SGLangConfig(
        # E/P/D architecture: Encode, Prefill, Decode workers all on GPU 0
        name="multimodal_disagg_qwen",
        directory=sglang_dir,
        script_name="multimodal_disagg.sh",
        marks=[
            pytest.mark.gpu_1,
250
251
252
253
254
            pytest.mark.profiled_vram_gib(16.1),  # actual profiled peak
            pytest.mark.requested_sglang_kv_tokens(
                1024
            ),  # KV cache cap (2x safety over min=512)
            pytest.mark.timeout(222),  # profiled 37s on RTX 6000 Ada
255
256
257
258
259
            pytest.mark.pre_merge,
        ],
        model="Qwen/Qwen3-VL-2B-Instruct",
        script_args=["--model", "Qwen/Qwen3-VL-2B-Instruct", "--single-gpu"],
        timeout=360,
260
        env={},
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
        frontend_port=DefaultPort.FRONTEND.value,
        request_payloads=[
            chat_payload(
                [
                    {"type": "text", "text": "What is in this image?"},
                    {
                        "type": "image_url",
                        "image_url": {
                            "url": "http://images.cocodataset.org/test2017/000000155781.jpg"
                        },
                    },
                ],
                repeat_count=1,
                expected_response=["image"],
                temperature=0.0,
                max_tokens=100,
            )
        ],
    ),
280
281
282
283
284
285
286
    "multimodal_agg_qwen": SGLangConfig(
        # Tests single-process aggregated multimodal inference using DecodeWorkerHandler
        # with in-process vision encoding (no separate encode worker)
        name="multimodal_agg_qwen",
        directory=sglang_dir,
        script_name="agg.sh",
        marks=[
287
288
289
            pytest.mark.skip(
                reason="Nightly CI failure: https://linear.app/nvidia/issue/DYN-2602"
            ),
290
            pytest.mark.gpu_1,
291
292
293
294
295
296
297
            pytest.mark.profiled_vram_gib(
                19.1
            ),  # actual peak at recommended token count
            pytest.mark.requested_sglang_kv_tokens(
                768
            ),  # KV cache cap (2x safety over min=384)
            pytest.mark.timeout(182),  # profiled 30s on RTX 6000 Ada
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
            pytest.mark.pre_merge,
            pytest.mark.nightly,
        ],
        model="Qwen/Qwen2.5-VL-7B-Instruct",
        script_args=[
            "--model-path",
            "Qwen/Qwen2.5-VL-7B-Instruct",
            "--chat-template",
            "qwen2-vl",
        ],
        delayed_start=0,
        timeout=360,
        frontend_port=DefaultPort.FRONTEND.value,
        request_payloads=[
            chat_payload(
                [
                    {"type": "text", "text": "What is in this image?"},
                    {
                        "type": "image_url",
                        "image_url": {
                            "url": "http://images.cocodataset.org/test2017/000000155781.jpg"
                        },
                    },
                ],
                repeat_count=1,
                expected_response=["image"],
                temperature=0.0,
                max_tokens=100,
            )
        ],
    ),
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
    "video_agg_qwen": SGLangConfig(
        # Tests aggregated video inference using DecodeWorkerHandler
        # with in-process vision encoding (no separate encode worker).
        # Reuses agg_vision.sh because image and video share the same aggregated
        # multimodal SGLang request path.
        name="video_agg_qwen",
        directory=sglang_dir,
        script_name="agg_vision.sh",
        marks=[
            pytest.mark.gpu_1,
            pytest.mark.profiled_vram_gib(13.3),  # same as multimodal_e_pd_qwen
            pytest.mark.timeout(360),
            pytest.mark.pre_merge,
        ],
        model="Qwen/Qwen2-VL-7B-Instruct",
        script_args=[
            "--model-path",
            "Qwen/Qwen2-VL-7B-Instruct",
            "--mem-fraction-static",
            "0.8",
        ],
        timeout=360,
        frontend_port=DefaultPort.FRONTEND.value,
        request_payloads=[
            chat_payload(
                [
                    {"type": "text", "text": "Describe the video in detail"},
                    {
                        "type": "video_url",
                        "video_url": {"url": REMOTE_VIDEO_TEST_URI},
                    },
                ],
                repeat_count=1,
                expected_response=["guitar", "tablet", "draw"],
                temperature=0.0,
                max_tokens=100,
            )
        ],
    ),
368
369
370
371
    "embedding_agg": SGLangConfig(
        name="embedding_agg",
        directory=sglang_dir,
        script_name="agg_embed.sh",
372
373
        marks=[
            pytest.mark.gpu_1,
374
375
376
377
378
379
380
            pytest.mark.profiled_vram_gib(
                9.8
            ),  # actual peak at recommended token count
            pytest.mark.requested_sglang_kv_tokens(
                128
            ),  # KV cache cap (2x safety over min=64)
            pytest.mark.timeout(147),  # profiled 24s on RTX 6000 Ada
381
382
383
            pytest.mark.pre_merge,
            pytest.mark.nightly,
        ],
384
385
        model="Qwen/Qwen3-Embedding-4B",
        delayed_start=0,
386
        frontend_port=DefaultPort.FRONTEND.value,
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
        request_payloads=[
            # Test default payload with multiple inputs
            embedding_payload_default(
                repeat_count=2,
                expected_response=["Generated 2 embeddings with dimension"],
            ),
            # Test single string input
            embedding_payload(
                input_text="Hello, world!",
                repeat_count=1,
                expected_response=["Generated 1 embeddings with dimension"],
            ),
            # Test multiple string inputs
            embedding_payload(
                input_text=[
                    "The quick brown fox jumps over the lazy dog.",
                    "Machine learning is transforming technology.",
                    "Natural language processing enables computers to understand text.",
                ],
                repeat_count=1,
                expected_response=["Generated 3 embeddings with dimension"],
            ),
        ],
    ),
411
412
413
414
    "completions_only": SGLangConfig(
        name="completions_only",
        directory=sglang_dir,
        script_name="agg.sh",
415
416
        marks=[
            pytest.mark.gpu_1,
417
418
419
420
421
422
423
            pytest.mark.profiled_vram_gib(
                14.7
            ),  # actual peak at recommended token count
            pytest.mark.requested_sglang_kv_tokens(
                64
            ),  # KV cache cap (2x safety over min=32)
            pytest.mark.timeout(341),  # profiled 57s on RTX 6000 Ada
424
            pytest.mark.post_merge,
425
        ],
426
427
428
429
430
431
432
433
434
435
436
        model="deepseek-ai/deepseek-llm-7b-base",
        script_args=[
            "--model-path",
            "deepseek-ai/deepseek-llm-7b-base",
            "--dyn-endpoint-types",
            "completions",
        ],
        request_payloads=[
            completion_payload_default(),
        ],
    ),
437
438
439
440
441
442
443
444
    "anthropic_messages": SGLangConfig(
        name="anthropic_messages",
        directory=sglang_dir,
        script_name="agg.sh",
        marks=[
            pytest.mark.gpu_1,
            pytest.mark.post_merge,
            pytest.mark.timeout(240),
Dmitry Tokarev's avatar
Dmitry Tokarev committed
445
            pytest.mark.skip(reason="DYN-2261"),
446
            # TODO: profile once DYN-2261 is fixed (uses agg.sh, profiler works)
447
448
449
450
451
452
453
454
455
        ],
        model="Qwen/Qwen3-0.6B",
        env={"DYN_ENABLE_ANTHROPIC_API": "1"},
        frontend_port=DefaultPort.FRONTEND.value,
        request_payloads=[
            anthropic_messages_payload_default(),
            anthropic_messages_stream_payload_default(),
        ],
    ),
456
457
458
}


Alec's avatar
Alec committed
459
@pytest.fixture(params=params_with_model_mark(sglang_configs))
460
461
462
463
464
465
466
def sglang_config_test(request):
    """Fixture that provides different SGLang test configurations"""
    return sglang_configs[request.param]


@pytest.mark.e2e
@pytest.mark.sglang
467
468
469
# Use 2 system ports because some `sglang_configs` validate metrics on multiple ports.
# This test iterates over all configs via `sglang_config_test`.
@pytest.mark.parametrize("num_system_ports", [2], indirect=True)
Alec's avatar
Alec committed
470
def test_sglang_deployment(
471
472
473
474
    sglang_config_test,
    request,
    runtime_services_dynamic_ports,
    dynamo_dynamic_ports,
475
    num_system_ports,
476
    predownload_models,
Alec's avatar
Alec committed
477
):
478
    """Test SGLang deployment scenarios using common helpers"""
479
480
481
    assert (
        num_system_ports >= 2
    ), "serve tests require at least SYSTEM_PORT1 + SYSTEM_PORT2"
482
483
484
485
    config = dataclasses.replace(
        sglang_config_test, frontend_port=dynamo_dynamic_ports.frontend_port
    )
    run_serve_deployment(config, request, ports=dynamo_dynamic_ports)
486
487


488
489
@pytest.mark.e2e
@pytest.mark.sglang
490
@pytest.mark.gpu_2
491
@pytest.mark.nightly
492
493
494
@pytest.mark.skip(
    reason="Requires 4 GPUs - enable when hardware is consistently available"
)
495
496
497
def test_sglang_disagg_dp_attention(
    request, runtime_services_dynamic_ports, dynamo_dynamic_ports, predownload_models
):
498
499
    """Test sglang disaggregated with DP attention (requires 4 GPUs)"""

500
    # Kept for reference; this test uses a different launch path and is skipped