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

4
import warnings
5
from collections.abc import Mapping
6
from typing import Literal
7
8

import pytest
9
import torch
10

11
from vllm.assets.audio import AudioAsset
12
from vllm.assets.image import ImageAsset
13
from vllm.assets.video import VideoAsset
14
from vllm.config import ModelConfig
15
16
from vllm.entrypoints.chat_utils import (
    parse_chat_messages,
17
    parse_chat_messages_async,
18
)
19
from vllm.multimodal import MultiModalDataDict, MultiModalUUIDDict
20
from vllm.multimodal.utils import (
21
22
23
    encode_audio_url,
    encode_image_url,
    encode_video_url,
24
)
25
from vllm.utils.serial_utils import tensor2base64
26
27

PHI3V_MODEL_ID = "microsoft/Phi-3.5-vision-instruct"
28
QWEN2AUDIO_MODEL_ID = "Qwen/Qwen2-Audio-7B-Instruct"
29
QWEN25OMNI_MODEL_ID = "Qwen/Qwen2.5-Omni-7B"
30
MISTRAL_MODEL_ID = "mistralai/Mistral-Small-3.1-24B-Instruct-2503"
31
32


33
@pytest.fixture(scope="function")
34
def phi3v_model_config():
35
36
37
38
39
40
41
42
    return ModelConfig(
        PHI3V_MODEL_ID,
        runner="generate",
        trust_remote_code=True,
        limit_mm_per_prompt={
            "image": 2,
        },
    )
43
44


45
46
@pytest.fixture(scope="function")
def phi3v_model_config_mm_interleaved():
47
48
49
50
51
52
53
54
55
    return ModelConfig(
        PHI3V_MODEL_ID,
        runner="generate",
        trust_remote_code=True,
        interleave_mm_strings=True,
        limit_mm_per_prompt={
            "image": 2,
        },
    )
56
57


58
59
60
61
62
63
64
65
66
67
68
69
70
@pytest.fixture(scope="function")
def phi3v_model_config_image_embeds():
    return ModelConfig(
        PHI3V_MODEL_ID,
        runner="generate",
        trust_remote_code=True,
        limit_mm_per_prompt={
            "image": 2,
        },
        enable_mm_embeds=True,
    )


71
72
73
74
75
76
77
78
79
80
@pytest.fixture(scope="function")
def qwen25omni_model_config_image_embeds():
    return ModelConfig(
        QWEN25OMNI_MODEL_ID,
        runner="generate",
        limit_mm_per_prompt={"image": 2},
        enable_mm_embeds=True,
    )


81
82
83
84
85
86
87
88
89
90
91
92
@pytest.fixture(scope="function")
def qwen2_audio_model_config():
    return ModelConfig(
        QWEN2AUDIO_MODEL_ID,
        runner="generate",
        trust_remote_code=True,
        limit_mm_per_prompt={
            "audio": 1,
        },
    )


93
94
95
96
97
98
99
100
101
102
103
104
105
@pytest.fixture(scope="function")
def audio_embeds_model_config():
    return ModelConfig(
        QWEN2AUDIO_MODEL_ID,
        runner="generate",
        trust_remote_code=True,
        limit_mm_per_prompt={
            "audio": 2,
        },
        enable_mm_embeds=True,
    )


106
107
@pytest.fixture(scope="function")
def qwen25omni_model_config_mm_interleaved():
108
109
110
111
112
113
114
115
116
117
    return ModelConfig(
        QWEN25OMNI_MODEL_ID,
        runner="generate",
        interleave_mm_strings=True,
        limit_mm_per_prompt={
            "image": 2,
            "audio": 1,
            "video": 1,
        },
    )
118
119


120
121
@pytest.fixture(scope="function")
def mistral_model_config():
122
123
124
125
126
127
128
    return ModelConfig(
        MISTRAL_MODEL_ID,
        runner="generate",
        limit_mm_per_prompt={
            "image": 2,
        },
    )
129
130


131
132
@pytest.fixture(scope="module")
def image_url():
133
    image = ImageAsset("cherry_blossom")
134
    return encode_image_url(image.pil_image)
135
136


137
138
@pytest.fixture(scope="module")
def video_url():
139
    video = VideoAsset("baby_reading", 1)
140
    return encode_video_url(video.np_ndarrays)
141
142
143
144


@pytest.fixture(scope="module")
def audio_url():
145
    audio = AudioAsset("mary_had_lamb")
146
    return encode_audio_url(*audio.audio_and_sample_rate)
147
148


149
def _assert_mm_data_is_image_input(
150
    mm_data: MultiModalDataDict | None,
151
    image_count: int,
152
    skipped_image_indices: list | None = None,
153
154
155
156
157
158
159
) -> None:
    assert mm_data is not None
    assert set(mm_data.keys()) == {"image"}

    image_data = mm_data.get("image")
    assert image_data is not None

160
    assert isinstance(image_data, list) and len(image_data) == image_count
161
162
163
    if skipped_image_indices is not None:
        for i in skipped_image_indices:
            assert image_data[i] is None
164
165


166
def _assert_mm_uuids(
167
    mm_uuids: MultiModalUUIDDict | None,
168
    media_count: int,
169
    expected_uuids: list[str | None],
170
171
172
173
174
175
176
177
178
    modality: str = "image",
) -> None:
    if len(expected_uuids) > 0:
        assert mm_uuids is not None
        assert modality in mm_uuids

        image_uuids = mm_uuids.get(modality)
        assert image_uuids is not None

179
        assert isinstance(image_uuids, list) and len(image_uuids) == media_count
180
181
182
183
184
185

        assert image_uuids == expected_uuids
    else:
        assert mm_uuids is None


186
187
188
189
190
ModalityType = Literal["image", "video", "audio"]
MultiModalDataCounts = Mapping[ModalityType, int]


def _assert_mm_data_inputs(
191
    mm_data: MultiModalDataDict | None,
192
    data_count: MultiModalDataCounts,
193
    skipped_media_indices: dict[str, list] | None = None,  # modality -> list[int]
194
195
196
197
198
199
200
201
202
) -> None:
    assert mm_data is not None
    assert set(data_count.keys()) == (set(mm_data.keys()))

    for modality, n in data_count.items():
        modality_data = mm_data.get(modality)
        assert modality_data is not None
        assert isinstance(modality_data, list) and len(modality_data) == n

203
        if skipped_media_indices is not None:
204
            skipped_media_indices_for_modality = skipped_media_indices.get(modality)
205
206
207
208
            assert skipped_media_indices_for_modality is not None
            for i in skipped_media_indices_for_modality:
                assert modality_data[i] is None

209

210
211
212
213
def test_parse_chat_messages_single_image(
    phi3v_model_config,
    image_url,
):
214
    conversation, mm_data, mm_uuids = parse_chat_messages(
215
216
217
218
219
220
221
222
223
        [
            {
                "role": "user",
                "content": [
                    {"type": "image_url", "image_url": {"url": image_url}},
                    {"type": "text", "text": "What's in the image?"},
                ],
            }
        ],
224
        phi3v_model_config,
225
226
        content_format="string",
    )
227

228
229
230
    assert conversation == [
        {"role": "user", "content": "<|image_1|>\nWhat's in the image?"}
    ]
231
    _assert_mm_data_is_image_input(mm_data, 1)
232
233
234
235
236
237
238
239
240
    _assert_mm_uuids(mm_uuids, 1, expected_uuids=[None])


def test_parse_chat_messages_single_image_with_uuid(
    phi3v_model_config,
    image_url,
):
    image_uuid = str(hash(image_url))
    conversation, mm_data, mm_uuids = parse_chat_messages(
241
242
243
244
245
246
247
248
249
250
        [
            {
                "role": "user",
                "content": [
                    {
                        "type": "image_url",
                        "image_url": {
                            "url": image_url,
                        },
                        "uuid": image_uuid,
251
                    },
252
253
254
255
                    {"type": "text", "text": "What's in the image?"},
                ],
            }
        ],
256
        phi3v_model_config,
257
258
259
        content_format="string",
    )

260
261
262
    assert conversation == [
        {"role": "user", "content": "<|image_1|>\nWhat's in the image?"}
    ]
263
264
265
266
    _assert_mm_data_is_image_input(mm_data, 1)
    _assert_mm_uuids(mm_uuids, 1, expected_uuids=[image_uuid])


267
268
269
270
271
272
def test_parse_chat_messages_single_empty_image_with_uuid(
    phi3v_model_config,
    image_url,
):
    image_uuid = str(hash(image_url))
    conversation, mm_data, mm_uuids = parse_chat_messages(
273
274
275
276
277
278
279
280
281
282
283
284
285
        [
            {
                "role": "user",
                "content": [
                    {
                        "type": "image_url",
                        "image_url": None,
                        "uuid": image_uuid,
                    },
                    {"type": "text", "text": "What's in the image?"},
                ],
            }
        ],
286
        phi3v_model_config,
287
288
289
        content_format="string",
    )

