Transformers 文档

管道

管道

管道是一种使用模型进行推理的简单而有效的方法。这些管道对象抽象了库中的大部分复杂代码,提供了一个专门用于多种任务的简单API,包括命名实体识别、掩码语言建模、情感分析、特征提取和问答。请参阅任务摘要以获取使用示例。

需要注意的管道抽象有两类:

管道抽象

pipeline 抽象是所有其他可用管道的包装器。它可以像其他管道一样实例化,但可以提供额外的便利性。

单个项目的简单调用:

>>> pipe = pipeline("text-classification")
>>> pipe("This restaurant is awesome")
[{'label': 'POSITIVE', 'score': 0.9998743534088135}]

如果你想使用hub上的特定模型,如果该模型已经在hub上定义了任务,你可以忽略该任务:

>>> pipe = pipeline(model="FacebookAI/roberta-large-mnli")
>>> pipe("This restaurant is awesome")
[{'label': 'NEUTRAL', 'score': 0.7313136458396912}]

要在多个项目上调用管道,你可以使用列表来调用它。

>>> pipe = pipeline("text-classification")
>>> pipe(["This restaurant is awesome", "This restaurant is awful"])
[{'label': 'POSITIVE', 'score': 0.9998743534088135},
 {'label': 'NEGATIVE', 'score': 0.9996669292449951}]

为了遍历完整的数据集,建议直接使用dataset。这意味着你不需要一次性分配整个数据集,也不需要自己进行批处理。这在GPU上的速度应该与自定义循环一样快。如果不行,请不要犹豫创建一个问题。

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")

# KeyDataset (only *pt*) will simply return the item in the dict returned by the dataset item
# as we're not interested in the *target* part of the dataset. For sentence pair use KeyPairDataset
for out in tqdm(pipe(KeyDataset(dataset, "file"))):
    print(out)
    # {"text": "NUMBER TEN FRESH NELLY IS WAITING ON YOU GOOD NIGHT HUSBAND"}
    # {"text": ....}
    # ....

为了方便使用,也可以使用生成器:

from transformers import pipeline

pipe = pipeline("text-classification")


def data():
    while True:
        # This could come from a dataset, a database, a queue or HTTP request
        # in a server
        # Caveat: because this is iterative, you cannot use `num_workers > 1` variable
        # to use multiple threads to preprocess data. You can still have 1 thread that
        # does the preprocessing while the main runs the big inference
        yield "This is a test"


for out in pipe(data()):
    print(out)
    # {"text": "NUMBER TEN FRESH NELLY IS WAITING ON YOU GOOD NIGHT HUSBAND"}
    # {"text": ....}
    # ....

transformers.pipeline

< >

( task: 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[str, bool, 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.Dict[str, typing.Any] = None pipeline_class: typing.Optional[typing.Any] = None **kwargs ) Pipeline

参数

  • task (str) — The task defining which pipeline will be returned. Currently accepted tasks are:
  • model (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).

    如果没有提供,将加载task的默认值。

  • config (str or PretrainedConfig, optional) — The configuration that will be used by the pipeline to instantiate the model. This can be a model identifier or an actual pretrained model configuration inheriting from PretrainedConfig.

    如果没有提供,将使用请求模型的默认配置文件。这意味着如果提供了model,将使用其默认配置。然而,如果没有提供model,则将使用此task的默认模型的配置。

  • tokenizer (str or PreTrainedTokenizer, optional) — The tokenizer that will be used by the pipeline to encode data for the model. This can be a model identifier or an actual pretrained tokenizer inheriting from PreTrainedTokenizer.

    如果没有提供,将加载给定model的默认分词器(如果它是一个字符串)。如果model未指定或不是一个字符串,则加载config的默认分词器(如果它是一个字符串)。然而,如果config也未给出或不是一个字符串,则将加载给定task的默认分词器。

  • feature_extractor (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.

    特征提取器用于非NLP模型,例如语音或视觉模型以及多模态模型。多模态模型还需要传递一个分词器。

    如果没有提供,将加载给定model的默认特征提取器(如果它是一个字符串)。如果model未指定或不是字符串,则加载config的默认特征提取器(如果它是一个字符串)。然而,如果config也未给出或不是字符串,则将加载给定task的默认特征提取器。

  • image_processor (str or BaseImageProcessor, optional) — The image processor that will be used by the pipeline to preprocess images for the model. This can be a model identifier or an actual image processor inheriting from BaseImageProcessor.

    图像处理器用于需要图像输入的视觉模型和多模态模型。多模态模型还需要传递一个分词器。

    如果没有提供,将加载给定model的默认图像处理器(如果它是一个字符串)。如果model未指定或不是字符串,则加载config的默认图像处理器(如果它是一个字符串)。

  • processor (str or ProcessorMixin, optional) — The processor that will be used by the pipeline to preprocess data for the model. This can be a model identifier or an actual processor inheriting from ProcessorMixin.

    处理器用于需要多模态输入的多模态模型,例如,一个需要文本和图像输入的模型。

    如果没有提供,将加载给定model的默认处理器(如果它是一个字符串)。如果model未指定或不是一个字符串,则加载config的默认处理器(如果它是一个字符串)。

  • framework (str, optional) — The framework to use, either "pt" for PyTorch or "tf" for TensorFlow. The specified framework must be installed.

    如果没有指定框架,将默认使用当前安装的框架。如果没有指定框架且两个框架都已安装,将默认使用model的框架,如果没有提供模型,则默认使用PyTorch。

  • revision (str, 可选, 默认为 "main") — 当传递任务名称或字符串模型标识符时:要使用的特定模型版本。它可以是分支名称、标签名称或提交ID,因为我们使用基于git的系统在huggingface.co上存储模型和其他工件,所以revision可以是git允许的任何标识符。
  • use_fast (bool, 可选, 默认为 True) — 是否尽可能使用快速分词器(一个 PreTrainedTokenizerFast)。
  • use_auth_token (strbool, 可选) — 用于远程文件的HTTP承载授权的令牌。如果为 True,将使用运行 huggingface-cli login 时生成的令牌(存储在 ~/.huggingface 中)。
  • device (int or str or torch.device) — 定义此管道将被分配到的设备(例如"cpu""cuda:1""mps",或像1这样的GPU序号)。
  • device_map (str or Dict[str, Union[int, str, torch.device], optional) — Sent directly as model_kwargs (just a simpler shortcut). When accelerate library is present, set device_map="auto" to compute the most optimized device_map automatically (see here for more information).

    不要同时使用 device_mapdevice,因为它们会发生冲突

  • torch_dtype (strtorch.dtype, 可选) — 直接作为 model_kwargs 发送(只是一个更简单的快捷方式)以使用此模型可用的精度 (torch.float16, torch.bfloat16, … 或 "auto").
  • trust_remote_code (bool, 可选, 默认为 False) — 是否允许在Hub上定义的建模、配置、分词甚至管道文件中使用自定义代码。此选项应仅对您信任的仓库设置为True,并且您已经阅读了代码,因为它将在您的本地机器上执行Hub上的代码。
  • model_kwargs (Dict[str, Any], 可选) — 传递给模型的 from_pretrained(..., **model_kwargs) 函数的额外关键字参数字典。
  • kwargs (Dict[str, Any], 可选) — 传递给特定管道初始化的额外关键字参数(请参阅相应管道类的文档以获取可能的值)。

返回

Pipeline

适合该任务的管道。

用于构建Pipeline的工具工厂方法。

一个管道包括:

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.

示例:

>>> from transformers import pipeline, AutoModelForTokenClassification, AutoTokenizer

>>> # Sentiment analysis pipeline
>>> analyzer = pipeline("sentiment-analysis")

>>> # Question answering pipeline, specifying the checkpoint identifier
>>> oracle = pipeline(
...     "question-answering", model="distilbert/distilbert-base-cased-distilled-squad", tokenizer="google-bert/bert-base-cased"
... )

>>> # Named entity recognition pipeline, passing in a specific model and tokenizer
>>> model = AutoModelForTokenClassification.from_pretrained("dbmdz/bert-large-cased-finetuned-conll03-english")
>>> tokenizer = AutoTokenizer.from_pretrained("google-bert/bert-base-cased")
>>> recognizer = pipeline("ner", model=model, tokenizer=tokenizer)

管道批处理

所有管道都可以使用批处理。当管道使用其流式处理能力时(例如传递列表或Datasetgenerator时),这将起作用。

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)
    # [{'label': 'POSITIVE', 'score': 0.9998743534088135}]
    # Exactly the same output as before, but the content are passed
    # as batches to the model

然而,这并不自动意味着性能的提升。根据硬件、数据和实际使用的模型,它可能是10倍的加速,也可能是5倍的减速。

主要是一个加速的示例:

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)

示例中最常见的减速情况:

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

这是一个偶尔比其他句子长得多的句子。在这种情况下,整个批次需要达到400个标记的长度,因此整个批次的大小将是[64, 400]而不是[64, 4],从而导致严重的减速。更糟糕的是,在更大的批次上,程序甚至会崩溃。

------------------------------
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)  # (bs, n_heads, q_length, 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)

对于这个问题,没有(通用的)好的解决方案,你的体验可能会因你的使用情况而异。经验法则:

对于用户来说,一个经验法则是:

  • 在您的负载和硬件上测量性能。测量、测量,并持续测量。真实数据是唯一的方法。

  • 如果您受到延迟限制(实时产品进行推理),请不要进行批处理。

  • 如果您使用的是CPU,请不要进行批处理。

  • 如果您正在使用吞吐量(您希望在一堆静态数据上运行您的模型),在GPU上,那么:

    • If you have no clue about the size of the sequence_length (“natural” data), by default don’t batch, measure and try tentatively to add it, add OOM checks to recover when it will fail (and it will at some point if you don’t control the sequence_length.)
    • If your sequence_length is super regular, then batching is more likely to be VERY interesting, measure and push it until you get OOMs.
    • The larger the GPU the more likely batching is going to be more interesting
  • 一旦启用批处理,请确保您能够妥善处理OOMs。

管道分块批处理

zero-shot-classificationquestion-answering 在某种意义上稍微有些特殊,因为单个输入可能会导致模型的多次前向传递。在正常情况下,这可能会导致 batch_size 参数出现问题。

为了避免这个问题,这两个管道都有点特殊,它们是ChunkPipeline而不是常规的Pipeline。简而言之:

preprocessed = pipe.preprocess(inputs)
model_outputs = pipe.forward(preprocessed)
outputs = pipe.postprocess(model_outputs)

现在变为:

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)

这对你的代码来说应该是非常透明的,因为管道是以相同的方式使用的。

这是一个简化的视图,因为管道可以自动处理批次!这意味着你不必关心你的输入实际上会触发多少次前向传递,你可以独立于输入优化batch_size。前一节的注意事项仍然适用。

Pipeline FP16 推理

模型可以在FP16中运行,这在GPU上可以显著加快速度,同时节省内存。大多数模型不会因此遭受明显的性能损失。模型越大,这种情况发生的可能性就越小。

要启用FP16推理,您可以简单地将torch_dtype=torch.float16torch_dtype='float16'传递给管道构造函数。请注意,这仅适用于具有PyTorch后端的模型。您的输入将在内部转换为FP16。

管道自定义代码

如果你想覆盖一个特定的管道。

不要犹豫,为手头的任务创建一个问题,管道的目标是易于使用并支持大多数情况,所以transformers可能支持你的用例。

如果你想简单尝试,你可以:

  • 子类化您选择的管道
class MyPipeline(TextClassificationPipeline):
    def postprocess():
        # Your code goes here
        scores = scores * 100
        # And here


my_pipeline = MyPipeline(model=model, tokenizer=tokenizer, ...)
# or if you use *pipeline* function, then:
my_pipeline = pipeline(model="xxxx", pipeline_class=MyPipeline)

这将使您能够执行所有您想要的自定义代码。

实现一个管道

实现一个新的管道

音频

可用于音频任务的管道包括以下内容。

音频分类管道

transformers.AudioClassificationPipeline

< >

( *args **kwargs )

参数

  • model (PreTrainedModelTFPreTrainedModel) — 管道将用于进行预测的模型。这需要是一个继承自 PreTrainedModel 的模型(适用于 PyTorch)和 TFPreTrainedModel 的模型(适用于 TensorFlow)。
  • feature_extractor (SequenceFeatureExtractor) — 管道将使用该特征提取器来为模型编码数据。该对象继承自 SequenceFeatureExtractor.
  • modelcard (strModelCard, 可选) — 为此管道模型归因的模型卡片。
  • framework (str, optional) — The framework to use, either "pt" for PyTorch or "tf" for TensorFlow. The specified framework must be installed.

    如果没有指定框架,将默认使用当前安装的框架。如果没有指定框架且两个框架都已安装,将默认使用model的框架,如果没有提供模型,则默认使用PyTorch。

  • task (str, 默认为 "") — 管道的任务标识符。
  • num_workers (int, 可选, 默认为 8) — 当管道使用 DataLoader 时(在传递数据集时,用于 Pytorch 模型的 GPU 上),要使用的工作线程数。
  • batch_size (int, 可选, 默认为 1) — 当管道使用 DataLoader 时(当传递数据集时,在 GPU 上用于 Pytorch 模型),使用的批次大小,对于推理来说,这并不总是有益的,请阅读 Batching with pipelines
  • args_parser (ArgumentHandler, 可选) — 负责解析提供的管道参数的对象的引用。
  • device (int, optional, 默认为 -1) — 用于CPU/GPU支持的设备序号。将此设置为-1将利用CPU,设置为正数将在关联的CUDA设备ID上运行模型。你也可以传递原生的torch.devicestr
  • torch_dtype (strtorch.dtype, 可选) — 直接作为 model_kwargs 发送(只是一个更简单的快捷方式)以使用此模型可用的精度 (torch.float16, torch.bfloat16, … 或 "auto")
  • binary_output (bool, 可选, 默认为 False) — 标志指示管道的输出是否应以序列化格式(即pickle)或原始输出数据(例如文本)进行。

使用任何AutoModelForAudioClassification的音频分类管道。该管道预测原始波形或音频文件的类别。如果是音频文件,应安装ffmpeg以支持多种音频格式。

示例:

>>> 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'}]

了解更多关于使用管道的基础知识,请参阅管道教程

目前可以从pipeline()使用以下任务标识符加载此管道: "audio-classification"

查看可用模型列表在 huggingface.co/models

__call__

< >

( inputs: typing.Union[numpy.ndarray, bytes, str] **kwargs ) 一个包含以下键的dict列表

