sd_samplers_kdiffusion.py 20.9 KB
Newer Older
1
from collections import deque
2
import torch
A
AUTOMATIC 已提交
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
D
DepFA 已提交
9
from modules.script_callbacks import CFGDenoiserParams, cfg_denoiser_callback
O
opparco 已提交
10
from modules.script_callbacks import CFGDenoisedParams, cfg_denoised_callback
C
catboxanon 已提交
11
from modules.script_callbacks import AfterCFGCallbackParams, cfg_after_cfg_callback
12

A
AUTOMATIC 已提交
13
samplers_k_diffusion = [
14
    ('Euler a', 'sample_euler_ancestral', ['k_euler_a', 'k_euler_ancestral'], {"uses_ensd": True}),
A
AUTOMATIC 已提交
15 16
    ('Euler', 'sample_euler', ['k_euler'], {}),
    ('LMS', 'sample_lms', ['k_lms'], {}),
17
    ('Heun', 'sample_heun', ['k_heun'], {"second_order": True}),
A
AUTOMATIC 已提交
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}),
A
AUTOMATIC 已提交
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, 'discard_next_to_last_sigma': True}),
24 25
    ('DPM fast', 'sample_dpm_fast', ['k_dpm_fast'], {"uses_ensd": True}),
    ('DPM adaptive', 'sample_dpm_adaptive', ['k_dpm_ad'], {"uses_ensd": True}),
A
AUTOMATIC 已提交
26
    ('LMS Karras', 'sample_lms', ['k_lms_ka'], {'scheduler': 'karras'}),
27 28 29
    ('DPM2 Karras', 'sample_dpm_2', ['k_dpm_2_ka'], {'scheduler': 'karras', 'discard_next_to_last_sigma': True, "uses_ensd": True, "second_order": True}),
    ('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}),
    ('DPM++ 2S a Karras', 'sample_dpmpp_2s_ancestral', ['k_dpmpp_2s_a_ka'], {'scheduler': 'karras', "uses_ensd": True, "second_order": True}),
A
AUTOMATIC 已提交
30
    ('DPM++ 2M Karras', 'sample_dpmpp_2m', ['k_dpmpp_2m_ka'], {'scheduler': 'karras'}),
31
    ('DPM++ SDE Karras', 'sample_dpmpp_sde', ['k_dpmpp_sde_ka'], {'scheduler': 'karras', "second_order": True, "brownian_noise": True}),
32
    ('DPM++ 2M SDE Karras', 'sample_dpmpp_2m_sde', ['k_dpmpp_2m_sde_ka'], {'scheduler': 'karras', "brownian_noise": True, 'discard_next_to_last_sigma': True}),
A
AUTOMATIC 已提交
33 34 35
]

samplers_data_k_diffusion = [
36
    sd_samplers_common.SamplerData(label, lambda model, funcname=funcname: KDiffusionSampler(funcname, model), aliases, options)
A
AUTOMATIC 已提交
37
    for label, funcname, aliases, options in samplers_k_diffusion
A
AUTOMATIC 已提交
38 39 40
    if hasattr(k_diffusion.sampling, funcname)
]

41
sampler_extra_params = {
A
AUTOMATIC 已提交
42 43 44
    'sample_euler': ['s_churn', 's_tmin', 's_tmax', 's_noise'],
    'sample_heun': ['s_churn', 's_tmin', 's_tmax', 's_noise'],
    'sample_dpm_2': ['s_churn', 's_tmin', 's_tmax', 's_noise'],
45
}
46

47
k_diffusion_samplers_map = {x.name: x for x in samplers_data_k_diffusion}
48
k_diffusion_scheduler = {
49
    'Automatic': None,
50 51 52 53 54
    'karras': k_diffusion.sampling.get_sigmas_karras,
    'exponential': k_diffusion.sampling.get_sigmas_exponential,
    'polyexponential': k_diffusion.sampling.get_sigmas_polyexponential
}

55

56
class CFGDenoiser(torch.nn.Module):
57 58 59 60 61 62 63
    """
    Classifier free guidance denoiser. A wrapper for stable diffusion model (specifically for unet)
    that can take a noisy picture and produce a noise-free picture using two guidances (prompts)
    instead of one. Originally, the second prompt is just an empty string, but we use non-empty
    negative prompt.
    """