290
291
292
    assert conversation == [
        {"role": "user", "content": "<|image_1|>\nWhat's in the image?"}
    ]
293
294
295
296
    _assert_mm_data_is_image_input(mm_data, 1, skipped_image_indices=[0])
    _assert_mm_uuids(mm_uuids, 1, expected_uuids=[image_uuid])


297
298
299
300
301
302
def test_parse_chat_messages_single_image_with_bad_uuid_format(
    phi3v_model_config,
    image_url,
):
    image_uuid = str(hash(image_url))
    conversation, mm_data, mm_uuids = parse_chat_messages(
303
304
305
306
307
308
309
310
311
312
313
        [
            {
                "role": "user",
                "content": [
                    {
                        "type": "image_url",
                        "image_url": {
                            "url": image_url,
                            "uuid": image_uuid,
                        },
                        "bad_uuid_key": image_uuid,
314
                    },
315
316
317
318
                    {"type": "text", "text": "What's in the image?"},
                ],
            }
        ],
319
        phi3v_model_config,
320
321
322
        content_format="string",
    )

323
324
325
    assert conversation == [
        {"role": "user", "content": "<|image_1|>\nWhat's in the image?"}
    ]
326
327
328
329
330
331
332
333
334
335
336
337
    _assert_mm_data_is_image_input(mm_data, 1)
    _assert_mm_uuids(mm_uuids, 1, expected_uuids=[None])


def test_parse_chat_messages_multiple_images_with_uuids(
    phi3v_model_config,
    image_url,
):
    image_uuid1 = "my_uuid_1"
    image_uuid2 = "my_uuid_2"

    conversation, mm_data, mm_uuids = parse_chat_messages(
338
339
340
341
342
343
344
345
346
347
        [
            {
                "role": "user",
                "content": [
                    {
                        "type": "image_url",
                        "image_url": {
                            "url": image_url,
                        },
                        "uuid": image_uuid1,
348
                    },
349
350
351
352
353
354
                    {
                        "type": "image_url",
                        "image_url": {
                            "url": image_url,
                        },
                        "uuid": image_uuid2,
355
                    },
356
357
358
359
                    {"type": "text", "text": "What's in the image?"},
                ],
            }
        ],
360
        phi3v_model_config,
361
362
363
        content_format="string",
    )

364
365
366
367
368
369
    assert conversation == [
        {
            "role": "user",
            "content": "<|image_1|>\n<|image_2|>\nWhat's in the image?",
        }
    ]
370
371
372
373
    _assert_mm_data_is_image_input(mm_data, 2)
    _assert_mm_uuids(mm_uuids, 2, expected_uuids=[image_uuid1, image_uuid2])


374
375
376
377
378
379
380
381
def test_parse_chat_messages_multiple_empty_images_with_uuids(
    phi3v_model_config,
    image_url,
):
    image_uuid1 = "my_uuid_1"
    image_uuid2 = "my_uuid_2"

    conversation, mm_data, mm_uuids = parse_chat_messages(
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
        [
            {
                "role": "user",
                "content": [
                    {
                        "type": "image_url",
                        "image_url": None,
                        "uuid": image_uuid1,
                    },
                    {
                        "type": "image_url",
                        "image_url": None,
                        "uuid": image_uuid2,
                    },
                    {"type": "text", "text": "What's in the image?"},
                ],
            }
        ],
400
        phi3v_model_config,
401
402
403
        content_format="string",
    )

404
405
406
407
408
409
    assert conversation == [
        {
            "role": "user",
            "content": "<|image_1|>\n<|image_2|>\nWhat's in the image?",
        }
    ]
410
411
412
413
414
415
416
417
418
419
420
421
    _assert_mm_data_is_image_input(mm_data, 2, skipped_image_indices=[0, 1])
    _assert_mm_uuids(mm_uuids, 2, expected_uuids=[image_uuid1, image_uuid2])


def test_parse_chat_messages_mixed_empty_images_with_uuids(
    phi3v_model_config,
    image_url,
):
    image_uuid1 = "my_uuid_1"
    image_uuid2 = "my_uuid_2"

    conversation, mm_data, mm_uuids = parse_chat_messages(
422
423
424
425
426
427
428
429
430
431
        [
            {
                "role": "user",
                "content": [
                    {
                        "type": "image_url",
                        "image_url": {
                            "url": image_url,
                        },
                        "uuid": image_uuid1,
432
                    },
433
434
435
436
437
438
439
440
441
                    {
                        "type": "image_url",
                        "image_url": None,
                        "uuid": image_uuid2,
                    },
                    {"type": "text", "text": "What's in the image?"},
                ],
            }
        ],
442
        phi3v_model_config,
443
444
445
        content_format="string",
    )

446
447
448
449
450
451
    assert conversation == [
        {
            "role": "user",
            "content": "<|image_1|>\n<|image_2|>\nWhat's in the image?",
        }
    ]
452
453
454
455
    _assert_mm_data_is_image_input(mm_data, 2, skipped_image_indices=[1])
    _assert_mm_uuids(mm_uuids, 2, expected_uuids=[image_uuid1, image_uuid2])


456
457
458
459
460
461
@pytest.mark.asyncio
async def test_parse_chat_messages_single_image_with_uuid_async(
    phi3v_model_config,
    image_url,
):
    image_uuid = str(hash(image_url))
462
    conversation, mm_data, mm_uuids = await parse_chat_messages_async(
463
464
465
466
467
468
469
470
        [
            {
                "role": "user",
                "content": [
                    {
                        "type": "image_url",
                        "image_url": {"url": image_url},
                        "uuid": image_uuid,
471
                    },
472
473
474
475
                    {"type": "text", "text": "What's in the image?"},
                ],
            }
        ],
476
        phi3v_model_config,
477
478
479
        content_format="string",
    )

480
481
482
    assert conversation == [
        {"role": "user", "content": "<|image_1|>\nWhat's in the image?"}
    ]
483
    _assert_mm_data_is_image_input(mm_data, 1)
484
485
486
    _assert_mm_uuids(mm_uuids, 1, expected_uuids=[image_uuid])


487
488
489
490
491
492
@pytest.mark.asyncio
async def test_parse_chat_messages_empty_image_with_uuid_async(
    phi3v_model_config,
    image_url,
):
    image_uuid = str(hash(image_url))
493
    conversation, mm_data, mm_uuids = await parse_chat_messages_async(
494
495
496
497
498
499
500
501
502
503
504
505
506
        [
            {
                "role": "user",
                "content": [
                    {
                        "type": "image_url",
                        "image_url": None,
                        "uuid": image_uuid,
                    },
                    {"type": "text", "text": "What's in the image?"},
                ],
            }
        ],
507
        phi3v_model_config,
508
509
510
        content_format="string",
    )

511
512
513
    assert conversation == [
        {"role": "user", "content": "<|image_1|>\nWhat's in the image?"}
    ]
514
    _assert_mm_data_is_image_input(mm_data, 1, skipped_image_indices=[0])
515
516
517
    _assert_mm_uuids(mm_uuids, 1, expected_uuids=[image_uuid])


518
519
520
521
522
523
524
525
@pytest.mark.asyncio
async def test_parse_chat_messages_multiple_images_with_uuids_async(
    phi3v_model_config,
    image_url,
):
    image_uuid1 = "my_uuid_1"
    image_uuid2 = "my_uuid_2"

526
    conversation, mm_data, mm_uuids = await parse_chat_messages_async(
527
528
529
530
531
532
533
534
        [
            {
                "role": "user",
                "content": [
                    {
                        "type": "image_url",
                        "image_url": {"url": image_url},
                        "uuid": image_uuid1,
535
                    },
536
537
538
539
540
541
542
543
544
                    {
                        "type": "image_pil",
                        "image_pil": ImageAsset("cherry_blossom").pil_image,
                        "uuid": image_uuid2,
                    },
                    {"type": "text", "text": "What's in these images?"},
                ],
            }
        ],
545
        phi3v_model_config,
546
547
548
        content_format="string",
    )

549
550
551
552
553
554
    assert conversation == [
        {
            "role": "user",
            "content": "<|image_1|>\n<|image_2|>\nWhat's in these images?",
        }
    ]
555
    _assert_mm_data_is_image_input(mm_data, 2)
556
557
558
    _assert_mm_uuids(mm_uuids, 2, expected_uuids=[image_uuid1, image_uuid2])


559
560
561
562
563
564
565
566
@pytest.mark.asyncio
async def test_parse_chat_messages_multiple_empty_images_with_uuids_async(
    phi3v_model_config,
    image_url,
):
    image_uuid1 = "my_uuid_1"
    image_uuid2 = "my_uuid_2"

