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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# -*- coding: utf-8 -*-
|
| 2 |
+
"""Copy of Copy_of_stable_diffusion.ipynb
|
| 3 |
+
|
| 4 |
+
Automatically generated by Colaboratory.
|
| 5 |
+
|
| 6 |
+
Original file is located at
|
| 7 |
+
https://colab.research.google.com/drive/1BL1N7XfktS-i3v6tNPHSMxvRh_IZctQ_
|
| 8 |
+
"""
|
| 9 |
+
|
| 10 |
+
!pip install diffusers==0.11.1
|
| 11 |
+
!pip install transformers scipy ftfy accelerate
|
| 12 |
+
|
| 13 |
+
import torch
|
| 14 |
+
from diffusers import StableDiffusionPipeline
|
| 15 |
+
|
| 16 |
+
pipe = StableDiffusionPipeline.from_pretrained("CompVis/stable-diffusion-v1-4", torch_dtype=torch.float16)
|
| 17 |
+
|
| 18 |
+
"""Next, let's move the pipeline to GPU to have faster inference."""
|
| 19 |
+
|
| 20 |
+
pipe = pipe.to("cuda")
|
| 21 |
+
|
| 22 |
+
prompt = "a photograph of an astronaut riding a horse"
|
| 23 |
+
image = pipe(prompt).images[0] # image here is in [PIL format](https://pillow.readthedocs.io/en/stable/)
|
| 24 |
+
|
| 25 |
+
# Now to display an image you can either save it such as:
|
| 26 |
+
image.save(f"astronaut_rides_horse.png")
|
| 27 |
+
|
| 28 |
+
# or if you're in a google colab you can directly display it with
|
| 29 |
+
image
|
| 30 |
+
|
| 31 |
+
import torch
|
| 32 |
+
|
| 33 |
+
generator = torch.Generator("cuda").manual_seed(1024)
|
| 34 |
+
|
| 35 |
+
image = pipe(prompt, generator=generator).images[0]
|
| 36 |
+
|
| 37 |
+
image
|
| 38 |
+
|
| 39 |
+
import torch
|
| 40 |
+
|
| 41 |
+
generator = torch.Generator("cuda").manual_seed(1024)
|
| 42 |
+
|
| 43 |
+
image = pipe(prompt, num_inference_steps=15, generator=generator).images[0]
|
| 44 |
+
|
| 45 |
+
image
|
| 46 |
+
|
| 47 |
+
from PIL import Image
|
| 48 |
+
|
| 49 |
+
def image_grid(imgs, rows, cols):
|
| 50 |
+
assert len(imgs) == rows*cols
|
| 51 |
+
|
| 52 |
+
w, h = imgs[0].size
|
| 53 |
+
grid = Image.new('RGB', size=(cols*w, rows*h))
|
| 54 |
+
grid_w, grid_h = grid.size
|
| 55 |
+
|
| 56 |
+
for i, img in enumerate(imgs):
|
| 57 |
+
grid.paste(img, box=(i%cols*w, i//cols*h))
|
| 58 |
+
return grid
|
| 59 |
+
|
| 60 |
+
num_images = 3
|
| 61 |
+
prompt = ["a photograph of an astronaut riding a horse"] * num_images
|
| 62 |
+
|
| 63 |
+
images = pipe(prompt).images
|
| 64 |
+
|
| 65 |
+
grid = image_grid(images, rows=1, cols=3)
|
| 66 |
+
grid
|
| 67 |
+
|
| 68 |
+
"""And here's how to generate a grid of `n × m` images."""
|
| 69 |
+
|
| 70 |
+
num_cols = 3
|
| 71 |
+
num_rows = 4
|
| 72 |
+
|
| 73 |
+
prompt = ["a photograph of an astronaut riding a horse"] * num_cols
|
| 74 |
+
|
| 75 |
+
all_images = []
|
| 76 |
+
for i in range(num_rows):
|
| 77 |
+
images = pipe(prompt).images
|
| 78 |
+
all_images.extend(images)
|
| 79 |
+
|
| 80 |
+
grid = image_grid(all_images, rows=num_rows, cols=num_cols)
|
| 81 |
+
grid
|
| 82 |
+
|
| 83 |
+
prompt = "a photograph of an astronaut riding a horse"
|
| 84 |
+
|
| 85 |
+
image = pipe(prompt, height=512, width=768).images[0]
|
| 86 |
+
image
|
| 87 |
+
|
| 88 |
+
"""
|
| 89 |
+
|
| 90 |
+
After this brief introduction to Latent and Stable Diffusion, let's see how to make advanced use of 🤗 Hugging Face Diffusers!"""
|
| 91 |
+
|
| 92 |
+
import torch
|
| 93 |
+
torch_device = "cuda" if torch.cuda.is_available() else "cpu"
|
| 94 |
+
|
| 95 |
+
from transformers import CLIPTextModel, CLIPTokenizer
|
| 96 |
+
from diffusers import AutoencoderKL, UNet2DConditionModel, PNDMScheduler
|
| 97 |
+
|
| 98 |
+
# 1. Load the autoencoder model which will be used to decode the latents into image space.
|
| 99 |
+
vae = AutoencoderKL.from_pretrained("CompVis/stable-diffusion-v1-4", subfolder="vae")
|
| 100 |
+
|
| 101 |
+
# 2. Load the tokenizer and text encoder to tokenize and encode the text.
|
| 102 |
+
tokenizer = CLIPTokenizer.from_pretrained("openai/clip-vit-large-patch14")
|
| 103 |
+
text_encoder = CLIPTextModel.from_pretrained("openai/clip-vit-large-patch14")
|
| 104 |
+
|
| 105 |
+
# 3. The UNet model for generating the latents.
|
| 106 |
+
unet = UNet2DConditionModel.from_pretrained("CompVis/stable-diffusion-v1-4", subfolder="unet")
|
| 107 |
+
|
| 108 |
+
"""Now instead of loading the pre-defined scheduler, we'll use the K-LMS scheduler instead."""
|
| 109 |
+
|
| 110 |
+
from diffusers import LMSDiscreteScheduler
|
| 111 |
+
|
| 112 |
+
scheduler = LMSDiscreteScheduler.from_pretrained("CompVis/stable-diffusion-v1-4", subfolder="scheduler")
|
| 113 |
+
|
| 114 |
+
vae = vae.to(torch_device)
|
| 115 |
+
text_encoder = text_encoder.to(torch_device)
|
| 116 |
+
unet = unet.to(torch_device)
|
| 117 |
+
|
| 118 |
+
prompt = ["a photograph of an astronaut riding a horse"]
|
| 119 |
+
|
| 120 |
+
height = 512 # default height of Stable Diffusion
|
| 121 |
+
width = 512 # default width of Stable Diffusion
|
| 122 |
+
|
| 123 |
+
num_inference_steps = 100 # Number of denoising steps
|
| 124 |
+
|
| 125 |
+
guidance_scale = 7.5 # Scale for classifier-free guidance
|
| 126 |
+
|
| 127 |
+
generator = torch.manual_seed(32) # Seed generator to create the inital latent noise
|
| 128 |
+
|
| 129 |
+
batch_size = 1
|
| 130 |
+
|
| 131 |
+
text_input = tokenizer(prompt, padding="max_length", max_length=tokenizer.model_max_length, truncation=True, return_tensors="pt")
|
| 132 |
+
|
| 133 |
+
with torch.no_grad():
|
| 134 |
+
text_embeddings = text_encoder(text_input.input_ids.to(torch_device))[0]
|
| 135 |
+
|
| 136 |
+
max_length = text_input.input_ids.shape[-1]
|
| 137 |
+
uncond_input = tokenizer(
|
| 138 |
+
[""] * batch_size, padding="max_length", max_length=max_length, return_tensors="pt"
|
| 139 |
+
)
|
| 140 |
+
with torch.no_grad():
|
| 141 |
+
uncond_embeddings = text_encoder(uncond_input.input_ids.to(torch_device))[0]
|
| 142 |
+
|
| 143 |
+
text_embeddings = torch.cat([uncond_embeddings, text_embeddings])
|
| 144 |
+
|
| 145 |
+
latents = torch.randn(
|
| 146 |
+
(batch_size, unet.in_channels, height // 8, width // 8),
|
| 147 |
+
generator=generator,
|
| 148 |
+
)
|
| 149 |
+
latents = latents.to(torch_device)
|
| 150 |
+
|
| 151 |
+
latents.shape
|
| 152 |
+
|
| 153 |
+
scheduler.set_timesteps(num_inference_steps)
|
| 154 |
+
|
| 155 |
+
latents = latents * scheduler.init_noise_sigma
|
| 156 |
+
|
| 157 |
+
from tqdm.auto import tqdm
|
| 158 |
+
from torch import autocast
|
| 159 |
+
|
| 160 |
+
for t in tqdm(scheduler.timesteps):
|
| 161 |
+
# expand the latents if we are doing classifier-free guidance to avoid doing two forward passes.
|
| 162 |
+
latent_model_input = torch.cat([latents] * 2)
|
| 163 |
+
|
| 164 |
+
latent_model_input = scheduler.scale_model_input(latent_model_input, t)
|
| 165 |
+
|
| 166 |
+
# predict the noise residual
|
| 167 |
+
with torch.no_grad():
|
| 168 |
+
noise_pred = unet(latent_model_input, t, encoder_hidden_states=text_embeddings).sample
|
| 169 |
+
|
| 170 |
+
# perform guidance
|
| 171 |
+
noise_pred_uncond, noise_pred_text = noise_pred.chunk(2)
|
| 172 |
+
noise_pred = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond)
|
| 173 |
+
|
| 174 |
+
# compute the previous noisy sample x_t -> x_t-1
|
| 175 |
+
latents = scheduler.step(noise_pred, t, latents).prev_sample
|
| 176 |
+
|
| 177 |
+
# scale and decode the image latents with vae
|
| 178 |
+
latents = 1 / 0.18215 * latents
|
| 179 |
+
|
| 180 |
+
with torch.no_grad():
|
| 181 |
+
image = vae.decode(latents).sample
|
| 182 |
+
|
| 183 |
+
image = (image / 2 + 0.5).clamp(0, 1)
|
| 184 |
+
image = image.detach().cpu().permute(0, 2, 3, 1).numpy()
|
| 185 |
+
images = (image * 255).round().astype("uint8")
|
| 186 |
+
pil_images = [Image.fromarray(image) for image in images]
|
| 187 |
+
pil_images[0]
|
| 188 |
+
|