The pipelines are a great and easy way to use models for inference. These pipelines are objects that abstract most of the complex code from the library, offering a simple API dedicated to several tasks, including Named Entity Recognition, Masked Language Modeling, Sentiment Analysis, Feature Extraction and Question Answering. See the task summary for examples of use.
There are two categories of pipeline abstractions to be aware about:
The pipeline abstraction is a wrapper around all the other available pipelines. It is instantiated as any other pipeline but can provide additional quality of life.
Simple call on one item:
>>> pipe = pipeline("text-classification") >>> pipe("This restaurant is awesome") [{'label': 'POSITIVE', 'score': 0.9998743534088135}]
If you want to use a specific model from the hub you can ignore the task if the model on the hub already defines it:
>>> pipe = pipeline(model="FacebookAI/roberta-large-mnli") >>> pipe("This restaurant is awesome") [{'label': 'NEUTRAL', 'score': 0.7313136458396912}]
To call a pipeline on many items, you can call it with a list.
>>> pipe = pipeline("text-classification") >>> pipe(["This restaurant is awesome", "This restaurant is awful"]) [{'label': 'POSITIVE', 'score': 0.9998743534088135}, {'label': 'NEGATIVE', 'score': 0.9996669292449951}]
To iterate over full datasets it is recommended to use a dataset
directly. This means you don’t need to allocate the whole dataset at once, nor do you need to do batching yourself. This should work just as fast as custom loops on GPU. If it doesn’t don’t hesitate to create an issue.
import datasets from transformers import pipeline from transformers.pipelines.pt_utils import KeyDataset from tqdm.auto import tqdm pipe = pipeline("automatic-speech-recognition", model="facebook/wav2vec2-base-960h", device=0) dataset = datasets.load_dataset("superb", name="asr", split="test") for out in tqdm(pipe(KeyDataset(dataset, "file"))): print(out)
For ease of use, a generator is also possible:
from transformers import pipeline pipe = pipeline("text-classification") def data(): while True: yield "This is a test" for out in pipe(data()): print(out)transformers.pipeline < source >
( task: typing.Optional[str] = None model: typing.Union[str, ForwardRef('PreTrainedModel'), ForwardRef('TFPreTrainedModel'), NoneType] = None config: typing.Union[str, transformers.configuration_utils.PretrainedConfig, NoneType] = None tokenizer: typing.Union[str, transformers.tokenization_utils.PreTrainedTokenizer, ForwardRef('PreTrainedTokenizerFast'), NoneType] = None feature_extractor: typing.Union[str, ForwardRef('SequenceFeatureExtractor'), NoneType] = None image_processor: typing.Union[str, transformers.image_processing_utils.BaseImageProcessor, NoneType] = None processor: typing.Union[str, transformers.processing_utils.ProcessorMixin, NoneType] = None framework: typing.Optional[str] = None revision: typing.Optional[str] = None use_fast: bool = True token: typing.Union[bool, str, NoneType] = None device: typing.Union[int, str, ForwardRef('torch.device'), NoneType] = None device_map = None torch_dtype = None trust_remote_code: typing.Optional[bool] = None model_kwargs: typing.Optional[typing.Dict[str, typing.Any]] = None pipeline_class: typing.Optional[typing.Any] = None **kwargs ) → Pipeline
Parameters
str
) — The task defining which pipeline will be returned. Currently accepted tasks are:
"audio-classification"
: will return a AudioClassificationPipeline."automatic-speech-recognition"
: will return a AutomaticSpeechRecognitionPipeline."depth-estimation"
: will return a DepthEstimationPipeline."document-question-answering"
: will return a DocumentQuestionAnsweringPipeline."feature-extraction"
: will return a FeatureExtractionPipeline."fill-mask"
: will return a FillMaskPipeline:."image-classification"
: will return a ImageClassificationPipeline."image-feature-extraction"
: will return an ImageFeatureExtractionPipeline."image-segmentation"
: will return a ImageSegmentationPipeline."image-text-to-text"
: will return a ImageTextToTextPipeline."image-to-image"
: will return a ImageToImagePipeline."image-to-text"
: will return a ImageToTextPipeline."mask-generation"
: will return a MaskGenerationPipeline."object-detection"
: will return a ObjectDetectionPipeline."question-answering"
: will return a QuestionAnsweringPipeline."summarization"
: will return a SummarizationPipeline."table-question-answering"
: will return a TableQuestionAnsweringPipeline."text2text-generation"
: will return a Text2TextGenerationPipeline."text-classification"
(alias "sentiment-analysis"
available): will return a TextClassificationPipeline."text-generation"
: will return a TextGenerationPipeline:."text-to-audio"
(alias "text-to-speech"
available): will return a TextToAudioPipeline:."token-classification"
(alias "ner"
available): will return a TokenClassificationPipeline."translation"
: will return a TranslationPipeline."translation_xx_to_yy"
: will return a TranslationPipeline."video-classification"
: will return a VideoClassificationPipeline."visual-question-answering"
: will return a VisualQuestionAnsweringPipeline."zero-shot-classification"
: will return a ZeroShotClassificationPipeline."zero-shot-image-classification"
: will return a ZeroShotImageClassificationPipeline."zero-shot-audio-classification"
: will return a ZeroShotAudioClassificationPipeline."zero-shot-object-detection"
: will return a ZeroShotObjectDetectionPipeline.str
or PreTrainedModel or TFPreTrainedModel, optional) — The model that will be used by the pipeline to make predictions. This can be a model identifier or an actual instance of a pretrained model inheriting from PreTrainedModel (for PyTorch) or TFPreTrainedModel (for TensorFlow).
If not provided, the default for the task
will be loaded.
str
or PretrainedConfig, optional) — The configuration that will be used by the pipeline to instantiate the model. This can be a model identifier or an actual pretrained model configuration inheriting from PretrainedConfig.
If not provided, the default configuration file for the requested model will be used. That means that if model
is given, its default configuration will be used. However, if model
is not supplied, this task
’s default model’s config is used instead.
str
or PreTrainedTokenizer, optional) — The tokenizer that will be used by the pipeline to encode data for the model. This can be a model identifier or an actual pretrained tokenizer inheriting from PreTrainedTokenizer.
If not provided, the default tokenizer for the given model
will be loaded (if it is a string). If model
is not specified or not a string, then the default tokenizer for config
is loaded (if it is a string). However, if config
is also not given or not a string, then the default tokenizer for the given task
will be loaded.
str
or PreTrainedFeatureExtractor
, optional) — The feature extractor that will be used by the pipeline to encode data for the model. This can be a model identifier or an actual pretrained feature extractor inheriting from PreTrainedFeatureExtractor
.
Feature extractors are used for non-NLP models, such as Speech or Vision models as well as multi-modal models. Multi-modal models will also require a tokenizer to be passed.
If not provided, the default feature extractor for the given model
will be loaded (if it is a string). If model
is not specified or not a string, then the default feature extractor for config
is loaded (if it is a string). However, if config
is also not given or not a string, then the default feature extractor for the given task
will be loaded.
str
or BaseImageProcessor, optional) — The image processor that will be used by the pipeline to preprocess images for the model. This can be a model identifier or an actual image processor inheriting from BaseImageProcessor.
Image processors are used for Vision models and multi-modal models that require image inputs. Multi-modal models will also require a tokenizer to be passed.
If not provided, the default image processor for the given model
will be loaded (if it is a string). If model
is not specified or not a string, then the default image processor for config
is loaded (if it is a string).
str
or ProcessorMixin, optional) — The processor that will be used by the pipeline to preprocess data for the model. This can be a model identifier or an actual processor inheriting from ProcessorMixin.
Processors are used for multi-modal models that require multi-modal inputs, for example, a model that requires both text and image inputs.
If not provided, the default processor for the given model
will be loaded (if it is a string). If model
is not specified or not a string, then the default processor for config
is loaded (if it is a string).
str
, optional) — The framework to use, either "pt"
for PyTorch or "tf"
for TensorFlow. The specified framework must be installed.
If no framework is specified, will default to the one currently installed. If no framework is specified and both frameworks are installed, will default to the framework of the model
, or to PyTorch if no model is provided.
str
, optional, defaults to "main"
) — When passing a task name or a string model identifier: The specific model version to use. It can be a branch name, a tag name, or a commit id, since we use a git-based system for storing models and other artifacts on huggingface.co, so revision
can be any identifier allowed by git. bool
, optional, defaults to True
) — Whether or not to use a Fast tokenizer if possible (a PreTrainedTokenizerFast). str
or bool, optional) — The token to use as HTTP bearer authorization for remote files. If True
, will use the token generated when running huggingface-cli login
(stored in ~/.huggingface
). int
or str
or torch.device
) — Defines the device (e.g., "cpu"
, "cuda:1"
, "mps"
, or a GPU ordinal rank like 1
) on which this pipeline will be allocated. str
or Dict[str, Union[int, str, torch.device]
, optional) — Sent directly as model_kwargs
(just a simpler shortcut). When accelerate
library is present, set device_map="auto"
to compute the most optimized device_map
automatically (see here for more information).
Do not use device_map
AND device
at the same time as they will conflict
str
or torch.dtype
, optional) — Sent directly as model_kwargs
(just a simpler shortcut) to use the available precision for this model (torch.float16
, torch.bfloat16
, … or "auto"
). bool
, optional, defaults to False
) — Whether or not to allow for custom code defined on the Hub in their own modeling, configuration, tokenization or even pipeline files. This option should only be set to True
for repositories you trust and in which you have read the code, as it will execute code present on the Hub on your local machine. Dict[str, Any]
, optional) — Additional dictionary of keyword arguments passed along to the model’s from_pretrained(..., **model_kwargs)
function. Dict[str, Any]
, optional) — Additional keyword arguments passed along to the specific pipeline init (see the documentation for the corresponding pipeline class for possible values). A suitable pipeline for the task.
Utility factory method to build a Pipeline.
A pipeline consists of:
While there are such optional arguments as `tokenizer`, `feature_extractor`, `image_processor`, and `processor`, they shouldn't be specified all at once. If these components are not provided, `pipeline` will try to load required ones automatically. In case you want to provide these components explicitly, please refer to a specific pipeline in order to get more details regarding what components are required.
Examples:
>>> from transformers import pipeline, AutoModelForTokenClassification, AutoTokenizer >>> >>> analyzer = pipeline("sentiment-analysis") >>> >>> oracle = pipeline( ... "question-answering", model="distilbert/distilbert-base-cased-distilled-squad", tokenizer="google-bert/bert-base-cased" ... ) >>> >>> model = AutoModelForTokenClassification.from_pretrained("dbmdz/bert-large-cased-finetuned-conll03-english") >>> tokenizer = AutoTokenizer.from_pretrained("google-bert/bert-base-cased") >>> recognizer = pipeline("ner", model=model, tokenizer=tokenizer)Pipeline batching
All pipelines can use batching. This will work whenever the pipeline uses its streaming ability (so when passing lists or Dataset
or generator
).
from transformers import pipeline from transformers.pipelines.pt_utils import KeyDataset import datasets dataset = datasets.load_dataset("imdb", name="plain_text", split="unsupervised") pipe = pipeline("text-classification", device=0) for out in pipe(KeyDataset(dataset, "text"), batch_size=8, truncation="only_first"): print(out)
However, this is not automatically a win for performance. It can be either a 10x speedup or 5x slowdown depending on hardware, data and the actual model being used.
Example where it’s mostly a speedup:
from transformers import pipeline from torch.utils.data import Dataset from tqdm.auto import tqdm pipe = pipeline("text-classification", device=0) class MyDataset(Dataset): def __len__(self): return 5000 def __getitem__(self, i): return "This is a test" dataset = MyDataset() for batch_size in [1, 8, 64, 256]: print("-" * 30) print(f"Streaming batch_size={batch_size}") for out in tqdm(pipe(dataset, batch_size=batch_size), total=len(dataset)): pass
# On GTX 970 ------------------------------ Streaming no batching 100%|██████████████████████████████████████████████████████████████████████| 5000/5000 [00:26<00:00, 187.52it/s] ------------------------------ Streaming batch_size=8 100%|█████████████████████████████████████████████████████████████████████| 5000/5000 [00:04<00:00, 1205.95it/s] ------------------------------ Streaming batch_size=64 100%|█████████████████████████████████████████████████████████████████████| 5000/5000 [00:02<00:00, 2478.24it/s] ------------------------------ Streaming batch_size=256 100%|█████████████████████████████████████████████████████████████████████| 5000/5000 [00:01<00:00, 2554.43it/s] (diminishing returns, saturated the GPU)
Example where it’s most a slowdown:
class MyDataset(Dataset): def __len__(self): return 5000 def __getitem__(self, i): if i % 64 == 0: n = 100 else: n = 1 return "This is a test" * n
This is a occasional very long sentence compared to the other. In that case, the whole batch will need to be 400 tokens long, so the whole batch will be [64, 400] instead of [64, 4], leading to the high slowdown. Even worse, on bigger batches, the program simply crashes.
Streaming no batching 100%|█████████████████████████████████████████████████████████████████████| 1000/1000 [00:05<00:00, 183.69it/s] Streaming batch_size=8 100%|█████████████████████████████████████████████████████████████████████| 1000/1000 [00:03<00:00, 265.74it/s] Streaming batch_size=64 100%|██████████████████████████████████████████████████████████████████████| 1000/1000 [00:26<00:00, 37.80it/s] Streaming batch_size=256 0%| | 0/1000 [00:00<?, ?it/s] Traceback (most recent call last): File "/home/nicolas/src/transformers/test.py", line 42, in <module> for out in tqdm(pipe(dataset, batch_size=256), total=len(dataset)): .... q = q / math.sqrt(dim_per_head) RuntimeError: CUDA out of memory. Tried to allocate 376.00 MiB (GPU 0; 3.95 GiB total capacity; 1.72 GiB already allocated; 354.88 MiB free; 2.46 GiB reserved in total by PyTorch)
There are no good (general) solutions for this problem, and your mileage may vary depending on your use cases. Rule of thumb:
For users, a rule of thumb is:
Measure performance on your load, with your hardware. Measure, measure, and keep measuring. Real numbers are the only way to go.
If you are latency constrained (live product doing inference), don’t batch.
If you are using CPU, don’t batch.
If you are using throughput (you want to run your model on a bunch of static data), on GPU, then:
As soon as you enable batching, make sure you can handle OOMs nicely.
zero-shot-classification
and question-answering
are slightly specific in the sense, that a single input might yield multiple forward pass of a model. Under normal circumstances, this would yield issues with batch_size
argument.
In order to circumvent this issue, both of these pipelines are a bit specific, they are ChunkPipeline
instead of regular Pipeline
. In short:
preprocessed = pipe.preprocess(inputs) model_outputs = pipe.forward(preprocessed) outputs = pipe.postprocess(model_outputs)
Now becomes:
all_model_outputs = [] for preprocessed in pipe.preprocess(inputs): model_outputs = pipe.forward(preprocessed) all_model_outputs.append(model_outputs) outputs = pipe.postprocess(all_model_outputs)
This should be very transparent to your code because the pipelines are used in the same way.
This is a simplified view, since the pipeline can handle automatically the batch to ! Meaning you don’t have to care about how many forward passes you inputs are actually going to trigger, you can optimize the batch_size
independently of the inputs. The caveats from the previous section still apply.
Models can be run in FP16 which can be significantly faster on GPU while saving memory. Most models will not suffer noticeable performance loss from this. The larger the model, the less likely that it will.
To enable FP16 inference, you can simply pass torch_dtype=torch.float16
or torch_dtype='float16'
to the pipeline constructor. Note that this only works for models with a PyTorch backend. Your inputs will be converted to FP16 internally.
If you want to override a specific pipeline.
Don’t hesitate to create an issue for your task at hand, the goal of the pipeline is to be easy to use and support most cases, so transformers
could maybe support your use case.
If you want to try simply you can:
class MyPipeline(TextClassificationPipeline): def postprocess(): scores = scores * 100 my_pipeline = MyPipeline(model=model, tokenizer=tokenizer, ...) my_pipeline = pipeline(model="xxxx", pipeline_class=MyPipeline)
That should enable you to do all the custom code you want.
Implementing a pipeline AudioPipelines available for audio tasks include the following.
AudioClassificationPipeline class transformers.AudioClassificationPipeline < source >( *args **kwargs )
Parameters
str
or ModelCard
, optional) — Model card attributed to the model for this pipeline. str
, optional) — The framework to use, either "pt"
for PyTorch or "tf"
for TensorFlow. The specified framework must be installed.
If no framework is specified, will default to the one currently installed. If no framework is specified and both frameworks are installed, will default to the framework of the model
, or to PyTorch if no model is provided.
str
, defaults to ""
) — A task-identifier for the pipeline. int
, optional, defaults to 8) — When the pipeline will use DataLoader (when passing a dataset, on GPU for a Pytorch model), the number of workers to be used. int
, optional, defaults to 1) — When the pipeline will use DataLoader (when passing a dataset, on GPU for a Pytorch model), the size of the batch to use, for inference this is not always beneficial, please read Batching with pipelines . int
, optional, defaults to -1) — Device ordinal for CPU/GPU supports. Setting this to -1 will leverage CPU, a positive will run the model on the associated CUDA device id. You can pass native torch.device
or a str
too str
or torch.dtype
, optional) — Sent directly as model_kwargs
(just a simpler shortcut) to use the available precision for this model (torch.float16
, torch.bfloat16
, … or "auto"
) bool
, optional, defaults to False
) — Flag indicating if the output the pipeline should happen in a serialized format (i.e., pickle) or as the raw output data e.g. text. Audio classification pipeline using any AutoModelForAudioClassification
. This pipeline predicts the class of a raw waveform or an audio file. In case of an audio file, ffmpeg should be installed to support multiple audio formats.
Example:
>>> from transformers import pipeline >>> classifier = pipeline(model="superb/wav2vec2-base-superb-ks") >>> classifier("https://huggingface.co/datasets/Narsil/asr_dummy/resolve/main/1.flac") [{'score': 0.997, 'label': '_unknown_'}, {'score': 0.002, 'label': 'left'}, {'score': 0.0, 'label': 'yes'}, {'score': 0.0, 'label': 'down'}, {'score': 0.0, 'label': 'stop'}]
Learn more about the basics of using a pipeline in the pipeline tutorial
This pipeline can currently be loaded from pipeline() using the following task identifier: "audio-classification"
.
See the list of available models on huggingface.co/models.
__call__ < source >( inputs: typing.Union[numpy.ndarray, bytes, str] **kwargs ) → A list of dict
with the following keys
Parameters
np.ndarray
or bytes
or str
or dict
) — The inputs is either :
str
that is the filename of the audio file, the file will be read at the correct sampling rate to get the waveform using ffmpeg. This requires ffmpeg to be installed on the system.bytes
it is supposed to be the content of an audio file and is interpreted by ffmpeg in the same way.np.ndarray
of shape (n, ) of type np.float32
or np.float64
) Raw audio at the correct sampling rate (no further check will be done)dict
form can be used to pass raw audio sampled at arbitrary sampling_rate
and let this pipeline do the resampling. The dict must be either be in the format {"sampling_rate": int, "raw": np.array}
, or {"sampling_rate": int, "array": np.array}
, where the key "raw"
or "array"
is used to denote the raw audio waveform.int
, optional, defaults to None) — The number of top labels that will be returned by the pipeline. If the provided number is None
or higher than the number of labels available in the model configuration, it will default to the number of labels. str
, optional, defaults to “softmax”) — The function to apply to the model output. By default, the pipeline will apply the softmax function to the output of the model. Valid options: [“softmax”, “sigmoid”, “none”]. Note that passing Python’s built-in None
will default to “softmax”, so you need to pass the string “none” to disable any post-processing. Returns
A list of dict
with the following keys
str
) — The label predicted.float
) — The corresponding probability.Classify the sequence(s) given as inputs. See the AutomaticSpeechRecognitionPipeline documentation for more information.
AutomaticSpeechRecognitionPipeline class transformers.AutomaticSpeechRecognitionPipeline < source >( model: PreTrainedModel feature_extractor: typing.Union[ForwardRef('SequenceFeatureExtractor'), str] = None tokenizer: typing.Optional[transformers.tokenization_utils.PreTrainedTokenizer] = None decoder: typing.Union[ForwardRef('BeamSearchDecoderCTC'), str, NoneType] = None device: typing.Union[int, ForwardRef('torch.device')] = None torch_dtype: typing.Union[str, ForwardRef('torch.dtype'), NoneType] = None **kwargs )
Parameters
pyctcdecode.BeamSearchDecoderCTC
, optional) — PyCTCDecode’s BeamSearchDecoderCTC can be passed for language model boosted decoding. See Wav2Vec2ProcessorWithLM for more information. float
, optional, defaults to 0) — The input length for in each chunk. If chunk_length_s = 0
then chunking is disabled (default).
For more information on how to effectively use chunk_length_s
, please have a look at the ASR chunking blog post.
float
, optional, defaults to chunk_length_s / 6
) — The length of stride on the left and right of each chunk. Used only with chunk_length_s > 0
. This enables the model to see more context and infer letters better than without this context but the pipeline discards the stride bits at the end to make the final reconstitution as perfect as possible.
For more information on how to effectively use stride_length_s
, please have a look at the ASR chunking blog post.
str
, optional) — The framework to use, either "pt"
for PyTorch or "tf"
for TensorFlow. The specified framework must be installed. If no framework is specified, will default to the one currently installed. If no framework is specified and both frameworks are installed, will default to the framework of the model
, or to PyTorch if no model is provided. int
, torch.device
], optional) — Device ordinal for CPU/GPU supports. Setting this to None
will leverage CPU, a positive will run the model on the associated CUDA device id. int
, torch.dtype
], optional) — The data-type (dtype) of the computation. Setting this to None
will use float32 precision. Set to torch.float16
or torch.bfloat16
to use half-precision in the respective dtypes. Pipeline that aims at extracting spoken text contained within some audio.
The input can be either a raw waveform or a audio file. In case of the audio file, ffmpeg should be installed for to support multiple audio formats
Example:
>>> from transformers import pipeline >>> transcriber = pipeline(model="openai/whisper-base") >>> transcriber("https://huggingface.co/datasets/Narsil/asr_dummy/resolve/main/1.flac") {'text': ' He hoped there would be stew for dinner, turnips and carrots and bruised potatoes and fat mutton pieces to be ladled out in thick, peppered flour-fatten sauce.'}
Learn more about the basics of using a pipeline in the pipeline tutorial
__call__ < source >( inputs: typing.Union[numpy.ndarray, bytes, str] **kwargs ) → Dict
Parameters
np.ndarray
or bytes
or str
or dict
) — The inputs is either :
str
that is either the filename of a local audio file, or a public URL address to download the audio file. The file will be read at the correct sampling rate to get the waveform using ffmpeg. This requires ffmpeg to be installed on the system.bytes
it is supposed to be the content of an audio file and is interpreted by ffmpeg in the same way.np.ndarray
of shape (n, ) of type np.float32
or np.float64
) Raw audio at the correct sampling rate (no further check will be done)dict
form can be used to pass raw audio sampled at arbitrary sampling_rate
and let this pipeline do the resampling. The dict must be in the format {"sampling_rate": int, "raw": np.array}
with optionally a "stride": (left: int, right: int)
than can ask the pipeline to treat the first left
samples and last right
samples to be ignored in decoding (but used at inference to provide more context to the model). Only use stride
with CTC models.str
or bool
) — Only available for pure CTC models (Wav2Vec2, HuBERT, etc) and the Whisper model. Not available for other sequence-to-sequence models.
For CTC models, timestamps can take one of two formats:
"char"
: the pipeline will return timestamps along the text for every character in the text. For instance, if you get [{"text": "h", "timestamp": (0.5, 0.6)}, {"text": "i", "timestamp": (0.7, 0.9)}]
, then it means the model predicts that the letter “h” was spoken after 0.5
and before 0.6
seconds."word"
: the pipeline will return timestamps along the text for every word in the text. For instance, if you get [{"text": "hi ", "timestamp": (0.5, 0.9)}, {"text": "there", "timestamp": (1.0, 1.5)}]
, then it means the model predicts that the word “hi” was spoken after 0.5
and before 0.9
seconds.For the Whisper model, timestamps can take one of two formats:
"word"
: same as above for word-level CTC timestamps. Word-level timestamps are predicted through the dynamic-time warping (DTW) algorithm, an approximation to word-level timestamps by inspecting the cross-attention weights.True
: the pipeline will return timestamps along the text for segments of words in the text. For instance, if you get [{"text": " Hi there!", "timestamp": (0.5, 1.5)}]
, then it means the model predicts that the segment “Hi there!” was spoken after 0.5
and before 1.5
seconds. Note that a segment of text refers to a sequence of one or more words, rather than individual words as with word-level timestamps.dict
, optional) — The dictionary of ad-hoc parametrization of generate_config
to be used for the generation call. For a complete overview of generate, check the following guide. A dictionary with the following keys:
str
): The recognized text.List[Dict]
) When using return_timestamps
, the chunks
will become a list containing all the various text chunks identified by the model, e.g.* [{"text": "hi ", "timestamp": (0.5, 0.9)}, {"text": "there", "timestamp": (1.0, 1.5)}]
. The original full text can roughly be recovered by doing "".join(chunk["text"] for chunk in output["chunks"])
.Transcribe the audio sequence(s) given as inputs to text. See the AutomaticSpeechRecognitionPipeline documentation for more information.
TextToAudioPipeline class transformers.TextToAudioPipeline < source >( *args vocoder = None sampling_rate = None **kwargs )
Text-to-audio generation pipeline using any AutoModelForTextToWaveform
or AutoModelForTextToSpectrogram
. This pipeline generates an audio file from an input text and optional other conditional inputs.
Example:
>>> from transformers import pipeline >>> pipe = pipeline(model="suno/bark-small") >>> output = pipe("Hey it's HuggingFace on the phone!") >>> audio = output["audio"] >>> sampling_rate = output["sampling_rate"]
Learn more about the basics of using a pipeline in the pipeline tutorial
You can specify parameters passed to the model by using TextToAudioPipeline.__call__.forward_params
or TextToAudioPipeline.__call__.generate_kwargs
.
Example:
>>> from transformers import pipeline >>> music_generator = pipeline(task="text-to-audio", model="facebook/musicgen-small", framework="pt") >>> >>> generate_kwargs = { ... "do_sample": True, ... "temperature": 0.7, ... "max_new_tokens": 35, ... } >>> outputs = music_generator("Techno music with high melodic riffs", generate_kwargs=generate_kwargs)
This pipeline can currently be loaded from pipeline() using the following task identifiers: "text-to-speech"
or "text-to-audio"
.
See the list of available models on huggingface.co/models.
__call__ < source >( text_inputs: typing.Union[str, typing.List[str]] **forward_params ) → A dict
or a list of dict
Parameters
str
or List[str]
) — The text(s) to generate. dict
, optional) — Parameters passed to the model generation/forward method. forward_params
are always passed to the underlying model. dict
, optional) — The dictionary of ad-hoc parametrization of generate_config
to be used for the generation call. For a complete overview of generate, check the following guide. generate_kwargs
are only passed to the underlying model if the latter is a generative model. Returns
A dict
or a list of dict
The dictionaries have two keys:
np.ndarray
of shape (nb_channels, audio_length)
) — The generated audio waveform.int
) — The sampling rate of the generated audio waveform.Generates speech/audio from the inputs. See the TextToAudioPipeline documentation for more information.
ZeroShotAudioClassificationPipeline class transformers.ZeroShotAudioClassificationPipeline < source >( **kwargs )
Parameters
str
or ModelCard
, optional) — Model card attributed to the model for this pipeline. str
, optional) — The framework to use, either "pt"
for PyTorch or "tf"
for TensorFlow. The specified framework must be installed.
If no framework is specified, will default to the one currently installed. If no framework is specified and both frameworks are installed, will default to the framework of the model
, or to PyTorch if no model is provided.
str
, defaults to ""
) — A task-identifier for the pipeline. int
, optional, defaults to 8) — When the pipeline will use DataLoader (when passing a dataset, on GPU for a Pytorch model), the number of workers to be used. int
, optional, defaults to 1) — When the pipeline will use DataLoader (when passing a dataset, on GPU for a Pytorch model), the size of the batch to use, for inference this is not always beneficial, please read Batching with pipelines . int
, optional, defaults to -1) — Device ordinal for CPU/GPU supports. Setting this to -1 will leverage CPU, a positive will run the model on the associated CUDA device id. You can pass native torch.device
or a str
too str
or torch.dtype
, optional) — Sent directly as model_kwargs
(just a simpler shortcut) to use the available precision for this model (torch.float16
, torch.bfloat16
, … or "auto"
) bool
, optional, defaults to False
) — Flag indicating if the output the pipeline should happen in a serialized format (i.e., pickle) or as the raw output data e.g. text. Zero shot audio classification pipeline using ClapModel
. This pipeline predicts the class of an audio when you provide an audio and a set of candidate_labels
.
The default hypothesis_template
is : "This is a sound of {}."
. Make sure you update it for your usage.
Example:
>>> from transformers import pipeline >>> from datasets import load_dataset >>> dataset = load_dataset("ashraq/esc50") >>> audio = next(iter(dataset["train"]["audio"]))["array"] >>> classifier = pipeline(task="zero-shot-audio-classification", model="laion/clap-htsat-unfused") >>> classifier(audio, candidate_labels=["Sound of a dog", "Sound of vaccum cleaner"]) [{'score': 0.9996, 'label': 'Sound of a dog'}, {'score': 0.0004, 'label': 'Sound of vaccum cleaner'}]
Learn more about the basics of using a pipeline in the pipeline tutorial This audio classification pipeline can currently be loaded from pipeline() using the following task identifier: "zero-shot-audio-classification"
. See the list of available models on huggingface.co/models.
( audios: typing.Union[numpy.ndarray, bytes, str] **kwargs )
Parameters
str
, List[str]
, np.array
or List[np.array]
) — The pipeline handles three types of inputs:
List[str]
) — The candidate labels for this audio. They will be formatted using hypothesis_template. str
, optional, defaults to "This is a sound of {}"
) — The format used in conjunction with candidate_labels to attempt the audio classification by replacing the placeholder with the candidate_labels. Pass ”{}” if candidate_labels are already formatted. Assign labels to the audio(s) passed as inputs.
Computer visionPipelines available for computer vision tasks include the following.
DepthEstimationPipeline class transformers.DepthEstimationPipeline < source >( *args **kwargs )
Parameters
str
or ModelCard
, optional) — Model card attributed to the model for this pipeline. str
, optional) — The framework to use, either "pt"
for PyTorch or "tf"
for TensorFlow. The specified framework must be installed.
If no framework is specified, will default to the one currently installed. If no framework is specified and both frameworks are installed, will default to the framework of the model
, or to PyTorch if no model is provided.
str
, defaults to ""
) — A task-identifier for the pipeline. int
, optional, defaults to 8) — When the pipeline will use DataLoader (when passing a dataset, on GPU for a Pytorch model), the number of workers to be used. int
, optional, defaults to 1) — When the pipeline will use DataLoader (when passing a dataset, on GPU for a Pytorch model), the size of the batch to use, for inference this is not always beneficial, please read Batching with pipelines . int
, optional, defaults to -1) — Device ordinal for CPU/GPU supports. Setting this to -1 will leverage CPU, a positive will run the model on the associated CUDA device id. You can pass native torch.device
or a str
too str
or torch.dtype
, optional) — Sent directly as model_kwargs
(just a simpler shortcut) to use the available precision for this model (torch.float16
, torch.bfloat16
, … or "auto"
) bool
, optional, defaults to False
) — Flag indicating if the output the pipeline should happen in a serialized format (i.e., pickle) or as the raw output data e.g. text. Depth estimation pipeline using any AutoModelForDepthEstimation
. This pipeline predicts the depth of an image.
Example:
>>> from transformers import pipeline >>> depth_estimator = pipeline(task="depth-estimation", model="LiheYoung/depth-anything-base-hf") >>> output = depth_estimator("http://images.cocodataset.org/val2017/000000039769.jpg") >>> >>> output["predicted_depth"].shape torch.Size([1, 384, 384])
Learn more about the basics of using a pipeline in the pipeline tutorial
This depth estimation pipeline can currently be loaded from pipeline() using the following task identifier: "depth-estimation"
.
See the list of available models on huggingface.co/models.
__call__ < source >( inputs: typing.Union[str, typing.List[str], ForwardRef('Image.Image'), typing.List[ForwardRef('Image.Image')]] = None **kwargs )
Parameters
str
, List[str]
, PIL.Image
or List[PIL.Image]
) — The pipeline handles three types of images:
The pipeline accepts either a single image or a batch of images, which must then be passed as a string. Images in a batch must all be in the same format: all as http links, all as local paths, or all as PIL images.
Dict
, optional) — A dictionary of argument names to parameter values, to control pipeline behaviour. The only parameter available right now is timeout
, which is the length of time, in seconds, that the pipeline should wait before giving up on trying to download an image. float
, optional, defaults to None) — The maximum time in seconds to wait for fetching images from the web. If None, no timeout is set and the call may block forever. Predict the depth(s) of the image(s) passed as inputs.
ImageClassificationPipeline class transformers.ImageClassificationPipeline < source >( *args **kwargs )
Parameters
str
or ModelCard
, optional) — Model card attributed to the model for this pipeline. str
, optional) — The framework to use, either "pt"
for PyTorch or "tf"
for TensorFlow. The specified framework must be installed.
If no framework is specified, will default to the one currently installed. If no framework is specified and both frameworks are installed, will default to the framework of the model
, or to PyTorch if no model is provided.
str
, defaults to ""
) — A task-identifier for the pipeline. int
, optional, defaults to 8) — When the pipeline will use DataLoader (when passing a dataset, on GPU for a Pytorch model), the number of workers to be used. int
, optional, defaults to 1) — When the pipeline will use DataLoader (when passing a dataset, on GPU for a Pytorch model), the size of the batch to use, for inference this is not always beneficial, please read Batching with pipelines . int
, optional, defaults to -1) — Device ordinal for CPU/GPU supports. Setting this to -1 will leverage CPU, a positive will run the model on the associated CUDA device id. You can pass native torch.device
or a str
too str
or torch.dtype
, optional) — Sent directly as model_kwargs
(just a simpler shortcut) to use the available precision for this model (torch.float16
, torch.bfloat16
, … or "auto"
) bool
, optional, defaults to False
) — Flag indicating if the output the pipeline should happen in a serialized format (i.e., pickle) or as the raw output data e.g. text. str
, optional, defaults to "default"
) — The function to apply to the model outputs in order to retrieve the scores. Accepts four different values:
"default"
: if the model has a single label, will apply the sigmoid function on the output. If the model has several labels, will apply the softmax function on the output."sigmoid"
: Applies the sigmoid function on the output."softmax"
: Applies the softmax function on the output."none"
: Does not apply any function on the output.Image classification pipeline using any AutoModelForImageClassification
. This pipeline predicts the class of an image.
Example:
>>> from transformers import pipeline >>> classifier = pipeline(model="microsoft/beit-base-patch16-224-pt22k-ft22k") >>> classifier("https://huggingface.co/datasets/Narsil/image_dummy/raw/main/parrots.png") [{'score': 0.442, 'label': 'macaw'}, {'score': 0.088, 'label': 'popinjay'}, {'score': 0.075, 'label': 'parrot'}, {'score': 0.073, 'label': 'parodist, lampooner'}, {'score': 0.046, 'label': 'poll, poll_parrot'}]
Learn more about the basics of using a pipeline in the pipeline tutorial
This image classification pipeline can currently be loaded from pipeline() using the following task identifier: "image-classification"
.
See the list of available models on huggingface.co/models.
__call__ < source >( inputs: typing.Union[str, typing.List[str], ForwardRef('Image.Image'), typing.List[ForwardRef('Image.Image')]] = None **kwargs )
Parameters
str
, List[str]
, PIL.Image
or List[PIL.Image]
) — The pipeline handles three types of images:
The pipeline accepts either a single image or a batch of images, which must then be passed as a string. Images in a batch must all be in the same format: all as http links, all as local paths, or all as PIL images.
str
, optional, defaults to "default"
) — The function to apply to the model outputs in order to retrieve the scores. Accepts four different values:
If this argument is not specified, then it will apply the following functions according to the number of labels:
Possible values are:
"sigmoid"
: Applies the sigmoid function on the output."softmax"
: Applies the softmax function on the output."none"
: Does not apply any function on the output.int
, optional, defaults to 5) — The number of top labels that will be returned by the pipeline. If the provided number is higher than the number of labels available in the model configuration, it will default to the number of labels. float
, optional, defaults to None) — The maximum time in seconds to wait for fetching images from the web. If None, no timeout is set and the call may block forever. Assign labels to the image(s) passed as inputs.
ImageSegmentationPipeline class transformers.ImageSegmentationPipeline < source >( *args **kwargs )
Parameters
str
or ModelCard
, optional) — Model card attributed to the model for this pipeline. str
, optional) — The framework to use, either "pt"
for PyTorch or "tf"
for TensorFlow. The specified framework must be installed.
If no framework is specified, will default to the one currently installed. If no framework is specified and both frameworks are installed, will default to the framework of the model
, or to PyTorch if no model is provided.
str
, defaults to ""
) — A task-identifier for the pipeline. int
, optional, defaults to 8) — When the pipeline will use DataLoader (when passing a dataset, on GPU for a Pytorch model), the number of workers to be used. int
, optional, defaults to 1) — When the pipeline will use DataLoader (when passing a dataset, on GPU for a Pytorch model), the size of the batch to use, for inference this is not always beneficial, please read Batching with pipelines . int
, optional, defaults to -1) — Device ordinal for CPU/GPU supports. Setting this to -1 will leverage CPU, a positive will run the model on the associated CUDA device id. You can pass native torch.device
or a str
too str
or torch.dtype
, optional) — Sent directly as model_kwargs
(just a simpler shortcut) to use the available precision for this model (torch.float16
, torch.bfloat16
, … or "auto"
) bool
, optional, defaults to False
) — Flag indicating if the output the pipeline should happen in a serialized format (i.e., pickle) or as the raw output data e.g. text. Image segmentation pipeline using any AutoModelForXXXSegmentation
. This pipeline predicts masks of objects and their classes.
Example:
>>> from transformers import pipeline >>> segmenter = pipeline(model="facebook/detr-resnet-50-panoptic") >>> segments = segmenter("https://huggingface.co/datasets/Narsil/image_dummy/raw/main/parrots.png") >>> len(segments) 2 >>> segments[0]["label"] 'bird' >>> segments[1]["label"] 'bird' >>> type(segments[0]["mask"]) <class 'PIL.Image.Image'> >>> segments[0]["mask"].size (768, 512)
This image segmentation pipeline can currently be loaded from pipeline() using the following task identifier: "image-segmentation"
.
See the list of available models on huggingface.co/models.
__call__ < source >( inputs = None **kwargs )
Parameters
str
, List[str]
, PIL.Image
or List[PIL.Image]
) — The pipeline handles three types of images:
The pipeline accepts either a single image or a batch of images. Images in a batch must all be in the same format: all as HTTP(S) links, all as local paths, or all as PIL images.
str
, optional) — Segmentation task to be performed, choose [semantic
, instance
and panoptic
] depending on model capabilities. If not set, the pipeline will attempt tp resolve in the following order: panoptic
, instance
, semantic
. float
, optional, defaults to 0.9) — Probability threshold to filter out predicted masks. float
, optional, defaults to 0.5) — Threshold to use when turning the predicted masks into binary values. float
, optional, defaults to 0.5) — Mask overlap threshold to eliminate small, disconnected segments. float
, optional, defaults to None) — The maximum time in seconds to wait for fetching images from the web. If None, no timeout is set and the call may block forever. Perform segmentation (detect masks & classes) in the image(s) passed as inputs.
ImageToImagePipeline class transformers.ImageToImagePipeline < source >( *args **kwargs )
Parameters
str
or ModelCard
, optional) — Model card attributed to the model for this pipeline. str
, optional) — The framework to use, either "pt"
for PyTorch or "tf"
for TensorFlow. The specified framework must be installed.
If no framework is specified, will default to the one currently installed. If no framework is specified and both frameworks are installed, will default to the framework of the model
, or to PyTorch if no model is provided.
str
, defaults to ""
) — A task-identifier for the pipeline. int
, optional, defaults to 8) — When the pipeline will use DataLoader (when passing a dataset, on GPU for a Pytorch model), the number of workers to be used. int
, optional, defaults to 1) — When the pipeline will use DataLoader (when passing a dataset, on GPU for a Pytorch model), the size of the batch to use, for inference this is not always beneficial, please read Batching with pipelines . int
, optional, defaults to -1) — Device ordinal for CPU/GPU supports. Setting this to -1 will leverage CPU, a positive will run the model on the associated CUDA device id. You can pass native torch.device
or a str
too str
or torch.dtype
, optional) — Sent directly as model_kwargs
(just a simpler shortcut) to use the available precision for this model (torch.float16
, torch.bfloat16
, … or "auto"
) bool
, optional, defaults to False
) — Flag indicating if the output the pipeline should happen in a serialized format (i.e., pickle) or as the raw output data e.g. text. Image to Image pipeline using any AutoModelForImageToImage
. This pipeline generates an image based on a previous image input.
Example:
>>> from PIL import Image >>> import requests >>> from transformers import pipeline >>> upscaler = pipeline("image-to-image", model="caidas/swin2SR-classical-sr-x2-64") >>> img = Image.open(requests.get("http://images.cocodataset.org/val2017/000000039769.jpg", stream=True).raw) >>> img = img.resize((64, 64)) >>> upscaled_img = upscaler(img) >>> img.size (64, 64) >>> upscaled_img.size (144, 144)
This image to image pipeline can currently be loaded from pipeline() using the following task identifier: "image-to-image"
.
See the list of available models on huggingface.co/models.
__call__ < source >( images: typing.Union[str, typing.List[str], ForwardRef('Image.Image'), typing.List[ForwardRef('Image.Image')]] **kwargs )
Parameters
str
, List[str]
, PIL.Image
or List[PIL.Image]
) — The pipeline handles three types of images:
The pipeline accepts either a single image or a batch of images, which must then be passed as a string. Images in a batch must all be in the same format: all as http links, all as local paths, or all as PIL images.
float
, optional, defaults to None) — The maximum time in seconds to wait for fetching images from the web. If None, no timeout is used and the call may block forever. Transform the image(s) passed as inputs.
ObjectDetectionPipeline class transformers.ObjectDetectionPipeline < source >( *args **kwargs )
Parameters
str
or ModelCard
, optional) — Model card attributed to the model for this pipeline. str
, optional) — The framework to use, either "pt"
for PyTorch or "tf"
for TensorFlow. The specified framework must be installed.
If no framework is specified, will default to the one currently installed. If no framework is specified and both frameworks are installed, will default to the framework of the model
, or to PyTorch if no model is provided.
str
, defaults to ""
) — A task-identifier for the pipeline. int
, optional, defaults to 8) — When the pipeline will use DataLoader (when passing a dataset, on GPU for a Pytorch model), the number of workers to be used. int
, optional, defaults to 1) — When the pipeline will use DataLoader (when passing a dataset, on GPU for a Pytorch model), the size of the batch to use, for inference this is not always beneficial, please read Batching with pipelines . int
, optional, defaults to -1) — Device ordinal for CPU/GPU supports. Setting this to -1 will leverage CPU, a positive will run the model on the associated CUDA device id. You can pass native torch.device
or a str
too str
or torch.dtype
, optional) — Sent directly as model_kwargs
(just a simpler shortcut) to use the available precision for this model (torch.float16
, torch.bfloat16
, … or "auto"
) bool
, optional, defaults to False
) — Flag indicating if the output the pipeline should happen in a serialized format (i.e., pickle) or as the raw output data e.g. text. Object detection pipeline using any AutoModelForObjectDetection
. This pipeline predicts bounding boxes of objects and their classes.
Example:
>>> from transformers import pipeline >>> detector = pipeline(model="facebook/detr-resnet-50") >>> detector("https://huggingface.co/datasets/Narsil/image_dummy/raw/main/parrots.png") [{'score': 0.997, 'label': 'bird', 'box': {'xmin': 69, 'ymin': 171, 'xmax': 396, 'ymax': 507}}, {'score': 0.999, 'label': 'bird', 'box': {'xmin': 398, 'ymin': 105, 'xmax': 767, 'ymax': 507}}] >>>
Learn more about the basics of using a pipeline in the pipeline tutorial
This object detection pipeline can currently be loaded from pipeline() using the following task identifier: "object-detection"
.
See the list of available models on huggingface.co/models.
__call__ < source >( *args **kwargs )
Parameters
str
, List[str]
, PIL.Image
or List[PIL.Image]
) — The pipeline handles three types of images:
The pipeline accepts either a single image or a batch of images. Images in a batch must all be in the same format: all as HTTP(S) links, all as local paths, or all as PIL images.
float
, optional, defaults to 0.5) — The probability necessary to make a prediction. float
, optional, defaults to None) — The maximum time in seconds to wait for fetching images from the web. If None, no timeout is set and the call may block forever. Detect objects (bounding boxes & classes) in the image(s) passed as inputs.
VideoClassificationPipeline class transformers.VideoClassificationPipeline < source >( *args **kwargs )
Parameters
str
or ModelCard
, optional) — Model card attributed to the model for this pipeline. str
, optional) — The framework to use, either "pt"
for PyTorch or "tf"
for TensorFlow. The specified framework must be installed.
If no framework is specified, will default to the one currently installed. If no framework is specified and both frameworks are installed, will default to the framework of the model
, or to PyTorch if no model is provided.
str
, defaults to ""
) — A task-identifier for the pipeline. int
, optional, defaults to 8) — When the pipeline will use DataLoader (when passing a dataset, on GPU for a Pytorch model), the number of workers to be used. int
, optional, defaults to 1) — When the pipeline will use DataLoader (when passing a dataset, on GPU for a Pytorch model), the size of the batch to use, for inference this is not always beneficial, please read Batching with pipelines . int
, optional, defaults to -1) — Device ordinal for CPU/GPU supports. Setting this to -1 will leverage CPU, a positive will run the model on the associated CUDA device id. You can pass native torch.device
or a str
too str
or torch.dtype
, optional) — Sent directly as model_kwargs
(just a simpler shortcut) to use the available precision for this model (torch.float16
, torch.bfloat16
, … or "auto"
) bool
, optional, defaults to False
) — Flag indicating if the output the pipeline should happen in a serialized format (i.e., pickle) or as the raw output data e.g. text. Video classification pipeline using any AutoModelForVideoClassification
. This pipeline predicts the class of a video.
This video classification pipeline can currently be loaded from pipeline() using the following task identifier: "video-classification"
.
See the list of available models on huggingface.co/models.
__call__ < source >( inputs: typing.Union[str, typing.List[str]] = None **kwargs )
Parameters
str
, List[str]
) — The pipeline handles three types of videos:
The pipeline accepts either a single video or a batch of videos, which must then be passed as a string. Videos in a batch must all be in the same format: all as http links or all as local paths.
int
, optional, defaults to 5) — The number of top labels that will be returned by the pipeline. If the provided number is higher than the number of labels available in the model configuration, it will default to the number of labels. int
, optional, defaults to self.model.config.num_frames
) — The number of frames sampled from the video to run the classification on. If not provided, will default to the number of frames specified in the model configuration. int
, optional, defaults to 1) — The sampling rate used to select frames from the video. If not provided, will default to 1, i.e. every frame will be used. str
, optional, defaults to “softmax”) — The function to apply to the model output. By default, the pipeline will apply the softmax function to the output of the model. Valid options: [“softmax”, “sigmoid”, “none”]. Note that passing Python’s built-in None
will default to “softmax”, so you need to pass the string “none” to disable any post-processing. Assign labels to the video(s) passed as inputs.
ZeroShotImageClassificationPipeline class transformers.ZeroShotImageClassificationPipeline < source >( **kwargs )
Parameters
str
or ModelCard
, optional) — Model card attributed to the model for this pipeline. str
, optional) — The framework to use, either "pt"
for PyTorch or "tf"
for TensorFlow. The specified framework must be installed.
If no framework is specified, will default to the one currently installed. If no framework is specified and both frameworks are installed, will default to the framework of the model
, or to PyTorch if no model is provided.
str
, defaults to ""
) — A task-identifier for the pipeline. int
, optional, defaults to 8) — When the pipeline will use DataLoader (when passing a dataset, on GPU for a Pytorch model), the number of workers to be used. int
, optional, defaults to 1) — When the pipeline will use DataLoader (when passing a dataset, on GPU for a Pytorch model), the size of the batch to use, for inference this is not always beneficial, please read Batching with pipelines . int
, optional, defaults to -1) — Device ordinal for CPU/GPU supports. Setting this to -1 will leverage CPU, a positive will run the model on the associated CUDA device id. You can pass native torch.device
or a str
too str
or torch.dtype
, optional) — Sent directly as model_kwargs
(just a simpler shortcut) to use the available precision for this model (torch.float16
, torch.bfloat16
, … or "auto"
) bool
, optional, defaults to False
) — Flag indicating if the output the pipeline should happen in a serialized format (i.e., pickle) or as the raw output data e.g. text. Zero shot image classification pipeline using CLIPModel
. This pipeline predicts the class of an image when you provide an image and a set of candidate_labels
.
Example:
>>> from transformers import pipeline >>> classifier = pipeline(model="google/siglip-so400m-patch14-384") >>> classifier( ... "https://huggingface.co/datasets/Narsil/image_dummy/raw/main/parrots.png", ... candidate_labels=["animals", "humans", "landscape"], ... ) [{'score': 0.965, 'label': 'animals'}, {'score': 0.03, 'label': 'humans'}, {'score': 0.005, 'label': 'landscape'}] >>> classifier( ... "https://huggingface.co/datasets/Narsil/image_dummy/raw/main/parrots.png", ... candidate_labels=["black and white", "photorealist", "painting"], ... ) [{'score': 0.996, 'label': 'black and white'}, {'score': 0.003, 'label': 'photorealist'}, {'score': 0.0, 'label': 'painting'}]
Learn more about the basics of using a pipeline in the pipeline tutorial
This image classification pipeline can currently be loaded from pipeline() using the following task identifier: "zero-shot-image-classification"
.
See the list of available models on huggingface.co/models.
__call__ < source >( image: typing.Union[str, typing.List[str], ForwardRef('Image'), typing.List[ForwardRef('Image')]] = None **kwargs )
Parameters
str
, List[str]
, PIL.Image
or List[PIL.Image]
) — The pipeline handles three types of images:
List[str]
) — The candidate labels for this image. They will be formatted using hypothesis_template. str
, optional, defaults to "This is a photo of {}"
) — The format used in conjunction with candidate_labels to attempt the image classification by replacing the placeholder with the candidate_labels. Pass ”{}” if candidate_labels are already formatted. float
, optional, defaults to None) — The maximum time in seconds to wait for fetching images from the web. If None, no timeout is set and the call may block forever. Assign labels to the image(s) passed as inputs.
ZeroShotObjectDetectionPipeline class transformers.ZeroShotObjectDetectionPipeline < source >( **kwargs )
Parameters
str
or ModelCard
, optional) — Model card attributed to the model for this pipeline. str
, optional) — The framework to use, either "pt"
for PyTorch or "tf"
for TensorFlow. The specified framework must be installed.
If no framework is specified, will default to the one currently installed. If no framework is specified and both frameworks are installed, will default to the framework of the model
, or to PyTorch if no model is provided.
str
, defaults to ""
) — A task-identifier for the pipeline. int
, optional, defaults to 8) — When the pipeline will use DataLoader (when passing a dataset, on GPU for a Pytorch model), the number of workers to be used. int
, optional, defaults to 1) — When the pipeline will use DataLoader (when passing a dataset, on GPU for a Pytorch model), the size of the batch to use, for inference this is not always beneficial, please read Batching with pipelines . int
, optional, defaults to -1) — Device ordinal for CPU/GPU supports. Setting this to -1 will leverage CPU, a positive will run the model on the associated CUDA device id. You can pass native torch.device
or a str
too str
or torch.dtype
, optional) — Sent directly as model_kwargs
(just a simpler shortcut) to use the available precision for this model (torch.float16
, torch.bfloat16
, … or "auto"
) bool
, optional, defaults to False
) — Flag indicating if the output the pipeline should happen in a serialized format (i.e., pickle) or as the raw output data e.g. text. Zero shot object detection pipeline using OwlViTForObjectDetection
. This pipeline predicts bounding boxes of objects when you provide an image and a set of candidate_labels
.
Example:
>>> from transformers import pipeline >>> detector = pipeline(model="google/owlvit-base-patch32", task="zero-shot-object-detection") >>> detector( ... "http://images.cocodataset.org/val2017/000000039769.jpg", ... candidate_labels=["cat", "couch"], ... ) [{'score': 0.287, 'label': 'cat', 'box': {'xmin': 324, 'ymin': 20, 'xmax': 640, 'ymax': 373}}, {'score': 0.254, 'label': 'cat', 'box': {'xmin': 1, 'ymin': 55, 'xmax': 315, 'ymax': 472}}, {'score': 0.121, 'label': 'couch', 'box': {'xmin': 4, 'ymin': 0, 'xmax': 642, 'ymax': 476}}] >>> detector( ... "https://huggingface.co/datasets/Narsil/image_dummy/raw/main/parrots.png", ... candidate_labels=["head", "bird"], ... ) [{'score': 0.119, 'label': 'bird', 'box': {'xmin': 71, 'ymin': 170, 'xmax': 410, 'ymax': 508}}]
Learn more about the basics of using a pipeline in the pipeline tutorial
This object detection pipeline can currently be loaded from pipeline() using the following task identifier: "zero-shot-object-detection"
.
See the list of available models on huggingface.co/models.
__call__ < source >( image: typing.Union[str, ForwardRef('Image.Image'), typing.List[typing.Dict[str, typing.Any]]] candidate_labels: typing.Union[str, typing.List[str]] = None **kwargs )
Parameters
str
, PIL.Image
or List[Dict[str, Any]]
) — The pipeline handles three types of images:
You can use this parameter to send directly a list of images, or a dataset or a generator like so:
Detect objects (bounding boxes & classes) in the image(s) passed as inputs.
Natural Language ProcessingPipelines available for natural language processing tasks include the following.
FillMaskPipeline class transformers.FillMaskPipeline < source >( model: typing.Union[ForwardRef('PreTrainedModel'), ForwardRef('TFPreTrainedModel')] tokenizer: typing.Optional[transformers.tokenization_utils.PreTrainedTokenizer] = None feature_extractor: typing.Optional[ForwardRef('SequenceFeatureExtractor')] = None image_processor: typing.Optional[transformers.image_processing_utils.BaseImageProcessor] = None processor: typing.Optional[transformers.processing_utils.ProcessorMixin] = None modelcard: typing.Optional[transformers.modelcard.ModelCard] = None framework: typing.Optional[str] = None task: str = '' args_parser: ArgumentHandler = None device: typing.Union[int, ForwardRef('torch.device')] = None torch_dtype: typing.Union[str, ForwardRef('torch.dtype'), NoneType] = None binary_output: bool = False **kwargs )
Parameters
str
or ModelCard
, optional) — Model card attributed to the model for this pipeline. str
, optional) — The framework to use, either "pt"
for PyTorch or "tf"
for TensorFlow. The specified framework must be installed.
If no framework is specified, will default to the one currently installed. If no framework is specified and both frameworks are installed, will default to the framework of the model
, or to PyTorch if no model is provided.
str
, defaults to ""
) — A task-identifier for the pipeline. int
, optional, defaults to 8) — When the pipeline will use DataLoader (when passing a dataset, on GPU for a Pytorch model), the number of workers to be used. int
, optional, defaults to 1) — When the pipeline will use DataLoader (when passing a dataset, on GPU for a Pytorch model), the size of the batch to use, for inference this is not always beneficial, please read Batching with pipelines . int
, optional, defaults to -1) — Device ordinal for CPU/GPU supports. Setting this to -1 will leverage CPU, a positive will run the model on the associated CUDA device id. You can pass native torch.device
or a str
too str
or torch.dtype
, optional) — Sent directly as model_kwargs
(just a simpler shortcut) to use the available precision for this model (torch.float16
, torch.bfloat16
, … or "auto"
) bool
, optional, defaults to False
) — Flag indicating if the output the pipeline should happen in a serialized format (i.e., pickle) or as the raw output data e.g. text. int
, optional, defaults to 5) — The number of predictions to return. str
or List[str]
, optional) — When passed, the model will limit the scores to the passed targets instead of looking up in the whole vocab. If the provided targets are not in the model vocab, they will be tokenized and the first resulting token will be used (with a warning, and that might be slower). dict
, optional) — Additional dictionary of keyword arguments passed along to the tokenizer. Masked language modeling prediction pipeline using any ModelWithLMHead
. See the masked language modeling examples for more information.
Example:
>>> from transformers import pipeline >>> fill_masker = pipeline(model="google-bert/bert-base-uncased") >>> fill_masker("This is a simple [MASK].") [{'score': 0.042, 'token': 3291, 'token_str': 'problem', 'sequence': 'this is a simple problem.'}, {'score': 0.031, 'token': 3160, 'token_str': 'question', 'sequence': 'this is a simple question.'}, {'score': 0.03, 'token': 8522, 'token_str': 'equation', 'sequence': 'this is a simple equation.'}, {'score': 0.027, 'token': 2028, 'token_str': 'one', 'sequence': 'this is a simple one.'}, {'score': 0.024, 'token': 3627, 'token_str': 'rule', 'sequence': 'this is a simple rule.'}]
Learn more about the basics of using a pipeline in the pipeline tutorial
This mask filling pipeline can currently be loaded from pipeline() using the following task identifier: "fill-mask"
.
The models that this pipeline can use are models that have been trained with a masked language modeling objective, which includes the bi-directional models in the library. See the up-to-date list of available models on huggingface.co/models.
This pipeline only works for inputs with exactly one token masked. Experimental: We added support for multiple masks. The returned values are raw model output, and correspond to disjoint probabilities where one might expect joint probabilities (See discussion).
This pipeline now supports tokenizer_kwargs. For example try:
>>> from transformers import pipeline >>> fill_masker = pipeline(model="google-bert/bert-base-uncased") >>> tokenizer_kwargs = {"truncation": True} >>> fill_masker( ... "This is a simple [MASK]. " + "...with a large amount of repeated text appended. " * 100, ... tokenizer_kwargs=tokenizer_kwargs, ... )__call__ < source >
( inputs **kwargs ) → A list or a list of list of dict
Parameters
str
or List[str]
) — One or several texts (or one list of prompts) with masked tokens. str
or List[str]
, optional) — When passed, the model will limit the scores to the passed targets instead of looking up in the whole vocab. If the provided targets are not in the model vocab, they will be tokenized and the first resulting token will be used (with a warning, and that might be slower). int
, optional) — When passed, overrides the number of predictions to return. Returns
A list or a list of list of dict
Each result comes as list of dictionaries with the following keys:
str
) — The corresponding input with the mask token prediction.float
) — The corresponding probability.int
) — The predicted token id (to replace the masked one).str
) — The predicted token (to replace the masked one).Fill the masked token in the text(s) given as inputs.
QuestionAnsweringPipeline class transformers.QuestionAnsweringPipeline < source >( model: typing.Union[ForwardRef('PreTrainedModel'), ForwardRef('TFPreTrainedModel')] tokenizer: PreTrainedTokenizer modelcard: typing.Optional[transformers.modelcard.ModelCard] = None framework: typing.Optional[str] = None task: str = '' **kwargs )
Parameters
str
or ModelCard
, optional) — Model card attributed to the model for this pipeline. str
, optional) — The framework to use, either "pt"
for PyTorch or "tf"
for TensorFlow. The specified framework must be installed.
If no framework is specified, will default to the one currently installed. If no framework is specified and both frameworks are installed, will default to the framework of the model
, or to PyTorch if no model is provided.
str
, defaults to ""
) — A task-identifier for the pipeline. int
, optional, defaults to 8) — When the pipeline will use DataLoader (when passing a dataset, on GPU for a Pytorch model), the number of workers to be used. int
, optional, defaults to 1) — When the pipeline will use DataLoader (when passing a dataset, on GPU for a Pytorch model), the size of the batch to use, for inference this is not always beneficial, please read Batching with pipelines . int
, optional, defaults to -1) — Device ordinal for CPU/GPU supports. Setting this to -1 will leverage CPU, a positive will run the model on the associated CUDA device id. You can pass native torch.device
or a str
too str
or torch.dtype
, optional) — Sent directly as model_kwargs
(just a simpler shortcut) to use the available precision for this model (torch.float16
, torch.bfloat16
, … or "auto"
) bool
, optional, defaults to False
) — Flag indicating if the output the pipeline should happen in a serialized format (i.e., pickle) or as the raw output data e.g. text. Question Answering pipeline using any ModelForQuestionAnswering
. See the question answering examples for more information.
Example:
>>> from transformers import pipeline >>> oracle = pipeline(model="deepset/roberta-base-squad2") >>> oracle(question="Where do I live?", context="My name is Wolfgang and I live in Berlin") {'score': 0.9191, 'start': 34, 'end': 40, 'answer': 'Berlin'}
Learn more about the basics of using a pipeline in the pipeline tutorial
This question answering pipeline can currently be loaded from pipeline() using the following task identifier: "question-answering"
.
The models that this pipeline can use are models that have been fine-tuned on a question answering task. See the up-to-date list of available models on huggingface.co/models.
__call__ < source >( *args **kwargs ) → A dict
or a list of dict
Parameters
str
or List[str]
) — One or several question(s) (must be used in conjunction with the context
argument). str
or List[str]
) — One or several context(s) associated with the question(s) (must be used in conjunction with the question
argument). int
, optional, defaults to 1) — The number of answers to return (will be chosen by order of likelihood). Note that we return less than top_k answers if there are not enough options available within the context. int
, optional, defaults to 128) — If the context is too long to fit with the question for the model, it will be split in several chunks with some overlap. This argument controls the size of that overlap. int
, optional, defaults to 15) — The maximum length of predicted answers (e.g., only answers with a shorter length are considered). int
, optional, defaults to 384) — The maximum length of the total sentence (context + question) in tokens of each chunk passed to the model. The context will be split in several chunks (using doc_stride
as overlap) if needed. int
, optional, defaults to 64) — The maximum length of the question after tokenization. It will be truncated if needed. bool
, optional, defaults to False
) — Whether or not we accept impossible as an answer. bool
, optional, defaults to True
) — Attempts to align the answer to real words. Improves quality on space separated languages. Might hurt on non-space-separated languages (like Japanese or Chinese) Returns
A dict
or a list of dict
Each result comes as a dictionary with the following keys:
float
) — The probability associated to the answer.int
) — The character start index of the answer (in the tokenized version of the input).int
) — The character end index of the answer (in the tokenized version of the input).str
) — The answer to the question.Answer the question(s) given as inputs by using the context(s).
create_sample < source >( question: typing.Union[str, typing.List[str]] context: typing.Union[str, typing.List[str]] ) → One or a list of SquadExample
Parameters
str
or List[str]
) — The question(s) asked. str
or List[str]
) — The context(s) in which we will look for the answer. Returns
One or a list of SquadExample
The corresponding SquadExample
grouping question and context.
QuestionAnsweringPipeline leverages the SquadExample
internally. This helper method encapsulate all the logic for converting question(s) and context(s) to SquadExample
.
We currently support extractive question answering.
span_to_answer < source >( text: str start: int end: int ) → Dictionary like `{‘answer’
Parameters
str
) — The actual context to extract the answer from. int
) — The answer starting token index. int
) — The answer end token index. Returns
Dictionary like `{‘answer’
str, ‘start’: int, ‘end’: int}`
When decoding from token probabilities, this method maps token indexes to actual word in the initial context.
SummarizationPipeline class transformers.SummarizationPipeline < source >( *args **kwargs )
Parameters
str
or ModelCard
, optional) — Model card attributed to the model for this pipeline. str
, optional) — The framework to use, either "pt"
for PyTorch or "tf"
for TensorFlow. The specified framework must be installed.
If no framework is specified, will default to the one currently installed. If no framework is specified and both frameworks are installed, will default to the framework of the model
, or to PyTorch if no model is provided.
str
, defaults to ""
) — A task-identifier for the pipeline. int
, optional, defaults to 8) — When the pipeline will use DataLoader (when passing a dataset, on GPU for a Pytorch model), the number of workers to be used. int
, optional, defaults to 1) — When the pipeline will use DataLoader (when passing a dataset, on GPU for a Pytorch model), the size of the batch to use, for inference this is not always beneficial, please read Batching with pipelines . int
, optional, defaults to -1) — Device ordinal for CPU/GPU supports. Setting this to -1 will leverage CPU, a positive will run the model on the associated CUDA device id. You can pass native torch.device
or a str
too str
or torch.dtype
, optional) — Sent directly as model_kwargs
(just a simpler shortcut) to use the available precision for this model (torch.float16
, torch.bfloat16
, … or "auto"
) bool
, optional, defaults to False
) — Flag indicating if the output the pipeline should happen in a serialized format (i.e., pickle) or as the raw output data e.g. text. Summarize news articles and other documents.
This summarizing pipeline can currently be loaded from pipeline() using the following task identifier: "summarization"
.
The models that this pipeline can use are models that have been fine-tuned on a summarization task, which is currently, ’bart-large-cnn’, ’google-t5/t5-small’, ’google-t5/t5-base’, ’google-t5/t5-large’, ’google-t5/t5-3b’, ’google-t5/t5-11b’. See the up-to-date list of available models on huggingface.co/models. For a list of available parameters, see the following documentation
Usage:
summarizer = pipeline("summarization") summarizer("An apple a day, keeps the doctor away", min_length=5, max_length=20) summarizer = pipeline("summarization", model="google-t5/t5-base", tokenizer="google-t5/t5-base", framework="tf") summarizer("An apple a day, keeps the doctor away", min_length=5, max_length=20)__call__ < source >
( *args **kwargs ) → A list or a list of list of dict
Parameters
List[str]
) — One or several articles (or one list of articles) to summarize. bool
, optional, defaults to True
) — Whether or not to include the decoded texts in the outputs bool
, optional, defaults to False
) — Whether or not to include the tensors of predictions (as token indices) in the outputs. bool
, optional, defaults to False
) — Whether or not to clean up the potential extra spaces in the text output. Returns
A list or a list of list of dict
Each result comes as a dictionary with the following keys:
str
, present when return_text=True
) — The summary of the corresponding input.torch.Tensor
or tf.Tensor
, present when return_tensors=True
) — The token ids of the summary.Summarize the text(s) given as inputs.
TableQuestionAnsweringPipeline class transformers.TableQuestionAnsweringPipeline < source >( args_parser = <transformers.pipelines.table_question_answering.TableQuestionAnsweringArgumentHandler object at 0x7fc275fd9b40> *args **kwargs )
Parameters
str
or ModelCard
, optional) — Model card attributed to the model for this pipeline. str
, optional) — The framework to use, either "pt"
for PyTorch or "tf"
for TensorFlow. The specified framework must be installed.
If no framework is specified, will default to the one currently installed. If no framework is specified and both frameworks are installed, will default to the framework of the model
, or to PyTorch if no model is provided.
str
, defaults to ""
) — A task-identifier for the pipeline. int
, optional, defaults to 8) — When the pipeline will use DataLoader (when passing a dataset, on GPU for a Pytorch model), the number of workers to be used. int
, optional, defaults to 1) — When the pipeline will use DataLoader (when passing a dataset, on GPU for a Pytorch model), the size of the batch to use, for inference this is not always beneficial, please read Batching with pipelines . int
, optional, defaults to -1) — Device ordinal for CPU/GPU supports. Setting this to -1 will leverage CPU, a positive will run the model on the associated CUDA device id. You can pass native torch.device
or a str
too str
or torch.dtype
, optional) — Sent directly as model_kwargs
(just a simpler shortcut) to use the available precision for this model (torch.float16
, torch.bfloat16
, … or "auto"
) bool
, optional, defaults to False
) — Flag indicating if the output the pipeline should happen in a serialized format (i.e., pickle) or as the raw output data e.g. text. Table Question Answering pipeline using a ModelForTableQuestionAnswering
. This pipeline is only available in PyTorch.
Example:
>>> from transformers import pipeline >>> oracle = pipeline(model="google/tapas-base-finetuned-wtq") >>> table = { ... "Repository": ["Transformers", "Datasets", "Tokenizers"], ... "Stars": ["36542", "4512", "3934"], ... "Contributors": ["651", "77", "34"], ... "Programming language": ["Python", "Python", "Rust, Python and NodeJS"], ... } >>> oracle(query="How many stars does the transformers repository have?", table=table) {'answer': 'AVERAGE > 36542', 'coordinates': [(0, 1)], 'cells': ['36542'], 'aggregator': 'AVERAGE'}
Learn more about the basics of using a pipeline in the pipeline tutorial
This tabular question answering pipeline can currently be loaded from pipeline() using the following task identifier: "table-question-answering"
.
The models that this pipeline can use are models that have been fine-tuned on a tabular question answering task. See the up-to-date list of available models on huggingface.co/models.
__call__ < source >( *args **kwargs ) → A dictionary or a list of dictionaries containing results
Parameters
pd.DataFrame
or Dict
) — Pandas DataFrame or dictionary that will be converted to a DataFrame containing all the table values. See above for an example of dictionary. str
or List[str]
) — Query or list of queries that will be sent to the model alongside the table. bool
, optional, defaults to False
) — Whether to do inference sequentially or as a batch. Batching is faster, but models like SQA require the inference to be done sequentially to extract relations within sequences, given their conversational nature. bool
, str
or PaddingStrategy, optional, defaults to False
) — Activates and controls padding. Accepts the following values:
True
or 'longest'
: Pad to the longest sequence in the batch (or no padding if only a single sequence if provided).'max_length'
: Pad to a maximum length specified with the argument max_length
or to the maximum acceptable input length for the model if that argument is not provided.False
or 'do_not_pad'
(default): No padding (i.e., can output a batch with sequences of different lengths).bool
, str
or TapasTruncationStrategy
, optional, defaults to False
) — Activates and controls truncation. Accepts the following values:
True
or 'drop_rows_to_fit'
: Truncate to a maximum length specified with the argument max_length
or to the maximum acceptable input length for the model if that argument is not provided. This will truncate row by row, removing rows from the table.False
or 'do_not_truncate'
(default): No truncation (i.e., can output batch with sequence lengths greater than the model maximum admissible input size).Returns
A dictionary or a list of dictionaries containing results
Each result is a dictionary with the following keys:
str
) — The answer of the query given the table. If there is an aggregator, the answer will be preceded by AGGREGATOR >
.List[Tuple[int, int]]
) — Coordinates of the cells of the answers.List[str]
) — List of strings made up of the answer cell values.str
) — If the model has an aggregator, this returns the aggregator.Answers queries according to a table. The pipeline accepts several types of inputs which are detailed below:
pipeline(table, query)
pipeline(table, [query])
pipeline(table=table, query=query)
pipeline(table=table, query=[query])
pipeline({"table": table, "query": query})
pipeline({"table": table, "query": [query]})
pipeline([{"table": table, "query": query}, {"table": table, "query": query}])
The table
argument should be a dict or a DataFrame built from that dict, containing the whole table:
Example:
data = { "actors": ["brad pitt", "leonardo di caprio", "george clooney"], "age": ["56", "45", "59"], "number of movies": ["87", "53", "69"], "date of birth": ["7 february 1967", "10 june 1996", "28 november 1967"], }
This dictionary can be passed in as such, or can be converted to a pandas DataFrame:
Example:
import pandas as pd table = pd.DataFrame.from_dict(data)TextClassificationPipeline class transformers.TextClassificationPipeline < source >
( **kwargs )
Parameters
str
or ModelCard
, optional) — Model card attributed to the model for this pipeline. str
, optional) — The framework to use, either "pt"
for PyTorch or "tf"
for TensorFlow. The specified framework must be installed.
If no framework is specified, will default to the one currently installed. If no framework is specified and both frameworks are installed, will default to the framework of the model
, or to PyTorch if no model is provided.
str
, defaults to ""
) — A task-identifier for the pipeline. int
, optional, defaults to 8) — When the pipeline will use DataLoader (when passing a dataset, on GPU for a Pytorch model), the number of workers to be used. int
, optional, defaults to 1) — When the pipeline will use DataLoader (when passing a dataset, on GPU for a Pytorch model), the size of the batch to use, for inference this is not always beneficial, please read Batching with pipelines . int
, optional, defaults to -1) — Device ordinal for CPU/GPU supports. Setting this to -1 will leverage CPU, a positive will run the model on the associated CUDA device id. You can pass native torch.device
or a str
too str
or torch.dtype
, optional) — Sent directly as model_kwargs
(just a simpler shortcut) to use the available precision for this model (torch.float16
, torch.bfloat16
, … or "auto"
) bool
, optional, defaults to False
) — Flag indicating if the output the pipeline should happen in a serialized format (i.e., pickle) or as the raw output data e.g. text. bool
, optional, defaults to False
) — Whether to return all prediction scores or just the one of the predicted class. str
, optional, defaults to "default"
) — The function to apply to the model outputs in order to retrieve the scores. Accepts four different values:
"default"
: if the model has a single label, will apply the sigmoid function on the output. If the model has several labels, will apply the softmax function on the output. In case of regression tasks, will not apply any function on the output."sigmoid"
: Applies the sigmoid function on the output."softmax"
: Applies the softmax function on the output."none"
: Does not apply any function on the output.Text classification pipeline using any ModelForSequenceClassification
. See the sequence classification examples for more information.
Example:
>>> from transformers import pipeline >>> classifier = pipeline(model="distilbert/distilbert-base-uncased-finetuned-sst-2-english") >>> classifier("This movie is disgustingly good !") [{'label': 'POSITIVE', 'score': 1.0}] >>> classifier("Director tried too much.") [{'label': 'NEGATIVE', 'score': 0.996}]
Learn more about the basics of using a pipeline in the pipeline tutorial
This text classification pipeline can currently be loaded from pipeline() using the following task identifier: "sentiment-analysis"
(for classifying sequences according to positive or negative sentiments).
If multiple classification labels are available (model.config.num_labels >= 2
), the pipeline will run a softmax over the results. If there is a single label, the pipeline will run a sigmoid over the result. In case of regression tasks (model.config.problem_type == "regression"
), will not apply any function on the output.
The models that this pipeline can use are models that have been fine-tuned on a sequence classification task. See the up-to-date list of available models on huggingface.co/models.
__call__ < source >( inputs **kwargs ) → A list or a list of list of dict
Parameters
str
or List[str]
or Dict[str]
, or List[Dict[str]]
) — One or several texts to classify. In order to use text pairs for your classification, you can send a dictionary containing {"text", "text_pair"}
keys, or a list of those. int
, optional, defaults to 1
) — How many results to return. str
, optional, defaults to "default"
) — The function to apply to the model outputs in order to retrieve the scores. Accepts four different values:
If this argument is not specified, then it will apply the following functions according to the number of labels:
Possible values are:
"sigmoid"
: Applies the sigmoid function on the output."softmax"
: Applies the softmax function on the output."none"
: Does not apply any function on the output.Returns
A list or a list of list of dict
Each result comes as list of dictionaries with the following keys:
str
) — The label predicted.float
) — The corresponding probability.If top_k
is used, one such dictionary is returned per label.
Classify the text(s) given as inputs.
TextGenerationPipeline class transformers.TextGenerationPipeline < source >( *args **kwargs )
Parameters
str
or ModelCard
, optional) — Model card attributed to the model for this pipeline. str
, optional) — The framework to use, either "pt"
for PyTorch or "tf"
for TensorFlow. The specified framework must be installed.
If no framework is specified, will default to the one currently installed. If no framework is specified and both frameworks are installed, will default to the framework of the model
, or to PyTorch if no model is provided.
str
, defaults to ""
) — A task-identifier for the pipeline. int
, optional, defaults to 8) — When the pipeline will use DataLoader (when passing a dataset, on GPU for a Pytorch model), the number of workers to be used. int
, optional, defaults to 1) — When the pipeline will use DataLoader (when passing a dataset, on GPU for a Pytorch model), the size of the batch to use, for inference this is not always beneficial, please read Batching with pipelines . int
, optional, defaults to -1) — Device ordinal for CPU/GPU supports. Setting this to -1 will leverage CPU, a positive will run the model on the associated CUDA device id. You can pass native torch.device
or a str
too str
or torch.dtype
, optional) — Sent directly as model_kwargs
(just a simpler shortcut) to use the available precision for this model (torch.float16
, torch.bfloat16
, … or "auto"
) bool
, optional, defaults to False
) — Flag indicating if the output the pipeline should happen in a serialized format (i.e., pickle) or as the raw output data e.g. text. Language generation pipeline using any ModelWithLMHead
. This pipeline predicts the words that will follow a specified text prompt. When the underlying model is a conversational model, it can also accept one or more chats, in which case the pipeline will operate in chat mode and will continue the chat(s) by adding its response(s). Each chat takes the form of a list of dicts, where each dict contains “role” and “content” keys.
Examples:
>>> from transformers import pipeline >>> generator = pipeline(model="openai-community/gpt2") >>> generator("I can't believe you did such a ", do_sample=False) [{'generated_text': "I can't believe you did such a icky thing to me. I'm so sorry. I'm so sorry. I'm so sorry. I'm so sorry. I'm so sorry. I'm so sorry. I'm so sorry. I"}] >>> >>> outputs = generator("My tart needs some", num_return_sequences=4, return_full_text=False)
>>> from transformers import pipeline >>> generator = pipeline(model="HuggingFaceH4/zephyr-7b-beta") >>> >>> generator([{"role": "user", "content": "What is the capital of France? Answer in one word."}], do_sample=False, max_new_tokens=2) [{'generated_text': [{'role': 'user', 'content': 'What is the capital of France? Answer in one word.'}, {'role': 'assistant', 'content': 'Paris'}]}]
Learn more about the basics of using a pipeline in the pipeline tutorial. You can pass text generation parameters to this pipeline to control stopping criteria, decoding strategy, and more. Learn more about text generation parameters in Text generation strategies and Text generation.
This language generation pipeline can currently be loaded from pipeline() using the following task identifier: "text-generation"
.
The models that this pipeline can use are models that have been trained with an autoregressive language modeling objective. See the list of available text completion models and the list of conversational models on [huggingface.co/models].
__call__ < source >( text_inputs **kwargs ) → A list or a list of lists of dict
Parameters
str
, List[str]
, List[Dict[str, str]], or List[List[Dict[str, str]]]
) — One or several prompts (or one list of prompts) to complete. If strings or a list of string are passed, this pipeline will continue each prompt. Alternatively, a “chat”, in the form of a list of dicts with “role” and “content” keys, can be passed, or a list of such chats. When chats are passed, the model’s chat template will be used to format them before passing them to the model. bool
, optional, defaults to False
) — Returns the tensors of predictions (as token indices) in the outputs. If set to True
, the decoded text is not returned. bool
, optional) — Returns the decoded texts in the outputs. bool
, optional, defaults to True
) — If set to False
only added text is returned, otherwise the full text is returned. Cannot be specified at the same time as return_text
. bool
, optional, defaults to True
) — Whether or not to clean up the potential extra spaces in the text output. bool
, optional) — This indicates that you want the model to continue the last message in the input chat rather than starting a new one, allowing you to “prefill” its response. By default this is True
when the final message in the input chat has the assistant
role and False
otherwise, but you can manually override that behaviour by setting this flag. str
, optional) — Prefix added to prompt. str
, optional) — By default, this pipelines does not handle long generation (ones that exceed in one form or the other the model maximum length). There is no perfect way to address this (more info :https://github.com/huggingface/transformers/issues/14033#issuecomment-948385227). This provides common strategies to work around that problem depending on your use case.
None
: default strategy where nothing in particular happens"hole"
: Truncates left of input, and leaves a gap wide enough to let generation happen (might truncate a lot of the prompt and not suitable when generation exceed the model capacity)dict
, optional) — Additional keyword arguments to pass along to the generate method of the model (see the generate method corresponding to your framework here). Returns
A list or a list of lists of dict
Returns one of the following dictionaries (cannot return a combination of both generated_text
and generated_token_ids
):
str
, present when return_text=True
) — The generated text.torch.Tensor
or tf.Tensor
, present when return_tensors=True
) — The token ids of the generated text.Complete the prompt(s) given as inputs.
Text2TextGenerationPipeline class transformers.Text2TextGenerationPipeline < source >( *args **kwargs )
Parameters
str
or ModelCard
, optional) — Model card attributed to the model for this pipeline. str
, optional) — The framework to use, either "pt"
for PyTorch or "tf"
for TensorFlow. The specified framework must be installed.
If no framework is specified, will default to the one currently installed. If no framework is specified and both frameworks are installed, will default to the framework of the model
, or to PyTorch if no model is provided.
str
, defaults to ""
) — A task-identifier for the pipeline. int
, optional, defaults to 8) — When the pipeline will use DataLoader (when passing a dataset, on GPU for a Pytorch model), the number of workers to be used. int
, optional, defaults to 1) — When the pipeline will use DataLoader (when passing a dataset, on GPU for a Pytorch model), the size of the batch to use, for inference this is not always beneficial, please read Batching with pipelines . int
, optional, defaults to -1) — Device ordinal for CPU/GPU supports. Setting this to -1 will leverage CPU, a positive will run the model on the associated CUDA device id. You can pass native torch.device
or a str
too str
or torch.dtype
, optional) — Sent directly as model_kwargs
(just a simpler shortcut) to use the available precision for this model (torch.float16
, torch.bfloat16
, … or "auto"
) bool
, optional, defaults to False
) — Flag indicating if the output the pipeline should happen in a serialized format (i.e., pickle) or as the raw output data e.g. text. Pipeline for text to text generation using seq2seq models.
Example:
>>> from transformers import pipeline >>> generator = pipeline(model="mrm8488/t5-base-finetuned-question-generation-ap") >>> generator( ... "answer: Manuel context: Manuel has created RuPERTa-base with the support of HF-Transformers and Google" ... ) [{'generated_text': 'question: Who created the RuPERTa-base?'}]
Learn more about the basics of using a pipeline in the pipeline tutorial. You can pass text generation parameters to this pipeline to control stopping criteria, decoding strategy, and more. Learn more about text generation parameters in Text generation strategies and Text generation.
This Text2TextGenerationPipeline pipeline can currently be loaded from pipeline() using the following task identifier: "text2text-generation"
.
The models that this pipeline can use are models that have been fine-tuned on a translation task. See the up-to-date list of available models on huggingface.co/models. For a list of available parameters, see the following documentation
Usage:
text2text_generator = pipeline("text2text-generation") text2text_generator("question: What is 42 ? context: 42 is the answer to life, the universe and everything")__call__ < source >
( *args **kwargs ) → A list or a list of list of dict
Parameters
str
or List[str]
) — Input text for the encoder. bool
, optional, defaults to False
) — Whether or not to include the tensors of predictions (as token indices) in the outputs. bool
, optional, defaults to True
) — Whether or not to include the decoded texts in the outputs. bool
, optional, defaults to False
) — Whether or not to clean up the potential extra spaces in the text output. TruncationStrategy
, optional, defaults to TruncationStrategy.DO_NOT_TRUNCATE
) — The truncation strategy for the tokenization within the pipeline. TruncationStrategy.DO_NOT_TRUNCATE
(default) will never truncate, but it is sometimes desirable to truncate the input to fit the model’s max_length instead of throwing an error down the line. Returns
A list or a list of list of dict
Each result comes as a dictionary with the following keys:
str
, present when return_text=True
) — The generated text.torch.Tensor
or tf.Tensor
, present when return_tensors=True
) — The token ids of the generated text.Generate the output text(s) using text(s) given as inputs.
check_inputs < source >( input_length: int min_length: int max_length: int )
Checks whether there might be something wrong with given input with regard to the model.
TokenClassificationPipeline class transformers.TokenClassificationPipeline < source >( args_parser = <transformers.pipelines.token_classification.TokenClassificationArgumentHandler object at 0x7fc275f06b00> *args **kwargs )
Parameters
str
or ModelCard
, optional) — Model card attributed to the model for this pipeline. str
, optional) — The framework to use, either "pt"
for PyTorch or "tf"
for TensorFlow. The specified framework must be installed.
If no framework is specified, will default to the one currently installed. If no framework is specified and both frameworks are installed, will default to the framework of the model
, or to PyTorch if no model is provided.
str
, defaults to ""
) — A task-identifier for the pipeline. int
, optional, defaults to 8) — When the pipeline will use DataLoader (when passing a dataset, on GPU for a Pytorch model), the number of workers to be used. int
, optional, defaults to 1) — When the pipeline will use DataLoader (when passing a dataset, on GPU for a Pytorch model), the size of the batch to use, for inference this is not always beneficial, please read Batching with pipelines . int
, optional, defaults to -1) — Device ordinal for CPU/GPU supports. Setting this to -1 will leverage CPU, a positive will run the model on the associated CUDA device id. You can pass native torch.device
or a str
too str
or torch.dtype
, optional) — Sent directly as model_kwargs
(just a simpler shortcut) to use the available precision for this model (torch.float16
, torch.bfloat16
, … or "auto"
) bool
, optional, defaults to False
) — Flag indicating if the output the pipeline should happen in a serialized format (i.e., pickle) or as the raw output data e.g. text. List[str]
, defaults to ["O"]
) — A list of labels to ignore. bool
, optional, defaults to False
) — DEPRECATED, use aggregation_strategy
instead. Whether or not to group the tokens corresponding to the same entity together in the predictions or not. int
, optional) — If stride is provided, the pipeline is applied on all the text. The text is split into chunks of size model_max_length. Works only with fast tokenizers and aggregation_strategy
different from NONE
. The value of this argument defines the number of overlapping tokens between chunks. In other words, the model will shift forward by tokenizer.model_max_length - stride
tokens each step. str
, optional, defaults to "none"
) — The strategy to fuse (or not) tokens based on the model prediction.
SIMPLE
strategy except that words, cannot end up with different tags. Words will simply use the tag of the first token of the word when there is ambiguity.SIMPLE
strategy except that words, cannot end up with different tags. scores will be averaged first across tokens, and then the maximum label is applied.SIMPLE
strategy except that words, cannot end up with different tags. Word entity will simply be the token with the maximum score.Named Entity Recognition pipeline using any ModelForTokenClassification
. See the named entity recognition examples for more information.
Example:
>>> from transformers import pipeline >>> token_classifier = pipeline(model="Jean-Baptiste/camembert-ner", aggregation_strategy="simple") >>> sentence = "Je m'appelle jean-baptiste et je vis à montréal" >>> tokens = token_classifier(sentence) >>> tokens [{'entity_group': 'PER', 'score': 0.9931, 'word': 'jean-baptiste', 'start': 12, 'end': 26}, {'entity_group': 'LOC', 'score': 0.998, 'word': 'montréal', 'start': 38, 'end': 47}] >>> token = tokens[0] >>> >>> sentence[token["start"] : token["end"]] ' jean-baptiste' >>> >>> syntaxer = pipeline(model="vblagoje/bert-english-uncased-finetuned-pos", aggregation_strategy="simple") >>> syntaxer("My name is Sarah and I live in London") [{'entity_group': 'PRON', 'score': 0.999, 'word': 'my', 'start': 0, 'end': 2}, {'entity_group': 'NOUN', 'score': 0.997, 'word': 'name', 'start': 3, 'end': 7}, {'entity_group': 'AUX', 'score': 0.994, 'word': 'is', 'start': 8, 'end': 10}, {'entity_group': 'PROPN', 'score': 0.999, 'word': 'sarah', 'start': 11, 'end': 16}, {'entity_group': 'CCONJ', 'score': 0.999, 'word': 'and', 'start': 17, 'end': 20}, {'entity_group': 'PRON', 'score': 0.999, 'word': 'i', 'start': 21, 'end': 22}, {'entity_group': 'VERB', 'score': 0.998, 'word': 'live', 'start': 23, 'end': 27}, {'entity_group': 'ADP', 'score': 0.999, 'word': 'in', 'start': 28, 'end': 30}, {'entity_group': 'PROPN', 'score': 0.999, 'word': 'london', 'start': 31, 'end': 37}]
Learn more about the basics of using a pipeline in the pipeline tutorial
This token recognition pipeline can currently be loaded from pipeline() using the following task identifier: "ner"
(for predicting the classes of tokens in a sequence: person, organisation, location or miscellaneous).
The models that this pipeline can use are models that have been fine-tuned on a token classification task. See the up-to-date list of available models on huggingface.co/models.
__call__ < source >( inputs: typing.Union[str, typing.List[str]] **kwargs ) → A list or a list of list of dict
Parameters
Returns
A list or a list of list of dict
Each result comes as a list of dictionaries (one for each token in the corresponding input, or each entity if this pipeline was instantiated with an aggregation_strategy) with the following keys:
str
) — The token/word classified. This is obtained by decoding the selected tokens. If you want to have the exact string in the original sentence, use start
and end
.float
) — The corresponding probability for entity
.str
) — The entity predicted for that token/word (it is named entity_group when aggregation_strategy is not "none"
.int
, only present when aggregation_strategy="none"
) — The index of the corresponding token in the sentence.int
, optional) — The index of the start of the corresponding entity in the sentence. Only exists if the offsets are available within the tokenizerint
, optional) — The index of the end of the corresponding entity in the sentence. Only exists if the offsets are available within the tokenizerClassify each token of the text(s) given as inputs.
aggregate_words < source >( entities: typing.List[dict] aggregation_strategy: AggregationStrategy )
Override tokens from a given word that disagree to force agreement on word boundaries.
Example: micro|soft| com|pany| B-ENT I-NAME I-ENT I-ENT will be rewritten with first strategy as microsoft| company| B-ENT I-ENT
gather_pre_entities < source >( sentence: str input_ids: ndarray scores: ndarray offset_mapping: typing.Optional[typing.List[typing.Tuple[int, int]]] special_tokens_mask: ndarray aggregation_strategy: AggregationStrategy )
Fuse various numpy arrays into dicts with all the information needed for aggregation
group_entities < source >( entities: typing.List[dict] )
Parameters
Find and group together the adjacent tokens with the same entity predicted.
group_sub_entities < source >( entities: typing.List[dict] )
Parameters
Group together the adjacent tokens with the same entity predicted.
TranslationPipeline class transformers.TranslationPipeline < source >( *args **kwargs )
Parameters
str
or ModelCard
, optional) — Model card attributed to the model for this pipeline. str
, optional) — The framework to use, either "pt"
for PyTorch or "tf"
for TensorFlow. The specified framework must be installed.
If no framework is specified, will default to the one currently installed. If no framework is specified and both frameworks are installed, will default to the framework of the model
, or to PyTorch if no model is provided.
str
, defaults to ""
) — A task-identifier for the pipeline. int
, optional, defaults to 8) — When the pipeline will use DataLoader (when passing a dataset, on GPU for a Pytorch model), the number of workers to be used. int
, optional, defaults to 1) — When the pipeline will use DataLoader (when passing a dataset, on GPU for a Pytorch model), the size of the batch to use, for inference this is not always beneficial, please read Batching with pipelines . int
, optional, defaults to -1) — Device ordinal for CPU/GPU supports. Setting this to -1 will leverage CPU, a positive will run the model on the associated CUDA device id. You can pass native torch.device
or a str
too str
or torch.dtype
, optional) — Sent directly as model_kwargs
(just a simpler shortcut) to use the available precision for this model (torch.float16
, torch.bfloat16
, … or "auto"
) bool
, optional, defaults to False
) — Flag indicating if the output the pipeline should happen in a serialized format (i.e., pickle) or as the raw output data e.g. text. Translates from one language to another.
This translation pipeline can currently be loaded from pipeline() using the following task identifier: "translation_xx_to_yy"
.
The models that this pipeline can use are models that have been fine-tuned on a translation task. See the up-to-date list of available models on huggingface.co/models. For a list of available parameters, see the following documentation
Usage:
en_fr_translator = pipeline("translation_en_to_fr") en_fr_translator("How old are you?")__call__ < source >
( *args **kwargs ) → A list or a list of list of dict
Parameters
str
or List[str]
) — Texts to be translated. bool
, optional, defaults to False
) — Whether or not to include the tensors of predictions (as token indices) in the outputs. bool
, optional, defaults to True
) — Whether or not to include the decoded texts in the outputs. bool
, optional, defaults to False
) — Whether or not to clean up the potential extra spaces in the text output. str
, optional) — The language of the input. Might be required for multilingual models. Will not have any effect for single pair translation models str
, optional) — The language of the desired output. Might be required for multilingual models. Will not have any effect for single pair translation models Returns
A list or a list of list of dict
Each result comes as a dictionary with the following keys:
str
, present when return_text=True
) — The translation.torch.Tensor
or tf.Tensor
, present when return_tensors=True
) — The token ids of the translation.Translate the text(s) given as inputs.
ZeroShotClassificationPipeline class transformers.ZeroShotClassificationPipeline < source >( args_parser = <transformers.pipelines.zero_shot_classification.ZeroShotClassificationArgumentHandler object at 0x7fc275f3c250> *args **kwargs )
Parameters
str
or ModelCard
, optional) — Model card attributed to the model for this pipeline. str
, optional) — The framework to use, either "pt"
for PyTorch or "tf"
for TensorFlow. The specified framework must be installed.
If no framework is specified, will default to the one currently installed. If no framework is specified and both frameworks are installed, will default to the framework of the model
, or to PyTorch if no model is provided.
str
, defaults to ""
) — A task-identifier for the pipeline. int
, optional, defaults to 8) — When the pipeline will use DataLoader (when passing a dataset, on GPU for a Pytorch model), the number of workers to be used. int
, optional, defaults to 1) — When the pipeline will use DataLoader (when passing a dataset, on GPU for a Pytorch model), the size of the batch to use, for inference this is not always beneficial, please read Batching with pipelines . int
, optional, defaults to -1) — Device ordinal for CPU/GPU supports. Setting this to -1 will leverage CPU, a positive will run the model on the associated CUDA device id. You can pass native torch.device
or a str
too str
or torch.dtype
, optional) — Sent directly as model_kwargs
(just a simpler shortcut) to use the available precision for this model (torch.float16
, torch.bfloat16
, … or "auto"
) bool
, optional, defaults to False
) — Flag indicating if the output the pipeline should happen in a serialized format (i.e., pickle) or as the raw output data e.g. text. NLI-based zero-shot classification pipeline using a ModelForSequenceClassification
trained on NLI (natural language inference) tasks. Equivalent of text-classification
pipelines, but these models don’t require a hardcoded number of potential classes, they can be chosen at runtime. It usually means it’s slower but it is much more flexible.
Any combination of sequences and labels can be passed and each combination will be posed as a premise/hypothesis pair and passed to the pretrained model. Then, the logit for entailment is taken as the logit for the candidate label being valid. Any NLI model can be used, but the id of the entailment label must be included in the model config’s :attr:~transformers.PretrainedConfig.label2id.
Example:
>>> from transformers import pipeline >>> oracle = pipeline(model="facebook/bart-large-mnli") >>> oracle( ... "I have a problem with my iphone that needs to be resolved asap!!", ... candidate_labels=["urgent", "not urgent", "phone", "tablet", "computer"], ... ) {'sequence': 'I have a problem with my iphone that needs to be resolved asap!!', 'labels': ['urgent', 'phone', 'computer', 'not urgent', 'tablet'], 'scores': [0.504, 0.479, 0.013, 0.003, 0.002]} >>> oracle( ... "I have a problem with my iphone that needs to be resolved asap!!", ... candidate_labels=["english", "german"], ... ) {'sequence': 'I have a problem with my iphone that needs to be resolved asap!!', 'labels': ['english', 'german'], 'scores': [0.814, 0.186]}
Learn more about the basics of using a pipeline in the pipeline tutorial
This NLI pipeline can currently be loaded from pipeline() using the following task identifier: "zero-shot-classification"
.
The models that this pipeline can use are models that have been fine-tuned on an NLI task. See the up-to-date list of available models on huggingface.co/models.
__call__ < source >( sequences: typing.Union[str, typing.List[str]] *args **kwargs ) → A dict
or a list of dict
Parameters
str
or List[str]
) — The sequence(s) to classify, will be truncated if the model input is too large. str
or List[str]
) — The set of possible class labels to classify each sequence into. Can be a single label, a string of comma-separated labels, or a list of labels. str
, optional, defaults to "This example is {}."
) — The template used to turn each label into an NLI-style hypothesis. This template must include a {} or similar syntax for the candidate label to be inserted into the template. For example, the default template is "This example is {}."
With the candidate label "sports"
, this would be fed into the model like "<cls> sequence to classify <sep> This example is sports . <sep>"
. The default template works well in many cases, but it may be worthwhile to experiment with different templates depending on the task setting. bool
, optional, defaults to False
) — Whether or not multiple candidate labels can be true. If False
, the scores are normalized such that the sum of the label likelihoods for each sequence is 1. If True
, the labels are considered independent and probabilities are normalized for each candidate by doing a softmax of the entailment score vs. the contradiction score. Returns
A dict
or a list of dict
Each result comes as a dictionary with the following keys:
str
) — The sequence for which this is the output.List[str]
) — The labels sorted by order of likelihood.List[float]
) — The probabilities for each of the labels.Classify the sequence(s) given as inputs. See the ZeroShotClassificationPipeline documentation for more information.
MultimodalPipelines available for multimodal tasks include the following.
DocumentQuestionAnsweringPipeline class transformers.DocumentQuestionAnsweringPipeline < source >( *args **kwargs )
Parameters
str
or ModelCard
, optional) — Model card attributed to the model for this pipeline. str
, optional) — The framework to use, either "pt"
for PyTorch or "tf"
for TensorFlow. The specified framework must be installed.
If no framework is specified, will default to the one currently installed. If no framework is specified and both frameworks are installed, will default to the framework of the model
, or to PyTorch if no model is provided.
str
, defaults to ""
) — A task-identifier for the pipeline. int
, optional, defaults to 8) — When the pipeline will use DataLoader (when passing a dataset, on GPU for a Pytorch model), the number of workers to be used. int
, optional, defaults to 1) — When the pipeline will use DataLoader (when passing a dataset, on GPU for a Pytorch model), the size of the batch to use, for inference this is not always beneficial, please read Batching with pipelines . int
, optional, defaults to -1) — Device ordinal for CPU/GPU supports. Setting this to -1 will leverage CPU, a positive will run the model on the associated CUDA device id. You can pass native torch.device
or a str
too str
or torch.dtype
, optional) — Sent directly as model_kwargs
(just a simpler shortcut) to use the available precision for this model (torch.float16
, torch.bfloat16
, … or "auto"
) bool
, optional, defaults to False
) — Flag indicating if the output the pipeline should happen in a serialized format (i.e., pickle) or as the raw output data e.g. text. Document Question Answering pipeline using any AutoModelForDocumentQuestionAnswering
. The inputs/outputs are similar to the (extractive) question answering pipeline; however, the pipeline takes an image (and optional OCR’d words/boxes) as input instead of text context.
Example:
>>> from transformers import pipeline >>> document_qa = pipeline(model="impira/layoutlm-document-qa") >>> document_qa( ... image="https://huggingface.co/spaces/impira/docquery/resolve/2359223c1837a7587402bda0f2643382a6eefeab/invoice.png", ... question="What is the invoice number?", ... ) [{'score': 0.425, 'answer': 'us-001', 'start': 16, 'end': 16}]
Learn more about the basics of using a pipeline in the pipeline tutorial
This document question answering pipeline can currently be loaded from pipeline() using the following task identifier: "document-question-answering"
.
The models that this pipeline can use are models that have been fine-tuned on a document question answering task. See the up-to-date list of available models on huggingface.co/models.
__call__ < source >( image: typing.Union[ForwardRef('Image.Image'), str] question: typing.Optional[str] = None word_boxes: typing.Tuple[str, typing.List[float]] = None **kwargs ) → A dict
or a list of dict
Parameters
str
or PIL.Image
) — The pipeline handles three types of images:
The pipeline accepts either a single image or a batch of images. If given a single image, it can be broadcasted to multiple questions.
str
) — A question to ask of the document. List[str, Tuple[float, float, float, float]]
, optional) — A list of words and bounding boxes (normalized 0->1000). If you provide this optional input, then the pipeline will use these words and boxes instead of running OCR on the image to derive them for models that need them (e.g. LayoutLM). This allows you to reuse OCR’d results across many invocations of the pipeline without having to re-run it each time. int
, optional, defaults to 1) — The number of answers to return (will be chosen by order of likelihood). Note that we return less than top_k answers if there are not enough options available within the context. int
, optional, defaults to 128) — If the words in the document are too long to fit with the question for the model, it will be split in several chunks with some overlap. This argument controls the size of that overlap. int
, optional, defaults to 15) — The maximum length of predicted answers (e.g., only answers with a shorter length are considered). int
, optional, defaults to 384) — The maximum length of the total sentence (context + question) in tokens of each chunk passed to the model. The context will be split in several chunks (using doc_stride
as overlap) if needed. int
, optional, defaults to 64) — The maximum length of the question after tokenization. It will be truncated if needed. bool
, optional, defaults to False
) — Whether or not we accept impossible as an answer. str
, optional) — Language to use while running OCR. Defaults to english. str
, optional) — Additional flags to pass to tesseract while running OCR. float
, optional, defaults to None) — The maximum time in seconds to wait for fetching images from the web. If None, no timeout is set and the call may block forever. Returns
A dict
or a list of dict
Each result comes as a dictionary with the following keys:
float
) — The probability associated to the answer.int
) — The start word index of the answer (in the OCR’d version of the input or provided word_boxes
).int
) — The end word index of the answer (in the OCR’d version of the input or provided word_boxes
).str
) — The answer to the question.list[int]
) — The index of each word/box pair that is in the answerAnswer the question(s) given as inputs by using the document(s). A document is defined as an image and an optional list of (word, box) tuples which represent the text in the document. If the word_boxes
are not provided, it will use the Tesseract OCR engine (if available) to extract the words and boxes automatically for LayoutLM-like models which require them as input. For Donut, no OCR is run.
You can invoke the pipeline several ways:
pipeline(image=image, question=question)
pipeline(image=image, question=question, word_boxes=word_boxes)
pipeline([{"image": image, "question": question}])
pipeline([{"image": image, "question": question, "word_boxes": word_boxes}])
( model: typing.Union[ForwardRef('PreTrainedModel'), ForwardRef('TFPreTrainedModel')] tokenizer: typing.Optional[transformers.tokenization_utils.PreTrainedTokenizer] = None feature_extractor: typing.Optional[ForwardRef('SequenceFeatureExtractor')] = None image_processor: typing.Optional[transformers.image_processing_utils.BaseImageProcessor] = None processor: typing.Optional[transformers.processing_utils.ProcessorMixin] = None modelcard: typing.Optional[transformers.modelcard.ModelCard] = None framework: typing.Optional[str] = None task: str = '' args_parser: ArgumentHandler = None device: typing.Union[int, ForwardRef('torch.device')] = None torch_dtype: typing.Union[str, ForwardRef('torch.dtype'), NoneType] = None binary_output: bool = False **kwargs )
Parameters
str
or ModelCard
, optional) — Model card attributed to the model for this pipeline. str
, optional) — The framework to use, either "pt"
for PyTorch or "tf"
for TensorFlow. The specified framework must be installed.
If no framework is specified, will default to the one currently installed. If no framework is specified and both frameworks are installed, will default to the framework of the model
, or to PyTorch if no model is provided.
str
, defaults to ""
) — A task-identifier for the pipeline. int
, optional, defaults to 8) — When the pipeline will use DataLoader (when passing a dataset, on GPU for a Pytorch model), the number of workers to be used. int
, optional, defaults to 1) — When the pipeline will use DataLoader (when passing a dataset, on GPU for a Pytorch model), the size of the batch to use, for inference this is not always beneficial, please read Batching with pipelines . int
, optional, defaults to -1) — Device ordinal for CPU/GPU supports. Setting this to -1 will leverage CPU, a positive will run the model on the associated CUDA device id. You can pass native torch.device
or a str
too str
or torch.dtype
, optional) — Sent directly as model_kwargs
(just a simpler shortcut) to use the available precision for this model (torch.float16
, torch.bfloat16
, … or "auto"
) dict
, optional) — Additional dictionary of keyword arguments passed along to the tokenizer. bool
, optional) — If True
, returns a tensor according to the specified framework, otherwise returns a list. Feature extraction pipeline uses no model head. This pipeline extracts the hidden states from the base transformer, which can be used as features in downstream tasks.
Example:
>>> from transformers import pipeline >>> extractor = pipeline(model="google-bert/bert-base-uncased", task="feature-extraction") >>> result = extractor("This is a simple test.", return_tensors=True) >>> result.shape torch.Size([1, 8, 768])
Learn more about the basics of using a pipeline in the pipeline tutorial
This feature extraction pipeline can currently be loaded from pipeline() using the task identifier: "feature-extraction"
.
All models may be used for this pipeline. See a list of all models, including community-contributed models on huggingface.co/models.
( *args **kwargs ) → A nested list of float
Parameters
The features computed by the model.
Extract the features of the input(s).
ImageFeatureExtractionPipeline( model: typing.Union[ForwardRef('PreTrainedModel'), ForwardRef('TFPreTrainedModel')] tokenizer: typing.Optional[transformers.tokenization_utils.PreTrainedTokenizer] = None feature_extractor: typing.Optional[ForwardRef('SequenceFeatureExtractor')] = None image_processor: typing.Optional[transformers.image_processing_utils.BaseImageProcessor] = None processor: typing.Optional[transformers.processing_utils.ProcessorMixin] = None modelcard: typing.Optional[transformers.modelcard.ModelCard] = None framework: typing.Optional[str] = None task: str = '' args_parser: ArgumentHandler = None device: typing.Union[int, ForwardRef('torch.device')] = None torch_dtype: typing.Union[str, ForwardRef('torch.dtype'), NoneType] = None binary_output: bool = False **kwargs )
Parameters
str
or ModelCard
, optional) — Model card attributed to the model for this pipeline. str
, optional) — The framework to use, either "pt"
for PyTorch or "tf"
for TensorFlow. The specified framework must be installed.
If no framework is specified, will default to the one currently installed. If no framework is specified and both frameworks are installed, will default to the framework of the model
, or to PyTorch if no model is provided.
str
, defaults to ""
) — A task-identifier for the pipeline. int
, optional, defaults to 8) — When the pipeline will use DataLoader (when passing a dataset, on GPU for a Pytorch model), the number of workers to be used. int
, optional, defaults to 1) — When the pipeline will use DataLoader (when passing a dataset, on GPU for a Pytorch model), the size of the batch to use, for inference this is not always beneficial, please read Batching with pipelines . int
, optional, defaults to -1) — Device ordinal for CPU/GPU supports. Setting this to -1 will leverage CPU, a positive will run the model on the associated CUDA device id. You can pass native torch.device
or a str
too str
or torch.dtype
, optional) — Sent directly as model_kwargs
(just a simpler shortcut) to use the available precision for this model (torch.float16
, torch.bfloat16
, … or "auto"
) bool
, optional, defaults to False
) — Flag indicating if the output the pipeline should happen in a serialized format (i.e., pickle) or as the raw output data e.g. text. dict
, optional) — Additional dictionary of keyword arguments passed along to the image processor e.g. {“size”: {“height”: 100, “width”: 100}} bool
, optional, defaults to False
) — Whether or not to return the pooled output. If False
, the model will return the raw hidden states. Image feature extraction pipeline uses no model head. This pipeline extracts the hidden states from the base transformer, which can be used as features in downstream tasks.
Example:
>>> from transformers import pipeline >>> extractor = pipeline(model="google/vit-base-patch16-224", task="image-feature-extraction") >>> result = extractor("https://huggingface.co/datasets/Narsil/image_dummy/raw/main/parrots.png", return_tensors=True) >>> result.shape torch.Size([1, 197, 768])
Learn more about the basics of using a pipeline in the pipeline tutorial
This image feature extraction pipeline can currently be loaded from pipeline() using the task identifier: "image-feature-extraction"
.
All vision models may be used for this pipeline. See a list of all models, including community-contributed models on huggingface.co/models.
( *args **kwargs ) → A nested list of float
Parameters
str
, List[str]
, PIL.Image
or List[PIL.Image]
) — The pipeline handles three types of images:
The pipeline accepts either a single image or a batch of images, which must then be passed as a string. Images in a batch must all be in the same format: all as http links, all as local paths, or all as PIL images.
float
, optional, defaults to None) — The maximum time in seconds to wait for fetching images from the web. If None, no timeout is used and the call may block forever. The features computed by the model.
Extract the features of the input(s).
ImageToTextPipeline class transformers.ImageToTextPipeline < source >( *args **kwargs )
Parameters
str
or ModelCard
, optional) — Model card attributed to the model for this pipeline. str
, optional) — The framework to use, either "pt"
for PyTorch or "tf"
for TensorFlow. The specified framework must be installed.
If no framework is specified, will default to the one currently installed. If no framework is specified and both frameworks are installed, will default to the framework of the model
, or to PyTorch if no model is provided.
str
, defaults to ""
) — A task-identifier for the pipeline. int
, optional, defaults to 8) — When the pipeline will use DataLoader (when passing a dataset, on GPU for a Pytorch model), the number of workers to be used. int
, optional, defaults to 1) — When the pipeline will use DataLoader (when passing a dataset, on GPU for a Pytorch model), the size of the batch to use, for inference this is not always beneficial, please read Batching with pipelines . int
, optional, defaults to -1) — Device ordinal for CPU/GPU supports. Setting this to -1 will leverage CPU, a positive will run the model on the associated CUDA device id. You can pass native torch.device
or a str
too str
or torch.dtype
, optional) — Sent directly as model_kwargs
(just a simpler shortcut) to use the available precision for this model (torch.float16
, torch.bfloat16
, … or "auto"
) bool
, optional, defaults to False
) — Flag indicating if the output the pipeline should happen in a serialized format (i.e., pickle) or as the raw output data e.g. text. Image To Text pipeline using a AutoModelForVision2Seq
. This pipeline predicts a caption for a given image.
Example:
>>> from transformers import pipeline >>> captioner = pipeline(model="ydshieh/vit-gpt2-coco-en") >>> captioner("https://huggingface.co/datasets/Narsil/image_dummy/raw/main/parrots.png") [{'generated_text': 'two birds are standing next to each other '}]
Learn more about the basics of using a pipeline in the pipeline tutorial
This image to text pipeline can currently be loaded from pipeline() using the following task identifier: “image-to-text”.
See the list of available models on huggingface.co/models.
__call__ < source >( inputs: typing.Union[str, typing.List[str], ForwardRef('Image.Image'), typing.List[ForwardRef('Image.Image')]] = None **kwargs ) → A list or a list of list of dict
Parameters
str
, List[str]
, PIL.Image
or List[PIL.Image]
) — The pipeline handles three types of images:
The pipeline accepts either a single image or a batch of images.
int
, optional) — The amount of maximum tokens to generate. By default it will use generate
default. Dict
, optional) — Pass it to send all of these arguments directly to generate
allowing full control of this function. float
, optional, defaults to None) — The maximum time in seconds to wait for fetching images from the web. If None, no timeout is set and the call may block forever. Returns
A list or a list of list of dict
Each result comes as a dictionary with the following key:
str
) — The generated text.Assign labels to the image(s) passed as inputs.
ImageTextToTextPipeline class transformers.ImageTextToTextPipeline < source >( *args **kwargs )
Parameters
tokenizer
, feature_extractor
, and image_processor
. str
or ModelCard
, optional) — Model card attributed to the model for this pipeline. str
, optional) — The framework to use, either "pt"
for PyTorch or "tf"
for TensorFlow. The specified framework must be installed.
If no framework is specified, will default to the one currently installed. If no framework is specified and both frameworks are installed, will default to the framework of the model
, or to PyTorch if no model is provided.
str
, defaults to ""
) — A task-identifier for the pipeline. int
, optional, defaults to 8) — When the pipeline will use DataLoader (when passing a dataset, on GPU for a Pytorch model), the number of workers to be used. int
, optional, defaults to 1) — When the pipeline will use DataLoader (when passing a dataset, on GPU for a Pytorch model), the size of the batch to use, for inference this is not always beneficial, please read Batching with pipelines . int
, optional, defaults to -1) — Device ordinal for CPU/GPU supports. Setting this to -1 will leverage CPU, a positive will run the model on the associated CUDA device id. You can pass native torch.device
or a str
too str
or torch.dtype
, optional) — Sent directly as model_kwargs
(just a simpler shortcut) to use the available precision for this model (torch.float16
, torch.bfloat16
, … or "auto"
) bool
, optional, defaults to False
) — Flag indicating if the output the pipeline should happen in a serialized format (i.e., pickle) or as the raw output data e.g. text. Image-text-to-text pipeline using an AutoModelForImageTextToText
. This pipeline generates text given an image and text. When the underlying model is a conversational model, it can also accept one or more chats, in which case the pipeline will operate in chat mode and will continue the chat(s) by adding its response(s). Each chat takes the form of a list of dicts, where each dict contains “role” and “content” keys.
Example:
>>> from transformers import pipeline >>> pipe = pipeline(task="image-text-to-text", model="Salesforce/blip-image-captioning-base") >>> pipe("https://huggingface.co/datasets/Narsil/image_dummy/raw/main/parrots.png", text="A photo of") [{'generated_text': 'a photo of two birds'}]
>>> from transformers import pipeline >>> pipe = pipeline("image-text-to-text", model="llava-hf/llava-interleave-qwen-0.5b-hf") >>> messages = [ >>> { >>> "role": "user", >>> "content": [ >>> { >>> "type": "image", >>> "url": "https://qianwen-res.oss-cn-beijing.aliyuncs.com/Qwen-VL/assets/demo.jpeg", >>> }, >>> {"type": "text", "text": "Describe this image."}, >>> ], >>> }, >>> { >>> "role": "assistant", >>> "content": [ >>> {"type": "text", "text": "There is a dog and"}, >>> ], >>> }, >>> ] >>> pipe(text=messages, max_new_tokens=20, return_full_text=False) [{'input_text': [{'role': 'user', 'content': [{'type': 'image', 'url': 'https://qianwen-res.oss-cn-beijing.aliyuncs.com/Qwen-VL/assets/demo.jpeg'}, {'type': 'text', 'text': 'Describe this image.'}]}, {'role': 'assistant', 'content': [{'type': 'text', 'text': 'There is a dog and'}]}], 'generated_text': ' a person in the image. The dog is sitting on the sand, and the person is sitting on'}]
Learn more about the basics of using a pipeline in the pipeline tutorial
This image-text to text pipeline can currently be loaded from pipeline() using the following task identifier: “image-text-to-text”.
See the list of available models on huggingface.co/models.
__call__ < source >( images: typing.Union[str, typing.List[str], typing.List[typing.List[str]], ForwardRef('Image.Image'), typing.List[ForwardRef('Image.Image')], typing.List[typing.List[ForwardRef('Image.Image')]], NoneType] = None text: typing.Union[str, typing.List[str], typing.List[dict], NoneType] = None **kwargs ) → A list or a list of list of dict
Parameters
str
, List[str]
, PIL.Image or
List[PIL.Image]`) — The pipeline handles three types of images:
The pipeline accepts either a single image or a batch of images.
List[Dict[str, Union[str, PIL.Image]]]
) — The text to be used for generation. If a list of strings is passed, the length of the list should be the same as the number of images. Text can also follow the chat format: a list of dictionaries where each dictionary represents a message in a conversation. Each dictionary should have two keys: ‘role’ and ‘content’. ‘role’ should be one of ‘user’, ‘system’ or ‘assistant’. ‘content’ should be a list of dictionary containing the text of the message and the type of the message. The type of the message can be either ‘text’ or ‘image’. If the type is ‘image’, no text is needed. bool
, optional, defaults to False
) — Returns the tensors of predictions (as token indices) in the outputs. If set to True
, the decoded text is not returned. bool
, optional) — Returns the decoded texts in the outputs. bool
, optional, defaults to True
) — If set to False
only added text is returned, otherwise the full text is returned. Cannot be specified at the same time as return_text
. bool
, optional, defaults to True
) — Whether or not to clean up the potential extra spaces in the text output. bool
, optional) — This indicates that you want the model to continue the last message in the input chat rather than starting a new one, allowing you to “prefill” its response. By default this is True
when the final message in the input chat has the assistant
role and False
otherwise, but you can manually override that behaviour by setting this flag. Returns
A list or a list of list of dict
Each result comes as a dictionary with the following key (cannot return a combination of both generated_text
and generated_token_ids
):
str
, present when return_text=True
) — The generated text.torch.Tensor
, present when return_tensors=True
) — The token ids of the generated text.str
) — The input text.Generate a text given text and the image(s) passed as inputs.
MaskGenerationPipeline class transformers.MaskGenerationPipeline < source >( **kwargs )
Parameters
str
or ModelCard
, optional) — Model card attributed to the model for this pipeline. str
, optional) — The framework to use, either "pt"
for PyTorch or "tf"
for TensorFlow. The specified framework must be installed.
If no framework is specified, will default to the one currently installed. If no framework is specified and both frameworks are installed, will default to the framework of the model
, or to PyTorch if no model is provided.
str
, defaults to ""
) — A task-identifier for the pipeline. int
, optional, defaults to 8) — When the pipeline will use DataLoader (when passing a dataset, on GPU for a Pytorch model), the number of workers to be used. int
, optional, defaults to 1) — When the pipeline will use DataLoader (when passing a dataset, on GPU for a Pytorch model), the size of the batch to use, for inference this is not always beneficial, please read Batching with pipelines . int
, optional, defaults to -1) — Device ordinal for CPU/GPU supports. Setting this to -1 will leverage CPU, a positive will run the model on the associated CUDA device id. You can pass native torch.device
or a str
too str
or torch.dtype
, optional) — Sent directly as model_kwargs
(just a simpler shortcut) to use the available precision for this model (torch.float16
, torch.bfloat16
, … or "auto"
) bool
, optional, defaults to False
) — Flag indicating if the output the pipeline should happen in a serialized format (i.e., pickle) or as the raw output data e.g. text. bool
, optional, default to False
) — Whether or not to output the bounding box predictions. bool
, optional, default to False
) — Whether or not to output the masks in RLE
format Automatic mask generation for images using SamForMaskGeneration
. This pipeline predicts binary masks for an image, given an image. It is a ChunkPipeline
because you can seperate the points in a mini-batch in order to avoid OOM issues. Use the points_per_batch
argument to control the number of points that will be processed at the same time. Default is 64
.
The pipeline works in 3 steps:
preprocess
: A grid of 1024 points evenly separated is generated along with bounding boxes and point labels. For more details on how the points and bounding boxes are created, check the _generate_crop_boxes
function. The image is also preprocessed using the image_processor
. This function yields
a minibatch of points_per_batch
.
forward
: feeds the outputs of preprocess
to the model. The image embedding is computed only once. Calls both self.model.get_image_embeddings
and makes sure that the gradients are not computed, and the tensors and models are on the same device.
postprocess
: The most important part of the automatic mask generation happens here. Three steps are induced:
pred_iou_thresh
and stability_scores
. Also applies a variety of filters based on non maximum suppression to remove bad masks.Example:
>>> from transformers import pipeline >>> generator = pipeline(model="facebook/sam-vit-base", task="mask-generation") >>> outputs = generator( ... "http://images.cocodataset.org/val2017/000000039769.jpg", ... ) >>> outputs = generator( ... "https://huggingface.co/datasets/Narsil/image_dummy/raw/main/parrots.png", points_per_batch=128 ... )
Learn more about the basics of using a pipeline in the pipeline tutorial
This segmentation pipeline can currently be loaded from pipeline() using the following task identifier: "mask-generation"
.
See the list of available models on huggingface.co/models.
__call__ < source >( image *args num_workers = None batch_size = None **kwargs ) → Dict
Parameters
np.ndarray
or bytes
or str
or dict
) — Image or list of images. float
, optional, defaults to 0.0) — Threshold to use when turning the predicted masks into binary values. float
, optional, defaults to 0.88) — A filtering threshold in [0,1]
applied on the model’s predicted mask quality. float
, optional, defaults to 0.95) — A filtering threshold in [0,1]
, using the stability of the mask under changes to the cutoff used to binarize the model’s mask predictions. int
, optional, defaults to 1) — The amount to shift the cutoff when calculated the stability score. float
, optional, defaults to 0.7) — The box IoU cutoff used by non-maximal suppression to filter duplicate masks. int
, optional, defaults to 0) — If crops_n_layers>0
, mask prediction will be run again on crops of the image. Sets the number of layers to run, where each layer has 2**i_layer number of image crops. float
, optional, defaults to 512 / 1500
) — Sets the degree to which crops overlap. In the first crop layer, crops will overlap by this fraction of the image length. Later layers with more crops scale down this overlap. int
, optional, defaults to 1
) — The number of points-per-side sampled in layer n is scaled down by crop_n_points_downscale_factor**n. float
, optional, defaults to None) — The maximum time in seconds to wait for fetching images from the web. If None, no timeout is set and the call may block forever. A dictionary with the following keys:
PIL.Image
) — A binary mask of the detected object as a PIL Image of shape (width, height)
of the original image. Returns a mask filled with zeros if no object is found.float
) — Optionally, when the model is capable of estimating a confidence of the “object” described by the label and the mask.Generates binary segmentation masks
VisualQuestionAnsweringPipeline class transformers.VisualQuestionAnsweringPipeline < source >( *args **kwargs )
Parameters
str
or ModelCard
, optional) — Model card attributed to the model for this pipeline. str
, optional) — The framework to use, either "pt"
for PyTorch or "tf"
for TensorFlow. The specified framework must be installed.
If no framework is specified, will default to the one currently installed. If no framework is specified and both frameworks are installed, will default to the framework of the model
, or to PyTorch if no model is provided.
str
, defaults to ""
) — A task-identifier for the pipeline. int
, optional, defaults to 8) — When the pipeline will use DataLoader (when passing a dataset, on GPU for a Pytorch model), the number of workers to be used. int
, optional, defaults to 1) — When the pipeline will use DataLoader (when passing a dataset, on GPU for a Pytorch model), the size of the batch to use, for inference this is not always beneficial, please read Batching with pipelines . int
, optional, defaults to -1) — Device ordinal for CPU/GPU supports. Setting this to -1 will leverage CPU, a positive will run the model on the associated CUDA device id. You can pass native torch.device
or a str
too str
or torch.dtype
, optional) — Sent directly as model_kwargs
(just a simpler shortcut) to use the available precision for this model (torch.float16
, torch.bfloat16
, … or "auto"
) bool
, optional, defaults to False
) — Flag indicating if the output the pipeline should happen in a serialized format (i.e., pickle) or as the raw output data e.g. text. Visual Question Answering pipeline using a AutoModelForVisualQuestionAnswering
. This pipeline is currently only available in PyTorch.
Example:
>>> from transformers import pipeline >>> oracle = pipeline(model="dandelin/vilt-b32-finetuned-vqa") >>> image_url = "https://huggingface.co/datasets/Narsil/image_dummy/raw/main/lena.png" >>> oracle(question="What is she wearing ?", image=image_url) [{'score': 0.948, 'answer': 'hat'}, {'score': 0.009, 'answer': 'fedora'}, {'score': 0.003, 'answer': 'clothes'}, {'score': 0.003, 'answer': 'sun hat'}, {'score': 0.002, 'answer': 'nothing'}] >>> oracle(question="What is she wearing ?", image=image_url, top_k=1) [{'score': 0.948, 'answer': 'hat'}] >>> oracle(question="Is this a person ?", image=image_url, top_k=1) [{'score': 0.993, 'answer': 'yes'}] >>> oracle(question="Is this a man ?", image=image_url, top_k=1) [{'score': 0.996, 'answer': 'no'}]
Learn more about the basics of using a pipeline in the pipeline tutorial
This visual question answering pipeline can currently be loaded from pipeline() using the following task identifiers: "visual-question-answering", "vqa"
.
The models that this pipeline can use are models that have been fine-tuned on a visual question answering task. See the up-to-date list of available models on huggingface.co/models.
__call__ < source >( image: typing.Union[ForwardRef('Image.Image'), str, typing.List[ForwardRef('Image.Image')], typing.List[str], ForwardRef('KeyDataset')] question: typing.Union[str, typing.List[str]] = None **kwargs ) → A dictionary or a list of dictionaries containing the result. The dictionaries contain the following keys
Parameters
str
, List[str]
, PIL.Image
, List[PIL.Image]
or KeyDataset
) — The pipeline handles three types of images:
The pipeline accepts either a single image or a batch of images. If given a single image, it can be broadcasted to multiple questions. For dataset: the passed in dataset must be of type transformers.pipelines.pt_utils.KeyDataset
Example:
Returns
A dictionary or a list of dictionaries containing the result. The dictionaries contain the following keys
str
) — The label identified by the model.int
) — The score attributed by the model for that label.Answers open-ended questions about images. The pipeline accepts several types of inputs which are detailed below:
pipeline(image=image, question=question)
pipeline({"image": image, "question": question})
pipeline([{"image": image, "question": question}])
pipeline([{"image": image, "question": question}, {"image": image, "question": question}])
( model: typing.Union[ForwardRef('PreTrainedModel'), ForwardRef('TFPreTrainedModel')] tokenizer: typing.Optional[transformers.tokenization_utils.PreTrainedTokenizer] = None feature_extractor: typing.Optional[ForwardRef('SequenceFeatureExtractor')] = None image_processor: typing.Optional[transformers.image_processing_utils.BaseImageProcessor] = None processor: typing.Optional[transformers.processing_utils.ProcessorMixin] = None modelcard: typing.Optional[transformers.modelcard.ModelCard] = None framework: typing.Optional[str] = None task: str = '' args_parser: ArgumentHandler = None device: typing.Union[int, ForwardRef('torch.device')] = None torch_dtype: typing.Union[str, ForwardRef('torch.dtype'), NoneType] = None binary_output: bool = False **kwargs )
Parameters
tokenizer
, feature_extractor
, and image_processor
. str
or ModelCard
, optional) — Model card attributed to the model for this pipeline. str
, optional) — The framework to use, either "pt"
for PyTorch or "tf"
for TensorFlow. The specified framework must be installed.
If no framework is specified, will default to the one currently installed. If no framework is specified and both frameworks are installed, will default to the framework of the model
, or to PyTorch if no model is provided.
str
, defaults to ""
) — A task-identifier for the pipeline. int
, optional, defaults to 8) — When the pipeline will use DataLoader (when passing a dataset, on GPU for a Pytorch model), the number of workers to be used. int
, optional, defaults to 1) — When the pipeline will use DataLoader (when passing a dataset, on GPU for a Pytorch model), the size of the batch to use, for inference this is not always beneficial, please read Batching with pipelines . int
, optional, defaults to -1) — Device ordinal for CPU/GPU supports. Setting this to -1 will leverage CPU, a positive will run the model on the associated CUDA device id. You can pass native torch.device
or a str
too str
or torch.dtype
, optional) — Sent directly as model_kwargs
(just a simpler shortcut) to use the available precision for this model (torch.float16
, torch.bfloat16
, … or "auto"
) bool
, optional, defaults to False
) — Flag indicating if the output the pipeline should happen in a serialized format (i.e., pickle) or as the raw output data e.g. text. The Pipeline class is the class from which all pipelines inherit. Refer to this class for methods shared across different pipelines.
Base class implementing pipelined operations. Pipeline workflow is defined as a sequence of the following operations:
Input -> Tokenization -> Model Inference -> Post-Processing (task dependent) -> Output
Pipeline supports running on CPU or GPU through the device argument (see below).
Some pipeline, like for instance FeatureExtractionPipeline ('feature-extraction'
) output large tensor object as nested-lists. In order to avoid dumping such large structure as textual data we provide the binary_output
constructor argument. If set to True
, the output will be stored in the pickle format.
( supported_models: typing.Union[typing.List[str], dict] )
Parameters
List[str]
or dict
) — The list of models supported by the pipeline, or a dictionary with model class values. Check if the model class is in supported by the pipeline.
Context Manager allowing tensor allocation on the user-specified device in framework agnostic way.
Examples:
pipe = pipeline(..., device=0) with pipe.device_placement(): output = pipe(...)ensure_tensor_on_device < source >
( **inputs ) → Dict[str, torch.Tensor]
Parameters
torch.Tensor
, the rest is ignored) — The tensors to place on self.device
. Returns
Dict[str, torch.Tensor]
The same as inputs
but on the proper device.
Ensure PyTorch tensors are on the specified device.
postprocess < source >( model_outputs: ModelOutput **postprocess_parameters: typing.Dict )
Postprocess will receive the raw outputs of the _forward
method, generally tensors, and reformat them into something more friendly. Generally it will output a list or a dict or results (containing just strings and numbers).
Scikit / Keras interface to transformers’ pipelines. This method will forward to call().
preprocess < source >( input_: typing.Any **preprocess_parameters: typing.Dict )
Preprocess will take the input_
of a specific pipeline and return a dictionary of everything necessary for _forward
to run properly. It should contain at least one tensor, but might have arbitrary other items.
( repo_id: str use_temp_dir: typing.Optional[bool] = None commit_message: typing.Optional[str] = None private: typing.Optional[bool] = None token: typing.Union[bool, str, NoneType] = None max_shard_size: typing.Union[int, str, NoneType] = '5GB' create_pr: bool = False safe_serialization: bool = True revision: typing.Optional[str] = None commit_description: typing.Optional[str] = None tags: typing.Optional[list[str]] = None **deprecated_kwargs )
Parameters
str
) — The name of the repository you want to push your pipe to. It should contain your organization name when pushing to a given organization. bool
, optional) — Whether or not to use a temporary directory to store the files saved before they are pushed to the Hub. Will default to True
if there is no directory named like repo_id
, False
otherwise. str
, optional) — Message to commit while pushing. Will default to "Upload pipe"
. bool
, optional) — Whether to make the repo private. If None
(default), the repo will be public unless the organization’s default is private. This value is ignored if the repo already exists. bool
or str
, optional) — The token to use as HTTP bearer authorization for remote files. If True
, will use the token generated when running huggingface-cli login
(stored in ~/.huggingface
). Will default to True
if repo_url
is not specified. int
or str
, optional, defaults to "5GB"
) — Only applicable for models. The maximum size for a checkpoint before being sharded. Checkpoints shard will then be each of size lower than this size. If expressed as a string, needs to be digits followed by a unit (like "5MB"
). We default it to "5GB"
so that users can easily load models on free-tier Google Colab instances without any CPU OOM issues. bool
, optional, defaults to False
) — Whether or not to create a PR with the uploaded files or directly commit. bool
, optional, defaults to True
) — Whether or not to convert the model weights in safetensors format for safer serialization. str
, optional) — Branch to push the uploaded files to. str
, optional) — The description of the commit that will be created List[str]
, optional) — List of tags to push on the Hub. Upload the pipeline file to the 🤗 Model Hub.
Examples:
from transformers import pipeline pipe = pipeline("google-bert/bert-base-cased") pipe.push_to_hub("my-finetuned-bert") pipe.push_to_hub("huggingface/my-finetuned-bert")save_pretrained < source >
( save_directory: typing.Union[str, os.PathLike] safe_serialization: bool = True **kwargs )
Parameters
str
or os.PathLike
) — A path to the directory where to saved. It will be created if it doesn’t exist. str
) — Whether to save the model using safetensors
or the traditional way for PyTorch or Tensorflow. Dict[str, Any]
, optional) — Additional key word arguments passed along to the push_to_hub() method. Save the pipeline’s model and tokenizer.
Scikit / Keras interface to transformers’ pipelines. This method will forward to call().
< > Update on GitHubRetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4