test_model_runner.py 17.5 KB
Newer Older
1
2
# SPDX-License-Identifier: Apache-2.0

youkaichao's avatar
youkaichao committed
3
import pytest
4
5
import torch

6
7
from vllm.distributed.parallel_state import (ensure_model_parallel_initialized,
                                             init_distributed_environment)
8
from vllm.engine.arg_utils import EngineArgs
9
from vllm.model_executor.sampling_metadata import SamplingMetadata
10
from vllm.sequence import SamplingParams, SequenceData, SequenceGroupMetadata
11
from vllm.utils import get_open_port
12
from vllm.worker.model_runner import ModelRunner
13
14


15
16
17
18
def _create_model_runner(model: str, *args, **kwargs) -> ModelRunner:
    engine_args = EngineArgs(model, *args, **kwargs)
    engine_config = engine_args.create_engine_config()
    model_runner = ModelRunner(
19
        vllm_config=engine_config,
20
21
22
23
24
        is_driver_worker=True,
    )
    return model_runner


25
26
27
28
29
30
31
32
33
def test_deepseek_mla_attn_backend_module():
    model_runner = _create_model_runner(
        "deepseek-ai/DeepSeek-Coder-V2-Lite-Instruct",
        trust_remote_code=True,
        enable_chunked_prefill=False,
    )
    assert model_runner.attn_backend.__name__ == "TritonMLABackend"


34
35
36
37
38
39
40
@pytest.mark.parametrize("batch_size", list(range(1, 257, 3)))
@pytest.mark.parametrize("use_prompt_embeds", [True, False])
def test_prepare_prompt(batch_size, use_prompt_embeds, monkeypatch):
    if use_prompt_embeds:
        # Prompt Embeddings is only currently supported on V0
        monkeypatch.setenv("VLLM_USE_V1", "0")

41
42
43
44
45
46
    model_runner = _create_model_runner(
        "facebook/opt-125m",
        max_num_batched_tokens=100000,
        max_num_seqs=100000,
        enable_chunked_prefill=False,
    )
Woosuk Kwon's avatar
Woosuk Kwon committed
47

48
49
    seq_lens: list[int] = []
    seq_group_metadata_list: list[SequenceGroupMetadata] = []
50
    block_tables = {0: [1]}
51
    expected_input_embeds_len = 0
52
53
    for i in range(batch_size):
        # make sure all tokens fit into one block
54
55
        seq_len = i % (model_runner.block_size - 1) + 1
        seq_lens.append(seq_len)
56
57
58
59
60
61
62
63
64
        if use_prompt_embeds:
            seq_data = SequenceData.from_seqs(
                prompt_token_ids=[0] * seq_len,
                prompt_embeds=torch.rand(seq_len, 10),
            )
            expected_input_embeds_len += seq_len
        else:
            seq_data = SequenceData.from_seqs(prompt_token_ids=range(seq_len))

65
66
67
68
69
70
71
72
73
        seq_group_metadata = SequenceGroupMetadata(
            request_id=f"test_{i}",
            is_prompt=True,
            seq_data={0: seq_data},
            sampling_params=SamplingParams(temperature=0),
            block_tables=block_tables,
        )
        assert seq_group_metadata.token_chunk_size == seq_data.get_len()
        seq_group_metadata_list.append(seq_group_metadata)
Woosuk Kwon's avatar
Woosuk Kwon committed
74

75
76
    expected_selected_token_indices = []
    selected_token_start_idx = 0
77
    for seq_len in seq_lens:
78
        expected_selected_token_indices.append(selected_token_start_idx +
79
80
                                               seq_len - 1)
        selected_token_start_idx += seq_len
81
82
    model_input = model_runner._prepare_model_input_tensors(
        seq_group_metadata_list)
83
84
    input_tokens = model_input.input_tokens
    input_positions = model_input.input_positions
85
    input_embeds = model_input.inputs_embeds
86
87
    attn_metadata = model_input.attn_metadata
    return_seq_lens = model_input.seq_lens
88
    slot_mapping = attn_metadata.slot_mapping
89
    assert return_seq_lens == seq_lens
