# 包装思维链数据 -> Qwen3 thinking 格式训练语料
# 输入: NuminaMath(数学CoT) + OpenThoughts(通用reasoning/solution分离) + fineweb(通用文本)
# 输出: 统一 Qwen3 chat+thinking 格式的 jsonl, 按 4:4:2 混合
# 格式: <|im_start|>user\n{problem}<|im_end|>\n<|im_start|>assistant\n\n{reasoning}\n\n\n{solution}<|im_end|>
import json, sys, glob
import pandas as pd
OUT = '/root/autodl-tmp/data/cot_mix_v1.jsonl'
N_MATH = 4000 # 数学思维链条数
N_GENERAL = 4000 # 通用思维链条数
N_TEXT = 2000 # 通用文本条数
def qwen3_thinking(problem, reasoning, solution):
return (f'<|im_start|>user\n{problem}<|im_end|>\n'
f'<|im_start|>assistant\n\n{reasoning}\n\n\n{solution}<|im_end|>')
def extract_boxed(sol):
"""括号配对提取最后一个 \boxed{...} 的完整内容(支持嵌套)。"""
i = sol.rfind('\\boxed{')
if i == -1:
return None, sol
j = i + len('\\boxed{')
depth = 1
k = j
while k < len(sol) and depth > 0:
if sol[k] == '{':
depth += 1
elif sol[k] == '}':
depth -= 1
k += 1
if depth != 0:
return None, sol
boxed = sol[i:k] # 完整 \boxed{...}
reasoning = sol[:i].strip()
return boxed, reasoning
def wrap_numinamath(df):
"""NuminaMath: solution 是完整解答(推理+答案),整体当 think,末尾 boxed 当答案。"""
out = []
for _, r in df.iterrows():
sol = str(r['solution']).strip()
boxed, reasoning = extract_boxed(sol)
answer = boxed if boxed else sol.split('\n')[-1].strip()
out.append(qwen3_thinking(str(r['problem']).strip(), reasoning, answer))
return out
def wrap_openthoughts(df):
"""OpenThoughts: deepseek_reasoning(think) + deepseek_solution(答案) 已分离。"""
out = []
for _, r in df.iterrows():
out.append(qwen3_thinking(
str(r['problem']).strip(),
str(r['deepseek_reasoning']).strip(),
str(r['deepseek_solution']).strip()))
return out
def main():
docs = []
# 1. 数学思维链: NuminaMath 第一个分片
nm = pd.read_parquet('/root/autodl-tmp/data/numinamath-cot/data/train-00000-of-00005.parquet')
nm = nm.head(N_MATH)
docs += wrap_numinamath(nm)
print(f'数学思维链: {N_MATH} 条', flush=True)
# 2. 通用思维链: OpenThoughts 后3分片, 筛 science+puzzle(排除 math/code)
gen = []
for f in sorted(glob.glob('/root/autodl-tmp/data/openthoughts/metadata/t[0-9]*.parquet')):
df = pd.read_parquet(f)
df = df[df['domain'].isin(['biology', 'physics', 'chemistry', 'puzzle'])]
gen.append(df)
if gen:
gen = pd.concat(gen).head(N_GENERAL)
docs += wrap_openthoughts(gen)
print(f'通用思维链: {len(gen)} 条', flush=True)
# 3. 通用文本: 从 mix_v1 里取(它含 30% fineweb + 20% 中文)
txt = []
for l in open('/root/autodl-tmp/data/mix_v1.jsonl'):
txt.append(json.loads(l)['text'])
if len(txt) >= N_TEXT:
break
docs += txt
print(f'通用文本: {len(txt)} 条', flush=True)
# 打乱前:过滤超长样本(思维链数据长尾,>1536 token 丢弃)
from transformers import AutoTokenizer
tok = AutoTokenizer.from_pretrained('/root/autodl-tmp/models/Qwen/Qwen3-4B')
MAX_TOK = 1536
docs = [d for d in docs if len(tok(d)['input_ids']) <= MAX_TOK]
print(f'过滤后 {len(docs)} 条(<= {MAX_TOK} token)', flush=True)
# 打乱 + 写盘
import random
random.seed(0)
random.shuffle(docs)
with open(OUT, 'w') as f:
for d in docs:
f.write(json.dumps({'text': d}, ensure_ascii=False) + '\n')
print(f'总计 {len(docs)} 条 -> {OUT}', flush=True)
if __name__ == '__main__':
main()