Ë
    S^(hÏ ã                  ó$  — d Z ddlm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mZmZ ddlmZmZmZmZmZmZmZ dd	lmZmZ dd
l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'm(Z(  ejR                  e*«      Z+dZ,d:d„Z-d;d„Z.e G d„ de«      «       Z/e G d„ de«      «       Z0e G d„ de«      «       Z1e G d„ de«      «       Z2 G d„ dejf                  jh                  «      Z5 G d„ dejf                  jh                  «      Z6 G d„ dejf                  jh                  «      Z7 G d„ d ejf                  jh                  «      Z8 G d!„ d"ejf                  jh                  «      Z9 G d#„ d$e«      Z:d%Z;d&Z<d'Z=e G d(„ d)ejf                  jh                  «      «       Z> G d*„ d+e:«      Z? G d,„ d-ejf                  jh                  «      Z@ G d.„ d/e:«      ZA ed0e;«       G d1„ d2e:«      «       ZB ed3e;«       G d4„ d5e:«      «       ZC ed6e;«       G d7„ d8e:«      «       ZDg d9¢ZEy)<zTensorFlow BLIP model.é    )ÚannotationsN)Ú	dataclass)ÚAnyÚOptionalÚTupleÚUnioné   )ÚTFBaseModelOutputÚTFBaseModelOutputWithPooling)ÚTFPreTrainedModelÚget_initializerÚget_tf_activationÚkerasÚkeras_serializableÚ
shape_listÚunpack_inputs)Úcheck_embeddings_within_boundsÚstable_softmax)ÚModelOutputÚadd_start_docstringsÚ%add_start_docstrings_to_model_forwardÚloggingÚreplace_return_docstringsé   )Ú
BlipConfigÚBlipTextConfigÚBlipVisionConfig)ÚBLIP_TEXT_INPUTS_DOCSTRINGÚTFBlipTextLMHeadModelÚTFBlipTextModelzSalesforce/blip-vqa-basec           	     ó¾   — t         j                  j                  t        j                  j                  t        j                  t        | «      d   «      | d¬«      «      S )Nr   T)Úy_trueÚy_predÚfrom_logits)ÚtfÚmathÚreduce_meanr   ÚmetricsÚsparse_categorical_crossentropyÚranger   )Úlogitss    úg/var/www/skyplay_api_hub/venv/lib/python3.12/site-packages/transformers/models/blip/modeling_tf_blip.pyÚcontrastive_lossr-   5   sJ   € Ü�7‰7×ÑÜ�‰×5Ñ5Ü—8‘8œJ vÓ.¨qÑ1Ó2¸6Ètð 	6ó 	
óð ó    c                ód   — t        | «      }t        t        j                  | «      «      }||z   dz  S )Ng       @)r-   r%   Ú	transpose)Ú
similarityÚcaption_lossÚ
image_losss      r,   Ú	blip_lossr4   >   s/   € Ü# JÓ/€LÜ!¤"§,¡,¨zÓ":Ó;€JØ˜:Ñ%¨Ñ,Ð,r.   c                  óv   — e Zd ZU dZdZded<   dZded<   dZded<   dZded	<   dZ	d
ed<   dZ
d
ed<   ed„ «       Zy)Ú)TFBlipForConditionalGenerationModelOutputaÖ  
    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 (`tf.Tensor`, *optional*, returned when `labels` is provided, `tf.Tensor` of shape `(1,)`):
            Languge modeling loss from the text decoder.
        logits (`tf.Tensor` of shape `(batch_size, sequence_length, config.vocab_size)`, *optional*):
            Prediction scores of the language modeling head of the text decoder model.
        image_embeds (`tf.Tensor` of shape `(batch_size, output_dim)`, *optional*):
            The image embeddings obtained after applying the Vision Transformer model to the input image.
        last_hidden_state (`tf.Tensor` 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(tf.Tensor)`, *optional*, returned when `output_hidden_states=True`):
            Tuple of `tf.Tensor` (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(tf.Tensor)`, *optional*, returned when `output_attentions=True` is passed):
            Tuple of `tf.Tensor` (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úTuple[tf.Tensor] | NoneÚlossr+   útf.Tensor | NoneÚimage_embedsúOptional[tf.Tensor]Úlast_hidden_stateúTuple[tf.Tensor, ...] | NoneÚ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_logitsz8TFBlipForConditionalGenerationModelOutput.decoder_logitsg   s#   € ä�‰ðWäô	
ð
 �{‰{Ðr.   )Ú__name__Ú
__module__Ú__qualname__Ú__doc__r8   Ú__annotations__r+   r:   r<   r>   r?   ÚpropertyrF   © r.   r,   r6   r6   D   s^   … ñð4 %)€DÐ
!Ó(Ø&*€FÐ#Ó*Ø%)€LÐ"Ó)Ø-1ÐÐ*Ó1Ø26€MÐ/Ó6Ø/3€JÐ,Ó3àñó ñr.   r6   c                  óX   — e Zd ZU dZdZded<   dZded<   dZded<   dZded	<   dZ	ded
<   y)ÚTFBlipTextVisionModelOutputa‘  
    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 (`tf.Tensor` of shape `(1,)`, *optional*, returned when `labels` is provided):
            Languge modeling loss from the text decoder.
        image_embeds (`tf.Tensor` 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 (`tf.Tensor` 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(tf.Tensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
            Tuple of `tf.Tensor` (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(tf.Tensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
            Tuple of `tf.Tensor` (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.
    Nr9   r8   r:   r;   r<   r=   r>   r?   )
rG   rH   rI   rJ   r8   rK   r:   r<   r>   r?   rM   r.   r,   rO   rO   q   sA   … ñð0 "€DÐ
Ó!Ø%)€LÐ"Ó)Ø-1ÐÐ*Ó1Ø26€MÐ/Ó6Ø/3€JÐ,Ô3r.   rO   c                  ó‚   — e Zd ZU dZdZded<   dZded<   dZded<   dZded<   dZ	d	ed
<   dZ
ded<   dZd	ed<   dZded<   y)Ú"TFBlipImageTextMatchingModelOutputa9  
    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 (`tf.Tensor`):
            The image-text similarity scores.
        loss (`tf.Tensor` of shape `(1,)`, *optional*, returned when `labels` is provided):
            Languge modeling loss from the text decoder.
        image_embeds (`tf.Tensor` 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 (`tf.Tensor` 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(tf.Tensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
            Tuple of `tf.Tensor` (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 (`tf.Tensor` of shape `(batch_size, hidden_size)`, *optional*):
            Last layer hidden-state of the vision of the vision-only branch of the model.
        attentions (`tuple(tf.Tensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
            Tuple of `tf.Tensor` (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 (`tf.Tensor`):
            The question embeddings obtained by the text projection layer.
    Nr9   Ú	itm_scorer8   r:   r;   r<   r=   r>   Úvision_pooler_outputr?   r7   Úquestion_embeds)rG   rH   rI   rJ   rR   rK   r8   r:   r<   r>   rS   r?   rT   rM   r.   r,   rQ   rQ   ’   sc   … ñð> #'€IÐÓ&Ø!€DÐ
Ó!Ø%)€LÐ"Ó)Ø-1ÐÐ*Ó1Ø26€MÐ/Ó6Ø-1ÐÐ*Ó1Ø/3€JÐ,Ó3Ø/3€OÐ,Ô3r.   rQ   c                  ó|   — e Zd ZU dZdZded<   dZded<   dZded<   dZded<   dZ	ded	<   dZ
d
ed<   dZd
ed<   dd„Zy)ÚTFBlipOutputaÇ  
    Args:
        loss (`tf.Tensor` of shape `(1,)`, *optional*, returned when `return_loss` is `True`):
            Contrastive loss for image-text similarity.
        logits_per_image:(`tf.Tensor` 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:(`tf.Tensor` 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(`tf.Tensor` of shape `(batch_size, output_dim`):
            The text embeddings obtained by applying the projection layer to the pooled output of [`BlipTextModel`].
        image_embeds(`tf.Tensor` 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`].
    Nr9   r8   r;   Úlogits_per_imageÚlogits_per_textÚtext_embedsr:   r   Útext_model_outputÚvision_model_outputc                óH   ‡ — t        ˆ fd„‰ j                  «       D «       «      S )Nc              3  ód   •K  — | ]'  }|d vr‰|   nt        ‰|«      j                  «       –— Œ) y­w))rZ   r[   N)ÚgetattrÚto_tuple)Ú.0ÚkrE   s     €r,   ú	<genexpr>z(TFBlipOutput.to_tuple.<locals>.<genexpr>Ü   s=   øè ø€ ò 
àð Ð LÑLˆD�ŠGÔRYÐZ^Ð`aÓRb×RkÑRkÓRmÓmñ
ùs   ƒ-0)ÚtupleÚkeysrD   s   `r,   r_   zTFBlipOutput.to_tupleÛ   s#   ø€ Üó 
à—Y‘Y“[ô
ó 
ð 	
r.   )Úreturnz
Tuple[Any])rG   rH   rI   rJ   r8   rK   rW   rX   rY   r:   rZ   r[   r_   rM   r.   r,   rV   rV   ½   s^   … ñð( "€DÐ
Ó!Ø,0ÐÐ)Ó0Ø+/€OÐ(Ó/Ø'+€KÐ$Ó+Ø(,€LÐ%Ó,Ø6:ÐÐ3Ó:Ø8<ÐÐ5Ó<ô
r.   rV   c                  ó0   ‡ — e Zd Zdˆ fd„Zdd„Zdd„Zˆ xZS )ÚTFBlipVisionEmbeddingsc                óÌ  •— t        ‰| �  di |¤Ž || _        |j                  | _        |j
                  | _        |j                  | _        t        j                  j                  | j                  | j                  | j                  t        | j                  j                  «      dd¬«      | _        | j
                  | j                  z  dz  | _        | j                  dz   | _        y )NÚchannels_lastÚpatch_embedding)ÚfiltersÚkernel_sizeÚstridesÚkernel_initializerÚdata_formatÚnameé   r   rM   )ÚsuperÚ__init__ÚconfigÚhidden_sizeÚ	embed_dimÚ
image_sizeÚ
patch_sizer   ÚlayersÚConv2Dr   Úinitializer_rangerj   Únum_patchesÚnum_positions©rE   rt   ÚkwargsÚ	__class__s      €r,   rs   zTFBlipVisionEmbeddings.__init__ã   s¹   ø€ Ü‰ÑÑ"˜6Ò"ØˆŒØ×+Ñ+ˆŒØ ×+Ñ+ˆŒØ ×+Ñ+ˆŒä$Ÿ|™|×2Ñ2Ø—N‘NØŸ™Ø—O‘OÜ.¨t¯{©{×/LÑ/LÓMØ'Ø"ð  3ó  
ˆÔð !ŸO™O¨t¯©Ñ>À1ÑDˆÔØ!×-Ñ-°Ñ1ˆÕr.   c                ó"  — | j                  dd| j                  ft        | j                  j                  «      dd¬«      | _        | j                  d| j                  | j                  ft        | j                  j                  «      dd¬«      | _        | j                  ry d| _        t        | dd «      �Pt        j                  | j                  j                  «      5  | j                  j                  g d¢«       d d d «       y y # 1 sw Y   y xY w)Nr   TÚclass_embedding©ÚshapeÚinitializerÚ	trainablerp   Úposition_embeddingrj   )NNNr	   )Ú
add_weightrv   r   rt   r{   r‚   r}   r‡   Úbuiltr^   r%   Ú
name_scoperj   rp   Úbuild©rE   Úinput_shapes     r,   r‹   zTFBlipVisionEmbeddings.buildö   sö   € Ø#Ÿ™Ø�a˜Ÿ™Ð(Ü'¨¯©×(EÑ(EÓFØØ"ð	  /ó  
ˆÔð #'§/¡/Ø�d×(Ñ(¨$¯.©.Ð9Ü'¨¯©×(EÑ(EÓFØØ%ð	 #2ó #
ˆÔð �:Š:ØØˆŒ
Ü�4Ð*¨DÓ1Ð=Ü—‘˜t×3Ñ3×8Ñ8Ó9ñ BØ×$Ñ$×*Ñ*Ò+@ÔA÷Bð Bð >÷Bð Bús   ÃDÄDc                óº  — t        j                  |«      d   }t        j                  |d¬«      }| j                  |«      }t        j                  ||| j
                  df«      }t        j                  | j                  |d| j                  f«      }t        j                  ||gd¬«      }|| j                  d d …d t        j                  |«      d   …d d …f   z   }|S )Nr   )r   rq   r	   r   ©Úperméÿÿÿÿr   ©Úaxis)r%   r„   r0   rj   Úreshaper|   Úbroadcast_tor‚   rv   Úconcatr‡   )rE   Úpixel_valuesÚ
