Skip to main content
Quick Reference

NN Cheatsheet

Neural networks on one page — neurons, shapes, backprop, losses, and the traps around logits, gradients, and eval mode.

10 sections 10 tables 14 code snippets

A small network

Hidden ReLU, linear head

nn.Linear(4, 8)
nn.ReLU()
nn.Linear(8, 3)

Loss on logits

nn.CrossEntropyLoss()

What a network is

PieceMeaning
NeuronA weighted sum plus a bias, then an activation
Linear mapnn.Linear(in, out) computes y = x @ W.T + b
NonlinearityReLU sits between the two linear maps. Without it they collapse into one
LogitsThe last linear map has no activation. Those raw scores are the logits
ParametersLinear(4, 8) stores 4 * 8 weights plus 8 biases. ReLU stores none
Head3 outputs means 3 class scores. A binary head is one logit, or two class logits

This page is a neural network in PyTorch. Conv nets, sequence models, and hosted GenAI APIs are left out.

One unit

The weighted sum

# z = w1*x1 + w2*x2 + b

What each part does

PartRole
WeightsEach input has a weight. A larger weight moves the sum more
BiasShifts the sum. Default bias=True. bias=False forces the boundary through the origin
ActivationReLU, sigmoid, or tanh applied to z. A step function has gradient 0 almost everywhere
One layerOne linear map, even with a monotonic activation, cuts the inputs with one hyperplane
XORXOR is not a hyperplane. A hidden layer plus a nonlinearity can represent it
WidthA wide hidden layer with ReLU can approximate a continuous function on a closed bounded set. Enough units does not make training easy

Shapes

Weight layout

# W shape is (out, in), not (in, out)

Which axis is which

TensorShape
BatchUsual input is (N, in_features). The last axis is the feature size
Single vectorLinear also accepts one vector of length in_features, with no batch axis
Weight(out_features, in_features). The forward pass multiplies by the transpose
Bias(out_features,), added on every row of the batch
OutputLeading dims stay. The last dim becomes out_features
MismatchA batch whose last dim is not in_features raises a size error

The forward pass

Call the module

logits = model(x)

What runs

CallEffect
model(x)Runs hooks, then forward. Prefer this over calling forward yourself
SequentialFeeds each module the previous output. A shape clash fails at that boundary
ReLUmax(0, z) on every element. No weights
Last layerLeave it linear for a class head or a regression head
Same objectmodel holds the parameters. A new nn.Linear is a different set of weights
Device and dtypeThe batch and the weights must share a device and a dtype

Backprop

Fill the gradients

loss.backward()

The chain rule

StepWhat happens
GraphThe forward pass records how each tensor was made
Chain ruleEach layer multiplies the upstream gradient by its local gradient
Leaf .gradGradients land on parameters. Those leaves start with requires_grad=True
Accumulate.backward() adds into .grad. It keeps a value that is already there
Freed graphAfter a backward the graph is dropped. A second backward needs retain_graph=True
Scalar.backward() on a vector of losses asks for an explicit gradient. Reduce with mean or sum

Losses

Logits and class indices

nn.CrossEntropyLoss()(logits, y)

Index dtype

# y is a long tensor of class indices

Match the head

PairTarget
CrossEntropyLossRaw logits and class indices. It applies log-softmax inside
NLLLossLog-probabilities, usually from LogSoftmax, plus class indices
Softmax then cross-entropyApplies the squash twice and trains on the wrong numbers
BCEWithLogitsLossOne logit and a float target of 0 or 1. Skip a sigmoid in front
MSELossA linear head and a numeric target of the same shape
ReductionDefault mean averages the batch. sum grows when the batch grows

One update

Clear, backward, step

opt.zero_grad()
loss.backward()
opt.step()

Why this order

LineWhy
zero_gradClears the gradient left by the previous step
backwardFills .grad from this batch
stepMoves each parameter using that gradient and the learning rate
OrderStep before backward uses a missing or stale gradient
OptimizerBuild it after the model exists, from model.parameters()
Batch sizeA mean loss stays on a similar scale when the batch changes. A sum does not

Parameters

Freeze every parameter

for p in model.parameters():
    p.requires_grad = False

What is trainable

KnobEffect
parameters()Every weight and bias. ReLU contributes nothing
requires_gradTrue on parameters by default. False leaves that tensor out of the graph
FreezeSet requires_grad off before you create the optimizer
New layer laterAn optimizer keeps the list it was given. A layer added afterward is absent from that list
detachCuts a tensor off the graph so earlier layers get no gradient from it
.item()A Python number. It drops the graph and copies a GPU value to the CPU

Initialization

Default Linear scale

# uniform from -1/sqrt(in) to 1/sqrt(in)

Starting values

SchemeWhen
Default LinearUniform on that range. The source calls kaiming uniform with a = sqrt(5), which simplifies to this
All zerosEvery unit in the layer computes the same value and receives the same update
He for ReLUkaiming_uniform_ with nonlinearity="relu" uses a larger scale than the default
XavierSuits tanh and sigmoid. It uses both fan-in and fan-out
BiasDefault bias is uniform on the same 1/sqrt(in) range
Broken scaleHuge weights make the loss NaN. Tiny weights barely move

Interview traps

Score without a graph

with torch.no_grad():
    pred = model(x)

The class is the argmax

# argmax(logits) picks the same class as argmax(softmax)

Eval is a mode switch

# model.eval() does not stop autograd

Traps worth memorising

TrapWhat happensPrefer
Softmax before CrossEntropyLossThe loss applies log-softmax againPass logits
model.eval() aloneDropout and batch norm switch mode. Gradients still flowAlso use torch.no_grad() while scoring
Forgot zero_gradThis step adds onto the previous gradientClear .grad before every backward
One-hot long tensor as yClass indices have shape (N) and dtype longPass indices, not a one-hot long tensor
Softmax over dim 0Mixes the examples in the batchSoftmax on the class axis of a Linear head
Label -1Out of bounds. The ignored index defaults to -100Use ignore_index for the pad value you actually store

How to use this page: call the module, train on logits with class indices, and clear the gradient before each backward. Score inside torch.no_grad.