90
    assert len(slot_mapping) == len(input_tokens)
91
92
93

    # Verify input metadata is correct for prompts.
    device = model_runner.device
94
95
    assert attn_metadata.num_prefills > 0
    assert attn_metadata.num_decode_tokens == 0
96
    torch.testing.assert_close(
97
98
99
        attn_metadata.seq_lens_tensor,
        torch.tensor(seq_lens, device=device, dtype=torch.int))
    assert attn_metadata.seq_lens == seq_lens
100
101
    assert attn_metadata.max_prefill_seq_len == max(seq_lens)
    assert attn_metadata.max_decode_seq_len == 0
102
103
104
105

    # Test subquery start locs.
    start_idx = 0
    start_loc = [start_idx]
106
107
    for seq_len in seq_lens:
        start_idx += seq_len
108
        start_loc.append(start_idx)
109
    torch.testing.assert_close(
110
        attn_metadata.query_start_loc,
111
112
113
        torch.tensor(start_loc, dtype=torch.int32, device=device))

    # Test seq start locs. Note that for normal prefill it is
114
    # equivalent to query_start_loc.
115
116
    start_idx = 0
    seq_start_loc = [start_idx]
117
118
    for seq_len in seq_lens:
        start_idx += seq_len
119
120
        seq_start_loc.append(start_idx)

121
    torch.testing.assert_close(
122
        attn_metadata.seq_start_loc,
123
        torch.tensor(start_loc, dtype=torch.int32, device=device))
124
    torch.testing.assert_close(
125
126
        attn_metadata.context_lens_tensor,
        torch.zeros(attn_metadata.context_lens_tensor.shape[0],
127
128
129
130
131
132
                    dtype=torch.int,
                    device=device))

    expected = torch.tensor([[] for _ in range(len(seq_group_metadata_list))],
                            dtype=torch.int32,
                            device=model_runner.device)
133
    torch.testing.assert_close(attn_metadata.block_tables, expected)
134
    # Cuda graph should not be used for prerill.
135
    assert attn_metadata.use_cuda_graph is False
136

137
138
    assert len(input_tokens) == sum(seq_lens)
    assert len(input_positions) == sum(seq_lens)
139
140
141
142
143
    if expected_input_embeds_len == 0:
        torch.testing.assert_close(input_tokens, input_positions)
        assert input_embeds is None
    else:
        assert len(input_embeds) == expected_input_embeds_len
144

145
146
    sampling_metadata = SamplingMetadata.prepare(
        seq_group_metadata_list,
147
148
        seq_lens,
        query_lens=seq_lens,
149
150
        device=model_runner.device,
        pin_memory=model_runner.pin_memory)
151
152
    assert len(input_tokens) == sum(seq_lens)
    assert len(input_positions) == sum(seq_lens)
153
154
155
156
157
    actual = sampling_metadata.selected_token_indices
    expected = torch.tensor(expected_selected_token_indices,
                            device=actual.device,
                            dtype=actual.dtype)
    torch.testing.assert_close(actual, expected)
158
    torch.allclose(input_tokens, input_positions)
159
160
161
162
163
164
165
166

    actual = sampling_metadata.selected_token_indices
    expected = torch.tensor(expected_selected_token_indices,
                            device=actual.device,
                            dtype=actual.dtype)
    torch.testing.assert_close(actual, expected)


167
168
169
170
171
172
173
@pytest.mark.parametrize("batch_size", list(range(1, 257, 3)))
@pytest.mark.parametrize("use_prompt_embeds", [True, False])
def test_prepare_decode_cuda_graph(batch_size, use_prompt_embeds, monkeypatch):
    if use_prompt_embeds:
        # Prompt Embeddings is only currently supported on V0
        monkeypatch.setenv("VLLM_USE_V1", "0")

174
    model_runner = _create_model_runner(
175
176
177
178
        "facebook/opt-125m",
        seed=0,
        dtype="float16",
        enforce_eager=False,
179
180
181
        max_num_batched_tokens=100000,
        max_num_seqs=100000,
        enable_chunked_prefill=False,
182
183
    )

