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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) 2025 Bytedance Ltd. and/or its affiliates
|
| 2 |
+
# Copyright 2024 Black Forest Labs and The HuggingFace Team. All rights reserved.
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
|
| 16 |
+
from typing import Any, Callable, Dict, List, Optional, Union
|
| 17 |
+
|
| 18 |
+
import diffusers
|
| 19 |
+
import numpy as np
|
| 20 |
+
import torch
|
| 21 |
+
import torch.nn as nn
|
| 22 |
+
from diffusers import FluxPipeline
|
| 23 |
+
from diffusers.pipelines.flux.pipeline_flux import calculate_shift, retrieve_timesteps
|
| 24 |
+
from diffusers.pipelines.flux.pipeline_output import FluxPipelineOutput
|
| 25 |
+
from einops import repeat
|
| 26 |
+
from huggingface_hub import hf_hub_download
|
| 27 |
+
from safetensors.torch import load_file
|
| 28 |
+
|
| 29 |
+
from dreamo.transformer import flux_transformer_forward
|
| 30 |
+
from dreamo.utils import convert_flux_lora_to_diffusers
|
| 31 |
+
|
| 32 |
+
diffusers.models.transformers.transformer_flux.FluxTransformer2DModel.forward = flux_transformer_forward
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
def get_task_embedding_idx(task):
|
| 36 |
+
return 0
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
class DreamOPipeline(FluxPipeline):
|
| 40 |
+
def __init__(self, scheduler, vae, text_encoder, tokenizer, text_encoder_2, tokenizer_2, transformer):
|
| 41 |
+
super().__init__(scheduler, vae, text_encoder, tokenizer, text_encoder_2, tokenizer_2, transformer)
|
| 42 |
+
self.t5_embedding = nn.Embedding(10, 4096)
|
| 43 |
+
self.task_embedding = nn.Embedding(2, 3072)
|
| 44 |
+
self.idx_embedding = nn.Embedding(10, 3072)
|
| 45 |
+
|
| 46 |
+
def load_dreamo_model(self, device, use_turbo=True, version='v1.1'):
|
| 47 |
+
# download models and load file
|
| 48 |
+
hf_hub_download(repo_id='ByteDance/DreamO', filename='dreamo.safetensors', local_dir='models')
|
| 49 |
+
hf_hub_download(repo_id='ByteDance/DreamO', filename='dreamo_cfg_distill.safetensors', local_dir='models')
|
| 50 |
+
if version == 'v1':
|
| 51 |
+
hf_hub_download(repo_id='ByteDance/DreamO', filename='dreamo_quality_lora_pos.safetensors',
|
| 52 |
+
local_dir='models')
|
| 53 |
+
hf_hub_download(repo_id='ByteDance/DreamO', filename='dreamo_quality_lora_neg.safetensors',
|
| 54 |
+
local_dir='models')
|
| 55 |
+
quality_lora_pos = load_file('models/dreamo_quality_lora_pos.safetensors')
|
| 56 |
+
quality_lora_neg = load_file('models/dreamo_quality_lora_neg.safetensors')
|
| 57 |
+
elif version == 'v1.1':
|
| 58 |
+
hf_hub_download(repo_id='ByteDance/DreamO', filename='v1.1/dreamo_sft_lora.safetensors', local_dir='models')
|
| 59 |
+
hf_hub_download(repo_id='ByteDance/DreamO', filename='v1.1/dreamo_dpo_lora.safetensors', local_dir='models')
|
| 60 |
+
sft_lora = load_file('models/v1.1/dreamo_sft_lora.safetensors')
|
| 61 |
+
dpo_lora = load_file('models/v1.1/dreamo_dpo_lora.safetensors')
|
| 62 |
+
else:
|
| 63 |
+
raise ValueError(f'there is no {version}')
|
| 64 |
+
dreamo_lora = load_file('models/dreamo.safetensors')
|
| 65 |
+
cfg_distill_lora = load_file('models/dreamo_cfg_distill.safetensors')
|
| 66 |
+
|
| 67 |
+
# load embedding
|
| 68 |
+
self.t5_embedding.weight.data = dreamo_lora.pop('dreamo_t5_embedding.weight')[-10:]
|
| 69 |
+
self.task_embedding.weight.data = dreamo_lora.pop('dreamo_task_embedding.weight')
|
| 70 |
+
self.idx_embedding.weight.data = dreamo_lora.pop('dreamo_idx_embedding.weight')
|
| 71 |
+
self._prepare_t5()
|
| 72 |
+
|
| 73 |
+
# main lora
|
| 74 |
+
dreamo_diffuser_lora = convert_flux_lora_to_diffusers(dreamo_lora)
|
| 75 |
+
adapter_names = ['dreamo']
|
| 76 |
+
adapter_weights = [1]
|
| 77 |
+
self.load_lora_weights(dreamo_diffuser_lora, adapter_name='dreamo')
|
| 78 |
+
|
| 79 |
+
# cfg lora to avoid true image cfg
|
| 80 |
+
cfg_diffuser_lora = convert_flux_lora_to_diffusers(cfg_distill_lora)
|
| 81 |
+
self.load_lora_weights(cfg_diffuser_lora, adapter_name='cfg')
|
| 82 |
+
adapter_names.append('cfg')
|
| 83 |
+
adapter_weights.append(1)
|
| 84 |
+
|
| 85 |
+
# turbo lora to speed up (from 25+ step to 12 step)
|
| 86 |
+
if use_turbo:
|
| 87 |
+
self.load_lora_weights(
|
| 88 |
+
hf_hub_download(
|
| 89 |
+
"alimama-creative/FLUX.1-Turbo-Alpha", "diffusion_pytorch_model.safetensors", local_dir='models'
|
| 90 |
+
),
|
| 91 |
+
adapter_name='turbo',
|
| 92 |
+
)
|
| 93 |
+
adapter_names.append('turbo')
|
| 94 |
+
adapter_weights.append(1)
|
| 95 |
+
|
| 96 |
+
if version == 'v1':
|
| 97 |
+
# quality loras, one pos, one neg
|
| 98 |
+
quality_lora_pos = convert_flux_lora_to_diffusers(quality_lora_pos)
|
| 99 |
+
self.load_lora_weights(quality_lora_pos, adapter_name='quality_pos')
|
| 100 |
+
adapter_names.append('quality_pos')
|
| 101 |
+
adapter_weights.append(0.15)
|
| 102 |
+
quality_lora_neg = convert_flux_lora_to_diffusers(quality_lora_neg)
|
| 103 |
+
self.load_lora_weights(quality_lora_neg, adapter_name='quality_neg')
|
| 104 |
+
adapter_names.append('quality_neg')
|
| 105 |
+
adapter_weights.append(-0.8)
|
| 106 |
+
elif version == 'v1.1':
|
| 107 |
+
self.load_lora_weights(sft_lora, adapter_name='sft_lora')
|
| 108 |
+
adapter_names.append('sft_lora')
|
| 109 |
+
adapter_weights.append(1)
|
| 110 |
+
self.load_lora_weights(dpo_lora, adapter_name='dpo_lora')
|
| 111 |
+
adapter_names.append('dpo_lora')
|
| 112 |
+
adapter_weights.append(1.25)
|
| 113 |
+
|
| 114 |
+
self.set_adapters(adapter_names, adapter_weights)
|
| 115 |
+
self.fuse_lora(adapter_names=adapter_names, lora_scale=1)
|
| 116 |
+
self.unload_lora_weights()
|
| 117 |
+
|
| 118 |
+
self.t5_embedding = self.t5_embedding.to(device)
|
| 119 |
+
self.task_embedding = self.task_embedding.to(device)
|
| 120 |
+
self.idx_embedding = self.idx_embedding.to(device)
|
| 121 |
+
|
| 122 |
+
def _prepare_t5(self):
|
| 123 |
+
self.text_encoder_2.resize_token_embeddings(len(self.tokenizer_2))
|
| 124 |
+
num_new_token = 10
|
| 125 |
+
new_token_list = [f"[ref#{i}]" for i in range(1, 10)] + ["[res]"]
|
| 126 |
+
self.tokenizer_2.add_tokens(new_token_list, special_tokens=False)
|
| 127 |
+
self.text_encoder_2.resize_token_embeddings(len(self.tokenizer_2))
|
| 128 |
+
input_embedding = self.text_encoder_2.get_input_embeddings().weight.data
|
| 129 |
+
input_embedding[-num_new_token:] = self.t5_embedding.weight.data
|
| 130 |
+
|
| 131 |
+
@staticmethod
|
| 132 |
+
def _prepare_latent_image_ids(batch_size, height, width, device, dtype, start_height=0, start_width=0):
|
| 133 |
+
latent_image_ids = torch.zeros(height // 2, width // 2, 3)
|
| 134 |
+
latent_image_ids[..., 1] = latent_image_ids[..., 1] + torch.arange(height // 2)[:, None] + start_height
|
| 135 |
+
latent_image_ids[..., 2] = latent_image_ids[..., 2] + torch.arange(width // 2)[None, :] + start_width
|
| 136 |
+
|
| 137 |
+
latent_image_id_height, latent_image_id_width, latent_image_id_channels = latent_image_ids.shape
|
| 138 |
+
|
| 139 |
+
latent_image_ids = latent_image_ids[None, :].repeat(batch_size, 1, 1, 1)
|
| 140 |
+
latent_image_ids = latent_image_ids.reshape(
|
| 141 |
+
batch_size, latent_image_id_height * latent_image_id_width, latent_image_id_channels
|
| 142 |
+
)
|
| 143 |
+
|
| 144 |
+
return latent_image_ids.to(device=device, dtype=dtype)
|
| 145 |
+
|
| 146 |
+
@staticmethod
|
| 147 |
+
def _prepare_style_latent_image_ids(batch_size, height, width, device, dtype, start_height=0, start_width=0):
|
| 148 |
+
latent_image_ids = torch.zeros(height // 2, width // 2, 3)
|
| 149 |
+
latent_image_ids[..., 1] = latent_image_ids[..., 1] + start_height
|
| 150 |
+
latent_image_ids[..., 2] = latent_image_ids[..., 2] + start_width
|
| 151 |
+
|
| 152 |
+
latent_image_id_height, latent_image_id_width, latent_image_id_channels = latent_image_ids.shape
|
| 153 |
+
|
| 154 |
+
latent_image_ids = latent_image_ids[None, :].repeat(batch_size, 1, 1, 1)
|
| 155 |
+
latent_image_ids = latent_image_ids.reshape(
|
| 156 |
+
batch_size, latent_image_id_height * latent_image_id_width, latent_image_id_channels
|
| 157 |
+
)
|
| 158 |
+
|
| 159 |
+
return latent_image_ids.to(device=device, dtype=dtype)
|
| 160 |
+
|
| 161 |
+
@torch.no_grad()
|
| 162 |
+
def __call__(
|
| 163 |
+
self,
|
| 164 |
+
prompt: Union[str, List[str]] = None,
|
| 165 |
+
prompt_2: Optional[Union[str, List[str]]] = None,
|
| 166 |
+
negative_prompt: Union[str, List[str]] = None,
|
| 167 |
+
negative_prompt_2: Optional[Union[str, List[str]]] = None,
|
| 168 |
+
true_cfg_scale: float = 1.0,
|
| 169 |
+
true_cfg_start_step: int = 1,
|
| 170 |
+
true_cfg_end_step: int = 1,
|
| 171 |
+
height: Optional[int] = None,
|
| 172 |
+
width: Optional[int] = None,
|
| 173 |
+
num_inference_steps: int = 28,
|
| 174 |
+
sigmas: Optional[List[float]] = None,
|
| 175 |
+
guidance_scale: float = 3.5,
|
| 176 |
+
neg_guidance_scale: float = 3.5,
|
| 177 |
+
num_images_per_prompt: Optional[int] = 1,
|
| 178 |
+
generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
|
| 179 |
+
latents: Optional[torch.FloatTensor] = None,
|
| 180 |
+
prompt_embeds: Optional[torch.FloatTensor] = None,
|
| 181 |
+
pooled_prompt_embeds: Optional[torch.FloatTensor] = None,
|
| 182 |
+
negative_prompt_embeds: Optional[torch.FloatTensor] = None,
|
| 183 |
+
negative_pooled_prompt_embeds: Optional[torch.FloatTensor] = None,
|
| 184 |
+
output_type: Optional[str] = "pil",
|
| 185 |
+
return_dict: bool = True,
|
| 186 |
+
joint_attention_kwargs: Optional[Dict[str, Any]] = None,
|
| 187 |
+
callback_on_step_end: Optional[Callable[[int, int, Dict], None]] = None,
|
| 188 |
+
callback_on_step_end_tensor_inputs: List[str] = ["latents"],
|
| 189 |
+
max_sequence_length: int = 512,
|
| 190 |
+
ref_conds=None,
|
| 191 |
+
first_step_guidance_scale=3.5,
|
| 192 |
+
):
|
| 193 |
+
r"""
|
| 194 |
+
Function invoked when calling the pipeline for generation.
|
| 195 |
+
|
| 196 |
+
Args:
|
| 197 |
+
prompt (`str` or `List[str]`, *optional*):
|
| 198 |
+
The prompt or prompts to guide the image generation. If not defined, one has to pass `prompt_embeds`.
|
| 199 |
+
instead.
|
| 200 |
+
prompt_2 (`str` or `List[str]`, *optional*):
|
| 201 |
+
The prompt or prompts to be sent to `tokenizer_2` and `text_encoder_2`. If not defined, `prompt` is
|
| 202 |
+
will be used instead.
|
| 203 |
+
negative_prompt (`str` or `List[str]`, *optional*):
|
| 204 |
+
The prompt or prompts not to guide the image generation. If not defined, one has to pass
|
| 205 |
+
`negative_prompt_embeds` instead. Ignored when not using guidance (i.e., ignored if `true_cfg_scale` is
|
| 206 |
+
not greater than `1`).
|
| 207 |
+
negative_prompt_2 (`str` or `List[str]`, *optional*):
|
| 208 |
+
The prompt or prompts not to guide the image generation to be sent to `tokenizer_2` and
|
| 209 |
+
`text_encoder_2`. If not defined, `negative_prompt` is used in all the text-encoders.
|
| 210 |
+
true_cfg_scale (`float`, *optional*, defaults to 1.0):
|
| 211 |
+
When > 1.0 and a provided `negative_prompt`, enables true classifier-free guidance.
|
| 212 |
+
height (`int`, *optional*, defaults to self.unet.config.sample_size * self.vae_scale_factor):
|
| 213 |
+
The height in pixels of the generated image. This is set to 1024 by default for the best results.
|
| 214 |
+
width (`int`, *optional*, defaults to self.unet.config.sample_size * self.vae_scale_factor):
|
| 215 |
+
The width in pixels of the generated image. This is set to 1024 by default for the best results.
|
| 216 |
+
num_inference_steps (`int`, *optional*, defaults to 50):
|
| 217 |
+
The number of denoising steps. More denoising steps usually lead to a higher quality image at the
|
| 218 |
+
expense of slower inference.
|
| 219 |
+
sigmas (`List[float]`, *optional*):
|
| 220 |
+
Custom sigmas to use for the denoising process with schedulers which support a `sigmas` argument in
|
| 221 |
+
their `set_timesteps` method. If not defined, the default behavior when `num_inference_steps` is passed
|
| 222 |
+
will be used.
|
| 223 |
+
guidance_scale (`float`, *optional*, defaults to 3.5):
|
| 224 |
+
Guidance scale as defined in [Classifier-Free Diffusion Guidance](https://arxiv.org/abs/2207.12598).
|
| 225 |
+
`guidance_scale` is defined as `w` of equation 2. of [Imagen
|
| 226 |
+
Paper](https://arxiv.org/pdf/2205.11487.pdf). Guidance scale is enabled by setting `guidance_scale >
|
| 227 |
+
1`. Higher guidance scale encourages to generate images that are closely linked to the text `prompt`,
|
| 228 |
+
usually at the expense of lower image quality.
|
| 229 |
+
num_images_per_prompt (`int`, *optional*, defaults to 1):
|
| 230 |
+
The number of images to generate per prompt.
|
| 231 |
+
generator (`torch.Generator` or `List[torch.Generator]`, *optional*):
|
| 232 |
+
One or a list of [torch generator(s)](https://pytorch.org/docs/stable/generated/torch.Generator.html)
|
| 233 |
+
to make generation deterministic.
|
| 234 |
+
latents (`torch.FloatTensor`, *optional*):
|
| 235 |
+
Pre-generated noisy latents, sampled from a Gaussian distribution, to be used as inputs for image
|
| 236 |
+
generation. Can be used to tweak the same generation with different prompts. If not provided, a latents
|
| 237 |
+
tensor will ge generated by sampling using the supplied random `generator`.
|
| 238 |
+
prompt_embeds (`torch.FloatTensor`, *optional*):
|
| 239 |
+
Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not
|
| 240 |
+
provided, text embeddings will be generated from `prompt` input argument.
|
| 241 |
+
pooled_prompt_embeds (`torch.FloatTensor`, *optional*):
|
| 242 |
+
Pre-generated pooled text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting.
|
| 243 |
+
If not provided, pooled text embeddings will be generated from `prompt` input argument.
|
| 244 |
+
negative_prompt_embeds (`torch.FloatTensor`, *optional*):
|
| 245 |
+
Pre-generated negative text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
|
| 246 |
+
weighting. If not provided, negative_prompt_embeds will be generated from `negative_prompt` input
|
| 247 |
+
argument.
|
| 248 |
+
negative_pooled_prompt_embeds (`torch.FloatTensor`, *optional*):
|
| 249 |
+
Pre-generated negative pooled text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
|
| 250 |
+
weighting. If not provided, pooled negative_prompt_embeds will be generated from `negative_prompt`
|
| 251 |
+
input argument.
|
| 252 |
+
output_type (`str`, *optional*, defaults to `"pil"`):
|
| 253 |
+
The output format of the generate image. Choose between
|
| 254 |
+
[PIL](https://pillow.readthedocs.io/en/stable/): `PIL.Image.Image` or `np.array`.
|
| 255 |
+
return_dict (`bool`, *optional*, defaults to `True`):
|
| 256 |
+
Whether or not to return a [`~pipelines.flux.FluxPipelineOutput`] instead of a plain tuple.
|
| 257 |
+
joint_attention_kwargs (`dict`, *optional*):
|
| 258 |
+
A kwargs dictionary that if specified is passed along to the `AttentionProcessor` as defined under
|
| 259 |
+
`self.processor` in
|
| 260 |
+
[diffusers.models.attention_processor](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py).
|
| 261 |
+
callback_on_step_end (`Callable`, *optional*):
|
| 262 |
+
A function that calls at the end of each denoising steps during the inference. The function is called
|
| 263 |
+
with the following arguments: `callback_on_step_end(self: DiffusionPipeline, step: int, timestep: int,
|
| 264 |
+
callback_kwargs: Dict)`. `callback_kwargs` will include a list of all tensors as specified by
|
| 265 |
+
`callback_on_step_end_tensor_inputs`.
|
| 266 |
+
callback_on_step_end_tensor_inputs (`List`, *optional*):
|
| 267 |
+
The list of tensor inputs for the `callback_on_step_end` function. The tensors specified in the list
|
| 268 |
+
will be passed as `callback_kwargs` argument. You will only be able to include variables listed in the
|
| 269 |
+
`._callback_tensor_inputs` attribute of your pipeline class.
|
| 270 |
+
max_sequence_length (`int` defaults to 512): Maximum sequence length to use with the `prompt`.
|
| 271 |
+
|
| 272 |
+
Examples:
|
| 273 |
+
|
| 274 |
+
Returns:
|
| 275 |
+
[`~pipelines.flux.FluxPipelineOutput`] or `tuple`: [`~pipelines.flux.FluxPipelineOutput`] if `return_dict`
|
| 276 |
+
is True, otherwise a `tuple`. When returning a tuple, the first element is a list with the generated
|
| 277 |
+
images.
|
| 278 |
+
"""
|
| 279 |
+
|
| 280 |
+
height = height or self.default_sample_size * self.vae_scale_factor
|
| 281 |
+
width = width or self.default_sample_size * self.vae_scale_factor
|
| 282 |
+
|
| 283 |
+
# 1. Check inputs. Raise error if not correct
|
| 284 |
+
self.check_inputs(
|
| 285 |
+
prompt,
|
| 286 |
+
prompt_2,
|
| 287 |
+
height,
|
| 288 |
+
width,
|
| 289 |
+
prompt_embeds=prompt_embeds,
|
| 290 |
+
pooled_prompt_embeds=pooled_prompt_embeds,
|
| 291 |
+
callback_on_step_end_tensor_inputs=callback_on_step_end_tensor_inputs,
|
| 292 |
+
max_sequence_length=max_sequence_length,
|
| 293 |
+
)
|
| 294 |
+
|
| 295 |
+
self._guidance_scale = guidance_scale
|
| 296 |
+
self._joint_attention_kwargs = joint_attention_kwargs
|
| 297 |
+
self._current_timestep = None
|
| 298 |
+
self._interrupt = False
|
| 299 |
+
|
| 300 |
+
# 2. Define call parameters
|
| 301 |
+
if prompt is not None and isinstance(prompt, str):
|
| 302 |
+
batch_size = 1
|
| 303 |
+
elif prompt is not None and isinstance(prompt, list):
|
| 304 |
+
batch_size = len(prompt)
|
| 305 |
+
else:
|
| 306 |
+
batch_size = prompt_embeds.shape[0]
|
| 307 |
+
|
| 308 |
+
device = self._execution_device
|
| 309 |
+
|
| 310 |
+
lora_scale = (
|
| 311 |
+
self.joint_attention_kwargs.get("scale", None) if self.joint_attention_kwargs is not None else None
|
| 312 |
+
)
|
| 313 |
+
has_neg_prompt = negative_prompt is not None or (
|
| 314 |
+
negative_prompt_embeds is not None and negative_pooled_prompt_embeds is not None
|
| 315 |
+
)
|
| 316 |
+
do_true_cfg = true_cfg_scale > 1 and has_neg_prompt
|
| 317 |
+
(
|
| 318 |
+
prompt_embeds,
|
| 319 |
+
pooled_prompt_embeds,
|
| 320 |
+
text_ids,
|
| 321 |
+
) = self.encode_prompt(
|
| 322 |
+
prompt=prompt,
|
| 323 |
+
prompt_2=prompt_2,
|
| 324 |
+
prompt_embeds=prompt_embeds,
|
| 325 |
+
pooled_prompt_embeds=pooled_prompt_embeds,
|
| 326 |
+
device=device,
|
| 327 |
+
num_images_per_prompt=num_images_per_prompt,
|
| 328 |
+
max_sequence_length=max_sequence_length,
|
| 329 |
+
lora_scale=lora_scale,
|
| 330 |
+
)
|
| 331 |
+
if do_true_cfg:
|
| 332 |
+
(
|
| 333 |
+
negative_prompt_embeds,
|
| 334 |
+
negative_pooled_prompt_embeds,
|
| 335 |
+
_,
|
| 336 |
+
) = self.encode_prompt(
|
| 337 |
+
prompt=negative_prompt,
|
| 338 |
+
prompt_2=negative_prompt_2,
|
| 339 |
+
prompt_embeds=negative_prompt_embeds,
|
| 340 |
+
pooled_prompt_embeds=negative_pooled_prompt_embeds,
|
| 341 |
+
device=device,
|
| 342 |
+
num_images_per_prompt=num_images_per_prompt,
|
| 343 |
+
max_sequence_length=max_sequence_length,
|
| 344 |
+
lora_scale=lora_scale,
|
| 345 |
+
)
|
| 346 |
+
|
| 347 |
+
# 4. Prepare latent variables
|
| 348 |
+
num_channels_latents = self.transformer.config.in_channels // 4
|
| 349 |
+
latents, latent_image_ids = self.prepare_latents(
|
| 350 |
+
batch_size * num_images_per_prompt,
|
| 351 |
+
num_channels_latents,
|
| 352 |
+
height,
|
| 353 |
+
width,
|
| 354 |
+
prompt_embeds.dtype,
|
| 355 |
+
device,
|
| 356 |
+
generator,
|
| 357 |
+
latents,
|
| 358 |
+
)
|
| 359 |
+
|
| 360 |
+
# 4.1 concat ref tokens to latent
|
| 361 |
+
origin_img_len = latents.shape[1]
|
| 362 |
+
embeddings = repeat(self.task_embedding.weight[1], "c -> n l c", n=batch_size, l=origin_img_len)
|
| 363 |
+
ref_latents = []
|
| 364 |
+
ref_latent_image_idss = []
|
| 365 |
+
start_height = height // 16
|
| 366 |
+
start_width = width // 16
|
| 367 |
+
for ref_cond in ref_conds:
|
| 368 |
+
img = ref_cond['img'] # [b, 3, h, w], range [-1, 1]
|
| 369 |
+
task = ref_cond['task']
|
| 370 |
+
idx = ref_cond['idx']
|
| 371 |
+
|
| 372 |
+
# encode ref with VAE
|
| 373 |
+
img = img.to(latents)
|
| 374 |
+
ref_latent = self.vae.encode(img).latent_dist.sample()
|
| 375 |
+
ref_latent = (ref_latent - self.vae.config.shift_factor) * self.vae.config.scaling_factor
|
| 376 |
+
cur_height = ref_latent.shape[2]
|
| 377 |
+
cur_width = ref_latent.shape[3]
|
| 378 |
+
ref_latent = self._pack_latents(ref_latent, batch_size, num_channels_latents, cur_height, cur_width)
|
| 379 |
+
ref_latent_image_ids = self._prepare_latent_image_ids(
|
| 380 |
+
batch_size, cur_height, cur_width, device, prompt_embeds.dtype, start_height, start_width
|
| 381 |
+
)
|
| 382 |
+
start_height += cur_height // 2
|
| 383 |
+
start_width += cur_width // 2
|
| 384 |
+
|
| 385 |
+
# prepare task_idx_embedding
|
| 386 |
+
task_idx = get_task_embedding_idx(task)
|
| 387 |
+
cur_task_embedding = repeat(
|
| 388 |
+
self.task_embedding.weight[task_idx], "c -> n l c", n=batch_size, l=ref_latent.shape[1]
|
| 389 |
+
)
|
| 390 |
+
cur_idx_embedding = repeat(
|
| 391 |
+
self.idx_embedding.weight[idx], "c -> n l c", n=batch_size, l=ref_latent.shape[1]
|
| 392 |
+
)
|
| 393 |
+
cur_embedding = cur_task_embedding + cur_idx_embedding
|
| 394 |
+
|
| 395 |
+
# concat ref to latent
|
| 396 |
+
embeddings = torch.cat([embeddings, cur_embedding], dim=1)
|
| 397 |
+
ref_latents.append(ref_latent)
|
| 398 |
+
ref_latent_image_idss.append(ref_latent_image_ids)
|
| 399 |
+
|
| 400 |
+
# 5. Prepare timesteps
|
| 401 |
+
sigmas = np.linspace(1.0, 1 / num_inference_steps, num_inference_steps) if sigmas is None else sigmas
|
| 402 |
+
image_seq_len = latents.shape[1]
|
| 403 |
+
mu = calculate_shift(
|
| 404 |
+
image_seq_len,
|
| 405 |
+
self.scheduler.config.get("base_image_seq_len", 256),
|
| 406 |
+
self.scheduler.config.get("max_image_seq_len", 4096),
|
| 407 |
+
self.scheduler.config.get("base_shift", 0.5),
|
| 408 |
+
self.scheduler.config.get("max_shift", 1.15),
|
| 409 |
+
)
|
| 410 |
+
timesteps, num_inference_steps = retrieve_timesteps(
|
| 411 |
+
self.scheduler,
|
| 412 |
+
num_inference_steps,
|
| 413 |
+
device,
|
| 414 |
+
sigmas=sigmas,
|
| 415 |
+
mu=mu,
|
| 416 |
+
)
|
| 417 |
+
num_warmup_steps = max(len(timesteps) - num_inference_steps * self.scheduler.order, 0)
|
| 418 |
+
self._num_timesteps = len(timesteps)
|
| 419 |
+
|
| 420 |
+
# handle guidance
|
| 421 |
+
if self.transformer.config.guidance_embeds:
|
| 422 |
+
guidance = torch.full([1], guidance_scale, device=device, dtype=torch.float32)
|
| 423 |
+
guidance = guidance.expand(latents.shape[0])
|
| 424 |
+
else:
|
| 425 |
+
guidance = None
|
| 426 |
+
neg_guidance = torch.full([1], neg_guidance_scale, device=device, dtype=torch.float32)
|
| 427 |
+
neg_guidance = neg_guidance.expand(latents.shape[0])
|
| 428 |
+
first_step_guidance = torch.full([1], first_step_guidance_scale, device=device, dtype=torch.float32)
|
| 429 |
+
|
| 430 |
+
if self.joint_attention_kwargs is None:
|
| 431 |
+
self._joint_attention_kwargs = {}
|
| 432 |
+
|
| 433 |
+
# 6. Denoising loop
|
| 434 |
+
with self.progress_bar(total=num_inference_steps) as progress_bar:
|
| 435 |
+
for i, t in enumerate(timesteps):
|
| 436 |
+
if self.interrupt:
|
| 437 |
+
continue
|
| 438 |
+
|
| 439 |
+
self._current_timestep = t
|
| 440 |
+
# broadcast to batch dimension in a way that's compatible with ONNX/Core ML
|
| 441 |
+
timestep = t.expand(latents.shape[0]).to(latents.dtype)
|
| 442 |
+
|
| 443 |
+
noise_pred = self.transformer(
|
| 444 |
+
hidden_states=torch.cat((latents, *ref_latents), dim=1),
|
| 445 |
+
timestep=timestep / 1000,
|
| 446 |
+
guidance=guidance if i > 0 else first_step_guidance,
|
| 447 |
+
pooled_projections=pooled_prompt_embeds,
|
| 448 |
+
encoder_hidden_states=prompt_embeds,
|
| 449 |
+
txt_ids=text_ids,
|
| 450 |
+
img_ids=torch.cat((latent_image_ids, *ref_latent_image_idss), dim=1),
|
| 451 |
+
joint_attention_kwargs=self.joint_attention_kwargs,
|
| 452 |
+
return_dict=False,
|
| 453 |
+
embeddings=embeddings,
|
| 454 |
+
)[0][:, :origin_img_len]
|
| 455 |
+
|
| 456 |
+
if do_true_cfg and i >= true_cfg_start_step and i < true_cfg_end_step:
|
| 457 |
+
neg_noise_pred = self.transformer(
|
| 458 |
+
hidden_states=latents,
|
| 459 |
+
timestep=timestep / 1000,
|
| 460 |
+
guidance=neg_guidance,
|
| 461 |
+
pooled_projections=negative_pooled_prompt_embeds,
|
| 462 |
+
encoder_hidden_states=negative_prompt_embeds,
|
| 463 |
+
txt_ids=text_ids,
|
| 464 |
+
img_ids=latent_image_ids,
|
| 465 |
+
joint_attention_kwargs=self.joint_attention_kwargs,
|
| 466 |
+
return_dict=False,
|
| 467 |
+
)[0]
|
| 468 |
+
noise_pred = neg_noise_pred + true_cfg_scale * (noise_pred - neg_noise_pred)
|
| 469 |
+
|
| 470 |
+
# compute the previous noisy sample x_t -> x_t-1
|
| 471 |
+
latents_dtype = latents.dtype
|
| 472 |
+
latents = self.scheduler.step(noise_pred, t, latents, return_dict=False)[0]
|
| 473 |
+
|
| 474 |
+
if latents.dtype != latents_dtype and torch.backends.mps.is_available():
|
| 475 |
+
# some platforms (eg. apple mps) misbehave due to a pytorch bug: https://github.com/pytorch/pytorch/pull/99272
|
| 476 |
+
latents = latents.to(latents_dtype)
|
| 477 |
+
|
| 478 |
+
if callback_on_step_end is not None:
|
| 479 |
+
callback_kwargs = {}
|
| 480 |
+
for k in callback_on_step_end_tensor_inputs:
|
| 481 |
+
callback_kwargs[k] = locals()[k]
|
| 482 |
+
callback_outputs = callback_on_step_end(self, i, t, callback_kwargs)
|
| 483 |
+
|
| 484 |
+
latents = callback_outputs.pop("latents", latents)
|
| 485 |
+
prompt_embeds = callback_outputs.pop("prompt_embeds", prompt_embeds)
|
| 486 |
+
|
| 487 |
+
# call the callback, if provided
|
| 488 |
+
if i == len(timesteps) - 1 or ((i + 1) > num_warmup_steps and (i + 1) % self.scheduler.order == 0):
|
| 489 |
+
progress_bar.update()
|
| 490 |
+
|
| 491 |
+
self._current_timestep = None
|
| 492 |
+
|
| 493 |
+
if output_type == "latent":
|
| 494 |
+
image = latents
|
| 495 |
+
else:
|
| 496 |
+
latents = self._unpack_latents(latents, height, width, self.vae_scale_factor)
|
| 497 |
+
latents = (latents / self.vae.config.scaling_factor) + self.vae.config.shift_factor
|
| 498 |
+
image = self.vae.decode(latents, return_dict=False)[0]
|
| 499 |
+
image = self.image_processor.postprocess(image, output_type=output_type)
|
| 500 |
+
|
| 501 |
+
# Offload all models
|
| 502 |
+
self.maybe_free_model_hooks()
|
| 503 |
+
|
| 504 |
+
if not return_dict:
|
| 505 |
+
return (image,)
|
| 506 |
+
|
| 507 |
+
return FluxPipelineOutput(images=image)
|
dreamo/transformer.py
ADDED
|
@@ -0,0 +1,187 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) 2025 Bytedance Ltd. and/or its affiliates
|
| 2 |
+
# Copyright 2024 Black Forest Labs and The HuggingFace Team. All rights reserved.
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
|
| 16 |
+
from typing import Any, Dict, Optional, Union
|
| 17 |
+
|
| 18 |
+
import numpy as np
|
| 19 |
+
import torch
|
| 20 |
+
from diffusers.models.modeling_outputs import Transformer2DModelOutput
|
| 21 |
+
from diffusers.utils import (
|
| 22 |
+
USE_PEFT_BACKEND,
|
| 23 |
+
logging,
|
| 24 |
+
scale_lora_layers,
|
| 25 |
+
unscale_lora_layers,
|
| 26 |
+
)
|
| 27 |
+
|
| 28 |
+
logger = logging.get_logger(__name__) # pylint: disable=invalid-name
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
def flux_transformer_forward(
|
| 32 |
+
self,
|
| 33 |
+
hidden_states: torch.Tensor,
|
| 34 |
+
encoder_hidden_states: torch.Tensor = None,
|
| 35 |
+
pooled_projections: torch.Tensor = None,
|
| 36 |
+
timestep: torch.LongTensor = None,
|
| 37 |
+
img_ids: torch.Tensor = None,
|
| 38 |
+
txt_ids: torch.Tensor = None,
|
| 39 |
+
guidance: torch.Tensor = None,
|
| 40 |
+
joint_attention_kwargs: Optional[Dict[str, Any]] = None,
|
| 41 |
+
controlnet_block_samples=None,
|
| 42 |
+
controlnet_single_block_samples=None,
|
| 43 |
+
return_dict: bool = True,
|
| 44 |
+
controlnet_blocks_repeat: bool = False,
|
| 45 |
+
embeddings: torch.Tensor = None,
|
| 46 |
+
) -> Union[torch.Tensor, Transformer2DModelOutput]:
|
| 47 |
+
"""
|
| 48 |
+
The [`FluxTransformer2DModel`] forward method.
|
| 49 |
+
|
| 50 |
+
Args:
|
| 51 |
+
hidden_states (`torch.Tensor` of shape `(batch_size, image_sequence_length, in_channels)`):
|
| 52 |
+
Input `hidden_states`.
|
| 53 |
+
encoder_hidden_states (`torch.Tensor` of shape `(batch_size, text_sequence_length, joint_attention_dim)`):
|
| 54 |
+
Conditional embeddings (embeddings computed from the input conditions such as prompts) to use.
|
| 55 |
+
pooled_projections (`torch.Tensor` of shape `(batch_size, projection_dim)`): Embeddings projected
|
| 56 |
+
from the embeddings of input conditions.
|
| 57 |
+
timestep ( `torch.LongTensor`):
|
| 58 |
+
Used to indicate denoising step.
|
| 59 |
+
block_controlnet_hidden_states: (`list` of `torch.Tensor`):
|
| 60 |
+
A list of tensors that if specified are added to the residuals of transformer blocks.
|
| 61 |
+
joint_attention_kwargs (`dict`, *optional*):
|
| 62 |
+
A kwargs dictionary that if specified is passed along to the `AttentionProcessor` as defined under
|
| 63 |
+
`self.processor` in
|
| 64 |
+
[diffusers.models.attention_processor](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py).
|
| 65 |
+
return_dict (`bool`, *optional*, defaults to `True`):
|
| 66 |
+
Whether or not to return a [`~models.transformer_2d.Transformer2DModelOutput`] instead of a plain
|
| 67 |
+
tuple.
|
| 68 |
+
|
| 69 |
+
Returns:
|
| 70 |
+
If `return_dict` is True, an [`~models.transformer_2d.Transformer2DModelOutput`] is returned, otherwise a
|
| 71 |
+
`tuple` where the first element is the sample tensor.
|
| 72 |
+
"""
|
| 73 |
+
if joint_attention_kwargs is not None:
|
| 74 |
+
joint_attention_kwargs = joint_attention_kwargs.copy()
|
| 75 |
+
lora_scale = joint_attention_kwargs.pop("scale", 1.0)
|
| 76 |
+
else:
|
| 77 |
+
lora_scale = 1.0
|
| 78 |
+
|
| 79 |
+
if USE_PEFT_BACKEND:
|
| 80 |
+
# weight the lora layers by setting `lora_scale` for each PEFT layer
|
| 81 |
+
scale_lora_layers(self, lora_scale)
|
| 82 |
+
else:
|
| 83 |
+
if joint_attention_kwargs is not None and joint_attention_kwargs.get("scale", None) is not None:
|
| 84 |
+
logger.warning(
|
| 85 |
+
"Passing `scale` via `joint_attention_kwargs` when not using the PEFT backend is ineffective."
|
| 86 |
+
)
|
| 87 |
+
|
| 88 |
+
hidden_states = self.x_embedder(hidden_states)
|
| 89 |
+
# add task and idx embedding
|
| 90 |
+
if embeddings is not None:
|
| 91 |
+
hidden_states = hidden_states + embeddings
|
| 92 |
+
|
| 93 |
+
timestep = timestep.to(hidden_states.dtype) * 1000
|
| 94 |
+
guidance = guidance.to(hidden_states.dtype) * 1000 if guidance is not None else None
|
| 95 |
+
|
| 96 |
+
temb = (
|
| 97 |
+
self.time_text_embed(timestep, pooled_projections)
|
| 98 |
+
if guidance is None
|
| 99 |
+
else self.time_text_embed(timestep, guidance, pooled_projections)
|
| 100 |
+
)
|
| 101 |
+
encoder_hidden_states = self.context_embedder(encoder_hidden_states)
|
| 102 |
+
|
| 103 |
+
if txt_ids.ndim == 3:
|
| 104 |
+
# logger.warning(
|
| 105 |
+
# "Passing `txt_ids` 3d torch.Tensor is deprecated."
|
| 106 |
+
# "Please remove the batch dimension and pass it as a 2d torch Tensor"
|
| 107 |
+
# )
|
| 108 |
+
txt_ids = txt_ids[0]
|
| 109 |
+
if img_ids.ndim == 3:
|
| 110 |
+
# logger.warning(
|
| 111 |
+
# "Passing `img_ids` 3d torch.Tensor is deprecated."
|
| 112 |
+
# "Please remove the batch dimension and pass it as a 2d torch Tensor"
|
| 113 |
+
# )
|
| 114 |
+
img_ids = img_ids[0]
|
| 115 |
+
|
| 116 |
+
ids = torch.cat((txt_ids, img_ids), dim=0)
|
| 117 |
+
image_rotary_emb = self.pos_embed(ids)
|
| 118 |
+
|
| 119 |
+
for index_block, block in enumerate(self.transformer_blocks):
|
| 120 |
+
if torch.is_grad_enabled() and self.gradient_checkpointing:
|
| 121 |
+
encoder_hidden_states, hidden_states = self._gradient_checkpointing_func(
|
| 122 |
+
block,
|
| 123 |
+
hidden_states,
|
| 124 |
+
encoder_hidden_states,
|
| 125 |
+
temb,
|
| 126 |
+
image_rotary_emb,
|
| 127 |
+
)
|
| 128 |
+
|
| 129 |
+
else:
|
| 130 |
+
encoder_hidden_states, hidden_states = block(
|
| 131 |
+
hidden_states=hidden_states,
|
| 132 |
+
encoder_hidden_states=encoder_hidden_states,
|
| 133 |
+
temb=temb,
|
| 134 |
+
image_rotary_emb=image_rotary_emb,
|
| 135 |
+
joint_attention_kwargs=joint_attention_kwargs,
|
| 136 |
+
)
|
| 137 |
+
|
| 138 |
+
# controlnet residual
|
| 139 |
+
if controlnet_block_samples is not None:
|
| 140 |
+
interval_control = len(self.transformer_blocks) / len(controlnet_block_samples)
|
| 141 |
+
interval_control = int(np.ceil(interval_control))
|
| 142 |
+
# For Xlabs ControlNet.
|
| 143 |
+
if controlnet_blocks_repeat:
|
| 144 |
+
hidden_states = hidden_states + controlnet_block_samples[index_block % len(controlnet_block_samples)]
|
| 145 |
+
else:
|
| 146 |
+
hidden_states = hidden_states + controlnet_block_samples[index_block // interval_control]
|
| 147 |
+
hidden_states = torch.cat([encoder_hidden_states, hidden_states], dim=1)
|
| 148 |
+
|
| 149 |
+
for index_block, block in enumerate(self.single_transformer_blocks):
|
| 150 |
+
if torch.is_grad_enabled() and self.gradient_checkpointing:
|
| 151 |
+
hidden_states = self._gradient_checkpointing_func(
|
| 152 |
+
block,
|
| 153 |
+
hidden_states,
|
| 154 |
+
temb,
|
| 155 |
+
image_rotary_emb,
|
| 156 |
+
)
|
| 157 |
+
|
| 158 |
+
else:
|
| 159 |
+
hidden_states = block(
|
| 160 |
+
hidden_states=hidden_states,
|
| 161 |
+
temb=temb,
|
| 162 |
+
image_rotary_emb=image_rotary_emb,
|
| 163 |
+
joint_attention_kwargs=joint_attention_kwargs,
|
| 164 |
+
)
|
| 165 |
+
|
| 166 |
+
# controlnet residual
|
| 167 |
+
if controlnet_single_block_samples is not None:
|
| 168 |
+
interval_control = len(self.single_transformer_blocks) / len(controlnet_single_block_samples)
|
| 169 |
+
interval_control = int(np.ceil(interval_control))
|
| 170 |
+
hidden_states[:, encoder_hidden_states.shape[1] :, ...] = (
|
| 171 |
+
hidden_states[:, encoder_hidden_states.shape[1] :, ...]
|
| 172 |
+
+ controlnet_single_block_samples[index_block // interval_control]
|
| 173 |
+
)
|
| 174 |
+
|
| 175 |
+
hidden_states = hidden_states[:, encoder_hidden_states.shape[1] :, ...]
|
| 176 |
+
|
| 177 |
+
hidden_states = self.norm_out(hidden_states, temb)
|
| 178 |
+
output = self.proj_out(hidden_states)
|
| 179 |
+
|
| 180 |
+
if USE_PEFT_BACKEND:
|
| 181 |
+
# remove `lora_scale` from each PEFT layer
|
| 182 |
+
unscale_lora_layers(self, lora_scale)
|
| 183 |
+
|
| 184 |
+
if not return_dict:
|
| 185 |
+
return (output,)
|
| 186 |
+
|
| 187 |
+
return Transformer2DModelOutput(sample=output)
|
dreamo/utils.py
ADDED
|
@@ -0,0 +1,232 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) 2025 Bytedance Ltd. and/or its affiliates
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
|
| 15 |
+
import math
|
| 16 |
+
import re
|
| 17 |
+
|
| 18 |
+
import cv2
|
| 19 |
+
import numpy as np
|
| 20 |
+
import torch
|
| 21 |
+
from torchvision.utils import make_grid
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
# from basicsr
|
| 25 |
+
def img2tensor(imgs, bgr2rgb=True, float32=True):
|
| 26 |
+
"""Numpy array to tensor.
|
| 27 |
+
|
| 28 |
+
Args:
|
| 29 |
+
imgs (list[ndarray] | ndarray): Input images.
|
| 30 |
+
bgr2rgb (bool): Whether to change bgr to rgb.
|
| 31 |
+
float32 (bool): Whether to change to float32.
|
| 32 |
+
|
| 33 |
+
Returns:
|
| 34 |
+
list[tensor] | tensor: Tensor images. If returned results only have
|
| 35 |
+
one element, just return tensor.
|
| 36 |
+
"""
|
| 37 |
+
|
| 38 |
+
def _totensor(img, bgr2rgb, float32):
|
| 39 |
+
if img.shape[2] == 3 and bgr2rgb:
|
| 40 |
+
if img.dtype == 'float64':
|
| 41 |
+
img = img.astype('float32')
|
| 42 |
+
img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
|
| 43 |
+
img = torch.from_numpy(img.transpose(2, 0, 1))
|
| 44 |
+
if float32:
|
| 45 |
+
img = img.float()
|
| 46 |
+
return img
|
| 47 |
+
|
| 48 |
+
if isinstance(imgs, list):
|
| 49 |
+
return [_totensor(img, bgr2rgb, float32) for img in imgs]
|
| 50 |
+
return _totensor(imgs, bgr2rgb, float32)
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
def tensor2img(tensor, rgb2bgr=True, out_type=np.uint8, min_max=(0, 1)):
|
| 54 |
+
"""Convert torch Tensors into image numpy arrays.
|
| 55 |
+
|
| 56 |
+
After clamping to [min, max], values will be normalized to [0, 1].
|
| 57 |
+
|
| 58 |
+
Args:
|
| 59 |
+
tensor (Tensor or list[Tensor]): Accept shapes:
|
| 60 |
+
1) 4D mini-batch Tensor of shape (B x 3/1 x H x W);
|
| 61 |
+
2) 3D Tensor of shape (3/1 x H x W);
|
| 62 |
+
3) 2D Tensor of shape (H x W).
|
| 63 |
+
Tensor channel should be in RGB order.
|
| 64 |
+
rgb2bgr (bool): Whether to change rgb to bgr.
|
| 65 |
+
out_type (numpy type): output types. If ``np.uint8``, transform outputs
|
| 66 |
+
to uint8 type with range [0, 255]; otherwise, float type with
|
| 67 |
+
range [0, 1]. Default: ``np.uint8``.
|
| 68 |
+
min_max (tuple[int]): min and max values for clamp.
|
| 69 |
+
|
| 70 |
+
Returns:
|
| 71 |
+
(Tensor or list): 3D ndarray of shape (H x W x C) OR 2D ndarray of
|
| 72 |
+
shape (H x W). The channel order is BGR.
|
| 73 |
+
"""
|
| 74 |
+
if not (torch.is_tensor(tensor) or (isinstance(tensor, list) and all(torch.is_tensor(t) for t in tensor))):
|
| 75 |
+
raise TypeError(f'tensor or list of tensors expected, got {type(tensor)}')
|
| 76 |
+
|
| 77 |
+
if torch.is_tensor(tensor):
|
| 78 |
+
tensor = [tensor]
|
| 79 |
+
result = []
|
| 80 |
+
for _tensor in tensor:
|
| 81 |
+
_tensor = _tensor.squeeze(0).float().detach().cpu().clamp_(*min_max)
|
| 82 |
+
_tensor = (_tensor - min_max[0]) / (min_max[1] - min_max[0])
|
| 83 |
+
|
| 84 |
+
n_dim = _tensor.dim()
|
| 85 |
+
if n_dim == 4:
|
| 86 |
+
img_np = make_grid(_tensor, nrow=int(math.sqrt(_tensor.size(0))), normalize=False).numpy()
|
| 87 |
+
img_np = img_np.transpose(1, 2, 0)
|
| 88 |
+
if rgb2bgr:
|
| 89 |
+
img_np = cv2.cvtColor(img_np, cv2.COLOR_RGB2BGR)
|
| 90 |
+
elif n_dim == 3:
|
| 91 |
+
img_np = _tensor.numpy()
|
| 92 |
+
img_np = img_np.transpose(1, 2, 0)
|
| 93 |
+
if img_np.shape[2] == 1: # gray image
|
| 94 |
+
img_np = np.squeeze(img_np, axis=2)
|
| 95 |
+
else:
|
| 96 |
+
if rgb2bgr:
|
| 97 |
+
img_np = cv2.cvtColor(img_np, cv2.COLOR_RGB2BGR)
|
| 98 |
+
elif n_dim == 2:
|
| 99 |
+
img_np = _tensor.numpy()
|
| 100 |
+
else:
|
| 101 |
+
raise TypeError(f'Only support 4D, 3D or 2D tensor. But received with dimension: {n_dim}')
|
| 102 |
+
if out_type == np.uint8:
|
| 103 |
+
# Unlike MATLAB, numpy.unit8() WILL NOT round by default.
|
| 104 |
+
img_np = (img_np * 255.0).round()
|
| 105 |
+
img_np = img_np.astype(out_type)
|
| 106 |
+
result.append(img_np)
|
| 107 |
+
if len(result) == 1:
|
| 108 |
+
result = result[0]
|
| 109 |
+
return result
|
| 110 |
+
|
| 111 |
+
|
| 112 |
+
def resize_numpy_image_area(image, area=512 * 512):
|
| 113 |
+
h, w = image.shape[:2]
|
| 114 |
+
k = math.sqrt(area / (h * w))
|
| 115 |
+
h = int(h * k) - (int(h * k) % 16)
|
| 116 |
+
w = int(w * k) - (int(w * k) % 16)
|
| 117 |
+
image = cv2.resize(image, (w, h), interpolation=cv2.INTER_AREA)
|
| 118 |
+
return image
|
| 119 |
+
|
| 120 |
+
def resize_numpy_image_long(image, long_edge=768):
|
| 121 |
+
h, w = image.shape[:2]
|
| 122 |
+
if max(h, w) <= long_edge:
|
| 123 |
+
return image
|
| 124 |
+
k = long_edge / max(h, w)
|
| 125 |
+
h = int(h * k)
|
| 126 |
+
w = int(w * k)
|
| 127 |
+
image = cv2.resize(image, (w, h), interpolation=cv2.INTER_AREA)
|
| 128 |
+
return image
|
| 129 |
+
|
| 130 |
+
|
| 131 |
+
# reference: https://github.com/huggingface/diffusers/pull/9295/files
|
| 132 |
+
def convert_flux_lora_to_diffusers(old_state_dict):
|
| 133 |
+
new_state_dict = {}
|
| 134 |
+
orig_keys = list(old_state_dict.keys())
|
| 135 |
+
|
| 136 |
+
def handle_qkv(sds_sd, ait_sd, sds_key, ait_keys, dims=None):
|
| 137 |
+
down_weight = sds_sd.pop(sds_key)
|
| 138 |
+
up_weight = sds_sd.pop(sds_key.replace(".down.weight", ".up.weight"))
|
| 139 |
+
|
| 140 |
+
# calculate dims if not provided
|
| 141 |
+
num_splits = len(ait_keys)
|
| 142 |
+
if dims is None:
|
| 143 |
+
dims = [up_weight.shape[0] // num_splits] * num_splits
|
| 144 |
+
else:
|
| 145 |
+
assert sum(dims) == up_weight.shape[0]
|
| 146 |
+
|
| 147 |
+
# make ai-toolkit weight
|
| 148 |
+
ait_down_keys = [k + ".lora_A.weight" for k in ait_keys]
|
| 149 |
+
ait_up_keys = [k + ".lora_B.weight" for k in ait_keys]
|
| 150 |
+
|
| 151 |
+
# down_weight is copied to each split
|
| 152 |
+
ait_sd.update({k: down_weight for k in ait_down_keys})
|
| 153 |
+
|
| 154 |
+
# up_weight is split to each split
|
| 155 |
+
ait_sd.update({k: v for k, v in zip(ait_up_keys, torch.split(up_weight, dims, dim=0))}) # noqa: C416
|
| 156 |
+
|
| 157 |
+
for old_key in orig_keys:
|
| 158 |
+
# Handle double_blocks
|
| 159 |
+
if 'double_blocks' in old_key:
|
| 160 |
+
block_num = re.search(r"double_blocks_(\d+)", old_key).group(1)
|
| 161 |
+
new_key = f"transformer.transformer_blocks.{block_num}"
|
| 162 |
+
|
| 163 |
+
if "proj_lora1" in old_key:
|
| 164 |
+
new_key += ".attn.to_out.0"
|
| 165 |
+
elif "proj_lora2" in old_key:
|
| 166 |
+
new_key += ".attn.to_add_out"
|
| 167 |
+
elif "qkv_lora2" in old_key and "up" not in old_key:
|
| 168 |
+
handle_qkv(
|
| 169 |
+
old_state_dict,
|
| 170 |
+
new_state_dict,
|
| 171 |
+
old_key,
|
| 172 |
+
[
|
| 173 |
+
f"transformer.transformer_blocks.{block_num}.attn.add_q_proj",
|
| 174 |
+
f"transformer.transformer_blocks.{block_num}.attn.add_k_proj",
|
| 175 |
+
f"transformer.transformer_blocks.{block_num}.attn.add_v_proj",
|
| 176 |
+
],
|
| 177 |
+
)
|
| 178 |
+
# continue
|
| 179 |
+
elif "qkv_lora1" in old_key and "up" not in old_key:
|
| 180 |
+
handle_qkv(
|
| 181 |
+
old_state_dict,
|
| 182 |
+
new_state_dict,
|
| 183 |
+
old_key,
|
| 184 |
+
[
|
| 185 |
+
f"transformer.transformer_blocks.{block_num}.attn.to_q",
|
| 186 |
+
f"transformer.transformer_blocks.{block_num}.attn.to_k",
|
| 187 |
+
f"transformer.transformer_blocks.{block_num}.attn.to_v",
|
| 188 |
+
],
|
| 189 |
+
)
|
| 190 |
+
# continue
|
| 191 |
+
|
| 192 |
+
if "down" in old_key:
|
| 193 |
+
new_key += ".lora_A.weight"
|
| 194 |
+
elif "up" in old_key:
|
| 195 |
+
new_key += ".lora_B.weight"
|
| 196 |
+
|
| 197 |
+
# Handle single_blocks
|
| 198 |
+
elif 'single_blocks' in old_key:
|
| 199 |
+
block_num = re.search(r"single_blocks_(\d+)", old_key).group(1)
|
| 200 |
+
new_key = f"transformer.single_transformer_blocks.{block_num}"
|
| 201 |
+
|
| 202 |
+
if "proj_lora" in old_key:
|
| 203 |
+
new_key += ".proj_out"
|
| 204 |
+
elif "qkv_lora" in old_key and "up" not in old_key:
|
| 205 |
+
handle_qkv(
|
| 206 |
+
old_state_dict,
|
| 207 |
+
new_state_dict,
|
| 208 |
+
old_key,
|
| 209 |
+
[
|
| 210 |
+
f"transformer.single_transformer_blocks.{block_num}.attn.to_q",
|
| 211 |
+
f"transformer.single_transformer_blocks.{block_num}.attn.to_k",
|
| 212 |
+
f"transformer.single_transformer_blocks.{block_num}.attn.to_v",
|
| 213 |
+
],
|
| 214 |
+
)
|
| 215 |
+
|
| 216 |
+
if "down" in old_key:
|
| 217 |
+
new_key += ".lora_A.weight"
|
| 218 |
+
elif "up" in old_key:
|
| 219 |
+
new_key += ".lora_B.weight"
|
| 220 |
+
|
| 221 |
+
else:
|
| 222 |
+
# Handle other potential key patterns here
|
| 223 |
+
new_key = old_key
|
| 224 |
+
|
| 225 |
+
# Since we already handle qkv above.
|
| 226 |
+
if "qkv" not in old_key and 'embedding' not in old_key:
|
| 227 |
+
new_state_dict[new_key] = old_state_dict.pop(old_key)
|
| 228 |
+
|
| 229 |
+
# if len(old_state_dict) > 0:
|
| 230 |
+
# raise ValueError(f"`old_state_dict` should be at this point but has: {list(old_state_dict.keys())}.")
|
| 231 |
+
|
| 232 |
+
return new_state_dict
|