PythiloLesson 3 of 8 · progress kept in this browser

Freeze parameters and running statistics separately

Setting requires_grad to false freezes parameter gradients, but a normalization layer can still update running statistics in training mode. Calling train on the enclosing model recursively changes its children, so the backbone must be placed back in evaluation mode after the global mode change.

This exercise uses a real BatchNorm layer and verifies that a forward pass leaves its running mean unchanged. The new head stays trainable. Fine-tuning policies should separately state which parameters receive gradients, which modules update state and which stochastic layers remain active. One flag does not express all three choices.

import torch
from torch import nn
body=nn.BatchNorm1d(2)
body.eval()
before=body.running_mean.clone()
body(torch.tensor([[1.,2.],[3.,4.]]))
print(torch.equal(before,body.running_mean))
This example uses torch. Run it in the Pythilo app, where these features are available.
Your task

Implement prepare_finetune(model,backbone). Set model.train(), disable gradients for every backbone parameter, then backbone.eval(). Return the list of model parameters still requiring gradients.

This lesson uses torch, which Python in this browser does not include. Read it here, and run and check it in the Pythilo app on iPhone or iPad.