batch_sizeÚpatch_embedsÚclass_embedsÚ
embeddingss         r,   ÚcallzTFBlipVisionEmbeddings.call  sÂ   € ô —X‘X˜lÓ+¨AÑ.ˆ
Ü—|‘| L°|ÔDˆØ×+Ñ+¨LÓ9ˆÜ—z‘z ,°¸T×=MÑ=MÈrÐ0RÓSˆä—‘ t×';Ñ';¸jÈ!ÈTÏ^É^Ð=\Ó]ˆÜ—Y‘Y ¨lÐ;À!ÔDˆ
Ø $×"9Ñ"9º!Ð=V¼r¿x¹xÈ
Ó?SÐTUÑ?VÐ=VÒXYÐ:YÑ"ZÑZˆ
ØÐr.   ©rt   r   ©N)r—   ú	tf.Tensorre   rŸ   ©rG   rH   rI   rs   r‹   rœ   Ú__classcell__©r€   s   @r,   rg   rg   â   s   ø„ õ2ó&B÷,r.   rg   c                  óL   ‡ — e Zd Zdˆ fd„Zddˆ fd„Z	 	 	 d	 	 	 	 	 	 	 dd„Zˆ xZS )	ÚTFBlipTextEmbeddingsc                óT   •— t        ‰| �  di |¤Ž |j                  | _        || _        y )NrM   )rr   rs   ru   rv   rt   r~   s      €r,   rs   zTFBlipTextEmbeddings.__init__  s'   ø€ Ü‰ÑÑ"˜6Ò"à×+Ñ+ˆŒàˆ�r.   c                ó„  •— t        j                  d«      5  | j                  | j                  j                  | j
                  ft        | j                  j                  | j                  j                  z  «      dd¬«      | _	        d d d «       t        j                  d«      5  | j                  | j                  j                  | j
                  ft        | j                  j                  | j                  j                  z  «      dd¬«      | _        d d d «       t        ‰| �5  |«       y # 1 sw Y   Œ¥xY w# 1 sw Y   Œ%xY w)NÚtoken_embeddingTÚweightrƒ   r‡   r›   )r%   rŠ   rˆ   rt   Ú
vocab_sizerv   r   Úinitializer_factorr{   r¨   Úmax_position_embeddingsr‡   rr   r‹   )rE   r�   r€   s     €r,   r‹   zTFBlipTextEmbeddings.build#  sü   ø€ Ü�]‰]Ð,Ó-ñ 	ØŸ/™/Ø—{‘{×-Ñ-¨t¯~©~Ð>Ü+¨D¯K©K×,JÑ,JÈTÏ[É[×MjÑMjÑ,jÓkØØð	 *ó ˆDŒK÷	ô �]‰]Ð/Ó0ñ 	Ø&*§o¡oØ—{‘{×:Ñ:¸D¿N¹NÐKÜ+¨D¯K©K×,JÑ,JÈTÏ[É[×MjÑMjÑ,jÓkØØ!ð	 '6ó 'ˆDÔ#÷	ô 	‰‰�kÕ"÷!	ð 	ú÷	ð 	ús   —A/D*Â#A/D6Ä*D3Ä6D?c                ó®  — |€|€t        d«      ‚|€At        || j                  j                  «       t	        j
                  | j                  |¬«      }t        |«      dd }|€/t	        j                  t	        j                  d|d   ¬«      d¬«      }t	        j
                  | j                  |¬«      }t	        j                  ||d   ddf¬	«      }||z   }|S )
z’
        Applies embedding based on inputs tensor.

        Returns:
            final_embeddings (`tf.Tensor`): output embedding tensor.
        Nz5You have to specify either input_ids or inputs_embeds)ÚparamsÚindicesr‘   r   )ÚstartÚlimitr’   r   )ÚinputÚ	multiples)Ú
ValueErrorr   rt   r©   r%   Úgatherr¨   r   Úexpand_dimsr*   r‡   Útile)rE   Ú	input_idsÚposition_idsÚinputs_embedsr�   Úposition_embedsÚfinal_embeddingss          r,   rœ   zTFBlipTextEmbeddings.call6  sÅ   € ð Ð Ð!6ÜÐTÓUÐUàÐ Ü*¨9°d·k±k×6LÑ6LÔMÜŸI™I¨T¯[©[À)ÔLˆMä  Ó/°°Ð4ˆàÐÜŸ>™>¬"¯(©(¸À+ÈbÁ/Ô*RÐYZÔ[ˆLäŸ)™)¨4×+BÑ+BÈLÔYˆÜŸ'™'¨ÀKÐPQÁNÐTUÐWXÐCYÔZˆØ(¨?Ñ:ÐàÐr.   )rt   r   rž   )r�   ztf.TensorShape)NNN)r·   r;   r¸   r;   r¹   r;   re   rŸ   r    r¢   s   @r,   r¤   r¤     sC   ø„ õö#ð* *.Ø,0Ø-1ð	 à&ð ð *ð ð +ð	 ð
 
÷ r.   r¤   c                  óL   ‡ — e Zd ZdZˆ fd„Z	 	 	 d	 	 	 	 	 	 	 	 	 dd„Zdd„Zˆ xZS )ÚTFBlipAttentionz=Multi-headed attention from 'Attention Is All You Need' paperc                óè  •— t        ‰| �  di |¤Ž || _        |j                  | _        |j
                  | _        | j                  | j                  z  | _        | j                  | j                  z  | j                  k7  r&t        d| j                  › d| j                  › d�«      ‚| j                  dz  | _	        t        j                  j                  |j                  d¬«      | _        t        j                  j                  d| j                  z  t!        |j"                  «      d¬	«      | _        t        j                  j                  | j                  t!        |j"                  «      d
