Ë
    S^(hi ã                   óè  — d Z ddlZddlmZ ddlmZmZmZmZ ddl	Z	ddl
Z	ddl	mZ ddlmZ ddlmZ dd	lmZ dd
lmZmZ ddlmZ ddlmZmZmZmZmZmZ ddlmZm Z m!Z! ddl"m#Z#m$Z$  ejJ                  e&«      Z'dZ(de	jR                  de	jR                  fd„Z*de	jR                  de	jR                  fd„Z+e G d„ de«      «       Z,e G d„ de«      «       Z-e G d„ de«      «       Z.e G d„ de«      «       Z/ G d„ dej`                  «      Z1 G d „ d!ej`                  «      Z2 G d"„ d#ej`                  «      Z3 G d$„ d%ej`                  «      Z4 G d&„ d'ej`                  «      Z5 G d(„ d)e«      Z6d*Z7d+Z8d,Z9d-Z: G d.„ d/ej`                  «      Z; G d0„ d1e6«      Z< ed2e7«       G d3„ d4e6«      «       Z= ed5e7«       G d6„ d7e6e«      «       Z> ed8e7«       G d9„ d:e6e«      «       Z? ed;e7«       G d<„ d=e6«      «       Z@g d>¢ZAy)?zPyTorch BLIP model.é    N)Ú	dataclass)ÚAnyÚOptionalÚTupleÚUnion)Únn)Ú	normalizeé   )ÚACT2FN)ÚGenerationMixin)ÚBaseModelOutputÚBaseModelOutputWithPooling)ÚPreTrainedModel)ÚModelOutputÚadd_start_docstringsÚ%add_start_docstrings_to_model_forwardÚloggingÚreplace_return_docstringsÚ	torch_inté   )Ú
BlipConfigÚBlipTextConfigÚBlipVisionConfig)ÚBlipTextLMHeadModelÚBlipTextModelzSalesforce/blip-vqa-baseÚlogitsÚreturnc                 ó’   — t         j                  j                  | t        j                  t        | «      | j                  ¬«      «      S )N©Údevice)r   Ú
functionalÚcross_entropyÚtorchÚarangeÚlenr    )r   s    úd/var/www/skyplay_api_hub/venv/lib/python3.12/site-packages/transformers/models/blip/modeling_blip.pyÚcontrastive_lossr'   0   s/   € Ü�=‰=×&Ñ& v¬u¯|©|¼CÀ»KÐPV×P]ÑP]Ô/^Ó_Ð_ó    Ú
similarityc                 óZ   — t        | «      }t        | j                  «       «      }||z   dz  S )Ng       @)r'   Út)r)   Úcaption_lossÚ
image_losss      r&   Ú	blip_lossr.   5   s,   € Ü# JÓ/€LÜ! *§,¡,£.Ó1€JØ˜:Ñ%¨Ñ,Ð,r(   c                   ó2  — e Zd ZU dZdZeeej                        e	d<   dZ
eeej                        e	d<   dZeej                     e	d<   dZeej                     e	d<   dZeeej                  df      e	d<   dZeeej                  df      e	d	<   ed
„ «       Zy)Ú'BlipForConditionalGenerationModelOutputa  
    Adapted from the base class for vision model's outputs that also contains image embeddings of the pooling of the
    last hidden states. This class also adds the loss term from the text decoder.

    Args:
        loss (`torch.FloatTensor`, *optional*, returned when `labels` is provided, `torch.FloatTensor` of shape `(1,)`):
            Languge modeling loss from the text decoder.
        logits (`torch.FloatTensor` of shape `(batch_size, sequence_length, config.vocab_size)`, *optional*):
            Prediction scores of the language modeling head of the text decoder model.
        image_embeds (`torch.FloatTensor` of shape `(batch_size, output_dim)`, *optional*):
            The image embeddings obtained after applying the Vision Transformer model to the input image.
        last_hidden_state (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
            Sequence of hidden-states at the output of the last layer of the model.
        hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True`):
            Tuple of `torch.FloatTensor` (one for the output of the embeddings, if the model has an embedding layer, +
            one for the output of each layer) of shape `(batch_size, sequence_length, hidden_size)`.

            Hidden-states of the model at the output of each layer plus the optional initial embedding outputs.
        attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed):
            Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
            sequence_length)`.

            Attentions weights after the attention softmax, used to compute the weighted average in the self-attention
            heads.
    NÚlossr   Úimage_embedsÚlast_hidden_state.Úhidden_statesÚ
attentionsc                 óN   — t        j                  dt        «       | j                  S )Nz¢`decoder_logits` attribute is deprecated and will be removed in version 5 of Transformers. Please use the `logits` attribute to retrieve the final output instead.)ÚwarningsÚwarnÚFutureWarningr   ©Úselfs    r&   Údecoder_logitsz6BlipForConditionalGenerationModelOutput.decoder_logits^   s#   € ä�‰ðWäô	
ð
 �{‰{Ðr(   )Ú__name__Ú
__module__Ú__qualname__Ú__doc__r1   r   r   r#   ÚFloatTensorÚ__annotations__r   r2   r3   r4   r5   Úpropertyr<   © r(   r&   r0   r0   ;   s¸   … ñð4 04€Dˆ(�5˜×*Ñ*Ñ+Ñ
,Ó3Ø15€FˆH�U˜5×,Ñ,Ñ-Ñ.Ó5Ø04€L�(˜5×,Ñ,Ñ-Ó4Ø59Ð�x × 1Ñ 1Ñ2Ó9Ø=A€M�8˜E %×"3Ñ"3°SÐ"8Ñ9Ñ:ÓAØ:>€J�˜˜u×0Ñ0°#Ð5Ñ6Ñ7Ó>àñó ñr(   r0   c                   óî   — e Zd ZU dZdZeej                     ed<   dZ	eej                     ed<   dZ
eej                     ed<   dZeeej                  df      ed<   dZeeej                  df      ed<   y)	ÚBlipTextVisionModelOutputaÉ  
    Adapted from the base class for vision model's outputs that also contains image embeddings of the pooling of the
    last hidden states. This class also adds the loss term from the text decoder.

    Args:
        loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `labels` is provided):
            Languge modeling loss from the text decoder.
        image_embeds (`torch.FloatTensor` of shape `(batch_size, output_dim)` *optional* returned when model is initialized with `with_projection=True`):
            The image embeddings obtained by applying the projection layer to the pooler_output.
        last_hidden_state (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`):
            Sequence of hidden-states at the output of the last layer of the model.
        hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
            Tuple of `torch.FloatTensor` (one for the output of the embeddings, if the model has an embedding layer, +
            one for the output of each layer) of shape `(batch_size, sequence_length, hidden_size)`.

            Hidden-states of the model at the output of each layer plus the optional initial embedding outputs.
        attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
            Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
            sequence_length)`.

            Attentions weights after the attention softmax, used to compute the weighted average in the self-attention
            heads.
    Nr1   r2   r3   .r4   r5   )r=   r>   r?   r@   r1   r   r#   rA   rB   r2   r3   r4   r   r5   rD   r(   r&   rF   rF   h   s‡   … ñð0 )-€Dˆ(�5×$Ñ$Ñ
%Ó,Ø04€L�(˜5×,Ñ,Ñ-Ó4Ø59Ð�x × 1Ñ 1Ñ2Ó9Ø=A€M�8˜E %×"3Ñ"3°SÐ"8Ñ9Ñ:ÓAØ:>€J�˜˜u×0Ñ0°#Ð5Ñ6Ñ7Ô>r(   rF   c                   ól  — e Zd ZU dZdZeej                     ed<   dZ	eej                     ed<   dZ
eej                     ed<   dZeej                     ed<   dZeeej                  df      ed<   dZeej                     ed	<   dZeeej                  df      ed
<   dZeeej                        ed<   y)Ú BlipImageTextMatchingModelOutputa‰  
    Adapted from the base class for vision model's outputs that also contains image embeddings of the pooling of the
    last hidden states. This class also adds the loss term from the text decoder as well as the image-text similarity
    scores.

    Args:
        itm_score (`torch.FloatTensor`):
            The image-text similarity scores.
        loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `labels` is provided):
            Languge modeling loss from the text decoder.
        image_embeds (`torch.FloatTensor` of shape `(batch_size, output_dim)` *optional* returned when model is initialized with `with_projection=True`):
            The image embeddings obtained by applying the projection layer to the pooler_output.
        last_hidden_state (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`):
            Sequence of hidden-states at the output of the last layer of the model.
        hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
            Tuple of `torch.FloatTensor` (one for the output of the embeddings, if the model has an embedding layer, +
            one for the output of each layer) of shape `(batch_size, sequence_length, hidden_size)`.

            Hidden-states of the model at the output of each layer plus the optional initial embedding outputs.
        vision_pooler_output (`torch.FloatTensor` of shape `(batch_size, hidden_size)`, *optional*):
            Last layer hidden-state of the vision of the vision-only branch of the model.
        attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
            Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
            sequence_length)`.

            Attentions weights after the attention softmax, used to compute the weighted average in the self-attention
            heads.
        question_embeds (`torch.FloatTensor`):
            The question embeddings obtained by the text projection layer.
    NÚ	itm_scorer1   r2   r3   .r4   Úvision_pooler_outputr5   Úquestion_embeds)r=   r>   r?   r@   rI   r   r#   rA   rB   r1   r2   r3   r4   r   rJ   r5   rK   rD   r(   r&   rH   rH   ‰   sÌ   … ñð> .2€Iˆx˜×)Ñ)Ñ*Ó1Ø(,€Dˆ(�5×$Ñ$Ñ
