Skip to content

Commit aecb7d6

Browse files
committed
ella adapter implementation. tested with sd1.5 model
1 parent 09a9dfd commit aecb7d6

File tree

10 files changed

+579
-1
lines changed

10 files changed

+579
-1
lines changed
Lines changed: 92 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,92 @@
1+
import argparse
2+
from pathlib import Path
3+
4+
from refiners.fluxion.utils import load_from_safetensors, save_to_safetensors
5+
6+
7+
class Args(argparse.Namespace):
8+
source_path: str
9+
output_path: str | None
10+
use_half: bool
11+
12+
13+
def convert(args: Args) -> None:
14+
weights = load_from_safetensors(args.source_path)
15+
16+
for key in list(weights.keys()):
17+
if "latents" in key:
18+
new_key = "PerceiverResampler.Parallel.Sum.Latents.ParameterInitialized.weight"
19+
weights[new_key] = weights.pop(key)
20+
elif "time_embedding" in key:
21+
new_key = key.replace("time_embedding", "TimestepEncoder.RangeEncoder").replace("linear", "Linear")
22+
weights[new_key] = weights.pop(key)
23+
elif "proj_in" in key:
24+
new_key = f"PerceiverResampler.Parallel.Linear.{key.split('.')[-1]}"
25+
weights[new_key] = weights.pop(key)
26+
elif "time_aware" in key:
27+
new_key = f"PerceiverResampler.Parallel.Sum.Chain.Linear.{key.split('.')[-1]}"
28+
weights[new_key] = weights.pop(key)
29+
elif "attn.in_proj" in key:
30+
layer_num = int(key.split(".")[2])
31+
query_param, key_param, value_param = weights.pop(key).chunk(3, dim=0)
32+
param_type = "weight" if "weight" in key else "bias"
33+
for i, param in enumerate([query_param, key_param, value_param]):
34+
new_key = f"PerceiverResampler.Chain.PerceiverAttentionBlock_{layer_num+1}.Parallel._PerceiverAttentionBlock.Sum.Parallel.Chain.Attention.Distribute.Linear_{i+1}.{param_type}"
35+
weights[new_key] = param
36+
elif "attn.out_proj" in key:
37+
layer_num = int(key.split(".")[2])
38+
new_key = f"PerceiverResampler.Chain.PerceiverAttentionBlock_{layer_num+1}.Parallel._PerceiverAttentionBlock.Sum.Parallel.Chain.Attention.Linear.{key.split('.')[-1]}"
39+
weights[new_key] = weights.pop(key)
40+
elif "ln_ff" in key:
41+
layer_num = int(key.split(".")[2])
42+
new_key = f"PerceiverResampler.Chain.PerceiverAttentionBlock_{layer_num+1}.Parallel._PerceiverAttentionBlock.Residual.Chain.OutputAdaLayerNorm.Parallel.Chain.Linear.{key.split('.')[-1]}"
43+
weights[new_key] = weights.pop(key)
44+
elif "ln_1" in key or "ln_2" in key:
45+
layer_num = int(key.split(".")[2])
46+
n = int(key.split(".")[3].split("_")[-1])
47+
layernorm_type = "LatentsAdaLayerNorm" if n == 1 else "InputAdaLayerNorm"
48+
new_key = f"PerceiverResampler.Chain.PerceiverAttentionBlock_{layer_num+1}.Parallel._PerceiverAttentionBlock.Sum.Parallel.Chain.Distribute.{layernorm_type}.Parallel.Chain.Linear.{key.split('.')[-1]}"
49+
weights[new_key] = weights.pop(key)
50+
elif "mlp" in key:
51+
layer_num = int(key.split(".")[2])
52+
n = 1 if "c_fc" in key else 2
53+
new_key = f"PerceiverResampler.Chain.PerceiverAttentionBlock_{layer_num+1}.Parallel._PerceiverAttentionBlock.Residual.Chain.Linear_{n}.{key.split('.')[-1]}"
54+
weights[new_key] = weights.pop(key)
55+
56+
if args.use_half:
57+
weights = {key: value.half() for key, value in weights.items()}
58+
59+
return weights
60+
61+
62+
if __name__ == "__main__":
63+
parser = argparse.ArgumentParser(description="Convert a pretrained Ella Adapter to refiners implementation")
64+
parser.add_argument(
65+
"--from",
66+
type=str,
67+
required=True,
68+
dest="source_path",
69+
help=("Official checkpoint from https://huggingface.co/QQGYLab/ELLA/blob/main/ella-sd1.5-tsc-t5xl.safetensors"),
70+
)
71+
parser.add_argument(
72+
"--to",
73+
type=str,
74+
dest="output_path",
75+
default=None,
76+
help=(
77+
"Path to save the converted model (extension will be .safetensors). If not specified, the output path will"
78+
" be the source path with the prefix set to refiners"
79+
),
80+
)
81+
parser.add_argument(
82+
"--half",
83+
action="store_true",
84+
dest="use_half",
85+
default=True,
86+
help="Use this flag to save the output file as half precision (default: full precision).",
87+
)
88+
args = parser.parse_args(namespace=Args())
89+
weights = convert(args)
90+
if args.output_path is None:
91+
args.output_path = f"rrefiners_{Path(args.source_path).stem}.safetensors"
92+
save_to_safetensors(path=args.output_path, tensors=weights)

