AI from scratch · Toolkit 0 · Stage 4: the engineer's toolkit

Your ML workbench: the command line, git and environments

"It worked inside my notebook, but crashes when deployed." "Which version of the model generated this chart?" "I ran cells 1, 4, 2, and 7 and got 93% accuracy, but running top-to-bottom gets 81%." Real machine learning projects rarely live in isolated browser tabs. They run on remote GPU clusters, inside automated training pipelines, and behind production web APIs. This lesson covers what a junior machine learning engineer needs on day one: navigating the shell, isolating dependencies with virtual environments, tracking code snapshots with git, and turning exploratory notebooks into reproducible, parameter-driven scripts.

1. The terminal and filesystem paths

The shell is not magic; it is simply a fast text interface to your filesystem and running processes. A file tree starts at root (/). Where you currently are is your working directory (pwd). Every path you write is either absolute (starts from root /) or relative (relative to where you are right now):

PathMeaningWhen to use it
.Current working directorypython -m venv .venv (create inside current folder)
..Parent directory (one level up)cd .. or pd.read_csv("../data/outages.csv")
~Your user home directory (e.g. /Users/you)Quick shortcuts in your interactive shell (never in code)
data/train.csvRelative path inside the projectAlways in shared scripts (portable across machines)
/Users/you/project/data.csvHardcoded absolute pathNever in code: breaks on your teammate's computer or server
bash · ~/ml-project
learner@server:~/ml-project$ pwd /home/learner/ml-project learner@server:~/ml-project$ ls -F data/ models/ requirements.txt train.py

Click any command above or inspect the terminal session.

A training script begins with: data_path = sys.argv[1]. You run: python train.py --epochs 50 data/train.csv. What value does sys.argv[1] hold?

The shell splits commands by whitespace into a plain string array: sys.argv[0] is "train.py", sys.argv[1] is "--epochs", and sys.argv[2] is "50". That fragile indexing is why production code uses Python's standard argparse module instead of raw sys.argv.

The shell is a text interface to files and processes; flags and arguments pass settings to programs without editing source files.

2. Virtual environments and pinned dependencies

If Project A requires torch 2.1 and Project B requires torch 2.4, running global pip install causes one project to silently break the other. A virtual environment is an isolated folder on disk containing its own Python executable and independent package directory (site-packages):

# 1. Create a fresh virtual environment in .venv
python3 -m venv .venv

# 2. Activate it (changes PATH so 'python' points to .venv/bin/python)
source .venv/bin/activate       # On Windows: .venv\Scripts\activate

# 3. Install your project's pinned packages
pip install -r requirements.txt

# 4. Save your exact package versions for your team
pip freeze > requirements.txt

Never leave dependency versions unpinned. If your requirements.txt says numpy instead of numpy==1.26.4, pip will fetch whatever version is newest six months from now—which may have dropped deprecated functions, changed default numerical rounding, or broken binary compatibility with your CUDA drivers.

Why is torch>=2.0.0 in a production requirements.txt riskier than torch==2.2.0?

Range pins like >= allow pip to pull newly released versions. A new release can deprecate tensor methods, alter weight initialization defaults, or change binary CUDA driver requirements, breaking an automated build months after you wrote it.

Virtual environments isolate dependencies per project; exact version pins prevent future upstream releases from breaking your code.

Why virtual environments and pinned versions are non-negotiable
  1. System Python safety. Operating systems (especially Linux and macOS) rely on internal Python packages for system utilities. Installing packages globally can corrupt system tools.
  2. C-extension and CUDA alignment. PyTorch, NumPy, and TensorFlow wrap optimized C++ and CUDA binaries compiled against specific library ABIs. Mixing versions causes hard segmentation faults.
  3. Container and cloud parity. When training moves from your laptop to an AWS EC2 instance, Google Cloud Vertex, or a Kubernetes pod, the container image installs requirements.txt. Exact pins ensure identical package trees across machines.
  4. Modern tooling. Fast package managers like uv (written in Rust) provide instant virtualenv creation and lockfiles (uv.lock) that compute cryptographic hashes for every installed package.

