test_dynamo_serve.py 15.2 KB
Newer Older
Neelay Shah's avatar
Neelay Shah committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
# SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.


import logging
import os
import time

import pytest
import requests

from tests.utils.deployment_graph import (
    DeploymentGraph,
    Payload,
27
    chat_completions_response_handler,
Neelay Shah's avatar
Neelay Shah committed
28
29
30
31
32
33
34
    completions_response_handler,
)
from tests.utils.managed_process import ManagedProcess

text_prompt = "Tell me a short joke about AI."

multimodal_payload = Payload(
35
    payload_chat={
Neelay Shah's avatar
Neelay Shah committed
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
        "model": "llava-hf/llava-1.5-7b-hf",
        "messages": [
            {
                "role": "user",
                "content": [
                    {"type": "text", "text": "What is in this image?"},
                    {
                        "type": "image_url",
                        "image_url": {
                            "url": "http://images.cocodataset.org/test2017/000000155781.jpg"
                        },
                    },
                ],
            }
        ],
        "max_tokens": 300,  # Reduced from 500
        "stream": False,
    },
54
    repeat_count=1,
Neelay Shah's avatar
Neelay Shah committed
55
56
57
58
59
    expected_log=[],
    expected_response=["bus"],
)

text_payload = Payload(
60
    payload_chat={
Neelay Shah's avatar
Neelay Shah committed
61
62
63
64
65
66
67
68
69
        "model": "deepseek-ai/DeepSeek-R1-Distill-Llama-8B",
        "messages": [
            {
                "role": "user",
                "content": text_prompt,  # Shorter prompt
            }
        ],
        "max_tokens": 150,  # Reduced from 500
        "temperature": 0.1,
70
        # "seed": 0,
Neelay Shah's avatar
Neelay Shah committed
71
    },
72
73
74
75
76
    payload_completions={
        "model": "deepseek-ai/DeepSeek-R1-Distill-Llama-8B",
        "prompt": text_prompt,
        "max_tokens": 150,
        "temperature": 0.1,
77
        # "seed": 0,
78
79
    },
    repeat_count=10,
Neelay Shah's avatar
Neelay Shah committed
80
81
82
83
84
85
86
87
88
89
    expected_log=[],
    expected_response=["AI"],
)

