InfraOneInfraOneSchool of AI

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")

Set seed

torch.manual_seed(42)

import torch

device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
torch.manual_seed(42)
print(device)

Use .to(device) for both model and tensors. A very common error is putting the model on GPU but leaving the input batch on CPU.

Tensors

Tensors are PyTorch’s core data structure. Think of them as arrays that can run on CPU or GPU and can track gradients when needed.

tensor device flow

Need

Code

Scalar

torch.tensor(3.0)

Vector

torch.tensor([1, 2, 3])

Matrix

torch.tensor([[1, 2], [3, 4]])

Zeros

torch.zeros(2, 3)

Ones

torch.ones(2, 3)

Random normal

torch.randn(2, 3)

Range

torch.arange(0, 10, 2)

x = torch.randn(4, 3)
print(x.shape)     # torch.Size([4, 3])
print(x.dtype)     # usually torch.float32
print(x.device)    # cpu or cuda

One-line rule: use float tensors for model inputs and targets in regression, long tensors for class labels in classification.

features = torch.tensor([[1, 2], [3, 4]], dtype=torch.float32)
labels = torch.tensor([0, 1], dtype=torch.long)

Tensor shape operations

Most PyTorch bugs are shape bugs. Print shapes often, especially before a loss function.

Operation

Code

Meaning

Reshape

x.view(2, 6)

Reuse memory if possible

Safer reshape

x.reshape(2, 6)

Works more often

Add dimension

x.unsqueeze(0)

Add batch-like axis

Remove dimension

x.squeeze()

Drop size-1 axes

Transpose 2D

x.T

Swap rows and columns

Concatenate

torch.cat([a, b], dim=0)

Join along existing axis

Stack

torch.stack([a, b], dim=0)

Create new axis

x = torch.randn(32, 10)       # 32 rows, 10 features
x = x.unsqueeze(1)            # 32, 1, 10
x = x.squeeze(1)              # 32, 10

One-line rule: cat grows an existing dimension, while stack creates a new dimension.

Indexing, slicing and masks

PyTorch indexing is close to NumPy, but the result is still a tensor.

Need

Code

First row

x[0]

First column

x[:, 0]

Rows 2 to 4

x[2:5]

Boolean mask

x[x > 0]

Top values

torch.topk(x, k=3)

Class prediction

logits.argmax(dim=1)

logits = torch.tensor([[1.2, 0.3, 2.1], [0.1, 3.4, 1.5]])
preds = logits.argmax(dim=1)
print(preds)  # tensor([2, 1])

One-line rule: model classification outputs are usually logits, not probabilities; argmax works on logits.

Autograd

Autograd records tensor operations and computes gradients during backpropagation. Only tensors with requires_grad=True track gradients.

Need

Code

Track gradients

x.requires_grad_(True)

Backpropagate

loss.backward()

Read gradients

x.grad

Stop tracking

with torch.no_grad():

Detach tensor

x.detach()

Clear gradients

optimizer.zero_grad()

x = torch.tensor(2.0, requires_grad=True)
y = x ** 2 + 3 * x

y.backward()
print(x.grad)  # derivative at x=2 is 7

One-line rule: call optimizer.zero_grad() before loss.backward() in each training step, or gradients accumulate.

Datasets and DataLoaders

Use Dataset to define how one sample is read. Use DataLoader to batch, shuffle and parallelize sample loading.

Component

Purpose

Dataset

Returns one item by index

DataLoader

Creates batches from a dataset

batch_size

Samples per batch

shuffle=True

Randomizes training order

num_workers

Uses worker processes for loading

from torch.utils.data import TensorDataset, DataLoader

X = torch.randn(100, 5)
y = torch.randint(0, 2, (100,))

dataset = TensorDataset(X, y)
loader = DataLoader(dataset, batch_size=16, shuffle=True)

for xb, yb in loader:
    print(xb.shape, yb.shape)
    break

One-line rule: shuffle training data, but usually do not shuffle validation or test data.

Models with torch.nn

Most PyTorch models subclass nn.Module. Define layers in __init__, then define the data flow in forward.

Layer

Common use

nn.Linear

Dense layer

nn.ReLU

Non-linearity

nn.Dropout

Regularization

nn.BatchNorm1d

Normalize activations

nn.Conv2d

Image features

nn.Embedding

Token or ID vectors

import torch.nn as nn

class MLP(nn.Module):
    def __init__(self, input_dim, hidden_dim, output_dim):
        super().__init__()
        self.net = nn.Sequential(
            nn.Linear(input_dim, hidden_dim),
            nn.ReLU(),
            nn.Linear(hidden_dim, output_dim)
        )

    def forward(self, x):
        return self.net(x)

model = MLP(5, 16, 2).to(device)

One-line rule: do not call forward() directly; call model(x) so PyTorch hooks work correctly.

Loss functions and optimizers

Choose the loss function based on the prediction target. The optimizer updates model weights using gradients.

Problem

Output shape

Target

Loss

Binary classification

[N, 1]

float 0/1

BCEWithLogitsLoss

Multi-class classification

[N, C]

long class id

CrossEntropyLoss

Regression

[N, 1]

float value

MSELoss

criterion = nn.CrossEntropyLoss()
optimizer = torch.optim.Adam(model.parameters(), lr=1e-3)

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.

training loop workflow
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.

Need

Code

Save weights

torch.save(model.state_dict(), "model.pt")

Load weights

model.load_state_dict(torch.load("model.pt"))

Save checkpoint

Save model, optimizer and epoch

CPU load

map_location="cpu"

torch.save({
    "model": model.state_dict(),
    "optimizer": optimizer.state_dict(),
    "epoch": 5
}, "checkpoint.pt")

checkpoint = torch.load("checkpoint.pt", map_location=device)
model.load_state_dict(checkpoint["model"])
optimizer.load_state_dict(checkpoint["optimizer"])

One-line rule: recreate the same model architecture before loading its weights.

Debugging checklist

Use this PyTorch cheatsheet section when the code runs but the result looks wrong.

Symptom

Check first

Device error

Model and tensors on same device

Loss not decreasing

Learning rate, labels, loss choice

Shape error

Print x.shape before each layer

NaN loss

Lower learning rate, inspect inputs

Bad accuracy

Confirm label encoding

Slow training

Batch size, DataLoader, GPU use

print(next(model.parameters()).device)
print(xb.device, yb.device)
print(logits.shape, yb.shape)

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.

Share this article
XLinkedInWhatsApp

Related reads