¬	«      | _        y )Nz;embed_dim must be divisible by num_heads (got `embed_dim`: z and `num_heads`: z).ç      à¿Údropout©rp   r	   Úqkv©rn   rp   Ú
projectionrM   )rr   rs   rt   ru   rv   Únum_attention_headsÚ	num_headsÚhead_dimr³   Úscaler   ry   ÚDropoutÚattention_dropoutrÀ   ÚDenser   r{   rÂ   rÄ   r~   s      €r,   rs   zTFBlipAttention.__init__X  s/  ø€ Ü‰ÑÑ"˜6Ò"ØˆŒØ×+Ñ+ˆŒØ×3Ñ3ˆŒØŸ™¨$¯.©.Ñ8ˆŒØ�=‰=˜4Ÿ>™>Ñ)¨T¯^©^Ò;ÜØMÈdÏnÉnÐM]ð ^Ø—N‘NÐ# 2ð'óð ð —]‘] DÑ(ˆŒ
Ü—|‘|×+Ñ+¨F×,DÑ,DÈ9Ð+ÓUˆŒä—<‘<×%Ñ%Ø�—‘Ñ´?À6×C[ÑC[Ó3\Ðchð &ó 
ˆŒô  Ÿ,™,×,Ñ,Ø�N‰N¬¸v×?WÑ?WÓ/XÐ_kð -ó 
ˆ�r.   c                ó`  — t        |«      \  }}}| j                  |«      }t        j                  |||d| j                  | j
                  f«      }t        j                  |d¬«      }|d   |d   |d   }}
}	|	t        j                  |
d«      z  }|| j                  z  }t        |d¬	«      }| j                  ||¬
«      }|�||z  }t        j                  ||z  d¬«      }t        |«      dd | j                  gz   }t        j                  ||«      }| j                  |«      }|r||f}|S |df}|S )z#Input shape: Batch x Time x Channelr	   )rq   r   r	   r   é   r�   r   r   rq   )r   r   r	   rq   r‘   r’   )ÚtrainingN)r   rq   r   r	   éþÿÿÿ)r   rÂ   r%   r”   rÆ   rÇ   r0   rÈ   r   rÀ   rv   rÄ   )rE   r>   Ú	head_maskÚoutput_attentionsrÎ   ÚbszÚtgt_lenrv   Ú	mixed_qkvÚquery_statesÚ
key_statesÚvalue_statesÚattention_scoresÚattention_probsÚcontext_layerÚnew_context_layer_shapeÚoutputÚoutputss                     r,   rœ   zTFBlipAttention.calln  sA  € ô #-¨]Ó";ÑˆˆW�ià—H‘H˜]Ó+ˆ	Ü—J‘J˜y¨3°¸¸D¿N¹NÈDÏMÉMÐ*ZÓ[ˆ	Ü—L‘L °ÔAˆ	à1:¸1±¸yÈ¹|ÈYÐWXÉ\ ,�jˆð (¬"¯,©,°zÀ<Ó*PÑPÐà+¨d¯j©jÑ8Ðô )Ð)9ÀÔCˆð Ÿ,™, À˜,ÓJˆð Ð Ø-°	Ñ9ˆOäŸ™ _°|Ñ%CÈ,ÔWˆä",¨]Ó";¸C¸RÐ"@ÀDÇNÁNÐCSÑ"SÐÜŸ
™
 =Ð2IÓJˆà—‘ Ó/ˆá/@�6˜?Ð+ˆàˆð HNÈtÀnˆàˆr.   c                óÆ  — | j                   ry d| _         t        | dd «      �Mt        j                  | j                  j
                  «      5  | j                  j                  d «       d d d «       t        | dd «      �Zt        j                  | j                  j
                  «      5  | j                  j                  d d | j                  g«       d d d «       t        | dd «      �[t        j                  | j                  j
                  «      5  | j                  j                  d d | j                  g«       d d d «       y y # 1 sw Y   ŒÙxY w# 1 sw Y   Œ~xY w# 1 sw Y   y xY w)NTrÀ   rÂ   rÄ   )
r‰   r^   r%   rŠ   rÀ   rp   r‹   rÂ   rv   rÄ   rŒ   s     r,   r‹   zTFBlipAttention.buildš  s  € Ø�:Š:ØØˆŒ
Ü�4˜ DÓ)Ð5Ü—‘˜tŸ|™|×0Ñ0Ó1ñ )Ø—‘×"Ñ" 4Ô(÷)ä�4˜ Ó%Ð1Ü—‘˜tŸx™xŸ}™}Ó-ñ =Ø—‘—‘  d¨D¯N©NÐ;Ô<÷=ä�4˜ tÓ,Ð8Ü—‘˜tŸ™×3Ñ3Ó4ñ DØ—‘×%Ñ% t¨T°4·>±>Ð&BÔC÷Dð Dð 9÷)ð )ú÷=ð =ú÷Dð Dús$   ÁD?Â%)EÄ)EÄ?EÅEÅE )NFN)
r>   rŸ   rÐ   r9   rÑ   úOptional[bool]rÎ   rß   re   z;Tuple[tf.Tensor, tf.Tensor | None, Tuple[tf.Tensor] | None]rž   )rG   rH   rI   rJ   rs   rœ   r‹   r¡   r¢   s   @r,   r½   r½   U  sS   ø„ ÙGô
ð2 '+Ø,1Ø#'ð*à ð*ð $ð*ð *ð	*ð
 !ð*ð 
Eó*÷XDr.   r½   c                  ó0   ‡ — e Zd Zdˆ fd„Zdd„Zdd„Zˆ xZS )Ú	TFBlipMLPc                ó¶  •— t        ‰| �  di |¤Ž t        |j                  «      | _        |j
                  dz  d|j                  z  dz  z  }d|j
                  z  dz  }t        j                  j                  |j                  t        |«      d¬«      | _        t        j                  j                  |j
                  t        |«      d¬«      | _        || _        y )Nr¿   rq   Úfc1)Úunitsrn   rp   Úfc2rM   )rr   rs   r   Ú
hidden_actÚactivation_fnru   Únum_hidden_layersr   ry   rË   Úintermediate_sizer   rã   rå   rt   )rE   rt   r   Úin_proj_stdÚfc_stdr€   s        €r,   rs   zTFBlipMLP.__init__ª  sÈ   ø€ Ü‰ÑÑ"˜6Ò"ä.¨v×/@Ñ/@ÓAˆÔà×)Ñ)¨4Ñ/°Q¸×9QÑ9QÑ5QÐVZÑ4ZÑ[ˆØ�f×(Ñ(Ñ(¨TÑ1ˆä—<‘<×%Ñ%Ø×*Ñ*¼ÈvÓ?VÐ]bð &ó 
ˆŒô —<‘<×%Ñ%Ø×$Ñ$¼ÈÓ9UÐ\að &ó 
ˆŒð ˆ�r.   c                óp   — | j                  |¬«      }| j                  |«      }| j                  |¬«      }|S )N)Úinputs)rã   rç   rå   )rE   r>   s     r,   rœ   zTFBlipMLP.callº  s8   € ØŸ™¨˜Ó6ˆØ×*Ñ*¨=Ó9ˆØŸ™¨˜Ó6ˆØÐr.   c                ó"  — | j                   ry d| _         t        | dd «      �dt        j                  | j                  j
                  «      5  | j                  j                  d d | j                  j                  g«       d d d «       t        | dd «      �et        j                  | j                  j
                  «      5  | j                  j                  d d | j                  j                  g«       d d d «       y y # 1 sw Y   Œ|xY w# 1 sw Y   y xY w)NTrã   rå   )r‰   r^   r%   rŠ   rã   rp   r‹   rt   ru   rå   ré   rŒ   s     r,   r‹   zTFBlipMLP.buildÀ  sØ   € Ø�:Š:ØØˆŒ
Ü�4˜ Ó%Ð1Ü—‘˜tŸx™xŸ}™}Ó-ñ FØ—‘—‘  d¨D¯K©K×,CÑ,CÐDÔE÷Fä�4˜ Ó%Ð1Ü—‘˜tŸx™xŸ}™}Ó-ñ LØ—‘—‘  d¨D¯K©K×,IÑ,IÐJÔK÷Lð Lð 2÷Fð Fú÷Lð Lús   Á3C9Â<3DÃ9DÄD©rt   r   )r>   rŸ   re   rŸ   rž   ©rG   rH   rI   rs   rœ   r‹   r¡   r¢   s   @r,   rá   rá   ©  s   ø„ õó ÷	Lr.   rá   c                  óH   ‡ — e Zd Zdˆ fd„Z	 	 d	 	 	 	 	 	 	 	 	 dd„Zdd„Zˆ xZS )ÚTFBlipEncoderLayerc                óN  •— t        ‰| �  di |¤Ž |j                  | _        t	        |d¬«      | _        t        j                  j                  |j                  d¬«      | _
        t        |d¬«      | _        t        j                  j                  |j                  d¬«      | _        y )NÚ	self_attnrÁ   Úlayer_norm1©Úepsilonrp   ÚmlpÚlayer_norm2rM   )rr   rs   ru   rv   r½   rô   r   ry   ÚLayerNormalizationÚlayer_norm_epsrõ   rá   rø   rù   r~   s      €r,   rs   zTFBlipEncoderLayer.__init__Í  s‚   ø€ Ü‰ÑÑ"˜6Ò"Ø×+Ñ+ˆŒÜ(¨°kÔBˆŒÜ Ÿ<™<×:Ñ:À6×CXÑCXÐ_lÐ:ÓmˆÔÜ˜V¨%Ô0ˆŒÜ Ÿ<™<×:Ñ:À6×CXÑCXÐ_lÐ:ÓmˆÕr.   c                óÎ   — |}| j                  |«      }| j                  ||||¬«      \  }}||z   }|}| j                  |«      }| j                  |«      }||z   }|f}|r||fz  }|S )a9  
        Args:
            hidden_states (`tf.Tensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
            attention_mask (`tf.Tensor`): 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.
        )r>   rÐ   rÑ   rÎ   )rõ   rô   rù   rø   )rE   r>   Úattention_maskrÑ   rÎ   ÚresidualÚattn_weightsrÝ   s           r,   rœ   zTFBlipEncoderLayer.callÕ  s’   € ð" !ˆà×(Ñ(¨Ó7ˆØ&*§n¡nØ'Ø$Ø/Øð	 '5ó '
Ñ#ˆ�|ð &¨Ñ0ˆØ ˆØ×(Ñ(¨Ó7ˆØŸ™ Ó/ˆà%¨Ñ0ˆà Ð"ˆáØ˜�Ñ&ˆGàˆr.   c                ó”  — | j                   ry d| _         t        | dd «      �Mt        j                  | j                  j
                  «      5  | j                  j                  d «       d d d «       t        | dd «      �Zt        j                  | j                  j
                  «      5  | j                  j                  d d | j                  g«       d d d «       t        | dd «      �Mt        j                  | j                  j
                  «      5  | j                  j                  d «       d d d «       t        | dd «      �[t        j                  | j                  j
                  «      5  | j                  j                  d d | j                  g«       d d d «       y y # 1 sw Y   �Œ4xY w# 1 sw Y   ŒÙxY w# 1 sw Y   Œ‹xY w# 1 sw Y   y xY w)NTrô   rõ   rø   rù   )r‰   r^   r%   rŠ   rô   rp   r‹   rõ   rv   rø   rù   rŒ   s     r,   r‹   zTFBlipEncoderLayer.buildý  sp  € Ø�:Š:ØØˆŒ
Ü�4˜ dÓ+Ð7Ü—‘˜tŸ~™~×2Ñ2Ó3ñ +Ø—‘×$Ñ$ TÔ*÷+ä�4˜¨Ó-Ð9Ü—‘˜t×/Ñ/×4Ñ4Ó5ñ EØ× Ñ ×&Ñ&¨¨d°D·N±NÐ'CÔD÷Eä�4˜ Ó%Ð1Ü—‘˜tŸx™xŸ}™}Ó-ñ %Ø—‘—‘˜tÔ$÷%ä�4˜¨Ó-Ð9Ü—‘˜t×/Ñ/×4Ñ4Ó5ñ EØ× Ñ ×&Ñ&¨¨d°D·N±NÐ'CÔD÷Eð Eð :÷+ñ +ú÷Eð Eú÷%ð %ú÷Eð Eús0   ÁFÂ%)F&ÄF2Å&)F>ÆF#Æ&F/Æ2F;Æ>Grï   )FN)
r>   rŸ   rý   rŸ   rÑ   rß   rÎ   rß   re   zTuple[tf.Tensor]rž   rð   r¢   s   @r,   rò   rò   Ì  sM   ø„ õnð -2Ø#'ð&à ð&ð "ð&ð *ð	&ð
 !ð&ð 
