()
| 141 | |
| 142 | |
| 143 | def main(): |
| 144 | # initialize gen and disc, note: discriminator should be called critic, |
| 145 | # according to WGAN paper (since it no longer outputs between [0, 1]) |
| 146 | # but really who cares.. |
| 147 | #加载生成模型 |
| 148 | gen = Generator( |
| 149 | config.Z_DIM, config.W_DIM, config.IN_CHANNELS, img_channels=config.CHANNELS_IMG |
| 150 | ).to(config.DEVICE) |
| 151 | #加载判别模型 |
| 152 | critic = Discriminator( |
| 153 | config.IN_CHANNELS, img_channels=config.CHANNELS_IMG |
| 154 | ).to(config.DEVICE) |
| 155 | ema = EMA(gamma=0.999, save_frequency=2000) |
| 156 | # initialize optimizers and scalers for FP16 training |
| 157 | opt_gen = optim.Adam([{"params": [param for name, param in gen.named_parameters() if "map" not in name]}, |
| 158 | {"params": gen.map.parameters(), "lr": 1e-5}], lr=config.LEARNING_RATE, betas=(0.0, 0.99)) |
| 159 | opt_critic = optim.Adam( |
| 160 | critic.parameters(), lr=config.LEARNING_RATE, betas=(0.0, 0.99) |
| 161 | ) |
| 162 | scaler_critic = torch.cuda.amp.GradScaler() |
| 163 | scaler_gen = torch.cuda.amp.GradScaler() |
| 164 | |
| 165 | # for tensorboard plotting |
| 166 | writer = SummaryWriter(f"logs/gan") |
| 167 | |
| 168 | if config.LOAD_MODEL: |
| 169 | load_checkpoint( |
| 170 | config.CHECKPOINT_GEN, gen, opt_gen, config.LEARNING_RATE, |
| 171 | ) |
| 172 | load_checkpoint( |
| 173 | config.CHECKPOINT_CRITIC, critic, opt_critic, config.LEARNING_RATE, |
| 174 | ) |
| 175 | |
| 176 | gen.train() |
| 177 | critic.train() |
| 178 | |
| 179 | tensorboard_step = 0 |
| 180 | # start at step that corresponds to img size that we set in config |
| 181 | step = int(log2(config.START_TRAIN_AT_IMG_SIZE / 4)) #step => 5 |
| 182 | for num_epochs in config.PROGRESSIVE_EPOCHS[step:7]: |
| 183 | alpha = 1e-5 # start with very low alpha |
| 184 | #加载数据集 |
| 185 | loader, dataset = get_loader(4 * 2 ** step) # 4->0, 8->1, 16->2, 32->3, 64 -> 4 |
| 186 | print(f"Current image size: {4 * 2 ** step}") |
| 187 | |
| 188 | for epoch in range(num_epochs): |
| 189 | print(f"Epoch [{epoch+1}/{num_epochs}]") |
| 190 | tensorboard_step, alpha = train_fn( |
| 191 | critic, |
| 192 | gen, |
| 193 | loader, |
| 194 | dataset, |
| 195 | step, |
| 196 | alpha, |
| 197 | opt_critic, |
| 198 | opt_gen, |
| 199 | tensorboard_step, |
| 200 | writer, |
no test coverage detected