|
| 1 | +""" |
| 2 | +Convert a CogView3 checkpoint to the Diffusers format. |
| 3 | +
|
| 4 | +This script converts a CogView3 checkpoint to the Diffusers format, which can then be used |
| 5 | +with the Diffusers library. |
| 6 | +
|
| 7 | +Example usage: |
| 8 | + python scripts/convert_cogview3_to_diffusers.py \ |
| 9 | + --original_state_dict_repo_id "THUDM/cogview3" \ |
| 10 | + --filename "cogview3.pt" \ |
| 11 | + --transformer \ |
| 12 | + --output_path "./cogview3_diffusers" \ |
| 13 | + --dtype "bf16" |
| 14 | +
|
| 15 | +Alternatively, if you have a local checkpoint: |
| 16 | + python scripts/convert_cogview3_to_diffusers.py \ |
| 17 | + --checkpoint_path '/raid/.cache/huggingface/models--ZP2HF--CogView3-SAT/snapshots/ca86ce9ba94f9a7f2dd109e7a59e4c8ad04121be/cogview3plus_3b/1/mp_rank_00_model_states.pt' \ |
| 18 | + --transformer \ |
| 19 | + --output_path "/raid/yiyi/cogview3_diffusers" \ |
| 20 | + --dtype "bf16" |
| 21 | +
|
| 22 | +Arguments: |
| 23 | + --original_state_dict_repo_id: The Hugging Face repo ID containing the original checkpoint. |
| 24 | + --filename: The filename of the checkpoint in the repo (default: "flux.safetensors"). |
| 25 | + --checkpoint_path: Path to a local checkpoint file (alternative to repo_id and filename). |
| 26 | + --transformer: Flag to convert the transformer model. |
| 27 | + --output_path: The path to save the converted model. |
| 28 | + --dtype: The dtype to save the model in (default: "bf16", options: "fp16", "bf16", "fp32"). |
| 29 | +
|
| 30 | +Note: You must provide either --original_state_dict_repo_id or --checkpoint_path. |
| 31 | +""" |
| 32 | + |
| 33 | +import argparse |
| 34 | +from contextlib import nullcontext |
| 35 | + |
| 36 | +import torch |
| 37 | +from accelerate import init_empty_weights |
| 38 | +from huggingface_hub import hf_hub_download |
| 39 | + |
| 40 | +from diffusers import CogView3PlusTransformer2DModel |
| 41 | +from diffusers.utils.import_utils import is_accelerate_available |
| 42 | + |
| 43 | + |
| 44 | +CTX = init_empty_weights if is_accelerate_available else nullcontext |
| 45 | + |
| 46 | +parser = argparse.ArgumentParser() |
| 47 | +parser.add_argument("--original_state_dict_repo_id", default=None, type=str) |
| 48 | +parser.add_argument("--filename", default="flux.safetensors", type=str) |
| 49 | +parser.add_argument("--checkpoint_path", default=None, type=str) |
| 50 | +parser.add_argument("--transformer", action="store_true") |
| 51 | +parser.add_argument("--output_path", type=str) |
| 52 | +parser.add_argument("--dtype", type=str, default="bf16") |
| 53 | + |
| 54 | +args = parser.parse_args() |
| 55 | + |
| 56 | + |
| 57 | +def load_original_checkpoint(args): |
| 58 | + if args.original_state_dict_repo_id is not None: |
| 59 | + ckpt_path = hf_hub_download(repo_id=args.original_state_dict_repo_id, filename=args.filename) |
| 60 | + elif args.checkpoint_path is not None: |
| 61 | + ckpt_path = args.checkpoint_path |
| 62 | + else: |
| 63 | + raise ValueError("Please provide either `original_state_dict_repo_id` or a local `checkpoint_path`") |
| 64 | + |
| 65 | + original_state_dict = torch.load(ckpt_path, map_location="cpu") |
| 66 | + return original_state_dict |
| 67 | + |
| 68 | + |
| 69 | +# this is specific to `AdaLayerNormContinuous`: |
| 70 | +# diffusers imnplementation split the linear projection into the scale, shift while CogView3 split it tino shift, scale |
| 71 | +def swap_scale_shift(weight, dim): |
| 72 | + shift, scale = weight.chunk(2, dim=0) |
| 73 | + new_weight = torch.cat([scale, shift], dim=0) |
| 74 | + return new_weight |
| 75 | + |
| 76 | + |
| 77 | +def convert_cogview3_transformer_checkpoint_to_diffusers(original_state_dict): |
| 78 | + new_state_dict = {} |
| 79 | + |
| 80 | + # Convert pos_embed |
| 81 | + new_state_dict["pos_embed.proj.weight"] = original_state_dict.pop("mixins.patch_embed.proj.weight") |
| 82 | + new_state_dict["pos_embed.proj.bias"] = original_state_dict.pop("mixins.patch_embed.proj.bias") |
| 83 | + new_state_dict["pos_embed.text_proj.weight"] = original_state_dict.pop("mixins.patch_embed.text_proj.weight") |
| 84 | + new_state_dict["pos_embed.text_proj.bias"] = original_state_dict.pop("mixins.patch_embed.text_proj.bias") |
| 85 | + |
| 86 | + # Convert time_text_embed |
| 87 | + new_state_dict["time_text_embed.timestep_embedder.linear_1.weight"] = original_state_dict.pop( |
| 88 | + "time_embed.0.weight" |
| 89 | + ) |
| 90 | + new_state_dict["time_text_embed.timestep_embedder.linear_1.bias"] = original_state_dict.pop("time_embed.0.bias") |
| 91 | + new_state_dict["time_text_embed.timestep_embedder.linear_2.weight"] = original_state_dict.pop( |
| 92 | + "time_embed.2.weight" |
| 93 | + ) |
| 94 | + new_state_dict["time_text_embed.timestep_embedder.linear_2.bias"] = original_state_dict.pop("time_embed.2.bias") |
| 95 | + new_state_dict["time_text_embed.text_embedder.linear_1.weight"] = original_state_dict.pop("label_emb.0.0.weight") |
| 96 | + new_state_dict["time_text_embed.text_embedder.linear_1.bias"] = original_state_dict.pop("label_emb.0.0.bias") |
| 97 | + new_state_dict["time_text_embed.text_embedder.linear_2.weight"] = original_state_dict.pop("label_emb.0.2.weight") |
| 98 | + new_state_dict["time_text_embed.text_embedder.linear_2.bias"] = original_state_dict.pop("label_emb.0.2.bias") |
| 99 | + |
| 100 | + # Convert transformer blocks |
| 101 | + for i in range(30): |
| 102 | + block_prefix = f"transformer_blocks.{i}." |
| 103 | + old_prefix = f"transformer.layers.{i}." |
| 104 | + adaln_prefix = f"mixins.adaln.adaln_modules.{i}." |
| 105 | + |
| 106 | + new_state_dict[block_prefix + "norm1.linear.weight"] = original_state_dict.pop(adaln_prefix + "1.weight") |
| 107 | + new_state_dict[block_prefix + "norm1.linear.bias"] = original_state_dict.pop(adaln_prefix + "1.bias") |
| 108 | + |
| 109 | + qkv_weight = original_state_dict.pop(old_prefix + "attention.query_key_value.weight") |
| 110 | + qkv_bias = original_state_dict.pop(old_prefix + "attention.query_key_value.bias") |
| 111 | + q, k, v = qkv_weight.chunk(3, dim=0) |
| 112 | + q_bias, k_bias, v_bias = qkv_bias.chunk(3, dim=0) |
| 113 | + |
| 114 | + new_state_dict[block_prefix + "attn.to_q.weight"] = q |
| 115 | + new_state_dict[block_prefix + "attn.to_q.bias"] = q_bias |
| 116 | + new_state_dict[block_prefix + "attn.to_k.weight"] = k |
| 117 | + new_state_dict[block_prefix + "attn.to_k.bias"] = k_bias |
| 118 | + new_state_dict[block_prefix + "attn.to_v.weight"] = v |
| 119 | + new_state_dict[block_prefix + "attn.to_v.bias"] = v_bias |
| 120 | + |
| 121 | + new_state_dict[block_prefix + "attn.to_out.0.weight"] = original_state_dict.pop( |
| 122 | + old_prefix + "attention.dense.weight" |
| 123 | + ) |
| 124 | + new_state_dict[block_prefix + "attn.to_out.0.bias"] = original_state_dict.pop( |
| 125 | + old_prefix + "attention.dense.bias" |
| 126 | + ) |
| 127 | + |
| 128 | + new_state_dict[block_prefix + "ff.net.0.proj.weight"] = original_state_dict.pop( |
| 129 | + old_prefix + "mlp.dense_h_to_4h.weight" |
| 130 | + ) |
| 131 | + new_state_dict[block_prefix + "ff.net.0.proj.bias"] = original_state_dict.pop( |
| 132 | + old_prefix + "mlp.dense_h_to_4h.bias" |
| 133 | + ) |
| 134 | + new_state_dict[block_prefix + "ff.net.2.weight"] = original_state_dict.pop( |
| 135 | + old_prefix + "mlp.dense_4h_to_h.weight" |
| 136 | + ) |
| 137 | + new_state_dict[block_prefix + "ff.net.2.bias"] = original_state_dict.pop(old_prefix + "mlp.dense_4h_to_h.bias") |
| 138 | + |
| 139 | + # Convert final norm and projection |
| 140 | + new_state_dict["norm_out.linear.weight"] = swap_scale_shift( |
| 141 | + original_state_dict.pop("mixins.final_layer.adaln.1.weight"), dim=0 |
| 142 | + ) |
| 143 | + new_state_dict["norm_out.linear.bias"] = swap_scale_shift( |
| 144 | + original_state_dict.pop("mixins.final_layer.adaln.1.bias"), dim=0 |
| 145 | + ) |
| 146 | + new_state_dict["proj_out.weight"] = original_state_dict.pop("mixins.final_layer.linear.weight") |
| 147 | + new_state_dict["proj_out.bias"] = original_state_dict.pop("mixins.final_layer.linear.bias") |
| 148 | + |
| 149 | + return new_state_dict |
| 150 | + |
| 151 | + |
| 152 | +def main(args): |
| 153 | + original_ckpt = load_original_checkpoint(args) |
| 154 | + original_ckpt = original_ckpt["module"] |
| 155 | + original_ckpt = {k.replace("model.diffusion_model.", ""): v for k, v in original_ckpt.items()} |
| 156 | + |
| 157 | + original_dtype = next(iter(original_ckpt.values())).dtype |
| 158 | + dtype = None |
| 159 | + if args.dtype is None: |
| 160 | + dtype = original_dtype |
| 161 | + elif args.dtype == "fp16": |
| 162 | + dtype = torch.float16 |
| 163 | + elif args.dtype == "bf16": |
| 164 | + dtype = torch.bfloat16 |
| 165 | + elif args.dtype == "fp32": |
| 166 | + dtype = torch.float32 |
| 167 | + else: |
| 168 | + raise ValueError(f"Unsupported dtype: {args.dtype}") |
| 169 | + |
| 170 | + if args.transformer: |
| 171 | + converted_transformer_state_dict = convert_cogview3_transformer_checkpoint_to_diffusers(original_ckpt) |
| 172 | + transformer = CogView3PlusTransformer2DModel() |
| 173 | + transformer.load_state_dict(converted_transformer_state_dict, strict=True) |
| 174 | + |
| 175 | + print(f"Saving CogView3 Transformer in Diffusers format in {args.output_path}/transformer") |
| 176 | + transformer.to(dtype).save_pretrained(f"{args.output_path}/transformer") |
| 177 | + |
| 178 | + if len(original_ckpt) > 0: |
| 179 | + print(f"Warning: {len(original_ckpt)} keys were not converted and will be saved as is: {original_ckpt.keys()}") |
| 180 | + |
| 181 | + |
| 182 | +if __name__ == "__main__": |
| 183 | + main(args) |
0 commit comments