64 65 66 67 68 69
    def __init__(self, model):
        super().__init__()
        self.inner_model = model
        self.mask = None
        self.nmask = None
        self.init_latent = None
A
AUTOMATIC 已提交
70
        self.step = 0
71
        self.image_cfg_scale = None
72

73 74 75 76 77 78 79 80 81 82
    def combine_denoised(self, x_out, conds_list, uncond, cond_scale):
        denoised_uncond = x_out[-uncond.shape[0]:]
        denoised = torch.clone(denoised_uncond)

        for i, conds in enumerate(conds_list):
            for cond_index, weight in conds:
                denoised[i] += (x_out[cond_index] - denoised_uncond[i]) * (weight * cond_scale)

        return denoised

83 84 85 86 87 88
    def combine_denoised_for_edit_model(self, x_out, cond_scale):
        out_cond, out_img_cond, out_uncond = x_out.chunk(3)
        denoised = out_uncond + cond_scale * (out_cond - out_img_cond) + self.image_cfg_scale * (out_img_cond - out_uncond)

        return denoised

D
devdn 已提交
89
    def forward(self, x, sigma, uncond, cond, cond_scale, s_min_uncond, image_cond):
90
        if state.interrupted or state.skipped:
91
            raise sd_samplers_common.InterruptedException
92

93 94 95 96
        # at self.image_cfg_scale == 1.0 produced results for edit model are the same as with normal sampling,
        # so is_edit_model is set to False to support AND composition.
        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

A
AUTOMATIC 已提交
97
        conds_list, tensor = prompt_parser.reconstruct_multicond_batch(cond, self.step)
A
AUTOMATIC 已提交
98 99
        uncond = prompt_parser.reconstruct_cond_batch(uncond, self.step)

A
AUTOMATIC 已提交
100
        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)"
101

A
AUTOMATIC 已提交
102 103 104
        batch_size = len(conds_list)
        repeats = [len(conds_list[i]) for i in range(batch_size)]

105 106
        if shared.sd_model.model.conditioning_key == "crossattn-adm":
            image_uncond = torch.zeros_like(image_cond)
107
            make_condition_dict = lambda c_crossattn, c_adm: {"c_crossattn": c_crossattn, "c_adm": c_adm}
108 109
        else:
            image_uncond = image_cond
110
            make_condition_dict = lambda c_crossattn, c_concat: {"c_crossattn": c_crossattn, "c_concat": [c_concat]}
111

112 113 114
        if not is_edit_model:
            x_in = torch.cat([torch.stack([x[i] for _ in range(n)]) for i, n in enumerate(repeats)] + [x])
            sigma_in = torch.cat([torch.stack([sigma[i] for _ in range(n)]) for i, n in enumerate(repeats)] + [sigma])
115
            image_cond_in = torch.cat([torch.stack([image_cond[i] for _ in range(n)]) for i, n in enumerate(repeats)] + [image_uncond])
116 117 118
        else:
            x_in = torch.cat([torch.stack([x[i] for _ in range(n)]) for i, n in enumerate(repeats)] + [x] + [x])
            sigma_in = torch.cat([torch.stack([sigma[i] for _ in range(n)]) for i, n in enumerate(repeats)] + [sigma] + [sigma])
119
            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)])
A
AUTOMATIC 已提交
120

L
laksjdjf 已提交
121
        denoiser_params = CFGDenoiserParams(x_in, image_cond_in, sigma_in, state.sampling_step, state.sampling_steps, tensor, uncond)
D
DepFA 已提交
122 123 124 125
        cfg_denoiser_callback(denoiser_params)
        x_in = denoiser_params.x
        image_cond_in = denoiser_params.image_cond
        sigma_in = denoiser_params.sigma
126 127
        tensor = denoiser_params.text_cond
        uncond = denoiser_params.text_uncond
128
        skip_uncond = False
D
DepFA 已提交
129

