Transformers 文档
管道 (Pipelines)
并获得增强的文档体验
开始使用
管道 (Pipelines)
管道是使用模型进行推理的一种极佳且简便的方式。这些管道是封装了库中大部分复杂代码的对象,为多种任务提供了简单的 API,包括命名实体识别、掩码语言建模、情感分析、特征提取和问答。有关使用示例,请参阅任务摘要。
需要注意的管道抽象有两个类别:
- pipeline() 是最强大的对象,它封装了所有其他管道。
- 针对音频、计算机视觉、自然语言处理和多模态任务,提供了特定任务的管道。
管道抽象
pipeline 抽象是所有其他可用管道的包装器。它的实例化方式与任何其他管道一样,但可以提供额外的便利性。
对单个项目的简单调用
>>> pipe = pipeline("text-classification")
>>> pipe("This restaurant is awesome")
[{'label': 'POSITIVE', 'score': 0.9998743534088135}]
如果你想使用模型中心中的特定模型,如果该模型已经定义了任务,你可以忽略任务参数。
>>> pipe = pipeline(model="FacebookAI/roberta-large-mnli")
>>> pipe("This restaurant is awesome")
[{'label': 'NEUTRAL', 'score': 0.7313136458396912}]
要对多个项目调用管道,你可以用一个 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("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: typing.Optional[str] = None model: typing.Union[str, ForwardRef('PreTrainedModel'), ForwardRef('TFPreTrainedModel'), NoneType] = None config: typing.Union[str, transformers.configuration_utils.PretrainedConfig, NoneType] = None tokenizer: typing.Union[str, transformers.tokenization_utils.PreTrainedTokenizer, ForwardRef('PreTrainedTokenizerFast'), NoneType] = None feature_extractor: typing.Union[str, ForwardRef('SequenceFeatureExtractor'), NoneType] = None image_processor: typing.Union[str, transformers.image_processing_utils.BaseImageProcessor, NoneType] = None processor: typing.Union[str, transformers.processing_utils.ProcessorMixin, NoneType] = None framework: typing.Optional[str] = None revision: typing.Optional[str] = None use_fast: bool = True token: typing.Union[str, bool, NoneType] = None device: typing.Union[int, str, ForwardRef('torch.device'), NoneType] = None device_map: typing.Union[str, dict[str, typing.Union[int, str]], NoneType] = None torch_dtype: typing.Union[str, ForwardRef('torch.dtype'), NoneType] = 'auto' trust_remote_code: typing.Optional[bool] = None model_kwargs: typing.Optional[dict[str, typing.Any]] = None pipeline_class: typing.Optional[typing.Any] = None **kwargs: typing.Any ) → Pipeline
参数
- task (
str
) — 定义将返回哪个管道的任务。目前接受的任务有:"audio-classification"
: 将返回一个 AudioClassificationPipeline。"automatic-speech-recognition"
: 将返回一个 AutomaticSpeechRecognitionPipeline。"depth-estimation"
: 将返回一个 DepthEstimationPipeline。"document-question-answering"
: 将返回一个 DocumentQuestionAnsweringPipeline。"feature-extraction"
: 将返回一个 FeatureExtractionPipeline。"fill-mask"
: 将返回一个 FillMaskPipeline。"image-classification"
: 将返回一个 ImageClassificationPipeline。"image-feature-extraction"
: 将返回一个 ImageFeatureExtractionPipeline。"image-segmentation"
: 将返回一个 ImageSegmentationPipeline。"image-text-to-text"
: 将返回一个 ImageTextToTextPipeline。"image-to-image"
: 将返回一个 ImageToImagePipeline。"image-to-text"
: 将返回一个 ImageToTextPipeline。"mask-generation"
: 将返回一个 MaskGenerationPipeline。"object-detection"
: 将返回一个 ObjectDetectionPipeline。"question-answering"
: 将返回一个 QuestionAnsweringPipeline。"summarization"
: 将返回一个 SummarizationPipeline。"table-question-answering"
: 将返回一个 TableQuestionAnsweringPipeline。"text2text-generation"
: 将返回一个 Text2TextGenerationPipeline。"text-classification"
(别名"sentiment-analysis"
可用): 将返回一个 TextClassificationPipeline。"text-generation"
: 将返回一个 TextGenerationPipeline。"text-to-audio"
(别名"text-to-speech"
可用): 将返回一个 TextToAudioPipeline。"token-classification"
(别名"ner"
可用): 将返回一个 TokenClassificationPipeline。"translation"
: 将返回一个 TranslationPipeline。"translation_xx_to_yy"
: 将返回一个 TranslationPipeline。"video-classification"
: 将返回一个 VideoClassificationPipeline。"visual-question-answering"
: 将返回一个 VisualQuestionAnsweringPipeline。"zero-shot-classification"
: 将返回一个 ZeroShotClassificationPipeline。"zero-shot-image-classification"
: 将返回一个 ZeroShotImageClassificationPipeline。"zero-shot-audio-classification"
: 将返回一个 ZeroShotAudioClassificationPipeline。"zero-shot-object-detection"
: 将返回一个 ZeroShotObjectDetectionPipeline。
- model (
str
或 PreTrainedModel 或 TFPreTrainedModel, 可选) — 管道用于进行预测的模型。这可以是一个模型标识符,也可以是一个继承自 PreTrainedModel (适用于 PyTorch) 或 TFPreTrainedModel (适用于 TensorFlow) 的预训练模型的实际实例。如果未提供,将加载
task
的默认模型。 - config (
str
或 PretrainedConfig, 可选) — 管道用于实例化模型的配置。这可以是一个模型标识符,也可以是一个继承自 PretrainedConfig 的实际预训练模型配置。如果未提供,将使用所请求模型的默认配置文件。这意味着如果给定了
model
,将使用其默认配置。但是,如果未提供model
,则会使用该task
的默认模型的配置。 - tokenizer (
str
或 PreTrainedTokenizer, 可选) — 管道用于为模型编码数据的分词器。这可以是一个模型标识符,也可以是一个继承自 PreTrainedTokenizer 的实际预训练分词器。如果未提供,将加载给定
model
的默认分词器(如果它是一个字符串)。如果model
未指定或不是字符串,则加载config
的默认分词器(如果它是一个字符串)。然而,如果config
也未给定或不是字符串,则将加载给定task
的默认分词器。 - feature_extractor (
str
或PreTrainedFeatureExtractor
, 可选) — 管道用于为模型编码数据的特征提取器。这可以是一个模型标识符,也可以是一个继承自PreTrainedFeatureExtractor
的实际预训练特征提取器。特征提取器用于非 NLP 模型,例如语音或视觉模型以及多模态模型。多模态模型还需要传入一个分词器。
如果未提供,将加载给定
model
的默认特征提取器(如果它是一个字符串)。如果model
未指定或不是字符串,则加载config
的默认特征提取器(如果它是一个字符串)。然而,如果config
也未给定或不是字符串,则将加载给定task
的默认特征提取器。 - image_processor (
str
或 BaseImageProcessor, 可选) — 管道用于为模型预处理图像的图像处理器。这可以是一个模型标识符,也可以是一个继承自 BaseImageProcessor 的实际图像处理器。图像处理器用于视觉模型和需要图像输入的多模态模型。多模态模型还需要传入一个分词器。
如果未提供,将加载给定
model
的默认图像处理器(如果它是一个字符串)。如果model
未指定或不是字符串,则加载config
的默认图像处理器(如果它是一个字符串)。 - processor (
str
或 ProcessorMixin, 可选) — 管道用于为模型预处理数据的处理器。这可以是一个模型标识符,也可以是一个继承自 ProcessorMixin 的实际处理器。处理器用于需要多模态输入的多模态模型,例如,一个同时需要文本和图像输入的模型。
如果未提供,将加载给定
model
的默认处理器(如果它是一个字符串)。如果model
未指定或不是字符串,则加载config
的默认处理器(如果它是一个字符串)。 - framework (
str
, 可选) — 要使用的框架,可以是"pt"
(PyTorch) 或"tf"
(TensorFlow)。指定的框架必须已安装。如果未指定框架,将默认为当前安装的框架。如果未指定框架且两个框架都已安装,将默认为
model
的框架,或者在未提供模型时默认为 PyTorch。 - revision (
str
, 可选, 默认为"main"
) — 当传递任务名称或字符串模型标识符时:要使用的特定模型版本。它可以是分支名称、标签名称或提交 ID,因为我们使用基于 git 的系统在 huggingface.co 上存储模型和其他工件,所以revision
可以是 git 允许的任何标识符。 - use_fast (
bool
, 可选, 默认为True
) — 是否尽可能使用快速分词器(一个 PreTrainedTokenizerFast)。 - use_auth_token (
str
或 bool, 可选) — 用于远程文件的 HTTP 持有者授权令牌。如果为True
,将使用运行huggingface-cli login
时生成的令牌(存储在~/.huggingface
中)。 - device (
int
或str
或torch.device
) — 定义此管道将分配到的设备(例如,"cpu"
,"cuda:1"
,"mps"
或 GPU 序号1
)。 - device_map (
str
或dict[str, Union[int, str, torch.device]
, 可选) — 直接作为model_kwargs
发送(只是一个更简单的快捷方式)。当存在accelerate
库时,设置device_map="auto"
可自动计算最优的device_map
(更多信息请参见此处)。不要同时使用
device_map
和device
,因为它们会冲突。 - torch_dtype (
str
或torch.dtype
, 可选) — 直接作为model_kwargs
发送(只是一个更简单的快捷方式),以使用此模型的可用精度(torch.float16
,torch.bfloat16
, … 或"auto"
)。 - trust_remote_code (
bool
, 可选, 默认为False
) — 是否允许在模型中心上定义的自定义代码在其自己的建模、配置、分词甚至管道文件中。此选项仅应为您信任且已阅读其代码的仓库设置为True
,因为它将在您的本地计算机上执行模型中心上的代码。 - model_kwargs (
dict[str, Any]
, 可选) — 传递给模型的from_pretrained(..., **model_kwargs)
函数的额外关键字参数字典。 - kwargs (
dict[str, Any]
, 可选) — 传递给特定管道初始化的额外关键字参数(有关可能的值,请参阅相应管道类的文档)。
返回
适合该任务的管道。
用于构建 Pipeline 的实用工厂方法。
一个管道由以下部分组成:
示例
>>> from transformers import pipeline, AutoModelForTokenClassification, AutoTokenizer
>>> # Sentiment analysis pipeline
>>> analyzer = pipeline("sentiment-analysis")
>>> # Question answering pipeline, specifying the checkpoint identifier
>>> oracle = pipeline(
... "question-answering", model="distilbert/distilbert-base-cased-distilled-squad", tokenizer="google-bert/bert-base-cased"
... )
>>> # Named entity recognition pipeline, passing in a specific model and tokenizer
>>> model = AutoModelForTokenClassification.from_pretrained("dbmdz/bert-large-cased-finetuned-conll03-english")
>>> tokenizer = AutoTokenizer.from_pretrained("google-bert/bert-base-cased")
>>> recognizer = pipeline("ner", model=model, tokenizer=tokenizer)
管道批处理
所有管道都可以使用批处理。这在管道使用其流式处理能力时(即传递列表、`Dataset` 或 `generator` 时)会起作用。
from transformers import pipeline
from transformers.pipelines.pt_utils import KeyDataset
import datasets
dataset = datasets.load_dataset("imdb", name="plain_text", split="unsupervised")
pipe = pipeline("text-classification", device=0)
for out in pipe(KeyDataset(dataset, "text"), batch_size=8, truncation="only_first"):
print(out)
# [{'label': 'POSITIVE', 'score': 0.9998743534088135}]
# Exactly the same output as before, but the content are passed
# as batches to the model
然而,这并不一定能提升性能。根据硬件、数据和所使用的实际模型,它可能会带来 10 倍的加速,也可能导致 5 倍的减速。
在大多数情况下能提速的例子
from transformers import pipeline
from torch.utils.data import Dataset
from tqdm.auto import tqdm
pipe = pipeline("text-classification", device=0)
class MyDataset(Dataset):
def __len__(self):
return 5000
def __getitem__(self, i):
return "This is a test"
dataset = MyDataset()
for batch_size in [1, 8, 64, 256]:
print("-" * 30)
print(f"Streaming batch_size={batch_size}")
for out in tqdm(pipe(dataset, batch_size=batch_size), total=len(dataset)):
pass
# On GTX 970
------------------------------
Streaming no batching
100%|██████████████████████████████████████████████████████████████████████| 5000/5000 [00:26<00:00, 187.52it/s]
------------------------------
Streaming batch_size=8
100%|█████████████████████████████████████████████████████████████████████| 5000/5000 [00:04<00:00, 1205.95it/s]
------------------------------
Streaming batch_size=64
100%|█████████████████████████████████████████████████████████████████████| 5000/5000 [00:02<00:00, 2478.24it/s]
------------------------------
Streaming batch_size=256
100%|█████████████████████████████████████████████████████████████████████| 5000/5000 [00:01<00:00, 2554.43it/s]
(diminishing returns, saturated the GPU)
在大多数情况下会减速的例子
class MyDataset(Dataset):
def __len__(self):
return 5000
def __getitem__(self, i):
if i % 64 == 0:
n = 100
else:
n = 1
return "This is a test" * n
这是一个偶尔出现的与其他句子相比非常长的句子。在这种情况下,**整个**批次都需要是 400 个词元长,所以整个批次的大小将是 [64, 400] 而不是 [64, 4],从而导致了严重的减速。更糟糕的是,在更大的批次上,程序会直接崩溃。
------------------------------
Streaming no batching
100%|█████████████████████████████████████████████████████████████████████| 1000/1000 [00:05<00:00, 183.69it/s]
------------------------------
Streaming batch_size=8
100%|█████████████████████████████████████████████████████████████████████| 1000/1000 [00:03<00:00, 265.74it/s]
------------------------------
Streaming batch_size=64
100%|██████████████████████████████████████████████████████████████████████| 1000/1000 [00:26<00:00, 37.80it/s]
------------------------------
Streaming batch_size=256
0%| | 0/1000 [00:00<?, ?it/s]
Traceback (most recent call last):
File "/home/nicolas/src/transformers/test.py", line 42, in <module>
for out in tqdm(pipe(dataset, batch_size=256), total=len(dataset)):
....
q = q / math.sqrt(dim_per_head) # (bs, n_heads, q_length, dim_per_head)
RuntimeError: CUDA out of memory. Tried to allocate 376.00 MiB (GPU 0; 3.95 GiB total capacity; 1.72 GiB already allocated; 354.88 MiB free; 2.46 GiB reserved in total by PyTorch)
对于这个问题,没有好的(通用的)解决方案,具体效果可能因您的使用情况而异。经验法则如下:
对于用户来说,一个经验法则是:
在你的负载和硬件上测量性能。测量,测量,再测量。真实数据是唯一的标准。
如果你受延迟限制(实时产品进行推理),不要进行批处理。
如果你使用 CPU,不要进行批处理。
如果你关注吞吐量(你想在一堆静态数据上运行你的模型),在 GPU 上,那么:
- 如果你对序列长度的大小没有概念(“自然”数据),默认不要批处理,测量并尝试性地添加它,并添加 OOM 检查以便在失败时恢复(如果你不控制序列长度,它迟早会失败)。
- 如果你的序列长度非常规整,那么批处理很可能非常有效,测量并增加批处理大小直到出现 OOMs。
- GPU 越大,批处理越有可能带来更好的效果。
一旦你启用了批处理,请确保你能很好地处理 OOMs。
管道分块批处理
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)
这对你的代码来说应该是透明的,因为管道的使用方式是相同的。
这是一个简化的视图,因为管道可以自动处理批处理!这意味着你不需要关心你的输入实际上会触发多少次前向传播,你可以独立于输入来优化 `batch_size`。上一节的注意事项仍然适用。
管道 FP16 推理
模型可以在 FP16 模式下运行,这在 GPU 上可以显著加快速度并节省内存。大多数模型不会因此遭受明显的性能损失。模型越大,性能损失的可能性就越小。
要启用 FP16 推理,您只需向管道构造函数传递 `torch_dtype=torch.float16` 或 `torch_dtype='float16'`。请注意,这仅适用于具有 PyTorch 后端的模型。您的输入将在内部转换为 FP16。
管道自定义代码
如果你想覆盖一个特定的管道。
请随时为你的任务创建一个 issue,管道的目标是易于使用并支持大多数情况,因此 `transformers` 也许可以支持你的用例。
如果你想简单尝试,可以:
- 子类化您选择的管道
class MyPipeline(TextClassificationPipeline):
def postprocess():
# Your code goes here
scores = scores * 100
# And here
my_pipeline = MyPipeline(model=model, tokenizer=tokenizer, ...)
# or if you use *pipeline* function, then:
my_pipeline = pipeline(model="xxxx", pipeline_class=MyPipeline)
这应该能让你实现所有你想要的自定义代码。
实现一个管道
音频
可用于音频任务的管道包括以下内容。
AudioClassificationPipeline
class transformers.AudioClassificationPipeline
< 来源 >( *args **kwargs )
参数
- model (PreTrainedModel 或 TFPreTrainedModel) — 管道用于进行预测的模型。这需要是一个继承自 PyTorch 的 PreTrainedModel 或 TensorFlow 的 TFPreTrainedModel 的模型。
- feature_extractor (SequenceFeatureExtractor) — 管道用于为模型编码数据的特征提取器。该对象继承自 SequenceFeatureExtractor。
- modelcard (
str
或ModelCard
, 可选) — 归属于此管道模型的模型卡片。 - framework (
str
, 可选) — 要使用的框架,可以是"pt"
(PyTorch) 或"tf"
(TensorFlow)。指定的框架必须已安装。如果未指定框架,将默认为当前安装的框架。如果未指定框架且两个框架都已安装,将默认为
model
的框架,或者在未提供模型时默认为 PyTorch。 - task (
str
, 默认为""
) — 管道的任务标识符。 - num_workers (
int
, 可选, 默认为 8) — 当管道使用 DataLoader 时(传递数据集,在 GPU 上使用 Pytorch 模型时),要使用的工作进程数。 - batch_size (
int
, 可选, 默认为 1) — 当流水线使用 DataLoader 时(例如,在 GPU 上为 Pytorch 模型传递数据集时),要使用的批次大小。对于推理,这并不总是有益的,请阅读流水线批处理。 - args_parser (ArgumentHandler, 可选) — 对负责解析所提供流水线参数的对象的引用。
- device (
int
, 可选, 默认为 -1) — 用于 CPU/GPU 支持的设备序号。将其设置为 -1 将使用 CPU,正数将在相应的 CUDA 设备 ID 上运行模型。您也可以传递原生的torch.device
或str
。 - torch_dtype (
str
或torch.dtype
, 可选) — 直接作为model_kwargs
发送(只是一个更简单的快捷方式),以使用此模型可用的精度(torch.float16
、torch.bfloat16
等或"auto"
)。 - binary_output (
bool
, 可选, 默认为False
) — 指示流水线输出是否应为序列化格式(即 pickle)或原始输出数据(例如文本)的标志。
使用任何 AutoModelForAudioClassification
的音频分类流水线。此流水线可预测原始波形或音频文件的类别。对于音频文件,应安装 ffmpeg 以支持多种音频格式。
示例
>>> from transformers import pipeline
>>> classifier = pipeline(model="superb/wav2vec2-base-superb-ks")
>>> classifier("https://huggingface.co/datasets/Narsil/asr_dummy/resolve/main/1.flac")
[{'score': 0.997, 'label': '_unknown_'}, {'score': 0.002, 'label': 'left'}, {'score': 0.0, 'label': 'yes'}, {'score': 0.0, 'label': 'down'}, {'score': 0.0, 'label': 'stop'}]
在流水线教程中了解有关使用流水线基础知识的更多信息。
此流水线目前可以使用以下任务标识符从 pipeline() 加载:"audio-classification"
。
请参阅 huggingface.co/models 上的可用模型列表。
__call__
< 源 >( inputs: typing.Union[numpy.ndarray, bytes, str, dict] **kwargs: typing.Any ) → 包含以下键的 `dict` 列表
参数
- inputs (
np.ndarray
或bytes
或str
或dict
) — 输入可以是:str
:音频文件的文件名,将使用 ffmpeg 以正确的采样率读取文件以获取波形。这需要在系统上安装 ffmpeg。bytes
:被视作音频文件的内容,并由 ffmpeg 以相同的方式解释。- (
np.ndarray
,形状为 (n, ),类型为np.float32
或np.float64
):以正确采样率提供的原始音频(不会进行进一步检查)。 dict
形式:可用于传递以任意sampling_rate
采样的原始音频,并让此流水线进行重采样。字典格式必须为{"sampling_rate": int, "raw": np.array}
或{"sampling_rate": int, "array": np.array}
,其中键"raw"
或"array"
用于表示原始音频波形。
- top_k (
int
, 可选, 默认为 None) — 流水线将返回的排名最高的标签数量。如果提供的数字为None
或高于模型配置中可用的标签数量,它将默认为标签的总数。 - function_to_apply(
str
, 可选, 默认为 "softmax") — 应用于模型输出的函数。默认情况下,流水线将对模型输出应用 softmax 函数。有效选项:["softmax", "sigmoid", "none"]。请注意,传递 Python 内置的None
将默认为 "softmax",因此您需要传递字符串 "none" 来禁用任何后处理。
返回
包含以下键的 `dict` 列表
- label (
str
) — 预测的标签。 - score (
float
) — 对应的概率。
对作为输入给定的序列进行分类。有关更多信息,请参阅 AutomaticSpeechRecognitionPipeline 文档。
AutomaticSpeechRecognitionPipeline
class transformers.AutomaticSpeechRecognitionPipeline
< 源 >( model: PreTrainedModel feature_extractor: typing.Union[ForwardRef('SequenceFeatureExtractor'), str] = None tokenizer: typing.Optional[transformers.tokenization_utils.PreTrainedTokenizer] = None decoder: typing.Union[ForwardRef('BeamSearchDecoderCTC'), str, NoneType] = None device: typing.Union[int, ForwardRef('torch.device')] = None torch_dtype: typing.Union[str, ForwardRef('torch.dtype'), NoneType] = None **kwargs )
参数
- model (PreTrainedModel 或 TFPreTrainedModel) — 流水线将用于进行预测的模型。对于 PyTorch,这需要是继承自 PreTrainedModel 的模型;对于 TensorFlow,则是继承自 TFPreTrainedModel 的模型。
- feature_extractor (SequenceFeatureExtractor) — 流水线将用于为模型编码波形的特征提取器。
- tokenizer (PreTrainedTokenizer) — 流水线将用于为模型编码数据的分词器。此对象继承自 PreTrainedTokenizer。
- decoder (
pyctcdecode.BeamSearchDecoderCTC
, 可选) — PyCTCDecode 的 BeamSearchDecoderCTC 可用于语言模型增强的解码。更多信息请参阅 Wav2Vec2ProcessorWithLM。 - chunk_length_s (
float
, 可选, 默认为 0) — 每个块的输入长度。如果chunk_length_s = 0
,则禁用分块(默认)。有关如何有效使用
chunk_length_s
的更多信息,请参阅 ASR 分块博客文章。 - stride_length_s (
float
, 可选, 默认为chunk_length_s / 6
) — 每个块左右两侧的步幅长度。仅在chunk_length_s > 0
时使用。这使模型能够看到更多上下文并更好地推断字母,但流水线会在末尾丢弃步幅部分,以使最终重构尽可能完美。有关如何有效使用
stride_length_s
的更多信息,请参阅 ASR 分块博客文章。 - framework (
str
, 可选) — 要使用的框架,可以是"pt"
(PyTorch) 或"tf"
(TensorFlow)。必须安装指定的框架。如果未指定框架,将默认为当前安装的框架。如果未指定框架且两个框架都已安装,将默认为model
的框架,如果未提供模型,则默认为 PyTorch。 - device (Union[
int
,torch.device
], 可选) — 用于 CPU/GPU 支持的设备序号。将其设置为None
将使用 CPU,正数将在相应的 CUDA 设备 ID 上运行模型。 - torch_dtype (Union[
int
,torch.dtype
], 可选) — 计算的数据类型 (dtype)。将其设置为None
将使用 float32 精度。设置为torch.float16
或torch.bfloat16
以在相应的 dtype 中使用半精度。
旨在从音频中提取口语文本的流水线。
输入可以是原始波形或音频文件。对于音频文件,应安装 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.'}
在流水线教程中了解有关使用流水线基础知识的更多信息。
__call__
< 源 >( inputs: typing.Union[numpy.ndarray, bytes, str, dict] **kwargs: typing.Any ) → `Dict`
参数
- inputs (
np.ndarray
或bytes
或str
或dict
) — 输入可以是: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
:流水线将为文本中的词段返回带时间戳的文本。例如,如果您得到[{"text": " Hi there!", "timestamp": (0.5, 1.5)}]
,则表示模型预测“Hi there!”这个片段是在0.5
秒之后和1.5
秒之前说出的。请注意,文本片段指的是一个或多个单词的序列,而不是像词级时间戳那样的单个单词。
- generate_kwargs (
dict
, 可选) — 用于生成调用的generate_config
的临时参数化字典。有关 `generate` 的完整概述,请查看以下指南。
返回
字典
一个包含以下键的字典:
- text (
str
): 识别出的文本。 - chunks (可选,
list[Dict]
) 当使用 `return_timestamps` 时,`chunks` 将成为一个包含模型识别出的所有不同文本块的列表,例如 `[{"text": "hi ", "timestamp": (0.5, 0.9)}, {"text": "there", "timestamp": (1.0, 1.5)}]`。可以通过执行 `"".join(chunk["text"] for chunk in output["chunks"])` 来大致恢复原始全文。
将作为输入给出的音频序列转录为文本。有关更多信息,请参阅 AutomaticSpeechRecognitionPipeline 文档。
TextToAudioPipeline
class transformers.TextToAudioPipeline
< 源 >( *args vocoder = None sampling_rate = None no_processor = True **kwargs )
使用任何 AutoModelForTextToWaveform
或 AutoModelForTextToSpectrogram
的文本到音频生成流水线。此流水线根据输入文本和可选的其他条件输入生成音频文件。
除非您使用的模型在其配置文件(generation_config.json
)中明确设置了这些生成参数,否则将使用以下默认值:
- 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"]
在流水线教程中了解有关使用流水线基础知识的更多信息。
您可以使用 TextToAudioPipeline.__call__.forward_params
或 TextToAudioPipeline.__call__.generate_kwargs
指定传递给模型的参数。
示例
>>> from transformers import pipeline
>>> music_generator = pipeline(task="text-to-audio", model="facebook/musicgen-small", framework="pt")
>>> # diversify the music generation by adding randomness with a high temperature and set a maximum music length
>>> generate_kwargs = {
... "do_sample": True,
... "temperature": 0.7,
... "max_new_tokens": 35,
... }
>>> outputs = music_generator("Techno music with high melodic riffs", generate_kwargs=generate_kwargs)
此流水线目前可以使用以下任务标识符从 pipeline() 加载:"text-to-speech"
或 "text-to-audio"
。
请参阅 huggingface.co/models 上的可用模型列表。
__call__
< 源 >( text_inputs: typing.Union[str, list[str]] **forward_params ) → `dict` 或 `dict` 列表
参数
- text_inputs (
str
或list[str]
) — 要生成的文本。 - forward_params (
dict
, 可选) — 传递给模型生成/前向方法的参数。forward_params
总是传递给底层模型。 - generate_kwargs (
dict
, 可选) — 用于生成调用的generate_config
的临时参数化字典。有关 `generate` 的完整概述,请查看以下指南。仅当底层模型是生成模型时,`generate_kwargs` 才传递给它。
返回
一个 `dict` 或一个 `dict` 列表
字典有两个键:
- audio (
np.ndarray
,形状为(nb_channels, audio_length)
) — 生成的音频波形。 - sampling_rate (
int
) — 生成的音频波形的采样率。
根据输入生成语音/音频。有关更多信息,请参阅 TextToAudioPipeline 文档。
ZeroShotAudioClassificationPipeline
class transformers.ZeroShotAudioClassificationPipeline
< 源 >( **kwargs )
参数
- model (PreTrainedModel 或 TFPreTrainedModel) — 流水线将用于进行预测的模型。对于 PyTorch,这需要是继承自 PreTrainedModel 的模型;对于 TensorFlow,则是继承自 TFPreTrainedModel 的模型。
- tokenizer (PreTrainedTokenizer) — 流水线将用于为模型编码数据的分词器。此对象继承自 PreTrainedTokenizer。
- feature_extractor (SequenceFeatureExtractor) — 流水线将用于为模型编码数据的特征提取器。此对象继承自 SequenceFeatureExtractor。
- modelcard (
str
或ModelCard
, 可选) — 归属于此流水线模型的模型卡。 - framework (
str
, 可选) — 要使用的框架,可以是"pt"
(PyTorch) 或"tf"
(TensorFlow)。必须安装指定的框架。如果未指定框架,将默认为当前安装的框架。如果未指定框架且两个框架都已安装,将默认为
model
的框架,如果未提供模型,则默认为 PyTorch。 - task (
str
, 默认为""
) — 流水线的任务标识符。 - num_workers (
int
, 可选, 默认为 8) — 当流水线使用 DataLoader 时(例如,在 GPU 上为 Pytorch 模型传递数据集时),要使用的工作进程数。 - batch_size (
int
, 可选, 默认为 1) — 当流水线使用 DataLoader 时(例如,在 GPU 上为 Pytorch 模型传递数据集时),要使用的批次大小。对于推理,这并不总是有益的,请阅读流水线批处理。 - args_parser (ArgumentHandler, 可选) — 对负责解析所提供流水线参数的对象的引用。
- device (
int
, 可选, 默认为 -1) — 用于 CPU/GPU 支持的设备序号。将其设置为 -1 将使用 CPU,正数将在相应的 CUDA 设备 ID 上运行模型。您也可以传递原生的torch.device
或str
。 - torch_dtype (
str
或torch.dtype
, 可选) — 直接作为model_kwargs
发送(只是一个更简单的快捷方式),以使用此模型可用的精度(torch.float16
、torch.bfloat16
等或"auto"
)。 - binary_output (
bool
, 可选, 默认为False
) — 指示流水线输出是否应为序列化格式(即 pickle)或原始输出数据(例如文本)的标志。
使用 ClapModel
的零样本音频分类流水线。当您提供一个音频和一组 candidate_labels
时,此流水线可预测该音频的类别。
默认的 hypothesis_template
是:"This is a sound of {}."
。请确保根据您的用途更新它。
示例
>>> from transformers import pipeline
>>> from datasets import load_dataset
>>> dataset = load_dataset("ashraq/esc50")
>>> audio = next(iter(dataset["train"]["audio"]))["array"]
>>> classifier = pipeline(task="zero-shot-audio-classification", model="laion/clap-htsat-unfused")
>>> classifier(audio, candidate_labels=["Sound of a dog", "Sound of vaccum cleaner"])
[{'score': 0.9996, 'label': 'Sound of a dog'}, {'score': 0.0004, 'label': 'Sound of vaccum cleaner'}]
在流水线教程中了解有关使用流水线基础知识的更多信息。此音频分类流水线目前可以使用以下任务标识符从 pipeline() 加载:"zero-shot-audio-classification"
。请参阅 huggingface.co/models 上的可用模型列表。
__call__
< 源 >( audios: typing.Union[numpy.ndarray, bytes, str, dict] **kwargs: typing.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 已经格式化,则传递 ”{}”。
为作为输入传递的音频分配标签。
计算机视觉
可用于计算机视觉任务的流水线包括以下内容。
DepthEstimationPipeline
class transformers.DepthEstimationPipeline
< source >( *args **kwargs )
参数
- model (PreTrainedModel or TFPreTrainedModel) — 将由流水线用于进行预测的模型。对于PyTorch,这需要是继承自 PreTrainedModel 的模型;对于TensorFlow,则需要是继承自 TFPreTrainedModel 的模型。
- image_processor (BaseImageProcessor) — 将由流水线用于为模型编码数据的图像处理器。此对象继承自 BaseImageProcessor。
- modelcard (
str
orModelCard
, 可选) — 归属于此流水线模型的模型卡。 - framework (
str
, 可选) — 要使用的框架,可以是"pt"
(PyTorch) 或"tf"
(TensorFlow)。指定的框架必须已安装。如果未指定框架,将默认使用当前安装的框架。如果未指定框架且两个框架都已安装,将默认使用
model
的框架,或者在未提供模型时默认使用PyTorch。 - task (
str
, 默认为""
) — 流水线的任务标识符。 - num_workers (
int
, 可选, 默认为 8) — 当流水线使用 DataLoader (当传递数据集,在GPU上使用Pytorch模型时),要使用的工作进程数量。 - batch_size (
int
, 可选, 默认为 1) — 当流水线使用 DataLoader (当传递数据集,在GPU上使用Pytorch模型时) 时,要使用的批次大小,对于推理而言,这并不总是有益的,请阅读 使用流水线进行批处理。 - args_parser (ArgumentHandler, 可选) — 对负责解析所提供流水线参数的对象的引用。
- device (
int
, 可选, 默认为 -1) — 用于CPU/GPU支持的设备序号。将其设置为-1将使用CPU,正数将在相应的CUDA设备ID上运行模型。您也可以传递原生的torch.device
或str
。 - torch_dtype (
str
ortorch.dtype
, 可选) — 直接作为model_kwargs
发送(只是一个更简单的快捷方式),以使用此模型可用的精度(torch.float16
、torch.bfloat16
等或"auto"
)。 - 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() 加载此深度估计流水线:"depth-estimation"
。
请在 huggingface.co/models 上查看可用模型的列表。
__call__
< source >( inputs: typing.Union[str, list[str], ForwardRef('Image.Image'), list['Image.Image']] **kwargs: typing.Any )
参数
- inputs (
str
,list[str]
,PIL.Image
orlist[PIL.Image]
) — 流水线处理三种类型的图像:- 包含指向图像的 http 链接的字符串
- 包含本地图像路径的字符串
- 直接加载在 PIL 中的图像
流水线接受单个图像或一批图像,批处理时必须以字符串形式传递。批处理中的图像必须都是相同格式:全部为 http 链接,全部为本地路径,或全部为 PIL 图像。
- parameters (
Dict
, 可选) — 参数名称到参数值的字典,用于控制流水线行为。目前唯一可用的参数是timeout
,即流水线在放弃尝试下载图像之前应等待的时间长度(以秒为单位)。 - timeout (
float
, 可选, 默认为 None) — 从网页获取图像时等待的最大时间(以秒为单位)。如果为 None,则不设置超时,调用可能会永远阻塞。
预测作为输入传递的图像的深度。
ImageClassificationPipeline
class transformers.ImageClassificationPipeline
< source >( *args **kwargs )
参数
- model (PreTrainedModel or TFPreTrainedModel) — 将由流水线用于进行预测的模型。对于PyTorch,这需要是继承自 PreTrainedModel 的模型;对于TensorFlow,则需要是继承自 TFPreTrainedModel 的模型。
- image_processor (BaseImageProcessor) — 将由流水线用于为模型编码数据的图像处理器。此对象继承自 BaseImageProcessor。
- modelcard (
str
orModelCard
, 可选) — 归属于此流水线模型的模型卡。 - framework (
str
, 可选) — 要使用的框架,可以是"pt"
(PyTorch) 或"tf"
(TensorFlow)。指定的框架必须已安装。如果未指定框架,将默认使用当前安装的框架。如果未指定框架且两个框架都已安装,将默认使用
model
的框架,或者在未提供模型时默认使用PyTorch。 - task (
str
, 默认为""
) — 流水线的任务标识符。 - num_workers (
int
, 可选, 默认为 8) — 当流水线使用 DataLoader (当传递数据集,在GPU上使用Pytorch模型时),要使用的工作进程数量。 - batch_size (
int
, 可选, 默认为 1) — 当流水线使用 DataLoader (当传递数据集,在GPU上使用Pytorch模型时) 时,要使用的批次大小,对于推理而言,这并不总是有益的,请阅读 使用流水线进行批处理。 - args_parser (ArgumentHandler, 可选) — 对负责解析所提供流水线参数的对象的引用。
- device (
int
, 可选, 默认为 -1) — 用于CPU/GPU支持的设备序号。将其设置为-1将使用CPU,正数将在相应的CUDA设备ID上运行模型。您也可以传递原生的torch.device
或str
。 - torch_dtype (
str
ortorch.dtype
, 可选) — 直接作为model_kwargs
发送(只是一个更简单的快捷方式),以使用此模型可用的精度(torch.float16
、torch.bfloat16
等或"auto"
)。 - binary_output (
bool
, 可选, 默认为False
) — 指示流水线输出是否应以序列化格式(即 pickle)或作为原始输出数据(例如文本)进行的标志。 - function_to_apply (
str
, 可选, 默认为"default"
) — 应用于模型输出以检索分数的函数。接受四个不同的值:"default"
: 如果模型只有一个标签,将对输出应用 sigmoid 函数。如果模型有多个标签,将对输出应用 softmax 函数。"sigmoid"
: 对输出应用 sigmoid 函数。"softmax"
: 对输出应用 softmax 函数。"none"
: 不对输出应用任何函数。
使用任何 AutoModelForImageClassification
的图像分类流水线。此流水线预测图像的类别。
示例
>>> from transformers import pipeline
>>> classifier = pipeline(model="microsoft/beit-base-patch16-224-pt22k-ft22k")
>>> classifier("https://huggingface.co/datasets/Narsil/image_dummy/raw/main/parrots.png")
[{'score': 0.442, 'label': 'macaw'}, {'score': 0.088, 'label': 'popinjay'}, {'score': 0.075, 'label': 'parrot'}, {'score': 0.073, 'label': 'parodist, lampooner'}, {'score': 0.046, 'label': 'poll, poll_parrot'}]
在流水线教程中了解有关使用流水线基础知识的更多信息。
目前可以使用以下任务标识符从 pipeline() 加载此图像分类流水线:"image-classification"
。
请在 huggingface.co/models 上查看可用模型的列表。
__call__
< source >( inputs: typing.Union[str, list[str], ForwardRef('Image.Image'), list['Image.Image']] **kwargs: typing.Any )
参数
- inputs (
str
,list[str]
,PIL.Image
orlist[PIL.Image]
) — 流水线处理三种类型的图像:- 包含指向图像的 http 链接的字符串
- 包含本地图像路径的字符串
- 直接加载在 PIL 中的图像
流水线接受单个图像或一批图像,批处理时必须以字符串形式传递。批处理中的图像必须都是相同格式:全部为 http 链接,全部为本地路径,或全部为 PIL 图像。
- function_to_apply (
str
, 可选, 默认为"default"
) — 应用于模型输出以检索分数的函数。接受四个不同的值:如果未指定此参数,则将根据标签数量应用以下函数:
- 如果模型只有一个标签,将对输出应用 sigmoid 函数。
- 如果模型有多个标签,将对输出应用 softmax 函数。
可能的值为:
"sigmoid"
: 对输出应用 sigmoid 函数。"softmax"
: 对输出应用 softmax 函数。"none"
: 不对输出应用任何函数。
- top_k (
int
, 可选, 默认为 5) — 流水线将返回的排名靠前的标签数量。如果提供的数量高于模型配置中可用的标签数量,则将默认为标签的数量。 - timeout (
float
, 可选, 默认为 None) — 从网页获取图像时等待的最大时间(以秒为单位)。如果为 None,则不设置超时,调用可能会永远阻塞。
为作为输入传递的图像分配标签。
ImageSegmentationPipeline
class transformers.ImageSegmentationPipeline
< source >( *args **kwargs )
参数
- model (PreTrainedModel or TFPreTrainedModel) — 将由流水线用于进行预测的模型。对于PyTorch,这需要是继承自 PreTrainedModel 的模型;对于TensorFlow,则需要是继承自 TFPreTrainedModel 的模型。
- image_processor (BaseImageProcessor) — 将由流水线用于为模型编码数据的图像处理器。此对象继承自 BaseImageProcessor。
- modelcard (
str
orModelCard
, 可选) — 归属于此流水线模型的模型卡。 - framework (
str
, 可选) — 要使用的框架,可以是"pt"
(PyTorch) 或"tf"
(TensorFlow)。指定的框架必须已安装。如果未指定框架,将默认使用当前安装的框架。如果未指定框架且两个框架都已安装,将默认使用
model
的框架,或者在未提供模型时默认使用PyTorch。 - task (
str
, 默认为""
) — 流水线的任务标识符。 - num_workers (
int
, 可选, 默认为 8) — 当流水线使用 DataLoader (当传递数据集,在GPU上使用Pytorch模型时),要使用的工作进程数量。 - batch_size (
int
, 可选, 默认为 1) — 当流水线使用 DataLoader (当传递数据集,在GPU上使用Pytorch模型时) 时,要使用的批次大小,对于推理而言,这并不总是有益的,请阅读 使用流水线进行批处理。 - args_parser (ArgumentHandler, 可选) — 对负责解析所提供流水线参数的对象的引用。
- device (
int
, 可选, 默认为 -1) — 用于CPU/GPU支持的设备序号。将其设置为-1将使用CPU,正数将在相应的CUDA设备ID上运行模型。您也可以传递原生的torch.device
或str
。 - torch_dtype (
str
ortorch.dtype
, 可选) — 直接作为model_kwargs
发送(只是一个更简单的快捷方式),以使用此模型可用的精度(torch.float16
、torch.bfloat16
等或"auto"
)。 - binary_output (
bool
, 可选, 默认为False
) — 指示流水线输出是否应以序列化格式(即 pickle)或作为原始输出数据(例如文本)进行的标志。
使用任何 AutoModelForXXXSegmentation
的图像分割流水线。此流水线预测对象的掩码及其类别。
示例
>>> from transformers import pipeline
>>> segmenter = pipeline(model="facebook/detr-resnet-50-panoptic")
>>> segments = segmenter("https://huggingface.co/datasets/Narsil/image_dummy/raw/main/parrots.png")
>>> len(segments)
2
>>> segments[0]["label"]
'bird'
>>> segments[1]["label"]
'bird'
>>> type(segments[0]["mask"]) # This is a black and white mask showing where is the bird on the original image.
<class 'PIL.Image.Image'>
>>> segments[0]["mask"].size
(768, 512)
目前可以使用以下任务标识符从 pipeline() 加载此图像分割流水线:"image-segmentation"
。
请在 huggingface.co/models 上查看可用模型的列表。
__call__
< source >( inputs: typing.Union[str, ForwardRef('Image.Image'), list[str], list['Image.Image']] **kwargs: typing.Any )
参数
- inputs (
str
,list[str]
,PIL.Image
orlist[PIL.Image]
) — 流水线处理三种类型的图像:- 包含指向图像的 HTTP(S) 链接的字符串
- 包含本地图像路径的字符串
- 直接加载在 PIL 中的图像
流水线接受单个图像或一批图像。批处理中的图像必须都是相同格式:全部为 HTTP(S) 链接,全部为本地路径,或全部为 PIL 图像。
- subtask (
str
, 可选) — 要执行的分割任务,根据模型能力选择 [semantic
,instance
,panoptic
]。如果未设置,流水线将尝试按以下顺序解析:panoptic
,instance
,semantic
。 - threshold (
float
, 可选, 默认为 0.9) — 用于过滤预测掩码的概率阈值。 - mask_threshold (
float
, 可选, 默认为 0.5) — 将预测掩码转换为二进制值时使用的阈值。 - overlap_mask_area_threshold (
float
, 可选, 默认为 0.5) — 掩码重叠阈值,用于消除小的、不连贯的片段。 - timeout (
float
, 可选, 默认为 None) — 从网页获取图像时等待的最大时间(以秒为单位)。如果为 None,则不设置超时,调用可能会永远阻塞。
在作为输入传递的图像中执行分割(检测掩码和类别)。
ImageToImagePipeline
class transformers.ImageToImagePipeline
< source >( *args **kwargs )
参数
- model (PreTrainedModel 或 TFPreTrainedModel) — 流水线用于进行预测的模型。对于 PyTorch,该模型需要继承自 PreTrainedModel;对于 TensorFlow,则需要继承自 TFPreTrainedModel。
- image_processor (BaseImageProcessor) — 流水线用于为模型编码数据的图像处理器。此对象继承自 BaseImageProcessor。
- modelcard (
str
或ModelCard
, 可选) — 归属于此流水线模型的模型卡。 - framework (
str
, 可选) — 要使用的框架,可以是"pt"
(PyTorch) 或"tf"
(TensorFlow)。指定的框架必须已安装。如果未指定框架,将默认使用当前已安装的框架。如果未指定框架但两个框架都已安装,将默认使用 `model` 的框架,或者在未提供模型时默认使用 PyTorch。
- task (
str
, 默认为""
) — 流水线的任务标识符。 - num_workers (
int
, 可选, 默认为 8) — 当流水线使用 DataLoader 时(例如,在 GPU 上为 Pytorch 模型传递数据集时),要使用的工作进程数量。 - batch_size (
int
, 可选, 默认为 1) — 当流水线使用 DataLoader 时(例如,在 GPU 上为 Pytorch 模型传递数据集时),要使用的批次大小。对于推理,这并不总是有益的,请阅读 流水线批处理。 - args_parser (ArgumentHandler, 可选) — 负责解析提供的流水线参数的对象的引用。
- device (
int
, 可选, 默认为 -1) — 支持 CPU/GPU 的设备序号。设置为 -1 将使用 CPU,正数将在相应的 CUDA 设备 ID 上运行模型。您也可以传递原生的 `torch.device` 或 `str`。 - torch_dtype (
str
或torch.dtype
, 可选) — 直接作为 `model_kwargs` 发送(仅为简便的快捷方式),以使用此模型可用的精度(`torch.float16`、`torch.bfloat16`... 或 `"auto"`)。 - binary_output (
bool
, 可选, 默认为False
) — 指示流水线输出是否应以序列化格式(例如 pickle)或原始输出数据(例如文本)形式出现的标志。
使用任何 `AutoModelForImageToImage` 的图像到图像流水线。此流水线基于先前的图像输入生成新图像。
示例
>>> from PIL import Image
>>> import requests
>>> from transformers import pipeline
>>> upscaler = pipeline("image-to-image", model="caidas/swin2SR-classical-sr-x2-64")
>>> img = Image.open(requests.get("http://images.cocodataset.org/val2017/000000039769.jpg", stream=True).raw)
>>> img = img.resize((64, 64))
>>> upscaled_img = upscaler(img)
>>> img.size
(64, 64)
>>> upscaled_img.size
(144, 144)
目前,可以使用以下任务标识符从 pipeline() 加载此图像到图像流水线:`"image-to-image"`。
请在 huggingface.co/models 查看可用模型列表。
__call__
< source >( images: typing.Union[str, list[str], ForwardRef('Image.Image'), list['Image.Image']] **kwargs: typing.Any )
转换作为输入传递的图像。
ObjectDetectionPipeline
class transformers.ObjectDetectionPipeline
< source >( *args **kwargs )
参数
- model (PreTrainedModel 或 TFPreTrainedModel) — 流水线用于进行预测的模型。对于 PyTorch,该模型需要继承自 PreTrainedModel;对于 TensorFlow,则需要继承自 TFPreTrainedModel。
- image_processor (BaseImageProcessor) — 流水线用于为模型编码数据的图像处理器。此对象继承自 BaseImageProcessor。
- modelcard (
str
或ModelCard
, 可选) — 归属于此流水线模型的模型卡。 - framework (
str
, 可选) — 要使用的框架,可以是"pt"
(PyTorch) 或"tf"
(TensorFlow)。指定的框架必须已安装。如果未指定框架,将默认使用当前已安装的框架。如果未指定框架但两个框架都已安装,将默认使用 `model` 的框架,或者在未提供模型时默认使用 PyTorch。
- task (
str
, 默认为""
) — 流水线的任务标识符。 - num_workers (
int
, 可选, 默认为 8) — 当流水线使用 DataLoader 时(例如,在 GPU 上为 Pytorch 模型传递数据集时),要使用的工作进程数量。 - batch_size (
int
, 可选, 默认为 1) — 当流水线使用 DataLoader 时(例如,在 GPU 上为 Pytorch 模型传递数据集时),要使用的批次大小。对于推理,这并不总是有益的,请阅读 流水线批处理。 - args_parser (ArgumentHandler, 可选) — 负责解析提供的流水线参数的对象的引用。
- device (
int
, 可选, 默认为 -1) — 支持 CPU/GPU 的设备序号。设置为 -1 将使用 CPU,正数将在相应的 CUDA 设备 ID 上运行模型。您也可以传递原生的 `torch.device` 或 `str`。 - torch_dtype (
str
或torch.dtype
, 可选) — 直接作为 `model_kwargs` 发送(仅为简便的快捷方式),以使用此模型可用的精度(`torch.float16`、`torch.bfloat16`... 或 `"auto"`)。 - binary_output (
bool
, 可选, 默认为False
) — 指示流水线输出是否应以序列化格式(例如 pickle)或原始输出数据(例如文本)形式出现的标志。
使用任何 `AutoModelForObjectDetection` 的目标检测流水线。此流水线预测对象的边界框及其类别。
示例
>>> from transformers import pipeline
>>> detector = pipeline(model="facebook/detr-resnet-50")
>>> detector("https://huggingface.co/datasets/Narsil/image_dummy/raw/main/parrots.png")
[{'score': 0.997, 'label': 'bird', 'box': {'xmin': 69, 'ymin': 171, 'xmax': 396, 'ymax': 507}}, {'score': 0.999, 'label': 'bird', 'box': {'xmin': 398, 'ymin': 105, 'xmax': 767, 'ymax': 507}}]
>>> # x, y are expressed relative to the top left hand corner.
在流水线教程中了解有关使用流水线基础知识的更多信息。
目前,可以使用以下任务标识符从 pipeline() 加载此目标检测流水线:`"object-detection"`。
请在 huggingface.co/models 查看可用模型列表。
__call__
< source >( *args **kwargs )
参数
- inputs (
str
,list[str]
,PIL.Image
或list[PIL.Image]
) — 流水线处理三种类型的图像:- 包含指向图像的 HTTP(S) 链接的字符串
- 包含本地图像路径的字符串
- 直接加载的 PIL 图像
流水线接受单个图像或一批图像。批次中的图像必须全部采用相同格式:全部为 HTTP(S) 链接、全部为本地路径或全部为 PIL 图像。
- threshold (
float
, 可选, 默认为 0.5) — 进行预测所需的概率阈值。 - timeout (
float
, 可选, 默认为 None) — 从网络获取图像的最大等待时间(秒)。如果为 None,则不设置超时,调用可能会永久阻塞。
检测作为输入传递的图像中的对象(边界框和类别)。
VideoClassificationPipeline
class transformers.VideoClassificationPipeline
< source >( *args **kwargs )
参数
- model (PreTrainedModel 或 TFPreTrainedModel) — 流水线用于进行预测的模型。对于 PyTorch,该模型需要继承自 PreTrainedModel;对于 TensorFlow,则需要继承自 TFPreTrainedModel。
- image_processor (BaseImageProcessor) — 流水线用于为模型编码数据的图像处理器。此对象继承自 BaseImageProcessor。
- modelcard (
str
或ModelCard
, 可选) — 归属于此流水线模型的模型卡。 - framework (
str
, 可选) — 要使用的框架,可以是"pt"
(PyTorch) 或"tf"
(TensorFlow)。指定的框架必须已安装。如果未指定框架,将默认使用当前已安装的框架。如果未指定框架但两个框架都已安装,将默认使用 `model` 的框架,或者在未提供模型时默认使用 PyTorch。
- task (
str
, 默认为""
) — 流水线的任务标识符。 - num_workers (
int
, 可选, 默认为 8) — 当流水线使用 DataLoader 时(例如,在 GPU 上为 Pytorch 模型传递数据集时),要使用的工作进程数量。 - batch_size (
int
, 可选, 默认为 1) — 当流水线使用 DataLoader 时(例如,在 GPU 上为 Pytorch 模型传递数据集时),要使用的批次大小。对于推理,这并不总是有益的,请阅读 流水线批处理。 - args_parser (ArgumentHandler, 可选) — 负责解析提供的流水线参数的对象的引用。
- device (
int
, 可选, 默认为 -1) — 支持 CPU/GPU 的设备序号。设置为 -1 将使用 CPU,正数将在相应的 CUDA 设备 ID 上运行模型。您也可以传递原生的 `torch.device` 或 `str`。 - torch_dtype (
str
或torch.dtype
, 可选) — 直接作为 `model_kwargs` 发送(仅为简便的快捷方式),以使用此模型可用的精度(`torch.float16`、`torch.bfloat16`... 或 `"auto"`)。 - binary_output (
bool
, 可选, 默认为False
) — 指示流水线输出是否应以序列化格式(例如 pickle)或原始输出数据(例如文本)形式出现的标志。
使用任何 `AutoModelForVideoClassification` 的视频分类流水线。此流水线预测视频的类别。
目前,可以使用以下任务标识符从 pipeline() 加载此视频分类流水线:`"video-classification"`。
请在 huggingface.co/models 查看可用模型列表。
__call__
< source >( inputs: typing.Union[str, list[str], NoneType] = None **kwargs )
参数
- inputs (
str
,list[str]
) — 流水线处理三种类型的视频:- 包含指向视频的 http 链接的字符串
- 包含本地视频路径的字符串
流水线接受单个视频或一批视频,后者必须作为字符串传递。批次中的视频必须全部采用相同格式:全部为 http 链接或全部为本地路径。
- top_k (
int
, 可选, 默认为 5) — 流水线将返回的最高标签数量。如果提供的数量高于模型配置中可用的标签数量,则将默认为标签数量。 - num_frames (
int
, 可选, 默认为self.model.config.num_frames
) — 从视频中采样用于分类的帧数。如果未提供,则将默认为模型配置中指定的帧数。 - frame_sampling_rate (
int
, 可选, 默认为 1) — 用于从视频中选择帧的采样率。如果未提供,则默认为 1,即使用每一帧。 - function_to_apply(
str
, 可选, 默认为 “softmax”) — 应用于模型输出的函数。默认情况下,流水线将对模型输出应用 softmax 函数。有效选项:[“softmax”, “sigmoid”, “none”]。注意,传递 Python 内置的 `None` 将默认为 “softmax”,因此需要传递字符串 “none” 来禁用任何后处理。
为作为输入传递的视频分配标签。
ZeroShotImageClassificationPipeline
class transformers.ZeroShotImageClassificationPipeline
< source >( **kwargs )
参数
- model (PreTrainedModel 或 TFPreTrainedModel) — 流水线用于进行预测的模型。对于 PyTorch,该模型需要继承自 PreTrainedModel;对于 TensorFlow,则需要继承自 TFPreTrainedModel。
- image_processor (BaseImageProcessor) — 流水线用于为模型编码数据的图像处理器。此对象继承自 BaseImageProcessor。
- modelcard (
str
或ModelCard
, 可选) — 归属于此流水线模型使用的模型卡。 - framework (
str
, 可选) — 要使用的框架,可以是 PyTorch 的"pt"
或 TensorFlow 的"tf"
。指定的框架必须已安装。如果未指定框架,则默认为当前已安装的框架。如果未指定框架且两个框架都已安装,则默认为
model
所使用的框架,如果未提供模型,则默认为 PyTorch。 - task (
str
, 默认为""
) — 流水线的任务标识符。 - num_workers (
int
, 可选, 默认为 8) — 当流水线使用 DataLoader 时(例如在 GPU 上为 PyTorch 模型传递数据集时),要使用的工作进程数。 - batch_size (
int
, 可选, 默认为 1) — 当流水线使用 DataLoader 时(例如在 GPU 上为 PyTorch 模型传递数据集时),要使用的批量大小。对于推理,这并不总是有益的,请阅读流水线批处理。 - args_parser (ArgumentHandler, 可选) — 对负责解析所提供流水线参数的对象的引用。
- device (
int
, 可选, 默认为 -1) — 支持 CPU/GPU 的设备序号。设置为 -1 将使用 CPU,正数将在相应的 CUDA 设备 ID 上运行模型。您也可以传递原生的torch.device
或str
。 - torch_dtype (
str
或torch.dtype
, 可选) — 直接作为model_kwargs
发送(这只是一个更简单的快捷方式),以使用此模型的可用精度(torch.float16
、torch.bfloat16
, ... 或"auto"
)。 - 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() 加载:"zero-shot-image-classification"
。
请在 huggingface.co/models 上查看可用模型列表。
__call__
< 源码 >( image: typing.Union[str, list[str], ForwardRef('Image.Image'), list['Image.Image']] candidate_labels: list **kwargs: typing.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 或 TFPreTrainedModel) — 流水线将用于进行预测的模型。对于 PyTorch,它需要是继承自 PreTrainedModel 的模型;对于 TensorFlow,它需要是继承自 TFPreTrainedModel 的模型。
- image_processor (BaseImageProcessor) — 流水线将用于为模型编码数据的图像处理器。此对象继承自 BaseImageProcessor。
- modelcard (
str
或ModelCard
, 可选) — 归属于此流水线模型使用的模型卡。 - framework (
str
, 可选) — 要使用的框架,可以是 PyTorch 的"pt"
或 TensorFlow 的"tf"
。指定的框架必须已安装。如果未指定框架,则默认为当前已安装的框架。如果未指定框架且两个框架都已安装,则默认为
model
所使用的框架,如果未提供模型,则默认为 PyTorch。 - task (
str
, 默认为""
) — 流水线的任务标识符。 - num_workers (
int
, 可选, 默认为 8) — 当流水线使用 DataLoader 时(例如在 GPU 上为 PyTorch 模型传递数据集时),要使用的工作进程数。 - batch_size (
int
, 可选, 默认为 1) — 当流水线使用 DataLoader 时(例如在 GPU 上为 PyTorch 模型传递数据集时),要使用的批量大小。对于推理,这并不总是有益的,请阅读流水线批处理。 - args_parser (ArgumentHandler, 可选) — 对负责解析所提供流水线参数的对象的引用。
- device (
int
, 可选, 默认为 -1) — 支持 CPU/GPU 的设备序号。设置为 -1 将使用 CPU,正数将在相应的 CUDA 设备 ID 上运行模型。您也可以传递原生的torch.device
或str
。 - torch_dtype (
str
或torch.dtype
, 可选) — 直接作为model_kwargs
发送(这只是一个更简单的快捷方式),以使用此模型的可用精度(torch.float16
、torch.bfloat16
, ... 或"auto"
)。 - 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() 加载:"zero-shot-object-detection"
。
请在 huggingface.co/models 上查看可用模型列表。
__call__
< 源码 >( image: typing.Union[str, ForwardRef('Image.Image'), list[dict[str, typing.Any]]] candidate_labels: typing.Union[str, list[str], NoneType] = None **kwargs: typing.Any )
检测作为输入传递的图像中的对象(边界框和类别)。
自然语言处理
可用于自然语言处理任务的流水线包括以下几种。
FillMaskPipeline
class transformers.FillMaskPipeline
< 源码 >( model: typing.Union[ForwardRef('PreTrainedModel'), ForwardRef('TFPreTrainedModel')] tokenizer: typing.Optional[transformers.tokenization_utils.PreTrainedTokenizer] = None feature_extractor: typing.Optional[ForwardRef('SequenceFeatureExtractor')] = None image_processor: typing.Optional[transformers.image_processing_utils.BaseImageProcessor] = None processor: typing.Optional[transformers.processing_utils.ProcessorMixin] = None modelcard: typing.Optional[transformers.modelcard.ModelCard] = None framework: typing.Optional[str] = None task: str = '' args_parser: ArgumentHandler = None device: typing.Union[int, ForwardRef('torch.device')] = None torch_dtype: typing.Union[str, ForwardRef('torch.dtype'), NoneType] = None binary_output: bool = False **kwargs )
参数
- model (PreTrainedModel 或 TFPreTrainedModel) — 流水线将用于进行预测的模型。对于 PyTorch,它需要是继承自 PreTrainedModel 的模型;对于 TensorFlow,它需要是继承自 TFPreTrainedModel 的模型。
- tokenizer (PreTrainedTokenizer) — 流水线将用于为模型编码数据的分词器。此对象继承自 PreTrainedTokenizer。
- modelcard (
str
或ModelCard
, 可选) — 归属于此流水线模型使用的模型卡。 - framework (
str
, 可选) — 要使用的框架,可以是 PyTorch 的"pt"
或 TensorFlow 的"tf"
。指定的框架必须已安装。如果未指定框架,则默认为当前已安装的框架。如果未指定框架且两个框架都已安装,则默认为
model
所使用的框架,如果未提供模型,则默认为 PyTorch。 - task (
str
, 默认为""
) — 流水线的任务标识符。 - num_workers (
int
, 可选, 默认为 8) — 当流水线使用 DataLoader 时(例如在 GPU 上为 PyTorch 模型传递数据集时),要使用的工作进程数。 - batch_size (
int
, 可选, 默认为 1) — 当流水线使用 DataLoader 时(例如在 GPU 上为 PyTorch 模型传递数据集时),要使用的批量大小。对于推理,这并不总是有益的,请阅读流水线批处理。 - args_parser (ArgumentHandler, 可选) — 对负责解析所提供流水线参数的对象的引用。
- device (
int
, 可选, 默认为 -1) — 支持 CPU/GPU 的设备序号。设置为 -1 将使用 CPU,正数将在相应的 CUDA 设备 ID 上运行模型。您也可以传递原生的torch.device
或str
。 - torch_dtype (
str
或torch.dtype
, 可选) — 直接作为model_kwargs
发送(这只是一个更简单的快捷方式),以使用此模型的可用精度(torch.float16
、torch.bfloat16
, ... 或"auto"
)。 - binary_output (
bool
, 可选, 默认为False
) — 指示流水线输出是否应以序列化格式(例如 pickle)或作为原始输出数据(例如文本)进行的标志。 - top_k (
int
, 可选, 默认为 5) — 要返回的预测数量。 - targets (
str
或list[str]
, 可选) — 当传递此参数时,模型将把分数限制在传递的目标上,而不是在整个词汇表中查找。如果提供的目标不在模型词汇表中,它们将被分词,并使用第一个生成的分词(会有一个警告,并且可能会变慢)。 - tokenizer_kwargs (
dict
, 可选) — 传递给分词器的额外关键字参数字典。
使用任何 ModelWithLMHead
的掩码语言建模预测流水线。有关更多信息,请参阅掩码语言建模示例。
示例
>>> from transformers import pipeline
>>> fill_masker = pipeline(model="google-bert/bert-base-uncased")
>>> fill_masker("This is a simple [MASK].")
[{'score': 0.042, 'token': 3291, 'token_str': 'problem', 'sequence': 'this is a simple problem.'}, {'score': 0.031, 'token': 3160, 'token_str': 'question', 'sequence': 'this is a simple question.'}, {'score': 0.03, 'token': 8522, 'token_str': 'equation', 'sequence': 'this is a simple equation.'}, {'score': 0.027, 'token': 2028, 'token_str': 'one', 'sequence': 'this is a simple one.'}, {'score': 0.024, 'token': 3627, 'token_str': 'rule', 'sequence': 'this is a simple rule.'}]
在流水线教程中了解有关使用流水线基础知识的更多信息。
此掩码填充流水线目前可以使用以下任务标识符从 pipeline() 加载:"fill-mask"
。
此流水线可以使用的模型是那些使用掩码语言建模目标进行训练的模型,其中包括库中的双向模型。请在 huggingface.co/models 上查看最新的可用模型列表。
此流水线仅适用于只有一个标记被掩码的输入。实验性功能:我们添加了对多个掩码的支持。返回的值是原始模型输出,对应于离散概率,而人们可能期望的是联合概率(参见讨论)。
此流水线现在支持 tokenizer_kwargs。例如,可以尝试:
>>> from transformers import pipeline
>>> fill_masker = pipeline(model="google-bert/bert-base-uncased")
>>> tokenizer_kwargs = {"truncation": True}
>>> fill_masker(
... "This is a simple [MASK]. " + "...with a large amount of repeated text appended. " * 100,
... tokenizer_kwargs=tokenizer_kwargs,
... )
__call__
< 源码 >( inputs: typing.Union[str, list[str]] **kwargs: typing.Any ) → dict
的列表或列表的列表
参数
- inputs (
str
或list[str]
) — 一个或多个带有掩码标记的文本(或一个提示列表)。 - targets (
str
或list[str]
, 可选) — 当传递此参数时,模型将把分数限制在传递的目标上,而不是在整个词汇表中查找。如果提供的目标不在模型词汇表中,它们将被分词,并使用第一个生成的分词(会有一个警告,并且可能会变慢)。 - top_k (
int
, 可选) — 当传递此参数时,将覆盖要返回的预测数量。
返回
dict
的列表或列表的列表
每个结果都以字典列表的形式出现,包含以下键:
- sequence (
str
) — 带有掩码标记预测的相应输入。 - score (
float
) — 对应的概率。 - token (
int
) — 预测的标记 ID(用于替换掩码标记)。 - token_str (
str
) — 预测的标记(用于替换掩码标记)。
填充作为输入给出的文本中的掩码标记。
QuestionAnsweringPipeline
class transformers.QuestionAnsweringPipeline
< 源码 >( model: typing.Union[ForwardRef('PreTrainedModel'), ForwardRef('TFPreTrainedModel')] tokenizer: PreTrainedTokenizer modelcard: typing.Optional[transformers.modelcard.ModelCard] = None framework: typing.Optional[str] = None task: str = '' **kwargs )
参数
- model (PreTrainedModel 或 TFPreTrainedModel) — 流水线将用于进行预测的模型。对于 PyTorch,它需要是继承自 PreTrainedModel 的模型;对于 TensorFlow,它需要是继承自 TFPreTrainedModel 的模型。
- tokenizer (PreTrainedTokenizer) — 流水线将用于为模型编码数据的分词器。此对象继承自 PreTrainedTokenizer。
- modelcard (
str
或ModelCard
, 可选) — 归属于此流水线模型使用的模型卡。 - framework (
str
, 可选) — 要使用的框架,可以是"pt"
(PyTorch) 或"tf"
(TensorFlow)。必须已安装指定的框架。如果未指定框架,则将默认使用当前已安装的框架。如果未指定框架但两种框架都已安装,则将默认使用
model
的框架,如果未提供模型,则默认使用 PyTorch。 - task (
str
, 默认为""
) — 流水线的任务标识符。 - num_workers (
int
, 可选, 默认为 8) — 当流水线使用 DataLoader 时(例如在 GPU 上为 Pytorch 模型传递数据集时),要使用的工作进程数。 - batch_size (
int
, 可选, 默认为 1) — 当流水线使用 DataLoader 时(例如在 GPU 上为 Pytorch 模型传递数据集时),要使用的批次大小。对于推理,这并不总是有益的,请阅读流水线批处理。 - args_parser (ArgumentHandler, 可选) — 负责解析所提供流水线参数的对象的引用。
- device (
int
, 可选, 默认为 -1) — 用于 CPU/GPU 支持的设备序号。将其设置为 -1 将使用 CPU,正数将在相应的 CUDA 设备 ID 上运行模型。您也可以传递原生的torch.device
或str
。 - torch_dtype (
str
或torch.dtype
, 可选) — 直接作为model_kwargs
发送(只是一个更简单的快捷方式),以使用此模型可用的精度(torch.float16
、torch.bfloat16
等或"auto"
)。 - binary_output (
bool
, 可选, 默认为False
) — 指示流水线的输出应为序列化格式(即 pickle)还是原始输出数据(例如文本)的标志。
使用任何 ModelForQuestionAnswering
的问答流水线。有关更多信息,请参阅问答示例。
示例
>>> from transformers import pipeline
>>> oracle = pipeline(model="deepset/roberta-base-squad2")
>>> oracle(question="Where do I live?", context="My name is Wolfgang and I live in Berlin")
{'score': 0.9191, 'start': 34, 'end': 40, 'answer': 'Berlin'}
在流水线教程中了解有关使用流水线基础知识的更多信息。
目前可以使用以下任务标识符从 pipeline() 加载此问答流水线:"question-answering"
。
此流水线可以使用的模型是已经在问答任务上进行了微调的模型。请参阅 huggingface.co/models 上可用的最新模型列表。
__call__
< 源代码 >( *args **kwargs ) → 一个 dict
或 dict
列表
参数
- question (
str
或list[str]
) — 一个或多个问题(必须与context
参数一起使用)。 - context (
str
或list[str]
) — 与问题相关的一个或多个上下文(必须与question
参数一起使用)。 - top_k (
int
, 可选, 默认为 1) — 要返回的答案数量(将按可能性顺序选择)。请注意,如果上下文中没有足够的可用选项,我们将返回少于 top_k 个答案。 - doc_stride (
int
, 可选, 默认为 128) — 如果上下文太长,无法与模型的问题相适应,它将被分割成几个带有重叠的块。此参数控制重叠的大小。 - max_answer_len (
int
, 可选, 默认为 15) — 预测答案的最大长度(例如,只考虑长度较短的答案)。 - max_seq_len (
int
, 可选, 默认为 384) — 传递给模型的每个块的总句子(上下文 + 问题)的最大长度(以词元为单位)。如果需要,上下文将被分割成几个块(使用doc_stride
作为重叠)。 - max_question_len (
int
, 可选, 默认为 64) — 标记化后问题的最大长度。如果需要,它将被截断。 - handle_impossible_answer (
bool
, 可选, 默认为False
) — 是否接受无法回答的答案。 - align_to_words (
bool
, 可选, 默认为True
) — 尝试将答案与实际单词对齐。在以空格分隔的语言上可以提高质量。在非空格分隔的语言(如日语或中文)上可能会有负面影响。
返回
一个 `dict` 或一个 `dict` 列表
每个结果都以字典形式返回,包含以下键:
- score (
float
) — 与答案相关的概率。 - start (
int
) — 答案的字符起始索引(在输入的标记化版本中)。 - end (
int
) — 答案的字符结束索引(在输入的标记化版本中)。 - answer (
str
) — 问题的答案。
通过使用上下文来回答作为输入给出的问题。
create_sample
< 源代码 >( question: typing.Union[str, list[str]] context: typing.Union[str, list[str]] ) → 一个或一个 SquadExample
列表
QuestionAnsweringPipeline 内部利用 SquadExample
。这个辅助方法封装了将问题和上下文转换为 SquadExample
的所有逻辑。
我们目前支持抽取式问答。
span_to_answer
< 源代码 >( text: str start: int end: int ) → 类似 `{‘answer’` 的字典
当从词元概率解码时,此方法将词元索引映射到初始上下文中的实际单词。
SummarizationPipeline
class transformers.SummarizationPipeline
< 源代码 >( *args **kwargs )
参数
- model (PreTrainedModel 或 TFPreTrainedModel) — 流水线用于进行预测的模型。对于 PyTorch,它需要是继承自 PreTrainedModel 的模型;对于 TensorFlow,它需要是继承自 TFPreTrainedModel 的模型。
- tokenizer (PreTrainedTokenizer) — 流水线用于为模型编码数据的分词器。该对象继承自 PreTrainedTokenizer。
- modelcard (
str
或ModelCard
, 可选) — 归属于此流水线模型使用的模型卡。 - framework (
str
, 可选) — 要使用的框架,可以是"pt"
(PyTorch) 或"tf"
(TensorFlow)。必须已安装指定的框架。如果未指定框架,则将默认使用当前已安装的框架。如果未指定框架但两种框架都已安装,则将默认使用
model
的框架,如果未提供模型,则默认使用 PyTorch。 - task (
str
, 默认为""
) — 流水线的任务标识符。 - num_workers (
int
, 可选, 默认为 8) — 当流水线使用 DataLoader 时(例如在 GPU 上为 Pytorch 模型传递数据集时),要使用的工作进程数。 - batch_size (
int
, 可选, 默认为 1) — 当流水线使用 DataLoader 时(例如在 GPU 上为 Pytorch 模型传递数据集时),要使用的批次大小。对于推理,这并不总是有益的,请阅读流水线批处理。 - args_parser (ArgumentHandler, 可选) — 负责解析所提供流水线参数的对象的引用。
- device (
int
, 可选, 默认为 -1) — 用于 CPU/GPU 支持的设备序号。将其设置为 -1 将使用 CPU,正数将在相应的 CUDA 设备 ID 上运行模型。您也可以传递原生的torch.device
或str
。 - torch_dtype (
str
或torch.dtype
, 可选) — 直接作为model_kwargs
发送(只是一个更简单的快捷方式),以使用此模型可用的精度(torch.float16
、torch.bfloat16
等或"auto"
)。 - binary_output (
bool
, 可选, 默认为False
) — 指示流水线的输出应为序列化格式(即 pickle)还是原始输出数据(例如文本)的标志。
对新闻文章和其他文档进行摘要。
目前可以使用以下任务标识符从 pipeline() 加载此摘要流水线:"summarization"
。
此流水线可以使用的模型是已经在摘要任务上进行了微调的模型,目前包括:’bart-large-cnn’、’google-t5/t5-small’、’google-t5/t5-base’、’google-t5/t5-large’、’google-t5/t5-3b’、’google-t5/t5-11b’。请参阅 huggingface.co/models 上可用的最新模型列表。有关可用参数的列表,请参阅以下文档
除非您使用的模型在其配置文件(generation_config.json
)中明确设置了这些生成参数,否则将使用以下默认值:
- max_new_tokens: 256
- num_beams: 4
用法
# use bart in pytorch
summarizer = pipeline("summarization")
summarizer("An apple a day, keeps the doctor away", min_length=5, max_length=20)
# use t5 in tf
summarizer = pipeline("summarization", model="google-t5/t5-base", tokenizer="google-t5/t5-base", framework="tf")
summarizer("An apple a day, keeps the doctor away", min_length=5, max_length=20)
__call__
< 源代码 >( *args **kwargs ) → 一个列表或一个 dict
的列表的列表
参数
- documents (str 或
list[str]
) — 一篇或多篇文章(或一个文章列表)用于摘要。 - return_text (
bool
, 可选, 默认为True
) — 是否在输出中包含解码后的文本 - return_tensors (
bool
, 可选, 默认为False
) — 是否在输出中包含预测的张量(作为词元索引)。 - clean_up_tokenization_spaces (
bool
, 可选, 默认为False
) — 是否清理文本输出中可能存在的多余空格。 - generate_kwargs — 传递给模型 generate 方法的额外关键字参数(请参见与您的框架对应的 generate 方法此处)。
返回
dict
的列表或列表的列表
每个结果都以字典形式返回,包含以下键:
- summary_text (
str
,当return_text=True
时存在) — 相应输入的摘要。 - summary_token_ids (
torch.Tensor
或tf.Tensor
,当return_tensors=True
时存在) — 摘要的词元 ID。
对作为输入给出的文本进行摘要。
TableQuestionAnsweringPipeline
class transformers.TableQuestionAnsweringPipeline
< 源代码 >( args_parser = <transformers.pipelines.table_question_answering.TableQuestionAnsweringArgumentHandler object at 0x7eff9573bdf0> *args **kwargs )
参数
- model (PreTrainedModel 或 TFPreTrainedModel) — 流水线用于进行预测的模型。对于 PyTorch,它需要是继承自 PreTrainedModel 的模型;对于 TensorFlow,它需要是继承自 TFPreTrainedModel 的模型。
- tokenizer (PreTrainedTokenizer) — 流水线用于为模型编码数据的分词器。该对象继承自 PreTrainedTokenizer。
- modelcard (
str
或ModelCard
, 可选) — 归属于此流水线模型使用的模型卡。 - framework (
str
, 可选) — 要使用的框架,可以是"pt"
(PyTorch) 或"tf"
(TensorFlow)。必须已安装指定的框架。如果未指定框架,则将默认使用当前已安装的框架。如果未指定框架但两种框架都已安装,则将默认使用
model
的框架,如果未提供模型,则默认使用 PyTorch。 - task (
str
, 默认为""
) — 流水线的任务标识符。 - num_workers (
int
, 可选, 默认为 8) — 当流水线使用 DataLoader 时(例如在 GPU 上为 Pytorch 模型传递数据集时),要使用的工作进程数。 - batch_size (
int
, optional, defaults to 1) — 当 pipeline 使用 DataLoader 时(例如在 GPU 上为 Pytorch 模型传递数据集时),要使用的批处理大小。对于推理,这并非总是有益的,请阅读使用 pipeline 进行批处理。 - args_parser (ArgumentHandler, optional) — 对负责解析所提供 pipeline 参数的对象的引用。
- device (
int
, optional, defaults to -1) — 用于 CPU/GPU 支持的设备序号。将其设置为 -1 将使用 CPU,正数将在相应的 CUDA 设备 ID 上运行模型。您也可以传递原生的torch.device
或str
。 - torch_dtype (
str
ortorch.dtype
, optional) — 直接作为model_kwargs
发送(只是一个更简单的快捷方式),以使用此模型的可用精度(torch.float16
,torch.bfloat16
, … 或"auto"
)。 - binary_output (
bool
, optional, defaults toFalse
) — 指示 pipeline 的输出应该是序列化格式(例如 pickle)还是原始输出数据(例如文本)的标志。
使用 ModelForTableQuestionAnswering
的表格问答 pipeline。此 pipeline 仅在 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() 使用以下任务标识符加载:"table-question-answering"
。
此 pipeline 可以使用的模型是那些在表格问答任务上进行微调的模型。请参阅 huggingface.co/models 上可用的最新模型列表。
__call__
< source >( *args **kwargs ) → 包含结果的字典或字典列表
参数
- table (
pd.DataFrame
orDict
) — Pandas DataFrame 或将被转换为包含所有表格值的 DataFrame 的字典。有关字典示例,请参见上文。 - query (
str
orlist[str]
) — 将与表格一起发送到模型的查询或查询列表。 - sequential (
bool
, optional, defaults toFalse
) — 是按顺序进行推理还是批量进行。批量处理速度更快,但像 SQA 这样的模型,由于其对话性质,需要按顺序进行推理以提取序列内的关系。 - padding (
bool
,str
or PaddingStrategy, optional, defaults toFalse
) — 激活和控制填充。接受以下值:True
或'longest'
:填充到批处理中最长的序列(如果只提供单个序列,则不填充)。'max_length'
:填充到由max_length
参数指定的最大长度,如果未提供该参数,则填充到模型可接受的最大输入长度。False
或'do_not_pad'
(默认):不填充(即,可以输出具有不同长度序列的批处理)。
- truncation (
bool
,str
orTapasTruncationStrategy
, optional, defaults toFalse
) — 激活和控制截断。接受以下值:True
或'drop_rows_to_fit'
:截断到由max_length
参数指定的最大长度,如果未提供该参数,则截断到模型可接受的最大输入长度。这将逐行截断,从表格中移除行。False
或'do_not_truncate'
(默认):不截断(即,可以输出序列长度大于模型最大可接受输入大小的批处理)。
返回
包含结果的字典或字典列表
每个结果都是一个包含以下键的字典
- answer (
str
) — 给定表格的查询答案。如果存在聚合器,答案前将加上AGGREGATOR >
。 - coordinates (
list[tuple[int, int]]
) — 答案单元格的坐标。 - cells (
list[str]
) — 由答案单元格值组成的字符串列表。 - aggregator (
str
) — 如果模型有聚合器,则返回该聚合器。
根据表格回答查询。pipeline 接受下面详述的几种输入类型
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
TextClassificationPipeline
class transformers.TextClassificationPipeline
< source >( **kwargs )
参数
- model (PreTrainedModel or TFPreTrainedModel) — pipeline 用于进行预测的模型。对于 PyTorch,这需要是继承自 PreTrainedModel 的模型;对于 TensorFlow,则是继承自 TFPreTrainedModel 的模型。
- tokenizer (PreTrainedTokenizer) — pipeline 用于为模型编码数据的分词器。该对象继承自 PreTrainedTokenizer。
- modelcard (
str
orModelCard
, optional) — 归属于此 pipeline 模型的模型卡。 - framework (
str
, optional) — 要使用的框架,"pt"
表示 PyTorch,"tf"
表示 TensorFlow。必须安装指定的框架。如果未指定框架,将默认使用当前安装的框架。如果未指定框架且两个框架都已安装,将默认使用
model
的框架,如果未提供模型,则默认为 PyTorch。 - task (
str
, defaults to""
) — pipeline 的任务标识符。 - num_workers (
int
, optional, defaults to 8) — 当 pipeline 使用 DataLoader 时(例如在 GPU 上为 Pytorch 模型传递数据集时),要使用的工作进程数。 - batch_size (
int
, optional, defaults to 1) — 当 pipeline 使用 DataLoader 时(例如在 GPU 上为 Pytorch 模型传递数据集时),要使用的批处理大小。对于推理,这并非总是有益的,请阅读使用 pipeline 进行批处理。 - args_parser (ArgumentHandler, optional) — 对负责解析所提供 pipeline 参数的对象的引用。
- device (
int
, optional, defaults to -1) — 用于 CPU/GPU 支持的设备序号。将其设置为 -1 将使用 CPU,正数将在相应的 CUDA 设备 ID 上运行模型。您也可以传递原生的torch.device
或str
。 - torch_dtype (
str
ortorch.dtype
, optional) — 直接作为model_kwargs
发送(只是一个更简单的快捷方式),以使用此模型的可用精度(torch.float16
,torch.bfloat16
, … 或"auto"
)。 - binary_output (
bool
, optional, defaults toFalse
) — 指示 pipeline 的输出应该是序列化格式(例如 pickle)还是原始输出数据(例如文本)的标志。 - return_all_scores (
bool
, optional, defaults toFalse
) — 是返回所有预测分数,还是只返回预测类别的分数。 - function_to_apply (
str
, optional, defaults to"default"
) — 应用于模型输出以检索分数的函数。接受四种不同的值:"default"
:如果模型只有一个标签,将对输出应用 sigmoid 函数。如果模型有多个标签,将对输出应用 softmax 函数。对于回归任务,不会对输出应用任何函数。"sigmoid"
:对输出应用 sigmoid 函数。"softmax"
:对输出应用 softmax 函数。"none"
:不对输出应用任何函数。
使用任何 ModelForSequenceClassification
的文本分类 pipeline。有关更多信息,请参阅序列分类示例。
示例
>>> 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() 使用以下任务标识符加载:"sentiment-analysis"
(用于根据正面或负面情绪对序列进行分类)。
如果有多个分类标签可用(model.config.num_labels >= 2
),pipeline 将对结果运行 softmax。如果只有一个标签,pipeline 将对结果运行 sigmoid。对于回归任务(model.config.problem_type == "regression"
),不会对输出应用任何函数。
此 pipeline 可以使用的模型是那些在序列分类任务上进行微调的模型。请参阅 huggingface.co/models 上可用的最新模型列表。
__call__
< source >( inputs: typing.Union[str, list[str], dict[str, str], list[dict[str, str]]] **kwargs: typing.Any ) → 一个 dict
列表
参数
- inputs (
str
orlist[str]
ordict[str]
, orlist[dict[str]]
) — 一个或多个要分类的文本。为了使用文本对进行分类,您可以发送一个包含{"text", "text_pair"}
键的字典,或这些字典的列表。 - top_k (
int
, optional, defaults to1
) — 返回多少个结果。 - function_to_apply (
str
, optional, defaults to"default"
) — 应用于模型输出以检索分数的函数。接受四种不同的值:如果未指定此参数,则将根据标签数量应用以下函数:
- 如果问题类型是回归,将不对输出应用任何函数。
- 如果模型只有一个标签,将对输出应用 sigmoid 函数。
- 如果模型有多个标签,将对输出应用 softmax 函数。
可能的值为:
"sigmoid"
:对输出应用 sigmoid 函数。"softmax"
:对输出应用 softmax 函数。"none"
:不对输出应用任何函数。
返回
一个 dict
列表
每个结果都以字典列表的形式出现,包含以下键:
- label (
str
) — 预测的标签。 - score (
float
) — 对应的概率。
如果使用 top_k
,则每个标签返回一个这样的字典。
对给定的输入文本进行分类。
TextGenerationPipeline
class transformers.TextGenerationPipeline
< source >( *args **kwargs )
参数
- model (PreTrainedModel or TFPreTrainedModel) — pipeline 用于进行预测的模型。对于 PyTorch,这需要是继承自 PreTrainedModel 的模型;对于 TensorFlow,则是继承自 TFPreTrainedModel 的模型。
- tokenizer (PreTrainedTokenizer) — pipeline 用于为模型编码数据的分词器。该对象继承自 PreTrainedTokenizer。
- modelcard (
str
orModelCard
, optional) — 归属于此 pipeline 模型的模型卡。 - framework (
str
, optional) — 要使用的框架,"pt"
表示 PyTorch,"tf"
表示 TensorFlow。必须安装指定的框架。如果未指定框架,将默认使用当前安装的框架。如果未指定框架且两个框架都已安装,将默认使用
model
的框架,如果未提供模型,则默认为 PyTorch。 - task (
str
, defaults to""
) — pipeline 的任务标识符。 - num_workers (
int
, optional, defaults to 8) — 当 pipeline 使用 DataLoader 时(例如在 GPU 上为 Pytorch 模型传递数据集时),要使用的工作进程数。 - batch_size (
int
, optional, defaults to 1) — 当 pipeline 使用 DataLoader 时(例如在 GPU 上为 Pytorch 模型传递数据集时),要使用的批处理大小。对于推理,这并非总是有益的,请阅读使用 pipeline 进行批处理。 - args_parser (ArgumentHandler, optional) — 对负责解析所提供 pipeline 参数的对象的引用。
- device (
int
, optional, defaults to -1) — 用于 CPU/GPU 支持的设备序号。将其设置为 -1 将使用 CPU,正数将在相应的 CUDA 设备 ID 上运行模型。您也可以传递原生的torch.device
或str
。 - torch_dtype (
str
ortorch.dtype
, optional) — 直接作为model_kwargs
发送(只是一个更简单的快捷方式),以使用此模型的可用精度(torch.float16
,torch.bfloat16
, … 或"auto"
)。 - binary_output (
bool
, optional, defaults toFalse
) — 指示 pipeline 的输出应该是序列化格式(例如 pickle)还是原始输出数据(例如文本)的标志。
使用任何 ModelWithLMHead
或 ModelForCausalLM
的语言生成 pipeline。此 pipeline 预测将跟随指定文本提示的词语。当底层模型是对话模型时,它也可以接受一个或多个聊天,在这种情况下,pipeline 将以聊天模式运行,并通过添加其响应来继续聊天。每个聊天都采用字典列表的形式,其中每个字典都包含“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 目前可以通过 pipeline() 使用以下任务标识符加载:"text-generation"
。
此 pipeline 可以使用的模型是那些使用自回归语言建模目标训练的模型。请参阅 [huggingface.co/models] 上的可用文本补全模型列表和对话模型列表。
__call__
< source >( text_inputs **kwargs ) → 一个列表或列表的列表,其中包含 dict
参数
- text_inputs (
str
,list[str]
, list[dict[str, str]] 或list[list[dict[str, str]]]
) — 一个或多个待补全的提示(或一个提示列表)。如果传入字符串或字符串列表,此 pipeline 将延续每个提示。或者,也可以传入“聊天”形式,即一个包含“role”和“content”键的字典列表,或多个此类聊天记录的列表。当传入聊天记录时,将使用模型的聊天模板对其进行格式化,然后再传递给模型。 - return_tensors (
bool
, 可选, 默认为False
) — 在输出中返回预测的张量(作为 token 索引)。如果设置为True
,则不返回解码后的文本。 - return_text (
bool
, 可选) — 在输出中返回解码后的文本。 - return_full_text (
bool
, 可选, 默认为True
) — 如果设置为False
,则只返回新增的文本,否则返回完整文本。不能与return_text
同时指定。 - clean_up_tokenization_spaces (
bool
, 可选, 默认为True
) — 是否清理文本输出中可能出现的额外空格。 - continue_final_message(
bool
, 可选) — 这表示您希望模型继续输入聊天中的最后一条消息,而不是开始一条新消息,从而允许您“预填充”其响应。默认情况下,当输入聊天中的最后一条消息角色为assistant
时,此值为True
,否则为False
,但您可以通过设置此标志来手动覆盖该行为。 - prefix (
str
, 可选) — 添加到提示的前缀。 - handle_long_generation (
str
, 可选) — 默认情况下,此 pipeline 不处理长文本生成(即以某种形式超过模型最大长度的生成)。没有完美的方法来解决这个问题(更多信息:https://github.com/huggingface/transformers/issues/14033#issuecomment-948385227)。这里提供了根据您的用例来解决该问题的常用策略。None
:默认策略,不进行特殊处理"hole"
:从输入的左侧截断,并留出足够的空间让生成发生(可能会截断大量提示,并且不适用于生成超过模型容量的情况)
- generate_kwargs (
dict
, 可选) — 传递给模型 generate 方法的额外关键字参数(请参阅与您的框架对应的 generate 方法此处)。
返回
一个列表或列表的列表,元素为 dict
返回以下字典之一(不能同时返回 generated_text
和 generated_token_ids
)
- generated_text (
str
,当return_text=True
时存在) — 生成的文本。 - generated_token_ids (
torch.Tensor
或tf.Tensor
,当return_tensors=True
时存在) — 生成文本的 token ID。
补全作为输入给出的提示。
Text2TextGenerationPipeline
class transformers.Text2TextGenerationPipeline
< 源码 >( *args **kwargs )
参数
- model (PreTrainedModel 或 TFPreTrainedModel) — pipeline 将用于进行预测的模型。对于 PyTorch,这需要是继承自 PreTrainedModel 的模型;对于 TensorFlow,这需要是继承自 TFPreTrainedModel 的模型。
- tokenizer (PreTrainedTokenizer) — pipeline 将用于为模型编码数据的分词器。该对象继承自 PreTrainedTokenizer。
- modelcard (
str
或ModelCard
, 可选) — 归属于此 pipeline 模型 的模型卡。 - framework (
str
, 可选) — 要使用的框架,可以是"pt"
(PyTorch) 或"tf"
(TensorFlow)。指定的框架必须已安装。如果未指定框架,将默认为当前已安装的框架。如果未指定框架且两个框架都已安装,将默认为
model
的框架,或者如果未提供模型,则默认为 PyTorch。 - task (
str
, 默认为""
) — pipeline 的任务标识符。 - num_workers (
int
, 可选, 默认为 8) — 当 pipeline 使用 DataLoader(在 GPU 上为 Pytorch 模型传递数据集时)时,要使用的工作进程数量。 - batch_size (
int
, 可选, 默认为 1) — 当 pipeline 使用 DataLoader(在 GPU 上为 Pytorch 模型传递数据集时)时,要使用的批量大小,对于推理而言,这并不总是有益的,请阅读 Pipeline 批处理。 - args_parser (ArgumentHandler, 可选) — 负责解析提供的 pipeline 参数的对象的引用。
- device (
int
, 可选, 默认为 -1) — 支持 CPU/GPU 的设备序号。设置为 -1 将使用 CPU,正数将在相应的 CUDA 设备 ID 上运行模型。您也可以传递原生的torch.device
或str
。 - torch_dtype (
str
或torch.dtype
, 可选) — 直接作为model_kwargs
发送(只是一个更简单的快捷方式),以使用此模型可用的精度(torch.float16
,torch.bfloat16
, ... 或"auto"
)。 - binary_output (
bool
, 可选, 默认为False
) — 指示 pipeline 的输出是否应以序列化格式(例如 pickle)或原始输出数据(例如文本)进行的标志。
使用 seq2seq 模型进行文本到文本生成的 Pipeline。
除非您使用的模型在其配置文件(generation_config.json
)中明确设置了这些生成参数,否则将使用以下默认值:
- max_new_tokens: 256
- num_beams: 4
示例
>>> from transformers import pipeline
>>> generator = pipeline(model="mrm8488/t5-base-finetuned-question-generation-ap")
>>> generator(
... "answer: Manuel context: Manuel has created RuPERTa-base with the support of HF-Transformers and Google"
... )
[{'generated_text': 'question: Who created the RuPERTa-base?'}]
在pipeline 教程中了解更多关于使用 pipeline 的基础知识。您可以将文本生成参数传递给此 pipeline 以控制停止标准、解码策略等。在文本生成策略和文本生成中了解更多关于文本生成参数的信息。
此 Text2TextGenerationPipeline 目前可以从 pipeline() 使用以下任务标识符加载:"text2text-generation"
。
此 pipeline 可以使用的模型是那些在翻译任务上进行了微调的模型。请在 huggingface.co/models 上查看最新的可用模型列表。有关可用参数的列表,请参阅以下文档。
用法
text2text_generator = pipeline("text2text-generation")
text2text_generator("question: What is 42 ? context: 42 is the answer to life, the universe and everything")
__call__
< 源码 >( *args: typing.Union[str, list[str]] **kwargs: typing.Any ) → 一个列表或列表的列表,元素为 dict
参数
- args (
str
或list[str]
) — 编码器的输入文本。 - return_tensors (
bool
, 可选, 默认为False
) — 是否在输出中包含预测的张量(作为 token 索引)。 - return_text (
bool
, 可选, 默认为True
) — 是否在输出中包含解码后的文本。 - clean_up_tokenization_spaces (
bool
, 可选, 默认为False
) — 是否清理文本输出中可能出现的额外空格。 - truncation (
TruncationStrategy
, 可选, 默认为TruncationStrategy.DO_NOT_TRUNCATE
) — pipeline 内部分词的截断策略。TruncationStrategy.DO_NOT_TRUNCATE
(默认) 永远不会截断,但有时为了适应模型的 max_length 而截断输入比后续抛出错误更可取。 - generate_kwargs — 传递给模型 generate 方法的额外关键字参数(请参阅与您的框架对应的 generate 方法此处)。
返回
dict
的列表或列表的列表
每个结果都以字典形式返回,包含以下键:
- generated_text (
str
,当return_text=True
时存在) — 生成的文本。 - generated_token_ids (
torch.Tensor
或tf.Tensor
,当return_tensors=True
时存在) — 生成文本的 token ID。
使用作为输入给出的文本生成输出文本。
检查给定输入相对于模型是否存在潜在问题。
TokenClassificationPipeline
class transformers.TokenClassificationPipeline
< 源码 >( args_parser = <transformers.pipelines.token_classification.TokenClassificationArgumentHandler object at 0x7eff957a1a80> *args **kwargs )
参数
- model (PreTrainedModel 或 TFPreTrainedModel) — pipeline 将用于进行预测的模型。对于 PyTorch,这需要是继承自 PreTrainedModel 的模型;对于 TensorFlow,这需要是继承自 TFPreTrainedModel 的模型。
- tokenizer (PreTrainedTokenizer) — pipeline 将用于为模型编码数据的分词器。该对象继承自 PreTrainedTokenizer。
- modelcard (
str
或ModelCard
, 可选) — 归属于此 pipeline 模型 的模型卡。 - framework (
str
, 可选) — 要使用的框架,可以是"pt"
(PyTorch) 或"tf"
(TensorFlow)。指定的框架必须已安装。如果未指定框架,将默认为当前已安装的框架。如果未指定框架且两个框架都已安装,将默认为
model
的框架,或者如果未提供模型,则默认为 PyTorch。 - task (
str
, 默认为""
) — pipeline 的任务标识符。 - num_workers (
int
, 可选, 默认为 8) — 当 pipeline 使用 DataLoader(在 GPU 上为 Pytorch 模型传递数据集时)时,要使用的工作进程数量。 - batch_size (
int
, 可选, 默认为 1) — 当 pipeline 使用 DataLoader(在 GPU 上为 Pytorch 模型传递数据集时)时,要使用的批量大小,对于推理而言,这并不总是有益的,请阅读 Pipeline 批处理。 - args_parser (ArgumentHandler, 可选) — 负责解析提供的 pipeline 参数的对象的引用。
- device (
int
, 可选, 默认为 -1) — 支持 CPU/GPU 的设备序号。设置为 -1 将使用 CPU,正数将在相应的 CUDA 设备 ID 上运行模型。您也可以传递原生的torch.device
或str
。 - torch_dtype (
str
或torch.dtype
, 可选) — 直接作为model_kwargs
发送(只是一个更简单的快捷方式),以使用此模型可用的精度(torch.float16
,torch.bfloat16
, ... 或"auto"
)。 - binary_output (
bool
, 可选, 默认为False
) — 指示 pipeline 的输出是否应以序列化格式(例如 pickle)或原始输出数据(例如文本)进行的标志。 - ignore_labels (
list[str]
, 默认为["O"]
) — 要忽略的标签列表。 - grouped_entities (
bool
, 可选, 默认为False
) — 已弃用,请改用aggregation_strategy
。是否在预测中将对应同一实体的 token 组合在一起。 - 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
策略,但词语不能最终带有不同的标签。当存在歧义时,词语将简单地使用该词第一个 token 的标签。 - “average”:(仅适用于基于词的模型)将使用
SIMPLE
策略,但词语不能最终带有不同的标签。分数将首先在 token 之间取平均,然后应用最大标签。 - “max”:(仅适用于基于词的模型)将使用
SIMPLE
策略,但词语不能最终带有不同的标签。词语实体将简单地是得分最高的 token。
使用任何 ModelForTokenClassification
的命名实体识别 pipeline。有关更多信息,请参阅命名实体识别示例。
示例
>>> 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}]
在流水线教程中了解有关使用流水线基础知识的更多信息。
此 token 识别 pipeline 目前可以从 pipeline() 使用以下任务标识符加载:"ner"
(用于预测序列中 token 的类别:person, organisation, location 或 miscellaneous)。
此 pipeline 可以使用的模型是那些在 token 分类任务上进行了微调的模型。请在 huggingface.co/models 上查看最新的可用模型列表。
__call__
< 源码 >( inputs: typing.Union[str, list[str]] **kwargs: typing.Any ) → dict
的列表或列表的列表
参数
返回
dict
的列表或列表的列表
每个结果都以字典列表的形式出现(对应输入中的每个 token 一个,或者如果此 pipeline 使用 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 进行分类。
覆盖给定词中不一致的 token,以强制在词边界上达成一致。
例如:micro|soft| com|pany| B-ENT I-NAME I-ENT I-ENT 使用 first 策略将被重写为 microsoft| company| B-ENT I-ENT
gather_pre_entities
< 源码 >( sentence: str input_ids: ndarray scores: ndarray offset_mapping: typing.Optional[list[tuple[int, int]]] special_tokens_mask: ndarray aggregation_strategy: AggregationStrategy word_ids: typing.Optional[list[typing.Optional[int]]] = None word_to_chars_map: typing.Optional[list[tuple[int, int]]] = None )
将各种 numpy 数组融合成包含聚合所需所有信息的字典。
查找并组合具有相同实体预测的相邻 token。
将具有相同预测实体的相邻词元(token)组合在一起。
TranslationPipeline
class transformers.TranslationPipeline
< 源 >( *args **kwargs )
参数
- model (PreTrainedModel or TFPreTrainedModel) — 管道将用于进行预测的模型。对于 PyTorch,它必须是继承自 PreTrainedModel 的模型;对于 TensorFlow,它必须是继承自 TFPreTrainedModel 的模型。
- tokenizer (PreTrainedTokenizer) — 管道将用于为模型编码数据的分词器。该对象继承自 PreTrainedTokenizer。
- modelcard (
str
orModelCard
, optional) — 归属于此管道模型的模型卡。 - framework (
str
, optional) — 要使用的框架,可以是"pt"
(PyTorch) 或"tf"
(TensorFlow)。指定的框架必须已安装。如果未指定框架,将默认使用当前已安装的框架。如果未指定框架且两个框架都已安装,将默认使用
model
的框架,或者在未提供模型时默认使用 PyTorch。 - task (
str
, defaults to""
) — 管道的任务标识符。 - num_workers (
int
, optional, defaults to 8) — 当管道使用 DataLoader 时(例如,在 GPU 上为 PyTorch 模型传递数据集时),要使用的工作进程数。 - batch_size (
int
, optional, defaults to 1) — 当管道使用 DataLoader 时(例如,在 GPU 上为 PyTorch 模型传递数据集时),要使用的批大小。对于推理来说,这并不总是有益的,请阅读使用管道进行批处理。 - args_parser (ArgumentHandler, optional) — 对负责解析所提供管道参数的对象的引用。
- device (
int
, optional, defaults to -1) — 支持 CPU/GPU 的设备序号。设置为 -1 将使用 CPU,正数将在相应的 CUDA 设备 ID 上运行模型。您也可以传递原生的torch.device
或str
。 - torch_dtype (
str
ortorch.dtype
, optional) — 直接作为model_kwargs
传递(只是一个更简单的快捷方式),以使用此模型的可用精度(torch.float16
、torch.bfloat16
等或"auto"
)。 - binary_output (
bool
, optional, defaults toFalse
) — 指示管道的输出是应该以序列化格式(即 pickle)还是以原始输出数据(例如文本)的形式进行的标志。
将一种语言翻译成另一种语言。
当前可以使用任务标识符 "translation_xx_to_yy"
从 pipeline() 加载此翻译管道。
此管道可以使用的模型是那些已经在翻译任务上进行了微调的模型。请在 huggingface.co/models 上查看最新的可用模型列表。有关可用参数的列表,请参阅以下文档。
除非您使用的模型在其配置文件(generation_config.json
)中明确设置了这些生成参数,否则将使用以下默认值:
- max_new_tokens: 256
- num_beams: 4
__call__
< 源 >( *args **kwargs ) → 一个列表或一个 dict
的列表的列表
参数
- args (
str
orlist[str]
) — 要翻译的文本。 - return_tensors (
bool
, optional, defaults toFalse
) — 是否在输出中包含预测的张量(作为词元索引)。 - return_text (
bool
, optional, defaults toTrue
) — 是否在输出中包含解码后的文本。 - clean_up_tokenization_spaces (
bool
, optional, defaults toFalse
) — 是否清除文本输出中可能存在的多余空格。 - src_lang (
str
, optional) — 输入文本的语言。对于多语言模型可能是必需的。对于单语对翻译模型没有影响。 - tgt_lang (
str
, optional) — 期望输出的语言。对于多语言模型可能是必需的。对于单语对翻译模型没有影响。 - generate_kwargs — 要传递给模型生成方法的附加关键字参数(请参阅与您的框架对应的生成方法 此处)。
返回
dict
的列表或列表的列表
每个结果都以字典形式返回,包含以下键:
- translation_text (
str
, 仅当return_text=True
时存在) — 翻译结果。 - translation_token_ids (
torch.Tensor
或tf.Tensor
, 仅当return_tensors=True
时存在) — 翻译结果的词元 ID。
翻译作为输入给定的文本。
ZeroShotClassificationPipeline
class transformers.ZeroShotClassificationPipeline
< 源 >( args_parser = <transformers.pipelines.zero_shot_classification.ZeroShotClassificationArgumentHandler object at 0x7eff957a35e0> *args **kwargs )
参数
- model (PreTrainedModel or TFPreTrainedModel) — 管道将用于进行预测的模型。对于 PyTorch,它必须是继承自 PreTrainedModel 的模型;对于 TensorFlow,它必须是继承自 TFPreTrainedModel 的模型。
- tokenizer (PreTrainedTokenizer) — 管道将用于为模型编码数据的分词器。该对象继承自 PreTrainedTokenizer。
- modelcard (
str
orModelCard
, optional) — 归属于此管道模型的模型卡。 - framework (
str
, optional) — 要使用的框架,可以是"pt"
(PyTorch) 或"tf"
(TensorFlow)。指定的框架必须已安装。如果未指定框架,将默认使用当前已安装的框架。如果未指定框架且两个框架都已安装,将默认使用
model
的框架,或者在未提供模型时默认使用 PyTorch。 - task (
str
, defaults to""
) — 管道的任务标识符。 - num_workers (
int
, optional, defaults to 8) — 当管道使用 DataLoader 时(例如,在 GPU 上为 PyTorch 模型传递数据集时),要使用的工作进程数。 - batch_size (
int
, optional, defaults to 1) — 当管道使用 DataLoader 时(例如,在 GPU 上为 PyTorch 模型传递数据集时),要使用的批大小。对于推理来说,这并不总是有益的,请阅读使用管道进行批处理。 - args_parser (ArgumentHandler, optional) — 对负责解析所提供管道参数的对象的引用。
- device (
int
, optional, defaults to -1) — 支持 CPU/GPU 的设备序号。设置为 -1 将使用 CPU,正数将在相应的 CUDA 设备 ID 上运行模型。您也可以传递原生的torch.device
或str
。 - torch_dtype (
str
ortorch.dtype
, optional) — 直接作为model_kwargs
传递(只是一个更简单的快捷方式),以使用此模型的可用精度(torch.float16
、torch.bfloat16
等或"auto"
)。 - binary_output (
bool
, optional, defaults toFalse
) — 指示管道的输出是应该以序列化格式(即 pickle)还是以原始输出数据(例如文本)的形式进行的标志。
基于自然语言推理(NLI)的零样本分类管道,使用在 NLI 任务上训练的 `ModelForSequenceClassification`。等同于 `text-classification` 管道,但这些模型不需要硬编码数量的潜在类别,它们可以在运行时选择。这通常意味着它会更慢,但灵活性**要大得多**。
可以传递序列和标签的任意组合,每个组合将被构造成一个前提/假设对并传递给预训练模型。然后,*蕴含(entailment)* 的 logit 被视为候选标签有效的 logit。可以使用任何 NLI 模型,但*蕴含*标签的 ID 必须包含在模型配置的 :attr:`~transformers.PretrainedConfig.label2id` 中。
示例
>>> from transformers import pipeline
>>> oracle = pipeline(model="facebook/bart-large-mnli")
>>> oracle(
... "I have a problem with my iphone that needs to be resolved asap!!",
... candidate_labels=["urgent", "not urgent", "phone", "tablet", "computer"],
... )
{'sequence': 'I have a problem with my iphone that needs to be resolved asap!!', 'labels': ['urgent', 'phone', 'computer', 'not urgent', 'tablet'], 'scores': [0.504, 0.479, 0.013, 0.003, 0.002]}
>>> oracle(
... "I have a problem with my iphone that needs to be resolved asap!!",
... candidate_labels=["english", "german"],
... )
{'sequence': 'I have a problem with my iphone that needs to be resolved asap!!', 'labels': ['english', 'german'], 'scores': [0.814, 0.186]}
在流水线教程中了解有关使用流水线基础知识的更多信息。
当前可以使用任务标识符 "zero-shot-classification"
从 pipeline() 加载此 NLI 管道。
此管道可以使用的模型是那些已经在 NLI 任务上进行了微调的模型。请在 huggingface.co/models 上查看最新的可用模型列表。
__call__
< 源 >( sequences: typing.Union[str, list[str]] *args **kwargs ) → dict
或 dict
列表
参数
- sequences (
str
orlist[str]
) — 要分类的序列。如果模型输入太大,将被截断。 - candidate_labels (
str
orlist[str]
) — 用于对每个序列进行分类的可能类别标签集。可以是一个单一标签、一个逗号分隔的标签字符串或一个标签列表。 - hypothesis_template (
str
, optional, defaults to"This example is {}."
) — 用于将每个标签转换为 NLI 风格假设的模板。此模板必须包含一个 {} 或类似的语法,以便将候选标签插入模板中。例如,默认模板是 `"This example is {}."`。对于候选标签 `"sports"`,它将被输入到模型中,形式为 `"<cls> 要分类的序列 <sep> This example is sports . <sep>"`。默认模板在许多情况下效果很好,但根据任务设置,尝试不同的模板可能值得一试。 - multi_label (
bool
, optional, defaults toFalse
) — 是否允许多个候选标签为真。如果为 `False`,则对得分进行归一化,使得每个序列的标签似然之和为 1。如果为 `True`,则标签被视为独立的,并通过对蕴含分数与矛盾分数进行 softmax 来对每个候选标签的概率进行归一化。
返回
一个 `dict` 或一个 `dict` 列表
每个结果都以字典形式返回,包含以下键:
- sequence (
str
) — 此输出所对应的序列。 - labels (
list[str]
) — 按似然顺序排序的标签。 - scores (
list[float]
) — 每个标签的概率。
对作为输入给定的序列进行分类。更多信息请参阅 ZeroShotClassificationPipeline 文档。
多模态
可用于多模态任务的管道包括以下几种。
DocumentQuestionAnsweringPipeline
class transformers.DocumentQuestionAnsweringPipeline
< 源 >( *args **kwargs )
参数
- model (PreTrainedModel or TFPreTrainedModel) — 管道将用于进行预测的模型。对于 PyTorch,它必须是继承自 PreTrainedModel 的模型;对于 TensorFlow,它必须是继承自 TFPreTrainedModel 的模型。
- tokenizer (PreTrainedTokenizer) — 管道将用于为模型编码数据的分词器。该对象继承自 PreTrainedTokenizer。
- image_processor (BaseImageProcessor) — 管道将用于为模型编码数据的图像处理器。该对象继承自 BaseImageProcessor。
- modelcard (
str
orModelCard
, optional) — 归属于此管道模型的模型卡。 - framework (
str
, optional) — 要使用的框架,可以是"pt"
(PyTorch) 或"tf"
(TensorFlow)。指定的框架必须已安装。如果未指定框架,将默认使用当前已安装的框架。如果未指定框架且两个框架都已安装,将默认使用
model
的框架,或者在未提供模型时默认使用 PyTorch。 - task (
str
, defaults to""
) — 管道的任务标识符。 - num_workers (
int
, optional, defaults to 8) — 当管道使用 DataLoader 时(例如,在 GPU 上为 PyTorch 模型传递数据集时),要使用的工作进程数。 - batch_size (
int
, optional, defaults to 1) — 当管道使用 DataLoader 时(例如,在 GPU 上为 PyTorch 模型传递数据集时),要使用的批大小。对于推理来说,这并不总是有益的,请阅读使用管道进行批处理。 - args_parser (ArgumentHandler, optional) — 对负责解析所提供管道参数的对象的引用。
- device (
int
, optional, defaults to -1) — 支持 CPU/GPU 的设备序号。设置为 -1 将使用 CPU,正数将在相应的 CUDA 设备 ID 上运行模型。您也可以传递原生的torch.device
或str
。 - torch_dtype (
str
ortorch.dtype
, optional) — 直接作为model_kwargs
传递(只是一个更简单的快捷方式),以使用此模型的可用精度(torch.float16
、torch.bfloat16
等或"auto"
)。 - binary_output (
bool
, optional, defaults toFalse
) — 指示管道的输出是应该以序列化格式(即 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/spaces/impira/docquery/resolve/2359223c1837a7587402bda0f2643382a6eefeab/invoice.png",
... question="What is the invoice number?",
... )
[{'score': 0.425, 'answer': 'us-001', 'start': 16, 'end': 16}]
在流水线教程中了解有关使用流水线基础知识的更多信息。
当前可以使用任务标识符 "document-question-answering"
从 pipeline() 加载此文档问答管道。
此管道可以使用的模型是那些已经在文档问答任务上进行了微调的模型。请在 huggingface.co/models 上查看最新的可用模型列表。
__call__
< 源 >( image: typing.Union[ForwardRef('Image.Image'), str, list[dict[str, typing.Any]]] question: typing.Optional[str] = None word_boxes: typing.Optional[tuple[str, list[float]]] = None **kwargs: typing.Any ) → dict
或 dict
列表
参数
- image (
str
orPIL.Image
) — 管道处理三种类型的图像:- 指向图像的 http 链接的字符串
- 指向本地图像路径的字符串
- 直接在 PIL 中加载的图像
管道接受单个图像或一批图像。如果给定单个图像,它可以被广播到多个问题上。
- question (
str
) — 向文档提出的问题。 - word_boxes (
list[str, tuple[float, float, float, float]]
, optional) — 单词及其边界框(归一化到 0->1000)的列表。如果您提供此可选输入,对于需要它们的模型(例如 LayoutLM),流水线将使用这些单词和框,而不是在图像上运行 OCR 来派生它们。这允许您在多次调用流水线时重用 OCR 结果,而无需每次都重新运行。 - top_k (
int
, optional, defaults to 1) — 要返回的答案数量(将按可能性顺序选择)。请注意,如果上下文中没有足够的可用选项,我们将返回少于 top_k 个答案。 - doc_stride (
int
, optional, defaults to 128) — 如果文档中的单词太长,无法与模型的问题相匹配,它将被分成几个有重叠的块。此参数控制重叠的大小。 - max_answer_len (
int
, optional, defaults to 15) — 预测答案的最大长度(例如,只考虑长度较短的答案)。 - max_seq_len (
int
, optional, defaults to 384) — 传递给模型的每个块的总句子(上下文 + 问题)的最大长度(以词元为单位)。如果需要,上下文将被分成几个块(使用doc_stride
作为重叠)。 - max_question_len (
int
, optional, defaults to 64) — 标记化后问题的最大长度。如果需要,它将被截断。 - handle_impossible_answer (
bool
, optional, defaults toFalse
) — 是否接受“不可能”作为答案。 - lang (
str
, optional) — 运行 OCR 时使用的语言。默认为英语。 - tesseract_config (
str
, optional) — 运行 OCR 时传递给 tesseract 的附加标志。 - timeout (
float
, optional, defaults to None) — 从网页获取图片的最长等待时间(秒)。如果为 None,则不设置超时,调用可能会永远阻塞。
返回
一个 `dict` 或一个 `dict` 列表
每个结果都以字典形式返回,包含以下键:
- score (
float
) — 与答案相关的概率。 - start (
int
) — 答案的起始单词索引(在输入的 OCR 版本或提供的word_boxes
中)。 - end (
int
) — 答案的结束单词索引(在输入的 OCR 版本或提供的word_boxes
中)。 - answer (
str
) — 问题的答案。 - words (
list[int]
) — 答案中每个单词/框对的索引。
通过使用文档来回答作为输入给出的问题。文档被定义为一个图像和一个可选的(单词,框)元组列表,表示文档中的文本。如果未提供 word_boxes
,它将使用 Tesseract OCR 引擎(如果可用)为需要它们作为输入的 LayoutLM 类模型自动提取单词和框。对于 Donut 模型,不运行 OCR。
您可以通过多种方式调用流水线
pipeline(image=image, question=question)
pipeline(image=image, question=question, word_boxes=word_boxes)
pipeline([{"image": image, "question": question}])
pipeline([{"image": image, "question": question, "word_boxes": word_boxes}])
FeatureExtractionPipeline
class transformers.FeatureExtractionPipeline
< 源 >( model: typing.Union[ForwardRef('PreTrainedModel'), ForwardRef('TFPreTrainedModel')] tokenizer: typing.Optional[transformers.tokenization_utils.PreTrainedTokenizer] = None feature_extractor: typing.Optional[ForwardRef('SequenceFeatureExtractor')] = None image_processor: typing.Optional[transformers.image_processing_utils.BaseImageProcessor] = None processor: typing.Optional[transformers.processing_utils.ProcessorMixin] = None modelcard: typing.Optional[transformers.modelcard.ModelCard] = None framework: typing.Optional[str] = None task: str = '' args_parser: ArgumentHandler = None device: typing.Union[int, ForwardRef('torch.device')] = None torch_dtype: typing.Union[str, ForwardRef('torch.dtype'), NoneType] = None binary_output: bool = False **kwargs )
参数
- model (PreTrainedModel or TFPreTrainedModel) — 将被流水线用于进行预测的模型。对于 PyTorch,它需要是继承自 PreTrainedModel 的模型,对于 TensorFlow,它需要是继承自 TFPreTrainedModel 的模型。
- tokenizer (PreTrainedTokenizer) — 将被流水线用于为模型编码数据的分词器。此对象继承自 PreTrainedTokenizer。
- modelcard (
str
orModelCard
, optional) — 归属于此流水线模型的模型卡。 - framework (
str
, optional) — 要使用的框架,可以是"pt"
(PyTorch)或"tf"
(TensorFlow)。必须安装指定的框架。如果未指定框架,将默认为当前安装的框架。如果未指定框架且两个框架都已安装,将默认为
model
的框架,如果未提供模型,则默认为 PyTorch。 - task (
str
, defaults to""
) — 流水线的任务标识符。 - num_workers (
int
, optional, defaults to 8) — 当流水线将使用 DataLoader 时(当传递数据集,在 GPU 上使用 Pytorch 模型时),要使用的工作进程数。 - batch_size (
int
, optional, defaults to 1) — 当流水线将使用 DataLoader 时(当传递数据集,在 GPU 上使用 Pytorch 模型时),要使用的批量大小,对于推理而言,这并非总是有益的,请阅读流水线批处理。 - args_parser (ArgumentHandler, optional) — 对负责解析所提供流水线参数的对象的引用。
- device (
int
, optional, defaults to -1) — 用于 CPU/GPU 支持的设备序号。将其设置为 -1 将使用 CPU,正数将在关联的 CUDA 设备 ID 上运行模型。您也可以传递原生的torch.device
或str
。 - torch_dtype (
str
ortorch.dtype
, optional) — 直接作为model_kwargs
发送(只是一个更简单的快捷方式),以使用此模型的可用精度(torch.float16
、torch.bfloat16
等或"auto"
)。 - tokenize_kwargs (
dict
, optional) — 传递给分词器的额外关键字参数字典。 - return_tensors (
bool
, optional) — 如果为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])
在流水线教程中了解有关使用流水线基础知识的更多信息。
当前可以使用任务标识符 "feature-extraction"
从 pipeline() 加载此特征提取流水线。
所有模型都可以用于此流水线。在 huggingface.co/models 上查看所有模型列表,包括社区贡献的模型。
__call__
< 源 >( *args: typing.Union[str, list[str]] **kwargs: typing.Any ) → float
的嵌套列表
提取输入文本的特征。
ImageFeatureExtractionPipeline
class transformers.ImageFeatureExtractionPipeline
< 源 >( model: typing.Union[ForwardRef('PreTrainedModel'), ForwardRef('TFPreTrainedModel')] tokenizer: typing.Optional[transformers.tokenization_utils.PreTrainedTokenizer] = None feature_extractor: typing.Optional[ForwardRef('SequenceFeatureExtractor')] = None image_processor: typing.Optional[transformers.image_processing_utils.BaseImageProcessor] = None processor: typing.Optional[transformers.processing_utils.ProcessorMixin] = None modelcard: typing.Optional[transformers.modelcard.ModelCard] = None framework: typing.Optional[str] = None task: str = '' args_parser: ArgumentHandler = None device: typing.Union[int, ForwardRef('torch.device')] = None torch_dtype: typing.Union[str, ForwardRef('torch.dtype'), NoneType] = None binary_output: bool = False **kwargs )
参数
- model (PreTrainedModel or TFPreTrainedModel) — 将被流水线用于进行预测的模型。对于 PyTorch,它需要是继承自 PreTrainedModel 的模型,对于 TensorFlow,它需要是继承自 TFPreTrainedModel 的模型。
- image_processor (BaseImageProcessor) — 将被流水线用于为模型编码数据的图像处理器。此对象继承自 BaseImageProcessor。
- modelcard (
str
orModelCard
, optional) — 归属于此流水线模型的模型卡。 - framework (
str
, optional) — 要使用的框架,可以是"pt"
(PyTorch)或"tf"
(TensorFlow)。必须安装指定的框架。如果未指定框架,将默认为当前安装的框架。如果未指定框架且两个框架都已安装,将默认为
model
的框架,如果未提供模型,则默认为 PyTorch。 - task (
str
, defaults to""
) — 流水线的任务标识符。 - num_workers (
int
, optional, defaults to 8) — 当流水线将使用 DataLoader 时(当传递数据集,在 GPU 上使用 Pytorch 模型时),要使用的工作进程数。 - batch_size (
int
, optional, defaults to 1) — 当流水线将使用 DataLoader 时(当传递数据集,在 GPU 上使用 Pytorch 模型时),要使用的批量大小,对于推理而言,这并非总是有益的,请阅读流水线批处理。 - args_parser (ArgumentHandler, optional) — 对负责解析所提供流水线参数的对象的引用。
- device (
int
, optional, defaults to -1) — 用于 CPU/GPU 支持的设备序号。将其设置为 -1 将使用 CPU,正数将在关联的 CUDA 设备 ID 上运行模型。您也可以传递原生的torch.device
或str
。 - torch_dtype (
str
ortorch.dtype
, optional) — 直接作为model_kwargs
发送(只是一个更简单的快捷方式),以使用此模型的可用精度(torch.float16
、torch.bfloat16
等或"auto"
)。 - binary_output (
bool
, optional, defaults toFalse
) — 指示流水线的输出是应以序列化格式(例如 pickle)还是作为原始输出数据(例如文本)进行的标志。 - image_processor_kwargs (
dict
, optional) — 传递给图像处理器的额外关键字参数字典,例如 {“size”: {“height”: 100, “width”: 100}}。 - pool (
bool
, optional, defaults toFalse
) — 是否返回池化输出。如果为False
,模型将返回原始隐藏状态。
图像特征提取流水线不使用模型头部。此流水线从基础 Transformer 中提取隐藏状态,这些状态可用作下游任务中的特征。
示例
>>> from transformers import pipeline
>>> extractor = pipeline(model="google/vit-base-patch16-224", task="image-feature-extraction")
>>> result = extractor("https://huggingface.co/datasets/Narsil/image_dummy/raw/main/parrots.png", return_tensors=True)
>>> result.shape # This is a tensor of shape [1, sequence_lenth, hidden_dimension] representing the input image.
torch.Size([1, 197, 768])
在流水线教程中了解有关使用流水线基础知识的更多信息。
当前可以使用任务标识符 "image-feature-extraction"
从 pipeline() 加载此图像特征提取流水线。
所有视觉模型都可以用于此流水线。在 huggingface.co/models 上查看所有模型列表,包括社区贡献的模型。
__call__
< 源 >( *args: typing.Union[str, ForwardRef('Image.Image'), list['Image.Image'], list[str]] **kwargs: typing.Any ) → float
的嵌套列表
参数
- images (
str
,list[str]
,PIL.Image
orlist[PIL.Image]
) — 流水线处理三种类型的图像:- 包含指向图像的 http 链接的字符串
- 包含本地图像路径的字符串
- 直接加载到 PIL 中的图像
流水线接受单个图像或一批图像,后者必须作为字符串传递。批处理中的图像必须都具有相同的格式:全部为 http 链接、全部为本地路径或全部为 PIL 图像。
- timeout (
float
, optional, defaults to None) — 从网页获取图片的最长等待时间(秒)。如果为 None,则不使用超时,调用可能会永远阻塞。
返回
float
的嵌套列表
模型计算的特征。
提取输入的特征。
ImageToTextPipeline
class transformers.ImageToTextPipeline
< 源 >( *args **kwargs )
参数
- model (PreTrainedModel or TFPreTrainedModel) — 将被流水线用于进行预测的模型。对于 PyTorch,它需要是继承自 PreTrainedModel 的模型,对于 TensorFlow,它需要是继承自 TFPreTrainedModel 的模型。
- tokenizer (PreTrainedTokenizer) — 将被流水线用于为模型编码数据的分词器。此对象继承自 PreTrainedTokenizer。
- image_processor (BaseImageProcessor) — 将被流水线用于为模型编码数据的图像处理器。此对象继承自 BaseImageProcessor。
- modelcard (
str
orModelCard
, optional) — 归属于此流水线模型的模型卡。 - framework (
str
, optional) — 要使用的框架,可以是"pt"
(PyTorch)或"tf"
(TensorFlow)。必须安装指定的框架。如果未指定框架,将默认为当前安装的框架。如果未指定框架且两个框架都已安装,将默认为
model
的框架,如果未提供模型,则默认为 PyTorch。 - task (
str
, defaults to""
) — 流水线的任务标识符。 - num_workers (
int
, optional, defaults to 8) — 当流水线将使用 DataLoader 时(当传递数据集,在 GPU 上使用 Pytorch 模型时),要使用的工作进程数。 - batch_size (
int
,可选,默认为 1) — 当 pipeline 使用 DataLoader 时(例如,在 GPU 上为 Pytorch 模型传递数据集时),要使用的批次大小。对于推理,这并非总是有益的,请阅读使用 pipeline 进行批处理。 - args_parser (ArgumentHandler,可选) — 负责解析所提供的 pipeline 参数的对象的引用。
- device (
int
,可选,默认为 -1) — 用于 CPU/GPU 支持的设备序号。将其设置为 -1 将使用 CPU,正数将在相应的 CUDA 设备 ID 上运行模型。您也可以传递原生的torch.device
或str
。 - torch_dtype (
str
或torch.dtype
,可选) — 直接作为model_kwargs
发送(只是一个更简单的快捷方式),以使用此模型可用的精度(torch.float16
、torch.bfloat16
等或"auto"
)。 - binary_output (
bool
,可选,默认为False
) — 指示 pipeline 的输出是否应以序列化格式(如 pickle)或原始输出数据(如文本)进行的标志。
使用 AutoModelForVision2Seq
的图像到文本 pipeline。此 pipeline 为给定图像预测标题。
除非您使用的模型在其配置文件(generation_config.json
)中明确设置了这些生成参数,否则将使用以下默认值:
- max_new_tokens: 256
示例
>>> from transformers import pipeline
>>> captioner = pipeline(model="ydshieh/vit-gpt2-coco-en")
>>> captioner("https://huggingface.co/datasets/Narsil/image_dummy/raw/main/parrots.png")
[{'generated_text': 'two birds are standing next to each other '}]
在流水线教程中了解有关使用流水线基础知识的更多信息。
此图像到文本 pipeline 目前可以使用以下任务标识符从 pipeline() 加载:“image-to-text”。
请参阅 huggingface.co/models 上的可用模型列表。
__call__
< 源 >( inputs: typing.Union[str, list[str], ForwardRef('Image.Image'), list['Image.Image']] **kwargs ) → dict
的列表或列表的列表
参数
- inputs (
str
、list[str]
、PIL.Image
或list[PIL.Image]
) — pipeline 处理三种类型的图像:- 包含指向图像的 HTTP(s) 链接的字符串
- 包含本地图像路径的字符串
- 直接加载到 PIL 中的图像
pipeline 接受单个图像或一批图像。
- max_new_tokens (
int
,可选) — 要生成的最大词元数。默认情况下,它将使用generate
的默认值。 - generate_kwargs (
Dict
,可选) — 传递它以将所有这些参数直接发送到generate
,从而实现对此函数的完全控制。 - timeout (
float
,可选,默认为 None) — 从 Web 获取图像的最长等待时间(秒)。如果为 None,则不设置超时,调用可能会永远阻塞。
返回
dict
的列表或列表的列表
每个结果都以字典形式返回,包含以下键:
- generated_text (
str
) — 生成的文本。
为作为输入传递的图像分配标签。
ImageTextToTextPipeline
class transformers.ImageTextToTextPipeline
< 源 >( *args **kwargs )
参数
- model (PreTrainedModel 或 TFPreTrainedModel) — pipeline 用于进行预测的模型。对于 PyTorch,这需要是继承自 PreTrainedModel 的模型;对于 TensorFlow,则是继承自 TFPreTrainedModel 的模型。
- processor (ProcessorMixin) — pipeline 用于为模型编码数据的处理器。该对象继承自 ProcessorMixin。处理器是一个复合对象,可能包含 `tokenizer`、`feature_extractor` 和 `image_processor`。
- modelcard (
str
或ModelCard
,可选) — 归属于此 pipeline 模型的模型卡。 - framework (
str
,可选) — 要使用的框架,可以是"pt"
(PyTorch) 或"tf"
(TensorFlow)。指定的框架必须已安装。如果未指定框架,将默认为当前安装的框架。如果未指定框架且两个框架都已安装,将默认为 `model` 的框架,或者在未提供模型时默认为 PyTorch。
- task (
str
,默认为""
) — pipeline 的任务标识符。 - num_workers (
int
,可选,默认为 8) — 当 pipeline 使用 DataLoader 时(例如,在 GPU 上为 Pytorch 模型传递数据集时),要使用的工作进程数。 - batch_size (
int
,可选,默认为 1) — 当 pipeline 使用 DataLoader 时(例如,在 GPU 上为 Pytorch 模型传递数据集时),要使用的批次大小。对于推理,这并非总是有益的,请阅读使用 pipeline 进行批处理。 - args_parser (ArgumentHandler,可选) — 负责解析所提供的 pipeline 参数的对象的引用。
- device (
int
,可选,默认为 -1) — 用于 CPU/GPU 支持的设备序号。将其设置为 -1 将使用 CPU,正数将在相应的 CUDA 设备 ID 上运行模型。您也可以传递原生的torch.device
或str
。 - torch_dtype (
str
或torch.dtype
,可选) — 直接作为model_kwargs
发送(只是一个更简单的快捷方式),以使用此模型可用的精度(torch.float16
、torch.bfloat16
等或"auto"
)。 - binary_output (
bool
,可选,默认为False
) — 指示 pipeline 的输出是否应以序列化格式(如 pickle)或原始输出数据(如文本)进行的标志。
使用 `AutoModelForImageTextToText` 的图文到文本 pipeline。此 pipeline 根据图像和文本生成文本。当底层模型是对话模型时,它还可以接受一个或多个聊天,在这种情况下,pipeline 将以聊天模式运行,并通过添加其响应来继续聊天。每个聊天都采用字典列表的形式,其中每个字典包含“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://qianwen-res.oss-cn-beijing.aliyuncs.com/Qwen-VL/assets/demo.jpeg",
>>> },
>>> {"type": "text", "text": "Describe this image."},
>>> ],
>>> },
>>> {
>>> "role": "assistant",
>>> "content": [
>>> {"type": "text", "text": "There is a dog and"},
>>> ],
>>> },
>>> ]
>>> pipe(text=messages, max_new_tokens=20, return_full_text=False)
[{'input_text': [{'role': 'user',
'content': [{'type': 'image',
'url': 'https://qianwen-res.oss-cn-beijing.aliyuncs.com/Qwen-VL/assets/demo.jpeg'},
{'type': 'text', 'text': 'Describe this image.'}]},
{'role': 'assistant',
'content': [{'type': 'text', 'text': 'There is a dog and'}]}],
'generated_text': ' a person in the image. The dog is sitting on the sand, and the person is sitting on'}]
在流水线教程中了解有关使用流水线基础知识的更多信息。
此图文到文本 pipeline 目前可以使用以下任务标识符从 pipeline() 加载:“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] = None text: typing.Union[str, list[str], list[dict], NoneType] = None **kwargs ) → dict
的列表或列表的列表
参数
- images (
str
、list[str]
、PIL.Image
、`list[PIL.Image]`、`list[dict[str, Union[str, PIL.Image]]]` ) — pipeline 处理三种类型的图像:- 包含指向图像的 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
) — 在输出中返回预测的张量(作为词元索引)。如果设置为True
,则不返回解码后的文本。 - return_text (
bool
,可选) — 在输出中返回解码后的文本。 - return_full_text (
bool
,可选,默认为True
) — 如果设置为False
,则只返回添加的文本;否则返回全文。不能与return_text
同时指定。 - clean_up_tokenization_spaces (
bool
,可选,默认为True
) — 是否清理文本输出中潜在的多余空格。 - continue_final_message(
bool
,可选) — 这表示您希望模型继续输入聊天中的最后一条消息,而不是开始一条新消息,从而允许您“预填充”其响应。默认情况下,当输入聊天中的最后一条消息角色为 `assistant` 时,此值为 `True`,否则为 `False`,但您可以通过设置此标志手动覆盖该行为。
返回
dict
的列表或列表的列表
每个结果都以字典形式返回,包含以下键(不能同时返回 generated_text
和 generated_token_ids
的组合):
- generated_text (
str
,当return_text=True
时存在) — 生成的文本。 - generated_token_ids (
torch.Tensor
,当return_tensors=True
时存在) — 生成文本的词元 ID。 - input_text (
str
) — 输入文本。
根据作为输入传递的文本和图像生成文本。
MaskGenerationPipeline
class transformers.MaskGenerationPipeline
< 源 >( **kwargs )
参数
- model (PreTrainedModel 或 TFPreTrainedModel) — pipeline 用于进行预测的模型。对于 PyTorch,这需要是继承自 PreTrainedModel 的模型;对于 TensorFlow,则是继承自 TFPreTrainedModel 的模型。
- image_processor (BaseImageProcessor) — pipeline 用于为模型编码数据的图像处理器。该对象继承自 BaseImageProcessor。
- modelcard (
str
或ModelCard
,可选) — 归属于此 pipeline 模型的模型卡。 - framework (
str
,可选) — 要使用的框架,可以是"pt"
(PyTorch) 或"tf"
(TensorFlow)。指定的框架必须已安装。如果未指定框架,将默认为当前安装的框架。如果未指定框架且两个框架都已安装,将默认为 `model` 的框架,或者在未提供模型时默认为 PyTorch。
- task (
str
,默认为""
) — pipeline 的任务标识符。 - num_workers (
int
,可选,默认为 8) — 当 pipeline 使用 DataLoader 时(例如,在 GPU 上为 Pytorch 模型传递数据集时),要使用的工作进程数。 - batch_size (
int
,可选,默认为 1) — 当 pipeline 使用 DataLoader 时(例如,在 GPU 上为 Pytorch 模型传递数据集时),要使用的批次大小。对于推理,这并非总是有益的,请阅读使用 pipeline 进行批处理。 - args_parser (ArgumentHandler,可选) — 负责解析所提供的 pipeline 参数的对象的引用。
- device (
int
,可选,默认为 -1) — 用于 CPU/GPU 支持的设备序号。将其设置为 -1 将使用 CPU,正数将在相应的 CUDA 设备 ID 上运行模型。您也可以传递原生的torch.device
或str
。 - torch_dtype (
str
或torch.dtype
,可选) — 直接作为model_kwargs
发送(只是一个更简单的快捷方式),以使用此模型可用的精度(torch.float16
、torch.bfloat16
等或"auto"
)。 - binary_output (
bool
,可选,默认为False
) — 指示 pipeline 的输出是否应以序列化格式(如 pickle)或原始输出数据(如文本)进行的标志。 - points_per_batch (可选,int,默认为 64) — 设置模型同时运行的点数。更高的数值可能更快,但会使用更多 GPU 内存。
- output_bboxes_mask (
bool
,可选,默认为False
) — 是否输出边界框预测。 - output_rle_masks (
bool
,可选,默认为False
) — 是否以 `RLE` 格式输出掩码。
使用 `SamForMaskGeneration` 对图像进行自动掩码生成。此 pipeline 为给定图像预测二元掩码。它是一个 `ChunkPipeline`,因为您可以将点分成小批次以避免内存不足(OOM)问题。使用 `points_per_batch` 参数控制将同时处理的点数。默认为 `64`。
该 pipeline 分三步工作:
`preprocess`:生成一个由 1024 个均匀分布的点组成的网格,以及边界框和点标签。有关如何创建点和边界框的更多详细信息,请查看 `_generate_crop_boxes` 函数。图像也使用 `image_processor` 进行预处理。此函数 `yields` 一个 `points_per_batch` 大小的小批次。
`forward`:将 `preprocess` 的输出馈送到模型。图像嵌入只计算一次。调用 `self.model.get_image_embeddings` 并确保不计算梯度,并且张量和模型在同一设备上。
`postprocess`:自动掩码生成的最重要部分发生在这里。包括三个步骤:
- image_processor.postprocess_masks(在每个小批次循环中运行):接收原始输出掩码,根据图像大小调整其大小,并将其转换为二元掩码。
- image_processor.filter_masks(在每个小批次循环中):同时使用 `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() 加载:`"mask-generation"`。
请参阅 huggingface.co/models 上的可用模型列表。
__call__
< 源 >( image: typing.Union[str, ForwardRef('Image.Image'), list[str], list['Image.Image']] *args: typing.Any **kwargs: typing.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,则不设置超时,调用可能会永远阻塞。
返回
字典
一个包含以下键的字典:
- mask (
PIL.Image
) — 检测到的物体的二进制掩码,形式为与原始图像形状相同的 PIL 图像(width, height)
。如果未找到物体,则返回一个填充为零的掩码。 - score (可选
float
) — 可选。当模型能够估算由标签和掩码描述的“物体”的置信度时提供。
生成二进制分割掩码
VisualQuestionAnsweringPipeline
class transformers.VisualQuestionAnsweringPipeline
< 源码 >( *args **kwargs )
参数
- model (PreTrainedModel or TFPreTrainedModel) — 将被 pipeline 用来进行预测的模型。对于 PyTorch,该模型需要继承自 PreTrainedModel;对于 TensorFlow,则需要继承自 TFPreTrainedModel。
- tokenizer (PreTrainedTokenizer) — 将被 pipeline 用来为模型编码数据的分词器。该对象继承自 PreTrainedTokenizer。
- image_processor (BaseImageProcessor) — 将被 pipeline 用来为模型编码数据的图像处理器。该对象继承自 BaseImageProcessor。
- modelcard (
str
orModelCard
,可选) — 归属于此 pipeline 模型的模型卡。 - framework (
str
,可选) — 要使用的框架,"pt"
表示 PyTorch,"tf"
表示 TensorFlow。指定的框架必须已安装。如果未指定框架,将默认为当前安装的框架。如果未指定框架且两种框架都已安装,将默认为
model
的框架,或者在未提供模型时默认为 PyTorch。 - task (
str
,默认为""
) — pipeline 的任务标识符。 - num_workers (
int
,可选,默认为 8) — 当 pipeline 使用 DataLoader(当传递数据集,在 GPU 上使用 Pytorch 模型时),要使用的工作进程数。 - batch_size (
int
,可选,默认为 1) — 当 pipeline 使用 DataLoader(当传递数据集,在 GPU 上使用 Pytorch 模型时),要使用的批处理大小。对于推理,这并不总是有益的,请阅读 使用 pipeline 进行批处理。 - args_parser (ArgumentHandler,可选) — 负责解析提供的 pipeline 参数的对象的引用。
- device (
int
,可选,默认为 -1) — 用于 CPU/GPU 支持的设备序号。将其设置为 -1 将使用 CPU,正数将在相应的 CUDA 设备 id 上运行模型。您也可以传递原生的torch.device
或str
。 - torch_dtype (
str
ortorch.dtype
,可选) — 直接作为model_kwargs
发送(只是一个更简单的快捷方式),以使用此模型的可用精度(torch.float16
、torch.bfloat16
等或"auto"
)。 - binary_output (
bool
,可选,默认为False
) — 指示 pipeline 的输出是否应以序列化格式(即 pickle)进行,或作为原始输出数据(例如文本)。
使用 AutoModelForVisualQuestionAnswering
的视觉问答 pipeline。此 pipeline 目前仅在 PyTorch 中可用。
除非您使用的模型在其配置文件(generation_config.json
)中明确设置了这些生成参数,否则将使用以下默认值:
- max_new_tokens: 256
示例
>>> from transformers import pipeline
>>> oracle = pipeline(model="dandelin/vilt-b32-finetuned-vqa")
>>> image_url = "https://huggingface.co/datasets/Narsil/image_dummy/raw/main/lena.png"
>>> oracle(question="What is she wearing ?", image=image_url)
[{'score': 0.948, 'answer': 'hat'}, {'score': 0.009, 'answer': 'fedora'}, {'score': 0.003, 'answer': 'clothes'}, {'score': 0.003, 'answer': 'sun hat'}, {'score': 0.002, 'answer': 'nothing'}]
>>> oracle(question="What is she wearing ?", image=image_url, top_k=1)
[{'score': 0.948, 'answer': 'hat'}]
>>> oracle(question="Is this a person ?", image=image_url, top_k=1)
[{'score': 0.993, 'answer': 'yes'}]
>>> oracle(question="Is this a man ?", image=image_url, top_k=1)
[{'score': 0.996, 'answer': 'no'}]
在流水线教程中了解有关使用流水线基础知识的更多信息。
这个视觉问答 pipeline 目前可以通过使用以下任务标识符从 pipeline() 加载:"visual-question-answering", "vqa"
。
此 pipeline 可以使用的模型是那些在视觉问答任务上进行过微调的模型。请在 huggingface.co/models 上查看最新的可用模型列表。
__call__
< 源码 >( image: typing.Union[ForwardRef('Image.Image'), str, list['Image.Image'], list[str], ForwardRef('KeyDataset')] question: typing.Union[str, list[str], NoneType] = None **kwargs ) → 包含结果的字典或字典列表。字典包含以下键
参数
- image (
str
,list[str]
,PIL.Image
,list[PIL.Image]
orKeyDataset
) — pipeline 处理三种类型的图像:- 包含指向图像的 http 链接的字符串
- 包含本地图像路径的字符串
- 直接加载到 PIL 中的图像
pipeline 接受单个图像或一批图像。如果给定单个图像,它可以广播到多个问题。对于数据集:传入的数据集必须是
transformers.pipelines.pt_utils.KeyDataset
类型。例如:
返回
包含结果的字典或字典列表。字典包含以下键
- label (
str
) — 模型识别的标签。 - score (
int
) — 模型为该标签赋予的分数。
回答关于图像的开放式问题。pipeline 接受多种类型的输入,详情如下
pipeline(image=image, question=question)
pipeline({"image": image, "question": question})
pipeline([{"image": image, "question": question}])
pipeline([{"image": image, "question": question}, {"image": image, "question": question}])
父类:Pipeline
class transformers.Pipeline
< 源码 >( model: typing.Union[ForwardRef('PreTrainedModel'), ForwardRef('TFPreTrainedModel')] tokenizer: typing.Optional[transformers.tokenization_utils.PreTrainedTokenizer] = None feature_extractor: typing.Optional[ForwardRef('SequenceFeatureExtractor')] = None image_processor: typing.Optional[transformers.image_processing_utils.BaseImageProcessor] = None processor: typing.Optional[transformers.processing_utils.ProcessorMixin] = None modelcard: typing.Optional[transformers.modelcard.ModelCard] = None framework: typing.Optional[str] = None task: str = '' args_parser: ArgumentHandler = None device: typing.Union[int, ForwardRef('torch.device')] = None torch_dtype: typing.Union[str, ForwardRef('torch.dtype'), NoneType] = None binary_output: bool = False **kwargs )
参数
- model (PreTrainedModel or TFPreTrainedModel) — 将被 pipeline 用来进行预测的模型。对于 PyTorch,该模型需要继承自 PreTrainedModel;对于 TensorFlow,则需要继承自 TFPreTrainedModel。
- tokenizer (PreTrainedTokenizer) — 将被 pipeline 用来为模型编码数据的分词器。该对象继承自 PreTrainedTokenizer。
- feature_extractor (SequenceFeatureExtractor) — 将被 pipeline 用来为模型编码数据的特征提取器。该对象继承自 SequenceFeatureExtractor。
- image_processor (BaseImageProcessor) — 将被 pipeline 用来为模型编码数据的图像处理器。该对象继承自 BaseImageProcessor。
- processor (ProcessorMixin) — 将被 pipeline 用来为模型编码数据的处理器。该对象继承自 ProcessorMixin。处理器是一个复合对象,可能包含
tokenizer
、feature_extractor
和image_processor
。 - modelcard (
str
orModelCard
,可选) — 归属于此 pipeline 模型的模型卡。 - framework (
str
,可选) — 要使用的框架,"pt"
表示 PyTorch,"tf"
表示 TensorFlow。指定的框架必须已安装。如果未指定框架,将默认为当前安装的框架。如果未指定框架且两种框架都已安装,将默认为
model
的框架,或者在未提供模型时默认为 PyTorch。 - task (
str
,默认为""
) — pipeline 的任务标识符。 - num_workers (
int
,可选,默认为 8) — 当 pipeline 使用 DataLoader(当传递数据集,在 GPU 上使用 Pytorch 模型时),要使用的工作进程数。 - batch_size (
int
,可选,默认为 1) — 当 pipeline 使用 DataLoader(当传递数据集,在 GPU 上使用 Pytorch 模型时),要使用的批处理大小。对于推理,这并不总是有益的,请阅读 使用 pipeline 进行批处理。 - args_parser (ArgumentHandler,可选) — 负责解析提供的 pipeline 参数的对象的引用。
- device (
int
,可选,默认为 -1) — 用于 CPU/GPU 支持的设备序号。将其设置为 -1 将使用 CPU,正数将在相应的 CUDA 设备 id 上运行模型。您也可以传递原生的torch.device
或str
。 - torch_dtype (
str
ortorch.dtype
,可选) — 直接作为model_kwargs
发送(只是一个更简单的快捷方式),以使用此模型的可用精度(torch.float16
、torch.bfloat16
等或"auto"
)。 - binary_output (
bool
,可选,默认为False
) — 指示 pipeline 的输出是否应以序列化格式(即 pickle)进行,或作为原始输出数据(例如文本)。
Pipeline 类是所有 pipeline 继承的基类。有关不同 pipeline 共享的方法,请参考此类。
实现流水线操作的基类。Pipeline 的工作流程定义为以下操作序列
输入 -> 分词 -> 模型推理 -> 后处理 (依赖于任务) -> 输出
Pipeline 通过 device 参数支持在 CPU 或 GPU 上运行(见下文)。
某些 pipeline,例如 FeatureExtractionPipeline ('feature-extraction'
),会以嵌套列表的形式输出大型张量对象。为避免将如此大的结构作为文本数据转储,我们提供了 binary_output
构造函数参数。如果设置为 True
,输出将以 pickle 格式存储。
check_model_type
< 源码 >( supported_models: typing.Union[list[str], dict] )
检查模型类是否受 pipeline 支持。
上下文管理器,以框架无关的方式允许在用户指定的设备上分配张量。
ensure_tensor_on_device
< 源码 >( **inputs ) → dict[str, torch.Tensor]
确保 PyTorch 张量在指定的设备上。
后处理将接收 _forward
方法的原始输出(通常是张量),并将其重新格式化为更友好的形式。通常它会输出一个结果列表或字典(仅包含字符串和数字)。
Scikit / Keras 接口,用于 transformers 的 pipeline。此方法将转发到 call()。
预处理将接收特定 pipeline 的 `input_`,并返回一个包含所有 `_forward` 正常运行所需内容的字典。它应至少包含一个张量,但可能包含任意其他项。
push_to_hub
< 源码 >( repo_id: str use_temp_dir: typing.Optional[bool] = None commit_message: typing.Optional[str] = None private: typing.Optional[bool] = None token: typing.Union[bool, str, NoneType] = None max_shard_size: typing.Union[str, int, NoneType] = '5GB' create_pr: bool = False safe_serialization: bool = True revision: typing.Optional[str] = None commit_description: typing.Optional[str] = None tags: typing.Optional[list[str]] = None **deprecated_kwargs )
参数
- repo_id (
str
) — 您想要将 pipeline 推送到的存储库的名称。在推送到给定组织时,它应包含您的组织名称。 - use_temp_dir (
bool
,可选) — 是否使用临时目录存储保存的文件,然后再推送到 Hub。如果不存在名为repo_id
的目录,则默认为True
,否则为False
。 - commit_message (
str
, optional) — 推送时要提交的消息。默认为"Upload pipe"
。 - private (
bool
, optional) — 是否将仓库设为私有。如果为None
(默认值),仓库将是公开的,除非组织的默认设置是私有。如果仓库已存在,则此值将被忽略。 - token (
bool
orstr
, optional) — 用作远程文件 HTTP bearer 授权的 token。如果为True
,将使用运行huggingface-cli login
时生成的 token(存储在~/.huggingface
中)。如果未指定repo_url
,则默认为True
。 - max_shard_size (
int
orstr
, optional, defaults to"5GB"
) — 仅适用于模型。检查点在分片之前的最大大小。检查点分片的大小将小于此大小。如果表示为字符串,则需要是数字后跟一个单位(如"5MB"
)。我们默认为"5GB"
,以便用户可以在免费的 Google Colab 实例上轻松加载模型,而不会出现任何 CPU OOM 问题。 - create_pr (
bool
, optional, defaults toFalse
) — 是否为上传的文件创建一个 PR(拉取请求)或直接提交。 - safe_serialization (
bool
, optional, defaults toTrue
) — 是否将模型权重转换为 safetensors 格式以进行更安全的序列化。 - revision (
str
, optional) — 要将上传文件推送到的分支。 - commit_description (
str
, optional) — 将要创建的提交的描述 - tags (
list[str]
, optional) — 要推送到 Hub 的标签列表。
将 pipeline 文件上传到 🤗 Model Hub。
示例
from transformers import pipeline
pipe = pipeline("google-bert/bert-base-cased")
# Push the pipe to your namespace with the name "my-finetuned-bert".
pipe.push_to_hub("my-finetuned-bert")
# Push the pipe to an organization with the name "my-finetuned-bert".
pipe.push_to_hub("huggingface/my-finetuned-bert")
save_pretrained
< source >( save_directory: typing.Union[str, os.PathLike] safe_serialization: bool = True **kwargs )
参数
- save_directory (
str
oros.PathLike
) — 要保存到的目录路径。如果不存在,则会创建该目录。 - safe_serialization (
str
) — 是使用safetensors
还是传统的 PyTorch 或 Tensorflow 方式保存模型。 - kwargs (
dict[str, Any]
, optional) — 传递给 push_to_hub() 方法的附加关键字参数。
保存 pipeline 的模型和 tokenizer。
Scikit / Keras 接口,用于 transformers 的 pipeline。此方法将转发到 call()。