sagar007 commited on
Commit
dbfd4a1
·
verified ·
1 Parent(s): bf7ef8a

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +135 -77
app.py CHANGED
@@ -1,4 +1,3 @@
1
- import gradio as gr
2
  import PIL
3
  import torch
4
  import numpy as np
@@ -13,7 +12,7 @@ torch_device = "cuda" if torch.cuda.is_available() else "mps" if torch.ba
13
  height, width = 512, 512
14
  guidance_scale = 8
15
  loss_scale = 200
16
- num_inference_steps = 10
17
 
18
 
19
  model_path = "CompVis/stable-diffusion-v1-4"
@@ -42,109 +41,168 @@ styles_mapping = {
42
 
43
  # Define seeds for all the styles
44
  seed_list = [11, 56, 110, 65, 5, 29, 47]
45
- # Optimized loss computation functions
 
46
  def edge_detection(image):
47
  channels = image.shape[1]
48
- kernels = torch.tensor([[-1, -2, -1], [0, 0, 0], [1, 2, 1],
49
- [-1, 0, 1], [-2, 0, 2], [-1, 0, 1]], device=image.device).float()
50
- kernels = kernels.view(2, 1, 3, 3).repeat(channels, 1, 1, 1)
51
- padded_image = F.pad(image, (1, 1, 1, 1), mode='replicate')
52
- edge = F.conv2d(padded_image, kernels, groups=channels)
53
- return torch.sqrt(edge[:, :channels]**2 + edge[:, channels:]**2)
54
-
55
- def compute_loss(original_image, loss_type: str):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
56
  if loss_type == 'blue':
57
- return torch.abs(original_image[:,2] - 0.9).mean()
 
 
58
  elif loss_type == 'edge':
59
- ed_value = edge_detection(original_image)
60
- return F.mse_loss(ed_value, (ed_value > 0.5).float())
61
  elif loss_type == 'contrast':
62
- transformed_image = TF.adjust_contrast(original_image, contrast_factor=2.0)
63
- return torch.abs(transformed_image - original_image).mean()
 
64
  elif loss_type == 'brightness':
65
- transformed_image = TF.adjust_brightness(original_image, brightness_factor=2.0)
66
- return torch.abs(transformed_image - original_image).mean()
 
67
  elif loss_type == 'sharpness':
68
- transformed_image = TF.adjust_sharpness(original_image, sharpness_factor=2.0)
69
- return torch.abs(transformed_image - original_image).mean()
 
70
  elif loss_type == 'saturation':
71
- transformed_image = TF.adjust_saturation(original_image, saturation_factor=10.0)
72
- return torch.abs(transformed_image - original_image).mean()
 
73
  else:
74
- return torch.tensor(0.0, device=original_image.device)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
75
 
76
- # Optimized generate_image function
77
  def generate_image(seed, prompt, loss_type, loss_flag=False):
78
- generator = torch.manual_seed(seed)
79
- batch_size = 1
80
 
81
- text_embeddings = sd_pipeline._encode_prompt(prompt, sd_pipeline.device, 1, True)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
82
 
 
 
 
83
  latents = torch.randn(
84
- (batch_size, sd_pipeline.unet.config.in_channels, height // 8, width // 8),
85
- generator=generator,
86
- ).to(sd_pipeline.device)
 
87
 
88
- latents = latents * sd_pipeline.scheduler.init_noise_sigma
 
89
 
90
- sd_pipeline.scheduler.set_timesteps(num_inference_steps)
91
 
92
- for i, t in enumerate(tqdm(sd_pipeline.scheduler.timesteps)):
93
  latent_model_input = torch.cat([latents] * 2)
94
- latent_model_input = sd_pipeline.scheduler.scale_model_input(latent_model_input, t)
 
95
 
96
  with torch.no_grad():
97
- noise_pred = sd_pipeline.unet(latent_model_input, t, encoder_hidden_states=text_embeddings).sample
98
 
99
  noise_pred_uncond, noise_pred_text = noise_pred.chunk(2)
100
  noise_pred = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond)
101
 
102
- if loss_flag and i % 5 == 0:
 
103
  latents = latents.detach().requires_grad_()
104
- latents_x0 = sd_pipeline.scheduler.step(noise_pred, t, latents).prev_sample
105
- with torch.no_grad():
106
- denoised_images = sd_pipeline.vae.decode((1 / 0.18215) * latents_x0).sample / 2 + 0.5
 
 
 
 
107
 
108
  loss = compute_loss(denoised_images, loss_type) * loss_scale
109
- print(f"Step {i}, Loss: {loss.item():.4f}")
 
110
 
111
  cond_grad = torch.autograd.grad(loss, latents)[0]
112
- latents = latents.detach() - cond_grad * sd_pipeline.scheduler.sigmas[i] ** 2
113
 
114
- latents = sd_pipeline.scheduler.step(noise_pred, t, latents).prev_sample
115
 
116
- return latents
117
-
118
- def generate_image(prompt, style, guidance_type):
119
- styled_prompt = f"{prompt} in the style of {styles_mapping[style]}"
120
- seed = torch.randint(0, 1000000, (1,)).item()
121
- latents = generate_image(seed, styled_prompt, guidance_type, loss_flag=True)
122
- with torch.no_grad():
123
- image = sd_pipeline.decode_latents(latents)
124
- image = sd_pipeline.numpy_to_pil(image)[0]
125
- return image
126
-
127
- def get_examples():
128
- examples = [
129
- ["A bird sitting on a tree", "Midjourney", "edge"],
130
- ["Cats fighting on the road", "Marc Allante", "brightness"],
131
- ["A mouse with the head of a puppy", "Hitokomoru Style", "contrast"],
132
- ["A woman with a smiling face in front of an Italian Pizza", "Hanfu Anime", "brightness"],
133
- ["A campfire (oil on canvas)", "Birb Style", "blue"],
134
- ]
135
- return examples
136
-
137
- iface = gr.Interface(
138
- fn=generate_image,
139
- inputs=[
140
- gr.Textbox(label="Prompt"),
141
- gr.Dropdown(list(styles_mapping.keys()), label="Style"),
142
- gr.Dropdown(["blue", "edge", "contrast", "brightness", "sharpness", "saturation"], label="Guidance Type"),
143
- ],
144
- outputs=gr.Image(label="Generated Image"),
145
- title="Stable Diffusion with Custom Styles",
146
- description="Generate images using a custom Stable Diffusion model with various styles and guidance types.",
147
- examples=get_examples(),
148
- )
149
-
150
- iface.launch()
 
 
1
  import PIL
2
  import torch
3
  import numpy as np
 
12
  height, width = 512, 512
13
  guidance_scale = 8
14
  loss_scale = 200
15
+ num_inference_steps = 50
16
 
17
 
18
  model_path = "CompVis/stable-diffusion-v1-4"
 
41
 
42
  # Define seeds for all the styles
43
  seed_list = [11, 56, 110, 65, 5, 29, 47]
44
+
45
+ # Loss Function based on Edge Detection
46
  def edge_detection(image):
47
  channels = image.shape[1]
48
+
49
+ # Define the kernels for Edge Detection
50
+ ed_x = torch.tensor([[-1, 0, 1], [-2, 0, 2], [-1, 0, 1]], dtype=torch.float32).unsqueeze(0).unsqueeze(0)
51
+ ed_y = torch.tensor([[1, 2, 1], [0, 0, 0], [-1, -2, -1]], dtype=torch.float32).unsqueeze(0).unsqueeze(0)
52
+
53
+ # Replicate the Edge detection kernels for each channel
54
+ ed_x = ed_x.repeat(channels, 1, 1, 1).to(image.device)
55
+ ed_y = ed_y.repeat(channels, 1, 1, 1).to(image.device)
56
+
57
+ # ed_x = ed_x.to(torch.float16)
58
+ # ed_y = ed_y.to(torch.float16)
59
+
60
+ # Convolve the image with the Edge detection kernels
61
+ conv_ed_x = F.conv2d(image, ed_x, padding=1, groups=channels)
62
+ conv_ed_y = F.conv2d(image, ed_y, padding=1, groups=channels)
63
+
64
+ # Combine the x and y gradients after convolution
65
+ ed_value = torch.sqrt(conv_ed_x**2 + conv_ed_y**2)
66
+
67
+ return ed_value
68
+
69
+ def edge_loss(image):
70
+ ed_value = edge_detection(image)
71
+ ed_capped = (ed_value > 0.5).to(torch.float32)
72
+ return F.mse_loss(ed_value, ed_capped)
73
+
74
+ def compute_loss(original_image, loss_type):
75
+
76
  if loss_type == 'blue':
77
+ # blue loss
78
+ # [:,2] -> all images in batch, only the blue channel
79
+ error = torch.abs(original_image[:,2] - 0.9).mean()
80
  elif loss_type == 'edge':
81
+ # edge loss
82
+ error = edge_loss(original_image)
83
  elif loss_type == 'contrast':
84
+ # RGB to Gray loss
85
+ transformed_image = T.functional.adjust_contrast(original_image, contrast_factor = 2)
86
+ error = torch.abs(transformed_image - original_image).mean()
87
  elif loss_type == 'brightness':
88
+ # brightnesss loss
89
+ transformed_image = T.functional.adjust_brightness(original_image, brightness_factor = 2)
90
+ error = torch.abs(transformed_image - original_image).mean()
91
  elif loss_type == 'sharpness':
92
+ # sharpness loss
93
+ transformed_image = T.functional.adjust_sharpness(original_image, sharpness_factor = 2)
94
+ error = torch.abs(transformed_image - original_image).mean()
95
  elif loss_type == 'saturation':
96
+ # saturation loss
97
+ transformed_image = T.functional.adjust_saturation(original_image, saturation_factor = 10)
98
+ error = torch.abs(transformed_image - original_image).mean()
99
  else:
100
+ print("error. Loss not defined")
101
+
102
+ return error
103
+
104
+
105
+ def get_examples():
106
+ examples = [
107
+ ['A bird sitting on a tree', 'Midjourney', 'edge', 5],
108
+ ['Cats fighting on the road', 'Marc Allante', 'brightness', 65],
109
+ ['A mouse with the head of a puppy', 'Hitokomoru Style', 'contrast', 110],
110
+ ['A woman with a smiling face in front of an Italian Pizza', 'Hanfu Anime', 'brightness', 29],
111
+ ['A campfire (oil on canvas)', 'Birb Style', 'blue', 47],
112
+ ]
113
+ return(examples)
114
+
115
+
116
+ def latents_to_pil(latents):
117
+ # bath of latents -> list of images
118
+ latents = (1 / 0.18215) * latents
119
+ with torch.no_grad():
120
+ image = sd_pipeline.vae.decode(latents).sample
121
+ image = (image / 2 + 0.5).clamp(0, 1) # 0 to 1
122
+ image = image.detach().cpu().permute(0, 2, 3, 1).numpy()
123
+ image = (image * 255).round().astype("uint8")
124
+ return Image.fromarray(image[0])
125
+
126
+
127
+ def show_image(prompt, concept, guidance_type):
128
+
129
+ for idx, sd in enumerate(styles_mapping.keys()):
130
+ if(sd == concept):
131
+ break
132
+ seed = seed_list[idx]
133
+ prompt = f"{prompt} in the style of {styles_mapping[sd]}"
134
+ styled_image_without_loss = latents_to_pil(generate_image(seed, prompt, guidance_type, loss_flag=False))
135
+ styled_image_with_loss = latents_to_pil(generate_image(seed, prompt, guidance_type, loss_flag=True))
136
+ return([styled_image_without_loss, styled_image_with_loss])
137
+
138
 
 
139
  def generate_image(seed, prompt, loss_type, loss_flag=False):
 
 
140
 
141
+ generator = torch.manual_seed(seed)
142
+ batch_size = 1
143
+
144
+ # scheduler
145
+ scheduler = LMSDiscreteScheduler(beta_start = 0.00085, beta_end = 0.012, beta_schedule = "scaled_linear", num_train_timesteps = 1000)
146
+ scheduler.set_timesteps(num_inference_steps)
147
+ scheduler.timesteps = scheduler.timesteps.to(torch.float32)
148
+
149
+ # text embeddings of the prompt
150
+ text_input = sd_pipeline.tokenizer(prompt, padding='max_length', max_length = sd_pipeline.tokenizer.model_max_length, truncation= True, return_tensors="pt")
151
+ input_ids = text_input.input_ids.to(torch_device)
152
+
153
+ with torch.no_grad():
154
+ text_embeddings = sd_pipeline.text_encoder(text_input.input_ids.to(torch_device))[0]
155
+
156
+ max_length = text_input.input_ids.shape[-1]
157
+ uncond_input = sd_pipeline.tokenizer(
158
+ [""] * batch_size, padding="max_length", max_length= max_length, return_tensors="pt"
159
+ )
160
+
161
+ with torch.no_grad():
162
+ uncond_embeddings = sd_pipeline.text_encoder(uncond_input.input_ids.to(torch_device))[0]
163
 
164
+ text_embeddings = torch.cat([uncond_embeddings,text_embeddings]) # shape: 2,77,768
165
+
166
+ # random latent
167
  latents = torch.randn(
168
+ (batch_size, sd_pipeline.unet.config.in_channels, height// 8, width //8),
169
+ generator = generator,
170
+ ) .to(torch.float32)
171
+
172
 
173
+ latents = latents.to(torch_device)
174
+ latents = latents * scheduler.init_noise_sigma
175
 
176
+ for i, t in tqdm(enumerate(scheduler.timesteps), total = len(scheduler.timesteps)):
177
 
 
178
  latent_model_input = torch.cat([latents] * 2)
179
+ sigma = scheduler.sigmas[i]
180
+ latent_model_input = scheduler.scale_model_input(latent_model_input, t)
181
 
182
  with torch.no_grad():
183
+ noise_pred = sd_pipeline.unet(latent_model_input.to(torch.float32), t, encoder_hidden_states=text_embeddings)["sample"]
184
 
185
  noise_pred_uncond, noise_pred_text = noise_pred.chunk(2)
186
  noise_pred = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond)
187
 
188
+ if loss_flag and i%5 == 0:
189
+
190
  latents = latents.detach().requires_grad_()
191
+ # the following line alone does not work, it requires change to reduce step only once
192
+ # hence commenting it out
193
+ #latents_x0 = scheduler.step(noise_pred,t, latents).pred_original_sample
194
+ latents_x0 = latents - sigma * noise_pred
195
+
196
+ # use vae to decode the image
197
+ denoised_images = sd_pipeline.vae.decode((1/ 0.18215) * latents_x0).sample / 2 + 0.5 # range(0,1)
198
 
199
  loss = compute_loss(denoised_images, loss_type) * loss_scale
200
+ #loss = loss.to(torch.float16)
201
+ print(f"{i} loss {loss}")
202
 
203
  cond_grad = torch.autograd.grad(loss, latents)[0]
204
+ latents = latents.detach() - cond_grad * sigma**2
205
 
206
+ latents = scheduler.step(noise_pred,t, latents).prev_sample
207
 
208
+ return latents