567
    conversation, mm_data, mm_uuids = await parse_chat_messages_async(
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
        [
            {
                "role": "user",
                "content": [
                    {
                        "type": "image_url",
                        "image_url": None,
                        "uuid": image_uuid1,
                    },
                    {
                        "type": "image_pil",
                        "image_pil": None,
                        "uuid": image_uuid2,
                    },
                    {"type": "text", "text": "What's in these images?"},
                ],
            }
        ],
586
        phi3v_model_config,
587
588
589
        content_format="string",
    )

590
591
592
593
594
595
    assert conversation == [
        {
            "role": "user",
            "content": "<|image_1|>\n<|image_2|>\nWhat's in these images?",
        }
    ]
596
    _assert_mm_data_is_image_input(mm_data, 2, skipped_image_indices=[0, 1])
597
598
599
    _assert_mm_uuids(mm_uuids, 2, expected_uuids=[image_uuid1, image_uuid2])


600
601
602
603
604
605
606
@pytest.mark.asyncio
async def test_parse_chat_messages_multiple_images_with_partial_uuids_async(
    phi3v_model_config,
    image_url,
):
    image_uuid2 = "my_uuid_2"

607
    conversation, mm_data, mm_uuids = await parse_chat_messages_async(
608
609
610
611
612
613
614
        [
            {
                "role": "user",
                "content": [
                    {
                        "type": "image_url",
                        "image_url": {"url": image_url},
615
                    },
616
617
618
619
620
621
622
623
624
                    {
                        "type": "image_pil",
                        "image_pil": ImageAsset("cherry_blossom").pil_image,
                        "uuid": image_uuid2,
                    },
                    {"type": "text", "text": "What's in these images?"},
                ],
            }
        ],
625
        phi3v_model_config,
626
627
628
        content_format="string",
    )

629
630
631
632
633
634
    assert conversation == [
        {
            "role": "user",
            "content": "<|image_1|>\n<|image_2|>\nWhat's in these images?",
        }
    ]
635
    _assert_mm_data_is_image_input(mm_data, 2)
636
    _assert_mm_uuids(mm_uuids, 2, expected_uuids=[None, image_uuid2])
637
638


639
640
641
642
def test_parse_chat_messages_empty_system(
    mistral_model_config,
):
    # Test string format
643
    conversation, _, _ = parse_chat_messages(
644
        [
645
            {"role": "system", "content": ""},
646
647
            {
                "role": "user",
648
                "content": [{"type": "text", "text": "Who are you?"}],
649
650
            },
        ],
651
        mistral_model_config,
652
653
        content_format="string",
    )
654
    assert conversation == [
655
656
        {"role": "system", "content": ""},
        {"role": "user", "content": "Who are you?"},
657
    ]
658
659

    # Test openai format
660
    conversation, _, _ = parse_chat_messages(
661
        [
662
            {"role": "system", "content": ""},
663
664
            {
                "role": "user",
665
                "content": [{"type": "text", "text": "Who are you?"}],
666
667
            },
        ],
668
        mistral_model_config,
669
670
671
        content_format="openai",
    )
    assert conversation == [
672
673
        {"role": "system", "content": [{"type": "text", "text": ""}]},
        {"role": "user", "content": [{"type": "text", "text": "Who are you?"}]},
674
    ]
675
676


677
@pytest.mark.asyncio
678
679
680
681
async def test_parse_chat_messages_single_image_async(
    phi3v_model_config,
    image_url,
):
682
    conversation, mm_data, mm_uuids = await parse_chat_messages_async(
683
684
685
686
687
688
689
690
691
        [
            {
                "role": "user",
                "content": [
                    {"type": "image_url", "image_url": {"url": image_url}},
                    {"type": "text", "text": "What's in the image?"},
                ],
            }
        ],
692
        phi3v_model_config,
693
694
        content_format="string",
    )
695

696
697
698
    assert conversation == [
        {"role": "user", "content": "<|image_1|>\nWhat's in the image?"}
    ]
699
    _assert_mm_data_is_image_input(mm_data, 1)
700
    _assert_mm_uuids(mm_uuids, 1, expected_uuids=[None])
701
702
703
704
705
706


def test_parse_chat_messages_multiple_images(
    phi3v_model_config,
    image_url,
):
707
    conversation, mm_data, mm_uuids = parse_chat_messages(
708
709
710
711
712
713
714
715
716
717
718
719
720
        [
            {
                "role": "user",
                "content": [
                    {"type": "image_url", "image_url": {"url": image_url}},
                    {
                        "type": "image_pil",
                        "image_pil": ImageAsset("cherry_blossom").pil_image,
                    },
                    {"type": "text", "text": "What's in these images?"},
                ],
            }
        ],
721
        phi3v_model_config,
722
723
        content_format="string",
    )
724

725
726
727
728
729
730
    assert conversation == [
        {
            "role": "user",
            "content": "<|image_1|>\n<|image_2|>\nWhat's in these images?",
        }
    ]
731
    _assert_mm_data_is_image_input(mm_data, 2)
732
    _assert_mm_uuids(mm_uuids, 2, expected_uuids=[None, None])
733
734


735
736
737
738
739
def test_parse_chat_messages_empty_pil_image_with_uuid(
    phi3v_model_config,
):
    uuid = "abcd"
    conversation, mm_data, mm_uuids = parse_chat_messages(
740
741
742
743
744
745
746
747
748
        [
            {
                "role": "user",
                "content": [
                    {"type": "image_pil", "image_pil": None, "uuid": uuid},
                    {"type": "text", "text": "What's in this image?"},
                ],
            }
        ],
749
        phi3v_model_config,
750
751
752
        content_format="string",
    )

753
754
755
756
757
758
    assert conversation == [
        {
            "role": "user",
            "content": "<|image_1|>\nWhat's in this image?",
        }
    ]
759
760
761
762
763
    _assert_mm_data_is_image_input(mm_data, 1, skipped_image_indices=[0])
    _assert_mm_uuids(mm_uuids, 1, expected_uuids=[uuid])


def test_parse_chat_messages_empty_image_embeds_with_uuid(
764
    phi3v_model_config_image_embeds,
765
766
767
):
    uuid = "abcd"
    conversation, mm_data, mm_uuids = parse_chat_messages(
768
769
770
771
772
773
774
775
776
        [
            {
                "role": "user",
                "content": [
                    {"type": "image_embeds", "image_embeds": None, "uuid": uuid},
                    {"type": "text", "text": "What's in this image?"},
                ],
            }
        ],
777
        phi3v_model_config_image_embeds,
778
779
780
        content_format="string",
    )

781
782
783
784
785
786
    assert conversation == [
        {
            "role": "user",
            "content": "<|image_1|>\nWhat's in this image?",
        }
    ]
787

788
789
    assert mm_data is not None
    assert "image" in mm_data
790
791
792
793
    assert isinstance(mm_data["image"], list)
    assert len(mm_data["image"]) == 1
    assert mm_data["image"][0] is None

794
795
796
    _assert_mm_uuids(mm_uuids, 1, expected_uuids=[uuid])


797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
def test_parse_chat_messages_empty_audio_embeds_with_uuid(
    audio_embeds_model_config,
):
    """Test audio_embeds with UUID (no actual embeds data)."""
    uuid = "test-audio-uuid-123"

    conversation, mm_data, mm_uuids = parse_chat_messages(
        [
            {
                "role": "user",
                "content": [
                    {"type": "text", "text": "Describe this audio"},
                    {"type": "audio_embeds", "audio_embeds": None, "uuid": uuid},
                ],
            }
        ],
813
        audio_embeds_model_config,
814
815
816
817
818
819
        content_format="string",
    )

    # Should have audio in mm_data as None (UUID provided)
    assert mm_data is not None
    assert "audio" in mm_data
820
821
822
823
    assert isinstance(mm_data["audio"], list)
    assert len(mm_data["audio"]) == 1
    assert mm_data["audio"][0] is None

824
825
826
827
828
829
830
831
832
833
834
835
    # UUID should be recorded
    _assert_mm_uuids(mm_uuids, 1, modality="audio", expected_uuids=[uuid])


def test_parse_chat_messages_audio_embeds_with_string(
    audio_embeds_model_config,
):
    """Test audio_embeds with base64 string embedding data."""

    import torch

    # Create a sample audio embedding tensor
836
837
    hidden_size = audio_embeds_model_config.get_inputs_embeds_size()
    audio_embedding = torch.randn(1, 128, hidden_size)
838
839

    # Encode it as base64
840
    base64_audio_embedding = tensor2base64(audio_embedding)
841
842
843
844
845
846
847
848
849
850
851
852
853
854

    conversation, mm_data, mm_uuids = parse_chat_messages(
        [
            {
                "role": "user",
                "content": [
                    {"type": "text", "text": "Describe this audio"},
                    {
                        "type": "audio_embeds",
                        "audio_embeds": base64_audio_embedding,
                    },
                ],
            }
        ],
855
        audio_embeds_model_config,
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
        content_format="string",
    )

    # Should have audio embedding in mm_data (single tensor, not a list)
    assert mm_data is not None
    assert "audio" in mm_data
    assert isinstance(mm_data["audio"], torch.Tensor)
    assert mm_data["audio"].shape == audio_embedding.shape
    # No UUID provided
    assert mm_uuids is not None
    assert "audio" in mm_uuids
    _assert_mm_uuids(mm_uuids, 1, modality="audio", expected_uuids=[None])


