base.py 68 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590
  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 collections
  16. import copy
  17. import csv
  18. import importlib
  19. import json
  20. import os
  21. import pickle
  22. import sys
  23. import traceback
  24. import types
  25. import warnings
  26. from abc import ABC, abstractmethod
  27. from collections import UserDict
  28. from contextlib import contextmanager
  29. from os.path import abspath, exists
  30. from typing import TYPE_CHECKING, Any, Optional, Union
  31. from ..dynamic_module_utils import custom_object_save
  32. from ..feature_extraction_utils import PreTrainedFeatureExtractor
  33. from ..generation import GenerationConfig
  34. from ..image_processing_utils import BaseImageProcessor
  35. from ..modelcard import ModelCard
  36. from ..models.auto import AutoConfig, AutoTokenizer
  37. from ..processing_utils import ProcessorMixin
  38. from ..tokenization_utils import PreTrainedTokenizer
  39. from ..utils import (
  40. ModelOutput,
  41. PushToHubMixin,
  42. add_end_docstrings,
  43. copy_func,
  44. infer_framework,
  45. is_tf_available,
  46. is_torch_available,
  47. is_torch_cuda_available,
  48. is_torch_hpu_available,
  49. is_torch_mlu_available,
  50. is_torch_mps_available,
  51. is_torch_musa_available,
  52. is_torch_npu_available,
  53. is_torch_xpu_available,
  54. logging,
  55. )
  56. from ..utils.deprecation import deprecate_kwarg
  57. GenericTensor = Union[list["GenericTensor"], "torch.Tensor", "tf.Tensor"]
  58. if is_tf_available():
  59. import tensorflow as tf
  60. from ..models.auto.modeling_tf_auto import TFAutoModel
  61. if is_torch_available() or TYPE_CHECKING:
  62. import torch
  63. from torch.utils.data import DataLoader, Dataset
  64. from ..modeling_utils import PreTrainedModel
  65. from ..models.auto.modeling_auto import AutoModel
  66. # Re-export for backward compatibility
  67. from .pt_utils import KeyDataset
  68. else:
  69. Dataset = None
  70. KeyDataset = None
  71. if TYPE_CHECKING:
  72. from ..modeling_tf_utils import TFPreTrainedModel
  73. from ..modeling_utils import PreTrainedModel
  74. logger = logging.get_logger(__name__)
  75. def no_collate_fn(items):
  76. if len(items) != 1:
  77. raise ValueError("This collate_fn is meant to be used with batch_size=1")
  78. return items[0]
  79. def _pad(items, key, padding_value, padding_side):
  80. batch_size = len(items)
  81. if isinstance(items[0][key], torch.Tensor):
  82. # Others include `attention_mask` etc...
  83. shape = items[0][key].shape
  84. dim = len(shape)
  85. if dim == 1:
  86. # We have a list of 1-dim torch tensors, which can be stacked without padding
  87. return torch.cat([item[key] for item in items], dim=0)
  88. if key in ["pixel_values", "image"]:
  89. # This is probable image so padding shouldn't be necessary
  90. # B, C, H, W
  91. return torch.cat([item[key] for item in items], dim=0)
  92. elif dim == 4 and key == "input_features":
  93. # this is probably a mel spectrogram batched
  94. return torch.cat([item[key] for item in items], dim=0)
  95. max_length = max(item[key].shape[1] for item in items)
  96. min_length = min(item[key].shape[1] for item in items)
  97. dtype = items[0][key].dtype
  98. if dim == 2:
  99. if max_length == min_length:
  100. # Bypass for `ImageGPT` which doesn't provide a padding value, yet
  101. # we can consistently pad since the size should be matching
  102. return torch.cat([item[key] for item in items], dim=0)
  103. tensor = torch.zeros((batch_size, max_length), dtype=dtype) + padding_value
  104. elif dim == 3:
  105. tensor = torch.zeros((batch_size, max_length, shape[-1]), dtype=dtype) + padding_value
  106. elif dim == 4:
  107. tensor = torch.zeros((batch_size, max_length, shape[-2], shape[-1]), dtype=dtype) + padding_value
  108. for i, item in enumerate(items):
  109. if dim == 2:
  110. if padding_side == "left":
  111. tensor[i, -len(item[key][0]) :] = item[key][0].clone()
  112. else:
  113. tensor[i, : len(item[key][0])] = item[key][0].clone()
  114. elif dim == 3:
  115. if padding_side == "left":
  116. tensor[i, -len(item[key][0]) :, :] = item[key][0].clone()
  117. else:
  118. tensor[i, : len(item[key][0]), :] = item[key][0].clone()
  119. elif dim == 4:
  120. if padding_side == "left":
  121. tensor[i, -len(item[key][0]) :, :, :] = item[key][0].clone()
  122. else:
  123. tensor[i, : len(item[key][0]), :, :] = item[key][0].clone()
  124. return tensor
  125. else:
  126. return [item[key] for item in items]
  127. def pad_collate_fn(tokenizer, feature_extractor):
  128. # Tokenizer
  129. t_padding_side = None
  130. # Feature extractor
  131. f_padding_side = None
  132. if tokenizer is None and feature_extractor is None:
  133. raise ValueError("Pipeline without tokenizer or feature_extractor cannot do batching")
  134. if tokenizer is not None:
  135. if tokenizer.pad_token_id is None:
  136. raise ValueError(
  137. "Pipeline with tokenizer without pad_token cannot do batching. You can try to set it with "
  138. "`pipe.tokenizer.pad_token_id = model.config.eos_token_id`."
  139. )
  140. else:
  141. t_padding_value = tokenizer.pad_token_id
  142. t_padding_side = tokenizer.padding_side
  143. if feature_extractor is not None:
  144. # Feature extractor can be images, where no padding is expected
  145. f_padding_value = getattr(feature_extractor, "padding_value", None)
  146. f_padding_side = getattr(feature_extractor, "padding_side", None)
  147. if t_padding_side is not None and f_padding_side is not None and t_padding_side != f_padding_side:
  148. raise ValueError(
  149. f"The feature extractor, and tokenizer don't agree on padding side {t_padding_side} != {f_padding_side}"
  150. )
  151. padding_side = "right"
  152. if t_padding_side is not None:
  153. padding_side = t_padding_side
  154. if f_padding_side is not None:
  155. padding_side = f_padding_side
  156. def inner(items):
  157. keys = set(items[0].keys())
  158. for item in items:
  159. if set(item.keys()) != keys:
  160. raise ValueError(
  161. f"The elements of the batch contain different keys. Cannot batch them ({set(item.keys())} !="
  162. f" {keys})"
  163. )
  164. # input_values, input_pixels, input_ids, ...
  165. padded = {}
  166. for key in keys:
  167. if key == "input_ids":
  168. # ImageGPT uses a feature extractor
  169. if tokenizer is None and feature_extractor is not None:
  170. _padding_value = f_padding_value
  171. else:
  172. _padding_value = t_padding_value
  173. elif key in {"input_values", "pixel_values", "input_features"}:
  174. _padding_value = f_padding_value
  175. elif key in {"p_mask", "special_tokens_mask"}:
  176. _padding_value = 1
  177. elif key in {"attention_mask", "token_type_ids"}:
  178. _padding_value = 0
  179. else:
  180. # This is likely another random key maybe even user provided
  181. _padding_value = 0
  182. padded[key] = _pad(items, key, _padding_value, padding_side)
  183. return padded
  184. return inner
  185. def infer_framework_load_model(
  186. model,
  187. config: AutoConfig,
  188. model_classes: Optional[dict[str, tuple[type]]] = None,
  189. task: Optional[str] = None,
  190. framework: Optional[str] = None,
  191. **model_kwargs,
  192. ):
  193. """
  194. Select framework (TensorFlow or PyTorch) to use from the `model` passed. Returns a tuple (framework, model).
  195. If `model` is instantiated, this function will just infer the framework from the model class. Otherwise `model` is
  196. actually a checkpoint name and this method will try to instantiate it using `model_classes`. Since we don't want to
  197. instantiate the model twice, this model is returned for use by the pipeline.
  198. If both frameworks are installed and available for `model`, PyTorch is selected.
  199. Args:
  200. model (`str`, [`PreTrainedModel`] or [`TFPreTrainedModel]`):
  201. The model to infer the framework from. If `str`, a checkpoint name. The model to infer the framewrok from.
  202. config ([`AutoConfig`]):
  203. The config associated with the model to help using the correct class
  204. model_classes (dictionary `str` to `type`, *optional*):
  205. A mapping framework to class.
  206. task (`str`):
  207. The task defining which pipeline will be returned.
  208. model_kwargs:
  209. Additional dictionary of keyword arguments passed along to the model's `from_pretrained(...,
  210. **model_kwargs)` function.
  211. Returns:
  212. `Tuple`: A tuple framework, model.
  213. """
  214. if not is_tf_available() and not is_torch_available():
  215. raise RuntimeError(
  216. "At least one of TensorFlow 2.0 or PyTorch should be installed. "
  217. "To install TensorFlow 2.0, read the instructions at https://www.tensorflow.org/install/ "
  218. "To install PyTorch, read the instructions at https://pytorch.org/."
  219. )
  220. if isinstance(model, str):
  221. model_kwargs["_from_pipeline"] = task
  222. class_tuple = ()
  223. look_pt = is_torch_available() and framework in {"pt", None}
  224. look_tf = is_tf_available() and framework in {"tf", None}
  225. if model_classes:
  226. if look_pt:
  227. class_tuple = class_tuple + model_classes.get("pt", (AutoModel,))
  228. if look_tf:
  229. class_tuple = class_tuple + model_classes.get("tf", (TFAutoModel,))
  230. if config.architectures:
  231. classes = []
  232. for architecture in config.architectures:
  233. transformers_module = importlib.import_module("transformers")
  234. if look_pt:
  235. _class = getattr(transformers_module, architecture, None)
  236. if _class is not None:
  237. classes.append(_class)
  238. if look_tf:
  239. _class = getattr(transformers_module, f"TF{architecture}", None)
  240. if _class is not None:
  241. classes.append(_class)
  242. class_tuple = class_tuple + tuple(classes)
  243. if len(class_tuple) == 0:
  244. raise ValueError(f"Pipeline cannot infer suitable model classes from {model}")
  245. all_traceback = {}
  246. for model_class in class_tuple:
  247. kwargs = model_kwargs.copy()
  248. if framework == "pt" and model.endswith(".h5"):
  249. kwargs["from_tf"] = True
  250. logger.warning(
  251. "Model might be a TensorFlow model (ending with `.h5`) but TensorFlow is not available. "
  252. "Trying to load the model with PyTorch."
  253. )
  254. elif framework == "tf" and model.endswith(".bin"):
  255. kwargs["from_pt"] = True
  256. logger.warning(
  257. "Model might be a PyTorch model (ending with `.bin`) but PyTorch is not available. "
  258. "Trying to load the model with Tensorflow."
  259. )
  260. try:
  261. model = model_class.from_pretrained(model, **kwargs)
  262. if hasattr(model, "eval"):
  263. model = model.eval()
  264. # Stop loading on the first successful load.
  265. break
  266. except (OSError, ValueError, TypeError, RuntimeError):
  267. # `from_pretrained` may raise a `TypeError` or `RuntimeError` when the requested `dtype`
  268. # is not supported on the execution device (e.g. bf16 on a consumer GPU). We capture those so
  269. # we can transparently retry the load in float32 before surfacing an error to the user.
  270. fallback_tried = False
  271. if is_torch_available() and ("dtype" in kwargs):
  272. import torch # local import to avoid unnecessarily importing torch for TF/JAX users
  273. fallback_tried = True
  274. fp32_kwargs = kwargs.copy()
  275. fp32_kwargs["dtype"] = torch.float32
  276. try:
  277. model = model_class.from_pretrained(model, **fp32_kwargs)
  278. if hasattr(model, "eval"):
  279. model = model.eval()
  280. logger.warning(
  281. "Falling back to torch.float32 because loading with the original dtype failed on the"
  282. " target device."
  283. )
  284. break
  285. except Exception:
  286. # If it still fails, capture the traceback and continue to the next class.
  287. all_traceback[model_class.__name__] = traceback.format_exc()
  288. continue
  289. # If no fallback was attempted or it also failed, record the original traceback.
  290. if not fallback_tried:
  291. all_traceback[model_class.__name__] = traceback.format_exc()
  292. continue
  293. if isinstance(model, str):
  294. error = ""
  295. for class_name, trace in all_traceback.items():
  296. error += f"while loading with {class_name}, an error is thrown:\n{trace}\n"
  297. raise ValueError(
  298. f"Could not load model {model} with any of the following classes: {class_tuple}. See the original errors:\n\n{error}\n"
  299. )
  300. if framework is None:
  301. framework = infer_framework(model.__class__)
  302. return framework, model
  303. def infer_framework_from_model(
  304. model,
  305. model_classes: Optional[dict[str, tuple[type]]] = None,
  306. task: Optional[str] = None,
  307. framework: Optional[str] = None,
  308. **model_kwargs,
  309. ):
  310. """
  311. Select framework (TensorFlow or PyTorch) to use from the `model` passed. Returns a tuple (framework, model).
  312. If `model` is instantiated, this function will just infer the framework from the model class. Otherwise `model` is
  313. actually a checkpoint name and this method will try to instantiate it using `model_classes`. Since we don't want to
  314. instantiate the model twice, this model is returned for use by the pipeline.
  315. If both frameworks are installed and available for `model`, PyTorch is selected.
  316. Args:
  317. model (`str`, [`PreTrainedModel`] or [`TFPreTrainedModel]`):
  318. The model to infer the framework from. If `str`, a checkpoint name. The model to infer the framewrok from.
  319. model_classes (dictionary `str` to `type`, *optional*):
  320. A mapping framework to class.
  321. task (`str`):
  322. The task defining which pipeline will be returned.
  323. model_kwargs:
  324. Additional dictionary of keyword arguments passed along to the model's `from_pretrained(...,
  325. **model_kwargs)` function.
  326. Returns:
  327. `Tuple`: A tuple framework, model.
  328. """
  329. if isinstance(model, str):
  330. config = AutoConfig.from_pretrained(model, _from_pipeline=task, **model_kwargs)
  331. else:
  332. config = model.config
  333. return infer_framework_load_model(
  334. model, config, model_classes=model_classes, _from_pipeline=task, task=task, framework=framework, **model_kwargs
  335. )
  336. def get_framework(model, revision: Optional[str] = None):
  337. """
  338. Select framework (TensorFlow or PyTorch) to use.
  339. Args:
  340. model (`str`, [`PreTrainedModel`] or [`TFPreTrainedModel]`):
  341. If both frameworks are installed, picks the one corresponding to the model passed (either a model class or
  342. the model name). If no specific model is provided, defaults to using PyTorch.
  343. """
  344. warnings.warn(
  345. "`get_framework` is deprecated and will be removed in v5, use `infer_framework_from_model` instead.",
  346. FutureWarning,
  347. )
  348. if not is_tf_available() and not is_torch_available():
  349. raise RuntimeError(
  350. "At least one of TensorFlow 2.0 or PyTorch should be installed. "
  351. "To install TensorFlow 2.0, read the instructions at https://www.tensorflow.org/install/ "
  352. "To install PyTorch, read the instructions at https://pytorch.org/."
  353. )
  354. if isinstance(model, str):
  355. if is_torch_available() and not is_tf_available():
  356. model = AutoModel.from_pretrained(model, revision=revision)
  357. elif is_tf_available() and not is_torch_available():
  358. model = TFAutoModel.from_pretrained(model, revision=revision)
  359. else:
  360. try:
  361. model = AutoModel.from_pretrained(model, revision=revision)
  362. except OSError:
  363. model = TFAutoModel.from_pretrained(model, revision=revision)
  364. framework = infer_framework(model.__class__)
  365. return framework
  366. def get_default_model_and_revision(
  367. targeted_task: dict, framework: Optional[str], task_options: Optional[Any]
  368. ) -> tuple[str, str]:
  369. """
  370. Select a default model to use for a given task. Defaults to pytorch if ambiguous.
  371. Args:
  372. targeted_task (`Dict`):
  373. Dictionary representing the given task, that should contain default models
  374. framework (`str`, None)
  375. "pt", "tf" or None, representing a specific framework if it was specified, or None if we don't know yet.
  376. task_options (`Any`, None)
  377. Any further value required by the task to get fully specified, for instance (SRC, TGT) languages for
  378. translation task.
  379. Returns
  380. Tuple:
  381. - `str` The model string representing the default model for this pipeline.
  382. - `str` The revision of the model.
  383. """
  384. if is_torch_available() and not is_tf_available():
  385. framework = "pt"
  386. elif is_tf_available() and not is_torch_available():
  387. framework = "tf"
  388. defaults = targeted_task["default"]
  389. if task_options:
  390. if task_options not in defaults:
  391. raise ValueError(f"The task does not provide any default models for options {task_options}")
  392. default_models = defaults[task_options]["model"]
  393. elif "model" in defaults:
  394. default_models = targeted_task["default"]["model"]
  395. else:
  396. # XXX This error message needs to be updated to be more generic if more tasks are going to become
  397. # parametrized
  398. raise ValueError('The task defaults can\'t be correctly selected. You probably meant "translation_xx_to_yy"')
  399. if framework is None:
  400. framework = "pt"
  401. return default_models[framework]
  402. def load_assistant_model(
  403. model: "PreTrainedModel",
  404. assistant_model: Optional[Union[str, "PreTrainedModel"]],
  405. assistant_tokenizer: Optional[PreTrainedTokenizer],
  406. ) -> tuple[Optional["PreTrainedModel"], Optional[PreTrainedTokenizer]]:
  407. """
  408. Prepares the assistant model and the assistant tokenizer for a pipeline whose model that can call `generate`.
  409. Args:
  410. model ([`PreTrainedModel`]):
  411. The main model that will be used by the pipeline to make predictions.
  412. assistant_model (`str` or [`PreTrainedModel`], *optional*):
  413. The assistant model that will be used by the pipeline to make predictions.
  414. assistant_tokenizer ([`PreTrainedTokenizer`], *optional*):
  415. The assistant tokenizer that will be used by the pipeline to encode data for the model.
  416. Returns:
  417. Tuple: The loaded assistant model and (optionally) the loaded tokenizer.
  418. """
  419. if not model.can_generate() or assistant_model is None:
  420. return None, None
  421. if getattr(model, "framework") != "pt" or not isinstance(model, PreTrainedModel):
  422. raise ValueError(
  423. "Assisted generation, triggered by the `assistant_model` argument, is only available for "
  424. "`PreTrainedModel` model instances. For instance, TF or JAX models are not supported."
  425. )
  426. # If the model is passed as a string, load the model and the corresponding tokenizer
  427. if isinstance(assistant_model, str):
  428. assistant_config = AutoConfig.from_pretrained(assistant_model)
  429. _, loaded_assistant_model = infer_framework_load_model(assistant_model, config=assistant_config)
  430. loaded_assistant_model = loaded_assistant_model.to(device=model.device, dtype=model.dtype)
  431. loaded_assistant_tokenizer = AutoTokenizer.from_pretrained(assistant_model)
  432. else:
  433. loaded_assistant_model = assistant_model
  434. loaded_assistant_tokenizer = assistant_tokenizer
  435. # Finally, let's check the tokenizers: if the two models have different tokenizers, we need to keep the assistant
  436. # tokenizer
  437. same_vocab_size = model.config.vocab_size == loaded_assistant_model.config.vocab_size
  438. same_special_tokens = all(
  439. getattr(model.config, token) == getattr(loaded_assistant_model.config, token)
  440. for token in ("eos_token_id", "pad_token_id", "bos_token_id")
  441. )
  442. if same_vocab_size and same_special_tokens:
  443. loaded_assistant_tokenizer = None
  444. elif loaded_assistant_tokenizer is None:
  445. raise ValueError(
  446. "The assistant model has a different tokenizer than the main model. You should pass the assistant "
  447. "tokenizer."
  448. )
  449. return loaded_assistant_model, loaded_assistant_tokenizer
  450. class PipelineException(Exception):
  451. """
  452. Raised by a [`Pipeline`] when handling __call__.
  453. Args:
  454. task (`str`): The task of the pipeline.
  455. model (`str`): The model used by the pipeline.
  456. reason (`str`): The error message to display.
  457. """
  458. def __init__(self, task: str, model: str, reason: str):
  459. super().__init__(reason)
  460. self.task = task
  461. self.model = model
  462. class ArgumentHandler(ABC):
  463. """
  464. Base interface for handling arguments for each [`~pipelines.Pipeline`].
  465. """
  466. @abstractmethod
  467. def __call__(self, *args, **kwargs):
  468. raise NotImplementedError()
  469. class PipelineDataFormat:
  470. """
  471. Base class for all the pipeline supported data format both for reading and writing. Supported data formats
  472. currently includes:
  473. - JSON
  474. - CSV
  475. - stdin/stdout (pipe)
  476. `PipelineDataFormat` also includes some utilities to work with multi-columns like mapping from datasets columns to
  477. pipelines keyword arguments through the `dataset_kwarg_1=dataset_column_1` format.
  478. Args:
  479. output_path (`str`): Where to save the outgoing data.
  480. input_path (`str`): Where to look for the input data.
  481. column (`str`): The column to read.
  482. overwrite (`bool`, *optional*, defaults to `False`):
  483. Whether or not to overwrite the `output_path`.
  484. """
  485. SUPPORTED_FORMATS = ["json", "csv", "pipe"]
  486. def __init__(
  487. self,
  488. output_path: Optional[str],
  489. input_path: Optional[str],
  490. column: Optional[str],
  491. overwrite: bool = False,
  492. ):
  493. self.output_path = output_path
  494. self.input_path = input_path
  495. self.column = column.split(",") if column is not None else [""]
  496. self.is_multi_columns = len(self.column) > 1
  497. if self.is_multi_columns:
  498. self.column = [tuple(c.split("=")) if "=" in c else (c, c) for c in self.column]
  499. if output_path is not None and not overwrite:
  500. if exists(abspath(self.output_path)):
  501. raise OSError(f"{self.output_path} already exists on disk")
  502. if input_path is not None:
  503. if not exists(abspath(self.input_path)):
  504. raise OSError(f"{self.input_path} doesn't exist on disk")
  505. @abstractmethod
  506. def __iter__(self):
  507. raise NotImplementedError()
  508. @abstractmethod
  509. def save(self, data: Union[dict, list[dict]]):
  510. """
  511. Save the provided data object with the representation for the current [`~pipelines.PipelineDataFormat`].
  512. Args:
  513. data (`dict` or list of `dict`): The data to store.
  514. """
  515. raise NotImplementedError()
  516. def save_binary(self, data: Union[dict, list[dict]]) -> str:
  517. """
  518. Save the provided data object as a pickle-formatted binary data on the disk.
  519. Args:
  520. data (`dict` or list of `dict`): The data to store.
  521. Returns:
  522. `str`: Path where the data has been saved.
  523. """
  524. path, _ = os.path.splitext(self.output_path)
  525. binary_path = os.path.extsep.join((path, "pickle"))
  526. with open(binary_path, "wb+") as f_output:
  527. pickle.dump(data, f_output)
  528. return binary_path
  529. @staticmethod
  530. def from_str(
  531. format: str,
  532. output_path: Optional[str],
  533. input_path: Optional[str],
  534. column: Optional[str],
  535. overwrite=False,
  536. ) -> "PipelineDataFormat":
  537. """
  538. Creates an instance of the right subclass of [`~pipelines.PipelineDataFormat`] depending on `format`.
  539. Args:
  540. format (`str`):
  541. The format of the desired pipeline. Acceptable values are `"json"`, `"csv"` or `"pipe"`.
  542. output_path (`str`, *optional*):
  543. Where to save the outgoing data.
  544. input_path (`str`, *optional*):
  545. Where to look for the input data.
  546. column (`str`, *optional*):
  547. The column to read.
  548. overwrite (`bool`, *optional*, defaults to `False`):
  549. Whether or not to overwrite the `output_path`.
  550. Returns:
  551. [`~pipelines.PipelineDataFormat`]: The proper data format.
  552. """
  553. if format == "json":
  554. return JsonPipelineDataFormat(output_path, input_path, column, overwrite=overwrite)
  555. elif format == "csv":
  556. return CsvPipelineDataFormat(output_path, input_path, column, overwrite=overwrite)
  557. elif format == "pipe":
  558. return PipedPipelineDataFormat(output_path, input_path, column, overwrite=overwrite)
  559. else:
  560. raise KeyError(f"Unknown reader {format} (Available reader are json/csv/pipe)")
  561. class CsvPipelineDataFormat(PipelineDataFormat):
  562. """
  563. Support for pipelines using CSV data format.
  564. Args:
  565. output_path (`str`): Where to save the outgoing data.
  566. input_path (`str`): Where to look for the input data.
  567. column (`str`): The column to read.
  568. overwrite (`bool`, *optional*, defaults to `False`):
  569. Whether or not to overwrite the `output_path`.
  570. """
  571. def __init__(
  572. self,
  573. output_path: Optional[str],
  574. input_path: Optional[str],
  575. column: Optional[str],
  576. overwrite=False,
  577. ):
  578. super().__init__(output_path, input_path, column, overwrite=overwrite)
  579. def __iter__(self):
  580. with open(self.input_path, "r") as f:
  581. reader = csv.DictReader(f)
  582. for row in reader:
  583. if self.is_multi_columns:
  584. yield {k: row[c] for k, c in self.column}
  585. else:
  586. yield row[self.column[0]]
  587. def save(self, data: list[dict]):
  588. """
  589. Save the provided data object with the representation for the current [`~pipelines.PipelineDataFormat`].
  590. Args:
  591. data (`list[dict]`): The data to store.
  592. """
  593. with open(self.output_path, "w") as f:
  594. if len(data) > 0:
  595. writer = csv.DictWriter(f, list(data[0].keys()))
  596. writer.writeheader()
  597. writer.writerows(data)
  598. class JsonPipelineDataFormat(PipelineDataFormat):
  599. """
  600. Support for pipelines using JSON file format.
  601. Args:
  602. output_path (`str`): Where to save the outgoing data.
  603. input_path (`str`): Where to look for the input data.
  604. column (`str`): The column to read.
  605. overwrite (`bool`, *optional*, defaults to `False`):
  606. Whether or not to overwrite the `output_path`.
  607. """
  608. def __init__(
  609. self,
  610. output_path: Optional[str],
  611. input_path: Optional[str],
  612. column: Optional[str],
  613. overwrite=False,
  614. ):
  615. super().__init__(output_path, input_path, column, overwrite=overwrite)
  616. with open(input_path, "r") as f:
  617. self._entries = json.load(f)
  618. def __iter__(self):
  619. for entry in self._entries:
  620. if self.is_multi_columns:
  621. yield {k: entry[c] for k, c in self.column}
  622. else:
  623. yield entry[self.column[0]]
  624. def save(self, data: dict):
  625. """
  626. Save the provided data object in a json file.
  627. Args:
  628. data (`dict`): The data to store.
  629. """
  630. with open(self.output_path, "w") as f:
  631. json.dump(data, f)
  632. class PipedPipelineDataFormat(PipelineDataFormat):
  633. """
  634. Read data from piped input to the python process. For multi columns data, columns should separated by \t
  635. If columns are provided, then the output will be a dictionary with {column_x: value_x}
  636. Args:
  637. output_path (`str`): Where to save the outgoing data.
  638. input_path (`str`): Where to look for the input data.
  639. column (`str`): The column to read.
  640. overwrite (`bool`, *optional*, defaults to `False`):
  641. Whether or not to overwrite the `output_path`.
  642. """
  643. def __iter__(self):
  644. for line in sys.stdin:
  645. # Split for multi-columns
  646. if "\t" in line:
  647. line = line.split("\t")
  648. if self.column:
  649. # Dictionary to map arguments
  650. yield {kwargs: l for (kwargs, _), l in zip(self.column, line)}
  651. else:
  652. yield tuple(line)
  653. # No dictionary to map arguments
  654. else:
  655. yield line
  656. def save(self, data: dict):
  657. """
  658. Print the data.
  659. Args:
  660. data (`dict`): The data to store.
  661. """
  662. print(data)
  663. def save_binary(self, data: Union[dict, list[dict]]) -> str:
  664. if self.output_path is None:
  665. raise KeyError(
  666. "When using piped input on pipeline outputting large object requires an output file path. "
  667. "Please provide such output path through --output argument."
  668. )
  669. return super().save_binary(data)
  670. class _ScikitCompat(ABC):
  671. """
  672. Interface layer for the Scikit and Keras compatibility.
  673. """
  674. @abstractmethod
  675. def transform(self, X):
  676. raise NotImplementedError()
  677. @abstractmethod
  678. def predict(self, X):
  679. raise NotImplementedError()
  680. def build_pipeline_init_args(
  681. has_tokenizer: bool = False,
  682. has_feature_extractor: bool = False,
  683. has_image_processor: bool = False,
  684. has_processor: bool = False,
  685. supports_binary_output: bool = True,
  686. ) -> str:
  687. docstring = r"""
  688. Arguments:
  689. model ([`PreTrainedModel`] or [`TFPreTrainedModel`]):
  690. The model that will be used by the pipeline to make predictions. This needs to be a model inheriting from
  691. [`PreTrainedModel`] for PyTorch and [`TFPreTrainedModel`] for TensorFlow."""
  692. if has_tokenizer:
  693. docstring += r"""
  694. tokenizer ([`PreTrainedTokenizer`]):
  695. The tokenizer that will be used by the pipeline to encode data for the model. This object inherits from
  696. [`PreTrainedTokenizer`]."""
  697. if has_feature_extractor:
  698. docstring += r"""
  699. feature_extractor ([`SequenceFeatureExtractor`]):
  700. The feature extractor that will be used by the pipeline to encode data for the model. This object inherits from
  701. [`SequenceFeatureExtractor`]."""
  702. if has_image_processor:
  703. docstring += r"""
  704. image_processor ([`BaseImageProcessor`]):
  705. The image processor that will be used by the pipeline to encode data for the model. This object inherits from
  706. [`BaseImageProcessor`]."""
  707. if has_processor:
  708. docstring += r"""
  709. processor ([`ProcessorMixin`]):
  710. The processor that will be used by the pipeline to encode data for the model. This object inherits from
  711. [`ProcessorMixin`]. Processor is a composite object that might contain `tokenizer`, `feature_extractor`, and
  712. `image_processor`."""
  713. docstring += r"""
  714. modelcard (`str` or [`ModelCard`], *optional*):
  715. Model card attributed to the model for this pipeline.
  716. framework (`str`, *optional*):
  717. The framework to use, either `"pt"` for PyTorch or `"tf"` for TensorFlow. The specified framework must be
  718. installed.
  719. If no framework is specified, will default to the one currently installed. If no framework is specified and
  720. both frameworks are installed, will default to the framework of the `model`, or to PyTorch if no model is
  721. provided.
  722. task (`str`, defaults to `""`):
  723. A task-identifier for the pipeline.
  724. num_workers (`int`, *optional*, defaults to 8):
  725. When the pipeline will use *DataLoader* (when passing a dataset, on GPU for a Pytorch model), the number of
  726. workers to be used.
  727. batch_size (`int`, *optional*, defaults to 1):
  728. When the pipeline will use *DataLoader* (when passing a dataset, on GPU for a Pytorch model), the size of
  729. the batch to use, for inference this is not always beneficial, please read [Batching with
  730. pipelines](https://huggingface.co/transformers/main_classes/pipelines.html#pipeline-batching) .
  731. args_parser ([`~pipelines.ArgumentHandler`], *optional*):
  732. Reference to the object in charge of parsing supplied pipeline parameters.
  733. device (`int`, *optional*, defaults to -1):
  734. Device ordinal for CPU/GPU supports. Setting this to -1 will leverage CPU, a positive will run the model on
  735. the associated CUDA device id. You can pass native `torch.device` or a `str` too
  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. if supports_binary_output:
  740. docstring += r"""
  741. binary_output (`bool`, *optional*, defaults to `False`):
  742. Flag indicating if the output the pipeline should happen in a serialized format (i.e., pickle) or as
  743. the raw output data e.g. text."""
  744. return docstring
  745. PIPELINE_INIT_ARGS = build_pipeline_init_args(
  746. has_tokenizer=True,
  747. has_feature_extractor=True,
  748. has_image_processor=True,
  749. has_processor=True,
  750. supports_binary_output=True,
  751. )
  752. SUPPORTED_PEFT_TASKS = {
  753. "document-question-answering": ["PeftModelForQuestionAnswering"],
  754. "feature-extraction": ["PeftModelForFeatureExtraction", "PeftModel"],
  755. "question-answering": ["PeftModelForQuestionAnswering"],
  756. "summarization": ["PeftModelForSeq2SeqLM"],
  757. "table-question-answering": ["PeftModelForQuestionAnswering"],
  758. "text2text-generation": ["PeftModelForSeq2SeqLM"],
  759. "text-classification": ["PeftModelForSequenceClassification"],
  760. "sentiment-analysis": ["PeftModelForSequenceClassification"],
  761. "text-generation": ["PeftModelForCausalLM"],
  762. "token-classification": ["PeftModelForTokenClassification"],
  763. "ner": ["PeftModelForTokenClassification"],
  764. "translation": ["PeftModelForSeq2SeqLM"],
  765. "translation_xx_to_yy": ["PeftModelForSeq2SeqLM"],
  766. "zero-shot-classification": ["PeftModelForSequenceClassification"],
  767. }
  768. if is_torch_available():
  769. from transformers.pipelines.pt_utils import (
  770. PipelineChunkIterator,
  771. PipelineDataset,
  772. PipelineIterator,
  773. PipelinePackIterator,
  774. )
  775. @add_end_docstrings(
  776. build_pipeline_init_args(
  777. has_tokenizer=True, has_feature_extractor=True, has_image_processor=True, has_processor=True
  778. )
  779. )
  780. class Pipeline(_ScikitCompat, PushToHubMixin):
  781. """
  782. The Pipeline class is the class from which all pipelines inherit. Refer to this class for methods shared across
  783. different pipelines.
  784. Base class implementing pipelined operations. Pipeline workflow is defined as a sequence of the following
  785. operations:
  786. Input -> Tokenization -> Model Inference -> Post-Processing (task dependent) -> Output
  787. Pipeline supports running on CPU or GPU through the device argument (see below).
  788. Some pipeline, like for instance [`FeatureExtractionPipeline`] (`'feature-extraction'`) output large tensor object
  789. as nested-lists. In order to avoid dumping such large structure as textual data we provide the `binary_output`
  790. constructor argument. If set to `True`, the output will be stored in the pickle format.
  791. """
  792. # These flags should be overridden for downstream pipelines. They indicate which preprocessing classes are
  793. # used by each pipeline. The possible values are:
  794. # - True (the class is mandatory, raise an error if it's not present in the repo)
  795. # - None (the class is optional; it should be loaded if present in the repo but the pipeline can work without it)
  796. # - False (the class is never used by the pipeline and should not be loaded even if present)
  797. _load_processor = None
  798. _load_image_processor = None
  799. _load_feature_extractor = None
  800. _load_tokenizer = None
  801. # Pipelines that call `generate` have shared logic, e.g. preparing the generation config.
  802. _pipeline_calls_generate = False
  803. default_input_names = None
  804. def __init__(
  805. self,
  806. model: Union["PreTrainedModel", "TFPreTrainedModel"],
  807. tokenizer: Optional[PreTrainedTokenizer] = None,
  808. feature_extractor: Optional[PreTrainedFeatureExtractor] = None,
  809. image_processor: Optional[BaseImageProcessor] = None,
  810. processor: Optional[ProcessorMixin] = None,
  811. modelcard: Optional[ModelCard] = None,
  812. framework: Optional[str] = None,
  813. task: str = "",
  814. device: Optional[Union[int, "torch.device"]] = None,
  815. binary_output: bool = False,
  816. **kwargs,
  817. ):
  818. # We need to pop them for _sanitize_parameters call later
  819. _, _, _ = kwargs.pop("args_parser", None), kwargs.pop("torch_dtype", None), kwargs.pop("dtype", None)
  820. if framework is None:
  821. framework, model = infer_framework_load_model(model, config=model.config)
  822. if framework in ("tf", "jax"):
  823. logger.warning_once(
  824. "TensorFlow and JAX classes are deprecated and will be removed in Transformers v5. We "
  825. "recommend migrating to PyTorch classes or pinning your version of Transformers."
  826. )
  827. self.task = task
  828. self.model = model
  829. self.tokenizer = tokenizer
  830. self.feature_extractor = feature_extractor
  831. self.image_processor = image_processor
  832. self.processor = processor
  833. self.modelcard = modelcard
  834. self.framework = framework
  835. # `accelerate` device map
  836. hf_device_map = getattr(self.model, "hf_device_map", None)
  837. if hf_device_map is not None and device is not None:
  838. raise ValueError(
  839. "The model has been loaded with `accelerate` and therefore cannot be moved to a specific device. Please "
  840. "discard the `device` argument when creating your pipeline object."
  841. )
  842. if device is None:
  843. if hf_device_map is not None:
  844. # Take the first device used by `accelerate`.
  845. device = next(iter(hf_device_map.values()))
  846. else:
  847. device = 0
  848. if is_torch_available() and self.framework == "pt":
  849. if device == -1 and self.model.device is not None:
  850. device = self.model.device
  851. if isinstance(device, torch.device):
  852. if (device.type == "xpu" and not is_torch_xpu_available(check_device=True)) or (
  853. device.type == "hpu" and not is_torch_hpu_available()
  854. ):
  855. raise ValueError(f'{device} is not available, you should use device="cpu" instead')
  856. self.device = device
  857. elif isinstance(device, str):
  858. if ("xpu" in device and not is_torch_xpu_available(check_device=True)) or (
  859. "hpu" in device and not is_torch_hpu_available()
  860. ):
  861. raise ValueError(f'{device} is not available, you should use device="cpu" instead')
  862. self.device = torch.device(device)
  863. elif device < 0:
  864. self.device = torch.device("cpu")
  865. elif is_torch_mlu_available():
  866. self.device = torch.device(f"mlu:{device}")
  867. elif is_torch_musa_available():
  868. self.device = torch.device(f"musa:{device}")
  869. elif is_torch_cuda_available():
  870. self.device = torch.device(f"cuda:{device}")
  871. elif is_torch_npu_available():
  872. self.device = torch.device(f"npu:{device}")
  873. elif is_torch_hpu_available():
  874. self.device = torch.device(f"hpu:{device}")
  875. elif is_torch_xpu_available(check_device=True):
  876. self.device = torch.device(f"xpu:{device}")
  877. elif is_torch_mps_available():
  878. self.device = torch.device(f"mps:{device}")
  879. else:
  880. self.device = torch.device("cpu")
  881. else:
  882. self.device = device if device is not None else -1
  883. if is_torch_available() and torch.distributed.is_available() and torch.distributed.is_initialized():
  884. self.device = self.model.device
  885. logger.warning(f"Device set to use {self.device}")
  886. self.binary_output = binary_output
  887. # We shouldn't call `model.to()` for models loaded with accelerate as well as the case that model is already on device
  888. if (
  889. self.framework == "pt"
  890. and self.model.device != self.device
  891. and not (isinstance(self.device, int) and self.device < 0)
  892. and hf_device_map is None
  893. ):
  894. self.model.to(self.device)
  895. # If it's a generation pipeline and the model can generate:
  896. # 1 - create a local generation config. This is done to avoid side-effects on the model as we apply local
  897. # tweaks to the generation config.
  898. # 2 - load the assistant model if it is passed.
  899. if self._pipeline_calls_generate and self.model.can_generate():
  900. self.assistant_model, self.assistant_tokenizer = load_assistant_model(
  901. self.model, kwargs.pop("assistant_model", None), kwargs.pop("assistant_tokenizer", None)
  902. )
  903. self.prefix = self.model.config.prefix if hasattr(self.model.config, "prefix") else None
  904. # each pipeline with text generation capabilities should define its own default generation in a
  905. # `_default_generation_config` class attribute
  906. default_pipeline_generation_config = getattr(self, "_default_generation_config", GenerationConfig())
  907. if hasattr(self.model, "_prepare_generation_config"): # TF doesn't have `_prepare_generation_config`
  908. # Uses `generate`'s logic to enforce the following priority of arguments:
  909. # 1. user-defined config options in `**kwargs`
  910. # 2. model's generation config values
  911. # 3. pipeline's default generation config values
  912. # NOTE: _prepare_generation_config creates a deep copy of the generation config before updating it,
  913. # and returns all kwargs that were not used to update the generation config
  914. prepared_generation_config, kwargs = self.model._prepare_generation_config(
  915. generation_config=default_pipeline_generation_config, use_model_defaults=True, **kwargs
  916. )
  917. self.generation_config = prepared_generation_config
  918. # if the `max_new_tokens` is set to the pipeline default, but `max_length` is set to a non-default
  919. # value: let's honor `max_length`. E.g. we want Whisper's default `max_length=448` take precedence
  920. # over over the pipeline's length default.
  921. if (
  922. default_pipeline_generation_config.max_new_tokens is not None # there's a pipeline default
  923. and self.generation_config.max_new_tokens == default_pipeline_generation_config.max_new_tokens
  924. and self.generation_config.max_length is not None
  925. and self.generation_config.max_length != 20 # global default
  926. ):
  927. self.generation_config.max_new_tokens = None
  928. else:
  929. # TODO (joao): no PT model should reach this line. However, some audio models with complex
  930. # inheritance patterns do. Streamline those models such that this line is no longer needed.
  931. # In those models, the default generation config is not (yet) used.
  932. self.generation_config = copy.deepcopy(self.model.generation_config)
  933. # Update the generation config with task specific params if they exist.
  934. # NOTE: 1. `prefix` is pipeline-specific and doesn't exist in the generation config.
  935. # 2. `task_specific_params` is a legacy feature and should be removed in a future version.
  936. task_specific_params = self.model.config.task_specific_params
  937. if task_specific_params is not None and task in task_specific_params:
  938. this_task_params = task_specific_params.get(task)
  939. if "prefix" in this_task_params:
  940. self.prefix = this_task_params.pop("prefix")
  941. self.generation_config.update(**this_task_params)
  942. # If the tokenizer has a pad token but the model doesn't, set it so that `generate` is aware of it.
  943. if (
  944. self.tokenizer is not None
  945. and self.tokenizer.pad_token_id is not None
  946. and self.generation_config.pad_token_id is None
  947. ):
  948. self.generation_config.pad_token_id = self.tokenizer.pad_token_id
  949. self.call_count = 0
  950. self._batch_size = kwargs.pop("batch_size", None)
  951. self._num_workers = kwargs.pop("num_workers", None)
  952. self._preprocess_params, self._forward_params, self._postprocess_params = self._sanitize_parameters(**kwargs)
  953. # In processor only mode, we can get the modality processors from the processor
  954. if self.processor is not None and all(
  955. [self.tokenizer is None, self.feature_extractor is None, self.image_processor is None]
  956. ):
  957. self.tokenizer = getattr(self.processor, "tokenizer", None)
  958. self.feature_extractor = getattr(self.processor, "feature_extractor", None)
  959. self.image_processor = getattr(self.processor, "image_processor", None)
  960. if self.image_processor is None and self.feature_extractor is not None:
  961. if isinstance(self.feature_extractor, BaseImageProcessor):
  962. # Backward compatible change, if users called
  963. # ImageSegmentationPipeline(.., feature_extractor=MyFeatureExtractor())
  964. # then we should keep working
  965. self.image_processor = self.feature_extractor
  966. def save_pretrained(
  967. self,
  968. save_directory: Union[str, os.PathLike],
  969. safe_serialization: bool = True,
  970. **kwargs: Any,
  971. ):
  972. """
  973. Save the pipeline's model and tokenizer.
  974. Args:
  975. save_directory (`str` or `os.PathLike`):
  976. A path to the directory where to saved. It will be created if it doesn't exist.
  977. safe_serialization (`str`):
  978. Whether to save the model using `safetensors` or the traditional way for PyTorch or Tensorflow.
  979. kwargs (`dict[str, Any]`, *optional*):
  980. Additional key word arguments passed along to the [`~utils.PushToHubMixin.push_to_hub`] method.
  981. """
  982. use_auth_token = kwargs.pop("use_auth_token", None)
  983. if use_auth_token is not None:
  984. warnings.warn(
  985. "The `use_auth_token` argument is deprecated and will be removed in v5 of Transformers. Please use `token` instead.",
  986. FutureWarning,
  987. )
  988. if kwargs.get("token") is not None:
  989. raise ValueError(
  990. "`token` and `use_auth_token` are both specified. Please set only the argument `token`."
  991. )
  992. kwargs["token"] = use_auth_token
  993. if os.path.isfile(save_directory):
  994. logger.error(f"Provided path ({save_directory}) should be a directory, not a file")
  995. return
  996. os.makedirs(save_directory, exist_ok=True)
  997. if hasattr(self, "_registered_impl"):
  998. # Add info to the config
  999. pipeline_info = self._registered_impl.copy()
  1000. custom_pipelines = {}
  1001. for task, info in pipeline_info.items():
  1002. if info["impl"] != self.__class__:
  1003. continue
  1004. info = info.copy()
  1005. module_name = info["impl"].__module__
  1006. last_module = module_name.split(".")[-1]
  1007. # Change classes into their names/full names
  1008. info["impl"] = f"{last_module}.{info['impl'].__name__}"
  1009. info["pt"] = tuple(c.__name__ for c in info["pt"])
  1010. info["tf"] = tuple(c.__name__ for c in info["tf"])
  1011. custom_pipelines[task] = info
  1012. self.model.config.custom_pipelines = custom_pipelines
  1013. # Save the pipeline custom code
  1014. custom_object_save(self, save_directory)
  1015. kwargs["safe_serialization"] = safe_serialization
  1016. self.model.save_pretrained(save_directory, **kwargs)
  1017. if self.tokenizer is not None:
  1018. self.tokenizer.save_pretrained(save_directory, **kwargs)
  1019. if self.feature_extractor is not None:
  1020. self.feature_extractor.save_pretrained(save_directory, **kwargs)
  1021. if self.image_processor is not None:
  1022. self.image_processor.save_pretrained(save_directory, **kwargs)
  1023. if self.modelcard is not None:
  1024. self.modelcard.save_pretrained(save_directory)
  1025. def transform(self, X):
  1026. """
  1027. Scikit / Keras interface to transformers' pipelines. This method will forward to __call__().
  1028. """
  1029. return self(X)
  1030. def predict(self, X):
  1031. """
  1032. Scikit / Keras interface to transformers' pipelines. This method will forward to __call__().
  1033. """
  1034. return self(X)
  1035. @property
  1036. def dtype(self) -> Optional["torch.dtype"]:
  1037. """
  1038. Dtype of the model (if it's Pytorch model), `None` otherwise.
  1039. """
  1040. return getattr(self.model, "dtype", None)
  1041. @property
  1042. def torch_dtype(self) -> Optional["torch.dtype"]:
  1043. """
  1044. Torch dtype of the model (if it's Pytorch model), `None` otherwise.
  1045. """
  1046. logger.warning_once("`torch_dtype` attribute is deprecated. Use `dtype` instead!")
  1047. return getattr(self.model, "dtype", None)
  1048. @contextmanager
  1049. def device_placement(self):
  1050. """
  1051. Context Manager allowing tensor allocation on the user-specified device in framework agnostic way.
  1052. Returns:
  1053. Context manager
  1054. Examples:
  1055. ```python
  1056. # Explicitly ask for tensor allocation on CUDA device :0
  1057. pipe = pipeline(..., device=0)
  1058. with pipe.device_placement():
  1059. # Every framework specific tensor allocation will be done on the request device
  1060. output = pipe(...)
  1061. ```"""
  1062. if self.framework == "tf":
  1063. with tf.device("/CPU:0" if self.device == -1 else f"/device:GPU:{self.device}"):
  1064. yield
  1065. else:
  1066. if self.device.type == "cuda":
  1067. with torch.cuda.device(self.device):
  1068. yield
  1069. elif self.device.type == "mlu":
  1070. with torch.mlu.device(self.device):
  1071. yield
  1072. elif self.device.type == "musa":
  1073. with torch.musa.device(self.device):
  1074. yield
  1075. elif self.device.type == "xpu":
  1076. with torch.xpu.device(self.device):
  1077. yield
  1078. else:
  1079. yield
  1080. def ensure_tensor_on_device(self, **inputs):
  1081. """
  1082. Ensure PyTorch tensors are on the specified device.
  1083. Args:
  1084. inputs (keyword arguments that should be `torch.Tensor`, the rest is ignored):
  1085. The tensors to place on `self.device`.
  1086. Recursive on lists **only**.
  1087. Return:
  1088. `dict[str, torch.Tensor]`: The same as `inputs` but on the proper device.
  1089. """
  1090. return self._ensure_tensor_on_device(inputs, self.device)
  1091. def _ensure_tensor_on_device(self, inputs, device):
  1092. if isinstance(inputs, ModelOutput):
  1093. return ModelOutput(
  1094. {name: self._ensure_tensor_on_device(tensor, device) for name, tensor in inputs.items()}
  1095. )
  1096. elif isinstance(inputs, dict):
  1097. return {name: self._ensure_tensor_on_device(tensor, device) for name, tensor in inputs.items()}
  1098. elif isinstance(inputs, UserDict):
  1099. return UserDict({name: self._ensure_tensor_on_device(tensor, device) for name, tensor in inputs.items()})
  1100. elif isinstance(inputs, list):
  1101. return [self._ensure_tensor_on_device(item, device) for item in inputs]
  1102. elif isinstance(inputs, tuple):
  1103. return tuple(self._ensure_tensor_on_device(item, device) for item in inputs)
  1104. elif isinstance(inputs, torch.Tensor):
  1105. return inputs.to(device)
  1106. else:
  1107. return inputs
  1108. def check_model_type(self, supported_models: Union[list[str], dict]):
  1109. """
  1110. Check if the model class is in supported by the pipeline.
  1111. Args:
  1112. supported_models (`list[str]` or `dict`):
  1113. The list of models supported by the pipeline, or a dictionary with model class values.
  1114. """
  1115. if not isinstance(supported_models, list): # Create from a model mapping
  1116. supported_models_names = []
  1117. if self.task in SUPPORTED_PEFT_TASKS:
  1118. supported_models_names.extend(SUPPORTED_PEFT_TASKS[self.task])
  1119. for model_name in supported_models.values():
  1120. # Mapping can now contain tuples of models for the same configuration.
  1121. if isinstance(model_name, tuple):
  1122. supported_models_names.extend(list(model_name))
  1123. else:
  1124. supported_models_names.append(model_name)
  1125. if hasattr(supported_models, "_model_mapping"):
  1126. for model in supported_models._model_mapping._extra_content.values():
  1127. if isinstance(model_name, tuple):
  1128. supported_models_names.extend([m.__name__ for m in model])
  1129. else:
  1130. supported_models_names.append(model.__name__)
  1131. supported_models = supported_models_names
  1132. if self.model.__class__.__name__ not in supported_models:
  1133. logger.error(
  1134. f"The model '{self.model.__class__.__name__}' is not supported for {self.task}. Supported models are"
  1135. f" {supported_models}."
  1136. )
  1137. @abstractmethod
  1138. def _sanitize_parameters(self, **pipeline_parameters):
  1139. """
  1140. _sanitize_parameters will be called with any excessive named arguments from either `__init__` or `__call__`
  1141. methods. It should return 3 dictionaries of the resolved parameters used by the various `preprocess`,
  1142. `forward` and `postprocess` methods. Do not fill dictionaries if the caller didn't specify a kwargs. This
  1143. lets you keep defaults in function signatures, which is more "natural".
  1144. It is not meant to be called directly, it will be automatically called and the final parameters resolved by
  1145. `__init__` and `__call__`
  1146. """
  1147. raise NotImplementedError("_sanitize_parameters not implemented")
  1148. @abstractmethod
  1149. def preprocess(self, input_: Any, **preprocess_parameters: dict) -> dict[str, GenericTensor]:
  1150. """
  1151. Preprocess will take the `input_` of a specific pipeline and return a dictionary of everything necessary for
  1152. `_forward` to run properly. It should contain at least one tensor, but might have arbitrary other items.
  1153. """
  1154. raise NotImplementedError("preprocess not implemented")
  1155. @abstractmethod
  1156. def _forward(self, input_tensors: dict[str, GenericTensor], **forward_parameters: dict) -> ModelOutput:
  1157. """
  1158. _forward will receive the prepared dictionary from `preprocess` and run it on the model. This method might
  1159. involve the GPU or the CPU and should be agnostic to it. Isolating this function is the reason for `preprocess`
  1160. and `postprocess` to exist, so that the hot path, this method generally can run as fast as possible.
  1161. It is not meant to be called directly, `forward` is preferred. It is basically the same but contains additional
  1162. code surrounding `_forward` making sure tensors and models are on the same device, disabling the training part
  1163. of the code (leading to faster inference).
  1164. """
  1165. raise NotImplementedError("_forward not implemented")
  1166. @abstractmethod
  1167. def postprocess(self, model_outputs: ModelOutput, **postprocess_parameters: dict) -> Any:
  1168. """
  1169. Postprocess will receive the raw outputs of the `_forward` method, generally tensors, and reformat them into
  1170. something more friendly. Generally it will output a list or a dict or results (containing just strings and
  1171. numbers).
  1172. """
  1173. raise NotImplementedError("postprocess not implemented")
  1174. def get_inference_context(self):
  1175. return torch.no_grad
  1176. def forward(self, model_inputs, **forward_params):
  1177. with self.device_placement():
  1178. if self.framework == "tf":
  1179. model_inputs["training"] = False
  1180. model_outputs = self._forward(model_inputs, **forward_params)
  1181. elif self.framework == "pt":
  1182. inference_context = self.get_inference_context()
  1183. with inference_context():
  1184. model_inputs = self._ensure_tensor_on_device(model_inputs, device=self.device)
  1185. model_outputs = self._forward(model_inputs, **forward_params)
  1186. model_outputs = self._ensure_tensor_on_device(model_outputs, device=torch.device("cpu"))
  1187. else:
  1188. raise ValueError(f"Framework {self.framework} is not supported")
  1189. return model_outputs
  1190. def get_iterator(
  1191. self, inputs, num_workers: int, batch_size: int, preprocess_params, forward_params, postprocess_params
  1192. ):
  1193. if isinstance(inputs, collections.abc.Sized):
  1194. dataset = PipelineDataset(inputs, self.preprocess, preprocess_params)
  1195. else:
  1196. if num_workers > 1:
  1197. logger.warning(
  1198. "For iterable dataset using num_workers>1 is likely to result"
  1199. " in errors since everything is iterable, setting `num_workers=1`"
  1200. " to guarantee correctness."
  1201. )
  1202. num_workers = 1
  1203. dataset = PipelineIterator(inputs, self.preprocess, preprocess_params)
  1204. if "TOKENIZERS_PARALLELISM" not in os.environ:
  1205. logger.info("Disabling tokenizer parallelism, we're using DataLoader multithreading already")
  1206. os.environ["TOKENIZERS_PARALLELISM"] = "false"
  1207. # TODO hack by collating feature_extractor and image_processor
  1208. feature_extractor = self.feature_extractor if self.feature_extractor is not None else self.image_processor
  1209. collate_fn = no_collate_fn if batch_size == 1 else pad_collate_fn(self.tokenizer, feature_extractor)
  1210. dataloader = DataLoader(dataset, num_workers=num_workers, batch_size=batch_size, collate_fn=collate_fn)
  1211. model_iterator = PipelineIterator(dataloader, self.forward, forward_params, loader_batch_size=batch_size)
  1212. final_iterator = PipelineIterator(model_iterator, self.postprocess, postprocess_params)
  1213. return final_iterator
  1214. def __call__(self, inputs, *args, num_workers=None, batch_size=None, **kwargs):
  1215. if args:
  1216. logger.warning(f"Ignoring args : {args}")
  1217. if num_workers is None:
  1218. if self._num_workers is None:
  1219. num_workers = 0
  1220. else:
  1221. num_workers = self._num_workers
  1222. if batch_size is None:
  1223. if self._batch_size is None:
  1224. batch_size = 1
  1225. else:
  1226. batch_size = self._batch_size
  1227. preprocess_params, forward_params, postprocess_params = self._sanitize_parameters(**kwargs)
  1228. # Fuse __init__ params and __call__ params without modifying the __init__ ones.
  1229. preprocess_params = {**self._preprocess_params, **preprocess_params}
  1230. forward_params = {**self._forward_params, **forward_params}
  1231. postprocess_params = {**self._postprocess_params, **postprocess_params}
  1232. self.call_count += 1
  1233. if self.call_count > 10 and self.framework == "pt" and self.device.type == "cuda":
  1234. logger.warning_once(
  1235. "You seem to be using the pipelines sequentially on GPU. In order to maximize efficiency please use a"
  1236. " dataset",
  1237. )
  1238. is_dataset = Dataset is not None and isinstance(inputs, Dataset)
  1239. is_generator = isinstance(inputs, types.GeneratorType)
  1240. is_list = isinstance(inputs, list)
  1241. is_iterable = is_dataset or is_generator or is_list
  1242. # TODO make the get_iterator work also for `tf` (and `flax`).
  1243. can_use_iterator = self.framework == "pt" and (is_dataset or is_generator or is_list)
  1244. if is_list:
  1245. if can_use_iterator:
  1246. final_iterator = self.get_iterator(
  1247. inputs, num_workers, batch_size, preprocess_params, forward_params, postprocess_params
  1248. )
  1249. outputs = list(final_iterator)
  1250. return outputs
  1251. else:
  1252. return self.run_multi(inputs, preprocess_params, forward_params, postprocess_params)
  1253. elif can_use_iterator:
  1254. return self.get_iterator(
  1255. inputs, num_workers, batch_size, preprocess_params, forward_params, postprocess_params
  1256. )
  1257. elif is_iterable:
  1258. return self.iterate(inputs, preprocess_params, forward_params, postprocess_params)
  1259. elif self.framework == "pt" and isinstance(self, ChunkPipeline):
  1260. return next(
  1261. iter(
  1262. self.get_iterator(
  1263. [inputs], num_workers, batch_size, preprocess_params, forward_params, postprocess_params
  1264. )
  1265. )
  1266. )
  1267. else:
  1268. return self.run_single(inputs, preprocess_params, forward_params, postprocess_params)
  1269. def run_multi(self, inputs, preprocess_params, forward_params, postprocess_params):
  1270. return [self.run_single(item, preprocess_params, forward_params, postprocess_params) for item in inputs]
  1271. def run_single(self, inputs, preprocess_params, forward_params, postprocess_params):
  1272. model_inputs = self.preprocess(inputs, **preprocess_params)
  1273. model_outputs = self.forward(model_inputs, **forward_params)
  1274. outputs = self.postprocess(model_outputs, **postprocess_params)
  1275. return outputs
  1276. def iterate(self, inputs, preprocess_params, forward_params, postprocess_params):
  1277. # This function should become `get_iterator` again, this is a temporary
  1278. # easy solution.
  1279. for input_ in inputs:
  1280. yield self.run_single(input_, preprocess_params, forward_params, postprocess_params)
  1281. Pipeline.push_to_hub = copy_func(Pipeline.push_to_hub)
  1282. if Pipeline.push_to_hub.__doc__ is not None:
  1283. Pipeline.push_to_hub.__doc__ = Pipeline.push_to_hub.__doc__.format(
  1284. object="pipe", object_class="pipeline", object_files="pipeline file"
  1285. ).replace(".from_pretrained", "")
  1286. class ChunkPipeline(Pipeline):
  1287. def run_single(self, inputs, preprocess_params, forward_params, postprocess_params):
  1288. all_outputs = []
  1289. for model_inputs in self.preprocess(inputs, **preprocess_params):
  1290. model_outputs = self.forward(model_inputs, **forward_params)
  1291. all_outputs.append(model_outputs)
  1292. outputs = self.postprocess(all_outputs, **postprocess_params)
  1293. return outputs
  1294. def get_iterator(
  1295. self, inputs, num_workers: int, batch_size: int, preprocess_params, forward_params, postprocess_params
  1296. ):
  1297. if "TOKENIZERS_PARALLELISM" not in os.environ:
  1298. logger.info("Disabling tokenizer parallelism, we're using DataLoader multithreading already")
  1299. os.environ["TOKENIZERS_PARALLELISM"] = "false"
  1300. if num_workers > 1:
  1301. logger.warning(
  1302. "For ChunkPipeline using num_workers>0 is likely to result in errors since everything is iterable,"
  1303. " setting `num_workers=1` to guarantee correctness."
  1304. )
  1305. num_workers = 1
  1306. dataset = PipelineChunkIterator(inputs, self.preprocess, preprocess_params)
  1307. # TODO hack by collating feature_extractor and image_processor
  1308. feature_extractor = self.feature_extractor if self.feature_extractor is not None else self.image_processor
  1309. collate_fn = no_collate_fn if batch_size == 1 else pad_collate_fn(self.tokenizer, feature_extractor)
  1310. dataloader = DataLoader(dataset, num_workers=num_workers, batch_size=batch_size, collate_fn=collate_fn)
  1311. model_iterator = PipelinePackIterator(dataloader, self.forward, forward_params, loader_batch_size=batch_size)
  1312. final_iterator = PipelineIterator(model_iterator, self.postprocess, postprocess_params)
  1313. return final_iterator
  1314. class PipelineRegistry:
  1315. def __init__(self, supported_tasks: dict[str, Any], task_aliases: dict[str, str]) -> None:
  1316. self.supported_tasks = supported_tasks
  1317. self.task_aliases = task_aliases
  1318. def get_supported_tasks(self) -> list[str]:
  1319. supported_task = list(self.supported_tasks.keys()) + list(self.task_aliases.keys())
  1320. supported_task.sort()
  1321. return supported_task
  1322. def check_task(self, task: str) -> tuple[str, dict, Any]:
  1323. if task in self.task_aliases:
  1324. task = self.task_aliases[task]
  1325. if task in self.supported_tasks:
  1326. targeted_task = self.supported_tasks[task]
  1327. return task, targeted_task, None
  1328. if task.startswith("translation"):
  1329. tokens = task.split("_")
  1330. if len(tokens) == 4 and tokens[0] == "translation" and tokens[2] == "to":
  1331. targeted_task = self.supported_tasks["translation"]
  1332. task = "translation"
  1333. return task, targeted_task, (tokens[1], tokens[3])
  1334. raise KeyError(f"Invalid translation task {task}, use 'translation_XX_to_YY' format")
  1335. raise KeyError(
  1336. f"Unknown task {task}, available tasks are {self.get_supported_tasks() + ['translation_XX_to_YY']}"
  1337. )
  1338. @deprecate_kwarg(old_name="tf_model", version="5.0.0")
  1339. def register_pipeline(
  1340. self,
  1341. task: str,
  1342. pipeline_class: type,
  1343. pt_model: Optional[Union[type, tuple[type]]] = None,
  1344. tf_model: Optional[Union[type, tuple[type]]] = None,
  1345. default: Optional[dict] = None,
  1346. type: Optional[str] = None,
  1347. ) -> None:
  1348. if task in self.supported_tasks:
  1349. logger.warning(f"{task} is already registered. Overwriting pipeline for task {task}...")
  1350. if pt_model is None:
  1351. pt_model = ()
  1352. elif not isinstance(pt_model, tuple):
  1353. pt_model = (pt_model,)
  1354. if tf_model is None:
  1355. tf_model = ()
  1356. elif not isinstance(tf_model, tuple):
  1357. tf_model = (tf_model,)
  1358. task_impl = {"impl": pipeline_class, "pt": pt_model, "tf": tf_model}
  1359. if default is not None:
  1360. if "model" not in default and ("pt" in default or "tf" in default):
  1361. default = {"model": default}
  1362. task_impl["default"] = default
  1363. if type is not None:
  1364. task_impl["type"] = type
  1365. self.supported_tasks[task] = task_impl
  1366. pipeline_class._registered_impl = {task: task_impl}
  1367. def to_dict(self):
  1368. return self.supported_tasks