JadenFK's picture
Merge branch 'main' of https://huggingface.co/spaces/baulab/Erasing-Concepts-In-Diffusion into main
aaad790
raw
history blame
No virus
10.6 kB
from pathlib import Path
import gradio as gr
import torch
from finetuning import FineTunedModel
from StableDiffuser import StableDiffuser
from tqdm import tqdm
model_map = {
'Car' : 'models/car.pt',
'Van Gogh' : 'models/vangogh.pt',
}
class Demo:
def __init__(self) -> None:
self.training = False
self.generating = False
self.nsteps = 50
self.diffuser = StableDiffuser(scheduler='DDIM', seed=42).to('cuda')
self.finetuner = None
with gr.Blocks() as demo:
self.layout()
self.switch_model(self.model_dropdown.value)
self.finetuner = self.finetuner.eval().half()
self.diffuser = self.diffuser.eval().half()
demo.queue(concurrency_count=2).launch()
def disable(self):
return [gr.update(interactive=False), gr.update(interactive=False)]
def switch_model(self, model_name):
if not model_name:
return
model_path = model_map[model_name]
checkpoint = torch.load(model_path)
self.finetuner = FineTunedModel.from_checkpoint(self.diffuser, checkpoint)
torch.cuda.empty_cache()
def layout(self):
with gr.Row():
with gr.Tab("Test") as inference_column:
with gr.Row():
self.explain_infr = gr.Markdown(interactive=False,
value='This is a demo of [Erasing Concepts from Stable Diffusion](https://erasing.baulab.info/). To try out a model where a concept has been erased, select a model and enter any prompt. For example, if you select the model "Van Gogh" you can generate images for the prompt "A portrait in the style of Van Gogh" and compare the erased and unerased models. We have also provided models with "cars" erased, and with "nudity" erased. You can also train and run your own custom model with a concept erased.')
with gr.Row():
with gr.Column(scale=1):
self.prompt_input_infr = gr.Text(
placeholder="Enter prompt...",
label="Prompt",
info="Prompt to generate"
)
with gr.Row():
self.model_dropdown = gr.Dropdown(
label="ESD Model",
choices=['Van Gogh', 'Car'],
value='Van Gogh',
interactive=True
)
self.seed_infr = gr.Number(
label="Seed",
value=42
)
with gr.Column(scale=2):
self.infr_button = gr.Button(
value="Generate",
interactive=True
)
with gr.Row():
self.image_new = gr.Image(
label="ESD",
interactive=False
)
self.image_orig = gr.Image(
label="SD",
interactive=False
)
with gr.Tab("Train") as training_column:
with gr.Row():
self.explain_train= gr.Markdown(interactive=False,
value='In this part you can erase any concept from Stable Diffusion. Enter a prompt for the concept or style you want to erase, and select ESD-x if you want to focus erasure on prompts that mention the concept explicitly, or ESD-u if you want to erase the concept even for prompts that do not mention the concept. With default settings, it takes about 20 minutes to fine-tune the model; then you can try inference above or download the weights. The training code used here is slightly different than the code tested in the original paper. Code and details are at [github link](https://github.com/rohitgandikota/erasing).')
with gr.Row():
with gr.Column(scale=3):
self.prompt_input = gr.Text(
placeholder="Enter prompt...",
label="Prompt to Erase",
info="Prompt corresponding to concept to erase"
)
self.train_method_input = gr.Dropdown(
choices=['ESD-x', 'ESD-u', 'ESD-self'],
value='ESD-x',
label='Train Method',
info='Method of training'
)
self.neg_guidance_input = gr.Number(
value=1,
label="Negative Guidance",
info='Guidance of negative training used to train'
)
self.iterations_input = gr.Number(
value=150,
precision=0,
label="Iterations",
info='iterations used to train'
)
self.lr_input = gr.Number(
value=1e-5,
label="Learning Rate",
info='Learning rate used to train'
)
with gr.Column(scale=1):
self.train_button = gr.Button(
value="Train",
)
self.download = gr.Files()
self.model_dropdown.change(self.switch_model, inputs=[self.model_dropdown])
self.infr_button.click(self.inference, inputs = [
self.prompt_input_infr,
self.seed_infr
],
outputs=[
self.image_new,
self.image_orig
]
)
self.train_button.click(self.disable,
outputs=[self.train_button, self.infr_button]
)
self.train_button.click(self.train, inputs = [
self.prompt_input,
self.train_method_input,
self.neg_guidance_input,
self.iterations_input,
self.lr_input
],
outputs=[self.train_button, self.infr_button, self.download, self.model_dropdown]
)
def train(self, prompt, train_method, neg_guidance, iterations, lr, pbar = gr.Progress(track_tqdm=True)):
if self.training:
return [None, None, None]
else:
self.training = True
del self.finetuner
torch.cuda.empty_cache()
self.diffuser = self.diffuser.train().float()
if train_method == 'ESD-x':
modules = ".*attn2$"
frozen = []
elif train_method == 'ESD-u':
modules = "unet$"
frozen = [".*attn2$", "unet.time_embedding$", "unet.conv_out$"]
elif train_method == 'ESD-self':
modules = ".*attn1$"
frozen = []
finetuner = FineTunedModel(self.diffuser, modules, frozen_modules=frozen)
optimizer = torch.optim.Adam(finetuner.parameters(), lr=lr)
criteria = torch.nn.MSELoss()
pbar = tqdm(range(iterations))
with torch.no_grad():
neutral_text_embeddings = self.diffuser.get_text_embeddings([''],n_imgs=1)
positive_text_embeddings = self.diffuser.get_text_embeddings([prompt],n_imgs=1)
for i in pbar:
with torch.no_grad():
self.diffuser.set_scheduler_timesteps(self.nsteps)
optimizer.zero_grad()
iteration = torch.randint(1, self.nsteps - 1, (1,)).item()
latents = self.diffuser.get_initial_latents(1, 512, 1)
with finetuner:
latents_steps, _ = self.diffuser.diffusion(
latents,
positive_text_embeddings,
start_iteration=0,
end_iteration=iteration,
guidance_scale=3,
show_progress=False
)
self.diffuser.set_scheduler_timesteps(1000)
iteration = int(iteration / self.nsteps * 1000)
positive_latents = self.diffuser.predict_noise(iteration, latents_steps[0], positive_text_embeddings, guidance_scale=1)
neutral_latents = self.diffuser.predict_noise(iteration, latents_steps[0], neutral_text_embeddings, guidance_scale=1)
with finetuner:
negative_latents = self.diffuser.predict_noise(iteration, latents_steps[0], positive_text_embeddings, guidance_scale=1)
positive_latents.requires_grad = False
neutral_latents.requires_grad = False
loss = criteria(negative_latents, neutral_latents - (neg_guidance*(positive_latents - neutral_latents))) #loss = criteria(e_n, e_0) works the best try 5000 epochs
loss.backward()
optimizer.step()
ft_path = f"{prompt.lower().replace(' ', '')}.pt"
torch.save(finetuner.state_dict(), ft_path)
self.finetuner = finetuner.eval().half()
self.diffuser = self.diffuser.eval().half()
torch.cuda.empty_cache()
self.training = False
model_map['Custom'] = ft_path
return [gr.update(interactive=True), gr.update(interactive=True), ft_path, gr.Dropdown.update(choices=list(model_map.keys()), value='Custom')]
def inference(self, prompt, seed, pbar = gr.Progress(track_tqdm=True)):
if self.generating:
return [None, None]
else:
self.generating = True
self.diffuser._seed = seed or 42
images = self.diffuser(
prompt,
n_steps=50,
reseed=True
)
orig_image = images[0][0]
torch.cuda.empty_cache()
with self.finetuner:
images = self.diffuser(
prompt,
n_steps=50,
reseed=True
)
edited_image = images[0][0]
self.generating = False
torch.cuda.empty_cache()
return edited_image, orig_image
demo = Demo()