File size: 8,281 Bytes
e120038
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
# -*- 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)