Transformers documentation

Pipelines

You are viewing main version, which requires installation from source. If you'd like regular pip install, checkout the latest stable version (v5.24.0).
Hugging Face's logo
Join the Hugging Face community

and get access to the augmented documentation experience

to get started

Pipelines

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

需要注意两类 pipeline 抽象:

Pipeline 抽象

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

对单个项的简单调用:

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

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

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

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

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

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

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

from transformers import pipeline

pipe = pipeline("text-classification")


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


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

transformers.pipeline

< >

( task: str | None = Nonemodel: str | PreTrainedModel | None = Noneconfig: str | PreTrainedConfig | None = Nonetokenizer: str | PreTrainedTokenizer | PreTrainedTokenizerFast | None = Nonefeature_extractor: str | FeatureExtractionMixin | None = Noneimage_processor: str | BaseImageProcessor | None = Nonevideo_processor: str | BaseVideoProcessor | None = Noneprocessor: str | ProcessorMixin | None = Nonerevision: str | None = Noneuse_fast: bool = Truetoken: str | bool | None = Nonedevice: int | str | torch.device | None = Nonedevice_map: str | dict[str, int | str] | None = Nonedtype: str | torch.dtype | None = 'auto'trust_remote_code: bool | None = Nonemodel_kwargs: dict[str, Any] | None = Nonepipeline_class: Any | None = None**kwargs: Any ) → Pipeline

参数

返回值

流水线

适用于该任务的流水线。

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

一个 pipeline 由以下部分组成:

While there are such optional arguments as `tokenizer`, `feature_extractor`, `image_processor`, and `processor`, they shouldn't be specified all at once. If these components are not provided, `pipeline` will try to load required ones automatically. In case you want to provide these components explicitly, please refer to a specific pipeline in order to get more details regarding what components are required.

示例:

>>> from transformers import pipeline, AutoModelForTokenClassification, AutoTokenizer

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

>>> # 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 批处理

所有流水线都可以使用批处理。只要流水线使用了其流式处理能力(例如传入列表、Dataset 或 generator),该功能即可生效。

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 倍的减速。

主要体现为速度提升的示例:

from transformers import pipeline
from torch.utils.data import Dataset
from tqdm.auto import tqdm

pipe = pipeline("text-classification", device=0)


class MyDataset(Dataset):
    def __len__(self):
        return 5000

    def __getitem__(self, i):
        return "This is a test"


dataset = MyDataset()

for batch_size in [1, 8, 64, 256]:
    print("-" * 30)
    print(f"Streaming batch_size={batch_size}")
    for out in tqdm(pipe(dataset, batch_size=batch_size), total=len(dataset)):
        pass
# On GTX 970
------------------------------
Streaming no batching
100%|██████████████████████████████████████████████████████████████████████| 5000/5000 [00:26<00:00, 187.52it/s]
------------------------------
Streaming batch_size=8
100%|█████████████████████████████████████████████████████████████████████| 5000/5000 [00:04<00:00, 1205.95it/s]
------------------------------
Streaming batch_size=64
100%|█████████████████████████████████████████████████████████████████████| 5000/5000 [00:02<00:00, 2478.24it/s]
------------------------------
Streaming batch_size=256
100%|█████████████████████████████████████████████████████████████████████| 5000/5000 [00:01<00:00, 2554.43it/s]
(diminishing returns, saturated the GPU)

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

class MyDataset(Dataset):
    def __len__(self):
        return 5000

    def __getitem__(self, i):
        if i % 64 == 0:
            n = 100
        else:
            n = 1
        return "This is a test" * n

与其余句子相比,这是一个偶尔出现的极长句子。在这种情况下,整个批次需要达到 400 个 token 的长度,因此整个批次的形状将是 [64, 400] 而不是 [64, 4],从而导致严重的性能下降。更糟糕的是,在更大的批次上,程序会直接崩溃。

------------------------------
Streaming no batching
100%|█████████████████████████████████████████████████████████████████████| 1000/1000 [00:05<00:00, 183.69it/s]
------------------------------
Streaming batch_size=8
100%|█████████████████████████████████████████████████████████████████████| 1000/1000 [00:03<00:00, 265.74it/s]
------------------------------
Streaming batch_size=64
100%|██████████████████████████████████████████████████████████████████████| 1000/1000 [00:26<00:00, 37.80it/s]
------------------------------
Streaming batch_size=256
  0%|                                                                                 | 0/1000 [00:00<?, ?it/s]
Traceback (most recent call last):
  File "/home/nicolas/src/transformers/test.py", line 42, in <module>
    for out in tqdm(pipe(dataset, batch_size=256), total=len(dataset)):
....
    q = q / math.sqrt(dim_per_head)  # (bs, n_heads, q_length, dim_per_head)
RuntimeError: CUDA out of memory. Tried to allocate 376.00 MiB (GPU 0; 3.95 GiB total capacity; 1.72 GiB already allocated; 354.88 MiB free; 2.46 GiB reserved in total by PyTorch)

这个问题没有好的(通用)解决方案,具体效果可能因使用场景而异。经验法则是:

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

  • 针对你的负载和硬件来衡量性能。测量、测量,并持续测量。真实数据是唯一可靠的路径。

  • 如果存在延迟限制(例如正在执行推理的实时产品),请勿使用批处理。

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

  • 如果你使用的是吞吐量(即希望在大量静态数据上运行模型),并且运行在 GPU 上,那么:

    • 如果您对 sequence_length(“自然”数据)的大小一无所知,默认情况下不要进行批处理,而是先进行测量,并尝试性地添加它。同时,请添加 OOM 检查,以便在失败时能够恢复(如果您不控制 sequence_length,它迟早会失败)。
    • 如果你的 sequence_length 非常规整,那么批处理(batching)往往能带来显著的性能提升。请进行测量,并逐步增大批大小,直到出现 OOM(内存溢出)为止。
    • GPU 越大,批处理就越有可能带来更显著的效果
  • 一旦启用批处理,请确保能够妥善地处理 OOM(内存溢出)问题。

Pipeline 分块批处理

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

为了规避此问题,这两个流水线都较为特殊,它们使用的是 ChunkPipeline 而非普通的 Pipeline。简而言之:

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

现在变为:

all_model_outputs = []
for preprocessed in pipe.preprocess(inputs):
    model_outputs = pipe.forward(preprocessed)
    all_model_outputs.append(model_outputs)
outputs = pipe.postprocess(all_model_outputs)

由于 pipeline 的使用方式相同,因此这一变化对您的代码来说应该是完全透明的。

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

Pipeline FP16 推理

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

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

Pipeline 自定义代码

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

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

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

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


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

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

实现流水线

实现新的流水线

音频

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

AudioClassificationPipeline

class transformers.AudioClassificationPipeline

< >

( *args**kwargs )

参数

  • model (PreTrainedModel) — 用于 pipeline 进行预测的模型。该模型必须继承自 PreTrainedModel。
  • feature_extractor (SequenceFeatureExtractor) — 流水线将使用该特征提取器为模型编码数据。此对象继承自 SequenceFeatureExtractor。
  • task (str,默认为 "") — 用于标识 pipeline 的任务标识符。
  • num_workers (int,可选,默认为 8) — 当 pipeline 使用 DataLoader(例如传入数据集,或在 GPU 上运行 PyTorch 模型时)时,要使用的 worker 数量。
  • batch_size (int,可选,默认为 1) — 当 pipeline 使用 DataLoader(例如传入数据集,或在 GPU 上运行 PyTorch 模型时),指定要使用的批次大小。对于推理任务,增大批次大小并不总是有益的,请参阅 使用 pipeline 进行批处理。
  • args_parser (ArgumentHandler,可选) — 负责解析所提供 pipeline 参数的对象引用。
  • device (int 或 str 或 torch.device,可选) — 流水线所分配的设备。若未设置,流水线将放置在第一个可用的加速器(CUDA、MPS、XPU 等)上,仅当没有可用加速器时才回退到 CPU;模型会自动移动至该设备。传入 device="cpu"(或 -1)可强制使用 CPU,传入正数序号或 "cuda:1" 可选择特定的加速器,或传入原生的 torch.device/str。如果 device 未设置,且 pipeline() 使用 device_map 在单个设备上加载模型,则模型将保留在该设备上。此参数不能与已通过 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 以支持多种音频格式。

示例:

>>> from transformers import pipeline

>>> classifier = pipeline(model="superb/wav2vec2-base-superb-ks")
>>> classifier("https://huggingface.co/datasets/Narsil/asr_dummy/resolve/main/1.flac")
[{'score': 0.997, 'label': '_unknown_'}, {'score': 0.002, 'label': 'left'}, {'score': 0.0, 'label': 'yes'}, {'score': 0.0, 'label': 'down'}, {'score': 0.0, 'label': 'stop'}]

在 pipeline 教程 中了解使用 pipeline 的基础知识。

目前,该流水线可以通过 pipeline() 使用以下任务标识符进行加载:"audio-classification"。

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

__call__

< >

( inputs: numpy.ndarray | bytes | str | dict**kwargs: Any ) → A list of dict with the following keys

参数

  • inputs (np.ndarray 或 bytes 或 str 或 dict) — inputs 可以是以下之一:
    • 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 文档。

AutomaticSpeechRecognitionPipeline

类 transformers.AutomaticSpeechRecognitionPipeline

< >

( model: PreTrainedModelfeature_extractor: typing.Union[ForwardRef('SequenceFeatureExtractor'), str, NoneType] = Nonetokenizer: transformers.tokenization_python.PythonBackend | None = Nonedecoder: typing.Union[ForwardRef('BeamSearchDecoderCTC'), str, NoneType] = Nonedevice: typing.Union[int, ForwardRef('torch.device'), NoneType] = None**kwargs )

参数

  • model (PreTrainedModel) — 用于 pipeline 进行预测的模型。该模型必须继承自 PreTrainedModel。
  • feature_extractor (SequenceFeatureExtractor,可选) — 流水线将使用该特征提取器对波形进行编码,以供模型使用。
  • tokenizer (PreTrainedTokenizer,可选) — 流水线用于为模型编码数据的分词器。该对象继承自 PreTrainedTokenizer。
  • decoder (pyctcdecode.BeamSearchDecoderCTC,可选) — 可以传入 PyCTCDecode 的 BeamSearchDecoderCTC 以进行语言模型增强的解码。更多信息请参阅 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

示例:

>>> from transformers import pipeline

>>> transcriber = pipeline(model="openai/whisper-base")
>>> transcriber("https://huggingface.co/datasets/Narsil/asr_dummy/resolve/main/1.flac")
{'text': ' He hoped there would be stew for dinner, turnips and carrots and bruised potatoes and fat mutton pieces to be ladled out in thick, peppered flour-fatten sauce.'}

