Advertisement
Guest User

Untitled

a guest
Sep 10th, 2022
276
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 7.36 KB | None | 0 0
  1. from calendar import prmonth
  2. from transformers import CLIPTextModel, CLIPTokenizer
  3. from diffusers import AutoencoderKL, UNet2DConditionModel
  4. import torch
  5.  
  6. # 1. Load the autoencoder model which will be used to decode the latents into image space.
  7. vae = AutoencoderKL.from_pretrained("CompVis/stable-diffusion-v1-4-fp16", torch_dtype=torch.float16, subfolder="vae", use_auth_token=False)
  8.  
  9. # 2. Load the tokenizer and text encoder to tokenize and encode the text.
  10. tokenizer = CLIPTokenizer.from_pretrained("openai/clip-vit-large-patch14", revision='0993c71e8ad62658387de2714a69f723ddfffacb')
  11. text_encoder = CLIPTextModel.from_pretrained("openai/clip-vit-large-patch14", revision='0993c71e8ad62658387de2714a69f723ddfffacb')
  12.  
  13. # 3. The UNet model for generating the latents.
  14. unet = UNet2DConditionModel.from_pretrained("CompVis/stable-diffusion-v1-4-fp16", torch_dtype=torch.float16, subfolder="unet", use_auth_token=False)
  15.  
  16. from diffusers import LMSDiscreteScheduler
  17.  
  18. scheduler = LMSDiscreteScheduler(beta_start=0.00085, beta_end=0.012, beta_schedule="scaled_linear", num_train_timesteps=1000)
  19. scheduler_b = LMSDiscreteScheduler(beta_start=0.00085, beta_end=0.012, beta_schedule="scaled_linear", num_train_timesteps=1000)
  20.  
  21. # Move models to GPU
  22. torch_device = "cuda"
  23. vae.to(torch_device)
  24. text_encoder.to(torch_device)
  25. unet.to(torch_device)
  26.  
  27. # Prompt setup
  28. prompt = ["lemon cake."]
  29. prompt_b = ["chocolate cake."]
  30.  
  31. height = 512                        # default height of Stable Diffusion
  32. width = 512                         # default width of Stable Diffusion
  33.  
  34. num_inference_steps = 50           # Number of denoising steps
  35.  
  36. guidance_scale = 7.5                # Scale for classifier-free guidance
  37.  
  38. generator = torch.manual_seed(3)    # Seed generator to create the inital latent noise
  39.  
  40. batch_size = len(prompt)
  41.  
  42. # Text embeddings
  43. text_input = tokenizer(prompt, padding="max_length", max_length=tokenizer.model_max_length, truncation=True, return_tensors="pt")
  44. text_b_input = tokenizer(prompt_b, padding="max_length", max_length=tokenizer.model_max_length, truncation=True, return_tensors="pt")
  45.  
  46. text_embeddings = text_encoder(text_input.input_ids.to(torch_device))[0]
  47. text_b_embeddings = text_encoder(text_b_input.input_ids.to(torch_device))[0]
  48.  
  49. # Unconditional embeddings
  50. max_length = text_input.input_ids.shape[-1]
  51. uncond_input = tokenizer(
  52.     [""] * batch_size, padding="max_length", max_length=max_length, return_tensors="pt"
  53. )
  54. uncond_embeddings = text_encoder(uncond_input.input_ids.to(torch_device))[0]  
  55.  
  56. # Concatenated embeddings
  57. text_embeddings = torch.cat([uncond_embeddings, text_embeddings])
  58. text_b_embeddings = torch.cat([uncond_embeddings, text_b_embeddings])
  59.  
  60. # Initial random noise
  61. latents = torch.randn(
  62.     (batch_size, unet.in_channels, height // 8, width // 8),
  63.     generator=generator,
  64. )
  65. latents = latents.to(torch_device)
  66.  
  67. # Scheduler setup
  68. scheduler.set_timesteps(num_inference_steps)
  69.  
  70. # The K-LMS scheduler needs to multiply the latents by its sigma values.
  71. latents = latents * scheduler.sigmas[0]
  72. latents_b = latents
  73.  
  74. from diffusers.models.attention import CrossAttention, AttentionBlock, BasicTransformerBlock
  75. import types
  76.  
  77. glob_save_att_map = None
  78. glob_use_att_map = None
  79. glob_att_layer_index = 0
  80.  
  81. def crossattn_attention(self, query, key, value, sequence_length, dim):
  82.     global glob_save_att_map, glob_use_att_map, glob_att_layer_index
  83.  
  84.     batch_size_attention = query.shape[0]
  85.     hidden_states = torch.zeros(
  86.         (batch_size_attention, sequence_length, dim // self.heads), device=query.device, dtype=query.dtype
  87.     )
  88.     slice_size = self._slice_size if self._slice_size is not None else hidden_states.shape[0]
  89.     for i in range(hidden_states.shape[0] // slice_size):
  90.         start_idx = i * slice_size
  91.         end_idx = (i + 1) * slice_size
  92.         if dim == 1280 or dim == 640:
  93.             if glob_use_att_map is not None:
  94.                 attn_slice = glob_use_att_map[glob_att_layer_index]
  95.             else:
  96.                 attn_slice = torch.matmul(query[start_idx:end_idx], key[start_idx:end_idx].transpose(1, 2)) * self.scale
  97.                 attn_slice = attn_slice.softmax(dim=-1)
  98.                 if glob_save_att_map is not None:
  99.                     glob_save_att_map.append(attn_slice)
  100.             glob_att_layer_index = glob_att_layer_index+1
  101.         else:
  102.             attn_slice = torch.matmul(query[start_idx:end_idx], key[start_idx:end_idx].transpose(1, 2)) * self.scale
  103.             attn_slice = attn_slice.softmax(dim=-1)
  104.            
  105.         attn_slice = torch.matmul(attn_slice, value[start_idx:end_idx])
  106.  
  107.         hidden_states[start_idx:end_idx] = attn_slice
  108.  
  109.     # reshape hidden_states
  110.     hidden_states = self.reshape_batch_dim_to_heads(hidden_states)
  111.  
  112.     return hidden_states
  113.  
  114. def replace_attention(model):
  115.     for module in model.modules():
  116.         if isinstance(module, BasicTransformerBlock):
  117.             module.attn2._attention = types.MethodType(crossattn_attention, module.attn2)
  118.             module.attn1._attention = types.MethodType(crossattn_attention, module.attn1)
  119.  
  120. replace_attention(unet)
  121.  
  122. scheduler.set_timesteps(num_inference_steps)
  123. scheduler_b.set_timesteps(num_inference_steps)
  124.  
  125. from PIL import Image
  126.  
  127. def step(i, t, latents, text_embeddings, scheduler, use_attmap=None, save_attmap=False):
  128.     global glob_save_att_map, glob_use_att_map, glob_att_layer_index
  129.  
  130.     # expand the latents if we are doing classifier-free guidance to avoid doing two forward passes.
  131.     latent_model_input = torch.cat([latents] * 2)
  132.     sigma = scheduler.sigmas[i]
  133.     latent_model_input = latent_model_input / ((sigma**2 + 1) ** 0.5)
  134.  
  135.     glob_save_att_map = [] if save_attmap else None
  136.  
  137.     glob_att_layer_index = 0
  138.     if use_attmap is not None:
  139.         glob_use_att_map = use_attmap
  140.     else:
  141.         glob_use_att_map = None
  142.  
  143.     # predict the noise residual
  144.     with torch.no_grad():
  145.       noise_pred = unet(latent_model_input, t, encoder_hidden_states=text_embeddings).sample
  146.  
  147.     result_attmap = glob_save_att_map
  148.     glob_save_att_map = None
  149.  
  150.     # perform guidance
  151.     noise_pred_uncond, noise_pred_text = noise_pred.chunk(2)
  152.     noise_pred = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond)
  153.  
  154.     # compute the previous noisy sample x_t -> x_t-1
  155.     latents = scheduler.step(noise_pred, i, latents).prev_sample
  156.  
  157.     return latents, result_attmap
  158.  
  159. def decodeImage(latents):
  160.     latents = 1 / 0.18215 * latents
  161.     image = vae.decode(latents).sample
  162.  
  163.     image = (image / 2 + 0.5).clamp(0, 1)
  164.     image = image.detach().cpu().permute(0, 2, 3, 1).numpy()
  165.     images = (image * 255).round().astype("uint8")
  166.     pil_images = [Image.fromarray(image) for image in images]
  167.     return pil_images
  168.  
  169. def saveImage(latents, suffix):
  170.     pil_images = decodeImage(latents)
  171.     pil_images[0].save(f"C:\\Projects\\SD\\attmap\\{suffix}.png")
  172.  
  173. from tqdm.auto import tqdm
  174.  
  175. with torch.autocast("cuda"):
  176.     for i, t in tqdm(enumerate(scheduler.timesteps)):
  177.         latents, attmap = step(i, t, latents, text_embeddings, scheduler, use_attmap=None, save_attmap=True)
  178.         if i < (num_inference_steps * 0.75):
  179.             latents_b, _ = step(i, t, latents_b, text_b_embeddings, scheduler_b, use_attmap=attmap)
  180.         else:
  181.             latents_b, _ = step(i, t, latents_b, text_b_embeddings, scheduler_b)
  182.  
  183.     saveImage(latents, "a")
  184.     del latents
  185.     saveImage(latents_b, "b")
  186.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement