
    ^jy                     H   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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 ddlmZ ddlmZ ddlmZ ddlm Z m!Z!m"Z" ddl#m$Z$ ddl%m&Z&m'Z' ddl(m)Z)  e"jT                  e+      Z, G d dejZ                        Z. G d dejZ                        Z/ G d dejZ                        Z0 G d dejZ                        Z1 G d dejZ                        Z2 G d dejZ                        Z3 G d  d!e      Z4 G d" d#ejZ                        Z5 G d$ d%ejZ                        Z6 G d& d'ejZ                        Z7 G d( d)ejZ                        Z8 G d* d+ejZ                        Z9 G d, d-e      Z: G d. d/e:      Z; G d0 d1e:e      Z<g d2Z=y)3    N)nn)CrossEntropyLoss   )initialization)ACT2FN)CacheDynamicCacheEncoderDecoderCache)GenerationMixin)create_bidirectional_maskcreate_causal_mask)GradientCheckpointingLayer))BaseModelOutputWithPastAndCrossAttentions,BaseModelOutputWithPoolingAndCrossAttentions!CausalLMOutputWithCrossAttentions)PreTrainedModel)Unpack)apply_chunking_to_forward)TransformersKwargscan_return_tuplelogging)merge_with_config_defaults)OutputRecordercapture_outputs   )BlipTextConfigc                        e Zd ZdZ fdZ	 	 	 	 d
dej                  dz  dej                  dz  dej                  dz  dedej                  f
d	Z
 xZS )BlipTextEmbeddingsz;Construct the embeddings from word and position embeddings.c                 ,   t         |           t        j                  |j                  |j
                  |j                        | _        t        j                  |j                  |j
                        | _	        t        j                  |j
                  |j                        | _
        t        j                  |j                        | _        | j                  dt!        j"                  |j                        j%                  d      d       || _        y )N)padding_idxepsposition_idsr   F)
persistent)super__init__r   	Embedding
vocab_sizehidden_sizepad_token_idword_embeddingsmax_position_embeddingsposition_embeddings	LayerNormlayer_norm_epsDropouthidden_dropout_probdropoutregister_buffertorcharangeexpandconfigselfr9   	__class__s     v/var/www/ramen.bs-engineer-server.com/venv/lib/python3.12/site-packages/transformers/models/blip/modeling_blip_text.pyr(   zBlipTextEmbeddings.__init__1   s    !||F,=,=v?Q?Q_e_r_rs#%<<0N0NPVPbPb#c f&8&8f>S>STzz&"<"<= 	ELL)G)GHOOPWXej 	 	
     N	input_idsr#   inputs_embedspast_key_values_lengthreturnc                 *   ||j                         }n|j                         d d }|d   }|| j                  d d |||z   f   }|| j                  |      }|}| j                  |      }||z  }| j	                  |      }| j                  |      }|S )Nr%   r   )sizer#   r-   r/   r0   r4   )	r;   r?   r#   r@   rA   input_shape
seq_length
embeddingsr/   s	            r=   forwardzBlipTextEmbeddings.forward@   s      #..*K',,.s3K ^
,,Q0FVlIl0l-lmL  00;M"
"66|D))
^^J/
\\*-
r>   )NNNr   )__name__
__module____qualname____doc__r(   r6   
LongTensorFloatTensorintTensorrH   __classcell__r<   s   @r=   r   r   .   ss    E" .20426&'##d* &&- ((4/	
 !$ 
r>   r   c                       e Zd Zd fd	Zd Zd Zd Zd Z	 	 	 	 ddej                  dej                  dz  d	ej                  dz  d
ej                  dz  dedz  dee   deej                  ej                  f   fdZ xZS )BlipTextSelfAttentionNc                    t         |           || _        |j                  |j                  z  dk7  r0t        |d      s$t        d|j                  |j                  fz        |j                  | _        t        |j                  |j                  z        | _        | j                  | j                  z  | _	        || _
        t        j                  |j                  | j                        | _        |r_t        j                  |j                  | j                        | _        t        j                  |j                  | j                        | _        n^t        j                  |j                  | j                        | _        t        j                  |j                  | j                        | _        t        j"                  |j$                        | _        y )Nr   embedding_sizezLThe hidden size (%d) is not a multiple of the number of attention heads (%d))r'   r(   r9   r+   num_attention_headshasattr