在 pipeline 教程 中了解使用 pipeline 的基础知识。

__call__

< >

( inputs: numpy.ndarray | bytes | str | dict**kwargs: Any ) → Dict

参数

  • inputs (np.ndarray 或 bytes 或 str 或 dict) — inputs 可以是以下之一:
    • str,可以是本地音频文件的文件名,也可以是用于下载音频文件的公共 URL 地址。该文件将以正确的采样率读取,并使用 ffmpeg 获取波形。这要求系统中已安装 ffmpeg。
    • bytes 应当是音频文件的内容,并且以相同的方式由 ffmpeg 进行解释。
    • (np.ndarray,形状为 (n, ),类型为 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:流水线将返回文本中 segments(词段)的时间戳。 例如,如果得到 [{"text": " Hi there!", "timestamp": (0.5, 1.5)}],则表示模型预测词段 “Hi there!” 是在 0.5 秒之后、1.5 秒之前说出的。 请注意,文本中的 segment 指的是一个或多个词的序列,而不是像词级时间戳那样指单个词。
  • generate_kwargs (dict, 可选) — 用于生成调用的 generate_config 的临时参数字典。如需了解 generate 的完整概览,请参阅以下指南。

返回值

Dict

一个包含以下键的字典:

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

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

TextToAudioPipeline

class transformers.TextToAudioPipeline

< >

( *argsvocoder = Nonesampling_rate = Nonenoise_scheduler = None**kwargs )

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

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

  • max_new_tokens: 256

示例:

>>> from transformers import pipeline

>>> pipe = pipeline(model="suno/bark-small")
>>> output = pipe("Hey it's HuggingFace on the phone!")

>>> audio = output["audio"]
>>> sampling_rate = output["sampling_rate"]

在 pipeline 教程 中了解使用 pipeline 的基础知识。

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

示例:

>>> 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() 使用以下任务标识符进行加载:"text-to-speech" 或 "text-to-audio"。

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

__call__

< >

( text_inputs**forward_params ) → AudioOutput or a list of AudioOutput, which is a TypedDict with two keys

参数

  • 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 的完整概览,请参阅以下指南。仅当底层模型为生成式模型时,generate_kwargs 才会传递给该模型,并且其优先级高于 forward_params。

返回值

AudioOutput 或 AudioOutput 的列表,它是一个包含两个键的 TypedDict

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

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

ZeroShotAudioClassificationPipeline

类 transformers.ZeroShotAudioClassificationPipeline

< >

( **kwargs )

参数

  • model (PreTrainedModel) — 用于 pipeline 进行预测的模型。该模型必须继承自 PreTrainedModel。
  • tokenizer (PreTrainedTokenizer) — 流水线用于为模型编码数据的分词器。该对象继承自 PreTrainedTokenizer。
  • feature_extractor (SequenceFeatureExtractor) — 流水线将使用该特征提取器为模型编码数据。此对象继承自 SequenceFeatureExtractor。
  • task (str,默认为 "") — 用于标识 pipeline 的任务标识符。
  • num_workers (int,可选,默认为 8) — 当 pipeline 使用 DataLoader(例如传入数据集,或在 GPU 上运行 PyTorch 模型时)时,要使用的 worker 数量。
  • batch_size (int,可选,默认为 1) — 当 pipeline 使用 DataLoader(例如传入数据集,或在 GPU 上运行 PyTorch 模型时),指定要使用的批次大小。对于推理任务,增大批次大小并不总是有益的,请参阅 使用 pipeline 进行批处理。
  • args_parser (ArgumentHandler,可选) — 负责解析所提供 pipeline 参数的对象引用。
  • device (int 或 str 或 torch.device,可选) — 流水线所分配的设备。若未设置,流水线将放置在第一个可用的加速器(CUDA、MPS、XPU 等)上,仅当没有可用加速器时才回退到 CPU;模型会自动移动至该设备。传入 device="cpu"(或 -1)可强制使用 CPU,传入正数序号或 "cuda:1" 可选择特定的加速器,或传入原生的 torch.device/str。如果 device 未设置,且 pipeline() 使用 device_map 在单个设备上加载模型,则模型将保留在该设备上。此参数不能与已通过 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 {}."。请确保根据你的使用场景对其进行更新。

示例:

>>> 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 可以通过 pipeline() 使用以下任务标识符进行加载:"zero-shot-audio-classification"。有关可用模型的列表,请访问 huggingface.co/models。

__call__

< >

( audios: numpy.ndarray | bytes | str | dict**kwargs: Any )

参数

  • 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 已经格式化,请传入 ”{}”。

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

计算机视觉

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

DepthEstimationPipeline

class transformers.DepthEstimationPipeline

< >

( *args**kwargs )

参数

  • model (PreTrainedModel) — 用于 pipeline 进行预测的模型。该模型必须继承自 PreTrainedModel。
  • image_processor (BaseImageProcessor) — 流水线将使用此图像处理器为模型编码数据。该对象继承自 BaseImageProcessor。
  • task (str,默认为 "") — 用于标识 pipeline 的任务标识符。
  • num_workers (int,可选,默认为 8) — 当 pipeline 使用 DataLoader(例如传入数据集,或在 GPU 上运行 PyTorch 模型时)时,要使用的 worker 数量。
  • batch_size (int,可选,默认为 1) — 当 pipeline 使用 DataLoader(例如传入数据集,或在 GPU 上运行 PyTorch 模型时),指定要使用的批次大小。对于推理任务,增大批次大小并不总是有益的,请参阅 使用 pipeline 进行批处理。
  • args_parser (ArgumentHandler,可选) — 负责解析所提供 pipeline 参数的对象引用。
  • device (int 或 str 或 torch.device,可选) — 流水线所分配的设备。若未设置,流水线将放置在第一个可用的加速器(CUDA、MPS、XPU 等)上,仅当没有可用加速器时才回退到 CPU;模型会自动移动至该设备。传入 device="cpu"(或 -1)可强制使用 CPU,传入正数序号或 "cuda:1" 可选择特定的加速器,或传入原生的 torch.device/str。如果 device 未设置,且 pipeline() 使用 device_map 在单个设备上加载模型,则模型将保留在该设备上。此参数不能与已通过 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 的深度估计流水线。该流水线用于预测图像的景深。

示例:

>>> from transformers import pipeline

>>> depth_estimator = pipeline(task="depth-estimation", model="LiheYoung/depth-anything-base-hf")
>>> output = depth_estimator("http://images.cocodataset.org/val2017/000000039769.jpg")
>>> # This is a tensor with the values being the depth expressed in meters for each pixel
>>> output["predicted_depth"].shape
torch.Size([1, 384, 384])

在 pipeline 教程 中了解使用 pipeline 的基础知识。

该深度估计流水线目前可以通过 pipeline() 使用以下任务标识符进行加载:"depth-estimation"。

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

__call__

< >

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

参数

  • inputs (str, list[str], PIL.Image 或 list[PIL.Image]) — 该流水线支持三种类型的图像:
    • 包含指向图像的 http 链接的字符串
    • 包含图像本地路径的字符串
    • 直接以 PIL 加载的图像

    Pipeline 接受单张图像或一批图像,随后必须以字符串形式传入。 批次中的图像必须全部采用相同的格式:全部为 http 链接、全部为本地路径,或全部为 PIL 图像。

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

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

ImageClassificationPipeline

class transformers.ImageClassificationPipeline

< >

( *args**kwargs )

参数

  • model (PreTrainedModel) — 用于 pipeline 进行预测的模型。该模型必须继承自 PreTrainedModel。
  • image_processor (BaseImageProcessor) — 流水线将使用此图像处理器为模型编码数据。该对象继承自 BaseImageProcessor。
  • task (str,默认为 "") — 用于标识 pipeline 的任务标识符。
  • num_workers (int,可选,默认为 8) — 当 pipeline 使用 DataLoader(例如传入数据集,或在 GPU 上运行 PyTorch 模型时)时,要使用的 worker 数量。
  • batch_size (int,可选,默认为 1) — 当 pipeline 使用 DataLoader(例如传入数据集,或在 GPU 上运行 PyTorch 模型时),指定要使用的批次大小。对于推理任务,增大批次大小并不总是有益的,请参阅 使用 pipeline 进行批处理。
  • args_parser (ArgumentHandler,可选) — 负责解析所提供 pipeline 参数的对象引用。
  • device (int 或 str 或 torch.device,可选) — 流水线所分配的设备。若未设置,流水线将放置在第一个可用的加速器(CUDA、MPS、XPU 等)上,仅当没有可用加速器时才回退到 CPU;模型会自动移动至该设备。传入 device="cpu"(或 -1)可强制使用 CPU,传入正数序号或 "cuda:1" 可选择特定的加速器,或传入原生的 torch.device/str。如果 device 未设置,且 pipeline() 使用 device_map 在单个设备上加载模型,则模型将保留在该设备上。此参数不能与已通过 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 的图像分类流水线。该流水线用于预测图像的类别。

示例:

>>> from transformers import pipeline

>>> classifier = pipeline(model="microsoft/beit-base-patch16-224-pt22k-ft22k")
>>> classifier("https://huggingface.co/datasets/Narsil/image_dummy/raw/main/parrots.png")
[{'score': 0.442, 'label': 'macaw'}, {'score': 0.088, 'label': 'popinjay'}, {'score': 0.075, 'label': 'parrot'}, {'score': 0.073, 'label': 'parodist, lampooner'}, {'score': 0.046, 'label': 'poll, poll_parrot'}]

在 pipeline 教程 中了解使用 pipeline 的基础知识。

该图像分类流水线目前可以通过 pipeline() 使用以下任务标识符进行加载:"image-classification"。

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

__call__

< >

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

参数

  • inputs (str, list[str], PIL.Image 或 list[PIL.Image]) — 该流水线支持三种类型的图像:
    • 包含指向图像的 http 链接的字符串
    • 包含图像本地路径的字符串
    • 直接以 PIL 加载的图像

    Pipeline 接受单张图像或一批图像,随后必须以字符串形式传入。 批次中的图像必须全部采用相同的格式:全部为 http 链接、全部为本地路径,或全部为 PIL 图像。

  • function_to_apply (str, 可选, 默认为 "default") — 用于处理模型输出以获取分数的函数。接受以下四种不同的值:

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

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

    可能的值包括:

    • "sigmoid":对输出应用 sigmoid 函数。
    • "softmax":对输出应用 softmax 函数。
    • "none":不对输出应用任何函数。
  • top_k (int,可选,默认为 5) — 流水线将返回的顶级标签数量。如果提供的数值大于模型配置中可用的标签数量,则默认使用标签数量。
  • timeout (float, 可选,默认为 None) — 从网络获取图像时等待的最大秒数。如果为 None,则不设置超时,调用可能会永久阻塞。

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

ImageSegmentationPipeline

class transformers.ImageSegmentationPipeline

< >

( *args**kwargs )

参数

  • model (PreTrainedModel) — 用于 pipeline 进行预测的模型。该模型必须继承自 PreTrainedModel。
  • image_processor (BaseImageProcessor) — 流水线将使用此图像处理器为模型编码数据。该对象继承自 BaseImageProcessor。
  • task (str,默认为 "") — 用于标识 pipeline 的任务标识符。
  • num_workers (int,可选,默认为 8) — 当 pipeline 使用 DataLoader(例如传入数据集,或在 GPU 上运行 PyTorch 模型时)时,要使用的 worker 数量。
  • batch_size (int,可选,默认为 1) — 当 pipeline 使用 DataLoader(例如传入数据集,或在 GPU 上运行 PyTorch 模型时),指定要使用的批次大小。对于推理任务,增大批次大小并不总是有益的,请参阅 使用 pipeline 进行批处理。
  • args_parser (ArgumentHandler,可选) — 负责解析所提供 pipeline 参数的对象引用。
  • device (int 或 str 或 torch.device,可选) — 流水线所分配的设备。若未设置,流水线将放置在第一个可用的加速器(CUDA、MPS、XPU 等)上,仅当没有可用加速器时才回退到 CPU;模型会自动移动至该设备。传入 device="cpu"(或 -1)可强制使用 CPU,传入正数序号或 "cuda:1" 可选择特定的加速器,或传入原生的 torch.device/str。如果 device 未设置,且 pipeline() 使用 device_map 在单个设备上加载模型,则模型将保留在该设备上。此参数不能与已通过 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 的图像分割流水线。该流水线用于预测对象的掩码及其类别。

示例:

>>> from transformers import pipeline

>>> segmenter = pipeline(model="facebook/detr-resnet-50-panoptic")
>>> segments = segmenter("https://huggingface.co/datasets/Narsil/image_dummy/raw/main/parrots.png")
>>> len(segments)
2

>>> segments[0]["label"]
'bird'

>>> segments[1]["label"]
'bird'

>>> type(segments[0]["mask"])  # This is a black and white mask showing where is the bird on the original image.
<class 'PIL.Image.Image'>

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

当前,此图像分割流水线可以通过 pipeline() 使用以下任务标识符进行加载:"image-segmentation"。

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

__call__

< >

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

参数

  • inputs (str, list[str], PIL.Image 或 list[PIL.Image]) — 该流水线支持三种类型的图像:
    • 包含指向图像的 HTTP(S) 链接的字符串
    • 包含图像本地路径的字符串
    • 直接以 PIL 加载的图像

    pipeline 接受单张图像或一批图像。批次中的图像必须全部采用相同的格式:全部为 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,则不设置超时,调用可能会永久阻塞。

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

KeypointMatchingPipeline

class transformers.KeypointMatchingPipeline

< >

( *args**kwargs )

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

__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 ) → Union[list[Match], list[list[Match]]]

