__init__.py 83 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229
  1. # coding=utf-8
  2. # Copyright 2018 The HuggingFace Inc. team.
  3. #
  4. # Licensed under the Apache License, Version 2.0 (the "License");
  5. # you may not use this file except in compliance with the License.
  6. # You may obtain a copy of the License at
  7. #
  8. # http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. import json
  16. import os
  17. import warnings
  18. from pathlib import Path
  19. from typing import TYPE_CHECKING, Any, Optional, Union
  20. from huggingface_hub import model_info
  21. from ..configuration_utils import PretrainedConfig
  22. from ..dynamic_module_utils import get_class_from_dynamic_module
  23. from ..feature_extraction_utils import PreTrainedFeatureExtractor
  24. from ..image_processing_utils import BaseImageProcessor
  25. from ..models.auto.configuration_auto import AutoConfig
  26. from ..models.auto.feature_extraction_auto import FEATURE_EXTRACTOR_MAPPING, AutoFeatureExtractor
  27. from ..models.auto.image_processing_auto import IMAGE_PROCESSOR_MAPPING, AutoImageProcessor
  28. from ..models.auto.modeling_auto import AutoModelForDepthEstimation, AutoModelForImageToImage
  29. from ..models.auto.processing_auto import PROCESSOR_MAPPING, AutoProcessor
  30. from ..models.auto.tokenization_auto import TOKENIZER_MAPPING, AutoTokenizer
  31. from ..processing_utils import ProcessorMixin
  32. from ..tokenization_utils import PreTrainedTokenizer
  33. from ..utils import (
  34. CONFIG_NAME,
  35. HUGGINGFACE_CO_RESOLVE_ENDPOINT,
  36. cached_file,
  37. extract_commit_hash,
  38. find_adapter_config_file,
  39. is_kenlm_available,
  40. is_offline_mode,
  41. is_peft_available,
  42. is_pyctcdecode_available,
  43. is_tf_available,
  44. is_torch_available,
  45. logging,
  46. )
  47. from .audio_classification import AudioClassificationPipeline
  48. from .automatic_speech_recognition import AutomaticSpeechRecognitionPipeline
  49. from .base import (
  50. ArgumentHandler,
  51. CsvPipelineDataFormat,
  52. JsonPipelineDataFormat,
  53. PipedPipelineDataFormat,
  54. Pipeline,
  55. PipelineDataFormat,
  56. PipelineException,
  57. PipelineRegistry,
  58. get_default_model_and_revision,
  59. infer_framework_load_model,
  60. )
  61. from .depth_estimation import DepthEstimationPipeline
  62. from .document_question_answering import DocumentQuestionAnsweringPipeline
  63. from .feature_extraction import FeatureExtractionPipeline
  64. from .fill_mask import FillMaskPipeline
  65. from .image_classification import ImageClassificationPipeline
  66. from .image_feature_extraction import ImageFeatureExtractionPipeline
  67. from .image_segmentation import ImageSegmentationPipeline
  68. from .image_text_to_text import ImageTextToTextPipeline
  69. from .image_to_image import ImageToImagePipeline
  70. from .image_to_text import ImageToTextPipeline
  71. from .keypoint_matching import KeypointMatchingPipeline
  72. from .mask_generation import MaskGenerationPipeline
  73. from .object_detection import ObjectDetectionPipeline
  74. from .question_answering import QuestionAnsweringArgumentHandler, QuestionAnsweringPipeline
  75. from .table_question_answering import TableQuestionAnsweringArgumentHandler, TableQuestionAnsweringPipeline
  76. from .text2text_generation import SummarizationPipeline, Text2TextGenerationPipeline, TranslationPipeline
  77. from .text_classification import TextClassificationPipeline
  78. from .text_generation import TextGenerationPipeline
  79. from .text_to_audio import TextToAudioPipeline
  80. from .token_classification import (
  81. AggregationStrategy,
  82. NerPipeline,
  83. TokenClassificationArgumentHandler,
  84. TokenClassificationPipeline,
  85. )
  86. from .video_classification import VideoClassificationPipeline
  87. from .visual_question_answering import VisualQuestionAnsweringPipeline
  88. from .zero_shot_audio_classification import ZeroShotAudioClassificationPipeline
  89. from .zero_shot_classification import ZeroShotClassificationArgumentHandler, ZeroShotClassificationPipeline
  90. from .zero_shot_image_classification import ZeroShotImageClassificationPipeline
  91. from .zero_shot_object_detection import ZeroShotObjectDetectionPipeline
  92. if is_tf_available():
  93. import tensorflow as tf
  94. from ..models.auto.modeling_tf_auto import (
  95. TFAutoModel,
  96. TFAutoModelForCausalLM,
  97. TFAutoModelForImageClassification,
  98. TFAutoModelForMaskedLM,
  99. TFAutoModelForQuestionAnswering,
  100. TFAutoModelForSeq2SeqLM,
  101. TFAutoModelForSequenceClassification,
  102. TFAutoModelForTableQuestionAnswering,
  103. TFAutoModelForTokenClassification,
  104. TFAutoModelForVision2Seq,
  105. TFAutoModelForZeroShotImageClassification,
  106. )
  107. if is_torch_available():
  108. import torch
  109. from ..models.auto.modeling_auto import (
  110. AutoModel,
  111. AutoModelForAudioClassification,
  112. AutoModelForCausalLM,
  113. AutoModelForCTC,
  114. AutoModelForDocumentQuestionAnswering,
  115. AutoModelForImageClassification,
  116. AutoModelForImageSegmentation,
  117. AutoModelForImageTextToText,
  118. AutoModelForKeypointMatching,
  119. AutoModelForMaskedLM,
  120. AutoModelForMaskGeneration,
  121. AutoModelForObjectDetection,
  122. AutoModelForQuestionAnswering,
  123. AutoModelForSemanticSegmentation,
  124. AutoModelForSeq2SeqLM,
  125. AutoModelForSequenceClassification,
  126. AutoModelForSpeechSeq2Seq,
  127. AutoModelForTableQuestionAnswering,
  128. AutoModelForTextToSpectrogram,
  129. AutoModelForTextToWaveform,
  130. AutoModelForTokenClassification,
  131. AutoModelForVideoClassification,
  132. AutoModelForVision2Seq,
  133. AutoModelForVisualQuestionAnswering,
  134. AutoModelForZeroShotImageClassification,
  135. AutoModelForZeroShotObjectDetection,
  136. )
  137. if TYPE_CHECKING:
  138. from ..modeling_tf_utils import TFPreTrainedModel
  139. from ..modeling_utils import PreTrainedModel
  140. from ..tokenization_utils_fast import PreTrainedTokenizerFast
  141. logger = logging.get_logger(__name__)
  142. # Register all the supported tasks here
  143. TASK_ALIASES = {
  144. "sentiment-analysis": "text-classification",
  145. "ner": "token-classification",
  146. "vqa": "visual-question-answering",
  147. "text-to-speech": "text-to-audio",
  148. }
  149. SUPPORTED_TASKS = {
  150. "audio-classification": {
  151. "impl": AudioClassificationPipeline,
  152. "tf": (),
  153. "pt": (AutoModelForAudioClassification,) if is_torch_available() else (),
  154. "default": {"model": {"pt": ("superb/wav2vec2-base-superb-ks", "372e048")}},
  155. "type": "audio",
  156. },
  157. "automatic-speech-recognition": {
  158. "impl": AutomaticSpeechRecognitionPipeline,
  159. "tf": (),
  160. "pt": (AutoModelForCTC, AutoModelForSpeechSeq2Seq) if is_torch_available() else (),
  161. "default": {"model": {"pt": ("facebook/wav2vec2-base-960h", "22aad52")}},
  162. "type": "multimodal",
  163. },
  164. "text-to-audio": {
  165. "impl": TextToAudioPipeline,
  166. "tf": (),
  167. "pt": (AutoModelForTextToWaveform, AutoModelForTextToSpectrogram) if is_torch_available() else (),
  168. "default": {"model": {"pt": ("suno/bark-small", "1dbd7a1")}},
  169. "type": "text",
  170. },
  171. "feature-extraction": {
  172. "impl": FeatureExtractionPipeline,
  173. "tf": (TFAutoModel,) if is_tf_available() else (),
  174. "pt": (AutoModel,) if is_torch_available() else (),
  175. "default": {
  176. "model": {
  177. "pt": ("distilbert/distilbert-base-cased", "6ea8117"),
  178. "tf": ("distilbert/distilbert-base-cased", "6ea8117"),
  179. }
  180. },
  181. "type": "multimodal",
  182. },
  183. "text-classification": {
  184. "impl": TextClassificationPipeline,
  185. "tf": (TFAutoModelForSequenceClassification,) if is_tf_available() else (),
  186. "pt": (AutoModelForSequenceClassification,) if is_torch_available() else (),
  187. "default": {
  188. "model": {
  189. "pt": ("distilbert/distilbert-base-uncased-finetuned-sst-2-english", "714eb0f"),
  190. "tf": ("distilbert/distilbert-base-uncased-finetuned-sst-2-english", "714eb0f"),
  191. },
  192. },
  193. "type": "text",
  194. },
  195. "token-classification": {
  196. "impl": TokenClassificationPipeline,
  197. "tf": (TFAutoModelForTokenClassification,) if is_tf_available() else (),
  198. "pt": (AutoModelForTokenClassification,) if is_torch_available() else (),
  199. "default": {
  200. "model": {
  201. "pt": ("dbmdz/bert-large-cased-finetuned-conll03-english", "4c53496"),
  202. "tf": ("dbmdz/bert-large-cased-finetuned-conll03-english", "4c53496"),
  203. },
  204. },
  205. "type": "text",
  206. },
  207. "question-answering": {
  208. "impl": QuestionAnsweringPipeline,
  209. "tf": (TFAutoModelForQuestionAnswering,) if is_tf_available() else (),
  210. "pt": (AutoModelForQuestionAnswering,) if is_torch_available() else (),
  211. "default": {
  212. "model": {
  213. "pt": ("distilbert/distilbert-base-cased-distilled-squad", "564e9b5"),
  214. "tf": ("distilbert/distilbert-base-cased-distilled-squad", "564e9b5"),
  215. },
  216. },
  217. "type": "text",
  218. },
  219. "table-question-answering": {
  220. "impl": TableQuestionAnsweringPipeline,
  221. "pt": (AutoModelForTableQuestionAnswering,) if is_torch_available() else (),
  222. "tf": (TFAutoModelForTableQuestionAnswering,) if is_tf_available() else (),
  223. "default": {
  224. "model": {
  225. "pt": ("google/tapas-base-finetuned-wtq", "e3dde19"),
  226. "tf": ("google/tapas-base-finetuned-wtq", "e3dde19"),
  227. },
  228. },
  229. "type": "text",
  230. },
  231. "visual-question-answering": {
  232. "impl": VisualQuestionAnsweringPipeline,
  233. "pt": (AutoModelForVisualQuestionAnswering,) if is_torch_available() else (),
  234. "tf": (),
  235. "default": {
  236. "model": {"pt": ("dandelin/vilt-b32-finetuned-vqa", "d0a1f6a")},
  237. },
  238. "type": "multimodal",
  239. },
  240. "document-question-answering": {
  241. "impl": DocumentQuestionAnsweringPipeline,
  242. "pt": (AutoModelForDocumentQuestionAnswering,) if is_torch_available() else (),
  243. "tf": (),
  244. "default": {
  245. "model": {"pt": ("impira/layoutlm-document-qa", "beed3c4")},
  246. },
  247. "type": "multimodal",
  248. },
  249. "fill-mask": {
  250. "impl": FillMaskPipeline,
  251. "tf": (TFAutoModelForMaskedLM,) if is_tf_available() else (),
  252. "pt": (AutoModelForMaskedLM,) if is_torch_available() else (),
  253. "default": {
  254. "model": {
  255. "pt": ("distilbert/distilroberta-base", "fb53ab8"),
  256. "tf": ("distilbert/distilroberta-base", "fb53ab8"),
  257. }
  258. },
  259. "type": "text",
  260. },
  261. "summarization": {
  262. "impl": SummarizationPipeline,
  263. "tf": (TFAutoModelForSeq2SeqLM,) if is_tf_available() else (),
  264. "pt": (AutoModelForSeq2SeqLM,) if is_torch_available() else (),
  265. "default": {
  266. "model": {"pt": ("sshleifer/distilbart-cnn-12-6", "a4f8f3e"), "tf": ("google-t5/t5-small", "df1b051")}
  267. },
  268. "type": "text",
  269. },
  270. # This task is a special case as it's parametrized by SRC, TGT languages.
  271. "translation": {
  272. "impl": TranslationPipeline,
  273. "tf": (TFAutoModelForSeq2SeqLM,) if is_tf_available() else (),
  274. "pt": (AutoModelForSeq2SeqLM,) if is_torch_available() else (),
  275. "default": {
  276. ("en", "fr"): {"model": {"pt": ("google-t5/t5-base", "a9723ea"), "tf": ("google-t5/t5-base", "a9723ea")}},
  277. ("en", "de"): {"model": {"pt": ("google-t5/t5-base", "a9723ea"), "tf": ("google-t5/t5-base", "a9723ea")}},
  278. ("en", "ro"): {"model": {"pt": ("google-t5/t5-base", "a9723ea"), "tf": ("google-t5/t5-base", "a9723ea")}},
  279. },
  280. "type": "text",
  281. },
  282. "text2text-generation": {
  283. "impl": Text2TextGenerationPipeline,
  284. "tf": (TFAutoModelForSeq2SeqLM,) if is_tf_available() else (),
  285. "pt": (AutoModelForSeq2SeqLM,) if is_torch_available() else (),
  286. "default": {"model": {"pt": ("google-t5/t5-base", "a9723ea"), "tf": ("google-t5/t5-base", "a9723ea")}},
  287. "type": "text",
  288. },
  289. "text-generation": {
  290. "impl": TextGenerationPipeline,
  291. "tf": (TFAutoModelForCausalLM,) if is_tf_available() else (),
  292. "pt": (AutoModelForCausalLM,) if is_torch_available() else (),
  293. "default": {"model": {"pt": ("openai-community/gpt2", "607a30d"), "tf": ("openai-community/gpt2", "607a30d")}},
  294. "type": "text",
  295. },
  296. "zero-shot-classification": {
  297. "impl": ZeroShotClassificationPipeline,
  298. "tf": (TFAutoModelForSequenceClassification,) if is_tf_available() else (),
  299. "pt": (AutoModelForSequenceClassification,) if is_torch_available() else (),
  300. "default": {
  301. "model": {
  302. "pt": ("facebook/bart-large-mnli", "d7645e1"),
  303. "tf": ("FacebookAI/roberta-large-mnli", "2a8f12d"),
  304. },
  305. "config": {
  306. "pt": ("facebook/bart-large-mnli", "d7645e1"),
  307. "tf": ("FacebookAI/roberta-large-mnli", "2a8f12d"),
  308. },
  309. },
  310. "type": "text",
  311. },
  312. "zero-shot-image-classification": {
  313. "impl": ZeroShotImageClassificationPipeline,
  314. "tf": (TFAutoModelForZeroShotImageClassification,) if is_tf_available() else (),
  315. "pt": (AutoModelForZeroShotImageClassification,) if is_torch_available() else (),
  316. "default": {
  317. "model": {
  318. "pt": ("openai/clip-vit-base-patch32", "3d74acf"),
  319. "tf": ("openai/clip-vit-base-patch32", "3d74acf"),
  320. }
  321. },
  322. "type": "multimodal",
  323. },
  324. "zero-shot-audio-classification": {
  325. "impl": ZeroShotAudioClassificationPipeline,
  326. "tf": (),
  327. "pt": (AutoModel,) if is_torch_available() else (),
  328. "default": {
  329. "model": {
  330. "pt": ("laion/clap-htsat-fused", "cca9e28"),
  331. }
  332. },
  333. "type": "multimodal",
  334. },
  335. "image-classification": {
  336. "impl": ImageClassificationPipeline,
  337. "tf": (TFAutoModelForImageClassification,) if is_tf_available() else (),
  338. "pt": (AutoModelForImageClassification,) if is_torch_available() else (),
  339. "default": {
  340. "model": {
  341. "pt": ("google/vit-base-patch16-224", "3f49326"),
  342. "tf": ("google/vit-base-patch16-224", "3f49326"),
  343. }
  344. },
  345. "type": "image",
  346. },
  347. "image-feature-extraction": {
  348. "impl": ImageFeatureExtractionPipeline,
  349. "tf": (TFAutoModel,) if is_tf_available() else (),
  350. "pt": (AutoModel,) if is_torch_available() else (),
  351. "default": {
  352. "model": {
  353. "pt": ("google/vit-base-patch16-224", "3f49326"),
  354. "tf": ("google/vit-base-patch16-224", "3f49326"),
  355. }
  356. },
  357. "type": "image",
  358. },
  359. "image-segmentation": {
  360. "impl": ImageSegmentationPipeline,
  361. "tf": (),
  362. "pt": (AutoModelForImageSegmentation, AutoModelForSemanticSegmentation) if is_torch_available() else (),
  363. "default": {"model": {"pt": ("facebook/detr-resnet-50-panoptic", "d53b52a")}},
  364. "type": "multimodal",
  365. },
  366. "image-to-text": {
  367. "impl": ImageToTextPipeline,
  368. "tf": (TFAutoModelForVision2Seq,) if is_tf_available() else (),
  369. "pt": (AutoModelForVision2Seq,) if is_torch_available() else (),
  370. "default": {
  371. "model": {
  372. "pt": ("ydshieh/vit-gpt2-coco-en", "5bebf1e"),
  373. "tf": ("ydshieh/vit-gpt2-coco-en", "5bebf1e"),
  374. }
  375. },
  376. "type": "multimodal",
  377. },
  378. "image-text-to-text": {
  379. "impl": ImageTextToTextPipeline,
  380. "tf": (),
  381. "pt": (AutoModelForImageTextToText,) if is_torch_available() else (),
  382. "default": {
  383. "model": {
  384. "pt": ("llava-hf/llava-onevision-qwen2-0.5b-ov-hf", "2c9ba3b"),
  385. }
  386. },
  387. "type": "multimodal",
  388. },
  389. "object-detection": {
  390. "impl": ObjectDetectionPipeline,
  391. "tf": (),
  392. "pt": (AutoModelForObjectDetection,) if is_torch_available() else (),
  393. "default": {"model": {"pt": ("facebook/detr-resnet-50", "1d5f47b")}},
  394. "type": "multimodal",
  395. },
  396. "zero-shot-object-detection": {
  397. "impl": ZeroShotObjectDetectionPipeline,
  398. "tf": (),
  399. "pt": (AutoModelForZeroShotObjectDetection,) if is_torch_available() else (),
  400. "default": {"model": {"pt": ("google/owlvit-base-patch32", "cbc355f")}},
  401. "type": "multimodal",
  402. },
  403. "depth-estimation": {
  404. "impl": DepthEstimationPipeline,
  405. "tf": (),
  406. "pt": (AutoModelForDepthEstimation,) if is_torch_available() else (),
  407. "default": {"model": {"pt": ("Intel/dpt-large", "bc15f29")}},
  408. "type": "image",
  409. },
  410. "video-classification": {
  411. "impl": VideoClassificationPipeline,
  412. "tf": (),
  413. "pt": (AutoModelForVideoClassification,) if is_torch_available() else (),
  414. "default": {"model": {"pt": ("MCG-NJU/videomae-base-finetuned-kinetics", "488eb9a")}},
  415. "type": "video",
  416. },
  417. "mask-generation": {
  418. "impl": MaskGenerationPipeline,
  419. "tf": (),
  420. "pt": (AutoModelForMaskGeneration,) if is_torch_available() else (),
  421. "default": {"model": {"pt": ("facebook/sam-vit-huge", "87aecf0")}},
  422. "type": "multimodal",
  423. },
  424. "image-to-image": {
  425. "impl": ImageToImagePipeline,
  426. "tf": (),
  427. "pt": (AutoModelForImageToImage,) if is_torch_available() else (),
  428. "default": {"model": {"pt": ("caidas/swin2SR-classical-sr-x2-64", "cee1c92")}},
  429. "type": "image",
  430. },
  431. "keypoint-matching": {
  432. "impl": KeypointMatchingPipeline,
  433. "tf": (),
  434. "pt": (AutoModelForKeypointMatching,) if is_torch_available() else (),
  435. "default": {"model": {"pt": ("magic-leap-community/superglue_outdoor", "f4041f8")}},
  436. "type": "image",
  437. },
  438. }
  439. PIPELINE_REGISTRY = PipelineRegistry(supported_tasks=SUPPORTED_TASKS, task_aliases=TASK_ALIASES)
  440. def get_supported_tasks() -> list[str]:
  441. """
  442. Returns a list of supported task strings.
  443. """
  444. return PIPELINE_REGISTRY.get_supported_tasks()
  445. def get_task(model: str, token: Optional[str] = None, **deprecated_kwargs) -> str:
  446. use_auth_token = deprecated_kwargs.pop("use_auth_token", None)
  447. if use_auth_token is not None:
  448. warnings.warn(
  449. "The `use_auth_token` argument is deprecated and will be removed in v5 of Transformers. Please use `token` instead.",
  450. FutureWarning,
  451. )
  452. if token is not None:
  453. raise ValueError("`token` and `use_auth_token` are both specified. Please set only the argument `token`.")
  454. token = use_auth_token
  455. if is_offline_mode():
  456. raise RuntimeError("You cannot infer task automatically within `pipeline` when using offline mode")
  457. try:
  458. info = model_info(model, token=token)
  459. except Exception as e:
  460. raise RuntimeError(f"Instantiating a pipeline without a task set raised an error: {e}")
  461. if not info.pipeline_tag:
  462. raise RuntimeError(
  463. f"The model {model} does not seem to have a correct `pipeline_tag` set to infer the task automatically"
  464. )
  465. if getattr(info, "library_name", "transformers") not in {"transformers", "timm"}:
  466. raise RuntimeError(f"This model is meant to be used with {info.library_name} not with transformers")
  467. task = info.pipeline_tag
  468. return task
  469. def check_task(task: str) -> tuple[str, dict, Any]:
  470. """
  471. Checks an incoming task string, to validate it's correct and return the default Pipeline and Model classes, and
  472. default models if they exist.
  473. Args:
  474. task (`str`):
  475. The task defining which pipeline will be returned. Currently accepted tasks are:
  476. - `"audio-classification"`
  477. - `"automatic-speech-recognition"`
  478. - `"conversational"`
  479. - `"depth-estimation"`
  480. - `"document-question-answering"`
  481. - `"feature-extraction"`
  482. - `"fill-mask"`
  483. - `"image-classification"`
  484. - `"image-feature-extraction"`
  485. - `"image-segmentation"`
  486. - `"image-to-text"`
  487. - `"image-to-image"`
  488. - `"keypoint-matching"`
  489. - `"object-detection"`
  490. - `"question-answering"`
  491. - `"summarization"`
  492. - `"table-question-answering"`
  493. - `"text2text-generation"`
  494. - `"text-classification"` (alias `"sentiment-analysis"` available)
  495. - `"text-generation"`
  496. - `"text-to-audio"` (alias `"text-to-speech"` available)
  497. - `"token-classification"` (alias `"ner"` available)
  498. - `"translation"`
  499. - `"translation_xx_to_yy"`
  500. - `"video-classification"`
  501. - `"visual-question-answering"` (alias `"vqa"` available)
  502. - `"zero-shot-classification"`
  503. - `"zero-shot-image-classification"`
  504. - `"zero-shot-object-detection"`
  505. Returns:
  506. (normalized_task: `str`, task_defaults: `dict`, task_options: (`tuple`, None)) The normalized task name
  507. (removed alias and options). The actual dictionary required to initialize the pipeline and some extra task
  508. options for parametrized tasks like "translation_xx_to_yy"
  509. """
  510. return PIPELINE_REGISTRY.check_task(task)
  511. def clean_custom_task(task_info):
  512. import transformers
  513. if "impl" not in task_info:
  514. raise RuntimeError("This model introduces a custom pipeline without specifying its implementation.")
  515. pt_class_names = task_info.get("pt", ())
  516. if isinstance(pt_class_names, str):
  517. pt_class_names = [pt_class_names]
  518. task_info["pt"] = tuple(getattr(transformers, c) for c in pt_class_names)
  519. tf_class_names = task_info.get("tf", ())
  520. if isinstance(tf_class_names, str):
  521. tf_class_names = [tf_class_names]
  522. task_info["tf"] = tuple(getattr(transformers, c) for c in tf_class_names)
  523. return task_info, None
  524. # <generated-code>
  525. # fmt: off
  526. # 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
  527. # The part of the file below was automatically generated from the code.
  528. # Do NOT edit this part of the file manually as any edits will be overwritten by the generation
  529. # of the file. If any change should be done, please apply the changes to the `pipeline` function
  530. # below and run `python utils/check_pipeline_typing.py --fix_and_overwrite` to update the file.
  531. # 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
  532. from typing import Literal, overload
  533. @overload
  534. def pipeline(task: Literal[None], model: Optional[Union[str, "PreTrainedModel", "TFPreTrainedModel"]] = None, config: Optional[Union[str, PretrainedConfig]] = None, tokenizer: Optional[Union[str, PreTrainedTokenizer, "PreTrainedTokenizerFast"]] = None, feature_extractor: Optional[Union[str, PreTrainedFeatureExtractor]] = None, image_processor: Optional[Union[str, BaseImageProcessor]] = None, processor: Optional[Union[str, ProcessorMixin]] = None, framework: Optional[str] = None, revision: Optional[str] = None, use_fast: bool = True, token: Optional[Union[str, bool]] = None, device: Optional[Union[int, str, "torch.device"]] = None, device_map: Optional[Union[str, dict[str, Union[int, str]]]] = None, dtype: Optional[Union[str, "torch.dtype"]] = "auto", trust_remote_code: Optional[bool] = None, model_kwargs: Optional[dict[str, Any]] = None, pipeline_class: Optional[Any] = None, **kwargs: Any) -> Pipeline: ...
  535. @overload
  536. def pipeline(task: Literal["audio-classification"], model: Optional[Union[str, "PreTrainedModel", "TFPreTrainedModel"]] = None, config: Optional[Union[str, PretrainedConfig]] = None, tokenizer: Optional[Union[str, PreTrainedTokenizer, "PreTrainedTokenizerFast"]] = None, feature_extractor: Optional[Union[str, PreTrainedFeatureExtractor]] = None, image_processor: Optional[Union[str, BaseImageProcessor]] = None, processor: Optional[Union[str, ProcessorMixin]] = None, framework: Optional[str] = None, revision: Optional[str] = None, use_fast: bool = True, token: Optional[Union[str, bool]] = None, device: Optional[Union[int, str, "torch.device"]] = None, device_map: Optional[Union[str, dict[str, Union[int, str]]]] = None, dtype: Optional[Union[str, "torch.dtype"]] = "auto", trust_remote_code: Optional[bool] = None, model_kwargs: Optional[dict[str, Any]] = None, pipeline_class: Optional[Any] = None, **kwargs: Any) -> AudioClassificationPipeline: ...
  537. @overload
  538. def pipeline(task: Literal["automatic-speech-recognition"], model: Optional[Union[str, "PreTrainedModel", "TFPreTrainedModel"]] = None, config: Optional[Union[str, PretrainedConfig]] = None, tokenizer: Optional[Union[str, PreTrainedTokenizer, "PreTrainedTokenizerFast"]] = None, feature_extractor: Optional[Union[str, PreTrainedFeatureExtractor]] = None, image_processor: Optional[Union[str, BaseImageProcessor]] = None, processor: Optional[Union[str, ProcessorMixin]] = None, framework: Optional[str] = None, revision: Optional[str] = None, use_fast: bool = True, token: Optional[Union[str, bool]] = None, device: Optional[Union[int, str, "torch.device"]] = None, device_map: Optional[Union[str, dict[str, Union[int, str]]]] = None, dtype: Optional[Union[str, "torch.dtype"]] = "auto", trust_remote_code: Optional[bool] = None, model_kwargs: Optional[dict[str, Any]] = None, pipeline_class: Optional[Any] = None, **kwargs: Any) -> AutomaticSpeechRecognitionPipeline: ...
  539. @overload
  540. def pipeline(task: Literal["depth-estimation"], model: Optional[Union[str, "PreTrainedModel", "TFPreTrainedModel"]] = None, config: Optional[Union[str, PretrainedConfig]] = None, tokenizer: Optional[Union[str, PreTrainedTokenizer, "PreTrainedTokenizerFast"]] = None, feature_extractor: Optional[Union[str, PreTrainedFeatureExtractor]] = None, image_processor: Optional[Union[str, BaseImageProcessor]] = None, processor: Optional[Union[str, ProcessorMixin]] = None, framework: Optional[str] = None, revision: Optional[str] = None, use_fast: bool = True, token: Optional[Union[str, bool]] = None, device: Optional[Union[int, str, "torch.device"]] = None, device_map: Optional[Union[str, dict[str, Union[int, str]]]] = None, dtype: Optional[Union[str, "torch.dtype"]] = "auto", trust_remote_code: Optional[bool] = None, model_kwargs: Optional[dict[str, Any]] = None, pipeline_class: Optional[Any] = None, **kwargs: Any) -> DepthEstimationPipeline: ...
  541. @overload
  542. def pipeline(task: Literal["document-question-answering"], model: Optional[Union[str, "PreTrainedModel", "TFPreTrainedModel"]] = None, config: Optional[Union[str, PretrainedConfig]] = None, tokenizer: Optional[Union[str, PreTrainedTokenizer, "PreTrainedTokenizerFast"]] = None, feature_extractor: Optional[Union[str, PreTrainedFeatureExtractor]] = None, image_processor: Optional[Union[str, BaseImageProcessor]] = None, processor: Optional[Union[str, ProcessorMixin]] = None, framework: Optional[str] = None, revision: Optional[str] = None, use_fast: bool = True, token: Optional[Union[str, bool]] = None, device: Optional[Union[int, str, "torch.device"]] = None, device_map: Optional[Union[str, dict[str, Union[int, str]]]] = None, dtype: Optional[Union[str, "torch.dtype"]] = "auto", trust_remote_code: Optional[bool] = None, model_kwargs: Optional[dict[str, Any]] = None, pipeline_class: Optional[Any] = None, **kwargs: Any) -> DocumentQuestionAnsweringPipeline: ...
  543. @overload
  544. def pipeline(task: Literal["feature-extraction"], model: Optional[Union[str, "PreTrainedModel", "TFPreTrainedModel"]] = None, config: Optional[Union[str, PretrainedConfig]] = None, tokenizer: Optional[Union[str, PreTrainedTokenizer, "PreTrainedTokenizerFast"]] = None, feature_extractor: Optional[Union[str, PreTrainedFeatureExtractor]] = None, image_processor: Optional[Union[str, BaseImageProcessor]] = None, processor: Optional[Union[str, ProcessorMixin]] = None, framework: Optional[str] = None, revision: Optional[str] = None, use_fast: bool = True, token: Optional[Union[str, bool]] = None, device: Optional[Union[int, str, "torch.device"]] = None, device_map: Optional[Union[str, dict[str, Union[int, str]]]] = None, dtype: Optional[Union[str, "torch.dtype"]] = "auto", trust_remote_code: Optional[bool] = None, model_kwargs: Optional[dict[str, Any]] = None, pipeline_class: Optional[Any] = None, **kwargs: Any) -> FeatureExtractionPipeline: ...
  545. @overload
  546. def pipeline(task: Literal["fill-mask"], model: Optional[Union[str, "PreTrainedModel", "TFPreTrainedModel"]] = None, config: Optional[Union[str, PretrainedConfig]] = None, tokenizer: Optional[Union[str, PreTrainedTokenizer, "PreTrainedTokenizerFast"]] = None, feature_extractor: Optional[Union[str, PreTrainedFeatureExtractor]] = None, image_processor: Optional[Union[str, BaseImageProcessor]] = None, processor: Optional[Union[str, ProcessorMixin]] = None, framework: Optional[str] = None, revision: Optional[str] = None, use_fast: bool = True, token: Optional[Union[str, bool]] = None, device: Optional[Union[int, str, "torch.device"]] = None, device_map: Optional[Union[str, dict[str, Union[int, str]]]] = None, dtype: Optional[Union[str, "torch.dtype"]] = "auto", trust_remote_code: Optional[bool] = None, model_kwargs: Optional[dict[str, Any]] = None, pipeline_class: Optional[Any] = None, **kwargs: Any) -> FillMaskPipeline: ...
  547. @overload
  548. def pipeline(task: Literal["image-classification"], model: Optional[Union[str, "PreTrainedModel", "TFPreTrainedModel"]] = None, config: Optional[Union[str, PretrainedConfig]] = None, tokenizer: Optional[Union[str, PreTrainedTokenizer, "PreTrainedTokenizerFast"]] = None, feature_extractor: Optional[Union[str, PreTrainedFeatureExtractor]] = None, image_processor: Optional[Union[str, BaseImageProcessor]] = None, processor: Optional[Union[str, ProcessorMixin]] = None, framework: Optional[str] = None, revision: Optional[str] = None, use_fast: bool = True, token: Optional[Union[str, bool]] = None, device: Optional[Union[int, str, "torch.device"]] = None, device_map: Optional[Union[str, dict[str, Union[int, str]]]] = None, dtype: Optional[Union[str, "torch.dtype"]] = "auto", trust_remote_code: Optional[bool] = None, model_kwargs: Optional[dict[str, Any]] = None, pipeline_class: Optional[Any] = None, **kwargs: Any) -> ImageClassificationPipeline: ...
  549. @overload
  550. def pipeline(task: Literal["image-feature-extraction"], model: Optional[Union[str, "PreTrainedModel", "TFPreTrainedModel"]] = None, config: Optional[Union[str, PretrainedConfig]] = None, tokenizer: Optional[Union[str, PreTrainedTokenizer, "PreTrainedTokenizerFast"]] = None, feature_extractor: Optional[Union[str, PreTrainedFeatureExtractor]] = None, image_processor: Optional[Union[str, BaseImageProcessor]] = None, processor: Optional[Union[str, ProcessorMixin]] = None, framework: Optional[str] = None, revision: Optional[str] = None, use_fast: bool = True, token: Optional[Union[str, bool]] = None, device: Optional[Union[int, str, "torch.device"]] = None, device_map: Optional[Union[str, dict[str, Union[int, str]]]] = None, dtype: Optional[Union[str, "torch.dtype"]] = "auto", trust_remote_code: Optional[bool] = None, model_kwargs: Optional[dict[str, Any]] = None, pipeline_class: Optional[Any] = None, **kwargs: Any) -> ImageFeatureExtractionPipeline: ...
  551. @overload
  552. def pipeline(task: Literal["image-segmentation"], model: Optional[Union[str, "PreTrainedModel", "TFPreTrainedModel"]] = None, config: Optional[Union[str, PretrainedConfig]] = None, tokenizer: Optional[Union[str, PreTrainedTokenizer, "PreTrainedTokenizerFast"]] = None, feature_extractor: Optional[Union[str, PreTrainedFeatureExtractor]] = None, image_processor: Optional[Union[str, BaseImageProcessor]] = None, processor: Optional[Union[str, ProcessorMixin]] = None, framework: Optional[str] = None, revision: Optional[str] = None, use_fast: bool = True, token: Optional[Union[str, bool]] = None, device: Optional[Union[int, str, "torch.device"]] = None, device_map: Optional[Union[str, dict[str, Union[int, str]]]] = None, dtype: Optional[Union[str, "torch.dtype"]] = "auto", trust_remote_code: Optional[bool] = None, model_kwargs: Optional[dict[str, Any]] = None, pipeline_class: Optional[Any] = None, **kwargs: Any) -> ImageSegmentationPipeline: ...
  553. @overload
  554. def pipeline(task: Literal["image-text-to-text"], model: Optional[Union[str, "PreTrainedModel", "TFPreTrainedModel"]] = None, config: Optional[Union[str, PretrainedConfig]] = None, tokenizer: Optional[Union[str, PreTrainedTokenizer, "PreTrainedTokenizerFast"]] = None, feature_extractor: Optional[Union[str, PreTrainedFeatureExtractor]] = None, image_processor: Optional[Union[str, BaseImageProcessor]] = None, processor: Optional[Union[str, ProcessorMixin]] = None, framework: Optional[str] = None, revision: Optional[str] = None, use_fast: bool = True, token: Optional[Union[str, bool]] = None, device: Optional[Union[int, str, "torch.device"]] = None, device_map: Optional[Union[str, dict[str, Union[int, str]]]] = None, dtype: Optional[Union[str, "torch.dtype"]] = "auto", trust_remote_code: Optional[bool] = None, model_kwargs: Optional[dict[str, Any]] = None, pipeline_class: Optional[Any] = None, **kwargs: Any) -> ImageTextToTextPipeline: ...
  555. @overload
  556. def pipeline(task: Literal["image-to-image"], model: Optional[Union[str, "PreTrainedModel", "TFPreTrainedModel"]] = None, config: Optional[Union[str, PretrainedConfig]] = None, tokenizer: Optional[Union[str, PreTrainedTokenizer, "PreTrainedTokenizerFast"]] = None, feature_extractor: Optional[Union[str, PreTrainedFeatureExtractor]] = None, image_processor: Optional[Union[str, BaseImageProcessor]] = None, processor: Optional[Union[str, ProcessorMixin]] = None, framework: Optional[str] = None, revision: Optional[str] = None, use_fast: bool = True, token: Optional[Union[str, bool]] = None, device: Optional[Union[int, str, "torch.device"]] = None, device_map: Optional[Union[str, dict[str, Union[int, str]]]] = None, dtype: Optional[Union[str, "torch.dtype"]] = "auto", trust_remote_code: Optional[bool] = None, model_kwargs: Optional[dict[str, Any]] = None, pipeline_class: Optional[Any] = None, **kwargs: Any) -> ImageToImagePipeline: ...
  557. @overload
  558. def pipeline(task: Literal["image-to-text"], model: Optional[Union[str, "PreTrainedModel", "TFPreTrainedModel"]] = None, config: Optional[Union[str, PretrainedConfig]] = None, tokenizer: Optional[Union[str, PreTrainedTokenizer, "PreTrainedTokenizerFast"]] = None, feature_extractor: Optional[Union[str, PreTrainedFeatureExtractor]] = None, image_processor: Optional[Union[str, BaseImageProcessor]] = None, processor: Optional[Union[str, ProcessorMixin]] = None, framework: Optional[str] = None, revision: Optional[str] = None, use_fast: bool = True, token: Optional[Union[str, bool]] = None, device: Optional[Union[int, str, "torch.device"]] = None, device_map: Optional[Union[str, dict[str, Union[int, str]]]] = None, dtype: Optional[Union[str, "torch.dtype"]] = "auto", trust_remote_code: Optional[bool] = None, model_kwargs: Optional[dict[str, Any]] = None, pipeline_class: Optional[Any] = None, **kwargs: Any) -> ImageToTextPipeline: ...
  559. @overload
  560. def pipeline(task: Literal["keypoint-matching"], model: Optional[Union[str, "PreTrainedModel", "TFPreTrainedModel"]] = None, config: Optional[Union[str, PretrainedConfig]] = None, tokenizer: Optional[Union[str, PreTrainedTokenizer, "PreTrainedTokenizerFast"]] = None, feature_extractor: Optional[Union[str, PreTrainedFeatureExtractor]] = None, image_processor: Optional[Union[str, BaseImageProcessor]] = None, processor: Optional[Union[str, ProcessorMixin]] = None, framework: Optional[str] = None, revision: Optional[str] = None, use_fast: bool = True, token: Optional[Union[str, bool]] = None, device: Optional[Union[int, str, "torch.device"]] = None, device_map: Optional[Union[str, dict[str, Union[int, str]]]] = None, dtype: Optional[Union[str, "torch.dtype"]] = "auto", trust_remote_code: Optional[bool] = None, model_kwargs: Optional[dict[str, Any]] = None, pipeline_class: Optional[Any] = None, **kwargs: Any) -> KeypointMatchingPipeline: ...
  561. @overload
  562. def pipeline(task: Literal["mask-generation"], model: Optional[Union[str, "PreTrainedModel", "TFPreTrainedModel"]] = None, config: Optional[Union[str, PretrainedConfig]] = None, tokenizer: Optional[Union[str, PreTrainedTokenizer, "PreTrainedTokenizerFast"]] = None, feature_extractor: Optional[Union[str, PreTrainedFeatureExtractor]] = None, image_processor: Optional[Union[str, BaseImageProcessor]] = None, processor: Optional[Union[str, ProcessorMixin]] = None, framework: Optional[str] = None, revision: Optional[str] = None, use_fast: bool = True, token: Optional[Union[str, bool]] = None, device: Optional[Union[int, str, "torch.device"]] = None, device_map: Optional[Union[str, dict[str, Union[int, str]]]] = None, dtype: Optional[Union[str, "torch.dtype"]] = "auto", trust_remote_code: Optional[bool] = None, model_kwargs: Optional[dict[str, Any]] = None, pipeline_class: Optional[Any] = None, **kwargs: Any) -> MaskGenerationPipeline: ...
  563. @overload
  564. def pipeline(task: Literal["object-detection"], model: Optional[Union[str, "PreTrainedModel", "TFPreTrainedModel"]] = None, config: Optional[Union[str, PretrainedConfig]] = None, tokenizer: Optional[Union[str, PreTrainedTokenizer, "PreTrainedTokenizerFast"]] = None, feature_extractor: Optional[Union[str, PreTrainedFeatureExtractor]] = None, image_processor: Optional[Union[str, BaseImageProcessor]] = None, processor: Optional[Union[str, ProcessorMixin]] = None, framework: Optional[str] = None, revision: Optional[str] = None, use_fast: bool = True, token: Optional[Union[str, bool]] = None, device: Optional[Union[int, str, "torch.device"]] = None, device_map: Optional[Union[str, dict[str, Union[int, str]]]] = None, dtype: Optional[Union[str, "torch.dtype"]] = "auto", trust_remote_code: Optional[bool] = None, model_kwargs: Optional[dict[str, Any]] = None, pipeline_class: Optional[Any] = None, **kwargs: Any) -> ObjectDetectionPipeline: ...
  565. @overload
  566. def pipeline(task: Literal["question-answering"], model: Optional[Union[str, "PreTrainedModel", "TFPreTrainedModel"]] = None, config: Optional[Union[str, PretrainedConfig]] = None, tokenizer: Optional[Union[str, PreTrainedTokenizer, "PreTrainedTokenizerFast"]] = None, feature_extractor: Optional[Union[str, PreTrainedFeatureExtractor]] = None, image_processor: Optional[Union[str, BaseImageProcessor]] = None, processor: Optional[Union[str, ProcessorMixin]] = None, framework: Optional[str] = None, revision: Optional[str] = None, use_fast: bool = True, token: Optional[Union[str, bool]] = None, device: Optional[Union[int, str, "torch.device"]] = None, device_map: Optional[Union[str, dict[str, Union[int, str]]]] = None, dtype: Optional[Union[str, "torch.dtype"]] = "auto", trust_remote_code: Optional[bool] = None, model_kwargs: Optional[dict[str, Any]] = None, pipeline_class: Optional[Any] = None, **kwargs: Any) -> QuestionAnsweringPipeline: ...
  567. @overload
  568. def pipeline(task: Literal["summarization"], model: Optional[Union[str, "PreTrainedModel", "TFPreTrainedModel"]] = None, config: Optional[Union[str, PretrainedConfig]] = None, tokenizer: Optional[Union[str, PreTrainedTokenizer, "PreTrainedTokenizerFast"]] = None, feature_extractor: Optional[Union[str, PreTrainedFeatureExtractor]] = None, image_processor: Optional[Union[str, BaseImageProcessor]] = None, processor: Optional[Union[str, ProcessorMixin]] = None, framework: Optional[str] = None, revision: Optional[str] = None, use_fast: bool = True, token: Optional[Union[str, bool]] = None, device: Optional[Union[int, str, "torch.device"]] = None, device_map: Optional[Union[str, dict[str, Union[int, str]]]] = None, dtype: Optional[Union[str, "torch.dtype"]] = "auto", trust_remote_code: Optional[bool] = None, model_kwargs: Optional[dict[str, Any]] = None, pipeline_class: Optional[Any] = None, **kwargs: Any) -> SummarizationPipeline: ...
  569. @overload
  570. def pipeline(task: Literal["table-question-answering"], model: Optional[Union[str, "PreTrainedModel", "TFPreTrainedModel"]] = None, config: Optional[Union[str, PretrainedConfig]] = None, tokenizer: Optional[Union[str, PreTrainedTokenizer, "PreTrainedTokenizerFast"]] = None, feature_extractor: Optional[Union[str, PreTrainedFeatureExtractor]] = None, image_processor: Optional[Union[str, BaseImageProcessor]] = None, processor: Optional[Union[str, ProcessorMixin]] = None, framework: Optional[str] = None, revision: Optional[str] = None, use_fast: bool = True, token: Optional[Union[str, bool]] = None, device: Optional[Union[int, str, "torch.device"]] = None, device_map: Optional[Union[str, dict[str, Union[int, str]]]] = None, dtype: Optional[Union[str, "torch.dtype"]] = "auto", trust_remote_code: Optional[bool] = None, model_kwargs: Optional[dict[str, Any]] = None, pipeline_class: Optional[Any] = None, **kwargs: Any) -> TableQuestionAnsweringPipeline: ...
  571. @overload
  572. def pipeline(task: Literal["text-classification"], model: Optional[Union[str, "PreTrainedModel", "TFPreTrainedModel"]] = None, config: Optional[Union[str, PretrainedConfig]] = None, tokenizer: Optional[Union[str, PreTrainedTokenizer, "PreTrainedTokenizerFast"]] = None, feature_extractor: Optional[Union[str, PreTrainedFeatureExtractor]] = None, image_processor: Optional[Union[str, BaseImageProcessor]] = None, processor: Optional[Union[str, ProcessorMixin]] = None, framework: Optional[str] = None, revision: Optional[str] = None, use_fast: bool = True, token: Optional[Union[str, bool]] = None, device: Optional[Union[int, str, "torch.device"]] = None, device_map: Optional[Union[str, dict[str, Union[int, str]]]] = None, dtype: Optional[Union[str, "torch.dtype"]] = "auto", trust_remote_code: Optional[bool] = None, model_kwargs: Optional[dict[str, Any]] = None, pipeline_class: Optional[Any] = None, **kwargs: Any) -> TextClassificationPipeline: ...
  573. @overload
  574. def pipeline(task: Literal["text-generation"], model: Optional[Union[str, "PreTrainedModel", "TFPreTrainedModel"]] = None, config: Optional[Union[str, PretrainedConfig]] = None, tokenizer: Optional[Union[str, PreTrainedTokenizer, "PreTrainedTokenizerFast"]] = None, feature_extractor: Optional[Union[str, PreTrainedFeatureExtractor]] = None, image_processor: Optional[Union[str, BaseImageProcessor]] = None, processor: Optional[Union[str, ProcessorMixin]] = None, framework: Optional[str] = None, revision: Optional[str] = None, use_fast: bool = True, token: Optional[Union[str, bool]] = None, device: Optional[Union[int, str, "torch.device"]] = None, device_map: Optional[Union[str, dict[str, Union[int, str]]]] = None, dtype: Optional[Union[str, "torch.dtype"]] = "auto", trust_remote_code: Optional[bool] = None, model_kwargs: Optional[dict[str, Any]] = None, pipeline_class: Optional[Any] = None, **kwargs: Any) -> TextGenerationPipeline: ...
  575. @overload
  576. def pipeline(task: Literal["text-to-audio"], model: Optional[Union[str, "PreTrainedModel", "TFPreTrainedModel"]] = None, config: Optional[Union[str, PretrainedConfig]] = None, tokenizer: Optional[Union[str, PreTrainedTokenizer, "PreTrainedTokenizerFast"]] = None, feature_extractor: Optional[Union[str, PreTrainedFeatureExtractor]] = None, image_processor: Optional[Union[str, BaseImageProcessor]] = None, processor: Optional[Union[str, ProcessorMixin]] = None, framework: Optional[str] = None, revision: Optional[str] = None, use_fast: bool = True, token: Optional[Union[str, bool]] = None, device: Optional[Union[int, str, "torch.device"]] = None, device_map: Optional[Union[str, dict[str, Union[int, str]]]] = None, dtype: Optional[Union[str, "torch.dtype"]] = "auto", trust_remote_code: Optional[bool] = None, model_kwargs: Optional[dict[str, Any]] = None, pipeline_class: Optional[Any] = None, **kwargs: Any) -> TextToAudioPipeline: ...
  577. @overload
  578. def pipeline(task: Literal["text2text-generation"], model: Optional[Union[str, "PreTrainedModel", "TFPreTrainedModel"]] = None, config: Optional[Union[str, PretrainedConfig]] = None, tokenizer: Optional[Union[str, PreTrainedTokenizer, "PreTrainedTokenizerFast"]] = None, feature_extractor: Optional[Union[str, PreTrainedFeatureExtractor]] = None, image_processor: Optional[Union[str, BaseImageProcessor]] = None, processor: Optional[Union[str, ProcessorMixin]] = None, framework: Optional[str] = None, revision: Optional[str] = None, use_fast: bool = True, token: Optional[Union[str, bool]] = None, device: Optional[Union[int, str, "torch.device"]] = None, device_map: Optional[Union[str, dict[str, Union[int, str]]]] = None, dtype: Optional[Union[str, "torch.dtype"]] = "auto", trust_remote_code: Optional[bool] = None, model_kwargs: Optional[dict[str, Any]] = None, pipeline_class: Optional[Any] = None, **kwargs: Any) -> Text2TextGenerationPipeline: ...
  579. @overload
  580. def pipeline(task: Literal["token-classification"], model: Optional[Union[str, "PreTrainedModel", "TFPreTrainedModel"]] = None, config: Optional[Union[str, PretrainedConfig]] = None, tokenizer: Optional[Union[str, PreTrainedTokenizer, "PreTrainedTokenizerFast"]] = None, feature_extractor: Optional[Union[str, PreTrainedFeatureExtractor]] = None, image_processor: Optional[Union[str, BaseImageProcessor]] = None, processor: Optional[Union[str, ProcessorMixin]] = None, framework: Optional[str] = None, revision: Optional[str] = None, use_fast: bool = True, token: Optional[Union[str, bool]] = None, device: Optional[Union[int, str, "torch.device"]] = None, device_map: Optional[Union[str, dict[str, Union[int, str]]]] = None, dtype: Optional[Union[str, "torch.dtype"]] = "auto", trust_remote_code: Optional[bool] = None, model_kwargs: Optional[dict[str, Any]] = None, pipeline_class: Optional[Any] = None, **kwargs: Any) -> TokenClassificationPipeline: ...
  581. @overload
  582. def pipeline(task: Literal["translation"], model: Optional[Union[str, "PreTrainedModel", "TFPreTrainedModel"]] = None, config: Optional[Union[str, PretrainedConfig]] = None, tokenizer: Optional[Union[str, PreTrainedTokenizer, "PreTrainedTokenizerFast"]] = None, feature_extractor: Optional[Union[str, PreTrainedFeatureExtractor]] = None, image_processor: Optional[Union[str, BaseImageProcessor]] = None, processor: Optional[Union[str, ProcessorMixin]] = None, framework: Optional[str] = None, revision: Optional[str] = None, use_fast: bool = True, token: Optional[Union[str, bool]] = None, device: Optional[Union[int, str, "torch.device"]] = None, device_map: Optional[Union[str, dict[str, Union[int, str]]]] = None, dtype: Optional[Union[str, "torch.dtype"]] = "auto", trust_remote_code: Optional[bool] = None, model_kwargs: Optional[dict[str, Any]] = None, pipeline_class: Optional[Any] = None, **kwargs: Any) -> TranslationPipeline: ...
  583. @overload
  584. def pipeline(task: Literal["video-classification"], model: Optional[Union[str, "PreTrainedModel", "TFPreTrainedModel"]] = None, config: Optional[Union[str, PretrainedConfig]] = None, tokenizer: Optional[Union[str, PreTrainedTokenizer, "PreTrainedTokenizerFast"]] = None, feature_extractor: Optional[Union[str, PreTrainedFeatureExtractor]] = None, image_processor: Optional[Union[str, BaseImageProcessor]] = None, processor: Optional[Union[str, ProcessorMixin]] = None, framework: Optional[str] = None, revision: Optional[str] = None, use_fast: bool = True, token: Optional[Union[str, bool]] = None, device: Optional[Union[int, str, "torch.device"]] = None, device_map: Optional[Union[str, dict[str, Union[int, str]]]] = None, dtype: Optional[Union[str, "torch.dtype"]] = "auto", trust_remote_code: Optional[bool] = None, model_kwargs: Optional[dict[str, Any]] = None, pipeline_class: Optional[Any] = None, **kwargs: Any) -> VideoClassificationPipeline: ...
  585. @overload
  586. def pipeline(task: Literal["visual-question-answering"], model: Optional[Union[str, "PreTrainedModel", "TFPreTrainedModel"]] = None, config: Optional[Union[str, PretrainedConfig]] = None, tokenizer: Optional[Union[str, PreTrainedTokenizer, "PreTrainedTokenizerFast"]] = None, feature_extractor: Optional[Union[str, PreTrainedFeatureExtractor]] = None, image_processor: Optional[Union[str, BaseImageProcessor]] = None, processor: Optional[Union[str, ProcessorMixin]] = None, framework: Optional[str] = None, revision: Optional[str] = None, use_fast: bool = True, token: Optional[Union[str, bool]] = None, device: Optional[Union[int, str, "torch.device"]] = None, device_map: Optional[Union[str, dict[str, Union[int, str]]]] = None, dtype: Optional[Union[str, "torch.dtype"]] = "auto", trust_remote_code: Optional[bool] = None, model_kwargs: Optional[dict[str, Any]] = None, pipeline_class: Optional[Any] = None, **kwargs: Any) -> VisualQuestionAnsweringPipeline: ...
  587. @overload
  588. def pipeline(task: Literal["zero-shot-audio-classification"], model: Optional[Union[str, "PreTrainedModel", "TFPreTrainedModel"]] = None, config: Optional[Union[str, PretrainedConfig]] = None, tokenizer: Optional[Union[str, PreTrainedTokenizer, "PreTrainedTokenizerFast"]] = None, feature_extractor: Optional[Union[str, PreTrainedFeatureExtractor]] = None, image_processor: Optional[Union[str, BaseImageProcessor]] = None, processor: Optional[Union[str, ProcessorMixin]] = None, framework: Optional[str] = None, revision: Optional[str] = None, use_fast: bool = True, token: Optional[Union[str, bool]] = None, device: Optional[Union[int, str, "torch.device"]] = None, device_map: Optional[Union[str, dict[str, Union[int, str]]]] = None, dtype: Optional[Union[str, "torch.dtype"]] = "auto", trust_remote_code: Optional[bool] = None, model_kwargs: Optional[dict[str, Any]] = None, pipeline_class: Optional[Any] = None, **kwargs: Any) -> ZeroShotAudioClassificationPipeline: ...
  589. @overload
  590. def pipeline(task: Literal["zero-shot-classification"], model: Optional[Union[str, "PreTrainedModel", "TFPreTrainedModel"]] = None, config: Optional[Union[str, PretrainedConfig]] = None, tokenizer: Optional[Union[str, PreTrainedTokenizer, "PreTrainedTokenizerFast"]] = None, feature_extractor: Optional[Union[str, PreTrainedFeatureExtractor]] = None, image_processor: Optional[Union[str, BaseImageProcessor]] = None, processor: Optional[Union[str, ProcessorMixin]] = None, framework: Optional[str] = None, revision: Optional[str] = None, use_fast: bool = True, token: Optional[Union[str, bool]] = None, device: Optional[Union[int, str, "torch.device"]] = None, device_map: Optional[Union[str, dict[str, Union[int, str]]]] = None, dtype: Optional[Union[str, "torch.dtype"]] = "auto", trust_remote_code: Optional[bool] = None, model_kwargs: Optional[dict[str, Any]] = None, pipeline_class: Optional[Any] = None, **kwargs: Any) -> ZeroShotClassificationPipeline: ...
  591. @overload
  592. def pipeline(task: Literal["zero-shot-image-classification"], model: Optional[Union[str, "PreTrainedModel", "TFPreTrainedModel"]] = None, config: Optional[Union[str, PretrainedConfig]] = None, tokenizer: Optional[Union[str, PreTrainedTokenizer, "PreTrainedTokenizerFast"]] = None, feature_extractor: Optional[Union[str, PreTrainedFeatureExtractor]] = None, image_processor: Optional[Union[str, BaseImageProcessor]] = None, processor: Optional[Union[str, ProcessorMixin]] = None, framework: Optional[str] = None, revision: Optional[str] = None, use_fast: bool = True, token: Optional[Union[str, bool]] = None, device: Optional[Union[int, str, "torch.device"]] = None, device_map: Optional[Union[str, dict[str, Union[int, str]]]] = None, dtype: Optional[Union[str, "torch.dtype"]] = "auto", trust_remote_code: Optional[bool] = None, model_kwargs: Optional[dict[str, Any]] = None, pipeline_class: Optional[Any] = None, **kwargs: Any) -> ZeroShotImageClassificationPipeline: ...
  593. @overload
  594. def pipeline(task: Literal["zero-shot-object-detection"], model: Optional[Union[str, "PreTrainedModel", "TFPreTrainedModel"]] = None, config: Optional[Union[str, PretrainedConfig]] = None, tokenizer: Optional[Union[str, PreTrainedTokenizer, "PreTrainedTokenizerFast"]] = None, feature_extractor: Optional[Union[str, PreTrainedFeatureExtractor]] = None, image_processor: Optional[Union[str, BaseImageProcessor]] = None, processor: Optional[Union[str, ProcessorMixin]] = None, framework: Optional[str] = None, revision: Optional[str] = None, use_fast: bool = True, token: Optional[Union[str, bool]] = None, device: Optional[Union[int, str, "torch.device"]] = None, device_map: Optional[Union[str, dict[str, Union[int, str]]]] = None, dtype: Optional[Union[str, "torch.dtype"]] = "auto", trust_remote_code: Optional[bool] = None, model_kwargs: Optional[dict[str, Any]] = None, pipeline_class: Optional[Any] = None, **kwargs: Any) -> ZeroShotObjectDetectionPipeline: ...
  595. # 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
  596. # The part of the file above was automatically generated from the code.
  597. # 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
  598. # fmt: on
  599. # </generated-code>
  600. def pipeline(
  601. task: Optional[str] = None,
  602. model: Optional[Union[str, "PreTrainedModel", "TFPreTrainedModel"]] = None,
  603. config: Optional[Union[str, PretrainedConfig]] = None,
  604. tokenizer: Optional[Union[str, PreTrainedTokenizer, "PreTrainedTokenizerFast"]] = None,
  605. feature_extractor: Optional[Union[str, PreTrainedFeatureExtractor]] = None,
  606. image_processor: Optional[Union[str, BaseImageProcessor]] = None,
  607. processor: Optional[Union[str, ProcessorMixin]] = None,
  608. framework: Optional[str] = None,
  609. revision: Optional[str] = None,
  610. use_fast: bool = True,
  611. token: Optional[Union[str, bool]] = None,
  612. device: Optional[Union[int, str, "torch.device"]] = None,
  613. device_map: Optional[Union[str, dict[str, Union[int, str]]]] = None,
  614. dtype: Optional[Union[str, "torch.dtype"]] = "auto",
  615. trust_remote_code: Optional[bool] = None,
  616. model_kwargs: Optional[dict[str, Any]] = None,
  617. pipeline_class: Optional[Any] = None,
  618. **kwargs: Any,
  619. ) -> Pipeline:
  620. """
  621. Utility factory method to build a [`Pipeline`].
  622. A pipeline consists of:
  623. - One or more components for pre-processing model inputs, such as a [tokenizer](tokenizer),
  624. [image_processor](image_processor), [feature_extractor](feature_extractor), or [processor](processors).
  625. - A [model](model) that generates predictions from the inputs.
  626. - Optional post-processing steps to refine the model's output, which can also be handled by processors.
  627. <Tip>
  628. While there are such optional arguments as `tokenizer`, `feature_extractor`, `image_processor`, and `processor`,
  629. they shouldn't be specified all at once. If these components are not provided, `pipeline` will try to load
  630. required ones automatically. In case you want to provide these components explicitly, please refer to a
  631. specific pipeline in order to get more details regarding what components are required.
  632. </Tip>
  633. Args:
  634. task (`str`):
  635. The task defining which pipeline will be returned. Currently accepted tasks are:
  636. - `"audio-classification"`: will return a [`AudioClassificationPipeline`].
  637. - `"automatic-speech-recognition"`: will return a [`AutomaticSpeechRecognitionPipeline`].
  638. - `"depth-estimation"`: will return a [`DepthEstimationPipeline`].
  639. - `"document-question-answering"`: will return a [`DocumentQuestionAnsweringPipeline`].
  640. - `"feature-extraction"`: will return a [`FeatureExtractionPipeline`].
  641. - `"fill-mask"`: will return a [`FillMaskPipeline`]:.
  642. - `"image-classification"`: will return a [`ImageClassificationPipeline`].
  643. - `"image-feature-extraction"`: will return an [`ImageFeatureExtractionPipeline`].
  644. - `"image-segmentation"`: will return a [`ImageSegmentationPipeline`].
  645. - `"image-text-to-text"`: will return a [`ImageTextToTextPipeline`].
  646. - `"image-to-image"`: will return a [`ImageToImagePipeline`].
  647. - `"image-to-text"`: will return a [`ImageToTextPipeline`].
  648. - `"keypoint-matching"`: will return a [`KeypointMatchingPipeline`].
  649. - `"mask-generation"`: will return a [`MaskGenerationPipeline`].
  650. - `"object-detection"`: will return a [`ObjectDetectionPipeline`].
  651. - `"question-answering"`: will return a [`QuestionAnsweringPipeline`].
  652. - `"summarization"`: will return a [`SummarizationPipeline`].
  653. - `"table-question-answering"`: will return a [`TableQuestionAnsweringPipeline`].
  654. - `"text2text-generation"`: will return a [`Text2TextGenerationPipeline`].
  655. - `"text-classification"` (alias `"sentiment-analysis"` available): will return a
  656. [`TextClassificationPipeline`].
  657. - `"text-generation"`: will return a [`TextGenerationPipeline`]:.
  658. - `"text-to-audio"` (alias `"text-to-speech"` available): will return a [`TextToAudioPipeline`]:.
  659. - `"token-classification"` (alias `"ner"` available): will return a [`TokenClassificationPipeline`].
  660. - `"translation"`: will return a [`TranslationPipeline`].
  661. - `"translation_xx_to_yy"`: will return a [`TranslationPipeline`].
  662. - `"video-classification"`: will return a [`VideoClassificationPipeline`].
  663. - `"visual-question-answering"`: will return a [`VisualQuestionAnsweringPipeline`].
  664. - `"zero-shot-classification"`: will return a [`ZeroShotClassificationPipeline`].
  665. - `"zero-shot-image-classification"`: will return a [`ZeroShotImageClassificationPipeline`].
  666. - `"zero-shot-audio-classification"`: will return a [`ZeroShotAudioClassificationPipeline`].
  667. - `"zero-shot-object-detection"`: will return a [`ZeroShotObjectDetectionPipeline`].
  668. model (`str` or [`PreTrainedModel`] or [`TFPreTrainedModel`], *optional*):
  669. The model that will be used by the pipeline to make predictions. This can be a model identifier or an
  670. actual instance of a pretrained model inheriting from [`PreTrainedModel`] (for PyTorch) or
  671. [`TFPreTrainedModel`] (for TensorFlow).
  672. If not provided, the default for the `task` will be loaded.
  673. config (`str` or [`PretrainedConfig`], *optional*):
  674. The configuration that will be used by the pipeline to instantiate the model. This can be a model
  675. identifier or an actual pretrained model configuration inheriting from [`PretrainedConfig`].
  676. If not provided, the default configuration file for the requested model will be used. That means that if
  677. `model` is given, its default configuration will be used. However, if `model` is not supplied, this
  678. `task`'s default model's config is used instead.
  679. tokenizer (`str` or [`PreTrainedTokenizer`], *optional*):
  680. The tokenizer that will be used by the pipeline to encode data for the model. This can be a model
  681. identifier or an actual pretrained tokenizer inheriting from [`PreTrainedTokenizer`].
  682. If not provided, the default tokenizer for the given `model` will be loaded (if it is a string). If `model`
  683. is not specified or not a string, then the default tokenizer for `config` is loaded (if it is a string).
  684. However, if `config` is also not given or not a string, then the default tokenizer for the given `task`
  685. will be loaded.
  686. feature_extractor (`str` or [`PreTrainedFeatureExtractor`], *optional*):
  687. The feature extractor that will be used by the pipeline to encode data for the model. This can be a model
  688. identifier or an actual pretrained feature extractor inheriting from [`PreTrainedFeatureExtractor`].
  689. Feature extractors are used for non-NLP models, such as Speech or Vision models as well as multi-modal
  690. models. Multi-modal models will also require a tokenizer to be passed.
  691. If not provided, the default feature extractor for the given `model` will be loaded (if it is a string). If
  692. `model` is not specified or not a string, then the default feature extractor for `config` is loaded (if it
  693. is a string). However, if `config` is also not given or not a string, then the default feature extractor
  694. for the given `task` will be loaded.
  695. image_processor (`str` or [`BaseImageProcessor`], *optional*):
  696. The image processor that will be used by the pipeline to preprocess images for the model. This can be a
  697. model identifier or an actual image processor inheriting from [`BaseImageProcessor`].
  698. Image processors are used for Vision models and multi-modal models that require image inputs. Multi-modal
  699. models will also require a tokenizer to be passed.
  700. If not provided, the default image processor for the given `model` will be loaded (if it is a string). If
  701. `model` is not specified or not a string, then the default image processor for `config` is loaded (if it is
  702. a string).
  703. processor (`str` or [`ProcessorMixin`], *optional*):
  704. The processor that will be used by the pipeline to preprocess data for the model. This can be a model
  705. identifier or an actual processor inheriting from [`ProcessorMixin`].
  706. Processors are used for multi-modal models that require multi-modal inputs, for example, a model that
  707. requires both text and image inputs.
  708. If not provided, the default processor for the given `model` will be loaded (if it is a string). If `model`
  709. is not specified or not a string, then the default processor for `config` is loaded (if it is a string).
  710. framework (`str`, *optional*):
  711. The framework to use, either `"pt"` for PyTorch or `"tf"` for TensorFlow. The specified framework must be
  712. installed.
  713. If no framework is specified, will default to the one currently installed. If no framework is specified and
  714. both frameworks are installed, will default to the framework of the `model`, or to PyTorch if no model is
  715. provided.
  716. revision (`str`, *optional*, defaults to `"main"`):
  717. When passing a task name or a string model identifier: The specific model version to use. It can be a
  718. branch name, a tag name, or a commit id, since we use a git-based system for storing models and other
  719. artifacts on huggingface.co, so `revision` can be any identifier allowed by git.
  720. use_fast (`bool`, *optional*, defaults to `True`):
  721. Whether or not to use a Fast tokenizer if possible (a [`PreTrainedTokenizerFast`]).
  722. use_auth_token (`str` or *bool*, *optional*):
  723. The token to use as HTTP bearer authorization for remote files. If `True`, will use the token generated
  724. when running `hf auth login` (stored in `~/.huggingface`).
  725. device (`int` or `str` or `torch.device`):
  726. Defines the device (*e.g.*, `"cpu"`, `"cuda:1"`, `"mps"`, or a GPU ordinal rank like `1`) on which this
  727. pipeline will be allocated.
  728. device_map (`str` or `dict[str, Union[int, str, torch.device]`, *optional*):
  729. Sent directly as `model_kwargs` (just a simpler shortcut). When `accelerate` library is present, set
  730. `device_map="auto"` to compute the most optimized `device_map` automatically (see
  731. [here](https://huggingface.co/docs/accelerate/main/en/package_reference/big_modeling#accelerate.cpu_offload)
  732. for more information).
  733. <Tip warning={true}>
  734. Do not use `device_map` AND `device` at the same time as they will conflict
  735. </Tip>
  736. dtype (`str` or `torch.dtype`, *optional*):
  737. Sent directly as `model_kwargs` (just a simpler shortcut) to use the available precision for this model
  738. (`torch.float16`, `torch.bfloat16`, ... or `"auto"`).
  739. trust_remote_code (`bool`, *optional*, defaults to `False`):
  740. Whether or not to allow for custom code defined on the Hub in their own modeling, configuration,
  741. tokenization or even pipeline files. This option should only be set to `True` for repositories you trust
  742. and in which you have read the code, as it will execute code present on the Hub on your local machine.
  743. model_kwargs (`dict[str, Any]`, *optional*):
  744. Additional dictionary of keyword arguments passed along to the model's `from_pretrained(...,
  745. **model_kwargs)` function.
  746. kwargs (`dict[str, Any]`, *optional*):
  747. Additional keyword arguments passed along to the specific pipeline init (see the documentation for the
  748. corresponding pipeline class for possible values).
  749. Returns:
  750. [`Pipeline`]: A suitable pipeline for the task.
  751. Examples:
  752. ```python
  753. >>> from transformers import pipeline, AutoModelForTokenClassification, AutoTokenizer
  754. >>> # Sentiment analysis pipeline
  755. >>> analyzer = pipeline("sentiment-analysis")
  756. >>> # Question answering pipeline, specifying the checkpoint identifier
  757. >>> oracle = pipeline(
  758. ... "question-answering", model="distilbert/distilbert-base-cased-distilled-squad", tokenizer="google-bert/bert-base-cased"
  759. ... )
  760. >>> # Named entity recognition pipeline, passing in a specific model and tokenizer
  761. >>> model = AutoModelForTokenClassification.from_pretrained("dbmdz/bert-large-cased-finetuned-conll03-english")
  762. >>> tokenizer = AutoTokenizer.from_pretrained("google-bert/bert-base-cased")
  763. >>> recognizer = pipeline("ner", model=model, tokenizer=tokenizer)
  764. ```"""
  765. if model_kwargs is None:
  766. model_kwargs = {}
  767. # Make sure we only pass use_auth_token once as a kwarg (it used to be possible to pass it in model_kwargs,
  768. # this is to keep BC).
  769. use_auth_token = model_kwargs.pop("use_auth_token", None)
  770. if use_auth_token is not None:
  771. warnings.warn(
  772. "The `use_auth_token` argument is deprecated and will be removed in v5 of Transformers. Please use `token` instead.",
  773. FutureWarning,
  774. )
  775. if token is not None:
  776. raise ValueError("`token` and `use_auth_token` are both specified. Please set only the argument `token`.")
  777. token = use_auth_token
  778. code_revision = kwargs.pop("code_revision", None)
  779. commit_hash = kwargs.pop("_commit_hash", None)
  780. hub_kwargs = {
  781. "revision": revision,
  782. "token": token,
  783. "trust_remote_code": trust_remote_code,
  784. "_commit_hash": commit_hash,
  785. }
  786. if task is None and model is None:
  787. raise RuntimeError(
  788. "Impossible to instantiate a pipeline without either a task or a model "
  789. "being specified. "
  790. "Please provide a task class or a model"
  791. )
  792. if model is None and tokenizer is not None:
  793. raise RuntimeError(
  794. "Impossible to instantiate a pipeline with tokenizer specified but not the model as the provided tokenizer"
  795. " may not be compatible with the default model. Please provide a PreTrainedModel class or a"
  796. " path/identifier to a pretrained model when providing tokenizer."
  797. )
  798. if model is None and feature_extractor is not None:
  799. raise RuntimeError(
  800. "Impossible to instantiate a pipeline with feature_extractor specified but not the model as the provided"
  801. " feature_extractor may not be compatible with the default model. Please provide a PreTrainedModel class"
  802. " or a path/identifier to a pretrained model when providing feature_extractor."
  803. )
  804. if isinstance(model, Path):
  805. model = str(model)
  806. if commit_hash is None:
  807. pretrained_model_name_or_path = None
  808. if isinstance(config, str):
  809. pretrained_model_name_or_path = config
  810. elif config is None and isinstance(model, str):
  811. pretrained_model_name_or_path = model
  812. if not isinstance(config, PretrainedConfig) and pretrained_model_name_or_path is not None:
  813. # We make a call to the config file first (which may be absent) to get the commit hash as soon as possible
  814. resolved_config_file = cached_file(
  815. pretrained_model_name_or_path,
  816. CONFIG_NAME,
  817. _raise_exceptions_for_gated_repo=False,
  818. _raise_exceptions_for_missing_entries=False,
  819. _raise_exceptions_for_connection_errors=False,
  820. cache_dir=model_kwargs.get("cache_dir"),
  821. **hub_kwargs,
  822. )
  823. hub_kwargs["_commit_hash"] = extract_commit_hash(resolved_config_file, commit_hash)
  824. else:
  825. hub_kwargs["_commit_hash"] = getattr(config, "_commit_hash", None)
  826. # Config is the primordial information item.
  827. # Instantiate config if needed
  828. adapter_path = None
  829. if isinstance(config, str):
  830. config = AutoConfig.from_pretrained(
  831. config, _from_pipeline=task, code_revision=code_revision, **hub_kwargs, **model_kwargs
  832. )
  833. hub_kwargs["_commit_hash"] = config._commit_hash
  834. elif config is None and isinstance(model, str):
  835. # Check for an adapter file in the model path if PEFT is available
  836. if is_peft_available():
  837. # `find_adapter_config_file` doesn't accept `trust_remote_code`
  838. _hub_kwargs = {k: v for k, v in hub_kwargs.items() if k != "trust_remote_code"}
  839. maybe_adapter_path = find_adapter_config_file(
  840. model,
  841. token=hub_kwargs["token"],
  842. revision=hub_kwargs["revision"],
  843. _commit_hash=hub_kwargs["_commit_hash"],
  844. )
  845. if maybe_adapter_path is not None:
  846. with open(maybe_adapter_path, "r", encoding="utf-8") as f:
  847. adapter_config = json.load(f)
  848. adapter_path = model
  849. model = adapter_config["base_model_name_or_path"]
  850. config = AutoConfig.from_pretrained(
  851. model, _from_pipeline=task, code_revision=code_revision, **hub_kwargs, **model_kwargs
  852. )
  853. hub_kwargs["_commit_hash"] = config._commit_hash
  854. custom_tasks = {}
  855. if config is not None and len(getattr(config, "custom_pipelines", {})) > 0:
  856. custom_tasks = config.custom_pipelines
  857. if task is None and trust_remote_code is not False:
  858. if len(custom_tasks) == 1:
  859. task = list(custom_tasks.keys())[0]
  860. else:
  861. raise RuntimeError(
  862. "We can't infer the task automatically for this model as there are multiple tasks available. Pick "
  863. f"one in {', '.join(custom_tasks.keys())}"
  864. )
  865. if task is None and model is not None:
  866. if not isinstance(model, str):
  867. raise RuntimeError(
  868. "Inferring the task automatically requires to check the hub with a model_id defined as a `str`. "
  869. f"{model} is not a valid model_id."
  870. )
  871. task = get_task(model, token)
  872. # Retrieve the task
  873. if task in custom_tasks:
  874. targeted_task, task_options = clean_custom_task(custom_tasks[task])
  875. if pipeline_class is None:
  876. if not trust_remote_code:
  877. raise ValueError(
  878. "Loading this pipeline requires you to execute the code in the pipeline file in that"
  879. " repo on your local machine. Make sure you have read the code there to avoid malicious use, then"
  880. " set the option `trust_remote_code=True` to remove this error."
  881. )
  882. class_ref = targeted_task["impl"]
  883. pipeline_class = get_class_from_dynamic_module(
  884. class_ref,
  885. model,
  886. code_revision=code_revision,
  887. **hub_kwargs,
  888. )
  889. else:
  890. normalized_task, targeted_task, task_options = check_task(task)
  891. if pipeline_class is None:
  892. pipeline_class = targeted_task["impl"]
  893. # Use default model/config/tokenizer for the task if no model is provided
  894. if model is None:
  895. # At that point framework might still be undetermined
  896. model, default_revision = get_default_model_and_revision(targeted_task, framework, task_options)
  897. revision = revision if revision is not None else default_revision
  898. logger.warning(
  899. f"No model was supplied, defaulted to {model} and revision"
  900. f" {revision} ({HUGGINGFACE_CO_RESOLVE_ENDPOINT}/{model}).\n"
  901. "Using a pipeline without specifying a model name and revision in production is not recommended."
  902. )
  903. hub_kwargs["revision"] = revision
  904. if config is None and isinstance(model, str):
  905. config = AutoConfig.from_pretrained(model, _from_pipeline=task, **hub_kwargs, **model_kwargs)
  906. hub_kwargs["_commit_hash"] = config._commit_hash
  907. if device_map is not None:
  908. if "device_map" in model_kwargs:
  909. raise ValueError(
  910. 'You cannot use both `pipeline(... device_map=..., model_kwargs={"device_map":...})` as those'
  911. " arguments might conflict, use only one.)"
  912. )
  913. if device is not None:
  914. logger.warning(
  915. "Both `device` and `device_map` are specified. `device` will override `device_map`. You"
  916. " will most likely encounter unexpected behavior. Please remove `device` and keep `device_map`."
  917. )
  918. model_kwargs["device_map"] = device_map
  919. # BC for the `torch_dtype` argument
  920. if (torch_dtype := kwargs.get("torch_dtype")) is not None:
  921. logger.warning_once("`torch_dtype` is deprecated! Use `dtype` instead!")
  922. # If both are provided, keep `dtype`
  923. dtype = torch_dtype if dtype == "auto" else dtype
  924. if "torch_dtype" in model_kwargs or "dtype" in model_kwargs:
  925. if "torch_dtype" in model_kwargs:
  926. logger.warning_once("`torch_dtype` is deprecated! Use `dtype` instead!")
  927. # If the user did not explicitly provide `dtype` (i.e. the function default "auto" is still
  928. # present) but a value is supplied inside `model_kwargs`, we silently defer to the latter instead of
  929. # raising. This prevents false positives like providing `dtype` only via `model_kwargs` while the
  930. # top-level argument keeps its default value "auto".
  931. if dtype == "auto":
  932. dtype = None
  933. else:
  934. raise ValueError(
  935. 'You cannot use both `pipeline(... dtype=..., model_kwargs={"dtype":...})` as those'
  936. " arguments might conflict, use only one.)"
  937. )
  938. if dtype is not None:
  939. if isinstance(dtype, str) and hasattr(torch, dtype):
  940. dtype = getattr(torch, dtype)
  941. model_kwargs["dtype"] = dtype
  942. model_name = model if isinstance(model, str) else None
  943. # Load the correct model if possible
  944. # Infer the framework from the model if not already defined
  945. if isinstance(model, str) or framework is None:
  946. model_classes = {"tf": targeted_task["tf"], "pt": targeted_task["pt"]}
  947. framework, model = infer_framework_load_model(
  948. adapter_path if adapter_path is not None else model,
  949. model_classes=model_classes,
  950. config=config,
  951. framework=framework,
  952. task=task,
  953. **hub_kwargs,
  954. **model_kwargs,
  955. )
  956. hub_kwargs["_commit_hash"] = model.config._commit_hash
  957. # Check which preprocessing classes the pipeline uses
  958. # None values indicate optional classes that the pipeline can run without, we don't raise errors if loading fails
  959. load_tokenizer = pipeline_class._load_tokenizer
  960. load_feature_extractor = pipeline_class._load_feature_extractor
  961. load_image_processor = pipeline_class._load_image_processor
  962. load_processor = pipeline_class._load_processor
  963. if load_tokenizer or load_tokenizer is None:
  964. try:
  965. # Try to infer tokenizer from model or config name (if provided as str)
  966. if tokenizer is None:
  967. if isinstance(model_name, str):
  968. tokenizer = model_name
  969. elif isinstance(config, str):
  970. tokenizer = config
  971. else:
  972. # Impossible to guess what is the right tokenizer here
  973. raise Exception(
  974. "Impossible to guess which tokenizer to use. "
  975. "Please provide a PreTrainedTokenizer class or a path/identifier to a pretrained tokenizer."
  976. )
  977. # Instantiate tokenizer if needed
  978. if isinstance(tokenizer, (str, tuple)):
  979. if isinstance(tokenizer, tuple):
  980. # For tuple we have (tokenizer name, {kwargs})
  981. use_fast = tokenizer[1].pop("use_fast", use_fast)
  982. tokenizer_identifier = tokenizer[0]
  983. tokenizer_kwargs = tokenizer[1]
  984. else:
  985. tokenizer_identifier = tokenizer
  986. tokenizer_kwargs = model_kwargs.copy()
  987. tokenizer_kwargs.pop("torch_dtype", None), tokenizer_kwargs.pop("dtype", None)
  988. tokenizer = AutoTokenizer.from_pretrained(
  989. tokenizer_identifier, use_fast=use_fast, _from_pipeline=task, **hub_kwargs, **tokenizer_kwargs
  990. )
  991. except Exception as e:
  992. if load_tokenizer:
  993. raise e
  994. else:
  995. tokenizer = None
  996. if load_image_processor or load_image_processor is None:
  997. try:
  998. # Try to infer image processor from model or config name (if provided as str)
  999. if image_processor is None:
  1000. if isinstance(model_name, str):
  1001. image_processor = model_name
  1002. elif isinstance(config, str):
  1003. image_processor = config
  1004. # Backward compatibility, as `feature_extractor` used to be the name
  1005. # for `ImageProcessor`.
  1006. elif feature_extractor is not None and isinstance(feature_extractor, BaseImageProcessor):
  1007. image_processor = feature_extractor
  1008. else:
  1009. # Impossible to guess what is the right image_processor here
  1010. raise Exception(
  1011. "Impossible to guess which image processor to use. "
  1012. "Please provide a PreTrainedImageProcessor class or a path/identifier "
  1013. "to a pretrained image processor."
  1014. )
  1015. # Instantiate image_processor if needed
  1016. if isinstance(image_processor, (str, tuple)):
  1017. image_processor = AutoImageProcessor.from_pretrained(
  1018. image_processor, _from_pipeline=task, **hub_kwargs, **model_kwargs
  1019. )
  1020. except Exception as e:
  1021. if load_image_processor:
  1022. raise e
  1023. else:
  1024. image_processor = None
  1025. if load_feature_extractor or load_feature_extractor is None:
  1026. try:
  1027. # Try to infer feature extractor from model or config name (if provided as str)
  1028. if feature_extractor is None:
  1029. if isinstance(model_name, str):
  1030. feature_extractor = model_name
  1031. elif isinstance(config, str):
  1032. feature_extractor = config
  1033. else:
  1034. # Impossible to guess what is the right feature_extractor here
  1035. raise Exception(
  1036. "Impossible to guess which feature extractor to use. "
  1037. "Please provide a PreTrainedFeatureExtractor class or a path/identifier "
  1038. "to a pretrained feature extractor."
  1039. )
  1040. # Instantiate feature_extractor if needed
  1041. if isinstance(feature_extractor, (str, tuple)):
  1042. feature_extractor = AutoFeatureExtractor.from_pretrained(
  1043. feature_extractor, _from_pipeline=task, **hub_kwargs, **model_kwargs
  1044. )
  1045. if (
  1046. feature_extractor._processor_class
  1047. and feature_extractor._processor_class.endswith("WithLM")
  1048. and isinstance(model_name, str)
  1049. ):
  1050. try:
  1051. import kenlm # to trigger `ImportError` if not installed
  1052. from pyctcdecode import BeamSearchDecoderCTC
  1053. if os.path.isdir(model_name) or os.path.isfile(model_name):
  1054. decoder = BeamSearchDecoderCTC.load_from_dir(model_name)
  1055. else:
  1056. language_model_glob = os.path.join(
  1057. BeamSearchDecoderCTC._LANGUAGE_MODEL_SERIALIZED_DIRECTORY, "*"
  1058. )
  1059. alphabet_filename = BeamSearchDecoderCTC._ALPHABET_SERIALIZED_FILENAME
  1060. allow_patterns = [language_model_glob, alphabet_filename]
  1061. decoder = BeamSearchDecoderCTC.load_from_hf_hub(model_name, allow_patterns=allow_patterns)
  1062. kwargs["decoder"] = decoder
  1063. except ImportError as e:
  1064. logger.warning(
  1065. f"Could not load the `decoder` for {model_name}. Defaulting to raw CTC. Error: {e}"
  1066. )
  1067. if not is_kenlm_available():
  1068. logger.warning("Try to install `kenlm`: `pip install kenlm")
  1069. if not is_pyctcdecode_available():
  1070. logger.warning("Try to install `pyctcdecode`: `pip install pyctcdecode")
  1071. except Exception as e:
  1072. if load_feature_extractor:
  1073. raise e
  1074. else:
  1075. feature_extractor = None
  1076. if load_processor or load_processor is None:
  1077. try:
  1078. # Try to infer processor from model or config name (if provided as str)
  1079. if processor is None:
  1080. if isinstance(model_name, str):
  1081. processor = model_name
  1082. elif isinstance(config, str):
  1083. processor = config
  1084. else:
  1085. # Impossible to guess what is the right processor here
  1086. raise Exception(
  1087. "Impossible to guess which processor to use. "
  1088. "Please provide a processor instance or a path/identifier "
  1089. "to a processor."
  1090. )
  1091. # Instantiate processor if needed
  1092. if isinstance(processor, (str, tuple)):
  1093. processor = AutoProcessor.from_pretrained(processor, _from_pipeline=task, **hub_kwargs, **model_kwargs)
  1094. if not isinstance(processor, ProcessorMixin):
  1095. raise TypeError(
  1096. "Processor was loaded, but it is not an instance of `ProcessorMixin`. "
  1097. f"Got type `{type(processor)}` instead. Please check that you specified "
  1098. "correct pipeline task for the model and model has processor implemented and saved."
  1099. )
  1100. except Exception as e:
  1101. if load_processor:
  1102. raise e
  1103. else:
  1104. processor = None
  1105. if task == "translation" and model.config.task_specific_params:
  1106. for key in model.config.task_specific_params:
  1107. if key.startswith("translation"):
  1108. task = key
  1109. warnings.warn(
  1110. f'"translation" task was used, instead of "translation_XX_to_YY", defaulting to "{task}"',
  1111. UserWarning,
  1112. )
  1113. break
  1114. if tokenizer is not None:
  1115. kwargs["tokenizer"] = tokenizer
  1116. if feature_extractor is not None:
  1117. kwargs["feature_extractor"] = feature_extractor
  1118. if dtype is not None:
  1119. kwargs["dtype"] = dtype
  1120. if image_processor is not None:
  1121. kwargs["image_processor"] = image_processor
  1122. if device is not None:
  1123. kwargs["device"] = device
  1124. if processor is not None:
  1125. kwargs["processor"] = processor
  1126. return pipeline_class(model=model, framework=framework, task=task, **kwargs)