Add step-by-step homework guide

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
zase414andClaude Opus 5.5 committed 2026-11-27 15:46:46 +01:00
1 parent f3fdb1ee65
commit 8512c2c27b
1 file changed
+828
+828
View File
@@ -0,0 +1,828 @@
# HW3 Walkthrough: One CNN, Three Tasks
This guide takes you from the empty skeleton to a trained `weights.pth`. It is meant for people who have **little PyTorch or NumPy experience**.
The goal is for you to understand what each piece does and why. Memorising function names is not the goal; you can always look those up. Each step has the same layout:
1. **Idea**: what is happening, in plain words.
2. **Code**: a working snippet, plus the exact place it goes in `train.py` or `model.py`.
3. **Check**: a quick way to confirm the step works before moving on.
> Line numbers refer to the **original, unedited** `train.py`. Once you start adding code, they shift. Search for the ‼️ markers instead.
---
## Contents
0. [The big picture](#0-the-big-picture)
1. [Five ideas you need before writing code](#1-five-ideas-you-need-before-writing-code)
2. [Step 1: Look at the data and set the config](#step-1-look-at-the-data-and-set-the-config)
3. [Step 2: The Dataset (`FruitDataset`)](#step-2-the-dataset-fruitdataset)
4. [Step 3: The model (`model.py`)](#step-3-the-model-modelpy)
5. [Step 4: The three losses](#step-4-the-three-losses)
6. [Step 5: The training loop (`run_fold`)](#step-5-the-training-loop-run_fold)
7. [Step 6: Train, watch, tune](#step-6-train-watch-tune)
8. [Step 7: Submit](#step-7-submit)
9. [Traps in the skeleton (read this!)](#traps-in-the-skeleton-read-this)
10. [Glossary of the PyTorch calls used](#glossary-of-the-pytorch-calls-used)
---
## 0. The big picture
You are building **one network** that looks at a 64×64 fruit photo and produces **three outputs at once**:
```
┌──────────────► class scores [30] "it's a Banana"
image ──► BACKBONE ──► │
[3,64,64] (shared) ├──────────────► embedding [128] a "fingerprint" vector
│
└──► DECODER ──► mask [1,64,64] "these pixels are fruit"
```
The backbone is **shared**: all three tasks learn from the same features. Training pushes three "pressures" (losses) into the same weights:
| Output | What it should do | Loss that teaches it | Graded by |
|---|---|---|---|
| class scores | highest score for the right fruit | Cross-entropy | Accuracy |
| mask | 1 on fruit pixels, 0 on background | Binary cross-entropy | Mean IoU |
| embedding | same fruit → vectors point the same way; different fruit → different directions | Triplet loss | ROC AUC and TPR@5%FPR |
Training is always the same four-beat rhythm, repeated thousands of times:
```
take a batch ─► model predicts ─► loss measures "how wrong" ─► gradients say "which way to nudge each weight" ─► optimizer nudges
```
Almost everything in `train.py` is bookkeeping around those four beats.
---
## 1. Five ideas you need before writing code
You can run each snippet in this section on its own (`python` then paste). They are small experiments for building intuition.
### 1.1 A tensor is an array with a shape, and the shape is everything
Most bugs in this homework are **shape bugs**. Images go through the network as a 4-D block:
```
[B, C, H, W] = [batch size, channels, height, width]
e.g. [32, 3, 64, 64] = 32 RGB images, 64×64 pixels each
```
PIL and NumPy store images as `[H, W, C]` (channels last). PyTorch wants `[C, H, W]` (channels first). That is why you will see `.permute(2, 0, 1)` in the dataset.
### 1.2 What a convolution does
A 3×3 convolution slides a small 3×3 "stencil" over the image. At each position it computes a weighted sum of the pixels under it, across *all* input channels. One stencil gives one output channel. If you ask for 8 output channels, you get 8 stencils, i.e. 8 different "detectors" (edge, colour blob, ...). **The stencil weights are what the network learns.**
```python
import torch, torch.nn as nn
x = torch.randn(2, 3, 64, 64) # 2 fake RGB images
conv = nn.Conv2d(3, 8, kernel_size=3, padding=1)
y = conv(x)
print(y.shape) # [2, 8, 64, 64] -> 8 feature maps, same size (padding=1 keeps it)
print(nn.MaxPool2d(2)(y).shape) # [2, 8, 32, 32] -> pooling halves H and W
print(conv.weight.shape) # [8, 3, 3, 3] -> 8 stencils, each 3 channels × 3 × 3
print(y.mean(dim=(2, 3)).shape) # [2, 8] -> "global average pool": one number per channel
```
The standard CNN pattern: **convolve (detect features) → pool (shrink) → repeat**. Each round gives fewer pixels but more channels. Early layers see edges; deep layers see "banana-ness".
### 1.3 Logits: the network outputs raw scores, not probabilities
The last layer outputs arbitrary real numbers called **logits**. To turn them into probabilities:
- **many classes, pick one** → `softmax` (all outputs sum to 1)
- **yes/no per pixel** → `sigmoid` (each output squashed into 0..1)
The loss functions below take **logits directly** and apply softmax or sigmoid internally, because that is numerically safer. So the model must **not** end with a softmax or sigmoid.
### 1.4 Gradients and the optimizer: the whole of "learning" in 5 lines
```python
w = torch.tensor(5.0, requires_grad=True) # one "weight", starts at 5
opt = torch.optim.SGD([w], lr=0.1)
for step in range(30):
opt.zero_grad() # 1. forget the previous gradient
loss = (w - 2) ** 2 # 2. predict + measure error (best w is 2)
loss.backward() # 3. compute d(loss)/d(w) -> stored in w.grad
opt.step() # 4. w = w - lr * w.grad
print(w) # ≈ 2.0
```
A real network does the same thing, just for ~2 million weights at once. **Why `zero_grad()`?** PyTorch *adds* new gradients to old ones. Without resetting them you get 6, 12, 18, ... instead of 6, 6, 6:
```python
w = torch.tensor(5.0, requires_grad=True)
for i in range(3):
((w - 2) ** 2).backward(); print(w.grad) # 6, 12, 18 ← accumulating!
```
### 1.5 `train()` vs `eval()`, and `no_grad()`
Some layers behave differently while training:
- **Dropout** randomly zeroes neurons during training (a regulariser) and does nothing at evaluation.
- **BatchNorm** normalises with the current batch's statistics during training, and with a running average at evaluation.
`model.train()` and `model.eval()` flip that switch. They do **not** train or evaluate anything by themselves. Forgetting `model.eval()` gives noisy, worse validation numbers. Forgetting to switch back to `model.train()` quietly ruins training.
`with torch.no_grad():` tells PyTorch "don't record operations for backprop here". It is faster and uses less memory. Use it whenever you only predict.
---
## Step 1: Look at the data and set the config
### Idea
Before writing a Dataset, **look at the files**. You need to know:
- how the folders are organised,
- how an image is paired with its mask,
- what values the mask contains (0/1? 0/255?).
### Do it
Download and unzip the dataset (link in the README) so that `data_dir` in the config points at the folder containing the 30 fruit folders. Then:
```bash
ls Data | head # expect 30 fruit folders
ls Data/<SomeFruit> # expect something like Images/ and Mask/
ls Data/<SomeFruit>/Images | head -3
ls Data/<SomeFruit>/Mask | head -3
python -c "from PIL import Image; import numpy as np; m=np.array(Image.open('PATH/TO/ONE/MASK')); print(m.shape, m.dtype, np.unique(m))"
```
The dataset code below assumes `Data/<Fruit>/Images/<name>.jpg` + `Data/<Fruit>/Mask/<name>.png` (or `<name>_mask.png`). **If your layout differs, only the folder and file-matching lines need changing.** The rest stays the same.
### Config ([confs/config.yml](confs/config.yml))
Replace the ❓ with reasonable starting values. The extra keys at the bottom are read by the code in this guide through `config.get(...)`, so adding them is safe.
```yaml
data_dir: "Data/" # folder that contains the 30 fruit folders
batch_size: 32 # images per step; 32-64 is fine for 64×64 images
learning_rate: 0.001 # Adam-family default; the single most important knob
num_epochs: 60 # one epoch = every training image seen once
random_seed: 42
num_folds: 1 # 1 = simple 80/20 split. Use this while developing.
output_dim: 30
cache_images: true # keep decoded images in RAM: ~2000 small images, huge speedup
image_size: [64, 64]
validate_every: 5 # run validation every N epochs
# --- extra keys used by the code in this guide ---
weight_decay: 0.0001
loss_weights: {cls: 1.0, seg: 1.0, triplet: 1.0}
triplet_margin: 0.3
hard_percentage: 0.2
augment: true
```
> **Why `num_folds: 1`?** K-fold cross-validation trains K separate models to get a more reliable score estimate. That is useful for comparing ideas, but K times slower, and you can only submit one model anyway.
---
## Step 2: The Dataset (`FruitDataset`)
### Idea
A PyTorch `Dataset` is just an object that answers two questions:
- `len(dataset)`: how many samples are there?
- `dataset[i]`: give me sample number *i*, already converted to tensors.
The `DataLoader` (already written in `main()`) then asks for, say, 32 random indices, calls `dataset[i]` for each, and **stacks** the results into a batch: 32 tensors of `[3,64,64]` become one `[32,3,64,64]` tensor.
So the Dataset's whole job is: **file on disk → correctly shaped, correctly scaled tensor.**
What `__getitem__` must return, and why:
| Return value | Shape / type | Why this format |
|---|---|---|
| `image` | float `[3, 64, 64]`, values ≈ −1..1 | conv layers want channels first; small centred numbers train much better than 0..255 |
| `mask` | float `[1, 64, 64]`, values **exactly 0 or 1** | must match the model's mask output shape; the loss and IoU code compare against 0/1 |
| `metadata` | `str`, e.g. `"Banana"` | used by `main()` for the stratified split |
| `label` | long (integer) tensor, e.g. `tensor(4)` | cross-entropy wants a class *index*, not a name |
| `idx` | `int` | lets the training loop write this sample's embedding into the "embedding bank" at the right row |
Two details are easy to get wrong:
- **Resize masks with `NEAREST`**, never bilinear. Bilinear blends neighbouring pixels and creates values like 0.5 at fruit edges. A mask pixel is either fruit or not.
- **Binarise masks.** Mask files are often stored as 0/255. The provided `compute_seg_metrics` checks `target == 1`, so a 0/255 mask gives IoU = 0 forever, with no error message.
### Code: replace the whole `FruitDataset` class (original lines 34–74)
```python
class FruitDataset(Dataset):
"""Fruit dataset: returns (image, mask, fruit_name, label, idx)."""
def __init__(self, data_dir, config):
self.data_dir = data_dir
self.config = config
self.image_size = tuple(config["image_size"]) # (64, 64)
self.images = [] # path to every image
self.masks = [] # path to the matching mask (same position!)
self.metadata = [] # fruit name of every image, e.g. "Banana"
for fruit in sorted(os.listdir(data_dir)):
fruit_dir = os.path.join(data_dir, fruit)
if not os.path.isdir(fruit_dir):
continue
img_dir = os.path.join(fruit_dir, "Images") # ← adapt if your folders are named differently
mask_dir = os.path.join(fruit_dir, "Mask") # ←
# map "file name without extension" -> mask file name
masks_by_stem = {os.path.splitext(f)[0]: f for f in os.listdir(mask_dir)}
for img_name in sorted(os.listdir(img_dir)):
stem = os.path.splitext(img_name)[0]
mask_name = masks_by_stem.get(stem) or masks_by_stem.get(stem + "_mask")
if mask_name is None:
raise FileNotFoundError(f"No mask found for {img_dir}/{img_name}")
self.images.append(os.path.join(img_dir, img_name))
self.masks.append(os.path.join(mask_dir, mask_name))
self.metadata.append(fruit)
# fruit name -> integer 0..29 (sorted, so it is always the same mapping)
self.class_names = sorted(set(self.metadata))
self.class_to_idx = {name: i for i, name in enumerate(self.class_names)}
self.labels = [self.class_to_idx[name] for name in self.metadata]
self.loaded_images = {} # idx -> (image, mask), filled only if caching
def __len__(self):
return len(self.images)
def _load(self, idx):
# --- image: file -> PIL -> numpy -> torch, shape [3, H, W], values ~[-1, 1]
image = Image.open(self.images[idx]).convert("RGB")
image = image.resize(self.image_size, Image.BILINEAR)
image = np.asarray(image, dtype=np.float32) / 255.0 # [H, W, 3] in [0, 1]
image = (image - 0.5) / 0.5 # [H, W, 3] in [-1, 1]
image = torch.from_numpy(image).permute(2, 0, 1) # [3, H, W]
# --- mask: file -> grayscale -> 0/1 float, shape [1, H, W]
mask = Image.open(self.masks[idx]).convert("L")
mask = mask.resize(self.image_size, Image.NEAREST) # NEAREST: no in-between values
mask = np.asarray(mask)
mask = mask > (mask.max() / 2) # works for 0/1 and 0/255 masks
mask = torch.from_numpy(mask).float().unsqueeze(0) # [1, H, W]
return image, mask
def __getitem__(self, idx):
if idx in self.loaded_images:
image, mask = self.loaded_images[idx]
else:
image, mask = self._load(idx)
if self.config.get("cache_images", False):
self.loaded_images[idx] = (image, mask)
metadata = self.metadata[idx]
label = torch.tensor(self.labels[idx], dtype=torch.long)
return image, mask, metadata, label, idx
```
**Why `_load` is a separate helper:** it keeps "read from disk" apart from "use the cache", so caching is three lines and easy to follow.
**Why `(x - 0.5) / 0.5`:** it centres pixel values around 0. Weights start out small and centred too, so the first layers aren't flooded with large one-sided inputs. Computing the true per-channel mean and std of the dataset is slightly better, but not necessary.
### Check
Temporarily add this at the bottom of `train.py`, or run it in a Python shell from the repo folder:
```python
import yaml
from train import FruitDataset
cfg = yaml.safe_load(open("confs/config.yml"))
ds = FruitDataset(cfg["data_dir"], cfg)
img, mask, name, label, idx = ds[0]
print(len(ds), len(ds.class_names)) # ~1969, 30
print(img.shape, img.min().item(), img.max().item()) # [3, 64, 64], ≈ -1, ≈ 1
print(mask.shape, mask.unique()) # [1, 64, 64], tensor([0., 1.])
print(name, label) # e.g. Apple_Braeburn tensor(0)
```
If `mask.unique()` shows only `0.` for most samples, the mask threshold or the file pairing is wrong. Fix that now, not after a 30-minute training run.
---
## Step 3: The model (`model.py`)
### Idea
The architecture is a small **U-Net-style** network:
```
input [3,64,64]
│ enc1: conv_block 3→32 ───────────────────────────────┐ f1 [32,64,64]
│ pool │
│ enc2: conv_block 32→64 ─────────────────────┐ f2 │
│ pool │ [64,32,32] │
│ enc3: conv_block 64→128 ───────────┐ f3 │ │
│ pool │[128,16,16] │
│ enc4: conv_block 128→256 → f4 [256,8,8] │ │ │
│ │ │ │
├─► global avg pool → [256] ─┬─► classifier → [30] logits │
│ └─► embedding head → [128], normalised to length 1
│ │ │ │
└─► upsample ×2 + concat f3 → dec3 → upsample + concat f2 → dec2 → upsample + concat f1 → dec1 → 1×1 conv → [1,64,64] logits
```
Why each part is there:
- **`conv_block` = (conv → BatchNorm → ReLU) × 2.** This is the basic CNN unit. BatchNorm keeps activations well-scaled, which makes training more stable and lets you use higher learning rates. ReLU is the non-linearity; without it, the stacked layers would collapse into one linear function.
- **Pooling** shrinks 64→32→16→8. Each pixel deeper in the network "sees" a larger area of the original image, so deep features describe whole objects.
- **Global average pooling** (`f4.mean(dim=(2,3))`) turns `[256, 8, 8]` into 256 numbers: "how strongly is each of the 256 features present anywhere in the image". This is what classification and embedding need, since *where* the fruit is doesn't matter for them.
- **The decoder** goes back up to 64×64, because a mask needs one answer *per pixel*.
- **Skip connections** (`torch.cat([..., f3], dim=1)`): after pooling down to 8×8, fine detail about edges is lost. Gluing the earlier, high-resolution features back on lets the decoder draw sharp mask borders. This is the core idea of U-Net, and it makes a big difference to IoU.
- **`F.normalize` on the embedding** makes every embedding vector length 1. The evaluation (`compute_roc_metrics`) compares embeddings by **cosine similarity**, which only looks at direction. Normalising makes the training objective match the evaluation.
### Code: replace the whole contents of [model.py](model.py)
```python
import torch
import torch.nn as nn
import torch.nn.functional as F
def conv_block(in_ch, out_ch):
"""Two 3x3 convolutions, each followed by BatchNorm and ReLU.
Keeps the spatial size (padding=1), changes the number of channels."""
return nn.Sequential(
nn.Conv2d(in_ch, out_ch, kernel_size=3, padding=1, bias=False),
nn.BatchNorm2d(out_ch),
nn.ReLU(inplace=True),
nn.Conv2d(out_ch, out_ch, kernel_size=3, padding=1, bias=False),
nn.BatchNorm2d(out_ch),
nn.ReLU(inplace=True),
)
class MyModel(nn.Module):
def __init__(self, input_size=None, hidden_size=128, output_size=30, embedding_dim=128):
# input_size / hidden_size are passed by train.py but a CNN does not need them
super().__init__()
# ---------- backbone (encoder): 64x64 -> 8x8, 3 -> 256 channels ----------
self.enc1 = conv_block(3, 32) # [B, 32, 64, 64]
self.enc2 = conv_block(32, 64) # [B, 64, 32, 32]
self.enc3 = conv_block(64, 128) # [B, 128, 16, 16]
self.enc4 = conv_block(128, 256) # [B, 256, 8, 8]
self.pool = nn.MaxPool2d(2) # halves H and W
# ---------- classification head: 256 numbers -> 30 class scores ----------
self.species_classifier = nn.Sequential(
nn.Dropout(0.3),
nn.Linear(256, output_size),
)
# ---------- embedding head: 256 numbers -> embedding_dim numbers ----------
self.embedding_head = nn.Sequential(
nn.Linear(256, 256),
nn.ReLU(inplace=True),
nn.Linear(256, embedding_dim),
)
# ---------- segmentation head (decoder): 8x8 -> 64x64, 1 channel ----------
self.up = nn.Upsample(scale_factor=2, mode="bilinear", align_corners=False)
self.dec3 = conv_block(256 + 128, 128) # 16x16
self.dec2 = conv_block(128 + 64, 64) # 32x32
self.dec1 = conv_block(64 + 32, 32) # 64x64
self.mask_out = nn.Conv2d(32, 1, kernel_size=1)
def encode(self, x):
f1 = self.enc1(x) # [B, 32, 64, 64]
f2 = self.enc2(self.pool(f1)) # [B, 64, 32, 32]
f3 = self.enc3(self.pool(f2)) # [B, 128, 16, 16]
f4 = self.enc4(self.pool(f3)) # [B, 256, 8, 8]
return f1, f2, f3, f4
def embed(self, f4):
pooled = f4.mean(dim=(2, 3)) # [B, 256] global average pool
emb = self.embedding_head(pooled) # [B, D]
return F.normalize(emb, dim=1) # length 1 -> cosine friendly
def forward(self, x):
f1, f2, f3, f4 = self.encode(x)
# classification
pooled = f4.mean(dim=(2, 3)) # [B, 256]
species = self.species_classifier(pooled) # [B, 30] (logits)
# embedding
embeddings = self.embed(f4) # [B, D]
# segmentation: upsample, glue on the encoder feature of the same size, convolve
d = self.dec3(torch.cat([self.up(f4), f3], dim=1)) # [B, 128, 16, 16]
d = self.dec2(torch.cat([self.up(d), f2], dim=1)) # [B, 64, 32, 32]
d = self.dec1(torch.cat([self.up(d), f1], dim=1)) # [B, 32, 64, 64]
masks = self.mask_out(d) # [B, 1, 64, 64] (logits)
return species, masks, embeddings
def get_embedding(self, x):
*_, f4 = self.encode(x)
return self.embed(f4)
```
Notes:
- The skeleton names `self.backbone` and `self.segmentation_head`. They are not required. With skip connections the decoder needs the *intermediate* encoder outputs, so separate `enc1..enc4` attributes are simpler than one `nn.Sequential` backbone.
- `__init__` keeps the `input_size` and `hidden_size` parameters because `main()` passes them ([train.py:692](train.py#L692)). The defaults also make `MyModel(output_size=30)` work, which is how the grader is likely to construct it.
- `get_embedding` must give **exactly the same** vector as the third output of `forward`. Both go through `self.embed`, so they cannot drift apart.
### Check
```python
import torch
from model import MyModel
m = MyModel(output_size=30)
s, k, e = m(torch.randn(4, 3, 64, 64))
print(s.shape, k.shape, e.shape) # [4, 30] [4, 1, 64, 64] [4, 128]
print(e.norm(dim=1)) # all ≈ 1.0
print(sum(p.numel() for p in m.parameters())) # ≈ 2 million weights
```
---
## Step 4: The three losses
A loss is a single number that is **small when the prediction is good**. `loss.backward()` then works out, for every weight, which direction makes that number smaller.
### 4.1 Classification: cross-entropy
**Idea:** turn the 30 logits into probabilities with softmax, then take the **−log of the probability given to the correct class**. If the model is 100% sure and right, −log(1) = 0. If it gives the right class only 1%, −log(0.01) ≈ 4.6. Being confidently wrong is punished heavily.
```python
logits = torch.tensor([[2.0, 0.5, -1.0]]) # 3 classes
label = torch.tensor([0]) # correct class is 0
probs = logits.softmax(dim=1) # [0.786, 0.175, 0.039]
print(-probs[0, 0].log()) # 0.2413 (by hand)
print(nn.CrossEntropyLoss()(logits, label)) # 0.2413 (same)
```
At the start, with random weights and 30 classes, the loss is about −log(1/30) ≈ **3.4**. If your first printed `Class Loss` is near 3.4, everything is wired correctly.
### 4.2 Segmentation: binary cross-entropy (BCE) per pixel
**Idea:** every pixel is its own yes/no question, "is this fruit?". Sigmoid turns the pixel's logit into a probability *p*. The loss is −log *p* where the truth is 1 and −log(1−*p*) where the truth is 0, averaged over all 64×64 pixels of all images.
```python
logit = torch.tensor([3.0, -2.0]) # two pixels
target = torch.tensor([1.0, 1.0]) # both are fruit
p = torch.sigmoid(logit) # [0.953, 0.119]
print(-(target*p.log() + (1-target)*(1-p).log())) # [0.049, 2.127]
print(nn.BCEWithLogitsLoss(reduction='none')(logit, target)) # same
```
The second pixel is fruit, but the model says 12%, so it gets a large penalty. Use **`BCEWithLogitsLoss`** (sigmoid built in), not `BCELoss`: the validation code already applies `torch.sigmoid(masks_pred)` itself, so it expects the model to output logits.
> **Optional, for the 90% IoU tier:** BCE treats every pixel equally. If fruit covers a small part of the image, "all background" already scores well. A **Dice loss** works on overlap directly and complements BCE:
> ```python
> def dice_loss(logits, target, eps=1.0):
> p = torch.sigmoid(logits)
> inter = (p * target).sum(dim=(1, 2, 3))
> union = p.sum(dim=(1, 2, 3)) + target.sum(dim=(1, 2, 3))
> return 1 - ((2 * inter + eps) / (union + eps)).mean()
> # segmentation_loss = mask_criterion(masks_pred, masks) + dice_loss(masks_pred, masks)
> ```
### 4.3 Embeddings: triplet loss
**Idea:** we don't have a "correct embedding" to compare against. All we know is which images should be *close together*. So we compare three images:
- **anchor**: some image (e.g. a banana)
- **positive**: a *different* image of the **same** fruit (another banana)
- **negative**: an image of a **different** fruit (e.g. a lemon)
and require: **distance(anchor, positive) + margin ≤ distance(anchor, negative)**.
If that holds, the loss is 0 and the triplet is "solved". Otherwise the loss equals how far it is off, which pulls the positive closer and pushes the negative away:
```
loss = max(0, d(a,p) − d(a,n) + margin)
```
The **margin** stops the model from settling for "barely closer". It must create a real gap.
The distance used is **cosine distance = 1 − cosine similarity**. It is 0 for vectors pointing the same way and 2 for opposite vectors. We use it because the grader scores embeddings by cosine similarity (`compute_roc_metrics`). Because of that 0..2 range, a margin of ~0.2–0.5 is sensible. The default `margin=1.0` in the function signature is too big for this scale.
```python
import torch.nn.functional as F
a = F.normalize(torch.tensor([[1.0, 0.0]]), dim=1) # anchor
p = F.normalize(torch.tensor([[1.0, 1.0]]), dim=1) # positive: 45° away
n = F.normalize(torch.tensor([[1.0, 0.2]]), dim=1) # negative: only 11° away ← bad!
d_pos = 1 - F.cosine_similarity(a, p) # 0.293
d_neg = 1 - F.cosine_similarity(a, n) # 0.019
print(torch.relu(d_pos - d_neg + 0.3)) # 0.574 > 0 -> this triplet will be corrected
```
**Where do triplets come from?** The provided `create_triplets_batch` does this for you, using an **embedding bank**: a table with one row per image, holding the latest embedding computed for it. For each anchor in the batch, it looks through the bank and picks **hard** examples: the same-fruit images that are currently *furthest* away, and the other-fruit images that are currently *closest*. Easy triplets already have loss 0 and teach nothing, so hard mining focuses training where the model is wrong.
Each triplet is a tuple `(anchor_vec, positive_vec, negative_vec)`. Only the anchor came out of the model in this step, so only the anchor carries gradient. The positive and negative are frozen copies from the bank. That is fine: every image is an anchor once per epoch.
### Code: fill in `compute_triplet_loss` (original lines 309–322)
```python
def compute_triplet_loss(triplets, margin=1.0):
"""Triplet loss with cosine distance. triplets: list of (anchor, positive, negative) vectors."""
anchors = torch.stack([t[0] for t in triplets]) # [T, D] (has gradient)
positives = torch.stack([t[1] for t in triplets]) # [T, D] (from bank, no gradient)
negatives = torch.stack([t[2] for t in triplets]) # [T, D] (from bank, no gradient)
# cosine distance = 1 - cosine similarity (0 = same direction, 2 = opposite)
d_pos = 1 - torch.nn.functional.cosine_similarity(anchors, positives, dim=1) # [T]
d_neg = 1 - torch.nn.functional.cosine_similarity(anchors, negatives, dim=1) # [T]
# want d_pos + margin <= d_neg ; penalise by how much this is violated
loss = torch.relu(d_pos - d_neg + margin).mean()
return loss
```
`torch.stack` turns a Python list of T vectors (each `[D]`) into one `[T, D]` tensor. All T triplets are then computed at once instead of in a Python loop. `torch.relu(x)` is just `max(0, x)`.
---
## Step 5: The training loop (`run_fold`)
### Idea
`run_fold` is the four-beat rhythm from section 0, plus:
- **Device handling:** the model lives on the GPU, so every batch must be moved there too (`.to(device)`). **The skeleton never does this. You must add it** (see [Traps](#traps-in-the-skeleton-read-this)).
- **The embedding bank**, filled once before training and then updated batch by batch.
- **A validation pass** every `validate_every` epochs, which logs metrics and saves the best model.
Combined loss:
```
loss = w_cls · classification_loss + w_seg · segmentation_loss + w_triplet · triplet_loss
```
Gradients of a sum are the sum of the gradients, so a single `loss.backward()` trains all three heads and the shared backbone at once. The weights `w_*` decide how loudly each task "speaks" to the backbone. Start with all 1.0 and change them only if one task lags behind the others (see Step 6).
### Code: 5a. Setup (replace original lines 400–402)
```python
device = get_device()
species_criterion = torch.nn.CrossEntropyLoss()
mask_criterion = torch.nn.BCEWithLogitsLoss()
optimizer = torch.optim.AdamW(model.parameters(),
lr=config['learning_rate'],
weight_decay=config.get('weight_decay', 1e-4))
scheduler = torch.optim.lr_scheduler.CosineAnnealingLR(
optimizer, T_max=config['num_epochs'])
w = config.get('loss_weights', {'cls': 1.0, 'seg': 1.0, 'triplet': 1.0})
margin = config.get('triplet_margin', 0.3)
hard_pct = config.get('hard_percentage', 0.2)
```
- **AdamW** is gradient descent that adapts the step size for each weight separately. It works out of the box far more often than plain SGD. *Weight decay* gently pulls weights toward zero, which reduces overfitting.
- **The scheduler** lowers the learning rate smoothly from `learning_rate` to ~0 over all epochs. Big steps early cover ground quickly; small steps late fine-tune. This usually adds a few percent at the end for free.
### Code: 5b. Initial embedding banks (original lines 409, 411)
```python
embedding_bank, all_labels = compute_embedding_bank(train_loader.dataset, model)
# ...
embedding_bank_val, all_labels_val = compute_embedding_bank(val_loader.dataset, model)
```
`train_loader.dataset` is the training `Subset`. The bank has one row per image of the *full* dataset. Rows of images outside this subset stay `NaN`, and `create_triplets_batch` skips them. That is why train and validation never mix.
### Code: 5c. Start of each epoch (original line 417)
```python
model.train()
```
This goes *inside* the epoch loop, not before it. `compute_embedding_bank` and the validation pass both switch the model to `eval()`, so you have to switch back every epoch.
### Code: 5d. Inside the training batch loop (original lines 423–468)
Put the device moves and the optional augmentation at the very top of the loop body. Then zero the gradients and predict:
```python
for batch_idx, (images, masks, metadata, labels, idxs) in enumerate(train_pbar):
images = images.to(device)
masks = masks.to(device)
labels = labels.to(device)
if config.get('augment', False):
# flip a random half of the batch left-right (image AND its mask)
flip = torch.rand(images.size(0), device=device) < 0.5
images[flip] = images[flip].flip(-1)
masks[flip] = masks[flip].flip(-1)
optimizer.zero_grad()
outputs, masks_pred, embeddings = model(images)
# (existing embedding-bank update code stays here unchanged)
```
Then fill in the losses, the backward pass, and the training accuracy:
```python
classification_loss = species_criterion(outputs, labels)
segmentation_loss = mask_criterion(masks_pred, masks)
triplets = create_triplets_batch(embeddings, labels, idxs,
embedding_bank, all_labels,
hard_percentage=hard_pct)
if len(triplets) > 0:
triplet_loss = compute_triplet_loss(triplets, margin=margin)
else:
triplet_loss = torch.tensor(0.0, device=images.device)
loss = (w['cls'] * classification_loss
+ w['seg'] * segmentation_loss
+ w['triplet'] * triplet_loss)
# (existing NaN check stays here)
loss.backward()
optimizer.step()
batch_loss = loss.item()
trn_loss += batch_loss
predictions = outputs.argmax(dim=1)
train_correct += (predictions == labels).sum().item()
train_total += labels.size(0)
```
Why things are in this order:
- `zero_grad` comes **before** the forward pass, so the gradients from the last batch are cleared.
- The bank update (already in the skeleton) comes **before** `create_triplets_batch`, so mining sees the freshest embeddings. Mining excludes the anchor itself (`idx != anchor_idx`), so an image is never its own positive.
- `backward` then `step`: compute the directions first, then move. Swap them and you update with stale gradients.
- **Augmentation** (random flips) shows the model "new" images for free. A banana flipped left-to-right is still a banana, and its mask flips the same way. It goes in the *training loop*, not in the Dataset, because train and validation share one Dataset object, and validation must never be augmented. `.flip(-1)` flips along the last axis, which is width.
**`.item()`** turns a one-number tensor into a plain Python float. Use it for logging. Never call `.item()` on a loss you still need to `backward()`.
After the batch loop ends, step the scheduler once per epoch (just before `trn_loss /= len(train_loader)`):
```python
scheduler.step()
```
### Code: 5e. Validation (original lines 495–533)
Switch modes (original line 495):
```python
model.eval()
```
Then, at the top of the validation batch loop, move the batch to the device *before* `model(images)`:
```python
for batch_idx, (images, masks, metadata, labels, idxs) in enumerate(val_pbar):
images = images.to(device)
masks = masks.to(device)
labels = labels.to(device)
outputs, masks_pred, embeddings = model(images)
```
Compute the losses exactly as in training, but with the **validation** bank. There is **no** `zero_grad`, `backward` or `step` here: validation only measures.
```python
classification_loss = species_criterion(outputs, labels)
segmentation_loss = mask_criterion(masks_pred, masks)
triplets = create_triplets_batch(embeddings, labels, idxs,
embedding_bank_val, all_labels_val,
hard_percentage=hard_pct)
if len(triplets) > 0:
triplet_loss = compute_triplet_loss(triplets, margin=margin)
else:
triplet_loss = torch.tensor(0.0, device=images.device)
loss = (w['cls'] * classification_loss
+ w['seg'] * segmentation_loss
+ w['triplet'] * triplet_loss)
```
And fix the crash a few lines below (see Trap 3). Change the six `.append(x.item())` lines to `.append(float(x))`:
```python
precision1.append(float(p1))
recall1.append(float(r1))
iou1.append(float(i1))
precision2.append(float(p2))
recall2.append(float(r2))
iou2.append(float(i2))
```
### Code: 5f. One fix in `compute_embedding_bank` (original line 181)
```python
# size of the FULL dataset (a Subset keeps the original indices)
dataset_size = len(dataset.dataset) if isinstance(dataset, Subset) else len(dataset)
```
---
## Step 6: Train, watch, tune
```bash
python train.py
tensorboard --logdir experiments/ # in a second terminal, open http://localhost:6006
```
### What healthy training looks like
| Signal | Expected |
|---|---|
| First `Class Loss` | ≈ 3.4 (= −log(1/30)). Much higher means a bug. |
| First `Seg Loss` | ≈ 0.7 (= −log 0.5), dropping fast below 0.2 |
| `Triplet Loss` | starts at or above the margin, slowly decreases; it rarely reaches 0 because mining always picks the hardest cases |
| Train accuracy | climbs steadily |
| Val accuracy | climbs, then flattens |
### Reading the curves and what to change
| Symptom | Meaning | Try |
|---|---|---|
| Losses don't move at all | wiring bug (forgot `step()`, wrong label type, lr far too small) | redo the Checks in Steps 2–3 |
| Loss jumps around or becomes NaN | learning rate too high | lower `learning_rate` ×3–10 |
| Train acc ≫ val acc (e.g. 99% vs 80%) | **overfitting**: memorising the training images | augmentation, more dropout, more `weight_decay`, fewer epochs |
| Both train and val low | **underfitting**: model too weak or too little training | more epochs, wider layers (e.g. 48/96/192/384 channels) |
| Val IoU stuck while accuracy is fine | segmentation under-weighted | raise `loss_weights.seg`, add Dice loss |
| AUC good but TPR@5%FPR low | embedding clusters overlap at the edges | raise `triplet_margin` slightly (0.3→0.5), raise `loss_weights.triplet` |
| Class 1 IoU always exactly 0 | mask is 0/255, not 0/1, or masks don't line up with images | re-run the Step 2 Check |
Change **one thing at a time**. Each run gets its own `experiments/experiment_<timestamp>/` folder with a copy of its config, so you can compare runs in TensorBoard.
> **Model selection caveat:** the skeleton saves `best_model.pth` when *validation accuracy* improves ([train.py:617](train.py#L617)). If IoU or embedding metrics peak at a different epoch, you may want to change the selection score, for example `val_score = (correct/total + np.mean(iou1) + roc) / 3`.
---
## Step 7: Submit
1. Copy the best weights:
```bash
cp experiments/experiment_<timestamp>/models/fold_1/best_model.pth weights.pth
```
2. Check that they load **exactly the way the grader loads them** (on CPU, into a fresh model):
```python
import torch
from model import MyModel
m = MyModel(output_size=30)
m.load_state_dict(torch.load("weights.pth", map_location=torch.device("cpu")))
m.eval()
s, k, e = m(torch.randn(2, 3, 64, 64))
print(s.shape, k.shape, e.shape)
```
If you change the architecture *after* training, old weights will no longer load. Always retrain, then export.
3. Write `llm_declaration.txt`.
4. Zip `model.py`, `train.py`, `weights.pth` and `llm_declaration.txt`.
---
## Traps in the skeleton (read this!)
These are not marked with ‼️, but each one will stop you:
1. **No `.to(device)` anywhere in the training or validation loops.** On a GPU the model is on `cuda` while batches stay on `cpu`. The first `model(images)` fails with *"Expected all tensors to be on the same device"*. On a CPU-only machine it silently works, so the bug only shows up on the cluster. Fix: Step 5d / 5e.
2. **`dataset_size = 1969` is hardcoded** in `compute_embedding_bank`. If your dataset folder has a different number of images, the bank is too small (index error) or contains extra rows. Fix: Step 5f.
3. **`compute_seg_metrics` sometimes returns a plain `0` instead of a tensor.** It does this when a denominator is zero, typically early in training when the model predicts *no* fruit pixels. The validation loop then calls `p1.item()` on an `int` and crashes with `AttributeError: 'int' object has no attribute 'item'`. Fix: Step 5e (`float(p1)`).
4. **`MyModel(input_size=786432, hidden_size=128, ...)`** in `main()` ([train.py:691-693](train.py#L691-L693)) is left over from a fully-connected network. Your CNN's `__init__` must still *accept* these arguments, or it crashes. The README only mentions `output_size`.
5. **`compute_embedding_bank` leaves the model in `eval()` mode.** If `model.train()` sits only once before the epoch loop, BatchNorm and Dropout stay in evaluation mode for the entire training. Put it at the top of *every* epoch (Step 5c).
6. **Mask values.** The IoU code checks `== 1`. Masks stored as 0/255 give IoU 0 with no error. Fix: binarise in the Dataset (Step 2).
7. **`triplet margin=1.0` default** is large for cosine distance (range 0–2). Pass a smaller margin from the config.
8. **README says `data/`, config says `Data/`.** Make `data_dir` match wherever you actually unzipped the dataset.
---
## Glossary of the PyTorch calls used
You don't need to memorise these; this is a reference.
| Call | What it does |
|---|---|
| `torch.from_numpy(a)` | NumPy array → tensor |
| `t.permute(2, 0, 1)` | reorder axes: `[H,W,C]` → `[C,H,W]` |
| `t.unsqueeze(0)` | add a size-1 axis at position 0: `[H,W]` → `[1,H,W]` |
| `t.float()`, `torch.long` | change number type (floats for images/masks, integers for class labels) |
| `t.to(device)` | move to GPU/CPU |
| `t.mean(dim=(2,3))` | average over height and width → one number per channel |
| `torch.cat([a, b], dim=1)` | glue along the channel axis: `[B,256,..]` + `[B,128,..]` → `[B,384,..]` |
| `torch.stack(list)` | list of same-shape tensors → one tensor with a new first axis |
| `t.argmax(dim=1)` | index of the largest score per row → predicted class |
| `t.flip(-1)` | mirror along the last axis (width) |
| `t.item()` | one-element tensor → Python number |
| `F.normalize(t, dim=1)` | scale each row to length 1 |
| `F.cosine_similarity(a, b, dim=1)` | cosine of the angle between matching rows |
| `nn.Conv2d(in, out, 3, padding=1)` | `out` learnable 3×3 filters over `in` channels |
| `nn.BatchNorm2d(c)` | normalise each channel to ~mean 0, std 1 (learned rescale) |
| `nn.MaxPool2d(2)` | keep the max of each 2×2 block → halves H and W |
| `nn.Upsample(scale_factor=2)` | doubles H and W (smooth interpolation) |
| `nn.Linear(a, b)` | fully connected layer: `a` numbers in, `b` numbers out |
| `nn.Dropout(p)` | randomly zero a fraction `p` of values (training only) |
| `optimizer.zero_grad() / loss.backward() / optimizer.step()` | clear gradients / compute gradients / update weights |
| `model.train() / model.eval()` | switch Dropout + BatchNorm behaviour |
| `with torch.no_grad():` | don't track gradients (faster prediction) |