anton-l HF Staff commited on
Commit
5db0ddd
·
1 Parent(s): 0ec105b

move the text encoder

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