The ML development stack
Python environments, Jupyter, NumPy, pandas, scikit-learn, PyTorch, Hugging Face, GPUs/CUDA and a project layout that scales from notebook to production.
Almost all practical Machine learning (ML) today is written in Python. Not because Python is fast (it isn't), but because it glues together very fast libraries written in C, C++ and CUDA. Knowing which tool does which job — and how to set them up so your work is repeatable — saves you weeks of confusion later. This lesson is the map of the toolbox you will use in every other lesson.
The layers of the stack
| Layer | Typical tools | What you use it for |
|---|---|---|
| Environment | venv, conda / mamba, uv, Docker | Isolated, pinned package versions per project |
| Interactive work | Jupyter / JupyterLab, VS Code notebooks, Google Colab | Exploration, plots, quick experiments |
| Numerics & data | NumPy, pandas (or Polars), matplotlib / seaborn | Arrays, tables, cleaning, joins, visualisation |
| Classical ML | scikit-learn, XGBoost, LightGBM | Tabular models, pipelines, metrics, cross-validation |
| Deep learning | PyTorch (also JAX, TensorFlow/Keras) | Neural networks, autograd, GPU training |
| Pretrained models | Hugging Face transformers, datasets, diffusers, peft | Download, fine-tune and share models and datasets |
| MLOps | MLflow, DVC, FastAPI, Docker, GitHub Actions | Tracking, versioning, serving, automation (later lessons) |
1. Isolated Python environments
Every project should have its own environment with pinned versions. venv ships with Python; conda/mamba also manage non-Python libraries (CUDA, MKL); uv is a very fast modern installer and project manager. Whatever you choose, commit a lock or requirements file so someone else (or CI, or a Docker image) can rebuild exactly the same environment — the first step towards Reproducibility[4].
# Option A: built-in venv + pip
python -m venv .venv
source .venv/bin/activate # Windows: .venv\Scripts\activate
pip install numpy pandas scikit-learn matplotlib jupyter
pip freeze > requirements.txt # pin exact versions
# Option B: conda / mamba (also manages CUDA & system libs)
conda create -n churn python=3.12
conda activate churn
# Option C: uv (fast resolver, writes pyproject.toml + uv.lock)
uv init churn && cd churn
uv add numpy pandas scikit-learn torch
uv run python -c "import sklearn; print(sklearn.__version__)"2. Notebooks vs. scripts
Jupyter notebooks are perfect for exploration: you see tables and plots right next to code. But notebooks hide state (cells run out of order), are hard to diff in Git, and are awkward to test. A healthy habit: explore in notebooks, then move stable code into `.py` modules under src/ and import them back into the notebook. Training and evaluation that must be repeated should be runnable as a script (python -m src.train --config configs/base.yaml).
3. The core data & classical-ML libraries
NumPy gives you n-dimensional arrays and vectorised math (no Python loops). pandas gives you labelled tables (DataFrame) for loading CSV/Parquet, cleaning, grouping and joining. scikit-learn gives you a uniform fit / predict / transform API for dozens of models, plus preprocessing, Pipeline, metrics and cross-validation[2]. Putting preprocessing inside a Pipeline is the easiest way to avoid Data leakage.
import numpy as np
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import LogisticRegression
df = pd.read_csv("data/raw/churn.csv")
X = df[["tenure_months", "monthly_charges"]].to_numpy(dtype=np.float32)
y = df["churned"].to_numpy()
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.2, stratify=y, random_state=42)
model = make_pipeline(StandardScaler(), LogisticRegression(max_iter=1000))
model.fit(X_train, y_train) # scaler is fit on TRAIN only
print("test accuracy:", model.score(X_test, y_test))4. PyTorch, GPUs and CUDA
Deep learning is mostly huge matrix multiplications on tensors. A GPU has thousands of simple cores that do these in parallel, often 10–100× faster than a CPU. NVIDIA GPUs are programmed through CUDA; PyTorch hides CUDA behind tensor.to("cuda"). Apple Silicon uses the MPS backend. Two numbers matter most on a GPU: VRAM (memory — decides how big a model and batch fit) and throughput (FLOPS). Run nvidia-smi in a terminal to see your GPU, driver/CUDA version, memory use and utilisation[1].
import torch
if torch.cuda.is_available():
device = torch.device("cuda")
print(torch.cuda.get_device_name(0))
elif torch.backends.mps.is_available(): # Apple Silicon
device = torch.device("mps")
else:
device = torch.device("cpu")
model = torch.nn.Linear(128, 2).to(device)
x = torch.randn(32, 128, device=device) # create data directly on the device
with torch.autocast(device_type=device.type, dtype=torch.bfloat16,
enabled=device.type == "cuda"):
logits = model(x)
print(logits.shape, logits.device)- What it is
- Where tensors live and where the math runs. Model and data must be on the same device.
- ↑ If you increase it
- Moving from CPU to a GPU (or to a bigger GPU) speeds up training/inference of neural nets dramatically and lets larger batches/models fit in memory.
- ↓ If you decrease it
- On CPU, small classical models (scikit-learn, gradient boosting) are often fine; deep nets become very slow. Mixing devices raises “Expected all tensors to be on the same device” errors.
- Typical values
cudafor training deep nets;cpufor tabular ML and many small-model inference services.
- What it is
- Number of background processes that load and preprocess batches while the GPU computes.
- ↑ If you increase it
- Keeps the GPU fed (higher utilisation in
nvidia-smi) when loading/augmentation is the bottleneck; too many workers waste RAM and CPU and can slow startup. - ↓ If you decrease it
- 0 means loading happens in the main process — simplest to debug, but the GPU often sits idle waiting for data.
- Typical values
- 2–8, roughly up to the number of CPU cores; 0 while debugging.
- What it is
- How many bits each number uses. fp32 = 4 bytes, bf16/fp16 = 2 bytes. Mixed precision computes most ops in 16-bit while keeping sensitive parts in 32-bit.
- ↑ If you increase it
- More bits (fp32) = more numerical headroom, but 2× memory and slower on modern GPUs with tensor cores.
- ↓ If you decrease it
- 16-bit roughly halves memory and speeds up matmuls; fp16 can overflow/underflow (needs loss scaling), bf16 is usually safer.
- Typical values
- bf16 autocast on recent NVIDIA GPUs; fp32 on CPU.
5. Hugging Face: pretrained models in three lines
You rarely train language or vision models from scratch. The Hugging Face Hub hosts hundreds of thousands of pretrained models and datasets; transformers loads them with one call, and datasets streams data efficiently[3]. This is Transfer learning in practice.
from transformers import pipeline
from datasets import load_dataset
clf = pipeline("sentiment-analysis") # downloads a default model once
print(clf("This course finally made MLOps click!"))
# [{'label': 'POSITIVE', 'score': 0.99...}]
ds = load_dataset("imdb", split="test[:100]") # first 100 test reviews
print(ds[0]["text"][:80], ds[0]["label"])6. A project layout that scales
churn-project/
├── pyproject.toml / requirements.txt # pinned dependencies
├── README.md
├── configs/
│ └── base.yaml # hyperparameters, paths (no magic numbers in code)
├── data/ # git-ignored; tracked by DVC
│ ├── raw/ # immutable original data
│ └── processed/
├── notebooks/ # exploration only, numbered: 01-eda.ipynb
├── src/
│ ├── data.py # loading & cleaning
│ ├── features.py # feature engineering
│ ├── train.py # entry point: python -m src.train
│ ├── evaluate.py
│ └── serve.py # FastAPI app
├── tests/ # pytest: data checks, feature unit tests
├── models/ # git-ignored; or logged to MLflow
├── Dockerfile
└── .github/workflows/ci.yamltorch.cuda.is_available() returns False; use the install selector on pytorch.org. • Notebooks run out of order → results nobody can reproduce; restart & run all before trusting a number. • Committing large CSVs or model files to Git → bloated repo; use DVC/artifact stores. • Forgetting model.eval() and torch.no_grad() at inference → dropout/batch-norm behave like training and memory is wasted.▸Go deeper: how much GPU memory do I need?
- memory(weights)
- memory needed just to hold the model's parameters (in bytes; divide by 10⁹ for GB)
- ≈
- approximately equal — small overheads (buffers, framework) are ignored
- N_params
- number of parameters, e.g. 7×10⁹ for a “7B” model
- ×
- multiplication
- bytes_per_param
- storage per parameter: fp32 = 4, fp16/bf16 = 2, int8 = 1, int4 = 0.5
▸Worked example
Training needs much more than inference: gradients (same size as weights) plus optimizer state (Adam keeps two moments per parameter) plus activations that grow with batch size and sequence length. A common rule of thumb for mixed-precision Adam training is ~16 bytes per parameter before activations — so full fine-tuning of a 7B model needs >100 GB, which is why techniques like LoRA, quantization and gradient checkpointing exist. For inference of LLMs you also need memory for the KV cache.
Quiz
torch.cuda.is_available() returns False on a machine with an NVIDIA GPU. What is the most likely cause?nvidia-smi hovers around 20% during training and the CPU is busy decoding images. Which knob helps first?src/ modules?References
- [1]CUDA semantics (PyTorch documentation)DocsPyTorchdocs.pytorch.org
- [2]scikit-learn: Getting StartedDocsscikit-learn developersscikit-learn.org
- [3]Transformers documentationDocsHugging Facehuggingface.co
- [4]venv — Creation of virtual environmentsDocsPython Software Foundationdocs.python.org