%Ó,Ø04€L�(˜5×,Ñ,Ñ-Ó4Ø59Ð�x × 1Ñ 1Ñ2Ó9Ø=A€M�8˜E %×"3Ñ"3°SÐ"8Ñ9Ñ:ÓAØ8<Ð˜( 5×#4Ñ#4Ñ5Ó<Ø:>€J�˜˜u×0Ñ0°#Ð5Ñ6Ñ7Ó>Ø:>€O�X˜e E×$5Ñ$5Ñ6Ñ7Ô>r(   rH   c                   ó  — e Zd ZU dZdZeej                     ed<   dZ	eej                     ed<   dZ
eej                     ed<   dZeej                     ed<   dZeej                     ed<   dZeed<   dZeed	<   d
ee   fd„Zy)Ú
BlipOutputaï  
    Args:
        loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `return_loss` is `True`):
            Contrastive loss for image-text similarity.
        logits_per_image:(`torch.FloatTensor` of shape `(image_batch_size, text_batch_size)`):
            The scaled dot product scores between `image_embeds` and `text_embeds`. This represents the image-text
            similarity scores.
        logits_per_text:(`torch.FloatTensor` of shape `(text_batch_size, image_batch_size)`):
            The scaled dot product scores between `text_embeds` and `image_embeds`. This represents the text-image
            similarity scores.
        text_embeds(`torch.FloatTensor` of shape `(batch_size, output_dim`):
            The text embeddings obtained by applying the projection layer to the pooled output of [`BlipTextModel`].
        image_embeds(`torch.FloatTensor` of shape `(batch_size, output_dim`):
            The image embeddings obtained by applying the projection layer to the pooled output of [`BlipVisionModel`].
        text_model_output(`BaseModelOutputWithPooling`):
            The output of the [`BlipTextModel`].
        vision_model_output(`BaseModelOutputWithPooling`):
            The output of the [`BlipVisionModel`].
    Nr1   Úlogits_per_imageÚlogits_per_textÚtext_embedsr2   Útext_model_outputÚvision_model_outputr   c                 óH   ‡ — t        ˆ fd„‰ j                  «       D «       «      S )Nc              3   ód   •K  — | ]'  }|d vr‰|   nt        ‰|«      j                  «       –— Œ) y­w))rQ   rR   N)ÚgetattrÚto_tuple)Ú.0Úkr;   s     €r&   ú	<genexpr>z&BlipOutput.to_tuple.<locals>.<genexpr>Ó   s=   øè ø€ ò 
àð Ð LÑLˆD�ŠGÔRYÐZ^Ð`aÓRb×RkÑRkÓRmÓmñ
ùs   ƒ-0)ÚtupleÚkeysr:   s   `r&   rV   zBlipOutput.to_tupleÒ   s#   ø€ Üó 
à—Y‘Y“[ô
ó 
ð 	
r(   )r=   r>   r?   r@   r1   r   r#   rA   rB   rN   rO   rP   r2   rQ   r   rR   r   r   rV   rD   r(   r&   rM   rM   ´   s›   … ñð( )-€Dˆ(�5×$Ñ$Ñ
%Ó,Ø48Ð�h˜u×0Ñ0Ñ1Ó8Ø37€O�X˜e×/Ñ/Ñ0Ó7Ø/3€K�˜%×+Ñ+Ñ,Ó3Ø04€L�(˜5×,Ñ,Ñ-Ó4Ø48ÐÐ1Ó8Ø6:ÐÐ3Ó:ð
˜% ™*ô 
r(   rM   c                   ó¢   ‡ — e Zd Zdefˆ fd„Zdej                  dededej                  fd„Zddej                  d	e
dej                  fd
„Zˆ xZS )ÚBlipVisionEmbeddingsÚconfigc                 óp  •— t         ‰| �  «        || _        |j                  | _        |j
                  | _        |j                  | _        t        j                  t        j                  dd| j                  «      «      | _        t        j                  d| j                  | j                  | j                  ¬«      | _        | j
                  | j                  z  dz  | _        | j                  dz   | _        t        j                  t        j                  d| j                  | j                  «      «      | _        y )Nr   r
   )Úin_channelsÚout_channelsÚkernel_sizeÚstrideé   )ÚsuperÚ__init__r^   Úhidden_sizeÚ	embed_dimÚ
image_sizeÚ
patch_sizer   Ú	Parameterr#   ÚrandnÚclass_embeddingÚConv2dÚpatch_embeddingÚnum_patchesÚnum_positionsÚposition_embedding©r;   r^   Ú	__class__s     €r&   rf   zBlipVisionEmbeddings.__init__Ú   sá   ø€ Ü‰ÑÔØˆŒØ×+Ñ+ˆŒØ ×+Ñ+ˆŒØ ×+Ñ+ˆŒä!Ÿ|™|¬E¯K©K¸¸1¸d¿n¹nÓ,MÓNˆÔä!Ÿy™yØ¨¯©ÀDÇOÁOÐ\`×\kÑ\kô 
ˆÔð !ŸO™O¨t¯©Ñ>À1ÑDˆÔØ!×-Ñ-°Ñ1ˆÔä"$§,¡,¬u¯{©{¸1¸d×>PÑ>PÐRV×R`ÑR`Ó/aÓ"bˆÕr(   Ú
embeddingsÚheightÚwidthr   c                 ó¦  — |j                   d   dz
  }| j                  j                   d   dz
  }t        j                  j	                  «       s||k(  r||k(  r| j                  S | j                  dd…dd…f   }| j                  dd…dd…f   }|j                   d   }|| j
                  z  }	|| j
                  z  }
t        |dz  «      }|j                  d|||«      }|j                  dddd«      }t        j                  j                  ||	|
fdd	¬
«      }|j                  dddd«      j                  dd|«      }t        j                  ||fd¬«      S )a   
        This method allows to interpolate the pre-trained position encodings, to be able to use the model on higher resolution
        images. This method is also adapted to support torch.jit tracing.

        Adapted from:
        - https://github.com/facebookresearch/dino/blob/de9ee3df6cf39fac952ab558447af1fa1365362a/vision_transformer.py#L174-L194, and
        - https://github.com/facebookresearch/dinov2/blob/e1277af2ba9496fbadf7aec6eba56e8d882d1e35/dinov2/models/vision_transformer.py#L179-L211
        r   Néÿÿÿÿg      à?r   r
   rd   ÚbicubicF)ÚsizeÚmodeÚalign_corners©Údim)Úshaperr   r#   ÚjitÚ
is_tracingrj   r   ÚreshapeÚpermuter   r!   ÚinterpolateÚviewÚcat)r;   ru   rv   rw   rp   rq   Úclass_pos_embedÚpatch_pos_embedr   Ú
new_heightÚ	new_widthÚsqrt_num_positionss               r&   Úinterpolate_pos_encodingz-BlipVisionEmbeddings.interpolate_pos_encodingì   s`  € ð !×&Ñ& qÑ)¨AÑ-ˆØ×/Ñ/×5Ñ5°aÑ8¸1Ñ<ˆô �y‰y×#Ñ#Ô%¨+¸Ò*FÈ6ÐUZÊ?Ø×*Ñ*Ð*à×1Ñ1²!°R°a°R°%Ñ8ˆØ×1Ñ1²!°Q±R°%Ñ8ˆà×Ñ˜rÑ"ˆà˜tŸ™Ñ.ˆ
Ø˜TŸ_™_Ñ,ˆ	ä& }°cÑ'9Ó:ÐØ)×1Ñ1°!Ð5GÐI[Ð]`ÓaˆØ)×1Ñ1°!°Q¸¸1Ó=ˆäŸ-™-×3Ñ3ØØ˜iÐ(ØØð	 4ó 
ˆð *×1Ñ1°!°Q¸¸1Ó=×BÑBÀ1ÀbÈ#ÓNˆä�y‰y˜/¨?Ð;ÀÔCÐCr(   Úpixel_valuesr�   c                 ó  — |j                   \  }}}}| j                  j                  j                  }| j                  |j	                  |¬«      «      }|j                  d«      j                  dd«      }| j                  j                  |dd«      j	                  |«      }	t        j                  |	|gd¬«      }
|r| j                  |
||«      }n| j                  }|
|d d …d |
j                  d«      …d d …f   j	                  |«      z   }
|
S )N©Údtyperd   r   ry   r~   )r€   ro   Úweightr‘   ÚtoÚflattenÚ	transposerm   Úexpandr#   r‡   r�   rr   r{   )r;   rŽ   r�   Ú
batch_sizeÚ_rv   rw   Útarget_dtypeÚpatch_embedsÚclass_embedsru   rr   s               r&   ÚforwardzBlipVisionEmbeddings.forward  sü   € Ø'3×'9Ñ'9Ñ$ˆ
�A�v˜uØ×+Ñ+×2Ñ2×8Ñ8ˆØ×+Ñ+¨L¯O©OÀ,¨OÓ,OÓPˆØ#×+Ñ+¨AÓ.×8Ñ8¸¸AÓ>ˆØ×+Ñ+×2Ñ2°:¸qÀ"ÓE×HÑHÈÓVˆÜ—Y‘Y ¨lÐ;ÀÔCˆ
Ù#Ø!%×!>Ñ!>¸zÈ6ÐSXÓ!YÑà!%×!8Ñ!8ÐØÐ"4²QÐ8L¸*¿/¹/È!Ó:LÐ8LÊaÐ5OÑ"P×"SÑ"SÐT`Ó"aÑaˆ
ØÐr(   ©F)r=   r>   r?   r   rf   r#   ÚTensorÚintr�   rA   Úboolrœ   Ú__classcell__©rt   s   @r&   r]   r]   Ù   sm   ø„ ðcÐ/õ cð$&D°5·<±<ð &DÈð &DÐUXð &DÐ]b×]iÑ]ió &DñP E×$5Ñ$5ð ÐQUð Ðbg×bnÑbn÷ r(   r]   c            	       ó¦   ‡ — e Zd Zdefˆ fd„Z	 	 	 ddeej                     deej                     deej                     dej                  fd„Z
ˆ xZS )	ÚBlipTextEmbeddingsr^   c                 óN  •— t         ‰| �  «        |j                  }t        j                  |j
                  |«      | _        t        j                  |j                  |«      | _        | j                  dt        j                  |j                  «      j                  d«      d¬«       y )NÚposition_ids)r   ry   F)Ú
persistent)re   rf   rg   r   Ú	EmbeddingÚ
vocab_sizeÚtoken_embeddingÚmax_position_embeddingsrr   Úregister_bufferr#   r$   r–   ©r;   r^   rh   rt   s      €r&   rf   zBlipTextEmbeddings.__init__%  sƒ   ø€ Ü‰ÑÔØ×&Ñ&ˆ	ä!Ÿ|™|¨F×,=Ñ,=¸yÓIˆÔÜ"$§,¡,¨v×/MÑ/MÈyÓ"YˆÔð 	×ÑØœEŸL™L¨×)GÑ)GÓH×OÑOÐPWÓXÐejð 	õ 	
r(   Ú	input_idsr¦   Úinputs_embedsr   c                 ó8  — |�|j                   d   n|j                   d   }| j                  j                  j                   d   }||kD  rt        d|› d|› �«      ‚|€| j                  d d …d |…f   }|€| j                  |«      }| j                  |«      }||z   }|S )Nry   éþÿÿÿr   zRSequence length must be less than max_position_embeddings (got `sequence length`: z and max_position_embeddings: )r€   rr   r’   Ú
ValueErrorr¦   rª   )r;   r®   r¦   r¯   Ú
seq_lengthÚmax_position_embeddingÚposition_embeddingsru   s           r&   rœ   zBlipTextEmbeddings.forward1  sÇ   € ð -6Ð,A�Y—_‘_ RÒ(À}×GZÑGZÐ[]ÑG^ˆ
Ø!%×!8Ñ!8×!?Ñ!?×!EÑ!EÀaÑ!HÐàÐ.Ò.ÜØdØ�,Ð<Ð=SÐ<TðVóð ð
 ÐØ×,Ñ,ªQ°°°¨^Ñ<ˆLàÐ Ø ×0Ñ0°Ó;ˆMà"×5Ñ5°lÓCÐØ"Ð%8Ñ8ˆ
