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

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

import pytest
9
import os
10

Julien Denize's avatar
Julien Denize committed
11
12
13
14
from mistral_common.tokens.tokenizers.base import (SpecialTokenPolicy,
                                                   SpecialTokens)
from mistral_common.tokens.tokenizers.tekken import (SpecialTokenInfo,
                                                     Tekkenizer)
15

16
from vllm.assets.audio import AudioAsset
17
from vllm.assets.image import ImageAsset
18
from vllm.assets.video import VideoAsset
19
from vllm.config import ModelConfig
20
from vllm.entrypoints.chat_utils import (_try_extract_ast, load_chat_template,
21
22
                                         parse_chat_messages,
                                         parse_chat_messages_futures,
23
                                         resolve_chat_template_content_format,
24
                                         resolve_chat_template_kwargs,
25
                                         resolve_hf_chat_template)
26
from vllm.multimodal import MultiModalDataDict, MultiModalUUIDDict
27
28
from vllm.multimodal.utils import (encode_audio_base64, encode_image_base64,
                                   encode_video_base64)
29

30
from vllm.transformers_utils.tokenizer import get_tokenizer
Julien Denize's avatar
Julien Denize committed
31
from vllm.transformers_utils.tokenizers.mistral import MistralTokenizer
32

33
from ..models.registry import HF_EXAMPLE_MODELS
34
from ..utils import VLLM_PATH, models_path_prefix
35
36
37

EXAMPLES_DIR = VLLM_PATH / "examples"

38
PHI3V_MODEL_ID = os.path.join(models_path_prefix, "microsoft/Phi-3.5-vision-instruct")
zhuwenwen's avatar
zhuwenwen committed
39
ULTRAVOX_MODEL_ID = os.path.join(models_path_prefix, "fixie-ai/ultravox-v0_5-llama-3_2-1b")
zhuwenwen's avatar
zhuwenwen committed
40
QWEN2AUDIO_MODEL_ID = os.path.join(models_path_prefix, "Qwen/Qwen2-Audio-7B-Instruct")
zhuwenwen's avatar
zhuwenwen committed
41
QWEN2VL_MODEL_ID = os.path.join(models_path_prefix, "Qwen/Qwen2-VL-2B-Instruct")
zhuwenwen's avatar
zhuwenwen committed
42
QWEN25VL_MODEL_ID = os.path.join(models_path_prefix, "Qwen/Qwen2.5-VL-3B-Instruct")
43
QWEN25OMNI_MODEL_ID = os.path.join(models_path_prefix, "Qwen/Qwen2.5-Omni-7B")
44
QWEN3_MODEL_ID = os.path.join(models_path_prefix, "Qwen/Qwen3-8B")
zhuwenwen's avatar
zhuwenwen committed
45
LLAMA_GUARD_MODEL_ID = os.path.join(models_path_prefix, "meta-llama/Llama-Guard-3-1B")
zhuwenwen's avatar
zhuwenwen committed
46
HERMES_MODEL_ID = os.path.join(models_path_prefix, "NousResearch/Hermes-3-Llama-3.1-8B")
zhuwenwen's avatar
zhuwenwen committed
47
MISTRAL_MODEL_ID = os.path.join(models_path_prefix, "mistralai/Mistral-Small-3.1-24B-Instruct-2503")
48
49


50
@pytest.fixture(scope="function")
51
def phi3v_model_config():
52
53
54
55
56
57
58
59
    return ModelConfig(
        PHI3V_MODEL_ID,
        runner="generate",
        trust_remote_code=True,
        limit_mm_per_prompt={
            "image": 2,
        },
    )
60
61


62
63
@pytest.fixture(scope="function")
def phi3v_model_config_mm_interleaved():
64
65
66
67
68
69
70
71
72
    return ModelConfig(
        PHI3V_MODEL_ID,
        runner="generate",
        trust_remote_code=True,
        interleave_mm_strings=True,
        limit_mm_per_prompt={
            "image": 2,
        },
    )
73
74


75
76
77
78
79
80
81
82
83
84
85
86
87
@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,
    )
    
    
88
89
@pytest.fixture(scope="module")
def phi3v_tokenizer():
90
    return get_tokenizer(PHI3V_MODEL_ID)
91
92


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


@pytest.fixture(scope="module")
106
def qwen2_audio_tokenizer():
107
    return get_tokenizer(QWEN2AUDIO_MODEL_ID)
108
109
110
111


@pytest.fixture(scope="function")
def qwen25omni_model_config_mm_interleaved():
112
113
114
115
116
117
118
119
120
121
    return ModelConfig(
        QWEN25OMNI_MODEL_ID,
        runner="generate",
        interleave_mm_strings=True,
        limit_mm_per_prompt={
            "image": 2,
            "audio": 1,
            "video": 1,
        },
    )
122
123
124


@pytest.fixture(scope="module")
125
def qwen25omni_tokenizer():
126
    return get_tokenizer(QWEN25OMNI_MODEL_ID)
127
128


129
130
@pytest.fixture(scope="function")
def mistral_model_config():
131
132
133
134
135
136
137
    return ModelConfig(
        MISTRAL_MODEL_ID,
        runner="generate",
        limit_mm_per_prompt={
            "image": 2,
        },
    )
138
139
140
141


@pytest.fixture(scope="module")
def mistral_tokenizer():
142
    return get_tokenizer(MISTRAL_MODEL_ID)
143
144


145
146
@pytest.fixture(scope="module")
def image_url():
147
    image = ImageAsset("cherry_blossom")
148
149
150
151
    base64 = encode_image_base64(image.pil_image)
    return f"data:image/jpeg;base64,{base64}"


152
153
@pytest.fixture(scope="module")
def video_url():
154
    video = VideoAsset("baby_reading", 1)
155
156
157
158
159
160
    base64 = encode_video_base64(video.np_ndarrays)
    return f"data:video/jpeg;base64,{base64}"


@pytest.fixture(scope="module")
def audio_url():
161
    audio = AudioAsset("mary_had_lamb")
162
163
164
165
    base64 = encode_audio_base64(*audio.audio_and_sample_rate)
    return f"data:audio/ogg;base64,{base64}"


166
167
168
def _assert_mm_data_is_image_input(
    mm_data: Optional[MultiModalDataDict],
    image_count: int,
169
    skipped_image_indices: Optional[list] = None,
170
171
172
173
174
175
176
) -> 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

177
    assert isinstance(image_data, list) and len(image_data) == image_count
178
179
180
    if skipped_image_indices is not None:
        for i in skipped_image_indices:
            assert image_data[i] is None
181
182


