Spaces:
Runtime error
Runtime error
Upload app.py
Browse files
app.py
CHANGED
@@ -1,735 +1,743 @@
|
|
1 |
-
import
|
2 |
-
|
3 |
-
|
4 |
-
|
5 |
-
|
6 |
-
|
7 |
-
|
8 |
-
|
9 |
-
|
10 |
-
|
11 |
-
import
|
12 |
-
from
|
13 |
-
from
|
14 |
-
from
|
15 |
-
|
16 |
-
from
|
17 |
-
|
18 |
-
|
19 |
-
|
20 |
-
|
21 |
-
|
22 |
-
|
23 |
-
|
24 |
-
|
25 |
-
|
26 |
-
|
27 |
-
|
28 |
-
|
29 |
-
|
30 |
-
|
31 |
-
|
32 |
-
|
33 |
-
|
34 |
-
|
35 |
-
|
36 |
-
|
37 |
-
|
38 |
-
|
39 |
-
|
40 |
-
|
41 |
-
|
42 |
-
|
43 |
-
|
44 |
-
|
45 |
-
|
46 |
-
|
47 |
-
|
48 |
-
|
49 |
-
|
50 |
-
|
51 |
-
|
52 |
-
|
53 |
-
|
54 |
-
|
55 |
-
|
56 |
-
|
57 |
-
|
58 |
-
|
59 |
-
|
60 |
-
|
61 |
-
|
62 |
-
|
63 |
-
|
64 |
-
|
65 |
-
|
66 |
-
|
67 |
-
#
|
68 |
-
|
69 |
-
|
70 |
-
|
71 |
-
|
72 |
-
|
73 |
-
|
74 |
-
|
75 |
-
|
76 |
-
|
77 |
-
|
78 |
-
|
79 |
-
|
80 |
-
|
81 |
-
|
82 |
-
|
83 |
-
|
84 |
-
|
85 |
-
|
86 |
-
|
87 |
-
|
88 |
-
|
89 |
-
|
90 |
-
|
91 |
-
|
92 |
-
|
93 |
-
out =
|
94 |
-
|
95 |
-
|
96 |
-
|
97 |
-
|
98 |
-
|
99 |
-
|
100 |
-
|
101 |
-
|
102 |
-
|
103 |
-
return
|
104 |
-
|
105 |
-
|
106 |
-
|
107 |
-
|
108 |
-
|
109 |
-
|
110 |
-
|
111 |
-
|
112 |
-
|
113 |
-
|
114 |
-
|
115 |
-
|
116 |
-
|
117 |
-
|
118 |
-
|
119 |
-
|
120 |
-
|
121 |
-
|
122 |
-
|
123 |
-
|
124 |
-
|
125 |
-
|
126 |
-
|
127 |
-
|
128 |
-
|
129 |
-
|
130 |
-
|
131 |
-
|
132 |
-
|
133 |
-
|
134 |
-
|
135 |
-
|
136 |
-
|
137 |
-
|
138 |
-
|
139 |
-
|
140 |
-
|
141 |
-
|
142 |
-
|
143 |
-
|
144 |
-
|
145 |
-
|
146 |
-
|
147 |
-
|
148 |
-
|
149 |
-
|
150 |
-
|
151 |
-
|
152 |
-
|
153 |
-
|
154 |
-
|
155 |
-
|
156 |
-
|
157 |
-
|
158 |
-
|
159 |
-
|
160 |
-
|
161 |
-
|
162 |
-
|
163 |
-
|
164 |
-
|
165 |
-
|
166 |
-
|
167 |
-
|
168 |
-
|
169 |
-
|
170 |
-
|
171 |
-
|
172 |
-
|
173 |
-
|
174 |
-
def
|
175 |
-
|
176 |
-
|
177 |
-
|
178 |
-
|
179 |
-
|
180 |
-
|
181 |
-
|
182 |
-
|
183 |
-
|
184 |
-
|
185 |
-
|
186 |
-
|
187 |
-
|
188 |
-
|
189 |
-
|
190 |
-
|
191 |
-
|
192 |
-
|
193 |
-
|
194 |
-
|
195 |
-
|
196 |
-
|
197 |
-
|
198 |
-
|
199 |
-
qkv =
|
200 |
-
|
201 |
-
|
202 |
-
|
203 |
-
|
204 |
-
|
205 |
-
|
206 |
-
|
207 |
-
|
208 |
-
|
209 |
-
|
210 |
-
|
211 |
-
|
212 |
-
|
213 |
-
|
214 |
-
|
215 |
-
|
216 |
-
|
217 |
-
|
218 |
-
|
219 |
-
|
220 |
-
|
221 |
-
|
222 |
-
|
223 |
-
|
224 |
-
|
225 |
-
|
226 |
-
|
227 |
-
)
|
228 |
-
|
229 |
-
|
230 |
-
|
231 |
-
|
232 |
-
|
233 |
-
|
234 |
-
|
235 |
-
|
236 |
-
|
237 |
-
|
238 |
-
|
239 |
-
|
240 |
-
|
241 |
-
|
242 |
-
|
243 |
-
|
244 |
-
|
245 |
-
|
246 |
-
)
|
247 |
-
|
248 |
-
|
249 |
-
self.
|
250 |
-
self.
|
251 |
-
|
252 |
-
|
253 |
-
|
254 |
-
|
255 |
-
|
256 |
-
|
257 |
-
)
|
258 |
-
|
259 |
-
|
260 |
-
|
261 |
-
|
262 |
-
|
263 |
-
|
264 |
-
|
265 |
-
|
266 |
-
|
267 |
-
|
268 |
-
|
269 |
-
|
270 |
-
|
271 |
-
|
272 |
-
|
273 |
-
|
274 |
-
|
275 |
-
|
276 |
-
|
277 |
-
|
278 |
-
|
279 |
-
B, L,
|
280 |
-
|
281 |
-
|
282 |
-
|
283 |
-
|
284 |
-
|
285 |
-
|
286 |
-
|
287 |
-
|
288 |
-
|
289 |
-
|
290 |
-
|
291 |
-
#
|
292 |
-
|
293 |
-
|
294 |
-
|
295 |
-
|
296 |
-
|
297 |
-
|
298 |
-
|
299 |
-
|
300 |
-
|
301 |
-
|
302 |
-
|
303 |
-
|
304 |
-
|
305 |
-
|
306 |
-
|
307 |
-
|
308 |
-
|
309 |
-
|
310 |
-
|
311 |
-
|
312 |
-
|
313 |
-
|
314 |
-
|
315 |
-
|
316 |
-
self
|
317 |
-
|
318 |
-
|
319 |
-
|
320 |
-
|
321 |
-
|
322 |
-
|
323 |
-
|
324 |
-
self.
|
325 |
-
|
326 |
-
self.
|
327 |
-
|
328 |
-
self.
|
329 |
-
|
330 |
-
|
331 |
-
|
332 |
-
self.
|
333 |
-
|
334 |
-
|
335 |
-
|
336 |
-
|
337 |
-
|
338 |
-
|
339 |
-
|
340 |
-
|
341 |
-
|
342 |
-
|
343 |
-
|
344 |
-
|
345 |
-
|
346 |
-
|
347 |
-
|
348 |
-
|
349 |
-
|
350 |
-
|
351 |
-
|
352 |
-
|
353 |
-
|
354 |
-
|
355 |
-
|
356 |
-
|
357 |
-
|
358 |
-
|
359 |
-
|
360 |
-
|
361 |
-
|
362 |
-
|
363 |
-
|
364 |
-
|
365 |
-
|
366 |
-
|
367 |
-
|
368 |
-
|
369 |
-
|
370 |
-
|
371 |
-
|
372 |
-
|
373 |
-
|
374 |
-
|
375 |
-
|
376 |
-
|
377 |
-
|
378 |
-
|
379 |
-
|
380 |
-
|
381 |
-
|
382 |
-
|
383 |
-
|
384 |
-
|
385 |
-
|
386 |
-
|
387 |
-
|
388 |
-
|
389 |
-
|
390 |
-
|
391 |
-
|
392 |
-
|
393 |
-
|
394 |
-
|
395 |
-
|
396 |
-
|
397 |
-
|
398 |
-
self.
|
399 |
-
|
400 |
-
|
401 |
-
|
402 |
-
|
403 |
-
|
404 |
-
|
405 |
-
|
406 |
-
|
407 |
-
self.
|
408 |
-
|
409 |
-
self.
|
410 |
-
|
411 |
-
|
412 |
-
|
413 |
-
|
414 |
-
|
415 |
-
|
416 |
-
|
417 |
-
|
418 |
-
|
419 |
-
|
420 |
-
|
421 |
-
|
422 |
-
|
423 |
-
|
424 |
-
|
425 |
-
|
426 |
-
|
427 |
-
|
428 |
-
|
429 |
-
|
430 |
-
|
431 |
-
|
432 |
-
|
433 |
-
|
434 |
-
|
435 |
-
|
436 |
-
|
437 |
-
|
438 |
-
|
439 |
-
|
440 |
-
|
441 |
-
|
442 |
-
|
443 |
-
|
444 |
-
|
445 |
-
|
446 |
-
|
447 |
-
|
448 |
-
|
449 |
-
|
450 |
-
|
451 |
-
|
452 |
-
|
453 |
-
|
454 |
-
|
455 |
-
|
456 |
-
|
457 |
-
for
|
458 |
-
|
459 |
-
|
460 |
-
|
461 |
-
|
462 |
-
|
463 |
-
|
464 |
-
|
465 |
-
|
466 |
-
|
467 |
-
|
468 |
-
|
469 |
-
|
470 |
-
|
471 |
-
|
472 |
-
|
473 |
-
|
474 |
-
|
475 |
-
|
476 |
-
|
477 |
-
|
478 |
-
|
479 |
-
|
480 |
-
|
481 |
-
|
482 |
-
|
483 |
-
if
|
484 |
-
|
485 |
-
|
486 |
-
|
487 |
-
|
488 |
-
|
489 |
-
|
490 |
-
|
491 |
-
if
|
492 |
-
|
493 |
-
|
494 |
-
|
495 |
-
"
|
496 |
-
|
497 |
-
|
498 |
-
|
499 |
-
|
500 |
-
|
501 |
-
|
502 |
-
|
503 |
-
|
504 |
-
|
505 |
-
|
506 |
-
|
507 |
-
|
508 |
-
|
509 |
-
|
510 |
-
|
511 |
-
|
512 |
-
return
|
513 |
-
|
514 |
-
|
515 |
-
def
|
516 |
-
|
517 |
-
|
518 |
-
|
519 |
-
|
520 |
-
|
521 |
-
|
522 |
-
|
523 |
-
|
524 |
-
|
525 |
-
|
526 |
-
|
527 |
-
|
528 |
-
|
529 |
-
|
530 |
-
|
531 |
-
|
532 |
-
|
533 |
-
|
534 |
-
|
535 |
-
|
536 |
-
|
537 |
-
|
538 |
-
|
539 |
-
|
540 |
-
|
541 |
-
|
542 |
-
|
543 |
-
|
544 |
-
|
545 |
-
|
546 |
-
|
547 |
-
|
548 |
-
|
549 |
-
|
550 |
-
|
551 |
-
|
552 |
-
|
553 |
-
|
554 |
-
|
555 |
-
|
556 |
-
|
557 |
-
|
558 |
-
|
559 |
-
|
560 |
-
|
561 |
-
|
562 |
-
|
563 |
-
|
564 |
-
|
565 |
-
|
566 |
-
|
567 |
-
|
568 |
-
|
569 |
-
|
570 |
-
|
571 |
-
|
572 |
-
|
573 |
-
|
574 |
-
|
575 |
-
|
576 |
-
|
577 |
-
|
578 |
-
|
579 |
-
|
580 |
-
|
581 |
-
|
582 |
-
|
583 |
-
|
584 |
-
|
585 |
-
|
586 |
-
|
587 |
-
|
588 |
-
|
589 |
-
|
590 |
-
|
591 |
-
|
592 |
-
|
593 |
-
|
594 |
-
|
595 |
-
|
596 |
-
|
597 |
-
|
598 |
-
|
599 |
-
|
600 |
-
|
601 |
-
|
602 |
-
|
603 |
-
|
604 |
-
|
605 |
-
|
606 |
-
|
607 |
-
|
608 |
-
|
609 |
-
|
610 |
-
|
611 |
-
|
612 |
-
|
613 |
-
|
614 |
-
|
615 |
-
|
616 |
-
|
617 |
-
|
618 |
-
|
619 |
-
|
620 |
-
|
621 |
-
|
622 |
-
|
623 |
-
|
624 |
-
|
625 |
-
|
626 |
-
|
627 |
-
|
628 |
-
|
629 |
-
|
630 |
-
|
631 |
-
|
632 |
-
|
633 |
-
|
634 |
-
|
635 |
-
|
636 |
-
|
637 |
-
|
638 |
-
|
639 |
-
|
640 |
-
|
641 |
-
|
642 |
-
|
643 |
-
|
644 |
-
|
645 |
-
)
|
646 |
-
|
647 |
-
|
648 |
-
|
649 |
-
|
650 |
-
|
651 |
-
|
652 |
-
|
653 |
-
|
654 |
-
|
655 |
-
|
656 |
-
|
657 |
-
|
658 |
-
|
659 |
-
|
660 |
-
|
661 |
-
init_image =
|
662 |
-
|
663 |
-
|
664 |
-
|
665 |
-
|
666 |
-
|
667 |
-
|
668 |
-
|
669 |
-
|
670 |
-
|
671 |
-
|
672 |
-
|
673 |
-
|
674 |
-
|
675 |
-
|
676 |
-
|
677 |
-
|
678 |
-
|
679 |
-
|
680 |
-
|
681 |
-
|
682 |
-
|
683 |
-
|
684 |
-
|
685 |
-
|
686 |
-
|
687 |
-
|
688 |
-
|
689 |
-
|
690 |
-
|
691 |
-
|
692 |
-
|
693 |
-
|
694 |
-
|
695 |
-
|
696 |
-
|
697 |
-
|
698 |
-
|
699 |
-
|
700 |
-
|
701 |
-
|
702 |
-
|
703 |
-
|
704 |
-
|
705 |
-
|
706 |
-
|
707 |
-
|
708 |
-
|
709 |
-
|
710 |
-
|
711 |
-
|
712 |
-
|
713 |
-
|
714 |
-
|
715 |
-
|
716 |
-
|
717 |
-
|
718 |
-
|
719 |
-
|
720 |
-
|
721 |
-
|
722 |
-
|
723 |
-
|
724 |
-
|
725 |
-
|
726 |
-
|
727 |
-
|
728 |
-
|
729 |
-
|
730 |
-
|
731 |
-
|
732 |
-
|
733 |
-
|
734 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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)
|