amildravid4292 commited on
Commit
99e4caa
·
verified ·
1 Parent(s): a7f7674

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +439 -411
app.py CHANGED
@@ -12,399 +12,424 @@ import warnings
12
  warnings.filterwarnings("ignore")
13
  from PIL import Image
14
  import numpy as np
15
- from utils import load_models
16
  from editing import get_direction, debias
17
  from sampling import sample_weights
18
  from lora_w2w import LoRAw2w
 
 
 
 
 
 
 
 
 
 
 
 
 
19
  from huggingface_hub import snapshot_download
20
  import spaces
21
- import uuid
22
-
23
- global device
24
- device = "cuda"
25
-
26
 
27
  models_path = snapshot_download(repo_id="Snapchat/w2w")
28
 
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
- global young
38
- global pointy
39
- global wavy
40
- global thick
41
- young = get_direction(df, "Young", pinverse, 1000, device)
42
- young = debias(young, "Male", df, pinverse, device)
43
- young = debias(young, "Pointy_Nose", df, pinverse, device)
44
- young = debias(young, "Wavy_Hair", df, pinverse, device)
45
- young = debias(young, "Chubby", df, pinverse, device)
46
- young = debias(young, "No_Beard", df, pinverse, device)
47
- young = debias(young, "Mustache", df, pinverse, device)
48
-
49
- pointy = get_direction(df, "Pointy_Nose", pinverse, 1000, device)
50
- pointy = debias(pointy, "Young", df, pinverse, device)
51
- pointy = debias(pointy, "Male", df, pinverse, device)
52
- pointy = debias(pointy, "Wavy_Hair", df, pinverse, device)
53
- pointy = debias(pointy, "Chubby", df, pinverse, device)
54
- pointy = debias(pointy, "Heavy_Makeup", df, pinverse, device)
55
-
56
- wavy = get_direction(df, "Wavy_Hair", pinverse, 1000, device)
57
- wavy = debias(wavy, "Young", df, pinverse, device)
58
- wavy = debias(wavy, "Male", df, pinverse, device)
59
- wavy = debias(wavy, "Pointy_Nose", df, pinverse, device)
60
- wavy = debias(wavy, "Chubby", df, pinverse, device)
61
- wavy = debias(wavy, "Heavy_Makeup", df, pinverse, device)
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
-
79
-
80
- @torch.no_grad()
81
  @spaces.GPU
82
- def sample_then_run(network, unet):
83
- #load models
84
- mean.to(device)
85
- std.to(device)
86
- v.to(device)
87
- proj.to(device)
88
- unet, _, _, _, _ = load_models(device)
89
- network = sample_weights(unet, proj, mean, std, v[:, :1000], device, factor = 1.00)
90
- #inference
91
- prompt = "sks person"
92
- negative_prompt = "low quality, blurry, unfinished, nudity, weapon"
93
- seed = 5
94
- cfg = 3.0
95
- steps = 25
96
- image = inference( network, unet, prompt, negative_prompt, cfg, steps, seed)
97
- torch.save(network.proj.detach().cpu(), "model.pt" )
98
- print("done saving")
99
- return image, "model.pt", network.proj.detach().cpu()
100
-
101
-
102
 
 
 
 
103
 
104
-
105
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
106
 
107
- @torch.no_grad()
108
- @spaces.GPU
109
- def inference(network, unet, prompt, negative_prompt, guidance_scale, ddim_steps, seed):
110
- global device
111
- generator = torch.Generator(device=device).manual_seed(seed)
112
- latents = torch.randn(
113
- (1, unet.in_channels, 512 // 8, 512 // 8),
114
- generator = generator,
115
- device = device
116
- ).bfloat16()
117
-
118
-
119
- text_input = tokenizer(prompt, padding="max_length", max_length=tokenizer.model_max_length, truncation=True, return_tensors="pt")
120
-
121
- text_embeddings = text_encoder(text_input.input_ids.to(device))[0]
122
-
123
- max_length = text_input.input_ids.shape[-1]
124
- uncond_input = tokenizer(
125
- [negative_prompt], padding="max_length", max_length=max_length, return_tensors="pt"
126
- )
127
- uncond_embeddings = text_encoder(uncond_input.input_ids.to(device))[0]
128
- text_embeddings = torch.cat([uncond_embeddings, text_embeddings])
129
- noise_scheduler.set_timesteps(ddim_steps)
130
- latents = latents * noise_scheduler.init_noise_sigma
131
-
132
- for i,t in enumerate(tqdm.tqdm(noise_scheduler.timesteps)):
133
- latent_model_input = torch.cat([latents] * 2)
134
- latent_model_input = noise_scheduler.scale_model_input(latent_model_input, timestep=t)
135
- with network:
136
- noise_pred = unet(latent_model_input, t, encoder_hidden_states=text_embeddings, timestep_cond= None).sample
137
- #guidance
138
- noise_pred_uncond, noise_pred_text = noise_pred.chunk(2)
139
- noise_pred = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond)
140
- latents = noise_scheduler.step(noise_pred, t, latents).prev_sample
141
-
142
- latents = 1 / 0.18215 * latents
143
- image = vae.decode(latents).sample
144
- image = (image / 2 + 0.5).clamp(0, 1)
145
- image = image.detach().cpu().float().permute(0, 2, 3, 1).numpy()[0]
146
-
147
- image = Image.fromarray((image * 255).round().astype("uint8"))
148
-
149
- return image
150
-
151
-
152
- @torch.no_grad()
153
- @spaces.GPU
154
- def edit_inference(prompt, negative_prompt, guidance_scale, ddim_steps, seed, start_noise, a1, a2, a3, a4):
155
- start_items()
156
- global device
157
- #global generator
158
- global unet
159
- global vae
160
- global text_encoder
161
- global tokenizer
162
- global noise_scheduler
163
- global young
164
- global pointy
165
- global wavy
166
- global thick
167
-
168
- original_weights = network.proj.clone()
169
-
170
- #pad to same number of PCs
171
- pcs_original = original_weights.shape[1]
172
- pcs_edits = young.shape[1]
173
- padding = torch.zeros((1,pcs_original-pcs_edits)).to(device)
174
- young_pad = torch.cat((young, padding), 1)
175
- pointy_pad = torch.cat((pointy, padding), 1)
176
- wavy_pad = torch.cat((wavy, padding), 1)
177
- thick_pad = torch.cat((thick, padding), 1)
178
 
 
 
 
 
 
179
 
