AI Hints
Home›Fine-Tuning LLMs Tutorial›Your First LoRA Fine-Tune
Fine-Tuning LLMs · Lesson 51 of 120

First LoRA Run

Train it for real.

⏱ 2 min read▶ Video at 1:20:44🎓 Free
Watch this lesson in the Fine-Tuning LLMs courseWatch on YouTube ↗Full Fine-Tuning LLMs course

This is the big moment. We'll fine-tune a real language model, with LoRA, on our Riverside Books data. On a laptop CPU, it takes a minute or two.

  • The big moment
  • A real LLM, with LoRA
  • A minute or two on a laptop

Train it!

We import the trainer from s f t dot p y, and our small ask helper. We time the training. Then we print the training loss, and the test loss, from the log history. Finally, we ask the fine-tuned model about a new message. Run it. The training loss starts at zero point eight six, and drops to about zero point zero four. The test loss falls too, so it's learning, not memorising. And the model now answers with perfect JSON. Order status, for the book Emma.

app.pypython
import time
from sft import trainer, tok
from ask import ask

start = time.time()
trainer.train()
print(f"Training took {time.time() - start:.0f} seconds")
for log in trainer.state.log_history:
    if "loss" in log:
        print(f"step {log['step']:2}: train loss {log['loss']:.3f}")
    if "eval_loss" in log:
        print(f"step {log['step']:2}: eval loss  {log['eval_loss']:.3f}")
print(ask(trainer.model, tok, "hi, where is my copy of Emma??"))
Output
Training took 174 seconds
step 11: train loss 0.859
step 22: train loss 0.256
step 22: eval loss  0.133
step 33: train loss 0.091
step 44: train loss 0.048
step 44: eval loss  0.035
step 55: train loss 0.037
step 66: train loss 0.041
step 66: eval loss  0.025
{"intent": "order_status", "book": "Emma"}
Also uses chat.py
import json
from datasets import load_dataset

SYSTEM = "Read the customer's message. Reply with JSON: the intent and the book."

def to_example(row):
    answer = json.dumps({"intent": row["intent"], "book": row["book"]})
    return {"prompt": [{"role": "system", "content": SYSTEM},
                       {"role": "user", "content": row["message"]}],
            "completion": [{"role": "assistant", "content": answer}]}

data = load_dataset("json", data_files={"train": "tickets_train.jsonl",
                                        "test": "tickets_test.jsonl"})
data = data.map(to_example, remove_columns=["message", "intent", "book"])
Also uses ask.py
from chat import SYSTEM

def ask(model, tok, message):
    model.eval()                       # switch off training-only behaviour
    messages = [{"role": "system", "content": SYSTEM}, {"role": "user", "content": message}]
    ids = tok.apply_chat_template(messages, add_generation_prompt=True,
                                  return_dict=True, return_tensors="pt")
    out = model.generate(**ids, max_new_tokens=30, do_sample=False)
    return tok.decode(out[0][ids["input_ids"].shape[1]:], skip_special_tokens=True)
Also uses sft.py
from transformers import AutoTokenizer, AutoModelForCausalLM
from peft import LoraConfig
from trl import SFTTrainer, SFTConfig
from chat import data

NAME = "HuggingFaceTB/SmolLM2-135M-Instruct"
tok = AutoTokenizer.from_pretrained(NAME)
model = AutoModelForCausalLM.from_pretrained(NAME)
lora = LoraConfig(r=16, lora_alpha=32, lora_dropout=0.05,
                  target_modules="all-linear", task_type="CAUSAL_LM")
args = SFTConfig(output_dir="ticket-lora", num_train_epochs=1, learning_rate=2e-4,
                 per_device_train_batch_size=8, logging_steps=11,
                 eval_strategy="steps", eval_steps=22,
                 save_strategy="no", report_to="none")
trainer = SFTTrainer(model=model, args=args, train_dataset=data["train"],
                     eval_dataset=data["test"], processing_class=tok, peft_config=lora)

What just happened

Let's be clear about what just happened. We trained less than four percent of the model's numbers. Every original weight stayed frozen. And yet the model learned a brand new output format, from five hundred examples, in about two minutes, on a laptop. That's the power of LoRA.

keyvalue
Trained< 4% of the numbers
Frozenevery original weight
Learneda new output format
Costminutes, on a laptop

Summary

Let's recap. Trainer dot train ran our first LoRA fine-tune. Both losses fell, so the model learned the task. And it now writes clean JSON. Next, let's compare the model before, and after.

Key takeaways
  • trainer.train()
  • Train + eval loss fell
  • Clean JSON answers
Next up: Before and After — see the difference