Transformers 文档

Pipelines

Hugging Face's logo
Join the Hugging Face community

and get access to the augmented documentation experience

to get started

Pipelines

The pipelines are a great and easy way to use models for inference. These pipelines are objects that abstract most of the complex code from the library, offering a simple API dedicated to several tasks, including Named Entity Recognition, Masked Language Modeling, Sentiment Analysis, Feature Extraction and Question Answering. See the task summary for examples of use.

There are two categories of pipeline abstractions to be aware about

The pipeline abstraction

The pipeline abstraction is a wrapper around all the other available pipelines. It is instantiated as any other pipeline but can provide additional quality of life.

Simple call on one item

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

If you want to use a specific model from the hub you can ignore the task if the model on the hub already defines it

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

To call a pipeline on many items, you can call it with a list.

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

To iterate over full datasets it is recommended to use a dataset directly. This means you don’t need to allocate the whole dataset at once, nor do you need to do batching yourself. This should work just as fast as custom loops on GPU. If it doesn’t don’t hesitate to create an issue.

import datasets
from transformers import pipeline
from transformers.pipelines.pt_utils import KeyDataset
from tqdm.auto import tqdm

pipe = pipeline("automatic-speech-recognition", model="facebook/wav2vec2-base-960h", device=0)
dataset = datasets.load_dataset("superb", name="asr", split="test")

# 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": ....}
    # ....

For ease of use, a generator is also possible

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[bool, str, NoneType] = None device: typing.Union[int, str, ForwardRef('torch.device'), NoneType] = None device_map = None torch_dtype = None trust_remote_code: typing.Optional[bool] = None model_kwargs: typing.Dict[str, typing.Any] = None pipeline_class: typing.Optional[typing.Any] = None **kwargs ) Pipeline

