amildravid4292 commited on
Commit
76ee786
·
verified ·
1 Parent(s): c2731b3

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +372 -370
app.py CHANGED
@@ -19,341 +19,346 @@ from lora_w2w import LoRAw2w
19
  from huggingface_hub import snapshot_download
20
  import spaces
21
 
 
22
 
23
- def main():
24
-
25
- models_path = snapshot_download(repo_id="Snapchat/w2w")
26
-
27
- device = "cuda"
28
- mean = torch.load(f"{models_path}/files/mean.pt", map_location=torch.device('cpu')).bfloat16().to(device)
29
- std = torch.load(f"{models_path}/files/std.pt", map_location=torch.device('cpu')).bfloat16().to(device)
30
- v = torch.load(f"{models_path}/files/V.pt", map_location=torch.device('cpu')).bfloat16().to(device)
31
- proj = torch.load(f"{models_path}/files/proj_1000pc.pt", map_location=torch.device('cpu')).bfloat16().to(device)
32
- df = torch.load(f"{models_path}/files/identity_df.pt")
33
- weight_dimensions = torch.load(f"{models_path}/files/weight_dimensions.pt")
34
- pinverse = torch.load(f"{models_path}/files/pinverse_1000pc.pt", map_location=torch.device('cpu')).bfloat16().to(device)
35
-
36
-
37
- unet, vae, text_encoder, tokenizer, noise_scheduler = load_models(device)
38
- network = None
39
-
40
- young = get_direction(df, "Young", pinverse, 1000, device)
41
- young = debias(young, "Male", df, pinverse, device)
42
- young = debias(young, "Pointy_Nose", df, pinverse, device)
43
- young = debias(young, "Wavy_Hair", df, pinverse, device)
44
- young = debias(young, "Chubby", df, pinverse, device)
45
- young = debias(young, "No_Beard", df, pinverse, device)
46
- young = debias(young, "Mustache", df, pinverse, device)
47
-
48
- pointy = get_direction(df, "Pointy_Nose", pinverse, 1000, device)
49
- pointy = debias(pointy, "Young", df, pinverse, device)
50
- pointy = debias(pointy, "Male", df, pinverse, device)
51
- pointy = debias(pointy, "Wavy_Hair", df, pinverse, device)
52
- pointy = debias(pointy, "Chubby", df, pinverse, device)
53
- pointy = debias(pointy, "Heavy_Makeup", df, pinverse, device)
54
-
55
- wavy = get_direction(df, "Wavy_Hair", pinverse, 1000, device)
56
- wavy = debias(wavy, "Young", df, pinverse, device)
57
- wavy = debias(wavy, "Male", df, pinverse, device)
58
- wavy = debias(wavy, "Pointy_Nose", df, pinverse, device)
59
- wavy = debias(wavy, "Chubby", df, pinverse, device)
60
- wavy = debias(wavy, "Heavy_Makeup", df, pinverse, device)
61
-
62
-
63
- thick = get_direction(df, "Bushy_Eyebrows", pinverse, 1000, device)
64
- thick = debias(thick, "Male", df, pinverse, device)
65
- thick = debias(thick, "Young", df, pinverse, device)
66
- thick = debias(thick, "Pointy_Nose", df, pinverse, device)
67
- thick = debias(thick, "Wavy_Hair", df, pinverse, device)
68
- thick = debias(thick, "Mustache", df, pinverse, device)
69
- thick = debias(thick, "No_Beard", df, pinverse, device)
70
- thick = debias(thick, "Sideburns", df, pinverse, device)
71
- thick = debias(thick, "Big_Nose", df, pinverse, device)
72
- thick = debias(thick, "Big_Lips", df, pinverse, device)
73
- thick = debias(thick, "Black_Hair", df, pinverse, device)
74
- thick = debias(thick, "Brown_Hair", df, pinverse, device)
75
- thick = debias(thick, "Pale_Skin", df, pinverse, device)
76
- thick = debias(thick, "Heavy_Makeup", df, pinverse, device)
77
 
78
- def sample_model():
79
- nonlocal network
80
- mean.to(device)
81
- std.to(device)
82
- v.to(device)
83
- proj.to(device)
84
- unet, _, _, _, _ = load_models(device)
85
- network = sample_weights(unet, proj, mean, std, v[:, :1000], device, factor = 1.00)
86
- return network
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
87
 
88
- @torch.no_grad()
89
- @spaces.GPU
90
- def inference( prompt, negative_prompt, guidance_scale, ddim_steps, seed):
91
- nonlocal network
92
- generator = torch.Generator(device=device).manual_seed(seed)
93
- latents = torch.randn(
94
- (1, unet.in_channels, 512 // 8, 512 // 8),
95
- generator = generator,
96
- device = device
97
- ).bfloat16()
98
-
99
-
100
- text_input = tokenizer(prompt, padding="max_length", max_length=tokenizer.model_max_length, truncation=True, return_tensors="pt")
101
-
102
- text_embeddings = text_encoder(text_input.input_ids.to(device))[0]
103
-
104
- max_length = text_input.input_ids.shape[-1]
105
- uncond_input = tokenizer(
106
- [negative_prompt], padding="max_length", max_length=max_length, return_tensors="pt"
107
- )
108
- uncond_embeddings = text_encoder(uncond_input.input_ids.to(device))[0]
109
- text_embeddings = torch.cat([uncond_embeddings, text_embeddings])
110
- noise_scheduler.set_timesteps(ddim_steps)
111
- latents = latents * noise_scheduler.init_noise_sigma
112
-
113
- for i,t in enumerate(tqdm.tqdm(noise_scheduler.timesteps)):
114
- latent_model_input = torch.cat([latents] * 2)
115
- latent_model_input = noise_scheduler.scale_model_input(latent_model_input, timestep=t)
116
- with network:
117
- noise_pred = unet(latent_model_input, t, encoder_hidden_states=text_embeddings, timestep_cond= None).sample
118
- #guidance
119
- noise_pred_uncond, noise_pred_text = noise_pred.chunk(2)
120
- noise_pred = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond)
121
- latents = noise_scheduler.step(noise_pred, t, latents).prev_sample
122
-
123
- latents = 1 / 0.18215 * latents
124
- image = vae.decode(latents).sample
125
- image = (image / 2 + 0.5).clamp(0, 1)
126
- image = image.detach().cpu().float().permute(0, 2, 3, 1).numpy()[0]
127
-
128
- image = Image.fromarray((image * 255).round().astype("uint8"))
129
-
130
- return image
131
 
