o
    iD                    @   s  d Z ddlZddlmZ ddlmZmZmZmZ ddl	Z	ddl	m
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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"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. ddl/m0Z0m1Z1m2Z2 e&3e4Z5ee$ddG dd de"Z6G dd de
j7Z8	dJde
j7de	j9de	j9de	j9d ee	j9 d!e:d"e:fd#d$Z;G d%d& d&e
j7Z<G d'd( d(e
j7Z=G d)d* d*eZ>e$G d+d, d,eZ?G d-d. d.e
j7Z@G d/d0 d0e?ZAG d1d2 d2e
j7ZBG d3d4 d4e
j7ZCG d5d6 d6e
j7ZDG d7d8 d8e
j7ZEG d9d: d:e
j7ZFG d;d< d<eZGG d=d> d>e
j7ZHG d?d@ d@e
j7ZIG dAdB dBe?ZJe$dCdG dDdE dEe?ZKe$dFdG dGdH dHe?eZLg dIZMdS )KzPyTorch InstructBLIP model.    N)	dataclass)AnyCallableOptionalUnion)nn   )ACT2FN)GenerationMixin)FlashAttentionKwargs)GradientCheckpointingLayer)BaseModelOutput)BaseModelOutputWithPastAndCrossAttentionsBaseModelOutputWithPooling,BaseModelOutputWithPoolingAndCrossAttentions)ALL_ATTENTION_FUNCTIONSPreTrainedModel)Unpack)apply_chunking_to_forward find_pruneable_heads_and_indicesprune_linear_layer)ModelOutputTransformersKwargsauto_docstringcan_return_tuplelogging	torch_int)OutputRecordercheck_model_inputs   )	AutoModelAutoModelForCausalLMAutoModelForSeq2SeqLM   )InstructBlipConfigInstructBlipQFormerConfigInstructBlipVisionConfigzQ
    Class defining the outputs of [`InstructBlipForConditionalGeneration`].
    )custom_introc                   @   s   e Zd ZU dZdZeeej  e	d< dZ
eeej  e	d< dZeej e	d< dZeeej  e	d< dZeeej  e	d< dee fd	d
ZdS )/InstructBlipForConditionalGenerationModelOutputa  
    loss (`torch.FloatTensor`, *optional*, returned when `labels` is provided, `torch.FloatTensor` of shape `(1,)`):
        Language modeling loss from the language model.
    logits (`torch.FloatTensor` of shape `(batch_size, sequence_length, config.vocab_size)`):
        Prediction scores of the language modeling head of the language model.
    vision_outputs (`BaseModelOutputWithPooling`):
        Outputs of the vision encoder.
    qformer_outputs (`BaseModelOutputWithPoolingAndCrossAttentions`):
        Outputs of the Q-Former (Querying Transformer).
    language_model_outputs (`CausalLMOutputWithPast` or `Seq2SeqLMOutput`):
        Outputs of the language model.
    Nlosslogitsvision_outputsqformer_outputslanguage_model_outputsreturnc                    s   t  fdd  D S )Nc                 3   s.    | ]}|d vr | nt  | V  qdS )r+   r,   r-   N)getattrto_tuple).0kself s/home/ubuntu/veenaModal/venv/lib/python3.10/site-packages/transformers/models/instructblip/modeling_instructblip.py	<genexpr>J   s    
zKInstructBlipForConditionalGenerationModelOutput.to_tuple.<locals>.<genexpr>)tuplekeysr4   r6   r4   r7   r1   I   s   z8InstructBlipForConditionalGenerationModelOutput.to_tuple)__name__
__module____qualname____doc__r)   r   r9   torchFloatTensor__annotations__r*   r+   r,   r-   r   r1   r6   r6   r6   r7   r(   .   s   
 r(   c                       s\   e Zd Zdef fddZdejdededejfdd	Zddej	de
dejfddZ  ZS )InstructBlipVisionEmbeddingsconfigc                    s   t    || _|j| _|j| _|j| _tt	
dd| j| _tjd| j| j| jd| _| j| j d | _| jd | _tt	
d| j| j| _d S )Nr#   r   )in_channelsout_channelskernel_sizestrider   )super__init__rC   hidden_size	embed_dim
image_size
patch_sizer   	Parameterr?   randnclass_embeddingConv2dpatch_embeddingnum_patchesnum_positionsposition_embeddingr5   rC   	__class__r6   r7   rI   T   s   
z%InstructBlipVisionEmbeddings.__init__
embeddingsheightwidthr.   c                 C   s   |j d d }| jj d d }tj s||kr||kr| jS | jddddf }| jddddf }|j d }|| j }	|| j }
t|d }|d|||}|dddd}t	j
j||	|
fdd	d
}|dddddd|}tj||fddS )a   
        This method allows to interpolate the pre-trained position encodings, to be able to use the model on higher resolution
        images. This method is also adapted to support torch.jit tracing.

        Adapted from:
        - https://github.com/facebookresearch/dino/blob/de9ee3df6cf39fac952ab558447af1fa1365362a/vision_transformer.py#L174-L194, and
        - https://github.com/facebookresearch/dinov2/blob/e1277af2ba9496fbadf7aec6eba56e8d882d1e35/dinov2/models/vision_transformer.py#L179-L211
        r#   Ng      ?r   r   r   bicubicF)sizemodealign_cornersdim)shaperU   r?   jit