184
185
    context_lens: list[int] = []
    seq_group_metadata_list: list[SequenceGroupMetadata] = []
186
    # Assume each seq group finishes prefill.
187
188
    for i in range(batch_size):
        # make sure all tokens fit into one block
189
190
        context_len = i % (model_runner.block_size - 1) + 1
        context_lens.append(context_len)
191
192
193
194
195
196
197
198
199
200
        if use_prompt_embeds:
            seq_data = SequenceData.from_seqs(
                prompt_token_ids=[0] * context_len,
                prompt_embeds=torch.rand(context_len, 10),
            )
            output_embed = torch.rand(10)
        else:
            seq_data = SequenceData.from_seqs(
                prompt_token_ids=range(context_len))
            output_embed = None
201
202
        seq_data.update_num_computed_tokens(context_len)
        # Append one token ID since prefill is finished.
203
        seq_data.append_token_id(1, 0, output_embed)
204
205
206
207
208
209
210
211
212
        seq_group_metadata = SequenceGroupMetadata(
            request_id=f"test_{i}",
            is_prompt=False,
            seq_data={0: seq_data},
            sampling_params=SamplingParams(temperature=0),
            block_tables={0: [1]},
        )
        assert seq_group_metadata.token_chunk_size == 1
        seq_group_metadata_list.append(seq_group_metadata)
213

214
215
    model_input = model_runner._prepare_model_input_tensors(
        seq_group_metadata_list)
216
217
218
219
220
221
    input_tokens = model_input.input_tokens
    input_positions = model_input.input_positions
    input_embeds = model_input.inputs_embeds
    attn_metadata = model_input.attn_metadata
    slot_mapping = attn_metadata.slot_mapping

222
    assert len(slot_mapping) == len(input_tokens)
223

224
225
    expected_bs = model_runner.vllm_config.pad_for_cudagraph(
        len(seq_group_metadata_list))
226
227
    # Verify input metadata is correct for prompts.
    device = model_runner.device
228
229
230
231
232
233
234
    assert attn_metadata.num_prefills == 0
    assert attn_metadata.num_prefill_tokens == 0
    seq_lens = [context_len + 1 for context_len in context_lens]
    # seq_lens are padded to expected_bs
    for _ in range(expected_bs - len(seq_lens)):
        seq_lens.append(1)
    assert attn_metadata.seq_lens == seq_lens
235
    assert attn_metadata.num_decode_tokens == len(seq_lens)
236
237
238
239
240
241
    start_idx = 0
    start_loc = [start_idx]
    for _ in context_lens:
        # decode has only 1 token for query.
        start_idx += 1
        start_loc.append(start_idx)
242
    torch.testing.assert_close(
243
244
245
246
247
248
249
250
        attn_metadata.query_start_loc,
        torch.tensor(start_loc, dtype=torch.int32, device=device))

    start_idx = 0
    seq_start_loc = [start_idx]
    for seq_len in seq_lens:
        start_idx += seq_len
        seq_start_loc.append(start_idx)
251
    torch.testing.assert_close(
252
253
254
        attn_metadata.seq_start_loc,
        torch.tensor(seq_start_loc, dtype=torch.int32, device=device))

255
    torch.testing.assert_close(
256
257
258
        attn_metadata.context_lens_tensor,
        torch.tensor(context_lens, dtype=torch.int, device=device))
    assert attn_metadata.max_decode_seq_len == max(seq_lens)
259
    torch.testing.assert_close(
260
261
        attn_metadata.seq_lens_tensor[:len(seq_lens)],
        torch.tensor(seq_lens, dtype=torch.int, device=device))
262
263
264

    # block table's first index corresponds to each batch, meaning in
    # decoding it is each token.
265
    assert attn_metadata.block_tables.shape[0] == len(input_tokens)
266
    # Block table's second dim corresponds to each token's block number.
267
    # It is padded up to
268
    assert attn_metadata.block_tables.shape[1] == (
269
        model_runner.get_max_block_per_batch())
270
    assert attn_metadata.use_cuda_graph is True
271