132
 
133
- @torch.no_grad()
134
- @spaces.GPU
135
- def edit_inference(prompt, negative_prompt, guidance_scale, ddim_steps, seed, start_noise, a1, a2, a3, a4):
136
- nonlocal network
137
- original_weights = network.proj.clone()
138
-
139
- #pad to same number of PCs
140
- pcs_original = original_weights.shape[1]
141
- pcs_edits = young.shape[1]
142
- padding = torch.zeros((1,pcs_original-pcs_edits)).to(device)
143
- young_pad = torch.cat((young, padding), 1)
144
- pointy_pad = torch.cat((pointy, padding), 1)
145
- wavy_pad = torch.cat((wavy, padding), 1)
146
- thick_pad = torch.cat((thick, padding), 1)
147
 
148
-
149
- edited_weights = original_weights+a1*1e6*young_pad+a2*1e6*pointy_pad+a3*1e6*wavy_pad+a4*2e6*thick_pad
150
-
151
- generator = torch.Generator(device=device).manual_seed(seed)
152
- latents = torch.randn(
153
- (1, unet.in_channels, 512 // 8, 512 // 8),
154
- generator = generator,
155
- device = device
156
- ).bfloat16()
157
-
158
-
159
- text_input = tokenizer(prompt, padding="max_length", max_length=tokenizer.model_max_length, truncation=True, return_tensors="pt")
160
-
161
- text_embeddings = text_encoder(text_input.input_ids.to(device))[0]
162
-
163
- max_length = text_input.input_ids.shape[-1]
164
- uncond_input = tokenizer(
165
- [negative_prompt], padding="max_length", max_length=max_length, return_tensors="pt"
166
- )
167
- uncond_embeddings = text_encoder(uncond_input.input_ids.to(device))[0]
168
- text_embeddings = torch.cat([uncond_embeddings, text_embeddings])
169
- noise_scheduler.set_timesteps(ddim_steps)
170
- latents = latents * noise_scheduler.init_noise_sigma
171
 
172
-
173
-
174
- for i,t in enumerate(tqdm.tqdm(noise_scheduler.timesteps)):
175
- latent_model_input = torch.cat([latents] * 2)
176
- latent_model_input = noise_scheduler.scale_model_input(latent_model_input, timestep=t)
 
 
 
 
 
 
 
177
 
178
- if t>start_noise:
179
- pass
180
- elif t<=start_noise:
181
- network.proj = torch.nn.Parameter(edited_weights)
182
- network.reset()
183
-
184
-
185
- with network:
186
- noise_pred = unet(latent_model_input, t, encoder_hidden_states=text_embeddings, timestep_cond= None).sample
187
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
188
 
189
- #guidance
190
- noise_pred_uncond, noise_pred_text = noise_pred.chunk(2)
191
- noise_pred = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond)
192
- latents = noise_scheduler.step(noise_pred, t, latents).prev_sample
193
-
194
- latents = 1 / 0.18215 * latents
195
- image = vae.decode(latents).sample
196
- image = (image / 2 + 0.5).clamp(0, 1)
197
-
198
- image = image.detach().cpu().float().permute(0, 2, 3, 1).numpy()[0]
199
-
200
- image = Image.fromarray((image * 255).round().astype("uint8"))
201
-
202
- #reset weights back to original
203
- network.proj = torch.nn.Parameter(original_weights)
204
- network.reset()
205
-
206
- return image
207
 
208
- @spaces.GPU
209
- def sample_then_run():
210
- nonlocal network
211
- network = sample_model()
212
- prompt = "sks person"
213
- negative_prompt = "low quality, blurry, unfinished, nudity, weapon"
214
- seed = 5
215
- cfg = 3.0
216
- steps = 25
217
- image = inference( prompt, negative_prompt, cfg, steps, seed)
218
- torch.save(network.proj, "model.pt" )
219
- return image, "model.pt"
220
 
221
 
222
 
223
- class CustomImageDataset(Dataset):
224
- def __init__(self, images, transform=None):
225
- self.images = images
226
- self.transform = transform
227
-
228
- def __len__(self):
229
- return len(self.images)
230
-
231
- def __getitem__(self, idx):
232
- image = self.images[idx]
233
- if self.transform:
234
- image = self.transform(image)
235
- return image
236
-
237
- @spaces.GPU
238
- def invert(image, mask, pcs=10000, epochs=400, weight_decay = 1e-10, lr=1e-1):
239
-
240
- del unet
241
- del network
242
- unet, _, _, _, _ = load_models(device)
243
-
244
- proj = torch.zeros(1,pcs).bfloat16().to(device)
245
- network = LoRAw2w( proj, mean, std, v[:, :pcs],
246
- unet,
247
- rank=1,
248
- multiplier=1.0,
249
- alpha=27.0,
250
- train_method="xattn-strict"
251
- ).to(device, torch.bfloat16)
252
-
253
- ### load mask
254
- mask = transforms.Resize((64,64), interpolation=transforms.InterpolationMode.BILINEAR)(mask)
255
- mask = torchvision.transforms.functional.pil_to_tensor(mask).unsqueeze(0).to(device).bfloat16()[:,0,:,:].unsqueeze(1)
256
- ### check if an actual mask was draw, otherwise mask is just all ones
257
- if torch.sum(mask) == 0:
258
- mask = torch.ones((1,1,64,64)).to(device).bfloat16()
259
 
