《纽约客》漫画数据集上尝试IDEFICS

社区文章 发布于2023年9月23日

今年早些时候,我使用 Salesforce 的LAVIS 库和 instruct/多模态模型生成了漫画描述。他们的理念是结合视觉编码器 (BLIP-2)、Vicuna (LLaMa v1 + delta 权重) 和额外的 InstructBLIP 权重。这有点繁琐,因为 LLaMa v1 的发布有限,并且需要在内存中重新组装模型。

IDEFICS 是 HuggingFace 推出的一个完整的多模态 instruct 模型,我很高兴能在相同的任务上尝试它。

首先,我获得了一个 A100 CoLab Pro 笔记本,并按照 IDEFICS 博客文章中的描述加载了模型

from transformers import IdeficsForVisionText2Text, AutoProcessor

model = IdeficsForVisionText2Text.from_pretrained(
  "HuggingFaceM4/idefics-9b-instruct",
  torch_dtype=torch.bfloat16,
).to(device)
processor = AutoProcessor.from_pretrained("HuggingFaceM4/idefics-9b-instruct")

下面是如何获取《纽约客》漫画和字幕匹配数据集

from datasets import load_dataset
cartoons = load_dataset("jmhessel/newyorker_caption_contest", "matching")

我可以像这样从数据集中获取一张 PIL 图像

image = None
for cartoon in cartoons['train']:
  image = cartoon['image']
  #print(cartoon['caption_choices'])
  break
image # at end if you're doing CoLab, to see the image yourself

在之前的项目中,我有时间考虑提示。大多数图像字幕示例都使用“详细描述图像”的变体——但由于这已经是《纽约客》漫画的独特风格,您通常只会从每个响应中获得这些事实。如果我们想要足够的信息来提供提示并使其更容易为图像选择匹配的笑话或字幕,我声明它是一个漫画,要求具体细节,并暗示一个有趣的前提。

这是 instruct/聊天格式的提示

prompts = [
    [
        "User: Describe all characters and setting of this cartoon in detail. It may be sardonic or absurdist.",
        image,
        "<end_of_utterance>",
    ],
]

让我们继续完成 HF 博客中的其余生成代码

inputs = processor(prompts, return_tensors="pt").to(device)
bad_words_ids = processor.tokenizer(["<image>", "<fake_token_around_image>"], add_special_tokens=False).input_ids

generated_ids = model.generate(**inputs, bad_words_ids=bad_words_ids, max_length=100)
generated_text = processor.batch_decode(generated_ids, skip_special_tokens=True)
for i, t in enumerate(generated_text):
    print(f"{i}:\n{t}\n")

结果

giraffe cartoon from The New Yorker

用户:详细描述这幅漫画的所有人物和背景。它可能是讽刺或荒诞的。

助理:图像中有两只长颈鹿站在客厅里。一只长颈鹿坐在沙发上,另一只站在咖啡桌旁。客厅里摆放着一台挂在墙上的电视、一张边桌上的台灯和一盆放在地板上的盆栽。

通过了氛围检查!

CoLab 链接:https://colab.research.google.com/drive/15kd17YRdbVayggA-ZCYiXTYzZG4w8zUd?usp=sharing

未来工作

诚然,前几条漫画字幕的准确性不高,所以我做了一些精挑细选,但它们都在正确的范围内。我认为有机会用这种类似聊天的格式重写提示或做一些少量示例。

社区

注册登录 以发表评论