ameerazam08 commited on
Commit
a105aa8
1 Parent(s): 76d8871

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +711 -120
app.py CHANGED
@@ -1,139 +1,730 @@
1
  import gradio as gr
2
- import numpy as np
3
- import random
 
 
 
4
  import spaces
5
- import torch
6
- from diffusers import DiffusionPipeline, FlowMatchEulerDiscreteScheduler, AutoencoderTiny, AutoencoderKL
7
- from transformers import CLIPTextModel, CLIPTokenizer,T5EncoderModel, T5TokenizerFast
8
- from live_preview_helpers import calculate_shift, retrieve_timesteps, flux_pipe_call_that_returns_an_iterable_of_images
9
 
 
 
 
 
 
 
 
 
10
  dtype = torch.bfloat16
11
  device = "cuda" if torch.cuda.is_available() else "cpu"
 
 
 
 
 
 
 
 
12
 
13
- taef1 = AutoencoderTiny.from_pretrained("madebyollin/taef1", torch_dtype=dtype).to(device)
14
- good_vae = AutoencoderKL.from_pretrained("black-forest-labs/FLUX.1-dev", subfolder="vae", torch_dtype=dtype).to(device)
15
- pipe = DiffusionPipeline.from_pretrained("black-forest-labs/FLUX.1-dev", torch_dtype=dtype, vae=taef1).to(device)
16
- torch.cuda.empty_cache()
 
 
17
 
18
- MAX_SEED = np.iinfo(np.int32).max
19
- MAX_IMAGE_SIZE = 2048
20
 
21
- pipe.flux_pipe_call_that_returns_an_iterable_of_images = flux_pipe_call_that_returns_an_iterable_of_images.__get__(pipe)
 
 
 
 
 
 
 
 
 
22
 
23
- @spaces.GPU(duration=75)
24
- def infer(prompt, seed=42, randomize_seed=False, width=1024, height=1024, guidance_scale=3.5, num_inference_steps=28, progress=gr.Progress(track_tqdm=True)):
25
- if randomize_seed:
26
- seed = random.randint(0, MAX_SEED)
27
- generator = torch.Generator().manual_seed(seed)
 
28
 
29
- for img in pipe.flux_pipe_call_that_returns_an_iterable_of_images(
30
- prompt=prompt,
31
- guidance_scale=guidance_scale,
32
- num_inference_steps=num_inference_steps,
33
- width=width,
34
- height=height,
35
- generator=generator,
36
- output_type="pil",
37
- good_vae=good_vae,
38
- ):
39
- yield img, seed
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
40
 
41
- examples = [
42
- "a tiny astronaut hatching from an egg on the moon",
43
- "a cat holding a sign that says hello world",
44
- "an anime illustration of a wiener schnitzel",
45
- ]
46
-
47
- css="""
48
- #col-container {
49
- margin: 0 auto;
50
- max-width: 520px;
51
- }
52
- """
53
-
54
- with gr.Blocks(css=css) as demo:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
55
 
56
- with gr.Column(elem_id="col-container"):
57
- gr.Markdown(f"""# FLUX.1 [dev]
58
- 12B param rectified flow transformer guidance-distilled from [FLUX.1 [pro]](https://blackforestlabs.ai/)
59
- [[non-commercial license](https://huggingface.co/black-forest-labs/FLUX.1-dev/blob/main/LICENSE.md)] [[blog](https://blackforestlabs.ai/announcing-black-forest-labs/)] [[model](https://huggingface.co/black-forest-labs/FLUX.1-dev)]
60
- """)
61
-
62
- with gr.Row():
63
-
64
- prompt = gr.Text(
65
- label="Prompt",
66
- show_label=False,
67
- max_lines=1,
68
- placeholder="Enter your prompt",
69
- container=False,
70
- )
71
-
72
- run_button = gr.Button("Run", scale=0)
73
-
74
- result = gr.Image(label="Result", show_label=False)
75
-
76
- with gr.Accordion("Advanced Settings", open=False):
77
-
78
- seed = gr.Slider(
79
- label="Seed",
80
- minimum=0,
81
- maximum=MAX_SEED,
82
- step=1,
83
- value=0,
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
84
  )
85
-
86
- randomize_seed = gr.Checkbox(label="Randomize seed", value=True)
87
-
88
- with gr.Row():
89
-
90
- width = gr.Slider(
91
- label="Width",
92
- minimum=256,
93
- maximum=MAX_IMAGE_SIZE,
94
- step=32,
95
- value=1024,
96
- )
97
-
98
- height = gr.Slider(
99
- label="Height",
100
- minimum=256,
101
- maximum=MAX_IMAGE_SIZE,
102
- step=32,
103
- value=1024,
104
- )
105
-
106
- with gr.Row():
107
-
108
- guidance_scale = gr.Slider(
109
- label="Guidance Scale",
110
- minimum=1,
111
- maximum=15,
112
- step=0.1,
113
- value=3.5,
114
- )
115
-
116
- num_inference_steps = gr.Slider(
117
- label="Number of inference steps",
118
- minimum=1,
119
- maximum=50,
120
- step=1,
121
- value=28,
122
  )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
123
 
