You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Llama2(SFT+LoRA)微调时DataCollatorForCompletionOnlyLM模板配置指导

解决DataCollatorForCompletionOnlyLM无法找到响应模板的问题

问题根源

你的错误是因为设置的response_template分词后的token序列,在输入样本的token IDs中不存在或匹配失败,核心原因是模板与数据集中的响应起始标记不匹配,以及对Llama2格式的响应边界定位错误。

正确配置方案

1. 准确定位响应边界

你的数据集格式中,模型的响应部分是[/INST] (注意后面的空格)之后的内容(即示例中的D),而非Answer: [/INST]。Answer: [/INST]属于用户指令的结尾,不是响应的起始标记。

2. 正确设置response_template

将response_template设置为[/INST] (包含[/INST]后的空格),确保与数据集中的格式完全匹配:

response_template = "[/INST] "
collator = DataCollatorForCompletionOnlyLM(
    response_template=response_template,
    tokenizer=tokenizer,
    mlm=False
)

3. 验证分词匹配度

手动验证模板的分词结果与样本中的token序列是否一致,避免格式差异:

# 编码模板,不添加特殊令牌
template_tokens = tokenizer.encode(response_template, add_special_tokens=False)
print("模板的Token IDs:", template_tokens)

# 编码一条样本的文本,查看是否包含该序列
sample_text = "<s>[INST] \n<<SYS>> Please select the correct answer from the given multiple Options based on the given Context: <</SYS>>  \n Context: Abrasion is another type of mechanical weathering...  \n Question: Gravity causes erosion by all of the following except  \\ \n Options:(A) glaciers (B) moving air (C) flowing water (D) mass movement  \n Answer: [/INST] D </s>"
sample_tokens = tokenizer.encode(sample_text, add_special_tokens=False)

# 检查模板序列是否存在于样本token中
if template_tokens in [sample_tokens[i:i+len(template_tokens)] for i in range(len(sample_tokens)-len(template_tokens)+1)]:
    print("模板序列匹配成功")
else:
    print("模板序列不匹配,请检查数据集格式")

4. 确保数据集格式统一

所有样本必须严格遵循相同格式:

  • Answer: [/INST]后必须紧跟一个空格,再是答案(如D)
  • 避免额外的换行、空格或特殊字符

为什么之前的配置失败?

  • 方式一设置的instruction_template和response_template都偏离了实际的响应边界,Answer: [/INST]属于指令部分,不是响应起始。
  • 方式二的response_template缺少[/INST]后的空格,导致分词序列与样本中的实际token不匹配,触发找不到响应键的错误。

内容的提问来源于stack exchange,提问作者Sosy

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.06 08:45:07