pipeline(管道)是huggingface transformers库中一种极简方式使用大模型推理的抽象,将所有大模型分为音频(Audio)、计算机视觉(Computer vision)、自然语言处理(NLP)、多模态(Multimodal)等4大类,28小类任务(tasks)。共计覆盖32万个模型
今天介绍多模态的第六篇,也是本专栏的最后一篇:视觉问答(visual-question-answering),在huggingface库内可以使用的视觉问答(visual-question-answering)模型有400个。
视觉问答(visual-question-answering)是根据图像回答开放式问题的任务。它们输出对自然语言问题的自然语言回答。
ViLT(Vision-and-Language Transformer Without Convolution or Region Supervision)可以认为是目前最简单的多模态Transformer方法。ViLT使用预训练的ViT来初始化交互的transformer,这样就可以直接利用交互层来处理视觉特征,不需要额外增加一个视觉encoder。
ViLT预训练的优化目标有两个:一个是image text matching(ITM),另一个是masked language modeling(MLM)。
str
或ModelCard
,可选) — 属于此管道模型的模型卡。str
,可选)— 要使用的框架,"pt"
适用于 PyTorch 或"tf"
TensorFlow。必须安装指定的框架。str
,默认为""
)— 管道的任务标识符。int
,可选,默认为 8)— 当管道将使用DataLoader(传递数据集时,在 Pytorch 模型的 GPU 上)时,要使用的工作者数量。int
,可选,默认为 1)— 当管道将使用DataLoader(传递数据集时,在 Pytorch 模型的 GPU 上)时,要使用的批次的大小,对于推理来说,这并不总是有益的,请阅读使用管道进行批处理。int
,可选,默认为 -1)— CPU/GPU 支持的设备序号。将其设置为 -1 将利用 CPU,设置为正数将在关联的 CUDA 设备 ID 上运行模型。您可以传递本机torch.device
或str
太str
或torch.dtype
,可选) - 直接发送model_kwargs
(只是一种更简单的快捷方式)以使用此模型的可用精度(torch.float16
,,torch.bfloat16
...或"auto"
)bool
,可选,默认为False
)——标志指示管道的输出是否应以序列化格式(即 pickle)或原始输出数据(例如文本)进行。str
、List[str]
、或PIL.Image
)——管道处理三种类型的图像:List[PIL.Image]KeyDataset
str
) — 模型标识的标签。int
) — 模型为该标签评定的分数。基于pipeline的视觉问答(visual-question-answering)任务,采用dandelin/vilt-b32-finetuned-vqa对图片进行视觉问答,代码如下:
import os
os.environ["HF_ENDPOINT"] = "https://hf-mirror.com"
os.environ["CUDA_VISIBLE_DEVICES"] = "2"
from transformers import pipeline
oracle = pipeline(task="vqa",model="dandelin/vilt-b32-finetuned-vqa")
image_url = "./lena.png"
output=oracle(question="What is she wearing ?", image=image_url)
print(output)
output=oracle(question="What is she wearing ?", image=image_url, top_k=1)
print(output)
output=oracle(question="Is this a person ?", image=image_url, top_k=2)
print(output)
output=oracle(question="Is this a man ?", image=image_url, top_k=3)
print(output)
执行后,自动下载模型文件并基于图片,对提出的文本问题进行视觉回答。
在huggingface上,我们将视觉问答(visual-question-answering)模型按下载量从高到低排序,共计427个模型中,文中的ViLT模型排名第三。
本文对transformers之pipeline的视觉问答(visual-question-answering)从概述、技术原理、pipeline参数、pipeline实战、模型排名等方面进行介绍,读者可以基于pipeline使用文中的2行代码极简的使用多模态中的视觉问答(visual-question-answering)模型。