ó&÷PEr.   rò   c                  ó   — e Zd ZdZeZdZdgZy)ÚTFBlipPreTrainedModelz†
    An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
    models.
    Úblipr¸   N)rG   rH   rI   rJ   r   Úconfig_classÚbase_model_prefixÚ_keys_to_ignore_on_load_missingrM   r.   r,   r  r    s   „ ñð
 €LØÐØ'6Ð&7Ñ#r.   r  a:  
    This model inherits from [`TFPreTrainedModel`]. 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 [keras.Model](https://www.tensorflow.org/api_docs/python/tf/keras/Model) subclass. Use it
    as a regular TF 2.0 Keras Model and refer to the TF 2.0 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 [`~TFPreTrainedModel.from_pretrained`] method to load the model weights.
a=  
    Args:
        pixel_values (`tf.Tensor` 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.
aÇ  
    Args:
        input_ids (`tf.Tensor` 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 (`tf.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 (`tf.Tensor` 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 (`tf.Tensor` 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.
c                  ób   ‡ — e Zd ZeZ	 dˆ fd„Ze	 	 	 	 	 d	 	 	 	 	 	 	 	 	 	 	 dd„«       Zdd„Zˆ xZ	S )ÚTFBlipEncoderc                ó¨   •— t        ‰| �  di |¤Ž || _        t        |j                  «      D �cg c]  }t        |d|› �¬«      ‘Œ c}| _        y c c}w )Nz	layers_._rÁ   rM   )rr   rs   rt   r*   rè   rò   ry   )rE   rt   r   Úir€   s       €r,   rs   zTFBlipEncoder.__init__i  sI   ø€ Ü‰ÑÑ"˜6Ò"ØˆŒÜQVÐW]×WoÑWoÓQpÖqÈAÔ)¨&¸À1À#°ÖGÒqˆ�ùÒqs   ¯Ac                ó˜  — |�|n| j                   j                  }|�|n| j                   j                  }|�|n| j                   j                  }|rdnd}|rdnd}|}	t	        | j
                  «      D ]*  \  }
}|r||	fz   } ||	|||¬«      }|d   }	|sŒ"||d   fz   }Œ, |r||	fz   }|st        d„ |	||fD «       «      S t        |	||¬«      S )a  
        Args:
            inputs_embeds (`tf.Tensor` of shape `(batch_size, sequence_length, hidden_size)`):
                Embedded representation of the inputs. Should be float, not int tokens.
            attention_mask (`tf.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.
        NrM   )rÑ   rÎ   r   r   c              3  ó&   K  — | ]	  }|€Œ|–— Œ y ­wrž   rM   )r`   Úvs     r,   rb   z%TFBlipEncoder.call.<locals>.<genexpr>©  s   è ø€ Òe˜qÐWXÑWdœÑeùó   ‚Š)r<   r>   r?   )rt   rÑ   Úoutput_hidden_statesÚuse_return_dictÚ	enumeratery   rc   r
   )rE   r¹   rý   rÑ   r  Úreturn_dictrÎ   Úencoder_statesÚall_attentionsr>   ÚidxÚencoder_layerÚlayer_outputss                r,   rœ   zTFBlipEncoder.calln  s  € ð< 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�Ù)ØØØ"3Ø!ô	ˆMð *¨!Ñ,ˆMâ Ø!/°=ÀÑ3CÐ2EÑ!E‘ð	Fñ  Ø+¨}Ð.>Ñ>ˆNáÜÑe ]°NÀNÐ$SÔeÓeÐeÜ Ø+¸>ÐVdô
ð 	
r.   c                óô   — | j                   ry d| _         t        | dd «      �K| j                  D ];  }t        j                  |j
                  «      5  |j                  d «       d d d «       Œ= y y # 1 sw Y   ŒIxY w)NTry   )r‰   r^   ry   r%   rŠ   rp   r‹   )rE   r�   Úlayers      r,   r‹   zTFBlipEncoder.build®  sp   € Ø�:Š:ØØˆŒ
Ü�4˜ 4Ó(Ð4ØŸ™ò &�Ü—]‘] 5§:¡:Ó.ñ &Ø—K‘K Ô%÷&ð &ñ&ð 5÷&ð &ús   ÁA.Á.A7	rï   ©NNNNN)rý   r9   rÑ   rß   r  rß   r  rß   rÎ   rß   re   zUnion[Tuple, TFBaseModelOutput]rž   )
rG   rH   rI   r   r  rs   r   rœ   r‹   r¡   r¢   s   @r,   r  r  ]  sz   ø„ à€Lðõrð
 ð ,0Ø,0Ø/3Ø&*Ø#'ð=
ð )ð=
ð *ð	=
ð
 -ð=
ð $ð=
ð !ð=
ð 
)ò=
ó ð=
÷~&r.   r  c                  ó¢   ‡ — e Zd ZdZeZdˆ fd„Zd	d„Ze e	e
«       eee¬«      	 	 	 	 	 d
	 	 	 	 	 	 	 	 	 	 	 dd„«       «       «       Zd„ Zdd„Zˆ xZS )ÚTFBlipVisionModelr—   c                ó  •— t        ‰| �  |g|¢­i |¤Ž || _        t        |d¬«      | _        t        |d¬«      | _        t        j                  j                  |j                  d¬«      | _        |j                  | _        y )Nr›   rÁ   ÚencoderÚpost_layernormrö   )rr   rs   rt   rg   r›   r  r  r   ry   rú   rû   r  ru   rv   ©rE   rt   Úargsr   r€   s       €r,   rs   zTFBlipVisionModel.__init__¼  sm   ø€ Ü‰Ñ˜Ð1 $Ò1¨&Ò1ØˆŒä0°¸lÔKˆŒÜ$ V°)Ô<ˆŒÜ#Ÿl™l×=Ñ=Àf×F[ÑF[ÐbrÐ=ÓsˆÔØ×+Ñ+ˆ�r.   c                ó$  — | j                   j                  rt        j                  |j                  «      nd }| j                   j
                  rt        j                  |j                  «      nd }t        |j                  |j                  ||¬«      S )N©r<   Úpooler_outputr>   r?   )
rt   r  r%   Úconvert_to_tensorr>   rÑ   r?   r   r<   r$  )rE   rÜ   ÚhsÚattnss       r,   Úserving_outputz TFBlipVisionModel.serving_outputÅ  sq   € Ø;?¿;¹;×;[Ò;[ŒR×!Ñ! &×"6Ñ"6Ô7ÐaeˆØ;?¿;¹;×;XÒ;X”×$Ñ$ V×%6Ñ%6Ô7Ð^bˆä+Ø$×6Ñ6Ø ×.Ñ.ØØô	
ð 	
r.   ©Úoutput_typer  c                ó  — |�|n| j                   j                  }|�|n| j                   j                  }|�|n| j                   j                  }|€t	        d«      ‚| j                  |«      }| j                  |||||¬«      }|d   }| j                  |«      }|dd…ddd…f   }	| j                  t        j                  |	d«      «      }	t        j                  |	d«      }	|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   r#  )rt   rÑ   r  r  r³   r›   r  r  r%   rµ   Úsqueezer   r>   r?   )
rE   r—   rÑ   r  r  rÎ   r>   Úencoder_outputsr<   Úpooled_outputs
             r,   rœ   zTFBlipVisionModel.callÐ  s-  € ð 2CÐ1NÑ-ÐTX×T_ÑT_×TqÑTqÐà$8Ð$DÑ È$Ï+É+×JjÑJjð 	ð &1Ð%<‘kÀ$Ç+Á+×B]ÑB]ˆàÐÜÐ?Ó@Ð@àŸ™¨Ó5ˆàŸ,™,Ø'Ø/Ø!5Ø#Øð 'ó 
ˆð ,¨AÑ.ÐØ ×/Ñ/Ð0AÓBÐà)ª!¨Q²¨'Ñ2ˆà×+Ñ+¬B¯N©N¸=È!Ó,LÓMˆÜŸ
™
 =°!Ó4ˆáØ% }Ð5¸ÈÈÐ8KÑKÐKä+Ø/Ø'Ø)×7Ñ7Ø&×1Ñ1ô	
ð 	
r.   c                ó   — | j                   S rž   )r›   rD   s    r,   Úget_input_embeddingsz&TFBlipVisionModel.get_input_embeddings  s   € Ø�‰Ðr.   c                ó¬  — | j                   ry d| _         t        | dd «      �Mt        j                  | j                  j
                  «      5  | j                  j                  d «       d d d «       t        | dd «      �Mt        j                  | j                  j
                  «      5  | j                  j                  d «       d d d «       t        | dd «      �[t        j                  | j                  j
                  «      5  | j                  j                  d d | j                  g«       d d d «       y y # 1 sw Y   ŒÌxY w# 1 sw Y   Œ~xY w# 1 sw Y   y xY w)NTr›   r  r  )
r‰   r^   r%   rŠ   r›   rp   r‹   r  r  rv   rŒ   s     r,   r‹   zTFBlipVisionModel.build  s  € Ø�:Š:ØØˆŒ
Ü�4˜ tÓ,Ð8Ü—‘˜tŸ™×3Ñ3Ó4ñ ,Ø—‘×%Ñ% dÔ+÷,ä�4˜ DÓ)Ð5Ü—‘˜tŸ|™|×0Ñ0Ó1ñ )Ø—‘×"Ñ" 4Ô(÷)ä�4Ð)¨4Ó0Ð<Ü—‘˜t×2Ñ2×7Ñ7Ó8ñ HØ×#Ñ#×)Ñ)¨4°°t·~±~Ð*FÔG÷Hð Hð =÷,ð ,ú÷)ð )ú÷Hð Hús$   ÁD2Â%D>Ã?)E
Ä2D;Ä>EÅ
Er�   )rÜ   r   re   r   r  )r—   r9   rÑ   rß   r  rß   r  rß   rÎ   rß   re   z*Union[Tuple, TFBaseModelOutputWithPooling]rž   )rG   rH   rI   Úmain_input_namer   r  rs   r(  r   r   ÚBLIP_VISION_INPUTS_DOCSTRINGr   r   rœ   r0  r‹   r¡   r¢   s   @r,   r  r  ¸  s£   ø„ Ø$€OØ#€Lõ,ó	
ð Ù*Ð+GÓHÙÐ+GÐVfÔgð *.Ø,0Ø/3Ø&*Ø#'ð/
à&ð/
ð *ð/
ð -ð	/
ð
 $ð/
ð !ð/
ð 
4ò/
ó hó Ió ð/
òb÷Hr.   r  c                  óx   ‡ — e Zd ZeZdˆ fd„Zdd„Ze	 	 	 	 	 	 	 	 	 d	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 dd„«       Zˆ xZ	S )ÚTFBlipMainLayerc                ó  •— t        ‰| �  |i |¤Ž t        |j                  t        «      s"t        dt        |j                  «      › d�«      ‚t        |j                  t        «      s"t        dt        |j                  «      › d�«      ‚|j                  }|j                  }|j                  | _	        |j                  | _        |j                  | _        t        |d¬«      | _        t        |d¬«      | _        t"        j$                  j'                  | j                  dt)        |j*                  «      d¬	«      | _        t"        j$                  j'                  | j                  dt)        |j*                  «      d
¬	«      | _        || _        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 Ú
text_modelrÁ   Úvision_modelFÚvisual_projection)Úuse_biasrn   rp   Útext_projection)rr   rs   Ú
isinstanceÚtext_configr   Ú	TypeErrorÚtypeÚvision_configr   Úprojection_dimru   Útext_embed_dimÚvision_embed_dimr    r8  r  r9  r   ry   rË   r   r{   r:  r<  rt   )rE   rt   r!  r   r>  rA  r€   s         €r,   rs   zTFBlipMainLayer.__init__  sh  ø€ Ü‰Ñ˜$Ð) &Ò)ä˜&×,Ñ,¬nÔ=ÜðÜ˜×+Ñ+Ó,Ð-¨Qð0óð ô
 ˜&×.Ñ.Ô0@ÔAÜðÜ˜×-Ñ-Ó.Ð/¨qð2óð ð
 ×(Ñ(ˆØ×,Ñ,ˆà$×3Ñ3ˆÔØ)×5Ñ5ˆÔØ -× 9Ñ 9ˆÔä)¨+¸LÔIˆŒÜ-¨mÀ.ÔQˆÔä!&§¡×!3Ñ!3Ø×ÑØÜ.¨v×/GÑ/GÓHØ$ð	 "4ó "
ˆÔô  %Ÿ|™|×1Ñ1Ø×ÑØÜ.¨v×/GÑ/GÓHØ"ð	  2ó  
ˆÔð ˆ�r.   c                ó*  — | j                  dg t        j                  j                  | j                  j
                  «      d¬«      | _        | j                  ry d| _        t        | dd «      �Mt        j                  | j                  j                  «      5  | j                  j                  d «       d d d «       t        | dd «      �Mt        j                  | j                  j                  «      5  | j                  j                  d «       d d d «       t        | dd «      �Zt        j                  | j                  j                  «      5  | j                  j                  d d | j                   g«       d d d «       t        | dd «      �[t        j                  | j"                  j                  «      5  | j"                  j                  d d | j$                  g«       d d d «       y y # 1 sw Y   �Œ4xY w# 1 sw Y   ŒæxY w# 1 sw Y   Œ‹xY w# 1 sw Y   y xY w)NÚlogit_scaleT)rp   r„   r…   r†   r8  r9  r:  r<  )rˆ   r   ÚinitializersÚConstantrt   Úlogit_scale_init_valuerF  r‰   r^   r%   rŠ   r8  rp   r‹   r9  r:  rD  r<  rC  rŒ   s     r,   r‹   zTFBlipMainLayer.buildA  s½  € ØŸ?™?ØØÜ×*Ñ*×3Ñ3°D·K±K×4VÑ4VÓWØð	 +ó 
ˆÔð �:Š:ØØˆŒ
Ü�4˜ tÓ,Ð8Ü—‘˜tŸ™×3Ñ3Ó4ñ ,Ø—‘×%Ñ% dÔ+÷,ä�4˜¨Ó.Ð:Ü—‘˜t×0Ñ0×5Ñ5Ó6ñ .Ø×!Ñ!×'Ñ'¨Ô-÷.ä�4Ð,¨dÓ3Ð?Ü—‘˜t×5Ñ5×:Ñ:Ó;ñ RØ×&Ñ&×,Ñ,¨d°D¸$×:OÑ:OÐ-PÔQ÷Rä�4Ð*¨DÓ1Ð=Ü—‘˜t×3Ñ3×8Ñ8Ó9ñ NØ×$Ñ$×*Ñ*¨D°$¸×8KÑ8KÐ+LÔM÷Nð Nð >÷,ñ ,ú÷.ð .ú÷Rð Rú÷Nð Nús0   ÂG$Ã0G1Å
)G=Æ1)H	Ç$G.Ç1G:Ç=HÈ	Hc
           	     óö  — |�|n| j                   j                  }|�|n| j                   j                  }|�|n| j                   j                  }| j	                  |||||	¬«      }
| j                  |||||||	¬«      }|
d   }| j                  |«      }|d   }| j                  |«      }|t        j                  |ddd¬«      z  }|t        j                  |ddd¬«      z  }t        j                  | j                  «      }t        j                  ||d¬«      |z  }t        j                  |«      }d }|r!t        |«      }t        j                  |d	«      }|s||||||
f}|�|f|z   S |S t!        |||||||
¬
«      S )N©r—   rÑ   r  r  rÎ   )r·   rý   r¸   rÑ   r  r  rÎ   r   rq   r‘   T)Úordr“   Úkeepdims©Útranspose_b©r   )r8   rW   rX   rY   r:   rZ   r[   )rt   rÑ   r  r  r9  r8  r:  r<  r%   ÚnormÚexprF  Úmatmulr0   r4   r”   rV   )rE   r·   r—   rý   r¸   Úreturn_lossrÑ   r  r  rÎ   Úvision_outputsÚtext_outputsr:   rY   rF  rX   rW   r8   rÜ   s                      r,   rœ   zTFBlipMainLayer.callY  sº  € ð 2CÐ1NÑ-ÐTX×T_ÑT_×TqÑTqÐà$8Ð$DÑ È$Ï+É+×JjÑJjð 	ð &1Ð%<‘kÀ$Ç+Á+×B]ÑB]ˆà×*Ñ*Ø%Ø/Ø!5Ø#Øð +ó 
ˆð —‘ØØ)Ø%Ø/Ø!5Ø#Øð 'ó 
ˆð & aÑ(ˆØ×-Ñ-¨lÓ;ˆà" 1‘oˆØ×*Ñ*¨;Ó7ˆð $¤b§g¡g¨lÀÈÐUYÔ&ZÑZˆØ!¤B§G¡G¨K¸QÀRÐRVÔ$WÑWˆô —f‘f˜T×-Ñ-Ó.ˆÜŸ)™) K°È4ÔPÐS^Ñ^ˆÜŸ<™<¨Ó8ÐàˆÙÜ˜_Ó-ˆDÜ—:‘:˜d DÓ)ˆDáØ&¨¸ÀlÐT`ÐbpÐqˆFØ)-Ð)9�T�G˜fÑ$ÐE¸vÐEäØØ-Ø+Ø#Ø%Ø*Ø .ô
ð 	
r.   rï   rž   ©	NNNNNNNNN©r·   r9   r—   r9   rý   r9   r¸   r9   rT  rß   rÑ   rß   r  rß   r  rß   rÎ   rß   re   zUnion[Tuple, TFBlipOutput])
rG   rH   rI   r   r  rs   r‹   r   rœ   r¡   r¢   s   @r,   r5  r5    s³   ø„ Ø€Lõ&óPNð0 ð '+Ø)-Ø+/Ø)-Ø&*Ø,0Ø/3Ø&*Ø#'ðE
à#ðE
ð 'ðE
ð )ð	E
ð
 'ðE
