Spaces:
Sleeping
Sleeping
gaparmar
commited on
Commit
•
c2c05b2
1
Parent(s):
98322fb
adding source
Browse files- src/__pycache__/image_prep.cpython-310.pyc +0 -0
- src/__pycache__/model.cpython-310.pyc +0 -0
- src/__pycache__/pix2pix_turbo.cpython-310.pyc +0 -0
- src/image_prep.py +12 -0
- src/model.py +13 -0
- src/pix2pix_turbo.py +168 -0
src/__pycache__/image_prep.cpython-310.pyc
ADDED
Binary file (544 Bytes). View file
|
|
src/__pycache__/model.cpython-310.pyc
ADDED
Binary file (699 Bytes). View file
|
|
src/__pycache__/pix2pix_turbo.cpython-310.pyc
ADDED
Binary file (6.84 kB). View file
|
|
src/image_prep.py
ADDED
@@ -0,0 +1,12 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import numpy as np
|
2 |
+
from PIL import Image
|
3 |
+
import cv2
|
4 |
+
|
5 |
+
|
6 |
+
def canny_from_pil(image, low_threshold=100, high_threshold=200):
|
7 |
+
image = np.array(image)
|
8 |
+
image = cv2.Canny(image, low_threshold, high_threshold)
|
9 |
+
image = image[:, :, None]
|
10 |
+
image = np.concatenate([image, image, image], axis=2)
|
11 |
+
control_image = Image.fromarray(image)
|
12 |
+
return control_image
|
src/model.py
ADDED
@@ -0,0 +1,13 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import os, sys, pdb
|
2 |
+
|
3 |
+
import diffusers
|
4 |
+
from transformers import AutoTokenizer, PretrainedConfig
|
5 |
+
from diffusers import AutoencoderKL, UNet2DConditionModel, DDPMScheduler
|
6 |
+
|
7 |
+
|
8 |
+
def make_1step_sched():
|
9 |
+
noise_scheduler = DDPMScheduler.from_pretrained("stabilityai/sd-turbo", subfolder="scheduler")
|
10 |
+
noise_scheduler_1step = DDPMScheduler.from_pretrained("stabilityai/sd-turbo", subfolder="scheduler")
|
11 |
+
noise_scheduler_1step.set_timesteps(1, device="cuda")
|
12 |
+
noise_scheduler_1step.alphas_cumprod = noise_scheduler_1step.alphas_cumprod.cuda()
|
13 |
+
return noise_scheduler_1step
|
src/pix2pix_turbo.py
ADDED
@@ -0,0 +1,168 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import os, requests
|
2 |
+
import pdb
|
3 |
+
import copy
|
4 |
+
from tqdm import tqdm
|
5 |
+
import torch
|
6 |
+
from transformers import AutoTokenizer, PretrainedConfig, CLIPTextModel
|
7 |
+
from diffusers import AutoencoderKL, UNet2DConditionModel, DDPMScheduler
|
8 |
+
from diffusers.utils.peft_utils import set_weights_and_activate_adapters
|
9 |
+
from peft import LoraConfig
|
10 |
+
from .model import make_1step_sched
|
11 |
+
|
12 |
+
|
13 |
+
def my_vae_encoder_fwd(self, sample):
|
14 |
+
r"""The forward method of the `Encoder` class."""
|
15 |
+
sample = self.conv_in(sample)
|
16 |
+
l_blocks = []
|
17 |
+
# down
|
18 |
+
for down_block in self.down_blocks:
|
19 |
+
l_blocks.append(sample)
|
20 |
+
sample = down_block(sample)
|
21 |
+
# middle
|
22 |
+
sample = self.mid_block(sample)
|
23 |
+
sample = self.conv_norm_out(sample)
|
24 |
+
sample = self.conv_act(sample)
|
25 |
+
sample = self.conv_out(sample)
|
26 |
+
self.current_down_blocks = l_blocks
|
27 |
+
return sample
|
28 |
+
|
29 |
+
|
30 |
+
def my_vae_decoder_fwd(self,sample, latent_embeds = None):
|
31 |
+
sample = self.conv_in(sample)
|
32 |
+
upscale_dtype = next(iter(self.up_blocks.parameters())).dtype
|
33 |
+
# middle
|
34 |
+
sample = self.mid_block(sample, latent_embeds)
|
35 |
+
sample = sample.to(upscale_dtype)
|
36 |
+
if not self.ignore_skip:
|
37 |
+
skip_convs = [self.skip_conv_1, self.skip_conv_2, self.skip_conv_3, self.skip_conv_4]
|
38 |
+
# up
|
39 |
+
for idx, up_block in enumerate(self.up_blocks):
|
40 |
+
skip_in = skip_convs[idx](self.incoming_skip_acts[::-1][idx])
|
41 |
+
# add skip
|
42 |
+
sample = sample + skip_in
|
43 |
+
sample = up_block(sample, latent_embeds)
|
44 |
+
else:
|
45 |
+
for idx, up_block in enumerate(self.up_blocks):
|
46 |
+
sample = up_block(sample, latent_embeds)
|
47 |
+
# post-process
|
48 |
+
if latent_embeds is None:
|
49 |
+
sample = self.conv_norm_out(sample)
|
50 |
+
else:
|
51 |
+
sample = self.conv_norm_out(sample, latent_embeds)
|
52 |
+
sample = self.conv_act(sample)
|
53 |
+
sample = self.conv_out(sample)
|
54 |
+
return sample
|
55 |
+
|
56 |
+
|
57 |
+
class TwinConv(torch.nn.Module):
|
58 |
+
def __init__(self, convin_pretrained, convin_curr):
|
59 |
+
super(TwinConv, self).__init__()
|
60 |
+
self.conv_in_pretrained = copy.deepcopy(convin_pretrained)
|
61 |
+
self.conv_in_curr = copy.deepcopy(convin_curr)
|
62 |
+
self.r = None
|
63 |
+
def forward(self, x):
|
64 |
+
x1 = self.conv_in_pretrained(x).detach()
|
65 |
+
x2 = self.conv_in_curr(x)
|
66 |
+
return x1*(1-self.r) + x2*(self.r)
|
67 |
+
|
68 |
+
|
69 |
+
class Pix2Pix_Turbo(torch.nn.Module):
|
70 |
+
def __init__(self, name, ckpt_folder="checkpoints"):
|
71 |
+
super().__init__()
|
72 |
+
self.tokenizer = AutoTokenizer.from_pretrained("stabilityai/sd-turbo",subfolder="tokenizer")
|
73 |
+
self.text_encoder = CLIPTextModel.from_pretrained("stabilityai/sd-turbo", subfolder="text_encoder").cuda()
|
74 |
+
self.sched = make_1step_sched()
|
75 |
+
|
76 |
+
vae = AutoencoderKL.from_pretrained("stabilityai/sd-turbo", subfolder="vae")
|
77 |
+
unet = UNet2DConditionModel.from_pretrained("stabilityai/sd-turbo", subfolder="unet")
|
78 |
+
|
79 |
+
if name=="canny_to_image":
|
80 |
+
lora_rank = 8
|
81 |
+
P_UNET_SD="/home/gparmar/code/single_step_translation/output/paired/canny_canny_midjourney_512_512/sd21_turbo_direct_edge_withskip_opt_lora_8_proj/l2_lpips_gan_vagan_clip_224_patch_multilevel_sigmoid/lr_5e-5_l2_0.25_lpips_1_0.1_CLIPSIM_1.0/1node_8gpu_no_BS_1_GRAD_ACC_2/checkpoint-7501/unet_sd.pkl"
|
82 |
+
P_VAE_ENC_SD="/home/gparmar/code/single_step_translation/output/paired/canny_canny_midjourney_512_512/sd21_turbo_direct_edge_withskip_opt_lora_8_proj/l2_lpips_gan_vagan_clip_224_patch_multilevel_sigmoid/lr_5e-5_l2_0.25_lpips_1_0.1_CLIPSIM_1.0/1node_8gpu_no_BS_1_GRAD_ACC_2/checkpoint-7501/sd_vae_enc.pkl"
|
83 |
+
P_VAE_DEC_SD="/home/gparmar/code/single_step_translation/output/paired/canny_canny_midjourney_512_512/sd21_turbo_direct_edge_withskip_opt_lora_8_proj/l2_lpips_gan_vagan_clip_224_patch_multilevel_sigmoid/lr_5e-5_l2_0.25_lpips_1_0.1_CLIPSIM_1.0/1node_8gpu_no_BS_1_GRAD_ACC_2/checkpoint-7501/sd_vae_dec.pkl"
|
84 |
+
unet_lora_config = LoraConfig(r=lora_rank, init_lora_weights="gaussian", target_modules=[
|
85 |
+
"to_k", "to_q", "to_v", "to_out.0", "conv", "conv1", "conv2", "conv_shortcut", "conv_out",
|
86 |
+
"proj_in", "proj_out", "ff.net.2", "ff.net.0.proj"]
|
87 |
+
)
|
88 |
+
|
89 |
+
if name=="sketch_to_image_stochastic":
|
90 |
+
# download from url
|
91 |
+
url = "https://www.cs.cmu.edu/~clean-fid/tmp/img2img_turbo/ckpt/sketch_to_image_stochastic.pkl"
|
92 |
+
os.makedirs(ckpt_folder, exist_ok=True)
|
93 |
+
outf = os.path.join(ckpt_folder, "sketch_to_image_stochastic.pkl")
|
94 |
+
if not os.path.exists(outf):
|
95 |
+
print(f"Downloading checkpoint to {outf}")
|
96 |
+
response = requests.get(url, stream=True)
|
97 |
+
total_size_in_bytes= int(response.headers.get('content-length', 0))
|
98 |
+
block_size = 1024 # 1 Kibibyte
|
99 |
+
progress_bar = tqdm(total=total_size_in_bytes, unit='iB', unit_scale=True)
|
100 |
+
with open(outf, 'wb') as file:
|
101 |
+
for data in response.iter_content(block_size):
|
102 |
+
progress_bar.update(len(data))
|
103 |
+
file.write(data)
|
104 |
+
progress_bar.close()
|
105 |
+
if total_size_in_bytes != 0 and progress_bar.n != total_size_in_bytes:
|
106 |
+
print("ERROR, something went wrong")
|
107 |
+
print(f"Downloaded successfully to {outf}")
|
108 |
+
# p_ckpt = "/home/gparmar/code/img2img-turbo/single_step_translation/notebooks/DEMO/sketch_to_image_stochastic.pkl"
|
109 |
+
p_ckpt = outf
|
110 |
+
sd = torch.load(p_ckpt, map_location="cpu")
|
111 |
+
unet_lora_config = LoraConfig(r=sd["rank_unet"], init_lora_weights="gaussian", target_modules=sd["unet_lora_target_modules"])
|
112 |
+
convin_pretrained = copy.deepcopy(unet.conv_in)
|
113 |
+
unet.conv_in = TwinConv(convin_pretrained, unet.conv_in)
|
114 |
+
|
115 |
+
vae.encoder.forward = my_vae_encoder_fwd.__get__(vae.encoder, vae.encoder.__class__)
|
116 |
+
vae.decoder.forward = my_vae_decoder_fwd.__get__(vae.decoder, vae.decoder.__class__)
|
117 |
+
# add the skip connection convs
|
118 |
+
vae.decoder.skip_conv_1 = torch.nn.Conv2d(512, 512, kernel_size=(1, 1), stride=(1, 1), bias=False).cuda()
|
119 |
+
vae.decoder.skip_conv_2 = torch.nn.Conv2d(256, 512, kernel_size=(1, 1), stride=(1, 1), bias=False).cuda()
|
120 |
+
vae.decoder.skip_conv_3 = torch.nn.Conv2d(128, 512, kernel_size=(1, 1), stride=(1, 1), bias=False).cuda()
|
121 |
+
vae.decoder.skip_conv_4 = torch.nn.Conv2d(128, 256, kernel_size=(1, 1), stride=(1, 1), bias=False).cuda()
|
122 |
+
vae_lora_config = LoraConfig(r=sd["rank_vae"], init_lora_weights="gaussian", target_modules=sd["vae_lora_target_modules"])
|
123 |
+
vae.decoder.ignore_skip = False
|
124 |
+
vae.add_adapter(vae_lora_config, adapter_name="vae_skip")
|
125 |
+
unet.add_adapter(unet_lora_config)
|
126 |
+
unet.load_state_dict(sd["state_dict_unet"])
|
127 |
+
unet.enable_xformers_memory_efficient_attention()
|
128 |
+
|
129 |
+
vae.load_state_dict(sd["state_dict_vae"])
|
130 |
+
unet.to("cuda")
|
131 |
+
vae.to("cuda")
|
132 |
+
unet.eval()
|
133 |
+
vae.eval()
|
134 |
+
|
135 |
+
self.unet, self.vae = unet, vae
|
136 |
+
self.timesteps = torch.tensor([999], device="cuda").long()
|
137 |
+
|
138 |
+
|
139 |
+
def forward(self, c_t, prompt, deterministic=True, r=1.0, noise_map=None):
|
140 |
+
# encode the text prompt
|
141 |
+
caption_tokens = self.tokenizer(prompt, max_length=self.tokenizer.model_max_length,
|
142 |
+
padding="max_length", truncation=True, return_tensors="pt").input_ids.cuda()
|
143 |
+
caption_enc = self.text_encoder(caption_tokens)[0]
|
144 |
+
|
145 |
+
if deterministic:
|
146 |
+
encoded_control = self.vae.encode(c_t).latent_dist.sample()*self.vae.config.scaling_factor
|
147 |
+
model_pred = self.unet(encoded_control, self.timesteps, encoder_hidden_states=caption_enc,).sample
|
148 |
+
x_denoised = self.sched.step(model_pred, self.timesteps, encoded_control, return_dict=True).prev_sample
|
149 |
+
self.vae.decoder.incoming_skip_acts = self.vae.encoder.current_down_blocks
|
150 |
+
output_image = (self.vae.decode(x_denoised / self.vae.config.scaling_factor ).sample).clamp(-1,1)
|
151 |
+
else:
|
152 |
+
# scale the lora weights based on the r value
|
153 |
+
self.unet.set_adapters(["default"], weights=[r])
|
154 |
+
set_weights_and_activate_adapters(self.vae, ["vae_skip"], [r])
|
155 |
+
encoded_control = self.vae.encode(c_t).latent_dist.sample()*self.vae.config.scaling_factor
|
156 |
+
# combine the input and noise
|
157 |
+
unet_input = encoded_control*r + noise_map*(1-r)
|
158 |
+
self.unet.conv_in.r = r
|
159 |
+
unet_output = self.unet(unet_input, self.timesteps, encoder_hidden_states=caption_enc,).sample
|
160 |
+
self.unet.conv_in.r = None
|
161 |
+
x_denoised = self.sched.step(unet_output, self.timesteps, unet_input, return_dict=True).prev_sample
|
162 |
+
self.vae.decoder.incoming_skip_acts = self.vae.encoder.current_down_blocks
|
163 |
+
output_image = (self.vae.decode(x_denoised / self.vae.config.scaling_factor ).sample).clamp(-1,1)
|
164 |
+
|
165 |
+
return output_image
|
166 |
+
|
167 |
+
|
168 |
+
|