跳到主要内容

为聊天模型微调准备和分析数据

nbviewer

这个笔记本用作预处理和分析用于微调聊天模型的聊天数据集的工具。 它检查格式错误,提供基本统计信息,并估计用于微调成本的标记计数。 这里展示的方法对应于gpt-3.5-turbo的当前微调方法。 有关像babbage-002和davinci-002这样的模型的旧微调,请参见旧微调

import json
import tiktoken # 用于计数令牌
import numpy as np
from collections import defaultdict

数据加载

我们首先从示例JSONL文件中加载聊天数据集。

data_path = "data/toy_chat_fine_tuning.jsonl"

# 加载数据集
with open(data_path, 'r', encoding='utf-8') as f:
dataset = [json.loads(line) for line in f]

# 初始数据集统计信息
print("Num examples:", len(dataset))
print("First example:")
for message in dataset[0]["messages"]:
print(message)

Num examples: 5
First example:
{'role': 'system', 'content': 'You are a happy assistant that puts a positive spin on everything.'}
{'role': 'user', 'content': 'I fell off my bike today.'}
{'role': 'assistant', 'content': "It's great that you're getting exercise outdoors!"}

格式验证

我们可以执行各种错误检查,以验证数据集中的每个对话是否符合微调API所期望的格式。错误根据其性质进行分类,以便更容易进行调试。

  1. 数据类型检查:检查数据集中的每个条目是否为字典(dict)。错误类型:data_type
  2. 消息列表的存在性:检查每个条目中是否存在一个messages列表。错误类型:missing_messages_list
  3. 消息键检查:验证messages列表中的每条消息是否包含rolecontent键。错误类型:message_missing_key
  4. 消息中未识别的键:记录如果一条消息除了rolecontentweightfunction_callname之外还有其他键。错误类型:message_unrecognized_key
  5. 角色验证:确保role是”system”、“user”或”assistant”中的一个。错误类型:unrecognized_role
  6. 内容验证:验证content是否包含文本数据并且是一个字符串。错误类型:missing_content
  7. 助手消息的存在性:检查每个对话中是否至少有一条来自助手的消息。错误类型:example_missing_assistant_message

下面的代码执行这些检查,并打印出找到的每种类型的错误的计数。这对于调试和确保数据集已准备好进行下一步操作非常有用。

# 格式错误检查
format_errors = defaultdict(int)

for ex in dataset:
if not isinstance(ex, dict):
format_errors["data_type"] += 1
continue

messages = ex.get("messages", None)
if not messages:
format_errors["missing_messages_list"] += 1
continue

for message in messages:
if "role" not in message or "content" not in message:
format_errors["message_missing_key"] += 1

if any(k not in ("role", "content", "name", "function_call", "weight") for k in message):
format_errors["message_unrecognized_key"] += 1

if message.get("role", None) not in ("system", "user", "assistant", "function"):
format_errors["unrecognized_role"] += 1

content = message.get("content", None)
function_call = message.get("function_call", None)

if (not content and not function_call) or not isinstance(content, str):
format_errors["missing_content"] += 1

if not any(message.get("role", None) == "assistant" for message in messages):
format_errors["example_missing_assistant_message"] += 1

if format_errors:
print("Found errors:")
for k, v in format_errors.items():
print(f"{k}: {v}")
else:
print("No errors found")

No errors found

计数工具

让我们定义一些有用的工具,以便在笔记本的其余部分中使用。

encoding = tiktoken.get_encoding("cl100k_base")

# 不精确!
# 摘自 https://github.com/openai/openai-cookbook/blob/main/examples/How_to_count_tokens_with_tiktoken.ipynb
def num_tokens_from_messages(messages, tokens_per_message=3, tokens_per_name=1):
num_tokens = 0
for message in messages:
num_tokens += tokens_per_message
for key, value in message.items():
num_tokens += len(encoding.encode(value))
if key == "name":
num_tokens += tokens_per_name
num_tokens += 3
return num_tokens

def num_assistant_tokens_from_messages(messages):
num_tokens = 0
for message in messages:
if message["role"] == "assistant":
num_tokens += len(encoding.encode(message["content"]))
return num_tokens

def print_distribution(values, name):
print(f"\n#### Distribution of {name}:")
print(f"min / max: {min(values)}, {max(values)}")
print(f"mean / median: {np.mean(values)}, {np.median(values)}")
print(f"p5 / p95: {np.quantile(values, 0.1)}, {np.quantile(values, 0.9)}")

