File size: 26,917 Bytes
2cd4b2a
c15417b
 
 
 
eb710fe
 
 
 
 
 
 
 
86ffd66
dfca074
c15417b
eb710fe
3b7acd7
cfbf1bf
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6b24bcd
 
0e00c55
 
 
 
 
 
6b24bcd
fb01019
 
 
 
 
 
cb1cf1b
 
0e00c55
fb01019
0e00c55
cb1cf1b
 
0e00c55
cb1cf1b
 
0e00c55
 
cb1cf1b
 
 
0e00c55
 
 
cb1cf1b
0e00c55
 
 
 
fb01019
cb1cf1b
 
cfbf1bf
86ffd66
6b24bcd
0e00c55
 
fb01019
31081a5
 
76ee786
ac24ff3
0d54165
 
 
 
31081a5
 
0d54165
31081a5
 
95ecabf
 
ad7da82
 
 
 
 
 
95ecabf
 
67785ac
ad7da82
 
 
 
 
95ecabf
 
 
ad7da82
 
 
 
 
 
95ecabf
 
ad7da82
 
 
 
 
 
 
 
 
 
 
 
 
 
4ef9ffa
cfbf1bf
 
 
 
4ef9ffa
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d2b8415
d4bfcab
31081a5
0bc198e
 
 
 
 
c921f7a
31081a5
 
945f95c
31081a5
ad7da82
 
31081a5
6983a05
31081a5
ad7da82
31081a5
 
945f95c
ad7da82
945f95c
6b4a672
31081a5
 
ad7da82
31081a5
 
6b4a672
31081a5
ad7da82
 
31081a5
ad7da82
31081a5
ad7da82
 
 
31081a5
 
 
cf8bccb
31081a5
 
ad7da82
31081a5
 
 
 
 
 
 
 
 
 
 
67ad71c
ad7da82
 
31081a5
 
 
ad7da82
6b4a672
ad7da82
 
 
 
76ee786
31081a5
 
 
ad7da82
31081a5
6983a05
31081a5
ad7da82
31081a5
 
 
ad7da82
31081a5
6b4a672
31081a5
 
ad7da82
31081a5
 
6b4a672
31081a5
ad7da82
 
76ee786
31081a5
a020647
ad7da82
31081a5
ad7da82
31081a5
 
 
 
ad7da82
 
31081a5
 
 
ad7da82
76ee786
 
31081a5
 
 
ad7da82
31081a5
 
ad7da82
31081a5
 
 
 
 
 
 
ad7da82
 
31081a5
 
d2b8415
 
31081a5
 
 
 
 
 
 
 
 
79d99bd
9145fad
0ea3a05
94c4f9d
0ea3a05
31081a5
 
 
 
 
 
 
 
 
 
 
 
 
 
9935195
3b7acd7
31081a5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c15417b
31081a5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
76ee786
31081a5
 
 
 
 
aa1da5e
31081a5
 
 
 
 
 
 
aa1da5e
31081a5
 
c15417b
86ffd66
31081a5
 
 
 
 
 
621123f
 
31081a5
 
 
 
 
 
 
 
 
f15739b
 
31081a5
 
 
 
 
 
 
f15739b
 
31081a5
 
 
 
 
 
39eeaaf
31081a5
 
 
 
 
 
 
 
 
 
 
f15739b
31081a5
 
 
 
 
 
 
f15739b
 
31081a5
f15739b
31081a5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
76ee786
 
31081a5
76ee786
 
 
 
 
 
 
31081a5
 
76ee786
 
31081a5
 
 
76ee786
 
 
 
31081a5
 
76ee786
31081a5
 
 
 
76ee786
31081a5
76ee786
 
 
 
 
 
 
 
31081a5
 
76ee786
 
 
 
 
 
 
 
 
 
31081a5
 
76ee786
31081a5
 
 
76ee786
 
31081a5
76ee786
31081a5
 
 
 
76ee786
31081a5
76ee786
 
