Quick Reference · deep learning in Python · torch 2.13 (Jul 2026)

pytorch + torchvision · torchaudio

One idea holds the whole library together: a tensor remembers how it was made. That record is the autograd graph, and loss.backward() simply walks it backwards to fill in .grad. Layers, optimizers, data loaders and the two domain packages are all conveniences built around that single mechanism.

setup & inspect tensors & shapes autograd & nn data, optim, loop device, compile, deploy domain library gotcha / removed most common

Cross-checked against: docs.pytorch.org (torch · vision · audio API refs) · pytorch.org/blog (2.13 release) · github.com/pytorch (release notes, audio#3902) · the official PyTorch Cheat Sheet tutorial · learnpytorch.io

The loop everything serves  ·  and the three packages that feed it
ONE TRAINING STEP DataLoader batches a Dataset for x, y in loader: model(x) nn.Module forward builds the graph loss_fn(pred, y) one scalar tensor the graph's root loss.backward() walks the graph back fills every .grad opt.step() applies the grads to the parameters opt.zero_grad() → next batch WHAT LIVES WHERE, IN 2026 torchvision transforms.v2 · models + weights datasets · ops · image decode images: still here torchaudio transforms · functional · models pipelines · datasets · kaldi maintenance phase since 2.9 torchcodec audio + video decode / encode separate install · not bundled video I/O moved out (torchvision 0.26) · audio I/O moved out (torchaudio 2.9) torch the core · everything above is optional Tensor · autograd · nn · optim · utils.data · compile · distributed pin the triple: torch 2.13 · torchvision 0.28 · torchaudio 2.10 (audio no longer tracks torch)
# the whole library in twelve lines
import torch, torch.nn as nn
dev   = torch.accelerator.current_accelerator() if torch.accelerator.is_available() else "cpu"
model = nn.Sequential(nn.Linear(784, 128), nn.ReLU(), nn.Linear(128, 10)).to(dev)
opt   = torch.optim.AdamW(model.parameters(), lr=1e-3)
lossf = nn.CrossEntropyLoss()          # takes raw logits, not softmax

model.train()
for x, y in loader:
    x, y = x.to(dev), y.to(dev)
    loss = lossf(model(x), y)      # forward: the graph is recorded here
    opt.zero_grad()               # grads ACCUMULATE — clear them first
    loss.backward()               # backward: the graph is walked and freed
    opt.step()                    # parameters move
Read this once and most of the reference below is just filling in the blanks.
PART I

torch  ·  the core

Tensors, autograd, layers, optimizers, data and the runtime. Nothing here needs torchvision or torchaudio installed.

01Install & verifyonce per env
02The import mapwhat lives where
03Create tensorsthe only data type
04Attributes & dtypesread before you debug
05Shape surgerywhere most bugs live
06Broadcastingthe silent bug factory
07Index, slice, reduceNumPy rules apply
08Math & linear algebrathe actual compute
09Devices & precisioncuda · mps · xpu · cpu
10Autogradthe mechanism
11nn.Moduleevery model is one
12Layersnn.* building blocks
13Losses & activationspick by task
14Optimizers & schedulestorch.optim
15Dataset & DataLoadertorch.utils.data
16The training loopno framework required
17Save, load, checkpointstate dicts
18torch.compile & speedthe 2.x headline
19Memory & OOMwhen CUDA runs out
20Scale out & shipmulti-GPU · export
21Debug & reproducebefore you blame the model
PART II

torchvision  ·  images

Datasets, augmentation, pretrained models and vision ops. Two things changed recently and most tutorials online have not caught up: transforms live in transforms.v2, and video decoding was removed in 0.26 — image decoding stays.

V1What's insidesix namespaces
V2transforms v2 · the pipelinethe canonical order
V3Transforms worth knowinggeometry · colour
V4TVTensorsdetection & segmentation
V5Datasetsbuilt in
V6Models & weightsthe enum API
V7ops & utilsdetection plumbing
V8Image I/Oand where video went
V9Detection & segmentationthe other two heads
PART III

torchaudio  ·  sound

Read this first: since 2.9 torchaudio is in a declared maintenance phase. Its strengths — transforms, functional, models, pipelines, datasets, compliance.kaldi — are staying. Decoding and encoding moved out to TorchCodec, and torchaudio.io, torio and sox_effects were deleted. Anything on the web that streams audio through StreamReader is now broken code.

A1What survivedthe 2.9 cut
A2Load & savenow via TorchCodec
A3Spectrogram familywaveform → features
A4Resample & augmentSpecAugment
A5functionalstateless ops
A6Pipelines & modelspretrained speech
A7Datasets & batchingragged by nature
A8Speech to text, end to endthe whole path

Four pictures worth the whole reference

The mechanism, the shapes, the package boundaries, and the audio feature chain.

1 · the autograd graph

Forward builds the graph as a side effect. Backward walks the same edges in reverse, multiplying local derivatives.

x w × + b loss loss.backward() → w.grad, b.grad recorded because requires_grad=True

2 · the shape rosetta

Half of all PyTorch errors are one of these four conventions used in the wrong place.

(N, C, H, W) images · Conv2d batch, channels, height, width — channels FIRST, unlike PIL/NumPy (N, L, E) sequences · Transformer batch, length, embedding — only with batch_first=True (channel, time) waveform · torchaudio.load no batch dim — librosa returns bare (time,) (channel, freq, time) spectrogram freq = n_fft//2 + 1, or n_mels after MelScale

3 · who owns media I/O now

Both domain packages were narrowed to their strengths. Decoding was consolidated into one place.

STAYS torchvision transforms.v2 · models datasets · ops · image I/O torchaudio transforms · functional models · pipelines · datasets MOVED OUT torchcodec VideoDecoder AudioDecoder AudioEncoder pip install torchcodec torchvision 0.26 removed read_video · torchaudio 2.9 removed torchaudio.io

4 · the audio feature chain

Each named transform is just a prefix of this pipeline. Knowing where yours stops tells you its output shape.

waveform (ch, time) Spectrogram (ch, n_fft//2+1, t) MelSpectrogram (ch, n_mels, t) MFCC (ch, n_mfcc, t) STFT mel filterbank log + DCT MelSpectrogram = Spectrogram ⊕ MelScale MFCC re-runs the whole chain — melkwargs= tunes the middle

Worth memorizing

zero_grad firstgradients accumulate — skipping it silently sums batches
train() ≠ grad onit only flips Dropout and BatchNorm; use no_grad to stop tracking
no_grad vs inference_modeboth stop recording; inference_mode is stricter and faster
view vs reshapeview needs contiguous memory, reshape copies when it must
cat vs stackcat keeps the rank, stack adds a dimension
losses take logitsCrossEntropyLoss and BCEWithLogitsLoss apply the softmax/sigmoid themselves
.item() syncsit stalls the GPU — keep it out of the inner loop
backward frees the grapha second call needs retain_graph=True, which usually means a bug
weights_only=Truethe torch.load default since 2.6 — unpickling arbitrary files is code execution
weights=, not pretrained=and weights.transforms() gives the matching preprocessing
ToImage + ToDtypethe v2 replacement for ToTensor; scale=True is what divides by 255
media I/O lefttorchvision video (0.26) and torchaudio I/O (2.9) both live in torchcodec now
resample to bundle.sample_ratea pretrained speech model at the wrong rate fails quietly, not loudly
broadcasting aligns right(N,1) against (N,) becomes (N,N) — the loss silently averages N² pairs and nothing raises
running += loss leaksaccumulating the tensor keeps its graph alive; add .item()
_orig_mod. prefixtorch.compile wraps the model, so compiled checkpoints will not load into an uncompiled one
build tensors on the devicedevice= at creation, rather than allocating on CPU and copying
detection is list in, list outand in train() those models return a dict of losses, not predictions
CTC needs collapsingunique_consecutive, then drop the blank — argmax alone is not a transcript
pin the tripletorch 2.13 pairs with torchvision 0.28, but torchaudio is 2.10 — audio stopped tracking torch's numbering when it froze