参数

  • inputs (str, list[str], PIL.Image 或 list[PIL.Image]) — 该流水线支持三种类型的图像:
    • 包含指向图像的 http 链接的字符串
    • 包含图像本地路径的字符串
    • 直接以 PIL 加载的图像

    pipeline 接受单对图像或一批图像对,后者必须以字符串形式传入。 批次中的所有图像必须采用相同的格式:全部为 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

class transformers.ObjectDetectionPipeline

< >

( *args**kwargs )

参数

  • model (PreTrainedModel) — 用于 pipeline 进行预测的模型。该模型必须继承自 PreTrainedModel。
  • image_processor (BaseImageProcessor) — 流水线将使用此图像处理器为模型编码数据。该对象继承自 BaseImageProcessor。
  • task (str,默认为 "") — 用于标识 pipeline 的任务标识符。
  • num_workers (int,可选,默认为 8) — 当 pipeline 使用 DataLoader(例如传入数据集,或在 GPU 上运行 PyTorch 模型时)时,要使用的 worker 数量。
  • batch_size (int,可选,默认为 1) — 当 pipeline 使用 DataLoader(例如传入数据集,或在 GPU 上运行 PyTorch 模型时),指定要使用的批次大小。对于推理任务,增大批次大小并不总是有益的,请参阅 使用 pipeline 进行批处理。
  • args_parser (ArgumentHandler,可选) — 负责解析所提供 pipeline 参数的对象引用。
  • device (int 或 str 或 torch.device,可选) — 流水线所分配的设备。若未设置,流水线将放置在第一个可用的加速器(CUDA、MPS、XPU 等)上,仅当没有可用加速器时才回退到 CPU;模型会自动移动至该设备。传入 device="cpu"(或 -1)可强制使用 CPU,传入正数序号或 "cuda:1" 可选择特定的加速器,或传入原生的 torch.device/str。如果 device 未设置,且 pipeline() 使用 device_map 在单个设备上加载模型,则模型将保留在该设备上。此参数不能与已通过 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 的目标检测流水线。该流水线用于预测对象的边界框及其类别。

示例:

>>> from transformers import pipeline

>>> detector = pipeline(model="facebook/detr-resnet-50")
>>> detector("https://huggingface.co/datasets/Narsil/image_dummy/raw/main/parrots.png")
[{'score': 0.997, 'label': 'bird', 'box': {'xmin': 69, 'ymin': 171, 'xmax': 396, 'ymax': 507}}, {'score': 0.999, 'label': 'bird', 'box': {'xmin': 398, 'ymin': 105, 'xmax': 767, 'ymax': 507}}]

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

在 pipeline 教程 中了解使用 pipeline 的基础知识。

该目标检测流水线目前可以通过 pipeline() 使用以下任务标识符进行加载:"object-detection"。

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

__call__

< >

( *args**kwargs )

参数

  • inputs (str, list[str], PIL.Image 或 list[PIL.Image]) — 该流水线支持三种类型的图像:
    • 包含指向图像的 HTTP(S) 链接的字符串
    • 包含图像本地路径的字符串
    • 直接以 PIL 加载的图像

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

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

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

VideoClassificationPipeline

类 transformers.VideoClassificationPipeline

< >

( *args**kwargs )

参数

  • model (PreTrainedModel) — 用于 pipeline 进行预测的模型。该模型必须继承自 PreTrainedModel。
  • image_processor (BaseImageProcessor) — 流水线将使用此图像处理器为模型编码数据。该对象继承自 BaseImageProcessor。
  • video_processor (BaseVideoProcessor) — 流水线将使用此视频处理器对视频数据进行编码,以供模型使用。该对象继承自 BaseVideoProcessor。
  • task (str,默认为 "") — 用于标识 pipeline 的任务标识符。
  • num_workers (int,可选,默认为 8) — 当 pipeline 使用 DataLoader(例如传入数据集,或在 GPU 上运行 PyTorch 模型时)时,要使用的 worker 数量。
  • batch_size (int,可选,默认为 1) — 当 pipeline 使用 DataLoader(例如传入数据集,或在 GPU 上运行 PyTorch 模型时),指定要使用的批次大小。对于推理任务,增大批次大小并不总是有益的,请参阅 使用 pipeline 进行批处理。
  • args_parser (ArgumentHandler,可选) — 负责解析所提供 pipeline 参数的对象引用。
  • device (int 或 str 或 torch.device,可选) — 流水线所分配的设备。若未设置,流水线将放置在第一个可用的加速器(CUDA、MPS、XPU 等)上,仅当没有可用加速器时才回退到 CPU;模型会自动移动至该设备。传入 device="cpu"(或 -1)可强制使用 CPU,传入正数序号或 "cuda:1" 可选择特定的加速器,或传入原生的 torch.device/str。如果 device 未设置,且 pipeline() 使用 device_map 在单个设备上加载模型,则模型将保留在该设备上。此参数不能与已通过 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() 使用以下任务标识符进行加载:"video-classification"。

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

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

__call__

< >

( inputs: str | list[str] | None**kwargs )

参数

  • inputs (str, list[str]) — 该流水线支持三种类型的视频:
    • 包含指向视频的 http 链接的字符串
    • 包含视频本地路径的字符串

    pipeline 接受单个视频或一批视频,然后必须以字符串形式传入。 批次中的视频必须全部采用相同的格式:全部为 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” 可禁用后处理。

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

ZeroShotImageClassificationPipeline

class transformers.ZeroShotImageClassificationPipeline

< >

( **kwargs )

参数

  • model (PreTrainedModel) — 用于 pipeline 进行预测的模型。该模型必须继承自 PreTrainedModel。
  • image_processor (BaseImageProcessor) — 流水线将使用此图像处理器为模型编码数据。该对象继承自 BaseImageProcessor。
  • task (str,默认为 "") — 用于标识 pipeline 的任务标识符。
  • num_workers (int,可选,默认为 8) — 当 pipeline 使用 DataLoader(例如传入数据集,或在 GPU 上运行 PyTorch 模型时)时,要使用的 worker 数量。
  • batch_size (int,可选,默认为 1) — 当 pipeline 使用 DataLoader(例如传入数据集,或在 GPU 上运行 PyTorch 模型时),指定要使用的批次大小。对于推理任务,增大批次大小并不总是有益的,请参阅 使用 pipeline 进行批处理。
  • args_parser (ArgumentHandler,可选) — 负责解析所提供 pipeline 参数的对象引用。
  • device (int 或 str 或 torch.device,可选) — 流水线所分配的设备。若未设置,流水线将放置在第一个可用的加速器(CUDA、MPS、XPU 等)上,仅当没有可用加速器时才回退到 CPU;模型会自动移动至该设备。传入 device="cpu"(或 -1)可强制使用 CPU,传入正数序号或 "cuda:1" 可选择特定的加速器,或传入原生的 torch.device/str。如果 device 未设置,且 pipeline() 使用 device_map 在单个设备上加载模型,则模型将保留在该设备上。此参数不能与已通过 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 时,该流水线会预测图像的类别。

示例:

>>> from transformers import pipeline

>>> classifier = pipeline(model="google/siglip-so400m-patch14-384")
>>> classifier(
...     "https://huggingface.co/datasets/Narsil/image_dummy/raw/main/parrots.png",
...     candidate_labels=["animals", "humans", "landscape"],
... )
[{'score': 0.965, 'label': 'animals'}, {'score': 0.03, 'label': 'humans'}, {'score': 0.005, 'label': 'landscape'}]

