Download colab_train_intent_router.py from ejarbe/manus-training-data: direct link, hf CLI and curl.
- Browser
- Download file 11.3 kB
-
https://huggingface.co/datasets/ejarbe/manus-training-data/resolve/main/colab_train_intent_router.py
- Command line
-
hf download hf://datasets/ejarbe/manus-training-data/colab_train_intent_router.py
-
curl -L -o colab_train_intent_router.py https://huggingface.co/datasets/ejarbe/manus-training-data/resolve/main/colab_train_intent_router.py
11.3 kB
| #!/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) | |