Spaces:
Runtime error
Runtime error
Download train_lora.py from Expanded-Repetition/ammo-card: direct link, hf CLI and curl.
- Browser
- Download file 8.38 kB
-
https://huggingface.co/spaces/Expanded-Repetition/ammo-card/resolve/main/train_lora.py
- Command line
-
hf download hf://spaces/Expanded-Repetition/ammo-card/train_lora.py
-
curl -L -o train_lora.py https://huggingface.co/spaces/Expanded-Repetition/ammo-card/resolve/main/train_lora.py
8.38 kB
| """Optional LoRA fine-tuning for reviewed Amo code-improvement examples. | |
| This script is intentionally separate from the running web app. It never trains on | |
| all chat history; it uses only accepted examples exported from the improvement lab. | |
| """ | |
| from __future__ import annotations | |
| import argparse | |
| import json | |
| import random | |
| from pathlib import Path | |
| import torch | |
| from torch.utils.data import Dataset | |
| from transformers import AutoModelForCausalLM, AutoTokenizer, Trainer, TrainingArguments | |
| from peft import LoraConfig, get_peft_model | |
| DEFAULT_MODEL = "Qwen/Qwen2.5-Coder-1.5B-Instruct" | |
| class ChatSFTDataset(Dataset): | |
| def __init__(self, records, tokenizer, max_length=1024): | |
| self.items = [] | |
| self.tokenizer = tokenizer | |
| self.max_length = max_length | |
| for record in records: | |
| messages = record.get("messages") | |
| if not isinstance(messages, list) or len(messages) < 2: | |
| continue | |
| if messages[-1].get("role") != "assistant": | |
| continue | |
| try: | |
| prompt = tokenizer.apply_chat_template(messages[:-1], tokenize=False, add_generation_prompt=True) | |
| full = tokenizer.apply_chat_template(messages, tokenize=False, add_generation_prompt=False) | |
| prompt_ids = tokenizer(prompt, add_special_tokens=False)["input_ids"] | |
| encoded = tokenizer(full, max_length=max_length, truncation=True, add_special_tokens=False) | |
| input_ids = encoded["input_ids"] | |
| if len(input_ids) < 8: | |
| continue | |
| labels = list(input_ids) | |
| mask_count = min(len(prompt_ids), len(labels)) | |
| labels[:mask_count] = [-100] * mask_count | |
| # Skip samples whose completion was fully truncated away. | |
| if all(x == -100 for x in labels): | |
| continue | |
| self.items.append({"input_ids": input_ids, "attention_mask": encoded["attention_mask"], "labels": labels}) | |
| except Exception as exc: | |
| print(f"Skipping a malformed sample: {type(exc).__name__}: {exc}") | |
| def __len__(self): | |
| return len(self.items) | |
| def __getitem__(self, idx): | |
| return self.items[idx] | |
| class PaddingCollator: | |
| def __init__(self, tokenizer): | |
| self.tokenizer = tokenizer | |
| def __call__(self, features): | |
| max_len = max(len(x["input_ids"]) for x in features) | |
| pad_id = self.tokenizer.pad_token_id | |
| input_ids, attention_mask, labels = [], [], [] | |
| for item in features: | |
| padding = max_len - len(item["input_ids"]) | |
| input_ids.append(item["input_ids"] + [pad_id] * padding) | |
| attention_mask.append(item["attention_mask"] + [0] * padding) | |
| labels.append(item["labels"] + [-100] * padding) | |
| return { | |
| "input_ids": torch.tensor(input_ids, dtype=torch.long), | |
| "attention_mask": torch.tensor(attention_mask, dtype=torch.long), | |
| "labels": torch.tensor(labels, dtype=torch.long), | |
| } | |
| def read_jsonl(path: Path): | |
| records = [] | |
| with path.open(encoding="utf-8") as f: | |
| for line_number, line in enumerate(f, start=1): | |
| if not line.strip(): | |
| continue | |
| try: | |
| item = json.loads(line) | |
| if isinstance(item, dict) and isinstance(item.get("messages"), list): | |
| records.append(item) | |
| else: | |
| print(f"Skipping line {line_number}: missing messages list") | |
| except json.JSONDecodeError as exc: | |
| print(f"Skipping invalid JSON on line {line_number}: {exc}") | |
| return records | |
| def main(): | |
| parser = argparse.ArgumentParser(description="Fine-tune an Amo coding assistant with LoRA.") | |
| parser.add_argument("--data", default="data/amo_training_examples.jsonl", help="Reviewed accepted JSONL examples") | |
| parser.add_argument("--model", default=DEFAULT_MODEL, help="Small Hugging Face instruct model ID") | |
| parser.add_argument("--output", default="checkpoints/amo-coder-lora", help="Adapter output directory") | |
| parser.add_argument("--epochs", type=float, default=2.0) | |
| parser.add_argument("--max-length", type=int, default=1024) | |
| parser.add_argument("--min-examples", type=int, default=20) | |
| args = parser.parse_args() | |
| data_path = Path(args.data) | |
| if not data_path.exists(): | |
| raise SystemExit(f"Training file not found: {data_path}. Export it from Amo first.") | |
| records = read_jsonl(data_path) | |
| if len(records) < args.min_examples: | |
| raise SystemExit( | |
| f"Found {len(records)} examples; need at least {args.min_examples}. " | |
| "Collect and review diverse, tested examples first. Training on a tiny/repetitive set can make the model worse." | |
| ) | |
| random.Random(42).shuffle(records) | |
| val_count = max(2, int(len(records) * 0.1)) | |
| val_records, train_records = records[:val_count], records[val_count:] | |
| if not train_records: | |
| raise SystemExit("Not enough records after validation split.") | |
| if not torch.cuda.is_available(): | |
| raise SystemExit("No CUDA GPU is available. Select a GPU accelerator in Kaggle before training.") | |
| vram_gb = torch.cuda.get_device_properties(0).total_memory / (1024 ** 3) | |
| print(f"GPU: {torch.cuda.get_device_name(0)} · VRAM: {vram_gb:.1f} GiB") | |
| if vram_gb < 12: | |
| print("Warning: less than 12 GiB VRAM; reduce --max-length to 512 if out-of-memory occurs.") | |
| tokenizer = AutoTokenizer.from_pretrained(args.model, use_fast=True, trust_remote_code=False) | |
| if tokenizer.pad_token_id is None: | |
| tokenizer.pad_token = tokenizer.eos_token | |
| model = AutoModelForCausalLM.from_pretrained( | |
| args.model, | |
| torch_dtype=torch.float16, | |
| low_cpu_mem_usage=True, | |
| trust_remote_code=False, | |
| ) | |
| model.config.use_cache = False | |
| model.gradient_checkpointing_enable(gradient_checkpointing_kwargs={"use_reentrant": False}) | |
| model.enable_input_require_grads() | |
| # Discover supported linear layer names, avoiding model-specific hard-coded assumptions. | |
| target_modules = sorted({ | |
| name.rsplit(".", 1)[-1] | |
| for name, module in model.named_modules() | |
| if isinstance(module, torch.nn.Linear) and not name.endswith("lm_head") | |
| }) | |
| if not target_modules: | |
| raise SystemExit("Could not find linear layers for LoRA on this model architecture.") | |
| lora = LoraConfig( | |
| r=8, lora_alpha=16, lora_dropout=0.05, bias="none", | |
| task_type="CAUSAL_LM", target_modules=target_modules, | |
| ) | |
| model = get_peft_model(model, lora) | |
| model.print_trainable_parameters() | |
| train_set = ChatSFTDataset(train_records, tokenizer, max_length=args.max_length) | |
| val_set = ChatSFTDataset(val_records, tokenizer, max_length=args.max_length) | |
| if len(train_set) < 10 or len(val_set) < 1: | |
| raise SystemExit("Too few usable tokenized examples; review JSONL and max-length settings.") | |
| training_args = TrainingArguments( | |
| output_dir=args.output, | |
| num_train_epochs=args.epochs, | |
| per_device_train_batch_size=1, | |
| per_device_eval_batch_size=1, | |
| gradient_accumulation_steps=8, | |
| learning_rate=1e-4, | |
| weight_decay=0.01, | |
| warmup_ratio=0.03, | |
| logging_steps=5, | |
| eval_strategy="epoch", | |
| save_strategy="epoch", | |
| save_total_limit=2, | |
| load_best_model_at_end=True, | |
| metric_for_best_model="eval_loss", | |
| greater_is_better=False, | |
| fp16=True, | |
| gradient_checkpointing=True, | |
| gradient_checkpointing_kwargs={"use_reentrant": False}, | |
| report_to="none", | |
| dataloader_num_workers=0, | |
| seed=42, | |
| ) | |
| trainer = Trainer( | |
| model=model, | |
| args=training_args, | |
| train_dataset=train_set, | |
| eval_dataset=val_set, | |
| data_collator=PaddingCollator(tokenizer), | |
| ) | |
| trainer.train() | |
| out = Path(args.output) | |
| out.mkdir(parents=True, exist_ok=True) | |
| model.save_pretrained(out) | |
| tokenizer.save_pretrained(out) | |
| metrics = trainer.evaluate() | |
| print("Adapter saved to:", out.resolve()) | |
| print("Validation metrics:", metrics) | |
| print("Keep the original model as fallback and compare with a held-out coding benchmark before replacing it.") | |
| if __name__ == "__main__": | |
| main() | |