>>> classifier(
...     "https://huggingface.co/datasets/Narsil/image_dummy/raw/main/parrots.png",
...     candidate_labels=["black and white", "photorealist", "painting"],
... )
[{'score': 0.996, 'label': 'black and white'}, {'score': 0.003, 'label': 'photorealist'}, {'score': 0.0, 'label': 'painting'}]

在 pipeline 教程 中了解使用 pipeline 的基础知识。

该图像分类流水线目前可以通过 pipeline() 使用以下任务标识符进行加载:"zero-shot-image-classification"。

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

__call__

< >

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

参数

  • 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,则不设置超时,调用可能会永久阻塞。

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

ZeroShotObjectDetectionPipeline

class transformers.ZeroShotObjectDetectionPipeline

< >

( **kwargs )

参数

  • model (PreTrainedModel) — 用于 pipeline 进行预测的模型。该模型必须继承自 PreTrainedModel。
  • image_processor (BaseImageProcessor) — 流水线将使用此图像处理器为模型编码数据。该对象继承自 BaseImageProcessor。
  • task (str,默认为 "") — 用于标识 pipeline 的任务标识符。
  • num_workers (int,可选,默认为 8) — 当 pipeline 使用 DataLoader(例如传入数据集,或在 GPU 上运行 PyTorch 模型时)时,要使用的 worker 数量。
  • batch_size (int,可选,默认为 1) — 当 pipeline 使用 DataLoader(例如传入数据集,或在 GPU 上运行 PyTorch 模型时),指定要使用的批次大小。对于推理任务,增大批次大小并不总是有益的,请参阅 使用 pipeline 进行批处理。
  • args_parser (ArgumentHandler,可选) — 负责解析所提供 pipeline 参数的对象引用。
  • device (int 或 str 或 torch.device,可选) — 流水线所分配的设备。若未设置,流水线将放置在第一个可用的加速器(CUDA、MPS、XPU 等)上,仅当没有可用加速器时才回退到 CPU;模型会自动移动至该设备。传入 device="cpu"(或 -1)可强制使用 CPU,传入正数序号或 "cuda:1" 可选择特定的加速器,或传入原生的 torch.device/str。如果 device 未设置,且 pipeline() 使用 device_map 在单个设备上加载模型,则模型将保留在该设备上。此参数不能与已通过 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 时,该流水线会预测目标对象的边界框。

示例:

>>> from transformers import pipeline

>>> detector = pipeline(model="google/owlvit-base-patch32", task="zero-shot-object-detection")
>>> detector(
...     "http://images.cocodataset.org/val2017/000000039769.jpg",
...     candidate_labels=["cat", "couch"],
... )
[{'score': 0.287, 'label': 'cat', 'box': {'xmin': 324, 'ymin': 20, 'xmax': 640, 'ymax': 373}}, {'score': 0.254, 'label': 'cat', 'box': {'xmin': 1, 'ymin': 55, 'xmax': 315, 'ymax': 472}}, {'score': 0.121, 'label': 'couch', 'box': {'xmin': 4, 'ymin': 0, 'xmax': 642, 'ymax': 476}}]

>>> detector(
...     "https://huggingface.co/datasets/Narsil/image_dummy/raw/main/parrots.png",
...     candidate_labels=["head", "bird"],
... )
[{'score': 0.119, 'label': 'bird', 'box': {'xmin': 71, 'ymin': 170, 'xmax': 410, 'ymax': 508}}]

在 pipeline 教程 中了解使用 pipeline 的基础知识。

该目标检测流水线目前可以通过 pipeline() 使用以下任务标识符进行加载:"zero-shot-object-detection"。

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

__call__

< >

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

参数

  • image (str, PIL.Image 或 list[dict[str, Any]]) — 该流水线支持三种类型的图像:
    • 包含指向图像的 http url 的字符串
    • 包含图像本地路径的字符串
    • 直接以 PIL 加载的图像

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

    >>> 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}&zwnj;}, {'score': 0.25, 'label': 'cat', 'box': {'xmin': 1, 'ymin': 55, 'xmax': 315, 'ymax': 472}&zwnj;}, {'score': 0.121, 'label': 'couch', 'box': {'xmin': 4, 'ymin': 0, 'xmax': 642, 'ymax': 476}&zwnj;}], [{'score': 0.287, 'label': 'cat', 'box': {'xmin': 324, 'ymin': 20, 'xmax': 640, 'ymax': 373}&zwnj;}, {'score': 0.254, 'label': 'cat', 'box': {'xmin': 1, 'ymin': 55, 'xmax': 315, 'ymax': 472}&zwnj;}, {'score': 0.121, 'label': 'couch', 'box': {'xmin': 4, 'ymin': 0, 'xmax': 642, 'ymax': 476}&zwnj;}]]
  • candidate_labels (str 或 list[str] 或 list[list[str]]) — 模型应在图像中识别的内容。
  • threshold (float,可选,默认为 0.1) — 做出预测所需的概率。
  • top_k (int,可选,默认为 None) — 流水线将返回的预测结果数量。如果提供的数值为 None 或大于可用的预测结果数量,则默认返回所有预测结果。
  • timeout (float, 可选,默认为 None) — 从网络获取图像时等待的最大秒数。如果为 None,则不设置超时,调用可能会永久阻塞。

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

自然语言处理

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

DecisionPipeline

决策模型、decision 流水线以及 DecisionConfig 均为实验性功能:其 API 可能会随时变更,且不会经过弃用流程。

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

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。

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

< >

( *argsdecision_config: transformers.decision.configuration_utils.DecisionConfig | str | None = None**kwargs )

参数

  • model (PreTrainedModel) — 用于 pipeline 进行预测的模型。该模型必须继承自 PreTrainedModel。
  • tokenizer (PreTrainedTokenizer) — 流水线用于为模型编码数据的分词器。该对象继承自 PreTrainedTokenizer。
  • task (str,默认为 "") — 用于标识 pipeline 的任务标识符。
  • num_workers (int,可选,默认为 8) — 当 pipeline 使用 DataLoader(例如传入数据集,或在 GPU 上运行 PyTorch 模型时)时,要使用的 worker 数量。
  • batch_size (int,可选,默认为 1) — 当 pipeline 使用 DataLoader(例如传入数据集,或在 GPU 上运行 PyTorch 模型时),指定要使用的批次大小。对于推理任务,增大批次大小并不总是有益的,请参阅 使用 pipeline 进行批处理。
  • args_parser (ArgumentHandler,可选) — 负责解析所提供 pipeline 参数的对象引用。
  • device (int 或 str 或 torch.device,可选) — 流水线所分配的设备。若未设置,流水线将放置在第一个可用的加速器(CUDA、MPS、XPU 等)上,仅当没有可用加速器时才回退到 CPU;模型会自动移动至该设备。传入 device="cpu"(或 -1)可强制使用 CPU,传入正数序号或 "cuda:1" 可选择特定的加速器,或传入原生的 torch.device/str。如果 device 未设置,且 pipeline() 使用 device_map 在单个设备上加载模型,则模型将保留在该设备上。此参数不能与已通过 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)位于模型旁边,或位于作为 decision_config 提供的仓库中。决策模型(XxxForDecision)自行对选项进行评分;其他任何模型则通过其标签的下一个 token 的 logits 来评分,因此任何聊天模型都可以作答。

示例:

>>> 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 格式。

__call__

< >

( inputs*argsnum_workers = Nonebatch_size = None**kwargs )

类 transformers.DecisionConfig

< >

( labels: dict[str, list[str]] = <factory>temperature: dict[str, float | int] = <factory>chat_template: str | None = Nonenoul_options: list[str] = <factory>sanitize_control_tokens: bool = Trueadapter: str | None = None )

参数

  • 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(所有问题共用一个提示)通过 Jinja 模板渲染 state。默认使用分词器聊天模板中的通用提示。
  • noul_options (list[str],可选,默认为 ["true", "false"]) — 模板接收 noul 问题两个选项的顺序。
  • sanitize_control_tokens (bool,可选,默认为 True) — 请求中的控制标记是否以文本形式编码。自行转义这些标记的模板会将其禁用,以保留其原始代码的输入 id。
  • adapter (str, 可选) — 流水线加载到模型上的 LoRA 子文件夹,适用于未在根目录保存该 LoRA 的仓库。

决策模型的设置,保存为 decision.json(其聊天模板保存为 decision_template.jinja)。

get_logits_processor

< >

( question_type: str )

应用于 question_type 类型问题的选项分数的 LogitsProcessorList。

prepare_inputs

< >

( requestprocessor )

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

验证

< >

( )

在实例上运行类验证器。

FillMaskPipeline

class transformers.FillMaskPipeline

< >

( model: PreTrainedModeltokenizer: PreTrainedTokenizer | None = Nonefeature_extractor: PreTrainedFeatureExtractor | None = Noneimage_processor: BaseImageProcessor | None = Nonevideo_processor: BaseVideoProcessor | None = Noneprocessor: ProcessorMixin | None = Nonetask: str = ''device: int | torch.device | None = Nonebinary_output: bool = False**kwargs )

参数

  • model (PreTrainedModel) — 用于 pipeline 进行预测的模型。该模型必须继承自 PreTrainedModel。
  • tokenizer (PreTrainedTokenizer) — 流水线用于为模型编码数据的分词器。该对象继承自 PreTrainedTokenizer。
  • task (str,默认为 "") — 用于标识 pipeline 的任务标识符。
  • num_workers (int,可选,默认为 8) — 当 pipeline 使用 DataLoader(例如传入数据集,或在 GPU 上运行 PyTorch 模型时)时,要使用的 worker 数量。
  • batch_size (int,可选,默认为 1) — 当 pipeline 使用 DataLoader(例如传入数据集,或在 GPU 上运行 PyTorch 模型时),指定要使用的批次大小。对于推理任务,增大批次大小并不总是有益的,请参阅 使用 pipeline 进行批处理。
  • args_parser (ArgumentHandler,可选) — 负责解析所提供 pipeline 参数的对象引用。
  • device (int 或 str 或 torch.device,可选) — 流水线所分配的设备。若未设置,流水线将放置在第一个可用的加速器(CUDA、MPS、XPU 等)上,仅当没有可用加速器时才回退到 CPU;模型会自动移动至该设备。传入 device="cpu"(或 -1)可强制使用 CPU,传入正数序号或 "cuda:1" 可选择特定的加速器,或传入原生的 torch.device/str。如果 device 未设置,且 pipeline() 使用 device_map 在单个设备上加载模型,则模型将保留在该设备上。此参数不能与已通过 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,可选) — 传递给分词器的额外关键字参数字典。

__call__

< >

( inputs: str | list[str]**kwargs: Any ) → A list or a list of list of dict

