-
Notifications
You must be signed in to change notification settings - Fork 6.1k
[ControlNet] Adds controlnet for SanaTransformer #11040
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
24 commits
Select commit
Hold shift + click to select a range
321193b
added controlnet for sana transformer
ishan-modi 1955579
improve code quality
ishan-modi dfc396e
addressed PR comments
ishan-modi 009937b
bug fixes
ishan-modi 6a62c3e
added test cases
ishan-modi d698d81
update
ishan-modi 7f3cbc5
added dummy objects
ishan-modi 4145f6b
addressed PR comments
ishan-modi 62aa0a6
update
ishan-modi a4b701a
Forcing update
ishan-modi 4b86649
add to docs
ishan-modi e59208a
Merge branch 'main' into fixes-issue-10772
ishan-modi 6d01ea0
code quality
ishan-modi 3d085a2
addressed PR comments
ishan-modi dea5de5
addressed PR comments
ishan-modi e6ba267
update
ishan-modi 5776517
addressed PR comments
ishan-modi 344ee8a
added proper styling
ishan-modi b973cd0
update
ishan-modi e488bd8
Merge branch 'main' into fixes-issue-10772
ishan-modi cfe555f
Revert "added proper styling"
ishan-modi 86709f2
manually ordered
ishan-modi 3b8a9c0
Merge branch 'fixes-issue-10772' of https://github.com/ishan-modi/dif…
ishan-modi 0b20570
Apply suggestions from code review
a-r-r-o-w File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,29 @@ | ||
<!--Copyright 2024 The HuggingFace Team. All rights reserved. | ||
|
||
Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with | ||
the License. You may obtain a copy of the License at | ||
|
||
http://www.apache.org/licenses/LICENSE-2.0 | ||
|
||
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on | ||
an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the | ||
specific language governing permissions and limitations under the License. | ||
--> | ||
|
||
# SanaControlNetModel | ||
|
||
The ControlNet model was introduced in [Adding Conditional Control to Text-to-Image Diffusion Models](https://huggingface.co/papers/2302.05543) by Lvmin Zhang, Anyi Rao, Maneesh Agrawala. It provides a greater degree of control over text-to-image generation by conditioning the model on additional inputs such as edge maps, depth maps, segmentation maps, and keypoints for pose detection. | ||
|
||
The abstract from the paper is: | ||
|
||
*We present ControlNet, a neural network architecture to add spatial conditioning controls to large, pretrained text-to-image diffusion models. ControlNet locks the production-ready large diffusion models, and reuses their deep and robust encoding layers pretrained with billions of images as a strong backbone to learn a diverse set of conditional controls. The neural architecture is connected with "zero convolutions" (zero-initialized convolution layers) that progressively grow the parameters from zero and ensure that no harmful noise could affect the finetuning. We test various conditioning controls, eg, edges, depth, segmentation, human pose, etc, with Stable Diffusion, using single or multiple conditions, with or without prompts. We show that the training of ControlNets is robust with small (<50k) and large (>1m) datasets. Extensive results show that ControlNet may facilitate wider applications to control image diffusion models.* | ||
|
||
This model was contributed by [ishan24](https://huggingface.co/ishan24). ❤️ | ||
The original codebase can be found at [NVlabs/Sana](https://github.com/NVlabs/Sana), and you can find official ControlNet checkpoints on [Efficient-Large-Model's](https://huggingface.co/Efficient-Large-Model) Hub profile. | ||
|
||
## SanaControlNetModel | ||
[[autodoc]] SanaControlNetModel | ||
|
||
## SanaControlNetOutput | ||
[[autodoc]] models.controlnets.controlnet_sana.SanaControlNetOutput | ||
|
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,36 @@ | ||
<!--Copyright 2024 The HuggingFace Team. All rights reserved. | ||
|
||
Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with | ||
the License. You may obtain a copy of the License at | ||
|
||
http://www.apache.org/licenses/LICENSE-2.0 | ||
|
||
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on | ||
an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the | ||
specific language governing permissions and limitations under the License. | ||
--> | ||
|
||
# ControlNet | ||
|
||
<div class="flex flex-wrap space-x-1"> | ||
<img alt="LoRA" src="https://img.shields.io/badge/LoRA-d8b4fe?style=flat"/> | ||
</div> | ||
|
||
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. | ||
|
||
With a ControlNet model, you can provide an additional control image to condition and control Stable Diffusion generation. For example, if you provide a depth map, the ControlNet model generates an image that'll preserve the spatial information from the depth map. It is a more flexible and accurate way to control the image generation process. | ||
|
||
The abstract from the paper is: | ||
|
||
*We present ControlNet, a neural network architecture to add spatial conditioning controls to large, pretrained text-to-image diffusion models. ControlNet locks the production-ready large diffusion models, and reuses their deep and robust encoding layers pretrained with billions of images as a strong backbone to learn a diverse set of conditional controls. The neural architecture is connected with "zero convolutions" (zero-initialized convolution layers) that progressively grow the parameters from zero and ensure that no harmful noise could affect the finetuning. We test various conditioning controls, eg, edges, depth, segmentation, human pose, etc, with Stable Diffusion, using single or multiple conditions, with or without prompts. We show that the training of ControlNets is robust with small (<50k) and large (>1m) datasets. Extensive results show that ControlNet may facilitate wider applications to control image diffusion models.* | ||
|
||
This pipeline was contributed by [ishan24](https://huggingface.co/ishan24). ❤️ | ||
The original codebase can be found at [NVlabs/Sana](https://github.com/NVlabs/Sana), and you can find official ControlNet checkpoints on [Efficient-Large-Model's](https://huggingface.co/Efficient-Large-Model) Hub profile. | ||
|
||
## SanaControlNetPipeline | ||
[[autodoc]] SanaControlNetPipeline | ||
- all | ||
- __call__ | ||
|
||
## SanaPipelineOutput | ||
[[autodoc]] pipelines.sana.pipeline_output.SanaPipelineOutput |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,216 @@ | ||
#!/usr/bin/env python | ||
from __future__ import annotations | ||
|
||
import argparse | ||
from contextlib import nullcontext | ||
|
||
import torch | ||
from accelerate import init_empty_weights | ||
|
||
from diffusers import ( | ||
SanaControlNetModel, | ||
) | ||
from diffusers.models.modeling_utils import load_model_dict_into_meta | ||
from diffusers.utils.import_utils import is_accelerate_available | ||
|
||
|
||
CTX = init_empty_weights if is_accelerate_available else nullcontext | ||
|
||
|
||
def main(args): | ||
file_path = args.orig_ckpt_path | ||
|
||
all_state_dict = torch.load(file_path, weights_only=True) | ||
state_dict = all_state_dict.pop("state_dict") | ||
converted_state_dict = {} | ||
|
||
# Patch embeddings. | ||
converted_state_dict["patch_embed.proj.weight"] = state_dict.pop("x_embedder.proj.weight") | ||
converted_state_dict["patch_embed.proj.bias"] = state_dict.pop("x_embedder.proj.bias") | ||
|
||
# Caption projection. | ||
converted_state_dict["caption_projection.linear_1.weight"] = state_dict.pop("y_embedder.y_proj.fc1.weight") | ||
converted_state_dict["caption_projection.linear_1.bias"] = state_dict.pop("y_embedder.y_proj.fc1.bias") | ||
converted_state_dict["caption_projection.linear_2.weight"] = state_dict.pop("y_embedder.y_proj.fc2.weight") | ||
converted_state_dict["caption_projection.linear_2.bias"] = state_dict.pop("y_embedder.y_proj.fc2.bias") | ||
|
||
# AdaLN-single LN | ||
converted_state_dict["time_embed.emb.timestep_embedder.linear_1.weight"] = state_dict.pop( | ||
"t_embedder.mlp.0.weight" | ||
) | ||
converted_state_dict["time_embed.emb.timestep_embedder.linear_1.bias"] = state_dict.pop("t_embedder.mlp.0.bias") | ||
converted_state_dict["time_embed.emb.timestep_embedder.linear_2.weight"] = state_dict.pop( | ||
"t_embedder.mlp.2.weight" | ||
) | ||
converted_state_dict["time_embed.emb.timestep_embedder.linear_2.bias"] = state_dict.pop("t_embedder.mlp.2.bias") | ||
|
||
# Shared norm. | ||
converted_state_dict["time_embed.linear.weight"] = state_dict.pop("t_block.1.weight") | ||
converted_state_dict["time_embed.linear.bias"] = state_dict.pop("t_block.1.bias") | ||
|
||
# y norm | ||
converted_state_dict["caption_norm.weight"] = state_dict.pop("attention_y_norm.weight") | ||
|
||
# Positional embedding interpolation scale. | ||
interpolation_scale = {512: None, 1024: None, 2048: 1.0, 4096: 2.0} | ||
|
||
# ControlNet Input Projection. | ||
converted_state_dict["input_block.weight"] = state_dict.pop("controlnet.0.before_proj.weight") | ||
converted_state_dict["input_block.bias"] = state_dict.pop("controlnet.0.before_proj.bias") | ||
|
||
for depth in range(7): | ||
# Transformer blocks. | ||
converted_state_dict[f"transformer_blocks.{depth}.scale_shift_table"] = state_dict.pop( | ||
f"controlnet.{depth}.copied_block.scale_shift_table" | ||
) | ||
|
||
# Linear Attention is all you need 🤘 | ||
# Self attention. | ||
q, k, v = torch.chunk(state_dict.pop(f"controlnet.{depth}.copied_block.attn.qkv.weight"), 3, dim=0) | ||
converted_state_dict[f"transformer_blocks.{depth}.attn1.to_q.weight"] = q | ||
converted_state_dict[f"transformer_blocks.{depth}.attn1.to_k.weight"] = k | ||
converted_state_dict[f"transformer_blocks.{depth}.attn1.to_v.weight"] = v | ||
# Projection. | ||
converted_state_dict[f"transformer_blocks.{depth}.attn1.to_out.0.weight"] = state_dict.pop( | ||
f"controlnet.{depth}.copied_block.attn.proj.weight" | ||
) | ||
converted_state_dict[f"transformer_blocks.{depth}.attn1.to_out.0.bias"] = state_dict.pop( | ||
f"controlnet.{depth}.copied_block.attn.proj.bias" | ||
) | ||
|
||
# Feed-forward. | ||
converted_state_dict[f"transformer_blocks.{depth}.ff.conv_inverted.weight"] = state_dict.pop( | ||
f"controlnet.{depth}.copied_block.mlp.inverted_conv.conv.weight" | ||
) | ||
converted_state_dict[f"transformer_blocks.{depth}.ff.conv_inverted.bias"] = state_dict.pop( | ||
f"controlnet.{depth}.copied_block.mlp.inverted_conv.conv.bias" | ||
) | ||
converted_state_dict[f"transformer_blocks.{depth}.ff.conv_depth.weight"] = state_dict.pop( | ||
f"controlnet.{depth}.copied_block.mlp.depth_conv.conv.weight" | ||
) | ||
converted_state_dict[f"transformer_blocks.{depth}.ff.conv_depth.bias"] = state_dict.pop( | ||
f"controlnet.{depth}.copied_block.mlp.depth_conv.conv.bias" | ||
) | ||
converted_state_dict[f"transformer_blocks.{depth}.ff.conv_point.weight"] = state_dict.pop( | ||
f"controlnet.{depth}.copied_block.mlp.point_conv.conv.weight" | ||
) | ||
|
||
# Cross-attention. | ||
q = state_dict.pop(f"controlnet.{depth}.copied_block.cross_attn.q_linear.weight") | ||
q_bias = state_dict.pop(f"controlnet.{depth}.copied_block.cross_attn.q_linear.bias") | ||
k, v = torch.chunk(state_dict.pop(f"controlnet.{depth}.copied_block.cross_attn.kv_linear.weight"), 2, dim=0) | ||
k_bias, v_bias = torch.chunk( | ||
state_dict.pop(f"controlnet.{depth}.copied_block.cross_attn.kv_linear.bias"), 2, dim=0 | ||
) | ||
|
||
converted_state_dict[f"transformer_blocks.{depth}.attn2.to_q.weight"] = q | ||
converted_state_dict[f"transformer_blocks.{depth}.attn2.to_q.bias"] = q_bias | ||
converted_state_dict[f"transformer_blocks.{depth}.attn2.to_k.weight"] = k | ||
converted_state_dict[f"transformer_blocks.{depth}.attn2.to_k.bias"] = k_bias | ||
converted_state_dict[f"transformer_blocks.{depth}.attn2.to_v.weight"] = v | ||
converted_state_dict[f"transformer_blocks.{depth}.attn2.to_v.bias"] = v_bias | ||
|
||
converted_state_dict[f"transformer_blocks.{depth}.attn2.to_out.0.weight"] = state_dict.pop( | ||
f"controlnet.{depth}.copied_block.cross_attn.proj.weight" | ||
) | ||
converted_state_dict[f"transformer_blocks.{depth}.attn2.to_out.0.bias"] = state_dict.pop( | ||
f"controlnet.{depth}.copied_block.cross_attn.proj.bias" | ||
) | ||
|
||
# ControlNet After Projection | ||
converted_state_dict[f"controlnet_blocks.{depth}.weight"] = state_dict.pop( | ||
f"controlnet.{depth}.after_proj.weight" | ||
) | ||
converted_state_dict[f"controlnet_blocks.{depth}.bias"] = state_dict.pop(f"controlnet.{depth}.after_proj.bias") | ||
|
||
# ControlNet | ||
with CTX(): | ||
controlnet = SanaControlNetModel( | ||
num_attention_heads=model_kwargs[args.model_type]["num_attention_heads"], | ||
attention_head_dim=model_kwargs[args.model_type]["attention_head_dim"], | ||
num_layers=model_kwargs[args.model_type]["num_layers"], | ||
num_cross_attention_heads=model_kwargs[args.model_type]["num_cross_attention_heads"], | ||
cross_attention_head_dim=model_kwargs[args.model_type]["cross_attention_head_dim"], | ||
cross_attention_dim=model_kwargs[args.model_type]["cross_attention_dim"], | ||
caption_channels=2304, | ||
sample_size=args.image_size // 32, | ||
interpolation_scale=interpolation_scale[args.image_size], | ||
) | ||
|
||
if is_accelerate_available(): | ||
load_model_dict_into_meta(controlnet, converted_state_dict) | ||
else: | ||
controlnet.load_state_dict(converted_state_dict, strict=True, assign=True) | ||
|
||
num_model_params = sum(p.numel() for p in controlnet.parameters()) | ||
print(f"Total number of controlnet parameters: {num_model_params}") | ||
|
||
controlnet = controlnet.to(weight_dtype) | ||
controlnet.load_state_dict(converted_state_dict, strict=True) | ||
|
||
print(f"Saving Sana ControlNet in Diffusers format in {args.dump_path}.") | ||
controlnet.save_pretrained(args.dump_path) | ||
|
||
|
||
DTYPE_MAPPING = { | ||
"fp32": torch.float32, | ||
"fp16": torch.float16, | ||
"bf16": torch.bfloat16, | ||
} | ||
|
||
VARIANT_MAPPING = { | ||
"fp32": None, | ||
"fp16": "fp16", | ||
"bf16": "bf16", | ||
} | ||
|
||
|
||
if __name__ == "__main__": | ||
parser = argparse.ArgumentParser() | ||
|
||
parser.add_argument( | ||
"--orig_ckpt_path", default=None, type=str, required=True, help="Path to the checkpoint to convert." | ||
) | ||
parser.add_argument( | ||
"--image_size", | ||
default=1024, | ||
type=int, | ||
choices=[512, 1024, 2048, 4096], | ||
required=False, | ||
help="Image size of pretrained model, 512, 1024, 2048 or 4096.", | ||
) | ||
parser.add_argument( | ||
"--model_type", | ||
default="SanaMS_1600M_P1_ControlNet_D7", | ||
type=str, | ||
choices=["SanaMS_1600M_P1_ControlNet_D7", "SanaMS_600M_P1_ControlNet_D7"], | ||
) | ||
parser.add_argument("--dump_path", default=None, type=str, required=True, help="Path to the output pipeline.") | ||
parser.add_argument("--dtype", default="fp16", type=str, choices=["fp32", "fp16", "bf16"], help="Weight dtype.") | ||
|
||
args = parser.parse_args() | ||
|
||
model_kwargs = { | ||
"SanaMS_1600M_P1_ControlNet_D7": { | ||
"num_attention_heads": 70, | ||
"attention_head_dim": 32, | ||
"num_cross_attention_heads": 20, | ||
"cross_attention_head_dim": 112, | ||
"cross_attention_dim": 2240, | ||
"num_layers": 7, | ||
}, | ||
"SanaMS_600M_P1_ControlNet_D7": { | ||
"num_attention_heads": 36, | ||
"attention_head_dim": 32, | ||
"num_cross_attention_heads": 16, | ||
"cross_attention_head_dim": 72, | ||
"cross_attention_dim": 1152, | ||
"num_layers": 7, | ||
}, | ||
} | ||
|
||
device = "cuda" if torch.cuda.is_available() else "cpu" | ||
weight_dtype = DTYPE_MAPPING[args.dtype] | ||
variant = VARIANT_MAPPING[args.dtype] | ||
|
||
main(args) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.