Parameters

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

    If not provided, the default for the task will be loaded.

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

    If not provided, the default configuration file for the requested model will be used. That means that if model is given, its default configuration will be used. However, if model is not supplied, this task’s default model’s config is used instead.

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

    If not provided, the default tokenizer for the given model will be loaded (if it is a string). If model is not specified or not a string, then the default tokenizer for config is loaded (if it is a string). However, if config is also not given or not a string, then the default tokenizer for the given task will be loaded.

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

    Feature extractors are used for non-NLP models, such as Speech or Vision models as well as multi-modal models. Multi-modal models will also require a tokenizer to be passed.

    If not provided, the default feature extractor for the given model will be loaded (if it is a string). If model is not specified or not a string, then the default feature extractor for config is loaded (if it is a string). However, if config is also not given or not a string, then the default feature extractor for the given task will be loaded.

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

    Image processors are used for Vision models and multi-modal models that require image inputs. Multi-modal models will also require a tokenizer to be passed.

    If not provided, the default image processor for the given model will be loaded (if it is a string). If model is not specified or not a string, then the default image processor for config is loaded (if it is a string).

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

    Processors are used for multi-modal models that require multi-modal inputs, for example, a model that requires both text and image inputs.

    If not provided, the default processor for the given model will be loaded (if it is a string). If model is not specified or not a string, then the default processor for config is loaded (if it is a string).

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

    If no framework is specified, will default to the one currently installed. If no framework is specified and both frameworks are installed, will default to the framework of the model, or to PyTorch if no model is provided.

  • revision (str, optional, defaults to "main") — When passing a task name or a string model identifier: The specific model version to use. It can be a branch name, a tag name, or a commit id, since we use a git-based system for storing models and other artifacts on huggingface.co, so revision can be any identifier allowed by git.
  • use_fast (bool, optional, defaults to True) — 是否尽可能使用快速分词器 (PreTrainedTokenizerFast)。
  • use_auth_token (strbool, optional) — 用于远程文件的 HTTP Bearer 授权的令牌。如果为 True,将使用运行 huggingface-cli login 时生成的令牌(存储在 ~/.huggingface 中)。
  • device (intstrtorch.device) — 定义此 pipeline 将分配到的设备(例如"cpu""cuda:1""mps" 或类似 1 的 GPU 序号等级)。
  • device_map (strDict[str, Union[int, str, torch.device], optional) — 直接作为 model_kwargs 发送(只是一个更简单的快捷方式)。当 accelerate 库存在时,设置 device_map="auto" 以自动计算最优化的 device_map(有关更多信息,请参阅 此处)。

    请勿同时使用 device_mapdevice,因为它们会冲突

  • torch_dtype (strtorch.dtype, optional) — 直接作为 model_kwargs 发送(只是一个更简单的快捷方式),以使用此模型的可用精度 (torch.float16, torch.bfloat16, … 或 "auto")。
  • trust_remote_code (bool, optional, defaults to False) — 是否允许 Hub 上定义的自定义代码用于其自身的建模、配置、分词甚至 pipeline 文件中。此选项应仅针对您信任的仓库以及您已阅读代码的仓库设置为 True,因为它将在您的本地计算机上执行 Hub 上存在的代码。
  • model_kwargs (Dict[str, Any], optional) — 传递给模型的 from_pretrained(..., **model_kwargs) 函数的附加关键字参数字典。
  • kwargs (Dict[str, Any], optional) — 传递给特定 pipeline init 的附加关键字参数(有关可能的值,请参阅相应 pipeline 类的文档)。

返回:

Pipeline

适用于任务的 pipeline。

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

一个 pipeline 由以下部分组成:

虽然存在诸如 `tokenizer`、`feature_extractor`、`image_processor` 和 `processor` 等可选参数,但不应一次全部指定。如果未提供这些组件,`pipeline` 将尝试自动加载所需的组件。如果您想显式提供这些组件,请参阅特定的 pipeline,以获取有关需要哪些组件的更多详细信息。

示例:

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

Pipeline 批处理

所有 pipeline 都可以使用批处理。当 pipeline 使用其流式传输能力时(即在传递列表或 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 个 tokens 长,因此整个批次将是 [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 上,那么:

    • 如果您不了解 sequence_length 的大小(“自然”数据),默认情况下不要批处理,进行衡量并尝试初步添加它,添加 OOM 检查以在失败时恢复(如果您不控制 sequence_length,它将在某个时候失败)。
    • 如果您的 sequence_length 非常规则,那么批处理更有可能非常有趣,进行衡量并尽可能推送它,直到出现 OOM。
    • GPU 越大,批处理越有可能更有趣。
  • 一旦启用批处理,请确保您可以很好地处理 OOM。

Pipeline 块批处理

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

为了规避这个问题,这两个 pipeline 都有些特殊,它们是 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)

这对您的代码应该是非常透明的,因为 pipeline 的使用方式相同。

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

Pipeline FP16 推理

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

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

Pipeline 自定义代码

如果您想覆盖特定的 pipeline。

请随时针对您手头的任务创建 issue,pipeline 的目标是易于使用并支持大多数情况,因此 transformers 也许可以支持您的用例。

如果您想简单地尝试,您可以:

  • 子类化您选择的 pipeline
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)

这应该使您能够完成所有您想要的自定义代码。

实现 pipeline

实现新的 pipeline

音频

音频任务可用的 pipeline 包括以下几种:

AudioClassificationPipeline

class transformers.AudioClassificationPipeline

< >

( *args **kwargs )

Parameters

  • model (PreTrainedModelTFPreTrainedModel) — pipeline 将用于进行预测的模型。这需要是一个继承自 PyTorch 的 PreTrainedModel 和 TensorFlow 的 TFPreTrainedModel 的模型。
  • feature_extractor (SequenceFeatureExtractor) — feature extractor 将用于对模型数据进行编码。此对象继承自 SequenceFeatureExtractor
  • modelcard (strModelCard, optional) — 归属于此 pipeline 模型的模型卡。
  • framework (str, optional) — 要使用的框架,"pt" 代表 PyTorch,"tf" 代表 TensorFlow。必须安装指定的框架。

    如果未指定框架,则默认为当前安装的框架。如果未指定框架并且两个框架都已安装,则默认为 model 的框架,或者如果没有提供模型,则默认为 PyTorch。

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

音频分类 pipeline 使用任何 AutoModelForAudioClassification。此 pipeline 预测原始波形或音频文件的类别。如果是音频文件,应安装 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 教程 中了解有关使用 pipeline 的基础知识的更多信息

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

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

__call__

< >

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

Parameters

  • inputs (np.ndarraybytesstrdict) — 输入可以是以下之一:
    • str,即音频文件的文件名。文件将以正确的采样率读取,以使用 ffmpeg 获取波形。这需要在系统上安装 ffmpeg
    • bytes,它应该是音频文件的内容,并由 ffmpeg 以相同的方式解释。
    • (形状为 (n, ) 类型为 np.float32np.float64np.ndarray) 原始音频,采样率正确(不会进行进一步检查)
    • 可以使用 dict 格式传递以任意 sampling_rate 采样的原始音频,并让此 pipeline 进行重采样。dict 必须是 {"sampling_rate": int, "raw": np.array}{"sampling_rate": int, "array": np.array} 格式,其中键 "raw""array" 用于表示原始音频波形。
  • top_k (int, 可选, 默认为 None) — pipeline 将返回的前 k 个标签的数量。如果提供的数字为 None 或高于模型配置中可用的标签数量,则将默认为标签数量。
  • function_to_apply(str, 可选, 默认为 “softmax”) — 应用于模型输出的函数。默认情况下,pipeline 将 softmax 函数应用于模型的输出。有效选项:[“softmax”, “sigmoid”, “none”]。请注意,传递 Python 的内置 None 将默认为 “softmax”,因此您需要传递字符串 “none” 以禁用任何后处理。

返回:

包含以下键的 dict 列表

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

对作为输入给出的序列进行分类。有关更多信息,请参阅 AutomaticSpeechRecognitionPipeline 文档。

AutomaticSpeechRecognitionPipeline

class transformers.AutomaticSpeechRecognitionPipeline

< >

( model: PreTrainedModel feature_extractor: typing.Union[ForwardRef('SequenceFeatureExtractor'), str] = None tokenizer: typing.Optional[transformers.tokenization_utils.PreTrainedTokenizer] = None decoder: typing.Union[ForwardRef('BeamSearchDecoderCTC'), str, NoneType] = None device: typing.Union[int, ForwardRef('torch.device')] = None torch_dtype: typing.Union[str, ForwardRef('torch.dtype'), NoneType] = None **kwargs )

Parameters

  • model (PreTrainedModelTFPreTrainedModel) — pipeline 将用于进行预测的模型。这需要是一个继承自 PreTrainedModel (用于 PyTorch) 和 TFPreTrainedModel (用于 TensorFlow) 的模型。
  • feature_extractor (SequenceFeatureExtractor) — 特征提取器,pipeline 将使用它来编码模型的波形。
  • tokenizer (PreTrainedTokenizer) — tokenizer,pipeline 将使用它来编码模型的数据。此对象继承自 PreTrainedTokenizer
  • decoder (pyctcdecode.BeamSearchDecoderCTC, 可选) — 可以传递 PyCTCDecode 的 BeamSearchDecoderCTC 用于语言模型增强解码。有关更多信息,请参见 Wav2Vec2ProcessorWithLM
  • chunk_length_s (float, 可选, 默认为 0) — 每个 chunk 的输入长度。如果 chunk_length_s = 0,则禁用 chunking(默认)。

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

  • stride_length_s (float, 可选, 默认为 chunk_length_s / 6) — 每个 chunk 左右两侧的 stride 长度。仅与 chunk_length_s > 0 一起使用。这使模型能够看到更多上下文,并比没有此上下文更好地推断字母,但 pipeline 会丢弃末尾的 stride 位,以使最终重构尽可能完美。

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

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

旨在提取音频中包含的口语文本的 Pipeline。

输入可以是原始波形或音频文件。如果是音频文件,则应安装 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.'}

pipeline 教程 中了解有关使用 pipeline 的基础知识的更多信息

__call__

< >

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

Parameters

  • inputs (np.ndarraybytesstrdict) — 输入可以是以下之一:

    • str,即本地音频文件的文件名,或下载音频文件的公共 URL 地址。文件将以正确的采样率读取,以使用 ffmpeg 获取波形。这需要在系统上安装 ffmpeg
    • bytes,它应该是音频文件的内容,并由 ffmpeg 以相同的方式解释。
    • (形状为 (n, ) 类型为 np.float32np.float64np.ndarray) 原始音频,采样率正确(不会进行进一步检查)
    • 可以使用 dict 格式传递以任意 sampling_rate 采样的原始音频,并让此 pipeline 进行重采样。dict 必须是 {"sampling_rate": int, "raw": np.array} 格式,并且可以选择使用 "stride": (left: int, right: int),它可以要求 pipeline 处理前 left 个样本和后 right 个样本,以便在解码中忽略(但在推理中使用,以便为模型提供更多上下文)。仅将 stride 与 CTC 模型一起使用。
  • return_timestamps (可选, strbool) — 仅适用于纯 CTC 模型(Wav2Vec2、HuBERT 等)和 Whisper 模型。不适用于其他序列到序列模型。

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

    • "char":pipeline 将沿文本返回文本中每个字符的时间戳。例如,如果您得到 [{"text": "h", "timestamp": (0.5, 0.6)}, {"text": "i", "timestamp": (0.7, 0.9)}],则表示模型预测字母 “h” 在 0.5 秒之后和 0.6 秒之前被说出。
    • "word":pipeline 将沿文本返回文本中每个单词的时间戳。例如,如果您得到 [{"text": "hi ", "timestamp": (0.5, 0.9)}, {"text": "there", "timestamp": (1.0, 1.5)}],则表示模型预测单词 “hi” 在 0.5 秒之后和 0.9 秒之前被说出。

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

    • "word":与上述单词级 CTC 时间戳相同。单词级时间戳通过动态时间规整 (DTW) 算法预测,这是一种通过检查交叉注意力权重来近似单词级时间戳的方法。
    • True:pipeline 将沿文本返回文本中段落单词的时间戳。例如,如果您得到 [{"text": " Hi there!", "timestamp": (0.5, 1.5)}],则表示模型预测段落 “Hi there!” 在 0.5 秒之后和 1.5 秒之前被说出。请注意,文本段落指的是一个或多个单词的序列,而不是像单词级时间戳那样的单个单词。
  • generate_kwargs (dict, 可选) — generate_config 的特定参数字典,用于生成调用。有关生成的完整概述,请查看以下指南

返回:

Dict

包含以下键的字典

  • text (str): 识别的文本。
  • chunks (可选的, 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

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

pipeline 教程 中了解有关使用 pipeline 的基础知识的更多信息

您可以使用 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 ) 一个 dict 或一个 dict 列表

Parameters

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

返回:

一个 dict 或一个 dict 列表

字典包含两个键

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

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

ZeroShotAudioClassificationPipeline

class transformers.ZeroShotAudioClassificationPipeline

< >

( **kwargs )

Parameters

  • model (PreTrainedModelTFPreTrainedModel) — 管道将用于进行预测的模型。 这需要是一个继承自 PreTrainedModel(对于 PyTorch)和 TFPreTrainedModel(对于 TensorFlow)的模型。
  • tokenizer (PreTrainedTokenizer) — 分词器,管道将使用它来为模型编码数据。 此对象继承自 PreTrainedTokenizer
  • feature_extractor (SequenceFeatureExtractor) — 特征提取器,管道将使用它来为模型编码数据。 此对象继承自 SequenceFeatureExtractor
  • modelcard (strModelCard, 可选的) — 归属于此管道模型的模型卡。
  • framework (str, 可选的) — 要使用的框架,"pt" 代表 PyTorch,"tf" 代表 TensorFlow。 必须安装指定的框架。

    如果未指定框架,则默认为当前安装的框架。 如果未指定框架且两个框架都已安装,则默认为 model 的框架,如果未提供模型,则默认为 PyTorch。

  • task (str, 默认为 "") — 管道的任务标识符。
  • num_workers (int, 可选的, 默认为 8) — 当管道将使用 DataLoader 时(在 GPU 上为 Pytorch 模型传递数据集时),要使用的 worker 数量。
  • batch_size (int, 可选的, 默认为 1) — 当管道将使用 DataLoader 时(在 GPU 上为 Pytorch 模型传递数据集时),要使用的批次大小,对于推理来说这并不总是有利的,请阅读 管道批处理
  • args_parser (ArgumentHandler, 可选的) — 引用负责解析提供的管道参数的对象。
  • device (int, 可选的, 默认为 -1) — 用于 CPU/GPU 支持的设备序号。 将此设置为 -1 将利用 CPU,正值将在关联的 CUDA 设备 ID 上运行模型。 您也可以传递原生的 torch.devicestr
  • torch_dtype (strtorch.dtype, 可选的) — 直接作为 model_kwargs 发送(只是一个更简单的快捷方式),以使用此模型的可用精度(torch.float16torch.bfloat16、… 或 "auto"
  • binary_output (bool, 可选的, 默认为 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 )

Parameters

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

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

计算机视觉

可用于计算机视觉任务的 Pipeline 包括以下几种。

DepthEstimationPipeline

class transformers.DepthEstimationPipeline

< >

( *args **kwargs )

Parameters

  • model (PreTrainedModelTFPreTrainedModel) — Pipeline 将使用此模型进行预测。这需要是一个继承自 PreTrainedModel (用于 PyTorch) 和 TFPreTrainedModel (用于 TensorFlow) 的模型。
  • image_processor (BaseImageProcessor) — 图像处理器,pipeline 将使用它来编码模型数据。此对象继承自 BaseImageProcessor
  • modelcard (strModelCard, optional) — 归属于此 pipeline 模型的模型卡。
  • framework (str, optional) — 要使用的框架,"pt" 代表 PyTorch,"tf" 代表 TensorFlow。 必须安装指定的框架。

    如果未指定框架,则默认为当前安装的框架。 如果未指定框架并且同时安装了两个框架,则默认为 model 的框架;如果未提供模型,则默认为 PyTorch。

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

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

示例:

>>> 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 教程 中了解有关使用 pipeline 的基础知识的更多信息

此深度估计 pipeline 当前可以使用以下任务标识符从 pipeline() 加载:"depth-estimation"

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

__call__

< >

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

Parameters

  • inputs (str, List[str], PIL.ImageList[PIL.Image]) — pipeline 处理三种类型的图像:

    • 包含指向图像的 http 链接的字符串
    • 包含图像本地路径的字符串
    • 直接在 PIL 中加载的图像

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

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

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

ImageClassificationPipeline

class transformers.ImageClassificationPipeline

< >

( *args **kwargs )

Parameters

  • model (PreTrainedModelTFPreTrainedModel) — Pipeline 将使用此模型进行预测。这需要是一个继承自 PreTrainedModel (用于 PyTorch) 和 TFPreTrainedModel (用于 TensorFlow) 的模型。
  • image_processor (BaseImageProcessor) — 图像处理器,pipeline 将使用它来编码模型数据。此对象继承自 BaseImageProcessor
  • modelcard (strModelCard, optional) — 归属于此 pipeline 模型的模型卡。
  • framework (str, optional) — 要使用的框架,"pt" 代表 PyTorch,"tf" 代表 TensorFlow。 必须安装指定的框架。

    如果未指定框架,则默认为当前安装的框架。 如果未指定框架并且同时安装了两个框架,则默认为 model 的框架;如果未提供模型,则默认为 PyTorch。

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

    • "default":如果模型具有单个标签,则将 sigmoid 函数应用于输出。如果模型有多个标签,则将 softmax 函数应用于输出。
    • "sigmoid":将 sigmoid 函数应用于输出。
    • "softmax":将 softmax 函数应用于输出。
    • "none":不对输出应用任何函数。

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

示例:

>>> 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 教程 中了解有关使用 pipeline 的基础知识的更多信息

此图像分类 pipeline 当前可以从 pipeline() 使用以下任务标识符加载: "image-classification"

请参阅 huggingface.co/models 上可用的模型列表。

__call__

< >

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

Parameters

  • inputs (str, List[str], PIL.Image or List[PIL.Image]) — pipeline 处理三种类型的图像:

    • 包含指向图像的 http 链接的字符串
    • 包含图像本地路径的字符串
    • 直接在 PIL 中加载的图像

    pipeline 接受单个图像或一批图像,然后必须作为字符串传递。批处理中的图像必须都采用相同的格式:全部为 http 链接、全部为本地路径或全部为 PIL 图像。

  • function_to_apply (str, optional, defaults to "default") — 应用于模型输出以检索分数的函数。接受四个不同的值:

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

    • 如果模型具有单个标签,则将 sigmoid 函数应用于输出。
    • 如果模型有多个标签,则将 softmax 函数应用于输出。

    可能的值为:

    • "sigmoid":将 sigmoid 函数应用于输出。
    • "softmax":将 softmax 函数应用于输出。
    • "none":不对输出应用任何函数。
  • top_k (int, optional, defaults to 5) — pipeline 将返回的顶部标签的数量。如果提供的数字高于模型配置中可用的标签数量,它将默认为标签数量。
  • timeout (float, optional, defaults to None) — 等待从网络获取图像的最长时间(秒)。如果为 None,则不设置超时,并且调用可能会永远阻塞。

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

ImageSegmentationPipeline

class transformers.ImageSegmentationPipeline

< >

( *args **kwargs )

Parameters

  • model (PreTrainedModel or TFPreTrainedModel) — pipeline 将用于进行预测的模型。这需要是一个继承自 PyTorch 的 PreTrainedModel 和 TensorFlow 的 TFPreTrainedModel 的模型。
  • image_processor (BaseImageProcessor) — 图像处理器,pipeline 将使用它来编码模型数据。此对象继承自 BaseImageProcessor
  • modelcard (str or ModelCard, optional) — 归因于此 pipeline 模型的模型卡。
  • framework (str, optional) — 要使用的框架,"pt" 代表 PyTorch,"tf" 代表 TensorFlow。必须安装指定的框架。

    如果未指定框架,则默认为当前安装的框架。如果未指定框架并且两个框架都已安装,则默认为 model 的框架;如果未提供模型,则默认为 PyTorch。

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

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

示例:

>>> 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 当前可以从 pipeline() 使用以下任务标识符加载: "image-segmentation"

请参阅 huggingface.co/models 上可用的模型列表。

__call__

< >

( inputs = None **kwargs )

Parameters

  • inputs (str, List[str], PIL.Image or List[PIL.Image]) — pipeline 处理三种类型的图像:

    • 包含指向图像的 HTTP(S) 链接的字符串
    • 包含图像本地路径的字符串
    • 直接在 PIL 中加载的图像

    pipeline 接受单个图像或一批图像。批处理中的图像必须都采用相同的格式:全部为 HTTP(S) 链接、全部为本地路径或全部为 PIL 图像。

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

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

ImageToImagePipeline

class transformers.ImageToImagePipeline

< >

( *args **kwargs )

Parameters

  • model (PreTrainedModelTFPreTrainedModel) — pipeline 将用于进行预测的模型。这需要是一个继承自 PreTrainedModel (针对 PyTorch) 和 TFPreTrainedModel (针对 TensorFlow) 的模型。
  • image_processor (BaseImageProcessor) — pipeline 将用于为模型编码数据的图像处理器 (image processor)。此对象继承自 BaseImageProcessor
  • modelcard (strModelCard, optional) — 归属于此 pipeline 模型的模型卡 (Model card)。
  • framework (str, optional) — 要使用的框架,"pt" 代表 PyTorch,"tf" 代表 TensorFlow。指定的框架必须已安装。

    如果未指定框架,则默认为当前安装的框架。如果未指定框架且两个框架都已安装,则默认为 model 的框架,如果未提供模型,则默认为 PyTorch。

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

使用任何 AutoModelForImageToImage 的 Image to Image pipeline。此 pipeline 基于先前的图像输入生成图像。

示例:

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

此 image to image pipeline 当前可以从 pipeline() 使用以下任务标识符加载:"image-to-image"

请参阅 huggingface.co/models 上的可用模型列表。

__call__

< >

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

Parameters

  • images (str, List[str], PIL.ImageList[PIL.Image]) — pipeline 处理三种类型的图像:

    • 包含指向图像的 http 链接的字符串
    • 包含图像本地路径的字符串
    • 直接在 PIL 中加载的图像

    pipeline 接受单个图像或一批图像,然后必须作为字符串传递。批处理中的图像必须都采用相同的格式:全部为 http 链接,全部为本地路径,或全部为 PIL 图像。

  • timeout (float, optional, defaults to None) — 从网络获取图像时等待的最长时间(秒)。如果为 None,则不使用超时,调用可能会永远阻塞。

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

ObjectDetectionPipeline

class transformers.ObjectDetectionPipeline

< >

( *args **kwargs )

Parameters

  • model (PreTrainedModelTFPreTrainedModel) — pipeline 将用于进行预测的模型。这需要是一个继承自 PreTrainedModel (针对 PyTorch) 和 TFPreTrainedModel (针对 TensorFlow) 的模型。
  • image_processor (BaseImageProcessor) — pipeline 将用于为模型编码数据的图像处理器 (image processor)。此对象继承自 BaseImageProcessor
  • modelcard (strModelCard, optional) — 归属于此 pipeline 模型的模型卡 (Model card)。
  • framework (str, optional) — 要使用的框架,"pt" 代表 PyTorch,"tf" 代表 TensorFlow。指定的框架必须已安装。

    如果未指定框架,则默认为当前安装的框架。如果未指定框架且两个框架都已安装,则默认为 model 的框架,如果未提供模型,则默认为 PyTorch。

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

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

示例:

>>> 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 教程 中了解有关使用 pipeline 的基础知识的更多信息

此对象检测 pipeline 当前可以从 pipeline() 中使用以下任务标识符加载:"object-detection"

请参阅 huggingface.co/models 上的可用模型列表。

__call__

< >

( *args **kwargs )

Parameters

  • inputs (str, List[str], PIL.ImageList[PIL.Image]) — pipeline 处理三种类型的图像:

    • 包含指向图像的 HTTP(S) 链接的字符串
    • 包含图像本地路径的字符串
    • 直接在 PIL 中加载的图像

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

  • threshold (float, optional, defaults to 0.5) — 进行预测所需的概率。
  • timeout (float, optional, defaults to None) — 从网络获取图像的最长等待时间(秒)。如果为 None,则不设置超时,并且调用可能会永远阻塞。

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

VideoClassificationPipeline

class transformers.VideoClassificationPipeline

< >

( *args **kwargs )

Parameters

  • model (PreTrainedModelTFPreTrainedModel) — pipeline 将用于进行预测的模型。这需要是一个继承自 PyTorch 的 PreTrainedModel 模型和 TensorFlow 的 TFPreTrainedModel 模型。
  • image_processor (BaseImageProcessor) — pipeline 将用于为模型编码数据的图像处理器。此对象继承自 BaseImageProcessor
  • modelcard (strModelCard, optional) — 归因于此 pipeline 模型的模型卡。
  • framework (str, optional) — 要使用的框架,"pt" 代表 PyTorch,"tf" 代表 TensorFlow。必须安装指定的框架。

    如果未指定框架,则默认为当前安装的框架。如果未指定框架并且两个框架都已安装,则默认为 model 的框架,如果未提供模型,则默认为 PyTorch。

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

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

此视频分类 pipeline 当前可以从 pipeline() 中使用以下任务标识符加载:"video-classification"

请参阅 huggingface.co/models 上的可用模型列表。

__call__

< >

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

Parameters

  • inputs (str, List[str]) — pipeline 处理三种类型的视频:

    • 包含指向视频的 http 链接的字符串
    • 包含视频本地路径的字符串

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

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

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

ZeroShotImageClassificationPipeline

class transformers.ZeroShotImageClassificationPipeline

< >

( **kwargs )

Parameters

  • model (PreTrainedModelTFPreTrainedModel) — pipeline 将用于进行预测的模型。这需要是一个继承自 PreTrainedModel (对于 PyTorch) 和 TFPreTrainedModel (对于 TensorFlow) 的模型。
  • image_processor (BaseImageProcessor) — 将被 pipeline 用于编码模型数据的图像处理器。此对象继承自 BaseImageProcessor
  • modelcard (strModelCard, 可选) — 归属于此 pipeline 模型的模型卡。
  • framework (str, 可选) — 要使用的框架,"pt" 代表 PyTorch,"tf" 代表 TensorFlow。 必须安装指定的框架。

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

  • task (str, 默认为 "") — pipeline 的任务标识符。
  • num_workers (int, 可选, 默认为 8) — 当 pipeline 将使用 DataLoader (当传递数据集时,在 GPU 上用于 Pytorch 模型),要使用的工作进程数。
  • batch_size (int, 可选, 默认为 1) — 当 pipeline 将使用 DataLoader (当传递数据集时,在 GPU 上用于 Pytorch 模型),要使用的批次大小,对于推理来说这并不总是有益的,请阅读 使用 pipelines 进行批处理
  • args_parser (ArgumentHandler, 可选) — 负责解析提供的 pipeline 参数的对象的引用。
  • 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) — 标志,指示 pipeline 的输出应以序列化格式(即 pickle)还是原始输出数据(例如文本)发生。

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

示例:

>>> 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 教程 中了解有关使用 pipeline 的基础知识的更多信息

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

请参阅 huggingface.co/models 上的可用模型列表。

__call__

< >

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

Parameters

  • image (str, List[str], PIL.ImageList[PIL.Image]) — pipeline 处理三种类型的图像:

    • 包含指向图像的 http 链接的字符串
    • 包含图像本地路径的字符串
    • 直接在 PIL 中加载的图像
  • candidate_labels (List[str]) — 此图像的候选标签。它们将使用 hypothesis_template 格式化。
  • hypothesis_template (str, 可选, 默认为 "This is a photo of {}") — 与 candidate_labels 结合使用的格式,通过将占位符替换为 candidate_labels 来尝试图像分类。如果 candidate_labels 已经格式化,则传递 ”{}”。
  • timeout (float, 可选, 默认为 None) — 等待从网络获取图像的最长时间(秒)。如果为 None,则不设置超时,并且调用可能会永远阻塞。

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

ZeroShotObjectDetectionPipeline

class transformers.ZeroShotObjectDetectionPipeline

< >

( **kwargs )

Parameters

  • model (PreTrainedModelTFPreTrainedModel) — pipeline 将用于进行预测的模型。这需要是一个继承自 PreTrainedModel (对于 PyTorch) 和 TFPreTrainedModel (对于 TensorFlow) 的模型。
  • image_processor (BaseImageProcessor) — 将被 pipeline 用于编码模型数据的图像处理器。此对象继承自 BaseImageProcessor
  • modelcard (strModelCard, 可选) — 归属于此 pipeline 模型的模型卡。
  • framework (str, 可选) — 要使用的框架,"pt" 代表 PyTorch,"tf" 代表 TensorFlow。 必须安装指定的框架。

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

  • task (str, 默认为 "") — pipeline 的任务标识符。
  • num_workers (int, 可选,默认为 8) — 当 pipeline 将使用 DataLoader 时 (当传递数据集时,在 GPU 上用于 Pytorch 模型),要使用的 workers 数量。
  • batch_size (int, 可选,默认为 1) — 当 pipeline 将使用 DataLoader 时 (当传递数据集时,在 GPU 上用于 Pytorch 模型),要使用的批次大小。对于推理来说,这并不总是有益的,请阅读 使用 pipelines 进行批处理
  • args_parser (ArgumentHandler, 可选) — 负责解析提供的 pipeline 参数的对象的引用。
  • 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) — 标志,指示 pipeline 的输出是否应以序列化格式(即 pickle)或原始输出数据(例如文本)的形式进行。

