""" LoRA fine-tuning script for the Echo Flow transcript-cleanup model. Supports three backends: - CUDA + bitsandbytes (QLoRA, 4-bit) - the production target on a cloud GPU - Apple Silicon MPS or CPU (full-precision LoRA) - for local smoke tests - CPU-only (full-precision LoRA) - slowest fallback Usage: python scripts/train_lora.py --config configs/lora_qwen2.5_0.5b.yaml python scripts/train_lora.py --config configs/lora_qwen2.5_0.5b.yaml --device cpu """ import argparse import json import os import platform import random import sys from pathlib import Path import torch import yaml from datasets import Dataset from peft import LoraConfig, get_peft_model from transformers import ( AutoModelForCausalLM, AutoTokenizer, DataCollatorForSeq2Seq, TrainerCallback, TrainingArguments, ) from trl import SFTConfig, SFTTrainer class LoggingCallback(TrainerCallback): def on_log(self, args, state, control, logs=None, **kwargs): if logs: print(f"Step {state.global_step}: {logs}") def load_config(path: Path) -> dict: with path.open("r", encoding="utf-8") as f: return yaml.safe_load(f) def load_jsonl(path: Path) -> list[dict]: rows = [] with path.open("r", encoding="utf-8") as f: for line in f: line = line.strip() if not line: continue rows.append(json.loads(line)) return rows def format_messages(tokenizer, messages: list[dict]) -> str: return tokenizer.apply_chat_template(messages, tokenize=False, add_generation_prompt=False) def detect_device(requested: str | None) -> tuple[str, dict]: """Returns (device, runtime_options).""" if requested: return requested, {} if torch.cuda.is_available(): return "cuda", {"quantize": True, "bf16": True, "optim": "paged_adamw_8bit"} if hasattr(torch.backends, "mps") and torch.backends.mps.is_available(): return "mps", {"quantize": False, "bf16": False, "optim": "adamw_torch"} return "cpu", {"quantize": False, "bf16": False, "optim": "adamw_torch"} def main(): parser = argparse.ArgumentParser(description="LoRA fine-tune transcript cleanup model") parser.add_argument("--config", type=Path, default=Path("configs/lora_qwen2.5_0.5b.yaml")) parser.add_argument("--device", choices=["cuda", "mps", "cpu"], default=None) parser.add_argument("--dry-run", action="store_true", help="Verify setup without training") args = parser.parse_args() cfg = load_config(args.config) random.seed(cfg.get("seed", 42)) output_dir = Path(cfg["output_dir"]) output_dir.mkdir(parents=True, exist_ok=True) device, runtime_opts = detect_device(args.device) use_quantization = runtime_opts["quantize"] use_bf16 = runtime_opts["bf16"] optim_name = runtime_opts["optim"] print(f"Platform: {platform.platform()}") print(f"Device: {device}") print(f"Quantize: {use_quantization} bf16: {use_bf16} optim: {optim_name}") if use_quantization: try: from transformers import BitsAndBytesConfig bnb_config = BitsAndBytesConfig( load_in_4bit=True, bnb_4bit_quant_type="nf4", bnb_4bit_compute_dtype=torch.bfloat16, bnb_4bit_use_double_quant=True, ) except Exception as exc: print(f"Failed to build BitsAndBytesConfig: {exc}") print("Falling back to full precision.") use_quantization = False bnb_config = None else: bnb_config = None model_id = cfg["model_id"] print(f"Loading tokenizer and model: {model_id}") tokenizer = AutoTokenizer.from_pretrained(model_id, trust_remote_code=True) if tokenizer.pad_token is None: tokenizer.pad_token = tokenizer.eos_token model_kwargs = dict( trust_remote_code=True, ) if use_quantization: model_kwargs["quantization_config"] = bnb_config model_kwargs["device_map"] = "auto" model_kwargs["torch_dtype"] = torch.bfloat16 else: # On CPU/MPS, keep full precision (float16 has issues on MPS, bfloat16 not always supported) model_kwargs["torch_dtype"] = torch.float32 model = AutoModelForCausalLM.from_pretrained(model_id, **model_kwargs) if use_quantization: from peft import prepare_model_for_kbit_training model = prepare_model_for_kbit_training(model) if device == "mps": model = model.to("mps") elif device == "cpu": model = model.to("cpu") lora_config = LoraConfig( r=cfg["lora_r"], lora_alpha=cfg["lora_alpha"], target_modules=cfg["lora_target_modules"], lora_dropout=cfg.get("lora_dropout", 0.05), bias="none", task_type="CAUSAL_LM", ) model = get_peft_model(model, lora_config) if hasattr(model, "enable_input_require_grads"): model.enable_input_require_grads() # Disable KV cache during training (incompatible with grad checkpointing + LoRA) try: model.config.use_cache = False except Exception: pass if hasattr(model, "gradient_checkpointing_enable"): try: model.gradient_checkpointing_enable( gradient_checkpointing_kwargs={"use_reentrant": False} ) except Exception: try: model.gradient_checkpointing_enable() except Exception: pass model.print_trainable_parameters() train_path = Path(cfg["train_dataset"]) if not train_path.exists(): print(f"Training dataset not found: {train_path}") sys.exit(1) train_rows = load_jsonl(train_path) if cfg.get("max_samples"): train_rows = train_rows[: cfg["max_samples"]] print(f"Loaded {len(train_rows)} training rows from {train_path}") eval_path = Path(cfg["eval_dataset"]) if cfg.get("eval_dataset") else None eval_rows = [] if eval_path and eval_path.exists(): eval_rows = load_jsonl(eval_path) print(f"Loaded {len(eval_rows)} eval rows from {eval_path}") def to_text(row): return {"text": format_messages(tokenizer, row["messages"])} train_dataset = Dataset.from_list([to_text(r) for r in train_rows]) eval_dataset = ( Dataset.from_list([to_text(r) for r in eval_rows]) if eval_rows else None ) # Debug: print a sample to verify formatting print("\n--- Sample training text ---") print(train_dataset[0]["text"][:500]) print("--- End sample ---\n") # On CPU/MPS, drop batch size and gradient accumulation to a tiny number # to keep memory bounded. The full training run should happen on a GPU. if device in ("cpu", "mps"): per_device_batch_size = 1 grad_accum = 8 print(f"[{device}] Forcing per_device_batch_size=1, grad_accum=8 to fit memory") else: per_device_batch_size = cfg.get("per_device_batch_size", 4) grad_accum = cfg.get("gradient_accumulation_steps", 4) training_args = SFTConfig( output_dir=str(output_dir), num_train_epochs=cfg.get("num_epochs", 3), per_device_train_batch_size=per_device_batch_size, gradient_accumulation_steps=grad_accum, learning_rate=cfg.get("learning_rate", 2e-4), warmup_ratio=cfg.get("warmup_ratio", 0.03), lr_scheduler_type="cosine", logging_steps=cfg.get("logging_steps", 10), save_strategy="epoch", eval_strategy="epoch" if eval_dataset else "no", bf16=use_bf16, fp16=False, optim=optim_name, report_to="none", seed=cfg.get("seed", 42), dataloader_num_workers=0, max_length=cfg.get("max_seq_length", 1024), dataset_text_field="text", packing=False, ) trainer = SFTTrainer( model=model, processing_class=tokenizer, train_dataset=train_dataset, eval_dataset=eval_dataset, args=training_args, callbacks=[LoggingCallback()], ) if args.dry_run: print("Dry run: setup complete. Skipping training.") return print("Starting training...") trainer.train() adapter_dir = output_dir / "final_adapter" trainer.save_model(adapter_dir) tokenizer.save_pretrained(adapter_dir) print(f"Adapter saved to {adapter_dir}") if cfg.get("merge_and_save", True): merged_dir = output_dir / "merged" print(f"Merging adapter into base model and saving to {merged_dir}") merged_model = model.merge_and_unload() merged_model.save_pretrained(merged_dir) tokenizer.save_pretrained(merged_dir) print(f"Merged model saved to {merged_dir}") print("Training complete.") if __name__ == "__main__": main()