AILearn AI
LearnGlossarySources
ID/EN
Learn AI — open material for learning AIEvery lesson cites its original sources.
⚙ML Development & MLOps
  1. The ML development stack
  2. The ML lifecycle & MLOps maturity
  3. Experiment tracking with MLflow
  4. Model Registry, data versioning & lineage
  5. Deployment & model serving
  6. Monitoring, data drift & concept drift
  7. CI/CD, continuous training & feature stores
Modules
  1. ◎ AI Foundations
  2. ∿ Classical Machine Learning
  3. ⌬ Neural Networks
  4. ↘ Training Results & Evaluation
  5. ▦ Deep Learning Architectures
  6. ✎ Large Language Models
  7. ◐ Image Generation
  8. ♪ Audio & Speech AI
  9. ◈ Multimodal, Video & 3D
  10. ↻ Reinforcement Learning
  11. ⚙ ML Development & MLOps
  12. ★ Advanced & Frontier Topics
Learn/ML Development & MLOps

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.

Beginner~18 min·4 references
Key terms
Machine learning (ML)TensorGPUDatasetReproducibilityMixed-precision trainingInference

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.

≈
A professional kitchen
Python is the chef's language for giving orders. NumPy and pandas are the knives and cutting boards (preparing data). scikit-learn is a set of reliable classic recipes. PyTorch is the high-heat stove for deep learning, and the GPU is the industrial oven that cooks thousands of dishes in parallel. The virtual environment is your own labelled shelf, so another chef's ingredients never end up in your dish.

The layers of the stack

LayerTypical toolsWhat you use it for
Environmentvenv, conda / mamba, uv, DockerIsolated, pinned package versions per project
Interactive workJupyter / JupyterLab, VS Code notebooks, Google ColabExploration, plots, quick experiments
Numerics & dataNumPy, pandas (or Polars), matplotlib / seabornArrays, tables, cleaning, joins, visualisation
Classical MLscikit-learn, XGBoost, LightGBMTabular models, pipelines, metrics, cross-validation
Deep learningPyTorch (also JAX, TensorFlow/Keras)Neural networks, autograd, GPU training
Pretrained modelsHugging Face transformers, datasets, diffusers, peftDownload, fine-tune and share models and datasets
MLOpsMLflow, DVC, FastAPI, Docker, GitHub ActionsTracking, 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].

bash
# 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__)"
Three common ways to create a project environment

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.

python
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))
NumPy + pandas + scikit-learn in a dozen lines

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].

python
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)
Pick the best available device and move model + data to it
knobdevice (cpu / cuda / mps)
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
cuda for training deep nets; cpu for tabular ML and many small-model inference services.
knobDataLoader num_workers
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.
knobdtype / precision (fp32, bf16, fp16)
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.

python
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

text
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.yaml
A common layout (inspired by templates like Cookiecutter Data Science). Data and models are NOT committed to Git — they are versioned with DVC or stored in an artifact store.
!
Common pitfalls
• Installing everything into the global Python → version conflicts between projects. • A PyTorch build whose CUDA version doesn't match your driver → torch.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) ≈ N_params × bytes_per_param
Rule of thumb for the GPU memory the weights alone need.
In words: “the weights take (number of parameters) times (bytes used to store each one)”. It is only a lower bound: inference also needs activations and, for LLMs, the KV cache; training needs several times more for gradients and optimizer state. Halving the precision halves this number — that is why quantization lets bigger models fit.
Symbols(hover a symbol in the formula)
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
7B model (N_params = 7×10⁹): fp32: 7×10⁹ × 4 = 28×10⁹ B ≈ 28 GB bf16: 7×10⁹ × 2 = 14×10⁹ B ≈ 14 GB → fits a 24 GB GPU, with room for the KV cache int8: 7×10⁹ × 1 = 7×10⁹ B ≈ 7 GB int4: 7×10⁹ × 0.5 = 3.5×10⁹ B ≈ 3.5 GB → fits an 8 GB laptop GPU

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

1.
Why should each ML project have its own virtual environment with pinned versions?
2.
torch.cuda.is_available() returns False on a machine with an NVIDIA GPU. What is the most likely cause?
3.
Your GPU utilisation in nvidia-smi hovers around 20% during training and the CPU is busy decoding images. Which knob helps first?
4.
Roughly how much memory do the weights of a 7B-parameter model take in bf16?
5.
What is the recommended relationship between notebooks and src/ modules?
Score: 0/5

References

  1. [1]
    CUDA semantics (PyTorch documentation)
    DocsPyTorchdocs.pytorch.org
  2. [2]
    scikit-learn: Getting Started
    Docsscikit-learn developersscikit-learn.org
  3. [3]
    Transformers documentation
    DocsHugging Facehuggingface.co
  4. [4]
    venv — Creation of virtual environments
    DocsPython Software Foundationdocs.python.org
← Previous
Deep Reinforcement Learning: DQN, Policy Gradients and PPO
Next →
The ML lifecycle & MLOps maturity