参数

  • inputs (str 或 list[str]) — 一个或多个包含掩码标记的文本(或一个提示词列表)。
  • targets (str 或 list[str],可选) — 传入该参数时,模型会将分数限制在传入的 targets 范围内,而不是在整个词表中查找。如果提供的 targets 不在模型词表中,它们将被分词,并使用第一个生成的 token(会发出警告,且速度可能较慢)。
  • top_k (int,可选) — 如果传入,将覆盖要返回的预测数量。

返回值

dict 的列表或 dict 的列表的列表

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

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

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

TableQuestionAnsweringPipeline

class transformers.TableQuestionAnsweringPipeline

< >

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

参数

  • model (PreTrainedModel) — 用于 pipeline 进行预测的模型。该模型必须继承自 PreTrainedModel。
  • tokenizer (PreTrainedTokenizer) — 流水线用于为模型编码数据的分词器。该对象继承自 PreTrainedTokenizer。
  • task (str,默认为 "") — 用于标识 pipeline 的任务标识符。
  • num_workers (int,可选,默认为 8) — 当 pipeline 使用 DataLoader(例如传入数据集,或在 GPU 上运行 PyTorch 模型时)时,要使用的 worker 数量。
  • batch_size (int,可选,默认为 1) — 当 pipeline 使用 DataLoader(例如传入数据集,或在 GPU 上运行 PyTorch 模型时),指定要使用的批次大小。对于推理任务,增大批次大小并不总是有益的,请参阅 使用 pipeline 进行批处理。
  • args_parser (ArgumentHandler,可选) — 负责解析所提供 pipeline 参数的对象引用。
  • device (int 或 str 或 torch.device,可选) — 流水线所分配的设备。若未设置,流水线将放置在第一个可用的加速器(CUDA、MPS、XPU 等)上,仅当没有可用加速器时才回退到 CPU;模型会自动移动至该设备。传入 device="cpu"(或 -1)可强制使用 CPU,传入正数序号或 "cuda:1" 可选择特定的加速器,或传入原生的 torch.device/str。如果 device 未设置,且 pipeline() 使用 device_map 在单个设备上加载模型,则模型将保留在该设备上。此参数不能与已通过 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

示例:

>>> from transformers import pipeline

>>> oracle = pipeline(model="google/tapas-base-finetuned-wtq")
>>> table = {
...     "Repository": ["Transformers", "Datasets", "Tokenizers"],
...     "Stars": ["36542", "4512", "3934"],
...     "Contributors": ["651", "77", "34"],
...     "Programming language": ["Python", "Python", "Rust, Python and NodeJS"],
... }
>>> oracle(query="How many stars does the transformers repository have?", table=table)
{'answer': 'AVERAGE > 36542', 'coordinates': [(0, 1)], 'cells': ['36542'], 'aggregator': 'AVERAGE'}

在 pipeline 教程 中了解使用 pipeline 的基础知识。

该表格问答流水线目前可以通过 pipeline() 使用以下任务标识符进行加载:"table-question-answering"。

该流水线可使用的模型是在表格问答任务上经过微调的模型。 有关可用模型的最新列表,请参阅 huggingface.co/models。

__call__

< >

( *args**kwargs ) → A dictionary or a list of dictionaries containing results

参数

  • table (pd.DataFrame 或 Dict) — Pandas DataFrame 或字典,将被转换为包含所有表格值的 DataFrame。 字典示例见上文。
  • query (str 或 list[str]) — 将随表格一起发送给模型的查询或查询列表。
  • sequential (bool,可选,默认为 False) — 是否按顺序执行推理,还是作为批次执行。批次处理速度更快,但像 SQA 这样的模型由于其对话性质,需要按顺序执行推理才能提取序列内的关系。
  • padding (bool, str 或 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'(默认值):不进行截断(即,可以输出序列长度大于模型最大可接受输入大小的批次)。

返回值

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

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

  • 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,其中包含完整的表格:

示例:

data = {
    "actors": ["brad pitt", "leonardo di caprio", "george clooney"],
    "age": ["56", "45", "59"],
    "number of movies": ["87", "53", "69"],
    "date of birth": ["7 february 1967", "10 june 1996", "28 november 1967"],
}

此字典可以按原样传入,也可以转换为 pandas DataFrame:

示例:

import pandas as pd

table = pd.DataFrame.from_dict(data)

TextClassificationPipeline

class transformers.TextClassificationPipeline

< >

( **kwargs )

参数

  • model (PreTrainedModel) — 用于 pipeline 进行预测的模型。该模型必须继承自 PreTrainedModel。
  • tokenizer (PreTrainedTokenizer) — 流水线用于为模型编码数据的分词器。该对象继承自 PreTrainedTokenizer。
  • task (str,默认为 "") — 用于标识 pipeline 的任务标识符。
  • num_workers (int,可选,默认为 8) — 当 pipeline 使用 DataLoader(例如传入数据集,或在 GPU 上运行 PyTorch 模型时)时,要使用的 worker 数量。
  • batch_size (int,可选,默认为 1) — 当 pipeline 使用 DataLoader(例如传入数据集,或在 GPU 上运行 PyTorch 模型时),指定要使用的批次大小。对于推理任务,增大批次大小并不总是有益的,请参阅 使用 pipeline 进行批处理。
  • args_parser (ArgumentHandler,可选) — 负责解析所提供 pipeline 参数的对象引用。
  • device (int 或 str 或 torch.device,可选) — 流水线所分配的设备。若未设置,流水线将放置在第一个可用的加速器(CUDA、MPS、XPU 等)上,仅当没有可用加速器时才回退到 CPU;模型会自动移动至该设备。传入 device="cpu"(或 -1)可强制使用 CPU,传入正数序号或 "cuda:1" 可选择特定的加速器,或传入原生的 torch.device/str。如果 device 未设置,且 pipeline() 使用 device_map 在单个设备上加载模型,则模型将保留在该设备上。此参数不能与已通过 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 的文本分类流水线。有关更多信息,请参阅 序列分类示例。

示例:

>>> from transformers import pipeline

>>> classifier = pipeline(model="distilbert/distilbert-base-uncased-finetuned-sst-2-english")
>>> classifier("This movie is disgustingly good !")
[{'label': 'POSITIVE', 'score': 1.0}]

>>> classifier("Director tried too much.")
[{'label': 'NEGATIVE', 'score': 0.996}]

在 pipeline 教程 中了解使用 pipeline 的基础知识。

该文本分类流水线目前可以通过 pipeline() 使用以下任务标识符进行加载:"sentiment-analysis"(用于根据正面或负面情绪对序列进行分类)。

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

此流水线可使用的模型是在序列分类任务上经过微调的模型。有关可用模型的最新列表,请参阅 huggingface.co/models。

__call__

< >

( inputs: str | list[str] | dict[str, str] | list[dict[str, str]]**kwargs: Any ) → A list of dict

参数

  • 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

class transformers.TextGenerationPipeline

< >

( *args**kwargs )

参数

  • model (PreTrainedModel) — 用于 pipeline 进行预测的模型。该模型必须继承自 PreTrainedModel。
  • tokenizer (PreTrainedTokenizer) — 流水线用于为模型编码数据的分词器。该对象继承自 PreTrainedTokenizer。
  • task (str,默认为 "") — 用于标识 pipeline 的任务标识符。
  • num_workers (int,可选,默认为 8) — 当 pipeline 使用 DataLoader(例如传入数据集,或在 GPU 上运行 PyTorch 模型时)时,要使用的 worker 数量。
  • batch_size (int,可选,默认为 1) — 当 pipeline 使用 DataLoader(例如传入数据集,或在 GPU 上运行 PyTorch 模型时),指定要使用的批次大小。对于推理任务,增大批次大小并不总是有益的,请参阅 使用 pipeline 进行批处理。
  • args_parser (ArgumentHandler,可选) — 负责解析所提供 pipeline 参数的对象引用。
  • device (int 或 str 或 torch.device,可选) — 流水线所分配的设备。若未设置,流水线将放置在第一个可用的加速器(CUDA、MPS、XPU 等)上,仅当没有可用加速器时才回退到 CPU;模型会自动移动至该设备。传入 device="cpu"(或 -1)可强制使用 CPU,传入正数序号或 "cuda:1" 可选择特定的加速器,或传入原生的 torch.device/str。如果 device 未设置,且 pipeline() 使用 device_map 在单个设备上加载模型,则模型将保留在该设备上。此参数不能与已通过 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

示例:

>>> from transformers import pipeline

>>> generator = pipeline(model="openai-community/gpt2")
>>> generator("I can't believe you did such a ", do_sample=False)
[{'generated_text': "I can't believe you did such a icky thing to me. I'm so sorry. I'm so sorry. I'm so sorry. I'm so sorry. I'm so sorry. I'm so sorry. I'm so sorry. I"}]

>>> # These parameters will return suggestions, and only the newly created text making it easier for prompting suggestions.
>>> outputs = generator("My tart needs some", num_return_sequences=4, return_full_text=False)
>>> from transformers import pipeline

>>> generator = pipeline(model="HuggingFaceH4/zephyr-7b-beta")
>>> # Zephyr-beta is a conversational model, so let's pass it a chat instead of a single string
>>> generator([{"role": "user", "content": "What is the capital of France? Answer in one word."}], do_sample=False, max_new_tokens=2)
[{'generated_text': [{'role': 'user', 'content': 'What is the capital of France? Answer in one word.'}, {'role': 'assistant', 'content': 'Paris'}]}]

有关使用 pipeline 的基础知识,请参阅 pipeline 教程。您可以向此 pipeline 传递文本生成参数,以控制停止条件、解码策略等。有关文本生成参数的详细信息,请参阅 文本生成策略 和 文本生成。

该语言生成流水线目前可以通过 pipeline() 使用以下任务标识符进行加载:"text-generation"。

该流水线可使用的模型是采用自回归语言建模目标进行训练的模型。请参阅 [huggingface.co/models] 上可用的 文本补全模型 列表和 对话模型 列表。

__call__

< >

( text_inputs**kwargs ) → A list or a list of lists of dict

参数

  • text_inputs (str、list[str]、ChatType 或 list[ChatType]) — 一个或多个待补全的提示词(或一个提示词列表)。如果传入的是字符串或字符串列表,该流水线将对每个提示词进行续写。或者,也可以传入以字典列表形式表示的“chat”,其中每个字典包含 “role” 和 “content” 键;也可以传入此类 chat 的列表。当传入 chat 时,模型会先使用其 chat template 对其进行格式化,然后再传递给模型。
  • 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, optional) — 此参数表示你希望模型继续输入对话中的最后一条消息,而不是开始一条新消息,从而可以“预填充”其回复。 默认情况下,当输入对话中的最后一条消息的角色为 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 方法的额外关键字参数(参见 此处的 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

class transformers.TokenClassificationPipeline

< >

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

参数

  • model (PreTrainedModel) — 用于 pipeline 进行预测的模型。该模型必须继承自 PreTrainedModel。
  • tokenizer (PreTrainedTokenizer) — 流水线用于为模型编码数据的分词器。该对象继承自 PreTrainedTokenizer。
  • task (str,默认为 "") — 用于标识 pipeline 的任务标识符。
  • num_workers (int,可选,默认为 8) — 当 pipeline 使用 DataLoader(例如传入数据集,或在 GPU 上运行 PyTorch 模型时)时,要使用的 worker 数量。
  • batch_size (int,可选,默认为 1) — 当 pipeline 使用 DataLoader(例如传入数据集,或在 GPU 上运行 PyTorch 模型时),指定要使用的批次大小。对于推理任务,增大批次大小并不总是有益的,请参阅 使用 pipeline 进行批处理。
  • args_parser (ArgumentHandler,可选) — 负责解析所提供 pipeline 参数的对象引用。
  • device (int 或 str 或 torch.device,可选) — 流水线所分配的设备。若未设置,流水线将放置在第一个可用的加速器(CUDA、MPS、XPU 等)上,仅当没有可用加速器时才回退到 CPU;模型会自动移动至该设备。传入 device="cpu"(或 -1)可强制使用 CPU,传入正数序号或 "cuda:1" 可选择特定的加速器,或传入原生的 torch.device/str。如果 device 未设置,且 pipeline() 使用 device_map 在单个设备上加载模型,则模型将保留在该设备上。此参数不能与已通过 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, 可选) — 如果提供了 stride,则 pipeline 将应用于所有文本。文本会被拆分为大小为 model_max_length 的块。仅适用于 fast tokenizer 且 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 策略,但要求同一个词内的所有词元不能具有不同的标签。当存在歧义时,该词将直接使用其第一个词元的标签。
    • “average”:(仅适用于基于词元的模型)将使用 SIMPLE 策略,但要求同一词元内的各个 token 不能获得不同的标签。分数会先在 token 层面取平均值,然后应用得分最高的标签。
    • “max”:(仅适用于基于词元的模型)将使用 SIMPLE 策略,但要求同一词元内的各个 token 不能获得不同的标签。该词元实体的标签将直接取得分最高的 token 的标签。