124
- gr.Examples(
125
- examples = examples,
126
- fn = infer,
127
- inputs = [prompt],
128
- outputs = [result, seed],
129
- cache_examples="lazy"
 
 
 
130
  )
 
 
 
 
 
 
 
 
 
131
 
132
- gr.on(
133
- triggers=[run_button.click, prompt.submit],
134
- fn = infer,
135
- inputs = [prompt, seed, randomize_seed, width, height, guidance_scale, num_inference_steps],
136
- outputs = [result, seed]
 
 
 
 
137
  )
138
 
139
- demo.launch()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  import gradio as gr
2
+ from PIL import Image
3
+ from torchvision import transforms
4
+ from dataclasses import dataclass
5
+ import math
6
+ from typing import Callable
7
  import spaces
 
 
 
 
8
 
9
+ import torch
10
+ import random
11
+ from tqdm import tqdm
12
+ from einops import rearrange, repeat
13
+ from diffusers import AutoencoderKL
14
+ from torch import Tensor, nn
15
+ from transformers import CLIPTextModel, CLIPTokenizer, T5EncoderModel, T5Tokenizer
16
+ from safetensors.torch import load_file
17
  dtype = torch.bfloat16
18
  device = "cuda" if torch.cuda.is_available() else "cpu"
19
+ # ---------------- Encoders ----------------
20
+
21
+ class HFEmbedder(nn.Module):
22
+ def __init__(self, version: str, max_length: int, **hf_kwargs):
23
+ super().__init__()
24
+ self.is_clip = version.startswith("openai")
25
+ self.max_length = max_length
26
+ self.output_key = "pooler_output" if self.is_clip else "last_hidden_state"
27
 
28
+ if self.is_clip:
29
+ self.tokenizer: CLIPTokenizer = CLIPTokenizer.from_pretrained(version, max_length=max_length)
30
+ self.hf_module: CLIPTextModel = CLIPTextModel.from_pretrained(version, **hf_kwargs)
31
+ else:
32
+ self.tokenizer: T5Tokenizer = T5Tokenizer.from_pretrained(version, max_length=max_length)
33
+ self.hf_module: T5EncoderModel = T5EncoderModel.from_pretrained(version, **hf_kwargs)
34
 
35
+ self.hf_module = self.hf_module.eval().requires_grad_(False)
 
36
 
37
+ def forward(self, text: list[str]) -> Tensor:
38
+ batch_encoding = self.tokenizer(
39
+ text,
40
+ truncation=True,
41
+ max_length=self.max_length,
42
+ return_length=False,
43
+ return_overflowing_tokens=False,
44
+ padding="max_length",
45
+ return_tensors="pt",
46
+ )
47
 
48
+ outputs = self.hf_module(
49
+ input_ids=batch_encoding["input_ids"].to(self.hf_module.device),
50
+ attention_mask=None,
51
+ output_hidden_states=False,
52
+ )
53
+ return outputs[self.output_key]
54
 
55
+
56
+ device = "cuda"
57
+ t5 = HFEmbedder("DeepFloyd/t5-v1_1-xxl", max_length=512, torch_dtype=torch.bfloat16).to(device)
58
+ clip = HFEmbedder("openai/clip-vit-large-patch14", max_length=77, torch_dtype=torch.bfloat16).to(device)
59
+ ae = AutoencoderKL.from_pretrained("black-forest-labs/FLUX.1-dev", subfolder="vae", torch_dtype=torch.bfloat16).to(device)
60
+ # quantize(t5, weights=qfloat8)
61
+ # freeze(t5)
62
+
63
+
64
+ # ---------------- Model ----------------
65
+
66
+
67
+ def attention(q: Tensor, k: Tensor, v: Tensor, pe: Tensor) -> Tensor:
68
+ q, k = apply_rope(q, k, pe)
69
+
70
+ x = torch.nn.functional.scaled_dot_product_attention(q, k, v)
71
+ # x = rearrange(x, "B H L D -> B L (H D)")
72
+ x = x.permute(0, 2, 1, 3).reshape(x.size(0), x.size(2), -1)
73
+
74
+ return x
75
+
76
+
77
+ def rope(pos, dim, theta):
78
+ scale = torch.arange(0, dim, 2, dtype=torch.float64, device=pos.device) / dim
79
+ omega = 1.0 / (theta ** scale)
80
+
81
+ # out = torch.einsum("...n,d->...nd", pos, omega)
82
+ out = pos.unsqueeze(-1) * omega.unsqueeze(0)
83
+
84
+ cos_out = torch.cos(out)
85
+ sin_out = torch.sin(out)
86
+ out = torch.stack([cos_out, -sin_out, sin_out, cos_out], dim=-1)
87
+
88
+ # out = rearrange(out, "b n d (i j) -> b n d i j", i=2, j=2)
89
+ b, n, d, _ = out.shape
90
+ out = out.view(b, n, d, 2, 2)
91
+
92
+ return out.float()
93
+
94
+
95
+ def apply_rope(xq: Tensor, xk: Tensor, freqs_cis: Tensor) -> tuple[Tensor, Tensor]:
96
+ xq_ = xq.float().reshape(*xq.shape[:-1], -1, 1, 2)
97
+ xk_ = xk.float().reshape(*xk.shape[:-1], -1, 1, 2)
98
+ xq_out = freqs_cis[..., 0] * xq_[..., 0] + freqs_cis[..., 1] * xq_[..., 1]
99
+ xk_out = freqs_cis[..., 0] * xk_[..., 0] + freqs_cis[..., 1] * xk_[..., 1]
100
+ return xq_out.reshape(*xq.shape).type_as(xq), xk_out.reshape(*xk.shape).type_as(xk)
101
+
102
+
103
+ class EmbedND(nn.Module):
104
+ def __init__(self, dim: int, theta: int, axes_dim: list[int]):
105
+ super().__init__()
106
+ self.dim = dim
107
+ self.theta = theta
108
+ self.axes_dim = axes_dim
109
+
110
+ def forward(self, ids: Tensor) -> Tensor:
111
+ n_axes = ids.shape[-1]
112
+ emb = torch.cat(
113
+ [rope(ids[..., i], self.axes_dim[i], self.theta) for i in range(n_axes)],
114
+ dim=-3,
115
+ )
116
+
117
+ return emb.unsqueeze(1)
118
+
119
+
120
+ def timestep_embedding(t: Tensor, dim, max_period=10000, time_factor: float = 1000.0):
121
+ """
122
+ Create sinusoidal timestep embeddings.
123
+ :param t: a 1-D Tensor of N indices, one per batch element.
124
+ These may be fractional.
125
+ :param dim: the dimension of the output.
126
+ :param max_period: controls the minimum frequency of the embeddings.
127
+ :return: an (N, D) Tensor of positional embeddings.
128
+ """
129
+ t = time_factor * t
130
+ half = dim // 2
131
 