180
- edited_weights = original_weights+a1*1e6*young_pad+a2*1e6*pointy_pad+a3*1e6*wavy_pad+a4*2e6*thick_pad
181
-
182
- generator = torch.Generator(device=device).manual_seed(seed)
183
- latents = torch.randn(
184
- (1, unet.in_channels, 512 // 8, 512 // 8),
185
- generator = generator,
186
- device = device
187
- ).bfloat16()
188
-
189
 
190
- text_input = tokenizer(prompt, padding="max_length", max_length=tokenizer.model_max_length, truncation=True, return_tensors="pt")
191
-
192
- text_embeddings = text_encoder(text_input.input_ids.to(device))[0]
193
-
194
- max_length = text_input.input_ids.shape[-1]
195
- uncond_input = tokenizer(
196
- [negative_prompt], padding="max_length", max_length=max_length, return_tensors="pt"
197
- )
198
- uncond_embeddings = text_encoder(uncond_input.input_ids.to(device))[0]
199
- text_embeddings = torch.cat([uncond_embeddings, text_embeddings])
200
- noise_scheduler.set_timesteps(ddim_steps)
201
- latents = latents * noise_scheduler.init_noise_sigma
 
 
 
 
 
 
 
 
 
 
 
 
 
202
 
203
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
204
 
205
- for i,t in enumerate(tqdm.tqdm(noise_scheduler.timesteps)):
206
- latent_model_input = torch.cat([latents] * 2)
207
- latent_model_input = noise_scheduler.scale_model_input(latent_model_input, timestep=t)
208
-
209
- if t>start_noise:
210
- pass
211
- elif t<=start_noise:
212
- network.proj = torch.nn.Parameter(edited_weights)
213
- network.reset()
214
-
215
-
216
- with network:
217
- noise_pred = unet(latent_model_input, t, encoder_hidden_states=text_embeddings, timestep_cond= None).sample
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
218
 
 
 
 
 
 
 
219
 
220
- #guidance
221
- noise_pred_uncond, noise_pred_text = noise_pred.chunk(2)
222
- noise_pred = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond)
223
- latents = noise_scheduler.step(noise_pred, t, latents).prev_sample
224
-
225
- latents = 1 / 0.18215 * latents
226
- image = vae.decode(latents).sample
227
- image = (image / 2 + 0.5).clamp(0, 1)
228
-
229
- image = image.detach().cpu().float().permute(0, 2, 3, 1).numpy()[0]
230
-
231
- image = Image.fromarray((image * 255).round().astype("uint8"))
232
-
233
- #reset weights back to original
234
- network.proj = torch.nn.Parameter(original_weights)
235
- network.reset()
236
-
237
- return image
238
-
239
-
240
-
241
-
242
-
243
-
244
- class CustomImageDataset(Dataset):
245
- def __init__(self, images, transform=None):
246
- self.images = images
247
- self.transform = transform
248
-
249
- def __len__(self):
250
- return len(self.images)
251
-
252
- def __getitem__(self, idx):
253
- image = self.images[idx]
254
- if self.transform:
255
- image = self.transform(image)
256
  return image
257
 
258
- @spaces.GPU
259
- def invert(image, mask, pcs=10000, epochs=400, weight_decay = 1e-10, lr=1e-1):
260
- global unet
261
- del unet
262
- global network
263
- unet, _, _, _, _ = load_models(device)
264
-
265
- proj = torch.zeros(1,pcs).bfloat16().to(device)
266
- network = LoRAw2w( proj, mean, std, v[:, :pcs],
267
- unet,
268
- rank=1,
269
- multiplier=1.0,
270
- alpha=27.0,
271
- train_method="xattn-strict"
272
- ).to(device, torch.bfloat16)
273
-
274
- ### load mask
275
- mask = transforms.Resize((64,64), interpolation=transforms.InterpolationMode.BILINEAR)(mask)
276
- mask = torchvision.transforms.functional.pil_to_tensor(mask).unsqueeze(0).to(device).bfloat16()[:,0,:,:].unsqueeze(1)
277
- ### check if an actual mask was draw, otherwise mask is just all ones
278
- if torch.sum(mask) == 0:
279
- mask = torch.ones((1,1,64,64)).to(device).bfloat16()
280
-
281
- ### single image dataset
282
- image_transforms = transforms.Compose([transforms.Resize(512, interpolation=transforms.InterpolationMode.BILINEAR),
283
- transforms.RandomCrop(512),
284
- transforms.ToTensor(),
285
- transforms.Normalize([0.5], [0.5])])
286
-
287
-
288
- train_dataset = CustomImageDataset(image, transform=image_transforms)
289
- train_dataloader = torch.utils.data.DataLoader(train_dataset, batch_size=1, shuffle=True)
290
-
291
- ### optimizer
292
- optim = torch.optim.Adam(network.parameters(), lr=lr, weight_decay=weight_decay)
293
 
294
- ### training loop
295
- unet.train()
296
- for epoch in tqdm.tqdm(range(epochs)):
297
- for batch in train_dataloader:
298
- ### prepare inputs
299
- batch = batch.to(device).bfloat16()
300
- latents = vae.encode(batch).latent_dist.sample()
301
- latents = latents*0.18215
302
- noise = torch.randn_like(latents)
303
- bsz = latents.shape[0]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
304
 
