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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
# Copied from HuggingFaceM4/siglip-so400m-14-980-flash-attn2-navit and add tgt_sizes
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
import math
|
| 20 |
+
import os
|
| 21 |
+
import warnings
|
| 22 |
+
from dataclasses import dataclass
|
| 23 |
+
from typing import Optional
|
| 24 |
+
from typing import Tuple
|
| 25 |
+
from typing import Union
|
| 26 |
+
|
| 27 |
+
import numpy as np
|
| 28 |
+
import torch
|
| 29 |
+
import torch.nn.functional as F
|
| 30 |
+
import torch.utils.checkpoint
|
| 31 |
+
from torch import nn
|
| 32 |
+
from torch.nn.init import _calculate_fan_in_and_fan_out
|
| 33 |
+
from transformers.activations import ACT2FN
|
| 34 |
+
from transformers.configuration_utils import PretrainedConfig
|
| 35 |
+
from transformers.modeling_attn_mask_utils import _prepare_4d_attention_mask
|
| 36 |
+
from transformers.modeling_outputs import BaseModelOutput
|
| 37 |
+
from transformers.modeling_outputs import BaseModelOutputWithPooling
|
| 38 |
+
from transformers.modeling_utils import PreTrainedModel
|
| 39 |
+
from transformers.utils import add_start_docstrings
|
| 40 |
+
from transformers.utils import add_start_docstrings_to_model_forward
|
| 41 |
+
from transformers.utils import is_flash_attn_2_available
|
| 42 |
+
from transformers.utils import logging
|
| 43 |
+
from transformers.utils import ModelOutput
|
| 44 |
+
from transformers.utils import replace_return_docstrings
|
| 45 |
+
|
| 46 |
+
logger = logging.get_logger(__name__)
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
class SiglipVisionConfig(PretrainedConfig):
|
| 50 |
+
r"""
|
| 51 |
+
This is the configuration class to store the configuration of a [`SiglipVisionModel`]. It is used to instantiate a
|
| 52 |
+
Siglip vision encoder according to the specified arguments, defining the model architecture. Instantiating a
|
| 53 |
+
configuration with the defaults will yield a similar configuration to that of the vision encoder of the Siglip
|
| 54 |
+
[google/siglip-base-patch16-224](https://huggingface.co/google/siglip-base-patch16-224) architecture.
|
| 55 |
+
Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
|
| 56 |
+
documentation from [`PretrainedConfig`] for more information.
|
| 57 |
+
Args:
|
| 58 |
+
hidden_size (`int`, *optional*, defaults to 768):
|
| 59 |
+
Dimensionality of the encoder layers and the pooler layer.
|
| 60 |
+
intermediate_size (`int`, *optional*, defaults to 3072):
|
| 61 |
+
Dimensionality of the "intermediate" (i.e., feed-forward) layer in the Transformer encoder.
|
| 62 |
+
num_hidden_layers (`int`, *optional*, defaults to 12):
|
| 63 |
+
Number of hidden layers in the Transformer encoder.
|
| 64 |
+
num_attention_heads (`int`, *optional*, defaults to 12):
|
| 65 |
+
Number of attention heads for each attention layer in the Transformer encoder.
|
| 66 |
+
num_channels (`int`, *optional*, defaults to 3):
|
| 67 |
+
Number of channels in the input images.
|
| 68 |
+
image_size (`int`, *optional*, defaults to 224):
|
| 69 |
+
The size (resolution) of each image.
|
| 70 |
+
patch_size (`int`, *optional*, defaults to 16):
|
| 71 |
+
The size (resolution) of each patch.
|
| 72 |
+
hidden_act (`str` or `function`, *optional*, defaults to `"gelu_pytorch_tanh"`):
|
| 73 |
+
The non-linear activation function (function or string) in the encoder and pooler. If string, `"gelu"`,
|
| 74 |
+
`"relu"`, `"selu"` and `"gelu_new"` ``"quick_gelu"` are supported.
|
| 75 |
+
layer_norm_eps (`float`, *optional*, defaults to 1e-06):
|
| 76 |
+
The epsilon used by the layer normalization layers.
|
| 77 |
+
attention_dropout (`float`, *optional*, defaults to 0.0):
|
| 78 |
+
The dropout ratio for the attention probabilities.
|
| 79 |
+
Example:
|
| 80 |
+
```python
|
| 81 |
+
>>> from transformers import SiglipVisionConfig, SiglipVisionModel
|
| 82 |
+
>>> # Initializing a SiglipVisionConfig with google/siglip-base-patch16-224 style configuration
|
| 83 |
+
>>> configuration = SiglipVisionConfig()
|
| 84 |
+
>>> # Initializing a SiglipVisionModel (with random weights) from the google/siglip-base-patch16-224 style configuration
|
| 85 |
+
>>> model = SiglipVisionModel(configuration)
|
| 86 |
+
>>> # Accessing the model configuration
|
| 87 |
+
>>> configuration = model.config
|
| 88 |
+
```"""
|
| 89 |
+
|
| 90 |
+
model_type = "siglip_vision_model"
|
| 91 |
+
|
| 92 |
+
def __init__(
|
| 93 |
+
self,
|
| 94 |
+
hidden_size=768,
|
| 95 |
+
intermediate_size=3072,
|
| 96 |
+
num_hidden_layers=12,
|
| 97 |
+
num_attention_heads=12,
|
| 98 |
+
num_channels=3,
|
| 99 |
+
image_size=224,
|
| 100 |
+
patch_size=16,
|
| 101 |
+
hidden_act="gelu_pytorch_tanh",
|
| 102 |
+
layer_norm_eps=1e-6,
|
| 103 |
+
attention_dropout=0.0,
|
| 104 |
+
**kwargs,
|
| 105 |
+
):
|
| 106 |
+
super().__init__(**kwargs)
|
| 107 |
+
|
| 108 |
+
self.hidden_size = hidden_size
|
| 109 |
+
self.intermediate_size = intermediate_size
|
| 110 |
+
self.num_hidden_layers = num_hidden_layers
|
| 111 |
+
self.num_attention_heads = num_attention_heads
|
| 112 |
+
self.num_channels = num_channels
|
| 113 |
+
self.patch_size = patch_size
|
| 114 |
+
self.image_size = image_size
|
| 115 |
+
self.attention_dropout = attention_dropout
|
| 116 |
+
self.layer_norm_eps = layer_norm_eps
|
| 117 |
+
self.hidden_act = hidden_act
|
| 118 |
+
|
| 119 |
+
@classmethod
|
| 120 |
+
def from_pretrained(cls, pretrained_model_name_or_path: Union[str, os.PathLike], **kwargs) -> "PretrainedConfig":
|
| 121 |
+
cls._set_token_in_kwargs(kwargs)
|
| 122 |
+
|
| 123 |
+
config_dict, kwargs = cls.get_config_dict(pretrained_model_name_or_path, **kwargs)
|
| 124 |
+
|
| 125 |
+
# get the vision config dict if we are loading from SiglipConfig
|
| 126 |
+
if config_dict.get("model_type") == "siglip":
|
| 127 |
+
config_dict = config_dict["vision_config"]
|
| 128 |
+
|
| 129 |
+
if "model_type" in config_dict and hasattr(cls, "model_type") and config_dict["model_type"] != cls.model_type:
|
| 130 |
+
logger.warning(
|
| 131 |
+
f"You are using a model of type {config_dict['model_type']} to instantiate a model of type "
|
| 132 |
+
f"{cls.model_type}. This is not supported for all configurations of models and can yield errors."
|
| 133 |
+
)
|
| 134 |
+
|
| 135 |
+
return cls.from_dict(config_dict, **kwargs)
|
| 136 |
+
|
| 137 |
+
|
| 138 |
+
_CHECKPOINT_FOR_DOC = "google/siglip-base-patch16-224"
|
| 139 |
+
|
| 140 |
+
SIGLIP_PRETRAINED_MODEL_ARCHIVE_LIST = [
|
| 141 |
+
"google/siglip-base-patch16-224",
|
| 142 |
+
# See all SigLIP models at https://huggingface.co/models?filter=siglip
|
| 143 |
+
]
|
| 144 |
+
|
| 145 |
+
if is_flash_attn_2_available():
|
| 146 |
+
from flash_attn import flash_attn_func
|
| 147 |
+
from flash_attn import flash_attn_varlen_func
|
| 148 |
+
from flash_attn.bert_padding import index_first_axis # noqa
|
| 149 |
+
from flash_attn.bert_padding import pad_input
|
| 150 |
+
from flash_attn.bert_padding import unpad_input
|
| 151 |
+
|
| 152 |
+
|
| 153 |
+
# Copied from transformers.models.llama.modeling_llama._get_unpad_data
|
| 154 |
+
def _get_unpad_data(attention_mask):
|
| 155 |
+
seqlens_in_batch = attention_mask.sum(dim=-1, dtype=torch.int32)
|
| 156 |
+
indices = torch.nonzero(attention_mask.flatten(), as_tuple=False).flatten()
|
| 157 |
+
max_seqlen_in_batch = seqlens_in_batch.max().item()
|
| 158 |
+
cu_seqlens = F.pad(torch.cumsum(seqlens_in_batch, dim=0, dtype=torch.torch.int32), (1, 0))
|
| 159 |
+
return (
|
| 160 |
+
indices,
|
| 161 |
+
cu_seqlens,
|
| 162 |
+
max_seqlen_in_batch,
|
| 163 |
+
)
|
| 164 |
+
|
| 165 |
+
|
| 166 |
+
def _trunc_normal_(tensor, mean, std, a, b):
|
| 167 |
+
# Cut & paste from PyTorch official master until it's in a few official releases - RW
|
| 168 |
+
# Method based on https://people.sc.fsu.edu/~jburkardt/presentations/truncated_normal.pdf
|
| 169 |
+
def norm_cdf(x):
|
| 170 |
+
# Computes standard normal cumulative distribution function
|
| 171 |
+
return (1.0 + math.erf(x / math.sqrt(2.0))) / 2.0
|
| 172 |
+
|
| 173 |
+
if (mean < a - 2 * std) or (mean > b + 2 * std):
|
| 174 |
+
warnings.warn(
|
| 175 |
+
"mean is more than 2 std from [a, b] in nn.init.trunc_normal_. "
|
| 176 |
+
"The distribution of values may be incorrect.",
|
| 177 |
+
stacklevel=2,
|
| 178 |
+
)
|
| 179 |
+
|
| 180 |
+
# Values are generated by using a truncated uniform distribution and
|
| 181 |
+
# then using the inverse CDF for the normal distribution.
|
| 182 |
+
# Get upper and lower cdf values
|
| 183 |
+
l = norm_cdf((a - mean) / std)
|
| 184 |
+
u = norm_cdf((b - mean) / std)
|
| 185 |
+
|
| 186 |
+
# Uniformly fill tensor with values from [l, u], then translate to
|
| 187 |
+
# [2l-1, 2u-1].
|
| 188 |
+
tensor.uniform_(2 * l - 1, 2 * u - 1)
|
| 189 |
+
|
| 190 |
+
# Use inverse cdf transform for normal distribution to get truncated
|
| 191 |
+
# standard normal
|
| 192 |
+
if tensor.dtype in [torch.float16, torch.bfloat16]:
|
| 193 |
+
# The `erfinv_` op is not (yet?) defined in float16+cpu, bfloat16+gpu
|
| 194 |
+
og_dtype = tensor.dtype
|
| 195 |
+
tensor = tensor.to(torch.float32)
|
| 196 |
+
tensor.erfinv_()
|
| 197 |
+
tensor = tensor.to(og_dtype)
|
| 198 |
+
else:
|
| 199 |
+
tensor.erfinv_()
|
| 200 |
+
|
| 201 |
+
# Transform to proper mean, std
|
| 202 |
+
tensor.mul_(std * math.sqrt(2.0))
|
| 203 |
+
tensor.add_(mean)
|
| 204 |
+
|
| 205 |
+
# Clamp to ensure it's in the proper range
|
| 206 |
+
if tensor.dtype == torch.float16:
|
| 207 |
+
# The `clamp_` op is not (yet?) defined in float16+cpu
|
| 208 |
+
tensor = tensor.to(torch.float32)
|
| 209 |
+
tensor.clamp_(min=a, max=b)
|
| 210 |
+
tensor = tensor.to(torch.float16)
|
| 211 |
+
else:
|
| 212 |
+
tensor.clamp_(min=a, max=b)
|
| 213 |
+
|
| 214 |
+
|
| 215 |
+
def trunc_normal_tf_(
|
| 216 |
+
tensor: torch.Tensor, mean: float = 0.0, std: float = 1.0, a: float = -2.0, b: float = 2.0
|
| 217 |
+
) -> torch.Tensor:
|
| 218 |
+
"""Fills the input Tensor with values drawn from a truncated
|
| 219 |
+
normal distribution. The values are effectively drawn from the
|
| 220 |
+
normal distribution :math:`\\mathcal{N}(\text{mean}, \text{std}^2)`
|
| 221 |
+
with values outside :math:`[a, b]` redrawn until they are within
|
| 222 |
+
the bounds. The method used for generating the random values works
|
| 223 |
+
best when :math:`a \\leq \text{mean} \\leq b`.
|
| 224 |
+
NOTE: this 'tf' variant behaves closer to Tensorflow / JAX impl where the
|
| 225 |
+
bounds [a, b] are applied when sampling the normal distribution with mean=0, std=1.0
|
| 226 |
+
and the result is subsquently scaled and shifted by the mean and std args.
|
| 227 |
+
Args:
|
| 228 |
+
tensor: an n-dimensional `torch.Tensor`
|
| 229 |
+
mean: the mean of the normal distribution
|
| 230 |
+
std: the standard deviation of the normal distribution
|
| 231 |
+
a: the minimum cutoff value
|
| 232 |
+
b: the maximum cutoff value
|
| 233 |
+
"""
|
| 234 |
+
with torch.no_grad():
|
| 235 |
+
_trunc_normal_(tensor, 0, 1.0, a, b)
|
| 236 |
+
tensor.mul_(std).add_(mean)
|
| 237 |
+
|
| 238 |
+
|
| 239 |
+
def variance_scaling_(tensor, scale=1.0, mode="fan_in", distribution="normal"):
|
| 240 |
+
fan_in, fan_out = _calculate_fan_in_and_fan_out(tensor)
|
| 241 |
+
if mode == "fan_in":
|
| 242 |
+
denom = fan_in
|
| 243 |
+
elif mode == "fan_out":
|
| 244 |
+
denom = fan_out
|
| 245 |
+
elif mode == "fan_avg":
|
| 246 |
+
denom = (fan_in + fan_out) / 2
|
| 247 |
+
|
| 248 |
+
variance = scale / denom
|
| 249 |
+
|
| 250 |
+
if distribution == "truncated_normal":
|
| 251 |
+
# constant is stddev of standard normal truncated to (-2, 2)
|
| 252 |
+
trunc_normal_tf_(tensor, std=math.sqrt(variance) / 0.87962566103423978)
|
| 253 |
+
elif distribution == "normal":
|
| 254 |
+
with torch.no_grad():
|
| 255 |
+
tensor.normal_(std=math.sqrt(variance))
|
| 256 |
+
elif distribution == "uniform":
|
| 257 |
+
bound = math.sqrt(3 * variance)
|
| 258 |
+
with torch.no_grad():
|
| 259 |
+
tensor.uniform_(-bound, bound)
|
| 260 |
+
else:
|
| 261 |
+
raise ValueError(f"invalid distribution {distribution}")
|
| 262 |
+
|
| 263 |
+
|
| 264 |
+
def lecun_normal_(tensor):
|
| 265 |
+
variance_scaling_(tensor, mode="fan_in", distribution="truncated_normal")
|
| 266 |
+
|
| 267 |
+
|
| 268 |
+
def default_flax_embed_init(tensor):
|
| 269 |
+
variance_scaling_(tensor, mode="fan_in", distribution="normal")
|
| 270 |
+
|
| 271 |
+
|
| 272 |
+
@dataclass
|
| 273 |
+
# Copied from transformers.models.clip.modeling_clip.CLIPVisionModelOutput with CLIP->Siglip
|
| 274 |
+
class SiglipVisionModelOutput(ModelOutput):
|
| 275 |
+
"""
|
| 276 |
+
Base class for vision model's outputs that also contains image embeddings of the pooling of the last hidden states.
|
| 277 |
+
Args:
|
| 278 |
+
image_embeds (`torch.FloatTensor` of shape `(batch_size, output_dim)` *optional* returned when model is initialized with `with_projection=True`):
|
| 279 |
+
The image embeddings obtained by applying the projection layer to the pooler_output.
|
| 280 |
+
last_hidden_state (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`):
|
| 281 |
+
Sequence of hidden-states at the output of the last layer of the model.
|
| 282 |
+
hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
|
| 283 |
+
Tuple of `torch.FloatTensor` (one for the output of the embeddings, if the model has an embedding layer, +
|
| 284 |
+
one for the output of each layer) of shape `(batch_size, sequence_length, hidden_size)`.
|
| 285 |
+
Hidden-states of the model at the output of each layer plus the optional initial embedding outputs.
|
| 286 |
+
attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
|
| 287 |
+
Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
|
| 288 |
+
sequence_length)`.
|
| 289 |
+
Attentions weights after the attention softmax, used to compute the weighted average in the self-attention
|
| 290 |
+
heads.
|
| 291 |
+
"""
|
| 292 |
+
|
| 293 |
+
image_embeds: Optional[torch.FloatTensor] = None
|
| 294 |
+
last_hidden_state: torch.FloatTensor = None
|
| 295 |
+
hidden_states: Optional[Tuple[torch.FloatTensor]] = None
|
| 296 |
+
attentions: Optional[Tuple[torch.FloatTensor]] = None
|
| 297 |
+
|
| 298 |
+
|
| 299 |
+
class SiglipVisionEmbeddings(nn.Module):
|
| 300 |
+
def __init__(self, config: SiglipVisionConfig):
|
| 301 |
+
super().__init__()
|
| 302 |
+
self.config = config
|
| 303 |
+
self.embed_dim = config.hidden_size
|
| 304 |
+
self.image_size = config.image_size
|
| 305 |
+
self.patch_size = config.patch_size
|
| 306 |
+
|
| 307 |
+
self.patch_embedding = nn.Conv2d(
|
| 308 |
+
in_channels=config.num_channels,
|
| 309 |
+
out_channels=self.embed_dim,
|
| 310 |
+
kernel_size=self.patch_size,
|
| 311 |
+
stride=self.patch_size,
|
| 312 |
+
padding="valid",
|
| 313 |
+
)
|
| 314 |
+
|
| 315 |
+
self.num_patches_per_side = self.image_size // self.patch_size
|
| 316 |
+
self.num_patches = self.num_patches_per_side**2
|
| 317 |
+
self.num_positions = self.num_patches
|
| 318 |
+
self.position_embedding = nn.Embedding(self.num_positions, self.embed_dim)
|
| 319 |
+
|
| 320 |
+
def forward(
|
| 321 |
+
self,
|
| 322 |
+
pixel_values: torch.FloatTensor,
|
| 323 |
+
patch_attention_mask: torch.BoolTensor,
|
| 324 |
+
tgt_sizes: Optional[torch.IntTensor] = None,
|
| 325 |
+
) -> torch.Tensor:
|
| 326 |
+
batch_size = pixel_values.size(0)
|
| 327 |
+
|
| 328 |
+
patch_embeds = self.patch_embedding(pixel_values)
|
| 329 |
+
embeddings = patch_embeds.flatten(2).transpose(1, 2)
|
| 330 |
+
|
| 331 |
+
max_im_h, max_im_w = pixel_values.size(2), pixel_values.size(3)
|
| 332 |
+
max_nb_patches_h, max_nb_patches_w = max_im_h // self.patch_size, max_im_w // self.patch_size
|
| 333 |
+
boundaries = torch.arange(1 / self.num_patches_per_side, 1.0, 1 / self.num_patches_per_side)
|
| 334 |
+
position_ids = torch.full(
|
| 335 |
+
size=(
|
| 336 |
+
batch_size,
|
| 337 |
+
max_nb_patches_h * max_nb_patches_w,
|
| 338 |
+
),
|
| 339 |
+
fill_value=0,
|
| 340 |
+
)
|
| 341 |
+
|
| 342 |
+
for batch_idx, p_attn_mask in enumerate(patch_attention_mask):
|
| 343 |
+
if tgt_sizes is not None:
|
| 344 |
+
nb_patches_h = tgt_sizes[batch_idx][0]
|
| 345 |
+
nb_patches_w = tgt_sizes[batch_idx][1]
|
| 346 |
+
else:
|
| 347 |
+
nb_patches_h = p_attn_mask[:, 0].sum()
|
| 348 |
+
nb_patches_w = p_attn_mask[0].sum()
|
| 349 |
+
|
| 350 |
+
fractional_coords_h = torch.arange(0, 1 - 1e-6, 1 / nb_patches_h)
|
| 351 |
+
fractional_coords_w = torch.arange(0, 1 - 1e-6, 1 / nb_patches_w)
|
| 352 |
+
|
| 353 |
+
bucket_coords_h = torch.bucketize(fractional_coords_h, boundaries, right=True)
|
| 354 |
+
bucket_coords_w = torch.bucketize(fractional_coords_w, boundaries, right=True)
|
| 355 |
+
|
| 356 |
+
pos_ids = (bucket_coords_h[:, None] * self.num_patches_per_side + bucket_coords_w).flatten()
|
| 357 |
+
position_ids[batch_idx][p_attn_mask.view(-1).cpu()] = pos_ids
|
| 358 |
+
|
| 359 |
+
position_ids = position_ids.to(self.position_embedding.weight.device)
|
| 360 |
+
|
| 361 |
+
embeddings = embeddings + self.position_embedding(position_ids)
|
| 362 |
+
return embeddings
|
| 363 |
+
|
| 364 |
+
|
| 365 |
+
class SiglipAttention(nn.Module):
|
| 366 |
+
"""Multi-headed attention from 'Attention Is All You Need' paper"""
|
| 367 |
+
|
| 368 |
+
# Copied from transformers.models.clip.modeling_clip.CLIPAttention.__init__
|
| 369 |
+
def __init__(self, config):
|
| 370 |
+
super().__init__()
|
| 371 |
+
self.config = config
|
| 372 |
+
self.embed_dim = config.hidden_size
|
| 373 |
+
self.num_heads = config.num_attention_heads
|
| 374 |
+
self.head_dim = self.embed_dim // self.num_heads
|
| 375 |
+
if self.head_dim * self.num_heads != self.embed_dim:
|
| 376 |
+
raise ValueError(
|
| 377 |
+
f"embed_dim must be divisible by num_heads (got `embed_dim`: {self.embed_dim} and `num_heads`:"
|
| 378 |
+
f" {self.num_heads})."
|
| 379 |
+
)
|
| 380 |
+
self.scale = self.head_dim**-0.5
|
| 381 |
+
self.dropout = config.attention_dropout
|
| 382 |
+
|
| 383 |
+
self.k_proj = nn.Linear(self.embed_dim, self.embed_dim)
|
| 384 |
+
self.v_proj = nn.Linear(self.embed_dim, self.embed_dim)
|
| 385 |
+
self.q_proj = nn.Linear(self.embed_dim, self.embed_dim)
|
| 386 |
+
self.out_proj = nn.Linear(self.embed_dim, self.embed_dim)
|
| 387 |
+
|
| 388 |
+
def forward(
|
| 389 |
+
self,
|
| 390 |
+
hidden_states: torch.Tensor,
|
| 391 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 392 |
+
output_attentions: Optional[bool] = False,
|
| 393 |
+
) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
|
| 394 |
+
"""Input shape: Batch x Time x Channel"""
|
| 395 |
+
|
| 396 |
+
batch_size, q_len, _ = hidden_states.size()
|
| 397 |
+
|
| 398 |
+
query_states = self.q_proj(hidden_states)
|
| 399 |
+
key_states = self.k_proj(hidden_states)
|
| 400 |
+
value_states = self.v_proj(hidden_states)
|
| 401 |
+
|
| 402 |
+
query_states = query_states.view(batch_size, q_len, self.num_heads, self.head_dim).transpose(1, 2)
|
| 403 |
+
key_states = key_states.view(batch_size, q_len, self.num_heads, self.head_dim).transpose(1, 2)
|
| 404 |
+
value_states = value_states.view(batch_size, q_len, self.num_heads, self.head_dim).transpose(1, 2)
|
| 405 |
+
|
| 406 |
+
k_v_seq_len = key_states.shape[-2]
|
| 407 |
+
attn_weights = torch.matmul(query_states, key_states.transpose(2, 3)) * self.scale
|
| 408 |
+
|
| 409 |
+
if attn_weights.size() != (batch_size, self.num_heads, q_len, k_v_seq_len):
|
| 410 |
+
raise ValueError(
|
| 411 |
+
f"Attention weights should be of size {(batch_size, self.num_heads, q_len, k_v_seq_len)}, but is"
|
| 412 |
+
f" {attn_weights.size()}"
|
| 413 |
+
)
|
| 414 |
+
|
| 415 |
+
if attention_mask is not None:
|
| 416 |
+
if attention_mask.size() != (batch_size, 1, q_len, k_v_seq_len):
|
| 417 |
+
raise ValueError(
|
| 418 |
+
f"Attention mask should be of size {(batch_size, 1, q_len, k_v_seq_len)}, but is {attention_mask.size()}"
|
| 419 |
+
)
|
| 420 |
+
attn_weights = attn_weights + attention_mask
|
| 421 |
+
|
| 422 |
+
# upcast attention to fp32
|
| 423 |
+
attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query_states.dtype)
|
| 424 |
+
attn_weights = nn.functional.dropout(attn_weights, p=self.dropout, training=self.training)
|
| 425 |
+
attn_output = torch.matmul(attn_weights, value_states)
|
| 426 |
+
|
| 427 |
+
if attn_output.size() != (batch_size, self.num_heads, q_len, self.head_dim):
|
| 428 |
+
raise ValueError(
|
| 429 |
+
f"`attn_output` should be of size {(batch_size, self.num_heads, q_len, self.head_dim)}, but is"
|
| 430 |
+
f" {attn_output.size()}"
|
| 431 |
+
)
|
| 432 |
+
|
| 433 |
+
attn_output = attn_output.transpose(1, 2).contiguous()
|
| 434 |
+
attn_output = attn_output.reshape(batch_size, q_len, self.embed_dim)
|
| 435 |
+
|
| 436 |
+
attn_output = self.out_proj(attn_output)
|
| 437 |
+
|
| 438 |
+
return attn_output, attn_weights
|
| 439 |
+
|
| 440 |
+
|
| 441 |
+
class SiglipFlashAttention2(SiglipAttention):
|
| 442 |
+
"""
|
| 443 |
+
Llama flash attention module. This module inherits from `LlamaAttention` as the weights of the module stays
|
| 444 |
+
untouched. The only required change would be on the forward pass where it needs to correctly call the public API of
|
| 445 |
+
flash attention and deal with padding tokens in case the input contains any of them.
|
| 446 |
+
"""
|
| 447 |
+
|
| 448 |
+
def __init__(self, *args, **kwargs):
|
| 449 |
+
super().__init__(*args, **kwargs)
|
| 450 |
+
self.is_causal = False # Hack to make sure we don't use a causal mask
|
| 451 |
+
|
| 452 |
+
def forward(
|
| 453 |
+
self,
|
| 454 |
+
hidden_states: torch.Tensor,
|
| 455 |
+
attention_mask: Optional[torch.LongTensor] = None,
|
| 456 |
+
position_ids: Optional[torch.LongTensor] = None,
|
| 457 |
+
past_key_value: Optional[Tuple[torch.Tensor]] = None,
|
| 458 |
+
output_attentions: bool = False,
|
| 459 |
+
use_cache: bool = False,
|
| 460 |
+
**kwargs,
|
| 461 |
+
) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
|
| 462 |
+
output_attentions = False
|
| 463 |
+
|
| 464 |
+
bsz, q_len, _ = hidden_states.size()
|
| 465 |
+
|
| 466 |
+
query_states = self.q_proj(hidden_states)
|
| 467 |
+
key_states = self.k_proj(hidden_states)
|
| 468 |
+
value_states = self.v_proj(hidden_states)
|
| 469 |
+
|
| 470 |
+
# Flash attention requires the input to have the shape
|
| 471 |
+
# batch_size x seq_length x head_dim x hidden_dim
|
| 472 |
+
# therefore we just need to keep the original shape
|
| 473 |
+
query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
|
| 474 |
+
key_states = key_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
|
| 475 |
+
value_states = value_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
|
| 476 |
+
|
| 477 |
+
kv_seq_len = key_states.shape[-2]
|
| 478 |
+
if past_key_value is not None:
|
| 479 |
+
kv_seq_len += past_key_value.get_usable_length(kv_seq_len, self.layer_idx)
|
| 480 |
+
# cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len)
|
| 481 |
+
# query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids)
|
| 482 |
+
|
| 483 |
+
# if past_key_value is not None:
|
| 484 |
+
# cache_kwargs = {"sin": sin, "cos": cos} # Specific to RoPE models
|
| 485 |
+
# key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
|
| 486 |
+
|
| 487 |
+
# 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
|
| 488 |
+
# to be able to avoid many of these transpose/reshape/view.
|
| 489 |
+
query_states = query_states.transpose(1, 2)
|
| 490 |
+
key_states = key_states.transpose(1, 2)
|
| 491 |
+
value_states = value_states.transpose(1, 2)
|
| 492 |
+
|
| 493 |
+
dropout_rate = self.dropout if self.training else 0.0
|
| 494 |
+
|
| 495 |
+
# In PEFT, usually we cast the layer norms in float32 for training stability reasons
|
| 496 |
+
# therefore the input hidden states gets silently casted in float32. Hence, we need
|
| 497 |
+
# cast them back in the correct dtype just to be sure everything works as expected.
|
| 498 |
+
# This might slowdown training & inference so it is recommended to not cast the LayerNorms
|
| 499 |
+
# in fp32. (LlamaRMSNorm handles it correctly)
|
| 500 |
+
|
| 501 |
+
input_dtype = query_states.dtype
|
| 502 |
+
if input_dtype == torch.float32:
|
| 503 |
+
if torch.is_autocast_enabled():
|
| 504 |
+
target_dtype = torch.get_autocast_gpu_dtype()
|
| 505 |
+
# Handle the case where the model is quantized
|
| 506 |
+
elif hasattr(self.config, "_pre_quantization_dtype"):
|
| 507 |
+
target_dtype = self.config._pre_quantization_dtype
|
| 508 |
+
else:
|
| 509 |
+
target_dtype = self.q_proj.weight.dtype
|
| 510 |
+
|
| 511 |
+
logger.warning_once(
|
| 512 |
+
"The input hidden states seems to be silently casted in float32, this might be related to the fact"
|
| 513 |
+
" you have upcasted embedding or layer norm layers in float32. We will cast back the input in"
|
| 514 |
+
f" {target_dtype}."
|
| 515 |
+
)
|
| 516 |
+
|
| 517 |
+
query_states = query_states.to(target_dtype)
|
| 518 |
+
key_states = key_states.to(target_dtype)
|
| 519 |
+
value_states = value_states.to(target_dtype)
|
| 520 |
+
|
| 521 |
+
attn_output = self._flash_attention_forward(
|
| 522 |
+
query_states, key_states, value_states, attention_mask, q_len, dropout=dropout_rate
|
| 523 |
+
)
|
| 524 |
+
|
| 525 |
+
attn_output = attn_output.reshape(bsz, q_len, self.embed_dim).contiguous()
|
| 526 |
+
attn_output = self.out_proj(attn_output)
|
| 527 |
+
|
| 528 |
+
if not output_attentions:
|
| 529 |
+
attn_weights = None
|
| 530 |
+
|
| 531 |
+
return attn_output, attn_weights
|
| 532 |
+
|
| 533 |
+
def _flash_attention_forward(
|
| 534 |
+
self, query_states, key_states, value_states, attention_mask, query_length, dropout=0.0, softmax_scale=None
|
| 535 |
+
):
|
| 536 |
+
"""
|
| 537 |
+
Calls the forward method of Flash Attention - if the input hidden states contain at least one padding token
|
| 538 |
+
first unpad the input, then computes the attention scores and pad the final attention scores.
|
| 539 |
+
Args:
|
| 540 |
+
query_states (`torch.Tensor`):
|
| 541 |
+
Input query states to be passed to Flash Attention API
|
| 542 |
+
key_states (`torch.Tensor`):
|
| 543 |
+
Input key states to be passed to Flash Attention API
|
| 544 |
+
value_states (`torch.Tensor`):
|
| 545 |
+
Input value states to be passed to Flash Attention API
|
| 546 |
+
attention_mask (`torch.Tensor`):
|
| 547 |
+
The padding mask - corresponds to a tensor of size `(batch_size, seq_len)` where 0 stands for the
|
| 548 |
+
position of padding tokens and 1 for the position of non-padding tokens.
|
| 549 |
+
dropout (`int`, *optional*):
|
| 550 |
+
Attention dropout
|
| 551 |
+
softmax_scale (`float`, *optional*):
|
| 552 |
+
The scaling of QK^T before applying softmax. Default to 1 / sqrt(head_dim)
|
| 553 |
+
"""
|
| 554 |
+
|
| 555 |
+
# 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__.
|
| 556 |
+
causal = self.is_causal and query_length != 1
|
| 557 |
+
|
| 558 |
+
# Contains at least one padding token in the sequence
|
| 559 |
+
if attention_mask is not None:
|
| 560 |
+
batch_size = query_states.shape[0]
|
| 561 |
+
query_states, key_states, value_states, indices_q, cu_seq_lens, max_seq_lens = self._upad_input(
|
| 562 |
+
query_states, key_states, value_states, attention_mask, query_length
|
| 563 |
+
)
|
| 564 |
+
|
| 565 |
+
cu_seqlens_q, cu_seqlens_k = cu_seq_lens
|
| 566 |
+
max_seqlen_in_batch_q, max_seqlen_in_batch_k = max_seq_lens
|
| 567 |
+
|
| 568 |
+
attn_output_unpad = flash_attn_varlen_func(
|
| 569 |
+
query_states,
|
| 570 |
+
key_states,
|
| 571 |
+
value_states,
|
| 572 |
+
cu_seqlens_q=cu_seqlens_q,
|
| 573 |
+
cu_seqlens_k=cu_seqlens_k,
|
| 574 |
+
max_seqlen_q=max_seqlen_in_batch_q,
|
| 575 |
+
max_seqlen_k=max_seqlen_in_batch_k,
|
| 576 |
+
dropout_p=dropout,
|
| 577 |
+
softmax_scale=softmax_scale,
|
| 578 |
+
causal=causal,
|
| 579 |
+
)
|
| 580 |
+
|
| 581 |
+
attn_output = pad_input(attn_output_unpad, indices_q, batch_size, query_length)
|
| 582 |
+
else:
|
| 583 |
+
attn_output = flash_attn_func(
|
| 584 |
+
query_states, key_states, value_states, dropout, softmax_scale=softmax_scale, causal=causal
|
| 585 |
+
)
|
| 586 |
+
|
| 587 |
+
return attn_output
|
| 588 |
+
|
| 589 |
+
def _upad_input(self, query_layer, key_layer, value_layer, attention_mask, query_length):
|
| 590 |
+
indices_k, cu_seqlens_k, max_seqlen_in_batch_k = _get_unpad_data(attention_mask)
|
| 591 |
+
batch_size, kv_seq_len, num_key_value_heads, head_dim = key_layer.shape
|
| 592 |
+
|
| 593 |
+
key_layer = index_first_axis(
|
| 594 |
+
key_layer.reshape(batch_size * kv_seq_len, num_key_value_heads, head_dim), indices_k
|
| 595 |
+
)
|
| 596 |
+
value_layer = index_first_axis(
|
| 597 |
+
value_layer.reshape(batch_size * kv_seq_len, num_key_value_heads, head_dim), indices_k
|
| 598 |
+
)
|
| 599 |
+
if query_length == kv_seq_len:
|
| 600 |
+
query_layer = index_first_axis(
|
| 601 |
+
query_layer.reshape(batch_size * kv_seq_len, self.num_heads, head_dim), indices_k
|
| 602 |
+
)
|
| 603 |
+
cu_seqlens_q = cu_seqlens_k
|
| 604 |
+
max_seqlen_in_batch_q = max_seqlen_in_batch_k
|
| 605 |
+
indices_q = indices_k
|
| 606 |
+
elif query_length == 1:
|
| 607 |
+
max_seqlen_in_batch_q = 1
|
| 608 |
+
cu_seqlens_q = torch.arange(
|
| 609 |
+
batch_size + 1, dtype=torch.int32, device=query_layer.device
|
| 610 |
+
) # There is a memcpy here, that is very bad.
|
| 611 |
+
indices_q = cu_seqlens_q[:-1]
|
| 612 |
+
query_layer = query_layer.squeeze(1)
|
| 613 |
+
else:
|
| 614 |
+
# The -q_len: slice assumes left padding.
|
| 615 |
+
attention_mask = attention_mask[:, -query_length:]
|
| 616 |
+
query_layer, indices_q, cu_seqlens_q, max_seqlen_in_batch_q = unpad_input(query_layer, attention_mask)
|
| 617 |
+
|
| 618 |
+
return (
|
| 619 |
+
query_layer,
|
| 620 |
+
key_layer,
|
| 621 |
+
value_layer,
|
| 622 |
+
indices_q,
|
| 623 |
+
(cu_seqlens_q, cu_seqlens_k),
|
| 624 |
+
(max_seqlen_in_batch_q, max_seqlen_in_batch_k),
|
| 625 |
+
)
|
| 626 |
+
|
| 627 |
+
|
| 628 |
+
# Copied from transformers.models.clip.modeling_clip.CLIPMLP with CLIP->Siglip
|
| 629 |
+
class SiglipMLP(nn.Module):
|
| 630 |
+
def __init__(self, config):
|
| 631 |
+
super().__init__()
|
| 632 |
+
self.config = config
|
| 633 |
+
self.activation_fn = ACT2FN[config.hidden_act]
|
| 634 |
+
self.fc1 = nn.Linear(config.hidden_size, config.intermediate_size)
|
| 635 |
+
self.fc2 = nn.Linear(config.intermediate_size, config.hidden_size)
|
| 636 |
+
|
| 637 |
+
def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
|
| 638 |
+
hidden_states = self.fc1(hidden_states)
|
| 639 |
+
hidden_states = self.activation_fn(hidden_states)
|
| 640 |
+
hidden_states = self.fc2(hidden_states)
|
| 641 |
+
return hidden_states
|
| 642 |
+
|
| 643 |
+
|
| 644 |
+
# Copied from transformers.models.clip.modeling_clip.CLIPEncoderLayer with CLIP->Siglip
|
| 645 |
+
class SiglipEncoderLayer(nn.Module):
|
| 646 |
+
def __init__(self, config: SiglipVisionConfig):
|
| 647 |
+
super().__init__()
|
| 648 |
+
self.embed_dim = config.hidden_size
|
| 649 |
+
self._use_flash_attention_2 = config._attn_implementation == "flash_attention_2"
|
| 650 |
+
self.self_attn = SiglipAttention(config) if not self._use_flash_attention_2 else SiglipFlashAttention2(config)
|
| 651 |
+
self.layer_norm1 = nn.LayerNorm(self.embed_dim, eps=config.layer_norm_eps)
|
| 652 |
+
self.mlp = SiglipMLP(config)
|
| 653 |
+
self.layer_norm2 = nn.LayerNorm(self.embed_dim, eps=config.layer_norm_eps)
|
| 654 |
+
|
| 655 |
+
def forward(
|
| 656 |
+
self,
|
| 657 |
+
hidden_states: torch.Tensor,
|
| 658 |
+
attention_mask: torch.Tensor,
|
| 659 |
+
output_attentions: Optional[bool] = False,
|
| 660 |
+
) -> Tuple[torch.FloatTensor]:
|
| 661 |
+
"""
|
| 662 |
+
Args:
|
| 663 |
+
hidden_states (`torch.FloatTensor`):
|
| 664 |
+
Input to the layer of shape `(batch, seq_len, embed_dim)`.
|
| 665 |
+
attention_mask (`torch.FloatTensor`):
|
| 666 |
+
Attention mask of shape `(batch, 1, q_len, k_v_seq_len)` where padding elements are indicated by very large negative values.
|
| 667 |
+
output_attentions (`bool`, *optional*, defaults to `False`):
|
| 668 |
+
Whether or not to return the attentions tensors of all attention layers. See `attentions` under
|
| 669 |
+
returned tensors for more detail.
|
| 670 |
+
"""
|
| 671 |
+
residual = hidden_states
|
| 672 |
+
|
| 673 |
+
hidden_states = self.layer_norm1(hidden_states)
|
| 674 |
+
hidden_states, attn_weights = self.self_attn(
|
| 675 |
+
hidden_states=hidden_states,
|
| 676 |
+
attention_mask=attention_mask,
|
| 677 |
+
output_attentions=output_attentions,
|
| 678 |
+
)
|
| 679 |
+
hidden_states = residual + hidden_states
|
| 680 |
+
|
| 681 |
+
residual = hidden_states
|
| 682 |
+
hidden_states = self.layer_norm2(hidden_states)
|
| 683 |
+
hidden_states = self.mlp(hidden_states)
|
| 684 |
+
hidden_states = residual + hidden_states
|
| 685 |
+
|
| 686 |
+
outputs = (hidden_states,)
|
| 687 |
+
|
| 688 |
+
if output_attentions:
|
| 689 |
+
outputs += (attn_weights,)
|
| 690 |
+
|
| 691 |
+
return outputs
|
| 692 |
+
|
| 693 |
+
|
| 694 |
+
class SiglipPreTrainedModel(PreTrainedModel):
|
| 695 |
+
"""
|
| 696 |
+
An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
|
| 697 |
+
models.
|
| 698 |
+
"""
|
| 699 |
+
|
| 700 |
+
config_class = SiglipVisionConfig
|
| 701 |
+
base_model_prefix = "siglip"
|
| 702 |
+
supports_gradient_checkpointing = True
|
| 703 |
+
|
| 704 |
+
def _init_weights(self, module):
|
| 705 |
+
"""Initialize the weights"""
|
| 706 |
+
|
| 707 |
+
if isinstance(module, SiglipVisionEmbeddings):
|
| 708 |
+
width = self.config.hidden_size
|
| 709 |
+
nn.init.normal_(module.position_embedding.weight, std=1 / np.sqrt(width))
|
| 710 |
+
elif isinstance(module, nn.Embedding):
|
| 711 |
+
default_flax_embed_init(module.weight)
|
| 712 |
+
elif isinstance(module, SiglipAttention):
|
| 713 |
+
nn.init.normal_(module.q_proj.weight)
|
| 714 |
+
nn.init.normal_(module.k_proj.weight)
|
| 715 |
+
nn.init.normal_(module.v_proj.weight)
|
| 716 |
+
nn.init.normal_(module.out_proj.weight)
|
| 717 |
+
nn.init.zeros_(module.q_proj.bias)
|
| 718 |
+
nn.init.zeros_(module.k_proj.bias)
|
| 719 |
+
nn.init.zeros_(module.v_proj.bias)
|
| 720 |
+
nn.init.zeros_(module.out_proj.bias)
|
| 721 |
+
elif isinstance(module, SiglipMLP):
|
| 722 |
+
nn.init.normal_(module.fc1.weight)
|
| 723 |
+
nn.init.normal_(module.fc2.weight)
|
| 724 |
+
nn.init.normal_(module.fc1.bias, std=1e-6)
|
| 725 |
+
nn.init.normal_(module.fc2.bias, std=1e-6)
|
| 726 |
+
elif isinstance(module, (nn.Linear, nn.Conv2d)):
|
| 727 |
+
lecun_normal_(module.weight)
|
| 728 |
+
if module.bias is not None:
|
| 729 |
+
nn.init.zeros_(module.bias)
|
| 730 |
+
elif isinstance(module, nn.LayerNorm):
|
| 731 |
+
module.bias.data.zero_()
|
| 732 |
+
module.weight.data.fill_(1.0)
|
| 733 |
+
|
| 734 |
+
|
| 735 |
+
SIGLIP_START_DOCSTRING = r"""
|
| 736 |
+
This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
|
| 737 |
+
library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
|
| 738 |
+
etc.)
|
| 739 |
+
This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
|
| 740 |
+
Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
|
| 741 |
+
and behavior.
|
| 742 |
+
Parameters:
|
| 743 |
+
config ([`SiglipVisionConfig`]): Model configuration class with all the parameters of the model.
|
| 744 |
+
Initializing with a config file does not load the weights associated with the model, only the
|
| 745 |
+
configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.
|
| 746 |
+
"""
|
| 747 |
+
|
| 748 |
+
|
| 749 |
+
SIGLIP_VISION_INPUTS_DOCSTRING = r"""
|
| 750 |
+
Args:
|
| 751 |
+
pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`):
|
| 752 |
+
Pixel values. Padding will be ignored by default should you provide it. Pixel values can be obtained using
|
| 753 |
+
[`AutoImageProcessor`]. See [`CLIPImageProcessor.__call__`] for details.
|
| 754 |
+
output_attentions (`bool`, *optional*):
|
| 755 |
+
Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
|
| 756 |
+
tensors for more detail.
|
| 757 |
+
output_hidden_states (`bool`, *optional*):
|
| 758 |
+
Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
|
| 759 |
+
more detail.
|
| 760 |
+
return_dict (`bool`, *optional*):
|
| 761 |
+
Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
|
| 762 |
+
"""
|
| 763 |
+
|
| 764 |
+
|
| 765 |
+
# Copied from transformers.models.clip.modeling_clip.CLIPEncoder with CLIP->Siglip
|
| 766 |
+
class SiglipEncoder(nn.Module):
|
| 767 |
+
"""
|
| 768 |
+
Transformer encoder consisting of `config.num_hidden_layers` self attention layers. Each layer is a
|
| 769 |
+
[`SiglipEncoderLayer`].
|
| 770 |
+
Args:
|
| 771 |
+
config: SiglipConfig
|
| 772 |
+
"""
|
| 773 |
+
|
| 774 |
+
def __init__(self, config: SiglipVisionConfig):
|
| 775 |
+
super().__init__()
|
| 776 |
+
self.config = config
|
| 777 |
+
self.layers = nn.ModuleList([SiglipEncoderLayer(config) for _ in range(config.num_hidden_layers)])
|
| 778 |
+
self.gradient_checkpointing = False
|
| 779 |
+
|
| 780 |
+
# Ignore copy
|
| 781 |
+
def forward(
|
| 782 |
+
self,
|
| 783 |
+
inputs_embeds,
|
| 784 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 785 |
+
output_attentions: Optional[bool] = None,
|
| 786 |
+
output_hidden_states: Optional[bool] = None,
|
| 787 |
+
return_dict: Optional[bool] = None,
|
| 788 |
+
) -> Union[Tuple, BaseModelOutput]:
|
| 789 |
+
r"""
|
| 790 |
+
Args:
|
| 791 |
+
inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`):
|
| 792 |
+
Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation.
|
| 793 |
+
This is useful if you want more control over how to convert `input_ids` indices into associated vectors
|
| 794 |
+
than the model's internal embedding lookup matrix.
|
| 795 |
+
attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
|
| 796 |
+
Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
|
| 797 |
+
- 1 for tokens that are **not masked**,
|
| 798 |
+
- 0 for tokens that are **masked**.
|
| 799 |
+
[What are attention masks?](../glossary#attention-mask)
|
| 800 |
+
output_attentions (`bool`, *optional*):
|
| 801 |
+
Whether or not to return the attentions tensors of all attention layers. See `attentions` under
|
| 802 |
+
returned tensors for more detail.
|
| 803 |
+
output_hidden_states (`bool`, *optional*):
|
| 804 |
+
Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors
|
| 805 |
+
for more detail.
|
| 806 |
+
return_dict (`bool`, *optional*):
|
| 807 |
+
Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
|
| 808 |
+
"""
|
| 809 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
| 810 |
+
output_hidden_states = (
|
| 811 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
| 812 |
+
)
|
| 813 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 814 |
+
|
| 815 |
+
encoder_states = () if output_hidden_states else None
|
| 816 |
+
all_attentions = () if output_attentions else None
|
| 817 |
+
|
| 818 |
+
hidden_states = inputs_embeds
|
| 819 |
+
for encoder_layer in self.layers:
|
| 820 |
+
if output_hidden_states:
|
| 821 |
+
encoder_states = encoder_states + (hidden_states,)
|
| 822 |
+
if self.gradient_checkpointing and self.training:
|
| 823 |
+
layer_outputs = self._gradient_checkpointing_func(
|
| 824 |
+
encoder_layer.__call__,
|
| 825 |
+
hidden_states,
|
| 826 |
+
attention_mask,
|
| 827 |
+
output_attentions,
|
| 828 |
+
)
|
| 829 |
+
else:
|
| 830 |
+
layer_outputs = encoder_layer(
|
| 831 |
+
hidden_states,
|
| 832 |
+
attention_mask,
|
| 833 |
+
output_attentions=output_attentions,
|
| 834 |
+
)
|
| 835 |
+
|
| 836 |
+
hidden_states = layer_outputs[0]
|
| 837 |
+
|
| 838 |
+
if output_attentions:
|
| 839 |
+
all_attentions = all_attentions + (layer_outputs[1],)
|
| 840 |
+
|
| 841 |
+
if output_hidden_states:
|
| 842 |
+
encoder_states = encoder_states + (hidden_states,)
|
| 843 |
+
|
| 844 |
+
if not return_dict:
|
| 845 |
+
return tuple(v for v in [hidden_states, encoder_states, all_attentions] if v is not None)
|
| 846 |
+
return BaseModelOutput(last_hidden_state=hidden_states, hidden_states=encoder_states, attentions=all_attentions)
|
| 847 |
+
|
| 848 |
+
|
| 849 |
+
@add_start_docstrings("""The vision model from SigLIP without any head or projection on top.""", SIGLIP_START_DOCSTRING)
|
| 850 |
+
class SiglipVisionTransformer(SiglipPreTrainedModel):
|
| 851 |
+
config_class = SiglipVisionConfig
|
| 852 |
+
main_input_name = "pixel_values"
|
| 853 |
+
_supports_flash_attn_2 = True
|
| 854 |
+
_no_split_modules = []
|
| 855 |
+
|
| 856 |
+
def __init__(self, config: SiglipVisionConfig):
|
| 857 |
+
super().__init__(config)
|
| 858 |
+
self.config = config
|
| 859 |
+
embed_dim = config.hidden_size
|
| 860 |
+
|
| 861 |
+
self.embeddings = SiglipVisionEmbeddings(config)
|
| 862 |
+
self.encoder = SiglipEncoder(config)
|
| 863 |
+
self.post_layernorm = nn.LayerNorm(embed_dim, eps=config.layer_norm_eps)
|
| 864 |
+
self._use_flash_attention_2 = config._attn_implementation == "flash_attention_2"
|
| 865 |
+
|
| 866 |
+
# Initialize weights and apply final processing
|
| 867 |
+
self.post_init()
|
| 868 |
+
|
| 869 |
+
def get_input_embeddings(self) -> nn.Module:
|
| 870 |
+
return self.embeddings.patch_embedding
|
| 871 |
+
|
| 872 |
+
@add_start_docstrings_to_model_forward(SIGLIP_VISION_INPUTS_DOCSTRING)
|
| 873 |
+
@replace_return_docstrings(output_type=BaseModelOutputWithPooling, config_class=SiglipVisionConfig)
|
| 874 |
+
def forward(
|
| 875 |
+
self,
|
| 876 |
+
pixel_values,
|
| 877 |
+
patch_attention_mask: Optional[torch.BoolTensor] = None,
|
| 878 |
+
tgt_sizes: Optional[torch.IntTensor] = None,
|
| 879 |
+
output_attentions: Optional[bool] = None,
|
| 880 |
+
output_hidden_states: Optional[bool] = None,
|
| 881 |
+
return_dict: Optional[bool] = None,
|
| 882 |
+
) -> Union[Tuple, BaseModelOutputWithPooling]:
|
| 883 |
+
r"""
|
| 884 |
+
Returns:
|
| 885 |
+
"""
|
| 886 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
| 887 |
+
output_hidden_states = (
|
| 888 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
| 889 |
+
)
|
| 890 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 891 |
+
|
| 892 |
+
batch_size = pixel_values.size(0)
|
| 893 |
+
if patch_attention_mask is None:
|
| 894 |
+
patch_attention_mask = torch.ones(
|
| 895 |
+
size=(
|
| 896 |
+
batch_size,
|
| 897 |
+
pixel_values.size(2) // self.config.patch_size,
|
| 898 |
+
pixel_values.size(3) // self.config.patch_size,
|
| 899 |
+
),
|
| 900 |
+
dtype=torch.bool,
|
| 901 |
+
device=pixel_values.device,
|
| 902 |
+
)
|
| 903 |
+
|
| 904 |
+
hidden_states = self.embeddings(
|
| 905 |
+
pixel_values=pixel_values, patch_attention_mask=patch_attention_mask, tgt_sizes=tgt_sizes
|
| 906 |
+
)
|
| 907 |
+
|
| 908 |
+
patch_attention_mask = patch_attention_mask.view(batch_size, -1)
|
| 909 |
+
# The call to `_upad_input` in `_flash_attention_forward` is expensive
|
| 910 |
+
# So when the `patch_attention_mask` is full of 1s (i.e. attending to the whole sequence),
|
| 911 |
+
# avoiding passing the attention_mask, which is equivalent to attending to the full sequence
|
| 912 |
+
if not torch.any(~patch_attention_mask):
|
| 913 |
+
attention_mask = None
|
| 914 |
+
else:
|
| 915 |
+
attention_mask = (
|
| 916 |
+
_prepare_4d_attention_mask(patch_attention_mask, hidden_states.dtype)
|
| 917 |
+
if not self._use_flash_attention_2
|
| 918 |
+
else patch_attention_mask
|
| 919 |
+
)
|
| 920 |
+
|
| 921 |
+
encoder_outputs = self.encoder(
|
| 922 |
+
inputs_embeds=hidden_states,
|
| 923 |
+
attention_mask=attention_mask,
|
| 924 |
+
output_attentions=output_attentions,
|
| 925 |
+
output_hidden_states=output_hidden_states,
|
| 926 |
+
return_dict=return_dict,
|
| 927 |
+
)
|
| 928 |
+
|
| 929 |
+
last_hidden_state = encoder_outputs[0]
|
| 930 |
+
last_hidden_state = self.post_layernorm(last_hidden_state)
|
| 931 |
+
|
| 932 |
+
if not return_dict:
|
| 933 |
+
return (last_hidden_state, None) + encoder_outputs[1:]
|
| 934 |
+
|
| 935 |
+
return BaseModelOutputWithPooling(
|
| 936 |
+
last_hidden_state=last_hidden_state,
|
| 937 |
+
pooler_output=None,
|
| 938 |
+
hidden_states=encoder_outputs.hidden_states,
|
| 939 |
+
attentions=encoder_outputs.attentions,
|
| 940 |
+
)
|