参数

  • inputs (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.
  • top_k (int, 可选, 默认为 None) — 管道将返回的顶部标签的数量。如果提供的数字是 None 或 高于模型配置中可用的标签数量,它将默认为标签的数量。
  • function_to_apply(str, 可选, 默认为“softmax”) — 应用于模型输出的函数。默认情况下,管道将对模型输出应用softmax函数。有效选项:[“softmax”, “sigmoid”, “none”]。请注意,传递Python的内置None将默认为“softmax”,因此您需要传递字符串“none”以禁用任何后处理。

返回

一个包含以下键的dict列表

  • label (str) — 预测的标签。
  • score (float) — 对应的概率。

对输入的序列进行分类。更多信息请参阅AutomaticSpeechRecognitionPipeline文档。

自动语音识别管道

transformers.AutomaticSpeechRecognitionPipeline

< >

( 模型: PreTrainedModel 特征提取器: typing.Union[ForwardRef('SequenceFeatureExtractor'), str] = None 分词器: typing.Optional[transformers.tokenization_utils.PreTrainedTokenizer] = None 解码器: typing.Union[ForwardRef('BeamSearchDecoderCTC'), str, NoneType] = None 设备: typing.Union[int, ForwardRef('torch.device')] = None torch数据类型: typing.Union[str, ForwardRef('torch.dtype'), NoneType] = None **kwargs )

参数

  • model (PreTrainedModelTFPreTrainedModel) — 管道将用于进行预测的模型。这需要是一个继承自 PreTrainedModel 的模型(用于 PyTorch)和 TFPreTrainedModel 的模型(用于 TensorFlow)。
  • feature_extractor (SequenceFeatureExtractor) — 管道将使用的特征提取器,用于为模型编码波形。
  • tokenizer (PreTrainedTokenizer) — 管道将使用的分词器,用于为模型编码数据。此对象继承自 PreTrainedTokenizer.
  • 解码器 (pyctcdecode.BeamSearchDecoderCTC, 可选) — PyCTCDecode的 BeamSearchDecoderCTC 可以用于语言模型增强的解码。有关更多信息,请参见Wav2Vec2ProcessorWithLM.
  • chunk_length_s (float, optional, defaults to 0) — The input length for in each chunk. If chunk_length_s = 0 then chunking is disabled (default).

    有关如何有效使用chunk_length_s的更多信息,请查看ASR分块博客文章

  • stride_length_s (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.

    有关如何有效使用stride_length_s的更多信息,请查看ASR分块博客文章

  • 框架 (str, 可选) — 使用的框架,可以是 "pt" 表示 PyTorch 或 "tf" 表示 TensorFlow。指定的框架必须已安装。如果未指定框架,将默认使用当前安装的框架。如果未指定框架且两个框架都已安装,将默认使用 model 的框架,如果没有提供模型,则默认使用 PyTorch。
  • device (Union[int, torch.device], optional) — 支持CPU/GPU的设备序号。将此设置为None将利用CPU,设置为正数将在关联的CUDA设备ID上运行模型。
  • torch_dtype (Union[int, torch.dtype], optional) — 计算的数据类型(dtype)。将此设置为 None 将使用 float32 精度。设置为 torch.float16torch.bfloat16 以使用相应数据类型的半精度。

旨在从某些音频中提取口语文本的管道。

输入可以是原始波形或音频文件。如果是音频文件,应安装ffmpeg以支持多种音频格式

示例:

>>> 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.'}

了解更多关于使用管道的基础知识,请参阅管道教程

__call__

< >

( inputs: typing.Union[numpy.ndarray, bytes, str] **kwargs ) Dict

参数

  • inputs (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.
  • return_timestamps (optional, str or bool) — Only available for pure CTC models (Wav2Vec2, HuBERT, etc) and the Whisper model. Not available for other sequence-to-sequence models.

    对于CTC模型,时间戳可以采用以下两种格式之一:

    • "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.

    对于Whisper模型,时间戳可以采用以下两种格式之一:

    • "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.
  • generate_kwargs (dict, 可选) — 用于生成调用的generate_config的临时参数字典。有关生成的完整概述,请查看以下指南.

返回

Dict

一个包含以下键的字典:

  • text (str): 识别出的文本。
  • chunks (optional(, List[Dict]) 当使用 return_timestamps 时,chunks 将变成一个包含模型识别的所有不同文本块的列表,例如* [{"text": "hi ", "timestamp": (0.5, 0.9)}, {"text": "there", "timestamp": (1.0, 1.5)}]。原始完整文本可以通过执行 "".join(chunk["text"] for chunk in output["chunks"]) 大致恢复。

将输入的音频序列转录为文本。有关更多信息,请参阅AutomaticSpeechRecognitionPipeline文档。

TextToAudioPipeline

transformers.TextToAudioPipeline

< >

( *args vocoder = None sampling_rate = None **kwargs )

使用任何AutoModelForTextToWaveformAutoModelForTextToSpectrogram的文本到音频生成管道。该管道从输入文本和可选的其它条件输入生成音频文件。

示例:

>>> 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"]

了解更多关于使用管道的基础知识,请参阅管道教程

您可以通过使用TextToAudioPipeline.__call__.forward_paramsTextToAudioPipeline.__call__.generate_kwargs来指定传递给模型的参数。

示例:

>>> from transformers import pipeline

>>> music_generator = pipeline(task="text-to-audio", model="facebook/musicgen-small", framework="pt")

>>> # diversify the music generation by adding randomness with a high temperature and set a maximum music length
>>> 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)

目前可以通过使用以下任务标识符从pipeline()加载此管道:"text-to-speech""text-to-audio"

查看可用模型列表在 huggingface.co/models

__call__

< >

( text_inputs: typing.Union[str, typing.List[str]] **forward_params ) 一个 dictdict 的列表

参数

  • text_inputs (str or List[str]) — 要生成的文本。
  • forward_params (dict, 可选) — 传递给模型生成/前向方法的参数。forward_params 总是传递给底层模型。
  • generate_kwargs (dict, 可选) — 用于生成调用的generate_config的临时参数字典。有关生成的完整概述,请查看以下指南。只有在底层模型是生成模型时,generate_kwargs才会传递给底层模型。

返回

一个dict或一个dict的列表

字典有两个键:

  • audio (np.ndarray 形状为 (nb_channels, audio_length)) — 生成的音频波形。
  • sampling_rate (int) — 生成的音频波形的采样率。

从输入生成语音/音频。有关更多信息,请参阅TextToAudioPipeline文档。

ZeroShotAudioClassificationPipeline

transformers.ZeroShotAudioClassificationPipeline

< >

( **kwargs )

参数

  • model (PreTrainedModelTFPreTrainedModel) — 管道将用于进行预测的模型。这需要是一个继承自 PreTrainedModel 的 PyTorch 模型和继承自 TFPreTrainedModel 的 TensorFlow 模型。
  • tokenizer (PreTrainedTokenizer) — 管道将使用的分词器,用于为模型编码数据。此对象继承自 PreTrainedTokenizer.
  • feature_extractor (SequenceFeatureExtractor) — 管道将使用该特征提取器来为模型编码数据。该对象继承自 SequenceFeatureExtractor.
  • modelcard (strModelCard, 可选) — 归因于此管道模型的模型卡。
  • framework (str, optional) — The framework to use, either "pt" for PyTorch or "tf" for TensorFlow. The specified framework must be installed.

    如果没有指定框架,将默认使用当前安装的框架。如果没有指定框架且两个框架都已安装,将默认使用model的框架,如果没有提供模型,则默认使用PyTorch。

  • task (str, defaults to "") — 管道的一个任务标识符。
  • num_workers (int, 可选, 默认为 8) — 当管道将使用 DataLoader 时(在传递数据集时,对于 Pytorch 模型在 GPU 上),要使用的工作线程数。
  • batch_size (int, 可选, 默认为 1) — 当管道使用 DataLoader 时(当传递数据集时,在 GPU 上用于 Pytorch 模型),使用的批次大小,对于推理来说,这并不总是有益的,请阅读 Batching with pipelines
  • args_parser (ArgumentHandler, 可选) — 负责解析提供的管道参数的对象的引用。
  • device (int, 可选, 默认为 -1) — 用于CPU/GPU支持的设备序号。将此设置为-1将利用CPU,设置为正数将在关联的CUDA设备ID上运行模型。你也可以传递原生的torch.devicestr
  • torch_dtype (strtorch.dtype, 可选) — 直接作为 model_kwargs 发送(只是一个更简单的快捷方式)以使用此模型可用的精度 (torch.float16, torch.bfloat16, … 或 "auto")
  • binary_output (bool, optional, defaults to False) — 标志指示管道的输出是否应以序列化格式(即pickle)或原始输出数据(例如文本)进行。

使用ClapModel的零样本音频分类管道。当您提供一个音频和一组candidate_labels时,此管道会预测音频的类别。

默认的 hypothesis_template 是:"This is a sound of {}."。请确保根据您的使用情况进行更新。

示例:

>>> 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'}]

了解更多关于使用管道的基础知识,请参阅管道教程。这个音频分类管道目前可以从pipeline()加载,使用以下任务标识符: "zero-shot-audio-classification"。查看可用模型列表,请访问 huggingface.co/models

__call__

< >

( audios: typing.Union[numpy.ndarray, bytes, str] **kwargs )

参数

  • audios (str, List[str], np.arrayList[np.array]) — 管道处理三种类型的输入:
    • 包含指向音频的http链接的字符串
    • 包含音频本地路径的字符串
    • 加载到numpy中的音频
  • candidate_labels (List[str]) — 此音频的候选标签。它们将使用hypothesis_template进行格式化。
  • hypothesis_template (str, optional, defaults to "This is a sound of {}") — 用于与candidate_labels结合使用的格式,通过将占位符替换为candidate_labels来尝试音频分类。如果candidate_labels已经格式化,则传递“{}”。

将标签分配给作为输入传递的音频。

计算机视觉

可用于计算机视觉任务的管道包括以下内容。

深度估计管道

transformers.DepthEstimationPipeline

< >

( *args **kwargs )

参数

  • model (PreTrainedModelTFPreTrainedModel) — 管道将用于进行预测的模型。这需要是一个继承自 PreTrainedModel 的 PyTorch 模型和继承自 TFPreTrainedModel 的 TensorFlow 模型。
  • image_processor (BaseImageProcessor) — 管道将使用该图像处理器来为模型编码数据。此对象继承自 BaseImageProcessor.
  • modelcard (strModelCard, 可选) — 归因于此管道模型的模型卡。
  • framework (str, optional) — The framework to use, either "pt" for PyTorch or "tf" for TensorFlow. The specified framework must be installed.

    如果没有指定框架,将默认使用当前安装的框架。如果没有指定框架且两个框架都已安装,将默认使用model的框架,如果没有提供模型,则默认使用PyTorch。

  • task (str, 默认为 "") — 管道的一个任务标识符。
  • num_workers (int, optional, defaults to 8) — 当管道将使用DataLoader时(在传递数据集时,对于Pytorch模型在GPU上),要使用的工作线程数。
  • batch_size (int, 可选, 默认为 1) — 当管道使用 DataLoader 时(当传递数据集时,在 GPU 上用于 Pytorch 模型),使用的批次大小,对于推理来说,这并不总是有益的,请阅读 Batching with pipelines
  • args_parser (ArgumentHandler, 可选) — 负责解析提供的管道参数的对象的引用。
  • device (int, 可选, 默认为 -1) — 用于CPU/GPU支持的设备序号。将此设置为-1将利用CPU,设置为正数将在关联的CUDA设备ID上运行模型。你也可以传递原生的torch.devicestr
  • torch_dtype (strtorch.dtype, 可选) — 直接作为 model_kwargs 发送(只是一个更简单的快捷方式)以使用此模型可用的精度 (torch.float16, torch.bfloat16, … 或 "auto")
  • binary_output (bool, optional, defaults to False) — 标志指示管道的输出是否应以序列化格式(即pickle)或原始输出数据(例如文本)进行。

使用任何AutoModelForDepthEstimation的深度估计管道。此管道预测图像的深度。

示例:

>>> 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")
>>> # This is a tensor with the values being the depth expressed in meters for each pixel
>>> output["predicted_depth"].shape
torch.Size([1, 384, 384])

了解更多关于使用管道的基础知识,请参阅管道教程

这个深度估计管道目前可以通过使用以下任务标识符从pipeline()加载: "depth-estimation"

查看可用模型列表在 huggingface.co/models

__call__

< >

( inputs: typing.Union[str, typing.List[str], ForwardRef('Image.Image'), typing.List[ForwardRef('Image.Image')]] = None **kwargs )

参数

  • inputs (str, List[str], PIL.Image or List[PIL.Image]) — The pipeline handles three types of images:
    • A string containing a http link pointing to an image
    • A string containing a local path to an image
    • An image loaded in PIL directly

    管道接受单个图像或一批图像,这些图像必须作为字符串传递。 一批中的图像必须全部采用相同的格式:全部为http链接,全部为本地路径,或全部为PIL 图像。

  • 参数 (Dict, 可选) — 一个参数名称到参数值的字典,用于控制管道行为。 目前唯一可用的参数是 timeout,它是管道在放弃尝试下载图像之前应等待的时间长度,以秒为单位。
  • timeout (float, optional, 默认为 None) — 从网络获取图像的最大等待时间(以秒为单位)。如果为 None,则不设置超时,调用可能会永久阻塞。

预测作为输入传递的图像深度。

图像分类管道

transformers.ImageClassificationPipeline

< >

( *args **kwargs )

参数

  • model (PreTrainedModelTFPreTrainedModel) — 管道将用于进行预测的模型。这需要是一个继承自 PreTrainedModel 的模型用于 PyTorch 和 TFPreTrainedModel 用于 TensorFlow.
  • image_processor (BaseImageProcessor) — 管道将使用的图像处理器,用于为模型编码数据。此对象继承自 BaseImageProcessor.
  • modelcard (strModelCard, 可选) — 归因于此管道模型的模型卡。
  • framework (str, optional) — The framework to use, either "pt" for PyTorch or "tf" for TensorFlow. The specified framework must be installed.

    如果没有指定框架,将默认使用当前安装的框架。如果没有指定框架且两个框架都已安装,将默认使用model的框架,如果没有提供模型,则默认使用PyTorch。

  • task (str, 默认为 "") — 管道的一个任务标识符。
  • num_workers (int, optional, 默认为 8) — 当管道将使用 DataLoader 时(在传递数据集时,对于 Pytorch 模型在 GPU 上),要使用的工作线程数。
  • batch_size (int, 可选, 默认为 1) — 当管道使用 DataLoader 时(当传递数据集时,在 GPU 上用于 Pytorch 模型),使用的批次大小,对于推理来说,这并不总是有益的,请阅读 Batching with pipelines
  • args_parser (ArgumentHandler, 可选) — 负责解析提供的管道参数的对象的引用。
  • device (int, 可选, 默认为 -1) — 用于CPU/GPU支持的设备序号。将此设置为-1将利用CPU,设置为正数将在关联的CUDA设备ID上运行模型。你也可以传递原生的torch.devicestr
  • torch_dtype (strtorch.dtype, 可选) — 直接作为 model_kwargs 发送(只是一个更简单的快捷方式)以使用此模型可用的精度 (torch.float16, torch.bfloat16, … 或 "auto")
  • binary_output (bool, 可选, 默认为 False) — 标志指示管道的输出是否应以序列化格式(即pickle)或原始输出数据(例如文本)进行。
  • function_to_apply (str, 可选, 默认为 "default") — 应用于模型输出以获取分数的函数。接受四个不同的值:
    • "default": 如果模型有单个标签,将在输出上应用sigmoid函数。如果模型 有多个标签,将在输出上应用softmax函数。
    • "sigmoid": 在输出上应用sigmoid函数。
    • "softmax": 在输出上应用softmax函数。
    • "none": 不在输出上应用任何函数。

使用任何AutoModelForImageClassification的图像分类流程。此流程预测图像的类别。

示例:

>>> 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'}]

了解更多关于使用管道的基础知识,请参阅管道教程

这个图像分类管道目前可以从pipeline()使用以下任务标识符加载: "image-classification"

查看可用模型列表,请访问 huggingface.co/models

__call__

< >

( inputs: typing.Union[str, typing.List[str], ForwardRef('Image.Image'), typing.List[ForwardRef('Image.Image')]] = None **kwargs )

参数

  • inputs (str, List[str], PIL.Image or List[PIL.Image]) — The pipeline handles three types of images:
    • A string containing a http link pointing to an image
    • A string containing a local path to an image
    • An image loaded in PIL directly

    管道接受单个图像或一批图像,这些图像必须作为字符串传递。 一批中的图像必须全部采用相同的格式:全部为http链接,全部为本地路径,或全部为PIL 图像。

  • function_to_apply (str, optional, defaults to "default") — The function to apply to the model outputs in order to retrieve the scores. Accepts four different values:

    如果未指定此参数,则将根据标签数量应用以下函数:

    • 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.
  • top_k (int, 可选, 默认为 5) — 管道将返回的顶部标签的数量。如果提供的数字高于模型配置中可用的标签数量,则默认为标签数量。
  • timeout (float, optional, 默认为 None) — 从网络获取图像的最大等待时间(以秒为单位)。如果为 None,则不设置超时,调用可能会永久阻塞。

为作为输入传递的图像分配标签。

图像分割管道

transformers.ImageSegmentationPipeline

< >

( *args **kwargs )

参数

  • model (PreTrainedModelTFPreTrainedModel) — 管道将用于进行预测的模型。这需要是一个继承自 PreTrainedModel 的模型用于 PyTorch 和 TFPreTrainedModel 用于 TensorFlow.
  • image_processor (BaseImageProcessor) — 管道将使用该图像处理器来为模型编码数据。此对象继承自 BaseImageProcessor.
  • modelcard (strModelCard, 可选) — 归因于此管道模型的模型卡。
  • framework (str, optional) — The framework to use, either "pt" for PyTorch or "tf" for TensorFlow. The specified framework must be installed.

    如果没有指定框架,将默认使用当前安装的框架。如果没有指定框架且两个框架都已安装,将默认使用model的框架,如果没有提供模型,则默认使用PyTorch。

  • task (str, 默认为 "") — 管道的任务标识符。
  • num_workers (int, 可选, 默认为 8) — 当管道将使用 DataLoader 时(在传递数据集时,对于 Pytorch 模型在 GPU 上),要使用的工作线程数。
  • batch_size (int, optional, 默认为 1) — 当管道使用 DataLoader 时(当传递数据集时,在 GPU 上用于 Pytorch 模型),使用的批次大小,对于推理来说,这并不总是有益的,请阅读 Batching with pipelines
  • args_parser (ArgumentHandler, 可选) — 负责解析提供的管道参数的对象的引用。
  • device (int, 可选, 默认为 -1) — 用于CPU/GPU支持的设备序号。将此设置为-1将利用CPU,设置为正数将在关联的CUDA设备ID上运行模型。你也可以传递原生的torch.devicestr
  • torch_dtype (strtorch.dtype, 可选) — 直接作为 model_kwargs 发送(只是一个更简单的快捷方式)以使用此模型可用的精度 (torch.float16, torch.bfloat16, … 或 "auto")
  • binary_output (bool, 可选, 默认为 False) — 标志指示管道的输出是否应以序列化格式(即pickle)或原始输出数据(例如文本)进行。

使用任何AutoModelForXXXSegmentation的图像分割流程。此流程预测对象的掩码及其类别。

示例:

>>> 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"])  # This is a black and white mask showing where is the bird on the original image.
<class 'PIL.Image.Image'>

>>> segments[0]["mask"].size
(768, 512)

这个图像分割管道目前可以通过使用以下任务标识符从pipeline()加载: "image-segmentation"

查看可用模型列表,请访问 huggingface.co/models

__call__

< >

( inputs = 无 **kwargs )

参数

  • inputs (str, List[str], PIL.Image or List[PIL.Image]) — The pipeline handles three types of images:
    • A string containing an HTTP(S) link pointing to an image
    • A string containing a local path to an image
    • An image loaded in PIL directly

    管道接受单个图像或一批图像。批次中的图像必须全部为相同格式:全部为HTTP(S)链接,全部为本地路径,或全部为PIL图像。

  • 子任务 (str, 可选) — 要执行的分割任务,根据模型能力选择[semantic, instancepanoptic]。如果未设置,管道将尝试按以下顺序解析: panoptic, instance, semantic.
  • threshold (float, optional, 默认为 0.9) — 用于过滤预测掩码的概率阈值。
  • mask_threshold (float, optional, defaults to 0.5) — 用于将预测的掩码转换为二进制值的阈值。
  • overlap_mask_area_threshold (float, optional, defaults to 0.5) — 掩码重叠阈值,用于消除小的、不连续的片段。
  • timeout (float, optional, defaults to None) — 从网络获取图像的最大等待时间(以秒为单位)。如果为None,则不设置超时,调用可能会永久阻塞。

对作为输入传递的图像执行分割(检测掩码和类别)。

ImageToImagePipeline

transformers.ImageToImagePipeline

< >

( *args **kwargs )

参数

  • model (PreTrainedModelTFPreTrainedModel) — 管道将用于进行预测的模型。这需要是一个继承自 PreTrainedModel 的模型用于 PyTorch 和 TFPreTrainedModel 用于 TensorFlow.
  • image_processor (BaseImageProcessor) — 管道将使用的图像处理器,用于为模型编码数据。此对象继承自 BaseImageProcessor.
  • modelcard (strModelCard, 可选) — 归因于此管道模型的模型卡。
  • framework (str, optional) — The framework to use, either "pt" for PyTorch or "tf" for TensorFlow. The specified framework must be installed.

    如果没有指定框架,将默认使用当前安装的框架。如果没有指定框架且两个框架都已安装,将默认使用model的框架,如果没有提供模型,则默认使用PyTorch。

  • task (str, 默认为 "") — 管道的一个任务标识符。
  • num_workers (int, optional, 默认为 8) — 当管道将使用 DataLoader 时(在传递数据集时,对于 Pytorch 模型在 GPU 上),要使用的工作线程数。
  • batch_size (int, 可选, 默认为 1) — 当管道使用 DataLoader 时(当传递数据集时,在 GPU 上用于 Pytorch 模型),使用的批次大小,对于推理来说,这并不总是有益的,请阅读 Batching with pipelines
  • args_parser (ArgumentHandler, 可选) — 负责解析提供的管道参数的对象的引用。
  • device (int, 可选, 默认为 -1) — 用于CPU/GPU支持的设备序号。将此设置为-1将利用CPU,设置为正数将在关联的CUDA设备ID上运行模型。你也可以传递原生的torch.devicestr
  • torch_dtype (strtorch.dtype, 可选) — 直接作为 model_kwargs 发送(只是一个更简单的快捷方式)以使用此模型可用的精度 (torch.float16, torch.bfloat16, … 或 "auto")
  • binary_output (bool, 可选, 默认为 False) — 标志指示管道的输出是否应以序列化格式(即pickle)或原始输出数据(例如文本)进行。

使用任何AutoModelForImageToImage的图像到图像管道。该管道基于先前的图像输入生成图像。

示例:

>>> 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)

这个图像到图像的管道目前可以通过使用以下任务标识符从pipeline()加载: "image-to-image"

查看可用模型列表在 huggingface.co/models

__call__

< >

( images: typing.Union[str, typing.List[str], ForwardRef('Image.Image'), typing.List[ForwardRef('Image.Image')]] **kwargs )

参数

  • images (str, List[str], PIL.Image or List[PIL.Image]) — The pipeline handles three types of images:
    • A string containing a http link pointing to an image
    • A string containing a local path to an image
    • An image loaded in PIL directly

    管道接受单个图像或一批图像,这些图像必须作为字符串传递。 一批中的图像必须全部采用相同的格式:全部为http链接,全部为本地路径,或全部为PIL 图像。

  • timeout (float, optional, 默认为 None) — 从网络获取图像的最大等待时间(以秒为单位)。如果为 None,则不使用超时,调用可能会永久阻塞。

转换作为输入传递的图像。

ObjectDetectionPipeline

transformers.ObjectDetectionPipeline

< >

( *args **kwargs )

参数

  • model (PreTrainedModelTFPreTrainedModel) — 管道将用于进行预测的模型。这需要是一个继承自 PreTrainedModel 的模型用于 PyTorch 和 TFPreTrainedModel 用于 TensorFlow.
  • image_processor (BaseImageProcessor) — 管道将使用该图像处理器来为模型编码数据。此对象继承自 BaseImageProcessor.
  • modelcard (strModelCard, 可选) — 此管道的模型所归属的模型卡片。
  • framework (str, optional) — The framework to use, either "pt" for PyTorch or "tf" for TensorFlow. The specified framework must be installed.

    如果没有指定框架,将默认使用当前安装的框架。如果没有指定框架且两个框架都已安装,将默认使用model的框架,如果没有提供模型,则默认使用PyTorch。

  • task (str, 默认为 "") — 管道的一个任务标识符。
  • num_workers (int, 可选, 默认为 8) — 当管道使用 DataLoader 时(在传递数据集、在 GPU 上使用 Pytorch 模型时),要使用的工作线程数。
  • batch_size (int, 可选, 默认为 1) — 当管道使用 DataLoader 时(当传递数据集时,在 GPU 上用于 Pytorch 模型),使用的批次大小,对于推理来说,这并不总是有益的,请阅读 Batching with pipelines
  • args_parser (ArgumentHandler, 可选) — 负责解析提供的管道参数的对象的引用。
  • device (int, 可选, 默认为 -1) — 用于CPU/GPU支持的设备序号。将此设置为-1将利用CPU,设置为正数将在关联的CUDA设备ID上运行模型。你也可以传递原生的torch.devicestr
  • torch_dtype (strtorch.dtype, 可选) — 直接作为 model_kwargs 发送(只是一个更简单的快捷方式)以使用此模型可用的精度 (torch.float16, torch.bfloat16, … 或 "auto")
  • binary_output (bool, 可选, 默认为 False) — 标志指示管道的输出是否应以序列化格式(即pickle)或原始输出数据(例如文本)进行。

使用任何AutoModelForObjectDetection的对象检测流程。此流程预测对象的边界框及其类别。

示例:

>>> 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}}]