is_tracingrM   r   reshapepermuter   
functionalinterpolateviewcat)r5   rY   rZ   r[   rS   rT   class_pos_embedpatch_pos_embedrb   
new_height	new_widthsqrt_num_positionsr6   r6   r7   interpolate_pos_encodingf   s(   



z5InstructBlipVisionEmbeddings.interpolate_pos_encodingFpixel_valuesrq   c                 C   s   |j \}}}}| jjj}| |j|d}|ddd}| j|dd|}	t	j
|	|gdd}
|r<| |
||}n| j}|
|d d d |
dd d f | }
|
S )Ndtyper   r#   r\   ra   )rc   rR   weightrt   toflatten	transposerP   expandr?   rk   rq   rU   r^   )r5   rr   rq   
batch_size_rZ   r[   target_dtypepatch_embedsclass_embedsrY   rU   r6   r6   r7   forward   s   
*z$InstructBlipVisionEmbeddings.forwardF)r;   r<   r=   r&   rI   r?   Tensorintrq   r@   boolr   __classcell__r6   r6   rW   r7   rB   S   s    $(rB           modulequerykeyvalueattention_maskscalingdropoutc           
      K   sp   t ||dd| }|d ur|| }tjj|dd}tjj||| jd}t ||}	|	dd }	|	|fS )Nr\   ra   )ptrainingr#   r   )	r?   matmulrx   r   rh   softmaxr   r   
contiguous)
r   r   r   r   r   r   r   kwargsattn_weightsattn_outputr6   r6   r7   eager_attention_forward   s   
r   c                       sv   e Zd ZdZ fddZdejdedefddZ		dd
ejde	ej de
eje	ej e	e
ej  f fddZ  ZS )InstructBlipAttentionz=Multi-headed attention from 'Attention Is All You Need' paperc                    s  t    || _|j| _|j| _| j| j | _| j| j | jkr-td| j d| j d| jd | _	d| _
|j| _tj| jd| j dd| _|jr]tt| j}tt| j}nd }d }|d uryt|tj|dd|f}t|| j_t| j| j| _d S )	Nz;embed_dim must be divisible by num_heads (got `embed_dim`: z and `num_heads`: z).g      Fr   )bias)requires_grad)rH   rI   rC   rJ   rK   num_attention_heads	num_headshead_dim
ValueErrorscale	is_causalattention_dropoutr   Linearqkvqkv_biasrN   r?   zerosrk   
zeros_liker   
projection)r5   rC   q_biasv_biasr   rW   r6   r7   rI      s0   

zInstructBlipAttention.__init__tensorseq_lenbszc                 C   s    | ||| j| jdd S )Nr#   r   )rj   r   r   rx   r   )r5   r   r   r   r6   r6   r7   _shape   s    zInstructBlipAttention._shapeNhidden_states	head_maskr.   c                 K   s   |  \}}}| |}|||d| j|| j ddddd}|d |d |d }}	}
t}| jjdkr<t| jj }|| ||	|
fd| j	sHdn| j
| jd	|\}}|||d
 }| |}||fS )z#Input shape: Batch x Time x Channelr   r   r   r#      eagerNr   )r   r   r   r\   )r^   r   rf   r   rg   r   rC   _attn_implementationr   r   r   r   r   r   )r5   r   r   r   r   tgt_lenrK   	mixed_qkvquery_states
key_statesvalue_statesattention_interfacer   r   r6   r6   r7   r      s0   



zInstructBlipAttention.forwardN)r;   r<   r=   r>   rI   r?   r   r   r   r   r9   r   r   r6   r6   rW   r7   r      s    r   c                       2   e Zd Z fddZdejdejfddZ  ZS )InstructBlipMLPc                    sD   t    || _t|j | _t|j|j	| _
t|j	|j| _d S r   )rH   rI   rC   r	   
hidden_actactivation_fnr   r   rJ   intermediate_sizefc1fc2rV   rW   r6   r7   rI     s
   
zInstructBlipMLP.__init__r   r.   c                 C   s"   |  |}| |}| |}|S r   )r   r   r   r5   r   r6   r6   r7   r     s   


zInstructBlipMLP.forwardr;   r<   r=   rI   r?   r   r   r   r6   r6   rW   r7   r     s    r   c                	       sJ   e Zd Zdef fddZedejdejdee	 dej
fdd	Z  ZS )
InstructBlipEncoderLayerrC   c                    sR   t    |j| _t|| _tj| j|jd| _	t
|| _tj| j|jd| _d S Neps)rH   rI   rJ   rK   r   	self_attnr   	LayerNormlayer_norm_epslayer_norm1r   mlplayer_norm2rV   rW   r6   r7   rI     s   


z!InstructBlipEncoderLayer.__init__r   r   r   r.   c                 K   sT   |}|  |}| jd||d|\}}|| }|}| |}| |}|| }|S )N)r   r   r6   )r   r   r   r   )r5   r   r   r   residualr{   r6   r6   r7   r     s   



z InstructBlipEncoderLayer.forward)r;   r<   r=   r$   rI   r   r?   r   r   r   r@   r   r   r6   r6   rW   r7   r     s    r   c                   @   sB   e Zd ZU eed< dZdZdZdZdZ	dZ
dZg dZdd ZdS )InstructBlipPreTrainedModelrC   blipT)InstructBlipQFormerEmbeddingsr   %InstructBlipQFormerMultiHeadAttentionInstructBlipQFormerSelfOutputc                 C   s   | j j}t|tjtjfr%|jjjd|d |j	dur#|j	j
  dS dS t|tjr6|jjjd|d dS t|tjrK|j	j
  |jjd dS t|trftjj|jd|d tjj|jd|d dS t|ttfru|jj
  dS dS )zInitialize the weightsr   )meanstdN      ?)rC   initializer_range
