Repository navigation
Expand file tree
/
Copy path__init__.py
More file actions
executable file
·1238 lines (1098 loc) · 76.7 KB
/
Copy path__init__.py
File metadata and controls
executable file
·1238 lines (1098 loc) · 76.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# Copyright 2018 The HuggingFace Inc. team.
#
# 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.
from __future__ import annotations
import importlib
import json
import os
import warnings
from pathlib import Path
from typing import TYPE_CHECKING, Any, Optional, Union
from huggingface_hub import is_offline_mode
from ..configuration_utils import PreTrainedConfig
from ..dynamic_module_utils import get_class_from_dynamic_module
from ..feature_extraction_utils import FeatureExtractionMixin
from ..image_processing_utils import BaseImageProcessor
from ..models.auto.configuration_auto import AutoConfig
from ..models.auto.feature_extraction_auto import FEATURE_EXTRACTOR_MAPPING, AutoFeatureExtractor
from ..models.auto.image_processing_auto import IMAGE_PROCESSOR_MAPPING, AutoImageProcessor
from ..models.auto.modeling_auto import (
MODEL_FOR_DECISION_MAPPING,
AutoModelForDepthEstimation,
AutoModelForImageToImage,
)
from ..models.auto.processing_auto import PROCESSOR_MAPPING, AutoProcessor
from ..models.auto.tokenization_auto import TOKENIZER_MAPPING, AutoTokenizer
from ..models.auto.video_processing_auto import AutoVideoProcessor
from ..processing_utils import ProcessorMixin
from ..tokenization_python import PreTrainedTokenizer
from ..utils import (
CONFIG_NAME,
find_adapter_config_file,
hf_api,
is_kenlm_available,
is_peft_available,
is_pyctcdecode_available,
is_torch_available,
logging,
resolve_revision,
)
from ..video_processing_utils import BaseVideoProcessor
from .base import (
ArgumentHandler,
CsvPipelineDataFormat,
JsonPipelineDataFormat,
PipedPipelineDataFormat,
Pipeline,
PipelineDataFormat,
PipelineException,
PipelineRegistry,
get_default_model_and_revision,
load_model,
)
# Map each public pipeline class name to its submodule, used by __getattr__ and _resolve_impl.
# This replaces 27 eager submodule imports so that only the submodule(s) actually needed at
# runtime are loaded (e.g. only TextClassificationPipeline when running text-classification).
_PIPELINE_CLASS_TO_MODULE = {
"AggregationStrategy": "transformers.pipelines.token_classification",
"AnyToAnyPipeline": "transformers.pipelines.any_to_any",
"AudioClassificationPipeline": "transformers.pipelines.audio_classification",
"AutomaticSpeechRecognitionPipeline": "transformers.pipelines.automatic_speech_recognition",
"DecisionPipeline": "transformers.pipelines.decision",
"DepthEstimationPipeline": "transformers.pipelines.depth_estimation",
"DocumentQuestionAnsweringPipeline": "transformers.pipelines.document_question_answering",
"FeatureExtractionPipeline": "transformers.pipelines.feature_extraction",
"FillMaskPipeline": "transformers.pipelines.fill_mask",
"ImageClassificationPipeline": "transformers.pipelines.image_classification",
"ImageFeatureExtractionPipeline": "transformers.pipelines.image_feature_extraction",
"ImageSegmentationPipeline": "transformers.pipelines.image_segmentation",
"ImageTextToTextPipeline": "transformers.pipelines.image_text_to_text",
"KeypointMatchingPipeline": "transformers.pipelines.keypoint_matching",
"MaskGenerationPipeline": "transformers.pipelines.mask_generation",
"NerPipeline": "transformers.pipelines.token_classification",
"ObjectDetectionPipeline": "transformers.pipelines.object_detection",
"TableQuestionAnsweringArgumentHandler": "transformers.pipelines.table_question_answering",
"TableQuestionAnsweringPipeline": "transformers.pipelines.table_question_answering",
"TextClassificationPipeline": "transformers.pipelines.text_classification",
"TextGenerationPipeline": "transformers.pipelines.text_generation",
"TextToAudioPipeline": "transformers.pipelines.text_to_audio",
"TokenClassificationArgumentHandler": "transformers.pipelines.token_classification",
"TokenClassificationPipeline": "transformers.pipelines.token_classification",
"VideoClassificationPipeline": "transformers.pipelines.video_classification",
"ZeroShotAudioClassificationPipeline": "transformers.pipelines.zero_shot_audio_classification",
"ZeroShotClassificationArgumentHandler": "transformers.pipelines.zero_shot_classification",
"ZeroShotClassificationPipeline": "transformers.pipelines.zero_shot_classification",
"ZeroShotImageClassificationPipeline": "transformers.pipelines.zero_shot_image_classification",
"ZeroShotObjectDetectionPipeline": "transformers.pipelines.zero_shot_object_detection",
}
def _resolve_impl(impl):
"""Resolve a pipeline impl: dotted-path string -> class, or pass through a class unchanged."""
if isinstance(impl, str):
module_path, cls_name = impl.rsplit(".", 1)
return getattr(importlib.import_module(module_path), cls_name)
return impl
if is_torch_available():
import torch
from ..models.auto.modeling_auto import (
AutoModel,
AutoModelForAudioClassification,
AutoModelForCausalLM,
AutoModelForCTC,
AutoModelForDecision,
AutoModelForDocumentQuestionAnswering,
AutoModelForImageClassification,
AutoModelForImageSegmentation,
AutoModelForImageTextToText,
AutoModelForKeypointMatching,
AutoModelForMaskedLM,
AutoModelForMaskGeneration,
AutoModelForMultimodalLM,
AutoModelForObjectDetection,
AutoModelForQuestionAnswering,
AutoModelForSemanticSegmentation,
AutoModelForSeq2SeqLM,
AutoModelForSequenceClassification,
AutoModelForSpeechSeq2Seq,
AutoModelForTableQuestionAnswering,
AutoModelForTDT,
AutoModelForTextToSpectrogram,
AutoModelForTextToWaveform,
AutoModelForTokenClassification,
AutoModelForVideoClassification,
AutoModelForVisualQuestionAnswering,
AutoModelForZeroShotImageClassification,
AutoModelForZeroShotObjectDetection,
)
if TYPE_CHECKING:
from ..modeling_utils import PreTrainedModel
from ..tokenization_utils_tokenizers import PreTrainedTokenizerFast
from .any_to_any import AnyToAnyPipeline
from .audio_classification import AudioClassificationPipeline
from .automatic_speech_recognition import AutomaticSpeechRecognitionPipeline
from .decision import DecisionPipeline
from .depth_estimation import DepthEstimationPipeline
from .document_question_answering import DocumentQuestionAnsweringPipeline
from .feature_extraction import FeatureExtractionPipeline
from .fill_mask import FillMaskPipeline
from .image_classification import ImageClassificationPipeline
from .image_feature_extraction import ImageFeatureExtractionPipeline
from .image_segmentation import ImageSegmentationPipeline
from .image_text_to_text import ImageTextToTextPipeline
from .keypoint_matching import KeypointMatchingPipeline
from .mask_generation import MaskGenerationPipeline
from .object_detection import ObjectDetectionPipeline
from .table_question_answering import TableQuestionAnsweringPipeline
from .text_classification import TextClassificationPipeline
from .text_generation import TextGenerationPipeline
from .text_to_audio import TextToAudioPipeline
from .token_classification import TokenClassificationPipeline
from .video_classification import VideoClassificationPipeline
from .zero_shot_audio_classification import ZeroShotAudioClassificationPipeline
from .zero_shot_classification import ZeroShotClassificationPipeline
from .zero_shot_image_classification import ZeroShotImageClassificationPipeline
from .zero_shot_object_detection import ZeroShotObjectDetectionPipeline
logger = logging.get_logger(__name__)
# Register all the supported tasks here
TASK_ALIASES = {
"sentiment-analysis": "text-classification",
"ner": "token-classification",
"text-to-speech": "text-to-audio",
}
# Note: `["impl"]` values are dotted-path strings (e.g. "transformers.pipelines.text_classification.TextClassificationPipeline"),
# not class objects — resolved lazily at call time via `_resolve_impl()` to avoid eagerly importing all pipeline submodules.
SUPPORTED_TASKS = {
"audio-classification": {
"impl": "transformers.pipelines.audio_classification.AudioClassificationPipeline",
"pt": (AutoModelForAudioClassification,) if is_torch_available() else (),
"default": {"model": ("superb/wav2vec2-base-superb-ks", "372e048")},
"type": "audio",
},
"automatic-speech-recognition": {
"impl": "transformers.pipelines.automatic_speech_recognition.AutomaticSpeechRecognitionPipeline",
"pt": (AutoModelForCTC, AutoModelForTDT, AutoModelForSpeechSeq2Seq) if is_torch_available() else (),
"default": {"model": ("facebook/wav2vec2-base-960h", "22aad52")},
"type": "multimodal",
},
"text-to-audio": {
"impl": "transformers.pipelines.text_to_audio.TextToAudioPipeline",
"pt": (AutoModelForTextToWaveform, AutoModelForTextToSpectrogram) if is_torch_available() else (),
"default": {"model": ("suno/bark-small", "1dbd7a1")},
"type": "text",
},
"feature-extraction": {
"impl": "transformers.pipelines.feature_extraction.FeatureExtractionPipeline",
"pt": (AutoModel,) if is_torch_available() else (),
"default": {"model": ("distilbert/distilbert-base-cased", "6ea8117")},
"type": "text",
},
"text-classification": {
"impl": "transformers.pipelines.text_classification.TextClassificationPipeline",
"pt": (AutoModelForSequenceClassification,) if is_torch_available() else (),
"default": {"model": ("distilbert/distilbert-base-uncased-finetuned-sst-2-english", "714eb0f")},
"type": "text",
},
"token-classification": {
"impl": "transformers.pipelines.token_classification.TokenClassificationPipeline",
"pt": (AutoModelForTokenClassification,) if is_torch_available() else (),
"default": {"model": ("dbmdz/bert-large-cased-finetuned-conll03-english", "4c53496")},
"type": "text",
},
"table-question-answering": {
"impl": "transformers.pipelines.table_question_answering.TableQuestionAnsweringPipeline",
"pt": (AutoModelForTableQuestionAnswering,) if is_torch_available() else (),
"default": {"model": ("google/tapas-base-finetuned-wtq", "e3dde19")},
"type": "text",
},
"document-question-answering": {
"impl": "transformers.pipelines.document_question_answering.DocumentQuestionAnsweringPipeline",
"pt": (AutoModelForDocumentQuestionAnswering,) if is_torch_available() else (),
"default": {"model": ("impira/layoutlm-document-qa", "beed3c4")},
"type": "multimodal",
},
"fill-mask": {
"impl": "transformers.pipelines.fill_mask.FillMaskPipeline",
"pt": (AutoModelForMaskedLM,) if is_torch_available() else (),
"default": {"model": ("distilbert/distilroberta-base", "fb53ab8")},
"type": "text",
},
"text-generation": {
"impl": "transformers.pipelines.text_generation.TextGenerationPipeline",
"pt": (AutoModelForCausalLM,) if is_torch_available() else (),
"default": {"model": ("HuggingFaceTB/SmolLM3-3B", "a07cc9a")},
"type": "text",
},
"zero-shot-classification": {
"impl": "transformers.pipelines.zero_shot_classification.ZeroShotClassificationPipeline",
"pt": (AutoModelForSequenceClassification,) if is_torch_available() else (),
"default": {
"model": ("facebook/bart-large-mnli", "d7645e1"),
"config": ("facebook/bart-large-mnli", "d7645e1"),
},
"type": "text",
},
"zero-shot-image-classification": {
"impl": "transformers.pipelines.zero_shot_image_classification.ZeroShotImageClassificationPipeline",
"pt": (AutoModelForZeroShotImageClassification,) if is_torch_available() else (),
"default": {"model": ("openai/clip-vit-base-patch32", "3d74acf")},
"type": "multimodal",
},
"zero-shot-audio-classification": {
"impl": "transformers.pipelines.zero_shot_audio_classification.ZeroShotAudioClassificationPipeline",
"pt": (AutoModel,) if is_torch_available() else (),
"default": {"model": ("laion/clap-htsat-fused", "cca9e28")},
"type": "multimodal",
},
"image-classification": {
"impl": "transformers.pipelines.image_classification.ImageClassificationPipeline",
"pt": (AutoModelForImageClassification,) if is_torch_available() else (),
"default": {"model": ("google/vit-base-patch16-224", "3f49326")},
"type": "image",
},
"image-feature-extraction": {
"impl": "transformers.pipelines.image_feature_extraction.ImageFeatureExtractionPipeline",
"pt": (AutoModel,) if is_torch_available() else (),
"default": {"model": ("google/vit-base-patch16-224", "3f49326")},
"type": "image",
},
"image-segmentation": {
"impl": "transformers.pipelines.image_segmentation.ImageSegmentationPipeline",
"pt": (AutoModelForImageSegmentation, AutoModelForSemanticSegmentation) if is_torch_available() else (),
"default": {"model": ("facebook/detr-resnet-50-panoptic", "d53b52a")},
"type": "multimodal",
},
"image-text-to-text": {
"impl": "transformers.pipelines.image_text_to_text.ImageTextToTextPipeline",
"pt": (AutoModelForImageTextToText,) if is_torch_available() else (),
"default": {"model": ("Qwen/Qwen3-VL-2B-Instruct", "8964489")},
"type": "multimodal",
},
"object-detection": {
"impl": "transformers.pipelines.object_detection.ObjectDetectionPipeline",
"pt": (AutoModelForObjectDetection,) if is_torch_available() else (),
"default": {"model": ("facebook/detr-resnet-50", "1d5f47b")},
"type": "multimodal",
},
"zero-shot-object-detection": {
"impl": "transformers.pipelines.zero_shot_object_detection.ZeroShotObjectDetectionPipeline",
"pt": (AutoModelForZeroShotObjectDetection,) if is_torch_available() else (),
"default": {"model": ("google/owlvit-base-patch32", "cbc355f")},
"type": "multimodal",
},
"decision": {
"impl": "transformers.pipelines.decision.DecisionPipeline",
"pt": (AutoModelForDecision, AutoModelForImageTextToText, AutoModelForCausalLM)
if is_torch_available()
else (),
"default": {"model": ("Qwen/Qwen2.5-0.5B-Instruct", "7ae5576")},
"type": "multimodal",
},
"depth-estimation": {
"impl": "transformers.pipelines.depth_estimation.DepthEstimationPipeline",
"pt": (AutoModelForDepthEstimation,) if is_torch_available() else (),
"default": {"model": ("Intel/dpt-large", "bc15f29")},
"type": "image",
},
"video-classification": {
"impl": "transformers.pipelines.video_classification.VideoClassificationPipeline",
"pt": (AutoModelForVideoClassification,) if is_torch_available() else (),
"default": {"model": ("MCG-NJU/videomae-base-finetuned-kinetics", "488eb9a")},
"type": "video",
},
"mask-generation": {
"impl": "transformers.pipelines.mask_generation.MaskGenerationPipeline",
"pt": (AutoModelForMaskGeneration,) if is_torch_available() else (),
"default": {"model": ("facebook/sam-vit-huge", "87aecf0")},
"type": "multimodal",
},
"keypoint-matching": {
"impl": "transformers.pipelines.keypoint_matching.KeypointMatchingPipeline",
"pt": (AutoModelForKeypointMatching,) if is_torch_available() else (),
"default": {"model": ("magic-leap-community/superglue_outdoor", "f4041f8")},
"type": "image",
},
"any-to-any": {
"impl": "transformers.pipelines.any_to_any.AnyToAnyPipeline",
"tf": (),
"pt": (AutoModelForMultimodalLM,) if is_torch_available() else (),
"default": {
"model": {
"pt": ("google/gemma-3n-E4B-it", "c1221e9"),
}
},
"type": "multimodal",
},
}
PIPELINE_REGISTRY = PipelineRegistry(supported_tasks=SUPPORTED_TASKS, task_aliases=TASK_ALIASES)
REMOVED_TASKS = {
"text2text-generation": "Use the `text-generation` pipeline with a chat model instead.",
"summarization": "Use the `text-generation` pipeline with a chat model instead.",
"translation": "Use the `text-generation` pipeline with a chat model instead.",
"question-answering": "Use the `text-generation` pipeline with a chat model instead.",
"visual-question-answering": "Use the `image-text-to-text` pipeline with a vision-language chat model instead.",
"vqa": "Use the `image-text-to-text` pipeline with a vision-language chat model instead.",
"image-to-image": "For image generation tasks, please use 🤗 Diffusers instead.",
}
def _resolve_deprecated_task(task: str) -> str:
"""
Redirects tasks listed in `DEPRECATED_TASKS` to their replacement and raises an explicit error for tasks listed
in `REMOVED_TASKS`.
"""
if task == "image-to-text":
logger.warning_once(
f"The task `{task}` has been removed and has been replaced by `image-text-to-text`. The pipeline"
f" will be instantiated with the new task name.",
UserWarning,
)
return "image-text-to-text"
# Parametrized translation tasks such as "translation_en_to_fr" were removed along with "translation"
removed_task = "translation" if task.startswith("translation_") else task
if removed_task in REMOVED_TASKS:
raise KeyError(
f"The task {task} has been removed from transformers. {REMOVED_TASKS[removed_task]} See the migration"
f" guide for more details: https://github.com/huggingface/transformers/blob/main/MIGRATION_GUIDE_V5.md#pipelines"
)
return task
def get_supported_tasks() -> list[str]:
"""
Returns a list of supported task strings.
"""
return PIPELINE_REGISTRY.get_supported_tasks()
def get_task(model: str, token: str | None = None, **deprecated_kwargs) -> str:
if is_offline_mode():
raise RuntimeError("You cannot infer task automatically within `pipeline` when using offline mode")
try:
info = hf_api().model_info(model, token=token)
except Exception as e:
raise RuntimeError(f"Instantiating a pipeline without a task set raised an error: {e}")
if not info.pipeline_tag:
raise RuntimeError(
f"The model {model} does not seem to have a correct `pipeline_tag` set to infer the task automatically"
)
if getattr(info, "library_name", "transformers") not in {"transformers", "timm"}:
raise RuntimeError(f"This model is meant to be used with {info.library_name} not with transformers")
return _resolve_deprecated_task(info.pipeline_tag)
def check_task(task: str) -> tuple[str, dict, Any]:
"""
Checks an incoming task string, to validate it's correct and return the default Pipeline and Model classes, and
default models if they exist.
Args:
task (`str`):
The task defining which pipeline will be returned. Currently accepted tasks are:
- `"audio-classification"`
- `"automatic-speech-recognition"`
- `"conversational"`
- `"decision"`
- `"depth-estimation"`
- `"document-question-answering"`
- `"feature-extraction"`
- `"fill-mask"`
- `"image-classification"`
- `"image-feature-extraction"`
- `"image-segmentation"`
- `"keypoint-matching"`
- `"object-detection"`
- `"table-question-answering"`
- `"text-classification"` (alias `"sentiment-analysis"` available)
- `"text-generation"`
- `"text-to-audio"` (alias `"text-to-speech"` available)
- `"token-classification"` (alias `"ner"` available)
- `"video-classification"`
- `"zero-shot-classification"`
- `"zero-shot-image-classification"`
- `"zero-shot-object-detection"`
Returns:
(normalized_task: `str`, task_defaults: `dict`, task_options: (`tuple`, None)) The normalized task name
(removed alias and options).
"""
return PIPELINE_REGISTRY.check_task(_resolve_deprecated_task(task))
def clean_custom_task(task_info):
import transformers
if "impl" not in task_info:
raise RuntimeError("This model introduces a custom pipeline without specifying its implementation.")
pt_class_names = task_info.get("pt", ())
if isinstance(pt_class_names, str):
pt_class_names = [pt_class_names]
task_info["pt"] = tuple(getattr(transformers, c) for c in pt_class_names)
return task_info, None
# <generated-code>
# fmt: off
# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
# The part of the file below was automatically generated from the code.
# Do NOT edit this part of the file manually as any edits will be overwritten by the generation
# of the file. If any change should be done, please apply the changes to the `pipeline` function
# below and run `python utils/check_pipeline_typing.py --fix_and_overwrite` to update the file.
# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
from typing import Literal, overload
@overload
def pipeline(task: Literal[None], model: str | PreTrainedModel | None = None, config: str | PreTrainedConfig | None = None, tokenizer: str | PreTrainedTokenizer | PreTrainedTokenizerFast | None = None, feature_extractor: str | FeatureExtractionMixin | None = None, image_processor: str | BaseImageProcessor | None = None, video_processor: str | BaseVideoProcessor | None = None, processor: str | ProcessorMixin | None = None, revision: str | None = None, use_fast: bool = True, token: str | bool | None = None, device: int | str | torch.device | None = None, device_map: str | dict[str, int | str] | None = None, dtype: str | torch.dtype | None = "auto", trust_remote_code: bool | None = None, model_kwargs: dict[str, Any] | None = None, pipeline_class: Any | None = None, **kwargs: Any) -> Pipeline: ...
@overload
def pipeline(task: Literal["any-to-any"], model: str | PreTrainedModel | None = None, config: str | PreTrainedConfig | None = None, tokenizer: str | PreTrainedTokenizer | PreTrainedTokenizerFast | None = None, feature_extractor: str | FeatureExtractionMixin | None = None, image_processor: str | BaseImageProcessor | None = None, video_processor: str | BaseVideoProcessor | None = None, processor: str | ProcessorMixin | None = None, revision: str | None = None, use_fast: bool = True, token: str | bool | None = None, device: int | str | torch.device | None = None, device_map: str | dict[str, int | str] | None = None, dtype: str | torch.dtype | None = "auto", trust_remote_code: bool | None = None, model_kwargs: dict[str, Any] | None = None, pipeline_class: Any | None = None, **kwargs: Any) -> AnyToAnyPipeline: ...
@overload
def pipeline(task: Literal["audio-classification"], model: str | PreTrainedModel | None = None, config: str | PreTrainedConfig | None = None, tokenizer: str | PreTrainedTokenizer | PreTrainedTokenizerFast | None = None, feature_extractor: str | FeatureExtractionMixin | None = None, image_processor: str | BaseImageProcessor | None = None, video_processor: str | BaseVideoProcessor | None = None, processor: str | ProcessorMixin | None = None, revision: str | None = None, use_fast: bool = True, token: str | bool | None = None, device: int | str | torch.device | None = None, device_map: str | dict[str, int | str] | None = None, dtype: str | torch.dtype | None = "auto", trust_remote_code: bool | None = None, model_kwargs: dict[str, Any] | None = None, pipeline_class: Any | None = None, **kwargs: Any) -> AudioClassificationPipeline: ...
@overload
def pipeline(task: Literal["automatic-speech-recognition"], model: str | PreTrainedModel | None = None, config: str | PreTrainedConfig | None = None, tokenizer: str | PreTrainedTokenizer | PreTrainedTokenizerFast | None = None, feature_extractor: str | FeatureExtractionMixin | None = None, image_processor: str | BaseImageProcessor | None = None, video_processor: str | BaseVideoProcessor | None = None, processor: str | ProcessorMixin | None = None, revision: str | None = None, use_fast: bool = True, token: str | bool | None = None, device: int | str | torch.device | None = None, device_map: str | dict[str, int | str] | None = None, dtype: str | torch.dtype | None = "auto", trust_remote_code: bool | None = None, model_kwargs: dict[str, Any] | None = None, pipeline_class: Any | None = None, **kwargs: Any) -> AutomaticSpeechRecognitionPipeline: ...
@overload
def pipeline(task: Literal["decision"], model: str | PreTrainedModel | None = None, config: str | PreTrainedConfig | None = None, tokenizer: str | PreTrainedTokenizer | PreTrainedTokenizerFast | None = None, feature_extractor: str | FeatureExtractionMixin | None = None, image_processor: str | BaseImageProcessor | None = None, video_processor: str | BaseVideoProcessor | None = None, processor: str | ProcessorMixin | None = None, revision: str | None = None, use_fast: bool = True, token: str | bool | None = None, device: int | str | torch.device | None = None, device_map: str | dict[str, int | str] | None = None, dtype: str | torch.dtype | None = "auto", trust_remote_code: bool | None = None, model_kwargs: dict[str, Any] | None = None, pipeline_class: Any | None = None, **kwargs: Any) -> DecisionPipeline: ...
@overload
def pipeline(task: Literal["depth-estimation"], model: str | PreTrainedModel | None = None, config: str | PreTrainedConfig | None = None, tokenizer: str | PreTrainedTokenizer | PreTrainedTokenizerFast | None = None, feature_extractor: str | FeatureExtractionMixin | None = None, image_processor: str | BaseImageProcessor | None = None, video_processor: str | BaseVideoProcessor | None = None, processor: str | ProcessorMixin | None = None, revision: str | None = None, use_fast: bool = True, token: str | bool | None = None, device: int | str | torch.device | None = None, device_map: str | dict[str, int | str] | None = None, dtype: str | torch.dtype | None = "auto", trust_remote_code: bool | None = None, model_kwargs: dict[str, Any] | None = None, pipeline_class: Any | None = None, **kwargs: Any) -> DepthEstimationPipeline: ...
@overload
def pipeline(task: Literal["document-question-answering"], model: str | PreTrainedModel | None = None, config: str | PreTrainedConfig | None = None, tokenizer: str | PreTrainedTokenizer | PreTrainedTokenizerFast | None = None, feature_extractor: str | FeatureExtractionMixin | None = None, image_processor: str | BaseImageProcessor | None = None, video_processor: str | BaseVideoProcessor | None = None, processor: str | ProcessorMixin | None = None, revision: str | None = None, use_fast: bool = True, token: str | bool | None = None, device: int | str | torch.device | None = None, device_map: str | dict[str, int | str] | None = None, dtype: str | torch.dtype | None = "auto", trust_remote_code: bool | None = None, model_kwargs: dict[str, Any] | None = None, pipeline_class: Any | None = None, **kwargs: Any) -> DocumentQuestionAnsweringPipeline: ...
@overload
def pipeline(task: Literal["feature-extraction"], model: str | PreTrainedModel | None = None, config: str | PreTrainedConfig | None = None, tokenizer: str | PreTrainedTokenizer | PreTrainedTokenizerFast | None = None, feature_extractor: str | FeatureExtractionMixin | None = None, image_processor: str | BaseImageProcessor | None = None, video_processor: str | BaseVideoProcessor | None = None, processor: str | ProcessorMixin | None = None, revision: str | None = None, use_fast: bool = True, token: str | bool | None = None, device: int | str | torch.device | None = None, device_map: str | dict[str, int | str] | None = None, dtype: str | torch.dtype | None = "auto", trust_remote_code: bool | None = None, model_kwargs: dict[str, Any] | None = None, pipeline_class: Any | None = None, **kwargs: Any) -> FeatureExtractionPipeline: ...
@overload
def pipeline(task: Literal["fill-mask"], model: str | PreTrainedModel | None = None, config: str | PreTrainedConfig | None = None, tokenizer: str | PreTrainedTokenizer | PreTrainedTokenizerFast | None = None, feature_extractor: str | FeatureExtractionMixin | None = None, image_processor: str | BaseImageProcessor | None = None, video_processor: str | BaseVideoProcessor | None = None, processor: str | ProcessorMixin | None = None, revision: str | None = None, use_fast: bool = True, token: str | bool | None = None, device: int | str | torch.device | None = None, device_map: str | dict[str, int | str] | None = None, dtype: str | torch.dtype | None = "auto", trust_remote_code: bool | None = None, model_kwargs: dict[str, Any] | None = None, pipeline_class: Any | None = None, **kwargs: Any) -> FillMaskPipeline: ...
@overload
def pipeline(task: Literal["image-classification"], model: str | PreTrainedModel | None = None, config: str | PreTrainedConfig | None = None, tokenizer: str | PreTrainedTokenizer | PreTrainedTokenizerFast | None = None, feature_extractor: str | FeatureExtractionMixin | None = None, image_processor: str | BaseImageProcessor | None = None, video_processor: str | BaseVideoProcessor | None = None, processor: str | ProcessorMixin | None = None, revision: str | None = None, use_fast: bool = True, token: str | bool | None = None, device: int | str | torch.device | None = None, device_map: str | dict[str, int | str] | None = None, dtype: str | torch.dtype | None = "auto", trust_remote_code: bool | None = None, model_kwargs: dict[str, Any] | None = None, pipeline_class: Any | None = None, **kwargs: Any) -> ImageClassificationPipeline: ...
@overload
def pipeline(task: Literal["image-feature-extraction"], model: str | PreTrainedModel | None = None, config: str | PreTrainedConfig | None = None, tokenizer: str | PreTrainedTokenizer | PreTrainedTokenizerFast | None = None, feature_extractor: str | FeatureExtractionMixin | None = None, image_processor: str | BaseImageProcessor | None = None, video_processor: str | BaseVideoProcessor | None = None, processor: str | ProcessorMixin | None = None, revision: str | None = None, use_fast: bool = True, token: str | bool | None = None, device: int | str | torch.device | None = None, device_map: str | dict[str, int | str] | None = None, dtype: str | torch.dtype | None = "auto", trust_remote_code: bool | None = None, model_kwargs: dict[str, Any] | None = None, pipeline_class: Any | None = None, **kwargs: Any) -> ImageFeatureExtractionPipeline: ...
@overload
def pipeline(task: Literal["image-segmentation"], model: str | PreTrainedModel | None = None, config: str | PreTrainedConfig | None = None, tokenizer: str | PreTrainedTokenizer | PreTrainedTokenizerFast | None = None, feature_extractor: str | FeatureExtractionMixin | None = None, image_processor: str | BaseImageProcessor | None = None, video_processor: str | BaseVideoProcessor | None = None, processor: str | ProcessorMixin | None = None, revision: str | None = None, use_fast: bool = True, token: str | bool | None = None, device: int | str | torch.device | None = None, device_map: str | dict[str, int | str] | None = None, dtype: str | torch.dtype | None = "auto", trust_remote_code: bool | None = None, model_kwargs: dict[str, Any] | None = None, pipeline_class: Any | None = None, **kwargs: Any) -> ImageSegmentationPipeline: ...
@overload
def pipeline(task: Literal["image-text-to-text"], model: str | PreTrainedModel | None = None, config: str | PreTrainedConfig | None = None, tokenizer: str | PreTrainedTokenizer | PreTrainedTokenizerFast | None = None, feature_extractor: str | FeatureExtractionMixin | None = None, image_processor: str | BaseImageProcessor | None = None, video_processor: str | BaseVideoProcessor | None = None, processor: str | ProcessorMixin | None = None, revision: str | None = None, use_fast: bool = True, token: str | bool | None = None, device: int | str | torch.device | None = None, device_map: str | dict[str, int | str] | None = None, dtype: str | torch.dtype | None = "auto", trust_remote_code: bool | None = None, model_kwargs: dict[str, Any] | None = None, pipeline_class: Any | None = None, **kwargs: Any) -> ImageTextToTextPipeline: ...
@overload
def pipeline(task: Literal["keypoint-matching"], model: str | PreTrainedModel | None = None, config: str | PreTrainedConfig | None = None, tokenizer: str | PreTrainedTokenizer | PreTrainedTokenizerFast | None = None, feature_extractor: str | FeatureExtractionMixin | None = None, image_processor: str | BaseImageProcessor | None = None, video_processor: str | BaseVideoProcessor | None = None, processor: str | ProcessorMixin | None = None, revision: str | None = None, use_fast: bool = True, token: str | bool | None = None, device: int | str | torch.device | None = None, device_map: str | dict[str, int | str] | None = None, dtype: str | torch.dtype | None = "auto", trust_remote_code: bool | None = None, model_kwargs: dict[str, Any] | None = None, pipeline_class: Any | None = None, **kwargs: Any) -> KeypointMatchingPipeline: ...
@overload
def pipeline(task: Literal["mask-generation"], model: str | PreTrainedModel | None = None, config: str | PreTrainedConfig | None = None, tokenizer: str | PreTrainedTokenizer | PreTrainedTokenizerFast | None = None, feature_extractor: str | FeatureExtractionMixin | None = None, image_processor: str | BaseImageProcessor | None = None, video_processor: str | BaseVideoProcessor | None = None, processor: str | ProcessorMixin | None = None, revision: str | None = None, use_fast: bool = True, token: str | bool | None = None, device: int | str | torch.device | None = None, device_map: str | dict[str, int | str] | None = None, dtype: str | torch.dtype | None = "auto", trust_remote_code: bool | None = None, model_kwargs: dict[str, Any] | None = None, pipeline_class: Any | None = None, **kwargs: Any) -> MaskGenerationPipeline: ...
@overload
def pipeline(task: Literal["object-detection"], model: str | PreTrainedModel | None = None, config: str | PreTrainedConfig | None = None, tokenizer: str | PreTrainedTokenizer | PreTrainedTokenizerFast | None = None, feature_extractor: str | FeatureExtractionMixin | None = None, image_processor: str | BaseImageProcessor | None = None, video_processor: str | BaseVideoProcessor | None = None, processor: str | ProcessorMixin | None = None, revision: str | None = None, use_fast: bool = True, token: str | bool | None = None, device: int | str | torch.device | None = None, device_map: str | dict[str, int | str] | None = None, dtype: str | torch.dtype | None = "auto", trust_remote_code: bool | None = None, model_kwargs: dict[str, Any] | None = None, pipeline_class: Any | None = None, **kwargs: Any) -> ObjectDetectionPipeline: ...
@overload
def pipeline(task: Literal["table-question-answering"], model: str | PreTrainedModel | None = None, config: str | PreTrainedConfig | None = None, tokenizer: str | PreTrainedTokenizer | PreTrainedTokenizerFast | None = None, feature_extractor: str | FeatureExtractionMixin | None = None, image_processor: str | BaseImageProcessor | None = None, video_processor: str | BaseVideoProcessor | None = None, processor: str | ProcessorMixin | None = None, revision: str | None = None, use_fast: bool = True, token: str | bool | None = None, device: int | str | torch.device | None = None, device_map: str | dict[str, int | str] | None = None, dtype: str | torch.dtype | None = "auto", trust_remote_code: bool | None = None, model_kwargs: dict[str, Any] | None = None, pipeline_class: Any | None = None, **kwargs: Any) -> TableQuestionAnsweringPipeline: ...
@overload
def pipeline(task: Literal["text-classification"], model: str | PreTrainedModel | None = None, config: str | PreTrainedConfig | None = None, tokenizer: str | PreTrainedTokenizer | PreTrainedTokenizerFast | None = None, feature_extractor: str | FeatureExtractionMixin | None = None, image_processor: str | BaseImageProcessor | None = None, video_processor: str | BaseVideoProcessor | None = None, processor: str | ProcessorMixin | None = None, revision: str | None = None, use_fast: bool = True, token: str | bool | None = None, device: int | str | torch.device | None = None, device_map: str | dict[str, int | str] | None = None, dtype: str | torch.dtype | None = "auto", trust_remote_code: bool | None = None, model_kwargs: dict[str, Any] | None = None, pipeline_class: Any | None = None, **kwargs: Any) -> TextClassificationPipeline: ...
@overload
def pipeline(task: Literal["text-generation"], model: str | PreTrainedModel | None = None, config: str | PreTrainedConfig | None = None, tokenizer: str | PreTrainedTokenizer | PreTrainedTokenizerFast | None = None, feature_extractor: str | FeatureExtractionMixin | None = None, image_processor: str | BaseImageProcessor | None = None, video_processor: str | BaseVideoProcessor | None = None, processor: str | ProcessorMixin | None = None, revision: str | None = None, use_fast: bool = True, token: str | bool | None = None, device: int | str | torch.device | None = None, device_map: str | dict[str, int | str] | None = None, dtype: str | torch.dtype | None = "auto", trust_remote_code: bool | None = None, model_kwargs: dict[str, Any] | None = None, pipeline_class: Any | None = None, **kwargs: Any) -> TextGenerationPipeline: ...
@overload
def pipeline(task: Literal["text-to-audio"], model: str | PreTrainedModel | None = None, config: str | PreTrainedConfig | None = None, tokenizer: str | PreTrainedTokenizer | PreTrainedTokenizerFast | None = None, feature_extractor: str | FeatureExtractionMixin | None = None, image_processor: str | BaseImageProcessor | None = None, video_processor: str | BaseVideoProcessor | None = None, processor: str | ProcessorMixin | None = None, revision: str | None = None, use_fast: bool = True, token: str | bool | None = None, device: int | str | torch.device | None = None, device_map: str | dict[str, int | str] | None = None, dtype: str | torch.dtype | None = "auto", trust_remote_code: bool | None = None, model_kwargs: dict[str, Any] | None = None, pipeline_class: Any | None = None, **kwargs: Any) -> TextToAudioPipeline: ...
@overload
def pipeline(task: Literal["token-classification"], model: str | PreTrainedModel | None = None, config: str | PreTrainedConfig | None = None, tokenizer: str | PreTrainedTokenizer | PreTrainedTokenizerFast | None = None, feature_extractor: str | FeatureExtractionMixin | None = None, image_processor: str | BaseImageProcessor | None = None, video_processor: str | BaseVideoProcessor | None = None, processor: str | ProcessorMixin | None = None, revision: str | None = None, use_fast: bool = True, token: str | bool | None = None, device: int | str | torch.device | None = None, device_map: str | dict[str, int | str] | None = None, dtype: str | torch.dtype | None = "auto", trust_remote_code: bool | None = None, model_kwargs: dict[str, Any] | None = None, pipeline_class: Any | None = None, **kwargs: Any) -> TokenClassificationPipeline: ...
@overload
def pipeline(task: Literal["video-classification"], model: str | PreTrainedModel | None = None, config: str | PreTrainedConfig | None = None, tokenizer: str | PreTrainedTokenizer | PreTrainedTokenizerFast | None = None, feature_extractor: str | FeatureExtractionMixin | None = None, image_processor: str | BaseImageProcessor | None = None, video_processor: str | BaseVideoProcessor | None = None, processor: str | ProcessorMixin | None = None, revision: str | None = None, use_fast: bool = True, token: str | bool | None = None, device: int | str | torch.device | None = None, device_map: str | dict[str, int | str] | None = None, dtype: str | torch.dtype | None = "auto", trust_remote_code: bool | None = None, model_kwargs: dict[str, Any] | None = None, pipeline_class: Any | None = None, **kwargs: Any) -> VideoClassificationPipeline: ...
@overload
def pipeline(task: Literal["zero-shot-audio-classification"], model: str | PreTrainedModel | None = None, config: str | PreTrainedConfig | None = None, tokenizer: str | PreTrainedTokenizer | PreTrainedTokenizerFast | None = None, feature_extractor: str | FeatureExtractionMixin | None = None, image_processor: str | BaseImageProcessor | None = None, video_processor: str | BaseVideoProcessor | None = None, processor: str | ProcessorMixin | None = None, revision: str | None = None, use_fast: bool = True, token: str | bool | None = None, device: int | str | torch.device | None = None, device_map: str | dict[str, int | str] | None = None, dtype: str | torch.dtype | None = "auto", trust_remote_code: bool | None = None, model_kwargs: dict[str, Any] | None = None, pipeline_class: Any | None = None, **kwargs: Any) -> ZeroShotAudioClassificationPipeline: ...
@overload
def pipeline(task: Literal["zero-shot-classification"], model: str | PreTrainedModel | None = None, config: str | PreTrainedConfig | None = None, tokenizer: str | PreTrainedTokenizer | PreTrainedTokenizerFast | None = None, feature_extractor: str | FeatureExtractionMixin | None = None, image_processor: str | BaseImageProcessor | None = None, video_processor: str | BaseVideoProcessor | None = None, processor: str | ProcessorMixin | None = None, revision: str | None = None, use_fast: bool = True, token: str | bool | None = None, device: int | str | torch.device | None = None, device_map: str | dict[str, int | str] | None = None, dtype: str | torch.dtype | None = "auto", trust_remote_code: bool | None = None, model_kwargs: dict[str, Any] | None = None, pipeline_class: Any | None = None, **kwargs: Any) -> ZeroShotClassificationPipeline: ...
@overload
def pipeline(task: Literal["zero-shot-image-classification"], model: str | PreTrainedModel | None = None, config: str | PreTrainedConfig | None = None, tokenizer: str | PreTrainedTokenizer | PreTrainedTokenizerFast | None = None, feature_extractor: str | FeatureExtractionMixin | None = None, image_processor: str | BaseImageProcessor | None = None, video_processor: str | BaseVideoProcessor | None = None, processor: str | ProcessorMixin | None = None, revision: str | None = None, use_fast: bool = True, token: str | bool | None = None, device: int | str | torch.device | None = None, device_map: str | dict[str, int | str] | None = None, dtype: str | torch.dtype | None = "auto", trust_remote_code: bool | None = None, model_kwargs: dict[str, Any] | None = None, pipeline_class: Any | None = None, **kwargs: Any) -> ZeroShotImageClassificationPipeline: ...
@overload
def pipeline(task: Literal["zero-shot-object-detection"], model: str | PreTrainedModel | None = None, config: str | PreTrainedConfig | None = None, tokenizer: str | PreTrainedTokenizer | PreTrainedTokenizerFast | None = None, feature_extractor: str | FeatureExtractionMixin | None = None, image_processor: str | BaseImageProcessor | None = None, video_processor: str | BaseVideoProcessor | None = None, processor: str | ProcessorMixin | None = None, revision: str | None = None, use_fast: bool = True, token: str | bool | None = None, device: int | str | torch.device | None = None, device_map: str | dict[str, int | str] | None = None, dtype: str | torch.dtype | None = "auto", trust_remote_code: bool | None = None, model_kwargs: dict[str, Any] | None = None, pipeline_class: Any | None = None, **kwargs: Any) -> ZeroShotObjectDetectionPipeline: ...
# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
# The part of the file above was automatically generated from the code.
# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
# fmt: on
# </generated-code>
def _load_pipeline_component(load_flag, component, loader):
"""Load an optional pipeline component, preserving the original soft-failure behavior."""
if not (load_flag or load_flag is None):
return component
try:
return loader(component)
except Exception:
if load_flag:
raise
return None
def _infer_pipeline_component(
component,
model_name,
config,
error_message,
fallback_component=None,
):
"""Infer a component identifier from explicit input, then model/config fallbacks."""
if component is not None:
return component
if isinstance(model_name, str):
return model_name
if isinstance(config, str):
return config
if fallback_component is not None:
return fallback_component
raise Exception(error_message)
def _get_tokenizer_loading_kwargs(tokenizer, use_fast, model_kwargs):
"""Normalize tokenizer tuple/string inputs into `AutoTokenizer.from_pretrained` kwargs."""
if isinstance(tokenizer, tuple):
tokenizer_identifier = tokenizer[0]
tokenizer_kwargs = tokenizer[1].copy()
tokenizer_use_fast = tokenizer_kwargs.pop("use_fast", use_fast)
else:
tokenizer_identifier = tokenizer
tokenizer_kwargs = model_kwargs.copy()
tokenizer_kwargs.pop("torch_dtype", None)
tokenizer_kwargs.pop("dtype", None)
tokenizer_use_fast = use_fast
return tokenizer_identifier, tokenizer_kwargs, tokenizer_use_fast
def _resolve_tokenizer(tokenizer, load_tokenizer, use_fast, model_name, config, task, hub_kwargs, model_kwargs):
"""Resolve and optionally load the tokenizer required by the pipeline class."""
def load(tokenizer):
tokenizer = _infer_pipeline_component(
tokenizer,
model_name,
config,
"Impossible to guess which tokenizer to use. "
"Please provide a PreTrainedTokenizer class or a path/identifier to a pretrained tokenizer.",
)
if not isinstance(tokenizer, (str, tuple)):
return tokenizer
tokenizer_identifier, tokenizer_kwargs, tokenizer_use_fast = _get_tokenizer_loading_kwargs(
tokenizer, use_fast, model_kwargs
)
return AutoTokenizer.from_pretrained(
tokenizer_identifier,
use_fast=tokenizer_use_fast,
_from_pipeline=task,
**hub_kwargs,
**tokenizer_kwargs,
)
return _load_pipeline_component(load_tokenizer, tokenizer, load)
def _resolve_image_processor(
image_processor,
feature_extractor,
load_image_processor,
model_name,
config,
task,
hub_kwargs,
model_kwargs,
):
"""Resolve and optionally load the image processor for vision-capable pipelines."""
def load(image_processor):
image_processor = _infer_pipeline_component(
image_processor,
model_name,
config,
"Impossible to guess which image processor to use. "
"Please provide a PreTrainedImageProcessor class or a path/identifier to a pretrained image processor.",
fallback_component=feature_extractor if isinstance(feature_extractor, BaseImageProcessor) else None,
)
if not isinstance(image_processor, (str, tuple)):
return image_processor
return AutoImageProcessor.from_pretrained(image_processor, _from_pipeline=task, **hub_kwargs, **model_kwargs)
return _load_pipeline_component(load_image_processor, image_processor, load)
def _resolve_video_processor(
video_processor,
load_video_processor,
model_name,
config,
task,
hub_kwargs,
model_kwargs,
):
def load(video_processor):
video_processor = _infer_pipeline_component(
video_processor,
model_name,
config,
"Impossible to guess which video processor to use. "
"Please provide a BaseVideoProcessor class or a path/identifier to a pretrained video processor.",
)
if not isinstance(video_processor, str):
return video_processor
return AutoVideoProcessor.from_pretrained(video_processor, _from_pipeline=task, **hub_kwargs, **model_kwargs)
return _load_pipeline_component(load_video_processor, video_processor, load)
def _maybe_load_ctc_decoder(model_name, hub_kwargs, kwargs, pretrained_model_name_or_path):
"""Attach a pyctcdecode decoder when the loaded feature extractor declares an LM-backed processor."""
config_dict, _ = FeatureExtractionMixin.get_feature_extractor_dict(
pretrained_model_name_or_path or model_name,
**hub_kwargs,
)
processor_class = config_dict.get("processor_class", None)
if processor_class is None or not processor_class.endswith("WithLM") or not isinstance(model_name, str):
return
try:
import kenlm # to trigger `ImportError` if not installed
from pyctcdecode import BeamSearchDecoderCTC
if os.path.isdir(model_name) or os.path.isfile(model_name):
decoder = BeamSearchDecoderCTC.load_from_dir(model_name)
else:
language_model_glob = os.path.join(BeamSearchDecoderCTC._LANGUAGE_MODEL_SERIALIZED_DIRECTORY, "*")
alphabet_filename = BeamSearchDecoderCTC._ALPHABET_SERIALIZED_FILENAME
allow_patterns = [language_model_glob, alphabet_filename]
decoder = BeamSearchDecoderCTC.load_from_hf_hub(model_name, allow_patterns=allow_patterns)
kwargs["decoder"] = decoder
except ImportError as error:
logger.warning(f"Could not load the `decoder` for {model_name}. Defaulting to raw CTC. Error: {error}")
if not is_kenlm_available():
logger.warning("Try to install `kenlm`: `pip install kenlm")
if not is_pyctcdecode_available():
logger.warning("Try to install `pyctcdecode`: `pip install pyctcdecode")
def _resolve_feature_extractor(
feature_extractor,
load_feature_extractor,
model_name,
config,
task,
hub_kwargs,
model_kwargs,
kwargs,
pretrained_model_name_or_path,
):
"""Resolve and optionally load the feature extractor, including CTC decoder side-loading."""
def load(feature_extractor):
feature_extractor = _infer_pipeline_component(
feature_extractor,
model_name,
config,
"Impossible to guess which feature extractor to use. "
"Please provide a PreTrainedFeatureExtractor class or a path/identifier to a pretrained feature extractor.",
)
if not isinstance(feature_extractor, (str, tuple)):
return feature_extractor
feature_extractor = AutoFeatureExtractor.from_pretrained(
feature_extractor, _from_pipeline=task, **hub_kwargs, **model_kwargs
)
_maybe_load_ctc_decoder(model_name, hub_kwargs, kwargs, pretrained_model_name_or_path)
return feature_extractor
return _load_pipeline_component(load_feature_extractor, feature_extractor, load)
def _resolve_processor(processor, load_processor, model_name, config, task, hub_kwargs, model_kwargs):
"""Resolve and optionally load a multimodal processor."""
def load(processor):
processor = _infer_pipeline_component(
processor,
model_name,
config,
"Impossible to guess which processor to use. "
"Please provide a processor instance or a path/identifier to a processor.",
)
if not isinstance(processor, (str, tuple)):
return processor
processor = AutoProcessor.from_pretrained(processor, _from_pipeline=task, **hub_kwargs, **model_kwargs)
if not isinstance(processor, ProcessorMixin):
raise TypeError(
"Processor was loaded, but it is not an instance of `ProcessorMixin`. "
f"Got type `{type(processor)}` instead. Please check that you specified "
"correct pipeline task for the model and model has processor implemented and saved."
)
return processor
return _load_pipeline_component(load_processor, processor, load)
def pipeline(
task: str | None = None,
model: str | PreTrainedModel | None = None,
config: str | PreTrainedConfig | None = None,
tokenizer: str | PreTrainedTokenizer | PreTrainedTokenizerFast | None = None,
feature_extractor: str | FeatureExtractionMixin | None = None,
image_processor: str | BaseImageProcessor | None = None,
video_processor: str | BaseVideoProcessor | None = None,
processor: str | ProcessorMixin | None = None,
revision: str | None = None,
use_fast: bool = True,
token: str | bool | None = None,
device: int | str | torch.device | None = None,
device_map: str | dict[str, int | str] | None = None,
dtype: str | torch.dtype | None = "auto",
trust_remote_code: bool | None = None,
model_kwargs: dict[str, Any] | None = None,
pipeline_class: Any | None = None,
**kwargs: Any,
) -> Pipeline:
"""
Utility factory method to build a [`Pipeline`].
A pipeline consists of:
- One or more components for pre-processing model inputs, such as a [tokenizer](tokenizer),
[image_processor](image_processor), [feature_extractor](feature_extractor), or [processor](processors).
- A [model](model) that generates predictions from the inputs.
- Optional post-processing steps to refine the model's output, which can also be handled by processors.
<Tip>
While there are such optional arguments as `tokenizer`, `feature_extractor`, `image_processor`, and `processor`,
they shouldn't be specified all at once. If these components are not provided, `pipeline` will try to load
required ones automatically. In case you want to provide these components explicitly, please refer to a
specific pipeline in order to get more details regarding what components are required.
</Tip>
Args:
task (`str`):
The task defining which pipeline will be returned. Currently accepted tasks are:
- `"audio-classification"`: will return a [`AudioClassificationPipeline`].
- `"automatic-speech-recognition"`: will return a [`AutomaticSpeechRecognitionPipeline`].
- `"decision"`: will return a [`DecisionPipeline`].
- `"depth-estimation"`: will return a [`DepthEstimationPipeline`].
- `"document-question-answering"`: will return a [`DocumentQuestionAnsweringPipeline`].
- `"feature-extraction"`: will return a [`FeatureExtractionPipeline`].
- `"fill-mask"`: will return a [`FillMaskPipeline`]:.
- `"image-classification"`: will return a [`ImageClassificationPipeline`].
- `"image-feature-extraction"`: will return an [`ImageFeatureExtractionPipeline`].
- `"image-segmentation"`: will return a [`ImageSegmentationPipeline`].
- `"image-text-to-text"`: will return a [`ImageTextToTextPipeline`].
- `"keypoint-matching"`: will return a [`KeypointMatchingPipeline`].
- `"mask-generation"`: will return a [`MaskGenerationPipeline`].
- `"object-detection"`: will return a [`ObjectDetectionPipeline`].
- `"table-question-answering"`: will return a [`TableQuestionAnsweringPipeline`].
- `"text-classification"` (alias `"sentiment-analysis"` available): will return a
[`TextClassificationPipeline`].
- `"text-generation"`: will return a [`TextGenerationPipeline`]:.
- `"text-to-audio"` (alias `"text-to-speech"` available): will return a [`TextToAudioPipeline`]:.
- `"token-classification"` (alias `"ner"` available): will return a [`TokenClassificationPipeline`].
- `"video-classification"`: will return a [`VideoClassificationPipeline`].
- `"zero-shot-classification"`: will return a [`ZeroShotClassificationPipeline`].
- `"zero-shot-image-classification"`: will return a [`ZeroShotImageClassificationPipeline`].
- `"zero-shot-audio-classification"`: will return a [`ZeroShotAudioClassificationPipeline`].
- `"zero-shot-object-detection"`: will return a [`ZeroShotObjectDetectionPipeline`].
model (`str` or [`PreTrainedModel`], *optional*):
The model that will be used by the pipeline to make predictions. This can be a model identifier or an
actual instance of a pretrained model inheriting from [`PreTrainedModel`].
If not provided, the default for the `task` will be loaded.
config (`str` or [`PreTrainedConfig`], *optional*):
The configuration that will be used by the pipeline to instantiate the model. This can be a model
identifier or an actual pretrained model configuration inheriting from [`PreTrainedConfig`].
If not provided, the default configuration file for the requested model will be used. That means that if
`model` is given, its default configuration will be used. However, if `model` is not supplied, this
`task`'s default model's config is used instead.
tokenizer (`str` or [`PreTrainedTokenizer`], *optional*):
The tokenizer that will be used by the pipeline to encode data for the model. This can be a model
identifier or an actual pretrained tokenizer inheriting from [`PreTrainedTokenizer`].
If not provided, the default tokenizer for the given `model` will be loaded (if it is a string). If `model`
is not specified or not a string, then the default tokenizer for `config` is loaded (if it is a string).
However, if `config` is also not given or not a string, then the default tokenizer for the given `task`
will be loaded.
feature_extractor (`str` or [`FeatureExtractionMixin`], *optional*):
The feature extractor that will be used by the pipeline to encode data for the model. This can be a model
identifier or an actual pretrained feature extractor inheriting from [`FeatureExtractionMixin`].
Feature extractors are used for non-NLP models, such as Speech or Vision models as well as multi-modal
models. Multi-modal models will also require a tokenizer to be passed.
If not provided, the default feature extractor for the given `model` will be loaded (if it is a string). If
`model` is not specified or not a string, then the default feature extractor for `config` is loaded (if it
is a string). However, if `config` is also not given or not a string, then the default feature extractor
for the given `task` will be loaded.
image_processor (`str` or [`BaseImageProcessor`], *optional*):
The image processor that will be used by the pipeline to preprocess images for the model. This can be a
model identifier or an actual image processor inheriting from [`BaseImageProcessor`].
Image processors are used for Vision models and multi-modal models that require image inputs. Multi-modal
models will also require a tokenizer to be passed.
If not provided, the default image processor for the given `model` will be loaded (if it is a string). If
`model` is not specified or not a string, then the default image processor for `config` is loaded (if it is
a string).
processor (`str` or [`ProcessorMixin`], *optional*):
The processor that will be used by the pipeline to preprocess data for the model. This can be a model
identifier or an actual processor inheriting from [`ProcessorMixin`].
Processors are used for multi-modal models that require multi-modal inputs, for example, a model that
requires both text and image inputs.
If not provided, the default processor for the given `model` will be loaded (if it is a string). If `model`
is not specified or not a string, then the default processor for `config` is loaded (if it is a string).
revision (`str`, *optional*, defaults to `"main"`):
When passing a task name or a string model identifier: The specific model version to use. It can be a
branch name, a tag name, or a commit id, since we use a git-based system for storing models and other
artifacts on huggingface.co, so `revision` can be any identifier allowed by git.
use_fast (`bool`, *optional*, defaults to `True`):
Whether or not to use a Fast tokenizer if possible (a [`PreTrainedTokenizerFast`]).
token (`str` or *bool*, *optional*):
The token to use as HTTP bearer authorization for remote files. If `True`, will use the token generated
when running `hf auth login`.
device (`int` or `str` or `torch.device`, *optional*):
Defines the device (*e.g.*, `"cpu"`, `"cuda:1"`, `"mps"`, or a GPU ordinal rank like `1`) on which this
pipeline will be allocated. When left unset, the pipeline is automatically placed on the first available
accelerator (CUDA, MPS, XPU, ...) and only falls back to CPU when none is available; the model is moved
there for you. Pass `device="cpu"` (or `-1`) to force CPU. Cannot be used together with `device_map`.
device_map (`str` or `dict[str, Union[int, str, torch.device]`, *optional*):
Sent directly as `model_kwargs` (just a simpler shortcut). When `accelerate` library is present, set
`device_map="auto"` to compute the most optimized `device_map` automatically (see
[here](https://huggingface.co/docs/accelerate/main/en/package_reference/big_modeling#accelerate.cpu_offload)
for more information).
<Tip warning={true}>
Do not use `device_map` AND `device` at the same time as they will conflict
</Tip>
dtype (`str` or `torch.dtype`, *optional*, defaults to `"auto"`):
Precision the model is loaded in, forwarded to `from_pretrained`. Defaults to `"auto"`, which loads the
model in the dtype it was saved in. Pass an explicit `torch.float16`, `torch.bfloat16`, `torch.float32`,
... to override it.
trust_remote_code (`bool`, *optional*, defaults to `False`):
Whether or not to allow for custom code defined on the Hub in their own modeling, configuration,
tokenization or even pipeline files. This option should only be set to `True` for repositories you trust
and in which you have read the code, as it will execute code present on the Hub on your local machine.
model_kwargs (`dict[str, Any]`, *optional*):
Additional dictionary of keyword arguments passed along to the model's `from_pretrained(...,
**model_kwargs)` function.
kwargs (`dict[str, Any]`, *optional*):
Additional keyword arguments passed along to the specific pipeline init (see the documentation for the
corresponding pipeline class for possible values).
Returns:
[`Pipeline`]: A suitable pipeline for the task.
Examples:
```python
>>> from transformers import pipeline, AutoModelForTokenClassification, AutoTokenizer
>>> # Sentiment analysis pipeline
>>> analyzer = pipeline("sentiment-analysis")
>>> # Named entity recognition pipeline, passing in a specific model and tokenizer
>>> model = AutoModelForTokenClassification.from_pretrained("dbmdz/bert-large-cased-finetuned-conll03-english")
>>> tokenizer = AutoTokenizer.from_pretrained("google-bert/bert-base-cased")
>>> recognizer = pipeline("ner", model=model, tokenizer=tokenizer)
```"""
if model_kwargs is None:
model_kwargs = {}
code_revision = kwargs.pop("code_revision", None)
if "code_revision" in model_kwargs:
if code_revision is not None:
raise ValueError(
'You cannot use both `pipeline(... code_revision=..., model_kwargs={"code_revision":...})` as those'
" arguments might conflict, use only one."
)
code_revision = model_kwargs.pop("code_revision")
kwargs.pop("_commit_hash", None) # BC: not used anymore, `revision` is resolved to a commit hash instead
local_files_only = kwargs.get("local_files_only", False)
requested_revision = revision
hub_kwargs = {
"revision": revision,
"token": token,
"trust_remote_code": trust_remote_code,
"local_files_only": local_files_only,
"code_revision": code_revision,
}
if task is None and model is None:
raise RuntimeError(
"Impossible to instantiate a pipeline without either a task or a model "
"being specified. "
"Please provide a task class or a model"
)
if model is None and tokenizer is not None:
raise RuntimeError(
"Impossible to instantiate a pipeline with tokenizer specified but not the model as the provided tokenizer"
" may not be compatible with the default model. Please provide a PreTrainedModel class or a"
" path/identifier to a pretrained model when providing tokenizer."
)
if model is None and feature_extractor is not None:
raise RuntimeError(
"Impossible to instantiate a pipeline with feature_extractor specified but not the model as the provided"
" feature_extractor may not be compatible with the default model. Please provide a PreTrainedModel class"
" or a path/identifier to a pretrained model when providing feature_extractor."
)
if isinstance(model, Path):
model = str(model)
pretrained_model_name_or_path = None
if isinstance(config, str):
pretrained_model_name_or_path = config
elif config is None and isinstance(model, str):
pretrained_model_name_or_path = model
if pretrained_model_name_or_path is not None:
# Resolve the revision of the model repository once. Everything loaded from that repository below (config,
# remote code, weights, and the components that default to it) then uses this immutable commit.
hub_kwargs["revision"] = resolve_revision(
pretrained_model_name_or_path,
revision,
token=token,
local_files_only=local_files_only,
cache_dir=model_kwargs.get("cache_dir"),
)
# Config is the primordial information item.
# Instantiate config if needed
adapter_path = None