>>> # x, y  are expressed relative to the top left hand corner.

了解更多关于使用管道的基础知识,请参阅管道教程

这个目标检测管道目前可以通过使用以下任务标识符从pipeline()加载: "object-detection"

查看可用模型列表,请访问 huggingface.co/models

__call__

< >

( *args **kwargs )

参数

  • inputs (str, List[str], PIL.Image or List[PIL.Image]) — The pipeline handles three types of images:
    • A string containing an HTTP(S) link pointing to an image
    • A string containing a local path to an image
    • An image loaded in PIL directly

    管道接受单个图像或一批图像。批次中的图像必须全部为相同格式:全部为HTTP(S)链接、全部为本地路径或全部为PIL图像。

  • threshold (float, optional, 默认为 0.5) — 进行预测所需的概率。
  • timeout (float, optional, 默认为 None) — 从网络获取图像的最大等待时间(以秒为单位)。如果为 None,则不设置超时,调用可能会永久阻塞。

检测作为输入传递的图像中的对象(边界框和类别)。

VideoClassificationPipeline

transformers.VideoClassificationPipeline

< >

( *args **kwargs )

参数

  • model (PreTrainedModelTFPreTrainedModel) — 管道将用于进行预测的模型。这需要是一个继承自 PreTrainedModel 的模型用于 PyTorch 和 TFPreTrainedModel 用于 TensorFlow.
  • image_processor (BaseImageProcessor) — 管道将使用的图像处理器,用于为模型编码数据。此对象继承自 BaseImageProcessor.
  • modelcard (strModelCard, 可选) — 归因于此管道模型的模型卡。
  • framework (str, optional) — The framework to use, either "pt" for PyTorch or "tf" for TensorFlow. The specified framework must be installed.

    如果没有指定框架,将默认使用当前安装的框架。如果没有指定框架且两个框架都已安装,将默认使用model的框架,如果没有提供模型,则默认使用PyTorch。

  • task (str, 默认为 "") — 管道的一个任务标识符。
  • num_workers (int, 可选, 默认为 8) — 当管道将使用 DataLoader 时(在传递数据集时,对于 Pytorch 模型在 GPU 上),要使用的工作线程数。
  • batch_size (int, 可选, 默认为 1) — 当管道使用 DataLoader 时(当传递数据集时,在 GPU 上用于 Pytorch 模型),使用的批次大小,对于推理来说,这并不总是有益的,请阅读 Batching with pipelines
  • args_parser (ArgumentHandler, 可选) — 负责解析提供的管道参数的对象的引用。
  • device (int, 可选, 默认为 -1) — 用于CPU/GPU支持的设备序号。将此设置为-1将利用CPU,设置为正数将在关联的CUDA设备ID上运行模型。你也可以传递原生的torch.devicestr
  • torch_dtype (strtorch.dtype, 可选) — 直接作为 model_kwargs 发送(只是一个更简单的快捷方式)以使用此模型可用的精度 (torch.float16, torch.bfloat16, … 或 "auto")
  • binary_output (bool, 可选, 默认为 False) — 标志指示管道的输出是否应以序列化格式(即pickle)或原始输出数据(例如文本)进行。

使用任何AutoModelForVideoClassification的视频分类管道。此管道预测视频的类别。

这个视频分类管道目前可以通过使用以下任务标识符从pipeline()加载: "video-classification"

查看可用模型列表,请访问 huggingface.co/models

__call__

< >

( inputs: typing.Union[str, typing.List[str]] = None **kwargs )

参数

  • inputs (str, List[str]) — The pipeline handles three types of videos:
    • A string containing a http link pointing to a video
    • A string containing a local path to a video

    管道接受单个视频或一批视频,然后必须将其作为字符串传递。 批次中的视频必须全部采用相同的格式:全部为http链接或全部为本地路径。

  • top_k (int, 可选, 默认为 5) — 管道将返回的顶部标签数量。如果提供的数字高于模型配置中可用的标签数量,则默认为标签数量。
  • num_frames (int, 可选, 默认为 self.model.config.num_frames) — 从视频中采样的帧数,用于运行分类。如果未提供,将默认为模型配置中指定的帧数。
  • frame_sampling_rate (int, optional, defaults to 1) — 用于从视频中选择帧的采样率。如果未提供,将默认为1,即每一帧都会被使用。
  • function_to_apply(str, 可选, 默认为“softmax”) — 应用于模型输出的函数。默认情况下,管道将对模型输出应用softmax函数。有效选项:[“softmax”, “sigmoid”, “none”]。请注意,传递Python的内置None将默认为“softmax”,因此您需要传递字符串“none”以禁用任何后处理。

为作为输入传递的视频分配标签。

ZeroShotImageClassificationPipeline

transformers.ZeroShotImageClassificationPipeline

< >

( **kwargs )

参数

  • model (PreTrainedModelTFPreTrainedModel) — 管道将用于进行预测的模型。这需要是一个继承自 PreTrainedModel 的 PyTorch 模型和继承自 TFPreTrainedModel 的 TensorFlow 模型。
  • image_processor (BaseImageProcessor) — 管道将使用该图像处理器来为模型编码数据。此对象继承自 BaseImageProcessor.
  • modelcard (strModelCard, 可选) — 此管道的模型所归属的模型卡片。
  • framework (str, optional) — The framework to use, either "pt" for PyTorch or "tf" for TensorFlow. The specified framework must be installed.

    如果没有指定框架,将默认使用当前安装的框架。如果没有指定框架且两个框架都已安装,将默认使用model的框架,如果没有提供模型,则默认使用PyTorch。

  • task (str, 默认为 "") — 管道的一个任务标识符。
  • num_workers (int, optional, 默认为 8) — 当管道将使用 DataLoader 时(在传递数据集时,对于 Pytorch 模型在 GPU 上),要使用的工作线程数。
  • batch_size (int, 可选, 默认为 1) — 当管道使用 DataLoader 时(当传递数据集时,在 GPU 上用于 Pytorch 模型),使用的批次大小,对于推理来说,这并不总是有益的,请阅读 Batching with pipelines
  • args_parser (ArgumentHandler, 可选) — 负责解析提供的管道参数的对象的引用。
  • device (int, 可选, 默认为 -1) — 用于CPU/GPU支持的设备序号。将此设置为-1将利用CPU,设置为正数将在关联的CUDA设备ID上运行模型。你也可以传递原生的torch.devicestr
  • torch_dtype (strtorch.dtype, 可选) — 直接作为 model_kwargs 发送(只是一个更简单的快捷方式)以使用此模型可用的精度 (torch.float16, torch.bfloat16, … 或 "auto")
  • binary_output (bool, optional, defaults to False) — 标志指示管道的输出是否应以序列化格式(即pickle)或原始输出数据(例如文本)进行。

使用CLIPModel的零样本图像分类管道。当您提供一张图像和一组candidate_labels时,此管道会预测图像的类别。

示例:

>>> 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'}]

了解更多关于使用管道的基础知识,请参阅管道教程

这个图像分类管道目前可以从pipeline()使用以下任务标识符加载: "zero-shot-image-classification"

查看可用模型列表,请访问 huggingface.co/models

__call__

< >

( image: typing.Union[str, typing.List[str], ForwardRef('Image'), typing.List[ForwardRef('Image')]] = None **kwargs )

参数

  • image (str, List[str], PIL.ImageList[PIL.Image]) — 管道处理三种类型的图像:
    • 包含指向图像的http链接的字符串
    • 包含图像本地路径的字符串
    • 直接加载到PIL中的图像
  • candidate_labels (List[str]) — 此图像的候选标签。它们将使用hypothesis_template进行格式化。
  • hypothesis_template (str, optional, defaults to "This is a photo of {}") — 用于与candidate_labels结合使用的格式,通过将占位符替换为candidate_labels来尝试图像分类。如果candidate_labels已经格式化,则传递“{}”。
  • timeout (float, optional, 默认为 None) — 从网络获取图像的最大等待时间(以秒为单位)。如果为 None,则不设置超时,调用可能会永久阻塞。

为作为输入传递的图像分配标签。

ZeroShotObjectDetectionPipeline

transformers.ZeroShotObjectDetectionPipeline

< >

( **kwargs )

参数

  • model (PreTrainedModelTFPreTrainedModel) — 管道将用于进行预测的模型。这需要是从 PreTrainedModel 继承的模型(对于 PyTorch)和从 TFPreTrainedModel 继承的模型(对于 TensorFlow)。
  • image_processor (BaseImageProcessor) — 管道将使用该图像处理器来为模型编码数据。此对象继承自 BaseImageProcessor.
  • modelcard (strModelCard, 可选) — 归因于此管道模型的模型卡。
  • framework (str, optional) — The framework to use, either "pt" for PyTorch or "tf" for TensorFlow. The specified framework must be installed.

    如果没有指定框架,将默认使用当前安装的框架。如果没有指定框架且两个框架都已安装,将默认使用model的框架,如果没有提供模型,则默认使用PyTorch。

  • task (str, 默认为 "") — 管道的任务标识符。
  • num_workers (int, 可选, 默认为 8) — 当管道将使用 DataLoader 时(在传递数据集时,对于 Pytorch 模型在 GPU 上),要使用的工作线程数。
  • batch_size (int, 可选, 默认为 1) — 当管道使用 DataLoader 时(当传递数据集时,在 GPU 上用于 Pytorch 模型),使用的批次大小,对于推理来说,这并不总是有益的,请阅读 Batching with pipelines
  • args_parser (ArgumentHandler, 可选) — 负责解析提供的管道参数的对象的引用。
  • device (int, 可选, 默认为 -1) — 用于CPU/GPU支持的设备序号。将此设置为-1将利用CPU,设置为正数将在关联的CUDA设备ID上运行模型。你也可以传递原生的torch.devicestr
  • torch_dtype (strtorch.dtype, 可选) — 直接作为 model_kwargs 发送(只是一个更简单的快捷方式)以使用此模型可用的精度 (torch.float16, torch.bfloat16, … 或 "auto")
  • binary_output (bool, optional, 默认为 False) — 标志指示管道的输出是否应以序列化格式(即pickle)或原始输出数据(例如文本)进行。

