22  Additional Material: Transfer Learning and U-Net Experiments

A controlled adaptation study beyond the core lab

22.1 Optional adaptation study

The theory chapter explained U-Net and encoder transfer; the transfer learning and U-Net lab compared architectures and previewed adaptation. Here we hold the U-Net architecture fixed and study which learned weights initialize it and which parameters can update. This optional sheet extends the core lab with additional controls and runs independently from top to bottom. All prerequisite theory is explained in the concepts chapter.

The teaching question is: with only 16 labeled target fields, can an encoder trained on a related source task help? We actually train the source model, copy its encoder weights, and compare adaptation regimes. The source images are cleaner synthetic microscopy fields; the target images have weaker, variable contrast and more noise. Both tasks use the same foreground definition. This is a controlled synthetic domain change, not evidence about transferring to real microscopy.

Predict first. Rank scratch training, a frozen pretrained encoder, and full fine-tuning under a short target update budget. Would you expect freezing a randomly initialized encoder to be equivalent to transfer? What extra resource does pretraining consume?

22.2 1. Separate source, target training, validation, and test

from copy import deepcopy
import matplotlib.pyplot as plt
import torch

from dlbook.segmentation import TinyUNet, evaluate, fit, make_microscopy

torch.set_num_threads(1)
source_x, source_y = make_microscopy(96, seed=610, domain="source")
target_x, target_y = make_microscopy(16, seed=601, domain="target")
valid_x, valid_y = make_microscopy(24, seed=602, domain="target")
# These are exactly the first 16 target-training fields from the segmentation lab.
# No target validation or test field is used for source training.
assert source_x.shape[0] == 96 and target_x.shape[0] == 16
fig, axes = plt.subplots(1, 4, figsize=(10, 3))
for ax, panel, title in zip(axes, (source_x[0, 0], source_y[0, 0], target_x[0, 0], target_y[0, 0]),
                           ("Source image", "Source mask", "Target image", "Target mask")):
    ax.imshow(panel, cmap="gray", vmin=0, vmax=1)
    ax.set_title(title)
    ax.axis("off")
fig.tight_layout()
plt.show()
Source image and reference mask beside a target image and reference mask. The target image is noisier and its foreground contrast varies.
Figure 22.1: Separate synthetic source and target fields, shown before training. Source fields have cleaner contrast; target fields have variable contrast and greater noise. Both use disk-union semantic labels.

Independent generator streams play the role of separated sampling units. For real images, source/target separation requires checking patient identity, near duplicates, collection overlap, and the provenance of pretrained weights. A different filename or tile coordinate is not sufficient evidence of an independent case.

22.3 2. Learn source weights before calling anything “pretrained”

Use the same small U-Net and segmentation objective as before. Fit on the 96 source fields for 160 updates. Save the encoder state in memory. We transfer neither the source decoder nor optimizer state.

torch.manual_seed(71)
source_model = TinyUNet()
source_history = fit(source_model, source_x, source_y, steps=160, seed=72)
encoder_state = deepcopy(source_model.encoder.state_dict())
print("Source training diagnostic (not held-out performance):", evaluate(source_model, source_x, source_y))
Source training diagnostic (not held-out performance): {'dice': 0.9538483619689941, 'iou': 0.9120893478393555, 'pixel_accuracy': 0.9894793629646301, 'loss': 0.08449184149503708}

The source diagnostic only checks that the pretraining procedure learned something on its own training set. It is not a source generalization estimate. The source budget was specified in advance, rather than selected using target test results.

The provenance of this temporary checkpoint is explicit: generator version, source seed 610, 96 labeled fields, model seed 71, batch seed 72, 160 Adam updates, batch size 8, learning rate 0.003, and BCE plus soft Dice. The accompanying model-manifests/synthetic-unet-encoder.yml records this recipe. No external pretrained weights are downloaded.

22.4 3. Try freezing: decide what that phrase means

Regime Encoder initialization Encoder updates? Decoder initialization and updates
Scratch Random All encoder blocks Fresh random decoder, train all
Random-frozen control Random None Same fresh decoder, train all
Frozen transfer Learned source weights None Same fresh decoder, train all
Partial fine-tuning Learned source weights Bottleneck block only Same fresh decoder, train all
Full fine-tuning Learned source weights All encoder blocks Same fresh decoder, train all

Feature extraction keeps the encoder fixed and learns a downstream model. Our frozen regime learns a nonlinear multiscale decoder, so it is feature extraction but not a linear probe. A strict linear probe would keep the representation fixed and fit only a linear prediction head, such as a \(1\times1\) convolution on one feature map. Partial unfreezing adapts selected encoder blocks. Full fine-tuning allows all encoder weights to adapt.