ð $ðE
ð *ðE
ð -ðE
ð $ðE
ð !ðE
ð 
$òE
ó ôE
r.   r5  c                  ó"  ‡ — e Zd ZeZdgZdZd
ˆ fd„Zdd„Ze	 e
e«       eee¬«      	 	 	 	 	 	 	 	 	 d	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 dd„«       «       «       Z e
e«      	 	 	 	 d	 	 	 	 	 	 	 	 	 dd„«       Z e
e«      	 	 d	 	 	 	 	 dd„«       Zdd	„Zˆ xZS )ÚTFBlipModelú)text_decoder.cls.predictions.decoder.biasr·   c                óP   •— t        ‰| �  |g|¢­i |¤Ž t        |d¬«      | _        y )Nr  rÁ   )rr   rs   r5  r  )rE   rt   rí   r   r€   s       €r,   rs   zTFBlipModel.__init__§  s(   ø€ Ü‰Ñ˜Ð3 &Ò3¨FÒ3ä# F°Ô8ˆ�	r.   c                óp   — t        |j                  |j                  |j                  |j                  ¬«      S )N)rW   rX   rY   r:   )rV   rW   rX   rY   r:   )rE   rÜ   s     r,   r(  zTFBlipModel.serving_output¬  s3   € ÜØ#×4Ñ4Ø"×2Ñ2Ø×*Ñ*Ø×,Ñ,ô	
ð 	
r.   r)  c
                ó:   — | j                  |||||||||	¬«	      }
|
S )a§  
        Returns:

        Examples:

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

        >>> model = TFBlipModel.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="tf", padding=True
        ... )

        >>> outputs = model(**inputs)
        >>> logits_per_image = outputs.logits_per_image  # this is the image-text similarity score
        >>> probs = tf.nn.softmax(logits_per_image, axis=1)  # we can take the softmax to get the label probabilities
        ```)	r·   r—   rý   r¸   rT  rÑ   r  r  rÎ   )r  )rE   r·   r—   rý   r¸   rT  rÑ   r  r  rÎ   rÝ   s              r,   rœ   zTFBlipModel.call´  s:   € ðN —)‘)ØØ%Ø)Ø%Ø#Ø/Ø!5Ø#Øð ó 

ˆð ˆr.   c                ó¸   — |�|n| j                   j                  }| j                  j                  ||||¬«      }|d   }| j                  j	                  |«      }|S )a¯  
        Returns:
            text_features (`tf.Tensor` of shape `(batch_size, output_dim`): The text embeddings obtained by applying
            the projection layer to the pooled output of [`TFBlipTextModel`].

        Examples:

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

        >>> model = TFBlipModel.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="tf")
        >>> text_features = model.get_text_features(**inputs)
        ```)r·   rý   r¸   r  r   )rt   r  r  r8  r<  )rE   r·   rý   r¸   r  rV  r.  Útext_featuress           r,   Úget_text_featureszTFBlipModel.get_text_featuresè  sd   € ð0 &1Ð%<‘kÀ$Ç+Á+×B]ÑB]ˆà—y‘y×+Ñ+ØØ)Ø%Ø#ð	 ,ó 
