bio-expert / scripts /train_round2.py
andyz321's picture
Upload scripts/train_round2.py with huggingface_hub
e120038 verified
Raw History Blame Contribute Delete
8.28 kB
# -*- coding: utf-8 -*-
"""Round 2 训练:领域知识 + 身份认同 + 好奇心(多轮)。
两阶段:
stage1 领域 SFT —— round1 全量数据(555),建立领域能力
stage2 身份+好奇微调 —— round1 抽样 + round2 全量,身份过采样 xN
用法:
venv\\Scripts\\python.exe scripts\\train_round2.py --stage 1
venv\\Scripts\\python.exe scripts\\train_round2.py --stage 2
"""
import argparse
import glob
import json
import os
import random
from pathlib import Path
ROOT = Path(__file__).resolve().parent.parent
os.chdir(ROOT)
MODEL_DIR = ROOT / "models" / "Qwen3-8B"
ROUND1_GLOB = str(ROOT / "data" / "sft" / "bio_domain_v1_*.jsonl")
ROUND2_GLOB = str(ROOT / "data" / "sft" / "bio_domain_v2_*.jsonl")
OUT_ROOT = ROOT / "output"
IDENTITY_OVERSAMPLE = 3 # 身份样本过采样倍数(round3: 6->3,降低领域稀释)
CURIOSITY_OVERSAMPLE = 3 # 好奇样本过采样倍数(round3 新增)
ROUND1_RESAMPLE_STAGE2 = 0.35 # stage2 里保留的 round1 比例(防止遗忘领域能力)
import sys as _sys
_sys.path.insert(0, str(ROOT / "scripts"))
from prompt import SYSTEM_PROMPT # noqa: E402
max_seq_length = 2048
r = 32
lora_alpha = 32
learning_rate = 2e-4
per_device_batch = 2
grad_accum = 4
ap = argparse.ArgumentParser()
ap.add_argument("--stage", type=int, default=0, choices=[0, 1, 2, 3],
help="0=单阶段混合 1=仅领域 2=身份+好奇 3=round3 微调(裸问法版)")
ap.add_argument("--epochs", type=float, default=None)
ap.add_argument("--resume", default=None)
ap.add_argument("--init-adapter", default=None,
help="从已有 adapter 目录继续训(不是 checkpoint 断点)")
args = ap.parse_args()
random.seed(3407)
# ------------------------------------------------------------------ 读数据
def read_jsonl(path):
rows = []
with open(path, encoding="utf-8") as f:
for line in f:
line = line.strip()
if line:
try:
rows.append(json.loads(line))
except Exception:
pass
return rows
def collect():
"""返回 (stage1_rows, stage2_rows)。每行含 instruction/output 或 messages。"""
r1_files = sorted(glob.glob(ROUND1_GLOB))
r2_files = sorted(glob.glob(ROUND2_GLOB))
print(f"round1 files: {len(r1_files)}, round2 files: {len(r2_files)}", flush=True)
r1 = []
for p in r1_files:
r1.extend(read_jsonl(p))
r2 = []
for p in r2_files:
r2.extend(read_jsonl(p))
def split_by_slice(rows):
ident = [x for x in rows if x.get("_slice") == "identity"]
other = [x for x in rows if x.get("_slice") != "identity"]
return ident, other
r2_ident, r2_other = split_by_slice(r2)
r1_ident = [x for x in r1 if x.get("_slice") == "identity"]
r1_other = [x for x in r1 if x.get("_slice") != "identity"]
# stage0 = 单阶段混合:领域全量 + 身份过采样 + 好奇过采样
stage0 = []
stage0.extend(r1_other)
stage0.extend(r2_ident * IDENTITY_OVERSAMPLE)
stage0.extend(r2_other * CURIOSITY_OVERSAMPLE)
random.shuffle(stage0)
stage1 = [x for x in r1 if x.get("instruction") and x.get("output")]
# stage2:身份过采样 + 好奇过采样 + round1 领域抽样(防遗忘)
stage2 = []
stage2.extend(r2_ident * IDENTITY_OVERSAMPLE)
stage2.extend(r2_other * CURIOSITY_OVERSAMPLE)
keep = int(len(r1_other) * ROUND1_RESAMPLE_STAGE2)
stage2.extend(random.sample(r1_other, keep))
random.shuffle(stage2)
print(f"stage0 rows={len(stage0)} (r1 {len(r1_other)} + identity {len(r2_ident)}x{IDENTITY_OVERSAMPLE} "
f"+ r2_other {len(r2_other)}x{CURIOSITY_OVERSAMPLE})", flush=True)
print(f"stage1 rows={len(stage1)} stage2 rows={len(stage2)}", flush=True)
return stage0, stage1, stage2
stage0_rows, stage1_rows, stage2_rows = collect()
# stage3 = round3 微调:从 checkpoint-210 继续,领域全量 + 身份3x + 好奇3x(裸问法版)
stage3 = []
stage3.extend([x for x in stage0_rows if x.get("_slice") != "identity" or True])
rows = {0: stage0_rows, 1: stage1_rows, 2: stage2_rows, 3: stage3}[args.stage]
num_epochs = args.epochs if args.epochs is not None else (2 if args.stage == 0 else (3 if args.stage == 1 else 2))
OUT_DIR = OUT_ROOT / ("round2_mixed" if args.stage == 0 else f"round2_stage{args.stage}")
OUT_DIR.mkdir(parents=True, exist_ok=True)
# ------------------------------------------------------------------ 训练
from unsloth import FastLanguageModel # noqa: E402
import torch # noqa: E402
from trl import SFTTrainer # noqa: E402
from transformers import TrainingArguments # noqa: E402
print(f"CUDA: {torch.cuda.is_available()} | GPU: {torch.cuda.get_device_name(0) if torch.cuda.is_available() else 'n/a'}", flush=True)
model, tokenizer = FastLanguageModel.from_pretrained(
model_name=str(MODEL_DIR),
max_seq_length=max_seq_length,
dtype=None,
load_in_4bit=True,
)
model = FastLanguageModel.get_peft_model(
model,
r=r,
target_modules=["q_proj", "k_proj", "v_proj", "o_proj", "gate_proj", "up_proj", "down_proj"],
lora_alpha=lora_alpha,
lora_dropout=0,
bias="none",
use_gradient_checkpointing="unsloth",
random_state=3407,
use_rslora=False,
loftq_config=None,
)
if args.init_adapter:
from peft import PeftModel # noqa: E402
print(f"loading init adapter: {args.init_adapter}", flush=True)
model = PeftModel.from_pretrained(model, args.init_adapter, is_trainable=True)
print("INIT_ADAPTER_LOADED", flush=True)
print("PEFT ready", flush=True)
def formatting_func(examples):
"""兼容两种入参:
- Unsloth 初始化探针传的是单个样本(dict of scalars)
- 真正训练时传的是 batch(列 -> list)
"""
inst = examples["instruction"]
if isinstance(inst, str):
inst = [inst]
out = [examples["output"]]
raw_tail = examples.get("_messages_tail")
tail = [raw_tail] if raw_tail else [None]
else:
out = examples["output"]
tail = examples.get("_messages_tail") or [None] * len(inst)
texts = []
for i in range(len(inst)):
msgs = [
{"role": "system", "content": SYSTEM_PROMPT},
{"role": "user", "content": inst[i]},
{"role": "assistant", "content": out[i]},
]
t = tail[i] if i < len(tail) else None
if t:
for m in t:
msgs.append(m)
texts.append(tokenizer.apply_chat_template(
msgs, tokenize=False, add_generation_prompt=False,
))
return texts
from datasets import Dataset # noqa: E402
# 统一成 HF Dataset,保留 _messages_tail 列
cols = ["instruction", "output", "_messages_tail"]
norm = []
for x in rows:
norm.append({
"instruction": x["instruction"],
"output": x["output"],
"_messages_tail": x.get("_messages_tail") or [],
})
dataset = Dataset.from_list(norm)
print(f"dataset: {len(dataset)} rows", flush=True)
use_bf16 = torch.cuda.is_available() and torch.cuda.is_bf16_supported()
trainer = SFTTrainer(
model=model,
tokenizer=tokenizer,
train_dataset=dataset,
formatting_func=formatting_func,
args=TrainingArguments(
per_device_train_batch_size=per_device_batch,
gradient_accumulation_steps=grad_accum,
warmup_steps=5,
num_train_epochs=num_epochs,
learning_rate=learning_rate,
fp16=not use_bf16,
bf16=use_bf16,
logging_steps=1,
optim="adamw_8bit",
weight_decay=0.01,
lr_scheduler_type="linear",
seed=3407,
output_dir=str(OUT_DIR),
report_to="none",
save_strategy="steps",
save_steps=30,
save_total_limit=6,
),
)
print(f"=== stage{args.stage} 开始训练 ({len(dataset)} rows, {num_epochs} epochs) ===", flush=True)
if args.resume:
print(f"resume from {args.resume}", flush=True)
trainer.train(resume_from_checkpoint=args.resume)
else:
trainer.train()
model.save_pretrained(str(OUT_DIR / "adapter"))
tokenizer.save_pretrained(str(OUT_DIR / "adapter"))
print(f"adapter -> {OUT_DIR / 'adapter'}", flush=True)
print("TRAIN_DONE", flush=True)