31081a5
 
 
 
 
 
 
 
f15739b
66f443f
31081a5
76ee786
31081a5
 
 
 
 
 
76ee786
31081a5
 
 
 
 
 
76ee786
31081a5
 
 
 
 
 
 
 
 
 
621123f
76ee786
 
31081a5
76ee786
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
import os
import torch
import torchvision
import torchvision.transforms as transforms
from torch.utils.data import Dataset, DataLoader
import gradio as gr
import sys
import tqdm
sys.path.append(os.path.abspath(os.path.join("", "..")))
import gc
import warnings
warnings.filterwarnings("ignore")
from PIL import Image
import numpy as np
from editing import get_direction, debias
from lora_w2w import LoRAw2w
from huggingface_hub import snapshot_download
import spaces
from transformers import CLIPTextModel
from lora_w2w import LoRAw2w
from diffusers import AutoencoderKL, DDPMScheduler, DiffusionPipeline, UNet2DConditionModel, LMSDiscreteScheduler
from transformers import AutoTokenizer, PretrainedConfig
import warnings
warnings.filterwarnings("ignore")
from diffusers import (
    AutoencoderKL,
    DDPMScheduler,
    DiffusionPipeline,
    DPMSolverMultistepScheduler,
    UNet2DConditionModel,
    PNDMScheduler, 
    StableDiffusionPipeline
)


device = gr.State("cuda")
unet = gr.State()
vae = gr.State()
text_encoder = gr.State()
tokenizer = gr.State()
noise_scheduler = gr.State()
network = gr.State()

pretrained_model_name_or_path = "stablediffusionapi/realistic-vision-v51" 
revision = None
rank = 1
weight_dtype = torch.bfloat16
# Load scheduler, tokenizer and models.
pipe = StableDiffusionPipeline.from_pretrained("stablediffusionapi/realistic-vision-v51", 
                                            torch_dtype=torch.float16,safety_checker = None,
                                            requires_safety_checker = False).to(device.value)
noise_scheduler.value = pipe.scheduler
del pipe
tokenizer.value = AutoTokenizer.from_pretrained(
        pretrained_model_name_or_path, subfolder="tokenizer", revision=revision
    )
text_encoder.value = CLIPTextModel.from_pretrained(
        pretrained_model_name_or_path, subfolder="text_encoder", revision=revision
    )
vae.value = AutoencoderKL.from_pretrained(pretrained_model_name_or_path, subfolder="vae", revision=revision)
unet.value = UNet2DConditionModel.from_pretrained(
        pretrained_model_name_or_path, subfolder="unet", revision=revision
    )

unet.value.requires_grad_(False)
unet.value.to(device.value, dtype=weight_dtype)
vae.value.requires_grad_(False)

text_encoder.value.requires_grad_(False)
vae.value.requires_grad_(False)
vae.value.to(device.value, dtype=weight_dtype)
text_encoder.value.to(device.value, dtype=weight_dtype)
print("")










models_path = snapshot_download(repo_id="Snapchat/w2w")

mean = torch.load(f"{models_path}/files/mean.pt", map_location=torch.device('cpu')).bfloat16().to(device.value)
std = torch.load(f"{models_path}/files/std.pt", map_location=torch.device('cpu')).bfloat16().to(device.value)
v = torch.load(f"{models_path}/files/V.pt", map_location=torch.device('cpu')).bfloat16().to(device.value)
proj = torch.load(f"{models_path}/files/proj_1000pc.pt", map_location=torch.device('cpu')).bfloat16().to(device.value)
df = torch.load(f"{models_path}/files/identity_df.pt")
weight_dimensions = torch.load(f"{models_path}/files/weight_dimensions.pt")
pinverse = torch.load(f"{models_path}/files/pinverse_1000pc.pt", map_location=torch.device('cpu')).bfloat16().to(device.value)


