flowchart TD
subgraph Data["1. Data Pipeline"]
direction LR
D1["Dataset (float32)<br/>X: (n,p), y: (n,1)"]
D2["DataLoader<br/>Mini-Batch (xb, yb)"]
D1 --> D2
end
subgraph Forward["2. Forward Graph"]
direction LR
F1["1. zero_grad()<br/>Clear Stale Grads"]
F2["2. model(xb)<br/>Raw Logits (b,1)"]
F3["3. BCEWithLogits<br/>Build Autograd DAG"]
F1 --> F2 --> F3
end
subgraph Backward["3. Backprop & Eval"]
direction LR
B1["4. loss.backward()<br/>Compute dL/dW"]
B2["5. optimizer.step()<br/>Update Weights"]
B3["eval() + no_grad()<br/>Save state_dict()"]
B1 --> B2 --> B3
end
Data --> Forward
Forward --> Backward
28 PyTorch Core — Tensors, Autograd, nn.Module, Datasets, and Training Loops
Chapter Mission: Build an airtight engineering command of PyTorch’s core deep-learning engine from raw tensors to reproducible, checkpointed neural networks. Working on Bangladesh maternal and child health records (
mch_survey_sample), you will mastertorch.float32memory safety and device portability, trace reverse-mode automatic differentiation (autograd) and its gradient-accumulation trap, author customDataset/DataLoaderpipelines and raw-logitnn.Modulearchitectures paired withBCEWithLogitsLoss, execute the canonical 5-step training loop, enforceeval()+torch.no_grad()inference discipline, and persist portablestate_dictcheckpoints safely withweights_only=True.
Chapter Companion Notebooks (1-to-1 Mirrored in Google Colab)
| Lab Type | Interactive Colab Notebook | Scan (Print) |
|---|---|---|
| Walkthrough | ch28 / 01_walkthrough.ipynb | ![]() |
| Guided To-Dos | ch28 / 02_guided_todos.ipynb | ![]() |
| Coding Exam | ch28 / 03_coding_exam.ipynb | ![]() |
Learning Objectives
By the end of this chapter, you will be able to:
- Convert NumPy arrays into detached
torch.float32copies without hidden memory aliasing (torch.tensorvs.torch.from_numpy), and write device-agnostic code (cuda,mps,cpu) via a cleanget_device()helper. - Trace PyTorch’s dynamic autograd computation graph (
requires_grad=True,.grad_fn,.backward()), explain why gradients accumulate by default, and prevent silent corruption withzero_grad(). - Subclass
torch.utils.data.Dataset(__init__,__len__,__getitem__) and wrap it in a mini-batchDataLoaderwith(batch, 1)binary target alignment and leak-free feature scaling. - Author modular
nn.Modulenetworks (Linear -> ReLU -> Linear) that output raw logits paired withnn.BCEWithLogitsLoss(), avoiding the double-sigmoid trap, and audit trainable vs. frozen parameter counts. - Implement the canonical 5-step PyTorch training loop (
zero_grad\(\rightarrow\)forward\(\rightarrow\)loss\(\rightarrow\)backward\(\rightarrow\)step) with sample-weighted epoch averaging and deterministic CPU seeding. - Switch cleanly to inference mode using both
model.eval()andwith torch.no_grad():, and save/reload portablemodel.state_dict()checkpoints safely viatorch.load(..., weights_only=True).
28.1 Stage 1 — First-Principles Intuition: Why PyTorch Replaces Hand-Coded Gradients
In Chapter 27, deriving chain-rule gradients by hand for a two-layer MLP revealed how neural networks learn—and also showed how fragile manual backpropagation becomes the moment you add a residual skip connection, dropout mask, or third hidden layer. PyTorch automates that entire calculus engine while keeping Python completely interactive and debuggable.
Five mental models unlock 95% of everyday PyTorch engineering:
- Tensors Are Hardware-Portable, Autograd-Aware Arrays: Like NumPy
ndarrays, PyTorch tensors store contiguous multi-dimensional numbers—but PyTorch layers default totorch.float32(half the memory and far faster on GPUs than NumPy’sfloat64), can migrate cleanly acrosscpu,cuda, and Applempsvia.to(device), and can record every arithmetic operation for differentiation. - Define-by-Run Autograd Graphs: Whenever an operation touches a tensor with
requires_grad=True, PyTorch builds a fresh Directed Acyclic Graph (DAG) on the fly. Callingloss.backward()traverses that DAG in reverse using the chain rule, stores gradients inside each leaf tensor’s.gradattribute, and immediately frees intermediate activations to save memory. - Gradients Accumulate by Design: PyTorch adds new gradients onto existing
.gradbuffers (+=) rather than overwriting them—which enables multi-step gradient accumulation for giant batches, but silently doubles or corrupts updates if you forgetoptimizer.zero_grad()! - Raw Logits +
BCEWithLogitsLossBeatSigmoid + BCELoss: Returning raw unbounded logits \(z \in (-\infty, +\infty)\) fromnn.Module.forward()letsBCEWithLogitsLossfuse sigmoid and binary cross-entropy using the log-sum-exp identity, avoiding floating-point underflow (\(\ln(0)\)) while keeping gradients crisp. model.eval()andtorch.no_grad()Solve Two Different Problems:model.eval()changes layer behavior (turning off Dropout noise and freezing BatchNorm running statistics), whereaswith torch.no_grad():turns off autograd graph construction (cutting validation memory and speeding up inference). Always pair both!
Whether you train a 97-parameter tabular MLP or a 7-billion-parameter transformer, every single mini-batch repeats the exact same five lines:
optimizer.zero_grad()— wipe stale gradients from the previous batch.logits = model(xb)— run the forward pass and record the dynamic graph.loss = criterion(logits, yb)— compute the scalar objective.loss.backward()— differentiate the graph in reverse to populate.grad.optimizer.step()— update every parameter withrequires_grad=True.
28.2 Stage 2 — Visual Mental Model: Data Pipeline, Autograd DAG & 5-Step Loop
Follow this architecture whenever you wire a tabular clinical cohort into a reproducible PyTorch training and checkpointing workflow:
Notice the strict separation of concerns across all three tiers: Data converts cleaned, leak-free scaled NumPy matrices into float32 mini-batches ((batch, p) and (batch, 1)), Forward clears old gradients and constructs the dynamic computation graph through raw logits, and Backprop & Eval updates parameters before validating gradient-free and saving portable state_dict weights.
torch.from_numpy() Aliasing Trap!
Calling torch.from_numpy(arr) (or torch.as_tensor(arr, dtype=torch.float32) when arr is already np.float32) creates a tensor that shares the exact same CPU memory buffer as arr. Mutating the NumPy array later silently overwrites your PyTorch training tensor! Use torch.tensor(arr, dtype=torch.float32) whenever you want a guaranteed, safe copy.
28.3 Stage 3 — Line-by-Line Code Walkthrough & Error Anatomy
Open part_06_deep_learning/ch28_pytorch_tensors_autograd/01_walkthrough.ipynb in Colab and execute every cell top-to-bottom alongside the dissections below.
28.3.1 Setup: Device Portability Helper & Cleaning mch_survey_sample
import os
import tempfile
import numpy as np
import pandas as pd
import torch
import torch.nn as nn
from sklearn.metrics import roc_auc_score
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from torch.utils.data import DataLoader, Dataset
import sharukh_tutor as tutor
def get_device():
if torch.cuda.is_available():
return torch.device("cuda")
if hasattr(torch.backends, "mps") and torch.backends.mps.is_available():
return torch.device("mps")
return torch.device("cpu")
device = get_device()
torch.manual_seed(42)
mch_raw = tutor.load_data("mch_survey_sample", as_pandas=True)
mch = mch_raw.copy()
mch["residence"] = (
mch["residence"].astype(str).str.strip().str.title()
)
mch["anc_visits"] = mch["anc_visits"].replace(999, np.nan)
mch["is_urban"] = (mch["residence"] == "Urban").astype(int)
wealth_map = {
"Poorest": 1, "Poorer": 2, "Middle": 3,
"Richer": 4, "Richest": 5,
}
mch["wealth_num"] = mch["wealth_quintile"].map(wealth_map)
feat_cols = [
"maternal_age_years", "anc_visits", "wealth_num", "is_urban"
]
clean = mch[["maternal_anemia", "child_stunted"] + feat_cols].dropna()
print(f"PyTorch: {torch.__version__} | Active device: {device}")
print(f"Complete MCH rows: {len(clean)} | Features: {len(feat_cols)}")Expected Output:
Writing get_device() once at the top of every notebook ensures identical code runs seamlessly on an NVIDIA Colab GPU (cuda), Apple Silicon laptop (mps), or deterministic CPU container (cpu). Setting torch.manual_seed(42) locks initial weights and DataLoader shuffling for reproducible science.
28.3.2 Tensors vs. NumPy, float32, Aliasing & Device Portability
# NumPy defaults to float64; PyTorch layers expect float32
arr_f64 = np.array([[24.0, 4.0], [31.0, 2.0]])
arr_f32 = arr_f64.astype(np.float32)
t_alias = torch.from_numpy(arr_f32) # shares memory!
t_copy = torch.tensor(arr_f32, dtype=torch.float32) # safe copy
arr_f32[0, 0] = 999.0
print(f"NumPy default dtype: {arr_f64.dtype} | PyTorch: {t_copy.dtype}")
print(f"from_numpy (aliased) [0,0]: {t_alias[0, 0].item():.1f}")
print(f"torch.tensor (safe) [0,0]: {t_copy[0, 0].item():.1f}")
t_dev = t_copy.to(device)
print(f"Shape: {tuple(t_dev.shape)} | Device: {t_dev.device}")Expected Output:
Look closely at lines 2 and 3 of the output:
- Changing
arr_f32[0, 0] = 999.0after callingtorch.from_numpy(arr_f32)silently mutatedt_alias[0, 0]to999.0because both objects point to the same underlying RAM! - By contrast,
torch.tensor(arr_f32, dtype=torch.float32)allocated an independentfloat32copy, preserving24.0untouched.
28.3.3 Dynamic Autograd Graph & the .grad.zero_() Accumulation Trap
Consider the scalar quadratic function \(y(x) = 3x^2 - 4x + 5\), whose analytical derivative is \(\frac{dy}{dx} = 6x - 4\). At \(x = 2.0\), exact calculus gives \(y = 9.0\) and \(\frac{dy}{dx} = 8.0\):
# y = 3x^2 - 4x + 5 => dy/dx = 6x - 4 (at x=2: y=9, dy/dx=8)
x = torch.tensor(2.0, requires_grad=True)
y = 3.0 * x**2 - 4.0 * x + 5.0
print(f"Forward y={y.item():.1f} | grad_fn={type(y.grad_fn).__name__}")
y.backward()
print(f"After 1st backward() -> x.grad = {x.grad.item():.1f}")
# Trap: PyTorch ACCUMULATES gradients unless you zero them!
y2 = 3.0 * x**2 - 4.0 * x + 5.0
y2.backward()
print(f"After 2nd (NO zero_grad!) -> x.grad = {x.grad.item():.1f}")
x.grad.zero_()
y3 = 3.0 * x**2 - 4.0 * x + 5.0
y3.backward()
print(f"After x.grad.zero_() + 3rd -> x.grad = {x.grad.item():.1f}")Expected Output:
Three crucial autograd lessons live in those four lines:
y.grad_fn = AddBackward0: Every computed tensor remembers the backward operator that created it, forming a chain back to leafx.- Silent accumulation (
8.0 -> 16.0): Callingy2.backward()without resettingx.gradadded8.0on top of the old8.0! In a training loop, forgettingoptimizer.zero_grad()turns every mini-batch gradient into a snowballing sum of all previous batches. - In-place underscore convention (
zero_()): Trailing underscores in PyTorch (zero_(),add_(),fill_()) mutate tensors in place; resettingx.grad.zero_()restores the exact derivative8.0.
28.3.4 Custom Dataset & Mini-Batch DataLoader on mch_survey_sample
Before constructing tensors, split mch_survey_sample stratified 75/25 on child_stunted and fit StandardScaler strictly on X_train (preventing validation leakage!), then package both splits into a reusable Dataset and DataLoader:
X_all = clean[feat_cols].to_numpy(dtype=np.float32)
y_all = clean["child_stunted"].to_numpy(dtype=np.float32)
X_tr, X_va, y_tr, y_va = train_test_split(
X_all, y_all, test_size=0.25, stratify=y_all, random_state=42
)
# Fit StandardScaler strictly on X_train to prevent leakage
scaler = StandardScaler()
X_tr_s = scaler.fit_transform(X_tr)
X_va_s = scaler.transform(X_va)
class ClinicalTabularDataset(Dataset):
def __init__(self, X, y):
self.X = torch.tensor(X, dtype=torch.float32)
self.y = torch.tensor(y, dtype=torch.float32).reshape(-1, 1)
def __len__(self):
return len(self.X)
def __getitem__(self, idx):
return self.X[idx], self.y[idx]
torch.manual_seed(42)
train_ds = ClinicalTabularDataset(X_tr_s, y_tr)
val_ds = ClinicalTabularDataset(X_va_s, y_va)
train_loader = DataLoader(train_ds, batch_size=32, shuffle=True)
val_loader = DataLoader(val_ds, batch_size=32, shuffle=False)
xb, yb = next(iter(train_loader))
print(f"Train n={len(train_ds)} | Val n={len(val_ds)}")
print(
f"First batch X: {tuple(xb.shape)} ({xb.dtype}) | "
f"y: {tuple(yb.shape)} ({yb.dtype})"
)Expected Output:
Notice two subtle best practices:
.reshape(-1, 1)onself.y: Storing targets as 2D(n, 1)rather than 1D(n,)ensures every mini-batchybhas shape(32, 1), matching the(32, 1)logits returned bynn.Linear(..., 1)with zero broadcasting surprises!shuffle=Truefor training,shuffle=Falsefor validation: Shuffling training batches breaks sample-order correlations every epoch, while keeping validation unshuffled preserves deterministic row alignment for diagnostics and auditing.
28.3.5 Defining nn.Module (ClinicalRiskMLP) & Pairing Raw Logits with BCEWithLogitsLoss
class ClinicalRiskMLP(nn.Module):
def __init__(self, in_dim, hidden_dim=16):
super().__init__()
self.net = nn.Sequential(
nn.Linear(in_dim, hidden_dim),
nn.ReLU(),
nn.Linear(hidden_dim, 1),
)
def forward(self, x):
# Return raw logits — NO sigmoid! BCEWithLogitsLoss fuses it.
return self.net(x)
torch.manual_seed(42)
model = ClinicalRiskMLP(in_dim=4, hidden_dim=16).to(device)
n_params = sum(p.numel() for p in model.parameters())
logits_0 = model(xb.to(device))
criterion = nn.BCEWithLogitsLoss()
init_loss = criterion(logits_0, yb.to(device)).item()
print(f"Total trainable parameters: {n_params}")
print(
f"Logits shape: {tuple(logits_0.shape)} | "
f"Initial batch BCE loss: {init_loss:.5f}"
)Expected Output:
Check the parameter arithmetic by hand:
- Layer 1 (
nn.Linear(4, 16)): \(4 \times 16 = 64\) weights \(+ 16\) biases \(= \mathbf{80}\) parameters. - Activation (
nn.ReLU()): \(\mathbf{0}\) parameters. - Layer 2 (
nn.Linear(16, 1)): \(16 \times 1 = 16\) weights \(+ 1\) bias \(= \mathbf{17}\) parameters. - Total: \(80 + 17 = \mathbf{97}\) trainable scalar parameters! Calling
super().__init__()inside__init__is mandatory sonn.Moduleregisters every sub-layer’s parameters intomodel.parameters()andmodel.state_dict().
28.3.6 The Canonical 5-Step PyTorch Training Loop
Now wire ClinicalRiskMLP, BCEWithLogitsLoss, and Adam(lr=0.02) together over 30 epochs, monitoring both sample-weighted training loss and validation ROC-AUC:
torch.manual_seed(42)
model = ClinicalRiskMLP(in_dim=4, hidden_dim=16).to(device)
criterion = nn.BCEWithLogitsLoss()
optimizer = torch.optim.Adam(model.parameters(), lr=0.02)
for epoch in range(1, 31):
model.train()
tr_sum, tr_n = 0.0, 0
for xb, yb in train_loader:
xb, yb = xb.to(device), yb.to(device)
optimizer.zero_grad() # 1. Clear stale gradients
logits = model(xb) # 2. Forward pass (raw logits)
loss = criterion(logits, yb) # 3. Compute scalar BCE loss
loss.backward() # 4. Backprop via autograd
optimizer.step() # 5. Update weights
tr_sum += loss.item() * len(xb)
tr_n += len(xb)
tr_loss = tr_sum / tr_n
if epoch in (1, 10, 20, 30):
model.eval()
va_sum, va_n, p_list, y_list = 0.0, 0, [], []
with torch.no_grad():
for xb, yb in val_loader:
xb, yb = xb.to(device), yb.to(device)
lg = model(xb)
va_sum += criterion(lg, yb).item() * len(xb)
va_n += len(xb)
p_list.append(torch.sigmoid(lg).cpu().numpy().ravel())
y_list.append(yb.cpu().numpy().ravel())
auc = roc_auc_score(
np.concatenate(y_list), np.concatenate(p_list)
)
print(
f"Epoch {epoch:2d} | train_loss={tr_loss:.4f} | "
f"val_loss={va_sum / va_n:.4f} | val_auc={auc:.4f}"
)Expected Output:
Read those four epochs like an experienced deep-learning researcher:
- Training loss drops cleanly from
0.5409to0.3547, while validation ROC-AUC reaches0.7905at Epoch 10—edging past Chapter 23’s linear logistic regression (0.7772) on the exact same 4 non-leaking features! - Notice also how after Epoch 10,
train_losskeeps drifting downward (0.3614 -> 0.3547) whileval_lossticks slightly upward (0.3325 -> 0.3364). That gentle divergence is early overfitting—precisely why Chapter 29 introduces dropout, weight decay, learning-rate schedules, and early stopping! - Multiplying
loss.item() * len(xb)and dividing bytr_ncomputes the exact sample-weighted epoch mean, even though the final mini-batch of 369 rows contains only369 % 32 = 17samples!
28.3.7 Inference Mode (eval() + torch.no_grad()) & Safe state_dict Checkpointing
Never save a whole PyTorch model object via torch.save(model, path)—Python pickle couples the file to your exact class path and creates arbitrary-code-execution risks. Instead, persist only model.state_dict() and reload with weights_only=True:
X_sample = torch.tensor(X_va_s[:8], dtype=torch.float32).to(device)
with tempfile.TemporaryDirectory() as tmpdir:
ckpt_path = os.path.join(tmpdir, "stunting_mlp.pt")
torch.save(model.state_dict(), ckpt_path)
file_bytes = os.path.getsize(ckpt_path)
reloaded = ClinicalRiskMLP(in_dim=4, hidden_dim=16).to(device)
state = torch.load(
ckpt_path, map_location=device, weights_only=True
)
reloaded.load_state_dict(state)
model.eval()
reloaded.eval()
with torch.no_grad():
p_orig = torch.sigmoid(model(X_sample))
p_load = torch.sigmoid(reloaded(X_sample))
exact = bool(torch.allclose(p_orig, p_load, atol=1e-6))
print(f"Checkpoint size: {file_bytes} bytes | Match: {exact}")
print(f"First 4 probs: {np.round(p_load.cpu().numpy().ravel()[:4], 4)}")Expected Output:
Wrapping temporary checkpoint experiments inside with tempfile.TemporaryDirectory() as tmpdir: guarantees zero stray .pt artifacts pollute your repository, while map_location=device and weights_only=True make your checkpoint portable across CPU/GPU machines and safe in PyTorch 2.x!
28.3.8 Break It On Purpose! (PyTorch Error Anatomy)
nn.Linear)
Python’s Traceback:
Diagnosis: NumPy arrays default to float64 (Double), whereas PyTorch layers initialize weights in torch.float32 (Float). Converting a NumPy matrix via torch.from_numpy(arr) without casting triggers this exact crash on the first forward pass.
Fix: Always convert features and binary targets with torch.tensor(arr, dtype=torch.float32).
nn.Linear)
Python’s Traceback:
Diagnosis: Matrix multiplication X @ W^T + b requires X.shape[-1] == layer.in_features. Here the batch has 3 columns while layer4 expects 4.
Fix: Inspect X.shape before model instantiation and pass in_dim=X_train.shape[1] programmatically instead of hardcoding magic integers.
.backward() on a Freed Graph)
Python’s Traceback:
Diagnosis: To keep GPU/CPU memory low, PyTorch frees intermediate autograd buffers immediately after loss.backward() completes. Calling .backward() again on the same loss tensor—or reusing a cached tensor from a previous epoch without .detach()—hits this error.
Fix: Recompute the forward pass inside each training step (one fresh graph per .backward()), or detach logged scalars with .item() / .detach(). Only pass retain_graph=True for specialized multi-loss research algorithms.
28.4 Stage 4 — The Researcher’s Problem-Structuring Blueprint
Scenario: Your health-analytics lab wants a single reproducible pipeline train_and_checkpoint_mch_mlp(raw_df, target="child_stunted", epochs=30, seed=42) that cleans mch_survey_sample without mutating it, applies leak-free StandardScaler inside a stratified 75/25 split, trains ClinicalRiskMLP with DataLoader + BCEWithLogitsLoss + Adam, evaluates validation loss and ROC-AUC under eval() + torch.no_grad(), verifies a state_dict checkpoint round-trip in TemporaryDirectory(), and returns a structured audit dictionary.
28.4.1 Blueprint (Completed on Paper Before Coding)
Deterministic Seed & Leak-Free Hygiene:
- Call
torch.manual_seed(seed)at entry and work strictly ondf = raw_df.copy(). - Clean
residencecasing, replaceanc_visits == 999withnp.nan, deriveis_urbanandwealth_num, drop missing rows across the 4 non-leaking features plustarget, and split stratified 75/25. - Fit
StandardScaler()strictly onX_tr, transformX_va, and wrap both inClinicalTabularDataset+DataLoader(batch_size=32).
- Call
5-Step Training & Gradient-Free Evaluation:
- Train
ClinicalRiskMLP(in_dim=4, hidden_dim=16)forepochsepochs withBCEWithLogitsLoss()andAdam(lr=0.02). - Switch to
net.eval()+with torch.no_grad():to compute sample-weightedval_lossandval_aucfromtorch.sigmoid(logits).
- Train
Safe Checkpointing Verification:
- Inside
with tempfile.TemporaryDirectory() as tmpdir:, savenet.state_dict(), reload into a freshClinicalRiskMLP(4, 16)viatorch.load(p, weights_only=True), switch both to.eval(), and asserttorch.allclose(net(x0), fresh(x0), atol=1e-6).
- Inside
28.4.2 Clean Python Implementation (Verbatim in 01_walkthrough.ipynb)
def train_and_checkpoint_mch_mlp(
raw_df, target="child_stunted", epochs=30, seed=42
):
"""Leak-free PyTorch MLP training + weights_only checkpoint audit."""
torch.manual_seed(seed)
df = raw_df.copy()
df["residence"] = df["residence"].astype(str).str.strip().str.title()
df["anc_visits"] = df["anc_visits"].replace(999, np.nan)
df["is_urban"] = (df["residence"] == "Urban").astype(int)
w_map = {
"Poorest": 1, "Poorer": 2, "Middle": 3,
"Richer": 4, "Richest": 5,
}
df["wealth_num"] = df["wealth_quintile"].map(w_map)
cols = ["maternal_age_years", "anc_visits", "wealth_num", "is_urban"]
sub = df[[target] + cols].dropna()
X_tr, X_va, y_tr, y_va = train_test_split(
sub[cols].to_numpy(dtype=np.float32),
sub[target].to_numpy(dtype=np.float32),
test_size=0.25, stratify=sub[target], random_state=seed,
)
sc = StandardScaler()
tr_ld = DataLoader(
ClinicalTabularDataset(sc.fit_transform(X_tr), y_tr),
batch_size=32, shuffle=True,
)
va_ld = DataLoader(
ClinicalTabularDataset(sc.transform(X_va), y_va),
batch_size=32, shuffle=False,
)
net = ClinicalRiskMLP(in_dim=4, hidden_dim=16)
crit = nn.BCEWithLogitsLoss()
opt = torch.optim.Adam(net.parameters(), lr=0.02)
for _ in range(epochs):
net.train()
for xb, yb in tr_ld:
opt.zero_grad()
loss = crit(net(xb), yb)
loss.backward()
opt.step()
net.eval()
va_sum, va_n, ps, ys = 0.0, 0, [], []
with torch.no_grad():
for xb, yb in va_ld:
lg = net(xb)
va_sum += crit(lg, yb).item() * len(xb)
va_n += len(xb)
ps.append(torch.sigmoid(lg).numpy().ravel())
ys.append(yb.numpy().ravel())
auc = round(
float(roc_auc_score(np.concatenate(ys), np.concatenate(ps))), 4
)
with tempfile.TemporaryDirectory() as tmpdir:
p = os.path.join(tmpdir, f"{target}.pt")
torch.save(net.state_dict(), p)
fresh = ClinicalRiskMLP(in_dim=4, hidden_dim=16)
fresh.load_state_dict(torch.load(p, weights_only=True))
fresh.eval()
x0 = torch.tensor(sc.transform(X_va[:8]), dtype=torch.float32)
with torch.no_grad():
ok = bool(torch.allclose(net(x0), fresh(x0), atol=1e-6))
ckpt_bytes = int(os.path.getsize(p))
return {
"val_loss": round(va_sum / va_n, 4),
"val_auc": auc,
"ckpt_bytes": ckpt_bytes,
"ckpt_match": ok,
}
for label, col in [
("Stunting", "child_stunted"),
("Anemia", "maternal_anemia"),
]:
rep = train_and_checkpoint_mch_mlp(mch_raw, target=col)
print(
f"{label:8s} | val_loss={rep['val_loss']:.4f} | "
f"val_auc={rep['val_auc']:.4f} | "
f"ckpt={rep['ckpt_bytes']}B (match={rep['ckpt_match']})"
)Output:
28.5 Stage 5 — Guided “To-Do” Practice Labs
Open part_06_deep_learning/ch28_pytorch_tensors_autograd/02_guided_todos.ipynb in Google Colab, run Step 0 to activate sharukh-tutor, and implement all six PyTorch core functions and classes below. Pass each function or class name (without parentheses!) to tutor.check(...).
- To-Do 28.1 (
numpy_to_float_tensor(arr)): Return a detachedtorch.float32tensor copy (torch.tensor(arr, dtype=torch.float32)) that does not share memory with or mutate the input NumPy array. - To-Do 28.2 (
autograd_quadratic_grad(x_val)): Createx = torch.tensor(float(x_val), requires_grad=True), evaluate \(y = 3x^2 - 4x + 5\), cally.backward(), and return(round(y.item(), 4), round(x.grad.item(), 4)). - To-Do 28.3 (
ClinicalTabularDataset): Subclasstorch.utils.data.Datasetstoringfloat32X(n, p)andy(n, 1)tensors, with__len__and__getitem__(idx)returning(self.X[idx], self.y[idx]). - To-Do 28.4 (
ClinicalRiskMLP): Subclassnn.Modulewith__init__(self, in_dim, hidden_dim=16)stackingLinear(in_dim, hidden_dim) -> ReLU -> Linear(hidden_dim, 1), andforward(x)returning raw logits of shape(batch, 1)(NO sigmoid!). - To-Do 28.5 (
train_one_epoch(model, loader, optimizer, criterion)): Switch tomodel.train(), execute the 5-step training loop on every batch, and return the mean float loss rounded to 5 decimals. - To-Do 28.6 (
evaluate_binary_logits(model, loader)): Switch tomodel.eval(), evaluate insidewith torch.no_grad():withBCEWithLogitsLoss(), convert logits viatorch.sigmoid, and return{"loss": round5, "roc_auc": round4, "accuracy": round4}.
28.6 Stage 6 — Concept & Execution Trace Test (No Computer Allowed!)
Work through all 10 PyTorch tensor, autograd, and training-loop reasoning questions on paper before checking Stage 8:
- Memory Aliasing Trace: You run
a = np.array([1.0, 2.0], dtype=np.float32),t1 = torch.from_numpy(a),t2 = torch.tensor(a, dtype=torch.float32), and thena[0] = 50.0. What aret1[0].item()andt2[0].item()? - Hand-Differentiation Check: For \(y = 3x^2 - 4x + 5\) evaluated at \(x = -1.5\), what exact values does
autograd_quadratic_grad(-1.5)return for(y, dy/dx)? - Gradient Accumulation Bug: Suppose
x = torch.tensor(1.0, requires_grad=True). In aforloop of 3 iterations, you computey = 2.0 * x**2and cally.backward()without callingx.grad.zero_(). What isx.grad.item()after iteration 3? - Parameter Count by Hand: Compute the exact total number of scalar parameters in
ClinicalRiskMLP(in_dim=6, hidden_dim=10)(Linear(6, 10) -> ReLU -> Linear(10, 1)). - Double-Sigmoid Hazard: Why does adding
nn.Sigmoid()at the end ofClinicalRiskMLP.forward()break training when paired withnn.BCEWithLogitsLoss()? - Target Shape Alignment: A mini-batch of logits from
ClinicalRiskMLPhas shape(32, 1). Why do we reshapeself.yto(n, 1)insideClinicalTabularDatasetinstead of leaving it as 1D(n,)? model.eval()vs.torch.no_grad(): A teammate wraps validation inwith torch.no_grad():but forgetsmodel.eval()on a network containingnn.Dropout(0.5). Why do validation metrics still jitter randomly from run to run?- Memory Leak in Loss Logging: Why should you accumulate
total_loss += loss.item() * len(xb)instead oftotal_loss += loss * len(xb)across thousands of batches? - Uneven Final Mini-Batch: A dataset has
369training samples andbatch_size=32(drop_last=False). How many batches doesDataLoaderyield per epoch, what is the size of the final batch, and why is sample-weighted loss more accurate than plain batch averaging? - Safe Checkpointing in PyTorch 2.x: Give two reasons why
torch.save(model.state_dict(), path)+torch.load(path, weights_only=True)is strongly preferred overtorch.save(model, path).
28.7 Stage 7 — Chapter 28 Coding Exam (100 Points)
Open part_06_deep_learning/ch28_pytorch_tensors_autograd/03_coding_exam.ipynb, implement all three functions, and run tutor.check_exam("ch28", exam_submissions) to earn your Chapter 28 Exam score out of 100 points.
28.7.1 Exam Task 28.1 (30 Points): count_model_parameters(model)
Inspect model.parameters() without modifying any requires_grad flags:
- Count total scalar elements (
p.numel()), split intotrainable_params(p.requires_grad == True) andfrozen_params(p.requires_grad == False), satisfyingtotal_params == trainable_params + frozen_params. - Return
{"total_params": int, "trainable_params": int, "frozen_params": int}.
28.7.3 Exam Task 28.3 (35 Points): save_and_verify_state_dict(model, fresh_model, X_sample, ckpt_path)
Persist and verify model weights safely in PyTorch 2.x:
- Save
model.state_dict()tockpt_pathviatorch.save(...)and reload intofresh_modelviafresh_model.load_state_dict(torch.load(ckpt_path, weights_only=True)). - Set both
model.eval()andfresh_model.eval()(critical when Dropout or BatchNorm is present!), run both onX_sampleunderwith torch.no_grad():, and verifytorch.allclose(preds_orig, preds_reloaded, atol=1e-6). - Return
{"file_bytes": int, "predictions_match": bool}.
28.8 Stage 8 — Complete Annotated Solutions & Debugging Post-Mortem
28.8.1 A. Concept & Execution Trace Test Key
t1[0].item()is50.0(becausetorch.from_numpyshares memory withfloat32NumPy arrays), whereast2[0].item()remains1.0(becausetorch.tensorcopies the buffer).- \(y(-1.5) = 3(2.25) - 4(-1.5) + 5 = 6.75 + 6.0 + 5.0 = \mathbf{17.75}\); \(\frac{dy}{dx}(-1.5) = 6(-1.5) - 4 = \mathbf{-13.0}\). Returns
(17.75, -13.0). - Each backward pass computes \(\frac{dy}{dx} = 4x = 4.0\) and adds it onto
x.grad. After 3 unzeroed iterations,x.grad.item()\(= 4.0 + 4.0 + 4.0 = \mathbf{12.0}\). - Layer 1: \(6 \times 10 + 10 = 70\); ReLU: \(0\); Layer 2: \(10 \times 1 + 1 = 11\); Total \(= 70 + 11 = \mathbf{81}\) parameters.
BCEWithLogitsLossapplies sigmoid internally; addingnn.Sigmoid()inforward()applies sigmoid twice (\(\sigma(\sigma(z)) \in (0.50, 0.731)\)), making probabilities below0.50impossible and crushing gradients!BCEWithLogitsLossexpects predictions and targets to share exact shape(batch, 1). Leavingyas 1D(32,)raises a shape-mismatchValueError(or causes unintended(32, 32)outer broadcasting in some tensor operations).torch.no_grad()only disables autograd tracking; it does not disableDropoutrandomness! You must callmodel.eval()to turn off Dropout and freeze BatchNorm statistics.- Adding the live tensor
lossretains a pointer to every batch’s entire autograd computation graph in Python RAM/VRAM until the epoch finishes (classic OOM memory leak!). Callingloss.item()extracts a plain Pythonfloatand lets PyTorch free the graph immediately. ceil(369 / 32) = 12batches: eleven batches of32(352samples) plus one final batch of17samples. Plain batch averaging gives those 17 patients the same weight as 32 patients, whereas sample-weighted averaging computes the exact per-patient mean loss.- Saving
state_dict()decouples learned weights from Python class/module file paths (so refactoring code never breaks old checkpoints) and letstorch.load(..., weights_only=True)load pure tensors without executing arbitrary untrusted pickle code.
28.8.2 B. Annotated Solutions — Guided To-Dos (Mirrored in 02_guided_todos_SOLUTION.ipynb)
import numpy as np
import torch
import torch.nn as nn
from sklearn.metrics import roc_auc_score
from torch.utils.data import DataLoader, Dataset
# To-Do 28.1
def numpy_to_float_tensor(arr):
"""Return a detached torch.float32 copy with no shared memory."""
return torch.tensor(arr, dtype=torch.float32)
# To-Do 28.2
def autograd_quadratic_grad(x_val):
"""Compute y = 3x^2 - 4x + 5 and dy/dx via PyTorch autograd."""
x = torch.tensor(float(x_val), requires_grad=True)
y = 3.0 * x**2 - 4.0 * x + 5.0
y.backward()
return (round(y.item(), 4), round(x.grad.item(), 4))
# To-Do 28.3
class ClinicalTabularDataset(Dataset):
"""PyTorch Dataset storing float32 tabular X (n, p) and y (n, 1)."""
def __init__(self, X, y):
self.X = torch.tensor(X, dtype=torch.float32)
self.y = torch.tensor(y, dtype=torch.float32).reshape(-1, 1)
def __len__(self):
return len(self.X)
def __getitem__(self, idx):
return self.X[idx], self.y[idx]
# To-Do 28.4
class ClinicalRiskMLP(nn.Module):
"""Two-layer ReLU MLP outputting raw binary logits (batch, 1)."""
def __init__(self, in_dim, hidden_dim=16):
super().__init__()
self.net = nn.Sequential(
nn.Linear(in_dim, hidden_dim),
nn.ReLU(),
nn.Linear(hidden_dim, 1),
)
def forward(self, x):
return self.net(x)
# To-Do 28.5
def train_one_epoch(model, loader, optimizer, criterion):
"""Run one canonical 5-step training epoch and return mean loss."""
model.train()
total_loss, total_n = 0.0, 0
for xb, yb in loader:
optimizer.zero_grad()
logits = model(xb)
loss = criterion(logits, yb)
loss.backward()
optimizer.step()
total_loss += loss.item() * len(xb)
total_n += len(xb)
return round(total_loss / total_n, 5)
# To-Do 28.6
def evaluate_binary_logits(model, loader):
"""Evaluate raw-logit binary classifier under eval() + no_grad()."""
model.eval()
criterion = nn.BCEWithLogitsLoss()
total_loss, total_n = 0.0, 0
probs_list, y_list = [], []
with torch.no_grad():
for xb, yb in loader:
logits = model(xb)
total_loss += criterion(logits, yb).item() * len(xb)
total_n += len(xb)
probs_list.append(torch.sigmoid(logits).cpu().numpy().ravel())
y_list.append(yb.cpu().numpy().ravel())
probs = np.concatenate(probs_list)
y_true = np.concatenate(y_list).astype(int)
preds = (probs >= 0.5).astype(int)
return {
"loss": round(total_loss / total_n, 5),
"roc_auc": round(float(roc_auc_score(y_true, probs)), 4),
"accuracy": round(float(np.mean(preds == y_true)), 4),
}28.8.3 C. Annotated Solutions — Chapter 28 Exam (Mirrored in 03_coding_exam_SOLUTION.ipynb)
import os
from torch.utils.data import TensorDataset
# Exam Task 28.1 (30 pts)
def count_model_parameters(model):
"""Count total, trainable, and frozen scalar parameters in model."""
total = sum(p.numel() for p in model.parameters())
trainable = sum(
p.numel() for p in model.parameters() if p.requires_grad
)
frozen = total - trainable
return {
"total_params": int(total),
"trainable_params": int(trainable),
"frozen_params": int(frozen),
}
# Exam Task 28.2 (35 pts)
def train_pytorch_tabular_model(
X_train, y_train, X_val, y_val,
hidden_dim=16, epochs=40, lr=0.02, batch_size=32, seed=42,
):
"""Train a 2-layer ReLU MLP with DataLoader, Adam & BCEWithLogits."""
torch.manual_seed(seed)
X_tr_t = torch.tensor(X_train, dtype=torch.float32)
y_tr_t = torch.tensor(y_train, dtype=torch.float32).reshape(-1, 1)
X_va_t = torch.tensor(X_val, dtype=torch.float32)
y_va_t = torch.tensor(y_val, dtype=torch.float32).reshape(-1, 1)
tr_loader = DataLoader(
TensorDataset(X_tr_t, y_tr_t), batch_size=batch_size, shuffle=True
)
va_loader = DataLoader(
TensorDataset(X_va_t, y_va_t), batch_size=batch_size, shuffle=False
)
model = nn.Sequential(
nn.Linear(X_tr_t.shape[1], hidden_dim),
nn.ReLU(),
nn.Linear(hidden_dim, 1),
)
criterion = nn.BCEWithLogitsLoss()
optimizer = torch.optim.Adam(model.parameters(), lr=lr)
train_losses, val_losses = [], []
for _ in range(epochs):
model.train()
tr_sum, tr_n = 0.0, 0
for xb, yb in tr_loader:
optimizer.zero_grad()
loss = criterion(model(xb), yb)
loss.backward()
optimizer.step()
tr_sum += loss.item() * len(xb)
tr_n += len(xb)
train_losses.append(round(tr_sum / tr_n, 5))
model.eval()
va_sum, va_n = 0.0, 0
with torch.no_grad():
for xb, yb in va_loader:
va_sum += criterion(model(xb), yb).item() * len(xb)
va_n += len(xb)
val_losses.append(round(va_sum / va_n, 5))
model.eval()
with torch.no_grad():
probs = torch.sigmoid(model(X_va_t)).cpu().numpy().ravel()
val_auc = round(float(roc_auc_score(y_val, probs)), 4)
return {
"train_losses": train_losses,
"val_losses": val_losses,
"val_auc": val_auc,
"model": model,
}
# Exam Task 28.3 (35 pts)
def save_and_verify_state_dict(model, fresh_model, X_sample, ckpt_path):
"""Save model.state_dict(), reload with weights_only=True & verify."""
torch.save(model.state_dict(), ckpt_path)
state = torch.load(ckpt_path, weights_only=True)
fresh_model.load_state_dict(state)
model.eval()
fresh_model.eval()
with torch.no_grad():
preds_orig = model(X_sample)
preds_reloaded = fresh_model(X_sample)
match = bool(torch.allclose(preds_orig, preds_reloaded, atol=1e-6))
return {
"file_bytes": int(os.path.getsize(ckpt_path)),
"predictions_match": match,
}28.8.4 D. Debugging Post-Mortem: Top 3 Chapter 28 Failure Modes
- Forgetting
optimizer.zero_grad()Inside the Batch Loop: Because PyTorch accumulates gradients (+=) by default, omittingoptimizer.zero_grad()causes stale batch gradients to stack up across steps—exploding or stalling updates even when your model architecture and loss function are 100% correct. - Double-Sigmoid (
nn.Sigmoid+BCEWithLogitsLoss) or Float64 Dtype Crashes: Puttingnn.Sigmoid()insideforward()while training withBCEWithLogitsLoss()traps outputs in(0.5, 0.73), while feeding default NumPyfloat64arrays intonn.LinearraisesRuntimeError: expected Double and Float. Always cast inputs totorch.float32and emit raw logits. - Omitting
model.eval()During Validation or Checkpoint Verification: Running undertorch.no_grad()alone leavesnn.Dropoutactive, injecting random noise into validation AUC and breakingtorch.allclosecheckpoint equivalence checks. Always pairmodel.eval()withwith torch.no_grad():and reloadstate_dictwithweights_only=True.
You now command PyTorch’s complete core engine—float32 tensors, autograd, custom Dataset/DataLoader, nn.Module, the 5-step training loop, and safe state_dict checkpointing. In Chapter 29, you will diagnose why deep networks overfit or stall, and master SGD + Momentum vs. AdamW, learning-rate schedules, BatchNorm/LayerNorm, Dropout & Weight Decay, gradient clipping, and early stopping with best-checkpoint restoration!


