# LAVIS - 语言与视觉智能库 ## 最新消息:🎉 * [模型发布] 2023年11月,发布了 **X-InstructBLIP** 的实现
@inproceedings{li-etal-2023-lavis,
title = "{LAVIS}: A One-stop Library for Language-Vision Intelligence",
author = "Li, Dongxu and
Li, Junnan and
Le, Hung and
Wang, Guangsen and
Savarese, Silvio and
Hoi, Steven C.H.",
booktitle = "Proceedings of the 61st Annual Meeting of the Association for Computational Linguistics (Volume 3: System Demonstrations)",
month = jul,
year = "2023",
address = "Toronto, Canada",
publisher = "Association for Computational Linguistics",
url = "https://aclanthology.org/2023.acl-demo.3",
pages = "31--41",
abstract = "我们介绍了 LAVIS,一个用于语言-视觉研究和应用的开源深度学习库。LAVIS 旨在成为一个一站式综合库,使研究人员和从业者能够轻松获取语言-视觉领域的最新进展,并促进未来的研究和发展。它具有统一接口,可以轻松访问最先进的图像-语言、视频-语言模型和常见数据集。LAVIS 支持在各种任务上进行训练、评估和基准测试,包括多模态分类、检索、字幕生成、视觉问答、对话和预训练。同时,该库也具有高度可扩展性和可配置性,便于未来开发和定制。在本技术报告中,我们描述了该库的设计原则、关键组件和功能,并展示了跨常见语言-视觉任务的基准测试结果。",
}
## 目录
- [引言](#引言)
- [安装](#安装)
- [快速入门](#快速入门)
- [模型动物园](#模型动物园)
- [图像字幕生成](#图像字幕生成)
- [视觉问答 (VQA)](#视觉问答-vqa)
- [统一特征提取接口](#统一特征提取接口)
- [加载数据集](#加载数据集)
- [Jupyter Notebook 示例](#jupyter-notebook-示例)
- [资源与工具](#资源与工具)
- [文档](#文档)
- [伦理与负责任的使用](#伦理与负责任的使用)
- [技术报告与引用 LAVIS](#技术报告与引用-lavis)
- [许可证](#许可证)
## 引言
LAVIS 是一个用于语言与视觉智能研究和应用的 Python 深度学习库。该库旨在为工程师和研究人员提供一站式解决方案,以便快速为其特定的多模态场景开发模型,并在标准和自定义数据集上进行基准测试。
它采用统一的接口设计来访问:
- **10 多种**任务
(检索、字幕生成、视觉问答、多模态分类等);
- **20 多个**数据集(COCO、Flickr、Nocaps、Conceptual Commons、SBU 等);
- **30 多个**最先进的基础语言-视觉模型的预训练权重及其特定任务适配,包括 [ALBEF](https://arxiv.org/pdf/2107.07651.pdf)、
[BLIP](https://arxiv.org/pdf/2201.12086.pdf)、[ALPRO](https://arxiv.org/pdf/2112.09583.pdf)、[CLIP](https://arxiv.org/pdf/2103.00020.pdf)。
LAVIS 的主要特性包括: - **统一和模块化接口**:便于轻松利用和重用现有模块(数据集、模型、预处理),也便于添加新模块。 - **简便的开箱即用推理和特征提取**:随时可用的预训练模型使您能够利用最先进的多模态理解和生成能力处理自己的数据。 - **可复现的模型动物园和训练配方**:轻松在现有和新任务上复现和扩展最先进的模型。 - **数据集动物园和自动下载工具**:准备许多语言-视觉数据集可能很繁琐。LAVIS 提供自动下载脚本,帮助准备各种数据集及其注释。 下表列出了我们库中支持的任务、数据集和模型。这是一项持续的努力,我们正在致力于进一步扩展列表。 | 任务 | 支持的模型 | 支持的数据集 | | :------------------------------------: | :--------------------: | :----------------------------------: | | 图像-文本预训练 | ALBEF, BLIP | COCO, VisualGenome, SBU ConceptualCaptions | | 图像-文本检索 | ALBEF, BLIP, CLIP | COCO, Flickr30k | | 文本-图像检索 | ALBEF, BLIP, CLIP | COCO, Flickr30k | | 视觉问答 | ALBEF, BLIP | VQAv2, OKVQA, A-OKVQA | | 图像字幕生成 | BLIP | COCO, NoCaps | | 图像分类 | CLIP | ImageNet | | 自然语言视觉推理 (NLVR) | ALBEF, BLIP | NLVR2 | | 视觉蕴含 (VE) | ALBEF | SNLI-VE | | 视觉对话 | BLIP | VisDial | | 视频-文本检索 | BLIP, ALPRO | MSRVTT, DiDeMo | | 文本-视频检索 | BLIP, ALPRO | MSRVTT, DiDeMo | | 视频问答 (VideoQA) | BLIP, ALPRO | MSRVTT, MSVD | | 视频对话 | VGD-GPT | AVSD | | 多模态特征提取 | ALBEF, CLIP, BLIP, ALPRO | 自定义 | | 文本到图像生成 | [即将推出] | | ## 安装 1. (可选) 创建 conda 环境
conda create -n lavis python=3.8
conda activate lavis
2. 从 [PyPI](https://pypi.org/project/salesforce-lavis/) 安装
pip install salesforce-lavis
3. 或者,为了开发目的,您可以从源代码构建
git clone https://github.com/salesforce/LAVIS.git
cd LAVIS
pip install -e .
## 快速入门
### 模型动物园
模型动物园总结了 LAVIS 中支持的模型,查看方式:
from lavis.models import model_zoo
print(model_zoo)
# ==================================================
# 架构 类型
# ==================================================
# albef_classification ve
# albef_feature_extractor base
# albef_nlvr nlvr
# albef_pretrain base
# albef_retrieval coco, flickr
# albef_vqa vqav2
# alpro_qa msrvtt, msvd
# alpro_retrieval msrvtt, didemo
# blip_caption base_coco, large_coco
# blip_classification base
# blip_feature_extractor base
# blip_nlvr nlvr
# blip_pretrain base
# blip_retrieval coco, flickr
# blip_vqa vqav2, okvqa, aokvqa
# clip_feature_extractor ViT-B-32, ViT-B-16, ViT-L-14, ViT-L-14-336, RN50
# clip ViT-B-32, ViT-B-16, ViT-L-14, ViT-L-14-336, RN50
# gpt_dialogue base
让我们看看如何使用 LAVIS 中的模型对示例数据进行推理。我们首先从本地加载一个示例图像。
import torch
from PIL import Image
# 设置要使用的设备
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
# 加载示例图像
raw_image = Image.open("docs/_static/merlion.png").convert("RGB")
此示例图像显示的是新加坡地标——[鱼尾狮公园](https://en.wikipedia.org/wiki/Merlion)([来源](https://theculturetrip.com/asia/singapore/articles/what-exactly-is-singapores-merlion-anyway/))。
### 图像字幕生成
在此示例中,我们使用 BLIP 模型为图像生成字幕。为了更方便推理,我们还通过 `load_model_and_preprocess()` 将每个预训练模型与其预处理器(转换)关联起来。
import torch
from lavis.models import load_model_and_preprocess
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
# 加载 BLIP 字幕基础模型,以及 MSCOCO 字幕数据集上微调的检查点。
# 这也会加载关联的图像处理器
model, vis_processors, _ = load_model_and_preprocess(name="blip_caption", model_type="base_coco", is_eval=True, device=device)
# 预处理图像
# vis_processors 存储了用于 "train" 和 "eval"(验证 / 测试 / 推理)的图像转换
image = vis_processors["eval"](raw_image).unsqueeze(0).to(device)
# 生成字幕
model.generate({"image": image})
# ['a large fountain spewing water into the air']
### 视觉问答 (VQA)
BLIP 模型能够用自然语言回答关于图像的自由形式问题。
要访问 VQA 模型,只需更改传递给 `load_model_and_preprocess()` 的 `name` 和 `model_type` 参数即可。
from lavis.models import load_model_and_preprocess
model, vis_processors, txt_processors = load_model_and_preprocess(name="blip_vqa", model_type="vqav2", is_eval=True, device=device)
# 提出一个随机问题。
question = "Which city is this photo taken?"
image = vis_processors["eval"](raw_image).unsqueeze(0).to(device)
question = txt_processors["eval"](question)
model.predict_answers(samples={"image": image, "text_input": question}, inference_method="generate")
# ['singapore']
### 统一特征提取接口
LAVIS 提供一个统一的接口,用于从每个架构中提取特征。
要提取特征,我们加载每个模型的特征提取器变体。
多模态特征可用于多模态分类。
低维度的单模态特征可用于计算跨模态相似度。
from lavis.models import load_model_and_preprocess
model, vis_processors, txt_processors = load_model_and_preprocess(name="blip_feature_extractor", model_type="base", is_eval=True, device=device)
caption = "a large fountain spewing water into the air"
image = vis_processors["eval"](raw_image).unsqueeze(0).to(device)
text_input = txt_processors["eval"](caption)
sample = {"image": image, "text_input": [text_input]}
features_multimodal = model.extract_features(sample)
print(features_multimodal.multimodal_embeds.shape)
# torch.Size([1, 12, 768]), 对于多模态分类任务使用 features_multimodal[:,0,:]
features_image = model.extract_features(sample, mode="image")
features_text = model.extract_features(sample, mode="text")
print(features_image.image_embeds.shape)
# torch.Size([1, 197, 768])
print(features_text.text_embeds.shape)
# torch.Size([1, 12, 768])
# 低维度投影特征
print(features_image.image_embeds_proj.shape)
# torch.Size([1, 197, 256])
print(features_text.text_embeds_proj.shape)
# torch.Size([1, 12, 256])
similarity = features_image.image_embeds_proj[:,0,:] @ features_text.text_embeds_proj[:,0,:].t()
print(similarity)
# tensor([[0.2622]])
### 加载数据集
LAVIS 内在地支持各种常见的语言-视觉数据集,通过提供[自动下载工具](https://opensource.salesforce.com/LAVIS//latest/benchmark)来帮助下载和整理这些数据集。下载后,使用以下代码加载数据集:
from lavis.datasets.builders import dataset_zoo
dataset_names = dataset_zoo.get_names()
print(dataset_names)
# ['aok_vqa', 'coco_caption', 'coco_retrieval', 'coco_vqa', 'conceptual_caption_12m',
# 'conceptual_caption_3m', 'didemo_retrieval', 'flickr30k', 'imagenet', 'laion2B_multi',
# 'msrvtt_caption', 'msrvtt_qa', 'msrvtt_retrieval', 'msvd_caption', 'msvd_qa', 'nlvr',
# 'nocaps', 'ok_vqa', 'sbu_caption', 'snli_ve', 'vatex_caption', 'vg_caption', 'vg_vqa']
下载图像后,我们可以使用 `load_dataset()` 获取数据集。
from lavis.datasets.builders import load_dataset
coco_dataset = load_dataset("coco_caption")
print(coco_dataset.keys())
# dict_keys(['train', 'val', 'test'])
print(len(coco_dataset["train"]))
# 566747
print(coco_dataset["train"][0])
# {'image': <PIL.Image.Image image mode=RGB size=640x480>,
# 'text_input': 'A woman wearing a net on her head cutting a cake. ',
# 'image_id': 0}
如果您本地已有数据集的副本,可以传递 `vis_path` 参数来更改加载图像的默认位置。
coco_dataset = load_dataset("coco_caption", vis_path=YOUR_LOCAL_PATH)
## Jupyter Notebook 示例
更多推理示例(例如字幕生成、特征提取、VQA、GradCam、零样本分类)请参阅 [examples](https://github.com/salesforce/LAVIS/tree/main/examples)。
## 资源与工具
- **基准测试**:有关评估和训练支持模型的说明,请参阅[基准测试](https://opensource.salesforce.com/LAVIS//latest/benchmark)。
- **数据集下载和浏览**:有关下载常见语言-视觉数据集的说明和自动工具,请参阅[数据集下载](https://opensource.salesforce.com/LAVIS//latest/benchmark)。
- **GUI 演示**:要在本地运行演示,请执行 ```bash run_scripts/run_demo.sh```,然后按照提示在浏览器中查看。网页演示即将推出。
## 文档
有关更多详细信息和高级用法,请参阅
[文档](https://opensource.salesforce.com/LAVIS//latest/index.html#)。
## 伦理与负责任的使用
我们注意到,LAVIS 中的模型不保证其多模态能力;可能会观察到不正确或有偏见的预测。特别是,LAVIS 中使用的数据集和预训练模型可能包含社会经济偏见,这可能导致误分类和其他不希望的行为,例如冒犯或不恰当的言论。我们强烈建议用户在实际采用前审查 LAVIS 中的预训练模型和整个系统。我们计划通过调查和缓解这些潜在偏见和不恰当行为来改进库。
## 联系我们
如果您有任何问题、意见或建议,请随时通过 lavis@salesforce.com 联系我们。
## 许可证
[BSD 3-Clause 许可证](LICENSE.txt)