130 131 132 133 134
        # alternating uncond allows for higher thresholds without the quality loss normally expected from raising it
        if self.step % 2 and s_min_uncond > 0 and sigma[0] < s_min_uncond and not is_edit_model:
            skip_uncond = True
            x_in = x_in[:-batch_size]
            sigma_in = sigma_in[:-batch_size]
D
devdn 已提交
135

136 137 138 139 140 141 142 143 144 145
        # TODO add infotext entry
        if shared.opts.pad_cond_uncond and tensor.shape[1] != uncond.shape[1]:
            empty = shared.sd_model.cond_stage_model_empty_prompt
            num_repeats = (tensor.shape[1] - uncond.shape[1]) // empty.shape[1]

            if num_repeats < 0:
                tensor = torch.cat([tensor, empty.repeat((tensor.shape[0], -num_repeats, 1))], axis=1)
            elif num_repeats > 0:
                uncond = torch.cat([uncond, empty.repeat((uncond.shape[0], num_repeats, 1))], axis=1)

146 147
        if tensor.shape[1] == uncond.shape[1] or skip_uncond:
            if is_edit_model:
148
                cond_in = torch.cat([tensor, uncond, uncond])
149 150 151 152
            elif skip_uncond:
                cond_in = tensor
            else:
                cond_in = torch.cat([tensor, uncond])
153 154

            if shared.batch_cond_uncond:
155
                x_out = self.inner_model(x_in, sigma_in, cond=make_condition_dict([cond_in], image_cond_in))
156 157 158 159 160
            else:
                x_out = torch.zeros_like(x_in)
                for batch_offset in range(0, x_out.shape[0], batch_size):
                    a = batch_offset
                    b = a + batch_size
161
                    x_out[a:b] = self.inner_model(x_in[a:b], sigma_in[a:b], cond=make_condition_dict([cond_in[a:b]], image_cond_in[a:b]))
162
        else:
A
AUTOMATIC 已提交
163
            x_out = torch.zeros_like(x_in)
164 165
            batch_size = batch_size*2 if shared.batch_cond_uncond else batch_size
            for batch_offset in range(0, tensor.shape[0], batch_size):
A
AUTOMATIC 已提交
166
                a = batch_offset
167
                b = min(a + batch_size, tensor.shape[0])
168 169 170 171 172 173

                if not is_edit_model:
                    c_crossattn = [tensor[a:b]]
                else:
                    c_crossattn = torch.cat([tensor[a:b]], uncond)

174
                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]))
175

176
            if not skip_uncond:
D
devdn 已提交
177
                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]:]))
A
AUTOMATIC 已提交
178

179
        denoised_image_indexes = [x[0][0] for x in conds_list]
180 181
        if skip_uncond:
            fake_uncond = torch.cat([x_out[i:i+1] for i in denoised_image_indexes])
182
            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
183

C
catboxanon 已提交
184
        denoised_params = CFGDenoisedParams(x_out, state.sampling_step, state.sampling_steps, self.inner_model)
O
opparco 已提交
185 186
        cfg_denoised_callback(denoised_params)

187 188
        devices.test_for_nans(x_out, "unet")

189
        if opts.live_preview_content == "Prompt":
190
            sd_samplers_common.store_latent(torch.cat([x_out[i:i+1] for i in denoised_image_indexes]))
191
        elif opts.live_preview_content == "Negative prompt":
192
            sd_samplers_common.store_latent(x_out[-uncond.shape[0]:])
193

194
        if is_edit_model:
195
            denoised = self.combine_denoised_for_edit_model(x_out, cond_scale)
196 197 198 199
        elif skip_uncond:
            denoised = self.combine_denoised(x_out, conds_list, uncond, 1.0)
        else:
            denoised = self.combine_denoised(x_out, conds_list, uncond, cond_scale)
200 201 202 203

        if self.mask is not None:
            denoised = self.init_latent * self.mask + self.nmask * denoised

C
catboxanon 已提交
204 205
        after_cfg_callback_params = AfterCFGCallbackParams(denoised, state.sampling_step, state.sampling_steps)
        cfg_after_cfg_callback(after_cfg_callback_params)
206
        denoised = after_cfg_callback_params.x
C
catboxanon 已提交
207