@pytest.mark.asyncio
async def test_parse_chat_messages_audio_embeds_async(
    audio_embeds_model_config,
):
    """Test audio_embeds with async futures."""

    import torch

    # Create a sample audio embedding tensor
879
880
    hidden_size = audio_embeds_model_config.get_inputs_embeds_size()
    audio_embedding = torch.randn(1, 128, hidden_size)
881
882

    # Encode it as base64
883
    base64_audio_embedding = tensor2base64(audio_embedding)
884

885
    conversation, mm_data, mm_uuids = await parse_chat_messages_async(
886
887
888
889
890
891
892
893
894
895
896
897
        [
            {
                "role": "user",
                "content": [
                    {"type": "text", "text": "Describe this audio"},
                    {
                        "type": "audio_embeds",
                        "audio_embeds": base64_audio_embedding,
                    },
                ],
            }
        ],
898
        audio_embeds_model_config,
899
900
901
902
903
904
905
906
907
908
909
910
911
912
        content_format="string",
    )

    # Should have audio embedding in mm_data (single tensor, not a list)
    assert mm_data is not None
    assert "audio" in mm_data
    assert isinstance(mm_data["audio"], torch.Tensor)
    assert mm_data["audio"].shape == audio_embedding.shape
    # No UUID provided
    assert mm_uuids is not None
    assert "audio" in mm_uuids
    _assert_mm_uuids(mm_uuids, 1, modality="audio", expected_uuids=[None])


913
914
915
916
917
918
919
920
921
922
def test_parse_chat_messages_multiple_image_embeds(
    phi3v_model_config_image_embeds,
):
    """Test that multiple image_embeds in a single message are now supported.

    This test validates the fix for the limitation that previously only allowed
    one message with {'type': 'image_embeds'}. Now multiple image embeddings
    can be provided in a single request, similar to regular images.
    """
    # Create two sample image embedding tensors
923
924
925
    hidden_size = phi3v_model_config_image_embeds.get_inputs_embeds_size()
    image_embedding_1 = torch.randn(256, hidden_size)
    image_embedding_2 = torch.randn(128, hidden_size)
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037

    # Encode them as base64 using the convenience function
    base64_image_embedding_1 = tensor2base64(image_embedding_1)
    base64_image_embedding_2 = tensor2base64(image_embedding_2)

    conversation, mm_data, mm_uuids = parse_chat_messages(
        [
            {
                "role": "user",
                "content": [
                    {
                        "type": "image_embeds",
                        "image_embeds": base64_image_embedding_1,
                    },
                    {
                        "type": "image_embeds",
                        "image_embeds": base64_image_embedding_2,
                    },
                    {"type": "text", "text": "Describe these two images."},
                ],
            }
        ],
        phi3v_model_config_image_embeds,
        content_format="string",
    )

    # Verify conversation structure
    assert conversation == [
        {
            "role": "user",
            "content": "<|image_1|>\n<|image_2|>\nDescribe these two images.",
        }
    ]

    # Verify mm_data contains a list of embeddings (not a single embedding)
    assert mm_data is not None
    assert "image" in mm_data
    assert isinstance(mm_data["image"], list)
    assert len(mm_data["image"]) == 2

    # Verify each embedding has the correct shape
    assert isinstance(mm_data["image"][0], torch.Tensor)
    assert mm_data["image"][0].shape == image_embedding_1.shape
    assert isinstance(mm_data["image"][1], torch.Tensor)
    assert mm_data["image"][1].shape == image_embedding_2.shape

    # Verify UUIDs (None since we didn't provide any)
    _assert_mm_uuids(mm_uuids, 2, expected_uuids=[None, None])


def test_parse_chat_messages_multiple_image_embeds_with_uuids(
    phi3v_model_config_image_embeds,
):
    """Test multiple image_embeds with UUIDs.

    This validates that UUIDs are properly tracked for multiple embeddings.
    """
    uuid1 = "image-uuid-1"
    uuid2 = "image-uuid-2"

    conversation, mm_data, mm_uuids = parse_chat_messages(
        [
            {
                "role": "user",
                "content": [
                    {
                        "type": "image_embeds",
                        "image_embeds": None,
                        "uuid": uuid1,
                    },
                    {
                        "type": "image_embeds",
                        "image_embeds": None,
                        "uuid": uuid2,
                    },
                    {"type": "text", "text": "Compare these images."},
                ],
            }
        ],
        phi3v_model_config_image_embeds,
        content_format="string",
    )

    # Verify conversation structure
    assert conversation == [
        {
            "role": "user",
            "content": "<|image_1|>\n<|image_2|>\nCompare these images.",
        }
    ]

    # Verify mm_data contains a list with None values (UUID references)
    assert mm_data is not None
    assert "image" in mm_data
    assert isinstance(mm_data["image"], list)
    assert len(mm_data["image"]) == 2
    assert mm_data["image"][0] is None
    assert mm_data["image"][1] is None

    # Verify UUIDs are correctly tracked
    _assert_mm_uuids(mm_uuids, 2, expected_uuids=[uuid1, uuid2])


@pytest.mark.asyncio
async def test_parse_chat_messages_multiple_image_embeds_async(
    phi3v_model_config_image_embeds,
):
    """Test multiple image_embeds with async parsing.

    This validates the AsyncMultiModalItemTracker also supports multiple embeddings.
    """
    # Create two sample image embedding tensors
1038
1039
1040
    hidden_size = phi3v_model_config_image_embeds.get_inputs_embeds_size()
    image_embedding_1 = torch.randn(200, hidden_size)
    image_embedding_2 = torch.randn(150, hidden_size)
1041
1042
1043
1044
1045

    # Encode them as base64 using the convenience function
    base64_image_embedding_1 = tensor2base64(image_embedding_1)
    base64_image_embedding_2 = tensor2base64(image_embedding_2)

1046
    conversation, mm_data, mm_uuids = await parse_chat_messages_async(
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
        [
            {
                "role": "user",
                "content": [
                    {
                        "type": "image_embeds",
                        "image_embeds": base64_image_embedding_1,
                    },
                    {
                        "type": "image_embeds",
                        "image_embeds": base64_image_embedding_2,
                    },
                    {"type": "text", "text": "What do these images show?"},
                ],
            }
        ],
        phi3v_model_config_image_embeds,
        content_format="string",
    )

    # Verify conversation structure
    assert conversation == [
        {
            "role": "user",
            "content": "<|image_1|>\n<|image_2|>\nWhat do these images show?",
        }
    ]

    # Await the future and verify mm_data
    assert mm_data is not None
    assert "image" in mm_data
    assert isinstance(mm_data["image"], list)
    assert len(mm_data["image"]) == 2

    # Verify each embedding has the correct shape
    assert isinstance(mm_data["image"][0], torch.Tensor)
    assert mm_data["image"][0].shape == image_embedding_1.shape
    assert isinstance(mm_data["image"][1], torch.Tensor)
    assert mm_data["image"][1].shape == image_embedding_2.shape

    # Verify UUIDs
    _assert_mm_uuids(mm_uuids, 2, expected_uuids=[None, None])


1091
1092
@pytest.mark.asyncio
async def test_parse_chat_messages_empty_image_embeds_with_uuid_async(
1093
    phi3v_model_config_image_embeds,
1094
1095
):
    uuid = "abcd"
1096
    conversation, mm_data, mm_uuids = await parse_chat_messages_async(
1097
1098
1099
1100
1101
1102
1103
1104
1105
        [
            {
                "role": "user",
                "content": [
                    {"type": "image_embeds", "image_embeds": None, "uuid": uuid},
                    {"type": "text", "text": "What's in this image?"},
                ],
            }
        ],
1106
        phi3v_model_config_image_embeds,
1107
1108
1109
        content_format="string",
    )

1110
1111
1112
1113
1114
1115
    assert conversation == [
        {
            "role": "user",
            "content": "<|image_1|>\nWhat's in this image?",
        }
    ]
1116
1117
    assert mm_data is not None
    assert "image" in mm_data
1118
1119
1120
1121
    assert isinstance(mm_data["image"], list)
    assert len(mm_data["image"]) == 1
    assert mm_data["image"][0] is None

1122
1123
1124
    _assert_mm_uuids(mm_uuids, 1, expected_uuids=[uuid])