isinstancer   r   rQ   ru   datanormal_r   zero_	Embeddingr   fill_rB   inittrunc_normal_rU   rP   $InstructBlipForConditionalGenerationInstructBlipModelquery_tokens)r5   r   factorr6   r6   r7   _init_weightsH  s"   

z)InstructBlipPreTrainedModel._init_weightsN)r;   r<   r=   r$   rA   base_model_prefixsupports_gradient_checkpointing_supports_attention_backend_supports_flash_attn_supports_sdpa_supports_flex_attn_can_compile_fullgraph_no_split_modulesr   r6   r6   r6   r7   r   5  s   
 r   c                
       sV   e Zd ZdZdef fddZe	ddeej	 de
e deeef fd	d
Z  ZS )InstructBlipEncodera  
    Transformer encoder consisting of `config.num_hidden_layers` self attention layers. Each layer is a
    [`InstructBlipEncoderLayer`].

    Args:
        config (`InstructBlipConfig`):
            The corresponding vision configuration for the `InstructBlipEncoder`.
    rC   c                    :   t     | _t fddt jD | _d| _d S )Nc                    s   g | ]}t  qS r6   )r   )r2   r{   rC   r6   r7   
<listcomp>j  s    z0InstructBlipEncoder.__init__.<locals>.<listcomp>F)	rH   rI   rC   r   
ModuleListrangenum_hidden_layerslayersgradient_checkpointingrV   rW   r   r7   rI   g  s   
 
zInstructBlipEncoder.__init__Nr   r   r.   c                 K   s.   |}| j D ]}||fd|i|}qt|dS )Nr   last_hidden_state)r   r   )r5   inputs_embedsr   r   r   encoder_layerr6   r6   r7   r   m  s   

zInstructBlipEncoder.forwardr   )r;   r<   r=   r>   r$   rI   r   r   r?   r   r   r   r   r9   r   r   r   r6   r6   rW   r7   r   ]  s    	
r   c                       s   e Zd ZU dZeed< eedZdef fddZ	e
dde		ddeej d	ed
ee deeef fddZdd Z  ZS )InstructBlipVisionModelrr   rC   )r   
attentionsc                    sJ   t  | || _|j}t|| _t|| _tj	||j
d| _|   d S r   )rH   rI   rC   rJ   rB   rY   r   encoderr   r   r   post_layernorm	post_init)r5   rC   rK   rW   r6   r7   rI     s   

z InstructBlipVisionModel.__init__F)tie_last_hidden_statesNrq   r   r.   c                 K   sn   |d u rt d| j||d}| jdd|i|}|j}| |}|d d dd d f }| |}t||dS )Nz You have to specify pixel_values)rq   r   r   r   pooler_outputr6   )r   rY   r   r   r   r   )r5   rr   rq   r   r   encoder_outputsr   pooled_outputr6   r6   r7   r     s    

zInstructBlipVisionModel.forwardc                 C      | j S r   )rY   r4   r6   r6   r7   get_input_embeddings     z,InstructBlipVisionModel.get_input_embeddings)NF)r;   r<   r=   main_input_namer&   rA   r   r   _can_record_outputsrI   r   r   r   r?   r@   r   r   r   r   r9   r   r   r  r   r6   r6   rW   r7   r     s*   
 
r   c                       sb   e Zd Zd fdd	Zdd Zdd Zdd	 Zd
d Zdd Z				dde	e
 fddZ  ZS )r   Fc                    s"  t    || _|j|j dkrt|dstd|j|jf |j| _t|j|j | _| j| j | _	t
|j| j	| _|rQt
|j| j	| _t
|j| j	| _nt
|j| j	| _t
|j| j	| _t
|j| _t|dd| _| jdks{| jdkr|j| _t
d|j d	 | j| _d
| _d S )Nr   embedding_sizezLThe hidden size (%d) is not a multiple of the number of attention heads (%d)position_embedding_typeabsoluterelative_keyrelative_key_queryr   r#   F)rH   rI   rC   rJ   r   hasattrr   r   attention_head_sizeall_head_sizer   r   r   encoder_hidden_sizer   r   Dropoutattention_probs_dropout_probr   r0   r  max_position_embeddingsr   distance_embeddingsave_attentionr5   rC   is_cross_attentionrW   r6   r7   rI     s.   


z.InstructBlipQFormerMultiHeadAttention.__init__c                 C   
   || _ d S r   attn_gradients)r5   r  r6   r6   r7   save_attn_gradients     