A
AUTOMATIC 已提交
208
        self.step += 1
209 210 211
        return denoised


212
class TorchHijack:
213 214 215 216
    def __init__(self, sampler_noises):
        # Using a deque to efficiently receive the sampler_noises in the same order as the previous index-based
        # implementation.
        self.sampler_noises = deque(sampler_noises)
217 218 219

    def __getattr__(self, item):
        if item == 'randn_like':
220
            return self.randn_like
221 222 223 224

        if hasattr(torch, item):
            return getattr(torch, item)

225
        raise AttributeError(f"'{type(self).__name__}' object has no attribute '{item}'")
226

227 228 229 230 231 232
    def randn_like(self, x):
        if self.sampler_noises:
            noise = self.sampler_noises.popleft()
            if noise.shape == x.shape:
                return noise

233
        if opts.randn_source == "CPU" or x.device.type == 'mps':
B
brkirch 已提交
234 235 236
            return torch.randn_like(x, device=devices.cpu).to(x.device)
        else:
            return torch.randn_like(x)
237

238

239 240
class KDiffusionSampler:
    def __init__(self, funcname, sd_model):
A
AUTOMATIC 已提交
241 242 243
        denoiser = k_diffusion.external.CompVisVDenoiser if sd_model.parameterization == "v" else k_diffusion.external.CompVisDenoiser

        self.model_wrap = denoiser(sd_model, quantize=shared.opts.enable_quantization)
244 245
        self.funcname = funcname
        self.func = getattr(k_diffusion.sampling, self.funcname)
A
AUTOMATIC 已提交
246
        self.extra_params = sampler_extra_params.get(funcname, [])
247
        self.model_wrap_cfg = CFGDenoiser(self.model_wrap)
248
        self.sampler_noises = None
A
AUTOMATIC 已提交
249
        self.stop_at = None
250
        self.eta = None
251
        self.config = None  # set by the function calling the constructor
252
        self.last_latent = None
253
        self.s_min_uncond = None
254

255 256
        self.conditioning_key = sd_model.model.conditioning_key

A
AUTOMATIC 已提交
257
    def callback_state(self, d):
258 259
        step = d['i']
        latent = d["denoised"]
260
        if opts.live_preview_content == "Combined":
261
            sd_samplers_common.store_latent(latent)
262 263 264
        self.last_latent = latent

        if self.stop_at is not None and step > self.stop_at:
265
            raise sd_samplers_common.InterruptedException
266 267 268 269 270 271 272 273 274 275

        state.sampling_step = step
        shared.total_tqdm.update()

    def launch_sampling(self, steps, func):
        state.sampling_steps = steps
        state.sampling_step = 0

        try:
            return func()
276 277
        except RecursionError:
            print(
K
Kohaku-Blueleaf 已提交
278 279 280
                'Encountered RecursionError during sampling, returning last latent. '
                'rho >5 with a polyexponential scheduler may cause this error. '
                'You should try to use a smaller rho value instead.'
281 282
            )
            return self.last_latent
283
        except sd_samplers_common.InterruptedException:
284
            return self.last_latent
A
AUTOMATIC 已提交
285

286 287 288
    def number_of_needed_noises(self, p):
        return p.steps

289
    def initialize(self, p):
A
AUTOMATIC 已提交
290 291
        self.model_wrap_cfg.mask = p.mask if hasattr(p, 'mask') else None
        self.model_wrap_cfg.nmask = p.nmask if hasattr(p, 'nmask') else None
292
        self.model_wrap_cfg.step = 0
293
        self.model_wrap_cfg.image_cfg_scale = getattr(p, 'image_cfg_scale', None)
294
        self.eta = p.eta if p.eta is not None else opts.eta_ancestral
D
devdn 已提交
295
        self.s_min_uncond = getattr(p, 's_min_uncond', 0.0)
296

B
brkirch 已提交
297
        k_diffusion.sampling.torch = TorchHijack(self.sampler_noises if self.sampler_noises is not None else [])
298

299
        extra_params_kwargs = {}
A
AUTOMATIC 已提交
300 301 302
        for param_name in self.extra_params:
            if hasattr(p, param_name) and param_name in inspect.signature(self.func).parameters:
                extra_params_kwargs[param_name] = getattr(p, param_name)
