Skip to content

Commit 5c53ca5

Browse files
authored
[core] AnimateDiff SparseCtrl (#8897)
* initial sparse control model draft * remove unnecessary implementation * copy animatediff pipeline * remove deprecated callbacks * update * update pipeline implementation progress * make style * make fix-copies * update progress * add partially working pipeline * remove debug prints * add model docs * dummy objects * improve motion lora conversion script * fix bugs * update docstrings * remove unnecessary model params; docs * address review comment * add copied from to zero_module * copy animatediff test * add fast tests * update docs * update * update pipeline docs * fix expected slice values * fix license * remove get_down_block usage * remove temporal_double_self_attention from get_down_block * update * update docs with org and documentation images * make from_unet work in sparsecontrolnetmodel * add latest freeinit test from #8969 * make fix-copies * LoraLoaderMixin -> StableDiffsuionLoraLoaderMixin
1 parent 57a021d commit 5c53ca5

16 files changed

+2664
-6
lines changed

docs/source/en/_toctree.yml

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -267,6 +267,8 @@
267267
title: HunyuanDiT2DControlNetModel
268268
- local: api/models/controlnet_sd3
269269
title: SD3ControlNetModel
270+
- local: api/models/controlnet_sparsectrl
271+
title: SparseControlNetModel
270272
title: Models
271273
- isExpanded: false
272274
sections:
Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
<!-- Copyright 2024 The HuggingFace Team. All rights reserved.
2+
3+
Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
4+
the License. You may obtain a copy of the License at
5+
6+
http://www.apache.org/licenses/LICENSE-2.0
7+
8+
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
9+
an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
10+
specific language governing permissions and limitations under the License. -->
11+
12+
# SparseControlNetModel
13+
14+
SparseControlNetModel is an implementation of ControlNet for [AnimateDiff](https://arxiv.org/abs/2307.04725).
15+
16+
ControlNet was introduced in [Adding Conditional Control to Text-to-Image Diffusion Models](https://huggingface.co/papers/2302.05543) by Lvmin Zhang, Anyi Rao, and Maneesh Agrawala.
17+
18+
The SparseCtrl version of ControlNet was introduced in [SparseCtrl: Adding Sparse Controls to Text-to-Video Diffusion Models](https://arxiv.org/abs/2311.16933) for achieving controlled generation in text-to-video diffusion models by Yuwei Guo, Ceyuan Yang, Anyi Rao, Maneesh Agrawala, Dahua Lin, and Bo Dai.
19+
20+
The abstract from the paper is:
21+
22+
*The development of text-to-video (T2V), i.e., generating videos with a given text prompt, has been significantly advanced in recent years. However, relying solely on text prompts often results in ambiguous frame composition due to spatial uncertainty. The research community thus leverages the dense structure signals, e.g., per-frame depth/edge sequences, to enhance controllability, whose collection accordingly increases the burden of inference. In this work, we present SparseCtrl to enable flexible structure control with temporally sparse signals, requiring only one or a few inputs, as shown in Figure 1. It incorporates an additional condition encoder to process these sparse signals while leaving the pre-trained T2V model untouched. The proposed approach is compatible with various modalities, including sketches, depth maps, and RGB images, providing more practical control for video generation and promoting applications such as storyboarding, depth rendering, keyframe animation, and interpolation. Extensive experiments demonstrate the generalization of SparseCtrl on both original and personalized T2V generators. Codes and models will be publicly available at [this https URL](https://guoyww.github.io/projects/SparseCtrl).*
23+
24+
## Example for loading SparseControlNetModel
25+
26+
```python
27+
import torch
28+
from diffusers import SparseControlNetModel
29+
30+
# fp32 variant in float16
31+
# 1. Scribble checkpoint
32+
controlnet = SparseControlNetModel.from_pretrained("guoyww/animatediff-sparsectrl-scribble", torch_dtype=torch.float16)
33+
34+
# 2. RGB checkpoint
35+
controlnet = SparseControlNetModel.from_pretrained("guoyww/animatediff-sparsectrl-rgb", torch_dtype=torch.float16)
36+
37+
# For loading fp16 variant, pass `variant="fp16"` as an additional parameter
38+
```
39+
40+
## SparseControlNetModel
41+
42+
[[autodoc]] SparseControlNetModel
43+
44+
## SparseControlNetOutput
45+
46+
[[autodoc]] models.controlnet_sparsectrl.SparseControlNetOutput

docs/source/en/api/pipelines/animatediff.md

Lines changed: 189 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -100,6 +100,189 @@ AnimateDiff tends to work better with finetuned Stable Diffusion models. If you
100100

101101
</Tip>
102102

103+
### AnimateDiffSparseControlNetPipeline
104+
105+
[SparseCtrl: Adding Sparse Controls to Text-to-Video Diffusion Models](https://arxiv.org/abs/2311.16933) for achieving controlled generation in text-to-video diffusion models by Yuwei Guo, Ceyuan Yang, Anyi Rao, Maneesh Agrawala, Dahua Lin, and Bo Dai.
106+
107+
The abstract from the paper is:
108+
109+
*The development of text-to-video (T2V), i.e., generating videos with a given text prompt, has been significantly advanced in recent years. However, relying solely on text prompts often results in ambiguous frame composition due to spatial uncertainty. The research community thus leverages the dense structure signals, e.g., per-frame depth/edge sequences, to enhance controllability, whose collection accordingly increases the burden of inference. In this work, we present SparseCtrl to enable flexible structure control with temporally sparse signals, requiring only one or a few inputs, as shown in Figure 1. It incorporates an additional condition encoder to process these sparse signals while leaving the pre-trained T2V model untouched. The proposed approach is compatible with various modalities, including sketches, depth maps, and RGB images, providing more practical control for video generation and promoting applications such as storyboarding, depth rendering, keyframe animation, and interpolation. Extensive experiments demonstrate the generalization of SparseCtrl on both original and personalized T2V generators. Codes and models will be publicly available at [this https URL](https://guoyww.github.io/projects/SparseCtrl).*
110+
111+
SparseCtrl introduces the following checkpoints for controlled text-to-video generation:
112+
113+
- [SparseCtrl Scribble](https://huggingface.co/guoyww/animatediff-sparsectrl-scribble)
114+
- [SparseCtrl RGB](https://huggingface.co/guoyww/animatediff-sparsectrl-rgb)
115+
116+
#### Using SparseCtrl Scribble
117+
118+
```python
119+
import torch
120+
121+
from diffusers import AnimateDiffSparseControlNetPipeline
122+
from diffusers.models import AutoencoderKL, MotionAdapter, SparseControlNetModel
123+
from diffusers.schedulers import DPMSolverMultistepScheduler
124+
from diffusers.utils import export_to_gif, load_image
125+
126+
127+
model_id = "SG161222/Realistic_Vision_V5.1_noVAE"
128+
motion_adapter_id = "guoyww/animatediff-motion-adapter-v1-5-3"
129+
controlnet_id = "guoyww/animatediff-sparsectrl-scribble"
130+
lora_adapter_id = "guoyww/animatediff-motion-lora-v1-5-3"
131+
vae_id = "stabilityai/sd-vae-ft-mse"
132+
device = "cuda"
133+
134+
motion_adapter = MotionAdapter.from_pretrained(motion_adapter_id, torch_dtype=torch.float16).to(device)
135+
controlnet = SparseControlNetModel.from_pretrained(controlnet_id, torch_dtype=torch.float16).to(device)
136+
vae = AutoencoderKL.from_pretrained(vae_id, torch_dtype=torch.float16).to(device)
137+
scheduler = DPMSolverMultistepScheduler.from_pretrained(
138+
model_id,
139+
subfolder="scheduler",
140+
beta_schedule="linear",
141+
algorithm_type="dpmsolver++",
142+
use_karras_sigmas=True,
143+
)
144+
pipe = AnimateDiffSparseControlNetPipeline.from_pretrained(
145+
model_id,
146+
motion_adapter=motion_adapter,
147+
controlnet=controlnet,
148+
vae=vae,
149+
scheduler=scheduler,
150+
torch_dtype=torch.float16,
151+
).to(device)
152+
pipe.load_lora_weights(lora_adapter_id, adapter_name="motion_lora")
153+
pipe.fuse_lora(lora_scale=1.0)
154+
155+
prompt = "an aerial view of a cyberpunk city, night time, neon lights, masterpiece, high quality"
156+
negative_prompt = "low quality, worst quality, letterboxed"
157+
158+
image_files = [
159+
"https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/animatediff-scribble-1.png",
160+
"https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/animatediff-scribble-2.png",
161+
"https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/animatediff-scribble-3.png"
162+
]
163+
condition_frame_indices = [0, 8, 15]
164+
conditioning_frames = [load_image(img_file) for img_file in image_files]
165+
166+
video = pipe(
167+
prompt=prompt,
168+
negative_prompt=negative_prompt,
169+
num_inference_steps=25,
170+
conditioning_frames=conditioning_frames,
171+
controlnet_conditioning_scale=1.0,
172+
controlnet_frame_indices=condition_frame_indices,
173+
generator=torch.Generator().manual_seed(1337),
174+
).frames[0]
175+
export_to_gif(video, "output.gif")
176+
```
177+
178+
Here are some sample outputs:
179+
180+
<table align="center">
181+
<tr>
182+
<center>
183+
<b>an aerial view of a cyberpunk city, night time, neon lights, masterpiece, high quality</b>
184+
</center>
185+
</tr>
186+
<tr>
187+
<td>
188+
<center>
189+
<img src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/animatediff-scribble-1.png" alt="scribble-1" />
190+
</center>
191+
</td>
192+
<td>
193+
<center>
194+
<img src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/animatediff-scribble-2.png" alt="scribble-2" />
195+
</center>
196+
</td>
197+
<td>
198+
<center>
199+
<img src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/animatediff-scribble-3.png" alt="scribble-3" />
200+
</center>
201+
</td>
202+
</tr>
203+
<tr>
204+
<td colspan=3>
205+
<center>
206+
<img src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/animatediff-sparsectrl-scribble-results.gif" alt="an aerial view of a cyberpunk city, night time, neon lights, masterpiece, high quality" />
207+
</center>
208+
</td>
209+
</tr>
210+
</table>
211+
212+
#### Using SparseCtrl RGB
213+
214+
```python
215+
import torch
216+
217+
from diffusers import AnimateDiffSparseControlNetPipeline
218+
from diffusers.models import AutoencoderKL, MotionAdapter, SparseControlNetModel
219+
from diffusers.schedulers import DPMSolverMultistepScheduler
220+
from diffusers.utils import export_to_gif, load_image
221+
222+
223+
model_id = "SG161222/Realistic_Vision_V5.1_noVAE"
224+
motion_adapter_id = "guoyww/animatediff-motion-adapter-v1-5-3"
225+
controlnet_id = "guoyww/animatediff-sparsectrl-rgb"
226+
lora_adapter_id = "guoyww/animatediff-motion-lora-v1-5-3"
227+
vae_id = "stabilityai/sd-vae-ft-mse"
228+
device = "cuda"
229+
230+
motion_adapter = MotionAdapter.from_pretrained(motion_adapter_id, torch_dtype=torch.float16).to(device)
231+
controlnet = SparseControlNetModel.from_pretrained(controlnet_id, torch_dtype=torch.float16).to(device)
232+
vae = AutoencoderKL.from_pretrained(vae_id, torch_dtype=torch.float16).to(device)
233+
scheduler = DPMSolverMultistepScheduler.from_pretrained(
234+
model_id,
235+
subfolder="scheduler",
236+
beta_schedule="linear",
237+
algorithm_type="dpmsolver++",
238+
use_karras_sigmas=True,
239+
)
240+
pipe = AnimateDiffSparseControlNetPipeline.from_pretrained(
241+
model_id,
242+
motion_adapter=motion_adapter,
243+
controlnet=controlnet,
244+
vae=vae,
245+
scheduler=scheduler,
246+
torch_dtype=torch.float16,
247+
).to(device)
248+
pipe.load_lora_weights(lora_adapter_id, adapter_name="motion_lora")
249+
250+
image = load_image("https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/animatediff-firework.png")
251+
252+
video = pipe(
253+
prompt="closeup face photo of man in black clothes, night city street, bokeh, fireworks in background",
254+
negative_prompt="low quality, worst quality",
255+
num_inference_steps=25,
256+
conditioning_frames=image,
257+
controlnet_frame_indices=[0],
258+
controlnet_conditioning_scale=1.0,
259+
generator=torch.Generator().manual_seed(42),
260+
).frames[0]
261+
export_to_gif(video, "output.gif")
262+
```
263+
264+
Here are some sample outputs:
265+
266+
<table align="center">
267+
<tr>
268+
<center>
269+
<b>closeup face photo of man in black clothes, night city street, bokeh, fireworks in background</b>
270+
</center>
271+
</tr>
272+
<tr>
273+
<td>
274+
<center>
275+
<img src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/animatediff-firework.png" alt="closeup face photo of man in black clothes, night city street, bokeh, fireworks in background" />
276+
</center>
277+
</td>
278+
<td>
279+
<center>
280+
<img src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/animatediff-sparsectrl-rgb-result.gif" alt="closeup face photo of man in black clothes, night city street, bokeh, fireworks in background" />
281+
</center>
282+
</td>
283+
</tr>
284+
</table>
285+
103286
### AnimateDiffSDXLPipeline
104287

105288
AnimateDiff can also be used with SDXL models. This is currently an experimental feature as only a beta release of the motion adapter checkpoint is available.
@@ -571,7 +754,6 @@ ckpt_path = "https://huggingface.co/Lightricks/LongAnimateDiff/blob/main/lt_long
571754

572755
adapter = MotionAdapter.from_single_file(ckpt_path, torch_dtype=torch.float16)
573756
pipe = AnimateDiffPipeline.from_pretrained("emilianJR/epiCRealism", motion_adapter=adapter)
574-
575757
```
576758

577759
## AnimateDiffPipeline
@@ -580,6 +762,12 @@ pipe = AnimateDiffPipeline.from_pretrained("emilianJR/epiCRealism", motion_adapt
580762
- all
581763
- __call__
582764

765+
## AnimateDiffSparseControlNetPipeline
766+
767+
[[autodoc]] AnimateDiffSparseControlNetPipeline
768+
- all
769+
- __call__
770+
583771
## AnimateDiffSDXLPipeline
584772

585773
[[autodoc]] AnimateDiffSDXLPipeline

scripts/convert_animatediff_motion_lora_to_diffusers.py

Lines changed: 18 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,8 @@
11
import argparse
2+
import os
23

34
import torch
5+
from huggingface_hub import create_repo, upload_folder
46
from safetensors.torch import load_file, save_file
57

68

@@ -25,8 +27,14 @@ def convert_motion_module(original_state_dict):
2527

2628
def get_args():
2729
parser = argparse.ArgumentParser()
28-
parser.add_argument("--ckpt_path", type=str, required=True)
29-
parser.add_argument("--output_path", type=str, required=True)
30+
parser.add_argument("--ckpt_path", type=str, required=True, help="Path to checkpoint")
31+
parser.add_argument("--output_path", type=str, required=True, help="Path to output directory")
32+
parser.add_argument(
33+
"--push_to_hub",
34+
action="store_true",
35+
default=False,
36+
help="Whether to push the converted model to the HF or not",
37+
)
3038

3139
return parser.parse_args()
3240

@@ -51,4 +59,11 @@ def get_args():
5159
continue
5260
output_dict.update({f"unet.{module_name}": params})
5361

54-
save_file(output_dict, f"{args.output_path}/diffusion_pytorch_model.safetensors")
62+
os.makedirs(args.output_path, exist_ok=True)
63+
64+
filepath = os.path.join(args.output_path, "diffusion_pytorch_model.safetensors")
65+
save_file(output_dict, filepath)
66+
67+
if args.push_to_hub:
68+
repo_id = create_repo(args.output_path, exist_ok=True).repo_id
69+
upload_folder(repo_id=repo_id, folder_path=args.output_path, repo_type="model")
Lines changed: 83 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,83 @@
1+
import argparse
2+
from typing import Dict
3+
4+
import torch
5+
import torch.nn as nn
6+
7+
from diffusers import SparseControlNetModel
8+
9+
10+
KEYS_RENAME_MAPPING = {
11+
".attention_blocks.0": ".attn1",
12+
".attention_blocks.1": ".attn2",
13+
".attn1.pos_encoder": ".pos_embed",
14+
".ff_norm": ".norm3",
15+
".norms.0": ".norm1",
16+
".norms.1": ".norm2",
17+
".temporal_transformer": "",
18+
}
19+
20+
21+
def convert(original_state_dict: Dict[str, nn.Module]) -> Dict[str, nn.Module]:
22+
converted_state_dict = {}
23+
24+
for key in list(original_state_dict.keys()):
25+
renamed_key = key
26+
for new_name, old_name in KEYS_RENAME_MAPPING.items():
27+
renamed_key = renamed_key.replace(new_name, old_name)
28+
converted_state_dict[renamed_key] = original_state_dict.pop(key)
29+
30+
return converted_state_dict
31+
32+
33+
def get_args():
34+
parser = argparse.ArgumentParser()
35+
parser.add_argument("--ckpt_path", type=str, required=True, help="Path to checkpoint")
36+
parser.add_argument("--output_path", type=str, required=True, help="Path to output directory")
37+
parser.add_argument(
38+
"--max_motion_seq_length",
39+
type=int,
40+
default=32,
41+
help="Max motion sequence length supported by the motion adapter",
42+
)
43+
parser.add_argument(
44+
"--conditioning_channels", type=int, default=4, help="Number of channels in conditioning input to controlnet"
45+
)
46+
parser.add_argument(
47+
"--use_simplified_condition_embedding",
48+
action="store_true",
49+
default=False,
50+
help="Whether or not to use simplified condition embedding. When `conditioning_channels==4` i.e. latent inputs, set this to `True`. When `conditioning_channels==3` i.e. image inputs, set this to `False`",
51+
)
52+
parser.add_argument(
53+
"--save_fp16",
54+
action="store_true",
55+
default=False,
56+
help="Whether or not to save model in fp16 precision along with fp32",
57+
)
58+
parser.add_argument(
59+
"--push_to_hub", action="store_true", default=False, help="Whether or not to push saved model to the HF hub"
60+
)
61+
return parser.parse_args()
62+
63+
64+
if __name__ == "__main__":
65+
args = get_args()
66+
67+
state_dict = torch.load(args.ckpt_path, map_location="cpu")
68+
if "state_dict" in state_dict.keys():
69+
state_dict: dict = state_dict["state_dict"]
70+
71+
controlnet = SparseControlNetModel(
72+
conditioning_channels=args.conditioning_channels,
73+
motion_max_seq_length=args.max_motion_seq_length,
74+
use_simplified_condition_embedding=args.use_simplified_condition_embedding,
75+
)
76+
77+
state_dict = convert(state_dict)
78+
controlnet.load_state_dict(state_dict, strict=True)
79+
80+
controlnet.save_pretrained(args.output_path, push_to_hub=args.push_to_hub)
81+
if args.save_fp16:
82+
controlnet = controlnet.to(dtype=torch.float16)
83+
controlnet.save_pretrained(args.output_path, variant="fp16", push_to_hub=args.push_to_hub)

0 commit comments

Comments
 (0)