test_multi_api_servers.py 5.65 KB
Newer Older
1
# SPDX-License-Identifier: Apache-2.0
2
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
3
4
5
6
7
8
9
10
import asyncio
import os

import openai  # use the official client for correctness check
import pytest
import pytest_asyncio

from tests.utils import RemoteOpenAIServer
11
from tests.v1.utils import check_request_balancing
12

13
MODEL_NAME = "hmellor/tiny-random-LlamaForCausalLM"
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52

DP_SIZE = os.getenv("DP_SIZE", "1")


@pytest.fixture(scope="module")
def default_server_args():
    return [
        # use half precision for speed and memory savings in CI environment
        "--dtype",
        "bfloat16",
        "--max-model-len",
        "2048",
        "--max-num-seqs",
        "128",
        "--enforce-eager",
        "--api-server-count",
        "4",
        "--data_parallel_size",
        DP_SIZE,
    ]


@pytest.fixture(scope="module")
def server(default_server_args):
    with RemoteOpenAIServer(MODEL_NAME, default_server_args) as remote_server:
        yield remote_server


@pytest_asyncio.fixture
async def client(server):
    async with server.get_async_client() as async_client:
        yield async_client


@pytest.mark.asyncio
@pytest.mark.parametrize(
    "model_name",
    [MODEL_NAME],
)
53
54
55
async def test_single_completion(
    client: openai.AsyncOpenAI, server: RemoteOpenAIServer, model_name: str
) -> None:
56
57
    async def make_request():
        completion = await client.completions.create(
58
59
            model=model_name, prompt="Hello, my name is", max_tokens=10, temperature=1.0
        )
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98

        assert completion.id is not None
        assert completion.choices is not None and len(completion.choices) == 1

        choice = completion.choices[0]
        # The exact number of tokens can vary slightly with temperature=1.0,
        # so we check for a reasonable minimum length.
        assert len(choice.text) >= 1
        # Finish reason might not always be 'length' if the model finishes early
        # or due to other reasons, especially with high temperature.
        # So, we'll accept 'length' or 'stop'.
        assert choice.finish_reason in ("length", "stop")

        # Token counts can also vary, so we check they are positive.
        assert completion.usage.completion_tokens > 0
        assert completion.usage.prompt_tokens > 0
        assert completion.usage.total_tokens > 0
        return completion

    # Test single request
    result = await make_request()
    assert result is not None

    await asyncio.sleep(0.5)

    # Send two bursts of requests
    num_requests = 100
    tasks = [make_request() for _ in range(num_requests)]
    results = await asyncio.gather(*tasks)
    assert len(results) == num_requests
    assert all(completion is not None for completion in results)

    await asyncio.sleep(0.5)

    tasks = [make_request() for _ in range(num_requests)]
    results = await asyncio.gather(*tasks)
    assert len(results) == num_requests
    assert all(completion is not None for completion in results)

99
    # Check request balancing via Prometheus metrics if DP_SIZE > 1
100
    check_request_balancing(server, int(DP_SIZE))
101

102
103
104
105
106
107

@pytest.mark.asyncio
@pytest.mark.parametrize(
    "model_name",
    [MODEL_NAME],
)
108
109
110
async def test_completion_streaming(
    client: openai.AsyncOpenAI, server: RemoteOpenAIServer, model_name: str
) -> None:
111
112
113
114
115
116
117
118
119
120
121
122
123
    prompt = "What is an LLM?"

    async def make_streaming_request():
        # Perform a non-streaming request to get the expected full output
        single_completion = await client.completions.create(
            model=model_name,
            prompt=prompt,
            max_tokens=5,
            temperature=0.0,
        )
        single_output = single_completion.choices[0].text

        # Perform the streaming request
124
125
126
        stream = await client.completions.create(
            model=model_name, prompt=prompt, max_tokens=5, temperature=0.0, stream=True
        )
127
128
129
130
131
132
133
134
135
136
        chunks: list[str] = []
        finish_reason_count = 0
        last_chunk = None
        async for chunk in stream:
            chunks.append(chunk.choices[0].text)
            if chunk.choices[0].finish_reason is not None:
                finish_reason_count += 1
            last_chunk = chunk  # Keep track of the last chunk

        # finish reason should only return in the last block for OpenAI API
137
138
139
140
141
        assert finish_reason_count == 1, "Finish reason should appear exactly once."
        assert last_chunk is not None, "Stream should have yielded at least one chunk."
        assert last_chunk.choices[0].finish_reason == "length", (
            "Finish reason should be 'length'."
        )
142
        # Check that the combined text matches the non-streamed version.
143
144
145
        assert "".join(chunks) == single_output, (
            "Streamed output should match non-streamed output."
        )
146
147
148
149
150
151
152
153
154
155
156
157
158
        return True  # Indicate success for this request

    # Test single request
    result = await make_streaming_request()
    assert result is not None

    await asyncio.sleep(0.5)

    # Send two bursts of requests
    num_requests = 100
    tasks = [make_streaming_request() for _ in range(num_requests)]
    results = await asyncio.gather(*tasks)

159
160
161
    assert len(results) == num_requests, (
        f"Expected {num_requests} results, got {len(results)}"
    )
162
163
164
165
166
167
168
    assert all(results), "Not all streaming requests completed successfully."

    await asyncio.sleep(0.5)

    tasks = [make_streaming_request() for _ in range(num_requests)]
    results = await asyncio.gather(*tasks)

169
170
171
    assert len(results) == num_requests, (
        f"Expected {num_requests} results, got {len(results)}"
    )
172
    assert all(results), "Not all streaming requests completed successfully."
173
174

    # Check request balancing via Prometheus metrics if DP_SIZE > 1
175
    check_request_balancing(server, int(DP_SIZE))