|
| 1 | +import argparse |
| 2 | + |
| 3 | +import OmegaConf |
| 4 | +import torch |
| 5 | + |
| 6 | +from diffusers import UNetLDMModel, VQModel, LatentDiffusionUncondPipeline, DDIMScheduler |
| 7 | + |
| 8 | +def convert_ldm_original(checkpoint_path, config_path, output_path): |
| 9 | + config = OmegaConf.load(config_path) |
| 10 | + state_dict = torch.load(checkpoint_path, map_location="cpu")["model"] |
| 11 | + keys = list(state_dict.keys()) |
| 12 | + |
| 13 | + # extract state_dict for VQVAE |
| 14 | + first_stage_dict = {} |
| 15 | + first_stage_key = "first_stage_model." |
| 16 | + for key in keys: |
| 17 | + if key.startswith(first_stage_key): |
| 18 | + first_stage_dict[key.replace(first_stage_key, "")] = state_dict[key] |
| 19 | + |
| 20 | + # extract state_dict for UNetLDM |
| 21 | + unet_state_dict = {} |
| 22 | + unet_key = "model.diffusion_model." |
| 23 | + for key in keys: |
| 24 | + if key.startswith(unet_key): |
| 25 | + unet_state_dict[key.replace(unet_key, "")] = state_dict[key] |
| 26 | + |
| 27 | + vqvae_init_args = config.model.params.first_stage_config.params |
| 28 | + unet_init_args = config.model.params.unet_config.params |
| 29 | + |
| 30 | + vqvae = VQModel(**vqvae_init_args).eval() |
| 31 | + vqvae.load_state_dict(first_stage_dict) |
| 32 | + |
| 33 | + unet = UNetLDMModel(**unet_init_args).eval() |
| 34 | + unet.load_state_dict(unet_state_dict) |
| 35 | + |
| 36 | + noise_scheduler = DDIMScheduler( |
| 37 | + timesteps=config.model.params.timesteps, |
| 38 | + beta_schedule="scaled_linear", |
| 39 | + beta_start=config.model.params.linear_start, |
| 40 | + beta_end=config.model.params.linear_end, |
| 41 | + clip_sample=False, |
| 42 | + ) |
| 43 | + |
| 44 | + pipeline = LatentDiffusionUncondPipeline(vqvae, unet, noise_scheduler) |
| 45 | + pipeline.save_pretrained(output_path) |
| 46 | + |
| 47 | + |
| 48 | +if __name__ == "__main__": |
| 49 | + parser = argparse.ArgumentParser() |
| 50 | + parser.add_argument("--checkpoint_path", type=str, required=True) |
| 51 | + parser.add_argument("--config_path", type=str, required=True) |
| 52 | + parser.add_argument("--output_path", type=str, required=True) |
| 53 | + args = parser.parse_args() |
| 54 | + |
| 55 | + convert_ldm_original(args.checkpoint_path, args.config_path, args.output_path) |
| 56 | + |
0 commit comments