HomeAll tracks · pricing · account
Python11 apps · Python, SQL & data
Start free Log in

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

img = glyphs.images[22]a heart

Track your progress

Save where you are and see what you remember.

Sign up 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.

  1. Datatensors, batches 0 / 64
  2. Modelforward 0 / 155
  3. Losshow wrong 0 / 20
  4. Backwardgradients 0 / 20
  5. Stepupdate weights 0 / 42
  6. Evaluatepredict, score 0 / 62

Data0 / 64

torch.tensor.shape · .dtypetorch.zeros · ones · fulltorch.arange · linspacetorch.zeros_likex[r] · x[:, c]x[a:b, c:d:step]x[mask] · x[mask] = v.clone().reshape · .view.flatten.unsqueeze · .squeeze.permute · .Tkeepdim=Truetorch.from_numpy · .numpy()torch.tensor(df.to_numpy(dtype='float32'))TensorDatasetDataLoader(ds, batch_size, shuffle=True)drop_last=Truerandom_splittorch.Generator().manual_seed(n)polynomial featuresload('glyphs', messy=True)train / validation / test(y[:, None] == torch.arange(10)).sum(0)next(iter(loader))torch.rolltorch.log(price)K folds: randperm(N).reshape(K, N // K)standardise on the training rowsdevice = 'cuda' if torch.cuda.is_available() else 'cpu'xb = xb.to(device)x.device.reshape after permuteseed_everythingtorch.GeneratorDataLoader(ds, batch_size=B)x.unfold(0, tau, 1)split by timesorted(set(text)) · stoiCounter.most_common · <unk>encode · decoderandom · sequential windowsvocabulary + special tokensencode + pad to Tmask · valid lengthsteacher forcingF.unfold(x, kernel_size=p, stride=p)masked-token targets (BERT)v2.RandomCrop(16, padding=p)v2.Compose([...])torch.stack([aug(x) for x in xb])box_convertmake_anchorslabelling anchorsencode · decodeF.one_hot(ids, V)skip-gram · CBOWsubsamplingBPE: count pairs · merge the bestbpe(word): replay the merges[CLS] a [SEP] b [SEP]MDP as tensorsDataLoader(num_workers, pin_memory)

Model0 / 155

torch.manual_seed · rand · randn+ - * / **broadcastingtorch.dot@ · torch.matmul.norm()requires_grad=True.requires_grad_(False)if / for / whiletorch.wherew * x + bnn.Linear(in, out)nn.init.zeros_x.reshape(-1, 256) @ W + bnn.Sequential(nn.Flatten(), nn.Linear(256, 10))nn.Flatten()nn.Sequentialnn.ReLUhidden layernn.Sigmoid() · nn.Tanh()nn.GELU()the glyph MLPmodel[i]p.numel()nn.init.kaiming_uniform_(w, nonlinearity='relu')nn.init.xavier_uniform_(w)model.load_state_dict(state)nn.Dropout(p)class Net(nn.Module)super().__init__()model(x)nn.ModuleListnn.ModuleDictnn.Sequential(*layers)model.named_parameters()layer.requires_grad_(False)tied weightsnn.init.normal_ · zeros_ · kaiming_uniform_ · xavier_uniform_model.apply(fn)nn.LazyLinear(out)a layer with no weightsnn.Parameterregister_buffermodel.to(device)nn.Conv2dkernel · feature mapslide a kernelF.conv2dedge kernelnn.Conv2d(in, out, k)conv.weightConv2d(padding=p)Conv2d(stride=s)the output-size formulann.Conv2d(in, out, k)conv parameter countkernel_size=1nn.MaxPool2d(k)nn.AvgPool2d(k)LeNetFlatten size from a blank glyphnet[0].weightvgg_block(n_convs, in_c, out_c)nn.Conv2d(in_c, out_c, 3, padding=1)nn.Sequential(*layers)NiN blocknn.AdaptiveAvgPool2d(1)a head with no LinearInception blocktorch.cat(outs, dim=1)1 × 1 squeezenn.BatchNorm2d(C)Conv2d(..., bias=False) → BatchNorm2dF.relu(self.block(x) + x)1 × 1 projection shortcutnn.Conv2d(..., groups=g)torch.cat([x, layer(x)], dim=1)dense block (growth rate k)transitioncount_macs(model, x)groups=work per examplebigram tableh = tanh(x W_xh + h W_hh + b)nn.RNNCellnn.Embedding(vocab, d)nn.RNN(d, hidden, batch_first=True)nn.RNN(input, hidden, batch_first=True)output vs h_nnn.LSTMnn.LSTMCellforget-gate biasnn.GRUnn.GRUCellreset r · update znn.RNN(num_layers=L)bidirectional=Trueh_n.view(L, D, B, H)EncoderDecodergru(x, h)scores = K @ qattention weightsweights @ Vq.unsqueeze(1) - k.unsqueeze(0)softmax(-d ** 2 / (2 * width ** 2), dim=1) @ valuesscores.masked_fill(mask, float('-inf'))q @ k.transpose(-2, -1) / d ** 0.5additive scoremasked_fill(~mask, float('-inf'))F.scaled_dot_product_attentionencoder states as keysadditive attention with a masknn.GRUCellview + transpose (split heads)nn.MultiheadAttentionself-attentionpositional encodingnn.LayerNorm(d)residual + normnn.TransformerEncoderLayer(d, h, dim_feedforward, batch_first=True)nn.Transformercausal mask (tgt_mask)TinyGPTload_state_dict(load('tinygpt').state)Conv2d(C, d, kernel_size=p, stride=p)class token + positionscausal vs full maskswap the headSceneNet (one-stage detector)torchvision.ops.roi_pooltorchvision.ops.roi_alignFast R-CNN headnn.ConvTranspose2dF.conv_transpose2dnn.Upsample + Conv2dencoder → decoder (FCN)nn.Embedding(V, d)SkipGramnn.EmbeddingBag(mode='sum')text-CNNout[torch.arange(B), last]TinyBERTpadding maskload_state_dict(w.state, strict=False)mean over real tokenstask headsgenerator + discriminatorDCGAN Generatorload two halvesQ-tablenn.Embedding factor tabledot-product ratingtorch.autocast(device_type, dtype=torch.float16, enabled=on_gpu)torch.compile(model)

Loss0 / 20

Backward0 / 20

Step0 / 42

Evaluate0 / 62

Part 1

Tensors

0/8

A photo is a tensor: making, slicing, reshaping and reducing tensors, broadcasting, the maths a layer does, and the bridge to NumPy.

  1. 01 A photo is a tensortorch.tensor · .shape · .dtype · .item() Up next
  2. 02 Making tensorstorch.zeros · torch.ones · torch.full · torch.arange · torch.linspace · torch.rand · torch.randn · torch.zeros_like · torch.manual_seed Free account
  3. 03 Slicingimg[r] · img[:, c] · img[a:b, c:d] · img[::2] · img[-1] · img[img > 0.5] · .clone() Free account
  4. 04 Maths on tensors and broadcasting+ - * / ** · > == · broadcasting 🔒 Subscribe
  5. 05 Reshape without fear.reshape · .view · .flatten · .unsqueeze · .squeeze · .permute · .T · .contiguous() 🔒 Subscribe
  6. 06 Reductions and dim.sum(dim) · .mean(dim) · .max(dim) · .argmax(dim) · keepdim=True 🔒 Subscribe
  7. 07 Linear algebra you'll actually usetorch.dot · @ (torch.matmul) · .norm() 🔒 Subscribe
  8. 08 Tensors and the rest of Pythontorch.from_numpy · .numpy() · .tolist() · add_ · .float() / .long() 🔒 Subscribe
Part 2

Autograd

0/6

Slopes, requires_grad and backward, the computational graph, gradients that add up, and when to stop them.

  1. 09 Slopesdef f(x) on tensors · (f(x + h) - f(x)) / h · many h at once 🔒 Subscribe
  2. 10 requires_grad and .backward()requires_grad=True · .backward() · .grad 🔒 Subscribe
  3. 11 The graph.grad_fn · .grad_fn.name() · .is_leaf 🔒 Subscribe
  4. 12 Gradients add up.grad.zero_() · .grad = None · .backward(gradient=…) 🔒 Subscribe
  5. 13 Stop the gradient.detach() · torch.no_grad() · torch.inference_mode() · .requires_grad_(False) 🔒 Subscribe
  6. 14 Gradients through Pythonif · for · while on tensors · torch.where 🔒 Subscribe
Part 3

The training loop

0/9

Fit a line by hand, then the five-line loop every model uses: forward, loss, zero_grad, backward, step. Minibatches, validation, weight decay.

  1. 15 Fit a line by handw * x + b · (pred - y) ** 2 · .mean() · mean squared error 🔒 Subscribe
  2. 16 Gradient descent by handw -= lr * w.grad · torch.no_grad() · w.grad.zero_() 🔒 Subscribe
  3. 17 The five-line looptorch.optim.SGD · opt.zero_grad() · opt.step() 🔒 Subscribe
  4. 18 nn.Linear and nn.MSELossnn.Linear · nn.MSELoss · model.parameters() · model.weight · model.bias 🔒 Subscribe
  5. 19 MinibatchesTensorDataset · DataLoader(batch_size, shuffle) · len(loader) · drop_last 🔒 Subscribe
  6. 20 Train and validaterandom_split · torch.Generator().manual_seed · validation loss under torch.no_grad() 🔒 Subscribe
  7. 21 Too simple, too wigglytorch.cat([x ** k …], dim=1) · nn.Linear(degree, 1) · underfitting · overfitting 🔒 Subscribe
  8. 22 Weight decayL2 penalty · torch.optim.SGD(..., weight_decay=…) 🔒 Subscribe
  9. 23 Tidy training codedef train_one_epoch · def evaluate · def fit · model.train() · model.eval() · loader.dataset 🔒 Subscribe
Part 4

Classification

0/7

Softmax and cross-entropy, an image dataset, accuracy, and what happens when the world changes.

  1. 24 Scores to probabilitiestorch.softmax(x, dim) · F.softmax · .exp() · temperature 🔒 Subscribe
  2. 25 Cross-entropynn.CrossEntropyLoss · torch.log · reduction='none' 🔒 Subscribe
  3. 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
  4. 27 Softmax regression from scratchx.reshape(-1, 256) @ W + b · torch.exp · torch.log · p[torch.arange(n), y] 🔒 Subscribe
  5. 28 Softmax regression, concisenn.Sequential · nn.Flatten · nn.CrossEntropyLoss · torch.logsumexp 🔒 Subscribe
  6. 29 Is it any good?argmax(dim=1) · (pred == y).float().mean() · model.eval() · torch.no_grad() · torch.bincount 🔒 Subscribe
  7. 30 When the world changestorch.roll · accuracy per kind · covariate, label and concept shift 🔒 Subscribe
Part 5

Multilayer perceptrons

0/8

Hidden layers and activations, backprop, vanishing gradients and initialisation, early stopping, dropout.

  1. 31 Why a hidden layernn.Sequential · nn.ReLU · hidden units · decision boundary 🔒 Subscribe
  2. 32 Activationsnn.ReLU · nn.Sigmoid · nn.Tanh · nn.GELU 🔒 Subscribe
  3. 33 Your first MLPnn.Sequential · nn.ReLU · model[i] · p.numel() 🔒 Subscribe
  4. 34 Forward and backward.retain_grad() · loss.backward() through layers · torch.no_grad() 🔒 Subscribe
  5. 35 Vanishing and explodingp.grad.norm() per layer · nn.init.xavier_uniform_ · nn.init.kaiming_uniform_ 🔒 Subscribe
  6. 36 Early stoppingpatience · copy.deepcopy(model.state_dict()) · model.load_state_dict() 🔒 Subscribe
  7. 37 Dropoutnn.Dropout(p) · model.train() · model.eval() · the 1/(1−p) scaling 🔒 Subscribe
  8. 38 Price the homestorch.log · torch.randperm · torch.cat · 5-fold cross-validation · .sqrt() (RMSE) 🔒 Subscribe
Part 6

Building blocks

0/7

nn.Module, containers, parameters, initialisation, custom layers, saving and loading, devices.

  1. 39 nn.Module: a network as a classnn.Module · super().__init__() · forward · model(x) 🔒 Subscribe
  2. 40 Containers and control flownn.ModuleList · nn.ModuleDict · nn.Sequential(*layers) · for / if in forward 🔒 Subscribe
  3. 41 Parametersmodel.named_parameters() · module.requires_grad_(False) · p.requires_grad · tied weights 🔒 Subscribe
  4. 42 Initialisationnn.init.normal_ · nn.init.zeros_ · nn.init.kaiming_uniform_ · nn.init.xavier_uniform_ · model.apply(fn) · nn.LazyLinear 🔒 Subscribe
  5. 43 Custom layersnn.Parameter · register_buffer · named_buffers() 🔒 Subscribe
  6. 44 Save and loadtorch.save · torch.load · load_state_dict · opt.state_dict() · checkpoint dict 🔒 Subscribe
  7. 45 Devicestorch.device · torch.cuda.is_available() · .to(device) · x.device 🔒 Subscribe
Part 7

Convolutions

0/8

Why convolution, kernels, padding and stride, channels, pooling, LeNet.

  1. 46 Why convolutionnn.Conv2d · kernel_size · feature map · weight sharing 🔒 Subscribe
  2. 47 Slide a kernelF.conv2d · (N, C, H, W) · edge kernels 🔒 Subscribe
  3. 48 Learn a kernelnn.Conv2d(1, 1, 3, bias=False) · conv.weight · the loop on a kernel 🔒 Subscribe
  4. 49 Padding and stridenn.Conv2d(padding=, stride=) · padding='same' · ⌊(n + 2p − k) / s⌋ + 1 🔒 Subscribe
  5. 50 Channelsnn.Conv2d(in_channels, out_channels, k) · conv.weight (out, in, k, k) · kernel_size=1 🔒 Subscribe
  6. 51 Poolingnn.MaxPool2d · nn.AvgPool2d 🔒 Subscribe
  7. 52 LeNetnn.Sequential of Conv2d · MaxPool2d · Flatten · model[:k](torch.zeros(1, 1, 16, 16)) 🔒 Subscribe
  8. 53 Train LeNettrain a convnet · net[:2](x) · net[0].weight 🔒 Subscribe
Part 8

Make it work

0/4

Overfit one batch, read the loss curve, the classic PyTorch bugs, reproducible runs.

  1. 54 Overfit one batch firstone fixed batch · the loss must reach ~0 · a stalled loss = a bug 🔒 Subscribe
  2. 55 Read the loss curvesteps.append(loss.item()) · math.isnan · train vs validation loss 🔒 Subscribe
  3. 56 The classic bugsopt.zero_grad() · raw logits · model.eval() · .long() · .reshape · loss.item() 🔒 Subscribe
  4. 57 Reproducible runstorch.manual_seed · torch.Generator · random.seed · np.random.seed · torch.use_deterministic_algorithms 🔒 Subscribe
Part 9

Modern CNNs

0/7

Blocks, 1×1 convolutions, branches, batch normalisation, residual and dense connections.

  1. 58 Deeper with blocksvgg_block(n_convs, in_c, out_c) · nn.Conv2d(in_c, out_c, 3, padding=1) · nn.Sequential(*layers) 🔒 Subscribe
  2. 59 1 × 1 and global average poolingNiN block (3 × 3 conv → 1 × 1 → 1 × 1) · nn.AdaptiveAvgPool2d(1) · a head with no Linear 🔒 Subscribe
  3. 60 Many branchesan Inception block · torch.cat(outs, dim=1) · a 1 × 1 squeeze before a big kernel 🔒 Subscribe
  4. 61 Batch normalisationnn.BatchNorm2d · running_mean · running_var · train() / eval() · bias=False 🔒 Subscribe
  5. 62 Residual connectionsF.relu(self.block(x) + x) · a 1 × 1 projection shortcut · nn.Identity · nn.Conv2d(..., groups=…) 🔒 Subscribe
  6. 63 Dense connectionstorch.cat([x, layer(x)], dim=1) · growth rate · transition: 1 × 1 nn.Conv2d + nn.AvgPool2d(2) 🔒 Subscribe
  7. 64 Designing networkslayer.weight.numel() · isinstance(layer, nn.Conv2d) · a multiply-add counter · groups= 🔒 Subscribe
Part 10

Optimisation

0/8

The loss landscape, SGD and minibatch noise, momentum, adaptive rates, Adam, schedules.

  1. 65 The landscapedv.surface · dv.path · w.grad.norm() · SGD on a 2-element weight 🔒 Subscribe
  2. 66 Gradient descent, revisitedtorch.optim.SGD on a 2-weight tensor · lr < 2 ÷ curvature · torch.autograd.grad(..., create_graph=True) 🔒 Subscribe
  3. 67 SGD and minibatch noiseDataLoader(batch_size) · len(loader) · a batch gradient as a noisy estimate · counting work per example 🔒 Subscribe
  4. 68 MomentumSGD(..., momentum=0.9) · opt.state[p]['momentum_buffer'] · nesterov=True 🔒 Subscribe
  5. 69 Adaptive ratestorch.optim.Adagrad · torch.optim.RMSprop · optimizer.state[p] 🔒 Subscribe
  6. 70 Adam and AdamWtorch.optim.Adam · opt.state[w] · torch.optim.AdamW 🔒 Subscribe
  7. 71 Scheduleslr_scheduler.StepLR · CosineAnnealingLR · LinearLR + SequentialLR · OneCycleLR · scheduler.step() 🔒 Subscribe
  8. 72 Choosing an optimisertorch.optim.AdamW · opt.param_groups · nn.utils.clip_grad_norm_ 🔒 Subscribe
Part 11

Sequences and RNNs

0/10

Sequences, text to numbers, language models, hidden states, LSTM, GRU, deep and bidirectional RNNs.

  1. 73 Sequencesx.unfold(0, tau, 1) · a split by time · k-step forecasts fed back with torch.cat 🔒 Subscribe
  2. 74 Text to numberssorted(set(text)) · Counter.most_common · word2id.get(w, 0) · torch.tensor(ids) · ids.tolist() 🔒 Subscribe
  3. 75 Language modelstorch.bincount · torch.multinomial · perplexity = exp(mean −log p) · random / sequential minibatches 🔒 Subscribe
  4. 76 A hidden stateh = torch.tanh(x[t] @ W_xh + h @ W_hh + b) · nn.RNNCell · weight_ih · weight_hh 🔒 Subscribe
  5. 77 A character RNNnn.Embedding · nn.RNN(batch_first=True) · torch.multinomial(softmax(logits / temperature)) 🔒 Subscribe
  6. 78 nn.RNNnn.RNN(batch_first=True) · output, h_n = rnn(x, h0) · h.detach() 🔒 Subscribe
  7. 79 Backprop through timeh.retain_grad() · h.detach() every k steps (truncated BPTT) · nn.utils.clip_grad_norm_ 🔒 Subscribe
  8. 80 LSTMnn.LSTMCell · nn.LSTM → (output, (h_n, c_n)) · the forget-gate bias 🔒 Subscribe
  9. 81 GRUnn.GRUCell · nn.GRU · reset gate r · update gate z 🔒 Subscribe
  10. 82 Deeper and bidirectionalnn.RNN(num_layers=…) · bidirectional=True · output vs h_n · h_n.view(layers, directions, batch, hidden) 🔒 Subscribe
Part 12

Encoder–decoder

0/5

Translation data, encoder and decoder, teacher forcing, BLEU, beam search.

  1. 83 Translation datavocabulary with special tokens · stoi.get(w, UNK) · <eos> + padding to T · (X != PAD).sum(dim=1) · a boolean mask 🔒 Subscribe
  2. 84 Encoder and decoderEncoder(nn.Module) · Decoder(nn.Module) · self.gru(x, h) · the context vector 🔒 Subscribe
  3. 85 Training seq2seqteacher forcing · CrossEntropyLoss(ignore_index=PAD) · logits.reshape(-1, V) 🔒 Subscribe
  4. 86 Predict and scoregreedy decoding (argmax, feed back, stop at <eos>) · clipped n-gram precision · brevity penalty · BLEU 🔒 Subscribe
  5. 87 Beam searchbeam search · scores.unsqueeze(1) + log_probs · flatten().topk(k) · indices // V, % V · length normalisation 🔒 Subscribe
Part 13

Attention and transformers

0/11

Queries, keys and values, multi-head attention, positions, the transformer block, a tiny GPT, vision transformers.

  1. 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
  2. 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
  3. 90 Scoring functionsq @ k.transpose(-2, -1) · ÷ √d · additive score (Linear + tanh) · masked_fill(~mask, -inf) · F.scaled_dot_product_attention 🔒 Subscribe
  4. 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
  5. 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
  6. 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
  7. 94 The transformer blocknn.LayerNorm · residual + norm (post-norm / pre-norm) · nn.TransformerEncoderLayer(batch_first=True, norm_first=…) 🔒 Subscribe
  8. 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
  9. 96 A tiny GPTTinyGPT (token + position embeddings → causal blocks → LayerNorm → head) · load_state_dict(load('tinygpt').state) · torch.topk for top-k sampling 🔒 Subscribe
  10. 97 Vision transformerF.unfold · Conv2d(kernel_size=4, stride=4) as patch embedding · class token · learned positions 🔒 Subscribe
  11. 98 Pretraining at scalemasked-token targets (-100 = no loss) · causal vs full attention masks · held-out loss of load('tinygpt') 🔒 Subscribe
Part 14

Vision in practice

0/8

Augmentation, fine-tuning, boxes and IoU, anchors, a tiny detector, segmentation.

  1. 99 Augmentationv2.RandomCrop · v2.Compose · v2.RandomHorizontalFlip · v2.RandomErasing · v2.ColorJitter 🔒 Subscribe
  2. 100 Fine-tuningload_state_dict(load('glyphnet').state) · model.features.requires_grad_(False) · a new head · torch.optim.Adam([{'params': …, 'lr': …}, …]) parameter groups 🔒 Subscribe
  3. 101 Boxes and IoUtorchvision.ops.box_convert · IoU by hand · torchvision.ops.box_iou 🔒 Subscribe
  4. 102 Anchors and NMSmake_anchors · labelling anchors by IoU · encode / decode offsets · torchvision.ops.nms · torchvision.ops.batched_nms 🔒 Subscribe
  5. 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
  6. 104 The R-CNN familytorchvision.ops.roi_pool · torchvision.ops.roi_align (spatial_scale, sampling_ratio, aligned) · a Linear head on RoI features 🔒 Subscribe
  7. 105 Transposed convolutionnn.ConvTranspose2d · F.conv_transpose2d · (n − 1)·s − 2p + k · nn.Upsample + conv 🔒 Subscribe
  8. 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
Part 15

Language in practice

0/7

Word embeddings, word2vec, subwords, sentiment, BERT and fine-tuning.

  1. 107 Word embeddingsF.one_hot · torch.cdist · nn.Embedding · emb.weight · skip-gram and CBOW pairs 🔒 Subscribe
  2. 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
  3. 109 SubwordsCounter of pairs · most_common(1) · the merge list · nn.EmbeddingBag(mode='sum') 🔒 Subscribe
  4. 110 Similarity and analogyF.cosine_similarity · F.normalize(V, dim=1) then U @ U[i] · analogies: b − a + c, nearest word 🔒 Subscribe
  5. 111 Sentimentnn.Conv1d over time · .max(dim=2).values · out[torch.arange(B), last] 🔒 Subscribe
  6. 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
  7. 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
Part 16

Beyond

0/7

GANs, hyperparameter search, reinforcement learning, recommenders, and making it fast at home.

  1. 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
  2. 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
  3. 116 Hyperparameter searchgrid search · random search (10 ** (torch.rand(n) * 4 - 3)) · successive halving · choose on validation, test once 🔒 Subscribe
  4. 117 Decisions, rewards, valuesstates · actions · rewards · discount γ · value iteration: Q = R[nxt] + γ · V[nxt] · Q.max(dim=0) · Q.argmax(dim=0) 🔒 Subscribe
  5. 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
  6. 119 Recommendersnn.Embedding factors · bias embeddings · RMSE vs baselines · topk recommendations 🔒 Subscribe
  7. 120 Making it fast at hometorch.autocast · torch.amp.GradScaler · torch.compile · DataLoader(num_workers, pin_memory) · torch.cuda.synchronize() · DistributedDataParallel 🔒 Subscribe
Part 17

Case files

0/5

Open problems end to end: shapes, waves, tales, scenes, and a failing run to rescue.

  1. 121 Read the shapessplit · baseline · CNN · loss curves · confusion matrix · one test score 🔒 Subscribe
  2. 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
  3. 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
  4. 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
  5. 125 Case file: rescue a failing runprinted shapes · the loss curve · one fix at a time 🔒 Subscribe