deployment_graphs = {
    "agg": (
        DeploymentGraph(
            module="graphs.agg:Frontend",
            config="configs/agg.yaml",
            directory="/workspace/examples/llm",
90
            endpoints=["v1/chat/completions"],
91
92
93
            response_handlers=[
                chat_completions_response_handler,
            ],
Neelay Shah's avatar
Neelay Shah committed
94
95
96
97
98
99
100
101
102
            marks=[pytest.mark.gpu_1, pytest.mark.vllm],
        ),
        text_payload,
    ),
    "sglang_agg": (
        DeploymentGraph(
            module="graphs.agg:Frontend",
            config="configs/agg.yaml",
            directory="/workspace/examples/sglang",
103
104
105
106
107
            endpoints=["v1/chat/completions", "v1/completions"],
            response_handlers=[
                chat_completions_response_handler,
                completions_response_handler,
            ],
Neelay Shah's avatar
Neelay Shah committed
108
109
110
111
112
113
114
115
116
            marks=[pytest.mark.gpu_1, pytest.mark.sglang],
        ),
        text_payload,
    ),
    "disagg": (
        DeploymentGraph(
            module="graphs.disagg:Frontend",
            config="configs/disagg.yaml",
            directory="/workspace/examples/llm",
117
            endpoints=["v1/chat/completions"],
118
119
120
            response_handlers=[
                chat_completions_response_handler,
            ],
Neelay Shah's avatar
Neelay Shah committed
121
122
123
124
125
126
127
128
129
            marks=[pytest.mark.gpu_2, pytest.mark.vllm],
        ),
        text_payload,
    ),
    "agg_router": (
        DeploymentGraph(
            module="graphs.agg_router:Frontend",
            config="configs/agg_router.yaml",
            directory="/workspace/examples/llm",
130
            endpoints=["v1/chat/completions"],
131
132
133
            response_handlers=[
                chat_completions_response_handler,
            ],
Neelay Shah's avatar
Neelay Shah committed
134
            marks=[pytest.mark.gpu_1, pytest.mark.vllm],
135
136
137
138
            # FIXME: This is a hack to allow deployments to start before sending any requests.
            # When using KV-router, if all the endpoints are not registered, the service
            # enters a non-recoverable state.
            delayed_start=120,
Neelay Shah's avatar
Neelay Shah committed
139
140
141
142
143
144
145
146
        ),
        text_payload,
    ),
    "disagg_router": (
        DeploymentGraph(
            module="graphs.disagg_router:Frontend",
            config="configs/disagg_router.yaml",
            directory="/workspace/examples/llm",
147
            endpoints=["v1/chat/completions"],
148
149
150
            response_handlers=[
                chat_completions_response_handler,
            ],
Neelay Shah's avatar
Neelay Shah committed
151
            marks=[pytest.mark.gpu_2, pytest.mark.vllm],
152
153
154
155
            # FIXME: This is a hack to allow deployments to start before sending any requests.
            # When using KV-router, if all the endpoints are not registered, the service
            # enters a non-recoverable state.
            delayed_start=120,
Neelay Shah's avatar
Neelay Shah committed
156
157
158
159
160
161
        ),
        text_payload,
    ),
    "multimodal_agg": (
        DeploymentGraph(
            module="graphs.agg:Frontend",
162
            config="configs/agg-llava.yaml",
Neelay Shah's avatar
Neelay Shah committed
163
            directory="/workspace/examples/multimodal",
164
            endpoints=["v1/chat/completions"],
165
166
167
            response_handlers=[
                chat_completions_response_handler,
            ],
Neelay Shah's avatar
Neelay Shah committed
168
169
170
171
172
173
174
175
176
            marks=[pytest.mark.gpu_2, pytest.mark.vllm],
        ),
        multimodal_payload,
    ),
    "vllm_v1_agg": (
        DeploymentGraph(
            module="graphs.agg:Frontend",
            config="configs/agg.yaml",
            directory="/workspace/examples/vllm_v1",
177
178
179
180
181
            endpoints=["v1/chat/completions", "v1/completions"],
            response_handlers=[
                chat_completions_response_handler,
                completions_response_handler,
            ],
Neelay Shah's avatar
Neelay Shah committed
182
183
184
185
            marks=[pytest.mark.gpu_1, pytest.mark.vllm],
        ),
        text_payload,
    ),
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
    "trtllm_agg": (
        DeploymentGraph(
            module="graphs.agg:Frontend",
            config="configs/agg.yaml",
            directory="/workspace/examples/tensorrt_llm",
            endpoints=["v1/chat/completions", "v1/completions"],
            response_handlers=[
                chat_completions_response_handler,
                completions_response_handler,
            ],
            marks=[pytest.mark.gpu_1, pytest.mark.tensorrtllm],
        ),
        text_payload,
    ),
    "trtllm_agg_router": (
        DeploymentGraph(
202
            module="graphs.agg:Frontend",
203
204
205
206
207
208
209
210
211
212
213
            config="configs/agg_router.yaml",
            directory="/workspace/examples/tensorrt_llm",
            endpoints=["v1/chat/completions", "v1/completions"],
            response_handlers=[
                chat_completions_response_handler,
                completions_response_handler,
            ],
            marks=[pytest.mark.gpu_1, pytest.mark.tensorrtllm],
            # FIXME: This is a hack to allow deployments to start before sending any requests.
            # When using KV-router, if all the endpoints are not registered, the service
            # enters a non-recoverable state.
214
            delayed_start=120,
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
        ),
        text_payload,
    ),
    "trtllm_disagg": (
        DeploymentGraph(
            module="graphs.disagg:Frontend",
            config="configs/disagg.yaml",
            directory="/workspace/examples/tensorrt_llm",
            endpoints=["v1/chat/completions", "v1/completions"],
            response_handlers=[
                chat_completions_response_handler,
                completions_response_handler,
            ],
            marks=[pytest.mark.gpu_2, pytest.mark.tensorrtllm],
        ),
        text_payload,
    ),
    "trtllm_disagg_router": (
        DeploymentGraph(
234
            module="graphs.disagg:Frontend",
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
            config="configs/disagg_router.yaml",
            directory="/workspace/examples/tensorrt_llm",
            endpoints=["v1/chat/completions", "v1/completions"],
            response_handlers=[
                chat_completions_response_handler,
                completions_response_handler,
            ],
            marks=[pytest.mark.gpu_2, pytest.mark.tensorrtllm],
            # FIXME: This is a hack to allow deployments to start before sending any requests.
            # When using KV-router, if all the endpoints are not registered, the service
            # enters a non-recoverable state.
            delayed_start=120,
        ),
        text_payload,
    ),
Neelay Shah's avatar
Neelay Shah committed
250
251
252
253
254
255
256
257
258
259
}


class DynamoServeProcess(ManagedProcess):
    def __init__(self, graph: DeploymentGraph, request, port=8000, timeout=900):
        command = ["dynamo", "serve", graph.module]

        if graph.config:
            command.extend(["-f", os.path.join(graph.directory, graph.config)])

260
        # Handle multimodal deployments differently
Neelay Shah's avatar
Neelay Shah committed
261
        if "multimodal" in graph.directory:
262
263
264
            # Set DYNAMO_PORT environment variable for multimodal
            env = os.environ.copy()
            env["DYNAMO_PORT"] = str(port)
Neelay Shah's avatar
Neelay Shah committed
265
            health_check_urls = []
266
267
268
269
270
271
272
273
274
275
            # Don't add health check on port since multimodal uses DYNAMO_PORT
            health_check_ports = []
        else:
            # Regular LLM deployments
            command.extend(["--Frontend.port", str(port)])
            health_check_urls = [
                (f"http://localhost:{port}/v1/models", self._check_model)
            ]
            health_check_ports = [port]
            env = None