Here is the complete mechanism. Resetting the seed before construction gives every regime the same initial decoder. Loading a state dictionary supplies learned encoder weights; setting requires_grad controls future updates. These are distinct operations.

def transfer_model(source_encoder_state, regime, seed=70):
    """Same fresh decoder seed in all regimes; only named transfer modes load weights."""
    if regime not in {"scratch", "random-frozen", "frozen", "partial", "full"}:
        raise ValueError("unknown transfer regime")
    torch.manual_seed(seed)
    model = TinyUNet()
    if regime in {"frozen", "partial", "full"}:
        model.encoder.load_state_dict(deepcopy(source_encoder_state))
    if regime in {"frozen", "random-frozen", "partial"}:
        for parameter in model.encoder.parameters():
            parameter.requires_grad_(False)
    if regime == "partial":
        for parameter in model.encoder.bottom.parameters():
            parameter.requires_grad_(True)
    return model

frozen_probe = transfer_model(encoder_state, "frozen")
for name, value in frozen_probe.encoder.state_dict().items():
    torch.testing.assert_close(value, encoder_state[name], rtol=0, atol=0)
assert all(not p.requires_grad for p in frozen_probe.encoder.parameters())
assert all(p.requires_grad for p in frozen_probe.decode1.parameters())

The training helper builds a new optimizer after the flags are set, using only trainable parameters. If you unfreeze later, add the parameters to the optimizer or rebuild it deliberately. Otherwise, a parameter can receive a gradient and still never be updated.

Our tiny model has no BatchNorm or dropout. In larger pretrained models, freezing gradients does not by itself freeze BatchNorm running statistics, and eval() does not by itself disable gradients. Declare the intended training/evaluation modes as well as trainability when transferring those models.

22.5 4. Compare the adaptation ladder under fixed target resources

Every regime sees the same 16 target labels and the same minibatch stream. All receive 80 target updates, with the same loss, batch size, learning rate, and threshold. Parameter counts and work per update differ. Transfer also consumes 96 additional source labels and 160 source updates, which must be reported separately; this is not a matched-total-compute comparison.

regimes = ("scratch", "random-frozen", "frozen", "partial", "full")
models, results = {}, {}
for regime in regimes:
    model = transfer_model(encoder_state, regime, seed=70)
    before = {name: value.clone() for name, value in model.encoder.state_dict().items()}
    fit(model, target_x, target_y, steps=80, seed=73)
    if regime in ("frozen", "random-frozen"):
        for name, value in model.encoder.state_dict().items():
            torch.testing.assert_close(value, before[name], rtol=0, atol=0)
    if regime == "partial":
        for name, value in model.encoder.state_dict().items():
            if not name.startswith("bottom."):
                torch.testing.assert_close(value, before[name], rtol=0, atol=0)
    metrics = evaluate(model, valid_x, valid_y)
    trainable = sum(p.numel() for p in model.parameters() if p.requires_grad)
    results[regime] = {**metrics, "trainable_parameters": trainable}
    models[regime] = model
    print(regime, {key: round(value, 4) for key, value in results[regime].items()})
scratch {'dice': 0.223, 'iou': 0.1259, 'pixel_accuracy': 0.9101, 'loss': 0.5738, 'trainable_parameters': 7465}
random-frozen {'dice': 0.8109, 'iou': 0.6873, 'pixel_accuracy': 0.9655, 'loss': 0.3847, 'trainable_parameters': 2909}
frozen {'dice': 0.2766, 'iou': 0.1623, 'pixel_accuracy': 0.9132, 'loss': 0.6066, 'trainable_parameters': 2909}
partial {'dice': 0.8006, 'iou': 0.6716, 'pixel_accuracy': 0.9622, 'loss': 0.3515, 'trainable_parameters': 6397}
full {'dice': 0.6548, 'iou': 0.4898, 'pixel_accuracy': 0.9431, 'loss': 0.4287, 'trainable_parameters': 7465}
fig, ax = plt.subplots(figsize=(8, 4))
values = [results[regime]["dice"] for regime in regimes]
bars = ax.bar(regimes, values, color=["#8296a8", "#bac6d0", "#dba75b", "#659b9a", "#386c87"])
ax.bar_label(bars, fmt="%.3f", padding=3)
ax.set(ylabel="validation mean foreground Dice", ylim=(0, 1))
fig.tight_layout()
plt.show()
Bar chart of validation mean foreground Dice for scratch, random-frozen, frozen pretrained, partially fine-tuned, and fully fine-tuned encoders under the same target update budget.
Figure 22.2: Five regimes with the same architecture, target labels, initial decoder, and target-update budget. Source pretraining is additional work. The random-frozen control tests whether freezing alone explains a result. A single initialization is shown.

