test_async_llm_dp.py 10.8 KB
Newer Older
1
# SPDX-License-Identifier: Apache-2.0
2
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
3
4
5
6

import asyncio
import os
from contextlib import ExitStack
7
from dataclasses import dataclass
8
9
10
11

import pytest

from vllm import SamplingParams
12
from vllm.config import VllmConfig
13
14
from vllm.engine.arg_utils import AsyncEngineArgs
from vllm.inputs import PromptType
15
from vllm.outputs import RequestOutput
16
from vllm.platforms import current_platform
17
18
19
from vllm.sampling_params import RequestOutputKind
from vllm.v1.engine.async_llm import AsyncLLM
from vllm.v1.engine.core_client import DPAsyncMPClient
20
from vllm.v1.metrics.loggers import StatLoggerBase
21
from vllm.v1.metrics.stats import IterationStats, MultiModalCacheStats, SchedulerStats
22
23

DP_SIZE = int(os.getenv("DP_SIZE", 2))
24
25


26
async def generate(
27
28
29
30
31
    engine: AsyncLLM,
    request_id: str,
    prompt: PromptType,
    output_kind: RequestOutputKind,
    max_tokens: int,
32
33
    prompt_logprobs: int | None = None,
    data_parallel_rank: int | None = None,
34
) -> tuple[int, str]:
35
36
37
38
    # Ensure generate doesn't complete too fast for cancellation test.
    await asyncio.sleep(0.2)

    count = 0
39
40
41
42
43
44
45
46
47
48
49
50
51
    sampling_params = SamplingParams(
        max_tokens=max_tokens,
        ignore_eos=True,
        output_kind=output_kind,
        temperature=0,
        prompt_logprobs=prompt_logprobs,
    )
    async for out in engine.generate(
        request_id=request_id,
        prompt=prompt,
        sampling_params=sampling_params,
        data_parallel_rank=data_parallel_rank,
    ):
52
53
54
55
56
57
        num_tokens = len(out.outputs[0].token_ids)
        if output_kind == RequestOutputKind.DELTA:
            count += num_tokens
        else:
            count = num_tokens

58
        await asyncio.sleep(0.0)
59
60
61
62

    return count, request_id


63
64
65
66
67
68
69
@pytest.mark.parametrize(
    "model",
    [
        "ibm-research/PowerMoE-3b",
        "hmellor/tiny-random-LlamaForCausalLM",
    ],
)
70
@pytest.mark.parametrize(
Rui Qiao's avatar
Rui Qiao committed
71
72
73
74
75
76
77
    "output_kind",
    [
        RequestOutputKind.DELTA,
        RequestOutputKind.FINAL_ONLY,
    ],
)
@pytest.mark.parametrize("data_parallel_backend", ["mp", "ray"])
78
@pytest.mark.parametrize("async_scheduling", [True, False])
79
@pytest.mark.asyncio
80
async def test_load(
81
82
83
84
    model: str,
    output_kind: RequestOutputKind,
    data_parallel_backend: str,
    async_scheduling: bool,
85
):
86
87
88
    if async_scheduling and data_parallel_backend == "ray":
        # TODO(NickLucche) Re-enable when async scheduling is supported
        pytest.skip("Async scheduling is not supported with ray")
89
90
91
92
    elif data_parallel_backend == "ray" and current_platform.is_rocm():
        pytest.skip(
            "Ray as the distributed executor backend is not supported with ROCm."
        )
93
94
95
96
97
98
99
100
101
102
    stats_loggers = {}

    @dataclass
    class SimpleStatsLogger(StatLoggerBase):
        init_count: int = 0
        finished_req_count: int = 0

        def __init__(self, vllm_config: VllmConfig, engine_index: int = 0):
            stats_loggers[engine_index] = self

103
104
        def record(
            self,
105
106
107
            scheduler_stats: SchedulerStats | None,
            iteration_stats: IterationStats | None,
            mm_cache_stats: MultiModalCacheStats | None = None,
108
109
            engine_idx: int = 0,
        ):
