LPX55 commited on
Commit
10d2af3
·
verified ·
1 Parent(s): 734f877

Upload 6 files

Browse files
README.md CHANGED
@@ -1,14 +1,12 @@
1
  ---
2
- title: Kontext-FluxD Lightning
3
- emoji:
4
- colorFrom: gray
5
  colorTo: yellow
6
  sdk: gradio
7
  sdk_version: 5.35.0
8
  app_file: app.py
9
  pinned: false
10
- license: apache-2.0
11
- short_description: ⚡8-step Kontext Model w/ Multi-Image Editing
12
  ---
13
 
14
- Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
1
  ---
2
+ title: Flux Fill Outpainting / Kontex
3
+ emoji: 👈🖼️👉
4
+ colorFrom: red
5
  colorTo: yellow
6
  sdk: gradio
7
  sdk_version: 5.35.0
8
  app_file: app.py
9
  pinned: false
 
 
10
  ---
11
 
12
+ Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
app_kontext.py ADDED
@@ -0,0 +1,301 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import numpy as np
3
+ import spaces
4
+ import torch
5
+ import random
6
+ import os
7
+ import subprocess
8
+
9
+ #####################################################
10
+ # Forced Diffusers upgrade when cache was being stubborn; probably not needed now
11
+ force = subprocess.run("pip install -U diffusers", shell=True)
12
+ force = subprocess.run("pip install git+https://github.com/huggingface/diffusers.git", shell=True)
13
+ #####################################################
14
+
15
+ import diffusers
16
+ from diffusers import DiffusionPipeline
17
+ from diffusers.quantizers import PipelineQuantizationConfig
18
+ from diffusers.utils import load_image
19
+ from diffusers import FluxKontextPipeline
20
+ from PIL import Image
21
+ from huggingface_hub import hf_hub_download
22
+ from huggingface_hub.utils._runtime import dump_environment_info
23
+
24
+ #####################################################
25
+
26
+ MAX_SEED = np.iinfo(np.int32).max
27
+ API_TOKEN = os.environ['HF_TOKEN']
28
+ DEVICE = "cuda" if torch.cuda.is_available() else "cpu"
29
+
30
+ os.environ.setdefault('GRADIO_ANALYTICS_ENABLED', 'False')
31
+ os.environ.setdefault('HF_HUB_DISABLE_TELEMETRY', '1')
32
+
33
+ dump_environment_info()
34
+ logging.basicConfig(level=logging.DEBUG)
35
+ logger = logging.getLogger(__name__)
36
+
37
+ #####################################################
38
+
39
+ # TESTING TWO QUANTIZATION METHODS
40
+ # 1) If FP8 is supported; `torchao` for quantization
41
+ quant_config = PipelineQuantizationConfig(
42
+ quant_backend="torchao",
43
+ quant_kwargs={"quant_type": "float8dq_e4m3_row"},
44
+ components_to_quantize=["transformer"]
45
+ )
46
+ # 2) Otherwise, standard 4-bit quantization with bitsandbytes
47
+ # quant_config = PipelineQuantizationConfig(
48
+ # quant_backend="bitsandbytes_4bit",
49
+ # quant_kwargs={"load_in_4bit": True, "bnb_4bit_compute_dtype": torch.bfloat16, "bnb_4bit_quant_type": "nf4"},
50
+ # components_to_quantize=["transformer"]
51
+ # )
52
+
53
+ try:
54
+ # Set max memory usage for ZeroGPU
55
+ torch.cuda.set_per_process_memory_fraction(1.0)
56
+ torch.set_float32_matmul_precision("high")
57
+ except Exception as e:
58
+ print(f"Error setting memory usage: {e}")
59
+
60
+ #####################################################
61
+ # Load the pipeline with the specified quantization configuration.
62
+ # We use bfloat16 as the base dtype for mixed-precision inference.
63
+ # HF Spaces VRAM (50 GB) is sufficient to hold the entire pipeline (31.424 GB),
64
+ # Leave the entire pipeline to the GPU for the best performance.
65
+
66
+ # FLUX.1 Dev Kontext Lightning Model / 8-Steps
67
+ kontext_model = "LPX55/FLUX.1_Kontext-Lightning"
68
+ pipe = FluxKontextPipeline.from_pretrained(
69
+ kontext_model,
70
+ quantization_config=quant_config,
71
+ torch_dtype=torch.bfloat16
72
+ ).to(DEVICE)
73
+
74
+ #####################################################
75
+ # SECTION FOR LORA(S); SKIP FOR NOW
76
+
77
+ # try:
78
+ # repo_name = ""
79
+ # ckpt_name = ""
80
+ # pipe.load_lora_weights(hf_hub_download(repo_name, ckpt_name), adapter_name="A1")
81
+ # pipe.set_adapters(["A1"], adapter_weights=[0.5])
82
+ # pipe.fuse_lora(adapter_names=["A1"], lora_scale=1.0)
83
+ # pipe.unload_lora_weights()
84
+
85
+ # except Exception as e:
86
+ # print(f"Error while loading Lora: {e}")
87
+
88
+ #####################################################
89
+ def concatenate_images(images, direction="horizontal"):
90
+ """
91
+ Concatenate multiple PIL images either horizontally or vertically.
92
+
93
+ Args:
94
+ images: List of PIL Images
95
+ direction: "horizontal" or "vertical"
96
+
97
+ Returns:
98
+ PIL Image: Concatenated image
99
+ """
100
+ if not images:
101
+ return None
102
+
103
+ # Filter out None images
104
+ valid_images = [img for img in images if img is not None]
105
+
106
+ if not valid_images:
107
+ return None
108
+
109
+ if len(valid_images) == 1:
110
+ return valid_images[0].convert("RGB")
111
+
112
+ # Convert all images to RGB
113
+ valid_images = [img.convert("RGB") for img in valid_images]
114
+
115
+ if direction == "horizontal":
116
+ # Calculate total width and max height
117
+ total_width = sum(img.width for img in valid_images)
118
+ max_height = max(img.height for img in valid_images)
119
+
120
+ # Create new image
121
+ concatenated = Image.new('RGB', (total_width, max_height), (255, 255, 255))
122
+
123
+ # Paste images
124
+ x_offset = 0
125
+ for img in valid_images:
126
+ # Center image vertically if heights differ
127
+ y_offset = (max_height - img.height) // 2
128
+ concatenated.paste(img, (x_offset, y_offset))
129
+ x_offset += img.width
130
+
131
+ else: # vertical
132
+ # Calculate max width and total height
133
+ max_width = max(img.width for img in valid_images)
134
+ total_height = sum(img.height for img in valid_images)
135
+
136
+ # Create new image
137
+ concatenated = Image.new('RGB', (max_width, total_height), (255, 255, 255))
138
+
139
+ # Paste images
140
+ y_offset = 0
141
+ for img in valid_images:
142
+ # Center image horizontally if widths differ
143
+ x_offset = (max_width - img.width) // 2
144
+ concatenated.paste(img, (x_offset, y_offset))
145
+ y_offset += img.height
146
+
147
+ return concatenated
148
+
149
+ @spaces.GPU
150
+ @torch.no_grad()
151
+ def infer(input_images, prompt, seed=42, randomize_seed=False, guidance_scale=2.5, steps=8, width=1024, height=1024, progress=gr.Progress(track_tqdm=True)):
152
+
153
+ if randomize_seed:
154
+ seed = random.randint(0, MAX_SEED)
155
+
156
+ # Handle input_images - it could be a single image or a list of images
157
+ if input_images is None:
158
+ raise gr.Error("Please upload at least one image.")
159
+
160
+ # If it's a single image (not a list), convert to list
161
+ if not isinstance(input_images, list):
162
+ input_images = [input_images]
163
+
164
+ # Filter out None images
165
+ valid_images = [img[0] for img in input_images if img is not None]
166
+
167
+ if not valid_images:
168
+ raise gr.Error("Please upload at least one valid image.")
169
+
170
+ # Concatenate images horizontally
171
+ concatenated_image = concatenate_images(valid_images, "horizontal")
172
+
173
+ if concatenated_image is None:
174
+ raise gr.Error("Failed to process the input images.")
175
+
176
+ # original_width, original_height = concatenated_image.size
177
+
178
+ # if original_width >= original_height:
179
+ # new_width = 1024
180
+ # new_height = int(original_height * (new_width / original_width))
181
+ # new_height = round(new_height / 64) * 64
182
+ # else:
183
+ # new_height = 1024
184
+ # new_width = int(original_width * (new_height / original_height))
185
+ # new_width = round(new_width / 64) * 64
186
+
187
+ #concatenated_image_resized = concatenated_image.resize((new_width, new_height), Image.LANCZOS)
188
+
189
+ final_prompt = f"From the provided reference images, create a unified, cohesive image such that {prompt}. Maintain the identity and characteristics of each subject while adjusting their proportions, scale, and positioning to create a harmonious, naturally balanced composition. Blend and integrate all elements seamlessly with consistent lighting, perspective, and style.the final result should look like a single naturally captured scene where all subjects are properly sized and positioned relative to each other, not assembled from multiple sources."
190
+
191
+ image = pipe(
192
+ image=concatenated_image,
193
+ prompt=final_prompt,
194
+ guidance_scale=guidance_scale,
195
+ width=width,
196
+ height=height,
197
+ max_area=width * height,
198
+ num_inference_steps=steps,
199
+ generator=torch.Generator().manual_seed(seed),
200
+ ).images[0]
201
+
202
+ return image, seed, gr.update(visible=True)
203
+
204
+ css="""
205
+ #col-container {
206
+ margin: 0 auto;
207
+ max-width: 86vw;
208
+ }
209
+ """
210
+
211
+ with gr.Blocks(css=css) as demo:
212
+
213
+ with gr.Column(elem_id="col-container"):
214
+ gr.Markdown(f"""# FLUX.1 Kontext | Lightning 8-Step Model ⚡
215
+ """)
216
+ with gr.Row():
217
+ with gr.Column():
218
+ input_images = gr.Gallery(
219
+ label="Upload image(s) for editing",
220
+ show_label=True,
221
+ elem_id="gallery_input",
222
+ columns=3,
223
+ rows=2,
224
+ object_fit="contain",
225
+ height="auto",
226
+ file_types=['image'],
227
+ type='pil'
228
+ )
229
+
230
+ with gr.Row():
231
+ prompt = gr.Text(
232
+ label="Prompt",
233
+ show_label=False,
234
+ max_lines=1,
235
+ placeholder="Enter your prompt for editing (e.g., 'Remove glasses', 'Add a hat')",
236
+ container=False,
237
+ )
238
+ run_button = gr.Button("Run", scale=0)
239
+
240
+ with gr.Accordion("Advanced Settings", open=True):
241
+
242
+ with gr.Group():
243
+ width = gr.Slider(
244
+ label="W",
245
+ minimum=512,
246
+ maximum=2560,
247
+ step=64,
248
+ value=1024,
249
+ )
250
+
251
+ height = gr.Slider(
252
+ label="H",
253
+ minimum=512,
254
+ maximum=2560,
255
+ step=64,
256
+ value=1024,
257
+ )
258
+
259
+ seed = gr.Slider(
260
+ label="Seed",
261
+ minimum=0,
262
+ maximum=MAX_SEED,
263
+ step=1,
264
+ value=0,
265
+ )
266
+
267
+ randomize_seed = gr.Checkbox(label="Randomize seed", value=True)
268
+
269
+ guidance_scale = gr.Slider(
270
+ label="Guidance Scale",
271
+ minimum=1,
272
+ maximum=10,
273
+ step=0.1,
274
+ value=2.5,
275
+ )
276
+ input_steps = gr.Slider(
277
+ label="Steps",
278
+ minimum=1,
279
+ maximum=30,
280
+ step=1,
281
+ value=16,
282
+ )
283
+
284
+ with gr.Column():
285
+ result = gr.Image(label="Result", show_label=False, interactive=False)
286
+ reuse_button = gr.Button("Reuse this image", visible=False)
287
+
288
+ gr.on(
289
+ triggers=[run_button.click, prompt.submit],
290
+ fn = infer,
291
+ inputs = [input_images, prompt, seed, randomize_seed, guidance_scale, input_steps, width, height],
292
+ outputs = [result, seed, reuse_button]
293
+ )
294
+
295
+ reuse_button.click(
296
+ fn = lambda image: [image] if image is not None else [], # Convert single image to list for gallery
297
+ inputs = [result],
298
+ outputs = [input_images]
299
+ )
300
+
301
+ demo.launch()
controlnet_flux.py ADDED
@@ -0,0 +1,418 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ )
kontext_pipeline.py ADDED
@@ -0,0 +1,1134 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2025 Black Forest Labs and The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ import diffusers
15
+ import inspect
16
+ from typing import Any, Callable, Dict, List, Optional, Union
17
+
18
+ import numpy as np
19
+ import torch
20
+ from transformers import (
21
+ CLIPImageProcessor,
22
+ CLIPTextModel,
23
+ CLIPTokenizer,
24
+ CLIPVisionModelWithProjection,
25
+ T5EncoderModel,
26
+ T5TokenizerFast,
27
+ )
28
+
29
+ from diffusers.image_processor import PipelineImageInput, VaeImageProcessor
30
+ from diffusers.loaders import FluxIPAdapterMixin, FluxLoraLoaderMixin, FromSingleFileMixin, TextualInversionLoaderMixin
31
+ from diffusers.models import AutoencoderKL, FluxTransformer2DModel
32
+ from diffusers.schedulers import FlowMatchEulerDiscreteScheduler
33
+ from diffusers.utils import (
34
+ USE_PEFT_BACKEND,
35
+ is_torch_xla_available,
36
+ logging,
37
+ replace_example_docstring,
38
+ scale_lora_layers,
39
+ unscale_lora_layers,
40
+ )
41
+ from diffusers.utils.torch_utils import randn_tensor
42
+ from diffusers import DiffusionPipeline
43
+ from .pipeline_output import FluxPipelineOutput
44
+
45
+
46
+ if is_torch_xla_available():
47
+ import torch_xla.core.xla_model as xm
48
+
49
+ XLA_AVAILABLE = True
50
+ else:
51
+ XLA_AVAILABLE = False
52
+
53
+
54
+ logger = logging.get_logger(__name__) # pylint: disable=invalid-name
55
+
56
+ EXAMPLE_DOC_STRING = """
57
+ Examples:
58
+ ```py
59
+ >>> import torch
60
+ >>> from diffusers import FluxKontextPipeline
61
+ >>> from diffusers.utils import load_image
62
+
63
+ >>> pipe = FluxKontextPipeline.from_pretrained(
64
+ ... "black-forest-labs/FLUX.1-Kontext-dev", torch_dtype=torch.bfloat16
65
+ ... )
66
+ >>> pipe.to("cuda")
67
+
68
+ >>> image = load_image(
69
+ ... "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/yarn-art-pikachu.png"
70
+ ... ).convert("RGB")
71
+ >>> prompt = "Make Pikachu hold a sign that says 'Black Forest Labs is awesome', yarn art style, detailed, vibrant colors"
72
+ >>> image = pipe(
73
+ ... image=image,
74
+ ... prompt=prompt,
75
+ ... guidance_scale=2.5,
76
+ ... generator=torch.Generator().manual_seed(42),
77
+ ... ).images[0]
78
+ >>> image.save("output.png")
79
+ ```
80
+ """
81
+
82
+ PREFERRED_KONTEXT_RESOLUTIONS = [
83
+ (672, 1568),
84
+ (688, 1504),
85
+ (720, 1456),
86
+ (752, 1392),
87
+ (800, 1328),
88
+ (832, 1248),
89
+ (880, 1184),
90
+ (944, 1104),
91
+ (1024, 1024),
92
+ (1104, 944),
93
+ (1184, 880),
94
+ (1248, 832),
95
+ (1328, 800),
96
+ (1392, 752),
97
+ (1456, 720),
98
+ (1504, 688),
99
+ (1568, 672),
100
+ ]
101
+
102
+
103
+ def calculate_shift(
104
+ image_seq_len,
105
+ base_seq_len: int = 256,
106
+ max_seq_len: int = 4096,
107
+ base_shift: float = 0.5,
108
+ max_shift: float = 1.15,
109
+ ):
110
+ m = (max_shift - base_shift) / (max_seq_len - base_seq_len)
111
+ b = base_shift - m * base_seq_len
112
+ mu = image_seq_len * m + b
113
+ return mu
114
+
115
+
116
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.retrieve_timesteps
117
+ def retrieve_timesteps(
118
+ scheduler,
119
+ num_inference_steps: Optional[int] = None,
120
+ device: Optional[Union[str, torch.device]] = None,
121
+ timesteps: Optional[List[int]] = None,
122
+ sigmas: Optional[List[float]] = None,
123
+ **kwargs,
124
+ ):
125
+ r"""
126
+ Calls the scheduler's `set_timesteps` method and retrieves timesteps from the scheduler after the call. Handles
127
+ custom timesteps. Any kwargs will be supplied to `scheduler.set_timesteps`.
128
+
129
+ Args:
130
+ scheduler (`SchedulerMixin`):
131
+ The scheduler to get timesteps from.
132
+ num_inference_steps (`int`):
133
+ The number of diffusion steps used when generating samples with a pre-trained model. If used, `timesteps`
134
+ must be `None`.
135
+ device (`str` or `torch.device`, *optional*):
136
+ The device to which the timesteps should be moved to. If `None`, the timesteps are not moved.
137
+ timesteps (`List[int]`, *optional*):
138
+ Custom timesteps used to override the timestep spacing strategy of the scheduler. If `timesteps` is passed,
139
+ `num_inference_steps` and `sigmas` must be `None`.
140
+ sigmas (`List[float]`, *optional*):
141
+ Custom sigmas used to override the timestep spacing strategy of the scheduler. If `sigmas` is passed,
142
+ `num_inference_steps` and `timesteps` must be `None`.
143
+
144
+ Returns:
145
+ `Tuple[torch.Tensor, int]`: A tuple where the first element is the timestep schedule from the scheduler and the
146
+ second element is the number of inference steps.
147
+ """
148
+ if timesteps is not None and sigmas is not None:
149
+ raise ValueError("Only one of `timesteps` or `sigmas` can be passed. Please choose one to set custom values")
150
+ if timesteps is not None:
151
+ accepts_timesteps = "timesteps" in set(inspect.signature(scheduler.set_timesteps).parameters.keys())
152
+ if not accepts_timesteps:
153
+ raise ValueError(
154
+ f"The current scheduler class {scheduler.__class__}'s `set_timesteps` does not support custom"
155
+ f" timestep schedules. Please check whether you are using the correct scheduler."
156
+ )
157
+ scheduler.set_timesteps(timesteps=timesteps, device=device, **kwargs)
158
+ timesteps = scheduler.timesteps
159
+ num_inference_steps = len(timesteps)
160
+ elif sigmas is not None:
161
+ accept_sigmas = "sigmas" in set(inspect.signature(scheduler.set_timesteps).parameters.keys())
162
+ if not accept_sigmas:
163
+ raise ValueError(
164
+ f"The current scheduler class {scheduler.__class__}'s `set_timesteps` does not support custom"
165
+ f" sigmas schedules. Please check whether you are using the correct scheduler."
166
+ )
167
+ scheduler.set_timesteps(sigmas=sigmas, device=device, **kwargs)
168
+ timesteps = scheduler.timesteps
169
+ num_inference_steps = len(timesteps)
170
+ else:
171
+ scheduler.set_timesteps(num_inference_steps, device=device, **kwargs)
172
+ timesteps = scheduler.timesteps
173
+ return timesteps, num_inference_steps
174
+
175
+
176
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion_img2img.retrieve_latents
177
+ def retrieve_latents(
178
+ encoder_output: torch.Tensor, generator: Optional[torch.Generator] = None, sample_mode: str = "sample"
179
+ ):
180
+ if hasattr(encoder_output, "latent_dist") and sample_mode == "sample":
181
+ return encoder_output.latent_dist.sample(generator)
182
+ elif hasattr(encoder_output, "latent_dist") and sample_mode == "argmax":
183
+ return encoder_output.latent_dist.mode()
184
+ elif hasattr(encoder_output, "latents"):
185
+ return encoder_output.latents
186
+ else:
187
+ raise AttributeError("Could not access latents of provided encoder_output")
188
+
189
+
190
+ class FluxKontextPipeline(
191
+ DiffusionPipeline,
192
+ FluxLoraLoaderMixin,
193
+ FromSingleFileMixin,
194
+ TextualInversionLoaderMixin,
195
+ FluxIPAdapterMixin,
196
+ ):
197
+ r"""
198
+ The Flux Kontext pipeline for text-to-image generation.
199
+
200
+ Reference: https://blackforestlabs.ai/announcing-black-forest-labs/
201
+
202
+ Args:
203
+ transformer ([`FluxTransformer2DModel`]):
204
+ Conditional Transformer (MMDiT) architecture to denoise the encoded image latents.
205
+ scheduler ([`FlowMatchEulerDiscreteScheduler`]):
206
+ A scheduler to be used in combination with `transformer` to denoise the encoded image latents.
207
+ vae ([`AutoencoderKL`]):
208
+ Variational Auto-Encoder (VAE) Model to encode and decode images to and from latent representations.
209
+ text_encoder ([`CLIPTextModel`]):
210
+ [CLIP](https://huggingface.co/docs/transformers/model_doc/clip#transformers.CLIPTextModel), specifically
211
+ the [clip-vit-large-patch14](https://huggingface.co/openai/clip-vit-large-patch14) variant.
212
+ text_encoder_2 ([`T5EncoderModel`]):
213
+ [T5](https://huggingface.co/docs/transformers/en/model_doc/t5#transformers.T5EncoderModel), specifically
214
+ the [google/t5-v1_1-xxl](https://huggingface.co/google/t5-v1_1-xxl) variant.
215
+ tokenizer (`CLIPTokenizer`):
216
+ Tokenizer of class
217
+ [CLIPTokenizer](https://huggingface.co/docs/transformers/en/model_doc/clip#transformers.CLIPTokenizer).
218
+ tokenizer_2 (`T5TokenizerFast`):
219
+ Second Tokenizer of class
220
+ [T5TokenizerFast](https://huggingface.co/docs/transformers/en/model_doc/t5#transformers.T5TokenizerFast).
221
+ """
222
+
223
+ model_cpu_offload_seq = "text_encoder->text_encoder_2->image_encoder->transformer->vae"
224
+ _optional_components = ["image_encoder", "feature_extractor"]
225
+ _callback_tensor_inputs = ["latents", "prompt_embeds"]
226
+
227
+ def __init__(
228
+ self,
229
+ scheduler: FlowMatchEulerDiscreteScheduler,
230
+ vae: AutoencoderKL,
231
+ text_encoder: CLIPTextModel,
232
+ tokenizer: CLIPTokenizer,
233
+ text_encoder_2: T5EncoderModel,
234
+ tokenizer_2: T5TokenizerFast,
235
+ transformer: FluxTransformer2DModel,
236
+ image_encoder: CLIPVisionModelWithProjection = None,
237
+ feature_extractor: CLIPImageProcessor = None,
238
+ ):
239
+ super().__init__()
240
+
241
+ self.register_modules(
242
+ vae=vae,
243
+ text_encoder=text_encoder,
244
+ text_encoder_2=text_encoder_2,
245
+ tokenizer=tokenizer,
246
+ tokenizer_2=tokenizer_2,
247
+ transformer=transformer,
248
+ scheduler=scheduler,
249
+ image_encoder=image_encoder,
250
+ feature_extractor=feature_extractor,
251
+ )
252
+ self.vae_scale_factor = 2 ** (len(self.vae.config.block_out_channels) - 1) if getattr(self, "vae", None) else 8
253
+ # Flux latents are turned into 2x2 patches and packed. This means the latent width and height has to be divisible
254
+ # by the patch size. So the vae scale factor is multiplied by the patch size to account for this
255
+ self.latent_channels = self.vae.config.latent_channels if getattr(self, "vae", None) else 16
256
+ self.image_processor = VaeImageProcessor(vae_scale_factor=self.vae_scale_factor * 2)
257
+ self.tokenizer_max_length = (
258
+ self.tokenizer.model_max_length if hasattr(self, "tokenizer") and self.tokenizer is not None else 77
259
+ )
260
+ self.default_sample_size = 128
261
+
262
+ # Copied from diffusers.pipelines.flux.pipeline_flux.FluxPipeline._get_t5_prompt_embeds
263
+ def _get_t5_prompt_embeds(
264
+ self,
265
+ prompt: Union[str, List[str]] = None,
266
+ num_images_per_prompt: int = 1,
267
+ max_sequence_length: int = 512,
268
+ device: Optional[torch.device] = None,
269
+ dtype: Optional[torch.dtype] = None,
270
+ ):
271
+ device = device or self._execution_device
272
+ dtype = dtype or self.text_encoder.dtype
273
+
274
+ prompt = [prompt] if isinstance(prompt, str) else prompt
275
+ batch_size = len(prompt)
276
+
277
+ if isinstance(self, TextualInversionLoaderMixin):
278
+ prompt = self.maybe_convert_prompt(prompt, self.tokenizer_2)
279
+
280
+ text_inputs = self.tokenizer_2(
281
+ prompt,
282
+ padding="max_length",
283
+ max_length=max_sequence_length,
284
+ truncation=True,
285
+ return_length=False,
286
+ return_overflowing_tokens=False,
287
+ return_tensors="pt",
288
+ )
289
+ text_input_ids = text_inputs.input_ids
290
+ untruncated_ids = self.tokenizer_2(prompt, padding="longest", return_tensors="pt").input_ids
291
+
292
+ if untruncated_ids.shape[-1] >= text_input_ids.shape[-1] and not torch.equal(text_input_ids, untruncated_ids):
293
+ removed_text = self.tokenizer_2.batch_decode(untruncated_ids[:, self.tokenizer_max_length - 1 : -1])
294
+ logger.warning(
295
+ "The following part of your input was truncated because `max_sequence_length` is set to "
296
+ f" {max_sequence_length} tokens: {removed_text}"
297
+ )
298
+
299
+ prompt_embeds = self.text_encoder_2(text_input_ids.to(device), output_hidden_states=False)[0]
300
+
301
+ dtype = self.text_encoder_2.dtype
302
+ prompt_embeds = prompt_embeds.to(dtype=dtype, device=device)
303
+
304
+ _, seq_len, _ = prompt_embeds.shape
305
+
306
+ # duplicate text embeddings and attention mask for each generation per prompt, using mps friendly method
307
+ prompt_embeds = prompt_embeds.repeat(1, num_images_per_prompt, 1)
308
+ prompt_embeds = prompt_embeds.view(batch_size * num_images_per_prompt, seq_len, -1)
309
+
310
+ return prompt_embeds
311
+
312
+ # Copied from diffusers.pipelines.flux.pipeline_flux.FluxPipeline._get_clip_prompt_embeds
313
+ def _get_clip_prompt_embeds(
314
+ self,
315
+ prompt: Union[str, List[str]],
316
+ num_images_per_prompt: int = 1,
317
+ device: Optional[torch.device] = None,
318
+ ):
319
+ device = device or self._execution_device
320
+
321
+ prompt = [prompt] if isinstance(prompt, str) else prompt
322
+ batch_size = len(prompt)
323
+
324
+ if isinstance(self, TextualInversionLoaderMixin):
325
+ prompt = self.maybe_convert_prompt(prompt, self.tokenizer)
326
+
327
+ text_inputs = self.tokenizer(
328
+ prompt,
329
+ padding="max_length",
330
+ max_length=self.tokenizer_max_length,
331
+ truncation=True,
332
+ return_overflowing_tokens=False,
333
+ return_length=False,
334
+ return_tensors="pt",
335
+ )
336
+
337
+ text_input_ids = text_inputs.input_ids
338
+ untruncated_ids = self.tokenizer(prompt, padding="longest", return_tensors="pt").input_ids
339
+ if untruncated_ids.shape[-1] >= text_input_ids.shape[-1] and not torch.equal(text_input_ids, untruncated_ids):
340
+ removed_text = self.tokenizer.batch_decode(untruncated_ids[:, self.tokenizer_max_length - 1 : -1])
341
+ logger.warning(
342
+ "The following part of your input was truncated because CLIP can only handle sequences up to"
343
+ f" {self.tokenizer_max_length} tokens: {removed_text}"
344
+ )
345
+ prompt_embeds = self.text_encoder(text_input_ids.to(device), output_hidden_states=False)
346
+
347
+ # Use pooled output of CLIPTextModel
348
+ prompt_embeds = prompt_embeds.pooler_output
349
+ prompt_embeds = prompt_embeds.to(dtype=self.text_encoder.dtype, device=device)
350
+
351
+ # duplicate text embeddings for each generation per prompt, using mps friendly method
352
+ prompt_embeds = prompt_embeds.repeat(1, num_images_per_prompt)
353
+ prompt_embeds = prompt_embeds.view(batch_size * num_images_per_prompt, -1)
354
+
355
+ return prompt_embeds
356
+
357
+ # Copied from diffusers.pipelines.flux.pipeline_flux.FluxPipeline.encode_prompt
358
+ def encode_prompt(
359
+ self,
360
+ prompt: Union[str, List[str]],
361
+ prompt_2: Union[str, List[str]],
362
+ device: Optional[torch.device] = None,
363
+ num_images_per_prompt: int = 1,
364
+ prompt_embeds: Optional[torch.FloatTensor] = None,
365
+ pooled_prompt_embeds: Optional[torch.FloatTensor] = None,
366
+ max_sequence_length: int = 512,
367
+ lora_scale: Optional[float] = None,
368
+ ):
369
+ r"""
370
+
371
+ Args:
372
+ prompt (`str` or `List[str]`, *optional*):
373
+ prompt to be encoded
374
+ prompt_2 (`str` or `List[str]`, *optional*):
375
+ The prompt or prompts to be sent to the `tokenizer_2` and `text_encoder_2`. If not defined, `prompt` is
376
+ used in all text-encoders
377
+ device: (`torch.device`):
378
+ torch device
379
+ num_images_per_prompt (`int`):
380
+ number of images that should be generated per prompt
381
+ prompt_embeds (`torch.FloatTensor`, *optional*):
382
+ Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not
383
+ provided, text embeddings will be generated from `prompt` input argument.
384
+ pooled_prompt_embeds (`torch.FloatTensor`, *optional*):
385
+ Pre-generated pooled text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting.
386
+ If not provided, pooled text embeddings will be generated from `prompt` input argument.
387
+ lora_scale (`float`, *optional*):
388
+ A lora scale that will be applied to all LoRA layers of the text encoder if LoRA layers are loaded.
389
+ """
390
+ device = device or self._execution_device
391
+
392
+ # set lora scale so that monkey patched LoRA
393
+ # function of text encoder can correctly access it
394
+ if lora_scale is not None and isinstance(self, FluxLoraLoaderMixin):
395
+ self._lora_scale = lora_scale
396
+
397
+ # dynamically adjust the LoRA scale
398
+ if self.text_encoder is not None and USE_PEFT_BACKEND:
399
+ scale_lora_layers(self.text_encoder, lora_scale)
400
+ if self.text_encoder_2 is not None and USE_PEFT_BACKEND:
401
+ scale_lora_layers(self.text_encoder_2, lora_scale)
402
+
403
+ prompt = [prompt] if isinstance(prompt, str) else prompt
404
+
405
+ if prompt_embeds is None:
406
+ prompt_2 = prompt_2 or prompt
407
+ prompt_2 = [prompt_2] if isinstance(prompt_2, str) else prompt_2
408
+
409
+ # We only use the pooled prompt output from the CLIPTextModel
410
+ pooled_prompt_embeds = self._get_clip_prompt_embeds(
411
+ prompt=prompt,
412
+ device=device,
413
+ num_images_per_prompt=num_images_per_prompt,
414
+ )
415
+ prompt_embeds = self._get_t5_prompt_embeds(
416
+ prompt=prompt_2,
417
+ num_images_per_prompt=num_images_per_prompt,
418
+ max_sequence_length=max_sequence_length,
419
+ device=device,
420
+ )
421
+
422
+ if self.text_encoder is not None:
423
+ if isinstance(self, FluxLoraLoaderMixin) and USE_PEFT_BACKEND:
424
+ # Retrieve the original scale by scaling back the LoRA layers
425
+ unscale_lora_layers(self.text_encoder, lora_scale)
426
+
427
+ if self.text_encoder_2 is not None:
428
+ if isinstance(self, FluxLoraLoaderMixin) and USE_PEFT_BACKEND:
429
+ # Retrieve the original scale by scaling back the LoRA layers
430
+ unscale_lora_layers(self.text_encoder_2, lora_scale)
431
+
432
+ dtype = self.text_encoder.dtype if self.text_encoder is not None else self.transformer.dtype
433
+ text_ids = torch.zeros(prompt_embeds.shape[1], 3).to(device=device, dtype=dtype)
434
+
435
+ return prompt_embeds, pooled_prompt_embeds, text_ids
436
+
437
+ # Copied from diffusers.pipelines.flux.pipeline_flux.FluxPipeline.encode_image
438
+ def encode_image(self, image, device, num_images_per_prompt):
439
+ dtype = next(self.image_encoder.parameters()).dtype
440
+
441
+ if not isinstance(image, torch.Tensor):
442
+ image = self.feature_extractor(image, return_tensors="pt").pixel_values
443
+
444
+ image = image.to(device=device, dtype=dtype)
445
+ image_embeds = self.image_encoder(image).image_embeds
446
+ image_embeds = image_embeds.repeat_interleave(num_images_per_prompt, dim=0)
447
+ return image_embeds
448
+
449
+ # Copied from diffusers.pipelines.flux.pipeline_flux.FluxPipeline.prepare_ip_adapter_image_embeds
450
+ def prepare_ip_adapter_image_embeds(
451
+ self, ip_adapter_image, ip_adapter_image_embeds, device, num_images_per_prompt
452
+ ):
453
+ image_embeds = []
454
+ if ip_adapter_image_embeds is None:
455
+ if not isinstance(ip_adapter_image, list):
456
+ ip_adapter_image = [ip_adapter_image]
457
+
458
+ if len(ip_adapter_image) != self.transformer.encoder_hid_proj.num_ip_adapters:
459
+ raise ValueError(
460
+ f"`ip_adapter_image` must have same length as the number of IP Adapters. Got {len(ip_adapter_image)} images and {self.transformer.encoder_hid_proj.num_ip_adapters} IP Adapters."
461
+ )
462
+
463
+ for single_ip_adapter_image in ip_adapter_image:
464
+ single_image_embeds = self.encode_image(single_ip_adapter_image, device, 1)
465
+ image_embeds.append(single_image_embeds[None, :])
466
+ else:
467
+ if not isinstance(ip_adapter_image_embeds, list):
468
+ ip_adapter_image_embeds = [ip_adapter_image_embeds]
469
+
470
+ if len(ip_adapter_image_embeds) != self.transformer.encoder_hid_proj.num_ip_adapters:
471
+ raise ValueError(
472
+ f"`ip_adapter_image_embeds` must have same length as the number of IP Adapters. Got {len(ip_adapter_image_embeds)} image embeds and {self.transformer.encoder_hid_proj.num_ip_adapters} IP Adapters."
473
+ )
474
+
475
+ for single_image_embeds in ip_adapter_image_embeds:
476
+ image_embeds.append(single_image_embeds)
477
+
478
+ ip_adapter_image_embeds = []
479
+ for single_image_embeds in image_embeds:
480
+ single_image_embeds = torch.cat([single_image_embeds] * num_images_per_prompt, dim=0)
481
+ single_image_embeds = single_image_embeds.to(device=device)
482
+ ip_adapter_image_embeds.append(single_image_embeds)
483
+
484
+ return ip_adapter_image_embeds
485
+
486
+ # Copied from diffusers.pipelines.flux.pipeline_flux.FluxPipeline.check_inputs
487
+ def check_inputs(
488
+ self,
489
+ prompt,
490
+ prompt_2,
491
+ height,
492
+ width,
493
+ negative_prompt=None,
494
+ negative_prompt_2=None,
495
+ prompt_embeds=None,
496
+ negative_prompt_embeds=None,
497
+ pooled_prompt_embeds=None,
498
+ negative_pooled_prompt_embeds=None,
499
+ callback_on_step_end_tensor_inputs=None,
500
+ max_sequence_length=None,
501
+ ):
502
+ if height % (self.vae_scale_factor * 2) != 0 or width % (self.vae_scale_factor * 2) != 0:
503
+ logger.warning(
504
+ f"`height` and `width` have to be divisible by {self.vae_scale_factor * 2} but are {height} and {width}. Dimensions will be resized accordingly"
505
+ )
506
+
507
+ if callback_on_step_end_tensor_inputs is not None and not all(
508
+ k in self._callback_tensor_inputs for k in callback_on_step_end_tensor_inputs
509
+ ):
510
+ raise ValueError(
511
+ 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]}"
512
+ )
513
+
514
+ if prompt is not None and prompt_embeds is not None:
515
+ raise ValueError(
516
+ f"Cannot forward both `prompt`: {prompt} and `prompt_embeds`: {prompt_embeds}. Please make sure to"
517
+ " only forward one of the two."
518
+ )
519
+ elif prompt_2 is not None and prompt_embeds is not None:
520
+ raise ValueError(
521
+ f"Cannot forward both `prompt_2`: {prompt_2} and `prompt_embeds`: {prompt_embeds}. Please make sure to"
522
+ " only forward one of the two."
523
+ )
524
+ elif prompt is None and prompt_embeds is None:
525
+ raise ValueError(
526
+ "Provide either `prompt` or `prompt_embeds`. Cannot leave both `prompt` and `prompt_embeds` undefined."
527
+ )
528
+ elif prompt is not None and (not isinstance(prompt, str) and not isinstance(prompt, list)):
529
+ raise ValueError(f"`prompt` has to be of type `str` or `list` but is {type(prompt)}")
530
+ elif prompt_2 is not None and (not isinstance(prompt_2, str) and not isinstance(prompt_2, list)):
531
+ raise ValueError(f"`prompt_2` has to be of type `str` or `list` but is {type(prompt_2)}")
532
+
533
+ if negative_prompt is not None and negative_prompt_embeds is not None:
534
+ raise ValueError(
535
+ f"Cannot forward both `negative_prompt`: {negative_prompt} and `negative_prompt_embeds`:"
536
+ f" {negative_prompt_embeds}. Please make sure to only forward one of the two."
537
+ )
538
+ elif negative_prompt_2 is not None and negative_prompt_embeds is not None:
539
+ raise ValueError(
540
+ f"Cannot forward both `negative_prompt_2`: {negative_prompt_2} and `negative_prompt_embeds`:"
541
+ f" {negative_prompt_embeds}. Please make sure to only forward one of the two."
542
+ )
543
+
544
+ if prompt_embeds is not None and pooled_prompt_embeds is None:
545
+ raise ValueError(
546
+ "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`."
547
+ )
548
+ if negative_prompt_embeds is not None and negative_pooled_prompt_embeds is None:
549
+ raise ValueError(
550
+ "If `negative_prompt_embeds` are provided, `negative_pooled_prompt_embeds` also have to be passed. Make sure to generate `negative_pooled_prompt_embeds` from the same text encoder that was used to generate `negative_prompt_embeds`."
551
+ )
552
+
553
+ if max_sequence_length is not None and max_sequence_length > 512:
554
+ raise ValueError(f"`max_sequence_length` cannot be greater than 512 but is {max_sequence_length}")
555
+
556
+ @staticmethod
557
+ # Copied from diffusers.pipelines.flux.pipeline_flux.FluxPipeline._prepare_latent_image_ids
558
+ def _prepare_latent_image_ids(batch_size, height, width, device, dtype):
559
+ latent_image_ids = torch.zeros(height, width, 3)
560
+ latent_image_ids[..., 1] = latent_image_ids[..., 1] + torch.arange(height)[:, None]
561
+ latent_image_ids[..., 2] = latent_image_ids[..., 2] + torch.arange(width)[None, :]
562
+
563
+ latent_image_id_height, latent_image_id_width, latent_image_id_channels = latent_image_ids.shape
564
+
565
+ latent_image_ids = latent_image_ids.reshape(
566
+ latent_image_id_height * latent_image_id_width, latent_image_id_channels
567
+ )
568
+
569
+ return latent_image_ids.to(device=device, dtype=dtype)
570
+
571
+ @staticmethod
572
+ # Copied from diffusers.pipelines.flux.pipeline_flux.FluxPipeline._pack_latents
573
+ def _pack_latents(latents, batch_size, num_channels_latents, height, width):
574
+ latents = latents.view(batch_size, num_channels_latents, height // 2, 2, width // 2, 2)
575
+ latents = latents.permute(0, 2, 4, 1, 3, 5)
576
+ latents = latents.reshape(batch_size, (height // 2) * (width // 2), num_channels_latents * 4)
577
+
578
+ return latents
579
+
580
+ @staticmethod
581
+ # Copied from diffusers.pipelines.flux.pipeline_flux.FluxPipeline._unpack_latents
582
+ def _unpack_latents(latents, height, width, vae_scale_factor):
583
+ batch_size, num_patches, channels = latents.shape
584
+
585
+ # VAE applies 8x compression on images but we must also account for packing which requires
586
+ # latent height and width to be divisible by 2.
587
+ height = 2 * (int(height) // (vae_scale_factor * 2))
588
+ width = 2 * (int(width) // (vae_scale_factor * 2))
589
+
590
+ latents = latents.view(batch_size, height // 2, width // 2, channels // 4, 2, 2)
591
+ latents = latents.permute(0, 3, 1, 4, 2, 5)
592
+
593
+ latents = latents.reshape(batch_size, channels // (2 * 2), height, width)
594
+
595
+ return latents
596
+
597
+ def _encode_vae_image(self, image: torch.Tensor, generator: torch.Generator):
598
+ if isinstance(generator, list):
599
+ image_latents = [
600
+ retrieve_latents(self.vae.encode(image[i : i + 1]), generator=generator[i], sample_mode="argmax")
601
+ for i in range(image.shape[0])
602
+ ]
603
+ image_latents = torch.cat(image_latents, dim=0)
604
+ else:
605
+ image_latents = retrieve_latents(self.vae.encode(image), generator=generator, sample_mode="argmax")
606
+
607
+ image_latents = (image_latents - self.vae.config.shift_factor) * self.vae.config.scaling_factor
608
+
609
+ return image_latents
610
+
611
+ # Copied from diffusers.pipelines.flux.pipeline_flux.FluxPipeline.enable_vae_slicing
612
+ def enable_vae_slicing(self):
613
+ r"""
614
+ Enable sliced VAE decoding. When this option is enabled, the VAE will split the input tensor in slices to
615
+ compute decoding in several steps. This is useful to save some memory and allow larger batch sizes.
616
+ """
617
+ self.vae.enable_slicing()
618
+
619
+ # Copied from diffusers.pipelines.flux.pipeline_flux.FluxPipeline.disable_vae_slicing
620
+ def disable_vae_slicing(self):
621
+ r"""
622
+ Disable sliced VAE decoding. If `enable_vae_slicing` was previously enabled, this method will go back to
623
+ computing decoding in one step.
624
+ """
625
+ self.vae.disable_slicing()
626
+
627
+ # Copied from diffusers.pipelines.flux.pipeline_flux.FluxPipeline.enable_vae_tiling
628
+ def enable_vae_tiling(self):
629
+ r"""
630
+ Enable tiled VAE decoding. When this option is enabled, the VAE will split the input tensor into tiles to
631
+ compute decoding and encoding in several steps. This is useful for saving a large amount of memory and to allow
632
+ processing larger images.
633
+ """
634
+ self.vae.enable_tiling()
635
+
636
+ # Copied from diffusers.pipelines.flux.pipeline_flux.FluxPipeline.disable_vae_tiling
637
+ def disable_vae_tiling(self):
638
+ r"""
639
+ Disable tiled VAE decoding. If `enable_vae_tiling` was previously enabled, this method will go back to
640
+ computing decoding in one step.
641
+ """
642
+ self.vae.disable_tiling()
643
+
644
+ def prepare_latents(
645
+ self,
646
+ image: Optional[torch.Tensor],
647
+ batch_size: int,
648
+ num_channels_latents: int,
649
+ height: int,
650
+ width: int,
651
+ dtype: torch.dtype,
652
+ device: torch.device,
653
+ generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
654
+ latents: Optional[torch.Tensor] = None,
655
+ ):
656
+ if isinstance(generator, list) and len(generator) != batch_size:
657
+ raise ValueError(
658
+ f"You have passed a list of generators of length {len(generator)}, but requested an effective batch"
659
+ f" size of {batch_size}. Make sure the batch size matches the length of the generators."
660
+ )
661
+
662
+ # VAE applies 8x compression on images but we must also account for packing which requires
663
+ # latent height and width to be divisible by 2.
664
+ height = 2 * (int(height) // (self.vae_scale_factor * 2))
665
+ width = 2 * (int(width) // (self.vae_scale_factor * 2))
666
+ shape = (batch_size, num_channels_latents, height, width)
667
+
668
+ image_latents = image_ids = None
669
+ if image is not None:
670
+ image = image.to(device=device, dtype=dtype)
671
+ if image.shape[1] != self.latent_channels:
672
+ image_latents = self._encode_vae_image(image=image, generator=generator)
673
+ else:
674
+ image_latents = image
675
+ if batch_size > image_latents.shape[0] and batch_size % image_latents.shape[0] == 0:
676
+ # expand init_latents for batch_size
677
+ additional_image_per_prompt = batch_size // image_latents.shape[0]
678
+ image_latents = torch.cat([image_latents] * additional_image_per_prompt, dim=0)
679
+ elif batch_size > image_latents.shape[0] and batch_size % image_latents.shape[0] != 0:
680
+ raise ValueError(
681
+ f"Cannot duplicate `image` of batch size {image_latents.shape[0]} to {batch_size} text prompts."
682
+ )
683
+ else:
684
+ image_latents = torch.cat([image_latents], dim=0)
685
+
686
+ image_latent_height, image_latent_width = image_latents.shape[2:]
687
+ image_latents = self._pack_latents(
688
+ image_latents, batch_size, num_channels_latents, image_latent_height, image_latent_width
689
+ )
690
+ image_ids = self._prepare_latent_image_ids(
691
+ batch_size, image_latent_height // 2, image_latent_width // 2, device, dtype
692
+ )
693
+ # image ids are the same as latent ids with the first dimension set to 1 instead of 0
694
+ image_ids[..., 0] = 1
695
+
696
+ latent_ids = self._prepare_latent_image_ids(batch_size, height // 2, width // 2, device, dtype)
697
+
698
+ if latents is None:
699
+ latents = randn_tensor(shape, generator=generator, device=device, dtype=dtype)
700
+ latents = self._pack_latents(latents, batch_size, num_channels_latents, height, width)
701
+ else:
702
+ latents = latents.to(device=device, dtype=dtype)
703
+
704
+ return latents, image_latents, latent_ids, image_ids
705
+
706
+ @property
707
+ def guidance_scale(self):
708
+ return self._guidance_scale
709
+
710
+ @property
711
+ def joint_attention_kwargs(self):
712
+ return self._joint_attention_kwargs
713
+
714
+ @property
715
+ def num_timesteps(self):
716
+ return self._num_timesteps
717
+
718
+ @property
719
+ def current_timestep(self):
720
+ return self._current_timestep
721
+
722
+ @property
723
+ def interrupt(self):
724
+ return self._interrupt
725
+
726
+ @torch.no_grad()
727
+ @replace_example_docstring(EXAMPLE_DOC_STRING)
728
+ def __call__(
729
+ self,
730
+ image: Optional[PipelineImageInput] = None,
731
+ prompt: Union[str, List[str]] = None,
732
+ prompt_2: Optional[Union[str, List[str]]] = None,
733
+ negative_prompt: Union[str, List[str]] = None,
734
+ negative_prompt_2: Optional[Union[str, List[str]]] = None,
735
+ true_cfg_scale: float = 1.0,
736
+ height: Optional[int] = None,
737
+ width: Optional[int] = None,
738
+ num_inference_steps: int = 28,
739
+ sigmas: Optional[List[float]] = None,
740
+ guidance_scale: float = 3.5,
741
+ num_images_per_prompt: Optional[int] = 1,
742
+ generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
743
+ latents: Optional[torch.FloatTensor] = None,
744
+ prompt_embeds: Optional[torch.FloatTensor] = None,
745
+ pooled_prompt_embeds: Optional[torch.FloatTensor] = None,
746
+ ip_adapter_image: Optional[PipelineImageInput] = None,
747
+ ip_adapter_image_embeds: Optional[List[torch.Tensor]] = None,
748
+ negative_ip_adapter_image: Optional[PipelineImageInput] = None,
749
+ negative_ip_adapter_image_embeds: Optional[List[torch.Tensor]] = None,
750
+ negative_prompt_embeds: Optional[torch.FloatTensor] = None,
751
+ negative_pooled_prompt_embeds: Optional[torch.FloatTensor] = None,
752
+ output_type: Optional[str] = "pil",
753
+ return_dict: bool = True,
754
+ joint_attention_kwargs: Optional[Dict[str, Any]] = None,
755
+ callback_on_step_end: Optional[Callable[[int, int, Dict], None]] = None,
756
+ callback_on_step_end_tensor_inputs: List[str] = ["latents"],
757
+ max_sequence_length: int = 512,
758
+ max_area: int = 1024**2,
759
+ _auto_resize: bool = True,
760
+ ):
761
+ r"""
762
+ Function invoked when calling the pipeline for generation.
763
+
764
+ Args:
765
+ image (`torch.Tensor`, `PIL.Image.Image`, `np.ndarray`, `List[torch.Tensor]`, `List[PIL.Image.Image]`, or `List[np.ndarray]`):
766
+ `Image`, numpy array or tensor representing an image batch to be used as the starting point. For both
767
+ numpy array and pytorch tensor, the expected value range is between `[0, 1]` If it's a tensor or a list
768
+ or tensors, the expected shape should be `(B, C, H, W)` or `(C, H, W)`. If it is a numpy array or a
769
+ list of arrays, the expected shape should be `(B, H, W, C)` or `(H, W, C)` It can also accept image
770
+ latents as `image`, but if passing latents directly it is not encoded again.
771
+ prompt (`str` or `List[str]`, *optional*):
772
+ The prompt or prompts to guide the image generation. If not defined, one has to pass `prompt_embeds`.
773
+ instead.
774
+ prompt_2 (`str` or `List[str]`, *optional*):
775
+ The prompt or prompts to be sent to `tokenizer_2` and `text_encoder_2`. If not defined, `prompt` is
776
+ will be used instead.
777
+ negative_prompt (`str` or `List[str]`, *optional*):
778
+ The prompt or prompts not to guide the image generation. If not defined, one has to pass
779
+ `negative_prompt_embeds` instead. Ignored when not using guidance (i.e., ignored if `true_cfg_scale` is
780
+ not greater than `1`).
781
+ negative_prompt_2 (`str` or `List[str]`, *optional*):
782
+ The prompt or prompts not to guide the image generation to be sent to `tokenizer_2` and
783
+ `text_encoder_2`. If not defined, `negative_prompt` is used in all the text-encoders.
784
+ true_cfg_scale (`float`, *optional*, defaults to 1.0):
785
+ When > 1.0 and a provided `negative_prompt`, enables true classifier-free guidance.
786
+ height (`int`, *optional*, defaults to self.unet.config.sample_size * self.vae_scale_factor):
787
+ The height in pixels of the generated image. This is set to 1024 by default for the best results.
788
+ width (`int`, *optional*, defaults to self.unet.config.sample_size * self.vae_scale_factor):
789
+ The width in pixels of the generated image. This is set to 1024 by default for the best results.
790
+ num_inference_steps (`int`, *optional*, defaults to 50):
791
+ The number of denoising steps. More denoising steps usually lead to a higher quality image at the
792
+ expense of slower inference.
793
+ sigmas (`List[float]`, *optional*):
794
+ Custom sigmas to use for the denoising process with schedulers which support a `sigmas` argument in
795
+ their `set_timesteps` method. If not defined, the default behavior when `num_inference_steps` is passed
796
+ will be used.
797
+ guidance_scale (`float`, *optional*, defaults to 3.5):
798
+ Guidance scale as defined in [Classifier-Free Diffusion
799
+ Guidance](https://huggingface.co/papers/2207.12598). `guidance_scale` is defined as `w` of equation 2.
800
+ of [Imagen Paper](https://huggingface.co/papers/2205.11487). Guidance scale is enabled by setting
801
+ `guidance_scale > 1`. Higher guidance scale encourages to generate images that are closely linked to
802
+ the text `prompt`, usually at the expense of lower image quality.
803
+ num_images_per_prompt (`int`, *optional*, defaults to 1):
804
+ The number of images to generate per prompt.
805
+ generator (`torch.Generator` or `List[torch.Generator]`, *optional*):
806
+ One or a list of [torch generator(s)](https://pytorch.org/docs/stable/generated/torch.Generator.html)
807
+ to make generation deterministic.
808
+ latents (`torch.FloatTensor`, *optional*):
809
+ Pre-generated noisy latents, sampled from a Gaussian distribution, to be used as inputs for image
810
+ generation. Can be used to tweak the same generation with different prompts. If not provided, a latents
811
+ tensor will ge generated by sampling using the supplied random `generator`.
812
+ prompt_embeds (`torch.FloatTensor`, *optional*):
813
+ Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not
814
+ provided, text embeddings will be generated from `prompt` input argument.
815
+ pooled_prompt_embeds (`torch.FloatTensor`, *optional*):
816
+ Pre-generated pooled text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting.
817
+ If not provided, pooled text embeddings will be generated from `prompt` input argument.
818
+ ip_adapter_image: (`PipelineImageInput`, *optional*):
819
+ Optional image input to work with IP Adapters.
820
+ ip_adapter_image_embeds (`List[torch.Tensor]`, *optional*):
821
+ Pre-generated image embeddings for IP-Adapter. It should be a list of length same as number of
822
+ IP-adapters. Each element should be a tensor of shape `(batch_size, num_images, emb_dim)`. If not
823
+ provided, embeddings are computed from the `ip_adapter_image` input argument.
824
+ negative_ip_adapter_image:
825
+ (`PipelineImageInput`, *optional*): Optional image input to work with IP Adapters.
826
+ negative_ip_adapter_image_embeds (`List[torch.Tensor]`, *optional*):
827
+ Pre-generated image embeddings for IP-Adapter. It should be a list of length same as number of
828
+ IP-adapters. Each element should be a tensor of shape `(batch_size, num_images, emb_dim)`. If not
829
+ provided, embeddings are computed from the `ip_adapter_image` input argument.
830
+ negative_prompt_embeds (`torch.FloatTensor`, *optional*):
831
+ Pre-generated negative text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
832
+ weighting. If not provided, negative_prompt_embeds will be generated from `negative_prompt` input
833
+ argument.
834
+ negative_pooled_prompt_embeds (`torch.FloatTensor`, *optional*):
835
+ Pre-generated negative pooled text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
836
+ weighting. If not provided, pooled negative_prompt_embeds will be generated from `negative_prompt`
837
+ input argument.
838
+ output_type (`str`, *optional*, defaults to `"pil"`):
839
+ The output format of the generate image. Choose between
840
+ [PIL](https://pillow.readthedocs.io/en/stable/): `PIL.Image.Image` or `np.array`.
841
+ return_dict (`bool`, *optional*, defaults to `True`):
842
+ Whether or not to return a [`~pipelines.flux.FluxPipelineOutput`] instead of a plain tuple.
843
+ joint_attention_kwargs (`dict`, *optional*):
844
+ A kwargs dictionary that if specified is passed along to the `AttentionProcessor` as defined under
845
+ `self.processor` in
846
+ [diffusers.models.attention_processor](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py).
847
+ callback_on_step_end (`Callable`, *optional*):
848
+ A function that calls at the end of each denoising steps during the inference. The function is called
849
+ with the following arguments: `callback_on_step_end(self: DiffusionPipeline, step: int, timestep: int,
850
+ callback_kwargs: Dict)`. `callback_kwargs` will include a list of all tensors as specified by
851
+ `callback_on_step_end_tensor_inputs`.
852
+ callback_on_step_end_tensor_inputs (`List`, *optional*):
853
+ The list of tensor inputs for the `callback_on_step_end` function. The tensors specified in the list
854
+ will be passed as `callback_kwargs` argument. You will only be able to include variables listed in the
855
+ `._callback_tensor_inputs` attribute of your pipeline class.
856
+ max_sequence_length (`int` defaults to 512):
857
+ Maximum sequence length to use with the `prompt`.
858
+ max_area (`int`, defaults to `1024 ** 2`):
859
+ The maximum area of the generated image in pixels. The height and width will be adjusted to fit this
860
+ area while maintaining the aspect ratio.
861
+
862
+ Examples:
863
+
864
+ Returns:
865
+ [`~pipelines.flux.FluxPipelineOutput`] or `tuple`: [`~pipelines.flux.FluxPipelineOutput`] if `return_dict`
866
+ is True, otherwise a `tuple`. When returning a tuple, the first element is a list with the generated
867
+ images.
868
+ """
869
+
870
+ height = height or self.default_sample_size * self.vae_scale_factor
871
+ width = width or self.default_sample_size * self.vae_scale_factor
872
+
873
+ original_height, original_width = height, width
874
+ aspect_ratio = width / height
875
+ width = round((max_area * aspect_ratio) ** 0.5)
876
+ height = round((max_area / aspect_ratio) ** 0.5)
877
+
878
+ multiple_of = self.vae_scale_factor * 2
879
+ width = width // multiple_of * multiple_of
880
+ height = height // multiple_of * multiple_of
881
+
882
+ if height != original_height or width != original_width:
883
+ logger.warning(
884
+ f"Generation `height` and `width` have been adjusted to {height} and {width} to fit the model requirements."
885
+ )
886
+
887
+ # 1. Check inputs. Raise error if not correct
888
+ self.check_inputs(
889
+ prompt,
890
+ prompt_2,
891
+ height,
892
+ width,
893
+ negative_prompt=negative_prompt,
894
+ negative_prompt_2=negative_prompt_2,
895
+ prompt_embeds=prompt_embeds,
896
+ negative_prompt_embeds=negative_prompt_embeds,
897
+ pooled_prompt_embeds=pooled_prompt_embeds,
898
+ negative_pooled_prompt_embeds=negative_pooled_prompt_embeds,
899
+ callback_on_step_end_tensor_inputs=callback_on_step_end_tensor_inputs,
900
+ max_sequence_length=max_sequence_length,
901
+ )
902
+
903
+ self._guidance_scale = guidance_scale
904
+ self._joint_attention_kwargs = joint_attention_kwargs
905
+ self._current_timestep = None
906
+ self._interrupt = False
907
+
908
+ # 2. Define call parameters
909
+ if prompt is not None and isinstance(prompt, str):
910
+ batch_size = 1
911
+ elif prompt is not None and isinstance(prompt, list):
912
+ batch_size = len(prompt)
913
+ else:
914
+ batch_size = prompt_embeds.shape[0]
915
+
916
+ device = self._execution_device
917
+
918
+ lora_scale = (
919
+ self.joint_attention_kwargs.get("scale", None) if self.joint_attention_kwargs is not None else None
920
+ )
921
+ has_neg_prompt = negative_prompt is not None or (
922
+ negative_prompt_embeds is not None and negative_pooled_prompt_embeds is not None
923
+ )
924
+ do_true_cfg = true_cfg_scale > 1 and has_neg_prompt
925
+ (
926
+ prompt_embeds,
927
+ pooled_prompt_embeds,
928
+ text_ids,
929
+ ) = self.encode_prompt(
930
+ prompt=prompt,
931
+ prompt_2=prompt_2,
932
+ prompt_embeds=prompt_embeds,
933
+ pooled_prompt_embeds=pooled_prompt_embeds,
934
+ device=device,
935
+ num_images_per_prompt=num_images_per_prompt,
936
+ max_sequence_length=max_sequence_length,
937
+ lora_scale=lora_scale,
938
+ )
939
+ if do_true_cfg:
940
+ (
941
+ negative_prompt_embeds,
942
+ negative_pooled_prompt_embeds,
943
+ negative_text_ids,
944
+ ) = self.encode_prompt(
945
+ prompt=negative_prompt,
946
+ prompt_2=negative_prompt_2,
947
+ prompt_embeds=negative_prompt_embeds,
948
+ pooled_prompt_embeds=negative_pooled_prompt_embeds,
949
+ device=device,
950
+ num_images_per_prompt=num_images_per_prompt,
951
+ max_sequence_length=max_sequence_length,
952
+ lora_scale=lora_scale,
953
+ )
954
+
955
+ # 3. Preprocess image
956
+ if image is not None and not (isinstance(image, torch.Tensor) and image.size(1) == self.latent_channels):
957
+ img = image[0] if isinstance(image, list) else image
958
+ image_height, image_width = self.image_processor.get_default_height_width(img)
959
+ aspect_ratio = image_width / image_height
960
+ if _auto_resize:
961
+ # Kontext is trained on specific resolutions, using one of them is recommended
962
+ _, image_width, image_height = min(
963
+ (abs(aspect_ratio - w / h), w, h) for w, h in PREFERRED_KONTEXT_RESOLUTIONS
964
+ )
965
+ image_width = image_width // multiple_of * multiple_of
966
+ image_height = image_height // multiple_of * multiple_of
967
+ image = self.image_processor.resize(image, image_height, image_width)
968
+ image = self.image_processor.preprocess(image, image_height, image_width)
969
+
970
+ # 4. Prepare latent variables
971
+ num_channels_latents = self.transformer.config.in_channels // 4
972
+ latents, image_latents, latent_ids, image_ids = self.prepare_latents(
973
+ image,
974
+ batch_size * num_images_per_prompt,
975
+ num_channels_latents,
976
+ height,
977
+ width,
978
+ prompt_embeds.dtype,
979
+ device,
980
+ generator,
981
+ latents,
982
+ )
983
+ if image_ids is not None:
984
+ latent_ids = torch.cat([latent_ids, image_ids], dim=0) # dim 0 is sequence dimension
985
+
986
+ # 5. Prepare timesteps
987
+ sigmas = np.linspace(1.0, 1 / num_inference_steps, num_inference_steps) if sigmas is None else sigmas
988
+ image_seq_len = latents.shape[1]
989
+ mu = calculate_shift(
990
+ image_seq_len,
991
+ self.scheduler.config.get("base_image_seq_len", 256),
992
+ self.scheduler.config.get("max_image_seq_len", 4096),
993
+ self.scheduler.config.get("base_shift", 0.5),
994
+ self.scheduler.config.get("max_shift", 1.15),
995
+ )
996
+ timesteps, num_inference_steps = retrieve_timesteps(
997
+ self.scheduler,
998
+ num_inference_steps,
999
+ device,
1000
+ sigmas=sigmas,
1001
+ mu=mu,
1002
+ )
1003
+ num_warmup_steps = max(len(timesteps) - num_inference_steps * self.scheduler.order, 0)
1004
+ self._num_timesteps = len(timesteps)
1005
+
1006
+ # handle guidance
1007
+ if self.transformer.config.guidance_embeds:
1008
+ guidance = torch.full([1], guidance_scale, device=device, dtype=torch.float32)
1009
+ guidance = guidance.expand(latents.shape[0])
1010
+ else:
1011
+ guidance = None
1012
+
1013
+ if (ip_adapter_image is not None or ip_adapter_image_embeds is not None) and (
1014
+ negative_ip_adapter_image is None and negative_ip_adapter_image_embeds is None
1015
+ ):
1016
+ negative_ip_adapter_image = np.zeros((width, height, 3), dtype=np.uint8)
1017
+ negative_ip_adapter_image = [negative_ip_adapter_image] * self.transformer.encoder_hid_proj.num_ip_adapters
1018
+
1019
+ elif (ip_adapter_image is None and ip_adapter_image_embeds is None) and (
1020
+ negative_ip_adapter_image is not None or negative_ip_adapter_image_embeds is not None
1021
+ ):
1022
+ ip_adapter_image = np.zeros((width, height, 3), dtype=np.uint8)
1023
+ ip_adapter_image = [ip_adapter_image] * self.transformer.encoder_hid_proj.num_ip_adapters
1024
+
1025
+ if self.joint_attention_kwargs is None:
1026
+ self._joint_attention_kwargs = {}
1027
+
1028
+ image_embeds = None
1029
+ negative_image_embeds = None
1030
+ if ip_adapter_image is not None or ip_adapter_image_embeds is not None:
1031
+ image_embeds = self.prepare_ip_adapter_image_embeds(
1032
+ ip_adapter_image,
1033
+ ip_adapter_image_embeds,
1034
+ device,
1035
+ batch_size * num_images_per_prompt,
1036
+ )
1037
+ if negative_ip_adapter_image is not None or negative_ip_adapter_image_embeds is not None:
1038
+ negative_image_embeds = self.prepare_ip_adapter_image_embeds(
1039
+ negative_ip_adapter_image,
1040
+ negative_ip_adapter_image_embeds,
1041
+ device,
1042
+ batch_size * num_images_per_prompt,
1043
+ )
1044
+
1045
+ # 6. Denoising loop
1046
+ # We set the index here to remove DtoH sync, helpful especially during compilation.
1047
+ # Check out more details here: https://github.com/huggingface/diffusers/pull/11696
1048
+ self.scheduler.set_begin_index(0)
1049
+ with self.progress_bar(total=num_inference_steps) as progress_bar:
1050
+ for i, t in enumerate(timesteps):
1051
+ if self.interrupt:
1052
+ continue
1053
+
1054
+ self._current_timestep = t
1055
+ if image_embeds is not None:
1056
+ self._joint_attention_kwargs["ip_adapter_image_embeds"] = image_embeds
1057
+
1058
+ latent_model_input = latents
1059
+ if image_latents is not None:
1060
+ latent_model_input = torch.cat([latents, image_latents], dim=1)
1061
+ timestep = t.expand(latents.shape[0]).to(latents.dtype)
1062
+
1063
+ noise_pred = self.transformer(
1064
+ hidden_states=latent_model_input,
1065
+ timestep=timestep / 1000,
1066
+ guidance=guidance,
1067
+ pooled_projections=pooled_prompt_embeds,
1068
+ encoder_hidden_states=prompt_embeds,
1069
+ txt_ids=text_ids,
1070
+ img_ids=latent_ids,
1071
+ joint_attention_kwargs=self.joint_attention_kwargs,
1072
+ return_dict=False,
1073
+ )[0]
1074
+ noise_pred = noise_pred[:, : latents.size(1)]
1075
+
1076
+ if do_true_cfg:
1077
+ if negative_image_embeds is not None:
1078
+ self._joint_attention_kwargs["ip_adapter_image_embeds"] = negative_image_embeds
1079
+ neg_noise_pred = self.transformer(
1080
+ hidden_states=latent_model_input,
1081
+ timestep=timestep / 1000,
1082
+ guidance=guidance,
1083
+ pooled_projections=negative_pooled_prompt_embeds,
1084
+ encoder_hidden_states=negative_prompt_embeds,
1085
+ txt_ids=negative_text_ids,
1086
+ img_ids=latent_ids,
1087
+ joint_attention_kwargs=self.joint_attention_kwargs,
1088
+ return_dict=False,
1089
+ )[0]
1090
+ neg_noise_pred = neg_noise_pred[:, : latents.size(1)]
1091
+ noise_pred = neg_noise_pred + true_cfg_scale * (noise_pred - neg_noise_pred)
1092
+
1093
+ # compute the previous noisy sample x_t -> x_t-1
1094
+ latents_dtype = latents.dtype
1095
+ latents = self.scheduler.step(noise_pred, t, latents, return_dict=False)[0]
1096
+
1097
+ if latents.dtype != latents_dtype:
1098
+ if torch.backends.mps.is_available():
1099
+ # some platforms (eg. apple mps) misbehave due to a pytorch bug: https://github.com/pytorch/pytorch/pull/99272
1100
+ latents = latents.to(latents_dtype)
1101
+
1102
+ if callback_on_step_end is not None:
1103
+ callback_kwargs = {}
1104
+ for k in callback_on_step_end_tensor_inputs:
1105
+ callback_kwargs[k] = locals()[k]
1106
+ callback_outputs = callback_on_step_end(self, i, t, callback_kwargs)
1107
+
1108
+ latents = callback_outputs.pop("latents", latents)
1109
+ prompt_embeds = callback_outputs.pop("prompt_embeds", prompt_embeds)
1110
+
1111
+ # call the callback, if provided
1112
+ if i == len(timesteps) - 1 or ((i + 1) > num_warmup_steps and (i + 1) % self.scheduler.order == 0):
1113
+ progress_bar.update()
1114
+
1115
+ if XLA_AVAILABLE:
1116
+ xm.mark_step()
1117
+
1118
+ self._current_timestep = None
1119
+
1120
+ if output_type == "latent":
1121
+ image = latents
1122
+ else:
1123
+ latents = self._unpack_latents(latents, height, width, self.vae_scale_factor)
1124
+ latents = (latents / self.vae.config.scaling_factor) + self.vae.config.shift_factor
1125
+ image = self.vae.decode(latents, return_dict=False)[0]
1126
+ image = self.image_processor.postprocess(image, output_type=output_type)
1127
+
1128
+ # Offload all models
1129
+ self.maybe_free_model_hooks()
1130
+
1131
+ if not return_dict:
1132
+ return (image,)
1133
+
1134
+ return FluxPipelineOutput(images=image)
pipeline_flux_controlnet_inpaint.py ADDED
@@ -0,0 +1,1049 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import inspect
2
+ from typing import Any, Callable, Dict, List, Optional, Union
3
+
4
+ import numpy as np
5
+ import torch
6
+ from transformers 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
+ class FluxControlNetInpaintingPipeline(DiffusionPipeline, FluxLoraLoaderMixin):
153
+ r"""
154
+ The Flux pipeline for text-to-image generation.
155
+
156
+ Reference: https://blackforestlabs.ai/announcing-black-forest-labs/
157
+
158
+ Args:
159
+ transformer ([`FluxTransformer2DModel`]):
160
+ Conditional Transformer (MMDiT) architecture to denoise the encoded image latents.
161
+ scheduler ([`FlowMatchEulerDiscreteScheduler`]):
162
+ A scheduler to be used in combination with `transformer` to denoise the encoded image latents.
163
+ vae ([`AutoencoderKL`]):
164
+ Variational Auto-Encoder (VAE) Model to encode and decode images to and from latent representations.
165
+ text_encoder ([`CLIPTextModel`]):
166
+ [CLIP](https://huggingface.co/docs/transformers/model_doc/clip#transformers.CLIPTextModel), specifically
167
+ the [clip-vit-large-patch14](https://huggingface.co/openai/clip-vit-large-patch14) variant.
168
+ text_encoder_2 ([`T5EncoderModel`]):
169
+ [T5](https://huggingface.co/docs/transformers/en/model_doc/t5#transformers.T5EncoderModel), specifically
170
+ the [google/t5-v1_1-xxl](https://huggingface.co/google/t5-v1_1-xxl) variant.
171
+ tokenizer (`CLIPTokenizer`):
172
+ Tokenizer of class
173
+ [CLIPTokenizer](https://huggingface.co/docs/transformers/en/model_doc/clip#transformers.CLIPTokenizer).
174
+ tokenizer_2 (`T5TokenizerFast`):
175
+ Second Tokenizer of class
176
+ [T5TokenizerFast](https://huggingface.co/docs/transformers/en/model_doc/t5#transformers.T5TokenizerFast).
177
+ """
178
+
179
+ model_cpu_offload_seq = "text_encoder->text_encoder_2->transformer->vae"
180
+ _optional_components = []
181
+ _callback_tensor_inputs = ["latents", "prompt_embeds"]
182
+
183
+ def __init__(
184
+ self,
185
+ scheduler: FlowMatchEulerDiscreteScheduler,
186
+ vae: AutoencoderKL,
187
+ text_encoder: CLIPTextModel,
188
+ tokenizer: CLIPTokenizer,
189
+ text_encoder_2: T5EncoderModel,
190
+ tokenizer_2: T5TokenizerFast,
191
+ transformer: FluxTransformer2DModel,
192
+ controlnet: FluxControlNetModel,
193
+ ):
194
+ super().__init__()
195
+
196
+ self.register_modules(
197
+ vae=vae,
198
+ text_encoder=text_encoder,
199
+ text_encoder_2=text_encoder_2,
200
+ tokenizer=tokenizer,
201
+ tokenizer_2=tokenizer_2,
202
+ transformer=transformer,
203
+ scheduler=scheduler,
204
+ controlnet=controlnet,
205
+ )
206
+ self.vae_scale_factor = (
207
+ 2 ** (len(self.vae.config.block_out_channels))
208
+ if hasattr(self, "vae") and self.vae is not None
209
+ else 16
210
+ )
211
+ self.image_processor = VaeImageProcessor(vae_scale_factor=self.vae_scale_factor, do_resize=True, do_convert_rgb=True, do_normalize=True)
212
+ self.mask_processor = VaeImageProcessor(
213
+ vae_scale_factor=self.vae_scale_factor,
214
+ do_resize=True,
215
+ do_convert_grayscale=True,
216
+ do_normalize=False,
217
+ do_binarize=True,
218
+ )
219
+ self.tokenizer_max_length = (
220
+ self.tokenizer.model_max_length
221
+ if hasattr(self, "tokenizer") and self.tokenizer is not None
222
+ else 77
223
+ )
224
+ self.default_sample_size = 64
225
+
226
+ @property
227
+ def do_classifier_free_guidance(self):
228
+ return self._guidance_scale > 1
229
+
230
+ def _get_t5_prompt_embeds(
231
+ self,
232
+ prompt: Union[str, List[str]] = None,
233
+ num_images_per_prompt: int = 1,
234
+ max_sequence_length: int = 512,
235
+ device: Optional[torch.device] = None,
236
+ dtype: Optional[torch.dtype] = None,
237
+ ):
238
+ device = device or self._execution_device
239
+ dtype = dtype or self.text_encoder.dtype
240
+
241
+ prompt = [prompt] if isinstance(prompt, str) else prompt
242
+ batch_size = len(prompt)
243
+
244
+ text_inputs = self.tokenizer_2(
245
+ prompt,
246
+ padding="max_length",
247
+ max_length=max_sequence_length,
248
+ truncation=True,
249
+ return_length=False,
250
+ return_overflowing_tokens=False,
251
+ return_tensors="pt",
252
+ )
253
+ text_input_ids = text_inputs.input_ids
254
+ untruncated_ids = self.tokenizer_2(
255
+ prompt, padding="longest", return_tensors="pt"
256
+ ).input_ids
257
+
258
+ if untruncated_ids.shape[-1] >= text_input_ids.shape[-1] and not torch.equal(
259
+ text_input_ids, untruncated_ids
260
+ ):
261
+ removed_text = self.tokenizer_2.batch_decode(
262
+ untruncated_ids[:, self.tokenizer_max_length - 1 : -1]
263
+ )
264
+ logger.warning(
265
+ "The following part of your input was truncated because `max_sequence_length` is set to "
266
+ f" {max_sequence_length} tokens: {removed_text}"
267
+ )
268
+
269
+ prompt_embeds = self.text_encoder_2(
270
+ text_input_ids.to(device), output_hidden_states=False
271
+ )[0]
272
+
273
+ dtype = self.text_encoder_2.dtype
274
+ prompt_embeds = prompt_embeds.to(dtype=dtype, device=device)
275
+
276
+ _, seq_len, _ = prompt_embeds.shape
277
+
278
+ # duplicate text embeddings and attention mask for each generation per prompt, using mps friendly method
279
+ prompt_embeds = prompt_embeds.repeat(1, num_images_per_prompt, 1)
280
+ prompt_embeds = prompt_embeds.view(
281
+ batch_size * num_images_per_prompt, seq_len, -1
282
+ )
283
+
284
+ return prompt_embeds
285
+
286
+ def _get_clip_prompt_embeds(
287
+ self,
288
+ prompt: Union[str, List[str]],
289
+ num_images_per_prompt: int = 1,
290
+ device: Optional[torch.device] = None,
291
+ ):
292
+ device = device or self._execution_device
293
+
294
+ prompt = [prompt] if isinstance(prompt, str) else prompt
295
+ batch_size = len(prompt)
296
+
297
+ text_inputs = self.tokenizer(
298
+ prompt,
299
+ padding="max_length",
300
+ max_length=self.tokenizer_max_length,
301
+ truncation=True,
302
+ return_overflowing_tokens=False,
303
+ return_length=False,
304
+ return_tensors="pt",
305
+ )
306
+
307
+ text_input_ids = text_inputs.input_ids
308
+ untruncated_ids = self.tokenizer(
309
+ prompt, padding="longest", return_tensors="pt"
310
+ ).input_ids
311
+ if untruncated_ids.shape[-1] >= text_input_ids.shape[-1] and not torch.equal(
312
+ text_input_ids, untruncated_ids
313
+ ):
314
+ removed_text = self.tokenizer.batch_decode(
315
+ untruncated_ids[:, self.tokenizer_max_length - 1 : -1]
316
+ )
317
+ logger.warning(
318
+ "The following part of your input was truncated because CLIP can only handle sequences up to"
319
+ f" {self.tokenizer_max_length} tokens: {removed_text}"
320
+ )
321
+ prompt_embeds = self.text_encoder(
322
+ text_input_ids.to(device), output_hidden_states=False
323
+ )
324
+
325
+ # Use pooled output of CLIPTextModel
326
+ prompt_embeds = prompt_embeds.pooler_output
327
+ prompt_embeds = prompt_embeds.to(dtype=self.text_encoder.dtype, device=device)
328
+
329
+ # duplicate text embeddings for each generation per prompt, using mps friendly method
330
+ prompt_embeds = prompt_embeds.repeat(1, num_images_per_prompt, 1)
331
+ prompt_embeds = prompt_embeds.view(batch_size * num_images_per_prompt, -1)
332
+
333
+ return prompt_embeds
334
+
335
+ def encode_prompt(
336
+ self,
337
+ prompt: Union[str, List[str]],
338
+ prompt_2: Union[str, List[str]],
339
+ device: Optional[torch.device] = None,
340
+ num_images_per_prompt: int = 1,
341
+ do_classifier_free_guidance: bool = True,
342
+ negative_prompt: Optional[Union[str, List[str]]] = None,
343
+ negative_prompt_2: Optional[Union[str, List[str]]] = None,
344
+ prompt_embeds: Optional[torch.FloatTensor] = None,
345
+ pooled_prompt_embeds: Optional[torch.FloatTensor] = None,
346
+ max_sequence_length: int = 512,
347
+ lora_scale: Optional[float] = None,
348
+ ):
349
+ r"""
350
+
351
+ Args:
352
+ prompt (`str` or `List[str]`, *optional*):
353
+ prompt to be encoded
354
+ prompt_2 (`str` or `List[str]`, *optional*):
355
+ The prompt or prompts to be sent to the `tokenizer_2` and `text_encoder_2`. If not defined, `prompt` is
356
+ used in all text-encoders
357
+ device: (`torch.device`):
358
+ torch device
359
+ num_images_per_prompt (`int`):
360
+ number of images that should be generated per prompt
361
+ do_classifier_free_guidance (`bool`):
362
+ whether to use classifier-free guidance or not
363
+ negative_prompt (`str` or `List[str]`, *optional*):
364
+ negative prompt to be encoded
365
+ negative_prompt_2 (`str` or `List[str]`, *optional*):
366
+ negative prompt to be sent to the `tokenizer_2` and `text_encoder_2`. If not defined, `negative_prompt` is
367
+ used in all text-encoders
368
+ prompt_embeds (`torch.FloatTensor`, *optional*):
369
+ Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not
370
+ provided, text embeddings will be generated from `prompt` input argument.
371
+ pooled_prompt_embeds (`torch.FloatTensor`, *optional*):
372
+ Pre-generated pooled text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting.
373
+ If not provided, pooled text embeddings will be generated from `prompt` input argument.
374
+ clip_skip (`int`, *optional*):
375
+ Number of layers to be skipped from CLIP while computing the prompt embeddings. A value of 1 means that
376
+ the output of the pre-final layer will be used for computing the prompt embeddings.
377
+ lora_scale (`float`, *optional*):
378
+ A lora scale that will be applied to all LoRA layers of the text encoder if LoRA layers are loaded.
379
+ """
380
+ device = device or self._execution_device
381
+
382
+ # set lora scale so that monkey patched LoRA
383
+ # function of text encoder can correctly access it
384
+ if lora_scale is not None and isinstance(self, FluxLoraLoaderMixin):
385
+ self._lora_scale = lora_scale
386
+
387
+ # dynamically adjust the LoRA scale
388
+ if self.text_encoder is not None and USE_PEFT_BACKEND:
389
+ scale_lora_layers(self.text_encoder, lora_scale)
390
+ if self.text_encoder_2 is not None and USE_PEFT_BACKEND:
391
+ scale_lora_layers(self.text_encoder_2, lora_scale)
392
+
393
+ prompt = [prompt] if isinstance(prompt, str) else prompt
394
+ if prompt is not None:
395
+ batch_size = len(prompt)
396
+ else:
397
+ batch_size = prompt_embeds.shape[0]
398
+
399
+ if prompt_embeds is None:
400
+ prompt_2 = prompt_2 or prompt
401
+ prompt_2 = [prompt_2] if isinstance(prompt_2, str) else prompt_2
402
+
403
+ # We only use the pooled prompt output from the CLIPTextModel
404
+ pooled_prompt_embeds = self._get_clip_prompt_embeds(
405
+ prompt=prompt,
406
+ device=device,
407
+ num_images_per_prompt=num_images_per_prompt,
408
+ )
409
+ prompt_embeds = self._get_t5_prompt_embeds(
410
+ prompt=prompt_2,
411
+ num_images_per_prompt=num_images_per_prompt,
412
+ max_sequence_length=max_sequence_length,
413
+ device=device,
414
+ )
415
+
416
+ if do_classifier_free_guidance:
417
+ # 处理 negative prompt
418
+ negative_prompt = negative_prompt or ""
419
+ negative_prompt_2 = negative_prompt_2 or negative_prompt
420
+
421
+ negative_pooled_prompt_embeds = self._get_clip_prompt_embeds(
422
+ negative_prompt,
423
+ device=device,
424
+ num_images_per_prompt=num_images_per_prompt,
425
+ )
426
+ negative_prompt_embeds = self._get_t5_prompt_embeds(
427
+ negative_prompt_2,
428
+ num_images_per_prompt=num_images_per_prompt,
429
+ max_sequence_length=max_sequence_length,
430
+ device=device,
431
+ )
432
+ else:
433
+ negative_pooled_prompt_embeds = None
434
+ negative_prompt_embeds = None
435
+
436
+ if self.text_encoder is not None:
437
+ if isinstance(self, FluxLoraLoaderMixin) and USE_PEFT_BACKEND:
438
+ # Retrieve the original scale by scaling back the LoRA layers
439
+ unscale_lora_layers(self.text_encoder, lora_scale)
440
+
441
+ if self.text_encoder_2 is not None:
442
+ if isinstance(self, FluxLoraLoaderMixin) and USE_PEFT_BACKEND:
443
+ # Retrieve the original scale by scaling back the LoRA layers
444
+ unscale_lora_layers(self.text_encoder_2, lora_scale)
445
+
446
+ text_ids = torch.zeros(batch_size, prompt_embeds.shape[1], 3).to(
447
+ device=device, dtype=self.text_encoder.dtype
448
+ )
449
+
450
+ return prompt_embeds, pooled_prompt_embeds, negative_prompt_embeds, negative_pooled_prompt_embeds,text_ids
451
+
452
+ def check_inputs(
453
+ self,
454
+ prompt,
455
+ prompt_2,
456
+ height,
457
+ width,
458
+ prompt_embeds=None,
459
+ pooled_prompt_embeds=None,
460
+ callback_on_step_end_tensor_inputs=None,
461
+ max_sequence_length=None,
462
+ ):
463
+ if height % 8 != 0 or width % 8 != 0:
464
+ raise ValueError(
465
+ f"`height` and `width` have to be divisible by 8 but are {height} and {width}."
466
+ )
467
+
468
+ if callback_on_step_end_tensor_inputs is not None and not all(
469
+ k in self._callback_tensor_inputs
470
+ for k in callback_on_step_end_tensor_inputs
471
+ ):
472
+ raise ValueError(
473
+ 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]}"
474
+ )
475
+
476
+ if prompt is not None and prompt_embeds is not None:
477
+ raise ValueError(
478
+ f"Cannot forward both `prompt`: {prompt} and `prompt_embeds`: {prompt_embeds}. Please make sure to"
479
+ " only forward one of the two."
480
+ )
481
+ elif prompt_2 is not None and prompt_embeds is not None:
482
+ raise ValueError(
483
+ f"Cannot forward both `prompt_2`: {prompt_2} and `prompt_embeds`: {prompt_embeds}. Please make sure to"
484
+ " only forward one of the two."
485
+ )
486
+ elif prompt is None and prompt_embeds is None:
487
+ raise ValueError(
488
+ "Provide either `prompt` or `prompt_embeds`. Cannot leave both `prompt` and `prompt_embeds` undefined."
489
+ )
490
+ elif prompt is not None and (
491
+ not isinstance(prompt, str) and not isinstance(prompt, list)
492
+ ):
493
+ raise ValueError(
494
+ f"`prompt` has to be of type `str` or `list` but is {type(prompt)}"
495
+ )
496
+ elif prompt_2 is not None and (
497
+ not isinstance(prompt_2, str) and not isinstance(prompt_2, list)
498
+ ):
499
+ raise ValueError(
500
+ f"`prompt_2` has to be of type `str` or `list` but is {type(prompt_2)}"
501
+ )
502
+
503
+ if prompt_embeds is not None and pooled_prompt_embeds is None:
504
+ raise ValueError(
505
+ "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`."
506
+ )
507
+
508
+ if max_sequence_length is not None and max_sequence_length > 512:
509
+ raise ValueError(
510
+ f"`max_sequence_length` cannot be greater than 512 but is {max_sequence_length}"
511
+ )
512
+
513
+ # Copied from diffusers.pipelines.flux.pipeline_flux._prepare_latent_image_ids
514
+ @staticmethod
515
+ def _prepare_latent_image_ids(batch_size, height, width, device, dtype):
516
+ latent_image_ids = torch.zeros(height // 2, width // 2, 3)
517
+ latent_image_ids[..., 1] = (
518
+ latent_image_ids[..., 1] + torch.arange(height // 2)[:, None]
519
+ )
520
+ latent_image_ids[..., 2] = (
521
+ latent_image_ids[..., 2] + torch.arange(width // 2)[None, :]
522
+ )
523
+
524
+ (
525
+ latent_image_id_height,
526
+ latent_image_id_width,
527
+ latent_image_id_channels,
528
+ ) = latent_image_ids.shape
529
+
530
+ latent_image_ids = latent_image_ids[None, :].repeat(batch_size, 1, 1, 1)
531
+ latent_image_ids = latent_image_ids.reshape(
532
+ batch_size,
533
+ latent_image_id_height * latent_image_id_width,
534
+ latent_image_id_channels,
535
+ )
536
+
537
+ return latent_image_ids.to(device=device, dtype=dtype)
538
+
539
+ # Copied from diffusers.pipelines.flux.pipeline_flux._pack_latents
540
+ @staticmethod
541
+ def _pack_latents(latents, batch_size, num_channels_latents, height, width):
542
+ latents = latents.view(
543
+ batch_size, num_channels_latents, height // 2, 2, width // 2, 2
544
+ )
545
+ latents = latents.permute(0, 2, 4, 1, 3, 5)
546
+ latents = latents.reshape(
547
+ batch_size, (height // 2) * (width // 2), num_channels_latents * 4
548
+ )
549
+
550
+ return latents
551
+
552
+ # Copied from diffusers.pipelines.flux.pipeline_flux._unpack_latents
553
+ @staticmethod
554
+ def _unpack_latents(latents, height, width, vae_scale_factor):
555
+ batch_size, num_patches, channels = latents.shape
556
+
557
+ height = height // vae_scale_factor
558
+ width = width // vae_scale_factor
559
+
560
+ latents = latents.view(batch_size, height, width, channels // 4, 2, 2)
561
+ latents = latents.permute(0, 3, 1, 4, 2, 5)
562
+
563
+ latents = latents.reshape(
564
+ batch_size, channels // (2 * 2), height * 2, width * 2
565
+ )
566
+
567
+ return latents
568
+
569
+ # Copied from diffusers.pipelines.flux.pipeline_flux.prepare_latents
570
+ def prepare_latents(
571
+ self,
572
+ batch_size,
573
+ num_channels_latents,
574
+ height,
575
+ width,
576
+ dtype,
577
+ device,
578
+ generator,
579
+ latents=None,
580
+ ):
581
+ height = 2 * (int(height) // self.vae_scale_factor)
582
+ width = 2 * (int(width) // self.vae_scale_factor)
583
+
584
+ shape = (batch_size, num_channels_latents, height, width)
585
+
586
+ if latents is not None:
587
+ latent_image_ids = self._prepare_latent_image_ids(
588
+ batch_size, height, width, device, dtype
589
+ )
590
+ return latents.to(device=device, dtype=dtype), latent_image_ids
591
+
592
+ if isinstance(generator, list) and len(generator) != batch_size:
593
+ raise ValueError(
594
+ f"You have passed a list of generators of length {len(generator)}, but requested an effective batch"
595
+ f" size of {batch_size}. Make sure the batch size matches the length of the generators."
596
+ )
597
+
598
+ latents = randn_tensor(shape, generator=generator, device=device, dtype=dtype)
599
+ latents = self._pack_latents(
600
+ latents, batch_size, num_channels_latents, height, width
601
+ )
602
+
603
+ latent_image_ids = self._prepare_latent_image_ids(
604
+ batch_size, height, width, device, dtype
605
+ )
606
+
607
+ return latents, latent_image_ids
608
+
609
+ # Copied from diffusers.pipelines.controlnet.pipeline_controlnet.StableDiffusionControlNetPipeline.prepare_image
610
+ def prepare_image(
611
+ self,
612
+ image,
613
+ width,
614
+ height,
615
+ batch_size,
616
+ num_images_per_prompt,
617
+ device,
618
+ dtype,
619
+ ):
620
+ if isinstance(image, torch.Tensor):
621
+ pass
622
+ else:
623
+ image = self.image_processor.preprocess(image, height=height, width=width)
624
+
625
+ image_batch_size = image.shape[0]
626
+
627
+ if image_batch_size == 1:
628
+ repeat_by = batch_size
629
+ else:
630
+ # image batch size is the same as prompt batch size
631
+ repeat_by = num_images_per_prompt
632
+
633
+ image = image.repeat_interleave(repeat_by, dim=0)
634
+
635
+ image = image.to(device=device, dtype=dtype)
636
+
637
+ return image
638
+
639
+ def prepare_image_with_mask(
640
+ self,
641
+ image,
642
+ mask,
643
+ width,
644
+ height,
645
+ batch_size,
646
+ num_images_per_prompt,
647
+ device,
648
+ dtype,
649
+ do_classifier_free_guidance = False,
650
+ ):
651
+ # Prepare image
652
+ if isinstance(image, torch.Tensor):
653
+ pass
654
+ else:
655
+ image = self.image_processor.preprocess(image, height=height, width=width)
656
+
657
+ image_batch_size = image.shape[0]
658
+ if image_batch_size == 1:
659
+ repeat_by = batch_size
660
+ else:
661
+ # image batch size is the same as prompt batch size
662
+ repeat_by = num_images_per_prompt
663
+ image = image.repeat_interleave(repeat_by, dim=0)
664
+ image = image.to(device=device, dtype=dtype)
665
+
666
+ # Prepare mask
667
+ if isinstance(mask, torch.Tensor):
668
+ pass
669
+ else:
670
+ mask = self.mask_processor.preprocess(mask, height=height, width=width)
671
+ mask = mask.repeat_interleave(repeat_by, dim=0)
672
+ mask = mask.to(device=device, dtype=dtype)
673
+
674
+ # Get masked image
675
+ masked_image = image.clone()
676
+ masked_image[(mask > 0.5).repeat(1, 3, 1, 1)] = -1
677
+
678
+ # Encode to latents
679
+ image_latents = self.vae.encode(masked_image.to(self.vae.dtype)).latent_dist.sample()
680
+ image_latents = (
681
+ image_latents - self.vae.config.shift_factor
682
+ ) * self.vae.config.scaling_factor
683
+ image_latents = image_latents.to(dtype)
684
+
685
+ mask = torch.nn.functional.interpolate(
686
+ mask, size=(height // self.vae_scale_factor * 2, width // self.vae_scale_factor * 2)
687
+ )
688
+ mask = 1 - mask
689
+
690
+ control_image = torch.cat([image_latents, mask], dim=1)
691
+
692
+ # Pack cond latents
693
+ packed_control_image = self._pack_latents(
694
+ control_image,
695
+ batch_size * num_images_per_prompt,
696
+ control_image.shape[1],
697
+ control_image.shape[2],
698
+ control_image.shape[3],
699
+ )
700
+
701
+ if do_classifier_free_guidance:
702
+ packed_control_image = torch.cat([packed_control_image] * 2)
703
+
704
+ return packed_control_image, height, width
705
+
706
+ @property
707
+ def guidance_scale(self):
708
+ return self._guidance_scale
709
+
710
+ @property
711
+ def joint_attention_kwargs(self):
712
+ return self._joint_attention_kwargs
713
+
714
+ @property
715
+ def num_timesteps(self):
716
+ return self._num_timesteps
717
+
718
+ @property
719
+ def interrupt(self):
720
+ return self._interrupt
721
+
722
+ @torch.no_grad()
723
+ @replace_example_docstring(EXAMPLE_DOC_STRING)
724
+ def __call__(
725
+ self,
726
+ prompt: Union[str, List[str]] = None,
727
+ prompt_2: Optional[Union[str, List[str]]] = None,
728
+ height: Optional[int] = None,
729
+ width: Optional[int] = None,
730
+ num_inference_steps: int = 28,
731
+ timesteps: List[int] = None,
732
+ guidance_scale: float = 7.0,
733
+ true_guidance_scale: float = 3.5 ,
734
+ negative_prompt: Optional[Union[str, List[str]]] = None,
735
+ negative_prompt_2: Optional[Union[str, List[str]]] = None,
736
+ control_image: PipelineImageInput = None,
737
+ control_mask: PipelineImageInput = None,
738
+ controlnet_conditioning_scale: Union[float, List[float]] = 1.0,
739
+ num_images_per_prompt: Optional[int] = 1,
740
+ generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
741
+ latents: Optional[torch.FloatTensor] = None,
742
+ prompt_embeds: Optional[torch.FloatTensor] = None,
743
+ pooled_prompt_embeds: Optional[torch.FloatTensor] = None,
744
+ output_type: Optional[str] = "pil",
745
+ return_dict: bool = True,
746
+ joint_attention_kwargs: Optional[Dict[str, Any]] = None,
747
+ callback_on_step_end: Optional[Callable[[int, int, Dict], None]] = None,
748
+ callback_on_step_end_tensor_inputs: List[str] = ["latents"],
749
+ max_sequence_length: int = 512,
750
+ ):
751
+ r"""
752
+ Function invoked when calling the pipeline for generation.
753
+
754
+ Args:
755
+ prompt (`str` or `List[str]`, *optional*):
756
+ The prompt or prompts to guide the image generation. If not defined, one has to pass `prompt_embeds`.
757
+ instead.
758
+ prompt_2 (`str` or `List[str]`, *optional*):
759
+ The prompt or prompts to be sent to `tokenizer_2` and `text_encoder_2`. If not defined, `prompt` is
760
+ will be used instead
761
+ height (`int`, *optional*, defaults to self.unet.config.sample_size * self.vae_scale_factor):
762
+ The height in pixels of the generated image. This is set to 1024 by default for the best results.
763
+ width (`int`, *optional*, defaults to self.unet.config.sample_size * self.vae_scale_factor):
764
+ The width in pixels of the generated image. This is set to 1024 by default for the best results.
765
+ num_inference_steps (`int`, *optional*, defaults to 50):
766
+ The number of denoising steps. More denoising steps usually lead to a higher quality image at the
767
+ expense of slower inference.
768
+ timesteps (`List[int]`, *optional*):
769
+ Custom timesteps to use for the denoising process with schedulers which support a `timesteps` argument
770
+ in their `set_timesteps` method. If not defined, the default behavior when `num_inference_steps` is
771
+ passed will be used. Must be in descending order.
772
+ guidance_scale (`float`, *optional*, defaults to 7.0):
773
+ Guidance scale as defined in [Classifier-Free Diffusion Guidance](https://arxiv.org/abs/2207.12598).
774
+ `guidance_scale` is defined as `w` of equation 2. of [Imagen
775
+ Paper](https://arxiv.org/pdf/2205.11487.pdf). Guidance scale is enabled by setting `guidance_scale >
776
+ 1`. Higher guidance scale encourages to generate images that are closely linked to the text `prompt`,
777
+ usually at the expense of lower image quality.
778
+ num_images_per_prompt (`int`, *optional*, defaults to 1):
779
+ The number of images to generate per prompt.
780
+ generator (`torch.Generator` or `List[torch.Generator]`, *optional*):
781
+ One or a list of [torch generator(s)](https://pytorch.org/docs/stable/generated/torch.Generator.html)
782
+ to make generation deterministic.
783
+ latents (`torch.FloatTensor`, *optional*):
784
+ Pre-generated noisy latents, sampled from a Gaussian distribution, to be used as inputs for image
785
+ generation. Can be used to tweak the same generation with different prompts. If not provided, a latents
786
+ tensor will ge generated by sampling using the supplied random `generator`.
787
+ prompt_embeds (`torch.FloatTensor`, *optional*):
788
+ Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not
789
+ provided, text embeddings will be generated from `prompt` input argument.
790
+ pooled_prompt_embeds (`torch.FloatTensor`, *optional*):
791
+ Pre-generated pooled text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting.
792
+ If not provided, pooled text embeddings will be generated from `prompt` input argument.
793
+ output_type (`str`, *optional*, defaults to `"pil"`):
794
+ The output format of the generate image. Choose between
795
+ [PIL](https://pillow.readthedocs.io/en/stable/): `PIL.Image.Image` or `np.array`.
796
+ return_dict (`bool`, *optional*, defaults to `True`):
797
+ Whether or not to return a [`~pipelines.flux.FluxPipelineOutput`] instead of a plain tuple.
798
+ joint_attention_kwargs (`dict`, *optional*):
799
+ A kwargs dictionary that if specified is passed along to the `AttentionProcessor` as defined under
800
+ `self.processor` in
801
+ [diffusers.models.attention_processor](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py).
802
+ callback_on_step_end (`Callable`, *optional*):
803
+ A function that calls at the end of each denoising steps during the inference. The function is called
804
+ with the following arguments: `callback_on_step_end(self: DiffusionPipeline, step: int, timestep: int,
805
+ callback_kwargs: Dict)`. `callback_kwargs` will include a list of all tensors as specified by
806
+ `callback_on_step_end_tensor_inputs`.
807
+ callback_on_step_end_tensor_inputs (`List`, *optional*):
808
+ The list of tensor inputs for the `callback_on_step_end` function. The tensors specified in the list
809
+ will be passed as `callback_kwargs` argument. You will only be able to include variables listed in the
810
+ `._callback_tensor_inputs` attribute of your pipeline class.
811
+ max_sequence_length (`int` defaults to 512): Maximum sequence length to use with the `prompt`.
812
+
813
+ Examples:
814
+
815
+ Returns:
816
+ [`~pipelines.flux.FluxPipelineOutput`] or `tuple`: [`~pipelines.flux.FluxPipelineOutput`] if `return_dict`
817
+ is True, otherwise a `tuple`. When returning a tuple, the first element is a list with the generated
818
+ images.
819
+ """
820
+
821
+ height = height or self.default_sample_size * self.vae_scale_factor
822
+ width = width or self.default_sample_size * self.vae_scale_factor
823
+
824
+ # 1. Check inputs. Raise error if not correct
825
+ self.check_inputs(
826
+ prompt,
827
+ prompt_2,
828
+ height,
829
+ width,
830
+ prompt_embeds=prompt_embeds,
831
+ pooled_prompt_embeds=pooled_prompt_embeds,
832
+ callback_on_step_end_tensor_inputs=callback_on_step_end_tensor_inputs,
833
+ max_sequence_length=max_sequence_length,
834
+ )
835
+
836
+ self._guidance_scale = true_guidance_scale
837
+ self._joint_attention_kwargs = joint_attention_kwargs
838
+ self._interrupt = False
839
+
840
+ # 2. Define call parameters
841
+ if prompt is not None and isinstance(prompt, str):
842
+ batch_size = 1
843
+ elif prompt is not None and isinstance(prompt, list):
844
+ batch_size = len(prompt)
845
+ else:
846
+ batch_size = prompt_embeds.shape[0]
847
+
848
+ device = self._execution_device
849
+ dtype = self.transformer.dtype
850
+
851
+ lora_scale = (
852
+ self.joint_attention_kwargs.get("scale", None)
853
+ if self.joint_attention_kwargs is not None
854
+ else None
855
+ )
856
+ (
857
+ prompt_embeds,
858
+ pooled_prompt_embeds,
859
+ negative_prompt_embeds,
860
+ negative_pooled_prompt_embeds,
861
+ text_ids
862
+ ) = self.encode_prompt(
863
+ prompt=prompt,
864
+ prompt_2=prompt_2,
865
+ prompt_embeds=prompt_embeds,
866
+ pooled_prompt_embeds=pooled_prompt_embeds,
867
+ do_classifier_free_guidance = self.do_classifier_free_guidance,
868
+ negative_prompt = negative_prompt,
869
+ negative_prompt_2 = negative_prompt_2,
870
+ device=device,
871
+ num_images_per_prompt=num_images_per_prompt,
872
+ max_sequence_length=max_sequence_length,
873
+ lora_scale=lora_scale,
874
+ )
875
+
876
+ # 在 encode_prompt 之后
877
+ if self.do_classifier_free_guidance:
878
+ prompt_embeds = torch.cat([negative_prompt_embeds, prompt_embeds], dim = 0)
879
+ pooled_prompt_embeds = torch.cat([negative_pooled_prompt_embeds, pooled_prompt_embeds], dim = 0)
880
+ text_ids = torch.cat([text_ids, text_ids], dim = 0)
881
+
882
+ # 3. Prepare control image
883
+ num_channels_latents = self.transformer.config.in_channels // 4
884
+ if isinstance(self.controlnet, FluxControlNetModel):
885
+ control_image, height, width = self.prepare_image_with_mask(
886
+ image=control_image,
887
+ mask=control_mask,
888
+ width=width,
889
+ height=height,
890
+ batch_size=batch_size * num_images_per_prompt,
891
+ num_images_per_prompt=num_images_per_prompt,
892
+ device=device,
893
+ dtype=dtype,
894
+ do_classifier_free_guidance=self.do_classifier_free_guidance,
895
+ )
896
+
897
+ # 4. Prepare latent variables
898
+ num_channels_latents = self.transformer.config.in_channels // 4
899
+ latents, latent_image_ids = self.prepare_latents(
900
+ batch_size * num_images_per_prompt,
901
+ num_channels_latents,
902
+ height,
903
+ width,
904
+ prompt_embeds.dtype,
905
+ device,
906
+ generator,
907
+ latents,
908
+ )
909
+
910
+ if self.do_classifier_free_guidance:
911
+ latent_image_ids = torch.cat([latent_image_ids] * 2)
912
+
913
+ # 5. Prepare timesteps
914
+ sigmas = np.linspace(1.0, 1 / num_inference_steps, num_inference_steps)
915
+ image_seq_len = latents.shape[1]
916
+ mu = calculate_shift(
917
+ image_seq_len,
918
+ self.scheduler.config.base_image_seq_len,
919
+ self.scheduler.config.max_image_seq_len,
920
+ self.scheduler.config.base_shift,
921
+ self.scheduler.config.max_shift,
922
+ )
923
+ timesteps, num_inference_steps = retrieve_timesteps(
924
+ self.scheduler,
925
+ num_inference_steps,
926
+ device,
927
+ timesteps,
928
+ sigmas,
929
+ mu=mu,
930
+ )
931
+
932
+ num_warmup_steps = max(
933
+ len(timesteps) - num_inference_steps * self.scheduler.order, 0
934
+ )
935
+ self._num_timesteps = len(timesteps)
936
+
937
+ # 6. Denoising loop
938
+ with self.progress_bar(total=num_inference_steps) as progress_bar:
939
+ for i, t in enumerate(timesteps):
940
+ if self.interrupt:
941
+ continue
942
+
943
+ latent_model_input = torch.cat([latents] * 2) if self.do_classifier_free_guidance else latents
944
+
945
+ # broadcast to batch dimension in a way that's compatible with ONNX/Core ML
946
+ timestep = t.expand(latent_model_input.shape[0]).to(latent_model_input.dtype)
947
+
948
+ # handle guidance
949
+ if self.transformer.config.guidance_embeds:
950
+ guidance = torch.tensor([guidance_scale], device=device)
951
+ guidance = guidance.expand(latent_model_input.shape[0])
952
+ else:
953
+ guidance = None
954
+
955
+ # controlnet
956
+ (
957
+ controlnet_block_samples,
958
+ controlnet_single_block_samples,
959
+ ) = self.controlnet(
960
+ hidden_states=latent_model_input,
961
+ controlnet_cond=control_image,
962
+ conditioning_scale=controlnet_conditioning_scale,
963
+ timestep=timestep / 1000,
964
+ guidance=guidance,
965
+ pooled_projections=pooled_prompt_embeds,
966
+ encoder_hidden_states=prompt_embeds,
967
+ txt_ids=text_ids,
968
+ img_ids=latent_image_ids,
969
+ joint_attention_kwargs=self.joint_attention_kwargs,
970
+ return_dict=False,
971
+ )
972
+
973
+ noise_pred = self.transformer(
974
+ hidden_states=latent_model_input,
975
+ # YiYi notes: divide it by 1000 for now because we scale it by 1000 in the transforme rmodel (we should not keep it but I want to keep the inputs same for the model for testing)
976
+ timestep=timestep / 1000,
977
+ guidance=guidance,
978
+ pooled_projections=pooled_prompt_embeds,
979
+ encoder_hidden_states=prompt_embeds,
980
+ controlnet_block_samples=[
981
+ sample.to(dtype=self.transformer.dtype)
982
+ for sample in controlnet_block_samples
983
+ ],
984
+ controlnet_single_block_samples=[
985
+ sample.to(dtype=self.transformer.dtype)
986
+ for sample in controlnet_single_block_samples
987
+ ] if controlnet_single_block_samples is not None else controlnet_single_block_samples,
988
+ txt_ids=text_ids,
989
+ img_ids=latent_image_ids,
990
+ joint_attention_kwargs=self.joint_attention_kwargs,
991
+ return_dict=False,
992
+ )[0]
993
+
994
+ # 在生成循环中
995
+ if self.do_classifier_free_guidance:
996
+ noise_pred_uncond, noise_pred_text = noise_pred.chunk(2)
997
+ noise_pred = noise_pred_uncond + true_guidance_scale * (noise_pred_text - noise_pred_uncond)
998
+
999
+ # compute the previous noisy sample x_t -> x_t-1
1000
+ latents_dtype = latents.dtype
1001
+ latents = self.scheduler.step(
1002
+ noise_pred, t, latents, return_dict=False
1003
+ )[0]
1004
+
1005
+ if latents.dtype != latents_dtype:
1006
+ if torch.backends.mps.is_available():
1007
+ # some platforms (eg. apple mps) misbehave due to a pytorch bug: https://github.com/pytorch/pytorch/pull/99272
1008
+ latents = latents.to(latents_dtype)
1009
+
1010
+ if callback_on_step_end is not None:
1011
+ callback_kwargs = {}
1012
+ for k in callback_on_step_end_tensor_inputs:
1013
+ callback_kwargs[k] = locals()[k]
1014
+ callback_outputs = callback_on_step_end(self, i, t, callback_kwargs)
1015
+
1016
+ latents = callback_outputs.pop("latents", latents)
1017
+ prompt_embeds = callback_outputs.pop("prompt_embeds", prompt_embeds)
1018
+
1019
+ # call the callback, if provided
1020
+ if i == len(timesteps) - 1 or (
1021
+ (i + 1) > num_warmup_steps and (i + 1) % self.scheduler.order == 0
1022
+ ):
1023
+ progress_bar.update()
1024
+
1025
+ if XLA_AVAILABLE:
1026
+ xm.mark_step()
1027
+
1028
+ if output_type == "latent":
1029
+ image = latents
1030
+
1031
+ else:
1032
+ latents = self._unpack_latents(
1033
+ latents, height, width, self.vae_scale_factor
1034
+ )
1035
+ latents = (
1036
+ latents / self.vae.config.scaling_factor
1037
+ ) + self.vae.config.shift_factor
1038
+ latents = latents.to(self.vae.dtype)
1039
+
1040
+ image = self.vae.decode(latents, return_dict=False)[0]
1041
+ image = self.image_processor.postprocess(image, output_type=output_type)
1042
+
1043
+ # Offload all models
1044
+ self.maybe_free_model_hooks()
1045
+
1046
+ if not return_dict:
1047
+ return (image,)
1048
+
1049
+ return FluxPipelineOutput(images=image)
pipeline_flux_kontext.py ADDED
@@ -0,0 +1,1117 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2025 Black Forest Labs and The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ import inspect
16
+ from typing import Any, Callable, Dict, List, Optional, Union
17
+
18
+ import numpy as np
19
+ import torch
20
+ from transformers import (
21
+ CLIPImageProcessor,
22
+ CLIPTextModel,
23
+ CLIPTokenizer,
24
+ CLIPVisionModelWithProjection,
25
+ T5EncoderModel,
26
+ T5TokenizerFast,
27
+ )
28
+
29
+ from diffusers.image_processor import PipelineImageInput, VaeImageProcessor
30
+ from diffusers.loaders import FluxIPAdapterMixin, FluxLoraLoaderMixin, FromSingleFileMixin, TextualInversionLoaderMixin
31
+ from diffusers.models import AutoencoderKL, FluxTransformer2DModel
32
+ from diffusers.schedulers import FlowMatchEulerDiscreteScheduler
33
+ from diffusers.utils import (
34
+ USE_PEFT_BACKEND,
35
+ is_torch_xla_available,
36
+ logging,
37
+ replace_example_docstring,
38
+ scale_lora_layers,
39
+ unscale_lora_layers,
40
+ )
41
+ from diffusers.utils.torch_utils import randn_tensor
42
+ from diffusers.pipelines.pipeline_utils import DiffusionPipeline
43
+ from diffusers.pipelines.flux.pipeline_output import FluxPipelineOutput
44
+
45
+
46
+ if is_torch_xla_available():
47
+ import torch_xla.core.xla_model as xm
48
+
49
+ XLA_AVAILABLE = True
50
+ else:
51
+ XLA_AVAILABLE = False
52
+
53
+
54
+ logger = logging.get_logger(__name__) # pylint: disable=invalid-name
55
+
56
+ EXAMPLE_DOC_STRING = """
57
+ Examples:
58
+ ```py
59
+ >>> import torch
60
+ >>> from diffusers import FluxKontextPipeline
61
+ >>> from diffusers.utils import load_image
62
+
63
+ >>> pipe = FluxKontextPipeline.from_pretrained(
64
+ ... "black-forest-labs/FLUX.1-kontext", transformer=transformer, torch_dtype=torch.bfloat16
65
+ ... )
66
+ >>> pipe.to("cuda")
67
+
68
+ >>> image = load_image("inputs/yarn-art-pikachu.png").convert("RGB")
69
+ >>> prompt = "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/yarn-art-pikachu.png"
70
+ >>> image = pipe(
71
+ ... image=image,
72
+ ... prompt=prompt,
73
+ ... guidance_scale=2.5,
74
+ ... generator=torch.Generator().manual_seed(42),
75
+ ... ).images[0]
76
+ >>> image.save("output.png")
77
+ ```
78
+ """
79
+
80
+ PREFERRED_KONTEXT_RESOLUTIONS = [
81
+ (672, 1568),
82
+ (688, 1504),
83
+ (720, 1456),
84
+ (752, 1392),
85
+ (800, 1328),
86
+ (832, 1248),
87
+ (880, 1184),
88
+ (944, 1104),
89
+ (1024, 1024),
90
+ (1104, 944),
91
+ (1184, 880),
92
+ (1248, 832),
93
+ (1328, 800),
94
+ (1392, 752),
95
+ (1456, 720),
96
+ (1504, 688),
97
+ (1568, 672),
98
+ ]
99
+
100
+
101
+ def calculate_shift(
102
+ image_seq_len,
103
+ base_seq_len: int = 256,
104
+ max_seq_len: int = 4096,
105
+ base_shift: float = 0.5,
106
+ max_shift: float = 1.15,
107
+ ):
108
+ m = (max_shift - base_shift) / (max_seq_len - base_seq_len)
109
+ b = base_shift - m * base_seq_len
110
+ mu = image_seq_len * m + b
111
+ return mu
112
+
113
+
114
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.retrieve_timesteps
115
+ def retrieve_timesteps(
116
+ scheduler,
117
+ num_inference_steps: Optional[int] = None,
118
+ device: Optional[Union[str, torch.device]] = None,
119
+ timesteps: Optional[List[int]] = None,
120
+ sigmas: Optional[List[float]] = None,
121
+ **kwargs,
122
+ ):
123
+ r"""
124
+ Calls the scheduler's `set_timesteps` method and retrieves timesteps from the scheduler after the call. Handles
125
+ custom timesteps. Any kwargs will be supplied to `scheduler.set_timesteps`.
126
+
127
+ Args:
128
+ scheduler (`SchedulerMixin`):
129
+ The scheduler to get timesteps from.
130
+ num_inference_steps (`int`):
131
+ The number of diffusion steps used when generating samples with a pre-trained model. If used, `timesteps`
132
+ must be `None`.
133
+ device (`str` or `torch.device`, *optional*):
134
+ The device to which the timesteps should be moved to. If `None`, the timesteps are not moved.
135
+ timesteps (`List[int]`, *optional*):
136
+ Custom timesteps used to override the timestep spacing strategy of the scheduler. If `timesteps` is passed,
137
+ `num_inference_steps` and `sigmas` must be `None`.
138
+ sigmas (`List[float]`, *optional*):
139
+ Custom sigmas used to override the timestep spacing strategy of the scheduler. If `sigmas` is passed,
140
+ `num_inference_steps` and `timesteps` must be `None`.
141
+
142
+ Returns:
143
+ `Tuple[torch.Tensor, int]`: A tuple where the first element is the timestep schedule from the scheduler and the
144
+ second element is the number of inference steps.
145
+ """
146
+ if timesteps is not None and sigmas is not None:
147
+ raise ValueError("Only one of `timesteps` or `sigmas` can be passed. Please choose one to set custom values")
148
+ if timesteps is not None:
149
+ accepts_timesteps = "timesteps" in set(inspect.signature(scheduler.set_timesteps).parameters.keys())
150
+ if not accepts_timesteps:
151
+ raise ValueError(
152
+ f"The current scheduler class {scheduler.__class__}'s `set_timesteps` does not support custom"
153
+ f" timestep schedules. Please check whether you are using the correct scheduler."
154
+ )
155
+ scheduler.set_timesteps(timesteps=timesteps, device=device, **kwargs)
156
+ timesteps = scheduler.timesteps
157
+ num_inference_steps = len(timesteps)
158
+ elif sigmas is not None:
159
+ accept_sigmas = "sigmas" in set(inspect.signature(scheduler.set_timesteps).parameters.keys())
160
+ if not accept_sigmas:
161
+ raise ValueError(
162
+ f"The current scheduler class {scheduler.__class__}'s `set_timesteps` does not support custom"
163
+ f" sigmas schedules. Please check whether you are using the correct scheduler."
164
+ )
165
+ scheduler.set_timesteps(sigmas=sigmas, device=device, **kwargs)
166
+ timesteps = scheduler.timesteps
167
+ num_inference_steps = len(timesteps)
168
+ else:
169
+ scheduler.set_timesteps(num_inference_steps, device=device, **kwargs)
170
+ timesteps = scheduler.timesteps
171
+ return timesteps, num_inference_steps
172
+
173
+
174
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion_img2img.retrieve_latents
175
+ def retrieve_latents(
176
+ encoder_output: torch.Tensor, generator: Optional[torch.Generator] = None, sample_mode: str = "sample"
177
+ ):
178
+ if hasattr(encoder_output, "latent_dist") and sample_mode == "sample":
179
+ return encoder_output.latent_dist.sample(generator)
180
+ elif hasattr(encoder_output, "latent_dist") and sample_mode == "argmax":
181
+ return encoder_output.latent_dist.mode()
182
+ elif hasattr(encoder_output, "latents"):
183
+ return encoder_output.latents
184
+ else:
185
+ raise AttributeError("Could not access latents of provided encoder_output")
186
+
187
+
188
+ class FluxKontextPipeline(
189
+ DiffusionPipeline,
190
+ FluxLoraLoaderMixin,
191
+ FromSingleFileMixin,
192
+ TextualInversionLoaderMixin,
193
+ FluxIPAdapterMixin,
194
+ ):
195
+ r"""
196
+ The Flux Kontext pipeline for text-to-image generation.
197
+
198
+ Reference: https://blackforestlabs.ai/announcing-black-forest-labs/
199
+
200
+ Args:
201
+ transformer ([`FluxTransformer2DModel`]):
202
+ Conditional Transformer (MMDiT) architecture to denoise the encoded image latents.
203
+ scheduler ([`FlowMatchEulerDiscreteScheduler`]):
204
+ A scheduler to be used in combination with `transformer` to denoise the encoded image latents.
205
+ vae ([`AutoencoderKL`]):
206
+ Variational Auto-Encoder (VAE) Model to encode and decode images to and from latent representations.
207
+ text_encoder ([`CLIPTextModel`]):
208
+ [CLIP](https://huggingface.co/docs/transformers/model_doc/clip#transformers.CLIPTextModel), specifically
209
+ the [clip-vit-large-patch14](https://huggingface.co/openai/clip-vit-large-patch14) variant.
210
+ text_encoder_2 ([`T5EncoderModel`]):
211
+ [T5](https://huggingface.co/docs/transformers/en/model_doc/t5#transformers.T5EncoderModel), specifically
212
+ the [google/t5-v1_1-xxl](https://huggingface.co/google/t5-v1_1-xxl) variant.
213
+ tokenizer (`CLIPTokenizer`):
214
+ Tokenizer of class
215
+ [CLIPTokenizer](https://huggingface.co/docs/transformers/en/model_doc/clip#transformers.CLIPTokenizer).
216
+ tokenizer_2 (`T5TokenizerFast`):
217
+ Second Tokenizer of class
218
+ [T5TokenizerFast](https://huggingface.co/docs/transformers/en/model_doc/t5#transformers.T5TokenizerFast).
219
+ """
220
+
221
+ model_cpu_offload_seq = "text_encoder->text_encoder_2->image_encoder->transformer->vae"
222
+ _optional_components = ["image_encoder", "feature_extractor"]
223
+ _callback_tensor_inputs = ["latents", "prompt_embeds"]
224
+
225
+ def __init__(
226
+ self,
227
+ scheduler: FlowMatchEulerDiscreteScheduler,
228
+ vae: AutoencoderKL,
229
+ text_encoder: CLIPTextModel,
230
+ tokenizer: CLIPTokenizer,
231
+ text_encoder_2: T5EncoderModel,
232
+ tokenizer_2: T5TokenizerFast,
233
+ transformer: FluxTransformer2DModel,
234
+ image_encoder: CLIPVisionModelWithProjection = None,
235
+ feature_extractor: CLIPImageProcessor = None,
236
+ ):
237
+ super().__init__()
238
+
239
+ self.register_modules(
240
+ vae=vae,
241
+ text_encoder=text_encoder,
242
+ text_encoder_2=text_encoder_2,
243
+ tokenizer=tokenizer,
244
+ tokenizer_2=tokenizer_2,
245
+ transformer=transformer,
246
+ scheduler=scheduler,
247
+ image_encoder=image_encoder,
248
+ feature_extractor=feature_extractor,
249
+ )
250
+ self.vae_scale_factor = 2 ** (len(self.vae.config.block_out_channels) - 1) if getattr(self, "vae", None) else 8
251
+ # Flux latents are turned into 2x2 patches and packed. This means the latent width and height has to be divisible
252
+ # by the patch size. So the vae scale factor is multiplied by the patch size to account for this
253
+ self.latent_channels = self.vae.config.latent_channels if getattr(self, "vae", None) else 16
254
+ self.image_processor = VaeImageProcessor(vae_scale_factor=self.vae_scale_factor * 2)
255
+ self.tokenizer_max_length = (
256
+ self.tokenizer.model_max_length if hasattr(self, "tokenizer") and self.tokenizer is not None else 77
257
+ )
258
+ self.default_sample_size = 128
259
+
260
+ def _get_t5_prompt_embeds(
261
+ self,
262
+ prompt: Union[str, List[str]] = None,
263
+ num_images_per_prompt: int = 1,
264
+ max_sequence_length: int = 512,
265
+ device: Optional[torch.device] = None,
266
+ dtype: Optional[torch.dtype] = None,
267
+ ):
268
+ device = device or self._execution_device
269
+ dtype = dtype or self.text_encoder.dtype
270
+
271
+ prompt = [prompt] if isinstance(prompt, str) else prompt
272
+ batch_size = len(prompt)
273
+
274
+ if isinstance(self, TextualInversionLoaderMixin):
275
+ prompt = self.maybe_convert_prompt(prompt, self.tokenizer_2)
276
+
277
+ text_inputs = self.tokenizer_2(
278
+ prompt,
279
+ padding="max_length",
280
+ max_length=max_sequence_length,
281
+ truncation=True,
282
+ return_length=False,
283
+ return_overflowing_tokens=False,
284
+ return_tensors="pt",
285
+ )
286
+ text_input_ids = text_inputs.input_ids
287
+ untruncated_ids = self.tokenizer_2(prompt, padding="longest", return_tensors="pt").input_ids
288
+
289
+ if untruncated_ids.shape[-1] >= text_input_ids.shape[-1] and not torch.equal(text_input_ids, untruncated_ids):
290
+ removed_text = self.tokenizer_2.batch_decode(untruncated_ids[:, self.tokenizer_max_length - 1 : -1])
291
+ logger.warning(
292
+ "The following part of your input was truncated because `max_sequence_length` is set to "
293
+ f" {max_sequence_length} tokens: {removed_text}"
294
+ )
295
+
296
+ prompt_embeds = self.text_encoder_2(text_input_ids.to(device), output_hidden_states=False)[0]
297
+
298
+ dtype = self.text_encoder_2.dtype
299
+ prompt_embeds = prompt_embeds.to(dtype=dtype, device=device)
300
+
301
+ _, seq_len, _ = prompt_embeds.shape
302
+
303
+ # duplicate text embeddings and attention mask for each generation per prompt, using mps friendly method
304
+ prompt_embeds = prompt_embeds.repeat(1, num_images_per_prompt, 1)
305
+ prompt_embeds = prompt_embeds.view(batch_size * num_images_per_prompt, seq_len, -1)
306
+
307
+ return prompt_embeds
308
+
309
+ def _get_clip_prompt_embeds(
310
+ self,
311
+ prompt: Union[str, List[str]],
312
+ num_images_per_prompt: int = 1,
313
+ device: Optional[torch.device] = None,
314
+ ):
315
+ device = device or self._execution_device
316
+
317
+ prompt = [prompt] if isinstance(prompt, str) else prompt
318
+ batch_size = len(prompt)
319
+
320
+ if isinstance(self, TextualInversionLoaderMixin):
321
+ prompt = self.maybe_convert_prompt(prompt, self.tokenizer)
322
+
323
+ text_inputs = self.tokenizer(
324
+ prompt,
325
+ padding="max_length",
326
+ max_length=self.tokenizer_max_length,
327
+ truncation=True,
328
+ return_overflowing_tokens=False,
329
+ return_length=False,
330
+ return_tensors="pt",
331
+ )
332
+
333
+ text_input_ids = text_inputs.input_ids
334
+ untruncated_ids = self.tokenizer(prompt, padding="longest", return_tensors="pt").input_ids
335
+ if untruncated_ids.shape[-1] >= text_input_ids.shape[-1] and not torch.equal(text_input_ids, untruncated_ids):
336
+ removed_text = self.tokenizer.batch_decode(untruncated_ids[:, self.tokenizer_max_length - 1 : -1])
337
+ logger.warning(
338
+ "The following part of your input was truncated because CLIP can only handle sequences up to"
339
+ f" {self.tokenizer_max_length} tokens: {removed_text}"
340
+ )
341
+ prompt_embeds = self.text_encoder(text_input_ids.to(device), output_hidden_states=False)
342
+
343
+ # Use pooled output of CLIPTextModel
344
+ prompt_embeds = prompt_embeds.pooler_output
345
+ prompt_embeds = prompt_embeds.to(dtype=self.text_encoder.dtype, device=device)
346
+
347
+ # duplicate text embeddings for each generation per prompt, using mps friendly method
348
+ prompt_embeds = prompt_embeds.repeat(1, num_images_per_prompt)
349
+ prompt_embeds = prompt_embeds.view(batch_size * num_images_per_prompt, -1)
350
+
351
+ return prompt_embeds
352
+
353
+ def encode_prompt(
354
+ self,
355
+ prompt: Union[str, List[str]],
356
+ prompt_2: Union[str, List[str]],
357
+ device: Optional[torch.device] = None,
358
+ num_images_per_prompt: int = 1,
359
+ prompt_embeds: Optional[torch.FloatTensor] = None,
360
+ pooled_prompt_embeds: Optional[torch.FloatTensor] = None,
361
+ max_sequence_length: int = 512,
362
+ lora_scale: Optional[float] = None,
363
+ ):
364
+ r"""
365
+
366
+ Args:
367
+ prompt (`str` or `List[str]`, *optional*):
368
+ prompt to be encoded
369
+ prompt_2 (`str` or `List[str]`, *optional*):
370
+ The prompt or prompts to be sent to the `tokenizer_2` and `text_encoder_2`. If not defined, `prompt` is
371
+ used in all text-encoders
372
+ device: (`torch.device`):
373
+ torch device
374
+ num_images_per_prompt (`int`):
375
+ number of images that should be generated per prompt
376
+ prompt_embeds (`torch.FloatTensor`, *optional*):
377
+ Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not
378
+ provided, text embeddings will be generated from `prompt` input argument.
379
+ pooled_prompt_embeds (`torch.FloatTensor`, *optional*):
380
+ Pre-generated pooled text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting.
381
+ If not provided, pooled text embeddings will be generated from `prompt` input argument.
382
+ lora_scale (`float`, *optional*):
383
+ A lora scale that will be applied to all LoRA layers of the text encoder if LoRA layers are loaded.
384
+ """
385
+ device = device or self._execution_device
386
+
387
+ # set lora scale so that monkey patched LoRA
388
+ # function of text encoder can correctly access it
389
+ if lora_scale is not None and isinstance(self, FluxLoraLoaderMixin):
390
+ self._lora_scale = lora_scale
391
+
392
+ # dynamically adjust the LoRA scale
393
+ if self.text_encoder is not None and USE_PEFT_BACKEND:
394
+ scale_lora_layers(self.text_encoder, lora_scale)
395
+ if self.text_encoder_2 is not None and USE_PEFT_BACKEND:
396
+ scale_lora_layers(self.text_encoder_2, lora_scale)
397
+
398
+ prompt = [prompt] if isinstance(prompt, str) else prompt
399
+
400
+ if prompt_embeds is None:
401
+ prompt_2 = prompt_2 or prompt
402
+ prompt_2 = [prompt_2] if isinstance(prompt_2, str) else prompt_2
403
+
404
+ # We only use the pooled prompt output from the CLIPTextModel
405
+ pooled_prompt_embeds = self._get_clip_prompt_embeds(
406
+ prompt=prompt,
407
+ device=device,
408
+ num_images_per_prompt=num_images_per_prompt,
409
+ )
410
+ prompt_embeds = self._get_t5_prompt_embeds(
411
+ prompt=prompt_2,
412
+ num_images_per_prompt=num_images_per_prompt,
413
+ max_sequence_length=max_sequence_length,
414
+ device=device,
415
+ )
416
+
417
+ if self.text_encoder is not None:
418
+ if isinstance(self, FluxLoraLoaderMixin) and USE_PEFT_BACKEND:
419
+ # Retrieve the original scale by scaling back the LoRA layers
420
+ unscale_lora_layers(self.text_encoder, lora_scale)
421
+
422
+ if self.text_encoder_2 is not None:
423
+ if isinstance(self, FluxLoraLoaderMixin) and USE_PEFT_BACKEND:
424
+ # Retrieve the original scale by scaling back the LoRA layers
425
+ unscale_lora_layers(self.text_encoder_2, lora_scale)
426
+
427
+ dtype = self.text_encoder.dtype if self.text_encoder is not None else self.transformer.dtype
428
+ text_ids = torch.zeros(prompt_embeds.shape[1], 3).to(device=device, dtype=dtype)
429
+
430
+ return prompt_embeds, pooled_prompt_embeds, text_ids
431
+
432
+ def encode_image(self, image, device, num_images_per_prompt):
433
+ dtype = next(self.image_encoder.parameters()).dtype
434
+
435
+ if not isinstance(image, torch.Tensor):
436
+ image = self.feature_extractor(image, return_tensors="pt").pixel_values
437
+
438
+ image = image.to(device=device, dtype=dtype)
439
+ image_embeds = self.image_encoder(image).image_embeds
440
+ image_embeds = image_embeds.repeat_interleave(num_images_per_prompt, dim=0)
441
+ return image_embeds
442
+
443
+ def prepare_ip_adapter_image_embeds(
444
+ self, ip_adapter_image, ip_adapter_image_embeds, device, num_images_per_prompt
445
+ ):
446
+ image_embeds = []
447
+ if ip_adapter_image_embeds is None:
448
+ if not isinstance(ip_adapter_image, list):
449
+ ip_adapter_image = [ip_adapter_image]
450
+
451
+ if len(ip_adapter_image) != self.transformer.encoder_hid_proj.num_ip_adapters:
452
+ raise ValueError(
453
+ f"`ip_adapter_image` must have same length as the number of IP Adapters. Got {len(ip_adapter_image)} images and {self.transformer.encoder_hid_proj.num_ip_adapters} IP Adapters."
454
+ )
455
+
456
+ for single_ip_adapter_image in ip_adapter_image:
457
+ single_image_embeds = self.encode_image(single_ip_adapter_image, device, 1)
458
+ image_embeds.append(single_image_embeds[None, :])
459
+ else:
460
+ if not isinstance(ip_adapter_image_embeds, list):
461
+ ip_adapter_image_embeds = [ip_adapter_image_embeds]
462
+
463
+ if len(ip_adapter_image_embeds) != self.transformer.encoder_hid_proj.num_ip_adapters:
464
+ raise ValueError(
465
+ f"`ip_adapter_image_embeds` must have same length as the number of IP Adapters. Got {len(ip_adapter_image_embeds)} image embeds and {self.transformer.encoder_hid_proj.num_ip_adapters} IP Adapters."
466
+ )
467
+
468
+ for single_image_embeds in ip_adapter_image_embeds:
469
+ image_embeds.append(single_image_embeds)
470
+
471
+ ip_adapter_image_embeds = []
472
+ for single_image_embeds in image_embeds:
473
+ single_image_embeds = torch.cat([single_image_embeds] * num_images_per_prompt, dim=0)
474
+ single_image_embeds = single_image_embeds.to(device=device)
475
+ ip_adapter_image_embeds.append(single_image_embeds)
476
+
477
+ return ip_adapter_image_embeds
478
+
479
+ def check_inputs(
480
+ self,
481
+ prompt,
482
+ prompt_2,
483
+ height,
484
+ width,
485
+ negative_prompt=None,
486
+ negative_prompt_2=None,
487
+ prompt_embeds=None,
488
+ negative_prompt_embeds=None,
489
+ pooled_prompt_embeds=None,
490
+ negative_pooled_prompt_embeds=None,
491
+ callback_on_step_end_tensor_inputs=None,
492
+ max_sequence_length=None,
493
+ ):
494
+ if height % (self.vae_scale_factor * 2) != 0 or width % (self.vae_scale_factor * 2) != 0:
495
+ logger.warning(
496
+ f"`height` and `width` have to be divisible by {self.vae_scale_factor * 2} but are {height} and {width}. Dimensions will be resized accordingly"
497
+ )
498
+
499
+ if callback_on_step_end_tensor_inputs is not None and not all(
500
+ k in self._callback_tensor_inputs for k in callback_on_step_end_tensor_inputs
501
+ ):
502
+ raise ValueError(
503
+ 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]}"
504
+ )
505
+
506
+ if prompt is not None and prompt_embeds is not None:
507
+ raise ValueError(
508
+ f"Cannot forward both `prompt`: {prompt} and `prompt_embeds`: {prompt_embeds}. Please make sure to"
509
+ " only forward one of the two."
510
+ )
511
+ elif prompt_2 is not None and prompt_embeds is not None:
512
+ raise ValueError(
513
+ f"Cannot forward both `prompt_2`: {prompt_2} and `prompt_embeds`: {prompt_embeds}. Please make sure to"
514
+ " only forward one of the two."
515
+ )
516
+ elif prompt is None and prompt_embeds is None:
517
+ raise ValueError(
518
+ "Provide either `prompt` or `prompt_embeds`. Cannot leave both `prompt` and `prompt_embeds` undefined."
519
+ )
520
+ elif prompt is not None and (not isinstance(prompt, str) and not isinstance(prompt, list)):
521
+ raise ValueError(f"`prompt` has to be of type `str` or `list` but is {type(prompt)}")
522
+ elif prompt_2 is not None and (not isinstance(prompt_2, str) and not isinstance(prompt_2, list)):
523
+ raise ValueError(f"`prompt_2` has to be of type `str` or `list` but is {type(prompt_2)}")
524
+
525
+ if negative_prompt is not None and negative_prompt_embeds is not None:
526
+ raise ValueError(
527
+ f"Cannot forward both `negative_prompt`: {negative_prompt} and `negative_prompt_embeds`:"
528
+ f" {negative_prompt_embeds}. Please make sure to only forward one of the two."
529
+ )
530
+ elif negative_prompt_2 is not None and negative_prompt_embeds is not None:
531
+ raise ValueError(
532
+ f"Cannot forward both `negative_prompt_2`: {negative_prompt_2} and `negative_prompt_embeds`:"
533
+ f" {negative_prompt_embeds}. Please make sure to only forward one of the two."
534
+ )
535
+
536
+ if prompt_embeds is not None and pooled_prompt_embeds is None:
537
+ raise ValueError(
538
+ "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`."
539
+ )
540
+ if negative_prompt_embeds is not None and negative_pooled_prompt_embeds is None:
541
+ raise ValueError(
542
+ "If `negative_prompt_embeds` are provided, `negative_pooled_prompt_embeds` also have to be passed. Make sure to generate `negative_pooled_prompt_embeds` from the same text encoder that was used to generate `negative_prompt_embeds`."
543
+ )
544
+
545
+ if max_sequence_length is not None and max_sequence_length > 512:
546
+ raise ValueError(f"`max_sequence_length` cannot be greater than 512 but is {max_sequence_length}")
547
+
548
+ @staticmethod
549
+ def _prepare_latent_image_ids(batch_size, height, width, device, dtype):
550
+ latent_image_ids = torch.zeros(height, width, 3)
551
+ latent_image_ids[..., 1] = latent_image_ids[..., 1] + torch.arange(height)[:, None]
552
+ latent_image_ids[..., 2] = latent_image_ids[..., 2] + torch.arange(width)[None, :]
553
+
554
+ latent_image_id_height, latent_image_id_width, latent_image_id_channels = latent_image_ids.shape
555
+
556
+ latent_image_ids = latent_image_ids.reshape(
557
+ latent_image_id_height * latent_image_id_width, latent_image_id_channels
558
+ )
559
+
560
+ return latent_image_ids.to(device=device, dtype=dtype)
561
+
562
+ @staticmethod
563
+ def _pack_latents(latents, batch_size, num_channels_latents, height, width):
564
+ latents = latents.view(batch_size, num_channels_latents, height // 2, 2, width // 2, 2)
565
+ latents = latents.permute(0, 2, 4, 1, 3, 5)
566
+ latents = latents.reshape(batch_size, (height // 2) * (width // 2), num_channels_latents * 4)
567
+
568
+ return latents
569
+
570
+ @staticmethod
571
+ def _unpack_latents(latents, height, width, vae_scale_factor):
572
+ batch_size, num_patches, channels = latents.shape
573
+
574
+ # VAE applies 8x compression on images but we must also account for packing which requires
575
+ # latent height and width to be divisible by 2.
576
+ height = 2 * (int(height) // (vae_scale_factor * 2))
577
+ width = 2 * (int(width) // (vae_scale_factor * 2))
578
+
579
+ latents = latents.view(batch_size, height // 2, width // 2, channels // 4, 2, 2)
580
+ latents = latents.permute(0, 3, 1, 4, 2, 5)
581
+
582
+ latents = latents.reshape(batch_size, channels // (2 * 2), height, width)
583
+
584
+ return latents
585
+
586
+ # Copied from diffusers.pipelines.stable_diffusion_3.pipeline_stable_diffusion_3_inpaint.StableDiffusion3InpaintPipeline._encode_vae_image
587
+ def _encode_vae_image(self, image: torch.Tensor, generator: torch.Generator):
588
+ if isinstance(generator, list):
589
+ image_latents = [
590
+ retrieve_latents(self.vae.encode(image[i : i + 1]), generator=generator[i], sample_mode="argmax")
591
+ for i in range(image.shape[0])
592
+ ]
593
+ image_latents = torch.cat(image_latents, dim=0)
594
+ else:
595
+ image_latents = retrieve_latents(self.vae.encode(image), generator=generator, sample_mode="argmax")
596
+
597
+ image_latents = (image_latents - self.vae.config.shift_factor) * self.vae.config.scaling_factor
598
+
599
+ return image_latents
600
+
601
+ def enable_vae_slicing(self):
602
+ r"""
603
+ Enable sliced VAE decoding. When this option is enabled, the VAE will split the input tensor in slices to
604
+ compute decoding in several steps. This is useful to save some memory and allow larger batch sizes.
605
+ """
606
+ self.vae.enable_slicing()
607
+
608
+ def disable_vae_slicing(self):
609
+ r"""
610
+ Disable sliced VAE decoding. If `enable_vae_slicing` was previously enabled, this method will go back to
611
+ computing decoding in one step.
612
+ """
613
+ self.vae.disable_slicing()
614
+
615
+ def enable_vae_tiling(self):
616
+ r"""
617
+ Enable tiled VAE decoding. When this option is enabled, the VAE will split the input tensor into tiles to
618
+ compute decoding and encoding in several steps. This is useful for saving a large amount of memory and to allow
619
+ processing larger images.
620
+ """
621
+ self.vae.enable_tiling()
622
+
623
+ def disable_vae_tiling(self):
624
+ r"""
625
+ Disable tiled VAE decoding. If `enable_vae_tiling` was previously enabled, this method will go back to
626
+ computing decoding in one step.
627
+ """
628
+ self.vae.disable_tiling()
629
+
630
+ def prepare_latents(
631
+ self,
632
+ image: Optional[torch.Tensor],
633
+ batch_size: int,
634
+ num_channels_latents: int,
635
+ height: int,
636
+ width: int,
637
+ dtype: torch.dtype,
638
+ device: torch.device,
639
+ generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
640
+ latents: Optional[torch.Tensor] = None,
641
+ ):
642
+ if isinstance(generator, list) and len(generator) != batch_size:
643
+ raise ValueError(
644
+ f"You have passed a list of generators of length {len(generator)}, but requested an effective batch"
645
+ f" size of {batch_size}. Make sure the batch size matches the length of the generators."
646
+ )
647
+
648
+ # VAE applies 8x compression on images but we must also account for packing which requires
649
+ # latent height and width to be divisible by 2.
650
+ height = 2 * (int(height) // (self.vae_scale_factor * 2))
651
+ width = 2 * (int(width) // (self.vae_scale_factor * 2))
652
+ shape = (batch_size, num_channels_latents, height, width)
653
+
654
+ image_latents = image_ids = None
655
+ if image is not None:
656
+ image = image.to(device=device, dtype=dtype)
657
+ if image.shape[1] != self.latent_channels:
658
+ image_latents = self._encode_vae_image(image=image, generator=generator)
659
+ else:
660
+ image_latents = image
661
+ if batch_size > image_latents.shape[0] and batch_size % image_latents.shape[0] == 0:
662
+ # expand init_latents for batch_size
663
+ additional_image_per_prompt = batch_size // image_latents.shape[0]
664
+ image_latents = torch.cat([image_latents] * additional_image_per_prompt, dim=0)
665
+ elif batch_size > image_latents.shape[0] and batch_size % image_latents.shape[0] != 0:
666
+ raise ValueError(
667
+ f"Cannot duplicate `image` of batch size {image_latents.shape[0]} to {batch_size} text prompts."
668
+ )
669
+ else:
670
+ image_latents = torch.cat([image_latents], dim=0)
671
+
672
+ image_latent_height, image_latent_width = image_latents.shape[2:]
673
+ image_latents = self._pack_latents(
674
+ image_latents, batch_size, num_channels_latents, image_latent_height, image_latent_width
675
+ )
676
+ image_ids = self._prepare_latent_image_ids(
677
+ batch_size, image_latent_height // 2, image_latent_width // 2, device, dtype
678
+ )
679
+ # image ids are the same as latent ids with the first dimension set to 1 instead of 0
680
+ image_ids[..., 0] = 1
681
+
682
+ latent_ids = self._prepare_latent_image_ids(batch_size, height // 2, width // 2, device, dtype)
683
+
684
+ if latents is None:
685
+ latents = randn_tensor(shape, generator=generator, device=device, dtype=dtype)
686
+ latents = self._pack_latents(latents, batch_size, num_channels_latents, height, width)
687
+ else:
688
+ latents = latents.to(device=device, dtype=dtype)
689
+
690
+ return latents, image_latents, latent_ids, image_ids
691
+
692
+ @property
693
+ def guidance_scale(self):
694
+ return self._guidance_scale
695
+
696
+ @property
697
+ def joint_attention_kwargs(self):
698
+ return self._joint_attention_kwargs
699
+
700
+ @property
701
+ def num_timesteps(self):
702
+ return self._num_timesteps
703
+
704
+ @property
705
+ def current_timestep(self):
706
+ return self._current_timestep
707
+
708
+ @property
709
+ def interrupt(self):
710
+ return self._interrupt
711
+
712
+ @torch.no_grad()
713
+ @replace_example_docstring(EXAMPLE_DOC_STRING)
714
+ def __call__(
715
+ self,
716
+ image: Optional[PipelineImageInput] = None,
717
+ prompt: Union[str, List[str]] = None,
718
+ prompt_2: Optional[Union[str, List[str]]] = None,
719
+ negative_prompt: Union[str, List[str]] = None,
720
+ negative_prompt_2: Optional[Union[str, List[str]]] = None,
721
+ true_cfg_scale: float = 1.0,
722
+ height: Optional[int] = None,
723
+ width: Optional[int] = None,
724
+ num_inference_steps: int = 28,
725
+ sigmas: Optional[List[float]] = None,
726
+ guidance_scale: float = 3.5,
727
+ num_images_per_prompt: Optional[int] = 1,
728
+ generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
729
+ latents: Optional[torch.FloatTensor] = None,
730
+ prompt_embeds: Optional[torch.FloatTensor] = None,
731
+ pooled_prompt_embeds: Optional[torch.FloatTensor] = None,
732
+ ip_adapter_image: Optional[PipelineImageInput] = None,
733
+ ip_adapter_image_embeds: Optional[List[torch.Tensor]] = None,
734
+ negative_ip_adapter_image: Optional[PipelineImageInput] = None,
735
+ negative_ip_adapter_image_embeds: Optional[List[torch.Tensor]] = None,
736
+ negative_prompt_embeds: Optional[torch.FloatTensor] = None,
737
+ negative_pooled_prompt_embeds: Optional[torch.FloatTensor] = None,
738
+ output_type: Optional[str] = "pil",
739
+ return_dict: bool = True,
740
+ joint_attention_kwargs: Optional[Dict[str, Any]] = None,
741
+ callback_on_step_end: Optional[Callable[[int, int, Dict], None]] = None,
742
+ callback_on_step_end_tensor_inputs: List[str] = ["latents"],
743
+ max_sequence_length: int = 512,
744
+ max_area: int = 1024**2,
745
+ _auto_resize: bool = True,
746
+ ):
747
+ r"""
748
+ Function invoked when calling the pipeline for generation.
749
+
750
+ Args:
751
+ image (`torch.Tensor`, `PIL.Image.Image`, `np.ndarray`, `List[torch.Tensor]`, `List[PIL.Image.Image]`, or `List[np.ndarray]`):
752
+ `Image`, numpy array or tensor representing an image batch to be used as the starting point. For both
753
+ numpy array and pytorch tensor, the expected value range is between `[0, 1]` If it's a tensor or a list
754
+ or tensors, the expected shape should be `(B, C, H, W)` or `(C, H, W)`. If it is a numpy array or a
755
+ list of arrays, the expected shape should be `(B, H, W, C)` or `(H, W, C)` It can also accept image
756
+ latents as `image`, but if passing latents directly it is not encoded again.
757
+ prompt (`str` or `List[str]`, *optional*):
758
+ The prompt or prompts to guide the image generation. If not defined, one has to pass `prompt_embeds`.
759
+ instead.
760
+ prompt_2 (`str` or `List[str]`, *optional*):
761
+ The prompt or prompts to be sent to `tokenizer_2` and `text_encoder_2`. If not defined, `prompt` is
762
+ will be used instead.
763
+ negative_prompt (`str` or `List[str]`, *optional*):
764
+ The prompt or prompts not to guide the image generation. If not defined, one has to pass
765
+ `negative_prompt_embeds` instead. Ignored when not using guidance (i.e., ignored if `true_cfg_scale` is
766
+ not greater than `1`).
767
+ negative_prompt_2 (`str` or `List[str]`, *optional*):
768
+ The prompt or prompts not to guide the image generation to be sent to `tokenizer_2` and
769
+ `text_encoder_2`. If not defined, `negative_prompt` is used in all the text-encoders.
770
+ true_cfg_scale (`float`, *optional*, defaults to 1.0):
771
+ When > 1.0 and a provided `negative_prompt`, enables true classifier-free guidance.
772
+ height (`int`, *optional*, defaults to self.unet.config.sample_size * self.vae_scale_factor):
773
+ The height in pixels of the generated image. This is set to 1024 by default for the best results.
774
+ width (`int`, *optional*, defaults to self.unet.config.sample_size * self.vae_scale_factor):
775
+ The width in pixels of the generated image. This is set to 1024 by default for the best results.
776
+ num_inference_steps (`int`, *optional*, defaults to 50):
777
+ The number of denoising steps. More denoising steps usually lead to a higher quality image at the
778
+ expense of slower inference.
779
+ sigmas (`List[float]`, *optional*):
780
+ Custom sigmas to use for the denoising process with schedulers which support a `sigmas` argument in
781
+ their `set_timesteps` method. If not defined, the default behavior when `num_inference_steps` is passed
782
+ will be used.
783
+ guidance_scale (`float`, *optional*, defaults to 3.5):
784
+ Guidance scale as defined in [Classifier-Free Diffusion
785
+ Guidance](https://huggingface.co/papers/2207.12598). `guidance_scale` is defined as `w` of equation 2.
786
+ of [Imagen Paper](https://huggingface.co/papers/2205.11487). Guidance scale is enabled by setting
787
+ `guidance_scale > 1`. Higher guidance scale encourages to generate images that are closely linked to
788
+ the text `prompt`, usually at the expense of lower image quality.
789
+ num_images_per_prompt (`int`, *optional*, defaults to 1):
790
+ The number of images to generate per prompt.
791
+ generator (`torch.Generator` or `List[torch.Generator]`, *optional*):
792
+ One or a list of [torch generator(s)](https://pytorch.org/docs/stable/generated/torch.Generator.html)
793
+ to make generation deterministic.
794
+ latents (`torch.FloatTensor`, *optional*):
795
+ Pre-generated noisy latents, sampled from a Gaussian distribution, to be used as inputs for image
796
+ generation. Can be used to tweak the same generation with different prompts. If not provided, a latents
797
+ tensor will ge generated by sampling using the supplied random `generator`.
798
+ prompt_embeds (`torch.FloatTensor`, *optional*):
799
+ Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not
800
+ provided, text embeddings will be generated from `prompt` input argument.
801
+ pooled_prompt_embeds (`torch.FloatTensor`, *optional*):
802
+ Pre-generated pooled text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting.
803
+ If not provided, pooled text embeddings will be generated from `prompt` input argument.
804
+ ip_adapter_image: (`PipelineImageInput`, *optional*):
805
+ Optional image input to work with IP Adapters.
806
+ ip_adapter_image_embeds (`List[torch.Tensor]`, *optional*):
807
+ Pre-generated image embeddings for IP-Adapter. It should be a list of length same as number of
808
+ IP-adapters. Each element should be a tensor of shape `(batch_size, num_images, emb_dim)`. If not
809
+ provided, embeddings are computed from the `ip_adapter_image` input argument.
810
+ negative_ip_adapter_image:
811
+ (`PipelineImageInput`, *optional*): Optional image input to work with IP Adapters.
812
+ negative_ip_adapter_image_embeds (`List[torch.Tensor]`, *optional*):
813
+ Pre-generated image embeddings for IP-Adapter. It should be a list of length same as number of
814
+ IP-adapters. Each element should be a tensor of shape `(batch_size, num_images, emb_dim)`. If not
815
+ provided, embeddings are computed from the `ip_adapter_image` input argument.
816
+ negative_prompt_embeds (`torch.FloatTensor`, *optional*):
817
+ Pre-generated negative text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
818
+ weighting. If not provided, negative_prompt_embeds will be generated from `negative_prompt` input
819
+ argument.
820
+ negative_pooled_prompt_embeds (`torch.FloatTensor`, *optional*):
821
+ Pre-generated negative pooled text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
822
+ weighting. If not provided, pooled negative_prompt_embeds will be generated from `negative_prompt`
823
+ input argument.
824
+ output_type (`str`, *optional*, defaults to `"pil"`):
825
+ The output format of the generate image. Choose between
826
+ [PIL](https://pillow.readthedocs.io/en/stable/): `PIL.Image.Image` or `np.array`.
827
+ return_dict (`bool`, *optional*, defaults to `True`):
828
+ Whether or not to return a [`~pipelines.flux.FluxPipelineOutput`] instead of a plain tuple.
829
+ joint_attention_kwargs (`dict`, *optional*):
830
+ A kwargs dictionary that if specified is passed along to the `AttentionProcessor` as defined under
831
+ `self.processor` in
832
+ [diffusers.models.attention_processor](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py).
833
+ callback_on_step_end (`Callable`, *optional*):
834
+ A function that calls at the end of each denoising steps during the inference. The function is called
835
+ with the following arguments: `callback_on_step_end(self: DiffusionPipeline, step: int, timestep: int,
836
+ callback_kwargs: Dict)`. `callback_kwargs` will include a list of all tensors as specified by
837
+ `callback_on_step_end_tensor_inputs`.
838
+ callback_on_step_end_tensor_inputs (`List`, *optional*):
839
+ The list of tensor inputs for the `callback_on_step_end` function. The tensors specified in the list
840
+ will be passed as `callback_kwargs` argument. You will only be able to include variables listed in the
841
+ `._callback_tensor_inputs` attribute of your pipeline class.
842
+ max_sequence_length (`int` defaults to 512):
843
+ Maximum sequence length to use with the `prompt`.
844
+ max_area (`int`, defaults to `1024 ** 2`):
845
+ The maximum area of the generated image in pixels. The height and width will be adjusted to fit this
846
+ area while maintaining the aspect ratio.
847
+
848
+ Examples:
849
+
850
+ Returns:
851
+ [`~pipelines.flux.FluxPipelineOutput`] or `tuple`: [`~pipelines.flux.FluxPipelineOutput`] if `return_dict`
852
+ is True, otherwise a `tuple`. When returning a tuple, the first element is a list with the generated
853
+ images.
854
+ """
855
+
856
+ height = height or self.default_sample_size * self.vae_scale_factor
857
+ width = width or self.default_sample_size * self.vae_scale_factor
858
+
859
+ original_height, original_width = height, width
860
+ aspect_ratio = width / height
861
+ width = round((max_area * aspect_ratio) ** 0.5)
862
+ height = round((max_area / aspect_ratio) ** 0.5)
863
+
864
+ multiple_of = self.vae_scale_factor * 2
865
+ width = width // multiple_of * multiple_of
866
+ height = height // multiple_of * multiple_of
867
+
868
+ if height != original_height or width != original_width:
869
+ logger.warning(
870
+ f"Generation `height` and `width` have been adjusted to {height} and {width} to fit the model requirements."
871
+ )
872
+
873
+ # 1. Check inputs. Raise error if not correct
874
+ self.check_inputs(
875
+ prompt,
876
+ prompt_2,
877
+ height,
878
+ width,
879
+ negative_prompt=negative_prompt,
880
+ negative_prompt_2=negative_prompt_2,
881
+ prompt_embeds=prompt_embeds,
882
+ negative_prompt_embeds=negative_prompt_embeds,
883
+ pooled_prompt_embeds=pooled_prompt_embeds,
884
+ negative_pooled_prompt_embeds=negative_pooled_prompt_embeds,
885
+ callback_on_step_end_tensor_inputs=callback_on_step_end_tensor_inputs,
886
+ max_sequence_length=max_sequence_length,
887
+ )
888
+
889
+ self._guidance_scale = guidance_scale
890
+ self._joint_attention_kwargs = joint_attention_kwargs
891
+ self._current_timestep = None
892
+ self._interrupt = False
893
+
894
+ # 2. Define call parameters
895
+ if prompt is not None and isinstance(prompt, str):
896
+ batch_size = 1
897
+ elif prompt is not None and isinstance(prompt, list):
898
+ batch_size = len(prompt)
899
+ else:
900
+ batch_size = prompt_embeds.shape[0]
901
+
902
+ device = self._execution_device
903
+
904
+ lora_scale = (
905
+ self.joint_attention_kwargs.get("scale", None) if self.joint_attention_kwargs is not None else None
906
+ )
907
+ has_neg_prompt = negative_prompt is not None or (
908
+ negative_prompt_embeds is not None and negative_pooled_prompt_embeds is not None
909
+ )
910
+ do_true_cfg = true_cfg_scale > 1 and has_neg_prompt
911
+ (
912
+ prompt_embeds,
913
+ pooled_prompt_embeds,
914
+ text_ids,
915
+ ) = self.encode_prompt(
916
+ prompt=prompt,
917
+ prompt_2=prompt_2,
918
+ prompt_embeds=prompt_embeds,
919
+ pooled_prompt_embeds=pooled_prompt_embeds,
920
+ device=device,
921
+ num_images_per_prompt=num_images_per_prompt,
922
+ max_sequence_length=max_sequence_length,
923
+ lora_scale=lora_scale,
924
+ )
925
+ if do_true_cfg:
926
+ (
927
+ negative_prompt_embeds,
928
+ negative_pooled_prompt_embeds,
929
+ negative_text_ids,
930
+ ) = self.encode_prompt(
931
+ prompt=negative_prompt,
932
+ prompt_2=negative_prompt_2,
933
+ prompt_embeds=negative_prompt_embeds,
934
+ pooled_prompt_embeds=negative_pooled_prompt_embeds,
935
+ device=device,
936
+ num_images_per_prompt=num_images_per_prompt,
937
+ max_sequence_length=max_sequence_length,
938
+ lora_scale=lora_scale,
939
+ )
940
+
941
+ # 3. Preprocess image
942
+ if image is not None and not (isinstance(image, torch.Tensor) and image.size(1) == self.latent_channels):
943
+ img = image[0] if isinstance(image, list) else image
944
+ image_height, image_width = self.image_processor.get_default_height_width(img)
945
+ aspect_ratio = image_width / image_height
946
+ if _auto_resize:
947
+ # Kontext is trained on specific resolutions, using one of them is recommended
948
+ _, image_width, image_height = min(
949
+ (abs(aspect_ratio - w / h), w, h) for w, h in PREFERRED_KONTEXT_RESOLUTIONS
950
+ )
951
+ image_width = image_width // multiple_of * multiple_of
952
+ image_height = image_height // multiple_of * multiple_of
953
+ image = self.image_processor.resize(image, image_height, image_width)
954
+ image = self.image_processor.preprocess(image, image_height, image_width)
955
+
956
+ # 4. Prepare latent variables
957
+ num_channels_latents = self.transformer.config.in_channels // 4
958
+ latents, image_latents, latent_ids, image_ids = self.prepare_latents(
959
+ image,
960
+ batch_size * num_images_per_prompt,
961
+ num_channels_latents,
962
+ height,
963
+ width,
964
+ prompt_embeds.dtype,
965
+ device,
966
+ generator,
967
+ latents,
968
+ )
969
+ if image_ids is not None:
970
+ latent_ids = torch.cat([latent_ids, image_ids], dim=0) # dim 0 is sequence dimension
971
+
972
+ # 5. Prepare timesteps
973
+ sigmas = np.linspace(1.0, 1 / num_inference_steps, num_inference_steps) if sigmas is None else sigmas
974
+ image_seq_len = latents.shape[1]
975
+ mu = calculate_shift(
976
+ image_seq_len,
977
+ self.scheduler.config.get("base_image_seq_len", 256),
978
+ self.scheduler.config.get("max_image_seq_len", 4096),
979
+ self.scheduler.config.get("base_shift", 0.5),
980
+ self.scheduler.config.get("max_shift", 1.15),
981
+ )
982
+ timesteps, num_inference_steps = retrieve_timesteps(
983
+ self.scheduler,
984
+ num_inference_steps,
985
+ device,
986
+ sigmas=sigmas,
987
+ mu=mu,
988
+ )
989
+ num_warmup_steps = max(len(timesteps) - num_inference_steps * self.scheduler.order, 0)
990
+ self._num_timesteps = len(timesteps)
991
+
992
+ # handle guidance
993
+ if self.transformer.config.guidance_embeds:
994
+ guidance = torch.full([1], guidance_scale, device=device, dtype=torch.float32)
995
+ guidance = guidance.expand(latents.shape[0])
996
+ else:
997
+ guidance = None
998
+
999
+ if (ip_adapter_image is not None or ip_adapter_image_embeds is not None) and (
1000
+ negative_ip_adapter_image is None and negative_ip_adapter_image_embeds is None
1001
+ ):
1002
+ negative_ip_adapter_image = np.zeros((width, height, 3), dtype=np.uint8)
1003
+ negative_ip_adapter_image = [negative_ip_adapter_image] * self.transformer.encoder_hid_proj.num_ip_adapters
1004
+
1005
+ elif (ip_adapter_image is None and ip_adapter_image_embeds is None) and (
1006
+ negative_ip_adapter_image is not None or negative_ip_adapter_image_embeds is not None
1007
+ ):
1008
+ ip_adapter_image = np.zeros((width, height, 3), dtype=np.uint8)
1009
+ ip_adapter_image = [ip_adapter_image] * self.transformer.encoder_hid_proj.num_ip_adapters
1010
+
1011
+ if self.joint_attention_kwargs is None:
1012
+ self._joint_attention_kwargs = {}
1013
+
1014
+ image_embeds = None
1015
+ negative_image_embeds = None
1016
+ if ip_adapter_image is not None or ip_adapter_image_embeds is not None:
1017
+ image_embeds = self.prepare_ip_adapter_image_embeds(
1018
+ ip_adapter_image,
1019
+ ip_adapter_image_embeds,
1020
+ device,
1021
+ batch_size * num_images_per_prompt,
1022
+ )
1023
+ if negative_ip_adapter_image is not None or negative_ip_adapter_image_embeds is not None:
1024
+ negative_image_embeds = self.prepare_ip_adapter_image_embeds(
1025
+ negative_ip_adapter_image,
1026
+ negative_ip_adapter_image_embeds,
1027
+ device,
1028
+ batch_size * num_images_per_prompt,
1029
+ )
1030
+
1031
+ # 6. Denoising loop
1032
+ with self.progress_bar(total=num_inference_steps) as progress_bar:
1033
+ for i, t in enumerate(timesteps):
1034
+ if self.interrupt:
1035
+ continue
1036
+
1037
+ self._current_timestep = t
1038
+ if image_embeds is not None:
1039
+ self._joint_attention_kwargs["ip_adapter_image_embeds"] = image_embeds
1040
+
1041
+ latent_model_input = latents
1042
+ if image_latents is not None:
1043
+ latent_model_input = torch.cat([latents, image_latents], dim=1)
1044
+ timestep = t.expand(latents.shape[0]).to(latents.dtype)
1045
+
1046
+ noise_pred = self.transformer(
1047
+ hidden_states=latent_model_input,
1048
+ timestep=timestep / 1000,
1049
+ guidance=guidance,
1050
+ pooled_projections=pooled_prompt_embeds,
1051
+ encoder_hidden_states=prompt_embeds,
1052
+ txt_ids=text_ids,
1053
+ img_ids=latent_ids,
1054
+ joint_attention_kwargs=self.joint_attention_kwargs,
1055
+ return_dict=False,
1056
+ )[0]
1057
+ noise_pred = noise_pred[:, : latents.size(1)]
1058
+
1059
+ if do_true_cfg:
1060
+ if negative_image_embeds is not None:
1061
+ self._joint_attention_kwargs["ip_adapter_image_embeds"] = negative_image_embeds
1062
+ neg_noise_pred = self.transformer(
1063
+ hidden_states=latent_model_input,
1064
+ timestep=timestep / 1000,
1065
+ guidance=guidance,
1066
+ pooled_projections=negative_pooled_prompt_embeds,
1067
+ encoder_hidden_states=negative_prompt_embeds,
1068
+ txt_ids=negative_text_ids,
1069
+ img_ids=latent_ids,
1070
+ joint_attention_kwargs=self.joint_attention_kwargs,
1071
+ return_dict=False,
1072
+ )[0]
1073
+ neg_noise_pred = neg_noise_pred[:, : latents.size(1)]
1074
+ noise_pred = neg_noise_pred + true_cfg_scale * (noise_pred - neg_noise_pred)
1075
+
1076
+ # compute the previous noisy sample x_t -> x_t-1
1077
+ latents_dtype = latents.dtype
1078
+ latents = self.scheduler.step(noise_pred, t, latents, return_dict=False)[0]
1079
+
1080
+ if latents.dtype != latents_dtype:
1081
+ if torch.backends.mps.is_available():
1082
+ # some platforms (eg. apple mps) misbehave due to a pytorch bug: https://github.com/pytorch/pytorch/pull/99272
1083
+ latents = latents.to(latents_dtype)
1084
+
1085
+ if callback_on_step_end is not None:
1086
+ callback_kwargs = {}
1087
+ for k in callback_on_step_end_tensor_inputs:
1088
+ callback_kwargs[k] = locals()[k]
1089
+ callback_outputs = callback_on_step_end(self, i, t, callback_kwargs)
1090
+
1091
+ latents = callback_outputs.pop("latents", latents)
1092
+ prompt_embeds = callback_outputs.pop("prompt_embeds", prompt_embeds)
1093
+
1094
+ # call the callback, if provided
1095
+ if i == len(timesteps) - 1 or ((i + 1) > num_warmup_steps and (i + 1) % self.scheduler.order == 0):
1096
+ progress_bar.update()
1097
+
1098
+ if XLA_AVAILABLE:
1099
+ xm.mark_step()
1100
+
1101
+ self._current_timestep = None
1102
+
1103
+ if output_type == "latent":
1104
+ image = latents
1105
+ else:
1106
+ latents = self._unpack_latents(latents, height, width, self.vae_scale_factor)
1107
+ latents = (latents / self.vae.config.scaling_factor) + self.vae.config.shift_factor
1108
+ image = self.vae.decode(latents, return_dict=False)[0]
1109
+ image = self.image_processor.postprocess(image, output_type=output_type)
1110
+
1111
+ # Offload all models
1112
+ self.maybe_free_model_hooks()
1113
+
1114
+ if not return_dict:
1115
+ return (image,)
1116
+
1117
+ return FluxPipelineOutput(images=image)