|
| 1 | +import inspect |
| 2 | +from typing import List, Optional, Union |
| 3 | + |
| 4 | +import torch |
| 5 | +from torch import nn |
| 6 | +from torch.nn import functional as F |
| 7 | + |
| 8 | +from diffusers import AutoencoderKL, DiffusionPipeline, LMSDiscreteScheduler, PNDMScheduler, UNet2DConditionModel |
| 9 | +from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion import StableDiffusionPipelineOutput |
| 10 | +from torchvision import transforms |
| 11 | +from transformers import CLIPFeatureExtractor, CLIPModel, CLIPTextModel, CLIPTokenizer |
| 12 | + |
| 13 | + |
| 14 | +class MakeCutouts(nn.Module): |
| 15 | + def __init__(self, cut_size, cut_power=1.0): |
| 16 | + super().__init__() |
| 17 | + |
| 18 | + self.cut_size = cut_size |
| 19 | + self.cut_power = cut_power |
| 20 | + |
| 21 | + def forward(self, pixel_values, num_cutouts): |
| 22 | + sideY, sideX = pixel_values.shape[2:4] |
| 23 | + max_size = min(sideX, sideY) |
| 24 | + min_size = min(sideX, sideY, self.cut_size) |
| 25 | + cutouts = [] |
| 26 | + for _ in range(num_cutouts): |
| 27 | + size = int(torch.rand([]) ** self.cut_power * (max_size - min_size) + min_size) |
| 28 | + offsetx = torch.randint(0, sideX - size + 1, ()) |
| 29 | + offsety = torch.randint(0, sideY - size + 1, ()) |
| 30 | + cutout = pixel_values[:, :, offsety : offsety + size, offsetx : offsetx + size] |
| 31 | + cutouts.append(F.adaptive_avg_pool2d(cutout, self.cut_size)) |
| 32 | + return torch.cat(cutouts) |
| 33 | + |
| 34 | + |
| 35 | +def spherical_dist_loss(x, y): |
| 36 | + x = F.normalize(x, dim=-1) |
| 37 | + y = F.normalize(y, dim=-1) |
| 38 | + return (x - y).norm(dim=-1).div(2).arcsin().pow(2).mul(2) |
| 39 | + |
| 40 | + |
| 41 | +def set_requires_grad(model, value): |
| 42 | + for param in model.parameters(): |
| 43 | + param.requires_grad = value |
| 44 | + |
| 45 | + |
| 46 | +class CLIPGuidedStableDiffusion(DiffusionPipeline): |
| 47 | + """CLIP guided stable diffusion based on the amazing repo by @crowsonkb and @Jack000 |
| 48 | + - https://github.com/Jack000/glid-3-xl |
| 49 | + - https://github.dev/crowsonkb/k-diffusion |
| 50 | + """ |
| 51 | + |
| 52 | + def __init__( |
| 53 | + self, |
| 54 | + vae: AutoencoderKL, |
| 55 | + text_encoder: CLIPTextModel, |
| 56 | + clip_model: CLIPModel, |
| 57 | + tokenizer: CLIPTokenizer, |
| 58 | + unet: UNet2DConditionModel, |
| 59 | + scheduler: Union[PNDMScheduler, LMSDiscreteScheduler], |
| 60 | + feature_extractor: CLIPFeatureExtractor, |
| 61 | + ): |
| 62 | + super().__init__() |
| 63 | + scheduler = scheduler.set_format("pt") |
| 64 | + self.register_modules( |
| 65 | + vae=vae, |
| 66 | + text_encoder=text_encoder, |
| 67 | + clip_model=clip_model, |
| 68 | + tokenizer=tokenizer, |
| 69 | + unet=unet, |
| 70 | + scheduler=scheduler, |
| 71 | + feature_extractor=feature_extractor, |
| 72 | + ) |
| 73 | + |
| 74 | + self.normalize = transforms.Normalize(mean=feature_extractor.image_mean, std=feature_extractor.image_std) |
| 75 | + self.make_cutouts = MakeCutouts(feature_extractor.size) |
| 76 | + |
| 77 | + set_requires_grad(self.text_encoder, False) |
| 78 | + set_requires_grad(self.clip_model, False) |
| 79 | + |
| 80 | + def enable_attention_slicing(self, slice_size: Optional[Union[str, int]] = "auto"): |
| 81 | + if slice_size == "auto": |
| 82 | + # half the attention head size is usually a good trade-off between |
| 83 | + # speed and memory |
| 84 | + slice_size = self.unet.config.attention_head_dim // 2 |
| 85 | + self.unet.set_attention_slice(slice_size) |
| 86 | + |
| 87 | + def disable_attention_slicing(self): |
| 88 | + self.enable_attention_slicing(None) |
| 89 | + |
| 90 | + def freeze_vae(self): |
| 91 | + set_requires_grad(self.vae, False) |
| 92 | + |
| 93 | + def unfreeze_vae(self): |
| 94 | + set_requires_grad(self.vae, True) |
| 95 | + |
| 96 | + def freeze_unet(self): |
| 97 | + set_requires_grad(self.unet, False) |
| 98 | + |
| 99 | + def unfreeze_unet(self): |
| 100 | + set_requires_grad(self.unet, True) |
| 101 | + |
| 102 | + @torch.enable_grad() |
| 103 | + def cond_fn( |
| 104 | + self, |
| 105 | + latents, |
| 106 | + timestep, |
| 107 | + index, |
| 108 | + text_embeddings, |
| 109 | + noise_pred_original, |
| 110 | + text_embeddings_clip, |
| 111 | + clip_guidance_scale, |
| 112 | + num_cutouts, |
| 113 | + use_cutouts=True, |
| 114 | + ): |
| 115 | + latents = latents.detach().requires_grad_() |
| 116 | + |
| 117 | + if isinstance(self.scheduler, LMSDiscreteScheduler): |
| 118 | + sigma = self.scheduler.sigmas[index] |
| 119 | + # the model input needs to be scaled to match the continuous ODE formulation in K-LMS |
| 120 | + latent_model_input = latents / ((sigma**2 + 1) ** 0.5) |
| 121 | + else: |
| 122 | + latent_model_input = latents |
| 123 | + |
| 124 | + # predict the noise residual |
| 125 | + noise_pred = self.unet(latent_model_input, timestep, encoder_hidden_states=text_embeddings).sample |
| 126 | + |
| 127 | + if isinstance(self.scheduler, PNDMScheduler): |
| 128 | + alpha_prod_t = self.scheduler.alphas_cumprod[timestep] |
| 129 | + beta_prod_t = 1 - alpha_prod_t |
| 130 | + # compute predicted original sample from predicted noise also called |
| 131 | + # "predicted x_0" of formula (12) from https://arxiv.org/pdf/2010.02502.pdf |
| 132 | + pred_original_sample = (latents - beta_prod_t ** (0.5) * noise_pred) / alpha_prod_t ** (0.5) |
| 133 | + |
| 134 | + fac = torch.sqrt(beta_prod_t) |
| 135 | + sample = pred_original_sample * (fac) + latents * (1 - fac) |
| 136 | + elif isinstance(self.scheduler, LMSDiscreteScheduler): |
| 137 | + sigma = self.scheduler.sigmas[index] |
| 138 | + sample = latents - sigma * noise_pred |
| 139 | + else: |
| 140 | + raise ValueError(f"scheduler type {type(self.scheduler)} not supported") |
| 141 | + |
| 142 | + sample = 1 / 0.18215 * sample |
| 143 | + image = self.vae.decode(sample).sample |
| 144 | + image = (image / 2 + 0.5).clamp(0, 1) |
| 145 | + |
| 146 | + if use_cutouts: |
| 147 | + image = self.make_cutouts(image, num_cutouts) |
| 148 | + else: |
| 149 | + image = transforms.Resize(self.feature_extractor.size)(image) |
| 150 | + image = self.normalize(image) |
| 151 | + |
| 152 | + image_embeddings_clip = self.clip_model.get_image_features(image).float() |
| 153 | + image_embeddings_clip = image_embeddings_clip / image_embeddings_clip.norm(p=2, dim=-1, keepdim=True) |
| 154 | + |
| 155 | + if use_cutouts: |
| 156 | + dists = spherical_dist_loss(image_embeddings_clip, text_embeddings_clip) |
| 157 | + dists = dists.view([num_cutouts, sample.shape[0], -1]) |
| 158 | + loss = dists.sum(2).mean(0).sum() * clip_guidance_scale |
| 159 | + else: |
| 160 | + loss = spherical_dist_loss(image_embeddings_clip, text_embeddings_clip).mean() * clip_guidance_scale |
| 161 | + |
| 162 | + grads = -torch.autograd.grad(loss, latents)[0] |
| 163 | + |
| 164 | + if isinstance(self.scheduler, LMSDiscreteScheduler): |
| 165 | + latents = latents.detach() + grads * (sigma**2) |
| 166 | + noise_pred = noise_pred_original |
| 167 | + else: |
| 168 | + noise_pred = noise_pred_original - torch.sqrt(beta_prod_t) * grads |
| 169 | + return noise_pred, latents |
| 170 | + |
| 171 | + @torch.no_grad() |
| 172 | + def __call__( |
| 173 | + self, |
| 174 | + prompt: Union[str, List[str]], |
| 175 | + height: Optional[int] = 512, |
| 176 | + width: Optional[int] = 512, |
| 177 | + num_inference_steps: Optional[int] = 50, |
| 178 | + guidance_scale: Optional[float] = 7.5, |
| 179 | + clip_guidance_scale: Optional[float] = 100, |
| 180 | + clip_prompt: Optional[Union[str, List[str]]] = None, |
| 181 | + num_cutouts: Optional[int] = 4, |
| 182 | + use_cutouts: Optional[bool] = True, |
| 183 | + generator: Optional[torch.Generator] = None, |
| 184 | + latents: Optional[torch.FloatTensor] = None, |
| 185 | + output_type: Optional[str] = "pil", |
| 186 | + return_dict: bool = True, |
| 187 | + ): |
| 188 | + if isinstance(prompt, str): |
| 189 | + batch_size = 1 |
| 190 | + elif isinstance(prompt, list): |
| 191 | + batch_size = len(prompt) |
| 192 | + else: |
| 193 | + raise ValueError(f"`prompt` has to be of type `str` or `list` but is {type(prompt)}") |
| 194 | + |
| 195 | + if height % 8 != 0 or width % 8 != 0: |
| 196 | + raise ValueError(f"`height` and `width` have to be divisible by 8 but are {height} and {width}.") |
| 197 | + |
| 198 | + # get prompt text embeddings |
| 199 | + text_input = self.tokenizer( |
| 200 | + prompt, |
| 201 | + padding="max_length", |
| 202 | + max_length=self.tokenizer.model_max_length, |
| 203 | + truncation=True, |
| 204 | + return_tensors="pt", |
| 205 | + ) |
| 206 | + text_embeddings = self.text_encoder(text_input.input_ids.to(self.device))[0] |
| 207 | + |
| 208 | + if clip_guidance_scale > 0: |
| 209 | + if clip_prompt is not None: |
| 210 | + clip_text_input = self.tokenizer( |
| 211 | + clip_prompt, |
| 212 | + padding="max_length", |
| 213 | + max_length=self.tokenizer.model_max_length, |
| 214 | + truncation=True, |
| 215 | + return_tensors="pt", |
| 216 | + ).input_ids.to(self.device) |
| 217 | + else: |
| 218 | + clip_text_input = text_input.input_ids.to(self.device) |
| 219 | + text_embeddings_clip = self.clip_model.get_text_features(clip_text_input) |
| 220 | + text_embeddings_clip = text_embeddings_clip / text_embeddings_clip.norm(p=2, dim=-1, keepdim=True) |
| 221 | + |
| 222 | + # here `guidance_scale` is defined analog to the guidance weight `w` of equation (2) |
| 223 | + # of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1` |
| 224 | + # corresponds to doing no classifier free guidance. |
| 225 | + do_classifier_free_guidance = guidance_scale > 1.0 |
| 226 | + # get unconditional embeddings for classifier free guidance |
| 227 | + if do_classifier_free_guidance: |
| 228 | + max_length = text_input.input_ids.shape[-1] |
| 229 | + uncond_input = self.tokenizer( |
| 230 | + [""] * batch_size, padding="max_length", max_length=max_length, return_tensors="pt" |
| 231 | + ) |
| 232 | + uncond_embeddings = self.text_encoder(uncond_input.input_ids.to(self.device))[0] |
| 233 | + |
| 234 | + # For classifier free guidance, we need to do two forward passes. |
| 235 | + # Here we concatenate the unconditional and text embeddings into a single batch |
| 236 | + # to avoid doing two forward passes |
| 237 | + text_embeddings = torch.cat([uncond_embeddings, text_embeddings]) |
| 238 | + |
| 239 | + # get the initial random noise unless the user supplied it |
| 240 | + |
| 241 | + # Unlike in other pipelines, latents need to be generated in the target device |
| 242 | + # for 1-to-1 results reproducibility with the CompVis implementation. |
| 243 | + # However this currently doesn't work in `mps`. |
| 244 | + latents_device = "cpu" if self.device.type == "mps" else self.device |
| 245 | + latents_shape = (batch_size, self.unet.in_channels, height // 8, width // 8) |
| 246 | + if latents is None: |
| 247 | + latents = torch.randn( |
| 248 | + latents_shape, |
| 249 | + generator=generator, |
| 250 | + device=latents_device, |
| 251 | + ) |
| 252 | + else: |
| 253 | + if latents.shape != latents_shape: |
| 254 | + raise ValueError(f"Unexpected latents shape, got {latents.shape}, expected {latents_shape}") |
| 255 | + latents = latents.to(self.device) |
| 256 | + |
| 257 | + # set timesteps |
| 258 | + accepts_offset = "offset" in set(inspect.signature(self.scheduler.set_timesteps).parameters.keys()) |
| 259 | + extra_set_kwargs = {} |
| 260 | + if accepts_offset: |
| 261 | + extra_set_kwargs["offset"] = 1 |
| 262 | + |
| 263 | + self.scheduler.set_timesteps(num_inference_steps, **extra_set_kwargs) |
| 264 | + |
| 265 | + # if we use LMSDiscreteScheduler, let's make sure latents are multiplied by sigmas |
| 266 | + if isinstance(self.scheduler, LMSDiscreteScheduler): |
| 267 | + latents = latents * self.scheduler.sigmas[0] |
| 268 | + |
| 269 | + for i, t in enumerate(self.progress_bar(self.scheduler.timesteps)): |
| 270 | + # expand the latents if we are doing classifier free guidance |
| 271 | + latent_model_input = torch.cat([latents] * 2) if do_classifier_free_guidance else latents |
| 272 | + if isinstance(self.scheduler, LMSDiscreteScheduler): |
| 273 | + sigma = self.scheduler.sigmas[i] |
| 274 | + # the model input needs to be scaled to match the continuous ODE formulation in K-LMS |
| 275 | + latent_model_input = latent_model_input / ((sigma**2 + 1) ** 0.5) |
| 276 | + |
| 277 | + # # predict the noise residual |
| 278 | + noise_pred = self.unet(latent_model_input, t, encoder_hidden_states=text_embeddings).sample |
| 279 | + |
| 280 | + # perform classifier free guidance |
| 281 | + if do_classifier_free_guidance: |
| 282 | + noise_pred_uncond, noise_pred_text = noise_pred.chunk(2) |
| 283 | + noise_pred = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond) |
| 284 | + |
| 285 | + # perform clip guidance |
| 286 | + if clip_guidance_scale > 0: |
| 287 | + text_embeddings_for_guidance = ( |
| 288 | + text_embeddings.chunk(2)[0] if do_classifier_free_guidance else text_embeddings |
| 289 | + ) |
| 290 | + noise_pred, latents = self.cond_fn( |
| 291 | + latents, |
| 292 | + t, |
| 293 | + i, |
| 294 | + text_embeddings_for_guidance, |
| 295 | + noise_pred, |
| 296 | + text_embeddings_clip, |
| 297 | + clip_guidance_scale, |
| 298 | + num_cutouts, |
| 299 | + use_cutouts, |
| 300 | + ) |
| 301 | + |
| 302 | + # compute the previous noisy sample x_t -> x_t-1 |
| 303 | + if isinstance(self.scheduler, LMSDiscreteScheduler): |
| 304 | + latents = self.scheduler.step(noise_pred, i, latents).prev_sample |
| 305 | + else: |
| 306 | + latents = self.scheduler.step(noise_pred, t, latents).prev_sample |
| 307 | + |
| 308 | + # scale and decode the image latents with vae |
| 309 | + latents = 1 / 0.18215 * latents |
| 310 | + image = self.vae.decode(latents).sample |
| 311 | + |
| 312 | + image = (image / 2 + 0.5).clamp(0, 1) |
| 313 | + image = image.cpu().permute(0, 2, 3, 1).numpy() |
| 314 | + |
| 315 | + if output_type == "pil": |
| 316 | + image = self.numpy_to_pil(image) |
| 317 | + |
| 318 | + if not return_dict: |
| 319 | + return (image, None) |
| 320 | + |
| 321 | + return StableDiffusionPipelineOutput(images=image, nsfw_content_detected=None) |
0 commit comments