scripts/prepare_test_weights.py

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -352,6 +352,29 @@ def download_ip_adapter():
352352
download_files(urls, sdxl_models_folder)
353353

354354

355+
def download_t5xl_fp16():
356+
base_folder = os.path.join(test_weights_dir, "QQGYLab", "T5XLFP16")
357+
urls = [
358+
"https://huggingface.co/QQGYLab/ELLA/resolve/main/models--google--flan-t5-xl--text_encoder/config.json",
359+
"https://huggingface.co/QQGYLab/ELLA/resolve/main/models--google--flan-t5-xl--text_encoder/model.safetensors",
360+
"https://huggingface.co/QQGYLab/ELLA/resolve/main/models--google--flan-t5-xl--text_encoder/special_tokens_map.json",
361+
"https://huggingface.co/QQGYLab/ELLA/resolve/main/models--google--flan-t5-xl--text_encoder/spiece.model",
362+
"https://huggingface.co/QQGYLab/ELLA/resolve/main/models--google--flan-t5-xl--text_encoder/tokenizer.json",
363+
"https://huggingface.co/QQGYLab/ELLA/resolve/main/models--google--flan-t5-xl--text_encoder/tokenizer_config.json",
364+
]
365+
download_files(urls, base_folder)
366+
367+
368+
def download_ella_adapter():
369+
download_t5xl_fp16()
370+
base_folder = os.path.join(test_weights_dir, "QQGYLab", "ELLA")
371+
download_file(
372+
"https://huggingface.co/QQGYLab/ELLA/resolve/main/ella-sd1.5-tsc-t5xl.safetensors",
373+
base_folder,
374+
expected_hash="5af7b200",
375+
)
376+
377+
355378
def download_t2i_adapter():
356379
base_folder = os.path.join(test_weights_dir, "TencentARC", "t2iadapter_depth_sd15v2")
357380
urls = [
@@ -652,6 +675,17 @@ def convert_ip_adapter():
652675
)
653676

654677

678+
def convert_ella_adapter():
679+
os.makedirs("tests/weights/ELLA-Adapter", exist_ok=True)
680+
run_conversion_script(
681+
"convert_ella_adapter.py",
682+
"tests/weights/QQGYLab/ELLA/ella-sd1.5-tsc-t5xl.safetensors",
683+
"tests/weights/ELLA-Adapter/ella-sd1.5-tsc-t5xl.safetensors",
684+
half=True,
685+
expected_hash="a8a37510",
686+
)
687+
688+
655689
def convert_t2i_adapter():
656690
os.makedirs("tests/weights/T2I-Adapter", exist_ok=True)
657691
run_conversion_script(
@@ -803,6 +837,7 @@ def download_all():
803837
download_unclip()
804838
download_ip_adapter()
805839
download_t2i_adapter()
840+
download_ella_adapter()
806841
download_sam()
807842
download_hq_sam()
808843
download_dinov2()
@@ -824,6 +859,7 @@ def convert_all():
824859
convert_unclip()
825860
convert_ip_adapter()
826861
convert_t2i_adapter()
862+
convert_ella_adapter()
827863
convert_sam()
828864
convert_hq_sam()
829865
convert_dinov2()

src/refiners/foundationals/latent_diffusion/__init__.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@
1313
SD1UNet,
1414
StableDiffusion_1,
1515
StableDiffusion_1_Inpainting,
16+
SD1ELLAAdapter
1617
)
1718
from refiners.foundationals.latent_diffusion.stable_diffusion_xl import (
1819
ControlLoraAdapter,
@@ -32,6 +33,7 @@
3233
"SD1ControlnetAdapter",
3334
"SD1IPAdapter",
3435
"SD1T2IAdapter",
36+
"SD1ELLAAdapter",
3537
"SDXLUNet",
3638
"DoubleTextEncoder",
3739
"SDXLIPAdapter",

0 commit comments

Comments
 (0)