272
273
    assert len(input_tokens) == expected_bs
    assert len(input_positions) == expected_bs
274
275
276
277
278
279
    if use_prompt_embeds:
        expected_input_embeds_length = start_loc[-1]
        assert len(input_embeds) == expected_input_embeds_length
        assert expected_input_embeds_length <= expected_bs
    else:
        assert input_embeds is None
Woosuk Kwon's avatar
Woosuk Kwon committed
280

281
282
    # Verify Sampling
    expected_selected_token_indices = []
283
    for selected_token_start_idx, _ in enumerate(context_lens):
284
        expected_selected_token_indices.append(selected_token_start_idx)
285
286
    sampling_metadata = SamplingMetadata.prepare(
        seq_group_metadata_list,
287
        seq_lens,
288
289
        # query lens is all 1 for decode.
        query_lens=[1 for _ in range(len(context_lens))],
290
291
        device=model_runner.device,
        pin_memory=model_runner.pin_memory)
Woosuk Kwon's avatar
Woosuk Kwon committed
292
    actual = sampling_metadata.selected_token_indices
293
294
295
296
    expected = torch.tensor(expected_selected_token_indices,
                            device=actual.device,
                            dtype=actual.dtype)
    torch.testing.assert_close(actual, expected)
297
298
299
300


def test_empty_seq_group():
    """Verify prepare prompt and decode returns empty output."""
301
    model_runner = _create_model_runner(
302
303
304
305
306
        "facebook/opt-125m",
        seed=0,
        dtype="float16",
        enforce_eager=False,
    )
307
    seq_group_metadata_list: list[SequenceGroupMetadata] = []
308
309
    model_input = model_runner._prepare_model_input_tensors(
        seq_group_metadata_list)
310
311
312
313
314

    input_tokens = model_input.input_tokens
    input_positions = model_input.input_positions
    attn_metadata = model_input.attn_metadata

315
316
    assert input_tokens is None
    assert input_positions is None
317
    assert attn_metadata is None
318
319
320

    model_input = model_runner._prepare_model_input_tensors(
        seq_group_metadata_list)
321
322
323
324
325
326
327

    input_tokens = model_input.input_tokens
    input_positions = model_input.input_positions
    input_embeds = model_input.inputs_embeds
    attn_metadata = model_input.attn_metadata
    return_seq_lens = model_input.seq_lens

328
329
    assert input_tokens is None
    assert input_positions is None
330
    assert input_embeds is None
331
    assert attn_metadata is None
332
    assert return_seq_lens is None
333
334


335
336
337
338
339
340
341
@pytest.fixture
def distributed_init():
    init_distributed_environment(
        world_size=1,
        rank=0,
        distributed_init_method=f"tcp://127.0.0.1:{get_open_port()}",
        local_rank=0)
342
    ensure_model_parallel_initialized(1, 1)
343
344


345
@pytest.mark.parametrize("batch_size", list(range(2, 128, 3)))
346
@pytest.mark.parametrize("enforce_eager", [True, False])
347
348
349
350
351
352
353
@pytest.mark.parametrize('use_prompt_embeds', [True, False])
def test_hybrid_batches(batch_size, enforce_eager, use_prompt_embeds,
                        distributed_init, monkeypatch):
    if use_prompt_embeds:
        # Prompt Embeddings is only currently supported on V0
        monkeypatch.setenv("VLLM_USE_V1", "0")

354
    model_runner = _create_model_runner(
355
356
357
358
        "facebook/opt-125m",
        seed=0,
        dtype="float16",
        enforce_eager=enforce_eager,
359
360
361
        max_num_batched_tokens=100000,
        max_num_seqs=100000,
        enable_chunked_prefill=True,
362
363
364
    )

    # Add prefill requests.
365
366
367
368
    seq_lens: list[int] = []
    seq_group_metadata_list: list[SequenceGroupMetadata] = []
    prefill_metadata_list: list[SequenceGroupMetadata] = []
    decode_metadata_list: list[SequenceGroupMetadata] = []
369
370
371
    block_tables = {0: [1]}
    prefill_batch_size = batch_size // 2
    decode_batch_size = batch_size - prefill_batch_size
