anton-l HF staff commited on
Commit
d6cfe66
·
1 Parent(s): ccdcc08

unified model

Browse files
Files changed (1) hide show
  1. modeling_glide.py +678 -4
modeling_glide.py CHANGED
@@ -1,4 +1,5 @@
1
- # Copyright 2022 The HuggingFace Team. All rights reserved.
 
2
  #
3
  # Licensed under the Apache License, Version 2.0 (the "License");
4
  # you may not use this file except in compliance with the License.
@@ -10,23 +11,696 @@
10
  # distributed under the License is distributed on an "AS IS" BASIS,
11
  # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
  # See the License for the specific language governing permissions and
13
-
14
  # limitations under the License.
 
15
 
 
 
 
16
 
17
  import numpy as np
18
  import torch
 
 
19
 
20
  import tqdm
21
  from diffusers import (
22
  ClassifierFreeGuidanceScheduler,
23
- CLIPTextModel,
24
  DiffusionPipeline,
25
  GlideDDIMScheduler,
26
  GLIDESuperResUNetModel,
27
  GLIDETextToImageUNetModel,
28
  )
29
- from transformers import GPT2Tokenizer
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
30
 
31
 
32
  def _extract_into_tensor(arr, timesteps, broadcast_shape):
 
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.
 
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):