"deploy/snapshot/internal/cuda/cuda_test.go" did not exist on "6831020f35c4eba350b40616bf721922420bc010"
test_dynamo_serve.py 8.66 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
)
from tests.utils.managed_process import ManagedProcess

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

multimodal_payload = Payload(
34
    payload_chat={
Neelay Shah's avatar
Neelay Shah committed
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
        "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,
    },
53
    repeat_count=1,
Neelay Shah's avatar
Neelay Shah committed
54
55
56
57
58
59
60
61
    expected_log=[],
    expected_response=["bus"],
)

deployment_graphs = {
    "multimodal_agg": (
        DeploymentGraph(
            module="graphs.agg:Frontend",
62
            config="configs/agg-llava.yaml",
Neelay Shah's avatar
Neelay Shah committed
63
            directory="/workspace/examples/multimodal",
64
            endpoints=["v1/chat/completions"],
65
66
67
            response_handlers=[
                chat_completions_response_handler,
            ],
Neelay Shah's avatar
Neelay Shah committed
68
69
70
71
72
73
74
75
            marks=[pytest.mark.gpu_2, pytest.mark.vllm],
        ),
        multimodal_payload,
    ),
}


class DynamoServeProcess(ManagedProcess):
76
77
78
79
80
81
82
83
84
    def __init__(
        self,
        graph: DeploymentGraph,
        request,
        port=8000,
        timeout=900,
        display_output=True,
        args=None,
    ):
Neelay Shah's avatar
Neelay Shah committed
85
86
87
88
89
        command = ["dynamo", "serve", graph.module]

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

90
91
92
93
94
95
        if args:
            for k, v in args.items():
                command.extend([f"{k}", f"{v}"])

        health_check_urls = []
        health_check_ports = []
96
        env = None
97

98
        # Handle multimodal deployments differently
Neelay Shah's avatar
Neelay Shah committed
99
        if "multimodal" in graph.directory:
100
101
            env = os.environ.copy()
            env["DYNAMO_PORT"] = str(port)
102
103
104
105
106
107
108
        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]
Neelay Shah's avatar
Neelay Shah committed
109
110

        self.port = port
111
        self.graph = graph
Neelay Shah's avatar
Neelay Shah committed
112
113
114
115

        super().__init__(
            command=command,
            timeout=timeout,
116
            display_output=display_output,
Neelay Shah's avatar
Neelay Shah committed
117
            working_dir=graph.directory,
118
            health_check_ports=health_check_ports,
Neelay Shah's avatar
Neelay Shah committed
119
            health_check_urls=health_check_urls,
120
            delayed_start=graph.delayed_start,
Neelay Shah's avatar
Neelay Shah committed
121
            stragglers=["http"],
122
123
124
125
126
            straggler_commands=[
                "dynamo.sdk.cli.serve_dynamo",
                "from multiprocessing.resource_tracker",
                "from multiprocessing.spawn",
            ],
Neelay Shah's avatar
Neelay Shah committed
127
            log_dir=request.node.name,
128
            env=env,
Neelay Shah's avatar
Neelay Shah committed
129
130
131
132
133
134
135
136
137
138
139
        )

    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

140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
    def check_response(
        self, payload, response, response_handler, logger=logging.getLogger()
    ):
        assert response.status_code == 200, "Response Error"
        content = response_handler(response)
        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

    def wait_for_ready(self, payload, logger=logging.getLogger()):
        url = f"http://localhost:{self.port}/{self.graph.endpoints[0]}"
        start_time = time.time()
        retry_delay = 5
        elapsed = 0.0
        logger.info("Waiting for Deployment Ready")
        json_payload = (
            payload.payload_chat
            if self.graph.endpoints[0] == "v1/chat/completions"
            else payload.payload_completions
        )

        while time.time() - start_time < self.graph.timeout:
            elapsed = time.time() - start_time
            try:
                response = requests.post(
                    url,
                    json=json_payload,
                    timeout=self.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:
                break
        else:
            logger.error(
                "Service did not return a successful response within %s s",
                self.graph.timeout,
            )
            pytest.fail(
                "Service did not return a successful response within %s s"
                % self.graph.timeout
            )

        self.check_response(payload, response, self.graph.response_handlers[0], logger)

        logger.info("Deployment Ready")

Neelay Shah's avatar
Neelay Shah committed
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229

@pytest.fixture(
    params=[
        pytest.param("multimodal_agg", marks=[pytest.mark.vllm, 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
230
@pytest.mark.skip(reason="Multi-Modal currently failing CI, turning off for now.")
Neelay Shah's avatar
Neelay Shah committed
231
232
233
234
235
236
237
238
239
240
241
242
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

243
    with DynamoServeProcess(deployment_graph, request) as server_process:
244
245
        server_process.wait_for_ready(payload, logger)

246
247
248
249
250
251
        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()
            elapsed = 0.0
252

253
254
255
256
257
258
            request_body = (
                payload.payload_chat
                if endpoint == "v1/chat/completions"
                else payload.payload_completions
            )

259
            for _ in range(payload.repeat_count):
260
261
262
263
264
265
266
                elapsed = time.time() - start_time

                response = requests.post(
                    url,
                    json=request_body,
                    timeout=deployment_graph.timeout - elapsed,
                )
267
268
269
                server_process.check_response(
                    payload, response, response_handler, logger
                )