使用任意 ModelForTokenClassification 的命名实体识别流水线。有关更多信息,请参阅 命名实体识别示例。

示例:

>>> from transformers import pipeline

>>> token_classifier = pipeline(model="Jean-Baptiste/camembert-ner", aggregation_strategy="simple")
>>> sentence = "Je m'appelle jean-baptiste et je vis à montréal"
>>> tokens = token_classifier(sentence)
>>> tokens
[{'entity_group': 'PER', 'score': 0.9931, 'word': 'jean-baptiste', 'start': 12, 'end': 26}, {'entity_group': 'LOC', 'score': 0.998, 'word': 'montréal', 'start': 38, 'end': 47}]

>>> token = tokens[0]
>>> # Start and end provide an easy way to highlight words in the original text.
>>> sentence[token["start"] : token["end"]]
' jean-baptiste'

>>> # Some models use the same idea to do part of speech.
>>> syntaxer = pipeline(model="vblagoje/bert-english-uncased-finetuned-pos", aggregation_strategy="simple")
>>> syntaxer("My name is Sarah and I live in London")
[{'entity_group': 'PRON', 'score': 0.999, 'word': 'my', 'start': 0, 'end': 2}, {'entity_group': 'NOUN', 'score': 0.997, 'word': 'name', 'start': 3, 'end': 7}, {'entity_group': 'AUX', 'score': 0.994, 'word': 'is', 'start': 8, 'end': 10}, {'entity_group': 'PROPN', 'score': 0.999, 'word': 'sarah', 'start': 11, 'end': 16}, {'entity_group': 'CCONJ', 'score': 0.999, 'word': 'and', 'start': 17, 'end': 20}, {'entity_group': 'PRON', 'score': 0.999, 'word': 'i', 'start': 21, 'end': 22}, {'entity_group': 'VERB', 'score': 0.998, 'word': 'live', 'start': 23, 'end': 27}, {'entity_group': 'ADP', 'score': 0.999, 'word': 'in', 'start': 28, 'end': 30}, {'entity_group': 'PROPN', 'score': 0.999, 'word': 'london', 'start': 31, 'end': 37}]

在 pipeline 教程 中了解使用 pipeline 的基础知识。

该 token 识别流水线目前可以通过 pipeline() 使用以下任务标识符进行加载:"ner"(用于预测序列中 token 的类别:人物、组织、地点或其他)。

该流水线可使用的模型是在 token 分类任务上经过微调的模型。有关可用模型的最新列表,请参阅 huggingface.co/models。

__call__

< >

( inputs: str | list[str]**kwargs: Any ) → A list or a list of list of dict

参数

  • 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

< >

( entities: list[dict]aggregation_strategy: AggregationStrategy )

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

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

gather_pre_entities

< >

( sentence: strinput_ids: ndarrayscores: ndarrayoffset_mapping: list[tuple[int, int]] | Nonespecial_tokens_mask: ndarrayaggregation_strategy: AggregationStrategyword_ids: list[int | None] | None = Noneword_to_chars_map: list[tuple[int, int]] | None = None )

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

group_entities

< >

( entities: list[dict] )

参数

  • entities (dict) — 流水线预测的实体。

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

group_sub_entities

< >

( entities: list[dict] )

参数

  • entities (dict) — 流水线预测的实体。

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

ZeroShotClassificationPipeline

类 transformers.ZeroShotClassificationPipeline

< >

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

参数

  • model (PreTrainedModel) — 用于 pipeline 进行预测的模型。该模型必须继承自 PreTrainedModel。
  • tokenizer (PreTrainedTokenizer) — 流水线用于为模型编码数据的分词器。该对象继承自 PreTrainedTokenizer。
  • task (str,默认为 "") — 用于标识 pipeline 的任务标识符。
  • num_workers (int,可选,默认为 8) — 当 pipeline 使用 DataLoader(例如传入数据集,或在 GPU 上运行 PyTorch 模型时)时,要使用的 worker 数量。
  • batch_size (int,可选,默认为 1) — 当 pipeline 使用 DataLoader(例如传入数据集,或在 GPU 上运行 PyTorch 模型时),指定要使用的批次大小。对于推理任务,增大批次大小并不总是有益的,请参阅 使用 pipeline 进行批处理。
  • args_parser (ArgumentHandler,可选) — 负责解析所提供 pipeline 参数的对象引用。
  • device (int 或 str 或 torch.device,可选) — 流水线所分配的设备。若未设置,流水线将放置在第一个可用的加速器(CUDA、MPS、XPU 等)上,仅当没有可用加速器时才回退到 CPU;模型会自动移动至该设备。传入 device="cpu"(或 -1)可强制使用 CPU,传入正数序号或 "cuda:1" 可选择特定的加速器,或传入原生的 torch.device/str。如果 device 未设置,且 pipeline() 使用 device_map 在单个设备上加载模型,则模型将保留在该设备上。此参数不能与已通过 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。

示例:

>>> from transformers import pipeline

>>> oracle = pipeline(model="facebook/bart-large-mnli")
>>> oracle(
...     "I have a problem with my iphone that needs to be resolved asap!!",
...     candidate_labels=["urgent", "not urgent", "phone", "tablet", "computer"],
... )
{'sequence': 'I have a problem with my iphone that needs to be resolved asap!!', 'labels': ['urgent', 'phone', 'computer', 'not urgent', 'tablet'], 'scores': [0.504, 0.479, 0.013, 0.003, 0.002]}

>>> oracle(
...     "I have a problem with my iphone that needs to be resolved asap!!",
...     candidate_labels=["english", "german"],
... )
{'sequence': 'I have a problem with my iphone that needs to be resolved asap!!', 'labels': ['english', 'german'], 'scores': [0.814, 0.186]}

在 pipeline 教程 中了解使用 pipeline 的基础知识。

当前,此 NLI 流水线可以通过 pipeline() 使用以下任务标识符进行加载:"zero-shot-classification"。

该流水线可使用的模型是在 NLI 任务上经过微调的模型。有关可用模型的最新列表,请参阅 huggingface.co/models。

__call__

< >

( sequences: str | list[str]*args**kwargs ) → A dict or a list of dict

参数

  • 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 文档。

多模态

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

DocumentQuestionAnsweringPipeline

class transformers.DocumentQuestionAnsweringPipeline

< >

( *args**kwargs )

参数

  • model (PreTrainedModel) — 用于 pipeline 进行预测的模型。该模型必须继承自 PreTrainedModel。
  • tokenizer (PreTrainedTokenizer) — 流水线用于为模型编码数据的分词器。该对象继承自 PreTrainedTokenizer。
  • image_processor (BaseImageProcessor) — 流水线将使用此图像处理器为模型编码数据。该对象继承自 BaseImageProcessor。
  • task (str,默认为 "") — 用于标识 pipeline 的任务标识符。
  • num_workers (int,可选,默认为 8) — 当 pipeline 使用 DataLoader(例如传入数据集,或在 GPU 上运行 PyTorch 模型时)时,要使用的 worker 数量。
  • batch_size (int,可选,默认为 1) — 当 pipeline 使用 DataLoader(例如传入数据集,或在 GPU 上运行 PyTorch 模型时),指定要使用的批次大小。对于推理任务,增大批次大小并不总是有益的,请参阅 使用 pipeline 进行批处理。
  • args_parser (ArgumentHandler,可选) — 负责解析所提供 pipeline 参数的对象引用。
  • device (int 或 str 或 torch.device,可选) — 流水线所分配的设备。若未设置,流水线将放置在第一个可用的加速器(CUDA、MPS、XPU 等)上,仅当没有可用加速器时才回退到 CPU;模型会自动移动至该设备。传入 device="cpu"(或 -1)可强制使用 CPU,传入正数序号或 "cuda:1" 可选择特定的加速器,或传入原生的 torch.device/str。如果 device 未设置,且 pipeline() 使用 device_map 在单个设备上加载模型,则模型将保留在该设备上。此参数不能与已通过 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

示例:

>>> 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 的基础知识。

此文档问答流水线目前可以通过 pipeline() 使用以下任务标识符进行加载:"document-question-answering"。

该流水线可使用的模型是在文档问答任务上经过微调的模型。 有关可用模型的最新列表,请参阅 huggingface.co/models。

__call__

< >

( image: typing.Union[ForwardRef('Image.Image'), str, list[dict[str, typing.Any]]]question: str | None = Noneword_boxes: tuple[str, list[float]] | None = None**kwargs: Any ) → A dict or a list of dict

