Outimus commited on
Commit
a825dc7
1 Parent(s): 5121bc4

Upload sd_samplers_kdiffusion.py

Browse files
Files changed (1) hide show
  1. sd_samplers_kdiffusion.py +477 -0
sd_samplers_kdiffusion.py ADDED
@@ -0,0 +1,477 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from collections import deque
2
+ import torch
3
+ import inspect
4
+ import k_diffusion.sampling
5
+ from modules import prompt_parser, devices, sd_samplers_common
6
+
7
+ from modules.shared import opts, state
8
+ import modules.shared as shared
9
+ from modules.script_callbacks import CFGDenoiserParams, cfg_denoiser_callback
10
+ from modules.script_callbacks import CFGDenoisedParams, cfg_denoised_callback
11
+ from modules.script_callbacks import AfterCFGCallbackParams, cfg_after_cfg_callback
12
+
13
+ samplers_k_diffusion = [
14
+ ('Euler a', 'sample_euler_ancestral', ['k_euler_a', 'k_euler_ancestral'], {"uses_ensd": True}),
15
+ ('Euler', 'sample_euler', ['k_euler'], {}),
16
+ ('LMS', 'sample_lms', ['k_lms'], {}),
17
+ ('Heun', 'sample_heun', ['k_heun'], {"second_order": True}),
18
+ ('DPM2', 'sample_dpm_2', ['k_dpm_2'], {'discard_next_to_last_sigma': True}),
19
+ ('DPM2 a', 'sample_dpm_2_ancestral', ['k_dpm_2_a'], {'discard_next_to_last_sigma': True, "uses_ensd": True}),
20
+ ('DPM++ 2S a', 'sample_dpmpp_2s_ancestral', ['k_dpmpp_2s_a'], {"uses_ensd": True, "second_order": True}),
21
+ ('DPM++ 2M', 'sample_dpmpp_2m', ['k_dpmpp_2m'], {}),
22
+ ('DPM++ SDE', 'sample_dpmpp_sde', ['k_dpmpp_sde'], {"second_order": True, "brownian_noise": True}),
23
+ ('DPM++ 2M SDE', 'sample_dpmpp_2m_sde', ['k_dpmpp_2m_sde_ka'], {"brownian_noise": True}),
24
+ ('DPM fast', 'sample_dpm_fast', ['k_dpm_fast'], {"uses_ensd": True}),
25
+ ('DPM adaptive', 'sample_dpm_adaptive', ['k_dpm_ad'], {"uses_ensd": True}),
26
+ ('LMS Karras', 'sample_lms', ['k_lms_ka'], {'scheduler': 'karras'}),
27
+ ('DPM2 Karras', 'sample_dpm_2', ['k_dpm_2_ka'], {'scheduler': 'karras', 'discard_next_to_last_sigma': True, "uses_ensd": True, "second_order": True}),
28
+ ('DPM2 a Karras', 'sample_dpm_2_ancestral', ['k_dpm_2_a_ka'], {'scheduler': 'karras', 'discard_next_to_last_sigma': True, "uses_ensd": True, "second_order": True}),
29
+ ('DPM++ 2S a Karras', 'sample_dpmpp_2s_ancestral', ['k_dpmpp_2s_a_ka'], {'scheduler': 'karras', "uses_ensd": True, "second_order": True}),
30
+ ('DPM++ 2M Karras', 'sample_dpmpp_2m', ['k_dpmpp_2m_ka'], {'scheduler': 'karras'}),
31
+ ('DPM++ 2M Karras Sharp v1', 'sample_dpmpp_2m_v1', ['k_dpmpp_2m_ka_v1'], {'scheduler': 'karras'}),
32
+ ('DPM++ SDE Karras', 'sample_dpmpp_sde', ['k_dpmpp_sde_ka'], {'scheduler': 'karras', "second_order": True, "brownian_noise": True}),
33
+ ('DPM++ 2M SDE Karras', 'sample_dpmpp_2m_sde', ['k_dpmpp_2m_sde_ka'], {'scheduler': 'karras', "brownian_noise": True}),
34
+ ]
35
+
36
+ samplers_data_k_diffusion = [
37
+ sd_samplers_common.SamplerData(label, lambda model, funcname=funcname: KDiffusionSampler(funcname, model), aliases, options)
38
+ for label, funcname, aliases, options in samplers_k_diffusion
39
+ if hasattr(k_diffusion.sampling, funcname)
40
+ ]
41
+
42
+ sampler_extra_params = {
43
+ 'sample_euler': ['s_churn', 's_tmin', 's_tmax', 's_noise'],
44
+ 'sample_heun': ['s_churn', 's_tmin', 's_tmax', 's_noise'],
45
+ 'sample_dpm_2': ['s_churn', 's_tmin', 's_tmax', 's_noise'],
46
+ }
47
+
48
+ k_diffusion_samplers_map = {x.name: x for x in samplers_data_k_diffusion}
49
+ k_diffusion_scheduler = {
50
+ 'Automatic': None,
51
+ 'karras': k_diffusion.sampling.get_sigmas_karras,
52
+ 'exponential': k_diffusion.sampling.get_sigmas_exponential,
53
+ 'polyexponential': k_diffusion.sampling.get_sigmas_polyexponential
54
+ }
55
+
56
+
57
+ def catenate_conds(conds):
58
+ if not isinstance(conds[0], dict):
59
+ return torch.cat(conds)
60
+
61
+ return {key: torch.cat([x[key] for x in conds]) for key in conds[0].keys()}
62
+
63
+
64
+ def subscript_cond(cond, a, b):
65
+ if not isinstance(cond, dict):
66
+ return cond[a:b]
67
+
68
+ return {key: vec[a:b] for key, vec in cond.items()}
69
+
70
+
71
+ def pad_cond(tensor, repeats, empty):
72
+ if not isinstance(tensor, dict):
73
+ return torch.cat([tensor, empty.repeat((tensor.shape[0], repeats, 1))], axis=1)
74
+
75
+ tensor['crossattn'] = pad_cond(tensor['crossattn'], repeats, empty)
76
+ return tensor
77
+
78
+
79
+ class CFGDenoiser(torch.nn.Module):
80
+ """
81
+ Classifier free guidance denoiser. A wrapper for stable diffusion model (specifically for unet)
82
+ that can take a noisy picture and produce a noise-free picture using two guidances (prompts)
83
+ instead of one. Originally, the second prompt is just an empty string, but we use non-empty
84
+ negative prompt.
85
+ """
86
+
87
+ def __init__(self, model):
88
+ super().__init__()
89
+ self.inner_model = model
90
+ self.mask = None
91
+ self.nmask = None
92
+ self.init_latent = None
93
+ self.step = 0
94
+ self.image_cfg_scale = None
95
+ self.padded_cond_uncond = False
96
+
97
+ def combine_denoised(self, x_out, conds_list, uncond, cond_scale):
98
+ denoised_uncond = x_out[-uncond.shape[0]:]
99
+ denoised = torch.clone(denoised_uncond)
100
+
101
+ for i, conds in enumerate(conds_list):
102
+ for cond_index, weight in conds:
103
+ denoised[i] += (x_out[cond_index] - denoised_uncond[i]) * (weight * cond_scale)
104
+
105
+ return denoised
106
+
107
+ def combine_denoised_for_edit_model(self, x_out, cond_scale):
108
+ out_cond, out_img_cond, out_uncond = x_out.chunk(3)
109
+ denoised = out_uncond + cond_scale * (out_cond - out_img_cond) + self.image_cfg_scale * (out_img_cond - out_uncond)
110
+
111
+ return denoised
112
+
113
+ def forward(self, x, sigma, uncond, cond, cond_scale, s_min_uncond, image_cond):
114
+ if state.interrupted or state.skipped:
115
+ raise sd_samplers_common.InterruptedException
116
+
117
+ # at self.image_cfg_scale == 1.0 produced results for edit model are the same as with normal sampling,
118
+ # so is_edit_model is set to False to support AND composition.
119
+ is_edit_model = shared.sd_model.cond_stage_key == "edit" and self.image_cfg_scale is not None and self.image_cfg_scale != 1.0
120
+
121
+ conds_list, tensor = prompt_parser.reconstruct_multicond_batch(cond, self.step)
122
+ uncond = prompt_parser.reconstruct_cond_batch(uncond, self.step)
123
+
124
+ assert not is_edit_model or all(len(conds) == 1 for conds in conds_list), "AND is not supported for InstructPix2Pix checkpoint (unless using Image CFG scale = 1.0)"
125
+
126
+ batch_size = len(conds_list)
127
+ repeats = [len(conds_list[i]) for i in range(batch_size)]
128
+
129
+ if shared.sd_model.model.conditioning_key == "crossattn-adm":
130
+ image_uncond = torch.zeros_like(image_cond)
131
+ make_condition_dict = lambda c_crossattn, c_adm: {"c_crossattn": [c_crossattn], "c_adm": c_adm}
132
+ else:
133
+ image_uncond = image_cond
134
+ if isinstance(uncond, dict):
135
+ make_condition_dict = lambda c_crossattn, c_concat: {**c_crossattn, "c_concat": [c_concat]}
136
+ else:
137
+ make_condition_dict = lambda c_crossattn, c_concat: {"c_crossattn": [c_crossattn], "c_concat": [c_concat]}
138
+
139
+ if not is_edit_model:
140
+ x_in = torch.cat([torch.stack([x[i] for _ in range(n)]) for i, n in enumerate(repeats)] + [x])
141
+ sigma_in = torch.cat([torch.stack([sigma[i] for _ in range(n)]) for i, n in enumerate(repeats)] + [sigma])
142
+ image_cond_in = torch.cat([torch.stack([image_cond[i] for _ in range(n)]) for i, n in enumerate(repeats)] + [image_uncond])
143
+ else:
144
+ x_in = torch.cat([torch.stack([x[i] for _ in range(n)]) for i, n in enumerate(repeats)] + [x] + [x])
145
+ sigma_in = torch.cat([torch.stack([sigma[i] for _ in range(n)]) for i, n in enumerate(repeats)] + [sigma] + [sigma])
146
+ image_cond_in = torch.cat([torch.stack([image_cond[i] for _ in range(n)]) for i, n in enumerate(repeats)] + [image_uncond] + [torch.zeros_like(self.init_latent)])
147
+
148
+ denoiser_params = CFGDenoiserParams(x_in, image_cond_in, sigma_in, state.sampling_step, state.sampling_steps, tensor, uncond)
149
+ cfg_denoiser_callback(denoiser_params)
150
+ x_in = denoiser_params.x
151
+ image_cond_in = denoiser_params.image_cond
152
+ sigma_in = denoiser_params.sigma
153
+ tensor = denoiser_params.text_cond
154
+ uncond = denoiser_params.text_uncond
155
+ skip_uncond = False
156
+
157
+ # alternating uncond allows for higher thresholds without the quality loss normally expected from raising it
158
+ if self.step % 2 and s_min_uncond > 0 and sigma[0] < s_min_uncond and not is_edit_model:
159
+ skip_uncond = True
160
+ x_in = x_in[:-batch_size]
161
+ sigma_in = sigma_in[:-batch_size]
162
+
163
+ self.padded_cond_uncond = False
164
+ if shared.opts.pad_cond_uncond and tensor.shape[1] != uncond.shape[1]:
165
+ empty = shared.sd_model.cond_stage_model_empty_prompt
166
+ num_repeats = (tensor.shape[1] - uncond.shape[1]) // empty.shape[1]
167
+
168
+ if num_repeats < 0:
169
+ tensor = pad_cond(tensor, -num_repeats, empty)
170
+ self.padded_cond_uncond = True
171
+ elif num_repeats > 0:
172
+ uncond = pad_cond(uncond, num_repeats, empty)
173
+ self.padded_cond_uncond = True
174
+
175
+ if tensor.shape[1] == uncond.shape[1] or skip_uncond:
176
+ if is_edit_model:
177
+ cond_in = catenate_conds([tensor, uncond, uncond])
178
+ elif skip_uncond:
179
+ cond_in = tensor
180
+ else:
181
+ cond_in = catenate_conds([tensor, uncond])
182
+
183
+ if shared.batch_cond_uncond:
184
+ x_out = self.inner_model(x_in, sigma_in, cond=make_condition_dict(cond_in, image_cond_in))
185
+ else:
186
+ x_out = torch.zeros_like(x_in)
187
+ for batch_offset in range(0, x_out.shape[0], batch_size):
188
+ a = batch_offset
189
+ b = a + batch_size
190
+ x_out[a:b] = self.inner_model(x_in[a:b], sigma_in[a:b], cond=make_condition_dict(subscript_cond(cond_in, a, b), image_cond_in[a:b]))
191
+ else:
192
+ x_out = torch.zeros_like(x_in)
193
+ batch_size = batch_size*2 if shared.batch_cond_uncond else batch_size
194
+ for batch_offset in range(0, tensor.shape[0], batch_size):
195
+ a = batch_offset
196
+ b = min(a + batch_size, tensor.shape[0])
197
+
198
+ if not is_edit_model:
199
+ c_crossattn = subscript_cond(tensor, a, b)
200
+ else:
201
+ c_crossattn = torch.cat([tensor[a:b]], uncond)
202
+
203
+ x_out[a:b] = self.inner_model(x_in[a:b], sigma_in[a:b], cond=make_condition_dict(c_crossattn, image_cond_in[a:b]))
204
+
205
+ if not skip_uncond:
206
+ x_out[-uncond.shape[0]:] = self.inner_model(x_in[-uncond.shape[0]:], sigma_in[-uncond.shape[0]:], cond=make_condition_dict(uncond, image_cond_in[-uncond.shape[0]:]))
207
+
208
+ denoised_image_indexes = [x[0][0] for x in conds_list]
209
+ if skip_uncond:
210
+ fake_uncond = torch.cat([x_out[i:i+1] for i in denoised_image_indexes])
211
+ x_out = torch.cat([x_out, fake_uncond]) # we skipped uncond denoising, so we put cond-denoised image to where the uncond-denoised image should be
212
+
213
+ denoised_params = CFGDenoisedParams(x_out, state.sampling_step, state.sampling_steps, self.inner_model)
214
+ cfg_denoised_callback(denoised_params)
215
+
216
+ devices.test_for_nans(x_out, "unet")
217
+
218
+ if opts.live_preview_content == "Prompt":
219
+ sd_samplers_common.store_latent(torch.cat([x_out[i:i+1] for i in denoised_image_indexes]))
220
+ elif opts.live_preview_content == "Negative prompt":
221
+ sd_samplers_common.store_latent(x_out[-uncond.shape[0]:])
222
+
223
+ if is_edit_model:
224
+ denoised = self.combine_denoised_for_edit_model(x_out, cond_scale)
225
+ elif skip_uncond:
226
+ denoised = self.combine_denoised(x_out, conds_list, uncond, 1.0)
227
+ else:
228
+ denoised = self.combine_denoised(x_out, conds_list, uncond, cond_scale)
229
+
230
+ if self.mask is not None:
231
+ denoised = self.init_latent * self.mask + self.nmask * denoised
232
+
233
+ after_cfg_callback_params = AfterCFGCallbackParams(denoised, state.sampling_step, state.sampling_steps)
234
+ cfg_after_cfg_callback(after_cfg_callback_params)
235
+ denoised = after_cfg_callback_params.x
236
+
237
+ self.step += 1
238
+ return denoised
239
+
240
+
241
+ class TorchHijack:
242
+ def __init__(self, sampler_noises):
243
+ # Using a deque to efficiently receive the sampler_noises in the same order as the previous index-based
244
+ # implementation.
245
+ self.sampler_noises = deque(sampler_noises)
246
+
247
+ def __getattr__(self, item):
248
+ if item == 'randn_like':
249
+ return self.randn_like
250
+
251
+ if hasattr(torch, item):
252
+ return getattr(torch, item)
253
+
254
+ raise AttributeError(f"'{type(self).__name__}' object has no attribute '{item}'")
255
+
256
+ def randn_like(self, x):
257
+ if self.sampler_noises:
258
+ noise = self.sampler_noises.popleft()
259
+ if noise.shape == x.shape:
260
+ return noise
261
+
262
+ if opts.randn_source == "CPU" or x.device.type == 'mps':
263
+ return torch.randn_like(x, device=devices.cpu).to(x.device)
264
+ else:
265
+ return torch.randn_like(x)
266
+
267
+
268
+ class KDiffusionSampler:
269
+ def __init__(self, funcname, sd_model):
270
+ denoiser = k_diffusion.external.CompVisVDenoiser if sd_model.parameterization == "v" else k_diffusion.external.CompVisDenoiser
271
+
272
+ self.model_wrap = denoiser(sd_model, quantize=shared.opts.enable_quantization)
273
+ self.funcname = funcname
274
+ self.func = getattr(k_diffusion.sampling, self.funcname)
275
+ self.extra_params = sampler_extra_params.get(funcname, [])
276
+ self.model_wrap_cfg = CFGDenoiser(self.model_wrap)
277
+ self.sampler_noises = None
278
+ self.stop_at = None
279
+ self.eta = None
280
+ self.config = None # set by the function calling the constructor
281
+ self.last_latent = None
282
+ self.s_min_uncond = None
283
+
284
+ self.conditioning_key = sd_model.model.conditioning_key
285
+
286
+ def callback_state(self, d):
287
+ step = d['i']
288
+ latent = d["denoised"]
289
+ if opts.live_preview_content == "Combined":
290
+ sd_samplers_common.store_latent(latent)
291
+ self.last_latent = latent
292
+
293
+ if self.stop_at is not None and step > self.stop_at:
294
+ raise sd_samplers_common.InterruptedException
295
+
296
+ state.sampling_step = step
297
+ shared.total_tqdm.update()
298
+
299
+ def launch_sampling(self, steps, func):
300
+ state.sampling_steps = steps
301
+ state.sampling_step = 0
302
+
303
+ try:
304
+ return func()
305
+ except RecursionError:
306
+ print(
307
+ 'Encountered RecursionError during sampling, returning last latent. '
308
+ 'rho >5 with a polyexponential scheduler may cause this error. '
309
+ 'You should try to use a smaller rho value instead.'
310
+ )
311
+ return self.last_latent
312
+ except sd_samplers_common.InterruptedException:
313
+ return self.last_latent
314
+
315
+ def number_of_needed_noises(self, p):
316
+ return p.steps
317
+
318
+ def initialize(self, p):
319
+ self.model_wrap_cfg.mask = p.mask if hasattr(p, 'mask') else None
320
+ self.model_wrap_cfg.nmask = p.nmask if hasattr(p, 'nmask') else None
321
+ self.model_wrap_cfg.step = 0
322
+ self.model_wrap_cfg.image_cfg_scale = getattr(p, 'image_cfg_scale', None)
323
+ self.eta = p.eta if p.eta is not None else opts.eta_ancestral
324
+ self.s_min_uncond = getattr(p, 's_min_uncond', 0.0)
325
+
326
+ k_diffusion.sampling.torch = TorchHijack(self.sampler_noises if self.sampler_noises is not None else [])
327
+
328
+ extra_params_kwargs = {}
329
+ for param_name in self.extra_params:
330
+ if hasattr(p, param_name) and param_name in inspect.signature(self.func).parameters:
331
+ extra_params_kwargs[param_name] = getattr(p, param_name)
332
+
333
+ if 'eta' in inspect.signature(self.func).parameters:
334
+ if self.eta != 1.0:
335
+ p.extra_generation_params["Eta"] = self.eta
336
+
337
+ extra_params_kwargs['eta'] = self.eta
338
+
339
+ return extra_params_kwargs
340
+
341
+ def get_sigmas(self, p, steps):
342
+ discard_next_to_last_sigma = self.config is not None and self.config.options.get('discard_next_to_last_sigma', False)
343
+ if opts.always_discard_next_to_last_sigma and not discard_next_to_last_sigma:
344
+ discard_next_to_last_sigma = True
345
+ p.extra_generation_params["Discard penultimate sigma"] = True
346
+
347
+ steps += 1 if discard_next_to_last_sigma else 0
348
+
349
+ if p.sampler_noise_scheduler_override:
350
+ sigmas = p.sampler_noise_scheduler_override(steps)
351
+ elif opts.k_sched_type != "Automatic":
352
+ m_sigma_min, m_sigma_max = (self.model_wrap.sigmas[0].item(), self.model_wrap.sigmas[-1].item())
353
+ sigma_min, sigma_max = (0.1, 10) if opts.use_old_karras_scheduler_sigmas else (m_sigma_min, m_sigma_max)
354
+ sigmas_kwargs = {
355
+ 'sigma_min': sigma_min,
356
+ 'sigma_max': sigma_max,
357
+ }
358
+
359
+ sigmas_func = k_diffusion_scheduler[opts.k_sched_type]
360
+ p.extra_generation_params["Schedule type"] = opts.k_sched_type
361
+
362
+ if opts.sigma_min != m_sigma_min and opts.sigma_min != 0:
363
+ sigmas_kwargs['sigma_min'] = opts.sigma_min
364
+ p.extra_generation_params["Schedule min sigma"] = opts.sigma_min
365
+ if opts.sigma_max != m_sigma_max and opts.sigma_max != 0:
366
+ sigmas_kwargs['sigma_max'] = opts.sigma_max
367
+ p.extra_generation_params["Schedule max sigma"] = opts.sigma_max
368
+
369
+ default_rho = 1. if opts.k_sched_type == "polyexponential" else 7.
370
+
371
+ if opts.k_sched_type != 'exponential' and opts.rho != 0 and opts.rho != default_rho:
372
+ sigmas_kwargs['rho'] = opts.rho
373
+ p.extra_generation_params["Schedule rho"] = opts.rho
374
+
375
+ sigmas = sigmas_func(n=steps, **sigmas_kwargs, device=shared.device)
376
+ elif self.config is not None and self.config.options.get('scheduler', None) == 'karras':
377
+ sigma_min, sigma_max = (0.1, 10) if opts.use_old_karras_scheduler_sigmas else (self.model_wrap.sigmas[0].item(), self.model_wrap.sigmas[-1].item())
378
+
379
+ sigmas = k_diffusion.sampling.get_sigmas_karras(n=steps, sigma_min=sigma_min, sigma_max=sigma_max, device=shared.device)
380
+ else:
381
+ sigmas = self.model_wrap.get_sigmas(steps)
382
+
383
+ if discard_next_to_last_sigma:
384
+ sigmas = torch.cat([sigmas[:-2], sigmas[-1:]])
385
+
386
+ return sigmas
387
+
388
+ def create_noise_sampler(self, x, sigmas, p):
389
+ """For DPM++ SDE: manually create noise sampler to enable deterministic results across different batch sizes"""
390
+ if shared.opts.no_dpmpp_sde_batch_determinism:
391
+ return None
392
+
393
+ from k_diffusion.sampling import BrownianTreeNoiseSampler
394
+ sigma_min, sigma_max = sigmas[sigmas > 0].min(), sigmas.max()
395
+ current_iter_seeds = p.all_seeds[p.iteration * p.batch_size:(p.iteration + 1) * p.batch_size]
396
+ return BrownianTreeNoiseSampler(x, sigma_min, sigma_max, seed=current_iter_seeds)
397
+
398
+ def sample_img2img(self, p, x, noise, conditioning, unconditional_conditioning, steps=None, image_conditioning=None):
399
+ steps, t_enc = sd_samplers_common.setup_img2img_steps(p, steps)
400
+
401
+ sigmas = self.get_sigmas(p, steps)
402
+
403
+ sigma_sched = sigmas[steps - t_enc - 1:]
404
+ xi = x + noise * sigma_sched[0]
405
+
406
+ extra_params_kwargs = self.initialize(p)
407
+ parameters = inspect.signature(self.func).parameters
408
+
409
+ if 'sigma_min' in parameters:
410
+ ## last sigma is zero which isn't allowed by DPM Fast & Adaptive so taking value before last
411
+ extra_params_kwargs['sigma_min'] = sigma_sched[-2]
412
+ if 'sigma_max' in parameters:
413
+ extra_params_kwargs['sigma_max'] = sigma_sched[0]
414
+ if 'n' in parameters:
415
+ extra_params_kwargs['n'] = len(sigma_sched) - 1
416
+ if 'sigma_sched' in parameters:
417
+ extra_params_kwargs['sigma_sched'] = sigma_sched
418
+ if 'sigmas' in parameters:
419
+ extra_params_kwargs['sigmas'] = sigma_sched
420
+
421
+ if self.config.options.get('brownian_noise', False):
422
+ noise_sampler = self.create_noise_sampler(x, sigmas, p)
423
+ extra_params_kwargs['noise_sampler'] = noise_sampler
424
+
425
+ self.model_wrap_cfg.init_latent = x
426
+ self.last_latent = x
427
+ extra_args = {
428
+ 'cond': conditioning,
429
+ 'image_cond': image_conditioning,
430
+ 'uncond': unconditional_conditioning,
431
+ 'cond_scale': p.cfg_scale,
432
+ 's_min_uncond': self.s_min_uncond
433
+ }
434
+
435
+ samples = self.launch_sampling(t_enc + 1, lambda: self.func(self.model_wrap_cfg, xi, extra_args=extra_args, disable=False, callback=self.callback_state, **extra_params_kwargs))
436
+
437
+ if self.model_wrap_cfg.padded_cond_uncond:
438
+ p.extra_generation_params["Pad conds"] = True
439
+
440
+ return samples
441
+
442
+ def sample(self, p, x, conditioning, unconditional_conditioning, steps=None, image_conditioning=None):
443
+ steps = steps or p.steps
444
+
445
+ sigmas = self.get_sigmas(p, steps)
446
+
447
+ x = x * sigmas[0]
448
+
449
+ extra_params_kwargs = self.initialize(p)
450
+ parameters = inspect.signature(self.func).parameters
451
+
452
+ if 'sigma_min' in parameters:
453
+ extra_params_kwargs['sigma_min'] = self.model_wrap.sigmas[0].item()
454
+ extra_params_kwargs['sigma_max'] = self.model_wrap.sigmas[-1].item()
455
+ if 'n' in parameters:
456
+ extra_params_kwargs['n'] = steps
457
+ else:
458
+ extra_params_kwargs['sigmas'] = sigmas
459
+
460
+ if self.config.options.get('brownian_noise', False):
461
+ noise_sampler = self.create_noise_sampler(x, sigmas, p)
462
+ extra_params_kwargs['noise_sampler'] = noise_sampler
463
+
464
+ self.last_latent = x
465
+ samples = self.launch_sampling(steps, lambda: self.func(self.model_wrap_cfg, x, extra_args={
466
+ 'cond': conditioning,
467
+ 'image_cond': image_conditioning,
468
+ 'uncond': unconditional_conditioning,
469
+ 'cond_scale': p.cfg_scale,
470
+ 's_min_uncond': self.s_min_uncond
471
+ }, disable=False, callback=self.callback_state, **extra_params_kwargs))
472
+
473
+ if self.model_wrap_cfg.padded_cond_uncond:
474
+ p.extra_generation_params["Pad conds"] = True
475
+
476
+ return samples
477
+