305
- timesteps = torch.randint(0, noise_scheduler.config.num_train_timesteps, (bsz,), device=latents.device)
306
- timesteps = timesteps.long()
307
- noisy_latents = noise_scheduler.add_noise(latents, noise, timesteps)
308
- text_input = tokenizer("sks person", padding="max_length", max_length=tokenizer.model_max_length, truncation=True, return_tensors="pt")
309
- text_embeddings = text_encoder(text_input.input_ids.to(device))[0]
310
-
311
- ### loss + sgd step
312
- with network:
313
- model_pred = unet(noisy_latents, timesteps, text_embeddings).sample
314
- loss = torch.nn.functional.mse_loss(mask*model_pred.float(), mask*noise.float(), reduction="mean")
315
- optim.zero_grad()
316
- loss.backward()
317
- optim.step()
318
-
319
- ### return optimized network
320
- return network
321
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
322
 
323
- @spaces.GPU
324
- def run_inversion(dict, pcs, epochs, weight_decay,lr):
325
- global network
326
- init_image = dict["image"].convert("RGB").resize((512, 512))
327
- mask = dict["mask"].convert("RGB").resize((512, 512))
328
- network = invert([init_image], mask, pcs, epochs, weight_decay,lr)
 
 
 
 
 
329
 
330
 
331
- #sample an image
332
- prompt = "sks person"
333
- negative_prompt = "low quality, blurry, unfinished, nudity"
334
- seed = 5
335
- cfg = 3.0
336
- steps = 25
337
- image = inference( prompt, negative_prompt, cfg, steps, seed)
338
- torch.save(network.proj, "model.pt" )
339
- return image, "model.pt"
340
-
341
-
342
- @spaces.GPU
343
- def file_upload(file):
344
- global unet
345
- del unet
346
- global network
347
- global device
348
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
349
 
350
-
351
- proj = torch.load(file.name).to(device)
352
-
353
- #pad to 10000 Principal components to keep everything consistent
354
- pcs = proj.shape[1]
355
- padding = torch.zeros((1,10000-pcs)).to(device)
356
- proj = torch.cat((proj, padding), 1)
357
-
358
- unet, _, _, _, _ = load_models(device)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
359
 
360
 
361
- network = LoRAw2w( proj, mean, std, v[:, :10000],
362
- unet,
363
- rank=1,
364
- multiplier=1.0,
365
- alpha=27.0,
366
- train_method="xattn-strict"
367
- ).to(device, torch.bfloat16)
368
 
 
 
 
 
 
 
 
 
 
369
 
370
- prompt = "sks person"
371
- negative_prompt = "low quality, blurry, unfinished, nudity"
372
- seed = 5
373
- cfg = 3.0
374
- steps = 25
375
- image = inference( prompt, negative_prompt, cfg, steps, seed)
376
- return image
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
377
 
378
 
379
 
380
 
381
  intro = """
382
  <div style="display: flex;align-items: center;justify-content: center">
383
- <h1 style="margin-left: 12px;text-align: center;margin-bottom: 7px;display: inline-block"><em>weights2weights</em> Demo</h1>
384
- <h3 style="display: inline-block;margin-left: 10px;margin-top: 6px;font-weight: 500">Interpreting the Weight Space of Customized Diffusion Models</h3>
385
- </div>
386
- <p style="font-size: 0.95rem;margin: 0rem;line-height: 1.2em;margin-top:1em;display: inline-block">
387
- <a href="https://snap-research.github.io/weights2weights/" target="_blank">Project Page</a> | <a href="https://arxiv.org/abs/2406.09413" target="_blank">Paper</a>
388
- | <a href="https://github.com/snap-research/weights2weights" target="_blank">Code</a> |
389
- <a href="https://huggingface.co/spaces/Snapchat/w2w-demo?duplicate=true" target="_blank" style="
390
- display: inline-block;
391
- ">
392
- <img style="margin-top: -1em;margin-bottom: 0em;position: absolute;" src="https://bit.ly/3CWLGkA" alt="Duplicate Space"></a>
393
- </p>
394
- """
395
-
396
-
397
-
398
- with gr.Blocks(css="style.css") as demo:
399
- network = gr.State()
400
- unet = gr.State()
401
- vae = gr.State()
402
- text_encoder = gr.State()
403
- tokenizer = gr.State()
404
- noise_scheduler = gr.State()
405
- _, vae, text_encoder, tokenizer, noise_scheduler = load_models(device)
406
 
 
 
 
 
407
  gr.HTML(intro)
 
408
  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.""")
409
  with gr.Column():
410
  with gr.Row():
@@ -412,26 +437,26 @@ with gr.Blocks(css="style.css") as demo:
412
  gr.Markdown("""1) Either sample a new model, or upload an image (optionally draw a mask over the head) and click `invert`.""")
413
  sample = gr.Button("🎲 Sample New Model")
414
  input_image = gr.ImageEditor(elem_id="image_upload", type='pil', label="Reference Identity",
415
- width=512, height=512)
416
-
417
  with gr.Row():
418
  invert_button = gr.Button("⬆️ Invert")
419
-
420
-
421
-
422
  with gr.Column():
423
  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.""")
424
  gallery = gr.Image(label="Generated Image",height=512, width=512, interactive=False)
425
  submit = gr.Button("Generate")
426
-
427
-
428
  prompt = gr.Textbox(label="Prompt",
429
- info="Make sure to include 'sks person'" ,
430
- placeholder="sks person",
431
- value="sks person")
432
-
433
- seed = gr.Number(value=5, label="Seed", precision=0, interactive=True)
434
 
 
 
435
  # Editing
436
  with gr.Column():
437
  with gr.Row():
@@ -440,8 +465,8 @@ with gr.Blocks(css="style.css") as demo:
440
  with gr.Row():
441
  a3 = gr.Slider(label="- Curly Hair +", value=0, step=0.001, minimum=-1, maximum=1, interactive=True)
442
  a4 = gr.Slider(label="- Thick Eyebrows +", value=0, step=0.001, minimum=-1, maximum=1, interactive=True)
