LPX55 commited on
Commit
ae7e181
Β·
1 Parent(s): ba02a5b

refactor: revert back to old method

Browse files
Files changed (7) hide show
  1. app.py +96 -338
  2. controlnet_flux.py +7 -7
  3. controlnet_flux2.py +420 -0
  4. pipeline_flux_cnet.py +1051 -0
  5. test_app.py +374 -0
  6. transformer_flux.py +124 -7
  7. transformer_flux2.py +530 -0
app.py CHANGED
@@ -1,373 +1,131 @@
1
- import spaces
2
  import os
3
  import gradio as gr
4
  import torch
5
- import numpy as np
6
- import cv2
7
- import safetensors
8
- from PIL import Image, ImageDraw
9
- from diffusers import AutoencoderKL
10
  from diffusers.utils import load_image, check_min_version
11
  from controlnet_flux import FluxControlNetModel
12
- from pipeline_flux_controlnet_inpaint import FluxControlNetInpaintingPipeline
13
- from transformers import AutoProcessor, pipeline, AutoModelForMaskGeneration
14
- from diffusers.models.attention_processor import Attention
15
- from dataclasses import dataclass
16
- from typing import Any, List, Dict, Optional, Union, Tuple
17
- from diffusers import BitsAndBytesConfig as DiffusersBitsAndBytesConfig, FluxTransformer2DModel, FluxPipeline
18
- from transformers import BitsAndBytesConfig as BitsAndBytesConfig, T5EncoderModel
19
 
 
20
  # Ensure that the minimal version of diffusers is installed
21
  check_min_version("0.30.2")
22
- HF_TOKEN = os.getenv("HF_TOKEN")
23
- os.environ['PYTORCH_NO_CUDA_MEMORY_CACHING'] = '1'
24
- dtype = torch.bfloat16
25
-
26
- good_vae = AutoencoderKL.from_pretrained("black-forest-labs/FLUX.1-dev",
27
- subfolder="vae",
28
- torch_dtype=dtype,
29
- use_safetensors=True,
30
- token=HF_TOKEN
31
- ).to("cuda")
32
-
33
- # quant_config = DiffusersBitsAndBytesConfig(load_in_8bit=True)
34
- # transformer_8bit = FluxTransformer2DModel.from_pretrained(
35
- # "black-forest-labs/FLUX.1-dev",
36
- # subfolder="transformer",
37
- # quantization_config=quant_config,
38
- # torch_dtype=dtype,
39
- # token=HF_TOKEN
40
- # )
41
 
42
- # Quantize the text encoder to 8-bit precision
43
- quant_config = BitsAndBytesConfig(load_in_8bit=True)
44
- text_encoder_8bit = T5EncoderModel.from_pretrained(
45
- "black-forest-labs/FLUX.1-dev",
46
- subfolder="text_encoder_2",
47
- quantization_config=quant_config,
48
- torch_dtype=torch.float16,
 
 
 
49
  token=HF_TOKEN
50
  )
51
-
52
- # # Load necessary models and processors
53
- # controlnet = FluxControlNetModel.from_pretrained("alimama-creative/FLUX.1-dev-Controlnet-Inpainting-Beta", torch_dtype=torch.bfloat16)
54
- # pipe = FluxControlNetInpaintingPipeline.from_pretrained(
55
- # "LPX55/FLUX.1-merged_uncensored",
56
- # vae=good_vae,
57
- # # transformer=transformer_8bit,
58
- # controlnet=controlnet,
59
- # torch_dtype=dtype,
60
- # use_safetensors=True,
61
- # token=HF_TOKEN
62
- # ).to("cuda")
63
-
64
-
65
- controlnet = FluxControlNetModel.from_pretrained("alimama-creative/FLUX.1-dev-Controlnet-Inpainting-Beta", torch_dtype=torch.bfloat16)
66
  pipe = FluxControlNetInpaintingPipeline.from_pretrained(
67
  "black-forest-labs/FLUX.1-dev",
68
  controlnet=controlnet,
69
- torch_dtype=torch.bfloat16
 
 
70
  ).to("cuda")
71
  pipe.transformer.to(torch.bfloat16)
72
  pipe.controlnet.to(torch.bfloat16)
73
- pipe.text_encoder_2 = text_encoder_8bit
74
- base_attn_procs = pipe.transformer.attn_processors.copy()
75
 
