test_sglang.py 20.9 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
from typing import Optional
9
10
11

import pytest

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

logger = logging.getLogger(__name__)


38
39
40
41
42
def _is_cuda13() -> bool:
    v = os.environ.get("CUDA_VERSION", "")
    return v.startswith("13")


43
@dataclass
44
class SGLangConfig(EngineConfig):
45
46
    """Configuration for SGLang test scenarios"""

47
    stragglers: list[str] = field(default_factory=lambda: ["SGLANG:EngineCore"])
48
49


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

57
58
# SGLang test configurations
# NOTE: pytest.mark.gpu_1 tests take ~167s (2m 47s) total to run sequentially (with models pre-cached)
59
# TODO: Now that these tests use dynamic ports and each config has a profiled_vram_gib marker,
60
# optimize the runtime by bin-packing multiple engine deployments in parallel on the same GPU.
61
# A future collector/launcher can sum profiled_vram_gib values to decide how many tests fit
62
# concurrently without exceeding available VRAM.
63
64
sglang_configs = {
    "aggregated": SGLangConfig(
65
66
        # Uses backend agg.sh (with metrics enabled) for testing standard
        # aggregated deployment with metrics collection
67
        name="aggregated",
68
69
        directory=sglang_dir,
        script_name="agg.sh",
70
71
        marks=[
            pytest.mark.gpu_1,
72
73
74
75
76
77
78
            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
79
80
            pytest.mark.pre_merge,
        ],
81
        model="Qwen/Qwen3-0.6B",
82
        env={},
83
        frontend_port=DefaultPort.FRONTEND.value,
84
85
86
        request_payloads=[
            chat_payload_default(),
            completion_payload_default(),
87
88
            responses_payload_default(),
            responses_stream_payload_default(),
89
            metric_payload_default(min_num_requests=6, backend="sglang"),
90
        ],
91
92
    ),
    "disaggregated": SGLangConfig(
93
94
95
        name="disaggregated",
        directory=sglang_dir,
        script_name="disagg.sh",
Dmitry Tokarev's avatar
Dmitry Tokarev committed
96
97
        marks=[
            pytest.mark.gpu_2,
98
            pytest.mark.pre_merge,
99
        ],  # TODO(gpu_2): profile max_vram, timeout, add markers (separate PR)
100
101
        model="Qwen/Qwen3-0.6B",
        env={},
102
        frontend_port=DefaultPort.FRONTEND.value,
103
104
105
106
        request_payloads=[
            chat_payload_default(),
            completion_payload_default(),
        ],
107
    ),
108
109
    "disaggregated_same_gpu": SGLangConfig(
        # Uses disagg_same_gpu.sh for single-GPU disaggregated testing
110
111
        # Validates metrics from both prefill (DefaultPort.SYSTEM1) and decode
        # (DefaultPort.SYSTEM2) workers
112
113
114
        name="disaggregated_same_gpu",
        directory=sglang_dir,
        script_name="disagg_same_gpu.sh",
115
116
        marks=[
            pytest.mark.gpu_1,
117
118
119
120
121
122
123
            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),
124
            pytest.mark.pre_merge,
125
126
127
128
            pytest.mark.skipif(
                _is_cuda13(),
                reason="torch-memory-saver preload .so links libcudart.so.12, missing in cuda13 images",
            ),
129
        ],
130
        model="Qwen/Qwen3-0.6B",
131
132
        delayed_start=10,
        health_check_workers=True,
133
        env={},
134
        frontend_port=DefaultPort.FRONTEND.value,
135
136
137
        request_payloads=[
            chat_payload_default(),
            completion_payload_default(),
138
139
            # Disagg workers expose fewer sglang:* metrics (~14 vs ~25 for aggregated)
            # because each only runs half the scheduler pipeline.
140
141
            metric_payload_default(
                min_num_requests=6,
142
                backend="sglang_disagg",
143
144
145
146
                port=DefaultPort.SYSTEM1.value,
            ),
            metric_payload_default(
                min_num_requests=6,
147
                backend="sglang_disagg",
148
149
                port=DefaultPort.SYSTEM2.value,
            ),
150
151
        ],
    ),
