test_vllm.py 15.8 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
5
6
7
8
9
10
"""End-to-end tests covering reasoning effort behaviour.

Runtime note:
- `python -m pytest tests/frontend/test_vllm.py -v` took ~228s (3m48s) wall time.
- Measured on: Ubuntu 24.04.2, Intel(R) Core(TM) i9-14900K (32 CPUs), NVIDIA RTX 6000 Ada Generation (1 warmup run + 1 measured run).
- Expect variance depending on model cache state, compilation warmup, and system load.
"""
11
12
13
14
15
16

from __future__ import annotations

import logging
import os
import shutil
17
from typing import Any, Dict, Generator, Optional, Tuple
18
19
20
21
22

import pytest
import requests

from tests.utils.constants import GPT_OSS
23
from tests.utils.managed_process import DynamoFrontendProcess, ManagedProcess
24
from tests.utils.payloads import check_models_api
25
from tests.utils.port_utils import ServicePorts
26
27
28
29
30

logger = logging.getLogger(__name__)

TEST_MODEL = GPT_OSS

31
32
33
34
35
36
37
pytestmark = [
    pytest.mark.vllm,
    pytest.mark.gpu_1,
    pytest.mark.e2e,
    pytest.mark.model(TEST_MODEL),
]

38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
WEATHER_TOOL = {
    "type": "function",
    "function": {
        "name": "get_current_weather",
        "description": "Get the current weather",
        "parameters": {
            "type": "object",
            "properties": {
                "location": {
                    "type": "string",
                    "description": "The city and state, e.g. San Francisco, NY",
                },
                "format": {
                    "type": "string",
                    "enum": ["celsius", "fahrenheit"],
                    "description": "The temperature unit",
                },
            },
            "required": ["location", "format"],
        },
    },
}

SYSTEM_HEALTH_TOOL = {
    "type": "function",
    "function": {
        "name": "get_system_health",
        "description": "Returns the current health status of the LLM runtime—use before critical operations to verify the service is live.",
        "parameters": {"type": "object", "properties": {}},
    },
}


class VllmWorkerProcess(ManagedProcess):
    """Vllm Worker process for GPT-OSS model."""

74
75
76
77
78
79
80
81
    def __init__(
        self,
        request,
        *,
        frontend_port: int,
        system_port: int,
        worker_id: str = "vllm-worker",
    ):
82
        self.worker_id = worker_id
83
84
        self.frontend_port = int(frontend_port)
        self.system_port = int(system_port)
85
86
87
88
89
90
91

        command = [
            "python3",
            "-m",
            "dynamo.vllm",
            "--model",
            TEST_MODEL,
92
93
            "--max-model-len",
            "32768",  # 32768 uses ~1.5 GiB (original default 131072 used ~6 GiB KV cache)
94
95
96
97
            "--dyn-tool-call-parser",
            "harmony",
            "--dyn-reasoning-parser",
            "gpt_oss",
Dmitry Tokarev's avatar
Dmitry Tokarev committed
98
99
            "--max-model-len",  # this reduced max context window and amount of GPU memory allocated for context
            "32768",
100
101
        ]

102
103
104
105
106
107
108
109
110
111
        kv_bytes = os.environ.get("_PROFILE_OVERRIDE_VLLM_KV_CACHE_BYTES")
        if kv_bytes:
            command.extend(
                [
                    "--kv-cache-memory-bytes",
                    kv_bytes,
                    "--gpu-memory-utilization",
                    "0.01",
                ]
            )
112

113
114
115
        env = os.environ.copy()
        env["DYN_LOG"] = "debug"
        env["DYN_SYSTEM_USE_ENDPOINT_HEALTH_STATUS"] = '["generate"]'
116
        env["DYN_SYSTEM_PORT"] = str(self.system_port)
