Cuiunbo commited on
Commit
7e9623b
1 Parent(s): b4db9f4

Upload modeling_siglip.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. modeling_siglip.py +1473 -0
modeling_siglip.py ADDED
@@ -0,0 +1,1473 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2024 Google AI 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 Siglip model."""
16
+
17
+
18
+ import math
19
+ import warnings
20
+ from dataclasses import dataclass
21
+ from typing import Any, Optional, Tuple, Union
22
+
23
+ import numpy as np
24
+ import torch
25
+ import torch.nn.functional as F
26
+ import torch.utils.checkpoint
27
+ from torch import nn
28
+ from torch.nn.init import _calculate_fan_in_and_fan_out
29
+
30
+ from transformers.activations import ACT2FN
31
+ from transformers.modeling_attn_mask_utils import _prepare_4d_attention_mask
32
+ from transformers.modeling_outputs import BaseModelOutput, BaseModelOutputWithPooling
33
+ from transformers.modeling_utils import PreTrainedModel
34
+ from transformers.utils import (
35
+ ModelOutput,
36
+ add_start_docstrings,
37
+ add_start_docstrings_to_model_forward,
38
+ is_flash_attn_2_available,
39
+ logging,
40
+ replace_return_docstrings,
41
+ )
42
+ from .configuration_siglip import SiglipConfig, SiglipTextConfig, SiglipVisionConfig
43
+
44
+
45
+ logger = logging.get_logger(__name__)
46
+
47
+ _CHECKPOINT_FOR_DOC = "google/siglip-base-patch16-224"
48
+
49
+ SIGLIP_PRETRAINED_MODEL_ARCHIVE_LIST = [
50
+ "google/siglip-base-patch16-224",
51
+ # See all SigLIP models at https://huggingface.co/models?filter=siglip
52
+ ]
53
+
54
+ if is_flash_attn_2_available():
55
+ from flash_attn import flash_attn_func, flash_attn_varlen_func
56
+ from flash_attn.bert_padding import index_first_axis, pad_input, unpad_input # noqa
57
+
58
+
59
+ # Copied from transformers.models.llama.modeling_llama._get_unpad_data
60
+ def _get_unpad_data(attention_mask):
61
+ seqlens_in_batch = attention_mask.sum(dim=-1, dtype=torch.int32)
62
+ indices = torch.nonzero(attention_mask.flatten(), as_tuple=False).flatten()
63
+ max_seqlen_in_batch = seqlens_in_batch.max().item()
64
+ cu_seqlens = F.pad(torch.cumsum(seqlens_in_batch, dim=0, dtype=torch.torch.int32), (1, 0))
65
+ return (
66
+ indices,
67
+ cu_seqlens,
68
+ max_seqlen_in_batch,
69
+ )
70
+
71
+
72
+ def _trunc_normal_(tensor, mean, std, a, b):
73
+ # Cut & paste from PyTorch official master until it's in a few official releases - RW
74
+ # Method based on https://people.sc.fsu.edu/~jburkardt/presentations/truncated_normal.pdf
75
+ def norm_cdf(x):
76
+ # Computes standard normal cumulative distribution function
77
+ return (1.0 + math.erf(x / math.sqrt(2.0))) / 2.0
78
+
79
+ if (mean < a - 2 * std) or (mean > b + 2 * std):
80
+ warnings.warn(
81
+ "mean is more than 2 std from [a, b] in nn.init.trunc_normal_. "
82
+ "The distribution of values may be incorrect.",
83
+ stacklevel=2,
84
+ )
85
+
86
+ # Values are generated by using a truncated uniform distribution and
87
+ # then using the inverse CDF for the normal distribution.
88
+ # Get upper and lower cdf values
89
+ l = norm_cdf((a - mean) / std)
90
+ u = norm_cdf((b - mean) / std)
91
+
92
+ # Uniformly fill tensor with values from [l, u], then translate to
93
+ # [2l-1, 2u-1].
94
+ tensor.uniform_(2 * l - 1, 2 * u - 1)
95
+
96
+ # Use inverse cdf transform for normal distribution to get truncated
97
+ # standard normal
98
+ if tensor.dtype in [torch.float16, torch.bfloat16]:
99
+ # The `erfinv_` op is not (yet?) defined in float16+cpu, bfloat16+gpu
100
+ og_dtype = tensor.dtype
101
+ tensor = tensor.to(torch.float32)
102
+ tensor.erfinv_()
103
+ tensor = tensor.to(og_dtype)
104
+ else:
105
+ tensor.erfinv_()
106
+
107
+ # Transform to proper mean, std
108
+ tensor.mul_(std * math.sqrt(2.0))
109
+ tensor.add_(mean)
110
+
111
+ # Clamp to ensure it's in the proper range
112
+ if tensor.dtype == torch.float16:
113
+ # The `clamp_` op is not (yet?) defined in float16+cpu
114
+ tensor = tensor.to(torch.float32)
115
+ tensor.clamp_(min=a, max=b)
116
+ tensor = tensor.to(torch.float16)
117
+ else:
118
+ tensor.clamp_(min=a, max=b)
119
+
120
+
121
+ def trunc_normal_tf_(
122
+ tensor: torch.Tensor, mean: float = 0.0, std: float = 1.0, a: float = -2.0, b: float = 2.0
123
+ ) -> torch.Tensor:
124
+ """Fills the input Tensor with values drawn from a truncated
125
+ normal distribution. The values are effectively drawn from the
126
+ normal distribution :math:`\\mathcal{N}(\text{mean}, \text{std}^2)`
127
+ with values outside :math:`[a, b]` redrawn until they are within
128
+ the bounds. The method used for generating the random values works
129
+ best when :math:`a \\leq \text{mean} \\leq b`.
130
+
131
+ NOTE: this 'tf' variant behaves closer to Tensorflow / JAX impl where the
132
+ bounds [a, b] are applied when sampling the normal distribution with mean=0, std=1.0
133
+ and the result is subsquently scaled and shifted by the mean and std args.
134
+
135
+ Args:
136
+ tensor: an n-dimensional `torch.Tensor`
137
+ mean: the mean of the normal distribution
138
+ std: the standard deviation of the normal distribution
139
+ a: the minimum cutoff value
140
+ b: the maximum cutoff value
141
+ """
142
+ with torch.no_grad():
143
+ _trunc_normal_(tensor, 0, 1.0, a, b)
144
+ tensor.mul_(std).add_(mean)
145
+
146
+
147
+ def variance_scaling_(tensor, scale=1.0, mode="fan_in", distribution="normal"):
148
+ fan_in, fan_out = _calculate_fan_in_and_fan_out(tensor)
149
+ if mode == "fan_in":
150
+ denom = fan_in
151
+ elif mode == "fan_out":
152
+ denom = fan_out
153
+ elif mode == "fan_avg":
154
+ denom = (fan_in + fan_out) / 2
155
+
156
+ variance = scale / denom
157
+
158
+ if distribution == "truncated_normal":
159
+ # constant is stddev of standard normal truncated to (-2, 2)
160
+ trunc_normal_tf_(tensor, std=math.sqrt(variance) / 0.87962566103423978)
161
+ elif distribution == "normal":
162
+ with torch.no_grad():
163
+ tensor.normal_(std=math.sqrt(variance))
164
+ elif distribution == "uniform":
165
+ bound = math.sqrt(3 * variance)
166
+ with torch.no_grad():
167
+ tensor.uniform_(-bound, bound)
168
+ else:
169
+ raise ValueError(f"invalid distribution {distribution}")
170
+
171
+
172
+ def lecun_normal_(tensor):
173
+ variance_scaling_(tensor, mode="fan_in", distribution="truncated_normal")
174
+
175
+
176
+ def default_flax_embed_init(tensor):
177
+ variance_scaling_(tensor, mode="fan_in", distribution="normal")
178
+
179
+
180
+ @dataclass
181
+ # Copied from transformers.models.clip.modeling_clip.CLIPVisionModelOutput with CLIP->Siglip
182
+ class SiglipVisionModelOutput(ModelOutput):
183
+ """
184
+ Base class for vision model's outputs that also contains image embeddings of the pooling of the last hidden states.
185
+
186
+ Args:
187
+ image_embeds (`torch.FloatTensor` of shape `(batch_size, output_dim)` *optional* returned when model is initialized with `with_projection=True`):
188
+ The image embeddings obtained by applying the projection layer to the pooler_output.
189
+ last_hidden_state (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`):
190
+ Sequence of hidden-states at the output of the last layer of the model.
191
+ hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
192
+ Tuple of `torch.FloatTensor` (one for the output of the embeddings, if the model has an embedding layer, +
193
+ one for the output of each layer) of shape `(batch_size, sequence_length, hidden_size)`.
194
+
195
+ Hidden-states of the model at the output of each layer plus the optional initial embedding outputs.
196
+ attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
197
+ Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
198
+ sequence_length)`.
199
+
200
+ Attentions weights after the attention softmax, used to compute the weighted average in the self-attention
201
+ heads.
202
+ """
203
+
204
+ image_embeds: Optional[torch.FloatTensor] = None
205
+ last_hidden_state: torch.FloatTensor = None
206
+ hidden_states: Optional[Tuple[torch.FloatTensor]] = None
207
+ attentions: Optional[Tuple[torch.FloatTensor]] = None
208
+
209
+
210
+ @dataclass
211
+ # Copied from transformers.models.clip.modeling_clip.CLIPTextModelOutput with CLIP->Siglip
212
+ class SiglipTextModelOutput(ModelOutput):
213
+ """
214
+ Base class for text model's outputs that also contains a pooling of the last hidden states.
215
+
216
+ Args:
217
+ text_embeds (`torch.FloatTensor` of shape `(batch_size, output_dim)` *optional* returned when model is initialized with `with_projection=True`):
218
+ The text embeddings obtained by applying the projection layer to the pooler_output.
219
+ last_hidden_state (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`):
220
+ Sequence of hidden-states at the output of the last layer of the model.
221
+ hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
222
+ Tuple of `torch.FloatTensor` (one for the output of the embeddings, if the model has an embedding layer, +
223
+ one for the output of each layer) of shape `(batch_size, sequence_length, hidden_size)`.
224
+
225
+ Hidden-states of the model at the output of each layer plus the optional initial embedding outputs.
226
+ attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
227
+ Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
228
+ sequence_length)`.
229
+
230
+ Attentions weights after the attention softmax, used to compute the weighted average in the self-attention
231
+ heads.
232
+ """
233
+
234
+ text_embeds: Optional[torch.FloatTensor] = None
235
+ last_hidden_state: torch.FloatTensor = None
236
+ hidden_states: Optional[Tuple[torch.FloatTensor]] = None
237
+ attentions: Optional[Tuple[torch.FloatTensor]] = None
238
+
239
+
240
+ @dataclass
241
+ # Copied from transformers.models.clip.modeling_clip.CLIPOutput with CLIP->Siglip
242
+ class SiglipOutput(ModelOutput):
243
+ """
244
+ Args:
245
+ loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `return_loss` is `True`):
246
+ Contrastive loss for image-text similarity.
247
+ logits_per_image:(`torch.FloatTensor` of shape `(image_batch_size, text_batch_size)`):
248
+ The scaled dot product scores between `image_embeds` and `text_embeds`. This represents the image-text
249
+ similarity scores.
250
+ logits_per_text:(`torch.FloatTensor` of shape `(text_batch_size, image_batch_size)`):
251
+ The scaled dot product scores between `text_embeds` and `image_embeds`. This represents the text-image
252
+ similarity scores.
253
+ text_embeds(`torch.FloatTensor` of shape `(batch_size, output_dim`):
254
+ The text embeddings obtained by applying the projection layer to the pooled output of [`SiglipTextModel`].
255
+ image_embeds(`torch.FloatTensor` of shape `(batch_size, output_dim`):
256
+ The image embeddings obtained by applying the projection layer to the pooled output of [`SiglipVisionModel`].
257
+ text_model_output(`BaseModelOutputWithPooling`):
258
+ The output of the [`SiglipTextModel`].
259
+ vision_model_output(`BaseModelOutputWithPooling`):
260
+ The output of the [`SiglipVisionModel`].
261
+ """
262
+
263
+ loss: Optional[torch.FloatTensor] = None
264
+ logits_per_image: torch.FloatTensor = None
265
+ logits_per_text: torch.FloatTensor = None
266
+ text_embeds: torch.FloatTensor = None
267
+ image_embeds: torch.FloatTensor = None
268
+ text_model_output: BaseModelOutputWithPooling = None
269
+ vision_model_output: BaseModelOutputWithPooling = None
270
+
271
+ def to_tuple(self) -> Tuple[Any]:
272
+ return tuple(
273
+ self[k] if k not in ["text_model_output", "vision_model_output"] else getattr(self, k).to_tuple()
274
+ for k in self.keys()
275
+ )
276
+
277
+
278
+ class SiglipVisionEmbeddings(nn.Module):
279
+ def __init__(self, config: SiglipVisionConfig):
280
+ super().__init__()
281
+ self.config = config
282
+ self.embed_dim = config.hidden_size
283
+ self.image_size = config.image_size
284
+ self.patch_size = config.patch_size
285
+
286
+ self.patch_embedding = nn.Conv2d(
287
+ in_channels=config.num_channels,
288
+ out_channels=self.embed_dim,
289
+ kernel_size=self.patch_size,
290
+ stride=self.patch_size,
291
+ padding="valid",
292
+ )
293
+
294
+ self.num_patches_per_side = self.image_size // self.patch_size
295
+ self.num_patches = self.num_patches_per_side**2
296
+ self.num_positions = self.num_patches
297
+ self.position_embedding = nn.Embedding(self.num_positions, self.embed_dim)
298
+
299
+ def forward(self, pixel_values: torch.FloatTensor, patch_attention_mask: torch.BoolTensor) -> torch.Tensor:
300
+ batch_size = pixel_values.size(0)
301
+
302
+ patch_embeds = self.patch_embedding(pixel_values)
303
+ embeddings = patch_embeds.flatten(2).transpose(1, 2)
304
+
305
+ max_im_h, max_im_w = pixel_values.size(2), pixel_values.size(3)
306
+ max_nb_patches_h, max_nb_patches_w = max_im_h // self.patch_size, max_im_w // self.patch_size
307
+ boundaries = torch.arange(1 / self.num_patches_per_side, 1.0, 1 / self.num_patches_per_side)
308
+ position_ids = torch.full(
309
+ size=(
310
+ batch_size,
311
+ max_nb_patches_h * max_nb_patches_w,
312
+ ),
313
+ fill_value=0,
314
+ )
315
+
316
+ for batch_idx, p_attn_mask in enumerate(patch_attention_mask):
317
+ nb_patches_h = p_attn_mask[:, 0].sum()
318
+ nb_patches_w = p_attn_mask[0].sum()
319
+
320
+ fractional_coords_h = torch.arange(0, 1 - 1e-6, 1 / nb_patches_h)
321
+ fractional_coords_w = torch.arange(0, 1 - 1e-6, 1 / nb_patches_w)
322
+
323
+ bucket_coords_h = torch.bucketize(fractional_coords_h, boundaries, right=True)
324
+ bucket_coords_w = torch.bucketize(fractional_coords_w, boundaries, right=True)
325
+
326
+ pos_ids = (bucket_coords_h[:, None] * self.num_patches_per_side + bucket_coords_w).flatten()
327
+ position_ids[batch_idx][p_attn_mask.view(-1).cpu()] = pos_ids
328
+
329
+ position_ids = position_ids.to(self.position_embedding.weight.device)
330
+
331
+ embeddings = embeddings + self.position_embedding(position_ids)
332
+ return embeddings
333
+
334
+
335
+ # Copied from transformers.models.clip.modeling_clip.CLIPTextEmbeddings with CLIP->Siglip
336
+ class SiglipTextEmbeddings(nn.Module):
337
+ def __init__(self, config: SiglipTextConfig):
338
+ super().__init__()
339
+ embed_dim = config.hidden_size
340
+
341
+ self.token_embedding = nn.Embedding(config.vocab_size, embed_dim)
342
+ self.position_embedding = nn.Embedding(config.max_position_embeddings, embed_dim)
343
+
344
+ # position_ids (1, len position emb) is contiguous in memory and exported when serialized
345
+ self.register_buffer(
346
+ "position_ids", torch.arange(config.max_position_embeddings).expand((1, -1)), persistent=False
347
+ )
348
+
349
+ def forward(
350
+ self,
351
+ input_ids: Optional[torch.LongTensor] = None,
352
+ position_ids: Optional[torch.LongTensor] = None,
353
+ inputs_embeds: Optional[torch.FloatTensor] = None,
354
+ ) -> torch.Tensor:
355
+ seq_length = input_ids.shape[-1] if input_ids is not None else inputs_embeds.shape[-2]
356
+
357
+ if position_ids is None:
358
+ position_ids = self.position_ids[:, :seq_length]
359
+
360
+ if inputs_embeds is None:
361
+ inputs_embeds = self.token_embedding(input_ids)
362
+
363
+ position_embeddings = self.position_embedding(position_ids)
364
+ embeddings = inputs_embeds + position_embeddings
365
+
366
+ return embeddings
367
+
368
+
369
+ class SiglipAttention(nn.Module):
370
+ """Multi-headed attention from 'Attention Is All You Need' paper"""
371
+
372
+ # Copied from transformers.models.clip.modeling_clip.CLIPAttention.__init__
373
+ def __init__(self, config):
374
+ super().__init__()
375
+ self.config = config
376
+ self.embed_dim = config.hidden_size
377
+ self.num_heads = config.num_attention_heads
378
+ self.head_dim = self.embed_dim // self.num_heads
379
+ if self.head_dim * self.num_heads != self.embed_dim:
380
+ raise ValueError(
381
+ f"embed_dim must be divisible by num_heads (got `embed_dim`: {self.embed_dim} and `num_heads`:"
382
+ f" {self.num_heads})."
383
+ )
384
+ self.scale = self.head_dim**-0.5
385
+ self.dropout = config.attention_dropout
386
+
387
+ self.k_proj = nn.Linear(self.embed_dim, self.embed_dim)
388
+ self.v_proj = nn.Linear(self.embed_dim, self.embed_dim)
389
+ self.q_proj = nn.Linear(self.embed_dim, self.embed_dim)
390
+ self.out_proj = nn.Linear(self.embed_dim, self.embed_dim)
391
+
392
+ def forward(
393
+ self,
394
+ hidden_states: torch.Tensor,
395
+ attention_mask: Optional[torch.Tensor] = None,
396
+ output_attentions: Optional[bool] = False,
397
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
398
+ """Input shape: Batch x Time x Channel"""
399
+
400
+ batch_size, q_len, _ = hidden_states.size()
401
+
402
+ query_states = self.q_proj(hidden_states)
403
+ key_states = self.k_proj(hidden_states)
404
+ value_states = self.v_proj(hidden_states)
405
+
406
+ query_states = query_states.view(batch_size, q_len, self.num_heads, self.head_dim).transpose(1, 2)
407
+ key_states = key_states.view(batch_size, q_len, self.num_heads, self.head_dim).transpose(1, 2)
408
+ value_states = value_states.view(batch_size, q_len, self.num_heads, self.head_dim).transpose(1, 2)
409
+
410
+ k_v_seq_len = key_states.shape[-2]
411
+ attn_weights = torch.matmul(query_states, key_states.transpose(2, 3)) * self.scale
412
+
413
+ if attn_weights.size() != (batch_size, self.num_heads, q_len, k_v_seq_len):
414
+ raise ValueError(
415
+ f"Attention weights should be of size {(batch_size, self.num_heads, q_len, k_v_seq_len)}, but is"
416
+ f" {attn_weights.size()}"
417
+ )
418
+
419
+ if attention_mask is not None:
420
+ if attention_mask.size() != (batch_size, 1, q_len, k_v_seq_len):
421
+ raise ValueError(
422
+ f"Attention mask should be of size {(batch_size, 1, q_len, k_v_seq_len)}, but is {attention_mask.size()}"
423
+ )
424
+ attn_weights = attn_weights + attention_mask
425
+
426
+ # upcast attention to fp32
427
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query_states.dtype)
428
+ attn_weights = nn.functional.dropout(attn_weights, p=self.dropout, training=self.training)
429
+ attn_output = torch.matmul(attn_weights, value_states)
430
+
431
+ if attn_output.size() != (batch_size, self.num_heads, q_len, self.head_dim):
432
+ raise ValueError(
433
+ f"`attn_output` should be of size {(batch_size, self.num_heads, q_len, self.head_dim)}, but is"
434
+ f" {attn_output.size()}"
435
+ )
436
+
437
+ attn_output = attn_output.transpose(1, 2).contiguous()
438
+ attn_output = attn_output.reshape(batch_size, q_len, self.embed_dim)
439
+
440
+ attn_output = self.out_proj(attn_output)
441
+
442
+ return attn_output, attn_weights
443
+
444
+
445
+ class SiglipFlashAttention2(SiglipAttention):
446
+ """
447
+ Llama flash attention module. This module inherits from `LlamaAttention` as the weights of the module stays
448
+ untouched. The only required change would be on the forward pass where it needs to correctly call the public API of
449
+ flash attention and deal with padding tokens in case the input contains any of them.
450
+ """
451
+
452
+ def __init__(self, *args, **kwargs):
453
+ super().__init__(*args, **kwargs)
454
+ self.is_causal = False # Hack to make sure we don't use a causal mask
455
+
456
+ def forward(
457
+ self,
458
+ hidden_states: torch.Tensor,
459
+ attention_mask: Optional[torch.LongTensor] = None,
460
+ position_ids: Optional[torch.LongTensor] = None,
461
+ past_key_value: Optional[Tuple[torch.Tensor]] = None,
462
+ output_attentions: bool = False,
463
+ use_cache: bool = False,
464
+ **kwargs,
465
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
466
+ output_attentions = False
467
+
468
+ bsz, q_len, _ = hidden_states.size()
469
+
470
+ query_states = self.q_proj(hidden_states)
471
+ key_states = self.k_proj(hidden_states)
472
+ value_states = self.v_proj(hidden_states)
473
+
474
+ # Flash attention requires the input to have the shape
475
+ # batch_size x seq_length x head_dim x hidden_dim
476
+ # therefore we just need to keep the original shape
477
+ query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
478
+ key_states = key_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
479
+ value_states = value_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
480
+
481
+ kv_seq_len = key_states.shape[-2]
482
+ if past_key_value is not None:
483
+ kv_seq_len += past_key_value.get_usable_length(kv_seq_len, self.layer_idx)
484
+ # cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len)
485
+ # query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids)
486
+
487
+ # if past_key_value is not None:
488
+ # cache_kwargs = {"sin": sin, "cos": cos} # Specific to RoPE models
489
+ # key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
490
+
491
+ # TODO: These transpose are quite inefficient but Flash Attention requires the layout [batch_size, sequence_length, num_heads, head_dim]. We would need to refactor the KV cache
492
+ # to be able to avoid many of these transpose/reshape/view.
493
+ query_states = query_states.transpose(1, 2)
494
+ key_states = key_states.transpose(1, 2)
495
+ value_states = value_states.transpose(1, 2)
496
+
497
+ dropout_rate = self.dropout if self.training else 0.0
498
+
499
+ # In PEFT, usually we cast the layer norms in float32 for training stability reasons
500
+ # therefore the input hidden states gets silently casted in float32. Hence, we need
501
+ # cast them back in the correct dtype just to be sure everything works as expected.
502
+ # This might slowdown training & inference so it is recommended to not cast the LayerNorms
503
+ # in fp32. (LlamaRMSNorm handles it correctly)
504
+
505
+ input_dtype = query_states.dtype
506
+ if input_dtype == torch.float32:
507
+ if torch.is_autocast_enabled():
508
+ target_dtype = torch.get_autocast_gpu_dtype()
509
+ # Handle the case where the model is quantized
510
+ elif hasattr(self.config, "_pre_quantization_dtype"):
511
+ target_dtype = self.config._pre_quantization_dtype
512
+ else:
513
+ target_dtype = self.q_proj.weight.dtype
514
+
515
+ logger.warning_once(
516
+ "The input hidden states seems to be silently casted in float32, this might be related to the fact"
517
+ " you have upcasted embedding or layer norm layers in float32. We will cast back the input in"
518
+ f" {target_dtype}."
519
+ )
520
+
521
+ query_states = query_states.to(target_dtype)
522
+ key_states = key_states.to(target_dtype)
523
+ value_states = value_states.to(target_dtype)
524
+
525
+ attn_output = self._flash_attention_forward(
526
+ query_states, key_states, value_states, attention_mask, q_len, dropout=dropout_rate
527
+ )
528
+
529
+ attn_output = attn_output.reshape(bsz, q_len, self.embed_dim).contiguous()
530
+ attn_output = self.out_proj(attn_output)
531
+
532
+ if not output_attentions:
533
+ attn_weights = None
534
+
535
+ return attn_output, attn_weights
536
+
537
+ def _flash_attention_forward(
538
+ self, query_states, key_states, value_states, attention_mask, query_length, dropout=0.0, softmax_scale=None
539
+ ):
540
+ """
541
+ Calls the forward method of Flash Attention - if the input hidden states contain at least one padding token
542
+ first unpad the input, then computes the attention scores and pad the final attention scores.
543
+
544
+ Args:
545
+ query_states (`torch.Tensor`):
546
+ Input query states to be passed to Flash Attention API
547
+ key_states (`torch.Tensor`):
548
+ Input key states to be passed to Flash Attention API
549
+ value_states (`torch.Tensor`):
550
+ Input value states to be passed to Flash Attention API
551
+ attention_mask (`torch.Tensor`):
552
+ The padding mask - corresponds to a tensor of size `(batch_size, seq_len)` where 0 stands for the
553
+ position of padding tokens and 1 for the position of non-padding tokens.
554
+ dropout (`int`, *optional*):
555
+ Attention dropout
556
+ softmax_scale (`float`, *optional*):
557
+ The scaling of QK^T before applying softmax. Default to 1 / sqrt(head_dim)
558
+ """
559
+
560
+ # TODO: Remove the `query_length != 1` check once Flash Attention for RoCm is bumped to 2.1. For details, please see the comment in LlamaFlashAttention2 __init__.
561
+ causal = self.is_causal and query_length != 1
562
+
563
+ # Contains at least one padding token in the sequence
564
+ if attention_mask is not None:
565
+ batch_size = query_states.shape[0]
566
+ query_states, key_states, value_states, indices_q, cu_seq_lens, max_seq_lens = self._upad_input(
567
+ query_states, key_states, value_states, attention_mask, query_length
568
+ )
569
+
570
+ cu_seqlens_q, cu_seqlens_k = cu_seq_lens
571
+ max_seqlen_in_batch_q, max_seqlen_in_batch_k = max_seq_lens
572
+
573
+ attn_output_unpad = flash_attn_varlen_func(
574
+ query_states,
575
+ key_states,
576
+ value_states,
577
+ cu_seqlens_q=cu_seqlens_q,
578
+ cu_seqlens_k=cu_seqlens_k,
579
+ max_seqlen_q=max_seqlen_in_batch_q,
580
+ max_seqlen_k=max_seqlen_in_batch_k,
581
+ dropout_p=dropout,
582
+ softmax_scale=softmax_scale,
583
+ causal=causal,
584
+ )
585
+
586
+ attn_output = pad_input(attn_output_unpad, indices_q, batch_size, query_length)
587
+ else:
588
+ attn_output = flash_attn_func(
589
+ query_states, key_states, value_states, dropout, softmax_scale=softmax_scale, causal=causal
590
+ )
591
+
592
+ return attn_output
593
+
594
+ def _upad_input(self, query_layer, key_layer, value_layer, attention_mask, query_length):
595
+ indices_k, cu_seqlens_k, max_seqlen_in_batch_k = _get_unpad_data(attention_mask)
596
+ batch_size, kv_seq_len, num_key_value_heads, head_dim = key_layer.shape
597
+
598
+ key_layer = index_first_axis(
599
+ key_layer.reshape(batch_size * kv_seq_len, num_key_value_heads, head_dim), indices_k
600
+ )
601
+ value_layer = index_first_axis(
602
+ value_layer.reshape(batch_size * kv_seq_len, num_key_value_heads, head_dim), indices_k
603
+ )
604
+ if query_length == kv_seq_len:
605
+ query_layer = index_first_axis(
606
+ query_layer.reshape(batch_size * kv_seq_len, self.num_heads, head_dim), indices_k
607
+ )
608
+ cu_seqlens_q = cu_seqlens_k
609
+ max_seqlen_in_batch_q = max_seqlen_in_batch_k
610
+ indices_q = indices_k
611
+ elif query_length == 1:
612
+ max_seqlen_in_batch_q = 1
613
+ cu_seqlens_q = torch.arange(
614
+ batch_size + 1, dtype=torch.int32, device=query_layer.device
615
+ ) # There is a memcpy here, that is very bad.
616
+ indices_q = cu_seqlens_q[:-1]
617
+ query_layer = query_layer.squeeze(1)
618
+ else:
619
+ # The -q_len: slice assumes left padding.
620
+ attention_mask = attention_mask[:, -query_length:]
621
+ query_layer, indices_q, cu_seqlens_q, max_seqlen_in_batch_q = unpad_input(query_layer, attention_mask)
622
+
623
+ return (
624
+ query_layer,
625
+ key_layer,
626
+ value_layer,
627
+ indices_q,
628
+ (cu_seqlens_q, cu_seqlens_k),
629
+ (max_seqlen_in_batch_q, max_seqlen_in_batch_k),
630
+ )
631
+
632
+
633
+ # Copied from transformers.models.clip.modeling_clip.CLIPMLP with CLIP->Siglip
634
+ class SiglipMLP(nn.Module):
635
+ def __init__(self, config):
636
+ super().__init__()
637
+ self.config = config
638
+ self.activation_fn = ACT2FN[config.hidden_act]
639
+ self.fc1 = nn.Linear(config.hidden_size, config.intermediate_size)
640
+ self.fc2 = nn.Linear(config.intermediate_size, config.hidden_size)
641
+
642
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
643
+ hidden_states = self.fc1(hidden_states)
644
+ hidden_states = self.activation_fn(hidden_states)
645
+ hidden_states = self.fc2(hidden_states)
646
+ return hidden_states
647
+
648
+
649
+ # Copied from transformers.models.clip.modeling_clip.CLIPEncoderLayer with CLIP->Siglip
650
+ class SiglipEncoderLayer(nn.Module):
651
+ def __init__(self, config: SiglipConfig):
652
+ super().__init__()
653
+ self.embed_dim = config.hidden_size
654
+ self.self_attn = (
655
+ SiglipAttention(config)
656
+ if not getattr(config, "_flash_attn_2_enabled", False)
657
+ else SiglipFlashAttention2(config)
658
+ )
659
+ self.layer_norm1 = nn.LayerNorm(self.embed_dim, eps=config.layer_norm_eps)
660
+ self.mlp = SiglipMLP(config)
661
+ self.layer_norm2 = nn.LayerNorm(self.embed_dim, eps=config.layer_norm_eps)
662
+
663
+ def forward(
664
+ self,
665
+ hidden_states: torch.Tensor,
666
+ attention_mask: torch.Tensor,
667
+ output_attentions: Optional[bool] = False,
668
+ ) -> Tuple[torch.FloatTensor]:
669
+ """
670
+ Args:
671
+ hidden_states (`torch.FloatTensor`):
672
+ Input to the layer of shape `(batch, seq_len, embed_dim)`.
673
+ attention_mask (`torch.FloatTensor`):
674
+ Attention mask of shape `(batch, 1, q_len, k_v_seq_len)` where padding elements are indicated by very large negative values.
675
+ output_attentions (`bool`, *optional*, defaults to `False`):
676
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
677
+ returned tensors for more detail.
678
+ """
679
+ residual = hidden_states
680
+
681
+ hidden_states = self.layer_norm1(hidden_states)
682
+ hidden_states, attn_weights = self.self_attn(
683
+ hidden_states=hidden_states,
684
+ attention_mask=attention_mask,
685
+ output_attentions=output_attentions,
686
+ )
687
+ hidden_states = residual + hidden_states
688
+
689
+ residual = hidden_states
690
+ hidden_states = self.layer_norm2(hidden_states)
691
+ hidden_states = self.mlp(hidden_states)
692
+ hidden_states = residual + hidden_states
693
+
694
+ outputs = (hidden_states,)
695
+
696
+ if output_attentions:
697
+ outputs += (attn_weights,)
698
+
699
+ return outputs
700
+
701
+
702
+ class SiglipPreTrainedModel(PreTrainedModel):
703
+ """
704
+ An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
705
+ models.
706
+ """
707
+
708
+ config_class = SiglipConfig
709
+ base_model_prefix = "siglip"
710
+ supports_gradient_checkpointing = True
711
+
712
+ def _init_weights(self, module):
713
+ """Initialize the weights"""
714
+
715
+ if isinstance(module, SiglipVisionEmbeddings):
716
+ width = (
717
+ self.config.vision_config.hidden_size
718
+ if isinstance(self.config, SiglipConfig)
719
+ else self.config.hidden_size
720
+ )
721
+ nn.init.normal_(module.position_embedding.weight, std=1 / np.sqrt(width))
722
+ elif isinstance(module, nn.Embedding):
723
+ default_flax_embed_init(module.weight)
724
+ elif isinstance(module, SiglipAttention):
725
+ nn.init.normal_(module.q_proj.weight)
726
+ nn.init.normal_(module.k_proj.weight)
727
+ nn.init.normal_(module.v_proj.weight)
728
+ nn.init.normal_(module.out_proj.weight)
729
+ nn.init.zeros_(module.q_proj.bias)
730
+ nn.init.zeros_(module.k_proj.bias)
731
+ nn.init.zeros_(module.v_proj.bias)
732
+ nn.init.zeros_(module.out_proj.bias)
733
+ elif isinstance(module, SiglipMLP):
734
+ nn.init.normal_(module.fc1.weight)
735
+ nn.init.normal_(module.fc2.weight)
736
+ nn.init.normal_(module.fc1.bias, std=1e-6)
737
+ nn.init.normal_(module.fc2.bias, std=1e-6)
738
+ elif isinstance(module, SiglipMultiheadAttentionPoolingHead):
739
+ nn.init.normal_(module.probe.data)
740
+ nn.init.normal_(module.attention.in_proj_weight.data)
741
+ nn.init.zeros_(module.attention.in_proj_bias.data)
742
+ elif isinstance(module, SiglipModel):
743
+ logit_scale_init = torch.tensor(0.0)
744
+ module.logit_scale.data.fill_(logit_scale_init)
745
+ module.logit_bias.data.zero_()
746
+ elif isinstance(module, (nn.Linear, nn.Conv2d)):
747
+ lecun_normal_(module.weight)
748
+ if module.bias is not None:
749
+ nn.init.zeros_(module.bias)
750
+ elif isinstance(module, nn.LayerNorm):
751
+ module.bias.data.zero_()
752
+ module.weight.data.fill_(1.0)
753
+
754
+
755
+ SIGLIP_START_DOCSTRING = r"""
756
+ This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
757
+ library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
758
+ etc.)
759
+
760
+ This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
761
+ Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
762
+ and behavior.
763
+
764
+ Parameters:
765
+ config ([`SiglipConfig`]): Model configuration class with all the parameters of the model.
766
+ Initializing with a config file does not load the weights associated with the model, only the
767
+ configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.
768
+ """
769
+
770
+ SIGLIP_TEXT_INPUTS_DOCSTRING = r"""
771
+ Args:
772
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
773
+ Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
774
+ it.
775
+
776
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
777
+ [`PreTrainedTokenizer.__call__`] for details.
778
+
779
+ [What are input IDs?](../glossary#input-ids)
780
+ attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
781
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
782
+
783
+ - 1 for tokens that are **not masked**,
784
+ - 0 for tokens that are **masked**.
785
+
786
+ [What are attention masks?](../glossary#attention-mask)
787
+ position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
788
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
789
+ config.max_position_embeddings - 1]`.
790
+
791
+ [What are position IDs?](../glossary#position-ids)
792
+ output_attentions (`bool`, *optional*):
793
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
794
+ tensors for more detail.
795
+ output_hidden_states (`bool`, *optional*):
796
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
797
+ more detail.
798
+ return_dict (`bool`, *optional*):
799
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
800
+ """
801
+
802
+ SIGLIP_VISION_INPUTS_DOCSTRING = r"""
803
+ Args:
804
+ pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`):
805
+ Pixel values. Padding will be ignored by default should you provide it. Pixel values can be obtained using
806
+ [`AutoImageProcessor`]. See [`CLIPImageProcessor.__call__`] for details.
807
+ output_attentions (`bool`, *optional*):
808
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
809
+ tensors for more detail.
810
+ output_hidden_states (`bool`, *optional*):
811
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
812
+ more detail.
813
+ return_dict (`bool`, *optional*):
814
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
815
+ """
816
+
817
+ SIGLIP_INPUTS_DOCSTRING = r"""
818
+ Args:
819
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
820
+ Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
821
+ it.
822
+
823
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
824
+ [`PreTrainedTokenizer.__call__`] for details.
825
+
826
+ [What are input IDs?](../glossary#input-ids)
827
+ attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
828
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
829
+
830
+ - 1 for tokens that are **not masked**,
831
+ - 0 for tokens that are **masked**.
832
+
833
+ [What are attention masks?](../glossary#attention-mask)
834
+ position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
835
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
836
+ config.max_position_embeddings - 1]`.
837
+
838
+ [What are position IDs?](../glossary#position-ids)
839
+ pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`):
840
+ Pixel values. Padding will be ignored by default should you provide it. Pixel values can be obtained using
841
+ [`AutoImageProcessor`]. See [`CLIPImageProcessor.__call__`] for details.
842
+ return_loss (`bool`, *optional*):
843
+ Whether or not to return the contrastive loss.
844
+ output_attentions (`bool`, *optional*):
845
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
846
+ tensors for more detail.
847
+ output_hidden_states (`bool`, *optional*):
848
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
849
+ more detail.
850
+ return_dict (`bool`, *optional*):
851
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
852
+ """
853
+
854
+
855
+ # Copied from transformers.models.clip.modeling_clip.CLIPEncoder with CLIP->Siglip
856
+ class SiglipEncoder(nn.Module):
857
+ """
858
+ Transformer encoder consisting of `config.num_hidden_layers` self attention layers. Each layer is a
859
+ [`SiglipEncoderLayer`].
860
+
861
+ Args:
862
+ config: SiglipConfig
863
+ """
864
+
865
+ def __init__(self, config: SiglipConfig):
866
+ super().__init__()
867
+ self.config = config
868
+ self.layers = nn.ModuleList([SiglipEncoderLayer(config) for _ in range(config.num_hidden_layers)])
869
+ self.gradient_checkpointing = False
870
+
871
+ # Ignore copy
872
+ def forward(
873
+ self,
874
+ inputs_embeds,
875
+ attention_mask: Optional[torch.Tensor] = None,
876
+ output_attentions: Optional[bool] = None,
877
+ output_hidden_states: Optional[bool] = None,
878
+ return_dict: Optional[bool] = None,
879
+ ) -> Union[Tuple, BaseModelOutput]:
880
+ r"""
881
+ Args:
882
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`):
883
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation.
884
+ This is useful if you want more control over how to convert `input_ids` indices into associated vectors
885
+ than the model's internal embedding lookup matrix.
886
+ attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
887
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
888
+
889
+ - 1 for tokens that are **not masked**,
890
+ - 0 for tokens that are **masked**.
891
+
892
+ [What are attention masks?](../glossary#attention-mask)
893
+ output_attentions (`bool`, *optional*):
894
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
895
+ returned tensors for more detail.
896
+ output_hidden_states (`bool`, *optional*):
897
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors
898
+ for more detail.
899
+ return_dict (`bool`, *optional*):
900
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
901
+ """
902
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
903
+ output_hidden_states = (
904
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
905
+ )
906
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
907
+
908
+ encoder_states = () if output_hidden_states else None
909
+ all_attentions = () if output_attentions else None
910
+
911
+ hidden_states = inputs_embeds
912
+ for encoder_layer in self.layers:
913
+ if output_hidden_states:
914
+ encoder_states = encoder_states + (hidden_states,)
915
+ if self.gradient_checkpointing and self.training:
916
+ layer_outputs = self._gradient_checkpointing_func(
917
+ encoder_layer.__call__,
918
+ hidden_states,
919
+ attention_mask,
920
+ output_attentions,
921
+ )
922
+ else:
923
+ layer_outputs = encoder_layer(
924
+ hidden_states,
925
+ attention_mask,
926
+ output_attentions=output_attentions,
927
+ )
928
+
929
+ hidden_states = layer_outputs[0]
930
+
931
+ if output_attentions:
932
+ all_attentions = all_attentions + (layer_outputs[1],)
933
+
934
+ if output_hidden_states:
935
+ encoder_states = encoder_states + (hidden_states,)
936
+
937
+ if not return_dict:
938
+ return tuple(v for v in [hidden_states, encoder_states, all_attentions] if v is not None)
939
+ return BaseModelOutput(
940
+ last_hidden_state=hidden_states, hidden_states=encoder_states, attentions=all_attentions
941
+ )
942
+
943
+
944
+ class SiglipTextTransformer(nn.Module):
945
+ def __init__(self, config: SiglipTextConfig):
946
+ super().__init__()
947
+ self.config = config
948
+ embed_dim = config.hidden_size
949
+ self.embeddings = SiglipTextEmbeddings(config)
950
+ self.encoder = SiglipEncoder(config)
951
+ self.final_layer_norm = nn.LayerNorm(embed_dim, eps=config.layer_norm_eps)
952
+
953
+ self.head = nn.Linear(embed_dim, embed_dim)
954
+
955
+ @add_start_docstrings_to_model_forward(SIGLIP_TEXT_INPUTS_DOCSTRING)
956
+ @replace_return_docstrings(output_type=BaseModelOutputWithPooling, config_class=SiglipTextConfig)
957
+ def forward(
958
+ self,
959
+ input_ids: Optional[torch.Tensor] = None,
960
+ attention_mask: Optional[torch.Tensor] = None,
961
+ position_ids: Optional[torch.Tensor] = None,
962
+ output_attentions: Optional[bool] = None,
963
+ output_hidden_states: Optional[bool] = None,
964
+ return_dict: Optional[bool] = None,
965
+ ) -> Union[Tuple, BaseModelOutputWithPooling]:
966
+ r"""
967
+ Returns:
968
+
969
+ """
970
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
971
+ output_hidden_states = (
972
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
973
+ )
974
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
975
+
976
+ if input_ids is None:
977
+ raise ValueError("You have to specify input_ids")
978
+
979
+ input_shape = input_ids.size()
980
+ input_ids = input_ids.view(-1, input_shape[-1])
981
+
982
+ hidden_states = self.embeddings(input_ids=input_ids, position_ids=position_ids)
983
+
984
+ # note: SigLIP's text model does not use a causal mask, unlike the original CLIP model.
985
+ # expand attention_mask
986
+ if attention_mask is not None:
987
+ # [batch_size, seq_len] -> [batch_size, 1, tgt_seq_len, src_seq_len]
988
+ attention_mask = _prepare_4d_attention_mask(attention_mask, hidden_states.dtype)
989
+
990
+ encoder_outputs = self.encoder(
991
+ inputs_embeds=hidden_states,
992
+ attention_mask=attention_mask,
993
+ output_attentions=output_attentions,
994
+ output_hidden_states=output_hidden_states,
995
+ return_dict=return_dict,
996
+ )
997
+
998
+ last_hidden_state = encoder_outputs[0]
999
+ last_hidden_state = self.final_layer_norm(last_hidden_state)
1000
+
1001
+ # Assuming "sticky" EOS tokenization, last token is always EOS.
1002
+ pooled_output = last_hidden_state[:, -1, :]
1003
+ pooled_output = self.head(pooled_output)
1004
+
1005
+ if not return_dict:
1006
+ return (last_hidden_state, pooled_output) + encoder_outputs[1:]
1007
+
1008
+ return BaseModelOutputWithPooling(
1009
+ last_hidden_state=last_hidden_state,
1010
+ pooler_output=pooled_output,
1011
+ hidden_states=encoder_outputs.hidden_states,
1012
+ attentions=encoder_outputs.attentions,
1013
+ )
1014
+
1015
+
1016
+ @add_start_docstrings(
1017
+ """The text model from SigLIP without any head or projection on top.""",
1018
+ SIGLIP_START_DOCSTRING,
1019
+ )
1020
+ class SiglipTextModel(SiglipPreTrainedModel):
1021
+ config_class = SiglipTextConfig
1022
+
1023
+ _no_split_modules = ["SiglipTextEmbeddings", "SiglipEncoderLayer"]
1024
+
1025
+ def __init__(self, config: SiglipTextConfig):
1026
+ super().__init__(config)
1027
+ self.text_model = SiglipTextTransformer(config)
1028
+ # Initialize weights and apply final processing
1029
+ self.post_init()
1030
+
1031
+ def get_input_embeddings(self) -> nn.Module:
1032
+ return self.text_model.embeddings.token_embedding
1033
+
1034
+ def set_input_embeddings(self, value):
1035
+ self.text_model.embeddings.token_embedding = value
1036
+
1037
+ @add_start_docstrings_to_model_forward(SIGLIP_TEXT_INPUTS_DOCSTRING)
1038
+ @replace_return_docstrings(output_type=BaseModelOutputWithPooling, config_class=SiglipTextConfig)
1039
+ def forward(
1040
+ self,
1041
+ input_ids: Optional[torch.Tensor] = None,
1042
+ attention_mask: Optional[torch.Tensor] = None,
1043
+ position_ids: Optional[torch.Tensor] = None,
1044
+ output_attentions: Optional[bool] = None,
1045
+ output_hidden_states: Optional[bool] = None,
1046
+ return_dict: Optional[bool] = None,
1047
+ ) -> Union[Tuple, BaseModelOutputWithPooling]:
1048
+ r"""
1049
+ Returns:
1050
+
1051
+ Examples:
1052
+
1053
+ ```python
1054
+ >>> from transformers import AutoTokenizer, SiglipTextModel
1055
+
1056
+ >>> model = SiglipTextModel.from_pretrained("google/siglip-base-patch16-224")
1057
+ >>> tokenizer = AutoTokenizer.from_pretrained("google/siglip-base-patch16-224")
1058
+
1059
+ >>> # important: make sure to set padding="max_length" as that's how the model was trained
1060
+ >>> inputs = tokenizer(["a photo of a cat", "a photo of a dog"], padding="max_length", return_tensors="pt")
1061
+
1062
+ >>> outputs = model(**inputs)
1063
+ >>> last_hidden_state = outputs.last_hidden_state
1064
+ >>> pooled_output = outputs.pooler_output # pooled (EOS token) states
1065
+ ```"""
1066
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1067
+
1068
+ return self.text_model(
1069
+ input_ids=input_ids,
1070
+ attention_mask=attention_mask,
1071
+ position_ids=position_ids,
1072
+ output_attentions=output_attentions,
1073
+ output_hidden_states=output_hidden_states,
1074
+ return_dict=return_dict,
1075
+ )
1076
+
1077
+
1078
+ class SiglipVisionTransformer(nn.Module):
1079
+ def __init__(self, config: SiglipVisionConfig):
1080
+ super().__init__()
1081
+ self.config = config
1082
+ embed_dim = config.hidden_size
1083
+
1084
+ self.embeddings = SiglipVisionEmbeddings(config)
1085
+ self.encoder = SiglipEncoder(config)
1086
+ self.post_layernorm = nn.LayerNorm(embed_dim, eps=config.layer_norm_eps)
1087
+ self.head = SiglipMultiheadAttentionPoolingHead(config)
1088
+
1089
+ @add_start_docstrings_to_model_forward(SIGLIP_VISION_INPUTS_DOCSTRING)
1090
+ @replace_return_docstrings(output_type=BaseModelOutputWithPooling, config_class=SiglipVisionConfig)
1091
+ def forward(
1092
+ self,
1093
+ pixel_values,
1094
+ patch_attention_mask: Optional[torch.BoolTensor] = None,
1095
+ output_attentions: Optional[bool] = None,
1096
+ output_hidden_states: Optional[bool] = None,
1097
+ return_dict: Optional[bool] = None,
1098
+ ) -> Union[Tuple, BaseModelOutputWithPooling]:
1099
+ r"""
1100
+ Returns:
1101
+
1102
+ """
1103
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
1104
+ output_hidden_states = (
1105
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1106
+ )
1107
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1108
+
1109
+ batch_size = pixel_values.size(0)
1110
+ if patch_attention_mask is None:
1111
+ patch_attention_mask = torch.ones(
1112
+ size=(
1113
+ batch_size,
1114
+ pixel_values.size(2) // self.config.patch_size,
1115
+ pixel_values.size(3) // self.config.patch_size,
1116
+ ),
1117
+ dtype=torch.bool,
1118
+ device=pixel_values.device,
1119
+ )
1120
+
1121
+ hidden_states = self.embeddings(pixel_values=pixel_values, patch_attention_mask=patch_attention_mask)
1122
+
1123
+ patch_attention_mask = patch_attention_mask.view(batch_size, -1)
1124
+ # The call to `_upad_input` in `_flash_attention_forward` is expensive
1125
+ # So when the `patch_attention_mask` is full of 1s (i.e. attending to the whole sequence),
1126
+ # avoiding passing the attention_mask, which is equivalent to attending to the full sequence
1127
+ if not torch.any(~patch_attention_mask):
1128
+ attention_mask=None
1129
+ else:
1130
+ attention_mask = (
1131
+ _prepare_4d_attention_mask(patch_attention_mask, hidden_states.dtype)
1132
+ if not self.config._flash_attn_2_enabled
1133
+ else patch_attention_mask
1134
+ )
1135
+
1136
+ encoder_outputs = self.encoder(
1137
+ inputs_embeds=hidden_states,
1138
+ attention_mask=attention_mask,
1139
+ output_attentions=output_attentions,
1140
+ output_hidden_states=output_hidden_states,
1141
+ return_dict=return_dict,
1142
+ )
1143
+
1144
+ last_hidden_state = encoder_outputs[0]
1145
+ last_hidden_state = self.post_layernorm(last_hidden_state)
1146
+
1147
+ pooled_output = self.head(
1148
+ hidden_state=last_hidden_state,
1149
+ attention_mask=patch_attention_mask,
1150
+ )
1151
+
1152
+ if not return_dict:
1153
+ return (last_hidden_state, pooled_output) + encoder_outputs[1:]
1154
+
1155
+ return BaseModelOutputWithPooling(
1156
+ last_hidden_state=last_hidden_state,
1157
+ pooler_output=pooled_output,
1158
+ hidden_states=encoder_outputs.hidden_states,
1159
+ attentions=encoder_outputs.attentions,
1160
+ )
1161
+
1162
+
1163
+ class SiglipMultiheadAttentionPoolingHead(nn.Module):
1164
+ """Multihead Attention Pooling."""
1165
+
1166
+ def __init__(self, config: SiglipVisionConfig):
1167
+ super().__init__()
1168
+
1169
+ self.probe = nn.Parameter(torch.randn(1, 1, config.hidden_size))
1170
+ self.attention = torch.nn.MultiheadAttention(config.hidden_size, config.num_attention_heads, batch_first=True)
1171
+ self.layernorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
1172
+ self.mlp = SiglipMLP(config)
1173
+
1174
+ def forward(self, hidden_state, attention_mask):
1175
+ batch_size = hidden_state.shape[0]
1176
+ probe = self.probe.repeat(batch_size, 1, 1)
1177
+
1178
+ hidden_state = self.attention(
1179
+ query=probe, key=hidden_state, value=hidden_state, key_padding_mask=~attention_mask
1180
+ )[0]
1181
+
1182
+ residual = hidden_state
1183
+ hidden_state = self.layernorm(hidden_state)
1184
+ hidden_state = residual + self.mlp(hidden_state)
1185
+
1186
+ return hidden_state[:, 0]
1187
+
1188
+
1189
+ @add_start_docstrings(
1190
+ """The vision model from SigLIP without any head or projection on top.""",
1191
+ SIGLIP_START_DOCSTRING,
1192
+ )
1193
+ class SiglipVisionModel(SiglipPreTrainedModel):
1194
+ config_class = SiglipVisionConfig
1195
+ main_input_name = "pixel_values"
1196
+
1197
+ def __init__(self, config: SiglipVisionConfig):
1198
+ super().__init__(config)
1199
+
1200
+ self.vision_model = SiglipVisionTransformer(config)
1201
+
1202
+ # Initialize weights and apply final processing
1203
+ self.post_init()
1204
+
1205
+ def get_input_embeddings(self) -> nn.Module:
1206
+ return self.vision_model.embeddings.patch_embedding
1207
+
1208
+ @add_start_docstrings_to_model_forward(SIGLIP_VISION_INPUTS_DOCSTRING)
1209
+ @replace_return_docstrings(output_type=BaseModelOutputWithPooling, config_class=SiglipVisionConfig)
1210
+ def forward(
1211
+ self,
1212
+ pixel_values,
1213
+ patch_attention_mask: Optional[torch.BoolTensor] = None,
1214
+ output_attentions: Optional[bool] = None,
1215
+ output_hidden_states: Optional[bool] = None,
1216
+ return_dict: Optional[bool] = None,
1217
+ ) -> Union[Tuple, BaseModelOutputWithPooling]:
1218
+ r"""
1219
+ Returns:
1220
+
1221
+ Examples:
1222
+
1223
+ ```python
1224
+ >>> from PIL import Image
1225
+ >>> import requests
1226
+ >>> from transformers import AutoProcessor, SiglipVisionModel
1227
+
1228
+ >>> model = SiglipVisionModel.from_pretrained("google/siglip-base-patch16-224")
1229
+ >>> processor = AutoProcessor.from_pretrained("google/siglip-base-patch16-224")
1230
+
1231
+ >>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
1232
+ >>> image = Image.open(requests.get(url, stream=True).raw)
1233
+
1234
+ >>> inputs = processor(images=image, return_tensors="pt")
1235
+
1236
+ >>> outputs = model(**inputs)
1237
+ >>> last_hidden_state = outputs.last_hidden_state
1238
+ >>> pooled_output = outputs.pooler_output # pooled features
1239
+ ```"""
1240
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1241
+
1242
+ return self.vision_model(
1243
+ pixel_values=pixel_values,
1244
+ patch_attention_mask=patch_attention_mask,
1245
+ output_attentions=output_attentions,
1246
+ output_hidden_states=output_hidden_states,
1247
+ return_dict=return_dict,
1248
+ )
1249
+
1250
+
1251
+ @add_start_docstrings(SIGLIP_START_DOCSTRING)
1252
+ class SiglipModel(SiglipPreTrainedModel):
1253
+ config_class = SiglipConfig
1254
+
1255
+ def __init__(self, config: SiglipConfig):
1256
+ super().__init__(config)
1257
+
1258
+ if not isinstance(config.text_config, SiglipTextConfig):
1259
+ raise ValueError(
1260
+ "config.text_config is expected to be of type SiglipTextConfig but is of type"
1261
+ f" {type(config.text_config)}."
1262
+ )
1263
+
1264
+ if not isinstance(config.vision_config, SiglipVisionConfig):
1265
+ raise ValueError(
1266
+ "config.vision_config is expected to be of type SiglipVisionConfig but is of type"
1267
+ f" {type(config.vision_config)}."
1268
+ )
1269
+
1270
+ text_config = config.text_config
1271
+ vision_config = config.vision_config
1272
+
1273
+ self.text_model = SiglipTextTransformer(text_config)
1274
+ self.vision_model = SiglipVisionTransformer(vision_config)
1275
+
1276
+ self.logit_scale = nn.Parameter(torch.randn(1))
1277
+ self.logit_bias = nn.Parameter(torch.randn(1))
1278
+
1279
+ # Initialize weights and apply final processing
1280
+ self.post_init()
1281
+
1282
+ @add_start_docstrings_to_model_forward(SIGLIP_TEXT_INPUTS_DOCSTRING)
1283
+ def get_text_features(
1284
+ self,
1285
+ input_ids: Optional[torch.Tensor] = None,
1286
+ attention_mask: Optional[torch.Tensor] = None,
1287
+ position_ids: Optional[torch.Tensor] = None,
1288
+ output_attentions: Optional[bool] = None,
1289
+ output_hidden_states: Optional[bool] = None,
1290
+ return_dict: Optional[bool] = None,
1291
+ ) -> torch.FloatTensor:
1292
+ r"""
1293
+ Returns:
1294
+ text_features (`torch.FloatTensor` of shape `(batch_size, output_dim`): The text embeddings obtained by
1295
+ applying the projection layer to the pooled output of [`SiglipTextModel`].
1296
+
1297
+ Examples:
1298
+
1299
+ ```python
1300
+ >>> from transformers import AutoTokenizer, AutoModel
1301
+ >>> import torch
1302
+
1303
+ >>> model = AutoModel.from_pretrained("google/siglip-base-patch16-224")
1304
+ >>> tokenizer = AutoTokenizer.from_pretrained("google/siglip-base-patch16-224")
1305
+
1306
+ >>> # important: make sure to set padding="max_length" as that's how the model was trained
1307
+ >>> inputs = tokenizer(["a photo of a cat", "a photo of a dog"], padding="max_length", return_tensors="pt")
1308
+ >>> with torch.no_grad():
1309
+ ... text_features = model.get_text_features(**inputs)
1310
+ ```"""
1311
+ # Use SigLIP model's config for some fields (if specified) instead of those of vision & text components.
1312
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
1313
+ output_hidden_states = (
1314
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1315
+ )
1316
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1317
+
1318
+ text_outputs = self.text_model(
1319
+ input_ids=input_ids,
1320
+ attention_mask=attention_mask,
1321
+ position_ids=position_ids,
1322
+ output_attentions=output_attentions,
1323
+ output_hidden_states=output_hidden_states,
1324
+ return_dict=return_dict,
1325
+ )
1326
+
1327
+ pooled_output = text_outputs[1]
1328
+
1329
+ return pooled_output
1330
+
1331
+ @add_start_docstrings_to_model_forward(SIGLIP_VISION_INPUTS_DOCSTRING)
1332
+ def get_image_features(
1333
+ self,
1334
+ pixel_values: Optional[torch.FloatTensor] = None,
1335
+ output_attentions: Optional[bool] = None,
1336
+ output_hidden_states: Optional[bool] = None,
1337
+ return_dict: Optional[bool] = None,
1338
+ ) -> torch.FloatTensor:
1339
+ r"""
1340
+ Returns:
1341
+ image_features (`torch.FloatTensor` of shape `(batch_size, output_dim`): The image embeddings obtained by
1342
+ applying the projection layer to the pooled output of [`SiglipVisionModel`].
1343
+
1344
+ Examples:
1345
+
1346
+ ```python
1347
+ >>> from PIL import Image
1348
+ >>> import requests
1349
+ >>> from transformers import AutoProcessor, AutoModel
1350
+ >>> import torch
1351
+
1352
+ >>> model = AutoModel.from_pretrained("google/siglip-base-patch16-224")
1353
+ >>> processor = AutoProcessor.from_pretrained("google/siglip-base-patch16-224")
1354
+
1355
+ >>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
1356
+ >>> image = Image.open(requests.get(url, stream=True).raw)
1357
+
1358
+ >>> inputs = processor(images=image, return_tensors="pt")
1359
+
1360
+ >>> with torch.no_grad():
1361
+ ... image_features = model.get_image_features(**inputs)
1362
+ ```"""
1363
+ # Use SiglipModel's config for some fields (if specified) instead of those of vision & text components.
1364
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
1365
+ output_hidden_states = (
1366
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1367
+ )
1368
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1369
+
1370
+ vision_outputs = self.vision_model(
1371
+ pixel_values=pixel_values,
1372
+ output_attentions=output_attentions,
1373
+ output_hidden_states=output_hidden_states,
1374
+ return_dict=return_dict,
1375
+ )
1376
+
1377
+ pooled_output = vision_outputs[1]
1378
+
1379
+ return pooled_output
1380
+
1381
+ @add_start_docstrings_to_model_forward(SIGLIP_INPUTS_DOCSTRING)
1382
+ @replace_return_docstrings(output_type=SiglipOutput, config_class=SiglipConfig)
1383
+ def forward(
1384
+ self,
1385
+ input_ids: Optional[torch.LongTensor] = None,
1386
+ pixel_values: Optional[torch.FloatTensor] = None,
1387
+ attention_mask: Optional[torch.Tensor] = None,
1388
+ position_ids: Optional[torch.LongTensor] = None,
1389
+ return_loss: Optional[bool] = None,
1390
+ output_attentions: Optional[bool] = None,
1391
+ output_hidden_states: Optional[bool] = None,
1392
+ return_dict: Optional[bool] = None,
1393
+ ) -> Union[Tuple, SiglipOutput]:
1394
+ r"""
1395
+ Returns:
1396
+
1397
+ Examples:
1398
+
1399
+ ```python
1400
+ >>> from PIL import Image
1401
+ >>> import requests
1402
+ >>> from transformers import AutoProcessor, AutoModel
1403
+ >>> import torch
1404
+
1405
+ >>> model = AutoModel.from_pretrained("google/siglip-base-patch16-224")
1406
+ >>> processor = AutoProcessor.from_pretrained("google/siglip-base-patch16-224")
1407
+
1408
+ >>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
1409
+ >>> image = Image.open(requests.get(url, stream=True).raw)
1410
+
1411
+ >>> texts = ["a photo of 2 cats", "a photo of 2 dogs"]
1412
+ >>> # important: we pass `padding=max_length` since the model was trained with this
1413
+ >>> inputs = processor(text=texts, images=image, padding="max_length", return_tensors="pt")
1414
+
1415
+ >>> with torch.no_grad():
1416
+ ... outputs = model(**inputs)
1417
+
1418
+ >>> logits_per_image = outputs.logits_per_image
1419
+ >>> probs = torch.sigmoid(logits_per_image) # these are the probabilities
1420
+ >>> print(f"{probs[0][0]:.1%} that image 0 is '{texts[0]}'")
1421
+ 31.9% that image 0 is 'a photo of 2 cats'
1422
+ ```"""
1423
+ # Use SigLIP model's config for some fields (if specified) instead of those of vision & text components.
1424
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
1425
+ output_hidden_states = (
1426
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1427
+ )
1428
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1429
+
1430
+ vision_outputs = self.vision_model(
1431
+ pixel_values=pixel_values,
1432
+ output_attentions=output_attentions,
1433
+ output_hidden_states=output_hidden_states,
1434
+ return_dict=return_dict,
1435
+ )
1436
+
1437
+ text_outputs = self.text_model(
1438
+ input_ids=input_ids,
1439
+ attention_mask=attention_mask,
1440
+ position_ids=position_ids,
1441
+ output_attentions=output_attentions,
1442
+ output_hidden_states=output_hidden_states,
1443
+ return_dict=return_dict,
1444
+ )
1445
+
1446
+ image_embeds = vision_outputs[1]
1447
+ text_embeds = text_outputs[1]
1448
+
1449
+ # normalized features
1450
+ image_embeds = image_embeds / image_embeds.norm(p=2, dim=-1, keepdim=True)
1451
+ text_embeds = text_embeds / text_embeds.norm(p=2, dim=-1, keepdim=True)
1452
+
1453
+ # cosine similarity as logits
1454
+ logits_per_text = torch.matmul(text_embeds, image_embeds.t()) * self.logit_scale.exp() + self.logit_bias
1455
+ logits_per_image = logits_per_text.t()
1456
+
1457
+ loss = None
1458
+ if return_loss:
1459
+ raise NotImplementedError("SigLIP loss to be implemented")
1460
+
1461
+ if not return_dict:
1462
+ output = (logits_per_image, logits_per_text, text_embeds, image_embeds, text_outputs, vision_outputs)
1463
+ return ((loss,) + output) if loss is not None else output
1464
+
1465
+ return SiglipOutput(
1466
+ loss=loss,
1467
+ logits_per_image=logits_per_image,
1468
+ logits_per_text=logits_per_text,
1469
+ text_embeds=text_embeds,
1470
+ image_embeds=image_embeds,
1471
+ text_model_output=text_outputs,
1472
+ vision_model_output=vision_outputs,
1473
+ )