ViLT微调与BLIP-2零样本视觉问答

介绍将ViLT用于视觉问答的微调流程,包括数据加载、ViltProcessor预处理与推理步骤,并对比BLIP-2把VQA作为生成任务、组合预训练视觉编码器与LLM的零样本范式。

Copyright 2023 HuggingFace Team. 全权保留. 根据 Apache 许可, 版本 2.0 (“ License ”) 获得许可; 您不能使用此文件, 除非符合 您可在下列地点获得许可证副本: http://www.apache.org/licenses/LICENSE-2.0 除非适用法律要求或书面同意,否则根据许可证分发的软件在下列网址分发: a " :ASIS"BASIS,WITHOUTWARRANTIESORCONDITIONSOFANYKIND,或明示的或暗示的。 《许可证》规定的许可和限制的具体语言。 ⚠️ 注意此文件在 Markdown 中, 但包含我们doc- builder(类似于 MDX ) 的特定语法, 可能不是 在您的Markdown 查看器中正确渲染。 # 视觉问题回答 [[open-in-colab]] 视觉问题回答(VQA)是基于图像回答开放式问题的任务. 支持这项任务的模型的输入通常是将图像和问题结合起来,输出是 用自然语言表达的答案。 VQA的一些值得注意的使用案例包括: * 视力障碍者无障碍申请。 * 教育:对讲座或教科书中展示的视觉材料提出疑问. VQA也可以用于交互式博物馆展品或历史遗址. * 客户服务和电子商务:VQA可以通过让用户询问产品问题来增强用户体验. * 图像检索:VQA模型可以用来检索具有特定特性的图像,例如,用户可以问"是否有狗?"从一组图像中找到所有带有狗的图像. 在这个指南中,你会学会: - 精细调整分类 VQA模型,具体来说 [ViLT](<https://github.com/huggingface/transformers/blob/HEAD/docs/source/en/model_doc/vilt>),在Graphcore/vqa数据集上。 - 用你微调的ViLT进行推论. - 以基因模型进行零镜头VQA推论,如BLIP-2. ## 微调 ViLT ViLT模型将文本嵌入到一个Visual Transformer(ViT)中,允许它有一个最小的设计用于 视野与语言预训( VLP ) 。 此模式可用于下游的多个任务。 对于 VQA 任务, 一个分类器 头置于顶部(最后隐藏状态上方的线性层) `[CLS]` )和随机初始化。 因此,视觉问题回答被视为一种 **分类问题**. 较近期的模型,如BLIP,BLIP-2,以及InstructBLIP,将VQA视为遗传性任务. 稍后在本指南中,我们 说明如何用它们进行零镜头的VQA推论. 在开始前,请务必安装所有必要的图书馆。 ```bash pip install -q transformers datasets ``` 我们鼓励您与社区分享您的模型。 登录您的 Hugging Face 账户, 上传到 QQ 中心 。 当被提示时, 请输入您要登录的符号 : ```py >>> from huggingface_hub import notebook_login >>> notebook_login() ``` 将模式检查站定义为全球变量. ```py >>> model_checkpoint = "dandelin/vilt-b32-mlm" ``` ## 装入数据 为了说明起见,在本指南中,我们使用一个很小的样本,即附加注释的视觉问题回答。 `Graphcore/vqa` 数据集。 作为Graphcore/vqa数据集的替代品,您可以下载 官方手动提供的相同数据 [VQA 数据集页面](https://visualqa.org/download.html)。如果你喜欢跟随 带有自定义数据的教程,检查如何 [创建图像数据集](https://huggingface.co/docs/datasets/image_dataset#loading-script) 在 QQ 数据集文档中提供指南。 让我们从验证拆分中加载第一个 200 实例,并探索数据集的特性 : ```python >>> from datasets import load_dataset >>> dataset = load_dataset("Graphcore/vqa", split="validation[:200]") >>> dataset Dataset({ features: ['question', 'question_type', 'question_id', 'image_id', 'answer_type', 'label'], num_rows: 200 }) ``` 让我们看看一个例子来理解数据集的特征: ```py >>> dataset[0] {'question': 'Where is he looking?', 'question_type': 'none of the above', 'question_id': 262148000, 'image_id': '/root/.cache/huggingface/datasets/downloads/extracted/ca733e0e000fb2d7a09fbcc94dbfe7b5a30750681d0e965f8e0a23b1c2f98c75/val2014/COCO_val2014_000000262148.jpg', 'answer_type': 'other', 'label': {'ids': ['at table', 'down', 'skateboard', 'table'], 'weights': [0.30000001192092896, 1.0, 0.30000001192092896, 0.30000001192092896]}} ``` 与这项任务有关的特征包括: * `question`: 从图像中解答的问题 * `image_id`: 问题所指的图像路径 * `label`: 说明 我们可以去掉其余的功能,因为它们是不必要的: ```py >>> dataset = dataset.remove_columns(['question_type', 'question_id', 'answer_type']) ``` 如你所见, `label` 特性包含对同一问题的几个答案(称为 `ids` 由不同的人类注释家收集。 这是因为对一个问题的答案可能是主观的,在这种情况下,问题在于"他在哪里看?",有些人是"他在哪里看". 用"下",其他用"在桌子",另外用"滑板"等注解. 看看这幅图,想想你会给出什么答案: ```python >>> from PIL import Image >>> image = Image.open(dataset[0]['image_id']) >>> image ``` <img src=' https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/tasks/vqa-example.png" alt=' VQA 图像示例'/> 由于问题和答案的模糊性,这类数据集被视为一个多标签分类问题(例如: 多个答案可能是有效的。此外,不仅创建一个一热编码的向量,而且创建一个 软编码,根据某一答案出现在说明中的次数. 例如,在上述例子中,由于“下”的答案比其他答案更经常地被选中,因此它有一个“下”的答案。 分数(称为 `weight` 在数据集)中的1.0,其余的答案有 < 1.0的分数. 以后用一个合适的分类头来即时化模型,让我们创建两个词典:一个是地图 标签名称为整数,反之亦然: ```py >>> import itertools >>> labels = [item['ids'] for item in dataset['label']] >>> flattened_labels = list(itertools.chain(*labels)) >>> unique_labels = list(set(flattened_labels)) >>> label2id = {label: idx for idx, label in enumerate(unique_labels)} >>> id2label = {idx: label for label, idx in label2id.items()} ``` 现在我们有了地图,我们可以用他们的ID来取代字符串答案,并平整数据集,以便进行更方便的进一步预处理. ```python >>> def replace_ids(inputs): ... inputs["label"]["ids"] = [label2id[x] for x in inputs["label"]["ids"]] ... return inputs >>> dataset = dataset.map(replace_ids) >>> flat_dataset = dataset.flatten() >>> flat_dataset.features {'question': Value(dtype='string', id=None), 'image_id': Value(dtype='string', id=None), 'label.ids': Sequence(feature=Value(dtype='int64', id=None), length=-1, id=None), 'label.weights': Sequence(feature=Value(dtype='float64', id=None), length=-1, id=None)} ``` ## 预处理数据 下一步是加载一个ViLT处理器,为模型准备图像和文本数据. [`ViltProcessor`] 将 BERT 表示器和 ViLT 图像处理器包成一个方便的单一处理器 : ```py >>> from transformers import ViltProcessor >>> processor = ViltProcessor.from_pretrained(model_checkpoint) ``` 为了预处理数据,我们需要使用 [`ViltProcessor`]。处理器将使用 编号 [`BertTokenizerFast`] 以符号化文本并创建 `input_ids`, `attention_mask` 财务报告和财务报告 `token_type_ids` 用于文本数据。 至于图像,处理器会发挥杠杆作用 [`ViltImageProcessor`] 以调整图像大小并使其正常化,并创建 `pixel_values` 财务报告和财务报告 `pixel_mask`. 所有这些预处理步骤都是在引擎盖下完成的,我们只需要叫它 `processor`然而,我们仍然需要 准备目标标签。在这个表示式中,每个元素都对应一个可能的答案(标签)。对于正确的答案,元素持有 ,而其余的元素被设定为零。 以下函数应用 `processor` 以及上述标签的图像和问题及格式: ```py >>> import torch >>> def preprocess_data(examples): ... image_paths = examples['image_id'] ... images = [Image.open(image_path) for image_path in image_paths] ... texts = examples['question'] ... encoding = processor(images, texts, padding="max_length", truncation=True, return_tensors="pt") ... for k, v in encoding.items(): ... encoding[k] = v.squeeze() ... targets = [] ... for labels, scores in zip(examples['label.ids'], examples['label.weights']): ... target = torch.zeros(len(id2label)) ... for label, score in zip(labels, scores): ... target[label] = score ... targets.append(target) ... encoding["labels"] = targets ... return encoding ``` 要将预处理功能应用于整个数据集,请使用QQ数据集 [`~datasets.map`] 函数。您可以加速 `map` 由 设置 `batched=True` 以同时处理数据集的多个元素。此时,可以随意删除您不需要的列。 ```py >>> processed_dataset = flat_dataset.map(preprocess_data, batched=True, remove_columns=['question','question_type', 'question_id', 'image_id', 'answer_type', 'label.ids', 'label.weights']) >>> processed_dataset Dataset({ features: ['input_ids', 'token_type_ids', 'attention_mask', 'pixel_values', 'pixel_mask', 'labels'], num_rows: 200 }) ``` 作为最后一步,创建一组实例,使用 [`DefaultDataCollator`]: ```py >>> from transformers import DefaultDataCollator >>> data_collator = DefaultDataCollator() ``` ## 训练模型 你准备好开始训练你的模特儿了!ViLT与 [`ViltForQuestionAnswering`]。指定标签数量 与标签映射: ```py >>> from transformers import ViltForQuestionAnswering >>> model = ViltForQuestionAnswering.from_pretrained(model_checkpoint, num_labels=len(id2label), id2label=id2label, label2id=label2id) ``` 此时只剩下三个步骤: 1. 定义您的训练超参数 [`TrainingArguments`]: ```py >>> from transformers import TrainingArguments >>> repo_id = "MariaK/vilt_finetuned_200" >>> training_args = TrainingArguments( ... output_dir=repo_id, ... per_device_train_batch_size=4, ... num_train_epochs=20, ... save_steps=200, ... logging_steps=50, ... learning_rate=5e-5, ... save_total_limit=2, ... remove_unused_columns=False, ... push_to_hub=True, ... ) ``` 2. 将训练论证传递给 [`Trainer`] 与模型、数据集、处理器和数据核对器一起。 ```py >>> from transformers import Trainer >>> trainer = Trainer( ... model=model, ... args=training_args, ... data_collator=data_collator, ... train_dataset=processed_dataset, ... processing_class=processor, ... ) ``` 3. 调用 [`~Trainer.train`] 来调整你的模特儿 ```py >>> trainer.train() ``` 训练完成后,将你的模型与Hub分享 [`~Trainer.push_to_hub`] 在 QQ 枢纽上分享您最终模型的方法 : ```py >>> trainer.push_to_hub() ``` ## 推论 现在您已经对一个ViLT模型进行了微调,并上传到QQ枢纽,您可以使用它进行推论. 1. 取一个图像和一个问题,让他们用你的模型中的处理器来准备模型. 2. 通过模型转发结果或预处理. 3. 从日志中获取最有可能的答案的ID, 并找到实际的答案在 `id2label`. ```py >>> processor = ViltProcessor.from_pretrained("MariaK/vilt_finetuned_200") >>> image = Image.open(example['image_id']) >>> question = example['question'] >>> # prepare inputs >>> inputs = processor(image, question, return_tensors="pt") >>> model = ViltForQuestionAnswering.from_pretrained("MariaK/vilt_finetuned_200") >>> # forward pass >>> with torch.no_grad(): ... outputs = model(**inputs) >>> logits = outputs.logits >>> idx = logits.argmax(-1).item() >>> print("Predicted answer:", model.config.id2label[idx]) Predicted answer: down ``` ## 零射门 VQA 之前的模型将VQA视为分类任务. 一些最近的模型,如BLIP,BLIP-2,以及InstructBLIP方法. VQA作为遗传性任务。 [BLIP-2](<https://github.com/huggingface/transformers/blob/HEAD/docs/source/en/model_doc/blip-2>) 它引入了一个新的视觉语言预培训。 范式中,可以使用预训视觉编码器和 LLM 的任何组合(在 [BLIP-2博客文章](https://huggingface.co/blog/blip-2)). 这样可以实现state-of-the-art在包括视觉问答在内的多种视觉语言任务上的结果. 让我们来说明你如何使用这个模型来进行VQA. 首先,让我们加载模型,在这里,我们将明确将模型发送到一个 GPU,如果有的话,在训练时我们不需要提前做,因为 [`Trainer`] 自动处理此选项 : ```py >>> from transformers import AutoProcessor, Blip2ForConditionalGeneration from accelerate import Accelerator >>> import torch >>> processor = AutoProcessor.from_pretrained("Salesforce/blip2-opt-2.7b") >>> model = Blip2ForConditionalGeneration.from_pretrained("Salesforce/blip2-opt-2.7b", dtype=torch.float16) >>> device = Accelerator().device >>> model.to(device) ``` 该模型将图像和文本作为输入,所以让我们使用VQA数据集中的第一个例子中的完全相同的图像/问题对: ```py >>> example = dataset[0] >>> image = Image.open(example['image_id']) >>> question = example['question'] ``` 要使用 BLIP-2 来进行视觉问答任务, 文本提示必须遵循特定格式 : `Question: {} Answer:`. ```py >>> prompt = f"Question: {question} Answer:" ``` 现在我们需要用模型的处理器预处理图像/瞬间,通过模型传递处理过的输入,并解码输出: ```py >>> inputs = processor(image, text=prompt, return_tensors="pt").to(device, torch.float16) >>> generated_ids = model.generate(**inputs, max_new_tokens=10) >>> generated_text = processor.batch_decode(generated_ids, skip_special_tokens=True)[0].strip() >>> print(generated_text) "He is looking at the crowd" ``` 如你所见,模特儿认出了人群, 和脸的方向(向下看),但似乎错过了 然而,如果获取人类附加说明的数据集不可行的话, 方法可以很快产生有益的结果。

查看原始来源