Code Walkthrough

VIIRS Fine-tuning — Segmentation Head

Four-phase pipeline: extract frozen encoder–decoder features, check linear separability, train segmentation_head with focal loss, evaluate with PR/ROC curves. Entry: scripts/finetune_output_layer.py

euchmv/viirs_detections @ f8b56c3

VIIRS data / features on disk
MAnet model components
Loss computation & diagnostics
Saved outputs & metrics
CLI setup & constants
Setup CLI constants & four-subcommand pipeline ▶

Defines the four subcommands that form a sequential workflow: extract → check-separability → train → evaluate. Global constants fix the output directories and focal-loss hyperparameters used throughout.

L52FEATURES_DIR    = Path('output/features')
L53CHECKPOINTS_DIR = Path('output/checkpoints')
L55FOCAL_GAMMA = 2.0
L56FOCAL_ALPHA = 0.25

Source: scripts/finetune_output_layer.py:L50–L57

Branch --c14-substitute M15 | I5
Selects which VIIRS thermal band substitutes for ABI C14 (11.2 µm). M15 (10.76 µm) is the default; I5 (11.45 µm) is a closer spectral match but requires a separate IMG geolocation file. Both paths share identical code — they differ only in which pre-computed normalization stats file is loaded and which output subdirectory (output/features/M15/ vs output/features/I5/) is written to. This walkthrough follows both paths in parallel.
M15 · 10.76 µm
Norm Load M15 normalization stats ▶

Loads per-channel mean and std from a pre-computed .npz file. The three stats correspond to the three input channels: M14 (≈ ABI C11), M15 used for both C13 and C14, and the brightness temperature difference BTD M15−M16 (≈ ABI BTD C13−C15).

L66means = [float(stats['M14_mean']), float(stats['M15_mean']), float(stats['BTD_M15_M16_mean'])]
L67stds  = [float(stats['M14_std']),  float(stats['M15_std']),  float(stats['BTD_M15_M16_std'])]
Readsnorm_stats_path('M15') .npz file Returnsmeans, stds — each a list of 3 floats

Source: scripts/finetune_output_layer.py:L61–L68

I5 · 11.45 µm
Norm Load I5 normalization stats ▶

Same structure as the M15 path, but reads from the I5 stats file. The C14 slot is populated with I5 statistics instead of M15 statistics; the BTD channels (M15, M16) remain unchanged.

L66means = [float(stats['M14_mean']), float(stats['I5_mean']), float(stats['BTD_M15_M16_mean'])]
L67stds  = [float(stats['M14_std']),  float(stats['I5_std']),  float(stats['BTD_M15_M16_std'])]
Readsnorm_stats_path('I5') .npz file Returnsmeans, stds — each a list of 3 floats

Source: scripts/finetune_output_layer.py:L61–L68

means, stds → (3,)
Extract Load MAnet; run frozen encoder+decoder on each train scene ▶

Loads marvelous-moth-137 — an smp.MAnet with a ResNet-18 encoder (pretrained on ImageNet), 5 encoder stages, and decoder channels [256, 128, 64, 32, 16]. Each training scene is processed in a worker pool (worker count = os.sched_getaffinity(0), respecting SLURM limits). The encoder and decoder run under torch.no_grad(); the segmentation head is never called here.

Each scene's three input channels are z-score normalized, padded to the nearest multiple of 32, then forwarded through encoder and decoder only. Padding is stripped before saving.

$$ \tilde{x}_c = \frac{x_c - \mu_c}{\sigma_c}, \quad c \in \{\text{C11},\,\text{C14},\,\text{BTD}\} $$
L41array[0, 0] = (ds.CMI_C11.values - means[0]) / stds[0]
L42array[0, 1] = (ds.CMI_C14.values - means[1]) / stds[1]
L43array[0, 2] = ((ds.CMI_C13 - ds.CMI_C15).values - means[2]) / stds[2]
L53with torch.no_grad():
L54    enc_out = model.encoder(tensor)
L58    features = model.decoder(*enc_out)  # (1, C, H_pad, W_pad)

Model architecture defined in model_utils.py:

L18_MARVELOUS_MOTH_ARCH = dict(
L19    encoder_name='resnet18',
L20    encoder_weights='imagenet',
L21    in_channels=3,
L22    classes=2,
L23    encoder_depth=5,
L24    decoder_channels=[256, 128, 64, 32, 16],
L25)
ReadsVIIRS L1B xr.Dataset, means, stds Writesfeat — ndarray (16, H, W) float32 decoder feature maps