使用OwlViTForObjectDetection的零样本目标检测管道。当您提供图像和一组candidate_labels时,该管道会预测对象的边界框。

示例:

>>> 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}}]

了解更多关于使用管道的基础知识,请参阅管道教程

这个目标检测管道目前可以通过使用以下任务标识符从pipeline()加载: "zero-shot-object-detection"

查看可用模型列表,请访问 huggingface.co/models

__call__

< >

( image: typing.Union[str, ForwardRef('Image.Image'), typing.List[typing.Dict[str, typing.Any]]] candidate_labels: typing.Union[str, typing.List[str]] = None **kwargs )

参数

  • image (str, PIL.Image or List[Dict[str, Any]]) — The pipeline handles three types of images:
    • A string containing an http url pointing to an image
    • A string containing a local path to an image
    • An image loaded in PIL directly

    您可以使用此参数直接发送图像列表、数据集或生成器,如下所示:

检测作为输入传递的图像中的对象(边界框和类别)。

自然语言处理

可用于自然语言处理任务的管道包括以下内容。

FillMaskPipeline

transformers.FillMaskPipeline

< >

( 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 )

参数

  • model (PreTrainedModelTFPreTrainedModel) — 管道将用于进行预测的模型。这需要是一个继承自 PreTrainedModel 的模型用于 PyTorch 和 TFPreTrainedModel 用于 TensorFlow.
  • tokenizer (PreTrainedTokenizer) — 管道将使用的分词器,用于为模型编码数据。该对象继承自 PreTrainedTokenizer.
  • modelcard (strModelCard, 可选) — 归因于此管道模型的模型卡。
  • framework (str, optional) — The framework to use, either "pt" for PyTorch or "tf" for TensorFlow. The specified framework must be installed.

    如果没有指定框架,将默认使用当前安装的框架。如果没有指定框架且两个框架都已安装,将默认使用model的框架,如果没有提供模型,则默认使用PyTorch。

  • task (str, 默认为 "") — 管道的一个任务标识符。
  • num_workers (int, 可选, 默认为 8) — 当管道将使用 DataLoader 时(在传递数据集时,对于 Pytorch 模型在 GPU 上),要使用的工作线程数。
  • batch_size (int, optional, defaults to 1) — 当管道使用DataLoader时(当传递数据集时,在GPU上用于Pytorch模型),使用的批次大小,对于推理来说,这并不总是有益的,请阅读Batching with pipelines.
  • args_parser (ArgumentHandler, 可选) — 负责解析提供的管道参数的对象的引用。
  • device (int, 可选, 默认为 -1) — 用于CPU/GPU支持的设备序号。将此设置为-1将利用CPU,设置为正数将在关联的CUDA设备ID上运行模型。您也可以传递原生的torch.devicestr
  • torch_dtype (strtorch.dtype, 可选) — 直接作为 model_kwargs 发送(只是一个更简单的快捷方式)以使用此模型可用的精度 (torch.float16, torch.bfloat16, … 或 "auto")
  • binary_output (bool, 可选, 默认为 False) — 标志指示管道的输出是否应以序列化格式(即pickle)或原始输出数据(例如文本)进行。
  • top_k (int, optional, 默认为 5) — 返回的预测数量。
  • targets (strList[str], 可选) — 当传入时,模型将把分数限制在传入的目标上,而不是在整个词汇表中查找。如果提供的目标不在模型词汇表中,它们将被分词,并使用第一个生成的词(会有警告,并且可能会更慢)。
  • tokenizer_kwargs (dict, optional) — 传递给分词器的额外关键字参数字典。

使用任何ModelWithLMHead的掩码语言建模预测管道。有关更多信息,请参阅掩码语言建模示例

示例:

>>> 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.'}]

了解更多关于使用管道的基础知识,请参阅管道教程

这个掩码填充管道目前可以通过以下任务标识符从pipeline()加载: "fill-mask"

此管道可以使用的模型是那些已经通过掩码语言建模目标训练的模型,其中包括库中的双向模型。查看最新的可用模型列表,请访问 huggingface.co/models

此管道仅适用于恰好有一个标记被屏蔽的输入。实验性:我们添加了对多个屏蔽的支持。返回的值是原始模型输出,对应于可能期望联合概率的不相交概率(参见讨论)。

此管道现在支持 tokenizer_kwargs。例如,尝试:

>>> 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__

< >

( inputs **kwargs ) 一个列表或一个包含dict的列表

参数

  • inputs (strList[str]) — 一个或多个带有掩码标记的文本(或一个提示列表)。
  • targets (strList[str], 可选) — 当传入时,模型将限制分数为传入的目标,而不是在整个词汇表中查找。如果提供的目标不在模型词汇表中,它们将被分词,并使用第一个生成的词(会有警告,并且可能会较慢)。
  • top_k (int, optional) — 当传递时,覆盖要返回的预测数量。

返回

一个列表或一个包含dict的列表的列表

每个结果都作为字典列表返回,包含以下键:

  • sequence (str) — 带有掩码标记预测的相应输入。
  • score (float) — 相应的概率。
  • token (int) — 预测的标记ID(用于替换掩码标记)。
  • token_str (str) — 预测的标记(用于替换掩码标记)。

在作为输入提供的文本中填充被遮蔽的标记。

QuestionAnsweringPipeline

transformers.QuestionAnsweringPipeline

< >

( 模型: typing.Union[ForwardRef('PreTrainedModel'), ForwardRef('TFPreTrainedModel')] 分词器: PreTrainedTokenizer 模型卡片: typing.Optional[transformers.modelcard.ModelCard] = None 框架: typing.Optional[str] = None 任务: str = '' **kwargs )

参数

  • model (PreTrainedModelTFPreTrainedModel) — 管道将用于进行预测的模型。这需要是一个继承自 PreTrainedModel 的 PyTorch 模型和继承自 TFPreTrainedModel 的 TensorFlow 模型。
  • tokenizer (PreTrainedTokenizer) — 管道将使用的分词器,用于为模型编码数据。该对象继承自 PreTrainedTokenizer.
  • modelcard (strModelCard, 可选) — 归因于此管道模型的模型卡。
  • framework (str, optional) — The framework to use, either "pt" for PyTorch or "tf" for TensorFlow. The specified framework must be installed.

    如果没有指定框架,将默认使用当前安装的框架。如果没有指定框架且两个框架都已安装,将默认使用model的框架,如果没有提供模型,则默认使用PyTorch。

  • task (str, 默认为 "") — 管道的一个任务标识符。
  • num_workers (int, 可选, 默认为 8) — 当管道将使用 DataLoader 时(在传递数据集时,对于 Pytorch 模型在 GPU 上),要使用的工作线程数。
  • batch_size (int, 可选, 默认为 1) — 当管道使用 DataLoader 时(当传递数据集时,在 GPU 上用于 Pytorch 模型),使用的批次大小,对于推理来说,这并不总是有益的,请阅读 Batching with pipelines
  • args_parser (ArgumentHandler, 可选) — 负责解析提供的管道参数的对象的引用。
  • device (int, 可选, 默认为 -1) — 用于CPU/GPU支持的设备序号。将此设置为-1将利用CPU,设置为正数将在关联的CUDA设备ID上运行模型。你也可以传递原生的torch.devicestr
  • torch_dtype (strtorch.dtype, 可选) — 直接作为 model_kwargs 发送(只是一个更简单的快捷方式)以使用此模型可用的精度 (torch.float16, torch.bfloat16, … 或 "auto")
  • binary_output (bool, 可选, 默认为 False) — 标志指示管道的输出是否应以序列化格式(即pickle)或原始输出数据(例如文本)进行。

使用任何ModelForQuestionAnswering的问答管道。更多信息请参见问答示例

示例:

>>> 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'}

了解更多关于使用管道的基础知识,请参阅管道教程

这个问答管道目前可以从pipeline()使用以下任务标识符加载: "question-answering"

此管道可以使用的模型是已经在问答任务上进行了微调的模型。请参阅 huggingface.co/models 上最新的可用模型列表。

__call__

< >

( *args **kwargs ) 一个 dict 或一个 dict 的列表

参数

  • 问题 (strList[str]) — 一个或多个问题(必须与 context 参数一起使用)。
  • 上下文 (strList[str]) — 与问题相关的一个或多个上下文(必须与 question 参数一起使用)。
  • top_k (int, 可选, 默认为 1) — 返回的答案数量(将按可能性顺序选择)。请注意,如果上下文中没有足够的选项,我们将返回少于 top_k 的答案。
  • doc_stride (int, optional, 默认为 128) — 如果上下文太长,无法与模型的问题一起适应,它将被分成几个块,并有一些重叠。此参数控制该重叠的大小。
  • max_answer_len (int, optional, 默认为 15) — 预测答案的最大长度(例如,仅考虑长度较短的答案)。
  • max_seq_len (int, 可选, 默认为 384) — 传递给模型的每个块的总句子(上下文 + 问题)的最大长度(以标记为单位)。如果需要,上下文将被分成几个块(使用 doc_stride 作为重叠)。
  • max_question_len (int, optional, defaults to 64) — 问题在分词后的最大长度。如果超过这个长度,将会被截断。
  • handle_impossible_answer (bool, optional, defaults to False) — 是否接受不可能作为答案。
  • align_to_words (bool, 可选, 默认为 True) — 尝试将答案与真实单词对齐。提高空格分隔语言的质量。可能会对非空格分隔语言(如日语或中文)造成影响

返回

一个dict或一个dict的列表

每个结果都以字典形式返回,包含以下键:

  • score (float) — 与答案相关的概率。
  • start (int) — 答案的字符起始索引(在输入的标记化版本中)。
  • end (int) — 答案的字符结束索引(在输入的标记化版本中)。
  • answer (str) — 问题的答案。

使用上下文回答输入的问题。

create_sample

< >

( question: typing.Union[str, typing.List[str]] context: typing.Union[str, typing.List[str]] ) 一个或多个 SquadExample 的列表

参数

  • 问题 (strList[str]) — 提出的问题。
  • context (strList[str]) — 我们将在此上下文中寻找答案。

返回

一个或多个SquadExample的列表

对应的 SquadExample 分组问题和上下文。

QuestionAnsweringPipeline 内部利用了 SquadExample。这个辅助方法封装了将所有问题和上下文转换为 SquadExample 的逻辑。

我们目前支持抽取式问答。

span_to_answer

< >

