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):
| Path | Meaning | When to use it |
|---|---|---|
. | Current working directory | python -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.csv | Relative path inside the project | Always in shared scripts (portable across machines) |
/Users/you/project/data.csv | Hardcoded absolute path | Never in code: breaks on your teammate's computer or server |
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?
- "data/train.csv"
- "--epochs"
- "50"
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?
- A future minor or major release can deprecate methods or change default behaviors, causing a fresh install to silently fail
- Unpinned packages take twice as long to download from PyPI
- Python cannot resolve greater-than operators in virtual environments
>= 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
- System Python safety. Operating systems (especially Linux and macOS) rely on internal Python packages for system utilities. Installing packages globally can corrupt system tools.
- 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.
- 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. - 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:
| Zone | Where it is | What it does |
|---|---|---|
| Working Tree | Files on your disk | Where you edit code, run experiments, and test models. |
| Staging Area (Index) | Prepared snapshot buffer | Where you collect the exact changes ready for the next commit (git add). |
| Git Repository | The .git/ directory | The permanent, immutable history of commits (git commit). |
1. Working Tree
2. Staging Area
3. Commit History
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?
- Nothing, because git diff compares the working tree to the staging area
- The line-by-line diff of the changes you just staged
- An error stating that the file is already staged
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 train.pygit revert train.pygit reset train.py
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:
| Pattern | Why 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, *.safetensors | Large 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.json | API tokens and secret credentials. Committing these exposes your cloud accounts to public scrapers. |
__pycache__/, .DS_Store | Compiled bytecode and OS junk files. |
Why should model checkpoint files (*.pt or *.bin) be listed in .gitignore instead of committed directly into git?
- Git permanently stores full snapshots of every committed file, so large binaries permanently bloat repository download size for all collaborators
- Git cannot store binary data and will corrupt the weights file
- Git commits are limited to 10 MB maximum
.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
- The out-of-order execution trap. In a Jupyter notebook, variable states remain in the kernel memory regardless of cell order. If you run cell 10, then cell 3, then delete cell 2, the notebook appears to succeed. On a clean restart, it crashes. Always test: Kernel → Restart & Run All.
- Accidental secret leakage. Pushing an API key (OpenAI, Hugging Face, Kaggle) to a public or private GitHub repository triggers immediate bot scrapers. Always load keys from environment variables (
os.environ["API_KEY"]) stored in a git-ignored.envfile. - Git repository bloat. Once a multi-gigabyte file is committed, running
git rmdoes not remove it from historical packfiles. Removing it requires history-rewriting tools likegit-filter-repoor BFG Repo-Cleaner. - Model and data versioning. Git tracks code. For datasets and model weights, use dedicated tools: cloud object stores (S3/GCS), DVC (Data Version Control), or model registries (MLflow, Hugging Face Hub, Weights & Biases).
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