Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
shivamshrirao
GitHub Repository: shivamshrirao/diffusers
Path: blob/main/examples/community/stable_unclip.py
1448 views
1
import types
2
from typing import List, Optional, Tuple, Union
3
4
import torch
5
from transformers import CLIPTextModelWithProjection, CLIPTokenizer
6
from transformers.models.clip.modeling_clip import CLIPTextModelOutput
7
8
from diffusers.models import PriorTransformer
9
from diffusers.pipelines import DiffusionPipeline, StableDiffusionImageVariationPipeline
10
from diffusers.schedulers import UnCLIPScheduler
11
from diffusers.utils import logging, randn_tensor
12
13
14
logger = logging.get_logger(__name__) # pylint: disable=invalid-name
15
16
17
def _encode_image(self, image, device, num_images_per_prompt, do_classifier_free_guidance):
18
image = image.to(device=device)
19
image_embeddings = image # take image as image_embeddings
20
image_embeddings = image_embeddings.unsqueeze(1)
21
22
# duplicate image embeddings for each generation per prompt, using mps friendly method
23
bs_embed, seq_len, _ = image_embeddings.shape
24
image_embeddings = image_embeddings.repeat(1, num_images_per_prompt, 1)
25
image_embeddings = image_embeddings.view(bs_embed * num_images_per_prompt, seq_len, -1)
26
27
if do_classifier_free_guidance:
28
uncond_embeddings = torch.zeros_like(image_embeddings)
29
30
# For classifier free guidance, we need to do two forward passes.
31
# Here we concatenate the unconditional and text embeddings into a single batch
32
# to avoid doing two forward passes
33
image_embeddings = torch.cat([uncond_embeddings, image_embeddings])
34
35
return image_embeddings
36
37
38
class StableUnCLIPPipeline(DiffusionPipeline):
39
def __init__(
40
self,
41
prior: PriorTransformer,
42
tokenizer: CLIPTokenizer,
43
text_encoder: CLIPTextModelWithProjection,
44
prior_scheduler: UnCLIPScheduler,
45
decoder_pipe_kwargs: Optional[dict] = None,
46
):
47
super().__init__()
48
49
decoder_pipe_kwargs = dict(image_encoder=None) if decoder_pipe_kwargs is None else decoder_pipe_kwargs
50
51
decoder_pipe_kwargs["torch_dtype"] = decoder_pipe_kwargs.get("torch_dtype", None) or prior.dtype
52
53
self.decoder_pipe = StableDiffusionImageVariationPipeline.from_pretrained(
54
"lambdalabs/sd-image-variations-diffusers", **decoder_pipe_kwargs
55
)
56
57
# replace `_encode_image` method
58
self.decoder_pipe._encode_image = types.MethodType(_encode_image, self.decoder_pipe)
59
60
self.register_modules(
61
prior=prior,
62
tokenizer=tokenizer,
63
text_encoder=text_encoder,
64
prior_scheduler=prior_scheduler,
65
)
66
67
def _encode_prompt(
68
self,
69
prompt,
70
device,
71
num_images_per_prompt,
72
do_classifier_free_guidance,
73
text_model_output: Optional[Union[CLIPTextModelOutput, Tuple]] = None,
74
text_attention_mask: Optional[torch.Tensor] = None,
75
):
76
if text_model_output is None:
77
batch_size = len(prompt) if isinstance(prompt, list) else 1
78
# get prompt text embeddings
79
text_inputs = self.tokenizer(
80
prompt,
81
padding="max_length",
82
max_length=self.tokenizer.model_max_length,
83
return_tensors="pt",
84
)
85
text_input_ids = text_inputs.input_ids
86
text_mask = text_inputs.attention_mask.bool().to(device)
87
88
if text_input_ids.shape[-1] > self.tokenizer.model_max_length:
89
removed_text = self.tokenizer.batch_decode(text_input_ids[:, self.tokenizer.model_max_length :])
90
logger.warning(
91
"The following part of your input was truncated because CLIP can only handle sequences up to"
92
f" {self.tokenizer.model_max_length} tokens: {removed_text}"
93
)
94
text_input_ids = text_input_ids[:, : self.tokenizer.model_max_length]
95
96
text_encoder_output = self.text_encoder(text_input_ids.to(device))
97
98
text_embeddings = text_encoder_output.text_embeds
99
text_encoder_hidden_states = text_encoder_output.last_hidden_state
100
101
else:
102
batch_size = text_model_output[0].shape[0]
103
text_embeddings, text_encoder_hidden_states = text_model_output[0], text_model_output[1]
104
text_mask = text_attention_mask
105
106
text_embeddings = text_embeddings.repeat_interleave(num_images_per_prompt, dim=0)
107
text_encoder_hidden_states = text_encoder_hidden_states.repeat_interleave(num_images_per_prompt, dim=0)
108
text_mask = text_mask.repeat_interleave(num_images_per_prompt, dim=0)
109
110
if do_classifier_free_guidance:
111
uncond_tokens = [""] * batch_size
112
113
uncond_input = self.tokenizer(
114
uncond_tokens,
115
padding="max_length",
116
max_length=self.tokenizer.model_max_length,
117
truncation=True,
118
return_tensors="pt",
119
)
120
uncond_text_mask = uncond_input.attention_mask.bool().to(device)
121
uncond_embeddings_text_encoder_output = self.text_encoder(uncond_input.input_ids.to(device))
122
123
uncond_embeddings = uncond_embeddings_text_encoder_output.text_embeds
124
uncond_text_encoder_hidden_states = uncond_embeddings_text_encoder_output.last_hidden_state
125
126
# duplicate unconditional embeddings for each generation per prompt, using mps friendly method
127
128
seq_len = uncond_embeddings.shape[1]
129
uncond_embeddings = uncond_embeddings.repeat(1, num_images_per_prompt)
130
uncond_embeddings = uncond_embeddings.view(batch_size * num_images_per_prompt, seq_len)
131
132
seq_len = uncond_text_encoder_hidden_states.shape[1]
133
uncond_text_encoder_hidden_states = uncond_text_encoder_hidden_states.repeat(1, num_images_per_prompt, 1)
134
uncond_text_encoder_hidden_states = uncond_text_encoder_hidden_states.view(
135
batch_size * num_images_per_prompt, seq_len, -1
136
)
137
uncond_text_mask = uncond_text_mask.repeat_interleave(num_images_per_prompt, dim=0)
138
139
# done duplicates
140
141
# For classifier free guidance, we need to do two forward passes.
142
# Here we concatenate the unconditional and text embeddings into a single batch
143
# to avoid doing two forward passes
144
text_embeddings = torch.cat([uncond_embeddings, text_embeddings])
145
text_encoder_hidden_states = torch.cat([uncond_text_encoder_hidden_states, text_encoder_hidden_states])
146
147
text_mask = torch.cat([uncond_text_mask, text_mask])
148
149
return text_embeddings, text_encoder_hidden_states, text_mask
150
151
@property
152
def _execution_device(self):
153
r"""
154
Returns the device on which the pipeline's models will be executed. After calling
155
`pipeline.enable_sequential_cpu_offload()` the execution device can only be inferred from Accelerate's module
156
hooks.
157
"""
158
if self.device != torch.device("meta") or not hasattr(self.prior, "_hf_hook"):
159
return self.device
160
for module in self.prior.modules():
161
if (
162
hasattr(module, "_hf_hook")
163
and hasattr(module._hf_hook, "execution_device")
164
and module._hf_hook.execution_device is not None
165
):
166
return torch.device(module._hf_hook.execution_device)
167
return self.device
168
169
def prepare_latents(self, shape, dtype, device, generator, latents, scheduler):
170
if latents is None:
171
latents = randn_tensor(shape, generator=generator, device=device, dtype=dtype)
172
else:
173
if latents.shape != shape:
174
raise ValueError(f"Unexpected latents shape, got {latents.shape}, expected {shape}")
175
latents = latents.to(device)
176
177
latents = latents * scheduler.init_noise_sigma
178
return latents
179
180
def to(self, torch_device: Optional[Union[str, torch.device]] = None):
181
self.decoder_pipe.to(torch_device)
182
super().to(torch_device)
183
184
@torch.no_grad()
185
def __call__(
186
self,
187
prompt: Optional[Union[str, List[str]]] = None,
188
height: Optional[int] = None,
189
width: Optional[int] = None,
190
num_images_per_prompt: int = 1,
191
prior_num_inference_steps: int = 25,
192
generator: Optional[torch.Generator] = None,
193
prior_latents: Optional[torch.FloatTensor] = None,
194
text_model_output: Optional[Union[CLIPTextModelOutput, Tuple]] = None,
195
text_attention_mask: Optional[torch.Tensor] = None,
196
prior_guidance_scale: float = 4.0,
197
decoder_guidance_scale: float = 8.0,
198
decoder_num_inference_steps: int = 50,
199
decoder_num_images_per_prompt: Optional[int] = 1,
200
decoder_eta: float = 0.0,
201
output_type: Optional[str] = "pil",
202
return_dict: bool = True,
203
):
204
if prompt is not None:
205
if isinstance(prompt, str):
206
batch_size = 1
207
elif isinstance(prompt, list):
208
batch_size = len(prompt)
209
else:
210
raise ValueError(f"`prompt` has to be of type `str` or `list` but is {type(prompt)}")
211
else:
212
batch_size = text_model_output[0].shape[0]
213
214
device = self._execution_device
215
216
batch_size = batch_size * num_images_per_prompt
217
218
do_classifier_free_guidance = prior_guidance_scale > 1.0 or decoder_guidance_scale > 1.0
219
220
text_embeddings, text_encoder_hidden_states, text_mask = self._encode_prompt(
221
prompt, device, num_images_per_prompt, do_classifier_free_guidance, text_model_output, text_attention_mask
222
)
223
224
# prior
225
226
self.prior_scheduler.set_timesteps(prior_num_inference_steps, device=device)
227
prior_timesteps_tensor = self.prior_scheduler.timesteps
228
229
embedding_dim = self.prior.config.embedding_dim
230
231
prior_latents = self.prepare_latents(
232
(batch_size, embedding_dim),
233
text_embeddings.dtype,
234
device,
235
generator,
236
prior_latents,
237
self.prior_scheduler,
238
)
239
240
for i, t in enumerate(self.progress_bar(prior_timesteps_tensor)):
241
# expand the latents if we are doing classifier free guidance
242
latent_model_input = torch.cat([prior_latents] * 2) if do_classifier_free_guidance else prior_latents
243
244
predicted_image_embedding = self.prior(
245
latent_model_input,
246
timestep=t,
247
proj_embedding=text_embeddings,
248
encoder_hidden_states=text_encoder_hidden_states,
249
attention_mask=text_mask,
250
).predicted_image_embedding
251
252
if do_classifier_free_guidance:
253
predicted_image_embedding_uncond, predicted_image_embedding_text = predicted_image_embedding.chunk(2)
254
predicted_image_embedding = predicted_image_embedding_uncond + prior_guidance_scale * (
255
predicted_image_embedding_text - predicted_image_embedding_uncond
256
)
257
258
if i + 1 == prior_timesteps_tensor.shape[0]:
259
prev_timestep = None
260
else:
261
prev_timestep = prior_timesteps_tensor[i + 1]
262
263
prior_latents = self.prior_scheduler.step(
264
predicted_image_embedding,
265
timestep=t,
266
sample=prior_latents,
267
generator=generator,
268
prev_timestep=prev_timestep,
269
).prev_sample
270
271
prior_latents = self.prior.post_process_latents(prior_latents)
272
273
image_embeddings = prior_latents
274
275
output = self.decoder_pipe(
276
image=image_embeddings,
277
height=height,
278
width=width,
279
num_inference_steps=decoder_num_inference_steps,
280
guidance_scale=decoder_guidance_scale,
281
generator=generator,
282
output_type=output_type,
283
return_dict=return_dict,
284
num_images_per_prompt=decoder_num_images_per_prompt,
285
eta=decoder_eta,
286
)
287
return output
288
289