3. Git fundamentals: snapshotting your work

Git does not store diffs; it stores complete snapshots of your repository tree over time. To use git effectively, you must understand its three zones:

ZoneWhere it isWhat it does
Working TreeFiles on your diskWhere you edit code, run experiments, and test models.
Staging Area (Index)Prepared snapshot bufferWhere you collect the exact changes ready for the next commit (git add).
Git RepositoryThe .git/ directoryThe permanent, immutable history of commits (git commit).

1. Working Tree

train.py MODIFIED
.venv/ IGNORED
model_best.pt IGNORED

2. Staging Area

(empty)

3. Commit History

e1a4b9 · Init repo
f7c20d · Add linear model

Click "git add train.py" to stage the modified file.

Predict, then try it: you modified train.py, ran git add train.py, and then ran git diff. What does git diff output?

git diff without flags compares your Working Tree against the Staging Area. Because train.py was just staged, there are zero unstaged differences! To view what is currently staged and ready to commit, run git diff --staged (or git diff --cached).

Git records immutable snapshots; you choose exactly which changes enter the snapshot using the staging area.

4. Branches, diffs, and undoing mistakes

In machine learning research, 80% of experimental model architectures or feature ideas fail. If you make those edits directly on main, you break the stable baseline for everyone. Branches create isolated pointers for trying ideas safely:

# Create and switch to an experiment branch
git checkout -b exp-cosine-decay    # Or modern: git switch -c exp-cosine-decay

# See what branch you are on and what has changed
git status
git log --oneline -n 5

# Safe undoing:
git restore train.py               # Discard unstaged working tree changes (back to last commit)
git restore --staged train.py      # Unstage an accidental 'git add' without losing code
git revert a3f912                  # Undo an already-pushed bad commit by creating an inverse commit

You modified train.py with an experimental loss function, but training diverged and you want to discard all unstaged changes immediately. Which command restores the clean committed version?

git restore <file> discards unstaged changes in the working tree, bringing the file back to the state of the last commit. git revert is reserved for inverting previously committed snapshots.

Branches isolate experiments; git restore discards uncommitted workspace mistakes; git revert undoes committed snapshots safely.

5. The .gitignore file and what never belongs in git

Git is built for text code, not multi-gigabyte binary assets. A .gitignore file placed at the root of your repository tells git which files to completely ignore:

PatternWhy it must NEVER enter git
.venv/, env/Thousands of machine-specific binary libraries that bloat git and won't work on other operating systems anyway.
*.pt, *.bin, *.safetensorsLarge neural network weights. Git stores the entire binary blob for every single commit, permanently bloating repository size.
data/*.csv, images/Large raw datasets. Store these in cloud storage buckets (S3, GCS) or data registries, not git.
.env, keys.jsonAPI tokens and secret credentials. Committing these exposes your cloud accounts to public scrapers.
__pycache__/, .DS_StoreCompiled bytecode and OS junk files.

Why should model checkpoint files (*.pt or *.bin) be listed in .gitignore instead of committed directly into git?

Git objects are immutable. Even if you delete a 1 GB model weights file in the very next commit, that 1 GB file remains inside the hidden .git/objects/ packfiles forever. Anyone who clones the repository months later must download that entire 1 GB history.

Keep large weights, raw data files, virtual environments, and secret keys out of git with an airtight .gitignore file.

Where it breaks: hidden notebook state, unversioned weights, and git bloat

6. From notebook to script: the bridge

Exploratory data analysis often begins in a notebook. But once an architecture works, convert training into a modular Python script parameterized with argparse so you can run hyperparameter sweeps from the command line:

Modular Python scripts with argparse make your experiments repeatable from the terminal, runnable on remote GPUs, and orchestratable in batch pipelines.

All chapters: AI from scratch · Next: NumPy in depth.

Last updated