z9InstructBlipQFormerMultiHeadAttention.save_attn_gradientsc                 C   r  r   r  r4   r6   r6   r7   get_attn_gradients  r  z8InstructBlipQFormerMultiHeadAttention.get_attn_gradientsc                 C   r  r   attention_map)r5   r  r6   r6   r7   save_attention_map  r  z8InstructBlipQFormerMultiHeadAttention.save_attention_mapc                 C   r  r   r  r4   r6   r6   r7   get_attention_map  r  z7InstructBlipQFormerMultiHeadAttention.get_attention_mapc                 C   s6   |  d d | j| jf }|j| }|ddddS )Nr\   r   r   r#   r   )r^   r   r  rj   rg   )r5   xnew_x_shaper6   r6   r7   transpose_for_scores  s   
z:InstructBlipQFormerMultiHeadAttention.transpose_for_scoresNr   c                 K   s  |d u}|r|  | |}|  | |}	|}n|  | |}|  | |}	| |}
|  |
}t||dd}| jdksG| jdkr| d }tj	|tj
|jddd}tj	|tj
|jddd}|| }| || j d }|j|jd}| jdkrtd||}|| }n| jdkrtd||}td	||}|| | }|t| j }|j}|d ur|| }tjdd
||}|r| jr| | || j | |}|d ur|| }t||	}|dddd }| d d | jf }|j| }||fS )Nr\   r   r
  r  r#   rt   devicers   zbhld,lrd->bhlrzbhrd,lrd->bhlrra   r   r   r   )r#  r   r   r   r?   r   rx   r  r^   arangelongr%  rj   r  r  rv   rt   einsummathsqrtr  r   Softmaxr  r  register_hookr  r   rg   r   r  )r5   r   r   r   encoder_hidden_statesencoder_attention_maskr   r  	key_layervalue_layermixed_query_layerquery_layerattention_scores
seq_lengthposition_ids_lposition_ids_rdistancepositional_embeddingrelative_position_scoresrelative_position_scores_queryrelative_position_scores_keyattention_scores_dtypeattention_probsattention_probs_droppedcontext_layernew_context_layer_shaper6   r6   r7   r     sP   








z-InstructBlipQFormerMultiHeadAttention.forwardr   NNNN)r;   r<   r=   rI   r  r  r  r   r#  r   r   r   r   r6   r6   rW   r7   r     s    r   c                       8   e Zd Z fddZdejdejdejfddZ  ZS )r   c                    sB   t    t|j|j| _tj|j|jd| _t|j	| _
d S r   )rH   rI   r   r   rJ   denser   r   r  hidden_dropout_probr   rV   rW   r6   r7   rI   0     
z&InstructBlipQFormerSelfOutput.__init__r   input_tensorr.   c                 C   &   |  |}| |}| || }|S r   rC  r   r   r5   r   rF  r6   r6   r7   r   6     

z%InstructBlipQFormerSelfOutput.forwardr   r6   r6   rW   r7   r   /      $r   c                       sv   e Zd Zd fdd	Zdd Z				ddejdeej d	eej d
eej deej de	e
 dejfddZ  ZS )InstructBlipQFormerAttentionFc                    s,   t    t||| _t|| _t | _d S r   )rH   rI   r   	attentionr   outputsetpruned_headsr  rW   r6   r7   rI   ?  s   

z%InstructBlipQFormerAttention.__init__c                 C   s   t |dkrd S t|| jj| jj| j\}}t| jj|| j_t| jj|| j_t| jj	|| j_	t| j
j|dd| j
_| jjt | | j_| jj| jj | j_| j|| _d S )Nr   r#   ra   )lenr   rM  r   r  rP  r   r   r   r   rN  rC  r  union)r5   headsindexr6   r6   r7   prune_headsE  s   z(InstructBlipQFormerAttention.prune_headsNr   r   r   r-  r.  r   r.   c           
      K   s0   | j d|||||d|\}}| ||}	|	S )N)r   r   r   r-  r.  r6   )rM  rN  )
r5   r   r   r   r-  r.  r   r   r{   attention_outputr6   r6   r7   r   W  s   	
z$InstructBlipQFormerAttention.forwardr   rA  )r;   r<   r=   rI   rU  r?   r   r   r@   r   r   r   r   r6   r6   rW   r7   rL  >  s,    rL  c                       r   )InstructBlipQFormerIntermediatec                    sD   t    t|j|j| _t|jt	rt
|j | _d S |j| _d S r   )rH   rI   r   r   rJ   r   rC  r   r   strr	   intermediate_act_fnrV   rW   r6   r7   rI   n  s
   
z(InstructBlipQFormerIntermediate.__init__r   r.   c                 C   s   |  |}| |}|S r   )rC  rY  r   r6   r6   r7   r   v  s   

z'InstructBlipQFormerIntermediate.forwardr   r6   r6   rW   r7   rW  m  s    rW  c                       rB  )InstructBlipQFormerOutputc                    sB   t    t|j|j| _tj|j|jd| _t	|j
| _d S r   )rH   rI   r   r   r   rJ   rC  r   r   r  rD  r   rV   rW   r6   r7   rI   ~  rE  z"InstructBlipQFormerOutput.__init__r   rF  r.   c                 C   rG  r   rH  rI  r6   r6   r7   r     rJ  z!InstructBlipQFormerOutput.forwardr   r6   r6   rW   r7   rZ  }  rK  rZ  c                       sJ   e Zd Z fddZ					ddee fddZdd	 Zd
d Z  Z	S )InstructBlipQFormerLayerc                    s~   t    |j| _d| _t|| _|| _||j dkr&t|dd| _d| _	nd| _	t
|| _t|| _t
|| _t|| _d S )Nr#   r   T)r  F)rH   rI   chunk_size_feed_forwardseq_len_dimrL  rM  	layer_idxcross_attention_frequencycrossattentionhas_cross_attentionrW  intermediaterZ  rN  intermediate_queryoutput_query)r5   rC   r^  rW   r6   r7   rI     s   




