Shelves / AI and ML Foundations
AI·144
Python for AI
Python as the AI workbench and why it won: the language features that matter for ML code, type hints for data and model code, virtual environments and dependency management with uv, venv and conda, packaging with pyproject.toml and wheels, NumPy in depth (ndarrays, dtypes, memory layout, views, broadcasting, vectorisation, random generators), SciPy, pandas 3.0 and Polars for tabular data, matplotlib for plots, Jupyter notebooks and their pitfalls, profiling CPU and memory, making Python fast, and how the same work looks in Java, Kotlin, Go, Rust, C++ and Julia.
Start here: Python as the AI workbench
Almost all AI work happens in Python, yet the heavy lifting doesn't run in Python at all: libraries like NumPy and PyTorch hand whole arrays to compiled C, C++ and GPU code. Writing AI code well means writing Python that describes array operations and lets the libraries do the loops. Three habits matter from day one: vectorise, mind your number types, and make runs reproducible.
Vectorise: let NumPy do the loop
dot product of two 1,000,000-element vectors
Python loop over lists: 39.3 ms
NumPy a @ b: 0.72 ms (≈55× faster)
standardise a 2,000 × 64 matrix (subtract column means, divide by column stds)
nested Python loops: 88.9 ms
NumPy broadcasting (X - mu) / sd: 0.86 ms (≈100× faster)
(X - mu) / sd works although X is 2,000 × 64 and mu has only 64 numbers: broadcasting stretches the smaller array across the larger one without copying it. Writing operations on whole arrays instead of element by element is the single biggest speed-up in ML code, and it's also shorter and closer to the maths.
Number types: memory, precision and silent surprises
1000 × 1000 matrix: float64 8.0 MB float32 4.0 MB float16 2.0 MB
float32: 1e8 + 1 = 1e8 (the +1 is lost: float32 keeps ~7 significant digits)
float16: largest value 65,504; 2048 + 1 = 2048
sum of ten million 0.1s in float32:
running total, one by one: 1,087,937.0 (8.8% wrong)
np.sum (pairwise summation): 1,000,000.1
in float64: 1,000,000.0
Models are usually trained in 32-bit or lower precision because it halves memory and doubles speed, and neural networks tolerate small errors. But precision bites in accumulations (sums, means, losses over millions of values) and in very large or small numbers (float16 overflows past 65,504, which is why mixed-precision training keeps some values in float32 and scales the loss). NumPy's sum adds in pairs, which keeps the error tiny; a naive running total didn't.
Reproducibility
two runs with default_rng(42): identical → True
two runs with default_rng(): identical → False
Random numbers drive data splits, initial weights, shuffling and dropout. Fix the seeds (NumPy, Python's random, PyTorch) and record library versions, or you won't be able to tell whether a change in results came from your change or from chance.
How deep to go in Python for AI
Volume 17 defines six mastery levels. For this chapter they look like this; the chapter aims at L3 everywhere, and its lab at L4.
| Level | What you can do |
|---|---|
| L1 | Use NumPy arrays, pandas data frames and notebooks for simple analysis |
| L2 | Write vectorised, typed, reproducible data and model code in a managed environment |
| L3 | Explain memory layout, broadcasting, dtypes and precision, and the Python–native boundary |
| L4 | Profile and fix slow or numerically unstable ML code |
| L5 | Structure ML projects: packaging, environments, configs, experiment tracking, testing |
| L6 | Set ML engineering standards and tooling across teams |
Why Python dominates AI
Python is slow as an interpreted language, yet nearly all AI research and most AI engineering use it. The reason: Python is the orchestration layer; the heavy computation runs in optimised C, C++, CUDA, Fortran and Rust libraries underneath (NumPy's C core and BLAS/LAPACK, PyTorch's ATen and CUDA kernels, Polars in Rust, tokenizers in Rust). Python provides:
- A readable, interactive language for experimentation (REPL, notebooks).
- The richest ecosystem: NumPy, SciPy, pandas, scikit-learn, PyTorch, JAX, Hugging Face Transformers, LangChain/LangGraph, vLLM, MLflow, and thousands more.
- First-class bindings to native code (C API, Cython, pybind11/nanobind, PyO3 for Rust).
- A community where new research code appears first.
Other languages have important roles: C++/CUDA for kernels and inference engines (llama.cpp, TensorRT-LLM), Rust for fast tooling (tokenizers, Polars, candle, uv, Ruff), Java/Kotlin for enterprise integration (Spring AI, LangChain4j, DJL), Go for infrastructure (Kubernetes operators, serving gateways, Ollama), TypeScript for AI apps and agents (Vercel AI SDK, LangChain.js), Julia for scientific computing, Mojo as a Python-superset systems language for AI.
Python language essentials for ML code
Beyond basics (Vol. 3 covers language fundamentals), ML code relies on:
- Iterables, generators and comprehensions for data pipelines that stream rather than load everything (
yield, generator expressions). - Context managers (
with) for resources and modes (torch.no_grad(), file handles, timers). - Decorators (
@torch.compile,@functools.cache,@dataclass). - Dataclasses and Pydantic models for configs and records (
@dataclass(frozen=True),pydantic.BaseModelfor validated configs and API payloads). *args/**kwargsand keyword-only arguments for flexible APIs; avoid mutable default arguments.pathlib,logging,argparse/Typer for scripts;asynciofor I/O-bound concurrency (calling model APIs in parallel).- The GIL and concurrency: CPython's Global Interpreter Lock lets only one thread run Python bytecode at a time; CPU-bound pure-Python code doesn't speed up with threads (use processes, vectorised libraries that release the GIL, or native extensions). The free-threaded build (PEP 703; experimental in 3.13, officially supported in 3.14) removes the GIL optionally; ecosystem support is growing.
# Streaming a large JSONL dataset with generators: constant memory
import json
from collections.abc import Iterator
from pathlib import Path
def read_records(path: Path) -> Iterator[dict]:
with path.open() as f:
for line in f:
if line.strip():
yield json.loads(line)
def clean(records: Iterator[dict]) -> Iterator[dict]:
for r in records:
text = r.get("text", "").strip()
if 20 <= len(text) <= 20_000:
yield {"id": r["id"], "text": text}
n = sum(1 for _ in clean(read_records(Path("corpus.jsonl"))))
Typing for data and model code
Type hints (PEP 484 onwards) are optional at runtime but valuable in ML codebases, which are notoriously hard to refactor:
from dataclasses import dataclass
from typing import Literal, Protocol
import numpy as np
from numpy.typing import NDArray
@dataclass(frozen=True)
class TrainConfig:
lr: float = 3e-4
batch_size: int = 64
epochs: int = 10
optimizer: Literal["adamw", "sgd"] = "adamw"
class Scorer(Protocol): # structural interface
def predict_proba(self, X: NDArray[np.float32]) -> NDArray[np.float32]: ...
def top_k(scores: NDArray[np.float32], k: int) -> NDArray[np.int64]:
return np.argsort(-scores)[:k]
- Static checkers: mypy, pyright (Pylance in VS Code), and newer fast checkers (Astral's ty, Meta's Pyrefly).
numpy.typing.NDArray[dtype]types dtypes but not shapes; libraries like jaxtyping add shape annotations (Float[Tensor, "batch seq dim"]) checked at runtime with beartype/typeguard.- Pydantic validates data at runtime (configs, API inputs, LLM structured outputs in 14B).
- Python 3.12+ syntax:
def f[T](x: T) -> T,type Vector = list[float].
Environments and dependencies
Why isolation matters
ML stacks have heavy, version-sensitive dependencies (PyTorch builds per CUDA version, NumPy ABI changes, conflicting transitive pins). Each project needs an isolated environment with locked versions so results are reproducible.
| Tool | Role |
|---|---|
| venv (stdlib) + pip | Basic virtual environments and installs |
| uv (Astral, Rust) | Very fast installer, resolver, lockfile (uv.lock), Python version management, project management, tool runner; the de facto modern default |
| Poetry, PDM, Hatch | Project/dependency managers with lockfiles |
| conda / mamba / pixi | Cross-language environments with binary packages (CUDA toolkits, C libraries, R); pixi uses conda-forge with lockfiles |
| Docker | Full system-level reproducibility (OS packages, CUDA drivers' user-space libs) |
# uv workflow: project with a lockfile and pinned Python
uv init churn-model && cd churn-model
uv python pin 3.13
uv add numpy pandas scikit-learn matplotlib
uv add --dev pytest ruff mypy ipykernel
uv run python train.py # runs inside the project environment, syncing from uv.lock
uv lock --upgrade-package pandas # controlled upgrades
# PyTorch with a specific CUDA build: configure the index in pyproject.toml ([tool.uv.sources])
Packaging
Modern Python packaging uses pyproject.toml (PEP 517/518/621) with a build backend (hatchling, setuptools, uv_build, maturin for Rust extensions, scikit-build-core for C++), producing wheels (.whl, prebuilt, possibly platform-specific with compiled extensions) and sdists.
[project]
name = "churn-model"
version = "0.3.0"
requires-python = ">=3.12"
dependencies = ["numpy>=2.1", "pandas>=3.0", "scikit-learn>=1.6"]
[project.optional-dependencies]
gpu = ["torch>=2.10"]
[project.scripts]
churn-train = "churn_model.train:main"
[build-system]
requires = ["hatchling"]
build-backend = "hatchling.build"
Lock dependencies for applications (exact versions + hashes); specify compatible ranges for libraries. The standard lockfile format pylock.toml (PEP 751, accepted 2025) is gaining tool support.
NumPy
NumPy's ndarray is the foundation of scientific Python: a typed, fixed-size, N-dimensional array in contiguous (or strided) memory, with operations implemented in C.
Arrays, dtypes and shapes
import numpy as np
a = np.array([[1, 2, 3], [4, 5, 6]], dtype=np.float32)
a.shape, a.ndim, a.dtype, a.size, a.itemsize, a.nbytes # (2, 3), 2, float32, 6, 4, 24
np.zeros((3, 4)); np.ones(5); np.arange(0, 1, 0.25); np.linspace(0, 1, 5); np.eye(3)
a.reshape(3, 2); a.T; a.ravel(); a[:, None, :].shape # (2, 1, 3): add an axis
| dtype | Bytes | Use |
|---|---|---|
float64 |
8 | Default for scientific computing; accumulation |
float32 |
4 | ML features and model weights on CPU |
float16, bfloat16 (via ml_dtypes) |
2 | Model weights/activations on accelerators (chapter 165) |
int64, int32, int8, uint8 |
8/4/1/1 | Indices, counts, images, quantised values |
bool |
1 | Masks |
Memory layout, strides and views
An ndarray is a pointer + shape + strides (bytes to step along each axis) + dtype. Many operations (slicing, transpose, reshape when possible) return views sharing the same memory, without copying:
x = np.arange(12, dtype=np.int64).reshape(3, 4)
x.strides # (32, 8): next row = 32 bytes, next column = 8 bytes (C/row-major order)
v = x[:, 1] # view: no copy
v[:] = -1 # modifies x too!
x.T.flags["C_CONTIGUOUS"] # False: transposed view has swapped strides
y = x[x > 5] # boolean (fancy) indexing returns a COPY
np.shares_memory(x, v) # True
Row-major (C order) vs column-major (Fortran order) layout affects speed: iterating along the contiguous axis is cache-friendly (Vol. 1 ch. on memory hierarchy). Call np.ascontiguousarray before passing to code expecting contiguous memory.
Broadcasting
Broadcasting lets NumPy operate on arrays of different shapes without copying: dimensions are compared from the right; they're compatible if equal or one of them is 1 (which is stretched virtually).
X = np.random.default_rng(0).normal(size=(1000, 3)) # 1000 samples, 3 features
mu = X.mean(axis=0) # shape (3,)
sigma = X.std(axis=0) # shape (3,)
Z = (X - mu) / sigma # (1000,3) op (3,) → broadcast along rows
# Pairwise squared distances between 1000 points and 50 centroids without loops:
C = X[:50]
D = ((X[:, None, :] - C[None, :, :]) ** 2).sum(axis=-1) # (1000,1,3) - (1,50,3) → (1000,50,3) → (1000,50)
# Memory-efficient alternative using ‖x−c‖² = ‖x‖² + ‖c‖² − 2x·c:
D2 = (X**2).sum(1)[:, None] + (C**2).sum(1)[None, :] - 2 * X @ C.T
np.allclose(D, D2) # True
Vectorisation
Replace Python loops with whole-array operations: they run in C, use SIMD instructions and avoid per-element interpreter overhead, typically 10–1000× faster.
import time
x = np.random.default_rng(0).random(10_000_000)
t = time.perf_counter(); s = 0.0
for v in x: s += v * v # pure Python loop
print("loop", time.perf_counter() - t) # ~1–2 s
t = time.perf_counter(); s = np.dot(x, x) # vectorised (BLAS)
print("dot ", time.perf_counter() - t) # ~5 ms
Key operations: element-wise ufuncs (np.exp, np.maximum), reductions (sum, mean, max, argmax with axis=), linear algebra (@, np.linalg), np.where, np.einsum (Einstein summation for complex tensor contractions: np.einsum("bij,bjk->bik", A, B) batched matmul), sorting/argpartition (top-k without full sort).
Random numbers
Use the Generator API with explicit seeds for reproducibility (not the legacy global np.random.seed):
rng = np.random.default_rng(seed=42)
rng.normal(0, 1, size=(3, 3)); rng.integers(0, 10, size=5); rng.choice(100, size=10, replace=False)
rng.permutation(10)
child_rngs = rng.spawn(4) # independent streams for parallel workers
SciPy
SciPy builds on NumPy with scientific algorithms:
| Module | Examples |
|---|---|
scipy.optimize |
minimize (BFGS, L-BFGS-B, Nelder-Mead), root finding, curve fitting, linear programming |
scipy.stats |
Distributions (pdf/cdf/sampling), hypothesis tests (t-test, chi-square, Mann-Whitney), bootstrap |
scipy.sparse |
Sparse matrices (CSR/CSC) for text features, graphs, recommender interactions |
scipy.linalg |
Decompositions (LU, QR, Cholesky, SVD, eigen) beyond numpy.linalg |
scipy.spatial |
KD-trees, distance matrices, convex hulls |
scipy.signal, scipy.fft |
Filtering, spectral analysis (audio, sensors) |
scipy.integrate, scipy.interpolate |
ODEs, quadrature, splines |
from scipy import optimize, stats
# Minimise the Rosenbrock function (a classic optimisation test)
res = optimize.minimize(optimize.rosen, x0=np.array([-1.2, 1.0]), method="L-BFGS-B")
res.x # ≈ [1, 1]
# Two-sample t-test: did variant B change average session length?
t, p = stats.ttest_ind(a_sessions, b_sessions, equal_var=False)
pandas and Polars
pandas
pandas provides labelled, column-typed tables (DataFrame) and 1-D labelled arrays (Series) for loading, cleaning, joining, aggregating and exploring tabular data.
pandas 3.0 (January 2026) changed defaults: Copy-on-Write is always on (indexing returns objects that behave like copies; chained assignment like df[df.x > 0]["y"] = 1 no longer silently modifies or warns ambiguously; use df.loc[mask, "y"] = 1), and a dedicated string dtype (str, backed by PyArrow when available) replaces generic object columns for text.
import pandas as pd
df = pd.read_parquet("orders.parquet") # columnar, typed, fast (prefer over CSV)
df.info(); df.describe(); df.head()
df["order_date"] = pd.to_datetime(df["order_date"], utc=True)
df = df.dropna(subset=["customer_id"]).drop_duplicates("order_id")
# Feature engineering per customer
features = (
df.assign(is_weekend=df["order_date"].dt.dayofweek >= 5)
.groupby("customer_id")
.agg(orders=("order_id", "count"),
revenue=("amount", "sum"),
avg_basket=("amount", "mean"),
weekend_share=("is_weekend", "mean"),
last_order=("order_date", "max"))
.reset_index()
)
features["days_since_last"] = (pd.Timestamp.now(tz="UTC") - features["last_order"]).dt.days
labels = pd.read_parquet("churn_labels.parquet")
train = features.merge(labels, on="customer_id", how="inner", validate="one_to_one")
Habits: use vectorised column operations (not apply with Python functions on large data), explicit dtypes (category for low-cardinality strings, nullable integers Int64), validate= on merges, method chaining for readability, and Parquet instead of CSV.
Polars
Polars (Rust core, Arrow memory) is a fast DataFrame library with a lazy query engine (query optimisation, predicate/projection pushdown, parallel execution, streaming for larger-than-memory data). Increasingly the choice for heavy data preparation:
import polars as pl
features = (
pl.scan_parquet("orders/*.parquet") # lazy: nothing read yet
.filter(pl.col("customer_id").is_not_null())
.group_by("customer_id")
.agg(pl.len().alias("orders"),
pl.col("amount").sum().alias("revenue"),
pl.col("order_date").max().alias("last_order"))
.collect() # optimised plan executes in parallel
)
DuckDB (in-process analytical SQL over Parquet/Arrow/DataFrames) is another excellent tool for data preparation: duckdb.sql("SELECT customer_id, count(*) FROM 'orders/*.parquet' GROUP BY 1").df().
matplotlib
matplotlib is the foundational plotting library (seaborn adds statistical plots on top; Plotly/Altair for interactive charts). Use the object-oriented API:
import matplotlib.pyplot as plt
fig, axes = plt.subplots(1, 2, figsize=(10, 4), constrained_layout=True)
axes[0].hist(features["revenue"], bins=50, log=True)
axes[0].set(title="Revenue per customer", xlabel="₹", ylabel="customers (log)")
axes[1].plot(history["epoch"], history["train_loss"], label="train")
axes[1].plot(history["epoch"], history["val_loss"], label="validation")
axes[1].set(title="Learning curves", xlabel="epoch", ylabel="loss"); axes[1].legend()
fig.savefig("eda.png", dpi=150)
Essential ML plots: distributions/histograms, learning curves (train vs validation loss), confusion matrices, ROC/PR curves, calibration plots, residual plots, feature importance, embeddings projected to 2-D (PCA/UMAP).
Jupyter notebooks
Jupyter (JupyterLab, VS Code notebooks, Google Colab, Kaggle) mixes code, output, plots and prose: ideal for exploration, analysis and teaching.
Pitfalls and practices:
- Hidden state and out-of-order execution: cells run in any order, so a notebook may "work" only because of a deleted cell's state. Restart and run all before trusting or sharing results.
- Reproducibility: pin environments; set seeds; record data versions.
- Version control: notebooks are JSON with outputs; strip outputs (nbstripout) or use Jupytext (paired
.pyfiles) or marimo (reactive notebooks stored as Python files, re-running dependent cells automatically). - Promote code out of notebooks: once logic stabilises, move it into a package with tests; notebooks import it. Don't deploy notebooks to production.
- Useful magics:
%timeit,%prun,%load_ext autoreload+%autoreload 2.
Profiling and performance
Measure before optimising (Vol. 9 ch. 105).
| Tool | Measures |
|---|---|
time.perf_counter, %timeit, timeit |
Wall time of snippets |
cProfile + snakeviz |
Function-level CPU time (deterministic) |
| py-spy | Sampling profiler, attaches to running processes, flame graphs, low overhead |
| Scalene | CPU (Python vs native), memory and GPU per line |
line_profiler |
Line-by-line timings for chosen functions |
| memray, tracemalloc | Memory allocations and leaks |
| PyTorch profiler, NVIDIA Nsight Systems | GPU kernels, data loading stalls (chapter 152) |
python -m cProfile -o prof.out train.py && snakeviz prof.out
py-spy record -o flame.svg -- python train.py
scalene --cpu --memory train.py
Making Python fast, in order of preference:
- Better algorithms and data structures (sets for membership, avoiding quadratic loops).
- Vectorise with NumPy/pandas/Polars; push work into libraries.
- Avoid unnecessary copies and conversions (dtype churn, Python lists of floats).
- Parallelise:
multiprocessing/concurrent.futures.ProcessPoolExecutorfor CPU-bound Python; asyncio for I/O; Ray/Dask for distributed data processing. - JIT compile: Numba (
@njitfor numeric loops),torch.compile, JAXjit. - Native extensions: Cython, C++ with pybind11/nanobind, Rust with PyO3/maturin.
from numba import njit
import numpy as np
@njit(cache=True)
def pairwise_min_dist(X): # loops are fine inside Numba: compiled to machine code
n = X.shape[0]; best = np.inf
for i in range(n):
for j in range(i + 1, n):
d = 0.0
for k in range(X.shape[1]):
diff = X[i, k] - X[j, k]; d += diff * diff
if d < best: best = d
return np.sqrt(best)
The same work in other languages
# Python / NumPy: standardise features and compute a linear model's predictions
import numpy as np
X = np.random.default_rng(0).normal(size=(1000, 3))
w = np.array([0.5, -1.0, 2.0])
Z = (X - X.mean(0)) / X.std(0)
y_hat = Z @ w
# Julia: arrays and broadcasting are built into the language; loops are fast (JIT-compiled)
using Statistics, Random
X = randn(MersenneTwister(0), 1000, 3)
w = [0.5, -1.0, 2.0]
Z = (X .- mean(X, dims=1)) ./ std(X, dims=1) # dot syntax broadcasts
ŷ = Z * w
// Rust: ndarray crate (NumPy-like) with BLAS optional; Polars and candle for data and tensors
use ndarray::{Array1, Array2, Axis};
use ndarray_rand::{RandomExt, rand_distr::StandardNormal};
let x: Array2<f64> = Array2::random((1000, 3), StandardNormal);
let w = Array1::from(vec![0.5, -1.0, 2.0]);
let mean = x.mean_axis(Axis(0)).unwrap();
let std = x.std_axis(Axis(0), 0.0);
let z = (&x - &mean) / &std; // broadcasting
let y_hat = z.dot(&w);
// Java: no NumPy equivalent in the JDK; use ND4J/DJL NDArray, Tribuo, or the Vector API for SIMD
// DJL (Deep Java Library) NDArray example:
try (NDManager m = NDManager.newBaseManager()) {
NDArray x = m.randomNormal(new Shape(1000, 3));
NDArray w = m.create(new float[]{0.5f, -1f, 2f});
NDArray c = x.sub(x.mean(new int[]{0})); // centre
NDArray z = c.div(c.pow(2).mean(new int[]{0}).sqrt()); // divide by std
NDArray yHat = z.matMul(w);
}
// For enterprise AI integration, Java teams typically call models via Spring AI / LangChain4j (14B).
// Go: gonum for numerics (mat, stat); fine for moderate workloads and infrastructure tooling
import ("gonum.org/v1/gonum/mat"; "gonum.org/v1/gonum/stat")
func standardise(x *mat.Dense) *mat.Dense {
r, c := x.Dims()
z := mat.NewDense(r, c, nil)
for j := 0; j < c; j++ {
col := mat.Col(nil, j, x)
mu, sd := stat.MeanStdDev(col, nil)
for i := 0; i < r; i++ { z.Set(i, j, (col[i]-mu)/sd) }
}
return z
}
// C++: Eigen (header-only linear algebra) — what many inference engines and robotics stacks use
#include <Eigen/Dense>
Eigen::MatrixXd X = Eigen::MatrixXd::Random(1000, 3);
Eigen::RowVectorXd mu = X.colwise().mean();
Eigen::MatrixXd C = X.rowwise() - mu;
Eigen::RowVectorXd sd = (C.array().square().colwise().sum() / X.rows()).sqrt();
Eigen::MatrixXd Z = C.array().rowwise() / sd.array();
Eigen::VectorXd w(3); w << 0.5, -1.0, 2.0;
Eigen::VectorXd yhat = Z * w;
Project structure for ML code
churn-model/
pyproject.toml uv.lock
src/churn_model/
data.py # loading, validation, splitting (pure functions)
features.py # feature engineering
model.py # model definition / training
evaluate.py # metrics, reports
cli.py # entry points (Typer)
configs/ # YAML/TOML experiment configs (Hydra or plain dataclasses)
notebooks/ # exploration, importing from src/
tests/ # unit tests for data and feature logic, smoke tests for training
data/ (gitignored; versioned with DVC/lakeFS) models/ (artifacts, tracked by MLflow)
Apply Volume 13's practices: small pure functions for data transformations (testable), configuration as data, explicit seeds, type hints, Ruff for linting/formatting, pytest, and CI that runs a fast smoke training on a tiny sample.
Lab: vectorisation, precision and reproducibility
Python 3.13.17 and NumPy 2.5.3 on the lab machine (2 vCPUs). Times are the best of three runs.
Experiment 1: loops versus array operations
| Task | Python loops | NumPy | Speed-up |
|---|---|---|---|
| dot product, 10⁶ elements | 39.3 ms (sum(x*y for …) over lists) |
0.72 ms (a @ b) |
≈55× |
| standardise 2,000 × 64 | 88.9 ms (nested loops) | 0.86 ms ((X - mu) / sd) |
≈100× |
Python 3.13's interpreter is noticeably faster than older versions at simple loops, which narrows the gap a little; the remaining gap comes from per-element object handling that compiled code avoids. When NumPy alone isn't enough (custom loops that can't be expressed as array operations), the usual escalation is Numba or Cython, then a compiled extension (Rust via PyO3, C++ via pybind11), or moving the work into PyTorch so it can run on a GPU.
Experiment 2: dtypes and precision
| Check | Result |
|---|---|
| 1000×1000 matrix: float64 / float32 / float16 | 8.0 / 4.0 / 2.0 MB |
float32(1e8) + float32(1) |
1e+08 (the 1 is lost) |
float16 maximum; float16(2048) + 1 |
65,504; 2,048 |
10⁷ × 0.1 in float32: cumsum[-1] / np.sum / float64 |
1,087,937.0 / 1,000,000.1 / 1,000,000.0 |
bfloat16 (16 bits, but with float32's 8-bit exponent) is the usual training format on modern accelerators because it has float32's range (no overflow at 65,504) while giving up precision, which gradient noise swamps anyway. Rules of thumb: accumulate in float32 or higher; compute losses and softmax in float32; keep running statistics (means, variances, optimizer moments) in float32.
Experiment 3: reproducibility
np.random.default_rng(42).random(3) == np.random.default_rng(42).random(3) # True
np.random.default_rng().random(3) == np.random.default_rng().random(3) # False
Full reproducibility needs more than seeds: PyTorch's torch.manual_seed, torch.use_deterministic_algorithms(True) (some GPU kernels are non-deterministic by default), the same library versions (record them with a lockfile from uv or pip-tools), the same data snapshot, and the same hardware type, since different CPUs and GPUs can produce slightly different floating-point results.
Try it yourself
- Time
np.einsum("ij,ij->i", A, B)against(A * B).sum(1)for 10,000 × 512 arrays. - Compute the mean of 10⁷ values near 10⁶ in float32 two ways (
np.meanand a running mean). Which drifts? - Train the Start Here model in float16 and see what happens to the loss.
- Create a
uvproject with pinned NumPy and scikit-learn versions and recordpython -m pip freezein the experiment output.
Revision sheet: Python for AI
Key ideas
- Python orchestrates; native code computes: NumPy, pandas, PyTorch, JAX run array operations in C/C++/CUDA.
- Vectorise: whole-array operations, broadcasting,
einsum; avoid per-element Python loops. - Memory layout: contiguous arrays, strides, views vs copies; in-place operations.
- dtypes: float64 for analysis, float32 default for models, bf16/fp16 for training speed, int8/int4 for inference; accumulate in higher precision.
- Environments:
uv/venv, lockfiles, pinned versions; notebooks for exploration, packages and scripts for anything repeated. - Reproducibility: seeds everywhere, deterministic algorithms, versioned data and code, recorded configs.
- Typing and testing ML code: type hints, shape checks, small unit tests on data transforms.
Numbers to remember
- Lab: NumPy ≈55–100× faster than Python loops for these tasks.
- float32 ≈ 7 significant digits; float16 max 65,504; bfloat16 has float32's range.
- Lab: naive float32 running sum of 10⁷ × 0.1 was 8.8% off; pairwise sum 0.00001% off.
Pitfalls
- Python loops over rows of large arrays or data frames.
- Silent dtype upcasting or downcasting (int overflow, float16 overflow).
- Accumulating losses or statistics in low precision.
- Unseeded randomness; unpinned dependencies; notebooks as the only record.
- Accidental copies of large arrays doubling memory.
Glossary
- Broadcasting: combining arrays of compatible shapes without copying.
- Vectorisation: expressing computation as whole-array operations.
- bfloat16: 16-bit float with an 8-bit exponent.
- Pairwise summation: adding numbers in a tree to limit rounding error.
- Lockfile: exact versions of all dependencies.