13import torch.nn as nn
14
15from labml import experiment, logger
16from labml.configs import option
17from labml_nn.experiments.cifar10 import CIFAR10Configs, CIFAR10VGGModel
18from labml_nn.normalization.batch_norm import BatchNorm
21class Configs(CIFAR10Configs):
28 pass
31class LargeModel(CIFAR10VGGModel):
创建卷积层和激活
38 def conv_block(self, in_channels, out_channels) -> nn.Module:
42 return nn.Sequential(
辍学
44 nn.Dropout(0.1),
卷积层
46 nn.Conv2d(in_channels, out_channels, kernel_size=3, padding=1),
批量标准化
48 BatchNorm(out_channels, track_running_stats=False),
激活 ReLU
50 nn.ReLU(inplace=True),
51 )
53 def __init__(self):
使用给定的卷积大小(通道)创建模型
55 super().__init__([[64, 64], [128, 128], [256, 256, 256], [512, 512, 512], [512, 512, 512]])
58@option(Configs.model)
59def _large_model(c: Configs):
63 return LargeModel().to(c.device)
66def main():
创建实验
68 experiment.create(name='cifar10', comment='large model')
创建配置
70 conf = Configs()
装载配置
72 experiment.configs(conf, {
73 'optimizer.optimizer': 'Adam',
74 'optimizer.learning_rate': 2.5e-4,
75 'is_save_models': True,
76 'epochs': 20,
77 })
设置保存/加载的模型
79 experiment.add_pytorch_models({'model': conf.model})
打印模型中参数的数量
81 logger.inspect(params=(sum(p.numel() for p in conf.model.parameters() if p.requires_grad)))
开始实验并运行训练循环
83 with experiment.start():
84 conf.run()
88if __name__ == '__main__':
89 main()