Jay Glidden commited on
Upload train_multi_lora.py with huggingface_hub
Browse files- train_multi_lora.py +52 -0
train_multi_lora.py
ADDED
|
@@ -0,0 +1,52 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""Multi-LoRA trainer for Qwen3.5-0.8B. Trains one role at a time."""
|
| 3 |
+
|
| 4 |
+
import json, os, sys, torch, argparse
|
| 5 |
+
from pathlib import Path
|
| 6 |
+
from datasets import Dataset
|
| 7 |
+
from transformers import AutoModelForCausalLM, AutoTokenizer, TrainingArguments, Trainer, DataCollatorForLanguageModeling, BitsAndBytesConfig
|
| 8 |
+
from peft import LoraConfig, get_peft_model, TaskType
|
| 9 |
+
|
| 10 |
+
BASE = "Jackrong/Qwen3.5-0.8B-Claude-4.6-Opus-Reasoning-Distilled"
|
| 11 |
+
R, ALPHA, DROPOUT = 16, 32, 0.05
|
| 12 |
+
MAX_LEN, BATCH, GRAD, EPOCHS = 512, 4, 8, 5
|
| 13 |
+
LR, WD = 1e-4, 0.01
|
| 14 |
+
|
| 15 |
+
def fmt(row):
|
| 16 |
+
parts = []
|
| 17 |
+
if row.get("system"): parts.append(f"<|im_start|>system\n{row['system']}<|im_end|>")
|
| 18 |
+
for m in row.get("messages", []):
|
| 19 |
+
parts.append(f"<|im_start|>{m['role']}\n{m['content']}<|im_end|>")
|
| 20 |
+
return "\n".join(parts)
|
| 21 |
+
|
| 22 |
+
def train(data_dir, output_dir, dry=False):
|
| 23 |
+
train_rows = [json.loads(l) for l in open(Path(data_dir)/"train.jsonl") if l.strip()]
|
| 24 |
+
val_rows = [json.loads(l) for l in open(Path(data_dir)/"val.jsonl") if l.strip()] if (Path(data_dir)/"val.jsonl").exists() else []
|
| 25 |
+
|
| 26 |
+
tok = AutoTokenizer.from_pretrained(BASE, trust_remote_code=True)
|
| 27 |
+
if tok.pad_token is None: tok.pad_token = tok.eos_token
|
| 28 |
+
|
| 29 |
+
train_enc = tok([fmt(r) for r in train_rows], truncation=True, max_length=MAX_LEN, padding=True, return_tensors="pt")
|
| 30 |
+
val_enc = tok([fmt(r) for r in val_rows], truncation=True, max_length=MAX_LEN, padding=True, return_tensors="pt") if val_rows else None
|
| 31 |
+
|
| 32 |
+
print(f"{Path(data_dir).name}: {len(train_rows)} train / {len(val_rows)} val")
|
| 33 |
+
if dry: return
|
| 34 |
+
|
| 35 |
+
model = AutoModelForCausalLM.from_pretrained(BASE, quantization_config=BitsAndBytesConfig(load_in_4bit=True, bnb_4bit_compute_dtype=torch.bfloat16, bnb_4bit_use_double_quant=True), device_map="auto", trust_remote_code=True, torch_dtype=torch.bfloat16)
|
| 36 |
+
model = get_peft_model(model, LoraConfig(r=R, lora_alpha=ALPHA, lora_dropout=DROPOUT, target_modules=["q_proj","k_proj","v_proj","o_proj","gate_proj","up_proj","down_proj"], task_type=TaskType.CAUSAL_LM))
|
| 37 |
+
model.print_trainable_parameters()
|
| 38 |
+
|
| 39 |
+
args = TrainingArguments(output_dir=output_dir, per_device_train_batch_size=BATCH, per_device_eval_batch_size=BATCH, gradient_accumulation_steps=GRAD, num_train_epochs=EPOCHS, learning_rate=LR, lr_scheduler_type="cosine", warmup_ratio=0.1, weight_decay=WD, logging_steps=20, save_strategy="epoch", eval_strategy="epoch" if val_rows else "no", bf16=True, report_to="none", save_total_limit=5, load_best_model_at_end=True if val_rows else False)
|
| 40 |
+
|
| 41 |
+
Trainer(model=model, args=args, train_dataset=Dataset.from_dict(train_enc), eval_dataset=Dataset.from_dict(val_enc) if val_enc else None, data_collator=DataCollatorForLanguageModeling(tok, mlm=False)).train()
|
| 42 |
+
|
| 43 |
+
model.save_pretrained(Path(output_dir)/"final")
|
| 44 |
+
tok.save_pretrained(Path(output_dir)/"final")
|
| 45 |
+
|
| 46 |
+
if __name__ == "__main__":
|
| 47 |
+
p = argparse.ArgumentParser()
|
| 48 |
+
p.add_argument("--data", required=True)
|
| 49 |
+
p.add_argument("--output", default="lora-output")
|
| 50 |
+
p.add_argument("--dry", action="store_true")
|
| 51 |
+
a = p.parse_args()
|
| 52 |
+
train(a.data, a.output, a.dry)
|