yiren98 commited on
Commit
cc6558b
·
1 Parent(s): 33b3c45

update app.py

Browse files
.gitignore ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ output/
2
+ results/
3
+ datasets/
4
+ wandb/
5
+ scripts/
6
+ __pycache__/
7
+ default_config.yaml
8
+ getDataset.py
9
+ train.py
README.md CHANGED
@@ -1,13 +1,12 @@
1
  ---
2
  title: OmniConsistency
3
- emoji: 🐨
4
- colorFrom: blue
5
- colorTo: gray
6
  sdk: gradio
7
  sdk_version: 5.31.0
8
  app_file: app.py
9
  pinned: false
10
- license: mit
11
  short_description: Generate styled image from reference image and external LoRA
12
  ---
13
 
 
1
  ---
2
  title: OmniConsistency
3
+ emoji: 🚀
4
+ colorFrom: gray
5
+ colorTo: pink
6
  sdk: gradio
7
  sdk_version: 5.31.0
8
  app_file: app.py
9
  pinned: false
 
10
  short_description: Generate styled image from reference image and external LoRA
11
  ---
12
 
app.py ADDED
@@ -0,0 +1,147 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import spaces
2
+ import time
3
+ import torch
4
+ import gradio as gr
5
+ from PIL import Image
6
+ from huggingface_hub import hf_hub_download
7
+ from src_inference.pipeline import FluxPipeline
8
+ from src_inference.lora_helper import set_single_lora
9
+ import random
10
+
11
+ base_path = "black-forest-labs/FLUX.1-dev"
12
+
13
+ # Download OmniConsistency LoRA using hf_hub_download
14
+ omni_consistency_path = hf_hub_download(repo_id="showlab/OmniConsistency",
15
+ filename="OmniConsistency.safetensors",
16
+ local_dir="./Model")
17
+
18
+ # Initialize the pipeline with the model
19
+ pipe = FluxPipeline.from_pretrained(base_path, torch_dtype=torch.bfloat16).to("cuda")
20
+
21
+ # Set LoRA weights
22
+ set_single_lora(pipe.transformer, omni_consistency_path, lora_weights=[1], cond_size=512)
23
+
24
+ # Function to clear cache
25
+ def clear_cache(transformer):
26
+ for name, attn_processor in transformer.attn_processors.items():
27
+ attn_processor.bank_kv.clear()
28
+
29
+ # Function to download all LoRAs in advance
30
+ def download_all_loras():
31
+ lora_names = [
32
+ "3D_Chibi", "American_Cartoon", "Chinese_Ink",
33
+ "Clay_Toy", "Fabric", "Ghibli", "Irasutoya",
34
+ "Jojo", "LEGO", "Line", "Macaron",
35
+ "Oil_Painting", "Origami", "Paper_Cutting",
36
+ "Picasso", "Pixel", "Poly", "Pop_Art",
37
+ "Rick_Morty", "Snoopy", "Van_Gogh", "Vector"
38
+ ]
39
+ for lora_name in lora_names:
40
+ hf_hub_download(repo_id="showlab/OmniConsistency",
41
+ filename=f"LoRAs/{lora_name}_rank128_bf16.safetensors",
42
+ local_dir="./LoRAs")
43
+
44
+ # Download all LoRAs in advance before the interface is launched
45
+ download_all_loras()
46
+
47
+ # Main function to generate the image
48
+ @spaces.GPU()
49
+ def generate_image(lora_name, prompt, uploaded_image, width, height, guidance_scale, num_inference_steps, seed):
50
+ # Download specific LoRA based on selection (use local directory as LoRAs are already downloaded)
51
+ lora_path = f"./LoRAs/LoRAs/{lora_name}_rank128_bf16.safetensors"
52
+
53
+ # Load the specific LoRA weights
54
+ pipe.unload_lora_weights()
55
+ pipe.load_lora_weights("./LoRAs/LoRAs", weight_name=f"{lora_name}_rank128_bf16.safetensors")
56
+
57
+ # Prepare input image
58
+ spatial_image = [uploaded_image.convert("RGB")]
59
+ subject_images = []
60
+
61
+ start_time = time.time()
62
+
63
+ # Generate the image
64
+ image = pipe(
65
+ prompt,
66
+ height=(int(height) // 8) * 8,
67
+ width=(int(width) // 8) * 8,
68
+ guidance_scale=guidance_scale,
69
+ num_inference_steps=num_inference_steps,
70
+ max_sequence_length=512,
71
+ generator=torch.Generator("cpu").manual_seed(seed),
72
+ spatial_images=spatial_image,
73
+ subject_images=subject_images,
74
+ cond_size=512,
75
+ ).images[0]
76
+
77
+ end_time = time.time()
78
+ elapsed_time = end_time - start_time
79
+ print(f"code running time: {elapsed_time} s")
80
+
81
+ # Clear cache after generation
82
+ clear_cache(pipe.transformer)
83
+
84
+ return image
85
+
86
+ # Example data
87
+ examples = [
88
+ ["3D_Chibi", "3D Chibi style", Image.open("./test_imgs/00.png"), 680, 1024, 3.5, 24, 42],
89
+ ["Origami", "Origami style", Image.open("./test_imgs/01.png"), 560, 1024, 3.5, 24, 42],
90
+ ["American_Cartoon", "American Cartoon style", Image.open("./test_imgs/02.png"), 568, 1024, 3.5, 24, 42],
91
+ ["Origami", "Origami style", Image.open("./test_imgs/03.png"), 768, 672, 3.5, 24, 42],
92
+ ["Paper_Cutting", "Paper Cutting style", Image.open("./test_imgs/04.png"), 696, 1024, 3.5, 24, 42]
93
+ ]
94
+
95
+ # Gradio interface setup
96
+ def create_gradio_interface():
97
+ lora_names = [
98
+ "3D_Chibi", "American_Cartoon", "Chinese_Ink",
99
+ "Clay_Toy", "Fabric", "Ghibli", "Irasutoya",
100
+ "Jojo", "LEGO", "Line", "Macaron",
101
+ "Oil_Painting", "Origami", "Paper_Cutting",
102
+ "Picasso", "Pixel", "Poly", "Pop_Art",
103
+ "Rick_Morty", "Snoopy", "Van_Gogh", "Vector"
104
+ ]
105
+
106
+ with gr.Blocks() as demo:
107
+ gr.Markdown("# OmniConsistency LoRA Image Generation")
108
+ gr.Markdown("Select a LoRA, enter a prompt, and upload an image to generate a new image with OmniConsistency.")
109
+ with gr.Row():
110
+ with gr.Column(scale=1):
111
+ lora_dropdown = gr.Dropdown(lora_names, label="Select LoRA")
112
+ prompt_box = gr.Textbox(label="Prompt", placeholder="Enter a prompt...")
113
+ image_input = gr.Image(type="pil", label="Upload Image")
114
+ with gr.Column(scale=1):
115
+ width_box = gr.Textbox(label="Width", value="1024")
116
+ height_box = gr.Textbox(label="Height", value="1024")
117
+ guidance_slider = gr.Slider(minimum=0.1, maximum=20, value=3.5, step=0.1, label="Guidance Scale")
118
+ steps_slider = gr.Slider(minimum=1, maximum=50, value=25, step=1, label="Inference Steps")
119
+ seed_slider = gr.Slider(minimum=1, maximum=10000000000, value=42, step=1, label="Seed")
120
+ generate_button = gr.Button("Generate")
121
+ output_image = gr.Image(type="pil", label="Generated Image")
122
+ # Add examples for Generation
123
+ gr.Examples(
124
+ examples=examples,
125
+ inputs=[lora_dropdown, prompt_box, image_input, height_box, width_box, guidance_slider, steps_slider, seed_slider],
126
+ outputs=output_image,
127
+ fn=generate_image,
128
+ cache_examples=False,
129
+ label="Examples"
130
+ )
131
+
132
+ generate_button.click(
133
+ fn=generate_image,
134
+ inputs=[
135
+ lora_dropdown, prompt_box, image_input,
136
+ width_box, height_box, guidance_slider,
137
+ steps_slider, seed_slider
138
+ ],
139
+ outputs=output_image
140
+ )
141
+
142
+ return demo
143
+
144
+
145
+ # Launch the Gradio interface
146
+ interface = create_gradio_interface()
147
+ interface.launch()
requirements.txt ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ --extra-index-url https://download.pytorch.org/whl/cu124
2
+ torch
3
+ torchvision
4
+ torchaudio==2.3.1
5
+ diffusers==0.32.2
6
+ easydict==1.13
7
+ einops==0.8.1
8
+ peft==0.14.0
9
+ pillow==11.0.0
10
+ protobuf==5.29.3
11
+ requests==2.32.3
12
+ safetensors==0.5.2
13
+ sentencepiece==0.2.0
14
+ spaces==0.34.1
15
+ transformers==4.49.0
16
+ datasets
17
+ wandb
src_inference/__init__.py ADDED
File without changes
src_inference/layers_cache.py ADDED
@@ -0,0 +1,366 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import inspect
2
+ import math
3
+ from typing import Callable, List, Optional, Tuple, Union
4
+ from einops import rearrange
5
+ import torch
6
+ from torch import nn
7
+ import torch.nn.functional as F
8
+ from torch import Tensor
9
+ from diffusers.models.attention_processor import Attention
10
+
11
+ class LoRALinearLayer(nn.Module):
12
+ def __init__(
13
+ self,
14
+ in_features: int,
15
+ out_features: int,
16
+ rank: int = 4,
17
+ network_alpha: Optional[float] = None,
18
+ device: Optional[Union[torch.device, str]] = None,
19
+ dtype: Optional[torch.dtype] = None,
20
+ cond_width=512,
21
+ cond_height=512,
22
+ number=0,
23
+ n_loras=1
24
+ ):
25
+ super().__init__()
26
+ self.down = nn.Linear(in_features, rank, bias=False, device=device, dtype=dtype)
27
+ self.up = nn.Linear(rank, out_features, bias=False, device=device, dtype=dtype)
28
+ # This value has the same meaning as the `--network_alpha` option in the kohya-ss trainer script.
29
+ # See https://github.com/darkstorm2150/sd-scripts/blob/main/docs/train_network_README-en.md#execute-learning
30
+ self.network_alpha = network_alpha
31
+ self.rank = rank
32
+ self.out_features = out_features
33
+ self.in_features = in_features
34
+
35
+ nn.init.normal_(self.down.weight, std=1 / rank)
36
+ nn.init.zeros_(self.up.weight)
37
+
38
+ self.cond_height = cond_height
39
+ self.cond_width = cond_width
40
+ self.number = number
41
+ self.n_loras = n_loras
42
+
43
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
44
+ orig_dtype = hidden_states.dtype
45
+ dtype = self.down.weight.dtype
46
+
47
+ ####
48
+ batch_size = hidden_states.shape[0]
49
+ cond_size = self.cond_width // 8 * self.cond_height // 8 * 16 // 64
50
+ block_size = hidden_states.shape[1] - cond_size * self.n_loras
51
+ shape = (batch_size, hidden_states.shape[1], 3072)
52
+ mask = torch.ones(shape, device=hidden_states.device, dtype=dtype)
53
+ mask[:, :block_size+self.number*cond_size, :] = 0
54
+ mask[:, block_size+(self.number+1)*cond_size:, :] = 0
55
+ hidden_states = mask * hidden_states
56
+ ####
57
+
58
+ down_hidden_states = self.down(hidden_states.to(dtype))
59
+ up_hidden_states = self.up(down_hidden_states)
60
+
61
+ if self.network_alpha is not None:
62
+ up_hidden_states *= self.network_alpha / self.rank
63
+
64
+ return up_hidden_states.to(orig_dtype)
65
+
66
+
67
+ class MultiSingleStreamBlockLoraProcessor(nn.Module):
68
+ def __init__(self, dim: int, ranks=[], lora_weights=[], network_alphas=[], device=None, dtype=None, cond_width=512, cond_height=512, n_loras=1):
69
+ super().__init__()
70
+ # Initialize a list to store the LoRA layers
71
+ self.n_loras = n_loras
72
+ self.cond_width = cond_width
73
+ self.cond_height = cond_height
74
+
75
+ self.q_loras = nn.ModuleList([
76
+ LoRALinearLayer(dim, dim, ranks[i],network_alphas[i], device=device, dtype=dtype, cond_width=cond_width, cond_height=cond_height, number=i, n_loras=n_loras)
77
+ for i in range(n_loras)
78
+ ])
79
+ self.k_loras = nn.ModuleList([
80
+ LoRALinearLayer(dim, dim, ranks[i],network_alphas[i], device=device, dtype=dtype, cond_width=cond_width, cond_height=cond_height, number=i, n_loras=n_loras)
81
+ for i in range(n_loras)
82
+ ])
83
+ self.v_loras = nn.ModuleList([
84
+ LoRALinearLayer(dim, dim, ranks[i],network_alphas[i], device=device, dtype=dtype, cond_width=cond_width, cond_height=cond_height, number=i, n_loras=n_loras)
85
+ for i in range(n_loras)
86
+ ])
87
+ self.lora_weights = lora_weights
88
+ self.bank_attn = None
89
+ self.bank_kv = []
90
+
91
+
92
+ def __call__(self,
93
+ attn: Attention,
94
+ hidden_states: torch.FloatTensor,
95
+ encoder_hidden_states: torch.FloatTensor = None,
96
+ attention_mask: Optional[torch.FloatTensor] = None,
97
+ image_rotary_emb: Optional[torch.Tensor] = None,
98
+ use_cond = False,
99
+ image_emb: torch.FloatTensor = None
100
+ ) -> torch.FloatTensor:
101
+
102
+ scaled_cond_size = self.cond_width // 8 * self.cond_height // 8 * 16 // 64
103
+ batch_size, _, _ = hidden_states.shape if encoder_hidden_states is None else encoder_hidden_states.shape
104
+ scaled_seq_len = hidden_states.shape[1]
105
+ block_size = scaled_seq_len - scaled_cond_size * self.n_loras
106
+
107
+ if len(self.bank_kv)== 0:
108
+ cache = True
109
+ else:
110
+ cache = False
111
+
112
+ if cache:
113
+ query = attn.to_q(hidden_states)
114
+ key = attn.to_k(hidden_states)
115
+ value = attn.to_v(hidden_states)
116
+ for i in range(self.n_loras):
117
+ query = query + self.lora_weights[i] * self.q_loras[i](hidden_states)
118
+ key = key + self.lora_weights[i] * self.k_loras[i](hidden_states)
119
+ value = value + self.lora_weights[i] * self.v_loras[i](hidden_states)
120
+
121
+ inner_dim = key.shape[-1]
122
+ head_dim = inner_dim // attn.heads
123
+
124
+ query = query.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
125
+ key = key.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
126
+ value = value.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
127
+
128
+
129
+ self.bank_kv.append(key[:, :, block_size:, :])
130
+ self.bank_kv.append(value[:, :, block_size:, :])
131
+
132
+ if attn.norm_q is not None:
133
+ query = attn.norm_q(query)
134
+ if attn.norm_k is not None:
135
+ key = attn.norm_k(key)
136
+
137
+ if image_rotary_emb is not None:
138
+ from diffusers.models.embeddings import apply_rotary_emb
139
+ query = apply_rotary_emb(query, image_rotary_emb)
140
+ key = apply_rotary_emb(key, image_rotary_emb)
141
+
142
+ num_cond_blocks = self.n_loras
143
+ mask = torch.ones((scaled_seq_len, scaled_seq_len), device=hidden_states.device)
144
+ mask[ :block_size, :] = 0 # First block_size row
145
+ for i in range(num_cond_blocks):
146
+ start = i * scaled_cond_size + block_size
147
+ end = (i + 1) * scaled_cond_size + block_size
148
+ mask[start:end, start:end] = 0 # Diagonal blocks
149
+ mask = mask * -1e20
150
+ mask = mask.to(query.dtype)
151
+
152
+ hidden_states = F.scaled_dot_product_attention(query, key, value, dropout_p=0.0, is_causal=False, attn_mask=mask)
153
+ else:
154
+ query = attn.to_q(hidden_states)
155
+ key = attn.to_k(hidden_states)
156
+ value = attn.to_v(hidden_states)
157
+
158
+ inner_dim = query.shape[-1]
159
+ head_dim = inner_dim // attn.heads
160
+
161
+ query = query.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
162
+ key = key.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
163
+ value = value.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
164
+
165
+ zero_pad = torch.zeros_like(self.bank_kv[0], dtype=query.dtype, device=query.device)
166
+
167
+
168
+ key = torch.concat([key[:, :, :scaled_seq_len, :], self.bank_kv[0]], dim=-2)
169
+ value = torch.concat([value[:, :, :scaled_seq_len, :], self.bank_kv[1]], dim=-2)
170
+
171
+ if attn.norm_q is not None:
172
+ query = attn.norm_q(query)
173
+ if attn.norm_k is not None:
174
+ key = attn.norm_k(key)
175
+
176
+ query = torch.concat([query[:, :, :scaled_seq_len, :], zero_pad], dim=-2)
177
+
178
+ if image_rotary_emb is not None:
179
+ from diffusers.models.embeddings import apply_rotary_emb
180
+ query = apply_rotary_emb(query, image_rotary_emb)
181
+ key = apply_rotary_emb(key, image_rotary_emb)
182
+
183
+ query = query[:, :, :scaled_seq_len, :]
184
+
185
+ hidden_states = F.scaled_dot_product_attention(query, key, value, dropout_p=0.0, is_causal=False, attn_mask=None)
186
+
187
+ hidden_states = hidden_states.transpose(1, 2).reshape(batch_size, -1, attn.heads * head_dim)
188
+ hidden_states = hidden_states.to(query.dtype)
189
+
190
+ hidden_states = hidden_states[:, : scaled_seq_len,:]
191
+
192
+ return hidden_states
193
+
194
+
195
+ class MultiDoubleStreamBlockLoraProcessor(nn.Module):
196
+ def __init__(self, dim: int, ranks=[], lora_weights=[], network_alphas=[], device=None, dtype=None, cond_width=512, cond_height=512, n_loras=1):
197
+ super().__init__()
198
+
199
+ # Initialize a list to store the LoRA layers
200
+ self.n_loras = n_loras
201
+ self.cond_width = cond_width
202
+ self.cond_height = cond_height
203
+ self.q_loras = nn.ModuleList([
204
+ LoRALinearLayer(dim, dim, ranks[i],network_alphas[i], device=device, dtype=dtype, cond_width=cond_width, cond_height=cond_height, number=i, n_loras=n_loras)
205
+ for i in range(n_loras)
206
+ ])
207
+ self.k_loras = nn.ModuleList([
208
+ LoRALinearLayer(dim, dim, ranks[i],network_alphas[i], device=device, dtype=dtype, cond_width=cond_width, cond_height=cond_height, number=i, n_loras=n_loras)
209
+ for i in range(n_loras)
210
+ ])
211
+ self.v_loras = nn.ModuleList([
212
+ LoRALinearLayer(dim, dim, ranks[i],network_alphas[i], device=device, dtype=dtype, cond_width=cond_width, cond_height=cond_height, number=i, n_loras=n_loras)
213
+ for i in range(n_loras)
214
+ ])
215
+ self.proj_loras = nn.ModuleList([
216
+ LoRALinearLayer(dim, dim, ranks[i],network_alphas[i], device=device, dtype=dtype, cond_width=cond_width, cond_height=cond_height, number=i, n_loras=n_loras)
217
+ for i in range(n_loras)
218
+ ])
219
+ self.lora_weights = lora_weights
220
+ self.bank_attn = None
221
+ self.bank_kv = []
222
+
223
+
224
+ def __call__(self,
225
+ attn: Attention,
226
+ hidden_states: torch.FloatTensor,
227
+ encoder_hidden_states: torch.FloatTensor = None,
228
+ attention_mask: Optional[torch.FloatTensor] = None,
229
+ image_rotary_emb: Optional[torch.Tensor] = None,
230
+ use_cond=False,
231
+ image_emb: torch.FloatTensor = None
232
+ ) -> torch.FloatTensor:
233
+
234
+ scaled_cond_size = self.cond_width // 8 * self.cond_height // 8 * 16 // 64
235
+ batch_size, _, _ = hidden_states.shape if encoder_hidden_states is None else encoder_hidden_states.shape
236
+ block_size = hidden_states.shape[1]
237
+ scaled_seq_len = encoder_hidden_states.shape[1] + hidden_states.shape[1]
238
+ scaled_block_size = scaled_seq_len
239
+
240
+ # `context` projections.
241
+ inner_dim = 3072
242
+ head_dim = inner_dim // attn.heads
243
+ encoder_hidden_states_query_proj = attn.add_q_proj(encoder_hidden_states)
244
+ encoder_hidden_states_key_proj = attn.add_k_proj(encoder_hidden_states)
245
+ encoder_hidden_states_value_proj = attn.add_v_proj(encoder_hidden_states)
246
+
247
+ encoder_hidden_states_query_proj = encoder_hidden_states_query_proj.view(
248
+ batch_size, -1, attn.heads, head_dim
249
+ ).transpose(1, 2)
250
+ encoder_hidden_states_key_proj = encoder_hidden_states_key_proj.view(
251
+ batch_size, -1, attn.heads, head_dim
252
+ ).transpose(1, 2)
253
+ encoder_hidden_states_value_proj = encoder_hidden_states_value_proj.view(
254
+ batch_size, -1, attn.heads, head_dim
255
+ ).transpose(1, 2)
256
+
257
+ if attn.norm_added_q is not None:
258
+ encoder_hidden_states_query_proj = attn.norm_added_q(encoder_hidden_states_query_proj)
259
+ if attn.norm_added_k is not None:
260
+ encoder_hidden_states_key_proj = attn.norm_added_k(encoder_hidden_states_key_proj)
261
+
262
+ if len(self.bank_kv)== 0:
263
+ cache = True
264
+ else:
265
+ cache = False
266
+
267
+ if cache:
268
+
269
+ query = attn.to_q(hidden_states)
270
+ key = attn.to_k(hidden_states)
271
+ value = attn.to_v(hidden_states)
272
+ for i in range(self.n_loras):
273
+ query = query + self.lora_weights[i] * self.q_loras[i](hidden_states)
274
+ key = key + self.lora_weights[i] * self.k_loras[i](hidden_states)
275
+ value = value + self.lora_weights[i] * self.v_loras[i](hidden_states)
276
+
277
+ inner_dim = key.shape[-1]
278
+ head_dim = inner_dim // attn.heads
279
+ query = query.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
280
+ key = key.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
281
+ value = value.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
282
+
283
+
284
+ self.bank_kv.append(key)
285
+ self.bank_kv.append(value)
286
+
287
+ if attn.norm_q is not None:
288
+ query = attn.norm_q(query)
289
+ if attn.norm_k is not None:
290
+ key = attn.norm_k(key)
291
+
292
+ # attention
293
+ query = torch.cat([encoder_hidden_states_query_proj, query], dim=2)
294
+ key = torch.cat([encoder_hidden_states_key_proj, key], dim=2)
295
+ value = torch.cat([encoder_hidden_states_value_proj, value], dim=2)
296
+
297
+ if image_rotary_emb is not None:
298
+ from diffusers.models.embeddings import apply_rotary_emb
299
+ query = apply_rotary_emb(query, image_rotary_emb)
300
+ key = apply_rotary_emb(key, image_rotary_emb)
301
+
302
+ num_cond_blocks = self.n_loras
303
+ mask = torch.ones((scaled_seq_len, scaled_seq_len), device=hidden_states.device)
304
+ mask[ :scaled_block_size-block_size, :] = 0 # First block_size row
305
+ for i in range(num_cond_blocks):
306
+ start = i * scaled_cond_size + scaled_block_size-block_size
307
+ end = (i + 1) * scaled_cond_size + scaled_block_size-block_size
308
+ mask[start:end, start:end] = 0 # Diagonal blocks
309
+ mask = mask * -1e20
310
+ mask = mask.to(query.dtype)
311
+
312
+ hidden_states = F.scaled_dot_product_attention(query, key, value, dropout_p=0.0, is_causal=False, attn_mask=mask)
313
+
314
+ else:
315
+ query = attn.to_q(hidden_states)
316
+ key = attn.to_k(hidden_states)
317
+ value = attn.to_v(hidden_states)
318
+
319
+ inner_dim = query.shape[-1]
320
+ head_dim = inner_dim // attn.heads
321
+
322
+ query = query.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
323
+ key = key.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
324
+ value = value.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
325
+
326
+ zero_pad = torch.zeros_like(self.bank_kv[0], dtype=query.dtype, device=query.device)
327
+
328
+ key = torch.concat([key[:, :, :block_size, :], self.bank_kv[0]], dim=-2)
329
+ value = torch.concat([value[:, :, :block_size, :], self.bank_kv[1]], dim=-2)
330
+
331
+ if attn.norm_q is not None:
332
+ query = attn.norm_q(query)
333
+ if attn.norm_k is not None:
334
+ key = attn.norm_k(key)
335
+
336
+ query = torch.concat([query[:, :, :block_size, :], zero_pad], dim=-2)
337
+
338
+ # attention
339
+ query = torch.cat([encoder_hidden_states_query_proj, query], dim=2)
340
+ key = torch.cat([encoder_hidden_states_key_proj, key], dim=2)
341
+ value = torch.cat([encoder_hidden_states_value_proj, value], dim=2)
342
+
343
+ if image_rotary_emb is not None:
344
+ from diffusers.models.embeddings import apply_rotary_emb
345
+ query = apply_rotary_emb(query, image_rotary_emb)
346
+ key = apply_rotary_emb(key, image_rotary_emb)
347
+
348
+ query = query[:, :, :scaled_block_size, :]
349
+
350
+ hidden_states = F.scaled_dot_product_attention(query, key, value, dropout_p=0.0, is_causal=False, attn_mask=None)
351
+
352
+ hidden_states = hidden_states.transpose(1, 2).reshape(batch_size, -1, attn.heads * head_dim)
353
+ hidden_states = hidden_states.to(query.dtype)
354
+
355
+ encoder_hidden_states, hidden_states = (
356
+ hidden_states[:, : encoder_hidden_states.shape[1]],
357
+ hidden_states[:, encoder_hidden_states.shape[1] :],
358
+ )
359
+
360
+ # Linear projection (with LoRA weight applied to each proj layer)
361
+ hidden_states = attn.to_out[0](hidden_states)
362
+ encoder_hidden_states = attn.to_add_out(encoder_hidden_states)
363
+
364
+ hidden_states = hidden_states[:, :block_size,:]
365
+
366
+ return hidden_states, encoder_hidden_states
src_inference/lora_helper.py ADDED
@@ -0,0 +1,194 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from diffusers.models.attention_processor import FluxAttnProcessor2_0
2
+ from safetensors import safe_open
3
+ import re
4
+ import torch
5
+ from .layers_cache import MultiDoubleStreamBlockLoraProcessor, MultiSingleStreamBlockLoraProcessor
6
+
7
+ device = "cuda"
8
+
9
+ def load_safetensors(path):
10
+ tensors = {}
11
+ with safe_open(path, framework="pt", device="cpu") as f:
12
+ for key in f.keys():
13
+ tensors[key] = f.get_tensor(key)
14
+ return tensors
15
+
16
+ def get_lora_rank(checkpoint):
17
+ for k in checkpoint.keys():
18
+ if k.endswith(".down.weight"):
19
+ return checkpoint[k].shape[0]
20
+
21
+ def load_checkpoint(local_path):
22
+ if local_path is not None:
23
+ if '.safetensors' in local_path:
24
+ print(f"Loading .safetensors checkpoint from {local_path}")
25
+ checkpoint = load_safetensors(local_path)
26
+ else:
27
+ print(f"Loading checkpoint from {local_path}")
28
+ checkpoint = torch.load(local_path, map_location='cpu')
29
+ return checkpoint
30
+
31
+ def update_model_with_lora(checkpoint, lora_weights, transformer, cond_size):
32
+ number = len(lora_weights)
33
+ ranks = [get_lora_rank(checkpoint) for _ in range(number)]
34
+ lora_attn_procs = {}
35
+ double_blocks_idx = list(range(19))
36
+ single_blocks_idx = list(range(38))
37
+ for name, attn_processor in transformer.attn_processors.items():
38
+ match = re.search(r'\.(\d+)\.', name)
39
+ if match:
40
+ layer_index = int(match.group(1))
41
+
42
+ if name.startswith("transformer_blocks") and layer_index in double_blocks_idx:
43
+
44
+ lora_state_dicts = {}
45
+ for key, value in checkpoint.items():
46
+ # Match based on the layer index in the key (assuming the key contains layer index)
47
+ if re.search(r'\.(\d+)\.', key):
48
+ checkpoint_layer_index = int(re.search(r'\.(\d+)\.', key).group(1))
49
+ if checkpoint_layer_index == layer_index and key.startswith("transformer_blocks"):
50
+ lora_state_dicts[key] = value
51
+
52
+ lora_attn_procs[name] = MultiDoubleStreamBlockLoraProcessor(
53
+ dim=3072, ranks=ranks, network_alphas=ranks, lora_weights=lora_weights, device=device, dtype=torch.bfloat16, cond_width=cond_size, cond_height=cond_size, n_loras=number
54
+ )
55
+
56
+ # Load the weights from the checkpoint dictionary into the corresponding layers
57
+ for n in range(number):
58
+ lora_attn_procs[name].q_loras[n].down.weight.data = lora_state_dicts.get(f'{name}.q_loras.{n}.down.weight', None)
59
+ lora_attn_procs[name].q_loras[n].up.weight.data = lora_state_dicts.get(f'{name}.q_loras.{n}.up.weight', None)
60
+ lora_attn_procs[name].k_loras[n].down.weight.data = lora_state_dicts.get(f'{name}.k_loras.{n}.down.weight', None)
61
+ lora_attn_procs[name].k_loras[n].up.weight.data = lora_state_dicts.get(f'{name}.k_loras.{n}.up.weight', None)
62
+ lora_attn_procs[name].v_loras[n].down.weight.data = lora_state_dicts.get(f'{name}.v_loras.{n}.down.weight', None)
63
+ lora_attn_procs[name].v_loras[n].up.weight.data = lora_state_dicts.get(f'{name}.v_loras.{n}.up.weight', None)
64
+ lora_attn_procs[name].proj_loras[n].down.weight.data = lora_state_dicts.get(f'{name}.proj_loras.{n}.down.weight', None)
65
+ lora_attn_procs[name].proj_loras[n].up.weight.data = lora_state_dicts.get(f'{name}.proj_loras.{n}.up.weight', None)
66
+ lora_attn_procs[name].to(device)
67
+
68
+ elif name.startswith("single_transformer_blocks") and layer_index in single_blocks_idx:
69
+
70
+ lora_state_dicts = {}
71
+ for key, value in checkpoint.items():
72
+ if re.search(r'\.(\d+)\.', key):
73
+ checkpoint_layer_index = int(re.search(r'\.(\d+)\.', key).group(1))
74
+ if checkpoint_layer_index == layer_index and key.startswith("single_transformer_blocks"):
75
+ lora_state_dicts[key] = value
76
+
77
+ lora_attn_procs[name] = MultiSingleStreamBlockLoraProcessor(
78
+ dim=3072, ranks=ranks, network_alphas=ranks, lora_weights=lora_weights, device=device, dtype=torch.bfloat16, cond_width=cond_size, cond_height=cond_size, n_loras=number
79
+ )
80
+ for n in range(number):
81
+ lora_attn_procs[name].q_loras[n].down.weight.data = lora_state_dicts.get(f'{name}.q_loras.{n}.down.weight', None)
82
+ lora_attn_procs[name].q_loras[n].up.weight.data = lora_state_dicts.get(f'{name}.q_loras.{n}.up.weight', None)
83
+ lora_attn_procs[name].k_loras[n].down.weight.data = lora_state_dicts.get(f'{name}.k_loras.{n}.down.weight', None)
84
+ lora_attn_procs[name].k_loras[n].up.weight.data = lora_state_dicts.get(f'{name}.k_loras.{n}.up.weight', None)
85
+ lora_attn_procs[name].v_loras[n].down.weight.data = lora_state_dicts.get(f'{name}.v_loras.{n}.down.weight', None)
86
+ lora_attn_procs[name].v_loras[n].up.weight.data = lora_state_dicts.get(f'{name}.v_loras.{n}.up.weight', None)
87
+ lora_attn_procs[name].to(device)
88
+ else:
89
+ lora_attn_procs[name] = FluxAttnProcessor2_0()
90
+
91
+ transformer.set_attn_processor(lora_attn_procs)
92
+
93
+
94
+ def update_model_with_multi_lora(checkpoints, lora_weights, transformer, cond_size):
95
+ ck_number = len(checkpoints)
96
+ cond_lora_number = [len(ls) for ls in lora_weights]
97
+ cond_number = sum(cond_lora_number)
98
+ ranks = [get_lora_rank(checkpoint) for checkpoint in checkpoints]
99
+ multi_lora_weight = []
100
+ for ls in lora_weights:
101
+ for n in ls:
102
+ multi_lora_weight.append(n)
103
+
104
+ lora_attn_procs = {}
105
+ double_blocks_idx = list(range(19))
106
+ single_blocks_idx = list(range(38))
107
+ for name, attn_processor in transformer.attn_processors.items():
108
+ match = re.search(r'\.(\d+)\.', name)
109
+ if match:
110
+ layer_index = int(match.group(1))
111
+
112
+ if name.startswith("transformer_blocks") and layer_index in double_blocks_idx:
113
+ lora_state_dicts = [{} for _ in range(ck_number)]
114
+ for idx, checkpoint in enumerate(checkpoints):
115
+ for key, value in checkpoint.items():
116
+ # Match based on the layer index in the key (assuming the key contains layer index)
117
+ if re.search(r'\.(\d+)\.', key):
118
+ checkpoint_layer_index = int(re.search(r'\.(\d+)\.', key).group(1))
119
+ if checkpoint_layer_index == layer_index and key.startswith("transformer_blocks"):
120
+ lora_state_dicts[idx][key] = value
121
+
122
+ lora_attn_procs[name] = MultiDoubleStreamBlockLoraProcessor(
123
+ dim=3072, ranks=ranks, network_alphas=ranks, lora_weights=multi_lora_weight, device=device, dtype=torch.bfloat16, cond_width=cond_size, cond_height=cond_size, n_loras=cond_number
124
+ )
125
+
126
+ # Load the weights from the checkpoint dictionary into the corresponding layers
127
+ num = 0
128
+ for idx in range(ck_number):
129
+ for n in range(cond_lora_number[idx]):
130
+ lora_attn_procs[name].q_loras[num].down.weight.data = lora_state_dicts[idx].get(f'{name}.q_loras.{n}.down.weight', None)
131
+ lora_attn_procs[name].q_loras[num].up.weight.data = lora_state_dicts[idx].get(f'{name}.q_loras.{n}.up.weight', None)
132
+ lora_attn_procs[name].k_loras[num].down.weight.data = lora_state_dicts[idx].get(f'{name}.k_loras.{n}.down.weight', None)
133
+ lora_attn_procs[name].k_loras[num].up.weight.data = lora_state_dicts[idx].get(f'{name}.k_loras.{n}.up.weight', None)
134
+ lora_attn_procs[name].v_loras[num].down.weight.data = lora_state_dicts[idx].get(f'{name}.v_loras.{n}.down.weight', None)
135
+ lora_attn_procs[name].v_loras[num].up.weight.data = lora_state_dicts[idx].get(f'{name}.v_loras.{n}.up.weight', None)
136
+ lora_attn_procs[name].proj_loras[num].down.weight.data = lora_state_dicts[idx].get(f'{name}.proj_loras.{n}.down.weight', None)
137
+ lora_attn_procs[name].proj_loras[num].up.weight.data = lora_state_dicts[idx].get(f'{name}.proj_loras.{n}.up.weight', None)
138
+ lora_attn_procs[name].to(device)
139
+ num += 1
140
+
141
+ elif name.startswith("single_transformer_blocks") and layer_index in single_blocks_idx:
142
+
143
+ lora_state_dicts = [{} for _ in range(ck_number)]
144
+ for idx, checkpoint in enumerate(checkpoints):
145
+ for key, value in checkpoint.items():
146
+ # Match based on the layer index in the key (assuming the key contains layer index)
147
+ if re.search(r'\.(\d+)\.', key):
148
+ checkpoint_layer_index = int(re.search(r'\.(\d+)\.', key).group(1))
149
+ if checkpoint_layer_index == layer_index and key.startswith("single_transformer_blocks"):
150
+ lora_state_dicts[idx][key] = value
151
+
152
+ lora_attn_procs[name] = MultiSingleStreamBlockLoraProcessor(
153
+ dim=3072, ranks=ranks, network_alphas=ranks, lora_weights=multi_lora_weight, device=device, dtype=torch.bfloat16, cond_width=cond_size, cond_height=cond_size, n_loras=cond_number
154
+ )
155
+ # Load the weights from the checkpoint dictionary into the corresponding layers
156
+ num = 0
157
+ for idx in range(ck_number):
158
+ for n in range(cond_lora_number[idx]):
159
+ lora_attn_procs[name].q_loras[num].down.weight.data = lora_state_dicts[idx].get(f'{name}.q_loras.{n}.down.weight', None)
160
+ lora_attn_procs[name].q_loras[num].up.weight.data = lora_state_dicts[idx].get(f'{name}.q_loras.{n}.up.weight', None)
161
+ lora_attn_procs[name].k_loras[num].down.weight.data = lora_state_dicts[idx].get(f'{name}.k_loras.{n}.down.weight', None)
162
+ lora_attn_procs[name].k_loras[num].up.weight.data = lora_state_dicts[idx].get(f'{name}.k_loras.{n}.up.weight', None)
163
+ lora_attn_procs[name].v_loras[num].down.weight.data = lora_state_dicts[idx].get(f'{name}.v_loras.{n}.down.weight', None)
164
+ lora_attn_procs[name].v_loras[num].up.weight.data = lora_state_dicts[idx].get(f'{name}.v_loras.{n}.up.weight', None)
165
+ lora_attn_procs[name].to(device)
166
+ num += 1
167
+
168
+ else:
169
+ lora_attn_procs[name] = FluxAttnProcessor2_0()
170
+
171
+ transformer.set_attn_processor(lora_attn_procs)
172
+
173
+
174
+ def set_single_lora(transformer, local_path, lora_weights=[], cond_size=512):
175
+ checkpoint = load_checkpoint(local_path)
176
+ update_model_with_lora(checkpoint, lora_weights, transformer, cond_size)
177
+
178
+ def set_multi_lora(transformer, local_paths, lora_weights=[[]], cond_size=512):
179
+ checkpoints = [load_checkpoint(local_path) for local_path in local_paths]
180
+ update_model_with_multi_lora(checkpoints, lora_weights, transformer, cond_size)
181
+
182
+ def unset_lora(transformer):
183
+ lora_attn_procs = {}
184
+ for name, attn_processor in transformer.attn_processors.items():
185
+ lora_attn_procs[name] = FluxAttnProcessor2_0()
186
+ transformer.set_attn_processor(lora_attn_procs)
187
+
188
+
189
+ '''
190
+ unset_lora(pipe.transformer)
191
+ lora_path = "./lora.safetensors"
192
+ lora_weights = [1, 1]
193
+ set_lora(pipe.transformer, local_path=lora_path, lora_weights=lora_weights, cond_size=512)
194
+ '''
src_inference/pipeline.py ADDED
@@ -0,0 +1,746 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import inspect
2
+ from typing import Any, Callable, Dict, List, Optional, Union
3
+
4
+ import numpy as np
5
+ import torch
6
+ from transformers import CLIPTextModel, CLIPTokenizer, T5EncoderModel, T5TokenizerFast
7
+
8
+ from diffusers.image_processor import (VaeImageProcessor)
9
+ from diffusers.loaders import FluxLoraLoaderMixin, FromSingleFileMixin
10
+ from diffusers.models.autoencoders import AutoencoderKL
11
+ from diffusers.schedulers import FlowMatchEulerDiscreteScheduler
12
+ from diffusers.utils import (
13
+ USE_PEFT_BACKEND,
14
+ is_torch_xla_available,
15
+ logging,
16
+ scale_lora_layers,
17
+ unscale_lora_layers,
18
+ )
19
+ from diffusers.utils.torch_utils import randn_tensor
20
+ from diffusers.pipelines.pipeline_utils import DiffusionPipeline
21
+ from diffusers.pipelines.flux.pipeline_output import FluxPipelineOutput
22
+ from torchvision.transforms.functional import pad
23
+ from diffusers import FluxTransformer2DModel
24
+
25
+ if is_torch_xla_available():
26
+ import torch_xla.core.xla_model as xm
27
+
28
+ XLA_AVAILABLE = True
29
+ else:
30
+ XLA_AVAILABLE = False
31
+
32
+ logger = logging.get_logger(__name__) # pylint: disable=invalid-name
33
+
34
+ def calculate_shift(
35
+ image_seq_len,
36
+ base_seq_len: int = 256,
37
+ max_seq_len: int = 4096,
38
+ base_shift: float = 0.5,
39
+ max_shift: float = 1.16,
40
+ ):
41
+ m = (max_shift - base_shift) / (max_seq_len - base_seq_len)
42
+ b = base_shift - m * base_seq_len
43
+ mu = image_seq_len * m + b
44
+ return mu
45
+
46
+ def prepare_latent_image_ids_(height, width, device, dtype):
47
+ latent_image_ids = torch.zeros(height//2, width//2, 3, device=device, dtype=dtype)
48
+ latent_image_ids[..., 1] = latent_image_ids[..., 1] + torch.arange(height//2, device=device)[:, None] # y
49
+ latent_image_ids[..., 2] = latent_image_ids[..., 2] + torch.arange(width//2, device=device)[None, :] # x
50
+ return latent_image_ids
51
+
52
+ def prepare_latent_subject_ids(height, width, device, dtype):
53
+ latent_image_ids = torch.zeros(height // 2, width // 2, 3, device=device, dtype=dtype)
54
+ latent_image_ids[..., 1] = latent_image_ids[..., 1] + torch.arange(height // 2, device=device)[:, None]
55
+ latent_image_ids[..., 2] = latent_image_ids[..., 2] + torch.arange(width // 2, device=device)[None, :]
56
+ latent_image_id_height, latent_image_id_width, latent_image_id_channels = latent_image_ids.shape
57
+ latent_image_ids = latent_image_ids.reshape(
58
+ latent_image_id_height * latent_image_id_width, latent_image_id_channels
59
+ )
60
+ return latent_image_ids.to(device=device, dtype=dtype)
61
+
62
+ def resize_position_encoding(batch_size, original_height, original_width, target_height, target_width, device, dtype):
63
+ latent_image_ids = prepare_latent_image_ids_(original_height, original_width, device, dtype)
64
+ latent_image_id_height, latent_image_id_width, latent_image_id_channels = latent_image_ids.shape
65
+ latent_image_ids = latent_image_ids.reshape(
66
+ latent_image_id_height * latent_image_id_width, latent_image_id_channels
67
+ )
68
+
69
+ scale_h = original_height / target_height
70
+ scale_w = original_width / target_width
71
+ latent_image_ids_resized = torch.zeros(target_height//2, target_width//2, 3, device=device, dtype=dtype)
72
+ latent_image_ids_resized[..., 1] = latent_image_ids_resized[..., 1] + torch.arange(target_height//2, device=device)[:, None] * scale_h
73
+ latent_image_ids_resized[..., 2] = latent_image_ids_resized[..., 2] + torch.arange(target_width//2, device=device)[None, :] * scale_w
74
+
75
+ cond_latent_image_id_height, cond_latent_image_id_width, cond_latent_image_id_channels = latent_image_ids_resized.shape
76
+ cond_latent_image_ids = latent_image_ids_resized.reshape(
77
+ cond_latent_image_id_height * cond_latent_image_id_width, cond_latent_image_id_channels
78
+ )
79
+ return latent_image_ids, cond_latent_image_ids
80
+
81
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion_img2img.retrieve_latents
82
+ def retrieve_latents(
83
+ encoder_output: torch.Tensor, generator: Optional[torch.Generator] = None, sample_mode: str = "sample"
84
+ ):
85
+ if hasattr(encoder_output, "latent_dist") and sample_mode == "sample":
86
+ return encoder_output.latent_dist.sample(generator)
87
+ elif hasattr(encoder_output, "latent_dist") and sample_mode == "argmax":
88
+ return encoder_output.latent_dist.mode()
89
+ elif hasattr(encoder_output, "latents"):
90
+ return encoder_output.latents
91
+ else:
92
+ raise AttributeError("Could not access latents of provided encoder_output")
93
+
94
+
95
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.retrieve_timesteps
96
+ def retrieve_timesteps(
97
+ scheduler,
98
+ num_inference_steps: Optional[int] = None,
99
+ device: Optional[Union[str, torch.device]] = None,
100
+ timesteps: Optional[List[int]] = None,
101
+ sigmas: Optional[List[float]] = None,
102
+ **kwargs,
103
+ ):
104
+ if timesteps is not None and sigmas is not None:
105
+ raise ValueError("Only one of `timesteps` or `sigmas` can be passed. Please choose one to set custom values")
106
+ if timesteps is not None:
107
+ accepts_timesteps = "timesteps" in set(inspect.signature(scheduler.set_timesteps).parameters.keys())
108
+ if not accepts_timesteps:
109
+ raise ValueError(
110
+ f"The current scheduler class {scheduler.__class__}'s `set_timesteps` does not support custom"
111
+ f" timestep schedules. Please check whether you are using the correct scheduler."
112
+ )
113
+ scheduler.set_timesteps(timesteps=timesteps, device=device, **kwargs)
114
+ timesteps = scheduler.timesteps
115
+ num_inference_steps = len(timesteps)
116
+ elif sigmas is not None:
117
+ accept_sigmas = "sigmas" in set(inspect.signature(scheduler.set_timesteps).parameters.keys())
118
+ if not accept_sigmas:
119
+ raise ValueError(
120
+ f"The current scheduler class {scheduler.__class__}'s `set_timesteps` does not support custom"
121
+ f" sigmas schedules. Please check whether you are using the correct scheduler."
122
+ )
123
+ scheduler.set_timesteps(sigmas=sigmas, device=device, **kwargs)
124
+ timesteps = scheduler.timesteps
125
+ num_inference_steps = len(timesteps)
126
+ else:
127
+ scheduler.set_timesteps(num_inference_steps, device=device, **kwargs)
128
+ timesteps = scheduler.timesteps
129
+ return timesteps, num_inference_steps
130
+
131
+
132
+ class FluxPipeline(DiffusionPipeline, FluxLoraLoaderMixin, FromSingleFileMixin):
133
+ def __init__(
134
+ self,
135
+ scheduler: FlowMatchEulerDiscreteScheduler,
136
+ vae: AutoencoderKL,
137
+ text_encoder: CLIPTextModel,
138
+ tokenizer: CLIPTokenizer,
139
+ text_encoder_2: T5EncoderModel,
140
+ tokenizer_2: T5TokenizerFast,
141
+ transformer: FluxTransformer2DModel,
142
+ ):
143
+ super().__init__()
144
+
145
+ self.register_modules(
146
+ vae=vae,
147
+ text_encoder=text_encoder,
148
+ text_encoder_2=text_encoder_2,
149
+ tokenizer=tokenizer,
150
+ tokenizer_2=tokenizer_2,
151
+ transformer=transformer,
152
+ scheduler=scheduler,
153
+ )
154
+ self.vae_scale_factor = (
155
+ 2 ** (len(self.vae.config.block_out_channels)) if hasattr(self, "vae") and self.vae is not None else 16
156
+ )
157
+ self.image_processor = VaeImageProcessor(vae_scale_factor=self.vae_scale_factor)
158
+ self.tokenizer_max_length = (
159
+ self.tokenizer.model_max_length if hasattr(self, "tokenizer") and self.tokenizer is not None else 77
160
+ )
161
+ self.default_sample_size = 64
162
+
163
+ def _get_t5_prompt_embeds(
164
+ self,
165
+ prompt: Union[str, List[str]] = None,
166
+ num_images_per_prompt: int = 1,
167
+ max_sequence_length: int = 512,
168
+ device: Optional[torch.device] = None,
169
+ dtype: Optional[torch.dtype] = None,
170
+ ):
171
+ device = device or self._execution_device
172
+ dtype = dtype or self.text_encoder.dtype
173
+
174
+ prompt = [prompt] if isinstance(prompt, str) else prompt
175
+ batch_size = len(prompt)
176
+
177
+ text_inputs = self.tokenizer_2(
178
+ prompt,
179
+ padding="max_length",
180
+ max_length=max_sequence_length,
181
+ truncation=True,
182
+ return_length=False,
183
+ return_overflowing_tokens=False,
184
+ return_tensors="pt",
185
+ )
186
+ text_input_ids = text_inputs.input_ids
187
+ untruncated_ids = self.tokenizer_2(prompt, padding="longest", return_tensors="pt").input_ids
188
+
189
+ if untruncated_ids.shape[-1] >= text_input_ids.shape[-1] and not torch.equal(text_input_ids, untruncated_ids):
190
+ removed_text = self.tokenizer_2.batch_decode(untruncated_ids[:, self.tokenizer_max_length - 1: -1])
191
+ logger.warning(
192
+ "The following part of your input was truncated because `max_sequence_length` is set to "
193
+ f" {max_sequence_length} tokens: {removed_text}"
194
+ )
195
+
196
+ prompt_embeds = self.text_encoder_2(text_input_ids.to(device), output_hidden_states=False)[0]
197
+
198
+ dtype = self.text_encoder_2.dtype
199
+ prompt_embeds = prompt_embeds.to(dtype=dtype, device=device)
200
+
201
+ _, seq_len, _ = prompt_embeds.shape
202
+
203
+ # duplicate text embeddings and attention mask for each generation per prompt, using mps friendly method
204
+ prompt_embeds = prompt_embeds.repeat(1, num_images_per_prompt, 1)
205
+ prompt_embeds = prompt_embeds.view(batch_size * num_images_per_prompt, seq_len, -1)
206
+
207
+ return prompt_embeds
208
+
209
+ def _get_clip_prompt_embeds(
210
+ self,
211
+ prompt: Union[str, List[str]],
212
+ num_images_per_prompt: int = 1,
213
+ device: Optional[torch.device] = None,
214
+ ):
215
+ device = device or self._execution_device
216
+
217
+ prompt = [prompt] if isinstance(prompt, str) else prompt
218
+ batch_size = len(prompt)
219
+
220
+ text_inputs = self.tokenizer(
221
+ prompt,
222
+ padding="max_length",
223
+ max_length=self.tokenizer_max_length,
224
+ truncation=True,
225
+ return_overflowing_tokens=False,
226
+ return_length=False,
227
+ return_tensors="pt",
228
+ )
229
+
230
+ text_input_ids = text_inputs.input_ids
231
+ untruncated_ids = self.tokenizer(prompt, padding="longest", return_tensors="pt").input_ids
232
+ if untruncated_ids.shape[-1] >= text_input_ids.shape[-1] and not torch.equal(text_input_ids, untruncated_ids):
233
+ removed_text = self.tokenizer.batch_decode(untruncated_ids[:, self.tokenizer_max_length - 1: -1])
234
+ logger.warning(
235
+ "The following part of your input was truncated because CLIP can only handle sequences up to"
236
+ f" {self.tokenizer_max_length} tokens: {removed_text}"
237
+ )
238
+ prompt_embeds = self.text_encoder(text_input_ids.to(device), output_hidden_states=False)
239
+
240
+ # Use pooled output of CLIPTextModel
241
+ prompt_embeds = prompt_embeds.pooler_output
242
+ prompt_embeds = prompt_embeds.to(dtype=self.text_encoder.dtype, device=device)
243
+
244
+ # duplicate text embeddings for each generation per prompt, using mps friendly method
245
+ prompt_embeds = prompt_embeds.repeat(1, num_images_per_prompt)
246
+ prompt_embeds = prompt_embeds.view(batch_size * num_images_per_prompt, -1)
247
+
248
+ return prompt_embeds
249
+
250
+ def encode_prompt(
251
+ self,
252
+ prompt: Union[str, List[str]],
253
+ prompt_2: Union[str, List[str]],
254
+ device: Optional[torch.device] = None,
255
+ num_images_per_prompt: int = 1,
256
+ prompt_embeds: Optional[torch.FloatTensor] = None,
257
+ pooled_prompt_embeds: Optional[torch.FloatTensor] = None,
258
+ max_sequence_length: int = 512,
259
+ lora_scale: Optional[float] = None,
260
+ ):
261
+ device = device or self._execution_device
262
+
263
+ # set lora scale so that monkey patched LoRA
264
+ # function of text encoder can correctly access it
265
+ if lora_scale is not None and isinstance(self, FluxLoraLoaderMixin):
266
+ self._lora_scale = lora_scale
267
+
268
+ # dynamically adjust the LoRA scale
269
+ if self.text_encoder is not None and USE_PEFT_BACKEND:
270
+ scale_lora_layers(self.text_encoder, lora_scale)
271
+ if self.text_encoder_2 is not None and USE_PEFT_BACKEND:
272
+ scale_lora_layers(self.text_encoder_2, lora_scale)
273
+
274
+ prompt = [prompt] if isinstance(prompt, str) else prompt
275
+
276
+ if prompt_embeds is None:
277
+ prompt_2 = prompt_2 or prompt
278
+ prompt_2 = [prompt_2] if isinstance(prompt_2, str) else prompt_2
279
+
280
+ # We only use the pooled prompt output from the CLIPTextModel
281
+ pooled_prompt_embeds = self._get_clip_prompt_embeds(
282
+ prompt=prompt,
283
+ device=device,
284
+ num_images_per_prompt=num_images_per_prompt,
285
+ )
286
+ prompt_embeds = self._get_t5_prompt_embeds(
287
+ prompt=prompt_2,
288
+ num_images_per_prompt=num_images_per_prompt,
289
+ max_sequence_length=max_sequence_length,
290
+ device=device,
291
+ )
292
+
293
+ if self.text_encoder is not None:
294
+ if isinstance(self, FluxLoraLoaderMixin) and USE_PEFT_BACKEND:
295
+ # Retrieve the original scale by scaling back the LoRA layers
296
+ unscale_lora_layers(self.text_encoder, lora_scale)
297
+
298
+ if self.text_encoder_2 is not None:
299
+ if isinstance(self, FluxLoraLoaderMixin) and USE_PEFT_BACKEND:
300
+ # Retrieve the original scale by scaling back the LoRA layers
301
+ unscale_lora_layers(self.text_encoder_2, lora_scale)
302
+
303
+ dtype = self.text_encoder.dtype if self.text_encoder is not None else self.transformer.dtype
304
+ text_ids = torch.zeros(prompt_embeds.shape[1], 3).to(device=device, dtype=dtype)
305
+
306
+ return prompt_embeds, pooled_prompt_embeds, text_ids
307
+
308
+ # Copied from diffusers.pipelines.stable_diffusion_3.pipeline_stable_diffusion_3_inpaint.StableDiffusion3InpaintPipeline._encode_vae_image
309
+ def _encode_vae_image(self, image: torch.Tensor, generator: torch.Generator):
310
+ if isinstance(generator, list):
311
+ image_latents = [
312
+ retrieve_latents(self.vae.encode(image[i: i + 1]), generator=generator[i])
313
+ for i in range(image.shape[0])
314
+ ]
315
+ image_latents = torch.cat(image_latents, dim=0)
316
+ else:
317
+ image_latents = retrieve_latents(self.vae.encode(image), generator=generator)
318
+
319
+ image_latents = (image_latents - self.vae.config.shift_factor) * self.vae.config.scaling_factor
320
+
321
+ return image_latents
322
+
323
+ def check_inputs(
324
+ self,
325
+ prompt,
326
+ prompt_2,
327
+ height,
328
+ width,
329
+ prompt_embeds=None,
330
+ pooled_prompt_embeds=None,
331
+ callback_on_step_end_tensor_inputs=None,
332
+ max_sequence_length=None,
333
+ ):
334
+ if height % 8 != 0 or width % 8 != 0:
335
+ raise ValueError(f"`height` and `width` have to be divisible by 8 but are {height} and {width}.")
336
+
337
+ if prompt is not None and prompt_embeds is not None:
338
+ raise ValueError(
339
+ f"Cannot forward both `prompt`: {prompt} and `prompt_embeds`: {prompt_embeds}. Please make sure to"
340
+ " only forward one of the two."
341
+ )
342
+ elif prompt_2 is not None and prompt_embeds is not None:
343
+ raise ValueError(
344
+ f"Cannot forward both `prompt_2`: {prompt_2} and `prompt_embeds`: {prompt_embeds}. Please make sure to"
345
+ " only forward one of the two."
346
+ )
347
+ elif prompt is None and prompt_embeds is None:
348
+ raise ValueError(
349
+ "Provide either `prompt` or `prompt_embeds`. Cannot leave both `prompt` and `prompt_embeds` undefined."
350
+ )
351
+ elif prompt is not None and (not isinstance(prompt, str) and not isinstance(prompt, list)):
352
+ raise ValueError(f"`prompt` has to be of type `str` or `list` but is {type(prompt)}")
353
+ elif prompt_2 is not None and (not isinstance(prompt_2, str) and not isinstance(prompt_2, list)):
354
+ raise ValueError(f"`prompt_2` has to be of type `str` or `list` but is {type(prompt_2)}")
355
+
356
+ if prompt_embeds is not None and pooled_prompt_embeds is None:
357
+ raise ValueError(
358
+ "If `prompt_embeds` are provided, `pooled_prompt_embeds` also have to be passed. Make sure to generate `pooled_prompt_embeds` from the same text encoder that was used to generate `prompt_embeds`."
359
+ )
360
+
361
+ if max_sequence_length is not None and max_sequence_length > 512:
362
+ raise ValueError(f"`max_sequence_length` cannot be greater than 512 but is {max_sequence_length}")
363
+
364
+ @staticmethod
365
+ def _prepare_latent_image_ids(batch_size, height, width, device, dtype):
366
+ latent_image_ids = torch.zeros(height // 2, width // 2, 3)
367
+ latent_image_ids[..., 1] = latent_image_ids[..., 1] + torch.arange(height // 2)[:, None]
368
+ latent_image_ids[..., 2] = latent_image_ids[..., 2] + torch.arange(width // 2)[None, :]
369
+ latent_image_id_height, latent_image_id_width, latent_image_id_channels = latent_image_ids.shape
370
+ latent_image_ids = latent_image_ids.reshape(
371
+ latent_image_id_height * latent_image_id_width, latent_image_id_channels
372
+ )
373
+ return latent_image_ids.to(device=device, dtype=dtype)
374
+
375
+ @staticmethod
376
+ def _pack_latents(latents, batch_size, num_channels_latents, height, width):
377
+ latents = latents.view(batch_size, num_channels_latents, height // 2, 2, width // 2, 2)
378
+ latents = latents.permute(0, 2, 4, 1, 3, 5)
379
+ latents = latents.reshape(batch_size, (height // 2) * (width // 2), num_channels_latents * 4)
380
+ return latents
381
+
382
+ @staticmethod
383
+ def _unpack_latents(latents, height, width, vae_scale_factor):
384
+ batch_size, num_patches, channels = latents.shape
385
+
386
+ height = height // vae_scale_factor
387
+ width = width // vae_scale_factor
388
+
389
+ latents = latents.view(batch_size, height, width, channels // 4, 2, 2)
390
+ latents = latents.permute(0, 3, 1, 4, 2, 5)
391
+
392
+ latents = latents.reshape(batch_size, channels // (2 * 2), height * 2, width * 2)
393
+
394
+ return latents
395
+
396
+ def enable_vae_slicing(self):
397
+ r"""
398
+ Enable sliced VAE decoding. When this option is enabled, the VAE will split the input tensor in slices to
399
+ compute decoding in several steps. This is useful to save some memory and allow larger batch sizes.
400
+ """
401
+ self.vae.enable_slicing()
402
+
403
+ def disable_vae_slicing(self):
404
+ r"""
405
+ Disable sliced VAE decoding. If `enable_vae_slicing` was previously enabled, this method will go back to
406
+ computing decoding in one step.
407
+ """
408
+ self.vae.disable_slicing()
409
+
410
+ def enable_vae_tiling(self):
411
+ r"""
412
+ Enable tiled VAE decoding. When this option is enabled, the VAE will split the input tensor into tiles to
413
+ compute decoding and encoding in several steps. This is useful for saving a large amount of memory and to allow
414
+ processing larger images.
415
+ """
416
+ self.vae.enable_tiling()
417
+
418
+ def disable_vae_tiling(self):
419
+ r"""
420
+ Disable tiled VAE decoding. If `enable_vae_tiling` was previously enabled, this method will go back to
421
+ computing decoding in one step.
422
+ """
423
+ self.vae.disable_tiling()
424
+
425
+ def prepare_latents(
426
+ self,
427
+ batch_size,
428
+ num_channels_latents,
429
+ height,
430
+ width,
431
+ dtype,
432
+ device,
433
+ generator,
434
+ subject_image,
435
+ condition_image,
436
+ latents=None,
437
+ cond_number=1,
438
+ sub_number=1
439
+ ):
440
+ height_cond = 2 * (self.cond_size // self.vae_scale_factor)
441
+ width_cond = 2 * (self.cond_size // self.vae_scale_factor)
442
+ height = 2 * (int(height) // self.vae_scale_factor)
443
+ width = 2 * (int(width) // self.vae_scale_factor)
444
+
445
+ shape = (batch_size, num_channels_latents, height, width) # 1 16 106 80
446
+ noise_latents = randn_tensor(shape, generator=generator, device=device, dtype=dtype)
447
+ noise_latents = self._pack_latents(noise_latents, batch_size, num_channels_latents, height, width)
448
+ noise_latent_image_ids, cond_latent_image_ids = resize_position_encoding(
449
+ batch_size,
450
+ height,
451
+ width,
452
+ height_cond,
453
+ width_cond,
454
+ device,
455
+ dtype,
456
+ )
457
+
458
+ latents_to_concat = []
459
+ latents_ids_to_concat = [noise_latent_image_ids]
460
+
461
+ # subject
462
+ if subject_image is not None:
463
+ shape_subject = (batch_size, num_channels_latents, height_cond*sub_number, width_cond)
464
+ subject_image = subject_image.to(device=device, dtype=dtype)
465
+ subject_image_latents = self._encode_vae_image(image=subject_image, generator=generator)
466
+ subject_latents = self._pack_latents(subject_image_latents, batch_size, num_channels_latents, height_cond*sub_number, width_cond)
467
+ mask2 = torch.zeros(shape_subject, device=device, dtype=dtype)
468
+ mask2 = self._pack_latents(mask2, batch_size, num_channels_latents, height_cond*sub_number, width_cond)
469
+ latent_subject_ids = prepare_latent_subject_ids(height_cond, width_cond, device, dtype)
470
+ latent_subject_ids[:, 1] += 64 # fixed offset
471
+ subject_latent_image_ids = torch.concat([latent_subject_ids for _ in range(sub_number)], dim=-2)
472
+ latents_to_concat.append(subject_latents)
473
+ latents_ids_to_concat.append(subject_latent_image_ids)
474
+
475
+ # spatial
476
+ if condition_image is not None:
477
+ shape_cond = (batch_size, num_channels_latents, height_cond*cond_number, width_cond)
478
+ condition_image = condition_image.to(device=device, dtype=dtype)
479
+ image_latents = self._encode_vae_image(image=condition_image, generator=generator)
480
+ cond_latents = self._pack_latents(image_latents, batch_size, num_channels_latents, height_cond*cond_number, width_cond)
481
+ mask3 = torch.zeros(shape_cond, device=device, dtype=dtype)
482
+ mask3 = self._pack_latents(mask3, batch_size, num_channels_latents, height_cond*cond_number, width_cond)
483
+ cond_latent_image_ids = cond_latent_image_ids
484
+ cond_latent_image_ids = torch.concat([cond_latent_image_ids for _ in range(cond_number)], dim=-2)
485
+ latents_ids_to_concat.append(cond_latent_image_ids)
486
+ latents_to_concat.append(cond_latents)
487
+
488
+ cond_latents = torch.concat(latents_to_concat, dim=-2)
489
+ latent_image_ids = torch.concat(latents_ids_to_concat, dim=-2)
490
+ return cond_latents, latent_image_ids, noise_latents
491
+
492
+ @property
493
+ def guidance_scale(self):
494
+ return self._guidance_scale
495
+
496
+ @property
497
+ def joint_attention_kwargs(self):
498
+ return self._joint_attention_kwargs
499
+
500
+ @property
501
+ def num_timesteps(self):
502
+ return self._num_timesteps
503
+
504
+ @property
505
+ def interrupt(self):
506
+ return self._interrupt
507
+
508
+ @torch.no_grad()
509
+ def __call__(
510
+ self,
511
+ prompt: Union[str, List[str]] = None,
512
+ prompt_2: Optional[Union[str, List[str]]] = None,
513
+ height: Optional[int] = None,
514
+ width: Optional[int] = None,
515
+ num_inference_steps: int = 28,
516
+ timesteps: List[int] = None,
517
+ guidance_scale: float = 3.5,
518
+ num_images_per_prompt: Optional[int] = 1,
519
+ generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
520
+ latents: Optional[torch.FloatTensor] = None,
521
+ prompt_embeds: Optional[torch.FloatTensor] = None,
522
+ pooled_prompt_embeds: Optional[torch.FloatTensor] = None,
523
+ output_type: Optional[str] = "pil",
524
+ return_dict: bool = True,
525
+ joint_attention_kwargs: Optional[Dict[str, Any]] = None,
526
+ callback_on_step_end: Optional[Callable[[int, int, Dict], None]] = None,
527
+ callback_on_step_end_tensor_inputs: List[str] = ["latents"],
528
+ max_sequence_length: int = 512,
529
+ spatial_images=[],
530
+ subject_images=[],
531
+ cond_size=512,
532
+ ):
533
+
534
+ height = height or self.default_sample_size * self.vae_scale_factor
535
+ width = width or self.default_sample_size * self.vae_scale_factor
536
+ self.cond_size = cond_size
537
+
538
+ # 1. Check inputs. Raise error if not correct
539
+ self.check_inputs(
540
+ prompt,
541
+ prompt_2,
542
+ height,
543
+ width,
544
+ prompt_embeds=prompt_embeds,
545
+ pooled_prompt_embeds=pooled_prompt_embeds,
546
+ callback_on_step_end_tensor_inputs=callback_on_step_end_tensor_inputs,
547
+ max_sequence_length=max_sequence_length,
548
+ )
549
+
550
+ self._guidance_scale = guidance_scale
551
+ self._joint_attention_kwargs = joint_attention_kwargs
552
+ self._interrupt = False
553
+
554
+ cond_number = len(spatial_images)
555
+ sub_number = len(subject_images)
556
+
557
+ if sub_number > 0:
558
+ subject_image_ls = []
559
+ for subject_image in subject_images:
560
+ w, h = subject_image.size[:2]
561
+ scale = self.cond_size / max(h, w)
562
+ new_h, new_w = int(h * scale), int(w * scale)
563
+ subject_image = self.image_processor.preprocess(subject_image, height=new_h, width=new_w)
564
+ subject_image = subject_image.to(dtype=torch.float32)
565
+ pad_h = cond_size - subject_image.shape[-2]
566
+ pad_w = cond_size - subject_image.shape[-1]
567
+ subject_image = pad(
568
+ subject_image,
569
+ padding=(int(pad_w / 2), int(pad_h / 2), int(pad_w / 2), int(pad_h / 2)),
570
+ fill=0
571
+ )
572
+ subject_image_ls.append(subject_image)
573
+ subject_image = torch.concat(subject_image_ls, dim=-2)
574
+ else:
575
+ subject_image = None
576
+
577
+ if cond_number > 0:
578
+ condition_image_ls = []
579
+ for img in spatial_images:
580
+ print(img)
581
+ condition_image = self.image_processor.preprocess(img, height=self.cond_size, width=self.cond_size)
582
+ condition_image = condition_image.to(dtype=torch.float32)
583
+ condition_image_ls.append(condition_image)
584
+ condition_image = torch.concat(condition_image_ls, dim=-2)
585
+ else:
586
+ condition_image = None
587
+
588
+ # 2. Define call parameters
589
+ if prompt is not None and isinstance(prompt, str):
590
+ batch_size = 1
591
+ elif prompt is not None and isinstance(prompt, list):
592
+ batch_size = len(prompt)
593
+ else:
594
+ batch_size = prompt_embeds.shape[0]
595
+
596
+ device = self._execution_device
597
+
598
+ lora_scale = (
599
+ self.joint_attention_kwargs.get("scale", None) if self.joint_attention_kwargs is not None else None
600
+ )
601
+ (
602
+ prompt_embeds,
603
+ pooled_prompt_embeds,
604
+ text_ids,
605
+ ) = self.encode_prompt(
606
+ prompt=prompt,
607
+ prompt_2=prompt_2,
608
+ prompt_embeds=prompt_embeds,
609
+ pooled_prompt_embeds=pooled_prompt_embeds,
610
+ device=device,
611
+ num_images_per_prompt=num_images_per_prompt,
612
+ max_sequence_length=max_sequence_length,
613
+ lora_scale=lora_scale,
614
+ )
615
+
616
+ # 4. Prepare latent variables
617
+ num_channels_latents = self.transformer.config.in_channels // 4 # 16
618
+ cond_latents, latent_image_ids, noise_latents = self.prepare_latents(
619
+ batch_size * num_images_per_prompt,
620
+ num_channels_latents,
621
+ height,
622
+ width,
623
+ prompt_embeds.dtype,
624
+ device,
625
+ generator,
626
+ subject_image,
627
+ condition_image,
628
+ latents,
629
+ cond_number,
630
+ sub_number
631
+ )
632
+ latents = noise_latents
633
+ # 5. Prepare timesteps
634
+ sigmas = np.linspace(1.0, 1 / num_inference_steps, num_inference_steps)
635
+ image_seq_len = latents.shape[1]
636
+ mu = calculate_shift(
637
+ image_seq_len,
638
+ self.scheduler.config.base_image_seq_len,
639
+ self.scheduler.config.max_image_seq_len,
640
+ self.scheduler.config.base_shift,
641
+ self.scheduler.config.max_shift,
642
+ )
643
+ timesteps, num_inference_steps = retrieve_timesteps(
644
+ self.scheduler,
645
+ num_inference_steps,
646
+ device,
647
+ timesteps,
648
+ sigmas,
649
+ mu=mu,
650
+ )
651
+ num_warmup_steps = max(len(timesteps) - num_inference_steps * self.scheduler.order, 0)
652
+ self._num_timesteps = len(timesteps)
653
+
654
+ # handle guidance
655
+ if self.transformer.config.guidance_embeds:
656
+ guidance = torch.full([1], guidance_scale, device=device, dtype=torch.float32)
657
+ guidance = guidance.expand(latents.shape[0])
658
+ else:
659
+ guidance = None
660
+
661
+ ## Caching conditions
662
+ # clean the cache
663
+ try:
664
+ for name, attn_processor in self.transformer.attn_processors.items():
665
+ attn_processor.bank_kv.clear()
666
+ except:
667
+ pass
668
+ # cache with warmup latents
669
+ t = torch.tensor([timesteps[0]], device=device)
670
+ timestep = t.expand(cond_latents.shape[0]).to(latents.dtype)
671
+ warmup_image_ids = latent_image_ids[latents.shape[1]:, :]
672
+ _ = self.transformer(
673
+ hidden_states=cond_latents,
674
+ timestep=torch.ones_like(timestep) * 0,
675
+ guidance=guidance,
676
+ pooled_projections=pooled_prompt_embeds,
677
+ encoder_hidden_states=prompt_embeds,
678
+ txt_ids=text_ids,
679
+ img_ids=warmup_image_ids,
680
+ joint_attention_kwargs=self.joint_attention_kwargs,
681
+ return_dict=False,
682
+ )[0]
683
+
684
+ del cond_latents, spatial_images, condition_image, condition_image_ls, img, _
685
+ torch.cuda.empty_cache()
686
+
687
+ # 6. Denoising loop
688
+ with self.progress_bar(total=num_inference_steps) as progress_bar:
689
+ for i, t in enumerate(timesteps):
690
+ if self.interrupt:
691
+ continue
692
+
693
+ # broadcast to batch dimension in a way that's compatible with ONNX/Core ML
694
+ timestep = t.expand(latents.shape[0]).to(latents.dtype)
695
+ noise_pred = self.transformer(
696
+ hidden_states=latents,
697
+ timestep=timestep / 1000,
698
+ guidance=guidance,
699
+ pooled_projections=pooled_prompt_embeds,
700
+ encoder_hidden_states=prompt_embeds,
701
+ txt_ids=text_ids,
702
+ img_ids=latent_image_ids,
703
+ joint_attention_kwargs=self.joint_attention_kwargs,
704
+ return_dict=False,
705
+ )[0]
706
+
707
+ # compute the previous noisy sample x_t -> x_t-1
708
+ latents_dtype = latents.dtype
709
+ latents = self.scheduler.step(noise_pred, t, latents, return_dict=False)[0]
710
+
711
+ if latents.dtype != latents_dtype:
712
+ if torch.backends.mps.is_available():
713
+ # some platforms (eg. apple mps) misbehave due to a pytorch bug: https://github.com/pytorch/pytorch/pull/99272
714
+ latents = latents.to(latents_dtype)
715
+
716
+ if callback_on_step_end is not None:
717
+ callback_kwargs = {}
718
+ for k in callback_on_step_end_tensor_inputs:
719
+ callback_kwargs[k] = locals()[k]
720
+ callback_outputs = callback_on_step_end(self, i, t, callback_kwargs)
721
+
722
+ latents = callback_outputs.pop("latents", latents)
723
+ prompt_embeds = callback_outputs.pop("prompt_embeds", prompt_embeds)
724
+
725
+ # call the callback, if provided
726
+ if i == len(timesteps) - 1 or ((i + 1) > num_warmup_steps and (i + 1) % self.scheduler.order == 0):
727
+ progress_bar.update()
728
+
729
+ if XLA_AVAILABLE:
730
+ xm.mark_step()
731
+
732
+ if output_type == "latent":
733
+ image = latents
734
+ else:
735
+ latents = self._unpack_latents(latents, height, width, self.vae_scale_factor)
736
+ latents = (latents / self.vae.config.scaling_factor) + self.vae.config.shift_factor
737
+ image = self.vae.decode(latents.to(dtype=self.vae.dtype), return_dict=False)[0]
738
+ image = self.image_processor.postprocess(image, output_type=output_type)
739
+
740
+ # Offload all models
741
+ self.maybe_free_model_hooks()
742
+
743
+ if not return_dict:
744
+ return (image,)
745
+
746
+ return FluxPipelineOutput(images=image)
test_imgs/00.png ADDED
test_imgs/01.png ADDED
test_imgs/02.png ADDED
test_imgs/03.png ADDED
test_imgs/04.png ADDED