young = gr.State()
young.value = get_direction(df, "Young", pinverse, 1000, device.value)
young.value = debias(young.value, "Male", df, pinverse, device.value)
young.value = debias(young.value, "Pointy_Nose", df, pinverse, device.value)
young.value = debias(young.value, "Wavy_Hair", df, pinverse, device.value)
young.value = debias(young.value, "Chubby", df, pinverse, device.value)
young.value = debias(young.value, "No_Beard", df, pinverse, device.value)
young.value = debias(young.value, "Mustache", df, pinverse, device.value)

pointy = gr.State()
pointy.value = get_direction(df, "Pointy_Nose", pinverse, 1000, device.value)
pointy.value = debias(pointy.value, "Young", df, pinverse, device.value)
pointy.value = debias(pointy.value, "Male", df, pinverse, device.value)
pointy.value = debias(pointy.value, "Wavy_Hair", df, pinverse, device.value)
pointy.value = debias(pointy.value, "Chubby", df, pinverse, device.value)
pointy.value = debias(pointy.value, "Heavy_Makeup", df, pinverse, device.value)

wavy = gr.State()
wavy.value = get_direction(df, "Wavy_Hair", pinverse, 1000, device.value)
wavy.value = debias(wavy.value, "Young", df, pinverse, device.value)
wavy.value = debias(wavy.value, "Male", df, pinverse, device.value)
wavy.value = debias(wavy.value, "Pointy_Nose", df, pinverse, device.value)
wavy.value = debias(wavy.value, "Chubby", df, pinverse, device.value)
wavy.value = debias(wavy.value, "Heavy_Makeup", df, pinverse, device.value)

thick = gr.State()
thick.value = get_direction(df, "Bushy_Eyebrows", pinverse, 1000, device.value)
thick.value = debias(thick.value, "Male", df, pinverse, device.value)
thick.value = debias(thick.value, "Young", df, pinverse, device.value)
thick.value = debias(thick.value, "Pointy_Nose", df, pinverse, device.value)
thick.value = debias(thick.value, "Wavy_Hair", df, pinverse, device.value)
thick.value = debias(thick.value, "Mustache", df, pinverse, device.value)
thick.value = debias(thick.value, "No_Beard", df, pinverse, device.value)
thick.value = debias(thick.value, "Sideburns", df, pinverse, device.value)
thick.value = debias(thick.value, "Big_Nose", df, pinverse, device.value)
thick.value = debias(thick.value, "Big_Lips", df, pinverse, device.value)
thick.value = debias(thick.value, "Black_Hair", df, pinverse, device.value)
thick.value = debias(thick.value, "Brown_Hair", df, pinverse, device.value)
thick.value = debias(thick.value, "Pale_Skin", df, pinverse, device.value)
thick.value = debias(thick.value, "Heavy_Makeup", df, pinverse, device.value)






@torch.no_grad()
@spaces.GPU
def sample_weights(unet, proj, mean, std, v, device, factor = 1.0): 
    # get mean and standard deviation for each principal component
    m = torch.mean(proj, 0)
    standev = torch.std(proj, 0)
    del proj
    torch.cuda.empty_cache()
    # sample
    sample = torch.zeros([1, 1000]).to(device)
    for i in range(1000):
        sample[0, i] = torch.normal(m[i], factor*standev[i], (1,1))

    # load weights into network
    net = LoRAw2w( sample, mean, std, v, 
                    unet,
                    rank=1,
                    multiplier=1.0,
                    alpha=27.0,
                    train_method="xattn-strict"
                ).to(device, torch.bfloat16)
        
    return net

@torch.no_grad()
@spaces.GPU
def sample_model():
    unet.value = UNet2DConditionModel.from_pretrained(
        pretrained_model_name_or_path, subfolder="unet", revision=revision
    )
    unet.value.requires_grad_(False)
    unet.value.to(device.value, dtype=weight_dtype)
    network.value = sample_weights(unet.value, proj, mean, std, v[:, :1000], device.value, factor = 1.00)
 
