-
Notifications
You must be signed in to change notification settings - Fork 6.6k
Z-Image-Turbo ControlNet #12792
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
base: main
Are you sure you want to change the base?
Z-Image-Turbo ControlNet #12792
Conversation
|
|
||
| def forward( | ||
| self, | ||
| transformer: ZImageTransformer2DModel, |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
let's not pass transformer as an input
given that there are some shared layers, we can consider these two alternative design:
- option1: pre-computed shared stuff inside the pipeline, you can add a method to the
ZImageTransformer2DModelto be used by controlnet if it makes things easier (but no need to change the transformer code) e.g. inside pipeline
... = self.transformer.prepare_inputs(...)
controlnet_block_samples = self.controlnet(control_image=control_image, ...) - Option2: we can try to inject controlnet into transformer inside
__init__. similar to https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/animatediff/pipeline_animatediff.py#L140. Basically create a model that combine controlnet + transformer
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Which option would you prefer?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
let's try option 2
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Done
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Hi @hlky , I managed to get your PR working locally, but I modified it to work differently. I unified the weights of the base model's transformer with the transformer from the controlnet model. Initially, I did this because I wanted to generate a unified gguf, since when you load the gguf from_single_file you wouldn't be able to load two transformers at the same time. So I unified them and tested with a single gguf and also with a single pretrained model, and it worked. If this is an easier strategy for users, it will only be necessary to upload a different model to Spaces, such as z-image-turbo-control-hf for e.g.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Hi @elismasilva, I see, currently if we used gguf for the transformer and controlnet this would not be applied to the combined model when it's created in the pipeline __init__, I think we can detect the quantization_config and pass that along to the combined model which should fix that, we can also add from_single_file support, a conversion script, etc. if users prefer to have a single weight file, but I did find that injecting the controlnet in __init__ as suggested by @yiyixuxu has increased cpu ram usage from creating the combined transformer+controlnet while the non-combined versions are also loaded, so I wonder if we should go for option 1 instead, we can still add from_single_file support to the controlnet for gguf in that case. Let's wait for some more input from YiYi on how best to proceed.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I think the init technique in this case is only valid if the person is going to use the pipeline as a whole. Consider that the ControlNet transformer is not an independent model like those in SDXL, for example; it's an additional weighting of the transformer. So I believe it should be the transformer model's responsibility to append these weights, in case someone tries to load the transformer model in isolation, as is possible, and also considering modular diffusers.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
in case someone tries to load the transformer model in isolation, as is possible, and also considering modular diffusers.
are you talking about this?
transformer = ZImageTransformer2DModel.from_pretrained(...)
controlnet = ZImageControlNetModel.from_pretrained(...)
pipe = ZImageControlNetPipeline.from_pretrained(
"Tongyi-MAI/Z-Image-Turbo", controlnet=controlnet, transforfmer=transformer, torch_dtype=torch.bfloat16
)I believe this PR already handle this use case, no? looking at its __init__
if isinstance(transformer, ZImageTransformer2DModel):
transformer = ZImageControlTransformer2DModel.from_controlnet(transformer, controlnet)the memory situation isn't ideal, but I think we should be able avoid it, I made a few suggestsion in the PR let's test it out to see if it works
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
in case someone tries to load the transformer model in isolation, as is possible, and also considering modular diffusers.
are you talking about this?
Ah yes, but I had something else in mind; I was thinking about eliminating the "controlnet" object as an intermediary for loading in the transformer's from_controlnet(), I thought that ControlNet could just be another internal module in the same model, but for that to happen we would have to rewrite practically the entire from_pretrained() function to load all the weights in meta device (I believe that's why there's an increase in memory usage during later loading). But anyway, the suggestion in option 3 is also good; you'll remove the things that are currently mixed together, will give a forward() call and a purpose for the controlnet model to exist, but in this case, there would now be two predictions in the pipeline, and the transformer would receive the samples from the controlnet.
|
How do we support control modes other than Canny? Other control modes still produce poor results—here’s what I got when I tried the HED example from the demo with prompt “A man holding a bottle” and input image. |
Hi, I ran a test with your image and got the following result:Result 1: Result 2:
To achieve a realistic effect, you will need to apply the Hires.Fix technique to the image after it has been generated: |
|
The docs for this PR live here. All of your documentation changes will be reflected on that endpoint. The docs are available until 30 days after the last update. |
yiyixuxu
left a comment
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
thanks, I left some comments!
| return original_state_dict | ||
|
|
||
|
|
||
| def convert_z_image_controlnet_checkpoint_to_diffusers(original_state_dict): |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
there is no conversion going on? maybe we could just load from the original repo using from_single_file so we don't need to host this seperately
| ) | ||
|
|
||
|
|
||
| class ZImageControlTransformerBlock(ZImageTransformerBlock): |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
let's not inherit from ZImageTransformerBlock, we can just copy over, modify and make a notes about it
| expected_kwargs, optional_kwargs = cls._get_signature_keys(cls) | ||
| config = FrozenDict({k: config.get(k) for k in config if k in expected_kwargs or k in optional_kwargs}) | ||
| config["_class_name"] = cls.__name__ | ||
| model = cls.from_config(config) |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
| model = cls.from_config(config) | |
| with init_empty_weights(): | |
| model = cls.from_config(config) |
| return model | ||
|
|
||
| for key, all_x_embedder in transformer.all_x_embedder.items(): | ||
| model.all_x_embedder[key].load_state_dict(all_x_embedder.state_dict()) |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Can you directly assign these modules instead? This avoids additional memory at loading since we discard the original transformer/controlnet after this anyway.
|
|
||
| def forward( | ||
| self, | ||
| transformer: ZImageTransformer2DModel, |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
in case someone tries to load the transformer model in isolation, as is possible, and also considering modular diffusers.
are you talking about this?
transformer = ZImageTransformer2DModel.from_pretrained(...)
controlnet = ZImageControlNetModel.from_pretrained(...)
pipe = ZImageControlNetPipeline.from_pretrained(
"Tongyi-MAI/Z-Image-Turbo", controlnet=controlnet, transforfmer=transformer, torch_dtype=torch.bfloat16
)I believe this PR already handle this use case, no? looking at its __init__
if isinstance(transformer, ZImageTransformer2DModel):
transformer = ZImageControlTransformer2DModel.from_controlnet(transformer, controlnet)the memory situation isn't ideal, but I think we should be able avoid it, I made a few suggestsion in the PR let's test it out to see if it works
|
ohm I thought about this a bit more. I think we can should try an Option 3 that's a middle ground between Option 1 and 2: instead of combining everything into one model, the controlnet only load shared layers from the transformer. so your class ZImageControlNetModel:
@classmethod
def from_transformer(cls, controlnet, transformer):
....
controlnet.t_embedder = transformer.t_embedder
controlnet.all_x_embedder = transformer.all_x_embedder
controlnet.cap_embedder = transformer.cap_embedder
return controlnetin pipeline, we still have both controlnet and transformer components and should work similarly to our other contorlnet pipelines what do you think? |
| elif "config_create_fn" in mapping_functions: | ||
| config_create_fn = mapping_functions["config_create_fn"] | ||
| diffusers_model_config = config_create_fn() |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Normally the config is from the Hub, without hosting the Diffusers format weights this seemed a good option, WDYT? Could be useful in other circumstances, like deriving the config from the weights. Alternative would perhaps be making PR to Hub repo with the config?
|
import torch
from diffusers import ZImageControlNetModel
from huggingface_hub import hf_hub_download
controlnet = ZImageControlNetModel.from_single_file(
hf_hub_download(
"alibaba-pai/Z-Image-Turbo-Fun-Controlnet-Union",
filename="Z-Image-Turbo-Fun-Controlnet-Union.safetensors",
),
torch_dtype=torch.bfloat16,
) |
@hlky If you need a ControlNet gguf to test the loading as well, I can try to generate one for you. I'm currently testing this model and trying build an image restoration pipeline, Here is the link to the unified model I mentioned earlier If you want to check it out, go to https://huggingface.co/elismasilva/z-image-control-turbo-unified, but I'll switch to using your implementation later. |
yiyixuxu
left a comment
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
thanks @hlky
looks good to me, I left some small feedbacks, mainly:
- not import class from z-transformer file, it gets messy to import from one model file to another, so let's not do it for now. That being said I think it makes seense to reuse layers in base model for controlnet/ip-adapter and such so we may do that in the future
- add missing
#Copied from statement
| from ..controlnets.controlnet import zero_module | ||
| from ..modeling_utils import ModelMixin | ||
| from ..transformers.transformer_z_image import ( | ||
| ADALN_EMBED_DIM, |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Can we use #Copied from for these shared layers, instead imports?
at least for now, in the future, we may restructure how we arrange our model code and put the controlnet et all in the same folder as the base model and then maybe we can do it differently
| return controlnet | ||
|
|
||
| @staticmethod | ||
| def create_coordinate_grid(size, start=None, device=None): |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
can we add a #Coped from?
| grids = torch.meshgrid(axes, indexing="ij") | ||
| return torch.stack(grids, dim=-1) | ||
|
|
||
| def patchify_and_embed( |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
here too if it's copied from the z-image transformer
|
cc @DN6 can you take a look for the single file? |







What does this PR do?
In the original code this is not a typical ControlNet, it is integrated into the
transformerand relies on operations performed in thetransformer's forward. In this PR we implement it as a typical ControlNet by duplicating the necessary operations from thetransformer's forward into the ControlNet's forward and passtransformertoZImageControlNetModel'sforwardto access the necessarytransformermodules, as a result this is perhaps a little slower than the original implementation, but it keeps things clean and in style.ZImageTransformer2DModelhas minimal changes,controlnet_block_samplesis introduced, this is aDict[int, torch.Tensor]returned fromZImageControlNetModelwhere theintis theZImageTransformer2DModellayersindex, this is another difference from typical ControlNet where every block has the ControlNet output applied.ZImageControlNetPipelinehas minimal changes, compared toZImagePipelineit addsprepare_imagefunction, addscontrol_imageandcontrolnet_conditioning_scaleparameters, prepares and encodescontrol_imageand callscontrolnetto obtaincontrolnet_block_sampleswhich are passed totransformer.control_guidance_start/control_guidance_endis not yet implemented.Test code
Output
Fixes #12769
Who can review?
Anyone in the community is free to review the PR once the tests have passed. Feel free to tag
members/contributors who may be interested in your PR.