àÐr(   )NNN)r=   r>   r?   r   rf   r   r#   Ú
LongTensorrA   rž   rœ   r¡   r¢   s   @r&   r¤   r¤   $  sj   ø„ ð

˜~õ 

ð 15Ø37Ø59ñ	à˜E×,Ñ,Ñ-ðð ˜u×/Ñ/Ñ0ðð   × 1Ñ 1Ñ2ð	ð
 
�‰÷r(   r¤   c                   óö   ‡ — e Zd ZdZˆ fd„Zdej                  dedefd„Z	 	 ddej                  de	ej                     d	e	e
   d
eej                  e	ej                     e	eej                        f   fd„Zˆ xZS )ÚBlipAttentionz=Multi-headed attention from 'Attention Is All You Need' paperc                 óz  •— t         ‰| �  «        || _        |j                  | _        |j
                  | _        | j                  | j                  z  | _        | j                  | j                  z  | j                  k7  r&t        d| j                  › d| j                  › d�«      ‚| j                  dz  | _	        t        j                  |j                  «      | _        t        j                  | j                  d| j                  z  «      | _        t        j                  | j                  | j                  «      | _        y )Nz;embed_dim must be divisible by num_heads (got `embed_dim`: z and `num_heads`: z).g      à¿r
   )re   rf   r^   rg   rh   Únum_attention_headsÚ	num_headsÚhead_dimr²   Úscaler   ÚDropoutÚattention_dropoutÚdropoutÚLinearÚqkvÚ
projectionrs   s     €r&   rf   zBlipAttention.__init__O  sí   ø€ Ü‰ÑÔØˆŒØ×+Ñ+ˆŒØ×3Ñ3ˆŒØŸ™¨$¯.©.Ñ8ˆŒØ�=‰=˜4Ÿ>™>Ñ)¨T¯^©^Ò;ÜØMÈdÏnÉnÐM]ð ^Ø—N‘NÐ# 2ð'óð ð —]‘] DÑ(ˆŒ
Ü—z‘z &×":Ñ":Ó;ˆŒä—9‘9˜TŸ^™^¨Q°·±Ñ-?Ó@ˆŒäŸ)™) D§N¡N°D·N±NÓCˆ�r(   ÚtensorÚseq_lenÚbszc                 óŽ   — |j                  ||| j                  | j                  «      j                  dd«      j	                  «       S )Nr   rd   )r†   r»   r¼   r•   Ú
contiguous)r;   rÄ   rÅ   rÆ   s       r&   Ú_shapezBlipAttention._shapea  s7   € Ø�{‰{˜3 ¨¯©¸¿¹ÓG×QÑQÐRSÐUVÓW×bÑbÓdÐdr(   r4   Ú	head_maskÚoutput_attentionsr   c                 ó²  — |j                  «       \  }}}| j                  |«      j                  ||d| j                  || j                  z  «      j	                  ddddd«      }|d   |d   |d   }
}	}t        j                  ||	j                  dd«      «      }|| j                  z  }t        j                  j                  |d¬«      }| j                  |«      }|�||z  }t        j                  ||
«      j	                  dddd«      }|j                  «       d	d | j                  fz   }|j                  |«      }| j                  |«      }|r||f}|S |d	f}|S )
z#Input shape: Batch x Time x Channelr
   rd   r   r   é   ry   r±   r~   N)r{   rÂ   rƒ   r»   r„   r#   Úmatmulr•   r½   r   r!   ÚsoftmaxrÀ   rh   rÃ   )r;   r4   rÊ   rË   rÆ   Útgt_lenrh   Ú	mixed_qkvÚquery_statesÚ
key_statesÚvalue_statesÚattention_scoresÚattention_probsÚcontext_layerÚnew_context_layer_shapeÚoutputÚoutputss                    r&   rœ   zBlipAttention.forwardd  sm  € ð #0×"4Ñ"4Ó"6ÑˆˆW�ið �H‰H�]Ó#ß‰W�S˜' 1 d§n¡n°iÀ4Ç>Á>Ñ6QÓRß‰W�Q˜˜1˜a Ó#ð 	ð
 2;¸1±¸yÈ¹|ÈYÐWXÉ\ ,�jˆô !Ÿ<™<¨°j×6JÑ6JÈ2ÈrÓ6RÓSÐà+¨d¯j©jÑ8Ðô Ÿ-™-×/Ñ/Ð0@ÀbÐ/ÓIˆð Ÿ,™, Ó7ˆð Ð Ø-°	Ñ9ˆOäŸ™ _°lÓC×KÑKÈAÈqÐRSÐUVÓWˆà"/×"4Ñ"4Ó"6°s¸Ð";¸t¿~¹~Ð>OÑ"OÐØ%×-Ñ-Ð.EÓFˆà—‘ Ó/ˆá/@�6˜?Ð+ˆàˆð HNÈtÀnˆàˆr(   ©NF)r=   r>   r?   r@   rf   r#   rž   rŸ   rÉ   r   r    r   rœ   r¡   r¢   s   @r&   r¸   r¸   L  s™   ø„ ÙGôDð$e˜UŸ\™\ð e°Cð e¸có eð -1Ø,1ñ	*à—|‘|ð*ð ˜EŸL™LÑ)ð*ð $ D™>ð	*ð
 
ˆu�|‰|˜X e§l¡lÑ3°X¸eÀEÇLÁLÑ>QÑ5RÐRÑ	S÷*r(   r¸   c                   óV   ‡ — e Zd Zˆ fd„Zdej
                  dej
                  fd„Zˆ xZS )ÚBlipMLPc                 ó  •— t         ‰| �  «        || _        t        |j                     | _        t        j                  |j                  |j                  «      | _
        t        j                  |j                  |j                  «      | _        y ©N)re   rf   r^   r   Ú