183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
def _assert_mm_uuids(
    mm_uuids: Optional[MultiModalUUIDDict],
    media_count: int,
    expected_uuids: list[Optional[str]],
    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

        assert isinstance(image_uuids,
                          list) and len(image_uuids) == media_count

        assert image_uuids == expected_uuids
    else:
        assert mm_uuids is None


204
205
206
207
208
ModalityType = Literal["image", "video", "audio"]
MultiModalDataCounts = Mapping[ModalityType, int]


def _assert_mm_data_inputs(
209
210
211
212
        mm_data: Optional[MultiModalDataDict],
        data_count: MultiModalDataCounts,
        skipped_media_indices: Optional[dict[
            str, list]] = None,  # modality -> list[int]
213
214
215
216
217
218
219
220
221
) -> 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

222
223
224
225
226
227
228
        if skipped_media_indices is not None:
            skipped_media_indices_for_modality = skipped_media_indices.get(
                modality)
            assert skipped_media_indices_for_modality is not None
            for i in skipped_media_indices_for_modality:
                assert modality_data[i] is None

229

230
231
232
233
234
def test_parse_chat_messages_single_image(
    phi3v_model_config,
    phi3v_tokenizer,
    image_url,
):
235
    conversation, mm_data, mm_uuids = parse_chat_messages(
236
237
238
        [{
            "role":
            "user",
239
240
241
242
243
244
245
246
247
248
249
250
            "content": [
                {
                    "type": "image_url",
                    "image_url": {
                        "url": image_url
                    }
                },
                {
                    "type": "text",
                    "text": "What's in the image?"
                },
            ],
251
252
253
254
255
        }],
        phi3v_model_config,
        phi3v_tokenizer,
        content_format="string",
    )
256
257
258
259
260

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


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

    assert conversation == [{
295
296
        "role": "user",
        "content": "<|image_1|>\nWhat's in the image?"
297
    }]
298
299
    _assert_mm_data_is_image_input(mm_data, 1)
    _assert_mm_uuids(mm_uuids, 1, expected_uuids=[image_uuid])
300
301


302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
def test_parse_chat_messages_single_empty_image_with_uuid(
    phi3v_model_config,
    phi3v_tokenizer,
    image_url,
):
    image_uuid = str(hash(image_url))
    conversation, mm_data, mm_uuids = parse_chat_messages(
        [{
            "role":
            "user",
            "content": [
                {
                    "type": "image_url",
                    "image_url": None,
                    "uuid": image_uuid,
                },
                {
                    "type": "text",
                    "text": "What's in the image?"
                },
            ],
        }],
        phi3v_model_config,
        phi3v_tokenizer,
        content_format="string",
    )

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


337
def test_parse_chat_messages_single_image_with_bad_uuid_format(
338
339
340
341
    phi3v_model_config,
    phi3v_tokenizer,
    image_url,
):
342
343
    image_uuid = str(hash(image_url))
    conversation, mm_data, mm_uuids = parse_chat_messages(
344
345
346
        [{
            "role":
            "user",
347
348
349
350
351
352
353
354
355
356
357
358
359
360
            "content": [
                {
                    "type": "image_url",
                    "image_url": {
                        "url": image_url,
                        "uuid": image_uuid,
                    },
                    "bad_uuid_key": image_uuid,
                },
                {
                    "type": "text",
                    "text": "What's in the image?"
                },
            ],
361
362
363
364
365
        }],
        phi3v_model_config,
        phi3v_tokenizer,
        content_format="string",
    )
366
367
368
369
370

    assert conversation == [{
        "role": "user",
        "content": "<|image_1|>\nWhat's in the image?"
    }]
371
372
    _assert_mm_data_is_image_input(mm_data, 1)
    _assert_mm_uuids(mm_uuids, 1, expected_uuids=[None])
373
374


375
def test_parse_chat_messages_multiple_images_with_uuids(
376
377
378
379
    phi3v_model_config,
    phi3v_tokenizer,
    image_url,
):
380
381
382
383
    image_uuid1 = "my_uuid_1"
    image_uuid2 = "my_uuid_2"

    conversation, mm_data, mm_uuids = parse_chat_messages(
384
385
386
        [{
            "role":
            "user",
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
            "content": [
                {
                    "type": "image_url",
                    "image_url": {
                        "url": image_url,
                    },
                    "uuid": image_uuid1,
                },
                {
                    "type": "image_url",
                    "image_url": {
                        "url": image_url,
                    },
                    "uuid": image_uuid2,
                },
                {
                    "type": "text",
                    "text": "What's in the image?"
                },
            ],
407
408
409
410
411
        }],
        phi3v_model_config,
        phi3v_tokenizer,
        content_format="string",
    )
412
413
414
415
416

    assert conversation == [{
        "role":
        "user",
        "content":
417
        "<|image_1|>\n<|image_2|>\nWhat's in the image?",
418
    }]
419
    _assert_mm_data_is_image_input(mm_data, 2)
420
    _assert_mm_uuids(mm_uuids, 2, expected_uuids=[image_uuid1, image_uuid2])
421
422


423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
def test_parse_chat_messages_multiple_empty_images_with_uuids(
    phi3v_model_config,
    phi3v_tokenizer,
    image_url,
):
    image_uuid1 = "my_uuid_1"
    image_uuid2 = "my_uuid_2"

    conversation, mm_data, mm_uuids = parse_chat_messages(
        [{
            "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?"
                },
            ],
        }],
        phi3v_model_config,
        phi3v_tokenizer,
        content_format="string",
    )

    assert conversation == [{
        "role":
        "user",
        "content":
        "<|image_1|>\n<|image_2|>\nWhat's in the image?",
    }]
    _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,
    phi3v_tokenizer,
    image_url,
):
    image_uuid1 = "my_uuid_1"
    image_uuid2 = "my_uuid_2"

    conversation, mm_data, mm_uuids = parse_chat_messages(
        [{
            "role":
            "user",
            "content": [
                {
                    "type": "image_url",
                    "image_url": {
                        "url": image_url,
                    },
                    "uuid": image_uuid1,
                },
                {
                    "type": "image_url",
                    "image_url": None,
                    "uuid": image_uuid2,
                },
                {
                    "type": "text",
                    "text": "What's in the image?"
                },
            ],
        }],
        phi3v_model_config,
        phi3v_tokenizer,
        content_format="string",
    )

    assert conversation == [{
        "role":
        "user",
        "content":
        "<|image_1|>\n<|image_2|>\nWhat's in the image?",
    }]
    _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])


513
@pytest.mark.asyncio
514
async def test_parse_chat_messages_single_image_with_uuid_async(
515
516
517
518
    phi3v_model_config,
    phi3v_tokenizer,
    image_url,
):
519
520
    image_uuid = str(hash(image_url))
    conversation, mm_future, mm_uuids = parse_chat_messages_futures(
521
522
523
        [{
            "role":
            "user",
524
525
526
527
528
529
530
531
532
533
534
535
536
            "content": [
                {
                    "type": "image_url",
                    "image_url": {
                        "url": image_url
                    },
                    "uuid": image_uuid,
                },
                {
                    "type": "text",
                    "text": "What's in the image?"
                },
            ],
537
538
539
540
541
        }],
        phi3v_model_config,
        phi3v_tokenizer,
        content_format="string",
    )
542
543

    assert conversation == [{
544
545
        "role": "user",
        "content": "<|image_1|>\nWhat's in the image?"
546
    }]
547
548
    _assert_mm_data_is_image_input(await mm_future, 1)
    _assert_mm_uuids(mm_uuids, 1, expected_uuids=[image_uuid])
549
550


551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
@pytest.mark.asyncio
async def test_parse_chat_messages_empty_image_with_uuid_async(
    phi3v_model_config,
    phi3v_tokenizer,
    image_url,
):
    image_uuid = str(hash(image_url))
    conversation, mm_future, mm_uuids = parse_chat_messages_futures(
        [{
            "role":
            "user",
            "content": [
                {
                    "type": "image_url",
                    "image_url": None,
                    "uuid": image_uuid,
                },
                {
                    "type": "text",
                    "text": "What's in the image?"
                },
            ],
        }],
        phi3v_model_config,
        phi3v_tokenizer,
        content_format="string",
    )

    assert conversation == [{
        "role": "user",
        "content": "<|image_1|>\nWhat's in the image?"
    }]
    _assert_mm_data_is_image_input(await mm_future,
                                   1,
                                   skipped_image_indices=[0])
    _assert_mm_uuids(mm_uuids, 1, expected_uuids=[image_uuid])


589
590
@pytest.mark.asyncio
async def test_parse_chat_messages_multiple_images_with_uuids_async(
591
592
593
594
    phi3v_model_config,
    phi3v_tokenizer,
    image_url,
):
595
596
597
598
    image_uuid1 = "my_uuid_1"
    image_uuid2 = "my_uuid_2"

    conversation, mm_future, mm_uuids = parse_chat_messages_futures(
599
600
601
        [{
            "role":
            "user",
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
            "content": [
                {
                    "type": "image_url",
                    "image_url": {
                        "url": image_url
                    },
                    "uuid": image_uuid1,
                },
                {
                    "type": "image_pil",
                    "image_pil": ImageAsset("cherry_blossom").pil_image,
                    "uuid": image_uuid2,
                },
                {
                    "type": "text",
                    "text": "What's in these images?"
                },
            ],
620
621
622
623
624
        }],
        phi3v_model_config,
        phi3v_tokenizer,
        content_format="string",
    )
625

626
627
628
629
    assert conversation == [{
        "role":
        "user",
        "content":
630
        "<|image_1|>\n<|image_2|>\nWhat's in these images?",
631
    }]
632
633
    _assert_mm_data_is_image_input(await mm_future, 2)
    _assert_mm_uuids(mm_uuids, 2, expected_uuids=[image_uuid1, image_uuid2])
634
635


