JadenFK commited on
Commit
5349660
1 Parent(s): 6a74362

Added cusotm models and refactor of layout

Browse files
Files changed (4) hide show
  1. app.py +147 -86
  2. finetuning.py +21 -3
  3. models/car.pt +3 -0
  4. models/vangogh.pt +3 -0
app.py CHANGED
@@ -6,6 +6,13 @@ from finetuning import FineTunedModel
6
  from StableDiffuser import StableDiffuser
7
  from tqdm import tqdm
8
 
 
 
 
 
 
 
 
9
  class Demo:
10
 
11
  def __init__(self) -> None:
@@ -20,62 +27,49 @@ class Demo:
20
 
21
  with gr.Blocks() as demo:
22
  self.layout()
 
 
 
 
 
23
  demo.queue(concurrency_count=2).launch()
24
 
25
  def disable(self):
26
  return [gr.update(interactive=False), gr.update(interactive=False)]
27
 
28
- def layout(self):
29
 
30
- with gr.Row():
 
31
 
32
- self.explain = gr.HTML(interactive=False,
33
- value="<p>This page demonstrates Erasing Concepts in Stable Diffusion (Ganikota, Materzynska, Fiotto-Kaufman and Bau; paper and code linked from https://erasing.baulab.info/). <br> Use it in two steps <br> 1. First, on the left fine-tune your own custom model by naming the concept that you want to erase. For example, you can try erasing all cars from a model by entering the prompt corresponding to the concept to erase as 'car'. This can take awhile. For example, with the default settings, this can take about an hour. <br> 2. Second, on the right once you have your model fine-tuned, you can try running it in inference. <br>If you want to run it yourself, then you can create your own instance. Configuration, code, and details are at https://github.com/xxxx/xxxx/xxx</p>")
 
 
 
 
 
 
 
 
 
34
 
 
 
 
35
  with gr.Row():
36
- with gr.Column(scale=1) as training_column:
37
- self.prompt_input = gr.Text(
38
- placeholder="Enter prompt...",
39
- label="Prompt to Erase",
40
- info="Prompt corresponding to concept to erase"
41
- )
42
- self.train_method_input = gr.Dropdown(
43
- choices=['ESD-x', 'ESD-self'],
44
- value='ESD-x',
45
- label='Train Method',
46
- info='Method of training'
47
- )
48
-
49
- self.neg_guidance_input = gr.Number(
50
- value=1,
51
- label="Negative Guidance",
52
- info='Guidance of negative training used to train'
53
- )
54
-
55
- self.iterations_input = gr.Number(
56
- value=150,
57
- precision=0,
58
- label="Iterations",
59
- info='iterations used to train'
60
- )
61
-
62
- self.lr_input = gr.Number(
63
- value=1e-5,
64
- label="Learning Rate",
65
- info='Learning rate used to train'
66
- )
67
-
68
- self.train_button = gr.Button(
69
- value="Train",
70
- )
71
-
72
- self.download = gr.Files()
73
 
74
- with gr.Column(scale=2) as inference_column:
75
 
76
  with gr.Row():
77
 
78
- with gr.Column(scale=5):
 
 
 
 
 
79
 
80
  self.prompt_input_infr = gr.Text(
81
  placeholder="Enter prompt...",
@@ -83,51 +77,110 @@ class Demo:
83
  info="Prompt to generate"
84
  )
85
 
86
- with gr.Column(scale=1):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
87
 
88
- self.seed_infr = gr.Number(
89
- label="Seed",
90
- value=42
91
  )
92
 
 
 
 
 
 
 
 
 
 
 
 
 
 
93
  with gr.Row():
94
 
95
- self.image_new = gr.Image(
96
- label="New Image",
97
- interactive=False
98
- )
99
- self.image_orig = gr.Image(
100
- label="Orig Image",
101
- interactive=False
102
- )
103
 
104
  with gr.Row():
105
 
106
- self.infr_button = gr.Button(
107
- value="Generate",
108
- interactive=False
109
- )
110
- self.infr_button.click(self.inference, inputs = [
111
- self.prompt_input_infr,
112
- self.seed_infr
113
- ],
114
- outputs=[
115
- self.image_new,
116
- self.image_orig
117
- ]
118
- )
119
- self.train_button.click(self.disable,
120
- outputs=[self.train_button, self.infr_button]
121
- )
122
- self.train_button.click(self.train, inputs = [
123
- self.prompt_input,
124
- self.train_method_input,
125
- self.neg_guidance_input,
126
- self.iterations_input,
127
- self.lr_input
128
- ],
129
- outputs=[self.train_button, self.infr_button, self.download]
130
- )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
131
 
132
  def train(self, prompt, train_method, neg_guidance, iterations, lr, pbar = gr.Progress(track_tqdm=True)):
133
 
@@ -145,12 +198,19 @@ class Demo:
145
  if train_method == 'ESD-x':
146
 
147
  modules = ".*attn2$"
 
 
 
 
 
 
148
 
149
  elif train_method == 'ESD-self':
150
 
151
  modules = ".*attn1$"
 
152
 
