swoyam-sarvam
commited on
Commit
·
2a0517c
1
Parent(s):
4c1d1b8
initial commit
Browse files- app.py +29 -0
- control.py +91 -0
- controlnet_flux.py +418 -0
- images/0.jpg +0 -0
- images/1.jpg +0 -0
- images/2.jpg +0 -0
- images/3.jpg +0 -0
- images/alibaba.png +0 -0
- images/alibabaalimama.png +0 -0
- images/alimama.png +0 -0
- images/flux1.jpg +0 -0
- images/flux2.jpg +0 -0
- images/flux3.jpg +0 -0
- pipeline_flux_controlnet_inpaint.py +1066 -0
- poetry.lock +0 -0
- pyproject.toml +18 -0
- temp_input.png +0 -0
- temp_mask.png +0 -0
- transformer_flux.py +525 -0
app.py
ADDED
|
@@ -0,0 +1,29 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import gradio as gr
|
| 2 |
+
from control import main
|
| 3 |
+
from diffusers.utils import load_image
|
| 4 |
+
|
| 5 |
+
|
| 6 |
+
def process_images(image, mask, prompt):
|
| 7 |
+
try:
|
| 8 |
+
# Pass images directly to main function
|
| 9 |
+
result = main(image, mask, prompt)
|
| 10 |
+
return result
|
| 11 |
+
except Exception as e:
|
| 12 |
+
return str(e)
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
# Create Gradio interface
|
| 16 |
+
demo = gr.Interface(
|
| 17 |
+
fn=process_images,
|
| 18 |
+
inputs=[
|
| 19 |
+
gr.Image(label="Input Image", type="pil"),
|
| 20 |
+
gr.Image(label="Mask Image", type="pil"),
|
| 21 |
+
gr.Textbox(label="Prompt"),
|
| 22 |
+
],
|
| 23 |
+
outputs=gr.Image(label="Generated Image"),
|
| 24 |
+
title="Image Inpainting with FLUX ControlNet",
|
| 25 |
+
description="Upload an image and its mask, then provide a prompt to generate the inpainted result.",
|
| 26 |
+
)
|
| 27 |
+
|
| 28 |
+
if __name__ == "__main__":
|
| 29 |
+
demo.launch()
|
control.py
ADDED
|
@@ -0,0 +1,91 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch
|
| 2 |
+
import argparse
|
| 3 |
+
from diffusers.utils import load_image, check_min_version
|
| 4 |
+
from controlnet_flux import FluxControlNetModel
|
| 5 |
+
from transformer_flux import FluxTransformer2DModel
|
| 6 |
+
from pipeline_flux_controlnet_inpaint import FluxControlNetInpaintingPipeline
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
def main(image, mask, prompt):
|
| 10 |
+
check_min_version("0.30.2")
|
| 11 |
+
|
| 12 |
+
# Enable memory optimizations
|
| 13 |
+
torch.backends.cuda.matmul.allow_tf32 = True
|
| 14 |
+
torch.backends.cudnn.allow_tf32 = True
|
| 15 |
+
torch.cuda.empty_cache()
|
| 16 |
+
torch.backends.cudnn.benchmark = True
|
| 17 |
+
|
| 18 |
+
# Set environment variable for memory allocation
|
| 19 |
+
import os
|
| 20 |
+
os.environ["PYTORCH_CUDA_ALLOC_CONF"] = "max_split_size_mb:512"
|
| 21 |
+
|
| 22 |
+
# Build pipeline components
|
| 23 |
+
controlnet = FluxControlNetModel.from_pretrained(
|
| 24 |
+
"alimama-creative/FLUX.1-dev-Controlnet-Inpainting-Alpha",
|
| 25 |
+
torch_dtype=torch.bfloat16,
|
| 26 |
+
).to("cuda")
|
| 27 |
+
|
| 28 |
+
transformer = FluxTransformer2DModel.from_pretrained(
|
| 29 |
+
"black-forest-labs/FLUX.1-dev",
|
| 30 |
+
subfolder="transformer",
|
| 31 |
+
torch_dtype=torch.bfloat16,
|
| 32 |
+
).to("cuda")
|
| 33 |
+
|
| 34 |
+
pipe = FluxControlNetInpaintingPipeline.from_pretrained(
|
| 35 |
+
"black-forest-labs/FLUX.1-dev",
|
| 36 |
+
controlnet=controlnet,
|
| 37 |
+
transformer=transformer,
|
| 38 |
+
torch_dtype=torch.bfloat16,
|
| 39 |
+
).to("cuda")
|
| 40 |
+
|
| 41 |
+
# Enable memory efficient attention
|
| 42 |
+
pipe.enable_attention_slicing(1)
|
| 43 |
+
|
| 44 |
+
# Load and process images
|
| 45 |
+
size = (384, 384) # or even (256, 256)
|
| 46 |
+
image = image.convert("RGB").resize(size)
|
| 47 |
+
mask = mask.convert("RGB").resize(size)
|
| 48 |
+
|
| 49 |
+
# Set generator
|
| 50 |
+
generator = torch.Generator(device="cuda").manual_seed(24)
|
| 51 |
+
|
| 52 |
+
# Run inference with memory optimizations
|
| 53 |
+
with torch.cuda.amp.autocast(): # Enable automatic mixed precision
|
| 54 |
+
result = pipe(
|
| 55 |
+
prompt=prompt,
|
| 56 |
+
height=size[1],
|
| 57 |
+
width=size[0],
|
| 58 |
+
control_image=image,
|
| 59 |
+
control_mask=mask,
|
| 60 |
+
num_inference_steps=28,
|
| 61 |
+
generator=generator,
|
| 62 |
+
controlnet_conditioning_scale=0.9,
|
| 63 |
+
guidance_scale=3.5,
|
| 64 |
+
negative_prompt="",
|
| 65 |
+
true_guidance_scale=1.0,
|
| 66 |
+
).images[0]
|
| 67 |
+
|
| 68 |
+
# Clear cache after generation
|
| 69 |
+
torch.cuda.empty_cache()
|
| 70 |
+
|
| 71 |
+
print("Successfully inpaint image")
|
| 72 |
+
return result
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
if __name__ == "__main__":
|
| 76 |
+
parser = argparse.ArgumentParser(
|
| 77 |
+
description="Inpaint an image using FluxControlNetInpaintingPipeline."
|
| 78 |
+
)
|
| 79 |
+
parser.add_argument(
|
| 80 |
+
"--image_path", type=str, required=True, help="Path to the input image."
|
| 81 |
+
)
|
| 82 |
+
parser.add_argument(
|
| 83 |
+
"--mask_path", type=str, required=True, help="Path to the mask image."
|
| 84 |
+
)
|
| 85 |
+
parser.add_argument(
|
| 86 |
+
"--prompt", type=str, required=True, help="Prompt for the inpainting process."
|
| 87 |
+
)
|
| 88 |
+
|
| 89 |
+
args = parser.parse_args()
|
| 90 |
+
result = main(args.image_path, args.mask_path, args.prompt)
|
| 91 |
+
result.save("output.png")
|
controlnet_flux.py
ADDED
|
@@ -0,0 +1,418 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from dataclasses import dataclass
|
| 2 |
+
from typing import Any, Dict, List, Optional, Tuple, Union
|
| 3 |
+
|
| 4 |
+
import torch
|
| 5 |
+
import torch.nn as nn
|
| 6 |
+
|
| 7 |
+
from diffusers.configuration_utils import ConfigMixin, register_to_config
|
| 8 |
+
from diffusers.loaders import PeftAdapterMixin
|
| 9 |
+
from diffusers.models.modeling_utils import ModelMixin
|
| 10 |
+
from diffusers.models.attention_processor import AttentionProcessor
|
| 11 |
+
from diffusers.utils import (
|
| 12 |
+
USE_PEFT_BACKEND,
|
| 13 |
+
is_torch_version,
|
| 14 |
+
logging,
|
| 15 |
+
scale_lora_layers,
|
| 16 |
+
unscale_lora_layers,
|
| 17 |
+
)
|
| 18 |
+
from diffusers.models.controlnet import BaseOutput, zero_module
|
| 19 |
+
from diffusers.models.embeddings import (
|
| 20 |
+
CombinedTimestepGuidanceTextProjEmbeddings,
|
| 21 |
+
CombinedTimestepTextProjEmbeddings,
|
| 22 |
+
)
|
| 23 |
+
from diffusers.models.modeling_outputs import Transformer2DModelOutput
|
| 24 |
+
from transformer_flux import (
|
| 25 |
+
EmbedND,
|
| 26 |
+
FluxSingleTransformerBlock,
|
| 27 |
+
FluxTransformerBlock,
|
| 28 |
+
)
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
logger = logging.get_logger(__name__) # pylint: disable=invalid-name
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
@dataclass
|
| 35 |
+
class FluxControlNetOutput(BaseOutput):
|
| 36 |
+
controlnet_block_samples: Tuple[torch.Tensor]
|
| 37 |
+
controlnet_single_block_samples: Tuple[torch.Tensor]
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
class FluxControlNetModel(ModelMixin, ConfigMixin, PeftAdapterMixin):
|
| 41 |
+
_supports_gradient_checkpointing = True
|
| 42 |
+
|
| 43 |
+
@register_to_config
|
| 44 |
+
def __init__(
|
| 45 |
+
self,
|
| 46 |
+
patch_size: int = 1,
|
| 47 |
+
in_channels: int = 64,
|
| 48 |
+
num_layers: int = 19,
|
| 49 |
+
num_single_layers: int = 38,
|
| 50 |
+
attention_head_dim: int = 128,
|
| 51 |
+
num_attention_heads: int = 24,
|
| 52 |
+
joint_attention_dim: int = 4096,
|
| 53 |
+
pooled_projection_dim: int = 768,
|
| 54 |
+
guidance_embeds: bool = False,
|
| 55 |
+
axes_dims_rope: List[int] = [16, 56, 56],
|
| 56 |
+
extra_condition_channels: int = 1 * 4,
|
| 57 |
+
):
|
| 58 |
+
super().__init__()
|
| 59 |
+
self.out_channels = in_channels
|
| 60 |
+
self.inner_dim = num_attention_heads * attention_head_dim
|
| 61 |
+
|
| 62 |
+
self.pos_embed = EmbedND(
|
| 63 |
+
dim=self.inner_dim, theta=10000, axes_dim=axes_dims_rope
|
| 64 |
+
)
|
| 65 |
+
text_time_guidance_cls = (
|
| 66 |
+
CombinedTimestepGuidanceTextProjEmbeddings
|
| 67 |
+
if guidance_embeds
|
| 68 |
+
else CombinedTimestepTextProjEmbeddings
|
| 69 |
+
)
|
| 70 |
+
self.time_text_embed = text_time_guidance_cls(
|
| 71 |
+
embedding_dim=self.inner_dim, pooled_projection_dim=pooled_projection_dim
|
| 72 |
+
)
|
| 73 |
+
|
| 74 |
+
self.context_embedder = nn.Linear(joint_attention_dim, self.inner_dim)
|
| 75 |
+
self.x_embedder = nn.Linear(in_channels, self.inner_dim)
|
| 76 |
+
|
| 77 |
+
self.transformer_blocks = nn.ModuleList(
|
| 78 |
+
[
|
| 79 |
+
FluxTransformerBlock(
|
| 80 |
+
dim=self.inner_dim,
|
| 81 |
+
num_attention_heads=num_attention_heads,
|
| 82 |
+
attention_head_dim=attention_head_dim,
|
| 83 |
+
)
|
| 84 |
+
for _ in range(num_layers)
|
| 85 |
+
]
|
| 86 |
+
)
|
| 87 |
+
|
| 88 |
+
self.single_transformer_blocks = nn.ModuleList(
|
| 89 |
+
[
|
| 90 |
+
FluxSingleTransformerBlock(
|
| 91 |
+
dim=self.inner_dim,
|
| 92 |
+
num_attention_heads=num_attention_heads,
|
| 93 |
+
attention_head_dim=attention_head_dim,
|
| 94 |
+
)
|
| 95 |
+
for _ in range(num_single_layers)
|
| 96 |
+
]
|
| 97 |
+
)
|
| 98 |
+
|
| 99 |
+
# controlnet_blocks
|
| 100 |
+
self.controlnet_blocks = nn.ModuleList([])
|
| 101 |
+
for _ in range(len(self.transformer_blocks)):
|
| 102 |
+
self.controlnet_blocks.append(
|
| 103 |
+
zero_module(nn.Linear(self.inner_dim, self.inner_dim))
|
| 104 |
+
)
|
| 105 |
+
|
| 106 |
+
self.controlnet_single_blocks = nn.ModuleList([])
|
| 107 |
+
for _ in range(len(self.single_transformer_blocks)):
|
| 108 |
+
self.controlnet_single_blocks.append(
|
| 109 |
+
zero_module(nn.Linear(self.inner_dim, self.inner_dim))
|
| 110 |
+
)
|
| 111 |
+
|
| 112 |
+
self.controlnet_x_embedder = zero_module(
|
| 113 |
+
torch.nn.Linear(in_channels + extra_condition_channels, self.inner_dim)
|
| 114 |
+
)
|
| 115 |
+
|
| 116 |
+
self.gradient_checkpointing = False
|
| 117 |
+
|
| 118 |
+
@property
|
| 119 |
+
# Copied from diffusers.models.unets.unet_2d_condition.UNet2DConditionModel.attn_processors
|
| 120 |
+
def attn_processors(self):
|
| 121 |
+
r"""
|
| 122 |
+
Returns:
|
| 123 |
+
`dict` of attention processors: A dictionary containing all attention processors used in the model with
|
| 124 |
+
indexed by its weight name.
|
| 125 |
+
"""
|
| 126 |
+
# set recursively
|
| 127 |
+
processors = {}
|
| 128 |
+
|
| 129 |
+
def fn_recursive_add_processors(name: str, module: torch.nn.Module, processors: Dict[str, AttentionProcessor]):
|
| 130 |
+
if hasattr(module, "get_processor"):
|
| 131 |
+
processors[f"{name}.processor"] = module.get_processor()
|
| 132 |
+
|
| 133 |
+
for sub_name, child in module.named_children():
|
| 134 |
+
fn_recursive_add_processors(f"{name}.{sub_name}", child, processors)
|
| 135 |
+
|
| 136 |
+
return processors
|
| 137 |
+
|
| 138 |
+
for name, module in self.named_children():
|
| 139 |
+
fn_recursive_add_processors(name, module, processors)
|
| 140 |
+
|
| 141 |
+
return processors
|
| 142 |
+
|
| 143 |
+
# Copied from diffusers.models.unets.unet_2d_condition.UNet2DConditionModel.set_attn_processor
|
| 144 |
+
def set_attn_processor(self, processor):
|
| 145 |
+
r"""
|
| 146 |
+
Sets the attention processor to use to compute attention.
|
| 147 |
+
|
| 148 |
+
Parameters:
|
| 149 |
+
processor (`dict` of `AttentionProcessor` or only `AttentionProcessor`):
|
| 150 |
+
The instantiated processor class or a dictionary of processor classes that will be set as the processor
|
| 151 |
+
for **all** `Attention` layers.
|
| 152 |
+
|
| 153 |
+
If `processor` is a dict, the key needs to define the path to the corresponding cross attention
|
| 154 |
+
processor. This is strongly recommended when setting trainable attention processors.
|
| 155 |
+
|
| 156 |
+
"""
|
| 157 |
+
count = len(self.attn_processors.keys())
|
| 158 |
+
|
| 159 |
+
if isinstance(processor, dict) and len(processor) != count:
|
| 160 |
+
raise ValueError(
|
| 161 |
+
f"A dict of processors was passed, but the number of processors {len(processor)} does not match the"
|
| 162 |
+
f" number of attention layers: {count}. Please make sure to pass {count} processor classes."
|
| 163 |
+
)
|
| 164 |
+
|
| 165 |
+
def fn_recursive_attn_processor(name: str, module: torch.nn.Module, processor):
|
| 166 |
+
if hasattr(module, "set_processor"):
|
| 167 |
+
if not isinstance(processor, dict):
|
| 168 |
+
module.set_processor(processor)
|
| 169 |
+
else:
|
| 170 |
+
module.set_processor(processor.pop(f"{name}.processor"))
|
| 171 |
+
|
| 172 |
+
for sub_name, child in module.named_children():
|
| 173 |
+
fn_recursive_attn_processor(f"{name}.{sub_name}", child, processor)
|
| 174 |
+
|
| 175 |
+
for name, module in self.named_children():
|
| 176 |
+
fn_recursive_attn_processor(name, module, processor)
|
| 177 |
+
|
| 178 |
+
def _set_gradient_checkpointing(self, module, value=False):
|
| 179 |
+
if hasattr(module, "gradient_checkpointing"):
|
| 180 |
+
module.gradient_checkpointing = value
|
| 181 |
+
|
| 182 |
+
@classmethod
|
| 183 |
+
def from_transformer(
|
| 184 |
+
cls,
|
| 185 |
+
transformer,
|
| 186 |
+
num_layers: int = 4,
|
| 187 |
+
num_single_layers: int = 10,
|
| 188 |
+
attention_head_dim: int = 128,
|
| 189 |
+
num_attention_heads: int = 24,
|
| 190 |
+
load_weights_from_transformer=True,
|
| 191 |
+
):
|
| 192 |
+
config = transformer.config
|
| 193 |
+
config["num_layers"] = num_layers
|
| 194 |
+
config["num_single_layers"] = num_single_layers
|
| 195 |
+
config["attention_head_dim"] = attention_head_dim
|
| 196 |
+
config["num_attention_heads"] = num_attention_heads
|
| 197 |
+
|
| 198 |
+
controlnet = cls(**config)
|
| 199 |
+
|
| 200 |
+
if load_weights_from_transformer:
|
| 201 |
+
controlnet.pos_embed.load_state_dict(transformer.pos_embed.state_dict())
|
| 202 |
+
controlnet.time_text_embed.load_state_dict(
|
| 203 |
+
transformer.time_text_embed.state_dict()
|
| 204 |
+
)
|
| 205 |
+
controlnet.context_embedder.load_state_dict(
|
| 206 |
+
transformer.context_embedder.state_dict()
|
| 207 |
+
)
|
| 208 |
+
controlnet.x_embedder.load_state_dict(transformer.x_embedder.state_dict())
|
| 209 |
+
controlnet.transformer_blocks.load_state_dict(
|
| 210 |
+
transformer.transformer_blocks.state_dict(), strict=False
|
| 211 |
+
)
|
| 212 |
+
controlnet.single_transformer_blocks.load_state_dict(
|
| 213 |
+
transformer.single_transformer_blocks.state_dict(), strict=False
|
| 214 |
+
)
|
| 215 |
+
|
| 216 |
+
controlnet.controlnet_x_embedder = zero_module(
|
| 217 |
+
controlnet.controlnet_x_embedder
|
| 218 |
+
)
|
| 219 |
+
|
| 220 |
+
return controlnet
|
| 221 |
+
|
| 222 |
+
def forward(
|
| 223 |
+
self,
|
| 224 |
+
hidden_states: torch.Tensor,
|
| 225 |
+
controlnet_cond: torch.Tensor,
|
| 226 |
+
conditioning_scale: float = 1.0,
|
| 227 |
+
encoder_hidden_states: torch.Tensor = None,
|
| 228 |
+
pooled_projections: torch.Tensor = None,
|
| 229 |
+
timestep: torch.LongTensor = None,
|
| 230 |
+
img_ids: torch.Tensor = None,
|
| 231 |
+
txt_ids: torch.Tensor = None,
|
| 232 |
+
guidance: torch.Tensor = None,
|
| 233 |
+
joint_attention_kwargs: Optional[Dict[str, Any]] = None,
|
| 234 |
+
return_dict: bool = True,
|
| 235 |
+
) -> Union[torch.FloatTensor, Transformer2DModelOutput]:
|
| 236 |
+
"""
|
| 237 |
+
The [`FluxTransformer2DModel`] forward method.
|
| 238 |
+
|
| 239 |
+
Args:
|
| 240 |
+
hidden_states (`torch.FloatTensor` of shape `(batch size, channel, height, width)`):
|
| 241 |
+
Input `hidden_states`.
|
| 242 |
+
encoder_hidden_states (`torch.FloatTensor` of shape `(batch size, sequence_len, embed_dims)`):
|
| 243 |
+
Conditional embeddings (embeddings computed from the input conditions such as prompts) to use.
|
| 244 |
+
pooled_projections (`torch.FloatTensor` of shape `(batch_size, projection_dim)`): Embeddings projected
|
| 245 |
+
from the embeddings of input conditions.
|
| 246 |
+
timestep ( `torch.LongTensor`):
|
| 247 |
+
Used to indicate denoising step.
|
| 248 |
+
block_controlnet_hidden_states: (`list` of `torch.Tensor`):
|
| 249 |
+
A list of tensors that if specified are added to the residuals of transformer blocks.
|
| 250 |
+
joint_attention_kwargs (`dict`, *optional*):
|
| 251 |
+
A kwargs dictionary that if specified is passed along to the `AttentionProcessor` as defined under
|
| 252 |
+
`self.processor` in
|
| 253 |
+
[diffusers.models.attention_processor](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py).
|
| 254 |
+
return_dict (`bool`, *optional*, defaults to `True`):
|
| 255 |
+
Whether or not to return a [`~models.transformer_2d.Transformer2DModelOutput`] instead of a plain
|
| 256 |
+
tuple.
|
| 257 |
+
|
| 258 |
+
Returns:
|
| 259 |
+
If `return_dict` is True, an [`~models.transformer_2d.Transformer2DModelOutput`] is returned, otherwise a
|
| 260 |
+
`tuple` where the first element is the sample tensor.
|
| 261 |
+
"""
|
| 262 |
+
if joint_attention_kwargs is not None:
|
| 263 |
+
joint_attention_kwargs = joint_attention_kwargs.copy()
|
| 264 |
+
lora_scale = joint_attention_kwargs.pop("scale", 1.0)
|
| 265 |
+
else:
|
| 266 |
+
lora_scale = 1.0
|
| 267 |
+
|
| 268 |
+
if USE_PEFT_BACKEND:
|
| 269 |
+
# weight the lora layers by setting `lora_scale` for each PEFT layer
|
| 270 |
+
scale_lora_layers(self, lora_scale)
|
| 271 |
+
else:
|
| 272 |
+
if (
|
| 273 |
+
joint_attention_kwargs is not None
|
| 274 |
+
and joint_attention_kwargs.get("scale", None) is not None
|
| 275 |
+
):
|
| 276 |
+
logger.warning(
|
| 277 |
+
"Passing `scale` via `joint_attention_kwargs` when not using the PEFT backend is ineffective."
|
| 278 |
+
)
|
| 279 |
+
hidden_states = self.x_embedder(hidden_states)
|
| 280 |
+
|
| 281 |
+
# add condition
|
| 282 |
+
hidden_states = hidden_states + self.controlnet_x_embedder(controlnet_cond)
|
| 283 |
+
|
| 284 |
+
timestep = timestep.to(hidden_states.dtype) * 1000
|
| 285 |
+
if guidance is not None:
|
| 286 |
+
guidance = guidance.to(hidden_states.dtype) * 1000
|
| 287 |
+
else:
|
| 288 |
+
guidance = None
|
| 289 |
+
temb = (
|
| 290 |
+
self.time_text_embed(timestep, pooled_projections)
|
| 291 |
+
if guidance is None
|
| 292 |
+
else self.time_text_embed(timestep, guidance, pooled_projections)
|
| 293 |
+
)
|
| 294 |
+
encoder_hidden_states = self.context_embedder(encoder_hidden_states)
|
| 295 |
+
|
| 296 |
+
txt_ids = txt_ids.expand(img_ids.size(0), -1, -1)
|
| 297 |
+
ids = torch.cat((txt_ids, img_ids), dim=1)
|
| 298 |
+
image_rotary_emb = self.pos_embed(ids)
|
| 299 |
+
|
| 300 |
+
block_samples = ()
|
| 301 |
+
for _, block in enumerate(self.transformer_blocks):
|
| 302 |
+
if self.training and self.gradient_checkpointing:
|
| 303 |
+
|
| 304 |
+
def create_custom_forward(module, return_dict=None):
|
| 305 |
+
def custom_forward(*inputs):
|
| 306 |
+
if return_dict is not None:
|
| 307 |
+
return module(*inputs, return_dict=return_dict)
|
| 308 |
+
else:
|
| 309 |
+
return module(*inputs)
|
| 310 |
+
|
| 311 |
+
return custom_forward
|
| 312 |
+
|
| 313 |
+
ckpt_kwargs: Dict[str, Any] = (
|
| 314 |
+
{"use_reentrant": False} if is_torch_version(">=", "1.11.0") else {}
|
| 315 |
+
)
|
| 316 |
+
(
|
| 317 |
+
encoder_hidden_states,
|
| 318 |
+
hidden_states,
|
| 319 |
+
) = torch.utils.checkpoint.checkpoint(
|
| 320 |
+
create_custom_forward(block),
|
| 321 |
+
hidden_states,
|
| 322 |
+
encoder_hidden_states,
|
| 323 |
+
temb,
|
| 324 |
+
image_rotary_emb,
|
| 325 |
+
**ckpt_kwargs,
|
| 326 |
+
)
|
| 327 |
+
|
| 328 |
+
else:
|
| 329 |
+
encoder_hidden_states, hidden_states = block(
|
| 330 |
+
hidden_states=hidden_states,
|
| 331 |
+
encoder_hidden_states=encoder_hidden_states,
|
| 332 |
+
temb=temb,
|
| 333 |
+
image_rotary_emb=image_rotary_emb,
|
| 334 |
+
)
|
| 335 |
+
block_samples = block_samples + (hidden_states,)
|
| 336 |
+
|
| 337 |
+
hidden_states = torch.cat([encoder_hidden_states, hidden_states], dim=1)
|
| 338 |
+
|
| 339 |
+
single_block_samples = ()
|
| 340 |
+
for _, block in enumerate(self.single_transformer_blocks):
|
| 341 |
+
if self.training and self.gradient_checkpointing:
|
| 342 |
+
|
| 343 |
+
def create_custom_forward(module, return_dict=None):
|
| 344 |
+
def custom_forward(*inputs):
|
| 345 |
+
if return_dict is not None:
|
| 346 |
+
return module(*inputs, return_dict=return_dict)
|
| 347 |
+
else:
|
| 348 |
+
return module(*inputs)
|
| 349 |
+
|
| 350 |
+
return custom_forward
|
| 351 |
+
|
| 352 |
+
ckpt_kwargs: Dict[str, Any] = (
|
| 353 |
+
{"use_reentrant": False} if is_torch_version(">=", "1.11.0") else {}
|
| 354 |
+
)
|
| 355 |
+
hidden_states = torch.utils.checkpoint.checkpoint(
|
| 356 |
+
create_custom_forward(block),
|
| 357 |
+
hidden_states,
|
| 358 |
+
temb,
|
| 359 |
+
image_rotary_emb,
|
| 360 |
+
**ckpt_kwargs,
|
| 361 |
+
)
|
| 362 |
+
|
| 363 |
+
else:
|
| 364 |
+
hidden_states = block(
|
| 365 |
+
hidden_states=hidden_states,
|
| 366 |
+
temb=temb,
|
| 367 |
+
image_rotary_emb=image_rotary_emb,
|
| 368 |
+
)
|
| 369 |
+
single_block_samples = single_block_samples + (
|
| 370 |
+
hidden_states[:, encoder_hidden_states.shape[1] :],
|
| 371 |
+
)
|
| 372 |
+
|
| 373 |
+
# controlnet block
|
| 374 |
+
controlnet_block_samples = ()
|
| 375 |
+
for block_sample, controlnet_block in zip(
|
| 376 |
+
block_samples, self.controlnet_blocks
|
| 377 |
+
):
|
| 378 |
+
block_sample = controlnet_block(block_sample)
|
| 379 |
+
controlnet_block_samples = controlnet_block_samples + (block_sample,)
|
| 380 |
+
|
| 381 |
+
controlnet_single_block_samples = ()
|
| 382 |
+
for single_block_sample, controlnet_block in zip(
|
| 383 |
+
single_block_samples, self.controlnet_single_blocks
|
| 384 |
+
):
|
| 385 |
+
single_block_sample = controlnet_block(single_block_sample)
|
| 386 |
+
controlnet_single_block_samples = controlnet_single_block_samples + (
|
| 387 |
+
single_block_sample,
|
| 388 |
+
)
|
| 389 |
+
|
| 390 |
+
# scaling
|
| 391 |
+
controlnet_block_samples = [
|
| 392 |
+
sample * conditioning_scale for sample in controlnet_block_samples
|
| 393 |
+
]
|
| 394 |
+
controlnet_single_block_samples = [
|
| 395 |
+
sample * conditioning_scale for sample in controlnet_single_block_samples
|
| 396 |
+
]
|
| 397 |
+
|
| 398 |
+
#
|
| 399 |
+
controlnet_block_samples = (
|
| 400 |
+
None if len(controlnet_block_samples) == 0 else controlnet_block_samples
|
| 401 |
+
)
|
| 402 |
+
controlnet_single_block_samples = (
|
| 403 |
+
None
|
| 404 |
+
if len(controlnet_single_block_samples) == 0
|
| 405 |
+
else controlnet_single_block_samples
|
| 406 |
+
)
|
| 407 |
+
|
| 408 |
+
if USE_PEFT_BACKEND:
|
| 409 |
+
# remove `lora_scale` from each PEFT layer
|
| 410 |
+
unscale_lora_layers(self, lora_scale)
|
| 411 |
+
|
| 412 |
+
if not return_dict:
|
| 413 |
+
return (controlnet_block_samples, controlnet_single_block_samples)
|
| 414 |
+
|
| 415 |
+
return FluxControlNetOutput(
|
| 416 |
+
controlnet_block_samples=controlnet_block_samples,
|
| 417 |
+
controlnet_single_block_samples=controlnet_single_block_samples,
|
| 418 |
+
)
|
images/0.jpg
ADDED
|
images/1.jpg
ADDED
|
images/2.jpg
ADDED
|
images/3.jpg
ADDED
|
images/alibaba.png
ADDED
|
images/alibabaalimama.png
ADDED
|
images/alimama.png
ADDED
|
images/flux1.jpg
ADDED
|
images/flux2.jpg
ADDED
|
images/flux3.jpg
ADDED
|
pipeline_flux_controlnet_inpaint.py
ADDED
|
@@ -0,0 +1,1066 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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formers import (
|
| 7 |
+
CLIPTextModel,
|
| 8 |
+
CLIPTokenizer,
|
| 9 |
+
T5EncoderModel,
|
| 10 |
+
T5TokenizerFast,
|
| 11 |
+
)
|
| 12 |
+
|
| 13 |
+
from diffusers.image_processor import PipelineImageInput, VaeImageProcessor
|
| 14 |
+
from diffusers.loaders import FluxLoraLoaderMixin
|
| 15 |
+
from diffusers.models.autoencoders import AutoencoderKL
|
| 16 |
+
|
| 17 |
+
from diffusers.schedulers import FlowMatchEulerDiscreteScheduler
|
| 18 |
+
from diffusers.utils import (
|
| 19 |
+
USE_PEFT_BACKEND,
|
| 20 |
+
is_torch_xla_available,
|
| 21 |
+
logging,
|
| 22 |
+
replace_example_docstring,
|
| 23 |
+
scale_lora_layers,
|
| 24 |
+
unscale_lora_layers,
|
| 25 |
+
)
|
| 26 |
+
from diffusers.utils.torch_utils import randn_tensor
|
| 27 |
+
from diffusers.pipelines.pipeline_utils import DiffusionPipeline
|
| 28 |
+
from diffusers.pipelines.flux.pipeline_output import FluxPipelineOutput
|
| 29 |
+
|
| 30 |
+
from transformer_flux import FluxTransformer2DModel
|
| 31 |
+
from controlnet_flux import FluxControlNetModel
|
| 32 |
+
|
| 33 |
+
if is_torch_xla_available():
|
| 34 |
+
import torch_xla.core.xla_model as xm
|
| 35 |
+
|
| 36 |
+
XLA_AVAILABLE = True
|
| 37 |
+
else:
|
| 38 |
+
XLA_AVAILABLE = False
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
logger = logging.get_logger(__name__) # pylint: disable=invalid-name
|
| 42 |
+
|
| 43 |
+
EXAMPLE_DOC_STRING = """
|
| 44 |
+
Examples:
|
| 45 |
+
```py
|
| 46 |
+
>>> import torch
|
| 47 |
+
>>> from diffusers.utils import load_image
|
| 48 |
+
>>> from diffusers import FluxControlNetPipeline
|
| 49 |
+
>>> from diffusers import FluxControlNetModel
|
| 50 |
+
|
| 51 |
+
>>> controlnet_model = "InstantX/FLUX.1-dev-controlnet-canny-alpha"
|
| 52 |
+
>>> controlnet = FluxControlNetModel.from_pretrained(controlnet_model, torch_dtype=torch.bfloat16)
|
| 53 |
+
>>> pipe = FluxControlNetPipeline.from_pretrained(
|
| 54 |
+
... base_model, controlnet=controlnet, torch_dtype=torch.bfloat16
|
| 55 |
+
... )
|
| 56 |
+
>>> pipe.to("cuda")
|
| 57 |
+
>>> control_image = load_image("https://huggingface.co/InstantX/SD3-Controlnet-Canny/resolve/main/canny.jpg")
|
| 58 |
+
>>> control_mask = load_image("https://huggingface.co/InstantX/SD3-Controlnet-Canny/resolve/main/canny.jpg")
|
| 59 |
+
>>> prompt = "A girl in city, 25 years old, cool, futuristic"
|
| 60 |
+
>>> image = pipe(
|
| 61 |
+
... prompt,
|
| 62 |
+
... control_image=control_image,
|
| 63 |
+
... controlnet_conditioning_scale=0.6,
|
| 64 |
+
... num_inference_steps=28,
|
| 65 |
+
... guidance_scale=3.5,
|
| 66 |
+
... ).images[0]
|
| 67 |
+
>>> image.save("flux.png")
|
| 68 |
+
```
|
| 69 |
+
"""
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
# Copied from diffusers.pipelines.flux.pipeline_flux.calculate_shift
|
| 73 |
+
def calculate_shift(
|
| 74 |
+
image_seq_len,
|
| 75 |
+
base_seq_len: int = 256,
|
| 76 |
+
max_seq_len: int = 4096,
|
| 77 |
+
base_shift: float = 0.5,
|
| 78 |
+
max_shift: float = 1.16,
|
| 79 |
+
):
|
| 80 |
+
m = (max_shift - base_shift) / (max_seq_len - base_seq_len)
|
| 81 |
+
b = base_shift - m * base_seq_len
|
| 82 |
+
mu = image_seq_len * m + b
|
| 83 |
+
return mu
|
| 84 |
+
|
| 85 |
+
|
| 86 |
+
# Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.retrieve_timesteps
|
| 87 |
+
def retrieve_timesteps(
|
| 88 |
+
scheduler,
|
| 89 |
+
num_inference_steps: Optional[int] = None,
|
| 90 |
+
device: Optional[Union[str, torch.device]] = None,
|
| 91 |
+
timesteps: Optional[List[int]] = None,
|
| 92 |
+
sigmas: Optional[List[float]] = None,
|
| 93 |
+
**kwargs,
|
| 94 |
+
):
|
| 95 |
+
"""
|
| 96 |
+
Calls the scheduler's `set_timesteps` method and retrieves timesteps from the scheduler after the call. Handles
|
| 97 |
+
custom timesteps. Any kwargs will be supplied to `scheduler.set_timesteps`.
|
| 98 |
+
|
| 99 |
+
Args:
|
| 100 |
+
scheduler (`SchedulerMixin`):
|
| 101 |
+
The scheduler to get timesteps from.
|
| 102 |
+
num_inference_steps (`int`):
|
| 103 |
+
The number of diffusion steps used when generating samples with a pre-trained model. If used, `timesteps`
|
| 104 |
+
must be `None`.
|
| 105 |
+
device (`str` or `torch.device`, *optional*):
|
| 106 |
+
The device to which the timesteps should be moved to. If `None`, the timesteps are not moved.
|
| 107 |
+
timesteps (`List[int]`, *optional*):
|
| 108 |
+
Custom timesteps used to override the timestep spacing strategy of the scheduler. If `timesteps` is passed,
|
| 109 |
+
`num_inference_steps` and `sigmas` must be `None`.
|
| 110 |
+
sigmas (`List[float]`, *optional*):
|
| 111 |
+
Custom sigmas used to override the timestep spacing strategy of the scheduler. If `sigmas` is passed,
|
| 112 |
+
`num_inference_steps` and `timesteps` must be `None`.
|
| 113 |
+
|
| 114 |
+
Returns:
|
| 115 |
+
`Tuple[torch.Tensor, int]`: A tuple where the first element is the timestep schedule from the scheduler and the
|
| 116 |
+
second element is the number of inference steps.
|
| 117 |
+
"""
|
| 118 |
+
if timesteps is not None and sigmas is not None:
|
| 119 |
+
raise ValueError(
|
| 120 |
+
"Only one of `timesteps` or `sigmas` can be passed. Please choose one to set custom values"
|
| 121 |
+
)
|
| 122 |
+
if timesteps is not None:
|
| 123 |
+
accepts_timesteps = "timesteps" in set(
|
| 124 |
+
inspect.signature(scheduler.set_timesteps).parameters.keys()
|
| 125 |
+
)
|
| 126 |
+
if not accepts_timesteps:
|
| 127 |
+
raise ValueError(
|
| 128 |
+
f"The current scheduler class {scheduler.__class__}'s `set_timesteps` does not support custom"
|
| 129 |
+
f" timestep schedules. Please check whether you are using the correct scheduler."
|
| 130 |
+
)
|
| 131 |
+
scheduler.set_timesteps(timesteps=timesteps, device=device, **kwargs)
|
| 132 |
+
timesteps = scheduler.timesteps
|
| 133 |
+
num_inference_steps = len(timesteps)
|
| 134 |
+
elif sigmas is not None:
|
| 135 |
+
accept_sigmas = "sigmas" in set(
|
| 136 |
+
inspect.signature(scheduler.set_timesteps).parameters.keys()
|
| 137 |
+
)
|
| 138 |
+
if not accept_sigmas:
|
| 139 |
+
raise ValueError(
|
| 140 |
+
f"The current scheduler class {scheduler.__class__}'s `set_timesteps` does not support custom"
|
| 141 |
+
f" sigmas schedules. Please check whether you are using the correct scheduler."
|
| 142 |
+
)
|
| 143 |
+
scheduler.set_timesteps(sigmas=sigmas, device=device, **kwargs)
|
| 144 |
+
timesteps = scheduler.timesteps
|
| 145 |
+
num_inference_steps = len(timesteps)
|
| 146 |
+
else:
|
| 147 |
+
scheduler.set_timesteps(num_inference_steps, device=device, **kwargs)
|
| 148 |
+
timesteps = scheduler.timesteps
|
| 149 |
+
return timesteps, num_inference_steps
|
| 150 |
+
|
| 151 |
+
|
| 152 |
+
def move_to_device(tensor, device):
|
| 153 |
+
if isinstance(tensor, torch.Tensor):
|
| 154 |
+
return tensor.to(device)
|
| 155 |
+
return tensor
|
| 156 |
+
|
| 157 |
+
|
| 158 |
+
class FluxControlNetInpaintingPipeline(DiffusionPipeline, FluxLoraLoaderMixin):
|
| 159 |
+
r"""
|
| 160 |
+
The Flux pipeline for text-to-image generation.
|
| 161 |
+
|
| 162 |
+
Reference: https://blackforestlabs.ai/announcing-black-forest-labs/
|
| 163 |
+
|
| 164 |
+
Args:
|
| 165 |
+
transformer ([`FluxTransformer2DModel`]):
|
| 166 |
+
Conditional Transformer (MMDiT) architecture to denoise the encoded image latents.
|
| 167 |
+
scheduler ([`FlowMatchEulerDiscreteScheduler`]):
|
| 168 |
+
A scheduler to be used in combination with `transformer` to denoise the encoded image latents.
|
| 169 |
+
vae ([`AutoencoderKL`]):
|
| 170 |
+
Variational Auto-Encoder (VAE) Model to encode and decode images to and from latent representations.
|
| 171 |
+
text_encoder ([`CLIPTextModel`]):
|
| 172 |
+
[CLIP](https://huggingface.co/docs/transformers/model_doc/clip#transformers.CLIPTextModel), specifically
|
| 173 |
+
the [clip-vit-large-patch14](https://huggingface.co/openai/clip-vit-large-patch14) variant.
|
| 174 |
+
text_encoder_2 ([`T5EncoderModel`]):
|
| 175 |
+
[T5](https://huggingface.co/docs/transformers/en/model_doc/t5#transformers.T5EncoderModel), specifically
|
| 176 |
+
the [google/t5-v1_1-xxl](https://huggingface.co/google/t5-v1_1-xxl) variant.
|
| 177 |
+
tokenizer (`CLIPTokenizer`):
|
| 178 |
+
Tokenizer of class
|
| 179 |
+
[CLIPTokenizer](https://huggingface.co/docs/transformers/en/model_doc/clip#transformers.CLIPTokenizer).
|
| 180 |
+
tokenizer_2 (`T5TokenizerFast`):
|
| 181 |
+
Second Tokenizer of class
|
| 182 |
+
[T5TokenizerFast](https://huggingface.co/docs/transformers/en/model_doc/t5#transformers.T5TokenizerFast).
|
| 183 |
+
"""
|
| 184 |
+
|
| 185 |
+
model_cpu_offload_seq = "text_encoder->text_encoder_2->transformer->vae"
|
| 186 |
+
_optional_components = []
|
| 187 |
+
_callback_tensor_inputs = ["latents", "prompt_embeds"]
|
| 188 |
+
|
| 189 |
+
def __init__(
|
| 190 |
+
self,
|
| 191 |
+
scheduler: FlowMatchEulerDiscreteScheduler,
|
| 192 |
+
vae: AutoencoderKL,
|
| 193 |
+
text_encoder: CLIPTextModel,
|
| 194 |
+
tokenizer: CLIPTokenizer,
|
| 195 |
+
text_encoder_2: T5EncoderModel,
|
| 196 |
+
tokenizer_2: T5TokenizerFast,
|
| 197 |
+
transformer: FluxTransformer2DModel,
|
| 198 |
+
controlnet: FluxControlNetModel,
|
| 199 |
+
):
|
| 200 |
+
super().__init__()
|
| 201 |
+
|
| 202 |
+
self.register_modules(
|
| 203 |
+
vae=vae,
|
| 204 |
+
text_encoder=text_encoder,
|
| 205 |
+
text_encoder_2=text_encoder_2,
|
| 206 |
+
tokenizer=tokenizer,
|
| 207 |
+
tokenizer_2=tokenizer_2,
|
| 208 |
+
transformer=transformer,
|
| 209 |
+
scheduler=scheduler,
|
| 210 |
+
controlnet=controlnet,
|
| 211 |
+
)
|
| 212 |
+
self.vae_scale_factor = (
|
| 213 |
+
2 ** (len(self.vae.config.block_out_channels))
|
| 214 |
+
if hasattr(self, "vae") and self.vae is not None
|
| 215 |
+
else 16
|
| 216 |
+
)
|
| 217 |
+
self.image_processor = VaeImageProcessor(
|
| 218 |
+
vae_scale_factor=self.vae_scale_factor,
|
| 219 |
+
do_resize=True,
|
| 220 |
+
do_convert_rgb=True,
|
| 221 |
+
do_normalize=True,
|
| 222 |
+
)
|
| 223 |
+
self.mask_processor = VaeImageProcessor(
|
| 224 |
+
vae_scale_factor=self.vae_scale_factor,
|
| 225 |
+
do_resize=True,
|
| 226 |
+
do_convert_grayscale=True,
|
| 227 |
+
do_normalize=False,
|
| 228 |
+
do_binarize=True,
|
| 229 |
+
)
|
| 230 |
+
self.tokenizer_max_length = (
|
| 231 |
+
self.tokenizer.model_max_length
|
| 232 |
+
if hasattr(self, "tokenizer") and self.tokenizer is not None
|
| 233 |
+
else 77
|
| 234 |
+
)
|
| 235 |
+
self.default_sample_size = 64
|
| 236 |
+
|
| 237 |
+
@property
|
| 238 |
+
def do_classifier_free_guidance(self):
|
| 239 |
+
return self._guidance_scale > 1
|
| 240 |
+
|
| 241 |
+
def _get_t5_prompt_embeds(
|
| 242 |
+
self,
|
| 243 |
+
prompt: Union[str, List[str]] = None,
|
| 244 |
+
num_images_per_prompt: int = 1,
|
| 245 |
+
max_sequence_length: int = 512,
|
| 246 |
+
device: Optional[torch.device] = None,
|
| 247 |
+
dtype: Optional[torch.dtype] = None,
|
| 248 |
+
):
|
| 249 |
+
device = device or self._execution_device
|
| 250 |
+
dtype = dtype or self.text_encoder.dtype
|
| 251 |
+
|
| 252 |
+
prompt = [prompt] if isinstance(prompt, str) else prompt
|
| 253 |
+
batch_size = len(prompt)
|
| 254 |
+
|
| 255 |
+
text_inputs = self.tokenizer_2(
|
| 256 |
+
prompt,
|
| 257 |
+
padding="max_length",
|
| 258 |
+
max_length=max_sequence_length,
|
| 259 |
+
truncation=True,
|
| 260 |
+
return_length=False,
|
| 261 |
+
return_overflowing_tokens=False,
|
| 262 |
+
return_tensors="pt",
|
| 263 |
+
)
|
| 264 |
+
text_input_ids = text_inputs.input_ids
|
| 265 |
+
untruncated_ids = self.tokenizer_2(
|
| 266 |
+
prompt, padding="longest", return_tensors="pt"
|
| 267 |
+
).input_ids
|
| 268 |
+
|
| 269 |
+
if untruncated_ids.shape[-1] >= text_input_ids.shape[-1] and not torch.equal(
|
| 270 |
+
text_input_ids, untruncated_ids
|
| 271 |
+
):
|
| 272 |
+
removed_text = self.tokenizer_2.batch_decode(
|
| 273 |
+
untruncated_ids[:, self.tokenizer_max_length - 1 : -1]
|
| 274 |
+
)
|
| 275 |
+
logger.warning(
|
| 276 |
+
"The following part of your input was truncated because `max_sequence_length` is set to "
|
| 277 |
+
f" {max_sequence_length} tokens: {removed_text}"
|
| 278 |
+
)
|
| 279 |
+
|
| 280 |
+
prompt_embeds = self.text_encoder_2(
|
| 281 |
+
text_input_ids.to(device), output_hidden_states=False
|
| 282 |
+
)[0]
|
| 283 |
+
|
| 284 |
+
dtype = self.text_encoder_2.dtype
|
| 285 |
+
prompt_embeds = prompt_embeds.to(dtype=dtype, device=device)
|
| 286 |
+
|
| 287 |
+
_, seq_len, _ = prompt_embeds.shape
|
| 288 |
+
|
| 289 |
+
# duplicate text embeddings and attention mask for each generation per prompt, using mps friendly method
|
| 290 |
+
prompt_embeds = prompt_embeds.repeat(1, num_images_per_prompt, 1)
|
| 291 |
+
prompt_embeds = prompt_embeds.view(
|
| 292 |
+
batch_size * num_images_per_prompt, seq_len, -1
|
| 293 |
+
)
|
| 294 |
+
|
| 295 |
+
return prompt_embeds
|
| 296 |
+
|
| 297 |
+
def _get_clip_prompt_embeds(
|
| 298 |
+
self,
|
| 299 |
+
prompt: Union[str, List[str]],
|
| 300 |
+
num_images_per_prompt: int = 1,
|
| 301 |
+
device: Optional[torch.device] = None,
|
| 302 |
+
):
|
| 303 |
+
device = device or self._execution_device
|
| 304 |
+
|
| 305 |
+
prompt = [prompt] if isinstance(prompt, str) else prompt
|
| 306 |
+
batch_size = len(prompt)
|
| 307 |
+
|
| 308 |
+
text_inputs = self.tokenizer(
|
| 309 |
+
prompt,
|
| 310 |
+
padding="max_length",
|
| 311 |
+
max_length=self.tokenizer_max_length,
|
| 312 |
+
truncation=True,
|
| 313 |
+
return_overflowing_tokens=False,
|
| 314 |
+
return_length=False,
|
| 315 |
+
return_tensors="pt",
|
| 316 |
+
)
|
| 317 |
+
|
| 318 |
+
text_input_ids = text_inputs.input_ids
|
| 319 |
+
untruncated_ids = self.tokenizer(
|
| 320 |
+
prompt, padding="longest", return_tensors="pt"
|
| 321 |
+
).input_ids
|
| 322 |
+
if untruncated_ids.shape[-1] >= text_input_ids.shape[-1] and not torch.equal(
|
| 323 |
+
text_input_ids, untruncated_ids
|
| 324 |
+
):
|
| 325 |
+
removed_text = self.tokenizer.batch_decode(
|
| 326 |
+
untruncated_ids[:, self.tokenizer_max_length - 1 : -1]
|
| 327 |
+
)
|
| 328 |
+
logger.warning(
|
| 329 |
+
"The following part of your input was truncated because CLIP can only handle sequences up to"
|
| 330 |
+
f" {self.tokenizer_max_length} tokens: {removed_text}"
|
| 331 |
+
)
|
| 332 |
+
prompt_embeds = self.text_encoder(
|
| 333 |
+
text_input_ids.to(device), output_hidden_states=False
|
| 334 |
+
)
|
| 335 |
+
|
| 336 |
+
# Use pooled output of CLIPTextModel
|
| 337 |
+
prompt_embeds = prompt_embeds.pooler_output
|
| 338 |
+
prompt_embeds = prompt_embeds.to(dtype=self.text_encoder.dtype, device=device)
|
| 339 |
+
|
| 340 |
+
# duplicate text embeddings for each generation per prompt, using mps friendly method
|
| 341 |
+
prompt_embeds = prompt_embeds.repeat(1, num_images_per_prompt, 1)
|
| 342 |
+
prompt_embeds = prompt_embeds.view(batch_size * num_images_per_prompt, -1)
|
| 343 |
+
|
| 344 |
+
return prompt_embeds
|
| 345 |
+
|
| 346 |
+
def encode_prompt(
|
| 347 |
+
self,
|
| 348 |
+
prompt: Union[str, List[str]],
|
| 349 |
+
prompt_2: Union[str, List[str]],
|
| 350 |
+
device: Optional[torch.device] = None,
|
| 351 |
+
num_images_per_prompt: int = 1,
|
| 352 |
+
do_classifier_free_guidance: bool = True,
|
| 353 |
+
negative_prompt: Optional[Union[str, List[str]]] = None,
|
| 354 |
+
negative_prompt_2: Optional[Union[str, List[str]]] = None,
|
| 355 |
+
prompt_embeds: Optional[torch.FloatTensor] = None,
|
| 356 |
+
pooled_prompt_embeds: Optional[torch.FloatTensor] = None,
|
| 357 |
+
max_sequence_length: int = 512,
|
| 358 |
+
lora_scale: Optional[float] = None,
|
| 359 |
+
):
|
| 360 |
+
r"""
|
| 361 |
+
|
| 362 |
+
Args:
|
| 363 |
+
prompt (`str` or `List[str]`, *optional*):
|
| 364 |
+
prompt to be encoded
|
| 365 |
+
prompt_2 (`str` or `List[str]`, *optional*):
|
| 366 |
+
The prompt or prompts to be sent to the `tokenizer_2` and `text_encoder_2`. If not defined, `prompt` is
|
| 367 |
+
used in all text-encoders
|
| 368 |
+
device: (`torch.device`):
|
| 369 |
+
torch device
|
| 370 |
+
num_images_per_prompt (`int`):
|
| 371 |
+
number of images that should be generated per prompt
|
| 372 |
+
do_classifier_free_guidance (`bool`):
|
| 373 |
+
whether to use classifier-free guidance or not
|
| 374 |
+
negative_prompt (`str` or `List[str]`, *optional*):
|
| 375 |
+
negative prompt to be encoded
|
| 376 |
+
negative_prompt_2 (`str` or `List[str]`, *optional*):
|
| 377 |
+
negative prompt to be sent to the `tokenizer_2` and `text_encoder_2`. If not defined, `negative_prompt` is
|
| 378 |
+
used in all text-encoders
|
| 379 |
+
prompt_embeds (`torch.FloatTensor`, *optional*):
|
| 380 |
+
Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not
|
| 381 |
+
provided, text embeddings will be generated from `prompt` input argument.
|
| 382 |
+
pooled_prompt_embeds (`torch.FloatTensor`, *optional*):
|
| 383 |
+
Pre-generated pooled text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting.
|
| 384 |
+
If not provided, pooled text embeddings will be generated from `prompt` input argument.
|
| 385 |
+
clip_skip (`int`, *optional*):
|
| 386 |
+
Number of layers to be skipped from CLIP while computing the prompt embeddings. A value of 1 means that
|
| 387 |
+
the output of the pre-final layer will be used for computing the prompt embeddings.
|
| 388 |
+
lora_scale (`float`, *optional*):
|
| 389 |
+
A lora scale that will be applied to all LoRA layers of the text encoder if LoRA layers are loaded.
|
| 390 |
+
"""
|
| 391 |
+
device = device or self._execution_device
|
| 392 |
+
|
| 393 |
+
# set lora scale so that monkey patched LoRA
|
| 394 |
+
# function of text encoder can correctly access it
|
| 395 |
+
if lora_scale is not None and isinstance(self, FluxLoraLoaderMixin):
|
| 396 |
+
self._lora_scale = lora_scale
|
| 397 |
+
|
| 398 |
+
# dynamically adjust the LoRA scale
|
| 399 |
+
if self.text_encoder is not None and USE_PEFT_BACKEND:
|
| 400 |
+
scale_lora_layers(self.text_encoder, lora_scale)
|
| 401 |
+
if self.text_encoder_2 is not None and USE_PEFT_BACKEND:
|
| 402 |
+
scale_lora_layers(self.text_encoder_2, lora_scale)
|
| 403 |
+
|
| 404 |
+
prompt = [prompt] if isinstance(prompt, str) else prompt
|
| 405 |
+
if prompt is not None:
|
| 406 |
+
batch_size = len(prompt)
|
| 407 |
+
else:
|
| 408 |
+
batch_size = prompt_embeds.shape[0]
|
| 409 |
+
|
| 410 |
+
if prompt_embeds is None:
|
| 411 |
+
prompt_2 = prompt_2 or prompt
|
| 412 |
+
prompt_2 = [prompt_2] if isinstance(prompt_2, str) else prompt_2
|
| 413 |
+
|
| 414 |
+
# We only use the pooled prompt output from the CLIPTextModel
|
| 415 |
+
pooled_prompt_embeds = self._get_clip_prompt_embeds(
|
| 416 |
+
prompt=prompt,
|
| 417 |
+
device=device,
|
| 418 |
+
num_images_per_prompt=num_images_per_prompt,
|
| 419 |
+
)
|
| 420 |
+
prompt_embeds = self._get_t5_prompt_embeds(
|
| 421 |
+
prompt=prompt_2,
|
| 422 |
+
num_images_per_prompt=num_images_per_prompt,
|
| 423 |
+
max_sequence_length=max_sequence_length,
|
| 424 |
+
device=device,
|
| 425 |
+
)
|
| 426 |
+
|
| 427 |
+
if do_classifier_free_guidance:
|
| 428 |
+
# 处理 negative prompt
|
| 429 |
+
negative_prompt = negative_prompt or ""
|
| 430 |
+
negative_prompt_2 = negative_prompt_2 or negative_prompt
|
| 431 |
+
|
| 432 |
+
negative_pooled_prompt_embeds = self._get_clip_prompt_embeds(
|
| 433 |
+
negative_prompt,
|
| 434 |
+
device=device,
|
| 435 |
+
num_images_per_prompt=num_images_per_prompt,
|
| 436 |
+
)
|
| 437 |
+
negative_prompt_embeds = self._get_t5_prompt_embeds(
|
| 438 |
+
negative_prompt_2,
|
| 439 |
+
num_images_per_prompt=num_images_per_prompt,
|
| 440 |
+
max_sequence_length=max_sequence_length,
|
| 441 |
+
device=device,
|
| 442 |
+
)
|
| 443 |
+
else:
|
| 444 |
+
negative_pooled_prompt_embeds = None
|
| 445 |
+
negative_prompt_embeds = None
|
| 446 |
+
|
| 447 |
+
if self.text_encoder is not None:
|
| 448 |
+
if isinstance(self, FluxLoraLoaderMixin) and USE_PEFT_BACKEND:
|
| 449 |
+
# Retrieve the original scale by scaling back the LoRA layers
|
| 450 |
+
unscale_lora_layers(self.text_encoder, lora_scale)
|
| 451 |
+
|
| 452 |
+
if self.text_encoder_2 is not None:
|
| 453 |
+
if isinstance(self, FluxLoraLoaderMixin) and USE_PEFT_BACKEND:
|
| 454 |
+
# Retrieve the original scale by scaling back the LoRA layers
|
| 455 |
+
unscale_lora_layers(self.text_encoder_2, lora_scale)
|
| 456 |
+
|
| 457 |
+
text_ids = torch.zeros(batch_size, prompt_embeds.shape[1], 3).to(
|
| 458 |
+
device=device, dtype=self.text_encoder.dtype
|
| 459 |
+
)
|
| 460 |
+
|
| 461 |
+
return (
|
| 462 |
+
prompt_embeds,
|
| 463 |
+
pooled_prompt_embeds,
|
| 464 |
+
negative_prompt_embeds,
|
| 465 |
+
negative_pooled_prompt_embeds,
|
| 466 |
+
text_ids,
|
| 467 |
+
)
|
| 468 |
+
|
| 469 |
+
def check_inputs(
|
| 470 |
+
self,
|
| 471 |
+
prompt,
|
| 472 |
+
prompt_2,
|
| 473 |
+
height,
|
| 474 |
+
width,
|
| 475 |
+
prompt_embeds=None,
|
| 476 |
+
pooled_prompt_embeds=None,
|
| 477 |
+
callback_on_step_end_tensor_inputs=None,
|
| 478 |
+
max_sequence_length=None,
|
| 479 |
+
):
|
| 480 |
+
if height % 8 != 0 or width % 8 != 0:
|
| 481 |
+
raise ValueError(
|
| 482 |
+
f"`height` and `width` have to be divisible by 8 but are {height} and {width}."
|
| 483 |
+
)
|
| 484 |
+
|
| 485 |
+
if callback_on_step_end_tensor_inputs is not None and not all(
|
| 486 |
+
k in self._callback_tensor_inputs
|
| 487 |
+
for k in callback_on_step_end_tensor_inputs
|
| 488 |
+
):
|
| 489 |
+
raise ValueError(
|
| 490 |
+
f"`callback_on_step_end_tensor_inputs` has to be in {self._callback_tensor_inputs}, but found {[k for k in callback_on_step_end_tensor_inputs if k not in self._callback_tensor_inputs]}"
|
| 491 |
+
)
|
| 492 |
+
|
| 493 |
+
if prompt is not None and prompt_embeds is not None:
|
| 494 |
+
raise ValueError(
|
| 495 |
+
f"Cannot forward both `prompt`: {prompt} and `prompt_embeds`: {prompt_embeds}. Please make sure to"
|
| 496 |
+
" only forward one of the two."
|
| 497 |
+
)
|
| 498 |
+
elif prompt_2 is not None and prompt_embeds is not None:
|
| 499 |
+
raise ValueError(
|
| 500 |
+
f"Cannot forward both `prompt_2`: {prompt_2} and `prompt_embeds`: {prompt_embeds}. Please make sure to"
|
| 501 |
+
" only forward one of the two."
|
| 502 |
+
)
|
| 503 |
+
elif prompt is None and prompt_embeds is None:
|
| 504 |
+
raise ValueError(
|
| 505 |
+
"Provide either `prompt` or `prompt_embeds`. Cannot leave both `prompt` and `prompt_embeds` undefined."
|
| 506 |
+
)
|
| 507 |
+
elif prompt is not None and (
|
| 508 |
+
not isinstance(prompt, str) and not isinstance(prompt, list)
|
| 509 |
+
):
|
| 510 |
+
raise ValueError(
|
| 511 |
+
f"`prompt` has to be of type `str` or `list` but is {type(prompt)}"
|
| 512 |
+
)
|
| 513 |
+
elif prompt_2 is not None and (
|
| 514 |
+
not isinstance(prompt_2, str) and not isinstance(prompt_2, list)
|
| 515 |
+
):
|
| 516 |
+
raise ValueError(
|
| 517 |
+
f"`prompt_2` has to be of type `str` or `list` but is {type(prompt_2)}"
|
| 518 |
+
)
|
| 519 |
+
|
| 520 |
+
if prompt_embeds is not None and pooled_prompt_embeds is None:
|
| 521 |
+
raise ValueError(
|
| 522 |
+
"If `prompt_embeds` are provided, `pooled_prompt_embeds` also have to be passed. Make sure to generate `pooled_prompt_embeds` from the same text encoder that was used to generate `prompt_embeds`."
|
| 523 |
+
)
|
| 524 |
+
|
| 525 |
+
if max_sequence_length is not None and max_sequence_length > 512:
|
| 526 |
+
raise ValueError(
|
| 527 |
+
f"`max_sequence_length` cannot be greater than 512 but is {max_sequence_length}"
|
| 528 |
+
)
|
| 529 |
+
|
| 530 |
+
# Copied from diffusers.pipelines.flux.pipeline_flux._prepare_latent_image_ids
|
| 531 |
+
@staticmethod
|
| 532 |
+
def _prepare_latent_image_ids(batch_size, height, width, device, dtype):
|
| 533 |
+
latent_image_ids = torch.zeros(height // 2, width // 2, 3)
|
| 534 |
+
latent_image_ids[..., 1] = (
|
| 535 |
+
latent_image_ids[..., 1] + torch.arange(height // 2)[:, None]
|
| 536 |
+
)
|
| 537 |
+
latent_image_ids[..., 2] = (
|
| 538 |
+
latent_image_ids[..., 2] + torch.arange(width // 2)[None, :]
|
| 539 |
+
)
|
| 540 |
+
|
| 541 |
+
(
|
| 542 |
+
latent_image_id_height,
|
| 543 |
+
latent_image_id_width,
|
| 544 |
+
latent_image_id_channels,
|
| 545 |
+
) = latent_image_ids.shape
|
| 546 |
+
|
| 547 |
+
latent_image_ids = latent_image_ids[None, :].repeat(batch_size, 1, 1, 1)
|
| 548 |
+
latent_image_ids = latent_image_ids.reshape(
|
| 549 |
+
batch_size,
|
| 550 |
+
latent_image_id_height * latent_image_id_width,
|
| 551 |
+
latent_image_id_channels,
|
| 552 |
+
)
|
| 553 |
+
|
| 554 |
+
return latent_image_ids.to(device=device, dtype=dtype)
|
| 555 |
+
|
| 556 |
+
# Copied from diffusers.pipelines.flux.pipeline_flux._pack_latents
|
| 557 |
+
@staticmethod
|
| 558 |
+
def _pack_latents(latents, batch_size, num_channels_latents, height, width):
|
| 559 |
+
latents = latents.view(
|
| 560 |
+
batch_size, num_channels_latents, height // 2, 2, width // 2, 2
|
| 561 |
+
)
|
| 562 |
+
latents = latents.permute(0, 2, 4, 1, 3, 5)
|
| 563 |
+
latents = latents.reshape(
|
| 564 |
+
batch_size, (height // 2) * (width // 2), num_channels_latents * 4
|
| 565 |
+
)
|
| 566 |
+
|
| 567 |
+
return latents
|
| 568 |
+
|
| 569 |
+
# Copied from diffusers.pipelines.flux.pipeline_flux._unpack_latents
|
| 570 |
+
@staticmethod
|
| 571 |
+
def _unpack_latents(latents, height, width, vae_scale_factor):
|
| 572 |
+
batch_size, num_patches, channels = latents.shape
|
| 573 |
+
|
| 574 |
+
height = height // vae_scale_factor
|
| 575 |
+
width = width // vae_scale_factor
|
| 576 |
+
|
| 577 |
+
latents = latents.view(batch_size, height, width, channels // 4, 2, 2)
|
| 578 |
+
latents = latents.permute(0, 3, 1, 4, 2, 5)
|
| 579 |
+
|
| 580 |
+
latents = latents.reshape(
|
| 581 |
+
batch_size, channels // (2 * 2), height * 2, width * 2
|
| 582 |
+
)
|
| 583 |
+
|
| 584 |
+
return latents
|
| 585 |
+
|
| 586 |
+
# Copied from diffusers.pipelines.flux.pipeline_flux.prepare_latents
|
| 587 |
+
def prepare_latents(
|
| 588 |
+
self,
|
| 589 |
+
batch_size,
|
| 590 |
+
num_channels_latents,
|
| 591 |
+
height,
|
| 592 |
+
width,
|
| 593 |
+
dtype,
|
| 594 |
+
device,
|
| 595 |
+
generator,
|
| 596 |
+
latents=None,
|
| 597 |
+
):
|
| 598 |
+
height = 2 * (int(height) // self.vae_scale_factor)
|
| 599 |
+
width = 2 * (int(width) // self.vae_scale_factor)
|
| 600 |
+
|
| 601 |
+
shape = (batch_size, num_channels_latents, height, width)
|
| 602 |
+
|
| 603 |
+
if latents is not None:
|
| 604 |
+
latent_image_ids = self._prepare_latent_image_ids(
|
| 605 |
+
batch_size, height, width, device, dtype
|
| 606 |
+
)
|
| 607 |
+
return latents.to(device=device, dtype=dtype), latent_image_ids
|
| 608 |
+
|
| 609 |
+
if isinstance(generator, list) and len(generator) != batch_size:
|
| 610 |
+
raise ValueError(
|
| 611 |
+
f"You have passed a list of generators of length {len(generator)}, but requested an effective batch"
|
| 612 |
+
f" size of {batch_size}. Make sure the batch size matches the length of the generators."
|
| 613 |
+
)
|
| 614 |
+
|
| 615 |
+
latents = randn_tensor(shape, generator=generator, device=device, dtype=dtype)
|
| 616 |
+
latents = self._pack_latents(
|
| 617 |
+
latents, batch_size, num_channels_latents, height, width
|
| 618 |
+
)
|
| 619 |
+
|
| 620 |
+
latent_image_ids = self._prepare_latent_image_ids(
|
| 621 |
+
batch_size, height, width, device, dtype
|
| 622 |
+
)
|
| 623 |
+
|
| 624 |
+
return latents, latent_image_ids
|
| 625 |
+
|
| 626 |
+
# Copied from diffusers.pipelines.controlnet.pipeline_controlnet.StableDiffusionControlNetPipeline.prepare_image
|
| 627 |
+
def prepare_image(
|
| 628 |
+
self,
|
| 629 |
+
image,
|
| 630 |
+
width,
|
| 631 |
+
height,
|
| 632 |
+
batch_size,
|
| 633 |
+
num_images_per_prompt,
|
| 634 |
+
device,
|
| 635 |
+
dtype,
|
| 636 |
+
):
|
| 637 |
+
if isinstance(image, torch.Tensor):
|
| 638 |
+
pass
|
| 639 |
+
else:
|
| 640 |
+
image = self.image_processor.preprocess(image, height=height, width=width)
|
| 641 |
+
|
| 642 |
+
image_batch_size = image.shape[0]
|
| 643 |
+
|
| 644 |
+
if image_batch_size == 1:
|
| 645 |
+
repeat_by = batch_size
|
| 646 |
+
else:
|
| 647 |
+
# image batch size is the same as prompt batch size
|
| 648 |
+
repeat_by = num_images_per_prompt
|
| 649 |
+
|
| 650 |
+
image = image.repeat_interleave(repeat_by, dim=0)
|
| 651 |
+
|
| 652 |
+
image = image.to(device=device, dtype=dtype)
|
| 653 |
+
|
| 654 |
+
return image
|
| 655 |
+
|
| 656 |
+
def prepare_image_with_mask(
|
| 657 |
+
self,
|
| 658 |
+
image,
|
| 659 |
+
mask,
|
| 660 |
+
width,
|
| 661 |
+
height,
|
| 662 |
+
batch_size,
|
| 663 |
+
num_images_per_prompt,
|
| 664 |
+
device,
|
| 665 |
+
dtype,
|
| 666 |
+
do_classifier_free_guidance=False,
|
| 667 |
+
):
|
| 668 |
+
# Prepare image
|
| 669 |
+
if isinstance(image, torch.Tensor):
|
| 670 |
+
pass
|
| 671 |
+
else:
|
| 672 |
+
image = self.image_processor.preprocess(image, height=height, width=width)
|
| 673 |
+
|
| 674 |
+
image_batch_size = image.shape[0]
|
| 675 |
+
if image_batch_size == 1:
|
| 676 |
+
repeat_by = batch_size
|
| 677 |
+
else:
|
| 678 |
+
# image batch size is the same as prompt batch size
|
| 679 |
+
repeat_by = num_images_per_prompt
|
| 680 |
+
image = image.repeat_interleave(repeat_by, dim=0)
|
| 681 |
+
image = image.to(device=device, dtype=dtype)
|
| 682 |
+
|
| 683 |
+
# Prepare mask
|
| 684 |
+
if isinstance(mask, torch.Tensor):
|
| 685 |
+
pass
|
| 686 |
+
else:
|
| 687 |
+
mask = self.mask_processor.preprocess(mask, height=height, width=width)
|
| 688 |
+
mask = mask.repeat_interleave(repeat_by, dim=0)
|
| 689 |
+
mask = mask.to(device=device, dtype=dtype)
|
| 690 |
+
|
| 691 |
+
# Get masked image
|
| 692 |
+
masked_image = image.clone()
|
| 693 |
+
masked_image[(mask > 0.5).repeat(1, 3, 1, 1)] = -1
|
| 694 |
+
|
| 695 |
+
# Encode to latents
|
| 696 |
+
image_latents = self.vae.encode(
|
| 697 |
+
masked_image.to(self.vae.dtype)
|
| 698 |
+
).latent_dist.sample()
|
| 699 |
+
image_latents = (
|
| 700 |
+
image_latents - self.vae.config.shift_factor
|
| 701 |
+
) * self.vae.config.scaling_factor
|
| 702 |
+
image_latents = image_latents.to(dtype)
|
| 703 |
+
|
| 704 |
+
mask = torch.nn.functional.interpolate(
|
| 705 |
+
mask,
|
| 706 |
+
size=(
|
| 707 |
+
height // self.vae_scale_factor * 2,
|
| 708 |
+
width // self.vae_scale_factor * 2,
|
| 709 |
+
),
|
| 710 |
+
)
|
| 711 |
+
mask = 1 - mask
|
| 712 |
+
|
| 713 |
+
control_image = torch.cat([image_latents, mask], dim=1)
|
| 714 |
+
|
| 715 |
+
# Pack cond latents
|
| 716 |
+
packed_control_image = self._pack_latents(
|
| 717 |
+
control_image,
|
| 718 |
+
batch_size * num_images_per_prompt,
|
| 719 |
+
control_image.shape[1],
|
| 720 |
+
control_image.shape[2],
|
| 721 |
+
control_image.shape[3],
|
| 722 |
+
)
|
| 723 |
+
|
| 724 |
+
if do_classifier_free_guidance:
|
| 725 |
+
packed_control_image = torch.cat([packed_control_image] * 2)
|
| 726 |
+
|
| 727 |
+
return packed_control_image, height, width
|
| 728 |
+
|
| 729 |
+
@property
|
| 730 |
+
def guidance_scale(self):
|
| 731 |
+
return self._guidance_scale
|
| 732 |
+
|
| 733 |
+
@property
|
| 734 |
+
def joint_attention_kwargs(self):
|
| 735 |
+
return self._joint_attention_kwargs
|
| 736 |
+
|
| 737 |
+
@property
|
| 738 |
+
def num_timesteps(self):
|
| 739 |
+
return self._num_timesteps
|
| 740 |
+
|
| 741 |
+
@property
|
| 742 |
+
def interrupt(self):
|
| 743 |
+
return self._interrupt
|
| 744 |
+
|
| 745 |
+
@torch.no_grad()
|
| 746 |
+
@replace_example_docstring(EXAMPLE_DOC_STRING)
|
| 747 |
+
def __call__(
|
| 748 |
+
self,
|
| 749 |
+
prompt: Union[str, List[str]] = None,
|
| 750 |
+
prompt_2: Optional[Union[str, List[str]]] = None,
|
| 751 |
+
height: Optional[int] = None,
|
| 752 |
+
width: Optional[int] = None,
|
| 753 |
+
num_inference_steps: int = 28,
|
| 754 |
+
timesteps: List[int] = None,
|
| 755 |
+
guidance_scale: float = 7.0,
|
| 756 |
+
true_guidance_scale: float = 3.5,
|
| 757 |
+
negative_prompt: Optional[Union[str, List[str]]] = None,
|
| 758 |
+
negative_prompt_2: Optional[Union[str, List[str]]] = None,
|
| 759 |
+
control_image: PipelineImageInput = None,
|
| 760 |
+
control_mask: PipelineImageInput = None,
|
| 761 |
+
controlnet_conditioning_scale: Union[float, List[float]] = 1.0,
|
| 762 |
+
num_images_per_prompt: Optional[int] = 1,
|
| 763 |
+
generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
|
| 764 |
+
latents: Optional[torch.FloatTensor] = None,
|
| 765 |
+
prompt_embeds: Optional[torch.FloatTensor] = None,
|
| 766 |
+
pooled_prompt_embeds: Optional[torch.FloatTensor] = None,
|
| 767 |
+
output_type: Optional[str] = "pil",
|
| 768 |
+
return_dict: bool = True,
|
| 769 |
+
joint_attention_kwargs: Optional[Dict[str, Any]] = None,
|
| 770 |
+
callback_on_step_end: Optional[Callable[[int, int, Dict], None]] = None,
|
| 771 |
+
callback_on_step_end_tensor_inputs: List[str] = ["latents"],
|
| 772 |
+
max_sequence_length: int = 512,
|
| 773 |
+
):
|
| 774 |
+
r"""
|
| 775 |
+
Function invoked when calling the pipeline for generation.
|
| 776 |
+
|
| 777 |
+
Args:
|
| 778 |
+
prompt (`str` or `List[str]`, *optional*):
|
| 779 |
+
The prompt or prompts to guide the image generation. If not defined, one has to pass `prompt_embeds`.
|
| 780 |
+
instead.
|
| 781 |
+
prompt_2 (`str` or `List[str]`, *optional*):
|
| 782 |
+
The prompt or prompts to be sent to `tokenizer_2` and `text_encoder_2`. If not defined, `prompt` is
|
| 783 |
+
will be used instead
|
| 784 |
+
height (`int`, *optional*, defaults to self.unet.config.sample_size * self.vae_scale_factor):
|
| 785 |
+
The height in pixels of the generated image. This is set to 1024 by default for the best results.
|
| 786 |
+
width (`int`, *optional*, defaults to self.unet.config.sample_size * self.vae_scale_factor):
|
| 787 |
+
The width in pixels of the generated image. This is set to 1024 by default for the best results.
|
| 788 |
+
num_inference_steps (`int`, *optional*, defaults to 50):
|
| 789 |
+
The number of denoising steps. More denoising steps usually lead to a higher quality image at the
|
| 790 |
+
expense of slower inference.
|
| 791 |
+
timesteps (`List[int]`, *optional*):
|
| 792 |
+
Custom timesteps to use for the denoising process with schedulers which support a `timesteps` argument
|
| 793 |
+
in their `set_timesteps` method. If not defined, the default behavior when `num_inference_steps` is
|
| 794 |
+
passed will be used. Must be in descending order.
|
| 795 |
+
guidance_scale (`float`, *optional*, defaults to 7.0):
|
| 796 |
+
Guidance scale as defined in [Classifier-Free Diffusion Guidance](https://arxiv.org/abs/2207.12598).
|
| 797 |
+
`guidance_scale` is defined as `w` of equation 2. of [Imagen
|
| 798 |
+
Paper](https://arxiv.org/pdf/2205.11487.pdf). Guidance scale is enabled by setting `guidance_scale >
|
| 799 |
+
1`. Higher guidance scale encourages to generate images that are closely linked to the text `prompt`,
|
| 800 |
+
usually at the expense of lower image quality.
|
| 801 |
+
num_images_per_prompt (`int`, *optional*, defaults to 1):
|
| 802 |
+
The number of images to generate per prompt.
|
| 803 |
+
generator (`torch.Generator` or `List[torch.Generator]`, *optional*):
|
| 804 |
+
One or a list of [torch generator(s)](https://pytorch.org/docs/stable/generated/torch.Generator.html)
|
| 805 |
+
to make generation deterministic.
|
| 806 |
+
latents (`torch.FloatTensor`, *optional*):
|
| 807 |
+
Pre-generated noisy latents, sampled from a Gaussian distribution, to be used as inputs for image
|
| 808 |
+
generation. Can be used to tweak the same generation with different prompts. If not provided, a latents
|
| 809 |
+
tensor will ge generated by sampling using the supplied random `generator`.
|
| 810 |
+
prompt_embeds (`torch.FloatTensor`, *optional*):
|
| 811 |
+
Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not
|
| 812 |
+
provided, text embeddings will be generated from `prompt` input argument.
|
| 813 |
+
pooled_prompt_embeds (`torch.FloatTensor`, *optional*):
|
| 814 |
+
Pre-generated pooled text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting.
|
| 815 |
+
If not provided, pooled text embeddings will be generated from `prompt` input argument.
|
| 816 |
+
output_type (`str`, *optional*, defaults to `"pil"`):
|
| 817 |
+
The output format of the generate image. Choose between
|
| 818 |
+
[PIL](https://pillow.readthedocs.io/en/stable/): `PIL.Image.Image` or `np.array`.
|
| 819 |
+
return_dict (`bool`, *optional*, defaults to `True`):
|
| 820 |
+
Whether or not to return a [`~pipelines.flux.FluxPipelineOutput`] instead of a plain tuple.
|
| 821 |
+
joint_attention_kwargs (`dict`, *optional*):
|
| 822 |
+
A kwargs dictionary that if specified is passed along to the `AttentionProcessor` as defined under
|
| 823 |
+
`self.processor` in
|
| 824 |
+
[diffusers.models.attention_processor](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py).
|
| 825 |
+
callback_on_step_end (`Callable`, *optional*):
|
| 826 |
+
A function that calls at the end of each denoising steps during the inference. The function is called
|
| 827 |
+
with the following arguments: `callback_on_step_end(self: DiffusionPipeline, step: int, timestep: int,
|
| 828 |
+
callback_kwargs: Dict)`. `callback_kwargs` will include a list of all tensors as specified by
|
| 829 |
+
`callback_on_step_end_tensor_inputs`.
|
| 830 |
+
callback_on_step_end_tensor_inputs (`List`, *optional*):
|
| 831 |
+
The list of tensor inputs for the `callback_on_step_end` function. The tensors specified in the list
|
| 832 |
+
will be passed as `callback_kwargs` argument. You will only be able to include variables listed in the
|
| 833 |
+
`._callback_tensor_inputs` attribute of your pipeline class.
|
| 834 |
+
max_sequence_length (`int` defaults to 512): Maximum sequence length to use with the `prompt`.
|
| 835 |
+
|
| 836 |
+
Examples:
|
| 837 |
+
|
| 838 |
+
Returns:
|
| 839 |
+
[`~pipelines.flux.FluxPipelineOutput`] or `tuple`: [`~pipelines.flux.FluxPipelineOutput`] if `return_dict`
|
| 840 |
+
is True, otherwise a `tuple`. When returning a tuple, the first element is a list with the generated
|
| 841 |
+
images.
|
| 842 |
+
"""
|
| 843 |
+
|
| 844 |
+
height = height or self.default_sample_size * self.vae_scale_factor
|
| 845 |
+
width = width or self.default_sample_size * self.vae_scale_factor
|
| 846 |
+
|
| 847 |
+
# 1. Check inputs. Raise error if not correct
|
| 848 |
+
self.check_inputs(
|
| 849 |
+
prompt,
|
| 850 |
+
prompt_2,
|
| 851 |
+
height,
|
| 852 |
+
width,
|
| 853 |
+
prompt_embeds=prompt_embeds,
|
| 854 |
+
pooled_prompt_embeds=pooled_prompt_embeds,
|
| 855 |
+
callback_on_step_end_tensor_inputs=callback_on_step_end_tensor_inputs,
|
| 856 |
+
max_sequence_length=max_sequence_length,
|
| 857 |
+
)
|
| 858 |
+
|
| 859 |
+
self._guidance_scale = true_guidance_scale
|
| 860 |
+
self._joint_attention_kwargs = joint_attention_kwargs
|
| 861 |
+
self._interrupt = False
|
| 862 |
+
|
| 863 |
+
# 2. Define call parameters
|
| 864 |
+
if prompt is not None and isinstance(prompt, str):
|
| 865 |
+
batch_size = 1
|
| 866 |
+
elif prompt is not None and isinstance(prompt, list):
|
| 867 |
+
batch_size = len(prompt)
|
| 868 |
+
else:
|
| 869 |
+
batch_size = prompt_embeds.shape[0]
|
| 870 |
+
|
| 871 |
+
device_0 = self.controlnet.device # First GPU
|
| 872 |
+
device_1 = self.transformer.device # Second GPU
|
| 873 |
+
|
| 874 |
+
# Move inputs to appropriate devices
|
| 875 |
+
prompt_embeds = prompt_embeds.to(device_0)
|
| 876 |
+
pooled_prompt_embeds = pooled_prompt_embeds.to(device_0)
|
| 877 |
+
|
| 878 |
+
# During the generation loop
|
| 879 |
+
latent_model_input = (
|
| 880 |
+
torch.cat([prompt_embeds] * 2)
|
| 881 |
+
if self.do_classifier_free_guidance
|
| 882 |
+
else prompt_embeds
|
| 883 |
+
)
|
| 884 |
+
timestep = torch.tensor([1.0], device=device_0)
|
| 885 |
+
|
| 886 |
+
# ControlNet forward pass on first GPU
|
| 887 |
+
controlnet_output = self.controlnet(
|
| 888 |
+
hidden_states=latent_model_input,
|
| 889 |
+
controlnet_cond=control_image.to(device_0),
|
| 890 |
+
conditioning_scale=controlnet_conditioning_scale,
|
| 891 |
+
timestep=timestep / 1000,
|
| 892 |
+
guidance=None,
|
| 893 |
+
pooled_projections=pooled_prompt_embeds,
|
| 894 |
+
encoder_hidden_states=prompt_embeds,
|
| 895 |
+
txt_ids=text_ids.to(device_0),
|
| 896 |
+
img_ids=latent_image_ids.to(device_0),
|
| 897 |
+
joint_attention_kwargs=self.joint_attention_kwargs,
|
| 898 |
+
return_dict=False,
|
| 899 |
+
)
|
| 900 |
+
|
| 901 |
+
# Move necessary data to second GPU for transformer
|
| 902 |
+
controlnet_block_samples = [
|
| 903 |
+
sample.to(device_1) for sample in controlnet_output[0]
|
| 904 |
+
]
|
| 905 |
+
controlnet_single_block_samples = (
|
| 906 |
+
[sample.to(device_1) for sample in controlnet_output[1]]
|
| 907 |
+
if controlnet_output[1] is not None
|
| 908 |
+
else None
|
| 909 |
+
)
|
| 910 |
+
|
| 911 |
+
# Transformer forward pass on second GPU
|
| 912 |
+
noise_pred = self.transformer(
|
| 913 |
+
hidden_states=latent_model_input.to(device_1),
|
| 914 |
+
timestep=timestep.to(device_1) / 1000,
|
| 915 |
+
guidance=None,
|
| 916 |
+
pooled_projections=pooled_prompt_embeds.to(device_1),
|
| 917 |
+
encoder_hidden_states=prompt_embeds.to(device_1),
|
| 918 |
+
controlnet_block_samples=controlnet_block_samples,
|
| 919 |
+
controlnet_single_block_samples=controlnet_single_block_samples,
|
| 920 |
+
txt_ids=text_ids.to(device_1),
|
| 921 |
+
img_ids=latent_image_ids.to(device_1),
|
| 922 |
+
joint_attention_kwargs=self.joint_attention_kwargs,
|
| 923 |
+
return_dict=False,
|
| 924 |
+
)[0]
|
| 925 |
+
|
| 926 |
+
# Move results back to first GPU for final processing
|
| 927 |
+
noise_pred = noise_pred.to(device_0)
|
| 928 |
+
|
| 929 |
+
# 5. Prepare timesteps
|
| 930 |
+
sigmas = np.linspace(1.0, 1 / num_inference_steps, num_inference_steps)
|
| 931 |
+
image_seq_len = noise_pred.shape[1]
|
| 932 |
+
mu = calculate_shift(
|
| 933 |
+
image_seq_len,
|
| 934 |
+
self.scheduler.config.base_image_seq_len,
|
| 935 |
+
self.scheduler.config.max_image_seq_len,
|
| 936 |
+
self.scheduler.config.base_shift,
|
| 937 |
+
self.scheduler.config.max_shift,
|
| 938 |
+
)
|
| 939 |
+
timesteps, num_inference_steps = retrieve_timesteps(
|
| 940 |
+
self.scheduler,
|
| 941 |
+
num_inference_steps,
|
| 942 |
+
device_0,
|
| 943 |
+
timesteps,
|
| 944 |
+
sigmas,
|
| 945 |
+
mu=mu,
|
| 946 |
+
)
|
| 947 |
+
|
| 948 |
+
num_warmup_steps = max(
|
| 949 |
+
len(timesteps) - num_inference_steps * self.scheduler.order, 0
|
| 950 |
+
)
|
| 951 |
+
self._num_timesteps = len(timesteps)
|
| 952 |
+
|
| 953 |
+
# 6. Denoising loop
|
| 954 |
+
with self.progress_bar(total=num_inference_steps) as progress_bar:
|
| 955 |
+
for i, t in enumerate(timesteps):
|
| 956 |
+
if self.interrupt:
|
| 957 |
+
continue
|
| 958 |
+
|
| 959 |
+
latent_model_input = (
|
| 960 |
+
torch.cat([noise_pred] * 2)
|
| 961 |
+
if self.do_classifier_free_guidance
|
| 962 |
+
else noise_pred
|
| 963 |
+
)
|
| 964 |
+
|
| 965 |
+
# broadcast to batch dimension in a way that's compatible with ONNX/Core ML
|
| 966 |
+
timestep = t.expand(latent_model_input.shape[0]).to(
|
| 967 |
+
latent_model_input.dtype
|
| 968 |
+
)
|
| 969 |
+
|
| 970 |
+
# handle guidance
|
| 971 |
+
if self.transformer.config.guidance_embeds:
|
| 972 |
+
guidance = torch.tensor([guidance_scale], device=device_0)
|
| 973 |
+
guidance = guidance.expand(latent_model_input.shape[0])
|
| 974 |
+
else:
|
| 975 |
+
guidance = None
|
| 976 |
+
|
| 977 |
+
# controlnet
|
| 978 |
+
(
|
| 979 |
+
controlnet_block_samples,
|
| 980 |
+
controlnet_single_block_samples,
|
| 981 |
+
) = self.controlnet(
|
| 982 |
+
hidden_states=latent_model_input,
|
| 983 |
+
controlnet_cond=control_image.to(device_0),
|
| 984 |
+
conditioning_scale=controlnet_conditioning_scale,
|
| 985 |
+
timestep=timestep / 1000,
|
| 986 |
+
guidance=guidance.to(device_0) if guidance is not None else None,
|
| 987 |
+
pooled_projections=pooled_prompt_embeds,
|
| 988 |
+
encoder_hidden_states=prompt_embeds,
|
| 989 |
+
txt_ids=text_ids.to(device_0),
|
| 990 |
+
img_ids=latent_image_ids.to(device_0),
|
| 991 |
+
joint_attention_kwargs=self.joint_attention_kwargs,
|
| 992 |
+
return_dict=False,
|
| 993 |
+
)
|
| 994 |
+
|
| 995 |
+
noise_pred = self.transformer(
|
| 996 |
+
hidden_states=latent_model_input.to(device_1),
|
| 997 |
+
timestep=timestep.to(device_1) / 1000,
|
| 998 |
+
guidance=guidance.to(device_1) if guidance is not None else None,
|
| 999 |
+
pooled_projections=pooled_prompt_embeds.to(device_1),
|
| 1000 |
+
encoder_hidden_states=prompt_embeds.to(device_1),
|
| 1001 |
+
controlnet_block_samples=controlnet_block_samples,
|
| 1002 |
+
controlnet_single_block_samples=controlnet_single_block_samples,
|
| 1003 |
+
txt_ids=text_ids.to(device_1),
|
| 1004 |
+
img_ids=latent_image_ids.to(device_1),
|
| 1005 |
+
joint_attention_kwargs=self.joint_attention_kwargs,
|
| 1006 |
+
return_dict=False,
|
| 1007 |
+
)[0]
|
| 1008 |
+
|
| 1009 |
+
# 在生成循环中
|
| 1010 |
+
if self.do_classifier_free_guidance:
|
| 1011 |
+
noise_pred_uncond, noise_pred_text = noise_pred.chunk(2)
|
| 1012 |
+
noise_pred = noise_pred_uncond + true_guidance_scale * (
|
| 1013 |
+
noise_pred_text - noise_pred_uncond
|
| 1014 |
+
)
|
| 1015 |
+
|
| 1016 |
+
# compute the previous noisy sample x_t -> x_t-1
|
| 1017 |
+
latents_dtype = noise_pred.dtype
|
| 1018 |
+
noise_pred = self.scheduler.step(
|
| 1019 |
+
noise_pred, t, noise_pred, return_dict=False
|
| 1020 |
+
)[0]
|
| 1021 |
+
|
| 1022 |
+
if noise_pred.dtype != latents_dtype:
|
| 1023 |
+
if torch.backends.mps.is_available():
|
| 1024 |
+
# some platforms (eg. apple mps) misbehave due to a pytorch bug: https://github.com/pytorch/pytorch/pull/99272
|
| 1025 |
+
noise_pred = noise_pred.to(latents_dtype)
|
| 1026 |
+
|
| 1027 |
+
if callback_on_step_end is not None:
|
| 1028 |
+
callback_kwargs = {}
|
| 1029 |
+
for k in callback_on_step_end_tensor_inputs:
|
| 1030 |
+
callback_kwargs[k] = locals()[k]
|
| 1031 |
+
callback_outputs = callback_on_step_end(self, i, t, callback_kwargs)
|
| 1032 |
+
|
| 1033 |
+
noise_pred = callback_outputs.pop("latents", noise_pred)
|
| 1034 |
+
prompt_embeds = callback_outputs.pop("prompt_embeds", prompt_embeds)
|
| 1035 |
+
|
| 1036 |
+
# call the callback, if provided
|
| 1037 |
+
if i == len(timesteps) - 1 or (
|
| 1038 |
+
(i + 1) > num_warmup_steps and (i + 1) % self.scheduler.order == 0
|
| 1039 |
+
):
|
| 1040 |
+
progress_bar.update()
|
| 1041 |
+
|
| 1042 |
+
if XLA_AVAILABLE:
|
| 1043 |
+
xm.mark_step()
|
| 1044 |
+
|
| 1045 |
+
if output_type == "latent":
|
| 1046 |
+
image = noise_pred
|
| 1047 |
+
|
| 1048 |
+
else:
|
| 1049 |
+
latents = self._unpack_latents(
|
| 1050 |
+
noise_pred, height, width, self.vae_scale_factor
|
| 1051 |
+
)
|
| 1052 |
+
latents = (
|
| 1053 |
+
latents / self.vae.config.scaling_factor
|
| 1054 |
+
) + self.vae.config.shift_factor
|
| 1055 |
+
latents = latents.to(self.vae.dtype)
|
| 1056 |
+
|
| 1057 |
+
image = self.vae.decode(latents, return_dict=False)[0]
|
| 1058 |
+
image = self.image_processor.postprocess(image, output_type=output_type)
|
| 1059 |
+
|
| 1060 |
+
# Offload all models
|
| 1061 |
+
self.maybe_free_model_hooks()
|
| 1062 |
+
|
| 1063 |
+
if not return_dict:
|
| 1064 |
+
return (image,)
|
| 1065 |
+
|
| 1066 |
+
return FluxPipelineOutput(images=image)
|
poetry.lock
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
pyproject.toml
ADDED
|
@@ -0,0 +1,18 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
[tool.poetry]
|
| 2 |
+
name = "arvo-inpainting"
|
| 3 |
+
version = "0.0.1"
|
| 4 |
+
description = "The inpaiting module for ARvo product photography pipeline"
|
| 5 |
+
authors = ["Swoyam-ARvo <[email protected]>"]
|
| 6 |
+
readme = "README.md"
|
| 7 |
+
|
| 8 |
+
[tool.poetry.dependencies]
|
| 9 |
+
python = "^3.11"
|
| 10 |
+
diffusers = "0.30.2"
|
| 11 |
+
torch = "^2.6.0"
|
| 12 |
+
gradio = "^5.17.1"
|
| 13 |
+
transformers = "^4.49.0"
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
[build-system]
|
| 17 |
+
requires = ["poetry-core"]
|
| 18 |
+
build-backend = "poetry.core.mason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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from typing import Any, Dict, List, Optional, Union
|
| 2 |
+
|
| 3 |
+
import numpy as np
|
| 4 |
+
import torch
|
| 5 |
+
import torch.nn as nn
|
| 6 |
+
import torch.nn.functional as F
|
| 7 |
+
|
| 8 |
+
from diffusers.configuration_utils import ConfigMixin, register_to_config
|
| 9 |
+
from diffusers.loaders import FromOriginalModelMixin, PeftAdapterMixin
|
| 10 |
+
from diffusers.models.attention import FeedForward
|
| 11 |
+
from diffusers.models.attention_processor import (
|
| 12 |
+
Attention,
|
| 13 |
+
FluxAttnProcessor2_0,
|
| 14 |
+
FluxSingleAttnProcessor2_0,
|
| 15 |
+
)
|
| 16 |
+
from diffusers.models.modeling_utils import ModelMixin
|
| 17 |
+
from diffusers.models.normalization import (
|
| 18 |
+
AdaLayerNormContinuous,
|
| 19 |
+
AdaLayerNormZero,
|
| 20 |
+
AdaLayerNormZeroSingle,
|
| 21 |
+
)
|
| 22 |
+
from diffusers.utils import (
|
| 23 |
+
USE_PEFT_BACKEND,
|
| 24 |
+
is_torch_version,
|
| 25 |
+
logging,
|
| 26 |
+
scale_lora_layers,
|
| 27 |
+
unscale_lora_layers,
|
| 28 |
+
)
|
| 29 |
+
from diffusers.utils.torch_utils import maybe_allow_in_graph
|
| 30 |
+
from diffusers.models.embeddings import (
|
| 31 |
+
CombinedTimestepGuidanceTextProjEmbeddings,
|
| 32 |
+
CombinedTimestepTextProjEmbeddings,
|
| 33 |
+
)
|
| 34 |
+
from diffusers.models.modeling_outputs import Transformer2DModelOutput
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
logger = logging.get_logger(__name__) # pylint: disable=invalid-name
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
# YiYi to-do: refactor rope related functions/classes
|
| 41 |
+
def rope(pos: torch.Tensor, dim: int, theta: int) -> torch.Tensor:
|
| 42 |
+
assert dim % 2 == 0, "The dimension must be even."
|
| 43 |
+
|
| 44 |
+
scale = torch.arange(0, dim, 2, dtype=torch.float64, device=pos.device) / dim
|
| 45 |
+
omega = 1.0 / (theta**scale)
|
| 46 |
+
|
| 47 |
+
batch_size, seq_length = pos.shape
|
| 48 |
+
out = torch.einsum("...n,d->...nd", pos, omega)
|
| 49 |
+
cos_out = torch.cos(out)
|
| 50 |
+
sin_out = torch.sin(out)
|
| 51 |
+
|
| 52 |
+
stacked_out = torch.stack([cos_out, -sin_out, sin_out, cos_out], dim=-1)
|
| 53 |
+
out = stacked_out.view(batch_size, -1, dim // 2, 2, 2)
|
| 54 |
+
return out.float()
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
# YiYi to-do: refactor rope related functions/classes
|
| 58 |
+
class EmbedND(nn.Module):
|
| 59 |
+
def __init__(self, dim: int, theta: int, axes_dim: List[int]):
|
| 60 |
+
super().__init__()
|
| 61 |
+
self.dim = dim
|
| 62 |
+
self.theta = theta
|
| 63 |
+
self.axes_dim = axes_dim
|
| 64 |
+
|
| 65 |
+
def forward(self, ids: torch.Tensor) -> torch.Tensor:
|
| 66 |
+
n_axes = ids.shape[-1]
|
| 67 |
+
emb = torch.cat(
|
| 68 |
+
[rope(ids[..., i], self.axes_dim[i], self.theta) for i in range(n_axes)],
|
| 69 |
+
dim=-3,
|
| 70 |
+
)
|
| 71 |
+
return emb.unsqueeze(1)
|
| 72 |
+
|
| 73 |
+
|
| 74 |
+
@maybe_allow_in_graph
|
| 75 |
+
class FluxSingleTransformerBlock(nn.Module):
|
| 76 |
+
r"""
|
| 77 |
+
A Transformer block following the MMDiT architecture, introduced in Stable Diffusion 3.
|
| 78 |
+
|
| 79 |
+
Reference: https://arxiv.org/abs/2403.03206
|
| 80 |
+
|
| 81 |
+
Parameters:
|
| 82 |
+
dim (`int`): The number of channels in the input and output.
|
| 83 |
+
num_attention_heads (`int`): The number of heads to use for multi-head attention.
|
| 84 |
+
attention_head_dim (`int`): The number of channels in each head.
|
| 85 |
+
context_pre_only (`bool`): Boolean to determine if we should add some blocks associated with the
|
| 86 |
+
processing of `context` conditions.
|
| 87 |
+
"""
|
| 88 |
+
|
| 89 |
+
def __init__(self, dim, num_attention_heads, attention_head_dim, mlp_ratio=4.0):
|
| 90 |
+
super().__init__()
|
| 91 |
+
self.mlp_hidden_dim = int(dim * mlp_ratio)
|
| 92 |
+
|
| 93 |
+
self.norm = AdaLayerNormZeroSingle(dim)
|
| 94 |
+
self.proj_mlp = nn.Linear(dim, self.mlp_hidden_dim)
|
| 95 |
+
self.act_mlp = nn.GELU(approximate="tanh")
|
| 96 |
+
self.proj_out = nn.Linear(dim + self.mlp_hidden_dim, dim)
|
| 97 |
+
|
| 98 |
+
processor = FluxSingleAttnProcessor2_0()
|
| 99 |
+
self.attn = Attention(
|
| 100 |
+
query_dim=dim,
|
| 101 |
+
cross_attention_dim=None,
|
| 102 |
+
dim_head=attention_head_dim,
|
| 103 |
+
heads=num_attention_heads,
|
| 104 |
+
out_dim=dim,
|
| 105 |
+
bias=True,
|
| 106 |
+
processor=processor,
|
| 107 |
+
qk_norm="rms_norm",
|
| 108 |
+
eps=1e-6,
|
| 109 |
+
pre_only=True,
|
| 110 |
+
)
|
| 111 |
+
|
| 112 |
+
def forward(
|
| 113 |
+
self,
|
| 114 |
+
hidden_states: torch.FloatTensor,
|
| 115 |
+
temb: torch.FloatTensor,
|
| 116 |
+
image_rotary_emb=None,
|
| 117 |
+
):
|
| 118 |
+
residual = hidden_states
|
| 119 |
+
norm_hidden_states, gate = self.norm(hidden_states, emb=temb)
|
| 120 |
+
mlp_hidden_states = self.act_mlp(self.proj_mlp(norm_hidden_states))
|
| 121 |
+
|
| 122 |
+
attn_output = self.attn(
|
| 123 |
+
hidden_states=norm_hidden_states,
|
| 124 |
+
image_rotary_emb=image_rotary_emb,
|
| 125 |
+
)
|
| 126 |
+
|
| 127 |
+
hidden_states = torch.cat([attn_output, mlp_hidden_states], dim=2)
|
| 128 |
+
gate = gate.unsqueeze(1)
|
| 129 |
+
hidden_states = gate * self.proj_out(hidden_states)
|
| 130 |
+
hidden_states = residual + hidden_states
|
| 131 |
+
if hidden_states.dtype == torch.float16:
|
| 132 |
+
hidden_states = hidden_states.clip(-65504, 65504)
|
| 133 |
+
|
| 134 |
+
return hidden_states
|
| 135 |
+
|
| 136 |
+
|
| 137 |
+
@maybe_allow_in_graph
|
| 138 |
+
class FluxTransformerBlock(nn.Module):
|
| 139 |
+
r"""
|
| 140 |
+
A Transformer block following the MMDiT architecture, introduced in Stable Diffusion 3.
|
| 141 |
+
|
| 142 |
+
Reference: https://arxiv.org/abs/2403.03206
|
| 143 |
+
|
| 144 |
+
Parameters:
|
| 145 |
+
dim (`int`): The number of channels in the input and output.
|
| 146 |
+
num_attention_heads (`int`): The number of heads to use for multi-head attention.
|
| 147 |
+
attention_head_dim (`int`): The number of channels in each head.
|
| 148 |
+
context_pre_only (`bool`): Boolean to determine if we should add some blocks associated with the
|
| 149 |
+
processing of `context` conditions.
|
| 150 |
+
"""
|
| 151 |
+
|
| 152 |
+
def __init__(
|
| 153 |
+
self, dim, num_attention_heads, attention_head_dim, qk_norm="rms_norm", eps=1e-6
|
| 154 |
+
):
|
| 155 |
+
super().__init__()
|
| 156 |
+
|
| 157 |
+
self.norm1 = AdaLayerNormZero(dim)
|
| 158 |
+
|
| 159 |
+
self.norm1_context = AdaLayerNormZero(dim)
|
| 160 |
+
|
| 161 |
+
if hasattr(F, "scaled_dot_product_attention"):
|
| 162 |
+
processor = FluxAttnProcessor2_0()
|
| 163 |
+
else:
|
| 164 |
+
raise ValueError(
|
| 165 |
+
"The current PyTorch version does not support the `scaled_dot_product_attention` function."
|
| 166 |
+
)
|
| 167 |
+
self.attn = Attention(
|
| 168 |
+
query_dim=dim,
|
| 169 |
+
cross_attention_dim=None,
|
| 170 |
+
added_kv_proj_dim=dim,
|
| 171 |
+
dim_head=attention_head_dim,
|
| 172 |
+
heads=num_attention_heads,
|
| 173 |
+
out_dim=dim,
|
| 174 |
+
context_pre_only=False,
|
| 175 |
+
bias=True,
|
| 176 |
+
processor=processor,
|
| 177 |
+
qk_norm=qk_norm,
|
| 178 |
+
eps=eps,
|
| 179 |
+
)
|
| 180 |
+
|
| 181 |
+
self.norm2 = nn.LayerNorm(dim, elementwise_affine=False, eps=1e-6)
|
| 182 |
+
self.ff = FeedForward(dim=dim, dim_out=dim, activation_fn="gelu-approximate")
|
| 183 |
+
|
| 184 |
+
self.norm2_context = nn.LayerNorm(dim, elementwise_affine=False, eps=1e-6)
|
| 185 |
+
self.ff_context = FeedForward(
|
| 186 |
+
dim=dim, dim_out=dim, activation_fn="gelu-approximate"
|
| 187 |
+
)
|
| 188 |
+
|
| 189 |
+
# let chunk size default to None
|
| 190 |
+
self._chunk_size = None
|
| 191 |
+
self._chunk_dim = 0
|
| 192 |
+
|
| 193 |
+
def forward(
|
| 194 |
+
self,
|
| 195 |
+
hidden_states: torch.FloatTensor,
|
| 196 |
+
encoder_hidden_states: torch.FloatTensor,
|
| 197 |
+
temb: torch.FloatTensor,
|
| 198 |
+
image_rotary_emb=None,
|
| 199 |
+
):
|
| 200 |
+
norm_hidden_states, gate_msa, shift_mlp, scale_mlp, gate_mlp = self.norm1(
|
| 201 |
+
hidden_states, emb=temb
|
| 202 |
+
)
|
| 203 |
+
|
| 204 |
+
(
|
| 205 |
+
norm_encoder_hidden_states,
|
| 206 |
+
c_gate_msa,
|
| 207 |
+
c_shift_mlp,
|
| 208 |
+
c_scale_mlp,
|
| 209 |
+
c_gate_mlp,
|
| 210 |
+
) = self.norm1_context(encoder_hidden_states, emb=temb)
|
| 211 |
+
|
| 212 |
+
# Attention.
|
| 213 |
+
attn_output, context_attn_output = self.attn(
|
| 214 |
+
hidden_states=norm_hidden_states,
|
| 215 |
+
encoder_hidden_states=norm_encoder_hidden_states,
|
| 216 |
+
image_rotary_emb=image_rotary_emb,
|
| 217 |
+
)
|
| 218 |
+
|
| 219 |
+
# Process attention outputs for the `hidden_states`.
|
| 220 |
+
attn_output = gate_msa.unsqueeze(1) * attn_output
|
| 221 |
+
hidden_states = hidden_states + attn_output
|
| 222 |
+
|
| 223 |
+
norm_hidden_states = self.norm2(hidden_states)
|
| 224 |
+
norm_hidden_states = (
|
| 225 |
+
norm_hidden_states * (1 + scale_mlp[:, None]) + shift_mlp[:, None]
|
| 226 |
+
)
|
| 227 |
+
|
| 228 |
+
ff_output = self.ff(norm_hidden_states)
|
| 229 |
+
ff_output = gate_mlp.unsqueeze(1) * ff_output
|
| 230 |
+
|
| 231 |
+
hidden_states = hidden_states + ff_output
|
| 232 |
+
|
| 233 |
+
# Process attention outputs for the `encoder_hidden_states`.
|
| 234 |
+
|
| 235 |
+
context_attn_output = c_gate_msa.unsqueeze(1) * context_attn_output
|
| 236 |
+
encoder_hidden_states = encoder_hidden_states + context_attn_output
|
| 237 |
+
|
| 238 |
+
norm_encoder_hidden_states = self.norm2_context(encoder_hidden_states)
|
| 239 |
+
norm_encoder_hidden_states = (
|
| 240 |
+
norm_encoder_hidden_states * (1 + c_scale_mlp[:, None])
|
| 241 |
+
+ c_shift_mlp[:, None]
|
| 242 |
+
)
|
| 243 |
+
|
| 244 |
+
context_ff_output = self.ff_context(norm_encoder_hidden_states)
|
| 245 |
+
encoder_hidden_states = (
|
| 246 |
+
encoder_hidden_states + c_gate_mlp.unsqueeze(1) * context_ff_output
|
| 247 |
+
)
|
| 248 |
+
if encoder_hidden_states.dtype == torch.float16:
|
| 249 |
+
encoder_hidden_states = encoder_hidden_states.clip(-65504, 65504)
|
| 250 |
+
|
| 251 |
+
return encoder_hidden_states, hidden_states
|
| 252 |
+
|
| 253 |
+
|
| 254 |
+
class FluxTransformer2DModel(
|
| 255 |
+
ModelMixin, ConfigMixin, PeftAdapterMixin, FromOriginalModelMixin
|
| 256 |
+
):
|
| 257 |
+
"""
|
| 258 |
+
The Transformer model introduced in Flux.
|
| 259 |
+
|
| 260 |
+
Reference: https://blackforestlabs.ai/announcing-black-forest-labs/
|
| 261 |
+
|
| 262 |
+
Parameters:
|
| 263 |
+
patch_size (`int`): Patch size to turn the input data into small patches.
|
| 264 |
+
in_channels (`int`, *optional*, defaults to 16): The number of channels in the input.
|
| 265 |
+
num_layers (`int`, *optional*, defaults to 18): The number of layers of MMDiT blocks to use.
|
| 266 |
+
num_single_layers (`int`, *optional*, defaults to 18): The number of layers of single DiT blocks to use.
|
| 267 |
+
attention_head_dim (`int`, *optional*, defaults to 64): The number of channels in each head.
|
| 268 |
+
num_attention_heads (`int`, *optional*, defaults to 18): The number of heads to use for multi-head attention.
|
| 269 |
+
joint_attention_dim (`int`, *optional*): The number of `encoder_hidden_states` dimensions to use.
|
| 270 |
+
pooled_projection_dim (`int`): Number of dimensions to use when projecting the `pooled_projections`.
|
| 271 |
+
guidance_embeds (`bool`, defaults to False): Whether to use guidance embeddings.
|
| 272 |
+
"""
|
| 273 |
+
|
| 274 |
+
_supports_gradient_checkpointing = True
|
| 275 |
+
|
| 276 |
+
@register_to_config
|
| 277 |
+
def __init__(
|
| 278 |
+
self,
|
| 279 |
+
patch_size: int = 1,
|
| 280 |
+
in_channels: int = 64,
|
| 281 |
+
num_layers: int = 19,
|
| 282 |
+
num_single_layers: int = 38,
|
| 283 |
+
attention_head_dim: int = 128,
|
| 284 |
+
num_attention_heads: int = 24,
|
| 285 |
+
joint_attention_dim: int = 4096,
|
| 286 |
+
pooled_projection_dim: int = 768,
|
| 287 |
+
guidance_embeds: bool = False,
|
| 288 |
+
axes_dims_rope: List[int] = [16, 56, 56],
|
| 289 |
+
):
|
| 290 |
+
super().__init__()
|
| 291 |
+
self.out_channels = in_channels
|
| 292 |
+
self.inner_dim = (
|
| 293 |
+
self.config.num_attention_heads * self.config.attention_head_dim
|
| 294 |
+
)
|
| 295 |
+
|
| 296 |
+
self.pos_embed = EmbedND(
|
| 297 |
+
dim=self.inner_dim, theta=10000, axes_dim=axes_dims_rope
|
| 298 |
+
)
|
| 299 |
+
text_time_guidance_cls = (
|
| 300 |
+
CombinedTimestepGuidanceTextProjEmbeddings
|
| 301 |
+
if guidance_embeds
|
| 302 |
+
else CombinedTimestepTextProjEmbeddings
|
| 303 |
+
)
|
| 304 |
+
self.time_text_embed = text_time_guidance_cls(
|
| 305 |
+
embedding_dim=self.inner_dim,
|
| 306 |
+
pooled_projection_dim=self.config.pooled_projection_dim,
|
| 307 |
+
)
|
| 308 |
+
|
| 309 |
+
self.context_embedder = nn.Linear(
|
| 310 |
+
self.config.joint_attention_dim, self.inner_dim
|
| 311 |
+
)
|
| 312 |
+
self.x_embedder = torch.nn.Linear(self.config.in_channels, self.inner_dim)
|
| 313 |
+
|
| 314 |
+
self.transformer_blocks = nn.ModuleList(
|
| 315 |
+
[
|
| 316 |
+
FluxTransformerBlock(
|
| 317 |
+
dim=self.inner_dim,
|
| 318 |
+
num_attention_heads=self.config.num_attention_heads,
|
| 319 |
+
attention_head_dim=self.config.attention_head_dim,
|
| 320 |
+
)
|
| 321 |
+
for i in range(self.config.num_layers)
|
| 322 |
+
]
|
| 323 |
+
)
|
| 324 |
+
|
| 325 |
+
self.single_transformer_blocks = nn.ModuleList(
|
| 326 |
+
[
|
| 327 |
+
FluxSingleTransformerBlock(
|
| 328 |
+
dim=self.inner_dim,
|
| 329 |
+
num_attention_heads=self.config.num_attention_heads,
|
| 330 |
+
attention_head_dim=self.config.attention_head_dim,
|
| 331 |
+
)
|
| 332 |
+
for i in range(self.config.num_single_layers)
|
| 333 |
+
]
|
| 334 |
+
)
|
| 335 |
+
|
| 336 |
+
self.norm_out = AdaLayerNormContinuous(
|
| 337 |
+
self.inner_dim, self.inner_dim, elementwise_affine=False, eps=1e-6
|
| 338 |
+
)
|
| 339 |
+
self.proj_out = nn.Linear(
|
| 340 |
+
self.inner_dim, patch_size * patch_size * self.out_channels, bias=True
|
| 341 |
+
)
|
| 342 |
+
|
| 343 |
+
self.gradient_checkpointing = False
|
| 344 |
+
|
| 345 |
+
def _set_gradient_checkpointing(self, module, value=False):
|
| 346 |
+
if hasattr(module, "gradient_checkpointing"):
|
| 347 |
+
module.gradient_checkpointing = value
|
| 348 |
+
|
| 349 |
+
def forward(
|
| 350 |
+
self,
|
| 351 |
+
hidden_states: torch.Tensor,
|
| 352 |
+
encoder_hidden_states: torch.Tensor = None,
|
| 353 |
+
pooled_projections: torch.Tensor = None,
|
| 354 |
+
timestep: torch.LongTensor = None,
|
| 355 |
+
img_ids: torch.Tensor = None,
|
| 356 |
+
txt_ids: torch.Tensor = None,
|
| 357 |
+
guidance: torch.Tensor = None,
|
| 358 |
+
joint_attention_kwargs: Optional[Dict[str, Any]] = None,
|
| 359 |
+
controlnet_block_samples=None,
|
| 360 |
+
controlnet_single_block_samples=None,
|
| 361 |
+
return_dict: bool = True,
|
| 362 |
+
) -> Union[torch.FloatTensor, Transformer2DModelOutput]:
|
| 363 |
+
"""
|
| 364 |
+
The [`FluxTransformer2DModel`] forward method.
|
| 365 |
+
|
| 366 |
+
Args:
|
| 367 |
+
hidden_states (`torch.FloatTensor` of shape `(batch size, channel, height, width)`):
|
| 368 |
+
Input `hidden_states`.
|
| 369 |
+
encoder_hidden_states (`torch.FloatTensor` of shape `(batch size, sequence_len, embed_dims)`):
|
| 370 |
+
Conditional embeddings (embeddings computed from the input conditions such as prompts) to use.
|
| 371 |
+
pooled_projections (`torch.FloatTensor` of shape `(batch_size, projection_dim)`): Embeddings projected
|
| 372 |
+
from the embeddings of input conditions.
|
| 373 |
+
timestep ( `torch.LongTensor`):
|
| 374 |
+
Used to indicate denoising step.
|
| 375 |
+
block_controlnet_hidden_states: (`list` of `torch.Tensor`):
|
| 376 |
+
A list of tensors that if specified are added to the residuals of transformer blocks.
|
| 377 |
+
joint_attention_kwargs (`dict`, *optional*):
|
| 378 |
+
A kwargs dictionary that if specified is passed along to the `AttentionProcessor` as defined under
|
| 379 |
+
`self.processor` in
|
| 380 |
+
[diffusers.models.attention_processor](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py).
|
| 381 |
+
return_dict (`bool`, *optional*, defaults to `True`):
|
| 382 |
+
Whether or not to return a [`~models.transformer_2d.Transformer2DModelOutput`] instead of a plain
|
| 383 |
+
tuple.
|
| 384 |
+
|
| 385 |
+
Returns:
|
| 386 |
+
If `return_dict` is True, an [`~models.transformer_2d.Transformer2DModelOutput`] is returned, otherwise a
|
| 387 |
+
`tuple` where the first element is the sample tensor.
|
| 388 |
+
"""
|
| 389 |
+
if joint_attention_kwargs is not None:
|
| 390 |
+
joint_attention_kwargs = joint_attention_kwargs.copy()
|
| 391 |
+
lora_scale = joint_attention_kwargs.pop("scale", 1.0)
|
| 392 |
+
else:
|
| 393 |
+
lora_scale = 1.0
|
| 394 |
+
|
| 395 |
+
if USE_PEFT_BACKEND:
|
| 396 |
+
# weight the lora layers by setting `lora_scale` for each PEFT layer
|
| 397 |
+
scale_lora_layers(self, lora_scale)
|
| 398 |
+
else:
|
| 399 |
+
if (
|
| 400 |
+
joint_attention_kwargs is not None
|
| 401 |
+
and joint_attention_kwargs.get("scale", None) is not None
|
| 402 |
+
):
|
| 403 |
+
logger.warning(
|
| 404 |
+
"Passing `scale` via `joint_attention_kwargs` when not using the PEFT backend is ineffective."
|
| 405 |
+
)
|
| 406 |
+
hidden_states = self.x_embedder(hidden_states)
|
| 407 |
+
|
| 408 |
+
timestep = timestep.to(hidden_states.dtype) * 1000
|
| 409 |
+
if guidance is not None:
|
| 410 |
+
guidance = guidance.to(hidden_states.dtype) * 1000
|
| 411 |
+
else:
|
| 412 |
+
guidance = None
|
| 413 |
+
temb = (
|
| 414 |
+
self.time_text_embed(timestep, pooled_projections)
|
| 415 |
+
if guidance is None
|
| 416 |
+
else self.time_text_embed(timestep, guidance, pooled_projections)
|
| 417 |
+
)
|
| 418 |
+
encoder_hidden_states = self.context_embedder(encoder_hidden_states)
|
| 419 |
+
|
| 420 |
+
txt_ids = txt_ids.expand(img_ids.size(0), -1, -1)
|
| 421 |
+
ids = torch.cat((txt_ids, img_ids), dim=1)
|
| 422 |
+
image_rotary_emb = self.pos_embed(ids)
|
| 423 |
+
|
| 424 |
+
for index_block, block in enumerate(self.transformer_blocks):
|
| 425 |
+
if self.training and self.gradient_checkpointing:
|
| 426 |
+
|
| 427 |
+
def create_custom_forward(module, return_dict=None):
|
| 428 |
+
def custom_forward(*inputs):
|
| 429 |
+
if return_dict is not None:
|
| 430 |
+
return module(*inputs, return_dict=return_dict)
|
| 431 |
+
else:
|
| 432 |
+
return module(*inputs)
|
| 433 |
+
|
| 434 |
+
return custom_forward
|
| 435 |
+
|
| 436 |
+
ckpt_kwargs: Dict[str, Any] = (
|
| 437 |
+
{"use_reentrant": False} if is_torch_version(">=", "1.11.0") else {}
|
| 438 |
+
)
|
| 439 |
+
(
|
| 440 |
+
encoder_hidden_states,
|
| 441 |
+
hidden_states,
|
| 442 |
+
) = torch.utils.checkpoint.checkpoint(
|
| 443 |
+
create_custom_forward(block),
|
| 444 |
+
hidden_states,
|
| 445 |
+
encoder_hidden_states,
|
| 446 |
+
temb,
|
| 447 |
+
image_rotary_emb,
|
| 448 |
+
**ckpt_kwargs,
|
| 449 |
+
)
|
| 450 |
+
|
| 451 |
+
else:
|
| 452 |
+
encoder_hidden_states, hidden_states = block(
|
| 453 |
+
hidden_states=hidden_states,
|
| 454 |
+
encoder_hidden_states=encoder_hidden_states,
|
| 455 |
+
temb=temb,
|
| 456 |
+
image_rotary_emb=image_rotary_emb,
|
| 457 |
+
)
|
| 458 |
+
|
| 459 |
+
# controlnet residual
|
| 460 |
+
if controlnet_block_samples is not None:
|
| 461 |
+
interval_control = len(self.transformer_blocks) / len(
|
| 462 |
+
controlnet_block_samples
|
| 463 |
+
)
|
| 464 |
+
interval_control = int(np.ceil(interval_control))
|
| 465 |
+
hidden_states = (
|
| 466 |
+
hidden_states
|
| 467 |
+
+ controlnet_block_samples[index_block // interval_control]
|
| 468 |
+
)
|
| 469 |
+
|
| 470 |
+
hidden_states = torch.cat([encoder_hidden_states, hidden_states], dim=1)
|
| 471 |
+
|
| 472 |
+
for index_block, block in enumerate(self.single_transformer_blocks):
|
| 473 |
+
if self.training and self.gradient_checkpointing:
|
| 474 |
+
|
| 475 |
+
def create_custom_forward(module, return_dict=None):
|
| 476 |
+
def custom_forward(*inputs):
|
| 477 |
+
if return_dict is not None:
|
| 478 |
+
return module(*inputs, return_dict=return_dict)
|
| 479 |
+
else:
|
| 480 |
+
return module(*inputs)
|
| 481 |
+
|
| 482 |
+
return custom_forward
|
| 483 |
+
|
| 484 |
+
ckpt_kwargs: Dict[str, Any] = (
|
| 485 |
+
{"use_reentrant": False} if is_torch_version(">=", "1.11.0") else {}
|
| 486 |
+
)
|
| 487 |
+
hidden_states = torch.utils.checkpoint.checkpoint(
|
| 488 |
+
create_custom_forward(block),
|
| 489 |
+
hidden_states,
|
| 490 |
+
temb,
|
| 491 |
+
image_rotary_emb,
|
| 492 |
+
**ckpt_kwargs,
|
| 493 |
+
)
|
| 494 |
+
|
| 495 |
+
else:
|
| 496 |
+
hidden_states = block(
|
| 497 |
+
hidden_states=hidden_states,
|
| 498 |
+
temb=temb,
|
| 499 |
+
image_rotary_emb=image_rotary_emb,
|
| 500 |
+
)
|
| 501 |
+
|
| 502 |
+
# controlnet residual
|
| 503 |
+
if controlnet_single_block_samples is not None:
|
| 504 |
+
interval_control = len(self.single_transformer_blocks) / len(
|
| 505 |
+
controlnet_single_block_samples
|
| 506 |
+
)
|
| 507 |
+
interval_control = int(np.ceil(interval_control))
|
| 508 |
+
hidden_states[:, encoder_hidden_states.shape[1] :, ...] = (
|
| 509 |
+
hidden_states[:, encoder_hidden_states.shape[1] :, ...]
|
| 510 |
+
+ controlnet_single_block_samples[index_block // interval_control]
|
| 511 |
+
)
|
| 512 |
+
|
| 513 |
+
hidden_states = hidden_states[:, encoder_hidden_states.shape[1] :, ...]
|
| 514 |
+
|
| 515 |
+
hidden_states = self.norm_out(hidden_states, temb)
|
| 516 |
+
output = self.proj_out(hidden_states)
|
| 517 |
+
|
| 518 |
+
if USE_PEFT_BACKEND:
|
| 519 |
+
# remove `lora_scale` from each PEFT layer
|
| 520 |
+
unscale_lora_layers(self, lora_scale)
|
| 521 |
+
|
| 522 |
+
if not return_dict:
|
| 523 |
+
return (output,)
|
| 524 |
+
|
| 525 |
+
return Transformer2DModelOutput(sample=output)
|