ˆð % Q™ˆØŸ	™	×1Ñ1°-Ó@ˆàÐr.   c                ó´   — |�|n| j                   j                  }| j                  j                  ||¬«      }|d   }| j                  j	                  |«      }|S )aT  
        Returns:
            image_features (`tf.Tensor` of shape `(batch_size, output_dim`): The image embeddings obtained by applying
            the projection layer to the pooled output of [`TFBlipVisionModel`].

        Examples:

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

        >>> model = TFBlipModel.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="tf")

        >>> image_features = model.get_image_features(**inputs)
        ```)r—   r  r   )rt   r  r  r9  r:  )rE   r—   r  rU  r.  Úimage_featuress         r,   Úget_image_featureszTFBlipModel.get_image_features  sX   € ð8 &1Ð%<‘kÀ$Ç+Á+×B]ÑB]ˆàŸ™×/Ñ/¸\ÐWbÐ/Ócˆà& qÑ)ˆØŸ™×4Ñ4°]ÓCˆàÐr.   c                óú   — | j                   ry d| _         t        | dd «      �Nt        j                  | j                  j
                  «      5  | j                  j                  d «       d d d «       y y # 1 sw Y   y xY w)NTr  )r‰   r^   r%   rŠ   r  rp   r‹   rŒ   s     r,   r‹   zTFBlipModel.build3  se   € Ø�:Š:ØØˆŒ
Ü�4˜ Ó&Ð2Ü—‘˜tŸy™yŸ~™~Ó.ñ &Ø—	‘	—‘ Ô%÷&ð &ð 3÷&ð &ús   ÁA1Á1A:rï   )rÜ   rV   re   rV   rW  rX  )NNNN)
r·   r9   rý   r9   r¸   r9   r  rß   re   rŸ   ©NN)r—   r9   r  rß   re   rŸ   rž   )rG   rH   rI   r   r  r  r2  rs   r(  r   r   ÚBLIP_INPUTS_DOCSTRINGr   rV   rœ   r   ra  r3  rd  r‹   r¡   r¢   s   @r,   rZ  rZ  ¢  sr  ø„ Ø€LØ'SÐ&TÐ#Ø!€Oõ9ó

ð Ù*Ð+@ÓAÙ¨<ÀjÔQð '+Ø)-Ø+/Ø)-Ø&*Ø,0Ø/3Ø&*Ø#'ð/à#ð/ð 'ð/ð )ð	/ð
 'ð/ð $ð/ð *ð/ð -ð/ð $ð/ð !ð/ð 
$ò/ó Ró Bó ð/ñb +Ð+EÓFð '+Ø+/Ø)-Ø&*ð#à#ð#ð )ð#ð 'ð	#ð
 $ð#ð 
ò#ó Gð#ñJ +Ð+GÓHð *.Ø&*ð"à&ð"ð $ð"ð 
ò	"ó Ið"÷H&r.   rZ  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	ˆ fd„Zd
d„Ze	 e
e«       eee¬«      	 	 	 	 	 	 	 d	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 dd„«       «       «       Z	 	 d	 	 	 	 	 	 	 dd„Zdd„Zˆ xZS )ÚTFBlipForConditionalGenerationr[  r—   c                ó  •— t        ‰| �  |g|¢­i |¤Ž t        |j                  d¬«      | _        t        |j                  d¬«      | _        |j                  j                  | _	        |j                  j                  | _        y )Nr9  rÁ   Útext_decoder)rr   rs   r  rA  r9  r   r>  rk  Úbos_token_idÚdecoder_input_idsÚpad_token_idÚdecoder_pad_token_idr   s       €r,   rs   z'TFBlipForConditionalGeneration.__init__J  sl   ø€ Ü‰Ñ˜Ð1 $Ò1¨&Ò1ä-¨f×.BÑ.BÈÔXˆÔä1°&×2DÑ2DÈ>ÔZˆÔà!'×!3Ñ!3×!@Ñ!@ˆÔØ$*×$6Ñ$6×$CÑ$CˆÕ!r.   c                óB   — | j                   j                  j                  S rž   ©r9  r›   rj   rD   s    r,   r0  z3TFBlipForConditionalGeneration.get_input_embeddingsT  ó   € Ø× Ñ ×+Ñ+×;Ñ;Ð;r.   r)  c	                óÔ  — |�|n| j                   j                  }| j                  |||||¬«      }	|	d   }
| j                  |||
|d|¬«      }|s'|d   |d   |
|	d   f|	dd z   }t	        d„ |D «       «      S |�|d   }|d   }nd}|d   }|�/|j
                  j                  dk(  rt        j                  |d	«      }t        |||
|	j                  |	j                  |	j                  ¬
«      S )aÆ  
        Returns:

        Examples:

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

        >>> processor = AutoProcessor.from_pretrained("Salesforce/blip-image-captioning-base")
        >>> model = TFBlipForConditionalGeneration.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="tf")

        >>> outputs = model(**inputs)
        ```NrK  r   F)r·   rý   Úencoder_hidden_statesÚlabelsr  rÎ   r   rq   c              3  ó&   K  — | ]	  }|€Œ|–— Œ y ­wrž   rM   ©r`   rÜ   s     r,   rb   z6TFBlipForConditionalGeneration.call.<locals>.<genexpr>‘  ó   è ø€ ÒL F¸Ñ9KœÑLùr  rP  )r8   r+   r:   r<   r>   r?   )rt   r  r9  rk  rc   r„   Úrankr%   r”   r6   r<   r>   r?   )rE   r—   r·   rý   rÑ   r  ru  r  rÎ   rU  r:   rÝ   r8   r+   s                 r,   rœ   z#TFBlipForConditionalGeneration.callW  s.  € ðH &1Ð%<‘kÀ$Ç+Á+×B]ÑB]ˆØ×*Ñ*Ø%Ø/Ø!5Ø#Øð +ó 
ˆð & aÑ(ˆà×#Ñ#ØØ)Ø".ØØØð $ó 
ˆñ Ø˜q‘z 7¨1¡:¨|¸^ÈAÑ=NÐOÐR`ÐabÐacÐRdÑdˆGÜÑL¨gÔLÓLÐLàÐØ˜1‘:ˆDØ˜Q‘Z‰FàˆDØ˜Q‘ZˆFàÐ §
¡
§¡°1Ò 4Ü—:‘:˜d DÓ)ˆDä8ØØØ%Ø,×>Ñ>Ø(×6Ñ6Ø%×0Ñ0ô
ð 	
r.   c           
     ó²  — |j                   d   }| j                  |¬«      }|d   }t        j                  t	        |«      dd t        j
                  ¬«      }t        |t        «      r&t        j                  |t        j
                  ¬«      }nj|€ht        j                  | j                  | j                  j                  j                  ggt        j
                  ¬«      }t        j                  ||df«      }t        j                  t        j                  |dft        j
                  ¬«      | j                  j                  j                  z  |dd…dd…f   gd¬«      }|�|dd…dd…f   nd} | j                   j"                  d	|dd…dd…f   | j                  j                  j$                  | j                  j                  j&                  |||dœ|¤Ž}	|	S )
ay  
        Overrides *generate* function to be able to use the model as a conditional generator

        Parameters:
            pixel_values (`tf.Tensor` of shape `(batch_size, num_channels, image_height, image_width)`:
                Input image to be processed
            input_ids (`tf.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
                The sequence used as a prompt for the generation.
            attention_mask (`tf.Tensor` 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, TFBlipForConditionalGeneration

        >>> model = TFBlipForConditionalGeneration.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="tf")

        >>> outputs = model.generate(**inputs)
        >>> print(processor.decode(outputs[0], skip_special_tokens=True))
        two cats sleeping on a couch
        ```
        r   ©r—   Nr‘   ©Údtyper   r’   )r·   Úeos_token_idrn  rý   rt  Úencoder_attention_maskrM   )r„   r9  r%   Úonesr   Úint32r=  Úlistr%  rm  rt   r>  r~  r¶   r–   rl  rk  ÚgenerateÚsep_token_idrn  )
rE   r—   r·   rý   Úgenerate_kwargsr˜   rU  r:   Úimage_attention_maskrÝ   s
             r,   rƒ  z'TFBlipForConditionalGeneration.generate¦  s¦  € ðN "×'Ñ'¨Ñ*ˆ
Ø×*Ñ*¸Ð*ÓEˆà% aÑ(ˆä!Ÿw™w¤z°,Ó'?ÀÀÐ'DÌBÏHÉHÔUÐä�i¤Ô&Ü×,Ñ,¨Y¼b¿h¹hÔG‰IØÐÜ×,Ñ,Ø×(Ñ(¨$¯+©+×*AÑ*A×*NÑ*NÐOÐPÔXZ×X`ÑX`ôˆIô Ÿ™ 	¨J¸¨?Ó;ˆIô —I‘IÜ�W‰W�j !�_¬B¯H©HÔ5¸¿¹×8OÑ8O×8\Ñ8\Ñ\Ð^gÒhiÐklÑkmÐhmÑ^nÐoÐvwô
ˆ	ð 4BÐ3M˜ª¨3¨B¨3¨Ò/ÐSWˆà,�$×#Ñ#×,Ñ,ð 
Ø¢ 3 B 3 Ñ'ØŸ™×0Ñ0×=Ñ=ØŸ™×0Ñ0×=Ñ=Ø)Ø".Ø#7ñ
ð ñ
ˆð ˆr.   c                óÆ  — | j                   ry d| _         t        | dd «      �Mt        j                  | j                  j
                  «      5  | j                  j                  d «       d d d «       t        | dd «      �Nt        j                  | j                  j
                  «      5  | j                  j                  d «       d d d «       y y # 1 sw Y   ŒexY w# 1 sw Y   y xY w)NTr9  rk  )r‰   r^   r%   rŠ   r9  rp   r‹   rk  rŒ   s     r,   r‹   z$TFBlipForConditionalGeneration.buildï  s½   € Ø�:Š:ØØˆŒ
Ü�4˜¨Ó.Ð:Ü—‘˜t×0Ñ0×5Ñ5Ó6ñ .Ø×!Ñ!×'Ñ'¨Ô-÷.ä�4˜¨Ó.Ð:Ü—‘˜t×0Ñ0×5Ñ5Ó6ñ .Ø×!Ñ!×'Ñ'¨Ô-÷.ð .ð ;÷.ð .ú÷.ð .ús   ÁCÂ%CÃCÃC rï   ©re   zkeras.layers.Layer)NNNNNNN)r—   rŸ   r·   r9   rý   r9   rÑ   rß   r  rß   ru  r9   r  rß   rÎ   rß   re   z7Union[Tuple, TFBlipForConditionalGenerationModelOutput]rf  )r—   rŸ   r·   r9   rý   r9   re   rŸ   rž   )rG   rH   rI   r   r  r  r2  rs   r0  r   r   r3  r   r6   rœ   rƒ  r‹   r¡   r¢   s   @r,   ri  ri  <  s  ø„ ð €LØ'SÐ&TÐ#Ø$€OõDó<ð Ù*Ð+GÓHÙÐ+TÐcmÔnð '+Ø+/Ø,0Ø/3Ø#'Ø&*Ø#'ðJ
àðJ
ð $ðJ
ð )ð	J
ð
 *ðJ