443
-
444
-
445
  with gr.Accordion("Advanced Options", open=False):
446
  with gr.Tab("Inversion"):
447
  with gr.Row():
@@ -452,62 +477,65 @@ with gr.Blocks(css="style.css") as demo:
452
  weight_decay = gr.Number(value=1e-10, label="Weight Decay", interactive=True)
453
  with gr.Tab("Sampling"):
454
  with gr.Row():
455
- cfg= gr.Slider(label="CFG", value=3.0, step=0.1, minimum=0, maximum=10, interactive=True)
456
- steps = gr.Slider(label="Inference Steps", value=25, step=1, minimum=0, maximum=100, interactive=True)
457
  with gr.Row():
458
- negative_prompt = gr.Textbox(label="Negative Prompt", placeholder="low quality, blurry, unfinished, nudity, weapon", value="low quality, blurry, unfinished, nudity, weapon")
459
- injection_step = gr.Slider(label="Injection Step", value=800, step=1, minimum=0, maximum=1000, interactive=True)
460
-
461
  with gr.Tab("Uploading a model"):
462
  gr.Markdown("""<div style="text-align: justify;">Upload a model below downloaded from this demo.""")
463
-
464
  file_input = gr.File(label="Upload Model", container=True)
465
-
466
-
467
-
468
-
469
  gr.Markdown("""<div style="text-align: justify;"> After sampling a new model or inverting, you can download the model below.""")
470
-
471
  with gr.Row():
472
  file_output = gr.File(label="Download Sampled/Inverted Model", container=True, interactive=False)
473
-
474
-
475
-
476
-
477
- invert_button.click(fn=run_inversion,
478
- inputs=[input_image, pcs, epochs, weight_decay,lr],
479
- outputs = [input_image, file_output])
480
-
481
 
482
- sample.click(fn=sample_then_run, outputs=[network, input_image, file_output])
483
-
 
 
 
 
 
 
 
 
484
  submit.click(
485
- fn=edit_inference, inputs=[prompt, negative_prompt, cfg, steps, seed, injection_step, a1, a2, a3, a4], outputs=[gallery]
486
- )
487
- file_input.change(fn=file_upload, inputs=file_input, outputs = gallery)
488
-
489
-
490
-
491
  help_text1 = """
492
- <b>Instructions</b>:
493
- 1. To get results faster without waiting in queue, you can duplicate into a private space with an A100 GPU.
494
- 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`.
495
- 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.
496
- 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.
497
- """
498
  help_text2 = """<b>Tips</b>:
499
- 1. Editing and Identity Generation
500
- * 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.
501
- * 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.
502
- * Sometimes the identity will not be perfectly consistent (e.g., there might be small variations of the face) when you use some seeds or prompts. This is a limitation of our method as well as an open-problem in personalized models.
503
- 2. Inversion
504
- * To obtain the best results for inversion, upload a high resolution photo of the face with minimal occlusion. It is recommended to draw over the face and hair to define a mask. But inversion should still work generally for non-closeup face shots.
505
- * For inverting a realistic photo of an identity, typically 800 epochs with lr=1e-1 and 10,000 principal components (PCs) works well. If the resulting generations have artifacted and unrealstic textures, there is probably overfitting and you may want to reduce the number of epochs or learning rate, or play with weight decay. If the generations do not look like the input photo, then you may want to increase the number of epochs.
506
- * For inverting out-of-distribution identities, such as artistic renditions of people or non-humans (e.g. the ones shown in the paper), it is recommended to use 1000 PCs, lr=1, and train for 800 epochs.
507
- * 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."""
508
-
509
 
 
510
  gr.Markdown(help_text1)
511
  gr.Markdown(help_text2)
512
- #demo.load(fn=start_items)
513
  demo.queue().launch()
 
 
 
 
12
  warnings.filterwarnings("ignore")
13
  from PIL import Image
14
  import numpy as np
 
15
  from editing import get_direction, debias
16
  from sampling import sample_weights
17
  from lora_w2w import LoRAw2w
18
+ from transformers import CLIPTextModel
19
+ from lora_w2w import LoRAw2w
20
+ from diffusers import AutoencoderKL, DDPMScheduler, DiffusionPipeline, UNet2DConditionModel, LMSDiscreteScheduler
21
+ from transformers import AutoTokenizer, PretrainedConfig
22
+ from diffusers import (
23
+ AutoencoderKL,
24
+ DDPMScheduler,
25
+ DiffusionPipeline,
26
+ DPMSolverMultistepScheduler,
27
+ UNet2DConditionModel,
28
+ PNDMScheduler,
29
+ StableDiffusionPipeline
30
+ )
31
  from huggingface_hub import snapshot_download
32
  import spaces
 
 
 
 
 
33
 
34
  models_path = snapshot_download(repo_id="Snapchat/w2w")
35
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
36
  @spaces.GPU
37
+ def load_models(device):
38
+ pretrained_model_name_or_path = "stablediffusionapi/realistic-vision-v51"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
39
 
40
+ revision = None
41
+ rank = 1
42
+ weight_dtype = torch.bfloat16
43
 
44
+ # Load scheduler, tokenizer and models.
45
+ pipe = StableDiffusionPipeline.from_pretrained("stablediffusionapi/realistic-vision-v51",
46
+ torch_dtype=torch.float16,safety_checker = None,
47
+ requires_safety_checker = False).to(device)
48
+ noise_scheduler = pipe.scheduler
49
+ del pipe
50
+ tokenizer = AutoTokenizer.from_pretrained(
51
+ pretrained_model_name_or_path, subfolder="tokenizer", revision=revision
52
+ )
53
+ text_encoder = CLIPTextModel.from_pretrained(
54
+ pretrained_model_name_or_path, subfolder="text_encoder", revision=revision
55
+ )
56
+ vae = AutoencoderKL.from_pretrained(pretrained_model_name_or_path, subfolder="vae", revision=revision)
57
+ unet = UNet2DConditionModel.from_pretrained(
58
+ pretrained_model_name_or_path, subfolder="unet", revision=revision
59
+ )
60
 
