test_sglang.py 21.6 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
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
    ),
    "aggregated_unified": SGLangConfig(
        name="aggregated_unified",
        directory=sglang_dir,
        script_name="agg.sh",
        script_args=["--unified"],
        marks=[
            pytest.mark.gpu_1,
            pytest.mark.profiled_vram_gib(3.7),
            pytest.mark.requested_sglang_kv_tokens(96),
            pytest.mark.timeout(195),
            pytest.mark.pre_merge,
        ],
        model="Qwen/Qwen3-0.6B",
        env={},
        frontend_port=DefaultPort.FRONTEND.value,
        request_payloads=[
            chat_payload_default(),
            completion_payload_default(),
        ],
111
112
    ),
    "disaggregated": SGLangConfig(
113
114
115
        name="disaggregated",
        directory=sglang_dir,
        script_name="disagg.sh",
Dmitry Tokarev's avatar
Dmitry Tokarev committed
116
117
        marks=[
            pytest.mark.gpu_2,
118
            pytest.mark.pre_merge,
119
        ],  # TODO(gpu_2): profile max_vram, timeout, add markers (separate PR)
120
121
        model="Qwen/Qwen3-0.6B",
        env={},
122
        frontend_port=DefaultPort.FRONTEND.value,
123
124
125
126
        request_payloads=[
            chat_payload_default(),
            completion_payload_default(),
        ],
127
    ),
128
129
    "disaggregated_same_gpu": SGLangConfig(
        # Uses disagg_same_gpu.sh for single-GPU disaggregated testing
130
131
        # Validates metrics from both prefill (DefaultPort.SYSTEM1) and decode
        # (DefaultPort.SYSTEM2) workers
132
133
134
        name="disaggregated_same_gpu",
        directory=sglang_dir,
        script_name="disagg_same_gpu.sh",
135
136
        marks=[
            pytest.mark.gpu_1,
137
138
139
140
141
142
143
            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),
144
            pytest.mark.pre_merge,
145
146
147
148
            pytest.mark.skipif(
                _is_cuda13(),
                reason="torch-memory-saver preload .so links libcudart.so.12, missing in cuda13 images",
            ),
149
        ],
150
        model="Qwen/Qwen3-0.6B",
151
152
        delayed_start=10,
        health_check_workers=True,
153
        env={},
154
        frontend_port=DefaultPort.FRONTEND.value,
155
156
157
        request_payloads=[
            chat_payload_default(),
            completion_payload_default(),
158
159
            # Disagg workers expose fewer sglang:* metrics (~14 vs ~25 for aggregated)
            # because each only runs half the scheduler pipeline.
160
161
            metric_payload_default(
                min_num_requests=6,
162
                backend="sglang_disagg",
163
164
165
166
                port=DefaultPort.SYSTEM1.value,
            ),
            metric_payload_default(
                min_num_requests=6,
167
                backend="sglang_disagg",
168
169
                port=DefaultPort.SYSTEM2.value,
            ),
170
171
        ],
    ),
172
    "kv_events": SGLangConfig(
173
174
175
        name="kv_events",
        directory=sglang_dir,
        script_name="agg_router.sh",
Dmitry Tokarev's avatar
Dmitry Tokarev committed
176
177
        marks=[
            pytest.mark.gpu_2,
178
            pytest.mark.pre_merge,
179
        ],  # TODO(gpu_2): profile max_vram, timeout, add markers (separate PR)
180
181
        model="Qwen/Qwen3-0.6B",
        env={
182
            "DYN_LOG": "dynamo_llm::kv_router::publisher=trace,dynamo_kv_router::scheduling::selector=info",
183
        },
184
        frontend_port=DefaultPort.FRONTEND.value,
185
186
187
        request_payloads=[
            chat_payload_default(
                expected_log=[
188
                    r"ZMQ listener .* received batch with \d+ events \(engine_seq=\d+(?:, [^)]*)?\)",
189
                    r"Event processor for worker_id \d+ processing event: Stored\(",
190
                    r"Selected worker: worker_type=\w+, worker_id=\d+ dp_rank=.*?, logit: ",
191
192
193
                ]
            )
        ],
194
    ),
195
196
197
198
199
    "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.
200
201
        # Uses SERVE_TEST_DIR (not sglang_dir) because template_verifier.sh/.py
        # are test-specific mock scripts in tests/serve/launch/
202
        name="template_verification",
203
        directory=SERVE_TEST_DIR,  # special directory for test-specific scripts
204
        script_name="template_verifier.sh",
205
206
        marks=[
            pytest.mark.gpu_1,
207
208
            pytest.mark.profiled_vram_gib(0.0),  # no GPU model load
            pytest.mark.timeout(120),  # profiled 12s on RTX 6000 Ada
209
210
211
            pytest.mark.pre_merge,
            pytest.mark.nightly,
        ],
212
213
        model="Qwen/Qwen3-0.6B",
        env={},
214
        frontend_port=DefaultPort.FRONTEND.value,
215
216
217
218
219
220
        request_payloads=[
            chat_payload_default(
                expected_response=["Successfully Applied Chat Template"]
            )
        ],
    ),
