AlekseyCalvin commited on
Commit
24f6fdf
1 Parent(s): cf0b1d3

Create app.py

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