使用 OwlViTForObjectDetection 的 Zero shot 目标检测 pipeline。当您提供图像和一组 candidate_labels 时,此 pipeline 会预测物体的边界框。

示例:

>>> 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 教程 中了解有关使用 pipeline 的基础知识的更多信息

目前可以从 pipeline() 加载此目标检测 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 )

Parameters

  • image (str, PIL.ImageList[Dict[str, Any]]) — pipeline 处理三种类型的图像:

    • 包含指向图像的 http url 的字符串
    • 包含图像本地路径的字符串
    • 直接在 PIL 中加载的图像

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

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

自然语言处理

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

FillMaskPipeline

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

Parameters

  • model (PreTrainedModelTFPreTrainedModel) — pipeline 将用于进行预测的模型。这需要是一个继承自 PyTorch 的 PreTrainedModel 和 TensorFlow 的 TFPreTrainedModel 的模型。
  • tokenizer (PreTrainedTokenizer) — tokenizer 将被 pipeline 用于为模型编码数据。此对象继承自 PreTrainedTokenizer
  • modelcard (strModelCard, 可选) — 归属于此 pipeline 模型的 Model card。
  • framework (str, 可选) — 要使用的框架,"pt" 用于 PyTorch,"tf" 用于 TensorFlow。必须安装指定的框架。

    如果未指定框架,则默认为当前安装的框架。如果未指定框架且同时安装了两个框架,则默认为 model 的框架,如果未提供模型,则默认为 PyTorch。

  • task (str, 默认为 "") — pipeline 的任务标识符。
  • num_workers (int, 可选,默认为 8) — 当 pipeline 将使用 DataLoader 时 (当传递数据集时,在 GPU 上用于 Pytorch 模型),要使用的 workers 数量。
  • batch_size (int, 可选,默认为 1) — 当 pipeline 将使用 DataLoader 时 (当传递数据集时,在 GPU 上用于 Pytorch 模型),要使用的批次大小。对于推理来说,这并不总是有益的,请阅读 使用 pipelines 进行批处理
  • args_parser (ArgumentHandler, 可选) — 负责解析提供的 pipeline 参数的对象的引用。
  • 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) — 标志,指示 pipeline 的输出是否应以序列化格式(即 pickle)或原始输出数据(例如文本)的形式进行。
  • top_k (int, 可选,默认为 5) — 要返回的预测数量。
  • targets (str or List[str], optional) — 当传入时,模型将把分数限制为传入的目标,而不是在整个词汇表中查找。如果提供的目标不在模型词汇表中,它们将被标记化,并将使用第一个生成的标记(带有警告,并且可能会更慢)。
  • 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 教程 中了解有关使用 pipeline 的基础知识的更多信息