ð -ðJ
ð !ðJ
ð $ðJ
ð !ðJ
ð 
AòJ
ó oó Ió ðJ
ð^ '+Ø+/ð	GàðGð $ðGð )ð	Gð 
óG÷R	.r.   ri  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	ˆ fd„Zd
d„Zd„ Ze	 e
e«       eee¬«      	 	 	 	 	 	 	 	 	 d	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 dd„«       «       «       Z	 d	 	 	 	 	 	 	 dd„Zdd„Zˆ xZS )ÚTFBlipForQuestionAnsweringr[  c                óB  •— t        ‰| �  |g|¢­i |¤Ž t        |j                  d¬«      | _        t        |j                  dd¬«      | _        t        |j                  d¬«      | _	        |j                  j                  | _        |j                  j                  | _        y )Nr9  rÁ   Útext_encoderF©rp   Úadd_pooling_layerrk  )rr   rs   r  rA  r9  r    r>  rŒ  r   rk  rn  ro  rl  Údecoder_start_token_idr   s       €r,   rs   z#TFBlipForQuestionAnswering.__init__  s„   ø€ Ü‰Ñ˜Ð1 $Ò1¨&Ò1ä-¨f×.BÑ.BÈÔXˆÔä+¨F×,>Ñ,>À^ÐglÔmˆÔä1°&×2DÑ2DÈ>ÔZˆÔà$*×$6Ñ$6×$CÑ$CˆÔ!Ø&,×&8Ñ&8×&EÑ&EˆÕ#r.   c                óB   — | j                   j                  j                  S rž   rq  rD   s    r,   r0  z/TFBlipForQuestionAnswering.get_input_embeddings  rr  r.   c           
     óF  — | j                   }| j                  }|�|€t        d«      ‚t        j                  t        |«      d   df|«      }t        j                  ||j                  «      }t        j                  ||d d …d d…f   gd«      }t        j                  |dk(  t        j                  t        j                  t        |«      |«      |j                  «      |«      }t        j                  j                  |t        j                  d|j                  ¬«      «       |S )Nz8decoder_start_token_id and pad_token_id must be defined!r   r   r‘   iœÿÿÿr|  )r�  ro  r³   r%   Úfillr   Úcastr}  r–   ÚwhereÚ	debuggingÚassert_greater_equalÚconstant)rE   r·   r�  rn  Ústart_tokensÚshifted_input_idss         r,   Ú_shift_rightz'TFBlipForQuestionAnswering._shift_right  sø   € Ø!%×!<Ñ!<ÐØ×0Ñ0ˆà!Ð)¨\Ð-AÜÐWÓXÐXä—w‘w¤
¨9Ó 5°aÑ 8¸!Ð<Ð>TÓUˆÜ—w‘w˜|¨Y¯_©_Ó=ˆÜŸI™I |°YºqÀ#À2À#¸vÑ5FÐ&GÈÓLÐô ŸH™HØ Ñ%Ü�G‰G”B—G‘GœJÐ'8Ó9¸<ÓHÐJ[×JaÑJaÓbØó
Ðô 	�‰×)Ñ)Ð*;¼R¿[¹[ÈÐRc×RiÑRiÔ=jÔkà Ð r.   r)  c           	     ó˜  — |€|€t        d«      ‚|	�|	n| j                  j                  }	| j                  ||||	|
¬«      }|d   }t	        j
                  t        |«      dd t        j                  ¬«      }| j                  |||||	|
¬«      }|	s|d   n|j                  }|�|€|}| j                  ||||||	|
¬«      }|�:|	rt	        j                  |j                  «      nt	        j                  |d   «      }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, TFBlipForQuestionAnswering

        >>> model = TFBlipForQuestionAnswering.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="tf")
        >>> labels = processor(text=label, return_tensors="tf").input_ids

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

        >>> # inference
        >>> text = "How many cats are in the picture?"
        >>> inputs = processor(images=image, text=text, return_tensors="tf")
        >>> 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 `TFBlipForQuestionAnswering`. 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`rK  r   r‘   r|  ©r·   rý   rt  r  r  rÎ   )r·   rý   rt  r  ru  r  rÎ   rq   c              3  ó&   K  — | ]	  }|€Œ|–— Œ y ­wrž   rM   rw  s     r,   rb   z2TFBlipForQuestionAnswering.call.<locals>.<genexpr>“  rx  r  )r8   r:   r<   r>   r?   )r³   rt   r  r9  r%   r€  r   Úint64rŒ  r<   rk  r'   r8   rc   rO   r>   r?   )rE   r·   r—   rm  Údecoder_attention_maskrý   rÑ   r  ru  r  rÎ   rU  r:   r†  rT   Úanswer_outputÚdecoder_lossrÝ   s                     r,   rœ   zTFBlipForQuestionAnswering.call.  sŸ  € ðb ˆ>Ð/Ð7Üðuóð ð &1Ð%<‘kÀ$Ç+Á+×B]ÑB]ˆà×*Ñ*Ø%Ø/Ø!5Ø#Øð +ó 
ˆð & aÑ(ˆÜ!Ÿw™w¤z°,Ó'?ÀÀÐ'DÌBÏHÉHÔUÐà×+Ñ+ØØ)Ø".Ø#7Ø#Øð ,ó 
ˆñ 5@˜/¨!Ò,À_×EfÑEfˆàÐÐ"3Ð";à &Ðà×)Ñ)Ø'Ø1Ø"1Ø#1ØØ#Øð *ó 
ˆð ÐÙALœ2Ÿ>™>¨-×*<Ñ*<Ô=ÔRT×R`ÑR`ÐanÐopÑaqÓRr‰LàˆLáØ# \°>À!Ñ3DÐEÈÐWXÐWYÐHZÑZˆGÜÑL¨gÔLÓLÐLä*ØØ%Ø,×>Ñ>Ø(×6Ñ6Ø%×0Ñ0ô
ð 	
r.   c           	     óâ  — | j                  |¬«      }|d   }t        j                  t        |«      dd t        j                  ¬«      }t        |t        «      rt        j                  |«      }| j                  ||||d¬«      }|d   }	t        j                  t        |	«      dd t        j                  ¬«      }
t        j                  t        j                  |	«      d   dft        j                  | j                  |j                  «      ¬	«      } | j                  j                  d|| j                   j"                  j$                  | j                   j"                  j&                  |	|
d
œ|¤Ž}|S )aC  
        Overrides *generate* function to be able to use the model as a conditional generator

        Parameters:
            input_ids (`tf.Tensor` of shape `(batch_size, sequence_length)`):
                The sequence used as a prompt for the generation.
            pixel_values (`tf.Tensor` of shape `(batch_size, num_channels, image_height, image_width)`:
                Input image to be processed
            attention_mask (`tf.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 MASKED tokens.
            generate_kwargs (dict, *optional*):
                Additional arguments passed to the `generate` function of the decoder


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

        >>> model = TFBlipForQuestionAnswering.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="tf")

        >>> outputs = model.generate(**inputs)
        >>> print(processor.decode(outputs[0], skip_special_tokens=True))
        2
        ```
        r{  r   Nr‘   r|  F)r·   rý   rt  r  r  r   )Úvalue)r·   r~  rn  rt  r  rM   )r9  r%   r€  r   r�  r=  r‚  ÚTensorrŒ  r’  r„   r“  r�  r}  rk  rƒ  rt   r>  r„  rn  )rE   r·   r—   rý   r…  rU  r:   r†  Úquestion_outputsrT   Úquestion_attention_maskÚbos_idsrÝ   s                r,   rƒ  z#TFBlipForQuestionAnswering.generate�  sM  € ðT ×*Ñ*¸Ð*ÓEˆà% aÑ(ˆä!Ÿw™w¤z°,Ó'?ÀÀÐ'DÌBÏHÉHÔUÐä�i¤Ô&ÜŸ	™	 )Ó,ˆIà×,Ñ,ØØ)Ø".Ø#7Øð -ó 
Ðð +¨1Ñ-ˆä"$§'¡'¬*°_Ó*EÀcÀrÐ*JÔRT×RZÑRZÔ"[Ðä—'‘'Ü�X‰X�oÓ& qÑ)¨1Ð-´R·W±W¸T×=XÑ=XÐZc×ZiÑZiÓ5jô
ˆð -�$×#Ñ#×,Ñ,ð 
ØØŸ™×0Ñ0×=Ñ=ØŸ™×0Ñ0×=Ñ=Ø"1Ø#:ñ
ð ñ
ˆð ˆr.   c                ó’  — | j                   ry d| _         t        | dd «      �Mt        j                  | j                  j
                  «      5  | j                  j                  d «       d d d «       t        | dd «      �Mt        j                  | j                  j
                  «      5  | j                  j                  d «       d d d «       t        | dd «      �Nt        j                  | j                  j
                  «      5  | j                  j                  d «       d d d «       y y # 1 sw Y   Œ¿xY w# 1 sw Y   ŒqxY w# 1 sw Y   y xY w)NTr9  rŒ  rk  )	r‰   r^   r%   rŠ   r9  rp   r‹   rŒ  rk  rŒ   s     r,   r‹   z TFBlipForQuestionAnswering.buildë  s  € Ø�:Š:ØØˆŒ
Ü�4˜¨Ó.Ð:Ü—‘˜t×0Ñ0×5Ñ5Ó6ñ .Ø×!Ñ!×'Ñ'¨Ô-÷.ä�4˜¨Ó.Ð:Ü—‘˜t×0Ñ0×5Ñ5Ó6ñ .Ø×!Ñ!×'Ñ'¨Ô-÷.ä�4˜¨Ó.Ð:Ü—‘˜t×0Ñ0×5Ñ5Ó6ñ .Ø×!Ñ!×'Ñ'¨Ô-÷.ð .ð ;÷.ð .ú÷.ð .ú÷.ð .ús$   ÁD%Â%D1Ã?D=Ä%D.Ä1D:Ä=Erï   rˆ  rW  )r·   rŸ   r—   r9   rm  r9   rŸ  r9   rý   r9   rÑ   rß   r  rß   ru  r9   r  rß   rÎ   rß   re   z)Union[Tuple, TFBlipTextVisionModelOutput]rž   )r·   rŸ   r—   rŸ   rý   r9   re   rŸ   )rG   rH   rI   r   r  r  rs   r0  rš  r   r   r3  r   rO   r   rœ   rƒ  r‹   r¡   r¢   s   @r,   rŠ  rŠ  û  s*  ø„ ð €LØ'SÐ&TÐ#õ
Fó<ò!ð. Ù*Ð+GÓHÙÐ+FÐUeÔfð *.Ø.2Ø37Ø+/Ø,0Ø/3Ø#'Ø&*Ø#'ðj
àðj
ð 'ðj
ð ,ð	j
ð
 !1ðj
ð )ðj
ð *ðj
ð -ðj
ð !ðj
ð $ðj
ð !ðj
ð 
3òj
ó gó Ió ðj
ð` ,0ð	LàðLð  ðLð )ð	Lð 
óL÷\.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ˆ fd„Zdd„Ze ee	«       e
ee¬«      	 	 	 	 	 	 	 d	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 d	d„«       «       «       Zd
d„Zˆ xZS )ÚTFBlipForImageTextRetrievalc                óü  •— t        ‰| �  |g|¢­i |¤Ž t        |j                  d¬«      | _        t        |j                  dd¬«      | _        t        j                  j                  |j                  t        |j                  «      d¬«      | _        t        j                  j                  |j                  t        |j                  «      d¬«      | _        t        j                  j                  d	t        |j                  «      d
¬«      | _        t#        |d«      s|j                  j$                  n|j&                  | _        t#        |d«      s|j                  j(                  n|j*                  | _        || _        y )Nr9  rÁ   rŒ  Fr�  Úvision_projrÃ   Ú	text_projrq   Úitm_headro  r�  )rr   rs   r  rA  r9  r    r>  rŒ  r   ry   rË   Úimage_text_hidden_sizer   r{   r¬  r­  r®  Úhasattrrn  ro  rl  r�  rt   r   s       €r,   rs   z$TFBlipForImageTextRetrieval.__init__  sM  ø€ Ü‰Ñ˜Ð1 $Ò1¨&Ò1ä-¨f×.BÑ.BÈÔXˆÔä+¨F×,>Ñ,>À^ÐglÔmˆÔô !Ÿ<™<×-Ñ-Ø×)Ñ)Ü.¨v×/GÑ/GÓHØð .ó 
ˆÔô Ÿ™×+Ñ+Ø×)Ñ)Ü.¨v×/GÑ/GÓHØð ,ó 
ˆŒô Ÿ™×*Ñ*Ø¤/°&×2JÑ2JÓ"KÐR\ð +ó 
ˆŒô ˜6Ð#9Ô:ð ×Ñ×+Ò+à×,Ñ,ð 	Ô!ô ˜6Ð#;Ô<ð ×Ñ×+Ò+à×.Ñ.ð 	Ô#ð
 ˆ�r.   c                óB   — | j                   j                  j                  S rž   rq  rD   s    r,   r0  z0TFBlipForImageTextRetrieval.get_input_embeddings+  rr  r.   r)  c	           	     óŒ  — |�|n| j                   j                  }| j                  |||||¬«      }	|	d   }
