Shuang59 nanliu commited on
Commit
e1eae4e
β€’
1 Parent(s): 0773c5a

Upload composable_stable_diffusion_pipeline.py (#8)

Browse files

- Upload composable_stable_diffusion_pipeline.py (507b3df142f340495689824f047f48559d10d52b)


Co-authored-by: Nan Liu <nanliu@users.noreply.huggingface.co>

composable_stable_diffusion_pipeline.py ADDED
@@ -0,0 +1,172 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ modified based on https://github.com/nanlliu/diffusers/blob/866af5d9af94568079f76567382e90154d98e2f8/src/diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion.py
3
+ """
4
+ import inspect
5
+ import warnings
6
+ from typing import List, Optional, Union
7
+
8
+ import torch
9
+
10
+ from tqdm.auto import tqdm
11
+ from transformers import CLIPFeatureExtractor, CLIPTextModel, CLIPTokenizer
12
+
13
+ from diffusers.models import AutoencoderKL, UNet2DConditionModel
14
+ from diffusers.pipeline_utils import DiffusionPipeline
15
+ from diffusers.schedulers import DDIMScheduler, LMSDiscreteScheduler, PNDMScheduler
16
+ from safety_checker import StableDiffusionSafetyChecker
17
+
18
+
19
+ class ComposableStableDiffusionPipeline(DiffusionPipeline):
20
+ def __init__(
21
+ self,
22
+ vae: AutoencoderKL,
23
+ text_encoder: CLIPTextModel,
24
+ tokenizer: CLIPTokenizer,
25
+ unet: UNet2DConditionModel,
26
+ scheduler: Union[DDIMScheduler, PNDMScheduler, LMSDiscreteScheduler],
27
+ safety_checker: StableDiffusionSafetyChecker,
28
+ feature_extractor: CLIPFeatureExtractor,
29
+ ):
30
+ super().__init__()
31
+ scheduler = scheduler.set_format("pt")
32
+ self.register_modules(
33
+ vae=vae,
34
+ text_encoder=text_encoder,
35
+ tokenizer=tokenizer,
36
+ unet=unet,
37
+ scheduler=scheduler,
38
+ safety_checker=safety_checker,
39
+ feature_extractor=feature_extractor,
40
+ )
41
+
42
+ @torch.no_grad()
43
+ def __call__(
44
+ self,
45
+ prompt: Union[str, List[str]],
46
+ height: Optional[int] = 512,
47
+ width: Optional[int] = 512,
48
+ num_inference_steps: Optional[int] = 50,
49
+ guidance_scale: Optional[float] = 7.5,
50
+ eta: Optional[float] = 0.0,
51
+ generator: Optional[torch.Generator] = None,
52
+ output_type: Optional[str] = "pil",
53
+ **kwargs,
54
+ ):
55
+ if "torch_device" in kwargs:
56
+ device = kwargs.pop("torch_device")
57
+ warnings.warn(
58
+ "`torch_device` is deprecated as an input argument to `__call__` and will be removed in v0.3.0."
59
+ " Consider using `pipe.to(torch_device)` instead."
60
+ )
61
+
62
+ # Set device as before (to be removed in 0.3.0)
63
+ if device is None:
64
+ device = "cuda" if torch.cuda.is_available() else "cpu"
65
+ self.to(device)
66
+
67
+ if isinstance(prompt, str):
68
+ batch_size = 1
69
+ elif isinstance(prompt, list):
70
+ batch_size = len(prompt)
71
+ else:
72
+ raise ValueError(f"`prompt` has to be of type `str` or `list` but is {type(prompt)}")
73
+
74
+ if height % 8 != 0 or width % 8 != 0:
75
+ raise ValueError(f"`height` and `width` have to be divisible by 8 but are {height} and {width}.")
76
+
77
+ if '|' in prompt:
78
+ prompt = [x.strip() for x in prompt.split('|')]
79
+ print(prompt)
80
+
81
+ # get prompt text embeddings
82
+ text_input = self.tokenizer(
83
+ prompt,
84
+ padding="max_length",
85
+ max_length=self.tokenizer.model_max_length,
86
+ truncation=True,
87
+ return_tensors="pt",
88
+ )
89
+ text_embeddings = self.text_encoder(text_input.input_ids.to(self.device))[0]
90
+
91
+ # here `guidance_scale` is defined analog to the guidance weight `w` of equation (2)
92
+ # of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1`
93
+ # corresponds to doing no classifier free guidance.
94
+ do_classifier_free_guidance = guidance_scale > 1.0
95
+ # get unconditional embeddings for classifier free guidance
96
+ if do_classifier_free_guidance:
97
+ max_length = text_input.input_ids.shape[-1]
98
+ uncond_input = self.tokenizer(
99
+ [""] * batch_size, padding="max_length", max_length=max_length, return_tensors="pt"
100
+ )
101
+ uncond_embeddings = self.text_encoder(uncond_input.input_ids.to(self.device))[0]
102
+
103
+ # For classifier free guidance, we need to do two forward passes.
104
+ # Here we concatenate the unconditional and text embeddings into a single batch
105
+ # to avoid doing two forward passes
106
+ text_embeddings = torch.cat([uncond_embeddings, text_embeddings])
107
+
108
+ # get the intial random noise
109
+ latents = torch.randn(
110
+ (batch_size, self.unet.in_channels, height // 8, width // 8),
111
+ generator=generator,
112
+ device=self.device,
113
+ )
114
+
115
+ # set timesteps
116
+ accepts_offset = "offset" in set(inspect.signature(self.scheduler.set_timesteps).parameters.keys())
117
+ extra_set_kwargs = {}
118
+ if accepts_offset:
119
+ extra_set_kwargs["offset"] = 1
120
+
121
+ self.scheduler.set_timesteps(num_inference_steps, **extra_set_kwargs)
122
+
123
+ # if we use LMSDiscreteScheduler, let's make sure latents are mulitplied by sigmas
124
+ if isinstance(self.scheduler, LMSDiscreteScheduler):
125
+ latents = latents * self.scheduler.sigmas[0]
126
+
127
+ # prepare extra kwargs for the scheduler step, since not all schedulers have the same signature
128
+ # eta (Ξ·) is only used with the DDIMScheduler, it will be ignored for other schedulers.
129
+ # eta corresponds to Ξ· in DDIM paper: https://arxiv.org/abs/2010.02502
130
+ # and should be between [0, 1]
131
+ accepts_eta = "eta" in set(inspect.signature(self.scheduler.step).parameters.keys())
132
+ extra_step_kwargs = {}
133
+ if accepts_eta:
134
+ extra_step_kwargs["eta"] = eta
135
+
136
+ for i, t in tqdm(enumerate(self.scheduler.timesteps)):
137
+ # expand the latents if we are doing classifier free guidance
138
+ latent_model_input = torch.cat([latents] * text_embeddings.shape[0]) if do_classifier_free_guidance else latents
139
+ if isinstance(self.scheduler, LMSDiscreteScheduler):
140
+ sigma = self.scheduler.sigmas[i]
141
+ latent_model_input = latent_model_input / ((sigma**2 + 1) ** 0.5)
142
+
143
+ # predict the noise residual
144
+ noise_pred = self.unet(latent_model_input, t, encoder_hidden_states=text_embeddings)["sample"]
145
+
146
+ # perform guidance
147
+ if do_classifier_free_guidance:
148
+ pred_decomp = noise_pred.chunk(text_embeddings.shape[0])
149
+ noise_pred_uncond, noise_pred_text = pred_decomp[0], torch.cat(pred_decomp[1:], dim=0).mean(dim=0, keepdim=True)
150
+ noise_pred = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond)
151
+
152
+ # compute the previous noisy sample x_t -> x_t-1
153
+ if isinstance(self.scheduler, LMSDiscreteScheduler):
154
+ latents = self.scheduler.step(noise_pred, i, latents, **extra_step_kwargs)["prev_sample"]
155
+ else:
156
+ latents = self.scheduler.step(noise_pred, t, latents, **extra_step_kwargs)["prev_sample"]
157
+
158
+ # scale and decode the image latents with vae
159
+ latents = 1 / 0.18215 * latents
160
+ image = self.vae.decode(latents)
161
+
162
+ image = (image / 2 + 0.5).clamp(0, 1)
163
+ image = image.cpu().permute(0, 2, 3, 1).numpy()
164
+
165
+ # run safety checker
166
+ safety_cheker_input = self.feature_extractor(self.numpy_to_pil(image), return_tensors="pt").to(self.device)
167
+ image, has_nsfw_concept = self.safety_checker(images=image, clip_input=safety_cheker_input.pixel_values)
168
+
169
+ if output_type == "pil":
170
+ image = self.numpy_to_pil(image)
171
+
172
+ return {"sample": image, "nsfw_content_detected": has_nsfw_concept}