Train a Small Model in Free Google Colab
Now you train. You will open a free Google Colab notebook with a T4 GPU, load a small open model in 4-bit, add LoRA adapters and train them on your dataset. We use Unsloth, a free open-source library that makes this faster and lighter on memory, on top of the Hugging Face libraries. At the end, you will see the same training with plain Hugging Face code.
Libraries change fast. Everything here was checked against the official docs as of November 2026. If a name or setting has changed since then, trust the official notebook and docs linked below.
What You'll Learn
- How to start a free Colab notebook with a T4 GPU
- Which small open models fit, and which one we use
- How to load a model in 4-bit and add LoRA adapters with Unsloth
- How to format your chat data and start training
- How to read the training loss, and what to do when memory runs out
Step 1: Open Colab and Pick a GPU
Google Colab gives you a free Python notebook in your browser with a GPU.
- Go to colab.research.google.com and sign in with your Google account.
- Create a new notebook.
- Open Runtime, then Change runtime type, and pick T4 GPU.
The free T4 has about 15 GB of usable GPU memory. Free sessions are limited: they end after at most 12 hours, stop when idle, and a GPU is not always available. Google does not publish exact limits (Colab FAQ). So save your work often, as lesson 6 shows.
Tip: the easiest start is Unsloth's own ready-made notebook. Open the Unsloth notebooks list, find Llama 3.2 (1B and 3B) Conversational, and open it in Colab. The code below follows that notebook, with our own dataset swapped in.
Step 2: Install the Libraries
Run the install cell from the official notebook exactly as it is. It pins library versions that are tested together on Colab, which saves you from version errors. In its simplest form, the install is:
!pip install unsloth
Then upload your tickets.jsonl file from lesson 3 using the folder icon on the left side of Colab.
Step 3: Choose a Base Model
These small open models fit LoRA training on a free T4 as of November 2026:
| Model on Hugging Face | Size | License |
|---|---|---|
unsloth/Llama-3.2-3B-Instruct (or the 1B version) | 3B (or 1B) | Llama 3.2 Community License |
Qwen/Qwen3-1.7B | 1.7B | Apache 2.0 |
HuggingFaceTB/SmolLM3-3B | 3B | Apache 2.0 |
We use Llama 3.2 3B Instruct, because Unsloth's official notebook is built and tested for it on the free T4. If you run out of memory, use the 1B version. Lesson 6 covers what each license allows.
Unsloth also has newer notebooks for models such as Qwen3.5 and Gemma 4. Check each model's Unsloth guide before you use it on a T4: for example, Unsloth does not recommend 4-bit QLoRA for Qwen3.5 models.
Step 4: Load the Model in 4-bit
from unsloth import FastLanguageModel
max_seq_length = 2048
model, tokenizer = FastLanguageModel.from_pretrained(
model_name="unsloth/Llama-3.2-3B-Instruct",
max_seq_length=max_seq_length,
dtype=None, # picks float16 on a T4 automatically
load_in_4bit=True, # QLoRA: load the frozen model in 4-bit
)
load_in_4bit=True is the QLoRA part from lesson 2. Set max_seq_length a bit above your longest example from lesson 3.
Step 5: Add LoRA Adapters
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", # saves memory
random_state=3407,
)
These are the settings from lesson 2: rank 16, alpha equal to the rank, and adapters on all the main linear layers. Gradient checkpointing trades a little speed for a lot of memory.
Step 6: Format Your Data
Load and split your data as in lesson 3, then turn each list of messages into one string with the model's chat template:
from datasets import load_dataset
from unsloth.chat_templates import get_chat_template
tokenizer = get_chat_template(tokenizer, chat_template="llama-3.1")
dataset = load_dataset("json", data_files="tickets.jsonl", split="train")
split = dataset.train_test_split(test_size=0.1, seed=42)
train_data, test_data = split["train"], split["test"]
def to_text(batch):
texts = [
tokenizer.apply_chat_template(msgs, tokenize=False, add_generation_prompt=False)
for msgs in batch["messages"]
]
return {"text": texts}
train_data = train_data.map(to_text, batched=True)
Llama 3.2 uses the same chat template as Llama 3.1, which is why the name says llama-3.1. Print train_data[0]["text"] once to see the marker tokens.
Step 7: Measure the Base Model First
Before you train, save a few answers from the untouched model on your test set. You will compare them with the trained model in lesson 5. Lesson 5 has the full code for this. Skip it for now if you only want to see training work, but come back to it: without a "before", you cannot prove training helped.
Step 8: Train
from trl import SFTConfig, SFTTrainer
from unsloth import is_bfloat16_supported
from unsloth.chat_templates import train_on_responses_only
trainer = SFTTrainer(
model=model,
processing_class=tokenizer,
train_dataset=train_data,
args=SFTConfig(
dataset_text_field="text",
max_length=max_seq_length,
per_device_train_batch_size=2,
gradient_accumulation_steps=4,
num_train_epochs=1,
learning_rate=2e-4,
warmup_steps=5,
logging_steps=5,
optim="adamw_8bit",
fp16=not is_bfloat16_supported(), # float16 on a T4
bf16=is_bfloat16_supported(),
seed=3407,
output_dir="outputs",
report_to="none",
),
)
# Learn only from the assistant's replies, not the user's messages
trainer = train_on_responses_only(
trainer,
instruction_part="<|start_header_id|>user<|end_header_id|>\n\n",
response_part="<|start_header_id|>assistant<|end_header_id|>\n\n",
)
trainer.train()
train_on_responses_only tells the trainer to grade the model only on the assistant's replies. The two marker strings are where Llama 3 user and assistant turns start. The model does not need to learn to write customer messages, only to answer them.
With a few hundred short examples, one epoch on a T4 often takes minutes, not hours. Longer examples and more epochs take longer.
Reading the Training Loss
Every few steps, the trainer prints the loss. You want it to go down, then level off.
| What you see | What it likely means | What to try |
|---|---|---|
| Loss drops, then levels off | Normal, healthy training | Nothing. Test it in lesson 5 |
| Loss barely moves | Learning rate too low, or the data has no clear pattern | Check data, try a higher learning rate |
Loss jumps around or becomes nan | Learning rate too high | Lower it, for example to 1e-4 |
| Loss falls close to zero | The model may be memorizing | Check the test set in lesson 5 |
When You Run Out of Memory
A "CUDA out of memory" error means the GPU is full. Try these, one at a time:
- Lower
per_device_train_batch_sizeto 1, and raisegradient_accumulation_stepsto 8. - Lower
max_seq_lengthif your examples are short. - Switch to the 1B model.
- Restart the runtime (Runtime, then Restart session) to clear old memory, and run the cells again.
The Same Thing With Plain Hugging Face
Unsloth is optional. Here is the same QLoRA setup with only Hugging Face's transformers, peft and trl. This shows what Unsloth does for you.
import torch
from transformers import AutoModelForCausalLM, AutoTokenizer, BitsAndBytesConfig
from datasets import load_dataset
from peft import LoraConfig
from trl import SFTConfig, SFTTrainer
dataset = load_dataset("json", data_files="tickets.jsonl", split="train")
split = dataset.train_test_split(test_size=0.1, seed=42)
model_id = "Qwen/Qwen3-1.7B"
bnb = BitsAndBytesConfig(
load_in_4bit=True,
bnb_4bit_quant_type="nf4",
bnb_4bit_use_double_quant=True,
bnb_4bit_compute_dtype=torch.float16,
)
model = AutoModelForCausalLM.from_pretrained(model_id, quantization_config=bnb, device_map="auto")
tokenizer = AutoTokenizer.from_pretrained(model_id)
peft_config = LoraConfig(r=16, lora_alpha=16, lora_dropout=0.0,
target_modules="all-linear", task_type="CAUSAL_LM")
trainer = SFTTrainer(
model=model,
processing_class=tokenizer,
train_dataset=split["train"], # the raw "messages" data from lesson 3
peft_config=peft_config,
args=SFTConfig(output_dir="outputs", max_length=1024, fp16=True,
per_device_train_batch_size=2, gradient_accumulation_steps=4,
num_train_epochs=1, learning_rate=2e-4, report_to="none"),
)
trainer.train()
Three things to notice:
- With data in the messages format, TRL applies the chat template for you.
- Qwen3 has a "thinking" mode that is on by default. When you chat with your trained model, pass
enable_thinking=Falsetoapply_chat_templateso it answers directly. fp16=Truematters on a T4. The T4 does not support bfloat16, and TRL uses bfloat16 by default unless you setfp16.
Official docs: TRL SFTTrainer, PEFT LoRA, bitsandbytes in transformers, Unsloth docs.
Key Takeaways
- Free Colab gives you a T4 GPU with about 15 GB of memory, with session limits Google does not guarantee.
- Start from Unsloth's official notebook and keep its install cell, since it pins tested versions.
- Load the base model in 4-bit, add LoRA adapters with rank 16, format your data with the model's chat template, then train.
- Train on the assistant's replies only, and watch the loss drop and level off.
- On a T4, use float16, not bfloat16. If memory runs out, lower the batch size or sequence length, or use a smaller model.
Cuestionario
A continuación · Lección 5 de 6
Evaluate Before and After Training
5 min de lectura
4 de 6 lecciones completadas

Pregúntale a Byte sobre esta lección
Un chat privado sobre esta lección. Byte ha leído toda la lección, responde en segundos y muestra la sección de donde sale cada respuesta. Puedes preguntar en cualquier idioma.
Preguntas y respuestas
Preguntas públicas sobre esta lección. El AI Tutor responde al momento en tu idioma, el equipo de FreeAcademy revisa las respuestas y cualquier estudiante puede leerlas.