( text: str start: int end: int ) 类似字典的 `{‘answer’

参数

  • text (str) — 从中提取答案的实际上下文。
  • start (int) — 答案开始的标记索引.
  • end (int) — 答案结束的标记索引。

返回

类似于字典的 `{‘answer’

str, ‘start’: int, ‘end’: int}`

从令牌概率解码时,此方法将令牌索引映射到初始上下文中的实际单词。

SummarizationPipeline

transformers.SummarizationPipeline

< >

( *args **kwargs )

参数

  • model (PreTrainedModelTFPreTrainedModel) — 管道将用于进行预测的模型。这需要是一个继承自 PreTrainedModel 的模型(用于 PyTorch)和 TFPreTrainedModel 的模型(用于 TensorFlow)。
  • tokenizer (PreTrainedTokenizer) — 管道将使用的分词器,用于为模型编码数据。该对象继承自 PreTrainedTokenizer.
  • modelcard (strModelCard, 可选) — 此管道的模型所归属的模型卡片。
  • framework (str, optional) — The framework to use, either "pt" for PyTorch or "tf" for TensorFlow. The specified framework must be installed.

    如果没有指定框架,将默认使用当前安装的框架。如果没有指定框架且两个框架都已安装,将默认使用model的框架,如果没有提供模型,则默认使用PyTorch。

  • task (str, defaults to "") — 管道的一个任务标识符。
  • num_workers (int, optional, 默认为 8) — 当管道将使用 DataLoader 时(在传递数据集时,对于 Pytorch 模型在 GPU 上),要使用的工作线程数。
  • batch_size (int, 可选, 默认为 1) — 当管道使用 DataLoader 时(当传递数据集时,在 GPU 上用于 Pytorch 模型),使用的批次大小,对于推理来说,这并不总是有益的,请阅读 Batching with pipelines
  • args_parser (ArgumentHandler, optional) — 负责解析提供的管道参数的对象的引用。
  • device (int, 可选, 默认为 -1) — 用于CPU/GPU支持的设备序号。将此设置为-1将利用CPU,设置为正数将在关联的CUDA设备ID上运行模型。您也可以传递原生的torch.devicestr
  • torch_dtype (strtorch.dtype, 可选) — 直接作为 model_kwargs 发送(只是一个更简单的快捷方式)以使用此模型可用的精度 (torch.float16, torch.bfloat16, … 或 "auto")
  • binary_output (bool, 可选, 默认为 False) — 标志指示管道的输出是否应以序列化格式(即pickle)或原始输出数据(例如文本)进行。

总结新闻文章和其他文档。

这个摘要生成管道目前可以通过使用以下任务标识符从pipeline()加载: "summarization"

该管道可以使用的模型是已经在摘要任务上微调过的模型,目前包括’bart-large-cnn’, ’google-t5/t5-small’, ’google-t5/t5-base’, ’google-t5/t5-large’, ’google-t5/t5-3b’, ’google-t5/t5-11b’。查看最新的可用模型列表,请访问huggingface.co/models。有关可用参数的列表,请参阅以下文档

用法:

# use bart in pytorch
summarizer = pipeline("summarization")
summarizer("An apple a day, keeps the doctor away", min_length=5, max_length=20)

# use t5 in tf
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__

< >

( *args **kwargs ) 一个列表或一个包含dict的列表

参数

  • 文档 (strList[str]) — 一个或多个文章(或一个文章列表)进行摘要。
  • return_text (bool, optional, defaults to True) — 是否在输出中包含解码后的文本
  • return_tensors (bool, optional, defaults to False) — 是否在输出中包含预测的张量(作为标记索引)。
  • clean_up_tokenization_spaces (bool, optional, defaults to False) — 是否清理文本输出中可能存在的额外空格。
  • generate_kwargs — 传递给模型生成方法的额外关键字参数(请参阅与您的框架对应的生成方法 here)。

返回

一个列表或一个包含dict的列表的列表

每个结果都作为一个字典返回,包含以下键:

  • summary_text (str, 当 return_text=True 时存在) — 对应输入的摘要。
  • summary_token_ids (torch.Tensortf.Tensor, 当 return_tensors=True 时存在) — 摘要的令牌ID。

总结作为输入提供的文本。

TableQuestionAnsweringPipeline

transformers.TableQuestionAnsweringPipeline

< >

( args_parser = *args **kwargs )

参数

  • model (PreTrainedModelTFPreTrainedModel) — 管道将用于进行预测的模型。这需要是一个继承自 PreTrainedModel 的模型用于 PyTorch 和 TFPreTrainedModel 用于 TensorFlow.
  • tokenizer (PreTrainedTokenizer) — 管道将使用的分词器,用于为模型编码数据。该对象继承自 PreTrainedTokenizer.
  • modelcard (strModelCard, 可选) — 归因于此管道模型的模型卡。
  • framework (str, optional) — The framework to use, either "pt" for PyTorch or "tf" for TensorFlow. The specified framework must be installed.

    如果没有指定框架,将默认使用当前安装的框架。如果没有指定框架且两个框架都已安装,将默认使用model的框架,如果没有提供模型,则默认使用PyTorch。

  • task (str, 默认为 "") — 管道的任务标识符。
  • num_workers (int, 可选, 默认为 8) — 当管道将使用 DataLoader 时(在传递数据集时,对于 Pytorch 模型在 GPU 上),要使用的工作线程数。
  • batch_size (int, 可选, 默认为 1) — 当管道使用 DataLoader 时(当传递数据集时,在 GPU 上用于 Pytorch 模型),使用的批次大小,对于推理来说,这并不总是有益的,请阅读 Batching with pipelines
  • args_parser (ArgumentHandler, 可选) — 负责解析提供的管道参数的对象的引用。
  • device (int, 可选, 默认为 -1) — 用于CPU/GPU支持的设备序号。将此设置为-1将利用CPU,设置为正数将在关联的CUDA设备ID上运行模型。你也可以传递原生的torch.devicestr
  • torch_dtype (strtorch.dtype, 可选) — 直接作为 model_kwargs 发送(只是一个更简单的快捷方式)以使用此模型可用的精度 (torch.float16, torch.bfloat16, … 或 "auto")
  • binary_output (bool, 可选, 默认为 False) — 标志指示管道的输出是否应以序列化格式(即pickle)或原始输出数据(例如文本)进行。

使用ModelForTableQuestionAnswering的表格问答管道。此管道仅在PyTorch中可用。

示例:

>>> 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'}

了解更多关于使用管道的基础知识,请参阅管道教程

这个表格问答管道目前可以从pipeline()加载,使用以下任务标识符:"table-question-answering"

此管道可以使用的模型是已经在表格问答任务上微调过的模型。 请参阅huggingface.co/models上的最新可用模型列表。

__call__

< >

( *args **kwargs ) 包含结果的字典或字典列表

参数

  • table (pd.DataFrameDict) — Pandas DataFrame 或将被转换为包含所有表格值的 DataFrame 的字典。 请参阅上面的字典示例。
  • query (strList[str]) — 将与表格一起发送到模型的查询或查询列表。
  • sequential (bool, 可选, 默认为 False) — 是否按顺序进行推理或作为批处理。批处理速度更快,但像SQA这样的模型需要按顺序进行推理,以便在序列中提取关系,考虑到它们的对话性质。
  • padding (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, strTapasTruncationStrategy, 可选, 默认为 False) — 激活并控制截断。接受以下值:
    • True'drop_rows_to_fit': 截断到由参数 max_length 指定的最大长度, 或者如果未提供该参数,则截断到模型可接受的最大输入长度。这将逐行截断,从表中删除行。
    • False'do_not_truncate' (默认): 不进行截断(即,可以输出序列长度大于模型最大可接受输入大小的批次)。

返回

包含结果的字典或字典列表

每个结果都是一个包含以下键的字典:

  • answer (str) — 给定表格的查询答案。如果有聚合器,答案将以 AGGREGATOR > 开头。
  • coordinates (List[Tuple[int, int]]) — 答案单元格的坐标。
  • cells (List[str]) — 由答案单元格值组成的字符串列表。
  • aggregator (str) — 如果模型有聚合器,则返回聚合器。

根据表格回答查询。该管道接受以下几种类型的输入,具体如下:

  • 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}])

table 参数应该是一个字典或从该字典构建的 DataFrame,包含整个表:

示例:

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"],
}

这个字典可以直接传入,也可以转换为pandas DataFrame:

示例:

import pandas as pd

table = pd.DataFrame.from_dict(data)

文本分类管道

transformers.TextClassificationPipeline

< >

( **kwargs )

参数

  • model (PreTrainedModelTFPreTrainedModel) — 管道将用于进行预测的模型。这需要是一个继承自 PreTrainedModel 的 PyTorch 模型和继承自 TFPreTrainedModel 的 TensorFlow 模型。
  • tokenizer (PreTrainedTokenizer) — 管道将使用的分词器,用于为模型编码数据。该对象继承自 PreTrainedTokenizer.
  • modelcard (strModelCard, 可选) — 归因于此管道模型的模型卡。
  • framework (str, optional) — The framework to use, either "pt" for PyTorch or "tf" for TensorFlow. The specified framework must be installed.

    如果没有指定框架,将默认使用当前安装的框架。如果没有指定框架且两个框架都已安装,将默认使用model的框架,如果没有提供模型,则默认使用PyTorch。

  • task (str, 默认为 "") — 管道的一个任务标识符。
  • num_workers (int, 可选, 默认为 8) — 当管道将使用 DataLoader 时(在传递数据集时,对于 Pytorch 模型在 GPU 上),要使用的工作线程数。
  • batch_size (int, 可选, 默认为 1) — 当管道使用 DataLoader 时(当传递数据集时,在 GPU 上用于 Pytorch 模型),使用的批次大小,对于推理来说,这并不总是有益的,请阅读 Batching with pipelines
  • args_parser (ArgumentHandler, 可选) — 负责解析提供的管道参数的对象的引用。
  • device (int, 可选, 默认为 -1) — 用于CPU/GPU支持的设备序号。将此设置为-1将利用CPU,设置为正数将在关联的CUDA设备ID上运行模型。你也可以传递原生的torch.devicestr
  • torch_dtype (strtorch.dtype, 可选) — 直接作为 model_kwargs 发送(只是一个更简单的快捷方式)以使用此模型可用的精度 (torch.float16, torch.bfloat16, … 或 "auto")
  • binary_output (bool, 可选, 默认为 False) — 标志指示管道的输出是否应以序列化格式(即pickle)或原始输出数据(例如文本)进行。
  • return_all_scores (bool, optional, defaults to False) — 是否返回所有预测分数或仅返回预测类别的分数。
  • function_to_apply (str, 可选, 默认为 "default") — 应用于模型输出以获取分数的函数。接受四种不同的值:
    • "default": 如果模型有单个标签,将在输出上应用sigmoid函数。如果模型 有多个标签,将在输出上应用softmax函数。在回归任务的情况下,不会 在输出上应用任何函数。
    • "sigmoid": 在输出上应用sigmoid函数。
    • "softmax": 在输出上应用softmax函数。
    • "none": 不在输出上应用任何函数。

使用任何ModelForSequenceClassification的文本分类管道。有关更多信息,请参阅序列分类示例

示例:

>>> 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}]

了解更多关于使用管道的基础知识,请参阅管道教程

这个文本分类管道目前可以从pipeline()加载,使用以下任务标识符: "sentiment-analysis"(用于根据积极或消极情绪对序列进行分类)。

如果有多个分类标签可用(model.config.num_labels >= 2),管道将对结果运行softmax。如果只有一个标签,管道将对结果运行sigmoid。在回归任务的情况下(model.config.problem_type == "regression"),不会对输出应用任何函数。

此管道可以使用的模型是已经在序列分类任务上进行了微调的模型。请参阅 huggingface.co/models 上最新的可用模型列表。

__call__

< >

( inputs **kwargs ) 一个列表或一个包含dict的列表

参数

  • inputs (strList[str]Dict[str], 或 List[Dict[str]]) — 一个或多个要分类的文本。为了使用文本对进行分类,您可以发送包含 {"text", "text_pair"} 键的字典,或这些字典的列表。
  • top_k (int, 可选, 默认为 1) — 返回多少结果.
  • function_to_apply (str, optional, defaults to "default") — The function to apply to the model outputs in order to retrieve the scores. Accepts four different values:

    如果未指定此参数,则将根据标签数量应用以下函数:

    • If problem type is regression, will not apply any function on the output.
    • 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.

返回

一个列表或一个包含dict的列表的列表

每个结果都作为字典列表返回,包含以下键:

  • label (str) — 预测的标签。
  • score (float) — 对应的概率。

如果使用了top_k,每个标签都会返回一个这样的字典。

对作为输入提供的文本进行分类。

文本生成管道

transformers.TextGenerationPipeline

< >

( *args **kwargs )

参数

  • model (PreTrainedModelTFPreTrainedModel) — 管道将用于进行预测的模型。这需要是一个继承自 PreTrainedModel 的 PyTorch 模型和继承自 TFPreTrainedModel 的 TensorFlow 模型。
  • tokenizer (PreTrainedTokenizer) — 管道将使用的分词器,用于为模型编码数据。该对象继承自 PreTrainedTokenizer.
  • modelcard (strModelCard, 可选) — 此管道的模型所归属的模型卡片。
  • framework (str, optional) — The framework to use, either "pt" for PyTorch or "tf" for TensorFlow. The specified framework must be installed.

    如果没有指定框架,将默认使用当前安装的框架。如果没有指定框架且两个框架都已安装,将默认使用model的框架,如果没有提供模型,则默认使用PyTorch。

  • task (str, 默认为 "") — 管道的一个任务标识符。
  • num_workers (int, 可选, 默认为 8) — 当管道使用 DataLoader 时(在传递数据集时,对于 Pytorch 模型在 GPU 上),要使用的工作线程数。
  • batch_size (int, 可选, 默认为 1) — 当管道使用 DataLoader 时(当传递数据集时,在 GPU 上用于 Pytorch 模型),使用的批次大小,对于推理来说,这并不总是有益的,请阅读 Batching with pipelines
  • args_parser (ArgumentHandler, 可选) — 负责解析提供的管道参数的对象的引用。
  • device (int, 可选, 默认为 -1) — 用于CPU/GPU支持的设备序号。将此设置为-1将利用CPU,设置为正数将在关联的CUDA设备ID上运行模型。你也可以传递原生的torch.devicestr
  • torch_dtype (strtorch.dtype, 可选) — 直接作为 model_kwargs 发送(只是一个更简单的快捷方式)以使用此模型可用的精度 (torch.float16, torch.bfloat16, … 或 "auto")
  • binary_output (bool, optional, defaults to False) — 标志指示管道的输出是否应以序列化格式(即pickle)或原始输出数据(例如文本)进行。

使用任何ModelWithLMHead的语言生成管道。此管道预测将跟随指定文本提示的单词。当底层模型是对话模型时,它还可以接受一个或多个聊天,在这种情况下,管道将以聊天模式运行,并通过添加其响应来继续聊天。每个聊天采用字典列表的形式,其中每个字典包含“role”和“content”键。

示例:

>>> 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"}]

>>> # These parameters will return suggestions, and only the newly created text making it easier for prompting suggestions.
>>> 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")
>>> # Zephyr-beta is a conversational model, so let's pass it a chat instead of a single string
>>> 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'}]}]

了解更多关于在管道教程中使用管道的基础知识。您可以向此管道传递文本生成参数以控制停止标准、解码策略等。了解更多关于文本生成参数的信息,请访问文本生成策略文本生成

目前可以通过以下任务标识符从pipeline()加载此语言生成管道: "text-generation"

此管道可以使用的模型是已经通过自回归语言建模目标训练的模型。请参阅可用的文本生成模型列表和[huggingface.co/models]上的对话模型列表。

__call__

< >

( text_inputs **kwargs ) 一个列表或一个包含dict的列表的列表

参数

  • text_inputs (str, List[str], List[Dict[str, str]], or List[List[Dict[str, str]]]) — 一个或多个提示(或一个提示列表)来完成。如果传递的是字符串或字符串列表, 此管道将继续每个提示。或者,可以传递一个“聊天”,形式为具有“role”和“content”键的字典列表, 或此类聊天的列表。当传递聊天时,模型的聊天模板将用于在传递给模型之前格式化它们。
  • return_tensors (bool, 可选, 默认为 False) — 返回输出中的预测张量(作为标记索引)。如果设置为 True,则不返回解码后的文本。
  • return_text (bool, optional) — 返回解码后的文本在输出中。
  • return_full_text (bool, 可选, 默认为 True) — 如果设置为 False,则只返回添加的文本,否则返回完整文本。不能与 return_text 同时指定。
  • clean_up_tokenization_spaces (bool, optional, defaults to True) — 是否清理文本输出中可能存在的额外空格。
  • continue_final_message( bool, optional) — 这表示您希望模型继续输入聊天中的最后一条消息,而不是开始一条新的消息,从而允许您“预填充”其响应。 默认情况下,当输入聊天中的最后一条消息具有assistant角色时,此值为True,否则为False,但您可以通过设置此标志手动覆盖该行为。
  • prefix (str, optional) — 添加到提示的前缀。
  • handle_long_generation (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 adress 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)
  • generate_kwargs (dict, optional) — 传递给模型生成方法的额外关键字参数(请参阅与您的框架对应的生成方法 here)。

返回

一个列表或一个包含dict的列表的列表

返回以下字典之一(不能同时返回generated_textgenerated_token_ids的组合):

  • generated_text (str, 当return_text=True时存在) — 生成的文本。
  • generated_token_ids (torch.Tensortf.Tensor, 当return_tensors=True时存在) — 生成文本的令牌ID。

完成作为输入给出的提示。

Text2TextGenerationPipeline

transformers.Text2TextGenerationPipeline

< >

( *args **kwargs )

参数

  • model (PreTrainedModelTFPreTrainedModel) — 管道将用于进行预测的模型。这需要是一个继承自 PreTrainedModel 的模型用于 PyTorch 和 TFPreTrainedModel 用于 TensorFlow.
  • tokenizer (PreTrainedTokenizer) — 管道将使用的分词器,用于为模型编码数据。该对象继承自 PreTrainedTokenizer.
  • modelcard (strModelCard, 可选) — 归因于此管道模型的模型卡。
  • framework (str, optional) — The framework to use, either "pt" for PyTorch or "tf" for TensorFlow. The specified framework must be installed.

    如果没有指定框架,将默认使用当前安装的框架。如果没有指定框架且两个框架都已安装,将默认使用model的框架,如果没有提供模型,则默认使用PyTorch。

  • task (str, 默认为 "") — 管道的一个任务标识符。
  • num_workers (int, optional, 默认为 8) — 当管道将使用 DataLoader 时(在传递数据集时,对于 Pytorch 模型在 GPU 上),要使用的工作线程数。
  • batch_size (int, 可选, 默认为 1) — 当管道使用 DataLoader 时(当传递数据集时,在 GPU 上用于 Pytorch 模型),使用的批次大小,对于推理来说,这并不总是有益的,请阅读 Batching with pipelines
  • args_parser (ArgumentHandler, 可选) — 负责解析提供的管道参数的对象的引用。
  • 设备 (int, 可选, 默认为 -1) — 用于CPU/GPU支持的设备序号。将此设置为-1将利用CPU,设置为正数将在关联的CUDA设备ID上运行模型。你也可以传递原生的torch.devicestr
  • torch_dtype (strtorch.dtype, 可选) — 直接作为 model_kwargs 发送(只是一个更简单的快捷方式)以使用此模型可用的精度 (torch.float16, torch.bfloat16, … 或 "auto")
  • binary_output (bool, 可选, 默认为 False) — 标志指示管道的输出是否应以序列化格式(即pickle)或原始输出数据(例如文本)进行。

使用seq2seq模型进行文本到文本生成的管道。

示例:

>>> 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?'}]

了解更多关于在管道教程中使用管道的基础知识。您可以向此管道传递文本生成参数以控制停止标准、解码策略等。了解更多关于文本生成参数的信息,请访问文本生成策略文本生成

这个Text2TextGenerationPipeline管道目前可以通过使用以下任务标识符从pipeline()加载:"text2text-generation"

此管道可以使用的模型是已经在翻译任务上微调过的模型。请参阅 huggingface.co/models 上最新的可用模型列表。有关可用参数的列表,请参阅 以下文档

用法:

text2text_generator = pipeline("text2text-generation")
text2text_generator("question: What is 42 ? context: 42 is the answer to life, the universe and everything")

__call__

< >

( *args **kwargs ) 一个列表或一个包含dict的列表

参数

  • args (str or List[str]) — 编码器的输入文本。
  • return_tensors (bool, optional, defaults to False) — 是否在输出中包含预测的张量(作为标记索引)。
  • return_text (bool, 可选, 默认为 True) — 是否在输出中包含解码后的文本。
  • clean_up_tokenization_spaces (bool, optional, defaults to False) — 是否清理文本输出中可能存在的额外空格。
  • 截断 (TruncationStrategy, 可选, 默认为 TruncationStrategy.DO_NOT_TRUNCATE) — 管道中标记化的截断策略。TruncationStrategy.DO_NOT_TRUNCATE (默认)将永远不会截断,但有时希望截断输入以适应模型的 max_length,而不是在后续过程中抛出错误。
  • generate_kwargs — 传递给模型生成方法的额外关键字参数(请参阅与您的框架对应的生成方法 here)。

返回

一个列表或一个包含dict的列表的列表

每个结果都作为一个字典返回,包含以下键:

  • generated_text (str, 当 return_text=True 时存在) — 生成的文本。
  • generated_token_ids (torch.Tensortf.Tensor, 当 return_tensors=True 时存在) — 生成文本的令牌ID。

使用给定的输入文本生成输出文本。

check_inputs

< >

( input_length: int min_length: int max_length: int )

检查给定输入是否可能对模型有问题。

TokenClassificationPipeline

transformers.TokenClassificationPipeline

< >

( args_parser = *args **kwargs )

参数

  • model (PreTrainedModelTFPreTrainedModel) — 管道将用于进行预测的模型。这需要是一个继承自 PreTrainedModel 的模型(适用于 PyTorch)和 TFPreTrainedModel 的模型(适用于 TensorFlow)。
  • tokenizer (PreTrainedTokenizer) — 管道将使用的分词器,用于为模型编码数据。该对象继承自 PreTrainedTokenizer.
  • modelcard (strModelCard, 可选) — 归因于此管道模型的模型卡。
  • framework (str, optional) — The framework to use, either "pt" for PyTorch or "tf" for TensorFlow. The specified framework must be installed.

    如果没有指定框架,将默认使用当前安装的框架。如果没有指定框架且两个框架都已安装,将默认使用model的框架,如果没有提供模型,则默认使用PyTorch。

  • task (str, 默认为 "") — 管道的任务标识符。
  • num_workers (int, 可选, 默认为 8) — 当管道将使用 DataLoader 时(在传递数据集时,对于 Pytorch 模型在 GPU 上),要使用的工作线程数。
  • batch_size (int, 可选, 默认为 1) — 当管道使用 DataLoader 时(当传递数据集时,在 GPU 上用于 Pytorch 模型),使用的批次大小,对于推理来说,这并不总是有益的,请阅读 Batching with pipelines
  • args_parser (ArgumentHandler, 可选) — 负责解析提供的管道参数的对象的引用。
  • device (int, 可选, 默认为 -1) — 用于CPU/GPU支持的设备序号。将此设置为-1将利用CPU,设置为正数将在关联的CUDA设备ID上运行模型。你也可以传递原生的torch.devicestr
  • torch_dtype (strtorch.dtype, 可选) — 直接作为 model_kwargs 发送(只是一个更简单的快捷方式)以使用此模型可用的精度 (torch.float16, torch.bfloat16, … 或 "auto")
  • binary_output (bool, optional, 默认为 False) — 标志指示管道的输出是否应以序列化格式(即pickle)或原始输出数据(例如文本)进行。
  • ignore_labels (List[str], 默认为 ["O"]) — 要忽略的标签列表。
  • grouped_entities (bool, 可选, 默认为 False) — 已弃用,请使用 aggregation_strategy 代替。是否在预测中将对应于同一实体的令牌分组在一起。
  • stride (int, 可选) — 如果提供了stride,管道将应用于所有文本。文本将被分割成大小为model_max_length的块。仅适用于快速分词器且aggregation_strategy不同于NONE的情况。 此参数的值定义了块之间重叠的标记数。换句话说,模型将在每一步向前移动tokenizer.model_max_length - stride个标记。
  • aggregation_strategy (str, optional, defaults to "none") — The strategy to fuse (or not) tokens based on the model prediction.
    • “none” : Will simply not do any aggregation and simply return raw results from the model
    • “simple” : Will attempt to group entities following the default schema. (A, B-TAG), (B, I-TAG), (C, I-TAG), (D, B-TAG2) (E, B-TAG2) will end up being [{“word”: ABC, “entity”: “TAG”}, {“word”: “D”, “entity”: “TAG2”}, {“word”: “E”, “entity”: “TAG2”}] Notice that two consecutive B tags will end up as different entities. On word based languages, we might end up splitting words undesirably : Imagine Microsoft being tagged as [{“word”: “Micro”, “entity”: “ENTERPRISE”}, {“word”: “soft”, “entity”: “NAME”}]. Look for FIRST, MAX, AVERAGE for ways to mitigate that and disambiguate words (on languages that support that meaning, which is basically tokens separated by a space). These mitigations will only work on real words, “New york” might still be tagged with two different entities.
    • “first” : (works only on word based models) Will use the 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.
    • “average” : (works only on word based models) Will use the 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.
    • “max” : (works only on word based models) Will use the SIMPLE strategy except that words, cannot end up with different tags. Word entity will simply be the token with the maximum score.

使用任何ModelForTokenClassification的命名实体识别管道。有关更多信息,请参阅命名实体识别示例

示例:

>>> 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]
>>> # Start and end provide an easy way to highlight words in the original text.
>>> sentence[token["start"] : token["end"]]
' jean-baptiste'

>>> # Some models use the same idea to do part of speech.
>>> 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}]

了解更多关于使用管道的基础知识,请参阅管道教程

这个标记识别管道目前可以通过使用以下任务标识符从pipeline()加载: "ner"(用于预测序列中标记的类别:人名、组织、地点或其他)。

此管道可以使用的模型是已经在标记分类任务上微调过的模型。请参阅 huggingface.co/models 上最新的可用模型列表。

__call__

< >

( inputs: typing.Union[str, typing.List[str]] **kwargs ) 一个列表或一个包含dict的列表

参数

  • inputs (strList[str]) — 一个或多个文本(或一个文本列表)用于标记分类。

返回

一个列表或一个包含dict的列表的列表

每个结果都作为一个字典列表返回(对应输入中的每个标记一个,或者如果此管道是用aggregation_strategy实例化的,则为每个实体一个),包含以下键:

  • word (str) — 分类的标记/单词。这是通过解码选定的标记获得的。如果您想要原始句子中的确切字符串,请使用startend
  • score (float) — 对应entity的概率。
  • entity (str) — 为该标记/单词预测的实体(当aggregation_strategy不是"none"时,它被称为entity_group)。
  • index (int, 仅在aggregation_strategy="none"时存在) — 句子中对应标记的索引。
  • start (int, 可选) — 句子中对应实体的起始索引。仅在标记器中存在偏移量时存在。
  • end (int, 可选) — 句子中对应实体的结束索引。仅在标记器中存在偏移量时存在。

对输入的文本中的每个标记进行分类。

aggregate_words

< >

( 实体: typing.List[dict] 聚合策略: AggregationStrategy )

覆盖来自给定单词的标记,这些标记在单词边界上不一致,以强制达成一致。

示例:micro|soft| com|pany| B-ENT I-NAME I-ENT I-ENT 将使用第一种策略重写为 microsoft| company| B-ENT I-ENT

gather_pre_entities

< >

( 句子: str 输入ID: ndarray 分数: ndarray 偏移映射: typing.Optional[typing.List[typing.Tuple[int, int]]] 特殊标记掩码: ndarray 聚合策略: AggregationStrategy )

将各种numpy数组合并为包含聚合所需所有信息的字典

group_entities

< >

( 实体: typing.List[dict] )

参数

  • entities (dict) — 由管道预测的实体。

找到并将具有相同预测实体的相邻标记分组在一起。

group_sub_entities

< >

( 实体: typing.List[dict] )

参数

  • entities (dict) — 由管道预测的实体。

将预测具有相同实体的相邻标记分组在一起。

翻译管道

transformers.TranslationPipeline

< >

( *args **kwargs )

参数

  • model (PreTrainedModelTFPreTrainedModel) — 管道将用于进行预测的模型。这需要是一个继承自 PreTrainedModel 的 PyTorch 模型和继承自 TFPreTrainedModel 的 TensorFlow 模型。
  • tokenizer (PreTrainedTokenizer) — 管道将使用的分词器,用于为模型编码数据。该对象继承自 PreTrainedTokenizer.
  • modelcard (strModelCard, 可选) — 此管道的模型所归属的模型卡片。
  • framework (str, optional) — The framework to use, either "pt" for PyTorch or "tf" for TensorFlow. The specified framework must be installed.

    如果没有指定框架,将默认使用当前安装的框架。如果没有指定框架且两个框架都已安装,将默认使用model的框架,如果没有提供模型,则默认使用PyTorch。

  • task (str, 默认为 "") — 管道的一个任务标识符。
  • num_workers (int, optional, defaults to 8) — 当管道将使用DataLoader时(在传递数据集时,对于Pytorch模型在GPU上),要使用的工作线程数。
  • batch_size (int, 可选, 默认为 1) — 当管道使用 DataLoader 时(当传递数据集时,在 GPU 上用于 Pytorch 模型),使用的批次大小,对于推理来说,这并不总是有益的,请阅读 Batching with pipelines
  • args_parser (ArgumentHandler, optional) — 负责解析提供的管道参数的对象的引用。
  • device (int, 可选, 默认为 -1) — 用于CPU/GPU支持的设备序号。将此设置为-1将利用CPU,设置为正数将在关联的CUDA设备ID上运行模型。你也可以传递原生的torch.devicestr
  • torch_dtype (strtorch.dtype, 可选) — 直接作为 model_kwargs 发送(只是一个更简单的快捷方式)以使用此模型可用的精度 (torch.float16, torch.bfloat16, … 或 "auto")
  • binary_output (bool, optional, defaults to False) — 标志指示管道的输出是否应以序列化格式(即pickle)或原始输出数据(例如文本)进行。

将一种语言翻译成另一种语言。

这个翻译管道目前可以通过以下任务标识符从pipeline()加载: "translation_xx_to_yy"

该管道可以使用的模型是已经在翻译任务上微调过的模型。请查看huggingface.co/models上的最新可用模型列表。 有关可用参数的列表,请参阅以下文档

用法:

en_fr_translator = pipeline("translation_en_to_fr")
en_fr_translator("How old are you?")

__call__

< >

( *args **kwargs ) 一个列表或一个包含dict的列表

参数

  • args (str or List[str]) — 要翻译的文本。
  • return_tensors (bool, 可选, 默认为 False) — 是否在输出中包含预测的张量(作为标记索引)。
  • return_text (bool, 可选, 默认为 True) — 是否在输出中包含解码后的文本。
  • clean_up_tokenization_spaces (bool, optional, defaults to False) — 是否清理文本输出中可能存在的额外空格。
  • src_lang (str, optional) — 输入的语言。对于多语言模型可能是必需的。对于单对翻译模型将不会有任何影响
  • tgt_lang (str, optional) — 所需输出的语言。对于多语言模型可能是必需的。对于单对翻译模型将不会有任何影响
  • generate_kwargs — 传递给模型生成方法的额外关键字参数(请参阅与您的框架对应的生成方法 这里)。

返回

一个列表或一个包含dict的列表的列表

每个结果都以字典形式返回,包含以下键:

  • translation_text (str, 当 return_text=True 时存在) — 翻译文本。
  • translation_token_ids (torch.Tensortf.Tensor, 当 return_tensors=True 时存在) — 翻译的标记ID。

将输入的文本翻译。

ZeroShotClassificationPipeline

class transformers.ZeroShotClassificationPipeline

< >

( args_parser = *args **kwargs )

参数

  • model (PreTrainedModelTFPreTrainedModel) — 管道将用于进行预测的模型。这需要是一个继承自 PreTrainedModel 的 PyTorch 模型和继承自 TFPreTrainedModel 的 TensorFlow 模型。
  • tokenizer (PreTrainedTokenizer) — 管道将使用的分词器,用于为模型编码数据。该对象继承自 PreTrainedTokenizer.
  • modelcard (strModelCard, 可选) — 归因于此管道模型的模型卡。
  • framework (str, optional) — The framework to use, either "pt" for PyTorch or "tf" for TensorFlow. The specified framework must be installed.

    如果没有指定框架,将默认使用当前安装的框架。如果没有指定框架且两个框架都已安装,将默认使用model的框架,如果没有提供模型,则默认使用PyTorch。

  • task (str, 默认为 "") — 管道的任务标识符。
  • num_workers (int, 可选, 默认为 8) — 当管道将使用 DataLoader 时(在传递数据集时,对于 Pytorch 模型在 GPU 上),要使用的工作线程数。
  • batch_size (int, 可选, 默认为 1) — 当管道使用 DataLoader 时(当传递数据集时,在 GPU 上用于 Pytorch 模型),使用的批次大小,对于推理来说,这并不总是有益的,请阅读 Batching with pipelines
  • args_parser (ArgumentHandler, 可选) — 负责解析提供的管道参数的对象的引用。
  • device (int, 可选, 默认为 -1) — 用于CPU/GPU支持的设备序号。将此设置为-1将利用CPU,设置为正数将在关联的CUDA设备ID上运行模型。你也可以传递原生的torch.devicestr
  • torch_dtype (strtorch.dtype, 可选) — 直接作为 model_kwargs 发送(只是一个更简单的快捷方式)以使用此模型可用的精度 (torch.float16, torch.bfloat16, … 或 "auto")
  • binary_output (bool, 可选, 默认为 False) — 标志指示管道的输出是否应以序列化格式(即pickle)或原始输出数据(例如文本)进行。

基于NLI的零样本分类管道,使用在NLI(自然语言推理)任务上训练的ModelForSequenceClassification。相当于text-classification管道,但这些模型不需要硬编码的潜在类别数量,它们可以在运行时选择。这通常意味着它较慢,但非常灵活。

可以传递任何序列和标签的组合,每个组合都将作为前提/假设对传递给预训练模型。然后,将entailment的logit作为候选标签有效的logit。可以使用任何NLI模型,但entailment标签的ID必须包含在模型配置的:attr:~transformers.PretrainedConfig.label2id中。

示例:

>>> 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]}

了解更多关于使用管道的基础知识,请参阅管道教程

这个NLI管道目前可以从pipeline()使用以下任务标识符加载: "zero-shot-classification"

此管道可以使用的模型是已经在NLI任务上微调过的模型。请查看huggingface.co/models上的最新可用模型列表。

__call__

< >

( sequences: typing.Union[str, typing.List[str]] *args **kwargs ) 一个 dict 或一个 dict 的列表

参数

  • sequences (strList[str]) — 要分类的序列,如果模型输入过大,将被截断。
  • candidate_labels (strList[str]) — 将每个序列分类的可能类别标签集。可以是单个标签、逗号分隔的标签字符串或标签列表。
  • hypothesis_template (str, optional, defaults to "This example is {}.") — 用于将每个标签转换为NLI风格假设的模板。此模板必须包含{}或类似的语法,以便将候选标签插入到模板中。例如,默认模板是"This example is {}."。使用候选标签"sports",这将输入到模型中,如" sequence to classify This example is sports . "。默认模板在许多情况下效果很好,但根据任务设置,尝试不同的模板可能是值得的。
  • multi_label (bool, 可选, 默认为 False) — 是否可以有多个候选标签为真。如果为 False,则分数被归一化,使得每个序列的标签似然之和为1。如果为 True,则标签被视为独立的,并且通过将蕴含分数与矛盾分数进行softmax来对每个候选标签的概率进行归一化。

返回

一个dict或一个dict的列表

每个结果都以字典形式返回,包含以下键:

  • sequence (str) — 这是输出的序列。
  • labels (List[str]) — 按可能性排序的标签。
  • scores (List[float]) — 每个标签的概率。

对输入的序列进行分类。更多信息请参阅ZeroShotClassificationPipeline文档。

多模态

可用于多模态任务的管道包括以下内容。

DocumentQuestionAnsweringPipeline

transformers.DocumentQuestionAnsweringPipeline

< >

( *args **kwargs )

参数

  • model (PreTrainedModelTFPreTrainedModel) — 管道将用于进行预测的模型。这需要是一个继承自 PreTrainedModel 的模型用于 PyTorch 和 TFPreTrainedModel 用于 TensorFlow.
  • tokenizer (PreTrainedTokenizer) — 管道将使用的分词器,用于为模型编码数据。此对象继承自 PreTrainedTokenizer.
  • image_processor (BaseImageProcessor) — 管道将使用此图像处理器来为模型编码数据。此对象继承自 BaseImageProcessor.
  • modelcard (strModelCard, 可选) — 此管道的模型所归属的模型卡片。
  • framework (str, optional) — The framework to use, either "pt" for PyTorch or "tf" for TensorFlow. The specified framework must be installed.

    如果没有指定框架,将默认使用当前安装的框架。如果没有指定框架且两个框架都已安装,将默认使用model的框架,如果没有提供模型,则默认使用PyTorch。

  • task (str, 默认为 "") — 管道的一个任务标识符。
  • num_workers (int, 可选, 默认为 8) — 当管道将使用 DataLoader 时(在传递数据集时,对于 Pytorch 模型在 GPU 上),要使用的工作线程数。
  • batch_size (int, 可选, 默认为 1) — 当管道使用 DataLoader 时(当传递数据集时,在 GPU 上用于 Pytorch 模型),使用的批次大小,对于推理来说,这并不总是有益的,请阅读 Batching with pipelines
  • args_parser (ArgumentHandler, 可选) — 负责解析提供的管道参数的对象的引用。
  • device (int, 可选, 默认为 -1) — 用于CPU/GPU支持的设备序号。将此设置为-1将利用CPU,设置为正数将在关联的CUDA设备ID上运行模型。你也可以传递原生的torch.devicestr
  • torch_dtype (strtorch.dtype, 可选) — 直接作为 model_kwargs 发送(只是一个更简单的快捷方式)以使用此模型可用的精度 (torch.float16, torch.bfloat16, … 或 "auto")
  • binary_output (bool, 可选, 默认为 False) — 标志指示管道的输出是否应以序列化格式(即pickle)或原始输出数据(例如文本)进行。

使用任何AutoModelForDocumentQuestionAnswering的文档问答管道。输入/输出与(抽取式)问答管道类似;然而,该管道以图像(和可选的OCR识别的单词/框)作为输入,而不是文本上下文。

示例:

>>> 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}]

了解更多关于使用管道的基础知识,请参阅管道教程

这个文档问答管道目前可以从pipeline()加载,使用以下任务标识符:"document-question-answering"

该管道可以使用的模型是已经在文档问答任务上进行了微调的模型。 请参阅最新的可用模型列表 huggingface.co/models

__call__

< >

( image: typing.Union[ForwardRef('Image.Image'), str] question: typing.Optional[str] = None word_boxes: typing.Tuple[str, typing.List[float]] = None **kwargs ) 一个 dict 或一个 dict 的列表

参数

  • image (str or PIL.Image) — The pipeline handles three types of images:
    • A string containing a http link pointing to an image
    • A string containing a local path to an image
    • An image loaded in PIL directly

    管道接受单个图像或一批图像。如果给定单个图像,它可以广播到多个问题。

  • 问题 (str) — 一个要问文档的问题。
  • word_boxes (List[str, Tuple[float, float, float, float]], 可选) — 一个包含单词和边界框(归一化到0->1000)的列表。如果您提供此可选输入,则管道将使用这些单词和框,而不是在图像上运行OCR来为需要它们的模型(例如LayoutLM)生成它们。这允许您在多次调用管道时重复使用OCR结果,而不必每次都重新运行它。
  • top_k (int, 可选, 默认为 1) — 返回的答案数量(将按可能性顺序选择)。请注意,如果上下文中没有足够的选项,我们将返回少于 top_k 的答案。
  • doc_stride (int, optional, 默认为 128) — 如果文档中的单词太长,无法与模型的问题一起适应,它将被分成几个有重叠的块。此参数控制该重叠的大小。
  • max_answer_len (int, optional, 默认为 15) — 预测答案的最大长度(例如,仅考虑长度较短的答案)。
  • max_seq_len (int, 可选, 默认为 384) — 传递给模型的每个块的总句子(上下文 + 问题)的最大长度(以标记为单位)。如果需要,上下文将被分成几个块(使用 doc_stride 作为重叠)。
  • max_question_len (int, optional, 默认为 64) — 问题在分词后的最大长度。如果需要,它将被截断。
  • handle_impossible_answer (bool, 可选, 默认为 False) — 是否接受不可能作为答案。
  • lang (str, 可选) — 运行OCR时使用的语言。默认为英语。
  • tesseract_config (str, 可选) — 在运行OCR时传递给tesseract的额外标志。
  • timeout (float, optional, defaults to None) — 从网络获取图像的最大等待时间(以秒为单位)。如果为None,则不设置超时,调用可能会永久阻塞。

返回

一个dict或一个dict的列表

每个结果都以字典形式出现,包含以下键:

  • score (float) — 与答案相关的概率。
  • start (int) — 答案的起始词索引(在输入的OCR版本或提供的word_boxes中)。
  • end (int) — 答案的结束词索引(在输入的OCR版本或提供的word_boxes中)。
  • answer (str) — 问题的答案。
  • words (list[int]) — 答案中每个词/框对的索引

通过使用文档回答输入的问题。文档被定义为一个图像和一个可选的(单词,框)元组列表,这些元组表示文档中的文本。如果没有提供word_boxes,它将使用Tesseract OCR引擎(如果可用)自动提取单词和框,以供需要它们作为输入的LayoutLM类模型使用。对于Donut,不运行OCR。

你可以通过几种方式调用管道:

  • 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}])

特征提取管道

transformers.FeatureExtractionPipeline

< >

( 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 )

参数

  • model (PreTrainedModelTFPreTrainedModel) — 管道将用于进行预测的模型。这需要是一个继承自 PreTrainedModel 的模型(用于 PyTorch)和 TFPreTrainedModel 的模型(用于 TensorFlow)。
  • tokenizer (PreTrainedTokenizer) — 管道将使用的分词器,用于为模型编码数据。该对象继承自 PreTrainedTokenizer.
  • modelcard (strModelCard, 可选) — 归因于此管道模型的模型卡。
  • framework (str, optional) — The framework to use, either "pt" for PyTorch or "tf" for TensorFlow. The specified framework must be installed.

    如果没有指定框架,将默认使用当前安装的框架。如果没有指定框架且两个框架都已安装,将默认使用model的框架,如果没有提供模型,则默认使用PyTorch。

  • task (str, 默认为 "") — 管道的一个任务标识符。
  • num_workers (int, optional, defaults to 8) — 当管道将使用DataLoader时(在传递数据集时,对于Pytorch模型在GPU上),要使用的工作线程数。
  • batch_size (int, 可选, 默认为 1) — 当管道使用 DataLoader 时(当传递数据集时,在 GPU 上用于 Pytorch 模型),使用的批次大小,对于推理来说,这并不总是有益的,请阅读 Batching with pipelines
  • args_parser (ArgumentHandler, 可选) — 负责解析提供的管道参数的对象的引用。
  • device (int, 可选, 默认为 -1) — 用于CPU/GPU支持的设备序号。将此设置为-1将利用CPU,设置为正数将在关联的CUDA设备ID上运行模型。你也可以传递原生的torch.devicestr
  • torch_dtype (strtorch.dtype, 可选) — 直接作为 model_kwargs 发送(只是一个更简单的快捷方式)以使用此模型可用的精度 (torch.float16, torch.bfloat16, … 或 "auto")
  • tokenize_kwargs (dict, optional) — 传递给分词器的额外关键字参数字典。
  • return_tensors (bool, 可选) — 如果 True,根据指定的框架返回一个张量,否则返回一个列表。

特征提取管道不使用模型头部。该管道从基础转换器中提取隐藏状态,这些隐藏状态可以用作下游任务中的特征。

示例:

>>> 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  # This is a tensor of shape [1, sequence_length, hidden_dimension] representing the input string.
torch.Size([1, 8, 768])

了解更多关于使用管道的基础知识,请参阅管道教程

这个特征提取管道目前可以从pipeline()使用任务标识符加载: "feature-extraction"

所有模型都可以用于此管道。查看所有模型的列表,包括社区贡献的模型,请访问 huggingface.co/models

__call__

< >

( *args **kwargs ) 一个嵌套的 float 列表

参数

  • args (strList[str]) — 一个或多个文本(或一个文本列表)以获取其特征.

返回

一个嵌套的float列表

模型计算的特征。

提取输入的特征。

图像特征提取管道

transformers.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 )

参数

  • model (PreTrainedModelTFPreTrainedModel) — 管道将用于进行预测的模型。这需要是一个继承自 PreTrainedModel 的模型用于 PyTorch 和 TFPreTrainedModel 用于 TensorFlow.
  • image_processor (BaseImageProcessor) — 管道将使用的图像处理器,用于为模型编码数据。此对象继承自 BaseImageProcessor.
  • modelcard (strModelCard, 可选) — 归因于此管道模型的模型卡。
  • framework (str, optional) — The framework to use, either "pt" for PyTorch or "tf" for TensorFlow. The specified framework must be installed.

    如果没有指定框架,将默认使用当前安装的框架。如果没有指定框架且两个框架都已安装,将默认使用model的框架,如果没有提供模型,则默认使用PyTorch。

  • task (str, defaults to "") — 管道的一个任务标识符。
  • num_workers (int, optional, 默认为 8) — 当管道将使用 DataLoader 时(在传递数据集时,对于 Pytorch 模型在 GPU 上),要使用的工作线程数。
  • batch_size (int, 可选, 默认为 1) — 当管道使用 DataLoader 时(当传递数据集时,在 GPU 上用于 Pytorch 模型),使用的批次大小,对于推理来说,这并不总是有益的,请阅读 Batching with pipelines
  • args_parser (ArgumentHandler, 可选) — 负责解析提供的管道参数的对象的引用。
  • device (int, 可选, 默认为 -1) — 用于CPU/GPU支持的设备序号。将此设置为-1将利用CPU,设置为正数将在关联的CUDA设备ID上运行模型。你也可以传递原生的torch.devicestr
  • torch_dtype (strtorch.dtype, 可选) — 直接作为 model_kwargs 发送(只是一个更简单的快捷方式)以使用此模型可用的精度 (torch.float16, torch.bfloat16, … 或 "auto")
  • binary_output (bool, 可选, 默认为 False) — 标志指示管道的输出是否应以序列化格式(即pickle)或原始输出数据(例如文本)进行。
  • image_processor_kwargs (dict, optional) — 传递给图像处理器的额外关键字参数字典,例如 {“size”: {“height”: 100, “width”: 100}‌}
  • pool (bool, 可选, 默认为 False) — 是否返回池化输出。如果为 False,模型将返回原始隐藏状态。

图像特征提取管道不使用模型头部。该管道从基础转换器中提取隐藏状态,这些隐藏状态可以用作下游任务中的特征。

示例:

>>> 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  # This is a tensor of shape [1, sequence_lenth, hidden_dimension] representing the input image.
torch.Size([1, 197, 768])

了解更多关于使用管道的基础知识,请参阅管道教程

此图像特征提取管道目前可以从pipeline()使用任务标识符加载: "image-feature-extraction"

所有视觉模型都可以用于此管道。查看所有模型的列表,包括社区贡献的模型,请访问 huggingface.co/models

__call__

< >

( *args **kwargs ) 一个嵌套的 float 列表

参数

  • images (str, List[str], PIL.Image or List[PIL.Image]) — The pipeline handles three types of images:
    • A string containing a http link pointing to an image
    • A string containing a local path to an image
    • An image loaded in PIL directly

    管道接受单个图像或一批图像,这些图像必须作为字符串传递。 一批中的图像必须全部采用相同的格式:全部为http链接,全部为本地路径,或全部为PIL 图像。

  • timeout (float, optional, 默认为 None) — 从网络获取图像的最大等待时间(以秒为单位)。如果为 None,则不使用超时,调用可能会永久阻塞。

返回

一个嵌套的float列表

模型计算的特征。

提取输入的特征。

图像转文本管道

transformers.ImageToTextPipeline

< >

( *args **kwargs )

参数

  • model (PreTrainedModelTFPreTrainedModel) — 管道将用于进行预测的模型。这需要是从 PreTrainedModel 继承的模型(对于 PyTorch)和从 TFPreTrainedModel 继承的模型(对于 TensorFlow)。
  • tokenizer (PreTrainedTokenizer) — 管道将使用的分词器,用于为模型编码数据。该对象继承自 PreTrainedTokenizer.
  • image_processor (BaseImageProcessor) — 管道将使用该图像处理器来为模型编码数据。此对象继承自 BaseImageProcessor.
  • modelcard (strModelCard, 可选) — 归因于此管道模型的模型卡。
  • framework (str, optional) — The framework to use, either "pt" for PyTorch or "tf" for TensorFlow. The specified framework must be installed.

    如果没有指定框架,将默认使用当前安装的框架。如果没有指定框架且两个框架都已安装,将默认使用model的框架,如果没有提供模型,则默认使用PyTorch。

  • task (str, 默认为 "") — 管道的一个任务标识符。
  • num_workers (int, 可选, 默认为 8) — 当管道将使用 DataLoader 时(在传递数据集时,对于 Pytorch 模型在 GPU 上),要使用的工作线程数。
  • batch_size (int, 可选, 默认为 1) — 当管道使用 DataLoader 时(当传递数据集时,在 GPU 上用于 Pytorch 模型),使用的批次大小,对于推理来说,这并不总是有益的,请阅读 Batching with pipelines
  • args_parser (ArgumentHandler, 可选) — 负责解析提供的管道参数的对象的引用。
  • device (int, 可选, 默认为 -1) — 用于CPU/GPU支持的设备序号。将此设置为-1将利用CPU,设置为正数将在关联的CUDA设备ID上运行模型。您也可以传递原生的torch.devicestr
  • torch_dtype (strtorch.dtype, 可选) — 直接作为 model_kwargs 发送(只是一个更简单的快捷方式)以使用此模型可用的精度 (torch.float16, torch.bfloat16, … 或 "auto")
  • binary_output (bool, 可选, 默认为 False) — 标志指示管道的输出是否应以序列化格式(即pickle)或原始输出数据(例如文本)进行。

使用AutoModelForVision2Seq的图像到文本管道。该管道预测给定图像的标题。

示例:

>>> 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 '}]

了解更多关于使用管道的基础知识,请参阅管道教程

这个图像到文本的管道目前可以通过以下任务标识符从pipeline()加载: “image-to-text”。

查看可用模型列表在 huggingface.co/models

__call__

< >

( inputs: typing.Union[str, typing.List[str], ForwardRef('Image.Image'), typing.List[ForwardRef('Image.Image')]] = None **kwargs ) 一个列表或一个包含dict的列表

参数

  • inputs (str, List[str], PIL.Image or List[PIL.Image]) — The pipeline handles three types of images:
    • A string containing a HTTP(s) link pointing to an image
    • A string containing a local path to an image
    • An image loaded in PIL directly

    管道接受单个图像或一批图像。

  • max_new_tokens (int, optional) — 生成的最大令牌数量。默认情况下,它将使用 generate 的默认值。
  • generate_kwargs (Dict, 可选) — 传递它以将所有参数直接发送到 generate,从而完全控制此函数。
  • timeout (float, optional, 默认为 None) — 从网络获取图像的最大等待时间(以秒为单位)。如果为 None,则不设置超时,调用可能会永久阻塞。

返回

一个列表或一个包含dict的列表的列表

每个结果都以字典形式返回,包含以下键:

  • generated_text (str) — 生成的文本。

为作为输入传递的图像分配标签。

ImageTextToTextPipeline

transformers.ImageTextToTextPipeline

< >

( *args **kwargs )

参数

  • model (PreTrainedModelTFPreTrainedModel) — 管道将用于进行预测的模型。这需要是一个继承自 PreTrainedModel 的 PyTorch 模型和继承自 TFPreTrainedModel 的 TensorFlow 模型。
  • processor (ProcessorMixin) — 管道将使用的处理器,用于为模型编码数据。该对象继承自 ProcessorMixin。处理器是一个复合对象,可能包含 tokenizerfeature_extractorimage_processor.
  • modelcard (strModelCard, 可选) — 归因于此管道模型的模型卡。
  • framework (str, optional) — The framework to use, either "pt" for PyTorch or "tf" for TensorFlow. The specified framework must be installed.

    如果没有指定框架,将默认使用当前安装的框架。如果没有指定框架且两个框架都已安装,将默认使用model的框架,如果没有提供模型,则默认使用PyTorch。

  • task (str, 默认为 "") — 管道的任务标识符。
  • num_workers (int, optional, 默认为 8) — 当管道使用 DataLoader 时(在传递数据集时,对于 Pytorch 模型在 GPU 上),要使用的工作线程数。
  • batch_size (int, 可选, 默认为 1) — 当管道使用 DataLoader 时(当传递数据集时,在 GPU 上用于 Pytorch 模型),使用的批次大小,对于推理来说,这并不总是有益的,请阅读 Batching with pipelines
  • args_parser (ArgumentHandler, 可选) — 负责解析提供的管道参数的对象的引用。
  • device (int, 可选, 默认为 -1) — 用于CPU/GPU支持的设备序号。将此设置为-1将利用CPU,设置为正数将在关联的CUDA设备ID上运行模型。你也可以传递原生的torch.devicestr
  • torch_dtype (strtorch.dtype, 可选) — 直接作为 model_kwargs 发送(只是一个更简单的快捷方式)以使用此模型可用的精度 (torch.float16, torch.bfloat16, … 或 "auto")
  • binary_output (bool, 可选, 默认为 False) — 标志指示管道的输出是否应以序列化格式(即pickle)或原始输出数据(例如文本)进行。

使用AutoModelForImageTextToText的图像文本到文本管道。该管道根据图像和文本生成文本。 当底层模型是对话模型时,它还可以接受一个或多个聊天, 在这种情况下,管道将以聊天模式运行,并通过添加其响应来继续聊天。 每个聊天采用字典列表的形式,其中每个字典包含“role”和“content”键。

示例:

>>> 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'}]

了解更多关于使用管道的基础知识,请参阅管道教程

这个图像文本到文本的管道目前可以通过以下任务标识符从 pipeline() 加载: “image-text-to-text”。

查看可用模型列表在 huggingface.co/models

__call__

< >

( 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 ) 一个列表或一个包含dict的列表

参数

  • images (str, List[str], PIL.Image or List[PIL.Image]`) — The pipeline handles three types of images:
    • A string containing a HTTP(s) link pointing to an image
    • A string containing a local path to an image
    • An image loaded in PIL directly

    管道接受单个图像或一批图像。

  • text (str, List[str], List[Dict[str, Union[str, PIL.Image]]]) — 用于生成的文本。如果传递的是字符串列表,列表的长度应与图像的数量相同。文本也可以遵循聊天格式:一个字典列表,其中每个字典代表对话中的一条消息。每个字典应有两个键:‘role’和‘content’。‘role’应为‘user’、‘system’或‘assistant’之一。‘content’应是一个包含消息文本和消息类型的字典列表。消息类型可以是‘text’或‘image’。如果类型是‘image’,则不需要文本。
  • return_tensors (bool, 可选, 默认为 False) — 返回输出中的预测张量(作为标记索引)。如果设置为 True,则不会返回解码后的文本。
  • return_text (bool, optional) — 在输出中返回解码后的文本。
  • return_full_text (bool, 可选, 默认为 True) — 如果设置为 False,则只返回添加的文本,否则返回完整文本。不能与 return_text 同时指定。
  • continue_final_message( bool, optional) — 这表示您希望模型继续输入聊天中的最后一条消息,而不是开始新的消息,从而允许您“预填充”其响应。 默认情况下,当输入聊天中的最后一条消息具有assistant角色时,此值为True,否则为False,但您可以通过设置此标志手动覆盖该行为。