636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
@pytest.mark.asyncio
async def test_parse_chat_messages_multiple_empty_images_with_uuids_async(
    phi3v_model_config,
    phi3v_tokenizer,
    image_url,
):
    image_uuid1 = "my_uuid_1"
    image_uuid2 = "my_uuid_2"

    conversation, mm_future, mm_uuids = parse_chat_messages_futures(
        [{
            "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?"
                },
            ],
        }],
        phi3v_model_config,
        phi3v_tokenizer,
        content_format="string",
    )

    assert conversation == [{
        "role":
        "user",
        "content":
        "<|image_1|>\n<|image_2|>\nWhat's in these images?",
    }]
    _assert_mm_data_is_image_input(await mm_future,
                                   2,
                                   skipped_image_indices=[0, 1])
    _assert_mm_uuids(mm_uuids, 2, expected_uuids=[image_uuid1, image_uuid2])


683
684
@pytest.mark.asyncio
async def test_parse_chat_messages_multiple_images_with_partial_uuids_async(
685
686
687
688
    phi3v_model_config,
    phi3v_tokenizer,
    image_url,
):
689
690
691
    image_uuid2 = "my_uuid_2"

    conversation, mm_future, mm_uuids = parse_chat_messages_futures(
692
693
694
695
696
697
698
699
        [{
            "role":
            "user",
            "content": [
                {
                    "type": "image_url",
                    "image_url": {
                        "url": image_url
700
                    },
701
702
                },
                {
703
704
705
                    "type": "image_pil",
                    "image_pil": ImageAsset("cherry_blossom").pil_image,
                    "uuid": image_uuid2,
706
707
                },
                {
708
709
710
711
                    "type": "text",
                    "text": "What's in these images?"
                },
            ],
712
713
714
715
716
        }],
        phi3v_model_config,
        phi3v_tokenizer,
        content_format="string",
    )
717
718
719
720
721

    assert conversation == [{
        "role":
        "user",
        "content":
722
        "<|image_1|>\n<|image_2|>\nWhat's in these images?",
723
    }]
724
725
    _assert_mm_data_is_image_input(await mm_future, 2)
    _assert_mm_uuids(mm_uuids, 2, expected_uuids=[None, image_uuid2])
726
727


728
729
730
def test_parse_chat_messages_empty_system(
    mistral_model_config,
    mistral_tokenizer,
731
):
732
    # Test string format
733
    conversation, _, _ = parse_chat_messages(
734
735
736
737
738
739
740
741
742
743
744
745
746
        [
            {
                "role": "system",
                "content": ""
            },
            {
                "role": "user",
                "content": [{
                    "type": "text",
                    "text": "Who are you?"
                }],
            },
        ],
747
748
        mistral_model_config,
        mistral_tokenizer,
749
750
        content_format="string",
    )
751
    assert conversation == [
752
753
754
755
        {
            "role": "system",
            "content": ""
        },
756
757
        {
            "role": "user",
758
            "content": "Who are you?"
759
        },
760
    ]
761
762

    # Test openai format
763
    conversation, _, _ = parse_chat_messages(
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
        [
            {
                "role": "system",
                "content": ""
            },
            {
                "role": "user",
                "content": [{
                    "type": "text",
                    "text": "Who are you?"
                }],
            },
        ],
        mistral_model_config,
        mistral_tokenizer,
        content_format="openai",
    )
    assert conversation == [
782
        {
783
            "role": "system",
784
785
786
787
            "content": [{
                "type": "text",
                "text": ""
            }]
788
789
790
        },
        {
            "role": "user",
791
792
793
794
            "content": [{
                "type": "text",
                "text": "Who are you?"
            }]
795
796
797
798
799
        },
    ]


@pytest.mark.asyncio
800
async def test_parse_chat_messages_single_image_async(
801
802
    phi3v_model_config,
    phi3v_tokenizer,
803
    image_url,
804
):
805
    conversation, mm_future, mm_uuids = parse_chat_messages_futures(
806
        [{
807
808
            "role":
            "user",
809
810
811
812
813
814
815
816
817
818
819
820
            "content": [
                {
                    "type": "image_url",
                    "image_url": {
                        "url": image_url
                    }
                },
                {
                    "type": "text",
                    "text": "What's in the image?"
                },
            ],
821
822
823
824
825
        }],
        phi3v_model_config,
        phi3v_tokenizer,
        content_format="string",
    )
826

827
828
829
830
831
    assert conversation == [{
        "role": "user",
        "content": "<|image_1|>\nWhat's in the image?"
    }]
    _assert_mm_data_is_image_input(await mm_future, 1)
832
    _assert_mm_uuids(mm_uuids, 1, expected_uuids=[None])
833
834


835
836
837
838
839
def test_parse_chat_messages_multiple_images(
    phi3v_model_config,
    phi3v_tokenizer,
    image_url,
):
840
    conversation, mm_data, mm_uuids = parse_chat_messages(
841
842
843
        [{
            "role":
            "user",
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
            "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?"
                },
            ],
860
861
862
863
864
        }],
        phi3v_model_config,
        phi3v_tokenizer,
        content_format="string",
    )
865
866
867
868
869

    assert conversation == [{
        "role":
        "user",
        "content":
870
        "<|image_1|>\n<|image_2|>\nWhat's in these images?",
871
    }]
872
    _assert_mm_data_is_image_input(mm_data, 2)
873
    _assert_mm_uuids(mm_uuids, 2, expected_uuids=[None, None])
874
875


876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
def test_parse_chat_messages_empty_pil_image_with_uuid(
    phi3v_model_config,
    phi3v_tokenizer,
):
    uuid = "abcd"
    conversation, mm_data, mm_uuids = parse_chat_messages(
        [{
            "role":
            "user",
            "content": [
                {
                    "type": "image_pil",
                    "image_pil": None,
                    "uuid": uuid
                },
                {
                    "type": "text",
                    "text": "What's in this image?"
                },
            ],
        }],
        phi3v_model_config,
        phi3v_tokenizer,
        content_format="string",
    )

    assert conversation == [{
        "role": "user",
        "content": "<|image_1|>\nWhat's in this image?",
    }]
    _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(
911
    phi3v_model_config_image_embeds,
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
    phi3v_tokenizer,
):
    uuid = "abcd"
    conversation, mm_data, mm_uuids = parse_chat_messages(
        [{
            "role":
            "user",
            "content": [
                {
                    "type": "image_embeds",
                    "image_embeds": None,
                    "uuid": uuid
                },
                {
                    "type": "text",
                    "text": "What's in this image?"
                },
            ],
        }],
931
        phi3v_model_config_image_embeds,
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
        phi3v_tokenizer,
        content_format="string",
    )

    assert conversation == [{
        "role": "user",
        "content": "<|image_1|>\nWhat's in this image?",
    }]
    assert mm_data is not None
    assert "image" in mm_data
    assert mm_data["image"] is None
    _assert_mm_uuids(mm_uuids, 1, expected_uuids=[uuid])


@pytest.mark.asyncio
async def test_parse_chat_messages_empty_image_embeds_with_uuid_async(
948
    phi3v_model_config_image_embeds,
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
    phi3v_tokenizer,
):
    uuid = "abcd"
    conversation, mm_future, mm_uuids = parse_chat_messages_futures(
        [{
            "role":
            "user",
            "content": [
                {
                    "type": "image_embeds",
                    "image_embeds": None,
                    "uuid": uuid
                },
                {
                    "type": "text",
                    "text": "What's in this image?"
                },
            ],
        }],
968
        phi3v_model_config_image_embeds,
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
        phi3v_tokenizer,
        content_format="string",
    )

    assert conversation == [{
        "role": "user",
        "content": "<|image_1|>\nWhat's in this image?",
    }]
    mm_data = await mm_future
    assert mm_data is not None
    assert "image" in mm_data
    assert mm_data["image"] is None
    _assert_mm_uuids(mm_uuids, 1, expected_uuids=[uuid])


984
@pytest.mark.asyncio
985
986
987
988
989
async def test_parse_chat_messages_multiple_images_async(
    phi3v_model_config,
    phi3v_tokenizer,
    image_url,
):
990
    conversation, mm_future, mm_uuids = parse_chat_messages_futures(
991
992
993
        [{
            "role":
            "user",
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
            "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?"
                },
            ],
1010
1011
1012
1013
1014
        }],
        phi3v_model_config,
        phi3v_tokenizer,
        content_format="string",
    )
1015

1016
1017
1018
1019
    assert conversation == [{
        "role":
        "user",
        "content":
1020
        "<|image_1|>\n<|image_2|>\nWhat's in these images?",
1021
1022
    }]
    _assert_mm_data_is_image_input(await mm_future, 2)
