sakthai-kaggle-notebooks / train-sakthai-0.5b-v2.py
Nanthasit's picture
Add improved 0.5B fine-tune script (MLP LoRA targets, rsLoRA, completion-only loss, v6+irrelevance)
e991f2f verified
Raw History Blame
6.91 kB
#!/usr/bin/env python3
"""
SakThai 0.5B — improved tool-calling fine-tune (config upgrade v2).
Free Kaggle/Colab T4. QLoRA. Drop-in replacement for the old 0.5B run.
WHAT CHANGED vs the config the live 0.5B adapter was trained with
-----------------------------------------------------------------
1. LoRA targets: attention-only (q/k/v/o) -> ALL linear (adds gate/up/down_proj).
Rank 8 -> 16, alpha 16 -> 32. Small models gain a lot from MLP adaptation.
2. use_rslora=True — stabilizes the higher effective rank (nearly free).
3. COMPLETION-ONLY LOSS — mask system/user/tool tokens; train only on the
assistant turns (incl. <tool_call>). This is the single biggest fix for
"emits a call vs echoes the prompt".
4. Data: combined-v6 (2,003) + irrelevance-supplement (10) — the old engine
pointed at combined-v5. Directly targets the irrelevance BFCL gap.
5. Chat-template rendering WITH tools, so training format == inference format.
Requires (Kaggle: add HF_TOKEN as a secret):
pip install -U "transformers>=4.44" "trl>=0.9,<0.20" peft datasets accelerate bitsandbytes
"""
import os
import torch
from datasets import load_dataset, concatenate_datasets
from transformers import (
AutoModelForCausalLM, AutoTokenizer, BitsAndBytesConfig, TrainingArguments,
)
from peft import LoraConfig, get_peft_model, prepare_model_for_kbit_training
from trl import SFTTrainer, DataCollatorForCompletionOnlyLM
# ─── Config ──────────────────────────────────────────────────────────────
BASE_MODEL = "Qwen/Qwen2.5-0.5B-Instruct"
HF_USER = "Nanthasit"
ADAPTER_REPO = f"{HF_USER}/sakthai-context-0.5b-tools" # overwrite in place, or add "-v2"
MERGED_REPO = f"{HF_USER}/sakthai-context-0.5b-merged" # ditto
MAX_SEQ_LEN = 2048 # tool schemas are long; 0.5B handles this fine on a T4
HF_TOKEN = os.environ.get("HF_TOKEN")
assert HF_TOKEN, "Set HF_TOKEN (Kaggle secret / Colab env)."
# ─── Load base (4-bit QLoRA) ─────────────────────────────────────────────
bnb = BitsAndBytesConfig(
load_in_4bit=True, bnb_4bit_quant_type="nf4",
bnb_4bit_compute_dtype=torch.bfloat16, bnb_4bit_use_double_quant=True,
)
tokenizer = AutoTokenizer.from_pretrained(BASE_MODEL)
if tokenizer.pad_token is None:
tokenizer.pad_token = tokenizer.eos_token
model = AutoModelForCausalLM.from_pretrained(
BASE_MODEL, quantization_config=bnb, device_map="auto", torch_dtype=torch.bfloat16,
)
model = prepare_model_for_kbit_training(model, use_gradient_checkpointing=True)
model.config.use_cache = False
# ─── LoRA: all-linear targets, r16, rsLoRA (the upgrade) ─────────────────
lora_config = LoraConfig(
r=16, lora_alpha=32, lora_dropout=0.05, bias="none", task_type="CAUSAL_LM",
target_modules=["q_proj", "k_proj", "v_proj", "o_proj",
"gate_proj", "up_proj", "down_proj"],
use_rslora=True,
)
model = get_peft_model(model, lora_config)
model.print_trainable_parameters()
# ─── Data: combined-v6 + irrelevance-supplement, rendered with tools ─────
def to_text(ex):
"""Render one example to a single ChatML string using the tokenizer's
chat template, passing tool schemas so the <tools> block is in the prompt."""
msgs = ex["messages"]
tools = ex.get("tools") or None
text = tokenizer.apply_chat_template(
msgs, tools=tools, tokenize=False, add_generation_prompt=False,
)
return {"text": text}
# Map each source to a uniform {"text"} schema BEFORE concatenating
# (combined-v6 and the supplement have slightly different columns).
main = load_dataset(f"{HF_USER}/sakthai-combined-v6", split="train")
train_data = main.map(to_text, remove_columns=main.column_names)
try:
supp = load_dataset(f"{HF_USER}/sakthai-irrelevance-supplement", split="train")
supp_text = supp.map(to_text, remove_columns=supp.column_names)
train_data = concatenate_datasets([train_data, supp_text])
except Exception as e:
print("irrelevance-supplement unavailable, continuing without it:", e)
# Real held-out test split (113) for eval_loss + early stopping — never trained on.
eval_raw = load_dataset(f"{HF_USER}/sakthai-combined-v6", split="test")
eval_data = eval_raw.map(to_text, remove_columns=eval_raw.column_names)
print(f"train={len(train_data)} eval={len(eval_data)}")
# ─── COMPLETION-ONLY masking: train only on assistant turns ──────────────
# Qwen ChatML: user/system/tool turns are masked; assistant turns (incl.
# <tool_call>) are the only tokens contributing to the loss.
collator = DataCollatorForCompletionOnlyLM(
instruction_template="<|im_start|>user\n",
response_template="<|im_start|>assistant\n",
tokenizer=tokenizer,
mlm=False,
)
# ─── Train ───────────────────────────────────────────────────────────────
training_args = TrainingArguments(
output_dir="./sakthai-0.5b-lora",
num_train_epochs=3, # 3–5 is the useful range for a 0.5B
per_device_train_batch_size=8,
gradient_accumulation_steps=2, # eff batch 16
gradient_checkpointing=True,
optim="adamw_8bit",
learning_rate=2e-4, lr_scheduler_type="cosine", warmup_ratio=0.03,
logging_steps=10, eval_strategy="steps", eval_steps=50,
save_strategy="steps", save_steps=100, save_total_limit=2,
load_best_model_at_end=True, metric_for_best_model="eval_loss",
bf16=True, tf32=True, report_to="none",
)
trainer = SFTTrainer(
model=model, tokenizer=tokenizer, args=training_args,
train_dataset=train_data, eval_dataset=eval_data,
dataset_text_field="text", max_seq_length=MAX_SEQ_LEN,
data_collator=collator,
)
trainer.train()
trainer.save_model("./sakthai-0.5b-lora-best")
tokenizer.save_pretrained("./sakthai-0.5b-lora-best")
# ─── Push adapter + merged ───────────────────────────────────────────────
from huggingface_hub import login
login(token=HF_TOKEN)
trainer.model.push_to_hub(ADAPTER_REPO) # LoRA adapter
tokenizer.push_to_hub(ADAPTER_REPO)
# merge to full weights (reload base in bf16, not 4-bit, then merge)
from peft import PeftModel
base = AutoModelForCausalLM.from_pretrained(BASE_MODEL, torch_dtype=torch.bfloat16, device_map="auto")
merged = PeftModel.from_pretrained(base, "./sakthai-0.5b-lora-best").merge_and_unload()
merged.push_to_hub(MERGED_REPO)
tokenizer.push_to_hub(MERGED_REPO)
print("Done. Next: convert merged -> GGUF Q4_K_M (llama.cpp) and run BFCL on the held-out split.")