Aluode/PerceptionLabPortable
0
1# coding=utf-82# Copyright 2023 The Salesforce Authors and The HuggingFace Team. All rights reserved.3#4# Licensed under the Apache License, Version 2.0 (the "License");5# you may not use this file except in compliance with the License.6# You may obtain a copy of the License at7#8# http://www.apache.org/licenses/LICENSE-2.09#10# Unless required by applicable law or agreed to in writing, software11# 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 and14# limitations under the License.15"""PyTorch BLIP-2 model."""16 17import math18import warnings19from dataclasses import dataclass20from typing import Any, Callable, Optional, Union21 22import torch23from torch import nn24from torch.nn import CrossEntropyLoss25 26from ...activations import ACT2FN27from ...generation import GenerationMixin28from ...modeling_layers import GradientCheckpointingLayer29from ...modeling_outputs import (30 BaseModelOutput,31 BaseModelOutputWithPastAndCrossAttentions,32 BaseModelOutputWithPooling,33 BaseModelOutputWithPoolingAndCrossAttentions,34 CausalLMOutputWithPast,35 Seq2SeqLMOutput,36)37from ...modeling_utils import ALL_ATTENTION_FUNCTIONS, PreTrainedModel38from ...processing_utils import Unpack39from ...pytorch_utils import apply_chunking_to_forward, find_pruneable_heads_and_indices, prune_linear_layer40from ...utils import (41 ModelOutput,42 TransformersKwargs,43 auto_docstring,44 can_return_tuple,45 filter_out_non_signature_kwargs,46 logging,47 torch_int,48)49from ...utils.generic import OutputRecorder, check_model_inputs50from ..auto import AutoModelForCausalLM, AutoModelForSeq2SeqLM51from .configuration_blip_2 import Blip2Config, Blip2QFormerConfig, Blip2VisionConfig52 53 54logger = logging.get_logger(__name__)55 56 57@dataclass58@auto_docstring(59 custom_intro="""60 Class defining the outputs of [`Blip2ForConditionalGeneration`].61 """62)63class Blip2ForConditionalGenerationModelOutput(ModelOutput):64 r"""65 loss (`torch.FloatTensor`, *optional*, returned when `labels` is provided, `torch.FloatTensor` of shape `(1,)`):66 Language modeling loss from the language model.67 logits (`torch.FloatTensor` of shape `(batch_size, sequence_length, config.vocab_size)`):68 Prediction scores of the language modeling head of the language model.69 vision_outputs (`BaseModelOutputWithPooling`):70 Outputs of the vision encoder.71 qformer_outputs (`BaseModelOutputWithPoolingAndCrossAttentions`):72 Outputs of the Q-Former (Querying Transformer).73 language_model_outputs (`CausalLMOutputWithPast` or `Seq2SeqLMOutput`):74 Outputs of the language model.75 """76 77 loss: Optional[tuple[torch.FloatTensor]] = None78 logits: Optional[tuple[torch.FloatTensor]] = None79 vision_outputs: Optional[torch.FloatTensor] = None80 qformer_outputs: Optional[tuple[torch.FloatTensor]] = None81 language_model_outputs: Optional[tuple[torch.FloatTensor]] = None82 83 def to_tuple(self) -> tuple[Any]:84 return tuple(85 self[k]86 if k not in ["vision_outputs", "qformer_outputs", "language_model_outputs"]87 else getattr(self, k).to_tuple()88 for k in self.keys()89 )90 91 92@dataclass93@auto_docstring94class Blip2ImageTextMatchingModelOutput(ModelOutput):95 r"""96 loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `return_loss` is `True`):97 Contrastive loss for image-text similarity.98 logits_per_image (`torch.FloatTensor` of shape `(image_batch_size, text_batch_size)`):99 The scaled dot product scores between `image_embeds` and `text_embeds`. This represents the image-text100 similarity scores.101 logits_per_text (`torch.FloatTensor` of shape `(text_batch_size, image_batch_size)`):102 The scaled dot product scores between `text_embeds` and `image_embeds`. This represents the text-image103 similarity scores.104 text_embeds (`torch.FloatTensor` of shape `(batch_size, output_dim`):105 The text embeddings obtained by applying the projection layer to the pooled output.106 image_embeds (`torch.FloatTensor` of shape `(batch_size, output_dim`):107 The image embeddings obtained by applying the projection layer to the pooled output.108 text_model_output (`BaseModelOutputWithPooling`):109 The output of the [`Blip2QFormerModel`].110 vision_model_output (`BaseModelOutputWithPooling`):111 The output of the [`Blip2VisionModel`].112 """113 114 loss: Optional[torch.FloatTensor] = None115 logits_per_image: Optional[torch.FloatTensor] = None116 logits_per_text: Optional[torch.FloatTensor] = None117 text_embeds: Optional[torch.FloatTensor] = None118 image_embeds: Optional[torch.FloatTensor] = None119 text_model_output: BaseModelOutputWithPooling = None120 vision_model_output: BaseModelOutputWithPooling = None121 122 def to_tuple(self) -> tuple[Any]:123 return tuple(124 self[k] if k not in ["text_model_output", "vision_model_output"] else getattr(self, k).to_tuple()125 for k in self.keys()126 )127 128 129@dataclass130@auto_docstring(131 custom_intro="""132 Base class for text model's outputs that also contains a pooling of the last hidden states.133 """134)135# Copied from transformers.models.clip.modeling_clip.CLIPTextModelOutput with CLIP->Blip2136class Blip2TextModelOutput(ModelOutput):137 r"""138 text_embeds (`torch.FloatTensor` of shape `(batch_size, output_dim)` *optional* returned when model is initialized with `with_projection=True`):139 The text embeddings obtained by applying the projection layer to the pooler_output.140 """141 142 text_embeds: Optional[torch.FloatTensor] = None143 last_hidden_state: Optional[torch.FloatTensor] = None144 hidden_states: Optional[tuple[torch.FloatTensor, ...]] = None145 attentions: Optional[tuple[torch.FloatTensor, ...]] = None146 147 148@dataclass149@auto_docstring(150 custom_intro="""151 Base class for vision model's outputs that also contains image embeddings of the pooling of the last hidden states.152 """153)154# Copied from transformers.models.clip.modeling_clip.CLIPVisionModelOutput with CLIP->Blip2155class Blip2VisionModelOutput(ModelOutput):156 r"""157 image_embeds (`torch.FloatTensor` of shape `(batch_size, output_dim)` *optional* returned when model is initialized with `with_projection=True`):158 The image embeddings obtained by applying the projection layer to the pooler_output.159 """160 161 image_embeds: Optional[torch.FloatTensor] = None162 last_hidden_state: Optional[torch.FloatTensor] = None163 hidden_states: Optional[tuple[torch.FloatTensor, ...]] = None164 attentions: Optional[tuple[torch.FloatTensor, ...]] = None165 166 167# Copied from transformers.models.blip.modeling_blip.BlipVisionEmbeddings with Blip->Blip2168class Blip2VisionEmbeddings(nn.Module):169 def __init__(self, config: Blip2VisionConfig):170 super().__init__()171 self.config = config172 self.embed_dim = config.hidden_size173 self.image_size = config.image_size174 self.patch_size = config.patch_size175 176 self.class_embedding = nn.Parameter(torch.randn(1, 1, self.embed_dim))177 178 self.patch_embedding = nn.Conv2d(179 in_channels=3, out_channels=self.embed_dim, kernel_size=self.patch_size, stride=self.patch_size180 )181 182 self.num_patches = (self.image_size // self.patch_size) ** 2183 self.num_positions = self.num_patches + 1184 185 self.position_embedding = nn.Parameter(torch.randn(1, self.num_positions, self.embed_dim))186 187 def interpolate_pos_encoding(self, embeddings: torch.Tensor, height: int, width: int) -> torch.Tensor:188 """189 This method allows to interpolate the pre-trained position encodings, to be able to use the model on higher resolution190 images. This method is also adapted to support torch.jit tracing.191 192 Adapted from:193 - https://github.com/facebookresearch/dino/blob/de9ee3df6cf39fac952ab558447af1fa1365362a/vision_transformer.py#L174-L194, and194 - https://github.com/facebookresearch/dinov2/blob/e1277af2ba9496fbadf7aec6eba56e8d882d1e35/dinov2/models/vision_transformer.py#L179-L211195 """196 197 num_patches = embeddings.shape[1] - 1198 num_positions = self.position_embedding.shape[1] - 1199 200 # always interpolate when tracing to ensure the exported model works for dynamic input shapes201 if not torch.jit.is_tracing() and num_patches == num_positions and height == width:202 return self.position_embedding203 204 class_pos_embed = self.position_embedding[:, :1]205 patch_pos_embed = self.position_embedding[:, 1:]206 207 dim = embeddings.shape[-1]208 209 new_height = height // self.patch_size210 new_width = width // self.patch_size211 212 sqrt_num_positions = torch_int(num_positions**0.5)213 patch_pos_embed = patch_pos_embed.reshape(1, sqrt_num_positions, sqrt_num_positions, dim)214 patch_pos_embed = patch_pos_embed.permute(0, 3, 1, 2)215 216 patch_pos_embed = nn.functional.interpolate(217 patch_pos_embed,218 size=(new_height, new_width),219 mode="bicubic",220 align_corners=False,221 )222 223 patch_pos_embed = patch_pos_embed.permute(0, 2, 3, 1).view(1, -1, dim)224 225 return torch.cat((class_pos_embed, patch_pos_embed), dim=1)226 227 def forward(self, pixel_values: torch.FloatTensor, interpolate_pos_encoding: bool = False) -> torch.Tensor:228 batch_size, _, height, width = pixel_values.shape229 target_dtype = self.patch_embedding.weight.dtype230 patch_embeds = self.patch_embedding(pixel_values.to(dtype=target_dtype)) # shape = [*, width, grid, grid]231 patch_embeds = patch_embeds.flatten(2).transpose(1, 2)232 class_embeds = self.class_embedding.expand(batch_size, 1, -1).to(target_dtype)233 embeddings = torch.cat([class_embeds, patch_embeds], dim=1)234 if interpolate_pos_encoding:235 position_embedding = self.interpolate_pos_encoding(embeddings, height, width)236 else:237 position_embedding = self.position_embedding238 embeddings = embeddings + position_embedding[:, : embeddings.size(1), :].to(target_dtype)239 return embeddings240 241 242# Adapted from transformers.models.siglip.modeling_siglip.eager_attention_forward -> BLIP doesn't cast attn weights to fp32243def eager_attention_forward(244 module: nn.Module,245 query: torch.Tensor,246 key: torch.Tensor,247 value: torch.Tensor,248 attention_mask: Optional[torch.Tensor],249 scaling: float,250 dropout: float = 0.0,251 **kwargs,252):253 attn_weights = torch.matmul(query, key.transpose(-1, -2)) * scaling254 if attention_mask is not None:255 attn_weights = attn_weights + attention_mask256 257 attn_weights = nn.functional.softmax(attn_weights, dim=-1)258 attn_weights = nn.functional.dropout(attn_weights, p=dropout, training=module.training)259 260 attn_output = torch.matmul(attn_weights, value)261 attn_output = attn_output.transpose(1, 2).contiguous()262 263 return attn_output, attn_weights264 265 266class Blip2Attention(nn.Module):267 """Multi-headed attention from 'Attention Is All You Need' paper"""268 269 def __init__(self, config):270 super().__init__()271 self.config = config272 self.embed_dim = config.hidden_size273 self.num_heads = config.num_attention_heads274 self.head_dim = self.embed_dim // self.num_heads275 if self.head_dim * self.num_heads != self.embed_dim:276 raise ValueError(277 f"embed_dim must be divisible by num_heads (got `embed_dim`: {self.embed_dim} and `num_heads`:"278 f" {self.num_heads})."279 )280 self.scale = self.head_dim**-0.5281 self.is_causal = False282 self.attention_dropout = config.attention_dropout283 284 # small tweak here compared to CLIP, no bias here285 self.qkv = nn.Linear(self.embed_dim, 3 * self.embed_dim, bias=False)286 287 if config.qkv_bias:288 q_bias = nn.Parameter(torch.zeros(self.embed_dim))289 v_bias = nn.Parameter(torch.zeros(self.embed_dim))290 else:291 q_bias = None292 v_bias = None293 294 if q_bias is not None:295 qkv_bias = torch.cat((q_bias, torch.zeros_like(v_bias, requires_grad=False), v_bias))296 self.qkv.bias = nn.Parameter(qkv_bias)297 298 self.projection = nn.Linear(self.embed_dim, self.embed_dim)299 300 def _shape(self, tensor: torch.Tensor, seq_len: int, bsz: int):301 return tensor.view(bsz, seq_len, self.num_heads, self.head_dim).transpose(1, 2).contiguous()302 303 def forward(304 self,305 hidden_states: torch.Tensor,306 head_mask: Optional[torch.Tensor] = None,307 **kwargs,308 ) -> tuple[torch.Tensor, Optional[torch.Tensor], Optional[tuple[torch.Tensor]]]:309 """Input shape: Batch x Time x Channel"""310 311 bsz, tgt_len, embed_dim = hidden_states.size()312 313 mixed_qkv = self.qkv(hidden_states)314 315 mixed_qkv = mixed_qkv.reshape(bsz, tgt_len, 3, self.num_heads, embed_dim // self.num_heads).permute(316 2, 0, 3, 1, 4317 )318 query_states, key_states, value_states = mixed_qkv[0], mixed_qkv[1], mixed_qkv[2]319 320 attention_interface: Callable = eager_attention_forward321 322 if self.config._attn_implementation != "eager":323 attention_interface = ALL_ATTENTION_FUNCTIONS[self.config._attn_implementation]324 325 attn_output, attn_weights = attention_interface(326 self,327 query_states,328 key_states,329 value_states,330 attention_mask=None,331 dropout=0.0 if not self.training else self.attention_dropout,332 scaling=self.scale,333 **kwargs,334 )335 336 attn_output = attn_output.reshape(bsz, tgt_len, -1).contiguous()337 attn_output = self.projection(attn_output)338 339 return attn_output, attn_weights340 341 342# Copied from transformers.models.blip.modeling_blip.BlipMLP343class Blip2MLP(nn.Module):344 def __init__(self, config):345 super().__init__()346 self.config = config347 self.activation_fn = ACT2FN[config.hidden_act]348 self.fc1 = nn.Linear(config.hidden_size, config.intermediate_size)349 self.fc2 = nn.Linear(config.intermediate_size, config.hidden_size)350 351 def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:352 hidden_states = self.fc1(hidden_states)353 hidden_states = self.activation_fn(hidden_states)354 hidden_states = self.fc2(hidden_states)355 return hidden_states356 357 358# Copied from transformers.models.blip.modeling_blip.BlipEncoderLayer with Blip->Blip2359class Blip2EncoderLayer(GradientCheckpointingLayer):360 def __init__(self, config: Blip2Config):361 super().__init__()362 self.embed_dim = config.hidden_size363 self.self_attn = Blip2Attention(config)364 self.layer_norm1 = nn.LayerNorm(self.embed_dim, eps=config.layer_norm_eps)365 self.mlp = Blip2MLP(config)366 self.layer_norm2 = nn.LayerNorm(self.embed_dim, eps=config.layer_norm_eps)367 368 @auto_docstring369 def forward(370 self,371 hidden_states: torch.Tensor,372 attention_mask: torch.Tensor,373 **kwargs: Unpack[TransformersKwargs],374 ) -> torch.FloatTensor:375 residual = hidden_states376 377 hidden_states = self.layer_norm1(hidden_states)378 hidden_states, _ = self.self_attn(379 hidden_states=hidden_states,380 head_mask=attention_mask,381 **kwargs,382 )383 hidden_states = hidden_states + residual384 residual = hidden_states385 hidden_states = self.layer_norm2(hidden_states)386 hidden_states = self.mlp(hidden_states)387 388 hidden_states = hidden_states + residual389 390 return hidden_states391 392 393@auto_docstring394class Blip2PreTrainedModel(PreTrainedModel):395 config: Blip2Config396 base_model_prefix = "blip"397 supports_gradient_checkpointing = True398 _supports_attention_backend = True399 _supports_flash_attn = True400 _supports_sdpa = True401 _supports_flex_attn = True402 403 _no_split_modules = [404 "Blip2Attention",405 "Blip2QFormerMultiHeadAttention",406 "Blip2EncoderLayer",407 "Blip2TextEmbeddings",408 "T5Block",409 "OPTDecoderLayer",410 ]411 _skip_keys_device_placement = "past_key_values"412 413 def _init_weights(self, module):414 """Initialize the weights"""415 factor = self.config.initializer_range416 417 if isinstance(module, (nn.Linear, nn.Conv2d)):418 module.weight.data.normal_(mean=0.0, std=factor)419 if module.bias is not None:420 module.bias.data.zero_()421 elif isinstance(module, nn.Embedding):422 module.weight.data.normal_(mean=0.0, std=factor)423 elif isinstance(module, nn.LayerNorm):424 module.bias.data.zero_()425 module.weight.data.fill_(1.0)426 elif isinstance(module, Blip2VisionEmbeddings):427 nn.init.trunc_normal_(module.position_embedding, mean=0.0, std=factor)428 nn.init.trunc_normal_(module.class_embedding, mean=0.0, std=factor)429 elif isinstance(430 module,431 (432 Blip2Model,433 Blip2TextModelWithProjection,434 Blip2VisionModelWithProjection,435 Blip2ForConditionalGeneration,436 Blip2ForImageTextRetrieval,437 ),438 ):439 module.query_tokens.data.zero_()440 441 442# Copied from transformers.models.blip.modeling_blip.BlipEncoder with Blip->Blip2443class Blip2Encoder(nn.Module):444 """445 Transformer encoder consisting of `config.num_hidden_layers` self attention layers. Each layer is a446 [`Blip2EncoderLayer`].447 448 Args:449 config (`Blip2Config`):450 The corresponding vision configuration for the `Blip2Encoder`.451 """452 453 def __init__(self, config: Blip2Config):454 super().__init__()455 self.config = config456 self.layers = nn.ModuleList([Blip2EncoderLayer(config) for _ in range(config.num_hidden_layers)])457 self.gradient_checkpointing = False458 459 @auto_docstring460 def forward(461 self,462 inputs_embeds,463 attention_mask: Optional[torch.Tensor] = None,464 **kwargs: Unpack[TransformersKwargs],465 ) -> Union[tuple, BaseModelOutput]:466 hidden_states = inputs_embeds467 for encoder_layer in self.layers:468 hidden_states = encoder_layer(469 hidden_states,470 attention_mask=attention_mask,471 **kwargs,472 )473 474 return BaseModelOutput(last_hidden_state=hidden_states)475 476 477@auto_docstring478# Copied from transformers.models.blip.modeling_blip.BlipVisionModel with Blip->Blip2, BLIP->BLIP_2479class Blip2VisionModel(Blip2PreTrainedModel):480 main_input_name = "pixel_values"481 config: Blip2VisionConfig482 _can_record_outputs = {483 "hidden_states": Blip2EncoderLayer,484 "attentions": Blip2Attention,485 }486 487 def __init__(self, config: Blip2VisionConfig):488 super().__init__(config)489 self.config = config490 embed_dim = config.hidden_size491 492 self.embeddings = Blip2VisionEmbeddings(config)493 self.encoder = Blip2Encoder(config)494 self.post_layernorm = nn.LayerNorm(embed_dim, eps=config.layer_norm_eps)495 496 self.post_init()497 498 @check_model_inputs(tie_last_hidden_states=False)499 @auto_docstring500 def forward(501 self,502 pixel_values: Optional[torch.FloatTensor] = None,503 interpolate_pos_encoding: bool = False,504 **kwargs: Unpack[TransformersKwargs],505 ) -> Union[tuple, BaseModelOutputWithPooling]:506 if pixel_values is None:507 raise ValueError("You have to specify pixel_values")508 509 hidden_states = self.embeddings(pixel_values, interpolate_pos_encoding=interpolate_pos_encoding)510 511 encoder_outputs: BaseModelOutput = self.encoder(512 inputs_embeds=hidden_states,513 **kwargs,514 )515 516 last_hidden_state = encoder_outputs.last_hidden_state517 last_hidden_state = self.post_layernorm(last_hidden_state)518 519 pooled_output = last_hidden_state[:, 0, :]520 pooled_output = self.post_layernorm(pooled_output)521 522 return BaseModelOutputWithPooling(523 last_hidden_state=last_hidden_state,524 pooler_output=pooled_output,525 )526 527 def get_input_embeddings(self):528 return self.embeddings529 530 531class Blip2QFormerMultiHeadAttention(nn.Module):532 def __init__(self, config, is_cross_attention=False):533 super().__init__()534 self.config = config535 if config.hidden_size % config.num_attention_heads != 0 and not hasattr(config, "embedding_size"):536 raise ValueError(537 "The hidden size (%d) is not a multiple of the number of attention heads (%d)"538 % (config.hidden_size, config.num_attention_heads)539 )540 541 self.num_attention_heads = config.num_attention_heads542 self.attention_head_size = int(config.hidden_size / config.num_attention_heads)543 self.all_head_size = self.num_attention_heads * self.attention_head_size544 545 self.query = nn.Linear(config.hidden_size, self.all_head_size)546 if is_cross_attention:547 self.key = nn.Linear(config.encoder_hidden_size, self.all_head_size)548 self.value = nn.Linear(config.encoder_hidden_size, self.all_head_size)549 else:550 self.key = nn.Linear(config.hidden_size, self.all_head_size)551 self.value = nn.Linear(config.hidden_size, self.all_head_size)552 553 self.dropout = nn.Dropout(config.attention_probs_dropout_prob)554 self.position_embedding_type = getattr(config, "position_embedding_type", "absolute")555 if self.position_embedding_type == "relative_key" or self.position_embedding_type == "relative_key_query":556 self.max_position_embeddings = config.max_position_embeddings557 self.distance_embedding = nn.Embedding(2 * config.max_position_embeddings - 1, self.attention_head_size)558 self.save_attention = False559 560 def save_attn_gradients(self, attn_gradients):561 self.attn_gradients = attn_gradients562 563 def get_attn_gradients(self):564 return self.attn_gradients565 566 def save_attention_map(self, attention_map):567 self.attention_map = attention_map568 569 def get_attention_map(self):570 return self.attention_map571 572 def transpose_for_scores(self, x):573 new_x_shape = x.size()[:-1] + (self.num_attention_heads, self.attention_head_size)574 x = x.view(*new_x_shape)575 return x.permute(0, 2, 1, 3)576 577 def forward(578 self,579 hidden_states,580 attention_mask=None,581 head_mask=None,582 encoder_hidden_states=None,583 encoder_attention_mask=None,584 **kwargs: Unpack[TransformersKwargs],585 ):586 # If this is instantiated as a cross-attention module, the keys587 # and values come from an encoder; the attention mask needs to be588 # such that the encoder's padding tokens are not attended to.589 is_cross_attention = encoder_hidden_states is not None590 591 if is_cross_attention:592 key_layer = self.transpose_for_scores(self.key(encoder_hidden_states))593 value_layer = self.transpose_for_scores(self.value(encoder_hidden_states))594 attention_mask = encoder_attention_mask595 else:596 key_layer = self.transpose_for_scores(self.key(hidden_states))597 value_layer = self.transpose_for_scores(self.value(hidden_states))598 599 mixed_query_layer = self.query(hidden_states)600 601 query_layer = self.transpose_for_scores(mixed_query_layer)602 603 # Take the dot product between "query" and "key" to get the raw attention scores.604 attention_scores = torch.matmul(query_layer, key_layer.transpose(-1, -2))605 606 if self.position_embedding_type == "relative_key" or self.position_embedding_type == "relative_key_query":607 seq_length = hidden_states.size()[1]608 position_ids_l = torch.arange(seq_length, dtype=torch.long, device=hidden_states.device).view(-1, 1)609 position_ids_r = torch.arange(seq_length, dtype=torch.long, device=hidden_states.device).view(1, -1)610 distance = position_ids_l - position_ids_r611 positional_embedding = self.distance_embedding(distance + self.max_position_embeddings - 1)612 positional_embedding = positional_embedding.to(dtype=query_layer.dtype) # fp16 compatibility613 614 if self.position_embedding_type == "relative_key":615 relative_position_scores = torch.einsum("bhld,lrd->bhlr", query_layer, positional_embedding)616 attention_scores = attention_scores + relative_position_scores617 elif self.position_embedding_type == "relative_key_query":618 relative_position_scores_query = torch.einsum("bhld,lrd->bhlr", query_layer, positional_embedding)619 relative_position_scores_key = torch.einsum("bhrd,lrd->bhlr", key_layer, positional_embedding)620 attention_scores = attention_scores + relative_position_scores_query + relative_position_scores_key621 622 attention_scores = attention_scores / math.sqrt(self.attention_head_size)623 624 if attention_mask is not None:625 # Apply the attention mask is (precomputed for all layers in BertModel forward() function)626 attention_scores = attention_scores + attention_mask627 628 # Normalize the attention scores to probabilities.629 attention_probs = nn.Softmax(dim=-1)(attention_scores)630 631 if is_cross_attention and self.save_attention:632 self.save_attention_map(attention_probs)633 attention_probs.register_hook(self.save_attn_gradients)634 635 # This is actually dropping out entire tokens to attend to, which might636 # seem a bit unusual, but is taken from the original Transformer paper.637 attention_probs_dropped = self.dropout(attention_probs)638 639 # Mask heads if we want to640 if head_mask is not None:641 attention_probs_dropped = attention_probs_dropped * head_mask642 643 context_layer = torch.matmul(attention_probs_dropped, value_layer)644 645 context_layer = context_layer.permute(0, 2, 1, 3).contiguous()646 new_context_layer_shape = context_layer.size()[:-2] + (self.all_head_size,)647 context_layer = context_layer.view(*new_context_layer_shape)648 649 return (650 context_layer,651 attention_probs,652 )653 654 655# Copied from transformers.models.bert.modeling_bert.BertSelfOutput with Bert->Blip2QFormer656class Blip2QFormerSelfOutput(nn.Module):657 def __init__(self, config):658 super().__init__()659 self.dense = nn.Linear(config.hidden_size, config.hidden_size)660 self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)661 self.dropout = nn.Dropout(config.hidden_dropout_prob)662 663 def forward(self, hidden_states: torch.Tensor, input_tensor: torch.Tensor) -> torch.Tensor:664 hidden_states = self.dense(hidden_states)665 hidden_states = self.dropout(hidden_states)666 hidden_states = self.LayerNorm(hidden_states + input_tensor)667 return hidden_states668 669 670class Blip2QFormerAttention(nn.Module):671 def __init__(self, config, is_cross_attention=False):672 super().__init__()673 self.attention = Blip2QFormerMultiHeadAttention(config, is_cross_attention)674 self.output = Blip2QFormerSelfOutput(config)675 self.pruned_heads = set()676 677 def prune_heads(self, heads):678 if len(heads) == 0:679 return680 heads, index = find_pruneable_heads_and_indices(681 heads, self.attention.num_attention_heads, self.attention.attention_head_size, self.pruned_heads682 )683 684 # Prune linear layers685 self.attention.query = prune_linear_layer(self.attention.query, index)686 self.attention.key = prune_linear_layer(self.attention.key, index)687 self.attention.value = prune_linear_layer(self.attention.value, index)688 self.output.dense = prune_linear_layer(self.output.dense, index, dim=1)689 690 # Update hyper params and store pruned heads691 self.attention.num_attention_heads = self.attention.num_attention_heads - len(heads)692 self.attention.all_head_size = self.attention.attention_head_size * self.attention.num_attention_heads693 self.pruned_heads = self.pruned_heads.union(heads)694 695 def forward(696 self,697 hidden_states: torch.Tensor,698 attention_mask: Optional[torch.FloatTensor] = None,699 head_mask: Optional[torch.FloatTensor] = None,700 encoder_hidden_states: Optional[torch.FloatTensor] = None,701 encoder_attention_mask: Optional[torch.FloatTensor] = None,702 **kwargs: Unpack[TransformersKwargs],703 ) -> torch.Tensor:704 attn_output, _ = self.attention(705 hidden_states=hidden_states,706 attention_mask=attention_mask,707 head_mask=head_mask,708 encoder_hidden_states=encoder_hidden_states,709 encoder_attention_mask=encoder_attention_mask,710 **kwargs,711 )712 attention_output = self.output(attn_output, hidden_states)713 return attention_output714 715 716# Copied from transformers.models.bert.modeling_bert.BertIntermediate with Bert->Blip2QFormer717class Blip2QFormerIntermediate(nn.Module):718 def __init__(self, config):719 super().__init__()720 self.dense = nn.Linear(config.hidden_size, config.intermediate_size)721 if isinstance(config.hidden_act, str):722 self.intermediate_act_fn = ACT2FN[config.hidden_act]723 else:724 self.intermediate_act_fn = config.hidden_act725 726 def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:727 hidden_states = self.dense(hidden_states)728 hidden_states = self.intermediate_act_fn(hidden_states)729 return hidden_states730 731 732# Copied from transformers.models.bert.modeling_bert.BertOutput with Bert->Blip2QFormer733class Blip2QFormerOutput(nn.Module):734 def __init__(self, config):735 super().__init__()736 self.dense = nn.Linear(config.intermediate_size, config.hidden_size)737 self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)738 self.dropout = nn.Dropout(config.hidden_dropout_prob)739 740 def forward(self, hidden_states: torch.Tensor, input_tensor: torch.Tensor) -> torch.Tensor:741 hidden_states = self.dense(hidden_states)742 hidden_states = self.dropout(hidden_states)743 hidden_states = self.LayerNorm(hidden_states + input_tensor)744 return hidden_states745 746 747class Blip2QFormerLayer(GradientCheckpointingLayer):748 def __init__(self, config, layer_idx):749 super().__init__()750 self.chunk_size_feed_forward = config.chunk_size_feed_forward751 self.seq_len_dim = 1752 self.attention = Blip2QFormerAttention(config)753 754 self.layer_idx = layer_idx755 756 if layer_idx % config.cross_attention_frequency == 0:757 self.crossattention = Blip2QFormerAttention(config, is_cross_attention=True)758 self.has_cross_attention = True759 else:760 self.has_cross_attention = False761 762 if config.use_qformer_text_input:763 self.intermediate = Blip2QFormerIntermediate(config)764 self.output = Blip2QFormerOutput(config)765 766 self.intermediate_query = Blip2QFormerIntermediate(config)767 self.output_query = Blip2QFormerOutput(config)768 769 def forward(770 self,771 hidden_states,772 attention_mask=None,773 head_mask=None,774 encoder_hidden_states=None,775 encoder_attention_mask=None,776 query_length=0,777 **kwargs: Unpack[TransformersKwargs],778 ):779 attention_output = self.attention(780 hidden_states=hidden_states,781 attention_mask=attention_mask,782 head_mask=head_mask,783 **kwargs,784 )785 786 if query_length > 0:787 query_attention_output = attention_output[:, :query_length, :]788 789 if self.has_cross_attention:790 if encoder_hidden_states is None:791 raise ValueError("encoder_hidden_states must be given for cross-attention layers")792 query_attention_output = self.crossattention(793 hidden_states=query_attention_output,794 attention_mask=attention_mask,795 head_mask=head_mask,796 encoder_hidden_states=encoder_hidden_states,797 encoder_attention_mask=encoder_attention_mask,798 **kwargs,799 )800 801 layer_output = apply_chunking_to_forward(802 self.feed_forward_chunk_query,803 self.chunk_size_feed_forward,804 self.seq_len_dim,805 query_attention_output,806 )807 808 if attention_output.shape[1] > query_length:809 layer_output_text = apply_chunking_to_forward(810 self.feed_forward_chunk,811 self.chunk_size_feed_forward,812 self.seq_len_dim,813 attention_output[:, query_length:, :],814 )815 layer_output = torch.cat([layer_output, layer_output_text], dim=1)816 else:817 layer_output = apply_chunking_to_forward(818 self.feed_forward_chunk,819 self.chunk_size_feed_forward,820 self.seq_len_dim,821 attention_output,822 )823 return layer_output824 825 def feed_forward_chunk(self, attention_output):826 intermediate_output = self.intermediate(attention_output)827 layer_output = self.output(intermediate_output, attention_output)828 return layer_output829 830 def feed_forward_chunk_query(self, attention_output):831 intermediate_output = self.intermediate_query(attention_output)832 layer_output = self.output_query(intermediate_output, attention_output)833 return layer_output834 835 836class Blip2QFormerEncoder(nn.Module):837 def __init__(self, config):838 super().__init__()839 self.config = config840 self.layer = nn.ModuleList(841 [Blip2QFormerLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]842 )843 self.gradient_checkpointing = False844 845 @can_return_tuple846 def forward(847 self,848 hidden_states,849 attention_mask=None,850 head_mask=None,851 encoder_hidden_states=None,852 encoder_attention_mask=None,853 query_length=0,854 **kwargs: Unpack[TransformersKwargs],855 ):856 for i in range(self.config.num_hidden_layers):857 layer_module = self.layer[i]858 layer_head_mask = head_mask[i] if head_mask is not None else None859 860 hidden_states = layer_module(861 hidden_states,862 attention_mask,863 layer_head_mask,864 encoder_hidden_states, # as a positional argument for gradient checkpointing865 encoder_attention_mask=encoder_attention_mask,866 query_length=query_length,867 **kwargs,868 )869 870 return BaseModelOutputWithPastAndCrossAttentions(871 last_hidden_state=hidden_states,872 )873 874 875class Blip2TextEmbeddings(nn.Module):876 """Construct the embeddings from word and position embeddings."""877 878 def __init__(self, config):879 super().__init__()880 self.word_embeddings = nn.Embedding(config.vocab_size, config.hidden_size, padding_idx=config.pad_token_id)881 self.position_embeddings = nn.Embedding(config.max_position_embeddings, config.hidden_size)882 883 # position_ids (1, len position emb) is contiguous in memory and exported when serialized884 self.register_buffer(885 "position_ids", torch.arange(config.max_position_embeddings).expand((1, -1)), persistent=False886 )887 self.position_embedding_type = getattr(config, "position_embedding_type", "absolute")888 889 def forward(890 self,891 input_ids: Optional[torch.FloatTensor] = None,892 position_ids: Optional[torch.LongTensor] = None,893 query_embeds: Optional[torch.FloatTensor] = None,894 ) -> torch.Tensor:895 if input_ids is not None:896 seq_length = input_ids.size()[1]897 else:898 seq_length = 0899 900 if position_ids is None:901 position_ids = self.position_ids[:, :seq_length]902 903 if input_ids is not None:904 input_ids = input_ids.to(self.word_embeddings.weight.device)905 embeddings = self.word_embeddings(input_ids)906 if self.position_embedding_type == "absolute":907 position_embeddings = self.position_embeddings(position_ids)908 embeddings += position_embeddings909 910 if query_embeds is not None:911 # `query_embeds` are kept in fp32 when we use it with Qformer912 if query_embeds.dtype != embeddings.dtype:913 query_embeds = query_embeds.to(embeddings.dtype)914 embeddings = torch.cat((query_embeds, embeddings), dim=1)915 else:916 embeddings = query_embeds917 918 return embeddings919 920 921@auto_docstring(922 custom_intro="""923 BLIP-2 Querying Transformer (Q-Former).924 """925)926class Blip2QFormerModel(Blip2PreTrainedModel):927 _supports_attention_backend = False # adds position on attn weights before last matmul928 _supports_flash_attn = False929 _supports_sdpa = False930 _supports_flex_attn = False931 932 _can_record_outputs = {933 "hidden_states": Blip2QFormerLayer,934 "attentions": [935 OutputRecorder(Blip2QFormerMultiHeadAttention, index=1, layer_name=".attention"),936 ],937 "cross_attentions": [938 OutputRecorder(Blip2QFormerMultiHeadAttention, index=1, layer_name=".crossattention"),939 ],940 }941 942 def __init__(self, config: Blip2QFormerConfig):943 super().__init__(config)944 self.config = config945 946 self.layernorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)947 self.dropout = nn.Dropout(config.hidden_dropout_prob)948 949 self.encoder = Blip2QFormerEncoder(config)950 951 self.post_init()952 953 def get_input_embeddings(self):954 return self.embeddings.word_embeddings955 956 def set_input_embeddings(self, value):957 self.embeddings.word_embeddings = value958 959 def _prune_heads(self, heads_to_prune):960 """961 Prunes heads of the model. heads_to_prune: dict of {layer_num: list of heads to prune in this layer} See base962 class PreTrainedModel963 """964 for layer, heads in heads_to_prune.items():965 self.encoder.layer[layer].attention.prune_heads(heads)966 967 def get_extended_attention_mask(968 self,969 attention_mask: torch.Tensor,970 input_shape: tuple[int],971 device: torch.device,972 has_query: bool = False,973 ) -> torch.Tensor:974 """975 Makes broadcastable attention and causal masks so that future and masked tokens are ignored.976 977 Arguments:978 attention_mask (`torch.Tensor`):979 Mask with ones indicating tokens to attend to, zeros for tokens to ignore.980 input_shape (`tuple[int]`):981 The shape of the input to the model.982 device (`torch.device`):983 The device of the input to the model.984 985 Returns:986 `torch.Tensor` The extended attention mask, with a the same dtype as `attention_mask.dtype`.987 """988 # We can provide a self-attention mask of dimensions [batch_size, from_seq_length, to_seq_length]989 # ourselves in which case we just need to make it broadcastable to all heads.990 if attention_mask.dim() == 3:991 extended_attention_mask = attention_mask[:, None, :, :]992 elif attention_mask.dim() == 2:993 # Provided a padding mask of dimensions [batch_size, seq_length]994 # - the model is an encoder, so make the mask broadcastable to [batch_size, num_heads, seq_length, seq_length]995 extended_attention_mask = attention_mask[:, None, None, :]996 else:997 raise ValueError(998 f"Wrong shape for input_ids (shape {input_shape}) or attention_mask (shape {attention_mask.shape})"999 )1000 1001 # Since attention_mask is 1.0 for positions we want to attend and 0.0 for1002 # masked positions, this operation will create a tensor which is 0.0 for1003 # positions we want to attend and -10000.0 for masked positions.1004 # Since we are adding it to the raw scores before the softmax, this is1005 # effectively the same as removing these entirely.1006 extended_attention_mask = extended_attention_mask.to(dtype=self.dtype) # fp16 compatibility1007 extended_attention_mask = (1.0 - extended_attention_mask) * -10000.01008 return extended_attention_mask1009 1010 @check_model_inputs()1011 @auto_docstring1012 def forward(1013 self,1014 query_embeds: torch.FloatTensor,1015 query_length: Optional[int] = None,1016 attention_mask: Optional[torch.FloatTensor] = None,1017 head_mask: Optional[torch.FloatTensor] = None,1018 encoder_hidden_states: Optional[torch.FloatTensor] = None,1019 encoder_attention_mask: Optional[torch.FloatTensor] = None,1020 **kwargs: Unpack[TransformersKwargs],1021 ) -> Union[tuple[torch.Tensor], BaseModelOutputWithPoolingAndCrossAttentions]:1022 r"""1023 query_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`):1024 Hidden states to be used in the attention computation. If cross-attention,1025 will be used for the query (i.e., key and value will use the encoder_hidden_states).1026 query_length (`int`, *optional*):1027 Length of the query, usually based on the number of query tokens.1028 If no value is provided, query_length will be inferred by the query_embeds.1029 """1030 query_length = (1031 query_length if query_length is not None else query_embeds.shape[1] if query_embeds is not None else 01032 )1033 1034 # `Blip2QFormerModel` is kept as fp321035 query_embeds = query_embeds.to(self.layernorm.weight.dtype)1036 embedding_output = self.layernorm(query_embeds)1037 embedding_output = self.dropout(embedding_output)1038 1039 input_shape = embedding_output.size()[:-1]1040 batch_size, seq_length = input_shape1041 device = embedding_output.device1042 1043 if attention_mask is None:1044 attention_mask = torch.ones(((batch_size, seq_length)), device=device)1045 1046 # We can provide a self-attention mask of dimensions [batch_size, from_seq_length, to_seq_length]1047 # ourselves in which case we just need to make it broadcastable to all heads.1048 extended_attention_mask = self.get_extended_attention_mask(attention_mask, input_shape, device)1049 1050 # If a 2D or 3D attention mask is provided for the cross-attention1051 # we need to make broadcastable to [batch_size, num_heads, seq_length, seq_length]1052 if encoder_hidden_states is not None:1053 # Qformer and latent query tokens are kept in fp32. We cast `encoder_hidden_states` if not fp32 already1054 if encoder_hidden_states.dtype != query_embeds.dtype:1055 encoder_hidden_states = encoder_hidden_states.to(query_embeds.dtype)1056 1057 if isinstance(encoder_hidden_states, list):1058 encoder_batch_size, encoder_sequence_length, _ = encoder_hidden_states[0].size()1059 else:1060 encoder_batch_size, encoder_sequence_length, _ = encoder_hidden_states.size()1061 encoder_hidden_shape = (encoder_batch_size, encoder_sequence_length)1062 1063 if isinstance(encoder_attention_mask, list):1064 encoder_extended_attention_mask = [self.invert_attention_mask(mask) for mask in encoder_attention_mask]1065 elif encoder_attention_mask is None:1066 encoder_attention_mask = torch.ones(encoder_hidden_shape, device=device)1067 encoder_extended_attention_mask = self.invert_attention_mask(encoder_attention_mask)1068 else:1069 encoder_extended_attention_mask = self.invert_attention_mask(encoder_attention_mask)1070 else:1071 encoder_extended_attention_mask = None1072 1073 # Prepare head mask if needed1074 # 1.0 in head_mask indicate we keep the head1075 # attention_probs has shape bsz x n_heads x N x N1076 # input head_mask has shape [num_heads] or [num_hidden_layers x num_heads]1077 # and head_mask is converted to shape [num_hidden_layers x batch x num_heads x seq_length x seq_length]1078 head_mask = self.get_head_mask(head_mask, self.config.num_hidden_layers)1079 1080 encoder_outputs: BaseModelOutput = self.encoder(1081 embedding_output,1082 attention_mask=extended_attention_mask,1083 head_mask=head_mask,1084 encoder_hidden_states=encoder_hidden_states,1085 encoder_attention_mask=encoder_extended_attention_mask,1086 query_length=query_length,1087 **kwargs,1088 )1089 sequence_output = encoder_outputs.last_hidden_state1090 pooled_output = sequence_output[:, 0, :]1091 1092 return BaseModelOutputWithPoolingAndCrossAttentions(1093 last_hidden_state=sequence_output,1094 pooler_output=pooled_output,1095 )1096 1097 1098@auto_docstring(1099 custom_intro="""1100 BLIP-2 Model for generating text and image features. The model consists of a vision encoder, Querying Transformer1101 (Q-Former) and a language model.1102 """1103)1104class Blip2Model(Blip2PreTrainedModel):1105 config: Blip2Config1106 main_input_name = "pixel_values"1107 _keep_in_fp32_modules = ["query_tokens", "qformer"]1108 _supports_flash_attn = False # because self.qformer does not support FA21109 1110 def __init__(self, config: Blip2Config):1111 super().__init__(config)1112 1113 self.vision_model = Blip2VisionModel._from_config(config.vision_config)1114 1115 self.query_tokens = nn.Parameter(torch.zeros(1, config.num_query_tokens, config.qformer_config.hidden_size))1116 self.qformer = Blip2QFormerModel._from_config(config.qformer_config)1117 1118 self.language_projection = nn.Linear(config.qformer_config.hidden_size, config.text_config.hidden_size)1119 if config.use_decoder_only_language_model:1120 language_model = AutoModelForCausalLM.from_config(config.text_config)1121 else:1122 language_model = AutoModelForSeq2SeqLM.from_config(config.text_config)1123 1124 # Update _tied_weights_keys using the base model used.1125 if language_model._tied_weights_keys is not None:1126 self._tied_weights_keys = [f"language_model.{k}" for k in language_model._tied_weights_keys]1127 1128 self.language_model = language_model1129 1130 # Initialize weights and apply final processing1131 self.post_init()1132 1133 def get_input_embeddings(self):1134 return self.language_model.get_input_embeddings()1135 1136 def set_input_embeddings(self, value):1137 self.language_model.set_input_embeddings(value)1138 1139 def set_output_embeddings(self, new_embeddings):1140 self.language_model.set_output_embeddings(new_embeddings)1141 1142 def get_output_embeddings(self) -> nn.Module:1143 return self.language_model.get_output_embeddings()1144 1145 def get_encoder(self):1146 return self.language_model.get_encoder()1147 1148 def get_decoder(self):1149 return self.language_model.get_decoder()1150 1151 def _tie_weights(self):1152 if not self.config.use_decoder_only_language_model:1153 self.language_model.encoder.embed_tokens = self.language_model.shared1154 self.language_model.decoder.embed_tokens = self.language_model.shared1155 1156 @filter_out_non_signature_kwargs()1157 @auto_docstring1158 def get_text_features(1159 self,1160 input_ids: torch.Tensor,1161 attention_mask: Optional[torch.Tensor] = None,1162 decoder_input_ids: Optional[torch.Tensor] = None,1163 decoder_attention_mask: Optional[torch.Tensor] = None,1164 labels: Optional[torch.Tensor] = None,1165 legacy_output: bool = True,1166 ) -> Union[torch.FloatTensor, CausalLMOutputWithPast]:1167 r"""1168 decoder_input_ids (`torch.LongTensor` of shape `(batch_size, target_sequence_length)`, *optional*):1169 Indices of decoder input sequence tokens in the vocabulary.1170 1171 Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and1172 [`PreTrainedTokenizer.__call__`] for details.1173 1174 [What are decoder input IDs?](../glossary#decoder-input-ids)1175 1176 T5 uses the `pad_token_id` as the starting token for `decoder_input_ids` generation. If `past_key_values`1177 is used, optionally only the last `decoder_input_ids` have to be input (see `past_key_values`).1178 1179 To know more on how to prepare `decoder_input_ids` for pretraining take a look at [T51180 Training](./t5#training).1181 decoder_attention_mask (`torch.BoolTensor` of shape `(batch_size, target_sequence_length)`, *optional*):1182 Default behavior: generate a tensor that ignores pad tokens in `decoder_input_ids`. Causal mask will also1183 be used by default.1184 legacy_output (`bool`, *optional*, defaults to `True`):1185 Whether to return a model output object or a tensor of features.1186 1187 Returns:1188 text_outputs (`CausalLMOutputWithPast` or `torch.FloatTensor`):1189 The language model outputs. If `legacy_output=False`, the output is a `torch.FloatTensor`.1190 1191 Examples:1192 ```python1193 >>> import torch1194 >>> from transformers import AutoTokenizer, Blip2Model1195 1196 >>> model = Blip2Model.from_pretrained("Salesforce/blip2-opt-2.7b")1197 >>> tokenizer = AutoTokenizer.from_pretrained("Salesforce/blip2-opt-2.7b")1198 1199 >>> inputs = tokenizer(["a photo of a cat"], padding=True, return_tensors="pt")1200 >>> with torch.inference_mode():