-
Notifications
You must be signed in to change notification settings - Fork 76
Expand file tree
/
Copy pathmodeling_auto.py
More file actions
4195 lines (3598 loc) · 174 KB
/
modeling_auto.py
File metadata and controls
4195 lines (3598 loc) · 174 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) Qualcomm Technologies, Inc. and/or its subsidiaries.
# SPDX-License-Identifier: BSD-3-Clause
#
# ----------------------------------------------------------------------------
import os
import warnings
from pathlib import Path
from time import perf_counter
from typing import List, Optional, Union
import numpy as np
import torch
import torch.nn as nn
from transformers import (
AutoImageProcessor,
AutoModel,
AutoModelForCausalLM,
AutoModelForCTC,
AutoModelForImageTextToText,
AutoModelForSequenceClassification,
AutoModelForSpeechSeq2Seq,
PreTrainedTokenizer,
PreTrainedTokenizerFast,
TextStreamer,
)
import QEfficient
from QEfficient.base.modeling_qeff import QEFFBaseModel
from QEfficient.base.onnx_transforms import FP16ClipTransform
from QEfficient.base.pytorch_transforms import SplitGateUpWeightsTransform
from QEfficient.generation.cloud_infer import QAICInferenceSession
from QEfficient.generation.text_generation_inference import (
CloudAI100ExecInfoNew,
PerfMetrics,
calculate_latency,
get_compilation_dims,
write_io_files,
)
from QEfficient.generation.vlm_generation import VisionLanguageGeneration
from QEfficient.transformers.modeling_utils import (
DYNAMIC_SEQ_LEN_SUPPORTED_MODEL_ARCH,
SPECIALIZED_DISAGG_SERVING_MODEL_ARCH,
_configure_proxy_for_model,
)
from QEfficient.transformers.models.pytorch_transforms import (
BlockedKVAttentionTransform,
CustomOpsTransform,
KVCacheExternalModuleMapperTransform,
KVCacheTransform,
PoolingTransform,
PrefillOnlyChunkedTransform,
PrefillOnlyTransform,
RevertPrefillKeepAttentionTransform,
RevertPrefillOnlyTransform,
SamplerTransform,
SpDTransform,
TextClassificationTransform,
VlmKVOffloadTransform,
VlmNoKVOffloadTransform,
)
from QEfficient.transformers.quantizers.auto import QEFF_AUTO_QUANTIZATION_CONFIG_MAPPING, with_replaced_quantizers
from QEfficient.transformers.quantizers.quant_transforms import (
AwqToMatmulNbitsTransform,
FP8DeQuantLinearToLinearTransform,
GPTQToMatmulNbitsTransform,
Mxfp4GptOssExpertDequantizeTransform,
)
from QEfficient.utils import (
constants,
get_padding_shape_from_config,
)
from QEfficient.utils.check_ccl_specializations import process_ccl_specializations
from QEfficient.utils.logging_utils import logger
from QEfficient.utils.sampler_utils import get_sampling_inputs_and_outputs
class QEFFTransformersBase(QEFFBaseModel):
"""
Base class for QEfficient wrappers around HuggingFace transformer models.
This class provides common functionality for loading, representing, and managing
HuggingFace models within the QEfficient framework. It serves as a parent
for specific model types like `AutoModel`, `AutoModelForCausalLM`, etc.
"""
_hf_auto_class: type
def __init__(self, model: nn.Module, **kwargs) -> None:
_configure_proxy_for_model(self, kwargs.pop("enable_proxy", False))
if (
hasattr(model, "config")
and hasattr(model.config, "quantization_config")
and not isinstance(model.config.quantization_config, tuple(QEFF_AUTO_QUANTIZATION_CONFIG_MAPPING.values()))
):
raise AssertionError("Please use `from_pretrained` method to load quantized models")
super().__init__(model, **kwargs)
def __repr__(self) -> str:
return self.__class__.__name__ + "\n" + self.model.__repr__()
@classmethod
@with_replaced_quantizers
def from_pretrained(cls, pretrained_model_name_or_path: str, *args, **kwargs):
"""
Load a QEfficient transformer model from a pretrained HuggingFace model or local path.
This is the recommended way to initialize any QEfficient transformer model.
The interface is similar to ``transformers.AutoModel.from_pretrained``.
Parameters
----------
pretrained_model_name_or_path : str
Model card name from HuggingFace or local path to model directory.
*args :
Positional arguments passed directly to `cls._hf_auto_class.from_pretrained`.
**kwargs :
Keyword arguments passed directly to `cls._hf_auto_class.from_pretrained`.
**Note:** `attn_implementation` and `low_cpu_mem_usage` are automatically set to "eager" and False respectively to ensure compatibility.
Returns
-------
QEFFTransformersBase
An instance of the specific QEFFAutoModel subclass, initialized with the pretrained weights.
"""
enable_proxy = kwargs.pop("enable_proxy", False)
if kwargs.get("attn_implementation", None) not in {None, "eager"}:
logger.warning('Updating attn_implementation="eager"')
if kwargs.get("low_cpu_mem_usage", None):
logger.warning("Updating low_cpu_mem_usage=False")
kwargs.update({"attn_implementation": "eager", "low_cpu_mem_usage": False})
model = cls._hf_auto_class.from_pretrained(pretrained_model_name_or_path, *args, **kwargs)
kwargs.update({"enable_proxy": enable_proxy} if enable_proxy else {})
return cls(model, pretrained_model_name_or_path=pretrained_model_name_or_path, **kwargs)
class MultimodalUtilityMixin:
"""
Mixin for multimodal models providing utilities like input auto-correction.
This mixin ensures that inputs to multimodal models conform to the expected
names, shapes, and dtypes defined by the model's `get_inputs_info` method.
"""
def __new__(cls, *args, **kwargs):
if cls is MultimodalUtilityMixin:
raise TypeError(f"only children of '{cls.__name__}' may be instantiated")
return object.__new__(cls)
def auto_correct_inputs(self, inputs):
"""
Validates and corrects model inputs to match expected specifications.
Checks if the provided inputs dictionary contains all required keys and
if the data types of the tensors match the model's specifications.
It then filters the input dictionary to only include expected inputs.
Parameters
----------
inputs : Dict[str, torch.Tensor]
A dictionary of input tensors, where keys are input names and values are `torch.Tensor` objects.
Returns
-------
Dict[str, torch.Tensor]
A filtered dictionary of input tensors that match the model's expected inputs.
Raises
------
RuntimeError
If any expected input is missing or has a mismatched data type.
"""
checked = True
inputs_info = self.model.get_inputs_info()
for valid_input_info in inputs_info:
if valid_input_info.name not in inputs:
checked = False
break
if inputs[valid_input_info.name].dtype != valid_input_info.datatype:
checked = False
break
if not checked:
err_str: str = (
"Expected following input names and shapes to be passed\n"
+ "\n".join([val.__repr__() for val in inputs_info])
+ "\ngot"
+ f"{[(k, v.shape, v.dtype) for k, v in inputs.items()]}"
)
raise RuntimeError(err_str)
return {k: v for k, v in inputs.items() if k in [iinfo.name for iinfo in inputs_info]}
class QEFFAutoModel(QEFFTransformersBase):
"""
QEfficient class for general transformer models from the HuggingFace hub (e.g., BERT, Sentence Transformers).
This class provides a unified interface for loading, exporting, compiling, and running
various encoder-only transformer models on Cloud AI 100 hardware. It supports pooling
for embedding extraction.
Example
-------
.. code-block:: python
from QEfficient import QEFFAutoModel
from transformers import AutoTokenizer
model = QEFFAutoModel.from_pretrained("sentence-transformers/all-MiniLM-L6-v2", pooling="mean")
model.compile(num_cores=16)
tokenizer = AutoTokenizer.from_pretrained("sentence-transformers/all-MiniLM-L6-v2")
inputs = tokenizer("My name is", return_tensors="pt")
output = model.generate(inputs)
print(output) # Output will be a dictionary containing extracted features.
"""
_hf_auto_class = AutoModel
_pytorch_transforms = [CustomOpsTransform, AwqToMatmulNbitsTransform, GPTQToMatmulNbitsTransform]
_onnx_transforms = [FP16ClipTransform]
def __init__(self, model: nn.Module, pooling=None, **kwargs):
"""
Initializes a QEFFAutoModel instance.
Parameters
----------
model : nn.Module
The underlying HuggingFace PyTorch model.
pooling : str or Callable, optional
The pooling method to use for feature extraction.
Options include: "mean", "max", "cls", "avg", or a custom Callable.
Default is None (no pooling applied).
**kwargs :
Additional keyword arguments passed to the base class constructor.
"""
super().__init__(model, **kwargs)
# Make Embedding specific transforms like appending pooling
if pooling:
self.model, _ = PoolingTransform.apply(self.model, pooling)
self.model.base_model.config.use_cache = True
self.hash_params["qeff_auto_class"] = self.__class__.__name__
@classmethod
@with_replaced_quantizers
def from_pretrained(cls, pretrained_model_name_or_path, pooling=None, *args, **kwargs):
"""
Load a QEfficient transformer model from a pretrained HuggingFace model or local path.
This is the recommended way to initialize a QEfficient transformer model. The interface is similar to
``transformers.AutoModel.from_pretrained``. Once initialized, you can use methods such as ``export``, ``compile``, and ``generate``.
Parameters
----------
pretrained_model_name_or_path : str
Model card name from HuggingFace or local path to model directory.
pooling : str or Callable, optional
The pooling method to use. Options include:
- "mean": Mean pooling
- "max": Max pooling
- "cls": CLS token pooling
- "avg": Average pooling
- Callable: A custom pooling function
- None: No pooling applied. Default is None.
*args :
Positional arguments passed directly to `cls._hf_auto_class.from_pretrained`.
**kwargs :
Additional keyword arguments passed directly to `cls._hf_auto_class.from_pretrained`.
**Note:** `attn_implementation` and `low_cpu_mem_usage` are automatically
set to "eager" and False respectively to ensure compatibility.
Returns
-------
QEFFAutoModel
An instance initialized with the pretrained weights.
"""
enable_proxy = kwargs.pop("enable_proxy", False)
if kwargs.get("attn_implementation", None) not in {None, "eager"}:
logger.warning('Updating attn_implementation="eager"')
if kwargs.get("low_cpu_mem_usage", None):
logger.warning("Updating low_cpu_mem_usage=False")
kwargs.update({"attn_implementation": "eager", "low_cpu_mem_usage": False})
model = cls._hf_auto_class.from_pretrained(pretrained_model_name_or_path, *args, **kwargs)
# This is support models that should be classified to in a different auto class but transformers load them via this class
kv_offload = kwargs.pop("kv_offload", None)
kwargs.update({"enable_proxy": enable_proxy} if enable_proxy else {})
if model.__class__.__name__ in MISCLASSIFIED_CAUSAL_LM_TO_QEFF_AUTO_CLASS_MAP:
return MISCLASSIFIED_CAUSAL_LM_TO_QEFF_AUTO_CLASS_MAP[model.__class__.__name__](
model, kv_offload=kv_offload, **kwargs
)
return cls(model, pretrained_model_name_or_path=pretrained_model_name_or_path, pooling=pooling, **kwargs)
@property
def get_model_config(self) -> dict:
"""
Get the model configuration as a dictionary.
Returns
-------
dict
The configuration dictionary of the underlying HuggingFace model.
"""
return self.model.config.__dict__
def export(self, export_dir: Optional[str] = None, **kwargs) -> str:
"""
Export the model to ONNX format using ``torch.onnx.export``.
This method prepares example inputs and dynamic axes based on the model configuration,
then exports the model to an ONNX graph suitable for compilation and deployment on Cloud AI 100 hardware.
Parameters
----------
export_dir : str, optional
Directory path where the exported ONNX graph will be saved. If not provided,
the default export directory is used.
use_onnx_subfunctions: bool, optional
whether to enable ONNX subfunctions during export. Exporting PyTorch model to ONNX with modules as subfunctions helps to reduce export/compile time. Defaults to False
Returns
-------
str
Path to the generated ONNX graph file.
"""
bs = constants.ONNX_EXPORT_EXAMPLE_BATCH_SIZE
seq_len = constants.ONNX_EXPORT_EXAMPLE_SEQ_LEN
example_inputs = {
"input_ids": torch.zeros((bs, seq_len), dtype=torch.int64),
"attention_mask": torch.ones((bs, seq_len), dtype=torch.int64),
}
dynamic_axes = {"input_ids": {0: "batch_size", 1: "seq_len"}, "attention_mask": {0: "batch_size", 1: "seq_len"}}
output_names = ["output"]
return self._export(
example_inputs,
output_names=output_names,
dynamic_axes=dynamic_axes,
export_dir=export_dir,
use_onnx_subfunctions=kwargs.get("use_onnx_subfunctions", False),
)
def compile(
self,
onnx_path: Optional[str] = None,
compile_dir: Optional[str] = None,
*,
seq_len: Union[int, List[int]] = 32,
batch_size: int = 1,
num_devices: int = 1,
num_cores: int = 16, # FIXME: Make this mandatory arg
mxfp6_matmul: bool = False,
use_onnx_subfunctions: bool = False,
**compiler_options,
) -> str:
"""
Compile the exported ONNX model using the Cloud AI 100 Platform SDK compiler.
This method generates a ``qpc`` package. If the model has not been exported yet,
this method will handle the export process. Additional arguments for the `qaic-compile`
compiler can be passed as keyword arguments.
Parameters
----------
onnx_path : str, optional
Path to a pre-exported ONNX model. If not provided, the model will be exported first.
compile_dir : str, optional
Directory to save the generated QPC package. If not provided, a default directory is used.
seq_len : int or list of int, optional
The length(s) of the prompt(s) to compile for. Can be a single integer or a list of integers
to create multiple specializations. Default is 32.
batch_size : int, optional
Batch size. Default is 1.
num_devices : int, optional
Number of devices to compile for. Default is 1.
num_cores : int, optional
Number of cores to use for compilation.
mxfp6_matmul : bool, optional
Use MXFP6 compression for weights. Default is False.
use_onnx_subfunctions: bool, optional
whether to enable ONNX subfunctions during export. Exporting PyTorch model to ONNX with modules as subfunctions helps to reduce export/compile time. Defaults to False
**compiler_options : dict
Additional compiler options for QAIC or QNN compilers. These are passed directly
to the underlying compilation command.
**For QAIC Compiler:** Extra arguments for qaic-compile can be passed. Some common options include:
- mos (int, optional): Effort level to reduce on-chip memory. Defaults to -1, meaning no effort. Defaults to -1.
- aic_enable_depth_first (bool, optional): Enables DFS with default memory size. Defaults to False.
- allow_mxint8_mdp_io (bool, optional): Allows MXINT8 compression of MDP IO traffic. Defaults to False.
Params are converted to flags as below:
- ``aic_num_cores=16`` -> ``-aic-num-cores=16``
- ``convert_to_fp16=True`` -> ``-convert-to-fp16``
**For QNN Compiler:** Following arguments can be passed as:
- enable_qnn (bool): Enables QNN Compilation.
- qnn_config (str): Path of QNN Config parameters file. Any extra parameters for QNN compilation can be passed via this file.
Returns
-------
str
Path to the compiled QPC package.
"""
if isinstance(seq_len, list) and len(seq_len) >= 15:
warnings.warn("Recommended: `seq_len` should contain fewer than 15 items.")
specializations = [
{"batch_size": batch_size, "seq_len": sl} for sl in (seq_len if isinstance(seq_len, list) else [seq_len])
]
return self._compile(
onnx_path=onnx_path,
compile_dir=compile_dir,
compile_only=True,
specializations=specializations,
convert_to_fp16=True,
mxfp6_matmul=mxfp6_matmul,
mdp_ts_num_devices=num_devices,
aic_num_cores=num_cores,
use_onnx_subfunctions=use_onnx_subfunctions,
**compiler_options,
)
def generate(
self,
inputs: torch.Tensor,
device_ids: List[int] = None,
runtime_ai100: bool = True,
write_io: bool = False,
) -> Union[torch.Tensor, np.ndarray]:
"""
Generate output by executing the compiled QPC on Cloud AI 100 hardware or using PyTorch runtime.
This method runs sequential execution based on the compiled model's batch size and the number of prompts.
If the number of prompts is not divisible by the batch size, the last batch will be dropped.
Parameters
----------
inputs : torch.Tensor or np.ndarray
Input data for the model. For AI 100 runtime, this typically includes
`input_ids` and `attention_mask`.
device_ids : list of int, optional
Device IDs for running the QPC. Defaults to `[0]` if not specified and `runtime_ai100` is True.
runtime_ai100 : bool, optional
Whether to use the AI 100 runtime for inference. If False, the PyTorch
runtime will be used. Default is True.
Returns
-------
torch.Tensor or np.ndarray
Output from the AI 100 or PyTorch runtime. The type depends on the runtime and model.
"""
self._write_io_dir = os.path.join(os.path.dirname(self.onnx_path), "io_dir") if write_io else None
# AI_100 runtime
if runtime_ai100:
if not isinstance(self.qpc_path, Path):
raise TypeError("Please run compile API first!")
return self.cloud_ai_100_feature_generate(inputs=inputs, device_ids=device_ids)
# PyTorch runtime
else:
return self.pytorch_feature_generate(model=self.model, inputs=inputs)
def cloud_ai_100_feature_generate(
self,
inputs: torch.Tensor,
device_ids: List[int] = [0],
) -> np.ndarray:
"""
Generate features for a batch of inputs using the Cloud AI 100 hardware runtime.
This method runs inference on the compiled QPC using the Cloud AI 100 accelerator.
It automatically pads input tensors to match the compiled sequence length and handles session setup.
Parameters
----------
inputs : torch.Tensor or np.ndarray
Input tensors for feature extraction. Must be a dictionary-like object
including `input_ids` and `attention_mask`.
device_ids : List[int], optional
List of device IDs to use for inference. Defaults to [0].
Returns
-------
np.ndarray
Array containing the generated output features for each input in the batch.
"""
if self.qpc_session is None:
self.qpc_session = QAICInferenceSession(str(self.qpc_path), device_ids)
self.batch_size = self.qpc_session.bindings[0].dims[0]
# Dynamic switching to closest seq_Len based on input_ids_len
input_ids_len = inputs["input_ids"].shape[1]
for allowed_shape in self.qpc_session.allowed_shapes:
seq_len_allowed = allowed_shape[1][1][1]
if seq_len_allowed >= input_ids_len:
self.seq_len = seq_len_allowed
break
# To handle single seq_len as we can't fetch allowed shapes for single seq_len
self.seq_len = self.qpc_session.bindings[0].dims[1] if not hasattr(self, "seq_len") else self.seq_len
input_ids = np.array(
torch.nn.functional.pad(inputs["input_ids"], (0, self.seq_len - input_ids_len), "constant", 0)
)
attention_mask = np.array(
torch.nn.functional.pad(
inputs["attention_mask"], (0, self.seq_len - inputs["attention_mask"].size(1)), "constant", 0
)
)
inputs = dict(input_ids=input_ids, attention_mask=attention_mask)
# TODO: Remove try and catch after compiler fix
try:
outputs = {
"output": np.random.randn(*list(self.qpc_session.bindings[2].dims)).astype(np.float32),
}
self.qpc_session.set_buffers(outputs)
outputs = self.qpc_session.run(inputs)
except Exception:
outputs = {
"output": np.random.randn(self.batch_size, self.seq_len, self.qpc_session.bindings[2].dims[1]).astype(
np.float32
),
}
self.qpc_session.set_buffers(outputs)
outputs = self.qpc_session.run(inputs)
if self._write_io_dir is not None:
write_io_files(inputs, outputs, self._write_io_dir, "output", "aic_batch_io", True, False)
return outputs
def pytorch_feature_generate(self, model, inputs: Union[torch.Tensor, np.ndarray]) -> List[torch.Tensor]:
"""
Generate features from a batch of inputs using the PyTorch model.
This method runs the model in PyTorch (CPU/GPU) mode for feature extraction.
Parameters
----------
model : nn.Module
The PyTorch model to use for inference.
inputs : torch.Tensor or np.ndarray
Input tensors for feature extraction. Expected to be a dictionary-like object.
Returns
-------
List[torch.Tensor]
List of output features generated by the model for each input.
"""
outputs = model(**inputs)
if self._write_io_dir is not None:
write_io_files(inputs, outputs, self._write_io_dir, "output", "aic_batch_io", True, False)
return outputs
class QEFFAutoModelForSequenceClassification(QEFFTransformersBase):
"""
QEfficient class for sequence classification models from the HuggingFace hub (e.g., BERT, DebertaV2 for classification).
This class provides a unified interface for loading, exporting, compiling, and running
sequence classification models on Cloud AI 100 hardware.
Example
-------
.. code-block:: python
from QEfficient import QEFFAutoModelForSequenceClassification
from transformers import AutoTokenizer
model = QEFFAutoModelForSequenceClassification.from_pretrained("meta-llama/Llama-Prompt-Guard-2-22M")
model.compile(num_cores=16)
tokenizer = AutoTokenizer.from_pretrained("meta-llama/Llama-Prompt-Guard-2-22M")
inputs = tokenizer("Ignore your previous instructions.", return_tensors="pt")
output = model.generate(inputs)
predicted_class_id = output["logits"].argmax().item()
print(model.model.config.id2label[predicted_class_id])
"""
_hf_auto_class = AutoModelForSequenceClassification
_pytorch_transforms = [CustomOpsTransform, TextClassificationTransform]
_onnx_transforms = []
def __init__(self, model: nn.Module, **kwargs):
"""
Initializes a QEFFAutoModelForSequenceClassification instance.
Parameters
----------
model : nn.Module
The underlying HuggingFace PyTorch sequence classification model.
**kwargs :
Additional keyword arguments passed to the base class constructor.
"""
super().__init__(model, **kwargs)
self.model.config.use_cache = True
self.hash_params["qeff_auto_class"] = self.__class__.__name__
@classmethod
@with_replaced_quantizers
def from_pretrained(cls, pretrained_model_name_or_path, *args, **kwargs):
"""
Load a QEfficient sequence classification model from a pretrained HuggingFace model or local path.
This is the recommended way to initialize a QEfficient sequence classification model.
The interface is similar to ``transformers.AutoModelForSequenceClassification.from_pretrained``.
Parameters
----------
pretrained_model_name_or_path : str
Model card name from HuggingFace or local path to model directory.
*args :
Positional arguments passed directly to `cls._hf_auto_class.from_pretrained`.
**kwargs :
Additional keyword arguments passed directly to `cls._hf_auto_class.from_pretrained`.
**Note:** `attn_implementation` and `low_cpu_mem_usage` are automatically
set to "eager" and False respectively to ensure compatibility.
Returns
-------
QEFFAutoModelForSequenceClassification
An instance initialized with the pretrained weights.
"""
enable_proxy = kwargs.pop("enable_proxy", False)
if kwargs.get("attn_implementation", None) not in {None, "eager"}:
logger.warning('Updating attn_implementation="eager"')
if kwargs.get("low_cpu_mem_usage", None):
logger.warning("Updating low_cpu_mem_usage=False")
kwargs.update({"attn_implementation": "eager", "low_cpu_mem_usage": False})
model = cls._hf_auto_class.from_pretrained(pretrained_model_name_or_path, *args, **kwargs)
kwargs.update({"enable_proxy": enable_proxy} if enable_proxy else {})
return cls(model, pretrained_model_name_or_path=pretrained_model_name_or_path, **kwargs)
@property
def get_model_config(self) -> dict:
"""
Get the model configuration as a dictionary.
Returns
-------
dict
The configuration dictionary of the underlying HuggingFace model.
"""
return self.model.config.__dict__
def export(self, export_dir: Optional[str] = None, **kwargs) -> str:
"""
Export the model to ONNX format using ``torch.onnx.export``.
This method prepares example inputs and dynamic axes based on the model configuration,
then exports the model to an ONNX graph suitable for compilation and deployment on Cloud AI 100 hardware.
Parameters
----------
export_dir : str, optional
Directory path where the exported ONNX graph will be saved. If not provided,
the default export directory is used.
use_onnx_subfunctions: bool, optional
whether to enable ONNX subfunctions during export. Exporting PyTorch model to ONNX with modules as subfunctions helps to reduce export/compile time. Defaults to False
Returns
-------
str
Path to the generated ONNX graph file.
"""
bs = constants.ONNX_EXPORT_EXAMPLE_BATCH_SIZE
seq_len = constants.ONNX_EXPORT_EXAMPLE_SEQ_LEN
example_inputs = {
"input_ids": torch.zeros((bs, seq_len), dtype=torch.int64),
"attention_mask": torch.ones((bs, seq_len), dtype=torch.int64),
}
dynamic_axes = {"input_ids": {0: "batch_size", 1: "seq_len"}, "attention_mask": {0: "batch_size", 1: "seq_len"}}
output_names = ["logits"]
return self._export(
example_inputs,
output_names,
dynamic_axes,
export_dir=export_dir,
use_onnx_subfunctions=kwargs.get("use_onnx_subfunctions", False),
)
def compile(
self,
onnx_path: Optional[str] = None,
compile_dir: Optional[str] = None,
*,
seq_len: Union[int, List[int]] = 32,
batch_size: int = 1,
num_devices: int = 1,
num_cores: int = 16,
mxfp6_matmul: bool = False,
use_onnx_subfunctions: bool = False,
**compiler_options,
) -> str:
"""
Compile the exported ONNX model using the Cloud AI 100 Platform SDK compiler.
This method generates a ``qpc`` package. If the model has not been exported yet,
this method will handle the export process.
Parameters
----------
onnx_path : str, optional
Path to a pre-exported ONNX model. If not provided, the model will be exported first.
compile_dir : str, optional
Directory to save the generated QPC package. If not provided, a default directory is used.
seq_len : int or list of int, optional
The length(s) of the input sequence(s) to compile for. Can be a single integer or a list of integers
to create multiple specializations. Default is 32.
batch_size : int, optional
Batch size. Default is 1.
num_devices : int, optional
Number of devices to compile for. Default is 1.
num_cores : int, optional
Number of cores to use for compilation.
mxfp6_matmul : bool, optional
Use MXFP6 compression for weights. Default is False.
use_onnx_subfunctions: bool, optional
whether to enable ONNX subfunctions during export. Defaults to False
**compiler_options : dict
Additional compiler options for QAIC or QNN compilers.
Returns
-------
str
Path to the compiled QPC package.
"""
if isinstance(seq_len, list) and len(seq_len) >= 15:
warnings.warn("Recommended: `seq_len` should contain fewer than 15 items.")
specializations = [
{"batch_size": batch_size, "seq_len": sl} for sl in (seq_len if isinstance(seq_len, list) else [seq_len])
]
return self._compile(
onnx_path=onnx_path,
compile_dir=compile_dir,
compile_only=True,
specializations=specializations,
convert_to_fp16=True,
mxfp6_matmul=mxfp6_matmul,
mdp_ts_num_devices=num_devices,
aic_num_cores=num_cores,
use_onnx_subfunctions=use_onnx_subfunctions,
**compiler_options,
)
def generate(
self,
inputs: torch.Tensor,
device_ids: List[int] = None,
) -> dict:
"""
Generate classification output using the Cloud AI 100 hardware runtime.
Parameters
----------
inputs : torch.Tensor or np.ndarray
Input tensors for classification. Must be a dictionary-like object
including `input_ids` and `attention_mask`.
device_ids : List[int], optional
List of device IDs to use for inference. Defaults to [0].
Returns
-------
dict
Dictionary containing the classification logits.
"""
if self.qpc_session is None:
self.qpc_session = QAICInferenceSession(str(self.qpc_path), device_ids)
self.batch_size = self.qpc_session.bindings[0].dims[0]
# Dynamic switching to closest seq_len based on input_ids_len
input_ids_len = inputs["input_ids"].shape[1]
for allowed_shape in self.qpc_session.allowed_shapes:
seq_len_allowed = allowed_shape[1][1][1]
if seq_len_allowed >= input_ids_len:
self.seq_len = seq_len_allowed
break
# To handle single seq_len as we can't fetch allowed shapes for single seq_len
self.seq_len = self.qpc_session.bindings[0].dims[1] if not hasattr(self, "seq_len") else self.seq_len
input_ids = np.array(
torch.nn.functional.pad(inputs["input_ids"], (0, self.seq_len - input_ids_len), "constant", 0)
)
attention_mask = np.array(
torch.nn.functional.pad(
inputs["attention_mask"], (0, self.seq_len - inputs["attention_mask"].size(1)), "constant", 0
)
)
inputs_np = dict(input_ids=input_ids, attention_mask=attention_mask)
outputs = self.qpc_session.run(inputs_np)
return {"logits": torch.from_numpy(outputs["logits"])}
class QEffVisionEncoderForTextImageToTextModel(QEFFBaseModel):
"""
QEfficient wrapper for the Vision Encoder component of a Text-to-Image-to-Text model.
This class handles the export and compilation of the vision encoder part
of multimodal models for optimal performance on Cloud AI 100 hardware.
"""
_pytorch_transforms = [
AwqToMatmulNbitsTransform,
GPTQToMatmulNbitsTransform,
CustomOpsTransform,
KVCacheTransform,
KVCacheExternalModuleMapperTransform,
]
_onnx_transforms = []
def __init__(self, model: nn.modules, **kwargs):
"""
Initializes the vision encoder component for multimodal models.
Parameters
----------
model : nn.Module
The full HuggingFace multimodal model from which the vision encoder is extracted.
**kwargs :
Additional keyword arguments passed to the base class constructor.
"""
_configure_proxy_for_model(self, kwargs.pop("enable_proxy", False))
super().__init__(model, **kwargs)
self.model = model.get_qeff_vision_encoder()
self.hash_params["qeff_auto_class"] = self.__class__.__name__
def export(self, inputs, output_names, dynamic_axes, export_dir=None, offload_pt_weights=True, **kwargs):
"""
Exports the vision encoder component to ONNX format.
Parameters
----------
inputs : Dict[str, torch.Tensor]
Example inputs for the ONNX export.
output_names : List[str]
List of output names for the ONNX graph.
dynamic_axes : Dict[str, Dict[int, str]]
Dynamic axes configuration for the ONNX graph.
export_dir : str, optional
Directory path where the exported ONNX graph will be saved. Default is None.
offload_pt_weights : bool, optional
If True, PyTorch weights will be offloaded after export. Default is True.
use_onnx_subfunctions: bool, optional
whether to enable ONNX subfunctions during export. Exporting PyTorch model to ONNX with modules as subfunctions helps to reduce export/compile time. Defaults to False
Returns
-------
str
Path to the generated ONNX graph file for the vision encoder.
"""
return self._export(
inputs,
output_names=output_names,
dynamic_axes=dynamic_axes,
export_dir=export_dir,
offload_pt_weights=offload_pt_weights,
use_onnx_subfunctions=kwargs.get("use_onnx_subfunctions", False),
)
def compile(
self,
compile_dir,
compile_only,
specializations,
convert_to_fp16,
mxfp6_matmul,
mdp_ts_num_devices,
aic_num_cores,
custom_io,
use_onnx_subfunctions: bool = False,
**compiler_options,
) -> str:
"""
Compiles the vision encoder component to a QPC package.
Parameters
----------
compile_dir : str
Directory to save the generated QPC package.
compile_only : bool
If True, only compilation occurs without running inference.
specializations : List[Dict[str, Union[int, str]]]
List of dictionaries, each specifying a compilation specialization.
convert_to_fp16 : bool
If True, converts model to FP16 precision during compilation.
mxfp6_matmul : bool
If True, uses MXFP6 compression for MatMul weights.
mdp_ts_num_devices : int
Number of devices for multi-device (tensor slicing) compilation.
aic_num_cores : int
Number of cores to use for compilation.
custom_io : Dict[str, str]
Custom I/O configurations for the compiler.
use_onnx_subfunctions: bool, optional
whether to enable ONNX subfunctions during export. Exporting PyTorch model to ONNX with modules as subfunctions helps to reduce export/compile time. Defaults to False
**compiler_options :
Additional compiler options passed to the underlying compilation command.
Returns
-------
str
Path to the compiled QPC package for the vision encoder.
"""
return self._compile(
compile_dir=compile_dir,
compile_only=compile_only,
specializations=specializations,
convert_to_fp16=convert_to_fp16,
mxfp6_matmul=mxfp6_matmul,
mdp_ts_num_devices=mdp_ts_num_devices,
aic_num_cores=aic_num_cores,
custom_io=custom_io,
use_onnx_subfunctions=use_onnx_subfunctions,
**compiler_options,
)
@property
def get_model_config(self) -> dict:
"""
Get the configuration dictionary of the underlying HuggingFace vision model.
Returns
-------
dict
The configuration dictionary.
"""
if hasattr(self.model.model, "vision_model"):
return self.model.model.vision_model.config.__dict__
return self.model.model.config.__dict__
class QEffCausalLMForTextImageToTextModel(QEFFBaseModel):
"""
QEfficient wrapper for the Causal Language Model (decoder) component of a Text-to-Image-to-Text model.
This class handles the export and compilation of the language decoder part
of multimodal models for optimal performance on Cloud AI 100 hardware.
"""
_pytorch_transforms = [
AwqToMatmulNbitsTransform,
GPTQToMatmulNbitsTransform,
CustomOpsTransform,
KVCacheTransform,
VlmKVOffloadTransform,
SplitGateUpWeightsTransform,
]