Shortcuts

多模态数据集

多模态数据集包含多种数据模态,例如文本+图像,可用于训练基于Transformer的模型。 torchtune目前仅支持用于视觉语言模型(VLMs)的多模态文本+图像聊天数据集。

在torchtune中使用多模态数据集进行微调的主要入口点是multimodal_chat_dataset()构建器。这允许您直接从配置中指定遵循多模态聊天数据格式的本地或Hugging Face数据集,并在其上训练您的VLM。

示例多模态数据集

这是一个用于视觉问答任务的多模态聊天数据集的示例。请注意,在文本中有一个占位符"",用于放置图像标记。在下面的示例中,这将被图像特殊标记<|image|>替换。

# data/my_data.json
[
    {
        "dialogue": [
            {
                "from": "human",
                "value": "<image>What time is it on the clock?",
            },
            {
                "from": "gpt",
                "value": "It is 10:00 AM.",
            },
        ],
        "image_path": "images/clock.jpg",
    },
    ...,
]
from torchtune.models.llama3_2_vision import llama3_2_vision_transform
from torchtune.datasets.multimodal import multimodal_chat_dataset

model_transform = Llama3VisionTransform(
    path="/tmp/Meta-Llama-3-8B-Instruct/original/tokenizer.model",
    prompt_template="torchtune.data.QuestionAnswerTemplate",
    max_seq_len=8192,
    image_size=560,
)
ds = multimodal_chat_dataset(
    model_transform=model_transform,
    source="json",
    data_files="data/my_data.json",
    column_map={
        "dialogue": "conversations",
        "image_path": "image",
    },
    image_dir="/home/user/dataset/",  # /home/user/dataset/images/clock.jpg
    image_tag="<image>",
    split="train",
)
tokenized_dict = ds[0]
print(model_transform.decode(tokenized_dict["tokens"], skip_special_tokens=False))
# '<|begin_of_text|><|start_header_id|>user<|end_header_id|>\n\nQuestion:<|image|>What time is it on the clock?Answer:<|eot_id|><|start_header_id|>assistant<|end_header_id|>\n\nIt is 10:00AM.<|eot_id|>'
print(tokenized_dict["encoder_input"]["images"][0].shape)  # (num_tiles, num_channels, tile_height, tile_width)
# torch.Size([4, 3, 224, 224])
tokenizer:
  _component_: torchtune.models.llama3_2_vision_transform
  path: /tmp/Meta-Llama-3-8B-Instruct/original/tokenizer.model
  prompt_template: torchtune.data.QuestionAnswerTemplate
  max_seq_len: 8192
  image_size: 560

dataset:
  _component_: torchtune.datasets.multimodal.multimodal_chat_dataset
  source: json
  data_files: data/my_data.json
  split: train
  column_map:
    dialogue: conversations
    image_path: image
  image_dir: /home/user/dataset/
  image_tag: "<image>"
  split: train

多模态数据集格式

目前,多模态数据集预计遵循"sharegpt"聊天格式,其中图像路径位于一列,用户与助手的对话位于另一列。

|  conversations                     | image        |
|------------------------------------|--------------|
| [{"from": "human", "value": "Q1"}, | images/1.jpg |
|  {"from": "gpt", "value": "A1"}]   |              |

例如,你可以查看ShareGPT4V数据集的模式。

目前,multimodal_chat_dataset() 每个对话样本仅支持单个图像路径。

从Hugging Face加载多模态数据集

您只需将数据集仓库名称传递给source,然后将其传递给Hugging Face的load_dataset。 对于大多数数据集,您还需要通过name指定split和/或子集。

# In code
from torchtune.models.llama3_2_vision import llama3_2_vision_transform
from torchtune.datasets.multimodal import multimodal_chat_dataset

model_transform = llama3_2_vision_transform(
    path="/tmp/Meta-Llama-3-8B-Instruct/original/tokenizer.model",
    max_seq_len=8192,
    image_size=560,
)
ds = multimodal_chat_dataset(
    model_transform=model_transform,
    source="Lin-Chen/ShareGPT4V",
    split="train",
    name="ShareGPT4V",
    image_dir="/home/user/dataset/",
    image_tag="<image>",
)
# In config
tokenizer:
  _component_: torchtune.models.llama3_2_vision.llama3_2_vision_transform
  path: /tmp/Meta-Llama-3-8B-Instruct/original/tokenizer.model
  max_seq_len: 8192
  image_size: 560