返回

一个列表或一个包含dict的列表的列表

每个结果都以字典形式返回,包含以下键(不能同时返回generated_textgenerated_token_ids):

  • generated_text (str, 当return_text=True时存在) — 生成的文本。
  • generated_token_ids (torch.Tensor, 当return_tensors=True时存在) — 生成文本的token id。
  • input_text (str) — 输入的文本。

根据输入的文本和图像生成文本。

MaskGenerationPipeline

transformers.MaskGenerationPipeline

< >

( **kwargs )

参数

  • model (PreTrainedModelTFPreTrainedModel) — 管道将用于进行预测的模型。这需要是一个继承自 PreTrainedModel 的模型(用于 PyTorch)和 TFPreTrainedModel 的模型(用于 TensorFlow)。
  • image_processor (BaseImageProcessor) — 管道将使用的图像处理器,用于为模型编码数据。此对象继承自 BaseImageProcessor.
  • modelcard (strModelCard, 可选) — 此管道的模型所归属的模型卡片。
  • framework (str, optional) — The framework to use, either "pt" for PyTorch or "tf" for TensorFlow. The specified framework must be installed.

    如果没有指定框架,将默认使用当前安装的框架。如果没有指定框架且两个框架都已安装,将默认使用model的框架,如果没有提供模型,则默认使用PyTorch。

  • task (str, 默认为 "") — 管道的一个任务标识符。
  • num_workers (int, optional, 默认为 8) — 当管道将使用 DataLoader 时(在传递数据集时,对于 Pytorch 模型在 GPU 上),要使用的工作线程数。
  • batch_size (int, 可选, 默认为 1) — 当管道使用 DataLoader 时(当传递数据集时,在 GPU 上用于 Pytorch 模型),使用的批次大小,对于推理来说,这并不总是有益的,请阅读 Batching with pipelines
  • args_parser (ArgumentHandler, optional) — 负责解析提供的管道参数的对象的引用。
  • device (int, 可选, 默认为 -1) — 用于CPU/GPU支持的设备序号。将此设置为-1将利用CPU,设置为正数将在关联的CUDA设备ID上运行模型。你也可以传递原生的torch.devicestr
  • torch_dtype (strtorch.dtype, 可选) — 直接作为 model_kwargs 发送(只是一个更简单的快捷方式)以使用此模型可用的精度 (torch.float16, torch.bfloat16, … 或 "auto")
  • binary_output (bool, 可选, 默认为 False) — 标志指示管道的输出是否应以序列化格式(即pickle)或原始输出数据(例如文本)进行。
  • points_per_batch (可选, int, 默认为 64) — 设置模型同时运行的点数。数值越大可能越快,但会占用更多的 GPU 内存。
  • output_bboxes_mask (bool, optional, default to False) — 是否输出边界框预测。
  • output_rle_masks (bool, 可选, 默认为 False) — 是否以 RLE 格式输出掩码