1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
def test_parse_chat_messages_empty_dict_image_embeds(
    phi3v_model_config_image_embeds,
):
    """Test that empty dictionary for image_embeds is handled without errors."""
    conversation, mm_data, mm_uuids = parse_chat_messages(
        [
            {
                "role": "user",
                "content": [
                    {"type": "image_embeds", "image_embeds": {}},
                    {"type": "text", "text": "What's in this image?"},
                ],
            }
        ],
        phi3v_model_config_image_embeds,
        content_format="string",
    )

    # Verify conversation structure
    assert conversation == [
        {
            "role": "user",
            "content": "<|image_1|>\nWhat's in this image?",
        }
    ]

    # Verify mm_data contains an empty dictionary of embeddings
    assert mm_data is not None
    assert "image" in mm_data
    assert isinstance(mm_data["image"], dict)
    assert len(mm_data["image"]) == 0

    # Verify UUIDs (None since we didn't provide any)
    _assert_mm_uuids(mm_uuids, 1, expected_uuids=[None])


def test_parse_chat_messages_multiple_dict_image_embeds(
1162
    qwen25omni_model_config_image_embeds,
1163
1164
1165
1166
):
    """Test that multiple dictionaries for image_embeds is handled without errors."""
    # Create two sample image embedding tensors
    batch_size = 2
1167
1168
1169
    hidden_size = qwen25omni_model_config_image_embeds.get_inputs_embeds_size()
    image_embeds = torch.randn(batch_size * 220, hidden_size)
    image_grid_thw = torch.tensor([[1, 22, 40] for _ in range(batch_size)])
1170
1171
1172
1173
1174
1175
1176
1177
1178

    conversation, mm_data, mm_uuids = parse_chat_messages(
        [
            {
                "role": "user",
                "content": [
                    {
                        "type": "image_embeds",
                        "image_embeds": {
1179
1180
                            "image_embeds": tensor2base64(embeds),
                            "image_grid_thw": tensor2base64(grid_thw),
1181
1182
                        },
                    }
1183
1184
1185
                    for embeds, grid_thw in zip(
                        image_embeds.chunk(batch_size), image_grid_thw
                    )
1186
1187
1188
1189
1190
1191
                ]
                + [
                    {"type": "text", "text": "Describe these two images."},
                ],
            }
        ],
1192
        qwen25omni_model_config_image_embeds,
1193
1194
1195
1196
1197
1198
1199
        content_format="string",
    )

    # Verify conversation structure
    assert conversation == [
        {
            "role": "user",
1200
1201
            "content": "<|vision_start|><|IMAGE|><|vision_end|>\n"
            "<|vision_start|><|IMAGE|><|vision_end|>\nDescribe these two images.",
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
        }
    ]

    # Verify mm_data contains a dictionary of multi-embeddings
    assert mm_data is not None
    assert "image" in mm_data
    assert isinstance(mm_data["image"], dict)
    assert len(mm_data["image"]) == batch_size

    # Verify each embedding has the correct shape
1212
1213
1214
1215
    assert isinstance(mm_data["image"]["image_embeds"], torch.Tensor)
    assert mm_data["image"]["image_embeds"].shape == image_embeds.shape
    assert isinstance(mm_data["image"]["image_grid_thw"], torch.Tensor)
    assert mm_data["image"]["image_grid_thw"].shape == image_grid_thw.shape
1216
1217
1218
1219
1220

    # Verify UUIDs (None since we didn't provide any)
    _assert_mm_uuids(mm_uuids, batch_size, expected_uuids=[None, None])


1221
@pytest.mark.asyncio
1222
1223
1224
1225
async def test_parse_chat_messages_multiple_images_async(
    phi3v_model_config,
    image_url,
):
1226
    conversation, mm_data, mm_uuids = await parse_chat_messages_async(
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
        [
            {
                "role": "user",
                "content": [
                    {"type": "image_url", "image_url": {"url": image_url}},
                    {
                        "type": "image_pil",
                        "image_pil": ImageAsset("cherry_blossom").pil_image,
                    },
                    {"type": "text", "text": "What's in these images?"},
                ],
            }
        ],
1240
        phi3v_model_config,
1241
1242
        content_format="string",
    )
1243

1244
1245
1246
1247
1248
1249
    assert conversation == [
        {
            "role": "user",
            "content": "<|image_1|>\n<|image_2|>\nWhat's in these images?",
        }
    ]
1250
    _assert_mm_data_is_image_input(mm_data, 2)
1251
    _assert_mm_uuids(mm_uuids, 2, expected_uuids=[None, None])
1252
1253
1254
1255
1256
1257


def test_parse_chat_messages_placeholder_already_in_prompt(
    phi3v_model_config,
    image_url,
):
1258
    conversation, mm_data, mm_uuids = parse_chat_messages(
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
        [
            {
                "role": "user",
                "content": [
                    {"type": "image_url", "image_url": {"url": image_url}},
                    {"type": "image_url", "image_url": {"url": image_url}},
                    {
                        "type": "text",
                        "text": "What's in <|image_1|> and how does it compare to <|image_2|>?",  # noqa: E501
                    },
                ],
            }
        ],
1272
        phi3v_model_config,
1273
1274
        content_format="string",
    )
1275
1276
1277
1278
1279
1280
    assert conversation == [
        {
            "role": "user",
            "content": "What's in <|image_1|> and how does it compare to <|image_2|>?",
        }
    ]
1281
    _assert_mm_data_is_image_input(mm_data, 2)
1282
    _assert_mm_uuids(mm_uuids, 2, expected_uuids=[None, None])
1283
1284


1285
1286
1287
1288
def test_parse_chat_messages_placeholder_one_already_in_prompt(
    phi3v_model_config,
    image_url,
):
1289
    conversation, mm_data, mm_uuids = parse_chat_messages(
1290
1291
1292
1293
1294
1295
1296
1297
        [
            {
                "role": "user",
                "content": [
                    {"type": "image_url", "image_url": {"url": image_url}},
                    {"type": "image_url", "image_url": {"url": image_url}},
                    {
                        "type": "text",
1298
1299
                        "text": "What's in <|image_1|> and how does it compare to "
                        "the other one?",
1300
1301
1302
1303
                    },
                ],
            }
        ],
1304
        phi3v_model_config,
1305
1306
        content_format="string",
    )
1307

1308
1309
1310
    assert conversation == [
        {
            "role": "user",
1311
1312
            "content": "<|image_2|>\nWhat's in <|image_1|> and how does it compare to "
            "the other one?",
1313
1314
        }
    ]
1315
    _assert_mm_data_is_image_input(mm_data, 2)
1316
    _assert_mm_uuids(mm_uuids, 2, expected_uuids=[None, None])
1317
1318


1319
1320
1321
1322
def test_parse_chat_messages_multiple_images_across_messages(
    phi3v_model_config,
    image_url,
):
1323
    conversation, mm_data, mm_uuids = parse_chat_messages(
1324
1325
        [
            {
1326
                "role": "user",
1327
                "content": [
1328
1329
                    {"type": "image_url", "image_url": {"url": image_url}},
                    {"type": "text", "text": "What's in this image?"},
1330
1331
                ],
            },
1332
            {"role": "assistant", "content": "Some stuff."},
1333
            {
1334
                "role": "user",
1335
                "content": [
1336
1337
                    {"type": "image_url", "image_url": {"url": image_url}},
                    {"type": "text", "text": "What about this one?"},
1338
1339
1340
                ],
            },
        ],
1341
        phi3v_model_config,
1342
1343
        content_format="string",
    )
1344
1345

    assert conversation == [
1346
1347
1348
        {"role": "user", "content": "<|image_1|>\nWhat's in this image?"},
        {"role": "assistant", "content": "Some stuff."},
        {"role": "user", "content": "<|image_2|>\nWhat about this one?"},
1349
    ]
1350
    _assert_mm_data_is_image_input(mm_data, 2)
1351
    _assert_mm_uuids(mm_uuids, 2, expected_uuids=[None, None])
1352
1353


1354
def test_parse_chat_messages_multiple_images_with_uuids_across_messages(
1355
    phi3v_model_config,
1356
    image_url,
1357
):
1358
1359
    image_uuid = str(hash(image_url))
    conversation, mm_data, mm_uuids = parse_chat_messages(
1360
1361
        [
            {
1362
                "role": "user",
1363
1364
1365
                "content": [
                    {
                        "type": "image_url",
1366
                        "image_url": {"url": image_url},
1367
1368
                        "uuid": image_uuid,
                    },
1369
                    {"type": "text", "text": "What's in this image?"},
1370
                ],
1371
            },
1372
            {"role": "assistant", "content": "Some stuff."},
1373
            {
1374
                "role": "user",
1375
1376
1377
                "content": [
                    {
                        "type": "image_url",
1378
                        "image_url": {"url": image_url},
1379
1380
                        "uuid": image_uuid,
                    },
1381
                    {"type": "text", "text": "What about this one?"},
1382
1383
1384
                ],
            },
        ],
1385
        phi3v_model_config,
1386
1387
1388
1389
        content_format="string",
    )

    assert conversation == [
1390
1391
1392
        {"role": "user", "content": "<|image_1|>\nWhat's in this image?"},
        {"role": "assistant", "content": "Some stuff."},
        {"role": "user", "content": "<|image_2|>\nWhat about this one?"},
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
    ]
    _assert_mm_data_is_image_input(mm_data, 2)
    _assert_mm_uuids(mm_uuids, 2, expected_uuids=[image_uuid, image_uuid])