@torch.no_grad()
@spaces.GPU
def inference( prompt, negative_prompt, guidance_scale, ddim_steps, seed):
    
    generator = torch.Generator(device=device.value).manual_seed(seed)
    latents = torch.randn(
        (1, unet.value.in_channels, 512 // 8, 512 // 8),
        generator = generator,
        device = device.value
    ).bfloat16()
   

    text_input = tokenizer.value(prompt, padding="max_length", max_length=tokenizer.value.model_max_length, truncation=True, return_tensors="pt")

    text_embeddings = text_encoder.value(text_input.input_ids.to(device.value))[0]

    max_length = text_input.input_ids.shape[-1]
    uncond_input = tokenizer.value(
                            [negative_prompt], padding="max_length", max_length=max_length, return_tensors="pt"
                        )
    uncond_embeddings = text_encoder.value(uncond_input.input_ids.to(device.value))[0]
    text_embeddings = torch.cat([uncond_embeddings, text_embeddings])
    noise_scheduler.value.set_timesteps(ddim_steps) 
    latents = latents * noise_scheduler.value.init_noise_sigma
    
    for i,t in enumerate(tqdm.tqdm(noise_scheduler.value.timesteps)):
        latent_model_input = torch.cat([latents] * 2)
        latent_model_input = noise_scheduler.value.scale_model_input(latent_model_input, timestep=t)
        with network.value:
            noise_pred = unet.value(latent_model_input, t, encoder_hidden_states=text_embeddings, timestep_cond= None).sample
        #guidance
        noise_pred_uncond, noise_pred_text = noise_pred.chunk(2)
        noise_pred = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond)
        latents = noise_scheduler.value.step(noise_pred, t, latents).prev_sample
    
    latents = 1 / 0.18215 * latents
    image = vae.value.decode(latents).sample
    image = (image / 2 + 0.5).clamp(0, 1)
    image = image.detach().cpu().float().permute(0, 2, 3, 1).numpy()[0]

    image = Image.fromarray((image * 255).round().astype("uint8"))

    return image


@torch.no_grad()
@spaces.GPU
def edit_inference(prompt, negative_prompt, guidance_scale, ddim_steps, seed, start_noise, a1, a2, a3, a4):
    
   
    original_weights = network.value.proj.clone()
    
    #pad to same number of PCs
    pcs_original = original_weights.shape[1]
    pcs_edits = young.value.shape[1]
    padding =  torch.zeros((1,pcs_original-pcs_edits)).to(device.value)
    young_pad = torch.cat((young.value, padding), 1)
    pointy_pad = torch.cat((pointy.value, padding), 1)
    wavy_pad = torch.cat((wavy.value, padding), 1)
    thick_pad = torch.cat((thick.value, padding), 1)
    

    edited_weights = original_weights+a1*1e6*young_pad+a2*1e6*pointy_pad+a3*1e6*wavy_pad+a4*2e6*thick_pad
   
    generator = torch.Generator(device=device.value).manual_seed(seed)
    latents = torch.randn(
        (1, unet.value.in_channels, 512 // 8, 512 // 8),
        generator = generator,
        device = device.value
    ).bfloat16()
   

    text_input = tokenizer.value(prompt, padding="max_length", max_length=tokenizer.value.model_max_length, truncation=True, return_tensors="pt")

    text_embeddings = text_encoder.value(text_input.input_ids.to(device.value))[0]

    max_length = text_input.input_ids.shape[-1]
    uncond_input = tokenizer.value(
                            [negative_prompt], padding="max_length", max_length=max_length, return_tensors="pt"
                        )
    uncond_embeddings = text_encoder.value(uncond_input.input_ids.to(device.value))[0]
    text_embeddings = torch.cat([uncond_embeddings, text_embeddings])
    noise_scheduler.value.set_timesteps(ddim_steps) 
    latents = latents * noise_scheduler.value.init_noise_sigma
    

 
    for i,t in enumerate(tqdm.tqdm(noise_scheduler.value.timesteps)):
        latent_model_input = torch.cat([latents] * 2)
        latent_model_input = noise_scheduler.value.scale_model_input(latent_model_input, timestep=t)
        
        if t>start_noise:
            pass
        elif t<=start_noise:
            network.value.proj = torch.nn.Parameter(edited_weights)
            network.value.reset()


        with network:
            noise_pred = unet.value(latent_model_input, t, encoder_hidden_states=text_embeddings, timestep_cond= None).sample
            
        
        #guidance
        noise_pred_uncond, noise_pred_text = noise_pred.chunk(2)
        noise_pred = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond)
        latents = noise_scheduler.value.step(noise_pred, t, latents).prev_sample
    
    latents = 1 / 0.18215 * latents
    image = vae.value.decode(latents).sample
    image = (image / 2 + 0.5).clamp(0, 1)

    image = image.detach().cpu().float().permute(0, 2, 3, 1).numpy()[0]

    image = Image.fromarray((image * 255).round().astype("uint8"))

    #reset weights back to original 
    network.value.proj = torch.nn.Parameter(original_weights)
    network.value.reset()

    return image
    
