-
Notifications
You must be signed in to change notification settings - Fork 247
Expand file tree
/
Copy pathmodeling_visual_language.py
More file actions
4671 lines (4167 loc) · 210 KB
/
Copy pathmodeling_visual_language.py
File metadata and controls
4671 lines (4167 loc) · 210 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
import copy
import enum
import inspect
import logging
import math
import os
import warnings
from abc import abstractmethod
from dataclasses import dataclass
from pathlib import Path
from typing import TYPE_CHECKING, Any, Dict, List, Optional, Tuple, Union
import numpy as np
import openvino
import openvino as ov
import torch
from huggingface_hub import hf_hub_download
from huggingface_hub.constants import HUGGINGFACE_HUB_CACHE
from openvino._offline_transformations import apply_moc_transformations, compress_model_transformation
from transformers import (
AutoConfig,
AutoImageProcessor,
GenerationConfig,
GenerationMixin,
PretrainedConfig,
PreTrainedTokenizer,
)
from transformers.modeling_outputs import BaseModelOutputWithPooling
from transformers.models.qwen2_5_vl.modeling_qwen2_5_vl import Qwen2_5_VLModel
from transformers.models.qwen2_vl.modeling_qwen2_vl import Qwen2VLModel, VisionRotaryEmbedding
from transformers.models.qwen3_vl.modeling_qwen3_vl import (
Qwen3VLModel,
Qwen3VLVisionModel,
Qwen3VLVisionRotaryEmbedding,
)
from transformers.utils import ModelOutput
from optimum.exporters.openvino import main_export
from optimum.exporters.openvino.stateful import ensure_stateful_is_available, model_has_input_output_name
from optimum.exporters.openvino.utils import save_config
from optimum.intel.openvino.configuration import OVConfig, OVQuantizationConfigBase, OVWeightQuantizationConfig
from optimum.intel.openvino.modeling_base import OVBaseModel, OVModelPart
from optimum.intel.openvino.modeling_decoder import CausalLMOutputWithPast, OVModelForCausalLM
from optimum.intel.openvino.utils import (
OV_LANGUAGE_MODEL_NAME,
OV_TEXT_EMBEDDINGS_MODEL_NAME,
OV_VISION_EMBEDDINGS_MODEL_NAME,
TemporaryDirectory,
classproperty,
)
from optimum.intel.utils.import_utils import is_transformers_version
if is_transformers_version(">=", "4.46.0"):
from transformers import AutoModelForImageTextToText
transformers_auto_class = AutoModelForImageTextToText
else:
from transformers import AutoModelForVision2Seq
transformers_auto_class = AutoModelForVision2Seq
if TYPE_CHECKING:
from PIL.Image import Image
from transformers.image_utils import VideoInput
logger = logging.getLogger(__name__)
core = ov.Core()
class InputMode(enum.Enum):
LANGUAGE = 0
VISION = 1
SPEECH = 2
VISION_SPEECH = 3
class OVModelWithEmbedForCausalLM(OVModelForCausalLM):
def __init__(
self,
model: ov.Model,
text_embeds_model: ov.Model,
config: PretrainedConfig = None,
device: str = "CPU",
dynamic_shapes: bool = None,
ov_config: Optional[Dict[str, str]] = None,
model_save_dir: Optional[Union[str, Path, TemporaryDirectory]] = None,
quantization_config: Optional[Union[OVWeightQuantizationConfig, Dict]] = None,
**kwargs,
):
self.model = model
self.text_emb_model = text_embeds_model
self.request = None
self.text_emb_request = None
compile_only = kwargs.get("compile_only", False)
if compile_only:
self.text_emb_request = self.text_emb_model
self.request = self.model.create_infer_request()
super().__init__(
model=model,
config=config,
device=device,
dynamic_shapes=dynamic_shapes,
ov_config=ov_config,
model_save_dir=model_save_dir,
quantization_config=quantization_config,
**kwargs,
)
@property
def _ov_model_names(self) -> List[str]:
return ["model", "text_emb_model"]
def compile(self):
if self.request is None:
logger.info(f"Compiling the Language model to {self._device} ...")
super().compile()
self._compile_text_emb()
def _compile_text_emb(self):
if self.text_emb_request is None:
logger.info(f"Compiling the Text embeddings model to {self._device} ...")
if self._compile_only:
self.text_emb_request = self.text_emb_model
else:
logger.info(f"Compiling the Text embeddings model to {self._device} ...")
self.text_emb_request = self._compile_model(
self.text_emb_model, self._device, self.ov_config, self.model_save_dir
)
def clear_requests(self):
if self._compile_only:
raise ValueError(
"`clear_requests()` is not supported with `compile_only` mode, please initialize model without this option"
)
self.request = None
self.text_emb_request = None
def embed_tokens(self, input_ids: torch.LongTensor):
self._compile_text_emb()
res = self.text_emb_request(input_ids, share_inputs=True)
return res[0]
def prepare_inputs(
self,
input_ids: torch.LongTensor,
attention_mask: Optional[torch.LongTensor] = None,
past_key_values: Optional[Tuple[Tuple[torch.FloatTensor]]] = None,
position_ids: Optional[torch.LongTensor] = None,
inputs_embeds: Optional[torch.FloatTensor] = None,
token_type_ids: Optional[torch.LongTensor] = None,
visual_pos_masks: Optional[torch.FloatTensor] = None,
deepstack_visual_embeds: Optional[torch.FloatTensor] = None,
**kwargs,
):
batch_size = input_ids.shape[0] if input_ids is not None else inputs_embeds.shape[0]
inputs = {}
# past_key_values are not used explicitly, instead they are handled inside the model
if past_key_values is None:
# This is the first iteration in a sequence, reset all states
if self.request is not None:
self.request.reset_state()
# Set initial value for the next beam_idx input that will be used at the current iteration
# and will be optionally updated by _reorder_cache at the next iterations if beam_search is used
self.next_beam_idx = np.arange(batch_size, dtype=int)
self._past_length = 0
past_len = self._get_past_length(past_key_values)
if inputs_embeds is None:
inputs_embeds = self.embed_tokens(input_ids if past_key_values is None else input_ids[:, -1:])
if hasattr(self.config, "scale_emb"):
inputs_embeds = inputs_embeds * self.config.scale_emb
inputs["inputs_embeds"] = inputs_embeds
# Add the attention_mask inputs when needed
if "attention_mask" in self.input_names or "position_ids" in self.input_names:
if attention_mask is not None:
attention_mask = attention_mask.cpu().numpy()
else:
attention_mask = np.ones((inputs_embeds.shape[0], inputs_embeds.shape[1] + past_len), dtype=int)
if "attention_mask" in self.input_names:
inputs["attention_mask"] = attention_mask
if "position_ids" in self.input_names:
if position_ids is not None:
position_ids = position_ids.cpu().numpy()
else:
position_ids = np.cumsum(attention_mask, axis=1) - 1
position_ids[attention_mask == 0] = 1
if past_len:
position_ids = position_ids[:, -inputs_embeds.shape[1] :]
if (self.config.model_type in ["qwen2_vl", "qwen2_5_vl", "qwen3_vl"]) and position_ids.ndim != 3:
position_ids = np.repeat(np.expand_dims(position_ids, 0), 3, axis=0)
inputs["position_ids"] = position_ids
if "visual_pos_masks" in self.input_names:
if visual_pos_masks is not None:
inputs["visual_pos_masks"] = visual_pos_masks
else:
inputs["visual_pos_masks"] = torch.zeros(1, 1, dtype=torch.bool)
if "deepstack_visual_embeds" in self.input_names:
if deepstack_visual_embeds is not None:
inputs["deepstack_visual_embeds"] = torch.Tensor(deepstack_visual_embeds)
else:
num_layers = len(self.config.vision_config.deepstack_visual_indexes)
emd_dim = self.config.text_config.hidden_size
inputs["deepstack_visual_embeds"] = torch.zeros((num_layers, 1, emd_dim), dtype=torch.float32)
if "token_type_ids" in self.input_names:
if token_type_ids is None:
token_type_ids = np.zeros(inputs_embeds.shape[:2], dtype=int)
inputs["token_type_ids"] = token_type_ids
if "beam_idx" in self.input_names:
inputs["beam_idx"] = (
self.next_beam_idx if self.next_beam_idx is not None else np.arange(batch_size, dtype=int)
)
return inputs
def forward(
self,
input_ids: torch.LongTensor,
attention_mask: Optional[torch.LongTensor] = None,
past_key_values: Optional[Tuple[Tuple[torch.FloatTensor]]] = None,
position_ids: Optional[torch.LongTensor] = None,
inputs_embeds: Optional[torch.LongTensor] = None,
visual_pos_masks: Optional[torch.FloatTensor] = None,
deepstack_visual_embeds: Optional[torch.FloatTensor] = None,
**kwargs,
):
self.compile()
inputs = self.prepare_inputs(
input_ids=input_ids,
attention_mask=attention_mask,
past_key_values=past_key_values,
position_ids=position_ids,
inputs_embeds=inputs_embeds,
visual_pos_masks=visual_pos_masks,
deepstack_visual_embeds=deepstack_visual_embeds,
**kwargs,
)
# Run inference
self.request.start_async(inputs, share_inputs=True)
self.request.wait()
logits = self.request.get_tensor("logits").data
logits = torch.from_numpy(logits).clone().to(self.device)
past_key_values = ((),)
self._past_length += inputs["inputs_embeds"].shape[1]
return CausalLMOutputWithPast(logits=logits, past_key_values=past_key_values)
class OVVisionEmbedding(OVModelPart):
_model_name = "vision_embeddings"
def __init__(self, model: ov.Model, parent_model: OVBaseModel) -> None:
super().__init__(model, parent_model, model_name=self._model_name)
self.output_dtypes = {key.get_any_name(): key.get_element_type().get_type_name() for key in self.model.outputs}
self.output_names = {key.get_any_name(): idx for idx, key in enumerate(self.model.outputs)}
self.input_names = {key.get_any_name(): idx for idx, key in enumerate(self.model.inputs)}
self.hidden_states_output_names = []
if len(self.model.outputs) > 2:
self.hidden_states_output_names = [
key.get_any_name() for key in self.model.outputs[2:] if "hidden_states" in key.get_any_name()
]
self.input_names = {key.get_any_name(): idx for idx, key in enumerate(self.model.inputs)}
if model_has_input_output_name(self.model, "images"):
self._main_input = "images"
elif model_has_input_output_name(self.model, "hidden_states"):
self._main_input = "hidden_states"
else:
self._main_input = "pixel_values"
def forward(self, pixel_values, **kwargs):
self.compile()
inputs = {self._main_input: pixel_values}
if len(self.input_names) > 1:
for name in self.input_names:
if name in kwargs:
inputs[name] = kwargs[name]
result = self.request(inputs)
last_hidden_state = result[0]
hidden_states = None
pooler_out = None
if len(result) > 1:
pooler_out = result[1]
if self.hidden_states_output_names:
hidden_states = []
for out in self.hidden_states_output_names:
hidden_states.append(result[out])
return BaseModelOutputWithPooling(
pooler_output=pooler_out, last_hidden_state=last_hidden_state, hidden_states=hidden_states
)
class OVResampler(OVModelPart):
_model_name = "resampler"
def __init__(self, model: ov.Model, parent_model: OVBaseModel) -> None:
super().__init__(model, parent_model, model_name=self._model_name)
self.output_dtypes = {key.get_any_name(): key.get_element_type().get_type_name() for key in self.model.outputs}
self.output_names = {key.get_any_name(): idx for idx, key in enumerate(self.model.outputs)}
def forward(self, image_feature, pos_embed, key_padding_mask):
self.compile()
result = self.request(
{"image_feature": image_feature, "pos_embed": pos_embed, "key_padding_mask": key_padding_mask}
)[0]
return result
class OVVisionProjection(OVModelPart):
_model_name = "vision_projection"
def forward(self, img_features):
self.compile()
return self.request(img_features)[0]
class OVVisionResampler(OVVisionProjection):
_model_name = "vision_resampler"
class OVMultiModalProjector(OVVisionProjection):
_model_name = "multi_modal_projector"
class OVAudioEmbeddings(OVModelPart):
_model_name = "audio_embeddings"
def forward(self, audio_signal):
self.compile()
return self.request(audio_signal)[0]
class OVAudioEncoder(OVModelPart):
_model_name = "audio_encoder"
def forward(self, audio_feature, audio_mask):
self.compile()
return self.request({"audio_feature": audio_feature, "audio_mask": audio_mask})[0]
MODEL_PARTS_CLS_MAPPING = {
"resampler": OVResampler,
"language_model": OVModelWithEmbedForCausalLM,
"vision_embeddings": OVVisionEmbedding,
"vision_projection": OVVisionProjection,
"vision_resampler": OVVisionResampler,
"multi_modal_projector": OVMultiModalProjector,
"vision_embeddings_merger": OVVisionEmbedding,
"vision_embeddings_pos": OVVisionProjection,
"audio_embeddings": OVAudioEmbeddings,
"audio_forward_embeddings": OVAudioEmbeddings,
"audio_encoder": OVAudioEncoder,
"audio_vision_projection": OVAudioEmbeddings,
"audio_speech_projection": OVAudioEmbeddings,
}
class OVModelForVisualCausalLM(OVBaseModel, GenerationMixin):
export_feature = "image-text-to-text"
additional_parts = []
auto_model_class = transformers_auto_class
@classproperty
def _all_ov_model_paths(cls) -> Dict[str, str]:
model_paths = {
"lm_model": OV_LANGUAGE_MODEL_NAME,
"text_embeddings_model": OV_TEXT_EMBEDDINGS_MODEL_NAME,
"vision_embeddings_model": OV_VISION_EMBEDDINGS_MODEL_NAME,
}
for part in cls.additional_parts:
model_paths[f"{part}_model"] = f"openvino_{part}_model.xml"
return model_paths
def __init__(
self,
language_model: ov.Model,
text_embeddings: ov.Model,
vision_embeddings: ov.Model,
config: PretrainedConfig = None,
device: str = "CPU",
dynamic_shapes: bool = None,
ov_config: Optional[Dict[str, str]] = None,
model_save_dir: Optional[Union[str, Path, TemporaryDirectory]] = None,
quantization_config: Union[OVWeightQuantizationConfig, Dict] = None,
**kwargs,
):
if dynamic_shapes is not None:
logger.warning(
f"`dynamic_shapes` was set to {dynamic_shapes}, but this value will be ignored as only dynamic shapes are supported."
)
self.is_dynamic = True
self.config = config
self.use_cache = kwargs.get("use_cache", True)
self.model_save_dir = model_save_dir
self._device = device.upper()
self.ov_config = {} if ov_config is None else {**ov_config}
self.preprocessors = kwargs.get("preprocessors", [])
self._supports_cache_class = False
self.main_input_name = "input_ids"
self._compile_only = kwargs.get("compile_only", False)
for part in self.additional_parts:
setattr(self, f"{part}_model", kwargs.get(part))
enable_compilation = kwargs.get("compile", True)
self.generation_config = kwargs.get("generation_config", GenerationConfig.from_model_config(config))
self._openvino_config = None
if quantization_config:
self._openvino_config = OVConfig(quantization_config=quantization_config)
self._set_ov_config_parameters()
self.language_model = OVModelWithEmbedForCausalLM(
language_model,
text_embeddings,
config=config,
device=device,
ov_config=ov_config,
model_save_dir=model_save_dir,
quantization_config=quantization_config,
compile=self._compile_only or enable_compilation,
compile_only=self._compile_only,
)
self.vision_embeddings = OVVisionEmbedding(vision_embeddings, self)
for part in self.additional_parts:
model_part = getattr(self, f"{part}_model", None)
if model_part is not None:
model_part = MODEL_PARTS_CLS_MAPPING[part](model_part, self)
setattr(self, part, model_part)
if enable_compilation and not self._compile_only:
self.compile()
# Avoid warnings when creating a transformers pipeline
AutoConfig.register(self.base_model_prefix, AutoConfig)
self.auto_model_class.register(AutoConfig, self.__class__)
def clear_requests(self):
if self._compile_only:
raise ValueError(
"`clear_requests()` is not supported with `compile_only` mode, please initialize model without this option"
)
for component in self.components.values():
component.clear_requests()
def compile(self):
for component in self.components.values():
component.compile()
def _save_config(self, save_directory):
"""
Saves a model configuration into a directory, so that it can be re-loaded using the
[`from_pretrained`] class method.
"""
save_config(self.config, save_directory)
@classmethod
def _from_pretrained(
cls,
model_id: Union[str, Path],
config: PretrainedConfig,
token: Optional[Union[bool, str]] = None,
revision: Optional[str] = None,
force_download: bool = False,
cache_dir: str = HUGGINGFACE_HUB_CACHE,
local_files_only: bool = False,
load_in_8bit: bool = False,
quantization_config: Union[OVWeightQuantizationConfig, Dict] = None,
trust_remote_code: bool = False,
**kwargs,
):
"""
Loads a model and its configuration file from a directory or the HF Hub.
Arguments:
model_id (`str` or `Path`):
The directory from which to load the model.
Can be either:
- The model id of a pretrained model hosted inside a model repo on huggingface.co.
- The path to a directory containing the model weights.
token (Optional[Union[bool, str]], defaults to `None`):
The token to use as HTTP bearer authorization for remote files. If `True`, will use the token generated
when running `huggingface-cli login` (stored in `~/.huggingface`).
revision (`str`):
The specific model version to use. It can be a branch name, a tag name, or a commit id.
force_download (`bool`, *optional*, defaults to `False`):
Whether or not to force the (re-)download of the model weights and configuration files, overriding the
cached versions if they exist.
cache_dir (`Union[str, Path]`, *optional*):
The path to a directory in which a downloaded pretrained model configuration should be cached if the
standard cache should not be used.
encoder_file_name(`str`, *optional*):
The encoder model file name. Overwrites the default file name openvino_encoder_model.xml and allows one to
load the encoder model with a different name.
decoder_file_name(`str`, *optional*):
The decoder model file name. Overwrites the default file name openvino_decoder_model.xml and allows one to
load the decoder model with a different name.
decoder_with_past_file_name(`str`, *optional*):
The decoder with past key values model file name overwriting the default file name
openvino_decoder_with_past_model.xml, allowing to load the decoder model with a different name.
local_files_only(`bool`, *optional*, defaults to `False`):
Whether or not to only look at local files (i.e., do not try to download the model).
trust_remote_code (`bool`, *optional*, defaults to `False`):
Whether to trust remote code when loading model tokenizer/processor during quantization.
"""
model_cls = MODEL_TYPE_TO_CLS_MAPPING[config.model_type]
model_file_names = model_cls._all_ov_model_paths.copy()
for k in tuple(model_file_names):
model_file_names[f"{k}_bin"] = model_file_names[k].replace(".xml", ".bin")
compile_only = kwargs.get("compile_only", False)
if os.path.isdir(model_id):
# Load model from a local directory
model_save_dir = Path(model_id)
file_names = {k: os.path.join(model_id, model_file_names[k]) for k in model_file_names}
else:
file_names = {}
for name, file_name in model_file_names.items():
model_cache_path = hf_hub_download(
repo_id=model_id,
filename=file_name,
token=token,
revision=revision,
cache_dir=cache_dir,
force_download=force_download,
local_files_only=local_files_only,
)
file_names[name] = model_cache_path
model_save_dir = Path(model_cache_path).parent
if not compile_only:
language_model = model_cls.load_model(file_names["lm_model"])
text_embeddings = model_cls.load_model(file_names["text_embeddings_model"])
vision_embeddings = model_cls.load_model(file_names["vision_embeddings_model"])
for part in model_cls.additional_parts:
kwargs[part] = model_cls.load_model(file_names[f"{part}_model"])
else:
language_model = model_cls._compile_model(
file_names["lm_model"],
kwargs.get("device", "CPU"),
kwargs.get("ov_config"),
model_save_dir,
)
text_embeddings = model_cls._compile_model(
file_names["text_embeddings_model"],
kwargs.get("device", "CPU"),
kwargs.get("ov_config"),
model_save_dir,
)
vision_embeddings = model_cls._compile_model(
file_names["vision_embeddings_model"],
kwargs.get("device", "CPU"),
kwargs.get("ov_config"),
model_save_dir,
)
for part in model_cls.additional_parts:
kwargs[part] = model_cls._compile_model(
file_names[f"{part}_model"],
kwargs.get("device", "CPU"),
kwargs.get("ov_config"),
model_save_dir,
)
try:
generation_config = GenerationConfig.from_pretrained(
model_id,
token=token,
revision=revision,
cache_dir=cache_dir,
force_download=force_download,
local_files_only=local_files_only,
)
kwargs["generation_config"] = generation_config
except Exception:
pass
quantization_config = quantization_config or (OVWeightQuantizationConfig(bits=8) if load_in_8bit else None)
compile_model = kwargs.pop("compile", True)
model = model_cls(
language_model=language_model,
text_embeddings=text_embeddings,
vision_embeddings=vision_embeddings,
config=config,
model_save_dir=model_save_dir,
quantization_config=quantization_config,
compile=compile_model and not quantization_config,
**kwargs,
)
if quantization_config:
if hasattr(config, "name_or_path"):
model_id = config.name_or_path
else:
logger.warning(
"`model_id` could not be determined from the config. In the case there are default quantization "
"configurations for this model, they will not be applied."
)
quantization_config = cls._resolve_default_quantization_config(model_id, quantization_config)
model._apply_quantization(quantization_config, compile_only, compile_model, model_id, trust_remote_code)
return model
@classmethod
def _export(
cls,
model_id: str,
config: PretrainedConfig,
token: Optional[Union[bool, str]] = None,
revision: Optional[str] = None,
force_download: bool = False,
cache_dir: str = HUGGINGFACE_HUB_CACHE,
subfolder: str = "",
local_files_only: bool = False,
task: Optional[str] = None,
use_cache: bool = True,
trust_remote_code: bool = False,
load_in_8bit: Optional[bool] = None,
quantization_config: Union[OVWeightQuantizationConfig, Dict] = None,
**kwargs,
):
compile_only = kwargs.pop("compile_only", False)
if compile_only:
logger.warning(
"`compile_only` mode will be disabled because it does not support model export."
"Please provide openvino model obtained using optimum-cli or saved on disk using `save_pretrained`"
)
compile_only = False
save_dir = TemporaryDirectory()
save_dir_path = Path(save_dir.name)
# This attribute is needed to keep one reference on the temporary directory, since garbage collecting
# would end-up removing the directory containing the underlying OpenVINO model
cls._model_save_dir_tempdirectory_instance = save_dir
if task is None:
task = cls.export_feature
# If load_in_8bit and quantization_config not specified then ov_config is set to None and will be set by default in convert depending on the model size
if load_in_8bit is None and not quantization_config:
ov_config = None
else:
# Export in fp32 if compression won't be applied later
ov_config = OVConfig(dtype="fp32" if load_in_8bit is False else "auto")
stateful = kwargs.pop("stateful", ensure_stateful_is_available(warn=False) and use_cache)
variant = kwargs.pop("variant", None)
main_export(
model_name_or_path=model_id,
output=save_dir_path,
task=task,
subfolder=subfolder,
revision=revision,
cache_dir=cache_dir,
token=token,
local_files_only=local_files_only,
force_download=force_download,
trust_remote_code=trust_remote_code,
ov_config=ov_config,
stateful=stateful,
variant=variant,
)
name_or_path = config.name_or_path
config = AutoConfig.from_pretrained(save_dir_path, trust_remote_code=trust_remote_code)
# Keep the original name_or_path to be able to resolve default quantization config later
config.name_or_path = name_or_path
return cls._from_pretrained(
model_id=save_dir_path,
config=config,
use_cache=use_cache,
load_in_8bit=load_in_8bit,
quantization_config=quantization_config,
trust_remote_code=trust_remote_code,
**kwargs,
)
@property
def _component_names(self) -> List[str]:
base_components = ["language_model", "vision_embeddings"]
additional_components = [part for part in self.additional_parts if hasattr(self, part)]
return base_components + additional_components
@property
def _ov_model_names(self):
# TODO (nikita.savelyevv): Consider deprecating `lm_model` in favor of `language_model`
model_names = ["lm_model", "text_embeddings_model", "vision_embeddings_model"]
for part in self.additional_parts:
if hasattr(self, part):
model_names.append(part + "_model")
return model_names
@property
def ov_models(self) -> Dict[str, Union[openvino.Model, openvino.CompiledModel]]:
ov_models = {}
for ov_model_name in self._ov_model_names:
if ov_model_name == "lm_model":
ov_model = self.language_model.model
elif ov_model_name == "text_embeddings_model":
ov_model = self.language_model.text_emb_model
else:
ov_model = getattr(self, ov_model_name.replace("_model", "")).model
ov_models[ov_model_name] = ov_model
return ov_models
def reshape(self, batch_size: int, sequence_length: int):
logger.warning("Static shapes are not supported for causal language model.")
return self
def half(self):
"""
Converts all the model weights to FP16 for more efficient inference on GPU.
"""
for ov_model in self.ov_models.values():
apply_moc_transformations(ov_model, cf=False)
compress_model_transformation(ov_model)
return self
def to(self, device):
self.language_model.to(device)
super().to(device)
return self
def forward(
self,
input_ids,
pixel_values=None,
past_key_values=None,
inputs_embeds=None,
image_sizes=None,
attention_mask=None,
position_ids=None,
image_bound=None,
tgt_sizes=None,
pixel_values_videos=None,
image_grid_thw=None,
video_grid_thw=None,
rope_deltas=None,
images=None,
second_per_grid_ts=None,
token_type_ids=None,
pixel_attention_mask=None,
input_image_embeds: Optional[torch.FloatTensor] = None,
image_pixel_values: Optional[torch.FloatTensor] = None,
image_attention_mask=None,
audio_input_features: Optional[torch.FloatTensor] = None,
input_audio_embeds: Optional[torch.FloatTensor] = None,
audio_embed_sizes=None,
audio_attention_mask=None,
input_mode=None,
**kwargs,
):
if pixel_values is None:
pixel_values = images if images is not None else image_pixel_values
inputs_embeds, attention_mask, position_ids, *extra_outputs = self.get_multimodal_embeddings(
input_ids,
pixel_values,
inputs_embeds=inputs_embeds,
image_sizes=image_sizes,
attention_mask=attention_mask,
position_ids=position_ids,
past_key_values=past_key_values,
image_bound=image_bound,
tgt_sizes=tgt_sizes,
pixel_values_videos=pixel_values_videos,
image_grid_thw=image_grid_thw,
video_grid_thw=video_grid_thw,
rope_deltas=rope_deltas,
second_per_grid_ts=second_per_grid_ts,
pixel_attention_mask=pixel_attention_mask,
input_image_embeds=input_image_embeds,
image_attention_mask=image_attention_mask,
input_audio_embeds=input_audio_embeds if input_audio_embeds is not None else audio_input_features,
audio_embed_sizes=audio_embed_sizes,
audio_attention_mask=audio_attention_mask,
input_mode=input_mode,
**kwargs,
)
# Prepare additional kwargs for qwen3_vl models
additional_kwargs = {}
if self.config.model_type in ("qwen3_vl",) and extra_outputs:
additional_kwargs["visual_pos_masks"] = extra_outputs[0]
additional_kwargs["deepstack_visual_embeds"] = extra_outputs[1]
return self.language_model.forward(
input_ids=None,
inputs_embeds=inputs_embeds,
attention_mask=attention_mask,
position_ids=position_ids,
token_type_ids=token_type_ids,
past_key_values=past_key_values,
**additional_kwargs,
**kwargs,
)
def _reorder_cache(self, past_key_values, beam_idx):
return self.language_model._reorder_cache(past_key_values, beam_idx)
def get_vision_embeddings(self, pixel_values, **kwargs):
raise NotImplementedError
def get_text_embeddings(self, input_ids, **kwargs):
return self.language_model.embed_tokens(input_ids)
def merge_vision_text_embeddings(
self, vision_embeds, inputs_embeds, input_ids=None, attention_mask=None, position_ids=None, **kwargs
):
raise NotImplementedError
def get_multimodal_embeddings(
self, input_ids, pixel_values=None, attention_mask=None, position_ids=None, **kwargs
):
embeds_from_args = kwargs.pop("inputs_embeds", None)
inputs_embeds = (
embeds_from_args if embeds_from_args is not None else self.get_text_embeddings(input_ids, **kwargs)
)
if pixel_values is not None:
vision_embeds = self.get_vision_embeddings(pixel_values, input_ids=input_ids, **kwargs)
if vision_embeds is not None:
inputs_embeds, attention_mask, position_ids = self.merge_vision_text_embeddings(
vision_embeds,
inputs_embeds,
input_ids=input_ids,
attention_mask=attention_mask,
position_ids=position_ids,
**kwargs,
)
return inputs_embeds, attention_mask, position_ids
# Adopted from https://github.com/huggingface/transformers/blob/v4.44.2/src/transformers/models/llava/modeling_llava.py#L521
def prepare_inputs_for_generation(
self,
input_ids,
past_key_values=None,
inputs_embeds=None,
pixel_values=None,
image_sizes=None,
attention_mask=None,
**kwargs,
):
if past_key_values is not None:
past_length = self.language_model._get_past_length(past_key_values)
# Keep only the unprocessed tokens:
# 1 - If the length of the attention_mask exceeds the length of input_ids, then we are in a setting where
# some of the inputs are exclusively passed as part of the cache (e.g. when passing input_embeds as
# input)
if attention_mask is not None and past_length + 1 > input_ids.shape[1]:
input_discount = max(attention_mask.shape[1] - past_length, 1)
input_ids = input_ids[:, -input_discount:]
# 2 - If the past_length is smaller than input_ids', then input_ids holds all input tokens. We can discard
# input_ids based on the past_length.llava
elif past_length < input_ids.shape[1]:
input_ids = input_ids[:, past_length:]
# 3 - Otherwise (past_length >= input_ids.shape[1]), let's assume input_ids only has unprocessed tokens.
elif getattr(self.config, "image_token_index", -1) in input_ids:
input_ids = input_ids[:, input_ids.shape[1] - 1 :]
position_ids = kwargs.get("position_ids", None)
if attention_mask is not None and position_ids is None:
position_ids = attention_mask.long().cumsum(-1) - 1
position_ids.masked_fill_(attention_mask == 0, 1)
# position_ids in Gemma3 are 1-indexed
if self.config.model_type == "gemma3":
position_ids += 1
if past_key_values is not None:
position_ids = position_ids[:, -input_ids.shape[1] :]
# if `inputs_embeds` are passed, we only want to use them in the 1st generation step
if inputs_embeds is not None and past_key_values is None:
model_inputs = {"inputs_embeds": inputs_embeds}
else:
model_inputs = {"input_ids": input_ids}
if pixel_values is None:
pixel_values = kwargs.get("input_image_embeds", kwargs.get("images", kwargs.get("image_pixel_values")))
model_inputs.update(
{
"position_ids": position_ids,
"past_key_values": past_key_values,
"use_cache": kwargs.get("use_cache"),
"attention_mask": attention_mask,
"pixel_values": pixel_values,
"image_sizes": image_sizes,
"image_bound": kwargs.get("image_bound"),
"tgt_sizes": kwargs.get("tgt_sizes"),
"pixel_values_videos": kwargs.get("pixel_values_videos"),
"image_grid_thw": kwargs.get("image_grid_thw"),
"video_grid_thw": kwargs.get("video_grid_thw"),
"token_type_ids": kwargs.get("token_type_ids"),
"pixel_attention_mask": kwargs.get("pixel_attention_mask"),
"image_attention_mask": kwargs.get("image_attention_mask"),
"input_audio_embeds": kwargs.get("input_audio_embeds", kwargs.get("audio_input_features")),
"audio_embed_sizes": kwargs.get("audio_embed_sizes"),
"input_mode": kwargs.get("input_mode"),
}
)
return model_inputs
def can_generate(self):
"""Returns True to validate the check that the model using `GenerationMixin.generate()` can indeed generate."""
return True
@staticmethod
@abstractmethod
def preprocess_inputs(
text: str,
image: Optional["Image"] = None,
processor: Optional[AutoImageProcessor] = None,
tokenizer: Optional[PreTrainedTokenizer] = None,
config: Optional[PretrainedConfig] = None,
video: Optional["VideoInput"] = None,
audio: Optional[np.ndarray] = None,
):
"""
Preprocess input instruction and an image.
"""
# modified from https://github.com/huggingface/transformers/blob/v4.55.0/src/transformers/generation/utils.py#L1992
def _prepare_cache_for_generation(self, *args, **kwargs):
"""
This function is used to prepare the cache : when calling `generate` before the first inference, an instance of `DynamicCache` will be created.
For OVModel, we don't want model_kwargs to be updated before generation.
"""
return
def _preprocess_quantization_config(
self,
quantization_config: OVQuantizationConfigBase,
model_name_or_path: str,
) -> OVQuantizationConfigBase:
if quantization_config.processor is None or quantization_config.tokenizer is None:
quantization_config = quantization_config.clone()
if quantization_config.processor is None:
potential_processor_id = (
self.config.mm_vision_tower if isinstance(self, _OVNanoLlavaForCausalLM) else model_name_or_path
)
quantization_config.processor = potential_processor_id
if quantization_config.tokenizer is None:
quantization_config.tokenizer = model_name_or_path
return quantization_config
class _OVLlavaForCausalLM(OVModelForVisualCausalLM):
def __init__(
self,
language_model: ov.Model,
text_embeddings: ov.Model,
vision_embeddings: ov.Model,
config: PretrainedConfig = None,
device: str = "CPU",
dynamic_shapes: bool = None,
ov_config: Optional[Dict[str, str]] = None,
model_save_dir: Optional[Union[str, Path, TemporaryDirectory]] = None,
quantization_config: Union[OVWeightQuantizationConfig, Dict] = None,
**kwargs,
):
super().__init__(
language_model=language_model,
text_embeddings=text_embeddings,
vision_embeddings=vision_embeddings,
config=config,
device=device,
dynamic_shapes=dynamic_shapes,
ov_config=ov_config,
model_save_dir=model_save_dir,
quantization_config=quantization_config,
**kwargs,
)
self._support_new_processing = hasattr(self.config, "image_seq_length")
def get_vision_embeddings(self, pixel_values, input_ids=None, **kwargs):
if input_ids is not None and input_ids.shape[1] == 1:
return None
if not isinstance(pixel_values, list):
image_features = self.vision_embeddings(pixel_values).last_hidden_state
else:
image_features = []
for patch in pixel_values:
if isinstance(patch, list):
patch_feats = []
for patch_value in patch:
patch_feats.append(self.vision_embeddings(np.expand_dims(patch_value, 0)).last_hidden_state)
patch_feats = np.concatenate(patch_feats, axis=1)
else:
patch_feats = self.vision_embeddings(patch).last_hidden_state
image_features.append(patch_feats)
image_features = np.concatenate(image_features, 0)