152
    "kv_events": SGLangConfig(
153
154
155
        name="kv_events",
        directory=sglang_dir,
        script_name="agg_router.sh",
Dmitry Tokarev's avatar
Dmitry Tokarev committed
156
157
        marks=[
            pytest.mark.gpu_2,
158
            pytest.mark.pre_merge,
159
        ],  # TODO(gpu_2): profile max_vram, timeout, add markers (separate PR)
160
161
        model="Qwen/Qwen3-0.6B",
        env={
162
            "DYN_LOG": "dynamo_llm::kv_router::publisher=trace,dynamo_kv_router::scheduling::selector=info",
163
        },
164
        frontend_port=DefaultPort.FRONTEND.value,
165
166
167
        request_payloads=[
            chat_payload_default(
                expected_log=[
168
                    r"ZMQ listener .* received batch with \d+ events \(engine_seq=\d+(?:, [^)]*)?\)",
169
                    r"Event processor for worker_id \d+ processing event: Stored\(",
170
                    r"Selected worker: worker_type=\w+, worker_id=\d+ dp_rank=.*?, logit: ",
171
172
173
                ]
            )
        ],
174
    ),
175
176
177
178
179
    "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.
180
181
        # Uses SERVE_TEST_DIR (not sglang_dir) because template_verifier.sh/.py
        # are test-specific mock scripts in tests/serve/launch/
182
        name="template_verification",
183
        directory=SERVE_TEST_DIR,  # special directory for test-specific scripts
184
        script_name="template_verifier.sh",
185
186
        marks=[
            pytest.mark.gpu_1,
187
188
            pytest.mark.profiled_vram_gib(0.0),  # no GPU model load
            pytest.mark.timeout(120),  # profiled 12s on RTX 6000 Ada
189
190
191
            pytest.mark.pre_merge,
            pytest.mark.nightly,
        ],
192
193
        model="Qwen/Qwen3-0.6B",
        env={},
194
        frontend_port=DefaultPort.FRONTEND.value,
195
196
197
198
199
200
        request_payloads=[
            chat_payload_default(
                expected_response=["Successfully Applied Chat Template"]
            )
        ],
    ),
201
202
    # 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
203
204
    # / DYN_WORKER_GPU_MEM env vars. The profiler override distributes proportionally
    # but workers combined consistently use ~23.6 GiB regardless of fraction overrides.
205
    "multimodal_e_pd_qwen": SGLangConfig(
206
        # E/P/D architecture: Encode, Prefill, Decode workers all on GPU 0
207
        name="multimodal_e_pd_qwen",
208
        directory=sglang_dir,
209
        script_name="multimodal_epd.sh",
210
211
        marks=[
            pytest.mark.gpu_1,
212
213
214
            # 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
215
216
            pytest.mark.pre_merge,
        ],
217
218
        model="Qwen/Qwen3-VL-2B-Instruct",
        script_args=["--model", "Qwen/Qwen3-VL-2B-Instruct", "--single-gpu"],
219
        timeout=360,
220
221
222
223
        env={
            "DYN_ENCODE_GPU_MEM": "0.1",
            "DYN_WORKER_GPU_MEM": "0.4",
        },
224
        frontend_port=DefaultPort.FRONTEND.value,
225
226
227
228
229
230
231
232
233
234
235
236
        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,
237
238
239
                # 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.
240
                expected_response=["image"],
241
                temperature=0.0,
242
                max_tokens=100,
243
244
245
            )
        ],
    ),
246
247
248
249
250
251
252
    "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,
253
254
255
256
257
            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
258
259
260
261
262
            pytest.mark.pre_merge,
        ],
        model="Qwen/Qwen3-VL-2B-Instruct",
        script_args=["--model", "Qwen/Qwen3-VL-2B-Instruct", "--single-gpu"],
        timeout=360,
263
        env={},
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
        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,
            )
        ],
    ),
283
284
285
286
287
288
289
    "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=[
290
291
292
            pytest.mark.skip(
                reason="Nightly CI failure: https://linear.app/nvidia/issue/DYN-2602"
            ),
293
            pytest.mark.gpu_1,
294
295
296
297
298
299
300
            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
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
329
330
331
            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,
            )
        ],
    ),
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
368
369
370
    "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,
            )
        ],
    ),
371
372
373
374
    "embedding_agg": SGLangConfig(
        name="embedding_agg",
        directory=sglang_dir,
        script_name="agg_embed.sh",
375
376
        marks=[
            pytest.mark.gpu_1,
377
378
379
380
381
382
383
            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
384
385
386
            pytest.mark.pre_merge,
            pytest.mark.nightly,
        ],
387
388
        model="Qwen/Qwen3-Embedding-4B",
        delayed_start=0,
389
        frontend_port=DefaultPort.FRONTEND.value,
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
        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"],
            ),
        ],
    ),