117
118
119
120
121
122
123
124
125
126
127
128

        log_dir = f"{request.node.name}_{worker_id}"

        try:
            shutil.rmtree(log_dir)
        except FileNotFoundError:
            pass

        super().__init__(
            command=command,
            env=env,
            health_check_urls=[
129
130
                (f"http://localhost:{self.frontend_port}/v1/models", check_models_api),
                (f"http://localhost:{self.system_port}/health", self.is_ready),
131
132
133
            ],
            timeout=500,
            display_output=True,
134
            terminate_all_matching_process_names=False,
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
            stragglers=["VLLM::EngineCore"],
            straggler_commands=["-m dynamo.vllm"],
            log_dir=log_dir,
        )

    def is_ready(self, response) -> bool:
        try:
            status = (response.json() or {}).get("status")
        except ValueError:
            logger.warning("%s health response is not valid JSON", self.worker_id)
            return False

        is_ready = status == "ready"
        if is_ready:
            logger.info("%s status is ready", self.worker_id)
        else:
            logger.warning("%s status is not ready: %s", self.worker_id, status)
        return is_ready


def _send_chat_request(
    payload: Dict[str, Any],
157
158
    *,
    base_url: str,
159
160
161
162
163
164
    timeout: int = 180,
) -> requests.Response:
    """Send a chat completion request with a specific payload."""
    headers = {"Content-Type": "application/json"}

    response = requests.post(
165
        f"{base_url}/v1/chat/completions",
166
167
168
169
170
171
172
        headers=headers,
        json=payload,
        timeout=timeout,
    )
    return response


173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
@pytest.fixture(scope="function")
def start_services(
    request, runtime_services_dynamic_ports, dynamo_dynamic_ports: ServicePorts
) -> Generator[ServicePorts, None, None]:
    """Start frontend and worker processes for this test.

    `runtime_services_dynamic_ports` ensures NATS/etcd run on per-test ports and sets
    NATS_SERVER/ETCD_ENDPOINTS env vars for Dynamo to discover them.

    This fixture also *returns the exact ports used to launch the services* so tests
    cannot accidentally construct requests against a different `dynamo_dynamic_ports`
    instance (e.g., if fixture scopes/usage are changed in the future).
    """
    _ = runtime_services_dynamic_ports
    frontend_port = dynamo_dynamic_ports.frontend_port
    system_port = dynamo_dynamic_ports.system_ports[0]
    with DynamoFrontendProcess(
        request,
        frontend_port=frontend_port,
        # Optional debugging (not enabled on main):
        # If the frontend hits a Rust panic, enabling backtraces makes failures diagnosable
        # from CI logs without needing to repro locally.
        # extra_env={"RUST_BACKTRACE": "1", "TOKIO_BACKTRACE": "1"},
196
        terminate_all_matching_process_names=False,
197
    ):
198
        logger.info("Frontend started for tests")
199
200
201
202
203
        with VllmWorkerProcess(
            request,
            frontend_port=frontend_port,
            system_port=system_port,
        ):
204
            logger.info("Vllm Worker started for tests")
205
            yield dynamo_dynamic_ports
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237


def _extract_reasoning_metrics(data: Dict[str, Any]) -> Tuple[str, Optional[int]]:
    """Return the reasoning content and optional reasoning token count from a response."""
    choices = data.get("choices") or []
    if not choices:
        raise AssertionError(f"Response missing choices: {data}")

    message = choices[0].get("message") or {}
    reasoning_text = (message.get("reasoning_content") or "").strip()

    usage_block = data.get("usage") or {}
    tokens = usage_block.get("reasoning_tokens")
    reasoning_tokens: Optional[int] = tokens if isinstance(tokens, int) else None

    if not reasoning_text:
        raise AssertionError(f"Response missing reasoning content: {data}")

    return reasoning_text, reasoning_tokens


def _validate_chat_response(response: requests.Response) -> Dict[str, Any]:
    """Ensure the chat completion response is well-formed and return its payload."""
    assert (
        response.status_code == 200
    ), f"Chat request failed with status {response.status_code}: {response.text}"
    response_json = response.json()
    if "choices" not in response_json:
        raise AssertionError(f"Chat response missing 'choices': {response_json}")
    return response_json


