Fine-tuning used to mean renting serious GPU time. For small language models in the 1B-8B range, that is no longer true: with LoRA adapters and an optimized training library like Unsloth, you can fine-tune on a single consumer GPU, or even a free cloud notebook, in under an hour for a modest dataset.
This tutorial takes you from an empty environment to a trained adapter you can actually use. It assumes basic Python and a rough idea of what fine-tuning does; no prior training experience needed.
What Unsloth gives you
Unsloth is an open-source library that reimplements the expensive parts of transformer training with hand-written Triton kernels. The practical effect: training a LoRA adapter uses less VRAM and finishes sooner than the same job in stock Hugging Face Transformers. Unsloth’s own documentation advertises significant speedups; your mileage varies with model size and GPU, but the direction is consistent.
It works through the standard Hugging Face ecosystem: you load models from the Hub, train with TRL’s SFTTrainer, and get a normal LoRA adapter out. Nothing about the output is proprietary.
Hardware: what you actually need
For a 1B-3B parameter model with 4-bit quantization and LoRA, a GPU with 8GB of VRAM is workable. A 7B-8B model wants 12-16GB. If you have no GPU at all, a free Colab notebook with a T4 is enough to follow this tutorial end to end on a small dataset.
The two levers that control VRAM are quantization (4-bit instead of 16-bit roughly quarters the model memory) and LoRA rank (smaller rank means fewer trainable parameters). Both are set in the code below.
Setup
Install Unsloth and its training dependencies. Check Unsloth’s official GitHub repository for the current install command, since the pinned versions change with CUDA releases:
pip install "unsloth[colab-new] @ git+https://github.com/unslothai/unsloth.git"
pip install --no-deps trl peft accelerate bitsandbytes
The colab-new extra targets recent Colab runtimes; on a local machine with your own CUDA setup, follow the standard install instructions in the repo instead.
Preparing your dataset
For instruction fine-tuning, format your data as prompt-response pairs. The Alpaca format is the common convention: each row has an instruction, an optional input, and an output.
{"instruction": "Summarize this support ticket in one sentence.",
"input": "Customer reports the dashboard shows stale data after...",
"output": "Dashboard cache was not invalidated after the deploy."}
Save a few hundred to a few thousand of these as train.jsonl, one JSON object per line. Quality beats quantity here: 500 clean, representative examples will outperform 5,000 noisy ones. Cover the actual tasks you want the model to do, in the phrasing your users really use.
Keep 10% aside as a validation set. You will read its outputs by hand after training; no metric replaces looking at what the model actually writes.
Loading the model
from unsloth import FastLanguageModel
model, tokenizer = FastLanguageModel.from_pretrained(
model_name="unsloth/Llama-3.2-3B-Instruct-bnb-4bit",
max_seq_length=2048,
load_in_4bit=True,
)
model = FastLanguageModel.get_peft_model(
model,
r=16,
lora_alpha=16,
lora_dropout=0,
target_modules=["q_proj", "k_proj", "v_proj", "o_proj",
"gate_proj", "up_proj", "down_proj"],
bias="none",
use_gradient_checkpointing="unsloth",
)
A few choices worth understanding: max_seq_length caps the context window and directly controls memory use, so set it to the longest example in your data, not the model maximum. Rank r=16 is a sane starting point; raise it only if the model underfits. The unsloth/ model names on the Hub are pre-quantized versions that load faster.
Training
from trl import SFTTrainer
from transformers import TrainingArguments
from datasets import load_dataset
dataset = load_dataset("json", data_files="train.jsonl", split="train")
def format_alpaca(ex):
text = f"### Instruction:n{ex['instruction']}"
if ex.get("input"):
text += f"n### Input:n{ex['input']}"
text += f"n### Response:n{ex['output']}" + tokenizer.eos_token
return {"text": text}
dataset = dataset.map(format_alpaca)
trainer = SFTTrainer(
model=model,
tokenizer=tokenizer,
train_dataset=dataset,
dataset_text_field="text",
max_seq_length=2048,
args=TrainingArguments(
per_device_train_batch_size=2,
gradient_accumulation_steps=4,
num_train_epochs=2,
learning_rate=2e-4,
fp16=True,
logging_steps=10,
output_dir="outputs",
),
)
trainer.train()
Two epochs is a reasonable default for small datasets; more epochs on a few hundred examples mostly teaches the model to memorize. If the training loss collapses to near zero in the first epoch, your data is too repetitive or your learning rate is too high.
Checking the result before you trust it
After training, generate responses for your held-out validation examples and read them:
FastLanguageModel.for_inference(model)
inputs = tokenizer(["### Instruction:nSummarize this ticket:n### Input:n...n### Response:n"],
return_tensors="pt").to("cuda")
out = model.generate(**inputs, max_new_tokens=128, temperature=0.7)
print(tokenizer.decode(out[0], skip_special_tokens=True))
Look for three failure modes: the model ignoring the instruction format, repeating phrases from the training data verbatim, or degrading on tasks it handled well before fine-tuning. Any of these means adjusting data, rank, or epochs, not more training time.
Exporting your adapter
You have two common paths. Save the LoRA adapter alone (small, needs the base model at inference time) or merge it into a standalone model:
# Option 1: save the adapter
model.save_pretrained("my-adapter")
tokenizer.save_pretrained("my-adapter")
# Option 2: merge to 16-bit and export to GGUF for llama.cpp / Ollama
model.save_pretrained_merged("my-model-merged", tokenizer, save_method="merged_16bit")
model.save_pretrained_gguf("my-model-gguf", tokenizer, quantization_method="q8_0")
The GGUF export is the practical choice if you want to run the model locally with Ollama or llama.cpp. The q8_0 quantization keeps quality close to the merged model while keeping the file size manageable; check Unsloth’s docs for the current list of supported quantization methods.
What to try next
Once the basic loop works, the improvements that matter most are data improvements: more diverse examples, harder edge cases, and cleaner outputs. On the technical side, experiment with rank, try a larger base model if your GPU allows it, and consider DPO or ORPO (both supported in Unsloth) if you have preference data. Fine-tuning is mostly a data project wearing a training costume.