hidden_actÚactivation_fnr   rÁ   rg   Úintermediate_sizeÚfc1Úfc2rs   s     €r&   rf   zBlipMLP.__init__“  sd   ø€ Ü‰ÑÔØˆŒÜ# F×$5Ñ$5Ñ6ˆÔÜ—9‘9˜V×/Ñ/°×1IÑ1IÓJˆŒÜ—9‘9˜V×5Ñ5°v×7IÑ7IÓJˆ�r(   r4   r   c                 ól   — | j                  |«      }| j                  |«      }| j                  |«      }|S rß   )rã   rá   rä   )r;   r4   s     r&   rœ   zBlipMLP.forwardš  s4   € ØŸ™ Ó/ˆØ×*Ñ*¨=Ó9ˆØŸ™ Ó/ˆØÐr(   )r=   r>   r?   rf   r#   rž   rœ   r¡   r¢   s   @r&   rÝ   rÝ   ’  s$   ø„ ôKð U§\¡\ð °e·l±l÷ r(   rÝ   c            
       óˆ   ‡ — e Zd Zdefˆ fd„Z	 ddej                  dej                  dee   de	ej                     fd„Zˆ xZS )	ÚBlipEncoderLayerr^   c                 óD  •— t         ‰| �  «        |j                  | _        t	        |«      | _        t        j                  | j                  |j                  ¬«      | _	        t        |«      | _        t        j                  | j                  |j                  ¬«      | _        y ©N)Úeps)re   rf   rg   rh   r¸   Ú	self_attnr   Ú	LayerNormÚlayer_norm_epsÚlayer_norm1rÝ   ÚmlpÚlayer_norm2rs   s     €r&   rf   zBlipEncoderLayer.__init__¢  sl   ø€ Ü‰ÑÔØ×+Ñ+ˆŒÜ& vÓ.ˆŒÜŸ<™<¨¯©¸F×<QÑ<QÔRˆÔÜ˜6“?ˆŒÜŸ<™<¨¯©¸F×<QÑ<QÔRˆÕr(   r4   Úattention_maskrË   r   c                 óÌ   — |}| j                  |«      }| j                  |||¬«      \  }}||z   }|}| j                  |«      }| j                  |«      }||z   }|f}|r||fz  }|S )aI  
        Args:
            hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
            attention_mask (`torch.FloatTensor`): attention mask of size
                `(batch, 1, tgt_len, src_len)` where padding elements are indicated by very large negative values.
                `(config.encoder_attention_heads,)`.
            output_attentions (`bool`, *optional*):
                Whether or not to return the attentions tensors of all attention layers. See `attentions` under
                returned tensors for more detail.
        )r4   rÊ   rË   )rî   rë   rð   rï   )r;   r4   rñ   rË   ÚresidualÚattn_weightsrÚ   s          r&   rœ   zBlipEncoderLayer.forwardª  s�   € ð  !ˆà×(Ñ(¨Ó7ˆØ&*§n¡nØ'Ø$Ø/ð '5ó '
Ñ#ˆ�|ð
 &¨Ñ0ˆØ ˆØ×(Ñ(¨Ó7ˆØŸ™ Ó/ˆà%¨Ñ0ˆà Ð"ˆáØ˜�Ñ&ˆGàˆr(   r�   )r=   r>   r?   r   rf   r#   rž   r   r    r   rA   rœ   r¡   r¢   s   @r&   rç   rç   ¡  sX   ø„ ðS˜zõ Sð -2ñ	$à—|‘|ð$ð Ÿ™ð$ð $ D™>ð	$ð
 
ˆu× Ñ Ñ	!÷$r(   rç   c                   ó0   — e Zd ZdZeZdZdZddgZdgZ	d„ Z
y)	ÚBlipPreTrainedModelz†
    An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
    models.
    ÚblipTrç   r¤   Úpast_key_valuec                 ó0  — | j                   j                  }t        |t        j                  «      s4t        |t        j
                  «      st        |t        j                  «      rc|j                  j                  j                  d|¬«       t        |d«      r0|j                  �$|j                  j                  j                  «        t        |t        «      r�t        | j                   d«      r | j                   j                  j                  }t        j                  j!                  |j"                  d|¬«       t        j                  j!                  |j$                  d|¬«       yt        |t        j&                  «      rJ|j                  j                  j                  «        |j                  j                  j)                  d«       yt        |t        j                  «      r2|j                  �%|j                  j                  j                  «        yyy)zInitialize the weightsg        )ÚmeanÚstdÚbiasNÚvision_configg      ð?)r^   Úinitializer_rangeÚ
isinstancer   rn   r¨   rÁ   r’   ÚdataÚnormal_Úhasattrrü   Úzero_r]   rý   ÚinitÚtrunc_normal_rr   rm   rì   Úfill_)r;   ÚmoduleÚfactors      r&   Ú_init_weightsz!BlipPreTrainedModel._init_weightsÝ  st  € à—‘×.Ñ.ˆÜ�fœbŸi™iÔ(¬J°v¼r¿|¹|Ô,LÔPZÐ[aÔce×clÑclÔPmØ�M‰M×Ñ×&Ñ&¨C°VÐ&Ô<Ü�v˜vÔ&¨6¯;©;Ð+BØ—‘× Ñ ×&Ñ&Ô(ä�fÔ2Ô3Ü�t—{‘{ OÔ4ØŸ™×2Ñ2×DÑD�Ü�G‰G×!Ñ!Ø×)Ñ)ØØð "ô ô �G‰G×!Ñ!Ø×&Ñ&ØØð "õ ô ˜¤§¡Ô-Ø�K‰K×Ñ×"Ñ"Ô$Ø�M‰M×Ñ×$Ñ$ SÕ)Ü˜¤§	¡	Ô*¨v¯{©{Ð/FØ�K‰K×Ñ×"Ñ"Õ$ð 0GÐ*r(   N)r=   r>   r?   r@   r   Úconfig_classÚbase_model_prefixÚsupports_gradient_checkpointingÚ_no_split_modulesÚ_skip_keys_device_placementr	  rD   r(   r&   rö   rö   Ñ  s4   „ ñð
 €LØÐØ&*Ð#Ø+Ð-AÐBÐØ#3Ð"4Ðó%r(   rö   a=  
    This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
    library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
    etc.)

    This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
    Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
    and behavior.

    Parameters:
        config ([`BlipConfig`]): Model configuration class with all the parameters of the model.
            Initializing with a config file does not load the weights associated with the model, only the
            configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.
aN  
    Args:
        input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
            Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
            it.

            Indices can be obtained using [`AutoProcessor`]. See [`BlipProcessor.__call__`] for details.

            [What are input IDs?](../glossary#input-ids)
        attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
            Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:

            - 1 for tokens that are **not masked**,
            - 0 for tokens that are **masked**.

            [What are attention masks?](../glossary#attention-mask)
        position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
            Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
            config.max_position_embeddings - 1]`.

            [What are position IDs?](../glossary#position-ids)
        output_attentions (`bool`, *optional*):
            Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
            tensors for more detail.
        output_hidden_states (`bool`, *optional*):
            Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
            more detail.
        return_dict (`bool`, *optional*):
            Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
aØ  
    Args:
        pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`):
            Pixel values. Padding will be ignored by default should you provide it. Pixel values can be obtained using
            [`BlipImageProcessor`]. See [`BlipImageProcessor.__call__`] for details.
        output_attentions (`bool`, *optional*):
            Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
            tensors for more detail.
        output_hidden_states (`bool`, *optional*):
            Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
            more detail.
        return_dict (`bool`, *optional*):
            Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
        interpolate_pos_encoding (`bool`, *optional*, defaults to `False`):
            Whether to interpolate the pre-trained position encodings.
as  
    Args:
        input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
            Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
            it.

            Indices can be obtained using [`AutoProcessor`]. See [`BlipProcessor.__call__`] for details.

            [What are input IDs?](../glossary#input-ids)
        attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
            Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:

            - 1 for tokens that are **not masked**,
            - 0 for tokens that are **masked**.

            [What are attention masks?](../glossary#attention-mask)
        position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
            Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
            config.max_position_embeddings - 1]`.

            [What are position IDs?](../glossary#position-ids)
        pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`):
            Pixel values. Padding will be ignored by default should you provide it. Pixel values can be obtained using
            [`BlipImageProcessor`]. See [`BlipImageProcessor.__call__`] for details.
        return_loss (`bool`, *optional*):
            Whether or not to return the contrastive loss.
        output_attentions (`bool`, *optional*):
            Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
            tensors for more detail.
        output_hidden_states (`bool`, *optional*):
            Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
            more detail.
        return_dict (`bool`, *optional*):
            Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
        interpolate_pos_encoding (`bool`, *optional*, defaults to `False`):
            Whether to interpolate the pre-trained position encodings.
c                   ó„   ‡ — e Zd ZdZdefˆ fd„Z	 	 	 	 d
deej                     dee	   dee	   dee	   de
eef   f
d	„Zˆ xZS )ÚBlipEncoderzû
    Transformer encoder consisting of `config.num_hidden_layers` self attention layers. Each layer is a
    [`BlipEncoderLayer`].

    Args:
        config (`BlipConfig`):
            The corresponding vision configuration for the `BlipEncoder`.
    r^   c                 óÐ   •— t         ‰| �  «        || _        t        j                  t        |j                  «      D �cg c]  }t        |«      ‘Œ c}«      | _        d| _	        y c c}w rÛ   )
re   rf   r^   r   Ú
ModuleListÚrangeÚnum_hidden_layersrç   ÚlayersÚgradient_checkpointing)r;   r^   r˜   rt   s      €r&   rf   zBlipEncoder.__init__k  sO   ø€ Ü‰ÑÔØˆŒÜ—m‘mÄuÈV×MeÑMeÓGfÖ$gÀ!Ô%5°fÕ%=Ò$gÓhˆŒØ&+ˆÕ#ùò %hs   ½A#rñ   rË   Úoutput_hidden_statesÚreturn_dictr   c                 ó  — |�|n| j                   j                  }|�|n| j                   j                  }|�|n| j                   j                  }|rdnd}|rdnd}|}t	        | j
                  «      D ]`  \  }	}
|r||fz   }| j                  r+| j                  r| j                  |
j                  |||«      }n |
|||¬«      }|d   }|sŒX||d   fz   }Œb |r||fz   }|st        d„ |||fD «       «      S t        |||¬«      S )aŠ  
        Args:
            inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`):
                Embedded representation of the inputs. Should be float, not int tokens.
            attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
                Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:

                - 1 for tokens that are **not masked**,
                - 0 for tokens that are **masked**.

                [What are attention masks?](../glossary#attention-mask)
            output_attentions (`bool`, *optional*):
                Whether or not to return the attentions tensors of all attention layers. See `attentions` under
                returned tensors for more detail.
            output_hidden_states (`bool`, *optional*):
                Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors
                for more detail.
            return_dict (`bool`, *optional*):
                Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
        NrD   )rË   r   r   c              3   ó&   K  — | ]	  }|€Œ|–— Œ y ­wrß   rD   )rW   Úvs     r&   rY   z&BlipEncoder.forward.<locals>.<genexpr>±  s   è ø€ Òe˜qÐWXÑWdœÑeùó   ‚Š)r3   r4   r5   )r^   rË   r  Úuse_return_dictÚ	enumerater  r  ÚtrainingÚ_gradient_checkpointing_funcÚ__call__rZ   r   )r;   r¯   rñ   rË   r  r  Úencoder_statesÚall_attentionsr4   ÚidxÚencoder_layerÚlayer_outputss               r&   rœ   zBlipEncoder.forwardq  sA  € ð8 2CÐ1NÑ-ÐTX×T_ÑT_×TqÑTqÐà$8Ð$DÑ È$Ï+É+×JjÑJjð 	ð &1Ð%<‘kÀ$Ç+Á+×B]ÑB]ˆá3™¸ˆÙ0™°dˆà%ˆÜ"+¨D¯K©KÓ"8ò 	FÑˆC�Ù#Ø!/°=Ð2BÑ!B�Ø×*Ò*¨t¯}ª}Ø $× AÑ AØ!×*Ñ*Ø!Ø"Ø%ó	!‘ñ !.Ø!Ø"Ø&7ô!�ð *¨!Ñ,ˆMâ Ø!/°=ÀÑ3CÐ2EÑ!E‘ð)	Fñ,  Ø+¨}Ð.>Ñ>ˆNáÜÑe ]°NÀNÐ$SÔeÓeÐeÜØ+¸>ÐVdô
ð 	
r(   ©NNNN)r=   r>   r?   r@   r   rf   r   r#   rž   r    r   r   r   rœ   r¡   r¢   s   @r&   r  r  a  s~   ø„ ñð,˜zõ ,ð 26Ø,0Ø/3Ø&*ñC
ð ! §¡Ñ.ðC
ð $ D™>ð	C
ð
 ' t™nðC
ð ˜d‘^ðC
ð 
ˆu�oÐ%Ñ	&÷C
r(   r  c                   óÄ   ‡ — e Zd ZdZeZdefˆ fd„Z ee«       e	e
e¬«      	 	 	 	 	 ddeej                     dee   dee   dee   ded	eee
f   fd
„«       «       Zd„ Zˆ xZS )ÚBlipVisionModelrŽ   r^   c                 óö   •— t         ‰| �  |«       || _        |j                  }t	        |«      | _        t        |«      | _        t        j                  ||j                  ¬«      | _        | j                  «        y ré   )re   rf   r^   rg   r]   ru   r  Úencoderr   rì   rí   Úpost_layernormÚ	post_initr­   s      €r&   rf   zBlipVisionModel.__init__»  s]   ø€ Ü‰Ñ˜Ô ØˆŒØ×&Ñ&ˆ	ä.¨vÓ6ˆŒÜ" 6Ó*ˆŒÜ Ÿl™l¨9¸&×:OÑ:OÔPˆÔà�‰Õr(   ©Úoutput_typer
  rË   r  r  r�   r   c                 óÌ  — |�|n| j                   j                  }|�|n| j                   j                  }|�|n| j                   j                  }|€t	        d«      ‚| j                  ||¬«      }| j                  ||||¬«      }|d   }| j                  |«      }|dd…ddd…f   }	| j                  |	«      }	|s
||	f|dd z   S t        ||	|j                  |j                  ¬«      S )z
        Returns:

        Nz You have to specify pixel_values)r�   )r¯   rË   r  r  r   r   )r3   Úpooler_outputr4   r5   )r^   rË   r  r  r²   ru   r+  r,  r   r4   r5   )
r;   rŽ   rË   r  r  r�   r4   Úencoder_outputsr3   Úpooled_outputs
             r&   rœ   zBlipVisionModel.forwardÆ  s  € ð 2CÐ1NÑ-ÐTX×T_ÑT_×TqÑTqÐà$8Ð$DÑ È$Ï+É+×JjÑJjð 	ð &1Ð%<‘kÀ$Ç+Á+×B]ÑB]ˆàÐÜÐ?Ó@Ð@àŸ™¨ÐOg˜ÓhˆàŸ,™,Ø'Ø/Ø!5Ø#ð	 'ó 
