test_model_runner.py 17.6 KB
Newer Older
1
# SPDX-License-Identifier: Apache-2.0
2
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
3

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

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


16
17
18
19
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(
20
        vllm_config=engine_config,
21
22
23
24
25
        is_driver_worker=True,
    )
    return model_runner


26
27
28
29
30
31
32
33
34
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"


35
36
37
38
39
40
41
@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")

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,
47
        enable_prompt_embeds=True,
48
    )
Woosuk Kwon's avatar
Woosuk Kwon committed
49

50
51
    seq_lens: list[int] = []
    seq_group_metadata_list: list[SequenceGroupMetadata] = []
52
    block_tables = {0: [1]}
53
    expected_input_embeds_len = 0
54
55
    for i in range(batch_size):
        # make sure all tokens fit into one block
56
57
        seq_len = i % (model_runner.block_size - 1) + 1
        seq_lens.append(seq_len)
58
59
60
61
62
63
64
65
66
        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))

67
68
69
70
71
72
73
74
75
        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
76

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

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

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

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

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

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

139
140
    assert len(input_tokens) == sum(seq_lens)
    assert len(input_positions) == sum(seq_lens)
141
142
143
144
145
    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
146

147
148
    sampling_metadata = SamplingMetadata.prepare(
        seq_group_metadata_list,
149
150
        seq_lens,
        query_lens=seq_lens,
151
152
        device=model_runner.device,
        pin_memory=model_runner.pin_memory)
153
154
    assert len(input_tokens) == sum(seq_lens)
    assert len(input_positions) == sum(seq_lens)
155
156
157
158
159
    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)
160
    torch.allclose(input_tokens, input_positions)
161
162
163
164
165
166
167
168

    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)


169
170
171
172
173
174
175
@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")

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

187
188
    context_lens: list[int] = []
    seq_group_metadata_list: list[SequenceGroupMetadata] = []
189
    # Assume each seq group finishes prefill.
190
191
    for i in range(batch_size):
        # make sure all tokens fit into one block
192
193
        context_len = i % (model_runner.block_size - 1) + 1
        context_lens.append(context_len)
194
195
196
197
198
199
200
201
202
203
        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
204
205
        seq_data.update_num_computed_tokens(context_len)
        # Append one token ID since prefill is finished.
206
        seq_data.append_token_id(1, 0, output_embed)
207
208
209
210
211
212
213
214
215
        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)
216

217
218
    model_input = model_runner._prepare_model_input_tensors(
        seq_group_metadata_list)
219
220
221
222
223
224
    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

225
    assert len(slot_mapping) == len(input_tokens)
226

227
228
    expected_bs = model_runner.vllm_config.pad_for_cudagraph(
        len(seq_group_metadata_list))
229
230
    # Verify input metadata is correct for prompts.
    device = model_runner.device
231
232
233
234
235
236
237
    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
238
    assert attn_metadata.num_decode_tokens == len(seq_lens)
239
240
241
242
243
244
    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)
245
    torch.testing.assert_close(
246
247
248
249
250
251
252
253
        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)
254
    torch.testing.assert_close(
255
256
257
        attn_metadata.seq_start_loc,
        torch.tensor(seq_start_loc, dtype=torch.int32, device=device))

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

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

275
276
    assert len(input_tokens) == expected_bs
    assert len(input_positions) == expected_bs
277
278
279
280
281
282
    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
283

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


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

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

318
319
    assert input_tokens is None
    assert input_positions is None
320
    assert attn_metadata is None
321
322
323

    model_input = model_runner._prepare_model_input_tensors(
        seq_group_metadata_list)
324
325
326
327
328
329
330

    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

331
332
    assert input_tokens is None
    assert input_positions is None
333
    assert input_embeds is None
334
    assert attn_metadata is None
335
    assert return_seq_lens is None
336
337


338
339
340
341
342
343
344
@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)
345
    ensure_model_parallel_initialized(1, 1)
346
347


348
@pytest.mark.parametrize("batch_size", list(range(2, 128, 3)))
349
@pytest.mark.parametrize("enforce_eager", [True, False])
350
351
352
353
354
355
356
@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")

357
    model_runner = _create_model_runner(
358
359
360
361
        "facebook/opt-125m",
        seed=0,
        dtype="float16",
        enforce_eager=enforce_eager,
362
363
364
        max_num_batched_tokens=100000,
        max_num_seqs=100000,
        enable_chunked_prefill=True,
365
        enable_prompt_embeds=True,
366
367
368
    )

    # Add prefill requests.
369
370
371
372
    seq_lens: list[int] = []
    seq_group_metadata_list: list[SequenceGroupMetadata] = []
    prefill_metadata_list: list[SequenceGroupMetadata] = []
    decode_metadata_list: list[SequenceGroupMetadata] = []
373
374
375
    block_tables = {0: [1]}
    prefill_batch_size = batch_size // 2
    decode_batch_size = batch_size - prefill_batch_size
376
    expected_input_embeds_len = 0
377
378
    for i in range(prefill_batch_size):
        # make sure all tokens fit into one block
379
380
        seq_len = i % (model_runner.block_size - 1) + 1
        seq_lens.append(seq_len)
381
382
383
384
385
386
387
388
389
        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), )
390
391
392
393
394
395
396
397
398
399
400
401
402
403
        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
404
        context_len = i % (model_runner.block_size - 1) + 1
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
        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)
420
        seq_data.update_num_computed_tokens(context_len)
421
422
423
424
425
426
427
428
429
430
431
        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)

432
    model_input = model_runner.prepare_model_input(seq_group_metadata_list)
433
434
435
436
437

    input_tokens = model_input.input_tokens
    input_positions = model_input.input_positions
    input_embeds = model_input.inputs_embeds
    attn_metadata = model_input.attn_metadata
438
439
440
441
442
443
444

    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
445
    assert attn_metadata.num_decode_tokens == decode_batch_size
446
    assert attn_metadata.num_prefill_tokens == sum(seq_lens)
447
448
449
450
    if expected_input_embeds_len == 0:
        assert input_embeds is None
    else:
        assert len(input_embeds) == expected_input_embeds_len
451
452
453

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

457
    for attr_expected, attr_actual in zip(vars(attn_metadata.prefill_metadata),
458
459
                                          vars(prefill_meta_actual)):
        assert attr_expected[1] == attr_actual[1]
460
    for attr_expected, attr_actual in zip(vars(attn_metadata.decode_metadata),
461
462
                                          vars(decode_meta_actual)):
        assert attr_expected[1] == attr_actual[1]