使用SamForMaskGeneration自动生成图像的掩码。该管道根据给定的图像预测二进制掩码。它是一个ChunkPipeline,因为你可以将小批量中的点分开以避免内存不足(OOM)问题。使用points_per_batch参数来控制同时处理的点数,默认值为64

管道工作分为3个步骤:

  1. preprocess: 生成了一个由1024个均匀分布的点组成的网格,以及边界框和点标签。 有关如何创建点和边界框的更多详细信息,请查看_generate_crop_boxes函数。图像还使用image_processor进行了预处理。此函数yields一个包含points_per_batch的小批量数据。

  2. forward: 将preprocess的输出传递给模型。图像嵌入只计算一次。 调用self.model.get_image_embeddings并确保不计算梯度,且张量和模型位于同一设备上。

  3. postprocess: 自动生成掩码的最重要部分发生在这里。分为三个步骤:

    • image_processor.postprocess_masks (run on each minibatch loop): takes in the raw output masks, resizes them according to the image size, and transforms there to binary masks.
    • image_processor.filter_masks (on each minibatch loop): uses both pred_iou_thresh and stability_scores. Also applies a variety of filters based on non maximum suppression to remove bad masks.
    • image_processor.postprocess_masks_for_amg applies the NSM on the mask to only keep relevant ones.