372
    expected_input_embeds_len = 0
373
374
    for i in range(prefill_batch_size):
        # make sure all tokens fit into one block
375
376
        seq_len = i % (model_runner.block_size - 1) + 1
        seq_lens.append(seq_len)
377
378
379
380
381
382
383
384
385
        if use_prompt_embeds:
            seq_data = SequenceData.from_seqs(
                prompt_token_ids=[0] * seq_len,
                prompt_embeds=torch.rand(seq_len, 10),
            )
            expected_input_embeds_len += seq_len
        else:
            seq_data = SequenceData.from_seqs(
                prompt_token_ids=range(seq_len), )
386
387
388
389
390
391
392
393
394
395
396
397
398
399
        seq_group_metadata = SequenceGroupMetadata(
            request_id=f"test_{i}",
            is_prompt=True,
            seq_data={0: seq_data},
            sampling_params=SamplingParams(temperature=0),
            block_tables=block_tables,
        )
        assert seq_group_metadata.token_chunk_size == seq_data.get_len()
        seq_group_metadata_list.append(seq_group_metadata)
        prefill_metadata_list.append(seq_group_metadata)

    # Add decode requests
    for i in range(prefill_batch_size, batch_size):
        # make sure all tokens fit into one block
400
        context_len = i % (model_runner.block_size - 1) + 1
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
        if use_prompt_embeds:
            seq_data = SequenceData.from_seqs(
                prompt_token_ids=[0] * context_len,
                prompt_embeds=torch.rand(context_len, 10),
            )
            output_embed = torch.rand(10)
            # This also iterates the expected input_embeds, because the model
            # needs both the input and output embeddings passed into together
            expected_input_embeds_len += 1
        else:
            seq_data = SequenceData.from_seqs(
                prompt_token_ids=range(context_len), )
            output_embed = None
        assert len(seq_data.prompt_token_ids) == context_len
        seq_data.append_token_id(1, 0, output_embed)
416
        seq_data.update_num_computed_tokens(context_len)
417
418
419
420
421
422
423
424
425
426
427
        seq_group_metadata = SequenceGroupMetadata(
            request_id=f"test_{i}",
            is_prompt=False,
            seq_data={0: seq_data},
            sampling_params=SamplingParams(temperature=0),
            block_tables={0: [1]},
        )
        assert seq_group_metadata.token_chunk_size == 1
        seq_group_metadata_list.append(seq_group_metadata)
        decode_metadata_list.append(seq_group_metadata)

428
    model_input = model_runner.prepare_model_input(seq_group_metadata_list)
429
430
431
432
433

    input_tokens = model_input.input_tokens
    input_positions = model_input.input_positions
    input_embeds = model_input.inputs_embeds
    attn_metadata = model_input.attn_metadata
434
435
436
437
438
439
440

    prefill_meta_actual = attn_metadata.prefill_metadata
    decode_meta_actual = attn_metadata.decode_metadata

    assert len(attn_metadata.slot_mapping) == len(input_tokens)
    assert len(input_positions) == len(input_tokens)
    assert attn_metadata.num_prefills == prefill_batch_size
441
    assert attn_metadata.num_decode_tokens == decode_batch_size
442
    assert attn_metadata.num_prefill_tokens == sum(seq_lens)
443
444
445
446
    if expected_input_embeds_len == 0:
        assert input_embeds is None
    else:
        assert len(input_embeds) == expected_input_embeds_len
447
448
449

    # Verify attn metadata is consistent. We don't need to test individual
    # values here because they are tested above.
450
    attn_metadata = model_runner._prepare_model_input_tensors(
451
        seq_group_metadata_list).attn_metadata
452

453
    for attr_expected, attr_actual in zip(vars(attn_metadata.prefill_metadata),
454
455
                                          vars(prefill_meta_actual)):
        assert attr_expected[1] == attr_actual[1]
456
    for attr_expected, attr_actual in zip(vars(attn_metadata.decode_metadata),
457
458
                                          vars(decode_meta_actual)):
        assert attr_expected[1] == attr_actual[1]