414
415
416
417
    "completions_only": SGLangConfig(
        name="completions_only",
        directory=sglang_dir,
        script_name="agg.sh",
418
419
        marks=[
            pytest.mark.gpu_1,
420
421
422
423
424
425
426
            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
427
            pytest.mark.post_merge,
428
        ],
429
430
431
432
433
434
435
436
437
438
439
        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(),
        ],
    ),
440
441
442
443
444
445
446
447
    "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
448
            pytest.mark.skip(reason="DYN-2261"),
449
            # TODO: profile once DYN-2261 is fixed (uses agg.sh, profiler works)
450
451
452
453
454
455
456
457
458
        ],
        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(),
        ],
    ),
459
460
461
}


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


@pytest.mark.e2e
@pytest.mark.sglang
470
471
472
# 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
473
def test_sglang_deployment(
474
475
476
477
    sglang_config_test,
    request,
    runtime_services_dynamic_ports,
    dynamo_dynamic_ports,
478
    num_system_ports,
479
    predownload_models,
Alec's avatar
Alec committed
480
):
481
    """Test SGLang deployment scenarios using common helpers"""
482
483
484
    assert (
        num_system_ports >= 2
    ), "serve tests require at least SYSTEM_PORT1 + SYSTEM_PORT2"
485
486
487
488
    config = dataclasses.replace(
        sglang_config_test, frontend_port=dynamo_dynamic_ports.frontend_port
    )
    run_serve_deployment(config, request, ports=dynamo_dynamic_ports)
489
490


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

503
    # Kept for reference; this test uses a different launch path and is skipped
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597


# ── LoRA Tests ──────────────────────────────────────────────────────────────

lora_dir = os.path.join(sglang_dir, "launch/lora")


def lora_chat_payload(
    lora_name: str,
    s3_uri: str,
    system_port: int = DefaultPort.SYSTEM1.value,
    repeat_count: int = 2,
    expected_response: Optional[list] = None,
    expected_log: Optional[list] = None,
    max_tokens: int = 100,
    temperature: float = 0.0,
) -> LoraTestChatPayload:
    """Create a LoRA-enabled chat payload for testing"""
    return LoraTestChatPayload(
        body={
            "model": lora_name,
            "messages": [
                {
                    "role": "user",
                    "content": "What is deep learning? Answer in one sentence.",
                }
            ],
            "max_tokens": max_tokens,
            "temperature": temperature,
            "stream": False,
        },
        lora_name=lora_name,
        s3_uri=s3_uri,
        system_port=system_port,
        repeat_count=repeat_count,
        expected_response=expected_response
        or ["learning", "neural", "network", "AI", "model"],
        expected_log=expected_log or [],
    )


@pytest.mark.sglang
@pytest.mark.e2e
@pytest.mark.gpu_1
@pytest.mark.model("Qwen/Qwen3-0.6B")
@pytest.mark.profiled_vram_gib(4.7)
@pytest.mark.requested_sglang_kv_tokens(2848)
@pytest.mark.timeout(158)
@pytest.mark.pre_merge
def test_sglang_lora_aggregated(
    request,
    runtime_services_dynamic_ports,
    predownload_models,
    minio_lora_service,
    dynamo_dynamic_ports,
):
    """
    Test LoRA inference with aggregated SGLang deployment.

    This test:
    1. Uses MinIO fixture to provide S3-compatible storage with uploaded LoRA
    2. Starts SGLang with LoRA support enabled
    3. Loads the LoRA adapter via system API
    4. Runs inference with the LoRA model
    """
    minio_config: MinioLoraConfig = minio_lora_service

    lora_payload = lora_chat_payload(
        lora_name=minio_config.lora_name,
        s3_uri=minio_config.get_s3_uri(),
        system_port=DefaultPort.SYSTEM1.value,
        repeat_count=2,
    )

    config = SGLangConfig(
        name="test_sglang_lora_aggregated",
        directory=sglang_dir,
        script_name="lora/agg_lora.sh",
        marks=[],
        model="Qwen/Qwen3-0.6B",
        timeout=158,
        env=minio_config.get_env_vars(),
        request_payloads=[lora_payload],
    )

    config = dataclasses.replace(
        config, frontend_port=dynamo_dynamic_ports.frontend_port
    )
    run_serve_deployment(
        config,
        request,
        ports=dynamo_dynamic_ports,
        extra_env=minio_config.get_env_vars(),
    )