153
- finetuner = FineTunedModel(self.diffuser, modules)
154
 
155
  optimizer = torch.optim.Adam(finetuner.parameters(), lr=lr)
156
  criteria = torch.nn.MSELoss()
@@ -202,7 +262,7 @@ class Demo:
202
  loss.backward()
203
  optimizer.step()
204
 
205
- torch.save(finetuner.state_dict(), 'ft.ckpt')
206
 
207
  self.finetuner = finetuner.eval().half()
208
 
@@ -210,19 +270,20 @@ class Demo:
210
 
211
  torch.cuda.empty_cache()
212
 
213
- self.training = False
214
 
215
- return [gr.update(interactive=True), gr.update(interactive=True), 'ft.ckpt']
216
 
 
217
 
218
- def inference(self, prompt, seed, pbar = gr.Progress(track_tqdm=True)):
219
 
 
220
  if self.generating:
221
  return [None, None]
222
  else:
223
  self.generating = True
224
 
225
- self.diffuser._seed = seed
226
 
227
  images = self.diffuser(
228
  prompt,
 
6
  from StableDiffuser import StableDiffuser
7
  from tqdm import tqdm
8
 
9
+
10
+ model_map = {
11
+ 'Car' : 'models/car.pt',
12
+ 'Van Gogh' : 'models/vangogh.pt',
13
+ }
14
+
15
+
16
  class Demo:
17
 
18
  def __init__(self) -> None:
 
27
 
28
  with gr.Blocks() as demo:
29
  self.layout()
30
+ self.switch_model(self.model_dropdown.value)
31
+
32
+ self.finetuner = self.finetuner.eval().half()
33
+ self.diffuser = self.diffuser.eval().half()
34
+
35
  demo.queue(concurrency_count=2).launch()
36
 
37
  def disable(self):
38
  return [gr.update(interactive=False), gr.update(interactive=False)]
39
 
40
+ def switch_model(self, model_name):
41
 
42
+ if not model_name:
43
+ return
44
 
45
+ model_path = model_map[model_name]
46
+
47
+ checkpoint = torch.load(model_path)
48
+
49
+ del self.finetuner
50
+
51
+ torch.cuda.empty_cache()
52
+
53
+ self.finetuner = FineTunedModel.from_checkpoint(self.diffuser, checkpoint)
54
+
55
+
56
 
57
+ def layout(self):
58
+
59
+
60
  with gr.Row():
61
+
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
62
 
63
+ with gr.Tab("Test") as inference_column:
64
 
65
  with gr.Row():
66
 
67
+ self.explain_infr = gr.Markdown(interactive=False,
68
+ 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.')
69
+
70
+ with gr.Row():
71
+
72
+ with gr.Column(scale=1):
73
 
74
  self.prompt_input_infr = gr.Text(
75
  placeholder="Enter prompt...",
 
77
  info="Prompt to generate"
78
  )
79
 
80
+ with gr.Row():
81
+
82
+ self.model_dropdown = gr.Dropdown(
83
+ label="ESD Model",
84
+ choices=['Van Gogh', 'Car'],
85
+ value='Van Gogh',
86
+ interactive=True
87
+ )
88
+
89
+ self.seed_infr = gr.Number(
90
+ label="Seed",
91
+ value=42
92
+ )
93
+
94
+ with gr.Column(scale=2):
95
 
96
+ self.infr_button = gr.Button(
97
+ value="Generate",
98
+ interactive=True
99
  )
100
 
101
+ with gr.Row():
102
+
103
+ self.image_new = gr.Image(
104
+ label="ESD",
105
+ interactive=False
106
+ )
107
+ self.image_orig = gr.Image(
108
+ label="SD",
109
+ interactive=False
110
+ )
111
+
112
+ with gr.Tab("Train") as training_column:
113
+
114
  with gr.Row():
115
 
116
+ self.explain_train= gr.Markdown(interactive=False,
117
+ 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).')
 
 
 
 
 
 
118
 
119
  with gr.Row():
120
 
121
+ with gr.Column(scale=3):
122
+
123
+ self.prompt_input = gr.Text(
124
+ placeholder="Enter prompt...",
125
+ label="Prompt to Erase",
126
+ info="Prompt corresponding to concept to erase"
127
+ )
128
+ self.train_method_input = gr.Dropdown(
129
+ choices=['ESD-x', 'ESD-u', 'ESD-self'],
130
+ value='ESD-x',
131
+ label='Train Method',
132
+ info='Method of training'
133
+ )
134
+
135
+ self.neg_guidance_input = gr.Number(
136
+ value=1,
137
+ label="Negative Guidance",
138
+ info='Guidance of negative training used to train'
139
+ )
140
+
141
+ self.iterations_input = gr.Number(
142
+ value=150,
143
+ precision=0,
144
+ label="Iterations",
145
+ info='iterations used to train'
146
+ )
147
+
148
+ self.lr_input = gr.Number(
149
+ value=1e-5,
150
+ label="Learning Rate",
151
+ info='Learning rate used to train'
152
+ )
153
+
154
+ with gr.Column(scale=1):
155
+
156
+ self.train_button = gr.Button(
157
+ value="Train",
158
+ )
159
+
160
+ self.download = gr.Files()
161
+
162
+ self.model_dropdown.change(self.switch_model, inputs=[self.model_dropdown])
163
+ self.infr_button.click(self.inference, inputs = [
164
+ self.prompt_input_infr,
165
+ self.seed_infr
166
+ ],
167
+ outputs=[
168
+ self.image_new,
169
+ self.image_orig
170
+ ]
171
+ )
172
+ self.train_button.click(self.disable,
173
+ outputs=[self.train_button, self.infr_button]
174
+ )
175
+ self.train_button.click(self.train, inputs = [
176
+ self.prompt_input,
177
+ self.train_method_input,
178
+ self.neg_guidance_input,
179
+ self.iterations_input,
180
+ self.lr_input
181
+ ],
182
+ outputs=[self.train_button, self.infr_button, self.download, self.model_dropdown]
183
+ )
184
 
185
  def train(self, prompt, train_method, neg_guidance, iterations, lr, pbar = gr.Progress(track_tqdm=True)):
186
 
 
198
  if train_method == 'ESD-x':
199
 
200
  modules = ".*attn2$"
201
+ frozen = []
202
+
203
+ elif train_method == 'ESD-u':
204
+
205
+ modules = "unet$"
206
+ frozen = [".*attn2$", "unet.time_embedding$", "unet.conv_out$"]
207
 
208
  elif train_method == 'ESD-self':
209
 
210
  modules = ".*attn1$"
211
+ frozen = []
212
 
213
+ finetuner = FineTunedModel(self.diffuser, modules, frozen_modules=frozen)
214
 
215
  optimizer = torch.optim.Adam(finetuner.parameters(), lr=lr)
216
  criteria = torch.nn.MSELoss()
 
262
  loss.backward()
263
  optimizer.step()
264
 
265
+ torch.save(finetuner.state_dict(), 'ft.pt')
266
 
267
  self.finetuner = finetuner.eval().half()
268
 
 
270
 
271
  torch.cuda.empty_cache()
272
 
273
+ self.training = False
274
 
275
+ model_map['Custom'] = 'ft.pt'
276
 
277
+ return [gr.update(interactive=True), gr.update(interactive=True), 'ft.pt', gr.Dropdown.update(choices=list(model_map.keys()), value='Custom')]
278
 
 
279
 
280
+ def inference(self, prompt, seed, pbar = gr.Progress(track_tqdm=True)):
281
  if self.generating:
282
  return [None, None]
283
  else:
284
  self.generating = True
285
 
286
+ self.diffuser._seed = seed or 42
287
 
288
  images = self.diffuser(
289
  prompt,
finetuning.py CHANGED
@@ -38,18 +38,36 @@ class FineTunedModel(torch.nn.Module):
38
 
39
  print(f"=> Finetuning {module_name}")
40
 
41
- for module_name, module in ft_module.named_modules():
 
 
 
42
  for freeze_module_name in frozen_modules:
43
 
44
- match = re.search(freeze_module_name, module_name)
45
 
46
  if match:
47
- print(f"=> Freezing {module_name}")
48
  util.freeze(module)
49
 
50
  self.ft_modules_list = torch.nn.ModuleList(self.ft_modules.values())
51
  self.orig_modules_list = torch.nn.ModuleList(self.orig_modules.values())
52
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
53
  def __enter__(self):
54
 
55
  for key, ft_module in self.ft_modules.items():
 
38
 
39
  print(f"=> Finetuning {module_name}")
40
 
41
+ for ft_module_name, module in ft_module.named_modules():
42
+
43
+ ft_module_name = f"{module_name}.{ft_module_name}"
44
+
45
  for freeze_module_name in frozen_modules:
46
 
47
+ match = re.search(freeze_module_name, ft_module_name)
48
 
49
  if match:
50
+ print(f"=> Freezing {ft_module_name}")
51
  util.freeze(module)
52
 
53
  self.ft_modules_list = torch.nn.ModuleList(self.ft_modules.values())
54
  self.orig_modules_list = torch.nn.ModuleList(self.orig_modules.values())
55
 
56
+
57
+ @classmethod
58
+ def from_checkpoint(cls, model, checkpoint, frozen_modules=[]):
59
+
60
+ if isinstance(checkpoint, str):
61
+ checkpoint = torch.load(checkpoint)
62
+
63
+ modules = [f"{key}$" for key in list(checkpoint.keys())]
64
+
65
+ ftm = FineTunedModel(model, modules, frozen_modules=frozen_modules)
66
+ ftm.load_state_dict(checkpoint)
67
+
68
+ return ftm
69
+
70
+
71
  def __enter__(self):
72
 
73
  for key, ft_module in self.ft_modules.items():
models/car.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:1a486d8417dc06dcdadfafe738ca32fb9d48f3a1a144d96cb2781e9e5f0c6f98
3
+ size 3438317621
models/vangogh.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:75cdb4313898f593b16f23dbceca498f3f16a749802450ab358a12c204404c27
3
+ size 175873179