参数

  • image (str 或 PIL.Image) — 该流水线支持三种类型的图像:
    • 包含指向图像的 http 链接的字符串
    • 包含图像本地路径的字符串
    • 直接以 PIL 加载的图像

    该 pipeline 接受单张图像或一批图像。如果提供单张图像,它可以被广播到多个问题。

  • question (str) — 要向文档提出的问题。
  • word_boxes (list[str, tuple[float, float, float, float]], 可选) — 一个包含单词及其边界框(归一化到 0->1000)的列表。如果您提供了此可选输入,那么对于需要这些信息的模型(例如 LayoutLM),流水线将直接使用这些单词和边界框,而无需对图像运行 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) — 是否接受“impossible”作为答案。
  • 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,则会自动使用 Tesseract OCR 引擎(如果可用)来提取单词和边界框,以供需要它们作为输入的 LayoutLM 类模型使用。对于 Donut,则不会运行 OCR。

您可以通过多种方式调用 pipeline:

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

FeatureExtractionPipeline

class transformers.FeatureExtractionPipeline

< >

( model: PreTrainedModeltokenizer: PreTrainedTokenizer | None = Nonefeature_extractor: PreTrainedFeatureExtractor | None = Noneimage_processor: BaseImageProcessor | None = Nonevideo_processor: BaseVideoProcessor | None = Noneprocessor: ProcessorMixin | None = Nonetask: str = ''device: int | torch.device | None = Nonebinary_output: bool = False**kwargs )

参数

  • model (PreTrainedModel) — 用于 pipeline 进行预测的模型。该模型必须继承自 PreTrainedModel。
  • tokenizer (PreTrainedTokenizer) — 流水线用于为模型编码数据的分词器。该对象继承自 PreTrainedTokenizer。
  • task (str,默认为 "") — 用于标识 pipeline 的任务标识符。
  • num_workers (int,可选,默认为 8) — 当 pipeline 使用 DataLoader(例如传入数据集,或在 GPU 上运行 PyTorch 模型时)时,要使用的 worker 数量。
  • batch_size (int,可选,默认为 1) — 当 pipeline 使用 DataLoader(例如传入数据集,或在 GPU 上运行 PyTorch 模型时),指定要使用的批次大小。对于推理任务,增大批次大小并不总是有益的,请参阅 使用 pipeline 进行批处理。
  • args_parser (ArgumentHandler,可选) — 负责解析所提供 pipeline 参数的对象引用。
  • device (int 或 str 或 torch.device,可选) — 流水线所分配的设备。若未设置,流水线将放置在第一个可用的加速器(CUDA、MPS、XPU 等)上,仅当没有可用加速器时才回退到 CPU;模型会自动移动至该设备。传入 device="cpu"(或 -1)可强制使用 CPU,传入正数序号或 "cuda:1" 可选择特定的加速器,或传入原生的 torch.device/str。如果 device 未设置,且 pipeline() 使用 device_map 在单个设备上加载模型,则模型将保留在该设备上。此参数不能与已通过 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 中提取隐藏状态,这些隐藏状态可作为下游任务中的特征使用。

示例:

>>> from transformers import pipeline

>>> extractor = pipeline(model="google-bert/bert-base-uncased", task="feature-extraction")
>>> result = extractor("This is a simple test.", return_tensors=True)
>>> result.shape  # This is a tensor of shape [1, sequence_length, hidden_dimension] representing the input string.
torch.Size([1, 8, 768])

在 pipeline 教程 中了解使用 pipeline 的基础知识。

当前,此特征提取流水线可通过 pipeline() 加载,使用的任务标识符为:"feature-extraction"。

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

__call__

< >

( *args: str | list[str]**kwargs: Any ) → A nested list of float

参数

  • args(str 或 list[str])— 一个或多个文本(或一个文本列表),用于提取其特征。

返回值

float 的嵌套列表

模型计算出的特征。

提取输入文本的特征。

ImageFeatureExtractionPipeline

class transformers.ImageFeatureExtractionPipeline

< >

( model: PreTrainedModeltokenizer: PreTrainedTokenizer | None = Nonefeature_extractor: PreTrainedFeatureExtractor | None = Noneimage_processor: BaseImageProcessor | None = Nonevideo_processor: BaseVideoProcessor | None = Noneprocessor: ProcessorMixin | None = Nonetask: str = ''device: int | torch.device | None = Nonebinary_output: bool = False**kwargs )

参数

  • model (PreTrainedModel) — 用于 pipeline 进行预测的模型。该模型必须继承自 PreTrainedModel。
  • image_processor (BaseImageProcessor) — 流水线将使用此图像处理器为模型编码数据。该对象继承自 BaseImageProcessor。
  • task (str,默认为 "") — 用于标识 pipeline 的任务标识符。
  • num_workers (int,可选,默认为 8) — 当 pipeline 使用 DataLoader(例如传入数据集,或在 GPU 上运行 PyTorch 模型时)时,要使用的 worker 数量。
  • batch_size (int,可选,默认为 1) — 当 pipeline 使用 DataLoader(例如传入数据集,或在 GPU 上运行 PyTorch 模型时),指定要使用的批次大小。对于推理任务,增大批次大小并不总是有益的,请参阅 使用 pipeline 进行批处理。
  • args_parser (ArgumentHandler,可选) — 负责解析所提供 pipeline 参数的对象引用。
  • device (int 或 str 或 torch.device,可选) — 流水线所分配的设备。若未设置,流水线将放置在第一个可用的加速器(CUDA、MPS、XPU 等)上,仅当没有可用加速器时才回退到 CPU;模型会自动移动至该设备。传入 device="cpu"(或 -1)可强制使用 CPU,传入正数序号或 "cuda:1" 可选择特定的加速器,或传入原生的 torch.device/str。如果 device 未设置,且 pipeline() 使用 device_map 在单个设备上加载模型,则模型将保留在该设备上。此参数不能与已通过 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 中提取隐藏状态,这些隐藏状态可作为下游任务中的特征使用。

示例:

>>> 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 的基础知识。

当前,此图像特征提取流水线可通过 pipeline() 使用任务标识符 "image-feature-extraction" 进行加载。

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

__call__

< >

( *args: typing.Union[str, ForwardRef('Image.Image'), list['Image.Image'], list[str]]**kwargs: Any ) → A nested list of float

参数

  • images (str, list[str], PIL.Image 或 list[PIL.Image]) — 该流水线支持三种类型的图像:
    • 包含指向图像的 http 链接的字符串
    • 包含图像本地路径的字符串
    • 直接以 PIL 加载的图像

    Pipeline 接受单张图像或一批图像,随后必须以字符串形式传入。 批次中的图像必须全部采用相同的格式:全部为 http 链接、全部为本地路径,或全部为 PIL 图像。

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

返回值

float 的嵌套列表

模型计算出的特征。

提取输入的特征。

ImageTextToTextPipeline

class transformers.ImageTextToTextPipeline

< >

( *args**kwargs )

参数

  • model (PreTrainedModel) — 用于 pipeline 进行预测的模型。该模型必须继承自 PreTrainedModel。
  • processor (ProcessorMixin) — 流水线将使用该处理器为模型编码数据。该对象继承自 ProcessorMixin。Processor 是一个复合对象,可能包含 tokenizer、feature_extractor 和 image_processor。
  • task (str,默认为 "") — 用于标识 pipeline 的任务标识符。
  • num_workers (int,可选,默认为 8) — 当 pipeline 使用 DataLoader(例如传入数据集,或在 GPU 上运行 PyTorch 模型时)时,要使用的 worker 数量。
  • batch_size (int,可选,默认为 1) — 当 pipeline 使用 DataLoader(例如传入数据集,或在 GPU 上运行 PyTorch 模型时),指定要使用的批次大小。对于推理任务,增大批次大小并不总是有益的,请参阅 使用 pipeline 进行批处理。
  • args_parser (ArgumentHandler,可选) — 负责解析所提供 pipeline 参数的对象引用。
  • device (int 或 str 或 torch.device,可选) — 流水线所分配的设备。若未设置,流水线将放置在第一个可用的加速器(CUDA、MPS、XPU 等)上,仅当没有可用加速器时才回退到 CPU;模型会自动移动至该设备。传入 device="cpu"(或 -1)可强制使用 CPU,传入正数序号或 "cuda:1" 可选择特定的加速器,或传入原生的 torch.device/str。如果 device 未设置,且 pipeline() 使用 device_map 在单个设备上加载模型,则模型将保留在该设备上。此参数不能与已通过 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

示例:

>>> from transformers import pipeline

>>> pipe = pipeline(task="image-text-to-text", model="Salesforce/blip-image-captioning-base")
>>> pipe("https://huggingface.co/datasets/Narsil/image_dummy/raw/main/parrots.png", text="A photo of")
[{'generated_text': 'a photo of two birds'}]
>>> from transformers import pipeline

