move the text encoder
Browse files- model_index.json +1 -1
- pipeline_glide.py +911 -0
model_index.json
CHANGED
@@ -3,7 +3,7 @@
|
|
3 |
"_diffusers_version": "0.0.3",
|
4 |
"_module": "pipeline_glide",
|
5 |
"text_encoder": [
|
6 |
-
"
|
7 |
"CLIPTextModel"
|
8 |
],
|
9 |
"text_noise_scheduler": [
|
|
|
3 |
"_diffusers_version": "0.0.3",
|
4 |
"_module": "pipeline_glide",
|
5 |
"text_encoder": [
|
6 |
+
"pipeline_glide",
|
7 |
"CLIPTextModel"
|
8 |
],
|
9 |
"text_noise_scheduler": [
|
pipeline_glide.py
ADDED
@@ -0,0 +1,911 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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 |
+
# you may not use this file except in compliance with the License.
|
6 |
+
# You may obtain a copy of the License at
|
7 |
+
#
|
8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
9 |
+
#
|
10 |
+
# Unless required by applicable law or agreed to in writing, software
|
11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
13 |
+
# See the License for the specific language governing permissions and
|
14 |
+
# limitations under the License.
|
15 |
+
""" PyTorch CLIP model."""
|
16 |
+
|
17 |
+
import math
|
18 |
+
from dataclasses import dataclass
|
19 |
+
from typing import Any, Optional, Tuple, Union
|
20 |
+
|
21 |
+
import numpy as np
|
22 |
+
import torch
|
23 |
+
import torch.utils.checkpoint
|
24 |
+
from torch import nn
|
25 |
+
|
26 |
+
import tqdm
|
27 |
+
from transformers import CLIPConfig, CLIPModel, CLIPTextConfig, CLIPVisionConfig, GPT2Tokenizer
|
28 |
+
from transformers.activations import ACT2FN
|
29 |
+
from transformers.modeling_outputs import BaseModelOutput, BaseModelOutputWithPooling
|
30 |
+
from transformers.modeling_utils import PreTrainedModel
|
31 |
+
from transformers.utils import (
|
32 |
+
ModelOutput,
|
33 |
+
add_start_docstrings,
|
34 |
+
add_start_docstrings_to_model_forward,
|
35 |
+
logging,
|
36 |
+
replace_return_docstrings,
|
37 |
+
)
|
38 |
+
|
39 |
+
from ..models import GLIDESuperResUNetModel, GLIDETextToImageUNetModel
|
40 |
+
from ..pipeline_utils import DiffusionPipeline
|
41 |
+
from ..schedulers import ClassifierFreeGuidanceScheduler, DDIMScheduler
|
42 |
+
|
43 |
+
|
44 |
+
#####################
|
45 |
+
# START OF THE CLIP MODEL COPY-PASTE (with a modified attention module)
|
46 |
+
#####################
|
47 |
+
|
48 |
+
logger = logging.get_logger(__name__)
|
49 |
+
|
50 |
+
_CHECKPOINT_FOR_DOC = "fusing/glide-base"
|
51 |
+
|
52 |
+
CLIP_PRETRAINED_MODEL_ARCHIVE_LIST = [
|
53 |
+
"fusing/glide-base",
|
54 |
+
# See all CLIP models at https://huggingface.co/models?filter=clip
|
55 |
+
]
|
56 |
+
|
57 |
+
|
58 |
+
# Copied from transformers.models.bart.modeling_bart._expand_mask
|
59 |
+
def _expand_mask(mask: torch.Tensor, dtype: torch.dtype, tgt_len: Optional[int] = None):
|
60 |
+
"""
|
61 |
+
Expands attention_mask from `[bsz, seq_len]` to `[bsz, 1, tgt_seq_len, src_seq_len]`.
|
62 |
+
"""
|
63 |
+
bsz, src_len = mask.size()
|
64 |
+
tgt_len = tgt_len if tgt_len is not None else src_len
|
65 |
+
|
66 |
+
expanded_mask = mask[:, None, None, :].expand(bsz, 1, tgt_len, src_len).to(dtype)
|
67 |
+
|
68 |
+
inverted_mask = 1.0 - expanded_mask
|
69 |
+
|
70 |
+
return inverted_mask.masked_fill(inverted_mask.to(torch.bool), torch.finfo(dtype).min)
|
71 |
+
|
72 |
+
|
73 |
+
# contrastive loss function, adapted from
|
74 |
+
# https://sachinruk.github.io/blog/pytorch/pytorch%20lightning/loss%20function/gpu/2021/03/07/CLIP.html
|
75 |
+
def contrastive_loss(logits: torch.Tensor) -> torch.Tensor:
|
76 |
+
return nn.functional.cross_entropy(logits, torch.arange(len(logits), device=logits.device))
|
77 |
+
|
78 |
+
|
79 |
+
def clip_loss(similarity: torch.Tensor) -> torch.Tensor:
|
80 |
+
caption_loss = contrastive_loss(similarity)
|
81 |
+
image_loss = contrastive_loss(similarity.T)
|
82 |
+
return (caption_loss + image_loss) / 2.0
|
83 |
+
|
84 |
+
|
85 |
+
@dataclass
|
86 |
+
class CLIPOutput(ModelOutput):
|
87 |
+
"""
|
88 |
+
Args:
|
89 |
+
loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `return_loss` is `True`):
|
90 |
+
Contrastive loss for image-text similarity.
|
91 |
+
logits_per_image:(`torch.FloatTensor` of shape `(image_batch_size, text_batch_size)`):
|
92 |
+
The scaled dot product scores between `image_embeds` and `text_embeds`. This represents the image-text
|
93 |
+
similarity scores.
|
94 |
+
logits_per_text:(`torch.FloatTensor` of shape `(text_batch_size, image_batch_size)`):
|
95 |
+
The scaled dot product scores between `text_embeds` and `image_embeds`. This represents the text-image
|
96 |
+
similarity scores.
|
97 |
+
text_embeds(`torch.FloatTensor` of shape `(batch_size, output_dim`):
|
98 |
+
The text embeddings obtained by applying the projection layer to the pooled output of [`CLIPTextModel`].
|
99 |
+
image_embeds(`torch.FloatTensor` of shape `(batch_size, output_dim`):
|
100 |
+
The image embeddings obtained by applying the projection layer to the pooled output of [`CLIPVisionModel`].
|
101 |
+
text_model_output(`BaseModelOutputWithPooling`):
|
102 |
+
The output of the [`CLIPTextModel`].
|
103 |
+
vision_model_output(`BaseModelOutputWithPooling`):
|
104 |
+
The output of the [`CLIPVisionModel`].
|
105 |
+
"""
|
106 |
+
|
107 |
+
loss: Optional[torch.FloatTensor] = None
|
108 |
+
logits_per_image: torch.FloatTensor = None
|
109 |
+
logits_per_text: torch.FloatTensor = None
|
110 |
+
text_embeds: torch.FloatTensor = None
|
111 |
+
image_embeds: torch.FloatTensor = None
|
112 |
+
text_model_output: BaseModelOutputWithPooling = None
|
113 |
+
vision_model_output: BaseModelOutputWithPooling = None
|
114 |
+
|
115 |
+
def to_tuple(self) -> Tuple[Any]:
|
116 |
+
return tuple(
|
117 |
+
self[k] if k not in ["text_model_output", "vision_model_output"] else getattr(self, k).to_tuple()
|
118 |
+
for k in self.keys()
|
119 |
+
)
|
120 |
+
|
121 |
+
|
122 |
+
class CLIPVisionEmbeddings(nn.Module):
|
123 |
+
def __init__(self, config: CLIPVisionConfig):
|
124 |
+
super().__init__()
|
125 |
+
self.config = config
|
126 |
+
self.embed_dim = config.hidden_size
|
127 |
+
self.image_size = config.image_size
|
128 |
+
self.patch_size = config.patch_size
|
129 |
+
|
130 |
+
self.class_embedding = nn.Parameter(torch.randn(self.embed_dim))
|
131 |
+
|
132 |
+
self.patch_embedding = nn.Conv2d(
|
133 |
+
in_channels=3, out_channels=self.embed_dim, kernel_size=self.patch_size, stride=self.patch_size, bias=False
|
134 |
+
)
|
135 |
+
|
136 |
+
self.num_patches = (self.image_size // self.patch_size) ** 2
|
137 |
+
self.num_positions = self.num_patches + 1
|
138 |
+
self.position_embedding = nn.Embedding(self.num_positions, self.embed_dim)
|
139 |
+
self.register_buffer("position_ids", torch.arange(self.num_positions).expand((1, -1)))
|
140 |
+
|
141 |
+
def forward(self, pixel_values: torch.FloatTensor) -> torch.Tensor:
|
142 |
+
batch_size = pixel_values.shape[0]
|
143 |
+
patch_embeds = self.patch_embedding(pixel_values) # shape = [*, width, grid, grid]
|
144 |
+
patch_embeds = patch_embeds.flatten(2).transpose(1, 2)
|
145 |
+
|
146 |
+
class_embeds = self.class_embedding.expand(batch_size, 1, -1)
|
147 |
+
embeddings = torch.cat([class_embeds, patch_embeds], dim=1)
|
148 |
+
embeddings = embeddings + self.position_embedding(self.position_ids)
|
149 |
+
return embeddings
|
150 |
+
|
151 |
+
|
152 |
+
class CLIPTextEmbeddings(nn.Module):
|
153 |
+
def __init__(self, config: CLIPTextConfig):
|
154 |
+
super().__init__()
|
155 |
+
embed_dim = config.hidden_size
|
156 |
+
|
157 |
+
self.token_embedding = nn.Embedding(config.vocab_size, embed_dim)
|
158 |
+
self.position_embedding = nn.Embedding(config.max_position_embeddings, embed_dim)
|
159 |
+
self.use_padding_embeddings = config.use_padding_embeddings
|
160 |
+
if self.use_padding_embeddings:
|
161 |
+
self.padding_embedding = nn.Embedding(config.max_position_embeddings, embed_dim)
|
162 |
+
|
163 |
+
# position_ids (1, len position emb) is contiguous in memory and exported when serialized
|
164 |
+
self.register_buffer("position_ids", torch.arange(config.max_position_embeddings).expand((1, -1)))
|
165 |
+
|
166 |
+
def forward(
|
167 |
+
self,
|
168 |
+
input_ids: Optional[torch.LongTensor] = None,
|
169 |
+
position_ids: Optional[torch.LongTensor] = None,
|
170 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
171 |
+
attention_mask: Optional[torch.Tensor] = None,
|
172 |
+
) -> torch.Tensor:
|
173 |
+
seq_length = input_ids.shape[-1] if input_ids is not None else inputs_embeds.shape[-2]
|
174 |
+
|
175 |
+
if position_ids is None:
|
176 |
+
position_ids = self.position_ids[:, :seq_length]
|
177 |
+
|
178 |
+
if inputs_embeds is None:
|
179 |
+
inputs_embeds = self.token_embedding(input_ids)
|
180 |
+
|
181 |
+
position_embeddings = self.position_embedding(position_ids)
|
182 |
+
embeddings = inputs_embeds + position_embeddings
|
183 |
+
|
184 |
+
if self.use_padding_embeddings and attention_mask is not None:
|
185 |
+
padding_embeddings = self.padding_embedding(position_ids)
|
186 |
+
embeddings = torch.where(attention_mask.bool().unsqueeze(-1), embeddings, padding_embeddings)
|
187 |
+
|
188 |
+
return embeddings
|
189 |
+
|
190 |
+
|
191 |
+
class CLIPAttention(nn.Module):
|
192 |
+
"""Multi-headed attention from 'Attention Is All You Need' paper"""
|
193 |
+
|
194 |
+
def __init__(self, config):
|
195 |
+
super().__init__()
|
196 |
+
self.config = config
|
197 |
+
self.embed_dim = config.hidden_size
|
198 |
+
self.num_heads = config.num_attention_heads
|
199 |
+
self.head_dim = self.embed_dim // self.num_heads
|
200 |
+
if self.head_dim * self.num_heads != self.embed_dim:
|
201 |
+
raise ValueError(
|
202 |
+
f"embed_dim must be divisible by num_heads (got `embed_dim`: {self.embed_dim} and `num_heads`:"
|
203 |
+
f" {self.num_heads})."
|
204 |
+
)
|
205 |
+
self.scale = 1 / math.sqrt(math.sqrt(self.head_dim))
|
206 |
+
|
207 |
+
self.qkv_proj = nn.Linear(self.embed_dim, self.embed_dim * 3)
|
208 |
+
self.out_proj = nn.Linear(self.embed_dim, self.embed_dim)
|
209 |
+
|
210 |
+
def forward(
|
211 |
+
self,
|
212 |
+
hidden_states: torch.Tensor,
|
213 |
+
attention_mask: Optional[torch.Tensor] = None,
|
214 |
+
causal_attention_mask: Optional[torch.Tensor] = None,
|
215 |
+
output_attentions: Optional[bool] = False,
|
216 |
+
) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
|
217 |
+
"""Input shape: Batch x Time x Channel"""
|
218 |
+
|
219 |
+
bsz, tgt_len, embed_dim = hidden_states.size()
|
220 |
+
|
221 |
+
qkv_states = self.qkv_proj(hidden_states)
|
222 |
+
qkv_states = qkv_states.view(bsz, tgt_len, self.num_heads, -1)
|
223 |
+
query_states, key_states, value_states = torch.split(qkv_states, self.head_dim, dim=-1)
|
224 |
+
|
225 |
+
attn_weights = torch.einsum("bthc,bshc->bhts", query_states * self.scale, key_states * self.scale)
|
226 |
+
|
227 |
+
wdtype = attn_weights.dtype
|
228 |
+
attn_weights = nn.functional.softmax(attn_weights.float(), dim=-1).type(wdtype)
|
229 |
+
|
230 |
+
attn_output = torch.einsum("bhts,bshc->bthc", attn_weights, value_states)
|
231 |
+
attn_output = attn_output.reshape(bsz, tgt_len, -1)
|
232 |
+
|
233 |
+
attn_output = self.out_proj(attn_output)
|
234 |
+
|
235 |
+
return attn_output, attn_weights
|
236 |
+
|
237 |
+
|
238 |
+
class CLIPMLP(nn.Module):
|
239 |
+
def __init__(self, config):
|
240 |
+
super().__init__()
|
241 |
+
self.config = config
|
242 |
+
self.activation_fn = ACT2FN[config.hidden_act]
|
243 |
+
self.fc1 = nn.Linear(config.hidden_size, config.intermediate_size)
|
244 |
+
self.fc2 = nn.Linear(config.intermediate_size, config.hidden_size)
|
245 |
+
|
246 |
+
def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
|
247 |
+
hidden_states = self.fc1(hidden_states)
|
248 |
+
hidden_states = self.activation_fn(hidden_states)
|
249 |
+
hidden_states = self.fc2(hidden_states)
|
250 |
+
return hidden_states
|
251 |
+
|
252 |
+
|
253 |
+
class CLIPEncoderLayer(nn.Module):
|
254 |
+
def __init__(self, config: CLIPConfig):
|
255 |
+
super().__init__()
|
256 |
+
self.embed_dim = config.hidden_size
|
257 |
+
self.self_attn = CLIPAttention(config)
|
258 |
+
self.layer_norm1 = nn.LayerNorm(self.embed_dim)
|
259 |
+
self.mlp = CLIPMLP(config)
|
260 |
+
self.layer_norm2 = nn.LayerNorm(self.embed_dim)
|
261 |
+
|
262 |
+
def forward(
|
263 |
+
self,
|
264 |
+
hidden_states: torch.Tensor,
|
265 |
+
attention_mask: torch.Tensor,
|
266 |
+
causal_attention_mask: torch.Tensor,
|
267 |
+
output_attentions: Optional[bool] = False,
|
268 |
+
) -> Tuple[torch.FloatTensor]:
|
269 |
+
"""
|
270 |
+
Args:
|
271 |
+
hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
|
272 |
+
attention_mask (`torch.FloatTensor`): attention mask of size
|
273 |
+
`(batch, 1, tgt_len, src_len)` where padding elements are indicated by very large negative values.
|
274 |
+
`(config.encoder_attention_heads,)`.
|
275 |
+
output_attentions (`bool`, *optional*):
|
276 |
+
Whether or not to return the attentions tensors of all attention layers. See `attentions` under
|
277 |
+
returned tensors for more detail.
|
278 |
+
"""
|
279 |
+
residual = hidden_states
|
280 |
+
|
281 |
+
hidden_states = self.layer_norm1(hidden_states)
|
282 |
+
hidden_states, attn_weights = self.self_attn(
|
283 |
+
hidden_states=hidden_states,
|
284 |
+
attention_mask=attention_mask,
|
285 |
+
causal_attention_mask=causal_attention_mask,
|
286 |
+
output_attentions=output_attentions,
|
287 |
+
)
|
288 |
+
hidden_states = residual + hidden_states
|
289 |
+
|
290 |
+
residual = hidden_states
|
291 |
+
hidden_states = self.layer_norm2(hidden_states)
|
292 |
+
hidden_states = self.mlp(hidden_states)
|
293 |
+
hidden_states = residual + hidden_states
|
294 |
+
|
295 |
+
outputs = (hidden_states,)
|
296 |
+
|
297 |
+
if output_attentions:
|
298 |
+
outputs += (attn_weights,)
|
299 |
+
|
300 |
+
return outputs
|
301 |
+
|
302 |
+
|
303 |
+
class CLIPPreTrainedModel(PreTrainedModel):
|
304 |
+
"""
|
305 |
+
An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
|
306 |
+
models.
|
307 |
+
"""
|
308 |
+
|
309 |
+
config_class = CLIPConfig
|
310 |
+
base_model_prefix = "clip"
|
311 |
+
supports_gradient_checkpointing = True
|
312 |
+
_keys_to_ignore_on_load_missing = [r"position_ids"]
|
313 |
+
|
314 |
+
def _init_weights(self, module):
|
315 |
+
"""Initialize the weights"""
|
316 |
+
factor = self.config.initializer_factor
|
317 |
+
if isinstance(module, CLIPTextEmbeddings):
|
318 |
+
module.token_embedding.weight.data.normal_(mean=0.0, std=factor * 0.02)
|
319 |
+
module.position_embedding.weight.data.normal_(mean=0.0, std=factor * 0.02)
|
320 |
+
if hasattr(module, "padding_embedding"):
|
321 |
+
module.padding_embedding.weight.data.normal_(mean=0.0, std=factor * 0.02)
|
322 |
+
elif isinstance(module, CLIPVisionEmbeddings):
|
323 |
+
factor = self.config.initializer_factor
|
324 |
+
nn.init.normal_(module.class_embedding, mean=0.0, std=module.embed_dim**-0.5 * factor)
|
325 |
+
nn.init.normal_(module.patch_embedding.weight, std=module.config.initializer_range * factor)
|
326 |
+
nn.init.normal_(module.position_embedding.weight, std=module.config.initializer_range * factor)
|
327 |
+
elif isinstance(module, CLIPAttention):
|
328 |
+
factor = self.config.initializer_factor
|
329 |
+
in_proj_std = (module.embed_dim**-0.5) * ((2 * module.config.num_hidden_layers) ** -0.5) * factor
|
330 |
+
out_proj_std = (module.embed_dim**-0.5) * factor
|
331 |
+
nn.init.normal_(module.qkv_proj.weight, std=in_proj_std)
|
332 |
+
nn.init.normal_(module.out_proj.weight, std=out_proj_std)
|
333 |
+
elif isinstance(module, CLIPMLP):
|
334 |
+
factor = self.config.initializer_factor
|
335 |
+
in_proj_std = (
|
336 |
+
(module.config.hidden_size**-0.5) * ((2 * module.config.num_hidden_layers) ** -0.5) * factor
|
337 |
+
)
|
338 |
+
fc_std = (2 * module.config.hidden_size) ** -0.5 * factor
|
339 |
+
nn.init.normal_(module.fc1.weight, std=fc_std)
|
340 |
+
nn.init.normal_(module.fc2.weight, std=in_proj_std)
|
341 |
+
elif isinstance(module, CLIPModel):
|
342 |
+
nn.init.normal_(
|
343 |
+
module.text_projection.weight,
|
344 |
+
std=module.text_embed_dim**-0.5 * self.config.initializer_factor,
|
345 |
+
)
|
346 |
+
nn.init.normal_(
|
347 |
+
module.visual_projection.weight,
|
348 |
+
std=module.vision_embed_dim**-0.5 * self.config.initializer_factor,
|
349 |
+
)
|
350 |
+
|
351 |
+
if isinstance(module, nn.LayerNorm):
|
352 |
+
module.bias.data.zero_()
|
353 |
+
module.weight.data.fill_(1.0)
|
354 |
+
if isinstance(module, nn.Linear) and module.bias is not None:
|
355 |
+
module.bias.data.zero_()
|
356 |
+
|
357 |
+
def _set_gradient_checkpointing(self, module, value=False):
|
358 |
+
if isinstance(module, CLIPEncoder):
|
359 |
+
module.gradient_checkpointing = value
|
360 |
+
|
361 |
+
|
362 |
+
CLIP_START_DOCSTRING = r"""
|
363 |
+
This model is a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass. Use it
|
364 |
+
as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and
|
365 |
+
behavior.
|
366 |
+
|
367 |
+
Parameters:
|
368 |
+
config ([`CLIPConfig`]): Model configuration class with all the parameters of the model.
|
369 |
+
Initializing with a config file does not load the weights associated with the model, only the
|
370 |
+
configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.
|
371 |
+
"""
|
372 |
+
|
373 |
+
CLIP_TEXT_INPUTS_DOCSTRING = r"""
|
374 |
+
Args:
|
375 |
+
input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
|
376 |
+
Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
|
377 |
+
it.
|
378 |
+
|
379 |
+
Indices can be obtained using [`CLIPTokenizer`]. See [`PreTrainedTokenizer.encode`] and
|
380 |
+
[`PreTrainedTokenizer.__call__`] for details.
|
381 |
+
|
382 |
+
[What are input IDs?](../glossary#input-ids)
|
383 |
+
attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
|
384 |
+
Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
|
385 |
+
|
386 |
+
- 1 for tokens that are **not masked**,
|
387 |
+
- 0 for tokens that are **masked**.
|
388 |
+
|
389 |
+
[What are attention masks?](../glossary#attention-mask)
|
390 |
+
position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
|
391 |
+
Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
|
392 |
+
config.max_position_embeddings - 1]`.
|
393 |
+
|
394 |
+
[What are position IDs?](../glossary#position-ids)
|
395 |
+
output_attentions (`bool`, *optional*):
|
396 |
+
Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
|
397 |
+
tensors for more detail.
|
398 |
+
output_hidden_states (`bool`, *optional*):
|
399 |
+
Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
|
400 |
+
more detail.
|
401 |
+
return_dict (`bool`, *optional*):
|
402 |
+
Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
|
403 |
+
"""
|
404 |
+
|
405 |
+
CLIP_VISION_INPUTS_DOCSTRING = r"""
|
406 |
+
Args:
|
407 |
+
pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`):
|
408 |
+
Pixel values. Padding will be ignored by default should you provide it. Pixel values can be obtained using
|
409 |
+
[`CLIPFeatureExtractor`]. See [`CLIPFeatureExtractor.__call__`] for details.
|
410 |
+
output_attentions (`bool`, *optional*):
|
411 |
+
Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
|
412 |
+
tensors for more detail.
|
413 |
+
output_hidden_states (`bool`, *optional*):
|
414 |
+
Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
|
415 |
+
more detail.
|
416 |
+
return_dict (`bool`, *optional*):
|
417 |
+
Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
|
418 |
+
"""
|
419 |
+
|
420 |
+
CLIP_INPUTS_DOCSTRING = r"""
|
421 |
+
Args:
|
422 |
+
input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
|
423 |
+
Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
|
424 |
+
it.
|
425 |
+
|
426 |
+
Indices can be obtained using [`CLIPTokenizer`]. See [`PreTrainedTokenizer.encode`] and
|
427 |
+
[`PreTrainedTokenizer.__call__`] for details.
|
428 |
+
|
429 |
+
[What are input IDs?](../glossary#input-ids)
|
430 |
+
attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
|
431 |
+
Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
|
432 |
+
|
433 |
+
- 1 for tokens that are **not masked**,
|
434 |
+
- 0 for tokens that are **masked**.
|
435 |
+
|
436 |
+
[What are attention masks?](../glossary#attention-mask)
|
437 |
+
position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
|
438 |
+
Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
|
439 |
+
config.max_position_embeddings - 1]`.
|
440 |
+
|
441 |
+
[What are position IDs?](../glossary#position-ids)
|
442 |
+
pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`):
|
443 |
+
Pixel values. Padding will be ignored by default should you provide it. Pixel values can be obtained using
|
444 |
+
[`CLIPFeatureExtractor`]. See [`CLIPFeatureExtractor.__call__`] for details.
|
445 |
+
return_loss (`bool`, *optional*):
|
446 |
+
Whether or not to return the contrastive loss.
|
447 |
+
output_attentions (`bool`, *optional*):
|
448 |
+
Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
|
449 |
+
tensors for more detail.
|
450 |
+
output_hidden_states (`bool`, *optional*):
|
451 |
+
Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
|
452 |
+
more detail.
|
453 |
+
return_dict (`bool`, *optional*):
|
454 |
+
Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
|
455 |
+
"""
|
456 |
+
|
457 |
+
|
458 |
+
class CLIPEncoder(nn.Module):
|
459 |
+
"""
|
460 |
+
Transformer encoder consisting of `config.num_hidden_layers` self attention layers. Each layer is a
|
461 |
+
[`CLIPEncoderLayer`].
|
462 |
+
|
463 |
+
Args:
|
464 |
+
config: CLIPConfig
|
465 |
+
"""
|
466 |
+
|
467 |
+
def __init__(self, config: CLIPConfig):
|
468 |
+
super().__init__()
|
469 |
+
self.config = config
|
470 |
+
self.layers = nn.ModuleList([CLIPEncoderLayer(config) for _ in range(config.num_hidden_layers)])
|
471 |
+
self.gradient_checkpointing = False
|
472 |
+
|
473 |
+
def forward(
|
474 |
+
self,
|
475 |
+
inputs_embeds,
|
476 |
+
attention_mask: Optional[torch.Tensor] = None,
|
477 |
+
causal_attention_mask: Optional[torch.Tensor] = None,
|
478 |
+
output_attentions: Optional[bool] = None,
|
479 |
+
output_hidden_states: Optional[bool] = None,
|
480 |
+
return_dict: Optional[bool] = None,
|
481 |
+
) -> Union[Tuple, BaseModelOutput]:
|
482 |
+
r"""
|
483 |
+
Args:
|
484 |
+
inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`):
|
485 |
+
Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation.
|
486 |
+
This is useful if you want more control over how to convert `input_ids` indices into associated vectors
|
487 |
+
than the model's internal embedding lookup matrix.
|
488 |
+
attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
|
489 |
+
Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
|
490 |
+
|
491 |
+
- 1 for tokens that are **not masked**,
|
492 |
+
- 0 for tokens that are **masked**.
|
493 |
+
|
494 |
+
[What are attention masks?](../glossary#attention-mask)
|
495 |
+
causal_attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
|
496 |
+
Causal mask for the text model. Mask values selected in `[0, 1]`:
|
497 |
+
|
498 |
+
- 1 for tokens that are **not masked**,
|
499 |
+
- 0 for tokens that are **masked**.
|
500 |
+
|
501 |
+
[What are attention masks?](../glossary#attention-mask)
|
502 |
+
output_attentions (`bool`, *optional*):
|
503 |
+
Whether or not to return the attentions tensors of all attention layers. See `attentions` under
|
504 |
+
returned tensors for more detail.
|
505 |
+
output_hidden_states (`bool`, *optional*):
|
506 |
+
Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors
|
507 |
+
for more detail.
|
508 |
+
return_dict (`bool`, *optional*):
|
509 |
+
Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
|
510 |
+
"""
|
511 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
512 |
+
output_hidden_states = (
|
513 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
514 |
+
)
|
515 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
516 |
+
|
517 |
+
encoder_states = () if output_hidden_states else None
|
518 |
+
all_attentions = () if output_attentions else None
|
519 |
+
|
520 |
+
hidden_states = inputs_embeds
|
521 |
+
for idx, encoder_layer in enumerate(self.layers):
|
522 |
+
if output_hidden_states:
|
523 |
+
encoder_states = encoder_states + (hidden_states,)
|
524 |
+
if self.gradient_checkpointing and self.training:
|
525 |
+
|
526 |
+
def create_custom_forward(module):
|
527 |
+
def custom_forward(*inputs):
|
528 |
+
return module(*inputs, output_attentions)
|
529 |
+
|
530 |
+
return custom_forward
|
531 |
+
|
532 |
+
layer_outputs = torch.utils.checkpoint.checkpoint(
|
533 |
+
create_custom_forward(encoder_layer),
|
534 |
+
hidden_states,
|
535 |
+
attention_mask,
|
536 |
+
causal_attention_mask,
|
537 |
+
)
|
538 |
+
else:
|
539 |
+
layer_outputs = encoder_layer(
|
540 |
+
hidden_states,
|
541 |
+
attention_mask,
|
542 |
+
causal_attention_mask,
|
543 |
+
output_attentions=output_attentions,
|
544 |
+
)
|
545 |
+
|
546 |
+
hidden_states = layer_outputs[0]
|
547 |
+
|
548 |
+
if output_attentions:
|
549 |
+
all_attentions = all_attentions + (layer_outputs[1],)
|
550 |
+
|
551 |
+
if output_hidden_states:
|
552 |
+
encoder_states = encoder_states + (hidden_states,)
|
553 |
+
|
554 |
+
if not return_dict:
|
555 |
+
return tuple(v for v in [hidden_states, encoder_states, all_attentions] if v is not None)
|
556 |
+
return BaseModelOutput(
|
557 |
+
last_hidden_state=hidden_states, hidden_states=encoder_states, attentions=all_attentions
|
558 |
+
)
|
559 |
+
|
560 |
+
|
561 |
+
class CLIPTextTransformer(nn.Module):
|
562 |
+
def __init__(self, config: CLIPTextConfig):
|
563 |
+
super().__init__()
|
564 |
+
self.config = config
|
565 |
+
embed_dim = config.hidden_size
|
566 |
+
self.embeddings = CLIPTextEmbeddings(config)
|
567 |
+
self.encoder = CLIPEncoder(config)
|
568 |
+
self.final_layer_norm = nn.LayerNorm(embed_dim)
|
569 |
+
|
570 |
+
@add_start_docstrings_to_model_forward(CLIP_TEXT_INPUTS_DOCSTRING)
|
571 |
+
@replace_return_docstrings(output_type=BaseModelOutputWithPooling, config_class=CLIPTextConfig)
|
572 |
+
def forward(
|
573 |
+
self,
|
574 |
+
input_ids: Optional[torch.Tensor] = None,
|
575 |
+
attention_mask: Optional[torch.Tensor] = None,
|
576 |
+
position_ids: Optional[torch.Tensor] = None,
|
577 |
+
output_attentions: Optional[bool] = None,
|
578 |
+
output_hidden_states: Optional[bool] = None,
|
579 |
+
return_dict: Optional[bool] = None,
|
580 |
+
) -> Union[Tuple, BaseModelOutputWithPooling]:
|
581 |
+
r"""
|
582 |
+
Returns:
|
583 |
+
|
584 |
+
"""
|
585 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
586 |
+
output_hidden_states = (
|
587 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
588 |
+
)
|
589 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
590 |
+
|
591 |
+
if input_ids is None:
|
592 |
+
raise ValueError("You have to specify either input_ids")
|
593 |
+
|
594 |
+
input_shape = input_ids.size()
|
595 |
+
input_ids = input_ids.view(-1, input_shape[-1])
|
596 |
+
|
597 |
+
hidden_states = self.embeddings(input_ids=input_ids, position_ids=position_ids, attention_mask=attention_mask)
|
598 |
+
|
599 |
+
bsz, seq_len = input_shape
|
600 |
+
# CLIP's text model uses causal mask, prepare it here.
|
601 |
+
# https://github.com/openai/CLIP/blob/cfcffb90e69f37bf2ff1e988237a0fbe41f33c04/clip/model.py#L324
|
602 |
+
causal_attention_mask = self._build_causal_attention_mask(bsz, seq_len).to(hidden_states.device)
|
603 |
+
|
604 |
+
# expand attention_mask
|
605 |
+
if attention_mask is not None:
|
606 |
+
# [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len]
|
607 |
+
attention_mask = _expand_mask(attention_mask, hidden_states.dtype)
|
608 |
+
|
609 |
+
encoder_outputs = self.encoder(
|
610 |
+
inputs_embeds=hidden_states,
|
611 |
+
attention_mask=None,
|
612 |
+
causal_attention_mask=None,
|
613 |
+
output_attentions=output_attentions,
|
614 |
+
output_hidden_states=output_hidden_states,
|
615 |
+
return_dict=return_dict,
|
616 |
+
)
|
617 |
+
|
618 |
+
last_hidden_state = encoder_outputs[0]
|
619 |
+
last_hidden_state = self.final_layer_norm(last_hidden_state)
|
620 |
+
|
621 |
+
# text_embeds.shape = [batch_size, sequence_length, transformer.width]
|
622 |
+
# take features from the eot embedding (eot_token is the highest number in each sequence)
|
623 |
+
pooled_output = last_hidden_state[torch.arange(last_hidden_state.shape[0]), input_ids.argmax(dim=-1)]
|
624 |
+
|
625 |
+
if not return_dict:
|
626 |
+
return (last_hidden_state, pooled_output) + encoder_outputs[1:]
|
627 |
+
|
628 |
+
return BaseModelOutputWithPooling(
|
629 |
+
last_hidden_state=last_hidden_state,
|
630 |
+
pooler_output=pooled_output,
|
631 |
+
hidden_states=encoder_outputs.hidden_states,
|
632 |
+
attentions=encoder_outputs.attentions,
|
633 |
+
)
|
634 |
+
|
635 |
+
def _build_causal_attention_mask(self, bsz, seq_len):
|
636 |
+
# lazily create causal attention mask, with full attention between the vision tokens
|
637 |
+
# pytorch uses additive attention mask; fill with -inf
|
638 |
+
mask = torch.empty(bsz, seq_len, seq_len)
|
639 |
+
mask.fill_(torch.tensor(float("-inf")))
|
640 |
+
mask.triu_(1) # zero out the lower diagonal
|
641 |
+
mask = mask.unsqueeze(1) # expand mask
|
642 |
+
return mask
|
643 |
+
|
644 |
+
|
645 |
+
class CLIPTextModel(CLIPPreTrainedModel):
|
646 |
+
config_class = CLIPTextConfig
|
647 |
+
|
648 |
+
def __init__(self, config: CLIPTextConfig):
|
649 |
+
super().__init__(config)
|
650 |
+
self.text_model = CLIPTextTransformer(config)
|
651 |
+
# Initialize weights and apply final processing
|
652 |
+
self.post_init()
|
653 |
+
|
654 |
+
def get_input_embeddings(self) -> nn.Module:
|
655 |
+
return self.text_model.embeddings.token_embedding
|
656 |
+
|
657 |
+
def set_input_embeddings(self, value):
|
658 |
+
self.text_model.embeddings.token_embedding = value
|
659 |
+
|
660 |
+
@add_start_docstrings_to_model_forward(CLIP_TEXT_INPUTS_DOCSTRING)
|
661 |
+
@replace_return_docstrings(output_type=BaseModelOutputWithPooling, config_class=CLIPTextConfig)
|
662 |
+
def forward(
|
663 |
+
self,
|
664 |
+
input_ids: Optional[torch.Tensor] = None,
|
665 |
+
attention_mask: Optional[torch.Tensor] = None,
|
666 |
+
position_ids: Optional[torch.Tensor] = None,
|
667 |
+
output_attentions: Optional[bool] = None,
|
668 |
+
output_hidden_states: Optional[bool] = None,
|
669 |
+
return_dict: Optional[bool] = None,
|
670 |
+
) -> Union[Tuple, BaseModelOutputWithPooling]:
|
671 |
+
r"""
|
672 |
+
Returns:
|
673 |
+
|
674 |
+
Examples:
|
675 |
+
|
676 |
+
```python
|
677 |
+
>>> from transformers import CLIPTokenizer, CLIPTextModel
|
678 |
+
|
679 |
+
>>> model = CLIPTextModel.from_pretrained("openai/clip-vit-base-patch32")
|
680 |
+
>>> tokenizer = CLIPTokenizer.from_pretrained("openai/clip-vit-base-patch32")
|
681 |
+
|
682 |
+
>>> inputs = tokenizer(["a photo of a cat", "a photo of a dog"], padding=True, return_tensors="pt")
|
683 |
+
|
684 |
+
>>> outputs = model(**inputs)
|
685 |
+
>>> last_hidden_state = outputs.last_hidden_state
|
686 |
+
>>> pooled_output = outputs.pooler_output # pooled (EOS token) states
|
687 |
+
```"""
|
688 |
+
return self.text_model(
|
689 |
+
input_ids=input_ids,
|
690 |
+
attention_mask=attention_mask,
|
691 |
+
position_ids=position_ids,
|
692 |
+
output_attentions=output_attentions,
|
693 |
+
output_hidden_states=output_hidden_states,
|
694 |
+
return_dict=return_dict,
|
695 |
+
)
|
696 |
+
|
697 |
+
|
698 |
+
#####################
|
699 |
+
# END OF THE CLIP MODEL COPY-PASTE
|
700 |
+
#####################
|
701 |
+
|
702 |
+
|
703 |
+
def _extract_into_tensor(arr, timesteps, broadcast_shape):
|
704 |
+
"""
|
705 |
+
Extract values from a 1-D numpy array for a batch of indices.
|
706 |
+
|
707 |
+
:param arr: the 1-D numpy array.
|
708 |
+
:param timesteps: a tensor of indices into the array to extract.
|
709 |
+
:param broadcast_shape: a larger shape of K dimensions with the batch
|
710 |
+
dimension equal to the length of timesteps.
|
711 |
+
:return: a tensor of shape [batch_size, 1, ...] where the shape has K dims.
|
712 |
+
"""
|
713 |
+
res = torch.from_numpy(arr).to(device=timesteps.device)[timesteps].float()
|
714 |
+
while len(res.shape) < len(broadcast_shape):
|
715 |
+
res = res[..., None]
|
716 |
+
return res + torch.zeros(broadcast_shape, device=timesteps.device)
|
717 |
+
|
718 |
+
|
719 |
+
class GLIDE(DiffusionPipeline):
|
720 |
+
def __init__(
|
721 |
+
self,
|
722 |
+
text_unet: GLIDETextToImageUNetModel,
|
723 |
+
text_noise_scheduler: ClassifierFreeGuidanceScheduler,
|
724 |
+
text_encoder: CLIPTextModel,
|
725 |
+
tokenizer: GPT2Tokenizer,
|
726 |
+
upscale_unet: GLIDESuperResUNetModel,
|
727 |
+
upscale_noise_scheduler: DDIMScheduler,
|
728 |
+
):
|
729 |
+
super().__init__()
|
730 |
+
self.register_modules(
|
731 |
+
text_unet=text_unet,
|
732 |
+
text_noise_scheduler=text_noise_scheduler,
|
733 |
+
text_encoder=text_encoder,
|
734 |
+
tokenizer=tokenizer,
|
735 |
+
upscale_unet=upscale_unet,
|
736 |
+
upscale_noise_scheduler=upscale_noise_scheduler,
|
737 |
+
)
|
738 |
+
|
739 |
+
def q_posterior_mean_variance(self, scheduler, x_start, x_t, t):
|
740 |
+
"""
|
741 |
+
Compute the mean and variance of the diffusion posterior:
|
742 |
+
|
743 |
+
q(x_{t-1} | x_t, x_0)
|
744 |
+
|
745 |
+
"""
|
746 |
+
assert x_start.shape == x_t.shape
|
747 |
+
posterior_mean = (
|
748 |
+
_extract_into_tensor(scheduler.posterior_mean_coef1, t, x_t.shape) * x_start
|
749 |
+
+ _extract_into_tensor(scheduler.posterior_mean_coef2, t, x_t.shape) * x_t
|
750 |
+
)
|
751 |
+
posterior_variance = _extract_into_tensor(scheduler.posterior_variance, t, x_t.shape)
|
752 |
+
posterior_log_variance_clipped = _extract_into_tensor(scheduler.posterior_log_variance_clipped, t, x_t.shape)
|
753 |
+
assert (
|
754 |
+
posterior_mean.shape[0]
|
755 |
+
== posterior_variance.shape[0]
|
756 |
+
== posterior_log_variance_clipped.shape[0]
|
757 |
+
== x_start.shape[0]
|
758 |
+
)
|
759 |
+
return posterior_mean, posterior_variance, posterior_log_variance_clipped
|
760 |
+
|
761 |
+
def p_mean_variance(self, model, scheduler, x, t, transformer_out=None, low_res=None, clip_denoised=True):
|
762 |
+
"""
|
763 |
+
Apply the model to get p(x_{t-1} | x_t), as well as a prediction of
|
764 |
+
the initial x, x_0.
|
765 |
+
|
766 |
+
:param model: the model, which takes a signal and a batch of timesteps
|
767 |
+
as input.
|
768 |
+
:param x: the [N x C x ...] tensor at time t.
|
769 |
+
:param t: a 1-D Tensor of timesteps.
|
770 |
+
:param clip_denoised: if True, clip the denoised signal into [-1, 1].
|
771 |
+
:param model_kwargs: if not None, a dict of extra keyword arguments to
|
772 |
+
pass to the model. This can be used for conditioning.
|
773 |
+
:return: a dict with the following keys:
|
774 |
+
- 'mean': the model mean output.
|
775 |
+
- 'variance': the model variance output.
|
776 |
+
- 'log_variance': the log of 'variance'.
|
777 |
+
- 'pred_xstart': the prediction for x_0.
|
778 |
+
"""
|
779 |
+
|
780 |
+
B, C = x.shape[:2]
|
781 |
+
assert t.shape == (B,)
|
782 |
+
if transformer_out is None:
|
783 |
+
# super-res model
|
784 |
+
model_output = model(x, t, low_res)
|
785 |
+
else:
|
786 |
+
# text2image model
|
787 |
+
model_output = model(x, t, transformer_out)
|
788 |
+
|
789 |
+
assert model_output.shape == (B, C * 2, *x.shape[2:])
|
790 |
+
model_output, model_var_values = torch.split(model_output, C, dim=1)
|
791 |
+
min_log = _extract_into_tensor(scheduler.posterior_log_variance_clipped, t, x.shape)
|
792 |
+
max_log = _extract_into_tensor(np.log(scheduler.betas), t, x.shape)
|
793 |
+
# The model_var_values is [-1, 1] for [min_var, max_var].
|
794 |
+
frac = (model_var_values + 1) / 2
|
795 |
+
model_log_variance = frac * max_log + (1 - frac) * min_log
|
796 |
+
model_variance = torch.exp(model_log_variance)
|
797 |
+
|
798 |
+
pred_xstart = self._predict_xstart_from_eps(scheduler, x_t=x, t=t, eps=model_output)
|
799 |
+
if clip_denoised:
|
800 |
+
pred_xstart = pred_xstart.clamp(-1, 1)
|
801 |
+
model_mean, _, _ = self.q_posterior_mean_variance(scheduler, x_start=pred_xstart, x_t=x, t=t)
|
802 |
+
|
803 |
+
assert model_mean.shape == model_log_variance.shape == pred_xstart.shape == x.shape
|
804 |
+
return model_mean, model_variance, model_log_variance, pred_xstart
|
805 |
+
|
806 |
+
def _predict_xstart_from_eps(self, scheduler, x_t, t, eps):
|
807 |
+
assert x_t.shape == eps.shape
|
808 |
+
return (
|
809 |
+
_extract_into_tensor(scheduler.sqrt_recip_alphas_cumprod, t, x_t.shape) * x_t
|
810 |
+
- _extract_into_tensor(scheduler.sqrt_recipm1_alphas_cumprod, t, x_t.shape) * eps
|
811 |
+
)
|
812 |
+
|
813 |
+
def _predict_eps_from_xstart(self, scheduler, x_t, t, pred_xstart):
|
814 |
+
return (
|
815 |
+
_extract_into_tensor(scheduler.sqrt_recip_alphas_cumprod, t, x_t.shape) * x_t - pred_xstart
|
816 |
+
) / _extract_into_tensor(scheduler.sqrt_recipm1_alphas_cumprod, t, x_t.shape)
|
817 |
+
|
818 |
+
@torch.no_grad()
|
819 |
+
def __call__(self, prompt, generator=None, torch_device=None, num_inference_steps_upscale=50):
|
820 |
+
torch_device = "cuda" if torch.cuda.is_available() else "cpu"
|
821 |
+
|
822 |
+
self.text_unet.to(torch_device)
|
823 |
+
self.text_encoder.to(torch_device)
|
824 |
+
self.upscale_unet.to(torch_device)
|
825 |
+
|
826 |
+
# Create a classifier-free guidance sampling function
|
827 |
+
guidance_scale = 3.0
|
828 |
+
|
829 |
+
def text_model_fn(x_t, ts, transformer_out, **kwargs):
|
830 |
+
half = x_t[: len(x_t) // 2]
|
831 |
+
combined = torch.cat([half, half], dim=0)
|
832 |
+
model_out = self.text_unet(combined, ts, transformer_out, **kwargs)
|
833 |
+
eps, rest = model_out[:, :3], model_out[:, 3:]
|
834 |
+
cond_eps, uncond_eps = torch.split(eps, len(eps) // 2, dim=0)
|
835 |
+
half_eps = uncond_eps + guidance_scale * (cond_eps - uncond_eps)
|
836 |
+
eps = torch.cat([half_eps, half_eps], dim=0)
|
837 |
+
return torch.cat([eps, rest], dim=1)
|
838 |
+
|
839 |
+
# 1. Sample gaussian noise
|
840 |
+
batch_size = 2 # second image is empty for classifier-free guidance
|
841 |
+
image = self.text_noise_scheduler.sample_noise(
|
842 |
+
(batch_size, self.text_unet.in_channels, 64, 64), device=torch_device, generator=generator
|
843 |
+
)
|
844 |
+
|
845 |
+
# 2. Encode tokens
|
846 |
+
# an empty input is needed to guide the model away from (
|
847 |
+
inputs = self.tokenizer([prompt, ""], padding="max_length", max_length=128, return_tensors="pt")
|
848 |
+
input_ids = inputs["input_ids"].to(torch_device)
|
849 |
+
attention_mask = inputs["attention_mask"].to(torch_device)
|
850 |
+
transformer_out = self.text_encoder(input_ids, attention_mask).last_hidden_state
|
851 |
+
|
852 |
+
# 3. Run the text2image generation step
|
853 |
+
num_timesteps = len(self.text_noise_scheduler)
|
854 |
+
for i in tqdm.tqdm(reversed(range(num_timesteps)), total=num_timesteps):
|
855 |
+
t = torch.tensor([i] * image.shape[0], device=torch_device)
|
856 |
+
mean, variance, log_variance, pred_xstart = self.p_mean_variance(
|
857 |
+
text_model_fn, self.text_noise_scheduler, image, t, transformer_out=transformer_out
|
858 |
+
)
|
859 |
+
noise = self.text_noise_scheduler.sample_noise(image.shape, device=torch_device, generator=generator)
|
860 |
+
nonzero_mask = (t != 0).float().view(-1, *([1] * (len(image.shape) - 1))) # no noise when t == 0
|
861 |
+
image = mean + nonzero_mask * torch.exp(0.5 * log_variance) * noise
|
862 |
+
|
863 |
+
# 4. Run the upscaling step
|
864 |
+
batch_size = 1
|
865 |
+
image = image[:1]
|
866 |
+
low_res = ((image + 1) * 127.5).round() / 127.5 - 1
|
867 |
+
eta = 0.0
|
868 |
+
|
869 |
+
# Tune this parameter to control the sharpness of 256x256 images.
|
870 |
+
# A value of 1.0 is sharper, but sometimes results in grainy artifacts.
|
871 |
+
upsample_temp = 0.997
|
872 |
+
|
873 |
+
# Sample gaussian noise to begin loop
|
874 |
+
image = torch.randn(
|
875 |
+
(batch_size, self.unet.in_channels, self.unet.resolution, self.unet.resolution),
|
876 |
+
generator=generator,
|
877 |
+
)
|
878 |
+
image = image.to(torch_device)
|
879 |
+
|
880 |
+
# See formulas (12) and (16) of DDIM paper https://arxiv.org/pdf/2010.02502.pdf
|
881 |
+
# Ideally, read DDIM paper in-detail understanding
|
882 |
+
|
883 |
+
# Notation (<variable name> -> <name in paper>
|
884 |
+
# - pred_noise_t -> e_theta(x_t, t)
|
885 |
+
# - pred_original_image -> f_theta(x_t, t) or x_0
|
886 |
+
# - std_dev_t -> sigma_t
|
887 |
+
# - eta -> η
|
888 |
+
# - pred_image_direction -> "direction pointingc to x_t"
|
889 |
+
# - pred_prev_image -> "x_t-1"
|
890 |
+
for t in tqdm.tqdm(reversed(range(num_inference_steps_upscale)), total=num_inference_steps_upscale):
|
891 |
+
# 1. predict noise residual
|
892 |
+
with torch.no_grad():
|
893 |
+
time_input = torch.tensor([t] * image.shape[0], device=torch_device)
|
894 |
+
model_output = self.upscale_unet(image, time_input, low_res)
|
895 |
+
noise_residual, pred_variance = torch.split(model_output, 3, dim=1)
|
896 |
+
|
897 |
+
# 2. predict previous mean of image x_t-1
|
898 |
+
pred_prev_image = self.upscale_noise_scheduler.step(noise_residual, image, t, num_inference_steps_upscale, eta)
|
899 |
+
|
900 |
+
# 3. optionally sample variance
|
901 |
+
variance = 0
|
902 |
+
if eta > 0:
|
903 |
+
noise = torch.randn(image.shape, generator=generator).to(image.device)
|
904 |
+
variance = self.upscale_noise_scheduler.get_variance(t, num_inference_steps_upscale).sqrt() * eta * noise
|
905 |
+
|
906 |
+
# 4. set current image to prev_image: x_t -> x_t-1
|
907 |
+
image = pred_prev_image + variance
|
908 |
+
|
909 |
+
image = image.permute(0, 2, 3, 1)
|
910 |
+
|
911 |
+
return image
|