|
| 1 | +import argparse |
| 2 | +from pathlib import Path |
| 3 | + |
| 4 | +import torch |
| 5 | +from huggingface_hub import hf_hub_download # type: ignore |
| 6 | + |
| 7 | +from refiners.fluxion.utils import load_from_safetensors, save_to_safetensors |
| 8 | + |
| 9 | + |
| 10 | +class Args(argparse.Namespace): |
| 11 | + source_path: str |
| 12 | + output_path: str | None |
| 13 | + use_half: bool |
| 14 | + |
| 15 | + |
| 16 | +def convert(args: Args) -> dict[str, torch.Tensor]: |
| 17 | + if Path(args.source_path).suffix != ".safetensors": |
| 18 | + args.source_path = hf_hub_download( |
| 19 | + repo_id=args.source_path, filename="ella-sd1.5-tsc-t5xl.safetensors", local_dir="tests/weights/ELLA-Adapter" |
| 20 | + ) |
| 21 | + weights = load_from_safetensors(args.source_path) |
| 22 | + |
| 23 | + for key in list(weights.keys()): |
| 24 | + if "latents" in key: |
| 25 | + new_key = "PerceiverResampler.Latents.ParameterInitialized.weight" |
| 26 | + weights[new_key] = weights.pop(key) |
| 27 | + elif "time_embedding" in key: |
| 28 | + new_key = key.replace("time_embedding", "TimestepEncoder.RangeEncoder").replace("linear", "Linear") |
| 29 | + weights[new_key] = weights.pop(key) |
| 30 | + elif "proj_in" in key: |
| 31 | + new_key = f"PerceiverResampler.Linear.{key.split('.')[-1]}" |
| 32 | + weights[new_key] = weights.pop(key) |
| 33 | + elif "time_aware" in key: |
| 34 | + new_key = f"PerceiverResampler.Residual.Linear.{key.split('.')[-1]}" |
| 35 | + weights[new_key] = weights.pop(key) |
| 36 | + elif "attn.in_proj" in key: |
| 37 | + layer_num = int(key.split(".")[2]) |
| 38 | + query_param, key_param, value_param = weights.pop(key).chunk(3, dim=0) |
| 39 | + param_type = "weight" if "weight" in key else "bias" |
| 40 | + for i, param in enumerate([query_param, key_param, value_param]): |
| 41 | + new_key = f"PerceiverResampler.Transformer.TransformerLayer_{layer_num+1}.Residual_1.PerceiverAttention.Attention.Distribute.Linear_{i+1}.{param_type}" |
| 42 | + weights[new_key] = param |
| 43 | + elif "attn.out_proj" in key: |
| 44 | + layer_num = int(key.split(".")[2]) |
| 45 | + new_key = f"PerceiverResampler.Transformer.TransformerLayer_{layer_num+1}.Residual_1.PerceiverAttention.Attention.Linear.{key.split('.')[-1]}" |
| 46 | + weights[new_key] = weights.pop(key) |
| 47 | + elif "ln_ff" in key: |
| 48 | + layer_num = int(key.split(".")[2]) |
| 49 | + new_key = f"PerceiverResampler.Transformer.TransformerLayer_{layer_num+1}.Residual_2.AdaLayerNorm.Parallel.Chain.Linear.{key.split('.')[-1]}" |
| 50 | + weights[new_key] = weights.pop(key) |
| 51 | + elif "ln_1" in key or "ln_2" in key: |
| 52 | + layer_num = int(key.split(".")[2]) |
| 53 | + n = 1 if int(key.split(".")[3].split("_")[-1]) == 2 else 2 |
| 54 | + new_key = f"PerceiverResampler.Transformer.TransformerLayer_{layer_num+1}.Residual_1.PerceiverAttention.Distribute.AdaLayerNorm_{n}.Parallel.Chain.Linear.{key.split('.')[-1]}" |
| 55 | + weights[new_key] = weights.pop(key) |
| 56 | + elif "mlp" in key: |
| 57 | + layer_num = int(key.split(".")[2]) |
| 58 | + n = 1 if "c_fc" in key else 2 |
| 59 | + new_key = f"PerceiverResampler.Transformer.TransformerLayer_{layer_num+1}.Residual_2.FeedForward.Linear_{n}.{key.split('.')[-1]}" |
| 60 | + weights[new_key] = weights.pop(key) |
| 61 | + |
| 62 | + if args.use_half: |
| 63 | + weights = {key: value.half() for key, value in weights.items()} |
| 64 | + |
| 65 | + return weights |
| 66 | + |
| 67 | + |
| 68 | +if __name__ == "__main__": |
| 69 | + parser = argparse.ArgumentParser(description="Convert a pretrained Ella Adapter to refiners implementation") |
| 70 | + parser.add_argument( |
| 71 | + "--from", |
| 72 | + type=str, |
| 73 | + dest="source_path", |
| 74 | + default="QQGYLab/ELLA", |
| 75 | + help=( |
| 76 | + "A path to a local .safetensors weights. If not provided, a repo from Hugging Face Hub will be used" |
| 77 | + "Default to QQGYLab/ELLA" |
| 78 | + ), |
| 79 | + ) |
| 80 | + |
| 81 | + parser.add_argument( |
| 82 | + "--to", |
| 83 | + type=str, |
| 84 | + dest="output_path", |
| 85 | + default=None, |
| 86 | + help=( |
| 87 | + "Path to save the converted model (extension will be .safetensors). If not specified, the output path will" |
| 88 | + " be the source path with the prefix set to refiners" |
| 89 | + ), |
| 90 | + ) |
| 91 | + parser.add_argument( |
| 92 | + "--half", |
| 93 | + action="store_true", |
| 94 | + dest="use_half", |
| 95 | + default=True, |
| 96 | + help="Use this flag to save the output file as half precision (default: full precision).", |
| 97 | + ) |
| 98 | + args = parser.parse_args(namespace=Args()) |
| 99 | + weights = convert(args) |
| 100 | + if args.output_path is None: |
| 101 | + args.output_path = f"{Path(args.source_path).stem}-refiners.safetensors" |
| 102 | + save_to_safetensors(path=args.output_path, tensors=weights) |
0 commit comments