Neelay Shah's avatar
Neelay Shah committed
276
277
278
279
280
281
282
283

        self.port = port

        super().__init__(
            command=command,
            timeout=timeout,
            display_output=True,
            working_dir=graph.directory,
284
            health_check_ports=health_check_ports,
Neelay Shah's avatar
Neelay Shah committed
285
            health_check_urls=health_check_urls,
286
            delayed_start=graph.delayed_start,
Neelay Shah's avatar
Neelay Shah committed
287
288
            stragglers=["http"],
            log_dir=request.node.name,
289
            env=env,  # Pass the environment variables
Neelay Shah's avatar
Neelay Shah committed
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
        )

    def _check_model(self, response):
        try:
            data = response.json()
        except ValueError:
            return False
        if data.get("data") and len(data["data"]) > 0:
            return True
        return False


@pytest.fixture(
    params=[
        pytest.param("agg", marks=[pytest.mark.vllm, pytest.mark.gpu_1]),
        pytest.param("agg_router", marks=[pytest.mark.vllm, pytest.mark.gpu_1]),
        pytest.param("disagg", marks=[pytest.mark.vllm, pytest.mark.gpu_2]),
        pytest.param("disagg_router", marks=[pytest.mark.vllm, pytest.mark.gpu_2]),
        pytest.param("multimodal_agg", marks=[pytest.mark.vllm, pytest.mark.gpu_2]),
309
310
311
312
313
314
315
316
317
318
        pytest.param("trtllm_agg", marks=[pytest.mark.tensorrtllm, pytest.mark.gpu_1]),
        pytest.param(
            "trtllm_agg_router", marks=[pytest.mark.tensorrtllm, pytest.mark.gpu_1]
        ),
        pytest.param(
            "trtllm_disagg", marks=[pytest.mark.tensorrtllm, pytest.mark.gpu_2]
        ),
        pytest.param(
            "trtllm_disagg_router", marks=[pytest.mark.tensorrtllm, pytest.mark.gpu_2]
        ),
Neelay Shah's avatar
Neelay Shah committed
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
        #        pytest.param("sglang", marks=[pytest.mark.sglang, pytest.mark.gpu_2]),
    ]
)
def deployment_graph_test(request):
    """
    Fixture that provides different deployment graph test configurations.
    """
    return deployment_graphs[request.param]


@pytest.mark.e2e
@pytest.mark.slow
def test_serve_deployment(deployment_graph_test, request, runtime_services):
    """
    Test dynamo serve deployments with different graph configurations.
    """

    # runtime_services is used to start nats and etcd

    logger = logging.getLogger(request.node.name)
    logger.info("Starting test_deployment")

    deployment_graph, payload = deployment_graph_test

343
344
345
    def check_response(response, response_handler):
        assert response.status_code == 200, "Server is not healthy"
        content = response_handler(response)
Neelay Shah's avatar
Neelay Shah committed
346
347
348
349
350
        logger.info("Received Content: %s", content)
        # Check for expected responses
        assert content, "Empty response content"
        for expected in payload.expected_response:
            assert expected in content, "Expected '%s' not found in response" % expected
351
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
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428

    with DynamoServeProcess(deployment_graph, request) as server_process:
        first_success_pending = True
        for endpoint, response_handler in zip(
            deployment_graph.endpoints, deployment_graph.response_handlers
        ):
            url = f"http://localhost:{server_process.port}/{endpoint}"
            start_time = time.time()
            retry_delay = 5
            elapsed = 0.0
            request_body = (
                payload.payload_chat
                if endpoint == "v1/chat/completions"
                else payload.payload_completions
            )

            # We can skip this
            while (
                time.time() - start_time < deployment_graph.timeout
                and first_success_pending
            ):
                elapsed = time.time() - start_time
                try:
                    response = requests.post(
                        url,
                        json=request_body,
                        timeout=deployment_graph.timeout - elapsed,
                    )
                except (requests.RequestException, requests.Timeout) as e:
                    logger.warning("Retrying due to Request failed: %s", e)
                    time.sleep(retry_delay)
                    continue
                logger.info("Response%r", response)
                if response.status_code == 500:
                    error = response.json().get("error", "")
                    if "no instances" in error:
                        logger.warning("Retrying due to no instances available")
                        time.sleep(retry_delay)
                        continue
                if response.status_code == 404:
                    error = response.json().get("error", "")
                    if "Model not found" in error:
                        logger.warning("Retrying due to model not found")
                        time.sleep(retry_delay)
                        continue
                # Process the response
                if response.status_code != 200:
                    logger.error(
                        "Service returned status code %s: %s",
                        response.status_code,
                        response.text,
                    )
                    pytest.fail(
                        "Service returned status code %s: %s"
                        % (response.status_code, response.text)
                    )
                else:
                    check_response(response, response_handler)
                    first_success_pending = False
                    break
            else:
                if first_success_pending:
                    logger.error(
                        "Service did not return a successful response within %s s",
                        deployment_graph.timeout,
                    )
                    pytest.fail(
                        "Service did not return a successful response within %s s"
                        % deployment_graph.timeout
                    )

            for _ in range(payload.repeat_count):
                response = requests.post(
                    url,
                    json=request_body,
                    timeout=deployment_graph.timeout - elapsed,
                )
                check_response(response, response_handler)