PyTorch
PyTorch is a tensor library with automatic differentiation and building blocks for neural networks. This page covers the parts you use in every project: tensors, autograd, models, data loading, losses, optimizers, a complete training loop, regularization, checkpoints and reproducibility. Everything runs on the CPU. The examples use data/customers.csv (churn). The blocks share one session:
import copy
import numpy as npimport pandas as pdimport torchfrom torch import nnfrom torch.utils.data import DataLoader, Dataset, TensorDataset
torch.set_num_threads(1) # repeatable sums; no clash with other processestorch.manual_seed(42) # weights, dropout, torch.rand*print(torch.get_num_threads(), torch.rand(3))1 tensor([0.8823, 0.9150, 0.3829])Quick lookup
Section titled “Quick lookup”| I want to… | Use… | Notes |
|---|---|---|
| a tensor from a list | torch.tensor([1.0, 2.0]) |
copies; float32 |
| a float32 tensor from NumPy | torch.as_tensor(arr, dtype=torch.float32) |
NumPy is float64 |
| a NumPy array back | t.detach().numpy() |
shares memory |
| one Python number | t.item() |
loss.item() |
| change the dtype | t.float(), t.long(), t.to(torch.int64) |
|
| reshape | t.reshape(n, -1), t.unsqueeze(1), t.squeeze(1) |
-1 = infer |
| reduce over rows | t.mean(dim=0) |
keepdim=True keeps the axis |
| join tensors | torch.cat([a, b], dim=0), torch.stack([a, b]) |
stack adds a dimension |
| track gradients | torch.tensor(1.0, requires_grad=True) |
leaf tensor |
| compute gradients | loss.backward(), then w.grad |
gradients add up |
| run without a graph | with torch.no_grad(): |
prediction, updates |
| write a model | subclass nn.Module, define forward |
layers in __init__ |
| chain layers | nn.Sequential(nn.Linear(7, 32), nn.ReLU(), ...) |
|
| count parameters | sum(p.numel() for p in model.parameters()) |
|
| wrap arrays as a dataset | TensorDataset(X, y) |
|
| a dataset from a DataFrame | subclass Dataset: __len__, __getitem__ |
|
| shuffled mini-batches | DataLoader(ds, batch_size=64, shuffle=True, generator=g) |
g = seeded torch.Generator |
| a regression loss | nn.MSELoss(), nn.L1Loss(), nn.HuberLoss() |
float targets |
| a binary loss | nn.BCEWithLogitsLoss(pos_weight=w) |
raw logits in |
| a multiclass loss | nn.CrossEntropyLoss() |
int64 class indices |
| a default optimizer | torch.optim.AdamW(model.parameters(), lr=1e-3) |
|
| weight decay | AdamW(..., weight_decay=0.01) |
decoupled L2 |
| lower the rate on a plateau | lr_scheduler.ReduceLROnPlateau(opt, patience=3) |
sched.step(val_loss) |
| dropout | nn.Dropout(p=0.3) after an activation |
train mode only |
| switch dropout and batch norm | model.train() / model.eval() |
not the same as no_grad |
| probabilities from logits | torch.sigmoid(z), z.softmax(dim=1) |
|
| the predicted class | z.argmax(dim=1) |
|
| keep the best weights | copy.deepcopy(model.state_dict()) |
not a reference |
| save weights | torch.save({"config": cfg, "state_dict": sd}, path) |
|
| load weights safely | torch.load(path, weights_only=True) |
the default since PyTorch 2.6; write it for older versions |
| pick a device | device = "cuda" if torch.cuda.is_available() else "cpu" |
torch.backends.mps.is_available() on Apple |
| move a model and a batch | model.to(device), xb.to(device) in the loop |
the same device for both |
| a GPU tensor as NumPy | t.detach().cpu().numpy() |
.cpu() first |
| repeatable runs | torch.manual_seed(42), torch.set_num_threads(1) |
plus a seeded generator |
Tensors
Section titled “Tensors”X = torch.arange(12.0).reshape(3, 4) # 3 rows, 4 featuresprint(X.shape, X.dtype, X[:, 0].shape, X[:, :1].shape, X.unsqueeze(0).shape)print(X.sum(dim=0), X.argmax(dim=1), (X @ torch.ones(4)).tolist())Z = (X - X.mean(dim=0)) / X.std(dim=0, correction=0) # broadcasting, like NumPyprint(Z[0], torch.from_numpy(np.ones(2)).dtype) # NumPy float64 stays float64torch.Size([3, 4]) torch.float32 torch.Size([3]) torch.Size([3, 1]) torch.Size([1, 3, 4])tensor([12., 15., 18., 21.]) tensor([3, 3, 3]) [6.0, 22.0, 38.0]tensor([-1.2247, -1.2247, -1.2247, -1.2247]) torch.float64| dtype | Use | Convert |
|---|---|---|
float32 |
features, weights, MSE and BCE targets | .float() |
float64 |
NumPy default; gradient checks | .double() |
int64 |
class indices for CrossEntropyLoss, nn.Embedding input |
.long() |
bool |
masks: t[t > 0] |
| Shape tool | Effect |
|---|---|
reshape(a, b) / view(a, b) |
new shape; view needs contiguous memory |
unsqueeze(d) / squeeze(d) |
add / remove a size-1 dimension |
flatten(start_dim=1) |
keep the batch dimension, join the rest |
t.T, permute(0, 2, 3, 1) |
swap / reorder dimensions |
cat(dim=0) / stack() |
join along an existing / a new dimension |
| NumPy interop | Copies | dtype |
|---|---|---|
torch.from_numpy(arr) |
no, shared memory | kept |
torch.as_tensor(arr, dtype=torch.float32) |
only if the dtype changes | as asked |
torch.tensor(arr) |
always | kept |
t.numpy() |
no, shared memory | kept; fails if requires_grad |
t.detach().numpy() |
no | safe for tensors in a graph |
Autograd
Section titled “Autograd”w = torch.tensor(2.0, requires_grad=True)loss = (3.0 * w - 5.0) ** 2 # dL/dw = 6 * (3w - 5) = 6loss.backward()print(w.grad)with torch.no_grad(): # update outside the graph w -= 0.1 * w.gradw.grad.zero_() # backward() adds to .grad: reset itprint(round(w.item(), 2), w.grad)tensor(6.)1.4 tensor(0.)| Rule | Code |
|---|---|
| gradients accumulate | optimizer.zero_grad() before every backward() |
| update weights outside the graph | with torch.no_grad(): w -= lr * w.grad |
| leave the graph to plot or store | t.detach() |
| sum losses for logging | total += loss.item(), not total += loss |
only leaf tensors keep .grad |
create weights with requires_grad=True |
The nn.Module template
Section titled “The nn.Module template”class MLP(nn.Module): """n_features -> hidden layers -> n_out logits."""
def __init__(self, n_features: int, hidden: tuple[int, ...] = (32, 16), n_out: int = 1, dropout: float = 0.0) -> None: super().__init__() # always first layers: list[nn.Module] = [] sizes = (n_features, *hidden) for size_in, size_out in zip(sizes[:-1], sizes[1:], strict=True): layers += [nn.Linear(size_in, size_out), nn.ReLU(), nn.Dropout(dropout)] layers.append(nn.Linear(sizes[-1], n_out)) self.net = nn.Sequential(*layers) # registered: its weights are parameters self.n_out = n_out
def forward(self, x: torch.Tensor) -> torch.Tensor: out = self.net(x) return out.squeeze(1) if self.n_out == 1 else out # (n,) or (n, K)
model = MLP(7)print(sum(p.numel() for p in model.parameters()), model(torch.zeros(5, 7)).shape)print([name for name, _ in model.named_parameters()][:2])801 torch.Size([5])['net.0.weight', 'net.0.bias']| Layer | Shape in → out | Parameters |
|---|---|---|
nn.Linear(i, o) |
(n, i) → (n, o) |
i·o + o |
nn.ReLU(), nn.GELU(), nn.Tanh() |
same | 0 |
nn.Dropout(p) |
same | 0 |
nn.BatchNorm1d(f), nn.LayerNorm(f) |
(n, f) → (n, f) |
2f |
nn.Embedding(v, d) |
(n,) int64 → (n, d) |
v·d |
nn.Conv2d(c, k, 3, padding=1) |
(n, c, H, W) → (n, k, H, W) |
k·c·9 + k |
nn.MaxPool2d(2) |
(n, c, H, W) → (n, c, H/2, W/2) |
0 |
nn.Flatten() |
(n, c, H, W) → (n, c·H·W) |
0 |
Layers created in __init__ as attributes (or inside nn.Sequential, nn.ModuleList) are registered. A plain Python list of layers is not: its weights are invisible to the optimizer and to state_dict().
Dataset and DataLoader
Section titled “Dataset and DataLoader”from sklearn.model_selection import train_test_splitfrom sklearn.preprocessing import StandardScaler
customers = pd.read_csv("data/customers.csv")features = ["tenure_months", "monthly_charges", "support_tickets", "logins_last_30d", "avg_session_minutes", "has_autopay", "age"]train_df, valid_df = train_test_split(customers, test_size=0.2, stratify=customers["churned"], random_state=42)scaler = StandardScaler().fit(train_df[features]) # fit on training rows only
class ChurnDataset(Dataset): def __init__(self, df: pd.DataFrame) -> None: self.X = torch.as_tensor(scaler.transform(df[features]), dtype=torch.float32) self.y = torch.tensor(df["churned"].to_numpy(), dtype=torch.float32) # copy
def __len__(self) -> int: return len(self.y)
def __getitem__(self, i: int) -> tuple[torch.Tensor, torch.Tensor]: return self.X[i], self.y[i]
train_ds, valid_ds = ChurnDataset(train_df), ChurnDataset(valid_df)g = torch.Generator().manual_seed(42) # repeatable shufflingtrain_loader = DataLoader(train_ds, batch_size=64, shuffle=True, generator=g)valid_loader = DataLoader(valid_ds, batch_size=256) # no shuffle for evaluationxb, yb = next(iter(train_loader))print(len(train_ds), len(train_loader), xb.shape, xb.dtype, yb.shape)4000 63 torch.Size([64, 7]) torch.float32 torch.Size([64])DataLoader argument |
Effect |
|---|---|
batch_size=64 |
rows per optimizer step |
shuffle=True |
new order every epoch: training only |
generator=torch.Generator().manual_seed(42) |
repeatable order |
drop_last=True |
skip the last, smaller batch |
num_workers=2 |
load in subprocesses; needs if __name__ == "__main__": in scripts |
collate_fn=f |
custom batching (padding variable-length sequences) |
TensorDataset(X, y) |
the quick dataset for tensors already in memory |
Losses and target formats
Section titled “Losses and target formats”| Task | Last layer | Loss | Model output | Target | Predict |
|---|---|---|---|---|---|
| regression | Linear(h, 1) |
MSELoss(), L1Loss(), HuberLoss() |
float (n,) |
float (n,) |
the output |
| binary | Linear(h, 1) |
BCEWithLogitsLoss(pos_weight=w) |
logits (n,) |
float 0./1. (n,) |
torch.sigmoid(z) |
| multiclass | Linear(h, K) |
CrossEntropyLoss(weight=w) |
logits (n, K) |
int64 (n,) in 0..K-1, or float probabilities (n, K) |
z.softmax(1), z.argmax(1) |
| multilabel | Linear(h, K) |
BCEWithLogitsLoss() |
logits (n, K) |
float 0./1. (n, K) |
torch.sigmoid(z) > 0.5 |
logits = torch.tensor([2.0, -1.0, 0.5])print(round(nn.BCEWithLogitsLoss()(logits, torch.tensor([1.0, 0.0, 1.0])).item(), 4))scores = torch.tensor([[2.0, 0.1, -1.0], [0.0, 1.5, 0.2]]) # (n=2, K=3)print(round(nn.CrossEntropyLoss()(scores, torch.tensor([0, 1])).item(), 4))print(scores.softmax(dim=1).sum(dim=1), scores.argmax(dim=1))0.30480.2922tensor([1., 1.]) tensor([0, 1])The wrong target dtype fails loudly:
nn.CrossEntropyLoss()(scores, torch.tensor([0.0, 1.0])) # float labels of shape (n,)RuntimeError: expected target dtype to be Long or Byte, but got Floatpos_weight = n_negative / n_positive balances a rare positive class, like class_weight="balanced" in scikit-learn. Never put a sigmoid before BCEWithLogitsLoss or a softmax before CrossEntropyLoss: they apply it inside, in a numerically stable way.
Optimizers and schedulers
Section titled “Optimizers and schedulers”| Optimizer | Use | Typical lr |
|---|---|---|
torch.optim.SGD(p, lr, momentum=0.9) |
simple models; tuned schedules | 0.01–0.1 |
torch.optim.Adam(p, lr) |
a fast default | 1e-3 |
torch.optim.AdamW(p, lr, weight_decay=0.01) |
the default with decoupled weight decay | 1e-3 |
Scheduler (torch.optim.lr_scheduler) |
Step call | Effect |
|---|---|---|
StepLR(opt, step_size=10, gamma=0.5) |
sched.step() per epoch |
halve every 10 epochs |
ReduceLROnPlateau(opt, factor=0.5, patience=3) |
sched.step(val_loss) |
lower when validation stalls |
OneCycleLR(opt, max_lr, total_steps) |
sched.step() per batch |
warm up, then anneal |
CosineAnnealingLR(opt, T_max=epochs) |
sched.step() per epoch |
smooth decay |
Build the optimizer after the model, and call sched.step() after optimizer.step().
The training loop template
Section titled “The training loop template”def train_one_epoch(model, loader, loss_fn, optimizer) -> float: model.train() # dropout on total = 0.0 for xb, yb in loader: optimizer.zero_grad() # 1. clear old gradients loss = loss_fn(model(xb), yb) # 2. forward loss.backward() # 3. gradients optimizer.step() # 4. update total += loss.item() * len(yb) # .item(): no graph kept return total / len(loader.dataset)
@torch.no_grad() # no graph during evaluationdef evaluate(model, loader, loss_fn) -> float: model.eval() # dropout off total = sum(loss_fn(model(xb), yb).item() * len(yb) for xb, yb in loader) return total / len(loader.dataset)
def fit(model, train_loader, valid_loader, loss_fn, optimizer, epochs=50, patience=5): best_loss, best_state, bad = float("inf"), None, 0 for epoch in range(1, epochs + 1): train_loss = train_one_epoch(model, train_loader, loss_fn, optimizer) valid_loss = evaluate(model, valid_loader, loss_fn) if valid_loss < best_loss - 1e-4: # early stopping on the validation loss best_loss, bad = valid_loss, 0 best_state = copy.deepcopy(model.state_dict()) # a copy, not a view else: bad += 1 if epoch % 5 == 0 or bad == patience: print(f"epoch {epoch:2d} train {train_loss:.4f} valid {valid_loss:.4f}") if bad == patience: break model.load_state_dict(best_state) # restore the best epoch return best_loss
torch.manual_seed(42)model = MLP(len(features), hidden=(32, 16), dropout=0.2)optimizer = torch.optim.AdamW(model.parameters(), lr=3e-3, weight_decay=0.01)best = fit(model, train_loader, valid_loader, nn.BCEWithLogitsLoss(), optimizer)print("best valid loss", round(best, 4))epoch 5 train 0.4131 valid 0.4001epoch 10 train 0.4019 valid 0.3958epoch 15 train 0.3974 valid 0.3846epoch 20 train 0.3849 valid 0.3829epoch 25 train 0.3833 valid 0.3822epoch 30 train 0.3834 valid 0.3818epoch 34 train 0.3777 valid 0.3839best valid loss 0.3799from sklearn.metrics import roc_auc_score
model.eval()with torch.no_grad(): proba = torch.sigmoid(model(valid_ds.X)).numpy() # logits -> probabilitiesprint(proba[:3].round(3), round(roc_auc_score(valid_ds.y.numpy(), proba), 3))[0.085 0.483 0.064] 0.812model.train() |
model.eval() |
torch.no_grad() |
|
|---|---|---|---|
| dropout | active | off | unchanged |
| batch norm | batch statistics; updates running stats | running stats | unchanged |
| graph recorded | yes | yes | no |
| use for | training steps | validation, prediction | validation, prediction, manual updates |
Regularization
Section titled “Regularization”| Tool | Code | Effect |
|---|---|---|
| dropout | nn.Dropout(0.2) after each activation |
zeroes 20% of values in training, scales the rest by 1/0.8 |
| weight decay | AdamW(..., weight_decay=0.01) |
shrinks every weight a little each step |
| early stopping | patience on the validation loss, restore the best state |
stops when overfitting starts |
| a smaller network | fewer or narrower layers | fewer parameters to memorize with |
| more data, augmentation | flips, crops, noise | more variety |
| batch norm | nn.BatchNorm1d(h) before the activation |
stabler training; some regularization |
Signs of overfitting: the training loss keeps falling while the validation loss rises. Signs of underfitting: both stay high; use a bigger network, a higher lr or more epochs.
Saving and loading
Section titled “Saving and loading”from pathlib import Path
Path("output").mkdir(exist_ok=True)config = {"n_features": len(features), "hidden": [32, 16], "dropout": 0.2}torch.save({"config": config, "state_dict": model.state_dict()}, "output/churn_mlp.pt")ckpt = torch.load("output/churn_mlp.pt", weights_only=True) # the default; explicitcfg = ckpt["config"]restored = MLP(cfg["n_features"], tuple(cfg["hidden"]), dropout=cfg["dropout"])print(restored.load_state_dict(ckpt["state_dict"]))restored.eval()with torch.no_grad(): print(torch.equal(restored(valid_ds.X), model(valid_ds.X)))<All keys matched successfully>True| Do | Avoid |
|---|---|
save model.state_dict() plus a config dict |
torch.save(model, path): pickles the class path |
torch.load(path, weights_only=True) (explicit; the default since 2.6) |
weights_only=False on files from others |
| save the scaler and the feature list next to the weights | a model you cannot feed |
| save optimizer state, epoch and RNG states to resume training | resuming with a fresh optimizer |
model.eval() after loading |
predicting with dropout on |
model.load_state_dict(sd, strict=True) (default) |
strict=False hides missing keys |
Reproducibility
Section titled “Reproducibility”| Source of variation | Control |
|---|---|
initial weights, dropout, torch.rand* |
torch.manual_seed(42) before building the model |
DataLoader shuffling |
generator=torch.Generator().manual_seed(42) |
| NumPy and scikit-learn steps | np.random.default_rng(42), random_state=42 |
| float sums that depend on the thread count | torch.set_num_threads(1) |
| several processes on all cores | torch.set_num_threads(1) in each worker |
| nondeterministic kernels | torch.use_deterministic_algorithms(True) |
DataLoader workers |
worker_init_fn that seeds NumPy per worker |
| library versions | pin torch in requirements.txt or pyproject.toml |
The same seed on another machine, thread count or PyTorch version can give slightly different numbers. Compare runs with a tolerance (torch.allclose), not exact equality.
Gotchas
Section titled “Gotchas”| Trap | Symptom | Fix |
|---|---|---|
| float64 NumPy input | RuntimeError: mat1 and mat2 must have the same dtype |
torch.as_tensor(arr, dtype=torch.float32) |
torch.std default |
values differ from NumPy and StandardScaler |
std(correction=0) |
from_numpy shares memory |
changing the array changes the tensor | torch.tensor(arr) or .clone() |
no zero_grad() |
the loss jumps or diverges | optimizer.zero_grad() each step |
| sigmoid or softmax before the loss | slow learning, unstable loss | pass raw logits |
output (n, 1), target (n,) |
BCE ValueError; MSE broadcasts to (n, n) with a warning |
squeeze(1) the output |
float class labels for CrossEntropyLoss |
RuntimeError: expected target dtype to be Long or Byte |
y.long() |
torch.as_tensor(series.to_numpy()) in pandas 3 |
UserWarning: the NumPy array is not writable |
torch.tensor(...) copies; or to_numpy(copy=True) |
eval() forgotten |
predictions change between calls (dropout) | model.eval() before predicting |
no_grad() thought to switch modes |
dropout still on | use eval() and no_grad() together |
best weights stored as model.state_dict() |
the “best” weights change with training | copy.deepcopy(model.state_dict()) |
| layers kept in a plain list | they do not train; missing from state_dict |
nn.ModuleList or nn.Sequential |
| optimizer built before a model rebuild | the new model does not learn | build the optimizer after the model |
total += loss |
memory grows every step | total += loss.item() |
Conv2d on (n, H, W) |
channel-count error | add the channel axis: x.unsqueeze(1) |
torch.load(path, weights_only=False) on a file from others |
runs pickled code from the file | keep the default safe mode; pass weights_only=True explicitly on PyTorch older than 2.6 |
torch.save(model, path), then torch.load(path) |
UnpicklingError: safe mode refuses a pickled module |
save and load the state_dict |
| tensors on different devices | RuntimeError, for example Tensor for argument input is on cpu but expected on mps |
move the model and each batch with .to(device) |
| scaler fitted on all rows | optimistic validation loss | fit the scaler on the training rows only |
Learn more
Section titled “Learn more”- Module 42 lesson: deep learning with PyTorch and its cheat sheet
- Module 32: math for ML for gradients and gradient descent
- Module 36: classification for logits, probabilities and class weights
- Module 44: ML in production for serving a saved model
- Master cheat sheet: NumPy, deployment and the ML workflow