z!InstructBlipQFormerLayer.__init__Nr   r   c              	   K   s   | j |f||d|}|dkrk|d d d |d d f }	| jr6|d u r(td| j|	f||||d|}	t| j| j| j|	}
|jd |krit| j	| j| j|d d |d d d f 
|
j}tj|
|gdd}
|
S t| j	| j| j|}
|
S )N)r   r   r   z>encoder_hidden_states must be given for cross-attention layers)r   r   r-  r.  r#   ra   )rM  ra  r   r`  r   feed_forward_chunk_queryr\  r]  rc   feed_forward_chunkrv   r%  r?   rk   )r5   r   r   r   r-  r.  query_lengthr   rV  query_attention_outputlayer_outputlayer_output_textr6   r6   r7   r     s^   
	z InstructBlipQFormerLayer.forwardc                 C      |  |}| ||}|S r   )rb  rN  r5   rV  intermediate_outputri  r6   r6   r7   rf       
z+InstructBlipQFormerLayer.feed_forward_chunkc                 C   rk  r   )rc  rd  rl  r6   r6   r7   re    rn  z1InstructBlipQFormerLayer.feed_forward_chunk_queryNNNNr   )
r;   r<   r=   rI   r   r   r   rf  re  r   r6   r6   rW   r7   r[    s    
8r[  c                       s>   e Zd Z fddZe					ddee fddZ  ZS )	InstructBlipQFormerEncoderc                    r   )Nc                    s   g | ]}t  |qS r6   )r[  )r2   r^  r   r6   r7   r         z7InstructBlipQFormerEncoder.__init__.<locals>.<listcomp>F)	rH   rI   rC   r   r   r   r   layerr   rV   rW   r   r7   rI     s   

z#InstructBlipQFormerEncoder.__init__Nr   r   c                 K   sV   t | jjD ]}| j| }	|d ur|| nd }
|	|||
|f||d|}qt|dS )N)r.  rg  r   )r   rC   r   rr  r   )r5   r   r   r   r-  r.  rg  r   ilayer_modulelayer_head_maskr6   r6   r7   r     s"   

z"InstructBlipQFormerEncoder.forwardro  )	r;   r<   r=   rI   r   r   r   r   r   r6   r6   rW   r7   rp    s    rp  c                       s2   e Zd ZdZ fddZ				dddZ  ZS )	r   z;Construct the embeddings from word and position embeddings.c                    s   t    tj|j|j|jd| _t|j|j| _	tj
|j|jd| _t|j| _| jdt|jddd t|dd| _|| _d S )	N)padding_idxr   position_ids)r#   r\   F)
persistentr  r	  )rH   rI   r   r   
vocab_sizerJ   pad_token_idword_embeddingsr  position_embeddingsr   r   	layernormr  rD  r   register_bufferr?   r&  ry   r0   r  rC   rV   rW   r6   r7   rI     s   

z&InstructBlipQFormerEmbeddings.__init__Nr   c                 C   s   |d ur|  d }nd}|d u r | jd d ||| f  }|d urI| |}| jdkr;| ||j}|| }|d urHtj	||fdd}n|}|| j
jj}| 
|}| |}|S )Nr#   r   r	  ra   )r^   rw  cloner{  r  r|  rv   r%  r?   rk   r}  ru   rt   r   )r5   	input_idsrw  query_embedspast_key_values_lengthr4  rY   r|  r6   r6   r7   r     s$   



z%InstructBlipQFormerEmbeddings.forward)NNNr   )r;   r<   r=   r>   rI   r   r   r6   r6   rW   r7   r     s    r   c                       s  e Zd ZdZdZdZdZdZee	e
dddge	e
dddgdZdef fd	d
Zdd Zdd Zdd Z	d"dejdee dejdedejf
ddZee						d#dejdeej deej deej deej deej deej dee deeej e f fd d!Z!  Z"S )$InstructBlipQFormerModelz
    Querying Transformer (Q-Former), used in InstructBLIP. Slightly modified from BLIP-2 as it also takes the
    instruction as input.
    Fr#   z
.attention)rT  
layer_namez.crossattention)r   r   cross_attentionsrC   c                    s2   t  | || _t|| _t|| _|   d S r   )rH   rI   rC   r   rY   rp  r   r   rV   rW   r6   r7   rI   S  s
   

