We always want to get our hands dirty to reinforce what we have learned. But one of the major issues with Transformer-based LLMs is that they need heavy compute, which is not available cheaply. For many of us, that is where the exploration stops.
However, this problem has a solution: Kaggle. It is the data science website owned by Google, and it lends every verified account free NVIDIA GPUs for a fixed number of hours each week. The web browser is our usual way in, but it can eat up a lot of RAM and slow down everything else.
In this article, we explore how to manage all the steps directly from the terminal. That makes things much easier and leaves us free to do other tasks at the same time.
Your own computer never does the heavy work. It only writes the code, sends it and collects the result. That is why the same steps work from a Windows laptop, a Linux PC or a Raspberry Pi.
Checked on 2 November 2026 against the documentation for Kaggle's official command-line tool, which is linked at the end. Kaggle changes its GPU quota and session limits from time to time, so this guide doesn't quote them. Your current numbers are on your Kaggle settings page.
First, let's understand the different ways to "train" an LLM
"Training an LLM" can mean three very different jobs, and only one of them fits on a free GPU.
- Pre-training builds a model from nothing. It takes thousands of data centre GPUs running for weeks. Nobody does this on Kaggle.
- Fine-tuning takes a model someone has already pre-trained and teaches it your data, your style or your task. This is what you will do here.
- Running (inference) just uses a model to answer. You can do that on Kaggle too, but it isn't training.
We explain the difference, and why it matters for hardware, in GPUs for AI: what you need to run a model at home.
The trick that makes fine-tuning cheap is LoRA. Instead of changing all of a model's billions of weights, LoRA freezes them and trains a small add-on, called an adapter, that is often only a few megabytes. Our Fine-Tuning and LoRA lesson, part of the Large Language Models course, explains how it works, including QLoRA. The LLM lifecycle article shows where fine-tuning fits in a model's life.
What Kaggle gives you
| What you get | |
|---|---|
| GPU | GPU T4 ×2: two NVIDIA T4 cards with 16 GB of memory each. It is the default GPU for command-line runs. |
| Time | a weekly GPU quota and a time cap on each run; both are shown on your Kaggle settings page |
| Software | Python with PyTorch and Hugging Face Transformers already installed |
| Internet | optional, switched on per notebook, needed to download models from Hugging Face |
| Storage for results | anything your script saves in /kaggle/working/ comes back to you |
Two facts about the T4 shape everything below:
- 16 GB per card is plenty for a small model. The example uses a 0.5-billion-parameter model, which trains comfortably. Models of a few billion parameters also fit if you load them in 4-bit (QLoRA).
- The T4 does not support the
bf16number format that many tutorials use. Usefp16instead, or training stops with an error.
Kaggle also lets you use its GPUs in a browser notebook: create a notebook, open Session options → Accelerator, pick GPU T4 x2 and run cells. That is the easiest way to experiment. This guide uses the command line, because it lets you start a run from anywhere and repeat it with one command.
Step 1: Create and verify your Kaggle account
- Sign up at kaggle.com with an email or Google account.
- Verify your phone number: profile picture → Settings → Phone verification. If you skip this, the GPU and internet options stay greyed out.
- On the same Settings page, note your GPU quota so you know how many hours you have this week.
Step 2: Install the Kaggle command-line tool
The tool needs Python 3.11 or newer. Install it inside a virtual environment, so it doesn't clash with anything else on your machine.
Windows
Install Python from python.org and tick Add python.exe to PATH in the installer. Then, in PowerShell:
mkdir C:\kaggle-work; cd C:\kaggle-work
python -m venv .venv
.\.venv\Scripts\Activate.ps1
pip install kaggle
If PowerShell refuses to run the activate script, run Set-ExecutionPolicy -Scope CurrentUser RemoteSigned once, then activate again.
Linux (Ubuntu or Debian)
sudo apt update && sudo apt install -y python3-venv python3-pip
mkdir -p ~/kaggle-work && cd ~/kaggle-work
python3 -m venv .venv
source .venv/bin/activate
pip install kaggle
Check your Python version first with python3 --version. If it is older than 3.11, install a newer one before continuing.
Raspberry Pi
The Pi has no NVIDIA GPU, so it never trains anything itself. Here it is just the remote control: it sends the job and receives the model. That makes a Pi a perfectly good machine for this.
sudo apt update && sudo apt full-upgrade -y
sudo apt install -y python3-venv
mkdir -p ~/kaggle-work && cd ~/kaggle-work
python3 -m venv .venv
source .venv/bin/activate
pip install kaggle
The virtual environment matters on Raspberry Pi OS. Recent versions refuse a plain pip install outside one, with an "externally-managed-environment" error.
Step 3: Connect the tool to your account
The simplest way is to sign in from the terminal:
kaggle auth login
If that doesn't suit your setup, for example on a Pi with no browser, create a token instead. Go to Settings → API on Kaggle (or open kaggle.com/settings/api), create a token, and give it to the tool in one of two ways:
- set it as the environment variable
KAGGLE_API_TOKENin your terminal, or - save it in a file called
access_tokeninside a.kagglefolder in your home folder (~/.kaggle/on Linux and the Pi,C:\Users\<you>\.kaggle\on Windows).
Older guides tell you to download a kaggle.json file. That still works, but Kaggle now calls it a legacy key.
Treat the token like a password. Never commit it to Git, never paste it into a notebook and never show it in a screenshot. If it leaks, delete it on the same settings page and create a new one.
Test the connection:
kaggle kernels list --mine
A list, or an empty table, means you are connected. ("Kernel" is Kaggle's old name for a notebook, and the commands still use it.)
Step 4: Upload your training data
Fine-tuning data for a chat model is usually a JSONL file: one JSON object per line, each holding one conversation. For example, train.jsonl:
{"messages": [{"role": "user", "content": "What is Ohm's law?"}, {"role": "assistant", "content": "Voltage equals current times resistance: V = I × R."}]}
{"messages": [{"role": "user", "content": "What does a diode do?"}, {"role": "assistant", "content": "It lets current flow in one direction and blocks it in the other."}]}
A few hundred good examples teach a model a style or a format. Quality matters far more than quantity.
Put the file in a folder and upload it to Kaggle as a dataset:
mkdir my-chat-data # put train.jsonl inside
kaggle datasets init -p my-chat-data
# edit my-chat-data/dataset-metadata.json:
# set "title" and set "id" to "yourname/my-chat-data"
kaggle datasets create -p my-chat-data
Replace yourname with your Kaggle username, here and below. New datasets are private by default. When you change the data, upload a new version with kaggle datasets version -p my-chat-data -m "more examples".
Step 5: Write the training script
Create a folder for the job and let the tool make its settings file:
mkdir train-job
kaggle kernels init -p train-job
Save this as train-job/train.py. It fine-tunes Qwen2.5-0.5B-Instruct, a small open model, with LoRA:
import os
os.environ["CUDA_VISIBLE_DEVICES"] = "0" # use one of the two T4s; enough for a small model
import subprocess, sys
subprocess.run([sys.executable, "-m", "pip", "install", "-q", "peft", "trl"], check=True)
from datasets import load_dataset
from peft import LoraConfig
from transformers import AutoModelForCausalLM, AutoTokenizer
from trl import SFTConfig, SFTTrainer
BASE = "Qwen/Qwen2.5-0.5B-Instruct"
data = load_dataset("json", data_files="/kaggle/input/my-chat-data/train.jsonl", split="train")
tokenizer = AutoTokenizer.from_pretrained(BASE)
model = AutoModelForCausalLM.from_pretrained(BASE)
trainer = SFTTrainer(
model=model,
processing_class=tokenizer,
train_dataset=data,
peft_config=LoraConfig(
r=16, lora_alpha=32, lora_dropout=0.05,
target_modules="all-linear", task_type="CAUSAL_LM",
),
args=SFTConfig(
output_dir="/kaggle/working/checkpoints",
num_train_epochs=3,
per_device_train_batch_size=4,
gradient_accumulation_steps=4,
learning_rate=2e-4,
fp16=True, # the T4 has no bf16
logging_steps=10,
save_strategy="epoch", # a checkpoint after every epoch
report_to="none",
),
)
trainer.train()
trainer.save_model("/kaggle/working/my-lora-adapter")
tokenizer.save_pretrained("/kaggle/working/my-lora-adapter")
Three paths matter:
/kaggle/input/my-chat-data/is where Kaggle puts your dataset./kaggle/working/is the only folder that comes back to you. Anything saved elsewhere is lost when the run ends.my-lora-adapteris your result: the small adapter, not a full copy of the model.
Now edit train-job/kernel-metadata.json so the run gets a GPU, internet access and your data:
{
"id": "yourname/llm-finetune",
"title": "llm-finetune",
"code_file": "train.py",
"language": "python",
"kernel_type": "script",
"is_private": "true",
"enable_gpu": "true",
"enable_internet": "true",
"machine_shape": "NvidiaTeslaT4",
"dataset_sources": ["yourname/my-chat-data"]
}
Internet is needed because the script downloads the base model from Hugging Face and installs two libraries.
Step 6: Run it on Kaggle's GPU
These three commands are the same on Windows, Linux and the Pi:
kaggle kernels push -p train-job
kaggle kernels status yourname/llm-finetune
kaggle kernels output yourname/llm-finetune -p results
push uploads the script and starts it on a GPU. Run status now and then: it says running, then complete (or error). Once it is complete, output downloads everything from /kaggle/working/, including the adapter and the run log, into a folder called results. If a run fails, the log is the first place to look.
You can close your laptop, or let your Pi sleep, while it trains. The job runs on Kaggle, not on your machine.
Step 7: Talk to your model
On any computer with Python, install transformers, peft and torch, and load the adapter. The base model downloads automatically the first time.
from peft import AutoPeftModelForCausalLM
from transformers import AutoTokenizer
path = "results/my-lora-adapter"
model = AutoPeftModelForCausalLM.from_pretrained(path)
tokenizer = AutoTokenizer.from_pretrained(path)
messages = [{"role": "user", "content": "What is Ohm's law?"}]
ids = tokenizer.apply_chat_template(messages, add_generation_prompt=True, return_tensors="pt")
out = model.generate(ids, max_new_tokens=100)
print(tokenizer.decode(out[0][ids.shape[1]:], skip_special_tokens=True))
A 0.5-billion-parameter model answers on an ordinary laptop CPU, no GPU needed. To run it on a Raspberry Pi, the usual route is to merge the adapter into the model and convert it to the GGUF format for llama.cpp, which is built to run models on small CPUs.
When something goes wrong
| Problem | Fix |
|---|---|
| GPU option greyed out | Verify your phone number in Kaggle's settings |
401 Unauthorized from the tool | The token is missing, in the wrong place or deleted; sign in again or create a new token |
externally-managed-environment on the Pi | Activate the virtual environment before pip install |
Error mentioning bf16 | The T4 doesn't support it; use fp16=True |
CUDA out of memory | Lower per_device_train_batch_size, use shorter examples or pick a smaller model |
| Run stops partway | It hit the per-run time cap; train for fewer epochs or on less data, and keep the run well inside the cap |
| Weekly GPU hours run out | Wait for the weekly reset; don't leave browser notebooks idle with the GPU on, because idle time still counts |
Adapter missing from results | The script saved it outside /kaggle/working/ |
Good habits
- Test small first. Run the script on 20 examples with
"enable_gpu": "false"to catch mistakes, then switch the GPU on for the real run. Mistakes cost minutes on the CPU; on the GPU they cost your weekly hours. - Keep data private. Datasets and notebooks are private by default. Leave them that way for anything personal or sensitive.
- Start tiny, then grow. Get the whole loop working with the 0.5B model before trying a bigger one. The steps don't change, only the model name and the memory settings.
Links
- Kaggle command-line tool on GitHub: installation, sign-in and every command used here
- Kaggle Notebooks documentation
- Hugging Face TRL documentation: the
SFTTrainerused in the script - Hugging Face PEFT documentation: LoRA adapters