示例:

>>> 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
... )

了解更多关于使用管道的基础知识,请参阅管道教程

这个分割管道目前可以通过使用以下任务标识符从pipeline()加载: "mask-generation"

查看可用的模型列表在 huggingface.co/models

__call__

< >

( image *args num_workers = 无 batch_size = 无 **kwargs ) Dict

参数

  • inputs (np.ndarray or bytes or str or dict) — 图像或图像列表。
  • mask_threshold (float, optional, defaults to 0.0) — 将预测的掩码转换为二进制值时使用的阈值。
  • pred_iou_thresh (float, optional, defaults to 0.88) — 应用于模型预测的掩码质量的过滤阈值,范围为 [0,1]
  • stability_score_thresh (float, optional, defaults to 0.95) — 一个在[0,1]范围内的过滤阈值,使用掩码在用于二值化模型掩码预测的截止值变化下的稳定性。
  • stability_score_offset (int, optional, defaults to 1) — 计算稳定性分数时,用于调整截止点的偏移量。
  • crops_nms_thresh (float, optional, defaults to 0.7) — 用于非极大值抑制的框 IoU 阈值,用于过滤重复的掩码。
  • crops_n_layers (int, 可选, 默认为 0) — 如果 crops_n_layers>0,将在图像的裁剪区域上再次运行掩码预测。设置运行的层数,其中每层有 2**i_layer 数量的图像裁剪区域。
  • crop_overlap_ratio (float, 可选, 默认为 512 / 1500) — 设置作物重叠的程度。在第一层作物中,作物将重叠图像长度的这一部分。后续层中更多的作物会缩小这种重叠。
  • crop_n_points_downscale_factor (int, optional, defaults to 1) — 在第n层中采样的每边点数通过crop_n_points_downscale_factor**n进行缩放。
  • timeout (float, optional, 默认为 None) — 从网络获取图像的最大等待时间(以秒为单位)。如果为 None,则不设置超时,调用可能会永久阻塞。

返回

Dict

包含以下键的字典:

  • mask (PIL.Image) — 检测到的对象的二进制掩码,作为原始图像形状为 (width, height) 的 PIL 图像。如果未找到对象,则返回填充零的掩码。
  • score (可选 float) — 当模型能够估计由标签和掩码描述的“对象”的置信度时,可选地返回。

生成二进制分割掩码

视觉问答管道

transformers.VisualQuestionAnsweringPipeline

< >

( *args **kwargs )

参数

  • model (PreTrainedModelTFPreTrainedModel) — 管道将用于进行预测的模型。这需要是从 PreTrainedModel 继承的模型(对于 PyTorch)和从 TFPreTrainedModel 继承的模型(对于 TensorFlow)。
  • tokenizer (PreTrainedTokenizer) — 管道将使用的分词器,用于为模型编码数据。该对象继承自 PreTrainedTokenizer.
  • image_processor (BaseImageProcessor) — 管道将使用此图像处理器来为模型编码数据。此对象继承自 BaseImageProcessor.
  • modelcard (strModelCard, 可选) — 此管道的模型所归属的模型卡片。
  • framework (str, optional) — The framework to use, either "pt" for PyTorch or "tf" for TensorFlow. The specified framework must be installed.

    如果没有指定框架,将默认使用当前安装的框架。如果没有指定框架且两个框架都已安装,将默认使用model的框架,如果没有提供模型,则默认使用PyTorch。

  • task (str, 默认为 "") — 管道的一个任务标识符。
  • num_workers (int, optional, 默认为 8) — 当管道将使用 DataLoader 时(当传递数据集时,在 GPU 上用于 Pytorch 模型),要使用的工作线程数。
  • batch_size (int, 可选, 默认为 1) — 当管道使用 DataLoader 时(当传递数据集时,在 GPU 上用于 Pytorch 模型),使用的批次大小,对于推理来说,这并不总是有益的,请阅读 Batching with pipelines
  • args_parser (ArgumentHandler, optional) — 负责解析提供的管道参数的对象的引用。
  • device (int, optional, 默认为 -1) — 用于CPU/GPU支持的设备序号。将此设置为-1将利用CPU,设置为正数将在关联的CUDA设备ID上运行模型。你也可以传递原生的torch.devicestr
  • torch_dtype (strtorch.dtype, 可选) — 直接作为 model_kwargs 发送(只是一个更简单的快捷方式)以使用此模型可用的精度 (torch.float16, torch.bfloat16, … 或 "auto")
  • binary_output (bool, optional, defaults to False) — 标志指示管道的输出是否应以序列化格式(即pickle)或原始输出数据(例如文本)进行。

使用AutoModelForVisualQuestionAnswering的视觉问答管道。该管道目前仅在PyTorch中可用。

示例:

>>> 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'}]

了解更多关于使用管道的基础知识,请参阅管道教程

这个视觉问答管道目前可以从pipeline()加载,使用以下任务标识符:"visual-question-answering", "vqa"

此管道可以使用的模型是已在视觉问答任务上进行微调的模型。请参阅 huggingface.co/models 上最新的可用模型列表。

__call__

< >

( 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 ) 包含结果的字典或字典列表。字典包含以下键

参数

  • image (str, List[str], PIL.Image, List[PIL.Image] or KeyDataset) — The pipeline handles three types of images:
    • A string containing a http link pointing to an image
    • A string containing a local path to an image
    • An image loaded in PIL directly

    管道接受单个图像或一批图像。如果给定单个图像,它可以广播到多个问题。 对于数据集:传入的数据集必须为类型 transformers.pipelines.pt_utils.KeyDataset 示例:

返回

包含结果的字典或字典列表。这些字典包含以下键

  • label (str) — 模型识别的标签。
  • score (int) — 模型为该标签分配的分数。

回答关于图像的开放式问题。该管道接受几种类型的输入,具体如下:

  • pipeline(image=image, question=question)
  • pipeline({"image": image, "question": question})
  • pipeline([{"image": image, "question": question}])
  • pipeline([{"image": image, "question": question}, {"image": image, "question": question}])

父类: Pipeline

transformers.Pipeline

< >

( 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 )

参数

  • model (PreTrainedModelTFPreTrainedModel) — 管道将用于进行预测的模型。这需要是从 PreTrainedModel 继承的模型用于 PyTorch,以及从 TFPreTrainedModel 继承的模型用于 TensorFlow。
  • tokenizer (PreTrainedTokenizer) — 管道将使用的分词器,用于为模型编码数据。该对象继承自 PreTrainedTokenizer.
  • feature_extractor (SequenceFeatureExtractor) — 管道将使用该特征提取器来为模型编码数据。该对象继承自 SequenceFeatureExtractor.
  • image_processor (BaseImageProcessor) — 管道将使用该图像处理器来为模型编码数据。此对象继承自 BaseImageProcessor.
  • processor (ProcessorMixin) — 管道将使用的处理器,用于为模型编码数据。该对象继承自 ProcessorMixin。处理器是一个复合对象,可能包含 tokenizerfeature_extractorimage_processor.
  • modelcard (strModelCard, 可选) — 此管道的模型所归属的模型卡片。
  • framework (str, optional) — The framework to use, either "pt" for PyTorch or "tf" for TensorFlow. The specified framework must be installed.

    如果没有指定框架,将默认使用当前安装的框架。如果没有指定框架且两个框架都已安装,将默认使用model的框架,如果没有提供模型,则默认使用PyTorch。

  • task (str, 默认为 "") — 管道的一个任务标识符。
  • num_workers (int, 可选, 默认为 8) — 当管道将使用 DataLoader 时(在传递数据集时,在 GPU 上用于 Pytorch 模型),要使用的工作线程数。
  • batch_size (int, 可选, 默认为 1) — 当管道使用 DataLoader 时(当传递数据集时,在 GPU 上用于 Pytorch 模型),使用的批次大小,对于推理来说,这并不总是有益的,请阅读 Batching with pipelines
  • args_parser (ArgumentHandler, 可选) — 负责解析提供的管道参数的对象的引用。
  • device (int, 可选, 默认为 -1) — 用于CPU/GPU支持的设备序号。将此设置为-1将利用CPU,设置为正数将在关联的CUDA设备ID上运行模型。你也可以传递原生的torch.devicestr
  • torch_dtype (strtorch.dtype, 可选) — 直接作为 model_kwargs 发送(只是一个更简单的快捷方式)以使用此模型可用的精度 (torch.float16, torch.bfloat16, … 或 "auto")
  • binary_output (bool, 可选, 默认为 False) — 标志指示管道的输出是否应以序列化格式(即pickle)或原始输出数据(例如文本)进行。

Pipeline 类是所有管道继承的类。请参考此类以获取跨不同管道共享的方法。

实现管道操作的基类。管道工作流被定义为以下操作序列:

输入 -> 分词 -> 模型推理 -> 后处理(任务依赖) -> 输出

Pipeline 支持通过 device 参数在 CPU 或 GPU 上运行(见下文)。

一些管道,例如FeatureExtractionPipeline ('feature-extraction') 输出大型张量对象作为嵌套列表。为了避免将这些大型结构作为文本数据转储,我们提供了binary_output构造函数参数。如果设置为True,输出将以pickle格式存储。

check_model_type

< >

( supported_models: typing.Union[typing.List[str], dict] )

参数

  • supported_models (List[str]dict) — 管道支持的模型列表,或包含模型类值的字典。

检查模型类是否由管道支持。

设备放置

< >

( )

上下文管理器允许以框架无关的方式在用户指定的设备上分配张量。

示例:

# Explicitly ask for tensor allocation on CUDA device :0
pipe = pipeline(..., device=0)
with pipe.device_placement():
    # Every framework specific tensor allocation will be done on the request device
    output = pipe(...)

ensure_tensor_on_device

< >

( **inputs ) Dict[str, torch.Tensor]

参数

  • inputs (应该是torch.Tensor的关键字参数,其余部分将被忽略) — 要放置在self.device上的张量。
  • 递归 仅在列表上 。 —

返回

Dict[str, torch.Tensor]

inputs 相同,但在适当的设备上。

确保PyTorch张量位于指定的设备上。

后处理

< >

( model_outputs: ModelOutput **postprocess_parameters: typing.Dict )

后处理将接收_forward方法的原始输出,通常是张量,并将它们重新格式化为更友好的形式。通常它会输出一个列表或字典或结果(仅包含字符串和数字)。

预测

< >

( X )

Scikit / Keras 接口到 transformers 的 pipelines。此方法将转发到 call()。

预处理

< >

( input_: typing.Any **preprocess_parameters: typing.Dict )

预处理将获取特定管道的input_并返回一个包含所有必要内容的字典,以便_forward能够正常运行。它应至少包含一个张量,但可能包含其他任意项目。

push_to_hub

< >

( 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: str = None commit_description: str = None tags: typing.Optional[typing.List[str]] = None **deprecated_kwargs )

参数

  • repo_id (str) — 您想要推送管道的仓库名称。当推送到特定组织时,它应包含您的组织名称。
  • use_temp_dir (bool, 可选) — 是否使用临时目录来存储推送到 Hub 之前保存的文件。 如果没有名为 repo_id 的目录,则默认为 True,否则为 False
  • commit_message (str, optional) — 推送时提交的消息。默认为 "Upload pipe".
  • private (bool, 可选) — 是否将仓库设为私有。如果为 None(默认值),仓库将为公开,除非组织的默认设置为私有。如果仓库已存在,则忽略此值。
  • token (boolstr, 可选) — 用于远程文件的HTTP承载授权的令牌。如果为 True,将使用运行 huggingface-cli login 时生成的令牌(存储在 ~/.huggingface 中)。如果未指定 repo_url,则默认为 True
  • max_shard_size (intstr, 可选, 默认为 "5GB") — 仅适用于模型。分片前检查点的最大大小。分片后的检查点大小将小于此大小。如果以字符串形式表示,需要是数字后跟单位(如 "5MB")。我们默认将其设置为 "5GB",以便用户可以在免费层级的Google Colab实例上轻松加载模型,而不会出现CPU内存不足的问题。
  • create_pr (bool, 可选, 默认为 False) — 是否创建一个带有上传文件的PR或直接提交。
  • safe_serialization (bool, optional, defaults to True) — 是否将模型权重转换为safetensors格式以实现更安全的序列化。
  • revision (str, optional) — 将上传的文件推送到的分支.
  • commit_description (str, optional) — 将要创建的提交的描述
  • 标签 (List[str], 可选) — 推送到Hub的标签列表。

将管道文件上传到 🤗 模型中心。

示例:

from transformers import pipeline

pipe = pipeline("google-bert/bert-base-cased")

# Push the pipe to your namespace with the name "my-finetuned-bert".
pipe.push_to_hub("my-finetuned-bert")

# Push the pipe to an organization with the name "my-finetuned-bert".
pipe.push_to_hub("huggingface/my-finetuned-bert")

save_pretrained

< >

( save_directory: typing.Union[str, os.PathLike] safe_serialization: bool = True **kwargs )

参数

  • save_directory (str or os.PathLike) — 一个指向保存目录的路径。如果目录不存在,将会被创建。
  • safe_serialization (str) — 是否使用safetensors或传统方式保存PyTorch或Tensorflow模型.
  • kwargs (Dict[str, Any], 可选) — 传递给 push_to_hub() 方法的额外关键字参数。

保存管道的模型和分词器。

transform

< >

( X )

Scikit / Keras 接口到 transformers 的 pipelines。此方法将转发到 call()。

< > Update on GitHub