# Tokenizer is passed into the dataset in the recipe
dataset:
  _component_: torchtune.datasets.multimodal.multimodal_chat_dataset
  source: Lin-Chen/ShareGPT4V
  split: train
  name: ShareGPT4V
  image_dir: /home/user/dataset/
  image_tag: "<image>"

这将使用默认的列名“conversations”和“image”。要更改列名,请使用column_map参数(参见重命名列)。

加载本地和远程多模态数据集

要通过https加载遵循instruct格式的本地或远程数据集,您需要指定sourcedata_filessplit参数。有关加载本地或远程文件的更多详细信息,请参阅Hugging Face的load_dataset 文档。请参阅上面的示例多模态数据集

加载图片

在许多情况下,您的数据集将包含图像的路径而不是原始图像本身。multimodal_chat_dataset() 会自动为您处理这个问题,但如果您正在为自定义多模态数据集编写自定义消息转换 (参见自定义消息转换),您可以直接使用load_image()工具。

from torchtune.data import load_image
from pathlib import Path

sample = {
    "conversations": [
        {
            "from": "human",
            "value": "What time is it on the clock?",
        },
        {
            "from": "gpt",
            "value": "It is 10:00 AM.",
        },
    ],
    "image": "images/clock.jpg",
}
image_dir = "/home/user/dataset/"
pil_image = load_image(Path(image_dir) / Path(sample["image"]))
print(pil_image)
# <PIL.Image.Image>

然后,您可以直接将PIL图像添加到相关消息的内容中。在消息中,仅支持PIL图像作为图像内容,不支持图像路径或URL。

from torchtune.data import Message

user_message = None
for msg in sample["conversations"]:
    if msg["from"] == "human":
        user_message = Message(
            role="user",
            content=[
                {"type": "image", "content": pil_image},
                {"type": "text", "content": msg["value"]},
            ]
        )
print(user_message.contains_media)
# True
print(user_message.get_media())
# [<PIL.Image.Image>]
print(user_message.text_content)
# What time is it on the clock?

如果数据集中的图像路径是相对路径,您可以使用image_dir参数在multimodal_chat_dataset()中预先添加图像在本地下载的完整路径。

在文本中交错显示图像

torchtune 支持在文本的任何位置添加多张图片,只要您的模型支持。

import PIL
from torchtune.data import Message

image_dog = PIL.Image.new(mode="RGB", size=(4, 4))
image_cat = PIL.Image.new(mode="RGB", size=(4, 4))
image_bird = PIL.Image.new(mode="RGB", size=(4, 4))

user_message = Message(
    role="user",
    content=[
        {"type": "image", "content": image_dog},
        {"type": "text", "content": "This is an image of a dog. "},
        {"type": "image", "content": image_cat},
        {"type": "text", "content": "This is an image of a cat. "},
        {"type": "image", "content": image_bird},
        {"type": "text", "content": "This is a bird, the best pet of the three."},
    ]
)
print(user_message.contains_media)
# True
print(user_message.get_media())
# [<PIL.Image.Image>, <PIL.Image.Image>, <PIL.Image.Image>]
print(user_message.text_content)
# This is an image of a dog. This is an image of a cat. This is a bird, the best pet of the three.

您的数据集可能包含图像占位符标签,这些标签指示图像应在文本中的哪个位置被引用。例如,参见ShareGPT4V ,它使用了""。您可以使用实用工具format_content_with_images()轻松创建类似于上述的交错消息内容,该工具将图像占位符标签替换为传入的图像。

import PIL
from torchtune.data import Message, format_content_with_images

image_dog = PIL.Image.new(mode="RGB", size=(4, 4))
image_cat = PIL.Image.new(mode="RGB", size=(4, 4))
image_bird = PIL.Image.new(mode="RGB", size=(4, 4))

text = "[img]This is an image of a dog. [img]This is an image of a cat. [img]This is a bird, the best pet of the three."
user_message = Message(
    role="user",
    content=format_content_with_images(
        content=text,
        image_tag="[img]",
        images=[image_dog, image_cat, image_bird],
    ),
)
print(user_message.contains_media)
# True
print(user_message.get_media())
# [<PIL.Image.Image>,<PIL.Image.Image>, <PIL.Image.Image>]
print(user_message.text_content)
# This is an image of a dog. This is an image of a cat. This is a bird, the best pet of the three.

当您传入image_tag时,这将在multimodal_chat_dataset()中自动为您处理。

内置多模态数据集