unsloth 笔记;数据集

1 数据格式

格式 (Format) 描述 (Description) 训练类型 (Training Type)
Raw Corpus 来自某个来源的原始文本,例如网站、书籍或文章。 持续预训练 (Continued Pretraining, CPT)
Instruct 提供给模型的指令,以及一个期望输出的示例。 监督式微调 (Supervised Fine-tuning, SFT)
Conversation 用户与 AI 助手之间的多轮对话。 监督式微调 (Supervised Fine-tuning, SFT)
RLHF 用户与 AI 助手之间的对话,其中助手的回答会由脚本、其他模型或人工评估者进行排序。 强化学习 (Reinforcement Learning, RL)

1.1 持续预训练

使用原始文本格式,没有特定结构:

bash 复制代码
"text": "Pasta carbonara is a traditional Roman pasta dish. The sauce is made by mixing raw eggs with grated Pecorino Romano cheese and black pepper. The hot pasta is then tossed with crispy guanciale (cured pork cheek) and the egg mixture, creating a creamy sauce from the residual heat. Despite popular belief, authentic carbonara never contains cream or garlic. The dish likely originated in Rome in the mid-20th century, though its exact origins are debated..."

这种格式保留了自然语言的流畅性,适合模型从连续文本中学习。

1.2 指令格式

适用于单轮任务执行:

python 复制代码
"Instruction": "Task we want the model to perform.",
"Input": "Optional, but useful, it will essentially be the user's query.",
"Output": "The expected result of the task and the output of the model."

1.3 多轮对话格式

1.3.1 ShareGPT 格式

python 复制代码
{
  "conversations": [
    {
      "from": "human",
      "value": "Can you help me make pasta carbonara?"
    },
    {
      "from": "gpt",
      "value": "Would you like the traditional Roman recipe, or a simpler version?"
    },
    {
      "from": "human",
      "value": "The traditional version please"
    },
    {
      "from": "gpt",
      "value": "The authentic Roman carbonara uses just a few ingredients: pasta, guanciale, eggs, Pecorino Romano, and black pepper. Would you like the detailed recipe?"
    }
  ]
}

这里使用 "from" 和 "value" 键,消息在人类与 GPT 间交替,形成自然对话流。

1.3.2 OpenAI ChatML 格式

这是 Hugging Face 默认支持的格式,也是目前最常用的格式。

bash 复制代码
{
  "messages": [
    {
      "role": "user",
      "content": "What is 1+1?"
    },
    {
      "role": "assistant",
      "content": "It's 2!"
    }
  ]
}

2 在 Unsloth 中应用 Chat 模板

(将原始raw file改成大模型能够理解/要求的格式)

2.1 检查 Unsloth 当前支持的 chat 模板

python 复制代码
from unsloth.chat_templates import CHAT_TEMPLATES
print(list(CHAT_TEMPLATES.keys()))
'''
['unsloth', 'zephyr', 'chatml', 'mistral', 'llama', 'vicuna', 
'vicuna_old', 'vicuna old', 
'alpaca', 'gemma', 'gemma_chatml', 'gemma2', 'gemma2_chatml', 
'llama-3', 'llama3', 'phi-3',
 'phi-35', 'phi-3.5', 'llama-3.1', 'llama-31', 'llama-3.2', 
'llama-3.3', 'llama-32', 
'llama-33', 'qwen-2.5', 'qwen-25', 'qwen25', 'qwen2.5', 'phi-4', 
'gemma-3', 'gemma3', 
'qwen-3', 'qwen3', 'gemma-3n', 'gemma3n', 'gpt-oss', 'gptoss', 
'qwen3-instruct', 'qwen3-thinking']
'''

2.2 使用 get_chat_template 应用正确的模板

python 复制代码
from unsloth.chat_templates import get_chat_template

tokenizer = get_chat_template(
    tokenizer,
    chat_template = "gemma-3", # 修改为对应的模板名称
)

2.2.1 为什么不直接使用 tokenizer 自带的 apply_chat_template?

  • 原始模型上传时,chat_template 属性有时会包含错误,并且更新较慢。
  • 相比之下,Unsloth 在上传量化版本模型到仓库时,会彻底检查并修复 chat_template 中的错误。
  • 此外,Unsloth 的 get_chat_template 和 apply_chat_template 方法提供了更强大的数据处理功能,文档中有完整说明。

2.3 定义格式化函数