@torch.no_grad()
@spaces.GPU
def sample_then_run():
    sample_model()    
    prompt = "sks person"
    negative_prompt = "low quality, blurry, unfinished, nudity, weapon"
    seed = 5
    cfg = 3.0
    steps = 25
    image = inference( prompt, negative_prompt, cfg, steps, seed)
    torch.save(network.value.proj.detach(), "model.pt" )
    # net = torch.load("model.pt").cpu()
    network.value.proj.detach().cpu()
    
    return image, "model.pt", network.value #net   #, network.value.cpu()


class CustomImageDataset(Dataset):
    def __init__(self, images, transform=None):
        self.images = images
        self.transform = transform

    def __len__(self):
        return len(self.images)

    def __getitem__(self, idx):
        image = self.images[idx]
        if self.transform:
            image = self.transform(image)
        return image

@spaces.GPU
def invert(image, mask, pcs=10000, epochs=400, weight_decay = 1e-10, lr=1e-1):
    global unet
    del unet
    global network
    unet, _, _, _, _ = load_models(device)
    
    proj = torch.zeros(1,pcs).bfloat16().to(device)
    network = LoRAw2w( proj, mean, std, v[:, :pcs], 
                        unet,
                        rank=1,
                        multiplier=1.0,
                        alpha=27.0,
                        train_method="xattn-strict"
                    ).to(device, torch.bfloat16)

    ### load mask
    mask = transforms.Resize((64,64), interpolation=transforms.InterpolationMode.BILINEAR)(mask)
    mask = torchvision.transforms.functional.pil_to_tensor(mask).unsqueeze(0).to(device).bfloat16()[:,0,:,:].unsqueeze(1)
    ### check if an actual mask was draw, otherwise mask is just all ones
    if torch.sum(mask) == 0:
        mask = torch.ones((1,1,64,64)).to(device).bfloat16()
        
    ### single image dataset
    image_transforms = transforms.Compose([transforms.Resize(512, interpolation=transforms.InterpolationMode.BILINEAR),
                                                transforms.RandomCrop(512),
                                                transforms.ToTensor(),
                                                transforms.Normalize([0.5], [0.5])])


    train_dataset = CustomImageDataset(image, transform=image_transforms)
    train_dataloader = torch.utils.data.DataLoader(train_dataset, batch_size=1, shuffle=True) 

    ### optimizer 
    optim = torch.optim.Adam(network.parameters(), lr=lr, weight_decay=weight_decay)    

    ### training loop
    unet.train()
    for epoch in tqdm.tqdm(range(epochs)):
        for batch in train_dataloader:
            ### prepare inputs
            batch = batch.to(device).bfloat16()
            latents = vae.encode(batch).latent_dist.sample()
            latents = latents*0.18215
            noise = torch.randn_like(latents)
            bsz = latents.shape[0]
         
            timesteps = torch.randint(0, noise_scheduler.config.num_train_timesteps, (bsz,), device=latents.device)
            timesteps = timesteps.long()
            noisy_latents = noise_scheduler.add_noise(latents, noise, timesteps)
            text_input = tokenizer("sks person", padding="max_length", max_length=tokenizer.model_max_length, truncation=True, return_tensors="pt")
            text_embeddings = text_encoder(text_input.input_ids.to(device))[0]

            ### loss + sgd step
            with network:
                model_pred = unet(noisy_latents, timesteps, text_embeddings).sample
                loss = torch.nn.functional.mse_loss(mask*model_pred.float(), mask*noise.float(), reduction="mean")
                optim.zero_grad()
                loss.backward()
                optim.step()

    ### return optimized network
    return network