61
+ unet.requires_grad_(False)
62
+ unet.to(device, dtype=weight_dtype)
63
+ vae.requires_grad_(False)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
64
 
65
+ text_encoder.requires_grad_(False)
66
+ vae.requires_grad_(False)
67
+ vae.to(device, dtype=weight_dtype)
68
+ text_encoder.to(device, dtype=weight_dtype)
69
+ print("")
70
 
71
+ return unet, vae, text_encoder, tokenizer, noise_scheduler
 
 
 
 
 
 
 
 
72
 
73
+ class main():
74
+ def __init__(self):
75
+ super(main, self).__init__()
76
+
77
+ device = "cuda"
78
+ mean = torch.load(f"{models_path}/files/mean.pt", map_location=torch.device('cpu')).bfloat16().to(device)
79
+ std = torch.load(f"{models_path}/files/std.pt", map_location=torch.device('cpu')).bfloat16().to(device)
80
+ v = torch.load(f"{models_path}/files/V.pt", map_location=torch.device('cpu')).bfloat16().to(device)
81
+ proj = torch.load(f"{models_path}/files/proj_1000pc.pt", map_location=torch.device('cpu')).bfloat16().to(device)
82
+ df = torch.load(f"{models_path}/files/identity_df.pt")
83
+ weight_dimensions = torch.load(f"{models_path}/files/weight_dimensions.pt")
84
+ pinverse = torch.load(f"{models_path}/files/pinverse_1000pc.pt", map_location=torch.device('cpu')).bfloat16().to(device)
85
+
86
+ self.device = device
87
+ self.mean = mean
88
+ self.std = std
89
+ self.v = v
90
+ self.proj = proj
91
+ self.df = df
92
+ self.weight_dimensions = weight_dimensions
93
+ self.pinverse = pinverse
94
+
95
+ self.unet, self.vae, self.text_encoder, self.tokenizer, self.noise_scheduler = load_models(self.device)
96
+ print(self.text_encoder.device)
97
+ self.network = None
98
 
99
+ young = get_direction(df, "Young", pinverse, 1000, device)
100
+ young = debias(young, "Male", df, pinverse, device)
101
+ young = debias(young, "Pointy_Nose", df, pinverse, device)
102
+ young = debias(young, "Wavy_Hair", df, pinverse, device)
103
+ young = debias(young, "Chubby", df, pinverse, device)
104
+ young = debias(young, "No_Beard", df, pinverse, device)
105
+ young = debias(young, "Mustache", df, pinverse, device)
106
+ self.young = young
107
+
108
+ pointy = get_direction(df, "Pointy_Nose", pinverse, 1000, device)
109
+ pointy = debias(pointy, "Young", df, pinverse, device)
110
+ pointy = debias(pointy, "Male", df, pinverse, device)
111
+ pointy = debias(pointy, "Wavy_Hair", df, pinverse, device)
112
+ pointy = debias(pointy, "Chubby", df, pinverse, device)
113
+ pointy = debias(pointy, "Heavy_Makeup", df, pinverse, device)
114
+ self.pointy = pointy
115
+
116
+ wavy = get_direction(df, "Wavy_Hair", pinverse, 1000, device)
117
+ wavy = debias(wavy, "Young", df, pinverse, device)
118
+ wavy = debias(wavy, "Male", df, pinverse, device)
119
+ wavy = debias(wavy, "Pointy_Nose", df, pinverse, device)
120
+ wavy = debias(wavy, "Chubby", df, pinverse, device)
121
+ wavy = debias(wavy, "Heavy_Makeup", df, pinverse, device)
122
+ self.wavy = wavy
123
+
124
+
125
+ thick = get_direction(df, "Bushy_Eyebrows", pinverse, 1000, device)
126
+ thick = debias(thick, "Male", df, pinverse, device)
127
+ thick = debias(thick, "Young", df, pinverse, device)
128
+ thick = debias(thick, "Pointy_Nose", df, pinverse, device)
129
+ thick = debias(thick, "Wavy_Hair", df, pinverse, device)
130
+ thick = debias(thick, "Mustache", df, pinverse, device)
131
+ thick = debias(thick, "No_Beard", df, pinverse, device)
132
+ thick = debias(thick, "Sideburns", df, pinverse, device)
133
+ thick = debias(thick, "Big_Nose", df, pinverse, device)
134
+ thick = debias(thick, "Big_Lips", df, pinverse, device)
135
+ thick = debias(thick, "Black_Hair", df, pinverse, device)
136
+ thick = debias(thick, "Brown_Hair", df, pinverse, device)
137
+ thick = debias(thick, "Pale_Skin", df, pinverse, device)
138
+ thick = debias(thick, "Heavy_Makeup", df, pinverse, device)
139
+ self.thick = thick
140
+
141
+
142
+
143
+ def sample_model(self):
144
+ self.unet, _, _, _, _ = load_models(self.device)
145
+ self.network = sample_weights(self.unet, self.proj, self.mean, self.std, self.v[:, :1000], self.device, factor = 1.00)
146
+
147
 
