(args)
| 273 | |
| 274 | |
| 275 | def main(args): |
| 276 | logging_dir = os.path.join(args.output_dir, args.logging_dir) |
| 277 | accelerator_project_config = ProjectConfiguration(project_dir=args.output_dir, logging_dir=logging_dir) |
| 278 | |
| 279 | kwargs = InitProcessGroupKwargs(timeout=timedelta(seconds=7200)) # a big number for high resolution or big dataset |
| 280 | accelerator = Accelerator( |
| 281 | gradient_accumulation_steps=args.gradient_accumulation_steps, |
| 282 | mixed_precision=args.mixed_precision, |
| 283 | log_with=args.logger, |
| 284 | project_config=accelerator_project_config, |
| 285 | kwargs_handlers=[kwargs], |
| 286 | ) |
| 287 | |
| 288 | if args.logger == "tensorboard": |
| 289 | if not is_tensorboard_available(): |
| 290 | raise ImportError("Make sure to install tensorboard if you want to use it for logging during training.") |
| 291 | |
| 292 | elif args.logger == "wandb": |
| 293 | if not is_wandb_available(): |
| 294 | raise ImportError("Make sure to install wandb if you want to use it for logging during training.") |
| 295 | import wandb |
| 296 | |
| 297 | # `accelerate` 0.16.0 will have better support for customized saving |
| 298 | if version.parse(accelerate.__version__) >= version.parse("0.16.0"): |
| 299 | # create custom saving & loading hooks so that `accelerator.save_state(...)` serializes in a nice format |
| 300 | def save_model_hook(models, weights, output_dir): |
| 301 | if accelerator.is_main_process: |
| 302 | if args.use_ema: |
| 303 | ema_model.save_pretrained(os.path.join(output_dir, "unet_ema")) |
| 304 | |
| 305 | for i, model in enumerate(models): |
| 306 | model.save_pretrained(os.path.join(output_dir, "unet")) |
| 307 | |
| 308 | # make sure to pop weight so that corresponding model is not saved again |
| 309 | weights.pop() |
| 310 | |
| 311 | def load_model_hook(models, input_dir): |
| 312 | if args.use_ema: |
| 313 | load_model = EMAModel.from_pretrained(os.path.join(input_dir, "unet_ema"), UNet2DModel) |
| 314 | ema_model.load_state_dict(load_model.state_dict()) |
| 315 | ema_model.to(accelerator.device) |
| 316 | del load_model |
| 317 | |
| 318 | for i in range(len(models)): |
| 319 | # pop models so that they are not loaded again |
| 320 | model = models.pop() |
| 321 | |
| 322 | # load diffusers style into model |
| 323 | load_model = UNet2DModel.from_pretrained(input_dir, subfolder="unet") |
| 324 | model.register_to_config(**load_model.config) |
| 325 | |
| 326 | model.load_state_dict(load_model.state_dict()) |
| 327 | del load_model |
| 328 | |
| 329 | accelerator.register_save_state_pre_hook(save_model_hook) |
| 330 | accelerator.register_load_state_pre_hook(load_model_hook) |
| 331 | |
| 332 | # Make one log on every process with the configuration for debugging. |
no test coverage detected