z!InstructBlipQFormerModel.__init__c                 C   s   | j jS r   rY   r{  r4   r6   r6   r7   r  ]  s   z-InstructBlipQFormerModel.get_input_embeddingsc                 C   s   || j _d S r   r  r5   r   r6   r6   r7   set_input_embeddings`  s   z-InstructBlipQFormerModel.set_input_embeddingsc                 C   s*   |  D ]\}}| jj| j| qdS )z
        Prunes heads of the model. heads_to_prune: dict of {layer_num: list of heads to prune in this layer} See base
        class PreTrainedModel
        N)itemsr   rr  rM  rU  )r5   heads_to_prunerr  rS  r6   r6   r7   _prune_headsc  s   z%InstructBlipQFormerModel._prune_headsr   input_shaper%  	has_queryr.   c                 C   s   |  dkr|dddddddf }n|  dkr(|ddddddf }ntd| d|j d|j| jd}d| d	 }|S )
a>  
        Makes broadcastable attention and causal masks so that future and masked tokens are ignored.

        Arguments:
            attention_mask (`torch.Tensor`):
                Mask with ones indicating tokens to attend to, zeros for tokens to ignore.
            input_shape (`tuple[int]`):
                The shape of the input to the model.
            device: (`torch.device`):
                The device of the input to the model.

        Returns:
            `torch.Tensor` The extended attention mask, with a the same dtype as `attention_mask.dtype`.
        r   Nr   z!Wrong shape for input_ids (shape z) or attention_mask (shape )rs   r   g     )rb   r   rc   rv   rt   )r5   r   r  r%  r  extended_attention_maskr6   r6   r7   get_extended_attention_maskk  s   	z4InstructBlipQFormerModel.get_extended_attention_maskNr  rw  r  r   r-  r.  r   c                    sf  |du r|du rt d|dur|jd nd}	 j|||d}
|
 dd }|\}}|
j}|du r;tj||f|d} |||}|durt|t	rU|d  \}}}n| \}}}||f}t|t	ro fdd	|D }n|du rtj||d} 
|}n 
|}nd} | jj} j|
f|||||	d
|}|j}|dddddf }t||dS )a$  
        query_embeds (`torch.FloatTensor`  of shape `(batch_size, sequence_length, hidden_size)`):
            Hidden states to be used in the attention computation. If cross-attention,
            will be used for the query (i.e., key and value will use the encoder_hidden_states).
        Nz7You have to specify query_embeds when input_ids is Noner#   r   )r  rw  r  r\   )r%  c                    s   g | ]}  |qS r6   )invert_attention_mask)r2   maskr4   r6   r7   r     rq  z4InstructBlipQFormerModel.forward.<locals>.<listcomp>)r   r   r-  r.  rg  r   )r   rc   rY   r^   r%  r?   onesr  r   listr  get_head_maskrC   r   r   r   r   )r5   r  r   rw  r  r   r-  r.  r   rg  embedding_outputr  rz   r4  r%  r  encoder_batch_sizeencoder_sequence_lengthr{   encoder_hidden_shapeencoder_extended_attention_maskr   sequence_outputr  r6   r4   r7   r     sX   

	z InstructBlipQFormerModel.forwardr   )NNNNNN)#r;   r<   r=   r>   r   r   r   r   r[  r   r   r  r%   rI   r  r  r  r?   r   r9   r   r%  r   r  r   r   
LongTensorr   r@   r   r   r   r   r   r   r6   r6   rW   r7   r  >  sn    


+	
r  z[
    InstructBLIP base Model consisting of language model, qformer and vision encoder.
    c                       s   e Zd ZdZdgZdef fddZdd Zdd	 Zd
d Z	dd Z
dejdejfddZee							ddejdejdeej deej deej deej deej deej dedee deeef fddZ  ZS )r   rr   r   rC   c                    s   t  | t|j| _ttd|j	|j
j| _t|j
| _t|j
j|jj| _t|j| _| jjd ur@| j| jj | jjd urN| j| jj |   d S Nr#   )rH   rI   r   vision_configvision_modelr   rN   r?   r   num_query_tokensqformer_configrJ   r   r  qformerr   text_configlanguage_projectionr    from_configlanguage_modelr   extend_keep_in_fp32_modulesr   rV   rW   r6   r7   rI     s   zInstructBlipModel.__init__c                 C   
   | j  S r   r  r  r4   r6   r6   r7   r    r  z&InstructBlipModel.get_input_embeddingsc                 C      | j | d S r   r  r  r  r6   r6   r7   r  	     z&InstructBlipModel.set_input_embeddingsc                 C   ,   | j js| jj| jj_| jj| jj_d S d S r   rC   use_decoder_only_language_modelr  sharedr   embed_tokensdecoderr4   r6   r6   r7   _tie_weights     zInstructBlipModel._tie_weightsc                 C   P   | j }t|dkrd|vrtj dkrtd t| jdr&d| jj	_
dS dS z
        Some pre-processing hacks to make the model `accelerate` compatible. Check
        https://github.com/huggingface/transformers/pull/21707 for more details.
        r#   r  a  The `language_model` is not in the `hf_device_map` dictionary and you are running your script in a multi-GPU environment. this may lead to unexpected behavior when using `accelerate`. Please pass a `device_map` that contains `language_model` to remove this warning. Please refer to https://github.com/huggingface/blog/blob/main/accelerate-large-models.md for more details on creating a `device_map` for large models._hf_hookTNhf_device_maprQ  r?   cudadevice_countloggerwarningr  r  r  io_same_devicer5   r  r6   r6   r7   _preprocess_accelerate     "z(InstructBlipModel._preprocess_accelerater  r   c                 C   `   |du r||   tj| jjtj|jdk}|d}n|| jjk}|d	|
|j}|S zZ
        Obtains multimodal placeholder mask from `input_ids` or `inputs_embeds`.
        Nr$  r\   r  r?   r   rC   image_token_idr'  r%  all	unsqueeze	expand_asrv   r5   r  r   special_image_maskr6   r6   r7   get_placeholder_mask%     z&InstructBlipModel.get_placeholder_maskNFqformer_input_idsqformer_attention_maskr   decoder_input_idsdecoder_attention_maskrq   r   r.   c
                 K   s|  | j d||	d|
}|d }tj| dd tj|jd}| j|jd dd}tj| dd tj|jd}|du rCt	|}tj
||gdd}| jd|||||d|
}|d ddd|dddf }|du r| j |}|du rt	|}| |}||j|j}| j||d	}|||}| jjr| jd||d
|
}n| jd||||d|
}t|||dS )a  
        qformer_input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
            Indices of input sequence tokens in the vocabulary of the Q-Former. Input tokens can optionally be provided
            to serve as text prompt, which the Q-Former model will encode.

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

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

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

            [What are attention masks?](../glossary#attention-mask)
        decoder_attention_mask (`torch.BoolTensor` of shape `(batch_size, target_sequence_length)`, *optional*):
            Default behavior: generate a tensor that ignores pad tokens in `decoder_input_ids`. Causal mask will also
            be used by default.

            Only relevant in case an encoder-decoder language model (like T5) is used.
        )rr   rq   r   Nr\   r$  r#   ra   )r  r   r  r-  r.  r   r   r   )r   r   r  r  r/   r6   )r  r?   r  r^   r'  r%  r   ry   rc   	ones_likerk   r  r  r  r  rv   rt   r  masked_scatterrC   r  r(   )r5   rr   r  r  r  r   r  r  r   rq   r   r+   image_embedsimage_attention_maskr   query_attention_maskquery_outputsquery_outputlanguage_model_inputsr  outputsr6   r6   r7   r   4  sf   (  