t        j                  t        |
«      dd t        j                  ¬«      }| j                  |||
|||¬«      }|s|d   n|j                  }| j                  |dd…ddd…f   «      }| j                  ||||¬«      }|s|d   n|j                  }t        j                  j                  | j                  |
dd…ddd…f   «      dd¬	«      \  }}t        j                  j                  | j                  |dd…ddd…f   «      dd¬	«      \  }}t        j                  ||d
¬«      }|r|}|}n|}|}|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, TFBlipForImageTextRetrieval

        >>> model = TFBlipForImageTextRetrieval.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="tf")
        >>> outputs = model(**inputs)
        ```
        NrK  r   r‘   r|  rœ  )r·   rý   r  rÎ   rq   )rL  r“   TrN  c              3  ó&   K  — | ]	  }|€Œ|–— Œ y ­wrž   rM   rw  s     r,   rb   z3TFBlipForImageTextRetrieval.call.<locals>.<genexpr>†  rx  r  )rR   r<   r>   r?   rT   )rt   r  r9  r%   r€  r   rž  rŒ  r<   r®  ÚlinalgÚ	normalizer¬  r­  rS  rc   rQ   r>   r?   )rE   r·   r—   Úuse_itm_headrý   rÑ   r  r  rÎ   rU  r:   Ú
image_attsÚitm_question_embedsÚ
itm_outputÚno_itm_question_embedsÚ
image_featÚ_Ú	text_featÚno_itm_outputrÜ   rT   rÝ   s                         r,   rœ   z TFBlipForImageTextRetrieval.call.  s  € ðF &1Ð%<‘kÀ$Ç+Á+×B]ÑB]ˆà×*Ñ*Ø%Ø/Ø!5Ø#Øð +ó 
ˆð & aÑ(ˆÜ—W‘WœZ¨Ó5°c°rÐ:Ä"Ç(Á(ÔKˆ
ð #×/Ñ/ØØ)Ø".Ø#-Ø#Øð 0ó 
Ðñ =HÐ1°!Ò4ÐM`×MrÑMrÐà—]‘]Ð#6²q¸!ºQ°wÑ#?Ó@ˆ
à!%×!2Ñ!2ØØ)Ø#Øð	 "3ó "
Ðñ .9Ð" 1Ò%Ð>T×>fÑ>fð 	ô Ÿ	™	×+Ñ+¨D×,<Ñ,<¸\Ê!ÈQÒPQÈ'Ñ=RÓ,SÐYZÐacÐ+Ód‰ˆ
�AÜ—y‘y×*Ñ*¨4¯>©>Ð:PÒQRÐTUÒWXÐQXÑ:YÓ+ZÐ`aÐhjÐ*Ók‰ˆ	�1äŸ	™	 *¨iÀTÔJˆáØˆFØ1‰Oà"ˆFØ4ˆOáØ˜~¨aÑ0Ð1°NÀ1À2Ð4FÑFÈ/ÐI[Ñ[ˆGÜÑL¨gÔLÓLÐLä1ØØ,×>Ñ>Ø(×6Ñ6Ø%×0Ñ0Ø+ô
ð 	
r.   c                óö  — | j                   ry d| _         t        | dd «      �Mt        j                  | j                  j
                  «      5  | j                  j                  d «       d d d «       t        | dd «      �Mt        j                  | j                  j
                  «      5  | j                  j                  d «       d d d «       t        | dd «      �nt        j                  | j                  j
                  «      5  | j                  j                  d d | j                  j                  j                  g«       d d d «       t        | dd «      �nt        j                  | j                  j
                  «      5  | j                  j                  d d | j                  j                  j                  g«       d d d «       t        | dd «      �ot        j                  | j                  j
                  «      5  | j                  j                  d d | j                  j                  j                  g«       d d d «       y y # 1 sw Y   �Œ×xY w# 1 sw Y   �ŒŠxY w# 1 sw Y   �ŒxY w# 1 sw Y   Œ­xY w# 1 sw Y   y xY w)NTr9  rŒ  r¬  r­  r®  )r‰   r^   r%   rŠ   r9  rp   r‹   rŒ  r¬  rt   rA  ru   r­  r>  r®  rŒ   s     r,   r‹   z!TFBlipForImageTextRetrieval.build�  s÷  € Ø�:Š:ØØˆŒ
Ü�4˜¨Ó.Ð:Ü—‘˜t×0Ñ0×5Ñ5Ó6ñ .Ø×!Ñ!×'Ñ'¨Ô-÷.ä�4˜¨Ó.Ð:Ü—‘˜t×0Ñ0×5Ñ5Ó6ñ .Ø×!Ñ!×'Ñ'¨Ô-÷.ä�4˜¨Ó-Ð9Ü—‘˜t×/Ñ/×4Ñ4Ó5ñ \Ø× Ñ ×&Ñ&¨¨d°D·K±K×4MÑ4M×4YÑ4YÐ'ZÔ[÷\ä�4˜ dÓ+Ð7Ü—‘˜tŸ~™~×2Ñ2Ó3ñ XØ—‘×$Ñ$ d¨D°$·+±+×2IÑ2I×2UÑ2UÐ%VÔW÷Xä�4˜ TÓ*Ð6Ü—‘˜tŸ}™}×1Ñ1Ó2ñ WØ—‘×#Ñ# T¨4°·±×1HÑ1H×1TÑ1TÐ$UÔV÷Wð Wð 7÷.ñ .ú÷.ñ .ú÷\ñ \ú÷Xð Xú÷Wð Wús<   ÁH<Â%I	Ã?=IÅ:=I#Ç5=I/È<IÉ	IÉI É#I,É/I8rï   rˆ  )NTNNNNN)r·   rŸ   r—   r9   r¶  rß   rý   r9   rÑ   rß   r  rß   r  rß   rÎ   rß   re   z0Union[Tuple, TFBlipImageTextMatchingModelOutput]rž   )rG   rH   rI   r   r  rs   r0  r   r   r3  r   rQ   r   rœ   r‹   r¡   r¢   s   @r,   rª  rª  ú  sË   ø„ ð €Lõ$óL<ð Ù*Ð+GÓHÙÐ+MÐ\lÔmð *.Ø'+Ø+/Ø,0Ø/3Ø&*Ø#'ð]
àð]
ð 'ð]
ð %ð	]
ð
 )ð]
ð *ð]
ð -ð]
ð $ð]
ð !ð]
ð 
:ò]
ó nó Ió ð]
÷~Wr.   rª  )rZ  r  ri  rŠ  r  r    rª  )r+   rŸ   re   rŸ   )r1   rŸ   re   rŸ   )FrJ   Ú
__future__r   rA   Údataclassesr   Útypingr   r   r   r   Ú
tensorflowr%   Úmodeling_tf_outputsr
   r   Úmodeling_tf_utilsr   r   r   r   r   r   r   Útf_utilsr   r   Úutilsr   r   r   r   r   Úconfiguration_blipr   r   r   Úmodeling_tf_blip_textr   r   r    Ú
get_loggerrG   ÚloggerÚ_CHECKPOINT_FOR_DOCr-   r4   r6   rO   rQ   rV   ry   ÚLayerrg   r¤   r½   rá   rò   r  ÚBLIP_START_DOCSTRINGr3  rg  r  r  r5  rZ  ri  rŠ  rª  Ú__all__rM   r.   r,   ú<module>rÐ     s  ðñ å "ã Ý !ß .Ó .ã ç R÷÷ ñ ÷ G÷õ ÷ MÑ Lß eÑ eð 
ˆ×	Ñ	˜HÓ	%€à0Ð óó-ð ô)°ó )ó ð)ðX ô4 +ó 4ó ð4ð@ ô'4¨ó '4ó ð'4ðT ô!
�;ó !
ó ð!
ôH5˜UŸ\™\×/Ñ/ô 5ôr7 ˜5Ÿ<™<×-Ñ-ô 7 ôtQD�e—l‘l×(Ñ(ô QDôh L�—‘×"Ñ"ô  LôF@E˜Ÿ™×+Ñ+ô @EôF8Ð-ô 8ðÐ ð Ð ð"Ð ðJ ôW&�E—L‘L×&Ñ&ó W&ó ðW&ôt[HÐ-ô [Hô|I
�e—l‘l×(Ñ(ô I
ôXW&Ð'ô W&ñt ðð óôs.Ð%:ó s.óðs.ñl ðð
 óôt.Ð!6ó t.óðt.ñn ðð
 óô`WÐ"7ó `Wóð`WòF�r.   