-
Notifications
You must be signed in to change notification settings - Fork 13
/
Copy pathsigmas_merge.py
419 lines (355 loc) · 14 KB
/
sigmas_merge.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
import enum
import matplotlib.scale
import torch
from copy import deepcopy
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
from PIL import Image
from io import BytesIO
import numpy as np
from math import *
import comfy.samplers
from scipy.stats import norm
def loglinear_interp(t_steps, num_steps):
"""
Performs log-linear interpolation of a given array of decreasing numbers.
"""
xs = np.linspace(0, 1, len(t_steps))
ys = np.log(t_steps[::-1])
new_xs = np.linspace(0, 1, num_steps)
new_ys = np.interp(new_xs, xs, ys)
interped_ys = np.exp(new_ys)[::-1].copy()
return interped_ys
class GraphScale(enum.StrEnum):
linear = "linear"
log = "log"
def tensor_to_graph_image(tensor, color="blue", scale: GraphScale=GraphScale.linear):
SCALE_FUNCTIONS: dict[str, matplotlib.scale.ScaleBase] = {
GraphScale.linear: matplotlib.scale.LinearScale,
GraphScale.log: matplotlib.scale.LogScale,
}
plt.figure()
plt.plot(tensor.numpy(), marker='o', linestyle='-', color=color)
plt.title("Graph from Tensor")
plt.xlabel("Index")
plt.ylabel("Value")
plt.yscale(scale)
with BytesIO() as buf:
plt.savefig(buf, format='png')
buf.seek(0)
image = Image.open(buf).copy()
plt.close()
return image
def fibonacci_normalized_descending(n):
fib_sequence = [0, 1]
for _ in range(n):
if n > 1:
fib_sequence.append(fib_sequence[-1] + fib_sequence[-2])
max_value = fib_sequence[-1]
normalized_sequence = [x / max_value for x in fib_sequence]
descending_sequence = normalized_sequence[::-1]
return descending_sequence
class sigmas_merge:
def __init__(self):
pass
@classmethod
def INPUT_TYPES(s):
return {
"required": {
"sigmas_1": ("SIGMAS", {"forceInput": True}),
"sigmas_2": ("SIGMAS", {"forceInput": True}),
"proportion_1": ("FLOAT", {"default": 0.5, "min": 0,"max": 1,"step": 0.01})
}
}
FUNCTION = "simple_output"
RETURN_TYPES = ("SIGMAS",)
CATEGORY = "sampling/custom_sampling/sigmas"
def simple_output(self, sigmas_1, sigmas_2, proportion_1):
return (sigmas_1*proportion_1+sigmas_2*(1-proportion_1),)
class sigmas_mult:
def __init__(self):
pass
@classmethod
def INPUT_TYPES(s):
return {
"required": {
"sigmas": ("SIGMAS", {"forceInput": True}),
"factor": ("FLOAT", {"default": 1, "min": 0,"max": 100,"step": 0.01})
}
}
FUNCTION = "simple_output"
RETURN_TYPES = ("SIGMAS",)
CATEGORY = "sampling/custom_sampling/sigmas"
def simple_output(self, sigmas, factor):
return (sigmas*factor,)
class sigmas_to_graph:
def __init__(self):
pass
@classmethod
def INPUT_TYPES(s):
# quick list from comfyroll studio https://github.com/Suzie1/ComfyUI_Comfyroll_CustomNodes/blob/main/nodes/nodes_graphics_filter.py
# that also appears to be based on the Color Tint node by hnmr293
# trimmed of incompatible colors
col = ["black", "red", "green", "blue",
"cyan", "magenta", "yellow", "purple",
"lime", "navy", "teal", "orange",
"maroon", "lavender", "olive"]
scale_options = [option.value for option in GraphScale]
return {
"required": {
"sigmas": ("SIGMAS", {"forceInput": True}),
"color": (col, {"default": "blue"}),
"print_as_list" : ("BOOLEAN", {"default": False}),
"scale": (scale_options, {"default": GraphScale.linear})
}
}
FUNCTION = "simple_output"
RETURN_TYPES = ("IMAGE",)
CATEGORY = "sampling/custom_sampling/sigmas"
def simple_output(self, sigmas, color, print_as_list, scale: GraphScale):
if print_as_list:
print(sigmas.tolist())
sigmas_percentages = ((sigmas-sigmas.min())/(sigmas.max()-sigmas.min())).tolist()
sigmas_percentages_w_steps = [(i,round(s,4)) for i,s in enumerate(sigmas_percentages)]
print(sigmas_percentages_w_steps)
sigmas_graph = tensor_to_graph_image(sigmas.cpu(), color=color, scale=scale)
numpy_image = np.array(sigmas_graph)
numpy_image = numpy_image / 255.0
tensor_image = torch.from_numpy(numpy_image)
tensor_image = tensor_image.unsqueeze(0)
images_tensor = torch.cat([tensor_image], 0)
return (images_tensor,)
class sigmas_concat:
def __init__(self):
pass
@classmethod
def INPUT_TYPES(s):
return {
"required": {
"sigmas_1": ("SIGMAS", {"forceInput": True}),
"sigmas_2": ("SIGMAS", {"forceInput": True}),
"sigmas_1_until": ("INT", {"default": 10, "min": 0,"max": 1000,"step": 1}),
"rescale_sum" : ("BOOLEAN", {"default": False}),
}
}
FUNCTION = "simple_output"
RETURN_TYPES = ("SIGMAS",)
CATEGORY = "sampling/custom_sampling/sigmas"
def simple_output(self, sigmas_1, sigmas_2, sigmas_1_until,rescale_sum):
result = torch.cat((sigmas_1[:sigmas_1_until], sigmas_2[sigmas_1_until:]))
if rescale_sum:
result = result*torch.sum(result).item()/torch.sum(sigmas_1).item()
return (result,)
class the_golden_scheduler:
def __init__(self):
pass
@classmethod
def INPUT_TYPES(s):
return {
"required": {
"model": ("MODEL",),
"steps": ("INT", {"default": 20, "min": 0,"max": 100000,"step": 1}),
"sgm" : ("BOOLEAN", {"default": False}),
}
}
FUNCTION = "simple_output"
RETURN_TYPES = ("SIGMAS",)
CATEGORY = "sampling/custom_sampling/schedulers"
def simple_output(self,model,steps,sgm):
s = model.get_model_object("model_sampling")
sigmin = s.sigma(s.timestep(s.sigma_min))
sigmax = s.sigma(s.timestep(s.sigma_max))
if sgm:
steps+=1
phi = (1 + 5 ** 0.5) / 2
sigmas = [(1-x/(steps-1))**phi*sigmax+(x/(steps-1))**phi*sigmin for x in range(steps)]
if sgm:
sigmas = sigmas[:-1]
sigmas = torch.tensor(sigmas+[0])
return (sigmas,)
class GaussianTailScheduler:
def __init__(self):
pass
@classmethod
def INPUT_TYPES(s):
return {
"required": {
"model": ("MODEL",),
"steps": ("INT", {"default": 20, "min": 0,"max": 100000,"step": 1}),
}
}
FUNCTION = "simple_output"
RETURN_TYPES = ("SIGMAS",)
CATEGORY = "sampling/custom_sampling/schedulers"
def simple_output(self,model,steps):
s = model.model.model_sampling
sigmin = s.sigma(s.timestep(s.sigma_min))
sigmax = s.sigma(s.timestep(s.sigma_max))
sigmas = [(sigmax-sigmin) * 2 * (1 - norm.cdf((x/(steps-1))*3.2905)) + sigmin for x in range(steps)]
sigmas = torch.tensor(sigmas+[0])
return (sigmas,)
class aligned_scheduler:
def __init__(self):
pass
@classmethod
def INPUT_TYPES(s):
return {
"required": {
"model": ("MODEL",),
"steps": ("INT", {"default": 10, "min": 1,"max": 10000,"step": 1}),
# "scheduler": (comfy.samplers.SCHEDULER_NAMES, {"default":"simple"}),
"model_type": (["SD1", "SDXL", "SVD"], ),
"force_sigma_min" : ("BOOLEAN", {"default": False}),
}
}
FUNCTION = "simple_output"
RETURN_TYPES = ("SIGMAS",)
CATEGORY = "sampling/custom_sampling/schedulers"
def simple_output(self, model, steps, model_type, force_sigma_min):
timestep_indices = {"SD1":[999, 850, 736, 645, 545, 455, 343, 233, 124, 24, 0],
"SDXL":[999, 845, 730, 587, 443, 310, 193, 116, 53, 13, 0],
"SVD":[995, 920, 811, 686, 555, 418, 315, 174, 109, 12, 0],}
indices = timestep_indices[model_type]
indices = [999 - i for i in indices]
sigmas = comfy.samplers.calculate_sigmas(model.get_model_object("model_sampling"), "simple", 1000)[indices]
sigmas = loglinear_interp(sigmas.tolist(), steps + 1 if not force_sigma_min else steps)
sigmas = torch.FloatTensor(sigmas)
sigmas = torch.cat([sigmas[:-1] if not force_sigma_min else sigmas, torch.FloatTensor([0.])])
return (sigmas.cpu(),)
class sigmas_min_max_out_node:
def __init__(self):
pass
@classmethod
def INPUT_TYPES(s):
return {
"required": {
"model": ("MODEL",),
}
}
FUNCTION = "simple_output"
RETURN_TYPES = ("FLOAT","FLOAT",)
RETURN_NAMES = ("Sigmas_max","Sigmas_min",)
CATEGORY = "sampling/custom_sampling/sigmas"
def simple_output(self,model):
s = model.get_model_object("model_sampling")
sigmin = s.sigma(s.timestep(s.sigma_min)).item()
sigmax = s.sigma(s.timestep(s.sigma_max)).item()
return (sigmax,sigmin,)
class manual_scheduler:
def __init__(self):
pass
@classmethod
def INPUT_TYPES(s):
return {
"required": {
"model": ("MODEL",),
"custom_sigmas_manual_schedule": ("STRING", {"default": "((1 - cos(2 * pi * (1-y**0.5) * 0.5)) / 2)*sigmax+((1 - cos(2 * pi * y**0.5 * 0.5)) / 2)*sigmin"}),
"steps": ("INT", {"default": 20, "min": 0,"max": 100000,"step": 1}),
"sgm" : ("BOOLEAN", {"default": False}),
}
}
FUNCTION = "simple_output"
RETURN_TYPES = ("SIGMAS",)
CATEGORY = "sampling/custom_sampling/schedulers"
def simple_output(self,model, custom_sigmas_manual_schedule,steps,sgm):
if sgm:
steps+=1
s = model.get_model_object("model_sampling")
sigmin = s.sigma(s.timestep(s.sigma_min))
sigmax = s.sigma(s.timestep(s.sigma_max))
phi = (1 + 5 ** 0.5) / 2
sigmas = []
s = steps
fibo = fibonacci_normalized_descending(s)
for j in range(steps):
y = j/(s-1)
x = 1-y
f = fibo[j]
try:
f = eval(custom_sigmas_manual_schedule)
except:
print("could not evaluate {custom_sigmas_manual_schedule}")
f = 0
sigmas.append(f)
if sgm:
sigmas = sigmas[:-1]
sigmas = torch.tensor(sigmas+[0])
return (sigmas,)
def remap_range_no_clamp(value, minIn, MaxIn, minOut, maxOut):
finalValue = ((value - minIn) / (MaxIn - minIn)) * (maxOut - minOut) + minOut;
return finalValue;
class get_sigma_float:
def __init__(self):
pass
@classmethod
def INPUT_TYPES(s):
return {
"required": {
"model": ("MODEL",),
"sigmas": ("SIGMAS", {"forceInput": True}),
}
}
FUNCTION = "simple_output"
RETURN_TYPES = ("FLOAT",)
CATEGORY = "sampling/custom_sampling/sigmas"
def simple_output(self,sigmas,model):
sigfloat = float((sigmas[0]-sigmas[-1])/model.model.latent_format.scale_factor)
return (sigfloat,)
def remap_range_no_clamp(value, minIn, MaxIn, minOut, maxOut):
finalValue = ((value - minIn) / (MaxIn - minIn)) * (maxOut - minOut) + minOut;
return finalValue;
class sigmas_gradual_merge:
def __init__(self):
pass
@classmethod
def INPUT_TYPES(s):
return {
"required": {
"sigmas_1": ("SIGMAS", {"forceInput": True}),
"sigmas_2": ("SIGMAS", {"forceInput": True}),
"proportion_1": ("FLOAT", {"default": 0.5, "min": 0,"max": 1,"step": 0.01})
}
}
FUNCTION = "simple_output"
RETURN_TYPES = ("SIGMAS",)
CATEGORY = "sampling/custom_sampling/sigmas"
def simple_output(self,sigmas_1,sigmas_2,proportion_1):
result_sigmas = deepcopy(sigmas_1)
for idx,s in enumerate(result_sigmas):
current_factor = remap_range_no_clamp(idx,0,len(result_sigmas)-1,proportion_1,1-proportion_1)
result_sigmas[idx] = sigmas_1[idx]*current_factor+sigmas_2[idx]*(1-current_factor)
return (result_sigmas,)
class multi_sigmas_average:
def __init__(self):
pass
@classmethod
def INPUT_TYPES(s):
sigmas_inputs = {f"sigmas_{X+2}": ("SIGMAS", {"forceInput": True}) for X in range(24)}
return {
"required": {
"sigmas_1": ("SIGMAS", {"forceInput": True}),
},
"optional": sigmas_inputs
}
FUNCTION = "simple_output"
RETURN_TYPES = ("SIGMAS",)
CATEGORY = "sampling/custom_sampling/sigmas"
def simple_output(self,sigmas_1,**kwargs):
tensors = [sigmas_1] + [v for k, v in kwargs.items() if k.startswith('sigmas_')]
result_sigmas = torch.mean(torch.stack(tensors), dim=0)
return (result_sigmas,)
NODE_CLASS_MAPPINGS = {
"Merge sigmas by average": sigmas_merge,
"Merge sigmas gradually": sigmas_gradual_merge,
"Merge many sigmas by average": multi_sigmas_average,
"Multiply sigmas": sigmas_mult,
"Split and concatenate sigmas": sigmas_concat,
"The Golden Scheduler": the_golden_scheduler,
"Gaussian Tail Scheduler": GaussianTailScheduler,
"Aligned Scheduler": aligned_scheduler,
"Manual scheduler": manual_scheduler,
"Get sigmas as float": get_sigma_float,
"Graph sigmas": sigmas_to_graph,
"Output min/max sigmas": sigmas_min_max_out_node,
}