Shuang59 commited on
Commit
38e2e7e
β€’
1 Parent(s): 4ab31f0

Delete composable_stable_diffusion_pipeline.py

Browse files
composable_stable_diffusion_pipeline.py DELETED
@@ -1,357 +0,0 @@
1
- """
2
- modified based on diffusion library from Huggingface: https://github.com/huggingface/diffusers/blob/main/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
- from dataclasses import dataclass
19
- from typing import List, Union
20
-
21
- import numpy as np
22
-
23
- import PIL
24
-
25
- from diffusers.utils import BaseOutput
26
-
27
-
28
- @dataclass
29
- class StableDiffusionPipelineOutput(BaseOutput):
30
- """
31
- Output class for Stable Diffusion pipelines.
32
- Args:
33
- images (`List[PIL.Image.Image]` or `np.ndarray`)
34
- List of denoised PIL images of length `batch_size` or numpy array of shape `(batch_size, height, width,
35
- num_channels)`. PIL images or numpy array present the denoised images of the diffusion pipeline.
36
- nsfw_content_detected (`List[bool]`)
37
- List of flags denoting whether the corresponding generated image likely represents "not-safe-for-work"
38
- (nsfw) content.
39
- """
40
-
41
- images: Union[List[PIL.Image.Image], np.ndarray]
42
- nsfw_content_detected: List[bool]
43
-
44
- class ComposableStableDiffusionPipeline(DiffusionPipeline):
45
- r"""
46
- Pipeline for text-to-image generation using Stable Diffusion.
47
-
48
- This model inherits from [`DiffusionPipeline`]. Check the superclass documentation for the generic methods the
49
- library implements for all the pipelines (such as downloading or saving, running on a particular device, etc.)
50
-
51
- Args:
52
- vae ([`AutoencoderKL`]):
53
- Variational Auto-Encoder (VAE) Model to encode and decode images to and from latent representations.
54
- text_encoder ([`CLIPTextModel`]):
55
- Frozen text-encoder. Stable Diffusion uses the text portion of
56
- [CLIP](https://huggingface.co/docs/transformers/model_doc/clip#transformers.CLIPTextModel), specifically
57
- the [clip-vit-large-patch14](https://huggingface.co/openai/clip-vit-large-patch14) variant.
58
- tokenizer (`CLIPTokenizer`):
59
- Tokenizer of class
60
- [CLIPTokenizer](https://huggingface.co/docs/transformers/v4.21.0/en/model_doc/clip#transformers.CLIPTokenizer).
61
- unet ([`UNet2DConditionModel`]): Conditional U-Net architecture to denoise the encoded image latents.
62
- scheduler ([`SchedulerMixin`]):
63
- A scheduler to be used in combination with `unet` to denoise the encoded image latens. Can be one of
64
- [`DDIMScheduler`], [`LMSDiscreteScheduler`], or [`PNDMScheduler`].
65
- safety_checker ([`StableDiffusionSafetyChecker`]):
66
- Classification module that estimates whether generated images could be considered offsensive or harmful.
67
- Please, refer to the [model card](https://huggingface.co/CompVis/stable-diffusion-v1-4) for details.
68
- feature_extractor ([`CLIPFeatureExtractor`]):
69
- Model that extracts features from generated images to be used as inputs for the `safety_checker`.
70
- """
71
-
72
- def __init__(
73
- self,
74
- vae: AutoencoderKL,
75
- text_encoder: CLIPTextModel,
76
- tokenizer: CLIPTokenizer,
77
- unet: UNet2DConditionModel,
78
- scheduler: Union[DDIMScheduler, PNDMScheduler, LMSDiscreteScheduler],
79
- safety_checker: StableDiffusionSafetyChecker,
80
- feature_extractor: CLIPFeatureExtractor,
81
- ):
82
- super().__init__()
83
- self.register_modules(
84
- vae=vae,
85
- text_encoder=text_encoder,
86
- tokenizer=tokenizer,
87
- unet=unet,
88
- scheduler=scheduler,
89
- safety_checker=safety_checker,
90
- feature_extractor=feature_extractor,
91
- )
92
-
93
- def enable_attention_slicing(self, slice_size: Optional[Union[str, int]] = "auto"):
94
- r"""
95
- Enable sliced attention computation.
96
-
97
- When this option is enabled, the attention module will split the input tensor in slices, to compute attention
98
- in several steps. This is useful to save some memory in exchange for a small speed decrease.
99
-
100
- Args:
101
- slice_size (`str` or `int`, *optional*, defaults to `"auto"`):
102
- When `"auto"`, halves the input to the attention heads, so attention will be computed in two steps. If
103
- a number is provided, uses as many slices as `attention_head_dim // slice_size`. In this case,
104
- `attention_head_dim` must be a multiple of `slice_size`.
105
- """
106
- if slice_size == "auto":
107
- # half the attention head size is usually a good trade-off between
108
- # speed and memory
109
- slice_size = self.unet.config.attention_head_dim // 2
110
- self.unet.set_attention_slice(slice_size)
111
-
112
- def disable_attention_slicing(self):
113
- r"""
114
- Disable sliced attention computation. If `enable_attention_slicing` was previously invoked, this method will go
115
- back to computing attention in one step.
116
- """
117
- # set slice_size = `None` to disable `attention slicing`
118
- self.enable_attention_slicing(None)
119
-
120
- @torch.no_grad()
121
- def __call__(
122
- self,
123
- prompt: Union[str, List[str]],
124
- height: Optional[int] = 512,
125
- width: Optional[int] = 512,
126
- num_inference_steps: Optional[int] = 50,
127
- guidance_scale: Optional[float] = 7.5,
128
- eta: Optional[float] = 0.0,
129
- generator: Optional[torch.Generator] = None,
130
- latents: Optional[torch.FloatTensor] = None,
131
- output_type: Optional[str] = "pil",
132
- return_dict: bool = True,
133
- weights: Optional[str] = "",
134
- **kwargs,
135
- ):
136
- r"""
137
- Function invoked when calling the pipeline for generation.
138
-
139
- Args:
140
- prompt (`str` or `List[str]`):
141
- The prompt or prompts to guide the image generation.
142
- height (`int`, *optional*, defaults to 512):
143
- The height in pixels of the generated image.
144
- width (`int`, *optional*, defaults to 512):
145
- The width in pixels of the generated image.
146
- num_inference_steps (`int`, *optional*, defaults to 50):
147
- The number of denoising steps. More denoising steps usually lead to a higher quality image at the
148
- expense of slower inference.
149
- guidance_scale (`float`, *optional*, defaults to 7.5):
150
- Guidance scale as defined in [Classifier-Free Diffusion Guidance](https://arxiv.org/abs/2207.12598).
151
- `guidance_scale` is defined as `w` of equation 2. of [Imagen
152
- Paper](https://arxiv.org/pdf/2205.11487.pdf). Guidance scale is enabled by setting `guidance_scale >
153
- 1`. Higher guidance scale encourages to generate images that are closely linked to the text `prompt`,
154
- usually at the expense of lower image quality.
155
- eta (`float`, *optional*, defaults to 0.0):
156
- Corresponds to parameter eta (Ξ·) in the DDIM paper: https://arxiv.org/abs/2010.02502. Only applies to
157
- [`schedulers.DDIMScheduler`], will be ignored for others.
158
- generator (`torch.Generator`, *optional*):
159
- A [torch generator](https://pytorch.org/docs/stable/generated/torch.Generator.html) to make generation
160
- deterministic.
161
- latents (`torch.FloatTensor`, *optional*):
162
- Pre-generated noisy latents, sampled from a Gaussian distribution, to be used as inputs for image
163
- generation. Can be used to tweak the same generation with different prompts. If not provided, a latents
164
- tensor will ge generated by sampling using the supplied random `generator`.
165
- output_type (`str`, *optional*, defaults to `"pil"`):
166
- The output format of the generate image. Choose between
167
- [PIL](https://pillow.readthedocs.io/en/stable/): `PIL.Image.Image` or `nd.array`.
168
- return_dict (`bool`, *optional*, defaults to `True`):
169
- Whether or not to return a [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] instead of a
170
- plain tuple.
171
-
172
- Returns:
173
- [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] or `tuple`:
174
- [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] if `return_dict` is True, otherwise a `tuple.
175
- When returning a tuple, the first element is a list with the generated images, and the second element is a
176
- list of `bool`s denoting whether the corresponding generated image likely represents "not-safe-for-work"
177
- (nsfw) content, according to the `safety_checker`.
178
- """
179
-
180
- if "torch_device" in kwargs:
181
- device = kwargs.pop("torch_device")
182
- warnings.warn(
183
- "`torch_device` is deprecated as an input argument to `__call__` and will be removed in v0.3.0."
184
- " Consider using `pipe.to(torch_device)` instead."
185
- )
186
-
187
- # Set device as before (to be removed in 0.3.0)
188
- if device is None:
189
- device = "cuda" if torch.cuda.is_available() else "cpu"
190
- self.to(device)
191
-
192
- if isinstance(prompt, str):
193
- batch_size = 1
194
- elif isinstance(prompt, list):
195
- batch_size = len(prompt)
196
- else:
197
- raise ValueError(f"`prompt` has to be of type `str` or `list` but is {type(prompt)}")
198
-
199
- if height % 8 != 0 or width % 8 != 0:
200
- raise ValueError(f"`height` and `width` have to be divisible by 8 but are {height} and {width}.")
201
-
202
- if '|' in prompt:
203
- prompt = [x.strip() for x in prompt.split('|')]
204
- print(f"composing {prompt}...")
205
-
206
- # get prompt text embeddings
207
- text_input = self.tokenizer(
208
- prompt,
209
- padding="max_length",
210
- max_length=self.tokenizer.model_max_length,
211
- truncation=True,
212
- return_tensors="pt",
213
- )
214
- text_embeddings = self.text_encoder(text_input.input_ids.to(self.device))[0]
215
-
216
- if not weights:
217
- # specify weights for prompts (excluding the unconditional score)
218
- print('using equal weights for all prompts...')
219
- pos_weights = torch.tensor([1 / (text_embeddings.shape[0] - 1)] * (text_embeddings.shape[0] - 1),
220
- device=self.device).reshape(-1, 1, 1, 1)
221
- neg_weights = torch.tensor([1.], device=self.device).reshape(-1, 1, 1, 1)
222
- mask = torch.tensor([False] + [True] * pos_weights.shape[0], dtype=torch.bool)
223
- else:
224
- # set prompt weight for each
225
- num_prompts = len(prompt) if isinstance(prompt, list) else 1
226
- weights = [float(w.strip()) for w in weights.split("|")]
227
- if len(weights) < num_prompts:
228
- weights.append(1.)
229
- weights = torch.tensor(weights, device=self.device)
230
- assert len(weights) == text_embeddings.shape[0], "weights specified are not equal to the number of prompts"
231
- pos_weights = []
232
- neg_weights = []
233
- mask = [] # first one is unconditional score
234
- for w in weights:
235
- if w > 0:
236
- pos_weights.append(w)
237
- mask.append(True)
238
- else:
239
- neg_weights.append(abs(w))
240
- mask.append(False)
241
- # normalize the weights
242
- pos_weights = torch.tensor(pos_weights, device=self.device).reshape(-1, 1, 1, 1)
243
- pos_weights = pos_weights / pos_weights.sum()
244
- neg_weights = torch.tensor(neg_weights, device=self.device).reshape(-1, 1, 1, 1)
245
- neg_weights = neg_weights / neg_weights.sum()
246
- mask = torch.tensor(mask, device=self.device, dtype=torch.bool)
247
-
248
- # here `guidance_scale` is defined analog to the guidance weight `w` of equation (2)
249
- # of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1`
250
- # corresponds to doing no classifier free guidance.
251
- do_classifier_free_guidance = guidance_scale > 1.0
252
- # get unconditional embeddings for classifier free guidance
253
- if do_classifier_free_guidance:
254
- max_length = text_input.input_ids.shape[-1]
255
-
256
- if torch.all(mask):
257
- # no negative prompts, so we use empty string as the negative prompt
258
- uncond_input = self.tokenizer(
259
- [""] * batch_size, padding="max_length", max_length=max_length, return_tensors="pt"
260
- )
261
- uncond_embeddings = self.text_encoder(uncond_input.input_ids.to(self.device))[0]
262
-
263
- # For classifier free guidance, we need to do two forward passes.
264
- # Here we concatenate the unconditional and text embeddings into a single batch
265
- # to avoid doing two forward passes
266
- text_embeddings = torch.cat([uncond_embeddings, text_embeddings])
267
-
268
- # update negative weights
269
- neg_weights = torch.tensor([1.], device=self.device)
270
- mask = torch.tensor([False] + mask.detach().tolist(), device=self.device, dtype=torch.bool)
271
-
272
- # get the initial random noise unless the user supplied it
273
-
274
- # Unlike in other pipelines, latents need to be generated in the target device
275
- # for 1-to-1 results reproducibility with the CompVis implementation.
276
- # However this currently doesn't work in `mps`.
277
- latents_device = "cpu" if self.device.type == "mps" else self.device
278
- latents_shape = (batch_size, self.unet.in_channels, height // 8, width // 8)
279
- if latents is None:
280
- latents = torch.randn(
281
- latents_shape,
282
- generator=generator,
283
- device=latents_device,
284
- )
285
- else:
286
- if latents.shape != latents_shape:
287
- raise ValueError(f"Unexpected latents shape, got {latents.shape}, expected {latents_shape}")
288
- latents = latents.to(self.device)
289
-
290
- # set timesteps
291
- accepts_offset = "offset" in set(inspect.signature(self.scheduler.set_timesteps).parameters.keys())
292
- extra_set_kwargs = {}
293
- if accepts_offset:
294
- extra_set_kwargs["offset"] = 1
295
-
296
- self.scheduler.set_timesteps(num_inference_steps, **extra_set_kwargs)
297
-
298
- # if we use LMSDiscreteScheduler, let's make sure latents are mulitplied by sigmas
299
- if isinstance(self.scheduler, LMSDiscreteScheduler):
300
- latents = latents * self.scheduler.sigmas[0]
301
-
302
- # prepare extra kwargs for the scheduler step, since not all schedulers have the same signature
303
- # eta (Ξ·) is only used with the DDIMScheduler, it will be ignored for other schedulers.
304
- # eta corresponds to Ξ· in DDIM paper: https://arxiv.org/abs/2010.02502
305
- # and should be between [0, 1]
306
- accepts_eta = "eta" in set(inspect.signature(self.scheduler.step).parameters.keys())
307
- extra_step_kwargs = {}
308
- if accepts_eta:
309
- extra_step_kwargs["eta"] = eta
310
-
311
- for i, t in enumerate(self.progress_bar(self.scheduler.timesteps)):
312
- # expand the latents if we are doing classifier free guidance
313
- latent_model_input = torch.cat([latents] * text_embeddings.shape[0]) if do_classifier_free_guidance else latents
314
- if isinstance(self.scheduler, LMSDiscreteScheduler):
315
- sigma = self.scheduler.sigmas[i]
316
- # the model input needs to be scaled to match the continuous ODE formulation in K-LMS
317
- latent_model_input = latent_model_input / ((sigma**2 + 1) ** 0.5)
318
-
319
- # reduce memory by predicting each score sequentially
320
- noise_preds = []
321
- # predict the noise residual
322
- for latent_in, text_embedding_in in zip(
323
- torch.chunk(latent_model_input, chunks=latent_model_input.shape[0], dim=0),
324
- torch.chunk(text_embeddings, chunks=text_embeddings.shape[0], dim=0)):
325
- noise_preds.append(self.unet(latent_in, t, encoder_hidden_states=text_embedding_in).sample)
326
- noise_preds = torch.cat(noise_preds, dim=0)
327
-
328
- # perform guidance
329
- if do_classifier_free_guidance:
330
- noise_pred_uncond = (noise_preds[~mask] * neg_weights).sum(dim=0, keepdims=True)
331
- noise_pred_text = (noise_preds[mask] * pos_weights).sum(dim=0, keepdims=True)
332
- noise_pred = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond)
333
-
334
- # compute the previous noisy sample x_t -> x_t-1
335
- if isinstance(self.scheduler, LMSDiscreteScheduler):
336
- latents = self.scheduler.step(noise_pred, i, latents, **extra_step_kwargs).prev_sample
337
- else:
338
- latents = self.scheduler.step(noise_pred, t, latents, **extra_step_kwargs).prev_sample
339
-
340
- # scale and decode the image latents with vae
341
- latents = 1 / 0.18215 * latents
342
- image = self.vae.decode(latents).sample
343
-
344
- image = (image / 2 + 0.5).clamp(0, 1)
345
- image = image.cpu().permute(0, 2, 3, 1).numpy()
346
-
347
- # run safety checker
348
- safety_cheker_input = self.feature_extractor(self.numpy_to_pil(image), return_tensors="pt").to(self.device)
349
- image, has_nsfw_concept = self.safety_checker(images=image, clip_input=safety_cheker_input.pixel_values)
350
-
351
- if output_type == "pil":
352
- image = self.numpy_to_pil(image)
353
-
354
- if not return_dict:
355
- return (image, has_nsfw_concept)
356
-
357
- return StableDiffusionPipelineOutput(images=image, nsfw_content_detected=has_nsfw_concept)