1023
    _assert_mm_uuids(mm_uuids, 2, expected_uuids=[None, None])
1024

1025
1026

def test_parse_chat_messages_placeholder_already_in_prompt(
1027
1028
1029
1030
    phi3v_model_config,
    phi3v_tokenizer,
    image_url,
):
1031
    conversation, mm_data, mm_uuids = parse_chat_messages(
1032
1033
1034
1035
        [{
            "role":
            "user",
            "content": [
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
                {
                    "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
                },
            ],
1055
1056
1057
1058
1059
        }],
        phi3v_model_config,
        phi3v_tokenizer,
        content_format="string",
    )
1060
1061
1062
1063
    assert conversation == [{
        "role":
        "user",
        "content":
1064
        "What's in <|image_1|> and how does it compare to <|image_2|>?",
1065
1066
    }]
    _assert_mm_data_is_image_input(mm_data, 2)
1067
    _assert_mm_uuids(mm_uuids, 2, expected_uuids=[None, None])
1068
1069


1070
1071
def test_parse_chat_messages_placeholder_one_already_in_prompt(
    phi3v_model_config,
1072
1073
1074
    phi3v_tokenizer,
    image_url,
):
1075
    conversation, mm_data, mm_uuids = parse_chat_messages(
1076
1077
1078
        [{
            "role":
            "user",
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
            "content": [
                {
                    "type": "image_url",
                    "image_url": {
                        "url": image_url
                    }
                },
                {
                    "type": "image_url",
                    "image_url": {
                        "url": image_url
                    }
                },
                {
                    "type":
                    "text",
                    "text":
1096
1097
1098
                    "What's in <|image_1|> and how does it compare to the other one?",  # noqa: E501
                },
            ],
1099
        }],
1100
        phi3v_model_config,
1101
1102
1103
1104
1105
1106
1107
1108
        phi3v_tokenizer,
        content_format="string",
    )

    assert conversation == [{
        "role":
        "user",
        "content":
1109
        "<|image_2|>\nWhat's in <|image_1|> and how does it compare to the "
1110
        "other one?",
1111
1112
    }]
    _assert_mm_data_is_image_input(mm_data, 2)
1113
    _assert_mm_uuids(mm_uuids, 2, expected_uuids=[None, None])
1114
1115


1116
1117
def test_parse_chat_messages_multiple_images_across_messages(
    phi3v_model_config,
1118
1119
1120
    phi3v_tokenizer,
    image_url,
):
1121
    conversation, mm_data, mm_uuids = parse_chat_messages(
1122
1123
1124
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
        [
            {
                "role":
                "user",
                "content": [
                    {
                        "type": "image_url",
                        "image_url": {
                            "url": image_url
                        }
                    },
                    {
                        "type": "text",
                        "text": "What's in this image?"
                    },
                ],
            },
            {
                "role": "assistant",
                "content": "Some stuff."
            },
            {
                "role":
                "user",
                "content": [
                    {
                        "type": "image_url",
                        "image_url": {
                            "url": image_url
                        }
                    },
                    {
                        "type": "text",
                        "text": "What about this one?"
                    },
                ],
            },
        ],
1160
1161
1162
1163
        phi3v_model_config,
        phi3v_tokenizer,
        content_format="string",
    )
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178

    assert conversation == [
        {
            "role": "user",
            "content": "<|image_1|>\nWhat's in this image?"
        },
        {
            "role": "assistant",
            "content": "Some stuff."
        },
        {
            "role": "user",
            "content": "<|image_2|>\nWhat about this one?"
        },
    ]
1179
    _assert_mm_data_is_image_input(mm_data, 2)
1180
    _assert_mm_uuids(mm_uuids, 2, expected_uuids=[None, None])
1181
1182


1183
def test_parse_chat_messages_multiple_images_with_uuids_across_messages(
1184
1185
    phi3v_model_config,
    phi3v_tokenizer,
1186
    image_url,
1187
):
1188
1189
    image_uuid = str(hash(image_url))
    conversation, mm_data, mm_uuids = parse_chat_messages(
1190
1191
        [
            {
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
                "role":
                "user",
                "content": [
                    {
                        "type": "image_url",
                        "image_url": {
                            "url": image_url
                        },
                        "uuid": image_uuid,
                    },
                    {
                        "type": "text",
                        "text": "What's in this image?"
                    },
                ],
1207
1208
1209
1210
1211
1212
            },
            {
                "role": "assistant",
                "content": "Some stuff."
            },
            {
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
                "role":
                "user",
                "content": [
                    {
                        "type": "image_url",
                        "image_url": {
                            "url": image_url
                        },
                        "uuid": image_uuid,
                    },
                    {
                        "type": "text",
                        "text": "What about this one?"
                    },
                ],
            },
        ],
        phi3v_model_config,
        phi3v_tokenizer,
        content_format="string",
    )

    assert conversation == [
        {
            "role": "user",
            "content": "<|image_1|>\nWhat's in this image?"
        },
        {
            "role": "assistant",
            "content": "Some stuff."
        },
        {
            "role": "user",
            "content": "<|image_2|>\nWhat about this one?"
        },
    ]
    _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,
    phi3v_tokenizer,
):
    conversation, mm_data, mm_uuids = parse_chat_messages(
        [
            {
                "role": "user",
                "content": [{
                    "type": "text",
                    "text": "What's in this text?"
                }],
            },
            {
                "role": "assistant",
                "content": "Some stuff."
            },
            {
                "role": "user",
                "content": "What about this one?"
1273
1274
            },
        ],
1275
1276
1277
1278
        phi3v_model_config,
        phi3v_tokenizer,
        content_format="openai",
    )
1279
1280
1281
1282
1283
1284
1285

    assert conversation == [
        {
            "role": "user",
            "content": [{
                "type": "text",
                "text": "What's in this text?"
1286
            }],
1287
1288
1289
1290
1291
1292
        },
        {
            "role": "assistant",
            "content": [{
                "type": "text",
                "text": "Some stuff."
1293
            }],
1294
1295
1296
1297
1298
1299
        },
        {
            "role": "user",
            "content": [{
                "type": "text",
                "text": "What about this one?"
1300
            }],
1301
1302
        },
    ]
1303
1304
    assert mm_data is None
    assert mm_uuids is None
1305
1306


1307
1308
1309
1310
1311
def test_parse_chat_messages_rejects_too_many_images_in_one_message(
    phi3v_model_config,
    phi3v_tokenizer,
    image_url,
):
1312
1313
1314
    with warnings.catch_warnings():
        warnings.filterwarnings(
            "ignore",
1315
1316
            message="coroutine 'async_get_and_parse_image' was never awaited",
        )
1317
        with pytest.raises(ValueError, match="At most"):
1318
1319
1320
1321
            parse_chat_messages(
                [{
                    "role":
                    "user",
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
                    "content": [
                        {
                            "type": "image_url",
                            "image_url": {
                                "url": image_url
                            },
                        },
                        {
                            "type": "image_url",
                            "image_url": {
                                "url": image_url
                            },
                        },
                        {
                            "type": "image_url",
                            "image_url": {
                                "url": image_url
                            },
                        },
                        {
                            "type": "text",
                            "text": "What's in these images?"
                        },
                    ],
1346
1347
1348
1349
1350
                }],
                phi3v_model_config,
                phi3v_tokenizer,
                content_format="string",
            )
1351
1352


1353
1354
1355
1356
1357
def test_parse_chat_messages_rejects_too_many_images_across_messages(
    phi3v_model_config,
    phi3v_tokenizer,
    image_url,
):
1358
1359
1360
    with warnings.catch_warnings():
        warnings.filterwarnings(
            "ignore",
1361
1362
            message="coroutine 'async_get_and_parse_image' was never awaited",
        )
1363
        with pytest.raises(ValueError, match="At most"):
1364
            parse_chat_messages(
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
                [
                    {
                        "role":
                        "user",
                        "content": [
                            {
                                "type": "image_url",
                                "image_url": {
                                    "url": image_url
                                },
                            },
                            {
                                "type": "text",
                                "text": "What's in this image?"
                            },
                        ],
                    },
                    {
                        "role": "assistant",
                        "content": "Some stuff."
                    },
                    {
                        "role":
                        "user",
                        "content": [
                            {
                                "type": "image_url",
                                "image_url": {
                                    "url": image_url
                                },
                            },
                            {
                                "type": "image_url",
                                "image_url": {
                                    "url": image_url
                                },
                            },
                            {
                                "type": "text",
                                "text": "What about these two?"
                            },
                        ],
                    },
                ],
1409
1410
1411
1412
                phi3v_model_config,
                phi3v_tokenizer,
                content_format="string",
            )