238
# Measured using: tests/utils/profile_pytest.py tests/frontend/test_vllm.py::test_reasoning_effort
239
240
@pytest.mark.profiled_vram_gib(20.4)  # actual profiled peak
# TODO: profile with --kv-bytes once pre-existing 500 panic is fixed (JoinError::Panic "Cannot drop a runtime in a context where blocking is not allowed")
241
@pytest.mark.timeout(300)  # 3x observed ~70s wall time, rounded up
242
@pytest.mark.post_merge
243
244
245
def test_reasoning_effort(
    request, start_services: ServicePorts, predownload_models
) -> None:
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
    """High reasoning effort should yield more detailed reasoning than low effort."""

    prompt = (
        "Outline the critical steps and trade-offs when designing a Mars habitat. "
        "Focus on life-support, energy, and redundancy considerations."
    )

    logger.info("Start to test reasoning effort")
    high_payload = {
        "model": TEST_MODEL,
        "messages": [
            {
                "role": "user",
                "content": prompt,
            }
        ],
        "max_tokens": 2000,
        "chat_template_args": {"reasoning_effort": "high"},
    }

    low_payload = {
        "model": TEST_MODEL,
        "messages": [
            {
                "role": "user",
                "content": prompt,
            }
        ],
        "max_tokens": 2000,
        "chat_template_args": {"reasoning_effort": "low"},
    }

278
279
    base_url = f"http://localhost:{start_services.frontend_port}"
    high_response = _send_chat_request(high_payload, base_url=base_url)
280
281
282
283
    high_reasoning_text, high_reasoning_tokens = _extract_reasoning_metrics(
        _validate_chat_response(high_response)
    )

284
    low_response = _send_chat_request(low_payload, base_url=base_url)
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
    low_reasoning_text, low_reasoning_tokens = _extract_reasoning_metrics(
        _validate_chat_response(low_response)
    )

    logger.info(
        "Low effort reasoning tokens: %s, High effort reasoning tokens: %s",
        low_reasoning_tokens,
        high_reasoning_tokens,
    )

    if low_reasoning_tokens is not None and high_reasoning_tokens is not None:
        assert high_reasoning_tokens >= low_reasoning_tokens, (
            "Expected high reasoning effort to use at least as many reasoning tokens "
            f"as low effort (low={low_reasoning_tokens}, high={high_reasoning_tokens})"
        )
    else:
        assert len(high_reasoning_text) > len(low_reasoning_text), (
            "Expected high reasoning effort response to include longer reasoning "
            "content than low effort"
        )


307
# Measured using: tests/utils/profile_pytest.py tests/frontend/test_vllm.py::test_tool_calling
308
309
@pytest.mark.profiled_vram_gib(20.4)  # actual profiled peak
# TODO: profile with --kv-bytes once pre-existing 500 panic is fixed (JoinError::Panic "Cannot drop a runtime in a context where blocking is not allowed")
310
@pytest.mark.timeout(113)  # 3x observed 37.4s wall time
311
@pytest.mark.post_merge
312
313
314
def test_tool_calling(
    request, start_services: ServicePorts, predownload_models
) -> None:
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
    """Test tool calling functionality with weather and system health tools."""

    payload = {
        "model": TEST_MODEL,
        "messages": [
            {
                "role": "user",
                "content": "What is the weather like in San Francisco today?",
            }
        ],
        "max_tokens": 2000,
        "tools": [
            WEATHER_TOOL,
            SYSTEM_HEALTH_TOOL,
        ],
        "tool_choice": "auto",
        "response_format": {"type": "text"},
    }

334
335
    base_url = f"http://localhost:{start_services.frontend_port}"
    response = _send_chat_request(payload, base_url=base_url)
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
    response_data = _validate_chat_response(response)

    logger.info("Tool call response: %s", response_data)

    choices = response_data.get("choices", [])
    assert choices, "Response missing choices"

    message = choices[0].get("message", {})
    tool_calls = message.get("tool_calls", [])

    assert tool_calls, "Expected model to generate tool calls for weather query"
    assert any(
        tc.get("function", {}).get("name") == "get_current_weather" for tc in tool_calls
    ), "Expected get_current_weather tool to be called"