python 复制代码
def formatting_prompts_func(examples):
   convos = examples["conversations"]
   #从批量样本中取出对话字段。
   texts = [
       tokenizer.apply_chat_template(
           convo,
           tokenize = False,              # 直接生成字符串,不做 token 化
           add_generation_prompt = False  # 不在最后额外加 Assistant 的起始符
       ) 
       for convo in convos
   ]
   '''
    每条 convo 都是一个 list:
    [
      {"role": "user", "content": "Explain boolean operators."},
      {"role": "assistant", "content": "Boolean operators are ..."}
    ]

   tokenizer.apply_chat_template(...)把这轮对话按照 gemma-3 的 chat 格式拼接成文本
    【前面已经get_chat_template(tokenizer, chat_template="gemma-3") 设置好了】
   输出会是类似这样的字符串
        <bos><start_of_turn>user
        Explain boolean operators.<end_of_turn>
        <start_of_turn>assistant
        Boolean operators are ...

   '''
   return { "text" : texts, }
   '''
    给每条样本生成一个新的 "text" 字段,存放清理好的对话字符串。

    格式化后的 dataset 就能直接用于微调。
    '''

2.4 加载数据并应用格式化

python 复制代码
from datasets import load_dataset
dataset = load_dataset("repo_name/dataset_name", split = "train")

dataset = dataset.map(formatting_prompts_func, batched = True)
'''
Hugging Face Datasets 的 map 会对整个数据集执行上面的函数,生成一个新的 "text" 列。

原始的 "conversations" 仍然在,只是又多了 "text"。
'''

2.4.1 处理 ShareGPT 格式

如果数据集是 ShareGPT 格式 ("from" / "value"),而不是 ChatML 格式 ("role" / "content"),可以先用 standardize_sharegpt 转换

python 复制代码
from datasets import load_dataset
dataset = load_dataset("mlabonne/FineTome-100k", split = "train")


######################相比于ChatML多出来的部分######################
from unsloth.chat_templates import standardize_sharegpt
dataset = standardize_sharegpt(dataset)
#只有当你的目标数据集是 ShareGPT 格式,而模型需要的是 ChatML 格式 时,才需要使用 standardize_sharegpt 方法
######################相比于ChatML多出来的部分######################

dataset = dataset.map(formatting_prompts_func, batched = True)

3 其他问题

3.1 数据集需要多大

  • 一般建议数据集的最少规模为 100 条样本,这样微调才能得到基本可用的结果。
  • 如果要达到更理想的效果,1,000 条以上的数据集更为合适。
  • 通常情况下,数据越多,效果越好。
  • 不过,微调模型的效果主要取决于数据质量,所以一定要仔细清洗和准备数据。

3.2 如果我有多个数据集,该怎么办?

A: 如果你手头有多个数据集,可以选择:

  1. 统一所有数据集的格式 → 合并成一个数据集 → 在合并后的大数据集上进行微调。

  2. 使用 Multiple Datasets notebook,直接在多个数据集上进行微调。

3.3 我可以对同一个模型进行多次微调吗?

可以对已经微调过的模型再次进行微调,但最佳做法是:

  • 把所有数据集合并后,一次性完成微调。

原因是:

  • 对已微调过的模型再次训练,可能会改变之前已经学到的知识和效果。

4 其他(见文档)

多列微调、多轮对话微调、视觉微调

相关推荐
乐橙开放平台4 小时前
门店监控想集中看?乐橙含光支持多品牌摄像头跨店管理
网络·笔记·物联网·自动化·音视频·智能家居
深圳老胡4 小时前
STM32C5A3ZG开发板网络接口配置流程详解
笔记·stm32·单片机·代码规范
Z21-X4 小时前
云原生运维学习笔记:存储、网络与操作系统——云计算的底层基石
运维·笔记·学习·云原生
深圳老胡4 小时前
STM32C5A3ZG 开发板调试笔记:USB 复用 ST-Link 与工程生成警告说明
笔记·stm32·单片机·代码规范
职豚求职小程序6 小时前
易方达基金27秋招笔试|场次+考情全梳理
笔记
Swilderrr19 小时前
论文精读:《Directory-Aware Query and Maintenance in Vector Databases》
笔记·学习
SatanII19 小时前
K8s 存储与配置管理|Volume、ConfigMap、Secret 核心笔记
笔记·rpc·kubernetes
I'mChloe21 小时前
飞牛NAS部署flatnotes实战:Docker、8080端口、Markdown笔记与固定地址访问
笔记·docker·容器
库玛西21 小时前
外部排序全解析:败者树、置换-选择排序与最佳归并树
c语言·数据结构·c++·笔记·考研·算法
摇滚侠21 小时前
《Java并发编程之美》第 2 章 并发编程的其他基础知识 阅读笔记 3
android·java·笔记