Pause before explaining. In the documented run, full fine-tuning performs best among the candidate training regimes. Frozen transfer is weaker than the random-frozen control under this particular short budget. This is a useful failure, not a result to hide: source training does not guarantee that a frozen representation and a newly initialized decoder will adapt well.

Do not attribute this ordering to a specific mechanism without another experiment. Possible influences include source/target mismatch, different feature scales, decoder adaptation, and finite-budget optimization. The result does not prove that pretrained features are intrinsically worse. Likewise, full fine-tuning’s advantage over scratch does not establish an advantage at equal total data or compute.

22.6 5. Improve based on an explicit diagnosis

Choose one follow-up investigation and preregister it before rerunning:

  • Optimization-budget hypothesis: double the target update budget for every regime, keeping everything else fixed. Does frozen transfer catch up?
  • Domain-mismatch hypothesis: add an explicit noise-standard-deviation argument to the generator and change only that value, keeping the domain, seeds, source checkpoint, and geometry-generation code fixed. Verify that target masks remain identical.
  • Unfreezing hypothesis: compare frozen transfer with bottleneck-only adaptation under the same target budget. Which layers are allowed to change?
  • Data-budget hypothesis: compare 8 and 16 target-training fields, always taking a fixed prefix of the same training stream and evaluating on the same validation stream.

For multiple initialization repeats, use fresh model seeds and apply each seed to every regime. Do not present the variation across these seeds as uncertainty across patients or datasets. Keep the source checkpoint fixed if the question concerns target-stage randomness; repeat source pretraining separately if that is the variable of interest.

22.6.1 Differential learning rates — implementation depth

A common adaptation choice is a smaller learning rate for pretrained weights than for a fresh decoder. It changes the optimization protocol and should be evaluated as a separate experiment. The parameter groups must not overlap:

example = transfer_model(encoder_state, "full", seed=70)
encoder_parameters = list(example.encoder.parameters())
decoder_parameters = [p for name, p in example.named_parameters() if not name.startswith("encoder.")]
assert {id(p) for p in encoder_parameters}.isdisjoint(id(p) for p in decoder_parameters)
assert len(encoder_parameters) + len(decoder_parameters) == len(list(example.parameters()))
optimizer = torch.optim.Adam([
    {"params": encoder_parameters, "lr": 0.0003},
    {"params": decoder_parameters, "lr": 0.003},
])
# This example defines groups; it is not substituted into the comparison above.

22.7 Final evaluation after choosing a regime

Predeclare selection by validation mean foreground Dice among scratch, frozen transfer, partial fine-tuning, and full fine-tuning. The random-frozen model is a diagnostic control. Freeze the selected model and its threshold at 0.5. This notebook uses its own reserved target test stream, seed 613, separate from the lab’s seed 603.

candidates = ("scratch", "frozen", "partial", "full")
selected = max(candidates, key=lambda name: results[name]["dice"])
test_x, test_y = make_microscopy(24, seed=613, domain="target")
print("Validation-selected regime:", selected)
print("One final target test assessment:", evaluate(models[selected], test_x, test_y))
Validation-selected regime: partial
One final target test assessment: {'dice': 0.8141729235649109, 'iou': 0.6899517178535461, 'pixel_accuracy': 0.9599428772926331, 'loss': 0.3386611342430115}

The selected result remains a small same-generator study. It cannot establish clinical robustness, patient-level generalization, or a general ranking of transfer strategies. For a real-data project, define source provenance, the patient/specimen split, mask policy, preprocessing, label budget, tuning budget, and external evaluation before training.

22.8 Knowledge check and report

  1. Why is a frozen random encoder not a pretrained encoder?
  2. Why is our frozen decoder experiment not a linear probe?
  3. Which weights change in the partial regime? Which do not?
  4. Why can requires_grad=False and eval() solve different problems?
  5. Which resource is controlled by equal target updates, and which resource is added by pretraining?
  6. What observation would support further unfreezing rather than merely more decoder updates?

Report the full table, including the random-frozen control and the poor frozen-transfer result if reproduced. State your follow-up hypothesis and conclude only what that controlled comparison supports. The first version’s purpose is to establish a correct adaptation workflow and a testable explanation, not to prescribe one universally best regime.