ˆð ,¨AÑ.ÐØ ×/Ñ/Ð0AÓBÐà)ª!¨Q²¨'Ñ2ˆØ×+Ñ+¨MÓ:ˆáØ% }Ð5¸ÈÈÐ8KÑKÐKä)Ø/Ø'Ø)×7Ñ7Ø&×1Ñ1ô	
ð 	
r(   c                 ó   — | j                   S rß   )ru   r:   s    r&   Úget_input_embeddingsz$BlipVisionModel.get_input_embeddingsö  s   € Ø�‰Ðr(   ©NNNNF)r=   r>   r?   Úmain_input_namer   r
  rf   r   ÚBLIP_VISION_INPUTS_DOCSTRINGr   r   r   r#   rA   r    r   r   rœ   r5  r¡   r¢   s   @r&   r)  r)  ·  sº   ø„ Ø$€OØ#€Lð	Ð/õ 	ñ +Ð+GÓHÙÐ+EÐTdÔeð 59Ø,0Ø/3Ø&*Ø).ñ,
à˜u×0Ñ0Ñ1ð,
ð $ D™>ð,
ð ' t™nð	,
ð
 ˜d‘^ð,
ð #'ð,
ð 
ˆuÐ0Ð0Ñ	1ò,
ó fó Ið,
ö\r(   r)  zÂ
    This model is going to be deprecated in future versions. Please use `BlipForConditionalGeneration`, `BlipForQuestionAnswering` or `BlipForImageTextRetrieval` depending on your usecase.
    c                   óê  ‡ — e Zd ZeZdefˆ fd„Zd„ Zd„ Z ee	«      	 	 	 	 dde
ej                     de
ej                     de
ej                     de
e   d	ej                  f
d
„«       Z ee«      	 	 	 dde
ej                     de
e   ded	ej                  fd„«       Z ee«      	 	 	 	 	 dde
ej&                     de
ej                     de
ej                     de
e   ded	ej                  fd„«       Z ee«       eee¬«      	 	 	 	 	 	 	 	 	 dde
ej&                     de
ej                     de
ej                     de
ej&                     de
e   de
e   de
e   de
e   ded	eeef   fd„«       «       Zˆ xZS )Ú	BlipModelr^   c                 óz  •— t         ‰| �  |«       t        |j                  t        «      s"t        dt        |j                  «      › d�«      ‚t        |j                  t        «      s"t        dt        |j                  «      › d�«      ‚|j                  }|j                  }|j                  | _	        |j                  | _        |j                  | _        t        |«      | _        t        |«      | _        t#        j$                  | j                  | j                  d¬«      | _        t#        j$                  | j                  | j                  d¬«      | _        t#        j*                  t-        j.                  | j0                  j2                  «      «      | _        t6        j9                  d«       | j;                  «        y )NzKconfig.text_config is expected to be of type BlipTextConfig but is of type ú.zOconfig.vision_config is expected to be of type BlipVisionConfig but is of type F)rü   z¸`BlipModel` is going to be deprecated in future release, please use `BlipForConditionalGeneration`, `BlipForQuestionAnswering` or `BlipForImageTextRetrieval` depending on your usecase.)re   rf   rÿ   Útext_configr   Ú	TypeErrorÚtyperý   r   Úprojection_dimrg   Útext_embed_dimÚvision_embed_dimr   Ú
text_modelr)  Úvision_modelr   rÁ   Úvisual_projectionÚtext_projectionrk   r#   rÄ   r^   Úlogit_scale_init_valueÚlogit_scaleÚloggerÚwarningr-  )r;   r^   r=  rý   rt   s       €r&   rf   zBlipModel.__init__  sh  ø€ Ü‰Ñ˜Ô ä˜&×,Ñ,¬nÔ=ÜðÜ˜×+Ñ+Ó,Ð-¨Qð0óð ô
 ˜&×.Ñ.Ô0@ÔAÜðÜ˜×-Ñ-Ó.Ð/¨qð2óð ð
 ×(Ñ(ˆØ×,Ñ,ˆà$×3Ñ3ˆÔØ)×5Ñ5ˆÔØ -× 9Ñ 9ˆÔä'¨Ó4ˆŒÜ+¨MÓ:ˆÔä!#§¡¨4×+@Ñ+@À$×BUÑBUÐ\aÔ!bˆÔÜ!Ÿy™y¨×)<Ñ)<¸d×>QÑ>QÐX]Ô^ˆÔÜŸ<™<¬¯©°T·[±[×5WÑ5WÓ(XÓYˆÔä�‰ð Gô	
ð
 	�‰Õr(   c                 ó6   — | j                   j                  «       S rß   )rC  r5  r:   s    r&   r5  zBlipModel.get_input_embeddings'  s   € Ø�‰×3Ñ3Ó5Ð5r(   c                 ó:   — | j                   j                  |«       y rß   )rC  Úset_input_embeddings©r;   Úvalues     r&   rM  zBlipModel.set_input_embeddings*  s   € Ø�‰×,Ñ,¨UÕ3r(   r®   rñ   r¦   r  r   c                 ó�   — |�|n| j                   j                  }| j                  ||||¬«      }|d   }| j                  |«      }|S )a±  
        Returns:
            text_features (`torch.FloatTensor` of shape `(batch_size, output_dim`): The text embeddings obtained by
            applying the projection layer to the pooled output of [`BlipTextModel`].

        Examples:

        ```python
        >>> from transformers import AutoProcessor, BlipModel

        >>> model = BlipModel.from_pretrained("Salesforce/blip-image-captioning-base")
        >>> processor = AutoProcessor.from_pretrained("Salesforce/blip-image-captioning-base")

        >>> inputs = processor(text=["a photo of a cat", "a photo of a dog"], padding=True, return_tensors="pt")
        >>> text_features = model.get_text_features(**inputs)
        ```)r®   rñ   r¦   r  r   )r^   r  rC  rF  )r;   r®   rñ   r¦   r  Útext_outputsr3  Útext_featuress           r&   Úget_text_featureszBlipModel.get_text_features-  sZ   € ð0 &1Ð%<‘kÀ$Ç+Á+×B]ÑB]ˆà—‘ØØ)Ø%Ø#ð	 'ó 
ˆð % Q™ˆØ×,Ñ,¨]Ó;ˆàÐr(   rŽ   r�   c                 óŽ   — |�|n| j                   j                  }| j                  |||¬«      }|d   }| j                  |«      }|S )aV  
        Returns:
            image_features (`torch.FloatTensor` of shape `(batch_size, output_dim`): The image embeddings obtained by
            applying the projection layer to the pooled output of [`BlipVisionModel`].

        Examples:

        ```python
        >>> from PIL import Image
        >>> import requests
        >>> from transformers import AutoProcessor, BlipModel

        >>> model = BlipModel.from_pretrained("Salesforce/blip-image-captioning-base")
        >>> processor = AutoProcessor.from_pretrained("Salesforce/blip-image-captioning-base")

        >>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
        >>> image = Image.open(requests.get(url, stream=True).raw)

        >>> inputs = processor(images=image, return_tensors="pt")

        >>> image_features = model.get_image_features(**inputs)
        ```)rŽ   r  r�   r   )r^   r  rD  rE  )r;   rŽ   r  r�   Úvision_outputsr3  Úimage_featuress          r&   Úget_image_featureszBlipModel.get_image_featuresS  sZ   € ð: &1Ð%<‘kÀ$Ç+Á+×B]ÑB]ˆà×*Ñ*Ø%Ø#Ø%=ð +ó 
ˆð ' qÑ)ˆØ×/Ñ/°Ó>ˆàÐr(   c                 ó4  — |�|n| j                   j                  }| j                  |dd||¬«      }|d   }t        j                  |j                  «       dd t        j                  ¬«      }| j                  |||||¬«      }	|	d   }
| j                  |
«      }|S )	aË  
        Returns:
            multimodal_features (`torch.FloatTensor` of shape `(batch_size, output_dim`): The multimodal embeddings
            obtained by applying the image embeddings to the text encoder using the cross-attention mechanism.

        Examples:
        ```python
        >>> from PIL import Image
        >>> import requests
        >>> from transformers import AutoProcessor, BlipModel

        >>> model = BlipModel.from_pretrained("Salesforce/blip-image-captioning-base")
        >>> processor = AutoProcessor.from_pretrained("Salesforce/blip-image-captioning-base")

        >>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
        >>> image = Image.open(requests.get(url, stream=True).raw)
        >>> texts = ["a photo of a cat", "a photo of a dog"]
        >>> inputs = processor(images=image, text=texts, padding=True, return_tensors="pt")

        >>> multimodal_features = model.get_multimodal_features(**inputs)
        ```NT©rŽ   rË   r  r  r�   r   ry   r�   ©r®   rñ   Úencoder_hidden_statesÚencoder_attention_maskr  r   )	r^   r  rD  r#   Úonesr{   ÚlongrC  rF  )r;   r®   rŽ   rñ   r  r�   rU  r2   Ú
image_attsrQ  r3  Úmultimodal_featuress               r&   Úget_multimodal_featuresz!BlipModel.get_multimodal_features}  s²   € ð< &1Ð%<‘kÀ$Ç+Á+×B]ÑB]ˆØ×*Ñ*Ø%Ø"Ø!%Ø#Ø%=ð +ó 
ˆð & aÑ(ˆÜ—Z‘Z × 1Ñ 1Ó 3°C°RÐ 8ÄÇ
Á
ÔKˆ
à—‘ØØ)Ø".Ø#-Ø#ð 'ó 
ˆð % Q™ˆØ"×2Ñ2°=ÓAÐà"Ð"r(   r.  Úreturn_lossrË   r  c
           	      ó:  — |�|n| j                   j                  }|�|n| j                   j                  }|�|n| j                   j                  }| j	                  |||||	¬«      }
| j                  ||||||¬«      }|
d   }| j                  |«      }|d   }| j                  |«      }||j                  ddd¬«      z  }||j                  ddd¬«      z  }| j                  j                  «       j                  |j                  ¬	«      }|j                  |j                  |j                  ¬
«      }t        j                  ||j!                  «       «      |z  }|j!                  «       }d}|rt#        |«      }|s||||||
f}|�|f|z   S |S t%        |||||||
¬«      S )a›  
        Returns:

        Examples:

        ```python
        >>> from PIL import Image
        >>> import requests
        >>> from transformers import AutoProcessor, BlipModel

        >>> model = BlipModel.from_pretrained("Salesforce/blip-image-captioning-base")
        >>> processor = AutoProcessor.from_pretrained("Salesforce/blip-image-captioning-base")

        >>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
        >>> image = Image.open(requests.get(url, stream=True).raw)

        >>> inputs = processor(
        ...     text=["a photo of a cat", "a photo of a dog"], images=image, return_tensors="pt", padding=True
        ... )

        >>> outputs = model(**inputs)
        >>> logits_per_image = outputs.logits_per_image  # this is the image-text similarity score
        >>> probs = logits_per_image.softmax(dim=1)  # we can take the softmax to get the label probabilities
        ```NrY  )r®   rñ   r¦   rË   r  r  r   rd   ry   T)Úpr   Úkeepdimr   )r    r‘   )r1   rN   rO   rP   r2   rQ   rR   )r^   rË   r  r  rD  rC  rE  rF  ÚnormrH  Úexpr“   r    r‘   r#   rÎ   r+   r.   rM   )r;   r®   rŽ   rñ   r¦   rb  rË   r  r  r�   rU  rQ  r2   rP   rH  rO   rN   r1   rÙ   s                      r&   rœ   zBlipModel.forward´  sâ  € ðN 2CÐ1NÑ-ÐTX×T_ÑT_×TqÑTqÐà$8Ð$DÑ È$Ï+É+×JjÑJjð 	ð &1Ð%<‘kÀ$Ç+Á+×B]ÑB]ˆà×*Ñ*Ø%Ø/Ø!5Ø#Ø%=ð +ó 
