Freezing layers in PyTorch is a technique used to keep certain parts of a neural network unchanged during training, often to speed up fine-tuning or to preserve learned features. This guide walks you through the process step by step, from identifying which layers to freeze to verifying that your gradients are correctly disabled. You’ll learn both the basic method and more advanced patterns for partial freezing, all with clear code examples you can adapt to your own models.
Ingredients
- 1 PyTorch model (e.g., a pre-trained ResNet or a custom nn.Module)
- 1 optimizer (e.g., torch.optim.SGD or Adam)
- 1 training loop (your existing code)
- 1 dataset (any, as long as it matches your model’s input)
- Optional: a learning rate scheduler
Instructions
- Identify the layers to freeze. Decide which parts of the model should stay fixed. For fine-tuning, this is often the backbone (e.g., all layers except the final classifier). Print your model’s architecture with
print(model)to see layer names. - Set requires_grad to False. Iterate over the parameters of the layers you want to freeze and set
param.requires_grad = False. For example, to freeze all layers except the last one:for name, param in model.named_parameters(): if 'fc' not in name: # 'fc' is the classifier layer in many models param.requires_grad = False - Create the optimizer. When you create your optimizer, pass only the parameters that have
requires_grad=True. This is crucial—otherwise the optimizer will still try to update frozen parameters (though they won’t change, it wastes memory).optimizer = torch.optim.Adam(filter(lambda p: p.requires_grad, model.parameters()), lr=0.001) - Run your training loop normally. The frozen layers will not be updated, and their gradients will be
None. The rest of the model trains as usual. - Verify freezing. After a few steps, check that the frozen parameters have not changed. You can do this by saving a copy before training and comparing after, or by checking that
param.grad is Nonefor frozen parameters. - Unfreeze later if needed. To unfreeze, set
param.requires_grad = Trueagain and re-create the optimizer with all parameters. This is common in two-stage fine-tuning: first train only the head, then unfreeze the backbone and continue with a lower learning rate.
Tips
- Use
model.eval()vsmodel.train()carefully. Freezing does not change the behavior of dropout or batch normalization. If you freeze a layer, it still runs in training mode unless you set the whole model to eval. For fine-tuning, you usually keep the model in train mode, but be aware that batch norm statistics will still update if the layer is frozen—consider settingmodel.eval()for the frozen part if that’s an issue. - Check for buffers. Some layers (like BatchNorm) have buffers (running_mean, running_var) that are not parameters. Freezing parameters does not freeze buffers. If you need to freeze those too, you must set
track_running_stats=Falseor handle them separately. - Common mistake: forgetting to filter optimizer. If you pass all parameters to the optimizer, it will compute gradients for frozen ones (which are None) and may cause errors or waste memory. Always filter.
- Use
torch.no_grad()for inference. When you’re not training, wrap your forward pass inwith torch.no_grad():to save memory and speed up computation, regardless of freezing.
Serving Suggestions
This technique is best served with a fine-tuning task, such as adapting a pre-trained image classifier to a new dataset with few samples. It also pairs well with transfer learning for NLP models like BERT, where you freeze the embedding layers and only train the classification head. For a complete meal, combine freezing with a low learning rate for the unfrozen layers and a higher one for the newly added layers.
Variations
- Layer-wise learning rates. Instead of freezing, assign different learning rates to different parameter groups. This gives more control and often works better than binary freezing.
- Gradual unfreezing. Start with all layers frozen except the head, then progressively unfreeze layers from the end to the beginning as training progresses.
- Freezing only certain types of layers. For example, freeze only convolutional layers but keep batch norm layers trainable. You can filter by layer type using
isinstance. - Use
requires_gradon tensors directly. If you have a custom layer, you can setrequires_gradon the tensor itself, but it’s easier to do it via the parameter.
Storage and Reheating
Freezing is not a physical process, but the effects persist as long as you keep requires_grad=False on the parameters. If you save and reload your model, the frozen state is not stored—you’ll need to re-apply the freezing after loading. The training loop itself can be stored as a script and reused. There’s no time limit; you can keep the model in a frozen state indefinitely, but remember to unfreeze when you want to train those layers again.
Frequently Asked Questions
Why do my frozen parameters still change?
This usually happens because you didn’t filter the optimizer. Even if requires_grad=False, the optimizer might still update if you passed the parameter. Double-check that you used filter(lambda p: p.requires_grad, model.parameters()).
Can I freeze a layer after some training?
Yes, you can set requires_grad=False at any point. The optimizer will stop updating it from that moment. However, if the optimizer has already accumulated state (like momentum), it’s safer to re-create the optimizer after freezing.
Does freezing speed up training?
It can, because you skip gradient computation for those layers. However, the forward pass still runs, so the speedup is limited. The main benefit is preventing overfitting and preserving learned features.
What about batch normalization?
Batch norm layers have both parameters (weight and bias) and buffers (running mean and variance). Freezing the parameters does not stop the buffers from updating. To freeze buffers, you need to set track_running_stats=False or put the model in eval mode.
How do I freeze only part of a layer?
You can’t freeze individual neurons easily, but you can freeze specific parameters by name. For example, to freeze only the weight of a linear layer but not the bias, filter by param.shape or name.
Is freezing the same as setting model.eval()?
No. model.eval() changes the behavior of dropout and batch norm, but does not affect gradient computation. Freezing is about requires_grad. You can do both independently.
Related
- Morrisons Stewing Beef: Easy Slow Cooker Recipe
- Lean Stewing Beef: How to Cook It So It’s Tender
- Mercury Freezing Point: How to Freeze It Safely
More recipes to cook
Safety notes: safe minimum internal temperatures from USDA FSIS; raw and undercooked fish guidance from the U.S. FDA. Food safety notes
Spotted an error? Tell us and we will correct it (corrections policy).