303

304
        if 'eta' in inspect.signature(self.func).parameters:
305 306 307
            if self.eta != 1.0:
                p.extra_generation_params["Eta"] = self.eta

308 309 310 311
            extra_params_kwargs['eta'] = self.eta

        return extra_params_kwargs

A
AUTOMATIC 已提交
312
    def get_sigmas(self, p, steps):
313 314 315 316 317 318
        discard_next_to_last_sigma = self.config is not None and self.config.options.get('discard_next_to_last_sigma', False)
        if opts.always_discard_next_to_last_sigma and not discard_next_to_last_sigma:
            discard_next_to_last_sigma = True
            p.extra_generation_params["Discard penultimate sigma"] = True

        steps += 1 if discard_next_to_last_sigma else 0
H
hentailord85ez 已提交
319

320
        if p.sampler_noise_scheduler_override:
A
AUTOMATIC 已提交
321
            sigmas = p.sampler_noise_scheduler_override(steps)
322
        elif opts.k_sched_type != "Automatic":
K
Kohaku-Blueleaf 已提交
323 324
            m_sigma_min, m_sigma_max = (self.model_wrap.sigmas[0].item(), self.model_wrap.sigmas[-1].item())
            sigma_min, sigma_max = (0.1, 10)
325
            sigmas_kwargs = {
K
Kohaku-Blueleaf 已提交
326 327
                'sigma_min': sigma_min if opts.use_old_karras_scheduler_sigmas else m_sigma_min,
                'sigma_max': sigma_max if opts.use_old_karras_scheduler_sigmas else m_sigma_max
328
            }
K
Kohaku-Blueleaf 已提交
329 330

            sigmas_func = k_diffusion_scheduler[opts.k_sched_type]
K
Kohaku-Blueleaf 已提交
331
            p.extra_generation_params["KDiff Schedule Type"] = opts.k_sched_type
K
Kohaku-Blueleaf 已提交
332 333 334 335

            if opts.sigma_min != 0.3:
                # take 0.0 as model default
                sigmas_kwargs['sigma_min'] = opts.sigma_min or m_sigma_min
K
Kohaku-Blueleaf 已提交
336
                p.extra_generation_params["KDiff Schedule min sigma"] = opts.sigma_min
K
Kohaku-Blueleaf 已提交
337 338
            if opts.sigma_max != 14.6:
                sigmas_kwargs['sigma_max'] = opts.sigma_max or m_sigma_max
K
Kohaku-Blueleaf 已提交
339
                p.extra_generation_params["KDiff Schedule max sigma"] = opts.sigma_max
K
Kohaku-Blueleaf 已提交
340 341
            if opts.k_sched_type != 'exponential':
                sigmas_kwargs['rho'] = opts.rho
K
Kohaku-Blueleaf 已提交
342
                p.extra_generation_params["KDiff Schedule rho"] = opts.rho
K
Kohaku-Blueleaf 已提交
343

344
            sigmas = sigmas_func(n=steps, **sigmas_kwargs, device=shared.device)
A
AUTOMATIC 已提交
345
        elif self.config is not None and self.config.options.get('scheduler', None) == 'karras':
346 347 348
            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())

            sigmas = k_diffusion.sampling.get_sigmas_karras(n=steps, sigma_min=sigma_min, sigma_max=sigma_max, device=shared.device)
349
        else:
A
AUTOMATIC 已提交
350
            sigmas = self.model_wrap.get_sigmas(steps)
351

352
        if discard_next_to_last_sigma:
353 354
            sigmas = torch.cat([sigmas[:-2], sigmas[-1:]])

A
AUTOMATIC 已提交
355 356
        return sigmas

R
RcINS 已提交
357
    def create_noise_sampler(self, x, sigmas, p):
358 359 360 361 362 363
        """For DPM++ SDE: manually create noise sampler to enable deterministic results across different batch sizes"""
        if shared.opts.no_dpmpp_sde_batch_determinism:
            return None

        from k_diffusion.sampling import BrownianTreeNoiseSampler
        sigma_min, sigma_max = sigmas[sigmas > 0].min(), sigmas.max()