def test_parse_chat_messages_context_text_format(
    phi3v_model_config,
):
    conversation, mm_data, mm_uuids = parse_chat_messages(
        [
            {
                "role": "user",
1405
                "content": [{"type": "text", "text": "What's in this text?"}],
1406
            },
1407
1408
            {"role": "assistant", "content": "Some stuff."},
            {"role": "user", "content": "What about this one?"},
1409
        ],
1410
        phi3v_model_config,
1411
1412
        content_format="openai",
    )
1413
1414
1415
1416

    assert conversation == [
        {
            "role": "user",
1417
            "content": [{"type": "text", "text": "What's in this text?"}],
1418
1419
1420
        },
        {
            "role": "assistant",
1421
            "content": [{"type": "text", "text": "Some stuff."}],
1422
1423
1424
        },
        {
            "role": "user",
1425
            "content": [{"type": "text", "text": "What about this one?"}],
1426
1427
        },
    ]
1428
1429
    assert mm_data is None
    assert mm_uuids is None
1430
1431


1432
1433
1434
1435
def test_parse_chat_messages_rejects_too_many_images_in_one_message(
    phi3v_model_config,
    image_url,
):
1436
1437
1438
    with warnings.catch_warnings():
        warnings.filterwarnings(
            "ignore",
1439
1440
            message="coroutine 'async_get_and_parse_image' was never awaited",
        )
1441
        with pytest.raises(ValueError, match="At most"):
1442
            parse_chat_messages(
1443
1444
1445
1446
1447
1448
1449
                [
                    {
                        "role": "user",
                        "content": [
                            {
                                "type": "image_url",
                                "image_url": {"url": image_url},
1450
                            },
1451
1452
1453
                            {
                                "type": "image_url",
                                "image_url": {"url": image_url},
1454
                            },
1455
1456
1457
                            {
                                "type": "image_url",
                                "image_url": {"url": image_url},
1458
                            },
1459
1460
1461
1462
                            {"type": "text", "text": "What's in these images?"},
                        ],
                    }
                ],
1463
                phi3v_model_config,
1464
1465
                content_format="string",
            )
1466
1467


1468
1469
1470
1471
def test_parse_chat_messages_rejects_too_many_images_across_messages(
    phi3v_model_config,
    image_url,
):
1472
1473
1474
    with warnings.catch_warnings():
        warnings.filterwarnings(
            "ignore",
1475
1476
            message="coroutine 'async_get_and_parse_image' was never awaited",
        )
1477
        with pytest.raises(ValueError, match="At most"):
1478
            parse_chat_messages(
1479
1480
                [
                    {
1481
                        "role": "user",
1482
1483
1484
                        "content": [
                            {
                                "type": "image_url",
1485
                                "image_url": {"url": image_url},
1486
                            },
1487
                            {"type": "text", "text": "What's in this image?"},
1488
1489
                        ],
                    },
1490
                    {"role": "assistant", "content": "Some stuff."},
1491
                    {
1492
                        "role": "user",
1493
1494
1495
                        "content": [
                            {
                                "type": "image_url",
1496
                                "image_url": {"url": image_url},
1497
1498
1499
                            },
                            {
                                "type": "image_url",
1500
                                "image_url": {"url": image_url},
1501
                            },
1502
                            {"type": "text", "text": "What about these two?"},
1503
1504
1505
                        ],
                    },
                ],
1506
                phi3v_model_config,
1507
1508
                content_format="string",
            )
1509
1510
1511
1512
1513
1514


def test_parse_chat_messages_multiple_images_uncommon_input(
    phi3v_model_config,
    image_url,
):
1515
    conversation, mm_data, mm_uuids = parse_chat_messages(
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
        [
            {
                "role": "user",
                "content": [
                    "What's in these images?",
                    {"image_url": image_url},
                    {"image_url": image_url},
                ],
            }
        ],
1526
        phi3v_model_config,
1527
1528
        content_format="string",
    )
1529

1530
1531
1532
1533
1534
1535
    assert conversation == [
        {
            "role": "user",
            "content": "<|image_1|>\n<|image_2|>\nWhat's in these images?",
        }
    ]
1536
    _assert_mm_data_is_image_input(mm_data, 2)
1537
    _assert_mm_uuids(mm_uuids, 2, expected_uuids=[None, None])
1538
1539


1540
1541
1542
1543
def test_parse_chat_messages_multiple_images_interleave(
    phi3v_model_config_mm_interleaved,
    image_url,
):
1544
    conversation, mm_data, mm_uuids = parse_chat_messages(
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
        [
            {
                "role": "user",
                "content": [
                    {
                        "type": "text",
                        "text": "I need you to compare this image",
                    },
                    {"type": "image_url", "image_url": {"url": image_url}},
                    {"type": "text", "text": "and this one"},
                    {"type": "image_url", "image_url": {"url": image_url}},
                    {"type": "text", "text": "Do they have differences?"},
                ],
            }
        ],
1560
        phi3v_model_config_mm_interleaved,
1561
1562
1563
        content_format="string",
    )

1564
1565
1566
1567
1568
1569
1570
    assert conversation == [
        {
            "role": "user",
            "content": "I need you to compare this image\n<|image_1|>\nand this one\n<|image_2|>\n"  # noqa: E501
            "Do they have differences?",
        }
    ]
1571
    _assert_mm_data_is_image_input(mm_data, 2)
1572
    _assert_mm_uuids(mm_uuids, 2, expected_uuids=[None, None])
1573
1574
1575
1576
1577
1578
1579


@pytest.mark.asyncio
async def test_parse_chat_messages_multiple_images_interleave_async(
    phi3v_model_config_mm_interleaved,
    image_url,
):
1580
    conversation, mm_data, mm_uuids = await parse_chat_messages_async(
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
        [
            {
                "role": "user",
                "content": [
                    {
                        "type": "text",
                        "text": "I need you to compare this image",
                    },
                    {"type": "image_url", "image_url": {"url": image_url}},
                    {"type": "text", "text": "and this one"},
                    {"type": "image_url", "image_url": {"url": image_url}},
                    {"type": "text", "text": "Do they have differences?"},
                ],
            }
        ],
1596
        phi3v_model_config_mm_interleaved,
1597
1598
1599
        content_format="string",
    )

1600
1601
1602
1603
1604
1605
1606
    assert conversation == [
        {
            "role": "user",
            "content": "I need you to compare this image\n<|image_1|>\nand this one\n<|image_2|>\n"  # noqa: E501
            "Do they have differences?",
        }
    ]
1607
    _assert_mm_data_is_image_input(mm_data, 2)
1608
1609
1610
1611
1612
1613
1614
1615
1616
    _assert_mm_uuids(mm_uuids, 2, expected_uuids=[None, None])


@pytest.mark.asyncio
async def test_parse_chat_messages_multiple_images_with_uuids_interleave_async(
    phi3v_model_config_mm_interleaved,
    image_url,
):
    image_uuid = str(hash(image_url))
1617
    conversation, mm_data, mm_uuids = await parse_chat_messages_async(
1618
1619
1620
1621
1622
1623
1624
        [
            {
                "role": "user",
                "content": [
                    {
                        "type": "text",
                        "text": "I need you to compare this image",
1625
                    },
1626
1627
1628
1629
                    {
                        "type": "image_url",
                        "image_url": {"url": image_url},
                        "uuid": image_uuid,
1630
                    },
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
                    {"type": "text", "text": "and this one"},
                    {
                        "type": "image_url",
                        "image_url": {"url": image_url},
                        "uuid": image_uuid,
                    },
                    {"type": "text", "text": "Do they have differences?"},
                ],
            }
        ],
1641
        phi3v_model_config_mm_interleaved,
1642
1643
1644
        content_format="string",
    )

1645
1646
1647
1648
1649
1650
1651
    assert conversation == [
        {
            "role": "user",
            "content": "I need you to compare this image\n<|image_1|>\nand this one\n<|image_2|>\n"  # noqa: E501
            "Do they have differences?",
        }
    ]
1652
    _assert_mm_data_is_image_input(mm_data, 2)
1653
    _assert_mm_uuids(mm_uuids, 2, expected_uuids=[image_uuid, image_uuid])
1654
1655
1656
1657
1658
1659


def test_parse_chat_messages_multiple_images_multiple_messages_interleave(
    phi3v_model_config_mm_interleaved,
    image_url,
):
1660
    conversation, mm_data, mm_uuids = parse_chat_messages(
1661
1662
        [
            {
1663
                "role": "user",
1664
                "content": [
1665
1666
1667
                    {"type": "text", "text": "What's on this image?"},
                    {"type": "image_url", "image_url": {"url": image_url}},
                    {"type": "text", "text": "Be accurate."},
1668
1669
                ],
            },
1670
            {"role": "assistant", "content": "Some stuff."},
1671
            {
1672
                "role": "user",
1673
                "content": [
1674
1675
                    {"type": "text", "text": "What's on this image?"},
                    {"type": "image_url", "image_url": {"url": image_url}},
1676
1677
1678
                ],
            },
        ],
1679
        phi3v_model_config_mm_interleaved,
1680
1681
1682
        content_format="string",
    )

