目录

配置数据集以进行微调

本教程将指导您完成如何设置要微调的数据集。

您将学到什么
  • 如何快速开始使用内置数据集

  • 如何使用 Hugging Face Hub 中的任何数据集

  • 如何使用 instruct、chat 或 text completion 数据集

  • 如何从代码、配置或命令行配置数据集

  • 如何完全自定义您自己的数据集

先决条件

数据集是微调工作流的核心组件,用作“指导” wheel“来指导特定用例的 LLM 生成。许多公开共享 开源数据集在微调 LLM 方面已经很流行,并且是一个很棒的 训练模型的起点。Torchtune 为您提供了下载外部 社区数据集,加载自定义本地数据集,或创建您自己的数据集。

内置数据集

要使用库中的内置数据集之一,只需导入并调用数据集生成器即可 功能。您可以在此处查看所有受支持的数据集的列表。

from torchtune.datasets import alpaca_dataset

# Load in tokenizer
tokenizer = ...
dataset = alpaca_dataset(tokenizer)
# YAML config
dataset:
  _component_: torchtune.datasets.alpaca_dataset
# Command line
tune run full_finetune_single_device --config llama3/8B_full_single_device \
dataset=torchtune.datasets.alpaca_dataset

Hugging Face 数据集

我们为 Hugging Face Hub 上的数据集提供一流的支持。在引擎盖下, 我们所有的内置数据集和数据集生成器都使用 Hugging Face 来加载您的数据,无论是本地还是中心。load_dataset()

您可以将 Hugging Face 数据集路径传入我们的任何构建器中的参数 以指定要下载的 Hub 上的数据集。此外,所有构建器都接受 任何支持的 keyword-arguments。您可以查看完整列表 在 Hugging Face 的文档上sourceload_dataset()

from torchtune.datasets import text_completion_dataset

# Load in tokenizer
tokenizer = ...
dataset = text_completion_dataset(
    tokenizer,
    source="allenai/c4",
    # Keyword-arguments that are passed into load_dataset
    split="train",
    data_dir="realnewslike",
)
# YAML config
dataset:
  _component_: torchtune.datasets.text_completion_dataset
  source: allenai/c4
  split: train
  data_dir: realnewslike
# Command line
tune run full_finetune_single_device --config llama3/8B_full_single_device \
dataset=torchtune.datasets.text_completion_dataset dataset.source=allenai/c4 \
dataset.split=train dataset.data_dir=realnewslike

设置最大序列长度

所有 我们的训练配方会将样本填充到批次中的最大序列长度, 不是全球性的。如果您希望全局设置最大序列长度的上限, 您可以在 数据集生成器中使用 指定它。数据集中的任何样本 ,这比 中将被截断的时间长。 确保分词器的 EOS ID 是最后一个令牌,但 .padded_collate()max_seq_lenmax_seq_len

通常,您希望每个数据样本中返回的最大序列长度与上下文窗口匹配 size 的模型。您还可以减小此值以减少内存使用量 具体取决于您的硬件限制。

from torchtune.datasets import alpaca_dataset

# Load in tokenizer
tokenizer = ...
dataset = alpaca_dataset(
    tokenizer=tokenizer,
    max_seq_len=4096,
)
# YAML config
dataset:
  _component_: torchtune.datasets.alpaca_dataset
  max_seq_len: 4096
# Command line
tune run full_finetune_single_device --config llama3/8B_full_single_device \
dataset.max_seq_len=4096

样品包装

您可以通过传入 .这需要对数据集进行一些预处理,这可能会 减慢第一批的时间,但可以显著加快训练速度 取决于数据集。packed=True

from torchtune.datasets import alpaca_dataset, PackedDataset

# Load in tokenizer
tokenizer = ...
dataset = alpaca_dataset(
    tokenizer=tokenizer,
    packed=True,
)
print(isinstance(dataset, PackedDataset))  # True
# YAML config
dataset:
  _component_: torchtune.datasets.alpaca_dataset
  packed: True
# Command line
tune run full_finetune_single_device --config llama3/8B_full_single_device \
dataset.packed=True

自定义非结构化文本语料库

对于持续的预训练,通常使用与预训练类似的数据设置 对于简单的文本完成任务。这意味着没有 instruct 模板、聊天格式、 和最少的特殊代币(仅限 BOS 和 EOS)。要指定非结构化文本语料库, 您可以将构建器与 Hugging Face 数据集或自定义本地语料库。以下是为 local 指定它的方法 文件:

from torchtune.datasets import text_completion_dataset

# Load in tokenizer
tokenizer = ...
dataset = text_completion_dataset(
    tokenizer,
    source="text",
    data_files="path/to/my_data.txt",
    split="train",
)
# YAML config
dataset:
  _component_: torchtune.datasets.text_completion_dataset
  source: text
  data_files: path/to/my_data.txt
  split: train
# Command line
tune run --nproc_per_node 4 full_finetune_distributed --config llama3/8B_full \
dataset=torchtune.datasets.text_completion_dataset dataset.source=text \
dataset.data_files=path/to/my_data.txt dataset.split=train

