import gradio as gr import torch import os from diffusers.utils import is_xformers_available from finetuning import FineTunedModel from StableDiffuser import StableDiffuser from memory_efficiency import MemoryEfficiencyWrapper from train import train import os def populate_model_map(): model_map = {} for model_file in os.listdir('models'): path = 'models/' + model_file if any([existing_path == path for existing_path in model_map.values()]): continue model_map[model_file] = path return model_map model_map = populate_model_map() ORIGINAL_SPACE_ID = 'baulab/Erasing-Concepts-In-Diffusion' SPACE_ID = os.getenv('SPACE_ID') SHARED_UI_WARNING = f'''## Attention - Training using the ESD-u method does not work in this shared UI. You can either duplicate and use it with a gpu with at least 40GB, or clone this repository to run on your own machine.
Duplicate Space
''' class Demo: def __init__(self) -> None: self.training = False self.generating = False with gr.Blocks() as demo: self.layout() demo.queue(concurrency_count=5).launch() def layout(self): with gr.Row(): if SPACE_ID == ORIGINAL_SPACE_ID: self.warning = gr.Markdown(SHARED_UI_WARNING) 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 several other pre-fine-tuned models with artistic styles and objects erased (Check out the "ESD Model" drop-down). You can also train and run your own custom models. Check out the "train" section for custom erasure of concepts.') with gr.Row(): with gr.Column(scale=1): self.prompt_input_infr = gr.Text( placeholder="Enter prompt...", label="Prompt", info="Prompt to generate" ) self.negative_prompt_input_infr = gr.Text( label="Negative prompt" ) with gr.Row(): self.model_dropdown = gr.Dropdown( label="ESD Model", choices= list(model_map.keys()), value='Van Gogh', interactive=True ) self.model_reload_button = gr.Button( value="🔄", interactive=True ) self.seed_infr = gr.Number( label="Seed", value=42 ) self.img_width_infr = gr.Slider( label="Image width", minimum=256, maximum=1024, value=512, step=64 ) self.img_height_infr = gr.Slider( label="Image height", minimum=256, maximum=1024, value=512, step=64 ) self.base_repo_id_or_path_input_infr = gr.Text( label="Base model", value="CompVis/stable-diffusion-v1-4", info="Path or huggingface repo id of the base model that this edit was done against" ) 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. [NOTE: ESD-u is currently unavailable in this space. But you can duplicate the space and run it on GPU with VRAM >40GB for enabling ESD-u]. With default settings, it takes about 15 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.train_model_input = gr.Text( label="Model to Edit", value="CompVis/stable-diffusion-v1-4", info="Path or huggingface repo id of the model to edit" ) self.train_img_size_input = gr.Slider( value=512, step=64, minimum=256, maximum=1024, label="Image Size", info="Image size for training, should match the model's native image size" ) self.prompt_input = gr.Text( placeholder="Enter prompt...", label="Prompt to Erase", info="Prompt corresponding to concept to erase" ) choices = ['ESD-x', 'ESD-self', 'ESD-u'] #if torch.cuda.get_device_properties(0).total_memory * 1e-9 >= 40 or is_xformers_available(): # choices.append('ESD-u') self.train_method_input = gr.Dropdown( choices=choices, 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' ) self.train_seed_input = gr.Number( value=-1, label="Seed", info="Set to a fixed number for reproducible training results, or use -1 to pick randomly" ) self.train_save_every_input = gr.Number( value=-1, label="Save every N steps", info="If >0, save the model throughout training at the given step interval." ) with gr.Column(): self.train_memory_options = gr.Markdown(interactive=False, value='Performance and VRAM usage optimizations, may not work on all devices:') with gr.Row(): self.train_use_adamw8bit_input = gr.Checkbox(label="8bit AdamW", value=True) self.train_use_xformers_input = gr.Checkbox(label="xformers", value=True) self.train_use_amp_input = gr.Checkbox(label="AMP", value=True) self.train_use_gradient_checkpointing_input = gr.Checkbox( label="Gradient checkpointing", value=False) with gr.Column(scale=1): self.train_status = gr.Button(value='', variant='primary', label='Status', interactive=False) self.train_button = gr.Button( value="Train", ) self.train_cancel_button = gr.Button( value="Cancel training" ) self.download = gr.Files() with gr.Tab("Export") as export_column: with gr.Row(): self.explain_train= gr.Markdown(interactive=False, value='Export a model to Diffusers format. Please enter the base model and select the editing weights.') with gr.Row(): with gr.Column(scale=3): self.base_repo_id_or_path_input_export = gr.Text( label="Base model", value="CompVis/stable-diffusion-v1-4", info="Path or huggingface repo id of the base model that this edit was done against" ) self.model_dropdown_export = gr.Dropdown( label="ESD Model", choices=list(model_map.keys()), value='Van Gogh', interactive=True ) self.save_path_input_export = gr.Text( label="Output path", placeholder="./exported_models/model_name", info="Path to export the model to. A diffusers folder will be written to this location." ) self.save_half_export = gr.Checkbox( label="Save as fp16" ) with gr.Column(scale=1): self.export_status = gr.Button( value='', variant='primary', label='Status', interactive=False) self.export_button = gr.Button( value="Export") self.infr_button.click(self.inference, inputs = [ self.prompt_input_infr, self.negative_prompt_input_infr, self.seed_infr, self.img_width_infr, self.img_height_infr, self.model_dropdown, self.base_repo_id_or_path_input_infr ], outputs=[ self.image_new, self.image_orig ] ) self.model_reload_button.click(self.reload_models, inputs=[self.model_dropdown], outputs=[self.model_dropdown]) train_event = self.train_button.click(self.train, inputs = [ self.train_model_input, self.train_img_size_input, self.prompt_input, self.train_method_input, self.neg_guidance_input, self.iterations_input, self.lr_input, self.train_use_adamw8bit_input, self.train_use_xformers_input, self.train_use_amp_input, self.train_use_gradient_checkpointing_input, self.train_seed_input, self.train_save_every_input, ], outputs=[self.train_button, self.train_status, self.download, self.model_dropdown] ) self.train_cancel_button.click(lambda x: print("cancel pressed"), cancels=[train_event]) self.export_button.click(self.export, inputs = [ self.model_dropdown_export, self.base_repo_id_or_path_input_export, self.save_path_input_export, self.save_half_export ], outputs=[self.export_status] ) def reload_models(self, model_dropdown): current_model_name = model_dropdown global model_map model_map = populate_model_map() return [gr.Dropdown.update(choices=list(model_map.keys()), value=current_model_name)] def train(self, repo_id_or_path, img_size, prompt, train_method, neg_guidance, iterations, lr, use_adamw8bit=True, use_xformers=False, use_amp=False, use_gradient_checkpointing=False, seed=-1, save_every=-1, pbar = gr.Progress(track_tqdm=True)): if self.training: return [gr.update(interactive=True, value='Train'), gr.update(value='Someone else is training... Try again soon'), None, gr.update()] print(f"Training {repo_id_or_path} at {img_size} to remove '{prompt}'.") print(f" {train_method}, negative guidance {neg_guidance}, lr {lr}, {iterations} iterations.") print(f" {'✅' if use_gradient_checkpointing else '❌'} gradient checkpointing") print(f" {'✅' if use_amp else '❌'} AMP") print(f" {'✅' if use_xformers else '❌'} xformers") print(f" {'✅' if use_adamw8bit else '❌'} 8-bit AdamW") 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 = [] # build a save path, ensure it isn't in use while True: randn = torch.randint(1, 10000000, (1,)).item() options = f'{"a8" if use_adamw8bit else ""}{"AM" if use_amp else ""}{"xf" if use_xformers else ""}{"gc" if use_gradient_checkpointing else ""}' save_path = f"models/{prompt.lower().replace(' ', '')}_{train_method}_ng{neg_guidance}_lr{lr}_iter{iterations}_seed{seed}_{options}__{randn}.pt" if not os.path.exists(save_path): break # repeat until a not-in-use path is found try: self.training = True self.train_cancel_button.update(interactive=True) train(repo_id_or_path, img_size, prompt, modules, frozen, iterations, neg_guidance, lr, save_path, use_adamw8bit, use_xformers, use_amp, use_gradient_checkpointing, seed=int(seed), save_every=int(save_every)) finally: self.training = False self.train_cancel_button.update(interactive=False) torch.cuda.empty_cache() new_model_name = f'{os.path.basename(save_path)}' model_map[new_model_name] = save_path return [gr.update(interactive=True, value='Train'), gr.update(value=f'Done Training! Try your model ({new_model_name}) in the "Test" tab'), save_path, gr.Dropdown.update(choices=list(model_map.keys()), value=new_model_name)] def export(self, model_name, base_repo_id_or_path, save_path, save_half): model_path = model_map[model_name] checkpoint = torch.load(model_path) diffuser = StableDiffuser(scheduler='DDIM', keep_pipeline=True, repo_id_or_path=base_repo_id_or_path ).eval() finetuner = FineTunedModel.from_checkpoint(diffuser, checkpoint).eval() with finetuner: if save_half: diffuser = diffuser.half() diffuser.pipeline.to('cpu', torch_dtype=torch.float16) diffuser.pipeline.save_pretrained(save_path) return [gr.update(value=f'Done! Your model is at {save_path}.')] def inference(self, prompt, negative_prompt, seed, width, height, model_name, base_repo_id_or_path, pbar = gr.Progress(track_tqdm=True)): seed = seed or 42 model_path = model_map[model_name] checkpoint = torch.load(model_path) self.diffuser = StableDiffuser(scheduler='DDIM', repo_id_or_path=base_repo_id_or_path).to('cuda').eval().half() finetuner = FineTunedModel.from_checkpoint(self.diffuser, checkpoint).eval().half() generator = torch.manual_seed(seed) torch.cuda.empty_cache() images = self.diffuser( prompt, negative_prompt, width=width, height=height, n_steps=50, generator=generator ) orig_image = images[0][0] torch.cuda.empty_cache() with finetuner: images = self.diffuser( prompt, negative_prompt, width=width, height=height, n_steps=50, generator=generator ) edited_image = images[0][0] del finetuner torch.cuda.empty_cache() return edited_image, orig_image demo = Demo()