1683
1684
1685
1686
1687
    assert conversation == [
        {
            "role": "user",
            "content": "What's on this image?\n<|image_1|>\nBe accurate.",
        },
1688
1689
        {"role": "assistant", "content": "Some stuff."},
        {"role": "user", "content": "What's on this image?\n<|image_2|>"},
1690
    ]
1691
    _assert_mm_data_is_image_input(mm_data, 2)
1692
1693
1694
    _assert_mm_uuids(mm_uuids, 2, expected_uuids=[None, None])


1695
def test_parse_chat_messages_multiple_images_with_uuids_multiple_messages_interleave(
1696
1697
1698
1699
1700
1701
1702
    phi3v_model_config_mm_interleaved,
    image_url,
):
    image_uuid = str(hash(image_url))
    conversation, mm_data, mm_uuids = parse_chat_messages(
        [
            {
1703
                "role": "user",
1704
                "content": [
1705
                    {"type": "text", "text": "What's on this image?"},
1706
1707
                    {
                        "type": "image_url",
1708
                        "image_url": {"url": image_url},
1709
1710
                        "uuid": image_uuid,
                    },
1711
                    {"type": "text", "text": "Be accurate."},
1712
1713
                ],
            },
1714
            {"role": "assistant", "content": "Some stuff."},
1715
            {
1716
                "role": "user",
1717
                "content": [
1718
                    {"type": "text", "text": "What's on this image?"},
1719
1720
                    {
                        "type": "image_url",
1721
                        "image_url": {"url": image_url},
1722
1723
1724
1725
1726
                        "uuid": image_uuid,
                    },
                ],
            },
        ],
1727
        phi3v_model_config_mm_interleaved,
1728
1729
1730
1731
1732
1733
1734
1735
        content_format="string",
    )

    assert conversation == [
        {
            "role": "user",
            "content": "What's on this image?\n<|image_1|>\nBe accurate.",
        },
1736
1737
        {"role": "assistant", "content": "Some stuff."},
        {"role": "user", "content": "What's on this image?\n<|image_2|>"},
1738
1739
1740
    ]
    _assert_mm_data_is_image_input(mm_data, 2)
    _assert_mm_uuids(mm_uuids, 2, expected_uuids=[image_uuid, image_uuid])
1741
1742
1743


def test_parse_chat_messages_multiple_modals_multiple_messages_interleave(
1744
1745
1746
1747
1748
    qwen25omni_model_config_mm_interleaved,
    image_url,
    video_url,
    audio_url,
):
1749
    conversation, mm_data, mm_uuids = parse_chat_messages(
1750
1751
        [
            {
1752
                "role": "user",
1753
                "content": [
1754
1755
1756
1757
                    {"type": "text", "text": "What's on this image?"},
                    {"type": "image_url", "image_url": {"url": image_url}},
                    {"type": "text", "text": "Now listen to this audio"},
                    {"type": "audio_url", "audio_url": {"url": audio_url}},
1758
1759
                ],
            },
1760
            {"role": "assistant", "content": "Some stuff."},
1761
            {
1762
                "role": "user",
1763
                "content": [
1764
1765
1766
1767
                    {"type": "text", "text": "What's on this image?"},
                    {"type": "image_url", "image_url": {"url": image_url}},
                    {"type": "text", "text": "And what's in the video?"},
                    {"type": "video_url", "video_url": {"url": video_url}},
1768
1769
1770
                ],
            },
        ],
1771
        qwen25omni_model_config_mm_interleaved,
1772
1773
1774
1775
1776
        content_format="string",
    )

    assert conversation == [
        {
1777
            "role": "user",
1778
1779
            "content": "What's on this image?\n<|vision_start|><|IMAGE|><|vision_end|>"
            "\nNow listen to this audio\nAudio 1: <|audio_bos|><|AUDIO|><|audio_eos|>",
1780
        },
1781
        {"role": "assistant", "content": "Some stuff."},
1782
        {
1783
            "role": "user",
1784
1785
            "content": "What's on this image?\n<|vision_start|><|IMAGE|><|vision_end|>"
            "\nAnd what's in the video?\n<|vision_start|><|VIDEO|><|vision_end|>",
1786
1787
        },
    ]
1788
1789

    _assert_mm_data_inputs(mm_data, {"image": 2, "video": 1, "audio": 1})
1790
    _assert_mm_uuids(mm_uuids, 2, modality="image", expected_uuids=[None, None])
1791
1792
1793
1794
    _assert_mm_uuids(mm_uuids, 1, modality="video", expected_uuids=[None])
    _assert_mm_uuids(mm_uuids, 1, modality="audio", expected_uuids=[None])


1795
def test_parse_chat_messages_multiple_modals_with_uuids_multiple_messages_interleave(
1796
1797
1798
1799
1800
1801
1802
1803
    qwen25omni_model_config_mm_interleaved,
    image_url,
    video_url,
    audio_url,
):
    conversation, mm_data, mm_uuids = parse_chat_messages(
        [
            {
1804
                "role": "user",
1805
                "content": [
1806
                    {"type": "text", "text": "What's on this image?"},
1807
1808
                    {
                        "type": "image_url",
1809
                        "image_url": {"url": image_url},
1810
1811
                        "uuid": "image_123",
                    },
1812
                    {"type": "text", "text": "Now listen to this audio"},
1813
1814
                    {
                        "type": "audio_url",
1815
                        "audio_url": {"url": audio_url},
1816
1817
1818
1819
                        "uuid": "audio_123",
                    },
                ],
            },
1820
            {"role": "assistant", "content": "Some stuff."},
1821
            {
1822
                "role": "user",
1823
                "content": [
1824
                    {"type": "text", "text": "What's on this image?"},
1825
1826
                    {
                        "type": "image_url",
1827
                        "image_url": {"url": image_url},
1828
1829
                        "uuid": "image_123",
                    },
1830
                    {"type": "text", "text": "And what's in the video?"},
1831
1832
                    {
                        "type": "video_url",
1833
                        "video_url": {"url": video_url},
1834
1835
1836
1837
1838
                        "uuid": "video_123",
                    },
                ],
            },
        ],
1839
        qwen25omni_model_config_mm_interleaved,
1840
1841
1842
1843
1844
        content_format="string",
    )

    assert conversation == [
        {
1845
            "role": "user",
1846
1847
            "content": "What's on this image?\n<|vision_start|><|IMAGE|><|vision_end|>"
            "\nNow listen to this audio\nAudio 1: <|audio_bos|><|AUDIO|><|audio_eos|>",
1848
        },
1849
        {"role": "assistant", "content": "Some stuff."},
1850
        {
1851
            "role": "user",
1852
1853
            "content": "What's on this image?\n<|vision_start|><|IMAGE|><|vision_end|>"
            "\nAnd what's in the video?\n<|vision_start|><|VIDEO|><|vision_end|>",
1854
1855
1856
1857
        },
    ]

    _assert_mm_data_inputs(mm_data, {"image": 2, "video": 1, "audio": 1})
1858
1859
1860
1861
1862
    _assert_mm_uuids(
        mm_uuids, 2, modality="image", expected_uuids=["image_123", "image_123"]
    )
    _assert_mm_uuids(mm_uuids, 1, modality="video", expected_uuids=["video_123"])
    _assert_mm_uuids(mm_uuids, 1, modality="audio", expected_uuids=["audio_123"])
1863
1864


1865
1866
1867
1868
1869
1870
1871
1872
1873
def test_parse_chat_messages_multiple_modals_with_uuids_multiple_empty_media_messages_interleave(  # noqa: E501
    qwen25omni_model_config_mm_interleaved,
    image_url,
    video_url,
    audio_url,
):
    conversation, mm_data, mm_uuids = parse_chat_messages(
        [
            {
1874
                "role": "user",
1875
                "content": [
1876
                    {"type": "text", "text": "What's on this image?"},
1877
1878
1879
1880
1881
                    {
                        "type": "image_url",
                        "image_url": None,
                        "uuid": "image_123",
                    },
1882
                    {"type": "text", "text": "Now listen to this audio"},
1883
1884
1885
1886
1887
1888
1889
                    {
                        "type": "audio_url",
                        "audio_url": None,
                        "uuid": "audio_123",
                    },
                ],
            },
1890
            {"role": "assistant", "content": "Some stuff."},
1891
            {
1892
                "role": "user",
1893
                "content": [
1894
                    {"type": "text", "text": "What's on this image?"},
1895
1896
1897
1898
1899
                    {
                        "type": "image_url",
                        "image_url": None,
                        "uuid": "image_123",
                    },
1900
                    {"type": "text", "text": "And what's in the video?"},
1901
1902
1903
1904
1905
1906
1907
1908
                    {
                        "type": "video_url",
                        "video_url": None,
                        "uuid": "video_123",
                    },
                ],
            },
        ],
1909
        qwen25omni_model_config_mm_interleaved,
1910
1911
1912
1913
1914
        content_format="string",
    )

    assert conversation == [
        {
1915
            "role": "user",
1916
1917
            "content": "What's on this image?\n<|vision_start|><|IMAGE|><|vision_end|>"
            "\nNow listen to this audio\nAudio 1: <|audio_bos|><|AUDIO|><|audio_eos|>",
1918
        },
1919
        {"role": "assistant", "content": "Some stuff."},
1920
        {
1921
            "role": "user",
1922
1923
            "content": "What's on this image?\n<|vision_start|><|IMAGE|><|vision_end|>"
            "\nAnd what's in the video?\n<|vision_start|><|VIDEO|><|vision_end|>",
1924
1925
1926
        },
    ]

