carminezacc commited on
Commit
e8a1827
·
verified ·
1 Parent(s): 6914069

Initial release

Browse files
README.md CHANGED
@@ -1,3 +1,160 @@
1
  ---
2
  license: apache-2.0
 
 
 
 
 
3
  ---
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  ---
2
  license: apache-2.0
3
+ tags:
4
+ - image-editing
5
+ - diffusion
6
+ - flux
7
+ - multi-instance
8
  ---
9
+
10
+ # MICE: Multi-Instance Controlled Editing
11
+
12
+ Code for spatially-controlled multi-instance image editing with FLUX.2-klein (4B).
13
+ MICE constrains cross-instance attention leakage during inference so that each edit stays within its intended spatial region.
14
+
15
+ ## Requirements
16
+
17
+ ```bash
18
+ pip install torch diffusers transformers pillow tqdm loguru numpy
19
+ ```
20
+
21
+ The model weights are downloaded automatically from HuggingFace on first run:
22
+ ```
23
+ black-forest-labs/FLUX.2-klein-4B
24
+ ```
25
+
26
+ ## Quick start — single image
27
+
28
+ ```bash
29
+ python infer.py \
30
+ --image input.jpg \
31
+ --edits "Replace the cat with a dog" "Replace the lamp with a vase" \
32
+ --masks mask_cat.png mask_lamp.png \
33
+ --output result.png
34
+ ```
35
+
36
+ Provide one `--edits` string and one `--masks` path per instance you want to edit.
37
+ Masks are binary images (white = instance region, black = background).
38
+
39
+ If you do not have masks, use normalized bounding boxes instead:
40
+
41
+ ```bash
42
+ python infer.py \
43
+ --image input.jpg \
44
+ --edits "Replace the cat with a dog" \
45
+ --bboxes "0.1 0.2 0.5 0.8" \
46
+ --output result.png
47
+ ```
48
+
49
+ ### All options
50
+
51
+ | Flag | Default | Description |
52
+ |---|---|---|
53
+ | `--image` | *(required)* | Path to the input image |
54
+ | `--edits` | *(required)* | Edit instruction per instance |
55
+ | `--masks` | — | Binary mask image per instance (mutually exclusive with `--bboxes`) |
56
+ | `--bboxes` | — | Normalized `x1 y1 x2 y2` bbox per instance (mutually exclusive with `--masks`) |
57
+ | `--output` | `result.png` | Output path |
58
+ | `--model` | `black-forest-labs/FLUX.2-klein-4B` | HuggingFace model ID or local path |
59
+ | `--num_inference_steps` | `4` | Number of denoising steps |
60
+ | `--kernel_size` | `11` | Spatial kernel size for attention falloff |
61
+ | `--temperature` | `3.0` | Steepness of spatial falloff |
62
+ | `--double_layers` | `0,5` | Double-stream block range for attention binding |
63
+ | `--single_layers` | `0,20` | Single-stream block range for attention binding |
64
+ | `--strict` | flag | Stricter cross-instance isolation |
65
+
66
+ ## Benchmark inference
67
+
68
+ Scripts for running inference over the full MICE-Bench and LoMOE-Bench datasets are also included.
69
+
70
+ ### MICE-Bench (ground-truth masks)
71
+
72
+ ```bash
73
+ python infer_flux2_mice.py \
74
+ --exp_name my_experiment \
75
+ --dataset_root ../mice_bench \
76
+ --num_inference_steps 4 \
77
+ --kernel_size 11 \
78
+ --temperature 3.0 \
79
+ --hard_image_attribute_binding_list_double 0,5 \
80
+ --hard_image_attribute_binding_list_single 0,20 \
81
+ --use_masks
82
+ ```
83
+
84
+ Results are saved to `results_micebench/mice_flux2_klein_<exp_name>/`.
85
+
86
+ ### MICE-Bench (SAM3 masks)
87
+
88
+ ```bash
89
+ python infer_flux2_mice_sam3.py \
90
+ --exp_name my_experiment \
91
+ --dataset_root /path/to/mice_bench_sam3 \
92
+ --num_inference_steps 4 \
93
+ --kernel_size 11 \
94
+ --temperature 3.0 \
95
+ --use_masks
96
+ ```
97
+
98
+ Results are saved to `results_micebench_sam3/mice_flux2_sam3_<exp_name>/`.
99
+
100
+ ### LoMOE-Bench (ground-truth masks)
101
+
102
+ LoMOE-Bench is expected at `benchmark/data/LoMOE-Bench/` relative to the repository root (path is hardcoded in `lomoe_dataset.py`).
103
+
104
+ ```bash
105
+ python infer_flux2_lomoe.py \
106
+ --exp_name my_experiment \
107
+ --num_inference_steps 4 \
108
+ --kernel_size 11 \
109
+ --temperature 3.0 \
110
+ --hard_image_attribute_binding_list_double 0,5 \
111
+ --hard_image_attribute_binding_list_single 0,20 \
112
+ --use_masks
113
+ ```
114
+
115
+ Results are saved to `results/lomoe_flux2_klein_<exp_name>/`.
116
+
117
+ ### LoMOE-Bench (SAM3 masks)
118
+
119
+ ```bash
120
+ python infer_flux2_lomoe_sam3.py \
121
+ --exp_name my_experiment \
122
+ --dataset_root /path/to/lomoe_bench_sam3 \
123
+ --num_inference_steps 4 \
124
+ --kernel_size 11 \
125
+ --temperature 3.0 \
126
+ --use_masks
127
+ ```
128
+
129
+ Results are saved to `results_sam3/lomoe_flux2_sam3_<exp_name>/`.
130
+
131
+ ## Dataset structure
132
+
133
+ **MICE-Bench** (`--dataset_root`):
134
+ ```
135
+ mice_bench/
136
+ LoMOE.json
137
+ images/
138
+ masks/
139
+ ```
140
+
141
+ **SAM3 datasets** (`--dataset_root`):
142
+ ```
143
+ <dataset_root>/
144
+ LoMOE_mobius.json # mask paths point to SAM3-generated masks
145
+ images/
146
+ masks/
147
+ ```
148
+
149
+ **LoMOE-Bench** (hardcoded path `benchmark/data/LoMOE-Bench/`):
150
+ ```
151
+ benchmark/data/LoMOE-Bench/
152
+ LoMOE.json
153
+ LoMOE_multi_turn_faithful.json
154
+ LoMOE_multi_turn_enhanced.json
155
+ utils/
156
+ mask_orig_prompts.txt
157
+ text_prompts.txt
158
+ images/
159
+ masks/
160
+ ```
flux2/__init__.py ADDED
File without changes
flux2/attention/__init__.py ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import enum
2
+
3
+ from .attention_processor_base import Flux2AttnProcessor, Flux2ParallelSelfAttnProcessor
4
+ from .attention_processor_APITASM_kernel_nonlap import Flux2APITASMAttnProcessorKernelNonLap, Flux2ParallelSelfAttnProcessorAPITASMKernelNonLap
5
+
6
+
7
+ class AttentionSetting(enum.Enum):
8
+ FULL = 'full'
9
+ APITASMkernelNonLap = 'apitasmkernelnonlap'
10
+ APITASMkernelNonLapStrict = 'apitasmkernelnonlapstrict'
11
+
12
+
13
+ def get_attention_processors(attention_setting: AttentionSetting, sigma_scale: float = 0.6, kernel_size: int = 11, temperature: float = 3.0):
14
+ if attention_setting == AttentionSetting.FULL:
15
+ return Flux2AttnProcessor(), Flux2ParallelSelfAttnProcessor()
16
+ elif attention_setting == AttentionSetting.APITASMkernelNonLap:
17
+ return Flux2APITASMAttnProcessorKernelNonLap(kernel_size=kernel_size, temperature=temperature), Flux2ParallelSelfAttnProcessorAPITASMKernelNonLap(kernel_size=kernel_size, temperature=temperature)
18
+ elif attention_setting == AttentionSetting.APITASMkernelNonLapStrict:
19
+ return Flux2APITASMAttnProcessorKernelNonLap(kernel_size=kernel_size, temperature=temperature, strict=True), Flux2ParallelSelfAttnProcessorAPITASMKernelNonLap(kernel_size=kernel_size, temperature=temperature, strict=True)
20
+ else:
21
+ raise NotImplementedError(f"Attention setting {attention_setting.value} is not supported")
flux2/attention/attention_processor_APITASM_kernel_nonlap.py ADDED
@@ -0,0 +1,619 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import inspect
2
+ from typing import Any, Dict, List, Optional, Tuple, Union
3
+
4
+ import torch
5
+ from diffusers.models.embeddings import apply_rotary_emb
6
+ from diffusers.models.attention_dispatch import dispatch_attention_fn
7
+ import torch
8
+ import torch.nn as nn
9
+ import torch.nn.functional as F
10
+ from PIL import Image
11
+
12
+ from .attention_utils import _get_qkv_projections, MaskType
13
+
14
+ TRANSFORMER_NUM_LAYERS = 5
15
+ TRANSFORMER_SINGLE_NUM_LAYERS = 20
16
+
17
+ """
18
+ Tight Context: σ≈1.0 (Only immediate neighbors influence the edit).
19
+ Medium Context: σ≈3.0 (Allows bleeding for smoother blending).
20
+ Wide Context: σ≈5.0+ (Risk of instance confusion, but better lighting/global coherence).
21
+ """
22
+
23
+ import torch
24
+
25
+ import numpy as np
26
+ import os
27
+
28
+ # Image.fromarray((((Flux2APITASMAttnProcessor.cond_hard_bind_mask.clamp(-50) / 50. )+1)*255).float().cpu().numpy()).convert('RGB').save('HARD_MASK.png')
29
+
30
+
31
+ def fill_hard_text_bind_mask(atten_mask, instance_text_index_lst, image_w_instance_token_index_list, seq_len, HW, instance_num, instance_position_mask_list, image_token_H, image_token_W, context_image_w_instance_token_index_list=None):
32
+
33
+ for i in range(instance_num + 1):
34
+
35
+ instance_text_idxs = instance_text_index_lst[i]
36
+
37
+ # Activate text-to-text attention (always needed)
38
+ atten_mask[instance_text_idxs[:, None], instance_text_idxs] = 0.0
39
+
40
+ # Activate text-to-image attention
41
+ # For global prompt (i==0) activate attention to the corresponding image tokens
42
+ if i == 0:
43
+ image_token_index = torch.tensor(image_w_instance_token_index_list[i])
44
+ context_image_token_index = torch.tensor(context_image_w_instance_token_index_list[i])
45
+
46
+ # Activate attentions prompt to image if i==0 else local-prompt to bridge-image/global-image
47
+ atten_mask[instance_text_idxs[:, None], seq_len + image_token_index] = 0.0
48
+
49
+ if i == 0:
50
+ # Activate attentions prompt to context if i==0 else local-prompt to context-bridge-image/context-global-image
51
+ atten_mask[instance_text_idxs[:, None], seq_len + HW + context_image_token_index] = 0.0
52
+
53
+ if i > 0:
54
+ instance_img_in_patch_idxs = instance_position_mask_list[i-1].reshape(image_token_H * image_token_W).nonzero(as_tuple=True)[0].to(atten_mask.device)
55
+ # Activate attentions local-prompt to instance-image
56
+ atten_mask[instance_text_idxs[:, None], seq_len + instance_img_in_patch_idxs] = 0.0
57
+ # Activate attentions local-prompt to context-instance-image
58
+ atten_mask[instance_text_idxs[:, None], seq_len + HW + instance_img_in_patch_idxs] = 0.0
59
+
60
+ return atten_mask
61
+
62
+
63
+ def fill_image_bind_mask(atten_mask, mask_type, instance_text_index_lst, image_w_instance_token_index_list, seq_len, HW, instance_num, global_seq_len, instance_position_mask_list, image_token_H, image_token_W, query, context_image_w_instance_token_index_list=None, kernel_size=11, temperature=3.0, smooth_P_L=False, free_context=False, free_latent=False, free_LC=False):
64
+ """
65
+ Fills the attention mask with:
66
+ - 0.0 for valid connections
67
+ - -inf for hard blocks
68
+ - Gaussian decay values for soft connections (based on kernel convolution on mask)
69
+
70
+ kernel_size: Controls the Gaussian kernel size for convolution.
71
+ temperature: Controls falloff intensity (higher = softer falloff).
72
+ """
73
+ device = atten_mask.device
74
+ dtype = atten_mask.dtype
75
+
76
+ # --- 1. GLOBAL SETUP (Standard Flux Logic) ---
77
+ # Global Image <-> Global Prompt/Context (Keep as 0.0 for open connection)
78
+ global_image_token_index = torch.tensor(image_w_instance_token_index_list[0], device=device)
79
+ global_context_image_token_index = torch.tensor(context_image_w_instance_token_index_list[0], device=device)
80
+
81
+ # Global Image -> Global Prompt
82
+ atten_mask[(seq_len + global_image_token_index)[:, None], : global_seq_len] = 0.0
83
+ # Global Image -> Global Image
84
+ atten_mask[(seq_len + global_image_token_index)[:, None], seq_len + global_image_token_index] = 0.0
85
+ # Global Image -> Context Image
86
+ atten_mask[(seq_len + global_image_token_index)[:, None], seq_len + HW + global_context_image_token_index] = 0.0
87
+
88
+ # Context Image -> Global Prompt
89
+ atten_mask[(seq_len + HW + global_context_image_token_index)[:, None], : global_seq_len] = 0.0
90
+ # Context Image -> Global Image
91
+ atten_mask[(seq_len + HW + global_context_image_token_index)[:, None], seq_len + global_image_token_index] = 0.0
92
+ # Context Image -> Context Image
93
+ atten_mask[(seq_len + HW + global_context_image_token_index)[:, None], seq_len + HW + global_context_image_token_index] = 0.0
94
+
95
+ # --- 2. PREPARE GAUSSIAN KERNEL ---
96
+ # We want a 2D Gaussian kernel
97
+ sigma = 0.3 * ((kernel_size - 1) * 0.5 - 1) + 0.8
98
+ k_range = torch.arange(kernel_size, dtype=dtype, device=device) - (kernel_size - 1) / 2.0
99
+ k_y, k_x = torch.meshgrid(k_range, k_range, indexing='ij')
100
+ kernel = torch.exp(-(k_y**2 + k_x**2) / (2 * sigma**2))
101
+ kernel = kernel / kernel.sum() # Normalize so sum is 1? Or max is 1?
102
+ # Actually, for "attention strength", we usually want the center to be 1.0 (max attention)
103
+ # The pure Gaussian PDF integrates to 1, but its peak value depends on sigma.
104
+ # We want the "mask" values to be close to 0 (allow) inside the object.
105
+ # Let's normalize the kernel so its MAX value is 1.0, so convolution on a solid block of 1s yields values near 1?
106
+ # No, convolution is sum of products.
107
+ # If we want smoothing:
108
+ # 1. Convolve binary mask with Gaussian kernel (sum=1). Result is 0..1 (approx density).
109
+ # 2. Convert density to log-probability bias. bias = log(density + epsilon)
110
+ # - If density=1 (inside object), log(1)=0 (full attention).
111
+ # - If density=0 (far away), log(eps) = large negative (blocked).
112
+ kernel = kernel / kernel.sum() # Normalize volume to 1
113
+
114
+ # Reshape kernel for conv2d: (Out_channels, In_channels, H, W)
115
+ kernel = kernel.view(1, 1, kernel_size, kernel_size).to(device, dtype)
116
+
117
+
118
+ # --- 3. INSTANCE LOGIC ---
119
+ for i in range(1, instance_num + 1):
120
+ instance_text_idxs = instance_text_index_lst[i]
121
+
122
+ # Get the boolean mask for this instance (H, W)
123
+ inst_mask_2d = instance_position_mask_list[i-1].to(device).float()
124
+
125
+ # Calculate union of all other masks
126
+ other_masks_2d = torch.zeros_like(inst_mask_2d)
127
+ for j in range(instance_num):
128
+ if j != (i - 1):
129
+ other_masks_2d = torch.logical_or(other_masks_2d, instance_position_mask_list[j].to(device))
130
+ other_masks_2d = other_masks_2d.float()
131
+
132
+ # Get flat indices for rows (Queries) - These are the pixels belonging to the instance
133
+ instance_flat_indices = inst_mask_2d.reshape(-1).nonzero(as_tuple=True)[0]
134
+
135
+ # --- A. Text Interaction (Always Open) ---
136
+ # Instance -> Local Prompt
137
+ atten_mask[seq_len + instance_flat_indices[:, None], instance_text_idxs] = 0.0
138
+ atten_mask[seq_len + HW + instance_flat_indices[:, None], instance_text_idxs] = 0.0
139
+
140
+ # --- B. HARD MASK LOGIC ---
141
+ if mask_type in [MaskType.HARD, MaskType.HARD2]:
142
+ # Block interactions with Global Prompt
143
+ atten_mask[seq_len + instance_flat_indices[:, None], : global_seq_len] = -float('inf')
144
+
145
+ # Convolution-based Smoothing
146
+
147
+ # Prepare input for conv2d: (B=1, C=1, H, W)
148
+ mask_input = inst_mask_2d.view(1, 1, image_token_H, image_token_W).to(dtype)
149
+
150
+ # Padding to keep size same
151
+ pad_size = kernel_size // 2
152
+
153
+ # Convolve
154
+ convolved_mask = F.conv2d(mask_input, kernel, padding=pad_size)
155
+
156
+ # Flatten to (HW,)
157
+ convolved_flat = convolved_mask.view(-1)
158
+
159
+ # Convert to Attention Bias
160
+ # Values are roughly [0, 1]. Map 0->-inf, 1->0
161
+ # Add epsilon to avoid log(0)
162
+ # Use temperature scaling to control falloff intensity:
163
+ # - temperature = 1.0: standard log mapping (steep falloff)
164
+ # - temperature > 1.0: softer falloff (more attention outside mask)
165
+ # - temperature < 1.0: sharper falloff (less attention outside mask)
166
+ gaussian_bias = torch.log(convolved_flat + 1e-6) / temperature
167
+
168
+ # Remove extra smoothed added parts for areas that overlap other masks
169
+ overlap_mask_2d = (inst_mask_2d == 0) & (other_masks_2d == 1)
170
+ overlap_mask_flat = overlap_mask_2d.view(-1)
171
+ gaussian_bias[overlap_mask_flat] = -float('inf')
172
+
173
+
174
+ # Ideally max value should be 0. We can shift it if needed, but if the kernel sum is 1
175
+ # and the mask has a large enough area, the center of the mask will be ~1.0.
176
+ # However, for small objects or edges, it might be < 1.
177
+ # Let's keep it as log(density).
178
+
179
+ # Only keep values comparable to float range? No, attention masks can be very negative.
180
+
181
+ # 3. Apply Bias to the Attention Mask
182
+ # We broadcast the (1, HW) bias to (Num_Instance_Pixels, HW)
183
+ atten_mask[seq_len + instance_flat_indices[:, None], seq_len : seq_len + (image_token_H * image_token_W)] = gaussian_bias.to(dtype)
184
+
185
+ # Also apply to the Context-Image tokens (optional, but consistent)
186
+ atten_mask[seq_len + instance_flat_indices[:, None], seq_len + HW : seq_len + HW + (image_token_H * image_token_W)] = gaussian_bias.to(dtype)
187
+
188
+ # do the same FROM the context-image tokens
189
+ atten_mask[seq_len + HW + instance_flat_indices[:, None], seq_len : seq_len + (image_token_H * image_token_W)] = gaussian_bias.to(dtype)
190
+ atten_mask[seq_len + HW + instance_flat_indices[:, None], seq_len + HW : seq_len + HW + (image_token_H * image_token_W)] = gaussian_bias.to(dtype)
191
+
192
+
193
+ # 4. Enforce Hard Intra-Instance Attention
194
+ # "Fully allowing interactions only inside the edit correspondances"
195
+ atten_mask[seq_len + instance_flat_indices[:, None], seq_len + instance_flat_indices] = 0.0
196
+ atten_mask[seq_len + instance_flat_indices[:, None], seq_len + HW + instance_flat_indices] = 0.0
197
+
198
+ # Apply Bias to Prompt <-> Image interactions
199
+ if smooth_P_L:
200
+ # Image (Latent) -> Prompt
201
+ atten_mask[seq_len : seq_len + HW, instance_text_idxs] = gaussian_bias[:, None].to(dtype)
202
+
203
+ # Prompt -> Image (Latent)
204
+ atten_mask[instance_text_idxs[:, None], seq_len : seq_len + HW] = gaussian_bias[None, :].to(dtype)
205
+
206
+
207
+ # 5. Handle Global Prompt
208
+ # Usually we still block global prompt to keep text guidance specific
209
+ atten_mask[seq_len + instance_flat_indices[:, None], : global_seq_len] = -float('inf')
210
+
211
+ # 4. Enforce Hard Intra-Instance Attention - Context Copy
212
+ atten_mask[seq_len + HW + instance_flat_indices[:, None], seq_len + instance_flat_indices] = 0.0
213
+ atten_mask[seq_len + HW + instance_flat_indices[:, None], seq_len + HW + instance_flat_indices] = 0.0
214
+
215
+ if free_context:
216
+ atten_mask[seq_len + HW:seq_len+HW+HW, seq_len:seq_len+HW+HW] = 0.0
217
+
218
+ if free_latent:
219
+ atten_mask[seq_len:seq_len+HW, seq_len:seq_len+HW+HW] = 0.0
220
+
221
+ if free_LC:
222
+ atten_mask[seq_len:seq_len+HW, seq_len+HW:seq_len+HW+HW] = 0.0
223
+
224
+ # --- VISUALIZATION BLOCK ---
225
+ if Flux2APITASMAttnProcessorKernelNonLap.debug_info is not None:
226
+ try:
227
+ debug_info = Flux2APITASMAttnProcessorKernelNonLap.debug_info
228
+ save_dir = debug_info.get('output_dir', '.')
229
+ sample_id = debug_info.get('sample_id', 'unknown')
230
+ original_image = debug_info.get('image', None) # PIL Image
231
+
232
+ if original_image is not None and MaskType.HARD == mask_type: # Only visualize once per sample/type
233
+ vis_dir = os.path.join(save_dir, "debug_vis")
234
+ os.makedirs(vis_dir, exist_ok=True)
235
+
236
+ # Pick the center token of the instance as the "Query"
237
+ mid_idx = len(instance_flat_indices) // 2
238
+ center_token_idx = instance_flat_indices[mid_idx]
239
+
240
+ # Extract the attention mask row for this token, looking at all Image tokens
241
+ # Row: seq_len + center_token_idx
242
+ # Cols: seq_len : seq_len + HW (The Image Tokens)
243
+ mask_row = atten_mask[seq_len + center_token_idx, seq_len : seq_len + (image_token_H * image_token_W)]
244
+
245
+ # mask_row contains -inf, 0.0, and gaussian values.
246
+ heatmap_vals = torch.exp(mask_row).float().cpu().numpy()
247
+
248
+ # Reshape to (H, W)
249
+ heatmap_img = heatmap_vals.reshape(image_token_H, image_token_W)
250
+
251
+ # Normalize
252
+ heatmap_img = np.clip(heatmap_img, 0, 1)
253
+
254
+ # Convert to uint8 255
255
+ heatmap_uint8 = (heatmap_img * 255).astype(np.uint8)
256
+
257
+ # Create a heatmap image
258
+ heatmap_pil = Image.fromarray(heatmap_uint8, mode='L')
259
+ heatmap_pil = heatmap_pil.resize(original_image.size, resample=Image.NEAREST)
260
+
261
+ # Create a red solid image
262
+ red_img = Image.new("RGB", original_image.size, (255, 0, 0))
263
+
264
+ # Composite
265
+ mask_alpha = heatmap_pil
266
+ vis_img = Image.composite(red_img, original_image, mask_alpha)
267
+
268
+ # Save
269
+ filename = f"{sample_id}_inst{i}_kernel{kernel_size}_center_view.png"
270
+ vis_img.save(os.path.join(vis_dir, filename))
271
+
272
+ except Exception as e:
273
+ print(f"Error in visualization: {e}")
274
+
275
+
276
+ return atten_mask
277
+
278
+
279
+ class Flux2APITASMAttnProcessorKernelNonLap:
280
+ _attention_backend = None
281
+ _parallel_config = None
282
+ counter = 0
283
+ cond_hard_bind_mask = None
284
+ cond_soft_bind_mask = None
285
+ cond_hard_bind_mask2 = None
286
+ uncond_hard_bind_mask = None
287
+ uncond_soft_bind_mask = None
288
+ uncond_hard_bind_mask2 = None
289
+ cfg_inference_steps_multiplier = 1
290
+ debug_info = None
291
+
292
+ def __init__(self, kernel_size: int = 11, temperature: float = 3.0, strict: bool = False):
293
+ if not hasattr(F, "scaled_dot_product_attention"):
294
+ raise ImportError(f"{self.__class__.__name__} requires PyTorch 2.0. Please upgrade your pytorch version.")
295
+ self.kernel_size = kernel_size
296
+ self.temperature = temperature
297
+ self.strict = strict
298
+
299
+ @classmethod
300
+ def clear_cached_masks(cls):
301
+ """Clear all cached attention masks. Should be called after each training sample."""
302
+ cls.cond_hard_bind_mask = None
303
+ cls.cond_soft_bind_mask = None
304
+ cls.cond_hard_bind_mask2 = None
305
+ cls.uncond_hard_bind_mask = None
306
+ cls.uncond_soft_bind_mask = None
307
+ cls.uncond_hard_bind_mask2 = None
308
+ cls.counter = 0
309
+
310
+ def __call__(
311
+ self,
312
+ attn: "Flux2Attention",
313
+ hidden_states: torch.Tensor,
314
+ encoder_hidden_states: torch.Tensor = None,
315
+ attention_mask: Optional[torch.Tensor] = None,
316
+ image_rotary_emb: Optional[torch.Tensor] = None,
317
+ # APITA args
318
+ pos_instance_text_index_lst: Optional[List[List[int]]] = None,
319
+ neg_instance_text_index_lst: Optional[List[List[int]]] = None,
320
+ pos_seq_len: Optional[int] = None,
321
+ neg_seq_len: Optional[int] = None,
322
+ instance_position_mask_list: Optional[List[List[int]]] = None,
323
+ hard_image_attribute_binding_list_double: Optional[List[int]] = None,
324
+ hard_image_attribute_binding_list_single: Optional[List[int]] = None,
325
+ num_inference_steps: Optional[int] = None,
326
+ image_w_instance_token_index_list: Optional[List[List[int]]] = None,
327
+ image_w_instance_token_H_list: Optional[List[int]] = None,
328
+ image_w_instance_token_W_list: Optional[List[int]] = None,
329
+ context_image_w_instance_token_index_list: Optional[List[List[int]]] = None,
330
+ is_conditional: Optional[bool] = None,
331
+ hard_masking_steps: List = None,
332
+ relaxed_timesteps: str = None,
333
+ smooth_P_L: bool = False,
334
+ free_latent: bool = False,
335
+ free_context: bool = False,
336
+ free_LC: bool = False,
337
+ ) -> torch.Tensor:
338
+ query, key, value, encoder_query, encoder_key, encoder_value = _get_qkv_projections(
339
+ attn, hidden_states, encoder_hidden_states
340
+ )
341
+
342
+ assert hard_masking_steps != None, "hard masking steps must not be none in attention processor"
343
+ assert relaxed_timesteps != None, "relaxed behavior must be defined in attn processor"
344
+
345
+ query = query.unflatten(-1, (attn.heads, -1))
346
+ key = key.unflatten(-1, (attn.heads, -1))
347
+ value = value.unflatten(-1, (attn.heads, -1))
348
+
349
+ query = attn.norm_q(query)
350
+ key = attn.norm_k(key)
351
+
352
+ if attn.added_kv_proj_dim is not None:
353
+ encoder_query = encoder_query.unflatten(-1, (attn.heads, -1))
354
+ encoder_key = encoder_key.unflatten(-1, (attn.heads, -1))
355
+ encoder_value = encoder_value.unflatten(-1, (attn.heads, -1))
356
+
357
+ encoder_query = attn.norm_added_q(encoder_query)
358
+ encoder_key = attn.norm_added_k(encoder_key)
359
+
360
+ query = torch.cat([encoder_query, query], dim=1)
361
+ key = torch.cat([encoder_key, key], dim=1)
362
+ value = torch.cat([encoder_value, value], dim=1)
363
+
364
+ if image_rotary_emb is not None:
365
+ query = apply_rotary_emb(query, image_rotary_emb, sequence_dim=1)
366
+ key = apply_rotary_emb(key, image_rotary_emb, sequence_dim=1)
367
+
368
+
369
+ # APITA logic
370
+ assert is_conditional is not None, "is_conditional must be provided"
371
+ assert pos_seq_len is not None, "pos_seq_len must be provided"
372
+ assert instance_position_mask_list is not None, "instance_position_mask_list must be provided"
373
+ assert hard_image_attribute_binding_list_double is not None, "hard_image_attribute_binding_list_double must be provided"
374
+ assert num_inference_steps is not None, "num_inference_steps must be provided"
375
+ assert image_w_instance_token_index_list is not None, "image_w_instance_token_index_list must be provided"
376
+ assert image_w_instance_token_H_list is not None, "image_w_instance_token_H_list must be provided"
377
+ assert image_w_instance_token_W_list is not None, "image_w_instance_token_W_list must be provided"
378
+ assert context_image_w_instance_token_index_list is not None, "context_image_w_instance_token_index_list must be provided"
379
+
380
+ seq_len = pos_seq_len if is_conditional else neg_seq_len
381
+ instance_text_index_lst = pos_instance_text_index_lst if is_conditional else neg_instance_text_index_lst
382
+ HW = (query.shape[1] - seq_len) // 2
383
+ image_token_H = image_w_instance_token_H_list[0] // 16
384
+ image_token_W = image_w_instance_token_W_list[0] // 16
385
+ global_seq_len = pos_instance_text_index_lst[0].shape[0] if is_conditional else neg_instance_text_index_lst[0].shape[0]
386
+ instance_num = len(instance_position_mask_list)
387
+ Flux2APITASMAttnProcessorKernelNonLap.cfg_inference_steps_multiplier = 2 if not is_conditional else 1
388
+
389
+ if self.strict and instance_num > 1:
390
+ areas = [mask.sum().item() for mask in instance_position_mask_list]
391
+ new_mask_list = []
392
+ for i, mask in enumerate(instance_position_mask_list):
393
+ new_mask = mask.to(query.device).clone()
394
+ for j, other_mask in enumerate(instance_position_mask_list):
395
+ if i != j and areas[j] < areas[i]:
396
+ new_mask = new_mask * (1 - other_mask.to(query.device))
397
+ new_mask_list.append(new_mask)
398
+ instance_position_mask_list = new_mask_list
399
+
400
+ if (Flux2APITASMAttnProcessorKernelNonLap.cond_hard_bind_mask is None and is_conditional) or (Flux2APITASMAttnProcessorKernelNonLap.uncond_hard_bind_mask is None and not is_conditional):
401
+ atten_mask = torch.full((query.shape[1], query.shape[1]), -float('inf'), device=query.device, dtype=query.dtype)
402
+ atten_mask = fill_hard_text_bind_mask(atten_mask, instance_text_index_lst, image_w_instance_token_index_list, seq_len, HW, instance_num, instance_position_mask_list, image_token_H, image_token_W, context_image_w_instance_token_index_list=context_image_w_instance_token_index_list)
403
+ atten_mask = fill_image_bind_mask(atten_mask, MaskType.HARD, instance_text_index_lst, image_w_instance_token_index_list, seq_len, HW, instance_num, global_seq_len, instance_position_mask_list, image_token_H, image_token_W, query, context_image_w_instance_token_index_list=context_image_w_instance_token_index_list, kernel_size=self.kernel_size, temperature=self.temperature, smooth_P_L=smooth_P_L, free_context=free_context, free_latent=free_latent, free_LC=free_LC)
404
+ Flux2APITASMAttnProcessorKernelNonLap.cond_hard_bind_mask = atten_mask if is_conditional else Flux2APITASMAttnProcessorKernelNonLap.uncond_hard_bind_mask
405
+
406
+ if (Flux2APITASMAttnProcessorKernelNonLap.cond_soft_bind_mask is None and is_conditional) or (Flux2APITASMAttnProcessorKernelNonLap.uncond_soft_bind_mask is None and not is_conditional):
407
+ atten_mask = torch.full((query.shape[1], query.shape[1]), -float('inf'), device=query.device, dtype=query.dtype)
408
+ atten_mask = fill_hard_text_bind_mask(atten_mask, instance_text_index_lst, image_w_instance_token_index_list, seq_len, HW, instance_num, instance_position_mask_list, image_token_H, image_token_W, context_image_w_instance_token_index_list=context_image_w_instance_token_index_list)
409
+ atten_mask = fill_image_bind_mask(atten_mask, MaskType.SOFT, instance_text_index_lst, image_w_instance_token_index_list, seq_len, HW, instance_num, global_seq_len, instance_position_mask_list, image_token_H, image_token_W, query, context_image_w_instance_token_index_list=context_image_w_instance_token_index_list, kernel_size=self.kernel_size, temperature=self.temperature, smooth_P_L=smooth_P_L, free_context=free_context, free_latent=free_latent, free_LC=free_LC)
410
+ Flux2APITASMAttnProcessorKernelNonLap.cond_soft_bind_mask = atten_mask if is_conditional else Flux2APITASMAttnProcessorKernelNonLap.uncond_soft_bind_mask
411
+
412
+ if Flux2APITASMAttnProcessorKernelNonLap.counter % TRANSFORMER_NUM_LAYERS in hard_image_attribute_binding_list_double:
413
+ atten_mask = Flux2APITASMAttnProcessorKernelNonLap.cond_hard_bind_mask if is_conditional else Flux2APITASMAttnProcessorKernelNonLap.uncond_hard_bind_mask
414
+ else:
415
+ atten_mask = Flux2APITASMAttnProcessorKernelNonLap.cond_soft_bind_mask if is_conditional else Flux2APITASMAttnProcessorKernelNonLap.uncond_soft_bind_mask
416
+
417
+ if Flux2APITASMAttnProcessorKernelNonLap.counter // TRANSFORMER_NUM_LAYERS not in hard_masking_steps:
418
+ if relaxed_timesteps == "full":
419
+ atten_mask = None
420
+ elif relaxed_timesteps == "soft":
421
+ atten_mask = Flux2APITASMAttnProcessorKernelNonLap.cond_soft_bind_mask if is_conditional else Flux2APITASMAttnProcessorKernelNonLap.uncond_soft_bind_mask
422
+ else:
423
+ raise NotImplementedError(f"relaxed_timesteps={relaxed_timesteps}")
424
+
425
+ if Flux2APITASMAttnProcessorKernelNonLap.counter == 0:
426
+ Image.fromarray((((Flux2APITASMAttnProcessorKernelNonLap.cond_hard_bind_mask.clamp(-50) / 50. )+1)*255).float().cpu().numpy()).convert('RGB').save('HARD_MASK_smoothpl.png')
427
+
428
+ Flux2APITASMAttnProcessorKernelNonLap.counter += 1
429
+
430
+ hidden_states = dispatch_attention_fn(
431
+ query,
432
+ key,
433
+ value,
434
+ attn_mask=atten_mask,
435
+ backend=self._attention_backend,
436
+ parallel_config=self._parallel_config,
437
+ )
438
+ hidden_states = hidden_states.flatten(2, 3)
439
+ hidden_states = hidden_states.to(query.dtype)
440
+
441
+ if encoder_hidden_states is not None:
442
+ encoder_hidden_states, hidden_states = hidden_states.split_with_sizes(
443
+ [encoder_hidden_states.shape[1], hidden_states.shape[1] - encoder_hidden_states.shape[1]], dim=1
444
+ )
445
+ encoder_hidden_states = attn.to_add_out(encoder_hidden_states)
446
+
447
+ hidden_states = attn.to_out[0](hidden_states)
448
+ hidden_states = attn.to_out[1](hidden_states)
449
+
450
+ if Flux2APITASMAttnProcessorKernelNonLap.counter % (num_inference_steps * TRANSFORMER_NUM_LAYERS * Flux2APITASMAttnProcessorKernelNonLap.cfg_inference_steps_multiplier) == 0:
451
+ Flux2APITASMAttnProcessorKernelNonLap.clear_cached_masks()
452
+
453
+
454
+ if encoder_hidden_states is not None:
455
+ return hidden_states, encoder_hidden_states
456
+ else:
457
+ return hidden_states
458
+
459
+
460
+ class Flux2ParallelSelfAttnProcessorAPITASMKernelNonLap:
461
+ _attention_backend = None
462
+ _parallel_config = None
463
+ counter = 0
464
+ cond_hard_bind_mask = None
465
+ cond_soft_bind_mask = None
466
+ cond_hard_bind_mask2 = None
467
+ uncond_hard_bind_mask = None
468
+ uncond_soft_bind_mask = None
469
+ uncond_hard_bind_mask2 = None
470
+ cfg_inference_steps_multiplier = 1
471
+
472
+ def __init__(self, kernel_size: int = 11, temperature: float = 3.0, strict: bool = False):
473
+ if not hasattr(F, "scaled_dot_product_attention"):
474
+ raise ImportError(f"{self.__class__.__name__} requires PyTorch 2.0. Please upgrade your pytorch version.")
475
+ self.kernel_size = kernel_size
476
+ self.temperature = temperature
477
+ self.strict = strict
478
+
479
+ @classmethod
480
+ def clear_cached_masks(cls):
481
+ """Clear all cached attention masks. Should be called after each training sample."""
482
+ cls.cond_hard_bind_mask = None
483
+ cls.cond_soft_bind_mask = None
484
+ cls.cond_hard_bind_mask2 = None
485
+ cls.uncond_hard_bind_mask = None
486
+ cls.uncond_soft_bind_mask = None
487
+ cls.uncond_hard_bind_mask2 = None
488
+ cls.counter = 0
489
+
490
+ def __call__(
491
+ self,
492
+ attn: "Flux2ParallelSelfAttention",
493
+ hidden_states: torch.Tensor,
494
+ attention_mask: Optional[torch.Tensor] = None,
495
+ image_rotary_emb: Optional[torch.Tensor] = None,
496
+ # APITA args
497
+ pos_instance_text_index_lst: Optional[List[List[int]]] = None,
498
+ neg_instance_text_index_lst: Optional[List[List[int]]] = None,
499
+ pos_seq_len: Optional[int] = None,
500
+ neg_seq_len: Optional[int] = None,
501
+ instance_position_mask_list: Optional[List[List[int]]] = None,
502
+ hard_image_attribute_binding_list_double: Optional[List[int]] = None,
503
+ hard_image_attribute_binding_list_single: Optional[List[int]] = None,
504
+ num_inference_steps: Optional[int] = None,
505
+ image_w_instance_token_index_list: Optional[List[List[int]]] = None,
506
+ image_w_instance_token_H_list: Optional[List[int]] = None,
507
+ image_w_instance_token_W_list: Optional[List[int]] = None,
508
+ context_image_w_instance_token_index_list: Optional[List[List[int]]] = None,
509
+ is_conditional: Optional[bool] = None,
510
+ hard_masking_steps: List = None,
511
+ relaxed_timesteps: str = None,
512
+ smooth_P_L: bool = False,
513
+ free_context: bool = False,
514
+ free_latent: bool = False,
515
+ free_LC: bool = False,
516
+ ) -> torch.Tensor:
517
+ assert hard_masking_steps != None, "hard masking steps must not be none in attention processor"
518
+ assert relaxed_timesteps != None, "relaxed behavior must be defined in attn processor"
519
+
520
+ # Parallel in (QKV + MLP in) projection
521
+ hidden_states = attn.to_qkv_mlp_proj(hidden_states)
522
+ qkv, mlp_hidden_states = torch.split(
523
+ hidden_states, [3 * attn.inner_dim, attn.mlp_hidden_dim * attn.mlp_mult_factor], dim=-1
524
+ )
525
+
526
+ # Handle the attention logic
527
+ query, key, value = qkv.chunk(3, dim=-1)
528
+
529
+ query = query.unflatten(-1, (attn.heads, -1))
530
+ key = key.unflatten(-1, (attn.heads, -1))
531
+ value = value.unflatten(-1, (attn.heads, -1))
532
+
533
+ query = attn.norm_q(query)
534
+ key = attn.norm_k(key)
535
+
536
+ if image_rotary_emb is not None:
537
+ query = apply_rotary_emb(query, image_rotary_emb, sequence_dim=1)
538
+ key = apply_rotary_emb(key, image_rotary_emb, sequence_dim=1)
539
+
540
+
541
+ # APITA logic
542
+ assert is_conditional is not None, "is_conditional must be provided"
543
+ assert pos_seq_len is not None, "pos_seq_len must be provided"
544
+ assert instance_position_mask_list is not None, "instance_position_mask_list must be provided"
545
+ assert hard_image_attribute_binding_list_single is not None, "hard_image_attribute_binding_list_single must be provided"
546
+ assert num_inference_steps is not None, "num_inference_steps must be provided"
547
+ assert image_w_instance_token_index_list is not None, "image_w_instance_token_index_list must be provided"
548
+ assert image_w_instance_token_H_list is not None, "image_w_instance_token_H_list must be provided"
549
+ assert image_w_instance_token_W_list is not None, "image_w_instance_token_W_list must be provided"
550
+ assert context_image_w_instance_token_index_list is not None, "context_image_w_instance_token_index_list must be provided"
551
+
552
+ seq_len = pos_seq_len if is_conditional else neg_seq_len
553
+ instance_text_index_lst = pos_instance_text_index_lst if is_conditional else neg_instance_text_index_lst
554
+ HW = (query.shape[1] - seq_len) // 2
555
+ image_token_H = image_w_instance_token_H_list[0] // 16
556
+ image_token_W = image_w_instance_token_W_list[0] // 16
557
+ global_seq_len = pos_instance_text_index_lst[0].shape[0] if is_conditional else neg_instance_text_index_lst[0].shape[0]
558
+ instance_num = len(instance_position_mask_list)
559
+ Flux2ParallelSelfAttnProcessorAPITASMKernelNonLap.cfg_inference_steps_multiplier = 2 if not is_conditional else 1
560
+
561
+ if self.strict and instance_num > 1:
562
+ areas = [mask.sum().item() for mask in instance_position_mask_list]
563
+ new_mask_list = []
564
+ for i, mask in enumerate(instance_position_mask_list):
565
+ new_mask = mask.to(query.device).clone()
566
+ for j, other_mask in enumerate(instance_position_mask_list):
567
+ if i != j and areas[j] < areas[i]:
568
+ new_mask = new_mask * (1 - other_mask.to(query.device))
569
+ new_mask_list.append(new_mask)
570
+ instance_position_mask_list = new_mask_list
571
+
572
+ if (Flux2ParallelSelfAttnProcessorAPITASMKernelNonLap.cond_hard_bind_mask is None and is_conditional) or (Flux2ParallelSelfAttnProcessorAPITASMKernelNonLap.uncond_hard_bind_mask is None and not is_conditional):
573
+ atten_mask = torch.full((query.shape[1], query.shape[1]), -float('inf'), device=query.device, dtype=query.dtype)
574
+ atten_mask = fill_hard_text_bind_mask(atten_mask, instance_text_index_lst, image_w_instance_token_index_list, seq_len, HW, instance_num, instance_position_mask_list, image_token_H, image_token_W, context_image_w_instance_token_index_list=context_image_w_instance_token_index_list)
575
+ atten_mask = fill_image_bind_mask(atten_mask, MaskType.HARD, instance_text_index_lst, image_w_instance_token_index_list, seq_len, HW, instance_num, global_seq_len, instance_position_mask_list, image_token_H, image_token_W, query, context_image_w_instance_token_index_list=context_image_w_instance_token_index_list, kernel_size=self.kernel_size, temperature=self.temperature, smooth_P_L=smooth_P_L, free_context=free_context, free_latent=free_latent, free_LC=free_LC)
576
+ Flux2ParallelSelfAttnProcessorAPITASMKernelNonLap.cond_hard_bind_mask = atten_mask if is_conditional else Flux2ParallelSelfAttnProcessorAPITASMKernelNonLap.uncond_hard_bind_mask
577
+
578
+ if (Flux2ParallelSelfAttnProcessorAPITASMKernelNonLap.cond_soft_bind_mask is None and is_conditional) or (Flux2ParallelSelfAttnProcessorAPITASMKernelNonLap.uncond_soft_bind_mask is None and not is_conditional):
579
+ atten_mask = torch.full((query.shape[1], query.shape[1]), -float('inf'), device=query.device, dtype=query.dtype)
580
+ atten_mask = fill_hard_text_bind_mask(atten_mask, instance_text_index_lst, image_w_instance_token_index_list, seq_len, HW, instance_num, instance_position_mask_list, image_token_H, image_token_W, context_image_w_instance_token_index_list=context_image_w_instance_token_index_list)
581
+ atten_mask = fill_image_bind_mask(atten_mask, MaskType.SOFT, instance_text_index_lst, image_w_instance_token_index_list, seq_len, HW, instance_num, global_seq_len, instance_position_mask_list, image_token_H, image_token_W, query, context_image_w_instance_token_index_list=context_image_w_instance_token_index_list, kernel_size=self.kernel_size, temperature=self.temperature, smooth_P_L=smooth_P_L, free_context=free_context, free_latent=free_latent, free_LC=free_LC)
582
+ Flux2ParallelSelfAttnProcessorAPITASMKernelNonLap.cond_soft_bind_mask = atten_mask if is_conditional else Flux2ParallelSelfAttnProcessorAPITASMKernelNonLap.uncond_soft_bind_mask
583
+
584
+ if Flux2ParallelSelfAttnProcessorAPITASMKernelNonLap.counter % TRANSFORMER_SINGLE_NUM_LAYERS in hard_image_attribute_binding_list_single:
585
+ atten_mask = Flux2ParallelSelfAttnProcessorAPITASMKernelNonLap.cond_hard_bind_mask if is_conditional else Flux2ParallelSelfAttnProcessorAPITASMKernelNonLap.uncond_hard_bind_mask
586
+ else:
587
+ atten_mask = Flux2ParallelSelfAttnProcessorAPITASMKernelNonLap.cond_soft_bind_mask if is_conditional else Flux2ParallelSelfAttnProcessorAPITASMKernelNonLap.uncond_soft_bind_mask
588
+
589
+ if Flux2ParallelSelfAttnProcessorAPITASMKernelNonLap.counter // TRANSFORMER_SINGLE_NUM_LAYERS not in hard_masking_steps:
590
+ if relaxed_timesteps == "full":
591
+ atten_mask = None
592
+ elif relaxed_timesteps == "soft":
593
+ atten_mask = Flux2ParallelSelfAttnProcessorAPITASMKernelNonLap.cond_soft_bind_mask if is_conditional else Flux2ParallelSelfAttnProcessorAPITASMKernelNonLap.uncond_soft_bind_mask
594
+ else:
595
+ raise NotImplementedError(f"relaxed_timesteps={relaxed_timesteps}")
596
+ Flux2ParallelSelfAttnProcessorAPITASMKernelNonLap.counter += 1
597
+
598
+ hidden_states = dispatch_attention_fn(
599
+ query,
600
+ key,
601
+ value,
602
+ attn_mask=atten_mask,
603
+ backend=self._attention_backend,
604
+ parallel_config=self._parallel_config,
605
+ )
606
+ hidden_states = hidden_states.flatten(2, 3)
607
+ hidden_states = hidden_states.to(query.dtype)
608
+
609
+ # Handle the feedforward (FF) logic
610
+ mlp_hidden_states = attn.mlp_act_fn(mlp_hidden_states)
611
+
612
+ # Concatenate and parallel output projection
613
+ hidden_states = torch.cat([hidden_states, mlp_hidden_states], dim=-1)
614
+ hidden_states = attn.to_out(hidden_states)
615
+
616
+ if Flux2ParallelSelfAttnProcessorAPITASMKernelNonLap.counter % (num_inference_steps * TRANSFORMER_SINGLE_NUM_LAYERS * Flux2ParallelSelfAttnProcessorAPITASMKernelNonLap.cfg_inference_steps_multiplier) == 0:
617
+ Flux2ParallelSelfAttnProcessorAPITASMKernelNonLap.clear_cached_masks()
618
+
619
+ return hidden_states
flux2/attention/attention_processor_base.py ADDED
@@ -0,0 +1,136 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import inspect
2
+ from typing import Any, Dict, List, Optional, Tuple, Union
3
+
4
+ import torch
5
+ from diffusers.models.embeddings import apply_rotary_emb
6
+ from diffusers.models.attention_dispatch import dispatch_attention_fn
7
+ import torch
8
+ import torch.nn as nn
9
+ import torch.nn.functional as F
10
+
11
+ from .attention_utils import _get_qkv_projections
12
+
13
+
14
+ class Flux2AttnProcessor:
15
+ _attention_backend = None
16
+ _parallel_config = None
17
+
18
+ def __init__(self):
19
+ if not hasattr(F, "scaled_dot_product_attention"):
20
+ raise ImportError(f"{self.__class__.__name__} requires PyTorch 2.0. Please upgrade your pytorch version.")
21
+
22
+ def __call__(
23
+ self,
24
+ attn: "Flux2Attention",
25
+ hidden_states: torch.Tensor,
26
+ encoder_hidden_states: torch.Tensor = None,
27
+ attention_mask: Optional[torch.Tensor] = None,
28
+ image_rotary_emb: Optional[torch.Tensor] = None,
29
+ ) -> torch.Tensor:
30
+ query, key, value, encoder_query, encoder_key, encoder_value = _get_qkv_projections(
31
+ attn, hidden_states, encoder_hidden_states
32
+ )
33
+
34
+ query = query.unflatten(-1, (attn.heads, -1))
35
+ key = key.unflatten(-1, (attn.heads, -1))
36
+ value = value.unflatten(-1, (attn.heads, -1))
37
+
38
+ query = attn.norm_q(query)
39
+ key = attn.norm_k(key)
40
+
41
+ if attn.added_kv_proj_dim is not None:
42
+ encoder_query = encoder_query.unflatten(-1, (attn.heads, -1))
43
+ encoder_key = encoder_key.unflatten(-1, (attn.heads, -1))
44
+ encoder_value = encoder_value.unflatten(-1, (attn.heads, -1))
45
+
46
+ encoder_query = attn.norm_added_q(encoder_query)
47
+ encoder_key = attn.norm_added_k(encoder_key)
48
+
49
+ query = torch.cat([encoder_query, query], dim=1)
50
+ key = torch.cat([encoder_key, key], dim=1)
51
+ value = torch.cat([encoder_value, value], dim=1)
52
+
53
+ if image_rotary_emb is not None:
54
+ query = apply_rotary_emb(query, image_rotary_emb, sequence_dim=1)
55
+ key = apply_rotary_emb(key, image_rotary_emb, sequence_dim=1)
56
+
57
+ hidden_states = dispatch_attention_fn(
58
+ query,
59
+ key,
60
+ value,
61
+ attn_mask=attention_mask,
62
+ backend=self._attention_backend,
63
+ parallel_config=self._parallel_config,
64
+ )
65
+ hidden_states = hidden_states.flatten(2, 3)
66
+ hidden_states = hidden_states.to(query.dtype)
67
+
68
+ if encoder_hidden_states is not None:
69
+ encoder_hidden_states, hidden_states = hidden_states.split_with_sizes(
70
+ [encoder_hidden_states.shape[1], hidden_states.shape[1] - encoder_hidden_states.shape[1]], dim=1
71
+ )
72
+ encoder_hidden_states = attn.to_add_out(encoder_hidden_states)
73
+
74
+ hidden_states = attn.to_out[0](hidden_states)
75
+ hidden_states = attn.to_out[1](hidden_states)
76
+
77
+ if encoder_hidden_states is not None:
78
+ return hidden_states, encoder_hidden_states
79
+ else:
80
+ return hidden_states
81
+
82
+
83
+ class Flux2ParallelSelfAttnProcessor:
84
+ _attention_backend = None
85
+ _parallel_config = None
86
+
87
+ def __init__(self):
88
+ if not hasattr(F, "scaled_dot_product_attention"):
89
+ raise ImportError(f"{self.__class__.__name__} requires PyTorch 2.0. Please upgrade your pytorch version.")
90
+
91
+ def __call__(
92
+ self,
93
+ attn: "Flux2ParallelSelfAttention",
94
+ hidden_states: torch.Tensor,
95
+ attention_mask: Optional[torch.Tensor] = None,
96
+ image_rotary_emb: Optional[torch.Tensor] = None,
97
+ ) -> torch.Tensor:
98
+ # Parallel in (QKV + MLP in) projection
99
+ hidden_states = attn.to_qkv_mlp_proj(hidden_states)
100
+ qkv, mlp_hidden_states = torch.split(
101
+ hidden_states, [3 * attn.inner_dim, attn.mlp_hidden_dim * attn.mlp_mult_factor], dim=-1
102
+ )
103
+
104
+ # Handle the attention logic
105
+ query, key, value = qkv.chunk(3, dim=-1)
106
+
107
+ query = query.unflatten(-1, (attn.heads, -1))
108
+ key = key.unflatten(-1, (attn.heads, -1))
109
+ value = value.unflatten(-1, (attn.heads, -1))
110
+
111
+ query = attn.norm_q(query)
112
+ key = attn.norm_k(key)
113
+
114
+ if image_rotary_emb is not None:
115
+ query = apply_rotary_emb(query, image_rotary_emb, sequence_dim=1)
116
+ key = apply_rotary_emb(key, image_rotary_emb, sequence_dim=1)
117
+
118
+ hidden_states = dispatch_attention_fn(
119
+ query,
120
+ key,
121
+ value,
122
+ attn_mask=attention_mask,
123
+ backend=self._attention_backend,
124
+ parallel_config=self._parallel_config,
125
+ )
126
+ hidden_states = hidden_states.flatten(2, 3)
127
+ hidden_states = hidden_states.to(query.dtype)
128
+
129
+ # Handle the feedforward (FF) logic
130
+ mlp_hidden_states = attn.mlp_act_fn(mlp_hidden_states)
131
+
132
+ # Concatenate and parallel output projection
133
+ hidden_states = torch.cat([hidden_states, mlp_hidden_states], dim=-1)
134
+ hidden_states = attn.to_out(hidden_states)
135
+
136
+ return hidden_states
flux2/attention/attention_utils.py ADDED
@@ -0,0 +1,40 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ from diffusers.models.embeddings import apply_rotary_emb
3
+ from diffusers.models.attention_dispatch import dispatch_attention_fn
4
+ from enum import Enum
5
+
6
+ class MaskType(Enum):
7
+ HARD = 'hard'
8
+ HARD2 = 'hard2'
9
+ SOFT = 'soft'
10
+
11
+
12
+ def _get_projections(attn: "Flux2Attention", hidden_states, encoder_hidden_states=None):
13
+ query = attn.to_q(hidden_states)
14
+ key = attn.to_k(hidden_states)
15
+ value = attn.to_v(hidden_states)
16
+
17
+ encoder_query = encoder_key = encoder_value = None
18
+ if encoder_hidden_states is not None and attn.added_kv_proj_dim is not None:
19
+ encoder_query = attn.add_q_proj(encoder_hidden_states)
20
+ encoder_key = attn.add_k_proj(encoder_hidden_states)
21
+ encoder_value = attn.add_v_proj(encoder_hidden_states)
22
+
23
+ return query, key, value, encoder_query, encoder_key, encoder_value
24
+
25
+
26
+ def _get_fused_projections(attn: "Flux2Attention", hidden_states, encoder_hidden_states=None):
27
+ query, key, value = attn.to_qkv(hidden_states).chunk(3, dim=-1)
28
+
29
+ encoder_query = encoder_key = encoder_value = (None,)
30
+ if encoder_hidden_states is not None and hasattr(attn, "to_added_qkv"):
31
+ encoder_query, encoder_key, encoder_value = attn.to_added_qkv(encoder_hidden_states).chunk(3, dim=-1)
32
+
33
+ return query, key, value, encoder_query, encoder_key, encoder_value
34
+
35
+
36
+ def _get_qkv_projections(attn: "Flux2Attention", hidden_states, encoder_hidden_states=None):
37
+ if attn.fused_projections:
38
+ return _get_fused_projections(attn, hidden_states, encoder_hidden_states)
39
+ return _get_projections(attn, hidden_states, encoder_hidden_states)
40
+
flux2/pipeline_flux2_klein.py ADDED
@@ -0,0 +1,1040 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2025 Black Forest Labs and The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ import inspect
16
+ from typing import Any, Callable, Dict, List, Optional, Tuple, Union
17
+
18
+ import numpy as np
19
+ import PIL
20
+ import torch
21
+ from transformers import Qwen2TokenizerFast, Qwen3ForCausalLM
22
+
23
+ from diffusers.loaders import Flux2LoraLoaderMixin
24
+ from diffusers.models import AutoencoderKLFlux2
25
+ from diffusers.schedulers import FlowMatchEulerDiscreteScheduler
26
+ from diffusers.utils import is_torch_xla_available, logging, replace_example_docstring
27
+ from diffusers.utils.torch_utils import randn_tensor
28
+ from diffusers.pipelines.pipeline_utils import DiffusionPipeline
29
+ from diffusers.pipelines.flux2.image_processor import Flux2ImageProcessor
30
+ from diffusers.pipelines.flux2.pipeline_output import Flux2PipelineOutput
31
+
32
+ from .transformer_flux2_klein import Flux2Transformer2DModel
33
+ from .pipeline_utils import find_inner_sentence_token_span_qwen, create_position_mask_list, resize_mask
34
+
35
+
36
+ if is_torch_xla_available():
37
+ import torch_xla.core.xla_model as xm
38
+
39
+ XLA_AVAILABLE = True
40
+ else:
41
+ XLA_AVAILABLE = False
42
+
43
+
44
+ logger = logging.get_logger(__name__) # pylint: disable=invalid-name
45
+
46
+ EXAMPLE_DOC_STRING = """
47
+ Examples:
48
+ ```py
49
+ >>> import torch
50
+ >>> from diffusers import Flux2KleinPipeline
51
+
52
+ >>> pipe = Flux2KleinPipeline.from_pretrained(
53
+ ... "black-forest-labs/FLUX.2-klein-base-9B", torch_dtype=torch.bfloat16
54
+ ... )
55
+ >>> pipe.to("cuda")
56
+ >>> prompt = "A cat holding a sign that says hello world"
57
+ >>> # Depending on the variant being used, the pipeline call will slightly vary.
58
+ >>> # Refer to the pipeline documentation for more details.
59
+ >>> image = pipe(prompt, num_inference_steps=50, guidance_scale=4.0).images[0]
60
+ >>> image.save("flux2_output.png")
61
+ ```
62
+ """
63
+
64
+
65
+ # Copied from diffusers.pipelines.flux2.pipeline_flux2.compute_empirical_mu
66
+ def compute_empirical_mu(image_seq_len: int, num_steps: int) -> float:
67
+ a1, b1 = 8.73809524e-05, 1.89833333
68
+ a2, b2 = 0.00016927, 0.45666666
69
+
70
+ if image_seq_len > 4300:
71
+ mu = a2 * image_seq_len + b2
72
+ return float(mu)
73
+
74
+ m_200 = a2 * image_seq_len + b2
75
+ m_10 = a1 * image_seq_len + b1
76
+
77
+ a = (m_200 - m_10) / 190.0
78
+ b = m_200 - 200.0 * a
79
+ mu = a * num_steps + b
80
+
81
+ return float(mu)
82
+
83
+
84
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.retrieve_timesteps
85
+ def retrieve_timesteps(
86
+ scheduler,
87
+ num_inference_steps: Optional[int] = None,
88
+ device: Optional[Union[str, torch.device]] = None,
89
+ timesteps: Optional[List[int]] = None,
90
+ sigmas: Optional[List[float]] = None,
91
+ **kwargs,
92
+ ):
93
+ r"""
94
+ Calls the scheduler's `set_timesteps` method and retrieves timesteps from the scheduler after the call. Handles
95
+ custom timesteps. Any kwargs will be supplied to `scheduler.set_timesteps`.
96
+
97
+ Args:
98
+ scheduler (`SchedulerMixin`):
99
+ The scheduler to get timesteps from.
100
+ num_inference_steps (`int`):
101
+ The number of diffusion steps used when generating samples with a pre-trained model. If used, `timesteps`
102
+ must be `None`.
103
+ device (`str` or `torch.device`, *optional*):
104
+ The device to which the timesteps should be moved to. If `None`, the timesteps are not moved.
105
+ timesteps (`List[int]`, *optional*):
106
+ Custom timesteps used to override the timestep spacing strategy of the scheduler. If `timesteps` is passed,
107
+ `num_inference_steps` and `sigmas` must be `None`.
108
+ sigmas (`List[float]`, *optional*):
109
+ Custom sigmas used to override the timestep spacing strategy of the scheduler. If `sigmas` is passed,
110
+ `num_inference_steps` and `timesteps` must be `None`.
111
+
112
+ Returns:
113
+ `Tuple[torch.Tensor, int]`: A tuple where the first element is the timestep schedule from the scheduler and the
114
+ second element is the number of inference steps.
115
+ """
116
+ if timesteps is not None and sigmas is not None:
117
+ raise ValueError("Only one of `timesteps` or `sigmas` can be passed. Please choose one to set custom values")
118
+ if timesteps is not None:
119
+ accepts_timesteps = "timesteps" in set(inspect.signature(scheduler.set_timesteps).parameters.keys())
120
+ if not accepts_timesteps:
121
+ raise ValueError(
122
+ f"The current scheduler class {scheduler.__class__}'s `set_timesteps` does not support custom"
123
+ f" timestep schedules. Please check whether you are using the correct scheduler."
124
+ )
125
+ scheduler.set_timesteps(timesteps=timesteps, device=device, **kwargs)
126
+ timesteps = scheduler.timesteps
127
+ num_inference_steps = len(timesteps)
128
+ elif sigmas is not None:
129
+ accept_sigmas = "sigmas" in set(inspect.signature(scheduler.set_timesteps).parameters.keys())
130
+ if not accept_sigmas:
131
+ raise ValueError(
132
+ f"The current scheduler class {scheduler.__class__}'s `set_timesteps` does not support custom"
133
+ f" sigmas schedules. Please check whether you are using the correct scheduler."
134
+ )
135
+ scheduler.set_timesteps(sigmas=sigmas, device=device, **kwargs)
136
+ timesteps = scheduler.timesteps
137
+ num_inference_steps = len(timesteps)
138
+ else:
139
+ scheduler.set_timesteps(num_inference_steps, device=device, **kwargs)
140
+ timesteps = scheduler.timesteps
141
+ return timesteps, num_inference_steps
142
+
143
+
144
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion_img2img.retrieve_latents
145
+ def retrieve_latents(
146
+ encoder_output: torch.Tensor, generator: Optional[torch.Generator] = None, sample_mode: str = "sample"
147
+ ):
148
+ if hasattr(encoder_output, "latent_dist") and sample_mode == "sample":
149
+ return encoder_output.latent_dist.sample(generator)
150
+ elif hasattr(encoder_output, "latent_dist") and sample_mode == "argmax":
151
+ return encoder_output.latent_dist.mode()
152
+ elif hasattr(encoder_output, "latents"):
153
+ return encoder_output.latents
154
+ else:
155
+ raise AttributeError("Could not access latents of provided encoder_output")
156
+
157
+
158
+ class Flux2KleinPipeline(DiffusionPipeline, Flux2LoraLoaderMixin):
159
+ r"""
160
+ The Flux2 Klein pipeline for text-to-image generation.
161
+
162
+ Reference:
163
+ [https://bfl.ai/blog/flux2-klein-towards-interactive-visual-intelligence](https://bfl.ai/blog/flux2-klein-towards-interactive-visual-intelligence)
164
+
165
+ Args:
166
+ transformer ([`Flux2Transformer2DModel`]):
167
+ Conditional Transformer (MMDiT) architecture to denoise the encoded image latents.
168
+ scheduler ([`FlowMatchEulerDiscreteScheduler`]):
169
+ A scheduler to be used in combination with `transformer` to denoise the encoded image latents.
170
+ vae ([`AutoencoderKLFlux2`]):
171
+ Variational Auto-Encoder (VAE) Model to encode and decode images to and from latent representations.
172
+ text_encoder ([`Qwen3ForCausalLM`]):
173
+ [Qwen3ForCausalLM](https://huggingface.co/docs/transformers/en/model_doc/qwen3#transformers.Qwen3ForCausalLM)
174
+ tokenizer (`Qwen2TokenizerFast`):
175
+ Tokenizer of class
176
+ [Qwen2TokenizerFast](https://huggingface.co/docs/transformers/en/model_doc/qwen2#transformers.Qwen2TokenizerFast).
177
+ """
178
+
179
+ model_cpu_offload_seq = "text_encoder->transformer->vae"
180
+ _callback_tensor_inputs = ["latents", "prompt_embeds"]
181
+
182
+ def __init__(
183
+ self,
184
+ scheduler: FlowMatchEulerDiscreteScheduler,
185
+ vae: AutoencoderKLFlux2,
186
+ text_encoder: Qwen3ForCausalLM,
187
+ tokenizer: Qwen2TokenizerFast,
188
+ transformer: Flux2Transformer2DModel,
189
+ is_distilled: bool = False,
190
+ ):
191
+ super().__init__()
192
+
193
+ self.register_modules(
194
+ vae=vae,
195
+ text_encoder=text_encoder,
196
+ tokenizer=tokenizer,
197
+ scheduler=scheduler,
198
+ transformer=transformer,
199
+ )
200
+
201
+ self.register_to_config(is_distilled=is_distilled)
202
+
203
+ self.vae_scale_factor = 2 ** (len(self.vae.config.block_out_channels) - 1) if getattr(self, "vae", None) else 8
204
+ # Flux latents are turned into 2x2 patches and packed. This means the latent width and height has to be divisible
205
+ # by the patch size. So the vae scale factor is multiplied by the patch size to account for this
206
+ self.image_processor = Flux2ImageProcessor(vae_scale_factor=self.vae_scale_factor * 2)
207
+ self.tokenizer_max_length = 512
208
+ self.default_sample_size = 128
209
+
210
+ @staticmethod
211
+ def _get_qwen3_prompt_embeds(
212
+ text_encoder: Qwen3ForCausalLM,
213
+ tokenizer: Qwen2TokenizerFast,
214
+ prompt: Union[str, List[str]],
215
+ dtype: Optional[torch.dtype] = None,
216
+ device: Optional[torch.device] = None,
217
+ max_sequence_length: int = 512,
218
+ hidden_states_layers: List[int] = (9, 18, 27),
219
+ prompt_settings: str = None,
220
+ num_instance_text_tokens: int = 200,
221
+ num_global_text_tokens: int = 200,
222
+ ):
223
+ assert prompt_settings in ['base', 'inner_local_prompts', 'outer_local_prompts', 'outer_global_prompts'], 'prompt_settings must be one of base, inner_local_prompts, outer_local_prompts, outer_global_prompts'
224
+ dtype = text_encoder.dtype if dtype is None else dtype
225
+ device = text_encoder.device if device is None else device
226
+
227
+ prompt = [prompt] if isinstance(prompt, str) else prompt
228
+ batch_size = len(prompt)
229
+
230
+ prompt = [prompt_.split('$BREAKFLAG$') for prompt_ in prompt]
231
+ if prompt_settings in ['inner_local_prompts', 'base']:
232
+ prompt_to_encode = [prompt_[0] for prompt_ in prompt]
233
+ elif prompt_settings in ['outer_local_prompts', 'outer_local_prompts_smart']:
234
+ prompt_to_encode = prompt[0]
235
+ assert batch_size == 1, "Batch size must be 1 for outer local prompts"
236
+ else:
237
+ raise ValueError(f"Invalid prompt settings: {prompt_settings}")
238
+
239
+ all_input_ids = []
240
+ all_attention_masks = []
241
+
242
+ for single_prompt in prompt_to_encode:
243
+ messages = [{"role": "user", "content": single_prompt}]
244
+ text = tokenizer.apply_chat_template(
245
+ messages,
246
+ tokenize=False,
247
+ add_generation_prompt=True,
248
+ enable_thinking=False,
249
+ )
250
+ inputs = tokenizer(
251
+ text,
252
+ return_tensors="pt",
253
+ padding="max_length",
254
+ truncation=True,
255
+ max_length=max_sequence_length,
256
+ )
257
+
258
+ all_input_ids.append(inputs["input_ids"])
259
+ all_attention_masks.append(inputs["attention_mask"])
260
+
261
+ input_ids = torch.cat(all_input_ids, dim=0).to(device)
262
+ attention_mask = torch.cat(all_attention_masks, dim=0).to(device)
263
+
264
+ # Forward pass through the model
265
+ output = text_encoder(
266
+ input_ids=input_ids,
267
+ attention_mask=attention_mask,
268
+ output_hidden_states=True,
269
+ use_cache=False,
270
+ )
271
+
272
+ # Only use outputs from intermediate layers and stack them
273
+ out = torch.stack([output.hidden_states[k] for k in hidden_states_layers], dim=1)
274
+ out = out.to(dtype=dtype, device=device)
275
+
276
+ batched_instance_text_index_lst = []
277
+
278
+ # Initialize seq_len for the base case
279
+ # seq_len = out.shape[2]
280
+
281
+ if prompt_settings in ['inner_local_prompts', 'base']:
282
+ batched_inner_sentences = [prompt_[1:] for prompt_ in prompt]
283
+ for batch_idx, inner_sentences in enumerate(batched_inner_sentences):
284
+ instance_text_index_lst = []
285
+ for inner_sentence in inner_sentences:
286
+ inner_mask = torch.zeros_like(attention_mask[batch_idx])
287
+ start, end = find_inner_sentence_token_span_qwen(tokenizer, prompt_to_encode[batch_idx], inner_sentence, max_sequence_length=max_sequence_length)
288
+ if start is None:
289
+ logger.warning(f"Inner sentence not found in tokenized prompt: {inner_sentence}")
290
+ else:
291
+ inner_mask[start:end] = 1
292
+ instance_text_index_lst.append(inner_mask)
293
+ batched_instance_text_index_lst.append(instance_text_index_lst)
294
+ elif prompt_settings in ['outer_local_prompts', 'outer_local_prompts_smart']:
295
+ begin_idx = 0
296
+ out_list = []
297
+ instance_text_index_lst = []
298
+ for i, _ in enumerate(prompt_to_encode):
299
+ num_tokens_to_select = num_global_text_tokens
300
+ if i != 0:
301
+ num_tokens_to_select = torch.sum(input_ids[i] != 0).item() if prompt_settings == 'outer_local_prompts_smart' else num_instance_text_tokens
302
+ out_list.append(out[[i], :, :num_tokens_to_select, :].contiguous())
303
+ instance_text_index = torch.arange(begin_idx, begin_idx+num_tokens_to_select).int()
304
+ instance_text_index_lst.append(instance_text_index)
305
+ begin_idx += num_tokens_to_select
306
+
307
+ out = torch.cat(out_list, dim=2)
308
+ batched_instance_text_index_lst.append(instance_text_index_lst)
309
+ else:
310
+ raise ValueError(f"Invalid prompt settings: {prompt_settings}")
311
+
312
+ batch_size, num_channels, seq_len, hidden_dim = out.shape
313
+ out = out.permute(0, 2, 1, 3).reshape(batch_size, seq_len, num_channels * hidden_dim)
314
+
315
+ return out, batched_instance_text_index_lst, seq_len
316
+
317
+ @staticmethod
318
+ # Copied from diffusers.pipelines.flux2.pipeline_flux2.Flux2Pipeline._prepare_text_ids
319
+ def _prepare_text_ids(
320
+ x: torch.Tensor, # (B, L, D) or (L, D)
321
+ t_coord: Optional[torch.Tensor] = None,
322
+ ):
323
+ B, L, _ = x.shape
324
+ out_ids = []
325
+
326
+ for i in range(B):
327
+ t = torch.arange(1) if t_coord is None else t_coord[i]
328
+ h = torch.arange(1)
329
+ w = torch.arange(1)
330
+ l = torch.arange(L)
331
+
332
+ coords = torch.cartesian_prod(t, h, w, l)
333
+ out_ids.append(coords)
334
+
335
+ return torch.stack(out_ids)
336
+
337
+ @staticmethod
338
+ # Copied from diffusers.pipelines.flux2.pipeline_flux2.Flux2Pipeline._prepare_latent_ids
339
+ def _prepare_latent_ids(
340
+ latents: torch.Tensor, # (B, C, H, W)
341
+ ):
342
+ r"""
343
+ Generates 4D position coordinates (T, H, W, L) for latent tensors.
344
+
345
+ Args:
346
+ latents (torch.Tensor):
347
+ Latent tensor of shape (B, C, H, W)
348
+
349
+ Returns:
350
+ torch.Tensor:
351
+ Position IDs tensor of shape (B, H*W, 4) All batches share the same coordinate structure: T=0,
352
+ H=[0..H-1], W=[0..W-1], L=0
353
+ """
354
+
355
+ batch_size, _, height, width = latents.shape
356
+
357
+ t = torch.arange(1) # [0] - time dimension
358
+ h = torch.arange(height)
359
+ w = torch.arange(width)
360
+ l = torch.arange(1) # [0] - layer dimension
361
+
362
+ # Create position IDs: (H*W, 4)
363
+ latent_ids = torch.cartesian_prod(t, h, w, l)
364
+
365
+ # Expand to batch: (B, H*W, 4)
366
+ latent_ids = latent_ids.unsqueeze(0).expand(batch_size, -1, -1)
367
+
368
+ return latent_ids
369
+
370
+ @staticmethod
371
+ # Copied from diffusers.pipelines.flux2.pipeline_flux2.Flux2Pipeline._prepare_image_ids
372
+ def _prepare_image_ids(
373
+ image_latents: List[torch.Tensor], # [(1, C, H, W), (1, C, H, W), ...]
374
+ scale: int = 10,
375
+ ):
376
+ r"""
377
+ Generates 4D time-space coordinates (T, H, W, L) for a sequence of image latents.
378
+
379
+ This function creates a unique coordinate for every pixel/patch across all input latent with different
380
+ dimensions.
381
+
382
+ Args:
383
+ image_latents (List[torch.Tensor]):
384
+ A list of image latent feature tensors, typically of shape (C, H, W).
385
+ scale (int, optional):
386
+ A factor used to define the time separation (T-coordinate) between latents. T-coordinate for the i-th
387
+ latent is: 'scale + scale * i'. Defaults to 10.
388
+
389
+ Returns:
390
+ torch.Tensor:
391
+ The combined coordinate tensor. Shape: (1, N_total, 4) Where N_total is the sum of (H * W) for all
392
+ input latents.
393
+
394
+ Coordinate Components (Dimension 4):
395
+ - T (Time): The unique index indicating which latent image the coordinate belongs to.
396
+ - H (Height): The row index within that latent image.
397
+ - W (Width): The column index within that latent image.
398
+ - L (Seq. Length): A sequence length dimension, which is always fixed at 0 (size 1)
399
+ """
400
+
401
+ if not isinstance(image_latents, list):
402
+ raise ValueError(f"Expected `image_latents` to be a list, got {type(image_latents)}.")
403
+
404
+ # create time offset for each reference image
405
+ t_coords = [scale + scale * t for t in torch.arange(0, len(image_latents))]
406
+ t_coords = [t.view(-1) for t in t_coords]
407
+
408
+ image_latent_ids = []
409
+ for x, t in zip(image_latents, t_coords):
410
+ x = x.squeeze(0)
411
+ _, height, width = x.shape
412
+
413
+ x_ids = torch.cartesian_prod(t, torch.arange(height), torch.arange(width), torch.arange(1))
414
+ image_latent_ids.append(x_ids)
415
+
416
+ image_latent_ids = torch.cat(image_latent_ids, dim=0)
417
+ image_latent_ids = image_latent_ids.unsqueeze(0)
418
+
419
+ return image_latent_ids
420
+
421
+ @staticmethod
422
+ # Copied from diffusers.pipelines.flux2.pipeline_flux2.Flux2Pipeline._patchify_latents
423
+ def _patchify_latents(latents):
424
+ batch_size, num_channels_latents, height, width = latents.shape
425
+ latents = latents.view(batch_size, num_channels_latents, height // 2, 2, width // 2, 2)
426
+ latents = latents.permute(0, 1, 3, 5, 2, 4)
427
+ latents = latents.reshape(batch_size, num_channels_latents * 4, height // 2, width // 2)
428
+ return latents
429
+
430
+ @staticmethod
431
+ # Copied from diffusers.pipelines.flux2.pipeline_flux2.Flux2Pipeline._unpatchify_latents
432
+ def _unpatchify_latents(latents):
433
+ batch_size, num_channels_latents, height, width = latents.shape
434
+ latents = latents.reshape(batch_size, num_channels_latents // (2 * 2), 2, 2, height, width)
435
+ latents = latents.permute(0, 1, 4, 2, 5, 3)
436
+ latents = latents.reshape(batch_size, num_channels_latents // (2 * 2), height * 2, width * 2)
437
+ return latents
438
+
439
+ @staticmethod
440
+ # Copied from diffusers.pipelines.flux2.pipeline_flux2.Flux2Pipeline._pack_latents
441
+ def _pack_latents(latents):
442
+ """
443
+ pack latents: (batch_size, num_channels, height, width) -> (batch_size, height * width, num_channels)
444
+ """
445
+
446
+ batch_size, num_channels, height, width = latents.shape
447
+ latents = latents.reshape(batch_size, num_channels, height * width).permute(0, 2, 1)
448
+
449
+ return latents
450
+
451
+ @staticmethod
452
+ # Copied from diffusers.pipelines.flux2.pipeline_flux2.Flux2Pipeline._unpack_latents_with_ids
453
+ def _unpack_latents_with_ids(x: torch.Tensor, x_ids: torch.Tensor) -> list[torch.Tensor]:
454
+ """
455
+ using position ids to scatter tokens into place
456
+ """
457
+ x_list = []
458
+ for data, pos in zip(x, x_ids):
459
+ _, ch = data.shape # noqa: F841
460
+ h_ids = pos[:, 1].to(torch.int64)
461
+ w_ids = pos[:, 2].to(torch.int64)
462
+
463
+ h = torch.max(h_ids) + 1
464
+ w = torch.max(w_ids) + 1
465
+
466
+ flat_ids = h_ids * w + w_ids
467
+
468
+ out = torch.zeros((h * w, ch), device=data.device, dtype=data.dtype)
469
+ out.scatter_(0, flat_ids.unsqueeze(1).expand(-1, ch), data)
470
+
471
+ # reshape from (H * W, C) to (H, W, C) and permute to (C, H, W)
472
+
473
+ out = out.view(h, w, ch).permute(2, 0, 1)
474
+ x_list.append(out)
475
+
476
+ return torch.stack(x_list, dim=0)
477
+
478
+ def encode_prompt(
479
+ self,
480
+ prompt: Union[str, List[str]],
481
+ device: Optional[torch.device] = None,
482
+ num_images_per_prompt: int = 1,
483
+ prompt_embeds: Optional[torch.Tensor] = None,
484
+ max_sequence_length: int = 512,
485
+ text_encoder_out_layers: Tuple[int] = (9, 18, 27),
486
+ prompt_settings: str = None,
487
+ num_instance_text_tokens: int = 200,
488
+ num_global_text_tokens: int = 200,
489
+ ):
490
+ device = device or self._execution_device
491
+
492
+ if prompt is None:
493
+ prompt = ""
494
+
495
+ prompt = [prompt] if isinstance(prompt, str) else prompt
496
+
497
+ if prompt_embeds is None:
498
+ prompt_embeds, batched_instance_text_index_lst, seq_len = self._get_qwen3_prompt_embeds(
499
+ text_encoder=self.text_encoder,
500
+ tokenizer=self.tokenizer,
501
+ prompt=prompt,
502
+ device=device,
503
+ max_sequence_length=max_sequence_length,
504
+ hidden_states_layers=text_encoder_out_layers,
505
+ prompt_settings=prompt_settings,
506
+ num_instance_text_tokens=num_instance_text_tokens,
507
+ num_global_text_tokens=num_global_text_tokens,
508
+ )
509
+
510
+ batch_size, seq_len, _ = prompt_embeds.shape
511
+ prompt_embeds = prompt_embeds.repeat(1, num_images_per_prompt, 1)
512
+ prompt_embeds = prompt_embeds.view(batch_size * num_images_per_prompt, seq_len, -1)
513
+
514
+ text_ids = self._prepare_text_ids(prompt_embeds)
515
+ text_ids = text_ids.to(device)
516
+ return prompt_embeds, text_ids, batched_instance_text_index_lst, seq_len
517
+
518
+ # Copied from diffusers.pipelines.flux2.pipeline_flux2.Flux2Pipeline._encode_vae_image
519
+ def _encode_vae_image(self, image: torch.Tensor, generator: torch.Generator):
520
+ if image.ndim != 4:
521
+ raise ValueError(f"Expected image dims 4, got {image.ndim}.")
522
+
523
+ image_latents = retrieve_latents(self.vae.encode(image), generator=generator, sample_mode="argmax")
524
+ image_latents = self._patchify_latents(image_latents)
525
+
526
+ latents_bn_mean = self.vae.bn.running_mean.view(1, -1, 1, 1).to(image_latents.device, image_latents.dtype)
527
+ latents_bn_std = torch.sqrt(self.vae.bn.running_var.view(1, -1, 1, 1) + self.vae.config.batch_norm_eps)
528
+ image_latents = (image_latents - latents_bn_mean) / latents_bn_std
529
+
530
+ return image_latents
531
+
532
+ # Copied from diffusers.pipelines.flux2.pipeline_flux2.Flux2Pipeline.prepare_latents
533
+ def prepare_latents(
534
+ self,
535
+ batch_size,
536
+ num_latents_channels,
537
+ height,
538
+ width,
539
+ dtype,
540
+ device,
541
+ generator: torch.Generator,
542
+ latents: Optional[torch.Tensor] = None,
543
+ ):
544
+ # VAE applies 8x compression on images but we must also account for packing which requires
545
+ # latent height and width to be divisible by 2.
546
+ height = 2 * (int(height) // (self.vae_scale_factor * 2))
547
+ width = 2 * (int(width) // (self.vae_scale_factor * 2))
548
+
549
+ shape = (batch_size, num_latents_channels * 4, height // 2, width // 2)
550
+ if isinstance(generator, list) and len(generator) != batch_size:
551
+ raise ValueError(
552
+ f"You have passed a list of generators of length {len(generator)}, but requested an effective batch"
553
+ f" size of {batch_size}. Make sure the batch size matches the length of the generators."
554
+ )
555
+ if latents is None:
556
+ latents = randn_tensor(shape, generator=generator, device=device, dtype=dtype)
557
+ else:
558
+ latents = latents.to(device=device, dtype=dtype)
559
+
560
+ latent_ids = self._prepare_latent_ids(latents)
561
+ latent_ids = latent_ids.to(device)
562
+
563
+ latents = self._pack_latents(latents) # [B, C, H, W] -> [B, H*W, C]
564
+ return latents, latent_ids
565
+
566
+ # Copied from diffusers.pipelines.flux2.pipeline_flux2.Flux2Pipeline.prepare_image_latents
567
+ def prepare_image_latents(
568
+ self,
569
+ images: List[torch.Tensor],
570
+ batch_size,
571
+ generator: torch.Generator,
572
+ device,
573
+ dtype,
574
+ ):
575
+ image_latents = []
576
+ for image in images:
577
+ image = image.to(device=device, dtype=dtype)
578
+ imagge_latent = self._encode_vae_image(image=image, generator=generator)
579
+ image_latents.append(imagge_latent) # (1, 128, 32, 32)
580
+
581
+ image_latent_ids = self._prepare_image_ids(image_latents)
582
+
583
+ # Pack each latent and concatenate
584
+ packed_latents = []
585
+ for latent in image_latents:
586
+ # latent: (1, 128, 32, 32)
587
+ packed = self._pack_latents(latent) # (1, 1024, 128)
588
+ packed = packed.squeeze(0) # (1024, 128) - remove batch dim
589
+ packed_latents.append(packed)
590
+
591
+ # Concatenate all reference tokens along sequence dimension
592
+ image_latents = torch.cat(packed_latents, dim=0) # (N*1024, 128)
593
+ image_latents = image_latents.unsqueeze(0) # (1, N*1024, 128)
594
+
595
+ image_latents = image_latents.repeat(batch_size, 1, 1)
596
+ image_latent_ids = image_latent_ids.repeat(batch_size, 1, 1)
597
+ image_latent_ids = image_latent_ids.to(device)
598
+
599
+ return image_latents, image_latent_ids
600
+
601
+ def check_inputs(
602
+ self,
603
+ prompt,
604
+ height,
605
+ width,
606
+ prompt_embeds=None,
607
+ callback_on_step_end_tensor_inputs=None,
608
+ guidance_scale=None,
609
+ ):
610
+ if (
611
+ height is not None
612
+ and height % (self.vae_scale_factor * 2) != 0
613
+ or width is not None
614
+ and width % (self.vae_scale_factor * 2) != 0
615
+ ):
616
+ logger.warning(
617
+ f"`height` and `width` have to be divisible by {self.vae_scale_factor * 2} but are {height} and {width}. Dimensions will be resized accordingly"
618
+ )
619
+
620
+ if callback_on_step_end_tensor_inputs is not None and not all(
621
+ k in self._callback_tensor_inputs for k in callback_on_step_end_tensor_inputs
622
+ ):
623
+ raise ValueError(
624
+ 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]}"
625
+ )
626
+
627
+ if prompt is not None and prompt_embeds is not None:
628
+ raise ValueError(
629
+ f"Cannot forward both `prompt`: {prompt} and `prompt_embeds`: {prompt_embeds}. Please make sure to"
630
+ " only forward one of the two."
631
+ )
632
+ elif prompt is None and prompt_embeds is None:
633
+ raise ValueError(
634
+ "Provide either `prompt` or `prompt_embeds`. Cannot leave both `prompt` and `prompt_embeds` undefined."
635
+ )
636
+ elif prompt is not None and (not isinstance(prompt, str) and not isinstance(prompt, list)):
637
+ raise ValueError(f"`prompt` has to be of type `str` or `list` but is {type(prompt)}")
638
+
639
+ if guidance_scale > 1.0 and self.config.is_distilled:
640
+ logger.warning(f"Guidance scale {guidance_scale} is ignored for step-wise distilled models.")
641
+
642
+ @property
643
+ def guidance_scale(self):
644
+ return self._guidance_scale
645
+
646
+ @property
647
+ def do_classifier_free_guidance(self):
648
+ return self._guidance_scale > 1 and not self.config.is_distilled
649
+
650
+ @property
651
+ def attention_kwargs(self):
652
+ return self._attention_kwargs
653
+
654
+ @property
655
+ def num_timesteps(self):
656
+ return self._num_timesteps
657
+
658
+ @property
659
+ def current_timestep(self):
660
+ return self._current_timestep
661
+
662
+ @property
663
+ def interrupt(self):
664
+ return self._interrupt
665
+
666
+ @torch.no_grad()
667
+ @replace_example_docstring(EXAMPLE_DOC_STRING)
668
+ def __call__(
669
+ self,
670
+ image: Optional[Union[List[PIL.Image.Image], PIL.Image.Image]] = None,
671
+ prompt: Union[str, List[str]] = None,
672
+ height: Optional[int] = None,
673
+ width: Optional[int] = None,
674
+ num_inference_steps: int = 50,
675
+ sigmas: Optional[List[float]] = None,
676
+ guidance_scale: Optional[float] = 4.0,
677
+ num_images_per_prompt: int = 1,
678
+ generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
679
+ latents: Optional[torch.Tensor] = None,
680
+ prompt_embeds: Optional[torch.Tensor] = None,
681
+ negative_prompt_embeds: Optional[Union[str, List[str]]] = None,
682
+ output_type: Optional[str] = "pil",
683
+ return_dict: bool = True,
684
+ attention_kwargs: Optional[Dict[str, Any]] = None,
685
+ callback_on_step_end: Optional[Callable[[int, int, Dict], None]] = None,
686
+ callback_on_step_end_tensor_inputs: List[str] = ["latents"],
687
+ max_sequence_length: int = 512,
688
+ text_encoder_out_layers: Tuple[int] = (9, 18, 27),
689
+ # APITA
690
+ attention_setting: str = 'full',
691
+ prompt_settings: str = 'inner_local_prompts',
692
+ hard_image_attribute_binding_list_double = [],
693
+ hard_image_attribute_binding_list_single = [],
694
+ instance_bboxes_xyxy_normalized: list[list[float]] = None,
695
+ instance_masks_yx: list[torch.Tensor] = None,
696
+ bring_area_to_1024_squared: bool = True,
697
+ hard_masking_steps: List = None,
698
+ relaxed_timesteps: str = None,
699
+ free_latent: bool = False,
700
+ free_context: bool = False,
701
+ free_LC: bool = False,
702
+ ):
703
+ r"""
704
+ Function invoked when calling the pipeline for generation.
705
+
706
+ Args:
707
+ image (`torch.Tensor`, `PIL.Image.Image`, `np.ndarray`, `List[torch.Tensor]`, `List[PIL.Image.Image]`, or `List[np.ndarray]`):
708
+ `Image`, numpy array or tensor representing an image batch to be used as the starting point. For both
709
+ numpy array and pytorch tensor, the expected value range is between `[0, 1]` If it's a tensor or a list
710
+ or tensors, the expected shape should be `(B, C, H, W)` or `(C, H, W)`. If it is a numpy array or a
711
+ list of arrays, the expected shape should be `(B, H, W, C)` or `(H, W, C)` It can also accept image
712
+ latents as `image`, but if passing latents directly it is not encoded again.
713
+ prompt (`str` or `List[str]`, *optional*):
714
+ The prompt or prompts to guide the image generation. If not defined, one has to pass `prompt_embeds`.
715
+ instead.
716
+ guidance_scale (`float`, *optional*, defaults to 4.0):
717
+ Guidance scale as defined in [Classifier-Free Diffusion
718
+ Guidance](https://huggingface.co/papers/2207.12598). `guidance_scale` is defined as `w` of equation 2.
719
+ of [Imagen Paper](https://huggingface.co/papers/2205.11487). Guidance scale is enabled by setting
720
+ `guidance_scale > 1`. Higher guidance scale encourages to generate images that are closely linked to
721
+ the text `prompt`, usually at the expense of lower image quality. For step-wise distilled models,
722
+ `guidance_scale` is ignored.
723
+ height (`int`, *optional*, defaults to self.unet.config.sample_size * self.vae_scale_factor):
724
+ The height in pixels of the generated image. This is set to 1024 by default for the best results.
725
+ width (`int`, *optional*, defaults to self.unet.config.sample_size * self.vae_scale_factor):
726
+ The width in pixels of the generated image. This is set to 1024 by default for the best results.
727
+ num_inference_steps (`int`, *optional*, defaults to 50):
728
+ The number of denoising steps. More denoising steps usually lead to a higher quality image at the
729
+ expense of slower inference.
730
+ sigmas (`List[float]`, *optional*):
731
+ Custom sigmas to use for the denoising process with schedulers which support a `sigmas` argument in
732
+ their `set_timesteps` method. If not defined, the default behavior when `num_inference_steps` is passed
733
+ will be used.
734
+ num_images_per_prompt (`int`, *optional*, defaults to 1):
735
+ The number of images to generate per prompt.
736
+ generator (`torch.Generator` or `List[torch.Generator]`, *optional*):
737
+ One or a list of [torch generator(s)](https://pytorch.org/docs/stable/generated/torch.Generator.html)
738
+ to make generation deterministic.
739
+ latents (`torch.Tensor`, *optional*):
740
+ Pre-generated noisy latents, sampled from a Gaussian distribution, to be used as inputs for image
741
+ generation. Can be used to tweak the same generation with different prompts. If not provided, a latents
742
+ tensor will be generated by sampling using the supplied random `generator`.
743
+ prompt_embeds (`torch.Tensor`, *optional*):
744
+ Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not
745
+ provided, text embeddings will be generated from `prompt` input argument.
746
+ negative_prompt_embeds (`torch.Tensor`, *optional*):
747
+ Pre-generated negative text embeddings. Note that "" is used as the negative prompt in this pipeline.
748
+ If not provided, will be generated from "".
749
+ output_type (`str`, *optional*, defaults to `"pil"`):
750
+ The output format of the generate image. Choose between
751
+ [PIL](https://pillow.readthedocs.io/en/stable/): `PIL.Image.Image` or `np.array`.
752
+ return_dict (`bool`, *optional*, defaults to `True`):
753
+ Whether or not to return a [`~pipelines.qwenimage.QwenImagePipelineOutput`] instead of a plain tuple.
754
+ attention_kwargs (`dict`, *optional*):
755
+ A kwargs dictionary that if specified is passed along to the `AttentionProcessor` as defined under
756
+ `self.processor` in
757
+ [diffusers.models.attention_processor](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py).
758
+ callback_on_step_end (`Callable`, *optional*):
759
+ A function that calls at the end of each denoising steps during the inference. The function is called
760
+ with the following arguments: `callback_on_step_end(self: DiffusionPipeline, step: int, timestep: int,
761
+ callback_kwargs: Dict)`. `callback_kwargs` will include a list of all tensors as specified by
762
+ `callback_on_step_end_tensor_inputs`.
763
+ callback_on_step_end_tensor_inputs (`List`, *optional*):
764
+ The list of tensor inputs for the `callback_on_step_end` function. The tensors specified in the list
765
+ will be passed as `callback_kwargs` argument. You will only be able to include variables listed in the
766
+ `._callback_tensor_inputs` attribute of your pipeline class.
767
+ max_sequence_length (`int` defaults to 512): Maximum sequence length to use with the `prompt`.
768
+ text_encoder_out_layers (`Tuple[int]`):
769
+ Layer indices to use in the `text_encoder` to derive the final prompt embeddings.
770
+
771
+ Examples:
772
+
773
+ Returns:
774
+ [`~pipelines.flux2.Flux2PipelineOutput`] or `tuple`: [`~pipelines.flux2.Flux2PipelineOutput`] if
775
+ `return_dict` is True, otherwise a `tuple`. When returning a tuple, the first element is a list with the
776
+ generated images.
777
+ """
778
+
779
+ assert hard_masking_steps != None, "hard masking steps need to be selected"
780
+ assert relaxed_timesteps != None, "relaxed timestep behavior needs to be selected"
781
+
782
+ # 1. Check inputs. Raise error if not correct
783
+ self.check_inputs(
784
+ prompt=prompt,
785
+ height=height,
786
+ width=width,
787
+ prompt_embeds=prompt_embeds,
788
+ callback_on_step_end_tensor_inputs=callback_on_step_end_tensor_inputs,
789
+ guidance_scale=guidance_scale,
790
+ )
791
+ assert instance_bboxes_xyxy_normalized is not None or instance_masks_yx is not None, "instance_bboxes_xyxy_normalized or instance_masks_yx must be provided"
792
+ assert instance_bboxes_xyxy_normalized is None or instance_masks_yx is None, "instance_bboxes_xyxy_normalized and instance_masks_yx cannot be provided together"
793
+ use_masks = instance_masks_yx is not None
794
+
795
+ self._guidance_scale = guidance_scale
796
+ self._attention_kwargs = attention_kwargs
797
+ self._current_timestep = None
798
+ self._interrupt = False
799
+
800
+ # 2. Define call parameters
801
+ if prompt is not None and isinstance(prompt, str):
802
+ batch_size = 1
803
+ elif prompt is not None and isinstance(prompt, list):
804
+ batch_size = len(prompt)
805
+ else:
806
+ batch_size = prompt_embeds.shape[0]
807
+
808
+ device = self._execution_device
809
+
810
+ # 3. prepare text embeddings
811
+ prompt_embeds, text_ids, instance_text_index_lst, seq_len = self.encode_prompt(
812
+ prompt=prompt,
813
+ prompt_embeds=prompt_embeds,
814
+ device=device,
815
+ num_images_per_prompt=num_images_per_prompt,
816
+ max_sequence_length=max_sequence_length,
817
+ text_encoder_out_layers=text_encoder_out_layers,
818
+ prompt_settings=prompt_settings,
819
+ )
820
+
821
+ if self.do_classifier_free_guidance:
822
+ negative_prompt = ""
823
+ if prompt is not None and isinstance(prompt, list):
824
+ negative_prompt = [negative_prompt] * len(prompt)
825
+ negative_prompt_embeds, negative_text_ids, negative_instance_text_index_lst, negative_seq_len = self.encode_prompt(
826
+ prompt=negative_prompt,
827
+ prompt_embeds=negative_prompt_embeds,
828
+ device=device,
829
+ num_images_per_prompt=num_images_per_prompt,
830
+ max_sequence_length=max_sequence_length,
831
+ text_encoder_out_layers=text_encoder_out_layers,
832
+ prompt_settings=prompt_settings,
833
+ )
834
+
835
+ # 4. process images
836
+ if image is not None and not isinstance(image, list):
837
+ image = [image]
838
+
839
+ condition_images = None
840
+ if image is not None:
841
+ for img in image:
842
+ self.image_processor.check_image_input(img)
843
+
844
+ condition_images = []
845
+ for img in image:
846
+ image_width, image_height = img.size
847
+ if image_width * image_height > 1024 * 1024:
848
+ img = self.image_processor._resize_to_target_area(img, 1024 * 1024)
849
+ image_width, image_height = img.size
850
+
851
+ multiple_of = self.vae_scale_factor * 2
852
+ image_width = (image_width // multiple_of) * multiple_of
853
+ image_height = (image_height // multiple_of) * multiple_of
854
+ img = self.image_processor.preprocess(img, height=image_height, width=image_width, resize_mode="default")
855
+ condition_images.append(img)
856
+ height = height or image_height
857
+ width = width or image_width
858
+
859
+ height = height or self.default_sample_size * self.vae_scale_factor
860
+ width = width or self.default_sample_size * self.vae_scale_factor
861
+
862
+ # 5. prepare latent variables
863
+ num_channels_latents = self.transformer.config.in_channels // 4
864
+ latents, latent_ids = self.prepare_latents(
865
+ batch_size=batch_size * num_images_per_prompt,
866
+ num_latents_channels=num_channels_latents,
867
+ height=height,
868
+ width=width,
869
+ dtype=prompt_embeds.dtype,
870
+ device=device,
871
+ generator=generator,
872
+ latents=latents,
873
+ )
874
+
875
+ image_latents = None
876
+ image_latent_ids = None
877
+ if condition_images is not None:
878
+ image_latents, image_latent_ids = self.prepare_image_latents(
879
+ images=condition_images,
880
+ batch_size=batch_size * num_images_per_prompt,
881
+ generator=generator,
882
+ device=device,
883
+ dtype=self.vae.dtype,
884
+ )
885
+
886
+ # 6. Prepare timesteps
887
+ sigmas = np.linspace(1.0, 1 / num_inference_steps, num_inference_steps) if sigmas is None else sigmas
888
+ if hasattr(self.scheduler.config, "use_flow_sigmas") and self.scheduler.config.use_flow_sigmas:
889
+ sigmas = None
890
+ image_seq_len = latents.shape[1]
891
+ mu = compute_empirical_mu(image_seq_len=image_seq_len, num_steps=num_inference_steps)
892
+ timesteps, num_inference_steps = retrieve_timesteps(
893
+ self.scheduler,
894
+ num_inference_steps,
895
+ device,
896
+ sigmas=sigmas,
897
+ mu=mu,
898
+ )
899
+ num_warmup_steps = max(len(timesteps) - num_inference_steps * self.scheduler.order, 0)
900
+ self._num_timesteps = len(timesteps)
901
+
902
+
903
+ #Create masks from boxes
904
+ instance_text_index_lst = instance_text_index_lst[0]
905
+ txt_seq_lens_list = [instance_text_index_lst[text_idx].shape[0] for text_idx in range(len(instance_text_index_lst))]
906
+
907
+ if use_masks:
908
+ instance_position_mask_list = [resize_mask(instance_mask_yx, height // self.vae_scale_factor // 2, width // self.vae_scale_factor // 2) for instance_mask_yx in instance_masks_yx]
909
+ context_image_position_mask_list = [resize_mask(instance_mask_yx, height // self.vae_scale_factor // 2, width // self.vae_scale_factor // 2) for instance_mask_yx in instance_masks_yx]
910
+ else:
911
+ instance_position_mask_list = create_position_mask_list(instance_bboxes_xyxy_normalized, height, width, self.vae_scale_factor)
912
+ context_image_position_mask_list = create_position_mask_list(instance_bboxes_xyxy_normalized, height, width, self.vae_scale_factor)
913
+
914
+ # 7. Denoising loop
915
+ # We set the index here to remove DtoH sync, helpful especially during compilation.
916
+ # Check out more details here: https://github.com/huggingface/diffusers/pull/11696
917
+ self.scheduler.set_begin_index(0)
918
+ with self.progress_bar(total=num_inference_steps) as progress_bar:
919
+ for i, t in enumerate(timesteps):
920
+ if self.interrupt:
921
+ continue
922
+
923
+ self._current_timestep = t
924
+ # broadcast to batch dimension in a way that's compatible with ONNX/Core ML
925
+ timestep = t.expand(latents.shape[0]).to(latents.dtype)
926
+
927
+ latent_model_input = latents.to(self.transformer.dtype)
928
+ latent_image_ids = latent_ids
929
+
930
+ if image_latents is not None:
931
+ latent_model_input = torch.cat([latents, image_latents], dim=1).to(self.transformer.dtype)
932
+ latent_image_ids = torch.cat([latent_ids, image_latent_ids], dim=1)
933
+
934
+ if attention_setting == "full":
935
+ pass
936
+ elif attention_setting.lower() in ["apita", "apitasm", "apitasmasym", "apitasmmin", "apitasmdiag", "apitasmkernel", "apitasmkernellatent", "apitasmkernelnonlap", "apitasmkernelnonlapstrict"] or attention_setting in ["APITA", "APITASM", "APITASMasym", "APITASMmin", "APITASMdiag", "APITASMkernel", "APITASMkernelLatent", "APITASMkernelNonLap", "APITASMkernelNonLapStrict", "apitasmkernelnonlap", "apitasmkernelnonlapstrict"]:
937
+ if self._attention_kwargs is None:
938
+ self._attention_kwargs = {}
939
+ self._attention_kwargs['pos_instance_text_index_lst'] = instance_text_index_lst
940
+ self._attention_kwargs['instance_position_mask_list'] = instance_position_mask_list
941
+ self._attention_kwargs['pos_seq_len'] = seq_len
942
+ self._attention_kwargs['hard_image_attribute_binding_list_double'] = hard_image_attribute_binding_list_double
943
+ self._attention_kwargs['hard_image_attribute_binding_list_single'] = hard_image_attribute_binding_list_single
944
+ self._attention_kwargs['num_inference_steps'] = num_inference_steps
945
+ self._attention_kwargs['image_w_instance_token_index_list'] = [list(range(latents.shape[1]))]
946
+ self._attention_kwargs['image_w_instance_token_H_list'] = [height]
947
+ self._attention_kwargs['image_w_instance_token_W_list'] = [width]
948
+ self._attention_kwargs['context_image_w_instance_token_index_list'] = [list(range(image_latents.shape[1]))]
949
+ self._attention_kwargs["hard_masking_steps"] = hard_masking_steps
950
+ self._attention_kwargs["relaxed_timesteps"] = relaxed_timesteps
951
+ self._attention_kwargs["free_latent"] = free_latent
952
+ self._attention_kwargs["free_context"] = free_context
953
+ self._attention_kwargs["free_LC"] = free_LC
954
+ # self._attention_kwargs['num_hard_control_steps'] = num_hard_control_steps
955
+ # self._attention_kwargs['now_steps'] = i
956
+ if self.do_classifier_free_guidance:
957
+ self._attention_kwargs['neg_instance_text_index_lst'] = negative_instance_text_index_lst
958
+ self._attention_kwargs['neg_seq_len'] = negative_seq_len
959
+ else:
960
+ raise NotImplementedError(f"Attention setting {attention_setting} not implemented")
961
+
962
+ with self.transformer.cache_context("cond"):
963
+ self._attention_kwargs['is_conditional'] = True
964
+ noise_pred = self.transformer(
965
+ hidden_states=latent_model_input, # (B, image_seq_len, C)
966
+ timestep=timestep / 1000,
967
+ guidance=None,
968
+ encoder_hidden_states=prompt_embeds,
969
+ txt_ids=text_ids, # B, text_seq_len, 4
970
+ img_ids=latent_image_ids, # B, image_seq_len, 4
971
+ joint_attention_kwargs=self.attention_kwargs,
972
+ return_dict=False,
973
+ )[0]
974
+
975
+ noise_pred = noise_pred[:, : latents.size(1) :]
976
+
977
+ if self.do_classifier_free_guidance:
978
+ with self.transformer.cache_context("uncond"):
979
+ self._attention_kwargs['is_conditional'] = False
980
+ neg_noise_pred = self.transformer(
981
+ hidden_states=latent_model_input,
982
+ timestep=timestep / 1000,
983
+ guidance=None,
984
+ encoder_hidden_states=negative_prompt_embeds,
985
+ txt_ids=negative_text_ids,
986
+ img_ids=latent_image_ids,
987
+ joint_attention_kwargs=self._attention_kwargs,
988
+ return_dict=False,
989
+ )[0]
990
+ neg_noise_pred = neg_noise_pred[:, : latents.size(1) :]
991
+ noise_pred = neg_noise_pred + guidance_scale * (noise_pred - neg_noise_pred)
992
+
993
+ # compute the previous noisy sample x_t -> x_t-1
994
+ latents_dtype = latents.dtype
995
+ latents = self.scheduler.step(noise_pred, t, latents, return_dict=False)[0]
996
+
997
+ if latents.dtype != latents_dtype:
998
+ if torch.backends.mps.is_available():
999
+ # some platforms (eg. apple mps) misbehave due to a pytorch bug: https://github.com/pytorch/pytorch/pull/99272
1000
+ latents = latents.to(latents_dtype)
1001
+
1002
+ if callback_on_step_end is not None:
1003
+ callback_kwargs = {}
1004
+ for k in callback_on_step_end_tensor_inputs:
1005
+ callback_kwargs[k] = locals()[k]
1006
+ callback_outputs = callback_on_step_end(self, i, t, callback_kwargs)
1007
+
1008
+ latents = callback_outputs.pop("latents", latents)
1009
+ prompt_embeds = callback_outputs.pop("prompt_embeds", prompt_embeds)
1010
+
1011
+ # call the callback, if provided
1012
+ if i == len(timesteps) - 1 or ((i + 1) > num_warmup_steps and (i + 1) % self.scheduler.order == 0):
1013
+ progress_bar.update()
1014
+
1015
+ if XLA_AVAILABLE:
1016
+ xm.mark_step()
1017
+
1018
+ self._current_timestep = None
1019
+
1020
+ latents = self._unpack_latents_with_ids(latents, latent_ids)
1021
+
1022
+ latents_bn_mean = self.vae.bn.running_mean.view(1, -1, 1, 1).to(latents.device, latents.dtype)
1023
+ latents_bn_std = torch.sqrt(self.vae.bn.running_var.view(1, -1, 1, 1) + self.vae.config.batch_norm_eps).to(
1024
+ latents.device, latents.dtype
1025
+ )
1026
+ latents = latents * latents_bn_std + latents_bn_mean
1027
+ latents = self._unpatchify_latents(latents)
1028
+ if output_type == "latent":
1029
+ image = latents
1030
+ else:
1031
+ image = self.vae.decode(latents, return_dict=False)[0]
1032
+ image = self.image_processor.postprocess(image, output_type=output_type)
1033
+
1034
+ # Offload all models
1035
+ self.maybe_free_model_hooks()
1036
+
1037
+ if not return_dict:
1038
+ return (image,)
1039
+
1040
+ return Flux2PipelineOutput(images=image)
flux2/pipeline_utils.py ADDED
@@ -0,0 +1,77 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import math
2
+ import torch
3
+
4
+ def resize_mask(mask, H, W):
5
+ return torch.nn.functional.interpolate(mask.unsqueeze(0).unsqueeze(0), size=(H, W), mode="nearest").squeeze(0).squeeze(0)
6
+
7
+
8
+ def find_inner_sentence_token_span_qwen(tokenizer, full_prompt: str, inner_sentence: str, max_sequence_length: int = 512):
9
+ """
10
+ Returns (start_idx, end_idx) token span for `inner_sentence` inside `full_prompt` for Qwen.
11
+ Uses `apply_chat_template` logic matching `_get_qwen3_prompt_embeds`.
12
+ Indices are over the token dimension used by the model.
13
+ end_idx is exclusive. Returns None if no contiguous match is found.
14
+ """
15
+ messages = [{"role": "user", "content": full_prompt}]
16
+
17
+ if hasattr(tokenizer, "apply_chat_template"):
18
+ try:
19
+ text = tokenizer.apply_chat_template(
20
+ messages,
21
+ tokenize=False,
22
+ add_generation_prompt=True,
23
+ enable_thinking=False,
24
+ )
25
+ except TypeError:
26
+ text = tokenizer.apply_chat_template(
27
+ messages,
28
+ tokenize=False,
29
+ add_generation_prompt=True,
30
+ )
31
+ else:
32
+ raise ValueError("Tokenizer must have apply_chat_template method")
33
+
34
+ inputs = tokenizer(
35
+ text,
36
+ return_tensors="pt",
37
+ padding="max_length",
38
+ truncation=True,
39
+ max_length=max_sequence_length,
40
+ )
41
+
42
+ full_ids = inputs["input_ids"][0]
43
+ full_mask = inputs["attention_mask"][0]
44
+ valid_len = int(full_mask.sum().item())
45
+ full_ids = full_ids[:valid_len].tolist()
46
+
47
+ tokenizer_obj = tokenizer.tokenizer if hasattr(tokenizer, "tokenizer") else tokenizer
48
+ inner_ids = tokenizer_obj.encode(inner_sentence, add_special_tokens=False)
49
+
50
+ if not inner_ids:
51
+ return None, None
52
+
53
+ n = len(inner_ids)
54
+ for i in range(0, len(full_ids) - n + 1):
55
+ if full_ids[i : i + n] == inner_ids:
56
+ return i, i + n
57
+
58
+ return None, None
59
+
60
+
61
+ def create_position_mask_list(instance_bboxes_xyxy_normalized, height, width, vae_scale_factor):
62
+ position_mask_list = []
63
+ for i in range(len(instance_bboxes_xyxy_normalized)):
64
+ instance_box_i = instance_bboxes_xyxy_normalized[i]
65
+ position_mask_list.append(change_box_to_position_mask(instance_box_i, height // vae_scale_factor // 2, width // vae_scale_factor // 2))
66
+ return position_mask_list
67
+
68
+
69
+ def change_box_to_position_mask(box, H, W):
70
+ x1, y1, x2, y2 = box
71
+ x1 = math.floor(x1 * W)
72
+ y1 = math.floor(y1 * H)
73
+ x2 = math.ceil(x2 * W)
74
+ y2 = math.ceil(y2 * H)
75
+ position_mask = torch.zeros(H, W)
76
+ position_mask[y1: y2, x1: x2] = 1
77
+ return position_mask
flux2/transformer_flux2_klein.py ADDED
@@ -0,0 +1,765 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2025 Black Forest Labs, The HuggingFace Team and The InstantX Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ import inspect
16
+ from typing import Any, Dict, List, Optional, Tuple, Union
17
+
18
+ import torch
19
+ import torch.nn as nn
20
+ import torch.nn.functional as F
21
+
22
+ from diffusers.configuration_utils import ConfigMixin, register_to_config
23
+ from diffusers.loaders import FluxTransformer2DLoadersMixin, FromOriginalModelMixin, PeftAdapterMixin
24
+ from diffusers.utils import USE_PEFT_BACKEND, logging, scale_lora_layers, unscale_lora_layers
25
+ from diffusers.models._modeling_parallel import ContextParallelInput, ContextParallelOutput
26
+ from diffusers.models.attention import AttentionMixin, AttentionModuleMixin
27
+ from diffusers.models.attention_dispatch import dispatch_attention_fn
28
+ from diffusers.models.cache_utils import CacheMixin
29
+ from diffusers.models.embeddings import (
30
+ TimestepEmbedding,
31
+ Timesteps,
32
+ apply_rotary_emb,
33
+ get_1d_rotary_pos_embed,
34
+ )
35
+ from diffusers.models.modeling_outputs import Transformer2DModelOutput
36
+ from diffusers.models.modeling_utils import ModelMixin
37
+ from diffusers.models.normalization import AdaLayerNormContinuous
38
+ from .attention.attention_processor_base import Flux2AttnProcessor, Flux2ParallelSelfAttnProcessor
39
+
40
+
41
+ logger = logging.get_logger(__name__) # pylint: disable=invalid-name
42
+
43
+
44
+ class Flux2SwiGLU(nn.Module):
45
+ """
46
+ Flux 2 uses a SwiGLU-style activation in the transformer feedforward sub-blocks, but with the linear projection
47
+ layer fused into the first linear layer of the FF sub-block. Thus, this module has no trainable parameters.
48
+ """
49
+
50
+ def __init__(self):
51
+ super().__init__()
52
+ self.gate_fn = nn.SiLU()
53
+
54
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
55
+ x1, x2 = x.chunk(2, dim=-1)
56
+ x = self.gate_fn(x1) * x2
57
+ return x
58
+
59
+
60
+ class Flux2FeedForward(nn.Module):
61
+ def __init__(
62
+ self,
63
+ dim: int,
64
+ dim_out: Optional[int] = None,
65
+ mult: float = 3.0,
66
+ inner_dim: Optional[int] = None,
67
+ bias: bool = False,
68
+ ):
69
+ super().__init__()
70
+ if inner_dim is None:
71
+ inner_dim = int(dim * mult)
72
+ dim_out = dim_out or dim
73
+
74
+ # Flux2SwiGLU will reduce the dimension by half
75
+ self.linear_in = nn.Linear(dim, inner_dim * 2, bias=bias)
76
+ self.act_fn = Flux2SwiGLU()
77
+ self.linear_out = nn.Linear(inner_dim, dim_out, bias=bias)
78
+
79
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
80
+ x = self.linear_in(x)
81
+ x = self.act_fn(x)
82
+ x = self.linear_out(x)
83
+ return x
84
+
85
+
86
+ class Flux2Attention(torch.nn.Module, AttentionModuleMixin):
87
+ _default_processor_cls = Flux2AttnProcessor
88
+ _available_processors = [Flux2AttnProcessor]
89
+
90
+ def __init__(
91
+ self,
92
+ query_dim: int,
93
+ heads: int = 8,
94
+ dim_head: int = 64,
95
+ dropout: float = 0.0,
96
+ bias: bool = False,
97
+ added_kv_proj_dim: Optional[int] = None,
98
+ added_proj_bias: Optional[bool] = True,
99
+ out_bias: bool = True,
100
+ eps: float = 1e-5,
101
+ out_dim: int = None,
102
+ elementwise_affine: bool = True,
103
+ processor=None,
104
+ ):
105
+ super().__init__()
106
+
107
+ self.head_dim = dim_head
108
+ self.inner_dim = out_dim if out_dim is not None else dim_head * heads
109
+ self.query_dim = query_dim
110
+ self.out_dim = out_dim if out_dim is not None else query_dim
111
+ self.heads = out_dim // dim_head if out_dim is not None else heads
112
+
113
+ self.use_bias = bias
114
+ self.dropout = dropout
115
+
116
+ self.added_kv_proj_dim = added_kv_proj_dim
117
+ self.added_proj_bias = added_proj_bias
118
+
119
+ self.to_q = torch.nn.Linear(query_dim, self.inner_dim, bias=bias)
120
+ self.to_k = torch.nn.Linear(query_dim, self.inner_dim, bias=bias)
121
+ self.to_v = torch.nn.Linear(query_dim, self.inner_dim, bias=bias)
122
+
123
+ # QK Norm
124
+ self.norm_q = torch.nn.RMSNorm(dim_head, eps=eps, elementwise_affine=elementwise_affine)
125
+ self.norm_k = torch.nn.RMSNorm(dim_head, eps=eps, elementwise_affine=elementwise_affine)
126
+
127
+ self.to_out = torch.nn.ModuleList([])
128
+ self.to_out.append(torch.nn.Linear(self.inner_dim, self.out_dim, bias=out_bias))
129
+ self.to_out.append(torch.nn.Dropout(dropout))
130
+
131
+ if added_kv_proj_dim is not None:
132
+ self.norm_added_q = torch.nn.RMSNorm(dim_head, eps=eps)
133
+ self.norm_added_k = torch.nn.RMSNorm(dim_head, eps=eps)
134
+ self.add_q_proj = torch.nn.Linear(added_kv_proj_dim, self.inner_dim, bias=added_proj_bias)
135
+ self.add_k_proj = torch.nn.Linear(added_kv_proj_dim, self.inner_dim, bias=added_proj_bias)
136
+ self.add_v_proj = torch.nn.Linear(added_kv_proj_dim, self.inner_dim, bias=added_proj_bias)
137
+ self.to_add_out = torch.nn.Linear(self.inner_dim, query_dim, bias=out_bias)
138
+
139
+ if processor is None:
140
+ processor = self._default_processor_cls()
141
+ self.set_processor(processor)
142
+
143
+ def forward(
144
+ self,
145
+ hidden_states: torch.Tensor,
146
+ encoder_hidden_states: Optional[torch.Tensor] = None,
147
+ attention_mask: Optional[torch.Tensor] = None,
148
+ image_rotary_emb: Optional[torch.Tensor] = None,
149
+ **kwargs,
150
+ ) -> torch.Tensor:
151
+ attn_parameters = set(inspect.signature(self.processor.__call__).parameters.keys())
152
+ unused_kwargs = [k for k, _ in kwargs.items() if k not in attn_parameters]
153
+ if len(unused_kwargs) > 0:
154
+ logger.warning(
155
+ f"joint_attention_kwargs {unused_kwargs} are not expected by {self.processor.__class__.__name__} and will be ignored."
156
+ )
157
+ kwargs = {k: w for k, w in kwargs.items() if k in attn_parameters}
158
+ return self.processor(self, hidden_states, encoder_hidden_states, attention_mask, image_rotary_emb, **kwargs)
159
+
160
+
161
+
162
+ class Flux2ParallelSelfAttention(torch.nn.Module, AttentionModuleMixin):
163
+ """
164
+ Flux 2 parallel self-attention for the Flux 2 single-stream transformer blocks.
165
+
166
+ This implements a parallel transformer block, where the attention QKV projections are fused to the feedforward (FF)
167
+ input projections, and the attention output projections are fused to the FF output projections. See the [ViT-22B
168
+ paper](https://arxiv.org/abs/2302.05442) for a visual depiction of this type of transformer block.
169
+ """
170
+
171
+ _default_processor_cls = Flux2ParallelSelfAttnProcessor
172
+ _available_processors = [Flux2ParallelSelfAttnProcessor]
173
+ # Does not support QKV fusion as the QKV projections are always fused
174
+ _supports_qkv_fusion = False
175
+
176
+ def __init__(
177
+ self,
178
+ query_dim: int,
179
+ heads: int = 8,
180
+ dim_head: int = 64,
181
+ dropout: float = 0.0,
182
+ bias: bool = False,
183
+ out_bias: bool = True,
184
+ eps: float = 1e-5,
185
+ out_dim: int = None,
186
+ elementwise_affine: bool = True,
187
+ mlp_ratio: float = 4.0,
188
+ mlp_mult_factor: int = 2,
189
+ processor=None,
190
+ ):
191
+ super().__init__()
192
+
193
+ self.head_dim = dim_head
194
+ self.inner_dim = out_dim if out_dim is not None else dim_head * heads
195
+ self.query_dim = query_dim
196
+ self.out_dim = out_dim if out_dim is not None else query_dim
197
+ self.heads = out_dim // dim_head if out_dim is not None else heads
198
+
199
+ self.use_bias = bias
200
+ self.dropout = dropout
201
+
202
+ self.mlp_ratio = mlp_ratio
203
+ self.mlp_hidden_dim = int(query_dim * self.mlp_ratio)
204
+ self.mlp_mult_factor = mlp_mult_factor
205
+
206
+ # Fused QKV projections + MLP input projection
207
+ self.to_qkv_mlp_proj = torch.nn.Linear(
208
+ self.query_dim, self.inner_dim * 3 + self.mlp_hidden_dim * self.mlp_mult_factor, bias=bias
209
+ )
210
+ self.mlp_act_fn = Flux2SwiGLU()
211
+
212
+ # QK Norm
213
+ self.norm_q = torch.nn.RMSNorm(dim_head, eps=eps, elementwise_affine=elementwise_affine)
214
+ self.norm_k = torch.nn.RMSNorm(dim_head, eps=eps, elementwise_affine=elementwise_affine)
215
+
216
+ # Fused attention output projection + MLP output projection
217
+ self.to_out = torch.nn.Linear(self.inner_dim + self.mlp_hidden_dim, self.out_dim, bias=out_bias)
218
+
219
+ if processor is None:
220
+ processor = self._default_processor_cls()
221
+ self.set_processor(processor)
222
+
223
+ def forward(
224
+ self,
225
+ hidden_states: torch.Tensor,
226
+ attention_mask: Optional[torch.Tensor] = None,
227
+ image_rotary_emb: Optional[torch.Tensor] = None,
228
+ **kwargs,
229
+ ) -> torch.Tensor:
230
+ attn_parameters = set(inspect.signature(self.processor.__call__).parameters.keys())
231
+ unused_kwargs = [k for k, _ in kwargs.items() if k not in attn_parameters]
232
+ if len(unused_kwargs) > 0:
233
+ logger.warning(
234
+ f"joint_attention_kwargs {unused_kwargs} are not expected by {self.processor.__class__.__name__} and will be ignored."
235
+ )
236
+ kwargs = {k: w for k, w in kwargs.items() if k in attn_parameters}
237
+ return self.processor(self, hidden_states, attention_mask, image_rotary_emb, **kwargs)
238
+
239
+
240
+ class Flux2SingleTransformerBlock(nn.Module):
241
+ def __init__(
242
+ self,
243
+ dim: int,
244
+ num_attention_heads: int,
245
+ attention_head_dim: int,
246
+ mlp_ratio: float = 3.0,
247
+ eps: float = 1e-6,
248
+ bias: bool = False,
249
+ ):
250
+ super().__init__()
251
+
252
+ self.norm = nn.LayerNorm(dim, elementwise_affine=False, eps=eps)
253
+
254
+ # Note that the MLP in/out linear layers are fused with the attention QKV/out projections, respectively; this
255
+ # is often called a "parallel" transformer block. See the [ViT-22B paper](https://arxiv.org/abs/2302.05442)
256
+ # for a visual depiction of this type of transformer block.
257
+ self.attn = Flux2ParallelSelfAttention(
258
+ query_dim=dim,
259
+ dim_head=attention_head_dim,
260
+ heads=num_attention_heads,
261
+ out_dim=dim,
262
+ bias=bias,
263
+ out_bias=bias,
264
+ eps=eps,
265
+ mlp_ratio=mlp_ratio,
266
+ mlp_mult_factor=2,
267
+ processor=Flux2ParallelSelfAttnProcessor(),
268
+ )
269
+
270
+ def forward(
271
+ self,
272
+ hidden_states: torch.Tensor,
273
+ encoder_hidden_states: Optional[torch.Tensor],
274
+ temb_mod_params: Tuple[torch.Tensor, torch.Tensor, torch.Tensor],
275
+ image_rotary_emb: Optional[Tuple[torch.Tensor, torch.Tensor]] = None,
276
+ joint_attention_kwargs: Optional[Dict[str, Any]] = None,
277
+ split_hidden_states: bool = False,
278
+ text_seq_len: Optional[int] = None,
279
+ ) -> Tuple[torch.Tensor, torch.Tensor]:
280
+ # If encoder_hidden_states is None, hidden_states is assumed to have encoder_hidden_states already
281
+ # concatenated
282
+ if encoder_hidden_states is not None:
283
+ text_seq_len = encoder_hidden_states.shape[1]
284
+ hidden_states = torch.cat([encoder_hidden_states, hidden_states], dim=1)
285
+
286
+ mod_shift, mod_scale, mod_gate = temb_mod_params
287
+
288
+ norm_hidden_states = self.norm(hidden_states)
289
+ norm_hidden_states = (1 + mod_scale) * norm_hidden_states + mod_shift
290
+
291
+ joint_attention_kwargs = joint_attention_kwargs or {}
292
+ attn_output = self.attn(
293
+ hidden_states=norm_hidden_states,
294
+ image_rotary_emb=image_rotary_emb,
295
+ **joint_attention_kwargs,
296
+ )
297
+
298
+ hidden_states = hidden_states + mod_gate * attn_output
299
+ if hidden_states.dtype == torch.float16:
300
+ hidden_states = hidden_states.clip(-65504, 65504)
301
+
302
+ if split_hidden_states:
303
+ encoder_hidden_states, hidden_states = hidden_states[:, :text_seq_len], hidden_states[:, text_seq_len:]
304
+ return encoder_hidden_states, hidden_states
305
+ else:
306
+ return hidden_states
307
+
308
+
309
+ class Flux2TransformerBlock(nn.Module):
310
+ def __init__(
311
+ self,
312
+ dim: int,
313
+ num_attention_heads: int,
314
+ attention_head_dim: int,
315
+ mlp_ratio: float = 3.0,
316
+ eps: float = 1e-6,
317
+ bias: bool = False,
318
+ ):
319
+ super().__init__()
320
+ self.mlp_hidden_dim = int(dim * mlp_ratio)
321
+
322
+ self.norm1 = nn.LayerNorm(dim, elementwise_affine=False, eps=eps)
323
+ self.norm1_context = nn.LayerNorm(dim, elementwise_affine=False, eps=eps)
324
+
325
+ self.attn = Flux2Attention(
326
+ query_dim=dim,
327
+ added_kv_proj_dim=dim,
328
+ dim_head=attention_head_dim,
329
+ heads=num_attention_heads,
330
+ out_dim=dim,
331
+ bias=bias,
332
+ added_proj_bias=bias,
333
+ out_bias=bias,
334
+ eps=eps,
335
+ processor=Flux2AttnProcessor(),
336
+ )
337
+
338
+ self.norm2 = nn.LayerNorm(dim, elementwise_affine=False, eps=eps)
339
+ self.ff = Flux2FeedForward(dim=dim, dim_out=dim, mult=mlp_ratio, bias=bias)
340
+
341
+ self.norm2_context = nn.LayerNorm(dim, elementwise_affine=False, eps=eps)
342
+ self.ff_context = Flux2FeedForward(dim=dim, dim_out=dim, mult=mlp_ratio, bias=bias)
343
+
344
+ def forward(
345
+ self,
346
+ hidden_states: torch.Tensor,
347
+ encoder_hidden_states: torch.Tensor,
348
+ temb_mod_params_img: Tuple[Tuple[torch.Tensor, torch.Tensor, torch.Tensor], ...],
349
+ temb_mod_params_txt: Tuple[Tuple[torch.Tensor, torch.Tensor, torch.Tensor], ...],
350
+ image_rotary_emb: Optional[Tuple[torch.Tensor, torch.Tensor]] = None,
351
+ joint_attention_kwargs: Optional[Dict[str, Any]] = None,
352
+ ) -> Tuple[torch.Tensor, torch.Tensor]:
353
+ joint_attention_kwargs = joint_attention_kwargs or {}
354
+
355
+ # Modulation parameters shape: [1, 1, self.dim]
356
+ (shift_msa, scale_msa, gate_msa), (shift_mlp, scale_mlp, gate_mlp) = temb_mod_params_img
357
+ (c_shift_msa, c_scale_msa, c_gate_msa), (c_shift_mlp, c_scale_mlp, c_gate_mlp) = temb_mod_params_txt
358
+
359
+ # Img stream
360
+ norm_hidden_states = self.norm1(hidden_states)
361
+ norm_hidden_states = (1 + scale_msa) * norm_hidden_states + shift_msa
362
+
363
+ # Conditioning txt stream
364
+ norm_encoder_hidden_states = self.norm1_context(encoder_hidden_states)
365
+ norm_encoder_hidden_states = (1 + c_scale_msa) * norm_encoder_hidden_states + c_shift_msa
366
+
367
+ # Attention on concatenated img + txt stream
368
+ attention_outputs = self.attn(
369
+ hidden_states=norm_hidden_states,
370
+ encoder_hidden_states=norm_encoder_hidden_states,
371
+ image_rotary_emb=image_rotary_emb,
372
+ **joint_attention_kwargs,
373
+ )
374
+
375
+ attn_output, context_attn_output = attention_outputs
376
+
377
+ # Process attention outputs for the image stream (`hidden_states`).
378
+ attn_output = gate_msa * attn_output
379
+ hidden_states = hidden_states + attn_output
380
+
381
+ norm_hidden_states = self.norm2(hidden_states)
382
+ norm_hidden_states = norm_hidden_states * (1 + scale_mlp) + shift_mlp
383
+
384
+ ff_output = self.ff(norm_hidden_states)
385
+ hidden_states = hidden_states + gate_mlp * ff_output
386
+
387
+ # Process attention outputs for the text stream (`encoder_hidden_states`).
388
+ context_attn_output = c_gate_msa * context_attn_output
389
+ encoder_hidden_states = encoder_hidden_states + context_attn_output
390
+
391
+ norm_encoder_hidden_states = self.norm2_context(encoder_hidden_states)
392
+ norm_encoder_hidden_states = norm_encoder_hidden_states * (1 + c_scale_mlp) + c_shift_mlp
393
+
394
+ context_ff_output = self.ff_context(norm_encoder_hidden_states)
395
+ encoder_hidden_states = encoder_hidden_states + c_gate_mlp * context_ff_output
396
+ if encoder_hidden_states.dtype == torch.float16:
397
+ encoder_hidden_states = encoder_hidden_states.clip(-65504, 65504)
398
+
399
+ return encoder_hidden_states, hidden_states
400
+
401
+
402
+ class Flux2PosEmbed(nn.Module):
403
+ # modified from https://github.com/black-forest-labs/flux/blob/c00d7c60b085fce8058b9df845e036090873f2ce/src/flux/modules/layers.py#L11
404
+ def __init__(self, theta: int, axes_dim: List[int]):
405
+ super().__init__()
406
+ self.theta = theta
407
+ self.axes_dim = axes_dim
408
+
409
+ def forward(self, ids: torch.Tensor) -> torch.Tensor:
410
+ # Expected ids shape: [S, len(self.axes_dim)]
411
+ cos_out = []
412
+ sin_out = []
413
+ pos = ids.float()
414
+ is_mps = ids.device.type == "mps"
415
+ is_npu = ids.device.type == "npu"
416
+ freqs_dtype = torch.float32 if (is_mps or is_npu) else torch.float64
417
+ # Unlike Flux 1, loop over len(self.axes_dim) rather than ids.shape[-1]
418
+ for i in range(len(self.axes_dim)):
419
+ cos, sin = get_1d_rotary_pos_embed(
420
+ self.axes_dim[i],
421
+ pos[..., i],
422
+ theta=self.theta,
423
+ repeat_interleave_real=True,
424
+ use_real=True,
425
+ freqs_dtype=freqs_dtype,
426
+ )
427
+ cos_out.append(cos)
428
+ sin_out.append(sin)
429
+ freqs_cos = torch.cat(cos_out, dim=-1).to(ids.device)
430
+ freqs_sin = torch.cat(sin_out, dim=-1).to(ids.device)
431
+ return freqs_cos, freqs_sin
432
+
433
+
434
+ class Flux2TimestepGuidanceEmbeddings(nn.Module):
435
+ def __init__(
436
+ self,
437
+ in_channels: int = 256,
438
+ embedding_dim: int = 6144,
439
+ bias: bool = False,
440
+ guidance_embeds: bool = True,
441
+ ):
442
+ super().__init__()
443
+
444
+ self.time_proj = Timesteps(num_channels=in_channels, flip_sin_to_cos=True, downscale_freq_shift=0)
445
+ self.timestep_embedder = TimestepEmbedding(
446
+ in_channels=in_channels, time_embed_dim=embedding_dim, sample_proj_bias=bias
447
+ )
448
+
449
+ if guidance_embeds:
450
+ self.guidance_embedder = TimestepEmbedding(
451
+ in_channels=in_channels, time_embed_dim=embedding_dim, sample_proj_bias=bias
452
+ )
453
+ else:
454
+ self.guidance_embedder = None
455
+
456
+ def forward(self, timestep: torch.Tensor, guidance: torch.Tensor) -> torch.Tensor:
457
+ timesteps_proj = self.time_proj(timestep)
458
+ timesteps_emb = self.timestep_embedder(timesteps_proj.to(timestep.dtype)) # (N, D)
459
+
460
+ if guidance is not None and self.guidance_embedder is not None:
461
+ guidance_proj = self.time_proj(guidance)
462
+ guidance_emb = self.guidance_embedder(guidance_proj.to(guidance.dtype)) # (N, D)
463
+ time_guidance_emb = timesteps_emb + guidance_emb
464
+ return time_guidance_emb
465
+ else:
466
+ return timesteps_emb
467
+
468
+
469
+ class Flux2Modulation(nn.Module):
470
+ def __init__(self, dim: int, mod_param_sets: int = 2, bias: bool = False):
471
+ super().__init__()
472
+ self.mod_param_sets = mod_param_sets
473
+
474
+ self.linear = nn.Linear(dim, dim * 3 * self.mod_param_sets, bias=bias)
475
+ self.act_fn = nn.SiLU()
476
+
477
+ def forward(self, temb: torch.Tensor) -> Tuple[Tuple[torch.Tensor, torch.Tensor, torch.Tensor], ...]:
478
+ mod = self.act_fn(temb)
479
+ mod = self.linear(mod)
480
+
481
+ if mod.ndim == 2:
482
+ mod = mod.unsqueeze(1)
483
+ mod_params = torch.chunk(mod, 3 * self.mod_param_sets, dim=-1)
484
+ # Return tuple of 3-tuples of modulation params shift/scale/gate
485
+ return tuple(mod_params[3 * i : 3 * (i + 1)] for i in range(self.mod_param_sets))
486
+
487
+
488
+ class Flux2Transformer2DModel(
489
+ ModelMixin,
490
+ ConfigMixin,
491
+ PeftAdapterMixin,
492
+ FromOriginalModelMixin,
493
+ FluxTransformer2DLoadersMixin,
494
+ CacheMixin,
495
+ AttentionMixin,
496
+ ):
497
+ """
498
+ The Transformer model introduced in Flux 2.
499
+
500
+ Reference: https://blackforestlabs.ai/announcing-black-forest-labs/
501
+
502
+ Args:
503
+ patch_size (`int`, defaults to `1`):
504
+ Patch size to turn the input data into small patches.
505
+ in_channels (`int`, defaults to `128`):
506
+ The number of channels in the input.
507
+ out_channels (`int`, *optional*, defaults to `None`):
508
+ The number of channels in the output. If not specified, it defaults to `in_channels`.
509
+ num_layers (`int`, defaults to `8`):
510
+ The number of layers of dual stream DiT blocks to use.
511
+ num_single_layers (`int`, defaults to `48`):
512
+ The number of layers of single stream DiT blocks to use.
513
+ attention_head_dim (`int`, defaults to `128`):
514
+ The number of dimensions to use for each attention head.
515
+ num_attention_heads (`int`, defaults to `48`):
516
+ The number of attention heads to use.
517
+ joint_attention_dim (`int`, defaults to `15360`):
518
+ The number of dimensions to use for the joint attention (embedding/channel dimension of
519
+ `encoder_hidden_states`).
520
+ pooled_projection_dim (`int`, defaults to `768`):
521
+ The number of dimensions to use for the pooled projection.
522
+ guidance_embeds (`bool`, defaults to `True`):
523
+ Whether to use guidance embeddings for guidance-distilled variant of the model.
524
+ axes_dims_rope (`Tuple[int]`, defaults to `(32, 32, 32, 32)`):
525
+ The dimensions to use for the rotary positional embeddings.
526
+ """
527
+
528
+ _supports_gradient_checkpointing = True
529
+ _no_split_modules = ["Flux2TransformerBlock", "Flux2SingleTransformerBlock"]
530
+ _skip_layerwise_casting_patterns = ["pos_embed", "norm"]
531
+ _repeated_blocks = ["Flux2TransformerBlock", "Flux2SingleTransformerBlock"]
532
+ _cp_plan = {
533
+ "": {
534
+ "hidden_states": ContextParallelInput(split_dim=1, expected_dims=3, split_output=False),
535
+ "encoder_hidden_states": ContextParallelInput(split_dim=1, expected_dims=3, split_output=False),
536
+ "img_ids": ContextParallelInput(split_dim=1, expected_dims=3, split_output=False),
537
+ "txt_ids": ContextParallelInput(split_dim=1, expected_dims=3, split_output=False),
538
+ },
539
+ "proj_out": ContextParallelOutput(gather_dim=1, expected_dims=3),
540
+ }
541
+
542
+ @register_to_config
543
+ def __init__(
544
+ self,
545
+ patch_size: int = 1,
546
+ in_channels: int = 128,
547
+ out_channels: Optional[int] = None,
548
+ num_layers: int = 8,
549
+ num_single_layers: int = 48,
550
+ attention_head_dim: int = 128,
551
+ num_attention_heads: int = 48,
552
+ joint_attention_dim: int = 15360,
553
+ timestep_guidance_channels: int = 256,
554
+ mlp_ratio: float = 3.0,
555
+ axes_dims_rope: Tuple[int, ...] = (32, 32, 32, 32),
556
+ rope_theta: int = 2000,
557
+ eps: float = 1e-6,
558
+ guidance_embeds: bool = True,
559
+ ):
560
+ super().__init__()
561
+ self.out_channels = out_channels or in_channels
562
+ self.inner_dim = num_attention_heads * attention_head_dim
563
+
564
+ # 1. Sinusoidal positional embedding for RoPE on image and text tokens
565
+ self.pos_embed = Flux2PosEmbed(theta=rope_theta, axes_dim=axes_dims_rope)
566
+
567
+ # 2. Combined timestep + guidance embedding
568
+ self.time_guidance_embed = Flux2TimestepGuidanceEmbeddings(
569
+ in_channels=timestep_guidance_channels,
570
+ embedding_dim=self.inner_dim,
571
+ bias=False,
572
+ guidance_embeds=guidance_embeds,
573
+ )
574
+
575
+ # 3. Modulation (double stream and single stream blocks share modulation parameters, resp.)
576
+ # Two sets of shift/scale/gate modulation parameters for the double stream attn and FF sub-blocks
577
+ self.double_stream_modulation_img = Flux2Modulation(self.inner_dim, mod_param_sets=2, bias=False)
578
+ self.double_stream_modulation_txt = Flux2Modulation(self.inner_dim, mod_param_sets=2, bias=False)
579
+ # Only one set of modulation parameters as the attn and FF sub-blocks are run in parallel for single stream
580
+ self.single_stream_modulation = Flux2Modulation(self.inner_dim, mod_param_sets=1, bias=False)
581
+
582
+ # 4. Input projections
583
+ self.x_embedder = nn.Linear(in_channels, self.inner_dim, bias=False)
584
+ self.context_embedder = nn.Linear(joint_attention_dim, self.inner_dim, bias=False)
585
+
586
+ # 5. Double Stream Transformer Blocks
587
+ self.transformer_blocks = nn.ModuleList(
588
+ [
589
+ Flux2TransformerBlock(
590
+ dim=self.inner_dim,
591
+ num_attention_heads=num_attention_heads,
592
+ attention_head_dim=attention_head_dim,
593
+ mlp_ratio=mlp_ratio,
594
+ eps=eps,
595
+ bias=False,
596
+ )
597
+ for _ in range(num_layers)
598
+ ]
599
+ )
600
+
601
+ # 6. Single Stream Transformer Blocks
602
+ self.single_transformer_blocks = nn.ModuleList(
603
+ [
604
+ Flux2SingleTransformerBlock(
605
+ dim=self.inner_dim,
606
+ num_attention_heads=num_attention_heads,
607
+ attention_head_dim=attention_head_dim,
608
+ mlp_ratio=mlp_ratio,
609
+ eps=eps,
610
+ bias=False,
611
+ )
612
+ for _ in range(num_single_layers)
613
+ ]
614
+ )
615
+
616
+ # 7. Output layers
617
+ self.norm_out = AdaLayerNormContinuous(
618
+ self.inner_dim, self.inner_dim, elementwise_affine=False, eps=eps, bias=False
619
+ )
620
+ self.proj_out = nn.Linear(self.inner_dim, patch_size * patch_size * self.out_channels, bias=False)
621
+
622
+ self.gradient_checkpointing = False
623
+
624
+ def forward(
625
+ self,
626
+ hidden_states: torch.Tensor,
627
+ encoder_hidden_states: torch.Tensor = None,
628
+ timestep: torch.LongTensor = None,
629
+ img_ids: torch.Tensor = None,
630
+ txt_ids: torch.Tensor = None,
631
+ guidance: torch.Tensor = None,
632
+ joint_attention_kwargs: Optional[Dict[str, Any]] = None,
633
+ return_dict: bool = True,
634
+ ) -> Union[torch.Tensor, Transformer2DModelOutput]:
635
+ """
636
+ The [`FluxTransformer2DModel`] forward method.
637
+
638
+ Args:
639
+ hidden_states (`torch.Tensor` of shape `(batch_size, image_sequence_length, in_channels)`):
640
+ Input `hidden_states`.
641
+ encoder_hidden_states (`torch.Tensor` of shape `(batch_size, text_sequence_length, joint_attention_dim)`):
642
+ Conditional embeddings (embeddings computed from the input conditions such as prompts) to use.
643
+ timestep ( `torch.LongTensor`):
644
+ Used to indicate denoising step.
645
+ block_controlnet_hidden_states: (`list` of `torch.Tensor`):
646
+ A list of tensors that if specified are added to the residuals of transformer blocks.
647
+ joint_attention_kwargs (`dict`, *optional*):
648
+ A kwargs dictionary that if specified is passed along to the `AttentionProcessor` as defined under
649
+ `self.processor` in
650
+ [diffusers.models.attention_processor](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py).
651
+ return_dict (`bool`, *optional*, defaults to `True`):
652
+ Whether or not to return a [`~models.transformer_2d.Transformer2DModelOutput`] instead of a plain
653
+ tuple.
654
+
655
+ Returns:
656
+ If `return_dict` is True, an [`~models.transformer_2d.Transformer2DModelOutput`] is returned, otherwise a
657
+ `tuple` where the first element is the sample tensor.
658
+ """
659
+ # 0. Handle input arguments
660
+ if joint_attention_kwargs is not None:
661
+ joint_attention_kwargs = joint_attention_kwargs.copy()
662
+ lora_scale = joint_attention_kwargs.pop("scale", 1.0)
663
+ else:
664
+ lora_scale = 1.0
665
+
666
+ if USE_PEFT_BACKEND:
667
+ # weight the lora layers by setting `lora_scale` for each PEFT layer
668
+ scale_lora_layers(self, lora_scale)
669
+ else:
670
+ if joint_attention_kwargs is not None and joint_attention_kwargs.get("scale", None) is not None:
671
+ logger.warning(
672
+ "Passing `scale` via `joint_attention_kwargs` when not using the PEFT backend is ineffective."
673
+ )
674
+
675
+ num_txt_tokens = encoder_hidden_states.shape[1]
676
+
677
+ # 1. Calculate timestep embedding and modulation parameters
678
+ timestep = timestep.to(hidden_states.dtype) * 1000
679
+
680
+ if guidance is not None:
681
+ guidance = guidance.to(hidden_states.dtype) * 1000
682
+
683
+ temb = self.time_guidance_embed(timestep, guidance)
684
+
685
+ double_stream_mod_img = self.double_stream_modulation_img(temb)
686
+ double_stream_mod_txt = self.double_stream_modulation_txt(temb)
687
+ single_stream_mod = self.single_stream_modulation(temb)[0]
688
+
689
+ # 2. Input projection for image (hidden_states) and conditioning text (encoder_hidden_states)
690
+ hidden_states = self.x_embedder(hidden_states)
691
+ encoder_hidden_states = self.context_embedder(encoder_hidden_states)
692
+
693
+ # 3. Calculate RoPE embeddings from image and text tokens
694
+ # NOTE: the below logic means that we can't support batched inference with images of different resolutions or
695
+ # text prompts of differents lengths. Is this a use case we want to support?
696
+ if img_ids.ndim == 3:
697
+ img_ids = img_ids[0]
698
+ if txt_ids.ndim == 3:
699
+ txt_ids = txt_ids[0]
700
+
701
+ image_rotary_emb = self.pos_embed(img_ids)
702
+ text_rotary_emb = self.pos_embed(txt_ids)
703
+ concat_rotary_emb = (
704
+ torch.cat([text_rotary_emb[0], image_rotary_emb[0]], dim=0),
705
+ torch.cat([text_rotary_emb[1], image_rotary_emb[1]], dim=0),
706
+ )
707
+
708
+ # 4. Double Stream Transformer Blocks
709
+ for index_block, block in enumerate(self.transformer_blocks):
710
+ if torch.is_grad_enabled() and self.gradient_checkpointing:
711
+ encoder_hidden_states, hidden_states = self._gradient_checkpointing_func(
712
+ block,
713
+ hidden_states,
714
+ encoder_hidden_states,
715
+ double_stream_mod_img,
716
+ double_stream_mod_txt,
717
+ concat_rotary_emb,
718
+ joint_attention_kwargs,
719
+ )
720
+ else:
721
+ encoder_hidden_states, hidden_states = block(
722
+ hidden_states=hidden_states,
723
+ encoder_hidden_states=encoder_hidden_states,
724
+ temb_mod_params_img=double_stream_mod_img,
725
+ temb_mod_params_txt=double_stream_mod_txt,
726
+ image_rotary_emb=concat_rotary_emb,
727
+ joint_attention_kwargs=joint_attention_kwargs,
728
+ )
729
+ # Concatenate text and image streams for single-block inference
730
+ hidden_states = torch.cat([encoder_hidden_states, hidden_states], dim=1)
731
+
732
+ # 5. Single Stream Transformer Blocks
733
+ for index_block, block in enumerate(self.single_transformer_blocks):
734
+ if torch.is_grad_enabled() and self.gradient_checkpointing:
735
+ hidden_states = self._gradient_checkpointing_func(
736
+ block,
737
+ hidden_states,
738
+ None,
739
+ single_stream_mod,
740
+ concat_rotary_emb,
741
+ joint_attention_kwargs,
742
+ )
743
+ else:
744
+ hidden_states = block(
745
+ hidden_states=hidden_states,
746
+ encoder_hidden_states=None,
747
+ temb_mod_params=single_stream_mod,
748
+ image_rotary_emb=concat_rotary_emb,
749
+ joint_attention_kwargs=joint_attention_kwargs,
750
+ )
751
+ # Remove text tokens from concatenated stream
752
+ hidden_states = hidden_states[:, num_txt_tokens:, ...]
753
+
754
+ # 6. Output layers
755
+ hidden_states = self.norm_out(hidden_states, temb)
756
+ output = self.proj_out(hidden_states)
757
+
758
+ if USE_PEFT_BACKEND:
759
+ # remove `lora_scale` from each PEFT layer
760
+ unscale_lora_layers(self, lora_scale)
761
+
762
+ if not return_dict:
763
+ return (output,)
764
+
765
+ return Transformer2DModelOutput(sample=output)
infer.py ADDED
@@ -0,0 +1,197 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Single-image inference with MICE.
3
+
4
+ Each edit targets one instance in the image, described by a text instruction
5
+ and a mask (or bounding box). Multiple edits can be applied simultaneously.
6
+
7
+ Example usage:
8
+
9
+ # With masks (recommended)
10
+ python infer.py \
11
+ --image input.jpg \
12
+ --edits "Replace the cat with a dog" "Replace the lamp with a vase" \
13
+ --masks mask_cat.png mask_lamp.png \
14
+ --output result.png
15
+
16
+ # With bounding boxes (normalized x1 y1 x2 y2)
17
+ python infer.py \
18
+ --image input.jpg \
19
+ --edits "Replace the cat with a dog" \
20
+ --bboxes "0.1 0.2 0.5 0.8" \
21
+ --output result.png
22
+ """
23
+ import sys
24
+ import argparse
25
+ import torch
26
+ import numpy as np
27
+ from PIL import Image
28
+ from pathlib import Path
29
+ from loguru import logger
30
+
31
+ REPO_ROOT = Path(__file__).resolve().parent
32
+ if str(REPO_ROOT) not in sys.path:
33
+ sys.path.insert(0, str(REPO_ROOT))
34
+
35
+ from flux2.pipeline_flux2_klein import Flux2KleinPipeline
36
+ from flux2.transformer_flux2_klein import Flux2Transformer2DModel, Flux2Attention, Flux2ParallelSelfAttention
37
+ from flux2.attention import get_attention_processors, AttentionSetting
38
+
39
+ SEED = 42
40
+
41
+
42
+ def load_mask(mask_path: str) -> torch.Tensor:
43
+ mask_np = np.array(Image.open(mask_path).convert('L'))
44
+ return torch.from_numpy(mask_np > 127).float()
45
+
46
+
47
+ def parse_args():
48
+ parser = argparse.ArgumentParser(
49
+ description="MICE: spatially-controlled multi-instance image editing.",
50
+ formatter_class=argparse.RawDescriptionHelpFormatter,
51
+ epilog=__doc__,
52
+ )
53
+ parser.add_argument("--image", type=str, required=True,
54
+ help="Path to the input image")
55
+ parser.add_argument("--edits", type=str, nargs="+", required=True,
56
+ help="Edit instruction for each instance, e.g. 'Replace the cat with a dog'")
57
+ parser.add_argument("--masks", type=str, nargs="+", default=None,
58
+ help="Path to a binary mask image for each edit (white = instance region)")
59
+ parser.add_argument("--bboxes", type=str, nargs="+", default=None,
60
+ help="Normalized bounding box for each edit as 'x1 y1 x2 y2' (values in [0,1])")
61
+ parser.add_argument("--output", type=str, default="result.png",
62
+ help="Path to save the output image (default: result.png)")
63
+ parser.add_argument("--model", type=str, default="black-forest-labs/FLUX.2-klein-4B",
64
+ help="HuggingFace model ID or local path")
65
+ parser.add_argument("--num_inference_steps", type=int, default=4)
66
+ parser.add_argument("--kernel_size", type=int, default=11,
67
+ help="Spatial kernel size for attention falloff")
68
+ parser.add_argument("--temperature", type=float, default=3.0,
69
+ help="Steepness of spatial falloff")
70
+ parser.add_argument("--double_layers", type=str, default="0,5",
71
+ help="Range of double-stream blocks to apply binding, e.g. '0,5'")
72
+ parser.add_argument("--single_layers", type=str, default="0,20",
73
+ help="Range of single-stream blocks to apply binding, e.g. '0,20'")
74
+ parser.add_argument("--strict", action="store_true",
75
+ help="Use stricter cross-instance isolation")
76
+ return parser.parse_args()
77
+
78
+
79
+ def main():
80
+ args = parse_args()
81
+
82
+ if args.masks is None and args.bboxes is None:
83
+ logger.error("Provide either --masks or --bboxes.")
84
+ sys.exit(1)
85
+ if args.masks is not None and args.bboxes is not None:
86
+ logger.error("Provide either --masks or --bboxes, not both.")
87
+ sys.exit(1)
88
+
89
+ n = len(args.edits)
90
+ if args.masks is not None and len(args.masks) != n:
91
+ logger.error(f"Number of --masks ({len(args.masks)}) must match number of --edits ({n}).")
92
+ sys.exit(1)
93
+ if args.bboxes is not None and len(args.bboxes) != n:
94
+ logger.error(f"Number of --bboxes ({len(args.bboxes)}) must match number of --edits ({n}).")
95
+ sys.exit(1)
96
+
97
+ def parse_layer_range(s):
98
+ parts = [int(x) for x in s.split(',')]
99
+ return list(range(parts[0], parts[1])) if len(parts) >= 2 else []
100
+
101
+ double_layers = parse_layer_range(args.double_layers)
102
+ single_layers = parse_layer_range(args.single_layers)
103
+
104
+ device = "cuda" if torch.cuda.is_available() else "cpu"
105
+ torch.manual_seed(SEED)
106
+ np.random.seed(SEED)
107
+
108
+ # Load image
109
+ image = Image.open(args.image).convert('RGB')
110
+ original_size = image.size # (w, h)
111
+
112
+ # Resize to ~1024² area, divisible by 16
113
+ vae_scale_factor = 8
114
+ target_size = 1024
115
+ w, h = original_size
116
+ aspect = w / h
117
+ new_w = round((target_size * target_size * aspect) ** 0.5)
118
+ new_h = round((target_size * target_size / aspect) ** 0.5)
119
+ multiple_of = vae_scale_factor * 2
120
+ new_w = new_w // multiple_of * multiple_of
121
+ new_h = new_h // multiple_of * multiple_of
122
+ image = image.resize((new_w, new_h), resample=Image.LANCZOS)
123
+
124
+ # Build prompt
125
+ prompts = [" "] + args.edits
126
+ prompt = "$BREAKFLAG$".join(prompts)
127
+
128
+ # Load masks or parse bboxes
129
+ instance_masks = None
130
+ instance_bboxes = None
131
+ if args.masks is not None:
132
+ instance_masks = [load_mask(m) for m in args.masks]
133
+ else:
134
+ instance_bboxes = []
135
+ for bbox_str in args.bboxes:
136
+ x1, y1, x2, y2 = [float(v) for v in bbox_str.split()]
137
+ instance_bboxes.append([x1, y1, x2, y2])
138
+
139
+ # Load pipeline
140
+ logger.info(f"Loading model from {args.model} ...")
141
+ transformer = Flux2Transformer2DModel.from_pretrained(
142
+ args.model, subfolder="transformer", torch_dtype=torch.bfloat16, low_cpu_mem_usage=False
143
+ )
144
+ pipe = Flux2KleinPipeline.from_pretrained(
145
+ args.model, transformer=transformer, torch_dtype=torch.bfloat16
146
+ )
147
+ pipe.to(device)
148
+
149
+ # Set attention processor
150
+ setting = AttentionSetting.APITASMkernelNonLapStrict if args.strict else AttentionSetting.APITASMkernelNonLap
151
+ attn_proc, parallel_attn_proc = get_attention_processors(setting, kernel_size=args.kernel_size, temperature=args.temperature)
152
+ for name, module in pipe.transformer.named_modules():
153
+ if isinstance(module, Flux2Attention):
154
+ module.set_processor(attn_proc)
155
+ elif isinstance(module, Flux2ParallelSelfAttention):
156
+ module.set_processor(parallel_attn_proc)
157
+
158
+ # Run inference
159
+ logger.info("Running inference ...")
160
+ kwargs = {}
161
+ if instance_masks is not None:
162
+ kwargs["instance_masks_yx"] = instance_masks
163
+ else:
164
+ kwargs["instance_bboxes_xyxy_normalized"] = instance_bboxes
165
+
166
+ result = pipe(
167
+ image=image,
168
+ prompt=prompt,
169
+ height=new_h,
170
+ width=new_w,
171
+ num_inference_steps=args.num_inference_steps,
172
+ guidance_scale=1.0,
173
+ prompt_settings="outer_local_prompts",
174
+ attention_setting=setting.value,
175
+ hard_image_attribute_binding_list_double=double_layers,
176
+ hard_image_attribute_binding_list_single=single_layers,
177
+ generator=torch.Generator(device=device).manual_seed(SEED),
178
+ hard_masking_steps=list(range(args.num_inference_steps)),
179
+ relaxed_timesteps="soft",
180
+ attention_kwargs={"smooth_P_L": False},
181
+ free_latent=False,
182
+ free_context=False,
183
+ **kwargs,
184
+ )
185
+
186
+ output_image = result.images[0]
187
+
188
+ # Resize back to original dimensions
189
+ if output_image.size != original_size:
190
+ output_image = output_image.resize(original_size, resample=Image.LANCZOS)
191
+
192
+ output_image.save(args.output)
193
+ logger.info(f"Saved result to {args.output}")
194
+
195
+
196
+ if __name__ == "__main__":
197
+ main()
infer_flux2_lomoe.py ADDED
@@ -0,0 +1,198 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Script for running MICE inference on the LoMOE-Bench dataset.
3
+ """
4
+ import sys
5
+ import argparse
6
+ import torch
7
+ import numpy as np
8
+ from PIL import Image
9
+ from pathlib import Path
10
+ from tqdm import tqdm
11
+ from loguru import logger
12
+ import random
13
+
14
+ REPO_ROOT = Path(__file__).resolve().parent
15
+ if str(REPO_ROOT) not in sys.path:
16
+ sys.path.insert(0, str(REPO_ROOT))
17
+
18
+ from flux2.pipeline_flux2_klein import Flux2KleinPipeline
19
+ from flux2.transformer_flux2_klein import Flux2Transformer2DModel, Flux2Attention, Flux2ParallelSelfAttention
20
+ from flux2.attention import get_attention_processors, AttentionSetting
21
+ from lomoe_dataset import get_lomoe_dataloader
22
+
23
+ SEED = 0
24
+ torch.manual_seed(SEED)
25
+ random.seed(SEED)
26
+ np.random.seed(SEED)
27
+ torch.backends.cudnn.deterministic = True
28
+ torch.backends.cudnn.benchmark = False
29
+
30
+ def parse_args():
31
+ parser = argparse.ArgumentParser(description="Run MICE inference on the LoMOE-Bench dataset.")
32
+
33
+ parser.add_argument("--pretrained_model_name_or_path", type=str, default="black-forest-labs/FLUX.2-klein-4B")
34
+ parser.add_argument("--output_dir", type=str, default="results")
35
+ parser.add_argument("--exp_name", type=str, required=True, help="Experiment name for results subfolder")
36
+ parser.add_argument("--num_samples", type=int, default=None, help="Limit number of samples (for debugging)")
37
+ parser.add_argument("--num_inference_steps", type=int, default=4)
38
+ parser.add_argument("--guidance_scale", type=float, default=1.0)
39
+ parser.add_argument("--prompt_settings", type=str, default='outer_local_prompts',
40
+ choices=['base', 'inner_local_prompts', 'outer_local_prompts', 'outer_local_prompts_smart'])
41
+ parser.add_argument("--attention_setting", type=str, default='apitasmkernelnonlap',
42
+ choices=[s.value for s in AttentionSetting] + [s.name for s in AttentionSetting])
43
+ parser.add_argument("--bring_area_to_1024_squared", action="store_true")
44
+ parser.add_argument("--hard_image_attribute_binding_list_double", type=str, default="0,5",
45
+ help="Layer range (start, end) for double-stream blocks")
46
+ parser.add_argument("--hard_image_attribute_binding_list_single", type=str, default="0,20",
47
+ help="Layer range (start, end) for single-stream blocks")
48
+ parser.add_argument("--use_masks", action="store_true", help="Use masks instead of bboxes")
49
+ parser.add_argument("--sigma_scale", type=float, default=0.6)
50
+ parser.add_argument("--kernel_size", type=int, default=11)
51
+ parser.add_argument("--temperature", type=float, default=3.0)
52
+ parser.add_argument("--masking_steps", type=str, default="all",
53
+ help="Steps for hard masking, or \"all\"")
54
+ parser.add_argument("--relaxed_timesteps", type=str, default="soft", choices=["soft", "full"])
55
+ parser.add_argument("--smooth_P_L", action="store_true")
56
+ parser.add_argument("--free_latent", action="store_true")
57
+ parser.add_argument("--free_context", action="store_true")
58
+
59
+ args = parser.parse_args()
60
+
61
+ if args.use_masks:
62
+ logger.info("Using masks for image attribute binding")
63
+
64
+ def str2list(string):
65
+ return [int(item) for item in string.split(',')]
66
+
67
+ steps_list = list(range(0, args.num_inference_steps)) if args.masking_steps == "all" else str2list(args.masking_steps)
68
+ args.masking_steps = steps_list
69
+
70
+ def parse_layer_range(s):
71
+ parts = str2list(s)
72
+ return list(range(parts[0], parts[1])) if len(parts) >= 2 else []
73
+
74
+ args.hard_image_attribute_binding_list_double = parse_layer_range(args.hard_image_attribute_binding_list_double)
75
+ args.hard_image_attribute_binding_list_single = parse_layer_range(args.hard_image_attribute_binding_list_single)
76
+
77
+ return args
78
+
79
+ def load_pipeline(args, device):
80
+ logger.info(f"Loading Flux2KleinPipeline from {args.pretrained_model_name_or_path}")
81
+
82
+ transformer = Flux2Transformer2DModel.from_pretrained(
83
+ args.pretrained_model_name_or_path,
84
+ subfolder="transformer",
85
+ torch_dtype=torch.bfloat16,
86
+ low_cpu_mem_usage=False
87
+ )
88
+
89
+ pipe = Flux2KleinPipeline.from_pretrained(
90
+ args.pretrained_model_name_or_path,
91
+ transformer=transformer,
92
+ torch_dtype=torch.bfloat16
93
+ )
94
+ pipe.to(device)
95
+
96
+ return pipe
97
+
98
+ def main():
99
+ args = parse_args()
100
+ device = "cuda" if torch.cuda.is_available() else "cpu"
101
+
102
+ save_dir = Path(args.output_dir) / f"lomoe_flux2_klein_{args.exp_name}"
103
+ save_dir.mkdir(parents=True, exist_ok=True)
104
+ logger.info(f"Results will be saved to {save_dir}")
105
+
106
+ pipe = load_pipeline(args, device)
107
+
108
+ attn_proc = None
109
+ parallel_attn_proc = None
110
+ logger.info(f"Setting attention processor to {args.attention_setting}")
111
+ attn_setting_enum = AttentionSetting(args.attention_setting.lower())
112
+ processors = get_attention_processors(attn_setting_enum, args.sigma_scale, args.kernel_size, args.temperature)
113
+
114
+ if isinstance(processors, tuple) and len(processors) == 2:
115
+ attn_proc, parallel_attn_proc = processors
116
+ for name, module in pipe.transformer.named_modules():
117
+ if isinstance(module, Flux2Attention):
118
+ module.set_processor(attn_proc)
119
+ elif isinstance(module, Flux2ParallelSelfAttention):
120
+ module.set_processor(parallel_attn_proc)
121
+ else:
122
+ pipe.transformer.set_attn_processor(processors)
123
+
124
+ dataloader = get_lomoe_dataloader(
125
+ batch_size=1,
126
+ shuffle=False,
127
+ target_size=1024
128
+ )
129
+
130
+ if args.num_samples:
131
+ logger.info(f"Limiting to first {args.num_samples} samples")
132
+
133
+ logger.info("Starting inference...")
134
+
135
+ for i, batch in enumerate(tqdm(dataloader)):
136
+ if args.num_samples and i >= args.num_samples:
137
+ break
138
+
139
+ for sample in batch:
140
+ sample_id = sample['sample_id']
141
+ image = sample['image']
142
+ original_size = sample['original_size']
143
+ bboxes = sample['bboxes']
144
+ masks = sample['masks']
145
+ prompt_with_breakflag = sample['prompt']
146
+
147
+ filename = f"{sample_id}_result.png"
148
+ save_path = save_dir / filename
149
+ if save_path.exists():
150
+ continue
151
+
152
+ if attn_proc and hasattr(attn_proc, 'clear_cached_masks'):
153
+ attn_proc.clear_cached_masks()
154
+ if parallel_attn_proc and hasattr(parallel_attn_proc, 'clear_cached_masks'):
155
+ parallel_attn_proc.clear_cached_masks()
156
+
157
+ w, h = image.size
158
+
159
+ logger.info(f"Processing sample {sample_id}...")
160
+
161
+ kwargs = {}
162
+ if args.use_masks:
163
+ kwargs['instance_masks_yx'] = masks
164
+ else:
165
+ kwargs['instance_bboxes_xyxy_normalized'] = bboxes
166
+
167
+ result = pipe(
168
+ image=image,
169
+ prompt=prompt_with_breakflag,
170
+ height=h,
171
+ width=w,
172
+ num_inference_steps=args.num_inference_steps,
173
+ guidance_scale=args.guidance_scale,
174
+ prompt_settings=args.prompt_settings,
175
+ attention_setting=args.attention_setting,
176
+ hard_image_attribute_binding_list_double=args.hard_image_attribute_binding_list_double,
177
+ hard_image_attribute_binding_list_single=args.hard_image_attribute_binding_list_single,
178
+ bring_area_to_1024_squared=args.bring_area_to_1024_squared,
179
+ generator=torch.Generator(device=device).manual_seed(SEED),
180
+ hard_masking_steps=args.masking_steps,
181
+ relaxed_timesteps=args.relaxed_timesteps,
182
+ attention_kwargs={"smooth_P_L": args.smooth_P_L},
183
+ free_latent=args.free_latent,
184
+ free_context=args.free_context,
185
+ **kwargs,
186
+ )
187
+
188
+ generated_image = result.images[0]
189
+
190
+ orig_w, orig_h = original_size
191
+ if generated_image.size != (orig_w, orig_h):
192
+ generated_image = generated_image.resize((orig_w, orig_h), resample=Image.LANCZOS)
193
+
194
+ generated_image.save(save_path)
195
+ logger.info(f"Saved result to {save_path}")
196
+
197
+ if __name__ == "__main__":
198
+ main()
infer_flux2_lomoe_sam3.py ADDED
@@ -0,0 +1,203 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Script for running MICE inference on the SAM3-masked LoMOE-Bench dataset.
3
+ """
4
+ import sys
5
+ import argparse
6
+ import torch
7
+ import numpy as np
8
+ from PIL import Image
9
+ from pathlib import Path
10
+ from tqdm import tqdm
11
+ from loguru import logger
12
+ import random
13
+
14
+ REPO_ROOT = Path(__file__).resolve().parent
15
+ if str(REPO_ROOT) not in sys.path:
16
+ sys.path.insert(0, str(REPO_ROOT))
17
+
18
+ from flux2.pipeline_flux2_klein import Flux2KleinPipeline
19
+ from flux2.transformer_flux2_klein import Flux2Transformer2DModel, Flux2Attention, Flux2ParallelSelfAttention
20
+ from flux2.attention import get_attention_processors, AttentionSetting
21
+ from lomoe_dataset_mobius import get_lomoe_mobius_dataloader
22
+
23
+ SEED = 0
24
+ torch.manual_seed(SEED)
25
+ random.seed(SEED)
26
+ np.random.seed(SEED)
27
+ torch.backends.cudnn.deterministic = True
28
+ torch.backends.cudnn.benchmark = False
29
+
30
+
31
+ def parse_args():
32
+ parser = argparse.ArgumentParser(description="Run MICE inference on the SAM3-masked LoMOE-Bench dataset.")
33
+
34
+ parser.add_argument("--pretrained_model_name_or_path", type=str, default="black-forest-labs/FLUX.2-klein-4B")
35
+ parser.add_argument("--dataset_root", type=str, default="/mnt/ssd1/lomoe_bench_sam3",
36
+ help="Root directory of the SAM3-masked LoMOE-Bench dataset")
37
+ parser.add_argument("--output_dir", type=str, default="results_sam3")
38
+ parser.add_argument("--exp_name", type=str, required=True, help="Experiment name for results subfolder")
39
+ parser.add_argument("--num_samples", type=int, default=None, help="Limit number of samples (for debugging)")
40
+ parser.add_argument("--num_inference_steps", type=int, default=4)
41
+ parser.add_argument("--guidance_scale", type=float, default=1.0)
42
+ parser.add_argument("--prompt_settings", type=str, default='outer_local_prompts',
43
+ choices=['base', 'inner_local_prompts', 'outer_local_prompts', 'outer_local_prompts_smart'])
44
+ parser.add_argument("--attention_setting", type=str, default='apitasmkernelnonlap',
45
+ choices=[s.value for s in AttentionSetting] + [s.name for s in AttentionSetting])
46
+ parser.add_argument("--bring_area_to_1024_squared", action="store_true")
47
+ parser.add_argument("--hard_image_attribute_binding_list", type=str, default="0,57",
48
+ help="Layer range (start, end) for attention binding")
49
+ parser.add_argument("--use_masks", action="store_true", help="Use masks instead of bboxes")
50
+ parser.add_argument("--sigma_scale", type=float, default=0.6)
51
+ parser.add_argument("--kernel_size", type=int, default=11)
52
+ parser.add_argument("--temperature", type=float, default=3.0)
53
+ parser.add_argument("--masking_steps", type=str, default="all",
54
+ help="Steps for hard masking, or \"all\"")
55
+ parser.add_argument("--relaxed_timesteps", type=str, default="soft", choices=["soft", "full"])
56
+ parser.add_argument("--smooth_P_L", action="store_true")
57
+ parser.add_argument("--free_latent", action="store_true")
58
+ parser.add_argument("--free_context", action="store_true")
59
+ parser.add_argument("--free_LC", action="store_true")
60
+
61
+ args = parser.parse_args()
62
+
63
+ if args.use_masks:
64
+ logger.info("Using masks for image attribute binding")
65
+
66
+ def str2list(string):
67
+ return [int(item) for item in string.split(',')]
68
+
69
+ steps_list = list(range(0, args.num_inference_steps)) if args.masking_steps == "all" else str2list(args.masking_steps)
70
+ args.masking_steps = steps_list
71
+
72
+ raw_layer_list = str2list(args.hard_image_attribute_binding_list)
73
+ if len(raw_layer_list) > 0:
74
+ args.hard_image_attribute_binding_list = list(range(raw_layer_list[0], raw_layer_list[1]))
75
+ else:
76
+ args.hard_image_attribute_binding_list = []
77
+
78
+ return args
79
+
80
+
81
+ def load_pipeline(args, device):
82
+ logger.info(f"Loading Flux2KleinPipeline from {args.pretrained_model_name_or_path}")
83
+
84
+ transformer = Flux2Transformer2DModel.from_pretrained(
85
+ args.pretrained_model_name_or_path,
86
+ subfolder="transformer",
87
+ torch_dtype=torch.bfloat16,
88
+ low_cpu_mem_usage=False
89
+ )
90
+
91
+ pipe = Flux2KleinPipeline.from_pretrained(
92
+ args.pretrained_model_name_or_path,
93
+ transformer=transformer,
94
+ torch_dtype=torch.bfloat16
95
+ )
96
+ pipe.to(device)
97
+
98
+ return pipe
99
+
100
+
101
+ def main():
102
+ args = parse_args()
103
+ device = "cuda" if torch.cuda.is_available() else "cpu"
104
+
105
+ save_dir = Path(args.output_dir) / f"lomoe_flux2_sam3_{args.exp_name}"
106
+ save_dir.mkdir(parents=True, exist_ok=True)
107
+ logger.info(f"Results will be saved to {save_dir}")
108
+
109
+ pipe = load_pipeline(args, device)
110
+
111
+ attn_proc = None
112
+ parallel_attn_proc = None
113
+ logger.info(f"Setting attention processor to {args.attention_setting}")
114
+ attn_setting_enum = AttentionSetting(args.attention_setting.lower())
115
+ processors = get_attention_processors(attn_setting_enum, args.sigma_scale, args.kernel_size, args.temperature)
116
+
117
+ if isinstance(processors, tuple) and len(processors) == 2:
118
+ attn_proc, parallel_attn_proc = processors
119
+ for name, module in pipe.transformer.named_modules():
120
+ if isinstance(module, Flux2Attention):
121
+ module.set_processor(attn_proc)
122
+ elif isinstance(module, Flux2ParallelSelfAttention):
123
+ module.set_processor(parallel_attn_proc)
124
+ else:
125
+ pipe.transformer.set_attn_processor(processors)
126
+
127
+ dataloader = get_lomoe_mobius_dataloader(
128
+ root_dir=args.dataset_root,
129
+ batch_size=1,
130
+ shuffle=False,
131
+ target_size=1024,
132
+ )
133
+
134
+ if args.num_samples:
135
+ logger.info(f"Limiting to first {args.num_samples} samples")
136
+
137
+ logger.info("Starting inference...")
138
+
139
+ for i, batch in enumerate(tqdm(dataloader)):
140
+ if args.num_samples and i >= args.num_samples:
141
+ break
142
+
143
+ for sample in batch:
144
+ sample_id = sample['sample_id']
145
+ image = sample['image']
146
+ original_size = sample['original_size']
147
+ bboxes = sample['bboxes']
148
+ masks = sample['masks']
149
+ prompt_with_breakflag = sample['prompt']
150
+
151
+ filename = f"{sample_id}_result.png"
152
+ save_path = save_dir / filename
153
+ if save_path.exists():
154
+ continue
155
+
156
+ if attn_proc and hasattr(attn_proc, 'clear_cached_masks'):
157
+ attn_proc.clear_cached_masks()
158
+ if parallel_attn_proc and hasattr(parallel_attn_proc, 'clear_cached_masks'):
159
+ parallel_attn_proc.clear_cached_masks()
160
+
161
+ w, h = image.size
162
+
163
+ logger.info(f"Processing sample {sample_id}...")
164
+
165
+ kwargs = {}
166
+ if args.use_masks:
167
+ kwargs['instance_masks_yx'] = masks
168
+ else:
169
+ kwargs['instance_bboxes_xyxy_normalized'] = bboxes
170
+
171
+ result = pipe(
172
+ image=image,
173
+ prompt=prompt_with_breakflag,
174
+ height=h,
175
+ width=w,
176
+ num_inference_steps=args.num_inference_steps,
177
+ guidance_scale=args.guidance_scale,
178
+ prompt_settings=args.prompt_settings,
179
+ attention_setting=args.attention_setting,
180
+ hard_image_attribute_binding_list=args.hard_image_attribute_binding_list,
181
+ bring_area_to_1024_squared=args.bring_area_to_1024_squared,
182
+ generator=torch.Generator(device=device).manual_seed(SEED),
183
+ hard_masking_steps=args.masking_steps,
184
+ relaxed_timesteps=args.relaxed_timesteps,
185
+ attention_kwargs={"smooth_P_L": args.smooth_P_L},
186
+ free_latent=args.free_latent,
187
+ free_context=args.free_context,
188
+ free_LC=args.free_LC,
189
+ **kwargs,
190
+ )
191
+
192
+ generated_image = result.images[0]
193
+
194
+ orig_w, orig_h = original_size
195
+ if generated_image.size != (orig_w, orig_h):
196
+ generated_image = generated_image.resize((orig_w, orig_h), resample=Image.LANCZOS)
197
+
198
+ generated_image.save(save_path)
199
+ logger.info(f"Saved result to {save_path}")
200
+
201
+
202
+ if __name__ == "__main__":
203
+ main()
infer_flux2_mice.py ADDED
@@ -0,0 +1,202 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Script for running MICE inference on the MICE-Bench dataset.
3
+ """
4
+ import sys
5
+ import argparse
6
+ import torch
7
+ import numpy as np
8
+ from PIL import Image
9
+ from pathlib import Path
10
+ from tqdm import tqdm
11
+ from loguru import logger
12
+ import random
13
+ from mice_dataset import get_mice_dataloader
14
+
15
+ REPO_ROOT = Path(__file__).resolve().parent
16
+ if str(REPO_ROOT) not in sys.path:
17
+ sys.path.insert(0, str(REPO_ROOT))
18
+
19
+ from flux2.pipeline_flux2_klein import Flux2KleinPipeline
20
+ from flux2.transformer_flux2_klein import Flux2Transformer2DModel, Flux2Attention, Flux2ParallelSelfAttention
21
+ from flux2.attention import get_attention_processors, AttentionSetting
22
+
23
+ SEED = 0
24
+ torch.manual_seed(SEED)
25
+ random.seed(SEED)
26
+ np.random.seed(SEED)
27
+ torch.backends.cudnn.deterministic = True
28
+ torch.backends.cudnn.benchmark = False
29
+
30
+ def parse_args():
31
+ parser = argparse.ArgumentParser(description="Run MICE inference on the MICE-Bench dataset.")
32
+
33
+ parser.add_argument("--pretrained_model_name_or_path", type=str, default="black-forest-labs/FLUX.2-klein-4B")
34
+ parser.add_argument("--dataset_root", type=str, default="../mice_bench", help="Root directory of MICE-Bench dataset")
35
+ parser.add_argument("--output_dir", type=str, default="results_micebench")
36
+ parser.add_argument("--exp_name", type=str, required=True, help="Experiment name for results subfolder")
37
+ parser.add_argument("--num_samples", type=int, default=None, help="Limit number of samples (for debugging)")
38
+ parser.add_argument("--num_inference_steps", type=int, default=4)
39
+ parser.add_argument("--guidance_scale", type=float, default=1.0)
40
+ parser.add_argument("--prompt_settings", type=str, default='outer_local_prompts',
41
+ choices=['base', 'inner_local_prompts', 'outer_local_prompts', 'outer_local_prompts_smart'])
42
+ parser.add_argument("--attention_setting", type=str, default='apitasmkernelnonlap',
43
+ choices=[s.value for s in AttentionSetting] + [s.name for s in AttentionSetting])
44
+ parser.add_argument("--bring_area_to_1024_squared", action="store_true")
45
+ parser.add_argument("--hard_image_attribute_binding_list_double", type=str, default="0,5",
46
+ help="Layer range (start, end) for double-stream blocks")
47
+ parser.add_argument("--hard_image_attribute_binding_list_single", type=str, default="0,20",
48
+ help="Layer range (start, end) for single-stream blocks")
49
+ parser.add_argument("--use_masks", action="store_true", help="Use masks instead of bboxes")
50
+ parser.add_argument("--sigma_scale", type=float, default=0.6)
51
+ parser.add_argument("--kernel_size", type=int, default=11)
52
+ parser.add_argument("--temperature", type=float, default=3.0)
53
+ parser.add_argument("--masking_steps", type=str, default="all",
54
+ help="Steps for hard masking, or \"all\"")
55
+ parser.add_argument("--relaxed_timesteps", type=str, default="soft", choices=["soft", "full"])
56
+ parser.add_argument("--smooth_P_L", action="store_true")
57
+ parser.add_argument("--free_latent", action="store_true")
58
+ parser.add_argument("--free_context", action="store_true")
59
+ parser.add_argument("--free_LC", action="store_true")
60
+
61
+ args = parser.parse_args()
62
+
63
+ if args.use_masks:
64
+ logger.info("Using masks for image attribute binding")
65
+
66
+ def str2list(string):
67
+ return [int(item) for item in string.split(',')]
68
+
69
+ steps_list = list(range(0, args.num_inference_steps)) if args.masking_steps == "all" else str2list(args.masking_steps)
70
+ args.masking_steps = steps_list
71
+
72
+ def parse_layer_range(s):
73
+ parts = str2list(s)
74
+ return list(range(parts[0], parts[1])) if len(parts) >= 2 else []
75
+
76
+ args.hard_image_attribute_binding_list_double = parse_layer_range(args.hard_image_attribute_binding_list_double)
77
+ args.hard_image_attribute_binding_list_single = parse_layer_range(args.hard_image_attribute_binding_list_single)
78
+
79
+ return args
80
+
81
+ def load_pipeline(args, device):
82
+ logger.info(f"Loading Flux2KleinPipeline from {args.pretrained_model_name_or_path}")
83
+
84
+ transformer = Flux2Transformer2DModel.from_pretrained(
85
+ args.pretrained_model_name_or_path,
86
+ subfolder="transformer",
87
+ torch_dtype=torch.bfloat16,
88
+ low_cpu_mem_usage=False
89
+ )
90
+
91
+ pipe = Flux2KleinPipeline.from_pretrained(
92
+ args.pretrained_model_name_or_path,
93
+ transformer=transformer,
94
+ torch_dtype=torch.bfloat16
95
+ )
96
+ pipe.to(device)
97
+
98
+ return pipe
99
+
100
+ def main():
101
+ args = parse_args()
102
+ device = "cuda" if torch.cuda.is_available() else "cpu"
103
+
104
+ save_dir = Path(args.output_dir) / f"mice_flux2_klein_{args.exp_name}"
105
+ save_dir.mkdir(parents=True, exist_ok=True)
106
+ logger.info(f"Results will be saved to {save_dir}")
107
+
108
+ pipe = load_pipeline(args, device)
109
+
110
+ attn_proc = None
111
+ parallel_attn_proc = None
112
+ logger.info(f"Setting attention processor to {args.attention_setting}")
113
+ attn_setting_enum = AttentionSetting(args.attention_setting.lower())
114
+ processors = get_attention_processors(attn_setting_enum, args.sigma_scale, args.kernel_size, args.temperature)
115
+
116
+ if isinstance(processors, tuple) and len(processors) == 2:
117
+ attn_proc, parallel_attn_proc = processors
118
+ for name, module in pipe.transformer.named_modules():
119
+ if isinstance(module, Flux2Attention):
120
+ module.set_processor(attn_proc)
121
+ elif isinstance(module, Flux2ParallelSelfAttention):
122
+ module.set_processor(parallel_attn_proc)
123
+ else:
124
+ pipe.transformer.set_attn_processor(processors)
125
+
126
+ dataloader = get_mice_dataloader(
127
+ root_dir=args.dataset_root,
128
+ batch_size=1,
129
+ shuffle=False,
130
+ target_size=1024
131
+ )
132
+
133
+ if args.num_samples:
134
+ logger.info(f"Limiting to first {args.num_samples} samples")
135
+
136
+ logger.info("Starting inference...")
137
+
138
+ for i, batch in enumerate(tqdm(dataloader)):
139
+ if args.num_samples and i >= args.num_samples:
140
+ break
141
+
142
+ for sample in batch:
143
+ sample_id = sample['sample_id']
144
+ image = sample['image']
145
+ original_size = sample['original_size']
146
+ bboxes = sample['bboxes']
147
+ masks = sample['masks']
148
+ prompt_with_breakflag = sample['prompt']
149
+
150
+ filename = f"{sample_id}_result.png"
151
+ save_path = save_dir / filename
152
+ if save_path.exists():
153
+ continue
154
+
155
+ if attn_proc and hasattr(attn_proc, 'clear_cached_masks'):
156
+ attn_proc.clear_cached_masks()
157
+ if parallel_attn_proc and hasattr(parallel_attn_proc, 'clear_cached_masks'):
158
+ parallel_attn_proc.clear_cached_masks()
159
+
160
+ w, h = image.size
161
+
162
+ logger.info(f"Processing sample {sample_id}...")
163
+
164
+ kwargs = {}
165
+ if args.use_masks:
166
+ kwargs['instance_masks_yx'] = masks
167
+ else:
168
+ kwargs['instance_bboxes_xyxy_normalized'] = bboxes
169
+
170
+ result = pipe(
171
+ image=image,
172
+ prompt=prompt_with_breakflag,
173
+ height=h,
174
+ width=w,
175
+ num_inference_steps=args.num_inference_steps,
176
+ guidance_scale=args.guidance_scale,
177
+ prompt_settings=args.prompt_settings,
178
+ attention_setting=args.attention_setting,
179
+ hard_image_attribute_binding_list_double=args.hard_image_attribute_binding_list_double,
180
+ hard_image_attribute_binding_list_single=args.hard_image_attribute_binding_list_single,
181
+ bring_area_to_1024_squared=args.bring_area_to_1024_squared,
182
+ generator=torch.Generator(device=device).manual_seed(SEED),
183
+ hard_masking_steps=args.masking_steps,
184
+ relaxed_timesteps=args.relaxed_timesteps,
185
+ attention_kwargs={"smooth_P_L": args.smooth_P_L},
186
+ free_latent=args.free_latent,
187
+ free_context=args.free_context,
188
+ free_LC=args.free_LC,
189
+ **kwargs,
190
+ )
191
+
192
+ generated_image = result.images[0]
193
+
194
+ orig_w, orig_h = original_size
195
+ if generated_image.size != (orig_w, orig_h):
196
+ generated_image = generated_image.resize((orig_w, orig_h), resample=Image.LANCZOS)
197
+
198
+ generated_image.save(save_path)
199
+ logger.info(f"Saved result to {save_path}")
200
+
201
+ if __name__ == "__main__":
202
+ main()
infer_flux2_mice_sam3.py ADDED
@@ -0,0 +1,199 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Script for running MICE inference on the SAM3-masked MICE-Bench dataset.
3
+ """
4
+ import sys
5
+ import argparse
6
+ import torch
7
+ import numpy as np
8
+ from PIL import Image
9
+ from pathlib import Path
10
+ from tqdm import tqdm
11
+ from loguru import logger
12
+ import random
13
+ from mice_dataset_mobius import get_mice_mobius_dataloader
14
+
15
+ REPO_ROOT = Path(__file__).resolve().parent
16
+ if str(REPO_ROOT) not in sys.path:
17
+ sys.path.insert(0, str(REPO_ROOT))
18
+
19
+ from flux2.pipeline_flux2_klein import Flux2KleinPipeline
20
+ from flux2.transformer_flux2_klein import Flux2Transformer2DModel, Flux2Attention, Flux2ParallelSelfAttention
21
+ from flux2.attention import get_attention_processors, AttentionSetting
22
+
23
+ SEED = 0
24
+ torch.manual_seed(SEED)
25
+ random.seed(SEED)
26
+ np.random.seed(SEED)
27
+ torch.backends.cudnn.deterministic = True
28
+ torch.backends.cudnn.benchmark = False
29
+
30
+ def parse_args():
31
+ parser = argparse.ArgumentParser(description="Run MICE inference on the SAM3-masked MICE-Bench dataset.")
32
+
33
+ parser.add_argument("--pretrained_model_name_or_path", type=str, default="black-forest-labs/FLUX.2-klein-4B")
34
+ parser.add_argument("--dataset_root", type=str, default="/mnt/ssd1/mice_bench_sam3",
35
+ help="Root directory of the SAM3-masked MICE-Bench dataset")
36
+ parser.add_argument("--output_dir", type=str, default="results_micebench_sam3")
37
+ parser.add_argument("--exp_name", type=str, required=True, help="Experiment name for results subfolder")
38
+ parser.add_argument("--num_samples", type=int, default=None, help="Limit number of samples (for debugging)")
39
+ parser.add_argument("--num_inference_steps", type=int, default=4)
40
+ parser.add_argument("--guidance_scale", type=float, default=1.0)
41
+ parser.add_argument("--prompt_settings", type=str, default='outer_local_prompts',
42
+ choices=['base', 'inner_local_prompts', 'outer_local_prompts', 'outer_local_prompts_smart'])
43
+ parser.add_argument("--attention_setting", type=str, default='apitasmkernelnonlap',
44
+ choices=[s.value for s in AttentionSetting] + [s.name for s in AttentionSetting])
45
+ parser.add_argument("--bring_area_to_1024_squared", action="store_true")
46
+ parser.add_argument("--hard_image_attribute_binding_list", type=str, default="0,57",
47
+ help="Layer range (start, end) for attention binding")
48
+ parser.add_argument("--use_masks", action="store_true", help="Use masks instead of bboxes")
49
+ parser.add_argument("--sigma_scale", type=float, default=0.6)
50
+ parser.add_argument("--kernel_size", type=int, default=11)
51
+ parser.add_argument("--temperature", type=float, default=3.0)
52
+ parser.add_argument("--masking_steps", type=str, default="all",
53
+ help="Steps for hard masking, or \"all\"")
54
+ parser.add_argument("--relaxed_timesteps", type=str, default="soft", choices=["soft", "full"])
55
+ parser.add_argument("--smooth_P_L", action="store_true")
56
+ parser.add_argument("--free_latent", action="store_true")
57
+ parser.add_argument("--free_context", action="store_true")
58
+ parser.add_argument("--free_LC", action="store_true")
59
+
60
+ args = parser.parse_args()
61
+
62
+ if args.use_masks:
63
+ logger.info("Using masks for image attribute binding")
64
+
65
+ def str2list(string):
66
+ return [int(item) for item in string.split(',')]
67
+
68
+ steps_list = list(range(0, args.num_inference_steps)) if args.masking_steps == "all" else str2list(args.masking_steps)
69
+ args.masking_steps = steps_list
70
+
71
+ raw_layer_list = str2list(args.hard_image_attribute_binding_list)
72
+ if len(raw_layer_list) > 0:
73
+ args.hard_image_attribute_binding_list = list(range(raw_layer_list[0], raw_layer_list[1]))
74
+ else:
75
+ args.hard_image_attribute_binding_list = []
76
+
77
+ return args
78
+
79
+ def load_pipeline(args, device):
80
+ logger.info(f"Loading Flux2KleinPipeline from {args.pretrained_model_name_or_path}")
81
+
82
+ transformer = Flux2Transformer2DModel.from_pretrained(
83
+ args.pretrained_model_name_or_path,
84
+ subfolder="transformer",
85
+ torch_dtype=torch.bfloat16,
86
+ low_cpu_mem_usage=False
87
+ )
88
+
89
+ pipe = Flux2KleinPipeline.from_pretrained(
90
+ args.pretrained_model_name_or_path,
91
+ transformer=transformer,
92
+ torch_dtype=torch.bfloat16
93
+ )
94
+ pipe.to(device)
95
+
96
+ return pipe
97
+
98
+ def main():
99
+ args = parse_args()
100
+ device = "cuda" if torch.cuda.is_available() else "cpu"
101
+
102
+ save_dir = Path(args.output_dir) / f"mice_flux2_sam3_{args.exp_name}"
103
+ save_dir.mkdir(parents=True, exist_ok=True)
104
+ logger.info(f"Results will be saved to {save_dir}")
105
+
106
+ pipe = load_pipeline(args, device)
107
+
108
+ attn_proc = None
109
+ parallel_attn_proc = None
110
+ logger.info(f"Setting attention processor to {args.attention_setting}")
111
+ attn_setting_enum = AttentionSetting(args.attention_setting.lower())
112
+ processors = get_attention_processors(attn_setting_enum, args.sigma_scale, args.kernel_size, args.temperature)
113
+
114
+ if isinstance(processors, tuple) and len(processors) == 2:
115
+ attn_proc, parallel_attn_proc = processors
116
+ for name, module in pipe.transformer.named_modules():
117
+ if isinstance(module, Flux2Attention):
118
+ module.set_processor(attn_proc)
119
+ elif isinstance(module, Flux2ParallelSelfAttention):
120
+ module.set_processor(parallel_attn_proc)
121
+ else:
122
+ pipe.transformer.set_attn_processor(processors)
123
+
124
+ dataloader = get_mice_mobius_dataloader(
125
+ root_dir=args.dataset_root,
126
+ batch_size=1,
127
+ shuffle=False,
128
+ target_size=1024
129
+ )
130
+
131
+ if args.num_samples:
132
+ logger.info(f"Limiting to first {args.num_samples} samples")
133
+
134
+ logger.info("Starting inference...")
135
+
136
+ for i, batch in enumerate(tqdm(dataloader)):
137
+ if args.num_samples and i >= args.num_samples:
138
+ break
139
+
140
+ for sample in batch:
141
+ sample_id = sample['sample_id']
142
+ image = sample['image']
143
+ original_size = sample['original_size']
144
+ bboxes = sample['bboxes']
145
+ masks = sample['masks']
146
+ prompt_with_breakflag = sample['prompt']
147
+
148
+ filename = f"{sample_id}_result.png"
149
+ save_path = save_dir / filename
150
+ if save_path.exists():
151
+ continue
152
+
153
+ if attn_proc and hasattr(attn_proc, 'clear_cached_masks'):
154
+ attn_proc.clear_cached_masks()
155
+ if parallel_attn_proc and hasattr(parallel_attn_proc, 'clear_cached_masks'):
156
+ parallel_attn_proc.clear_cached_masks()
157
+
158
+ w, h = image.size
159
+
160
+ logger.info(f"Processing sample {sample_id}...")
161
+
162
+ kwargs = {}
163
+ if args.use_masks:
164
+ kwargs['instance_masks_yx'] = masks
165
+ else:
166
+ kwargs['instance_bboxes_xyxy_normalized'] = bboxes
167
+
168
+ result = pipe(
169
+ image=image,
170
+ prompt=prompt_with_breakflag,
171
+ height=h,
172
+ width=w,
173
+ num_inference_steps=args.num_inference_steps,
174
+ guidance_scale=args.guidance_scale,
175
+ prompt_settings=args.prompt_settings,
176
+ attention_setting=args.attention_setting,
177
+ hard_image_attribute_binding_list=args.hard_image_attribute_binding_list,
178
+ bring_area_to_1024_squared=args.bring_area_to_1024_squared,
179
+ generator=torch.Generator(device=device).manual_seed(SEED),
180
+ hard_masking_steps=args.masking_steps,
181
+ relaxed_timesteps=args.relaxed_timesteps,
182
+ attention_kwargs={"smooth_P_L": args.smooth_P_L},
183
+ free_latent=args.free_latent,
184
+ free_context=args.free_context,
185
+ free_LC=args.free_LC,
186
+ **kwargs,
187
+ )
188
+
189
+ generated_image = result.images[0]
190
+
191
+ orig_w, orig_h = original_size
192
+ if generated_image.size != (orig_w, orig_h):
193
+ generated_image = generated_image.resize((orig_w, orig_h), resample=Image.LANCZOS)
194
+
195
+ generated_image.save(save_path)
196
+ logger.info(f"Saved result to {save_path}")
197
+
198
+ if __name__ == "__main__":
199
+ main()
lomoe_dataset.py ADDED
@@ -0,0 +1,169 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+ import re
3
+ import numpy as np
4
+ import torch
5
+ from pathlib import Path
6
+ from PIL import Image
7
+ from torch.utils.data import Dataset, DataLoader
8
+ from loguru import logger
9
+
10
+ LOMOE_BASE_PATH = Path(__file__).parent
11
+ LOMOE_BENCH_PATH = LOMOE_BASE_PATH / 'benchmark/data/LoMOE-Bench'
12
+
13
+ def parse_quoted_strings(line: str) -> list[str]:
14
+ return re.findall(r'"([^"]*)"', line)
15
+
16
+
17
+ def load_mask(mask_path: Path) -> torch.Tensor:
18
+ if not mask_path.exists():
19
+ raise FileNotFoundError(f"Mask path {mask_path} does not exist.")
20
+ mask = torch.from_numpy(np.array(Image.open(mask_path).convert('L')) > 127).float()
21
+ return mask
22
+
23
+
24
+ def get_bbox_from_mask(mask_path: Path) -> list[float]:
25
+ if not mask_path.exists():
26
+ raise FileNotFoundError(f"Mask path {mask_path} does not exist.")
27
+ mask = Image.open(mask_path).convert('L')
28
+ mask_np = np.array(mask)
29
+ y_coords, x_coords = np.where(mask_np > 127)
30
+ if len(x_coords) == 0:
31
+ raise ValueError(f"Mask {mask_path} is empty.")
32
+ x1, x2 = x_coords.min(), x_coords.max()
33
+ y1, y2 = y_coords.min(), y_coords.max()
34
+ h, w = mask_np.shape
35
+ return [float(x1) / w, float(y1) / h, float(x2) / w, float(y2) / h]
36
+
37
+
38
+ def load_prompts_data(lomoe_config: dict, multi_turn_faithful_config: dict, multi_turn_enhanced_config: dict) -> dict[str, dict]:
39
+ source_file = LOMOE_BENCH_PATH / 'utils/mask_orig_prompts.txt'
40
+ target_file = LOMOE_BENCH_PATH / 'utils/text_prompts.txt'
41
+
42
+ if not source_file.exists() or not target_file.exists():
43
+ logger.warning("Prompt text files not found. Falling back to JSON config.")
44
+ prompts_data = {}
45
+ for sample_id, config in lomoe_config.items():
46
+ prompts_data[sample_id] = {
47
+ 'sources': [],
48
+ 'targets': parse_quoted_strings(config.get('fg_prompt', "")),
49
+ 'image_path': config['image_path'],
50
+ 'mask_paths': parse_quoted_strings(config.get('mask_path', "")),
51
+ }
52
+ return prompts_data
53
+
54
+ with open(source_file, 'r', encoding='utf-8') as f:
55
+ source_lines = f.readlines()
56
+
57
+ with open(target_file, 'r', encoding='utf-8') as f:
58
+ target_lines = f.readlines()
59
+
60
+ sorted_sample_ids = sorted(lomoe_config.keys(), key=lambda x: int(x))
61
+
62
+ if len(sorted_sample_ids) != len(source_lines):
63
+ logger.warning(f"Mismatch: {len(sorted_sample_ids)} JSON samples vs {len(source_lines)} txt lines. Truncating to minimum.")
64
+
65
+ prompts_data = {}
66
+ for sample_id, src_line, tgt_line in zip(sorted_sample_ids, source_lines, target_lines):
67
+ sources = parse_quoted_strings(src_line)
68
+ targets = parse_quoted_strings(tgt_line)
69
+ prompts_data[sample_id] = {
70
+ 'sources': sources,
71
+ 'targets': targets,
72
+ 'image_path': lomoe_config[sample_id]['image_path'],
73
+ 'mask_paths': parse_quoted_strings(lomoe_config[sample_id]['mask_path']),
74
+ "edit_instance_single": lomoe_config[sample_id]['edit_inst_single'],
75
+ "multi_turn_faithful": multi_turn_faithful_config[sample_id],
76
+ "multi_turn_enhanced": multi_turn_enhanced_config[sample_id],
77
+ }
78
+
79
+ return prompts_data
80
+
81
+ class LoMOEDataset(Dataset):
82
+ def __init__(self, target_size=1024, vae_scale_factor=8):
83
+ self.target_size = target_size
84
+ self.vae_scale_factor = vae_scale_factor
85
+
86
+ config_path = LOMOE_BENCH_PATH / 'LoMOE.json'
87
+ with open(config_path, 'r', encoding='utf-8') as f:
88
+ self.lomoe_config = json.load(f)
89
+
90
+ multi_turn_faithful_path = LOMOE_BENCH_PATH / 'LoMOE_multi_turn_faithful.json'
91
+ with open(multi_turn_faithful_path, 'r', encoding='utf-8') as f:
92
+ self.multi_turn_faithful_config = json.load(f)
93
+
94
+ multi_turn_enhanced_path = LOMOE_BENCH_PATH / 'LoMOE_multi_turn_enhanced.json'
95
+ with open(multi_turn_enhanced_path, 'r', encoding='utf-8') as f:
96
+ self.multi_turn_enhanced_config = json.load(f)
97
+
98
+ self.prompts_data = load_prompts_data(self.lomoe_config, self.multi_turn_faithful_config, self.multi_turn_enhanced_config)
99
+ self.sorted_ids = sorted(self.prompts_data.keys(), key=lambda x: int(x))
100
+
101
+ def __len__(self):
102
+ return len(self.sorted_ids)
103
+
104
+ def __getitem__(self, idx):
105
+ sample_id = self.sorted_ids[idx]
106
+ sample_prompts = self.prompts_data[sample_id]
107
+
108
+ image_path = LOMOE_BENCH_PATH / sample_prompts['image_path']
109
+ source_image = Image.open(image_path).convert('RGB')
110
+
111
+ instance_bboxes = []
112
+ for mask_p in sample_prompts['mask_paths']:
113
+ bbox = get_bbox_from_mask(LOMOE_BENCH_PATH / mask_p)
114
+ instance_bboxes.append(bbox)
115
+
116
+ instance_masks = []
117
+ for mask_p in sample_prompts['mask_paths']:
118
+ mask = load_mask(LOMOE_BENCH_PATH / mask_p)
119
+ instance_masks.append(mask)
120
+
121
+ text_sources = sample_prompts['sources']
122
+ text_targets = sample_prompts['targets']
123
+
124
+ global_prompt = " "
125
+ prompts = [global_prompt]
126
+ for src, tgt in zip(text_sources, text_targets):
127
+ prompts.append(f'Replace {src} with {tgt}')
128
+
129
+ prompt_2 = '$BREAKFLAG$'.join(prompts)
130
+
131
+ original_width, original_height = source_image.size
132
+ aspect_ratio = original_width / original_height
133
+ width = round((self.target_size * self.target_size * aspect_ratio) ** 0.5)
134
+ height = round((self.target_size * self.target_size / aspect_ratio) ** 0.5)
135
+
136
+ multiple_of = self.vae_scale_factor * 2
137
+ width = width // multiple_of * multiple_of
138
+ height = height // multiple_of * multiple_of
139
+
140
+ source_image_resized = source_image.resize((width, height), resample=Image.LANCZOS)
141
+
142
+ return {
143
+ "image": source_image_resized,
144
+ "prompt": prompt_2,
145
+ "sources": text_sources,
146
+ "edit_instance_single": sample_prompts['edit_instance_single'],
147
+ "bboxes": instance_bboxes,
148
+ "masks": instance_masks,
149
+ "sample_id": sample_id,
150
+ "original_size": [original_width, original_height],
151
+ 'targets': text_targets,
152
+ "multi_turn_faithful": sample_prompts['multi_turn_faithful'],
153
+ "multi_turn_enhanced": sample_prompts['multi_turn_enhanced'],
154
+ }
155
+
156
+
157
+ def collate_fn(batch):
158
+ return batch
159
+
160
+
161
+ def get_lomoe_dataloader(batch_size=1, shuffle=False, num_workers=0, **kwargs):
162
+ dataset = LoMOEDataset(**kwargs)
163
+ return DataLoader(
164
+ dataset,
165
+ batch_size=batch_size,
166
+ shuffle=shuffle,
167
+ num_workers=num_workers,
168
+ collate_fn=collate_fn
169
+ )
lomoe_dataset_mobius.py ADDED
@@ -0,0 +1,182 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Dataset loader for the SAM3-masked LoMOE-Bench dataset.
3
+ Reads from a dataset root directory that uses the same structure as the Mobius-masked dataset
4
+ (LoMOE_mobius.json with updated mask paths pointing to SAM3 masks).
5
+ """
6
+ import json
7
+ import re
8
+ import numpy as np
9
+ import torch
10
+ from pathlib import Path
11
+ from PIL import Image
12
+ from torch.utils.data import Dataset, DataLoader
13
+ from loguru import logger
14
+
15
+ # Original benchmark root (for prompt text files only)
16
+ LOMOE_BENCH_ORIG = Path("/mnt/ssd1/LoMOE/benchmark/data/LoMOE-Bench")
17
+
18
+ DEFAULT_ROOT = Path("/mnt/ssd1/lomoe_bench_mobius")
19
+
20
+
21
+ def parse_quoted_strings(line: str) -> list:
22
+ return re.findall(r'"([^"]*)"', line)
23
+
24
+
25
+ def load_mask(mask_path: Path) -> torch.Tensor:
26
+ if not mask_path.exists():
27
+ raise FileNotFoundError(f"Mask not found: {mask_path}")
28
+ mask = torch.from_numpy(np.array(Image.open(mask_path).convert('L')) > 127).float()
29
+ return mask
30
+
31
+
32
+ def get_bbox_from_mask(mask_path: Path) -> list:
33
+ if not mask_path.exists():
34
+ raise FileNotFoundError(f"Mask not found: {mask_path}")
35
+ mask_np = np.array(Image.open(mask_path).convert('L'))
36
+ y_coords, x_coords = np.where(mask_np > 127)
37
+ if len(x_coords) == 0:
38
+ raise ValueError(f"Empty mask: {mask_path}")
39
+ x1, x2 = x_coords.min(), x_coords.max()
40
+ y1, y2 = y_coords.min(), y_coords.max()
41
+ h, w = mask_np.shape
42
+ return [float(x1) / w, float(y1) / h, float(x2) / w, float(y2) / h]
43
+
44
+
45
+ def load_prompts_data(lomoe_config: dict) -> dict:
46
+ source_file = LOMOE_BENCH_ORIG / 'utils/mask_orig_prompts.txt'
47
+ target_file = LOMOE_BENCH_ORIG / 'utils/text_prompts.txt'
48
+
49
+ if not source_file.exists() or not target_file.exists():
50
+ logger.warning("Prompt text files not found. Falling back to JSON fg_prompt.")
51
+ prompts_data = {}
52
+ for sample_id, config in lomoe_config.items():
53
+ prompts_data[sample_id] = {
54
+ 'sources': [],
55
+ 'targets': parse_quoted_strings(config.get('fg_prompt', "")),
56
+ 'image_path': config['image_path'],
57
+ 'mask_paths': parse_quoted_strings(config.get('mask_path', "")),
58
+ 'edit_instance_single': config.get('edit_inst_single', ''),
59
+ }
60
+ return prompts_data
61
+
62
+ with open(source_file, 'r', encoding='utf-8') as f:
63
+ source_lines = f.readlines()
64
+ with open(target_file, 'r', encoding='utf-8') as f:
65
+ target_lines = f.readlines()
66
+
67
+ sorted_sample_ids = sorted(lomoe_config.keys(), key=lambda x: int(x))
68
+
69
+ if len(sorted_sample_ids) != len(source_lines):
70
+ logger.warning(
71
+ f"Mismatch: {len(sorted_sample_ids)} JSON samples vs {len(source_lines)} txt lines. "
72
+ f"Truncating to minimum."
73
+ )
74
+
75
+ prompts_data = {}
76
+ for sample_id, src_line, tgt_line in zip(sorted_sample_ids, source_lines, target_lines):
77
+ sources = parse_quoted_strings(src_line)
78
+ targets = parse_quoted_strings(tgt_line)
79
+ prompts_data[sample_id] = {
80
+ 'sources': sources,
81
+ 'targets': targets,
82
+ 'image_path': lomoe_config[sample_id]['image_path'],
83
+ 'mask_paths': parse_quoted_strings(lomoe_config[sample_id]['mask_path']),
84
+ 'edit_instance_single': lomoe_config[sample_id].get('edit_inst_single', ''),
85
+ }
86
+
87
+ return prompts_data
88
+
89
+
90
+ class LoMOEMobiusDataset(Dataset):
91
+ def __init__(self, root_dir=None, target_size=1024, vae_scale_factor=8):
92
+ self.target_size = target_size
93
+ self.vae_scale_factor = vae_scale_factor
94
+ self.root_dir = Path(root_dir) if root_dir else DEFAULT_ROOT
95
+
96
+ config_path = self.root_dir / 'LoMOE_mobius.json'
97
+ if not config_path.exists():
98
+ raise FileNotFoundError(
99
+ f"LoMOE_mobius.json not found at {config_path}."
100
+ )
101
+
102
+ with open(config_path, 'r', encoding='utf-8') as f:
103
+ self.lomoe_config = json.load(f)
104
+
105
+ self.prompts_data = load_prompts_data(self.lomoe_config)
106
+ self.sorted_ids = sorted(self.prompts_data.keys(), key=lambda x: int(x))
107
+
108
+ def __len__(self):
109
+ return len(self.sorted_ids)
110
+
111
+ def __getitem__(self, idx):
112
+ sample_id = self.sorted_ids[idx]
113
+ sample_prompts = self.prompts_data[sample_id]
114
+
115
+ image_path = self.root_dir / sample_prompts['image_path']
116
+ if not image_path.exists():
117
+ image_path = LOMOE_BENCH_ORIG / sample_prompts['image_path']
118
+ source_image = Image.open(image_path).convert('RGB')
119
+
120
+ instance_bboxes = []
121
+ instance_masks = []
122
+ for mask_rel in sample_prompts['mask_paths']:
123
+ mask_path = self.root_dir / mask_rel
124
+ if not mask_path.exists() or 'MISSING_MASK' in mask_rel:
125
+ logger.warning(f"Mask missing for sample {sample_id}: {mask_rel} — using zero mask")
126
+ h, w = source_image.size[1], source_image.size[0]
127
+ instance_masks.append(torch.zeros(h, w))
128
+ instance_bboxes.append([0.0, 0.0, 1.0, 1.0])
129
+ continue
130
+ try:
131
+ instance_masks.append(load_mask(mask_path))
132
+ instance_bboxes.append(get_bbox_from_mask(mask_path))
133
+ except Exception as e:
134
+ logger.warning(f"Failed to load mask {mask_path}: {e} — using zero mask")
135
+ h, w = source_image.size[1], source_image.size[0]
136
+ instance_masks.append(torch.zeros(h, w))
137
+ instance_bboxes.append([0.0, 0.0, 1.0, 1.0])
138
+
139
+ text_sources = sample_prompts['sources']
140
+ text_targets = sample_prompts['targets']
141
+
142
+ global_prompt = " "
143
+ prompts = [global_prompt]
144
+ for src, tgt in zip(text_sources, text_targets):
145
+ prompts.append(f'Replace {src} with {tgt}')
146
+ prompt_with_breakflag = '$BREAKFLAG$'.join(prompts)
147
+
148
+ original_width, original_height = source_image.size
149
+ aspect_ratio = original_width / original_height
150
+ width = round((self.target_size * self.target_size * aspect_ratio) ** 0.5)
151
+ height = round((self.target_size * self.target_size / aspect_ratio) ** 0.5)
152
+
153
+ multiple_of = self.vae_scale_factor * 2
154
+ width = width // multiple_of * multiple_of
155
+ height = height // multiple_of * multiple_of
156
+
157
+ source_image_resized = source_image.resize((width, height), resample=Image.LANCZOS)
158
+
159
+ return {
160
+ "image": source_image_resized,
161
+ "prompt": prompt_with_breakflag,
162
+ "edit_instance_single": sample_prompts['edit_instance_single'],
163
+ "bboxes": instance_bboxes,
164
+ "masks": instance_masks,
165
+ "sample_id": sample_id,
166
+ "original_size": [original_width, original_height],
167
+ }
168
+
169
+
170
+ def collate_fn(batch):
171
+ return batch
172
+
173
+
174
+ def get_lomoe_mobius_dataloader(root_dir=None, batch_size=1, shuffle=False, num_workers=0, **kwargs):
175
+ dataset = LoMOEMobiusDataset(root_dir=root_dir, **kwargs)
176
+ return DataLoader(
177
+ dataset,
178
+ batch_size=batch_size,
179
+ shuffle=shuffle,
180
+ num_workers=num_workers,
181
+ collate_fn=collate_fn,
182
+ )
mice_dataset.py ADDED
@@ -0,0 +1,114 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+ import re
3
+ import numpy as np
4
+ import torch
5
+ from pathlib import Path
6
+ from PIL import Image
7
+ from torch.utils.data import Dataset, DataLoader
8
+
9
+ def parse_quoted_strings(line: str) -> list[str]:
10
+ return re.findall(r'"([^"]*)"', line)
11
+
12
+ def load_mask(mask_path: Path) -> torch.Tensor:
13
+ if not mask_path.exists():
14
+ raise FileNotFoundError(f"Mask path {mask_path} does not exist.")
15
+ mask = torch.from_numpy(np.array(Image.open(mask_path).convert('L')) > 127).float()
16
+ return mask
17
+
18
+ def get_bbox_from_mask(mask_path: Path) -> list[float]:
19
+ if not mask_path.exists():
20
+ raise FileNotFoundError(f"Mask path {mask_path} does not exist.")
21
+ mask = Image.open(mask_path).convert('L')
22
+ mask_np = np.array(mask)
23
+ y_coords, x_coords = np.where(mask_np > 127)
24
+ if len(x_coords) == 0:
25
+ raise ValueError(f"Mask {mask_path} is empty.")
26
+ x1, x2 = x_coords.min(), x_coords.max()
27
+ y1, y2 = y_coords.min(), y_coords.max()
28
+ h, w = mask_np.shape
29
+ return [float(x1) / w, float(y1) / h, float(x2) / w, float(y2) / h]
30
+
31
+
32
+ class MiceBenchDataset(Dataset):
33
+ def __init__(self, root_dir='../mice_bench', target_size=1024, vae_scale_factor=8):
34
+ self.root_dir = Path(root_dir)
35
+ self.target_size = target_size
36
+ self.vae_scale_factor = vae_scale_factor
37
+
38
+ config_path = self.root_dir / 'LoMOE.json'
39
+ with open(config_path, 'r', encoding='utf-8') as f:
40
+ self.lomoe_config = json.load(f)
41
+
42
+ self.sorted_ids = sorted(self.lomoe_config.keys(), key=lambda x: int(x))
43
+
44
+ def __len__(self):
45
+ return len(self.sorted_ids)
46
+
47
+ def __getitem__(self, idx):
48
+ sample_id = self.sorted_ids[idx]
49
+ sample_data = self.lomoe_config[sample_id]
50
+
51
+ image_path = self.root_dir / sample_data['image_path']
52
+ if not image_path.exists():
53
+ raise FileNotFoundError(f"Image path {image_path} does not exist.")
54
+
55
+ source_image = Image.open(image_path).convert('RGB')
56
+
57
+ mask_paths = parse_quoted_strings(sample_data.get('mask_path', ""))
58
+
59
+ instance_bboxes = []
60
+ for mask_p in mask_paths:
61
+ bbox = get_bbox_from_mask(self.root_dir / mask_p)
62
+ instance_bboxes.append(bbox)
63
+
64
+ instance_masks = []
65
+ for mask_p in mask_paths:
66
+ mask = load_mask(self.root_dir / mask_p)
67
+ instance_masks.append(mask)
68
+
69
+ text_sources = parse_quoted_strings(sample_data.get('source_prompt', ""))
70
+ text_targets = parse_quoted_strings(sample_data.get('fg_prompt', ""))
71
+
72
+ global_prompt = " "
73
+ prompts = [global_prompt]
74
+ for src, tgt in zip(text_sources, text_targets):
75
+ prompts.append(f'Replace the {src} with {tgt}')
76
+
77
+ prompt_with_breakflag = '$BREAKFLAG$'.join(prompts)
78
+
79
+ original_width, original_height = source_image.size
80
+ aspect_ratio = original_width / original_height
81
+ width = round((self.target_size * self.target_size * aspect_ratio) ** 0.5)
82
+ height = round((self.target_size * self.target_size / aspect_ratio) ** 0.5)
83
+
84
+ multiple_of = self.vae_scale_factor * 2
85
+ width = width // multiple_of * multiple_of
86
+ height = height // multiple_of * multiple_of
87
+
88
+ source_image_resized = source_image.resize((width, height), resample=Image.LANCZOS)
89
+
90
+ return {
91
+ "image": source_image_resized,
92
+ "prompt": prompt_with_breakflag,
93
+ "sources": text_sources,
94
+ "targets": text_targets,
95
+ "bboxes": instance_bboxes,
96
+ "masks": instance_masks,
97
+ "sample_id": sample_id,
98
+ "original_size": [original_width, original_height],
99
+ 'multi_turn_enhanced': sample_data.get('edit_inst_multi', ''),
100
+ 'edit_instance_single': sample_data['edit_inst_single'],
101
+ }
102
+
103
+ def collate_fn(batch):
104
+ return batch
105
+
106
+ def get_mice_dataloader(root_dir='../mice_bench', batch_size=1, shuffle=False, num_workers=0, **kwargs):
107
+ dataset = MiceBenchDataset(root_dir=root_dir, **kwargs)
108
+ return DataLoader(
109
+ dataset,
110
+ batch_size=batch_size,
111
+ shuffle=shuffle,
112
+ num_workers=num_workers,
113
+ collate_fn=collate_fn
114
+ )
mice_dataset_mobius.py ADDED
@@ -0,0 +1,125 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+ import re
3
+ import numpy as np
4
+ import torch
5
+ from pathlib import Path
6
+ from PIL import Image
7
+ from torch.utils.data import Dataset, DataLoader
8
+
9
+ def parse_quoted_strings(line: str) -> list[str]:
10
+ if not line:
11
+ return []
12
+ return re.findall(r'"([^"]*)"', line)
13
+
14
+ def load_mask(mask_path: Path) -> torch.Tensor:
15
+ if not mask_path.exists():
16
+ print(f"Warning: Mask path {mask_path} does not exist. Using empty mask.")
17
+ return torch.zeros((512, 512))
18
+ mask = torch.from_numpy(np.array(Image.open(mask_path).convert('L')) > 127).float()
19
+ return mask
20
+
21
+ def get_bbox_from_mask(mask_path: Path) -> list[float]:
22
+ if not mask_path.exists():
23
+ print(f"Warning: Mask path {mask_path} does not exist. Using full image bbox.")
24
+ return [0.0, 0.0, 1.0, 1.0]
25
+ mask = Image.open(mask_path).convert('L')
26
+ mask_np = np.array(mask)
27
+ y_coords, x_coords = np.where(mask_np > 127)
28
+ if len(x_coords) == 0:
29
+ print(f"Warning: Mask {mask_path} is empty. Using full image bbox.")
30
+ return [0.0, 0.0, 1.0, 1.0]
31
+ x1, x2 = x_coords.min(), x_coords.max()
32
+ y1, y2 = y_coords.min(), y_coords.max()
33
+ h, w = mask_np.shape
34
+ return [float(x1) / w, float(y1) / h, float(x2) / w, float(y2) / h]
35
+
36
+
37
+ class MiceBenchMobiusDataset(Dataset):
38
+ def __init__(self, root_dir='/mnt/ssd1/mice_bench_mobius', target_size=1024, vae_scale_factor=8):
39
+ self.root_dir = Path(root_dir)
40
+ self.target_size = target_size
41
+ self.vae_scale_factor = vae_scale_factor
42
+
43
+ config_path = self.root_dir / 'LoMOE_mobius.json'
44
+ with open(config_path, 'r', encoding='utf-8') as f:
45
+ self.lomoe_config = json.load(f)
46
+
47
+ self.sorted_ids = sorted(self.lomoe_config.keys(), key=lambda x: int(x))
48
+
49
+ def __len__(self):
50
+ return len(self.sorted_ids)
51
+
52
+ def __getitem__(self, idx):
53
+ sample_id = self.sorted_ids[idx]
54
+ sample_data = self.lomoe_config[sample_id]
55
+
56
+ image_path = self.root_dir / sample_data['image_path']
57
+ if not image_path.exists():
58
+ if str(image_path).endswith('.jpg'):
59
+ image_path = Path(str(image_path)[:-4] + '.png')
60
+ elif str(image_path).endswith('.png'):
61
+ image_path = Path(str(image_path)[:-4] + '.jpg')
62
+
63
+ if not image_path.exists():
64
+ raise FileNotFoundError(f"Image path {image_path} does not exist.")
65
+
66
+ source_image = Image.open(image_path).convert('RGB')
67
+
68
+ mask_paths = parse_quoted_strings(sample_data.get('mask_path', ""))
69
+
70
+ instance_bboxes = []
71
+ for mask_p in mask_paths:
72
+ bbox = get_bbox_from_mask(self.root_dir / mask_p)
73
+ instance_bboxes.append(bbox)
74
+
75
+ instance_masks = []
76
+ for mask_p in mask_paths:
77
+ mask = load_mask(self.root_dir / mask_p)
78
+ instance_masks.append(mask)
79
+
80
+ text_sources = parse_quoted_strings(sample_data.get('source_prompt', ""))
81
+ text_targets = parse_quoted_strings(sample_data.get('fg_prompt', ""))
82
+
83
+ global_prompt = " "
84
+ prompts = [global_prompt]
85
+ for src, tgt in zip(text_sources, text_targets):
86
+ prompts.append(f'Replace the {src} with {tgt}')
87
+
88
+ prompt_with_breakflag = '$BREAKFLAG$'.join(prompts)
89
+
90
+ original_width, original_height = source_image.size
91
+ aspect_ratio = original_width / original_height
92
+ width = round((self.target_size * self.target_size * aspect_ratio) ** 0.5)
93
+ height = round((self.target_size * self.target_size / aspect_ratio) ** 0.5)
94
+
95
+ multiple_of = self.vae_scale_factor * 2
96
+ width = width // multiple_of * multiple_of
97
+ height = height // multiple_of * multiple_of
98
+
99
+ source_image_resized = source_image.resize((width, height), resample=Image.LANCZOS)
100
+
101
+ return {
102
+ "image": source_image_resized,
103
+ "prompt": prompt_with_breakflag,
104
+ "sources": text_sources,
105
+ "targets": text_targets,
106
+ "bboxes": instance_bboxes,
107
+ "masks": instance_masks,
108
+ "sample_id": sample_id,
109
+ "original_size": [original_width, original_height],
110
+ 'multi_turn_enhanced': sample_data.get('edit_inst_multi', ''),
111
+ 'edit_instance_single': sample_data.get('edit_inst_single', ''),
112
+ }
113
+
114
+ def collate_fn(batch):
115
+ return batch
116
+
117
+ def get_mice_mobius_dataloader(root_dir='/mnt/ssd1/mice_bench_mobius', batch_size=1, shuffle=False, num_workers=0, **kwargs):
118
+ dataset = MiceBenchMobiusDataset(root_dir=root_dir, **kwargs)
119
+ return DataLoader(
120
+ dataset,
121
+ batch_size=batch_size,
122
+ shuffle=shuffle,
123
+ num_workers=num_workers,
124
+ collate_fn=collate_fn
125
+ )