forked from openvinotoolkit/openvino.genai
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest_vlm_pipeline.py
More file actions
2096 lines (1724 loc) · 73.7 KB
/
test_vlm_pipeline.py
File metadata and controls
2096 lines (1724 loc) · 73.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
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
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
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
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
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
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
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
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# Copyright (C) 2018-2026 Intel Corporation
# SPDX-License-Identifier: Apache-2.0
"""
Fixture hierarchy
synthetic_video ──────── synthetic_video_32x32_tensor
cat_image ───────────┬── cat_tensor
│ ├── cat_image_384x384
│ ├── cat_image_336x336
│ └── cat_image_32x32
│
├── iteration_images
│ ├── cat_tensor
│ ├── car_tensor
│ └── handwritten_tensor
│
├── image_sequence
│ └── cat_tensor
│
└── conversation_requests
├── cat_tensor
├── car_tensor
└── handwritten_tensor
car_tensor
handwritten_tensor
ov_pipe_model
ov_continious_batching_pipe
"""
import collections
from enum import Enum
from dataclasses import dataclass
from pathlib import Path
from typing import Callable, Generator
import openvino_tokenizers
import openvino
import PIL
import pytest
import platform
import requests
import sys
import os
import numpy as np
import transformers
from optimum.intel.openvino import OVModelForVisualCausalLM
from optimum.utils.import_utils import is_transformers_version
from openvino_genai import (
VLMPipeline,
GenerationConfig,
SchedulerConfig,
ContinuousBatchingPipeline,
GenerationStatus,
StreamingStatus,
GenerationFinishReason,
ChatHistory,
)
from utils.network import retry_request
from utils.generation_config import (
get_beam_search,
get_multinomial_all_parameters,
get_greedy,
)
from utils.constants import get_ov_cache_converted_models_dir
from utils.atomic_download import AtomicDownloadManager
import logging
logger = logging.getLogger(__name__)
class VisionType(Enum):
IMAGE = "IMAGE"
VIDEO = "VIDEO"
@dataclass(frozen=True)
class VlmModelInfo:
model_id: str
ov_backend: str
image_tag: Callable[[int], str]
video_tag: Callable[[int], str]
resolution: int
pipeline: VLMPipeline
def get_vision_tag(self, vision_type: VisionType) -> Callable[[int], str]:
return self.image_tag if vision_type == VisionType.IMAGE else self.video_tag
PROMPTS: list[str] = [
"What is in the image?",
"What is special about this image?",
"Describe the image"
]
VIDEO_MODEL_IDS = [
"optimum-intel-internal-testing/tiny-random-llava-next-video",
"optimum-intel-internal-testing/tiny-random-qwen2vl",
"optimum-intel-internal-testing/tiny-random-qwen2.5-vl",
]
MODEL_IDS: list[str] = [
"optimum-intel-internal-testing/tiny-random-minicpmv-2_6",
"optimum-intel-internal-testing/tiny-random-phi3-vision",
"optimum-intel-internal-testing/tiny-random-phi-4-multimodal",
"optimum-intel-internal-testing/tiny-random-llava",
"optimum-intel-internal-testing/tiny-random-llava-next",
"optimum-intel-internal-testing/tiny-random-internvl2",
"optimum-intel-internal-testing/tiny-random-gemma3",
"qnguyen3/nanoLLaVA",
"optimum-intel-internal-testing/tiny-random-MiniCPM-o-2_6",
*VIDEO_MODEL_IDS,
]
ADD_REQUEST_MODEL_IDS = [
MODEL_IDS[0],
*VIDEO_MODEL_IDS
]
IMAGE_TAG_GENERATOR_BY_MODEL: dict[str, Callable[[int], str]] = {
"optimum-intel-internal-testing/tiny-random-llava": lambda idx: "<image>",
"optimum-intel-internal-testing/tiny-random-llava-next": lambda idx: "<image>",
"optimum-intel-internal-testing/tiny-random-qwen2vl": lambda idx: "<|vision_start|><|image_pad|><|vision_end|>",
"optimum-intel-internal-testing/tiny-random-qwen2.5-vl": lambda idx: "<|vision_start|><|image_pad|><|vision_end|>",
"optimum-intel-internal-testing/tiny-random-gemma3": lambda idx: "<start_of_image>",
"optimum-intel-internal-testing/tiny-random-internvl2": lambda idx: "<image>\n",
"optimum-intel-internal-testing/tiny-random-minicpmv-2_6": lambda idx: "<image>./</image>\n",
"optimum-intel-internal-testing/tiny-random-MiniCPM-o-2_6": lambda idx: "<image>./</image>\n",
"optimum-intel-internal-testing/tiny-random-phi3-vision": lambda idx: f"<|image_{idx + 1}|>\n",
"optimum-intel-internal-testing/tiny-random-llava-next-video": lambda idx: "<image>\n",
"qnguyen3/nanoLLaVA": lambda idx: "<image>\n",
}
VIDEO_TAG_GENERATOR_BY_MODEL: dict[str, Callable[[int], str]] = {
"optimum-intel-internal-testing/tiny-random-llava-next-video": lambda idx: "<video>",
"optimum-intel-internal-testing/tiny-random-qwen2vl": lambda idx: "<|vision_start|><|video_pad|><|vision_end|>",
"optimum-intel-internal-testing/tiny-random-qwen2.5-vl": lambda idx: "<|vision_start|><|video_pad|><|vision_end|>",
}
RESOLUTION_BY_MODEL: dict[str, int | None] = {
"optimum-intel-internal-testing/tiny-random-gemma3": 32,
"qnguyen3/nanoLLaVA": 384,
"optimum-intel-internal-testing/tiny-random-llava-next-video": 336,
"optimum-intel-internal-testing/tiny-random-MiniCPM-o-2_6": 448,
}
RESOLUTION_BY_VIDEO_MODEL: dict[str, int | None] = {
"optimum-intel-internal-testing/tiny-random-llava-next-video": 32,
}
DEFAULT_RESOLUTION = 336
ATTENTION_BACKEND: list[str] = ["PA", "SDPA"]
DEFAULT_MAX_NEW_TOKENS = 30
DEFAULT_SCORE_EPSILON = 0.001
IMAGE_TOKENS_NUM = 54
MAX_RETRIES = 10
RETRY_BASE_DELAY_SEC = 0.1
RETRY_MAX_DELAY_SEC = 2.0
TEST_IMAGE_URLS = {
'cat': 'https://github.com/openvinotoolkit/openvino_notebooks/assets/29454499/d5fbbd1a-d484-415c-88cb-9986625b7b11',
'car': 'https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/tasks/car.jpg',
'handwritten': 'https://github.com/user-attachments/assets/8c9ae017-7837-4abc-ae92-c1054c9ec350'
}
NPU_UNSUPPORTED_MODELS = {
"optimum-intel-internal-testing/tiny-random-internvl2",
}
DEFAULT_NPUW_PROPERTIES = {
"DEVICE_PROPERTIES": {"NPU": {"NPUW_DEVICES": "CPU", "NPUW_ONLINE_PIPELINE": "NONE", "MAX_PROMPT_LEN": 4096}}
}
NPU_SUPPORTED_MODELS = [id for id in MODEL_IDS if id not in NPU_UNSUPPORTED_MODELS and id not in VIDEO_MODEL_IDS]
def _setup_generation_config(
pipeline: VLMPipeline,
max_new_tokens: int = DEFAULT_MAX_NEW_TOKENS,
ignore_eos: bool = False,
set_eos_token: bool = True,
do_sample: bool = True,
) -> GenerationConfig:
generation_config = pipeline.get_generation_config()
generation_config.max_new_tokens = max_new_tokens
generation_config.do_sample = do_sample
if set_eos_token:
generation_config.set_eos_token_id(pipeline.get_tokenizer().get_eos_token_id())
if ignore_eos:
generation_config.ignore_eos = True
return generation_config
def _get_ov_model(model_id: str) -> str:
if model_id in {"optimum-intel-internal-testing/tiny-random-phi-4-multimodal", "qnguyen3/nanoLLaVA"}:
pytest.skip("ValueError: The current version of Transformers does not allow for the export of the model. Maximum required is 4.53.3, got: 4.55.4")
if "optimum-intel-internal-testing/tiny-random-phi3-vision" == model_id:
pytest.xfail("AttributeError: 'DynamicCache' object has no attribute 'get_usable_length'. Ticket CVS-175110")
if "optimum-intel-internal-testing/tiny-random-MiniCPM-o-2_6" == model_id and is_transformers_version(
">", "4.51.3"
):
pytest.skip(
"ValueError: The current version of Transformers does not allow for the export of the model. Maximum supported version is 4.51.3"
)
ov_cache_converted_dir = get_ov_cache_converted_models_dir()
dir_name = str(model_id).replace(os.sep, "_")
model_dir = ov_cache_converted_dir / dir_name
manager = AtomicDownloadManager(model_dir)
if manager.is_complete() or (model_dir / "openvino_language_model.xml").exists():
return model_dir
def convert_to_temp(temp_dir: Path) -> None:
align_with_optimum_cli = {"padding_side": "left", "truncation_side": "left"}
processor = retry_request(
lambda: transformers.AutoProcessor.from_pretrained(
model_id,
trust_remote_code=True,
**align_with_optimum_cli,
)
)
model = retry_request(
lambda: OVModelForVisualCausalLM.from_pretrained(
model_id,
compile=False,
device="CPU",
export=True,
load_in_8bit=False,
trust_remote_code=model_id in {
"optimum-intel-internal-testing/tiny-random-minicpmv-2_6",
"optimum-intel-internal-testing/tiny-random-internvl2",
"optimum-intel-internal-testing/tiny-random-phi3-vision",
"optimum-intel-internal-testing/tiny-random-phi-4-multimodal",
"qnguyen3/nanoLLaVA",
"optimum-intel-internal-testing/tiny-random-MiniCPM-o-2_6",
},
)
)
if model.config.model_type == "llava-qwen2":
tokenizer = transformers.AutoTokenizer.from_pretrained(model_id, trust_remote_code=True)
# For tiny-random-internvl2 processor is actually tokenizer
elif isinstance(processor, transformers.Qwen2TokenizerFast):
tokenizer = processor
processor = transformers.AutoImageProcessor.from_pretrained(
model_id, trust_remote_code=True
)
else:
tokenizer = processor.tokenizer
if tokenizer.chat_template is None:
tokenizer.chat_template = processor.chat_template
tokenizer.save_pretrained(temp_dir)
ov_tokenizer, ov_detokenizer = openvino_tokenizers.convert_tokenizer(
tokenizer, with_detokenizer=True
)
openvino.save_model(ov_tokenizer, temp_dir / "openvino_tokenizer.xml")
openvino.save_model(ov_detokenizer, temp_dir / "openvino_detokenizer.xml")
if tokenizer.chat_template is not None and model.config.model_type == "phi3_v":
# It seems that tiny-random-phi3-vision is saved incorrectly. That line works this around.
processor.chat_template = tokenizer.chat_template
processor.audio_tokenizer = None
processor.save_pretrained(temp_dir)
model.save_pretrained(temp_dir)
manager.execute(convert_to_temp)
return model_dir
# On macOS, transformers<4.52 is required, but this causes gemma3 to fail
GEMMA3_MACOS_XFAIL_REASON = "gemma3 not supported on macOS with older transformers"
@pytest.fixture(scope="module")
def ov_pipe_model(request: pytest.FixtureRequest) -> VlmModelInfo:
ov_model, ov_backend = request.param
if sys.platform == "darwin" and "gemma3" in ov_model:
pytest.xfail(GEMMA3_MACOS_XFAIL_REASON)
models_path = _get_ov_model(ov_model)
pipeline = VLMPipeline(models_path, "CPU", ATTENTION_BACKEND=ov_backend)
return VlmModelInfo(
ov_model,
ov_backend,
IMAGE_TAG_GENERATOR_BY_MODEL.get(ov_model, lambda idx: ""),
VIDEO_TAG_GENERATOR_BY_MODEL.get(ov_model, lambda idx: ""),
RESOLUTION_BY_MODEL.get(ov_model, DEFAULT_RESOLUTION),
pipeline
)
parametrize_all_models = pytest.mark.parametrize(
"ov_pipe_model",
[(m, b) for m in MODEL_IDS for b in ATTENTION_BACKEND],
ids=lambda p: f"{p[0]}/{p[1]}",
indirect=["ov_pipe_model"],
)
parametrize_all_models_with_video = pytest.mark.parametrize(
"ov_pipe_model",
[(m, b) for m in VIDEO_MODEL_IDS for b in ATTENTION_BACKEND],
ids=lambda p: f"{p[0]}/{p[1]}",
indirect=["ov_pipe_model"],
)
parametrize_one_model_sdpa = pytest.mark.parametrize(
"ov_pipe_model",
[(MODEL_IDS[0], "SDPA")],
ids=lambda p: f"{p[0]}/{p[1]}",
indirect=["ov_pipe_model"],
)
parametrize_one_model_pa = pytest.mark.parametrize(
"ov_pipe_model",
[(MODEL_IDS[0], "PA")],
ids=lambda p: f"{p[0]}/{p[1]}",
indirect=["ov_pipe_model"],
)
parametrize_one_model_backends = pytest.mark.parametrize(
"ov_pipe_model",
[(MODEL_IDS[0], b) for b in ATTENTION_BACKEND],
ids=lambda p: f"{p[0]}/{p[1]}",
indirect=["ov_pipe_model"],
)
def _dict_to_sorted_tuple(d):
if isinstance(d, dict):
return tuple([(key, _dict_to_sorted_tuple(value)) for key, value in sorted(d.items())])
return d
def _sorted_tuple_to_dict(t):
if isinstance(t, tuple):
return {key: _sorted_tuple_to_dict(value) for key, value in t}
return t
@pytest.fixture(scope="module")
def ov_npu_pipe_model(request: pytest.FixtureRequest) -> VlmModelInfo:
ov_model, config = request.param
if sys.platform == "darwin" and "gemma3" in ov_model:
pytest.xfail(GEMMA3_MACOS_XFAIL_REASON)
models_path = _get_ov_model(ov_model)
pipeline = VLMPipeline(models_path, "NPU", config=_sorted_tuple_to_dict(config))
return VlmModelInfo(
ov_model,
"SDPA",
IMAGE_TAG_GENERATOR_BY_MODEL.get(ov_model, lambda idx: ""),
VIDEO_TAG_GENERATOR_BY_MODEL.get(ov_model, lambda idx: ""),
RESOLUTION_BY_MODEL.get(ov_model, DEFAULT_RESOLUTION),
pipeline,
)
def _parametrize_npu_models(models: str | list[str], config: dict | None = None, config_name: str | None = None):
if isinstance(models, str):
models = [models]
assert (config is None and config_name is None) or (config is not None and config_name is not None)
if config is not None:
config = _dict_to_sorted_tuple(config)
params = [(model, config) for model in models]
return pytest.mark.parametrize(
"ov_npu_pipe_model",
params,
ids=lambda p: f"{p[0]}/{config_name}",
indirect=["ov_npu_pipe_model"],
)
parametrize_all_models_npu = _parametrize_npu_models(
NPU_SUPPORTED_MODELS, DEFAULT_NPUW_PROPERTIES, "DEFAULT_NPUW_PROPERTIES"
)
parametrize_one_model_npu = _parametrize_npu_models(
NPU_SUPPORTED_MODELS[0], DEFAULT_NPUW_PROPERTIES, "DEFAULT_NPUW_PROPERTIES"
)
@pytest.fixture(scope="module")
def ov_continious_batching_pipe() -> ContinuousBatchingPipeline:
models_path = _get_ov_model(MODEL_IDS[0])
return ContinuousBatchingPipeline(models_path, SchedulerConfig(), "CPU")
@pytest.fixture(scope="module")
def ov_continious_batching_pipe_gemma() -> ContinuousBatchingPipeline:
models_path = _get_ov_model(MODEL_IDS[8])
return ContinuousBatchingPipeline(models_path, SchedulerConfig(), "CPU")
def download_image(link: str) -> PIL.Image:
return PIL.Image.open(requests.get(link, stream=True).raw).convert("RGB")
def from_cache_or_download(pytestconfig: pytest.Config, link: str, file_name: str):
def implementation():
try:
image_path = pytestconfig.cache.mkdir("images") / file_name
except AttributeError:
# Cache is disabled with -p no:cacheprovider
return download_image(link)
if image_path.exists():
image: PIL.Image = PIL.Image.open(image_path)
else:
image = download_image(link)
image.save(image_path)
return image
return retry(implementation, PIL.UnidentifiedImageError)
@pytest.fixture(scope="module")
def cat_image(pytestconfig: pytest.Config):
return from_cache_or_download(pytestconfig, TEST_IMAGE_URLS['cat'], "cat.jpg")
def resize_video(video, shape):
video_resized = []
for frame in video:
pil_image = PIL.Image.fromarray(frame)
resized = pil_image.resize(shape)
video_resized.append(np.array(resized))
return np.array(video_resized)
@pytest.fixture(scope="module")
def synthetic_video(pytestconfig):
# TODO: use real video
car_url = "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/tasks/car.jpg"
image = from_cache_or_download(pytestconfig, car_url, "car.jpg")
# make 10 frames
total_frames = 10
frames = []
frames.append(np.array(image))
shift = 3
for i in range(1, total_frames):
new_frame = np.zeros(np.array(image).shape, np.array(image).dtype)
width, height = image.size
for x in range(0, width):
for y in range(0, height):
# shift previous frame
new_frame[y, x] = frames[i-1][y, (x - shift + width) % width]
frames.append(new_frame)
return frames
@pytest.fixture(scope="module")
def synthetic_video_32x32(synthetic_video):
return resize_video(synthetic_video, (32, 32))
@pytest.fixture(scope="module")
def cat_image_448x448(cat_image):
return cat_image.resize((448, 448))
@pytest.fixture(scope="module")
def cat_image_384x384(cat_image):
return cat_image.resize((384, 384))
@pytest.fixture(scope="module")
def cat_image_336x336(cat_image):
return cat_image.resize((336, 336))
@pytest.fixture(scope="module")
def cat_image_32x32(cat_image):
return cat_image.resize((32, 32))
@pytest.fixture(scope="module")
def cat_tensor(cat_image) -> openvino.Tensor:
return openvino.Tensor(cat_image)
@pytest.fixture(scope="module")
def car_tensor(pytestconfig: pytest.Config) -> openvino.Tensor:
return openvino.Tensor(from_cache_or_download(pytestconfig, TEST_IMAGE_URLS['car'], "car.jpg"))
@pytest.fixture(scope="module")
def synthetic_video_32x32_tensor(synthetic_video_32x32):
return openvino.Tensor(synthetic_video_32x32)
@pytest.fixture(scope="module")
def handwritten_tensor(pytestconfig: pytest.Config) -> openvino.Tensor:
return openvino.Tensor(from_cache_or_download(pytestconfig, TEST_IMAGE_URLS['handwritten'], "handwritten.png"))
@pytest.fixture(scope="function", params=[
pytest.param([], id="no_images"),
pytest.param(["cat_tensor"], id="single_image"),
pytest.param(["cat_tensor", "handwritten_tensor", "car_tensor"], id="multiple_images"),
])
def test_images(request: pytest.FixtureRequest):
return [request.getfixturevalue(image) for image in request.param]
@parametrize_all_models
def test_vlm_pipeline(ov_pipe_model: VlmModelInfo, test_images: list[openvino.Tensor]):
ov_pipe = ov_pipe_model.pipeline
result_from_streamer = []
def streamer(word: str) -> bool:
nonlocal result_from_streamer
result_from_streamer.append(word)
return False
generation_config = _setup_generation_config(ov_pipe)
res = ov_pipe.generate(
PROMPTS[0],
images=test_images,
generation_config=generation_config,
streamer=streamer,
)
assert res.texts[0] == "".join(result_from_streamer)
@parametrize_one_model_sdpa
def test_vlm_readonly_image_tensor(ov_pipe_model: VlmModelInfo, cat_image_32x32):
ov_pipe = ov_pipe_model.pipeline
generation_config = _setup_generation_config(ov_pipe, max_new_tokens=5)
image_array = np.array(cat_image_32x32, dtype=np.uint8)
image_array.flags.writeable = False
readonly_image_tensor = openvino.Tensor(image_array)
ov_pipe.generate(
PROMPTS[0],
images=[readonly_image_tensor],
generation_config=generation_config,
)
@pytest.mark.parametrize(
"config",
[
pytest.param(get_greedy(), id="greedy"),
pytest.param(get_beam_search(), id="beam_search"),
]
)
@parametrize_one_model_pa
def test_vlm_continuous_batching_generate_vs_add_request(
ov_pipe_model: VlmModelInfo,
ov_continious_batching_pipe: ContinuousBatchingPipeline,
config: GenerationConfig,
request: pytest.FixtureRequest,
cat_tensor: openvino.Tensor
):
ov_pipe = ov_pipe_model.pipeline
generation_config = config
generation_config.max_new_tokens = DEFAULT_MAX_NEW_TOKENS
image_links_list = [[], [cat_tensor]]
if ov_pipe_model.model_id in VIDEO_MODEL_IDS:
synthetic_video_32x32_tensor = request.getfixturevalue("synthetic_video_32x32_tensor")
images_list = [[], [cat_tensor], [cat_tensor]]
videos_list = [[synthetic_video_32x32_tensor], [synthetic_video_32x32_tensor], []]
else:
images_list = [[], [cat_tensor]]
videos_list = [[], []]
res_generate = []
for idx, images in enumerate(images_list):
videos = videos_list[idx]
res_generate.append(
ov_pipe.generate(
PROMPTS[0],
images=images,
videos=videos,
generation_config=generation_config,
)
)
tokenizer = ov_continious_batching_pipe.get_tokenizer()
for idx, images in enumerate(images_list):
videos = videos_list[idx]
handle = ov_continious_batching_pipe.add_request(
idx,
PROMPTS[0],
images=images,
videos=videos,
generation_config=generation_config,
)
while handle.get_status() != GenerationStatus.FINISHED:
ov_continious_batching_pipe.step()
outputs = handle.read_all()
for out_idx, output in enumerate(outputs):
text = tokenizer.decode(output.generated_ids)
assert text == res_generate[idx].texts[out_idx]
assert abs(output.score - res_generate[idx].scores[out_idx]) < DEFAULT_SCORE_EPSILON
assert (
output.finish_reason == GenerationFinishReason.STOP
or output.finish_reason == GenerationFinishReason.LENGTH
)
@pytest.mark.parametrize(
"config",
[
pytest.param(get_greedy(), id="greedy"),
pytest.param(get_beam_search(), id="beam_search"),
]
)
def test_vlm_continuous_batching_generate_vs_add_request_for_gemma(
ov_continious_batching_pipe_gemma: ContinuousBatchingPipeline,
config: GenerationConfig,
cat_tensor: openvino.Tensor,
):
ov_cb_pipe = ov_continious_batching_pipe_gemma
image_links_list = [[], [cat_tensor]]
tokenizer = ov_cb_pipe.get_tokenizer()
for idx, images in enumerate(image_links_list):
handle = ov_cb_pipe.add_request(
idx, PROMPTS[0], images, config
)
while handle.get_status() != GenerationStatus.FINISHED:
ov_cb_pipe.step()
outputs = handle.read_all()
for output in outputs:
text = tokenizer.decode(output.generated_ids)
assert len(output.generated_ids) > 0, f"Should generate at least one token"
assert text.strip() != "", f"Decoded text should not be empty"
assert (
output.finish_reason == GenerationFinishReason.STOP
or output.finish_reason == GenerationFinishReason.LENGTH
)
@pytest.mark.parametrize(
"config",
[
pytest.param(get_greedy(), id="greedy"),
pytest.param(get_beam_search(), id="beam_search"),
]
)
@parametrize_one_model_sdpa
def test_vlm_continuous_batching_vs_stateful(
ov_pipe_model: VlmModelInfo,
ov_continious_batching_pipe: ContinuousBatchingPipeline,
config: GenerationConfig,
cat_tensor: openvino.Tensor,
):
ov_pipe = ov_pipe_model.pipeline
generation_config = config
generation_config.max_new_tokens = 25
image_links_list = [[], [cat_tensor]]
res_cb = []
for images in image_links_list:
res_cb.append(
ov_continious_batching_pipe.generate(
[PROMPTS[0]], images=[images], generation_config=[generation_config]
)
)
for idx, images in enumerate(image_links_list):
res_stateful = ov_pipe.generate(
PROMPTS[0], images=images, generation_config=generation_config
)
for out_idx, text in enumerate(res_stateful.texts):
assert text == res_cb[idx][0].texts[out_idx]
assert (
abs(res_stateful.scores[out_idx] - res_cb[idx][0].scores[out_idx]) < DEFAULT_SCORE_EPSILON
)
@parametrize_one_model_sdpa
def test_vlm_continuous_batching_vs_stateful_chat_history(
ov_pipe_model: VlmModelInfo,
ov_continious_batching_pipe: ContinuousBatchingPipeline,
cat_tensor: openvino.Tensor,
car_tensor: openvino.Tensor,
):
ov_pipe = ov_pipe_model.pipeline
generation_config = get_greedy()
image_links_list = [[cat_tensor], [car_tensor]]
histories_batch = 2
histories_cb = []
histories_stateful = []
for i in range(histories_batch):
histories_cb.append(ChatHistory())
histories_stateful.append(ChatHistory())
# Continuous batching generation
results_cb = []
for images in image_links_list:
for i in range(histories_batch):
histories_cb[i].append({"role": "user", "content": PROMPTS[i]})
results = ov_continious_batching_pipe.generate(
histories_cb,
images=[images for _ in range(histories_batch)],
generation_config=[generation_config for _ in range(histories_batch)],
)
for i in range(histories_batch):
histories_cb[i].append({"role": "assistant", "content": results[i].texts[0]})
results_cb.append(results)
# Stateful generation + comparison
for i in range(histories_batch):
for q_i, images in enumerate(image_links_list):
histories_stateful[i].append({"role": "user", "content": PROMPTS[i]})
result_stateful = ov_pipe.generate(
histories_stateful[i], images=images, generation_config=generation_config
)
histories_stateful[i].append({"role": "assistant", "content": result_stateful.texts[0]})
for out_idx, text in enumerate(result_stateful.texts):
assert text == results_cb[q_i][i].texts[out_idx]
assert abs(result_stateful.scores[out_idx] - results_cb[q_i][i].scores[out_idx]) < DEFAULT_SCORE_EPSILON
@pytest.fixture(scope="module", params=[
pytest.param([[], []], id="generation with text input only"),
pytest.param(
[[], ["cat_tensor", "car_tensor", "handwritten_tensor"], []],
id="combination of generations with text input and text + image input, empty image first"
),
pytest.param(
[["cat_tensor", "car_tensor", "handwritten_tensor"], ["cat_tensor"]],
id="generation with text + image input"
),
pytest.param(
[["cat_tensor", "car_tensor", "handwritten_tensor"], [], ["cat_tensor"]],
id="combination of generations with text input and text + image input, image input first"
),
])
def iteration_images(request) -> list[list[PIL.Image]]:
return [[request.getfixturevalue(image) for image in bundle] for bundle in request.param]
@pytest.fixture(scope="module", params=[
pytest.param(
[[[], [], []], [[], [ "synthetic_video_32x32_tensor"], []]],
id="Video on second iteration"
),
pytest.param(
[[["cat_tensor"], [], []], [["synthetic_video_32x32_tensor"], [], ["synthetic_video_32x32_tensor"]]],
id="Image + video on first iteration, image on third iteration"
),
pytest.param(
[[["cat_tensor", "car_tensor", "handwritten_tensor"], []], [["synthetic_video_32x32_tensor", "synthetic_video_32x32_tensor"], ["synthetic_video_32x32_tensor"]]],
id="3 images + 2 videos on first iteration, video on second iteration"
),
])
def iteration_images_and_videos(request):
params = []
for param in request.param:
params.append([[request.getfixturevalue(image) for image in bundle] for bundle in param])
return params
@parametrize_all_models
@pytest.mark.parametrize("system_message", ["", "You are a helpful assistant."])
def test_vlm_pipeline_chat(
ov_pipe_model: VlmModelInfo,
system_message: str,
iteration_images: list[list[PIL.Image]],
):
ov_pipe = ov_pipe_model.pipeline
def streamer(word: str) -> bool:
nonlocal result_from_streamer
result_from_streamer.append(word)
return False
generation_config = _setup_generation_config(ov_pipe)
ov_pipe.start_chat(system_message)
images = iteration_images[0]
result_from_streamer = []
res = ov_pipe.generate(
PROMPTS[0],
images=images,
generation_config=generation_config,
streamer=streamer,
)
assert res.texts[0] == "".join(result_from_streamer)
for image_set in iteration_images[1:]:
result_from_streamer = []
res = ov_pipe.generate(
PROMPTS[1],
images=image_set,
generation_config=generation_config,
streamer=streamer,
)
assert res.texts[0] == "".join(result_from_streamer)
ov_pipe.finish_chat()
@parametrize_all_models
def test_vlm_pipeline_start_chat_vs_chat_history(
ov_pipe_model: VlmModelInfo,
iteration_images: list[list[PIL.Image]],
):
ov_pipe = ov_pipe_model.pipeline
generation_config = _setup_generation_config(ov_pipe, do_sample=False)
prompts_with_images = [
(PROMPTS[0], iteration_images[0]),
*[(PROMPTS[1], image_set) for image_set in iteration_images[1:]],
]
# Collect chat_history results
answers_chat_history = []
history = ChatHistory()
for prompt, images in prompts_with_images:
history.append({"role": "user", "content": prompt})
messages_before = history.get_messages()
res = ov_pipe.generate(
history,
images=images,
generation_config=generation_config,
)
messages_after = history.get_messages()
assert messages_before == messages_after, "ChatHistory messages should not be mutated after generate."
answer = res.texts[0]
history.append({"role": "assistant", "content": answer})
answers_chat_history.append(answer)
# Collect start_chat results
answers_start_chat = []
ov_pipe.start_chat()
for prompt, images in prompts_with_images:
res = ov_pipe.generate(
prompt,
images=images,
generation_config=generation_config,
)
answers_start_chat.append(res.texts[0])
ov_pipe.finish_chat()
for i, (answer_start_chat, answer_chat_history) in enumerate(zip(answers_start_chat, answers_chat_history)):
assert answer_start_chat == answer_chat_history, (
f"Answer {i} does not match!\n"
f"answer_start_chat: {answer_start_chat}\n"
f"answer_chat_history: {answer_chat_history}"
)
@pytest.mark.parametrize(
"ov_pipe_model",
[
pytest.param(
("optimum-intel-internal-testing/tiny-random-qwen2.5-vl", "SDPA"),
id="qwen2.5-vl/SDPA",
),
],
indirect=["ov_pipe_model"],
)
def test_vlm_pipeline_chat_history_multipart_content(
ov_pipe_model: VlmModelInfo,
iteration_images: list[list[PIL.Image]],
):
ov_pipe = ov_pipe_model.pipeline
generation_config = _setup_generation_config(ov_pipe, do_sample=False)
prompts_with_images = [
(PROMPTS[0], iteration_images[0]),
*[(PROMPTS[1], image_set) for image_set in iteration_images[1:]],
]
# Collect chat_history results (baseline)
answers_chat_history = []
history = ChatHistory()
for prompt, images in prompts_with_images:
history.append({"role": "user", "content": prompt})
res = ov_pipe.generate(
history,
images=images,
generation_config=generation_config,
)
answer = res.texts[0]
history.append({"role": "assistant", "content": answer})
answers_chat_history.append(answer)
# Collect chat_history with multipart content (OpenAI-like) results
answers_chat_history_multipart_content = []
history_multipart_content = ChatHistory()
for prompt, images in prompts_with_images:
history_multipart_content.append(
{
"role": "user",
"content": [
*[{"type": "image"} for _ in images],
{"type": "text", "text": prompt},
],
}
)
res = ov_pipe.generate(
history_multipart_content,
images=images,
generation_config=generation_config,
)
answer = res.texts[0]
history_multipart_content.append({"role": "assistant", "content": answer})
answers_chat_history_multipart_content.append(answer)
for i, (answer_1, answer_2) in enumerate(zip(answers_chat_history, answers_chat_history_multipart_content)):
assert answer_1 == answer_2, (
f"Answer {i} does not match!\n"
f"answers_chat_history: {answer_1}\n"
f"answers_chat_history_multipart_content: {answer_2}"
)
@pytest.fixture(scope="module", params=[
pytest.param([[], []], id="generation with text input only"),
pytest.param(
[[], ["cat_tensor"], ["car_tensor"], ["handwritten_tensor"], []],
id="combination of generations with text input and text + image input, empty image first"
),
pytest.param(
[["cat_tensor"], ["car_tensor"], ["handwritten_tensor"]],
id="generation with text + image input"
),
pytest.param(
[["cat_tensor"], ["car_tensor"], [], ["handwritten_tensor"]],
id="combination of generations with text input and text + image input, image input first"
),
])
def iteration_images_npu(request):
return [[request.getfixturevalue(image) for image in bundle] for bundle in request.param]
@parametrize_all_models_npu
@pytest.mark.parametrize("system_message", ["", "You are a helpful assistant."])
@pytest.mark.skipif(
sys.platform == "darwin" or platform.machine() in ["aarch64", "arm64", "ARM64"],
reason="NPU plugin is available only on Linux and Windows x86_64",
)
def test_vlm_pipeline_chat_npu(ov_npu_pipe_model: VlmModelInfo, system_message, iteration_images_npu):
def run_chat(ov_pipe, system_message, iteration_images):
result_from_streamer = []
def streamer(word: str) -> bool:
result_from_streamer.append(word)
return False
generation_config = ov_pipe.get_generation_config()
generation_config.max_new_tokens = 30
generation_config.set_eos_token_id(ov_pipe.get_tokenizer().get_eos_token_id())
ov_pipe.start_chat(system_message)
for i, image_set in enumerate(iteration_images):
result_from_streamer = []
res = ov_pipe.generate(
PROMPTS[i % len(PROMPTS)],
images=image_set,
generation_config=generation_config,
streamer=streamer,
)
assert res.texts[0] == "".join(result_from_streamer)
ov_pipe.finish_chat()
npu_pipe = ov_npu_pipe_model.pipeline
run_chat(npu_pipe, system_message, iteration_images_npu)