148
+ @torch.no_grad()
149
+ @spaces.GPU
150
+ def inference(self, prompt, negative_prompt, guidance_scale, ddim_steps, seed):
151
+ device = self.device
152
+ generator = torch.Generator(device=device).manual_seed(seed)
153
+ latents = torch.randn(
154
+ (1, self.unet.in_channels, 512 // 8, 512 // 8),
155
+ generator = generator,
156
+ device = self.device
157
+ ).bfloat16()
158
+
159
+
160
+ text_input = self.tokenizer(prompt, padding="max_length", max_length=self.tokenizer.model_max_length, truncation=True, return_tensors="pt")
161
+
162
+ text_embeddings = self.text_encoder(text_input.input_ids.to(device))[0]
163
+
164
+ max_length = text_input.input_ids.shape[-1]
165
+ uncond_input = self.tokenizer(
166
+ [negative_prompt], padding="max_length", max_length=max_length, return_tensors="pt"
167
+ )
168
+ uncond_embeddings = self.text_encoder(uncond_input.input_ids.to(device))[0]
169
+ text_embeddings = torch.cat([uncond_embeddings, text_embeddings])
170
+ self.noise_scheduler.set_timesteps(ddim_steps)
171
+ latents = latents * self.noise_scheduler.init_noise_sigma
172
+
173
+ for i,t in enumerate(tqdm.tqdm(self.noise_scheduler.timesteps)):
174
+ latent_model_input = torch.cat([latents] * 2)
175
+ latent_model_input = self.noise_scheduler.scale_model_input(latent_model_input, timestep=t)
176
+ with self.network:
177
+ noise_pred = self.unet(latent_model_input, t, encoder_hidden_states=text_embeddings, timestep_cond= None).sample
178
+ #guidance
179
+ noise_pred_uncond, noise_pred_text = noise_pred.chunk(2)
180
+ noise_pred = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond)
181
+ latents = noise_scheduler.step(noise_pred, t, latents).prev_sample
182
 
183
+ latents = 1 / 0.18215 * latents
184
+ image = self.vae.decode(latents).sample
185
+ image = (image / 2 + 0.5).clamp(0, 1)
186
+ image = image.detach().cpu().float().permute(0, 2, 3, 1).numpy()[0]
187
+
188
+ image = Image.fromarray((image * 255).round().astype("uint8"))
189
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
190
  return image
191
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
192
 
193
+ @torch.no_grad()
194
+ @spaces.GPU
195
+ def edit_inference(self, prompt, negative_prompt, guidance_scale, ddim_steps, seed, start_noise, a1, a2, a3, a4):
196
+ device = self.device
197
+ original_weights = self,network.proj.clone()
198
+
199
+ #pad to same number of PCs
200
+ pcs_original = original_weights.shape[1]
201
+ pcs_edits = self.young.shape[1]
202
+ padding = torch.zeros((1,pcs_original-pcs_edits)).to(device)
203
+ young_pad = torch.cat((self.young, padding), 1)
204
+ pointy_pad = torch.cat((self.pointy, padding), 1)
205
+ wavy_pad = torch.cat((self.wavy, padding), 1)
206
+ thick_pad = torch.cat((self.thick, padding), 1)
207
+
208
+
209
+ edited_weights = original_weights+a1*1e6*young_pad+a2*1e6*pointy_pad+a3*1e6*wavy_pad+a4*2e6*thick_pad
210
+
211
+ generator = torch.Generator(device=device).manual_seed(seed)
212
+ latents = torch.randn(
213
+ (1, self.unet.in_channels, 512 // 8, 512 // 8),
214
+ generator = generator,
215
+ device = self.device
216
+ ).bfloat16()
217
+
218
+
219
+ text_input = self.tokenizer(prompt, padding="max_length", max_length=self.tokenizer.model_max_length, truncation=True, return_tensors="pt")
220
+
221
+ text_embeddings = text_encoder(text_input.input_ids.to(device))[0]
222
+
223
+ max_length = text_input.input_ids.shape[-1]
224
+ uncond_input = tokenizer(
225
+ [negative_prompt], padding="max_length", max_length=max_length, return_tensors="pt"
226
+ )
227
+ uncond_embeddings = text_encoder(uncond_input.input_ids.to(device))[0]
228
+ text_embeddings = torch.cat([uncond_embeddings, text_embeddings])
229
+ noise_scheduler.set_timesteps(ddim_steps)
230
+ latents = latents * noise_scheduler.init_noise_sigma
231
+
232
+
233
 
234
+ for i,t in enumerate(tqdm.tqdm(self.noise_scheduler.timesteps)):
235
+ latent_model_input = torch.cat([latents] * 2)
236
+ latent_model_input = self.noise_scheduler.scale_model_input(latent_model_input, timestep=t)
237
+
238
+ if t>start_noise:
239
+ pass
240
+ elif t<=start_noise:
241
+ self.network.proj = torch.nn.Parameter(edited_weights)
242
+ self.network.reset()
243
+
244
+
245
+ with self.network:
246
+ noise_pred = self.unet(latent_model_input, t, encoder_hidden_states=text_embeddings, timestep_cond= None).sample
247
+
248
+
249
+ #guidance
250
+ noise_pred_uncond, noise_pred_text = noise_pred.chunk(2)
251
+ noise_pred = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond)
252
+ latents = noise_scheduler.step(noise_pred, t, latents).prev_sample
253
+
254
+ latents = 1 / 0.18215 * latents
255
+ image = self.vae.decode(latents).sample
256
+ image = (image / 2 + 0.5).clamp(0, 1)
257
+
258
+ image = image.detach().cpu().float().permute(0, 2, 3, 1).numpy()[0]
259
+
260
+ image = Image.fromarray((image * 255).round().astype("uint8"))
261
+
262
+ #reset weights back to original
263
+ self.network.proj = torch.nn.Parameter(original_weights)
264
+ self.network.reset()
265
+
266
+ return image
267
 
268
+ @spaces.GPU
269
+ def sample_then_run(self):
270
+ self.sample_model()
271
+ prompt = "sks person"
272
+ negative_prompt = "low quality, blurry, unfinished, nudity, weapon"
273
+ seed = 5
274
+ cfg = 3.0
275
+ steps = 25
276
+ image = self.inference( prompt, negative_prompt, cfg, steps, seed)
277
+ torch.save(self.network.proj, "model.pt" )
278
+ return image, "model.pt"
279
 
280
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
281
 
