File size: 8,815 Bytes
640a27b
f71eb42
a24b16a
 
 
81ccbca
5349660
97b401e
e3abd80
97b401e
 
 
e1dc863
 
e3abd80
daebf8f
 
5349660
 
843b14b
 
 
 
88c9af4
f71eb42
c19b710
88c9af4
f0cf9b0
 
a24b16a
f0cf9b0
a24b16a
5349660
 
f0cf9b0
5349660
f0cf9b0
5349660
f0cf9b0
 
 
5349660
 
 
 
 
 
0166058
 
 
 
 
 
 
5349660
 
 
 
0a3fdbd
5349660
 
 
 
 
 
 
 
 
 
0166058
5349660
 
 
0166058
843b14b
5349660
 
 
 
 
 
 
 
 
 
 
 
 
f0cf9b0
843b14b
5349660
 
843b14b
f0cf9b0
 
5349660
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
81ccbca
 
5349660
 
 
 
 
 
 
 
81ccbca
 
5349660
 
 
 
 
 
 
 
 
 
 
 
 
81ccbca
5349660
843b14b
f0cf9b0
75cb83b
88c9af4
81ccbca
c19b710
7c71893
 
c19b710
a24b16a
f0cf9b0
a24b16a
5349660
 
 
 
 
 
843b14b
a24b16a
f71eb42
a24b16a
5349660
a24b16a
81ccbca
a24b16a
81ccbca
a24b16a
81ccbca
a24b16a
81ccbca
a24b16a
81ccbca
a24b16a
81ccbca
a24b16a
81ccbca
a24b16a
75cb83b
c19b710
7c71893
e3abd80
a24b16a
 
81ccbca
c19b710
81ccbca
e066869
81ccbca
 
 
a24b16a
81ccbca
a24b16a
 
843b14b
 
 
 
 
 
 
 
 
f71eb42
 
a24b16a
843b14b
a24b16a
 
 
 
 
843b14b
 
 
c19b710
f71eb42
 
843b14b
 
 
f0cf9b0
843b14b
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
import gradio as gr
import torch
from finetuning import FineTunedModel
from StableDiffuser import StableDiffuser
from tqdm import tqdm
from train import train

model_map = {'Van Gogh' : 'models/vangogh.pt', 
             'Pablo Picasso': 'models/pablopicasso.pt',
             'Car' : 'models/car.pt',
             'Garbage Truck': 'models/garbagetruck.pt',
             'French Horn': 'models/frenchhorn.pt',
             'Kilian Eng' : 'models/kilianeng.pt',
             'Thomas Kinkade' : 'models/thomaskinkade.pt',
             'Tyler Edlin' : 'models/tyleredlin.pt',
             'Kelly McKernan': 'models/kellymckernan.pt',
             'Rembrandt': 'models/rembrandt.pt' }


class Demo:

    def __init__(self) -> None:

        self.training = False

        self.diffuser = StableDiffuser(scheduler='DDIM', seed=42).to('cuda').eval().half()

        with gr.Blocks() as demo:
            self.layout()
            demo.queue(concurrency_count=2).launch()


    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= list(model_map.keys()),
                                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_status = gr.Button(value='', variant='primary', label='Status', interactive=False)

                        self.train_button = gr.Button(
                            value="Train",
                        )

                        self.download = gr.Files()

        self.infr_button.click(self.inference, inputs = [
            self.prompt_input_infr,
            self.seed_infr,
            self.model_dropdown
            ],
            outputs=[
                self.image_new,
                self.image_orig
            ]
        )
        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.train_status, self.download, self.model_dropdown]
        )

    def train(self, prompt, train_method, neg_guidance, iterations, lr, pbar = gr.Progress(track_tqdm=True)):
        # self.diffuser = StableDiffuser(scheduler='DDIM', seed=42).to('cuda').eval().half()
        if self.training:
            return [gr.update(interactive=True, value='Train'), gr.update(value='Someone else is training... Try again soon'), None, gr.update()]
        # clear the diffusers
        # del self.diffuser
        # torch.cuda.empty_cache()
        
        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 = []

        randn = torch.randint(1, 10000000, (1,)).item()

        save_path = f"models/{randn}_{prompt.lower().replace(' ', '')}.pt"

        self.training = True

        train(prompt, modules, frozen, iterations, neg_guidance, lr, save_path)

        self.training = False

        torch.cuda.empty_cache()

        model_map['Custom'] = save_path

        # del self.diffuser
        torch.cuda.empty_cache()
        # self.diffuser = StableDiffuser(scheduler='DDIM', seed=42).to('cuda').eval().half()
        return [gr.update(interactive=True, value='Train'), gr.update(value='Done Training! \n Try your custom model in the "Test" tab'), save_path, gr.Dropdown.update(choices=list(model_map.keys()), value='Custom')]


    def inference(self, prompt, seed, model_name, pbar = gr.Progress(track_tqdm=True)):
        
        self.diffuser._seed = seed or 42

        model_path = model_map[model_name]
        
        checkpoint = torch.load(model_path)

        self.finetuner = FineTunedModel.from_checkpoint(self.diffuser, checkpoint).eval().half()

        torch.cuda.empty_cache()

        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]

        del self.finetuner
        torch.cuda.empty_cache()

        return edited_image, orig_image


demo = Demo()