-
Notifications
You must be signed in to change notification settings - Fork 6.6k
[wip] [core] introduce pipeline-specific mixins to hold common methods #12322
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
Closed
Closed
Changes from 7 commits
Commits
Show all changes
76 commits
Select commit
Hold shift + click to select a range
d47d60f
up
sayakpaul 3698473
up
sayakpaul 13cf2b0
up
sayakpaul 9df6c2f
remove more.
sayakpaul c9a9559
Merge branch 'main' into qwen-pipeline-mixin
sayakpaul d7ef6a0
Merge branch 'main' into qwen-pipeline-mixin
sayakpaul 435a8c0
up
sayakpaul b2f0ff7
Merge branch 'main' into qwen-pipeline-mixin
sayakpaul d684d46
Merge branch 'main' into qwen-pipeline-mixin
sayakpaul 78f292e
propgate changes for qwenimagedit plus.
sayakpaul 5b3295a
apply to flux
sayakpaul a2b7de3
Merge branch 'main' into qwen-pipeline-mixin
sayakpaul 9fecdc9
up
sayakpaul fc87f40
Merge branch 'main' into qwen-pipeline-mixin
sayakpaul c5e9a4a
Merge branch 'main' into qwen-pipeline-mixin
sayakpaul 8885a13
Merge branch 'main' into qwen-pipeline-mixin
sayakpaul 8832dee
Merge branch 'main' into qwen-pipeline-mixin
sayakpaul 8ca0fa8
Merge branch 'main' into qwen-pipeline-mixin
sayakpaul 35dd13c
Merge branch 'main' into qwen-pipeline-mixin
sayakpaul 72fc6ad
Merge branch 'main' into qwen-pipeline-mixin
sayakpaul 8048623
move some methods to pipeline specific stuff.
sayakpaul debafc6
up
sayakpaul c12a61f
up
sayakpaul 7c9dc97
up
sayakpaul ef67154
copy
sayakpaul 9322997
remove some more.
sayakpaul c8176bf
up
sayakpaul 54adb21
sdxl.
sayakpaul 4839692
remove sdxl related duplications.
sayakpaul db38c47
up
sayakpaul 6c0d55d
up
sayakpaul d13e6c0
Merge branch 'main' into qwen-pipeline-mixin
sayakpaul b1a8835
Merge branch 'main' into qwen-pipeline-mixin
sayakpaul 89ebea4
up
sayakpaul 4bd7dd5
up
sayakpaul 755dc49
stable diffusion og.
sayakpaul 41c5921
stable diffusion og.
sayakpaul 2d4f144
up
sayakpaul abace05
up
sayakpaul 5f8a9b6
up
sayakpaul 6ac18d0
more
sayakpaul 64eaf85
up
sayakpaul 1579a83
up
sayakpaul 511c7a4
up
sayakpaul b3b11b5
up
sayakpaul ffc9562
Merge branch 'main' into qwen-pipeline-mixin
sayakpaul c6fc910
p
sayakpaul 15e3a0f
Revert "p"
sayakpaul 8094f66
up
sayakpaul 57cf1b4
up
sayakpaul d8247cf
up
sayakpaul 01f488e
Merge branch 'main' into qwen-pipeline-mixin
sayakpaul e3d6945
up
sayakpaul b9be438
up
sayakpaul d456b5d
up
sayakpaul 51fbe6a
up
sayakpaul ce43e58
up
sayakpaul 6cf9c6e
Merge branch 'main' into qwen-pipeline-mixin
sayakpaul e326b25
Merge branch 'main' into qwen-pipeline-mixin
sayakpaul e1ac8fd
make fix-copies
sayakpaul 16d67c4
resolve conflicts for now, refactor again later in a bit.
sayakpaul 3be4b01
remove methods again
sayakpaul 6e05c21
remove.
sayakpaul 10d798a
fix
sayakpaul cf3053b
Merge branch 'main' into qwen-pipeline-mixin
sayakpaul be58660
remove fluxcontrolmixin
sayakpaul 044392d
up
sayakpaul 6d88119
path change for StableDiffusionLoraLoaderMixin
sayakpaul b4432ff
Revert "path change for StableDiffusionLoraLoaderMixin"
sayakpaul e122079
Revert "up"
sayakpaul 131ea16
Merge branch 'main' into qwen-pipeline-mixin
sayakpaul e5c40f4
uo
sayakpaul a6d5c4d
up
sayakpaul 69927d9
Merge branch 'main' into qwen-pipeline-mixin
sayakpaul 9f9eb6a
up
sayakpaul 14f51c5
up
sayakpaul 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
293 changes: 293 additions & 0 deletions
293
src/diffusers/pipelines/qwenimage/pipeline_qwen_utils.py
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,293 @@ | ||
| # Copyright 2025 Qwen-Image Team and 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. | ||
|
|
||
| import math | ||
| from typing import List, Optional, Union | ||
|
|
||
| import torch | ||
|
|
||
| from ...utils import deprecate | ||
|
|
||
|
|
||
| class QwenImageMixin: | ||
| @property | ||
| def guidance_scale(self): | ||
| return self._guidance_scale | ||
|
|
||
| @property | ||
| def attention_kwargs(self): | ||
| return self._attention_kwargs | ||
|
|
||
| @property | ||
| def num_timesteps(self): | ||
| return self._num_timesteps | ||
|
|
||
| @property | ||
| def current_timestep(self): | ||
| return self._current_timestep | ||
|
|
||
| @property | ||
| def interrupt(self): | ||
| return self._interrupt | ||
|
|
||
| def enable_vae_slicing(self): | ||
| r""" | ||
| Enable sliced VAE decoding. When this option is enabled, the VAE will split the input tensor in slices to | ||
| compute decoding in several steps. This is useful to save some memory and allow larger batch sizes. | ||
| """ | ||
| depr_message = f"Calling `enable_vae_slicing()` on a `{self.__class__.__name__}` is deprecated and this method will be removed in a future version. Please use `pipe.vae.enable_slicing()`." | ||
| deprecate( | ||
| "enable_vae_slicing", | ||
| "0.40.0", | ||
| depr_message, | ||
| ) | ||
| self.vae.enable_slicing() | ||
|
|
||
| def disable_vae_slicing(self): | ||
| r""" | ||
| Disable sliced VAE decoding. If `enable_vae_slicing` was previously enabled, this method will go back to | ||
| computing decoding in one step. | ||
| """ | ||
| depr_message = f"Calling `disable_vae_slicing()` on a `{self.__class__.__name__}` is deprecated and this method will be removed in a future version. Please use `pipe.vae.disable_slicing()`." | ||
| deprecate( | ||
| "disable_vae_slicing", | ||
| "0.40.0", | ||
| depr_message, | ||
| ) | ||
| self.vae.disable_slicing() | ||
|
|
||
| def enable_vae_tiling(self): | ||
| r""" | ||
| Enable tiled VAE decoding. When this option is enabled, the VAE will split the input tensor into tiles to | ||
| compute decoding and encoding in several steps. This is useful for saving a large amount of memory and to allow | ||
| processing larger images. | ||
| """ | ||
| depr_message = f"Calling `enable_vae_tiling()` on a `{self.__class__.__name__}` is deprecated and this method will be removed in a future version. Please use `pipe.vae.enable_tiling()`." | ||
| deprecate( | ||
| "enable_vae_tiling", | ||
| "0.40.0", | ||
| depr_message, | ||
| ) | ||
| self.vae.enable_tiling() | ||
|
|
||
| def disable_vae_tiling(self): | ||
| r""" | ||
| Disable tiled VAE decoding. If `enable_vae_tiling` was previously enabled, this method will go back to | ||
| computing decoding in one step. | ||
| """ | ||
| depr_message = f"Calling `disable_vae_tiling()` on a `{self.__class__.__name__}` is deprecated and this method will be removed in a future version. Please use `pipe.vae.disable_tiling()`." | ||
| deprecate( | ||
| "disable_vae_tiling", | ||
| "0.40.0", | ||
| depr_message, | ||
| ) | ||
| self.vae.disable_tiling() | ||
|
|
||
| def _extract_masked_hidden(self, hidden_states: torch.Tensor, mask: torch.Tensor): | ||
| bool_mask = mask.bool() | ||
| valid_lengths = bool_mask.sum(dim=1) | ||
| selected = hidden_states[bool_mask] | ||
| split_result = torch.split(selected, valid_lengths.tolist(), dim=0) | ||
|
|
||
| return split_result | ||
|
|
||
| def _get_qwen_prompt_embeds( | ||
| self, | ||
| prompt: Union[str, List[str]], | ||
| image: Optional[torch.Tensor] = None, | ||
| device: Optional[torch.device] = None, | ||
| dtype: Optional[torch.dtype] = None, | ||
| ): | ||
| device = device or self._execution_device | ||
| dtype = dtype or self.text_encoder.dtype | ||
| prompt = [prompt] if isinstance(prompt, str) else prompt | ||
|
|
||
| template = self.prompt_template_encode | ||
| drop_idx = self.prompt_template_encode_start_idx | ||
| txt = [template.format(e) for e in prompt] | ||
| use_multimodal = image is not None and hasattr(self, "processor") | ||
|
|
||
| if use_multimodal: | ||
| # --- Multimodal (text+image) --- | ||
| model_inputs = self.processor( | ||
| text=txt, | ||
| images=image, | ||
| padding=True, | ||
| return_tensors="pt", | ||
| ).to(device) | ||
|
|
||
| outputs = self.text_encoder( | ||
| input_ids=model_inputs.input_ids, | ||
| attention_mask=model_inputs.attention_mask, | ||
| pixel_values=model_inputs.pixel_values, | ||
| image_grid_thw=model_inputs.image_grid_thw, | ||
| output_hidden_states=True, | ||
| ) | ||
| hidden_states = outputs.hidden_states[-1] | ||
| attn_mask = model_inputs.attention_mask | ||
| else: | ||
| # --- Text-only --- | ||
| txt_tokens = self.tokenizer( | ||
| txt, | ||
| max_length=self.tokenizer_max_length + drop_idx, | ||
| padding=True, | ||
| truncation=True, | ||
| return_tensors="pt", | ||
| ).to(device) | ||
|
|
||
| outputs = self.text_encoder( | ||
| input_ids=txt_tokens.input_ids, | ||
| attention_mask=txt_tokens.attention_mask, | ||
| output_hidden_states=True, | ||
| ) | ||
| hidden_states = outputs.hidden_states[-1] | ||
| attn_mask = txt_tokens.attention_mask | ||
|
|
||
| split_hidden_states = self._extract_masked_hidden(hidden_states, attn_mask) | ||
| split_hidden_states = [e[drop_idx:] for e in split_hidden_states] | ||
|
|
||
| attn_mask_list = [torch.ones(e.size(0), dtype=torch.long, device=e.device) for e in split_hidden_states] | ||
| max_seq_len = max(e.size(0) for e in split_hidden_states) | ||
|
|
||
| prompt_embeds = torch.stack( | ||
| [torch.cat([u, u.new_zeros(max_seq_len - u.size(0), u.size(1))]) for u in split_hidden_states] | ||
| ) | ||
| encoder_attention_mask = torch.stack( | ||
| [torch.cat([u, u.new_zeros(max_seq_len - u.size(0))]) for u in attn_mask_list] | ||
| ) | ||
|
|
||
| prompt_embeds = prompt_embeds.to(dtype=dtype, device=device) | ||
| return prompt_embeds, encoder_attention_mask | ||
|
|
||
| @staticmethod | ||
| def _pack_latents(latents, batch_size, num_channels_latents, height, width): | ||
| latents = latents.view(batch_size, num_channels_latents, height // 2, 2, width // 2, 2) | ||
| latents = latents.permute(0, 2, 4, 1, 3, 5) | ||
| latents = latents.reshape(batch_size, (height // 2) * (width // 2), num_channels_latents * 4) | ||
|
|
||
| return latents | ||
|
|
||
| @staticmethod | ||
| def _unpack_latents(latents, height, width, vae_scale_factor): | ||
| batch_size, num_patches, channels = latents.shape | ||
|
|
||
| # VAE applies 8x compression on images but we must also account for packing which requires | ||
| # latent height and width to be divisible by 2. | ||
| height = 2 * (int(height) // (vae_scale_factor * 2)) | ||
| width = 2 * (int(width) // (vae_scale_factor * 2)) | ||
|
|
||
| latents = latents.view(batch_size, height // 2, width // 2, channels // 4, 2, 2) | ||
| latents = latents.permute(0, 3, 1, 4, 2, 5) | ||
|
|
||
| latents = latents.reshape(batch_size, channels // (2 * 2), 1, height, width) | ||
|
|
||
| return latents | ||
|
|
||
|
|
||
| class QwenImagePipelineMixin(QwenImageMixin): | ||
sayakpaul marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| def encode_prompt( | ||
|
Member
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Only differing |
||
| self, | ||
| prompt: Union[str, List[str]], | ||
| device: Optional[torch.device] = None, | ||
| num_images_per_prompt: int = 1, | ||
| prompt_embeds: Optional[torch.Tensor] = None, | ||
| prompt_embeds_mask: Optional[torch.Tensor] = None, | ||
| max_sequence_length: int = 1024, | ||
| ): | ||
| r""" | ||
|
|
||
| Args: | ||
| prompt (`str` or `List[str]`, *optional*): | ||
| prompt to be encoded | ||
| device: (`torch.device`): | ||
| torch device | ||
| num_images_per_prompt (`int`): | ||
| number of images that should be generated per prompt | ||
| prompt_embeds (`torch.Tensor`, *optional*): | ||
| Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not | ||
| provided, text embeddings will be generated from `prompt` input argument. | ||
| prompt_embeds_mask (`torch.Tensor`, *optional*): Pre-generation masks. | ||
| max_sequence_length (`int`): Maximum sequence length to use. | ||
| """ | ||
| device = device or self._execution_device | ||
|
|
||
| prompt = [prompt] if isinstance(prompt, str) else prompt | ||
| batch_size = len(prompt) if prompt_embeds is None else prompt_embeds.shape[0] | ||
|
|
||
| if prompt_embeds is None: | ||
| prompt_embeds, prompt_embeds_mask = self._get_qwen_prompt_embeds(prompt, device) | ||
|
|
||
| prompt_embeds = prompt_embeds[:, :max_sequence_length] | ||
| prompt_embeds_mask = prompt_embeds_mask[:, :max_sequence_length] | ||
|
|
||
| _, seq_len, _ = prompt_embeds.shape | ||
| prompt_embeds = prompt_embeds.repeat(1, num_images_per_prompt, 1) | ||
| prompt_embeds = prompt_embeds.view(batch_size * num_images_per_prompt, seq_len, -1) | ||
| prompt_embeds_mask = prompt_embeds_mask.repeat(1, num_images_per_prompt, 1) | ||
| prompt_embeds_mask = prompt_embeds_mask.view(batch_size * num_images_per_prompt, seq_len) | ||
|
|
||
| return prompt_embeds, prompt_embeds_mask | ||
|
|
||
|
|
||
| class QwenImageEditPipelineMixin(QwenImageMixin): | ||
| def encode_prompt( | ||
| self, | ||
| prompt: Union[str, List[str]], | ||
| image: Optional[torch.Tensor] = None, | ||
| device: Optional[torch.device] = None, | ||
| num_images_per_prompt: int = 1, | ||
| prompt_embeds: Optional[torch.Tensor] = None, | ||
| prompt_embeds_mask: Optional[torch.Tensor] = None, | ||
| max_sequence_length: int = 1024, | ||
| ): | ||
| r""" | ||
|
|
||
| Args: | ||
| prompt (`str` or `List[str]`, *optional*): | ||
| prompt to be encoded | ||
| image (`torch.Tensor`, *optional*): | ||
| image to be encoded | ||
| device: (`torch.device`): | ||
| torch device | ||
| num_images_per_prompt (`int`): | ||
| number of images that should be generated per prompt | ||
| prompt_embeds (`torch.Tensor`, *optional*): | ||
| Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not | ||
| provided, text embeddings will be generated from `prompt` input argument. | ||
| """ | ||
| device = device or self._execution_device | ||
|
|
||
| prompt = [prompt] if isinstance(prompt, str) else prompt | ||
| batch_size = len(prompt) if prompt_embeds is None else prompt_embeds.shape[0] | ||
|
|
||
| if prompt_embeds is None: | ||
| prompt_embeds, prompt_embeds_mask = self._get_qwen_prompt_embeds(prompt, image, device) | ||
|
|
||
| _, seq_len, _ = prompt_embeds.shape | ||
| prompt_embeds = prompt_embeds.repeat(1, num_images_per_prompt, 1) | ||
| prompt_embeds = prompt_embeds.view(batch_size * num_images_per_prompt, seq_len, -1) | ||
| prompt_embeds_mask = prompt_embeds_mask.repeat(1, num_images_per_prompt, 1) | ||
| prompt_embeds_mask = prompt_embeds_mask.view(batch_size * num_images_per_prompt, seq_len) | ||
|
|
||
| return prompt_embeds, prompt_embeds_mask | ||
|
|
||
|
|
||
| def calculate_dimensions(target_area, ratio): | ||
| width = math.sqrt(target_area * ratio) | ||
| height = width / ratio | ||
|
|
||
| width = round(width / 32) * 32 | ||
| height = round(height / 32) * 32 | ||
|
|
||
| return width, height, None | ||
Oops, something went wrong.
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.
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.
Decided to unify it to further reduce LOC. It's a private method anyway, so, we should be safe.