File size: 11,288 Bytes
c7b482b | 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 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 | #!/usr/bin/env python3
"""
Intent Router Training — Cloud GPU (Colab T4 / CUDA)
Self-contained script for fine-tuning Qwen2.5-0.5B with LoRA on 14 intent
categories. Loads data from HuggingFace, trains with early stopping,
merges the adapter, pushes the merged model, and prints per-category eval.
Usage (Colab):
!python colab_train_intent_router.py
Environment:
HF_TOKEN — HuggingFace write token (or call huggingface_hub.login())
"""
import os
import subprocess
import sys
# ---------------------------------------------------------------------------
# 1. Install dependencies (idempotent — skips if already present)
# ---------------------------------------------------------------------------
subprocess.check_call(
[
sys.executable, "-m", "pip", "install", "-q",
"transformers>=4.44",
"peft>=0.12",
"trl>=0.9",
"datasets",
"huggingface_hub",
"accelerate",
"torch",
]
)
import torch # noqa: E402
from collections import Counter # noqa: E402
from datasets import load_dataset # noqa: E402
from huggingface_hub import login # noqa: E402
from peft import LoraConfig, PeftConfig, PeftModel # noqa: E402
from transformers import ( # noqa: E402
AutoModelForCausalLM,
AutoTokenizer,
EarlyStoppingCallback,
TrainerCallback,
)
from trl import SFTConfig, SFTTrainer # noqa: E402
# ---------------------------------------------------------------------------
# 2. HuggingFace authentication
# ---------------------------------------------------------------------------
HF_TOKEN = os.environ.get("HF_TOKEN")
if HF_TOKEN:
login(token=HF_TOKEN)
else:
print("HF_TOKEN not set — attempting interactive login...")
login()
# ---------------------------------------------------------------------------
# 3. Constants
# ---------------------------------------------------------------------------
MODEL_NAME = "Qwen/Qwen2.5-0.5B"
HF_DATASET = "ejarbe/manus-training-data"
TRAIN_FILE = "intent_train_v11.jsonl"
EVAL_FILE = "intent_eval_v10.jsonl"
OUTPUT_DIR = "manus-intent-router-cloud"
HF_MODEL_REPO = "ejarbe/manus-intent-router"
print("=" * 80)
print("MANUS INTENT ROUTER TRAINING — CLOUD GPU (CUDA)")
print("=" * 80)
device = "cuda" if torch.cuda.is_available() else "cpu"
print(f"Model : {MODEL_NAME}")
print(f"Device : {device} ({torch.cuda.get_device_name(0) if device == 'cuda' else 'N/A'})")
print(f"Dataset : {HF_DATASET}")
print(f"Train file : {TRAIN_FILE}")
print(f"Eval file : {EVAL_FILE}")
print(f"Output dir : {OUTPUT_DIR}")
print(f"Push target : {HF_MODEL_REPO}")
print("=" * 80)
if device != "cuda":
print("WARNING: CUDA not available. Training will be slow on CPU.")
# ---------------------------------------------------------------------------
# 4. NanGradientGuard callback (safety net — zeroes NaN/Inf grads)
# ---------------------------------------------------------------------------
class NanGradientGuard(TrainerCallback):
"""Zero out NaN/Inf gradients before optimizer step."""
def on_pre_optimizer_step(self, args, state, control, model=None, **kwargs):
if model is None:
return
nan_count = 0
for name, param in model.named_parameters():
if param.grad is not None:
bad = torch.isnan(param.grad) | torch.isinf(param.grad)
if bad.any():
nan_count += bad.sum().item()
param.grad = torch.where(
bad, torch.zeros_like(param.grad), param.grad
)
if nan_count > 0:
print(
f" [NanGuard] Step {state.global_step}:"
f" zeroed {nan_count} NaN/Inf gradient elements"
)
# ---------------------------------------------------------------------------
# 5. Load datasets from HuggingFace
# ---------------------------------------------------------------------------
print("\nLoading datasets from HuggingFace...")
ds = load_dataset(
HF_DATASET,
data_files={"train": TRAIN_FILE, "eval": EVAL_FILE},
)
train_dataset = ds["train"]
eval_dataset = ds["eval"]
print(f" Train : {len(train_dataset)} examples")
print(f" Eval : {len(eval_dataset)} examples")
# ---------------------------------------------------------------------------
# 6. LoRA config
# ---------------------------------------------------------------------------
print("\nConfiguring LoRA (r=16, alpha=32, q_proj + v_proj)...")
peft_config = LoraConfig(
r=16,
lora_alpha=32,
target_modules=["q_proj", "v_proj"],
lora_dropout=0.05,
bias="none",
task_type="CAUSAL_LM",
)
# ---------------------------------------------------------------------------
# 7. Training config — CUDA-optimized, eval + early stopping
# ---------------------------------------------------------------------------
print("\nConfiguring training (CUDA, eval every 100 steps, early stopping patience=3)...")
training_args = SFTConfig(
output_dir=OUTPUT_DIR,
num_train_epochs=5,
per_device_train_batch_size=8,
gradient_accumulation_steps=2, # Effective batch size = 16
gradient_checkpointing=True,
learning_rate=2e-5,
lr_scheduler_type="cosine",
warmup_ratio=0.1,
optim="adamw_torch",
logging_steps=10,
logging_first_step=True,
eval_strategy="steps",
eval_steps=100,
save_strategy="steps",
save_steps=100,
save_total_limit=5,
load_best_model_at_end=True,
metric_for_best_model="eval_loss",
greater_is_better=False,
push_to_hub=False,
report_to="none",
run_name="manus-intent-router-cloud",
bf16=torch.cuda.is_available() and torch.cuda.is_bf16_supported(),
fp16=False,
dataloader_num_workers=2,
)
effective_batch = (
training_args.per_device_train_batch_size
* training_args.gradient_accumulation_steps
)
total_steps = len(train_dataset) // effective_batch * int(training_args.num_train_epochs)
print(f" Effective batch size : {effective_batch}")
print(f" Max training steps : {total_steps}")
print(f" Eval every : {training_args.eval_steps} steps")
print(f" Early stopping : patience=3 on eval_loss")
# ---------------------------------------------------------------------------
# 8. Train
# ---------------------------------------------------------------------------
print("\nInitializing SFT trainer...")
trainer = SFTTrainer(
model=MODEL_NAME,
train_dataset=train_dataset,
eval_dataset=eval_dataset,
peft_config=peft_config,
args=training_args,
callbacks=[
NanGradientGuard(),
EarlyStoppingCallback(early_stopping_patience=3),
],
)
print("\nStarting training...")
print("=" * 80)
trainer.train()
print("\nSaving best adapter checkpoint...")
trainer.save_model()
# ---------------------------------------------------------------------------
# 9. Merge LoRA adapter into base model
# ---------------------------------------------------------------------------
print("\n" + "=" * 80)
print("MERGING LoRA adapter into base model...")
print("=" * 80)
peft_cfg = PeftConfig.from_pretrained(OUTPUT_DIR)
base_model = AutoModelForCausalLM.from_pretrained(
peft_cfg.base_model_name_or_path,
torch_dtype=torch.float32,
device_map="cpu",
)
tokenizer = AutoTokenizer.from_pretrained(OUTPUT_DIR)
model_with_lora = PeftModel.from_pretrained(base_model, OUTPUT_DIR)
merged_model = model_with_lora.merge_and_unload()
MERGED_DIR = f"{OUTPUT_DIR}-merged"
print(f"Saving merged model to {MERGED_DIR}...")
merged_model.save_pretrained(MERGED_DIR)
tokenizer.save_pretrained(MERGED_DIR)
param_count = sum(p.numel() for p in merged_model.parameters())
print(f"Merged model parameters: {param_count:,}")
# ---------------------------------------------------------------------------
# 10. Push merged model to HuggingFace
# ---------------------------------------------------------------------------
print(f"\nPushing merged model to {HF_MODEL_REPO}...")
merged_model.push_to_hub(HF_MODEL_REPO, commit_message="Cloud-trained merged model (v11 data)")
tokenizer.push_to_hub(HF_MODEL_REPO, commit_message="Cloud-trained merged model (v11 data)")
print("Push complete.")
# ---------------------------------------------------------------------------
# 11. Per-category evaluation
# ---------------------------------------------------------------------------
print("\n" + "=" * 80)
print("PER-CATEGORY EVALUATION")
print("=" * 80)
# Move merged model to GPU for fast inference
eval_model = merged_model.to(device)
eval_model.eval()
eval_tokenizer = tokenizer
# Extract ground-truth labels from eval dataset
# Training data format: {"text": "<system>...<user>query<assistant>LABEL"}
correct = 0
total = 0
per_cat_correct = Counter()
per_cat_total = Counter()
print(f"Evaluating on {len(eval_dataset)} examples...")
for i, example in enumerate(eval_dataset):
text = example["text"]
# Split on <|im_start|>assistant to get the prompt and expected label
if "<|im_start|>assistant" in text:
prompt_part = text.split("<|im_start|>assistant")[0] + "<|im_start|>assistant\n"
expected = text.split("<|im_start|>assistant\n")[-1].strip()
# Remove trailing <|im_end|> if present
expected = expected.replace("<|im_end|>", "").strip()
else:
continue
# Generate prediction
inputs = eval_tokenizer(prompt_part, return_tensors="pt", truncation=True, max_length=512)
inputs = {k: v.to(device) for k, v in inputs.items()}
with torch.no_grad():
outputs = eval_model.generate(
**inputs,
max_new_tokens=20,
do_sample=False,
temperature=1.0,
pad_token_id=eval_tokenizer.eos_token_id,
)
# Decode only the new tokens
generated = eval_tokenizer.decode(
outputs[0][inputs["input_ids"].shape[1]:], skip_special_tokens=True
).strip()
# Compare (first line only, case-insensitive)
predicted = generated.split("\n")[0].strip().lower()
expected_lower = expected.lower()
per_cat_total[expected_lower] += 1
if predicted == expected_lower:
correct += 1
per_cat_correct[expected_lower] += 1
total += 1
if (i + 1) % 200 == 0:
print(f" Evaluated {i + 1}/{len(eval_dataset)} (running acc: {correct / total:.1%})")
# Print results
print("\n" + "-" * 60)
print(f"{'Category':<35} {'Correct':>8} {'Total':>8} {'Accuracy':>10}")
print("-" * 60)
for cat in sorted(per_cat_total.keys()):
c = per_cat_correct[cat]
t = per_cat_total[cat]
acc = c / t if t > 0 else 0.0
print(f"{cat:<35} {c:>8} {t:>8} {acc:>9.1%}")
print("-" * 60)
overall_acc = correct / total if total > 0 else 0.0
print(f"{'OVERALL':<35} {correct:>8} {total:>8} {overall_acc:>9.1%}")
print("=" * 80)
# ---------------------------------------------------------------------------
# 12. Summary
# ---------------------------------------------------------------------------
print("\nTRAINING COMPLETE")
print(f" Merged model pushed to: https://huggingface.co/{HF_MODEL_REPO}")
print(f" Overall eval accuracy : {overall_acc:.1%}")
print(f" Target : 80%")
print(f" {'PASS' if overall_acc >= 0.80 else 'BELOW TARGET — may need more epochs or data'}")
print("=" * 80)
|