132
+ # Do not block CUDA steam, but having about 1e-4 differences with Flux official codes:
133
+ # freqs = torch.exp(-math.log(max_period) * torch.arange(start=0, end=half, dtype=torch.float32, device=t.device) / half)
134
+
135
+ # Block CUDA steam, but consistent with official codes:
136
+ freqs = torch.exp(-math.log(max_period) * torch.arange(start=0, end=half, dtype=torch.float32) / half).to(t.device)
137
+
138
+ args = t[:, None].float() * freqs[None]
139
+ embedding = torch.cat([torch.cos(args), torch.sin(args)], dim=-1)
140
+ if dim % 2:
141
+ embedding = torch.cat([embedding, torch.zeros_like(embedding[:, :1])], dim=-1)
142
+ if torch.is_floating_point(t):
143
+ embedding = embedding.to(t)
144
+ return embedding
145
+
146
+
147
+ class MLPEmbedder(nn.Module):
148
+ def __init__(self, in_dim: int, hidden_dim: int):
149
+ super().__init__()
150
+ self.in_layer = nn.Linear(in_dim, hidden_dim, bias=True)
151
+ self.silu = nn.SiLU()
152
+ self.out_layer = nn.Linear(hidden_dim, hidden_dim, bias=True)
153
+
154
+ def forward(self, x: Tensor) -> Tensor:
155
+ return self.out_layer(self.silu(self.in_layer(x)))
156
+
157
+
158
+ class RMSNorm(torch.nn.Module):
159
+ def __init__(self, dim: int):
160
+ super().__init__()
161
+ self.scale = nn.Parameter(torch.ones(dim))
162
+
163
+ def forward(self, x: Tensor):
164
+ x_dtype = x.dtype
165
+ x = x.float()
166
+ rrms = torch.rsqrt(torch.mean(x**2, dim=-1, keepdim=True) + 1e-6)
167
+ return (x * rrms).to(dtype=x_dtype) * self.scale
168
+
169
+
170
+ class QKNorm(torch.nn.Module):
171
+ def __init__(self, dim: int):
172
+ super().__init__()
173
+ self.query_norm = RMSNorm(dim)
174
+ self.key_norm = RMSNorm(dim)
175
+
176
+ def forward(self, q: Tensor, k: Tensor, v: Tensor) -> tuple[Tensor, Tensor]:
177
+ q = self.query_norm(q)
178
+ k = self.key_norm(k)
179
+ return q.to(v), k.to(v)
180
+
181
+
182
+ class SelfAttention(nn.Module):
183
+ def __init__(self, dim: int, num_heads: int = 8, qkv_bias: bool = False):
184
+ super().__init__()
185
+ self.num_heads = num_heads
186
+ head_dim = dim // num_heads
187
+
188
+ self.qkv = nn.Linear(dim, dim * 3, bias=qkv_bias)
189
+ self.norm = QKNorm(head_dim)
190
+ self.proj = nn.Linear(dim, dim)
191
+
192
+ def forward(self, x: Tensor, pe: Tensor) -> Tensor:
193
+ qkv = self.qkv(x)
194
+ # q, k, v = rearrange(qkv, "B L (K H D) -> K B H L D", K=3, H=self.num_heads)
195
+ B, L, _ = qkv.shape
196
+ qkv = qkv.view(B, L, 3, self.num_heads, -1)
197
+ q, k, v = qkv.permute(2, 0, 3, 1, 4)
198
+ q, k = self.norm(q, k, v)
199
+ x = attention(q, k, v, pe=pe)
200
+ x = self.proj(x)
201
+ return x
202
+
203
+
204
+ @dataclass
205
+ class ModulationOut:
206
+ shift: Tensor
207
+ scale: Tensor
208
+ gate: Tensor
209
+
210
+
211
+ class Modulation(nn.Module):
212
+ def __init__(self, dim: int, double: bool):
213
+ super().__init__()
214
+ self.is_double = double
215
+ self.multiplier = 6 if double else 3
216
+ self.lin = nn.Linear(dim, self.multiplier * dim, bias=True)
217
+
218
+ def forward(self, vec: Tensor) -> tuple[ModulationOut, ModulationOut | None]:
219
+ out = self.lin(nn.functional.silu(vec))[:, None, :].chunk(self.multiplier, dim=-1)
220
+
221
+ return (
222
+ ModulationOut(*out[:3]),
223
+ ModulationOut(*out[3:]) if self.is_double else None,
224
+ )
225
+
226
+
227
+ class DoubleStreamBlock(nn.Module):
228
+ def __init__(self, hidden_size: int, num_heads: int, mlp_ratio: float, qkv_bias: bool = False):
229
+ super().__init__()
230
+
231
+ mlp_hidden_dim = int(hidden_size * mlp_ratio)
232
+ self.num_heads = num_heads
233
+ self.hidden_size = hidden_size
234
+ self.img_mod = Modulation(hidden_size, double=True)
235
+ self.img_norm1 = nn.LayerNorm(hidden_size, elementwise_affine=False, eps=1e-6)
236
+ self.img_attn = SelfAttention(dim=hidden_size, num_heads=num_heads, qkv_bias=qkv_bias)
237
+
238
+ self.img_norm2 = nn.LayerNorm(hidden_size, elementwise_affine=False, eps=1e-6)
239
+ self.img_mlp = nn.Sequential(
240
+ nn.Linear(hidden_size, mlp_hidden_dim, bias=True),
241
+ nn.GELU(approximate="tanh"),
242
+ nn.Linear(mlp_hidden_dim, hidden_size, bias=True),
243
+ )
244
+
245
+ self.txt_mod = Modulation(hidden_size, double=True)
246
+ self.txt_norm1 = nn.LayerNorm(hidden_size, elementwise_affine=False, eps=1e-6)
247
+ self.txt_attn = SelfAttention(dim=hidden_size, num_heads=num_heads, qkv_bias=qkv_bias)
248
+
249
+ self.txt_norm2 = nn.LayerNorm(hidden_size, elementwise_affine=False, eps=1e-6)
250
+ self.txt_mlp = nn.Sequential(
251
+ nn.Linear(hidden_size, mlp_hidden_dim, bias=True),
252
+ nn.GELU(approximate="tanh"),
253
+ nn.Linear(mlp_hidden_dim, hidden_size, bias=True),
254
+ )
255
+
256
+ def forward(self, img: Tensor, txt: Tensor, vec: Tensor, pe: Tensor) -> tuple[Tensor, Tensor]:
257
+ img_mod1, img_mod2 = self.img_mod(vec)
258
+ txt_mod1, txt_mod2 = self.txt_mod(vec)
259
+
260
+ # prepare image for attention
261
+ img_modulated = self.img_norm1(img)
262
+ img_modulated = (1 + img_mod1.scale) * img_modulated + img_mod1.shift
263
+ img_qkv = self.img_attn.qkv(img_modulated)
264
+ # img_q, img_k, img_v = rearrange(img_qkv, "B L (K H D) -> K B H L D", K=3, H=self.num_heads)
265
+ B, L, _ = img_qkv.shape
266
+ H = self.num_heads
267
+ D = img_qkv.shape[-1] // (3 * H)
268
+ img_q, img_k, img_v = img_qkv.view(B, L, 3, H, D).permute(2, 0, 3, 1, 4)
269
+ img_q, img_k = self.img_attn.norm(img_q, img_k, img_v)
270
+
271
+ # prepare txt for attention
272
+ txt_modulated = self.txt_norm1(txt)
273
+ txt_modulated = (1 + txt_mod1.scale) * txt_modulated + txt_mod1.shift
274
+ txt_qkv = self.txt_attn.qkv(txt_modulated)
275
+ # txt_q, txt_k, txt_v = rearrange(txt_qkv, "B L (K H D) -> K B H L D", K=3, H=self.num_heads)
276
+ B, L, _ = txt_qkv.shape
277
+ txt_q, txt_k, txt_v = txt_qkv.view(B, L, 3, H, D).permute(2, 0, 3, 1, 4)
278
+ txt_q, txt_k = self.txt_attn.norm(txt_q, txt_k, txt_v)
279
+
280
+ # run actual attention
281
+ q = torch.cat((txt_q, img_q), dim=2)
282
+ k = torch.cat((txt_k, img_k), dim=2)
283
+ v = torch.cat((txt_v, img_v), dim=2)
284
+
285
+ attn = attention(q, k, v, pe=pe)
286
+ txt_attn, img_attn = attn[:, : txt.shape[1]], attn[:, txt.shape[1] :]
287
+
288
+ # calculate the img bloks
289
+ img = img + img_mod1.gate * self.img_attn.proj(img_attn)
290
+ img = img + img_mod2.gate * self.img_mlp((1 + img_mod2.scale) * self.img_norm2(img) + img_mod2.shift)
291
+
292
+ # calculate the txt bloks
293
+ txt = txt + txt_mod1.gate * self.txt_attn.proj(txt_attn)
294
+ txt = txt + txt_mod2.gate * self.txt_mlp((1 + txt_mod2.scale) * self.txt_norm2(txt) + txt_mod2.shift)
295
+ return img, txt
296
+
297
+
298
+ class SingleStreamBlock(nn.Module):
299
+ """
300
+ A DiT block with parallel linear layers as described in
301
+ https://arxiv.org/abs/2302.05442 and adapted modulation interface.
302
+ """
303
+
304
+ def __init__(
305
+ self,
306
+ hidden_size: int,
307
+ num_heads: int,
308
+ mlp_ratio: float = 4.0,
309
+ qk_scale: float | None = None,
310
+ ):
311
+ super().__init__()
312
+ self.hidden_dim = hidden_size
313
+ self.num_heads = num_heads
314
+ head_dim = hidden_size // num_heads
315
+ self.scale = qk_scale or head_dim**-0.5
316
+
317
+ self.mlp_hidden_dim = int(hidden_size * mlp_ratio)
318
+ # qkv and mlp_in
319
+ self.linear1 = nn.Linear(hidden_size, hidden_size * 3 + self.mlp_hidden_dim)
320
+ # proj and mlp_out
321
+ self.linear2 = nn.Linear(hidden_size + self.mlp_hidden_dim, hidden_size)
322
+
323
+ self.norm = QKNorm(head_dim)
324
+
325
+ self.hidden_size = hidden_size
326
+ self.pre_norm = nn.LayerNorm(hidden_size, elementwise_affine=False, eps=1e-6)
327
+
328
+ self.mlp_act = nn.GELU(approximate="tanh")
329
+ self.modulation = Modulation(hidden_size, double=False)
330
+
331
+ def forward(self, x: Tensor, vec: Tensor, pe: Tensor) -> Tensor:
332
+ mod, _ = self.modulation(vec)
333
+ x_mod = (1 + mod.scale) * self.pre_norm(x) + mod.shift
334
+ qkv, mlp = torch.split(self.linear1(x_mod), [3 * self.hidden_size, self.mlp_hidden_dim], dim=-1)
335
+
336
+ # q, k, v = rearrange(qkv, "B L (K H D) -> K B H L D", K=3, H=self.num_heads)
337
+ qkv = qkv.view(qkv.size(0), qkv.size(1), 3, self.num_heads, self.hidden_size // self.num_heads)
338
+ q, k, v = qkv.permute(2, 0, 3, 1, 4)
339
+ q, k = self.norm(q, k, v)
340
+
341
+ # compute attention
342
+ attn = attention(q, k, v, pe=pe)
343
+ # compute activation in mlp stream, cat again and run second linear layer
344
+ output = self.linear2(torch.cat((attn, self.mlp_act(mlp)), 2))
345
+ return x + mod.gate * output
346
 
347
+
348
+ class LastLayer(nn.Module):
349
+ def __init__(self, hidden_size: int, patch_size: int, out_channels: int):
350
+ super().__init__()
351
+ self.norm_final = nn.LayerNorm(hidden_size, elementwise_affine=False, eps=1e-6)
352
+ self.linear = nn.Linear(hidden_size, patch_size * patch_size * out_channels, bias=True)
353
+ self.adaLN_modulation = nn.Sequential(nn.SiLU(), nn.Linear(hidden_size, 2 * hidden_size, bias=True))
354
+
355
+ def forward(self, x: Tensor, vec: Tensor) -> Tensor:
356
+ shift, scale = self.adaLN_modulation(vec).chunk(2, dim=1)
357
+ x = (1 + scale[:, None, :]) * self.norm_final(x) + shift[:, None, :]
358
+ x = self.linear(x)
359
+ return x
360
+
361
+
362
+ class FluxParams:
363
+ in_channels: int = 64
364
+ vec_in_dim: int = 768
365
+ context_in_dim: int = 4096
366
+ hidden_size: int = 3072
367
+ mlp_ratio: float = 4.0
368
+ num_heads: int = 24
369
+ depth: int = 19
370
+ depth_single_blocks: int = 38
371
+ axes_dim: list = [16, 56, 56]
372
+ theta: int = 10_000
373
+ qkv_bias: bool = True
374
+ guidance_embed: bool = True
375
+
376
+
377
+ class Flux(nn.Module):
378
+ """
379
+ Transformer model for flow matching on sequences.
380
+ """
381
+
382
+ def __init__(self, params = FluxParams()):
383
+ super().__init__()
384
+
385
+ self.params = params
386
+ self.in_channels = params.in_channels
387
+ self.out_channels = self.in_channels
388
+ if params.hidden_size % params.num_heads != 0:
389
+ raise ValueError(
390
+ f"Hidden size {params.hidden_size} must be divisible by num_heads {params.num_heads}"
391
  )
392
+ pe_dim = params.hidden_size // params.num_heads
393
+ if sum(params.axes_dim) != pe_dim:
394
+ raise ValueError(f"Got {params.axes_dim} but expected positional dim {pe_dim}")
395
+ self.hidden_size = params.hidden_size
396
+ self.num_heads = params.num_heads
397
+ self.pe_embedder = EmbedND(dim=pe_dim, theta=params.theta, axes_dim=params.axes_dim)
398
+ self.img_in = nn.Linear(self.in_channels, self.hidden_size, bias=True)
399
+ self.time_in = MLPEmbedder(in_dim=256, hidden_dim=self.hidden_size)
400
+ self.vector_in = MLPEmbedder(params.vec_in_dim, self.hidden_size)
401
+ # self.guidance_in = (
402
+ # MLPEmbedder(in_dim=256, hidden_dim=self.hidden_size) if params.guidance_embed else nn.Identity()
403
+ # )
404
+ self.txt_in = nn.Linear(params.context_in_dim, self.hidden_size)
405
+
406
+ self.double_blocks = nn.ModuleList(
407
+ [
408
+ DoubleStreamBlock(
409
+ self.hidden_size,
410
+ self.num_heads,
411
+ mlp_ratio=params.mlp_ratio,
412
+ qkv_bias=params.qkv_bias,
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
413
  )
414
+ for _ in range(params.depth)
415
+ ]
416
+ )
417
+
418
+ self.single_blocks = nn.ModuleList(
419
+ [
420
+ SingleStreamBlock(self.hidden_size, self.num_heads, mlp_ratio=params.mlp_ratio)
421
+ for _ in range(params.depth_single_blocks)
422
+ ]
423
+ )
424
+
425
+ self.final_layer = LastLayer(self.hidden_size, 1, self.out_channels)
426
+
427
+ def forward(
428
+ self,
429
+ img: Tensor,
430
+ img_ids: Tensor,
431
+ txt: Tensor,
432
+ txt_ids: Tensor,
433
+ timesteps: Tensor,
434
+ y: Tensor,
435
+ guidance: Tensor | None = None,
436
+ use_guidance_vec = True,
437
+ ) -> Tensor:
438
+ if img.ndim != 3 or txt.ndim != 3:
439
+ raise ValueError("Input img and txt tensors must have 3 dimensions.")
440
+
441
+ # running on sequences img
442
+ img = self.img_in(img)
443
+ vec = self.time_in(timestep_embedding(timesteps, 256))
444
+ # if self.params.guidance_embed and use_guidance_vec:
445
+ # if guidance is None:
446
+ # raise ValueError("Didn't get guidance strength for guidance distilled model.")
447
+ # vec = vec + self.guidance_in(timestep_embedding(guidance, 256))
448
+ vec = vec + self.vector_in(y)
449
+ txt = self.txt_in(txt)
450
+
451
+ ids = torch.cat((txt_ids, img_ids), dim=1)
452
+ pe = self.pe_embedder(ids)
453
+
454
+ for block in self.double_blocks:
455
+ img, txt = block(img=img, txt=txt, vec=vec, pe=pe)
456
+
457
+ img = torch.cat((txt, img), 1)
458
+ for block in self.single_blocks:
459
+ img = block(img, vec=vec, pe=pe)
460
+ img = img[:, txt.shape[1] :, ...]
461
+
462
+ img = self.final_layer(img, vec) # (N, T, patch_size ** 2 * out_channels)
463
+ return img
464
+
465
+
466
+ def prepare(t5: HFEmbedder, clip: HFEmbedder, img: Tensor, prompt: str | list[str]) -> dict[str, Tensor]:
467
+ bs, c, h, w = img.shape
468
+ if bs == 1 and not isinstance(prompt, str):
469
+ bs = len(prompt)
470
+
471
+ img = rearrange(img, "b c (h ph) (w pw) -> b (h w) (c ph pw)", ph=2, pw=2)
472
+ if img.shape[0] == 1 and bs > 1:
473
+ img = repeat(img, "1 ... -> bs ...", bs=bs)
474
+
475
+ img_ids = torch.zeros(h // 2, w // 2, 3)
476
+ img_ids[..., 1] = img_ids[..., 1] + torch.arange(h // 2)[:, None]
477
+ img_ids[..., 2] = img_ids[..., 2] + torch.arange(w // 2)[None, :]
478
+ img_ids = repeat(img_ids, "h w c -> b (h w) c", b=bs)
479
+
480
+ if isinstance(prompt, str):
481
+ prompt = [prompt]
482
+ txt = t5(prompt)
483
+ if txt.shape[0] == 1 and bs > 1:
484
+ txt = repeat(txt, "1 ... -> bs ...", bs=bs)
485
+ txt_ids = torch.zeros(bs, txt.shape[1], 3)
486
+
487
+ vec = clip(prompt)
488
+ if vec.shape[0] == 1 and bs > 1:
489
+ vec = repeat(vec, "1 ... -> bs ...", bs=bs)
490
+
491
+ return {
492
+ "img": img,
493
+ "img_ids": img_ids.to(img.device),
494
+ "txt": txt.to(img.device),
495
+ "txt_ids": txt_ids.to(img.device),
496
+ "vec": vec.to(img.device),
497
+ }
498
+
499
+
500
+ def time_shift(mu: float, sigma: float, t: Tensor):
501
+ return math.exp(mu) / (math.exp(mu) + (1 / t - 1) ** sigma)
502
+
503
+
504
+ def get_lin_function(
505
+ x1: float = 256, y1: float = 0.5, x2: float = 4096, y2: float = 1.15
506
+ ) -> Callable[[float], float]:
507
+ m = (y2 - y1) / (x2 - x1)
508
+ b = y1 - m * x1
509
+ return lambda x: m * x + b
510
+
511
+
512
+ def get_schedule(
513
+ num_steps: int,
514
+ image_seq_len: int,
515
+ base_shift: float = 0.5,
516
+ max_shift: float = 1.15,
517
+ shift: bool = True,
518
+ ) -> list[float]:
519
+ # extra step for zero
520
+ timesteps = torch.linspace(1, 0, num_steps + 1)
521
+
522
+ # shifting the schedule to favor high timesteps for higher signal images
523
+ if shift:
524
+ # eastimate mu based on linear estimation between two points
525
+ mu = get_lin_function(y1=base_shift, y2=max_shift)(image_seq_len)
526
+ timesteps = time_shift(mu, 1.0, timesteps)
527
+
528
+ return timesteps.tolist()
529
+
530
+
531
+ def denoise(
532
+ model: Flux,
533
+ # model input
534
+ img: Tensor,
535
+ img_ids: Tensor,
536
+ txt: Tensor,
537
+ txt_ids: Tensor,
538
+ vec: Tensor,
539
+ # sampling parameters
540
+ timesteps: list[float],
541
+ guidance: float = 4.0,
542
+ use_cfg_guidance = False,
543
+ ):
544
+ # this is ignored for schnell
545
+ guidance_vec = torch.full((img.shape[0],), guidance, device=img.device, dtype=img.dtype)
546
+ for t_curr, t_prev in tqdm(zip(timesteps[:-1], timesteps[1:])):
547
+ t_vec = torch.full((img.shape[0],), t_curr, dtype=img.dtype, device=img.device)
548
+
549
+ if use_cfg_guidance:
550
+ half_x = img[:len(img)//2]
551
+ img = torch.cat([half_x, half_x], dim=0)
552
+ t_vec = torch.full((img.shape[0],), t_curr, dtype=img.dtype, device=img.device)
553
 
554
+ pred = model(
555
+ img=img,
556
+ img_ids=img_ids,
557
+ txt=txt,
558
+ txt_ids=txt_ids,
559
+ y=vec,
560
+ timesteps=t_vec,
561
+ guidance=guidance_vec,
562
+ use_guidance_vec=not use_cfg_guidance,
563
  )
564
+
565
+ if use_cfg_guidance:
566
+ uncond, cond = pred.chunk(2, dim=0)
567
+ model_output = uncond + guidance * (cond - uncond)
568
+ pred = torch.cat([model_output, model_output], dim=0)
569
+
570
+ img = img + (t_prev - t_curr) * pred
571
+
572
+ return img
573
 
574
+
575
+ def unpack(x: Tensor, height: int, width: int) -> Tensor:
576
+ return rearrange(
577
+ x,
578
+ "b (h w) (c ph pw) -> b c (h ph) (w pw)",
579
+ h=math.ceil(height / 16),
580
+ w=math.ceil(width / 16),
581
+ ph=2,
582
+ pw=2,
583
  )
584
 
585
+ @dataclass
586
+ class SamplingOptions:
587
+ prompt: str
588
+ width: int
589
+ height: int
590
+ guidance: float
591
+ seed: int | None
592
+
593
+
594
+ def get_image(image) -> torch.Tensor | None:
595
+ if image is None:
596
+ return None
597
+ image = Image.fromarray(image).convert("RGB")
598
+
599
+ transform = transforms.Compose([
600
+ transforms.ToTensor(),
601
+ transforms.Lambda(lambda x: 2.0 * x - 1.0),
602
+ ])
603
+ img: torch.Tensor = transform(image)
604
+ return img[None, ...]
605
+
606
+
607
+ # ---------------- Demo ----------------
608
+
609
+
610
+ class EmptyInitWrapper(torch.overrides.TorchFunctionMode):
611
+ def __init__(self, device=None):
612
+ self.device = device
613
+
614
+ def __torch_function__(self, func, types, args=(), kwargs=None):
615
+ kwargs = kwargs or {}
616
+ if getattr(func, "__module__", None) == "torch.nn.init":
617
+ if "tensor" in kwargs:
618
+ return kwargs["tensor"]
619
+ else:
620
+ return args[0]
621
+ if (
622
+ self.device is not None
623
+ and func in torch.utils._device._device_constructors()
624
+ and kwargs.get("device") is None
625
+ ):
626
+ kwargs["device"] = self.device
627
+ return func(*args, **kwargs)
628
+
629
+ with EmptyInitWrapper():
630
+ model = Flux().to(dtype=torch.bfloat16, device="cuda")
631
+ sd = load_file("./consolidated_s6700.safetensors")
632
+ sd = {k.replace("model.", ""): v for k, v in sd.items()}
633
+ result = model.load_state_dict(sd)
634
+
635
+ @spaces.GPU(duration=70)
636
+ @torch.no_grad()
637
+ def generate_image(
638
+ prompt, neg_prompt, width, height, guidance, seed,
639
+ do_img2img, init_image, image2image_strength, resize_img,
640
+ progress=gr.Progress(track_tqdm=True),
641
+ ):
642
+ if seed == 0:
643
+ seed = int(random.random() * 1000000)
644
+
645
+ device = "cuda" if torch.cuda.is_available() else "cpu"
646
+ torch_device = torch.device(device)
647
+
648
+ if do_img2img and init_image is not None:
649
+ init_image = get_image(init_image)
650
+ if resize_img:
651
+ init_image = torch.nn.functional.interpolate(init_image, (height, width))
652
+ else:
653
+ h, w = init_image.shape[-2:]
654
+ init_image = init_image[..., : 16 * (h // 16), : 16 * (w // 16)]
655
+ height = init_image.shape[-2]
656
+ width = init_image.shape[-1]
657
+ init_image = ae.encode(init_image.to(torch_device)).latent_dist.sample()
658
+ init_image = (init_image - ae.config.shift_factor) * ae.config.scaling_factor
659
+
660
+ generator = torch.Generator(device=device).manual_seed(seed)
661
+ x = torch.randn(1, 16, 2 * math.ceil(height / 16), 2 * math.ceil(width / 16), device=device, dtype=torch.bfloat16, generator=generator)
662
+
663
+ num_steps = 28
664
+ timesteps = get_schedule(num_steps, (x.shape[-1] * x.shape[-2]) // 4, shift=True)
665
+
666
+ if do_img2img and init_image is not None:
667
+ t_idx = int((1 - image2image_strength) * num_steps)
668
+ t = timesteps[t_idx]
669
+ timesteps = timesteps[t_idx:]
670
+ x = t * x + (1.0 - t) * init_image.to(x.dtype)
671
+
672
+ inp = prepare(t5=t5, clip=clip, img=x, prompt=[neg_prompt, prompt])
673
+ x = denoise(model, **inp, timesteps=timesteps, guidance=guidance, use_cfg_guidance=True)
674
+
675
+ # with profile(activities=[ProfilerActivity.CPU],record_shapes=True,profile_memory=True) as prof:
676
+ # print(prof.key_averages().table(sort_by="cpu_time_total", row_limit=20))
677
+
678
+ x = unpack(x.float(), height, width)
679
+ with torch.autocast(device_type=torch_device.type, dtype=torch.bfloat16):
680
+ x = x = (x / ae.config.scaling_factor) + ae.config.shift_factor
681
+ x = ae.decode(x).sample
682
+
683
+ x = x.clamp(-1, 1)
684
+ x = rearrange(x[0], "c h w -> h w c")
685
+ img = Image.fromarray((127.5 * (x + 1.0)).cpu().byte().numpy())
686
+
687
+ return img, seed
688
+
689
+ def create_demo():
690
+ with gr.Blocks(theme="bethecloud/storj_theme") as demo:
691
+ with gr.Row():
692
+ with gr.Column():
693
+ prompt = gr.Textbox(label="Prompt", value="a photo of a forest with mist swirling around the tree trunks. The word 'FLUX' is painted over it in big, red brush strokes with visible texture")
694
+ neg_prompt = gr.Textbox(label="Negative Prompt", value="bad photo")
695
+ width = gr.Slider(minimum=128, maximum=2048, step=64, label="Width", value=1360)
696
+ height = gr.Slider(minimum=128, maximum=2048, step=64, label="Height", value=768)
697
+ guidance = gr.Slider(minimum=1.0, maximum=5.0, step=0.1, label="Guidance", value=3.5)
698
+ seed = gr.Number(label="Seed", precision=-1)
699
+ do_img2img = gr.Checkbox(label="Image to Image", value=False)
700
+ init_image = gr.Image(label="Input Image", visible=False)
701
+ image2image_strength = gr.Slider(minimum=0.0, maximum=1.0, step=0.01, label="Noising strength", value=0.8, visible=False)
702
+ resize_img = gr.Checkbox(label="Resize image", value=True, visible=False)
703
+ generate_button = gr.Button("Generate")
704
+
705
+ with gr.Column():
706
+ output_image = gr.Image(label="Generated Image")
707
+ output_seed = gr.Text(label="Used Seed")
708
+
709
+ do_img2img.change(
710
+ fn=lambda x: [gr.update(visible=x), gr.update(visible=x), gr.update(visible=x)],
711
+ inputs=[do_img2img],
712
+ outputs=[init_image, image2image_strength, resize_img]
713
+ )
714
+
715
+ generate_button.click(
716
+ fn=generate_image,
717
+ inputs=[prompt, neg_prompt, width, height, guidance, seed, do_img2img, init_image, image2image_strength, resize_img],
718
+ outputs=[output_image, output_seed]
719
+ )
720
+
721
+ examples = [
722
+ "a tiny astronaut hatching from an egg on the moon",
723
+ "a cat holding a sign that says hello world",
724
+ "an anime illustration of a wiener schnitzel",
725
+ ]
726
+
727
+ return demo
728
+
729
+ demo = create_demo()
730
+ demo.launch(share=True)