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

move the text encoder

Browse files
Files changed (2) hide show
  1. model_index.json +1 -1
  2. modeling_clip_encoder.py +682 -0
model_index.json CHANGED
@@ -3,7 +3,7 @@
3
  "_diffusers_version": "0.0.3",
4
  "_module": "pipeline_glide",
5
  "text_encoder": [
6
- "diffusers",
7
  "CLIPTextModel"
8
  ],
9
  "text_noise_scheduler": [
 
3
  "_diffusers_version": "0.0.3",
4
  "_module": "pipeline_glide",
5
  "text_encoder": [
6
+ "modeling_clip_encoder",
7
  "CLIPTextModel"
8
  ],
9
  "text_noise_scheduler": [
modeling_clip_encoder.py ADDED
@@ -0,0 +1,682 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ )