Path: blob/master/labml_nn/distillation/small.py
4918 views
"""1---2title: Train a small model on CIFAR 103summary: >4Train a small model on CIFAR 10 to test how much distillation benefits.5---67# Train a small model on CIFAR 1089This trains a small model on CIFAR 10 to test how much [distillation](index.html) benefits.10"""1112import torch.nn as nn1314from labml import experiment, logger15from labml.configs import option16from labml_nn.experiments.cifar10 import CIFAR10Configs, CIFAR10VGGModel17from labml_nn.normalization.batch_norm import BatchNorm181920class Configs(CIFAR10Configs):21"""22## Configurations2324We use [`CIFAR10Configs`](../experiments/cifar10.html) which defines all the25dataset related configurations, optimizer, and a training loop.26"""27pass282930class SmallModel(CIFAR10VGGModel):31"""32### VGG style model for CIFAR-10 classification3334This derives from the [generic VGG style architecture](../experiments/cifar10.html).35"""3637def conv_block(self, in_channels, out_channels) -> nn.Module:38"""39Create a convolution layer and the activations40"""41return nn.Sequential(42# Convolution layer43nn.Conv2d(in_channels, out_channels, kernel_size=3, padding=1),44# Batch normalization45BatchNorm(out_channels, track_running_stats=False),46# ReLU activation47nn.ReLU(inplace=True),48)4950def __init__(self):51# Create a model with given convolution sizes (channels)52super().__init__([[32, 32], [64, 64], [128], [128], [128]])535455@option(Configs.model)56def _small_model(c: Configs):57"""58### Create model59"""60return SmallModel().to(c.device)616263def main():64# Create experiment65experiment.create(name='cifar10', comment='small model')66# Create configurations67conf = Configs()68# Load configurations69experiment.configs(conf, {70'optimizer.optimizer': 'Adam',71'optimizer.learning_rate': 2.5e-4,72})73# Set model for saving/loading74experiment.add_pytorch_models({'model': conf.model})75# Print number of parameters in the model76logger.inspect(params=(sum(p.numel() for p in conf.model.parameters() if p.requires_grad)))77# Start the experiment and run the training loop78with experiment.start():79conf.run()808182#83if __name__ == '__main__':84main()858687