1413
1414
1415
1416
1417
1418
1419


def test_parse_chat_messages_multiple_images_uncommon_input(
    phi3v_model_config,
    phi3v_tokenizer,
    image_url,
):
1420
    conversation, mm_data, mm_uuids = parse_chat_messages(
1421
1422
1423
1424
        [{
            "role":
            "user",
            "content": [
1425
1426
                "What's in these images?",
                {
1427
                    "image_url": image_url
1428
1429
                },
                {
1430
                    "image_url": image_url
1431
1432
                },
            ],
1433
1434
1435
1436
1437
        }],
        phi3v_model_config,
        phi3v_tokenizer,
        content_format="string",
    )
1438
1439
1440
1441
1442

    assert conversation == [{
        "role":
        "user",
        "content":
1443
        "<|image_1|>\n<|image_2|>\nWhat's in these images?",
1444
1445
    }]
    _assert_mm_data_is_image_input(mm_data, 2)
1446
    _assert_mm_uuids(mm_uuids, 2, expected_uuids=[None, None])
1447
1448


1449
1450
1451
1452
1453
def test_parse_chat_messages_multiple_images_interleave(
    phi3v_model_config_mm_interleaved,
    phi3v_tokenizer,
    image_url,
):
1454
    conversation, mm_data, mm_uuids = parse_chat_messages(
1455
1456
1457
        [{
            "role":
            "user",
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
            "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?"
                },
            ],
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
        }],
        phi3v_model_config_mm_interleaved,
        phi3v_tokenizer,
        content_format="string",
    )

    assert conversation == [{
        "role":
        "user",
        "content":
        "I need you to compare this image\n<|image_1|>\nand this one\n<|image_2|>\n"  # noqa: E501
1495
        "Do they have differences?",
1496
1497
    }]
    _assert_mm_data_is_image_input(mm_data, 2)
1498
    _assert_mm_uuids(mm_uuids, 2, expected_uuids=[None, None])
1499
1500
1501
1502
1503
1504
1505
1506


@pytest.mark.asyncio
async def test_parse_chat_messages_multiple_images_interleave_async(
    phi3v_model_config_mm_interleaved,
    phi3v_tokenizer,
    image_url,
):
1507
    conversation, mm_data, mm_uuids = parse_chat_messages_futures(
1508
1509
1510
        [{
            "role":
            "user",
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
            "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?"
                },
            ],
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
        }],
        phi3v_model_config_mm_interleaved,
        phi3v_tokenizer,
        content_format="string",
    )

    assert conversation == [{
        "role":
        "user",
        "content":
        "I need you to compare this image\n<|image_1|>\nand this one\n<|image_2|>\n"  # noqa: E501
1548
        "Do they have differences?",
1549
1550
    }]
    _assert_mm_data_is_image_input(await mm_data, 2)
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
    _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,
    phi3v_tokenizer,
    image_url,
):
    image_uuid = str(hash(image_url))
    conversation, mm_data, mm_uuids = parse_chat_messages_futures(
        [{
            "role":
            "user",
            "content": [
                {
                    "type": "text",
                    "text": "I need you to compare this image",
                },
                {
                    "type": "image_url",
                    "image_url": {
                        "url": image_url
                    },
                    "uuid": image_uuid,
                },
                {
                    "type": "text",
                    "text": "and this one"
                },
                {
                    "type": "image_url",
                    "image_url": {
                        "url": image_url
                    },
                    "uuid": image_uuid,
                },
                {
                    "type": "text",
                    "text": "Do they have differences?"
                },
            ],
        }],
        phi3v_model_config_mm_interleaved,
        phi3v_tokenizer,
        content_format="string",
    )

    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?",
    }]
    _assert_mm_data_is_image_input(await mm_data, 2)
    _assert_mm_uuids(mm_uuids, 2, expected_uuids=[image_uuid, image_uuid])
1608
1609
1610
1611
1612
1613
1614


def test_parse_chat_messages_multiple_images_multiple_messages_interleave(
    phi3v_model_config_mm_interleaved,
    phi3v_tokenizer,
    image_url,
):
1615
    conversation, mm_data, mm_uuids = parse_chat_messages(
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
        [
            {
                "role":
                "user",
                "content": [
                    {
                        "type": "text",
                        "text": "What's on this image?"
                    },
                    {
                        "type": "image_url",
                        "image_url": {
                            "url": image_url
                        }
                    },
                    {
                        "type": "text",
                        "text": "Be accurate."
                    },
                ],
            },
            {
                "role": "assistant",
                "content": "Some stuff."
            },
            {
                "role":
                "user",
                "content": [
                    {
                        "type": "text",
                        "text": "What's on this image?"
                    },
                    {
                        "type": "image_url",
                        "image_url": {
                            "url": image_url
                        }
                    },
                ],
            },
        ],
1658
1659
1660
1661
1662
        phi3v_model_config_mm_interleaved,
        phi3v_tokenizer,
        content_format="string",
    )

1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
    assert conversation == [
        {
            "role": "user",
            "content": "What's on this image?\n<|image_1|>\nBe accurate.",
        },
        {
            "role": "assistant",
            "content": "Some stuff."
        },
        {
            "role": "user",
            "content": "What's on this image?\n<|image_2|>"
        },
    ]
1677
    _assert_mm_data_is_image_input(mm_data, 2)
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
    _assert_mm_uuids(mm_uuids, 2, expected_uuids=[None, None])


def test_parse_chat_messages_multiple_images_with_uuids_multiple_messages_interleave(  # noqa: E501
    phi3v_model_config_mm_interleaved,
    phi3v_tokenizer,
    image_url,
):
    image_uuid = str(hash(image_url))
    conversation, mm_data, mm_uuids = parse_chat_messages(
        [
            {
                "role":
                "user",
                "content": [
                    {
                        "type": "text",
                        "text": "What's on this image?"
                    },
                    {
                        "type": "image_url",
                        "image_url": {
                            "url": image_url
                        },
                        "uuid": image_uuid,
                    },
                    {
                        "type": "text",
                        "text": "Be accurate."
                    },
                ],
            },
            {
                "role": "assistant",
                "content": "Some stuff."
            },
            {
                "role":
                "user",
                "content": [
                    {
                        "type": "text",
                        "text": "What's on this image?"
                    },
                    {
                        "type": "image_url",
                        "image_url": {
                            "url": image_url
                        },
                        "uuid": image_uuid,
                    },
                ],
            },
        ],
        phi3v_model_config_mm_interleaved,
        phi3v_tokenizer,
        content_format="string",
    )

    assert conversation == [
        {
            "role": "user",
            "content": "What's on this image?\n<|image_1|>\nBe accurate.",
        },
        {
            "role": "assistant",
            "content": "Some stuff."
        },
        {
            "role": "user",
            "content": "What's on this image?\n<|image_2|>"
        },
    ]
    _assert_mm_data_is_image_input(mm_data, 2)
    _assert_mm_uuids(mm_uuids, 2, expected_uuids=[image_uuid, image_uuid])
1753
1754
1755


def test_parse_chat_messages_multiple_modals_multiple_messages_interleave(
1756
1757
1758
1759
1760
1761
    qwen25omni_model_config_mm_interleaved,
    qwen25omni_tokenizer,
    image_url,
    video_url,
    audio_url,
):
1762
    conversation, mm_data, mm_uuids = parse_chat_messages(
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
        [
            {
                "role":
                "user",
                "content": [
                    {
                        "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
                        }
                    },
                ],
            },
            {
                "role": "assistant",
                "content": "Some stuff."
            },
            {
                "role":
                "user",
                "content": [
                    {
                        "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
                        }
                    },
                ],
            },
        ],
        qwen25omni_model_config_mm_interleaved,
        qwen25omni_tokenizer,
        content_format="string",
    )

    assert conversation == [
        {
1828
1829
            "role":
            "user",
1830
1831
1832
1833
1834
            "content":
            "What's on this image?\n<|vision_start|><|IMAGE|><|vision_end|>\n"
            "Now listen to this audio\nAudio 1: <|audio_bos|><|AUDIO|><|audio_eos|>",  # noqa: E501
        },
        {
1835
1836
            "role": "assistant",
            "content": "Some stuff."
1837
1838
        },
        {
1839
1840
            "role":
            "user",
1841
1842
1843
1844
1845
            "content":
            "What's on this image?\n<|vision_start|><|IMAGE|><|vision_end|>\n"
            "And what's in the video?\n<|vision_start|><|VIDEO|><|vision_end|>",
        },
    ]
