Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

initial refiner support #12371

Merged
merged 9 commits into from
Aug 10, 2023
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
add infotext
add proper support for recalculating conds in k-diffusion samplers
remove support for compvis samplers
  • Loading branch information
AUTOMATIC1111 committed Aug 6, 2023
commit 5a0db84b6c7322082c7532df11a29a95a59a612b
2 changes: 2 additions & 0 deletions modules/generation_parameters_copypaste.py
Original file line number Diff line number Diff line change
Expand Up @@ -344,6 +344,8 @@ def parse_generation_parameters(x: str):
('Pad conds', 'pad_cond_uncond'),
('VAE Encoder', 'sd_vae_encode_method'),
('VAE Decoder', 'sd_vae_decode_method'),
('Refiner', 'sd_refiner_checkpoint'),
('Refiner switch at', 'sd_refiner_switch_at'),
]


Expand Down
10 changes: 10 additions & 0 deletions modules/processing.py
Original file line number Diff line number Diff line change
Expand Up @@ -370,6 +370,9 @@ def setup_conds(self):
self.uc = self.get_conds_with_caching(prompt_parser.get_learned_conditioning, negative_prompts, self.steps * self.step_multiplier, [self.cached_uc], self.extra_network_data)
self.c = self.get_conds_with_caching(prompt_parser.get_multicond_learned_conditioning, prompts, self.steps * self.step_multiplier, [self.cached_c], self.extra_network_data)

def get_conds(self):
return self.c, self.uc

def parse_extra_network_prompts(self):
self.prompts, self.extra_network_data = extra_networks.parse_prompts(self.prompts)

Expand Down Expand Up @@ -1251,6 +1254,13 @@ def setup_conds(self):
with devices.autocast():
extra_networks.activate(self, self.extra_network_data)

def get_conds(self):
if self.is_hr_pass:
return self.hr_c, self.hr_uc

return super().get_conds()


def parse_extra_network_prompts(self):
res = super().parse_extra_network_prompts()

Expand Down
29 changes: 20 additions & 9 deletions modules/sd_samplers_common.py
Original file line number Diff line number Diff line change
Expand Up @@ -131,16 +131,27 @@ def torchsde_randn(size, dtype, device, seed):

def apply_refiner(sampler):
completed_ratio = sampler.step / sampler.steps
if completed_ratio > shared.opts.sd_refiner_switch_at and shared.sd_model.sd_checkpoint_info.title != shared.opts.sd_refiner_checkpoint:
refiner_checkpoint_info = sd_models.get_closet_checkpoint_match(shared.opts.sd_refiner_checkpoint)
if refiner_checkpoint_info is None:
raise Exception(f'Could not find checkpoint with name {shared.opts.sd_refiner_checkpoint}')

with sd_models.SkipWritingToConfig():
sd_models.reload_model_weights(info=refiner_checkpoint_info)
if completed_ratio <= shared.opts.sd_refiner_switch_at:
return False

if shared.sd_model.sd_checkpoint_info.title == shared.opts.sd_refiner_checkpoint:
return False

refiner_checkpoint_info = sd_models.get_closet_checkpoint_match(shared.opts.sd_refiner_checkpoint)
if refiner_checkpoint_info is None:
raise Exception(f'Could not find checkpoint with name {shared.opts.sd_refiner_checkpoint}')

sampler.p.extra_generation_params['Refiner'] = refiner_checkpoint_info.short_title
sampler.p.extra_generation_params['Refiner switch at'] = shared.opts.sd_refiner_switch_at

with sd_models.SkipWritingToConfig():
sd_models.reload_model_weights(info=refiner_checkpoint_info)

devices.torch_gc()
sampler.p.setup_conds()
sampler.update_inner_model()

devices.torch_gc()
return True

sampler.update_inner_model()