Source: viirs_detection/feature_extractor.py:L9–L61  ·  viirs_detection/model_utils.py:L18–L57  ·  scripts/finetune_output_layer.py:L72–L101

Save Save (16, H, W) feature maps and rasterized label masks to disk ▶

Feature maps and label masks are written as .npy files, one pair per training scene. Labels are rasterized from a GeoDataFrame of polygon annotations onto the swath pixel grid — pixel value = contrail ID (integer ≥ 1) for labeled contrails, 0 for background. Saving features once avoids re-running the frozen encoder+decoder on every training epoch.

L99np.save(out_dir / f'features_scene{scene_id:02d}.npy', feat)
L100np.save(out_dir / f'labels_scene{scene_id:02d}.npy', label)
Readsfeat (16, H, W), label_gdf, lat, lon Writesoutput/features/{M15|I5}/features_sceneXX.npy, labels_sceneXX.npy

Source: scripts/finetune_output_layer.py:L96–L101

features (16, H, W) · labels (H, W)
Check Optional: PCA + logistic regression to verify linear separability ▶

Runs before committing to training. Loads saved feature maps, reshapes each scene to (H×W, 16) pixel vectors, and splits by label > 0 (contrail) vs. background. Up to 50,000 pixels per class are sampled (seeded RNG for reproducibility). If the frozen decoder features are already linearly separable in this 16-dimensional space, training only the segmentation head — which is effectively a linear classifier — is sufficient.

L204pca = PCA(n_components=min(16, X.shape[1]))
L205pca.fit(X)
L206evr = pca.explained_variance_ratio_
L210lr     = LogisticRegression(max_iter=500, C=1.0)
L211scores = cross_val_score(lr, X, y, cv=5, scoring='roc_auc')

Reported at the CLI (source L213): ">0.8 suggests head-only fine-tuning is viable"

Readsfeatures_sceneXX.npy, labels_sceneXX.npy Writesstdout only — PCA variance ratios + 5-fold ROC-AUC

Source: scripts/finetune_output_layer.py:L161–L215

AUC > 0.8 → proceed
Dataset Build PatchDataset: scan scenes, keep only contrail-positive patches ▶

Loads all training scene .npy pairs from FEATURES_DIR / c14_substitute. PatchDataset pre-scans every valid (top, left) patch position at construction time using a stride of 512 px on 1024 px patches. Only positions where the label mask contains at least 50 contrail pixels are retained — this filters out background-only patches and keeps __len__ exact before any epoch begins.

L60    n_contrail = int(np.sum(
L61        label[top:top + patch_size, left:left + patch_size] > 0
L62    ))
L63    if n_contrail >= min_contrail_pixels:
L64        self.patches.append((scene_idx, top, left))

__getitem__ returns the feature patch as a tensor and a binarized label tensor ((label > 0).astype(int64), so all contrail IDs collapse to 1). Wrapped in DataLoader(batch_size=4, shuffle=True, num_workers=0).

Readsfeatures_sceneXX.npy, labels_sceneXX.npy Writesself.patches list of (scene_idx, top, left) tuples (in-memory)

Source: viirs_detection/patch_dataset.py:L6–L79  ·  scripts/finetune_output_layer.py:L241–L261

Freeze Freeze entire network; unfreeze segmentation_head; keep model.eval() ▶

All parameters in the MAnet are frozen first; then segmentation_head parameters are selectively unfrozen. The model is kept in eval() mode for the entire training run — this is intentional: it prevents the frozen encoder's BatchNorm layers from accumulating VIIRS-domain batch statistics, which would corrupt the pretrained ImageNet running means and variances.

L266for param in model.parameters():
L267    param.requires_grad = False
L268for param in model.segmentation_head.parameters():
L269    param.requires_grad = True
L271# Keep model in eval mode so frozen BatchNorm layers use running stats
L272model.eval()
L274optimizer = torch.optim.Adam(model.segmentation_head.parameters(), lr=lr)

Adam is constructed on segmentation_head.parameters() only (default lr=1e-3). The segmentation head is a single Conv2d(16 → 2, kernel_size=1) mapping the 16 decoder features per pixel to 2 class logits.

Readsfull MAnet (all parameters) Writesrequires_grad flags on all parameters; optimizer state

Source: scripts/finetune_output_layer.py:L263–L274

Epoch loop for epoch in range(1, epochs + 1)
epochs=20 (default) · batch_size=4 · lr=1e-3 · no early stopping
Focal Forward through segmentation_head; compute focal loss ▶