221
222
    # 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
223
224
    # / DYN_WORKER_GPU_MEM env vars. The profiler override distributes proportionally
    # but workers combined consistently use ~23.6 GiB regardless of fraction overrides.
225
    "multimodal_e_pd_qwen": SGLangConfig(
226
        # E/P/D architecture: Encode, Prefill, Decode workers all on GPU 0
227
        name="multimodal_e_pd_qwen",
228
        directory=sglang_dir,
229
        script_name="multimodal_epd.sh",
230
231
        marks=[
            pytest.mark.gpu_1,
232
233
234
            # 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
235
236
            pytest.mark.pre_merge,
        ],
237
238
        model="Qwen/Qwen3-VL-2B-Instruct",
        script_args=["--model", "Qwen/Qwen3-VL-2B-Instruct", "--single-gpu"],
239
        timeout=360,
240
241
242
243
        env={
            "DYN_ENCODE_GPU_MEM": "0.1",
            "DYN_WORKER_GPU_MEM": "0.4",
        },
244
        frontend_port=DefaultPort.FRONTEND.value,
245
246
247
248
249
250
251
252
253
254
255
256
        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,
257
258
259
                # 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.
260
                expected_response=["image"],
261
                temperature=0.0,
262
                max_tokens=100,
263
264
265
            )
        ],
    ),
266
267
268
269
270
271
272
    "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,
273
274
275
276
277
            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
278
279
280
281
282
            pytest.mark.pre_merge,
        ],
        model="Qwen/Qwen3-VL-2B-Instruct",
        script_args=["--model", "Qwen/Qwen3-VL-2B-Instruct", "--single-gpu"],
        timeout=360,
283
        env={},
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
        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,
            )
        ],
    ),
303
304
305
306
307
308
309
    "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=[
310
311
312
            pytest.mark.skip(
                reason="Nightly CI failure: https://linear.app/nvidia/issue/DYN-2602"
            ),
313
            pytest.mark.gpu_1,
314
315
316
317
318
319
320
            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
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
            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,
            )
        ],
    ),
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
    "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,
            )
        ],
    ),
391
392
393
394
    "embedding_agg": SGLangConfig(
        name="embedding_agg",
        directory=sglang_dir,
        script_name="agg_embed.sh",
395
396
        marks=[
            pytest.mark.gpu_1,
397
398
399
400
401
402
403
            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
404
405
406
            pytest.mark.pre_merge,
            pytest.mark.nightly,
        ],
407
408
        model="Qwen/Qwen3-Embedding-4B",
        delayed_start=0,
409
        frontend_port=DefaultPort.FRONTEND.value,
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
        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"],
            ),
        ],
    ),
434
435
436
437
    "completions_only": SGLangConfig(
        name="completions_only",
        directory=sglang_dir,
        script_name="agg.sh",
438
439
        marks=[
            pytest.mark.gpu_1,
440
441
442
443
444
445
446
            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
447
            pytest.mark.post_merge,
448
        ],
449
450
451
452
453
454
455
456
457
458
459
        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(),
        ],
    ),
460
461
462
463
464
465
466
467
    "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
468
            pytest.mark.skip(reason="DYN-2261"),
469
            # TODO: profile once DYN-2261 is fixed (uses agg.sh, profiler works)
470
471
472
473
474
475
476
477
478
        ],
        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(),
        ],
    ),
479
480
481
}


Alec's avatar
Alec committed
482
@pytest.fixture(params=params_with_model_mark(sglang_configs))
483
484
485
486
487
488
489
def sglang_config_test(request):
    """Fixture that provides different SGLang test configurations"""
    return sglang_configs[request.param]


@pytest.mark.e2e
@pytest.mark.sglang
490
491
492
# 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
493
def test_sglang_deployment(
494
495
496
497
    sglang_config_test,
    request,
    runtime_services_dynamic_ports,
    dynamo_dynamic_ports,
498
    num_system_ports,
499
    predownload_models,
Alec's avatar
Alec committed
500
):
501
    """Test SGLang deployment scenarios using common helpers"""
502
503
504
    assert (
        num_system_ports >= 2
    ), "serve tests require at least SYSTEM_PORT1 + SYSTEM_PORT2"
505
506
507
508
    config = dataclasses.replace(
        sglang_config_test, frontend_port=dynamo_dynamic_ports.frontend_port
    )
    run_serve_deployment(config, request, ports=dynamo_dynamic_ports)
509
510


511
512
@pytest.mark.e2e
@pytest.mark.sglang
513
@pytest.mark.gpu_2
514
@pytest.mark.nightly
515
516
517
@pytest.mark.skip(
    reason="Requires 4 GPUs - enable when hardware is consistently available"
)
518
519
520
def test_sglang_disagg_dp_attention(
    request, runtime_services_dynamic_ports, dynamo_dynamic_ports, predownload_models
):
521
522
    """Test sglang disaggregated with DP attention (requires 4 GPUs)"""

523
    # Kept for reference; this test uses a different launch path and is skipped
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
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617


# ── 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(),
    )