ˆð —‘ØØ)Ø%Ø/Ø!5Ø#ð 'ó 
ˆð & aÑ(ˆØ×-Ñ-¨lÓ;ˆà" 1‘oˆØ×*Ñ*¨;Ó7ˆð $ l×&7Ñ&7¸!ÀÈTÐ&7Ó&RÑRˆØ! K×$4Ñ$4°q¸bÈ$Ð$4Ó$OÑOˆð ×&Ñ&×*Ñ*Ó,×/Ñ/°{×7IÑ7IÐ/ÓJˆØ#—‘¨k×.@Ñ.@È×HYÑHY�ÓZˆÜŸ,™, {°L·N±NÓ4DÓEÈÑSˆØ*×,Ñ,Ó.ÐàˆÙÜ˜_Ó-ˆDáØ&¨¸ÀlÐT`ÐbpÐqˆFØ)-Ð)9�T�G˜fÑ$ÐE¸vÐEäØØ-Ø+Ø#Ø%Ø*Ø .ô
ð 	
r(   r'  ©NNFr6  )	NNNNNNNNF)r=   r>   r?   r   r
  rf   r5  rM  r   ÚBLIP_TEXT_INPUTS_DOCSTRINGr   r#   rž   r    rA   rS  r8  rW  ÚBLIP_INPUTS_DOCSTRINGr¶   ra  r   rM   r   r   rœ   r¡   r¢   s   @r&   r:  r:  ú  sŒ  ø„ ð €Lð"˜zõ "òH6ò4ñ +Ð+EÓFð -1Ø15Ø/3Ø&*ñ#à˜EŸL™LÑ)ð#ð ! §¡Ñ.ð#ð ˜uŸ|™|Ñ,ð	#ð
 ˜d‘^ð#ð 
×	Ñ	ò#ó Gð#ñJ +Ð+GÓHð 59Ø&*Ø).ñ	'à˜u×0Ñ0Ñ1ð'ð ˜d‘^ð'ð #'ð	'ð
 
×	Ñ	ò'ó Ið'ñR +Ð+@ÓAð 15Ø48Ø15Ø&*Ø).ñ4#à˜E×,Ñ,Ñ-ð4#ð ˜u×0Ñ0Ñ1ð4#ð ! §¡Ñ.ð	4#ð
 ˜d‘^ð4#ð #'ð4#ð 
×	Ñ	ò4#ó Bð4#ñl +Ð+@ÓAÙ¨:ÀJÔOð 15Ø48Ø15Ø37Ø&*Ø,0Ø/3Ø&*Ø).ñ\
à˜E×,Ñ,Ñ-ð\
ð ˜u×0Ñ0Ñ1ð\
ð ! §¡Ñ.ð	\
ð
 ˜u×/Ñ/Ñ0ð\
ð ˜d‘^ð\
ð $ D™>ð\
ð ' t™nð\
ð ˜d‘^ð\
ð #'ð\
ð 
ˆu�jÐ Ñ	!ò\
ó Pó Bô\
r(   r:  aÒ  
    BLIP Model for image captioning. The model consists of a vision encoder and a text decoder. One can optionally pass
    `input_ids` to the model, which serve as a text prompt, to make the text decoder continue the prompt. Otherwise,
    the decoder starts generating text from the [BOS] (beginning-of-sequence) token. will start generating the caption
    from the text input. If no text input is provided, the decoder will start with the [BOS] token only.
    c                   óÐ  ‡ — e Zd ZeZdgZdZdefˆ fd„Zd„ Zd„ Z	 e
e«       eee¬«      	 	 	 	 	 	 	 ddej                   deej$                     d	eej$                     d
ee   dee   deej$                     dee   dedeeef   fd„«       «       Z ej.                  «       	 	 	 ddej                   deej$                     d	eej$                     dedej$                  f
d„«       Zˆ xZS )ÚBlipForConditionalGenerationú)text_decoder.cls.predictions.decoder.biasrŽ   r^   c                 ó  •— t         ‰| �  |«       t        |j                  «      | _        t        |j                  «      | _        |j                  j                  | _	        |j                  j                  | _        | j                  «        y rß   )re   rf   r)  rý   rD  r   r=  Útext_decoderÚbos_token_idÚdecoder_input_idsÚpad_token_idÚdecoder_pad_token_idr-  rs   s     €r&   rf   z%BlipForConditionalGeneration.__init__#  sj   ø€ Ü‰Ñ˜Ô ä+¨F×,@Ñ,@ÓAˆÔä/°×0BÑ0BÓCˆÔà!'×!3Ñ!3×!@Ñ!@ˆÔØ$*×$6Ñ$6×$CÑ$CˆÔ!ð 	�‰Õr(   c                 ó6   — | j                   j                  «       S rß   )ro  r5  r:   s    r&   r5  z1BlipForConditionalGeneration.get_input_embeddings0  ó   € Ø× Ñ ×5Ñ5Ó7Ð7r(   c                 ó:   — | j                   j                  |«       y rß   )ro  rM  rN  s     r&   rM  z1BlipForConditionalGeneration.set_input_embeddings3  ó   € Ø×Ñ×.Ñ.¨uÕ5r(   r.  r®   rñ   rË   r  Úlabelsr  r�   r   c	                 óô  — |�|n| j                   j                  }|�|n| j                   j                  }|�|n| j                   j                  }| j	                  |||||¬«      }	|	d   }
| j                  |||
||d¬«      }|s4|�
|d   |d   fn|d   f}||
|	d   f|	dd z   z  }t        d„ |D «       «      S t        |j                  |j                  |
|	j                  |	j                  |	j                  ¬	«      S )
aÂ  
        Returns:

        Examples:

        ```python
        >>> from PIL import Image
        >>> import requests
        >>> from transformers import AutoProcessor, BlipForConditionalGeneration

        >>> processor = AutoProcessor.from_pretrained("Salesforce/blip-image-captioning-base")
        >>> model = BlipForConditionalGeneration.from_pretrained("Salesforce/blip-image-captioning-base")

        >>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
        >>> image = Image.open(requests.get(url, stream=True).raw)
        >>> text = "A picture of"

        >>> inputs = processor(images=image, text=text, return_tensors="pt")

        >>> outputs = model(**inputs)
        ```NrY  r   rú   )r®   rñ   r[  rx  r  Ú	reductionr   rd   c              3   ó&   K  — | ]	  }|€Œ|–— Œ y ­wrß   rD   ©rW   rÙ   s     r&   rY   z7BlipForConditionalGeneration.forward.<locals>.<genexpr>u  ó   è ø€ ÒL F¸Ñ9KœÑLùr  )r1   r   r2   r3   r4   r5   )r^   r  rË   r  rD  ro  rZ   r0   r1   r   r3   r4   r5   )r;   rŽ   r®   rñ   rË   r  rx  r  r�   rU  r2   rÚ   s               r&   rœ   z$BlipForConditionalGeneration.forward6  s8  € ðF &1Ð%<‘kÀ$Ç+Á+×B]ÑB]ˆØ1BÐ1NÑ-ÐTX×T_ÑT_×TqÑTqÐà$8Ð$DÑ È$Ï+É+×JjÑJjð 	ð ×*Ñ*Ø%Ø/Ø!5Ø#Ø%=ð +ó 
ˆð & aÑ(ˆà×#Ñ#ØØ)Ø".ØØ#Øð $ó 
ˆñ Ø28Ð2D�w˜q‘z 7¨1¡:Ñ.È7ÐSTÉ:È-ˆGØ˜ n°QÑ&7Ð8¸>È!È"Ð;MÑMÑMˆGÜÑL¨gÔLÓLÐLä6Ø—‘Ø—>‘>Ø%Ø,×>Ñ>Ø(×6Ñ6Ø%×0Ñ0ô
ð 	
r(   c           
      ó4  — |j                   d   }| j                  ||¬«      }|d   }t        j                  |j	                  «       dd t        j
                  |j                  ¬«      }	t        |t        «      rt        j                  |«      }nk|€it        j                  | j                  | j                  j                  j                  gg«      j                  |d«      j                  |j                  «      }| j                  j                  j                   |dd…df<   |�|dd…dd…f   nd} | j"                  j$                  d|dd…dd…f   | j                  j                  j&                  | j                  j                  j(                  |||	dœ|¤Ž}
|
S )	a‹  
        Overrides *generate* function to be able to use the model as a conditional generator

        Parameters:
            pixel_values (*torch.FloatTensor* of shape *(batch_size, num_channels, image_height, image_width)*:
                Input image to be processed
            input_ids (*torch.LongTensor* of shape *(batch_size, sequence_length)*, *optional*):
                The sequence used as a prompt for the generation.
            attention_mask (*torch.LongTensor* of shape *(batch_size, sequence_length)*, *optional*):
                Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:


        Examples:
        ```python
        >>> from PIL import Image
        >>> import requests
        >>> from transformers import AutoProcessor, BlipForConditionalGeneration

        >>> model = BlipForConditionalGeneration.from_pretrained("Salesforce/blip-image-captioning-base")
        >>> processor = AutoProcessor.from_pretrained("Salesforce/blip-image-captioning-base")

        >>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
        >>> image = Image.open(requests.get(url, stream=True).raw)

        >>> inputs = processor(images=image, return_tensors="pt")

        >>> outputs = model.generate(**inputs)
        >>> print(processor.decode(outputs[0], skip_special_tokens=True))
        two cats sleeping on a couch
        ```
        r   ©rŽ   r�   Nry   ©r‘   r    r   )r®   Úeos_token_idrr  rñ   r[  r\  rD   )r€   rD  r#   r]  r{   r^  r    rÿ   Úlistr¶   rq  r^   r=  r�  Úrepeatr“   rp  ro  ÚgenerateÚsep_token_idrr  )r;   rŽ   r®   rñ   r�   Úgenerate_kwargsr—   rU  r2   Úimage_attention_maskrÚ   s              r&   r„  z%BlipForConditionalGeneration.generate€  s}  € ðR "×'Ñ'¨Ñ*ˆ