260
- ### single image dataset
261
- image_transforms = transforms.Compose([transforms.Resize(512, interpolation=transforms.InterpolationMode.BILINEAR),
262
- transforms.RandomCrop(512),
263
- transforms.ToTensor(),
264
- transforms.Normalize([0.5], [0.5])])
265
-
266
-
267
- train_dataset = CustomImageDataset(image, transform=image_transforms)
268
- train_dataloader = torch.utils.data.DataLoader(train_dataset, batch_size=1, shuffle=True)
269
-
270
- ### optimizer
271
- optim = torch.optim.Adam(network.parameters(), lr=lr, weight_decay=weight_decay)
272
-
273
- ### training loop
274
- unet.train()
275
- for epoch in tqdm.tqdm(range(epochs)):
276
- for batch in train_dataloader:
277
- ### prepare inputs
278
- batch = batch.to(device).bfloat16()
279
- latents = vae.encode(batch).latent_dist.sample()
280
- latents = latents*0.18215
281
- noise = torch.randn_like(latents)
282
- bsz = latents.shape[0]
283
-
284
- timesteps = torch.randint(0, noise_scheduler.config.num_train_timesteps, (bsz,), device=latents.device)
285
- timesteps = timesteps.long()
286
- noisy_latents = noise_scheduler.add_noise(latents, noise, timesteps)
287
- text_input = tokenizer("sks person", padding="max_length", max_length=tokenizer.model_max_length, truncation=True, return_tensors="pt")
288
- text_embeddings = text_encoder(text_input.input_ids.to(device))[0]
289
-
290
- ### loss + sgd step
291
- with network:
292
- model_pred = unet(noisy_latents, timesteps, text_embeddings).sample
293
- loss = torch.nn.functional.mse_loss(mask*model_pred.float(), mask*noise.float(), reduction="mean")
294
- optim.zero_grad()
295
- loss.backward()
296
- optim.step()
297
-
298
- ### return optimized network
299
- return network
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
300
 
301
 
302
- @spaces.GPU
303
- def run_inversion(dict, pcs, epochs, weight_decay,lr):
304
- init_image = dict["image"].convert("RGB").resize((512, 512))
305
- mask = dict["mask"].convert("RGB").resize((512, 512))
306
- network = invert([init_image], mask, pcs, epochs, weight_decay,lr)
307
-
308
-
309
- #sample an image
310
- prompt = "sks person"
311
- negative_prompt = "low quality, blurry, unfinished, nudity"
312
- seed = 5
313
- cfg = 3.0
314
- steps = 25
315
- image = inference( prompt, negative_prompt, cfg, steps, seed)
316
- torch.save(network.proj, "model.pt" )
317
- return image, "model.pt"
318
-
319
-
320
- @spaces.GPU
321
- def file_upload(file):
322
- del unet
323
- del network
324
 
325
- proj = torch.load(file.name).to(device)
326
-
327
- #pad to 10000 Principal components to keep everything consistent
328
- pcs = proj.shape[1]
329
- padding = torch.zeros((1,10000-pcs)).to(device)
330
- proj = torch.cat((proj, padding), 1)
331
-
332
- unet, _, _, _, _ = load_models(device)
 
 
333
 
334
 
335
- network = LoRAw2w( proj, mean, std, v[:, :10000],
336
- unet,
337
- rank=1,
338
- multiplier=1.0,
339
- alpha=27.0,
340
- train_method="xattn-strict"
341
- ).to(device, torch.bfloat16)
342
 
 
 
 
 
 
 
 
 
343
 
344
- prompt = "sks person"
345
- negative_prompt = "low quality, blurry, unfinished, nudity"
346
- seed = 5
347
- cfg = 3.0
348
- steps = 25
349
- image = inference( prompt, negative_prompt, cfg, steps, seed)
350
- return image
 
 
 
 
 
 
 
 
 
 
351
 
352
 
353
 
354
 
355
- intro = """
356
- <div style="display: flex;align-items: center;justify-content: center">
357
  <h1 style="margin-left: 12px;text-align: center;margin-bottom: 7px;display: inline-block"><em>weights2weights</em> Demo</h1>
358
  <h3 style="display: inline-block;margin-left: 10px;margin-top: 6px;font-weight: 500">Interpreting the Weight Space of Customized Diffusion Models</h3>
359
  </div>
@@ -369,103 +374,101 @@ def main():
369
 
370
 
371
 
372
- with gr.Blocks(css="style.css") as demo:
373
-
374
-
375
-
376
- gr.HTML(intro)
377
 
378
- gr.Markdown("""<div style="text-align: justify;"> In this demo, you can get an identity-encoding model by sampling or inverting. To use a model previously downloaded from this demo see \"Uploading a model\" in the Advanced Options. Next, you can generate new images from it, or edit the identity encoded in the model and generate images from the edited model. We provide detailed instructions and tips at the bottom of the page.""")
379
- with gr.Column():
380
- with gr.Row():
381
- with gr.Column():
382
- gr.Markdown("""1) Either sample a new model, or upload an image (optionally draw a mask over the head) and click `invert`.""")
383
- sample = gr.Button("🎲 Sample New Model")
384
- input_image = gr.ImageEditor(elem_id="image_upload", type='pil', label="Reference Identity",
385
  width=512, height=512)
386
 
387
- with gr.Row():
388
- invert_button = gr.Button("⬆️ Invert")
389
 
390
 
391
 
392
- with gr.Column():
393
- gr.Markdown("""2) Generate images of the sampled/inverted identity or edit the identity with the sliders and generate new images with various prompts and seeds.""")
394
- gallery = gr.Image(label="Generated Image",height=512, width=512, interactive=False)
395
- submit = gr.Button("Generate")
396
 
397
 
398
- prompt = gr.Textbox(label="Prompt",
399
  info="Make sure to include 'sks person'" ,
400
  placeholder="sks person",
401
  value="sks person")
402
 