此掩码填充管道目前可以从 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 列表的列表

Parameters

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

返回:

一个列表或一个 dict 列表的列表

每个结果都以字典列表的形式出现,其中包含以下键

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

填充作为输入给出的文本中的掩码标记。

QuestionAnsweringPipeline

class transformers.QuestionAnsweringPipeline

< >

( model: typing.Union[ForwardRef('PreTrainedModel'), ForwardRef('TFPreTrainedModel')] tokenizer: PreTrainedTokenizer modelcard: typing.Optional[transformers.modelcard.ModelCard] = None framework: typing.Optional[str] = None task: str = '' **kwargs )

Parameters

  • model (PreTrainedModelTFPreTrainedModel) — 管道将用于进行预测的模型。 这需要是一个继承自 PreTrainedModel (对于 PyTorch) 和 TFPreTrainedModel (对于 TensorFlow) 的模型。
  • tokenizer (PreTrainedTokenizer) — 分词器,管道将使用它来为模型编码数据。 此对象继承自 PreTrainedTokenizer
  • modelcard (strModelCard, optional) — 归属于此管道模型的模型卡。
  • framework (str, optional) — 要使用的框架,"pt" 代表 PyTorch,"tf" 代表 TensorFlow。 必须安装指定的框架。

    如果未指定框架,则默认为当前安装的框架。 如果未指定框架并且安装了两个框架,则默认为 model 的框架,或者如果未提供模型,则默认为 PyTorch。

  • task (str, defaults to "") — 管道的任务标识符。
  • num_workers (int, optional, defaults to 8) — 当管道将使用 DataLoader 时(当传递数据集时,在 GPU 上用于 Pytorch 模型),要使用的工作人员数量。
  • batch_size (int, optional, defaults to 1) — 当管道将使用 DataLoader 时(当传递数据集时,在 GPU 上用于 Pytorch 模型),要使用的批次大小,对于推理,这并不总是有益,请阅读 使用管道进行批处理
  • args_parser (ArgumentHandler, optional) — 负责解析提供的管道参数的对象引用。
  • device (int, optional, defaults to -1) — 用于 CPU/GPU 支持的设备序号。 将此设置为 -1 将利用 CPU,正数将在关联的 CUDA 设备 ID 上运行模型。 您也可以传递原生 torch.devicestr
  • torch_dtype (strtorch.dtype, optional) — 直接作为 model_kwargs 发送(只是一个更简单的快捷方式),以使用此模型的可用精度 (torch.float16, torch.bfloat16, … 或 "auto")。
  • binary_output (bool, optional, defaults to 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 教程 中了解有关使用 pipeline 的基础知识的更多信息

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

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

__call__

< >

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

Parameters

  • question (strList[str]) — 一个或多个问题(必须与 context 参数结合使用)。
  • context (strList[str]) — 与问题关联的一个或多个上下文(必须与 question 参数结合使用)。
  • top_k (int, optional, defaults to 1) — 要返回的答案数量(将按可能性顺序选择)。 请注意,如果上下文中没有足够的选项可用,我们返回的答案将少于 top_k 个。
  • doc_stride (int, optional, defaults to 128) — 如果上下文太长而无法与问题一起放入模型,则会将其拆分为几个块,并带有一些重叠。 此参数控制该重叠的大小。
  • max_answer_len (int, optional, defaults to 15) — 预测答案的最大长度(例如,仅考虑长度较短的答案)。
  • max_seq_len (int, optional, defaults to 384) — 每个传递给模型的块中,总句子(上下文 + 问题)的最大标记长度。 如果需要,上下文将被拆分为多个块(使用 doc_stride 作为重叠)。
  • max_question_len (int, 可选,默认为 64) — 问题在分词后的最大长度。如果需要,将会被截断。
  • handle_impossible_answer (bool, 可选,默认为 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

Parameters

  • question (strList[str]) — 被提出的问题(可以是一个或多个)。
  • context (strList[str]) — 我们将在其中寻找答案的上下文(可以是一个或多个)。

返回:

一个或一组 SquadExample

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

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

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

span_to_answer

< >

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

Parameters

  • text (str) — 从中提取答案的实际上下文。
  • start (int) — 答案起始词语索引。
  • end (int) — 答案结束词语索引。

返回:

类似字典的结构 `{‘answer’

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

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

SummarizationPipeline

class transformers.SummarizationPipeline

< >

( *args **kwargs )

Parameters

  • model (PreTrainedModelTFPreTrainedModel) — 管道将用于进行预测的模型。这需要是一个继承自 PreTrainedModel (针对 PyTorch) 和 TFPreTrainedModel (针对 TensorFlow) 的模型。
  • tokenizer (PreTrainedTokenizer) — 管道将用于为模型编码数据的分词器。此对象继承自 PreTrainedTokenizer
  • modelcard (strModelCard, 可选) — 此管道模型的模型卡。
  • framework (str, 可选) — 要使用的框架,"pt" 代表 PyTorch,"tf" 代表 TensorFlow。必须安装指定的框架。

    如果未指定框架,则默认为当前安装的框架。如果未指定框架且两个框架都已安装,则默认为 model 的框架,如果未提供模型,则默认为 PyTorch。

  • task (str, 默认为 "") — 管道的任务标识符。
  • num_workers (int, 可选,默认为 8) — 当管道将使用 DataLoader 时(当传递数据集时,在 GPU 上用于 Pytorch 模型),要使用的工作进程数。
  • batch_size (int, 可选,默认为 1) — 当管道将使用 DataLoader 时(当传递数据集时,在 GPU 上用于 Pytorch 模型),要使用的批次大小,对于推理来说,这并不总是有益的,请阅读 管道批处理
  • 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() 使用以下任务标识符加载: "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 的列表或列表的列表

Parameters

  • documents (strList[str]) — 一篇或多篇文章(或文章列表)用于概括。
  • return_text (bool, optional, 默认为 True) — 是否在输出中包含解码后的文本
  • return_tensors (bool, optional, 默认为 False) — 是否在输出中包含预测的张量(作为 token 索引)。
  • clean_up_tokenization_spaces (bool, optional, 默认为 False) — 是否清理文本输出中潜在的额外空格。
  • generate_kwargs — 传递给模型的 generate 方法的附加关键字参数(请参阅与您的框架对应的 generate 方法此处)。

返回:

一个列表或一个 dict 列表的列表

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

  • summary_text (str, 当 return_text=True 时出现) — 对应输入的摘要。
  • summary_token_ids (torch.Tensortf.Tensor, 当 return_tensors=True 时出现) — 摘要的 token id。

概括作为输入给出的文本。

TableQuestionAnsweringPipeline

class transformers.TableQuestionAnsweringPipeline

< >

( args_parser = <transformers.pipelines.table_question_answering.TableQuestionAnsweringArgumentHandler object at 0x7f7879e55ff0> *args **kwargs )

Parameters

  • model (PreTrainedModelTFPreTrainedModel) — 管道将用于进行预测的模型。这需要是一个继承自 PreTrainedModel (对于 PyTorch) 和 TFPreTrainedModel (对于 TensorFlow) 的模型。
  • tokenizer (PreTrainedTokenizer) — tokenizer 将用于管道为模型编码数据。此对象继承自 PreTrainedTokenizer
  • modelcard (strModelCard, optional) — 归属于此管道模型的模型卡。
  • framework (str, optional) — 要使用的框架,"pt" 代表 PyTorch,"tf" 代表 TensorFlow。 必须安装指定的框架。

    如果未指定框架,将默认为当前安装的框架。 如果未指定框架且两个框架都已安装,则将默认为 model 的框架,或者如果未提供模型,则默认为 PyTorch。

  • task (str, 默认为 "") — 管道的任务标识符。
  • num_workers (int, optional, 默认为 8) — 当管道将使用 DataLoader 时(当传递数据集时,在 GPU 上用于 Pytorch 模型),要使用的工作进程数。
  • batch_size (int, optional, 默认为 1) — 当管道将使用 DataLoader 时(当传递数据集时,在 GPU 上用于 Pytorch 模型),要使用的批次大小,对于推理,这并不总是有益,请阅读 使用管道进行批处理
  • args_parser (ArgumentHandler, optional) — 引用负责解析提供的管道参数的对象。
  • device (int, optional, 默认为 -1) — 用于 CPU/GPU 支持的设备序号。 设置为 -1 将利用 CPU,正数将在关联的 CUDA 设备 ID 上运行模型。 您也可以传递原生 torch.devicestr
  • torch_dtype (strtorch.dtype, optional) — 直接作为 model_kwargs 发送(只是一个更简单的快捷方式),以使用此模型的可用精度 (torch.float16, torch.bfloat16, … 或 "auto")
  • binary_output (bool, optional, 默认为 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 教程 中了解有关使用 pipeline 的基础知识的更多信息

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

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

__call__

< >

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

Parameters

  • table (pd.DataFrameDict) — Pandas DataFrame 或字典,将转换为包含所有表格值的 DataFrame。 有关字典示例,请参见上文。
  • query (strList[str]) — 查询或查询列表,将与表格一起发送到模型。
  • sequential (bool, optional, 默认为 False) — 是否按顺序或批量执行推理。 批量处理速度更快,但像 SQA 这样的模型需要按顺序完成推理,以提取序列中的关系,因为它们的对话性质。
  • padding (bool, strPaddingStrategy, optional, 默认为 False) — 激活和控制填充。 接受以下值:

    • True'longest':填充到批次中最长的序列(如果仅提供单个序列,则不填充)。
    • 'max_length':填充到参数 max_length 指定的最大长度,如果未提供该参数,则填充到模型可接受的最大输入长度。
    • False'do_not_pad' (默认):不填充(即,可以输出具有不同长度序列的批次)。
  • truncation (bool, strTapasTruncationStrategy, optional, 默认为 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 参数应为 dict 或从该 dict 构建的 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)

TextClassificationPipeline

class transformers.TextClassificationPipeline

< >

( **kwargs )

Parameters

  • model (PreTrainedModelTFPreTrainedModel) — 将被 pipeline 用于进行预测的模型。这需要是一个继承自 PreTrainedModel (用于 PyTorch) 和 TFPreTrainedModel (用于 TensorFlow) 的模型。
  • tokenizer (PreTrainedTokenizer) — 将被 pipeline 用于为模型编码数据的分词器。此对象继承自 PreTrainedTokenizer
  • modelcard (strModelCard, 可选) — 归属于此 pipeline 模型的模型卡。
  • framework (str, 可选) — 要使用的框架,"pt" 用于 PyTorch,"tf" 用于 TensorFlow。指定的框架必须已安装。

    如果未指定框架,则默认为当前安装的框架。如果未指定框架且两个框架都已安装,则默认为 model 的框架,如果未提供模型,则默认为 PyTorch。

  • task (str, 默认为 "") — pipeline 的任务标识符。
  • num_workers (int, 可选, 默认为 8) — 当 pipeline 将使用 DataLoader 时(当传递数据集时,在 GPU 上用于 Pytorch 模型),要使用的工作进程数。
  • batch_size (int, 可选, 默认为 1) — 当 pipeline 将使用 DataLoader 时(当传递数据集时,在 GPU 上用于 Pytorch 模型),要使用的批次大小,对于推理来说,这并不总是有益的,请阅读 使用 pipelines 进行批处理
  • args_parser (ArgumentHandler, 可选) — 引用负责解析提供的 pipeline 参数的对象。
  • 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) — 标志,指示 pipeline 的输出是否应以序列化格式(即 pickle)或原始输出数据(例如文本)进行。
  • return_all_scores (bool, 可选, 默认为 False) — 是否返回所有预测分数,或者仅返回预测类别的分数。
  • function_to_apply (str, 可选, 默认为 "default") — 为了检索分数而应用于模型输出的函数。接受四个不同的值:

    • "default":如果模型只有一个标签,则将 sigmoid 函数应用于输出。如果模型有多个标签,则将 softmax 函数应用于输出。对于回归任务,将不对输出应用任何函数。
    • "sigmoid":将 sigmoid 函数应用于输出。
    • "softmax":将 softmax 函数应用于输出。
    • "none":不对输出应用任何函数。

文本分类 pipeline 使用任何 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 教程 中了解有关使用 pipeline 的基础知识的更多信息

此文本分类 pipeline 当前可以从 pipeline() 使用以下任务标识符加载: "sentiment-analysis"(用于根据正面或负面情感对序列进行分类)。

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

此 pipeline 可以使用的模型是在序列分类任务上微调过的模型。 请参阅 huggingface.co/models 上可用的最新模型列表。

__call__

< >

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

Parameters

  • inputs (strList[str]Dict[str], 或 List[Dict[str]]) — 要分类的一个或多个文本。 为了对文本对进行分类,您可以发送包含 {"text", "text_pair"} 键的字典,或这些字典的列表。
  • top_k (int, 可选, 默认为 1) — 要返回的结果数。
  • function_to_apply (str, 可选, 默认为 "default") — 为了检索分数而应用于模型输出的函数。接受四个不同的值:

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

    • 如果问题类型是回归,则不对输出应用任何函数。
    • 如果模型只有一个标签,则将 sigmoid 函数应用于输出。
    • 如果模型有多个标签,则将 softmax 函数应用于输出。

    可能的值为:

    • "sigmoid":将 sigmoid 函数应用于输出。
    • "softmax":将 softmax 函数应用于输出。
    • "none":不对输出应用任何函数。

返回:

一个列表或一个 dict 列表的列表

每个结果都以字典列表的形式出现,其中包含以下键

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

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

对作为输入给出的文本进行分类。

TextGenerationPipeline

class transformers.TextGenerationPipeline

< >

( *args **kwargs )

Parameters

  • model (PreTrainedModelTFPreTrainedModel) — 将被 pipeline 用于进行预测的模型。这需要是一个继承自 PreTrainedModel (用于 PyTorch) 和 TFPreTrainedModel (用于 TensorFlow) 的模型。
  • tokenizer (PreTrainedTokenizer) — 将被 pipeline 用于为模型编码数据的分词器。此对象继承自 PreTrainedTokenizer
  • modelcard (strModelCard, 可选) — 归属于此 pipeline 模型的模型卡。
  • framework (str, 可选) — 要使用的框架,"pt" 用于 PyTorch,"tf" 用于 TensorFlow。指定的框架必须已安装。

    如果未指定框架,则默认为当前安装的框架。如果未指定框架且两个框架都已安装,则默认为 model 的框架,如果未提供模型,则默认为 PyTorch。

  • task (str, 默认为 "") — pipeline 的任务标识符。
  • num_workers (int, 可选, 默认为 8) — 当 pipeline 将使用 DataLoader 时(当传递数据集时,在 GPU 上用于 Pytorch 模型),要使用的工作进程数。
  • batch_size (int, 可选, 默认为 1) — 当 pipeline 将使用 DataLoader 时(当传递数据集时,在 GPU 上用于 Pytorch 模型),要使用的批次大小,对于推理来说,这并不总是有益的,请阅读 使用 pipelines 进行批处理
  • args_parser (ArgumentHandler, 可选) — 引用负责解析提供的 pipeline 参数的对象。
  • 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)或原始输出数据(例如文本)形式进行。

使用任何 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 的列表或列表的列表

Parameters

  • text_inputs (str, List[str], Dict[str, str] 的列表, 或 List[List[Dict[str, str]]]) — 要完成的一个或多个提示(或一个提示列表)。如果传递字符串或字符串列表,则此管道将继续每个提示。或者,可以传递“聊天记录”,其形式为包含 “role” 和 “content” 键的字典列表,或者此类聊天记录的列表。当传递聊天记录时,模型的聊天模板将用于在将其传递给模型之前对其进行格式化。
  • return_tensors (bool, 可选, 默认为 False) — 在输出中返回预测张量(作为标记索引)。如果设置为 True,则不返回解码后的文本。
  • return_text (bool, 可选) — 在输出中返回解码后的文本。
  • return_full_text (bool, 可选, 默认为 True) — 如果设置为 False,则仅返回添加的文本,否则返回完整文本。不能与 return_text 同时指定。
  • clean_up_tokenization_spaces (bool, 可选, 默认为 True) — 是否清理文本输出中潜在的额外空格。
  • continue_final_message( bool, 可选) — 这表示您希望模型继续输入聊天记录中的最后一条消息,而不是开始新的消息,从而允许您“预填充”其响应。默认情况下,当输入聊天记录中的最后一条消息具有 assistant 角色时,此项为 True,否则为 False,但您可以通过设置此标志手动覆盖该行为。
  • prefix (str, 可选) — 添加到提示的前缀。
  • handle_long_generation (str, 可选) — 默认情况下,此管道不处理长生成(超过模型最大长度的生成)。没有完美的方法来解决这个问题(更多信息:https://github.com/huggingface/transformers/issues/14033#issuecomment-948385227)。这提供了根据您的用例解决此问题的常用策略。

    • None: 默认策略,不进行任何特殊处理
    • "hole": 截断输入的左侧,并留下足够宽的间隙以进行生成(可能会截断大量提示,并且不适用于生成超出模型容量的情况)
  • generate_kwargs (dict, 可选) — 要传递给模型的 generate 方法的其他关键字参数(请参阅与您的框架对应的 generate 方法 此处)。

返回:

dict 的列表或列表的列表

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

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

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

Text2TextGenerationPipeline

class transformers.Text2TextGenerationPipeline

< >

( *args **kwargs )

Parameters

  • model (PreTrainedModelTFPreTrainedModel) — 管道将用于进行预测的模型。这需要是一个继承自 PreTrainedModel(对于 PyTorch)和 TFPreTrainedModel(对于 TensorFlow)的模型。
  • tokenizer (PreTrainedTokenizer) — 管道将用于为模型编码数据的分词器。此对象继承自 PreTrainedTokenizer
  • modelcard (strModelCard, 可选) — 归因于此管道模型的模型卡。
  • framework (str, 可选) — 要使用的框架,"pt" 表示 PyTorch,"tf" 表示 TensorFlow。必须安装指定的框架。

    如果未指定框架,则默认为当前安装的框架。如果未指定框架且两个框架都已安装,则默认为 model 的框架;如果未提供模型,则默认为 PyTorch。

  • task (str, 默认为 "") — 管道的任务标识符。
  • num_workers (int, 可选, 默认为 8) — 当管道将使用 DataLoader 时(当传递数据集时,在 GPU 上用于 Pytorch 模型),要使用的工作人员数量。
  • batch_size (int, 可选, 默认为 1) — 当管道将使用 DataLoader 时(当传递数据集时,在 GPU 上用于 Pytorch 模型),要使用的批次大小,对于推理而言,这并非总是有利的,请阅读 使用管道进行批处理
  • 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)还是原始输出数据(例如文本)形式进行。

使用 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 的列表或列表的列表

Parameters

  • args (strList[str]) — 编码器的输入文本。
  • return_tensors (bool, 可选, 默认为 False) — 是否在输出中包含预测张量(作为标记索引)。
  • return_text (bool, 可选, 默认为 True) — 是否在输出中包含解码后的文本。
  • clean_up_tokenization_spaces (bool, 可选, 默认为 False) — 是否清理文本输出中潜在的额外空格。
  • truncation (TruncationStrategy, 可选, 默认为 TruncationStrategy.DO_NOT_TRUNCATE) — 管道内分词的截断策略。TruncationStrategy.DO_NOT_TRUNCATE(默认)将永远不会截断,但有时希望截断输入以适应模型的 max_length,而不是在稍后抛出错误。
  • generate_kwargs — 传递给模型的 generate 方法的附加关键字参数(请参阅此处与您的框架对应的 generate 方法)。

返回:

一个列表或一个 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

class transformers.TokenClassificationPipeline

< >

( args_parser = <transformers.pipelines.token_classification.TokenClassificationArgumentHandler object at 0x7f7879e235e0> *args **kwargs )

Parameters

  • model (PreTrainedModelTFPreTrainedModel) — 管道将用于进行预测的模型。这需要是一个继承自 PreTrainedModel(对于 PyTorch)和 TFPreTrainedModel(对于 TensorFlow)的模型。
  • tokenizer (PreTrainedTokenizer) — 管道将用于为模型编码数据的分词器。此对象继承自 PreTrainedTokenizer
  • modelcard (strModelCard, 可选) — 归属于此管道模型的模型卡。
  • framework (str, 可选) — 要使用的框架,"pt" 代表 PyTorch,"tf" 代表 TensorFlow。必须安装指定的框架。

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

  • task (str, 默认为 "") — 管道的任务标识符。
  • num_workers (int, 可选, 默认为 8) — 当管道将使用 DataLoader 时(当传递数据集时,在 GPU 上用于 Pytorch 模型),要使用的 worker 数量。
  • batch_size (int, 可选, 默认为 1) — 当管道将使用 DataLoader 时(当传递数据集时,在 GPU 上用于 Pytorch 模型),要使用的批次大小,对于推理,这并不总是有益的,请阅读 管道批处理
  • 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)还是原始输出数据(例如文本)形式进行。
  • 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") — 基于模型预测融合(或不融合)token的策略。

    • “none” : 将简单地不进行任何聚合,并简单地从模型返回原始结果
    • “simple” : 将尝试按照默认模式对实体进行分组。(A, B-TAG), (B, I-TAG), (C, I-TAG), (D, B-TAG2) (E, B-TAG2) 将最终变为 [{"word": ABC, "entity": "TAG"}, {"word": “D”, "entity": "TAG2"}, {"word": “E”, "entity": “TAG2”}] 请注意,两个连续的 B 标签将最终成为不同的实体。在基于单词的语言上,我们可能会不希望地拆分单词:想象一下 Microsoft 被标记为 [{"word": “Micro”, "entity": “ENTERPRISE”}, {"word": “soft”, "entity": “NAME”}]。查找 FIRST、MAX、AVERAGE 等方法来缓解这种情况,并消除单词的歧义(在支持该含义的语言上,基本上是空格分隔的 token)。这些缓解措施仅适用于真正的单词,“New york” 可能仍然被标记为两个不同的实体。
    • “first” : (仅适用于基于单词的模型)将使用 SIMPLE 策略,但单词不能以不同的标签结尾。当存在歧义时,单词将简单地使用单词的第一个 token 的标签。
    • “average” : (仅适用于基于单词的模型)将使用 SIMPLE 策略,但单词不能以不同的标签结尾。分数将首先在 token 之间平均,然后应用最大标签。
    • “max” : (仅适用于基于单词的模型)将使用 SIMPLE 策略,但单词不能以不同的标签结尾。单词实体将简单地是具有最高分数的 token。

命名实体识别管道,使用任何 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 教程 中了解有关使用 pipeline 的基础知识的更多信息

此 token 识别管道当前可以从 pipeline() 加载,使用以下任务标识符:"ner"(用于预测序列中 token 的类别:人、组织、地点或其他)。

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

__call__

< >

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

Parameters

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

返回:

一个列表或一个 dict 列表的列表

每个结果都以字典列表的形式出现(每个字典对应于相应输入中的一个 token,或者如果此管道使用 aggregation_strategy 实例化,则每个字典对应于一个实体),包含以下键

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

对作为输入给出的文本的每个 token 进行分类。

aggregate_words

< >

( entities: typing.List[dict] aggregation_strategy: AggregationStrategy )

覆盖来自给定单词的不同意的 token,以强制在单词边界上达成一致。

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

gather_pre_entities

< >

( sentence: str input_ids: ndarray scores: ndarray offset_mapping: typing.Optional[typing.List[typing.Tuple[int, int]]] special_tokens_mask: ndarray aggregation_strategy: AggregationStrategy )

将各种 numpy 数组融合到字典中,其中包含聚合所需的所有信息

group_entities

< >

( entities: typing.List[dict] )

Parameters

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

查找并将预测为相同实体的相邻 token 分组在一起。

group_sub_entities

< >

( entities: typing.List[dict] )

Parameters

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

将预测为相同实体的相邻 token 分组在一起。

TranslationPipeline

class transformers.TranslationPipeline

< >

( *args **kwargs )

Parameters

  • model (PreTrainedModelTFPreTrainedModel) — 将被管道用于进行预测的模型。这需要是一个继承自 PreTrainedModel (对于 PyTorch) 和 TFPreTrainedModel (对于 TensorFlow) 的模型。
  • tokenizer (PreTrainedTokenizer) — 将被管道用于为模型编码数据的分词器。此对象继承自 PreTrainedTokenizer
  • modelcard (strModelCard, 可选) — 归属于此管道模型的模型卡。
  • framework (str, 可选) — 要使用的框架,"pt" 代表 PyTorch,"tf" 代表 TensorFlow。必须安装指定的框架。

    如果未指定框架,则默认为当前安装的框架。如果未指定框架且两个框架都已安装,则默认为 model 的框架,如果未提供模型,则默认为 PyTorch。

  • task (str, defaults to "") — 管道的任务标识符。
  • num_workers (int, 可选, defaults to 8) — 当管道将使用 DataLoader 时(当传递数据集时,在 GPU 上用于 Pytorch 模型),要使用的工作进程数。
  • batch_size (int, 可选, defaults to 1) — 当管道将使用 DataLoader 时(当传递数据集时,在 GPU 上用于 Pytorch 模型),要使用的批次大小,对于推理,这并非总是有利,请阅读 使用管道进行批处理
  • args_parser (ArgumentHandler, 可选) — 负责解析提供的管道参数的对象的引用。
  • device (int, 可选, defaults to -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() 加载,使用以下任务标识符:"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 的列表或列表的列表

Parameters

  • args (strList[str]) — 要翻译的文本。
  • return_tensors (bool, 可选, 默认为 False) — 是否在输出中包含预测张量(作为令牌索引)。
  • return_text (bool, 可选, 默认为 True) — 是否在输出中包含解码后的文本。
  • clean_up_tokenization_spaces (bool, 可选, 默认为 False) — 是否清理文本输出中潜在的额外空格。
  • src_lang (str, 可选) — 输入的语言。 多语言模型可能需要。 对于单对翻译模型,将不起作用
  • tgt_lang (str, 可选) — 所需输出的语言。 多语言模型可能需要。 对于单对翻译模型,将不起作用
  • generate_kwargs — 要传递给模型的 generate 方法的其他关键字参数(请参阅与您的框架对应的 generate 方法 here)。

返回:

一个列表或一个 dict 列表的列表

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

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

翻译作为输入给出的文本。

ZeroShotClassificationPipeline

class transformers.ZeroShotClassificationPipeline

< >

( args_parser = <transformers.pipelines.zero_shot_classification.ZeroShotClassificationArgumentHandler object at 0x7f787a3bcc70> *args **kwargs )

Parameters

  • model (PreTrainedModelTFPreTrainedModel) — 管道将用于进行预测的模型。 这需要是一个继承自 PreTrainedModel 用于 PyTorch 和 TFPreTrainedModel 用于 TensorFlow 的模型。
  • tokenizer (PreTrainedTokenizer) — 管道将用于为模型编码数据的分词器。 此对象继承自 PreTrainedTokenizer
  • modelcard (strModelCard, 可选) — 此管道模型的模型卡。
  • framework (str, 可选) — 要使用的框架,"pt" 用于 PyTorch,"tf" 用于 TensorFlow。 必须安装指定的框架。

    如果未指定框架,则默认为当前安装的框架。 如果未指定框架并且两个框架都已安装,则默认为 model 的框架,如果未提供模型,则默认为 PyTorch。

  • task (str, 默认为 "") — 管道的任务标识符。
  • num_workers (int, 可选, 默认为 8) — 当管道将使用 DataLoader 时(在 GPU 上为 Pytorch 模型传递数据集时),要使用的工作人员数量。
  • batch_size (int, 可选, 默认为 1) — 当管道将使用 DataLoader 时(在 GPU 上为 Pytorch 模型传递数据集时),要使用的批处理大小,对于推理来说,这并不总是有益的,请阅读 管道批处理
  • 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 管道,但这些模型不需要硬编码的潜在类别数量,它们可以在运行时选择。 这通常意味着它速度较慢,但灵活。

可以传递序列和标签的任意组合,每个组合都将作为前提/假设对提出并传递给预训练模型。 然后,将蕴含的 logits 作为候选标签有效的 logits。 可以使用任何 NLI 模型,但蕴含标签的 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]}

pipeline 教程 中了解有关使用 pipeline 的基础知识的更多信息

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

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

__call__

< >

( sequences: typing.Union[str, typing.List[str]] *args **kwargs ) A dict 或 a list of dict

Parameters

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

返回:

一个 dict 或一个 dict 列表

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

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

对作为输入给出的序列进行分类。 有关更多信息,请参阅 ZeroShotClassificationPipeline 文档。

多模态

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

DocumentQuestionAnsweringPipeline

class transformers.DocumentQuestionAnsweringPipeline

< >

( *args **kwargs )

Parameters

  • model (PreTrainedModelTFPreTrainedModel) — pipeline 将用于进行预测的模型。这需要是一个继承自 PyTorch 的 PreTrainedModel 和 TensorFlow 的 TFPreTrainedModel 的模型。
  • tokenizer (PreTrainedTokenizer) — pipeline 将用于为模型编码数据的 tokenizer。此对象继承自 PreTrainedTokenizer
  • image_processor (BaseImageProcessor) — pipeline 将用于为模型编码数据的图像处理器。此对象继承自 BaseImageProcessor
  • modelcard (strModelCard, 可选) — 归属于此 pipeline 模型的模型卡。
  • framework (str, 可选) — 要使用的框架,PyTorch 使用 "pt",TensorFlow 使用 "tf"。必须安装指定的框架。

    如果未指定框架,则默认为当前安装的框架。如果未指定框架并且同时安装了这两个框架,则默认为 model 的框架,如果未提供模型,则默认为 PyTorch。

  • task (str, 默认为 "") — pipeline 的任务标识符。
  • num_workers (int, 可选, 默认为 8) — 当 pipeline 将使用 DataLoader 时(当传递数据集时,在 GPU 上用于 Pytorch 模型),要使用的工作进程数。
  • batch_size (int, 可选, 默认为 1) — 当 pipeline 将使用 DataLoader 时(当传递数据集时,在 GPU 上用于 Pytorch 模型),要使用的批次大小,对于推理来说,这并不总是有益的,请阅读 Batching with pipelines
  • args_parser (ArgumentHandler, 可选) — 负责解析提供的 pipeline 参数的对象的引用。
  • 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) — 标志,指示 pipeline 的输出应以序列化格式(即 pickle)还是原始输出数据(例如文本)进行。

文档问答 pipeline 使用任何 AutoModelForDocumentQuestionAnswering。输入/输出类似于(抽取式)问答 pipeline;但是,此 pipeline 接受图像(以及可选的 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 教程 中了解有关使用 pipeline 的基础知识的更多信息

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

此 pipeline 可以使用的模型是在文档问答任务上微调过的模型。请在 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 列表

Parameters

  • image (strPIL.Image) — 此 pipeline 处理三种类型的图像:

    • 包含指向图像的 http 链接的字符串
    • 包含图像本地路径的字符串
    • 直接在 PIL 中加载的图像

    此 pipeline 接受单个图像或一批图像。如果给定单个图像,则可以将其广播到多个问题。

  • question (str) — 要向文档提出的问题。
  • word_boxes (List[str, Tuple[float, float, float, float]], 可选) — 单词和边界框的列表(归一化 0->1000)。如果您提供此可选输入,则 pipeline 将使用这些单词和框,而不是在图像上运行 OCR 以获取模型所需的单词和框(例如 LayoutLM)。这允许您在 pipeline 的多次调用中重用 OCR 结果,而无需每次都重新运行它。
  • top_k (int, 可选, 默认为 1) — 要返回的答案数量(将按可能性顺序选择)。请注意,如果上下文中没有足够的选项,我们返回的答案将少于 top_k。
  • doc_stride (int, 可选, 默认为 128) — 如果文档中的单词太长而无法与模型的问题匹配,则会将其拆分为几个块,并带有一些重叠。此参数控制重叠的大小。
  • max_answer_len (int, 可选, 默认为 15) — 预测答案的最大长度(例如,仅考虑长度较短的答案)。
  • max_seq_len (int, 可选, 默认为 384) — 传递给模型的每个块中,总句子(上下文 + 问题)的最大长度(以 tokens 为单位)。如果需要,上下文将被拆分为几个块(使用 doc_stride 作为重叠)。
  • max_question_len (int, 可选, 默认为 64) — 问题在 tokenization 后的最大长度。如果需要,将被截断。
  • 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

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

FeatureExtractionPipeline

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

Parameters

  • model (PreTrainedModelTFPreTrainedModel) — pipeline 将用于进行预测的模型。这需要是一个继承自 PreTrainedModel (用于 PyTorch) 和 TFPreTrainedModel (用于 TensorFlow) 的模型。
  • tokenizer (PreTrainedTokenizer) — pipeline 将用于为模型编码数据的分词器。此对象继承自 PreTrainedTokenizer
  • modelcard (strModelCard, optional) — 归属于此 pipeline 模型的模型卡。
  • framework (str, optional) — 要使用的框架,"pt" 代表 PyTorch,"tf" 代表 TensorFlow。必须安装指定的框架。

    如果未指定框架,将默认为当前安装的框架。如果未指定框架且同时安装了两个框架,将默认为 model 的框架,如果未提供模型,则默认为 PyTorch。

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

特征提取 pipeline 不使用模型头。此 pipeline 从基础 Transformer 中提取隐藏状态,可以用作下游任务的特征。

示例:

>>> 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 教程 中了解有关使用 pipeline 的基础知识的更多信息

此特征提取 pipeline 当前可以从 pipeline() 使用任务标识符 "feature-extraction" 加载。

所有模型都可以用于此 pipeline。请参阅 huggingface.co/models 上的所有模型列表,包括社区贡献的模型。

__call__

< >

( *args **kwargs ) 浮点数嵌套列表 float

Parameters

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

返回:

浮点数嵌套列表 float

模型计算的特征。

提取输入的特征。

ImageFeatureExtractionPipeline

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

Parameters

  • model (PreTrainedModelTFPreTrainedModel) — pipeline 将用于进行预测的模型。这需要是一个继承自 PreTrainedModel (用于 PyTorch) 和 TFPreTrainedModel (用于 TensorFlow) 的模型。
  • image_processor (BaseImageProcessor) — pipeline 将用于为模型编码数据的图像处理器。此对象继承自 BaseImageProcessor
  • modelcard (strModelCard, optional) — 归属于此 pipeline 模型的模型卡。
  • framework (str, optional) — 要使用的框架,"pt" 代表 PyTorch,"tf" 代表 TensorFlow。必须安装指定的框架。

    如果未指定框架,将默认为当前安装的框架。如果未指定框架且同时安装了两个框架,将默认为 model 的框架,如果未提供模型,则默认为 PyTorch。

  • task (str, defaults to "") — 管道的任务标识符。
  • num_workers (int, 可选, 默认为 8) — 当管道将使用 DataLoader 时(当传递数据集时,在 GPU 上用于 Pytorch 模型),要使用的工作进程数。
  • batch_size (int, 可选, 默认为 1) — 当管道将使用 DataLoader 时(当传递数据集时,在 GPU 上用于 Pytorch 模型),要使用的批次大小;对于推理,这并不总是有益的,请阅读 使用管道进行批处理
  • 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, 可选) — 传递给图像处理器的其他关键字参数字典,例如 {“size”: {“height”: 100, “width”: 100}‌}
  • pool (bool, 可选, 默认为 False) — 是否返回池化输出。如果为 False,模型将返回原始隐藏状态。

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

示例:

>>> 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 教程 中了解有关使用 pipeline 的基础知识的更多信息

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

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

__call__

< >

( *args **kwargs ) 浮点数嵌套列表 float

Parameters

  • images (str, List[str], PIL.ImageList[PIL.Image]) — 管道处理三种类型的图像:

    • 包含指向图像的 http 链接的字符串
    • 包含图像本地路径的字符串
    • 直接在 PIL 中加载的图像

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

  • timeout (float, 可选, 默认为 None) — 等待从网络获取图像的最长时间(秒)。如果为 None,则不使用超时,并且调用可能会永远阻塞。

返回:

浮点数嵌套列表 float

模型计算的特征。

提取输入的特征。

ImageToTextPipeline

class transformers.ImageToTextPipeline

< >

( *args **kwargs )

Parameters

  • model (PreTrainedModelTFPreTrainedModel) — 管道将用于进行预测的模型。这需要是一个继承自 PreTrainedModel (对于 PyTorch) 和 TFPreTrainedModel (对于 TensorFlow) 的模型。
  • tokenizer (PreTrainedTokenizer) — 管道将用于为模型编码数据的分词器。此对象继承自 PreTrainedTokenizer
  • image_processor (BaseImageProcessor) — 管道将用于为模型编码数据的图像处理器。此对象继承自 BaseImageProcessor
  • modelcard (strModelCard, 可选) — 归属于此管道模型的模型卡。
  • framework (str, 可选) — 要使用的框架,"pt" 代表 PyTorch,"tf" 代表 TensorFlow。必须安装指定的框架。

    如果未指定框架,则默认为当前安装的框架。如果未指定框架并且同时安装了两个框架,则默认为 model 的框架,如果未提供模型,则默认为 PyTorch。

  • task (str, defaults to "") — 管道的任务标识符。
  • num_workers (int, 可选, 默认为 8) — 当管道将使用 DataLoader 时(当传递数据集时,在 GPU 上用于 Pytorch 模型),要使用的工作进程数。
  • batch_size (int, 可选, 默认为 1) — 当管道将使用 DataLoader 时(当传递数据集时,在 GPU 上用于 Pytorch 模型),要使用的批次大小;对于推理,这并不总是有益的,请阅读 使用管道进行批处理
  • 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 教程 中了解有关使用 pipeline 的基础知识的更多信息

此图像到文本管道目前可以使用以下任务标识符从 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 列表的列表

Parameters

  • inputs (str, List[str], PIL.ImageList[PIL.Image]) — 管道处理三种类型的图像:

    • 包含指向图像的 HTTP(s) 链接的字符串
    • 包含图像本地路径的字符串
    • 直接在 PIL 中加载的图像

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

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

返回:

一个列表或一个 dict 列表的列表

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

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

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

ImageTextToTextPipeline

class transformers.ImageTextToTextPipeline

< >

( *args **kwargs )

Parameters

  • model (PreTrainedModelTFPreTrainedModel) — 管道将用于进行预测的模型。这需要是一个继承自 PreTrainedModel (用于 PyTorch) 和 TFPreTrainedModel (用于 TensorFlow) 的模型。
  • processor (ProcessorMixin) — 管道将用于为模型编码数据的处理器。此对象继承自 ProcessorMixin。Processor 是一个复合对象,可能包含 tokenizerfeature_extractorimage_processor
  • modelcard (strModelCard, 可选) — 归属于此管道模型的模型卡。
  • framework (str, 可选) — 要使用的框架,"pt" 代表 PyTorch,"tf" 代表 TensorFlow。指定的框架必须已安装。

    如果未指定框架,则默认为当前安装的框架。如果未指定框架且两个框架都已安装,则默认为模型的框架;如果未提供模型,则默认为 PyTorch。

  • task (str, 默认为 "") — 管道的任务标识符。
  • num_workers (int, 可选, 默认为 8) — 当管道将使用 *DataLoader* 时(当传递数据集时,在 GPU 上用于 Pytorch 模型),要使用的工作进程数。
  • batch_size (int, 可选, 默认为 1) — 当管道将使用 *DataLoader* 时(当传递数据集时,在 GPU 上用于 Pytorch 模型),要使用的批次大小。对于推理来说,这并不总是有益的,请阅读 使用管道进行批处理
  • 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 教程 中了解有关使用 pipeline 的基础知识的更多信息

此图像-文本到文本管道目前可以使用以下任务标识符从 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 ) A list or a list of list of dict

Parameters

  • images (str, List[str], PIL.ImageList[PIL.Image]) — 管道处理三种类型的图像:指向图像的 HTTP(s) 链接的字符串,指向图像的本地路径的字符串,直接在 PIL 中加载的图像。管道接受单个图像或一批图像。
  • 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) — 在输出中返回预测的张量(作为 token 索引)。如果设置为 True,则不返回解码后的文本。
  • return_text (bool, 可选) — 在输出中返回解码后的文本。
  • return_full_text (bool, 可选, 默认为 True) — 如果设置为 False,则仅返回添加的文本;否则,返回完整文本。不能与 return_text 同时指定。
  • clean_up_tokenization_spaces (bool, 可选, 默认为 True) — 是否清理文本输出中可能存在的额外空格。
  • continue_final_message(** bool, 可选) — 这表示您希望模型继续输入聊天中的最后一条消息,而不是开始新消息,从而允许您“预填充”其响应。默认情况下,当输入聊天中的最后一条消息具有 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

class transformers.MaskGenerationPipeline

< >

( **kwargs )

Parameters

  • model (PreTrainedModelTFPreTrainedModel) — 管道将用于进行预测的模型。这需要是一个继承自 PreTrainedModel (用于 PyTorch) 和 TFPreTrainedModel (用于 TensorFlow) 的模型。
  • image_processor (BaseImageProcessor) — 管道将用于为模型编码数据的图像处理器。此对象继承自 BaseImageProcessor
  • modelcard (strModelCard, 可选) — 此 pipeline 模型相关的模型卡。
  • framework (str, 可选) — 要使用的框架,"pt" 代表 PyTorch,"tf" 代表 TensorFlow。指定的框架必须已安装。

    如果未指定框架,则默认为当前安装的框架。如果未指定框架且两个框架都已安装,则默认为 model 的框架;如果未提供模型,则默认为 PyTorch。

  • task (str, 默认为 "") — pipeline 的任务标识符。
  • num_workers (int, 可选, 默认为 8) — 当 pipeline 使用 DataLoader 时(当传递数据集时,在 GPU 上用于 Pytorch 模型),要使用的 worker 数量。
  • batch_size (int, 可选, 默认为 1) — 当 pipeline 使用 DataLoader 时(当传递数据集时,在 GPU 上用于 Pytorch 模型),要使用的批次大小。对于推理来说,这并不总是有益的,请阅读 使用 pipelines 进行批处理
  • args_parser (ArgumentHandler, 可选) — 负责解析提供的 pipeline 参数的对象的引用。
  • 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) — 标志,指示 pipeline 的输出应以序列化格式(即 pickle)还是原始输出数据(例如文本)进行。
  • points_per_batch (可选, int, 默认为 64) — 设置模型同时运行的点数。较高的数字可能会更快,但会使用更多的 GPU 内存。
  • output_bboxes_mask (bool, 可选, 默认为 False) — 是否输出边界框预测。
  • output_rle_masks (bool, 可选, 默认为 False) — 是否以 RLE 格式输出掩码

使用 SamForMaskGeneration 为图像自动生成掩码。此 pipeline 为给定图像预测二值掩码。它是一个 ChunkPipeline,因为你可以将点分成小批量,以避免 OOM 问题。使用 points_per_batch 参数来控制将同时处理的点数。默认值为 64

该 pipeline 分 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 (在每个小批量循环中运行): 接收原始输出掩码,根据图像大小调整其大小,并将其转换为二值掩码。
    • image_processor.filter_masks (在每个小批量循环中运行): 使用 pred_iou_threshstability_scores。还应用各种基于非极大值抑制的过滤器来移除不良掩码。
    • image_processor.postprocess_masks_for_amg 在掩码上应用 NSM,以仅保留相关的掩码。

示例:

>>> 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 教程 中了解有关使用 pipeline 的基础知识的更多信息

此分割 pipeline 目前可以从 pipeline() 加载,使用以下任务标识符: "mask-generation"

请参阅 huggingface.co/models 上的可用模型列表。

__call__

< >

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

Parameters

  • inputs (np.ndarraybytesstrdict) — 图像或图像列表。
  • mask_threshold (float, 可选, 默认为 0.0) — 将预测的掩码转换为二值时使用的阈值。
  • pred_iou_thresh (float, 可选, 默认为 0.88) — 应用于模型预测的掩码质量的 [0,1] 范围内的过滤阈值。
  • stability_score_thresh (float, 可选, 默认为 0.95) — [0,1] 范围内的过滤阈值,使用掩码在用于二值化模型掩码预测的截止值变化下的稳定性。
  • stability_score_offset (int, 可选, 默认为 1) — 计算稳定性得分时截止值偏移的量。
  • crops_nms_thresh (float, 可选, 默认为 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, 可选, 默认为 1) — 在第 n 层中采样的每边点数按 crop_n_points_downscale_factor**n 比例缩小。
  • timeout (float, 可选, 默认为 None) — 等待从网络获取图像的最长时间(秒)。如果为 None,则不设置超时,并且调用可能会永远阻塞。

返回:

Dict

包含以下键的字典

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

生成二值分割掩码

VisualQuestionAnsweringPipeline

class transformers.VisualQuestionAnsweringPipeline

< >

( *args **kwargs )

Parameters

  • model (PreTrainedModelTFPreTrainedModel) — pipeline 将用于进行预测的模型。这需要是一个继承自 PreTrainedModel (对于 PyTorch) 和 TFPreTrainedModel (对于 TensorFlow) 的模型。
  • tokenizer (PreTrainedTokenizer) — pipeline 将用于为模型编码数据的分词器。此对象继承自 PreTrainedTokenizer
  • image_processor (BaseImageProcessor) — 该图像处理器将被pipeline用于编码模型数据。此对象继承自 BaseImageProcessor
  • modelcard (strModelCard, optional) — 归属于此pipeline模型的模型卡。
  • framework (str, optional) — 要使用的框架,可以是 "pt" (PyTorch) 或 "tf" (TensorFlow)。指定的框架必须已安装。

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

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

Visual Question Answering pipeline using a AutoModelForVisualQuestionAnswering. 此pipeline目前仅在 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 教程 中了解有关使用 pipeline 的基础知识的更多信息

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

此pipeline可以使用的模型是在视觉问答任务上微调过的模型。 请在 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 ) 一个字典或包含结果的字典列表。字典包含以下键

Parameters

  • image (str, List[str], PIL.Image, List[PIL.Image]KeyDataset) — 该pipeline处理三种类型的图像:

    • 包含指向图像的 http 链接的字符串
    • 包含图像本地路径的字符串
    • 直接在 PIL 中加载的图像

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

返回:

一个字典或包含结果的字典列表。字典包含以下键

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

回答关于图像的开放式问题。 pipeline接受以下详细介绍的几种类型的输入

  • 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

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

Parameters

  • model (PreTrainedModelTFPreTrainedModel) — pipeline将用于进行预测的模型。 这需要是一个继承自 PyTorch 的 PreTrainedModel 和 TensorFlow 的 TFPreTrainedModel 的模型。
  • tokenizer (PreTrainedTokenizer) — 分词器将被pipeline用于编码模型数据。此对象继承自 PreTrainedTokenizer
  • feature_extractor (SequenceFeatureExtractor) — 特征提取器将被pipeline用于编码模型数据。此对象继承自 SequenceFeatureExtractor
  • image_processor (BaseImageProcessor) — 图像处理器将被pipeline用于编码模型数据。此对象继承自 BaseImageProcessor
  • processor (ProcessorMixin) — 处理器将被pipeline用于编码模型数据。此对象继承自 ProcessorMixin。 处理器是一个复合对象,可能包含 tokenizerfeature_extractorimage_processor
  • modelcard (strModelCard, optional) — 归属于此pipeline模型的模型卡。
  • framework (str, optional) — 要使用的框架,可以是 "pt" (PyTorch) 或 "tf" (TensorFlow)。指定的框架必须已安装。

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

  • task (str, 默认为 "") — pipeline 的任务标识符。
  • num_workers (int, 可选, 默认为 8) — 当 pipeline 将使用 DataLoader (当传递数据集时,在 GPU 上用于 Pytorch 模型),要使用的工作进程数。
  • batch_size (int, 可选, 默认为 1) — 当 pipeline 将使用 DataLoader (当传递数据集时,在 GPU 上用于 Pytorch 模型),要使用的批次大小。对于推理来说,这并不总是有益的,请阅读 使用 pipelines 进行批处理
  • args_parser (ArgumentHandler, 可选) — 负责解析提供的 pipeline 参数的对象的引用。
  • 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) — 指示 pipeline 的输出是否应以序列化格式(即 pickle)或原始输出数据(例如文本)形式进行的标志。

Pipeline 类是所有 pipelines 继承的类。有关不同 pipelines 共享的方法,请参阅此类。

实现 pipeline 操作的基类。Pipeline 工作流程定义为以下操作的序列:

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

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

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

check_model_type

< >

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

Parameters

  • supported_models (List[str]dict) — pipeline 支持的模型列表,或带有模型类值的字典。

检查模型类是否受 pipeline 支持。

device_placement

< >

( )

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

示例:

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

Parameters

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

返回:

Dict[str, torch.Tensor]

inputs 相同,但位于正确的设备上。

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

postprocess

< >

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

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

predict

< >

( X )

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

preprocess

< >

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

Preprocess 将获取特定 pipeline 的 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 )

Parameters

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

将 pipeline 文件上传到 🤗 Model 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 )

Parameters

  • save_directory (str or os.PathLike) — 要保存到的目录的路径。如果目录不存在,将创建该目录。
  • safe_serialization (str) — 是否使用 safetensors 或 PyTorch 或 Tensorflow 的传统方式保存模型。
  • kwargs (Dict[str, Any], optional) — 传递给 push_to_hub() 方法的其他关键字参数。

保存 pipeline 的模型和分词器。

transform

< >

( X )

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

< > 在 GitHub 上更新