John6666 commited on
Commit
4306be5
1 Parent(s): 634b26b

Upload app.py

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