403
- seed = gr.Number(value=5, label="Seed", precision=0, interactive=True)
404
 
405
- # Editing
406
- with gr.Column():
407
- with gr.Row():
408
- a1 = gr.Slider(label="- Young +", value=0, step=0.001, minimum=-1, maximum=1, interactive=True)
409
- a2 = gr.Slider(label="- Pointy Nose +", value=0, step=0.001, minimum=-1, maximum=1, interactive=True)
410
- with gr.Row():
411
- a3 = gr.Slider(label="- Curly Hair +", value=0, step=0.001, minimum=-1, maximum=1, interactive=True)
412
- a4 = gr.Slider(label="- Thick Eyebrows +", value=0, step=0.001, minimum=-1, maximum=1, interactive=True)
413
 
414
 
415
- with gr.Accordion("Advanced Options", open=False):
416
- with gr.Tab("Inversion"):
417
- with gr.Row():
418
- lr = gr.Number(value=1e-1, label="Learning Rate", interactive=True)
419
- pcs = gr.Slider(label="# Principal Components", value=10000, step=1, minimum=1, maximum=10000, interactive=True)
420
- with gr.Row():
421
- epochs = gr.Slider(label="Epochs", value=800, step=1, minimum=1, maximum=2000, interactive=True)
422
- weight_decay = gr.Number(value=1e-10, label="Weight Decay", interactive=True)
423
- with gr.Tab("Sampling"):
424
- with gr.Row():
425
- cfg= gr.Slider(label="CFG", value=3.0, step=0.1, minimum=0, maximum=10, interactive=True)
426
- steps = gr.Slider(label="Inference Steps", value=25, step=1, minimum=0, maximum=100, interactive=True)
427
- with gr.Row():
428
- negative_prompt = gr.Textbox(label="Negative Prompt", placeholder="low quality, blurry, unfinished, nudity, weapon", value="low quality, blurry, unfinished, nudity, weapon")
429
- injection_step = gr.Slider(label="Injection Step", value=800, step=1, minimum=0, maximum=1000, interactive=True)
430
 
431
- with gr.Tab("Uploading a model"):
432
- gr.Markdown("""<div style="text-align: justify;">Upload a model below downloaded from this demo.""")
433
 
434
- file_input = gr.File(label="Upload Model", container=True)
435
 
436
 
437
 
438
 
439
- gr.Markdown("""<div style="text-align: justify;"> After sampling a new model or inverting, you can download the model below.""")
440
 
441
- with gr.Row():
442
- file_output = gr.File(label="Download Sampled/Inverted Model", container=True, interactive=False)
443
 
444
 
445
 
446
 
447
- invert_button.click(fn=run_inversion,
448
  inputs=[input_image, pcs, epochs, weight_decay,lr],
449
  outputs = [input_image, file_output])
450
 
451
 
452
- sample.click(fn=sample_then_run, outputs=[input_image, file_output])
453
 
454
- submit.click(
455
- fn=edit_inference, inputs=[prompt, negative_prompt, cfg, steps, seed, injection_step, a1, a2, a3, a4], outputs=[gallery]
456
  )
457
- file_input.change(fn=file_upload, inputs=file_input, outputs = gallery)
458
 
459
 
460
 
461
- help_text1 = """
462
  <b>Instructions</b>:
463
  1. To get results faster without waiting in queue, you can duplicate into a private space with an A100 GPU.
464
  2. To begin, you will have to get an identity-encoding model. You can either sample one from *weights2weights* space by clicking `Sample New Model` or by uploading an image and clicking `invert` to invert the identity into a model. You can optionally draw over the head to define a mask in the image for better results. Sampling a model takes around 10 seconds and inversion takes around 2 minutes. After this is done, you can optionally download this model for later use. A model can be uploaded in the \"Uploading a model\" tab in the `Advanced Options`.
465
  3. After getting a model, an image of the identity will be displayed on the right. You can sample from the model by changing seeds as well as prompts and then clicking `Generate`. Make sure to include \"sks person\" in your prompt to keep the same identity.
466
  4. The identity in the model can be edited by changing the sliders for various attributes. After clicking `Generate`, you can see how the identity has changed and the effects are maintained across different seeds and prompts.
467
  """
468
- help_text2 = """<b>Tips</b>:
469
  1. Editing and Identity Generation
470
  * If you are interested in preserving more of the image during identity-editing (i.e., where the same seed and prompt results in the same image with only the identity changed), you can play with the "Injection Step" parameter in the \"Sampling\" tab in the `Advanced Options`. During the first *n* timesteps, the original model's weights will be used, and then the edited weights will be set during the remaining steps. Values closer to 1000 will set the edited weights early, having a more pronounced effect, which may disrupt some semantics and structure of the generated image. Lower values will set the edited weights later, better preserving image context. We notice that around 600-800 tends to produce the best results. Larger values in the range (700-1000) are helpful for more global attribute changes, while smaller (400-700) can be used for more finegrained edits. Although it is not always needed.
471
  * You can play around with negative prompts, number of inference steps, and CFG in the \"Sampling\" tab in the `Advanced Options` to affect the ultimate image quality.
@@ -477,11 +480,10 @@ def main():
477
  * Note that if you change the number of PCs, you will probably need to change the learning rate. For less PCs, higher learning rates are typically required."""
478
 
479
 
480
- gr.Markdown(help_text1)
481
- gr.Markdown(help_text2)
482
 
483
- demo.queue().launch()
 
484
 
485
 
486
- if __name__ == "__main__":
487
- main()
 
19
  from huggingface_hub import snapshot_download
20
  import spaces
21
 
22
+ models_path = snapshot_download(repo_id="Snapchat/w2w")
23
 