1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
    _assert_mm_data_inputs(
        mm_data,
        {"image": 2, "video": 1, "audio": 1},
        skipped_media_indices={"image": [0, 1], "video": [0], "audio": [0]},
    )
    _assert_mm_uuids(
        mm_uuids, 2, modality="image", expected_uuids=["image_123", "image_123"]
    )
    _assert_mm_uuids(mm_uuids, 1, modality="video", expected_uuids=["video_123"])
    _assert_mm_uuids(mm_uuids, 1, modality="audio", expected_uuids=["audio_123"])
1937
1938


1939
1940
1941
1942
1943
1944
1945
1946
1947
def test_parse_chat_messages_multiple_modals_with_partial_uuids_multiple_messages_interleave(  # noqa: E501
    qwen25omni_model_config_mm_interleaved,
    image_url,
    video_url,
    audio_url,
):
    conversation, mm_data, mm_uuids = parse_chat_messages(
        [
            {
1948
                "role": "user",
1949
                "content": [
1950
                    {"type": "text", "text": "What's on this image?"},
1951
1952
                    {
                        "type": "image_url",
1953
                        "image_url": {"url": image_url},
1954
1955
                        "uuid": "image_123",
                    },
1956
1957
                    {"type": "text", "text": "Now listen to this audio"},
                    {"type": "audio_url", "audio_url": {"url": audio_url}},
1958
1959
                ],
            },
1960
            {"role": "assistant", "content": "Some stuff."},
1961
            {
1962
                "role": "user",
1963
                "content": [
1964
1965
1966
                    {"type": "text", "text": "What's on this image?"},
                    {"type": "image_url", "image_url": {"url": image_url}},
                    {"type": "text", "text": "And what's in the video?"},
1967
1968
                    {
                        "type": "video_url",
1969
                        "video_url": {"url": video_url},
1970
1971
1972
1973
1974
                        "uuid": "video_123",
                    },
                ],
            },
        ],
1975
        qwen25omni_model_config_mm_interleaved,
1976
1977
1978
1979
1980
        content_format="string",
    )

    assert conversation == [
        {
1981
            "role": "user",
1982
1983
            "content": "What's on this image?\n<|vision_start|><|IMAGE|><|vision_end|>"
            "\nNow listen to this audio\nAudio 1: <|audio_bos|><|AUDIO|><|audio_eos|>",
1984
        },
1985
        {"role": "assistant", "content": "Some stuff."},
1986
        {
1987
            "role": "user",
1988
1989
            "content": "What's on this image?\n<|vision_start|><|IMAGE|><|vision_end|>"
            "\nAnd what's in the video?\n<|vision_start|><|VIDEO|><|vision_end|>",
1990
1991
1992
1993
        },
    ]

    _assert_mm_data_inputs(mm_data, {"image": 2, "video": 1, "audio": 1})
1994
1995
    _assert_mm_uuids(mm_uuids, 2, modality="image", expected_uuids=["image_123", None])
    _assert_mm_uuids(mm_uuids, 1, modality="video", expected_uuids=["video_123"])
1996
    _assert_mm_uuids(mm_uuids, 1, modality="audio", expected_uuids=[None])
1997
1998
1999
2000
2001
2002
2003


def test_parse_chat_messages_multiple_images_interleave_with_placeholders(
    phi3v_model_config_mm_interleaved,
    image_url,
):
    with pytest.raises(
2004
2005
2006
        ValueError,
        match=r"Found more '<|image_1|>' placeholders in input prompt "
        "than actual multimodal data items.",
2007
    ):
2008
        parse_chat_messages(
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
            [
                {
                    "role": "user",
                    "content": [
                        {"type": "image_url", "image_url": {"url": image_url}},
                        {"type": "image_url", "image_url": {"url": image_url}},
                        {
                            "type": "text",
                            "text": "I need you to compare this image\n<|image_1|>\nand this one\n<|image_2|>\n"  # noqa: E501
                            "Do they have differences?",
                        },
                    ],
                }
            ],
2023
            phi3v_model_config_mm_interleaved,
2024
2025
2026
2027
            content_format="string",
        )


2028
def test_parse_chat_messages_include_thinking_chunk(mistral_model_config):
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
    messages = [
        {
            "role": "system",
            "content": [
                {"type": "text", "text": "You are a helpful assistant."},
                {
                    "type": "thinking",
                    "closed": True,
                    "thinking": "Only return the answer when you are confident.",
                },
            ],
        },
        {"role": "user", "content": "What is 2+2?"},
        {
            "role": "assistant",
            "content": [
                {"type": "text", "text": "Let me think about it."},
                {"type": "thinking", "closed": True, "thinking": "2+2 = 4"},
                {
                    "type": "text",
                    "text": "The answer is 4.",
                },
            ],
        },
    ]
Julien Denize's avatar
Julien Denize committed
2054

2055
    conversation_with_thinking, _, _ = parse_chat_messages(
Julien Denize's avatar
Julien Denize committed
2056
        messages,
2057
        mistral_model_config,
Julien Denize's avatar
Julien Denize committed
2058
2059
2060
        content_format="openai",
    )

2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
    expected_conversation = [
        {
            "role": "system",
            "content": [
                {"type": "text", "text": "You are a helpful assistant."},
                {
                    "type": "text",
                    "text": "Only return the answer when you are confident.",
                },
            ],
        },
        {
            "role": "user",
            "content": [{"type": "text", "text": "What is 2+2?"}],
        },
        {
            "role": "assistant",
            "content": [
                {"type": "text", "text": "Let me think about it."},
                {"type": "text", "text": "2+2 = 4"},
                {"type": "text", "text": "The answer is 4."},
            ],
        },
    ]
Julien Denize's avatar
Julien Denize committed
2085
2086
2087
2088

    assert conversation_with_thinking == expected_conversation


2089
2090
2091
2092
2093
def test_parse_chat_messages_single_empty_audio_with_uuid(
    qwen2_audio_model_config,
):
    audio_uuid = "abcd"
    conversation, mm_data, mm_uuids = parse_chat_messages(
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
        [
            {
                "role": "user",
                "content": [
                    {
                        "type": "input_audio",
                        "input_audio": {},
                        "uuid": audio_uuid,
                    },
                    {"type": "text", "text": "What does the audio say?"},
                ],
            }
        ],
2107
        qwen2_audio_model_config,
2108
2109
2110
        content_format="string",
    )

2111
2112
2113
    assert conversation == [
        {
            "role": "user",
2114
2115
            "content": "Audio 1: <|audio_bos|><|AUDIO|><|audio_eos|>\nWhat does the "
            "audio say?",
2116
2117
        }
    ]
2118
    _assert_mm_data_inputs(mm_data, {"audio": 1})
2119
    _assert_mm_uuids(mm_uuids, 1, modality="audio", expected_uuids=[audio_uuid])
2120
2121
2122
2123
2124
2125
2126


@pytest.mark.asyncio
async def test_parse_chat_messages_single_empty_audio_with_uuid_async(
    qwen2_audio_model_config,
):
    audio_uuid = "abcd"
2127
    conversation, mm_data, mm_uuids = await parse_chat_messages_async(
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
        [
            {
                "role": "user",
                "content": [
                    {
                        "type": "input_audio",
                        "input_audio": {},
                        "uuid": audio_uuid,
                    },
                    {"type": "text", "text": "What does the audio say?"},
                ],
            }
        ],
2141
        qwen2_audio_model_config,
2142
2143
2144
        content_format="string",
    )

2145
2146
2147
    assert conversation == [
        {
            "role": "user",
2148
2149
            "content": "Audio 1: <|audio_bos|><|AUDIO|><|audio_eos|>\nWhat does the "
            "audio say?",
2150
2151
        }
    ]
2152
    _assert_mm_data_inputs(mm_data, {"audio": 1})
2153
    _assert_mm_uuids(mm_uuids, 1, modality="audio", expected_uuids=[audio_uuid])