自定义 instruct 数据集和 instruct 模板

如果您有库中尚未提供的自定义 instruct 数据集, 您可以使用构建器并指定 源路径。Instruct 数据集通常具有多个列,其中包含 的格式设置为提示模板。

要对特定任务微调 LLM,一种常见的方法是创建一个固定的指令 模板,该模板指导模型生成具有特定目标的输出。Instruct 模板 只是构建模型输入的 flavor 文本。它与模型无关 并且通常像任何其他文本一样进行标记化,但它可以帮助调节模型 以更好地响应预期的格式。例如,按以下方式构建数据:

"Below is an instruction that describes a task, paired with an input that provides further context. "
"Write a response that appropriately completes the request.\n\n"
"### Instruction:\n{instruction}\n\n### Input:\n{input}\n\n### Response:\n"

以下是格式为

from torchtune.data import AlpacaInstructTemplate

sample = {
    "instruction": "Classify the following into animals, plants, and minerals",
    "input": "Oak tree, copper ore, elephant",
}
prompt = AlpacaInstructTemplate.format(sample)
print(prompt)
# Below is an instruction that describes a task, paired with an input that provides further context.
# Write a response that appropriately completes the request.
#
# ### Instruction:
# Classify the following into animals, plants, and minerals
#
# ### Input:
# Oak tree, copper ore, elephant
#
# ### Response:
#

我们为常见任务(如摘要和语法更正)提供了其他 instruct 模板 <data>。如果您需要创建自己的 instruct 模板,您可以继承并创建自己的类。

from torchtune.datasets import instruct_dataset
from torchtune.data import InstructTemplate

class CustomTemplate(InstructTemplate):
    # Define the template as string with {} as placeholders for data columns
    template = ...

    # Implement this method
    @classmethod
    def format(
        cls, sample: Mapping[str, Any], column_map: Optional[Dict[str, str]] = None
    ) -> str:
        ...

# Load in tokenizer
tokenizer = ...
dataset = instruct_dataset(
    tokenizer=tokenizer,
    source="my/dataset/path",
    template="import.path.to.CustomTemplate",
)
# YAML config
dataset:
  _component_: torchtune.datasets.instruct_dataset
  source: my/dataset/path
  template: import.path.to.CustomTemplate
# Command line
tune run full_finetune_single_device --config llama3/8B_full_single_device \
dataset=torchtune.datasets.instruct_dataset dataset.source=my/dataset/path \
dataset.template=import.path.to.CustomTemplate

自定义聊天数据集和聊天格式

如果您有库中尚未提供的自定义聊天/对话数据集, 您可以使用构建器并指定 源路径。聊天数据集通常具有单个列和多个 back 以及 FORTH 用户和 Assistant 之间的消息。

聊天格式类似于 instruct 模板,只是它们格式化 system, user 和 Assistant 消息合并到消息列表中(请参阅 ) 以获取对话数据集。这些可以配置得与 instruct 非常相似 数据。

以下是使用

from torchtune.data import Llama2ChatFormat, Message

messages = [
    Message(
        role="system",
        content="You are a helpful, respectful, and honest assistant.",
    ),
    Message(
        role="user",
        content="I am going to Paris, what should I see?",
    ),
    Message(
        role="assistant",
        content="Paris, the capital of France, is known for its stunning architecture..."
    ),
]
formatted_messages = Llama2ChatFormat.format(messages)
print(formatted_messages)
# [
#     Message(
#         role="user",
#         content="[INST] <<SYS>>\nYou are a helpful, respectful and honest assistant.\n<</SYS>>\n\n"
#         "I am going to Paris, what should I see? [/INST] ",
#     ),
#     Message(
#         role="assistant",
#         content="Paris, the capital of France, is known for its stunning architecture..."
#     ),
# ]

请注意,系统消息现在已合并到用户消息中。如果您创建自定义 ChatFormat 您还可以添加更高级的行为。

from torchtune.datasets import chat_dataset
from torchtune.data import ChatFormat

class CustomChatFormat(ChatFormat):
    # Define templates for system, user, assistant messages
    # as strings with {} as placeholders for message content
    system = ...
    user = ...
    assistant = ...

    # Implement this method
    @classmethod
    def format(
        cls,
        sample: List[Message],
    ) -> List[Message]:
        ...

# Load in tokenizer
tokenizer = ...
dataset = chat_dataset(
    tokenizer=tokenizer,
    source="my/dataset/path",
    split="train",
    conversation_style="openai",
    chat_format="import.path.to.CustomChatFormat",
)
# YAML config
dataset:
  _component_: torchtune.datasets.chat_dataset
  source: my/dataset/path
  conversation_style: openai
  chat_format: import.path.to.CustomChatFormat
# Command line
tune run full_finetune_single_device --config llama3/8B_full_single_device \
dataset=torchtune.datasets.chat_dataset dataset.source=my/dataset/path \
dataset.conversation_style=openai dataset.chat_format=import.path.to.CustomChatFormat