24
+ class main():
25
+ def __init__(self):
26
+ super(main, self).__init__()
27
+
28
+ device = "cuda"
29
+ mean = torch.load(f"{models_path}/files/mean.pt", map_location=torch.device('cpu')).bfloat16().to(device)
30
+ std = torch.load(f"{models_path}/files/std.pt", map_location=torch.device('cpu')).bfloat16().to(device)
31
+ v = torch.load(f"{models_path}/files/V.pt", map_location=torch.device('cpu')).bfloat16().to(device)
32
+ proj = torch.load(f"{models_path}/files/proj_1000pc.pt", map_location=torch.device('cpu')).bfloat16().to(device)
33
+ df = torch.load(f"{models_path}/files/identity_df.pt")
34
+ weight_dimensions = torch.load(f"{models_path}/files/weight_dimensions.pt")
35
+ pinverse = torch.load(f"{models_path}/files/pinverse_1000pc.pt", map_location=torch.device('cpu')).bfloat16().to(device)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
36
 
37
+ self.device = device
38
+ self.mean = mean
39
+ self.std = std
40
+ self.v = v
41
+ self.proj = proj
42
+ self.df = df
43
+ self.weight_dimensions = weight_dimensions
44
+ self.pinverse = pinverse
45
+
46
+ self.unet, self.vae, self.text_encoder, self.tokenizer, self.noise_scheduler = load_models(device)
47
+ self.network = None
48
+
49
+ young = get_direction(df, "Young", pinverse, 1000, device)
50
+ young = debias(young, "Male", df, pinverse, device)
51
+ young = debias(young, "Pointy_Nose", df, pinverse, device)
52
+ young = debias(young, "Wavy_Hair", df, pinverse, device)
53
+ young = debias(young, "Chubby", df, pinverse, device)
54
+ young = debias(young, "No_Beard", df, pinverse, device)
55
+ young = debias(young, "Mustache", df, pinverse, device)
56
+ self.young = young
57
+
58
+ pointy = get_direction(df, "Pointy_Nose", pinverse, 1000, device)
59
+ pointy = debias(pointy, "Young", df, pinverse, device)
60
+ pointy = debias(pointy, "Male", df, pinverse, device)
61
+ pointy = debias(pointy, "Wavy_Hair", df, pinverse, device)
62
+ pointy = debias(pointy, "Chubby", df, pinverse, device)
63
+ pointy = debias(pointy, "Heavy_Makeup", df, pinverse, device)
64
+ self.pointy = pointy
65
+
66
+ wavy = get_direction(df, "Wavy_Hair", pinverse, 1000, device)
67
+ wavy = debias(wavy, "Young", df, pinverse, device)
68
+ wavy = debias(wavy, "Male", df, pinverse, device)
69
+ wavy = debias(wavy, "Pointy_Nose", df, pinverse, device)
70
+ wavy = debias(wavy, "Chubby", df, pinverse, device)
71
+ wavy = debias(wavy, "Heavy_Makeup", df, pinverse, device)
72
+ self.wavy = wavy
73
+
74
+
75
+ thick = get_direction(df, "Bushy_Eyebrows", pinverse, 1000, device)
76
+ thick = debias(thick, "Male", df, pinverse, device)
77
+ thick = debias(thick, "Young", df, pinverse, device)
78
+ thick = debias(thick, "Pointy_Nose", df, pinverse, device)
79
+ thick = debias(thick, "Wavy_Hair", df, pinverse, device)
80
+ thick = debias(thick, "Mustache", df, pinverse, device)
81
+ thick = debias(thick, "No_Beard", df, pinverse, device)
82
+ thick = debias(thick, "Sideburns", df, pinverse, device)
83
+ thick = debias(thick, "Big_Nose", df, pinverse, device)
84
+ thick = debias(thick, "Big_Lips", df, pinverse, device)
85
+ thick = debias(thick, "Black_Hair", df, pinverse, device)
86
+ thick = debias(thick, "Brown_Hair", df, pinverse, device)
87
+ thick = debias(thick, "Pale_Skin", df, pinverse, device)
88
+ thick = debias(thick, "Heavy_Makeup", df, pinverse, device)
89
+ self.thick = thick
90
+
91
+ def sample_model(self):
92
+ self.unet, _, _, _, _ = load_models(self.device)
93
+ self.network = sample_weights(self.unet, self.proj, self.mean, self.std, self.v[:, :1000], self.device, factor = 1.00)
94
+
95
 
96
+ @torch.no_grad()
97
+ @spaces.GPU
98
+ def inference(self, prompt, negative_prompt, guidance_scale, ddim_steps, seed):
99
+ generator = torch.Generator(device=device).manual_seed(seed)
100
+ latents = torch.randn(
101
+ (1, self.unet.in_channels, 512 // 8, 512 // 8),
102
+ generator = generator,
103
+ device = self.device
104
+ ).bfloat16()
105
+
106
+
107
+ text_input = self.tokenizer(prompt, padding="max_length", max_length=self.tokenizer.model_max_length, truncation=True, return_tensors="pt")
108
+
109
+ text_embeddings = self.text_encoder(text_input.input_ids.to(device))[0]
110
+
111
+ max_length = text_input.input_ids.shape[-1]
112
+ uncond_input = self.tokenizer(
113
+ [negative_prompt], padding="max_length", max_length=max_length, return_tensors="pt"
114
+ )
115
+ uncond_embeddings = self.text_encoder(uncond_input.input_ids.to(device))[0]
116
+ text_embeddings = torch.cat([uncond_embeddings, text_embeddings])
117
+ self.noise_scheduler.set_timesteps(ddim_steps)
118
+ latents = latents * self.noise_scheduler.init_noise_sigma
119
+
120
+ for i,t in enumerate(tqdm.tqdm(self.noise_scheduler.timesteps)):
121
+ latent_model_input = torch.cat([latents] * 2)
122
+ latent_model_input = self.noise_scheduler.scale_model_input(latent_model_input, timestep=t)
123
+ with self.network:
124
+ noise_pred = self.unet(latent_model_input, t, encoder_hidden_states=text_embeddings, timestep_cond= None).sample
125
+ #guidance
126
+ noise_pred_uncond, noise_pred_text = noise_pred.chunk(2)
127
+ noise_pred = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond)
128
+ latents = noise_scheduler.step(noise_pred, t, latents).prev_sample
129
+
130
+ latents = 1 / 0.18215 * latents
131
+ image = self.vae.decode(latents).sample
132
+ image = (image / 2 + 0.5).clamp(0, 1)
133
+ image = image.detach().cpu().float().permute(0, 2, 3, 1).numpy()[0]
134
+
135
+ image = Image.fromarray((image * 255).round().astype("uint8"))
136
+
137
+ return image
 