1846
1847

    _assert_mm_data_inputs(mm_data, {"image": 2, "video": 1, "audio": 1})
1848
1849
1850
1851
1852
1853
1854
1855
1856
    _assert_mm_uuids(mm_uuids,
                     2,
                     modality="image",
                     expected_uuids=[None, None])
    _assert_mm_uuids(mm_uuids, 1, modality="video", expected_uuids=[None])
    _assert_mm_uuids(mm_uuids, 1, modality="audio", expected_uuids=[None])


def test_parse_chat_messages_multiple_modals_with_uuids_multiple_messages_interleave(  # noqa: E501
1857
1858
1859
1860
1861
1862
    qwen25omni_model_config_mm_interleaved,
    qwen25omni_tokenizer,
    image_url,
    video_url,
    audio_url,
):
1863
    conversation, mm_data, mm_uuids = parse_chat_messages(
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
        [
            {
                "role":
                "user",
                "content": [
                    {
                        "type": "text",
                        "text": "What's on this image?"
                    },
                    {
                        "type": "image_url",
                        "image_url": {
                            "url": image_url
1877
1878
                        },
                        "uuid": "image_123",
1879
1880
1881
1882
1883
1884
1885
1886
1887
                    },
                    {
                        "type": "text",
                        "text": "Now listen to this audio"
                    },
                    {
                        "type": "audio_url",
                        "audio_url": {
                            "url": audio_url
1888
1889
                        },
                        "uuid": "audio_123",
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
                    },
                ],
            },
            {
                "role": "assistant",
                "content": "Some stuff."
            },
            {
                "role":
                "user",
                "content": [
                    {
                        "type": "text",
                        "text": "What's on this image?"
                    },
                    {
                        "type": "image_url",
                        "image_url": {
                            "url": image_url
1909
1910
                        },
                        "uuid": "image_123",
1911
1912
1913
1914
1915
1916
1917
1918
1919
                    },
                    {
                        "type": "text",
                        "text": "And what's in the video?"
                    },
                    {
                        "type": "video_url",
                        "video_url": {
                            "url": video_url
1920
1921
                        },
                        "uuid": "video_123",
1922
1923
1924
1925
1926
1927
                    },
                ],
            },
        ],
        qwen25omni_model_config_mm_interleaved,
        qwen25omni_tokenizer,
1928
1929
1930
        content_format="string",
    )

1931
1932
    assert conversation == [
        {
1933
1934
            "role":
            "user",
1935
1936
1937
1938
1939
            "content":
            "What's on this image?\n<|vision_start|><|IMAGE|><|vision_end|>\n"
            "Now listen to this audio\nAudio 1: <|audio_bos|><|AUDIO|><|audio_eos|>",  # noqa: E501
        },
        {
1940
1941
            "role": "assistant",
            "content": "Some stuff."
1942
1943
        },
        {
1944
1945
            "role":
            "user",
1946
1947
1948
1949
1950
            "content":
            "What's on this image?\n<|vision_start|><|IMAGE|><|vision_end|>\n"
            "And what's in the video?\n<|vision_start|><|VIDEO|><|vision_end|>",
        },
    ]
1951
1952

    _assert_mm_data_inputs(mm_data, {"image": 2, "video": 1, "audio": 1})
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
    _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"])
1965
1966


1967
def test_parse_chat_messages_multiple_modals_with_uuids_multiple_empty_media_messages_interleave(  # noqa: E501
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
    qwen25omni_model_config_mm_interleaved,
    qwen25omni_tokenizer,
    image_url,
    video_url,
    audio_url,
):
    conversation, mm_data, mm_uuids = parse_chat_messages(
        [
            {
                "role":
                "user",
                "content": [
                    {
                        "type": "text",
                        "text": "What's on this image?"
                    },
                    {
                        "type": "image_url",
1986
                        "image_url": None,
1987
1988
1989
1990
1991
1992
1993
1994
                        "uuid": "image_123",
                    },
                    {
                        "type": "text",
                        "text": "Now listen to this audio"
                    },
                    {
                        "type": "audio_url",
1995
                        "audio_url": None,
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
                        "uuid": "audio_123",
                    },
                ],
            },
            {
                "role": "assistant",
                "content": "Some stuff."
            },
            {
                "role":
                "user",
                "content": [
                    {
                        "type": "text",
                        "text": "What's on this image?"
                    },
                    {
                        "type": "image_url",
2014
                        "image_url": None,
2015
2016
2017
2018
2019
2020
2021
2022
                        "uuid": "image_123",
                    },
                    {
                        "type": "text",
                        "text": "And what's in the video?"
                    },
                    {
                        "type": "video_url",
2023
                        "video_url": None,
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
                        "uuid": "video_123",
                    },
                ],
            },
        ],
        qwen25omni_model_config_mm_interleaved,
        qwen25omni_tokenizer,
        content_format="string",
    )

    assert conversation == [
        {
2036
2037
            "role":
            "user",
2038
2039
2040
2041
2042
            "content":
            "What's on this image?\n<|vision_start|><|IMAGE|><|vision_end|>\n"
            "Now listen to this audio\nAudio 1: <|audio_bos|><|AUDIO|><|audio_eos|>",  # noqa: E501
        },
        {
2043
2044
            "role": "assistant",
            "content": "Some stuff."
2045
2046
        },
        {
2047
2048
            "role":
            "user",
2049
2050
2051
2052
2053
2054
            "content":
            "What's on this image?\n<|vision_start|><|IMAGE|><|vision_end|>\n"
            "And what's in the video?\n<|vision_start|><|VIDEO|><|vision_end|>",
        },
    ]

2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
    _assert_mm_data_inputs(mm_data, {
        "image": 2,
        "video": 1,
        "audio": 1
    },
                           skipped_media_indices={
                               "image": [0, 1],
                               "video": [0],
                               "audio": [0]
                           })
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
    _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"])


def test_parse_chat_messages_multiple_modals_with_partial_uuids_multiple_messages_interleave(  # noqa: E501
    qwen25omni_model_config_mm_interleaved,
    qwen25omni_tokenizer,
    image_url,
    video_url,
    audio_url,
):
    conversation, mm_data, mm_uuids = parse_chat_messages(
        [
            {
                "role":
                "user",
                "content": [
                    {
                        "type": "text",
                        "text": "What's on this image?"
                    },
                    {
                        "type": "image_url",
                        "image_url": {
                            "url": image_url
                        },
                        "uuid": "image_123",
                    },
                    {
                        "type": "text",
                        "text": "Now listen to this audio"
                    },
                    {
                        "type": "audio_url",
                        "audio_url": {
                            "url": audio_url
                        }
                    },
                ],
            },
            {
                "role": "assistant",
                "content": "Some stuff."
            },
            {
                "role":
                "user",
                "content": [
                    {
                        "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
                        },
                        "uuid": "video_123",
                    },
                ],
            },
        ],
2147
2148
2149
2150
2151
        qwen25omni_model_config_mm_interleaved,
        qwen25omni_tokenizer,
        content_format="string",
    )

2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
    assert conversation == [
        {
            "role":
            "user",
            "content":
            "What's on this image?\n<|vision_start|><|IMAGE|><|vision_end|>\n"
            "Now listen to this audio\nAudio 1: <|audio_bos|><|AUDIO|><|audio_eos|>",  # noqa: E501
        },
        {
            "role": "assistant",
            "content": "Some stuff."
        },
        {
            "role":
            "user",
            "content":
            "What's on this image?\n<|vision_start|><|IMAGE|><|vision_end|>\n"
            "And what's in the video?\n<|vision_start|><|VIDEO|><|vision_end|>",
        },
    ]
2172
2173

    _assert_mm_data_inputs(mm_data, {"image": 2, "video": 1, "audio": 1})
