2023-01-30 06:51:06 +00:00
from collections import deque
2022-09-03 09:08:45 +00:00
import torch
2022-09-28 07:49:07 +00:00
import inspect
2023-02-03 23:19:56 +00:00
import einops
2022-09-03 09:08:45 +00:00
import k_diffusion . sampling
2023-01-30 07:47:09 +00:00
from modules import prompt_parser , devices , sd_samplers_common
2022-09-03 09:08:45 +00:00
2023-01-30 06:51:06 +00:00
from modules . shared import opts , state
2022-09-03 09:08:45 +00:00
import modules . shared as shared
2022-11-02 00:38:17 +00:00
from modules . script_callbacks import CFGDenoiserParams , cfg_denoiser_callback
2022-09-03 09:08:45 +00:00
2022-09-03 14:21:15 +00:00
samplers_k_diffusion = [
2022-11-27 13:28:32 +00:00
( ' Euler a ' , ' sample_euler_ancestral ' , [ ' k_euler_a ' , ' k_euler_ancestral ' ] , { } ) ,
2022-10-06 11:12:52 +00:00
( ' Euler ' , ' sample_euler ' , [ ' k_euler ' ] , { } ) ,
( ' LMS ' , ' sample_lms ' , [ ' k_lms ' ] , { } ) ,
( ' Heun ' , ' sample_heun ' , [ ' k_heun ' ] , { } ) ,
2022-12-24 06:03:45 +00:00
( ' DPM2 ' , ' sample_dpm_2 ' , [ ' k_dpm_2 ' ] , { ' discard_next_to_last_sigma ' : True } ) ,
( ' DPM2 a ' , ' sample_dpm_2_ancestral ' , [ ' k_dpm_2_a ' ] , { ' discard_next_to_last_sigma ' : True } ) ,
2022-11-05 15:32:22 +00:00
( ' DPM++ 2S a ' , ' sample_dpmpp_2s_ancestral ' , [ ' k_dpmpp_2s_a ' ] , { } ) ,
( ' DPM++ 2M ' , ' sample_dpmpp_2m ' , [ ' k_dpmpp_2m ' ] , { } ) ,
2022-11-22 14:24:50 +00:00
( ' DPM++ SDE ' , ' sample_dpmpp_sde ' , [ ' k_dpmpp_sde ' ] , { } ) ,
2022-10-06 11:12:52 +00:00
( ' DPM fast ' , ' sample_dpm_fast ' , [ ' k_dpm_fast ' ] , { } ) ,
( ' DPM adaptive ' , ' sample_dpm_adaptive ' , [ ' k_dpm_ad ' ] , { } ) ,
( ' LMS Karras ' , ' sample_lms ' , [ ' k_lms_ka ' ] , { ' scheduler ' : ' karras ' } ) ,
2022-12-24 06:03:45 +00:00
( ' DPM2 Karras ' , ' sample_dpm_2 ' , [ ' k_dpm_2_ka ' ] , { ' scheduler ' : ' karras ' , ' discard_next_to_last_sigma ' : True } ) ,
( ' DPM2 a Karras ' , ' sample_dpm_2_ancestral ' , [ ' k_dpm_2_a_ka ' ] , { ' scheduler ' : ' karras ' , ' discard_next_to_last_sigma ' : True } ) ,
2022-11-05 15:32:22 +00:00
( ' DPM++ 2S a Karras ' , ' sample_dpmpp_2s_ancestral ' , [ ' k_dpmpp_2s_a_ka ' ] , { ' scheduler ' : ' karras ' } ) ,
( ' DPM++ 2M Karras ' , ' sample_dpmpp_2m ' , [ ' k_dpmpp_2m_ka ' ] , { ' scheduler ' : ' karras ' } ) ,
2022-11-22 14:24:50 +00:00
( ' DPM++ SDE Karras ' , ' sample_dpmpp_sde ' , [ ' k_dpmpp_sde_ka ' ] , { ' scheduler ' : ' karras ' } ) ,
2022-09-03 14:21:15 +00:00
]
samplers_data_k_diffusion = [
2023-01-30 06:51:06 +00:00
sd_samplers_common . SamplerData ( label , lambda model , funcname = funcname : KDiffusionSampler ( funcname , model ) , aliases , options )
2022-10-06 11:12:52 +00:00
for label , funcname , aliases , options in samplers_k_diffusion
2022-09-03 14:21:15 +00:00
if hasattr ( k_diffusion . sampling , funcname )
]
2022-09-26 08:56:47 +00:00
sampler_extra_params = {
2022-09-28 07:49:07 +00:00
' 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 ' ] ,
2022-09-26 08:56:47 +00:00
}
2022-09-03 09:08:45 +00:00
2022-10-22 17:48:13 +00:00
2022-09-03 09:08:45 +00:00
class CFGDenoiser ( torch . nn . Module ) :
2023-01-30 07:11:30 +00:00
"""
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 .
"""
2022-09-03 09:08:45 +00:00
def __init__ ( self , model ) :
super ( ) . __init__ ( )
self . inner_model = model
self . mask = None
self . nmask = None
self . init_latent = None
2022-09-15 10:10:16 +00:00
self . step = 0
2023-02-04 08:06:17 +00:00
self . image_cfg_scale = None
2022-09-03 09:08:45 +00:00
2022-12-24 15:38:16 +00:00
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
2023-02-04 08:06:17 +00:00
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
2022-10-19 20:47:45 +00:00
def forward ( self , x , sigma , uncond , cond , cond_scale , image_cond ) :
2022-10-18 14:23:38 +00:00
if state . interrupted or state . skipped :
2023-01-30 06:51:06 +00:00
raise sd_samplers_common . InterruptedException
2022-10-18 14:23:38 +00:00
2023-02-04 08:06:17 +00:00
# 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
2022-10-05 20:16:27 +00:00
conds_list , tensor = prompt_parser . reconstruct_multicond_batch ( cond , self . step )
2022-09-15 10:10:16 +00:00
uncond = prompt_parser . reconstruct_cond_batch ( uncond , self . step )
2023-02-04 08:06:17 +00:00
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) "
2022-10-05 20:16:27 +00:00
batch_size = len ( conds_list )
repeats = [ len ( conds_list [ i ] ) for i in range ( batch_size ) ]
2023-02-04 08:06:17 +00:00
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 ] )
image_cond_in = torch . cat ( [ torch . stack ( [ image_cond [ i ] for _ in range ( n ) ] ) for i , n in enumerate ( repeats ) ] + [ image_cond ] )
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 ] )
image_cond_in = torch . cat ( [ torch . stack ( [ image_cond [ i ] for _ in range ( n ) ] ) for i , n in enumerate ( repeats ) ] + [ image_cond ] + [ torch . zeros_like ( self . init_latent ) ] )
2022-10-05 20:16:27 +00:00
2022-11-02 00:38:17 +00:00
denoiser_params = CFGDenoiserParams ( x_in , image_cond_in , sigma_in , state . sampling_step , state . sampling_steps )
cfg_denoiser_callback ( denoiser_params )
x_in = denoiser_params . x
image_cond_in = denoiser_params . image_cond
sigma_in = denoiser_params . sigma
2022-10-30 23:48:33 +00:00
2022-10-08 12:25:59 +00:00
if tensor . shape [ 1 ] == uncond . shape [ 1 ] :
2023-02-04 08:06:17 +00:00
if not is_edit_model :
cond_in = torch . cat ( [ tensor , uncond ] )
else :
cond_in = torch . cat ( [ tensor , uncond , uncond ] )
2022-10-08 12:25:59 +00:00
if shared . batch_cond_uncond :
2022-10-19 20:47:45 +00:00
x_out = self . inner_model ( x_in , sigma_in , cond = { " c_crossattn " : [ cond_in ] , " c_concat " : [ image_cond_in ] } )
2022-10-08 12:25:59 +00:00
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
2022-10-19 20:47:45 +00:00
x_out [ a : b ] = self . inner_model ( x_in [ a : b ] , sigma_in [ a : b ] , cond = { " c_crossattn " : [ cond_in [ a : b ] ] , " c_concat " : [ image_cond_in [ a : b ] ] } )
2022-09-03 09:08:45 +00:00
else :
2022-10-05 20:16:27 +00:00
x_out = torch . zeros_like ( x_in )
2022-10-08 12:25:59 +00:00
batch_size = batch_size * 2 if shared . batch_cond_uncond else batch_size
for batch_offset in range ( 0 , tensor . shape [ 0 ] , batch_size ) :
2022-10-05 20:16:27 +00:00
a = batch_offset
2022-10-08 12:25:59 +00:00
b = min ( a + batch_size , tensor . shape [ 0 ] )
2023-02-04 08:06:17 +00:00
if not is_edit_model :
c_crossattn = [ tensor [ a : b ] ]
else :
c_crossattn = torch . cat ( [ tensor [ a : b ] ] , uncond )
x_out [ a : b ] = self . inner_model ( x_in [ a : b ] , sigma_in [ a : b ] , cond = { " c_crossattn " : c_crossattn , " c_concat " : [ image_cond_in [ a : b ] ] } )
2022-10-08 12:25:59 +00:00
2022-10-19 20:47:45 +00:00
x_out [ - uncond . shape [ 0 ] : ] = self . inner_model ( x_in [ - uncond . shape [ 0 ] : ] , sigma_in [ - uncond . shape [ 0 ] : ] , cond = { " c_crossattn " : [ uncond ] , " c_concat " : [ image_cond_in [ - uncond . shape [ 0 ] : ] ] } )
2022-10-05 20:16:27 +00:00
2023-01-16 19:59:46 +00:00
devices . test_for_nans ( x_out , " unet " )
2023-01-14 13:29:23 +00:00
if opts . live_preview_content == " Prompt " :
2023-01-30 06:51:06 +00:00
sd_samplers_common . store_latent ( x_out [ 0 : uncond . shape [ 0 ] ] )
2023-01-14 13:29:23 +00:00
elif opts . live_preview_content == " Negative prompt " :
2023-01-30 06:51:06 +00:00
sd_samplers_common . store_latent ( x_out [ - uncond . shape [ 0 ] : ] )
2023-01-14 13:29:23 +00:00
2023-02-04 08:06:17 +00:00
if not is_edit_model :
denoised = self . combine_denoised ( x_out , conds_list , uncond , cond_scale )
else :
denoised = self . combine_denoised_for_edit_model ( x_out , cond_scale )
2022-09-03 09:08:45 +00:00
if self . mask is not None :
denoised = self . init_latent * self . mask + self . nmask * denoised
2022-09-15 10:10:16 +00:00
self . step + = 1
2022-09-03 09:08:45 +00:00
return denoised
2022-09-16 06:47:03 +00:00
class TorchHijack :
2022-11-26 02:12:23 +00:00
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 )
2022-09-16 06:47:03 +00:00
def __getattr__ ( self , item ) :
if item == ' randn_like ' :
2022-11-26 02:12:23 +00:00
return self . randn_like
2022-09-16 06:47:03 +00:00
if hasattr ( torch , item ) :
return getattr ( torch , item )
raise AttributeError ( " ' {} ' object has no attribute ' {} ' " . format ( type ( self ) . __name__ , item ) )
2022-11-26 02:12:23 +00:00
def randn_like ( self , x ) :
if self . sampler_noises :
noise = self . sampler_noises . popleft ( )
if noise . shape == x . shape :
return noise
2022-11-30 13:02:39 +00:00
if x . device . type == ' mps ' :
return torch . randn_like ( x , device = devices . cpu ) . to ( x . device )
else :
return torch . randn_like ( x )
2022-11-26 02:12:23 +00:00
2022-09-13 18:49:58 +00:00
2022-09-03 09:08:45 +00:00
class KDiffusionSampler :
def __init__ ( self , funcname , sd_model ) :
2022-11-26 13:10:46 +00:00
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 )
2022-09-03 09:08:45 +00:00
self . funcname = funcname
self . func = getattr ( k_diffusion . sampling , self . funcname )
2022-09-28 07:49:07 +00:00
self . extra_params = sampler_extra_params . get ( funcname , [ ] )
2023-02-04 00:46:13 +00:00
self . model_wrap_cfg = CFGDenoiser ( self . model_wrap )
2022-09-13 18:49:58 +00:00
self . sampler_noises = None
2022-09-19 13:42:56 +00:00
self . stop_at = None
2022-09-28 15:09:06 +00:00
self . eta = None
2022-10-06 11:12:52 +00:00
self . config = None
2022-10-18 14:23:38 +00:00
self . last_latent = None
2022-09-03 09:08:45 +00:00
2022-10-19 22:09:43 +00:00
self . conditioning_key = sd_model . model . conditioning_key
2022-09-06 16:33:51 +00:00
def callback_state ( self , d ) :
2022-10-18 14:23:38 +00:00
step = d [ ' i ' ]
latent = d [ " denoised " ]
2023-01-14 13:29:23 +00:00
if opts . live_preview_content == " Combined " :
2023-01-30 06:51:06 +00:00
sd_samplers_common . store_latent ( latent )
2022-10-18 14:23:38 +00:00
self . last_latent = latent
if self . stop_at is not None and step > self . stop_at :
2023-01-30 06:51:06 +00:00
raise sd_samplers_common . InterruptedException
2022-10-18 14:23:38 +00:00
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 ( )
2023-01-30 06:51:06 +00:00
except sd_samplers_common . InterruptedException :
2022-10-18 14:23:38 +00:00
return self . last_latent
2022-09-06 16:33:51 +00:00
2022-09-13 18:49:58 +00:00
def number_of_needed_noises ( self , p ) :
return p . steps
2022-09-28 15:09:06 +00:00
def initialize ( self , p ) :
2022-09-19 13:42:56 +00:00
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
2023-01-25 20:25:40 +00:00
self . model_wrap_cfg . step = 0
2023-02-04 08:06:17 +00:00
self . model_wrap_cfg . image_cfg_scale = getattr ( p , ' image_cfg_scale ' , None )
2023-01-30 07:47:09 +00:00
self . eta = p . eta if p . eta is not None else opts . eta_ancestral
2022-09-03 09:08:45 +00:00
2022-11-30 13:02:39 +00:00
k_diffusion . sampling . torch = TorchHijack ( self . sampler_noises if self . sampler_noises is not None else [ ] )
2022-09-16 06:47:03 +00:00
2022-09-26 08:56:47 +00:00
extra_params_kwargs = { }
2022-09-28 07:49:07 +00:00
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 )
2022-09-26 08:56:47 +00:00
2022-09-28 15:09:06 +00:00
if ' eta ' in inspect . signature ( self . func ) . parameters :
2023-01-30 07:47:09 +00:00
if self . eta != 1.0 :
p . extra_generation_params [ " Eta " ] = self . eta
2022-09-28 15:09:06 +00:00
extra_params_kwargs [ ' eta ' ] = self . eta
return extra_params_kwargs
2022-12-24 06:03:45 +00:00
def get_sigmas ( self , p , steps ) :
2023-01-05 07:43:21 +00:00
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
2022-12-26 20:49:13 +00:00
2022-09-30 00:46:06 +00:00
if p . sampler_noise_scheduler_override :
2022-10-06 20:27:01 +00:00
sigmas = p . sampler_noise_scheduler_override ( steps )
elif self . config is not None and self . config . options . get ( ' scheduler ' , None ) == ' karras ' :
2023-01-01 06:51:37 +00:00
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 )
2022-09-30 00:46:06 +00:00
else :
2022-10-06 20:27:01 +00:00
sigmas = self . model_wrap . get_sigmas ( steps )
2022-09-28 15:09:06 +00:00
2023-01-05 07:43:21 +00:00
if discard_next_to_last_sigma :
2022-12-19 03:16:42 +00:00
sigmas = torch . cat ( [ sigmas [ : - 2 ] , sigmas [ - 1 : ] ] )
2022-12-24 06:03:45 +00:00
return sigmas
def sample_img2img ( self , p , x , noise , conditioning , unconditional_conditioning , steps = None , image_conditioning = None ) :
2023-01-30 06:51:06 +00:00
steps , t_enc = sd_samplers_common . setup_img2img_steps ( p , steps )
2022-12-24 06:03:45 +00:00
sigmas = self . get_sigmas ( p , steps )
2022-09-28 15:09:06 +00:00
sigma_sched = sigmas [ steps - t_enc - 1 : ]
2022-10-10 23:02:44 +00:00
xi = x + noise * sigma_sched [ 0 ]
extra_params_kwargs = self . initialize ( p )
if ' sigma_min ' in inspect . signature ( self . func ) . parameters :
2022-10-10 23:36:00 +00:00
## last sigma is zero which isn't allowed by DPM Fast & Adaptive so taking value before last
2022-10-10 23:02:44 +00:00
extra_params_kwargs [ ' sigma_min ' ] = sigma_sched [ - 2 ]
if ' sigma_max ' in inspect . signature ( self . func ) . parameters :
extra_params_kwargs [ ' sigma_max ' ] = sigma_sched [ 0 ]
if ' n ' in inspect . signature ( self . func ) . parameters :
extra_params_kwargs [ ' n ' ] = len ( sigma_sched ) - 1
if ' sigma_sched ' in inspect . signature ( self . func ) . parameters :
extra_params_kwargs [ ' sigma_sched ' ] = sigma_sched
if ' sigmas ' in inspect . signature ( self . func ) . parameters :
extra_params_kwargs [ ' sigmas ' ] = sigma_sched
2022-09-28 15:09:06 +00:00
self . model_wrap_cfg . init_latent = x
2022-10-20 20:49:14 +00:00
self . last_latent = x
2023-02-03 23:19:56 +00:00
extra_args = {
2022-10-19 20:47:45 +00:00
' cond ' : conditioning ,
' image_cond ' : image_conditioning ,
' uncond ' : unconditional_conditioning ,
2023-02-03 23:19:56 +00:00
' cond_scale ' : p . cfg_scale ,
}
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 ) )
2022-10-10 23:02:44 +00:00
2022-10-18 14:23:38 +00:00
return samples
2022-09-03 09:08:45 +00:00
2022-10-19 20:47:45 +00:00
def sample ( self , p , x , conditioning , unconditional_conditioning , steps = None , image_conditioning = None ) :
2022-09-19 13:42:56 +00:00
steps = steps or p . steps
2022-12-24 06:03:45 +00:00
sigmas = self . get_sigmas ( p , steps )
2022-10-06 11:12:52 +00:00
2022-09-03 09:08:45 +00:00
x = x * sigmas [ 0 ]
2022-09-28 15:09:06 +00:00
extra_params_kwargs = self . initialize ( p )
2022-09-29 07:15:38 +00:00
if ' sigma_min ' in inspect . signature ( self . func ) . parameters :
2022-09-29 10:30:33 +00:00
extra_params_kwargs [ ' sigma_min ' ] = self . model_wrap . sigmas [ 0 ] . item ( )
extra_params_kwargs [ ' sigma_max ' ] = self . model_wrap . sigmas [ - 1 ] . item ( )
2022-09-29 07:15:38 +00:00
if ' n ' in inspect . signature ( self . func ) . parameters :
2022-09-29 10:30:33 +00:00
extra_params_kwargs [ ' n ' ] = steps
else :
extra_params_kwargs [ ' sigmas ' ] = sigmas
2022-10-18 14:23:38 +00:00
2022-10-20 20:49:14 +00:00
self . last_latent = x
2022-10-19 20:47:45 +00:00
samples = self . launch_sampling ( steps , lambda : self . func ( self . model_wrap_cfg , x , extra_args = {
' cond ' : conditioning ,
' image_cond ' : image_conditioning ,
' uncond ' : unconditional_conditioning ,
' cond_scale ' : p . cfg_scale
} , disable = False , callback = self . callback_state , * * extra_params_kwargs ) )
2022-10-18 14:23:38 +00:00
2022-09-19 13:42:56 +00:00
return samples
2022-09-03 09:08:45 +00:00