Spaces:
Runtime error
Runtime error
File size: 8,377 Bytes
2b4b6d8 | 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 | """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()
|