ValueErrorrO   attention_head_sizeall_head_size	layer_idxr   Linearqueryencoder_hidden_sizekeyvaluer2   attention_probs_dropout_probr4   r;   r9   is_cross_attentionr\   r<   s       r=   r(   zBlipTextSelfAttention.__init__`   s`    : ::a?PVXhHi^%%v'A'ABC 
 $*#=#= #&v'9'9F<V<V'V#W !558P8PP"YYv1143E3EF
yy!;!;T=O=OPDH6#=#=t?Q?QRDJyy!3!3T5G5GHDH6#5#5t7I7IJDJzz&"E"EFr>   c                     || _         y Nattn_gradients)r;   rh   s     r=   save_attn_gradientsz)BlipTextSelfAttention.save_attn_gradientsx   s
    ,r>   c                     | j                   S rf   rg   r;   s    r=   get_attn_gradientsz(BlipTextSelfAttention.get_attn_gradients{   s    """r>   c                     || _         y rf   attention_map)r;   ro   s     r=   save_attention_mapz(BlipTextSelfAttention.save_attention_map~   s
    *r>   c                     | j                   S rf   rn   rk   s    r=   get_attention_mapz'BlipTextSelfAttention.get_attention_map   s    !!!r>   hidden_statesattention_maskencoder_hidden_statesencoder_attention_maskpast_key_valueskwargsrB   c                    |j                   d d }g |d| j                  }| j                  |      j                  |      j	                  dd      }	|d u}
|
r|n|}d}|St        |t              rA|j                  j                  | j                        }|
r|j                  }n|j                  }n|}|
r|n|}|
rK|I|rGj                  | j                     j                  }|j                  | j                     j                  }ng |j                   d d d| j                  }| j                  |      j                  |      j	                  dd      }| j!                  |      j                  |      j	                  dd      }|Kj#                  ||| j                        \  }}|
r)t        |t              rd|j                  | j                  <   t%        j&                  |	|j	                  dd            }|t)        j*                  | j                        z  }|||j-                  |j.                        z   } t1        j2                  d      |      }| j5                  |      }t%        j&                  ||      }|j7                  dddd	      j9                         }|j;                         d d | j<                  fz   } |j                  | }||fS )
Nr%   r      FT)dimr   r   )shaperZ   r^   view	transpose
isinstancer
   
is_updatedgetr\   cross_attention_cacheself_attention_cachelayerskeysvaluesr`   ra   updater6   matmulmathsqrttodevicer   Softmaxr4   permute
contiguousrD   r[   )r;   rs   rt   ru   rv   rw   rx   rE   hidden_shapequery_layerrd   r   curr_past_key_valuescurrent_states	key_layervalue_layerkv_shapeattention_scoresattention_probsattention_probs_droppedcontext_layernew_context_layer_shapes                         r=   rH   zBlipTextSelfAttention.forward   s    $))#2.CCbC$*B*BCjj/44\BLLQPQR
 3$>3E/>
&/+>?,77;;DNNK
%+:+P+P(+:+O+O('6$2D.-/"=*,33DNNCHHI.55dnnELLKQ--cr2QBQ8P8PQH055h?II!QOI**^499(CMMaQRSK*)=)D)DYP[]a]k]k)l&	;%*_FY*ZAEO..t~~> !<<Y5H5HR5PQ+dii8P8P.QQ%/.2C2CDTD[D[2\\ -"**,-=> #',,"?%<kJ%--aAq9DDF"/"4"4"6s";t?Q?Q>S"S***,CDo--r>   rf   NNNN)rI   rJ   rK   r(   ri   rl   rp   rr   r6   rP   rN   r   r   r   tuplerH   rQ   rR   s   @r=   rT   rT   _   s    G0-#+" 48:>;?(,D.||D. ))D0D.  %0047	D.
 !& 1 1D 8D. D. +,D. 
u||U\\)	*D.r>   rT   c                   n     e Zd Z fdZdej
                  dej
                  dej
                  fdZ xZS )BlipTextSelfOutputc                 (   t         |           t        j                  |j                  |j                        | _        t        j                  |j                  |j                        | _        t        j                  |j                        | _
        y Nr!   )r'   r(   r   r]   r+   denser0   r1   r2   r3   r4   r:   s     r=   r(   zBlipTextSelfOutput.__init__   s`    YYv1163E3EF
f&8&8f>S>STzz&"<"<=r>   rs   input_tensorrB   c                 r    | j                  |      }| j                  |      }| j                  ||z         }|S rf   r   r4   r0   r;   rs   r   s      r=   rH   zBlipTextSelfOutput.forward   7    

=1]3}|'CDr>   rI   rJ   rK   r(   r6   rP   rH   rQ   rR   s   @r=   r   r      1    >U\\  RWR^R^ r>   r   c                        e Zd Zd
 fd	Z	 	 	 ddej
                  dej                  dz  dej                  dz  dedz  dee	   de
ej
                  ej
                  f   fd	Z xZS )BlipTextAttentionNc                 h    t         |           t        |||      | _        t	        |      | _        y )Nr\   )r'   r(   rT   r;   r   outputrc   s       r=   r(   zBlipTextAttention.__init__   s,    )&2DPYZ	(0r>   rs   rt   ru   rw   rx   rB   c                 ^    | j                  ||||      \  }}| j                  ||      }||fS )Nrt   ru   rw   )r;   r   )	r;   rs   rt   ru   rw   rx   r   r   attention_outputs	            r=   rH   zBlipTextAttention.forward   sF     *.)"7+	 *3 *
&  ;;}mD00r>   )FN)NNN)rI   rJ   rK   r(   r6   rP   rN   r   r   r   r   rH   rQ   rR   s   @r=   r   r      s    1 48:>(,1||1 ))D01  %0047	1
 1 +,1 
u||U\\)	*1r>   r   c                   V     e Zd Z fdZdej
                  dej
                  fdZ xZS )BlipTextIntermediatec                    t         |           t        j                  |j                  |j
                        | _        t        |j                  t              rt        |j                     | _        y |j                  | _        y rf   )r'   r(   r   r]   r+   intermediate_sizer   r   
hidden_actstrr   intermediate_act_fnr:   s     r=   r(   zBlipTextIntermediate.__init__   s]    YYv1163K3KL
f''-'-f.?.?'@D$'-'8'8D$r>   rs   rB   c                 J    | j                  |      }| j                  |      }|S rf   )r   r   r;   rs   s     r=   rH   zBlipTextIntermediate.forward   s&    

=100?r>   r   rR   s   @r=   r   r      s#    9U\\ ell r>   r   c                   n     e Zd Z fdZdej
                  dej
                  dej
                  fdZ xZS )BlipTextOutputc                 (   t         |           t        j                  |j                  |j
                        | _        t        j                  |j
                  |j                        | _        t        j                  |j                        | _        y r   )r'   r(   r   r]   r   r+   r   r0   r1   r2   r3   r4   r:   s     r=   r(   zBlipTextOutput.__init__  s`    YYv779K9KL
f&8&8f>S>STzz&"<"<=r>   rs   r   rB   c                 r    | j                  |      }| j                  |      }| j                  ||z         }|S rf   r   r   s      r=   rH   zBlipTextOutput.forward  r   r>   r   rR   s   @r=   r   r     r   r>   r   c                        e Zd Z fdZ	 	 	 	 ddej
                  dej                  dz  dej                  dz  dej                  dz  dedz  dee	   d	ej
                  fd
Z
d Z xZS )BlipTextLayerc                 L   t         |           || _        |j                  | _        d| _        t        ||      | _        || _        | j                  j                  r't        || j                  j                  |      | _	        t        |      | _        t        |      | _        y )Nr   r   )rd   r\   )r'   r(   r9   chunk_size_feed_forwardseq_len_dimr   	attention	layer_num
is_decodercrossattentionr   intermediater   r   )r;   r9   r   r<   s      r=   r(   zBlipTextLayer.__init__  s    '-'E'E$*6YG";;!!"34;;+A+AY#D 18$V,r>   Nrs   ru   rt   rv   rw   rx   rB   c                     | j                  |||      \  }}|| j                  ||||      \  }}t        | j                  | j                  | j
                  |      }	|	S )N)rt   rw   r   )r   r   r   feed_forward_chunkr   r   )
r;   rs   ru   rt   rv   rw   rx   r   _layer_outputs
             r=   rH   zBlipTextLayer.forward!  s     #nn)+ - 
! !,"&"5"5 5&; /	 #6 #a 1##T%A%A4CSCSUe
 r>   c                 L    | j                  |      }| j                  ||      }|S rf   )r   r   )r;   r   intermediate_outputr   s       r=   r   z BlipTextLayer.feed_forward_chunk<  s,    "//0@A{{#68HIr>   r   )rI   rJ   rK   r(   r6   rP   rN   r   r   r   rH   r   rQ   rR   s   @r=   r   r     s    -" ;?37;?(,||  %0047 ))D0	
 !& 1 1D 8  +, 
6r>   r   c                        e Zd Z fdZ	 	 	 	 	 ddej
                  dej                  dz  dej                  dz  dej                  dz  dedz  dedz  d	e	e
   d
efdZ xZS )BlipTextEncoderc           	          t         |           || _        t        j                  t        |j                        D cg c]  }t        ||       c}      | _        d| _	        y c c}w )NF)
r'   r(   r9   r   
ModuleListrangenum_hidden_layersr   layergradient_checkpointing)r;   r9   ir<   s      r=   r(   zBlipTextEncoder.__init__D  sP    ]]eFLdLdFe#fM&!$<#fg
&+# $gs   A$Nrs   rt   ru   rv   rw   	use_cacherx   rB   c                    | j                   r%| j                  r|rt        j                  d       d}|rgt	        |t
              r!t        |t        | j                              }n6|4t        t        | j                        t        | j                              }| j                  D ]  } |||f|||d|} t        ||      S )NzZ`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`...F)r9   )rt   rv   rw   )last_hidden_staterw   )
r   trainingloggerwarningr   r	   r
   r9   r   r   )	r;   rs   rt   ru   rv   rw   r   rx   layer_modules	            r=   rH   zBlipTextEncoder.forwardJ  s     &&4==p "	 /<8"5o|[_[f[fGg"h ("5 4l$++6V# !JJ 	L(%  .'= / M	 9++
 	
r>   )NNNNN)rI   rJ   rK   r(   r6   rP   rN   r   boolr   r   r   rH   rQ   rR   s   @r=   r   r   C  s    , 48:>;?(,!%(
||(
 ))D0(
  %0047	(

 !& 1 1D 8(
 (
 $;(
 +,(
 
3(
r>   r   c                   V     e Zd Z fdZdej
                  dej
                  fdZ xZS )BlipTextPoolerc                     t         |           t        j                  |j                  |j                        | _        t        j                         | _        y rf   )r'   r(   r   r]   r+   r   Tanh
activationr:   s     r=   r(   zBlipTextPooler.__init__w  s9    YYv1163E3EF
'')r>   rs   rB   c                 \    |d d df   }| j                  |      }| j                  |      }|S )Nr   )r   r   )r;   rs   first_token_tensorpooled_outputs       r=   rH   zBlipTextPooler.forward|  s6     +1a40

#566r>   r   rR   s   @r=   r   r   v  s#    $
U\\ ell r>   r   c                   V     e Zd Z fdZdej
                  dej
                  fdZ xZS )BlipTextPredictionHeadTransformc                 h   t         |           t        j                  |j                  |j                        | _        t        |j                  t              rt        |j                     | _
        n|j                  | _
        t        j                  |j                  |j                        | _        y r   )r'   r(   r   r]   r+   r   r   r   r   r   transform_act_fnr0   r1   r:   s     r=   r(   z(BlipTextPredictionHeadTransform.__init__  s{    YYv1163E3EF
f''-$*6+<+<$=D!$*$5$5D!f&8&8f>S>STr>   rs   rB   c                 l    | j                  |      }| j                  |      }| j                  |      }|S rf   )r   r   r0   r   s     r=   rH   z'BlipTextPredictionHeadTransform.forward  s4    

=1--m<}5r>   r   rR   s   @r=   r   r     s$    UU\\ ell r>   r   c                   $     e Zd Z fdZd Z xZS )BlipTextLMPredictionHeadc                    t         |           t        |      | _        t	        j
                  |j                  |j                  d      | _        t	        j                  t        j                  |j                              | _        y )NT)bias)r'   r(   r   	transformr   r]   r+   r*   decoder	Parameterr6   zerosr   r:   s     r=   r(   z!BlipTextLMPredictionHead.__init__  s[    8@ yy!3!3V5F5FTRLLV->->!?@	r>   c                 J    | j                  |      }| j                  |      }|S rf   )r   r   r   s     r=   rH   z BlipTextLMPredictionHead.forward  s$    }5]3r>   )rI   rJ   rK   r(   rH   rQ   rR   s   @r=   r   r     s    Ar>   r   c                   V     e Zd Z fdZdej
                  dej
                  fdZ xZS )BlipTextOnlyMLMHeadc                 B    t         |           t        |      | _        y rf   )r'   r(   r   predictionsr:   s     r=   r(   zBlipTextOnlyMLMHead.__init__  s    3F;r>   sequence_outputrB   c                 (    | j                  |      }|S rf   )r   )r;   r   prediction_scoress      r=   rH   zBlipTextOnlyMLMHead.forward  s     ,,_=  r>   r   rR   s   @r=   r   r     s#    <!u|| ! !r>   r   c                   j     e Zd ZU dZeed<   dZg Ze e	e
dd      g e	e
dd      gdZ fd	Z xZS )
BlipTextPreTrainedModelz
    An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
    models.
    r9   bertr   z.attention.)index
layer_namez.crossattention.)rs   
attentionscross_attentionsc                     t         |   |       t        |t              rZt	        j
                  |j                  t        j                  |j                  j                  d         j                  d             y y )Nr%   r$   )r'   _init_weightsr   r   initcopy_r#   r6   r7   r}   r8   )r;   moduler<   s     r=   r  z%BlipTextPreTrainedModel._init_weights  s[    f%f01JJv**ELL9L9L9R9RSU9V,W,^,^_f,gh 2r>   )rI   rJ   rK   rL   r   __annotations__base_model_prefix_no_split_modulesr   r   rT   _can_record_outputsr  rQ   rR   s   @r=   r   r     sZ    
 &0mT
 0FXY
i ir>   r   c                   `    e Zd ZdZd fd	Zd Zd Zee	 	 	 	 	 	 	 	 	 	 dde	j                  dz  de	j                  dz  de	j                  dz  d	e	j                  dz  d
e	j                  dz  de	j                  dz  de	j                  dz  dedz  dedz  dedz  dee   defd              Z xZS )BlipTextModela&  
    The model can behave as an encoder (with only self-attention) as well as a decoder, in which case a layer of
    cross-attention is added between the self-attention layers, following the architecture described in [Attention is
    all you need](https://huggingface.co/papers/1706.03762) by Ashish Vaswani, Noam Shazeer, Niki Parmar, Jakob Uszkoreit,
    Llion Jones, Aidan N. Gomez, Lukasz Kaiser and Illia Polosukhin. argument and `is_decoder` set to `True`; an
    `encoder_hidden_states` is then expected as an input to the forward pass.
    c                     t         |   |       || _        t        |      | _        t        |      | _        |rt        |      nd | _        | j                          y rf   )
r'   r(   r9   r   rG   r   encoderr   pooler	post_init)r;   r9   add_pooling_layerr<   s      r=   r(   zBlipTextModel.__init__  sI     ,V4&v.0AnV,tr>   c                 .    | j                   j                  S rf   rG   r-   rk   s    r=   get_input_embeddingsz"BlipTextModel.get_input_embeddings  s    ...r>   c                 &    || j                   _        y rf   r  )r;   ra   s     r=   set_input_embeddingsz"BlipTextModel.set_input_embeddings  s    */'r>   Nr?   rt   r#   r@   encoder_embedsru   rv   rw   r   r   rx   rB   c           	         |
sd}	||t        d      ||j                         nd}|| j                  ||||      }n|}|
rt        | j                  |||      }nt        | j                  ||      }|t        | j                  |||      } | j                  |f|||||	d	|}|j                  }| j                  | j                  |      nd}t        |||j                  |j                  |j                  |j                  
      S )a  
        encoder_hidden_states  (`torch.FloatTensor`, *optional*):
            Sequence of hidden-states at the output of the last layer of the encoder. Used in the cross-attention if
            the model is configured as a decoder.
        encoder_attention_mask (`torch.FloatTensor`, *optional*):
            Mask to avoid performing attention on the padding token indices of the encoder input. This mask is used in
            the cross-attention if the model is configured as a decoder. Mask values selected in `[0, 1]`:
            - 1 for tokens that are **not masked**,
            - 0 for tokens that are **masked**.
        past_key_values (`Cache`, *optional*):
            Contains precomputed key and value hidden states of the attention blocks. Can be used to speed up decoding.
            If `past_key_values` are used, the user can optionally input only the last `decoder_input_ids` (those that
            don't have their past key value states given to this model) of shape `(batch_size, 1)` instead of all
            `decoder_input_ids` of shape `(batch_size, sequence_length)`.
        use_cache (`bool`, *optional*):
            If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
            `past_key_values`).
        FNzDYou cannot specify both input_ids and inputs_embeds at the same timer   )r?   r#   r@   rA   )r9   r@   rt   rw   )r9   r@   rt   )r9   r@   rt   ru   )rt   ru   rv   rw   r   )r   pooler_outputrw   rs   r  r  )rY   get_seq_lengthrG   r   r9   r   r  r   r  r   rw   rs   r  r  )r;   r?   rt   r#   r@   r  ru   rv   rw   r   r   rx   rA   embedding_outputencoder_outputsr   r   s                    r=   rH   zBlipTextModel.forward  sX   D I ]%>cddETE`!?!?!Afg!##)+'=	  /    ./{{.- /	N 7{{.-N "-%>{{.5&;	&" FRT\\F
)"7#9+F
 F
 *;;8<8OO4UY;-'+;;)77&11,==
 	
r>   )T)
NNNNNNNNNF)rI   rJ   rK   rL   r(   r  r  r   r   r6   rP   r   r   r   r   r   rH   rQ   rR   s   @r=   r  r    s(   /0   *..2,0-1.2596:(,!%"'[
<<$&[
 t+[
 llT)	[

 ||d*[
 t+[
  %||d2[
 !&t 3[
 [
 $;[
 4K[
 +,[
 
6[
   [
r>   r  c                        e Zd ZdddZ fdZd Zd Zd Zd Ze		 	 	 	 	 	 	 	 	 	 	 	 	 dd
e
j                  d	z  de
j                  d	z  de
j                  d	z  de
j                  d	z  de
j                  d	z  de
j                  d	z  de
j                  d	z  ded	z  ded	z  ded	z  ded	z  ded	z  dee
j                  z  dee   defd       Zd fd	Z xZS )BlipTextLMHeadModelzcls.predictions.biasz&bert.embeddings.word_embeddings.weight)zcls.predictions.decoder.biaszcls.predictions.decoder.weightc                     t         |   |       t        |d      | _        t	        |      | _        |j                  | _        | j                          y )NF)r  )r'   r(   r  r   r   clslabel_smoothingr  r:   s     r=   r(   zBlipTextLMHeadModel.__init__N  sB     !&EB	&v.%55r>   c                 6    | j                   j                         S rf   )r   r  rk   s    r=   r  z(BlipTextLMHeadModel.get_input_embeddingsW  s    yy--//r>   c                 :    | j                   j                  |       y rf   )r   r  r;   new_embeddingss     r=   r  z(BlipTextLMHeadModel.set_input_embeddingsZ  s    		&&~6r>   c                 B    | j                   j                  j                  S rf   )r#  r   r   rk   s    r=   get_output_embeddingsz)BlipTextLMHeadModel.get_output_embeddings]  s    xx##+++r>   c                     || j                   j                  _        |j                  | j                   j                  _        y rf   )r#  r   r   r   r'  s     r=   set_output_embeddingsz)BlipTextLMHeadModel.set_output_embeddings`  s,    '5$$2$7$7!r>   Nr?   rt   r#   r@   ru   rv   labelsrw   r   return_logitsr   	reductionlogits_to_keeprx   rB   c                 0   |d}	 | j                   |f|||||||	|d|}|j                  }t        |t              rt	        | d      n|}| j                  |dd|ddf         }|
r|ddddddf   j                         S d}||ddddddf   j                         }|ddddf   j                         j                  |j                        }t        || j                        } ||j                  d| j                  j                        |j                  d            }|dk(  r0|j                  |j                  d      d      j                  d      }t!        |||j"                  |j$                  |j&                  |j(                  	      S )
a  
        encoder_hidden_states (`torch.FloatTensor`, *optional*): Sequence of
            hidden-states at the output of the last layer of the encoder. Used in the cross-attention if the model is
            configured as a decoder.
        encoder_attention_mask (`torch.FloatTensor`, *optional*):
            Mask to avoid performing attention on the padding token indices of the encoder input. This mask is used in
            the cross-attention if the model is configured as a decoder. Mask values selected in `[0, 1]`:
            - 1 for tokens that are **not masked**,
            - 0 for tokens that are **masked**.
        labels (`torch.LongTensor`, *optional*):
            Labels for computing the left-to-right language modeling loss (next word prediction). Indices should be in
            `[-100, 0, ..., config.vocab_size]` (see `input_ids` docstring) Tokens with indices set to `-100` are
            ignored (masked), the loss is only computed for the tokens with labels n `[0, ..., config.vocab_size]`
        past_key_values (`Cache`, *optional*):
            Contains precomputed key and value hidden states of the attention blocks. Can be used to speed up decoding.
            If `past_key_values` are used, the user can optionally input only the last `decoder_input_ids` (those that
            don't have their past key value states given to this model) of shape `(batch_size, 1)` instead of all
            `decoder_input_ids` of shape `(batch_size, sequence_length)`.
        use_cache (`bool`, *optional*):
            If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
            `past_key_values`).
        NF)rt   r#   r@   ru   rv   rw   r   r   r%   r   )r/  r$  noner   )losslogitsrw   rs   r  r  )r   r   r   rO   slicer#  r   r   r   r   r$  r~   r9   r*   rD   sumr   rw   rs   r  r  )r;   r?   rt   r#   r@   ru   rv   r-  rw   r   r.  r   r/  r0  rx   outputsrs   slice_indicesr   lm_lossshifted_prediction_scoresloss_fcts                         r=   rH   zBlipTextLMHeadModel.forwardd  s   P I@I		A
)%'"7#9+!A
 A
  118B>SV8W~ot4]k HH]1mQ3F%GH$QQY/::<<(9!SbS!)(D(O(O(Q%AqrE]--/223L3S3STF')TMaMabH8==b$++BXBXY[a[f[fgi[jkGF"!,,'8'='=a'@"EII!L0$#33!//))$55
 	
r>   c                 8    t        |   |f||d|}d|d<   |S )N)rw   rt   Tr   )r'   prepare_inputs_for_generation)r;   r?   rw   rt   model_kwargsmodel_inputsr<   s         r=   r=  z1BlipTextLMHeadModel.prepare_inputs_for_generation  s>     w<
+)
 	
 &*\"r>   )NNNNNNNNNFTmeanr   )NN)rI   rJ   rK   _tied_weights_keysr(   r  r  r*  r,  r   r6   rP   r   r   r   rO   r   r   r   rH   r=  rQ   rR   s   @r=   r!  r!  H  sy   (>*R
07,8  *..2,0-1596:&*(,!%%*"& &-.P
<<$&P
 t+P
 llT)	P

 ||d*P
  %||d2P
 !&t 3P
 t#P
 P
 $;P
 d{P
 4KP
 :P
 ell*P
 +,P
  
+!P
 P
d r>   r!  )r  r!  r   )>r   r6   r   torch.nnr    r   r  activationsr   cache_utilsr   r	   r
   
generationr   masking_utilsr   r   modeling_layersr   modeling_outputsr   r   r   modeling_utilsr   processing_utilsr   pytorch_utilsr   utilsr   r   r   utils.genericr   utils.output_capturingr   r   configuration_blipr   
get_loggerrI   r   Moduler   rT   r   r   r   r   r   r   r   r   r   r   r   r  r!  __all__ r>   r=   <module>rU     s[       % & ! C C ) J 9 
 . & 6 B B 7 E . 
		H	%- -bi.BII i.Z 1		 12299  RYY -. -b/
bii /
fRYY  bii $ryy "!")) !io i4v
+ v
tz1? zz Nr>   