sampler.p.setup_conds()
2 changes: 0 additions & 2 deletions modules/sd_samplers_compvis.py
Original file line number Diff line number Diff line change
Expand Up @@ -71,8 +71,6 @@ def before_sample(self, x, ts, cond, unconditional_conditioning):
if state.interrupted or state.skipped:
raise sd_samplers_common.InterruptedException

sd_samplers_common.apply_refiner(self)

if self.stop_at is not None and self.step > self.stop_at:
raise sd_samplers_common.InterruptedException

Expand Down
24 changes: 16 additions & 8 deletions modules/sd_samplers_kdiffusion.py
Original file line number Diff line number Diff line change
Expand Up @@ -87,8 +87,9 @@ class CFGDenoiser(torch.nn.Module):
negative prompt.
"""

def __init__(self):
def __init__(self, sampler):
super().__init__()
self.sampler = sampler
self.model_wrap = None
self.mask = None
self.nmask = None
Expand Down Expand Up @@ -126,11 +127,17 @@ def combine_denoised_for_edit_model(self, x_out, cond_scale):
def update_inner_model(self):
self.model_wrap = None

c, uc = self.p.get_conds()
self.sampler.sampler_extra_args['cond'] = c
self.sampler.sampler_extra_args['uncond'] = uc

def forward(self, x, sigma, uncond, cond, cond_scale, s_min_uncond, image_cond):
if state.interrupted or state.skipped:
raise sd_samplers_common.InterruptedException

sd_samplers_common.apply_refiner(self)
if sd_samplers_common.apply_refiner(self):
cond = self.sampler.sampler_extra_args['cond']
uncond = self.sampler.sampler_extra_args['uncond']

# 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.
Expand Down Expand Up @@ -282,12 +289,12 @@ def randn_like(self, x):

class KDiffusionSampler:
def __init__(self, funcname, sd_model):

self.p = None
self.funcname = funcname
self.func = funcname if callable(funcname) else getattr(k_diffusion.sampling, self.funcname)
self.extra_params = sampler_extra_params.get(funcname, [])
self.model_wrap_cfg = CFGDenoiser()
self.sampler_extra_args = {}
self.model_wrap_cfg = CFGDenoiser(self)
self.model_wrap = self.model_wrap_cfg.inner_model
self.sampler_noises = None
self.stop_at = None
Expand Down Expand Up @@ -476,15 +483,15 @@ def sample_img2img(self, p, x, noise, conditioning, unconditional_conditioning,

self.model_wrap_cfg.init_latent = x
self.last_latent = x
extra_args = {
self.sampler_extra_args = {
'cond': conditioning,
'image_cond': image_conditioning,
'uncond': unconditional_conditioning,
'cond_scale': p.cfg_scale,
's_min_uncond': self.s_min_uncond
}

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))
samples = self.launch_sampling(t_enc + 1, lambda: self.func(self.model_wrap_cfg, xi, extra_args=self.sampler_extra_args, disable=False, callback=self.callback_state, **extra_params_kwargs))

if self.model_wrap_cfg.padded_cond_uncond:
p.extra_generation_params["Pad conds"] = True
Expand Down Expand Up @@ -514,13 +521,14 @@ def sample(self, p, x, conditioning, unconditional_conditioning, steps=None, ima
extra_params_kwargs['noise_sampler'] = noise_sampler

self.last_latent = x
samples = self.launch_sampling(steps, lambda: self.func(self.model_wrap_cfg, x, extra_args={
self.sampler_extra_args = {
'cond': conditioning,
'image_cond': image_conditioning,
'uncond': unconditional_conditioning,
'cond_scale': p.cfg_scale,
's_min_uncond': self.s_min_uncond
}, disable=False, callback=self.callback_state, **extra_params_kwargs))
}
samples = self.launch_sampling(steps, lambda: self.func(self.model_wrap_cfg, x, extra_args=self.sampler_extra_args, disable=False, callback=self.callback_state, **extra_params_kwargs))

if self.model_wrap_cfg.padded_cond_uncond:
p.extra_generation_params["Pad conds"] = True
Expand Down