110
            if iteration_stats:
111
                self.finished_req_count += len(iteration_stats.finished_requests)
112
113
114
115

        def log_engine_initialized(self):
            self.init_count += 1

116
117
118
    with ExitStack() as after:
        prompt = "This is a test of data parallel"

119
120
121
122
123
124
125
126
        engine_args = AsyncEngineArgs(
            model=model,
            enforce_eager=True,
            tensor_parallel_size=int(os.getenv("TP_SIZE", 1)),
            data_parallel_size=DP_SIZE,
            data_parallel_backend=data_parallel_backend,
            async_scheduling=async_scheduling,
        )
127
128
129
        engine = AsyncLLM.from_engine_args(
            engine_args, stat_loggers=[SimpleStatsLogger]
        )
130
131
132
133
134
135
136
137
138
139
140
141
        after.callback(engine.shutdown)

        NUM_REQUESTS = 100
        NUM_EXPECTED_TOKENS = 10

        request_ids = [f"request-{i}" for i in range(NUM_REQUESTS)]

        # Create concurrent requests.
        tasks = []
        for request_id in request_ids:
            tasks.append(
                asyncio.create_task(
142
143
144
145
146
                    generate(
                        engine, request_id, prompt, output_kind, NUM_EXPECTED_TOKENS
                    )
                )
            )
147
148
            # Short sleep to ensure that requests are distributed.
            await asyncio.sleep(0.01)
149
        # Confirm that we got all the EXPECTED tokens from the requests.
150
        done, pending = await asyncio.wait(tasks, return_when=asyncio.FIRST_EXCEPTION)
151
152
153
154
155
156
        for task in pending:
            task.cancel()
        for task in done:
            num_generated_tokens, request_id = await task
            assert num_generated_tokens == NUM_EXPECTED_TOKENS, (
                f"{request_id} generated {num_generated_tokens} but "
157
158
                f"expected {NUM_EXPECTED_TOKENS}"
            )
159
160
161
162
163
164
165
166

        assert not engine.output_processor.has_unfinished_requests()

        # testing internals here which may break
        core_client: DPAsyncMPClient = engine.engine_core
        # the engines only synchronize stopping every N steps so
        # allow a small amount of time here.
        for _ in range(10):
167
            if not core_client.engines_running:
168
169
170
                break
            await asyncio.sleep(0.5)

171
        assert not core_client.engines_running
172
        assert not core_client.reqs_in_flight
173
174
175
176
177
178
179
180
181

        # Check that requests were distributed between the engines
        print(f"Stats loggers after test: {stats_loggers}")
        assert len(stats_loggers) == DP_SIZE
        assert stats_loggers[0].init_count == 1

        for sl in stats_loggers.values():
            slogger: SimpleStatsLogger = sl

182
183
184
            assert slogger.finished_req_count > NUM_REQUESTS // (DP_SIZE + 1), (
                f"requests are imbalanced: {stats_loggers}"
            )
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
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
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
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326


# =============================================================================
# DP Pause/Resume Tests
# =============================================================================

DP_PAUSE_MODEL = "hmellor/tiny-random-LlamaForCausalLM"
DP_PAUSE_PROMPT = "This is a test of data parallel pause"


@pytest.mark.asyncio
async def test_dp_pause_resume_basic():
    """Pausing from the client (one call) pauses all DP ranks; resume clears it."""
    if current_platform.is_rocm():
        pytest.skip("DP pause tests use mp backend only")
    with ExitStack() as after:
        engine_args = AsyncEngineArgs(
            model=DP_PAUSE_MODEL,
            enforce_eager=True,
            tensor_parallel_size=int(os.getenv("TP_SIZE", 1)),
            data_parallel_size=DP_SIZE,
            data_parallel_backend="mp",
        )
        engine = AsyncLLM.from_engine_args(engine_args)
        after.callback(engine.shutdown)

        assert not await engine.is_paused()
        await engine.pause_generation(mode="abort")
        assert await engine.is_paused()
        await engine.resume_generation()
        assert not await engine.is_paused()

        # Engine still works after resume
        sampling_params = SamplingParams(max_tokens=5)
        async for out in engine.generate(
            request_id="after-resume",
            prompt=DP_PAUSE_PROMPT,
            sampling_params=sampling_params,
        ):
            pass
        assert out.finished