76
- detector_id = "IDEA-Research/grounding-dino-tiny"
77
- segmenter_id = "facebook/sam-vit-base"
78
-
79
- segmentator = AutoModelForMaskGeneration.from_pretrained(segmenter_id).cuda()
80
- segment_processor = AutoProcessor.from_pretrained(segmenter_id)
81
- object_detector = pipeline(model=detector_id, task="zero-shot-object-detection", device=torch.device("cuda"))
82
-
83
-
84
- @dataclass
85
- class BoundingBox:
86
- xmin: int
87
- ymin: int
88
- xmax: int
89
- ymax: int
90
- @property
91
- def xyxy(self) -> List[float]:
92
- return [self.xmin, self.ymin, self.xmax, self.ymax]
93
-
94
- @dataclass
95
- class DetectionResult:
96
- score: float
97
- label: str
98
- box: BoundingBox
99
- mask: Optional[np.array] = None
100
- @classmethod
101
- def from_dict(cls, detection_dict: Dict) -> 'DetectionResult':
102
- return cls(score=detection_dict['score'],
103
- label=detection_dict['label'],
104
- box=BoundingBox(xmin=detection_dict['box']['xmin'],
105
- ymin=detection_dict['box']['ymin'],
106
- xmax=detection_dict['box']['xmax'],
107
- ymax=detection_dict['box']['ymax']))
108
-
109
- def mask_to_polygon(mask: np.ndarray) -> List[List[int]]:
110
- contours, _ = cv2.findContours(mask.astype(np.uint8), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
111
- if not contours:
112
- return []
113
- largest_contour = max(contours, key=cv2.contourArea)
114
- polygon = largest_contour.reshape(-1, 2).tolist()
115
- return polygon
116
-
117
- def polygon_to_mask(polygon: List[Tuple[int, int]], image_shape: Tuple[int, int]) -> np.ndarray:
118
- mask = np.zeros(image_shape, dtype=np.uint8)
119
- pts = np.array(polygon, dtype=np.int32)
120
- cv2.fillPoly(mask, [pts], color=(255,))
121
- return mask
122
-
123
- def get_boxes(results: List[DetectionResult]) -> List[List[List[float]]]:
124
- boxes = []
125
- for result in results:
126
- xyxy = result.box.xyxy
127
- boxes.append(xyxy)
128
- return [boxes]
129
-
130
- def refine_masks(masks: torch.BoolTensor, polygon_refinement: bool = False) -> List[np.ndarray]:
131
- masks = masks.cpu().float()
132
- masks = masks.permute(0, 2, 3, 1)
133
- masks = masks.mean(axis=-1)
134
- masks = (masks > 0).int()
135
- masks = masks.numpy().astype(np.uint8)
136
- masks = list(masks)
137
- if polygon_refinement:
138
- for idx, mask in enumerate(masks):
139
- shape = mask.shape
140
- polygon = mask_to_polygon(mask)
141
- mask = polygon_to_mask(polygon, shape)
142
- masks[idx] = mask
143
- return masks
144
-
145
- def detect(
146
- object_detector,
147
- image: Image.Image,
148
- labels: List[str],
149
- threshold: float = 0.3,
150
- detector_id: Optional[str] = None
151
- ) -> List[Dict[str, Any]]:
152
- device = "cuda" if torch.cuda.is_available() else "cpu"
153
- detector_id = detector_id if detector_id is not None else detector_id
154
- labels = [label if label.endswith(".") else label+"." for label in labels]
155
- results = object_detector(image, candidate_labels=labels, threshold=threshold)
156
- results = [DetectionResult.from_dict(result) for result in results]
157
- return results
158
-
159
- def segment(
160
- segmentator,
161
- processor,
162
- image_tensor: torch.Tensor,
163
- detection_results: List[Dict[str, Any]],
164
- polygon_refinement: bool = False
165
- ) -> List[DetectionResult]:
166
- device = image_tensor.device
167
-
168
- boxes = get_boxes(detection_results)
169
-
170
- # Convert image tensor to float32 for processing
171
- image_tensor_float32 = image_tensor.to(torch.float32)
172
-
173
- inputs = processor(images=image_tensor_float32, input_boxes=boxes, return_tensors="pt", torch_dtype=torch.float32)
174
-
175
- # Process inputs and get outputs
176
- outputs = segmentator(**inputs)
177
-
178
- # Convert masks to bfloat16 if needed
179
- masks = outputs.pred_masks.to(torch.bfloat16)
180
-
181
- masks = processor.post_process_masks(
182
- masks=masks,
183
- original_sizes=inputs.original_sizes,
184
- reshaped_input_sizes=inputs.reshaped_input_sizes
185
- )[0]
186
-
187
- masks = refine_masks(masks, polygon_refinement)
188
-
189
- for detection_result, mask in zip(detection_results, masks):
190
- detection_result.mask = mask
191
-
192
- return detection_results
193
-
194
- def grounded_segmentation(
195
- detect_pipeline,
196
- segmentator,
197
- segment_processor,
198
- image: Union[Image.Image, str],
199
- labels: List[str],
200
- threshold: float = 0.3,
201
- polygon_refinement: bool = False,
202
- detector_id: Optional[str] = None,
203
- segmenter_id: Optional[str] = None
204
- ) -> Tuple[np.ndarray, List[DetectionResult]]:
205
- if isinstance(image, str):
206
- image = load_image(image)
207
-
208
- # Convert image to tensor and to float32 for processing
209
- image_tensor = torch.tensor(np.array(image), dtype=torch.float32, device="cuda").permute(2, 0, 1).unsqueeze(0) / 255.0
210
-
211
- detections = detect(detect_pipeline, image, labels, threshold, detector_id)
212
- detections = segment(segmentator, segment_processor, image_tensor, detections, polygon_refinement)
213
-
214
- # Convert image tensor back to numpy array for return
215
- image_array = image_tensor.squeeze(0).permute(1, 2, 0).cpu().numpy() * 255
216
- image_array = image_array.astype(np.uint8)
217
-
218
- return image_array, detections
219
-
220
- class CustomFluxAttnProcessor2_0:
221
- def __init__(self, height=44, width=88, attn_enforce=1.0):
222
- if not hasattr(torch.nn.functional, "scaled_dot_product_attention"):
223
- raise ImportError("FluxAttnProcessor2_0 requires PyTorch 2.0, to use it, please upgrade PyTorch to 2.0.")
224
- self.height = height
225
- self.width = width
226
- self.num_pixels = height * width
227
- self.step = 0
228
- self.attn_enforce = attn_enforce
229
-
230
- def __call__(
231
- self,
232
- attn: Attention,
233
- hidden_states: torch.FloatTensor,
234
- encoder_hidden_states: torch.FloatTensor = None,
235
- attention_mask: Optional[torch.FloatTensor] = None,
236
- image_rotary_emb: Optional[torch.Tensor] = None,
237
- ) -> torch.FloatTensor:
238
- self.step += 1
239
- batch_size, _, _ = hidden_states.shape if encoder_hidden_states is None else encoder_hidden_states.shape
240
- query = attn.to_q(hidden_states)
241
- key = attn.to_k(hidden_states)
242
- value = attn.to_v(hidden_states)
243
- inner_dim = key.shape[-1]
244
- head_dim = inner_dim // attn.heads
245
- query = query.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
246
- key = key.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
247
- value = value.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
248
- if attn.norm_q is not None:
249
- query = attn.norm_q(query)
250
- if attn.norm_k is not None:
251
- key = attn.norm_k(key)
252
- if encoder_hidden_states is not None:
253
- encoder_hidden_states_query_proj = attn.add_q_proj(encoder_hidden_states)
254
- encoder_hidden_states_key_proj = attn.add_k_proj(encoder_hidden_states)
255
- encoder_hidden_states_value_proj = attn.add_v_proj(encoder_hidden_states)
256
- encoder_hidden_states_query_proj = encoder_hidden_states_query_proj.view(
257
- batch_size, -1, attn.heads, head_dim
258
- ).transpose(1, 2)
259
- encoder_hidden_states_key_proj = encoder_hidden_states_key_proj.view(
260
- batch_size, -1, attn.heads, head_dim
261
- ).transpose(1, 2)
262
- encoder_hidden_states_value_proj = encoder_hidden_states_value_proj.view(
263
- batch_size, -1, attn.heads, head_dim
264
- ).transpose(1, 2)
265
- if attn.norm_added_q is not None:
266
- encoder_hidden_states_query_proj = attn.norm_added_q(encoder_hidden_states_query_proj)
267
- if attn.norm_added_k is not None:
268
- encoder_hidden_states_key_proj = attn.norm_added_k(encoder_hidden_states_key_proj)
269
- query = torch.cat([encoder_hidden_states_query_proj, query], dim=2)
270
- key = torch.cat([encoder_hidden_states_key_proj, key], dim=2)
271
- value = torch.cat([encoder_hidden_states_value_proj, value], dim=2)
272
- if image_rotary_emb is not None:
273
- from diffusers.models.embeddings import apply_rotary_emb
274
- query = apply_rotary_emb(query, image_rotary_emb)
275
- key = apply_rotary_emb(key, image_rotary_emb)
276
- if self.attn_enforce != 1.0:
277
- attn_probs = (torch.einsum('bhqd,bhkd->bhqk', query, key) * attn.scale).softmax(dim=-1)
278
- img_attn_probs = attn_probs[:, :, -self.num_pixels:, -self.num_pixels:]
279
- img_attn_probs = img_attn_probs.reshape((batch_size, attn.heads, self.height, self.width, self.height, self.width))
280
- img_attn_probs[:, :, :, self.width//2:, :, :self.width//2] *= self.attn_enforce
281
- img_attn_probs = img_attn_probs.reshape((batch_size, attn.heads, self.num_pixels, self.num_pixels))
282
- attn_probs[:, :, -self.num_pixels:, -self.num_pixels:] = img_attn_probs
283
- hidden_states = torch.einsum('bhqk,bhkd->bhqd', attn_probs, value)
284
- else:
285
- hidden_states = torch.nn.functional.scaled_dot_product_attention(query, key, value, dropout_p=0.0, is_causal=False)
286
- hidden_states = hidden_states.transpose(1, 2).reshape(batch_size, -1, attn.heads * head_dim)
287
- hidden_states = hidden_states.to(query.dtype)
288
- if encoder_hidden_states is not None:
289
- encoder_hidden_states, hidden_states = (
290
- hidden_states[:, : encoder_hidden_states.shape[1]],
291
- hidden_states[:, encoder_hidden_states.shape[1] :],
292
- )
293
- hidden_states = attn.to_out[0](hidden_states)
294
- hidden_states = attn.to_out[1](hidden_states)
295
- encoder_hidden_states = attn.to_add_out(encoder_hidden_states)
296
- return hidden_states, encoder_hidden_states
297
- else:
298
- return hidden_states
299
-
300
- def segment_image(image, object_name):
301
- image_array, detections = grounded_segmentation(
302
- object_detector,
303
- segmentator,
304
- segment_processor,
305
- image=image,
306
- labels=object_name,
307
- threshold=0.3,
308
- polygon_refinement=True,
309
- )
310
- segment_result = image_array * np.expand_dims((255 - detections[0].mask) / 255, axis=-1)
311
- segmented_image = Image.fromarray(segment_result.astype(np.uint8))
312
- return segmented_image
313
-
314
- def make_diptych(image):
315
- ref_image = np.array(image)
316
- ref_image = np.concatenate([ref_image, np.zeros_like(ref_image)], axis=1)
317
- ref_image = Image.fromarray(ref_image)
318
- return ref_image
319
 
320
  @spaces.GPU()
321
- def inpaint_image(image, prompt, object_name):
322
- width = 512
323
- height = 512
324
- size = (width * 2, height)
325
- diptych_text_prompt = f"A diptych with two side-by-side images of same {object_name}. On the left, a photo of {object_name}. On the right, {prompt}"
326
- reference_image = image.resize((width, height)).convert("RGB")
327
- segmented_image = segment_image(reference_image, object_name)
328
- mask_image = np.concatenate([np.zeros((height, width, 3)), np.ones((height, width, 3))*255], axis=1)
329
- mask_image = Image.fromarray(mask_image.astype(np.uint8))
330
- diptych_image_prompt = make_diptych(segmented_image)
331
-
332
- base_attn_procs = pipe.transformer.attn_processors.copy()
333
- new_attn_procs = base_attn_procs.copy()
334
- for i, (k, v) in enumerate(new_attn_procs.items()):
335
- new_attn_procs[k] = CustomFluxAttnProcessor2_0(height=height // 16, width=width // 16 * 2, attn_enforce=1.3)
336
- pipe.transformer.set_attn_processor(new_attn_procs)
337
- generator = torch.Generator(device="cuda").manual_seed(42)
338
- with torch.no_grad():
339
- result = pipe(
340
- prompt=diptych_text_prompt,
341
- height=size[1],
342
- width=size[0],
343
- control_image=diptych_image_prompt,
344
- control_mask=mask_image,
345
- num_inference_steps=20,
346
- generator=generator,
347
- controlnet_conditioning_scale=0.95,
348
- guidance_scale=3.5,
349
- negative_prompt="",
350
- true_guidance_scale=3.5
351
- ).images[0]
352
- result = result.crop((width, 0, width*2, height))
353
-
354
- torch.cuda.empty_cache()
355
- return result, diptych_image_prompt
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
356
 
357
  # Create Gradio interface
358
  iface = gr.Interface(
359
  fn=inpaint_image,
360
  inputs=[
361
  gr.Image(type="pil", label="Upload Image"),
362
- gr.Textbox(lines=3, value="replicate this {subject_name} exactly but as a photo of the {subject_name} surfing on the beach", label="Prompt"),
363
- gr.Textbox(lines=1, value="bear plushie", label="Subject Name")
364
  ],
365
  outputs=[
366
  gr.Image(type="pil", label="Inpainted Image"),
367
  gr.Image(type="pil", label="Diptych Image")
368
  ],
369
  title="FLUX Inpainting with Diptych Prompting",
370
- description="Upload an image, specify a prompt, and provide the subject name. The app will automatically generate the inpainted image."
371
  )
372
 
373
  # Launch the app
 
 
1
  import os
2
  import gradio as gr
3
  import torch
 
 
 
 
 
4
  from diffusers.utils import load_image, check_min_version
5
  from controlnet_flux import FluxControlNetModel
6
+ from transformer_flux import FluxTransformer2DModel
7
+ from pipeline_flux_cnet import FluxControlNetInpaintingPipeline
8
+ from PIL import Image, ImageDraw
9
+ import numpy as np
 
 
 
10
 
11
+ HF_TOKEN = os.getenv("HF_TOKEN")
12
  # Ensure that the minimal version of diffusers is installed
13
  check_min_version("0.30.2")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
14
 
15
+ # Build pipeline
16
+ controlnet = FluxControlNetModel.from_pretrained(
17
+ "alimama-creative/FLUX.1-dev-Controlnet-Inpainting-Beta",
18
+ torch_dtype=torch.bfloat16,
19
+ token=HF_TOKEN
20
+ )
21
+ transformer = FluxTransformer2DModel.from_pretrained(
22
+ "black-forest-labs/FLUX.1-dev",
23
+ subfolder='transformer',
24
+ torch_dtype=torch.bfloat16,
25
  token=HF_TOKEN
26
  )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
27
  pipe = FluxControlNetInpaintingPipeline.from_pretrained(
28
  "black-forest-labs/FLUX.1-dev",
29
  controlnet=controlnet,
30
+ transformer=transformer,
31
+ torch_dtype=torch.bfloat16,
32
+ token=HF_TOKEN
33
  ).to("cuda")
34
  pipe.transformer.to(torch.bfloat16)
35
  pipe.controlnet.to(torch.bfloat16)
 
 
36
 
37
+ def create_mask_from_editor(editor_value):
38
+ """
39
+ Create a mask from the ImageEditor value.
40
+ Args:
41
+ editor_value: Dictionary from EditorValue with 'background', 'layers', and 'composite'
42
+ Returns:
43
+ PIL Image with white mask
44
+ """
45
+ # The 'composite' key contains the final image with all layers applied
46
+ composite_image = editor_value['composite']
47
+ # Convert to numpy array
48
+ composite_array = np.array(composite_image)
49
+ # Create mask where the composite image is white
50
+ mask_array = np.all(composite_array == (255, 255, 255), axis=-1).astype(np.uint8) * 255
51
+ mask_image = Image.fromarray(mask_array)
52
+ return mask_image
53
+
54
+ def create_diptych_image(image, mask):
55
+ # Create a diptych image with original on left and masked on right
56
+ width, height = image.size
57
+ diptych = Image.new('RGB', (width * 2, height), 'black')
58
+ diptych.paste(image, (0, 0))
59
+ diptych.paste(mask, (width, 0))
60
+ return diptych
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
61
 
62
  @spaces.GPU()
63
+ def inpaint_image(image, prompt, editor_value):
64
+ # Create mask from editor value
65
+ mask = create_mask_from_editor(editor_value)
66
+
67
+ # Load and preprocess image
68
+ image = image.convert("RGB").resize((768, 768))
69
+ mask = mask.convert("L").resize((768, 768)) # Convert mask to single channel (grayscale)
70
+
71
+ # Create diptych image
72
+ diptych_image = create_diptych_image(image, mask)
73
+
74
+ # Preprocess prompt and image for the pipeline
75
+ prompt = pipe.tokenizer(prompt, return_tensors="pt", padding=True, truncation=True).input_ids.to("cuda")
76
+ image_tensor = pipe.feature_extractor(images=image, return_tensors="pt").pixel_values.to("cuda")
77
+ mask_tensor = pipe.feature_extractor(images=mask, return_tensors="pt").pixel_values.to("cuda")
78
+ control_image_tensor = pipe.feature_extractor(images=diptych_image, return_tensors="pt").pixel_values.to("cuda")
79
+
80
+ generator = torch.Generator(device="cuda").manual_seed(24)
81
+
82
+ # Calculate attention scale mask
83
+ attn_scale_factor = 1.5
84
+ size = (1536, 768)
85
+ H, W = size[1] // 16, size[0] // 16
86
+ attn_scale_mask = torch.zeros(size[1], size[0])
87
+ attn_scale_mask[:, 768:] = 1.0 # height, width
88
+ attn_scale_mask = torch.nn.functional.interpolate(attn_scale_mask[None, None, :, :], (H, W), mode='nearest-exact').flatten()
89
+ attn_scale_mask = attn_scale_mask[None, None, :, None].repeat(1, 24, 1, H*W)
90
+ transposed_inverted_attn_scale_mask = (1.0 - attn_scale_mask).transpose(-1, -2)
91
+ cross_attn_region = torch.logical_and(attn_scale_mask, transposed_inverted_attn_scale_mask)
92
+ cross_attn_region = cross_attn_region * attn_scale_factor
93
+ cross_attn_region[cross_attn_region < 1.0] = 1.0
94
+ full_attn_scale_mask = torch.ones(1, 24, 512+H*W, 512+H*W)
95
+ full_attn_scale_mask[:, :, 512:, 512:] = cross_attn_region
96
+ full_attn_scale_mask = full_attn_scale_mask.to(device=pipe.transformer.device, dtype=torch.bfloat16)
97
+
98
+ # Inpaint
99
+ result = pipe(
100
+ prompt=prompt,
101
+ height=size[1],
102
+ width=size[0],
103
+ control_image=control_image_tensor,
104
+ control_mask=mask_tensor,
105
+ num_inference_steps=20,
106
+ generator=generator,
107
+ controlnet_conditioning_scale=0.95,
108
+ guidance_scale=3.5,
109
+ negative_prompt="",
110
+ true_guidance_scale=1.0,
111
+ attn_scale_mask=full_attn_scale_mask,
112
+ ).images[0]
113
+ return result, diptych_image
114
 
115
  # Create Gradio interface
116
  iface = gr.Interface(
117
  fn=inpaint_image,
118
  inputs=[
119
  gr.Image(type="pil", label="Upload Image"),
120
+ gr.Textbox(lines=1, placeholder="Enter your prompt here (e.g., 'wearing a christmas hat, in a busy street')", label="Prompt"),
121
+ gr.ImageEditor(type="pil", label="Image with Mask", sources="upload", interactive=True)
122
  ],
123
  outputs=[
124
  gr.Image(type="pil", label="Inpainted Image"),
125
  gr.Image(type="pil", label="Diptych Image")
126
  ],
127
  title="FLUX Inpainting with Diptych Prompting",
128
+ description="Upload an image, specify a prompt, and draw a mask on the image. The app will automatically generate the inpainted image."
129
  )
130
 
131
  # Launch the app
controlnet_flux.py CHANGED
@@ -19,10 +19,10 @@ from diffusers.models.controlnet import BaseOutput, zero_module
19
  from diffusers.models.embeddings import (
20
  CombinedTimestepGuidanceTextProjEmbeddings,
21
  CombinedTimestepTextProjEmbeddings,
22
- FluxPosEmbed,
23
  )
24
  from diffusers.models.modeling_outputs import Transformer2DModelOutput
25
  from transformer_flux import (
 
26
  FluxSingleTransformerBlock,
27
  FluxTransformerBlock,
28
  )
@@ -59,10 +59,9 @@ class FluxControlNetModel(ModelMixin, ConfigMixin, PeftAdapterMixin):
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
- self.pos_embed = FluxPosEmbed(theta=10000, axes_dim=axes_dims_rope)
66
  text_time_guidance_cls = (
67
  CombinedTimestepGuidanceTextProjEmbeddings
68
  if guidance_embeds
@@ -296,8 +295,9 @@ class FluxControlNetModel(ModelMixin, ConfigMixin, PeftAdapterMixin):
296
 
297
  txt_ids = txt_ids.expand(img_ids.size(0), -1, -1)
298
  ids = torch.cat((txt_ids, img_ids), dim=1)
299
- image_rotary_emb = self.pos_embed(ids[0])
300
- # image_rotary_emb = torch.stack([self.pos_embed(id) for id in ids])
 
301
 
302
  block_samples = ()
303
  for _, block in enumerate(self.transformer_blocks):
 
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
  )
 
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
 
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
+ # import pdb; pdb.set_trace()
301
 
302
  block_samples = ()
303
  for _, block in enumerate(self.transformer_blocks):
controlnet_flux2.py ADDED
@@ -0,0 +1,420 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ FluxPosEmbed,
23
+ )
24
+ from diffusers.models.modeling_outputs import Transformer2DModelOutput
25
+ from transformer_flux import (
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
+ self.pos_embed = FluxPosEmbed(theta=10000, axes_dim=axes_dims_rope)
66
+ text_time_guidance_cls = (
67
+ CombinedTimestepGuidanceTextProjEmbeddings
68
+ if guidance_embeds
69
+ else CombinedTimestepTextProjEmbeddings
70
+ )
71
+ self.time_text_embed = text_time_guidance_cls(
72
+ embedding_dim=self.inner_dim, pooled_projection_dim=pooled_projection_dim
73
+ )
74
+
75
+ self.context_embedder = nn.Linear(joint_attention_dim, self.inner_dim)
76
+ self.x_embedder = nn.Linear(in_channels, self.inner_dim)
77
+
78
+ self.transformer_blocks = nn.ModuleList(
79
+ [
80
+ FluxTransformerBlock(
81
+ dim=self.inner_dim,
82
+ num_attention_heads=num_attention_heads,
83
+ attention_head_dim=attention_head_dim,
84
+ )
85
+ for _ in range(num_layers)
86
+ ]
87
+ )
88
+
89
+ self.single_transformer_blocks = nn.ModuleList(
90
+ [
91
+ FluxSingleTransformerBlock(
92
+ dim=self.inner_dim,
93
+ num_attention_heads=num_attention_heads,
94
+ attention_head_dim=attention_head_dim,
95
+ )
96
+ for _ in range(num_single_layers)
97
+ ]
98
+ )
99
+
100
+ # controlnet_blocks
101
+ self.controlnet_blocks = nn.ModuleList([])
102
+ for _ in range(len(self.transformer_blocks)):
103
+ self.controlnet_blocks.append(
104
+ zero_module(nn.Linear(self.inner_dim, self.inner_dim))
105
+ )
106
+
107
+ self.controlnet_single_blocks = nn.ModuleList([])
108
+ for _ in range(len(self.single_transformer_blocks)):
109
+ self.controlnet_single_blocks.append(
110
+ zero_module(nn.Linear(self.inner_dim, self.inner_dim))
111
+ )
112
+
113
+ self.controlnet_x_embedder = zero_module(
114
+ torch.nn.Linear(in_channels + extra_condition_channels, self.inner_dim)
115
+ )
116
+
117
+ self.gradient_checkpointing = False
118
+
119
+ @property
120
+ # Copied from diffusers.models.unets.unet_2d_condition.UNet2DConditionModel.attn_processors
121
+ def attn_processors(self):
122
+ r"""
123
+ Returns:
124
+ `dict` of attention processors: A dictionary containing all attention processors used in the model with
125
+ indexed by its weight name.
126
+ """
127
+ # set recursively
128
+ processors = {}
129
+
130
+ def fn_recursive_add_processors(name: str, module: torch.nn.Module, processors: Dict[str, AttentionProcessor]):
131
+ if hasattr(module, "get_processor"):
132
+ processors[f"{name}.processor"] = module.get_processor()
133
+
134
+ for sub_name, child in module.named_children():
135
+ fn_recursive_add_processors(f"{name}.{sub_name}", child, processors)
136
+
137
+ return processors
138
+
139
+ for name, module in self.named_children():
140
+ fn_recursive_add_processors(name, module, processors)
141
+
142
+ return processors
143
+
144
+ # Copied from diffusers.models.unets.unet_2d_condition.UNet2DConditionModel.set_attn_processor
145
+ def set_attn_processor(self, processor):
146
+ r"""
147
+ Sets the attention processor to use to compute attention.
148
+
149
+ Parameters:
150
+ processor (`dict` of `AttentionProcessor` or only `AttentionProcessor`):
151
+ The instantiated processor class or a dictionary of processor classes that will be set as the processor
152
+ for **all** `Attention` layers.
153
+
154
+ If `processor` is a dict, the key needs to define the path to the corresponding cross attention
155
+ processor. This is strongly recommended when setting trainable attention processors.
156
+
157
+ """
158
+ count = len(self.attn_processors.keys())
159
+
160
+ if isinstance(processor, dict) and len(processor) != count:
161
+ raise ValueError(
162
+ f"A dict of processors was passed, but the number of processors {len(processor)} does not match the"
163
+ f" number of attention layers: {count}. Please make sure to pass {count} processor classes."
164
+ )
165
+
166
+ def fn_recursive_attn_processor(name: str, module: torch.nn.Module, processor):
167
+ if hasattr(module, "set_processor"):
168
+ if not isinstance(processor, dict):
169
+ module.set_processor(processor)
170
+ else:
171
+ module.set_processor(processor.pop(f"{name}.processor"))
172
+
173
+ for sub_name, child in module.named_children():
174
+ fn_recursive_attn_processor(f"{name}.{sub_name}", child, processor)
175
+
176
+ for name, module in self.named_children():
177
+ fn_recursive_attn_processor(name, module, processor)
178
+
179
+ def _set_gradient_checkpointing(self, module, value=False):
180
+ if hasattr(module, "gradient_checkpointing"):
181
+ module.gradient_checkpointing = value
182
+
183
+ @classmethod
184
+ def from_transformer(
185
+ cls,
186
+ transformer,
187
+ num_layers: int = 4,
188
+ num_single_layers: int = 10,
189
+ attention_head_dim: int = 128,
190
+ num_attention_heads: int = 24,
191
+ load_weights_from_transformer=True,
192
+ ):
193
+ config = transformer.config
194
+ config["num_layers"] = num_layers
195
+ config["num_single_layers"] = num_single_layers
196
+ config["attention_head_dim"] = attention_head_dim
197
+ config["num_attention_heads"] = num_attention_heads
198
+
199
+ controlnet = cls(**config)
200
+
201
+ if load_weights_from_transformer:
202
+ controlnet.pos_embed.load_state_dict(transformer.pos_embed.state_dict())
203
+ controlnet.time_text_embed.load_state_dict(
204
+ transformer.time_text_embed.state_dict()
205
+ )
206
+ controlnet.context_embedder.load_state_dict(
207
+ transformer.context_embedder.state_dict()
208
+ )
209
+ controlnet.x_embedder.load_state_dict(transformer.x_embedder.state_dict())
210
+ controlnet.transformer_blocks.load_state_dict(
211
+ transformer.transformer_blocks.state_dict(), strict=False
212
+ )
213
+ controlnet.single_transformer_blocks.load_state_dict(
214
+ transformer.single_transformer_blocks.state_dict(), strict=False
215
+ )
216
+
217
+ controlnet.controlnet_x_embedder = zero_module(
218
+ controlnet.controlnet_x_embedder
219
+ )
220
+
221
+ return controlnet
222
+
223
+ def forward(
224
+ self,
225
+ hidden_states: torch.Tensor,
226
+ controlnet_cond: torch.Tensor,
227
+ conditioning_scale: float = 1.0,
228
+ encoder_hidden_states: torch.Tensor = None,
229
+ pooled_projections: torch.Tensor = None,
230
+ timestep: torch.LongTensor = None,
231
+ img_ids: torch.Tensor = None,
232
+ txt_ids: torch.Tensor = None,
233
+ guidance: torch.Tensor = None,
234
+ joint_attention_kwargs: Optional[Dict[str, Any]] = None,
235
+ return_dict: bool = True,
236
+ ) -> Union[torch.FloatTensor, Transformer2DModelOutput]:
237
+ """
238
+ The [`FluxTransformer2DModel`] forward method.
239
+
240
+ Args:
241
+ hidden_states (`torch.FloatTensor` of shape `(batch size, channel, height, width)`):
242
+ Input `hidden_states`.
243
+ encoder_hidden_states (`torch.FloatTensor` of shape `(batch size, sequence_len, embed_dims)`):
244
+ Conditional embeddings (embeddings computed from the input conditions such as prompts) to use.
245
+ pooled_projections (`torch.FloatTensor` of shape `(batch_size, projection_dim)`): Embeddings projected
246
+ from the embeddings of input conditions.
247
+ timestep ( `torch.LongTensor`):
248
+ Used to indicate denoising step.
249
+ block_controlnet_hidden_states: (`list` of `torch.Tensor`):
250
+ A list of tensors that if specified are added to the residuals of transformer blocks.
251
+ joint_attention_kwargs (`dict`, *optional*):
252
+ A kwargs dictionary that if specified is passed along to the `AttentionProcessor` as defined under
253
+ `self.processor` in
254
+ [diffusers.models.attention_processor](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py).
255
+ return_dict (`bool`, *optional*, defaults to `True`):
256
+ Whether or not to return a [`~models.transformer_2d.Transformer2DModelOutput`] instead of a plain
257
+ tuple.
258
+
259
+ Returns:
260
+ If `return_dict` is True, an [`~models.transformer_2d.Transformer2DModelOutput`] is returned, otherwise a
261
+ `tuple` where the first element is the sample tensor.
262
+ """
263
+ if joint_attention_kwargs is not None:
264
+ joint_attention_kwargs = joint_attention_kwargs.copy()
265
+ lora_scale = joint_attention_kwargs.pop("scale", 1.0)
266
+ else:
267
+ lora_scale = 1.0
268
+
269
+ if USE_PEFT_BACKEND:
270
+ # weight the lora layers by setting `lora_scale` for each PEFT layer
271
+ scale_lora_layers(self, lora_scale)
272
+ else:
273
+ if (
274
+ joint_attention_kwargs is not None
275
+ and joint_attention_kwargs.get("scale", None) is not None
276
+ ):
277
+ logger.warning(
278
+ "Passing `scale` via `joint_attention_kwargs` when not using the PEFT backend is ineffective."
279
+ )
280
+ hidden_states = self.x_embedder(hidden_states)
281
+
282
+ # add condition
283
+ hidden_states = hidden_states + self.controlnet_x_embedder(controlnet_cond)
284
+
285
+ timestep = timestep.to(hidden_states.dtype) * 1000
286
+ if guidance is not None:
287
+ guidance = guidance.to(hidden_states.dtype) * 1000
288
+ else:
289
+ guidance = None
290
+ temb = (
291
+ self.time_text_embed(timestep, pooled_projections)
292
+ if guidance is None
293
+ else self.time_text_embed(timestep, guidance, pooled_projections)
294
+ )
295
+ encoder_hidden_states = self.context_embedder(encoder_hidden_states)
296
+
297
+ txt_ids = txt_ids.expand(img_ids.size(0), -1, -1)
298
+ ids = torch.cat((txt_ids, img_ids), dim=1)
299
+ image_rotary_emb = self.pos_embed(ids[0])
300
+ # image_rotary_emb = torch.stack([self.pos_embed(id) for id in ids])
301
+
302
+ block_samples = ()
303
+ for _, block in enumerate(self.transformer_blocks):
304
+ if self.training and self.gradient_checkpointing:
305
+
306
+ def create_custom_forward(module, return_dict=None):
307
+ def custom_forward(*inputs):
308
+ if return_dict is not None:
309
+ return module(*inputs, return_dict=return_dict)
310
+ else:
311
+ return module(*inputs)
312
+
313
+ return custom_forward
314
+
315
+ ckpt_kwargs: Dict[str, Any] = (
316
+ {"use_reentrant": False} if is_torch_version(">=", "1.11.0") else {}
317
+ )
318
+ (
319
+ encoder_hidden_states,
320
+ hidden_states,
321
+ ) = torch.utils.checkpoint.checkpoint(
322
+ create_custom_forward(block),
323
+ hidden_states,
324
+ encoder_hidden_states,
325
+ temb,
326
+ image_rotary_emb,
327
+ **ckpt_kwargs,
328
+ )
329
+
330
+ else:
331
+ encoder_hidden_states, hidden_states = block(
332
+ hidden_states=hidden_states,
333
+ encoder_hidden_states=encoder_hidden_states,
334
+ temb=temb,
335
+ image_rotary_emb=image_rotary_emb,
336
+ )
337
+ block_samples = block_samples + (hidden_states,)
338
+
339
+ hidden_states = torch.cat([encoder_hidden_states, hidden_states], dim=1)
340
+
341
+ single_block_samples = ()
342
+ for _, block in enumerate(self.single_transformer_blocks):
343
+ if self.training and self.gradient_checkpointing:
344
+
345
+ def create_custom_forward(module, return_dict=None):
346
+ def custom_forward(*inputs):
347
+ if return_dict is not None:
348
+ return module(*inputs, return_dict=return_dict)
349
+ else:
350
+ return module(*inputs)
351
+
352
+ return custom_forward
353
+
354
+ ckpt_kwargs: Dict[str, Any] = (
355
+ {"use_reentrant": False} if is_torch_version(">=", "1.11.0") else {}
356
+ )
357
+ hidden_states = torch.utils.checkpoint.checkpoint(
358
+ create_custom_forward(block),
359
+ hidden_states,
360
+ temb,
361
+ image_rotary_emb,
362
+ **ckpt_kwargs,
363
+ )
364
+
365
+ else:
366
+ hidden_states = block(
367
+ hidden_states=hidden_states,
368
+ temb=temb,
369
+ image_rotary_emb=image_rotary_emb,
370
+ )
371
+ single_block_samples = single_block_samples + (
372
+ hidden_states[:, encoder_hidden_states.shape[1] :],
373
+ )
374
+
375
+ # controlnet block
376
+ controlnet_block_samples = ()
377
+ for block_sample, controlnet_block in zip(
378
+ block_samples, self.controlnet_blocks
379
+ ):
380
+ block_sample = controlnet_block(block_sample)
381
+ controlnet_block_samples = controlnet_block_samples + (block_sample,)
382
+
383
+ controlnet_single_block_samples = ()
384
+ for single_block_sample, controlnet_block in zip(
385
+ single_block_samples, self.controlnet_single_blocks
386
+ ):
387
+ single_block_sample = controlnet_block(single_block_sample)
388
+ controlnet_single_block_samples = controlnet_single_block_samples + (
389
+ single_block_sample,
390
+ )
391
+
392
+ # scaling
393
+ controlnet_block_samples = [
394
+ sample * conditioning_scale for sample in controlnet_block_samples
395
+ ]
396
+ controlnet_single_block_samples = [
397
+ sample * conditioning_scale for sample in controlnet_single_block_samples
398
+ ]
399
+
400
+ #
401
+ controlnet_block_samples = (
402
+ None if len(controlnet_block_samples) == 0 else controlnet_block_samples
403
+ )
404
+ controlnet_single_block_samples = (
405
+ None
406
+ if len(controlnet_single_block_samples) == 0
407
+ else controlnet_single_block_samples
408
+ )
409
+
410
+ if USE_PEFT_BACKEND:
411
+ # remove `lora_scale` from each PEFT layer
412
+ unscale_lora_layers(self, lora_scale)
413
+
414
+ if not return_dict:
415
+ return (controlnet_block_samples, controlnet_single_block_samples)
416
+
417
+ return FluxControlNetOutput(
418
+ controlnet_block_samples=controlnet_block_samples,
419
+ controlnet_single_block_samples=controlnet_single_block_samples,
420
+ )
pipeline_flux_cnet.py ADDED
@@ -0,0 +1,1051 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ attn_scale_mask: Optional[torch.FloatTensor] = None,
751
+ ):
752
+ r"""
753
+ Function invoked when calling the pipeline for generation.
754
+
755
+ Args:
756
+ prompt (`str` or `List[str]`, *optional*):
757
+ The prompt or prompts to guide the image generation. If not defined, one has to pass `prompt_embeds`.
758
+ instead.
759
+ prompt_2 (`str` or `List[str]`, *optional*):
760
+ The prompt or prompts to be sent to `tokenizer_2` and `text_encoder_2`. If not defined, `prompt` is
761
+ will be used instead
762
+ height (`int`, *optional*, defaults to self.unet.config.sample_size * self.vae_scale_factor):
763
+ The height in pixels of the generated image. This is set to 1024 by default for the best results.
764
+ width (`int`, *optional*, defaults to self.unet.config.sample_size * self.vae_scale_factor):
765
+ The width in pixels of the generated image. This is set to 1024 by default for the best results.
766
+ num_inference_steps (`int`, *optional*, defaults to 50):
767
+ The number of denoising steps. More denoising steps usually lead to a higher quality image at the
768
+ expense of slower inference.
769
+ timesteps (`List[int]`, *optional*):
770
+ Custom timesteps to use for the denoising process with schedulers which support a `timesteps` argument
771
+ in their `set_timesteps` method. If not defined, the default behavior when `num_inference_steps` is
772
+ passed will be used. Must be in descending order.
773
+ guidance_scale (`float`, *optional*, defaults to 7.0):
774
+ Guidance scale as defined in [Classifier-Free Diffusion Guidance](https://arxiv.org/abs/2207.12598).
775
+ `guidance_scale` is defined as `w` of equation 2. of [Imagen
776
+ Paper](https://arxiv.org/pdf/2205.11487.pdf). Guidance scale is enabled by setting `guidance_scale >
777
+ 1`. Higher guidance scale encourages to generate images that are closely linked to the text `prompt`,
778
+ usually at the expense of lower image quality.
779
+ num_images_per_prompt (`int`, *optional*, defaults to 1):
780
+ The number of images to generate per prompt.
781
+ generator (`torch.Generator` or `List[torch.Generator]`, *optional*):
782
+ One or a list of [torch generator(s)](https://pytorch.org/docs/stable/generated/torch.Generator.html)
783
+ to make generation deterministic.
784
+ latents (`torch.FloatTensor`, *optional*):
785
+ Pre-generated noisy latents, sampled from a Gaussian distribution, to be used as inputs for image
786
+ generation. Can be used to tweak the same generation with different prompts. If not provided, a latents
787
+ tensor will ge generated by sampling using the supplied random `generator`.
788
+ prompt_embeds (`torch.FloatTensor`, *optional*):
789
+ Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not
790
+ provided, text embeddings will be generated from `prompt` input argument.
791
+ pooled_prompt_embeds (`torch.FloatTensor`, *optional*):
792
+ Pre-generated pooled text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting.
793
+ If not provided, pooled text embeddings will be generated from `prompt` input argument.
794
+ output_type (`str`, *optional*, defaults to `"pil"`):
795
+ The output format of the generate image. Choose between
796
+ [PIL](https://pillow.readthedocs.io/en/stable/): `PIL.Image.Image` or `np.array`.
797
+ return_dict (`bool`, *optional*, defaults to `True`):
798
+ Whether or not to return a [`~pipelines.flux.FluxPipelineOutput`] instead of a plain tuple.
799
+ joint_attention_kwargs (`dict`, *optional*):
800
+ A kwargs dictionary that if specified is passed along to the `AttentionProcessor` as defined under
801
+ `self.processor` in
802
+ [diffusers.models.attention_processor](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py).
803
+ callback_on_step_end (`Callable`, *optional*):
804
+ A function that calls at the end of each denoising steps during the inference. The function is called
805
+ with the following arguments: `callback_on_step_end(self: DiffusionPipeline, step: int, timestep: int,
806
+ callback_kwargs: Dict)`. `callback_kwargs` will include a list of all tensors as specified by
807
+ `callback_on_step_end_tensor_inputs`.
808
+ callback_on_step_end_tensor_inputs (`List`, *optional*):
809
+ The list of tensor inputs for the `callback_on_step_end` function. The tensors specified in the list
810
+ will be passed as `callback_kwargs` argument. You will only be able to include variables listed in the
811
+ `._callback_tensor_inputs` attribute of your pipeline class.
812
+ max_sequence_length (`int` defaults to 512): Maximum sequence length to use with the `prompt`.
813
+
814
+ Examples:
815
+
816
+ Returns:
817
+ [`~pipelines.flux.FluxPipelineOutput`] or `tuple`: [`~pipelines.flux.FluxPipelineOutput`] if `return_dict`
818
+ is True, otherwise a `tuple`. When returning a tuple, the first element is a list with the generated
819
+ images.
820
+ """
821
+
822
+ height = height or self.default_sample_size * self.vae_scale_factor
823
+ width = width or self.default_sample_size * self.vae_scale_factor
824
+
825
+ # 1. Check inputs. Raise error if not correct
826
+ self.check_inputs(
827
+ prompt,
828
+ prompt_2,
829
+ height,
830
+ width,
831
+ prompt_embeds=prompt_embeds,
832
+ pooled_prompt_embeds=pooled_prompt_embeds,
833
+ callback_on_step_end_tensor_inputs=callback_on_step_end_tensor_inputs,
834
+ max_sequence_length=max_sequence_length,
835
+ )
836
+
837
+ self._guidance_scale = true_guidance_scale
838
+ self._joint_attention_kwargs = joint_attention_kwargs
839
+ self._interrupt = False
840
+
841
+ # 2. Define call parameters
842
+ if prompt is not None and isinstance(prompt, str):
843
+ batch_size = 1
844
+ elif prompt is not None and isinstance(prompt, list):
845
+ batch_size = len(prompt)
846
+ else:
847
+ batch_size = prompt_embeds.shape[0]
848
+
849
+ device = self._execution_device
850
+ dtype = self.transformer.dtype
851
+
852
+ lora_scale = (
853
+ self.joint_attention_kwargs.get("scale", None)
854
+ if self.joint_attention_kwargs is not None
855
+ else None
856
+ )
857
+ (
858
+ prompt_embeds,
859
+ pooled_prompt_embeds,
860
+ negative_prompt_embeds,
861
+ negative_pooled_prompt_embeds,
862
+ text_ids
863
+ ) = self.encode_prompt(
864
+ prompt=prompt,
865
+ prompt_2=prompt_2,
866
+ prompt_embeds=prompt_embeds,
867
+ pooled_prompt_embeds=pooled_prompt_embeds,
868
+ do_classifier_free_guidance = self.do_classifier_free_guidance,
869
+ negative_prompt = negative_prompt,
870
+ negative_prompt_2 = negative_prompt_2,
871
+ device=device,
872
+ num_images_per_prompt=num_images_per_prompt,
873
+ max_sequence_length=max_sequence_length,
874
+ lora_scale=lora_scale,
875
+ )
876
+
877
+ # 在 encode_prompt δΉ‹εŽ
878
+ if self.do_classifier_free_guidance:
879
+ prompt_embeds = torch.cat([negative_prompt_embeds, prompt_embeds], dim = 0)
880
+ pooled_prompt_embeds = torch.cat([negative_pooled_prompt_embeds, pooled_prompt_embeds], dim = 0)
881
+ text_ids = torch.cat([text_ids, text_ids], dim = 0)
882
+
883
+ # 3. Prepare control image
884
+ num_channels_latents = self.transformer.config.in_channels // 4
885
+ if isinstance(self.controlnet, FluxControlNetModel):
886
+ control_image, height, width = self.prepare_image_with_mask(
887
+ image=control_image,
888
+ mask=control_mask,
889
+ width=width,
890
+ height=height,
891
+ batch_size=batch_size * num_images_per_prompt,
892
+ num_images_per_prompt=num_images_per_prompt,
893
+ device=device,
894
+ dtype=dtype,
895
+ do_classifier_free_guidance=self.do_classifier_free_guidance,
896
+ )
897
+
898
+ # 4. Prepare latent variables
899
+ num_channels_latents = self.transformer.config.in_channels // 4
900
+ latents, latent_image_ids = self.prepare_latents(
901
+ batch_size * num_images_per_prompt,
902
+ num_channels_latents,
903
+ height,
904
+ width,
905
+ prompt_embeds.dtype,
906
+ device,
907
+ generator,
908
+ latents,
909
+ )
910
+
911
+ if self.do_classifier_free_guidance:
912
+ latent_image_ids = torch.cat([latent_image_ids] * 2)
913
+
914
+ # 5. Prepare timesteps
915
+ sigmas = np.linspace(1.0, 1 / num_inference_steps, num_inference_steps)
916
+ image_seq_len = latents.shape[1]
917
+ mu = calculate_shift(
918
+ image_seq_len,
919
+ self.scheduler.config.base_image_seq_len,
920
+ self.scheduler.config.max_image_seq_len,
921
+ self.scheduler.config.base_shift,
922
+ self.scheduler.config.max_shift,
923
+ )
924
+ timesteps, num_inference_steps = retrieve_timesteps(
925
+ self.scheduler,
926
+ num_inference_steps,
927
+ device,
928
+ timesteps,
929
+ sigmas,
930
+ mu=mu,
931
+ )
932
+
933
+ num_warmup_steps = max(
934
+ len(timesteps) - num_inference_steps * self.scheduler.order, 0
935
+ )
936
+ self._num_timesteps = len(timesteps)
937
+
938
+ # 6. Denoising loop
939
+ with self.progress_bar(total=num_inference_steps) as progress_bar:
940
+ for i, t in enumerate(timesteps):
941
+ if self.interrupt:
942
+ continue
943
+
944
+ latent_model_input = torch.cat([latents] * 2) if self.do_classifier_free_guidance else latents
945
+
946
+ # broadcast to batch dimension in a way that's compatible with ONNX/Core ML
947
+ timestep = t.expand(latent_model_input.shape[0]).to(latent_model_input.dtype)
948
+
949
+ # handle guidance
950
+ if self.transformer.config.guidance_embeds:
951
+ guidance = torch.tensor([guidance_scale], device=device)
952
+ guidance = guidance.expand(latent_model_input.shape[0])
953
+ else:
954
+ guidance = None
955
+
956
+ # controlnet
957
+ (
958
+ controlnet_block_samples,
959
+ controlnet_single_block_samples,
960
+ ) = self.controlnet(
961
+ hidden_states=latent_model_input,
962
+ controlnet_cond=control_image,
963
+ conditioning_scale=controlnet_conditioning_scale,
964
+ timestep=timestep / 1000,
965
+ guidance=guidance,
966
+ pooled_projections=pooled_prompt_embeds,
967
+ encoder_hidden_states=prompt_embeds,
968
+ txt_ids=text_ids,
969
+ img_ids=latent_image_ids,
970
+ joint_attention_kwargs=self.joint_attention_kwargs,
971
+ return_dict=False,
972
+ )
973
+
974
+ noise_pred = self.transformer(
975
+ hidden_states=latent_model_input,
976
+ # 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)
977
+ timestep=timestep / 1000,
978
+ guidance=guidance,
979
+ pooled_projections=pooled_prompt_embeds,
980
+ encoder_hidden_states=prompt_embeds,
981
+ controlnet_block_samples=[
982
+ sample.to(dtype=self.transformer.dtype)
983
+ for sample in controlnet_block_samples
984
+ ],
985
+ controlnet_single_block_samples=[
986
+ sample.to(dtype=self.transformer.dtype)
987
+ for sample in controlnet_single_block_samples
988
+ ] if controlnet_single_block_samples is not None else controlnet_single_block_samples,
989
+ txt_ids=text_ids,
990
+ img_ids=latent_image_ids,
991
+ joint_attention_kwargs=self.joint_attention_kwargs,
992
+ return_dict=False,
993
+ attn_scale_mask=attn_scale_mask,
994
+ )[0]
995
+
996
+ # εœ¨η”ŸζˆεΎͺ环中
997
+ if self.do_classifier_free_guidance:
998
+ noise_pred_uncond, noise_pred_text = noise_pred.chunk(2)
999
+ noise_pred = noise_pred_uncond + true_guidance_scale * (noise_pred_text - noise_pred_uncond)
1000
+
1001
+ # compute the previous noisy sample x_t -> x_t-1
1002
+ latents_dtype = latents.dtype
1003
+ latents = self.scheduler.step(
1004
+ noise_pred, t, latents, return_dict=False
1005
+ )[0]
1006
+
1007
+ if latents.dtype != latents_dtype:
1008
+ if torch.backends.mps.is_available():
1009
+ # some platforms (eg. apple mps) misbehave due to a pytorch bug: https://github.com/pytorch/pytorch/pull/99272
1010
+ latents = latents.to(latents_dtype)
1011
+
1012
+ if callback_on_step_end is not None:
1013
+ callback_kwargs = {}
1014
+ for k in callback_on_step_end_tensor_inputs:
1015
+ callback_kwargs[k] = locals()[k]
1016
+ callback_outputs = callback_on_step_end(self, i, t, callback_kwargs)
1017
+
1018
+ latents = callback_outputs.pop("latents", latents)
1019
+ prompt_embeds = callback_outputs.pop("prompt_embeds", prompt_embeds)
1020
+
1021
+ # call the callback, if provided
1022
+ if i == len(timesteps) - 1 or (
1023
+ (i + 1) > num_warmup_steps and (i + 1) % self.scheduler.order == 0
1024
+ ):
1025
+ progress_bar.update()
1026
+
1027
+ if XLA_AVAILABLE:
1028
+ xm.mark_step()
1029
+
1030
+ if output_type == "latent":
1031
+ image = latents
1032
+
1033
+ else:
1034
+ latents = self._unpack_latents(
1035
+ latents, height, width, self.vae_scale_factor
1036
+ )
1037
+ latents = (
1038
+ latents / self.vae.config.scaling_factor
1039
+ ) + self.vae.config.shift_factor
1040
+ latents = latents.to(self.vae.dtype)
1041
+
1042
+ image = self.vae.decode(latents, return_dict=False)[0]
1043
+ image = self.image_processor.postprocess(image, output_type=output_type)
1044
+
1045
+ # Offload all models
1046
+ self.maybe_free_model_hooks()
1047
+
1048
+ if not return_dict:
1049
+ return (image,)
1050
+
1051
+ return FluxPipelineOutput(images=image)
test_app.py ADDED
@@ -0,0 +1,374 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import spaces
2
+ import os
3
+ import gradio as gr
4
+ import torch
5
+ import numpy as np
6
+ import cv2
7
+ import safetensors
8
+ from PIL import Image, ImageDraw
9
+ from diffusers import AutoencoderKL
10
+ from diffusers.utils import load_image, check_min_version
11
+ from controlnet_flux import FluxControlNetModel
12
+ from pipeline_flux_controlnet_inpaint import FluxControlNetInpaintingPipeline
13
+ from transformers import AutoProcessor, pipeline, AutoModelForMaskGeneration
14
+ from diffusers.models.attention_processor import Attention
15
+ from dataclasses import dataclass
16
+ from typing import Any, List, Dict, Optional, Union, Tuple
17
+ from diffusers import BitsAndBytesConfig as DiffusersBitsAndBytesConfig, FluxTransformer2DModel, FluxPipeline
18
+ from transformers import BitsAndBytesConfig as BitsAndBytesConfig, T5EncoderModel
19
+
20
+ # Ensure that the minimal version of diffusers is installed
21
+ check_min_version("0.30.2")
22
+ HF_TOKEN = os.getenv("HF_TOKEN")
23
+ os.environ['PYTORCH_NO_CUDA_MEMORY_CACHING'] = '1'
24
+ dtype = torch.bfloat16
25
+
26
+ good_vae = AutoencoderKL.from_pretrained("black-forest-labs/FLUX.1-dev",
27
+ subfolder="vae",
28
+ torch_dtype=dtype,
29
+ use_safetensors=True,
30
+ token=HF_TOKEN
31
+ ).to("cuda")
32
+
33
+ # quant_config = DiffusersBitsAndBytesConfig(load_in_8bit=True)
34
+ # transformer_8bit = FluxTransformer2DModel.from_pretrained(
35
+ # "black-forest-labs/FLUX.1-dev",
36
+ # subfolder="transformer",
37
+ # quantization_config=quant_config,
38
+ # torch_dtype=dtype,
39
+ # token=HF_TOKEN
40
+ # )
41
+
42
+ # Quantize the text encoder to 8-bit precision
43
+ quant_config = BitsAndBytesConfig(load_in_8bit=True)
44
+ text_encoder_8bit = T5EncoderModel.from_pretrained(
45
+ "black-forest-labs/FLUX.1-dev",
46
+ subfolder="text_encoder_2",
47
+ quantization_config=quant_config,
48
+ torch_dtype=torch.float16,
49
+ token=HF_TOKEN
50
+ )
51
+
52
+ # # Load necessary models and processors
53
+ # controlnet = FluxControlNetModel.from_pretrained("alimama-creative/FLUX.1-dev-Controlnet-Inpainting-Beta", torch_dtype=torch.bfloat16)
54
+ # pipe = FluxControlNetInpaintingPipeline.from_pretrained(
55
+ # "LPX55/FLUX.1-merged_uncensored",
56
+ # vae=good_vae,
57
+ # # transformer=transformer_8bit,
58
+ # controlnet=controlnet,
59
+ # torch_dtype=dtype,
60
+ # use_safetensors=True,
61
+ # token=HF_TOKEN
62
+ # ).to("cuda")
63
+
64
+
65
+ controlnet = FluxControlNetModel.from_pretrained("alimama-creative/FLUX.1-dev-Controlnet-Inpainting-Beta", torch_dtype=torch.bfloat16)
66
+ pipe = FluxControlNetInpaintingPipeline.from_pretrained(
67
+ "black-forest-labs/FLUX.1-dev",
68
+ controlnet=controlnet,
69
+ torch_dtype=torch.bfloat16
70
+ ).to("cuda")
71
+ pipe.transformer.to(torch.bfloat16)
72
+ pipe.controlnet.to(torch.bfloat16)
73
+ pipe.text_encoder_2 = text_encoder_8bit
74
+ base_attn_procs = pipe.transformer.attn_processors.copy()
75
+
76
+ detector_id = "IDEA-Research/grounding-dino-tiny"
77
+ segmenter_id = "facebook/sam-vit-base"
78
+
79
+ segmentator = AutoModelForMaskGeneration.from_pretrained(segmenter_id).cuda()
80
+ segment_processor = AutoProcessor.from_pretrained(segmenter_id)
81
+ object_detector = pipeline(model=detector_id, task="zero-shot-object-detection", device=torch.device("cuda"))
82
+
83
+
84
+ @dataclass
85
+ class BoundingBox:
86
+ xmin: int
87
+ ymin: int
88
+ xmax: int
89
+ ymax: int
90
+ @property
91
+ def xyxy(self) -> List[float]:
92
+ return [self.xmin, self.ymin, self.xmax, self.ymax]
93
+
94
+ @dataclass
95
+ class DetectionResult:
96
+ score: float
97
+ label: str
98
+ box: BoundingBox
99
+ mask: Optional[np.array] = None
100
+ @classmethod
101
+ def from_dict(cls, detection_dict: Dict) -> 'DetectionResult':
102
+ return cls(score=detection_dict['score'],
103
+ label=detection_dict['label'],
104
+ box=BoundingBox(xmin=detection_dict['box']['xmin'],
105
+ ymin=detection_dict['box']['ymin'],
106
+ xmax=detection_dict['box']['xmax'],
107
+ ymax=detection_dict['box']['ymax']))
108
+
109
+ def mask_to_polygon(mask: np.ndarray) -> List[List[int]]:
110
+ contours, _ = cv2.findContours(mask.astype(np.uint8), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
111
+ if not contours:
112
+ return []
113
+ largest_contour = max(contours, key=cv2.contourArea)
114
+ polygon = largest_contour.reshape(-1, 2).tolist()
115
+ return polygon
116
+
117
+ def polygon_to_mask(polygon: List[Tuple[int, int]], image_shape: Tuple[int, int]) -> np.ndarray:
118
+ mask = np.zeros(image_shape, dtype=np.uint8)
119
+ pts = np.array(polygon, dtype=np.int32)
120
+ cv2.fillPoly(mask, [pts], color=(255,))
121
+ return mask
122
+
123
+ def get_boxes(results: List[DetectionResult]) -> List[List[List[float]]]:
124
+ boxes = []
125
+ for result in results:
126
+ xyxy = result.box.xyxy
127
+ boxes.append(xyxy)
128
+ return [boxes]
129
+
130
+ def refine_masks(masks: torch.BoolTensor, polygon_refinement: bool = False) -> List[np.ndarray]:
131
+ masks = masks.cpu().float()
132
+ masks = masks.permute(0, 2, 3, 1)
133
+ masks = masks.mean(axis=-1)
134
+ masks = (masks > 0).int()
135
+ masks = masks.numpy().astype(np.uint8)
136
+ masks = list(masks)
137
+ if polygon_refinement:
138
+ for idx, mask in enumerate(masks):
139
+ shape = mask.shape
140
+ polygon = mask_to_polygon(mask)
141
+ mask = polygon_to_mask(polygon, shape)
142
+ masks[idx] = mask
143
+ return masks
144
+
145
+ def detect(
146
+ object_detector,
147
+ image: Image.Image,
148
+ labels: List[str],
149
+ threshold: float = 0.3,
150
+ detector_id: Optional[str] = None
151
+ ) -> List[Dict[str, Any]]:
152
+ device = "cuda" if torch.cuda.is_available() else "cpu"
153
+ detector_id = detector_id if detector_id is not None else detector_id
154
+ labels = [label if label.endswith(".") else label+"." for label in labels]
155
+ results = object_detector(image, candidate_labels=labels, threshold=threshold)
156
+ results = [DetectionResult.from_dict(result) for result in results]
157
+ return results
158
+
159
+ def segment(
160
+ segmentator,
161
+ processor,
162
+ image_tensor: torch.Tensor,
163
+ detection_results: List[Dict[str, Any]],
164
+ polygon_refinement: bool = False
165
+ ) -> List[DetectionResult]:
166
+ device = image_tensor.device
167
+
168
+ boxes = get_boxes(detection_results)
169
+
170
+ # Convert image tensor to float32 for processing
171
+ image_tensor_float32 = image_tensor.to(torch.float32)
172
+
173
+ inputs = processor(images=image_tensor_float32, input_boxes=boxes, return_tensors="pt", torch_dtype=torch.float32)
174
+
175
+ # Process inputs and get outputs
176
+ outputs = segmentator(**inputs)
177
+
178
+ # Convert masks to bfloat16 if needed
179
+ masks = outputs.pred_masks.to(torch.bfloat16)
180
+
181
+ masks = processor.post_process_masks(
182
+ masks=masks,
183
+ original_sizes=inputs.original_sizes,
184
+ reshaped_input_sizes=inputs.reshaped_input_sizes
185
+ )[0]
186
+
187
+ masks = refine_masks(masks, polygon_refinement)
188
+
189
+ for detection_result, mask in zip(detection_results, masks):
190
+ detection_result.mask = mask
191
+
192
+ return detection_results
193
+
194
+ def grounded_segmentation(
195
+ detect_pipeline,
196
+ segmentator,
197
+ segment_processor,
198
+ image: Union[Image.Image, str],
199
+ labels: List[str],
200
+ threshold: float = 0.3,
201
+ polygon_refinement: bool = False,
202
+ detector_id: Optional[str] = None,
203
+ segmenter_id: Optional[str] = None
204
+ ) -> Tuple[np.ndarray, List[DetectionResult]]:
205
+ if isinstance(image, str):
206
+ image = load_image(image)
207
+
208
+ # Convert image to tensor and to float32 for processing
209
+ image_tensor = torch.tensor(np.array(image), dtype=torch.float32, device="cuda").permute(2, 0, 1).unsqueeze(0) / 255.0
210
+
211
+ detections = detect(detect_pipeline, image, labels, threshold, detector_id)
212
+ detections = segment(segmentator, segment_processor, image_tensor, detections, polygon_refinement)
213
+
214
+ # Convert image tensor back to numpy array for return
215
+ image_array = image_tensor.squeeze(0).permute(1, 2, 0).cpu().numpy() * 255
216
+ image_array = image_array.astype(np.uint8)
217
+
218
+ return image_array, detections
219
+
220
+ class CustomFluxAttnProcessor2_0:
221
+ def __init__(self, height=44, width=88, attn_enforce=1.0):
222
+ if not hasattr(torch.nn.functional, "scaled_dot_product_attention"):
223
+ raise ImportError("FluxAttnProcessor2_0 requires PyTorch 2.0, to use it, please upgrade PyTorch to 2.0.")
224
+ self.height = height
225
+ self.width = width
226
+ self.num_pixels = height * width
227
+ self.step = 0
228
+ self.attn_enforce = attn_enforce
229
+
230
+ def __call__(
231
+ self,
232
+ attn: Attention,
233
+ hidden_states: torch.FloatTensor,
234
+ encoder_hidden_states: torch.FloatTensor = None,
235
+ attention_mask: Optional[torch.FloatTensor] = None,
236
+ image_rotary_emb: Optional[torch.Tensor] = None,
237
+ ) -> torch.FloatTensor:
238
+ self.step += 1
239
+ batch_size, _, _ = hidden_states.shape if encoder_hidden_states is None else encoder_hidden_states.shape
240
+ query = attn.to_q(hidden_states)
241
+ key = attn.to_k(hidden_states)
242
+ value = attn.to_v(hidden_states)
243
+ inner_dim = key.shape[-1]
244
+ head_dim = inner_dim // attn.heads
245
+ query = query.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
246
+ key = key.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
247
+ value = value.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
248
+ if attn.norm_q is not None:
249
+ query = attn.norm_q(query)
250
+ if attn.norm_k is not None:
251
+ key = attn.norm_k(key)
252
+ if encoder_hidden_states is not None:
253
+ encoder_hidden_states_query_proj = attn.add_q_proj(encoder_hidden_states)
254
+ encoder_hidden_states_key_proj = attn.add_k_proj(encoder_hidden_states)
255
+ encoder_hidden_states_value_proj = attn.add_v_proj(encoder_hidden_states)
256
+ encoder_hidden_states_query_proj = encoder_hidden_states_query_proj.view(
257
+ batch_size, -1, attn.heads, head_dim
258
+ ).transpose(1, 2)
259
+ encoder_hidden_states_key_proj = encoder_hidden_states_key_proj.view(
260
+ batch_size, -1, attn.heads, head_dim
261
+ ).transpose(1, 2)
262
+ encoder_hidden_states_value_proj = encoder_hidden_states_value_proj.view(
263
+ batch_size, -1, attn.heads, head_dim
264
+ ).transpose(1, 2)
265
+ if attn.norm_added_q is not None:
266
+ encoder_hidden_states_query_proj = attn.norm_added_q(encoder_hidden_states_query_proj)
267
+ if attn.norm_added_k is not None:
268
+ encoder_hidden_states_key_proj = attn.norm_added_k(encoder_hidden_states_key_proj)
269
+ query = torch.cat([encoder_hidden_states_query_proj, query], dim=2)
270
+ key = torch.cat([encoder_hidden_states_key_proj, key], dim=2)
271
+ value = torch.cat([encoder_hidden_states_value_proj, value], dim=2)
272
+ if image_rotary_emb is not None:
273
+ from diffusers.models.embeddings import apply_rotary_emb
274
+ query = apply_rotary_emb(query, image_rotary_emb)
275
+ key = apply_rotary_emb(key, image_rotary_emb)
276
+ if self.attn_enforce != 1.0:
277
+ attn_probs = (torch.einsum('bhqd,bhkd->bhqk', query, key) * attn.scale).softmax(dim=-1)
278
+ img_attn_probs = attn_probs[:, :, -self.num_pixels:, -self.num_pixels:]
279
+ img_attn_probs = img_attn_probs.reshape((batch_size, attn.heads, self.height, self.width, self.height, self.width))
280
+ img_attn_probs[:, :, :, self.width//2:, :, :self.width//2] *= self.attn_enforce
281
+ img_attn_probs = img_attn_probs.reshape((batch_size, attn.heads, self.num_pixels, self.num_pixels))
282
+ attn_probs[:, :, -self.num_pixels:, -self.num_pixels:] = img_attn_probs
283
+ hidden_states = torch.einsum('bhqk,bhkd->bhqd', attn_probs, value)
284
+ else:
285
+ hidden_states = torch.nn.functional.scaled_dot_product_attention(query, key, value, dropout_p=0.0, is_causal=False)
286
+ hidden_states = hidden_states.transpose(1, 2).reshape(batch_size, -1, attn.heads * head_dim)
287
+ hidden_states = hidden_states.to(query.dtype)
288
+ if encoder_hidden_states is not None:
289
+ encoder_hidden_states, hidden_states = (
290
+ hidden_states[:, : encoder_hidden_states.shape[1]],
291
+ hidden_states[:, encoder_hidden_states.shape[1] :],
292
+ )
293
+ hidden_states = attn.to_out[0](hidden_states)
294
+ hidden_states = attn.to_out[1](hidden_states)
295
+ encoder_hidden_states = attn.to_add_out(encoder_hidden_states)
296
+ return hidden_states, encoder_hidden_states
297
+ else:
298
+ return hidden_states
299
+
300
+ def segment_image(image, object_name):
301
+ image_array, detections = grounded_segmentation(
302
+ object_detector,
303
+ segmentator,
304
+ segment_processor,
305
+ image=image,
306
+ labels=object_name,
307
+ threshold=0.3,
308
+ polygon_refinement=True,
309
+ )
310
+ segment_result = image_array * np.expand_dims((255 - detections[0].mask) / 255, axis=-1)
311
+ segmented_image = Image.fromarray(segment_result.astype(np.uint8))
312
+ return segmented_image
313
+
314
+ def make_diptych(image):
315
+ ref_image = np.array(image)
316
+ ref_image = np.concatenate([ref_image, np.zeros_like(ref_image)], axis=1)
317
+ ref_image = Image.fromarray(ref_image)
318
+ return ref_image
319
+
320
+ @spaces.GPU()
321
+ def inpaint_image(image, prompt, object_name):
322
+ width = 512
323
+ height = 512
324
+ size = (width * 2, height)
325
+ diptych_text_prompt = f"A diptych with two side-by-side images of same {object_name}. On the left, a photo of {object_name}. On the right, {prompt}"
326
+ reference_image = image.resize((width, height)).convert("RGB")
327
+ segmented_image = segment_image(reference_image, object_name)
328
+ mask_image = np.concatenate([np.zeros((height, width, 3)), np.ones((height, width, 3))*255], axis=1)
329
+ mask_image = Image.fromarray(mask_image.astype(np.uint8))
330
+ diptych_image_prompt = make_diptych(segmented_image)
331
+
332
+ base_attn_procs = pipe.transformer.attn_processors.copy()
333
+ new_attn_procs = base_attn_procs.copy()
334
+ for i, (k, v) in enumerate(new_attn_procs.items()):
335
+ new_attn_procs[k] = CustomFluxAttnProcessor2_0(height=height // 16, width=width // 16 * 2, attn_enforce=1.3)
336
+ pipe.transformer.set_attn_processor(new_attn_procs)
337
+ generator = torch.Generator(device="cuda").manual_seed(42)
338
+ with torch.no_grad():
339
+ result = pipe(
340
+ prompt=diptych_text_prompt,
341
+ height=size[1],
342
+ width=size[0],
343
+ control_image=diptych_image_prompt,
344
+ control_mask=mask_image,
345
+ num_inference_steps=20,
346
+ generator=generator,
347
+ controlnet_conditioning_scale=0.95,
348
+ guidance_scale=3.5,
349
+ negative_prompt="",
350
+ true_guidance_scale=3.5
351
+ ).images[0]
352
+ result = result.crop((width, 0, width*2, height))
353
+
354
+ torch.cuda.empty_cache()
355
+ return result, diptych_image_prompt
356
+
357
+ # Create Gradio interface
358
+ iface = gr.Interface(
359
+ fn=inpaint_image,
360
+ inputs=[
361
+ gr.Image(type="pil", label="Upload Image"),
362
+ gr.Textbox(lines=3, value="replicate this {subject_name} exactly but as a photo of the {subject_name} surfing on the beach", label="Prompt"),
363
+ gr.Textbox(lines=1, value="bear plushie", label="Subject Name")
364
+ ],
365
+ outputs=[
366
+ gr.Image(type="pil", label="Inpainted Image"),
367
+ gr.Image(type="pil", label="Diptych Image")
368
+ ],
369
+ title="FLUX Inpainting with Diptych Prompting",
370
+ description="Upload an image, specify a prompt, and provide the subject name. The app will automatically generate the inpainted image."
371
+ )
372
+
373
+ # Launch the app
374
+ iface.launch()
transformer_flux.py CHANGED
@@ -33,6 +33,7 @@ from diffusers.models.embeddings import (
33
  )
34
  from diffusers.models.modeling_outputs import Transformer2DModelOutput
35
 
 
36
 
37
  logger = logging.get_logger(__name__) # pylint: disable=invalid-name
38
 
@@ -70,7 +71,108 @@ class EmbedND(nn.Module):
70
  )
71
  return emb.unsqueeze(1)
72
 
 
 
 
 
 
 
73
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
74
  @maybe_allow_in_graph
75
  class FluxSingleTransformerBlock(nn.Module):
76
  r"""
@@ -114,14 +216,22 @@ class FluxSingleTransformerBlock(nn.Module):
114
  hidden_states: torch.FloatTensor,
115
  temb: torch.FloatTensor,
116
  image_rotary_emb=None,
 
117
  ):
118
  residual = hidden_states
119
  norm_hidden_states, gate = self.norm(hidden_states, emb=temb)
120
  mlp_hidden_states = self.act_mlp(self.proj_mlp(norm_hidden_states))
121
 
122
- attn_output = self.attn(
 
 
 
 
 
 
123
  hidden_states=norm_hidden_states,
124
  image_rotary_emb=image_rotary_emb,
 
125
  )
126
 
127
  hidden_states = torch.cat([attn_output, mlp_hidden_states], dim=2)
@@ -196,6 +306,7 @@ class FluxTransformerBlock(nn.Module):
196
  encoder_hidden_states: torch.FloatTensor,
197
  temb: torch.FloatTensor,
198
  image_rotary_emb=None,
 
199
  ):
200
  norm_hidden_states, gate_msa, shift_mlp, scale_mlp, gate_mlp = self.norm1(
201
  hidden_states, emb=temb
@@ -210,10 +321,18 @@ class FluxTransformerBlock(nn.Module):
210
  ) = self.norm1_context(encoder_hidden_states, emb=temb)
211
 
212
  # Attention.
213
- attn_output, context_attn_output = self.attn(
 
 
 
 
 
 
 
214
  hidden_states=norm_hidden_states,
215
  encoder_hidden_states=norm_encoder_hidden_states,
216
  image_rotary_emb=image_rotary_emb,
 
217
  )
218
 
219
  # Process attention outputs for the `hidden_states`.
@@ -359,6 +478,7 @@ class FluxTransformer2DModel(
359
  controlnet_block_samples=None,
360
  controlnet_single_block_samples=None,
361
  return_dict: bool = True,
 
362
  ) -> Union[torch.FloatTensor, Transformer2DModelOutput]:
363
  """
364
  The [`FluxTransformer2DModel`] forward method.
@@ -418,11 +538,6 @@ class FluxTransformer2DModel(
418
  encoder_hidden_states = self.context_embedder(encoder_hidden_states)
419
 
420
  txt_ids = txt_ids.expand(img_ids.size(0), -1, -1)
421
- # Add debugging statements
422
- print(f"txt_ids shape: {txt_ids.shape}")
423
- print(f"img_ids shape: {img_ids.shape}")
424
-
425
- # Ensure tensors have the same number of dimensions
426
  ids = torch.cat((txt_ids, img_ids), dim=1)
427
  image_rotary_emb = self.pos_embed(ids)
428
 
@@ -459,6 +574,7 @@ class FluxTransformer2DModel(
459
  encoder_hidden_states=encoder_hidden_states,
460
  temb=temb,
461
  image_rotary_emb=image_rotary_emb,
 
462
  )
463
 
464
  # controlnet residual
@@ -502,6 +618,7 @@ class FluxTransformer2DModel(
502
  hidden_states=hidden_states,
503
  temb=temb,
504
  image_rotary_emb=image_rotary_emb,
 
505
  )
506
 
507
  # controlnet residual
 
33
  )
34
  from diffusers.models.modeling_outputs import Transformer2DModelOutput
35
 
36
+ import math
37
 
38
  logger = logging.get_logger(__name__) # pylint: disable=invalid-name
39
 
 
71
  )
72
  return emb.unsqueeze(1)
73
 
74
+ def apply_rope(xq, xk, freqs_cis):
75
+ xq_ = xq.float().reshape(*xq.shape[:-1], -1, 1, 2)
76
+ xk_ = xk.float().reshape(*xk.shape[:-1], -1, 1, 2)
77
+ xq_out = freqs_cis[..., 0] * xq_[..., 0] + freqs_cis[..., 1] * xq_[..., 1]
78
+ xk_out = freqs_cis[..., 0] * xk_[..., 0] + freqs_cis[..., 1] * xk_[..., 1]
79
+ return xq_out.reshape(*xq.shape).type_as(xq), xk_out.reshape(*xk.shape).type_as(xk)
80
 
81
+ def custom_scaled_dot_product_attention(query, key, value, attn_scale_mask=None):
82
+
83
+ scale_factor = 1 / math.sqrt(query.size(-1))
84
+
85
+
86
+ attn_weight = query @ key.transpose(-2, -1) * scale_factor
87
+
88
+ attn_weight = torch.softmax(attn_weight, dim=-1)
89
+
90
+ if attn_scale_mask is not None:
91
+ attn_weight[:, :] * attn_scale_mask
92
+
93
+ return attn_weight @ value
94
+
95
+ def attn_forward(
96
+ attn: Attention,
97
+ hidden_states: torch.FloatTensor,
98
+ encoder_hidden_states: torch.FloatTensor = None,
99
+ attention_mask: Optional[torch.FloatTensor] = None,
100
+ image_rotary_emb: Optional[torch.Tensor] = None,
101
+ attn_scale_mask: Optional[torch.FloatTensor] = None,
102
+ ) -> torch.FloatTensor:
103
+ batch_size, _, _ = hidden_states.shape if encoder_hidden_states is None else encoder_hidden_states.shape
104
+
105
+ # `sample` projections.
106
+ query = attn.to_q(hidden_states)
107
+ key = attn.to_k(hidden_states)
108
+ value = attn.to_v(hidden_states)
109
+
110
+ inner_dim = key.shape[-1]
111
+ head_dim = inner_dim // attn.heads
112
+
113
+ query = query.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
114
+ key = key.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
115
+ value = value.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
116
+
117
+ if attn.norm_q is not None:
118
+ query = attn.norm_q(query)
119
+ if attn.norm_k is not None:
120
+ key = attn.norm_k(key)
121
+
122
+ # the attention in FluxSingleTransformerBlock does not use `encoder_hidden_states`
123
+ if encoder_hidden_states is not None:
124
+ # `context` projections.
125
+ encoder_hidden_states_query_proj = attn.add_q_proj(encoder_hidden_states)
126
+ encoder_hidden_states_key_proj = attn.add_k_proj(encoder_hidden_states)
127
+ encoder_hidden_states_value_proj = attn.add_v_proj(encoder_hidden_states)
128
+
129
+ encoder_hidden_states_query_proj = encoder_hidden_states_query_proj.view(
130
+ batch_size, -1, attn.heads, head_dim
131
+ ).transpose(1, 2)
132
+ encoder_hidden_states_key_proj = encoder_hidden_states_key_proj.view(
133
+ batch_size, -1, attn.heads, head_dim
134
+ ).transpose(1, 2)
135
+ encoder_hidden_states_value_proj = encoder_hidden_states_value_proj.view(
136
+ batch_size, -1, attn.heads, head_dim
137
+ ).transpose(1, 2)
138
+
139
+ if attn.norm_added_q is not None:
140
+ encoder_hidden_states_query_proj = attn.norm_added_q(encoder_hidden_states_query_proj)
141
+ if attn.norm_added_k is not None:
142
+ encoder_hidden_states_key_proj = attn.norm_added_k(encoder_hidden_states_key_proj)
143
+
144
+ # attention
145
+ query = torch.cat([encoder_hidden_states_query_proj, query], dim=2)
146
+ key = torch.cat([encoder_hidden_states_key_proj, key], dim=2)
147
+ value = torch.cat([encoder_hidden_states_value_proj, value], dim=2)
148
+
149
+ if image_rotary_emb is not None:
150
+
151
+ query, key = apply_rope(query, key, image_rotary_emb)
152
+
153
+ # hidden_states = F.scaled_dot_product_attention(query, key, value, dropout_p=0.0, is_causal=False, attn_mask=attention_mask)
154
+ # Calculate attention using scaled dot product attention
155
+ hidden_states = custom_scaled_dot_product_attention(query, key, value, attn_scale_mask)
156
+
157
+ hidden_states = hidden_states.transpose(1, 2).reshape(batch_size, -1, attn.heads * head_dim)
158
+ hidden_states = hidden_states.to(query.dtype)
159
+
160
+ if encoder_hidden_states is not None:
161
+ encoder_hidden_states, hidden_states = (
162
+ hidden_states[:, : encoder_hidden_states.shape[1]],
163
+ hidden_states[:, encoder_hidden_states.shape[1] :],
164
+ )
165
+
166
+ # linear proj
167
+ hidden_states = attn.to_out[0](hidden_states)
168
+ # dropout
169
+ hidden_states = attn.to_out[1](hidden_states)
170
+ encoder_hidden_states = attn.to_add_out(encoder_hidden_states)
171
+
172
+ return hidden_states, encoder_hidden_states
173
+ else:
174
+ return hidden_states
175
+
176
  @maybe_allow_in_graph
177
  class FluxSingleTransformerBlock(nn.Module):
178
  r"""
 
216
  hidden_states: torch.FloatTensor,
217
  temb: torch.FloatTensor,
218
  image_rotary_emb=None,
219
+ attn_scale_mask=None,
220
  ):
221
  residual = hidden_states
222
  norm_hidden_states, gate = self.norm(hidden_states, emb=temb)
223
  mlp_hidden_states = self.act_mlp(self.proj_mlp(norm_hidden_states))
224
 
225
+ # attn_output = self.attn(
226
+ # hidden_states=norm_hidden_states,
227
+ # image_rotary_emb=image_rotary_emb,
228
+ # )
229
+
230
+ attn_output = attn_forward(
231
+ self.attn,
232
  hidden_states=norm_hidden_states,
233
  image_rotary_emb=image_rotary_emb,
234
+ attn_scale_mask=attn_scale_mask,
235
  )
236
 
237
  hidden_states = torch.cat([attn_output, mlp_hidden_states], dim=2)
 
306
  encoder_hidden_states: torch.FloatTensor,
307
  temb: torch.FloatTensor,
308
  image_rotary_emb=None,
309
+ attn_scale_mask=None,
310
  ):
311
  norm_hidden_states, gate_msa, shift_mlp, scale_mlp, gate_mlp = self.norm1(
312
  hidden_states, emb=temb
 
321
  ) = self.norm1_context(encoder_hidden_states, emb=temb)
322
 
323
  # Attention.
324
+ # attn_output, context_attn_output = self.attn(
325
+ # hidden_states=norm_hidden_states,
326
+ # encoder_hidden_states=norm_encoder_hidden_states,
327
+ # image_rotary_emb=image_rotary_emb,
328
+ # )
329
+
330
+ attn_output, context_attn_output = attn_forward(
331
+ self.attn,
332
  hidden_states=norm_hidden_states,
333
  encoder_hidden_states=norm_encoder_hidden_states,
334
  image_rotary_emb=image_rotary_emb,
335
+ attn_scale_mask=attn_scale_mask,
336
  )
337
 
338
  # Process attention outputs for the `hidden_states`.
 
478
  controlnet_block_samples=None,
479
  controlnet_single_block_samples=None,
480
  return_dict: bool = True,
481
+ attn_scale_mask=None,
482
  ) -> Union[torch.FloatTensor, Transformer2DModelOutput]:
483
  """
484
  The [`FluxTransformer2DModel`] forward method.
 
538
  encoder_hidden_states = self.context_embedder(encoder_hidden_states)
539
 
540
  txt_ids = txt_ids.expand(img_ids.size(0), -1, -1)
 
 
 
 
 
541
  ids = torch.cat((txt_ids, img_ids), dim=1)
542
  image_rotary_emb = self.pos_embed(ids)
543
 
 
574
  encoder_hidden_states=encoder_hidden_states,
575
  temb=temb,
576
  image_rotary_emb=image_rotary_emb,
577
+ attn_scale_mask=attn_scale_mask,
578
  )
579
 
580
  # controlnet residual
 
618
  hidden_states=hidden_states,
619
  temb=temb,
620
  image_rotary_emb=image_rotary_emb,
621
+ attn_scale_mask=attn_scale_mask,
622
  )
623
 
624
  # controlnet residual
transformer_flux2.py ADDED
@@ -0,0 +1,530 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Any, Dict, List, Optional, Union
2
+
3
+ import numpy as np
4
+ import torch
5
+ import torch.nn as nn
6
+ import torch.nn.functional as F
7
+
8
+ from diffusers.configuration_utils import ConfigMixin, register_to_config
9
+ from diffusers.loaders import FromOriginalModelMixin, PeftAdapterMixin
10
+ from diffusers.models.attention import FeedForward
11
+ from diffusers.models.attention_processor import (
12
+ Attention,
13
+ FluxAttnProcessor2_0,
14
+ FluxSingleAttnProcessor2_0,
15
+ )
16
+ from diffusers.models.modeling_utils import ModelMixin
17
+ from diffusers.models.normalization import (
18
+ AdaLayerNormContinuous,
19
+ AdaLayerNormZero,
20
+ AdaLayerNormZeroSingle,
21
+ )
22
+ from diffusers.utils import (
23
+ USE_PEFT_BACKEND,
24
+ is_torch_version,
25
+ logging,
26
+ scale_lora_layers,
27
+ unscale_lora_layers,
28
+ )
29
+ from diffusers.utils.torch_utils import maybe_allow_in_graph
30
+ from diffusers.models.embeddings import (
31
+ CombinedTimestepGuidanceTextProjEmbeddings,
32
+ CombinedTimestepTextProjEmbeddings,
33
+ )
34
+ from diffusers.models.modeling_outputs import Transformer2DModelOutput
35
+
36
+
37
+ logger = logging.get_logger(__name__) # pylint: disable=invalid-name
38
+
39
+
40
+ # YiYi to-do: refactor rope related functions/classes
41
+ def rope(pos: torch.Tensor, dim: int, theta: int) -> torch.Tensor:
42
+ assert dim % 2 == 0, "The dimension must be even."
43
+
44
+ scale = torch.arange(0, dim, 2, dtype=torch.float64, device=pos.device) / dim
45
+ omega = 1.0 / (theta**scale)
46
+
47
+ batch_size, seq_length = pos.shape
48
+ out = torch.einsum("...n,d->...nd", pos, omega)
49
+ cos_out = torch.cos(out)
50
+ sin_out = torch.sin(out)
51
+
52
+ stacked_out = torch.stack([cos_out, -sin_out, sin_out, cos_out], dim=-1)
53
+ out = stacked_out.view(batch_size, -1, dim // 2, 2, 2)
54
+ return out.float()
55
+
56
+
57
+ # YiYi to-do: refactor rope related functions/classes
58
+ class EmbedND(nn.Module):
59
+ def __init__(self, dim: int, theta: int, axes_dim: List[int]):
60
+ super().__init__()
61
+ self.dim = dim
62
+ self.theta = theta
63
+ self.axes_dim = axes_dim
64
+
65
+ def forward(self, ids: torch.Tensor) -> torch.Tensor:
66
+ n_axes = ids.shape[-1]
67
+ emb = torch.cat(
68
+ [rope(ids[..., i], self.axes_dim[i], self.theta) for i in range(n_axes)],
69
+ dim=-3,
70
+ )
71
+ return emb.unsqueeze(1)
72
+
73
+
74
+ @maybe_allow_in_graph
75
+ class FluxSingleTransformerBlock(nn.Module):
76
+ r"""
77
+ A Transformer block following the MMDiT architecture, introduced in Stable Diffusion 3.
78
+
79
+ Reference: https://arxiv.org/abs/2403.03206
80
+
81
+ Parameters:
82
+ dim (`int`): The number of channels in the input and output.
83
+ num_attention_heads (`int`): The number of heads to use for multi-head attention.
84
+ attention_head_dim (`int`): The number of channels in each head.
85
+ context_pre_only (`bool`): Boolean to determine if we should add some blocks associated with the
86
+ processing of `context` conditions.
87
+ """
88
+
89
+ def __init__(self, dim, num_attention_heads, attention_head_dim, mlp_ratio=4.0):
90
+ super().__init__()
91
+ self.mlp_hidden_dim = int(dim * mlp_ratio)
92
+
93
+ self.norm = AdaLayerNormZeroSingle(dim)
94
+ self.proj_mlp = nn.Linear(dim, self.mlp_hidden_dim)
95
+ self.act_mlp = nn.GELU(approximate="tanh")
96
+ self.proj_out = nn.Linear(dim + self.mlp_hidden_dim, dim)
97
+
98
+ processor = FluxSingleAttnProcessor2_0()
99
+ self.attn = Attention(
100
+ query_dim=dim,
101
+ cross_attention_dim=None,
102
+ dim_head=attention_head_dim,
103
+ heads=num_attention_heads,
104
+ out_dim=dim,
105
+ bias=True,
106
+ processor=processor,
107
+ qk_norm="rms_norm",
108
+ eps=1e-6,
109
+ pre_only=True,
110
+ )
111
+
112
+ def forward(
113
+ self,
114
+ hidden_states: torch.FloatTensor,
115
+ temb: torch.FloatTensor,
116
+ image_rotary_emb=None,
117
+ ):
118
+ residual = hidden_states
119
+ norm_hidden_states, gate = self.norm(hidden_states, emb=temb)
120
+ mlp_hidden_states = self.act_mlp(self.proj_mlp(norm_hidden_states))
121
+
122
+ attn_output = self.attn(
123
+ hidden_states=norm_hidden_states,
124
+ image_rotary_emb=image_rotary_emb,
125
+ )
126
+
127
+ hidden_states = torch.cat([attn_output, mlp_hidden_states], dim=2)
128
+ gate = gate.unsqueeze(1)
129
+ hidden_states = gate * self.proj_out(hidden_states)
130
+ hidden_states = residual + hidden_states
131
+ if hidden_states.dtype == torch.float16:
132
+ hidden_states = hidden_states.clip(-65504, 65504)
133
+
134
+ return hidden_states
135
+
136
+
137
+ @maybe_allow_in_graph
138
+ class FluxTransformerBlock(nn.Module):
139
+ r"""
140
+ A Transformer block following the MMDiT architecture, introduced in Stable Diffusion 3.
141
+
142
+ Reference: https://arxiv.org/abs/2403.03206
143
+
144
+ Parameters:
145
+ dim (`int`): The number of channels in the input and output.
146
+ num_attention_heads (`int`): The number of heads to use for multi-head attention.
147
+ attention_head_dim (`int`): The number of channels in each head.
148
+ context_pre_only (`bool`): Boolean to determine if we should add some blocks associated with the
149
+ processing of `context` conditions.
150
+ """
151
+
152
+ def __init__(
153
+ self, dim, num_attention_heads, attention_head_dim, qk_norm="rms_norm", eps=1e-6
154
+ ):
155
+ super().__init__()
156
+
157
+ self.norm1 = AdaLayerNormZero(dim)
158
+
159
+ self.norm1_context = AdaLayerNormZero(dim)
160
+
161
+ if hasattr(F, "scaled_dot_product_attention"):
162
+ processor = FluxAttnProcessor2_0()
163
+ else:
164
+ raise ValueError(
165
+ "The current PyTorch version does not support the `scaled_dot_product_attention` function."
166
+ )
167
+ self.attn = Attention(
168
+ query_dim=dim,
169
+ cross_attention_dim=None,
170
+ added_kv_proj_dim=dim,
171
+ dim_head=attention_head_dim,
172
+ heads=num_attention_heads,
173
+ out_dim=dim,
174
+ context_pre_only=False,
175
+ bias=True,
176
+ processor=processor,
177
+ qk_norm=qk_norm,
178
+ eps=eps,
179
+ )
180
+
181
+ self.norm2 = nn.LayerNorm(dim, elementwise_affine=False, eps=1e-6)
182
+ self.ff = FeedForward(dim=dim, dim_out=dim, activation_fn="gelu-approximate")
183
+
184
+ self.norm2_context = nn.LayerNorm(dim, elementwise_affine=False, eps=1e-6)
185
+ self.ff_context = FeedForward(
186
+ dim=dim, dim_out=dim, activation_fn="gelu-approximate"
187
+ )
188
+
189
+ # let chunk size default to None
190
+ self._chunk_size = None
191
+ self._chunk_dim = 0
192
+
193
+ def forward(
194
+ self,
195
+ hidden_states: torch.FloatTensor,
196
+ encoder_hidden_states: torch.FloatTensor,
197
+ temb: torch.FloatTensor,
198
+ image_rotary_emb=None,
199
+ ):
200
+ norm_hidden_states, gate_msa, shift_mlp, scale_mlp, gate_mlp = self.norm1(
201
+ hidden_states, emb=temb
202
+ )
203
+
204
+ (
205
+ norm_encoder_hidden_states,
206
+ c_gate_msa,
207
+ c_shift_mlp,
208
+ c_scale_mlp,
209
+ c_gate_mlp,
210
+ ) = self.norm1_context(encoder_hidden_states, emb=temb)
211
+
212
+ # Attention.
213
+ attn_output, context_attn_output = self.attn(
214
+ hidden_states=norm_hidden_states,
215
+ encoder_hidden_states=norm_encoder_hidden_states,
216
+ image_rotary_emb=image_rotary_emb,
217
+ )
218
+
219
+ # Process attention outputs for the `hidden_states`.
220
+ attn_output = gate_msa.unsqueeze(1) * attn_output
221
+ hidden_states = hidden_states + attn_output
222
+
223
+ norm_hidden_states = self.norm2(hidden_states)
224
+ norm_hidden_states = (
225
+ norm_hidden_states * (1 + scale_mlp[:, None]) + shift_mlp[:, None]
226
+ )
227
+
228
+ ff_output = self.ff(norm_hidden_states)
229
+ ff_output = gate_mlp.unsqueeze(1) * ff_output
230
+
231
+ hidden_states = hidden_states + ff_output
232
+
233
+ # Process attention outputs for the `encoder_hidden_states`.
234
+
235
+ context_attn_output = c_gate_msa.unsqueeze(1) * context_attn_output
236
+ encoder_hidden_states = encoder_hidden_states + context_attn_output
237
+
238
+ norm_encoder_hidden_states = self.norm2_context(encoder_hidden_states)
239
+ norm_encoder_hidden_states = (
240
+ norm_encoder_hidden_states * (1 + c_scale_mlp[:, None])
241
+ + c_shift_mlp[:, None]
242
+ )
243
+
244
+ context_ff_output = self.ff_context(norm_encoder_hidden_states)
245
+ encoder_hidden_states = (
246
+ encoder_hidden_states + c_gate_mlp.unsqueeze(1) * context_ff_output
247
+ )
248
+ if encoder_hidden_states.dtype == torch.float16:
249
+ encoder_hidden_states = encoder_hidden_states.clip(-65504, 65504)
250
+
251
+ return encoder_hidden_states, hidden_states
252
+
253
+
254
+ class FluxTransformer2DModel(
255
+ ModelMixin, ConfigMixin, PeftAdapterMixin, FromOriginalModelMixin
256
+ ):
257
+ """
258
+ The Transformer model introduced in Flux.
259
+
260
+ Reference: https://blackforestlabs.ai/announcing-black-forest-labs/
261
+
262
+ Parameters:
263
+ patch_size (`int`): Patch size to turn the input data into small patches.
264
+ in_channels (`int`, *optional*, defaults to 16): The number of channels in the input.
265
+ num_layers (`int`, *optional*, defaults to 18): The number of layers of MMDiT blocks to use.
266
+ num_single_layers (`int`, *optional*, defaults to 18): The number of layers of single DiT blocks to use.
267
+ attention_head_dim (`int`, *optional*, defaults to 64): The number of channels in each head.
268
+ num_attention_heads (`int`, *optional*, defaults to 18): The number of heads to use for multi-head attention.
269
+ joint_attention_dim (`int`, *optional*): The number of `encoder_hidden_states` dimensions to use.
270
+ pooled_projection_dim (`int`): Number of dimensions to use when projecting the `pooled_projections`.
271
+ guidance_embeds (`bool`, defaults to False): Whether to use guidance embeddings.
272
+ """
273
+
274
+ _supports_gradient_checkpointing = True
275
+
276
+ @register_to_config
277
+ def __init__(
278
+ self,
279
+ patch_size: int = 1,
280
+ in_channels: int = 64,
281
+ num_layers: int = 19,
282
+ num_single_layers: int = 38,
283
+ attention_head_dim: int = 128,
284
+ num_attention_heads: int = 24,
285
+ joint_attention_dim: int = 4096,
286
+ pooled_projection_dim: int = 768,
287
+ guidance_embeds: bool = False,
288
+ axes_dims_rope: List[int] = [16, 56, 56],
289
+ ):
290
+ super().__init__()
291
+ self.out_channels = in_channels
292
+ self.inner_dim = (
293
+ self.config.num_attention_heads * self.config.attention_head_dim
294
+ )
295
+
296
+ self.pos_embed = EmbedND(
297
+ dim=self.inner_dim, theta=10000, axes_dim=axes_dims_rope
298
+ )
299
+ text_time_guidance_cls = (
300
+ CombinedTimestepGuidanceTextProjEmbeddings
301
+ if guidance_embeds
302
+ else CombinedTimestepTextProjEmbeddings
303
+ )
304
+ self.time_text_embed = text_time_guidance_cls(
305
+ embedding_dim=self.inner_dim,
306
+ pooled_projection_dim=self.config.pooled_projection_dim,
307
+ )
308
+
309
+ self.context_embedder = nn.Linear(
310
+ self.config.joint_attention_dim, self.inner_dim
311
+ )
312
+ self.x_embedder = torch.nn.Linear(self.config.in_channels, self.inner_dim)
313
+
314
+ self.transformer_blocks = nn.ModuleList(
315
+ [
316
+ FluxTransformerBlock(
317
+ dim=self.inner_dim,
318
+ num_attention_heads=self.config.num_attention_heads,
319
+ attention_head_dim=self.config.attention_head_dim,
320
+ )
321
+ for i in range(self.config.num_layers)
322
+ ]
323
+ )
324
+
325
+ self.single_transformer_blocks = nn.ModuleList(
326
+ [
327
+ FluxSingleTransformerBlock(
328
+ dim=self.inner_dim,
329
+ num_attention_heads=self.config.num_attention_heads,
330
+ attention_head_dim=self.config.attention_head_dim,
331
+ )
332
+ for i in range(self.config.num_single_layers)
333
+ ]
334
+ )
335
+
336
+ self.norm_out = AdaLayerNormContinuous(
337
+ self.inner_dim, self.inner_dim, elementwise_affine=False, eps=1e-6
338
+ )
339
+ self.proj_out = nn.Linear(
340
+ self.inner_dim, patch_size * patch_size * self.out_channels, bias=True
341
+ )
342
+
343
+ self.gradient_checkpointing = False
344
+
345
+ def _set_gradient_checkpointing(self, module, value=False):
346
+ if hasattr(module, "gradient_checkpointing"):
347
+ module.gradient_checkpointing = value
348
+
349
+ def forward(
350
+ self,
351
+ hidden_states: torch.Tensor,
352
+ encoder_hidden_states: torch.Tensor = None,
353
+ pooled_projections: torch.Tensor = None,
354
+ timestep: torch.LongTensor = None,
355
+ img_ids: torch.Tensor = None,
356
+ txt_ids: torch.Tensor = None,
357
+ guidance: torch.Tensor = None,
358
+ joint_attention_kwargs: Optional[Dict[str, Any]] = None,
359
+ controlnet_block_samples=None,
360
+ controlnet_single_block_samples=None,
361
+ return_dict: bool = True,
362
+ ) -> Union[torch.FloatTensor, Transformer2DModelOutput]:
363
+ """
364
+ The [`FluxTransformer2DModel`] forward method.
365
+
366
+ Args:
367
+ hidden_states (`torch.FloatTensor` of shape `(batch size, channel, height, width)`):
368
+ Input `hidden_states`.
369
+ encoder_hidden_states (`torch.FloatTensor` of shape `(batch size, sequence_len, embed_dims)`):
370
+ Conditional embeddings (embeddings computed from the input conditions such as prompts) to use.
371
+ pooled_projections (`torch.FloatTensor` of shape `(batch_size, projection_dim)`): Embeddings projected
372
+ from the embeddings of input conditions.
373
+ timestep ( `torch.LongTensor`):
374
+ Used to indicate denoising step.
375
+ block_controlnet_hidden_states: (`list` of `torch.Tensor`):
376
+ A list of tensors that if specified are added to the residuals of transformer blocks.
377
+ joint_attention_kwargs (`dict`, *optional*):
378
+ A kwargs dictionary that if specified is passed along to the `AttentionProcessor` as defined under
379
+ `self.processor` in
380
+ [diffusers.models.attention_processor](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py).
381
+ return_dict (`bool`, *optional*, defaults to `True`):
382
+ Whether or not to return a [`~models.transformer_2d.Transformer2DModelOutput`] instead of a plain
383
+ tuple.
384
+
385
+ Returns:
386
+ If `return_dict` is True, an [`~models.transformer_2d.Transformer2DModelOutput`] is returned, otherwise a
387
+ `tuple` where the first element is the sample tensor.
388
+ """
389
+ if joint_attention_kwargs is not None:
390
+ joint_attention_kwargs = joint_attention_kwargs.copy()
391
+ lora_scale = joint_attention_kwargs.pop("scale", 1.0)
392
+ else:
393
+ lora_scale = 1.0
394
+
395
+ if USE_PEFT_BACKEND:
396
+ # weight the lora layers by setting `lora_scale` for each PEFT layer
397
+ scale_lora_layers(self, lora_scale)
398
+ else:
399
+ if (
400
+ joint_attention_kwargs is not None
401
+ and joint_attention_kwargs.get("scale", None) is not None
402
+ ):
403
+ logger.warning(
404
+ "Passing `scale` via `joint_attention_kwargs` when not using the PEFT backend is ineffective."
405
+ )
406
+ hidden_states = self.x_embedder(hidden_states)
407
+
408
+ timestep = timestep.to(hidden_states.dtype) * 1000
409
+ if guidance is not None:
410
+ guidance = guidance.to(hidden_states.dtype) * 1000
411
+ else:
412
+ guidance = None
413
+ temb = (
414
+ self.time_text_embed(timestep, pooled_projections)
415
+ if guidance is None
416
+ else self.time_text_embed(timestep, guidance, pooled_projections)
417
+ )
418
+ encoder_hidden_states = self.context_embedder(encoder_hidden_states)
419
+
420
+ txt_ids = txt_ids.expand(img_ids.size(0), -1, -1)
421
+ # Add debugging statements
422
+ print(f"txt_ids shape: {txt_ids.shape}")
423
+ print(f"img_ids shape: {img_ids.shape}")
424
+
425
+ # Ensure tensors have the same number of dimensions
426
+ ids = torch.cat((txt_ids, img_ids), dim=1)
427
+ image_rotary_emb = self.pos_embed(ids)
428
+
429
+ for index_block, block in enumerate(self.transformer_blocks):
430
+ if self.training and self.gradient_checkpointing:
431
+
432
+ def create_custom_forward(module, return_dict=None):
433
+ def custom_forward(*inputs):
434
+ if return_dict is not None:
435
+ return module(*inputs, return_dict=return_dict)
436
+ else:
437
+ return module(*inputs)
438
+
439
+ return custom_forward
440
+
441
+ ckpt_kwargs: Dict[str, Any] = (
442
+ {"use_reentrant": False} if is_torch_version(">=", "1.11.0") else {}
443
+ )
444
+ (
445
+ encoder_hidden_states,
446
+ hidden_states,
447
+ ) = torch.utils.checkpoint.checkpoint(
448
+ create_custom_forward(block),
449
+ hidden_states,
450
+ encoder_hidden_states,
451
+ temb,
452
+ image_rotary_emb,
453
+ **ckpt_kwargs,
454
+ )
455
+
456
+ else:
457
+ encoder_hidden_states, hidden_states = block(
458
+ hidden_states=hidden_states,
459
+ encoder_hidden_states=encoder_hidden_states,
460
+ temb=temb,
461
+ image_rotary_emb=image_rotary_emb,
462
+ )
463
+
464
+ # controlnet residual
465
+ if controlnet_block_samples is not None:
466
+ interval_control = len(self.transformer_blocks) / len(
467
+ controlnet_block_samples
468
+ )
469
+ interval_control = int(np.ceil(interval_control))
470
+ hidden_states = (
471
+ hidden_states
472
+ + controlnet_block_samples[index_block // interval_control]
473
+ )
474
+
475
+ hidden_states = torch.cat([encoder_hidden_states, hidden_states], dim=1)
476
+
477
+ for index_block, block in enumerate(self.single_transformer_blocks):
478
+ if self.training and self.gradient_checkpointing:
479
+
480
+ def create_custom_forward(module, return_dict=None):
481
+ def custom_forward(*inputs):
482
+ if return_dict is not None:
483
+ return module(*inputs, return_dict=return_dict)
484
+ else:
485
+ return module(*inputs)
486
+
487
+ return custom_forward
488
+
489
+ ckpt_kwargs: Dict[str, Any] = (
490
+ {"use_reentrant": False} if is_torch_version(">=", "1.11.0") else {}
491
+ )
492
+ hidden_states = torch.utils.checkpoint.checkpoint(
493
+ create_custom_forward(block),
494
+ hidden_states,
495
+ temb,
496
+ image_rotary_emb,
497
+ **ckpt_kwargs,
498
+ )
499
+
500
+ else:
501
+ hidden_states = block(
502
+ hidden_states=hidden_states,
503
+ temb=temb,
504
+ image_rotary_emb=image_rotary_emb,
505
+ )
506
+
507
+ # controlnet residual
508
+ if controlnet_single_block_samples is not None:
509
+ interval_control = len(self.single_transformer_blocks) / len(
510
+ controlnet_single_block_samples
511
+ )
512
+ interval_control = int(np.ceil(interval_control))
513
+ hidden_states[:, encoder_hidden_states.shape[1] :, ...] = (
514
+ hidden_states[:, encoder_hidden_states.shape[1] :, ...]
515
+ + controlnet_single_block_samples[index_block // interval_control]
516
+ )
517
+
518
+ hidden_states = hidden_states[:, encoder_hidden_states.shape[1] :, ...]
519
+
520
+ hidden_states = self.norm_out(hidden_states, temb)
521
+ output = self.proj_out(hidden_states)
522
+
523
+ if USE_PEFT_BACKEND:
524
+ # remove `lora_scale` from each PEFT layer
525
+ unscale_lora_layers(self, lora_scale)
526
+
527
+ if not return_dict:
528
+ return (output,)
529
+
530
+ return Transformer2DModelOutput(sample=output)