Learning path: Deep Learning for Production: Transformers, Fine-Tuning and Serving · Step 11 of 13
LoRA Fine-Tune of a Tiny Model: Teach SmolLM2-135M Your House Style on a CPU
Fine-tune SmolLM2-135M-Instruct with LoRA on 50 support replies, on a laptop CPU: 921,600 trainable parameters (0.68%), loss 4.510 to 1.010 in 80 steps, a 3.7 MB adapter, and replies that pick up the house style but not the facts.
What you will learn
- Wrap a frozen model with a LoRA adapter using peft's LoraConfig and get_peft_model
- Build training examples whose labels mask the question with -100
- Train only the adapter with a plain PyTorch loop and save it
- Load base plus adapter with PeftModel and judge what changed and what didn't
Before you start
- Full Fine-Tuning vs LoRA vs QLoRA
- The Same Network in PyTorch
We've talked about LoRA in theory in Full Fine-Tuning vs LoRA vs QLoRA. Now let's do it once, small, from start to finish: teach a tiny model our tone. Four ideas to hold on to: a frozen base model, a small adapter, the training, and saving only the adapter. It all runs on a laptop CPU.
Replies in our house style
A support team wants every answer to sound like the team, not like a general chatbot. Three rules:
- Every reply starts with "Hi there!"
- It gives one short fix. No long essays.
- It ends with the sign-off "- Team Kestrel".
Here's one pair from data/replies.jsonl:
{"question": "I forgot my password. How do I reset it?", "answer": "Hi there! Open Settings, choose Security and click Reset password. We will email you a link. - Team Kestrel"}
There are 50 pairs like this one. Three more questions are kept aside in data/heldout.json. The model never sees them in training; we use them to test.
Sticky notes on a printed textbook
The base model is a printed textbook. We don't touch a single page. The LoRA adapter is a few sticky notes that change how you read the book. You can peel them off, and if you want to share your notes, you hand over only the notes, not the whole book. We train only the notes.
Before: the base model answers
The model is HuggingFaceTB/SmolLM2-135M-Instruct. 01_before.py asks the three held-out questions with greedy decoding and 60 new tokens each:
import json
import torch
from transformers import AutoModelForCausalLM, AutoTokenizer
MODEL = "HuggingFaceTB/SmolLM2-135M-Instruct"
tokenizer = AutoTokenizer.from_pretrained(MODEL)
model = AutoModelForCausalLM.from_pretrained(MODEL, dtype=torch.float32)
questions = json.load(open("data/heldout.json", encoding="utf-8"))
for question in questions:
messages = [{"role": "user", "content": question}]
prompt = tokenizer.apply_chat_template(
messages, add_generation_prompt=True, return_tensors="pt", return_dict=True
)
output = model.generate(
**prompt, max_new_tokens=60, do_sample=False, pad_token_id=tokenizer.eos_token_id
)
answer = tokenizer.decode(output[0][prompt["input_ids"].shape[1]:], skip_special_tokens=True)
print(f"Q: {question}")
print(f"A: {answer.strip()}")
print()
Q: How do I download my yearly report?
A: To download your yearly report, you can follow these steps:
1. **Download the Report**: Open your web browser and go to the official website of the company you want to download the report from.
2. **Download the Report**: Once you're on the website, look for the "
Q: The app will not let me change my phone number.
A: I'm sorry for any inconvenience this may cause. However, I'm designed to handle situations where you need assistance with your phone number. Please feel free to ask for help, and I'll do my best to assist you. If you have any other questions or need further assistance, feel free to ask
Q: My teammate did not get the invitation.
A: I'm sorry for the misunderstanding, but as a chatbot, I don't have the ability to access or respond to messages. I'm here to assist you with your questions or problems. If you need help with something, feel free to ask, and I'll do my best to assist you.
A general list of steps with a repeated heading, an apology with no fix, and "as a chatbot, I can't". Helpful in a general way, but no greeting, no short fix and no sign-off. It doesn't sound like our team.
Add the adapter
02_lora_setup.py wraps the frozen model with a LoRA adapter and counts what can be trained:
import torch
from peft import LoraConfig, get_peft_model
from transformers import AutoModelForCausalLM
MODEL = "HuggingFaceTB/SmolLM2-135M-Instruct"
model = AutoModelForCausalLM.from_pretrained(MODEL, dtype=torch.float32)
config = LoraConfig(
r=8,
lora_alpha=16,
target_modules=["q_proj", "k_proj", "v_proj", "o_proj"],
lora_dropout=0.05,
task_type="CAUSAL_LM",
)
model = get_peft_model(model, config)
trainable = sum(p.numel() for p in model.parameters() if p.requires_grad)
total = sum(p.numel() for p in model.parameters())
print(f"trainable parameters: {trainable:,}")
print(f"all parameters: {total:,}")
print(f"trainable share: {100 * trainable / total:.2f} %")
trainable parameters: 921,600
all parameters: 135,436,608
trainable share: 0.68 %
r=8is the size of the notes. A biggerrmeans bigger notes and more weights to train.lora_alpha=16scales how loudly the notes speak.target_modulessays where the notes go: the attention projectionsq_proj,k_proj,v_projando_proj. These names come from looking inside this particular model.get_peft_modelfreezes the base and adds the small trainable matrices.
We train 0.68% of the model. That's why this runs on a laptop.
Replies become training text
03_train.py sets up the same frozen base and adapter, with a fixed seed so the run is repeatable. Then each pair becomes one list of tokens, the question followed by the reply:
def encode(row):
messages = [{"role": "user", "content": row["question"]}]
prompt = tokenizer.apply_chat_template(messages, add_generation_prompt=True, tokenize=False)
prompt_ids = tokenizer(prompt, add_special_tokens=False)["input_ids"]
answer_ids = tokenizer(row["answer"] + tokenizer.eos_token, add_special_tokens=False)["input_ids"]
return prompt_ids + answer_ids, [-100] * len(prompt_ids) + answer_ids # learn only the answer
Look at the labels. The question part is marked -100, which means "ignore this part when you calculate the loss". So the model learns only the reply, the house style, not the question.
def make_batch(items):
longest = max(len(ids) for ids, _ in items)
pad = tokenizer.eos_token_id
ids = torch.tensor([i + [pad] * (longest - len(i)) for i, _ in items])
labels = torch.tensor([l + [-100] * (longest - len(l)) for _, l in items])
mask = torch.tensor([[1] * len(i) + [0] * (longest - len(i)) for i, _ in items])
return ids, mask, labels
Batches hold five examples. Short ones are padded to the same length, the padding is masked out with the attention mask, and its labels are -100 too.
The training loop
EPOCHS = 8
BATCH = 5
LEARNING_RATE = 5e-4
optimizer = torch.optim.AdamW([p for p in model.parameters() if p.requires_grad], lr=LEARNING_RATE)
model.train()
start = time.perf_counter()
step = 0
for epoch in range(1, EPOCHS + 1):
random.shuffle(examples)
for i in range(0, len(examples), BATCH):
ids, mask, labels = make_batch(examples[i:i + BATCH])
loss = model(input_ids=ids, attention_mask=mask, labels=labels).loss
loss.backward()
optimizer.step()
optimizer.zero_grad()
step += 1
if step == 1 or step % 10 == 0:
print(f"epoch {epoch} step {step:2d} loss {loss.item():.3f}")
seconds = time.perf_counter() - start
model.save_pretrained("adapter")
print(f"training time: {seconds:.0f} s on CPU")
It's the same forward, backward, step loop as in The Same Network in PyTorch. The difference is that the optimizer only gets the parameters with requires_grad, which are the adapter's. Fifty examples in batches of five is 10 steps per epoch, so 8 epochs make 80 steps.
epoch 1 step 1 loss 4.510
epoch 1 step 10 loss 3.645
epoch 2 step 20 loss 2.637
epoch 3 step 30 loss 2.559
epoch 4 step 40 loss 1.508
epoch 5 step 50 loss 1.590
epoch 6 step 60 loss 1.204
epoch 7 step 70 loss 1.357
epoch 8 step 80 loss 1.010
training time: 364 s on CPU
Lower is better, so the model got much better at writing the training replies. About six minutes on a laptop CPU. save_pretrained("adapter") saves only the adapter to a folder.
After: same questions, same settings
04_after.py loads the same frozen base and puts the saved adapter on top:
from peft import PeftModel
tokenizer = AutoTokenizer.from_pretrained(MODEL)
base = AutoModelForCausalLM.from_pretrained(MODEL, dtype=torch.float32)
model = PeftModel.from_pretrained(base, "adapter")
The rest of the file is the same generate loop as before: greedy, 60 new tokens.
Q: How do I download my yearly report?
A: Hi there! Open the website and click the report link. It will download the latest data. - Team Kestrel
Q: The app will not let me change my phone number.
A: Hi there! Open Settings, then Account, and add the number you want. The number will be removed from the list. - Team Kestrel
Q: My teammate did not get the invitation.
A: Hi there! Open Team and click Dispute. Remove the invitation from the team. - Team Kestrel
The style moved. All three replies have the greeting, a short fix and the sign-off. But be careful: the facts did not get better. The third answer tells us to click a button called Dispute, and we never taught that. The model learned how we talk, not what our product does.
A 3.7 MB adapter
05_adapter_size.py compares the saved adapter with the base model's weights file:
adapter/adapter_config.json 0.00 MB
adapter/adapter_model.safetensors 3.72 MB
base model weights: 269.1 MB
adapter weights: 3.7 MB
adapter is 1.4 % of the base file
02_lora_setup.py and 05_adapter_size.py.You could email the adapter to a teammate. The base model comes from its own place, and they put the two together with PeftModel.from_pretrained.
When is this worth it?
LoRA changes how a model behaves. It isn't a way to add knowledge.
| You need | Fine-tune with LoRA? | Better tool |
|---|---|---|
| Replies in our tone | Yes | - |
| Always the same format | Yes | - |
| Answers from our latest documents | No | Retrieval |
| Facts that change every week | No | Retrieval |
For style and format, fine-tune. For new facts, retrieve them. And always try a good prompt first, because it's the cheapest option. The full decision tree is in When NOT to Fine-Tune.
Common mistakes
- Leaving the question in the labels. Without
-100on the prompt tokens, the loss also counts the question, and the model learns the question as well as the reply. - Guessing
target_modules. Layer names differ between models. Look inside the model first. - Reading a low training loss as "it knows our product". It learned the style of 50 replies. The Dispute button shows it still makes up facts.
- Shipping the whole model.
save_pretrainedon a peft model saves only the adapter, which is the point.
Quick recap
| Step | File | Result |
|---|---|---|
| Before | 01_before.py | General answers, no house style |
| Add adapter | 02_lora_setup.py | 921,600 of 135,436,608 trainable (0.68%) |
| Train | 03_train.py | Loss 4.510 to 1.010 in 80 steps, 364 s on CPU |
| After | 04_after.py | Greeting, short fix, sign-off; facts still made up |
| Size | 05_adapter_size.py | 3.7 MB adapter vs 269.1 MB base (1.4%) |
Try it yourself
Change r to 4 and to 16 and compare the trainable share. Write 20 more replies in the data file and train again. Then pick a tone you like and ask the model three new questions.
Built this? Share your solution in the StudyEasy AI Community.
Join free on Skool →Full Fine-Tuning vs LoRA vs QLoRA: What Each One Changes and What It Costs
Next →Knowledge Distillation: Teach a Model 100 Times Smaller From a Teacher's Soft Labels
StudyEasy AI Community
Learn AI engineering, share what you build, and connect with other learners.
Free resources: lesson files, notebooks and code
Ask questions and join engineering discussions
Meet real people learning and building with AI
Machine Learning Engineer: From First Model to ML Engineer
Learn machine learning in Python, then ship it: data analysis, regression, classification, tuning, deployment and MLOps.View on Udemy ↗: Machine Learning Engineer: From First Model to ML Engineer (opens in a new tab)Related articles
Why Neural Networks: Pixels, One Neuron and Layers
Why pictures need neural networks: a handwritten digit is 784 numbers, one neuron is a weighted sum plus a bias and one small rule, and neurons stack into layers. Worked out on MNIST with NumPy.
The Forward Pass and Activation Functions: ReLU, Sigmoid, Tanh and Softmax
Follow numbers through a tiny 3-2-3 network in NumPy: one matrix product per layer, ReLU inside, softmax at the end, and a count of every weight and bias.
Loss and Backpropagation: How Wrong, and Who Is to Blame
The loss says how wrong the network was; backpropagation says how much each weight is to blame. MSE and cross-entropy, the chain rule by hand on a two-weight chain, then the same gradients from PyTorch autograd.
The Training Loop: Epochs, Mini-Batches, Learning Rate and Optimisers
How training is organised: shuffle, cut into mini-batches, take one step per batch, repeat per epoch. Real MNIST runs compare three learning rates, SGD against Adam, and show the overfitting signal in the validation loss.