Use this pytorch cheat sheet as a practical reference when you are building your first neural networks or revising core PyTorch syntax. It focuses on copy-paste patterns that work in real notebooks and scripts, with just enough explanation to avoid common beginner mistakes.
PyTorch cheat sheet essentials
Install PyTorch from the official selector at pytorch.org because the right command depends on your OS, Python version and CUDA setup.
Task
Code
Import PyTorch
import torch
Check version
torch.__version__
Check GPU
torch.cuda.is_available()
Pick device
torch.device("cuda" if torch.cuda.is_available() else "cpu")
One-line rule: CrossEntropyLoss expects raw logits and integer class labels, not softmax probabilities and not one-hot labels.
Training loop
A reliable training loop has the same order every time: set train mode, move batch to device, forward pass, compute loss, clear gradients, backpropagate and step.
model.train()
for epoch in range(5):
total_loss = 0.0
for xb, yb in loader:
xb = xb.to(device)
yb = yb.to(device)
logits = model(xb)
loss = criterion(logits, yb)
optimizer.zero_grad()
loss.backward()
optimizer.step()
total_loss += loss.item()
print(f"epoch={epoch+1}, loss={total_loss / len(loader):.4f}")
One-line rule: use loss.item() for logging a Python number; keep loss as a tensor for backward().
Evaluation and inference
Evaluation should turn off training-specific behavior and gradient tracking. This saves memory and gives correct behavior for layers such as dropout and batch normalization.
Need
Code
Eval mode
model.eval()
Disable gradients
with torch.no_grad():
Probabilities
torch.softmax(logits, dim=1)
Predicted class
logits.argmax(dim=1)
Accuracy
(preds == y).float().mean()
model.eval()
correct = 0
total = 0
with torch.no_grad():
for xb, yb in loader:
xb = xb.to(device)
yb = yb.to(device)
logits = model(xb)
preds = logits.argmax(dim=1)
correct += (preds == yb).sum().item()
total += yb.size(0)
print(correct / total)
One-line rule: use model.train() before training again after validation.
Saving and loading
Save state_dict() for most projects. It is lighter, safer and more flexible than saving the full model object.
One-line rule: when debugging, overfit a tiny batch first. If the model cannot memorize 8 to 32 samples, something is wrong in the data, labels, loss or training loop.
Next step
Keep this reference open while building a small project from scratch: load a tabular dataset, define an MLP, train it, evaluate it and save the best checkpoint. For deeper API details, use the official PyTorch documentation alongside this cheat sheet.
Frequently asked questions
Is PyTorch good for beginners?
Yes. PyTorch is beginner-friendly because its code style feels close to regular Python, and errors are usually easier to trace than in heavily abstracted frameworks. Beginners should still learn tensor shapes, gradients and training loops carefully.
What should I learn before PyTorch?
You should be comfortable with Python functions, classes, lists and basic NumPy-style array operations. For deep learning, basic linear algebra and the idea of gradients will make PyTorch much easier.
Do I need a GPU to learn PyTorch?
No. You can learn tensors, autograd, small neural networks and training loops on a CPU. A GPU becomes useful when you train larger models, process images or run experiments repeatedly.
What is the difference between torch and torch.nn?
`torch` contains the core tensor operations, math functions and utilities. `torch.nn` provides neural-network building blocks such as layers, activations, losses and the `Module` base class.
Why does CrossEntropyLoss not need softmax?
PyTorch's `CrossEntropyLoss` combines log-softmax and negative log likelihood internally. Passing softmax probabilities into it can make training less stable and less correct.