-
Notifications
You must be signed in to change notification settings - Fork 1
/
quickdif.py
2231 lines (1942 loc) · 77.5 KB
/
quickdif.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
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
94
95
96
97
98
99
100
101
102
103
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
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
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
250
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
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
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
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
399
400
401
402
403
404
405
406
407
408
409
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
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
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
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
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
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import argparse
import enum
import functools
import gc
import json
import os
import random
import re
import signal
import tomllib
from collections import OrderedDict
from contextlib import nullcontext
from copy import copy
from dataclasses import dataclass
from inspect import getmembers, signature
from io import BytesIO, UnsupportedOperation
from math import copysign
from pathlib import Path
from typing import Any, Callable
import numpy as np
import numpy.linalg as npl
from PIL import Image, ImageDraw, PngImagePlugin
from tqdm import tqdm
# LATENT COLORS {{{
# Auto-generated by latent_colors.py
COLS_FLUX = {'black': [-0.5078, -3.6922, -0.0828, -0.1686, -0.3088, -0.0380, -3.7931, 2.5188, -0.6338, -2.7876, -2.1070, -1.9136, -4.1296, 3.3386, 2.6405, 3.1277], 'white': [0.0357, 5.3646, -0.0003, 0.5294, 0.1117, -1.2432, 4.8129, -3.1450, 0.6049, 2.2375, 0.5748, 1.6056, 3.1637, -2.3134, -1.6879, -2.8735], 'red': [-2.7140, -1.4865, 4.0531, -0.4655, 0.2901, -1.9045, -2.1971, 2.7449, -1.9715, 2.2922, -3.0625, 2.2470, -0.7138, -1.5384, 2.6211, -0.1633], 'green': [-0.0527, 0.1779, -3.6351, -1.2372, 1.2649, 1.4261, 0.7553, -0.1153, -1.2478, 1.4677, 1.2485, -1.8668, -1.5345, 4.0122, -2.1648, 0.6987], 'blue': [2.2819, -0.8316, 0.1640, 2.4340, -1.8938, 0.2222, -0.1094, -0.9054, 3.5686, -5.1504, -1.2512, 0.2937, -0.5832, -1.3483, 1.5569, 1.7113], 'cyan': [2.0891, 1.9905, -4.1953, 0.5869, 0.0342, 1.8687, 2.5570, -2.5583, 2.4889, -1.9973, 2.1053, -1.3774, 0.0569, 1.6881, -2.4823, 0.5310], 'magenta': [0.5596, 0.5332, 3.2740, 1.2936, -1.3963, -1.5772, -0.2316, 0.3176, 1.3821, -1.3756, -2.3867, 2.6160, 1.1095, -4.1404, 2.1839, -0.2943], 'yellow': [-3.1145, 1.5895, -0.2401, -1.8268, 2.1619, -0.2006, 0.9635, 0.5971, -3.5229, 5.7695, 0.1277, 0.4292, -0.2327, 1.4972, -1.6908, -1.6265]} # fmt: off
COLS_FTMSE = {'black': [-0.9453, -2.5903, 1.1441, 1.3093], 'white': [2.1722, 1.3788, 0.0189, -1.1168], 'red': [1.2663, -0.8831, -1.8309, 0.7889], 'green': [0.7963, 0.7862, 2.3592, 1.8182], 'blue': [-0.6164, -2.9997, 0.9888, -1.3812], 'cyan': [0.6160, -0.1680, 2.9445, -0.0890], 'magenta': [0.7240, -1.5543, -1.3407, -1.4365], 'yellow': [2.3246, 1.9687, -0.0343, 1.6547]} # fmt: off
COLS_SD3 = {'black': [0.3509, -0.8920, -2.2919, -3.0386, 1.4051, -2.2471, -2.5398, -3.2714, 1.4144, 1.0222, -0.9082, -0.4731, -0.9010, 0.1464, 1.3631, 2.3277], 'white': [1.0282, -0.1147, 0.4672, 2.9856, 1.1010, 1.7535, 1.1014, 0.4585, -1.8682, 0.4737, 2.4779, 1.0348, 2.2727, -2.7473, -2.2652, -2.0885], 'red': [-1.2336, -2.0950, 1.1345, -0.1707, 2.9720, -2.8930, 0.8448, -5.1268, -0.5644, -0.5753, -0.3743, -1.1464, -0.8674, -0.4272, -0.2791, 0.6347], 'green': [-0.3974, -0.3626, -1.2440, -2.4115, 1.6257, 2.8064, -2.8260, -0.2319, -0.9973, 2.6148, 0.3199, 3.0879, -0.4664, 1.1531, -0.1449, 0.0310], 'blue': [3.5085, 0.6137, -2.6202, -0.1158, -0.8172, -2.8193, -1.1915, -0.2080, 2.5434, -0.2385, 0.1244, -2.2176, 1.2519, -3.0926, 0.4874, 1.7917], 'cyan': [2.2470, 1.0731, -2.5293, -0.4778, -0.6188, 2.3334, -2.5954, 2.2607, 0.0724, 1.9722, 1.5294, 1.9695, 1.9248, -1.8836, -0.4036, -0.4871], 'magenta': [1.7010, -0.5941, 0.0239, 2.5945, 0.4832, -3.6681, 1.8616, -2.2589, 0.9498, -1.7815, 0.6009, -3.1938, 1.2960, -3.0539, -0.8390, 0.5577], 'yellow': [-1.6557, -1.6916, 1.7513, -0.2433, 3.1708, 1.9903, -0.2312, -2.4153, -2.7154, 1.3859, 1.0528, 2.5863, -0.2995, 0.3382, -1.3912, -1.2727]} # fmt: off
COLS_XL = {'black': [-2.8325, 0.5036, 0.3537, 0.3401], 'white': [2.3400, 0.2188, 1.2240, -1.0676], 'red': [-2.5746, -2.5922, 1.4629, -1.6051], 'green': [-0.4603, 1.8433, 3.5376, 1.1637], 'blue': [0.0598, 2.1372, -2.2897, 0.5443], 'cyan': [1.6232, 3.4135, 0.6123, 1.0585], 'magenta': [-0.1147, -0.6371, -1.5609, -1.1584], 'yellow': [-0.8686, -1.3799, 4.3088, -1.0480]} # fmt: off
# }}}
# MATRICES {{{
XYZ_M1 = np.array(
# {{{
[
[0.4124, 0.3576, 0.1805],
[0.2126, 0.7152, 0.0722],
[0.0193, 0.1192, 0.9505],
]
).T # }}}
OKLAB_M1 = np.array(
# {{{
[
[0.8189330101, 0.0329845436, 0.0482003018],
[0.3618667424, 0.9293118715, 0.2643662691],
[-0.1288597137, 0.0361456387, 0.6338517070],
]
) # }}}
OKLAB_M2 = np.array(
# {{{
[
[0.2104542553, 1.9779984951, 0.0259040371],
[0.7936177850, -2.4285922050, 0.7827717662],
[-0.0040720468, 0.4505937099, -0.8086757660],
]
) # }}}
# }}}
# UTILS {{{
def addenv(k: str, val: str):
if k not in os.environ:
os.environ[k] = val
def get_suffix(string: str, separator: str = ":::", typing: type = str, default: Any = None) -> tuple[str, Any | None]:
split = string.rsplit(separator, 1)
match len(split):
case 1:
return (string, default)
case 2:
return split[0], typing(split[1])
case _:
raise ValueError(f"Unable to parse separators `{separator}` for value {string}")
def oversample(population: list, k: int):
samples = []
while len(samples) < k:
samples += random.sample(population, min(len(population), k - len(samples)))
assert len(samples) == k
return samples
def splitlist(values: list[str], separator: str = ":::", trim_groups=False, trim_items=True) -> list[list[str]]:
"""Split a list into sub-lists based on a separator.
`trim_groups` will disallow empty sub-lists, while `trim_items` will disallow empty strings."""
results = []
buf = []
last = ""
for v in values:
if v.strip() == separator:
if buf or not trim_groups:
results.append(buf)
buf = []
elif not trim_items or v.strip():
buf.append(v)
last = v
if buf or (not trim_groups and last.strip() == separator):
results.append(buf)
return results
def roundint(n: int | float, step: int) -> int:
if n % step >= step / 2:
return round(n + step - (n % step))
else:
return round(n - (n % step))
def spowf(n: float | int, pow: int | float) -> float:
return copysign(abs(n) ** pow, n)
def spowf_np(array: np.ndarray, pow: int | float | list[int | float]) -> np.ndarray:
return np.copysign(abs(array) ** pow, array)
def lrgb_to_oklab(array: np.ndarray) -> np.ndarray:
return (spowf_np(array @ (XYZ_M1 @ OKLAB_M1), 1 / 3)) @ OKLAB_M2
def oklab_to_lrgb(array: np.ndarray) -> np.ndarray:
return spowf_np((array @ npl.inv(OKLAB_M2)), 3) @ npl.inv(XYZ_M1 @ OKLAB_M1)
# }}}
# pexpand {{{
@functools.cache
def _pexpand_bounds(string: str, body: tuple[str, str]) -> None | tuple[int, int]:
start = len(string) + 1
end = 0
escape = False
for n, c in enumerate(string):
if escape:
escape = False
continue
elif c == "\\":
escape = True
continue
elif c == body[0]:
start = n
elif c == body[1]:
end = n
if end > start:
return (start, end)
return None
def _pexpand(prompt: str, body: tuple[str, str] = ("{", "}"), sep: str = "|", single: bool = False) -> list[str]:
bounds = _pexpand_bounds(prompt, body)
# Split first body; first close after last open
if bounds is not None:
prefix = prompt[: bounds[0]]
suffix = prompt[bounds[1] + 1 :]
values = []
current = ""
escape = False
for c in prompt[bounds[0] + 1 : bounds[1]]:
if escape:
current += c
escape = False
continue
elif c == "\\":
escape = True
if c == sep and not escape:
values.append(current)
current = ""
else:
current += c
values.append(current)
if single:
values = [random.choice(values)]
results = [prefix + v + suffix for v in values]
else:
results = [prompt]
# Recurse on unexpanded bodies
results, iter = [], results
for result in iter:
if _pexpand_bounds(result, body) is None:
results.append(result)
else:
results += pexpand(result, body, sep, single)
if single:
results = [random.choice(results)]
results[:] = dict.fromkeys(results)
return [result.replace("\\\\", "\x1a").replace("\\", "").replace("\x1a", "\\") for result in results]
@functools.cache
def _pexpand_cache(*args, **kwargs):
return _pexpand(*args, **kwargs)
def pexpand(prompt: str, body: tuple[str, str] = ("{", "}"), sep: str = "|", single: bool = False) -> list[str]:
if single:
return _pexpand(prompt, body, sep, single)
else:
return _pexpand_cache(prompt, body, sep, single)
# }}}
# Enums {{{
@enum.unique
class Iter(enum.StrEnum):
Basic = enum.auto()
Walk = enum.auto()
Shuffle = enum.auto()
@enum.unique
class Sampler(enum.StrEnum):
Default = enum.auto()
Ddim = enum.auto()
Ddpm = enum.auto()
Euler = enum.auto()
EulerK = enum.auto()
EulerF = enum.auto()
EulerA = enum.auto()
Dpm = enum.auto()
DpmK = enum.auto()
SDpm = enum.auto()
SDpmK = enum.auto()
Dpm2 = enum.auto()
Dpm2K = enum.auto()
SDpm2 = enum.auto()
SDpm2K = enum.auto()
Dpm3 = enum.auto()
Dpm3K = enum.auto()
Unipc = enum.auto()
UnipcK = enum.auto()
Unipc2 = enum.auto()
Unipc2K = enum.auto()
Unipc3 = enum.auto()
Unipc3K = enum.auto()
@enum.unique
class Spacing(enum.StrEnum):
Leading = enum.auto()
Trailing = enum.auto()
Linspace = enum.auto()
@enum.unique
class DType(enum.StrEnum):
F16 = enum.auto()
BF16 = enum.auto()
F32 = enum.auto()
F8 = enum.auto()
F8D = enum.auto()
F6 = enum.auto()
I8 = enum.auto()
I8D = enum.auto()
I4 = enum.auto()
I4D = enum.auto()
U7 = enum.auto()
U6 = enum.auto()
U5 = enum.auto()
U4 = enum.auto()
U3 = enum.auto()
U2 = enum.auto()
U1 = enum.auto()
@property
def torch_dtype(self):
"Returns torch.dtype"
match self:
case DType.F16:
return torch.float16
case DType.BF16:
return torch.bfloat16
case DType.F32:
return torch.float32
# Quantization parent types
# FloatX should use F16 instead
# https://github.com/pytorch/ao/tree/main/torchao/dtypes/floatx
# Does not work on AMD but performance absolutely tanks with bfloat16 casting
# So I'll just leave it in for my 0 Nvidia users.
case DType.F6:
return torch.float16
# Rest need BF16
case _:
return torch.bfloat16
@enum.unique
class Offload(enum.StrEnum):
NONE = enum.auto() # why no assign to None?
Model = enum.auto()
Sequential = enum.auto()
@enum.unique
class NoiseType(enum.StrEnum):
Cpu16 = enum.auto()
Cpu16B = enum.auto()
Cpu32 = enum.auto()
Cuda16 = enum.auto()
Cuda16B = enum.auto()
Cuda32 = enum.auto()
@property
def torch_device(self) -> str:
match self:
case NoiseType.Cpu16 | NoiseType.Cpu16B | NoiseType.Cpu32:
return "cpu"
case NoiseType.Cuda16 | NoiseType.Cuda16B | NoiseType.Cuda32:
return "cuda"
@property
def torch_dtype(self):
"Returns torch.dtype"
match self:
case NoiseType.Cpu16 | NoiseType.Cuda16:
return torch.float16
case NoiseType.Cpu16B | NoiseType.Cuda16B:
return torch.bfloat16
case NoiseType.Cpu32 | NoiseType.Cuda32:
return torch.float32
@enum.unique
class AttentionPatch(enum.StrEnum):
NONE = enum.auto()
Flash = enum.auto()
Triton = enum.auto()
@enum.unique
class SDPB(enum.StrEnum):
Math = enum.auto()
Flash = enum.auto()
Efficient = enum.auto()
CuDNN = enum.auto()
@property
def torch_sdp_backend(self):
"Returns torch.nn.attention.SDPBackend"
match self:
case SDPB.Math:
return SDPBackend.MATH
case SDPB.Flash:
return SDPBackend.FLASH_ATTENTION
case SDPB.Efficient:
return SDPBackend.EFFICIENT_ATTENTION
case SDPB.CuDNN:
return SDPBackend.CUDNN_ATTENTION
case _:
raise ValueError("Unreachable")
@enum.unique
class Compile(enum.StrEnum):
Off = enum.auto()
On = enum.auto()
On_Dyn = enum.auto()
On_Full = enum.auto()
On_Dyn_Full = enum.auto()
Max = enum.auto()
Max_Dyn = enum.auto()
Max_Full = enum.auto()
Max_Dyn_Full = enum.auto()
RO = enum.auto()
RO_Dyn = enum.auto()
RO_Full = enum.auto()
RO_Dyn_Full = enum.auto()
@property
def kwargs(self) -> dict[str, Any]:
result = {}
if self in [
Compile.On_Dyn,
Compile.On_Dyn_Full,
Compile.Max_Dyn,
Compile.Max_Dyn_Full,
Compile.RO_Dyn,
Compile.RO_Dyn_Full,
]:
result["dynamic"] = True
if self in [
Compile.On_Full,
Compile.On_Dyn_Full,
Compile.Max_Full,
Compile.Max_Dyn_Full,
Compile.RO_Full,
Compile.RO_Dyn_Full,
]:
result["fullgraph"] = True
if self in [
Compile.Max,
Compile.Max_Dyn,
Compile.Max_Full,
Compile.Max_Dyn_Full,
]:
result["mode"] = "max-autotune"
elif self in [
Compile.RO,
Compile.RO_Dyn,
Compile.RO_Full,
Compile.RO_Dyn_Full,
]:
result["mode"] = "reduce-overhead"
return result
@enum.unique
class LatentColor(enum.StrEnum):
Red = enum.auto()
Green = enum.auto()
Blue = enum.auto()
Cyan = enum.auto()
Magenta = enum.auto()
Yellow = enum.auto()
Black = enum.auto()
White = enum.auto()
# }}}
class Resolution:
# {{{
def __init__(self, resolution: str | tuple[int, int]):
if isinstance(resolution, str):
self._str = resolution
m = re.match(r"^ *([\d\.]+) *: *([\d\.]+) *(?:: *(\d+))? *(?:([@^]) *([\d\.]+))? *$", resolution)
if m:
hor, ver, rnd, method, mpx = m.groups()
hor, ver = float(hor), float(ver)
rnd = 64 if rnd is None else int(rnd)
mpx = 1.0 if mpx is None else float(mpx)
if method == "^":
mpx = mpx * mpx / 10**6
self._width = roundint(spowf(hor / ver * mpx * 10**6, 1 / 2), rnd)
self._height = roundint(spowf(ver / hor * mpx * 10**6, 1 / 2), rnd)
else:
m = re.match(r"^ *(\d+) *[x*]? *(\d+)? *$", resolution)
if m is None:
m = re.match(r"^ *(\d+)? *[x*] *(\d+) *$", resolution)
if m:
w, h = m.groups()
w = 1024 if w is None else int(w)
h = 1024 if h is None else int(h)
self._width, self._height = w, h
else:
raise ValueError
else:
self._str = None
self._width, self._height = resolution
if not (16 <= self.width <= 4096 and 16 <= self.height <= 4096):
raise ValueError
@property
def width(self) -> int:
return self._width
@property
def height(self) -> int:
return self._height
@property
def resolution(self) -> tuple[int, int]:
return (self.width, self.height)
def __repr__(self):
return str(self.width) + "x" + str(self.height)
def __str__(self):
return self._str if self._str is not None else self.__repr__()
# }}}
class Grid:
other_iters = ["resolution", "lora", "dtype"]
# {{{
def __init__(self, axes: None | str | tuple[str | None, str | None]):
self._x = None
self._y = None
self._str = None
if isinstance(axes, str):
m = re.match(r"^ *([A-Za-z_]+)? *?([,:]?) *([A-Za-z_]+)? *$", axes)
if m is None:
raise ValueError
assert m.group(1) is not None or m.group(3) is not None
self._x, self._y = m.group(1), m.group(3)
self._str = axes
elif isinstance(axes, tuple):
self._x, self._y = axes
params = Parameters()
if self._x is not None:
self._x = self._x.casefold()
if self._x == "none":
self._x = None
else:
assert params.get(self._x).meta or self._x in self.other_iters
if self._y is not None:
self._y = self._y.casefold()
if self._y == "none":
self._y = None
else:
assert params.get(self._y).meta or self._y in self.other_iters
@property
def x(self) -> str | None:
return self._x
@property
def y(self) -> str | None:
return self._y
@property
def axes(self) -> tuple[str | None, str | None]:
return (self.x, self.y)
def fold(self, images: list[tuple[dict[str, Any], Image.Image]]) -> tuple[list[Image.Image], list[Image.Image]]:
results: list[Image.Image] = []
# n, x, y
grids: list[list[list[tuple[dict[str, Any], Image.Image]]]] = []
others: list[Image.Image] = []
if self.x is None and self.y is None:
return (results, list(map(lambda t: t[1], images)))
for meta, img in images:
if self.x is not None:
if self.x not in meta:
others.append(img)
continue
if self.y is not None:
if self.y not in meta:
others.append(img)
continue
# Arrange in grid
n = 0
while True:
if len(grids) < (n + 1):
grids.append([[(meta, img)]])
break
# add X
if self.x is not None:
if not any(map(lambda gx: meta[self.x] == gx[0][0][self.x], grids[n])):
grids[n].append([(meta, img)])
break
# add Y
if self.y is not None:
do_break = False
for gx in grids[n]:
if (
# All gx columns unique Y
not any(map(lambda gy: meta[self.y] == gy[0][self.y], gx))
# All gx columns same X
and all(map(lambda gy: meta[self.x] == gy[0][self.x], gx))
):
gx.append((meta, img))
do_break = True
break
if do_break: # gotta love no outer breaks
break
n += 1
# Compile results
base_style = {"fill": (255, 255, 255), "stroke_fill": (0, 0, 0)}
for g in grids:
cells_x = cells_y = cell_w = cell_h = 0
for x in g:
cells_x += 1
cells_y = max(cells_y, len(x))
for y in x:
cell_w = max(cell_w, y[1].width)
cell_h = max(cell_h, y[1].height)
style = base_style | {"font_size": cell_w // 25}
pad = style["font_size"] // 4
style["stroke_width"] = max(1, style["font_size"] // 10)
canvas = Image.new("RGB", (cells_x * cell_w, cells_y * cell_h), (0, 0, 0))
for nx, ix in enumerate(g):
for ny, iy in enumerate(ix):
canvas.paste(
iy[1],
(nx * cell_w + (cell_w - iy[1].width) // 2, ny * cell_h + (cell_h - iy[1].height) // 2),
)
# X labels
if ny == 0 and self.x is not None:
draw = ImageDraw.Draw(canvas)
draw.text((nx * cell_w + pad, ny * cell_h), f"{self.x} : {iy[0][self.x]}", **style)
# Y labels
if nx == 0 and self.y is not None:
draw = ImageDraw.Draw(canvas)
draw.text(
(nx * cell_w + pad, (ny + 1) * cell_h - 5),
f"{self.y} : {iy[0][self.y]}",
anchor="lb",
**style,
)
results.append(canvas)
return results, others
def __repr__(self):
return str(self.x) + ", " + str(self.y)
def __str__(self):
return self._str if self._str is not None else self.__repr__()
# }}}
class QDParam:
# {{{
def __init__(
self,
name: str,
typing: type,
value: Any = None,
short: str | None = None,
help: str | None = None,
multi: bool = False,
meta: bool = False,
positional: bool = False,
):
self.name = name
self.typing = typing
self.help = help
self.short = short
self.multi = multi
self.meta = meta
self.positional = positional
self.value = value
self.default = copy(self.value)
def _cast(self, new):
return new if isinstance(new, self.typing) else self.typing(new)
@property
def value(self) -> Any:
return self._value
@value.setter
def value(self, new):
if isinstance(new, list):
if len(new) == 0:
new = None
if new is None:
self._value = new
elif isinstance(new, list):
if self.multi:
new = [self._cast(v) for v in new]
self._value = new
else:
raise ValueError(f"Refusing to assign list '{new}' to non-multi QDParam '{self.name}'")
else:
if self.multi:
self._value = [self._cast(new)]
else:
self._value = self._cast(new)
# }}}
class Parameters:
# {{{
### Batching
model = QDParam(
"model",
str,
short="-m",
value="stabilityai/stable-diffusion-xl-base-1.0",
meta=True,
multi=True,
help="Safetensor file or HuggingFace model ID. Append `:::` to denote revision",
)
prompt = QDParam("prompt", str, multi=True, meta=True, positional=True, help="Positive prompt")
negative = QDParam("negative", str, short="-n", multi=True, meta=True, help="Negative prompt")
seed = QDParam("seed", int, short="-e", multi=True, meta=True, help="Seed for RNG")
resolution = QDParam(
"resolution",
Resolution,
short="-r",
multi=True,
help="Resolution in either [width]x[height] or aspect_x:aspect_y[:round][@megapixels|^square] formats.",
)
steps = QDParam(
"steps",
int,
short="-s",
value=30,
multi=True,
meta=True,
help="Amount of denoising steps. Prior/Decoder models this only affects the Prior",
)
decoder_steps = QDParam(
"decoder_steps",
int,
short="-ds",
value=-8,
multi=True,
meta=True,
help="Amount of denoising steps for the Decoder if applicable",
)
guidance = QDParam(
"guidance",
float,
short="-g",
value=5.0,
multi=True,
meta=True,
help="CFG/Classier-Free Guidance. Will guide diffusion more strongly towards the prompts. High values will produce unnatural images",
)
decoder_guidance = QDParam(
"decoder_guidance",
float,
short="-dg",
multi=True,
meta=True,
help="Guidance for the Decoder stage if applicable",
)
rescale = QDParam(
"rescale",
float,
short="-G",
value=0.0,
multi=True,
meta=True,
help="Rescale the noise during guidance. Moderate values may help produce more natural images when using strong guidance",
)
pag = QDParam(
"pag",
float,
value=0.0,
multi=True,
meta=True,
help="Perturbed-Attention Guidance scale",
)
denoise = QDParam(
"denoise",
float,
short="-d",
multi=True,
meta=True,
help="Denoising amount for Img2Img. Higher values will change more",
)
noise_type = QDParam(
"noise_type",
NoiseType,
short="-nt",
value=NoiseType.Cpu32,
multi=True,
meta=True,
help="Device and precision to source RNG from. To reproduce seeds from other diffusion programs it may be necessary to change this",
)
noise_power = QDParam(
"noise_power",
float,
short="-np",
multi=True,
meta=True,
help="Multiplier to the initial latent noise if applicable. <1 for smoother, >1 for more details",
)
color = QDParam(
"color",
LatentColor,
short="-C",
value=LatentColor.Black,
multi=True,
meta=True,
help="Color of initial latent noise if applicable. Currently only for XL and SD-FT-MSE latent spaces",
)
color_power = QDParam(
"color_power",
float,
short="-c",
multi=True,
meta=True,
help="Power/opacity of colored latent noise",
)
variance_scale = QDParam(
"variance_scale",
int,
short="-vs",
value=2,
multi=True,
meta=True,
help="Amount of 'zones' for variance noise. '2' will make a 2x2 grid or 4 tiles",
)
variance_power = QDParam(
"variance_power",
float,
short="-vp",
multi=True,
meta=True,
help="Power/opacity for variance noise. Variance noise simply adds randomly generated colored zones to encourage new compositions on overfitted models",
)
power = QDParam(
"power",
float,
multi=True,
meta=True,
help="Simple filter which scales final image values away from gray based on an exponent",
)
pixelate = QDParam(
"pixelate",
float,
multi=True,
meta=True,
help="Pixelate image using a divisor. Best used with a pixel art Lora",
)
posterize = QDParam(
"posterize",
int,
multi=True,
meta=True,
help="Set amount of colors per channel. Best used with --pixelate",
)
sampler = QDParam(
"sampler",
Sampler,
short="-S",
value=Sampler.Default,
multi=True,
meta=True,
help="""Sampler to use in denoising. Naming scheme is as follows:
euler/ddim/etc. - Literal names;
k - Use karras sigmas;
s - Use SDE stochastic noise;
a - Use ancestral sampling;
2/3 - Use 2nd/3rd order sampling;
Ex. 'sdpm2k' is equivalent to 'DPM++ 2M SDE Karras'""",
)
dtype = QDParam(
"dtype",
DType,
short="-dt",
value=DType.F16,
multi=True,
help="Data format for inference. Should be left at FP16 unless the device or model does not work properly",
)
spacing = QDParam(
"spacing",
Spacing,
value=Spacing.Trailing,
multi=True,
meta=True,
help="Sampler timestep spacing",
)
### Global
lora = QDParam("lora", str, short="-l", meta=True, multi=True, help='Apply Loras, ex. "ms_paint.safetensors:::0.6"')
batch_count = QDParam("batch_count", int, short="-b", value=1, help="Behavior dependant on 'iter'")
batch_size = QDParam("batch_size", int, short="-B", value=1, help="Amount of images to produce in each job")
iter = QDParam(
"iter",
Iter,
value=Iter.Basic,
help="""Controls how jobs are created:
'basic' - Run every combination of parameters 'batch_count' times, incrementing seed each 'batch_count';
'walk' - Run every combination of parameters 'batch_count' times, incrementing seed for every individual job;
'shuffle' - Pick randomly from all given parameters 'batch_count' times""",
)
grid = QDParam(
"grid",
Grid,
help="Compile the images into a final grid using up to two parameters, formatted [X or none] ,: [Y or none]",
)
### System
output = QDParam(
"output",
Path,
short="-o",
value=Path("./quickdif_output/"),
help="Output directory for images",
)
offload = QDParam(
"offload",
Offload,
value=Offload.NONE,
help="Set amount of CPU offload. In most UIs, 'model' is equivalent to --med-vram while 'sequential' is equivalent to --low-vram",
)
attn_patch = QDParam(
"attn-patch",
AttentionPatch,
value=AttentionPatch.NONE,
help="""
Patch the SDPA function with a custom external attention processor.
Not compatible with --compile.
AMD Navi 3 users should install `git+https://github.com/ROCm/flash-attention@howiejay/navi_support` and use the `flash` patch for maximum speed""",
)
sdpb = QDParam("sdpb", SDPB, multi=True, help="Override the SDP attention backend(s) to use")
compile = QDParam("compile", Compile, value=Compile.Off, help="Compile network with torch.compile()")
tile = QDParam(
"tile",
bool,
help="Tile VAE. Slicing is already used by default so only set tile if creating very large images",
)
miopen_autotune = QDParam(
"miopen_autotune",
bool,
value=False,
help="""Set whether AMD MIOpen autotuning is enabled.
This only applies if the environment variable `MIOPEN_FIND_MODE` is unset.
For information, see `https://rocmdocs.amd.com/projects/MIOpen/en/latest/how-to/find-and-immediate.html#find-modes`""",
)
comment = QDParam("comment", str, meta=True, help="Add a comment to the image.")
def pairs(self) -> list[tuple[str, QDParam]]:
return [(k, v) for k, v in getmembers(self) if isinstance(v, QDParam)]
def labels(self) -> list[str]:
return list(map(lambda kv: kv[0], self.pairs()))
def params(self) -> list[QDParam]:
return list(map(lambda kv: kv[1], self.pairs()))
def get(self, key: str) -> QDParam: # not __getitem__ because direct field access should be used when possible
for k, v in self.pairs():
if k == key:
return v
raise ValueError
def __contains__(self, key: str) -> bool:
return key in self.labels()
def __setattr__(*args): # Effectively make the class static
raise ValueError
# }}}
def build_parser(parameters: Parameters) -> argparse.ArgumentParser:
# {{{
parser = argparse.ArgumentParser(
description="Quick and easy inference for a variety of Diffusers models. Not all models support all options",
add_help=False,
)
for param in parameters.params():
if param.positional:
flags = [param.name]
else:
flags = [param.short] if param.short else []
flags.append("--" + param.name.replace("_", "-"))
kwargs = {}
help = [param.help]
if isinstance(param.value, list) and len(param.value) == 1:
help += [f'Default "{param.value[0]}"']
elif param.value is not None:
help += [f'Default "{param.value}"']
help = ". ".join([h for h in help if h is not None])
if help:
kwargs["help"] = help
if param.typing is bool and param.multi is False:
kwargs["action"] = argparse.BooleanOptionalAction
else:
kwargs["type"] = param.typing
if issubclass(param.typing, enum.Enum):
kwargs["choices"] = [e.value for e in param.typing]
if param.multi:
kwargs["nargs"] = "*"
else:
kwargs["nargs"] = "?"
parser.add_argument(*flags, **kwargs)
parser.add_argument("-i", "--input", type=argparse.FileType(mode="rb"), help="Input image")
parser.add_argument(
"-I",
"--include",