>>> pipe = pipeline("image-text-to-text", model="llava-hf/llava-interleave-qwen-0.5b-hf")
>>> messages = [
>>>     {
>>>         "role": "user",
>>>         "content": [
>>>             {
>>>                 "type": "image",
>>>                 "url": "https://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 的基础知识。

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

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

__call__

< >

( images: typing.Union[str, list[str], list[list[str]], ForwardRef('Image.Image'), list['Image.Image'], list[list['Image.Image']], list[dict], NoneType] = Nonetext: str | list[str] | list[dict] | None = None**kwargs ) → A list or a list of list of dict

参数

  • images (str, list[str], PIL.Image, list[PIL.Image], list[dict[str, Union[str, PIL.Image]]]`) — 该流水线支持三种类型的图像:
    • 包含指向图像的 HTTP(s) 链接的字符串
    • 包含图像本地路径的字符串
    • 直接以 PIL 加载的图像

    该 pipeline 接受单张图像或一批图像。最后,此 pipeline 还支持聊天格式(参见 text),该参数中可包含图像和文本。

  • 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, optional) — 此参数表示你希望模型继续输入对话中的最后一条消息,而不是开始一条新消息,从而可以“预填充”其回复。 默认情况下,当输入对话中的最后一条消息的角色为 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

class transformers.AnyToAnyPipeline

< >

( *args**kwargs )

参数

  • model (PreTrainedModel) — 用于 pipeline 进行预测的模型。该模型必须继承自 PreTrainedModel。
  • processor (ProcessorMixin) — 流水线将使用该处理器为模型编码数据。该对象继承自 ProcessorMixin。Processor 是一个复合对象,可能包含 tokenizer、feature_extractor 和 image_processor。
  • task (str,默认为 "") — 用于标识 pipeline 的任务标识符。
  • num_workers (int,可选,默认为 8) — 当 pipeline 使用 DataLoader(例如传入数据集,或在 GPU 上运行 PyTorch 模型时)时,要使用的 worker 数量。
  • batch_size (int,可选,默认为 1) — 当 pipeline 使用 DataLoader(例如传入数据集,或在 GPU 上运行 PyTorch 模型时),指定要使用的批次大小。对于推理任务,增大批次大小并不总是有益的,请参阅 使用 pipeline 进行批处理。
  • args_parser (ArgumentHandler,可选) — 负责解析所提供 pipeline 参数的对象引用。
  • device (int 或 str 或 torch.device,可选) — 流水线所分配的设备。若未设置,流水线将放置在第一个可用的加速器(CUDA、MPS、XPU 等)上,仅当没有可用加速器时才回退到 CPU;模型会自动移动至该设备。传入 device="cpu"(或 -1)可强制使用 CPU,传入正数序号或 "cuda:1" 可选择特定的加速器,或传入原生的 torch.device/str。如果 device 未设置,且 pipeline() 使用 device_map 在单个设备上加载模型,则模型将保留在该设备上。此参数不能与已通过 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

示例:

>>> 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'}]
>>> 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 的基础知识。

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

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

__call__

< >

( text: str | list[str] | list[dict] | None = Noneimages: 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] = Nonevideos: 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] = Noneaudio: typing.Union[str, list[str], numpy.ndarray, ForwardRef('torch.Tensor'), collections.abc.Sequence[numpy.ndarray], collections.abc.Sequence['torch.Tensor'], NoneType] = None**kwargs ) → A list or a list of list of dict

参数

  • text (str, list[str], list[dict]) — 用于生成的文本。如果传入字符串列表,则列表的长度应与图像数量相同。文本也可以遵循聊天格式:一个字典列表,其中每个字典代表对话中的一条消息。每个字典应包含两个键:‘role’ 和 ‘content’。‘role’ 应为 ‘user’、‘system’ 或 ‘assistant’ 之一。‘content’ 应为一个字典列表,包含消息的文本和消息类型。
  • images (str, list[str], ImageInput) — 该流水线支持三种类型的图像:
    • 包含指向图像的 HTTP(s) 链接的字符串
    • 包含图像本地路径的字符串
    • 直接以 PIL 加载的图像

    该 pipeline 接受单张图像或一批图像。最后,此 pipeline 还支持聊天格式(参见 text),该参数中可包含图像和文本。

  • videos (str, list[str], VideoInput) — 该流水线支持三种类型的视频:
    • 包含指向视频的 HTTP(s) 链接的字符串
    • 包含视频本地路径的字符串
    • 以数组格式加载并解码的视频

    该 pipeline 接受单个视频或一批视频。最后,此 pipeline 还支持聊天格式(参见 text),该参数中可包含视频和文本。

  • audio (str, list[str], AudioInput) — 该流水线支持三种类型的音频输入:
    • 包含指向音频的 HTTP(s) 链接的字符串
    • 包含音频本地路径的字符串
    • 直接在 PIL 中加载的音频

    该 pipeline 接受单个 audios 或一批 audios。最后,此 pipeline 还支持聊天格式(参见 text),该参数中包含 audios 和文本。

  • 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, optional) — 此参数表示你希望模型继续输入对话中的最后一条消息,而不是开始一条新消息,从而可以“预填充”其回复。 默认情况下,当输入对话中的最后一条消息的角色为 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

class transformers.MaskGenerationPipeline

< >

( **kwargs )

参数

  • model (PreTrainedModel) — 用于 pipeline 进行预测的模型。该模型必须继承自 PreTrainedModel。
  • image_processor (BaseImageProcessor) — 流水线将使用此图像处理器为模型编码数据。该对象继承自 BaseImageProcessor。
  • task (str,默认为 "") — 用于标识 pipeline 的任务标识符。
  • num_workers (int,可选,默认为 8) — 当 pipeline 使用 DataLoader(例如传入数据集,或在 GPU 上运行 PyTorch 模型时)时,要使用的 worker 数量。
  • batch_size (int,可选,默认为 1) — 当 pipeline 使用 DataLoader(例如传入数据集,或在 GPU 上运行 PyTorch 模型时),指定要使用的批次大小。对于推理任务,增大批次大小并不总是有益的,请参阅 使用 pipeline 进行批处理。
  • args_parser (ArgumentHandler,可选) — 负责解析所提供 pipeline 参数的对象引用。
  • device (int 或 str 或 torch.device,可选) — 流水线所分配的设备。若未设置,流水线将放置在第一个可用的加速器(CUDA、MPS、XPU 等)上,仅当没有可用加速器时才回退到 CPU;模型会自动移动至该设备。传入 device="cpu"(或 -1)可强制使用 CPU,传入正数序号或 "cuda:1" 可选择特定的加速器,或传入原生的 torch.device/str。如果 device 未设置,且 pipeline() 使用 device_map 在单个设备上加载模型,则模型将保留在该设备上。此参数不能与已通过 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 为图像自动生成掩码。该流水线在给定图像的情况下,预测该图像的二值掩码。它是一个 ChunkPipeline,因为你可以将点分割到 mini-batch 中,以避免 OOM 问题。使用 points_per_batch 参数来控制同时处理的点数。默认值为 64。

该流水线分三步运行:

  1. preprocess:生成一个由 1024 个均匀分布的点组成的网格,以及边界框和点标签。有关点和边界框创建方式的更多详细信息,请查看 _generate_crop_boxes 函数。图像还会使用 image_processor 进行预处理。此函数 yields 一个包含 points_per_batch 个点的 mini-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,仅保留相关的掩码。

示例:

>>> from transformers import pipeline

>>> generator = pipeline(model="facebook/sam-vit-base", task="mask-generation")
>>> outputs = generator(
...     "http://images.cocodataset.org/val2017/000000039769.jpg",
... )

>>> outputs = generator(
...     "https://huggingface.co/datasets/Narsil/image_dummy/raw/main/parrots.png", points_per_batch=128
... )

在 pipeline 教程 中了解使用 pipeline 的基础知识。

当前,此分割流水线可以通过 pipeline() 加载,使用的任务标识符为:"mask-generation"。

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

__call__

< >

( image: typing.Union[str, ForwardRef('Image.Image'), list[str], list['Image.Image']]*args: Any**kwargs: Any ) → Dict

参数

  • 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

class transformers.Pipeline

< >

( model: PreTrainedModeltokenizer: PreTrainedTokenizer | None = Nonefeature_extractor: PreTrainedFeatureExtractor | None = Noneimage_processor: BaseImageProcessor | None = Nonevideo_processor: BaseVideoProcessor | None = Noneprocessor: ProcessorMixin | None = Nonetask: str = ''device: int | torch.device | None = Nonebinary_output: bool = False**kwargs )

参数

  • model (PreTrainedModel) — 用于 pipeline 进行预测的模型。该模型必须继承自 PreTrainedModel。
  • tokenizer (PreTrainedTokenizer) — 流水线用于为模型编码数据的分词器。该对象继承自 PreTrainedTokenizer。
  • feature_extractor (SequenceFeatureExtractor) — 流水线将使用该特征提取器为模型编码数据。此对象继承自 SequenceFeatureExtractor。
  • image_processor (BaseImageProcessor) — 流水线将使用此图像处理器为模型编码数据。该对象继承自 BaseImageProcessor。
  • processor (ProcessorMixin) — 流水线将使用该处理器为模型编码数据。该对象继承自 ProcessorMixin。Processor 是一个复合对象,可能包含 tokenizer、feature_extractor 和 image_processor。
  • task (str,默认为 "") — 用于标识 pipeline 的任务标识符。
  • num_workers (int,可选,默认为 8) — 当 pipeline 使用 DataLoader(例如传入数据集,或在 GPU 上运行 PyTorch 模型时)时,要使用的 worker 数量。
  • batch_size (int,可选,默认为 1) — 当 pipeline 使用 DataLoader(例如传入数据集,或在 GPU 上运行 PyTorch 模型时),指定要使用的批次大小。对于推理任务,增大批次大小并不总是有益的,请参阅 使用 pipeline 进行批处理。
  • args_parser (ArgumentHandler,可选) — 负责解析所提供 pipeline 参数的对象引用。
  • device (int 或 str 或 torch.device,可选) — 流水线所分配的设备。若未设置,流水线将放置在第一个可用的加速器(CUDA、MPS、XPU 等)上,仅当没有可用加速器时才回退到 CPU;模型会自动移动至该设备。传入 device="cpu"(或 -1)可强制使用 CPU,传入正数序号或 "cuda:1" 可选择特定的加速器,或传入原生的 torch.device/str。如果 device 未设置,且 pipeline() 使用 device_map 在单个设备上加载模型,则模型将保留在该设备上。此参数不能与已通过 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('feature-extraction'),会以嵌套列表的形式输出大型张量对象。为了避免将如此庞大的结构以文本数据的形式转储,我们提供了 binary_output 构造参数。如果将其设置为 True,输出将以 pickle 格式存储。

check_model_type

< >

( supported_models: list[str] | dict )

参数

  • supported_models (list[str] 或 dict) — 该 pipeline 支持的模型列表,或一个以模型类为值的字典。

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

设备放置

< >

( )

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

示例:

# 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

< >

( **inputs ) → dict[str, torch.Tensor]

参数

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

返回值

dict[str, torch.Tensor]

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

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

后处理

< >

( model_outputs: ModelOutput**postprocess_parameters: dict )

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

predict

< >

( X )

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

预处理

< >

( input_: Any**preprocess_parameters: dict )

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

push_to_hub

< >

( repo_id: strcommit_message: str | None = Nonecommit_description: str | None = Noneprivate: bool | None = Nonetoken: bool | str | None = Nonerevision: str | None = Nonecreate_pr: bool = Falsemax_shard_size: int | str | None = '50GB'tags: list[str] | None = None )

参数

  • 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") — 仅适用于模型。分片前检查点的最大大小。分片后的每个检查点大小都将小于该值。如果以字符串形式表示,则必须为数字后跟单位(例如 "5MB")。
  • tags (list[str],可选) — 要推送到 Hub 的标签列表。

将 pipeline 文件上传到 🤗 Model Hub。

示例:

from transformers import pipeline

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

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

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

save_pretrained

< >

( save_directory: str | os.PathLike**kwargs: Any )

参数

  • save_directory (str 或 os.PathLike) — 保存目录的路径。如果该目录不存在,将会自动创建。
  • kwargs (dict[str, Any],可选) — 传递给 push_to_hub() 方法的额外关键字参数。

保存 pipeline 的模型和 tokenizer。

transform

< >

( X )

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

Update on GitHub