282
+ class CustomImageDataset(Dataset):
283
+ def __init__(self, images, transform=None):
284
+ self.images = images
285
+ self.transform = transform
286
+
287
+ def __len__(self):
288
+ return len(self.images)
289
+
290
+ def __getitem__(self, idx):
291
+ image = self.images[idx]
292
+ if self.transform:
293
+ image = self.transform(image)
294
+ return image
295
+
296
+ @spaces.GPU
297
+ def invert(self, image, mask, pcs=10000, epochs=400, weight_decay = 1e-10, lr=1e-1):
298
+
299
+ del unet
300
+ del network
301
+ unet, _, _, _, _ = load_models(device)
302
+
303
+ proj = torch.zeros(1,pcs).bfloat16().to(device)
304
+ network = LoRAw2w( proj, mean, std, v[:, :pcs],
305
+ unet,
306
+ rank=1,
307
+ multiplier=1.0,
308
+ alpha=27.0,
309
+ train_method="xattn-strict"
310
+ ).to(device, torch.bfloat16)
311
 
312
+ ### load mask
313
+ mask = transforms.Resize((64,64), interpolation=transforms.InterpolationMode.BILINEAR)(mask)
314
+ mask = torchvision.transforms.functional.pil_to_tensor(mask).unsqueeze(0).to(device).bfloat16()[:,0,:,:].unsqueeze(1)
315
+ ### check if an actual mask was draw, otherwise mask is just all ones
316
+ if torch.sum(mask) == 0:
317
+ mask = torch.ones((1,1,64,64)).to(device).bfloat16()
318
+
319
+ ### single image dataset
320
+ image_transforms = transforms.Compose([transforms.Resize(512, interpolation=transforms.InterpolationMode.BILINEAR),
321
+ transforms.RandomCrop(512),
322
+ transforms.ToTensor(),
323
+ transforms.Normalize([0.5], [0.5])])
324
+
325
+
326
+ train_dataset = CustomImageDataset(image, transform=image_transforms)
327
+ train_dataloader = torch.utils.data.DataLoader(train_dataset, batch_size=1, shuffle=True)
328
+
329
+ ### optimizer
330
+ optim = torch.optim.Adam(network.parameters(), lr=lr, weight_decay=weight_decay)
331
+
332
+ ### training loop
333
+ unet.train()
334
+ for epoch in tqdm.tqdm(range(epochs)):
335
+ for batch in train_dataloader:
336
+ ### prepare inputs
337
+ batch = batch.to(device).bfloat16()
338
+ latents = vae.encode(batch).latent_dist.sample()
339
+ latents = latents*0.18215
340
+ noise = torch.randn_like(latents)
341
+ bsz = latents.shape[0]
342
+
343
+ timesteps = torch.randint(0, noise_scheduler.config.num_train_timesteps, (bsz,), device=latents.device)
344
+ timesteps = timesteps.long()
345
+ noisy_latents = noise_scheduler.add_noise(latents, noise, timesteps)
346
+ text_input = tokenizer("sks person", padding="max_length", max_length=tokenizer.model_max_length, truncation=True, return_tensors="pt")
347
+ text_embeddings = text_encoder(text_input.input_ids.to(device))[0]
348
+
349
+ ### loss + sgd step
350
+ with network:
351
+ model_pred = unet(noisy_latents, timesteps, text_embeddings).sample
352
+ loss = torch.nn.functional.mse_loss(mask*model_pred.float(), mask*noise.float(), reduction="mean")
353
+ optim.zero_grad()
354
+ loss.backward()
355
+ optim.step()
356
+
357
+ ### return optimized network
358
+ return network
359
 
360
 
361
+ @spaces.GPU
362
+ def run_inversion(self, dict, pcs, epochs, weight_decay,lr):
363
+ init_image = dict["image"].convert("RGB").resize((512, 512))
364
+ mask = dict["mask"].convert("RGB").resize((512, 512))
365
+ network = invert([init_image], mask, pcs, epochs, weight_decay,lr)
366
+
 
367
 
368
+ #sample an image
369
+ prompt = "sks person"
370
+ negative_prompt = "low quality, blurry, unfinished, nudity"
371
+ seed = 5
372
+ cfg = 3.0
373
+ steps = 25
374
+ image = inference( prompt, negative_prompt, cfg, steps, seed)
375
+ torch.save(network.proj, "model.pt" )
376
+ return image, "model.pt"
377
 
378
+
379
+ @spaces.GPU
380
+ def file_upload(self, file):
381
+
382
+ proj = torch.load(file.name).to(device)
383
+
384
+ #pad to 10000 Principal components to keep everything consistent
385
+ pcs = proj.shape[1]
386
+ padding = torch.zeros((1,10000-pcs)).to(device)
387
+ proj = torch.cat((proj, padding), 1)
388
+
389
+ unet, _, _, _, _ = load_models(device)
390
+
391
+
392
+ network = LoRAw2w( proj, mean, std, v[:, :10000],
393
+ unet,
394
+ rank=1,
395
+ multiplier=1.0,
396
+ alpha=27.0,
397
+ train_method="xattn-strict"
398
+ ).to(device, torch.bfloat16)
399
+
400
+
401
+ prompt = "sks person"
402
+ negative_prompt = "low quality, blurry, unfinished, nudity"
403
+ seed = 5
404
+ cfg = 3.0
405
+ steps = 25
406
+ image = inference( prompt, negative_prompt, cfg, steps, seed)
407
+ return image
408
 
409
 
410
 
411
 
412
  intro = """
413
  <div style="display: flex;align-items: center;justify-content: center">
414
+ <h1 style="margin-left: 12px;text-align: center;margin-bottom: 7px;display: inline-block"><em>weights2weights</em> Demo</h1>
415
+ <h3 style="display: inline-block;margin-left: 10px;margin-top: 6px;font-weight: 500">Interpreting the Weight Space of Customized Diffusion Models</h3>
416
+ </div>
417
+ <p style="font-size: 0.95rem;margin: 0rem;line-height: 1.2em;margin-top:1em;display: inline-block">
418
+ <a href="https://snap-research.github.io/weights2weights/" target="_blank">Project Page</a> | <a href="https://arxiv.org/abs/2406.09413" target="_blank">Paper</a>
419
+ | <a href="https://github.com/snap-research/weights2weights" target="_blank">Code</a> |
420
+ <a href="https://huggingface.co/spaces/Snapchat/w2w-demo?duplicate=true" target="_blank" style="
421
+ display: inline-block;
422
+ ">
423
+ <img style="margin-top: -1em;margin-bottom: 0em;position: absolute;" src="https://bit.ly/3CWLGkA" alt="Duplicate Space"></a>
424
+ </p>
425
+ """
 
 
 
 
 
 
 
 
 
 
 