@spaces.GPU
def run_inversion(dict, pcs, epochs, weight_decay,lr):
    global network
    init_image = dict["image"].convert("RGB").resize((512, 512))
    mask = dict["mask"].convert("RGB").resize((512, 512))
    network = invert([init_image], mask, pcs, epochs, weight_decay,lr)


    #sample an image
    prompt = "sks person"
    negative_prompt = "low quality, blurry, unfinished, nudity"
    seed = 5
    cfg = 3.0
    steps = 25
    image = inference( prompt, negative_prompt, cfg, steps, seed)
    torch.save(network.proj, "model.pt" )
    return image, "model.pt"
    
    
@spaces.GPU
def file_upload(file):
    global unet
    del unet
    global network
    global device

    
    
    proj = torch.load(file.name).to(device)

    #pad to 10000 Principal components to keep everything consistent
    pcs = proj.shape[1]
    padding =  torch.zeros((1,10000-pcs)).to(device)
    proj = torch.cat((proj, padding), 1)

    unet, _, _, _, _ = load_models(device)


    network = LoRAw2w( proj, mean, std, v[:, :10000], 
                        unet,
                        rank=1,
                        multiplier=1.0,
                        alpha=27.0,
                        train_method="xattn-strict"
                    ).to(device, torch.bfloat16)
        
    
    prompt = "sks person"
    negative_prompt = "low quality, blurry, unfinished, nudity"
    seed = 5
    cfg = 3.0
    steps = 25
    image = inference( prompt, negative_prompt, cfg, steps, seed)
    return image
    
    

    
intro = """
<div style="display: flex;align-items: center;justify-content: center">
    <h1 style="margin-left: 12px;text-align: center;margin-bottom: 7px;display: inline-block"><em>weights2weights</em> Demo</h1>
    <h3 style="display: inline-block;margin-left: 10px;margin-top: 6px;font-weight: 500">Interpreting the Weight Space of Customized Diffusion Models</h3>
</div>
<p style="font-size: 0.95rem;margin: 0rem;line-height: 1.2em;margin-top:1em;display: inline-block">
    <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>
     |  <a href="https://github.com/snap-research/weights2weights" target="_blank">Code</a> |
    <a href="https://huggingface.co/spaces/Snapchat/w2w-demo?duplicate=true" target="_blank" style="
        display: inline-block;
    ">
    <img style="margin-top: -1em;margin-bottom: 0em;position: absolute;" src="https://bit.ly/3CWLGkA" alt="Duplicate Space"></a>
</p>
"""