Ø×*Ñ*Ø%Ø%=ð +ó 
ˆð
 & aÑ(ˆä$Ÿz™z¨,×*;Ñ*;Ó*=¸c¸rÐ*BÌ%Ï*É*Ð]i×]pÑ]pÔqÐä�i¤Ô&Ü×(Ñ(¨Ó3‰IØÐä× Ñ  4×#9Ñ#9¸4¿;¹;×;RÑ;R×;_Ñ;_Ð"`Ð!aÓbß‘˜
 AÓ&ß‘�L×'Ñ'Ó(ð ð Ÿ+™+×1Ñ1×>Ñ>ˆ	’!�Q�$‰Ø3AÐ3M˜ª¨3¨B¨3¨Ò/ÐSWˆà,�$×#Ñ#×,Ñ,ð 
Ø¢ 3 B 3 Ñ'ØŸ™×0Ñ0×=Ñ=ØŸ™×0Ñ0×=Ñ=Ø)Ø".Ø#7ñ
ð ñ
ˆð ˆr(   )NNNNNNFrh  )r=   r>   r?   r   r
  Ú_tied_weights_keysr7  rf   r5  rM  r   r8  r   r0   r   r#   rA   r   r¶   r    r   r   rœ   Úno_gradr„  r¡   r¢   s   @r&   rl  rl    s”  ø„ ð €LØEÐFÐØ$€Oð˜zõ ò8ò6ñ +Ð+GÓHÙÐ+RÐaqÔrð 15Ø59Ø,0Ø/3Ø-1Ø&*Ø).ñF
à×'Ñ'ðF
ð ˜E×,Ñ,Ñ-ðF
ð ! ×!1Ñ!1Ñ2ð	F
ð
 $ D™>ðF
ð ' t™nðF
ð ˜×)Ñ)Ñ*ðF
ð ˜d‘^ðF
ð #'ðF
ð 
ˆuÐ=Ð=Ñ	>òF
ó só IðF
ðP €U‡]�]ƒ_ð 15Ø59Ø).ñHà×'Ñ'ðHð ˜E×,Ñ,Ñ-ðHð ! ×!1Ñ!1Ñ2ð	Hð
 #'ðHð 
×	Ñ	òHó ôHr(   rl  aS  
    BLIP Model for visual question answering. The model consists of a vision encoder, a text encoder as well as a text
    decoder. The vision encoder will encode the input image, the text encoder will encode the input question together
    with the encoding of the image, and the text decoder will output the answer to the question.
    c                   óü  ‡ — e Zd ZeZdgZdefˆ fd„Zd„ Zd„ Z e	e
«       eee¬«      	 	 	 	 	 	 	 	 ddej                  dej                   d	eej                     d
eej                     deej                     dee   dee   deej                     dee   dedeeef   fd„«       «       Z ej,                  «       	 	 ddej                  dej                   deej                     dedej                  f
d„«       Zˆ xZS )ÚBlipForQuestionAnsweringrm  r^   c                 óP  •— t         ‰| �  |«       t        |j                  «      | _        t        |j                  d¬«      | _        t        |j                  «      | _	        |j                  j                  | _        |j                  j                  | _        | j                  «        y )NF©Úadd_pooling_layer)re   rf   r)  rý   rD  r   r=  Útext_encoderr   ro  rr  rs  rp  Údecoder_start_token_idr-  rs   s     €r&   rf   z!BlipForQuestionAnswering.__init__Ø  s€   ø€ Ü‰Ñ˜Ô ä+¨F×,@Ñ,@ÓAˆÔä)¨&×*<Ñ*<ÐPUÔVˆÔä/°×0BÑ0BÓCˆÔà$*×$6Ñ$6×$CÑ$CˆÔ!Ø&,×&8Ñ&8×&EÑ&EˆÔ#ð 	�‰Õr(   c                 ó:   — | j                   j                  |«       y rß   ©r�  rM  rN  s     r&   rM  z-BlipForQuestionAnswering.set_input_embeddingsç  rw  r(   c                 ó6   — | j                   j                  «       S rß   ©r�  r5  r:   s    r&   r5  z-BlipForQuestionAnswering.get_input_embeddingsê  s   € à× Ñ ×5Ñ5Ó7Ð7r(   r.  r®   rŽ   rq  Údecoder_attention_maskrñ   rË   r  rx  r  r�   r   c           	      óô  — |€|€t        d«      ‚|	�|	n| j                  j                  }	|�|n| j                  j                  }|�|n| j                  j                  }| j                  ||||	|
¬«      }|d   }t        j                  |j                  «       dd t        j                  ¬«      }| j                  |||||	¬«      }|�|€|}|	s|d   n|j                  }| j                  ||||||	d¬	«      }|�0|	r|j                  j                  «       n|d   j                  «       }nd}|	s |||d   f|d
d z   }t        d„ |D «       «      S t!        |||j                  |j"                  |j$                  ¬«      S )a°  
        Returns:

        Examples:

        ```python
        >>> from PIL import Image
        >>> import requests
        >>> from transformers import AutoProcessor, BlipForQuestionAnswering

        >>> model = BlipForQuestionAnswering.from_pretrained("Salesforce/blip-vqa-base")
        >>> processor = AutoProcessor.from_pretrained("Salesforce/blip-vqa-base")

        >>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
        >>> image = Image.open(requests.get(url, stream=True).raw)

        >>> # training
        >>> text = "How many cats are in the picture?"
        >>> label = "2"
        >>> inputs = processor(images=image, text=text, return_tensors="pt")
        >>> labels = processor(text=label, return_tensors="pt").input_ids

        >>> inputs["labels"] = labels
        >>> outputs = model(**inputs)
        >>> loss = outputs.loss
        >>> loss.backward()

        >>> # inference
        >>> text = "How many cats are in the picture?"
        >>> inputs = processor(images=image, text=text, return_tensors="pt")
        >>> outputs = model.generate(**inputs)
        >>> print(processor.decode(outputs[0], skip_special_tokens=True))
        2
        ```Na  Either `decoder_input_ids` or `labels` should be passed when calling `forward` with `BlipForQuestionAnswering`. if you are training the model make sure that `labels` is passed, if you are using the model for inference make sure that `decoder_input_ids` is passed or call `generate`rY  r   ry   r�   rZ  rú   )r®   rñ   r[  r\  rx  r  rz  rd   c              3   ó&   K  — | ]	  }|€Œ|–— Œ y ­wrß   rD   r|  s     r&   rY   z3BlipForQuestionAnswering.forward.<locals>.<genexpr>V  r}  r  )r1   r2   r3   r4   r5   )r²   r^   r  rË   r  rD  r#   r]  r{   r^  r�  r3   ro  r1   rú   rZ   rF   r4   r5   )r;   r®   rŽ   rq  r•  rñ   rË   r  rx  r  r�   rU  r2   r‡  rK   Úanswer_outputÚdecoder_lossrÚ   s                     r&   rœ   z BlipForQuestionAnswering.forwardî  sÒ  € ðb ˆ>Ð/Ð7Üðuóð ð &1Ð%<‘kÀ$Ç+Á+×B]ÑB]ˆØ1BÐ1NÑ-ÐTX×T_ÑT_×TqÑTqÐà$8Ð$DÑ È$Ï+É+×JjÑJjð 	ð ×*Ñ*Ø%Ø/Ø!5Ø#Ø%=ð +ó 
ˆð & aÑ(ˆÜ$Ÿz™z¨,×*;Ñ*;Ó*=¸c¸rÐ*BÌ%Ï*É*ÔUÐà×+Ñ+ØØ)Ø".Ø#7Ø#ð ,ó 
ˆð ÐÐ"3Ð";à &Ðá4?˜/¨!Ò,À_×EfÑEfˆà×)Ñ)Ø'Ø1Ø"1Ø#1ØØ#Øð *ó 
ˆð ÐÙ8C˜=×-Ñ-×2Ñ2Ô4ÈÐWXÑIY×I^ÑI^ÓI`‰LàˆLáØ# \°>À!Ñ3DÐEÈÐWXÐWYÐHZÑZˆGÜÑL¨gÔLÓLÐLä(ØØ%Ø,×>Ñ>Ø(×6Ñ6Ø%×0Ñ0ô
ð 	
r(   c           	      óð  — | j                  ||¬«      }|d   }t        j                  |j                  «       dd t        j                  |j
                  ¬«      }t        |t        «      rt        j                  |«      }| j                  ||||d¬«      }	|	d   }
t        j                  |
j                  «       dd t        j                  |
j
                  ¬«      }t        j                  |
j                  d«      df| j                  |
j
                  ¬	«      } | j                  j                  d|| j                  j                  j                   | j                  j                  j"                  |
|d
œ|¤Ž}|S )aD  
        Overrides *generate* function to be able to use the model as a conditional generator

        Parameters:
            input_ids (*torch.LongTensor* of shape *(batch_size, sequence_length)*):
                The sequence used as a prompt for the generation.
            pixel_values (*torch.FloatTensor* of shape *(batch_size, num_channels, image_height, image_width)*:
                Input image to be processed
            attention_mask (*torch.LongTensor* of shape *(batch_size, sequence_length)*, *optional*):
                Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`. `1` for
                tokens that are NOT MASKED, `0` for MASKED tokens.
            **generate_kwargs:
                Additional arguments passed to the *generate* function of the decoder


        Examples:
        ```python
        >>> from PIL import Image
        >>> import requests
        >>> from transformers import AutoProcessor, BlipForQuestionAnswering

        >>> model = BlipForQuestionAnswering.from_pretrained("Salesforce/blip-vqa-base")
        >>> processor = AutoProcessor.from_pretrained("Salesforce/blip-vqa-base")

        >>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
        >>> image = Image.open(requests.get(url, stream=True).raw)
        >>> text = "How many cats are in the picture?"

        >>> inputs = processor(images=image, text=text, return_tensors="pt")

        >>> outputs = model.generate(**inputs)
        >>> print(processor.decode(outputs[0], skip_special_tokens=True))
        2
        ```
        r  r   Nry   r€  FrZ  r   )Ú