$

zInstructBlipModel.forward)NNNNNNF)r;   r<   r=   r  r  r$   rI   r  r  r  r  r?   r  r@   r  r   r   r   r   r   r   r   r   r9   r(   r   r   r6   r6   rW   r7   r     sR    	

r   a  
    InstructBLIP Model for generating text given an image and an optional text prompt. The model consists of a vision
    encoder, Querying Transformer (Q-Former) and a language model.

    One can optionally pass `input_ids` to the model, which serve as a text prompt, to make the language model continue
    the prompt. Otherwise, the language model starts generating text from the [BOS] (beginning-of-sequence) token.
    c                       s  e Zd ZU eed< dZdZdgZdef fddZdd Z	d	d
 Z
dd ZdejfddZdd Zdd Zdd Zdd Z			d-dejdejdeej dee dee f
ddZd ejd!ejfd"d#Zee								d.dejdejdeej d eej d$eej d%eej d&eej d!eej d'eej ded(ee deee f fd)d*Z!e" 						d/dejdeej deej d eej d$eej d!eej dedejfd+d,Z#  Z$S )0r   rC   rr   Tr   c                    s   t  | t|j| _tt	d|j
|jj| _t|j| _t|jj|jj| _|jr7t|j}nt|j}|jd urI| j|j |jd urU| j|j || _|   d S r  )rH   rI   r   _from_configr  r  r   rN   r?   r   r  r  rJ   r   r  r  r   r  r  r  r!   r  r"   r   r  r  r  r   )r5   rC   r  rW   r6   r7   rI     s   