with gr.Blocks(css="style.css") as demo:
    gr.HTML(intro)
    
    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.""")
    with gr.Column():
            with gr.Row():
                with gr.Column(): 
                    gr.Markdown("""1) Either sample a new model, or upload an image (optionally draw a mask over the head) and click `invert`.""")
                    sample = gr.Button("🎲 Sample New Model")
                    input_image = gr.ImageEditor(elem_id="image_upload", type='pil', label="Reference Identity",
                                           width=512, height=512)    
                  
                    with gr.Row():
                        invert_button = gr.Button("⬆️ Invert")



                with gr.Column():
                    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.""")
                    gallery = gr.Image(label="Generated Image",height=512, width=512, interactive=False)
                    submit = gr.Button("Generate")

                    
            prompt = gr.Textbox(label="Prompt",
                                            info="Make sure to include 'sks person'" ,
                                            placeholder="sks person", 
                                            value="sks person")
            
            seed = gr.Number(value=5, label="Seed", precision=0, interactive=True)
                
            # Editing 
            with gr.Column():
                with gr.Row():
                    a1 = gr.Slider(label="- Young +", value=0, step=0.001, minimum=-1, maximum=1, interactive=True)
                    a2 = gr.Slider(label="- Pointy Nose +", value=0, step=0.001, minimum=-1, maximum=1, interactive=True)       
                with gr.Row():        
                    a3 = gr.Slider(label="- Curly Hair +", value=0, step=0.001, minimum=-1, maximum=1, interactive=True)
                    a4 = gr.Slider(label="- Thick Eyebrows +", value=0, step=0.001, minimum=-1, maximum=1, interactive=True)

            
            with gr.Accordion("Advanced Options", open=False):
                with gr.Tab("Inversion"):
                    with gr.Row():     
                        lr = gr.Number(value=1e-1, label="Learning Rate", interactive=True)
                        pcs = gr.Slider(label="# Principal Components", value=10000, step=1, minimum=1, maximum=10000, interactive=True)
                    with gr.Row():
                        epochs = gr.Slider(label="Epochs", value=800, step=1, minimum=1, maximum=2000, interactive=True)
                        weight_decay = gr.Number(value=1e-10, label="Weight Decay", interactive=True)
                with gr.Tab("Sampling"):
                    with gr.Row():     
                            cfg= gr.Slider(label="CFG", value=3.0, step=0.1, minimum=0, maximum=10, interactive=True)
                            steps = gr.Slider(label="Inference Steps",  value=25, step=1, minimum=0, maximum=100, interactive=True)
                    with gr.Row():
                            negative_prompt = gr.Textbox(label="Negative Prompt", placeholder="low quality, blurry, unfinished, nudity, weapon", value="low quality, blurry, unfinished, nudity, weapon")
                            injection_step = gr.Slider(label="Injection Step",  value=800, step=1, minimum=0, maximum=1000, interactive=True)
                            
                with gr.Tab("Uploading a model"):
                    gr.Markdown("""<div style="text-align: justify;">Upload a model below downloaded from this demo.""")

                    file_input = gr.File(label="Upload Model", container=True)

     


    gr.Markdown("""<div style="text-align: justify;"> After sampling a new model or inverting, you can download the model below.""")

    with gr.Row():
        file_output = gr.File(label="Download Sampled/Inverted Model", container=True, interactive=False)
        



        invert_button.click(fn=run_inversion,
                    inputs=[input_image, pcs, epochs, weight_decay,lr], 
                    outputs = [input_image, file_output])
        
            
        sample.click(fn=sample_then_run, outputs=[input_image, file_output, network])
        
        submit.click(
            fn=edit_inference, inputs=[prompt, negative_prompt, cfg, steps, seed, injection_step, a1, a2, a3, a4], outputs=[gallery]
        )
        file_input.change(fn=file_upload, inputs=file_input, outputs = gallery)



    help_text1 = """
        <b>Instructions</b>:
        1. To get results faster without waiting in queue, you can duplicate into a private space with an A100 GPU.
        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`.   
        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.
        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. 
        """
    help_text2 = """<b>Tips</b>:
        1. Editing and Identity Generation
            * 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.
            * 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.
            * 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. 
        2. Inversion 
            * 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.
            * 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.
            * 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.
            * 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.""" 
    
        
    gr.Markdown(help_text1)
    gr.Markdown(help_text2)
    #demo.load(fn=start_items)
demo.queue().launch()