多个内存数据集

也可以在多个数据集上进行训练,并使用 我们的界面。您甚至可以混合使用指示和聊天数据集 或其他自定义数据集。

# YAML config
dataset:
  - _component_: torchtune.datasets.instruct_dataset
    source: vicgalle/alpaca-gpt4
    template: torchtune.data.AlpacaInstructTemplate
    split: train
    train_on_input: True
  - _component_: torchtune.datasets.instruct_dataset
    source: samsum
    template: torchtune.data.SummarizeTemplate
    column_map:
      output: summary
    split: train
    train_on_input: False
  - _component_: torchtune.datasets.chat_dataset
    ...

本地和远程数据集

要使用保存在本地硬盘驱动器上的数据集,只需指定文件类型并使用任何数据集传入参数 builder 函数。我们支持 Hugging Face 支持的所有文件类型,包括 csv、json、txt 等。sourcedata_filesload_dataset

from torchtune.datasets import instruct_dataset

# Load in tokenizer
tokenizer = ...
# Local files
dataset = instruct_dataset(
    tokenizer=tokenizer,
    source="csv",
    split="train",
    template="import.path.to.CustomTemplate"
    data_files="path/to/my/data.csv",
)
# Remote files
dataset = instruct_dataset(
    tokenizer=tokenizer,
    source="json",
    split="train",
    template="import.path.to.CustomTemplate"
    data_files="https://rajpurkar.github.io/SQuAD-explorer/dataset/train-v2.0.json",
    # You can also pass in any kwarg that load_dataset accepts
    field="data",
)
# YAML config - local files
dataset:
  _component_: torchtune.datasets.instruct_dataset
  source: csv
  template: import.path.to.CustomTemplate
  data_files: path/to/my/data.csv

# YAML config - remote files
dataset:
  _component_: torchtune.datasets.instruct_dataset
  source: json
  template: import.path.to.CustomTemplate
  data_files: https://rajpurkar.github.io/SQuAD-explorer/dataset/train-v2.0.json
  field: data
# Command line - local files
tune run full_finetune_single_device --config llama3/8B_full_single_device \
dataset=torchtune.datasets.chat_dataset dataset.source=csv \
dataset.template=import.path.to.CustomTemplate dataset.data_files=path/to/my/data.csv

完全自定义的数据集

不适合模板和处理的更高级的任务和数据集格式 那 , 和 provide 可能需要您创建自己的数据集 class 以获得更大的灵活性。让我们来看看 , 它具有 RLHF 首选项数据的自定义功能,作为了解您需要做什么的示例。

如果你看一下这个类的代码, 您会注意到它与 对首选项数据中所选样本和拒绝样本的调整。

chosen_message = [
    Message(role="user", content=prompt, masked=True),
    Message(role="assistant", content=transformed_sample[key_chosen]),
]
rejected_message = [
    Message(role="user", content=prompt, masked=True),
    Message(role="assistant", content=transformed_sample[key_rejected]),
]

chosen_input_ids, c_masks = self._tokenizer.tokenize_messages(
    chosen_message, self.max_seq_len
)
chosen_labels = list(
    np.where(c_masks, CROSS_ENTROPY_IGNORE_IDX, chosen_input_ids)
)

rejected_input_ids, r_masks = self._tokenizer.tokenize_messages(
    rejected_message, self.max_seq_len
)
rejected_labels = list(
    np.where(r_masks, CROSS_ENTROPY_IGNORE_IDX, rejected_input_ids)
)

对于易于从配置中自定义的特定数据集,您可以创建 构建器函数。这是 的 builder 函数 , 这会创建一个 configured 以使用 来自 Hugging Face 的配对数据集。请注意,我们还具有 以添加自定义 Instruct 模板。

def stack_exchanged_paired_dataset(
    tokenizer: ModelTokenizer,
    max_seq_len: int = 1024,
) -> PreferenceDataset:
    return PreferenceDataset(
        tokenizer=tokenizer,
        source="lvwerra/stack-exchange-paired",
        template=StackExchangedPairedTemplate(),
        column_map={
            "prompt": "question",
            "chosen": "response_j",
            "rejected": "response_k",
        },
        max_seq_len=max_seq_len,
        split="train",
        data_dir="data/rl",
    )

现在,我们可以轻松地从配置或命令行指定我们的自定义数据集。

# This is how you would configure the Alpaca dataset using the builder
dataset:
  _component_: torchtune.datasets.stack_exchanged_paired_dataset
  max_seq_len: 512
# Command line - local files
tune run full_finetune_single_device --config llama3/8B_full_single_device \
dataset=torchtune.datasets.stack_exchanged_paired_dataset dataset.max_seq_len=512

文档

访问 PyTorch 的全面开发人员文档

查看文档

教程

获取面向初学者和高级开发人员的深入教程

查看教程

资源

查找开发资源并解答您的问题

查看资源