138
 
139
 
140
+ @torch.no_grad()
141
+ @spaces.GPU
142
+ def edit_inference(self, prompt, negative_prompt, guidance_scale, ddim_steps, seed, start_noise, a1, a2, a3, a4):
143
+ original_weights = self,network.proj.clone()
144
+
145
+ #pad to same number of PCs
146
+ pcs_original = original_weights.shape[1]
147
+ pcs_edits = self.young.shape[1]
148
+ padding = torch.zeros((1,pcs_original-pcs_edits)).to(device)
149
+ young_pad = torch.cat((self.young, padding), 1)
150
+ pointy_pad = torch.cat((self.pointy, padding), 1)
151
+ wavy_pad = torch.cat((self.wavy, padding), 1)
152
+ thick_pad = torch.cat((self.thick, padding), 1)
153
+
154
 
155
+ edited_weights = original_weights+a1*1e6*young_pad+a2*1e6*pointy_pad+a3*1e6*wavy_pad+a4*2e6*thick_pad
156
+
157
+ generator = torch.Generator(device=device).manual_seed(seed)
158
+ latents = torch.randn(
159
+ (1, self.unet.in_channels, 512 // 8, 512 // 8),
160
+ generator = generator,
161
+ device = self.device
162
+ ).bfloat16()
163
+
 
 
 
 
 
 
 
 
 
 
 
 
 
 
164
 
165
+ text_input = self.tokenizer(prompt, padding="max_length", max_length=self.tokenizer.model_max_length, truncation=True, return_tensors="pt")
166
+
167
+ text_embeddings = text_encoder(text_input.input_ids.to(device))[0]
168
+
169
+ max_length = text_input.input_ids.shape[-1]
170
+ uncond_input = tokenizer(
171
+ [negative_prompt], padding="max_length", max_length=max_length, return_tensors="pt"
172
+ )
173
+ uncond_embeddings = text_encoder(uncond_input.input_ids.to(device))[0]
174
+ text_embeddings = torch.cat([uncond_embeddings, text_embeddings])
175
+ noise_scheduler.set_timesteps(ddim_steps)
176
+ latents = latents * noise_scheduler.init_noise_sigma
177
 
178
+
179
+
180
+ for i,t in enumerate(tqdm.tqdm(self.noise_scheduler.timesteps)):
181
+ latent_model_input = torch.cat([latents] * 2)
182
+ latent_model_input = self.noise_scheduler.scale_model_input(latent_model_input, timestep=t)
 
 
 
 
183
 
184
+ if t>start_noise:
185
+ pass
186
+ elif t<=start_noise:
187
+ self.network.proj = torch.nn.Parameter(edited_weights)
188
+ self.network.reset()
189
+
190
+
191
+ with self.network:
192
+ noise_pred = self.unet(latent_model_input, t, encoder_hidden_states=text_embeddings, timestep_cond= None).sample
193
+
194
+
195
+ #guidance
196
+ noise_pred_uncond, noise_pred_text = noise_pred.chunk(2)
197
+ noise_pred = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond)
198
+ latents = noise_scheduler.step(noise_pred, t, latents).prev_sample
199
 
200
+ latents = 1 / 0.18215 * latents
201
+ image = self.vae.decode(latents).sample
202
+ image = (image / 2 + 0.5).clamp(0, 1)
203
+
204
+ image = image.detach().cpu().float().permute(0, 2, 3, 1).numpy()[0]
205
+
206
+ image = Image.fromarray((image * 255).round().astype("uint8"))
207
+
208
+ #reset weights back to original
209
+ self.network.proj = torch.nn.Parameter(original_weights)
210
+ self.network.reset()
211
+
212
+ return image
 
 
 
 
 
213
 
214
+ @spaces.GPU
215
+ def sample_then_run(self):
216
+ sample_model()
217
+ prompt = "sks person"
218
+ negative_prompt = "low quality, blurry, unfinished, nudity, weapon"
219
+ seed = 5
220
+ cfg = 3.0
221
+ steps = 25
222
+ image = inference( prompt, negative_prompt, cfg, steps, seed)
223
+ torch.save(self.network.proj, "model.pt" )
224
+ return image, "model.pt"
 
225
 
226
 
227
 
228
+ class CustomImageDataset(Dataset):
229
+ def __init__(self, images, transform=None):
230
+ self.images = images
231
+ self.transform = transform
232
+
233
+ def __len__(self):
234
+ return len(self.images)
235
+
236
+ def __getitem__(self, idx):
237
+ image = self.images[idx]
238
+ if self.transform:
239
+ image = self.transform(image)
240
+ return image
241
+
242
+ @spaces.GPU
243
+ def invert(image, mask, pcs=10000, epochs=400, weight_decay = 1e-10, lr=1e-1):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
244
 
