# Pipelines

Pipeline 是一种使用模型进行推理的便捷方式。这些 pipeline 是对象，它们封装了库中大部分复杂的代码，并提供了一个简洁的 API，专门用于多项任务，包括命名实体识别、掩码语言建模、情感分析、特征提取和问答。有关使用示例，请参阅[任务列表](https://huggingface.co/tasks)。

需要注意两类 pipeline 抽象：

- [pipeline()](/docs/transformers/v5.23.0/zh/main_classes/pipelines#transformers.pipeline) 是最强大的对象，封装了所有其他流水线。
- 针对[音频](#audio)、[计算机视觉](#computer-vision)、[自然语言处理](#natural-language-processing)以及[多模态](#multimodal)任务，提供了专用的流水线。

## Pipeline 抽象[[transformers.pipeline]]

*pipeline* 抽象是对所有其他可用 pipeline 的封装。它的实例化方式与其他 pipeline 相同，但可以提供额外的便利性。

对单个项的简单调用：

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

如果你想使用 [hub](https://huggingface.co) 上的特定模型，并且该模型在 hub 上已经定义了任务，则可以忽略任务参数：

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

要对多个项目调用 pipeline，可以传入一个 *list*。

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

要遍历完整数据集，建议直接使用 `dataset`。这意味着你无需一次性分配整个数据集，也无需自行进行批处理。在 GPU 上，其速度应与自定义循环相当。如果并非如此，请随时创建 issue。

```python
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("s3prl/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": ....}
    # ....
```

为了方便使用，也可以使用生成器：

```python
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[[transformers.pipeline]]

```python
transformers.pipeline(task: str | None = None, model: str | PreTrainedModel | None = None, config: str | PreTrainedConfig | None = None, tokenizer: str | PreTrainedTokenizer | PreTrainedTokenizerFast | None = None, feature_extractor: str | FeatureExtractionMixin | None = None, image_processor: str | BaseImageProcessor | None = None, video_processor: str | BaseVideoProcessor | None = None, processor: str | ProcessorMixin | None = None, revision: str | None = None, use_fast: bool = True, token: str | bool | None = None, device: int | str | torch.device | None = None, device_map: str | dict[str, int | str] | None = None, dtype: str | torch.dtype | None = 'auto', trust_remote_code: bool | None = None, model_kwargs: dict[str, Any] | None = None, pipeline_class: Any | None = None, **kwargs: Any)
```

[来源](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/pipelines/__init__.py#L759)

**参数：**

task (`str`) : 定义将返回哪个管道的任务。当前接受的任务包括： - `"audio-classification"`：将返回 [AudioClassificationPipeline](/docs/transformers/v5.23.0/zh/main_classes/pipelines#transformers.AudioClassificationPipeline)。 - `"automatic-speech-recognition"`：将返回 [AutomaticSpeechRecognitionPipeline](/docs/transformers/v5.23.0/zh/main_classes/pipelines#transformers.AutomaticSpeechRecognitionPipeline)。 - `"decision"`：将返回 [DecisionPipeline](/docs/transformers/v5.23.0/zh/main_classes/pipelines#transformers.DecisionPipeline)。 - `"depth-estimation"`：将返回 [DepthEstimationPipeline](/docs/transformers/v5.23.0/zh/main_classes/pipelines#transformers.DepthEstimationPipeline)。 - `"document-question-answering"`：将返回 [DocumentQuestionAnsweringPipeline](/docs/transformers/v5.23.0/zh/main_classes/pipelines#transformers.DocumentQuestionAnsweringPipeline)。 - `"feature-extraction"`：将返回 [FeatureExtractionPipeline](/docs/transformers/v5.23.0/zh/main_classes/pipelines#transformers.FeatureExtractionPipeline)。 - `"fill-mask"`：将返回 [FillMaskPipeline](/docs/transformers/v5.23.0/zh/main_classes/pipelines#transformers.FillMaskPipeline)。 - `"image-classification"`：将返回 [ImageClassificationPipeline](/docs/transformers/v5.23.0/zh/main_classes/pipelines#transformers.ImageClassificationPipeline)。 - `"image-feature-extraction"`：将返回 [ImageFeatureExtractionPipeline](/docs/transformers/v5.23.0/zh/main_classes/pipelines#transformers.ImageFeatureExtractionPipeline)。 - `"image-segmentation"`：将返回 [ImageSegmentationPipeline](/docs/transformers/v5.23.0/zh/main_classes/pipelines#transformers.ImageSegmentationPipeline)。 - `"image-text-to-text"`：将返回 [ImageTextToTextPipeline](/docs/transformers/v5.23.0/zh/main_classes/pipelines#transformers.ImageTextToTextPipeline)。 - `"keypoint-matching"`：将返回 [KeypointMatchingPipeline](/docs/transformers/v5.23.0/zh/main_classes/pipelines#transformers.KeypointMatchingPipeline)。 - `"mask-generation"`：将返回 [MaskGenerationPipeline](/docs/transformers/v5.23.0/zh/main_classes/pipelines#transformers.MaskGenerationPipeline)。 - `"object-detection"`：将返回 [ObjectDetectionPipeline](/docs/transformers/v5.23.0/zh/main_classes/pipelines#transformers.ObjectDetectionPipeline)。 - `"table-question-answering"`：将返回 [TableQuestionAnsweringPipeline](/docs/transformers/v5.23.0/zh/main_classes/pipelines#transformers.TableQuestionAnsweringPipeline)。 - `"text-classification"`（可用别名 `"sentiment-analysis"`）：将返回 [TextClassificationPipeline](/docs/transformers/v5.23.0/zh/main_classes/pipelines#transformers.TextClassificationPipeline)。 - `"text-generation"`：将返回 [TextGenerationPipeline](/docs/transformers/v5.23.0/zh/main_classes/pipelines#transformers.TextGenerationPipeline)。 - `"text-to-audio"`（可用别名 `"text-to-speech"`）：将返回 [TextToAudioPipeline](/docs/transformers/v5.23.0/zh/main_classes/pipelines#transformers.TextToAudioPipeline)。 - `"token-classification"`（可用别名 `"ner"`）：将返回 [TokenClassificationPipeline](/docs/transformers/v5.23.0/zh/main_classes/pipelines#transformers.TokenClassificationPipeline)。 - `"video-classification"`：将返回 [VideoClassificationPipeline](/docs/transformers/v5.23.0/zh/main_classes/pipelines#transformers.VideoClassificationPipeline)。 - `"zero-shot-classification"`：将返回 [ZeroShotClassificationPipeline](/docs/transformers/v5.23.0/zh/main_classes/pipelines#transformers.ZeroShotClassificationPipeline)。 - `"zero-shot-image-classification"`：将返回 [ZeroShotImageClassificationPipeline](/docs/transformers/v5.23.0/zh/main_classes/pipelines#transformers.ZeroShotImageClassificationPipeline)。 - `"zero-shot-audio-classification"`：将返回 [ZeroShotAudioClassificationPipeline](/docs/transformers/v5.23.0/zh/main_classes/pipelines#transformers.ZeroShotAudioClassificationPipeline)。 - `"zero-shot-object-detection"`：将返回 [ZeroShotObjectDetectionPipeline](/docs/transformers/v5.23.0/zh/main_classes/pipelines#transformers.ZeroShotObjectDetectionPipeline)。

model (`str` 或 [PreTrainedModel](/docs/transformers/v5.23.0/zh/main_classes/model#transformers.PreTrainedModel)，*可选*)：流水线用于进行预测的模型。它可以是模型标识符，也可以是继承自 [PreTrainedModel](/docs/transformers/v5.23.0/zh/main_classes/model#transformers.PreTrainedModel) 的预训练模型实例。如果未提供，将加载 `task` 的默认模型。

config (`str` 或 [PreTrainedConfig](/docs/transformers/v5.23.0/zh/main_classes/configuration#transformers.PreTrainedConfig)，*可选*)：流水线用于实例化模型的配置。它可以是模型标识符，也可以是继承自 [PreTrainedConfig](/docs/transformers/v5.23.0/zh/main_classes/configuration#transformers.PreTrainedConfig) 的实际预训练模型配置。如果未提供，将使用所请求模型的默认配置文件。这意味着，如果提供了 `model`，将使用其默认配置。但是，如果未提供 `model`，则改用此 `task` 的默认模型配置。

tokenizer (`str` 或 [PreTrainedTokenizer](/docs/transformers/v5.23.0/zh/main_classes/tokenizer#transformers.PythonBackend)，*可选*)：流水线将使用该分词器为模型编码数据。它可以是模型标识符，也可以是继承自 [PreTrainedTokenizer](/docs/transformers/v5.23.0/zh/main_classes/tokenizer#transformers.PythonBackend) 的实际预训练分词器。如果未提供，则加载给定 `model` 的默认分词器（如果它是字符串）。如果未指定 `model` 或它不是字符串，则加载 `config` 的默认分词器（如果它是字符串）。但是，如果 `config` 也未提供或不是字符串，则加载给定 `task` 的默认分词器。

feature_extractor (`str` 或 [FeatureExtractionMixin](/docs/transformers/v5.23.0/zh/main_classes/feature_extractor#transformers.FeatureExtractionMixin)，*可选*)：流水线将使用该特征提取器为模型编码数据。它可以是模型标识符，也可以是继承自 [FeatureExtractionMixin](/docs/transformers/v5.23.0/zh/main_classes/feature_extractor#transformers.FeatureExtractionMixin) 的实际预训练特征提取器。特征提取器用于非 NLP 模型，例如语音或视觉模型，以及多模态模型。多模态模型还需要传入一个分词器。如果未提供，则加载给定 `model` 的默认特征提取器（如果它是字符串）。如果未指定 `model` 或它不是字符串，则加载 `config` 的默认特征提取器（如果它是字符串）。但是，如果 `config` 也未提供或不是字符串，则加载给定 `task` 的默认特征提取器。

image_processor (`str` 或 [BaseImageProcessor](/docs/transformers/v5.23.0/zh/main_classes/image_processor#transformers.BaseImageProcessor)，*可选*)：流水线将使用该图像处理器对模型所需的图像进行预处理。它可以是模型标识符，也可以是继承自 [BaseImageProcessor](/docs/transformers/v5.23.0/zh/main_classes/image_processor#transformers.BaseImageProcessor) 的实际图像处理器。图像处理器用于需要图像输入的视觉模型和多模态模型。多模态模型还需要传入一个分词器。如果未提供，则加载给定 `model` 的默认图像处理器（如果它是字符串）。如果未指定 `model` 或它不是字符串，则加载 `config` 的默认图像处理器（如果它是字符串）。

processor (`str` 或 [ProcessorMixin](/docs/transformers/v5.23.0/zh/main_classes/processors#transformers.ProcessorMixin)，*可选*)：流水线将使用该处理器为模型预处理数据。它可以是模型标识符，也可以是继承自 [ProcessorMixin](/docs/transformers/v5.23.0/zh/main_classes/processors#transformers.ProcessorMixin) 的实际处理器。处理器用于需要多模态输入的多模态模型，例如同时需要文本和图像输入的模型。如果未提供，则加载给定 `model` 的默认处理器（如果它是字符串）。如果未指定 `model` 或它不是字符串，则加载 `config` 的默认处理器（如果它是字符串）。

revision (`str`，*可选*，默认为 `"main"`)：在传入任务名称或字符串模型标识符时：指定要使用的具体模型版本。由于我们在 huggingface.co 上使用基于 git 的系统来存储模型及其他工件，因此 `revision` 可以是 git 允许的任何标识符，例如分支名称、标签名称或提交 ID。

use_fast (`bool`，*可选*，默认为 `True`)：如果可能，是否使用快速分词器（即 [PreTrainedTokenizerFast](/docs/transformers/v5.23.0/zh/main_classes/tokenizer#transformers.TokenizersBackend)）。

token (`str` 或 *bool*，*可选*) : 用于远程文件的 HTTP bearer 授权令牌。如果为 `True`，将使用运行 `hf auth login` 时生成的令牌。

device (`int` 或 `str` 或 `torch.device`，*可选*)：定义该流水线将分配到的设备（*例如*，`"cpu"`、`"cuda:1"`、`"mps"`，或类似 `1` 的 GPU 序号）。如果未设置，流水线会自动放置在第一个可用的加速器（CUDA、MPS、XPU 等）上，仅在没有可用加速器时才回退到 CPU；模型会被自动移动过去。传入 `device="cpu"`（或 `-1`）可强制使用 CPU。不能与 `device_map` 一起使用。

device_map (`str` 或 `dict[str, Union[int, str, torch.device]`，*可选*)：直接作为 `model_kwargs` 传入（只是一个更简单的快捷方式）。当存在 `accelerate` 库时，设置 `device_map="auto"` 可自动计算最优的 `device_map`（更多信息请参见[此处](https://huggingface.co/docs/accelerate/main/en/package_reference/big_modeling#accelerate.cpu_offload)）。请勿同时使用 `device_map` 和 `device`，因为它们会相互冲突

dtype (`str` 或 `torch.dtype`，*可选*，默认为 `"auto"`)：模型加载时使用的精度，会传递给 `from_pretrained`。默认为 `"auto"`，即以模型保存时的 dtype 加载模型。传入显式的 `torch.float16`、`torch.bfloat16`、`torch.float32` 等可覆盖该设置。

trust_remote_code (`bool`，*可选*，默认为 `False`)：是否允许使用在 Hub 上以自定义建模、配置、分词甚至流水线文件形式定义的代码。此选项仅应为您信任且已阅读过其代码的仓库设置为 `True`，因为它会在您的本地机器上执行 Hub 上存在的代码。

model_kwargs (`dict[str, Any]`，*可选*)：传递给模型 `from_pretrained(..., **model_kwargs)` 函数的额外关键字参数字典。

kwargs (`dict[str, Any]`，*可选*)：传递给特定 pipeline 初始化的额外关键字参数（有关可能的取值，请参阅相应 pipeline 类的文档）。

**返回：** [Pipeline](/docs/transformers/v5.23.0/zh/main_classes/pipelines#transformers.Pipeline)

适用于该任务的流水线。

用于构建 [Pipeline](/docs/transformers/v5.23.0/zh/main_classes/pipelines#transformers.Pipeline) 的实用工厂方法。

一个 pipeline 由以下部分组成：

- 一个或多个用于预处理模型输入的组件，例如 [tokenizer](tokenizer)，
[image_processor](image_processor)、[feature_extractor](feature_extractor) 或 [processor](processors)。
- 一个根据输入生成预测的[模型](model)。
- 用于优化模型输出的可选后处理步骤，这些步骤也可以由处理器来处理。

虽然存在诸如 `tokenizer`、`feature_extractor`、`image_processor` 和 `processor` 等可选参数，但不应同时指定它们。如果未提供这些组件，`pipeline` 将尝试自动加载所需的组件。如果您希望显式提供这些组件，请参阅具体的 pipeline 以获取有关所需组件的更多详细信息。

示例：

```python
>>> from transformers import pipeline, AutoModelForTokenClassification, AutoTokenizer

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

>>> # 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 使用了其流式处理能力（即传入列表、`Dataset` 或 `generator` 时），该功能即可生效。

```python
from transformers import pipeline
from transformers.pipelines.pt_utils import KeyDataset
import datasets

dataset = datasets.load_dataset("stanfordnlp/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 倍的减速。

以速度提升为主的示例：

```python
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
```

```text
# 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)
```

主要导致性能下降的示例：

```python
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 个 token 的长度，因此整个批次的形状将是 [64, 400] 而不是 [64, 4]，从而导致严重的性能下降。更糟糕的是，在更大的批次上，程序会直接崩溃。

```text
------------------------------
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 非常规整，那么批处理（batching）往往能带来显著的性能提升。请进行测量，并逐步增大批大小，直到出现 OOM（内存溢出）为止。
  - GPU 越大，批处理就越有可能带来更显著的效果
- 一旦启用批处理，请确保能够妥善地处理 OOM（内存溢出）问题。

## Pipeline 分块批处理

`zero-shot-classification` 和 `question-answering` 在某种程度上较为特殊，因为单个输入可能会触发模型进行多次前向传播。在通常情况下，这会导致 `batch_size` 参数出现问题。

为了规避此问题，这两个流水线都较为特殊，它们使用的是 `ChunkPipeline` 而非常规的 `Pipeline`。简而言之：

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

现在变为：

```python
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！这意味着您无需关心输入实际会触发多少次前向传播，可以独立于输入来优化 `batch_size`。上一节中的注意事项仍然适用。

## Pipeline FP16 推理

模型可以以 FP16 精度运行，这在 GPU 上能显著提升速度并节省内存。大多数模型在此精度下不会出现明显的性能损失。模型越大，出现性能损失的可能性就越低。

要启用 FP16 推理，只需向 pipeline 构造函数传入 `dtype=torch.float16` 或 `dtype='float16'`。请注意，这仅适用于使用 PyTorch 后端的模型。您的输入将在内部转换为 FP16。

## Pipeline 自定义代码

如果您想要覆盖特定的 pipeline。

请随时针对您当前的任务创建一个 issue，pipeline 的目标是易于使用并支持大多数场景，因此 `transformers` 或许能够支持您的用例。

如果您想简单尝试，可以：

- 子类化您选择的 pipeline

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

这样你就可以编写所有需要的自定义代码了。

## 实现流水线

[实现新的流水线](../add_new_pipeline)

## 音频

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

### AudioClassificationPipeline[[transformers.AudioClassificationPipeline]]

#### transformers.AudioClassificationPipeline[[transformers.AudioClassificationPipeline]]

```python
transformers.AudioClassificationPipeline(*args, **kwargs)
```

[来源](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/pipelines/audio_classification.py#L68)

**参数：**

model ([PreTrainedModel](/docs/transformers/v5.23.0/zh/main_classes/model#transformers.PreTrainedModel))：流水线用于进行预测的模型。该模型必须继承自 [PreTrainedModel](/docs/transformers/v5.23.0/zh/main_classes/model#transformers.PreTrainedModel)。

feature_extractor ([SequenceFeatureExtractor](/docs/transformers/v5.23.0/zh/main_classes/feature_extractor#transformers.SequenceFeatureExtractor))：流水线将使用该特征提取器为模型编码数据。此对象继承自 [SequenceFeatureExtractor](/docs/transformers/v5.23.0/zh/main_classes/feature_extractor#transformers.SequenceFeatureExtractor)。

task (`str`，默认为 `""`)：用于标识 pipeline 的任务。

num_workers (`int`，*可选*，默认值为 8)：当流水线使用 *DataLoader*（例如传入数据集，或在 GPU 上运行 PyTorch 模型时）时，所使用的 worker 数量。

batch_size (`int`，*可选*，默认为 1)：当流水线使用 *DataLoader*（例如传入数据集，或在 GPU 上运行 PyTorch 模型时）时，所使用的批次大小。对于推理而言，增大批次大小并不总是有益的，请参阅 [使用流水线进行批处理](https://huggingface.co/transformers/main_classes/pipelines.html#pipeline-batching)。

args_parser ([ArgumentHandler](/docs/transformers/v5.23.0/zh/internal/pipelines_utils#transformers.pipelines.ArgumentHandler)，*可选*)：负责解析所提供 pipeline 参数的对象引用。

device (`int` 或 `str` 或 `torch.device`，*可选*)：流水线所分配的设备。若未设置，流水线将放置在第一个可用的加速器（CUDA、MPS、XPU 等）上，仅当没有可用加速器时才回退到 CPU；模型会自动移动至该设备。传入 `device="cpu"`（或 `-1`）可强制使用 CPU，传入正序数或 `"cuda:1"` 可选择特定加速器，或传入原生的 `torch.device`/`str`。此参数不能与已通过 `accelerate` 加载的模型（即具有 `hf_device_map` 的模型）一起使用。

dtype (`str` 或 `torch.dtype`，*可选*，默认为 `"auto"`)：模型加载时使用的精度，会传递给 `from_pretrained`。默认为 `"auto"`，即以模型保存时的 dtype 加载模型（从检查点的 `config.dtype` 读取，否则从权重推断）。传入显式的 `torch.float16`、`torch.bfloat16`、`torch.float32` 等可覆盖该默认值。

binary_output (`bool`，*可选*，默认为 `False`)：一个标志，指示管道输出应采用序列化格式（即 pickle）还是原始输出数据（例如文本）。

使用任意 `AutoModelForAudioClassification` 的音频分类流水线。该流水线可预测原始波形或音频文件的类别。对于音频文件，需安装 ffmpeg 以支持多种音频格式。

示例：

```python
>>> 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_tutorial) 中了解使用 pipeline 的基础知识。

目前，该流水线可以通过 [pipeline()](/docs/transformers/v5.23.0/zh/main_classes/pipelines#transformers.pipeline) 使用以下任务标识符进行加载：`"audio-classification"`。

在 [huggingface.co/models](https://huggingface.co/models?filter=audio-classification) 上查看可用模型列表。

#### __调用__[[transformers.AudioClassificationPipeline.__call__]]

```python
__call__(inputs: numpy.ndarray | bytes | str | dict, **kwargs: Any)
```

[来源](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/pipelines/audio_classification.py#L110)

**参数：**

inputs (`np.ndarray` 或 `bytes` 或 `str` 或 `dict`) : 输入可以是以下之一： - `str`，即音频文件的文件名，文件将以正确的采样率读取，并使用 *ffmpeg* 获取波形。这要求系统中已安装 *ffmpeg*。 - `bytes`，应为音频文件的内容，并以相同方式由 *ffmpeg* 进行解析。 - (`np.ndarray`，形状为 (n, )，类型为 `np.float32` 或 `np.float64`) 以正确采样率表示的原始音频（不会进行进一步检查） - `dict` 形式可用于传递以任意 `sampling_rate` 采样的原始音频，并让此流水线执行重采样。该字典必须采用 `{"sampling_rate": int, "raw": np.array}` 或 `{"sampling_rate": int, "array": np.array}` 格式，其中键 `"raw"` 或 `"array"` 用于表示原始音频波形。

top_k (`int`，*可选*，默认为 None)：流水线将返回的顶级标签数量。如果提供的数值为 `None` 或大于模型配置中可用的标签数量，则默认使用标签总数。

function_to_apply (`str`, *可选*) : 应用于模型输出的函数。回归任务默认为 "none"，多标签分类任务默认为 "sigmoid"，其他任务默认为 "softmax"。有效选项：["softmax", "sigmoid", "none"]。在初始化或调用时显式提供的值会覆盖这些默认值。传入字符串 "none" 可禁用后处理。

**返回：** 一个 `dict` 列表，包含以下键

- **label** (`str`) -- 预测的标签。
- **score** (`float`) -- 对应的概率。

对作为输入给出的序列进行分类。有关更多信息，请参阅 [AutomaticSpeechRecognitionPipeline](/docs/transformers/v5.23.0/zh/main_classes/pipelines#transformers.AutomaticSpeechRecognitionPipeline) 文档。

### AutomaticSpeechRecognitionPipeline[[transformers.AutomaticSpeechRecognitionPipeline]]

#### transformers.AutomaticSpeechRecognitionPipeline[[transformers.AutomaticSpeechRecognitionPipeline]]

```python
transformers.AutomaticSpeechRecognitionPipeline(model: PreTrainedModel, feature_extractor: typing.Union[ForwardRef('SequenceFeatureExtractor'), str, NoneType] = None, tokenizer: transformers.tokenization_python.PythonBackend | None = None, decoder: typing.Union[ForwardRef('BeamSearchDecoderCTC'), str, NoneType] = None, device: typing.Union[int, ForwardRef('torch.device'), NoneType] = None, **kwargs)
```

[来源](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/pipelines/automatic_speech_recognition.py#L147)

**参数：**

model ([PreTrainedModel](/docs/transformers/v5.23.0/zh/main_classes/model#transformers.PreTrainedModel))：流水线用于进行预测的模型。该模型必须继承自 [PreTrainedModel](/docs/transformers/v5.23.0/zh/main_classes/model#transformers.PreTrainedModel)。

feature_extractor ([SequenceFeatureExtractor](/docs/transformers/v5.23.0/zh/main_classes/feature_extractor#transformers.SequenceFeatureExtractor)，*可选*)：流水线将使用该特征提取器对波形进行编码，以供模型使用。

tokenizer ([PreTrainedTokenizer](/docs/transformers/v5.23.0/zh/main_classes/tokenizer#transformers.PythonBackend)，*可选*)：流水线用于为模型编码数据的分词器。该对象继承自 [PreTrainedTokenizer](/docs/transformers/v5.23.0/zh/main_classes/tokenizer#transformers.PythonBackend)。

decoder (`pyctcdecode.BeamSearchDecoderCTC`，*可选*)：可以传入 [PyCTCDecode 的 BeamSearchDecoderCTC](https://github.com/kensho-technologies/pyctcdecode/blob/2fd33dc37c4111417e08d89ccd23d28e9b308d19/pyctcdecode/decoder.py#L180) 以进行语言模型增强的解码。有关更多信息，请参阅 [Wav2Vec2ProcessorWithLM](/docs/transformers/v5.23.0/zh/model_doc/wav2vec2#transformers.Wav2Vec2ProcessorWithLM)。已弃用，将在 Transformers v6 中移除。

device (Union[`int`, `torch.device`], *可选*) : CPU/GPU 支持的设备序号。将其设置为 `None` 将使用 CPU，设置为正整数则会在对应的 CUDA 设备 ID 上运行模型。

旨在从音频中提取语音文本的 Pipeline。

输入可以是原始波形或音频文件。如果使用音频文件，则需要安装 ffmpeg 以支持多种音频格式

除非您使用的模型在其配置文件（`generation_config.json`）中明确设置了这些生成参数，否则将使用以下默认值：
- max_new_tokens: 256
- num_beams: 5

示例：

```python
>>> 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_tutorial) 中了解使用 pipeline 的基础知识。

#### __调用__[[transformers.AutomaticSpeechRecognitionPipeline.__call__]]

```python
__call__(inputs: numpy.ndarray | bytes | str | dict, **kwargs: Any)
```

[来源](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/pipelines/automatic_speech_recognition.py#L238)

**参数：**

inputs (`np.ndarray` 或 `bytes` 或 `str` 或 `dict`) : 输入可以是以下之一： - `str`，即本地音频文件的文件名，或用于下载音频文件的公共 URL 地址。该文件将以正确的采样率读取，并使用 *ffmpeg* 获取波形。这要求系统中已安装 *ffmpeg*。 - `bytes`，应为音频文件的内容，并以相同方式由 *ffmpeg* 进行解析。 - （形状为 (n, ) 的 `np.ndarray`，类型为 `np.float32` 或 `np.float64`）以正确采样率提供的原始音频（不会进行进一步检查） - `dict` 形式可用于传递以任意 `sampling_rate` 采样的原始音频，并让此流水线执行重采样。该字典必须采用 `{"sampling_rate": int, "raw": np.array}` 格式，可选地包含 `"stride": (left: int, right: int)`，用于要求流水线在解码时忽略前 `left` 个采样点和最后 `right` 个采样点（但在推理时仍会使用它们，以为模型提供更多上下文）。仅对 CTC 模型使用 `stride`。

return_timestamps (*可选*，`str` 或 `bool`) : 仅适用于纯 CTC 模型（Wav2Vec2、HuBERT 等）和 Whisper 模型。不适用于其他序列到序列模型。 对于 CTC 模型，时间戳可以采用以下两种格式之一： - `"char"`：流水线将为文本中的每个字符返回对应的时间戳。例如，如果得到 `[{"text": "h", "timestamp": (0.5, 0.6)}, {"text": "i", "timestamp": (0.7, 0.9)}]`，则表示模型预测字母 "h" 在 `0.5` 秒之后、`0.6` 秒之前被说出。 - `"word"`：流水线将为文本中的每个单词返回对应的时间戳。例如，如果得到 `[{"text": "hi ", "timestamp": (0.5, 0.9)}, {"text": "there", "timestamp": (1.0, 1.5)}]`，则表示模型预测单词 "hi" 在 `0.5` 秒之后、`0.9` 秒之前被说出。 对于 Whisper 模型，时间戳可以采用以下两种格式之一： - `"word"`：与上述 CTC 的单词级时间戳相同。单词级时间戳是通过 *动态时间规整 (DTW)* 算法预测的，该算法通过检查交叉注意力权重来近似单词级时间戳。 - `True`：流水线将为文本中单词的 *片段* 返回对应的时间戳。例如，如果得到 `[{"text": " Hi there!", "timestamp": (0.5, 1.5)}]`，则表示模型预测片段 "Hi there!" 在 `0.5` 秒之后、`1.5` 秒之前被说出。请注意，文本片段指的是一个或多个单词组成的序列，而不是像单词级时间戳那样指单个单词。

generate_kwargs (`dict`, *可选*) : 用于生成调用的 `generate_config` 的临时参数化字典。如需了解 generate 的完整概览，请参阅[以下指南](https://huggingface.co/docs/transformers/en/main_classes/text_generation)。

**返回：** `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](/docs/transformers/v5.23.0/zh/main_classes/pipelines#transformers.AutomaticSpeechRecognitionPipeline) 文档。

### TextToAudioPipeline[[transformers.TextToAudioPipeline]]

#### transformers.TextToAudioPipeline[[transformers.TextToAudioPipeline]]

```python
transformers.TextToAudioPipeline(*args, vocoder = None, sampling_rate = None, noise_scheduler = None, **kwargs)
```

[来源](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/pipelines/text_to_audio.py#L46)

使用任意 `AutoModelForTextToWaveform` 或 `AutoModelForTextToSpectrogram` 的文本到音频生成流水线。该流水线根据输入文本以及可选的其他条件输入生成音频文件。

除非您使用的模型在 `generation_config.json` 中显式设置了生成参数，否则将使用 `generation.configuration_utils.py._get_default_generation_params()` 中的默认值。
- max_new_tokens: 256

示例：

```python
>>> 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_tutorial) 中了解使用 pipeline 的基础知识。

您可以使用 `TextToAudioPipeline.__call__.forward_params` 或 `TextToAudioPipeline.__call__.generate_kwargs` 来指定传递给模型的参数。

示例：

```python
>>> from transformers import pipeline

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

>>> # 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()](/docs/transformers/v5.23.0/zh/main_classes/pipelines#transformers.pipeline) 使用以下任务标识符进行加载：`"text-to-speech"` 或 `"text-to-audio"`。

在 [huggingface.co/models](https://huggingface.co/models?filter=text-to-speech) 上查看可用模型列表。

#### __调用__[[transformers.TextToAudioPipeline.__call__]]

```python
__call__(text_inputs, **forward_params)
```

[来源](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/pipelines/text_to_audio.py#L260)

**参数：**

text_inputs (`str`、`list[str]`、`ChatType` 或 `list[ChatType]`)：一个或多个待生成的文本。如果传入字符串或字符串列表，该流水线将生成相应的文本。或者，可以传入以包含 "role" 和 "content" 键的字典列表形式表示的 "chat"，或此类 chat 的列表。当传入 chat 时，将使用模型的 chat 模板对其进行格式化，然后再传递给模型。

forward_params (`dict`，*可选*)：传递给模型生成/前向方法的参数。`forward_params` 始终会传递给底层模型。

generate_kwargs (`dict`, *可选*) : 用于生成调用的 `generate_config` 的临时参数化字典。如需了解 generate 的完整概览，请参阅[以下指南](https://huggingface.co/docs/transformers/en/main_classes/text_generation)。仅当底层模型为生成式模型时，`generate_kwargs` 才会传递给该模型，并且其优先级高于 `forward_params`。

**返回：** `AudioOutput` 或 `AudioOutput` 列表，这是一个包含两个键的 `TypedDict`

- **audio**（形状为 `(nb_channels, audio_length)` 的 `np.ndarray`）-- 生成的音频波形。
- **sampling_rate** (`int`) -- 生成音频波形的采样率。

根据输入生成语音/音频。有关更多信息，请参阅 [TextToAudioPipeline](/docs/transformers/v5.23.0/zh/main_classes/pipelines#transformers.TextToAudioPipeline) 文档。

### ZeroShotAudioClassificationPipeline[[transformers.ZeroShotAudioClassificationPipeline]]

#### transformers.ZeroShotAudioClassificationPipeline[[transformers.ZeroShotAudioClassificationPipeline]]

```python
transformers.ZeroShotAudioClassificationPipeline(**kwargs)
```

[来源](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/pipelines/zero_shot_audio_classification.py#L32)

**参数：**

model ([PreTrainedModel](/docs/transformers/v5.23.0/zh/main_classes/model#transformers.PreTrainedModel))：流水线用于进行预测的模型。该模型必须继承自 [PreTrainedModel](/docs/transformers/v5.23.0/zh/main_classes/model#transformers.PreTrainedModel)。

tokenizer ([PreTrainedTokenizer](/docs/transformers/v5.23.0/zh/main_classes/tokenizer#transformers.PythonBackend))：流水线将使用该分词器为模型编码数据。此对象继承自 [PreTrainedTokenizer](/docs/transformers/v5.23.0/zh/main_classes/tokenizer#transformers.PythonBackend)。

feature_extractor ([SequenceFeatureExtractor](/docs/transformers/v5.23.0/zh/main_classes/feature_extractor#transformers.SequenceFeatureExtractor))：流水线将使用该特征提取器为模型编码数据。此对象继承自 [SequenceFeatureExtractor](/docs/transformers/v5.23.0/zh/main_classes/feature_extractor#transformers.SequenceFeatureExtractor)。

task (`str`，默认为 `""`)：用于标识 pipeline 的任务。

num_workers (`int`，*可选*，默认值为 8)：当流水线使用 *DataLoader*（例如传入数据集，或在 GPU 上运行 PyTorch 模型时）时，所使用的 worker 数量。

batch_size (`int`，*可选*，默认为 1)：当流水线使用 *DataLoader*（例如传入数据集，或在 GPU 上运行 PyTorch 模型时）时，所使用的批次大小。对于推理而言，增大批次大小并不总是有益的，请参阅 [使用流水线进行批处理](https://huggingface.co/transformers/main_classes/pipelines.html#pipeline-batching)。

args_parser ([ArgumentHandler](/docs/transformers/v5.23.0/zh/internal/pipelines_utils#transformers.pipelines.ArgumentHandler)，*可选*)：负责解析所提供 pipeline 参数的对象引用。

device (`int` 或 `str` 或 `torch.device`，*可选*)：流水线所分配的设备。若未设置，流水线将放置在第一个可用的加速器（CUDA、MPS、XPU 等）上，仅当没有可用加速器时才回退到 CPU；模型会自动移动至该设备。传入 `device="cpu"`（或 `-1`）可强制使用 CPU，传入正序数或 `"cuda:1"` 可选择特定加速器，或传入原生的 `torch.device`/`str`。此参数不能与已通过 `accelerate` 加载的模型（即具有 `hf_device_map` 的模型）一起使用。

dtype (`str` 或 `torch.dtype`，*可选*，默认为 `"auto"`)：模型加载时使用的精度，会传递给 `from_pretrained`。默认为 `"auto"`，即以模型保存时的 dtype 加载模型（从检查点的 `config.dtype` 读取，否则从权重推断）。传入显式的 `torch.float16`、`torch.bfloat16`、`torch.float32` 等可覆盖该默认值。

binary_output (`bool`，*可选*，默认为 `False`)：一个标志，指示管道输出应采用序列化格式（即 pickle）还是原始输出数据（例如文本）。

使用 `ClapModel` 的零样本音频分类流水线。该流水线在提供一段音频和一组 `candidate_labels` 时，预测该音频的类别。

默认的 `hypothesis_template` 为： `"This is a sound of {}."`。请确保根据你的使用场景对其进行更新。

示例：
```python
>>> 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 vacuum cleaner"])
[{'score': 0.9996, 'label': 'Sound of a dog'}, {'score': 0.0004, 'label': 'Sound of vacuum cleaner'}]
```

有关使用 pipeline 的基础知识，请参阅 [pipeline 教程](../pipeline_tutorial)。目前，该音频分类 pipeline 可以通过 [pipeline()](/docs/transformers/v5.23.0/zh/main_classes/pipelines#transformers.pipeline) 使用以下任务标识符进行加载：`"zero-shot-audio-classification"`。有关可用模型的列表，请访问 [huggingface.co/models](https://huggingface.co/models?filter=zero-shot-audio-classification)。

#### __调用__[[transformers.ZeroShotAudioClassificationPipeline.__call__]]

```python
__call__(audios: numpy.ndarray | bytes | str | dict, **kwargs: Any)
```

[来源](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/pipelines/zero_shot_audio_classification.py#L70)

**参数：**

audios (`str`、`list[str]`、`np.array` 或 `list[np.array]`)：该流水线支持三种类型的输入：- 包含指向音频的 http 链接的字符串 - 包含音频本地路径的字符串 - 以 numpy 加载的音频

candidate_labels (`list[str]`) : 此音频的候选标签。它们将使用 *hypothesis_template* 进行格式化。

hypothesis_template (`str`，*可选*，默认为 `"This is a sound of {}"`)：与 *candidate_labels* 配合使用的格式，通过将占位符替换为 candidate_labels 来尝试进行音频分类。如果 *candidate_labels* 已经格式化，请传入 "{}"。

**返回值：**

一个字典列表，每个建议的标签对应一个条目。每个字典包含以下键：
- **label** (`str`) -- *candidate_labels* 中的一个建议值。
- **score** (`float`) -- 模型为该标签赋予的分数。其取值范围为 0 到 1，由 `logits_per_audio` 的 `softmax` 计算得出。

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

## 计算机视觉

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

### DepthEstimationPipeline[[transformers.DepthEstimationPipeline]]

#### transformers.DepthEstimationPipeline[[transformers.DepthEstimationPipeline]]

```python
transformers.DepthEstimationPipeline(*args, **kwargs)
```

[来源](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/pipelines/depth_estimation.py#L25)

**参数：**

model ([PreTrainedModel](/docs/transformers/v5.23.0/zh/main_classes/model#transformers.PreTrainedModel))：流水线用于进行预测的模型。该模型必须继承自 [PreTrainedModel](/docs/transformers/v5.23.0/zh/main_classes/model#transformers.PreTrainedModel)。

image_processor ([BaseImageProcessor](/docs/transformers/v5.23.0/zh/main_classes/image_processor#transformers.BaseImageProcessor))：流水线将使用该图像处理器为模型编码数据。此对象继承自 [BaseImageProcessor](/docs/transformers/v5.23.0/zh/main_classes/image_processor#transformers.BaseImageProcessor)。

task (`str`，默认为 `""`)：用于标识 pipeline 的任务。

num_workers (`int`，*可选*，默认值为 8)：当流水线使用 *DataLoader*（例如传入数据集，或在 GPU 上运行 PyTorch 模型时）时，所使用的 worker 数量。

batch_size (`int`，*可选*，默认为 1)：当流水线使用 *DataLoader*（例如传入数据集，或在 GPU 上运行 PyTorch 模型时）时，所使用的批次大小。对于推理而言，增大批次大小并不总是有益的，请参阅 [使用流水线进行批处理](https://huggingface.co/transformers/main_classes/pipelines.html#pipeline-batching)。

args_parser ([ArgumentHandler](/docs/transformers/v5.23.0/zh/internal/pipelines_utils#transformers.pipelines.ArgumentHandler)，*可选*)：负责解析所提供 pipeline 参数的对象引用。

device (`int` 或 `str` 或 `torch.device`，*可选*)：流水线所分配的设备。若未设置，流水线将放置在第一个可用的加速器（CUDA、MPS、XPU 等）上，仅当没有可用加速器时才回退到 CPU；模型会自动移动至该设备。传入 `device="cpu"`（或 `-1`）可强制使用 CPU，传入正序数或 `"cuda:1"` 可选择特定加速器，或传入原生的 `torch.device`/`str`。此参数不能与已通过 `accelerate` 加载的模型（即具有 `hf_device_map` 的模型）一起使用。

dtype (`str` 或 `torch.dtype`，*可选*，默认为 `"auto"`)：模型加载时使用的精度，会传递给 `from_pretrained`。默认为 `"auto"`，即以模型保存时的 dtype 加载模型（从检查点的 `config.dtype` 读取，否则从权重推断）。传入显式的 `torch.float16`、`torch.bfloat16`、`torch.float32` 等可覆盖该默认值。

binary_output (`bool`，*可选*，默认为 `False`)：一个标志，指示管道输出应采用序列化格式（即 pickle）还是原始输出数据（例如文本）。

使用任意 `AutoModelForDepthEstimation` 的深度估计流水线。该流水线用于预测图像的景深。

示例：

```python
>>> 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_tutorial) 中了解使用 pipeline 的基础知识。

该深度估计流水线目前可以通过 [pipeline()](/docs/transformers/v5.23.0/zh/main_classes/pipelines#transformers.pipeline) 使用以下任务标识符进行加载：`"depth-estimation"`。

在 [huggingface.co/models](https://huggingface.co/models?filter=depth-estimation) 上查看可用模型列表。

#### __调用__[[transformers.DepthEstimationPipeline.__call__]]

```python
__call__(inputs: typing.Union[str, list[str], ForwardRef('Image.Image'), list['Image.Image']], **kwargs: Any)
```

[来源](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/pipelines/depth_estimation.py#L66)

**参数：**

inputs (`str`、`list[str]`、`PIL.Image` 或 `list[PIL.Image]`)：该流水线支持三种类型的图像： - 包含指向图像的 http 链接的字符串 - 包含图像本地路径的字符串 - 直接以 PIL 加载的图像  该流水线接受单张图像或一批图像，后者必须以字符串形式传入。批次中的图像必须全部采用相同的格式：全部为 http 链接、全部为本地路径，或全部为 PIL 图像。

parameters (`Dict`，*可选*)：一个从参数名映射到参数值的字典，用于控制流水线行为。目前唯一可用的参数是 `timeout`，即流水线在放弃尝试下载图像前应等待的秒数。

timeout (`float`, *可选*，默认为 None) : 从网络获取图像时等待的最大时间（秒）。如果为 None，则不设置超时，调用可能会永久阻塞。

**返回值：**

包含结果的字典或字典列表。如果输入是单张图像，则返回一个字典；如果输入是多张图像的列表，则返回一个与这些图像对应的字典列表。

这些字典包含以下键：

- **predicted_depth** (`torch.Tensor`) -- 模型预测的深度，类型为 `torch.Tensor`。
- **depth** (`PIL.Image`) -- 模型预测的深度，类型为 `PIL.Image`。

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

### ImageClassificationPipeline[[transformers.ImageClassificationPipeline]]

#### transformers.ImageClassificationPipeline[[transformers.ImageClassificationPipeline]]

```python
transformers.ImageClassificationPipeline(*args, **kwargs)
```

[来源](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/pipelines/image_classification.py#L74)

**参数：**

model ([PreTrainedModel](/docs/transformers/v5.23.0/zh/main_classes/model#transformers.PreTrainedModel))：流水线用于进行预测的模型。该模型必须继承自 [PreTrainedModel](/docs/transformers/v5.23.0/zh/main_classes/model#transformers.PreTrainedModel)。

image_processor ([BaseImageProcessor](/docs/transformers/v5.23.0/zh/main_classes/image_processor#transformers.BaseImageProcessor))：流水线将使用该图像处理器为模型编码数据。此对象继承自 [BaseImageProcessor](/docs/transformers/v5.23.0/zh/main_classes/image_processor#transformers.BaseImageProcessor)。

task (`str`，默认为 `""`)：用于标识 pipeline 的任务。

num_workers (`int`，*可选*，默认值为 8)：当流水线使用 *DataLoader*（例如传入数据集，或在 GPU 上运行 PyTorch 模型时）时，所使用的 worker 数量。

batch_size (`int`，*可选*，默认为 1)：当流水线使用 *DataLoader*（例如传入数据集，或在 GPU 上运行 PyTorch 模型时）时，所使用的批次大小。对于推理而言，增大批次大小并不总是有益的，请参阅 [使用流水线进行批处理](https://huggingface.co/transformers/main_classes/pipelines.html#pipeline-batching)。

args_parser ([ArgumentHandler](/docs/transformers/v5.23.0/zh/internal/pipelines_utils#transformers.pipelines.ArgumentHandler)，*可选*)：负责解析所提供 pipeline 参数的对象引用。

device (`int` 或 `str` 或 `torch.device`，*可选*)：流水线所分配的设备。若未设置，流水线将放置在第一个可用的加速器（CUDA、MPS、XPU 等）上，仅当没有可用加速器时才回退到 CPU；模型会自动移动至该设备。传入 `device="cpu"`（或 `-1`）可强制使用 CPU，传入正序数或 `"cuda:1"` 可选择特定加速器，或传入原生的 `torch.device`/`str`。此参数不能与已通过 `accelerate` 加载的模型（即具有 `hf_device_map` 的模型）一起使用。

dtype (`str` 或 `torch.dtype`，*可选*，默认为 `"auto"`)：模型加载时使用的精度，会传递给 `from_pretrained`。默认为 `"auto"`，即以模型保存时的 dtype 加载模型（从检查点的 `config.dtype` 读取，否则从权重推断）。传入显式的 `torch.float16`、`torch.bfloat16`、`torch.float32` 等可覆盖该默认值。

binary_output (`bool`，*可选*，默认为 `False`)：一个标志，指示管道输出应采用序列化格式（即 pickle）还是原始输出数据（例如文本）。

function_to_apply (`str`，*可选*，默认为 `"default"`)：用于处理模型输出以获取分数的函数。接受以下四种不同的值： - `"default"`：如果模型只有一个标签，则对输出应用 sigmoid 函数。如果模型有多个标签，则对输出应用 softmax 函数。对于回归任务，则不对输出应用任何函数。 - `"sigmoid"`：对输出应用 sigmoid 函数。 - `"softmax"`：对输出应用 softmax 函数。 - `"none"`：不对输出应用任何函数。

使用任意 `AutoModelForImageClassification` 的图像分类流水线。该流水线用于预测图像的类别。

示例：

```python
>>> 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_tutorial) 中了解使用 pipeline 的基础知识。

该图像分类流水线目前可以通过 [pipeline()](/docs/transformers/v5.23.0/zh/main_classes/pipelines#transformers.pipeline) 使用以下任务标识符进行加载：`"image-classification"`。

在 [huggingface.co/models](https://huggingface.co/models?filter=image-classification) 上查看可用模型列表。

#### __调用__[[transformers.ImageClassificationPipeline.__call__]]

```python
__call__(inputs: typing.Union[str, list[str], ForwardRef('Image.Image'), list['Image.Image']], **kwargs: Any)
```

[来源](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/pipelines/image_classification.py#L128)

**参数：**

inputs (`str`、`list[str]`、`PIL.Image` 或 `list[PIL.Image]`)：该流水线支持三种类型的图像： - 包含指向图像的 http 链接的字符串 - 包含图像本地路径的字符串 - 直接以 PIL 加载的图像  该流水线接受单张图像或一批图像，后者必须以字符串形式传入。批次中的图像必须全部采用相同的格式：全部为 http 链接、全部为本地路径，或全部为 PIL 图像。

function_to_apply (`str`，*可选*，默认为 `"default"`)：用于处理模型输出以获取分数的函数。接受以下四种不同的值： 如果未指定此参数，则将根据标签数量应用以下函数： - 如果问题类型为回归，则不对输出应用任何函数。 - 如果模型只有一个标签，则对输出应用 sigmoid 函数。 - 如果模型有多个标签，则对输出应用 softmax 函数。 可能的取值如下： - `"sigmoid"`：对输出应用 sigmoid 函数。 - `"softmax"`：对输出应用 softmax 函数。 - `"none"`：不对输出应用任何函数。

top_k (`int`，*可选*，默认值为 5)：流水线将返回的顶级标签数量。如果提供的数值大于模型配置中可用的标签数量，则默认使用标签数量。

timeout (`float`, *可选*，默认为 None) : 从网络获取图像时等待的最大时间（秒）。如果为 None，则不设置超时，调用可能会永久阻塞。

**返回值：**

包含结果的字典或字典列表。如果输入是单张图像，则返回一个字典；如果输入是多张图像的列表，则返回一个与这些图像对应的字典列表。

这些字典包含以下键：

- **label** (`str`) -- 模型识别出的标签。
- **score** (`int`) -- 模型为该标签分配的分数。

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

### ImageSegmentationPipeline[[transformers.ImageSegmentationPipeline]]

#### transformers.ImageSegmentationPipeline[[transformers.ImageSegmentationPipeline]]

```python
transformers.ImageSegmentationPipeline(*args, **kwargs)
```

[来源](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/pipelines/image_segmentation.py#L27)

**参数：**

model ([PreTrainedModel](/docs/transformers/v5.23.0/zh/main_classes/model#transformers.PreTrainedModel))：流水线用于进行预测的模型。该模型必须继承自 [PreTrainedModel](/docs/transformers/v5.23.0/zh/main_classes/model#transformers.PreTrainedModel)。

image_processor ([BaseImageProcessor](/docs/transformers/v5.23.0/zh/main_classes/image_processor#transformers.BaseImageProcessor))：流水线将使用该图像处理器为模型编码数据。此对象继承自 [BaseImageProcessor](/docs/transformers/v5.23.0/zh/main_classes/image_processor#transformers.BaseImageProcessor)。

task (`str`，默认为 `""`)：用于标识 pipeline 的任务。

num_workers (`int`，*可选*，默认值为 8)：当流水线使用 *DataLoader*（例如传入数据集，或在 GPU 上运行 PyTorch 模型时）时，所使用的 worker 数量。

batch_size (`int`，*可选*，默认为 1)：当流水线使用 *DataLoader*（例如传入数据集，或在 GPU 上运行 PyTorch 模型时）时，所使用的批次大小。对于推理而言，增大批次大小并不总是有益的，请参阅 [使用流水线进行批处理](https://huggingface.co/transformers/main_classes/pipelines.html#pipeline-batching)。

args_parser ([ArgumentHandler](/docs/transformers/v5.23.0/zh/internal/pipelines_utils#transformers.pipelines.ArgumentHandler)，*可选*)：负责解析所提供 pipeline 参数的对象引用。

device (`int` 或 `str` 或 `torch.device`，*可选*)：流水线所分配的设备。若未设置，流水线将放置在第一个可用的加速器（CUDA、MPS、XPU 等）上，仅当没有可用加速器时才回退到 CPU；模型会自动移动至该设备。传入 `device="cpu"`（或 `-1`）可强制使用 CPU，传入正序数或 `"cuda:1"` 可选择特定加速器，或传入原生的 `torch.device`/`str`。此参数不能与已通过 `accelerate` 加载的模型（即具有 `hf_device_map` 的模型）一起使用。

dtype (`str` 或 `torch.dtype`，*可选*，默认为 `"auto"`)：模型加载时使用的精度，会传递给 `from_pretrained`。默认为 `"auto"`，即以模型保存时的 dtype 加载模型（从检查点的 `config.dtype` 读取，否则从权重推断）。传入显式的 `torch.float16`、`torch.bfloat16`、`torch.float32` 等可覆盖该默认值。

binary_output (`bool`，*可选*，默认为 `False`)：一个标志，指示管道输出应采用序列化格式（即 pickle）还是原始输出数据（例如文本）。

使用任意 `AutoModelForXXXSegmentation` 的图像分割流水线。该流水线用于预测对象的掩码及其类别。

示例：

```python
>>> 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()](/docs/transformers/v5.23.0/zh/main_classes/pipelines#transformers.pipeline) 使用以下任务标识符进行加载：`"image-segmentation"`。

在 [huggingface.co/models](https://huggingface.co/models?filter=image-segmentation) 上查看可用模型列表。

#### __调用__[[transformers.ImageSegmentationPipeline.__call__]]

```python
__call__(inputs: typing.Union[str, ForwardRef('Image.Image'), list[str], list['Image.Image']], **kwargs: Any)
```

[来源](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/pipelines/image_segmentation.py#L101)

**参数：**

inputs (`str`、`list[str]`、`PIL.Image` 或 `list[PIL.Image]`)：该流水线处理三种类型的图像： - 包含指向图像的 HTTP(S) 链接的字符串 - 包含图像本地路径的字符串 - 直接以 PIL 加载的图像  该流水线接受单张图像或一批图像。批次中的图像必须全部采用相同的格式：全部为 HTTP(S) 链接、全部为本地路径，或全部为 PIL 图像。

subtask (`str`, *可选*) : 要执行的分割任务，根据模型能力从 [`semantic`、`instance` 和 `panoptic`] 中选择。如果未设置，流水线将按以下顺序尝试解析：`panoptic`、`instance`、`semantic`。

threshold (`float`, *可选*，默认为 0.9)：用于过滤预测掩码的概率阈值。

mask_threshold (`float`，*可选*，默认值为 0.5)：将预测掩码转换为二值时使用的阈值。

overlap_mask_area_threshold (`float`，*可选*，默认值为 0.5)：用于消除细小、不连续片段的掩码重叠阈值。

timeout (`float`, *可选*，默认为 None) : 从网络获取图像时等待的最大时间（秒）。如果为 None，则不设置超时，调用可能会永久阻塞。

**返回值：**

如果输入是单张图像，将返回一个字典列表；如果输入是多张图像的列表，将返回一个字典列表的列表，分别对应每张图像。

这些字典包含每个检测到的对象的掩码、标签和分数（如适用），并包含以下键：

- **label** (`str`) -- 模型识别出的类别标签。
- **mask** (`PIL.Image`) -- 检测到的对象的二值掩码，表示为原始图像形状 (width, height) 的 PIL Image。如果未检测到对象，则返回一个填充为零的掩码。
- **score**（*可选* `float`）-- 可选参数，当模型能够估计由标签和掩码所描述的“对象”的置信度时使用。

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

### KeypointMatchingPipeline[[transformers.KeypointMatchingPipeline]]

#### transformers.KeypointMatchingPipeline[[transformers.KeypointMatchingPipeline]]

```python
transformers.KeypointMatchingPipeline(*args, **kwargs)
```

[来源](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/pipelines/keypoint_matching.py#L67)

使用任意 `AutoModelForKeypointMatching` 的关键点匹配流水线。该流水线用于在两张图像之间匹配关键点。

#### __调用__[[transformers.KeypointMatchingPipeline.__call__]]

```python
__call__(inputs: list[collections.abc.Sequence[typing.Union[ForwardRef('Image.Image'), str]]] | collections.abc.Sequence[typing.Union[ForwardRef('Image.Image'), str]], threshold: float = 0.0, **kwargs: Any)
```

[来源](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/pipelines/keypoint_matching.py#L96)

**参数：**

inputs (`str`、`list[str]`、`PIL.Image` 或 `list[PIL.Image]`)：该流水线处理三种类型的图像： - 包含指向图像的 http 链接的字符串 - 包含图像本地路径的字符串 - 直接以 PIL 加载的图像  该流水线接受单对图像或一批图像对，后者必须以字符串形式传入。批次中的图像必须全部采用相同格式：全部为 http 链接、全部为本地路径，或全部为 PIL 图像。

threshold (`float`，*可选*，默认值为 0.0)：用于关键点匹配的阈值。匹配分数低于该阈值的匹配关键点将被过滤掉。值为 0 表示返回所有匹配的关键点。

kwargs : `timeout (`float`, *optional*, defaults to None)` 从网络获取图像时等待的最大秒数。如果为 None，则不设置超时，调用可能会永久阻塞。

**返回：** Union[list[Match], list[list[Match]]]

如果提供单个图像对，则为匹配列表；如果提供一批图像对，则为匹配列表的列表。每个匹配项都是一个字典，包含以下键：

- **keypoint_image_0**（`Keypoint`）：第一张图像中的关键点（x、y 坐标）。
- **keypoint_image_1**（`Keypoint`）：第二张图像中的关键点（x、y 坐标）。
- **score** (`float`)：两个关键点之间的匹配分数。

在两张图像的关键点之间查找匹配。

### ObjectDetectionPipeline[[transformers.ObjectDetectionPipeline]]

#### transformers.ObjectDetectionPipeline[[transformers.ObjectDetectionPipeline]]

```python
transformers.ObjectDetectionPipeline(*args, **kwargs)
```

[来源](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/pipelines/object_detection.py#L26)

**参数：**

model ([PreTrainedModel](/docs/transformers/v5.23.0/zh/main_classes/model#transformers.PreTrainedModel))：流水线用于进行预测的模型。该模型必须继承自 [PreTrainedModel](/docs/transformers/v5.23.0/zh/main_classes/model#transformers.PreTrainedModel)。

image_processor ([BaseImageProcessor](/docs/transformers/v5.23.0/zh/main_classes/image_processor#transformers.BaseImageProcessor))：流水线将使用该图像处理器为模型编码数据。此对象继承自 [BaseImageProcessor](/docs/transformers/v5.23.0/zh/main_classes/image_processor#transformers.BaseImageProcessor)。

task (`str`，默认为 `""`)：用于标识 pipeline 的任务。

num_workers (`int`，*可选*，默认值为 8)：当流水线使用 *DataLoader*（例如传入数据集，或在 GPU 上运行 PyTorch 模型时）时，所使用的 worker 数量。

batch_size (`int`，*可选*，默认为 1)：当流水线使用 *DataLoader*（例如传入数据集，或在 GPU 上运行 PyTorch 模型时）时，所使用的批次大小。对于推理而言，增大批次大小并不总是有益的，请参阅 [使用流水线进行批处理](https://huggingface.co/transformers/main_classes/pipelines.html#pipeline-batching)。

args_parser ([ArgumentHandler](/docs/transformers/v5.23.0/zh/internal/pipelines_utils#transformers.pipelines.ArgumentHandler)，*可选*)：负责解析所提供 pipeline 参数的对象引用。

device (`int` 或 `str` 或 `torch.device`，*可选*)：流水线所分配的设备。若未设置，流水线将放置在第一个可用的加速器（CUDA、MPS、XPU 等）上，仅当没有可用加速器时才回退到 CPU；模型会自动移动至该设备。传入 `device="cpu"`（或 `-1`）可强制使用 CPU，传入正序数或 `"cuda:1"` 可选择特定加速器，或传入原生的 `torch.device`/`str`。此参数不能与已通过 `accelerate` 加载的模型（即具有 `hf_device_map` 的模型）一起使用。

dtype (`str` 或 `torch.dtype`，*可选*，默认为 `"auto"`)：模型加载时使用的精度，会传递给 `from_pretrained`。默认为 `"auto"`，即以模型保存时的 dtype 加载模型（从检查点的 `config.dtype` 读取，否则从权重推断）。传入显式的 `torch.float16`、`torch.bfloat16`、`torch.float32` 等可覆盖该默认值。

binary_output (`bool`，*可选*，默认为 `False`)：一个标志，指示管道输出应采用序列化格式（即 pickle）还是原始输出数据（例如文本）。

使用任意 `AutoModelForObjectDetection` 的目标检测流水线。该流水线用于预测目标对象的边界框及其类别。

示例：

```python
>>> 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_tutorial) 中了解使用 pipeline 的基础知识。

该目标检测流水线目前可以通过 [pipeline()](/docs/transformers/v5.23.0/zh/main_classes/pipelines#transformers.pipeline) 使用以下任务标识符进行加载：`"object-detection"`。

在 [huggingface.co/models](https://huggingface.co/models?filter=object-detection) 上查看可用模型列表。

#### __调用__[[transformers.ObjectDetectionPipeline.__call__]]

```python
__call__(*args, **kwargs)
```

[来源](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/pipelines/object_detection.py#L81)

**参数：**

inputs (`str`、`list[str]`、`PIL.Image` 或 `list[PIL.Image]`)：该流水线处理三种类型的图像： - 包含指向图像的 HTTP(S) 链接的字符串 - 包含图像本地路径的字符串 - 直接以 PIL 加载的图像  该流水线接受单张图像或一批图像。批次中的图像必须全部采用相同的格式：全部为 HTTP(S) 链接、全部为本地路径，或全部为 PIL 图像。

threshold (`float`，*可选*，默认值为 0.5)：进行预测所需的概率。

timeout (`float`, *可选*，默认为 None) : 从网络获取图像时等待的最大时间（秒）。如果为 None，则不设置超时，调用可能会永久阻塞。

**返回值：**

包含结果的字典列表或字典列表的列表。如果输入是单张图像，则返回字典列表；如果输入是多张图像的列表，则返回与每张图像对应的字典列表的列表。

这些字典包含以下键：

- **label** (`str`) -- 模型识别出的类别标签。
- **score**（`float`）-- 模型为该标签分配的分数。
- **box** (`list[dict[str, int]]`) -- 检测到的对象在原始尺寸图像中的边界框。

检测作为输入传入的图像中的对象（边界框 & 类别）。

### VideoClassificationPipeline[[transformers.VideoClassificationPipeline]]

#### transformers.VideoClassificationPipeline[[transformers.VideoClassificationPipeline]]

```python
transformers.VideoClassificationPipeline(*args, **kwargs)
```

[来源](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/pipelines/video_classification.py#L41)

**参数：**

model ([PreTrainedModel](/docs/transformers/v5.23.0/zh/main_classes/model#transformers.PreTrainedModel))：流水线用于进行预测的模型。该模型必须继承自 [PreTrainedModel](/docs/transformers/v5.23.0/zh/main_classes/model#transformers.PreTrainedModel)。

image_processor ([BaseImageProcessor](/docs/transformers/v5.23.0/zh/main_classes/image_processor#transformers.BaseImageProcessor))：流水线将使用该图像处理器为模型编码数据。此对象继承自 [BaseImageProcessor](/docs/transformers/v5.23.0/zh/main_classes/image_processor#transformers.BaseImageProcessor)。

video_processor ([BaseVideoProcessor](/docs/transformers/v5.23.0/zh/main_classes/video_processor#transformers.BaseVideoProcessor))：流水线将使用该视频处理器对视频数据进行编码，以供模型使用。此对象继承自 [BaseVideoProcessor](/docs/transformers/v5.23.0/zh/main_classes/video_processor#transformers.BaseVideoProcessor)。

task (`str`，默认为 `""`)：用于标识 pipeline 的任务。

num_workers (`int`，*可选*，默认值为 8)：当流水线使用 *DataLoader*（例如传入数据集，或在 GPU 上运行 PyTorch 模型时）时，所使用的 worker 数量。

batch_size (`int`，*可选*，默认为 1)：当流水线使用 *DataLoader*（例如传入数据集，或在 GPU 上运行 PyTorch 模型时）时，所使用的批次大小。对于推理而言，增大批次大小并不总是有益的，请参阅 [使用流水线进行批处理](https://huggingface.co/transformers/main_classes/pipelines.html#pipeline-batching)。

args_parser ([ArgumentHandler](/docs/transformers/v5.23.0/zh/internal/pipelines_utils#transformers.pipelines.ArgumentHandler)，*可选*)：负责解析所提供 pipeline 参数的对象引用。

device (`int` 或 `str` 或 `torch.device`，*可选*)：流水线所分配的设备。若未设置，流水线将放置在第一个可用的加速器（CUDA、MPS、XPU 等）上，仅当没有可用加速器时才回退到 CPU；模型会自动移动至该设备。传入 `device="cpu"`（或 `-1`）可强制使用 CPU，传入正序数或 `"cuda:1"` 可选择特定加速器，或传入原生的 `torch.device`/`str`。此参数不能与已通过 `accelerate` 加载的模型（即具有 `hf_device_map` 的模型）一起使用。

dtype (`str` 或 `torch.dtype`，*可选*，默认为 `"auto"`)：模型加载时使用的精度，会传递给 `from_pretrained`。默认为 `"auto"`，即以模型保存时的 dtype 加载模型（从检查点的 `config.dtype` 读取，否则从权重推断）。传入显式的 `torch.float16`、`torch.bfloat16`、`torch.float32` 等可覆盖该默认值。

binary_output (`bool`，*可选*，默认为 `False`)：一个标志，指示管道输出应采用序列化格式（即 pickle）还是原始输出数据（例如文本）。

使用任意 `AutoModelForVideoClassification` 的视频分类流水线。该流水线用于预测视频的类别。

该视频分类流水线目前可以通过 [pipeline()](/docs/transformers/v5.23.0/zh/main_classes/pipelines#transformers.pipeline) 使用以下任务标识符进行加载：`"video-classification"`。

在 [huggingface.co/models](https://huggingface.co/models?filter=video-classification) 上查看可用模型列表。

该 pipeline 支持使用图像处理器（image processor）的模型（例如 VideoMAE、ViViT 和 TimeSformer 等旧版视频模型），也支持使用视频处理器（video processor）的模型（例如 VJEPA2 等较新的模型）。如果两者同时存在，视频处理器将优先使用；如果两者均未找到，pipeline 将抛出错误。

#### __调用__[[transformers.VideoClassificationPipeline.__call__]]

```python
__call__(inputs: str | list[str] | None, **kwargs)
```

[来源](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/pipelines/video_classification.py#L103)

**参数：**

inputs (`str`, `list[str]`) : 该流水线处理三种类型的视频：  - 包含指向视频的 http 链接的字符串 - 包含视频本地路径的字符串  该流水线接受单个视频或一批视频，此时必须以字符串形式传入。批次中的视频必须全部采用相同格式：全部为 http 链接或全部为本地路径。

top_k (`int`，*可选*，默认值为 5)：流水线将返回的顶级标签数量。如果提供的数值大于模型配置中可用的标签数量，则默认使用标签数量。

num_frames (`int`，*可选*，默认为 `self.model.config.num_frames`)：用于执行分类的视频采样帧数。如果未提供，则默认使用模型配置中指定的帧数。

frame_sampling_rate (`int`，*可选*，默认为 1)：用于从视频中选取帧的采样率。如果未提供，则默认为 1，即使用每一帧。

function_to_apply (`str`, *可选*) : 应用于模型输出的函数。回归任务默认为 "none"，多标签分类任务默认为 "sigmoid"，其他任务默认为 "softmax"。有效选项：["softmax", "sigmoid", "none"]。在初始化或调用时显式提供的值会覆盖这些默认值。传入字符串 "none" 可禁用后处理。

**返回值：**

包含结果的字典列表或字典列表的列表。如果输入是单个视频，将返回一个包含 `top_k` 个字典的列表；如果输入是多个视频的列表，将返回一个对应于这些视频的、包含 `top_k` 个字典的列表的列表。

这些字典包含以下键：

- **label** (`str`) -- 模型识别出的标签。
- **score** (`int`) -- 模型为该标签分配的分数。

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

### ZeroShotImageClassificationPipeline[[transformers.ZeroShotImageClassificationPipeline]]

#### transformers.ZeroShotImageClassificationPipeline[[transformers.ZeroShotImageClassificationPipeline]]

```python
transformers.ZeroShotImageClassificationPipeline(**kwargs)
```

[来源](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/pipelines/zero_shot_image_classification.py#L29)

**参数：**

model ([PreTrainedModel](/docs/transformers/v5.23.0/zh/main_classes/model#transformers.PreTrainedModel))：流水线用于进行预测的模型。该模型必须继承自 [PreTrainedModel](/docs/transformers/v5.23.0/zh/main_classes/model#transformers.PreTrainedModel)。

image_processor ([BaseImageProcessor](/docs/transformers/v5.23.0/zh/main_classes/image_processor#transformers.BaseImageProcessor))：流水线将使用该图像处理器为模型编码数据。此对象继承自 [BaseImageProcessor](/docs/transformers/v5.23.0/zh/main_classes/image_processor#transformers.BaseImageProcessor)。

task (`str`，默认为 `""`)：用于标识 pipeline 的任务。

num_workers (`int`，*可选*，默认值为 8)：当流水线使用 *DataLoader*（例如传入数据集，或在 GPU 上运行 PyTorch 模型时）时，所使用的 worker 数量。

batch_size (`int`，*可选*，默认为 1)：当流水线使用 *DataLoader*（例如传入数据集，或在 GPU 上运行 PyTorch 模型时）时，所使用的批次大小。对于推理而言，增大批次大小并不总是有益的，请参阅 [使用流水线进行批处理](https://huggingface.co/transformers/main_classes/pipelines.html#pipeline-batching)。

args_parser ([ArgumentHandler](/docs/transformers/v5.23.0/zh/internal/pipelines_utils#transformers.pipelines.ArgumentHandler)，*可选*)：负责解析所提供 pipeline 参数的对象引用。

device (`int` 或 `str` 或 `torch.device`，*可选*)：流水线所分配的设备。若未设置，流水线将放置在第一个可用的加速器（CUDA、MPS、XPU 等）上，仅当没有可用加速器时才回退到 CPU；模型会自动移动至该设备。传入 `device="cpu"`（或 `-1`）可强制使用 CPU，传入正序数或 `"cuda:1"` 可选择特定加速器，或传入原生的 `torch.device`/`str`。此参数不能与已通过 `accelerate` 加载的模型（即具有 `hf_device_map` 的模型）一起使用。

dtype (`str` 或 `torch.dtype`，*可选*，默认为 `"auto"`)：模型加载时使用的精度，会传递给 `from_pretrained`。默认为 `"auto"`，即以模型保存时的 dtype 加载模型（从检查点的 `config.dtype` 读取，否则从权重推断）。传入显式的 `torch.float16`、`torch.bfloat16`、`torch.float32` 等可覆盖该默认值。

binary_output (`bool`，*可选*，默认为 `False`)：一个标志，指示管道输出应采用序列化格式（即 pickle）还是原始输出数据（例如文本）。

使用 `CLIPModel` 的零样本图像分类流水线。当您提供一张图像和一组 `candidate_labels` 时，该流水线会预测图像的类别。

示例：

```python
>>> 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_tutorial) 中了解使用 pipeline 的基础知识。

该图像分类流水线目前可以通过 [pipeline()](/docs/transformers/v5.23.0/zh/main_classes/pipelines#transformers.pipeline) 使用以下任务标识符进行加载：`"zero-shot-image-classification"`。

在 [huggingface.co/models](https://huggingface.co/models?filter=zero-shot-image-classification) 上查看可用模型列表。

#### __调用__[[transformers.ZeroShotImageClassificationPipeline.__call__]]

```python
__call__(image: typing.Union[str, list[str], ForwardRef('Image.Image'), list['Image.Image']], candidate_labels: list[str], **kwargs: Any)
```

[来源](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/pipelines/zero_shot_image_classification.py#L83)

**参数：**

image (`str`、`list[str]`、`PIL.Image` 或 `list[PIL.Image]`)：该流水线处理三种类型的图像： - 包含指向图像的 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，则不设置超时，调用可能会永久阻塞。

**返回值：**

一个字典列表，每个建议的标签对应一个条目。每个字典包含以下键：
- **label** (`str`) -- *candidate_labels* 中的一个建议值。
- **score** (`float`) -- 模型分配给该标签的分数。它是一个介于 0 和 1 之间的值，由 `logits_per_image` 的 `softmax` 计算得出。

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

### ZeroShotObjectDetectionPipeline[[transformers.ZeroShotObjectDetectionPipeline]]

#### transformers.ZeroShotObjectDetectionPipeline[[transformers.ZeroShotObjectDetectionPipeline]]

```python
transformers.ZeroShotObjectDetectionPipeline(**kwargs)
```

[来源](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/pipelines/zero_shot_object_detection.py#L23)

**参数：**

model ([PreTrainedModel](/docs/transformers/v5.23.0/zh/main_classes/model#transformers.PreTrainedModel))：流水线用于进行预测的模型。该模型必须继承自 [PreTrainedModel](/docs/transformers/v5.23.0/zh/main_classes/model#transformers.PreTrainedModel)。

image_processor ([BaseImageProcessor](/docs/transformers/v5.23.0/zh/main_classes/image_processor#transformers.BaseImageProcessor))：流水线将使用该图像处理器为模型编码数据。此对象继承自 [BaseImageProcessor](/docs/transformers/v5.23.0/zh/main_classes/image_processor#transformers.BaseImageProcessor)。

task (`str`，默认为 `""`)：用于标识 pipeline 的任务。

num_workers (`int`，*可选*，默认值为 8)：当流水线使用 *DataLoader*（例如传入数据集，或在 GPU 上运行 PyTorch 模型时）时，所使用的 worker 数量。

batch_size (`int`，*可选*，默认为 1)：当流水线使用 *DataLoader*（例如传入数据集，或在 GPU 上运行 PyTorch 模型时）时，所使用的批次大小。对于推理而言，增大批次大小并不总是有益的，请参阅 [使用流水线进行批处理](https://huggingface.co/transformers/main_classes/pipelines.html#pipeline-batching)。

args_parser ([ArgumentHandler](/docs/transformers/v5.23.0/zh/internal/pipelines_utils#transformers.pipelines.ArgumentHandler)，*可选*)：负责解析所提供 pipeline 参数的对象引用。

device (`int` 或 `str` 或 `torch.device`，*可选*)：流水线所分配的设备。若未设置，流水线将放置在第一个可用的加速器（CUDA、MPS、XPU 等）上，仅当没有可用加速器时才回退到 CPU；模型会自动移动至该设备。传入 `device="cpu"`（或 `-1`）可强制使用 CPU，传入正序数或 `"cuda:1"` 可选择特定加速器，或传入原生的 `torch.device`/`str`。此参数不能与已通过 `accelerate` 加载的模型（即具有 `hf_device_map` 的模型）一起使用。

dtype (`str` 或 `torch.dtype`，*可选*，默认为 `"auto"`)：模型加载时使用的精度，会传递给 `from_pretrained`。默认为 `"auto"`，即以模型保存时的 dtype 加载模型（从检查点的 `config.dtype` 读取，否则从权重推断）。传入显式的 `torch.float16`、`torch.bfloat16`、`torch.float32` 等可覆盖该默认值。

binary_output (`bool`，*可选*，默认为 `False`)：一个标志，指示管道输出应采用序列化格式（即 pickle）还是原始输出数据（例如文本）。

使用 `OwlViTForObjectDetection` 的零样本目标检测流水线。当您提供一张图像和一组 `candidate_labels` 时，该流水线会预测目标对象的边界框。

示例：

```python
>>> 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_tutorial) 中了解使用 pipeline 的基础知识。

该目标检测流水线目前可以通过 [pipeline()](/docs/transformers/v5.23.0/zh/main_classes/pipelines#transformers.pipeline) 使用以下任务标识符进行加载：`"zero-shot-object-detection"`。

在 [huggingface.co/models](https://huggingface.co/models?filter=zero-shot-object-detection) 上查看可用模型列表。

#### __调用__[[transformers.ZeroShotObjectDetectionPipeline.__call__]]

```python
__call__(image: typing.Union[str, ForwardRef('Image.Image'), list[dict[str, typing.Any]]], candidate_labels: str | list[str] | None = None, **kwargs: Any)
```

[来源](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/pipelines/zero_shot_object_detection.py#L75)

**参数：**

image (`str`、`PIL.Image` 或 `list[dict[str, Any]]`)：该 pipeline 处理三种类型的图像： - 包含指向图像的 http url 的字符串 - 包含图像本地路径的字符串 - 直接通过 PIL 加载的图像  您可以使用此参数直接发送图像列表，或发送数据集或生成器，例如：  ```python >>> from transformers import pipeline  >>> detector = pipeline(model="google/owlvit-base-patch32", task="zero-shot-object-detection") >>> detector( ...     [ ...         { ...             "image": "http://images.cocodataset.org/val2017/000000039769.jpg", ...             "candidate_labels": ["cat", "couch"], ...         }, ...         { ...             "image": "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.25, '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}}], [{'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}}]] ```

candidate_labels (`str` 或 `list[str]` 或 `list[list[str]]`)：模型应在图像中识别的内容。

threshold (`float`，*可选*，默认值为 0.1)：进行预测所需的概率。

top_k (`int`，*可选*，默认为 None)：流水线将返回的 top 预测数量。如果提供的数值为 `None` 或大于可用的预测数量，则默认返回所有预测。

timeout (`float`, *可选*，默认为 None) : 从网络获取图像时等待的最大时间（秒）。如果为 None，则不设置超时，调用可能会永久阻塞。

**返回值：**

一个列表的列表，包含预测结果，每个输入图像对应一个列表。每个列表包含具有以下键的字典：

- **label** (`str`) -- 与检测到的对象对应的文本查询。
- **score** (`float`) -- 与对象对应的分数（介于 0 和 1 之间）。
- **box** (`dict[str,int]`) -- 检测到的对象在原始图像尺寸下的边界框。它是一个包含 `x_min`、`x_max`、`y_min` 和 `y_max` 键的字典。

检测作为输入传入的图像中的对象（边界框 & 类别）。

## 自然语言处理

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

### DecisionPipeline[[transformers.DecisionPipeline]]

> [!WARNING]
> 决策模型、`decision` 流水线以及 `DecisionConfig` 均为实验性功能：其 API 可能会随时变更，且不会经过弃用流程。

每次调用都会提出其问题：一个请求 `{"state": ..., "questions": ...}`，或一个带有 `questions` 的状态：

```python
from transformers import pipeline

decide = pipeline("decision", model="autotrust/GEV-26B-Decide")
decide(
    {
        "state": "I was charged twice for my order and want a refund.",
        "questions": {"refund": {"type": "noul", "instructions": "Is a refund requested?"}},
    }
)
```

图像以 `assets` 的形式提供，与 System One API 类似：状态、指令或标准中的每个占位符都会被替换为其对应的图像。一个 asset 可以是 `{"type": "image", "format": "png", "data_base64": ...}`、一个 PIL 图像、一个路径或一个 URL，并且模型需要一个能够处理图像的 processor。

```python
decide(
    {
        "state": "The customer sent photo-1 and asks if it is damaged.",
        "assets": {"photo-1": "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/coco_sample.png"},
        "questions": {"damaged": {"type": "noul", "instructions": "Is the product in the photo damaged?"}},
    }
)
```

#### transformers.DecisionPipeline[[transformers.DecisionPipeline]]

```python
transformers.DecisionPipeline(*args, decision_config: transformers.decision.configuration_utils.DecisionConfig | str | None = None, **kwargs)
```

[来源](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/pipelines/decision.py#L15)

**参数：**

model ([PreTrainedModel](/docs/transformers/v5.23.0/zh/main_classes/model#transformers.PreTrainedModel))：流水线用于进行预测的模型。该模型必须继承自 [PreTrainedModel](/docs/transformers/v5.23.0/zh/main_classes/model#transformers.PreTrainedModel)。

tokenizer ([PreTrainedTokenizer](/docs/transformers/v5.23.0/zh/main_classes/tokenizer#transformers.PythonBackend))：流水线将使用该分词器为模型编码数据。此对象继承自 [PreTrainedTokenizer](/docs/transformers/v5.23.0/zh/main_classes/tokenizer#transformers.PythonBackend)。

task (`str`，默认为 `""`)：用于标识 pipeline 的任务。

num_workers (`int`，*可选*，默认值为 8)：当流水线使用 *DataLoader*（例如传入数据集，或在 GPU 上运行 PyTorch 模型时）时，所使用的 worker 数量。

batch_size (`int`，*可选*，默认为 1)：当流水线使用 *DataLoader*（例如传入数据集，或在 GPU 上运行 PyTorch 模型时）时，所使用的批次大小。对于推理而言，增大批次大小并不总是有益的，请参阅 [使用流水线进行批处理](https://huggingface.co/transformers/main_classes/pipelines.html#pipeline-batching)。

args_parser ([ArgumentHandler](/docs/transformers/v5.23.0/zh/internal/pipelines_utils#transformers.pipelines.ArgumentHandler)，*可选*)：负责解析所提供 pipeline 参数的对象引用。

device (`int` 或 `str` 或 `torch.device`，*可选*)：流水线所分配的设备。若未设置，流水线将放置在第一个可用的加速器（CUDA、MPS、XPU 等）上，仅当没有可用加速器时才回退到 CPU；模型会自动移动至该设备。传入 `device="cpu"`（或 `-1`）可强制使用 CPU，传入正序数或 `"cuda:1"` 可选择特定加速器，或传入原生的 `torch.device`/`str`。此参数不能与已通过 `accelerate` 加载的模型（即具有 `hf_device_map` 的模型）一起使用。

dtype (`str` 或 `torch.dtype`，*可选*，默认为 `"auto"`)：模型加载时使用的精度，会传递给 `from_pretrained`。默认为 `"auto"`，即以模型保存时的 dtype 加载模型（从检查点的 `config.dtype` 读取，否则从权重推断）。传入显式的 `torch.float16`、`torch.bfloat16`、`torch.float32` 等可覆盖该默认值。

binary_output (`bool`，*可选*，默认为 `False`)：一个标志，指示管道输出应采用序列化格式（即 pickle）还是原始输出数据（例如文本）。

决策流水线：针对`state`回答类型化问题（`choice`、`score`、`noul`），为每个选项提供概率，每个提示词仅需一次前向传播（即 Jev 类模型的 System One API）。决策配置（参见[DecisionConfig](/docs/transformers/v5.23.0/zh/main_classes/pipelines#transformers.DecisionConfig)）位于模型旁边，或作为`decision_config`给出的仓库中。决策模型（`XxxForDecision`）自行对选项进行评分；其他任何模型则通过其标签的下一个 token 的 logits 来评分，因此任何聊天模型都可以作答。

示例：

```python
>>> from transformers import pipeline

>>> decide = pipeline("decision", model="Qwen/Qwen2.5-0.5B-Instruct")
>>> answers = decide(
...     {
...         "state": "I was charged twice for my order and want a refund.",
...         "questions": {"refund": {"type": "noul", "instructions": "Is a refund requested?"}},
...     }
... )
>>> answers["refund"]["type"]
'noul'
```

调用参数：inputs (`dict`、`str` 或 `list`)：`{"state": ..., "questions": {name: {"type": ..., "instructions": ..., "criteria": ...}}}` 或其 JSON，其中 `type` 为 `choice`（`criteria` 将选项映射到描述）、`score`（`criteria` 列出等级，最低等级在前）或 `noul`（可选的 `criteria` 描述 `true` 和 `false`）。请求可以携带 `assets`，与 System One API 相同。questions (`dict`，*可选*)：要针对输入提出的问题，作为请求的 `state`。assets (`dict`，*可选*)：以占位符为键的图片：只要占位符出现在 state、instructions 或 criteria 的字符串中，模型就会看到该图片。图片可以是 System One 资源（`{"type": "image", "format": "png", "data_base64": ...}`）、PIL 图像、路径或 URL。需要一个具有可处理图像的 processor 的模型。

返回 `dict`（或 `dict` 列表）：以问题名称为键的答案，采用 System One 格式。

#### __调用__[[transformers.DecisionPipeline.__call__]]

```python
__call__(inputs, *args, num_workers = None, batch_size = None, **kwargs)
```

[来源](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/pipelines/base.py#L1239)

#### transformers.DecisionConfig[[transformers.DecisionConfig]]

```python
transformers.DecisionConfig(labels: dict[str, list[str]] = <factory>, temperature: dict[str, float | int] = <factory>, chat_template: str | None = None, noul_options: list[str] = <factory>, sanitize_control_tokens: bool = True, adapter: str | None = None)
```

[来源](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/decision/configuration_utils.py#L30)

**参数：**

labels (`dict[str, list[str]]`, *可选*) : 针对每个问题类型，为从 logits 中读取标签的 head 提供选项的单 token 标签。对于 `noul`，默认值为 `Yes`/`No`；其他情况下，默认值为 `A`、`B`、`C`、...

temperature (`dict[str, float]`, *可选*) : 每种问题类型的温度值，在 softmax 之前应用于选项分数。默认值为 1。

chat_template (`str`, *可选*) : 使用 `question`（每个问题一个提示）或 `questions`（所有问题共用一个提示）来渲染 `state` 的 Jinja 模板。默认使用分词器聊天模板中的通用提示。

noul_options (`list[str]`，*可选*，默认为 `["true", "false"]`)：`noul` 问题中模板接收两个选项的顺序。

sanitize_control_tokens (`bool`，*可选*，默认为 `True`)：请求中的控制标记是否以文本形式编码。自行转义这些标记的模板会将其禁用，以保留其原始代码的输入 ID。

adapter (`str`, *可选*) : 流水线在模型上加载的 LoRA 子文件夹，适用于未将其存放在仓库根目录的仓库。

决策模型的设置，保存为 `decision.json`（其聊天模板保存为 `decision_template.jinja`）。

#### get_logits_processor[[transformers.DecisionConfig.get_logits_processor]]

```python
get_logits_processor(question_type: str)
```

[来源](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/decision/configuration_utils.py#L63)

应用于 `question_type` 类型问题的选项分数的 [LogitsProcessorList](/docs/transformers/v5.23.0/zh/internal/generation_utils#transformers.LogitsProcessorList)。

#### prepare_inputs[[transformers.DecisionConfig.prepare_inputs]]

```python
prepare_inputs(request, processor)
```

[来源](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/decision/configuration_utils.py#L78)

`request` 中每个提示词的标记化 `(inputs, questions)`，参见 `prepare_inputs()`。

#### 验证[[transformers.DecisionConfig.validate]]

```python
validate()
```

[来源](https://github.com/huggingface/transformers/blob/v5.23.0/src/huggingface_hub/dataclasses.py#L247)

在实例上运行类验证器。

### FillMaskPipeline[[transformers.FillMaskPipeline]]

#### transformers.FillMaskPipeline[[transformers.FillMaskPipeline]]

```python
transformers.FillMaskPipeline(model: PreTrainedModel, tokenizer: PreTrainedTokenizer | None = None, feature_extractor: PreTrainedFeatureExtractor | None = None, image_processor: BaseImageProcessor | None = None, video_processor: BaseVideoProcessor | None = None, processor: ProcessorMixin | None = None, task: str = '', device: int | torch.device | None = None, binary_output: bool = False, **kwargs)
```

[来源](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/pipelines/fill_mask.py#L28)

**参数：**

model ([PreTrainedModel](/docs/transformers/v5.23.0/zh/main_classes/model#transformers.PreTrainedModel))：流水线用于进行预测的模型。该模型必须继承自 [PreTrainedModel](/docs/transformers/v5.23.0/zh/main_classes/model#transformers.PreTrainedModel)。

tokenizer ([PreTrainedTokenizer](/docs/transformers/v5.23.0/zh/main_classes/tokenizer#transformers.PythonBackend))：流水线将使用该分词器为模型编码数据。此对象继承自 [PreTrainedTokenizer](/docs/transformers/v5.23.0/zh/main_classes/tokenizer#transformers.PythonBackend)。

task (`str`，默认为 `""`)：用于标识 pipeline 的任务。

num_workers (`int`，*可选*，默认值为 8)：当流水线使用 *DataLoader*（例如传入数据集，或在 GPU 上运行 PyTorch 模型时）时，所使用的 worker 数量。

batch_size (`int`，*可选*，默认为 1)：当流水线使用 *DataLoader*（例如传入数据集，或在 GPU 上运行 PyTorch 模型时）时，所使用的批次大小。对于推理而言，增大批次大小并不总是有益的，请参阅 [使用流水线进行批处理](https://huggingface.co/transformers/main_classes/pipelines.html#pipeline-batching)。

args_parser ([ArgumentHandler](/docs/transformers/v5.23.0/zh/internal/pipelines_utils#transformers.pipelines.ArgumentHandler)，*可选*)：负责解析所提供 pipeline 参数的对象引用。

device (`int` 或 `str` 或 `torch.device`，*可选*)：流水线所分配的设备。若未设置，流水线将放置在第一个可用的加速器（CUDA、MPS、XPU 等）上，仅当没有可用加速器时才回退到 CPU；模型会自动移动至该设备。传入 `device="cpu"`（或 `-1`）可强制使用 CPU，传入正序数或 `"cuda:1"` 可选择特定加速器，或传入原生的 `torch.device`/`str`。此参数不能与已通过 `accelerate` 加载的模型（即具有 `hf_device_map` 的模型）一起使用。

dtype (`str` 或 `torch.dtype`，*可选*，默认为 `"auto"`)：模型加载时使用的精度，会传递给 `from_pretrained`。默认为 `"auto"`，即以模型保存时的 dtype 加载模型（从检查点的 `config.dtype` 读取，否则从权重推断）。传入显式的 `torch.float16`、`torch.bfloat16`、`torch.float32` 等可覆盖该默认值。

binary_output (`bool`，*可选*，默认为 `False`)：一个标志，指示管道输出应采用序列化格式（即 pickle）还是原始输出数据（例如文本）。

top_k (`int`，*可选*，默认为 5)：要返回的预测数量。

targets (`str` 或 `list[str]`，*可选*) : 传入该参数时，模型会将分数限制在传入的目标范围内，而不是在整个词表中查找。如果提供的目标不在模型词表中，它们将被分词，并使用生成的第一个 token（会发出警告，且速度可能较慢）。

tokenizer_kwargs (`dict`, *可选*) : 传递给分词器的额外关键字参数字典。

#### __调用__[[transformers.FillMaskPipeline.__call__]]

```python
__call__(inputs: str | list[str], **kwargs: Any)
```

[来源](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/pipelines/fill_mask.py#L234)

**参数：**

inputs (`str` 或 `list[str]`)：一个或多个包含掩码标记的文本（或一个提示词列表）。

targets (`str` 或 `list[str]`，*可选*) : 传入该参数时，模型会将分数限制在传入的目标范围内，而不是在整个词表中查找。如果提供的目标不在模型词表中，它们将被分词，并使用生成的第一个 token（会发出警告，且速度可能较慢）。

top_k (`int`, *可选*) : 传入时，将覆盖要返回的预测数量。

**返回：** 一个 `dict` 列表或 `dict` 列表的列表

每个结果都以字典列表的形式返回，包含以下键：

- **sequence** (`str`) -- 带有掩码标记预测的对应输入。
- **score** (`float`) -- 对应的概率。
- **token** (`int`) -- 预测的 token id（用于替换被掩码的 token）。
- **token_str** (`str`) -- 预测的 token（用于替换被掩码的 token）。

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

### TableQuestionAnsweringPipeline[[transformers.TableQuestionAnsweringPipeline]]

#### transformers.TableQuestionAnsweringPipeline[[transformers.TableQuestionAnsweringPipeline]]

```python
transformers.TableQuestionAnsweringPipeline(args_parser = <transformers.pipelines.table_question_answering.TableQuestionAnsweringArgumentHandler object at 0x7f3f9e868a90>, **kwargs)
```

[来源](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/pipelines/table_question_answering.py#L78)

**参数：**

model ([PreTrainedModel](/docs/transformers/v5.23.0/zh/main_classes/model#transformers.PreTrainedModel))：流水线用于进行预测的模型。该模型必须继承自 [PreTrainedModel](/docs/transformers/v5.23.0/zh/main_classes/model#transformers.PreTrainedModel)。

tokenizer ([PreTrainedTokenizer](/docs/transformers/v5.23.0/zh/main_classes/tokenizer#transformers.PythonBackend))：流水线将使用该分词器为模型编码数据。此对象继承自 [PreTrainedTokenizer](/docs/transformers/v5.23.0/zh/main_classes/tokenizer#transformers.PythonBackend)。

task (`str`，默认为 `""`)：用于标识 pipeline 的任务。

num_workers (`int`，*可选*，默认值为 8)：当流水线使用 *DataLoader*（例如传入数据集，或在 GPU 上运行 PyTorch 模型时）时，所使用的 worker 数量。

batch_size (`int`，*可选*，默认为 1)：当流水线使用 *DataLoader*（例如传入数据集，或在 GPU 上运行 PyTorch 模型时）时，所使用的批次大小。对于推理而言，增大批次大小并不总是有益的，请参阅 [使用流水线进行批处理](https://huggingface.co/transformers/main_classes/pipelines.html#pipeline-batching)。

args_parser ([ArgumentHandler](/docs/transformers/v5.23.0/zh/internal/pipelines_utils#transformers.pipelines.ArgumentHandler)，*可选*)：负责解析所提供 pipeline 参数的对象引用。

device (`int` 或 `str` 或 `torch.device`，*可选*)：流水线所分配的设备。若未设置，流水线将放置在第一个可用的加速器（CUDA、MPS、XPU 等）上，仅当没有可用加速器时才回退到 CPU；模型会自动移动至该设备。传入 `device="cpu"`（或 `-1`）可强制使用 CPU，传入正序数或 `"cuda:1"` 可选择特定加速器，或传入原生的 `torch.device`/`str`。此参数不能与已通过 `accelerate` 加载的模型（即具有 `hf_device_map` 的模型）一起使用。

dtype (`str` 或 `torch.dtype`，*可选*，默认为 `"auto"`)：模型加载时使用的精度，会传递给 `from_pretrained`。默认为 `"auto"`，即以模型保存时的 dtype 加载模型（从检查点的 `config.dtype` 读取，否则从权重推断）。传入显式的 `torch.float16`、`torch.bfloat16`、`torch.float32` 等可覆盖该默认值。

binary_output (`bool`，*可选*，默认为 `False`)：一个标志，指示管道输出应采用序列化格式（即 pickle）还是原始输出数据（例如文本）。

使用 `ModelForTableQuestionAnswering` 的表格问答流水线。此流水线仅在 PyTorch 中可用。

除非您使用的模型在其配置文件（`generation_config.json`）中明确设置了这些生成参数，否则将使用以下默认值：
- max_new_tokens: 256

示例：

```python
>>> 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_tutorial) 中了解使用 pipeline 的基础知识。

该表格问答流水线目前可以通过 [pipeline()](/docs/transformers/v5.23.0/zh/main_classes/pipelines#transformers.pipeline) 使用以下任务标识符进行加载：`"table-question-answering"`。

该流水线可使用的模型是在表格问答任务上经过微调的模型。有关可用模型的最新列表，请参阅 [huggingface.co/models](https://huggingface.co/models?filter=table-question-answering)。

#### __调用__[[transformers.TableQuestionAnsweringPipeline.__call__]]

```python
__call__(*args, **kwargs)
```

[来源](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/pipelines/table_question_answering.py#L208)

**参数：**

table (`pd.DataFrame` 或 `Dict`)：Pandas DataFrame 或字典，将被转换为包含所有表格值的 DataFrame。字典示例见上文。

query (`str` 或 `list[str]`) : 将与表格一起发送给模型的查询或查询列表。

sequential (`bool`，*可选*，默认为 `False`)：是否按顺序执行推理，还是作为批次执行。批次推理速度更快，但像 SQA 这样的模型由于其对话性质，需要按顺序执行推理才能提取序列内的关系。

padding (`bool`、`str` 或 [PaddingStrategy](/docs/transformers/v5.23.0/zh/internal/file_utils#transformers.utils.PaddingStrategy)，*可选*，默认为 `False`)：启用并控制填充。接受以下值： - `True` 或 `'longest'`：填充至批次中最长的序列（如果仅提供单个序列，则不进行填充）。 - `'max_length'`：填充至由参数 `max_length` 指定的最大长度，或者如果未提供该参数，则填充至模型可接受的最大输入长度。 - `False` 或 `'do_not_pad'`（默认值）：不进行填充（即可以输出包含不同长度序列的批次）。

truncation (`bool`、`str` 或 `TapasTruncationStrategy`，*可选*，默认为 `False`)：启用并控制截断。接受以下值： - `True` 或 `'drop_rows_to_fit'`：截断至由参数 `max_length` 指定的最大长度，或者如果未提供该参数，则截断至模型可接受的最大输入长度。这将逐行进行截断，从表格中移除行。 - `False` 或 `'do_not_truncate'`（默认）：不截断（即，可以输出序列长度超过模型最大可接受输入大小的批次）。

**返回：** `A dictionary or a list of dictionaries containing results`

每个结果都是一个字典，包含以下键：

- **answer** (`str`) -- 基于表格给出的查询答案。如果存在聚合器，答案前会带有 `AGGREGATOR >`。
- **coordinates** (`list[tuple[int, int]]`) -- 答案单元格的坐标。
- **cells** (`list[str]`) -- 由答案单元格值组成的字符串列表。
- **aggregator** (`str`) -- 如果模型包含 aggregator，则返回该 aggregator。

根据表格回答查询。该流水线接受多种类型的输入，详细说明如下：

- `pipeline(table, query)`
- `pipeline(table, [query])`
- `pipeline(table=table, query=query)`
- `pipeline(table=table, query=[query])`
- `pipeline({"table": table, "query": query})`
- `pipeline({"table": table, "query": [query]})`
- `pipeline([{"table": table, "query": query}, {"table": table, "query": query}])`

`table` 参数应为一个字典，或基于该字典构建的 DataFrame，其中包含完整的表格：

示例：

```python
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：

示例：

```python
import pandas as pd

table = pd.DataFrame.from_dict(data)
```

### TextClassificationPipeline[[transformers.TextClassificationPipeline]]

#### transformers.TextClassificationPipeline[[transformers.TextClassificationPipeline]]

```python
transformers.TextClassificationPipeline(**kwargs)
```

[来源](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/pipelines/text_classification.py#L43)

**参数：**

model ([PreTrainedModel](/docs/transformers/v5.23.0/zh/main_classes/model#transformers.PreTrainedModel))：流水线用于进行预测的模型。该模型必须继承自 [PreTrainedModel](/docs/transformers/v5.23.0/zh/main_classes/model#transformers.PreTrainedModel)。

tokenizer ([PreTrainedTokenizer](/docs/transformers/v5.23.0/zh/main_classes/tokenizer#transformers.PythonBackend))：流水线将使用该分词器为模型编码数据。此对象继承自 [PreTrainedTokenizer](/docs/transformers/v5.23.0/zh/main_classes/tokenizer#transformers.PythonBackend)。

task (`str`，默认为 `""`)：用于标识 pipeline 的任务。

num_workers (`int`，*可选*，默认值为 8)：当流水线使用 *DataLoader*（例如传入数据集，或在 GPU 上运行 PyTorch 模型时）时，所使用的 worker 数量。

batch_size (`int`，*可选*，默认为 1)：当流水线使用 *DataLoader*（例如传入数据集，或在 GPU 上运行 PyTorch 模型时）时，所使用的批次大小。对于推理而言，增大批次大小并不总是有益的，请参阅 [使用流水线进行批处理](https://huggingface.co/transformers/main_classes/pipelines.html#pipeline-batching)。

args_parser ([ArgumentHandler](/docs/transformers/v5.23.0/zh/internal/pipelines_utils#transformers.pipelines.ArgumentHandler)，*可选*)：负责解析所提供 pipeline 参数的对象引用。

device (`int` 或 `str` 或 `torch.device`，*可选*)：流水线所分配的设备。若未设置，流水线将放置在第一个可用的加速器（CUDA、MPS、XPU 等）上，仅当没有可用加速器时才回退到 CPU；模型会自动移动至该设备。传入 `device="cpu"`（或 `-1`）可强制使用 CPU，传入正序数或 `"cuda:1"` 可选择特定加速器，或传入原生的 `torch.device`/`str`。此参数不能与已通过 `accelerate` 加载的模型（即具有 `hf_device_map` 的模型）一起使用。

dtype (`str` 或 `torch.dtype`，*可选*，默认为 `"auto"`)：模型加载时使用的精度，会传递给 `from_pretrained`。默认为 `"auto"`，即以模型保存时的 dtype 加载模型（从检查点的 `config.dtype` 读取，否则从权重推断）。传入显式的 `torch.float16`、`torch.bfloat16`、`torch.float32` 等可覆盖该默认值。

binary_output (`bool`，*可选*，默认为 `False`)：一个标志，指示管道输出应采用序列化格式（即 pickle）还是原始输出数据（例如文本）。

function_to_apply (`str`，*可选*，默认为 `"default"`)：用于处理模型输出以获取分数的函数。接受以下四种不同的值： - `"default"`：如果模型只有一个标签，则对输出应用 sigmoid 函数。如果模型有多个标签，则对输出应用 softmax 函数。对于回归任务，则不对输出应用任何函数。 - `"sigmoid"`：对输出应用 sigmoid 函数。 - `"softmax"`：对输出应用 softmax 函数。 - `"none"`：不对输出应用任何函数。

使用任意 `ModelForSequenceClassification` 的文本分类流水线。有关更多信息，请参阅 [序列分类示例](../task_summary#sequence-classification)。

示例：

```python
>>> 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_tutorial) 中了解使用 pipeline 的基础知识。

该文本分类流水线目前可以通过 [pipeline()](/docs/transformers/v5.23.0/zh/main_classes/pipelines#transformers.pipeline) 使用以下任务标识符进行加载：`"sentiment-analysis"`（用于根据正面或负面情绪对序列进行分类）。

如果存在多个分类标签（`model.config.num_labels >= 2`），pipeline 将对结果执行 softmax。如果只有一个标签，pipeline 将对结果执行 sigmoid。对于回归任务（`model.config.problem_type == "regression"`），则不会对输出应用任何函数。

该流水线可使用的模型是在序列分类任务上经过微调的模型。有关可用模型的最新列表，请参阅 [huggingface.co/models](https://huggingface.co/models?filter=text-classification)。

#### __调用__[[transformers.TextClassificationPipeline.__call__]]

```python
__call__(inputs: str | list[str] | dict[str, str] | list[dict[str, str]], **kwargs: Any)
```

[来源](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/pipelines/text_classification.py#L105)

**参数：**

inputs (`str` 或 `list[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[[transformers.TextGenerationPipeline]]

#### transformers.TextGenerationPipeline[[transformers.TextGenerationPipeline]]

```python
transformers.TextGenerationPipeline(*args, **kwargs)
```

[来源](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/pipelines/text_generation.py#L23)

**参数：**

model ([PreTrainedModel](/docs/transformers/v5.23.0/zh/main_classes/model#transformers.PreTrainedModel))：流水线用于进行预测的模型。该模型必须继承自 [PreTrainedModel](/docs/transformers/v5.23.0/zh/main_classes/model#transformers.PreTrainedModel)。

tokenizer ([PreTrainedTokenizer](/docs/transformers/v5.23.0/zh/main_classes/tokenizer#transformers.PythonBackend))：流水线将使用该分词器为模型编码数据。此对象继承自 [PreTrainedTokenizer](/docs/transformers/v5.23.0/zh/main_classes/tokenizer#transformers.PythonBackend)。

task (`str`，默认为 `""`)：用于标识 pipeline 的任务。

num_workers (`int`，*可选*，默认值为 8)：当流水线使用 *DataLoader*（例如传入数据集，或在 GPU 上运行 PyTorch 模型时）时，所使用的 worker 数量。

batch_size (`int`，*可选*，默认为 1)：当流水线使用 *DataLoader*（例如传入数据集，或在 GPU 上运行 PyTorch 模型时）时，所使用的批次大小。对于推理而言，增大批次大小并不总是有益的，请参阅 [使用流水线进行批处理](https://huggingface.co/transformers/main_classes/pipelines.html#pipeline-batching)。

args_parser ([ArgumentHandler](/docs/transformers/v5.23.0/zh/internal/pipelines_utils#transformers.pipelines.ArgumentHandler)，*可选*)：负责解析所提供 pipeline 参数的对象引用。

device (`int` 或 `str` 或 `torch.device`，*可选*)：流水线所分配的设备。若未设置，流水线将放置在第一个可用的加速器（CUDA、MPS、XPU 等）上，仅当没有可用加速器时才回退到 CPU；模型会自动移动至该设备。传入 `device="cpu"`（或 `-1`）可强制使用 CPU，传入正序数或 `"cuda:1"` 可选择特定加速器，或传入原生的 `torch.device`/`str`。此参数不能与已通过 `accelerate` 加载的模型（即具有 `hf_device_map` 的模型）一起使用。

dtype (`str` 或 `torch.dtype`，*可选*，默认为 `"auto"`)：模型加载时使用的精度，会传递给 `from_pretrained`。默认为 `"auto"`，即以模型保存时的 dtype 加载模型（从检查点的 `config.dtype` 读取，否则从权重推断）。传入显式的 `torch.float16`、`torch.bfloat16`、`torch.float32` 等可覆盖该默认值。

binary_output (`bool`，*可选*，默认为 `False`)：一个标志，指示管道输出应采用序列化格式（即 pickle）还是原始输出数据（例如文本）。

使用任意 `ModelWithLMHead` 或 `ModelForCausalLM` 的语言生成流水线。该流水线用于预测将跟随在指定文本提示之后的词语。当底层模型为对话模型时，它还可以接受一个或多个聊天，此时流水线将以聊天模式运行，并通过添加其回复来继续这些聊天。每个聊天的形式是一个字典列表，其中每个字典包含 "role" 和 "content" 键。

除非您使用的模型在其配置文件（`generation_config.json`）中明确设置了这些生成参数，否则将使用以下默认值：
- max_new_tokens: 256
- do_sample: True
- temperature: 0.7

示例：

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

```python
>>> 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 的基础知识，请参阅 [pipeline 教程](../pipeline_tutorial)。您可以向此 pipeline 传入文本生成参数，以控制停止条件、解码策略等。有关文本生成参数的详细信息，请参阅 [文本生成策略](../generation_strategies) 和 [文本生成](text_generation)。

该语言生成流水线目前可以通过 [pipeline()](/docs/transformers/v5.23.0/zh/main_classes/pipelines#transformers.pipeline) 使用以下任务标识符进行加载：`"text-generation"`。

该流水线可使用的模型是采用自回归语言建模目标进行训练的模型。请参阅 [huggingface.co/models] 上可用的 [文本补全模型](https://huggingface.co/models?filter=text-generation) 列表和 [对话模型](https://huggingface.co/models?other=conversational) 列表。

#### __调用__[[transformers.TextGenerationPipeline.__call__]]

```python
__call__(text_inputs, **kwargs)
```

[来源](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/pipelines/text_generation.py#L253)

**参数：**

text_inputs (`str`、`list[str]`、`ChatType` 或 `list[ChatType]`)：一个或多个待补全的提示词（或一个提示词列表）。如果传入的是字符串或字符串列表，该流水线将对每个提示词进行续写。或者，也可以传入以字典列表形式表示的“chat”，其中每个字典包含 "role" 和 "content" 键；也可以传入此类 chat 的列表。当传入 chat 时，模型将使用其 chat 模板对其进行格式化，然后再传递给模型。

return_tensors (`bool`，*可选*，默认为 `False`)：在输出中返回预测张量（以 token 索引形式）。如果设置为 `True`，则不会返回解码后的文本。

return_text (`bool`，*可选*)：返回输出中的解码文本。

return_full_text (`bool`，*可选*，默认为 `True`)：如果设置为 `False`，则仅返回新增的文本；否则返回完整文本。不能与 `return_text` 同时指定。

clean_up_tokenization_spaces (`bool`, *可选*) : 是否清理文本输出中可能存在的多余空格。默认使用分词器的 `clean_up_tokenization_spaces` 设置。

continue_final_message( `bool`, *可选*)：此参数表示你希望模型继续输入对话中的最后一条消息，而不是开始一条新消息，从而允许你“预填充”其回复。默认情况下，当输入对话中的最后一条消息具有 `assistant` 角色时，此值为 `True`，否则为 `False`，但你可以通过设置此标志来手动覆盖该行为。

prefix (`str`，*可选*)：添加到提示词的前缀。

stop_sequence (`str` 或 `list[str]`，*可选*)：一个或多个字符串，生成到这些字符串时停止生成。停止字符串会包含在输出中。

handle_long_generation (`str`, *可选*) : 默认情况下，此 pipeline 不处理长文本生成（即以任何形式超出模型最大长度的生成）。目前尚无完美的解决方案（更多信息：https://github.com/huggingface/transformers/issues/14033#issuecomment-948385227）。该参数提供了常见的策略，以便根据您的使用场景规避此问题。 - `None` : 默认策略，即不执行任何特殊操作 - `"hole"`：截断输入的左侧，并留出足够宽的空隙以进行生成（可能会截断大量提示词，且当生成内容超出模型容量时不适用）

tokenizer_encode_kwargs (`dict`, *可选*) : 传递给分词器编码步骤的额外关键字参数。如果文本输入是聊天，则会传递给 `apply_chat_template`。否则，会传递给 `__call__`。

generate_kwargs (`dict`, *可选*) : 传递给模型 generate 方法的额外关键字参数（参见 [此处](./text_generation) 的 generate 方法）。

**返回：** 一个 `dict` 列表或 `dict` 列表的列表

返回以下字典之一（不能同时返回 `generated_text` 和 `generated_token_ids`）：

- **generated_text**（`str`，当 `return_text=True` 时存在）-- 生成的文本。
- **generated_token_ids**（`torch.Tensor`，当 `return_tensors=True` 时存在）—— 生成文本的 token id。

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

### TokenClassificationPipeline[[transformers.TokenClassificationPipeline]]

#### transformers.TokenClassificationPipeline[[transformers.TokenClassificationPipeline]]

```python
transformers.TokenClassificationPipeline(args_parser = <transformers.pipelines.token_classification.TokenClassificationArgumentHandler object at 0x7f3f9e9c17d0>, **kwargs)
```

[来源](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/pipelines/token_classification.py#L91)

**参数：**

model ([PreTrainedModel](/docs/transformers/v5.23.0/zh/main_classes/model#transformers.PreTrainedModel))：流水线用于进行预测的模型。该模型必须继承自 [PreTrainedModel](/docs/transformers/v5.23.0/zh/main_classes/model#transformers.PreTrainedModel)。

tokenizer ([PreTrainedTokenizer](/docs/transformers/v5.23.0/zh/main_classes/tokenizer#transformers.PythonBackend))：流水线将使用该分词器为模型编码数据。此对象继承自 [PreTrainedTokenizer](/docs/transformers/v5.23.0/zh/main_classes/tokenizer#transformers.PythonBackend)。

task (`str`，默认为 `""`)：用于标识 pipeline 的任务。

num_workers (`int`，*可选*，默认值为 8)：当流水线使用 *DataLoader*（例如传入数据集，或在 GPU 上运行 PyTorch 模型时）时，所使用的 worker 数量。

batch_size (`int`，*可选*，默认为 1)：当流水线使用 *DataLoader*（例如传入数据集，或在 GPU 上运行 PyTorch 模型时）时，所使用的批次大小。对于推理而言，增大批次大小并不总是有益的，请参阅 [使用流水线进行批处理](https://huggingface.co/transformers/main_classes/pipelines.html#pipeline-batching)。

args_parser ([ArgumentHandler](/docs/transformers/v5.23.0/zh/internal/pipelines_utils#transformers.pipelines.ArgumentHandler)，*可选*)：负责解析所提供 pipeline 参数的对象引用。

device (`int` 或 `str` 或 `torch.device`，*可选*)：流水线所分配的设备。若未设置，流水线将放置在第一个可用的加速器（CUDA、MPS、XPU 等）上，仅当没有可用加速器时才回退到 CPU；模型会自动移动至该设备。传入 `device="cpu"`（或 `-1`）可强制使用 CPU，传入正序数或 `"cuda:1"` 可选择特定加速器，或传入原生的 `torch.device`/`str`。此参数不能与已通过 `accelerate` 加载的模型（即具有 `hf_device_map` 的模型）一起使用。

dtype (`str` 或 `torch.dtype`，*可选*，默认为 `"auto"`)：模型加载时使用的精度，会传递给 `from_pretrained`。默认为 `"auto"`，即以模型保存时的 dtype 加载模型（从检查点的 `config.dtype` 读取，否则从权重推断）。传入显式的 `torch.float16`、`torch.bfloat16`、`torch.float32` 等可覆盖该默认值。

binary_output (`bool`，*可选*，默认为 `False`)：一个标志，指示管道输出应采用序列化格式（即 pickle）还是原始输出数据（例如文本）。

ignore_labels (`list[str]`，默认为 `["O"]`)：要忽略的标签列表。

stride (`int`, *optional*) : 如果提供了 stride，则流水线将应用于所有文本。文本会被拆分为大小为 model_max_length 的块。仅适用于快速分词器且 `aggregation_strategy` 不同于 `NONE` 的情况。此参数的值定义了块之间重叠的 token 数量。换句话说，模型在每一步会向前移动 `tokenizer.model_max_length - stride` 个 token。

aggregation_strategy (`str`, *可选*，默认为 `"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` 的命名实体识别流水线。有关更多信息，请参阅 [命名实体识别示例](../task_summary#named-entity-recognition)。

示例：

```python
>>> 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_tutorial) 中了解使用 pipeline 的基础知识。

该 token 识别流水线目前可以通过 [pipeline()](/docs/transformers/v5.23.0/zh/main_classes/pipelines#transformers.pipeline) 使用以下任务标识符进行加载：`"ner"`（用于预测序列中 token 的类别：人物、组织、地点或其他）。

该流水线可使用的模型是在 token 分类任务上经过微调的模型。有关可用模型的最新列表，请参阅 [huggingface.co/models](https://huggingface.co/models?filter=token-classification)。

#### __调用__[[transformers.TokenClassificationPipeline.__call__]]

```python
__call__(inputs: str | list[str], **kwargs: Any)
```

[来源](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/pipelines/token_classification.py#L210)

**参数：**

inputs (`str` 或 `List[str]`)：用于文本分类的一个或多个文本（或一个文本列表）。当 `is_split_into_words=True` 时，可以是预先分词的。

**返回：** 一个 `dict` 列表或 `dict` 列表的列表

每个结果都以字典列表的形式返回（对应输入中的每个 token，或者如果该流水线实例化时指定了 aggregation_strategy，则对应每个实体），包含以下键：

- **word** (`str`) -- 被分类的 token/单词。该值通过对选中的 token 进行解码获得。如果您需要原始句子中的精确字符串，请使用 `start` 和 `end`。
- **score** (`float`) -- `entity` 对应的概率。
- **entity** (`str`) -- 为该 token/单词预测的实体（当 *aggregation_strategy* 不是 `"none"` 时，其名称为 *entity_group*）。
- **index**（`int`，仅在 `aggregation_strategy="none"` 时存在）-- 对应 token 在句子中的索引。
- **start** (`int`，*可选*) -- 对应实体在句子中起始位置的索引。仅当分词器中可用偏移量时存在
- **end** (`int`, *可选*) -- 对应实体在句子中结束位置的索引。仅当分词器中可用偏移量时存在

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

#### aggregate_words[[transformers.TokenClassificationPipeline.aggregate_words]]

```python
aggregate_words(entities: list[dict], aggregation_strategy: AggregationStrategy)
```

[来源](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/pipelines/token_classification.py#L522)

覆盖来自给定单词的冲突标记，以强制在单词边界处达成一致。

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

#### gather_pre_entities[[transformers.TokenClassificationPipeline.gather_pre_entities]]

```python
gather_pre_entities(sentence: str, input_ids: ndarray, scores: ndarray, offset_mapping: list[tuple[int, int]] | None, special_tokens_mask: ndarray, aggregation_strategy: AggregationStrategy, word_ids: list[int | None] | None = None, word_to_chars_map: list[tuple[int, int]] | None = None)
```

[来源](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/pipelines/token_classification.py#L398)

将多个 numpy 数组融合为字典，其中包含聚合所需的所有信息

#### group_entities[[transformers.TokenClassificationPipeline.group_entities]]

```python
group_entities(entities: list[dict])
```

[来源](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/pipelines/token_classification.py#L585)

**参数：**

entities (`dict`)：流水线预测的实体。

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

#### group_sub_entities[[transformers.TokenClassificationPipeline.group_sub_entities]]

```python
group_sub_entities(entities: list[dict])
```

[来源](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/pipelines/token_classification.py#L550)

**参数：**

entities (`dict`)：流水线预测的实体。

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

### ZeroShotClassificationPipeline[[transformers.ZeroShotClassificationPipeline]]

#### transformers.ZeroShotClassificationPipeline[[transformers.ZeroShotClassificationPipeline]]

```python
transformers.ZeroShotClassificationPipeline(args_parser = <transformers.pipelines.zero_shot_classification.ZeroShotClassificationArgumentHandler object at 0x7f3f9e15ff50>, **kwargs)
```

[来源](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/pipelines/zero_shot_classification.py#L44)

**参数：**

model ([PreTrainedModel](/docs/transformers/v5.23.0/zh/main_classes/model#transformers.PreTrainedModel))：流水线用于进行预测的模型。该模型必须继承自 [PreTrainedModel](/docs/transformers/v5.23.0/zh/main_classes/model#transformers.PreTrainedModel)。

tokenizer ([PreTrainedTokenizer](/docs/transformers/v5.23.0/zh/main_classes/tokenizer#transformers.PythonBackend))：流水线将使用该分词器为模型编码数据。此对象继承自 [PreTrainedTokenizer](/docs/transformers/v5.23.0/zh/main_classes/tokenizer#transformers.PythonBackend)。

task (`str`，默认为 `""`)：用于标识 pipeline 的任务。

num_workers (`int`，*可选*，默认值为 8)：当流水线使用 *DataLoader*（例如传入数据集，或在 GPU 上运行 PyTorch 模型时）时，所使用的 worker 数量。

batch_size (`int`，*可选*，默认为 1)：当流水线使用 *DataLoader*（例如传入数据集，或在 GPU 上运行 PyTorch 模型时）时，所使用的批次大小。对于推理而言，增大批次大小并不总是有益的，请参阅 [使用流水线进行批处理](https://huggingface.co/transformers/main_classes/pipelines.html#pipeline-batching)。

args_parser ([ArgumentHandler](/docs/transformers/v5.23.0/zh/internal/pipelines_utils#transformers.pipelines.ArgumentHandler)，*可选*)：负责解析所提供 pipeline 参数的对象引用。

device (`int` 或 `str` 或 `torch.device`，*可选*)：流水线所分配的设备。若未设置，流水线将放置在第一个可用的加速器（CUDA、MPS、XPU 等）上，仅当没有可用加速器时才回退到 CPU；模型会自动移动至该设备。传入 `device="cpu"`（或 `-1`）可强制使用 CPU，传入正序数或 `"cuda:1"` 可选择特定加速器，或传入原生的 `torch.device`/`str`。此参数不能与已通过 `accelerate` 加载的模型（即具有 `hf_device_map` 的模型）一起使用。

dtype (`str` 或 `torch.dtype`，*可选*，默认为 `"auto"`)：模型加载时使用的精度，会传递给 `from_pretrained`。默认为 `"auto"`，即以模型保存时的 dtype 加载模型（从检查点的 `config.dtype` 读取，否则从权重推断）。传入显式的 `torch.float16`、`torch.bfloat16`、`torch.float32` 等可覆盖该默认值。

binary_output (`bool`，*可选*，默认为 `False`)：一个标志，指示管道输出应采用序列化格式（即 pickle）还是原始输出数据（例如文本）。

基于 NLI 的零样本分类流水线，使用在 NLI（自然语言推理）任务上训练的 `ModelForSequenceClassification`。其功能等同于 `text-classification` 流水线，但这些模型不需要预先硬编码潜在类别的数量，可以在运行时动态指定。这通常意味着速度较慢，但灵活性要 **高得多**。

可以传入任意序列和标签的组合，每个组合都会作为前提/假设对传入预训练模型。随后，*entailment* 的 logit 将被用作候选标签有效的 logit。可以使用任何 NLI 模型，但模型配置中的 :attr:*~transformers.PreTrainedConfig.label2id* 必须包含 *entailment* 标签的 id。

示例：

```python
>>> 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_tutorial) 中了解使用 pipeline 的基础知识。

当前，此 NLI 流水线可以通过 [pipeline()](/docs/transformers/v5.23.0/zh/main_classes/pipelines#transformers.pipeline) 使用以下任务标识符进行加载：`"zero-shot-classification"`。

该流水线可使用的模型是在 NLI 任务上经过微调的模型。有关可用模型的最新列表，请参阅 [huggingface.co/models](https://huggingface.co/models?search=nli)。

#### __调用__[[transformers.ZeroShotClassificationPipeline.__call__]]

```python
__call__(sequences: str | list[str], *args, **kwargs)
```

[来源](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/pipelines/zero_shot_classification.py#L159)

**参数：**

sequences (`str` 或 `list[str]`)：要分类的序列，如果模型输入过大，将被截断。

candidate_labels (`str` 或 `list[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](/docs/transformers/v5.23.0/zh/main_classes/pipelines#transformers.ZeroShotClassificationPipeline) 文档。

## 多模态

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

### DocumentQuestionAnsweringPipeline[[transformers.DocumentQuestionAnsweringPipeline]]

#### transformers.DocumentQuestionAnsweringPipeline[[transformers.DocumentQuestionAnsweringPipeline]]

```python
transformers.DocumentQuestionAnsweringPipeline(*args, **kwargs)
```

[来源](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/pipelines/document_question_answering.py#L206)

**参数：**

model ([PreTrainedModel](/docs/transformers/v5.23.0/zh/main_classes/model#transformers.PreTrainedModel))：流水线用于进行预测的模型。该模型必须继承自 [PreTrainedModel](/docs/transformers/v5.23.0/zh/main_classes/model#transformers.PreTrainedModel)。

tokenizer ([PreTrainedTokenizer](/docs/transformers/v5.23.0/zh/main_classes/tokenizer#transformers.PythonBackend))：流水线将使用该分词器为模型编码数据。此对象继承自 [PreTrainedTokenizer](/docs/transformers/v5.23.0/zh/main_classes/tokenizer#transformers.PythonBackend)。

image_processor ([BaseImageProcessor](/docs/transformers/v5.23.0/zh/main_classes/image_processor#transformers.BaseImageProcessor))：流水线将使用该图像处理器为模型编码数据。此对象继承自 [BaseImageProcessor](/docs/transformers/v5.23.0/zh/main_classes/image_processor#transformers.BaseImageProcessor)。

task (`str`，默认为 `""`)：用于标识 pipeline 的任务。

num_workers (`int`，*可选*，默认值为 8)：当流水线使用 *DataLoader*（例如传入数据集，或在 GPU 上运行 PyTorch 模型时）时，所使用的 worker 数量。

batch_size (`int`，*可选*，默认为 1)：当流水线使用 *DataLoader*（例如传入数据集，或在 GPU 上运行 PyTorch 模型时）时，所使用的批次大小。对于推理而言，增大批次大小并不总是有益的，请参阅 [使用流水线进行批处理](https://huggingface.co/transformers/main_classes/pipelines.html#pipeline-batching)。

args_parser ([ArgumentHandler](/docs/transformers/v5.23.0/zh/internal/pipelines_utils#transformers.pipelines.ArgumentHandler)，*可选*)：负责解析所提供 pipeline 参数的对象引用。

device (`int` 或 `str` 或 `torch.device`，*可选*)：流水线所分配的设备。若未设置，流水线将放置在第一个可用的加速器（CUDA、MPS、XPU 等）上，仅当没有可用加速器时才回退到 CPU；模型会自动移动至该设备。传入 `device="cpu"`（或 `-1`）可强制使用 CPU，传入正序数或 `"cuda:1"` 可选择特定加速器，或传入原生的 `torch.device`/`str`。此参数不能与已通过 `accelerate` 加载的模型（即具有 `hf_device_map` 的模型）一起使用。

dtype (`str` 或 `torch.dtype`，*可选*，默认为 `"auto"`)：模型加载时使用的精度，会传递给 `from_pretrained`。默认为 `"auto"`，即以模型保存时的 dtype 加载模型（从检查点的 `config.dtype` 读取，否则从权重推断）。传入显式的 `torch.float16`、`torch.bfloat16`、`torch.float32` 等可覆盖该默认值。

binary_output (`bool`，*可选*，默认为 `False`)：一个标志，指示管道输出应采用序列化格式（即 pickle）还是原始输出数据（例如文本）。

使用任意 `AutoModelForDocumentQuestionAnswering` 的文档问答流水线。其输入/输出与（抽取式）问答流水线类似；不过，该流水线的输入是图像（以及可选的 OCR 识别出的单词/边界框），而非文本上下文。

除非您使用的模型在其配置文件（`generation_config.json`）中明确设置了这些生成参数，否则将使用以下默认值：
- max_new_tokens: 256

示例：

```python
>>> from transformers import pipeline

>>> document_qa = pipeline(model="impira/layoutlm-document-qa")
>>> document_qa(
...     image="https://huggingface.co/datasets/hf-internal-testing/transformers-synthetic-assets/resolve/main/images/invoice_docquery_a.png",
...     question="What is the invoice number?",
... )
[{'score': 0.425, 'answer': 'us-001', 'start': 16, 'end': 16}]
```

在 [pipeline 教程](../pipeline_tutorial) 中了解使用 pipeline 的基础知识。

此文档问答流水线目前可以通过 [pipeline()](/docs/transformers/v5.23.0/zh/main_classes/pipelines#transformers.pipeline) 使用以下任务标识符进行加载：`"document-question-answering"`。

该流水线可使用的模型是在文档问答任务上经过微调的模型。有关可用模型的最新列表，请参阅 [huggingface.co/models](https://huggingface.co/models?filter=document-question-answering)。

#### __调用__[[transformers.DocumentQuestionAnsweringPipeline.__call__]]

```python
__call__(image: typing.Union[ForwardRef('Image.Image'), str, list[dict[str, typing.Any]]], question: str | None = None, word_boxes: tuple[str, list[float]] | None = None, **kwargs: Any)
```

[来源](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/pipelines/document_question_answering.py#L338)

**参数：**

image (`str` 或 `PIL.Image`)：该流水线处理三种类型的图像： - 包含指向图像的 http 链接的字符串 - 包含图像本地路径的字符串 - 直接通过 PIL 加载的图像 该流水线接受单张图像或一批图像。如果提供单张图像，它可以广播到多个问题。

question (`str`) : 要针对文档提出的问题。

word_boxes (`list[str, tuple[float, float, float, float]]`, *可选*) : 一个包含单词和边界框（归一化 0->1000）的列表。如果您提供了此可选输入，那么对于需要这些信息的模型（例如 LayoutLM），流水线将直接使用这些单词和边界框，而不是对图像运行 OCR 来推导它们。这使得您无需每次调用流水线时都重新运行 OCR，即可在多次流水线调用中复用 OCR 结果。

top_k (`int`，*可选*，默认为 1)：要返回的答案数量（按可能性顺序选择）。请注意，如果上下文中可用的选项不足，返回的答案数量将少于 top_k。

doc_stride (`int`，*可选*，默认值为 128)：如果文档中的单词过长，无法与问题一起放入模型，则会被拆分为多个带有部分重叠的块。此参数用于控制该重叠的大小。

max_answer_len (`int`，*可选*，默认值为 15)：预测答案的最大长度（例如，仅考虑长度更短的答案）。

max_seq_len (`int`，*可选*，默认值为 384)：传递给模型的每个分块中，完整句子（上下文 + 问题）的最大长度（以 token 计）。如有必要，上下文将被拆分为多个分块（使用 `doc_stride` 作为重叠部分）。

max_question_len (`int`，*可选*，默认值为 64)：问题经过分词后的最大长度。如有必要，将被截断。

handle_impossible_answer (`bool`，*可选*，默认为 `False`)：是否接受“不可能”作为答案。

lang (`str`, *可选*) : 运行 OCR 时使用的语言。默认为 english。

tesseract_config (`str`, *可选*) : 在运行 OCR 时传递给 tesseract 的额外标志。

timeout (`float`, *可选*，默认为 None) : 从网络获取图像时等待的最大时间（秒）。如果为 None，则不设置超时，调用可能会永久阻塞。

**返回：** 一个 `dict` 或一个 `dict` 列表

每个结果都是一个字典，包含以下键：

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

根据给定的输入问题，利用文档进行回答。文档被定义为一幅图像以及一个可选的 (word, box) 元组列表，用于表示文档中的文本。如果未提供 `word_boxes`，对于需要它们作为输入的 LayoutLM 类模型，将使用 Tesseract OCR 引擎（如果可用）自动提取单词和边界框。对于 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[[transformers.FeatureExtractionPipeline]]

#### transformers.FeatureExtractionPipeline[[transformers.FeatureExtractionPipeline]]

```python
transformers.FeatureExtractionPipeline(model: PreTrainedModel, tokenizer: PreTrainedTokenizer | None = None, feature_extractor: PreTrainedFeatureExtractor | None = None, image_processor: BaseImageProcessor | None = None, video_processor: BaseVideoProcessor | None = None, processor: ProcessorMixin | None = None, task: str = '', device: int | torch.device | None = None, binary_output: bool = False, **kwargs)
```

[来源](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/pipelines/feature_extraction.py#L15)

**参数：**

model ([PreTrainedModel](/docs/transformers/v5.23.0/zh/main_classes/model#transformers.PreTrainedModel))：流水线用于进行预测的模型。该模型必须继承自 [PreTrainedModel](/docs/transformers/v5.23.0/zh/main_classes/model#transformers.PreTrainedModel)。

tokenizer ([PreTrainedTokenizer](/docs/transformers/v5.23.0/zh/main_classes/tokenizer#transformers.PythonBackend))：流水线将使用该分词器为模型编码数据。此对象继承自 [PreTrainedTokenizer](/docs/transformers/v5.23.0/zh/main_classes/tokenizer#transformers.PythonBackend)。

task (`str`，默认为 `""`)：用于标识 pipeline 的任务。

num_workers (`int`，*可选*，默认值为 8)：当流水线使用 *DataLoader*（例如传入数据集，或在 GPU 上运行 PyTorch 模型时）时，所使用的 worker 数量。

batch_size (`int`，*可选*，默认为 1)：当流水线使用 *DataLoader*（例如传入数据集，或在 GPU 上运行 PyTorch 模型时）时，所使用的批次大小。对于推理而言，增大批次大小并不总是有益的，请参阅 [使用流水线进行批处理](https://huggingface.co/transformers/main_classes/pipelines.html#pipeline-batching)。

args_parser ([ArgumentHandler](/docs/transformers/v5.23.0/zh/internal/pipelines_utils#transformers.pipelines.ArgumentHandler)，*可选*)：负责解析所提供 pipeline 参数的对象引用。

device (`int` 或 `str` 或 `torch.device`，*可选*)：流水线所分配的设备。若未设置，流水线将放置在第一个可用的加速器（CUDA、MPS、XPU 等）上，仅当没有可用加速器时才回退到 CPU；模型会自动移动至该设备。传入 `device="cpu"`（或 `-1`）可强制使用 CPU，传入正序数或 `"cuda:1"` 可选择特定加速器，或传入原生的 `torch.device`/`str`。此参数不能与已通过 `accelerate` 加载的模型（即具有 `hf_device_map` 的模型）一起使用。

dtype (`str` 或 `torch.dtype`，*可选*，默认为 `"auto"`)：模型加载时使用的精度，会传递给 `from_pretrained`。默认为 `"auto"`，即以模型保存时的 dtype 加载模型（从检查点的 `config.dtype` 读取，否则从权重推断）。传入显式的 `torch.float16`、`torch.bfloat16`、`torch.float32` 等可覆盖该默认值。

tokenize_kwargs (`dict`, *可选*) : 传递给分词器的额外关键字参数字典。

return_tensors (`bool`，*可选*)：如果为 `True`，则根据指定的框架返回张量，否则返回列表。

特征提取流水线不使用模型头。该流水线从基础 Transformer 中提取隐藏状态，这些隐藏状态可作为下游任务中的特征使用。

示例：

```python
>>> 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_tutorial) 中了解使用 pipeline 的基础知识。

当前，此特征提取流水线可通过 [pipeline()](/docs/transformers/v5.23.0/zh/main_classes/pipelines#transformers.pipeline) 加载，使用的任务标识符为：`"feature-extraction"`。

所有模型均可用于此流水线。有关所有模型的列表（包括社区贡献的模型），请访问 [huggingface.co/models](https://huggingface.co/models)。

#### __调用__[[transformers.FeatureExtractionPipeline.__call__]]

```python
__call__(*args: str | list[str], **kwargs: Any)
```

[来源](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/pipelines/feature_extraction.py#L78)

**参数：**

args (`str` 或 `list[str]`)：一个或多个文本（或一个文本列表），用于获取其特征。

**返回：** 一个嵌套的 `float` 列表

模型计算出的特征。

提取输入文本的特征。

### ImageFeatureExtractionPipeline[[transformers.ImageFeatureExtractionPipeline]]

#### transformers.ImageFeatureExtractionPipeline[[transformers.ImageFeatureExtractionPipeline]]

```python
transformers.ImageFeatureExtractionPipeline(model: PreTrainedModel, tokenizer: PreTrainedTokenizer | None = None, feature_extractor: PreTrainedFeatureExtractor | None = None, image_processor: BaseImageProcessor | None = None, video_processor: BaseVideoProcessor | None = None, processor: ProcessorMixin | None = None, task: str = '', device: int | torch.device | None = None, binary_output: bool = False, **kwargs)
```

[来源](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/pipelines/image_feature_extraction.py#L23)

**参数：**

model ([PreTrainedModel](/docs/transformers/v5.23.0/zh/main_classes/model#transformers.PreTrainedModel))：流水线用于进行预测的模型。该模型必须继承自 [PreTrainedModel](/docs/transformers/v5.23.0/zh/main_classes/model#transformers.PreTrainedModel)。

image_processor ([BaseImageProcessor](/docs/transformers/v5.23.0/zh/main_classes/image_processor#transformers.BaseImageProcessor))：流水线将使用该图像处理器为模型编码数据。此对象继承自 [BaseImageProcessor](/docs/transformers/v5.23.0/zh/main_classes/image_processor#transformers.BaseImageProcessor)。

task (`str`，默认为 `""`)：用于标识 pipeline 的任务。

num_workers (`int`，*可选*，默认值为 8)：当流水线使用 *DataLoader*（例如传入数据集，或在 GPU 上运行 PyTorch 模型时）时，所使用的 worker 数量。

batch_size (`int`，*可选*，默认为 1)：当流水线使用 *DataLoader*（例如传入数据集，或在 GPU 上运行 PyTorch 模型时）时，所使用的批次大小。对于推理而言，增大批次大小并不总是有益的，请参阅 [使用流水线进行批处理](https://huggingface.co/transformers/main_classes/pipelines.html#pipeline-batching)。

args_parser ([ArgumentHandler](/docs/transformers/v5.23.0/zh/internal/pipelines_utils#transformers.pipelines.ArgumentHandler)，*可选*)：负责解析所提供 pipeline 参数的对象引用。

device (`int` 或 `str` 或 `torch.device`，*可选*)：流水线所分配的设备。若未设置，流水线将放置在第一个可用的加速器（CUDA、MPS、XPU 等）上，仅当没有可用加速器时才回退到 CPU；模型会自动移动至该设备。传入 `device="cpu"`（或 `-1`）可强制使用 CPU，传入正序数或 `"cuda:1"` 可选择特定加速器，或传入原生的 `torch.device`/`str`。此参数不能与已通过 `accelerate` 加载的模型（即具有 `hf_device_map` 的模型）一起使用。

dtype (`str` 或 `torch.dtype`，*可选*，默认为 `"auto"`)：模型加载时使用的精度，会传递给 `from_pretrained`。默认为 `"auto"`，即以模型保存时的 dtype 加载模型（从检查点的 `config.dtype` 读取，否则从权重推断）。传入显式的 `torch.float16`、`torch.bfloat16`、`torch.float32` 等可覆盖该默认值。

binary_output (`bool`，*可选*，默认为 `False`)：一个标志，指示管道输出应采用序列化格式（即 pickle）还是原始输出数据（例如文本）。

image_processor_kwargs (`dict`, *可选*) : 传递给图像处理器（image processor）的额外关键字参数字典，例如 {"size": {"height": 100, "width": 100}}

pool (`bool`，*可选*，默认为 `False`)：是否返回池化输出。如果为 `False`，模型将返回原始隐藏状态。

图像特征提取流水线不使用模型头。该流水线从基础 Transformer 中提取隐藏状态，这些隐藏状态可作为下游任务中的特征使用。

示例：

```python
>>> 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_length, hidden_dimension] representing the input image.
torch.Size([1, 197, 768])
```

在 [pipeline 教程](../pipeline_tutorial) 中了解使用 pipeline 的基础知识。

当前，此图像特征提取流水线可通过 [pipeline()](/docs/transformers/v5.23.0/zh/main_classes/pipelines#transformers.pipeline) 使用任务标识符 `"image-feature-extraction"` 进行加载。

所有视觉模型均可用于此流水线。有关所有模型的列表（包括社区贡献的模型），请访问 [huggingface.co/models](https://huggingface.co/models)。

#### __调用__[[transformers.ImageFeatureExtractionPipeline.__call__]]

```python
__call__(*args: typing.Union[str, ForwardRef('Image.Image'), list['Image.Image'], list[str]], **kwargs: Any)
```

[来源](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/pipelines/image_feature_extraction.py#L94)

**参数：**

images (`str`、`list[str]`、`PIL.Image` 或 `list[PIL.Image]`)：该流水线支持三种类型的图像： - 包含指向图像的 http 链接的字符串 - 包含图像本地路径的字符串 - 直接以 PIL 加载的图像  该流水线接受单张图像或一批图像，后者必须以字符串形式传入。批次中的图像必须全部采用相同的格式：全部为 http 链接、全部为本地路径，或全部为 PIL 图像。

timeout (`float`，*可选*，默认为 None)：从网络获取图像时等待的最大时间（以秒为单位）。如果为 None，则不使用超时，调用可能会永久阻塞。

**返回：** 一个嵌套的 `float` 列表

模型计算出的特征。

提取输入的特征。

### ImageTextToTextPipeline[[transformers.ImageTextToTextPipeline]]

#### transformers.ImageTextToTextPipeline[[transformers.ImageTextToTextPipeline]]

```python
transformers.ImageTextToTextPipeline(*args, **kwargs)
```

[来源](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/pipelines/image_text_to_text.py#L53)

**参数：**

model ([PreTrainedModel](/docs/transformers/v5.23.0/zh/main_classes/model#transformers.PreTrainedModel))：流水线用于进行预测的模型。该模型必须继承自 [PreTrainedModel](/docs/transformers/v5.23.0/zh/main_classes/model#transformers.PreTrainedModel)。

processor ([ProcessorMixin](/docs/transformers/v5.23.0/zh/main_classes/processors#transformers.ProcessorMixin))：流水线将使用该处理器为模型编码数据。此对象继承自 [ProcessorMixin](/docs/transformers/v5.23.0/zh/main_classes/processors#transformers.ProcessorMixin)。Processor 是一个复合对象，可能包含 `tokenizer`、`feature_extractor` 和 `image_processor`。

task (`str`，默认为 `""`)：用于标识 pipeline 的任务。

num_workers (`int`，*可选*，默认值为 8)：当流水线使用 *DataLoader*（例如传入数据集，或在 GPU 上运行 PyTorch 模型时）时，所使用的 worker 数量。

batch_size (`int`，*可选*，默认为 1)：当流水线使用 *DataLoader*（例如传入数据集，或在 GPU 上运行 PyTorch 模型时）时，所使用的批次大小。对于推理而言，增大批次大小并不总是有益的，请参阅 [使用流水线进行批处理](https://huggingface.co/transformers/main_classes/pipelines.html#pipeline-batching)。

args_parser ([ArgumentHandler](/docs/transformers/v5.23.0/zh/internal/pipelines_utils#transformers.pipelines.ArgumentHandler)，*可选*)：负责解析所提供 pipeline 参数的对象引用。

device (`int` 或 `str` 或 `torch.device`，*可选*)：流水线所分配的设备。若未设置，流水线将放置在第一个可用的加速器（CUDA、MPS、XPU 等）上，仅当没有可用加速器时才回退到 CPU；模型会自动移动至该设备。传入 `device="cpu"`（或 `-1`）可强制使用 CPU，传入正序数或 `"cuda:1"` 可选择特定加速器，或传入原生的 `torch.device`/`str`。此参数不能与已通过 `accelerate` 加载的模型（即具有 `hf_device_map` 的模型）一起使用。

dtype (`str` 或 `torch.dtype`，*可选*，默认为 `"auto"`)：模型加载时使用的精度，会传递给 `from_pretrained`。默认为 `"auto"`，即以模型保存时的 dtype 加载模型（从检查点的 `config.dtype` 读取，否则从权重推断）。传入显式的 `torch.float16`、`torch.bfloat16`、`torch.float32` 等可覆盖该默认值。

binary_output (`bool`，*可选*，默认为 `False`)：一个标志，指示管道输出应采用序列化格式（即 pickle）还是原始输出数据（例如文本）。

使用 `AutoModelForImageTextToText` 的图像-文本到文本流水线。该流水线根据图像和文本生成文本。当底层模型为对话模型时，它还可以接受一个或多个聊天，此时流水线将以聊天模式运行，并通过添加其响应来继续这些聊天。每个聊天的形式是一个字典列表，其中每个字典包含 "role" 和 "content" 键。

除非您使用的模型在其配置文件（`generation_config.json`）中明确设置了这些生成参数，否则将使用以下默认值：
- max_new_tokens: 256

示例：

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

```python
>>> 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://huggingface.co/datasets/hf-internal-testing/transformers-synthetic-assets/resolve/main/images/qwen_vl_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://huggingface.co/datasets/hf-internal-testing/transformers-synthetic-assets/resolve/main/images/qwen_vl_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_tutorial) 中了解使用 pipeline 的基础知识。

该图像-文本到文本流水线目前可以通过 pipeline() 使用以下任务标识符进行加载："image-text-to-text"。

在 [huggingface.co/models](https://huggingface.co/models?pipeline_tag=image-text-to-text) 上查看可用模型列表。

#### __调用__[[transformers.ImageTextToTextPipeline.__call__]]

```python
__call__(images: typing.Union[str, list[str], list[list[str]], ForwardRef('Image.Image'), list['Image.Image'], list[list['Image.Image']], list[dict], NoneType] = None, text: str | list[str] | list[dict] | None = None, **kwargs)
```

[来源](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/pipelines/image_text_to_text.py#L217)

**参数：**

images (`str`, `list[str]`, `PIL.Image, `list[PIL.Image]`, `list[dict[str, Union[str, PIL.Image]]]`) : The pipeline handles three types of images:  - A string containing a HTTP(s) link pointing to an image - A string containing a local path to an image - An image loaded in PIL directly  The pipeline accepts either a single image or a batch of images. Finally, this pipeline also supports the chat format (see `text`) containing images and text in this argument.

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`, *可选*) : 是否清理文本输出中可能存在的多余空格。默认使用分词器的 `clean_up_tokenization_spaces` 设置。

continue_final_message( `bool`, *可选*)：此参数表示你希望模型继续输入对话中的最后一条消息，而不是开始一条新消息，从而允许你“预填充”其回复。默认情况下，当输入对话中的最后一条消息具有 `assistant` 角色时，此值为 `True`，否则为 `False`，但你可以通过设置此标志来手动覆盖该行为。

**返回：** 一个 `dict` 列表或 `dict` 列表的列表

每个结果都是一个字典，包含以下键（无法同时返回 `generated_text` 和 `generated_token_ids`）：

- **generated_text**（`str`，当 `return_text=True` 时存在）-- 生成的文本。
- **generated_token_ids**（`torch.Tensor`，当 `return_tensors=True` 时存在）—— 生成文本的 token id。
- **input_text** (`str`) -- 输入文本。

根据传入的文本和图像作为输入，生成文本。

### AnyToAnyPipeline[[transformers.AnyToAnyPipeline]]

#### transformers.AnyToAnyPipeline[[transformers.AnyToAnyPipeline]]

```python
transformers.AnyToAnyPipeline(*args, **kwargs)
```

[来源](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/pipelines/any_to_any.py#L67)

**参数：**

model ([PreTrainedModel](/docs/transformers/v5.23.0/zh/main_classes/model#transformers.PreTrainedModel))：流水线用于进行预测的模型。该模型必须继承自 [PreTrainedModel](/docs/transformers/v5.23.0/zh/main_classes/model#transformers.PreTrainedModel)。

processor ([ProcessorMixin](/docs/transformers/v5.23.0/zh/main_classes/processors#transformers.ProcessorMixin))：流水线将使用该处理器为模型编码数据。此对象继承自 [ProcessorMixin](/docs/transformers/v5.23.0/zh/main_classes/processors#transformers.ProcessorMixin)。Processor 是一个复合对象，可能包含 `tokenizer`、`feature_extractor` 和 `image_processor`。

task (`str`，默认为 `""`)：用于标识 pipeline 的任务。

num_workers (`int`，*可选*，默认值为 8)：当流水线使用 *DataLoader*（例如传入数据集，或在 GPU 上运行 PyTorch 模型时）时，所使用的 worker 数量。

batch_size (`int`，*可选*，默认为 1)：当流水线使用 *DataLoader*（例如传入数据集，或在 GPU 上运行 PyTorch 模型时）时，所使用的批次大小。对于推理而言，增大批次大小并不总是有益的，请参阅 [使用流水线进行批处理](https://huggingface.co/transformers/main_classes/pipelines.html#pipeline-batching)。

args_parser ([ArgumentHandler](/docs/transformers/v5.23.0/zh/internal/pipelines_utils#transformers.pipelines.ArgumentHandler)，*可选*)：负责解析所提供 pipeline 参数的对象引用。

device (`int` 或 `str` 或 `torch.device`，*可选*)：流水线所分配的设备。若未设置，流水线将放置在第一个可用的加速器（CUDA、MPS、XPU 等）上，仅当没有可用加速器时才回退到 CPU；模型会自动移动至该设备。传入 `device="cpu"`（或 `-1`）可强制使用 CPU，传入正序数或 `"cuda:1"` 可选择特定加速器，或传入原生的 `torch.device`/`str`。此参数不能与已通过 `accelerate` 加载的模型（即具有 `hf_device_map` 的模型）一起使用。

dtype (`str` 或 `torch.dtype`，*可选*，默认为 `"auto"`)：模型加载时使用的精度，会传递给 `from_pretrained`。默认为 `"auto"`，即以模型保存时的 dtype 加载模型（从检查点的 `config.dtype` 读取，否则从权重推断）。传入显式的 `torch.float16`、`torch.bfloat16`、`torch.float32` 等可覆盖该默认值。

binary_output (`bool`，*可选*，默认为 `False`)：一个标志，指示管道输出应采用序列化格式（即 pickle）还是原始输出数据（例如文本）。

使用 `AutoModelForMultimodalLM` 的多模态生成流水线。该流水线可根据任意组合的多模态数据和文本生成文本。当底层模型为对话模型时，它还可以接受一个或多个聊天，此时流水线将以聊天模式运行，并通过添加其响应来继续这些聊天。每个聊天采用字典列表的形式，其中每个字典包含 "role" 和 "content" 键。

除非您使用的模型在其配置文件（`generation_config.json`）中明确设置了这些生成参数，否则将使用以下默认值：
- max_new_tokens: 256

示例：

```python
>>> from transformers import pipeline

>>> pipe = pipeline(task="any-to-any", model="google/gemma-3n-E4B-it")
>>> pipe("https://huggingface.co/datasets/Narsil/image_dummy/raw/main/parrots.png", text="A photo of")
[{'generated_text': 'a photo of two birds'}]
```

```python
>>> from transformers import pipeline

>>> pipe = pipeline("any-to-any", model="google/gemma-3n-E4B-it")
>>> messages = [
>>>     {
>>>         "role": "user",
>>>         "content": [
>>>             {
>>>                 "type": "image",
>>>                 "url": "https://huggingface.co/datasets/hf-internal-testing/transformers-synthetic-assets/resolve/main/images/qwen_vl_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://huggingface.co/datasets/hf-internal-testing/transformers-synthetic-assets/resolve/main/images/qwen_vl_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_tutorial) 中了解使用 pipeline 的基础知识。

该多模态流水线目前可以通过 pipeline() 使用以下任务标识符进行加载："any-to-any"。

在 [huggingface.co/models](https://huggingface.co/models?pipeline_tag=any-to-any) 上查看可用模型列表。

#### __调用__[[transformers.AnyToAnyPipeline.__call__]]

```python
__call__(text: str | list[str] | list[dict], images: typing.Union[str, list[str], list[list[str]], ForwardRef('PIL.Image.Image'), numpy.ndarray, ForwardRef('torch.Tensor'), list['PIL.Image.Image'], list[numpy.ndarray], list['torch.Tensor'], NoneType] = None, videos: typing.Union[str, list[str], list['PIL.Image.Image'], numpy.ndarray, ForwardRef('torch.Tensor'), list[numpy.ndarray], list['torch.Tensor'], list[list['PIL.Image.Image']], list[list[numpy.ndarray]], list[list['torch.Tensor']], transformers.video_utils.URL, list[transformers.video_utils.URL], list[list[transformers.video_utils.URL]], transformers.video_utils.Path, list[transformers.video_utils.Path], list[list[transformers.video_utils.Path]], NoneType] = None, audio: typing.Union[str, list[str], numpy.ndarray, ForwardRef('torch.Tensor'), collections.abc.Sequence[numpy.ndarray], collections.abc.Sequence['torch.Tensor'], NoneType] = None, **kwargs)
```

[来源](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/pipelines/any_to_any.py#L258)

**参数：**

text (`str`, `list[str]`, `list[dict]`) : 用于生成的文本。如果传入字符串列表，则列表的长度应与图像数量相同。文本也可以遵循聊天格式：一个字典列表，其中每个字典代表对话中的一条消息。每个字典应包含两个键：'role' 和 'content'。'role' 应为 'user'、'system' 或 'assistant' 之一。'content' 应为一个字典列表，包含消息的文本和消息类型。

images (`str`, `list[str]`, `ImageInput`) : 该流水线处理三种类型的图像： - 包含指向图像的 HTTP(s) 链接的字符串 - 包含图像本地路径的字符串 - 直接通过 PIL 加载的图像 该流水线接受单张图像或一批图像。最后，此流水线还支持聊天格式（参见 `text`），该参数中可包含图像和文本。

videos (`str`, `list[str]`, `VideoInput`) : 该流水线支持三种类型的视频： - 包含指向视频的 HTTP(s) 链接的字符串 - 包含视频本地路径的字符串 - 已加载并解码为数组格式的视频 该流水线接受单个视频或一批视频。最后，此流水线还支持聊天格式（参见 `text`），允许在此参数中包含视频和文本。

audio (`str`, `list[str]`, `AudioInput`) : 该流水线处理三种类型的音频：  - 包含指向音频的 HTTP(s) 链接的字符串 - 包含音频本地路径的字符串 - 直接通过 PIL 加载的音频  该流水线接受单个音频或一批音频。最后，此流水线还支持聊天格式（参见 `text`），该格式在此参数中包含音频和文本。

return_tensors (`bool`，*可选*，默认为 `False`)：在输出中返回预测张量（以 token 索引形式）。如果设置为 `True`，则不会返回解码后的文本。

return_text (`bool`，*可选*)：返回输出中的解码文本。

return_full_text (`bool`，*可选*，默认为 `True`)：如果设置为 `False`，则仅返回新增的文本；否则返回完整文本。不能与 `return_text` 同时指定。

clean_up_tokenization_spaces (`bool`, *可选*) : 是否清理文本输出中可能存在的多余空格。默认使用分词器的 `clean_up_tokenization_spaces` 设置。

continue_final_message( `bool`, *可选*)：此参数表示你希望模型继续输入对话中的最后一条消息，而不是开始一条新消息，从而允许你“预填充”其回复。默认情况下，当输入对话中的最后一条消息具有 `assistant` 角色时，此值为 `True`，否则为 `False`，但你可以通过设置此标志来手动覆盖该行为。

**返回：** 一个 `dict` 列表或 `dict` 列表的列表

每个结果都是一个字典，包含以下键（无法同时返回 `generated_text` 和 `generated_token_ids`）：

- **generated_text**（`str`，当 `return_text=True` 且 `generation_mode="text"` 时存在）-- 生成的文本。
- **generated_audio**（`np.ndarray`，当 `generation_mode="audio"` 时存在）-- 生成的音频。
- **generated_image**（`PIL.Image.Image`，当 `generation_mode="image"` 时存在）-- 生成的图像。
- **generated_token_ids**（`torch.Tensor`，当 `return_tensors=True` 且 `generation_mode="text"` 时存在）-- 生成文本的 token id。
- **input_text** (`str`) -- 输入文本。

根据给定的文本以及可选的多模态数据作为输入，生成文本。

### MaskGenerationPipeline[[transformers.MaskGenerationPipeline]]

#### transformers.MaskGenerationPipeline[[transformers.MaskGenerationPipeline]]

```python
transformers.MaskGenerationPipeline(**kwargs)
```

[来源](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/pipelines/mask_generation.py#L36)

**参数：**

model ([PreTrainedModel](/docs/transformers/v5.23.0/zh/main_classes/model#transformers.PreTrainedModel))：流水线用于进行预测的模型。该模型必须继承自 [PreTrainedModel](/docs/transformers/v5.23.0/zh/main_classes/model#transformers.PreTrainedModel)。

image_processor ([BaseImageProcessor](/docs/transformers/v5.23.0/zh/main_classes/image_processor#transformers.BaseImageProcessor))：流水线将使用该图像处理器为模型编码数据。此对象继承自 [BaseImageProcessor](/docs/transformers/v5.23.0/zh/main_classes/image_processor#transformers.BaseImageProcessor)。

task (`str`，默认为 `""`)：用于标识 pipeline 的任务。

num_workers (`int`，*可选*，默认值为 8)：当流水线使用 *DataLoader*（例如传入数据集，或在 GPU 上运行 PyTorch 模型时）时，所使用的 worker 数量。

batch_size (`int`，*可选*，默认为 1)：当流水线使用 *DataLoader*（例如传入数据集，或在 GPU 上运行 PyTorch 模型时）时，所使用的批次大小。对于推理而言，增大批次大小并不总是有益的，请参阅 [使用流水线进行批处理](https://huggingface.co/transformers/main_classes/pipelines.html#pipeline-batching)。

args_parser ([ArgumentHandler](/docs/transformers/v5.23.0/zh/internal/pipelines_utils#transformers.pipelines.ArgumentHandler)，*可选*)：负责解析所提供 pipeline 参数的对象引用。

device (`int` 或 `str` 或 `torch.device`，*可选*)：流水线所分配的设备。若未设置，流水线将放置在第一个可用的加速器（CUDA、MPS、XPU 等）上，仅当没有可用加速器时才回退到 CPU；模型会自动移动至该设备。传入 `device="cpu"`（或 `-1`）可强制使用 CPU，传入正序数或 `"cuda:1"` 可选择特定加速器，或传入原生的 `torch.device`/`str`。此参数不能与已通过 `accelerate` 加载的模型（即具有 `hf_device_map` 的模型）一起使用。

dtype (`str` 或 `torch.dtype`，*可选*，默认为 `"auto"`)：模型加载时使用的精度，会传递给 `from_pretrained`。默认为 `"auto"`，即以模型保存时的 dtype 加载模型（从检查点的 `config.dtype` 读取，否则从权重推断）。传入显式的 `torch.float16`、`torch.bfloat16`、`torch.float32` 等可覆盖该默认值。

binary_output (`bool`，*可选*，默认为 `False`)：一个标志，指示管道输出应采用序列化格式（即 pickle）还是原始输出数据（例如文本）。

points_per_batch (*可选*，int，默认为 64)：设置模型同时运行的点数。数值越高可能速度越快，但会占用更多 GPU 内存。

output_bboxes_mask (`bool`，*可选*，默认为 `False`)：是否输出边界框预测。

output_rle_masks (`bool`，*可选*，默认为 `False`)：是否以 `RLE` 格式输出掩码

使用 `SamForMaskGeneration` 为图像自动生成掩码。该流水线在给定图像的情况下，预测图像的 binary mask。它是一个 `ChunkPipeline`，因为你可以将点按 mini-batch 拆分，以避免 OOM 问题。使用 `points_per_batch` 参数来控制同时处理的点数。默认值为 `64`。

该流水线分三步运行：
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 （在每个 mini-batch 循环中执行）：接收原始输出掩码，根据图像尺寸调整其大小，并将其转换为二值掩码。
   - image_processor.filter_masks （在每个 mini-batch 循环中）：同时使用 `pred_iou_thresh` 和 `stability_scores`。此外，还会应用多种基于非极大值抑制的过滤器，以移除质量不佳的掩码。
   - image_processor.postprocess_masks_for_amg 对掩码应用 NSM，仅保留相关的掩码。

示例：

```python
>>> 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_tutorial) 中了解使用 pipeline 的基础知识。

当前，此分割流水线可以通过 [pipeline()](/docs/transformers/v5.23.0/zh/main_classes/pipelines#transformers.pipeline) 加载，使用的任务标识符为：`"mask-generation"`。

在 [huggingface.co/models](https://huggingface.co/models?filter=mask-generation) 上查看可用模型列表。

#### __调用__[[transformers.MaskGenerationPipeline.__call__]]

```python
__call__(image: typing.Union[str, ForwardRef('Image.Image'), list[str], list['Image.Image']], *args: Any, **kwargs: Any)
```

[来源](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/pipelines/mask_generation.py#L143)

**参数：**

image (`str`、`List[str]`、`PIL.Image` 或 `List[PIL.Image]`)：图像或图像列表。

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 Image。如果未检测到对象，则返回一个全零掩码。
- **score**（*可选* `float`）-- 可选参数，当模型能够估计由标签和掩码所描述的“对象”的置信度时使用。

生成二值分割掩码

## 父类：`Pipeline`[[transformers.Pipeline]]

#### transformers.Pipeline[[transformers.Pipeline]]

```python
transformers.Pipeline(model: PreTrainedModel, tokenizer: PreTrainedTokenizer | None = None, feature_extractor: PreTrainedFeatureExtractor | None = None, image_processor: BaseImageProcessor | None = None, video_processor: BaseVideoProcessor | None = None, processor: ProcessorMixin | None = None, task: str = '', device: int | torch.device | None = None, binary_output: bool = False, **kwargs)
```

[来源](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/pipelines/base.py#L763)

**参数：**

model ([PreTrainedModel](/docs/transformers/v5.23.0/zh/main_classes/model#transformers.PreTrainedModel))：流水线用于进行预测的模型。该模型必须继承自 [PreTrainedModel](/docs/transformers/v5.23.0/zh/main_classes/model#transformers.PreTrainedModel)。

tokenizer ([PreTrainedTokenizer](/docs/transformers/v5.23.0/zh/main_classes/tokenizer#transformers.PythonBackend))：流水线将使用该分词器为模型编码数据。此对象继承自 [PreTrainedTokenizer](/docs/transformers/v5.23.0/zh/main_classes/tokenizer#transformers.PythonBackend)。

feature_extractor ([SequenceFeatureExtractor](/docs/transformers/v5.23.0/zh/main_classes/feature_extractor#transformers.SequenceFeatureExtractor))：流水线将使用该特征提取器为模型编码数据。此对象继承自 [SequenceFeatureExtractor](/docs/transformers/v5.23.0/zh/main_classes/feature_extractor#transformers.SequenceFeatureExtractor)。

image_processor ([BaseImageProcessor](/docs/transformers/v5.23.0/zh/main_classes/image_processor#transformers.BaseImageProcessor))：流水线将使用该图像处理器为模型编码数据。此对象继承自 [BaseImageProcessor](/docs/transformers/v5.23.0/zh/main_classes/image_processor#transformers.BaseImageProcessor)。

processor ([ProcessorMixin](/docs/transformers/v5.23.0/zh/main_classes/processors#transformers.ProcessorMixin))：流水线将使用该处理器为模型编码数据。此对象继承自 [ProcessorMixin](/docs/transformers/v5.23.0/zh/main_classes/processors#transformers.ProcessorMixin)。Processor 是一个复合对象，可能包含 `tokenizer`、`feature_extractor` 和 `image_processor`。

task (`str`，默认为 `""`)：用于标识 pipeline 的任务。

num_workers (`int`，*可选*，默认值为 8)：当流水线使用 *DataLoader*（例如传入数据集，或在 GPU 上运行 PyTorch 模型时）时，所使用的 worker 数量。

batch_size (`int`，*可选*，默认为 1)：当流水线使用 *DataLoader*（例如传入数据集，或在 GPU 上运行 PyTorch 模型时）时，所使用的批次大小。对于推理而言，增大批次大小并不总是有益的，请参阅 [使用流水线进行批处理](https://huggingface.co/transformers/main_classes/pipelines.html#pipeline-batching)。

args_parser ([ArgumentHandler](/docs/transformers/v5.23.0/zh/internal/pipelines_utils#transformers.pipelines.ArgumentHandler)，*可选*)：负责解析所提供 pipeline 参数的对象引用。

device (`int` 或 `str` 或 `torch.device`，*可选*)：流水线所分配的设备。若未设置，流水线将放置在第一个可用的加速器（CUDA、MPS、XPU 等）上，仅当没有可用加速器时才回退到 CPU；模型会自动移动至该设备。传入 `device="cpu"`（或 `-1`）可强制使用 CPU，传入正序数或 `"cuda:1"` 可选择特定加速器，或传入原生的 `torch.device`/`str`。此参数不能与已通过 `accelerate` 加载的模型（即具有 `hf_device_map` 的模型）一起使用。

dtype (`str` 或 `torch.dtype`，*可选*，默认为 `"auto"`)：模型加载时使用的精度，会传递给 `from_pretrained`。默认为 `"auto"`，即以模型保存时的 dtype 加载模型（从检查点的 `config.dtype` 读取，否则从权重推断）。传入显式的 `torch.float16`、`torch.bfloat16`、`torch.float32` 等可覆盖该默认值。

binary_output (`bool`，*可选*，默认为 `False`)：一个标志，指示管道输出应采用序列化格式（即 pickle）还是原始输出数据（例如文本）。

Pipeline 类是所有流水线继承的基类。如需了解不同流水线共用的方法，请参阅此类。

实现流水线操作的基类。流水线工作流被定义为以下操作的序列：

输入 -> 分词 -> 模型推理 -> 后处理（取决于任务） -> 输出

Pipeline 支持通过 device 参数在 CPU 或 GPU 上运行（详见下文）。

某些流水线，例如 [FeatureExtractionPipeline](/docs/transformers/v5.23.0/zh/main_classes/pipelines#transformers.FeatureExtractionPipeline)（`'feature-extraction'`），会以嵌套列表的形式输出大型张量对象。为了避免将如此庞大的结构以文本数据的形式转储，我们提供了 `binary_output` 构造参数。如果将其设置为 `True`，输出将以 pickle 格式存储。

#### check_model_type[[transformers.Pipeline.check_model_type]]

```python
check_model_type(supported_models: list[str] | dict)
```

[来源](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/pipelines/base.py#L1126)

**参数：**

supported_models （`list[str]` 或 `dict`）：流水线支持的模型列表，或包含模型类值的字典。

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

#### device_placement[[transformers.Pipeline.device_placement]]

```python
device_placement()
```

[来源](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/pipelines/base.py#L1012)

**返回值：**

上下文管理器

允许在用户指定设备上分配张量的上下文管理器。

示例：

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

#### ensure_tensor_on_device[[transformers.Pipeline.ensure_tensor_on_device]]

```python
ensure_tensor_on_device(**inputs)
```

[来源](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/pipelines/base.py#L1094)

**参数：**

inputs （应为 `torch.Tensor` 的关键字参数，其余将被忽略）：要放置在 `self.device` 上的张量。

仅对**列表**进行递归。--

**返回：** `dict[str, torch.Tensor]`

与 `inputs` 相同，但位于正确的设备上。

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

#### postprocess[[transformers.Pipeline.postprocess]]

```python
postprocess(model_outputs: ModelOutput, **postprocess_parameters: dict)
```

[来源](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/pipelines/base.py#L1193)

Postprocess 将接收 `_forward` 方法的原始输出（通常是张量），并将其重新格式化为更易用的形式。通常，它会输出一个包含结果（仅包含字符串和数字）的列表或字典。

#### predict[[transformers.Pipeline.predict]]

```python
predict(X)
```

[来源](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/pipelines/base.py#L991)

Scikit / Keras 接口，用于调用 transformers 的 pipelines。此方法会转发至 __call__()。

#### preprocess[[transformers.Pipeline.preprocess]]

```python
preprocess(input_: Any, **preprocess_parameters: dict)
```

[来源](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/pipelines/base.py#L1172)

Preprocess 会接收特定 pipeline 的 `input_`，并返回一个包含 `_forward` 正常运行所需全部内容的字典。它至少应包含一个张量，但可能还包含其他任意项目。

#### push_to_hub[[transformers.Pipeline.push_to_hub]]

```python
push_to_hub(repo_id: str, commit_message: str | None = None, commit_description: str | None = None, private: bool | None = None, token: bool | str | None = None, revision: str | None = None, create_pr: bool = False, max_shard_size: int | str | None = '50GB', tags: list[str] | None = None)
```

[来源](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/utils/hub.py#L822)

**参数：**

repo_id (`str`) : 要推送管道（pipe）的目标仓库名称。推送到特定组织时，该名称应包含您的组织名。

commit_message (`str`, *可选*) : 推送时提交的说明信息。默认值为 `"Upload pipe"`。

commit_description (`str`, *可选*) : 将创建的提交的描述

private (`bool`，*可选*)：是否将仓库设为私有。如果为 `None`（默认值），除非组织的默认设置为私有，否则仓库将是公开的。如果仓库已存在，则忽略此值。

token (`bool` 或 `str`，*可选*) : 用于远程文件的 HTTP bearer 授权令牌。如果为 `True`（默认值），将使用运行 `hf auth login` 时生成的令牌（存储在 `~/.huggingface` 中）。

revision (`str`, *可选*) : 推送上传文件的目标分支。

create_pr (`bool`，*可选*，默认为 `False`)：是否使用上传的文件创建 PR，还是直接提交。

max_shard_size (`int` 或 `str`，*可选*，默认为 `"50GB"`)：仅适用于模型。在分片之前，检查点（checkpoint）的最大大小。分片后的每个检查点大小都将小于此值。如果以字符串形式表示，则必须为数字后跟单位（例如 `"5MB"`）。

tags (`list[str]`，*可选*)：要推送到 Hub 的标签列表。

将 pipeline 文件上传到 🤗 Model Hub。

示例：

```python
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[[transformers.Pipeline.save_pretrained]]

```python
save_pretrained(save_directory: str | os.PathLike, **kwargs: Any)
```

[来源](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/pipelines/base.py#L939)

**参数：**

save_directory (`str` 或 `os.PathLike`) : 保存目录的路径。如果该目录不存在，将会自动创建。

kwargs (`dict[str, Any]`，*可选*)：传递给 [push_to_hub()](/docs/transformers/v5.23.0/zh/main_classes/model#transformers.utils.PushToHubMixin.push_to_hub) 方法的额外关键字参数。

保存 pipeline 的模型和 tokenizer。

#### transform[[transformers.Pipeline.transform]]

```python
transform(X)
```

[来源](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/pipelines/base.py#L985)

Scikit / Keras 接口，用于调用 transformers 的 pipelines。此方法会转发至 __call__()。