fill_valuer    )r®   r�  rr  r[  r\  rD   )rD  r#   r]  r{   r^  r    rÿ   r‚  r¶   r�  Úfullr�  ro  r„  r^   r=  r…  rr  )r;   r®   rŽ   rñ   r�   r†  rU  r2   r‡  Úquestion_outputsrK   Úquestion_attention_maskÚbos_idsrÚ   s                 r&   r„  z!BlipForQuestionAnswering.generate`  sh  € ðX ×*Ñ*Ø%Ø%=ð +ó 
ˆð
 & aÑ(ˆä$Ÿz™z¨,×*;Ñ*;Ó*=¸c¸rÐ*BÌ%Ï*É*Ð]i×]pÑ]pÔqÐä�i¤Ô&Ü×(Ñ(¨Ó3ˆIà×,Ñ,ØØ)Ø".Ø#7Øð -ó 
Ðð +¨1Ñ-ˆä"'§*¡*Ø× Ñ Ó" 3 BÐ'¬u¯z©zÀ/×BXÑBXô#
Ðô —*‘*Ø×!Ñ! !Ó$ aÐ(°T×5PÑ5PÐYh×YoÑYoô
ˆð -�$×#Ñ#×,Ñ,ð 
ØØŸ™×0Ñ0×=Ñ=ØŸ™×0Ñ0×=Ñ=Ø"1Ø#:ñ
ð ñ
ˆð ˆr(   )NNNNNNNFrÛ   )r=   r>   r?   r   r
  rˆ  rf   rM  r5  r   r8  r   rF   r   r#   r¶   rA   r   r    r   r   rœ   r‰  r„  r¡   r¢   s   @r&   r‹  r‹  Ì  s±  ø„ ð €LØEÐFÐð˜zõ ò6ò8ñ +Ð+GÓHÙÐ+DÐScÔdð
 9=Ø=AØ59Ø,0Ø/3Ø-1Ø&*Ø).ñn
à×#Ñ#ðn
ð ×'Ñ'ðn
ð $ E×$4Ñ$4Ñ5ð	n
ð
 !)¨×)9Ñ)9Ñ :ðn
ð ! ×!1Ñ!1Ñ2ðn
ð $ D™>ðn
ð ' t™nðn
ð ˜×)Ñ)Ñ*ðn
ð ˜d‘^ðn
ð #'ðn
ð 
ˆuÐ/Ð/Ñ	0òn
ó eó Iðn
ð` €U‡]�]ƒ_ð
 6:Ø).ñRà×#Ñ#ðRð ×'Ñ'ðRð ! ×!1Ñ!1Ñ2ð	Rð
 #'ðRð 
×	Ñ	òRó ôRr(   r‹  a   
    BLIP Model with a vision and text projector, and a classification head on top. The model is used in the context of
    image-text retrieval. Given an image and a text, the model returns the probability of the text being relevant to
    the image.
    c                   ó  ‡ — e Zd ZeZdefˆ fd„Zd„ Zd„ Z ee	«       e
ee¬«      	 	 	 	 	 	 ddej                  dej                  dee   d	eej                     d
ee   dee   dee   dedeeef   fd„«       «       Zˆ xZS )ÚBlipForImageTextRetrievalr^   c                 ó¾  •— t         ‰| �  |«       t        |j                  «      | _        t        |j                  d¬«      | _        t        j                  |j                  j                  |j                  «      | _        t        j                  |j                  j                  |j                  «      | _        t        j                  |j                  j                  d«      | _        t        |d«      s|j                  j                   n|j"                  | _        t        |d«      s|j                  j$                  n|j&                  | _        | j)                  «        y )NFr�  rd   rs  r�  )re   rf   r)  rý   rD  r   r=  r�  r   rÁ   rg   Úimage_text_hidden_sizeÚvision_projÚ	text_projÚitm_headr  rr  rs  rp  r�  r-  rs   s     €r&   rf   z"BlipForImageTextRetrieval.__init__Á  s  ø€ Ü‰Ñ˜Ô ä+¨F×,@Ñ,@ÓAˆÔä)¨&×*<Ñ*<ÐPUÔVˆÔô Ÿ9™9 V×%9Ñ%9×%EÑ%EÀv×GdÑGdÓeˆÔô Ÿ™ 6×#5Ñ#5×#AÑ#AÀ6×C`ÑC`ÓaˆŒô Ÿ	™	 &×"4Ñ"4×"@Ñ"@À!ÓDˆŒô ˜6Ð#9Ô:ð ×Ñ×+Ò+à×,Ñ,ð 	Ô!ô ˜6Ð#;Ô<ð ×Ñ×+Ò+à×.Ñ.ð 	Ô#ð 	�‰Õr(   c                 ó6   — | j                   j                  «       S rß   r”  r:   s    r&   r5  z.BlipForImageTextRetrieval.get_input_embeddingsß  ru  r(   c                 ó:   — | j                   j                  |«       y rß   r’  rN  s     r&   rM  z.BlipForImageTextRetrieval.set_input_embeddingsâ  rw  r(   r.  r®   rŽ   Úuse_itm_headrñ   rË   r  r  r�   r   c	           	      ó€  — |�|n| j                   j                  }|�|n| j                   j                  }|�|n| j                   j                  }| j	                  |||||¬«      }	|	d   }
t        j                  |
j                  «       dd t
        j                  ¬«      }|rE| j                  |||
||¬«      }|s|d   n|j                  }| j                  |dd…ddd…f   «      }n†| j                  |||¬«      }|s|d   n|j                  }t        | j                  |
dd…ddd…f   «      d¬«      }t        | j                  |dd…ddd…f   «      d¬«      }||j                  «       z  }|s#||	d   f|	d	d z   |fz   }t!        d
„ |D «       «      S t#        ||	j                  |	j$                  |	j&                  |¬«      S )a¹  
        Returns:

        Examples:

        ```python
        >>> from PIL import Image
        >>> import requests
        >>> from transformers import AutoProcessor, BlipForImageTextRetrieval

        >>> model = BlipForImageTextRetrieval.from_pretrained("Salesforce/blip-itm-base-coco")
        >>> processor = AutoProcessor.from_pretrained("Salesforce/blip-itm-base-coco")

        >>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
        >>> image = Image.open(requests.get(url, stream=True).raw)
        >>> text = "an image of a cat"

        >>> inputs = processor(images=image, text=text, return_tensors="pt")
        >>> outputs = model(**inputs)
        ```
        NrY  r   ry   r�   rZ  )r®   rñ   r  r~   rd   c              3   ó&   K  — | ]	  }|€Œ|–— Œ y ­wrß   rD   r|  s     r&   rY   z4BlipForImageTextRetrieval.forward.<locals>.<genexpr>2  r}  r  )rI   r3   r4   r5   rK   )r^   r  rË   r  rD  r#   r]  r{   r^  r�  r3   r¦  r	   r¤  r¥  r+   rZ   rH   r4   r5   )r;   r®   rŽ   r©  rñ   rË   r  r  r�   rU  r2   r_  rK   rÙ   Ú
image_featÚ	text_featrÚ   s                    r&   rœ   z!BlipForImageTextRetrieval.forwardå  së  € ðD &1Ð%<‘kÀ$Ç+Á+×B]ÑB]ˆØ1BÐ1NÑ-ÐTX×T_ÑT_×TqÑTqÐà$8Ð$DÑ È$Ï+É+×JjÑJjð 	ð ×*Ñ*Ø%Ø/Ø!5Ø#Ø%=ð +ó 
ˆð & aÑ(ˆÜ—Z‘Z × 1Ñ 1Ó 3°C°RÐ 8ÄÇ
Á
ÔKˆ
áØ"×/Ñ/Ø#Ø-Ø&2Ø'1Ø'ð 0ó ˆOñ 9D˜o¨aÒ0È×IjÑIjˆOà—]‘] ?²1°aº°7Ñ#;Ó<‰Fà"×/Ñ/Ø#Ø-Ø'ð 0ó ˆOñ
 9D˜o¨aÒ0È×IjÑIjˆOä" 4×#3Ñ#3°LÂÀAÂqÀÑ4IÓ#JÐPRÔSˆJÜ! $§.¡.°ÂÀAÂqÀÑ1IÓ"JÐPRÔSˆIà )§+¡+£-Ñ/ˆFáØ˜~¨aÑ0Ð1°NÀ1À2Ð4FÑFÈ/ÐI[Ñ[ˆGÜÑL¨gÔLÓLÐLä/ØØ,×>Ñ>Ø(×6Ñ6Ø%×0Ñ0Ø+ô
ð 	
r(   )TNNNNF)r=   r>   r?   r   r
  rf   r5  rM  r   r8  r   rF   r   r#   r¶   rA   r   r    r   r   rœ   r¡   r¢   s   @r&   r¡  r¡  ¶  sö   ø„ ð €Lð˜zõ ò<8ò6ñ +Ð+GÓHÙÐ+DÐScÔdð
 (,Ø59Ø,0Ø/3Ø&*Ø).ñS
à×#Ñ#ðS
ð ×'Ñ'ðS
ð ˜t‘nð	S
ð
 ! ×!1Ñ!1Ñ2ðS
ð $ D™>ðS
ð ' t™nðS
ð ˜d‘^ðS
ð #'ðS
ð 
ˆuÐ/Ð/Ñ	0òS
ó eó IôS
r(   r¡  )r:  rö   rl  r‹  r)  r   r¡  )Br@   r7   Údataclassesr   Útypingr   r   r   r   r#   Útorch.utils.checkpointr   Útorch.nn.functionalr	   Úactivationsr   Ú
generationr   Úmodeling_outputsr   r   Úmodeling_utilsr   Úutilsr   r   r   r   r   r   Úconfiguration_blipr   r   r   Úmodeling_blip_textr   r   Ú
get_loggerr=   rI  Ú_CHECKPOINT_FOR_DOCrž   r'   r.   r0   rF   rH   rM   ÚModuler]   r¤   r¸   rÝ   rç   rö   ÚBLIP_START_DOCSTRINGri  r8  rj  r  r)  r:  rl  r‹  r¡  Ú__all__rD   r(   r&   ú<module>r¾     sw  ðñ ã Ý !ß .Ó .ã Û Ý Ý )å !Ý )ß KÝ -÷÷ ÷ MÑ Lß Bð 
ˆ×	Ñ	˜HÓ	%€à0Ð ð`˜UŸ\™\ð `¨e¯l©ló `ð
-˜%Ÿ,™,ð -¨5¯<©<ó -ð ô)¨kó )ó ð)ðX ô? ó ?ó ð?ð@ ô'? {ó '?ó ð'?ðT ô!
�ó !
ó ð!
ôHG˜2Ÿ9™9ô GôV%˜Ÿ™ô %ôPB�B—I‘Iô BôLˆb�i‰iô ô-�r—y‘yô -ô`'%˜/ô '%ðTÐ ðÐ ð> Ð ð"$Ð ôNS
�"—)‘)ô S
ôl@Ð)ô @ñF ðð ó	ôR
Ð#ó R
óðR
ñj ðð óôkÐ#6¸ó kóðkñ\ ðð
 óô_Ð2°Oó _óð_ñD ðð
 óô|
Ð 3ó |
óð|
ò~�r(   