-
Notifications
You must be signed in to change notification settings - Fork 213
Expand file tree
/
Copy pathmodel_configs.py
More file actions
5453 lines (4638 loc) · 206 KB
/
model_configs.py
File metadata and controls
5453 lines (4638 loc) · 206 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 2024 The HuggingFace Team. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import enum
import logging
from copy import deepcopy
from typing import TYPE_CHECKING, Any, Dict, List, Optional, Tuple, Union
from transformers import AutoConfig, PretrainedConfig, PreTrainedModel
from optimum.exporters.onnx.config import OnnxConfig, TextDecoderOnnxConfig, TextDecoderWithPositionIdsOnnxConfig
from optimum.exporters.onnx.model_configs import (
AlbertOnnxConfig,
ASTOnnxConfig,
BartOnnxConfig,
BeitOnnxConfig,
BertOnnxConfig,
BlenderbotOnnxConfig,
BlenderbotSmallOnnxConfig,
BloomOnnxConfig,
CamembertOnnxConfig,
CLIPOnnxConfig,
CLIPTextOnnxConfig,
CLIPTextWithProjectionOnnxConfig,
CLIPVisionModelOnnxConfig,
CodeGenOnnxConfig,
ConvBertOnnxConfig,
ConvNextOnnxConfig,
Data2VecAudioOnnxConfig,
Data2VecTextOnnxConfig,
Data2VecVisionOnnxConfig,
DebertaOnnxConfig,
DebertaV2OnnxConfig,
DeiTOnnxConfig,
DistilBertOnnxConfig,
ElectraOnnxConfig,
EsmOnnxConfig,
FalconOnnxConfig,
FlaubertOnnxConfig,
GemmaOnnxConfig,
GPT2OnnxConfig,
GPTBigCodeOnnxConfig,
GPTJOnnxConfig,
GPTNeoOnnxConfig,
GPTNeoXOnnxConfig,
HubertOnnxConfig,
IBertOnnxConfig,
LevitOnnxConfig,
LlamaOnnxConfig,
MarianOnnxConfig,
MistralOnnxConfig,
MobileBertOnnxConfig,
MobileNetV1OnnxConfig,
MobileNetV2OnnxConfig,
MobileViTOnnxConfig,
MPNetOnnxConfig,
MPTOnnxConfig,
NystromformerOnnxConfig,
Olmo2OnnxConfig,
OPTOnnxConfig,
PegasusOnnxConfig,
PerceiverOnnxConfig,
PhiOnnxConfig,
Pix2StructOnnxConfig,
PoolFormerOnnxConfig,
RemBertOnnxConfig,
ResNetOnnxConfig,
RobertaOnnxConfig,
RoFormerOnnxConfig,
SamOnnxConfig,
SegformerOnnxConfig,
SentenceTransformersTransformerOnnxConfig,
SEWDOnnxConfig,
SEWOnnxConfig,
SiglipOnnxConfig,
SiglipTextOnnxConfig,
SiglipTextWithProjectionOnnxConfig,
SpeechT5OnnxConfig,
SqueezeBertOnnxConfig,
SwinOnnxConfig,
T5OnnxConfig,
UNetOnnxConfig,
UniSpeechOnnxConfig,
UniSpeechSATOnnxConfig,
VaeDecoderOnnxConfig,
VaeEncoderOnnxConfig,
VisionEncoderDecoderOnnxConfig,
VisionOnnxConfig,
ViTOnnxConfig,
Wav2Vec2ConformerOnnxConfig,
Wav2Vec2OnnxConfig,
WavLMOnnxConfig,
WhisperOnnxConfig,
XLMOnnxConfig,
XLMRobertaOnnxConfig,
)
from optimum.exporters.onnx.model_patcher import ModelPatcher
from optimum.exporters.openvino.utils import ONNX_SUPPORTED_ARCHITECTURES
from optimum.exporters.tasks import TasksManager
from optimum.utils import DEFAULT_DUMMY_SHAPES
from optimum.utils.input_generators import (
DTYPE_MAPPER,
DummyInputGenerator,
DummyPastKeyValuesGenerator,
DummySeq2SeqDecoderTextInputGenerator,
DummySeq2SeqPastKeyValuesGenerator,
DummyTextInputGenerator,
DummyTimestepInputGenerator,
DummyVisionInputGenerator,
FalconDummyPastKeyValuesGenerator,
GemmaDummyPastKeyValuesGenerator,
MistralDummyPastKeyValuesGenerator,
)
from optimum.utils.normalized_config import (
NormalizedConfig,
NormalizedTextConfig,
NormalizedVisionConfig,
)
from ...intel.utils.import_utils import is_diffusers_available, is_diffusers_version, is_transformers_version
from .model_patcher import (
AfmoeModelPatcher,
AquilaModelPatcher,
ArcticModelPatcher,
BaichuanModelPatcher,
BigBirdPegasusModelPatcher,
BlenderbotModelPatcher,
BlenderbotSmallModelPatcher,
BloomModelPatcher,
ChatGLMModelPatcher,
CodeGenModelPatcher,
CommonImageEmbeddingsModelPatcher,
DBRXModelPatcher,
DeciLMModelPatcher,
DeepseekPatcher,
FalconModelPatcher,
FluxTransfromerModelPatcher,
Gemma2ModelPatcher,
Gemma3LMModelPatcher,
GptJModelPatcher,
GptNeoModelPatcher,
GptNeoxModelPatcher,
GptOssModelPatcher,
GraniteMoeHybridModelPatcher,
GraniteMoEModelPatcher,
IBertModelPatcher,
Idefics3ImageEmbeddingsModelPatcher,
InputEmbeddingPatcher,
InternLM2Patcher,
InternLMModelPatcher,
InternVL2ChatLangModelPatcher,
InternVLChatImageEmbeddingModelPatcher,
JaisModelPatcher,
Lfm2ModelPatcher,
Llama4ImageEmbeddingsModelPatcher,
Llama4TextModelPatcher,
LlavaImageEmbeddingModelPatcher,
LlavaNextVideoImageEmbeddingModelPatcher,
LlavaQwen2ImageEmbeddingsModelPatcher,
MairaImageEmbeddingModelPatcher,
MambaPatcher,
MarianModelPatcher,
MiniCPM3Patcher,
MiniCPMModelPatcher,
MiniCPMVImageEmbeddingsModelPatcher,
MiniCPMVResamplerModelPatcher,
MistralModelPatcher,
MixtralModelPatcher,
MPTModelPatcher,
OVDecoderModelPatcher,
OVSeq2SeqModelPatcher,
OVSpeechT5ModelPatcher,
PegasusModelPatcher,
PersimmonModelPatcher,
Phi3ModelPatcher,
Phi3VisionImageEmbeddingsPatcher,
Phi4MMAudioEncoderPatcher,
Phi4MMAudioForwardEmbeddingsPatcher,
Phi4MMLanguageModelPatcher,
Phi4MMVisionEmbeddingsPatcher,
PhiMoEModelPatcher,
Qwen2_5_VLVisionEmbMergerPatcher,
Qwen2MoEPatcher,
Qwen2VLLanguageModelPatcher,
Qwen2VLVisionEmbMergerPatcher,
Qwen3MoeModelPatcher,
Qwen3NextModelPatcher,
Qwen3VLLanguageModelPatcher,
Qwen3VLVisionEmbMergerPatcher,
QwenModelPatcher,
SanaTextEncoderModelPatcher,
XverseModelPatcher,
Zamba2ModelPatcher,
)
COMMON_TEXT_TASKS = [
"feature-extraction",
"fill-mask",
"multiple-choice",
"question-answering",
"text-classification",
"token-classification",
]
COMMON_TEXT_GENERATION_TASKS = [
"feature-extraction",
"feature-extraction-with-past",
"text-generation",
"text-generation-with-past",
]
COMMON_TEXT2TEXT_GENERATION_TASKS = [
*COMMON_TEXT_GENERATION_TASKS,
"text2text-generation",
"text2text-generation-with-past",
]
logger = logging.getLogger(__name__)
if TYPE_CHECKING:
from transformers.modeling_utils import PreTrainedModel # noqa: F811
def init_model_configs():
if "open_clip" not in TasksManager._LIBRARY_TO_SUPPORTED_MODEL_TYPES:
TasksManager._LIBRARY_TO_SUPPORTED_MODEL_TYPES["open_clip"] = {}
TasksManager._CUSTOM_CLASSES[("pt", "llava", "image-text-to-text")] = (
"transformers",
"LlavaForConditionalGeneration",
)
TasksManager._CUSTOM_CLASSES[("pt", "llava_next", "image-text-to-text")] = (
"transformers",
"LlavaNextForConditionalGeneration",
)
TasksManager._CUSTOM_CLASSES[("pt", "qwen2_vl", "image-text-to-text")] = (
"transformers",
"Qwen2VLForConditionalGeneration",
)
TasksManager._CUSTOM_CLASSES[("pt", "qwen2_5_vl", "image-text-to-text")] = (
"transformers",
"AutoModelForImageTextToText",
)
TasksManager._CUSTOM_CLASSES[("pt", "llava_next_video", "image-text-to-text")] = (
"transformers",
"AutoModelForVision2Seq",
)
TasksManager._CUSTOM_CLASSES[("pt", "gemma3", "image-text-to-text")] = (
"transformers",
"Gemma3ForConditionalGeneration",
)
TasksManager._CUSTOM_CLASSES[("pt", "idefics3", "image-text-to-text")] = (
"transformers",
"AutoModelForImageTextToText",
)
TasksManager._CUSTOM_CLASSES[("pt", "smolvlm", "image-text-to-text")] = (
"transformers",
"AutoModelForImageTextToText",
)
TasksManager._CUSTOM_CLASSES[("pt", "phi4mm", "image-text-to-text")] = ("transformers", "AutoModelForCausalLM")
TasksManager._CUSTOM_CLASSES[("pt", "phi4mm", "automatic-speech-recognition")] = (
"transformers",
"AutoModelForCausalLM",
)
TasksManager._CUSTOM_CLASSES[("pt", "phi4_multimodal", "image-text-to-text")] = (
"transformers",
"AutoModelForCausalLM",
)
TasksManager._CUSTOM_CLASSES[("pt", "phi4_multimodal", "automatic-speech-recognition")] = (
"transformers",
"AutoModelForCausalLM",
)
TasksManager._CUSTOM_CLASSES[("pt", "llama4", "image-text-to-text")] = (
"transformers",
"AutoModelForImageTextToText",
)
if is_diffusers_available() and "fill" not in TasksManager._DIFFUSERS_TASKS_TO_MODEL_LOADERS:
TasksManager._DIFFUSERS_TASKS_TO_MODEL_LOADERS["fill"] = "FluxFillPipeline"
TasksManager._DIFFUSERS_TASKS_TO_MODEL_MAPPINGS["fill"] = {"flux": "FluxFillPipeline"}
TasksManager._DIFFUSERS_TASKS_TO_MODEL_LOADERS["text-to-image"] = ("AutoPipelineForText2Image", "SanaPipeline")
TasksManager._DIFFUSERS_TASKS_TO_MODEL_MAPPINGS["text-to-image"]["sana"] = "SanaPipeline"
TasksManager._DIFFUSERS_TASKS_TO_MODEL_MAPPINGS["text-to-image"]["sana-sprint"] = "SanaSprintPipeline"
if is_diffusers_available() and "text-to-video" not in TasksManager._DIFFUSERS_TASKS_TO_MODEL_MAPPINGS:
TasksManager._DIFFUSERS_TASKS_TO_MODEL_MAPPINGS["text-to-video"] = {}
TasksManager._DIFFUSERS_TASKS_TO_MODEL_MAPPINGS["text-to-video"]["ltx-video"] = "LTXPipeline"
supported_model_types = [
"_SUPPORTED_MODEL_TYPE",
"_DIFFUSERS_SUPPORTED_MODEL_TYPE",
"_TIMM_SUPPORTED_MODEL_TYPE",
"_SENTENCE_TRANSFORMERS_SUPPORTED_MODEL_TYPE",
]
# TODO: remove once models from ONNX_SUPPORTED_ARCHITECTURES are deprecated (optimum-intel v1.29)
for supported_models_config in supported_model_types:
supported_models = getattr(TasksManager, supported_models_config)
for model, export_configs in supported_models.items():
# adding only the architectures that are already supported via optimum-onnx v0.1.0
if "onnx" not in export_configs or model not in ONNX_SUPPORTED_ARCHITECTURES:
continue
onnx_config = export_configs["onnx"]
supported_models[model]["openvino"] = deepcopy(onnx_config)
setattr(TasksManager, supported_models_config, supported_models)
init_model_configs()
register_in_tasks_manager = TasksManager.create_register("openvino", overwrite_existing=True)
@register_in_tasks_manager("baichuan", *["text-generation", "text-generation-with-past"], library_name="transformers")
class BaichaunOpenVINOConfig(TextDecoderWithPositionIdsOnnxConfig):
DEFAULT_ONNX_OPSET = 13
NORMALIZED_CONFIG_CLASS = NormalizedTextConfig.with_args(
num_layers="num_hidden_layers", num_attention_heads="num_attention_heads", hidden_size="hidden_size"
)
_MODEL_PATCHER = BaichuanModelPatcher
@register_in_tasks_manager(
"qwen2",
*[
"text-generation",
"text-generation-with-past",
"feature-extraction",
"feature-extraction-with-past",
"text-classification",
"token-classification",
],
library_name="transformers",
)
class Qwen2OpenVINOConfig(TextDecoderWithPositionIdsOnnxConfig):
DEFAULT_ONNX_OPSET = 14
DUMMY_INPUT_GENERATOR_CLASSES = (DummyTextInputGenerator, MistralDummyPastKeyValuesGenerator)
DUMMY_PKV_GENERATOR_CLASS = MistralDummyPastKeyValuesGenerator
NORMALIZED_CONFIG_CLASS = NormalizedTextConfig
_MODEL_PATCHER = OVDecoderModelPatcher
@register_in_tasks_manager("qwen2_moe", *["text-generation", "text-generation-with-past"], library_name="transformers")
class Qwen2MoEOpenVINOConfig(TextDecoderWithPositionIdsOnnxConfig):
DEFAULT_ONNX_OPSET = 14
DUMMY_INPUT_GENERATOR_CLASSES = (DummyTextInputGenerator, MistralDummyPastKeyValuesGenerator)
DUMMY_PKV_GENERATOR_CLASS = MistralDummyPastKeyValuesGenerator
NORMALIZED_CONFIG_CLASS = NormalizedTextConfig
_MODEL_PATCHER = Qwen2MoEPatcher
@register_in_tasks_manager(
"qwen3",
*[
"text-generation",
"text-generation-with-past",
"feature-extraction",
"feature-extraction-with-past",
"text-classification",
],
library_name="transformers",
)
class Qwen3OpenVINOConfig(TextDecoderWithPositionIdsOnnxConfig):
MIN_TRANSFORMERS_VERSION = "4.51.0"
DUMMY_INPUT_GENERATOR_CLASSES = (DummyTextInputGenerator, GemmaDummyPastKeyValuesGenerator)
DUMMY_PKV_GENERATOR_CLASS = GemmaDummyPastKeyValuesGenerator
NORMALIZED_CONFIG_CLASS = NormalizedTextConfig
_MODEL_PATCHER = OVDecoderModelPatcher
@property
def inputs(self) -> Dict[str, Dict[int, str]]:
if self.task in ["feature-extraction"]:
common_inputs = {
"input_ids": {0: "batch_size", 1: "sequence_length"},
"attention_mask": {0: "batch_size", 1: "sequence_length"},
}
else:
common_inputs = super().inputs
return common_inputs
class DummyQwen3VLLMInputGenerator(DummyTextInputGenerator):
SUPPORTED_INPUT_NAMES = (
"input_ids",
"attention_mask",
"token_type_ids",
"position_ids",
"visual_pos_masks",
"deepstack_visual_embeds",
)
def __init__(
self,
task: str,
normalized_config: NormalizedTextConfig,
batch_size: int = DEFAULT_DUMMY_SHAPES["batch_size"],
sequence_length: int = DEFAULT_DUMMY_SHAPES["sequence_length"],
num_choices: int = DEFAULT_DUMMY_SHAPES["num_choices"],
random_batch_size_range: Optional[Tuple[int, int]] = None,
random_sequence_length_range: Optional[Tuple[int, int]] = None,
random_num_choices_range: Optional[Tuple[int, int]] = None,
padding_side: str = "right",
**kwargs,
):
super().__init__(
task=task,
normalized_config=normalized_config,
batch_size=batch_size,
sequence_length=sequence_length,
num_choices=num_choices,
random_batch_size_range=random_batch_size_range,
random_sequence_length_range=random_sequence_length_range,
random_num_choices_range=random_num_choices_range,
padding_side=padding_side,
**kwargs,
)
self.embed_dim = normalized_config.hidden_size
self.num_layers = len(self.normalized_config.deepstack_visual_indexes)
def generate(
self,
input_name: str,
framework: str = "pt",
int_dtype: str = "int64",
float_dtype: str = "fp32",
bool_dtype: str = "bool",
):
if input_name == "deepstack_visual_embeds":
return self.random_float_tensor(
[self.num_layers, 2 * self.sequence_length, self.embed_dim], framework=framework, dtype=float_dtype
)
if input_name == "visual_pos_masks":
return self.constant_tensor(
shape=[self.batch_size, self.sequence_length],
framework=framework,
value=1,
dtype=DTYPE_MAPPER.pt(bool_dtype),
)
return super().generate(input_name, framework, int_dtype, float_dtype)
@register_in_tasks_manager(
"qwen3_vl_text",
*[
"text-generation",
"text-generation-with-past",
],
library_name="transformers",
)
class Qwen3VLTextOpenVINOConfig(TextDecoderWithPositionIdsOnnxConfig):
MIN_TRANSFORMERS_VERSION = "4.57.0"
DUMMY_INPUT_GENERATOR_CLASSES = (DummyQwen3VLLMInputGenerator, GemmaDummyPastKeyValuesGenerator)
DUMMY_PKV_GENERATOR_CLASS = GemmaDummyPastKeyValuesGenerator
NORMALIZED_CONFIG_CLASS = NormalizedTextConfig
_MODEL_PATCHER = OVDecoderModelPatcher
@property
def inputs(self) -> Dict[str, Dict[int, str]]:
common_inputs = super().inputs
common_inputs["visual_pos_masks"] = {0: "batch_size", 1: "sequence_length"}
common_inputs["deepstack_visual_embeds"] = {0: "num_layers", 1: "visual_seqlen"}
return common_inputs
@register_in_tasks_manager(
"qwen3_moe",
*["text-generation", "text-generation-with-past", "feature-extraction", "feature-extraction-with-past"],
library_name="transformers",
)
class Qwen3MoEOpenVINOConfig(Qwen3OpenVINOConfig):
_MODEL_PATCHER = Qwen3MoeModelPatcher
@register_in_tasks_manager("minicpm", *["text-generation", "text-generation-with-past"], library_name="transformers")
class MiniCPMOpenVINOConfig(TextDecoderWithPositionIdsOnnxConfig):
DEFAULT_ONNX_OPSET = 14
MAX_TRANSFORMERS_VERSION = "4.53.3"
DUMMY_INPUT_GENERATOR_CLASSES = (DummyTextInputGenerator, MistralDummyPastKeyValuesGenerator)
DUMMY_PKV_GENERATOR_CLASS = MistralDummyPastKeyValuesGenerator
NORMALIZED_CONFIG_CLASS = NormalizedTextConfig
_MODEL_PATCHER = MiniCPMModelPatcher
class OVMiniCPM3DummyPastKeyValuesGenerator(MistralDummyPastKeyValuesGenerator):
def __init__(
self,
task: str,
normalized_config: NormalizedTextConfig,
batch_size: int = DEFAULT_DUMMY_SHAPES["batch_size"],
sequence_length: int = DEFAULT_DUMMY_SHAPES["sequence_length"],
random_batch_size_range: Optional[Tuple[int, int]] = None,
random_sequence_length_range: Optional[Tuple[int, int]] = None,
**kwargs,
):
super().__init__(
task=task,
normalized_config=normalized_config,
batch_size=batch_size,
sequence_length=sequence_length,
random_batch_size_range=random_batch_size_range,
random_sequence_length_range=random_sequence_length_range,
**kwargs,
)
self.v_head_dim = getattr(normalized_config, "v_head_dim", self.hidden_size // self.num_attention_heads)
self.k_head_dim = normalized_config.qk_nope_head_dim + normalized_config.qk_rope_head_dim
def generate(self, input_name: str, framework: str = "pt", int_dtype: str = "int64", float_dtype: str = "fp32"):
v_shape = (
self.batch_size,
self.num_key_value_heads,
self.sequence_length,
self.v_head_dim,
)
k_shape = (self.batch_size, self.num_key_value_heads, self.sequence_length, self.k_head_dim)
return [
(
self.random_float_tensor(k_shape, framework=framework, dtype=float_dtype),
self.random_float_tensor(v_shape, framework=framework, dtype=float_dtype),
)
for _ in range(self.num_layers)
]
@register_in_tasks_manager("minicpm3", *["text-generation", "text-generation-with-past"], library_name="transformers")
class MiniCPM3OpenVINOConfig(TextDecoderWithPositionIdsOnnxConfig):
DEFAULT_ONNX_OPSET = 14
MAX_TRANSFORMERS_VERSION = "4.53.3"
DUMMY_INPUT_GENERATOR_CLASSES = (DummyTextInputGenerator, OVMiniCPM3DummyPastKeyValuesGenerator)
DUMMY_PKV_GENERATOR_CLASS = OVMiniCPM3DummyPastKeyValuesGenerator
NORMALIZED_CONFIG_CLASS = NormalizedTextConfig
_MODEL_PATCHER = MiniCPM3Patcher
@register_in_tasks_manager("stablelm", *["text-generation", "text-generation-with-past"], library_name="transformers")
class StableLMOpenVINOConfig(TextDecoderWithPositionIdsOnnxConfig):
DEFAULT_ONNX_OPSET = 14
DUMMY_INPUT_GENERATOR_CLASSES = (DummyTextInputGenerator, MistralDummyPastKeyValuesGenerator)
DUMMY_PKV_GENERATOR_CLASS = MistralDummyPastKeyValuesGenerator
NORMALIZED_CONFIG_CLASS = NormalizedTextConfig
_MODEL_PATCHER = OVDecoderModelPatcher
class ChatGLM2DummyPastKeyValuesGenerator(DummyPastKeyValuesGenerator):
def __init__(
self,
task: str,
normalized_config: NormalizedTextConfig,
batch_size: int = DEFAULT_DUMMY_SHAPES["batch_size"],
sequence_length: int = DEFAULT_DUMMY_SHAPES["sequence_length"],
random_batch_size_range: Optional[Tuple[int, int]] = None,
random_sequence_length_range: Optional[Tuple[int, int]] = None,
**kwargs,
):
super().__init__(
task=task,
normalized_config=normalized_config,
batch_size=batch_size,
sequence_length=sequence_length,
random_batch_size_range=random_batch_size_range,
random_sequence_length_range=random_sequence_length_range,
)
self.multi_query_group_num = normalized_config.multi_query_group_num
self.head_dim = normalized_config.kv_channels
self.standart_cache_layout = hasattr(normalized_config, "rope_ratio")
def generate(self, input_name: str, framework: str = "pt", int_dtype: str = "int64", float_dtype: str = "fp32"):
if not self.standart_cache_layout:
pkv_shape = (
self.sequence_length,
self.batch_size,
self.multi_query_group_num,
self.head_dim,
)
else:
pkv_shape = (
self.batch_size,
self.multi_query_group_num,
self.sequence_length,
self.head_dim,
)
return [
(
self.random_float_tensor(pkv_shape, framework=framework, dtype=float_dtype),
self.random_float_tensor(pkv_shape, framework=framework, dtype=float_dtype),
)
for _ in range(self.num_layers)
]
@register_in_tasks_manager("chatglm", *["text-generation", "text-generation-with-past"], library_name="transformers")
class ChatGLM2OpenVINOConfig(TextDecoderWithPositionIdsOnnxConfig):
NORMALIZED_CONFIG_CLASS = NormalizedTextConfig.with_args(vocab_size="padded_vocab_size", num_layers="num_layers")
DUMMY_INPUT_GENERATOR_CLASSES = (DummyTextInputGenerator, ChatGLM2DummyPastKeyValuesGenerator)
DUMMY_PKV_GENERATOR_CLASS = ChatGLM2DummyPastKeyValuesGenerator
_MODEL_PATCHER = ChatGLMModelPatcher
MAX_TRANSFORMERS_VERSION = "4.55.4"
def generate_dummy_inputs(self, framework: str = "pt", **kwargs):
dummy_inputs_generators = self._create_dummy_input_generator_classes(**kwargs)
dummy_inputs = {}
input_names = [key for key in self.inputs.keys() if not key.startswith("past_key_values")]
if self.use_past_in_inputs and self.use_cache_branch is not False:
input_names.append("past_key_values")
for input_name in input_names:
input_was_inserted = False
for dummy_input_gen in dummy_inputs_generators:
if dummy_input_gen.supports_input(input_name):
dummy_inputs[input_name] = self.overwrite_shape_and_generate_input(
dummy_input_gen,
input_name,
framework,
input_shapes=kwargs,
)
input_was_inserted = True
break
if not input_was_inserted:
raise RuntimeError(
f'Could not generate dummy input for "{input_name}". Try adding a proper dummy input generator to the model ONNX config.'
)
# refer to https://github.com/huggingface/optimum/pull/764
if (
self.use_past_in_inputs
and self.PAD_ATTENTION_MASK_TO_PAST
and self.use_cache_branch is not False
and "attention_mask" in dummy_inputs
):
# Obtain the past sequence length from the value instead of the key (Bloom). ChatGLM has seq_len in 0 dim instead of -2
seq_len_dim = 0 if not hasattr(self._normalized_config, "rope_ratio") else -2
past_present_length = (
dummy_inputs["input_ids"].shape[1] + dummy_inputs["past_key_values"][0][1].shape[seq_len_dim]
)
dummy_inputs["attention_mask"] = DummyInputGenerator.pad_input_on_dim(
dummy_inputs["attention_mask"],
desired_length=past_present_length,
dim=1,
dtype=dummy_inputs["attention_mask"].dtype,
)
return dummy_inputs
def add_past_key_values(self, inputs_or_outputs: Dict[str, Dict[int, str]], direction: str):
"""
Fills `input_or_outputs` mapping with past_key_values dynamic axes considering the direction.
Args:
inputs_or_outputs (`Dict[str, Dict[int, str]]`): The mapping to fill.
direction (`str`):
either "inputs" or "outputs", it specifies whether `input_or_outputs` is the input mapping or the
output mapping, this is important for axes naming.
"""
if direction not in ["inputs", "outputs"]:
raise ValueError(f'direction must either be "inputs" or "outputs", but {direction} was given')
if direction == "inputs":
decoder_sequence_name = "past_sequence_length"
name = "past_key_values"
else:
decoder_sequence_name = "past_sequence_length + present_length"
name = "present"
is_v4 = hasattr(self._normalized_config, "rope_ratio")
for i in range(self._normalized_config.num_layers):
inputs_or_outputs[f"{name}.{i}.key"] = (
{1: "batch_size", 0: decoder_sequence_name}
if not is_v4
else {0: "batch_size", 2: decoder_sequence_name}
)
inputs_or_outputs[f"{name}.{i}.value"] = (
{1: "batch_size", 0: decoder_sequence_name}
if not is_v4
else {0: "batch_size", 2: decoder_sequence_name}
)
@register_in_tasks_manager("mixtral", *["text-generation", "text-generation-with-past"], library_name="transformers")
class MixtralOpenVINOConfig(TextDecoderWithPositionIdsOnnxConfig):
# The ONNX export of this architecture needs the Trilu operator support, available since opset 14
DEFAULT_ONNX_OPSET = 14
DUMMY_INPUT_GENERATOR_CLASSES = (
MistralDummyPastKeyValuesGenerator,
) + TextDecoderOnnxConfig.DUMMY_INPUT_GENERATOR_CLASSES
DUMMY_PKV_GENERATOR_CLASS = MistralDummyPastKeyValuesGenerator
NORMALIZED_CONFIG_CLASS = NormalizedTextConfig.with_args(num_key_value_heads="num_key_value_heads", allow_new=True)
_MODEL_PATCHER = MixtralModelPatcher
@register_in_tasks_manager(
"gemma",
*[
"feature-extraction",
"feature-extraction-with-past",
"text-generation",
"text-generation-with-past",
"text-classification",
],
library_name="transformers",
)
class GemmaOpenVINOConfig(GemmaOnnxConfig):
_MODEL_PATCHER = OVDecoderModelPatcher
@property
def inputs(self) -> Dict[str, Dict[int, str]]:
# position_ids was removed from optimum-onnx's gemma config because
# it's not necessary (it's correctly generated inside the model)
# but openvino genai requires it to be present to work properly
inputs = super().inputs
if "position_ids" not in inputs:
inputs["position_ids"] = {0: "batch_size", 1: "sequence_length"}
return inputs
class Eagle3DummyGenerator(DummyInputGenerator):
"""
Dummy input generator for Eagle-3 speculative decoding.
This generator produces synthetic `hidden_states` tensors that mimic the
intermediate hidden-state outputs of a *main (target) model*, which are
required by the Eagle-3 draft model during speculative decoding.
"""
SUPPORTED_INPUT_NAMES = ("hidden_states",)
def __init__(
self,
task: str,
normalized_config: NormalizedTextConfig,
batch_size: int = DEFAULT_DUMMY_SHAPES["batch_size"],
sequence_length: int = DEFAULT_DUMMY_SHAPES["sequence_length"],
**kwargs,
):
self.batch_size = batch_size
self.sequence_length = sequence_length
self.hidden_size = normalized_config.hidden_size
def generate(self, input_name: str, framework: str = "pt", int_dtype: str = "int64", float_dtype: str = "fp32"):
# hidden_states is provided as a concatenation of three hidden-layer outputs from the main model
shape = (
self.batch_size,
self.sequence_length,
self.hidden_size * 3,
)
return self.random_float_tensor(shape, framework=framework, dtype=float_dtype)
@register_in_tasks_manager(
"llama",
*[
"feature-extraction",
"feature-extraction-with-past",
"text-generation",
"text-generation-with-past",
"text-classification",
],
library_name="transformers",
)
class LlamaOpenVINOConfig(LlamaOnnxConfig):
_MODEL_PATCHER = OVDecoderModelPatcher
def __init__(
self,
config: PretrainedConfig,
task: str = "feature-extraction",
int_dtype: str = "int64",
float_dtype: str = "fp32",
use_past: bool = False,
use_past_in_inputs: bool = False,
preprocessors: list[Any] | None = None,
):
super().__init__(
config=config,
task=task,
int_dtype=int_dtype,
float_dtype=float_dtype,
use_past=use_past,
use_past_in_inputs=use_past_in_inputs,
preprocessors=preprocessors,
)
archs = getattr(config, "architectures", None)
self.eagle3 = False
if isinstance(archs, list) and len(archs) > 0 and "eagle3" in archs[0].lower():
self.DUMMY_INPUT_GENERATOR_CLASSES += (Eagle3DummyGenerator,)
self.MIN_TRANSFORMERS_VERSION = "4.54.0"
self.eagle3 = True
@property
def inputs(self) -> Dict[str, Dict[int, str]]:
common_inputs = super().inputs
# Eagle3 model has additional conditional input
if self.eagle3:
common_inputs["hidden_states"] = {0: "batch_size", 1: "sequence_length", 2: "hidden_size"}
return common_inputs
@property
def outputs(self) -> Dict[str, Dict[int, str]]:
common_outputs = super().outputs
# d2t map for Eagle3 is required to map draft tokens to target model token
if self.eagle3:
common_outputs["d2t"] = {0: "vocab_size"}
return common_outputs
@register_in_tasks_manager(
"gpt_oss",
*[
"feature-extraction",
"feature-extraction-with-past",
"text-generation",
"text-generation-with-past",
"text-classification",
],
library_name="transformers",
)
class GptOssOpenVINOConfig(LlamaOpenVINOConfig):
DUMMY_INPUT_GENERATOR_CLASSES = (DummyTextInputGenerator, GemmaDummyPastKeyValuesGenerator)
DUMMY_PKV_GENERATOR_CLASS = GemmaDummyPastKeyValuesGenerator
MIN_TRANSFORMERS_VERSION = "4.55.1"
_MODEL_PATCHER = GptOssModelPatcher
@register_in_tasks_manager(
"bitnet",
*[
"text-generation",
"text-generation-with-past",
],
library_name="transformers",
)
class BitnetOpenVINOConfig(LlamaOnnxConfig):
MIN_TRANSFORMERS_VERSION = "4.52.1"
_MODEL_PATCHER = OVDecoderModelPatcher
@register_in_tasks_manager(
"exaone",
*[
"feature-extraction",
"feature-extraction-with-past",
"text-generation",
"text-generation-with-past",
"text-classification",
],
library_name="transformers",
)
class ExaoneOpenVINOConfig(LlamaOpenVINOConfig):
pass
@register_in_tasks_manager(
"exaone4",
*[
"text-generation",
"text-generation-with-past",
],
library_name="transformers",
)
class Exaone4OpenVINOConfig(LlamaOpenVINOConfig):
MIN_TRANSFORMERS_VERSION = "4.54.0"
@register_in_tasks_manager(
"arcee",
*[
"feature-extraction",
"feature-extraction-with-past",
"text-generation",
"text-generation-with-past",
"text-classification",
],
library_name="transformers",
)
class ArceeOpenVINOConfig(LlamaOpenVINOConfig):
MIN_TRANSFORMERS_VERSION = "4.53.0"
@register_in_tasks_manager(
"cohere2",
*[
"feature-extraction",
"feature-extraction-with-past",
"text-generation",
"text-generation-with-past",
"text-classification",
],
library_name="transformers",
)
class Cohere2OpenVINOConfig(LlamaOpenVINOConfig):
MIN_TRANSFORMERS_VERSION = "4.48.0"
class QwenDummyPastKeyValuesGenerator(DummyPastKeyValuesGenerator):
def __init__(
self,
task: str,
normalized_config: NormalizedTextConfig,
batch_size: int = DEFAULT_DUMMY_SHAPES["batch_size"],
sequence_length: int = DEFAULT_DUMMY_SHAPES["sequence_length"],
random_batch_size_range: Optional[Tuple[int, int]] = None,
random_sequence_length_range: Optional[Tuple[int, int]] = None,
**kwargs,
):
super().__init__(
task=task,
normalized_config=normalized_config,
batch_size=batch_size,
sequence_length=sequence_length,
random_batch_size_range=random_batch_size_range,
random_sequence_length_range=random_sequence_length_range,
)
self.kv_channels = normalized_config.kv_channels
def generate(self, input_name: str, framework: str = "pt", int_dtype: str = "int64", float_dtype: str = "fp32"):
past_key_shape = (self.batch_size, self.sequence_length, self.num_attention_heads, self.kv_channels)
past_value_shape = (self.batch_size, self.sequence_length, self.num_attention_heads, self.kv_channels)
return [
(
self.random_float_tensor(past_key_shape, framework=framework, dtype=float_dtype),
self.random_float_tensor(past_value_shape, framework=framework, dtype=float_dtype),
)
for _ in range(self.num_layers)
]
@register_in_tasks_manager("qwen", *["text-generation", "text-generation-with-past"])
class QwenOpenVINOConfig(TextDecoderWithPositionIdsOnnxConfig):
DEFAULT_ONNX_OPSET = 14
MAX_TRANSFORMERS_VERSION = "4.55.4"
NORMALIZED_CONFIG_CLASS = NormalizedTextConfig.with_args(
num_layers="num_hidden_layers", num_attention_heads="num_attention_heads", hidden_size="hidden_size"
)
DUMMY_INPUT_GENERATOR_CLASSES = (DummyTextInputGenerator, QwenDummyPastKeyValuesGenerator)
DUMMY_PKV_GENERATOR_CLASS = QwenDummyPastKeyValuesGenerator
_MODEL_PATCHER = QwenModelPatcher
def generate_dummy_inputs(self, framework: str = "pt", **kwargs):
dummy_inputs_generators = self._create_dummy_input_generator_classes(**kwargs)
dummy_inputs = {}
input_names = [key for key in self.inputs.keys() if not key.startswith("past_key_values")]
if self.use_past_in_inputs and self.use_cache_branch is not False:
input_names.append("past_key_values")
for input_name in input_names:
input_was_inserted = False
for dummy_input_gen in dummy_inputs_generators:
if dummy_input_gen.supports_input(input_name):
dummy_inputs[input_name] = self.overwrite_shape_and_generate_input(
dummy_input_gen,
input_name,
framework,
input_shapes=kwargs,
)
input_was_inserted = True
break
if not input_was_inserted:
raise RuntimeError(
f'Could not generate dummy input for "{input_name}". Try adding a proper dummy input generator to the model ONNX config.'
)
# refer to https://github.com/huggingface/optimum/pull/764
if (
self.use_past_in_inputs
and self.PAD_ATTENTION_MASK_TO_PAST
and self.use_cache_branch is not False
and "attention_mask" in dummy_inputs
):
# Obtain the past sequence length from the value instead of the key (Bloom). Qwen has seq_len in 1 dim instead of -2
past_present_length = dummy_inputs["input_ids"].shape[1] + dummy_inputs["past_key_values"][0][1].shape[1]
dummy_inputs["attention_mask"] = DummyInputGenerator.pad_input_on_dim(
dummy_inputs["attention_mask"],
desired_length=past_present_length,
dim=1,
dtype=dummy_inputs["attention_mask"].dtype,
)
return dummy_inputs
def add_past_key_values(self, inputs_or_outputs: Dict[str, Dict[int, str]], direction: str):
"""
Fills `input_or_outputs` mapping with past_key_values dynamic axes considering the direction.
Args:
inputs_or_outputs (`Dict[str, Dict[int, str]]`): The mapping to fill.