426
 
427
+
428
+
429
+ with gr.Blocks(css="style.css") as demo:
430
+ model = main()
431
  gr.HTML(intro)
432
+
433
  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.""")
434
  with gr.Column():
435
  with gr.Row():
 
437
  gr.Markdown("""1) Either sample a new model, or upload an image (optionally draw a mask over the head) and click `invert`.""")
438
  sample = gr.Button("🎲 Sample New Model")
439
  input_image = gr.ImageEditor(elem_id="image_upload", type='pil', label="Reference Identity",
440
+ width=512, height=512)
441
+
442
  with gr.Row():
443
  invert_button = gr.Button("⬆️ Invert")
444
+
445
+
446
+
447
  with gr.Column():
448
  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.""")
449
  gallery = gr.Image(label="Generated Image",height=512, width=512, interactive=False)
450
  submit = gr.Button("Generate")
451
+
452
+
453
  prompt = gr.Textbox(label="Prompt",
454
+ info="Make sure to include 'sks person'" ,
455
+ placeholder="sks person",
456
+ value="sks person")
 
 
457
 
458
+ seed = gr.Number(value=5, label="Seed", precision=0, interactive=True)
459
+
460
  # Editing
461
  with gr.Column():
462
  with gr.Row():
 
465
  with gr.Row():
466
  a3 = gr.Slider(label="- Curly Hair +", value=0, step=0.001, minimum=-1, maximum=1, interactive=True)
467
  a4 = gr.Slider(label="- Thick Eyebrows +", value=0, step=0.001, minimum=-1, maximum=1, interactive=True)
468
+
469
+
470
  with gr.Accordion("Advanced Options", open=False):
471
  with gr.Tab("Inversion"):
472
  with gr.Row():
 
477
  weight_decay = gr.Number(value=1e-10, label="Weight Decay", interactive=True)
478
  with gr.Tab("Sampling"):
479
  with gr.Row():
480
+ cfg= gr.Slider(label="CFG", value=3.0, step=0.1, minimum=0, maximum=10, interactive=True)
481
+ steps = gr.Slider(label="Inference Steps", value=25, step=1, minimum=0, maximum=100, interactive=True)
482
  with gr.Row():
483
+ negative_prompt = gr.Textbox(label="Negative Prompt", placeholder="low quality, blurry, unfinished, nudity, weapon", value="low quality, blurry, unfinished, nudity, weapon")
484
+ injection_step = gr.Slider(label="Injection Step", value=800, step=1, minimum=0, maximum=1000, interactive=True)
485
+
486
  with gr.Tab("Uploading a model"):
487
  gr.Markdown("""<div style="text-align: justify;">Upload a model below downloaded from this demo.""")
488
+
489
  file_input = gr.File(label="Upload Model", container=True)
490
+
491
+
492
+
493
+
494
  gr.Markdown("""<div style="text-align: justify;"> After sampling a new model or inverting, you can download the model below.""")
495
+
496
  with gr.Row():
497
  file_output = gr.File(label="Download Sampled/Inverted Model", container=True, interactive=False)
 
 
 
 
 
 
 
 
498
 
499
+
500
+
501
+
502
+ invert_button.click(fn=model.run_inversion,
503
+ inputs=[input_image, pcs, epochs, weight_decay,lr],
504
+ outputs = [input_image, file_output])
505
+
506
+
507
+ sample.click(fn=model.sample_then_run, outputs=[input_image, file_output])
508
+
509
  submit.click(
510
+ fn=model.edit_inference, inputs=[prompt, negative_prompt, cfg, steps, seed, injection_step, a1, a2, a3, a4], outputs=[gallery]
511
+ )
512
+ file_input.change(fn=model.file_upload, inputs=file_input, outputs = gallery)
513
+
514
+
515
+
516
  help_text1 = """
517
+ <b>Instructions</b>:
518
+ 1. To get results faster without waiting in queue, you can duplicate into a private space with an A100 GPU.
519
+ 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`.
520
+ 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.
521
+ 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.
522
+ """
523
  help_text2 = """<b>Tips</b>:
524
+ 1. Editing and Identity Generation
525
+ * 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.
526
+ * 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.
527
+ * Sometimes the identity will not be perfectly consistent (e.g., there might be small variations of the face) when you use some seeds or prompts. This is a limitation of our method as well as an open-problem in personalized models.
528
+ 2. Inversion
529
+ * To obtain the best results for inversion, upload a high resolution photo of the face with minimal occlusion. It is recommended to draw over the face and hair to define a mask. But inversion should still work generally for non-closeup face shots.
530
+ * For inverting a realistic photo of an identity, typically 800 epochs with lr=1e-1 and 10,000 principal components (PCs) works well. If the resulting generations have artifacted and unrealstic textures, there is probably overfitting and you may want to reduce the number of epochs or learning rate, or play with weight decay. If the generations do not look like the input photo, then you may want to increase the number of epochs.
531
+ * For inverting out-of-distribution identities, such as artistic renditions of people or non-humans (e.g. the ones shown in the paper), it is recommended to use 1000 PCs, lr=1, and train for 800 epochs.
532
+ * 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."""
 
533
 
534
+
535
  gr.Markdown(help_text1)
536
  gr.Markdown(help_text2)
537
+
538
  demo.queue().launch()
539
+
540
+
541
+