245
+ del unet
246
+ del network
247
+ unet, _, _, _, _ = load_models(device)
248
+
249
+ proj = torch.zeros(1,pcs).bfloat16().to(device)
250
+ network = LoRAw2w( proj, mean, std, v[:, :pcs],
251
+ unet,
252
+ rank=1,
253
+ multiplier=1.0,
254
+ alpha=27.0,
255
+ train_method="xattn-strict"
256
+ ).to(device, torch.bfloat16)
257
+
258
+ ### load mask
259
+ mask = transforms.Resize((64,64), interpolation=transforms.InterpolationMode.BILINEAR)(mask)
260
+ mask = torchvision.transforms.functional.pil_to_tensor(mask).unsqueeze(0).to(device).bfloat16()[:,0,:,:].unsqueeze(1)
261
+ ### check if an actual mask was draw, otherwise mask is just all ones
262
+ if torch.sum(mask) == 0:
263
+ mask = torch.ones((1,1,64,64)).to(device).bfloat16()
264
+
265
+ ### single image dataset
266
+ image_transforms = transforms.Compose([transforms.Resize(512, interpolation=transforms.InterpolationMode.BILINEAR),
267
+ transforms.RandomCrop(512),
268
+ transforms.ToTensor(),
269
+ transforms.Normalize([0.5], [0.5])])
270
+
271
+
272
+ train_dataset = CustomImageDataset(image, transform=image_transforms)
273
+ train_dataloader = torch.utils.data.DataLoader(train_dataset, batch_size=1, shuffle=True)
274
+
275
+ ### optimizer
276
+ optim = torch.optim.Adam(network.parameters(), lr=lr, weight_decay=weight_decay)
277
+
278
+ ### training loop
279
+ unet.train()
280
+ for epoch in tqdm.tqdm(range(epochs)):
281
+ for batch in train_dataloader:
282
+ ### prepare inputs
283
+ batch = batch.to(device).bfloat16()
284
+ latents = vae.encode(batch).latent_dist.sample()
285
+ latents = latents*0.18215
286
+ noise = torch.randn_like(latents)
287
+ bsz = latents.shape[0]
288
+
289
+ timesteps = torch.randint(0, noise_scheduler.config.num_train_timesteps, (bsz,), device=latents.device)
290
+ timesteps = timesteps.long()
291
+ noisy_latents = noise_scheduler.add_noise(latents, noise, timesteps)
292
+ text_input = tokenizer("sks person", padding="max_length", max_length=tokenizer.model_max_length, truncation=True, return_tensors="pt")
293
+ text_embeddings = text_encoder(text_input.input_ids.to(device))[0]
294
+
295
+ ### loss + sgd step
296
+ with network:
297
+ model_pred = unet(noisy_latents, timesteps, text_embeddings).sample
298
+ loss = torch.nn.functional.mse_loss(mask*model_pred.float(), mask*noise.float(), reduction="mean")
299
+ optim.zero_grad()
300
+ loss.backward()
301
+ optim.step()
302
+
303
+ ### return optimized network
304
+ return network
305
 
306
 
307
+ @spaces.GPU
308
+ def run_inversion(dict, pcs, epochs, weight_decay,lr):
309
+ init_image = dict["image"].convert("RGB").resize((512, 512))
310
+ mask = dict["mask"].convert("RGB").resize((512, 512))
311
+ network = invert([init_image], mask, pcs, epochs, weight_decay,lr)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
312
 
313
+
314
+ #sample an image
315
+ prompt = "sks person"
316
+ negative_prompt = "low quality, blurry, unfinished, nudity"
317
+ seed = 5
318
+ cfg = 3.0
319
+ steps = 25
320
+ image = inference( prompt, negative_prompt, cfg, steps, seed)
321
+ torch.save(network.proj, "model.pt" )
322
+ return image, "model.pt"
323
 
324
 
325
+ @spaces.GPU
326
+ def file_upload(file):
327
+ del unet
328
+ del network
 
 
 
329
 
330
+ proj = torch.load(file.name).to(device)
331
+
332
+ #pad to 10000 Principal components to keep everything consistent
333
+ pcs = proj.shape[1]
334
+ padding = torch.zeros((1,10000-pcs)).to(device)
335
+ proj = torch.cat((proj, padding), 1)
336
+
337
+ unet, _, _, _, _ = load_models(device)
338
 
339
+
340
+ network = LoRAw2w( proj, mean, std, v[:, :10000],
341
+ unet,
342
+ rank=1,
343
+ multiplier=1.0,
344
+ alpha=27.0,
345
+ train_method="xattn-strict"
346
+ ).to(device, torch.bfloat16)
347
+
348
+
349
+ prompt = "sks person"
350
+ negative_prompt = "low quality, blurry, unfinished, nudity"
351
+ seed = 5
352
+ cfg = 3.0
353
+ steps = 25
354
+ image = inference( prompt, negative_prompt, cfg, steps, seed)
355
+ return image
356
 
357
 
358
 
359
 
360
+ intro = """
361
+ <div style="display: flex;align-items: center;justify-content: center">
362
  <h1 style="margin-left: 12px;text-align: center;margin-bottom: 7px;display: inline-block"><em>weights2weights</em> Demo</h1>
363
  <h3 style="display: inline-block;margin-left: 10px;margin-top: 6px;font-weight: 500">Interpreting the Weight Space of Customized Diffusion Models</h3>
364
  </div>
 
374
 
375
 
376
 
377
+ with gr.Blocks(css="style.css") as demo:
378
+ model = main()
379
+ gr.HTML(intro)
 
 
380
 
381
+ gr.Markdown("""<div style="text-align: justify;"> In this demo, you can get an identity-encoding model by sampling or inverting. To use a model previously downloaded from this demo see \"Uploading a model\" in the Advanced Options. Next, you can generate new images from it, or edit the identity encoded in the model and generate images from the edited model. We provide detailed instructions and tips at the bottom of the page.""")
382
+ with gr.Column():
383
+ with gr.Row():
384
+ with gr.Column():
385
+ gr.Markdown("""1) Either sample a new model, or upload an image (optionally draw a mask over the head) and click `invert`.""")
386
+ sample = gr.Button("🎲 Sample New Model")
387
+ input_image = gr.ImageEditor(elem_id="image_upload", type='pil', label="Reference Identity",
388
  width=512, height=512)
389
 
390
+ with gr.Row():
391
+ invert_button = gr.Button("⬆️ Invert")
392
 
393
 
394
 
