You have a notebook that trains a model. It works today. Next month you reinstall a package, and it fails. Or a friend runs it and gets different numbers, or an error on line 3. Or you try an idea, break everything, and cannot get back to the version that worked. Or you push your project to GitHub and an hour later your cloud bill shows someone else’s usage, because the key was in the code.
None of these is a machine-learning problem. All of them stop ML work. This last lesson of Part 2 teaches the three tools that prevent them: environments (so the packages are the same), Git (so every version is kept and shared safely), and the Hugging Face Hub (so you can start from a pretrained model, with its version pinned). It ends with the promise of the title: a real model, loaded in five lines.
How to use this page. The commands here run in a terminal on your own computer, not in the cells on this site, so the outputs you see were produced on the author’s Linux machine (Python 3.12, Git 2.53, pip 25.0, uv 0.13, transformers 4.57, in December 2026). Your numbers, paths and hashes will differ. If a command does not work for you, read the official page named in the text: tools change faster than lessons. P0.4 showed how to create and activate a virtual environment, and this lesson builds on it.
Why every project needs its own environment
Python programs use packages: code written by other people, such as NumPy. A package has versions, and versions change behaviour. NumPy 2.0 removed the name np.float_, for example. Code written for the old version fails on the new one:
AttributeError: `np.float_` was removed in the NumPy 2.0 release. Use `np.float64` instead.
Now picture two projects on one computer. Project A is an old tutorial that uses np.float_. Project B needs a new library that requires NumPy 2. If both share one set of installed packages, you can have only one NumPy, so one of them breaks. This is a dependency conflict, and it is the most common reason that “it worked yesterday”.
An environment solves it. It is a private folder holding a Python and its own copy of the packages, for one project. Project A gets the old NumPy, project B the new one, and neither touches the other, or the Python that your operating system uses.
The second reason is reproducibility. A saved environment description (a list of exact versions) lets a friend, a teacher or your future self rebuild the same setup. Models are sensitive to this: a different library version can change a default, a random number stream or a numerical detail, so the same code can give a different result (P1.G3).
venv and pip: the built-in way
venv ships with Python, and pip is Python’s package installer. P0.4 showed how to make and activate an environment (python3 -m venv .venv, then the activate line for your system). Here is what you do with it afterwards.
Check that you are inside it. After activation your prompt usually starts with (.venv). To be sure, ask Python itself:
which python # Linux and macOS: should point inside .venv
python -c "import sys; print(sys.prefix != sys.base_prefix)"
/home/ada/proj/.venv/bin/python
True
True means this Python is a virtual environment. (On Windows use where python.) Outside any environment the second line prints False.
Install and list packages. Always call pip as python -m pip. That guarantees the pip belongs to the Python you are running, and not to some other Python on your computer.
python -m pip install numpy
python -m pip list
Package Version
------- -------
numpy 2.5.5
pip 25.0.1
A new environment holds only pip (and sometimes a few tools) until you install something. Your numbers will differ.
Record what you installed. pip freeze prints every installed package with its exact version, in a format that pip install can read back. Save it in a file named requirements.txt, which is the common convention, and restore with -r:
python -m pip freeze > requirements.txt
python -m pip install -r requirements.txt
numpy==2.5.5
The second command, run in a brand-new environment, installs exactly the listed versions. In the demo, pip freeze in a second environment built this way printed the same line.
Pinning. A version specifier tells pip which versions are acceptable:
| Written as | Means |
|---|---|
numpy==2.5.5 | exactly this version (use it to reproduce a result) |
numpy>=2,<3 | any 2.x version |
numpy~=2.1.0 | 2.1.0 or newer, but below 2.2 (a “compatible release”: patch updates only) |
numpy | whatever is newest today (quick experiments only) |
In a shell, put a specifier with > or < in quotes (pip install "numpy>=2,<3"), because otherwise the shell reads > as “write to a file”.
Two honest limits. pip freeze lists everything, including the packages that your packages pulled in, so the file can be long, and it records versions for your operating system and Python. And requirements.txt does not record which Python you used, so write that down too (a line in the README is enough).
Common slips. Forgetting to activate (the install goes to the wrong Python, and then import fails); installing with a bare pip that belongs to another Python; moving or copying the .venv folder (it contains absolute paths, so create a new one from requirements.txt instead); and committing .venv to Git (never: it is rebuildable, and large). To leave an environment type deactivate. To delete it, delete the folder.
Go deeper Using the environment in Jupyter, and a note on Docker
A notebook runs in a kernel, which is a Python. If you start JupyterLab from a different Python than the one in your environment, your notebook cannot see your packages. The simplest fix is to install JupyterLab inside the same environment (P0.4). To use one environment from another JupyterLab, register it as a kernel: python -m ipykernel install --user --name myenv (the ipykernel package must be installed in that environment). In Colab you do not do this: the notebook runs on Google’s computer, with its own preinstalled packages, and pip install inside a cell adds to that session only.
Docker goes one step further than an environment: a container packages the operating system libraries as well, so it also fixes problems that Python packages cannot (a missing system library, a different Linux). It is outside this lesson; the course returns to deployment in P12.4.
conda and uv: two other tools
venv plus pip is enough for many projects. Two other tools are common in ML, and you will see them in tutorials and on teammates’ computers.
conda
conda is a package manager and environment manager that is not limited to Python. A conda package can be a Python library, but also a compiled library, a compiler, or Python itself. That is the case where it helps most: a project that needs a non-Python dependency that is hard to install otherwise. It also lets one machine hold environments with different Python versions.
conda create -n ml python=3.12
conda activate ml
conda install numpy
conda deactivate
conda env list
Save and rebuild an environment with a file called environment.yml:
conda env export --from-history > environment.yml
conda env create -f environment.yml
The conda documentation explains why --from-history matters: a plain conda env export writes every package including platform-specific ones, and may not work on another operating system. --from-history writes only what you asked for, which is more portable.
If you must use pip inside a conda environment, a common rule is to install with conda first and with pip last, and not to go back and forth. More about conda (channels, GPUs) is in the box after the uv section.
uv
uv is a newer tool, written in Rust, from the company Astral. It aims to replace venv, pip and more, with one fast program. Its documentation describes it as much faster than pip; this lesson does not time it. Install it by following docs.astral.sh/uv (the page lists several ways, and python -m pip install uv is one of them).
Used as a drop-in for the pip workflow:
uv venv # creates .venv in this folder
source .venv/bin/activate # Windows cmd: .venv\Scripts\activate.bat
# PowerShell: .\.venv\Scripts\Activate.ps1
uv pip install numpy
uv pip freeze > requirements.txt
Or in its project mode, where uv keeps the list of packages in a file called pyproject.toml and the exact resolved versions in a lockfile, uv.lock:
uv init # creates pyproject.toml, .python-version and more
uv add numpy # adds it to pyproject.toml, updates uv.lock, installs into .venv
uv run python script.py # runs inside the project environment
uv sync # makes .venv match uv.lock (on a fresh clone)
In this demo (uv 0.13), uv init made .python-version, README.md, pyproject.toml and a src folder (and a Git repository, plus a .gitignore); the uv documentation says this src layout is the default for an application since uv 0.12, and that --no-package makes a main.py instead. The first uv add numpy created .venv and uv.lock. The uv documentation says the lockfile should be committed to Git, so that everyone gets the same versions.
A lockfile is the important idea. pyproject.toml says what you want (a range such as numpy>=2.5.5, or whatever you wrote). The lockfile says what was chosen (numpy 2.5.5 exactly, and every package below it, with checksums). Rebuilding from the lockfile gives the same environment everywhere, which is more reliable than pip freeze, because the file is made for that purpose.
Go deeper More about conda, and how uv finds an environment
A conda environment is not a venv, and the two do not mix: use one or the other for a given project.
Channels and terms. Conda gets packages from channels, and the channel decides the licence terms. Anaconda’s default channel has terms of service that apply to some organisations, and the community channel conda-forge is a separate, free one (the Miniforge installer uses it by default). Read the terms that apply to your use before you rely on a channel at work.
GPUs (a hedge). For PyTorch, the pip wheels from PyTorch’s own install page bring the CUDA libraries they need as pip packages, so a CUDA toolkit is not something you must install by hand for most beginner uses. You still need a recent enough NVIDIA driver. Follow the selector on pytorch.org for your system, because the exact command changes with each release.
Gotcha: which environment does uv pip install use? It does not simply use the .venv in your folder. The uv documentation lists its order: an activated virtual environment first, then an activated conda environment, and only then a .venv in the current folder or a parent. In this demo, with a conda environment active, uv used the conda environment and not the new .venv. The line Using Python 3.12.12 environment at: ... that uv prints tells you which one it chose. Read it.
Which one should I use?
All three work, and many people use more than one. A short guide:
- Just starting, small project, only Python packages:
venvandpip. It is built in and is what most tutorials assume. - You want speed, and a lockfile with a project file: uv.
- You need a non-Python library or a specific Python version that is hard to get, or your team or cluster already uses it: conda.
- Joining an existing project: use what its README says, even if you would pick something else.
- Never: two tools managing the same environment.
Intuition
An environment is a separate toolbox for each job. If you keep every tool in one drawer, a new hammer pushes out the old one, and the job that needed the old one fails. The saved list (requirements.txt or the lockfile) is the shopping list that lets anyone refill an identical toolbox.
Where the picture breaks: a toolbox is the same on every shelf, but package files are built for an operating system and a Python version. The same list can install different files on another computer. That is why the Python version, and sometimes the operating system, belong in your notes.
Math
There is no formula here, but there is one rule worth knowing: version numbers are a promise, not a guarantee. Many projects use semantic versioning, written MAJOR.MINOR.PATCH (2.5.5). The idea is that a PATCH release fixes bugs, a MINOR release adds features without breaking old code, and a MAJOR release may break it. NumPy 1 to NumPy 2 was a major release, and np.float_ went away with it. Not every project follows the rule exactly, which is why a pin with == is the safe choice when you need the same result.
Code
A habit that costs five lines: print the versions at the top of every experiment, and save them with the results.
import sys, platform
import numpy as np
print("python", sys.version.split()[0], platform.system())
print("numpy ", np.__version__)python 3.12.12 Linux
numpy 2.5.5(Run in the demo environment from above. In a real project, add every package that matters, such as torch.__version__.)
Git: a save point for every version
Git is a program that records the history of a folder. Each time you ask, it stores a snapshot of your files, called a commit, with a message and a date. You can look at old snapshots, compare them, go back, and work on two ideas at once. GitHub is a website that hosts Git repositories so that you can back them up and share them. Git is the tool, GitHub is one place to keep a copy (GitLab and others also exist).
Why ML needs it: you try ideas all the time, and most of them fail. With Git, a failed idea costs you one command to undo. And “the code that produced this result” becomes a short commit ID that you can write next to the result.
The mental model: three places
A file passes through three places:
- The working folder: the files you edit.
- The staging area: the changes you have chosen to include in the next snapshot (
git add). - The repository: the saved commits (
git commit).
A remote is another copy of the repository, usually on GitHub. git push sends your commits there and git pull brings new ones back.
| Place | Holds | Moves forward with |
|---|---|---|
| Working folder | your files as you edit them | (you edit) |
| Staging area | the changes chosen for the next commit | git add |
| Local repository | saved commits | git commit |
| Remote (GitHub) | a shared copy | git push (and git pull back) |
One session, step by step
This is a real session, with a tiny train.py (the output of a few commands is trimmed). Hashes such as 69c7400 will be different on your computer.
git init -b main
git status
On branch main
No commits yet
Untracked files:
(use "git add <file>..." to include in what will be committed)
.env
.venv/
data/
train.py
git init makes the folder a repository (the history lives in a hidden .git folder, which you never edit by hand). git status is the command you will use most: it shows what Git sees. “Untracked” means Git has never been told about the file. Notice that .env, .venv/ and data/ are listed: we do not want those in Git. That is the job of .gitignore: create a file with that name that lists, one per line, what Git should ignore (the file in the next box is the one used here), and look at the status again:
.venv/
data/
.env
*.pt
__pycache__/
git status --short
?? .gitignore
?? train.py
The ignored items disappeared from the list. Now take the first snapshot:
git add train.py .gitignore
git commit -m "First version"
[main (root-commit) 69c7400] First version
Edit the file (change a learning rate from 0.1 to 0.01), then look at the change before you save it:
git diff
@@ -1,2 +1,2 @@
import numpy as np
-lr = 0.1
+lr = 0.01
Lines starting with - were removed and lines starting with + were added. git diff compares the working folder with the staging area; git diff --staged compares the staging area with the last commit. Then commit (-a stages every tracked file that changed, -m gives the message):
git commit -am "Lower learning rate"
Branches. A branch is a separate line of work. Try an idea on one without risking main:
git switch -c try-adam # create a branch and move to it
# ... edit, then: git commit -am "Try Adam"
git switch main # go back
git merge try-adam # bring the work into main
git log --oneline
git branch
Updating c3e2f07..74e028e
Fast-forward
train.py | 1 +
74e028e Try Adam
c3e2f07 Lower learning rate
69c7400 First version
* main
try-adam
git log --oneline shows the history, newest first. git branch lists branches, and * marks the one you are on. Here main had not changed since the branch started, so the merge was a fast-forward: Git simply moved main ahead. (Older tutorials use git checkout for what git switch and git restore do now. It still works.)
Sharing. Create an empty repository on GitHub, then connect it and send your commits:
git remote add origin https://github.com/YOUR-NAME/YOUR-REPO.git
git push -u origin main
branch 'main' set up to track 'origin/main'.
(This demo pushed to a local folder instead of GitHub, so only the last line is shown.) origin is the usual name of the remote, and -u remembers the link so later you can type just git push. To get a copy of someone else’s project, use git clone URL, which downloads the whole history into a new folder. To get new commits from the remote, use git pull. GitHub no longer accepts your account password for Git over HTTPS: it asks for a personal access token or an SSH key, or you can sign in with GitHub’s gh tool (see GitHub’s documentation for the current steps).
The commands at a glance:
| I want to | Command |
|---|---|
| start a repository / copy one | git init / git clone URL |
| see what changed | git status, git diff |
| choose changes for the next snapshot | git add FILE |
| save a snapshot | git commit -m "message" |
| undo edits to a file I have not staged | git restore FILE |
| see history | git log --oneline |
| make and move between branches | git switch -c NAME, git switch NAME |
| join a branch into the current one | git merge NAME |
| send / get commits | git push, git pull |
| stop tracking a file but keep it on disk | git rm --cached FILE (add -r for a folder) |
git restore FILE throws away your unsaved edits to that file, and Git cannot bring them back, so use it on purpose. Good commit messages say what and why in a few words (“Lower learning rate to stop loss spikes”), and a commit does best when it holds one idea.
Go deeper A merge conflict, and what it looks like
If two branches changed the same line, Git cannot choose. It stops, marks the file, and asks you. This one was produced on purpose:
Auto-merging cfg.py
CONFLICT (content): Merge conflict in cfg.py
Automatic merge failed; fix conflicts and then commit the result.<<<<<<< HEAD
lr = 0.05
=======
lr = 0.01
>>>>>>> aThe part between <<<<<<< and ======= is your current branch, and the part below it is the branch you merged. Edit the file to what you want, delete the three marker lines, run git add cfg.py and git commit. To give up on the merge, run git merge --abort. A conflict is not an error in Git: it is Git asking a question only you can answer.
Other things that were left out on purpose: git stash, rebasing, pull requests (the GitHub way of proposing a branch for review), and tags. They matter in team projects. The Git book at git-scm.com covers them.
What belongs in Git, and what does not
Git keeps every version of every file, forever, and every clone downloads all of it. That suits source code, which is small text. It does not suit the things ML projects produce.
| Put in Git | Keep out of Git |
|---|---|
Source code (.py, and notebooks, with care) | The environment folder .venv/ (rebuild it from requirements.txt or uv.lock) |
requirements.txt, environment.yml, uv.lock, pyproject.toml | Datasets, which are large and may have their own licence |
| A README, configuration files, small test data | Model checkpoints and weights (.pt, .pth, .ckpt, .safetensors) |
.gitignore, and .env.example (names only, no values) | Secrets: API keys, passwords, tokens, the real .env file |
A starting .gitignore for an ML project (the lines starting with # are comments):
# environments
.venv/
# secrets
.env
# data and model files
data/
*.pt
*.ckpt
*.safetensors
# Python and notebook leftovers
__pycache__/
.ipynb_checkpoints/
Large files. GitHub’s documentation says it warns about files over 50 MiB and blocks files over 100 MiB, and it recommends keeping a whole repository ideally under 1 GB. Deleting a big file in a later commit does not help, because the old commit still holds it. Two tools exist for large files, and this lesson only names them: Git LFS keeps pointers in Git and stores the big files on a separate server, and DVC (Data Version Control) tracks data and model files in storage that you choose, next to your Git history. For models, the Hugging Face Hub (below) is itself a place that stores big files.
Notebooks. A .ipynb file is text, so Git can store it, but it also contains the outputs and some metadata, so its diffs are noisy. Keep the committed notebook small, and consider clearing outputs before you commit.
Never commit a secret
An API key is a password that lets a program use a paid or private service. If you put one in code and push it to GitHub, treat it as public: automated programs scan public repositories for keys. (Whether the repository is private or public, the key is still in the history.)
Keep keys out of the code. Read them from an environment variable:
import os
token = os.environ.get("HF_TOKEN") # None if the variable is not set
and keep the value in a local .env file or your shell settings, which .gitignore excludes. Commit a .env.example that lists the names with empty values, so others know what to set.
If you committed a key anyway: (1) revoke or rotate it at once, in the service’s website, so the old key stops working. This is the step that actually protects you. (2) Only then, if you want it out of the history, rewrite the history with a tool such as git filter-repo (GitHub’s documentation describes the steps), knowing that clones and forks may still hold the old commits. (3) Add the file to .gitignore, and use a secrets scanner or push protection next time. Deleting the line in a new commit is not enough: the old commit still contains the key.
The Hugging Face Hub: pretrained models
Training a model from nothing needs a lot of data and compute. A pretrained model has already been trained by someone else, and you can use it, or fine-tune it (P5.10), instead of starting from zero. The Hugging Face Hub (huggingface.co) is the biggest public place to find them: a website where people share models, datasets and small demo apps. Each one is a Git repository, which is why this lesson comes right after Git.
Each model has an ID of the form owner/name, such as distilbert/distilbert-base-uncased-finetuned-sst-2-english, and a model card: the page that says what the model is, what it was trained on, how to use it, its limits, and its licence.
Check the licence before you use a model. Licences differ. This model’s card says Apache-2.0, a permissive licence that allows commercial use with conditions (keep the notice). Other models use custom licences, forbid some uses, or ask you to accept terms and sign in before you can download (“gated” models). Reading the card takes two minutes and avoids trouble later.
Load a model in 5 lines
The model for this lesson:
| Property | Value |
|---|---|
| Name | distilbert/distilbert-base-uncased-finetuned-sst-2-english |
| What it does | classifies English text as POSITIVE or NEGATIVE (fine-tuned on the SST-2 movie-review sentences) |
| Licence | Apache-2.0 (from the model card) |
| Download | one weight file of 268 MB (267,832,558 bytes), plus small files |
| Size | 66,955,010 parameters |
| Needs | CPU only, no account, no key, no GPU |
The five lines (the revision is the model’s Git commit, explained below):
from transformers import pipeline
classifier = pipeline("sentiment-analysis",
model="distilbert/distilbert-base-uncased-finetuned-sst-2-english",
revision="714eb0fa89d2f80546fda750413ed43d93601a13")
print(classifier(["I loved this film.", "The battery died after one day."]))
[{'label': 'POSITIVE', 'score': 0.9998805522918701}, {'label': 'NEGATIVE', 'score': 0.9993789196014404}]
You can run it yourself in the companion notebook, which needs no account and no GPU: open it in Colab. The first run downloads about 268 MB, so use a Wi-Fi connection if your data is limited. On your own computer, install transformers and torch into a virtual environment first (python -m pip install transformers torch; PyTorch is a large download, so check pytorch.org for the right build).
What pipeline just did, in order: (1) it looked up the model ID on the Hub and downloaded its files into a local cache; (2) it turned each sentence into integer tokens with the model’s tokenizer (P10.A2); (3) it ran the model, which outputs two raw scores called logits; (4) it turned them into probabilities with a softmax (P3.A8 teaches it) and picked the larger one. The score is that probability. You can do the same steps by hand, and the notebook does:
from transformers import AutoTokenizer, AutoModelForSequenceClassification
tok = AutoTokenizer.from_pretrained(name, revision=rev)
model = AutoModelForSequenceClassification.from_pretrained(name, revision=rev)
from_pretrained(ID) is the call behind everything on the Hub: it downloads (or reads from the cache) and builds the object. In the notebook, the first sentence becomes the tokens ['[CLS]', 'i', 'loved', 'this', 'film', '.', '[SEP]'] (the tokenizer lowercases it and adds two special tokens), the model gives the logits -4.35 for NEGATIVE and 4.68 for POSITIVE, and softmax turns these into 0.00012 and 0.99988.
Device. This ran on the CPU: with no GPU available, the run printed Device set to use cpu, and you can choose the device yourself with the device argument of pipeline. Small models like this one are fine on a CPU. Big language models are the case where a GPU or a smaller, compressed version of the model matters, and the course says so when it gets there.
The cache: where did the 268 MB go?
Downloaded files go into a cache so that the next run reads them from disk. By default it is the folder ~/.cache/huggingface/hub (your home folder, on every system). The environment variable HF_HOME moves the whole Hugging Face folder, and HF_HUB_CACHE moves only this cache. Inside, each model has a folder named models--owner--name, and in it the files of each downloaded revision. From the notebook:
models--distilbert--distilbert-base-uncased-finetuned-sst-2-english/snapshots/714eb0fa.../config.json
models--distilbert--distilbert-base-uncased-finetuned-sst-2-english/snapshots/714eb0fa.../model.safetensors
models--distilbert--distilbert-base-uncased-finetuned-sst-2-english/snapshots/714eb0fa.../tokenizer_config.json
models--distilbert--distilbert-base-uncased-finetuned-sst-2-english/snapshots/714eb0fa.../vocab.txt
distilbert/distilbert-base-uncased-finetuned-sst-2-english 268.1M on disk, 4 files
(The hash is shortened here.) Models add up: a few large ones can fill a laptop disk. The hf command-line tool that comes with huggingface_hub can show and delete cached models (see hf cache --help, because the exact subcommands changed between versions), and in Python huggingface_hub.scan_cache_dir() lists what is cached. To use only what is cached and never go online, set the environment variable HF_HUB_OFFLINE=1.
Pin the revision
A Hub repository is a Git repository, and the authors can change it: a new model file, a new tokenizer. If your code says only model="owner/name", you get whatever main holds today. The argument revision= accepts a branch, a tag or a commit hash. A commit hash never changes, so it is the way to make “the same model” mean the same weights next year. The notebook checks that the hash used here resolves to itself on the Hub. Where do you find a hash? On the model page, in the tab with the commit history, or by asking the API (HfApi().model_info(ID).sha).
Pinning costs you updates: you will not get a fix unless you change the hash. For a course exercise or a research result, pin. For a quick demo, main is fine.
Safety: two things to know before you download
1. trust_remote_code. Most models use code that is inside the transformers library. A few repositories ship their own Python files that define a new architecture. from_pretrained(..., trust_remote_code=True) would run that code on your computer. The documentation says to use it only for repositories you trust and whose code you have read. The default is False; leave it so. If a tutorial tells you to set it to True, open the repository’s .py files first.
2. Weight files: pickle or safetensors. A model’s weights are stored in a file. The older PyTorch format (.bin or .pt) is built on Python’s pickle, and the Hugging Face security documentation warns that loading a pickle can execute arbitrary code, so you should load pickled models only from sources you trust. safetensors (.safetensors) is a format made by Hugging Face that holds only the tensors and a small header, so loading it does not run code. That is why the notebook shows that only model.safetensors was downloaded, even though the repository also has a pytorch_model.bin: transformers prefers safetensors when the repository has it.
You can see why pickle is dangerous without any risk. This cell builds a pickle whose loading calls print. It only prints a sentence, but it could have called anything:
Runs real Python in your browser. First run downloads about 6 MB (once; your browser keeps it).
this code ran while loading the data
loaded value: None
The line was printed by the loading, not by anything we called. Replace print by something harmful and the same would happen. This is why the rule is: do not unpickle data from a source you do not trust. The Hub scans uploads and shows the imports that a pickle file uses, but its documentation says the scan is not foolproof.
Go deeper Datasets, tokens for private models, and downloading without code
The Hub also hosts datasets, with their own cards and licences (the datasets library loads them, and P2.5 showed the pandas way to look at tables). Some models and datasets are gated: you create a free account, accept the terms on the model page, and give your code an access token (a key, so treat it as one: keep it in HF_TOKEN or let hf auth login store it (older versions: huggingface-cli login), and never put it in Git). To download files without loading a model, there is hf download ID, and in Python huggingface_hub.snapshot_download. Check the licence of data as carefully as the licence of a model.
Putting it together: a reproducible project
The whole routine for a new project, and the record you keep with a result:
mkdir my-project,cd my-project,git init -b main.- Make the environment (
python3 -m venv .venv, oruv init), activate it, install what you need. - Write
.gitignorebefore the first commit, and add.venv/, data, checkpoints and.env. - Save the packages (
python -m pip freeze > requirements.txt, or commituv.lock), and note the Python version in the README. - Pin the model:
revision="<commit hash>". - Commit. Write the commit ID, the package versions and the seed (P1.G3) next to every result you report.
Then anyone can git clone, create an environment, install from the list, and run. That is what “reproducible” means in practice. (Experiment tracking tools, P12.3, automate the record. Even when the same environment is rebuilt, some GPU operations are not bit-for-bit repeatable, as P1.G3 explains.)
Common mistakes
- Installing without activating the environment. The package goes into the wrong Python and
importfails. Fix: check withwhich python; callpython -m pip. - Committing
.venv/, data or checkpoints. A huge repository that is slow to clone, and GitHub blocks files over 100 MiB. Fix: write.gitignorefirst; use LFS or DVC for big files. .gitignoreadded after the file was committed. The file is still tracked. Fix:git rm --cached FILE, then commit.pip freezein the wrong environment.requirements.txtlists unrelated packages. Fix: freeze only with the project environment active.- Mixing conda, pip and uv on one environment. Broken or confusing package state. Fix: one tool per environment.
model="owner/name"with norevisionin a published result. The model may change under you. Fix: pin the commit hash.trust_remote_code=Truecopied from a tutorial. You run unreviewed code. Fix: read the repository’s code, or avoid it.- Using a model without reading its licence. You may not be allowed to use it that way. Fix: read the model card.
Common misconceptions
Check yourself
Check your understanding
You committed a file with your API key and pushed it to a public repository. What should you do first?
Once a key has been public, someone may already have copied it. Only revoking it makes the copies useless. Deleting the file in a new commit leaves the key in the old commits. Making the repository private does not recall copies already taken. Rewriting history can come afterwards, but clones and forks may still hold the key, so it does not replace revoking.
What does
python -m pip freeze > requirements.txtdo?The
>sends the command output into the file. The command that installs from the file ispython -m pip install -r requirements.txt. Nothing is locked or uploaded, and the list is of whatever Python you ran, so it should run inside the project environment.You edited
train.py. Which command puts your edit into the staging area?git addputs the change in the staging area, andgit committhen saves everything staged. A plaingit commitwith nothing staged has nothing to save,git pushsends commits that already exist to a remote, andgit switchchanges branch. (Variants such asgit commit -astage tracked files themselves, butgit addis the command whose job is staging.)A model is loaded with
from_pretrained("owner/name")and norevision. What is the risk for a published result?Without
revision, the code loads the current state of themainbranch, and the authors can update it. A pinned commit hash removes that. Device choice, caching and licences do not depend onrevision: files are cached either way,pipelineuses the CPU unless asked, and the licence applies regardless.Which statement about weight files is correct?
Unpickling can call any function that the file names, so a file from an untrusted source can run code at load time. Safetensors was designed to avoid this by storing raw numbers. Safety does not depend on speed or file size, and the risk is not tied to an operating system.
A project needs a compiled non-Python library that is hard to build by hand, and your teammates already use conda. What is a reasonable choice?
conda packages are not limited to Python code, so it is a common choice for a project with such a dependency, and following the team keeps everyone on the same setup. The main Python is the shared setup that environments exist to avoid. conda is not limited to Python packages. A copied
.venvhas paths from the other computer and is not portable.
Exercises
- In a new folder, create a virtual environment, activate it, install NumPy, and save
requirements.txt. Then create a second environment and rebuild from the file. How do you check that both have the same NumPy?Show answer
python3 -m venv .venv, activate,python -m pip install numpy,python -m pip freeze > requirements.txt. In a second folder (or second environment) runpython -m pip install -r requirements.txtand thenpython -m pip freezeorpython -c "import numpy; print(numpy.__version__)"in both. The versions match because the file pins them with==. - In
git statusa filenotes.txtis shown as untracked. What are the two commands that put it into the history, and what does each do?Show answer
git add notes.txtcopies the file’s current content into the staging area, andgit commit -m "Add notes"saves the staged content as a snapshot in the repository. Until the commit, the file is not part of any snapshot. - Write a
.gitignorefor a project with adata/folder, a virtual environment in.venv, model files ending in.ptand a.envfile.Show answer
Four lines, one pattern each:.venv/,data/,*.ptand.env. A line ending in/matches a folder, and*.ptmatches any file ending in.pt. Commit the.gitignoreitself, and create it before the first commit. If a file was already committed,.gitignoredoes not help: usegit rm --cached FILE. - You see
ModuleNotFoundError: No module named 'numpy'right after you ranpip install numpywithout an error. Give two likely causes.Show answer
The install went to a different Python than the one that runs your code, for example because the environment was not active when you installed, or because the notebook kernel uses another Python. Checkwhich pythonandpython -m pip list, and install withpython -m pip install numpyfrom the same Python that runs the code. - On the Hub, a model card for a model you want says “license: other” and asks you to accept terms. What do you do before using it in a school project, and in a company product?
Show answer
Read the full licence text and the terms: they say which uses are allowed. A school project may be allowed where a commercial product is not, so a company should check the licence for commercial use (and ask whoever handles legal questions if unsure). Do not assume that being downloadable means being free to use for everything. - Using the five-line example, change the two sentences, and find one where the model is wrong or unsure. What does the
scoretell you, and what does it not?Show answer
The score is the probability the model gives to its chosen label, so it shows how strongly the model prefers one label. It is not the probability that the answer is right: a neutral sentence gets one of the two labels with a high score anyway (0.929 in the lesson’s example). Measuring accuracy needs labelled test data (P3.A4). - A tutorial says
trust_remote_code=Truein afrom_pretrainedcall. List what you check before running it.Show answer
Open the repository’s files and read the Python files that the model uses (the ones the config points to): look for network calls, file deletion, shell commands and anything you do not understand. Check who the author is and whether the repository is widely used. Pin arevisionso the code you read is the code you run (otherwise the authors could change the files after you checked). If you cannot review it, do not enable the option. - You and a friend both change the learning-rate line of
cfg.pyon different branches. What happens when you merge, and how do you finish?Show answer
Git reports a merge conflict and writes both versions in the file between<<<<<<<,=======and>>>>>>>lines. You edit the file to the value you want, remove the marker lines, thengit add cfg.pyandgit commit. Or you stop withgit merge --abort.
Interview questions
Short answers, the kind an interviewer wants. Try them aloud, then open the answer.
- What is the difference between
pip freezeoutput and a lockfile?Show answer
pip freezeprints the packages installed on one machine. A lockfile (such asuv.lock) is produced by a resolver to record the exact versions chosen for the whole dependency tree, for rebuilding elsewhere; it also separates what you asked for (inpyproject.toml) from what was chosen. - What is the difference between
git fetch,git pullandgit merge?Show answer
git fetchdownloads new commits from the remote and changes nothing in your files.git mergejoins another branch into the current one.git pullis a fetch followed by a merge (by default). - Why should model files and datasets not go straight into a Git repository?
Show answer
Git stores every version of every file and every clone downloads the whole history, so large binary files make the repository huge, and the hosting service limits file sizes (it warns from 50 MiB, and blocks files over 100 MiB). Use Git LFS, DVC or a model hub instead, and keep a pointer or a version ID in Git. - How do you make a model download reproducible?
Show answer
Pin the revision (a commit hash) of the model repository, write down the package versions, and fix the seed for anything random. Keep the code under Git, and record the commit ID next to the result.