Settings

Theme
Lite Mode (saves mobile data)

In Lite Mode, animations and videos don't play until you tap them, and their size is shown first. Interactive widgets still work.

Text size

Back up or move your progress →

Part 2: Programming Toolkit

Tooling: Git, environments, Hugging Face Hub

P2.845 min●○○ BeginnerReviewed Dec 1, 2026

Why this matters for machine learning

ML work depends on code, packages, data and downloaded models that all change over time. Environments, Git and a pinned model version let you, and anyone else, run the same thing again and get the same answer, and they stop you from leaking a secret or breaking a working setup.

  • A result only means something if you can reproduce it: same code, same package versions, same seed. This lesson fixes the first two, and P1.G3 shows the seed. (P1.G3: Randomness, seeds and reproducibility)
  • Fine-tuning starts from a pretrained model that you download by its Hub ID, and it needs the pinned environment and the Git history this lesson sets up. (P5.10: Transfer learning and fine-tuning)
  • Many of the language-model lessons in Part 10 start by loading a tokenizer or a model from the Hub, with the calls you meet here (tokenizers: P10.A2). (P10.A2: Tokenization deep dive, coming soon)
  • Experiment tracking can record the Git commit, the package versions and the model revision of each run, so you can find which setup gave which result. (P12.3: Experiment tracking and reproducibility, coming soon)

Before this: Your toolkit, Python essentials for ML

After this lesson you can

  • Explain why each project needs its own environment, create one with venv, conda or uv, and record and restore its packages (pip freeze, requirements.txt, environment.yml, uv.lock)
  • Choose between venv with pip, conda and uv for a given situation
  • Use the Git cycle (init, status, add, commit, diff, log, branch, switch, merge, push, pull, clone) and write a .gitignore that keeps data, checkpoints, environments and secrets out of the repository
  • Say what to do if an API key was committed: revoke it first
  • Load a pretrained model from the Hugging Face Hub in a few lines, read its model card and licence, pin its revision, find it in the cache, and name the risks of trust_remote_code and pickle weight files

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 asMeans
numpy==2.5.5exactly this version (use it to reproduce a result)
numpy>=2,<3any 2.x version
numpy~=2.1.02.1.0 or newer, but below 2.2 (a “compatible release”: patch updates only)
numpywhatever 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: venv and pip. 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:

  1. The working folder: the files you edit.
  2. The staging area: the changes you have chosen to include in the next snapshot (git add).
  3. 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.

PlaceHoldsMoves forward with
Working folderyour files as you edit them(you edit)
Staging areathe changes chosen for the next commitgit add
Local repositorysaved commitsgit commit
Remote (GitHub)a shared copygit push (and git pull back)
The path of a change: you edit in the working folder, git add chooses it for the next snapshot, git commit saves the snapshot in the repository, and git push sends it to the remote on GitHub. git pull brings new commits back the other way.

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 toCommand
start a repository / copy onegit init / git clone URL
see what changedgit status, git diff
choose changes for the next snapshotgit add FILE
save a snapshotgit commit -m "message"
undo edits to a file I have not stagedgit restore FILE
see historygit log --oneline
make and move between branchesgit switch -c NAME, git switch NAME
join a branch into the current onegit merge NAME
send / get commitsgit push, git pull
stop tracking a file but keep it on diskgit 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
>>>>>>> a

The 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 GitKeep 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.tomlDatasets, which are large and may have their own licence
A README, configuration files, small test dataModel 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:

PropertyValue
Namedistilbert/distilbert-base-uncased-finetuned-sst-2-english
What it doesclassifies English text as POSITIVE or NEGATIVE (fine-tuned on the SST-2 movie-review sentences)
LicenceApache-2.0 (from the model card)
Downloadone weight file of 268 MB (267,832,558 bytes), plus small files
Size66,955,010 parameters
NeedsCPU 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:

Loading a pickle can run code

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:

  1. mkdir my-project, cd my-project, git init -b main.
  2. Make the environment (python3 -m venv .venv, or uv init), activate it, install what you need.
  3. Write .gitignore before the first commit, and add .venv/, data, checkpoints and .env.
  4. Save the packages (python -m pip freeze > requirements.txt, or commit uv.lock), and note the Python version in the README.
  5. Pin the model: revision="<commit hash>".
  6. 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 import fails. Fix: check with which python; call python -m pip.
  • Committing .venv/, data or checkpoints. A huge repository that is slow to clone, and GitHub blocks files over 100 MiB. Fix: write .gitignore first; use LFS or DVC for big files.
  • .gitignore added after the file was committed. The file is still tracked. Fix: git rm --cached FILE, then commit.
  • pip freeze in the wrong environment. requirements.txt lists 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 no revision in a published result. The model may change under you. Fix: pin the commit hash.
  • trust_remote_code=True copied 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

  1. You committed a file with your API key and pushed it to a public repository. What should you do first?

  2. What does python -m pip freeze > requirements.txt do?

  3. You edited train.py. Which command puts your edit into the staging area?

  4. A model is loaded with from_pretrained("owner/name") and no revision. What is the risk for a published result?

  5. Which statement about weight files is correct?

  6. 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?

Exercises

  1. 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 answerpython3 -m venv .venv, activate, python -m pip install numpy, python -m pip freeze > requirements.txt. In a second folder (or second environment) run python -m pip install -r requirements.txt and then python -m pip freeze or python -c "import numpy; print(numpy.__version__)" in both. The versions match because the file pins them with ==.
  2. In git status a file notes.txt is shown as untracked. What are the two commands that put it into the history, and what does each do?
    Show answergit add notes.txt copies the file’s current content into the staging area, and git 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.
  3. Write a .gitignore for a project with a data/ folder, a virtual environment in .venv, model files ending in .pt and a .env file.
    Show answerFour lines, one pattern each: .venv/, data/, *.pt and .env. A line ending in / matches a folder, and *.pt matches any file ending in .pt. Commit the .gitignore itself, and create it before the first commit. If a file was already committed, .gitignore does not help: use git rm --cached FILE.
  4. You see ModuleNotFoundError: No module named 'numpy' right after you ran pip install numpy without an error. Give two likely causes.
    Show answerThe 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. Check which python and python -m pip list, and install with python -m pip install numpy from the same Python that runs the code.
  5. 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 answerRead 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.
  6. Using the five-line example, change the two sentences, and find one where the model is wrong or unsure. What does the score tell you, and what does it not?
    Show answerThe 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).
  7. A tutorial says trust_remote_code=True in a from_pretrained call. List what you check before running it.
    Show answerOpen 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 a revision so 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.
  8. You and a friend both change the learning-rate line of cfg.py on different branches. What happens when you merge, and how do you finish?
    Show answerGit 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, then git add cfg.py and git commit. Or you stop with git merge --abort.

Interview questions

Short answers, the kind an interviewer wants. Try them aloud, then open the answer.

  1. What is the difference between pip freeze output and a lockfile?
    Show answerpip freeze prints the packages installed on one machine. A lockfile (such as uv.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 (in pyproject.toml) from what was chosen.
  2. What is the difference between git fetch, git pull and git merge?
    Show answergit fetch downloads new commits from the remote and changes nothing in your files. git merge joins another branch into the current one. git pull is a fetch followed by a merge (by default).
  3. Why should model files and datasets not go straight into a Git repository?
    Show answerGit 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.
  4. How do you make a model download reproducible?
    Show answerPin 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.

Key takeaways

  • An environment is a private folder of Python and packages for one project. Projects need different versions of the same package, so they must not share. Create one with python3 -m venv .venv, activate it, and install with python -m pip install.
  • Record exactly what you installed: python -m pip freeze > requirements.txt, and restore with python -m pip install -r requirements.txt. Pin versions with == when you want the same result later. conda also installs non-Python libraries; uv is a fast tool that covers the venv and pip jobs and adds a project file and a lockfile.
  • Git keeps snapshots (commits) of your project. The cycle is edit, git add, git commit. A branch is a separate line of work, git merge joins branches, and git push and git pull share commits with a remote such as GitHub.
  • A .gitignore lists what Git must not track: .venv/, data, model checkpoints and .env files. Git keeps every version of every file forever, so big files do not belong in it (Git LFS and DVC exist for them), and a secret that was committed must be treated as leaked: revoke it first.
  • The Hugging Face Hub hosts models and datasets, each with a model card that states the licence and limits. pipeline(task, model=ID) loads a model and gives you a function. The files are cached on your disk, so the download happens once.
  • For reproducibility, pin the model with revision= (a commit hash) and write down package versions. A pretrained model is only as good as its training data: it can be confidently wrong on text it was not made for.
  • Safety: leave trust_remote_code off unless you have read the code, because it runs code from the repository on your computer. Prefer .safetensors weight files to pickle-based .bin files, because unpickling can run code.
Found a mistake? Tell us