2174
2175
2176
2177
2178
2179
2180
2181
2182
    _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"])
    _assert_mm_uuids(mm_uuids, 1, modality="audio", expected_uuids=[None])
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192


def test_parse_chat_messages_multiple_images_interleave_with_placeholders(
    phi3v_model_config_mm_interleaved,
    phi3v_tokenizer,
    image_url,
):
    with pytest.raises(
            ValueError,
            match=r"Found more '<|image_1|>' placeholders in input prompt "
2193
2194
            "than actual multimodal data items.",
    ):
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
        parse_chat_messages(
            [{
                "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
2217
                        "Do they have differences?",
2218
                    },
2219
                ],
2220
2221
2222
2223
2224
2225
2226
            }],
            phi3v_model_config_mm_interleaved,
            phi3v_tokenizer,
            content_format="string",
        )


2227
2228
2229
2230
2231
@pytest.mark.parametrize(
    "model",
    [
        QWEN2VL_MODEL_ID,  # tokenizer.chat_template is of type str
        HERMES_MODEL_ID,  # tokenizer.chat_template is of type dict
2232
2233
    ],
)
2234
2235
2236
@pytest.mark.parametrize("use_tools", [True, False])
def test_resolve_hf_chat_template(sample_json_schema, model, use_tools):
    """checks that chat_template is a dict type for HF models."""
2237
2238
2239
2240
2241
2242
2243
    model_info = HF_EXAMPLE_MODELS.find_hf_info(model)
    model_info.check_available_online(on_fail="skip")

    model_config = ModelConfig(
        model,
        tokenizer=model_info.tokenizer or model,
        tokenizer_mode=model_info.tokenizer_mode,
2244
        revision=model_info.revision,
2245
2246
        trust_remote_code=model_info.trust_remote_code,
        hf_overrides=model_info.hf_overrides,
2247
2248
2249
        skip_tokenizer_init=model_info.skip_tokenizer_init,
        enforce_eager=model_info.enforce_eager,
        dtype=model_info.dtype)
2250

2251
2252
    # Build the tokenizer
    tokenizer = get_tokenizer(
2253
        model,
2254
        trust_remote_code=model_config.trust_remote_code,
2255
2256
    )

2257
    tools = ([{
2258
2259
2260
2261
        "type": "function",
        "function": {
            "name": "dummy_function_name",
            "description": "This is a dummy function",
2262
2263
2264
            "parameters": sample_json_schema,
        },
    }] if use_tools else None)
2265
2266

    # Test detecting the tokenizer's chat_template
2267
    chat_template = resolve_hf_chat_template(
2268
2269
2270
        tokenizer,
        chat_template=None,
        tools=tools,
2271
        model_config=model_config,
2272
2273
2274
2275
    )
    assert isinstance(chat_template, str)


2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
@pytest.mark.parametrize(
    "model, expected_kwargs",
    [
        (
            QWEN2VL_MODEL_ID,
            {
                "add_vision_id", "add_generation_prompt",
                "continue_final_message", "tools"
            },
        ),
        (
            QWEN3_MODEL_ID,
            {
                "enable_thinking", "add_generation_prompt",
                "continue_final_message", "tools"
            },
        ),
    ],
)
def test_resolve_hf_chat_template_kwargs(sample_json_schema, model,
                                         expected_kwargs):
    """checks that chat_template is a dict type for HF models."""
    model_info = HF_EXAMPLE_MODELS.find_hf_info(model)
    model_info.check_available_online(on_fail="skip")

    tools = ([{
        "type": "function",
        "function": {
            "name": "dummy_function_name",
            "description": "This is a dummy function",
            "parameters": sample_json_schema,
        },
    }])

    chat_template_kwargs = {
        # both unused
        "unsed_kwargs_1": 123,
        "unsed_kwargs_2": "abc",
        # should not appear
        "chat_template": "{% Hello world! %}",
        # used by tokenizer
        "continue_final_message": True,
        "tools": tools,
        # both used by Qwen2-VL and Qwen3
        "add_generation_prompt": True,
        # only used by Qwen2-VL
        "add_vision_id": True,
        # only used by Qwen3
        "enable_thinking": True,
    }

    model_config = ModelConfig(
        model,
        tokenizer=model_info.tokenizer or model,
        tokenizer_mode=model_info.tokenizer_mode,
        revision=model_info.revision,
        trust_remote_code=model_info.trust_remote_code,
        hf_overrides=model_info.hf_overrides,
        skip_tokenizer_init=model_info.skip_tokenizer_init,
        enforce_eager=model_info.enforce_eager,
        dtype=model_info.dtype)

    # Build the tokenizer
    tokenizer = get_tokenizer(
        model,
        trust_remote_code=model_config.trust_remote_code,
    )

    # Test detecting the tokenizer's chat_template
    chat_template = resolve_hf_chat_template(
        tokenizer,
        chat_template=None,
        tools=tools,
        model_config=model_config,
    )
    resolved_chat_template_kwargs = resolve_chat_template_kwargs(
        tokenizer,
        chat_template=chat_template,
        chat_template_kwargs=chat_template_kwargs,
    )
    assert set(resolved_chat_template_kwargs.keys()) == expected_kwargs


2359
2360
# NOTE: Qwen2-Audio default chat template is specially defined inside
# processor class instead of using `tokenizer_config.json`
2361
2362
2363
2364
2365
# yapf: disable
@pytest.mark.parametrize(
    ("model", "expected_format"),
    [(PHI3V_MODEL_ID, "string"),
     (QWEN2VL_MODEL_ID, "openai"),
2366
     (QWEN25VL_MODEL_ID, "openai"),
2367
     (ULTRAVOX_MODEL_ID, "string"),
2368
     (QWEN2AUDIO_MODEL_ID, "openai"),
2369
2370
2371
2372
     (LLAMA_GUARD_MODEL_ID, "openai")],
)
# yapf: enable
def test_resolve_content_format_hf_defined(model, expected_format):
2373
2374
2375
2376
2377
2378
2379
    model_info = HF_EXAMPLE_MODELS.find_hf_info(model)
    model_info.check_available_online(on_fail="skip")

    model_config = ModelConfig(
        model,
        tokenizer=model_info.tokenizer or model,
        tokenizer_mode=model_info.tokenizer_mode,
2380
        revision=model_info.revision,
2381
2382
        trust_remote_code=model_info.trust_remote_code,
        hf_overrides=model_info.hf_overrides,
2383
2384
2385
        skip_tokenizer_init=model_info.skip_tokenizer_init,
        enforce_eager=model_info.enforce_eager,
        dtype=model_info.dtype)
2386

2387
    tokenizer = get_tokenizer(
2388
        model,
2389
        trust_remote_code=model_config.trust_remote_code,
2390
2391
    )

2392
    # Test detecting the tokenizer's chat_template
2393
    chat_template = resolve_hf_chat_template(
2394
2395
2396
        tokenizer,
        chat_template=None,
        tools=None,
2397
        model_config=model_config,
2398
    )
2399
2400
2401
2402
2403
2404
2405
2406
2407
    assert isinstance(chat_template, str)

    print("[TEXT]")
    print(chat_template)
    print("[AST]")
    print(_try_extract_ast(chat_template))

    resolved_format = resolve_chat_template_content_format(
        None,  # Test detecting the tokenizer's chat_template
2408
        None,
2409
2410
        "auto",
        tokenizer,
2411
        model_config=model_config,
2412
2413
2414
2415
2416
2417
2418
2419
    )

    assert resolved_format == expected_format


# yapf: disable
@pytest.mark.parametrize(
    ("model", "expected_format"),
2420
2421
2422
2423
2424
2425
2426
    [(os.path.join(models_path_prefix, "Salesforce/blip2-opt-2.7b"), "string"),
     (os.path.join(models_path_prefix, "facebook/chameleon-7b"), "string"),
     (os.path.join(models_path_prefix, "deepseek-ai/deepseek-vl2-tiny"), "string"),
     (os.path.join(models_path_prefix, "adept/fuyu-8b"), "string"),
     (os.path.join(models_path_prefix, "google/paligemma-3b-mix-224"), "string"),
     (os.path.join(models_path_prefix, "Qwen/Qwen-VL"), "string"),
     (os.path.join(models_path_prefix, "Qwen/Qwen-VL-Chat"), "string")],
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
)
# yapf: enable
def test_resolve_content_format_fallbacks(model, expected_format):
    model_info = HF_EXAMPLE_MODELS.find_hf_info(model)
    model_info.check_available_online(on_fail="skip")

    model_config = ModelConfig(
        model,
        tokenizer=model_info.tokenizer or model,
        tokenizer_mode=model_info.tokenizer_mode,
2437
        revision=model_info.revision,
2438
2439
        trust_remote_code=model_info.trust_remote_code,
        hf_overrides=model_info.hf_overrides,
2440
2441
2442
        skip_tokenizer_init=model_info.skip_tokenizer_init,
        enforce_eager=model_info.enforce_eager,
        dtype=model_info.dtype)