Each mini-batch of pre-extracted features (B, 16, 1024, 1024) is passed directly into model.segmentation_head, which produces logits of shape (B, 2, 1024, 1024) — one score per class per pixel. Focal loss down-weights easy, well-classified pixels (background dominates by count) and focuses gradient on uncertain ones.

$$ \mathcal{L}_\text{focal} = \frac{1}{N}\sum_i \alpha\,(1 - p_{t,i})^\gamma \cdot \text{CE}_i $$

where $p_{t,i} = e^{-\text{CE}_i}$,   $\alpha = 0.25$,   $\gamma = 2$

L106ce = F.cross_entropy(logits, targets, reduction='none')
L107pt = torch.exp(-ce)
L108return (FOCAL_ALPHA * (1 - pt) ** FOCAL_GAMMA * ce).mean()
L295logits = model.segmentation_head(feat_batch)
L296loss   = _focal_loss(logits, label_batch)
Readsfeat_batch (B, 16, 1024, 1024), label_batch (B, 1024, 1024) Writesloss — scalar tensor

Source: scripts/finetune_output_layer.py:L104–L108  ·  scripts/finetune_output_layer.py:L289–L301

Ckpt Adam step; log epoch loss; save state_dict if new best ▶

Each batch: optimizer.zero_grad() → loss.backward() → optimizer.step(). After all batches in the epoch, the average loss is computed and compared to the running best. If improved, the full model state_dict is saved. Loss is also appended to a CSV log for inspection after training.

L305avg_loss = total_loss / max(n_batches, 1)
L310if avg_loss < best_loss:
L311    best_loss = avg_loss
L312    torch.save(model.state_dict(), ckpt_path)
Readsloss scalar, best_loss Writesoutput/checkpoints/marvelous-moth-137_finetuned_{c14}_best.pt, training_log_{c14}.csv

Source: scripts/finetune_output_layer.py:L298–L317

Convergence avg_loss < best_loss ?
Yes → overwrite best checkpoint with current model.state_dict(), continue to next epoch.
No → skip checkpoint write, continue to next epoch.
Loop exits when epoch == epochs. There is no early stopping; all epochs run.
↩ if epoch < epochs, restart from forward-loss node above
best checkpoint
Eval Load best checkpoint; run full end-to-end inference on val scenes ▶

Loads the best checkpoint into a fresh model instance and sets model.eval(). For each validation scene, the full pipeline runs end-to-end from raw L1B data: band mapping, normalization, padding, full MAnet forward pass (encoder + decoder + segmentation head), softmax, and unpadding. This returns a raw probability map in [0, 1] per pixel; no threshold is applied here so the caller can sweep thresholds independently.

L341model.load_state_dict(torch.load(str(ckpt_path), map_location=device, weights_only=True))
L342model.eval()
L133probs = nn.functional.softmax(model(pad(torch.Tensor(array))), dim=1)
L136result = probs.cpu().numpy()[0, 1, hedge:-hedge, wedge:-wedge]

dim=1 = class axis (2 classes). Channel 1 = contrail probability. See the sidebar callout below for the softmax derivation.

Readsbest .pt checkpoint, val L1B files, means, stds Writesprob_map (H, W) in [0, 1] per val scene (in-memory)

Source: scripts/finetune_output_layer.py:L339–L370  ·  viirs_detection/viirs_adapter.py:L94–L144

prob_map (H, W) ∈ [0, 1]
Metrics PR/ROC curves and per-contrail threshold sweep; write metrics JSON ▶

Concatenates probability maps and binary labels from all validation scenes. Computes pixel-level precision-recall and ROC curves via sklearn, then runs a per-contrail threshold sweep: for each labeled contrail polygon (identified by ID k), it measures what fraction of that contrail's pixels exceed each of 20 evenly-spaced thresholds from 0.05 to 0.95. This is more informative than pixel-level metrics alone — a contrail can be partially or fully detected.

L375precision_arr, recall_arr, pr_thresholds = precision_recall_curve(labels, probs)
L376pr_auc  = float(auc(recall_arr, precision_arr))
L377fpr_arr, tpr_arr, _ = roc_curve(labels, probs)
L369    scene_rates.append([float(np.mean(px >= t)) for t in thresholds])
Readsprob_map + label_mask per val scene Writesoutput/checkpoints/val_metrics_{c14}.json — precision, recall, PR-AUC, FPR, TPR, per-contrail detection rates

Source: scripts/finetune_output_layer.py:L375–L408