BitSize Python · Deep Learning
Build neural networks, one tensor at a time.
Every PyTorch program runs one loop. Each lesson adds one part.
Part 1 · Tensors · about 12 min · free
Your training loop
Every PyTorch program runs these six steps, batch after batch. Each lesson adds a part to your kit; pass it and the part lights up.
- Datatensors, batches 0 / 64
- Modelforward 0 / 155
- Losshow wrong 0 / 20
- Backwardgradients 0 / 20
- Stepupdate weights 0 / 42
- Evaluatepredict, score 0 / 62
Data0 / 64
Model0 / 155
Loss0 / 20
Backward0 / 20
Step0 / 42
Evaluate0 / 62
Tensors
A photo is a tensor: making, slicing, reshaping and reducing tensors, broadcasting, the maths a layer does, and the bridge to NumPy.
- 01 A photo is a tensortorch.tensor · .shape · .dtype · .item() Up next
- 02 Making tensorstorch.zeros · torch.ones · torch.full · torch.arange · torch.linspace · torch.rand · torch.randn · torch.zeros_like · torch.manual_seed Free account
- 03 Slicingimg[r] · img[:, c] · img[a:b, c:d] · img[::2] · img[-1] · img[img > 0.5] · .clone() Free account
- 04 Maths on tensors and broadcasting+ - * / ** · > == · broadcasting 🔒 Subscribe
- 05 Reshape without fear.reshape · .view · .flatten · .unsqueeze · .squeeze · .permute · .T · .contiguous() 🔒 Subscribe
- 06 Reductions and dim.sum(dim) · .mean(dim) · .max(dim) · .argmax(dim) · keepdim=True 🔒 Subscribe
- 07 Linear algebra you'll actually usetorch.dot · @ (torch.matmul) · .norm() 🔒 Subscribe
- 08 Tensors and the rest of Pythontorch.from_numpy · .numpy() · .tolist() · add_ · .float() / .long() 🔒 Subscribe
Autograd
Slopes, requires_grad and backward, the computational graph, gradients that add up, and when to stop them.
- 09 Slopesdef f(x) on tensors · (f(x + h) - f(x)) / h · many h at once 🔒 Subscribe
- 10 requires_grad and .backward()requires_grad=True · .backward() · .grad 🔒 Subscribe
- 11 The graph.grad_fn · .grad_fn.name() · .is_leaf 🔒 Subscribe
- 12 Gradients add up.grad.zero_() · .grad = None · .backward(gradient=…) 🔒 Subscribe
- 13 Stop the gradient.detach() · torch.no_grad() · torch.inference_mode() · .requires_grad_(False) 🔒 Subscribe
- 14 Gradients through Pythonif · for · while on tensors · torch.where 🔒 Subscribe
The training loop
Fit a line by hand, then the five-line loop every model uses: forward, loss, zero_grad, backward, step. Minibatches, validation, weight decay.
- 15 Fit a line by handw * x + b · (pred - y) ** 2 · .mean() · mean squared error 🔒 Subscribe
- 16 Gradient descent by handw -= lr * w.grad · torch.no_grad() · w.grad.zero_() 🔒 Subscribe
- 17 The five-line looptorch.optim.SGD · opt.zero_grad() · opt.step() 🔒 Subscribe
- 18 nn.Linear and nn.MSELossnn.Linear · nn.MSELoss · model.parameters() · model.weight · model.bias 🔒 Subscribe
- 19 MinibatchesTensorDataset · DataLoader(batch_size, shuffle) · len(loader) · drop_last 🔒 Subscribe
- 20 Train and validaterandom_split · torch.Generator().manual_seed · validation loss under torch.no_grad() 🔒 Subscribe
- 21 Too simple, too wigglytorch.cat([x ** k …], dim=1) · nn.Linear(degree, 1) · underfitting · overfitting 🔒 Subscribe
- 22 Weight decayL2 penalty · torch.optim.SGD(..., weight_decay=…) 🔒 Subscribe
- 23 Tidy training codedef train_one_epoch · def evaluate · def fit · model.train() · model.eval() · loader.dataset 🔒 Subscribe
Classification
Softmax and cross-entropy, an image dataset, accuracy, and what happens when the world changes.
- 24 Scores to probabilitiestorch.softmax(x, dim) · F.softmax · .exp() · temperature 🔒 Subscribe
- 25 Cross-entropynn.CrossEntropyLoss · torch.log · reduction='none' 🔒 Subscribe
- 26 An image datasetload('glyphs', messy=True) · X[:4000] / X[4000:5000] / X[5000:] · (y[:, None] == torch.arange(10)).sum(0) · next(iter(loader)) 🔒 Subscribe
- 27 Softmax regression from scratchx.reshape(-1, 256) @ W + b · torch.exp · torch.log · p[torch.arange(n), y] 🔒 Subscribe
- 28 Softmax regression, concisenn.Sequential · nn.Flatten · nn.CrossEntropyLoss · torch.logsumexp 🔒 Subscribe
- 29 Is it any good?argmax(dim=1) · (pred == y).float().mean() · model.eval() · torch.no_grad() · torch.bincount 🔒 Subscribe
- 30 When the world changestorch.roll · accuracy per kind · covariate, label and concept shift 🔒 Subscribe
Multilayer perceptrons
Hidden layers and activations, backprop, vanishing gradients and initialisation, early stopping, dropout.
- 31 Why a hidden layernn.Sequential · nn.ReLU · hidden units · decision boundary 🔒 Subscribe
- 32 Activationsnn.ReLU · nn.Sigmoid · nn.Tanh · nn.GELU 🔒 Subscribe
- 33 Your first MLPnn.Sequential · nn.ReLU · model[i] · p.numel() 🔒 Subscribe
- 34 Forward and backward.retain_grad() · loss.backward() through layers · torch.no_grad() 🔒 Subscribe
- 35 Vanishing and explodingp.grad.norm() per layer · nn.init.xavier_uniform_ · nn.init.kaiming_uniform_ 🔒 Subscribe
- 36 Early stoppingpatience · copy.deepcopy(model.state_dict()) · model.load_state_dict() 🔒 Subscribe
- 37 Dropoutnn.Dropout(p) · model.train() · model.eval() · the 1/(1−p) scaling 🔒 Subscribe
- 38 Price the homestorch.log · torch.randperm · torch.cat · 5-fold cross-validation · .sqrt() (RMSE) 🔒 Subscribe
Building blocks
nn.Module, containers, parameters, initialisation, custom layers, saving and loading, devices.
- 39 nn.Module: a network as a classnn.Module · super().__init__() · forward · model(x) 🔒 Subscribe
- 40 Containers and control flownn.ModuleList · nn.ModuleDict · nn.Sequential(*layers) · for / if in forward 🔒 Subscribe
- 41 Parametersmodel.named_parameters() · module.requires_grad_(False) · p.requires_grad · tied weights 🔒 Subscribe
- 42 Initialisationnn.init.normal_ · nn.init.zeros_ · nn.init.kaiming_uniform_ · nn.init.xavier_uniform_ · model.apply(fn) · nn.LazyLinear 🔒 Subscribe
- 43 Custom layersnn.Parameter · register_buffer · named_buffers() 🔒 Subscribe
- 44 Save and loadtorch.save · torch.load · load_state_dict · opt.state_dict() · checkpoint dict 🔒 Subscribe
- 45 Devicestorch.device · torch.cuda.is_available() · .to(device) · x.device 🔒 Subscribe
Convolutions
Why convolution, kernels, padding and stride, channels, pooling, LeNet.
- 46 Why convolutionnn.Conv2d · kernel_size · feature map · weight sharing 🔒 Subscribe
- 47 Slide a kernelF.conv2d · (N, C, H, W) · edge kernels 🔒 Subscribe
- 48 Learn a kernelnn.Conv2d(1, 1, 3, bias=False) · conv.weight · the loop on a kernel 🔒 Subscribe
- 49 Padding and stridenn.Conv2d(padding=, stride=) · padding='same' · ⌊(n + 2p − k) / s⌋ + 1 🔒 Subscribe
- 50 Channelsnn.Conv2d(in_channels, out_channels, k) · conv.weight (out, in, k, k) · kernel_size=1 🔒 Subscribe
- 51 Poolingnn.MaxPool2d · nn.AvgPool2d 🔒 Subscribe
- 52 LeNetnn.Sequential of Conv2d · MaxPool2d · Flatten · model[:k](torch.zeros(1, 1, 16, 16)) 🔒 Subscribe
- 53 Train LeNettrain a convnet · net[:2](x) · net[0].weight 🔒 Subscribe
Make it work
Overfit one batch, read the loss curve, the classic PyTorch bugs, reproducible runs.
- 54 Overfit one batch firstone fixed batch · the loss must reach ~0 · a stalled loss = a bug 🔒 Subscribe
- 55 Read the loss curvesteps.append(loss.item()) · math.isnan · train vs validation loss 🔒 Subscribe
- 56 The classic bugsopt.zero_grad() · raw logits · model.eval() · .long() · .reshape · loss.item() 🔒 Subscribe
- 57 Reproducible runstorch.manual_seed · torch.Generator · random.seed · np.random.seed · torch.use_deterministic_algorithms 🔒 Subscribe
Modern CNNs
Blocks, 1×1 convolutions, branches, batch normalisation, residual and dense connections.
- 58 Deeper with blocksvgg_block(n_convs, in_c, out_c) · nn.Conv2d(in_c, out_c, 3, padding=1) · nn.Sequential(*layers) 🔒 Subscribe
- 59 1 × 1 and global average poolingNiN block (3 × 3 conv → 1 × 1 → 1 × 1) · nn.AdaptiveAvgPool2d(1) · a head with no Linear 🔒 Subscribe
- 60 Many branchesan Inception block · torch.cat(outs, dim=1) · a 1 × 1 squeeze before a big kernel 🔒 Subscribe
- 61 Batch normalisationnn.BatchNorm2d · running_mean · running_var · train() / eval() · bias=False 🔒 Subscribe
- 62 Residual connectionsF.relu(self.block(x) + x) · a 1 × 1 projection shortcut · nn.Identity · nn.Conv2d(..., groups=…) 🔒 Subscribe
- 63 Dense connectionstorch.cat([x, layer(x)], dim=1) · growth rate · transition: 1 × 1 nn.Conv2d + nn.AvgPool2d(2) 🔒 Subscribe
- 64 Designing networkslayer.weight.numel() · isinstance(layer, nn.Conv2d) · a multiply-add counter · groups= 🔒 Subscribe
Optimisation
The loss landscape, SGD and minibatch noise, momentum, adaptive rates, Adam, schedules.
- 65 The landscapedv.surface · dv.path · w.grad.norm() · SGD on a 2-element weight 🔒 Subscribe
- 66 Gradient descent, revisitedtorch.optim.SGD on a 2-weight tensor · lr < 2 ÷ curvature · torch.autograd.grad(..., create_graph=True) 🔒 Subscribe
- 67 SGD and minibatch noiseDataLoader(batch_size) · len(loader) · a batch gradient as a noisy estimate · counting work per example 🔒 Subscribe
- 68 MomentumSGD(..., momentum=0.9) · opt.state[p]['momentum_buffer'] · nesterov=True 🔒 Subscribe
- 69 Adaptive ratestorch.optim.Adagrad · torch.optim.RMSprop · optimizer.state[p] 🔒 Subscribe
- 70 Adam and AdamWtorch.optim.Adam · opt.state[w] · torch.optim.AdamW 🔒 Subscribe
- 71 Scheduleslr_scheduler.StepLR · CosineAnnealingLR · LinearLR + SequentialLR · OneCycleLR · scheduler.step() 🔒 Subscribe
- 72 Choosing an optimisertorch.optim.AdamW · opt.param_groups · nn.utils.clip_grad_norm_ 🔒 Subscribe
Sequences and RNNs
Sequences, text to numbers, language models, hidden states, LSTM, GRU, deep and bidirectional RNNs.
- 73 Sequencesx.unfold(0, tau, 1) · a split by time · k-step forecasts fed back with torch.cat 🔒 Subscribe
- 74 Text to numberssorted(set(text)) · Counter.most_common · word2id.get(w, 0) · torch.tensor(ids) · ids.tolist() 🔒 Subscribe
- 75 Language modelstorch.bincount · torch.multinomial · perplexity = exp(mean −log p) · random / sequential minibatches 🔒 Subscribe
- 76 A hidden stateh = torch.tanh(x[t] @ W_xh + h @ W_hh + b) · nn.RNNCell · weight_ih · weight_hh 🔒 Subscribe
- 77 A character RNNnn.Embedding · nn.RNN(batch_first=True) · torch.multinomial(softmax(logits / temperature)) 🔒 Subscribe
- 78 nn.RNNnn.RNN(batch_first=True) · output, h_n = rnn(x, h0) · h.detach() 🔒 Subscribe
- 79 Backprop through timeh.retain_grad() · h.detach() every k steps (truncated BPTT) · nn.utils.clip_grad_norm_ 🔒 Subscribe
- 80 LSTMnn.LSTMCell · nn.LSTM → (output, (h_n, c_n)) · the forget-gate bias 🔒 Subscribe
- 81 GRUnn.GRUCell · nn.GRU · reset gate r · update gate z 🔒 Subscribe
- 82 Deeper and bidirectionalnn.RNN(num_layers=…) · bidirectional=True · output vs h_n · h_n.view(layers, directions, batch, hidden) 🔒 Subscribe
Encoder–decoder
Translation data, encoder and decoder, teacher forcing, BLEU, beam search.
- 83 Translation datavocabulary with special tokens · stoi.get(w, UNK) · <eos> + padding to T · (X != PAD).sum(dim=1) · a boolean mask 🔒 Subscribe
- 84 Encoder and decoderEncoder(nn.Module) · Decoder(nn.Module) · self.gru(x, h) · the context vector 🔒 Subscribe
- 85 Training seq2seqteacher forcing · CrossEntropyLoss(ignore_index=PAD) · logits.reshape(-1, V) 🔒 Subscribe
- 86 Predict and scoregreedy decoding (argmax, feed back, stop at <eos>) · clipped n-gram precision · brevity penalty · BLEU 🔒 Subscribe
- 87 Beam searchbeam search · scores.unsqueeze(1) + log_probs · flatten().topk(k) · indices // V, % V · length normalisation 🔒 Subscribe
Attention and transformers
Queries, keys and values, multi-head attention, positions, the transformer block, a tiny GPT, vision transformers.
- 88 Queries, keys, valuesscores = K @ q · torch.softmax(scores, dim=0) · weights @ V · Q @ K.T for many queries · hard lookup V[scores.argmax()] 🔒 Subscribe
- 89 Attention by similaritydistances by broadcasting · torch.softmax(-d ** 2 / (2 * width ** 2), dim=1) @ y · masked_fill(mask, -inf) to hide a point from itself 🔒 Subscribe
- 90 Scoring functionsq @ k.transpose(-2, -1) · ÷ √d · additive score (Linear + tanh) · masked_fill(~mask, -inf) · F.scaled_dot_product_attention 🔒 Subscribe
- 91 Attention in seq2seqencoder states as keys · additive attention with a padding mask · torch.bmm context · nn.GRUCell decoding step by step · alignment heatmap 🔒 Subscribe
- 92 Multi-head attention.view(B, T, h, C // h).transpose(1, 2) · nn.MultiheadAttention(embed_dim, num_heads, batch_first=True) · in_proj_weight · out_proj · average_attn_weights 🔒 Subscribe
- 93 Self-attention and positionself-attention (q, k, v from the same X) · X[perm] permutation test · sinusoidal positions (sin / cos, P[:, 0::2]) · X + P · cost per layer and path length 🔒 Subscribe
- 94 The transformer blocknn.LayerNorm · residual + norm (post-norm / pre-norm) · nn.TransformerEncoderLayer(batch_first=True, norm_first=…) 🔒 Subscribe
- 95 Encoder and decoder, transformer editionnn.Transformer · nn.Transformer.generate_square_subsequent_mask · tgt_mask · cross-attention to the encoder memory · greedy decoding with a growing prefix 🔒 Subscribe
- 96 A tiny GPTTinyGPT (token + position embeddings → causal blocks → LayerNorm → head) · load_state_dict(load('tinygpt').state) · torch.topk for top-k sampling 🔒 Subscribe
- 97 Vision transformerF.unfold · Conv2d(kernel_size=4, stride=4) as patch embedding · class token · learned positions 🔒 Subscribe
- 98 Pretraining at scalemasked-token targets (-100 = no loss) · causal vs full attention masks · held-out loss of load('tinygpt') 🔒 Subscribe
Vision in practice
Augmentation, fine-tuning, boxes and IoU, anchors, a tiny detector, segmentation.
- 99 Augmentationv2.RandomCrop · v2.Compose · v2.RandomHorizontalFlip · v2.RandomErasing · v2.ColorJitter 🔒 Subscribe
- 100 Fine-tuningload_state_dict(load('glyphnet').state) · model.features.requires_grad_(False) · a new head · torch.optim.Adam([{'params': …, 'lr': …}, …]) parameter groups 🔒 Subscribe
- 101 Boxes and IoUtorchvision.ops.box_convert · IoU by hand · torchvision.ops.box_iou 🔒 Subscribe
- 102 Anchors and NMSmake_anchors · labelling anchors by IoU · encode / decode offsets · torchvision.ops.nms · torchvision.ops.batched_nms 🔒 Subscribe
- 103 A tiny detectorSceneNet: body + head8/head4 → scores (B, 160, 5), offsets (B, 160, 4) · hard-negative cross-entropy + F.smooth_l1_loss · detect 🔒 Subscribe
- 104 The R-CNN familytorchvision.ops.roi_pool · torchvision.ops.roi_align (spatial_scale, sampling_ratio, aligned) · a Linear head on RoI features 🔒 Subscribe
- 105 Transposed convolutionnn.ConvTranspose2d · F.conv_transpose2d · (n − 1)·s − 2p + k · nn.Upsample + conv 🔒 Subscribe
- 106 Segmentationencoder → decoder (a fully convolutional net) · F.cross_entropy on (B, C, H, W) scores and (B, H, W) masks · argmax(dim=1) · IoU per class 🔒 Subscribe
Language in practice
Word embeddings, word2vec, subwords, sentiment, BERT and fine-tuning.
- 107 Word embeddingsF.one_hot · torch.cdist · nn.Embedding · emb.weight · skip-gram and CBOW pairs 🔒 Subscribe
- 108 Train word2vecSkipGram (two nn.Embedding tables, a dot product per pair) · negative sampling with torch.multinomial(counts ** 0.75) · F.binary_cross_entropy_with_logits · subsampling frequent words 🔒 Subscribe
- 109 SubwordsCounter of pairs · most_common(1) · the merge list · nn.EmbeddingBag(mode='sum') 🔒 Subscribe
- 110 Similarity and analogyF.cosine_similarity · F.normalize(V, dim=1) then U @ U[i] · analogies: b − a + c, nearest word 🔒 Subscribe
- 111 Sentimentnn.Conv1d over time · .max(dim=2).values · out[torch.arange(B), last] 🔒 Subscribe
- 112 BERT[CLS] a [SEP] b [SEP] · token + segment + position embeddings · padding mask (masked_fill on [PAD] keys) · masked words: 15 %, 80/10/10, target −100 elsewhere · next-sentence prediction on [CLS] 🔒 Subscribe
- 113 Fine-tune an encoderload_state_dict(w.state, strict=False) · mean pooling with a padding mask · AdamW with a small lr · sequence / token / pair heads 🔒 Subscribe
Beyond
GANs, hyperparameter search, reinforcement learning, recommenders, and making it fast at home.
- 114 GANsgenerator + discriminator (two nn.Sequential, two optimisers) · fake.detach() in the discriminator's loss · F.binary_cross_entropy_with_logits for both losses 🔒 Subscribe
- 115 DCGANDCGAN Generator (Linear → view → ConvTranspose2d + BatchNorm → Tanh) · load_state_dict on the gen.* / disc.* halves · G.eval() before sampling · latent walk (1 − t)·z0 + t·z1 🔒 Subscribe
- 116 Hyperparameter searchgrid search · random search (10 ** (torch.rand(n) * 4 - 3)) · successive halving · choose on validation, test once 🔒 Subscribe
- 117 Decisions, rewards, valuesstates · actions · rewards · discount γ · value iteration: Q = R[nxt] + γ · V[nxt] · Q.max(dim=0) · Q.argmax(dim=0) 🔒 Subscribe
- 118 Q-learningQ = torch.zeros(states, actions) · Q[s, a] += α (r + γ · Q[s2].max() − Q[s, a]) · ε-greedy with torch.rand / torch.randint · Q[s].argmax() as the policy 🔒 Subscribe
- 119 Recommendersnn.Embedding factors · bias embeddings · RMSE vs baselines · topk recommendations 🔒 Subscribe
- 120 Making it fast at hometorch.autocast · torch.amp.GradScaler · torch.compile · DataLoader(num_workers, pin_memory) · torch.cuda.synchronize() · DistributedDataParallel 🔒 Subscribe
Case files
Open problems end to end: shapes, waves, tales, scenes, and a failing run to rescue.
- 121 Read the shapessplit · baseline · CNN · loss curves · confusion matrix · one test score 🔒 Subscribe
- 122 Forecast the wavesunfold windows (24 in, 24 out) · a split by time · nn.LSTM vs nn.Conv1d · error by horizon against a naive rule 🔒 Subscribe
- 123 Write like the talesno new API: a 90 / 10 split · fixed held-out windows · count baselines · TinyGPT + AdamW · held-out loss · seeded sampling 🔒 Subscribe
- 124 Find the objectsscenenet detect (boxes + classes) · a decoder on the frozen stem (a class per pixel) · segmenter pixels inside each box, detector's class · IoU per class on held-out scenes 🔒 Subscribe
- 125 Case file: rescue a failing runprinted shapes · the loss curve · one fix at a time 🔒 Subscribe