@pytest.mark.asyncio
async def test_dp_pause_abort():
    """Pause with abort from one client aborts in-flight requests on all DP ranks."""
    if current_platform.is_rocm():
        pytest.skip("DP pause tests use mp backend only")
    with ExitStack() as after:
        engine_args = AsyncEngineArgs(
            model=DP_PAUSE_MODEL,
            enforce_eager=True,
            tensor_parallel_size=int(os.getenv("TP_SIZE", 1)),
            data_parallel_size=DP_SIZE,
            data_parallel_backend="mp",
        )
        engine = AsyncLLM.from_engine_args(engine_args)
        after.callback(engine.shutdown)

        # Start several requests so they are distributed across ranks
        sampling_params = SamplingParams(max_tokens=500, ignore_eos=True)
        num_requests = 4
        outputs_by_id: dict[str, list[RequestOutput]] = {}

        async def gen(rid: str):
            out_list: list[RequestOutput] = []
            outputs_by_id[rid] = out_list
            async for out in engine.generate(
                request_id=rid,
                prompt=DP_PAUSE_PROMPT,
                sampling_params=sampling_params,
            ):
                out_list.append(out)
            return out_list[-1] if out_list else None

        tasks = [asyncio.create_task(gen(f"req-{i}")) for i in range(num_requests)]
        # Wait for some tokens on at least one request
        while not any(len(o) >= 2 for o in outputs_by_id.values()):
            await asyncio.sleep(0.02)

        await engine.pause_generation(mode="abort")

        finals = await asyncio.gather(*tasks)
        for i, final in enumerate(finals):
            assert final is not None, f"req-{i} had no output"
            assert final.finished
            assert final.outputs[0].finish_reason == "abort"

        assert await engine.is_paused()
        await engine.resume_generation()
        assert not await engine.is_paused()

        # New request completes after resume
        async for out in engine.generate(
            request_id="after-abort",
            prompt=DP_PAUSE_PROMPT,
            sampling_params=SamplingParams(max_tokens=5),
        ):
            pass
        assert out.finished
        assert not engine.output_processor.has_unfinished_requests()


@pytest.mark.asyncio
async def test_dp_pause_keep_then_resume():
    """Pause with keep queues new requests; resume allows them to run."""
    if current_platform.is_rocm():
        pytest.skip("DP pause tests use mp backend only")
    with ExitStack() as after:
        engine_args = AsyncEngineArgs(
            model=DP_PAUSE_MODEL,
            enforce_eager=True,
            tensor_parallel_size=int(os.getenv("TP_SIZE", 1)),
            data_parallel_size=DP_SIZE,
            data_parallel_backend="mp",
        )
        engine = AsyncLLM.from_engine_args(engine_args)
        after.callback(engine.shutdown)

        await engine.pause_generation(mode="keep")
        assert await engine.is_paused()

        request_done = asyncio.Event()

        async def gen():
            async for out in engine.generate(
                request_id="queued-keep",
                prompt=DP_PAUSE_PROMPT,
                sampling_params=SamplingParams(max_tokens=5),
            ):
                pass
            request_done.set()
            return out

        task = asyncio.create_task(gen())
        await asyncio.sleep(0.2)
        assert not request_done.is_set()

        await engine.resume_generation()
        final = await asyncio.wait_for(task, timeout=10.0)
        assert final.finished
        assert not await engine.is_paused()