z-InstructBlipForConditionalGeneration.__init__c                 C   r  r   r  r4   r6   r6   r7   r    r  z9InstructBlipForConditionalGeneration.get_input_embeddingsc                 C   r  r   r  r  r6   r6   r7   r    r  z9InstructBlipForConditionalGeneration.set_input_embeddingsc                 C   r  r   )r  set_output_embeddings)r5   new_embeddingsr6   r6   r7   r    r  z:InstructBlipForConditionalGeneration.set_output_embeddingsr.   c                 C   r  r   )r  get_output_embeddingsr4   r6   r6   r7   r    r  z:InstructBlipForConditionalGeneration.get_output_embeddingsc                 C   r  r   )r  get_encoderr4   r6   r6   r7   r    r  z0InstructBlipForConditionalGeneration.get_encoderc                 C   r  r   )r  get_decoderr4   r6   r6   r7   r    r  z0InstructBlipForConditionalGeneration.get_decoderc                 C   r  r   r  r4   r6   r6   r7   r    r  z1InstructBlipForConditionalGeneration._tie_weightsc                 C   r  r  r  r  r6   r6   r7   r    r  z;InstructBlipForConditionalGeneration._preprocess_accelerateNFr  r  rq   return_dictc                 C   s   | j ||dd}|d }tj| dd tj|jd}| j|jd dd}	tj|	 dd tj|jd}
|du r@t	|}tj
|
|gdd}| j|||	||dd	}|d ddd|	dddf }| |}|rr|||fS |S )
a$  
        Encodes images into continuous embeddings that can be forwarded to the language model.

        Args:
            pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, image_size, image_size)`):
                The tensors corresponding to the input images.
        T)rr   rq   r  r   Nr\   r$  r#   ra   )r  r   r  r-  r.  r  )r  r?   r  r^   r'  r%  r   ry   rc   r  rk   r  r  )r5   rr   r  r  rq   r  r+   r  r  r   r  r  r  r  r6   r6   r7   get_image_features  s2     
$

z7InstructBlipForConditionalGeneration.get_image_featuresr  r   c                 C   r  r  r  r  r6   r6   r7   r    r  z9InstructBlipForConditionalGeneration.get_placeholder_maskr   r  r  labelsr   c                 K   s   | j ||||
dd\}}}|du r|  |}|du r t|}||j|j}| j||d}|||}| j	j
r^| jd||d|}|d }d}|	dur]| jd||	| j	jjd|}nd|d< | jd|||||	d	|}|j}|j}t|||||d
S )aD  
        qformer_input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
            Indices of input sequence tokens in the vocabulary of the Q-Former. Input tokens can optionally be provided
            to serve as text prompt, which the Q-Former model will encode.

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

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

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

            [What are attention masks?](../glossary#attention-mask)
        decoder_attention_mask (`torch.BoolTensor` of shape `(batch_size, target_sequence_length)`, *optional*):
            Default behavior: generate a tensor that ignores pad tokens in `decoder_input_ids`. Causal mask will also
            be used by default.

            Only relevant in case an encoder-decoder language model (like T5) is used.
        labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
            Labels for computing the language modeling loss. Indices should be in `[-100, 0, ..., config.vocab_size -
            1]`. All labels set to `-100` are ignored (masked), the loss is only computed for labels in `[0, ...,
            config.vocab_size]`

        Examples:

        ```python
        >>> from transformers import InstructBlipProcessor, InstructBlipForConditionalGeneration
        >>> import torch
        >>> from PIL import Image
        >>> import requests

        >>> model = InstructBlipForConditionalGeneration.from_pretrained("Salesforce/instructblip-vicuna-7b")
        >>> processor = InstructBlipProcessor.from_pretrained("Salesforce/instructblip-vicuna-7b")

        >>> device = "cuda" if torch.cuda.is_available() else "cpu"
        >>> model.to(device)  # doctest: +IGNORE_RESULT

        >>> url = "https://raw.githubusercontent.com/salesforce/LAVIS/main/docs/_static/Confusing-Pictures.jpg"
        >>> image = Image.open(requests.get(url, stream=True).raw).convert("RGB")
        >>> prompt = "What is unusual about this image?"
        >>> inputs = processor(images=image, text=prompt, return_tensors="pt").to(device)

        >>> outputs = model.generate(
        ...     **inputs,
        ...     do_sample=False,
        ...     num_beams=5,
        ...     max_length=256,
        ...     min_length=1,
        ...     top_p=0.9,
        ...     repetition_penalty=1.5,
        ...     length_penalty=1.0,
        ...     temperature=1,
        ... )
        >>> generated_text = processor.batch_decode(outputs, skip_special_tokens=True)[0].strip()
        >>> print(generated_text)
        The unusual aspect of this image is that a man is ironing clothes on the back of a yellow SUV, which is parked in the middle of a busy city street. This is an unconventional approach to ironing clothes, as it requires the man to balance himself and his ironing equipment on top of the vehicle while navigating through traffic. Additionally, the presence of taxis and other vehicles in the scene further emphasizes the unusual nature of this situation.
        ```Tr  r  rq   r  Nr  r  r   )r*   r  ry  r  )r   r   r  r  r  )r)   r*   r+   r,   r-   r6   )r  r  r?   r  rv   r%  rt   r  r  rC   r  r  loss_functionr  ry  r)   r*   r(   )r5   rr   r  r  r  r   r  r  r   r  rq   r   r  r+   r  r  r  r*   r)   r6   r6   r7   r   .  sb   M
z,InstructBlipForConditionalGeneration.forwardc                 K   s  t | dr	|   |jd }	| j||||dd\}
}}|du rK|du rE| jjg| jj }|| jjjg }t	j
|gt	j|jd}||	d}|  |}|du rTt	|}|
|j|j}
| j||d}|||
}||d	}| jjjsw||d
< | jjdi ||}|S )a  
        Overrides `generate` function to be able to use the model as a conditional generator.

        Args:
            pixel_values (`torch.FloatTensor` of shape (batch_size, num_channels, height, width)):
                Input images to be processed.
            qformer_input_ids (`torch.LongTensor` of shape (batch_size, sequence_length), *optional*):
                The sequence used as a prompt to be fed to the Q-Former module.
            qformer_attention_mask (`torch.LongTensor` of shape (batch_size, sequence_length), *optional*):
                Mask to avoid performing attention on padding token indices.
            input_ids (`torch.LongTensor` of shape (batch_size, sequence_length), *optional*):
                The sequence used as a prompt for the generation.
            attention_mask (`torch.LongTensor` of shape (batch_size, sequence_length), *optional*):
                Mask to avoid performing attention on padding token indices.
            inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`):
                Embedded representation of the inputs. Should be float, not int tokens.
            interpolate_pos_encoding (`bool`, *optional*, defaults to `False`):
                Whether to interpolate the positional encoding of the image embeddings.

        Returns:
            captions (list): A list of strings of length batch_size * num_captions.
        r  r   Tr  Nr$  r#   r  r  r  r6   )r  r  rc   r  rC   image_token_indexr  r  bos_token_idr?   r   r'  r%  repeatr  r  rv   rt   r  r  r  is_encoder_decodergenerate)r5   rr   r  r  r  r   r   rq   generate_kwargsrz   r  r+   r  image_tokensstart_tokensr  inputsr  r6   r6   r7   r    s6   
"



z-InstructBlipForConditionalGeneration.generate)NFF)NNNNNNNF)NNNNNF)%r;   r<   r=   r$   rA   r  r   r  rI   r  r  r  r   Moduler  r  r  r  r  r?   r@   r  r   r   r  r  r   r   r   r   r   r9   r(   r   no_gradr  r   r6   r6   rW   r7   r     s   
 

1	


r   )r  r   r   r   r   )r   )Nr>   r)  dataclassesr   typingr   r   r   r   r?   r   activationsr	   
generationr
   modeling_flash_attention_utilsr   modeling_layersr   modeling_outputsr   r   r   r   modeling_utilsr   r   processing_utilsr   pytorch_utilsr   r   r   utilsr   r   r   r   r   r   utils.genericr   r   autor    r!   r"   configuration_instructblipr$   r%   r&   
get_loggerr;   r  r(   r  rB   r   floatr   r   r   r   r   r   r   r   r   rL  rW  rZ  r[  rp  r   r  r   r   __all__r6   r6   r6   r7   <module>   s    
R
M"'#4{/Y'3 - )	  X