2443

2444
    tokenizer = get_tokenizer(
2445
2446
2447
2448
2449
2450
2451
2452
2453
        model_config.tokenizer,
        trust_remote_code=model_config.trust_remote_code,
    )

    # Test detecting the tokenizer's chat_template
    chat_template = resolve_hf_chat_template(
        tokenizer,
        chat_template=None,
        tools=None,
2454
        model_config=model_config,
2455
2456
2457
2458
2459
2460
2461
2462
2463
    )
    assert isinstance(chat_template, str)

    print("[TEXT]")
    print(chat_template)
    print("[AST]")
    print(_try_extract_ast(chat_template))

    resolved_format = resolve_chat_template_content_format(
2464
        None,  # Test detecting the tokenizer's chat_template
2465
        None,
2466
2467
        "auto",
        tokenizer,
2468
        model_config=model_config,
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
    )

    assert resolved_format == expected_format


# yapf: disable
@pytest.mark.parametrize(
    ("template_path", "expected_format"),
    [("template_alpaca.jinja", "string"),
     ("template_baichuan.jinja", "string"),
     ("template_chatglm.jinja", "string"),
     ("template_chatglm2.jinja", "string"),
     ("template_chatml.jinja", "string"),
2482
     ("template_dse_qwen2_vl.jinja", "openai"),
2483
2484
2485
     ("template_falcon_180b.jinja", "string"),
     ("template_falcon.jinja", "string"),
     ("template_inkbot.jinja", "string"),
2486
     ("template_teleflm.jinja", "string"),
2487
2488
2489
2490
     ("template_vlm2vec.jinja", "openai"),
     ("tool_chat_template_granite_20b_fc.jinja", "string"),
     ("tool_chat_template_hermes.jinja", "string"),
     ("tool_chat_template_internlm2_tool.jinja", "string"),
2491
2492
     ("tool_chat_template_llama3.1_json.jinja", "openai"),
     ("tool_chat_template_llama3.2_json.jinja", "openai"),
2493
2494
2495
2496
2497
     ("tool_chat_template_mistral_parallel.jinja", "string"),
     ("tool_chat_template_mistral.jinja", "string")],
)
# yapf: enable
def test_resolve_content_format_examples(template_path, expected_format):
2498
2499
2500
2501
2502
2503
    model_config = ModelConfig(
        PHI3V_MODEL_ID,  # Dummy
        tokenizer=PHI3V_MODEL_ID,  # Dummy
        trust_remote_code=True,
    )

2504
    dummy_tokenizer = get_tokenizer(
2505
2506
        PHI3V_MODEL_ID,  # Dummy
        trust_remote_code=model_config.trust_remote_code,
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
    )
    dummy_tokenizer.chat_template = None

    chat_template = load_chat_template(EXAMPLES_DIR / template_path)
    assert isinstance(chat_template, str)

    print("[TEXT]")
    print(chat_template)
    print("[AST]")
    print(_try_extract_ast(chat_template))

    resolved_format = resolve_chat_template_content_format(
        chat_template,
2520
        None,
2521
2522
        "auto",
        dummy_tokenizer,
2523
        model_config=model_config,
2524
2525
2526
    )

    assert resolved_format == expected_format
Julien Denize's avatar
Julien Denize committed
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563


def test_parse_chat_messages_include_thinking_chunk(mistral_model_config,
                                                    mistral_tokenizer):
    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.",
        }],
    }]

2564
    conversation_with_thinking, _, _ = parse_chat_messages(
Julien Denize's avatar
Julien Denize committed
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
        messages,
        mistral_model_config,
        mistral_tokenizer,
        content_format="openai",
    )

    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."
            },
        ]
    }]

    assert conversation_with_thinking == expected_conversation


def test_apply_mistral_chat_template_thinking_chunk():
    # Moved import here to avoid yapf and isort conflicts
    from vllm.entrypoints.chat_utils import apply_mistral_chat_template
    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.",
        }],
    }, {
        "role": "user",
        "content": "Thanks, what is 3+3?"
    }]

    # TODO(Julien): upon model release change to a tokenizer already configured.
    # =================================================================
    mistral_tokenizer = MistralTokenizer.from_pretrained(
        "mistralai/Devstral-Small-2507")
    assert isinstance(mistral_tokenizer.tokenizer, Tekkenizer)
    # Add think special tokens to the tokenizer
    mistral_tokenizer.tokenizer._all_special_tokens[35] = SpecialTokenInfo(
        rank=35, is_control=True, token_str=SpecialTokens.begin_think.value)
    mistral_tokenizer.tokenizer._all_special_tokens[36] = SpecialTokenInfo(
        rank=36, is_control=True, token_str=SpecialTokens.end_think.value)
    mistral_tokenizer.tokenizer._special_tokens_reverse_vocab = {
        k: v
        for k, v in
        mistral_tokenizer.tokenizer._special_tokens_reverse_vocab.items()
        if v not in {35, 36}
    }
    mistral_tokenizer.tokenizer._special_tokens_reverse_vocab[
        SpecialTokens.begin_think.value] = 35
    mistral_tokenizer.tokenizer._special_tokens_reverse_vocab[
        SpecialTokens.end_think.value] = 36
    mistral_tokenizer.instruct.BEGIN_THINK = 35
    mistral_tokenizer.instruct.END_THINK = 36
    # =================================================================

    tokens_ids = apply_mistral_chat_template(mistral_tokenizer,
                                             messages,
                                             chat_template=None,
                                             tools=None)

    string_tokens = mistral_tokenizer.mistral.decode(
        tokens_ids, special_token_policy=SpecialTokenPolicy.KEEP)

    expected_tokens = (
        r"<s>[SYSTEM_PROMPT]You are a helpful assistant.[THINK]Only return the"
        r" answer when you are confident.[/THINK][/SYSTEM_PROMPT]"
        r"[INST]What is 2+2?[/INST]"
        r"Let me think about it.[THINK]2+2 = 4[/THINK]The answer is 4.</s>"
        r"[INST]Thanks, what is 3+3?[/INST]")

    assert string_tokens == expected_tokens
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767


def test_parse_chat_messages_single_empty_audio_with_uuid(
    qwen2_audio_model_config,
    qwen2_audio_tokenizer,
):
    audio_uuid = "abcd"
    conversation, mm_data, mm_uuids = parse_chat_messages(
        [{
            "role":
            "user",
            "content": [
                {
                    "type": "input_audio",
                    "input_audio": {},
                    "uuid": audio_uuid,
                },
                {
                    "type": "text",
                    "text": "What does the audio say?"
                },
            ],
        }],
        qwen2_audio_model_config,
        qwen2_audio_tokenizer,
        content_format="string",
    )

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


@pytest.mark.asyncio
async def test_parse_chat_messages_single_empty_audio_with_uuid_async(
    qwen2_audio_model_config,
    qwen2_audio_tokenizer,
):
    audio_uuid = "abcd"
    conversation, mm_future, mm_uuids = parse_chat_messages_futures(
        [{
            "role":
            "user",
            "content": [
                {
                    "type": "input_audio",
                    "input_audio": {},
                    "uuid": audio_uuid,
                },
                {
                    "type": "text",
                    "text": "What does the audio say?"
                },
            ],
        }],
        qwen2_audio_model_config,
        qwen2_audio_tokenizer,
        content_format="string",
    )

    assert conversation == [{
        "role":
        "user",
        "content":
        "Audio 1: <|audio_bos|><|AUDIO|><|audio_eos|>\nWhat does the audio say?"
    }]
    _assert_mm_data_inputs(await mm_future, {"audio": 1})
    _assert_mm_uuids(mm_uuids,
                     1,
                     modality="audio",
                     expected_uuids=[audio_uuid])