352
# Measured using: tests/utils/profile_pytest.py tests/frontend/test_vllm.py::test_tool_calling_second_round
353
354
@pytest.mark.profiled_vram_gib(20.4)  # actual profiled peak
# TODO: profile with --kv-bytes once pre-existing 500 panic is fixed (JoinError::Panic "Cannot drop a runtime in a context where blocking is not allowed")
355
@pytest.mark.timeout(115)  # 3x observed 38.1s wall time
356
@pytest.mark.nightly
357
def test_tool_calling_second_round(
358
    request, start_services: ServicePorts, predownload_models
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
) -> None:
    """Test tool calling with a follow-up message containing assistant's prior tool calls."""

    payload = {
        "model": TEST_MODEL,
        "messages": [
            # First message
            {
                "role": "user",
                "content": "What is the weather like in San Francisco today?",
            },
            # Assistant message with tool calls
            {
                "role": "assistant",
                "tool_calls": [
                    {
                        "id": "call-1",
                        "type": "function",
                        "function": {
                            "name": "get_current_weather",
                            "arguments": '{"format":"celsius","location":"San Francisco"}',
                        },
                    }
                ],
            },
            # Tool message with tool call result
            {
                "role": "tool",
                "tool_call_id": "call-1",
                "content": '{"celsius":"20"}',
            },
        ],
        "max_tokens": 2000,
        "tools": [
            WEATHER_TOOL,
            SYSTEM_HEALTH_TOOL,
        ],
        "tool_choice": "auto",
        "response_format": {"type": "text"},
    }

400
401
    base_url = f"http://localhost:{start_services.frontend_port}"
    response = _send_chat_request(payload, base_url=base_url)
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
    response_data = _validate_chat_response(response)

    logger.info("Tool call second round response: %s", response_data)

    choices = response_data.get("choices", [])
    assert choices, "Response missing choices"

    message = choices[0].get("message", {})
    content = message.get("content", "").strip()

    assert content, "Expected model to generate a response with content"
    assert "20" in content and any(
        temp_word in content.lower()
        for temp_word in ["celsius", "temperature", "degrees", "°c", "20°"]
    ), "Expected response to include temperature information from tool call result (20°C)"


419
# Measured using: tests/utils/profile_pytest.py tests/frontend/test_vllm.py::test_reasoning
420
421
@pytest.mark.profiled_vram_gib(20.4)  # actual profiled peak
# TODO: profile with --kv-bytes once pre-existing 500 panic is fixed (JoinError::Panic "Cannot drop a runtime in a context where blocking is not allowed")
422
@pytest.mark.timeout(131)  # 3x observed 43.4s wall time
423
@pytest.mark.nightly
424
def test_reasoning(request, start_services: ServicePorts, predownload_models) -> None:
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
    """Test reasoning functionality with a mathematical problem."""

    payload = {
        "model": TEST_MODEL,
        "messages": [
            {
                "role": "user",
                "content": (
                    "I'm playing assetto corsa competizione, and I need you to tell me "
                    "how many liters of fuel to take in a race. The qualifying time was "
                    "2:04.317, the race is 20 minutes long, and the car uses 2.73 liters per lap."
                ),
            }
        ],
        "max_tokens": 2000,
    }

442
443
    base_url = f"http://localhost:{start_services.frontend_port}"
    response = _send_chat_request(payload, base_url=base_url)
444
445
446
447
448
449
450
451
452
453
454
455
456
457
    response_data = _validate_chat_response(response)

    logger.info("Reasoning response: %s", response_data)

    choices = response_data.get("choices", [])
    assert choices, "Response missing choices"

    message = choices[0].get("message", {})
    content = message.get("content", "").strip()

    assert content, "Expected model to generate a response with content"
    assert any(
        char.isdigit() for char in content
    ), "Expected response to contain numerical calculations"