395
+ with gr.Column():
396
+ gr.Markdown("""2) Generate images of the sampled/inverted identity or edit the identity with the sliders and generate new images with various prompts and seeds.""")
397
+ gallery = gr.Image(label="Generated Image",height=512, width=512, interactive=False)
398
+ submit = gr.Button("Generate")
399
 
400
 
401
+ prompt = gr.Textbox(label="Prompt",
402
  info="Make sure to include 'sks person'" ,
403
  placeholder="sks person",
404
  value="sks person")
405
 
406
+ seed = gr.Number(value=5, label="Seed", precision=0, interactive=True)
407
 
408
+ # Editing
409
+ with gr.Column():
410
+ with gr.Row():
411
+ a1 = gr.Slider(label="- Young +", value=0, step=0.001, minimum=-1, maximum=1, interactive=True)
412
+ a2 = gr.Slider(label="- Pointy Nose +", value=0, step=0.001, minimum=-1, maximum=1, interactive=True)
413
+ with gr.Row():
414
+ a3 = gr.Slider(label="- Curly Hair +", value=0, step=0.001, minimum=-1, maximum=1, interactive=True)
415
+ a4 = gr.Slider(label="- Thick Eyebrows +", value=0, step=0.001, minimum=-1, maximum=1, interactive=True)
416
 
417
 
418
+ with gr.Accordion("Advanced Options", open=False):
419
+ with gr.Tab("Inversion"):
420
+ with gr.Row():
421
+ lr = gr.Number(value=1e-1, label="Learning Rate", interactive=True)
422
+ pcs = gr.Slider(label="# Principal Components", value=10000, step=1, minimum=1, maximum=10000, interactive=True)
423
+ with gr.Row():
424
+ epochs = gr.Slider(label="Epochs", value=800, step=1, minimum=1, maximum=2000, interactive=True)
425
+ weight_decay = gr.Number(value=1e-10, label="Weight Decay", interactive=True)
426
+ with gr.Tab("Sampling"):
427
+ with gr.Row():
428
+ cfg= gr.Slider(label="CFG", value=3.0, step=0.1, minimum=0, maximum=10, interactive=True)
429
+ steps = gr.Slider(label="Inference Steps", value=25, step=1, minimum=0, maximum=100, interactive=True)
430
+ with gr.Row():
431
+ negative_prompt = gr.Textbox(label="Negative Prompt", placeholder="low quality, blurry, unfinished, nudity, weapon", value="low quality, blurry, unfinished, nudity, weapon")
432
+ injection_step = gr.Slider(label="Injection Step", value=800, step=1, minimum=0, maximum=1000, interactive=True)
433
 
434
+ with gr.Tab("Uploading a model"):
435
+ gr.Markdown("""<div style="text-align: justify;">Upload a model below downloaded from this demo.""")
436
 
437
+ file_input = gr.File(label="Upload Model", container=True)
438
 
439
 
440
 
441
 
442
+ gr.Markdown("""<div style="text-align: justify;"> After sampling a new model or inverting, you can download the model below.""")
443
 
444
+ with gr.Row():
445
+ file_output = gr.File(label="Download Sampled/Inverted Model", container=True, interactive=False)
446
 
447
 
448
 
449
 
450
+ invert_button.click(fn=run_inversion,
451
  inputs=[input_image, pcs, epochs, weight_decay,lr],
452
  outputs = [input_image, file_output])
453
 
454
 
455
+ sample.click(fn=model.sample_then_run, outputs=[input_image, file_output])
456
 
457
+ submit.click(
458
+ fn=model.edit_inference, inputs=[prompt, negative_prompt, cfg, steps, seed, injection_step, a1, a2, a3, a4], outputs=[gallery]
459
  )
460
+ file_input.change(fn=file_upload, inputs=file_input, outputs = gallery)
461
 
462
 
463
 
464
+ help_text1 = """
465
  <b>Instructions</b>:
466
  1. To get results faster without waiting in queue, you can duplicate into a private space with an A100 GPU.
467
  2. To begin, you will have to get an identity-encoding model. You can either sample one from *weights2weights* space by clicking `Sample New Model` or by uploading an image and clicking `invert` to invert the identity into a model. You can optionally draw over the head to define a mask in the image for better results. Sampling a model takes around 10 seconds and inversion takes around 2 minutes. After this is done, you can optionally download this model for later use. A model can be uploaded in the \"Uploading a model\" tab in the `Advanced Options`.
468
  3. After getting a model, an image of the identity will be displayed on the right. You can sample from the model by changing seeds as well as prompts and then clicking `Generate`. Make sure to include \"sks person\" in your prompt to keep the same identity.
469
  4. The identity in the model can be edited by changing the sliders for various attributes. After clicking `Generate`, you can see how the identity has changed and the effects are maintained across different seeds and prompts.
470
  """
471
+ help_text2 = """<b>Tips</b>:
472
  1. Editing and Identity Generation
473
  * If you are interested in preserving more of the image during identity-editing (i.e., where the same seed and prompt results in the same image with only the identity changed), you can play with the "Injection Step" parameter in the \"Sampling\" tab in the `Advanced Options`. During the first *n* timesteps, the original model's weights will be used, and then the edited weights will be set during the remaining steps. Values closer to 1000 will set the edited weights early, having a more pronounced effect, which may disrupt some semantics and structure of the generated image. Lower values will set the edited weights later, better preserving image context. We notice that around 600-800 tends to produce the best results. Larger values in the range (700-1000) are helpful for more global attribute changes, while smaller (400-700) can be used for more finegrained edits. Although it is not always needed.
474
  * You can play around with negative prompts, number of inference steps, and CFG in the \"Sampling\" tab in the `Advanced Options` to affect the ultimate image quality.
 
480
  * Note that if you change the number of PCs, you will probably need to change the learning rate. For less PCs, higher learning rates are typically required."""
481
 
482
 
483
+ gr.Markdown(help_text1)
484
+ gr.Markdown(help_text2)
485
 
486
+ demo.queue().launch()
487
+
488
 
489