Every later lesson runs Python scripts that load a small language model, train adapters and measure results. For those scripts to behave the same on your computer as in the lessons, they need exactly the same library versions, exactly the same model files, and a few settings that keep downloads, usage data and model files under control.
In this lesson you build that environment once and prove it works:
- one folder,
~/finetune-practice, that holds everything the course creates; - a Python virtual environment with the course's pinned libraries;
- the two course models, downloaded at fixed revisions and checked against published checksums;
- a check script that reports every part as ok or FAIL.
You will also learn which model files the course never loads, and why.
Before you start
| Part | What you need |
|---|---|
| Goal | A working course environment, proved by check_setup.py printing "All checks passed." |
| Starting state | A 64-bit computer: macOS 14 or later on Apple silicon, Linux on x86_64 (with AVX2) or aarch64, or Windows 10 or 11 on x64 (with AVX2). Python 3.12, 3.13 or 3.14, a terminal and a plain-text editor. About 4 GB of free disk |
| Inputs | No values to choose: every version, revision and checksum is written in the scripts |
| Execution | A terminal, as your own user. No administrator rights are needed |
| Effects | Creates ~/finetune-practice with a 1.1 GB environment and a 1 GB model cache. Downloads about 1.2 GB (in the course's macOS test, 220 MB of packages and 1 GB of models) from PyPI, the PyTorch package index and Hugging Face. Nothing else on your computer changes |
| Network | Needed only in this lesson. Every later lesson works offline |
| Time | About 24 minutes in the course's test, on a computer heavily loaded by other work: 18 minutes to install the packages and 3.5 minutes to download the models. Your time depends on your connection and computer |
The terminal commands this course uses
You need to move between folders and run scripts. If these are new, try each one now:
| Task | macOS and Linux (bash, zsh) | Windows PowerShell |
|---|---|---|
| Show the current folder | pwd | pwd |
| List files | ls | dir |
| Make a folder and its parents | mkdir -p name/sub | New-Item -ItemType Directory -Force name\sub |
| Change folder | cd name | cd name |
| Run a Python script | python script.py | python script.py |
| Stop a running program | Ctrl+C | Ctrl+C |
~ means your home folder on macOS and Linux; in PowerShell use $HOME.
The lessons show macOS and Linux commands first and PowerShell where it
differs.
A two-minute Python readiness check
The course assumes you can write and debug small Python programs. Make the
folder for this lesson and save this script as readiness.py in it:
mkdir -p ~/finetune-practice/setup
cd ~/finetune-practice/setup
"""Readiness check: count how often each value of one key appears.
Run from ~/finetune-practice/setup with any Python 3:
python readiness.py
It stops with an error. Read the last line of the traceback and fix the
function so that it skips reports without the key.
"""
reports = [
{"equipment": "kayak", "location": "boathouse"},
{"equipment": "tent", "location": "campsite"},
{"equipment": "kayak", "location": "lodge"},
{"location": "workshop"},
]
def count_values(rows, key):
counts = {}
for row in rows:
counts[row[key]] = counts.get(row[key], 0) + 1
return counts
print(count_values(reports, "equipment"))
Run it with python3 readiness.py (or python readiness.py on Windows). It
fails, and the last line of the traceback reads KeyError: 'equipment'.
Fix the function so that a report without the key is skipped, run it
again, and expect {'kayak': 2, 'tent': 1}.
If you could not find the fix within a few minutes, study Python first (for example the course Python for AI and Machine Learning). This course does not teach Python syntax. The answer is at the end of this lesson.
Step 1: the practice folder and the environment
A virtual environment is a folder with its own Python and its own installed packages, so the course's pinned versions cannot clash with anything else on your computer. Create it inside the practice folder.
macOS and Linux:
mkdir -p ~/finetune-practice && cd ~/finetune-practice
python3 -m venv .venv
source .venv/bin/activate
Windows PowerShell:
New-Item -ItemType Directory -Force $HOME\finetune-practice; cd $HOME\finetune-practice
py -3.13 -m venv .venv
.\.venv\Scripts\Activate.ps1
On Windows, py -3.13 picks a specific installed Python; use -3.12 or
-3.14 if that is what you have. After activation your prompt starts with
(.venv), and python means the environment's Python. Check it:
python --version
python -c "import sys; print(sys.prefix)"
The first line must show Python 3.12, 3.13 or 3.14. The second must end in
finetune-practice/.venv. If python -m venv fails on Debian or Ubuntu with
a message about ensurepip, the system Python lacks the venv module:
install the python3-venv package with your package manager, then repeat
the step.
Step 2: install the pinned libraries
Run these three commands in order, in the activated environment:
python -m pip install numpy==2.5.4
python -m pip install torch==2.14.1 --index-url https://download.pytorch.org/whl/cpu
python -m pip install transformers==5.20.2 peft==0.21.2 trl==1.16.0 datasets==5.1.0 accelerate==1.15.0 bitsandbytes==0.50.2
python -m pip check
The same commands work in PowerShell. Here is why they are split this way:
- NumPy comes first, from PyPI. It sets the course's minimum Python (NumPy 2.5.4 needs Python 3.12 or later).
- torch comes second, from PyTorch's CPU index. On Linux the ordinary PyPI torch package is a 555 MB build for NVIDIA GPUs that also pulls in large NVIDIA libraries. The CPU index serves a CPU-only build. On macOS and Windows the CPU index serves the same build as PyPI, so one command works everywhere. Because NumPy is already installed, this command takes only torch and its small helpers from that index.
- The Hugging Face libraries come third, from PyPI. Transformers loads models, PEFT adds adapters, TRL runs supervised fine-tuning, Datasets reads the course data, Accelerate places work on a device, and bitsandbytes does 4-bit quantisation.
pip checkmust print "No broken requirements found." It confirms the three steps produced a consistent set.
Each command uses a single package index, so pip never mixes builds from two sources in one decision. In the course's test the install took 1,102 seconds (about 18 minutes, on a heavily loaded computer) and the environment was 1.1 GB.
Step 3: the course settings for every session
Four environment variables control how the libraries behave. Rather than
typing them each time, save a small script that activates the environment
and sets them. Save this as ~/finetune-practice/course-env.sh:
# Course environment for LLM Fine-Tuning with LoRA and QLoRA (bash or zsh).
# Run it at the start of every session: source ~/finetune-practice/course-env.sh
source "$HOME/finetune-practice/.venv/bin/activate"
export HF_HOME="$HOME/finetune-practice/hf-cache" # every model download stays in the practice folder
export HF_HUB_DISABLE_TELEMETRY=1 # send no usage data to Hugging Face
export HF_HUB_OFFLINE=1 # never download; a missing file is an error
export TOKENIZERS_PARALLELISM=false # silence a harmless warning in training scripts
On Windows save this as $HOME\finetune-practice\course-env.ps1 instead:
# Course environment for LLM Fine-Tuning with LoRA and QLoRA (Windows PowerShell).
# Run it at the start of every session: . $HOME\finetune-practice\course-env.ps1
. "$HOME\finetune-practice\.venv\Scripts\Activate.ps1"
$env:HF_HOME = "$HOME\finetune-practice\hf-cache" # every model download stays in the practice folder
$env:HF_HUB_DISABLE_TELEMETRY = "1" # send no usage data to Hugging Face
$env:HF_HUB_OFFLINE = "1" # never download; a missing file is an error
$env:TOKENIZERS_PARALLELISM = "false" # silence a harmless warning in training scripts
What each line does:
HF_HOMEis where the Hugging Face libraries keep their cache. By default that is~/.cache/huggingface, outside the practice folder. Here the cache moves inside it, so removing the practice folder removes every model the course downloaded, and nothing else is touched.HF_HUB_DISABLE_TELEMETRY=1turns off the usage data the libraries send by default. The course keeps everything on your computer.HF_HUB_OFFLINE=1makes the libraries use only cached files. Nothing can start a download in the middle of a lesson; a missing file stops a script at once with an error instead.TOKENIZERS_PARALLELISM=falsestops a warning the tokenizer library prints when training loads data in worker processes. It does not change any result.
The libraries read these variables when they are imported, so they must be
set before a script starts. That is why you run course-env.sh in the
terminal first, rather than setting the variables inside each script.
Use it now and at the start of every later session:
source ~/finetune-practice/course-env.sh
In PowerShell: . $HOME\finetune-practice\course-env.ps1 (the leading dot
and space matter: they run the script in your current session).

Everything the course creates lives under one folder. The parts created in this lesson are marked; the rest appear as you work through the course.
Step 4: download the course models
The course uses two models from Hugging Face. Both are Apache-2.0, need no account and are stored in the safetensors format:
| Model | Use | Weights |
|---|---|---|
| SmolLM2-135M-Instruct | The model you fine-tune in almost every lesson | 269 MB |
| SmolLM2-360M-Instruct | The size comparison in the QLoRA lessons | 724 MB |
Save this as ~/finetune-practice/download_models.py:
"""Download the two course models at their pinned revisions and verify them.
Run once from ~/finetune-practice with the course environment active:
python download_models.py
It needs the network, about 1 GB of free disk and a few minutes on a fast
connection. Run it again after an interruption: finished files are kept.
"""
import hashlib
import os
import sys
# This is the one script that may use the network. The setting must change
# before huggingface_hub is imported, because the library reads it on import.
os.environ["HF_HUB_OFFLINE"] = "0"
if "finetune-practice" not in os.environ.get("HF_HOME", ""):
sys.exit("HF_HOME is not set to the course cache. Run: source ~/finetune-practice/course-env.sh")
from huggingface_hub import snapshot_download # noqa: E402
MODELS = {
"SmolLM2-135M-Instruct": ("HuggingFaceTB/SmolLM2-135M-Instruct",
"12fd25f77366fa6b3b4b768ec3050bf629380bac",
"5af571cbf074e6d21a03528d2330792e532ca608f24ac70a143f6b369968ab8c"),
"SmolLM2-360M-Instruct": ("HuggingFaceTB/SmolLM2-360M-Instruct",
"a10cc1512eabd3dde888204e902eca88bddb4951",
"e6bffe7435d7ddc10fd3b9a9efd429dafbacb1cb17015fb5562664e7532bf86e"),
}
# Only the files a model needs: no pickle files, ONNX exports or training logs.
NEEDED = ["config.json", "generation_config.json", "tokenizer.json", "tokenizer_config.json",
"special_tokens_map.json", "vocab.json", "merges.txt", "model.safetensors"]
def sha256(path):
digest = hashlib.sha256()
with open(path, "rb") as f:
for block in iter(lambda: f.read(1 << 20), b""):
digest.update(block)
return digest.hexdigest()
for name, (repo, revision, expected) in MODELS.items():
folder = snapshot_download(repo, revision=revision, allow_patterns=NEEDED)
ok = sha256(os.path.join(folder, "model.safetensors")) == expected
print(f"{name:<24} {'checksum OK' if ok else 'CHECKSUM MISMATCH'} {folder}")
if not ok:
sys.exit(f"{name}: the weights do not match the pinned checksum; see the lesson's diagnosis table")
How it works:
- Offline for every other script.
course-env.shturns offline mode on, so this one script turns it off for itself, before importinghuggingface_hub, because the library reads the setting on import. TheHF_HOMEcheck stops the script if you forgotcourse-env.sh, which would otherwise put 1 GB of models in your default cache. revisionis the full 40-character commit hash of the model repository. A repository can change after this course was written: new weights, a new chat template, a new default setting. Pinning the revision means you get exactly the files the lessons were tested with. A shortened hash is not accepted.allow_patterns=NEEDEDdownloads only the configuration, tokenizer and weights. The repository also holds a pickle file of training arguments and several ONNX exports, which the course never needs.- The SHA-256 check compares the weights file with the checksum the Hugging Face API reported for that revision. A match proves the file is complete and unchanged.
snapshot_download stores files in the cache under
hub/models--HuggingFaceTB--SmolLM2-135M-Instruct/snapshots/<revision>/
and returns that folder. Do not edit files there; later scripts find the
models by repository name and revision, never by path.
Run it from ~/finetune-practice:
python download_models.py
Output from the course's test (illustrative; your cache path differs):
SmolLM2-135M-Instruct checksum OK /Users/you/finetune-practice/hf-cache/hub/models--HuggingFaceTB--SmolLM2-135M-Instruct/snapshots/12fd25f77366fa6b3b4b768ec3050bf629380bac
SmolLM2-360M-Instruct checksum OK /Users/you/finetune-practice/hf-cache/hub/models--HuggingFaceTB--SmolLM2-360M-Instruct/snapshots/a10cc1512eabd3dde888204e902eca88bddb4951
In the test this took 207 seconds for both models, and the cache was about 1 GB. Progress bars ("Fetching 8 files") appear while it runs. Hugging Face may also print a warning that you are sending unauthenticated requests and could set a token for faster downloads. The course models need no account, and you can ignore it.
On a slow or interrupted connection, run the script again. Finished files are kept. A file that was still downloading may start again from the beginning, and progress bars can stand still for minutes while large chunks arrive.
Step 5: check everything
Save this as ~/finetune-practice/check_setup.py:
"""Check the course environment before any lesson uses it.
Run from ~/finetune-practice with the course environment active:
python check_setup.py
Every line starts with ok or FAIL; the last line says whether all passed.
"""
import importlib.metadata as metadata
import os
import sys
PINS = {"numpy": "2.5.4", "torch": "2.14.1", "transformers": "5.20.2", "peft": "0.21.2",
"trl": "1.16.0", "datasets": "5.1.0", "accelerate": "1.15.0", "bitsandbytes": "0.50.2"}
MODELS = {"HuggingFaceTB/SmolLM2-135M-Instruct": "12fd25f77366fa6b3b4b768ec3050bf629380bac",
"HuggingFaceTB/SmolLM2-360M-Instruct": "a10cc1512eabd3dde888204e902eca88bddb4951"}
failures = []
def report(ok, label, detail):
print(f"{'ok ' if ok else 'FAIL'} {label:<26} {detail}")
if not ok:
failures.append(label)
# 1. The interpreter: the course environment, on a supported Python.
report(sys.prefix != sys.base_prefix and "finetune-practice" in sys.prefix,
"course environment", sys.executable)
report((3, 12) <= sys.version_info[:2] <= (3, 14), "Python 3.12 to 3.14", sys.version.split()[0])
# 2. The pinned libraries, and a CPU build of torch.
for package, version in PINS.items():
try:
installed = metadata.version(package)
except metadata.PackageNotFoundError:
installed = "not installed"
report(installed.split("+")[0] == version, package, installed)
import torch # noqa: E402
report(torch.version.cuda is None, "torch CPU build", f"cuda={torch.version.cuda}")
print(f"info Apple GPU (MPS) available: {torch.backends.mps.is_available()}; "
f"CUDA available: {torch.cuda.is_available()} (the course uses the CPU)")
# 3. The course settings from course-env.sh.
report("finetune-practice" in os.environ.get("HF_HOME", ""), "HF_HOME", os.environ.get("HF_HOME"))
report(os.environ.get("HF_HUB_OFFLINE") == "1", "HF_HUB_OFFLINE=1", os.environ.get("HF_HUB_OFFLINE"))
report(os.environ.get("HF_HUB_DISABLE_TELEMETRY") == "1", "HF_HUB_DISABLE_TELEMETRY=1",
os.environ.get("HF_HUB_DISABLE_TELEMETRY"))
# 4. 4-bit quantisation works on this CPU (x86 CPUs need AVX2).
try:
import bitsandbytes.functional as F
weights = torch.randn(64, 64)
packed, state = F.quantize_4bit(weights, quant_type="nf4")
restored = F.dequantize_4bit(packed, state, quant_type="nf4")
error = (restored - weights).abs().mean().item()
report(error < 0.2, "NF4 quantisation", f"mean round-trip error {error:.3f}")
except Exception as exc: # report the failure instead of stopping the check
report(False, "NF4 quantisation", f"{type(exc).__name__}: {exc}")
# 5. Both models load offline from their pinned revisions.
from transformers import AutoModelForCausalLM # noqa: E402
for repo, revision in MODELS.items():
name = repo.split("/")[1]
try:
model = AutoModelForCausalLM.from_pretrained(repo, revision=revision, dtype=torch.float32)
count = sum(p.numel() for p in model.parameters())
report(True, name, f"{count:,} parameters, loaded offline")
del model
except Exception as exc:
report(False, name, f"{type(exc).__name__}: {str(exc)[:120]}")
print("\nAll checks passed." if not failures else f"\n{len(failures)} check(s) failed: {', '.join(failures)}")
sys.exit(1 if failures else 0)
It checks five things in order, and keeps going after a failure so that you see every problem at once:
- The interpreter.
sys.prefixdiffers fromsys.base_prefixonly inside a virtual environment, and the path must be the course's environment. - The libraries. Each installed version is compared with its pin.
torch.version.cudaisNonefor a CPU build. The line about the Apple GPU and CUDA is information only: the course trains on the CPU either way. - The settings from
course-env.sh. - 4-bit quantisation. A small random matrix is packed into 4-bit NF4 and restored. A small error is expected, because that is what quantisation does; the QLoRA lessons explain it. On an x86 CPU without AVX2 this step fails.
- The models. Each model loads from its pinned revision with
HF_HUB_OFFLINE=1, so a missing file fails here, not halfway through a later lesson.
Run it from ~/finetune-practice:
python check_setup.py
Output from the course's test on macOS (illustrative; paths, the NF4 error and the device line differ by computer):
ok course environment /Users/you/finetune-practice/.venv/bin/python
ok Python 3.12 to 3.14 3.13.0
ok numpy 2.5.4
ok torch 2.14.1
ok transformers 5.20.2
ok peft 0.21.2
ok trl 1.16.0
ok datasets 5.1.0
ok accelerate 1.15.0
ok bitsandbytes 0.50.2
ok torch CPU build cuda=None
info Apple GPU (MPS) available: True; CUDA available: False (the course uses the CPU)
ok HF_HOME /Users/you/finetune-practice/hf-cache
ok HF_HUB_OFFLINE=1 1
ok HF_HUB_DISABLE_TELEMETRY=1 1
ok NF4 quantisation mean round-trip error 0.075
ok SmolLM2-135M-Instruct 134,515,008 parameters, loaded offline
ok SmolLM2-360M-Instruct 361,821,120 parameters, loaded offline
All checks passed.
Between these lines you will also see "Loading weights" progress bars, and on macOS torch may print a warning ending "Redirects are currently not supported in MacOs." Both are harmless.
The last line is what matters. "All checks passed." means the environment matches the one every later lesson was tested with. Exit code 0 confirms it for scripts.
Files the course never loads
Some files that look like models can run code on your computer when they are loaded:
- Pickle files (often
.bin,.ptor.pkl). Python's pickle format can carry instructions that run while the file loads. Hugging Face scans uploaded pickle files, but says the scan is not foolproof. - Remote code. Some repositories ship Python code that runs when the
model loads, if you pass
trust_remote_code=True.
The course therefore follows three rules:
- it loads weights only in the safetensors format, which stores numbers and nothing else;
- it downloads only the files a model needs;
- it never sets
trust_remote_code.
Later you will meet pickle files that the libraries write themselves, such
as training_args.bin beside every saved adapter. Your own files are safe
to keep. The rule is about loading files from anyone else.
When your result differs
| What you see | Likely cause | What to do |
|---|---|---|
On Windows, Activate.ps1 or course-env.ps1 will not run, with a message that running scripts is disabled on this system | PowerShell's execution policy blocks scripts, which is the default on many Windows computers | The Python documentation's fix allows scripts for your user only: Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope CurrentUser. It changes a security setting, so decide whether you accept it; it is not undone by removing the practice folder |
check_setup.py fails "course environment" and the path is not in finetune-practice | The environment is not active, so the system Python ran | Run source ~/finetune-practice/course-env.sh (PowerShell: . $HOME\finetune-practice\course-env.ps1) and run the check again |
On Linux, the torch download is about 555 MB and pip freeze lists nvidia- packages | torch came from PyPI instead of the CPU index | Remove .venv, create it again, and repeat Step 2 with the --index-url line exactly as shown |
pip reports that no matching distribution was found for torch==2.14.1 | Your Python is outside 3.12 to 3.14 (for example 3.15 or 3.11), or the computer is an Intel Mac or Windows on Arm | Install a supported Python, or use a supported computer, and start again from Step 1 |
| pip stops with a read timeout on a slow connection | The network, not the course | Add --timeout 120 to the pip command that failed and run it again |
download_models.py stops with "HF_HOME is not set to the course cache" | course-env.sh was not run in this terminal | Run it, then the download again |
download_models.py reports a checksum mismatch | An incomplete or altered file in the cache | Remove that model's folder under hf-cache/hub/ and run the download again |
A model line in check_setup.py fails with an error about offline mode or a missing file | The download did not finish, or HF_HOME points to another cache | Run download_models.py again, then the check |
| "NF4 quantisation" fails on an x86 computer | The CPU lacks AVX2, which bitsandbytes' CPU build needs | The 4-bit lessons cannot run on this computer; every other lesson can. Consider the optional GPU module, or another computer, for those lessons |
Your turn: diagnose four setups
A classmate ran check_setup.py on four different computers and sent you
one line from each run. For each line, name the cause, the evidence and
the fix before reading on.
FAIL course environment /usr/bin/python3FAIL torch CPU build cuda=13.…(a CUDA 13 version number; the exact one varies)FAIL SmolLM2-360M-Instruct OSError: We couldn't connect to 'https://huggingface.co' to load the files, and couldn't find them in the cached files.FAIL NF4 quantisationfollowed by an error from bitsandbytes, on a ten-year-old Intel laptop running Linux
Try all four before reading the hints and the answers below.
Hints
- Each line names the check that failed. Map it to one of the five parts of the check script.
- For line 3, ask what
HF_HUB_OFFLINE=1does when a file is missing.
Answers and reasoning
- The environment was not active. The path shows the system Python,
not
~/finetune-practice/.venv. Fix: runcourse-env.sh, then the check again. - A CUDA build of torch was installed.
torch.version.cudareports a CUDA version, so torch came from PyPI on Linux (a build that depends on NVIDIA's CUDA 13 libraries) rather than from the CPU index. Fix: recreate the environment and install torch with the--index-urlline. - The 360M model is missing from the cache. With offline mode on, the
library could not use the network, and the files were not cached:
either the download stopped early, or
HF_HOMEpointed elsewhere when it ran. Fix: rundownload_models.pyagain withcourse-env.shactive. - The CPU probably lacks AVX2. That instruction set is needed by bitsandbytes' x86 CPU build, and older Intel processors may not have it. Fix: the 4-bit lessons need another computer or the optional GPU module; everything else still works.
A common mistake with line 3 is to turn offline mode off and run the
lesson's script anyway. That works, but it downloads the model
mid-lesson, without the revision check and checksum that
download_models.py gives you.
Reset and cleanup
Keep everything this lesson created: every later lesson uses the
environment, the cache, course-env.sh and the check script. You may
remove ~/finetune-practice/setup after a path check:
cd ~/finetune-practice && pwd
rm -rf setup
pwd must print a path ending in finetune-practice. To start the whole
setup again from nothing, remove ~/finetune-practice itself; the final
challenge explains how to do that safely when you finish the course.
Check your understanding
- Why does the course install torch from a different index from the other libraries?
- You forget to run
course-env.shand rundownload_models.py. What happens, and why does the script behave that way? - A repository's newest revision has an improved chat template. Why does the course still download the older pinned revision?
Answer the questions before reading on.
Answers
- On Linux the ordinary PyPI package is a large build for NVIDIA GPUs; the CPU index serves a CPU-only build. Using one command for every platform keeps the instructions identical, and installing NumPy first means the CPU index supplies only torch.
- It stops with the message that
HF_HOMEis not set. Withoutcourse-env.sh, the models would go to the default cache outside the practice folder, and cleanup would miss them. - Every lesson was tested with the pinned files. A newer template or weights file could change what the model produces and how the training data is formatted, so the lessons' results and explanations might no longer hold. The course updates a pin only after retesting.
Readiness answer
Skip rows that do not have the key:
def count_values(rows, key):
counts = {}
for row in rows:
if key not in row:
continue
counts[row[key]] = counts.get(row[key], 0) + 1
return counts