数据警告和标记计数

通过一些轻量级分析,我们可以识别数据集中的潜在问题,比如缺失的消息,并提供关于消息和标记计数的统计见解。

  1. 缺失的系统/用户消息:计算缺少“系统”或“用户”消息的对话数量。这些消息对于定义助手的行为并启动对话至关重要。
  2. 每个示例的消息数量:总结每个对话中消息数量的分布,提供关于对话复杂性的见解。
  3. 每个示例的总标记数:计算并总结每个对话中标记总数的分布。这对于理解微调成本很重要。
  4. 助手消息中的标记数:计算每个对话中助手消息中的标记数,并总结这个分布。有助于理解助手的冗长程度。
  5. 标记限制警告:检查是否有任何示例超过最大标记限制(16,385个标记),因为这样的示例在微调过程中将被截断,可能导致数据丢失。
# 警告和令牌计数
n_missing_system = 0
n_missing_user = 0
n_messages = []
convo_lens = []
assistant_message_lens = []

for ex in dataset:
messages = ex["messages"]
if not any(message["role"] == "system" for message in messages):
n_missing_system += 1
if not any(message["role"] == "user" for message in messages):
n_missing_user += 1
n_messages.append(len(messages))
convo_lens.append(num_tokens_from_messages(messages))
assistant_message_lens.append(num_assistant_tokens_from_messages(messages))

print("Num examples missing system message:", n_missing_system)
print("Num examples missing user message:", n_missing_user)
print_distribution(n_messages, "num_messages_per_example")
print_distribution(convo_lens, "num_total_tokens_per_example")
print_distribution(assistant_message_lens, "num_assistant_tokens_per_example")
n_too_long = sum(l > 16,385 for l in convo_lens)
print(f"\n{n_too_long} examples may be over the 16,385 token limit, they will be truncated during fine-tuning")

Num examples missing system message: 1
Num examples missing user message: 1

#### Distribution of num_messages_per_example:
min / max: 2, 9
mean / median: 3.8, 3.0
p5 / p95: 2.0, 6.6000000000000005

#### Distribution of num_total_tokens_per_example:
min / max: 26, 8032
mean / median: 1648.4, 45.0
p5 / p95: 26.8, 4863.6

#### Distribution of num_assistant_tokens_per_example:
min / max: 4, 8000
mean / median: 1610.2, 10.0
p5 / p95: 6.0, 4811.200000000001

0 examples may be over the 16,385 token limit, they will be truncated during fine-tuning

成本估算

在这最后一节中,我们将估算用于微调的总标记数量,从而使我们能够近似成本。 值得注意的是,微调作业的持续时间也会随着标记数量的增加而增加。

# 定价与默认的n_epochs估计
MAX_TOKENS_PER_EXAMPLE = 16385

TARGET_EPOCHS = 3
MIN_TARGET_EXAMPLES = 100
MAX_TARGET_EXAMPLES = 25000
MIN_DEFAULT_EPOCHS = 1
MAX_DEFAULT_EPOCHS = 25

n_epochs = TARGET_EPOCHS
n_train_examples = len(dataset)
if n_train_examples * TARGET_EPOCHS < MIN_TARGET_EXAMPLES:
n_epochs = min(MAX_DEFAULT_EPOCHS, MIN_TARGET_EXAMPLES // n_train_examples)
elif n_train_examples * TARGET_EPOCHS > MAX_TARGET_EXAMPLES:
n_epochs = max(MIN_DEFAULT_EPOCHS, MAX_TARGET_EXAMPLES // n_train_examples)

n_billing_tokens_in_dataset = sum(min(MAX_TOKENS_PER_EXAMPLE, length) for length in convo_lens)
print(f"Dataset has ~{n_billing_tokens_in_dataset} tokens that will be charged for during training")
print(f"By default, you'll train for {n_epochs} epochs on this dataset")
print(f"By default, you'll be charged for ~{n_epochs * n_billing_tokens_in_dataset} tokens")

Dataset has ~4306 tokens that will be charged for during training
By default, you'll train for 20 epochs on this dataset
By default, you'll be charged for ~86120 tokens

请查看 https://openai.com/pricing 以估算总成本。