Compare commits

..
Author SHA1 Message Date
DepFA 7562ac7b8f dangerous lack of attention 2022-09-27 18:53:19 +01:00
DepFA 4a879dc6a2 Revert Script changes 2022-09-27 18:52:36 +01:00
DepFA 5de8c81106 override compatible_samplers with Euler 2022-09-27 18:47:29 +01:00
DepFA 584df9485d Include compatible_samplers method and client output 2022-09-27 18:46:42 +01:00
Connum 0f703af695 Merge branch 'master' into img2img-alt-force-method 2022-09-27 19:31:26 +02:00
Connum 4f5f78658e make UI restraints (currently sampling method only) more flexible and reusable across scripts 2022-09-27 19:31:01 +02:00
Connum c149363224 force Euler method for the "img2img alternative test" script 2022-09-27 10:09:17 +02:00
AUTOMATIC ada901ed66 added console outputs, more clear indication of progress, and ability to specify full filename to checkpoint merger
restore "Loading..." text
2022-09-27 10:44:00 +03:00
AUTOMATIC1111 a9dc307a21 Merge pull request #1066 from moorehousew/master
Add support for checkpoint merging
2022-09-27 09:59:37 +03:00
AUTOMATIC1111 dbe072dcff Merge pull request #1126 from AUTOMATIC1111/notification-sound
adds support for a notification.mp3 in the root directory that will play upon completion (fixes #1013)
2022-09-27 09:57:16 +03:00
DepFA adbd26a68f add missing s_tmax 2022-09-27 09:30:45 +03:00
DepFA 48d5796f0d pass eta to tex2img sampler 2022-09-27 09:30:45 +03:00
DepFA 76d6f7b407 Add DDIM Eta to txt2img in xy_grid 2022-09-27 09:30:45 +03:00
DepFA 61585e5778 rename DDIM eta label 2022-09-27 09:30:45 +03:00
DepFA fc2aa6b8f3 Add extra sampler params to xy_grid 2022-09-27 09:30:45 +03:00
DepFA a860839f1f take extra sampler properties from StableDiffusionProcessing 2022-09-27 09:30:45 +03:00
DepFA 4ea36a37d6 add sampler properties to StableDiffusionProcessing and Processed 2022-09-27 09:30:45 +03:00
DepFA 2ab3d593f9 pass extra KDiffusionSampler function parameters 2022-09-27 09:30:45 +03:00
DepFA 6b78833e33 Add extra kdiffusion parameters 2022-09-27 09:30:45 +03:00
DepFA ed5736139c pass ddim_eta and ddim_discretize 2022-09-27 09:30:45 +03:00
DepFA 619668ccfe Add options for exposed ddim sampler params
ddim_eta & ddim_discretize
2022-09-27 09:30:45 +03:00
DepFA 175baaaca2 xy_grid - Show blank cells when grid is incomplete 2022-09-27 09:06:44 +03:00
William Moorehouse dc11748dea Added smoothstep interpolation to checkpoint merging 2022-09-26 10:50:21 -04:00
William Moorehouse 91643f651d Add support for checkpoint merging 2022-09-25 19:22:12 -04:00
11 changed files with 232 additions and 20 deletions

No files matched your search

+45
View File
@@ -183,3 +183,48 @@ onUiUpdate(function(){
json_elem.parentElement.style.display="none"
})
/**
* Implement script-dependent UI restraints, e.g. forcing a specific sampling method
*/
let prev_ui_states = {};
function updateScriptRestraints() {
const currentTab = get_uiCurrentTab()?.textContent.trim();
const restraintsField = Array.from(gradioApp().querySelectorAll(`#${currentTab}_script_restraints_json textarea`))
.filter(el => uiElementIsVisible(el.closest('.gr-form')))?.[0];
if ( ! restraintsField ) {
return;
}
if ( typeof prev_ui_states[currentTab] === 'undefined' ) {
prev_ui_states[currentTab] = {};
}
window.requestAnimationFrame(() => {
const restraints = JSON.parse(restraintsField.value);
// const scriptSelect = gradioApp().querySelector(`#${currentTab}_scripts select`);
const methodRadios = gradioApp().querySelectorAll(`[name="radio-${currentTab}_sampling"]`);
if( restraints?.methods?.length ) {
prev_ui_states[currentTab].sampling_method = gradioApp().querySelector(`[name="radio-${currentTab}_sampling"]:checked`);
methodRadios.forEach(radio => {
const isAllowed = restraints.methods.includes(radio.value);
const label = radio.closest('label');
radio.disabled = !isAllowed;
radio.checked = isAllowed;
label.classList[isAllowed ? 'remove' : 'add']('!cursor-not-allowed','disabled');
label.title = !isAllowed ? `The selected script does not work with this method` : '';
});
} else {
// reset to previously selected method
methodRadios.forEach(radio => {
const label = radio.closest('label');
radio.disabled = false;
radio.checked = radio === prev_ui_states[currentTab].sampling_method;
label.classList.remove('!cursor-not-allowed','disabled');
label.title = '';
});
}
})
}
+57
View File
@@ -3,6 +3,9 @@ import os
import numpy as np
from PIL import Image
import torch
import tqdm
from modules import processing, shared, images, devices
from modules.shared import opts
import modules.gfpgan_model
@@ -135,3 +138,57 @@ def run_pnginfo(image):
info = f"<div><p>{message}<p></div>"
return '', geninfo, info
def run_modelmerger(modelname_0, modelname_1, interp_method, interp_amount):
# Linear interpolation (https://en.wikipedia.org/wiki/Linear_interpolation)
def weighted_sum(theta0, theta1, alpha):
return ((1 - alpha) * theta0) + (alpha * theta1)
# Smoothstep (https://en.wikipedia.org/wiki/Smoothstep)
def sigmoid(theta0, theta1, alpha):
alpha = alpha * alpha * (3 - (2 * alpha))
return theta0 + ((theta1 - theta0) * alpha)
if os.path.exists(modelname_0):
model0_filename = modelname_0
modelname_0 = os.path.splitext(os.path.basename(modelname_0))[0]
else:
model0_filename = 'models/' + modelname_0 + '.ckpt'
if os.path.exists(modelname_1):
model1_filename = modelname_1
modelname_1 = os.path.splitext(os.path.basename(modelname_1))[0]
else:
model1_filename = 'models/' + modelname_1 + '.ckpt'
print(f"Loading {model0_filename}...")
model_0 = torch.load(model0_filename, map_location='cpu')
print(f"Loading {model1_filename}...")
model_1 = torch.load(model1_filename, map_location='cpu')
theta_0 = model_0['state_dict']
theta_1 = model_1['state_dict']
theta_funcs = {
"Weighted Sum": weighted_sum,
"Sigmoid": sigmoid,
}
theta_func = theta_funcs[interp_method]
print(f"Merging...")
for key in tqdm.tqdm(theta_0.keys()):
if 'model' in key and key in theta_1:
theta_0[key] = theta_func(theta_0[key], theta_1[key], interp_amount)
for key in theta_1.keys():
if 'model' in key and key not in theta_0:
theta_0[key] = theta_1[key]
output_modelname = 'models/' + modelname_0 + '-' + modelname_1 + '-merged.ckpt'
print(f"Saving to {output_modelname}...")
torch.save(model_0, output_modelname)
print(f"Checkpoint saved.")
return "Checkpoint saved to " + output_modelname
+15 -1
View File
@@ -78,7 +78,14 @@ class StableDiffusionProcessing:
self.paste_to = None
self.color_corrections = None
self.denoising_strength: float = 0
self.ddim_eta = opts.ddim_eta
self.ddim_discretize = opts.ddim_discretize
self.s_churn = opts.s_churn
self.s_tmin = opts.s_tmin
self.s_tmax = float('inf') # not representable as a standard ui option
self.s_noise = opts.s_noise
if not seed_enable_extras:
self.subseed = -1
self.subseed_strength = 0
@@ -117,6 +124,13 @@ class Processed:
self.extra_generation_params = p.extra_generation_params
self.index_of_first_image = index_of_first_image
self.ddim_eta = p.ddim_eta
self.ddim_discretize = p.ddim_discretize
self.s_churn = p.s_churn
self.s_tmin = p.s_tmin
self.s_tmax = p.s_tmax
self.s_noise = p.s_noise
self.prompt = self.prompt if type(self.prompt) != list else self.prompt[0]
self.negative_prompt = self.negative_prompt if type(self.negative_prompt) != list else self.negative_prompt[0]
self.seed = int(self.seed if type(self.seed) != list else self.seed[0])
+29 -5
View File
@@ -1,6 +1,7 @@
import os
import sys
import traceback
import json
import modules.ui as ui
import gradio as gr
@@ -24,6 +25,14 @@ class Script:
def ui(self, is_img2img):
pass
# Put restraints on UI elements when this script is selected.
# Restricting the available sampling methods:
# {
# "methods": [ "Euler", "DDIM" ]
# }
def ui_restraints(self):
return {}
# Determines when the script should be shown in the dropdown menu via the
# returned value. As an example:
# is_img2img is True if the current tab is img2img, and False if it is txt2img.
@@ -46,8 +55,7 @@ class Script:
# your description as the value.
def describe(self):
return ""
scripts_data = []
@@ -106,7 +114,9 @@ class ScriptRunner:
titles = [wrap_call(script.title, script.filename, "title") or f"{script.filename} [error]" for script in self.scripts]
dropdown = gr.Dropdown(label="Script", choices=["None"] + titles, value="None", type="index")
id_prefix = "img2img_" if is_img2img else "txt2img_"
dropdown = gr.Dropdown(label="Script", choices=["None"] + titles, value="None", type="index", elem_id=id_prefix+"scripts")
inputs = [dropdown]
for script in self.scripts:
@@ -121,20 +131,27 @@ class ScriptRunner:
for control in controls:
control.custom_script_source = os.path.basename(script.filename)
control.visible = False
inputs += controls
script.args_to = len(inputs)
script_restraints_json = gr.Textbox(value="{}", elem_id=id_prefix+"script_restraints_json", show_label=False, visible=False)
inputs += [script_restraints_json];
def select_script(script_index):
if 0 < script_index <= len(self.scripts):
script = self.scripts[script_index-1]
args_from = script.args_from
args_to = script.args_to
else:
script = None
args_from = 0
args_to = 0
return [ui.gr_show(True if i == 0 else args_from <= i < args_to) for i in range(len(inputs))]
return (
[ui.gr_show(True if i == 0 else args_from <= i < args_to) for i in range(len(inputs)-1)]
+ [gr.Textbox.update(value=json.dumps(script.ui_restraints() if script is not None else {}), visible=False)]
)
dropdown.change(
fn=select_script,
@@ -142,6 +159,13 @@ class ScriptRunner:
outputs=inputs
)
script_restraints_json.change(
_js="updateScriptRestraints",
fn=lambda: None,
inputs=[],
outputs=[]
)
return inputs
def run(self, p: StableDiffusionProcessing, *args):
+22 -6
View File
@@ -37,6 +37,11 @@ samplers = [
]
samplers_for_img2img = [x for x in samplers if x.name != 'PLMS']
sampler_extra_params = {
'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'],
}
def setup_img2img_steps(p, steps=None):
if opts.img2img_fix_steps or steps is not None:
@@ -120,9 +125,9 @@ class VanillaStableDiffusionSampler:
# existing code fails with cetain step counts, like 9
try:
self.sampler.make_schedule(ddim_num_steps=steps, verbose=False)
self.sampler.make_schedule(ddim_num_steps=steps, ddim_eta=p.ddim_eta, ddim_discretize=p.ddim_discretize, verbose=False)
except Exception:
self.sampler.make_schedule(ddim_num_steps=steps+1, verbose=False)
self.sampler.make_schedule(ddim_num_steps=steps+1,ddim_eta=p.ddim_eta, ddim_discretize=p.ddim_discretize, verbose=False)
x1 = self.sampler.stochastic_encode(x, torch.tensor([t_enc] * int(x.shape[0])).to(shared.device), noise=noise)
@@ -149,9 +154,9 @@ class VanillaStableDiffusionSampler:
# existing code fails with cetin step counts, like 9
try:
samples_ddim, _ = self.sampler.sample(S=steps, conditioning=conditioning, batch_size=int(x.shape[0]), shape=x[0].shape, verbose=False, unconditional_guidance_scale=p.cfg_scale, unconditional_conditioning=unconditional_conditioning, x_T=x)
samples_ddim, _ = self.sampler.sample(S=steps, conditioning=conditioning, batch_size=int(x.shape[0]), shape=x[0].shape, verbose=False, unconditional_guidance_scale=p.cfg_scale, unconditional_conditioning=unconditional_conditioning, x_T=x, eta=p.ddim_eta)
except Exception:
samples_ddim, _ = self.sampler.sample(S=steps+1, conditioning=conditioning, batch_size=int(x.shape[0]), shape=x[0].shape, verbose=False, unconditional_guidance_scale=p.cfg_scale, unconditional_conditioning=unconditional_conditioning, x_T=x)
samples_ddim, _ = self.sampler.sample(S=steps+1, conditioning=conditioning, batch_size=int(x.shape[0]), shape=x[0].shape, verbose=False, unconditional_guidance_scale=p.cfg_scale, unconditional_conditioning=unconditional_conditioning, x_T=x, eta=p.ddim_eta)
return samples_ddim
@@ -224,6 +229,7 @@ class KDiffusionSampler:
self.model_wrap = k_diffusion.external.CompVisDenoiser(sd_model, quantize=shared.opts.enable_quantization)
self.funcname = funcname
self.func = getattr(k_diffusion.sampling, self.funcname)
self.extra_params = sampler_extra_params.get(funcname,[])
self.model_wrap_cfg = CFGDenoiser(self.model_wrap)
self.sampler_noises = None
self.sampler_noise_index = 0
@@ -269,7 +275,12 @@ class KDiffusionSampler:
if self.sampler_noises is not None:
k_diffusion.sampling.torch = TorchHijack(self)
return self.func(self.model_wrap_cfg, xi, sigma_sched, extra_args={'cond': conditioning, 'uncond': unconditional_conditioning, 'cond_scale': p.cfg_scale}, disable=False, callback=self.callback_state)
extra_params_kwargs = {}
for val in self.extra_params:
if hasattr(p,val):
extra_params_kwargs[val] = getattr(p,val)
return self.func(self.model_wrap_cfg, xi, sigma_sched, extra_args={'cond': conditioning, 'uncond': unconditional_conditioning, 'cond_scale': p.cfg_scale}, disable=False, callback=self.callback_state, **extra_params_kwargs)
def sample(self, p, x, conditioning, unconditional_conditioning, steps=None):
steps = steps or p.steps
@@ -286,7 +297,12 @@ class KDiffusionSampler:
if self.sampler_noises is not None:
k_diffusion.sampling.torch = TorchHijack(self)
samples = self.func(self.model_wrap_cfg, x, sigmas, extra_args={'cond': conditioning, 'uncond': unconditional_conditioning, 'cond_scale': p.cfg_scale}, disable=False, callback=self.callback_state)
extra_params_kwargs = {}
for val in self.extra_params:
if hasattr(p,val):
extra_params_kwargs[val] = getattr(p,val)
samples = self.func(self.model_wrap_cfg, x, sigmas, extra_args={'cond': conditioning, 'uncond': unconditional_conditioning, 'cond_scale': p.cfg_scale}, disable=False, callback=self.callback_state, **extra_params_kwargs)
return samples
+7
View File
@@ -220,6 +220,13 @@ options_templates.update(options_section(('ui', "User interface"), {
"js_modal_lightbox_initialy_zoomed": OptionInfo(True, "Show images zoomed in by default in full page image viewer"),
}))
options_templates.update(options_section(('sampler-params', "Sampler parameters"), {
"ddim_eta": OptionInfo(0.0, "DDIM eta", gr.Slider, {"minimum": 0.0, "maximum": 1.0, "step": 0.01}),
"ddim_discretize": OptionInfo('uniform', "img2img DDIM discretize", gr.Radio, {"choices": ['uniform','quad']}),
's_churn': OptionInfo(0.0, "sigma churn", gr.Slider, {"minimum": 0.0, "maximum": 1.0, "step": 0.01}),
's_tmin': OptionInfo(0.0, "sigma tmin", gr.Slider, {"minimum": 0.0, "maximum": 1.0, "step": 0.01}),
's_noise': OptionInfo(1.0, "sigma noise", gr.Slider, {"minimum": 0.0, "maximum": 1.0, "step": 0.01}),
}))
class Options:
data = None
+33 -4
View File
@@ -49,6 +49,7 @@ sample_img2img = sample_img2img if os.path.exists(sample_img2img) else None
css_hide_progressbar = """
.wrap .m-12 svg { display:none!important; }
.wrap .m-12::before { content:"Loading..." }
.progress-bar { display:none!important; }
.meta-text { display:none!important; }
"""
@@ -393,7 +394,7 @@ def setup_progressbar(progressbar, preview, id_part):
)
def create_ui(txt2img, img2img, run_extras, run_pnginfo):
def create_ui(txt2img, img2img, run_extras, run_pnginfo, run_modelmerger):
with gr.Blocks(analytics_enabled=False) as txt2img_interface:
txt2img_prompt, roll, txt2img_prompt_style, txt2img_negative_prompt, txt2img_prompt_style2, submit, _, txt2img_prompt_style_apply, txt2img_save_style, paste = create_toprow(is_img2img=False)
dummy_component = gr.Label(visible=False)
@@ -409,7 +410,7 @@ def create_ui(txt2img, img2img, run_extras, run_pnginfo):
with gr.Row().style(equal_height=False):
with gr.Column(variant='panel'):
steps = gr.Slider(minimum=1, maximum=150, step=1, label="Sampling Steps", value=20)
steps = gr.Slider(minimum=1, maximum=150, step=1, label="Sampling Steps", value=20, elem_id="txt2img_steps")
sampler_index = gr.Radio(label='Sampling method', elem_id="txt2img_sampling", choices=[x.name for x in samplers], value=samplers[0].name, type="index")
with gr.Group():
@@ -588,8 +589,8 @@ def create_ui(txt2img, img2img, run_extras, run_pnginfo):
with gr.Row():
resize_mode = gr.Radio(label="Resize mode", elem_id="resize_mode", show_label=False, choices=["Just resize", "Crop and resize", "Resize and fill"], type="index", value="Just resize")
steps = gr.Slider(minimum=1, maximum=150, step=1, label="Sampling Steps", value=20)
sampler_index = gr.Radio(label='Sampling method', choices=[x.name for x in samplers_for_img2img], value=samplers_for_img2img[0].name, type="index")
steps = gr.Slider(minimum=1, maximum=150, step=1, label="Sampling Steps", value=20, elem_id="img2img_steps")
sampler_index = gr.Radio(label='Sampling method', elem_id="img2img_sampling", choices=[x.name for x in samplers_for_img2img], value=samplers_for_img2img[0].name, type="index")
with gr.Group():
width = gr.Slider(minimum=64, maximum=2048, step=64, label="Width", value=512)
@@ -853,6 +854,33 @@ def create_ui(txt2img, img2img, run_extras, run_pnginfo):
outputs=[html, generation_info, html2],
)
with gr.Blocks() as modelmerger_interface:
with gr.Row().style(equal_height=False):
with gr.Column(variant='panel'):
gr.HTML(value="<p>A merger of the two checkpoints will be generated in your <b>/models</b> directory.</p>")
modelname_0 = gr.Textbox(elem_id="modelmerger_modelname_0", label="Model Name (to)")
modelname_1 = gr.Textbox(elem_id="modelmerger_modelname_1", label="Model Name (from)")
interp_method = gr.Radio(choices=["Weighted Sum", "Sigmoid"], value="Weighted Sum", label="Interpolation Method")
interp_amount = gr.Slider(minimum=0.0, maximum=1.0, step=0.05, label='Interpolation Amount', value=0.3)
submit = gr.Button(elem_id="modelmerger_merge", label="Merge", variant='primary')
with gr.Column(variant='panel'):
submit_result = gr.Textbox(elem_id="modelmerger_result", show_label=False)
submit.click(
fn=run_modelmerger,
inputs=[
modelname_0,
modelname_1,
interp_method,
interp_amount
],
outputs=[
submit_result,
]
)
def create_setting_component(key):
def fun():
return opts.data[key] if key in opts.data else opts.data_labels[key].default
@@ -950,6 +978,7 @@ def create_ui(txt2img, img2img, run_extras, run_pnginfo):
(img2img_interface, "img2img", "img2img"),
(extras_interface, "Extras", "extras"),
(pnginfo_interface, "PNG Info", "pnginfo"),
(modelmerger_interface, "Checkpoint Merger", "modelmerger"),
(settings_interface, "Settings", "settings"),
]
+7 -1
View File
@@ -119,7 +119,7 @@ class Script(scripts.Script):
def show(self, is_img2img):
return is_img2img
def ui(self, is_img2img):
original_prompt = gr.Textbox(label="Original prompt", lines=1)
original_negative_prompt = gr.Textbox(label="Original negative prompt", lines=1)
@@ -129,6 +129,12 @@ class Script(scripts.Script):
sigma_adjustment = gr.Checkbox(label="Sigma adjustment for finding noise for image", value=False)
return [original_prompt, original_negative_prompt, cfg, st, randomness, sigma_adjustment]
def ui_restraints(self):
restraints = {
"methods": ["Euler"]
}
return restraints
def run(self, p, original_prompt, original_negative_prompt, cfg, st, randomness, sigma_adjustment):
p.batch_size = 1
p.batch_count = 1
+11 -2
View File
@@ -2,6 +2,7 @@ from collections import namedtuple
from copy import copy
import random
from PIL import Image
import numpy as np
import modules.scripts as scripts
@@ -86,7 +87,12 @@ axis_options = [
AxisOption("Prompt S/R", str, apply_prompt, format_value),
AxisOption("Sampler", str, apply_sampler, format_value),
AxisOption("Checkpoint name", str, apply_checkpoint, format_value),
AxisOptionImg2Img("Denoising", float, apply_field("denoising_strength"), format_value_add_label), # as it is now all AxisOptionImg2Img items must go after AxisOption ones
AxisOption("Sigma Churn", float, apply_field("s_churn"), format_value_add_label),
AxisOption("Sigma min", float, apply_field("s_tmin"), format_value_add_label),
AxisOption("Sigma max", float, apply_field("s_tmax"), format_value_add_label),
AxisOption("Sigma noise", float, apply_field("s_noise"), format_value_add_label),
AxisOption("DDIM Eta", float, apply_field("ddim_eta"), format_value_add_label),
AxisOptionImg2Img("Denoising", float, apply_field("denoising_strength"), format_value_add_label),# as it is now all AxisOptionImg2Img items must go after AxisOption ones
]
@@ -108,7 +114,10 @@ def draw_xy_grid(p, xs, ys, x_labels, y_labels, cell, draw_legend):
if first_pocessed is None:
first_pocessed = processed
res.append(processed.images[0])
try:
res.append(processed.images[0])
except:
res.append(Image.new(res[0].mode, res[0].size))
grid = images.image_grid(res, rows=len(ys))
if draw_legend:
+4
View File
@@ -222,6 +222,10 @@ input[type="range"]{
margin: 0.5em 0 -0.3em 0;
}
.gr-input-label.disabled {
opacity: 0.48;
}
#txt2img_sampling label{
padding-left: 0.6em;
padding-right: 0.6em;
+2 -1
View File
@@ -85,7 +85,8 @@ def webui():
txt2img=wrap_gradio_gpu_call(modules.txt2img.txt2img),
img2img=wrap_gradio_gpu_call(modules.img2img.img2img),
run_extras=wrap_gradio_gpu_call(modules.extras.run_extras),
run_pnginfo=modules.extras.run_pnginfo
run_pnginfo=modules.extras.run_pnginfo,
run_modelmerger=modules.extras.run_modelmerger
)
demo.launch(