R
RcINS 已提交
364 365
        current_iter_seeds = p.all_seeds[p.iteration * p.batch_size:(p.iteration + 1) * p.batch_size]
        return BrownianTreeNoiseSampler(x, sigma_min, sigma_max, seed=current_iter_seeds)
366

A
AUTOMATIC 已提交
367
    def sample_img2img(self, p, x, noise, conditioning, unconditional_conditioning, steps=None, image_conditioning=None):
368
        steps, t_enc = sd_samplers_common.setup_img2img_steps(p, steps)
A
AUTOMATIC 已提交
369 370 371

        sigmas = self.get_sigmas(p, steps)

372
        sigma_sched = sigmas[steps - t_enc - 1:]
373
        xi = x + noise * sigma_sched[0]
374

375
        extra_params_kwargs = self.initialize(p)
376 377 378
        parameters = inspect.signature(self.func).parameters

        if 'sigma_min' in parameters:
M
Martin Cairns 已提交
379
            ## last sigma is zero which isn't allowed by DPM Fast & Adaptive so taking value before last
380
            extra_params_kwargs['sigma_min'] = sigma_sched[-2]
381
        if 'sigma_max' in parameters:
382
            extra_params_kwargs['sigma_max'] = sigma_sched[0]
383
        if 'n' in parameters:
384
            extra_params_kwargs['n'] = len(sigma_sched) - 1
385
        if 'sigma_sched' in parameters:
386
            extra_params_kwargs['sigma_sched'] = sigma_sched
387
        if 'sigmas' in parameters:
388
            extra_params_kwargs['sigmas'] = sigma_sched
389

390
        if self.config.options.get('brownian_noise', False):
R
RcINS 已提交
391
            noise_sampler = self.create_noise_sampler(x, sigmas, p)
392 393
            extra_params_kwargs['noise_sampler'] = noise_sampler

394
        self.model_wrap_cfg.init_latent = x
395
        self.last_latent = x
396
        extra_args = {
397 398 399
            'cond': conditioning,
            'image_cond': image_conditioning,
            'uncond': unconditional_conditioning,
K
Kyle 已提交
400
            'cond_scale': p.cfg_scale,
D
devdn 已提交
401
            's_min_uncond': self.s_min_uncond
K
Kyle 已提交
402 403 404
        }

        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))
405

406
        return samples
407

408
    def sample(self, p, x, conditioning, unconditional_conditioning, steps=None, image_conditioning=None):
A
AUTOMATIC 已提交
409 410
        steps = steps or p.steps

A
AUTOMATIC 已提交
411
        sigmas = self.get_sigmas(p, steps)
A
AUTOMATIC 已提交
412

413 414
        x = x * sigmas[0]

415
        extra_params_kwargs = self.initialize(p)
416 417 418
        parameters = inspect.signature(self.func).parameters

        if 'sigma_min' in parameters:
C
C43H66N12O12S2 已提交
419 420
            extra_params_kwargs['sigma_min'] = self.model_wrap.sigmas[0].item()
            extra_params_kwargs['sigma_max'] = self.model_wrap.sigmas[-1].item()
421
            if 'n' in parameters:
C
C43H66N12O12S2 已提交
422 423 424
                extra_params_kwargs['n'] = steps
        else:
            extra_params_kwargs['sigmas'] = sigmas
425

426
        if self.config.options.get('brownian_noise', False):
R
RcINS 已提交
427
            noise_sampler = self.create_noise_sampler(x, sigmas, p)
428 429
            extra_params_kwargs['noise_sampler'] = noise_sampler

430
        self.last_latent = x
431
        samples = self.launch_sampling(steps, lambda: self.func(self.model_wrap_cfg, x, extra_args={
432 433 434
            'cond': conditioning,
            'image_cond': image_conditioning,
            'uncond': unconditional_conditioning,
D
devdn 已提交
435 436
            'cond_scale': p.cfg_scale,
            's_min_uncond': self.s_min_uncond
437
        }, disable=False, callback=self.callback_state, **extra_params_kwargs))
438

A
AUTOMATIC 已提交
439
        return samples
440